llm-native-recorded.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import { NodeFileSystem } from "@effect/platform-node"
  2. import { HttpRecorder, Redactor } from "@opencode-ai/http-recorder"
  3. import { describe, expect } from "bun:test"
  4. import { tool, type ModelMessage, type JSONValue } from "ai"
  5. import { Effect, Layer, Stream } from "effect"
  6. import { FetchHttpClient } from "effect/unstable/http"
  7. import path from "node:path"
  8. import z from "zod"
  9. import { Auth } from "@/auth"
  10. import { Config } from "@/config/config"
  11. import { Plugin } from "@/plugin"
  12. import { Provider } from "@/provider/provider"
  13. import { ModelID, ProviderID } from "@/provider/schema"
  14. import { Filesystem } from "@/util/filesystem"
  15. import { LLMEvent, LLMResponse } from "@opencode-ai/llm"
  16. import { LLMClient, RequestExecutor } from "@opencode-ai/llm/route"
  17. import { RuntimeFlags } from "@/effect/runtime-flags"
  18. import type { Agent } from "../../src/agent/agent"
  19. import { LLM } from "../../src/session/llm"
  20. import { MessageV2 } from "../../src/session/message-v2"
  21. import { MessageID, SessionID } from "../../src/session/schema"
  22. import type { ModelsDev } from "@opencode-ai/core/models-dev"
  23. import { TestInstance } from "../fixture/fixture"
  24. import { testEffect } from "../lib/effect"
  25. const FIXTURES_DIR = path.join(import.meta.dir, "../fixtures/recordings")
  26. const zenURL = (connection: string) => `https://console.opencode.ai/proxy/connections/${connection}/v1`
  27. type ProviderSpec = {
  28. readonly providerID: ProviderID
  29. readonly modelID: string
  30. readonly cassette: string
  31. readonly protocol: string
  32. readonly tags: ReadonlyArray<string>
  33. readonly canRecord: boolean
  34. readonly config: (model: ModelsDev.Provider["models"][string]) => Partial<Config.Info>
  35. }
  36. const cloneModel = (model: ModelsDev.Provider["models"][string]) =>
  37. structuredClone(model) as NonNullable<NonNullable<Config.Info["provider"]>[string]["models"]>[string]
  38. const PROVIDERS = {
  39. openai: {
  40. providerID: ProviderID.openai,
  41. modelID: "gpt-4.1-mini",
  42. cassette: "session/native-openai-tool-loop",
  43. protocol: "openai-responses",
  44. tags: ["opencode", "native", "tool-loop"],
  45. canRecord: Boolean(process.env.OPENCODE_RECORD_OPENAI_API_KEY ?? process.env.OPENAI_API_KEY),
  46. config: (model) => ({
  47. enabled_providers: ["openai"],
  48. provider: {
  49. openai: {
  50. name: "OpenAI",
  51. env: ["OPENAI_API_KEY"],
  52. npm: "@ai-sdk/openai",
  53. api: "https://api.openai.com/v1",
  54. models: { [model.id]: cloneModel(model) },
  55. options: {
  56. apiKey: process.env.OPENCODE_RECORD_OPENAI_API_KEY ?? process.env.OPENAI_API_KEY ?? "fixture-openai-key",
  57. baseURL: "https://api.openai.com/v1",
  58. },
  59. },
  60. },
  61. }),
  62. },
  63. opencode: {
  64. providerID: ProviderID.opencode,
  65. modelID: "gpt-5.2-codex",
  66. cassette: "session/native-zen-tool-loop",
  67. protocol: "openai-responses",
  68. tags: ["opencode", "zen", "native", "tool-loop"],
  69. canRecord: Boolean(process.env.OPENCODE_RECORD_CONSOLE_TOKEN && process.env.OPENCODE_RECORD_ZEN_ORG_ID),
  70. config: (model) => ({
  71. enabled_providers: ["opencode"],
  72. provider: {
  73. opencode: {
  74. name: "OpenCode Zen",
  75. env: ["OPENCODE_CONSOLE_TOKEN"],
  76. npm: "@ai-sdk/openai-compatible",
  77. // The connection slug is account-specific; the cassette redactor
  78. // normalizes it to {connection} for replay. Set during recording.
  79. api: zenURL(process.env.OPENCODE_RECORD_ZEN_CONNECTION ?? "fixture"),
  80. models: { [model.id]: cloneModel(model) },
  81. options: {
  82. apiKey: process.env.OPENCODE_RECORD_CONSOLE_TOKEN ?? "fixture-console-token",
  83. headers: { "x-org-id": process.env.OPENCODE_RECORD_ZEN_ORG_ID ?? "fixture-org" },
  84. },
  85. },
  86. },
  87. }),
  88. },
  89. anthropic: {
  90. providerID: ProviderID.anthropic,
  91. modelID: "claude-haiku-4-5-20251001",
  92. cassette: "session/native-anthropic-tool-loop",
  93. protocol: "anthropic-messages",
  94. tags: ["opencode", "native", "tool-loop"],
  95. canRecord: Boolean(process.env.OPENCODE_RECORD_ANTHROPIC_API_KEY ?? process.env.ANTHROPIC_API_KEY),
  96. config: (model) => ({
  97. enabled_providers: ["anthropic"],
  98. provider: {
  99. anthropic: {
  100. name: "Anthropic",
  101. env: ["ANTHROPIC_API_KEY"],
  102. npm: "@ai-sdk/anthropic",
  103. api: "https://api.anthropic.com/v1",
  104. models: { [model.id]: cloneModel(model) },
  105. options: {
  106. apiKey:
  107. process.env.OPENCODE_RECORD_ANTHROPIC_API_KEY ?? process.env.ANTHROPIC_API_KEY ?? "fixture-anthropic-key",
  108. baseURL: "https://api.anthropic.com/v1",
  109. },
  110. },
  111. },
  112. }),
  113. },
  114. } satisfies Record<string, ProviderSpec>
  115. const shouldRecord = process.env.RECORD === "true"
  116. const canRun = (spec: ProviderSpec) =>
  117. shouldRecord ? spec.canRecord : HttpRecorder.hasCassetteSync(spec.cassette, { directory: FIXTURES_DIR })
  118. async function loadFixture(providerID: string, modelID: string) {
  119. const data = await Filesystem.readJson<Record<string, ModelsDev.Provider>>(
  120. path.join(import.meta.dir, "../tool/fixtures/models-api.json"),
  121. )
  122. const provider = data[providerID]
  123. if (!provider) throw new Error(`Missing provider in fixture: ${providerID}`)
  124. const model = provider.models[modelID]
  125. if (!model) throw new Error(`Missing model in fixture: ${modelID}`)
  126. return model
  127. }
  128. function recordedNativeLLMLayer(spec: ProviderSpec) {
  129. // Only the HTTP client is recorded; RequestExecutor and the opencode LLM stack remain real.
  130. const recordedClient = LLMClient.layer.pipe(
  131. Layer.provide(RequestExecutor.layer),
  132. Layer.provide(
  133. HttpRecorder.recordingLayer(spec.cassette, {
  134. mode: shouldRecord ? "record" : "replay",
  135. metadata: { provider: spec.providerID, protocol: spec.protocol, route: spec.protocol, tags: spec.tags },
  136. redactor: Redactor.compose(
  137. Redactor.defaults({
  138. url: {
  139. transform: (url) => url.replace(/\/proxy\/connections\/[^/]+\/v1/, "/proxy/connections/{connection}/v1"),
  140. },
  141. }),
  142. {
  143. response: (snapshot) => ({ ...snapshot, body: snapshot.body.replace(/wrk_[A-Z0-9]+/g, "wrk_redacted") }),
  144. },
  145. ),
  146. }).pipe(Layer.provide(FetchHttpClient.layer)),
  147. ),
  148. )
  149. return Layer.mergeAll(
  150. Provider.defaultLayer.pipe(
  151. Layer.provide(Auth.defaultLayer),
  152. Layer.provide(Config.defaultLayer),
  153. Layer.provide(Plugin.defaultLayer),
  154. ),
  155. LLM.layer.pipe(
  156. Layer.provide(Auth.defaultLayer),
  157. Layer.provide(Config.defaultLayer),
  158. Layer.provide(Provider.defaultLayer),
  159. Layer.provide(Plugin.defaultLayer),
  160. Layer.provide(recordedClient),
  161. Layer.provide(HttpRecorder.Cassette.fileSystem({ directory: FIXTURES_DIR }).pipe(Layer.provide(NodeFileSystem.layer))),
  162. Layer.provide(RuntimeFlags.layer({ experimentalNativeLlm: true })),
  163. ),
  164. )
  165. }
  166. const writeConfig = (directory: string, spec: ProviderSpec, model: ModelsDev.Provider["models"][string]) =>
  167. Effect.promise(() =>
  168. Bun.write(
  169. path.join(directory, "opencode.json"),
  170. JSON.stringify({ $schema: "https://opencode.ai/config.json", ...spec.config(model) }),
  171. ),
  172. )
  173. const collect = (input: LLM.StreamInput) =>
  174. Effect.gen(function* () {
  175. const llm = yield* LLM.Service
  176. return Array.from(yield* llm.stream(input).pipe(Stream.runCollect))
  177. })
  178. const WEATHER_RESULT = { temperature: 22, condition: "sunny" } as const
  179. const WEATHER_SYSTEM =
  180. "Use the get_weather tool exactly once to look up Paris, then reply with exactly: Paris is sunny."
  181. const WEATHER_USER = "What is the weather in Paris?"
  182. const weatherTool = tool({
  183. description: "Get the current weather for a city.",
  184. inputSchema: z.object({ city: z.string() }),
  185. execute: async () => WEATHER_RESULT,
  186. })
  187. const toolRoundtrip = (
  188. call: { readonly id: string; readonly name: string; readonly input: unknown },
  189. result: JSONValue,
  190. ): ModelMessage[] => [
  191. { role: "assistant", content: [{ type: "tool-call", toolCallId: call.id, toolName: call.name, input: call.input }] },
  192. {
  193. role: "tool",
  194. content: [{ type: "tool-result", toolCallId: call.id, toolName: call.name, output: { type: "json", value: result } }],
  195. },
  196. ]
  197. const driveToolLoop = (spec: ProviderSpec) =>
  198. Effect.gen(function* () {
  199. const test = yield* TestInstance
  200. const model = yield* Effect.promise(() => loadFixture(spec.providerID, spec.modelID))
  201. yield* writeConfig(test.directory, spec, model)
  202. const sessionID = SessionID.make(`session-recorded-${spec.providerID}-loop`)
  203. const modelID = ModelID.make(model.id)
  204. const agent = {
  205. name: "test",
  206. mode: "primary",
  207. prompt: "Answer using tools when appropriate.",
  208. options: {},
  209. permission: [{ permission: "*", pattern: "*", action: "allow" }],
  210. temperature: 0,
  211. } satisfies Agent.Info
  212. const provider = yield* Provider.Service
  213. const resolved = yield* provider.getModel(spec.providerID, modelID)
  214. const userMessage = { role: "user", content: WEATHER_USER } satisfies ModelMessage
  215. const base = {
  216. user: {
  217. id: MessageID.make(`msg_user-recorded-${spec.providerID}-loop`),
  218. sessionID,
  219. role: "user",
  220. time: { created: 0 },
  221. agent: agent.name,
  222. model: { providerID: spec.providerID, modelID },
  223. } satisfies MessageV2.User,
  224. sessionID,
  225. model: resolved,
  226. agent,
  227. system: [WEATHER_SYSTEM],
  228. tools: { get_weather: weatherTool },
  229. }
  230. const turn1 = yield* collect({ ...base, messages: [userMessage] })
  231. const toolCall = turn1.find(LLMEvent.is.toolCall)
  232. expect(toolCall).toBeDefined()
  233. expect(turn1.find(LLMEvent.is.toolResult)).toBeDefined()
  234. expect(toolCall!.name).toBe("get_weather")
  235. expect(toolCall!.input).toMatchObject({ city: expect.stringMatching(/Paris/i) })
  236. expect(turn1.filter(LLMEvent.is.stepFinish)).toHaveLength(1)
  237. const turn2 = yield* collect({
  238. ...base,
  239. messages: [userMessage, ...toolRoundtrip(toolCall!, WEATHER_RESULT)],
  240. })
  241. expect(LLMResponse.text({ events: turn2 })).toMatch(/Paris is sunny/i)
  242. expect(turn2.filter(LLMEvent.is.finish)).toHaveLength(1)
  243. expect(turn2.filter(LLMEvent.is.toolCall)).toHaveLength(0)
  244. })
  245. describe("session.llm native recorded", () => {
  246. for (const [name, spec] of Object.entries(PROVIDERS)) {
  247. const it = testEffect(recordedNativeLLMLayer(spec))
  248. const instance = canRun(spec) ? it.instance : it.instance.skip
  249. instance(`${name}: drives a tool loop to a final text answer`, () => driveToolLoop(spec))
  250. }
  251. })