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

driver.ts

540 lines22.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 { 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 { HttpClient } from "effect/http";
26import { ChildProcessSpawner } from "effect/process";
27​
28import * as OpenCode2TextGeneration from "./v2/textGeneration.ts";
29import { makeOpenCodeTextGeneration } from "./textGeneration.ts";
30import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
31import * as OpenCodeAdapterV2 from "./adapter.ts";
32import * as OpenCode2AdapterV2 from "./v2/adapter.ts";
33import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
34import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration";
35import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
36import { readOpenCodeGoUsageLimits } from "./usageLimits.ts";
37import {
38 checkOpenCodeProviderStatus,
39 loadOpenCode2Workspace,
40 makeOpenCode2ModelLoader,
41 makePendingOpenCodeProvider,
42 openCode2CommandsToServerProviderSlashCommands,
43 openCode2SkillsToServerProviderSkills,
44 openCodeSkillsToServerProviderSkills,
45 openCodeCommandsToServerProviderSlashCommands,
46} from "./status.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 "./versionProbe.ts";
54import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts";
55import * as OpenCode2Client from "./v2/OpenCode2Client.ts";
56import * as OpenCode2Server from "./v2/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: ProviderAdapter.ProviderAdapterV2Shape;
127 readonly v2: ProviderAdapter.ProviderAdapterV2Shape;
128}): ProviderAdapter.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: ProviderTextGeneration,
147 v2: ProviderTextGeneration,
148): ProviderTextGeneration {
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.ProviderHost
176 | ChildProcessSpawner.ChildProcessSpawner
177 | Crypto.Crypto
178 | FileSystem.FileSystem
179 | HttpClient.HttpClient
180 | OpenCodeRuntime.OpenCodeRuntime
181 | Path.Path;
182​
183export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv> = {
184 driverKind: DRIVER_KIND,
185 metadata: {
186 displayName: "OpenCode",
187 supportsMultipleInstances: true,
188 },
189 configSchema: OpenCodeSettings,
190 defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
191 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
192 Effect.gen(function* () {
193 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
194 const fileSystem = yield* FileSystem.FileSystem;
195 const pathService = yield* Path.Path;
196 const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
197 const httpClient = yield* HttpClient.HttpClient;
198 const crypto = yield* Crypto.Crypto;
199 const host = yield* ProviderHost.ProviderHost;
200 const processEnv = mergeProviderInstanceEnvironment(environment);
201 const continuationIdentity = defaultProviderContinuationIdentity({
202 driverKind: DRIVER_KIND,
203 instanceId,
204 });
205 const stampIdentity = withInstanceIdentity({
206 instanceId,
207 driverKind: DRIVER_KIND,
208 displayName,
209 accentColor,
210 continuationGroupKey: continuationIdentity.continuationKey,
211 });
212 const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
213 const runtimeProbe = yield* makeOpenCodeRuntimeProbe(
214 probeOpenCodeRuntime(effectiveConfig, processEnv).pipe(
215 Effect.provideService(HttpClient.HttpClient, httpClient),
216 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
217 ),
218 );
219 // Updates follow the installed package, which the version probe names. An
220 // unknown version offers no package update, since a guess could move a
221 // 2.x install onto 1.x's package or the reverse. A disabled instance never
222 // runs its binary, so it has no version and offers no update.
223 const noUpdate = makeManualOnlyProviderMaintenanceCapabilities({
224 provider: DRIVER_KIND,
225 packageName: null,
226 });
227 const maintenanceFor = (probed: typeof runtimeProbe.get) =>
228 probed.pipe(
229 Effect.map((result) => result.generation),
230 Effect.option,
231 Effect.flatMap((generation) =>
232 Option.isNone(generation)
233 ? Effect.succeed(noUpdate)
234 : resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation.value), {
235 binaryPath: effectiveConfig.binaryPath,
236 env: processEnv,
237 }),
238 ),
239 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
240 Effect.provideService(FileSystem.FileSystem, fileSystem),
241 Effect.provideService(Path.Path, pathService),
242 );
243 const cachedMaintenance = yield* makeCachedProviderMaintenanceResolution(
244 maintenanceFor(runtimeProbe.get),
245 );
246 // A fresh read (an update about to run, or a manual refresh) re-probes, so
247 // a binary replaced by the other major version gets its own package.
248 const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>
249 !effectiveConfig.enabled
250 ? Effect.succeed(noUpdate)
251 : options?.fresh === true
252 ? runtimeProbe.refresh.pipe(
253 Effect.ignore,
254 Effect.andThen(cachedMaintenance({ fresh: true })),
255 )
256 : cachedMaintenance();
257 const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({
258 instanceId,
259 displayName,
260 accentColor,
261 environment,
262 enabled,
263 config,
264 }).pipe(
265 Effect.mapError(
266 (cause) =>
267 new ProviderDriverError({
268 driver: DRIVER_KIND,
269 instanceId,
270 detail: "Failed to build OpenCode orchestration adapter.",
271 cause,
272 }),
273 ),
274 );
275 // One OpenCode 2 server per instance, spawned on first use or reached at `serverUrl`.
276 const openCode2Server = yield* OpenCode2Server.make({
277 binaryPath: effectiveConfig.binaryPath,
278 serverUrl: effectiveConfig.serverUrl,
279 serverPassword: effectiveConfig.serverPassword,
280 directory: host.paths.cwd,
281 environment: processEnv,
282 }).pipe(
283 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
284 Effect.provideService(
285 OpenCode2Client.OpenCode2Client,
286 yield* OpenCode2Client.make.pipe(
287 Effect.provideService(HttpClient.HttpClient, httpClient),
288 ),
289 ),
290 );
291 const orchestrationAdapter = selectOpenCodeRuntimeAdapter({
292 probe: runtimeProbe,
293 v1: openCodeV1Adapter,
294 v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(
295 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
296 ),
297 });
298 const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(
299 openCode2Server.withConnection((connection) =>
300 connection.client.model.list({ location: { directory: host.paths.cwd } }).pipe(
301 Effect.map((models) => models.data),
302 Effect.mapError(
303 (cause) =>
304 new OpenCodeRuntime.OpenCodeRuntimeError({
305 operation: "model.list",
306 detail: "The OpenCode server could not list its models.",
307 cause,
308 }),
309 ),
310 ),
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 = makeProviderSnapshotSettingsSource(effectiveConfig, host.settings);
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.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
469 ),
470 },
471 ).pipe(
472 Effect.mapError(
473 (cause) =>
474 new ProviderDriverError({
475 driver: DRIVER_KIND,
476 instanceId,
477 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
478 cause,
479 }),
480 ),
481 );
482​
483 return {
484 instanceId,
485 driverKind: DRIVER_KIND,
486 continuationIdentity,
487 displayName,
488 accentColor,
489 enabled,
490 snapshot,
491 snapshotForCwd: (cwd) =>
492 !effectiveConfig.enabled
493 ? snapshot.getSnapshot
494 : byOpenCodeRuntime(runtimeProbe.get, {
495 v2: Effect.all([
496 snapshot.getSnapshot,
497 listOpenCode2Workspace(cwd).pipe(
498 Effect.timeout("20 seconds"),
499 Effect.mapError(
500 (cause) =>
501 new ProviderDriverError({
502 driver: DRIVER_KIND,
503 instanceId,
504 detail: `Failed to list OpenCode commands and skills for '${cwd}'`,
505 cause,
506 }),
507 ),
508 ),
509 ]).pipe(
510 Effect.map(([machineSnapshot, { skills, commands }]) => ({
511 ...machineSnapshot,
512 skills: openCode2SkillsToServerProviderSkills(skills),
513 slashCommands: openCode2CommandsToServerProviderSlashCommands(commands),
514 })),
515 ),
516 v1: Effect.all([
517 snapshot.getSnapshot,
518 loadWorkspaceForCwd(cwd).pipe(Effect.timeout("20 seconds")),
519 ]).pipe(
520 Effect.map(([machineSnapshot, { skills, commands }]) => ({
521 ...machineSnapshot,
522 skills: openCodeSkillsToServerProviderSkills(skills),
523 slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),
524 })),
525 Effect.mapError(
526 (cause) =>
527 new ProviderDriverError({
528 driver: DRIVER_KIND,
529 instanceId,
530 detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,
531 cause,
532 }),
533 ),
534 ),
535 }),
536 orchestrationAdapter,
537 textGeneration,
538 } satisfies ProviderInstance;
539 }),
540};