session-runner-recorded.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import { HttpRecorder } from "@opencode-ai/http-recorder"
  2. import * as OpenAIChat from "@opencode-ai/ai/protocols/openai-chat"
  3. import { Auth, LLMClient, RequestExecutor } from "@opencode-ai/ai/route"
  4. import { Catalog } from "@opencode-ai/core/catalog"
  5. import { Database } from "@opencode-ai/core/database/database"
  6. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  7. import { LayerNodePlatform } from "@opencode-ai/core/effect/app-node-platform"
  8. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  9. import { Bus } from "@opencode-ai/core/bus"
  10. import { EventTable } from "@opencode-ai/core/event/sql"
  11. import { Job } from "@opencode-ai/core/job"
  12. import { Permission } from "@opencode-ai/core/permission"
  13. import { Agent } from "@opencode-ai/core/agent"
  14. import { Config } from "@opencode-ai/core/config"
  15. import { Project } from "@opencode-ai/core/project"
  16. import { ProjectTable } from "@opencode-ai/core/project/sql"
  17. import { AbsolutePath } from "@opencode-ai/core/schema"
  18. import { Session } from "@opencode-ai/core/session"
  19. import { Snapshot } from "@opencode-ai/core/snapshot"
  20. import { SessionCompaction } from "@opencode-ai/core/session/compaction"
  21. import { SessionTitle } from "@opencode-ai/core/session/title"
  22. import { SessionProjector } from "@opencode-ai/core/session/projector"
  23. import { SessionExecution } from "@opencode-ai/core/session/execution"
  24. import { SessionRunCoordinator } from "@opencode-ai/core/session/run-coordinator"
  25. import { SessionRunner } from "@opencode-ai/core/session/runner"
  26. import * as SessionRunnerLLM from "@opencode-ai/core/session/runner/llm"
  27. import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
  28. import { Tool } from "@opencode-ai/core/tool"
  29. import { SessionTable } from "@opencode-ai/core/session/sql"
  30. import { SessionStore } from "@opencode-ai/core/session/store"
  31. import { Location } from "@opencode-ai/core/location"
  32. import { InstructionBuiltIns } from "@opencode-ai/core/instructions/builtins"
  33. import { InstructionDiscovery } from "@opencode-ai/core/instruction-discovery"
  34. import { Instructions } from "@opencode-ai/core/instructions"
  35. import { SkillInstructions } from "@opencode-ai/core/skill/instructions"
  36. import { ReferenceInstructions } from "@opencode-ai/core/reference/instructions"
  37. import { McpInstructions } from "@opencode-ai/core/mcp/instructions"
  38. import { PluginSupervisor } from "@opencode-ai/core/plugin/supervisor"
  39. import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
  40. import { SystemPromptPlugin } from "@opencode-ai/core/plugin/system-prompt"
  41. import { describe, expect } from "bun:test"
  42. import { eq } from "drizzle-orm"
  43. import { Effect, Layer, Stream } from "effect"
  44. import { HttpClient, HttpClientResponse } from "effect/unstable/http"
  45. import path from "node:path"
  46. import { testEffect } from "./lib/effect"
  47. import { agentHost, catalogHost, host } from "./plugin/host"
  48. const cassetteName = "session-runner/openai-chat-streams-text"
  49. const cassetteDirectory = path.resolve(import.meta.dir, "fixtures/recordings")
  50. if (process.env.RECORD === "true") {
  51. if (process.env.CI !== undefined) throw new Error("Unset CI before recording HTTP cassettes")
  52. HttpRecorder.removeCassetteSync(cassetteName, { directory: cassetteDirectory })
  53. }
  54. const cassette = HttpRecorder.layerFetch(cassetteName, { directory: cassetteDirectory })
  55. const executor = RequestExecutor.layer.pipe(Layer.provide(cassette))
  56. const client = LLMClient.layer.pipe(Layer.provide(executor))
  57. const permission = Layer.succeed(
  58. Permission.Service,
  59. Permission.Service.of({
  60. assert: () => Effect.die("unused"),
  61. ask: () => Effect.die("unused"),
  62. reply: () => Effect.die("unused"),
  63. get: () => Effect.die("unused"),
  64. forSession: () => Effect.die("unused"),
  65. list: () => Effect.die("unused"),
  66. }),
  67. )
  68. const model = OpenAIChat.route
  69. .with({
  70. endpoint: { baseURL: "https://api.openai.com/v1" },
  71. auth: Auth.bearer(process.env.OPENAI_API_KEY ?? "fixture"),
  72. generation: { maxTokens: 20, temperature: 0 },
  73. })
  74. .model({ id: "gpt-4o-mini" })
  75. const models = Layer.mock(SessionRunnerModel.Service)({
  76. resolve: () =>
  77. Effect.succeed(
  78. SessionRunnerModel.resolved(model, {
  79. capabilities: { tools: true, input: ["text", "image"], output: ["text"] },
  80. cost: [],
  81. }),
  82. ),
  83. })
  84. const systemContext = Layer.mock(InstructionBuiltIns.Service, { load: () => Effect.succeed(Instructions.empty) })
  85. const instructionContext = Layer.mock(InstructionDiscovery.Service, { load: () => Effect.succeed(Instructions.empty) })
  86. const skillInstructions = Layer.mock(SkillInstructions.Service, { load: () => Effect.succeed(Instructions.empty) })
  87. const referenceInstructions = Layer.mock(ReferenceInstructions.Service, {
  88. load: () => Effect.succeed(Instructions.empty),
  89. })
  90. const mcpInstructions = Layer.mock(McpInstructions.Service, { load: () => Effect.succeed(Instructions.empty) })
  91. const config = Config.testLayer()
  92. const pluginSupervisor = Layer.succeed(PluginSupervisor.Service, PluginSupervisor.Service.of({ flush: Effect.void }))
  93. const promptCatalog = Layer.mock(Catalog.Service, {
  94. provider: {
  95. get: () => Effect.succeed(undefined),
  96. all: () => Effect.succeed([]),
  97. available: () => Effect.succeed([]),
  98. },
  99. model: {
  100. get: () => Effect.succeed(undefined),
  101. all: () => Effect.succeed([]),
  102. available: () => Effect.succeed([]),
  103. default: () => Effect.succeed(undefined),
  104. small: () => Effect.succeed(undefined),
  105. },
  106. })
  107. const runnerLayer = (llmClient: Layer.Layer<typeof LLMClient.Service>) =>
  108. AppNodeBuilder.build(SessionRunnerLLM.node, [
  109. [Snapshot.node, Snapshot.noopLayer],
  110. [LayerNodePlatform.llmClient, llmClient],
  111. [SessionRunnerModel.node, models],
  112. [InstructionBuiltIns.node, systemContext],
  113. [InstructionDiscovery.node, instructionContext],
  114. [Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
  115. [SkillInstructions.node, skillInstructions],
  116. [ReferenceInstructions.node, referenceInstructions],
  117. [McpInstructions.node, mcpInstructions],
  118. [Config.node, config],
  119. [Permission.node, permission],
  120. [PluginSupervisor.node, pluginSupervisor],
  121. ])
  122. const execution = (llmClient: Layer.Layer<typeof LLMClient.Service>) =>
  123. Layer.effect(
  124. SessionExecution.Service,
  125. Effect.gen(function* () {
  126. const sessionRunner = yield* SessionRunner.Service
  127. const coordinator = yield* SessionRunCoordinator.make<Session.ID, SessionRunner.RunError>({
  128. drain: (sessionID, force) => sessionRunner.drain({ sessionID, force }),
  129. })
  130. return SessionExecution.Service.of({
  131. active: coordinator.active,
  132. resume: coordinator.run,
  133. wake: coordinator.wake,
  134. interrupt: coordinator.interrupt,
  135. awaitIdle: coordinator.awaitIdle,
  136. })
  137. }),
  138. ).pipe(Layer.provide(runnerLayer(llmClient)))
  139. const testLayer = (llmClient: Layer.Layer<typeof LLMClient.Service>) =>
  140. AppNodeBuilder.build(
  141. LayerNode.group([
  142. Database.node,
  143. Bus.node,
  144. SessionProjector.node,
  145. SessionStore.node,
  146. Agent.node,
  147. Catalog.node,
  148. PluginHooks.node,
  149. Tool.node,
  150. SessionRunnerModel.node,
  151. InstructionBuiltIns.node,
  152. InstructionDiscovery.node,
  153. SkillInstructions.node,
  154. ReferenceInstructions.node,
  155. Config.node,
  156. Snapshot.node,
  157. SessionRunnerLLM.node,
  158. Session.node,
  159. ]),
  160. [
  161. [LayerNodePlatform.llmClient, llmClient],
  162. [Permission.node, permission],
  163. [Catalog.node, promptCatalog],
  164. [SessionRunnerModel.node, models],
  165. [InstructionBuiltIns.node, systemContext],
  166. [InstructionDiscovery.node, instructionContext],
  167. [Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
  168. [SkillInstructions.node, skillInstructions],
  169. [ReferenceInstructions.node, referenceInstructions],
  170. [Config.node, config],
  171. [Snapshot.node, Snapshot.noopLayer],
  172. [PluginSupervisor.node, pluginSupervisor],
  173. [SessionExecution.node, execution(llmClient)],
  174. ],
  175. )
  176. const it = testEffect(testLayer(client))
  177. const sessionID = Session.ID.make("ses_runner_recorded")
  178. describe("SessionRunnerLLM recorded", () => {
  179. it.effect("executes one recorded prompt through the recorded HTTP transport", () =>
  180. Effect.gen(function* () {
  181. const agents = yield* Agent.Service
  182. const catalog = yield* Catalog.Service
  183. const hooks = yield* PluginHooks.Service
  184. yield* agents.transform((draft) =>
  185. draft.update(Agent.ID.make("build"), (agent) => {
  186. agent.mode = "primary"
  187. agent.permissions.push({ action: "execute", resource: "*", effect: "deny" })
  188. }),
  189. )
  190. const pluginHost = host({
  191. agent: agentHost(agents),
  192. catalog: catalogHost(catalog),
  193. session: { hook: (name, callback) => hooks.register("session", name, callback) },
  194. })
  195. yield* Effect.forEach(SystemPromptPlugin.Plugins, (plugin) => plugin.effect(pluginHost), { discard: true })
  196. const { db } = yield* Database.Service
  197. yield* db
  198. .insert(ProjectTable)
  199. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  200. .onConflictDoNothing()
  201. .run()
  202. .pipe(Effect.orDie)
  203. yield* db
  204. .insert(SessionTable)
  205. .values({
  206. id: sessionID,
  207. project_id: Project.ID.global,
  208. slug: "test",
  209. directory: "/project",
  210. title: "test",
  211. version: "test",
  212. })
  213. .onConflictDoNothing()
  214. .run()
  215. .pipe(Effect.orDie)
  216. const session = yield* Session.Service
  217. const prompt = yield* session.prompt({
  218. sessionID,
  219. text: "Say hello in one short sentence.",
  220. resume: false,
  221. })
  222. yield* session.resume(sessionID)
  223. const messages = yield* session.context(sessionID)
  224. expect(messages).toHaveLength(2)
  225. expect(messages[0]).toMatchObject({ id: prompt.id, type: "user", text: "Say hello in one short sentence." })
  226. expect(messages[1]).toMatchObject({ type: "assistant", agent: "build", finish: "stop" })
  227. expect(messages[1]?.type === "assistant" ? messages[1].content : []).toMatchObject([
  228. { type: "text", text: "Hello!" },
  229. ])
  230. expect(
  231. (yield* db
  232. .select({ type: EventTable.type })
  233. .from(EventTable)
  234. .where(eq(EventTable.aggregate_id, sessionID))
  235. .orderBy(EventTable.seq)
  236. .all()).map((event) => event.type),
  237. ).toEqual([
  238. "session.input.admitted.1",
  239. "session.instructions.updated.2",
  240. "session.input.promoted.1",
  241. "session.step.started.1",
  242. "session.text.started.1",
  243. "session.text.ended.1",
  244. "session.step.ended.1",
  245. ])
  246. }),
  247. )
  248. })
  249. describe("SessionModelRequest HTTP bridge", () => {
  250. const bodies: Uint8Array[] = []
  251. const methods: string[] = []
  252. const response = [
  253. 'data: {"id":"chatcmpl_test","object":"chat.completion.chunk","created":0,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello!"},"finish_reason":null}]}',
  254. 'data: {"id":"chatcmpl_test","object":"chat.completion.chunk","created":0,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
  255. "data: [DONE]",
  256. "",
  257. ].join("\n\n")
  258. const transport = Layer.succeed(
  259. HttpClient.HttpClient,
  260. HttpClient.make((request) =>
  261. Effect.sync(() => {
  262. if (request.body._tag !== "Uint8Array") throw new Error(`Unexpected request body: ${request.body._tag}`)
  263. methods.push(request.method)
  264. bodies.push(request.body.body.slice())
  265. return HttpClientResponse.fromWeb(
  266. request,
  267. new Response(response, { headers: { "content-type": "text/event-stream" } }),
  268. )
  269. }),
  270. ),
  271. )
  272. const retryIt = testEffect(
  273. testLayer(LLMClient.layer.pipe(Layer.provide(RequestExecutor.layer.pipe(Layer.provide(transport))))),
  274. )
  275. retryIt.effect("lets an Effect plugin send the same POST Request twice", () =>
  276. Effect.gen(function* () {
  277. bodies.length = 0
  278. methods.length = 0
  279. const agents = yield* Agent.Service
  280. const catalog = yield* Catalog.Service
  281. const hooks = yield* PluginHooks.Service
  282. yield* agents.transform((draft) =>
  283. draft.update(Agent.ID.make("build"), (agent) => {
  284. agent.mode = "primary"
  285. agent.permissions.push({ action: "execute", resource: "*", effect: "deny" })
  286. }),
  287. )
  288. const pluginHost = host({
  289. agent: agentHost(agents),
  290. catalog: catalogHost(catalog),
  291. session: { hook: (name, callback) => hooks.register("session", name, callback) },
  292. })
  293. yield* pluginHost.session.hook("http", (event) =>
  294. event.use((request, next) =>
  295. Effect.gen(function* () {
  296. yield* next(request).pipe(Effect.flatMap((response) => Effect.promise(() => response.text())))
  297. return yield* next(request)
  298. }),
  299. ),
  300. )
  301. yield* Effect.forEach(SystemPromptPlugin.Plugins, (plugin) => plugin.effect(pluginHost), { discard: true })
  302. const { db } = yield* Database.Service
  303. yield* db
  304. .insert(ProjectTable)
  305. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  306. .onConflictDoNothing()
  307. .run()
  308. .pipe(Effect.orDie)
  309. const retrySessionID = Session.ID.make("ses_model_request_http_retry")
  310. yield* db
  311. .insert(SessionTable)
  312. .values({
  313. id: retrySessionID,
  314. project_id: Project.ID.global,
  315. slug: "test",
  316. directory: "/project",
  317. title: "test",
  318. version: "test",
  319. })
  320. .run()
  321. .pipe(Effect.orDie)
  322. const session = yield* Session.Service
  323. yield* session.prompt({ sessionID: retrySessionID, text: "Say hello.", resume: false })
  324. yield* session.resume(retrySessionID)
  325. expect(methods).toEqual(["POST", "POST"])
  326. expect(bodies).toHaveLength(2)
  327. expect(bodies[0]?.byteLength).toBeGreaterThan(0)
  328. expect(bodies[1]).toEqual(bodies[0])
  329. }),
  330. )
  331. })