Open History to see the last commit
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 );
108}
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 );
116}
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);
123}
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 );
161}
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 };
172}
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 };
206}
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 };
245}
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 awaitEnrichmentOnRefresh: true,
767 enrichSnapshot: Effect.fn("enrichSnapshot")(function ({
768 settings,
769 snapshot,
770 publishSnapshot,
771 signalEnriched,
772 }) {
773 let enriched = snapshot;
774 let catalog: ReadonlyArray<OpenCode2Model> | undefined;
775 let advisoryReady = false;
776 // Each publication replaces the whole snapshot, so both sources publish their combination.
777 const publishing = Semaphore.makeUnsafe(1);
778 const publish = publishing.withPermit(
779 Effect.suspend(() =>
780 publishSnapshot(
781 catalog === undefined
782 ? enriched
783 : withOpenCode2Catalog(enriched, effectiveConfig, catalog),
784 ),
785 ),
786 );
787 return Effect.all(
788 [
789 resolveMaintenance().pipe(
790 Effect.flatMap((maintenanceCapabilities) =>
791 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
792 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
793 }),
794 ),
795 Effect.provideService(HttpClient.HttpClient, httpClient),
796 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
797 Effect.flatMap((enrichedSnapshot) => {
798 enriched = enrichedSnapshot;
799 advisoryReady = true;
800 return publish;
801 }),
802 Effect.onExit((exit) =>
803 Exit.hasInterrupts(exit)
804 ? Effect.void
805 : Effect.suspend(() => {
806 const shouldPublishCatalog = !advisoryReady && catalog !== undefined;
807 advisoryReady = true;
808 return shouldPublishCatalog
809 ? publish.pipe(Effect.andThen(signalEnriched))
810 : signalEnriched;
811 }),
812 ),
813 ),
814 Stream.runForEach(catalogWatch.changes, (listed) => {
815 catalog = listed;
816 return advisoryReady ? publish : Effect.void;
817 }),
818 ],
819 { concurrency: "unbounded", discard: true },
820 );
821 }),
822 }).pipe(
823 Effect.mapError(
824 (cause) =>
825 new ProviderDriverError({
826 driver: DRIVER_KIND,
827 instanceId,
828 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
829 cause,
830 }),
831 ),
832 );
833
834 return {
835 instanceId,
836 driverKind: DRIVER_KIND,
837 continuationIdentity,
838 displayName,
839 accentColor,
840 enabled,
841 snapshot,
842 // A scan never installs OpenCode: without an offline probe result it fails and keeps the
843 // last inventory rather than guessing 1.x.
844 snapshotForCwd: (cwd) =>
845 !effectiveConfig.enabled
846 ? snapshot.getSnapshot
847 : runtimeProbe.get.pipe(
848 Effect.mapError(
849 (cause) =>
850 new ProviderDriverError({
851 driver: DRIVER_KIND,
852 instanceId,
853 detail: `Failed to probe OpenCode for '${cwd}'`,
854 cause,
855 }),
856 ),
857 Effect.flatMap((probed) =>
858 byOpenCodeRuntime(Effect.succeed(probed), {
859 v2: Effect.all(
860 [
861 snapshot.getSnapshot,
862 // A project's opencode.jsonc can define its own providers.
863 openCode2Server
864 .withConnection(({ client, events, url }) => {
865 const read = loadOpenCode2DirectoryCatalog(client, cwd);
866 return readSettledOpenCode2Catalog(read, processEnv).pipe(
867 Effect.tap((settled) =>
868 catalogWatch.follow(url, events, read, {
869 cwd,
870 ...Option.match(settled, {
871 onNone: () => ({}),
872 onSome: (catalog) => ({ settled: catalog }),
873 }),
874 }),
875 ),
876 );
877 })
878 .pipe(
879 Effect.orElseSucceed(() => Option.none<ReadonlyArray<OpenCode2Model>>()),
880 Effect.map(
881 Option.map((catalog) =>
882 openCode2ProviderModels(effectiveConfig, catalog),
883 ),
884 ),
885 ),
886 listOpenCode2Workspace(cwd).pipe(
887 // Leaves room for the reads around the scan wait, which uses the same override.
888 Effect.timeout(
889 2 * resolveProviderProbeTimeoutMs("opencode", 10_000, processEnv),
890 ),
891 Effect.mapError(
892 (cause) =>
893 new ProviderDriverError({
894 driver: DRIVER_KIND,
895 instanceId,
896 detail: `Failed to list OpenCode commands and skills for '${cwd}'`,
897 cause,
898 }),
899 ),
900 ),
901 ],
902 { concurrency: "unbounded" },
903 ).pipe(
904 Effect.map(([machineSnapshot, cwdModels, { skills, commands }]) => ({
905 ...machineSnapshot,
906 ...workspaceModelsFor(machineSnapshot.models, cwdModels),
907 skills: openCode2SkillsToServerProviderSkills(skills),
908 slashCommands: openCode2CommandsToServerProviderSlashCommands(commands),
909 // A finished scan lists at least the built-ins. None means it
910 // timed out, so the registry decides from the provider's health.
911 slashCommandsPending: commands.length > 0 ? false : undefined,
912 })),
913 ),
914 v1: Effect.all([
915 snapshot.getSnapshot,
916 loadWorkspaceForCwd(cwd).pipe(
917 // Leaves room for connection setup before the command fallback below.
918 Effect.timeout(
919 2 * resolveProviderProbeTimeoutMs("opencode", 10_000, processEnv),
920 ),
921 ),
922 ]).pipe(
923 Effect.map(
924 ([machineSnapshot, { skills, models, commands, slashCommandsPending }]) => ({
925 ...machineSnapshot,
926 ...workspaceModelsFor(machineSnapshot.models, models),
927 skills: openCodeSkillsToServerProviderSkills(skills),
928 slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),
929 slashCommandsPending,
930 }),
931 ),
932 Effect.mapError(
933 (cause) =>
934 new ProviderDriverError({
935 driver: DRIVER_KIND,
936 instanceId,
937 detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,
938 cause,
939 }),
940 ),
941 ),
942 }),
943 ),
944 ),
945 workspaceRescans: Stream.merge(catalogWatch.rescans, Stream.fromQueue(skillRescans)),
946 invalidateCaches: openCode2Server.forget,
947 afterUpdate,
948 orchestrationAdapter,
949 textGeneration,
950 } satisfies ProviderInstance;
951 }),
952};