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