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

OpenCodeDriver.ts

542 lines22.2 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 } 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 { ProviderHost } from "@t3tools/provider-core/server/ProviderHost";
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 "@t3tools/provider-core/server/ProviderAdapter";
34import type { TextGeneration } from "../../textGeneration/TextGeneration.ts";
35import { ProviderDriverError } from "../Errors.ts";
36import { readOpenCodeGoUsageLimits } from "../openCodeUsageLimits.ts";
37import {
38 checkOpenCodeProviderStatus,
39 loadOpenCode2Workspace,
40 makeOpenCode2ModelLoader,
41 makePendingOpenCodeProvider,
42 openCode2CommandsToServerProviderSlashCommands,
43 openCode2SkillsToServerProviderSkills,
44 openCodeSkillsToServerProviderSkills,
45 openCodeCommandsToServerProviderSlashCommands,
46} from "../OpenCodeProvider.ts";
47import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
48import * as OpenCodeRuntime from "../opencodeRuntime.ts";
49import {
50 makeOpenCodeRuntimeProbe,
51 probeOpenCodeRuntime,
52 type ProbedOpenCode,
53} from "../opencodeVersionProbe.ts";
54import * as OpenCodeServerOwner from "../OpenCodeServerOwner.ts";
55import * as OpenCode2Client from "../opencode2/OpenCode2Client.ts";
56import * as OpenCode2Server from "../opencode2/OpenCode2Server.ts";
57import {
58 defaultProviderContinuationIdentity,
59 type ProviderDriver,
60 type ProviderInstance,
61} from "@t3tools/provider-core/server/driver";
62import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
63import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
64import {
65 enrichProviderSnapshotWithVersionAdvisory,
66 makeCachedProviderMaintenanceResolution,
67 makeManualOnlyProviderMaintenanceCapabilities,
68 makePackageManagedProviderMaintenanceResolver,
69 normalizeCommandPath,
70 resolveProviderMaintenanceCapabilitiesEffect,
71} from "@t3tools/provider-core/server/maintenanceResolver";
72import {
73 haveProviderSnapshotSettingsChanged,
74 makeProviderSnapshotSettingsSource,
75 type ProviderSnapshotSettings,
76} from "@t3tools/provider-core/server/snapshotSettings";
77const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
78​
79const DRIVER_KIND = ProviderDriverKind.make("opencode");
80​
81function isOpenCodeNativeCommandPath(commandPath: string): boolean {
82 const normalized = normalizeCommandPath(commandPath);
83 return (
84 normalized.endsWith("/.opencode/bin/opencode") ||
85 normalized.endsWith("/.opencode/bin/opencode.exe")
86 );
88​
89/**
90 * OpenCode 1.x ships as `opencode-ai` and 2.x as `@opencode/cli`. An install is
91 * only ever updated within its own package: T3 never moves a 1.x install onto
92 * 2.x or back, since 2.x converts the shared database in place.
93 */
94export const openCodeUpdateFor = (generation: ProbedOpenCode["generation"]) =>
95 makePackageManagedProviderMaintenanceResolver({
96 provider: DRIVER_KIND,
97 npmPackageName: generation === "v2" ? "@opencode/cli" : "opencode-ai",
98 nativeUpdate: {
99 args: ["upgrade"],
100 isCommandPath: isOpenCodeNativeCommandPath,
101 },
102 });
103​
104type OpenCodeRuntimeProbe = Effect.Success<
105 ReturnType<typeof makeOpenCodeRuntimeProbe<OpenCodeRuntime.OpenCodeRuntimeError>>
106>;
107​
108/** Runs `v2` for a 2.x instance and `v1` otherwise; a failed probe keeps 1.x, whose checks report it. */
109function byOpenCodeRuntime<A, E, R, PE>(
110 probed: Effect.Effect<ProbedOpenCode | undefined, PE>,
111 paths: { readonly v1: Effect.Effect<A, E, R>; readonly v2: Effect.Effect<A, E, R> },
112): Effect.Effect<A, E, R> {
113 return probed.pipe(
114 Effect.orElseSucceed(() => undefined),
115 Effect.flatMap((result) => (result?.generation === "v2" ? paths.v2 : paths.v1)),
116 );
118​
119/**
120 * Routes each adapter call to the runtime the instance's probe detected. Capability and selection
121 * reads are hot, so they use the last successful probe (1.x before one lands) and never wait on a
122 * slow server. Opening a session waits for a probe, so each server is spoken to in its own protocol.
123 */
124function selectOpenCodeRuntimeAdapter(input: {
125 readonly probe: OpenCodeRuntimeProbe;
126 readonly v1: ProviderAdapterV2Shape;
127 readonly v2: ProviderAdapterV2Shape;
128}): ProviderAdapterV2Shape {
129 const pick = <PE>(probed: Effect.Effect<ProbedOpenCode | undefined, PE>) =>
130 byOpenCodeRuntime(probed, { v1: Effect.succeed(input.v1), v2: Effect.succeed(input.v2) });
131 const hot = pick(Effect.map(input.probe.lastSuccess, Option.getOrUndefined));
132 return {
133 instanceId: input.v1.instanceId,
134 driver: DRIVER_KIND,
135 getCapabilities: () => Effect.flatMap(hot, (adapter) => adapter.getCapabilities()),
136 planSelectionTransition: (transition) =>
137 Effect.flatMap(hot, (adapter) => adapter.planSelectionTransition(transition)),
138 openSession: (session) =>
139 Effect.flatMap(pick(input.probe.get), (adapter) => adapter.openSession(session)),
140 };
142​
143/** Text generation runs on the server the instance's probe detected, each in its own protocol. */
144function selectOpenCodeRuntimeTextGeneration(
145 probe: OpenCodeRuntimeProbe,
146 v1: TextGeneration["Service"],
147 v2: TextGeneration["Service"],
148): TextGeneration["Service"] {
149 return {
150 generateCommitMessage: (input) =>
151 byOpenCodeRuntime(probe.get, {
152 v1: v1.generateCommitMessage(input),
153 v2: v2.generateCommitMessage(input),
154 }),
155 generatePrContent: (input) =>
156 byOpenCodeRuntime(probe.get, {
157 v1: v1.generatePrContent(input),
158 v2: v2.generatePrContent(input),
159 }),
160 generateBranchName: (input) =>
161 byOpenCodeRuntime(probe.get, {
162 v1: v1.generateBranchName(input),
163 v2: v2.generateBranchName(input),
164 }),
165 generateThreadTitle: (input) =>
166 byOpenCodeRuntime(probe.get, {
167 v1: v1.generateThreadTitle(input),
168 v2: v2.generateThreadTitle(input),
169 }),
170 };
172​
173export type OpenCodeDriverEnv =
174 | OpenCodeAdapterV2.OpenCodeAdapterV2DriverEnv
175 | ProviderHost
176 | ChildProcessSpawner.ChildProcessSpawner
177 | Crypto.Crypto
178 | FileSystem.FileSystem
179 | HttpClient.HttpClient
180 | OpenCodeRuntime.OpenCodeRuntime
181 | Path.Path
182 | ServerConfig.ServerConfig;
183​
184export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv> = {
185 driverKind: DRIVER_KIND,
186 metadata: {
187 displayName: "OpenCode",
188 supportsMultipleInstances: true,
189 },
190 configSchema: OpenCodeSettings,
191 defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
192 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
193 Effect.gen(function* () {
194 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
195 const fileSystem = yield* FileSystem.FileSystem;
196 const pathService = yield* Path.Path;
197 const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
198 const serverConfig = yield* ServerConfig.ServerConfig;
199 const httpClient = yield* HttpClient.HttpClient;
200 const crypto = yield* Crypto.Crypto;
201 const host = yield* ProviderHost;
202 const processEnv = mergeProviderInstanceEnvironment(environment);
203 const continuationIdentity = defaultProviderContinuationIdentity({
204 driverKind: DRIVER_KIND,
205 instanceId,
206 });
207 const stampIdentity = withInstanceIdentity({
208 instanceId,
209 driverKind: DRIVER_KIND,
210 displayName,
211 accentColor,
212 continuationGroupKey: continuationIdentity.continuationKey,
213 });
214 const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
215 const runtimeProbe = yield* makeOpenCodeRuntimeProbe(
216 probeOpenCodeRuntime(effectiveConfig, processEnv).pipe(
217 Effect.provideService(HttpClient.HttpClient, httpClient),
218 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
219 ),
220 );
221 // Updates follow the installed package, which the version probe names. An
222 // unknown version offers no package update, since a guess could move a
223 // 2.x install onto 1.x's package or the reverse. A disabled instance never
224 // runs its binary, so it has no version and offers no update.
225 const noUpdate = makeManualOnlyProviderMaintenanceCapabilities({
226 provider: DRIVER_KIND,
227 packageName: null,
228 });
229 const maintenanceFor = (probed: typeof runtimeProbe.get) =>
230 probed.pipe(
231 Effect.map((result) => result.generation),
232 Effect.option,
233 Effect.flatMap((generation) =>
234 Option.isNone(generation)
235 ? Effect.succeed(noUpdate)
236 : resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation.value), {
237 binaryPath: effectiveConfig.binaryPath,
238 env: processEnv,
239 }),
240 ),
241 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
242 Effect.provideService(FileSystem.FileSystem, fileSystem),
243 Effect.provideService(Path.Path, pathService),
244 );
245 const cachedMaintenance = yield* makeCachedProviderMaintenanceResolution(
246 maintenanceFor(runtimeProbe.get),
247 );
248 // A fresh read (an update about to run, or a manual refresh) re-probes, so
249 // a binary replaced by the other major version gets its own package.
250 const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>
251 !effectiveConfig.enabled
252 ? Effect.succeed(noUpdate)
253 : options?.fresh === true
254 ? runtimeProbe.refresh.pipe(
255 Effect.ignore,
256 Effect.andThen(cachedMaintenance({ fresh: true })),
257 )
258 : cachedMaintenance();
259 const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({
260 instanceId,
261 displayName,
262 accentColor,
263 environment,
264 enabled,
265 config,
266 }).pipe(
267 Effect.mapError(
268 (cause) =>
269 new ProviderDriverError({
270 driver: DRIVER_KIND,
271 instanceId,
272 detail: "Failed to build OpenCode orchestration adapter.",
273 cause,
274 }),
275 ),
276 );
277 // One OpenCode 2 server per instance, spawned on first use or reached at `serverUrl`.
278 const openCode2Server = yield* OpenCode2Server.make({
279 binaryPath: effectiveConfig.binaryPath,
280 serverUrl: effectiveConfig.serverUrl,
281 serverPassword: effectiveConfig.serverPassword,
282 directory: serverConfig.cwd,
283 environment: processEnv,
284 }).pipe(
285 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
286 Effect.provideService(
287 OpenCode2Client.OpenCode2Client,
288 yield* OpenCode2Client.make.pipe(
289 Effect.provideService(HttpClient.HttpClient, httpClient),
290 ),
291 ),
292 );
293 const orchestrationAdapter = selectOpenCodeRuntimeAdapter({
294 probe: runtimeProbe,
295 v1: openCodeV1Adapter,
296 v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(
297 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
298 ),
299 });
300 const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(
301 openCode2Server.withConnection((connection) =>
302 connection.client.model.list({ location: { directory: serverConfig.cwd } }).pipe(
303 Effect.map((models) => models.data),
304 Effect.mapError(
305 (cause) =>
306 new OpenCodeRuntime.OpenCodeRuntimeError({
307 operation: "model.list",
308 detail: "The OpenCode server could not list its models.",
309 cause,
310 }),
311 ),
312 ),
313 ),
314 );
315 // A 2.x server lists skills and commands per directory, so one server
316 // answers every workspace. Its event stream says when a directory it had
317 // not served yet finished scanning.
318 const listOpenCode2Workspace = (cwd: string) =>
319 openCode2Server.withConnection(({ client, events }) =>
320 Effect.gen(function* () {
321 const location = { directory: cwd };
322 const scanned = yield* Deferred.make<void>();
323 const pending = new Set(["command.updated", "skill.updated"]);
324 const stream = yield* events.pipe(Effect.option);
325 if (stream._tag === "Some") {
326 yield* stream.value.pipe(
327 Stream.runForEach((event) =>
328 "location" in event &&
329 event.location?.directory === cwd &&
330 pending.delete(event.type) &&
331 pending.size === 0
332 ? Deferred.succeed(scanned, undefined)
333 : Effect.void,
334 ),
335 Effect.ignore,
336 Effect.forkScoped,
337 );
338 }
339 return yield* loadOpenCode2Workspace(
340 Effect.all(
341 {
342 skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)),
343 commands: client.command.list({ location }).pipe(Effect.map((list) => list.data)),
344 },
345 { concurrency: "unbounded" },
346 ),
347 Deferred.await(scanned),
348 );
349 }).pipe(Effect.scoped),
350 );
351 const serverOwner = yield* OpenCodeServerOwner.make({
352 binaryPath: effectiveConfig.binaryPath,
353 directory: serverConfig.cwd,
354 ...(effectiveConfig.serverPassword
355 ? { serverPassword: effectiveConfig.serverPassword }
356 : {}),
357 environment: processEnv,
358 });
359 const textGeneration = selectOpenCodeRuntimeTextGeneration(
360 runtimeProbe,
361 yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
362 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
363 ),
364 yield* OpenCode2TextGeneration.make().pipe(
365 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
366 ),
367 );
368​
369 const checkProvider = Effect.all(
370 {
371 provider: checkOpenCodeProviderStatus(
372 effectiveConfig,
373 serverConfig.cwd,
374 runtimeProbe.refresh,
375 loadOpenCode2Models,
376 ),
377 usageLimits: readOpenCodeGoUsageLimits({
378 enabled: effectiveConfig.enabled,
379 serverUrl: effectiveConfig.serverUrl,
380 environment: processEnv,
381 }),
382 },
383 { concurrency: "unbounded" },
384 ).pipe(
385 Effect.map(({ provider, usageLimits }) => ({ ...provider, usageLimits })),
386 Effect.map(stampIdentity),
387 Effect.provideService(FileSystem.FileSystem, fileSystem),
388 Effect.provideService(Path.Path, pathService),
389 Effect.provideService(HttpClient.HttpClient, httpClient),
390 Effect.provideService(Crypto.Crypto, crypto),
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, host.settings);
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};