Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

driver.ts

856 lines35.3 KB

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 );
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 );
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);
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 );
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 };
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 };
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 };
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 npmCacheDir: pathService.join(host.paths.providerStatusCacheDir, "npm"),
339 }),
340 ),
341 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
342 Effect.provideService(FileSystem.FileSystem, fileSystem),
343 Effect.provideService(Path.Path, pathService),
344 );
345 const cachedMaintenance = yield* makeCachedProviderMaintenanceResolution(
346 maintenanceFor(
347 isLocalOpenCodeServerUrl(effectiveConfig.serverUrl)
348 ? probeOpenCodeBinary(
349 effectiveConfig.binaryPath,
350 providerProbeEnvironment(processEnv),
351 ).pipe(
352 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
353 Effect.catch(() => runtimeProbe.get),
354 )
355 : runtimeProbe.get,
356 ),
357 );
358 const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>
359 !effectiveConfig.enabled
360 ? Effect.succeed(noUpdate)
361 : options?.fresh === true
362 ? runtimeProbe.refresh.pipe(
363 Effect.ignore,
364 Effect.andThen(cachedMaintenance({ fresh: true })),
365 )
366 : cachedMaintenance();
367 const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({
368 instanceId,
369 displayName,
370 accentColor,
371 environment,
372 enabled,
373 config: effectiveConfig,
374 }).pipe(
375 Effect.mapError(
376 (cause) =>
377 new ProviderDriverError({
378 driver: DRIVER_KIND,
379 instanceId,
380 detail: "Failed to build OpenCode orchestration adapter.",
381 cause,
382 }),
383 ),
384 );
385 const openCode2Server = yield* OpenCode2Server.make({
386 binaryPath: effectiveConfig.binaryPath,
387 serverUrl: effectiveConfig.serverUrl,
388 serverPassword: effectiveConfig.serverPassword,
389 directory: host.paths.cwd,
390 environment: processEnv,
391 }).pipe(
392 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
393 Effect.provideService(
394 OpenCode2Client.OpenCode2Client,
395 yield* OpenCode2Client.make.pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
396 ),
397 );
398 const orchestrationAdapter = selectOpenCodeRuntimeAdapter({
399 probe: runtimeProbe,
400 resolve: resolveRuntime,
401 v1: openCodeV1Adapter,
402 v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(
403 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
404 ),
405 });
406 const catalogWatch = yield* makeOpenCode2CatalogWatch(processEnv);
407 // An external server may not have the host's cwd; without a location it uses its own default.
408 const machineDirectory = (connection: OpenCode2Server.OpenCode2Connection) =>
409 connection.external ? undefined : host.paths.cwd;
410 const followMachineCatalog = (connection: OpenCode2Server.OpenCode2Connection) =>
411 catalogWatch.follow(
412 connection.url,
413 connection.events,
414 loadOpenCode2DirectoryCatalog(connection.client, machineDirectory(connection)),
415 );
416 // Locations whose scan T3 saw end on the current server; a scan is announced only once.
417 let scans = { url: "", scanned: new Set<string>() };
418 const followScans = (connection: OpenCode2Server.OpenCode2Connection) =>
419 Effect.suspend(() => {
420 const scanned = new Set<string>();
421 scans = { url: connection.url, scanned };
422 return connection.events.pipe(
423 Effect.flatMap((events) =>
424 followOpenCode2Scans(events, (directory) => Effect.sync(() => scanned.add(directory))),
425 ),
426 Effect.scoped,
427 Effect.ignore,
428 Effect.forkScoped,
429 );
430 });
431 // A session or text generation can start the server too, and reads no catalog when it does.
432 yield* Stream.runForEach(openCode2Server.connections, (connection) =>
433 followScans(connection).pipe(Effect.andThen(followMachineCatalog(connection))),
434 ).pipe(Effect.forkScoped);
435 const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(
436 openCode2Server.withConnection((connection) =>
437 followMachineCatalog(connection).pipe(
438 Effect.andThen(loadOpenCode2Catalog(connection.client, machineDirectory(connection))),
439 ),
440 ),
441 processEnv,
442 );
443 const listOpenCode2Workspace = (cwd: string) =>
444 openCode2Server.withConnection(({ client, events, url }) =>
445 Effect.gen(function* () {
446 // OpenCode names a location by its resolved path (no trailing slash or `..`).
447 const directory = pathService.resolve(cwd);
448 const location = { directory };
449 if (scans.url !== url) scans = { url, scanned: new Set() };
450 const { scanned: seen } = scans;
451 const scanned = yield* Deferred.make<void>();
452 const stream = yield* events.pipe(Effect.option);
453 if (stream._tag === "Some") {
454 yield* followOpenCode2Scans(stream.value, (scannedDirectory) =>
455 scannedDirectory === directory
456 ? Deferred.succeed(scanned, undefined).pipe(Effect.asVoid)
457 : Effect.void,
458 ).pipe(Effect.forkScoped);
459 }
460 const workspace = yield* loadOpenCode2Workspace(
461 Effect.all(
462 {
463 skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)),
464 commands: client.command.list({ location }).pipe(Effect.map((list) => list.data)),
465 },
466 { concurrency: "unbounded" },
467 ),
468 Deferred.await(scanned),
469 // Without events no scan can be awaited, so trust the first read as before.
470 stream._tag === "None" || seen.has(directory),
471 processEnv,
472 );
473 // A location loaded before T3 watched never announces its scan; wait for it only once.
474 seen.add(directory);
475 return workspace;
476 }).pipe(Effect.scoped),
477 );
478 const serverOwner = yield* OpenCodeServerOwner.make({
479 binaryPath: effectiveConfig.binaryPath,
480 directory: host.paths.cwd,
481 ...(effectiveConfig.serverPassword ? { serverPassword: effectiveConfig.serverPassword } : {}),
482 environment: processEnv,
483 });
484 const textGeneration = selectOpenCodeRuntimeTextGeneration(
485 resolveRuntime,
486 yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
487 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
488 ),
489 yield* OpenCode2TextGeneration.make().pipe(
490 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
491 ),
492 );
493​
494 const legacyUsageLimits = readOpenCodeGoUsageLimits({
495 enabled: effectiveConfig.enabled,
496 serverUrl: effectiveConfig.serverUrl,
497 environment: processEnv,
498 }).pipe(
499 Effect.provideService(FileSystem.FileSystem, fileSystem),
500 Effect.provideService(Path.Path, pathService),
501 Effect.provideService(HttpClient.HttpClient, httpClient),
502 Effect.provideService(Digest.Digest, digest),
503 );
504 let unsupportedUsageVersion: string | undefined;
505 const checkUsageLimits = Effect.gen(function* () {
506 if (!effectiveConfig.enabled) return yield* legacyUsageLimits;
507 const runtime = yield* runtimeProbe.get;
508 if (runtime.generation === "v1" || runtime.version === unsupportedUsageVersion)
509 return yield* legacyUsageLimits;
510 const limits = yield* openCode2Server.withConnection((connection) =>
511 connection.usageLimits(host.paths.cwd),
512 );
513 if (limits === undefined) unsupportedUsageVersion = runtime.version;
514 if (limits !== undefined && limits.unavailable?.reason !== "unsupported") return limits;
515 // Without a Console workspace the server reports nothing, but a local Go key still has usage.
516 const legacy = yield* legacyUsageLimits;
517 return limits !== undefined && legacy.unavailable?.reason === "unsupported" ? limits : legacy;
518 }).pipe(
519 Effect.timeout("10 seconds"),
520 Effect.catch(() =>
521 Effect.map(DateTime.now, (now) => ({
522 checkedAt: DateTime.formatIso(now),
523 windows: [],
524 unavailable: {
525 reason: "probeFailed" as const,
526 message: "OpenCode could not read workspace usage.",
527 },
528 })),
529 ),
530 );
531 const checkProvider = Effect.all(
532 {
533 // A configured loopback server reports its running version. Probe the local
534 // CLI separately so a completed npm update is not mistaken for a failure
535 // while that independently managed server still runs the previous binary.
536 installedVersion:
537 effectiveConfig.enabled && isLocalOpenCodeServerUrl(effectiveConfig.serverUrl)
538 ? probeOpenCodeBinary(
539 effectiveConfig.binaryPath,
540 providerProbeEnvironment(processEnv),
541 ).pipe(
542 Effect.map((probed) => probed.version),
543 Effect.orElseSucceed(() => undefined),
544 )
545 : Effect.void,
546 provider: checkOpenCodeProviderStatus(
547 effectiveConfig,
548 host.paths.cwd,
549 runtimeProbe.refresh,
550 loadOpenCode2Models,
551 processEnv,
552 host.compatibility,
553 ).pipe(
554 Effect.annotateLogs({ providerInstanceId: instanceId }),
555 Effect.annotateSpans({ providerInstanceId: instanceId }),
556 ),
557 usageLimits: checkUsageLimits,
558 },
559 { concurrency: "unbounded" },
560 ).pipe(
561 Effect.map(({ provider, usageLimits, installedVersion }) => ({
562 ...provider,
563 usageLimits,
564 ...(installedVersion === undefined ? {} : { installedVersion }),
565 })),
566 Effect.map(stampIdentity),
567 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
568 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
569 );
570 // The CLI writes its full JSON inventory to stdout, but the Bun-compiled binary does not
571 // flush more than one 64KB pipe buffer to a non-TTY stdout, so the piped output arrives
572 // truncated and unparseable — which degrades to an empty skill list and poisons the workspace
573 // snapshot the `$` picker reads.
574 const loadWorkspaceInventory = (
575 client: Parameters<typeof OpenCodeRuntime.loadOpenCodeCommands>[0],
576 ) =>
577 Effect.all(
578 {
579 skills: openCodeRuntime.loadOpenCodeSkills(client),
580 commandInventory: OpenCodeRuntime.loadOpenCodeCommands(client).pipe(
581 Effect.timeoutOption(resolveProviderProbeTimeoutMs("opencode", 10_000, processEnv)),
582 Effect.map((commands) => ({
583 commands: Option.getOrElse(commands, () => []),
584 slashCommandsPending: Option.isNone(commands),
585 })),
586 // SDK errors leave command discovery to the provider's health.
587 Effect.orElseSucceed(() => ({
588 commands: [],
589 slashCommandsPending: undefined,
590 })),
591 ),
592 // A project's opencode.jsonc can define its own providers.
593 models: OpenCodeRuntime.loadOpenCodeProviderCatalog(client).pipe(
594 Effect.timeoutOption("10 seconds"),
595 Effect.map(
596 Option.flatMapNullishOr((catalog) =>
597 openCodeProviderModels(effectiveConfig, catalog),
598 ),
599 ),
600 Effect.orElseSucceed(() => Option.none<ReadonlyArray<ServerProviderModel>>()),
601 ),
602 },
603 { concurrency: "unbounded" },
604 ).pipe(
605 Effect.map(({ skills, commandInventory, models }) => ({
606 skills,
607 models,
608 ...commandInventory,
609 })),
610 );
611 const loadWorkspaceForCwd = (cwd: string) =>
612 effectiveConfig.serverUrl.trim().length > 0
613 ? Effect.scoped(
614 Effect.gen(function* () {
615 const server = yield* openCodeRuntime.connectToOpenCodeServer({
616 binaryPath: effectiveConfig.binaryPath,
617 directory: cwd,
618 serverUrl: effectiveConfig.serverUrl,
619 ...(effectiveConfig.serverPassword
620 ? { serverPassword: effectiveConfig.serverPassword }
621 : {}),
622 environment: processEnv,
623 });
624 const client = openCodeRuntime.createOpenCodeSdkClient({
625 baseUrl: server.url,
626 directory: cwd,
627 ...(effectiveConfig.serverPassword
628 ? { serverPassword: effectiveConfig.serverPassword }
629 : {}),
630 });
631 return yield* loadWorkspaceInventory(client);
632 }),
633 )
634 : serverOwner.withServer((server) =>
635 loadWorkspaceInventory(
636 openCodeRuntime.createOpenCodeSdkClient({
637 baseUrl: server.url,
638 directory: cwd,
639 ...(server.serverPassword !== undefined
640 ? { serverPassword: server.serverPassword }
641 : {}),
642 }),
643 ),
644 );
645​
646 const serverUrl = effectiveConfig.serverUrl.trim();
647 const afterUpdate =
648 serverUrl.length > 0
649 ? replaceOutdatedService({
650 binaryPath: effectiveConfig.binaryPath,
651 serverUrl,
652 environment: processEnv,
653 }).pipe(
654 Effect.ensuring(openCode2Server.forget),
655 Effect.mapError(
656 (cause) =>
657 new ProviderDriverError({
658 driver: DRIVER_KIND,
659 instanceId,
660 detail: "Failed to replace the OpenCode service after an update.",
661 cause,
662 }),
663 ),
664 Effect.provideService(AgentScope, agentScope),
665 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
666 Effect.provideService(FileSystem.FileSystem, fileSystem),
667 Effect.provideService(Path.Path, pathService),
668 )
669 : Effect.void;
670​
671 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
672 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>({
673 resolveMaintenance,
674 getSettings: snapshotSettings.getSettings,
675 streamSettings: snapshotSettings.streamSettings,
676 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
677 checkProviderOnSettingsChange: () => false,
678 // A failed or still-loading catalog must recover without a manual
679 // refresh. Healthy instances need no recurring server starts.
680 refreshOnInterval: (snapshot) =>
681 snapshot.enabled &&
682 snapshot.installed &&
683 snapshot.status !== "ready" &&
684 snapshot.auth.status === "unknown",
685 initialSnapshot: (settings) =>
686 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
687 checkProvider,
688 checkUsageLimits,
689 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => {
690 let enriched = snapshot;
691 let catalog: ReadonlyArray<OpenCode2Model> | undefined;
692 // Each publication replaces the whole snapshot, so both sources publish their combination.
693 const publishing = Semaphore.makeUnsafe(1);
694 const publish = publishing.withPermit(
695 Effect.suspend(() =>
696 publishSnapshot(
697 catalog === undefined
698 ? enriched
699 : withOpenCode2Catalog(enriched, effectiveConfig, catalog),
700 ),
701 ),
702 );
703 return Effect.all(
704 [
705 resolveMaintenance().pipe(
706 Effect.flatMap((maintenanceCapabilities) =>
707 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
708 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
709 }),
710 ),
711 Effect.provideService(HttpClient.HttpClient, httpClient),
712 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
713 Effect.flatMap((enrichedSnapshot) => {
714 enriched = enrichedSnapshot;
715 return publish;
716 }),
717 ),
718 Stream.runForEach(catalogWatch.changes, (listed) => {
719 catalog = listed;
720 return publish;
721 }),
722 ],
723 { concurrency: "unbounded", discard: true },
724 );
725 },
726 }).pipe(
727 Effect.mapError(
728 (cause) =>
729 new ProviderDriverError({
730 driver: DRIVER_KIND,
731 instanceId,
732 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
733 cause,
734 }),
735 ),
736 );
737​
738 return {
739 instanceId,
740 driverKind: DRIVER_KIND,
741 continuationIdentity,
742 displayName,
743 accentColor,
744 enabled,
745 snapshot,
746 // A scan never installs OpenCode: without an offline probe result it fails and keeps the
747 // last inventory rather than guessing 1.x.
748 snapshotForCwd: (cwd) =>
749 !effectiveConfig.enabled
750 ? snapshot.getSnapshot
751 : runtimeProbe.get.pipe(
752 Effect.mapError(
753 (cause) =>
754 new ProviderDriverError({
755 driver: DRIVER_KIND,
756 instanceId,
757 detail: `Failed to probe OpenCode for '${cwd}'`,
758 cause,
759 }),
760 ),
761 Effect.flatMap((probed) =>
762 byOpenCodeRuntime(Effect.succeed(probed), {
763 v2: Effect.all(
764 [
765 snapshot.getSnapshot,
766 // A project's opencode.jsonc can define its own providers.
767 openCode2Server
768 .withConnection(({ client, events, url }) => {
769 const read = loadOpenCode2DirectoryCatalog(client, cwd);
770 return readSettledOpenCode2Catalog(read, processEnv).pipe(
771 Effect.tap((settled) =>
772 catalogWatch.follow(url, events, read, {
773 cwd,
774 ...Option.match(settled, {
775 onNone: () => ({}),
776 onSome: (catalog) => ({ settled: catalog }),
777 }),
778 }),
779 ),
780 );
781 })
782 .pipe(
783 Effect.orElseSucceed(() => Option.none<ReadonlyArray<OpenCode2Model>>()),
784 Effect.map(
785 Option.map((catalog) =>
786 openCode2ProviderModels(effectiveConfig, catalog),
787 ),
788 ),
789 ),
790 listOpenCode2Workspace(cwd).pipe(
791 // Leaves room for the reads around the scan wait, which uses the same override.
792 Effect.timeout(
793 2 * resolveProviderProbeTimeoutMs("opencode", 10_000, processEnv),
794 ),
795 Effect.mapError(
796 (cause) =>
797 new ProviderDriverError({
798 driver: DRIVER_KIND,
799 instanceId,
800 detail: `Failed to list OpenCode commands and skills for '${cwd}'`,
801 cause,
802 }),
803 ),
804 ),
805 ],
806 { concurrency: "unbounded" },
807 ).pipe(
808 Effect.map(([machineSnapshot, cwdModels, { skills, commands }]) => ({
809 ...machineSnapshot,
810 ...workspaceModelsFor(machineSnapshot.models, cwdModels),
811 skills: openCode2SkillsToServerProviderSkills(skills),
812 slashCommands: openCode2CommandsToServerProviderSlashCommands(commands),
813 // A finished scan lists at least the built-ins. None means it
814 // timed out, so the registry decides from the provider's health.
815 slashCommandsPending: commands.length > 0 ? false : undefined,
816 })),
817 ),
818 v1: Effect.all([
819 snapshot.getSnapshot,
820 loadWorkspaceForCwd(cwd).pipe(
821 // Leaves room for connection setup before the command fallback below.
822 Effect.timeout(
823 2 * resolveProviderProbeTimeoutMs("opencode", 10_000, processEnv),
824 ),
825 ),
826 ]).pipe(
827 Effect.map(
828 ([machineSnapshot, { skills, models, commands, slashCommandsPending }]) => ({
829 ...machineSnapshot,
830 ...workspaceModelsFor(machineSnapshot.models, models),
831 skills: openCodeSkillsToServerProviderSkills(skills),
832 slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),
833 slashCommandsPending,
834 }),
835 ),
836 Effect.mapError(
837 (cause) =>
838 new ProviderDriverError({
839 driver: DRIVER_KIND,
840 instanceId,
841 detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,
842 cause,
843 }),
844 ),
845 ),
846 }),
847 ),
848 ),
849 workspaceRescans: catalogWatch.rescans,
850 invalidateCaches: openCode2Server.forget,
851 afterUpdate,
852 orchestrationAdapter,
853 textGeneration,
854 } satisfies ProviderInstance;
855 }),
856};