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

driver.ts

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