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