session-runner-recorded.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. [Bus.node, Bus.configured({ persist: true })],
  162. [LayerNodePlatform.llmClient, llmClient],
  163. [Permission.node, permission],
  164. [Catalog.node, promptCatalog],
  165. [SessionRunnerModel.node, models],
  166. [InstructionBuiltIns.node, systemContext],
  167. [InstructionDiscovery.node, instructionContext],
  168. [Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
  169. [SkillInstructions.node, skillInstructions],
  170. [ReferenceInstructions.node, referenceInstructions],
  171. [Config.node, config],
  172. [Snapshot.node, Snapshot.noopLayer],
  173. [PluginSupervisor.node, pluginSupervisor],
  174. [SessionExecution.node, execution(llmClient)],
  175. ],
  176. )
  177. const it = testEffect(testLayer(client))
  178. const sessionID = Session.ID.make("ses_runner_recorded")
  179. describe("SessionRunnerLLM recorded", () => {
  180. it.effect("executes one recorded prompt through the recorded HTTP transport", () =>
  181. Effect.gen(function* () {
  182. const agents = yield* Agent.Service
  183. const catalog = yield* Catalog.Service
  184. const hooks = yield* PluginHooks.Service
  185. yield* agents.transform((draft) =>
  186. draft.update(Agent.ID.make("build"), (agent) => {
  187. agent.mode = "primary"
  188. agent.permissions.push({ action: "execute", resource: "*", effect: "deny" })
  189. }),
  190. )
  191. const pluginHost = host({
  192. agent: agentHost(agents),
  193. catalog: catalogHost(catalog),
  194. session: { hook: (name, callback) => hooks.register("session", name, callback) },
  195. })
  196. yield* Effect.forEach(SystemPromptPlugin.Plugins, (plugin) => plugin.effect(pluginHost), { discard: true })
  197. const { db } = yield* Database.Service
  198. yield* db
  199. .insert(ProjectTable)
  200. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  201. .onConflictDoNothing()
  202. .run()
  203. .pipe(Effect.orDie)
  204. yield* db
  205. .insert(SessionTable)
  206. .values({
  207. id: sessionID,
  208. project_id: Project.ID.global,
  209. slug: "test",
  210. directory: "/project",
  211. title: "test",
  212. version: "test",
  213. })
  214. .onConflictDoNothing()
  215. .run()
  216. .pipe(Effect.orDie)
  217. const session = yield* Session.Service
  218. const prompt = yield* session.prompt({
  219. sessionID,
  220. text: "Say hello in one short sentence.",
  221. resume: false,
  222. })
  223. yield* session.resume(sessionID)
  224. const messages = yield* session.context(sessionID)
  225. expect(messages).toHaveLength(2)
  226. expect(messages[0]).toMatchObject({ id: prompt.id, type: "user", text: "Say hello in one short sentence." })
  227. expect(messages[1]).toMatchObject({ type: "assistant", agent: "build", finish: "stop" })
  228. expect(messages[1]?.type === "assistant" ? messages[1].content : []).toMatchObject([
  229. { type: "text", text: "Hello!" },
  230. ])
  231. expect(
  232. (yield* db
  233. .select({ type: EventTable.type })
  234. .from(EventTable)
  235. .where(eq(EventTable.aggregate_id, sessionID))
  236. .orderBy(EventTable.seq)
  237. .all()).map((event) => event.type),
  238. ).toEqual([
  239. "session.input.admitted.1",
  240. "session.instructions.updated.2",
  241. "session.input.promoted.1",
  242. "session.step.started.1",
  243. "session.text.started.1",
  244. "session.text.ended.1",
  245. "session.step.ended.1",
  246. ])
  247. }),
  248. )
  249. })
  250. describe("SessionModelRequest HTTP bridge", () => {
  251. const bodies: Uint8Array[] = []
  252. const methods: string[] = []
  253. const headers: Array<string | undefined> = []
  254. const response = [
  255. '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}]}',
  256. 'data: {"id":"chatcmpl_test","object":"chat.completion.chunk","created":0,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
  257. "data: [DONE]",
  258. "",
  259. ].join("\n\n")
  260. const transport = Layer.succeed(
  261. HttpClient.HttpClient,
  262. HttpClient.make((request) =>
  263. Effect.sync(() => {
  264. if (request.body._tag !== "Uint8Array") throw new Error(`Unexpected request body: ${request.body._tag}`)
  265. methods.push(request.method)
  266. bodies.push(request.body.body.slice())
  267. headers.push(request.headers["x-hook"])
  268. return HttpClientResponse.fromWeb(
  269. request,
  270. new Response(response, { headers: { "content-type": "text/event-stream" } }),
  271. )
  272. }),
  273. ),
  274. )
  275. const httpIt = testEffect(
  276. testLayer(LLMClient.layer.pipe(Layer.provide(RequestExecutor.layer.pipe(Layer.provide(transport))))),
  277. )
  278. httpIt.effect("runs Effect HTTP request and response hooks around one provider request", () =>
  279. Effect.gen(function* () {
  280. bodies.length = 0
  281. methods.length = 0
  282. headers.length = 0
  283. const seen: string[] = []
  284. const agents = yield* Agent.Service
  285. const catalog = yield* Catalog.Service
  286. const hooks = yield* PluginHooks.Service
  287. yield* agents.transform((draft) =>
  288. draft.update(Agent.ID.make("build"), (agent) => {
  289. agent.mode = "primary"
  290. agent.permissions.push({ action: "execute", resource: "*", effect: "deny" })
  291. }),
  292. )
  293. const pluginHost = host({
  294. agent: agentHost(agents),
  295. catalog: catalogHost(catalog),
  296. session: { hook: (name, callback) => hooks.register("session", name, callback) },
  297. })
  298. yield* pluginHost.session.hook("http.request", (event) =>
  299. Effect.sync(() => {
  300. seen.push("request")
  301. event.request.headers.set("x-hook", "effect")
  302. }),
  303. )
  304. yield* pluginHost.session.hook("http.response", (event) =>
  305. Effect.gen(function* () {
  306. seen.push(`response:${event.response.status}:${event.request.headers.get("x-hook")}`)
  307. event.response = new Response(
  308. (yield* Effect.promise(() => event.response.text())).replace("Hello!", "Hooked!"),
  309. event.response,
  310. )
  311. }),
  312. )
  313. yield* Effect.forEach(SystemPromptPlugin.Plugins, (plugin) => plugin.effect(pluginHost), { discard: true })
  314. const { db } = yield* Database.Service
  315. yield* db
  316. .insert(ProjectTable)
  317. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  318. .onConflictDoNothing()
  319. .run()
  320. .pipe(Effect.orDie)
  321. const retrySessionID = Session.ID.make("ses_model_request_http_retry")
  322. yield* db
  323. .insert(SessionTable)
  324. .values({
  325. id: retrySessionID,
  326. project_id: Project.ID.global,
  327. slug: "test",
  328. directory: "/project",
  329. title: "test",
  330. version: "test",
  331. })
  332. .run()
  333. .pipe(Effect.orDie)
  334. const session = yield* Session.Service
  335. yield* session.prompt({ sessionID: retrySessionID, text: "Say hello.", resume: false })
  336. yield* session.resume(retrySessionID)
  337. expect(methods).toEqual(["POST"])
  338. expect(headers).toEqual(["effect"])
  339. expect(seen).toEqual(["request", "response:200:effect"])
  340. expect(bodies).toHaveLength(1)
  341. expect(bodies[0]?.byteLength).toBeGreaterThan(0)
  342. expect((yield* session.context(retrySessionID))[1]).toMatchObject({
  343. type: "assistant",
  344. content: [{ type: "text", text: "Hooked!" }],
  345. })
  346. }),
  347. )
  348. })