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