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