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

driver.ts

544 lines22.4 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 { readOpenCodeGoUsageLimits } from "./usageLimits.ts";
38import {
39 checkOpenCodeProviderStatus,
40 loadOpenCode2Workspace,
41 makeOpenCode2ModelLoader,
42 makePendingOpenCodeProvider,
43 openCode2CommandsToServerProviderSlashCommands,
44 openCode2SkillsToServerProviderSkills,
45 openCodeSkillsToServerProviderSkills,
46 openCodeCommandsToServerProviderSlashCommands,
47} from "./status.ts";
48import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
49import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
50import {
51 makeOpenCodeRuntimeProbe,
52 probeOpenCodeRuntime,
53 type ProbedOpenCode,
54} from "./versionProbe.ts";
55import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts";
56import * as OpenCode2Client from "./v2/OpenCode2Client.ts";
57import * as OpenCode2Server from "./v2/OpenCode2Server.ts";
58import {
59 defaultProviderContinuationIdentity,
60 type ProviderDriver,
61 type ProviderInstance,
62} from "@t3tools/provider-core/server/driver";
63import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
64import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
65import {
66 enrichProviderSnapshotWithVersionAdvisory,
67 makeCachedProviderMaintenanceResolution,
68 makeManualOnlyProviderMaintenanceCapabilities,
69 makePackageManagedProviderMaintenanceResolver,
70 normalizeCommandPath,
71 resolveProviderMaintenanceCapabilitiesEffect,
72} from "@t3tools/provider-core/server/maintenanceResolver";
73import {
74 haveProviderSnapshotSettingsChanged,
75 makeProviderSnapshotSettingsSource,
76 type ProviderSnapshotSettings,
77} from "@t3tools/provider-core/server/snapshotSettings";
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 );
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 );
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: ProviderAdapter.ProviderAdapterV2["Service"];
128 readonly v2: ProviderAdapter.ProviderAdapterV2["Service"];
129}): ProviderAdapter.ProviderAdapterV2["Service"] {
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 };
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: ProviderTextGeneration,
148 v2: ProviderTextGeneration,
149): ProviderTextGeneration {
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 };
173​
174export type OpenCodeDriverEnv =
175 | OpenCodeAdapterV2.OpenCodeAdapterV2DriverEnv
176 | ProviderHost.ProviderHost
177 | ChildProcessSpawner.ChildProcessSpawner
178 | Crypto.Crypto
179 | FileSystem.FileSystem
180 | HttpClient.HttpClient
181 | ProviderLatestVersions.ProviderLatestVersions
182 | OpenCodeRuntime.OpenCodeRuntime
183 | Path.Path;
184​
185export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv> = {
186 driverKind: DRIVER_KIND,
187 metadata: {
188 displayName: "OpenCode",
189 supportsMultipleInstances: true,
190 },
191 configSchema: OpenCodeSettings,
192 defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
193 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
194 Effect.gen(function* () {
195 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
196 const fileSystem = yield* FileSystem.FileSystem;
197 const pathService = yield* Path.Path;
198 const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
199 const httpClient = yield* HttpClient.HttpClient;
200 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
201 const crypto = yield* Crypto.Crypto;
202 const host = yield* ProviderHost.ProviderHost;
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: host.paths.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: host.paths.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: host.paths.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 host.paths.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(Crypto.Crypto, crypto),
392 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
393 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
394 );
395 // NOTE: the local branch intentionally uses the shared SDK server
396 // instead of `opencode debug skill` (loadSkillsFromCli). The CLI writes
397 // its full JSON inventory to stdout, but the Bun-compiled binary does
398 // not flush more than one 64KB pipe buffer to a non-TTY stdout, so the
399 // piped output arrives truncated and unparseable — which degrades to an
400 // empty skill list and poisons the workspace snapshot the `$` picker
401 // reads. The SDK `app.skills` endpoint honors the per-request directory
402 // and returns complete results regardless of size.
403 const loadWorkspaceInventory = (
404 client: Parameters<typeof OpenCodeRuntime.loadOpenCodeCommands>[0],
405 ) =>
406 Effect.all(
407 {
408 skills: openCodeRuntime.loadOpenCodeSkills(client),
409 commands: OpenCodeRuntime.loadOpenCodeCommands(client).pipe(
410 Effect.timeout("10 seconds"),
411 Effect.orElseSucceed(() => []),
412 ),
413 },
414 { concurrency: "unbounded" },
415 );
416 const loadWorkspaceForCwd = (cwd: string) =>
417 effectiveConfig.serverUrl.trim().length > 0
418 ? Effect.scoped(
419 Effect.gen(function* () {
420 const server = yield* openCodeRuntime.connectToOpenCodeServer({
421 binaryPath: effectiveConfig.binaryPath,
422 directory: cwd,
423 serverUrl: effectiveConfig.serverUrl,
424 ...(effectiveConfig.serverPassword
425 ? { serverPassword: effectiveConfig.serverPassword }
426 : {}),
427 environment: processEnv,
428 });
429 const client = openCodeRuntime.createOpenCodeSdkClient({
430 baseUrl: server.url,
431 directory: cwd,
432 ...(effectiveConfig.serverPassword
433 ? { serverPassword: effectiveConfig.serverPassword }
434 : {}),
435 });
436 return yield* loadWorkspaceInventory(client);
437 }),
438 )
439 : serverOwner.withServer((server) =>
440 loadWorkspaceInventory(
441 openCodeRuntime.createOpenCodeSdkClient({
442 baseUrl: server.url,
443 directory: cwd,
444 ...(server.serverPassword !== undefined
445 ? { serverPassword: server.serverPassword }
446 : {}),
447 }),
448 ),
449 );
450​
451 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
452 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
453 {
454 resolveMaintenance,
455 getSettings: snapshotSettings.getSettings,
456 streamSettings: snapshotSettings.streamSettings,
457 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
458 checkProviderOnSettingsChange: () => false,
459 refreshOnInterval: false,
460 initialSnapshot: (settings) =>
461 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
462 checkProvider,
463 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
464 resolveMaintenance().pipe(
465 Effect.flatMap((maintenanceCapabilities) =>
466 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
467 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
468 }),
469 ),
470 Effect.provideService(HttpClient.HttpClient, httpClient),
471 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
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};