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