Open History to see the last commit
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 } from "@t3tools/contracts";
16import * as Crypto from "effect/Crypto";
17import * as Deferred from "effect/Deferred";
18import * as Effect from "effect/Effect";
19import * as Option from "effect/Option";
20import * as FileSystem from "effect/FileSystem";
21import * as Path from "effect/Path";
22import * as Schema from "effect/Schema";
23import * as Stream from "effect/Stream";
24import { HttpClient } from "effect/http";
25import { ChildProcessSpawner } from "effect/process";
26
27import * as OpenCode2TextGeneration from "../../textGeneration/OpenCode2TextGeneration.ts";
28import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
29import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
30import * as ServerConfig from "../../config.ts";
31import * as OpenCodeAdapterV2 from "../../orchestration-v2/Adapters/OpenCodeAdapterV2.ts";
32import * as OpenCode2AdapterV2 from "../../orchestration-v2/Adapters/OpenCode2AdapterV2.ts";
33import type { ProviderAdapterV2Shape } from "../../orchestration-v2/ProviderAdapter.ts";
34import * as ServerSettings from "../../serverSettings.ts";
35import type { TextGeneration } from "../../textGeneration/TextGeneration.ts";
36import { ProviderDriverError } from "../Errors.ts";
37import { readOpenCodeGoUsageLimits } from "../openCodeUsageLimits.ts";
38import {
39 checkOpenCodeProviderStatus,
40 loadOpenCode2Workspace,
41 makeOpenCode2ModelLoader,
42 makePendingOpenCodeProvider,
43 openCode2CommandsToServerProviderSlashCommands,
44 openCode2SkillsToServerProviderSkills,
45 openCodeSkillsToServerProviderSkills,
46 openCodeCommandsToServerProviderSlashCommands,
47} from "../OpenCodeProvider.ts";
48import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
49import * as OpenCodeRuntime from "../opencodeRuntime.ts";
50import {
51 makeOpenCodeRuntimeProbe,
52 probeOpenCodeRuntime,
53 type ProbedOpenCode,
54} from "../opencodeVersionProbe.ts";
55import * as OpenCodeServerOwner from "../OpenCodeServerOwner.ts";
56import * as OpenCode2Client from "../opencode2/OpenCode2Client.ts";
57import * as OpenCode2Server from "../opencode2/OpenCode2Server.ts";
58import {
59 defaultProviderContinuationIdentity,
60 type ProviderDriver,
61 type ProviderInstance,
62} from "../ProviderDriver.ts";
63import { withInstanceIdentity } from "./instanceIdentity.ts";
64import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
65import {
66 enrichProviderSnapshotWithVersionAdvisory,
67 makeCachedProviderMaintenanceResolution,
68 makeManualOnlyProviderMaintenanceCapabilities,
69 makePackageManagedProviderMaintenanceResolver,
70 normalizeCommandPath,
71 resolveProviderMaintenanceCapabilitiesEffect,
72} from "../providerMaintenance.ts";
73import {
74 haveProviderSnapshotSettingsChanged,
75 makeProviderSnapshotSettingsSource,
76 type ProviderSnapshotSettings,
77} from "../providerUpdateSettings.ts";
78const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
79
80const DRIVER_KIND = ProviderDriverKind.make("opencode");
81
82function isOpenCodeNativeCommandPath(commandPath: string): boolean {
83 const normalized = normalizeCommandPath(commandPath);
84 return (
85 normalized.endsWith("/.opencode/bin/opencode") ||
86 normalized.endsWith("/.opencode/bin/opencode.exe")
87 );
88}
89
90/**
91 * OpenCode 1.x ships as `opencode-ai` and 2.x as `@opencode/cli`. An install is
92 * only ever updated within its own package: T3 never moves a 1.x install onto
93 * 2.x or back, since 2.x converts the shared database in place.
94 */
95export const openCodeUpdateFor = (generation: ProbedOpenCode["generation"]) =>
96 makePackageManagedProviderMaintenanceResolver({
97 provider: DRIVER_KIND,
98 npmPackageName: generation === "v2" ? "@opencode/cli" : "opencode-ai",
99 nativeUpdate: {
100 args: ["upgrade"],
101 isCommandPath: isOpenCodeNativeCommandPath,
102 },
103 });
104
105type OpenCodeRuntimeProbe = Effect.Success<
106 ReturnType<typeof makeOpenCodeRuntimeProbe<OpenCodeRuntime.OpenCodeRuntimeError>>
107>;
108
109/** Runs `v2` for a 2.x instance and `v1` otherwise; a failed probe keeps 1.x, whose checks report it. */
110function byOpenCodeRuntime<A, E, R, PE>(
111 probed: Effect.Effect<ProbedOpenCode | undefined, PE>,
112 paths: { readonly v1: Effect.Effect<A, E, R>; readonly v2: Effect.Effect<A, E, R> },
113): Effect.Effect<A, E, R> {
114 return probed.pipe(
115 Effect.orElseSucceed(() => undefined),
116 Effect.flatMap((result) => (result?.generation === "v2" ? paths.v2 : paths.v1)),
117 );
118}
119
120/**
121 * Routes each adapter call to the runtime the instance's probe detected. Capability and selection
122 * reads are hot, so they use the last successful probe (1.x before one lands) and never wait on a
123 * slow server. Opening a session waits for a probe, so each server is spoken to in its own protocol.
124 */
125function selectOpenCodeRuntimeAdapter(input: {
126 readonly probe: OpenCodeRuntimeProbe;
127 readonly v1: ProviderAdapterV2Shape;
128 readonly v2: ProviderAdapterV2Shape;
129}): ProviderAdapterV2Shape {
130 const pick = <PE>(probed: Effect.Effect<ProbedOpenCode | undefined, PE>) =>
131 byOpenCodeRuntime(probed, { v1: Effect.succeed(input.v1), v2: Effect.succeed(input.v2) });
132 const hot = pick(Effect.map(input.probe.lastSuccess, Option.getOrUndefined));
133 return {
134 instanceId: input.v1.instanceId,
135 driver: DRIVER_KIND,
136 getCapabilities: () => Effect.flatMap(hot, (adapter) => adapter.getCapabilities()),
137 planSelectionTransition: (transition) =>
138 Effect.flatMap(hot, (adapter) => adapter.planSelectionTransition(transition)),
139 openSession: (session) =>
140 Effect.flatMap(pick(input.probe.get), (adapter) => adapter.openSession(session)),
141 };
142}
143
144/** Text generation runs on the server the instance's probe detected, each in its own protocol. */
145function selectOpenCodeRuntimeTextGeneration(
146 probe: OpenCodeRuntimeProbe,
147 v1: TextGeneration["Service"],
148 v2: TextGeneration["Service"],
149): TextGeneration["Service"] {
150 return {
151 generateCommitMessage: (input) =>
152 byOpenCodeRuntime(probe.get, {
153 v1: v1.generateCommitMessage(input),
154 v2: v2.generateCommitMessage(input),
155 }),
156 generatePrContent: (input) =>
157 byOpenCodeRuntime(probe.get, {
158 v1: v1.generatePrContent(input),
159 v2: v2.generatePrContent(input),
160 }),
161 generateBranchName: (input) =>
162 byOpenCodeRuntime(probe.get, {
163 v1: v1.generateBranchName(input),
164 v2: v2.generateBranchName(input),
165 }),
166 generateThreadTitle: (input) =>
167 byOpenCodeRuntime(probe.get, {
168 v1: v1.generateThreadTitle(input),
169 v2: v2.generateThreadTitle(input),
170 }),
171 };
172}
173
174export type OpenCodeDriverEnv =
175 | OpenCodeAdapterV2.OpenCodeAdapterV2DriverEnv
176 | BackgroundPolicy.BackgroundPolicy
177 | ChildProcessSpawner.ChildProcessSpawner
178 | Crypto.Crypto
179 | FileSystem.FileSystem
180 | HttpClient.HttpClient
181 | OpenCodeRuntime.OpenCodeRuntime
182 | Path.Path
183 | ServerConfig.ServerConfig
184 | ServerSettings.ServerSettingsService;
185
186export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv> = {
187 driverKind: DRIVER_KIND,
188 metadata: {
189 displayName: "OpenCode",
190 supportsMultipleInstances: true,
191 },
192 configSchema: OpenCodeSettings,
193 defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
194 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
195 Effect.gen(function* () {
196 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
197 const fileSystem = yield* FileSystem.FileSystem;
198 const pathService = yield* Path.Path;
199 const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
200 const serverConfig = yield* ServerConfig.ServerConfig;
201 const httpClient = yield* HttpClient.HttpClient;
202 const crypto = yield* Crypto.Crypto;
203 const serverSettings = yield* ServerSettings.ServerSettingsService;
204 const processEnv = mergeProviderInstanceEnvironment(environment);
205 const continuationIdentity = defaultProviderContinuationIdentity({
206 driverKind: DRIVER_KIND,
207 instanceId,
208 });
209 const stampIdentity = withInstanceIdentity({
210 instanceId,
211 driverKind: DRIVER_KIND,
212 displayName,
213 accentColor,
214 continuationGroupKey: continuationIdentity.continuationKey,
215 });
216 const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
217 const runtimeProbe = yield* makeOpenCodeRuntimeProbe(
218 probeOpenCodeRuntime(effectiveConfig, processEnv).pipe(
219 Effect.provideService(HttpClient.HttpClient, httpClient),
220 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
221 ),
222 );
223 // Updates follow the installed package, which the version probe names. An
224 // unknown version offers no package update, since a guess could move a
225 // 2.x install onto 1.x's package or the reverse. A disabled instance never
226 // runs its binary, so it has no version and offers no update.
227 const noUpdate = makeManualOnlyProviderMaintenanceCapabilities({
228 provider: DRIVER_KIND,
229 packageName: null,
230 });
231 const maintenanceFor = (probed: typeof runtimeProbe.get) =>
232 probed.pipe(
233 Effect.map((result) => result.generation),
234 Effect.option,
235 Effect.flatMap((generation) =>
236 Option.isNone(generation)
237 ? Effect.succeed(noUpdate)
238 : resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation.value), {
239 binaryPath: effectiveConfig.binaryPath,
240 env: processEnv,
241 }),
242 ),
243 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
244 Effect.provideService(FileSystem.FileSystem, fileSystem),
245 Effect.provideService(Path.Path, pathService),
246 );
247 const cachedMaintenance = yield* makeCachedProviderMaintenanceResolution(
248 maintenanceFor(runtimeProbe.get),
249 );
250 // A fresh read (an update about to run, or a manual refresh) re-probes, so
251 // a binary replaced by the other major version gets its own package.
252 const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>
253 !effectiveConfig.enabled
254 ? Effect.succeed(noUpdate)
255 : options?.fresh === true
256 ? runtimeProbe.refresh.pipe(
257 Effect.ignore,
258 Effect.andThen(cachedMaintenance({ fresh: true })),
259 )
260 : cachedMaintenance();
261 const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({
262 instanceId,
263 displayName,
264 accentColor,
265 environment,
266 enabled,
267 config,
268 }).pipe(
269 Effect.mapError(
270 (cause) =>
271 new ProviderDriverError({
272 driver: DRIVER_KIND,
273 instanceId,
274 detail: "Failed to build OpenCode orchestration adapter.",
275 cause,
276 }),
277 ),
278 );
279 // One OpenCode 2 server per instance, spawned on first use or reached at `serverUrl`.
280 const openCode2Server = yield* OpenCode2Server.make({
281 binaryPath: effectiveConfig.binaryPath,
282 serverUrl: effectiveConfig.serverUrl,
283 serverPassword: effectiveConfig.serverPassword,
284 directory: serverConfig.cwd,
285 environment: processEnv,
286 }).pipe(
287 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
288 Effect.provideService(
289 OpenCode2Client.OpenCode2Client,
290 yield* OpenCode2Client.make.pipe(
291 Effect.provideService(HttpClient.HttpClient, httpClient),
292 ),
293 ),
294 );
295 const orchestrationAdapter = selectOpenCodeRuntimeAdapter({
296 probe: runtimeProbe,
297 v1: openCodeV1Adapter,
298 v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(
299 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
300 ),
301 });
302 const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(
303 openCode2Server.withConnection((connection) =>
304 connection.client.model.list({ location: { directory: serverConfig.cwd } }).pipe(
305 Effect.map((models) => models.data),
306 Effect.mapError(
307 (cause) =>
308 new OpenCodeRuntime.OpenCodeRuntimeError({
309 operation: "model.list",
310 detail: "The OpenCode server could not list its models.",
311 cause,
312 }),
313 ),
314 ),
315 ),
316 );
317 // A 2.x server lists skills and commands per directory, so one server
318 // answers every workspace. Its event stream says when a directory it had
319 // not served yet finished scanning.
320 const listOpenCode2Workspace = (cwd: string) =>
321 openCode2Server.withConnection(({ client, events }) =>
322 Effect.gen(function* () {
323 const location = { directory: cwd };
324 const scanned = yield* Deferred.make<void>();
325 const pending = new Set(["command.updated", "skill.updated"]);
326 const stream = yield* events.pipe(Effect.option);
327 if (stream._tag === "Some") {
328 yield* stream.value.pipe(
329 Stream.runForEach((event) =>
330 "location" in event &&
331 event.location?.directory === cwd &&
332 pending.delete(event.type) &&
333 pending.size === 0
334 ? Deferred.succeed(scanned, undefined)
335 : Effect.void,
336 ),
337 Effect.ignore,
338 Effect.forkScoped,
339 );
340 }
341 return yield* loadOpenCode2Workspace(
342 Effect.all(
343 {
344 skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)),
345 commands: client.command.list({ location }).pipe(Effect.map((list) => list.data)),
346 },
347 { concurrency: "unbounded" },
348 ),
349 Deferred.await(scanned),
350 );
351 }).pipe(Effect.scoped),
352 );
353 const serverOwner = yield* OpenCodeServerOwner.make({
354 binaryPath: effectiveConfig.binaryPath,
355 directory: serverConfig.cwd,
356 ...(effectiveConfig.serverPassword
357 ? { serverPassword: effectiveConfig.serverPassword }
358 : {}),
359 environment: processEnv,
360 });
361 const textGeneration = selectOpenCodeRuntimeTextGeneration(
362 runtimeProbe,
363 yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
364 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
365 ),
366 yield* OpenCode2TextGeneration.make().pipe(
367 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
368 ),
369 );
370
371 const checkProvider = Effect.all(
372 {
373 provider: checkOpenCodeProviderStatus(
374 effectiveConfig,
375 serverConfig.cwd,
376 runtimeProbe.refresh,
377 loadOpenCode2Models,
378 ),
379 usageLimits: readOpenCodeGoUsageLimits({
380 enabled: effectiveConfig.enabled,
381 serverUrl: effectiveConfig.serverUrl,
382 environment: processEnv,
383 }),
384 },
385 { concurrency: "unbounded" },
386 ).pipe(
387 Effect.map(({ provider, usageLimits }) => ({ ...provider, usageLimits })),
388 Effect.map(stampIdentity),
389 Effect.provideService(FileSystem.FileSystem, fileSystem),
390 Effect.provideService(Path.Path, pathService),
391 Effect.provideService(HttpClient.HttpClient, httpClient),
392 Effect.provideService(Crypto.Crypto, crypto),
393 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
394 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
395 );
396 // NOTE: the local branch intentionally uses the shared SDK server
397 // instead of `opencode debug skill` (loadSkillsFromCli). The CLI writes
398 // its full JSON inventory to stdout, but the Bun-compiled binary does
399 // not flush more than one 64KB pipe buffer to a non-TTY stdout, so the
400 // piped output arrives truncated and unparseable — which degrades to an
401 // empty skill list and poisons the workspace snapshot the `$` picker
402 // reads. The SDK `app.skills` endpoint honors the per-request directory
403 // and returns complete results regardless of size.
404 const loadWorkspaceInventory = (
405 client: Parameters<typeof OpenCodeRuntime.loadOpenCodeCommands>[0],
406 ) =>
407 Effect.all(
408 {
409 skills: openCodeRuntime.loadOpenCodeSkills(client),
410 commands: OpenCodeRuntime.loadOpenCodeCommands(client).pipe(
411 Effect.timeout("10 seconds"),
412 Effect.orElseSucceed(() => []),
413 ),
414 },
415 { concurrency: "unbounded" },
416 );
417 const loadWorkspaceForCwd = (cwd: string) =>
418 effectiveConfig.serverUrl.trim().length > 0
419 ? Effect.scoped(
420 Effect.gen(function* () {
421 const server = yield* openCodeRuntime.connectToOpenCodeServer({
422 binaryPath: effectiveConfig.binaryPath,
423 directory: cwd,
424 serverUrl: effectiveConfig.serverUrl,
425 ...(effectiveConfig.serverPassword
426 ? { serverPassword: effectiveConfig.serverPassword }
427 : {}),
428 environment: processEnv,
429 });
430 const client = openCodeRuntime.createOpenCodeSdkClient({
431 baseUrl: server.url,
432 directory: cwd,
433 ...(effectiveConfig.serverPassword
434 ? { serverPassword: effectiveConfig.serverPassword }
435 : {}),
436 });
437 return yield* loadWorkspaceInventory(client);
438 }),
439 )
440 : serverOwner.withServer((server) =>
441 loadWorkspaceInventory(
442 openCodeRuntime.createOpenCodeSdkClient({
443 baseUrl: server.url,
444 directory: cwd,
445 ...(server.serverPassword !== undefined
446 ? { serverPassword: server.serverPassword }
447 : {}),
448 }),
449 ),
450 );
451
452 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
453 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
454 {
455 resolveMaintenance,
456 getSettings: snapshotSettings.getSettings,
457 streamSettings: snapshotSettings.streamSettings,
458 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
459 checkProviderOnSettingsChange: () => false,
460 refreshOnInterval: false,
461 initialSnapshot: (settings) =>
462 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
463 checkProvider,
464 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
465 resolveMaintenance().pipe(
466 Effect.flatMap((maintenanceCapabilities) =>
467 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
468 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
469 }),
470 ),
471 Effect.provideService(HttpClient.HttpClient, httpClient),
472 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
473 ),
474 },
475 ).pipe(
476 Effect.mapError(
477 (cause) =>
478 new ProviderDriverError({
479 driver: DRIVER_KIND,
480 instanceId,
481 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
482 cause,
483 }),
484 ),
485 );
486
487 return {
488 instanceId,
489 driverKind: DRIVER_KIND,
490 continuationIdentity,
491 displayName,
492 accentColor,
493 enabled,
494 snapshot,
495 snapshotForCwd: (cwd) =>
496 !effectiveConfig.enabled
497 ? snapshot.getSnapshot
498 : byOpenCodeRuntime(runtimeProbe.get, {
499 v2: Effect.all([
500 snapshot.getSnapshot,
501 listOpenCode2Workspace(cwd).pipe(
502 Effect.timeout("20 seconds"),
503 Effect.mapError(
504 (cause) =>
505 new ProviderDriverError({
506 driver: DRIVER_KIND,
507 instanceId,
508 detail: `Failed to list OpenCode commands and skills for '${cwd}'`,
509 cause,
510 }),
511 ),
512 ),
513 ]).pipe(
514 Effect.map(([machineSnapshot, { skills, commands }]) => ({
515 ...machineSnapshot,
516 skills: openCode2SkillsToServerProviderSkills(skills),
517 slashCommands: openCode2CommandsToServerProviderSlashCommands(commands),
518 })),
519 ),
520 v1: Effect.all([
521 snapshot.getSnapshot,
522 loadWorkspaceForCwd(cwd).pipe(Effect.timeout("20 seconds")),
523 ]).pipe(
524 Effect.map(([machineSnapshot, { skills, commands }]) => ({
525 ...machineSnapshot,
526 skills: openCodeSkillsToServerProviderSkills(skills),
527 slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),
528 })),
529 Effect.mapError(
530 (cause) =>
531 new ProviderDriverError({
532 driver: DRIVER_KIND,
533 instanceId,
534 detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,
535 cause,
536 }),
537 ),
538 ),
539 }),
540 orchestrationAdapter,
541 textGeneration,
542 } satisfies ProviderInstance;
543 }),
544};