session-runner-recorded.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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, {
  86. project: true,
  87. load: () => Effect.succeed(Instructions.empty),
  88. })
  89. const skillInstructions = Layer.mock(SkillInstructions.Service, { load: () => Effect.succeed(Instructions.empty) })
  90. const referenceInstructions = Layer.mock(ReferenceInstructions.Service, {
  91. load: () => Effect.succeed(Instructions.empty),
  92. })
  93. const mcpInstructions = Layer.mock(McpInstructions.Service, { load: () => Effect.succeed(Instructions.empty) })
  94. const config = Config.testLayer()
  95. const pluginSupervisor = Layer.succeed(PluginSupervisor.Service, PluginSupervisor.Service.of({ flush: Effect.void }))
  96. const promptCatalog = Layer.mock(Catalog.Service, {
  97. provider: {
  98. get: () => Effect.succeed(undefined),
  99. all: () => Effect.succeed([]),
  100. available: () => Effect.succeed([]),
  101. },
  102. model: {
  103. get: () => Effect.succeed(undefined),
  104. all: () => Effect.succeed([]),
  105. available: () => Effect.succeed([]),
  106. default: () => Effect.succeed(undefined),
  107. small: () => Effect.succeed(undefined),
  108. },
  109. })
  110. const runnerLayer = (llmClient: Layer.Layer<typeof LLMClient.Service>) =>
  111. AppNodeBuilder.build(SessionRunnerLLM.node, [
  112. [Snapshot.node, Snapshot.noopLayer],
  113. [LayerNodePlatform.llmClient, llmClient],
  114. [SessionRunnerModel.node, models],
  115. [InstructionBuiltIns.node, systemContext],
  116. [InstructionDiscovery.node, instructionContext],
  117. [Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
  118. [SkillInstructions.node, skillInstructions],
  119. [ReferenceInstructions.node, referenceInstructions],
  120. [McpInstructions.node, mcpInstructions],
  121. [Config.node, config],
  122. [Permission.node, permission],
  123. [PluginSupervisor.node, pluginSupervisor],
  124. ])
  125. const execution = (llmClient: Layer.Layer<typeof LLMClient.Service>) =>
  126. Layer.effect(
  127. SessionExecution.Service,
  128. Effect.gen(function* () {
  129. const sessionRunner = yield* SessionRunner.Service
  130. const coordinator = yield* SessionRunCoordinator.make<Session.ID, SessionRunner.RunError>({
  131. drain: (sessionID, force) => sessionRunner.drain({ sessionID, force }),
  132. })
  133. return SessionExecution.Service.of({
  134. active: coordinator.active,
  135. resume: coordinator.run,
  136. wake: coordinator.wake,
  137. interrupt: coordinator.interrupt,
  138. awaitIdle: coordinator.awaitIdle,
  139. })
  140. }),
  141. ).pipe(Layer.provide(runnerLayer(llmClient)))
  142. const testLayer = (llmClient: Layer.Layer<typeof LLMClient.Service>) =>
  143. AppNodeBuilder.build(
  144. LayerNode.group([
  145. Database.node,
  146. Bus.node,
  147. SessionProjector.node,
  148. SessionStore.node,
  149. Agent.node,
  150. Catalog.node,
  151. PluginHooks.node,
  152. Tool.node,
  153. SessionRunnerModel.node,
  154. InstructionBuiltIns.node,
  155. InstructionDiscovery.node,
  156. SkillInstructions.node,
  157. ReferenceInstructions.node,
  158. Config.node,
  159. Snapshot.node,
  160. SessionRunnerLLM.node,
  161. Session.node,
  162. ]),
  163. [
  164. [Bus.node, Bus.configured({ persist: true })],
  165. [LayerNodePlatform.llmClient, llmClient],
  166. [Permission.node, permission],
  167. [Catalog.node, promptCatalog],
  168. [SessionRunnerModel.node, models],
  169. [InstructionBuiltIns.node, systemContext],
  170. [InstructionDiscovery.node, instructionContext],
  171. [Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
  172. [SkillInstructions.node, skillInstructions],
  173. [ReferenceInstructions.node, referenceInstructions],
  174. [Config.node, config],
  175. [Snapshot.node, Snapshot.noopLayer],
  176. [PluginSupervisor.node, pluginSupervisor],
  177. [SessionExecution.node, execution(llmClient)],
  178. ],
  179. )
  180. const it = testEffect(testLayer(client))
  181. const sessionID = Session.ID.make("ses_runner_recorded")
  182. describe("SessionRunnerLLM recorded", () => {
  183. it.effect("executes one recorded prompt through the recorded HTTP transport", () =>
  184. Effect.gen(function* () {
  185. const agents = yield* Agent.Service
  186. const catalog = yield* Catalog.Service
  187. const hooks = yield* PluginHooks.Service
  188. yield* agents.transform((draft) =>
  189. draft.update(Agent.ID.make("build"), (agent) => {
  190. agent.mode = "primary"
  191. agent.permissions.push({ action: "execute", resource: "*", effect: "deny" })
  192. }),
  193. )
  194. const pluginHost = host({
  195. agent: agentHost(agents),
  196. catalog: catalogHost(catalog),
  197. session: { hook: (name, callback) => hooks.register("session", name, callback) },
  198. })
  199. yield* Effect.forEach(SystemPromptPlugin.Plugins, (plugin) => plugin.effect(pluginHost), { discard: true })
  200. const { db } = yield* Database.Service
  201. yield* db
  202. .insert(ProjectTable)
  203. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  204. .onConflictDoNothing()
  205. .run()
  206. .pipe(Effect.orDie)
  207. yield* db
  208. .insert(SessionTable)
  209. .values({
  210. id: sessionID,
  211. project_id: Project.ID.global,
  212. slug: "test",
  213. directory: "/project",
  214. title: "test",
  215. version: "test",
  216. })
  217. .onConflictDoNothing()
  218. .run()
  219. .pipe(Effect.orDie)
  220. const session = yield* Session.Service
  221. const prompt = yield* session.prompt({
  222. sessionID,
  223. text: "Say hello in one short sentence.",
  224. resume: false,
  225. })
  226. yield* session.resume(sessionID)
  227. const messages = yield* session.context(sessionID)
  228. expect(messages).toHaveLength(2)
  229. expect(messages[0]).toMatchObject({ id: prompt.id, type: "user", text: "Say hello in one short sentence." })
  230. expect(messages[1]).toMatchObject({ type: "assistant", agent: "build", finish: "stop" })
  231. expect(messages[1]?.type === "assistant" ? messages[1].content : []).toMatchObject([
  232. { type: "text", text: "Hello!" },
  233. ])
  234. expect(
  235. (yield* db
  236. .select({ type: EventTable.type })
  237. .from(EventTable)
  238. .where(eq(EventTable.aggregate_id, sessionID))
  239. .orderBy(EventTable.seq)
  240. .all()).map((event) => event.type),
  241. ).toEqual([
  242. "session.input.admitted.1",
  243. "session.instructions.updated.2",
  244. "session.input.promoted.1",
  245. "session.step.started.1",
  246. "session.text.started.1",
  247. "session.text.ended.1",
  248. "session.step.ended.1",
  249. ])
  250. }),
  251. )
  252. })
  253. describe("SessionModelRequest HTTP bridge", () => {
  254. const bodies: Uint8Array[] = []
  255. const methods: string[] = []
  256. const headers: Array<string | undefined> = []
  257. const response = [
  258. '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}]}',
  259. 'data: {"id":"chatcmpl_test","object":"chat.completion.chunk","created":0,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
  260. "data: [DONE]",
  261. "",
  262. ].join("\n\n")
  263. const transport = Layer.succeed(
  264. HttpClient.HttpClient,
  265. HttpClient.make((request) =>
  266. Effect.sync(() => {
  267. if (request.body._tag !== "Uint8Array") throw new Error(`Unexpected request body: ${request.body._tag}`)
  268. methods.push(request.method)
  269. bodies.push(request.body.body.slice())
  270. headers.push(request.headers["x-hook"])
  271. return HttpClientResponse.fromWeb(
  272. request,
  273. new Response(response, { headers: { "content-type": "text/event-stream" } }),
  274. )
  275. }),
  276. ),
  277. )
  278. const httpIt = testEffect(
  279. testLayer(LLMClient.layer.pipe(Layer.provide(RequestExecutor.layer.pipe(Layer.provide(transport))))),
  280. )
  281. httpIt.effect("runs Effect HTTP request and response hooks around one provider request", () =>
  282. Effect.gen(function* () {
  283. bodies.length = 0
  284. methods.length = 0
  285. headers.length = 0
  286. const seen: string[] = []
  287. const agents = yield* Agent.Service
  288. const catalog = yield* Catalog.Service
  289. const hooks = yield* PluginHooks.Service
  290. yield* agents.transform((draft) =>
  291. draft.update(Agent.ID.make("build"), (agent) => {
  292. agent.mode = "primary"
  293. agent.permissions.push({ action: "execute", resource: "*", effect: "deny" })
  294. }),
  295. )
  296. const pluginHost = host({
  297. agent: agentHost(agents),
  298. catalog: catalogHost(catalog),
  299. session: { hook: (name, callback) => hooks.register("session", name, callback) },
  300. })
  301. yield* pluginHost.session.hook("http.request", (event) =>
  302. Effect.sync(() => {
  303. seen.push("request")
  304. event.request.headers.set("x-hook", "effect")
  305. }),
  306. )
  307. yield* pluginHost.session.hook("http.response", (event) =>
  308. Effect.gen(function* () {
  309. seen.push(`response:${event.response.status}:${event.request.headers.get("x-hook")}`)
  310. event.response = new Response(
  311. (yield* Effect.promise(() => event.response.text())).replace("Hello!", "Hooked!"),
  312. event.response,
  313. )
  314. }),
  315. )
  316. yield* Effect.forEach(SystemPromptPlugin.Plugins, (plugin) => plugin.effect(pluginHost), { discard: true })
  317. const { db } = yield* Database.Service
  318. yield* db
  319. .insert(ProjectTable)
  320. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  321. .onConflictDoNothing()
  322. .run()
  323. .pipe(Effect.orDie)
  324. const retrySessionID = Session.ID.make("ses_model_request_http_retry")
  325. yield* db
  326. .insert(SessionTable)
  327. .values({
  328. id: retrySessionID,
  329. project_id: Project.ID.global,
  330. slug: "test",
  331. directory: "/project",
  332. title: "test",
  333. version: "test",
  334. })
  335. .run()
  336. .pipe(Effect.orDie)
  337. const session = yield* Session.Service
  338. yield* session.prompt({ sessionID: retrySessionID, text: "Say hello.", resume: false })
  339. yield* session.resume(retrySessionID)
  340. expect(methods).toEqual(["POST"])
  341. expect(headers).toEqual(["effect"])
  342. expect(seen).toEqual(["request", "response:200:effect"])
  343. expect(bodies).toHaveLength(1)
  344. expect(bodies[0]?.byteLength).toBeGreaterThan(0)
  345. expect((yield* session.context(retrySessionID))[1]).toMatchObject({
  346. type: "assistant",
  347. content: [{ type: "text", text: "Hooked!" }],
  348. })
  349. }),
  350. )
  351. })