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

driver.ts

933 lines39.0 KB

1import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe";
2import {
3 ProviderDriverKind,
4 settingsSecretLiteral,
5 type ServerProviderModel,
6} from "@t3tools/contracts";
7import { OpenCodeSettings } from "../settings.ts";
8import * as Cause from "effect/Cause";
9import * as Digest from "effect/crypto/Digest";
10import * as SecureRandom from "effect/crypto/SecureRandom";
11import * as Deferred from "effect/Deferred";
12import * as Effect from "effect/Effect";
13import * as DateTime from "effect/DateTime";
14import * as Equal from "effect/Equal";
15import * as Exit from "effect/Exit";
16import * as Option from "effect/Option";
17import * as FileSystem from "effect/FileSystem";
18import * as Path from "effect/Path";
19import * as Queue from "effect/Queue";
20import * as Schema from "effect/Schema";
21import * as Scope from "effect/Scope";
22import * as Semaphore from "effect/Semaphore";
23import * as Stream from "effect/Stream";
24import * as HttpClient from "effect/http/HttpClient";
25import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
26​
27import * as OpenCode2TextGeneration from "./v2/textGeneration.ts";
28import { makeOpenCodeTextGeneration } from "./textGeneration.ts";
29import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
30import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
31import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
32import { AgentScope } from "@t3tools/shared/AgentScope";
33import * as HostProcess from "@t3tools/shared/HostProcess";
34import { compareSemverVersions } from "@t3tools/shared/semver";
35import * as OpenCodeAdapterV2 from "./adapter.ts";
36import * as OpenCode2AdapterV2 from "./v2/adapter.ts";
37import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
38import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration";
39import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
40import { openCodeUsageReader, type OpenCodeUsageReaderEnv } from "./usage.ts";
41import { withUsageAccess } from "@t3tools/provider-core/server/usageLimits";
42import { readOpenCodeGoUsageLimits } from "./usageLimits.ts";
43import { loadOpenCode2Catalog, loadOpenCode2DirectoryCatalog } from "./openCode2Catalog.ts";
44import {
45 checkOpenCodeProviderStatus,
46 followOpenCode2Scans,
47 loadOpenCode2Workspace,
48 makeOpenCode2CatalogWatch,
49 makeOpenCode2ModelLoader,
50 makePendingOpenCodeProvider,
51 openCode2CommandsToServerProviderSlashCommands,
52 openCode2ProviderModels,
53 openCode2SkillsToServerProviderSkills,
54 openCodeSkillsToServerProviderSkills,
55 openCodeCommandsToServerProviderSlashCommands,
56 openCodeProviderModels,
57 readSettledOpenCode2Catalog,
58 withOpenCode2Catalog,
59 type OpenCode2Model,
60} from "./status.ts";
61import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
62import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
63import {
64 makeOpenCodeRuntimeProbe,
65 probeOpenCodeRuntime,
66 probeOpenCodeBinary,
67 type ProbedOpenCode,
68} from "./versionProbe.ts";
69import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts";
70import * as OpenCode2Client from "./v2/OpenCode2Client.ts";
71import * as OpenCode2Server from "./v2/OpenCode2Server.ts";
72import { replaceOutdatedService } from "./v2/OpenCode2Service.ts";
73import {
74 defaultProviderContinuationIdentity,
75 type ProviderDriver,
76 type ProviderInstance,
77} from "@t3tools/provider-core/server/driver";
78import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
79import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
80import { providerProbeEnvironment } from "@t3tools/provider-core/server/snapshotProbe";
81import {
82 enrichProviderSnapshotWithVersionAdvisory,
83 makeCachedProviderMaintenanceResolution,
84 makeManualOnlyProviderMaintenanceCapabilities,
85 makePackageManagedProviderMaintenanceResolver,
86 normalizeCommandPath,
87 resolveProviderMaintenanceCapabilitiesEffect,
88} from "@t3tools/provider-core/server/maintenanceResolver";
89import {
90 haveProviderSnapshotSettingsChanged,
91 makeProviderSnapshotSettingsSource,
92 type ProviderSnapshotSettings,
93} from "@t3tools/provider-core/server/snapshotSettings";
94const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
95​
96const DRIVER_KIND = ProviderDriverKind.make("opencode");
97​
98// A loopback server runs on this environment, but can outlive its CLI installation.
99// Its reported version may therefore differ from the installed executable after an update.
100export function isLocalOpenCodeServerUrl(serverUrl: string): boolean {
101 const url = URL.parse(serverUrl.trim());
102 if (url?.protocol !== "http:" && url?.protocol !== "https:") return false;
103 return (
104 url.hostname === "localhost" ||
105 url.hostname === "[::1]" ||
106 /^127\.(?:\d{1,3}\.){2}\d{1,3}$/.test(url.hostname)
107 );
109​
110function isOpenCodeNativeCommandPath(commandPath: string): boolean {
111 const normalized = normalizeCommandPath(commandPath);
112 return (
113 normalized.endsWith("/.opencode/bin/opencode") ||
114 normalized.endsWith("/.opencode/bin/opencode.exe")
115 );
117​
118function openCodeNativeHome(commandPath: string): string | null {
119 const slashed = commandPath.replaceAll("\\", "/");
120 const match = /\/\.opencode\/bin\/opencode(?:\.exe)?$/i.exec(slashed);
121 if (!match) return null;
122 return match.index === 0 ? "/" : slashed.slice(0, match.index);
124​
125/** Update only within the installed package generation; 2.x converts the shared database in place. */
126export const openCodeUpdateFor = (generation: ProbedOpenCode["generation"]) =>
127 makePackageManagedProviderMaintenanceResolver({
128 provider: DRIVER_KIND,
129 npmPackageName: generation === "v2" ? "@opencode/cli" : "opencode-ai",
130 nativeUpdate: {
131 // `isOpenCodeNativeCommandPath` is the curl installer's own binary. Name the
132 // method so OpenCode does not have to infer it from `process.execPath`, which
133 // fails when the binary is launched through a wrapper or shim.
134 args: ["upgrade", "--method", "curl"],
135 isCommandPath: isOpenCodeNativeCommandPath,
136 requiresCommandPath: true,
137 // The curl installer writes to `$HOME/.opencode/bin`, so point HOME at the install it replaces.
138 env: (context) => {
139 const home =
140 openCodeNativeHome(context.realCommandPath) ??
141 openCodeNativeHome(context.resolvedCommandPath);
142 return home ? { HOME: home } : {};
143 },
144 },
145 // mise's `opencode` follows releases into 2.x, so it would upgrade 1.x across that line.
146 mise: { tool: "opencode", upgrade: generation === "v2" },
147 });
148​
149type OpenCodeRuntimeProbe = Effect.Success<
150 ReturnType<typeof makeOpenCodeRuntimeProbe<OpenCodeRuntime.OpenCodeRuntimeError>>
151>;
152​
153function byOpenCodeRuntime<A, E, R, PE>(
154 probed: Effect.Effect<ProbedOpenCode | undefined, PE>,
155 paths: { readonly v1: Effect.Effect<A, E, R>; readonly v2: Effect.Effect<A, E, R> },
156): Effect.Effect<A, E, R> {
157 return probed.pipe(
158 Effect.orElseSucceed(() => undefined),
159 Effect.flatMap((result) => (result?.generation === "v2" ? paths.v2 : paths.v1)),
160 );
162​
163// An unread catalog keeps what the registry found before rather than the machine catalog.
164function workspaceModelsFor(
165 machineModels: ReadonlyArray<ServerProviderModel>,
166 cwdModels: Option.Option<ReadonlyArray<ServerProviderModel>>,
167) {
168 if (Option.isNone(cwdModels)) return { workspaceModelsPending: true };
169 return Equal.equals(cwdModels.value, machineModels)
170 ? {}
171 : { models: cwdModels.value, workspaceModels: cwdModels.value };
173​
174// Hot reads use the last successful probe; session opens await it to select the correct protocol.
175function selectOpenCodeRuntimeAdapter(input: {
176 readonly probe: OpenCodeRuntimeProbe;
177 readonly resolve: Effect.Effect<ProbedOpenCode, OpenCodeRuntime.OpenCodeRuntimeError>;
178 readonly v1: ProviderAdapter.ProviderAdapterV2["Service"];
179 readonly v2: ProviderAdapter.ProviderAdapterV2["Service"];
180}): ProviderAdapter.ProviderAdapterV2["Service"] {
181 const pick = <PE>(probed: Effect.Effect<ProbedOpenCode | undefined, PE>) =>
182 byOpenCodeRuntime(probed, { v1: Effect.succeed(input.v1), v2: Effect.succeed(input.v2) });
183 const hot = pick(Effect.map(input.probe.lastSuccess, Option.getOrUndefined));
184 return {
185 instanceId: input.v1.instanceId,
186 driver: DRIVER_KIND,
187 getCapabilities: Effect.fn("OpenCodeDriver.getCapabilities")(function* () {
188 const probed = Option.getOrUndefined(yield* input.probe.lastSuccess);
189 const adapter = yield* pick(Effect.succeed(probed));
190 const capabilities = yield* adapter.getCapabilities();
191 return {
192 ...capabilities,
193 turns: {
194 ...capabilities.turns,
195 supportsNativeGoals:
196 capabilities.turns.supportsNativeGoals ??
197 (probed?.generation === "v2" && compareSemverVersions(probed.version, "2.2.5") >= 0),
198 },
199 };
200 }),
201 planSelectionTransition: (transition) =>
202 Effect.flatMap(hot, (adapter) => adapter.planSelectionTransition(transition)),
203 openSession: (session) =>
204 Effect.flatMap(pick(input.resolve), (adapter) => adapter.openSession(session)),
205 };
207​
208function selectOpenCodeRuntimeTextGeneration(
209 resolve: Effect.Effect<ProbedOpenCode, OpenCodeRuntime.OpenCodeRuntimeError>,
210 v1: ProviderTextGeneration,
211 v2: ProviderTextGeneration,
212): ProviderTextGeneration {
213 return {
214 generateCommitMessage: (input) =>
215 byOpenCodeRuntime(resolve, {
216 v1: v1.generateCommitMessage(input),
217 v2: v2.generateCommitMessage(input),
218 }),
219 generatePrContent: (input) =>
220 byOpenCodeRuntime(resolve, {
221 v1: v1.generatePrContent(input),
222 v2: v2.generatePrContent(input),
223 }),
224 generateBranchName: (input) =>
225 byOpenCodeRuntime(resolve, {
226 v1: v1.generateBranchName(input),
227 v2: v2.generateBranchName(input),
228 }),
229 generateThreadTitle: (input) =>
230 byOpenCodeRuntime(resolve, {
231 v1: v1.generateThreadTitle(input),
232 v2: v2.generateThreadTitle(input),
233 }),
234 generateReviewGuide: (input) =>
235 byOpenCodeRuntime(resolve, {
236 v1: v1.generateReviewGuide(input),
237 v2: v2.generateReviewGuide(input),
238 }),
239 generateTranscriptionPostProcessing: (input) =>
240 byOpenCodeRuntime(resolve, {
241 v1: v1.generateTranscriptionPostProcessing(input),
242 v2: v2.generateTranscriptionPostProcessing(input),
243 }),
244 };
246​
247export type OpenCodeDriverEnv =
248 | OpenCodeAdapterV2.OpenCodeAdapterV2DriverEnv
249 | ProviderHost.ProviderHost
250 | ChildProcessSpawner.ChildProcessSpawner
251 | Digest.Digest
252 | SecureRandom.SecureRandom
253 | FileSystem.FileSystem
254 | HttpClient.HttpClient
255 | ProviderLatestVersions.ProviderLatestVersions
256 | OpenCodeRuntime.OpenCodeRuntime
257 | Path.Path;
258​
259export const OpenCodeDriver: ProviderDriver<
260 OpenCodeSettings,
261 OpenCodeDriverEnv,
262 OpenCodeUsageReaderEnv
263> = {
264 driverKind: DRIVER_KIND,
265 metadata: {
266 displayName: "OpenCode",
267 supportsMultipleInstances: true,
268 },
269 configSchema: OpenCodeSettings,
270 defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
271 usage: openCodeUsageReader,
272 create: Effect.fn("OpencodeDriver.create")(function* ({
273 instanceId,
274 displayName,
275 accentColor,
276 environment,
277 enabled,
278 usageAccess = Effect.succeed(false),
279 config,
280 }) {
281 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
282 const fileSystem = yield* FileSystem.FileSystem;
283 const pathService = yield* Path.Path;
284 const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
285 const agentScope = yield* AgentScope;
286 const httpClient = yield* HttpClient.HttpClient;
287 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
288 const digest = yield* Digest.Digest;
289 const host = yield* ProviderHost.ProviderHost;
290 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
291 const continuationIdentity = defaultProviderContinuationIdentity({
292 driverKind: DRIVER_KIND,
293 instanceId,
294 });
295 const stampIdentity = withInstanceIdentity({
296 instanceId,
297 driverKind: DRIVER_KIND,
298 displayName,
299 accentColor,
300 continuationGroupKey: continuationIdentity.continuationKey,
301 });
302 const effectiveConfig = {
303 ...config,
304 enabled,
305 binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
306 // The instance registry has already read a referenced password from its secret provider.
307 serverPassword: settingsSecretLiteral(config.serverPassword),
308 } satisfies OpenCodeSettings;
309 const probeRuntime = (probeEnv: NodeJS.ProcessEnv) =>
310 probeOpenCodeRuntime(effectiveConfig, probeEnv).pipe(
311 Effect.provideService(HttpClient.HttpClient, httpClient),
312 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
313 );
314 const runtimeProbe = yield* makeOpenCodeRuntimeProbe(
315 probeRuntime(providerProbeEnvironment(processEnv)),
316 );
317 // A mise shim cannot install OpenCode offline; a session or text generation the user started
318 // may, so without a cached result it probes once online and caches what mise installed.
319 const resolveRuntime =
320 effectiveConfig.serverUrl.trim().length > 0
321 ? runtimeProbe.get
322 : runtimeProbe.lastSuccess.pipe(
323 Effect.flatMap(
324 Option.match({
325 onSome: Effect.succeed,
326 onNone: () => probeRuntime(processEnv).pipe(Effect.tap(runtimeProbe.record)),
327 }),
328 ),
329 );
330 const noUpdate = makeManualOnlyProviderMaintenanceCapabilities({
331 provider: DRIVER_KIND,
332 packageName: null,
333 });
334 const maintenanceFor = (probed: typeof runtimeProbe.get) =>
335 probed.pipe(
336 Effect.map((result) => result.generation),
337 Effect.option,
338 Effect.flatMap((generation) =>
339 Option.isNone(generation)
340 ? Effect.succeed(noUpdate)
341 : resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation.value), {
342 binaryPath: effectiveConfig.binaryPath,
343 env: processEnv,
344 npmCacheDir: pathService.join(host.paths.providerStatusCacheDir, "npm"),
345 }),
346 ),
347 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
348 Effect.provideService(FileSystem.FileSystem, fileSystem),
349 Effect.provideService(Path.Path, pathService),
350 );
351 const cachedMaintenance = yield* makeCachedProviderMaintenanceResolution(
352 maintenanceFor(
353 isLocalOpenCodeServerUrl(effectiveConfig.serverUrl)
354 ? probeOpenCodeBinary(
355 effectiveConfig.binaryPath,
356 providerProbeEnvironment(processEnv),
357 ).pipe(
358 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
359 Effect.catch(() => runtimeProbe.get),
360 )
361 : runtimeProbe.get,
362 ),
363 );
364 const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>
365 !effectiveConfig.enabled
366 ? Effect.succeed(noUpdate)
367 : options?.fresh === true
368 ? runtimeProbe.refresh.pipe(
369 Effect.ignore,
370 Effect.andThen(cachedMaintenance({ fresh: true })),
371 )
372 : cachedMaintenance();
373 const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({
374 instanceId,
375 displayName,
376 accentColor,
377 environment,
378 enabled,
379 config: effectiveConfig,
380 }).pipe(
381 Effect.mapError(
382 (cause) =>
383 new ProviderDriverError({
384 driver: DRIVER_KIND,
385 instanceId,
386 detail: "Failed to build OpenCode orchestration adapter.",
387 cause,
388 }),
389 ),
390 );
391 const openCode2Server = yield* OpenCode2Server.make({
392 binaryPath: effectiveConfig.binaryPath,
393 serverUrl: effectiveConfig.serverUrl,
394 serverPassword: effectiveConfig.serverPassword,
395 directory: host.paths.cwd,
396 environment: processEnv,
397 }).pipe(
398 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
399 Effect.provideService(
400 OpenCode2Client.OpenCode2Client,
401 yield* OpenCode2Client.make.pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
402 ),
403 );
404 const orchestrationAdapter = selectOpenCodeRuntimeAdapter({
405 probe: runtimeProbe,
406 resolve: resolveRuntime,
407 v1: openCodeV1Adapter,
408 v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(
409 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
410 ),
411 });
412 const catalogWatch = yield* makeOpenCode2CatalogWatch(processEnv);
413 // An external server may not have the host's cwd; without a location it uses its own default.
414 const machineDirectory = (connection: OpenCode2Server.OpenCode2Connection) =>
415 connection.external ? undefined : host.paths.cwd;
416 const followMachineCatalog = (connection: OpenCode2Server.OpenCode2Connection) =>
417 catalogWatch.follow(
418 connection.url,
419 connection.events,
420 loadOpenCode2DirectoryCatalog(connection.client, machineDirectory(connection)),
421 );
422 // Locations whose scan T3 saw end on the current server; a scan is announced only once.
423 let scans = { url: "", scanned: new Set<string>() };
424 // Skills that appear after a location's scan, such as a new SKILL.md or an MCP server's skills,
425 // are announced by another skill.updated.
426 const skillRescans = yield* Queue.unbounded<string, Cause.Done>();
427 yield* Effect.addFinalizer(() => Queue.end(skillRescans));
428 const skillUpdates = new Map<string, number>();
429 // Locations T3 has listed, by the cwd the registry asked for.
430 const listed = new Map<string, string>();
431 const driverScope = yield* Effect.scope;
432 // A configured server keeps one connection, so a dropped event stream is resubscribed on read.
433 let following:
434 | { readonly url: string; readonly subscribed: Deferred.Deferred<void> }
435 | undefined;
436 const followScans = Effect.fn("OpenCodeDriver.followScans")(function* (
437 connection: OpenCode2Server.OpenCode2Connection,
438 ) {
439 if (following?.url === connection.url) return yield* Deferred.await(following.subscribed);
440 const current = { url: connection.url, subscribed: yield* Deferred.make<void>() };
441 following = current;
442 const stopFollowing = Effect.sync(() => {
443 if (following === current) following = undefined;
444 }).pipe(Effect.andThen(Deferred.succeed(current.subscribed, undefined)));
445 // Resubscribing to the same server keeps the scans it already announced.
446 if (scans.url !== connection.url) scans = { url: connection.url, scanned: new Set() };
447 const { scanned } = scans;
448 const noteSkillUpdate = (event: {
449 readonly type: string;
450 readonly location?: { readonly directory?: string } | undefined;
451 }) => {
452 const directory = event.location?.directory;
453 // The skill.updated that ends a scan is covered by the read that waits for that scan.
454 if (
455 event.type !== "skill.updated" ||
456 directory === undefined ||
457 !(scanned.has(directory) || listed.has(directory))
458 ) {
459 return Effect.void;
460 }
461 skillUpdates.set(directory, (skillUpdates.get(directory) ?? 0) + 1);
462 const cwd = listed.get(directory);
463 return cwd === undefined ? Effect.void : Queue.offer(skillRescans, cwd);
464 };
465 // Subscribe before the caller reads: OpenCode sends no events from before a subscription.
466 const scope = yield* Scope.fork(driverScope);
467 const release = stopFollowing.pipe(Effect.andThen(Scope.close(scope, Exit.void)));
468 const events = yield* connection.events.pipe(
469 Effect.provideService(Scope.Scope, scope),
470 Effect.option,
471 Effect.onInterrupt(() => release),
472 );
473 if (events._tag === "None") return yield* release;
474 yield* Deferred.succeed(current.subscribed, undefined);
475 yield* Effect.forkIn(
476 followOpenCode2Scans(events.value.pipe(Stream.tap(noteSkillUpdate)), (directory) =>
477 Effect.sync(() => scanned.add(directory)),
478 ).pipe(Effect.ensuring(release)),
479 driverScope,
480 );
481 });
482 // A session or text generation can start the server too, and reads no catalog when it does.
483 yield* Stream.runForEach(openCode2Server.connections, (connection) =>
484 followScans(connection).pipe(Effect.andThen(followMachineCatalog(connection))),
485 ).pipe(Effect.forkScoped);
486 const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(
487 openCode2Server.withConnection((connection) =>
488 followMachineCatalog(connection).pipe(
489 Effect.andThen(loadOpenCode2Catalog(connection.client, machineDirectory(connection))),
490 ),
491 ),
492 processEnv,
493 );
494 const listOpenCode2Workspace = (cwd: string) =>
495 openCode2Server.withConnection((connection) =>
496 Effect.gen(function* () {
497 const { client, events, url } = connection;
498 const [, stream] = yield* Effect.all(
499 [followScans(connection), events.pipe(Effect.option)],
500 {
501 concurrency: "unbounded",
502 },
503 );
504 // OpenCode names a location by its resolved path (no trailing slash or `..`).
505 const directory = pathService.resolve(cwd);
506 const location = { directory };
507 if (scans.url !== url) scans = { url, scanned: new Set() };
508 const { scanned: seen } = scans;
509 const scanned = yield* Deferred.make<void>();
510 if (stream._tag === "Some") {
511 yield* followOpenCode2Scans(stream.value, (scannedDirectory) =>
512 scannedDirectory === directory
513 ? Deferred.succeed(scanned, undefined).pipe(Effect.asVoid)
514 : Effect.void,
515 ).pipe(Effect.forkScoped);
516 }
517 const wasListed = listed.has(directory);
518 let skillUpdatesBeforeRead = 0;
519 const workspace = yield* loadOpenCode2Workspace(
520 Effect.sync(() => {
521 skillUpdatesBeforeRead = skillUpdates.get(directory) ?? 0;
522 }).pipe(
523 Effect.andThen(
524 Effect.all(
525 {
526 skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)),
527 commands: client.command
528 .list({ location })
529 .pipe(Effect.map((list) => list.data)),
530 },
531 { concurrency: "unbounded" },
532 ),
533 ),
534 ),
535 Deferred.await(scanned),
536 // Without events no scan can be awaited, so trust the first read as before.
537 stream._tag === "None" || seen.has(directory),
538 processEnv,
539 );
540 // A location loaded before T3 watched never announces its scan; wait for it only once.
541 seen.add(directory);
542 listed.set(directory, cwd);
543 // The listener rescans a listed location itself; a first read may miss what it announced.
544 if (!wasListed && (skillUpdates.get(directory) ?? 0) !== skillUpdatesBeforeRead) {
545 yield* Queue.offer(skillRescans, cwd);
546 }
547 return workspace;
548 }).pipe(Effect.scoped),
549 );
550 const serverOwner = yield* OpenCodeServerOwner.make({
551 binaryPath: effectiveConfig.binaryPath,
552 directory: host.paths.cwd,
553 ...(effectiveConfig.serverPassword ? { serverPassword: effectiveConfig.serverPassword } : {}),
554 environment: processEnv,
555 });
556 const textGeneration = selectOpenCodeRuntimeTextGeneration(
557 resolveRuntime,
558 yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
559 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
560 ),
561 yield* OpenCode2TextGeneration.make().pipe(
562 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
563 ),
564 );
565​
566 // Reads OpenCode's auth.json and credential table for the Go key.
567 const legacyUsageLimits = withUsageAccess(
568 usageAccess,
569 readOpenCodeGoUsageLimits({
570 enabled: effectiveConfig.enabled,
571 serverUrl: effectiveConfig.serverUrl,
572 environment: processEnv,
573 }),
574 ).pipe(
575 Effect.provideService(FileSystem.FileSystem, fileSystem),
576 Effect.provideService(Path.Path, pathService),
577 Effect.provideService(HttpClient.HttpClient, httpClient),
578 Effect.provideService(Digest.Digest, digest),
579 );
580 let unsupportedUsageVersion: string | undefined;
581 const checkUsageLimits = Effect.gen(function* () {
582 if (!effectiveConfig.enabled) return yield* legacyUsageLimits;
583 const runtime = yield* runtimeProbe.get;
584 if (runtime.generation === "v1" || runtime.version === unsupportedUsageVersion)
585 return yield* legacyUsageLimits;
586 const limits = yield* openCode2Server.withConnection((connection) =>
587 connection.usageLimits(machineDirectory(connection)),
588 );
589 if (limits === undefined) unsupportedUsageVersion = runtime.version;
590 if (limits !== undefined && limits.unavailable?.reason !== "unsupported") return limits;
591 // Without a Console workspace the server reports nothing, but a local Go key still has usage.
592 const legacy = yield* legacyUsageLimits;
593 return limits !== undefined && legacy.unavailable?.reason === "unsupported" ? limits : legacy;
594 }).pipe(
595 Effect.timeout("10 seconds"),
596 Effect.catch(() =>
597 Effect.map(DateTime.now, (now) => ({
598 checkedAt: DateTime.formatIso(now),
599 windows: [],
600 unavailable: {
601 reason: "probeFailed" as const,
602 message: "OpenCode could not read workspace usage.",
603 },
604 })),
605 ),
606 );
607 const checkProvider = Effect.all(
608 {
609 // A configured loopback server reports its running version. Probe the local
610 // CLI separately so a completed npm update is not mistaken for a failure
611 // while that independently managed server still runs the previous binary.
612 installedVersion:
613 effectiveConfig.enabled && isLocalOpenCodeServerUrl(effectiveConfig.serverUrl)
614 ? probeOpenCodeBinary(
615 effectiveConfig.binaryPath,
616 providerProbeEnvironment(processEnv),
617 ).pipe(
618 Effect.map((probed) => probed.version),
619 Effect.orElseSucceed(() => undefined),
620 )
621 : Effect.void,
622 provider: checkOpenCodeProviderStatus(
623 effectiveConfig,
624 host.paths.cwd,
625 runtimeProbe.refresh,
626 loadOpenCode2Models,
627 processEnv,
628 host.compatibility,
629 ).pipe(
630 Effect.annotateLogs({ providerInstanceId: instanceId }),
631 Effect.annotateSpans({ providerInstanceId: instanceId }),
632 ),
633 usageLimits: checkUsageLimits,
634 },
635 { concurrency: "unbounded" },
636 ).pipe(
637 Effect.map(({ provider, usageLimits, installedVersion }) => ({
638 ...provider,
639 usageLimits,
640 ...(installedVersion === undefined ? {} : { installedVersion }),
641 })),
642 Effect.map(stampIdentity),
643 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
644 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
645 );
646 // The CLI writes its full JSON inventory to stdout, but the Bun-compiled binary does not
647 // flush more than one 64KB pipe buffer to a non-TTY stdout, so the piped output arrives
648 // truncated and unparseable — which degrades to an empty skill list and poisons the workspace
649 // snapshot the `$` picker reads.
650 const loadWorkspaceInventory = (
651 client: Parameters<typeof OpenCodeRuntime.loadOpenCodeCommands>[0],
652 ) =>
653 Effect.all(
654 {
655 skills: openCodeRuntime.loadOpenCodeSkills(client),
656 commandInventory: OpenCodeRuntime.loadOpenCodeCommands(client).pipe(
657 Effect.timeoutOption(resolveProviderProbeTimeoutMs("opencode", 10_000, processEnv)),
658 Effect.map((commands) => ({
659 commands: Option.getOrElse(commands, () => []),
660 slashCommandsPending: Option.isNone(commands),
661 })),
662 // SDK errors leave command discovery to the provider's health.
663 Effect.orElseSucceed(() => ({
664 commands: [],
665 slashCommandsPending: undefined,
666 })),
667 ),
668 // A project's opencode.jsonc can define its own providers.
669 models: OpenCodeRuntime.loadOpenCodeProviderCatalog(client).pipe(
670 Effect.timeoutOption("10 seconds"),
671 Effect.map(
672 Option.flatMapNullishOr((catalog) =>
673 openCodeProviderModels(effectiveConfig, catalog),
674 ),
675 ),
676 Effect.orElseSucceed(() => Option.none<ReadonlyArray<ServerProviderModel>>()),
677 ),
678 },
679 { concurrency: "unbounded" },
680 ).pipe(
681 Effect.map(({ skills, commandInventory, models }) => ({
682 skills,
683 models,
684 ...commandInventory,
685 })),
686 );
687 const loadWorkspaceForCwd = (cwd: string) =>
688 effectiveConfig.serverUrl.trim().length > 0
689 ? Effect.scoped(
690 Effect.gen(function* () {
691 const server = yield* openCodeRuntime.connectToOpenCodeServer({
692 binaryPath: effectiveConfig.binaryPath,
693 directory: cwd,
694 serverUrl: effectiveConfig.serverUrl,
695 ...(effectiveConfig.serverPassword
696 ? { serverPassword: effectiveConfig.serverPassword }
697 : {}),
698 environment: processEnv,
699 });
700 const client = openCodeRuntime.createOpenCodeSdkClient({
701 baseUrl: server.url,
702 directory: cwd,
703 ...(effectiveConfig.serverPassword
704 ? { serverPassword: effectiveConfig.serverPassword }
705 : {}),
706 });
707 return yield* loadWorkspaceInventory(client);
708 }),
709 )
710 : serverOwner.withServer((server) =>
711 loadWorkspaceInventory(
712 openCodeRuntime.createOpenCodeSdkClient({
713 baseUrl: server.url,
714 directory: cwd,
715 ...(server.serverPassword !== undefined
716 ? { serverPassword: server.serverPassword }
717 : {}),
718 }),
719 ),
720 );
721​
722 const serverUrl = effectiveConfig.serverUrl.trim();
723 const afterUpdate =
724 serverUrl.length > 0
725 ? replaceOutdatedService({
726 binaryPath: effectiveConfig.binaryPath,
727 serverUrl,
728 environment: processEnv,
729 }).pipe(
730 Effect.ensuring(openCode2Server.forget),
731 Effect.mapError(
732 (cause) =>
733 new ProviderDriverError({
734 driver: DRIVER_KIND,
735 instanceId,
736 detail: "Failed to replace the OpenCode service after an update.",
737 cause,
738 }),
739 ),
740 Effect.provideService(AgentScope, agentScope),
741 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
742 Effect.provideService(FileSystem.FileSystem, fileSystem),
743 Effect.provideService(Path.Path, pathService),
744 )
745 : Effect.void;
746​
747 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
748 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>({
749 resolveMaintenance,
750 getSettings: snapshotSettings.getSettings,
751 streamSettings: snapshotSettings.streamSettings,
752 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
753 checkProviderOnSettingsChange: () => false,
754 // A failed or still-loading catalog must recover without a manual
755 // refresh. Healthy instances need no recurring server starts.
756 refreshOnInterval: (snapshot) =>
757 snapshot.enabled &&
758 snapshot.installed &&
759 snapshot.status !== "ready" &&
760 snapshot.auth.status === "unknown",
761 initialSnapshot: (settings) =>
762 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
763 checkProvider,
764 checkUsageLimits,
765 recoverUsageOnInterval: true,
766 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => {
767 let enriched = snapshot;
768 let catalog: ReadonlyArray<OpenCode2Model> | undefined;
769 // Each publication replaces the whole snapshot, so both sources publish their combination.
770 const publishing = Semaphore.makeUnsafe(1);
771 const publish = publishing.withPermit(
772 Effect.suspend(() =>
773 publishSnapshot(
774 catalog === undefined
775 ? enriched
776 : withOpenCode2Catalog(enriched, effectiveConfig, catalog),
777 ),
778 ),
779 );
780 return Effect.all(
781 [
782 resolveMaintenance().pipe(
783 Effect.flatMap((maintenanceCapabilities) =>
784 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
785 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
786 }),
787 ),
788 Effect.provideService(HttpClient.HttpClient, httpClient),
789 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
790 Effect.flatMap((enrichedSnapshot) => {
791 enriched = enrichedSnapshot;
792 return publish;
793 }),
794 ),
795 Stream.runForEach(catalogWatch.changes, (listed) => {
796 catalog = listed;
797 return publish;
798 }),
799 ],
800 { concurrency: "unbounded", discard: true },
801 );
802 },
803 }).pipe(
804 Effect.mapError(
805 (cause) =>
806 new ProviderDriverError({
807 driver: DRIVER_KIND,
808 instanceId,
809 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
810 cause,
811 }),
812 ),
813 );
814​
815 return {
816 instanceId,
817 driverKind: DRIVER_KIND,
818 continuationIdentity,
819 displayName,
820 accentColor,
821 enabled,
822 snapshot,
823 // A scan never installs OpenCode: without an offline probe result it fails and keeps the
824 // last inventory rather than guessing 1.x.
825 snapshotForCwd: (cwd) =>
826 !effectiveConfig.enabled
827 ? snapshot.getSnapshot
828 : runtimeProbe.get.pipe(
829 Effect.mapError(
830 (cause) =>
831 new ProviderDriverError({
832 driver: DRIVER_KIND,
833 instanceId,
834 detail: `Failed to probe OpenCode for '${cwd}'`,
835 cause,
836 }),
837 ),
838 Effect.flatMap((probed) =>
839 byOpenCodeRuntime(Effect.succeed(probed), {
840 v2: Effect.all(
841 [
842 snapshot.getSnapshot,
843 // A project's opencode.jsonc can define its own providers.
844 openCode2Server
845 .withConnection(({ client, events, url }) => {
846 const read = loadOpenCode2DirectoryCatalog(client, cwd);
847 return readSettledOpenCode2Catalog(read, processEnv).pipe(
848 Effect.tap((settled) =>
849 catalogWatch.follow(url, events, read, {
850 cwd,
851 ...Option.match(settled, {
852 onNone: () => ({}),
853 onSome: (catalog) => ({ settled: catalog }),
854 }),
855 }),
856 ),
857 );
858 })
859 .pipe(
860 Effect.orElseSucceed(() => Option.none<ReadonlyArray<OpenCode2Model>>()),
861 Effect.map(
862 Option.map((catalog) =>
863 openCode2ProviderModels(effectiveConfig, catalog),
864 ),
865 ),
866 ),
867 listOpenCode2Workspace(cwd).pipe(
868 // Leaves room for the reads around the scan wait, which uses the same override.
869 Effect.timeout(
870 2 * resolveProviderProbeTimeoutMs("opencode", 10_000, processEnv),
871 ),
872 Effect.mapError(
873 (cause) =>
874 new ProviderDriverError({
875 driver: DRIVER_KIND,
876 instanceId,
877 detail: `Failed to list OpenCode commands and skills for '${cwd}'`,
878 cause,
879 }),
880 ),
881 ),
882 ],
883 { concurrency: "unbounded" },
884 ).pipe(
885 Effect.map(([machineSnapshot, cwdModels, { skills, commands }]) => ({
886 ...machineSnapshot,
887 ...workspaceModelsFor(machineSnapshot.models, cwdModels),
888 skills: openCode2SkillsToServerProviderSkills(skills),
889 slashCommands: openCode2CommandsToServerProviderSlashCommands(commands),
890 // A finished scan lists at least the built-ins. None means it
891 // timed out, so the registry decides from the provider's health.
892 slashCommandsPending: commands.length > 0 ? false : undefined,
893 })),
894 ),
895 v1: Effect.all([
896 snapshot.getSnapshot,
897 loadWorkspaceForCwd(cwd).pipe(
898 // Leaves room for connection setup before the command fallback below.
899 Effect.timeout(
900 2 * resolveProviderProbeTimeoutMs("opencode", 10_000, processEnv),
901 ),
902 ),
903 ]).pipe(
904 Effect.map(
905 ([machineSnapshot, { skills, models, commands, slashCommandsPending }]) => ({
906 ...machineSnapshot,
907 ...workspaceModelsFor(machineSnapshot.models, models),
908 skills: openCodeSkillsToServerProviderSkills(skills),
909 slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),
910 slashCommandsPending,
911 }),
912 ),
913 Effect.mapError(
914 (cause) =>
915 new ProviderDriverError({
916 driver: DRIVER_KIND,
917 instanceId,
918 detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,
919 cause,
920 }),
921 ),
922 ),
923 }),
924 ),
925 ),
926 workspaceRescans: Stream.merge(catalogWatch.rescans, Stream.fromQueue(skillRescans)),
927 invalidateCaches: openCode2Server.forget,
928 afterUpdate,
929 orchestrationAdapter,
930 textGeneration,
931 } satisfies ProviderInstance;
932 }),
933};