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 * as NodeURL from "node:url"; |
| 3 | |
| 4 | import type { ChatAttachment, ProviderApprovalDecision } from "@t3tools/contracts"; |
| 5 | import { |
| 6 | createOpencodeClient, |
| 7 | type Agent, |
| 8 | type Command, |
| 9 | type FilePartInput, |
| 10 | type OpencodeClient, |
| 11 | type ProviderListResponse, |
| 12 | type QuestionAnswer, |
| 13 | type QuestionRequest, |
| 14 | } from "@opencode-ai/sdk/v2"; |
| 15 | import * as Cause from "effect/Cause"; |
| 16 | import * as Context from "effect/Context"; |
| 17 | import * as Deferred from "effect/Deferred"; |
| 18 | import * as Effect from "effect/Effect"; |
| 19 | import * as Exit from "effect/Exit"; |
| 20 | import * as Fiber from "effect/Fiber"; |
| 21 | import * as Layer from "effect/Layer"; |
| 22 | import * as Option from "effect/Option"; |
| 23 | import * as P from "effect/Predicate"; |
| 24 | import * as Ref from "effect/Ref"; |
| 25 | import * as Result from "effect/Result"; |
| 26 | import * as Scope from "effect/Scope"; |
| 27 | import * as Schema from "effect/Schema"; |
| 28 | import * as Schedule from "effect/Schedule"; |
| 29 | import * as Stream from "effect/Stream"; |
| 30 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 31 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 32 | |
| 33 | import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; |
| 34 | import { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshotProbe"; |
| 35 | import * as OpenCodeServerLedger from "./OpenCodeServerLedger.ts"; |
| 36 | import { collectStreamAsString } from "@t3tools/provider-core/server/snapshotProbe"; |
| 37 | import * as NetService from "@t3tools/shared/Net"; |
| 38 | import { AgentScope } from "@t3tools/shared/AgentScope"; |
| 39 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 40 | import { parseSemver } from "@t3tools/shared/semver"; |
| 41 | import { resolveSpawnCommand } from "@t3tools/shared/shell"; |
| 42 | const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown)); |
| 43 | const OPENCODE_EMPTY_CONFIG_CONTENT = "{}"; |
| 44 | |
| 45 | const OPENCODE_HEALTH_TIMEOUT_MS = 5_000; |
| 46 | |
| 47 | const OpenCodeHealthSchema = Schema.Struct({ |
| 48 | healthy: Schema.Literal(true), |
| 49 | version: Schema.String, |
| 50 | }); |
| 51 | const decodeOpenCodeHealth = Schema.decodeUnknownEffect(OpenCodeHealthSchema); |
| 52 | |
| 53 | function resolveOpenCodeConfigContent( |
| 54 | inputEnvironment: Readonly<Record<string, string | undefined>> | undefined, |
| 55 | inheritedEnvironment: Readonly<Record<string, string | undefined>> = process.env, |
| 56 | ): string { |
| 57 | return ( |
| 58 | inputEnvironment?.OPENCODE_CONFIG_CONTENT ?? |
| 59 | inheritedEnvironment.OPENCODE_CONFIG_CONTENT ?? |
| 60 | OPENCODE_EMPTY_CONFIG_CONTENT |
| 61 | ); |
| 62 | } |
| 63 | |
| 64 | export function resolveOpenCodeServerPassword( |
| 65 | input: { |
| 66 | readonly external: boolean; |
| 67 | readonly serverPassword?: string; |
| 68 | readonly environment?: Readonly<Record<string, string | undefined>>; |
| 69 | }, |
| 70 | inheritedEnvironment: Readonly<Record<string, string | undefined>> = process.env, |
| 71 | ): string | undefined { |
| 72 | if (input.serverPassword !== undefined) { |
| 73 | return input.serverPassword; |
| 74 | } |
| 75 | if (input.external) { |
| 76 | return undefined; |
| 77 | } |
| 78 | return input.environment === undefined |
| 79 | ? inheritedEnvironment.OPENCODE_SERVER_PASSWORD |
| 80 | : input.environment.OPENCODE_SERVER_PASSWORD; |
| 81 | } |
| 82 | |
| 83 | const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 30_000; |
| 84 | const DEFAULT_HOSTNAME = "127.0.0.1"; |
| 85 | const OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS = 64 * 1024; |
| 86 | const OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT = "500 millis"; |
| 87 | const OPENCODE_SERVER_TERMINATE_GRACE = "1 second"; |
| 88 | export interface OpenCodeServerProcess { |
| 89 | readonly url: string; |
| 90 | readonly serverPassword?: string; |
| 91 | readonly version: string; |
| 92 | readonly isRunning: Effect.Effect<boolean>; |
| 93 | readonly exitCode: Effect.Effect<number, never>; |
| 94 | } |
| 95 | |
| 96 | export interface OpenCodeServerConnection { |
| 97 | readonly url: string; |
| 98 | readonly serverPassword?: string; |
| 99 | readonly version: string; |
| 100 | readonly exitCode: Effect.Effect<number, never> | null; |
| 101 | readonly external: boolean; |
| 102 | } |
| 103 | |
| 104 | const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError"; |
| 105 | const OpenCodeStartupFailureReason = Schema.Literal("databaseLocked"); |
| 106 | export type OpenCodeStartupFailureReason = typeof OpenCodeStartupFailureReason.Type; |
| 107 | |
| 108 | export class OpenCodeRuntimeError extends Schema.TaggedError<OpenCodeRuntimeError>()( |
| 109 | OPENCODE_RUNTIME_ERROR_TAG, |
| 110 | { |
| 111 | operation: Schema.String, |
| 112 | cause: Schema.optional(Schema.Defect()), |
| 113 | detail: Schema.String, |
| 114 | reason: Schema.optional(OpenCodeStartupFailureReason), |
| 115 | }, |
| 116 | ) {} |
| 117 | |
| 118 | // Classify stderr database locks at exit so callers need not parse diagnostics. |
| 119 | function classifyStartupExit(stderr: string): OpenCodeStartupFailureReason | undefined { |
| 120 | return /SQLITE_BUSY|database is locked/i.test(stderr) ? "databaseLocked" : undefined; |
| 121 | } |
| 122 | |
| 123 | export const isOpenCodeRuntimeError = (u: unknown): u is OpenCodeRuntimeError => |
| 124 | P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG); |
| 125 | |
| 126 | function encodeJsonStringForDiagnostics(input: unknown): string | undefined { |
| 127 | const result = encodeUnknownJsonStringExit(input); |
| 128 | return Exit.isSuccess(result) ? result.value : undefined; |
| 129 | } |
| 130 | |
| 131 | export function openCodeRuntimeErrorDetail(cause: unknown): string { |
| 132 | if (isOpenCodeRuntimeError(cause)) return cause.detail; |
| 133 | // Effect TimeoutError can have a non-string message. |
| 134 | if (cause instanceof Error) { |
| 135 | const message = cause.message; |
| 136 | if (typeof message === "string") { |
| 137 | const trimmedMessage = message.trim(); |
| 138 | if (trimmedMessage.length > 0) return trimmedMessage; |
| 139 | } |
| 140 | } |
| 141 | if (cause && typeof cause === "object") { |
| 142 | // SDK v2 throws response/request/error envelopes. |
| 143 | const anyCause = cause as Record<string, unknown>; |
| 144 | const status = (anyCause.response as { status?: number } | undefined)?.status; |
| 145 | const body = anyCause.error ?? anyCause.data ?? anyCause.body; |
| 146 | const encodedBody = encodeJsonStringForDiagnostics(body ?? cause); |
| 147 | if (encodedBody) { |
| 148 | return `status=${status ?? "?"} body=${encodedBody}`; |
| 149 | } |
| 150 | } |
| 151 | return String(cause); |
| 152 | } |
| 153 | |
| 154 | export const runOpenCodeSdk = <A>( |
| 155 | operation: string, |
| 156 | fn: (signal: AbortSignal) => Promise<A>, |
| 157 | ): Effect.Effect<A, OpenCodeRuntimeError> => |
| 158 | Effect.tryPromise({ |
| 159 | try: fn, |
| 160 | catch: (cause) => |
| 161 | new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }), |
| 162 | }).pipe(Effect.withSpan(`opencode.${operation}`)); |
| 163 | |
| 164 | const verifyOpenCodeServerVersion = Effect.fn("verifyOpenCodeServerVersion")(function* ( |
| 165 | client: OpencodeClient, |
| 166 | environment?: NodeJS.ProcessEnv, |
| 167 | ) { |
| 168 | const healthOption = yield* runOpenCodeSdk("global.health", (signal) => |
| 169 | client.global.health({ signal }), |
| 170 | ).pipe( |
| 171 | Effect.timeoutOption( |
| 172 | resolveProviderProbeTimeoutMs("opencode", OPENCODE_HEALTH_TIMEOUT_MS, environment), |
| 173 | ), |
| 174 | ); |
| 175 | if (Option.isNone(healthOption)) { |
| 176 | return yield* new OpenCodeRuntimeError({ |
| 177 | operation: "global.health", |
| 178 | detail: "Timed out while checking the OpenCode server version.", |
| 179 | }); |
| 180 | } |
| 181 | |
| 182 | const health = yield* decodeOpenCodeHealth(healthOption.value.data).pipe( |
| 183 | Effect.mapError( |
| 184 | (cause) => |
| 185 | new OpenCodeRuntimeError({ |
| 186 | operation: "global.health", |
| 187 | detail: "OpenCode server returned an invalid health response.", |
| 188 | cause, |
| 189 | }), |
| 190 | ), |
| 191 | ); |
| 192 | if (parseSemver(health.version) === null) { |
| 193 | return yield* new OpenCodeRuntimeError({ |
| 194 | operation: "global.health", |
| 195 | detail: "OpenCode server returned an invalid version.", |
| 196 | }); |
| 197 | } |
| 198 | return health.version; |
| 199 | }); |
| 200 | |
| 201 | export interface OpenCodeCommandResult { |
| 202 | readonly stdout: string; |
| 203 | readonly stderr: string; |
| 204 | readonly code: number; |
| 205 | } |
| 206 | |
| 207 | export interface OpenCodeInventory { |
| 208 | readonly providerList: ProviderListResponse; |
| 209 | readonly agents: ReadonlyArray<Agent>; |
| 210 | readonly skills: ReadonlyArray<OpenCodeSkill>; |
| 211 | readonly commands?: ReadonlyArray<OpenCodeSlashCommand>; |
| 212 | } |
| 213 | |
| 214 | export type OpenCodeSlashCommand = Pick<Command, "name" | "description" | "source" | "hints">; |
| 215 | |
| 216 | export const loadOpenCodeCommands = (client: OpencodeClient) => |
| 217 | runOpenCodeSdk("command.list", (signal) => client.command.list(undefined, { signal })).pipe( |
| 218 | Effect.map((result): ReadonlyArray<OpenCodeSlashCommand> => |
| 219 | (result.data ?? []).map(({ name, description, source, hints }) => ({ |
| 220 | name, |
| 221 | ...(description === undefined ? {} : { description }), |
| 222 | ...(source === undefined ? {} : { source }), |
| 223 | hints, |
| 224 | })), |
| 225 | ), |
| 226 | ); |
| 227 | |
| 228 | const loadOpenCodeProviders = (client: OpencodeClient) => |
| 229 | runOpenCodeSdk("provider.list", (signal) => client.provider.list(undefined, { signal })).pipe( |
| 230 | Effect.filterMapOrFail( |
| 231 | (list) => |
| 232 | list.data |
| 233 | ? Result.succeed(list.data) |
| 234 | : Result.fail( |
| 235 | new OpenCodeRuntimeError({ |
| 236 | operation: "provider.list", |
| 237 | detail: "OpenCode provider list was empty.", |
| 238 | }), |
| 239 | ), |
| 240 | (result) => result, |
| 241 | ), |
| 242 | ); |
| 243 | |
| 244 | const loadOpenCodeAgents = (client: OpencodeClient) => |
| 245 | runOpenCodeSdk("app.agents", (signal) => client.app.agents(undefined, { signal })).pipe( |
| 246 | Effect.map((result): ReadonlyArray<Agent> => result.data ?? []), |
| 247 | ); |
| 248 | |
| 249 | /** The providers and agents OpenCode resolves for the client's directory. Fails if either read does. */ |
| 250 | export const loadOpenCodeProviderCatalog = Effect.fn("OpenCodeRuntime.loadOpenCodeProviderCatalog")( |
| 251 | (client: OpencodeClient) => |
| 252 | Effect.all( |
| 253 | { providerList: loadOpenCodeProviders(client), agents: loadOpenCodeAgents(client) }, |
| 254 | { concurrency: "unbounded" }, |
| 255 | ), |
| 256 | ); |
| 257 | |
| 258 | export interface ParsedOpenCodeModelSlug { |
| 259 | readonly providerID: string; |
| 260 | readonly modelID: string; |
| 261 | } |
| 262 | |
| 263 | export interface OpenCodeCatalogModel { |
| 264 | readonly variants: ReadonlySet<string>; |
| 265 | readonly contextWindow: number | undefined; |
| 266 | } |
| 267 | |
| 268 | export type OpenCodeVariantCache = Map<string, OpenCodeCatalogModel | undefined>; |
| 269 | |
| 270 | /** The model's catalog entry; a failed read returns undefined and is not cached. */ |
| 271 | export const readOpenCodeCatalogModel = Effect.fnUntraced(function* ( |
| 272 | client: OpencodeClient, |
| 273 | model: ParsedOpenCodeModelSlug, |
| 274 | abortSignal?: AbortSignal, |
| 275 | cache?: OpenCodeVariantCache, |
| 276 | ) { |
| 277 | const key = `${model.providerID}/${model.modelID}`; |
| 278 | if (cache?.has(key)) return cache.get(key); |
| 279 | |
| 280 | const response = yield* runOpenCodeSdk("provider.list", (signal) => |
| 281 | client.provider.list(undefined, { |
| 282 | signal: abortSignal ? AbortSignal.any([signal, abortSignal]) : signal, |
| 283 | }), |
| 284 | ).pipe( |
| 285 | Effect.timeout("10 seconds"), |
| 286 | Effect.orElseSucceed(() => undefined), |
| 287 | ); |
| 288 | if (response?.data === undefined) return undefined; |
| 289 | |
| 290 | const catalogModel = response.data.all.find((provider) => provider.id === model.providerID) |
| 291 | ?.models[model.modelID]; |
| 292 | const entry: OpenCodeCatalogModel | undefined = catalogModel && { |
| 293 | variants: new Set(Object.keys(catalogModel.variants ?? {})), |
| 294 | contextWindow: catalogModel.limit?.input ?? catalogModel.limit?.context, |
| 295 | }; |
| 296 | // Keep only what this model needs; provider.list can return several megabytes. |
| 297 | cache?.set(key, entry); |
| 298 | return entry; |
| 299 | }); |
| 300 | |
| 301 | export const resolveOpenCodeVariant = Effect.fnUntraced(function* ( |
| 302 | client: OpencodeClient, |
| 303 | model: ParsedOpenCodeModelSlug | undefined, |
| 304 | variant: string | undefined, |
| 305 | abortSignal?: AbortSignal, |
| 306 | cache?: OpenCodeVariantCache, |
| 307 | ) { |
| 308 | if (!variant || !model) return variant; |
| 309 | // Only a confirmed catalog mismatch can invalidate a persisted selection. |
| 310 | const entry = yield* readOpenCodeCatalogModel(client, model, abortSignal, cache); |
| 311 | return entry !== undefined && !entry.variants.has(variant) ? undefined : variant; |
| 312 | }); |
| 313 | |
| 314 | export interface OpenCodeSkill { |
| 315 | readonly name?: string | null; |
| 316 | readonly description?: string | null; |
| 317 | readonly location?: string | null; |
| 318 | } |
| 319 | |
| 320 | export class OpenCodeRuntime extends Context.Service< |
| 321 | OpenCodeRuntime, |
| 322 | { |
| 323 | /** Closing the caller's scope kills the child. */ |
| 324 | readonly startOpenCodeServerProcess: (input: { |
| 325 | readonly binaryPath: string; |
| 326 | readonly directory: string; |
| 327 | readonly serverPassword?: string; |
| 328 | readonly environment?: NodeJS.ProcessEnv; |
| 329 | readonly port?: number; |
| 330 | readonly hostname?: string; |
| 331 | readonly timeoutMs?: number; |
| 332 | readonly verify?: (url: string) => Effect.Effect<string, OpenCodeRuntimeError>; |
| 333 | }) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>; |
| 334 | readonly connectToOpenCodeServer: (input: { |
| 335 | readonly binaryPath: string; |
| 336 | readonly directory: string; |
| 337 | readonly serverUrl?: string | null; |
| 338 | readonly serverPassword?: string; |
| 339 | readonly environment?: NodeJS.ProcessEnv; |
| 340 | readonly port?: number; |
| 341 | readonly hostname?: string; |
| 342 | readonly timeoutMs?: number; |
| 343 | }) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>; |
| 344 | readonly runOpenCodeCommand: (input: { |
| 345 | readonly binaryPath: string; |
| 346 | readonly args: ReadonlyArray<string>; |
| 347 | readonly environment?: NodeJS.ProcessEnv; |
| 348 | readonly cwd?: string; |
| 349 | }) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>; |
| 350 | readonly createOpenCodeSdkClient: (input: { |
| 351 | readonly baseUrl: string; |
| 352 | readonly directory: string; |
| 353 | readonly serverPassword?: string; |
| 354 | }) => OpencodeClient; |
| 355 | readonly loadOpenCodeInventory: ( |
| 356 | client: OpencodeClient, |
| 357 | ) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>; |
| 358 | readonly loadOpenCodeSkills: ( |
| 359 | client: OpencodeClient, |
| 360 | ) => Effect.Effect<ReadonlyArray<OpenCodeSkill>, OpenCodeRuntimeError>; |
| 361 | } |
| 362 | >()("@t3tools/provider-opencode/server/OpenCodeRuntime") {} |
| 363 | |
| 364 | export function parseServerUrlFromOutput(output: string): string | null { |
| 365 | // The last element is an unfinished line; a chunk can end mid-URL. |
| 366 | for (const line of output.split("\n").slice(0, -1)) { |
| 367 | const match = line.match(/server listening on\s+(https?:\/\/[^\s]+)/i); |
| 368 | if (match?.[1]) return match[1]; |
| 369 | } |
| 370 | return null; |
| 371 | } |
| 372 | |
| 373 | export function parseOpenCodeModelSlug( |
| 374 | slug: string | null | undefined, |
| 375 | ): ParsedOpenCodeModelSlug | null { |
| 376 | if (typeof slug !== "string") { |
| 377 | return null; |
| 378 | } |
| 379 | |
| 380 | const trimmed = slug.trim(); |
| 381 | const separator = trimmed.indexOf("/"); |
| 382 | if (separator <= 0 || separator === trimmed.length - 1) { |
| 383 | return null; |
| 384 | } |
| 385 | |
| 386 | return { |
| 387 | providerID: trimmed.slice(0, separator), |
| 388 | modelID: trimmed.slice(separator + 1), |
| 389 | }; |
| 390 | } |
| 391 | |
| 392 | export function openCodeQuestionId( |
| 393 | index: number, |
| 394 | question: QuestionRequest["questions"][number], |
| 395 | ): string { |
| 396 | const header = question.header |
| 397 | .trim() |
| 398 | .toLowerCase() |
| 399 | .replace(/[^a-z0-9_-]+/g, "-"); |
| 400 | return header.length > 0 ? `question-${index}-${header}` : `question-${index}`; |
| 401 | } |
| 402 | |
| 403 | // OpenCode inlines only text/plain; other text MIME parts reach APIs that reject them. |
| 404 | const OPENCODE_NATIVE_IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]); |
| 405 | const OPENCODE_NATIVE_FILE_PART_MAX_BYTES = 20 * 1024 * 1024; |
| 406 | |
| 407 | function isOpenCodeNativeFilePart(input: { |
| 408 | readonly mimeType: string; |
| 409 | readonly sizeBytes: number; |
| 410 | }): boolean { |
| 411 | if (input.sizeBytes > OPENCODE_NATIVE_FILE_PART_MAX_BYTES) { |
| 412 | return false; |
| 413 | } |
| 414 | const normalized = input.mimeType.trim().toLowerCase(); |
| 415 | return ( |
| 416 | OPENCODE_NATIVE_IMAGE_MIMES.has(normalized) || |
| 417 | normalized === "text/plain" || |
| 418 | normalized === "application/pdf" |
| 419 | ); |
| 420 | } |
| 421 | |
| 422 | export function toOpenCodeFileParts(input: { |
| 423 | readonly attachments: ReadonlyArray<ChatAttachment> | undefined; |
| 424 | readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null; |
| 425 | }): Array<FilePartInput> { |
| 426 | const parts: Array<FilePartInput> = []; |
| 427 | |
| 428 | for (const attachment of input.attachments ?? []) { |
| 429 | if ( |
| 430 | attachment.type === "file" && |
| 431 | "source" in attachment && |
| 432 | attachment.source?._tag === "pasted-text" |
| 433 | ) { |
| 434 | continue; |
| 435 | } |
| 436 | if (!isOpenCodeNativeFilePart(attachment)) { |
| 437 | continue; |
| 438 | } |
| 439 | const attachmentPath = input.resolveAttachmentPath(attachment); |
| 440 | if (!attachmentPath) { |
| 441 | continue; |
| 442 | } |
| 443 | |
| 444 | parts.push({ |
| 445 | type: "file", |
| 446 | mime: attachment.mimeType, |
| 447 | filename: attachment.name, |
| 448 | url: NodeURL.pathToFileURL(attachmentPath).href, |
| 449 | }); |
| 450 | } |
| 451 | |
| 452 | return parts; |
| 453 | } |
| 454 | |
| 455 | export function toOpenCodePermissionReply( |
| 456 | decision: ProviderApprovalDecision, |
| 457 | ): "once" | "always" | "reject" { |
| 458 | switch (decision) { |
| 459 | case "accept": |
| 460 | return "once"; |
| 461 | case "acceptForSession": |
| 462 | case "acceptAlways": |
| 463 | return "always"; |
| 464 | case "decline": |
| 465 | case "cancel": |
| 466 | default: |
| 467 | return "reject"; |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | export function toOpenCodeQuestionAnswers( |
| 472 | request: QuestionRequest, |
| 473 | answers: Record<string, unknown>, |
| 474 | ): Array<QuestionAnswer> { |
| 475 | return request.questions.map((question, index) => { |
| 476 | const raw = |
| 477 | answers[openCodeQuestionId(index, question)] ?? |
| 478 | answers[question.header] ?? |
| 479 | answers[question.question]; |
| 480 | if (Array.isArray(raw)) { |
| 481 | return raw.filter((value): value is string => typeof value === "string"); |
| 482 | } |
| 483 | if (typeof raw === "string") { |
| 484 | return raw.trim().length > 0 ? [raw] : []; |
| 485 | } |
| 486 | return []; |
| 487 | }); |
| 488 | } |
| 489 | |
| 490 | function ensureRuntimeError( |
| 491 | operation: OpenCodeRuntimeError["operation"], |
| 492 | detail: string, |
| 493 | cause: unknown, |
| 494 | ): OpenCodeRuntimeError { |
| 495 | return isOpenCodeRuntimeError(cause) |
| 496 | ? cause |
| 497 | : new OpenCodeRuntimeError({ operation, detail, cause }); |
| 498 | } |
| 499 | |
| 500 | const makeOpenCodeRuntime = Effect.gen(function* () { |
| 501 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 502 | const netService = yield* NetService.NetService; |
| 503 | const hostPlatform = yield* HostProcess.Platform; |
| 504 | const serverLedger = yield* OpenCodeServerLedger.OpenCodeServerLedger; |
| 505 | const agentScope = yield* AgentScope; |
| 506 | // npm's Windows shim lets the child escape libuv kill-on-close; run its executable directly. |
| 507 | const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) => |
| 508 | resolveSpawnCommand(command, args, { ...(env ? { env } : {}), bypassNpmShim: true }); |
| 509 | |
| 510 | const runOpenCodeCommand: OpenCodeRuntime["Service"]["runOpenCodeCommand"] = Effect.fn( |
| 511 | "OpenCodeRuntime.runOpenCodeCommand", |
| 512 | )( |
| 513 | function* (input) { |
| 514 | const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment); |
| 515 | const child = yield* spawner.spawn( |
| 516 | ChildProcess.make(spawnCommand.command, spawnCommand.args, { |
| 517 | detached: hostPlatform !== "win32", |
| 518 | shell: spawnCommand.shell, |
| 519 | ...(input.cwd ? { cwd: input.cwd } : {}), |
| 520 | ...(input.environment ? { env: input.environment } : { extendEnv: true }), |
| 521 | }), |
| 522 | ); |
| 523 | const terminateCommandGroup = |
| 524 | hostPlatform === "win32" |
| 525 | ? child.kill({ killSignal: "SIGKILL" }).pipe(Effect.asVoid) |
| 526 | : Effect.sync(() => { |
| 527 | try { |
| 528 | signalProcessGroup(Number(child.pid), "SIGKILL"); |
| 529 | } catch {} |
| 530 | }); |
| 531 | yield* Effect.addFinalizer(() => terminateCommandGroup.pipe(Effect.ignore)); |
| 532 | const [stdout, stderr, code] = yield* Effect.all( |
| 533 | [collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode], |
| 534 | { concurrency: "unbounded" }, |
| 535 | ); |
| 536 | const exitCode = Number(code); |
| 537 | if (yield* isWindowsCommandNotFound(exitCode, stderr)) { |
| 538 | return yield* new OpenCodeRuntimeError({ |
| 539 | operation: "runOpenCodeCommand", |
| 540 | detail: `spawn ${input.binaryPath} ENOENT`, |
| 541 | }); |
| 542 | } |
| 543 | return { |
| 544 | stdout, |
| 545 | stderr, |
| 546 | code: exitCode, |
| 547 | } satisfies OpenCodeCommandResult; |
| 548 | }, |
| 549 | (effect, input) => |
| 550 | effect.pipe( |
| 551 | Effect.scoped, |
| 552 | Effect.mapError((cause) => |
| 553 | ensureRuntimeError( |
| 554 | "runOpenCodeCommand", |
| 555 | `Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`, |
| 556 | cause, |
| 557 | ), |
| 558 | ), |
| 559 | ), |
| 560 | ); |
| 561 | |
| 562 | const createOpenCodeSdkClient: OpenCodeRuntime["Service"]["createOpenCodeSdkClient"] = (input) => |
| 563 | createOpencodeClient({ |
| 564 | baseUrl: input.baseUrl, |
| 565 | directory: input.directory, |
| 566 | ...(input.serverPassword |
| 567 | ? { |
| 568 | headers: { |
| 569 | Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`, |
| 570 | }, |
| 571 | } |
| 572 | : {}), |
| 573 | throwOnError: true, |
| 574 | }); |
| 575 | |
| 576 | const startServerAttempt: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = Effect.fn( |
| 577 | "OpenCodeRuntime.startServerAttempt", |
| 578 | )(function* (input) { |
| 579 | const runtimeScope = yield* Scope.Scope; |
| 580 | |
| 581 | const hostname = input.hostname ?? DEFAULT_HOSTNAME; |
| 582 | const port = |
| 583 | input.port ?? |
| 584 | (yield* netService.findAvailablePort(0).pipe( |
| 585 | Effect.mapError( |
| 586 | (cause) => |
| 587 | new OpenCodeRuntimeError({ |
| 588 | operation: "startOpenCodeServerProcess", |
| 589 | detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`, |
| 590 | cause, |
| 591 | }), |
| 592 | ), |
| 593 | )); |
| 594 | const timeoutMs = |
| 595 | input.timeoutMs ?? |
| 596 | resolveProviderProbeTimeoutMs( |
| 597 | "opencode", |
| 598 | DEFAULT_OPENCODE_SERVER_TIMEOUT_MS, |
| 599 | input.environment, |
| 600 | ); |
| 601 | const args = ["serve", `--hostname=${hostname}`, `--port=${port}`]; |
| 602 | const launch = yield* agentScope.wrap({ |
| 603 | command: input.binaryPath, |
| 604 | args, |
| 605 | name: "opencode", |
| 606 | env: input.environment, |
| 607 | shared: true, |
| 608 | }); |
| 609 | const spawnCommand = yield* resolveCommand(launch.command, launch.args, input.environment); |
| 610 | const serverPassword = resolveOpenCodeServerPassword({ |
| 611 | external: false, |
| 612 | ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}), |
| 613 | ...(input.environment !== undefined ? { environment: input.environment } : {}), |
| 614 | }); |
| 615 | |
| 616 | // Scopes close in reverse order. Forking this before the group kill is |
| 617 | // registered forgets the ledger entry only once the group is stopped. |
| 618 | const ledgerScope = yield* Scope.fork(runtimeScope); |
| 619 | const child = yield* spawner |
| 620 | .spawn( |
| 621 | ChildProcess.make(spawnCommand.command, spawnCommand.args, { |
| 622 | detached: hostPlatform !== "win32", |
| 623 | shell: spawnCommand.shell, |
| 624 | env: { |
| 625 | ...input.environment, |
| 626 | ...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}), |
| 627 | // The value is set explicitly (rather than relying on inheritance) because |
| 628 | // `extendEnv` is false whenever `input.environment` is provided. |
| 629 | OPENCODE_CONFIG_CONTENT: resolveOpenCodeConfigContent(input.environment), |
| 630 | }, |
| 631 | extendEnv: input.environment === undefined, |
| 632 | }), |
| 633 | ) |
| 634 | .pipe( |
| 635 | Effect.provideService(Scope.Scope, runtimeScope), |
| 636 | Effect.mapError( |
| 637 | (cause) => |
| 638 | new OpenCodeRuntimeError({ |
| 639 | operation: "startOpenCodeServerProcess", |
| 640 | detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`, |
| 641 | cause, |
| 642 | }), |
| 643 | ), |
| 644 | ); |
| 645 | |
| 646 | // Signals the server's own group and force-kills only what outlives the grace, |
| 647 | // so a group that exits promptly does not hold up the scope that closes it. |
| 648 | const terminateChild = child |
| 649 | .kill({ killSignal: "SIGTERM", forceKillAfter: OPENCODE_SERVER_TERMINATE_GRACE }) |
| 650 | .pipe(Effect.ignore); |
| 651 | // Registered before recording, so an interrupt while the ledger writes |
| 652 | // still stops the group. |
| 653 | yield* Scope.addFinalizer(runtimeScope, terminateChild); |
| 654 | const forgetServer = yield* serverLedger.track({ pid: Number(child.pid), port, args }); |
| 655 | yield* Scope.addFinalizer(ledgerScope, forgetServer); |
| 656 | |
| 657 | const stdoutRef = yield* Ref.make<string | null>(""); |
| 658 | const stderrRef = yield* Ref.make<string | null>(""); |
| 659 | const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>(); |
| 660 | |
| 661 | const setReadyFromStdoutChunk = (chunk: string) => |
| 662 | Ref.modify(stdoutRef, (stdout) => { |
| 663 | if (stdout === null) { |
| 664 | return [null, null] as const; |
| 665 | } |
| 666 | const nextStdout = `${stdout}${chunk}`; |
| 667 | return [ |
| 668 | parseServerUrlFromOutput(nextStdout), |
| 669 | nextStdout.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS), |
| 670 | ] as const; |
| 671 | }).pipe( |
| 672 | Effect.flatMap((parsed) => |
| 673 | parsed ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore) : Effect.void, |
| 674 | ), |
| 675 | ); |
| 676 | |
| 677 | const stdoutFiber = yield* child.stdout.pipe( |
| 678 | Stream.decodeText(), |
| 679 | Stream.runForEach(setReadyFromStdoutChunk), |
| 680 | Effect.ignore, |
| 681 | Effect.forkIn(runtimeScope), |
| 682 | ); |
| 683 | const stderrFiber = yield* child.stderr.pipe( |
| 684 | Stream.decodeText(), |
| 685 | Stream.runForEach((chunk) => |
| 686 | Ref.update(stderrRef, (stderr) => |
| 687 | stderr === null |
| 688 | ? null |
| 689 | : `${stderr}${chunk}`.slice(-OPENCODE_SERVER_STARTUP_MAX_OUTPUT_CHARS), |
| 690 | ), |
| 691 | ), |
| 692 | Effect.ignore, |
| 693 | Effect.forkIn(runtimeScope), |
| 694 | ); |
| 695 | |
| 696 | const exitFiber = yield* child.exitCode.pipe( |
| 697 | Effect.flatMap((code) => |
| 698 | Effect.gen(function* () { |
| 699 | // Allow trailing diagnostics to drain, but descendants can keep pipes open. |
| 700 | const drained = yield* Fiber.joinAll([stdoutFiber, stderrFiber]).pipe( |
| 701 | Effect.timeoutOption(OPENCODE_SERVER_EXIT_DRAIN_TIMEOUT), |
| 702 | ); |
| 703 | if (Option.isNone(drained)) { |
| 704 | yield* Fiber.interruptAll([stdoutFiber, stderrFiber]); |
| 705 | } |
| 706 | const stdout = (yield* Ref.get(stdoutRef)) ?? ""; |
| 707 | const stderr = (yield* Ref.get(stderrRef)) ?? ""; |
| 708 | const exitCode = Number(code); |
| 709 | const reason = classifyStartupExit(stderr); |
| 710 | yield* Deferred.fail( |
| 711 | readyDeferred, |
| 712 | new OpenCodeRuntimeError({ |
| 713 | operation: "startOpenCodeServerProcess", |
| 714 | ...(reason ? { reason } : {}), |
| 715 | detail: [ |
| 716 | `OpenCode server exited before startup completed (code: ${String(exitCode)}).`, |
| 717 | stdout.trim() ? `stdout:\n${stdout.trim()}` : null, |
| 718 | stderr.trim() ? `stderr:\n${stderr.trim()}` : null, |
| 719 | ] |
| 720 | .filter(Boolean) |
| 721 | .join("\n\n"), |
| 722 | cause: { exitCode, stdout, stderr }, |
| 723 | }), |
| 724 | ).pipe(Effect.ignore); |
| 725 | }), |
| 726 | ), |
| 727 | Effect.ignore, |
| 728 | Effect.forkIn(runtimeScope), |
| 729 | ); |
| 730 | |
| 731 | const readyExit = yield* Effect.exit( |
| 732 | Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)), |
| 733 | ); |
| 734 | |
| 735 | if (Exit.isFailure(readyExit) || Option.isNone(readyExit.value)) { |
| 736 | yield* Fiber.interruptAll([stdoutFiber, stderrFiber, exitFiber]).pipe(Effect.ignore); |
| 737 | } |
| 738 | |
| 739 | if (Exit.isFailure(readyExit)) { |
| 740 | const squashed = Cause.squash(readyExit.cause); |
| 741 | return yield* ensureRuntimeError( |
| 742 | "startOpenCodeServerProcess", |
| 743 | `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`, |
| 744 | squashed, |
| 745 | ); |
| 746 | } |
| 747 | |
| 748 | const readyOption = readyExit.value; |
| 749 | if (Option.isNone(readyOption)) { |
| 750 | return yield* new OpenCodeRuntimeError({ |
| 751 | operation: "startOpenCodeServerProcess", |
| 752 | detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`, |
| 753 | }); |
| 754 | } |
| 755 | |
| 756 | // Keep draining both pipes until the process scope closes. Stopping the |
| 757 | // readers can block OpenCode when its output buffers fill. Startup output |
| 758 | // is no longer needed, so discard later output instead of retaining it. |
| 759 | yield* Ref.set(stdoutRef, null); |
| 760 | yield* Ref.set(stderrRef, null); |
| 761 | |
| 762 | const url = readyOption.value; |
| 763 | const version = yield* ( |
| 764 | input.verify?.(url) ?? |
| 765 | verifyOpenCodeServerVersion( |
| 766 | createOpenCodeSdkClient({ |
| 767 | baseUrl: url, |
| 768 | directory: input.directory, |
| 769 | ...(serverPassword !== undefined ? { serverPassword } : {}), |
| 770 | }), |
| 771 | input.environment, |
| 772 | ) |
| 773 | ); |
| 774 | |
| 775 | return { |
| 776 | url, |
| 777 | ...(serverPassword !== undefined ? { serverPassword } : {}), |
| 778 | version, |
| 779 | isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)), |
| 780 | exitCode: child.exitCode.pipe( |
| 781 | Effect.map(Number), |
| 782 | Effect.orElseSucceed(() => 0), |
| 783 | ), |
| 784 | } satisfies OpenCodeServerProcess; |
| 785 | }); |
| 786 | |
| 787 | const startOpenCodeServerProcess: OpenCodeRuntime["Service"]["startOpenCodeServerProcess"] = |
| 788 | Effect.fn("OpenCodeRuntime.startOpenCodeServerProcess")(function* (input) { |
| 789 | const ownerScope = yield* Scope.Scope; |
| 790 | const attempt = Effect.gen(function* () { |
| 791 | const attemptScope = yield* Scope.fork(ownerScope); |
| 792 | return yield* startServerAttempt(input).pipe( |
| 793 | Effect.provideService(Scope.Scope, attemptScope), |
| 794 | Effect.onExit((exit) => |
| 795 | Exit.isFailure(exit) ? Scope.close(attemptScope, exit) : Effect.void, |
| 796 | ), |
| 797 | ); |
| 798 | }); |
| 799 | // Shared opencode.db locks are transient; retry those, not configuration/executable errors. |
| 800 | return yield* attempt.pipe( |
| 801 | Effect.retry({ |
| 802 | times: 3, |
| 803 | schedule: Schedule.spaced("250 millis"), |
| 804 | while: (error) => error.reason === "databaseLocked", |
| 805 | }), |
| 806 | ); |
| 807 | }); |
| 808 | |
| 809 | const connectToOpenCodeServer: OpenCodeRuntime["Service"]["connectToOpenCodeServer"] = ( |
| 810 | input, |
| 811 | ) => { |
| 812 | const serverUrl = input.serverUrl?.trim(); |
| 813 | if (serverUrl) { |
| 814 | const serverPassword = resolveOpenCodeServerPassword({ |
| 815 | external: true, |
| 816 | ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}), |
| 817 | }); |
| 818 | return verifyOpenCodeServerVersion( |
| 819 | createOpenCodeSdkClient({ |
| 820 | baseUrl: serverUrl, |
| 821 | directory: input.directory, |
| 822 | ...(serverPassword !== undefined ? { serverPassword } : {}), |
| 823 | }), |
| 824 | input.environment, |
| 825 | ).pipe( |
| 826 | Effect.map((version) => ({ |
| 827 | url: serverUrl, |
| 828 | ...(serverPassword !== undefined ? { serverPassword } : {}), |
| 829 | version, |
| 830 | exitCode: null, |
| 831 | external: true, |
| 832 | })), |
| 833 | ); |
| 834 | } |
| 835 | |
| 836 | return startOpenCodeServerProcess({ |
| 837 | binaryPath: input.binaryPath, |
| 838 | directory: input.directory, |
| 839 | ...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}), |
| 840 | ...(input.environment !== undefined ? { environment: input.environment } : {}), |
| 841 | ...(input.port !== undefined ? { port: input.port } : {}), |
| 842 | ...(input.hostname !== undefined ? { hostname: input.hostname } : {}), |
| 843 | ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}), |
| 844 | }).pipe( |
| 845 | Effect.map((server) => ({ |
| 846 | url: server.url, |
| 847 | ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}), |
| 848 | version: server.version, |
| 849 | exitCode: server.exitCode, |
| 850 | external: false, |
| 851 | })), |
| 852 | ); |
| 853 | }; |
| 854 | |
| 855 | const loadOpenCodeSkills: OpenCodeRuntime["Service"]["loadOpenCodeSkills"] = (client) => |
| 856 | runOpenCodeSdk("app.skills", (signal) => client.app.skills(undefined, { signal })).pipe( |
| 857 | Effect.map((result) => |
| 858 | (result.data ?? []).map((skill) => ({ |
| 859 | name: skill.name, |
| 860 | ...(skill.description === undefined ? {} : { description: skill.description }), |
| 861 | location: skill.location, |
| 862 | })), |
| 863 | ), |
| 864 | ); |
| 865 | const loadSkills = (client: OpencodeClient) => |
| 866 | loadOpenCodeSkills(client).pipe(Effect.orElseSucceed((): ReadonlyArray<OpenCodeSkill> => [])); |
| 867 | |
| 868 | const loadOpenCodeInventory: OpenCodeRuntime["Service"]["loadOpenCodeInventory"] = (client) => |
| 869 | Effect.all( |
| 870 | [ |
| 871 | loadOpenCodeProviders(client), |
| 872 | loadOpenCodeAgents(client).pipe(Effect.orElseSucceed((): ReadonlyArray<Agent> => [])), |
| 873 | loadSkills(client), |
| 874 | loadOpenCodeCommands(client).pipe(Effect.orElseSucceed(() => [])), |
| 875 | ], |
| 876 | { |
| 877 | concurrency: "unbounded", |
| 878 | }, |
| 879 | ).pipe( |
| 880 | Effect.map(([providerList, agents, skills, commands]) => ({ |
| 881 | providerList, |
| 882 | agents, |
| 883 | skills, |
| 884 | commands, |
| 885 | })), |
| 886 | ); |
| 887 | |
| 888 | return { |
| 889 | startOpenCodeServerProcess, |
| 890 | connectToOpenCodeServer, |
| 891 | runOpenCodeCommand, |
| 892 | createOpenCodeSdkClient, |
| 893 | loadOpenCodeInventory, |
| 894 | loadOpenCodeSkills, |
| 895 | } satisfies OpenCodeRuntime["Service"]; |
| 896 | }); |
| 897 | |
| 898 | export const layer = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe( |
| 899 | Layer.provide(NetService.layer), |
| 900 | ); |