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/unstable/http";
25import { ChildProcessSpawner } from "effect/unstable/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 "../Layers/openCodeUsageLimits.ts";
38import {
39 checkOpenCodeProviderStatus,
40 loadOpenCode2Workspace,
41 makeOpenCode2ModelLoader,
42 makePendingOpenCodeProvider,
43 openCode2CommandsToServerProviderSlashCommands,
44 openCode2SkillsToServerProviderSkills,
45 openCodeSkillsToServerProviderSkills,
46 openCodeCommandsToServerProviderSlashCommands,
47} from "../Layers/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 serverSettings = yield* ServerSettings.ServerSettingsService;
203 const processEnv = mergeProviderInstanceEnvironment(environment);
204 const continuationIdentity = defaultProviderContinuationIdentity({
205 driverKind: DRIVER_KIND,
206 instanceId,
207 });
208 const stampIdentity = withInstanceIdentity({
209 instanceId,
210 driverKind: DRIVER_KIND,
211 displayName,
212 accentColor,
213 continuationGroupKey: continuationIdentity.continuationKey,
214 });
215 const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
216 const runtimeProbe = yield* makeOpenCodeRuntimeProbe(
217 probeOpenCodeRuntime(effectiveConfig, processEnv).pipe(
218 Effect.provideService(HttpClient.HttpClient, httpClient),
219 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
220 ),
221 );
222 // Updates follow the installed package, which the version probe names. An
223 // unknown version offers no package update, since a guess could move a
224 // 2.x install onto 1.x's package or the reverse. A disabled instance never
225 // runs its binary, so it has no version and offers no update.
226 const noUpdate = makeManualOnlyProviderMaintenanceCapabilities({
227 provider: DRIVER_KIND,
228 packageName: null,
229 });
230 const maintenanceFor = (probed: typeof runtimeProbe.get) =>
231 probed.pipe(
232 Effect.map((result) => result.generation),
233 Effect.option,
234 Effect.flatMap((generation) =>
235 Option.isNone(generation)
236 ? Effect.succeed(noUpdate)
237 : resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation.value), {
238 binaryPath: effectiveConfig.binaryPath,
239 env: processEnv,
240 }),
241 ),
242 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
243 Effect.provideService(FileSystem.FileSystem, fileSystem),
244 Effect.provideService(Path.Path, pathService),
245 );
246 const cachedMaintenance = yield* makeCachedProviderMaintenanceResolution(
247 maintenanceFor(runtimeProbe.get),
248 );
249 // A fresh read (an update about to run, or a manual refresh) re-probes, so
250 // a binary replaced by the other major version gets its own package.
251 const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>
252 !effectiveConfig.enabled
253 ? Effect.succeed(noUpdate)
254 : options?.fresh === true
255 ? runtimeProbe.refresh.pipe(
256 Effect.ignore,
257 Effect.andThen(cachedMaintenance({ fresh: true })),
258 )
259 : cachedMaintenance();
260 const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({
261 instanceId,
262 displayName,
263 accentColor,
264 environment,
265 enabled,
266 config,
267 }).pipe(
268 Effect.mapError(
269 (cause) =>
270 new ProviderDriverError({
271 driver: DRIVER_KIND,
272 instanceId,
273 detail: "Failed to build OpenCode orchestration adapter.",
274 cause,
275 }),
276 ),
277 );
278 // One OpenCode 2 server per instance, spawned on first use or reached at `serverUrl`.
279 const openCode2Server = yield* OpenCode2Server.make({
280 binaryPath: effectiveConfig.binaryPath,
281 serverUrl: effectiveConfig.serverUrl,
282 serverPassword: effectiveConfig.serverPassword,
283 directory: serverConfig.cwd,
284 environment: processEnv,
285 }).pipe(
286 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
287 Effect.provideService(
288 OpenCode2Client.OpenCode2Client,
289 yield* OpenCode2Client.make.pipe(
290 Effect.provideService(HttpClient.HttpClient, httpClient),
291 ),
292 ),
293 );
294 const orchestrationAdapter = selectOpenCodeRuntimeAdapter({
295 probe: runtimeProbe,
296 v1: openCodeV1Adapter,
297 v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(
298 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
299 ),
300 });
301 const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(
302 openCode2Server.withConnection((connection) =>
303 connection.client.model.list({ location: { directory: serverConfig.cwd } }).pipe(
304 Effect.map((models) => models.data),
305 Effect.mapError(
306 (cause) =>
307 new OpenCodeRuntime.OpenCodeRuntimeError({
308 operation: "model.list",
309 detail: "The OpenCode server could not list its models.",
310 cause,
311 }),
312 ),
313 ),
314 ),
315 );
316 // A 2.x server lists skills and commands per directory, so one server
317 // answers every workspace. Its event stream says when a directory it had
318 // not served yet finished scanning.
319 const listOpenCode2Workspace = (cwd: string) =>
320 openCode2Server.withConnection(({ client, events }) =>
321 Effect.gen(function* () {
322 const location = { directory: cwd };
323 const scanned = yield* Deferred.make<void>();
324 const pending = new Set(["command.updated", "skill.updated"]);
325 const stream = yield* events.pipe(Effect.option);
326 if (stream._tag === "Some") {
327 yield* stream.value.pipe(
328 Stream.runForEach((event) =>
329 "location" in event &&
330 event.location?.directory === cwd &&
331 pending.delete(event.type) &&
332 pending.size === 0
333 ? Deferred.succeed(scanned, undefined)
334 : Effect.void,
335 ),
336 Effect.ignore,
337 Effect.forkScoped,
338 );
339 }
340 return yield* loadOpenCode2Workspace(
341 Effect.all(
342 {
343 skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)),
344 commands: client.command.list({ location }).pipe(Effect.map((list) => list.data)),
345 },
346 { concurrency: "unbounded" },
347 ),
348 Deferred.await(scanned),
349 );
350 }).pipe(Effect.scoped),
351 );
352 const serverOwner = yield* OpenCodeServerOwner.make({
353 binaryPath: effectiveConfig.binaryPath,
354 directory: serverConfig.cwd,
355 ...(effectiveConfig.serverPassword
356 ? { serverPassword: effectiveConfig.serverPassword }
357 : {}),
358 environment: processEnv,
359 });
360 const textGeneration = selectOpenCodeRuntimeTextGeneration(
361 runtimeProbe,
362 yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
363 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
364 ),
365 yield* OpenCode2TextGeneration.make().pipe(
366 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
367 ),
368 );
369
370 const checkProvider = Effect.all(
371 {
372 provider: checkOpenCodeProviderStatus(
373 effectiveConfig,
374 serverConfig.cwd,
375 runtimeProbe.refresh,
376 loadOpenCode2Models,
377 ),
378 usageLimits: readOpenCodeGoUsageLimits({
379 enabled: effectiveConfig.enabled,
380 serverUrl: effectiveConfig.serverUrl,
381 environment: processEnv,
382 }),
383 },
384 { concurrency: "unbounded" },
385 ).pipe(
386 Effect.map(({ provider, usageLimits }) => ({ ...provider, usageLimits })),
387 Effect.map(stampIdentity),
388 Effect.provideService(FileSystem.FileSystem, fileSystem),
389 Effect.provideService(Path.Path, pathService),
390 Effect.provideService(HttpClient.HttpClient, httpClient),
391 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
392 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
393 );
394 // NOTE: the local branch intentionally uses the shared SDK server
395 // instead of `opencode debug skill` (loadSkillsFromCli). The CLI writes
396 // its full JSON inventory to stdout, but the Bun-compiled binary does
397 // not flush more than one 64KB pipe buffer to a non-TTY stdout, so the
398 // piped output arrives truncated and unparseable — which degrades to an
399 // empty skill list and poisons the workspace snapshot the `$` picker
400 // reads. The SDK `app.skills` endpoint honors the per-request directory
401 // and returns complete results regardless of size.
402 const loadWorkspaceInventory = (
403 client: Parameters<typeof OpenCodeRuntime.loadOpenCodeCommands>[0],
404 ) =>
405 Effect.all(
406 {
407 skills: openCodeRuntime.loadOpenCodeSkills(client),
408 commands: OpenCodeRuntime.loadOpenCodeCommands(client).pipe(
409 Effect.timeout("10 seconds"),
410 Effect.orElseSucceed(() => []),
411 ),
412 },
413 { concurrency: "unbounded" },
414 );
415 const loadWorkspaceForCwd = (cwd: string) =>
416 effectiveConfig.serverUrl.trim().length > 0
417 ? Effect.scoped(
418 Effect.gen(function* () {
419 const server = yield* openCodeRuntime.connectToOpenCodeServer({
420 binaryPath: effectiveConfig.binaryPath,
421 directory: cwd,
422 serverUrl: effectiveConfig.serverUrl,
423 ...(effectiveConfig.serverPassword
424 ? { serverPassword: effectiveConfig.serverPassword }
425 : {}),
426 environment: processEnv,
427 });
428 const client = openCodeRuntime.createOpenCodeSdkClient({
429 baseUrl: server.url,
430 directory: cwd,
431 ...(effectiveConfig.serverPassword
432 ? { serverPassword: effectiveConfig.serverPassword }
433 : {}),
434 });
435 return yield* loadWorkspaceInventory(client);
436 }),
437 )
438 : serverOwner.withServer((server) =>
439 loadWorkspaceInventory(
440 openCodeRuntime.createOpenCodeSdkClient({
441 baseUrl: server.url,
442 directory: cwd,
443 ...(server.serverPassword !== undefined
444 ? { serverPassword: server.serverPassword }
445 : {}),
446 }),
447 ),
448 );
449
450 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
451 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
452 {
453 resolveMaintenance,
454 getSettings: snapshotSettings.getSettings,
455 streamSettings: snapshotSettings.streamSettings,
456 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
457 checkProviderOnSettingsChange: () => false,
458 refreshOnInterval: false,
459 initialSnapshot: (settings) =>
460 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
461 checkProvider,
462 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
463 resolveMaintenance().pipe(
464 Effect.flatMap((maintenanceCapabilities) =>
465 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
466 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
467 }),
468 ),
469 Effect.provideService(HttpClient.HttpClient, httpClient),
470 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
471 ),
472 },
473 ).pipe(
474 Effect.mapError(
475 (cause) =>
476 new ProviderDriverError({
477 driver: DRIVER_KIND,
478 instanceId,
479 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
480 cause,
481 }),
482 ),
483 );
484
485 return {
486 instanceId,
487 driverKind: DRIVER_KIND,
488 continuationIdentity,
489 displayName,
490 accentColor,
491 enabled,
492 snapshot,
493 snapshotForCwd: (cwd) =>
494 !effectiveConfig.enabled
495 ? snapshot.getSnapshot
496 : byOpenCodeRuntime(runtimeProbe.get, {
497 v2: Effect.all([
498 snapshot.getSnapshot,
499 listOpenCode2Workspace(cwd).pipe(
500 Effect.timeout("20 seconds"),
501 Effect.mapError(
502 (cause) =>
503 new ProviderDriverError({
504 driver: DRIVER_KIND,
505 instanceId,
506 detail: `Failed to list OpenCode commands and skills for '${cwd}'`,
507 cause,
508 }),
509 ),
510 ),
511 ]).pipe(
512 Effect.map(([machineSnapshot, { skills, commands }]) => ({
513 ...machineSnapshot,
514 skills: openCode2SkillsToServerProviderSkills(skills),
515 slashCommands: openCode2CommandsToServerProviderSlashCommands(commands),
516 })),
517 ),
518 v1: Effect.all([
519 snapshot.getSnapshot,
520 loadWorkspaceForCwd(cwd).pipe(Effect.timeout("20 seconds")),
521 ]).pipe(
522 Effect.map(([machineSnapshot, { skills, commands }]) => ({
523 ...machineSnapshot,
524 skills: openCodeSkillsToServerProviderSkills(skills),
525 slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),
526 })),
527 Effect.mapError(
528 (cause) =>
529 new ProviderDriverError({
530 driver: DRIVER_KIND,
531 instanceId,
532 detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,
533 cause,
534 }),
535 ),
536 ),
537 }),
538 orchestrationAdapter,
539 textGeneration,
540 } satisfies ProviderInstance;
541 }),
542};