Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OpenCodeDriver.ts

451 lines18.0 KB

1/**
2 * OpenCodeDriver — `ProviderDriver` for the OpenCode runtime.
3 *
4 * Mirrors the Codex / Claude drivers: a plain value whose `create()`
5 * bundles `snapshot` / `adapter` / `textGeneration` closures over the
6 * per-instance `OpenCodeSettings`.
7 *
8 * Two instances with different `serverUrl`s therefore talk to independent
9 * OpenCode servers; when no `serverUrl` is set, the adapter + text-generation
10 * shares spin up their own scoped child processes, and those child
11 * processes are released when the registry scope closes.
12 *
13 * @module provider/Drivers/OpenCodeDriver
14 */
15import { OpenCodeSettings, ProviderDriverKind, TextGenerationError } from "@t3tools/contracts";
16import * as Crypto from "effect/Crypto";
17import * as Effect from "effect/Effect";
18import * as Option from "effect/Option";
19import * as FileSystem from "effect/FileSystem";
20import * as Path from "effect/Path";
21import * as Schema from "effect/Schema";
22import { HttpClient } from "effect/unstable/http";
23import { ChildProcessSpawner } from "effect/unstable/process";
24​
25import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
26import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
27import * as ServerConfig from "../../config.ts";
28import * as OpenCodeAdapterV2 from "../../orchestration-v2/Adapters/OpenCodeAdapterV2.ts";
29import * as OpenCode2AdapterV2 from "../../orchestration-v2/Adapters/OpenCode2AdapterV2.ts";
30import type { ProviderAdapterV2Shape } from "../../orchestration-v2/ProviderAdapter.ts";
31import * as ServerSettings from "../../serverSettings.ts";
32import type { TextGeneration } from "../../textGeneration/TextGeneration.ts";
33import { ProviderDriverError } from "../Errors.ts";
34import { readOpenCodeGoUsageLimits } from "../Layers/openCodeUsageLimits.ts";
35import {
36 checkOpenCodeProviderStatus,
37 makeOpenCode2ModelLoader,
38 makePendingOpenCodeProvider,
39 openCodeSkillsToServerProviderSkills,
40 openCodeCommandsToServerProviderSlashCommands,
41} from "../Layers/OpenCodeProvider.ts";
42import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
43import * as OpenCodeRuntime from "../opencodeRuntime.ts";
44import {
45 makeOpenCodeRuntimeProbe,
46 probeOpenCodeRuntime,
47 type ProbedOpenCode,
48} from "../opencodeVersionProbe.ts";
49import * as OpenCodeServerOwner from "../OpenCodeServerOwner.ts";
50import * as OpenCode2Client from "../opencode2/OpenCode2Client.ts";
51import * as OpenCode2Server from "../opencode2/OpenCode2Server.ts";
52import {
53 defaultProviderContinuationIdentity,
54 type ProviderDriver,
55 type ProviderInstance,
56} from "../ProviderDriver.ts";
57import { withInstanceIdentity } from "./instanceIdentity.ts";
58import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
59import {
60 enrichProviderSnapshotWithVersionAdvisory,
61 makeCachedProviderMaintenanceResolution,
62 makePackageManagedProviderMaintenanceResolver,
63 normalizeCommandPath,
64 resolveProviderMaintenanceCapabilitiesEffect,
65} from "../providerMaintenance.ts";
66import {
67 haveProviderSnapshotSettingsChanged,
68 makeProviderSnapshotSettingsSource,
69 type ProviderSnapshotSettings,
70} from "../providerUpdateSettings.ts";
71const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
72​
73const DRIVER_KIND = ProviderDriverKind.make("opencode");
74​
75function isOpenCodeNativeCommandPath(commandPath: string): boolean {
76 const normalized = normalizeCommandPath(commandPath);
77 return (
78 normalized.endsWith("/.opencode/bin/opencode") ||
79 normalized.endsWith("/.opencode/bin/opencode.exe")
80 );
82​
83const UPDATE = makePackageManagedProviderMaintenanceResolver({
84 provider: DRIVER_KIND,
85 npmPackageName: "opencode-ai",
86 nativeUpdate: {
87 args: ["upgrade"],
88 isCommandPath: isOpenCodeNativeCommandPath,
89 },
90});
91​
92export const OPENCODE_2_TEXT_GENERATION_UNSUPPORTED =
93 "T3 Code cannot generate text with OpenCode 2 yet.";
94​
95type OpenCodeRuntimeProbe = Effect.Success<
96 ReturnType<typeof makeOpenCodeRuntimeProbe<OpenCodeRuntime.OpenCodeRuntimeError>>
97>;
98​
99/** Runs `v2` for a 2.x instance and `v1` otherwise; a failed probe keeps 1.x, whose checks report it. */
100function byOpenCodeRuntime<A, E, R, PE>(
101 probed: Effect.Effect<ProbedOpenCode | undefined, PE>,
102 paths: { readonly v1: Effect.Effect<A, E, R>; readonly v2: Effect.Effect<A, E, R> },
103): Effect.Effect<A, E, R> {
104 return probed.pipe(
105 Effect.orElseSucceed(() => undefined),
106 Effect.flatMap((result) => (result?.generation === "v2" ? paths.v2 : paths.v1)),
107 );
109​
110/**
111 * Routes each adapter call to the runtime the instance's probe detected. Capability and selection
112 * reads are hot, so they use the last successful probe (1.x before one lands) and never wait on a
113 * slow server. Opening a session waits for a probe, so each server is spoken to in its own protocol.
114 */
115function selectOpenCodeRuntimeAdapter(input: {
116 readonly probe: OpenCodeRuntimeProbe;
117 readonly v1: ProviderAdapterV2Shape;
118 readonly v2: ProviderAdapterV2Shape;
119}): ProviderAdapterV2Shape {
120 const pick = <PE>(probed: Effect.Effect<ProbedOpenCode | undefined, PE>) =>
121 byOpenCodeRuntime(probed, { v1: Effect.succeed(input.v1), v2: Effect.succeed(input.v2) });
122 const hot = pick(Effect.map(input.probe.lastSuccess, Option.getOrUndefined));
123 return {
124 instanceId: input.v1.instanceId,
125 driver: DRIVER_KIND,
126 getCapabilities: () => Effect.flatMap(hot, (adapter) => adapter.getCapabilities()),
127 planSelectionTransition: (transition) =>
128 Effect.flatMap(hot, (adapter) => adapter.planSelectionTransition(transition)),
129 openSession: (session) =>
130 Effect.flatMap(pick(input.probe.get), (adapter) => adapter.openSession(session)),
131 };
133​
134/** Text generation starts or connects to a 1.x server per call, so a 2.x is refused first. */
135function selectOpenCodeRuntimeTextGeneration(
136 probe: OpenCodeRuntimeProbe,
137 v1: TextGeneration["Service"],
138): TextGeneration["Service"] {
139 const refuse = (operation: string) =>
140 Effect.fail(
141 new TextGenerationError({ operation, detail: OPENCODE_2_TEXT_GENERATION_UNSUPPORTED }),
142 );
143 return {
144 generateCommitMessage: (input) =>
145 byOpenCodeRuntime(probe.get, {
146 v1: v1.generateCommitMessage(input),
147 v2: refuse("generateCommitMessage"),
148 }),
149 generatePrContent: (input) =>
150 byOpenCodeRuntime(probe.get, {
151 v1: v1.generatePrContent(input),
152 v2: refuse("generatePrContent"),
153 }),
154 generateBranchName: (input) =>
155 byOpenCodeRuntime(probe.get, {
156 v1: v1.generateBranchName(input),
157 v2: refuse("generateBranchName"),
158 }),
159 generateThreadTitle: (input) =>
160 byOpenCodeRuntime(probe.get, {
161 v1: v1.generateThreadTitle(input),
162 v2: refuse("generateThreadTitle"),
163 }),
164 };
166​
167export type OpenCodeDriverEnv =
168 | OpenCodeAdapterV2.OpenCodeAdapterV2DriverEnv
169 | BackgroundPolicy.BackgroundPolicy
170 | ChildProcessSpawner.ChildProcessSpawner
171 | Crypto.Crypto
172 | FileSystem.FileSystem
173 | HttpClient.HttpClient
174 | OpenCodeRuntime.OpenCodeRuntime
175 | Path.Path
176 | ServerConfig.ServerConfig
177 | ServerSettings.ServerSettingsService;
178​
179export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv> = {
180 driverKind: DRIVER_KIND,
181 metadata: {
182 displayName: "OpenCode",
183 supportsMultipleInstances: true,
184 },
185 configSchema: OpenCodeSettings,
186 defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
187 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
188 Effect.gen(function* () {
189 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
190 const fileSystem = yield* FileSystem.FileSystem;
191 const pathService = yield* Path.Path;
192 const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
193 const serverConfig = yield* ServerConfig.ServerConfig;
194 const httpClient = yield* HttpClient.HttpClient;
195 const serverSettings = yield* ServerSettings.ServerSettingsService;
196 const processEnv = mergeProviderInstanceEnvironment(environment);
197 const continuationIdentity = defaultProviderContinuationIdentity({
198 driverKind: DRIVER_KIND,
199 instanceId,
200 });
201 const stampIdentity = withInstanceIdentity({
202 instanceId,
203 driverKind: DRIVER_KIND,
204 displayName,
205 accentColor,
206 continuationGroupKey: continuationIdentity.continuationKey,
207 });
208 const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
209 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
210 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
211 binaryPath: effectiveConfig.binaryPath,
212 env: processEnv,
213 }).pipe(
214 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
215 Effect.provideService(FileSystem.FileSystem, fileSystem),
216 Effect.provideService(Path.Path, pathService),
217 ),
218 );
219​
220 const runtimeProbe = yield* makeOpenCodeRuntimeProbe(
221 probeOpenCodeRuntime(effectiveConfig, processEnv).pipe(
222 Effect.provideService(HttpClient.HttpClient, httpClient),
223 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
224 ),
225 );
226 const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({
227 instanceId,
228 displayName,
229 accentColor,
230 environment,
231 enabled,
232 config,
233 }).pipe(
234 Effect.mapError(
235 (cause) =>
236 new ProviderDriverError({
237 driver: DRIVER_KIND,
238 instanceId,
239 detail: "Failed to build OpenCode orchestration adapter.",
240 cause,
241 }),
242 ),
243 );
244 // One OpenCode 2 server per instance, spawned on first use or reached at `serverUrl`.
245 const openCode2Server = yield* OpenCode2Server.make({
246 binaryPath: effectiveConfig.binaryPath,
247 serverUrl: effectiveConfig.serverUrl,
248 serverPassword: effectiveConfig.serverPassword,
249 directory: serverConfig.cwd,
250 environment: processEnv,
251 }).pipe(
252 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
253 Effect.provideService(
254 OpenCode2Client.OpenCode2Client,
255 yield* OpenCode2Client.make.pipe(
256 Effect.provideService(HttpClient.HttpClient, httpClient),
257 ),
258 ),
259 );
260 const orchestrationAdapter = selectOpenCodeRuntimeAdapter({
261 probe: runtimeProbe,
262 v1: openCodeV1Adapter,
263 v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(
264 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
265 ),
266 });
267 const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(
268 openCode2Server.withConnection((connection) =>
269 connection.client.model.list({ location: { directory: serverConfig.cwd } }).pipe(
270 Effect.map((models) => models.data),
271 Effect.mapError(
272 (cause) =>
273 new OpenCodeRuntime.OpenCodeRuntimeError({
274 operation: "model.list",
275 detail: "The OpenCode server could not list its models.",
276 cause,
277 }),
278 ),
279 ),
280 ),
281 );
282 const serverOwner = yield* OpenCodeServerOwner.make({
283 binaryPath: effectiveConfig.binaryPath,
284 directory: serverConfig.cwd,
285 ...(effectiveConfig.serverPassword
286 ? { serverPassword: effectiveConfig.serverPassword }
287 : {}),
288 environment: processEnv,
289 });
290 const textGeneration = selectOpenCodeRuntimeTextGeneration(
291 runtimeProbe,
292 yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
293 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
294 ),
295 );
296​
297 const checkProvider = Effect.all(
298 {
299 provider: checkOpenCodeProviderStatus(
300 effectiveConfig,
301 serverConfig.cwd,
302 runtimeProbe.refresh,
303 loadOpenCode2Models,
304 ),
305 usageLimits: readOpenCodeGoUsageLimits({
306 enabled: effectiveConfig.enabled,
307 serverUrl: effectiveConfig.serverUrl,
308 environment: processEnv,
309 }),
310 },
311 { concurrency: "unbounded" },
312 ).pipe(
313 Effect.map(({ provider, usageLimits }) => ({ ...provider, usageLimits })),
314 Effect.map(stampIdentity),
315 Effect.provideService(FileSystem.FileSystem, fileSystem),
316 Effect.provideService(Path.Path, pathService),
317 Effect.provideService(HttpClient.HttpClient, httpClient),
318 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
319 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
320 );
321 // NOTE: the local branch intentionally uses the shared SDK server
322 // instead of `opencode debug skill` (loadSkillsFromCli). The CLI writes
323 // its full JSON inventory to stdout, but the Bun-compiled binary does
324 // not flush more than one 64KB pipe buffer to a non-TTY stdout, so the
325 // piped output arrives truncated and unparseable — which degrades to an
326 // empty skill list and poisons the workspace snapshot the `$` picker
327 // reads. The SDK `app.skills` endpoint honors the per-request directory
328 // and returns complete results regardless of size.
329 const loadWorkspaceInventory = (
330 client: Parameters<typeof OpenCodeRuntime.loadOpenCodeCommands>[0],
331 ) =>
332 Effect.all(
333 {
334 skills: openCodeRuntime.loadOpenCodeSkills(client),
335 commands: OpenCodeRuntime.loadOpenCodeCommands(client).pipe(
336 Effect.timeout("10 seconds"),
337 Effect.orElseSucceed(() => []),
338 ),
339 },
340 { concurrency: "unbounded" },
341 );
342 const loadWorkspaceForCwd = (cwd: string) =>
343 effectiveConfig.serverUrl.trim().length > 0
344 ? Effect.scoped(
345 Effect.gen(function* () {
346 const server = yield* openCodeRuntime.connectToOpenCodeServer({
347 binaryPath: effectiveConfig.binaryPath,
348 directory: cwd,
349 serverUrl: effectiveConfig.serverUrl,
350 ...(effectiveConfig.serverPassword
351 ? { serverPassword: effectiveConfig.serverPassword }
352 : {}),
353 environment: processEnv,
354 });
355 const client = openCodeRuntime.createOpenCodeSdkClient({
356 baseUrl: server.url,
357 directory: cwd,
358 ...(effectiveConfig.serverPassword
359 ? { serverPassword: effectiveConfig.serverPassword }
360 : {}),
361 });
362 return yield* loadWorkspaceInventory(client);
363 }),
364 )
365 : serverOwner.withServer((server) =>
366 loadWorkspaceInventory(
367 openCodeRuntime.createOpenCodeSdkClient({
368 baseUrl: server.url,
369 directory: cwd,
370 ...(server.serverPassword !== undefined
371 ? { serverPassword: server.serverPassword }
372 : {}),
373 }),
374 ),
375 );
376​
377 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
378 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
379 {
380 resolveMaintenance,
381 getSettings: snapshotSettings.getSettings,
382 streamSettings: snapshotSettings.streamSettings,
383 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
384 checkProviderOnSettingsChange: () => false,
385 refreshOnInterval: false,
386 initialSnapshot: (settings) =>
387 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
388 checkProvider,
389 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
390 resolveMaintenance().pipe(
391 Effect.flatMap((maintenanceCapabilities) =>
392 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
393 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
394 }),
395 ),
396 Effect.provideService(HttpClient.HttpClient, httpClient),
397 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
398 ),
399 },
400 ).pipe(
401 Effect.mapError(
402 (cause) =>
403 new ProviderDriverError({
404 driver: DRIVER_KIND,
405 instanceId,
406 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
407 cause,
408 }),
409 ),
410 );
411​
412 return {
413 instanceId,
414 driverKind: DRIVER_KIND,
415 continuationIdentity,
416 displayName,
417 accentColor,
418 enabled,
419 snapshot,
420 // OpenCode 2 has no per-workspace skill and command inventory yet, so a
421 // 2.x workspace shows the machine snapshot instead of starting a 1.x server.
422 snapshotForCwd: (cwd) =>
423 !effectiveConfig.enabled
424 ? snapshot.getSnapshot
425 : byOpenCodeRuntime(runtimeProbe.get, {
426 v2: snapshot.getSnapshot,
427 v1: Effect.all([
428 snapshot.getSnapshot,
429 loadWorkspaceForCwd(cwd).pipe(Effect.timeout("20 seconds")),
430 ]).pipe(
431 Effect.map(([machineSnapshot, { skills, commands }]) => ({
432 ...machineSnapshot,
433 skills: openCodeSkillsToServerProviderSkills(skills),
434 slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),
435 })),
436 Effect.mapError(
437 (cause) =>
438 new ProviderDriverError({
439 driver: DRIVER_KIND,
440 instanceId,
441 detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,
442 cause,
443 }),
444 ),
445 ),
446 }),
447 orchestrationAdapter,
448 textGeneration,
449 } satisfies ProviderInstance;
450 }),
451};