session-runner-recorded.test.ts 14 KB

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