The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeAssert from "node:assert/strict"; |
| 2 | import * as NodeSqlite from "node:sqlite"; |
| 3 | |
| 4 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 5 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 6 | import { it } from "@effect/vitest"; |
| 7 | import * as Deferred from "effect/Deferred"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Fiber from "effect/Fiber"; |
| 10 | import * as FileSystem from "effect/FileSystem"; |
| 11 | import * as Layer from "effect/Layer"; |
| 12 | import * as Logger from "effect/Logger"; |
| 13 | import * as Schema from "effect/Schema"; |
| 14 | import * as Tracer from "effect/Tracer"; |
| 15 | import * as TestClock from "effect/testing/TestClock"; |
| 16 | import * as HttpClient from "effect/http/HttpClient"; |
| 17 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 18 | import { beforeEach } from "vite-plus/test"; |
| 19 | import { buildProviderOptionSelectionsFromDescriptors } from "@t3tools/shared/model"; |
| 20 | import { settingsSecretLiteral } from "@t3tools/contracts"; |
| 21 | |
| 22 | import { OpenCodeSettings } from "../settings.ts"; |
| 23 | import type { ProviderCompatibilityLookup } from "@t3tools/provider-core/server/compatibility"; |
| 24 | import * as OpenCodeRuntime from "./OpenCodeRuntime.ts"; |
| 25 | import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts"; |
| 26 | import { |
| 27 | checkOpenCodeProviderStatus, |
| 28 | loadOpenCode2Workspace, |
| 29 | makeOpenCode2ModelLoader, |
| 30 | type OpenCode2Model, |
| 31 | type OpenCode2Workspace, |
| 32 | } from "./status.ts"; |
| 33 | import { readOpenCodeGoUsageLimits } from "./usageLimits.ts"; |
| 34 | import { probeOpenCodeRuntime } from "./versionProbe.ts"; |
| 35 | import { |
| 36 | OPENCODE_1_RESPONSES, |
| 37 | OPENCODE_2_RESPONSES, |
| 38 | replayOpenCodeServer, |
| 39 | } from "./probeResponses.fixture.ts"; |
| 40 | const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings); |
| 41 | |
| 42 | const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n"; |
| 43 | |
| 44 | it.effect("reads Go limits with the instance's XDG credentials and preserves reset times", () => |
| 45 | Effect.gen(function* () { |
| 46 | const resetsAt = "2026-09-17T12:00:00.000Z"; |
| 47 | const limits = yield* readOpenCodeGoUsageLimits({ |
| 48 | enabled: true, |
| 49 | serverUrl: "", |
| 50 | environment: { XDG_DATA_HOME: "/instance/data", OPENCODE_API_KEY: "env-key" }, |
| 51 | }).pipe( |
| 52 | Effect.provideService( |
| 53 | FileSystem.FileSystem, |
| 54 | FileSystem.makeNoop({ |
| 55 | readFileString: (path) => { |
| 56 | NodeAssert.equal(path, "/instance/data/opencode/auth.json"); |
| 57 | return Effect.succeed( |
| 58 | JSON.stringify({ "opencode-go": { type: "api", key: "instance-key" } }), |
| 59 | ); |
| 60 | }, |
| 61 | }), |
| 62 | ), |
| 63 | Effect.provideService( |
| 64 | HttpClient.HttpClient, |
| 65 | HttpClient.make((request) => { |
| 66 | NodeAssert.equal(request.url, "https://opencode.ai/zen/go/v1/usage"); |
| 67 | NodeAssert.equal(request.headers.authorization, "Bearer instance-key"); |
| 68 | return Effect.succeed( |
| 69 | HttpClientResponse.fromWeb( |
| 70 | request, |
| 71 | Response.json({ |
| 72 | usage: { |
| 73 | rolling: { percent: 0, resetsAt }, |
| 74 | weekly: { percent: 10, resetsAt }, |
| 75 | monthly: { percent: 125, resetsAt }, |
| 76 | }, |
| 77 | }), |
| 78 | ), |
| 79 | ); |
| 80 | }), |
| 81 | ), |
| 82 | Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 83 | ); |
| 84 | NodeAssert.equal(limits.unavailable, undefined); |
| 85 | NodeAssert.equal( |
| 86 | limits.credentialFingerprint, |
| 87 | "aba48e85c981a8edc1c9fb4575121accc7235fa55d0f8689f66f153de5566a37", |
| 88 | ); |
| 89 | NodeAssert.deepEqual( |
| 90 | limits.windows.map(({ kind, usedPercent, resetsAt: reset }) => ({ |
| 91 | kind, |
| 92 | usedPercent, |
| 93 | reset, |
| 94 | })), |
| 95 | [ |
| 96 | { kind: "session", usedPercent: 0, reset: resetsAt }, |
| 97 | { kind: "weekly", usedPercent: 10, reset: resetsAt }, |
| 98 | { kind: "monthly", usedPercent: 100, reset: resetsAt }, |
| 99 | ], |
| 100 | ); |
| 101 | }), |
| 102 | ); |
| 103 | |
| 104 | it.effect( |
| 105 | "uses the selected public Console key for Go limits, falling back only on auth rejection", |
| 106 | () => |
| 107 | Effect.gen(function* () { |
| 108 | const fs = yield* FileSystem.FileSystem; |
| 109 | const dataHome = yield* fs.makeTempDirectoryScoped(); |
| 110 | yield* fs.makeDirectory(`${dataHome}/opencode`); |
| 111 | yield* fs.writeFileString( |
| 112 | `${dataHome}/opencode/auth.json`, |
| 113 | JSON.stringify({ "opencode-go": { type: "api", key: "go-key" } }), |
| 114 | ); |
| 115 | const database = yield* Effect.acquireRelease( |
| 116 | Effect.sync(() => new NodeSqlite.DatabaseSync(`${dataHome}/opencode/opencode.db`)), |
| 117 | (database) => Effect.sync(() => database.close()), |
| 118 | ); |
| 119 | database.exec( |
| 120 | "CREATE TABLE credential (id text PRIMARY KEY, integration_id text, value text, active integer, time_created integer, time_updated integer)", |
| 121 | ); |
| 122 | const insert = database.prepare("INSERT INTO credential VALUES (?, ?, ?, ?, ?, ?)"); |
| 123 | const window = { percent: 1, resetsAt: "2026-09-17T12:00:00.000Z" }; |
| 124 | const consoleKey = { type: "key", key: "console-key" }; |
| 125 | const fingerprints = new Map([ |
| 126 | ["console-key", "3e45cfde9158185930d4cc7020a4e390895574fd54bd8f9631d23a336bbf94f0"], |
| 127 | ["go-key", "d0e590e93fc9bd9353f2b993c0c287391cae505da2a78cb698b75418d2f5367e"], |
| 128 | ["inline-key", "85649de18e63305548b6407e185f708483727ee6189cc4bc9512ddb17e23e776"], |
| 129 | ]); |
| 130 | for (const { |
| 131 | consoleRow = consoleKey, |
| 132 | active = 1, |
| 133 | consoleStatus = 200, |
| 134 | inline = false, |
| 135 | databaseFile, |
| 136 | requested, |
| 137 | } of [ |
| 138 | { |
| 139 | consoleRow: { ...consoleKey, metadata: { server: "https://opencode.ai/console" } }, |
| 140 | requested: ["console-key"], |
| 141 | }, |
| 142 | { consoleStatus: 401, requested: ["console-key", "go-key"] }, |
| 143 | { consoleStatus: 403, requested: ["console-key", "go-key"] }, |
| 144 | { consoleStatus: 500, requested: ["console-key"] }, |
| 145 | { active: 0, requested: ["go-key"] }, |
| 146 | { |
| 147 | consoleRow: { |
| 148 | type: "oauth", |
| 149 | methodID: "device", |
| 150 | access: "token", |
| 151 | refresh: "refresh", |
| 152 | expires: 0, |
| 153 | }, |
| 154 | requested: ["go-key"], |
| 155 | }, |
| 156 | { |
| 157 | consoleRow: { ...consoleKey, metadata: { server: "https://console.example" } }, |
| 158 | requested: ["go-key"], |
| 159 | }, |
| 160 | { inline: true, requested: ["inline-key"] }, |
| 161 | { databaseFile: "selected.db", requested: ["console-key"] }, |
| 162 | { databaseFile: ":memory:", requested: ["go-key"] }, |
| 163 | { active: null, requested: ["console-key"] }, |
| 164 | ]) { |
| 165 | database.exec("DELETE FROM credential"); |
| 166 | insert.run("cred_selected", "opencode", JSON.stringify(consoleRow), active, 2, 2); |
| 167 | // Legacy selections follow creation order, even when an older key was updated later. |
| 168 | insert.run( |
| 169 | "cred_older", |
| 170 | "opencode", |
| 171 | JSON.stringify({ type: "key", key: "old-key" }), |
| 172 | active === null ? null : 0, |
| 173 | 1, |
| 174 | 9, |
| 175 | ); |
| 176 | insert.run("cred_other", "other", JSON.stringify(consoleKey), 1, 10, 10); |
| 177 | if (databaseFile === "selected.db") { |
| 178 | yield* fs.writeFile( |
| 179 | `${dataHome}/opencode/selected.db`, |
| 180 | yield* fs.readFile(`${dataHome}/opencode/opencode.db`), |
| 181 | ); |
| 182 | database |
| 183 | .prepare("UPDATE credential SET value = ? WHERE id = 'cred_selected'") |
| 184 | .run(JSON.stringify({ type: "key", key: "old-key" })); |
| 185 | } |
| 186 | const before = yield* fs.readFile(`${dataHome}/opencode/opencode.db`); |
| 187 | const authorizations: string[] = []; |
| 188 | const limits = yield* readOpenCodeGoUsageLimits({ |
| 189 | enabled: true, |
| 190 | serverUrl: "", |
| 191 | environment: { |
| 192 | XDG_DATA_HOME: dataHome, |
| 193 | ...(databaseFile !== undefined ? { OPENCODE_DB: databaseFile } : {}), |
| 194 | ...(inline |
| 195 | ? { OPENCODE_AUTH_CONTENT: '{"opencode-go":{"type":"api","key":"inline-key"}}' } |
| 196 | : {}), |
| 197 | }, |
| 198 | }).pipe( |
| 199 | Effect.provideService( |
| 200 | HttpClient.HttpClient, |
| 201 | HttpClient.make((request) => { |
| 202 | NodeAssert.equal(request.url, "https://opencode.ai/zen/go/v1/usage"); |
| 203 | const key = (request.headers.authorization ?? "").replace("Bearer ", ""); |
| 204 | authorizations.push(key); |
| 205 | // The legacy key is expired in the regression; it only works in fallback scenarios. |
| 206 | const status = |
| 207 | key === "console-key" ? consoleStatus : requested.includes(key) ? 200 : 401; |
| 208 | return Effect.succeed( |
| 209 | HttpClientResponse.fromWeb( |
| 210 | request, |
| 211 | Response.json( |
| 212 | { usage: { rolling: window, weekly: window, monthly: window } }, |
| 213 | { status }, |
| 214 | ), |
| 215 | ), |
| 216 | ); |
| 217 | }), |
| 218 | ), |
| 219 | ); |
| 220 | NodeAssert.deepEqual(authorizations, requested); |
| 221 | NodeAssert.deepEqual(yield* fs.readFile(`${dataHome}/opencode/opencode.db`), before); |
| 222 | NodeAssert.equal( |
| 223 | limits.unavailable?.reason, |
| 224 | consoleStatus === 500 ? "probeFailed" : undefined, |
| 225 | ); |
| 226 | NodeAssert.equal(limits.windows.length, consoleStatus === 500 ? 0 : 3); |
| 227 | NodeAssert.equal( |
| 228 | limits.credentialFingerprint, |
| 229 | consoleStatus === 500 ? undefined : fingerprints.get(requested.at(-1)!), |
| 230 | ); |
| 231 | } |
| 232 | }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 233 | ); |
| 234 | |
| 235 | it.effect("prefers the selected stored Go key over the auth.json key OpenCode 2 imported", () => |
| 236 | Effect.gen(function* () { |
| 237 | const fs = yield* FileSystem.FileSystem; |
| 238 | const dataHome = yield* fs.makeTempDirectoryScoped(); |
| 239 | yield* fs.makeDirectory(`${dataHome}/opencode`); |
| 240 | yield* fs.writeFileString( |
| 241 | `${dataHome}/opencode/auth.json`, |
| 242 | JSON.stringify({ "opencode-go": { type: "api", key: "imported-key" } }), |
| 243 | ); |
| 244 | const database = yield* Effect.acquireRelease( |
| 245 | Effect.sync(() => new NodeSqlite.DatabaseSync(`${dataHome}/opencode/opencode.db`)), |
| 246 | (database) => Effect.sync(() => database.close()), |
| 247 | ); |
| 248 | database.exec( |
| 249 | "CREATE TABLE credential (id text PRIMARY KEY, integration_id text, value text, active integer, time_created integer, time_updated integer)", |
| 250 | ); |
| 251 | const insert = database.prepare("INSERT INTO credential VALUES (?, ?, ?, ?, ?, ?)"); |
| 252 | insert.run( |
| 253 | "cred_imported", |
| 254 | "opencode-go", |
| 255 | JSON.stringify({ type: "key", key: "imported-key" }), |
| 256 | 0, |
| 257 | 1, |
| 258 | 2, |
| 259 | ); |
| 260 | insert.run( |
| 261 | "cred_replaced", |
| 262 | "opencode-go", |
| 263 | JSON.stringify({ type: "key", key: "replaced-key" }), |
| 264 | 1, |
| 265 | 2, |
| 266 | 2, |
| 267 | ); |
| 268 | const window = { percent: 1, resetsAt: "2026-09-17T12:00:00.000Z" }; |
| 269 | for (const { replacedStatus, requested } of [ |
| 270 | { replacedStatus: 200, requested: ["replaced-key"] }, |
| 271 | { replacedStatus: 401, requested: ["replaced-key", "imported-key"] }, |
| 272 | ]) { |
| 273 | const authorizations: string[] = []; |
| 274 | const limits = yield* readOpenCodeGoUsageLimits({ |
| 275 | enabled: true, |
| 276 | serverUrl: "", |
| 277 | environment: { XDG_DATA_HOME: dataHome }, |
| 278 | }).pipe( |
| 279 | Effect.provideService( |
| 280 | HttpClient.HttpClient, |
| 281 | HttpClient.make((request) => { |
| 282 | const key = (request.headers.authorization ?? "").replace("Bearer ", ""); |
| 283 | authorizations.push(key); |
| 284 | const status = key === "replaced-key" ? replacedStatus : 200; |
| 285 | return Effect.succeed( |
| 286 | HttpClientResponse.fromWeb( |
| 287 | request, |
| 288 | Response.json( |
| 289 | { usage: { rolling: window, weekly: window, monthly: window } }, |
| 290 | { status }, |
| 291 | ), |
| 292 | ), |
| 293 | ); |
| 294 | }), |
| 295 | ), |
| 296 | ); |
| 297 | NodeAssert.deepEqual(authorizations, requested); |
| 298 | NodeAssert.equal(limits.unavailable, undefined); |
| 299 | NodeAssert.equal(limits.windows.length, 3); |
| 300 | } |
| 301 | }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), |
| 302 | ); |
| 303 | |
| 304 | it.effect("does not read local credentials for external or disabled OpenCode instances", () => |
| 305 | Effect.gen(function* () { |
| 306 | for (const settings of [ |
| 307 | { enabled: true, serverUrl: "https://remote.example" }, |
| 308 | { enabled: false, serverUrl: "" }, |
| 309 | ]) { |
| 310 | const limits = yield* readOpenCodeGoUsageLimits({ ...settings, environment: {} }).pipe( |
| 311 | Effect.provideService( |
| 312 | FileSystem.FileSystem, |
| 313 | FileSystem.makeNoop({ |
| 314 | readFileString: () => Effect.die("unexpected credential read"), |
| 315 | }), |
| 316 | ), |
| 317 | Effect.provideService( |
| 318 | HttpClient.HttpClient, |
| 319 | HttpClient.make(() => Effect.die("unexpected usage request")), |
| 320 | ), |
| 321 | Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 322 | ); |
| 323 | NodeAssert.equal(limits.unavailable?.reason, "unsupported"); |
| 324 | } |
| 325 | }), |
| 326 | ); |
| 327 | |
| 328 | it.effect("keeps Go entitlement absence distinct from failed or malformed usage responses", () => |
| 329 | Effect.gen(function* () { |
| 330 | for (const [status, reason] of [ |
| 331 | [403, "unsupported"], |
| 332 | [401, "probeFailed"], |
| 333 | [200, "probeFailed"], |
| 334 | ] as const) { |
| 335 | const limits = yield* readOpenCodeGoUsageLimits({ |
| 336 | enabled: true, |
| 337 | serverUrl: "", |
| 338 | environment: { |
| 339 | OPENCODE_AUTH_CONTENT: '{"opencode-go":{"type":"api","key":"inline-key"}}', |
| 340 | }, |
| 341 | }).pipe( |
| 342 | Effect.provideService( |
| 343 | FileSystem.FileSystem, |
| 344 | FileSystem.makeNoop({ |
| 345 | readFileString: () => Effect.die("inline credentials must bypass disk"), |
| 346 | }), |
| 347 | ), |
| 348 | Effect.provideService( |
| 349 | HttpClient.HttpClient, |
| 350 | HttpClient.make((request) => |
| 351 | Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({}, { status }))), |
| 352 | ), |
| 353 | ), |
| 354 | Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 355 | ); |
| 356 | NodeAssert.equal(limits.unavailable?.reason, reason); |
| 357 | NodeAssert.equal(limits.credentialFingerprint, undefined); |
| 358 | NodeAssert.deepEqual(limits.windows, []); |
| 359 | } |
| 360 | }), |
| 361 | ); |
| 362 | |
| 363 | const runtimeMock = { |
| 364 | state: { |
| 365 | runVersionError: null as Error | null, |
| 366 | runVersionPending: false, |
| 367 | versionStdout: DEFAULT_VERSION_STDOUT, |
| 368 | inventoryError: null as Error | null, |
| 369 | connectionError: null as Error | null, |
| 370 | inventoryCwd: null as string | null, |
| 371 | startCalls: 0, |
| 372 | closeCalls: 0, |
| 373 | sdkClientInputs: [] as Array<{ |
| 374 | baseUrl: string; |
| 375 | directory: string; |
| 376 | serverPassword?: string; |
| 377 | }>, |
| 378 | inventory: { |
| 379 | providerList: { connected: [] as string[], all: [] as unknown[], default: {} }, |
| 380 | agents: [] as unknown[], |
| 381 | skills: [] as unknown[], |
| 382 | } as unknown, |
| 383 | }, |
| 384 | reset() { |
| 385 | this.state.runVersionError = null; |
| 386 | this.state.runVersionPending = false; |
| 387 | this.state.versionStdout = DEFAULT_VERSION_STDOUT; |
| 388 | this.state.inventoryError = null; |
| 389 | this.state.connectionError = null; |
| 390 | this.state.inventoryCwd = null; |
| 391 | this.state.startCalls = 0; |
| 392 | this.state.closeCalls = 0; |
| 393 | this.state.sdkClientInputs.length = 0; |
| 394 | this.state.inventory = { |
| 395 | providerList: { connected: [], all: [] as unknown[], default: {} }, |
| 396 | agents: [] as unknown[], |
| 397 | skills: [] as unknown[], |
| 398 | }; |
| 399 | }, |
| 400 | }; |
| 401 | |
| 402 | const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = { |
| 403 | startOpenCodeServerProcess: ({ serverPassword, environment }) => |
| 404 | Effect.gen(function* () { |
| 405 | runtimeMock.state.startCalls += 1; |
| 406 | yield* Effect.addFinalizer(() => |
| 407 | Effect.sync(() => { |
| 408 | runtimeMock.state.closeCalls += 1; |
| 409 | }), |
| 410 | ); |
| 411 | const effectiveServerPassword = OpenCodeRuntime.resolveOpenCodeServerPassword({ |
| 412 | external: false, |
| 413 | ...(serverPassword !== undefined ? { serverPassword } : {}), |
| 414 | ...(environment !== undefined ? { environment } : {}), |
| 415 | }); |
| 416 | return { |
| 417 | url: "http://127.0.0.1:4301", |
| 418 | ...(effectiveServerPassword !== undefined |
| 419 | ? { serverPassword: effectiveServerPassword } |
| 420 | : {}), |
| 421 | version: "1.14.19", |
| 422 | isRunning: Effect.succeed(true), |
| 423 | exitCode: Effect.never, |
| 424 | }; |
| 425 | }), |
| 426 | connectToOpenCodeServer: ({ serverUrl, serverPassword }) => |
| 427 | Effect.gen(function* () { |
| 428 | if (runtimeMock.state.connectionError) { |
| 429 | return yield* new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 430 | operation: "global.health", |
| 431 | detail: runtimeMock.state.connectionError.message, |
| 432 | cause: runtimeMock.state.connectionError, |
| 433 | }); |
| 434 | } |
| 435 | if (!serverUrl) { |
| 436 | yield* Effect.addFinalizer(() => |
| 437 | Effect.sync(() => { |
| 438 | runtimeMock.state.closeCalls += 1; |
| 439 | }), |
| 440 | ); |
| 441 | } |
| 442 | return { |
| 443 | url: serverUrl ?? "http://127.0.0.1:4301", |
| 444 | ...(serverPassword ? { serverPassword } : {}), |
| 445 | version: "1.14.19", |
| 446 | exitCode: null, |
| 447 | external: Boolean(serverUrl), |
| 448 | }; |
| 449 | }), |
| 450 | runOpenCodeCommand: () => |
| 451 | runtimeMock.state.runVersionPending |
| 452 | ? Effect.never |
| 453 | : runtimeMock.state.runVersionError |
| 454 | ? Effect.fail( |
| 455 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 456 | operation: "runOpenCodeCommand", |
| 457 | detail: runtimeMock.state.runVersionError.message, |
| 458 | cause: runtimeMock.state.runVersionError, |
| 459 | }), |
| 460 | ) |
| 461 | : Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }), |
| 462 | createOpenCodeSdkClient: (input) => { |
| 463 | runtimeMock.state.sdkClientInputs.push(input); |
| 464 | return {} as unknown as ReturnType< |
| 465 | OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"] |
| 466 | >; |
| 467 | }, |
| 468 | loadOpenCodeInventory: () => |
| 469 | runtimeMock.state.inventoryError |
| 470 | ? Effect.fail( |
| 471 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 472 | operation: "loadOpenCodeInventory", |
| 473 | detail: runtimeMock.state.inventoryError.message, |
| 474 | cause: runtimeMock.state.inventoryError, |
| 475 | }), |
| 476 | ) |
| 477 | : Effect.succeed(runtimeMock.state.inventory as OpenCodeRuntime.OpenCodeInventory), |
| 478 | loadOpenCodeSkills: () => Effect.succeed([]), |
| 479 | }; |
| 480 | |
| 481 | beforeEach(() => { |
| 482 | runtimeMock.reset(); |
| 483 | }); |
| 484 | |
| 485 | const layerTest = Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe( |
| 486 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 487 | ); |
| 488 | |
| 489 | // As the instance registry hands them to the driver: a referenced password is already read. |
| 490 | const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>) => { |
| 491 | const settings = decodeOpenCodeSettings({ |
| 492 | enabled: true, |
| 493 | binaryPath: "opencode", |
| 494 | serverUrl: "", |
| 495 | serverPassword: "", |
| 496 | customModels: [], |
| 497 | ...overrides, |
| 498 | }); |
| 499 | return { ...settings, serverPassword: settingsSecretLiteral(settings.serverPassword) }; |
| 500 | }; |
| 501 | |
| 502 | const checkProvider = Effect.fn("checkProvider")(function* ( |
| 503 | settings: ReturnType<typeof makeOpenCodeSettings>, |
| 504 | cwd = process.cwd(), |
| 505 | environment?: NodeJS.ProcessEnv, |
| 506 | server = replayOpenCodeServer(OPENCODE_1_RESPONSES, settings.serverPassword), |
| 507 | openCode2Models: Effect.Effect< |
| 508 | ReadonlyArray<OpenCode2Model>, |
| 509 | OpenCodeRuntime.OpenCodeRuntimeError |
| 510 | > = Effect.succeed([]), |
| 511 | compatibility?: ProviderCompatibilityLookup, |
| 512 | ) { |
| 513 | return yield* Effect.scoped( |
| 514 | Effect.gen(function* () { |
| 515 | const serverOwner = yield* OpenCodeServerOwner.make({ |
| 516 | binaryPath: settings.binaryPath, |
| 517 | directory: cwd, |
| 518 | ...(settings.serverPassword ? { serverPassword: settings.serverPassword } : {}), |
| 519 | ...(environment ? { environment } : {}), |
| 520 | }); |
| 521 | const probe = probeOpenCodeRuntime(settings, environment).pipe( |
| 522 | Effect.provideService(HttpClient.HttpClient, server), |
| 523 | Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble), |
| 524 | ); |
| 525 | return yield* checkOpenCodeProviderStatus( |
| 526 | settings, |
| 527 | cwd, |
| 528 | probe, |
| 529 | openCode2Models, |
| 530 | environment, |
| 531 | compatibility, |
| 532 | ).pipe(Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner)); |
| 533 | }), |
| 534 | ); |
| 535 | }); |
| 536 | |
| 537 | it.layer(layerTest)("checkOpenCodeProviderStatus", (it) => { |
| 538 | it.effect.each(["version", "inventory", "models", "empty-v1", "empty-v2"] as const)( |
| 539 | "records %s discovery failures in the existing trace and logger", |
| 540 | (failure) => |
| 541 | Effect.gen(function* () { |
| 542 | const cause = new Error("discovery connection reset"); |
| 543 | const v2 = failure === "models" || failure === "empty-v2"; |
| 544 | runtimeMock.state.versionStdout = v2 ? "opencode v2.0.18\n" : DEFAULT_VERSION_STDOUT; |
| 545 | if (failure === "version") runtimeMock.state.runVersionError = cause; |
| 546 | if (failure === "inventory") runtimeMock.state.inventoryError = cause; |
| 547 | if (failure === "empty-v1") { |
| 548 | runtimeMock.state.inventory = { |
| 549 | providerList: { |
| 550 | connected: ["openai"], |
| 551 | all: [{ id: "openai", name: "OpenAI", models: {} }], |
| 552 | default: {}, |
| 553 | }, |
| 554 | agents: [], |
| 555 | skills: [], |
| 556 | }; |
| 557 | } |
| 558 | const spans: Array<Tracer.NativeSpan> = []; |
| 559 | yield* checkProvider( |
| 560 | makeOpenCodeSettings({ serverPassword: "private-password" }), |
| 561 | process.cwd(), |
| 562 | undefined, |
| 563 | undefined, |
| 564 | failure === "models" |
| 565 | ? Effect.fail( |
| 566 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 567 | operation: "model.list", |
| 568 | detail: "model list failed", |
| 569 | cause, |
| 570 | }), |
| 571 | ) |
| 572 | : Effect.succeed([]), |
| 573 | ).pipe( |
| 574 | Effect.provideService( |
| 575 | Tracer.Tracer, |
| 576 | Tracer.make({ |
| 577 | span: (options) => { |
| 578 | const span = new Tracer.NativeSpan(options); |
| 579 | spans.push(span); |
| 580 | return span; |
| 581 | }, |
| 582 | }), |
| 583 | ), |
| 584 | Effect.provide(Logger.layer([Logger.tracerLogger], { mergeWithExisting: false })), |
| 585 | ); |
| 586 | |
| 587 | const diagnostics = spans.flatMap((span) => |
| 588 | span.events |
| 589 | .filter(([name]) => name === "OpenCode discovery failed") |
| 590 | .map((event) => ({ span, event })), |
| 591 | ); |
| 592 | NodeAssert.equal(diagnostics.length, 1); |
| 593 | const { |
| 594 | span, |
| 595 | event: [, timestamp, attributes], |
| 596 | } = diagnostics[0]!; |
| 597 | NodeAssert.equal(attributes.provider, "opencode"); |
| 598 | NodeAssert.equal( |
| 599 | attributes.phase, |
| 600 | failure.startsWith("empty") ? (v2 ? "models" : "inventory") : failure, |
| 601 | ); |
| 602 | NodeAssert.equal(attributes.outcome, failure.startsWith("empty") ? "empty" : "failed"); |
| 603 | NodeAssert.equal(attributes.serverMode, "managed"); |
| 604 | NodeAssert.equal(attributes["effect.logLevel"], "WARN"); |
| 605 | NodeAssert.ok(timestamp >= 0n); |
| 606 | NodeAssert.ok(span.traceId.length > 0); |
| 607 | NodeAssert.equal(span.attributes.get("discovery.outcome"), attributes.outcome); |
| 608 | if (!failure.startsWith("empty")) { |
| 609 | NodeAssert.match(String(attributes["effect.cause"]), /discovery connection reset/); |
| 610 | } |
| 611 | NodeAssert.ok(!JSON.stringify(attributes).includes("private-password")); |
| 612 | }), |
| 613 | ); |
| 614 | |
| 615 | it.effect("keeps an empty legacy catalog retryable until connected providers list models", () => |
| 616 | Effect.gen(function* () { |
| 617 | const upstream = { id: "openai", name: "OpenAI", models: {} }; |
| 618 | runtimeMock.state.inventory = { |
| 619 | providerList: { connected: ["openai"], all: [upstream], default: {} }, |
| 620 | agents: [], |
| 621 | skills: [], |
| 622 | }; |
| 623 | const settings = makeOpenCodeSettings(); |
| 624 | const empty = yield* checkProvider(settings); |
| 625 | NodeAssert.equal(empty.status, "warning"); |
| 626 | NodeAssert.equal(empty.auth.status, "unknown"); |
| 627 | NodeAssert.deepEqual(empty.models, []); |
| 628 | |
| 629 | upstream.models = { |
| 630 | "gpt-5.4": { id: "gpt-5.4", name: "GPT-5.4", variants: {} }, |
| 631 | }; |
| 632 | const ready = yield* checkProvider(settings); |
| 633 | NodeAssert.equal(ready.status, "ready"); |
| 634 | NodeAssert.equal(ready.auth.status, "authenticated"); |
| 635 | NodeAssert.deepEqual( |
| 636 | ready.models.map((model) => model.slug), |
| 637 | ["openai/gpt-5.4"], |
| 638 | ); |
| 639 | }), |
| 640 | ); |
| 641 | |
| 642 | it.effect("emits OpenCode variant defaults so trait picker can resolve a visible selection", () => |
| 643 | Effect.gen(function* () { |
| 644 | runtimeMock.state.inventory = { |
| 645 | providerList: { |
| 646 | connected: ["openai"], |
| 647 | all: [ |
| 648 | { |
| 649 | id: "openai", |
| 650 | name: "OpenAI", |
| 651 | models: { |
| 652 | "gpt-5.4": { |
| 653 | id: "gpt-5.4", |
| 654 | name: "GPT-5.4", |
| 655 | variants: { |
| 656 | none: {}, |
| 657 | low: {}, |
| 658 | medium: {}, |
| 659 | high: {}, |
| 660 | xhigh: {}, |
| 661 | }, |
| 662 | }, |
| 663 | }, |
| 664 | }, |
| 665 | ], |
| 666 | default: {}, |
| 667 | }, |
| 668 | agents: [ |
| 669 | { name: "build", hidden: false, mode: "primary" }, |
| 670 | { name: "plan", hidden: false, mode: "primary" }, |
| 671 | ], |
| 672 | }; |
| 673 | |
| 674 | const snapshot = yield* checkProvider(makeOpenCodeSettings()); |
| 675 | const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4"); |
| 676 | |
| 677 | NodeAssert.ok(model); |
| 678 | const variantDescriptor = model.capabilities?.optionDescriptors?.find( |
| 679 | (descriptor) => descriptor.id === "variant" && descriptor.type === "select", |
| 680 | ); |
| 681 | NodeAssert.ok(variantDescriptor && variantDescriptor.type === "select"); |
| 682 | NodeAssert.equal( |
| 683 | variantDescriptor.options.find((option) => option.isDefault === true)?.id, |
| 684 | "medium", |
| 685 | ); |
| 686 | NodeAssert.equal( |
| 687 | variantDescriptor.options.find((option) => option.id === "xhigh")?.label, |
| 688 | "Extra High", |
| 689 | ); |
| 690 | const agentDescriptor = model.capabilities?.optionDescriptors?.find( |
| 691 | (descriptor) => descriptor.id === "agent" && descriptor.type === "select", |
| 692 | ); |
| 693 | NodeAssert.ok(agentDescriptor && agentDescriptor.type === "select"); |
| 694 | NodeAssert.equal( |
| 695 | agentDescriptor.options.find((option) => option.isDefault === true)?.id, |
| 696 | "build", |
| 697 | ); |
| 698 | }), |
| 699 | ); |
| 700 | |
| 701 | it.effect("keeps Agent without inventing Reasoning for models with no variants", () => |
| 702 | Effect.gen(function* () { |
| 703 | runtimeMock.state.inventory = { |
| 704 | providerList: { |
| 705 | connected: ["opencode"], |
| 706 | all: [ |
| 707 | { |
| 708 | id: "opencode", |
| 709 | name: "OpenCode Zen", |
| 710 | models: { |
| 711 | "big-pickle": { id: "big-pickle", name: "Big Pickle", variants: {} }, |
| 712 | "glm-5": { id: "glm-5", name: "GLM-5" }, |
| 713 | }, |
| 714 | }, |
| 715 | ], |
| 716 | default: {}, |
| 717 | }, |
| 718 | agents: [ |
| 719 | { name: "build", hidden: false, mode: "primary" }, |
| 720 | { name: "plan", hidden: false, mode: "primary" }, |
| 721 | ], |
| 722 | }; |
| 723 | const snapshot = yield* checkProvider(makeOpenCodeSettings()); |
| 724 | for (const slug of ["opencode/big-pickle", "opencode/glm-5"]) { |
| 725 | const model = snapshot.models.find((entry) => entry.slug === slug); |
| 726 | NodeAssert.ok(model); |
| 727 | const descriptors = model.capabilities?.optionDescriptors; |
| 728 | NodeAssert.deepEqual(descriptors, [ |
| 729 | { |
| 730 | id: "agent", |
| 731 | label: "Agent", |
| 732 | type: "select", |
| 733 | options: [ |
| 734 | { id: "build", label: "Build", isDefault: true }, |
| 735 | { id: "plan", label: "Plan" }, |
| 736 | ], |
| 737 | currentValue: "build", |
| 738 | }, |
| 739 | ]); |
| 740 | NodeAssert.deepEqual(buildProviderOptionSelectionsFromDescriptors(descriptors), [ |
| 741 | { id: "agent", value: "build" }, |
| 742 | ]); |
| 743 | } |
| 744 | }), |
| 745 | ); |
| 746 | |
| 747 | it.effect("includes OpenCode skills in the provider snapshot", () => |
| 748 | Effect.gen(function* () { |
| 749 | runtimeMock.state.inventory = { |
| 750 | providerList: { |
| 751 | connected: ["openai"], |
| 752 | all: [ |
| 753 | { |
| 754 | id: "openai", |
| 755 | name: "OpenAI", |
| 756 | models: { |
| 757 | "gpt-5.4": { |
| 758 | id: "gpt-5.4", |
| 759 | name: "GPT-5.4", |
| 760 | variants: {}, |
| 761 | }, |
| 762 | }, |
| 763 | }, |
| 764 | ], |
| 765 | default: {}, |
| 766 | }, |
| 767 | agents: [], |
| 768 | skills: [ |
| 769 | { |
| 770 | name: "openclaw-review", |
| 771 | description: "Review OpenClaw workflow changes.", |
| 772 | location: "/Users/test/.agents/skills/openclaw-review/SKILL.md", |
| 773 | }, |
| 774 | { |
| 775 | name: "openclaw-triage", |
| 776 | description: "Triage OpenClaw routing issues.", |
| 777 | location: "/Users/test/.agents/skills/openclaw-triage/SKILL.md", |
| 778 | }, |
| 779 | { |
| 780 | name: "missing-location", |
| 781 | description: "This incomplete SDK row should be skipped.", |
| 782 | location: "", |
| 783 | }, |
| 784 | ], |
| 785 | }; |
| 786 | |
| 787 | const snapshot = yield* checkProvider(makeOpenCodeSettings()); |
| 788 | |
| 789 | NodeAssert.deepEqual( |
| 790 | snapshot.skills.map((skill) => ({ |
| 791 | name: skill.name, |
| 792 | path: skill.path, |
| 793 | enabled: skill.enabled, |
| 794 | shortDescription: skill.shortDescription, |
| 795 | })), |
| 796 | [ |
| 797 | { |
| 798 | name: "openclaw-review", |
| 799 | path: "/Users/test/.agents/skills/openclaw-review/SKILL.md", |
| 800 | enabled: true, |
| 801 | shortDescription: "Review OpenClaw workflow changes.", |
| 802 | }, |
| 803 | { |
| 804 | name: "openclaw-triage", |
| 805 | path: "/Users/test/.agents/skills/openclaw-triage/SKILL.md", |
| 806 | enabled: true, |
| 807 | shortDescription: "Triage OpenClaw routing issues.", |
| 808 | }, |
| 809 | ], |
| 810 | ); |
| 811 | }), |
| 812 | ); |
| 813 | |
| 814 | it.effect("reports the upgraded CLI without restarting a borrowed OpenCode server", () => |
| 815 | Effect.gen(function* () { |
| 816 | const settings = makeOpenCodeSettings(); |
| 817 | const owner = yield* OpenCodeServerOwner.make({ |
| 818 | binaryPath: settings.binaryPath, |
| 819 | directory: process.cwd(), |
| 820 | }); |
| 821 | yield* owner.withServer(() => |
| 822 | Effect.gen(function* () { |
| 823 | runtimeMock.state.versionStdout = "opencode 1.14.20\n"; |
| 824 | const snapshot = yield* checkOpenCodeProviderStatus( |
| 825 | settings, |
| 826 | process.cwd(), |
| 827 | probeOpenCodeRuntime(settings).pipe( |
| 828 | Effect.provideService( |
| 829 | HttpClient.HttpClient, |
| 830 | replayOpenCodeServer(OPENCODE_1_RESPONSES, settings.serverPassword), |
| 831 | ), |
| 832 | Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble), |
| 833 | ), |
| 834 | Effect.succeed([]), |
| 835 | ).pipe(Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, owner)); |
| 836 | |
| 837 | NodeAssert.equal(snapshot.version, "1.14.19"); |
| 838 | NodeAssert.equal(snapshot.installedVersion, "1.14.20"); |
| 839 | NodeAssert.equal(runtimeMock.state.startCalls, 1); |
| 840 | NodeAssert.equal(runtimeMock.state.closeCalls, 0); |
| 841 | }), |
| 842 | ); |
| 843 | }), |
| 844 | ); |
| 845 | |
| 846 | it.effect("lists a local OpenCode 2 binary's models in Full access only, never via 1.x", () => |
| 847 | Effect.gen(function* () { |
| 848 | runtimeMock.state.versionStdout = "opencode v2.0.18\n"; |
| 849 | const snapshot = yield* checkProvider( |
| 850 | makeOpenCodeSettings(), |
| 851 | process.cwd(), |
| 852 | undefined, |
| 853 | undefined, |
| 854 | Effect.succeed([ |
| 855 | { providerID: "opencode", id: "big-pickle", name: "Big Pickle", variants: [] }, |
| 856 | { |
| 857 | providerID: "opencode", |
| 858 | id: "space-bunny-free", |
| 859 | name: "Space Bunny Free", |
| 860 | variants: [{ id: "low" }, { id: "medium" }, { id: "high" }, { id: "xhigh" }], |
| 861 | }, |
| 862 | { |
| 863 | providerID: "opencode-go", |
| 864 | id: "deepseek-v4.1-flash", |
| 865 | name: "DeepSeek V4.1 Flash", |
| 866 | variants: [{ id: "low" }, { id: "high" }, { id: "max" }], |
| 867 | }, |
| 868 | ]), |
| 869 | ); |
| 870 | |
| 871 | NodeAssert.equal(snapshot.status, "ready"); |
| 872 | NodeAssert.equal(snapshot.version, "2.0.18"); |
| 873 | NodeAssert.equal("installedVersion" in snapshot, false); |
| 874 | NodeAssert.deepEqual(snapshot.supportedRuntimeModes, [ |
| 875 | "approval-required", |
| 876 | "auto-accept-edits", |
| 877 | "auto", |
| 878 | "full-access", |
| 879 | ]); |
| 880 | NodeAssert.equal(snapshot.showInteractionModeToggle, true); |
| 881 | NodeAssert.deepEqual( |
| 882 | snapshot.slashCommands.map((command) => command.name), |
| 883 | ["compact"], |
| 884 | ); |
| 885 | NodeAssert.deepEqual( |
| 886 | snapshot.models.map((model) => model.slug), |
| 887 | ["opencode/big-pickle", "opencode-go/deepseek-v4.1-flash", "opencode/space-bunny-free"], |
| 888 | ); |
| 889 | const variant = snapshot.models.find((model) => model.slug === "opencode/space-bunny-free") |
| 890 | ?.capabilities?.optionDescriptors?.[0]; |
| 891 | NodeAssert.deepEqual( |
| 892 | variant?.type === "select" ? variant.options.map((option) => option.id) : [], |
| 893 | ["low", "medium", "high", "xhigh"], |
| 894 | ); |
| 895 | NodeAssert.equal( |
| 896 | variant?.type === "select" |
| 897 | ? variant.options.find((option) => option.id === "xhigh")?.label |
| 898 | : undefined, |
| 899 | "Extra High", |
| 900 | ); |
| 901 | const goVariant = snapshot.models.find( |
| 902 | (model) => model.slug === "opencode-go/deepseek-v4.1-flash", |
| 903 | )?.capabilities?.optionDescriptors?.[0]; |
| 904 | const goVariantIds = |
| 905 | goVariant?.type === "select" ? goVariant.options.map((option) => option.id) : []; |
| 906 | NodeAssert.deepEqual(goVariantIds, ["low", "high", "max"]); |
| 907 | NodeAssert.ok( |
| 908 | goVariant?.type === "select" && |
| 909 | goVariant.currentValue !== undefined && |
| 910 | goVariantIds.includes(goVariant.currentValue), |
| 911 | "an OpenCode Go model gets a default reasoning variant it lists", |
| 912 | ); |
| 913 | NodeAssert.equal(runtimeMock.state.sdkClientInputs.length, 0); |
| 914 | }), |
| 915 | ); |
| 916 | |
| 917 | it.effect("marks older releases of a family and deprecated models as legacy", () => |
| 918 | Effect.gen(function* () { |
| 919 | const releases = [ |
| 920 | ["opencode", "opus-4-5", "claude-opus", "2025-11-24", "active"], |
| 921 | ["opencode", "opus-5-5", "claude-opus", "2026-09-22", "active"], |
| 922 | ["opencode", "opus-preview", "claude-opus", "2026-10-01", "deprecated"], |
| 923 | ["opencode", "flash", "flash", "2026-09-10", "active"], |
| 924 | ["opencode", "flash-free", "flash", "2026-09-10", "active"], |
| 925 | ["opencode", "big-pickle", undefined, "2025-10-17", "active"], |
| 926 | ["openrouter", "opus-4-5", "claude-opus", "2025-11-24", "active"], |
| 927 | ] as const; |
| 928 | const legacySlugs = ( |
| 929 | models: ReadonlyArray<{ readonly slug: string; readonly isLegacy?: boolean | undefined }>, |
| 930 | ) => |
| 931 | models |
| 932 | .filter((model) => model.isLegacy) |
| 933 | .map((model) => model.slug) |
| 934 | .toSorted(); |
| 935 | const expected = ["opencode/opus-4-5", "opencode/opus-preview"]; |
| 936 | |
| 937 | runtimeMock.state.inventory = { |
| 938 | providerList: { |
| 939 | connected: ["opencode", "openrouter"], |
| 940 | all: ["opencode", "openrouter"].map((providerID) => ({ |
| 941 | id: providerID, |
| 942 | name: providerID, |
| 943 | models: Object.fromEntries( |
| 944 | releases |
| 945 | .filter(([provider]) => provider === providerID) |
| 946 | .map(([, id, family, releaseDate, status]) => [ |
| 947 | id, |
| 948 | { id, name: id, family, release_date: releaseDate, status, variants: {} }, |
| 949 | ]), |
| 950 | ), |
| 951 | })), |
| 952 | default: {}, |
| 953 | }, |
| 954 | agents: [], |
| 955 | }; |
| 956 | NodeAssert.deepEqual( |
| 957 | legacySlugs((yield* checkProvider(makeOpenCodeSettings())).models), |
| 958 | expected, |
| 959 | ); |
| 960 | |
| 961 | runtimeMock.state.versionStdout = "opencode v2.0.18\n"; |
| 962 | const openCode2 = yield* checkProvider( |
| 963 | makeOpenCodeSettings(), |
| 964 | process.cwd(), |
| 965 | undefined, |
| 966 | undefined, |
| 967 | Effect.succeed( |
| 968 | releases.map(([providerID, id, family, releaseDate, status]) => ({ |
| 969 | providerID, |
| 970 | id, |
| 971 | name: id, |
| 972 | variants: [], |
| 973 | family, |
| 974 | released: Date.parse(releaseDate), |
| 975 | deprecated: status === "deprecated", |
| 976 | })), |
| 977 | ), |
| 978 | ); |
| 979 | NodeAssert.deepEqual(legacySlugs(openCode2.models), expected); |
| 980 | }), |
| 981 | ); |
| 982 | |
| 983 | it.effect("reports a failed OpenCode 2 model list without the server's response", () => |
| 984 | Effect.gen(function* () { |
| 985 | runtimeMock.state.versionStdout = "opencode v2.0.18\n"; |
| 986 | const snapshot = yield* checkProvider( |
| 987 | makeOpenCodeSettings(), |
| 988 | process.cwd(), |
| 989 | undefined, |
| 990 | undefined, |
| 991 | Effect.fail( |
| 992 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 993 | operation: "model.list", |
| 994 | detail: 'status=500 body={"token":"leaked-response-body"}', |
| 995 | }), |
| 996 | ), |
| 997 | ); |
| 998 | |
| 999 | NodeAssert.equal(snapshot.status, "error"); |
| 1000 | NodeAssert.equal(snapshot.message, "OpenCode could not load its model list."); |
| 1001 | NodeAssert.deepEqual( |
| 1002 | snapshot.slashCommands.map((command) => command.name), |
| 1003 | ["compact"], |
| 1004 | ); |
| 1005 | }), |
| 1006 | ); |
| 1007 | |
| 1008 | it.effect("reports local model inventory failures without treating them as empty", () => |
| 1009 | Effect.gen(function* () { |
| 1010 | runtimeMock.state.versionStdout = "opencode 1.14.20\n"; |
| 1011 | runtimeMock.state.inventoryError = new Error("opencode models failed"); |
| 1012 | const snapshot = yield* checkProvider(makeOpenCodeSettings()); |
| 1013 | |
| 1014 | NodeAssert.equal(snapshot.status, "error"); |
| 1015 | NodeAssert.equal(snapshot.installed, true); |
| 1016 | NodeAssert.equal(snapshot.version, "1.14.19"); |
| 1017 | NodeAssert.equal(snapshot.installedVersion, "1.14.20"); |
| 1018 | NodeAssert.equal(snapshot.models.length, 0); |
| 1019 | NodeAssert.equal( |
| 1020 | snapshot.message, |
| 1021 | "Failed to load OpenCode provider inventory: opencode models failed", |
| 1022 | ); |
| 1023 | }), |
| 1024 | ); |
| 1025 | }); |
| 1026 | |
| 1027 | it.layer(layerTest)("checkOpenCodeProviderStatus with configured server URL", (it) => { |
| 1028 | it.effect.each([ |
| 1029 | "401 Unauthorized", |
| 1030 | "403 Forbidden", |
| 1031 | "status=401 body={}", |
| 1032 | "status=403 body={}", |
| 1033 | "HTTP 401", |
| 1034 | "HTTP/1.1 403", |
| 1035 | "Response status code: 401", |
| 1036 | "Response status code: 403", |
| 1037 | "Request failed with status code 401", |
| 1038 | "Request failed with status code 403", |
| 1039 | ])("keeps explicit authentication rejection actionable: %s", (detail) => |
| 1040 | Effect.gen(function* () { |
| 1041 | runtimeMock.state.connectionError = new Error(detail); |
| 1042 | const snapshot = yield* checkProvider( |
| 1043 | makeOpenCodeSettings({ serverUrl: "http://127.0.0.1:9999" }), |
| 1044 | ); |
| 1045 | |
| 1046 | NodeAssert.equal(snapshot.status, "error"); |
| 1047 | NodeAssert.equal(snapshot.auth.status, "unauthenticated"); |
| 1048 | NodeAssert.equal( |
| 1049 | snapshot.message, |
| 1050 | "OpenCode server rejected authentication. Check the server URL and password.", |
| 1051 | ); |
| 1052 | }), |
| 1053 | ); |
| 1054 | |
| 1055 | it.effect.each([401, 403, 4010, 4030])("keeps connection failures on port %s retryable", (port) => |
| 1056 | Effect.gen(function* () { |
| 1057 | const serverUrl = `http://127.0.0.1:${port}`; |
| 1058 | runtimeMock.state.connectionError = new Error(`connect ECONNREFUSED 127.0.0.1:${port}`); |
| 1059 | const snapshot = yield* checkProvider(makeOpenCodeSettings({ serverUrl })); |
| 1060 | |
| 1061 | NodeAssert.equal(snapshot.status, "error"); |
| 1062 | NodeAssert.equal(snapshot.auth.status, "unknown"); |
| 1063 | NodeAssert.equal( |
| 1064 | snapshot.message, |
| 1065 | `Couldn't reach the configured OpenCode server at ${serverUrl}. Check that the server is running and the URL is correct.`, |
| 1066 | ); |
| 1067 | }), |
| 1068 | ); |
| 1069 | |
| 1070 | it.effect("routes a configured OpenCode 2 server to the 2.x check, never via 1.x", () => |
| 1071 | Effect.gen(function* () { |
| 1072 | const settings = makeOpenCodeSettings({ |
| 1073 | serverUrl: "http://127.0.0.1:9999", |
| 1074 | serverPassword: "secret-password", |
| 1075 | }); |
| 1076 | const snapshot = yield* checkProvider( |
| 1077 | settings, |
| 1078 | process.cwd(), |
| 1079 | undefined, |
| 1080 | replayOpenCodeServer(OPENCODE_2_RESPONSES, "secret-password"), |
| 1081 | ); |
| 1082 | |
| 1083 | NodeAssert.equal(snapshot.status, "warning"); |
| 1084 | NodeAssert.equal(snapshot.version, "2.0.18"); |
| 1085 | NodeAssert.equal("installedVersion" in snapshot, false); |
| 1086 | NodeAssert.deepEqual(snapshot.supportedRuntimeModes, [ |
| 1087 | "approval-required", |
| 1088 | "auto-accept-edits", |
| 1089 | "auto", |
| 1090 | "full-access", |
| 1091 | ]); |
| 1092 | NodeAssert.equal(runtimeMock.state.sdkClientInputs.length, 0); |
| 1093 | }), |
| 1094 | ); |
| 1095 | |
| 1096 | it.effect("reports a rejected OpenCode 2 password as an auth error, not a version", () => |
| 1097 | Effect.gen(function* () { |
| 1098 | const snapshot = yield* checkProvider( |
| 1099 | makeOpenCodeSettings({ serverUrl: "http://127.0.0.1:9999", serverPassword: "wrong" }), |
| 1100 | process.cwd(), |
| 1101 | undefined, |
| 1102 | replayOpenCodeServer(OPENCODE_2_RESPONSES, "secret-password"), |
| 1103 | ); |
| 1104 | |
| 1105 | NodeAssert.equal(snapshot.status, "error"); |
| 1106 | NodeAssert.equal( |
| 1107 | snapshot.message, |
| 1108 | "OpenCode server rejected authentication. Check the server URL and password.", |
| 1109 | ); |
| 1110 | }), |
| 1111 | ); |
| 1112 | |
| 1113 | it.effect("reports a version the policy rates broken before loading inventory", () => |
| 1114 | Effect.gen(function* () { |
| 1115 | const snapshot = yield* checkProvider( |
| 1116 | makeOpenCodeSettings(), |
| 1117 | undefined, |
| 1118 | undefined, |
| 1119 | undefined, |
| 1120 | undefined, |
| 1121 | () => |
| 1122 | Effect.succeed({ |
| 1123 | status: "broken", |
| 1124 | message: null, |
| 1125 | recommendedVersion: null, |
| 1126 | recommendedRange: ">=2.0.18", |
| 1127 | }), |
| 1128 | ); |
| 1129 | |
| 1130 | NodeAssert.equal(snapshot.status, "error"); |
| 1131 | NodeAssert.match(snapshot.message ?? "", /OpenCode 1\.14\.19 does not work/); |
| 1132 | NodeAssert.equal(runtimeMock.state.sdkClientInputs.length, 0); |
| 1133 | }), |
| 1134 | ); |
| 1135 | |
| 1136 | it.effect("reports a failed server connection before loading inventory", () => |
| 1137 | Effect.gen(function* () { |
| 1138 | runtimeMock.state.connectionError = new Error("OpenCode server refused the connection."); |
| 1139 | const snapshot = yield* checkProvider( |
| 1140 | makeOpenCodeSettings({ serverUrl: "http://127.0.0.1:9999" }), |
| 1141 | ); |
| 1142 | |
| 1143 | NodeAssert.equal(snapshot.status, "error"); |
| 1144 | NodeAssert.equal(snapshot.models.length, 0); |
| 1145 | NodeAssert.match(snapshot.message ?? "", /refused the connection/); |
| 1146 | NodeAssert.equal(runtimeMock.state.sdkClientInputs.length, 0); |
| 1147 | }), |
| 1148 | ); |
| 1149 | }); |
| 1150 | |
| 1151 | const builtinCommands = [ |
| 1152 | { name: "init", description: "guided AGENTS.md setup" }, |
| 1153 | { name: "review", description: "review changes [commit|branch|pr], defaults to uncommitted" }, |
| 1154 | ]; |
| 1155 | const builtinSkills = [ |
| 1156 | { id: "opencode", name: "OpenCode", path: "/builtin/opencode.md" }, |
| 1157 | { id: "report", name: "Report", path: "/builtin/report.md" }, |
| 1158 | ]; |
| 1159 | const scanned: OpenCode2Workspace = { |
| 1160 | commands: [...builtinCommands, { name: "hello", description: "Say hello to the workspace" }], |
| 1161 | skills: [ |
| 1162 | ...builtinSkills, |
| 1163 | { |
| 1164 | id: "greet", |
| 1165 | name: "greet", |
| 1166 | path: "/work/.opencode/skills/greet/SKILL.md", |
| 1167 | description: "Greets the user with the secret word MANGO.", |
| 1168 | }, |
| 1169 | ], |
| 1170 | }; |
| 1171 | |
| 1172 | it.effect( |
| 1173 | "reads a loaded OpenCode 2 directory listing no commands again once its scan has ended", |
| 1174 | () => |
| 1175 | Effect.gen(function* () { |
| 1176 | const reads: Array<OpenCode2Workspace> = [{ commands: [], skills: [] }, scanned]; |
| 1177 | const scanEnded = yield* Deferred.make<void>(); |
| 1178 | const load = yield* loadOpenCode2Workspace( |
| 1179 | Effect.sync(() => reads.shift()!), |
| 1180 | Deferred.await(scanEnded), |
| 1181 | Effect.succeed(true), |
| 1182 | ).pipe(Effect.forkChild); |
| 1183 | yield* Effect.yieldNow; |
| 1184 | NodeAssert.equal(reads.length, 1); |
| 1185 | yield* Deferred.succeed(scanEnded, undefined); |
| 1186 | NodeAssert.deepEqual(yield* Fiber.join(load), scanned); |
| 1187 | }), |
| 1188 | ); |
| 1189 | |
| 1190 | it.effect("waits for the scan of a cold OpenCode 2 directory that first lists only built-ins", () => |
| 1191 | Effect.gen(function* () { |
| 1192 | const calls: Array<string> = []; |
| 1193 | const reads: Array<OpenCode2Workspace> = [ |
| 1194 | { commands: builtinCommands, skills: builtinSkills }, |
| 1195 | scanned, |
| 1196 | ]; |
| 1197 | const workspace = yield* loadOpenCode2Workspace( |
| 1198 | Effect.sync(() => (calls.push("read"), reads.shift()!)), |
| 1199 | Effect.sync(() => void calls.push("scanned")), |
| 1200 | Effect.sync(() => (calls.push("loaded"), false)), |
| 1201 | ); |
| 1202 | NodeAssert.deepEqual(workspace, scanned); |
| 1203 | NodeAssert.deepEqual(calls, ["loaded", "read", "scanned", "read"]); |
| 1204 | }), |
| 1205 | ); |
| 1206 | |
| 1207 | it.effect("reads an already loaded OpenCode 2 directory once without waiting for a scan", () => |
| 1208 | Effect.gen(function* () { |
| 1209 | const calls: Array<string> = []; |
| 1210 | const workspace = yield* loadOpenCode2Workspace( |
| 1211 | Effect.sync(() => (calls.push("read"), scanned)), |
| 1212 | Effect.sync(() => void calls.push("scanned")), |
| 1213 | Effect.succeed(true), |
| 1214 | ); |
| 1215 | NodeAssert.deepEqual(workspace, scanned); |
| 1216 | NodeAssert.deepEqual(calls, ["read"]); |
| 1217 | }), |
| 1218 | ); |
| 1219 | |
| 1220 | it.effect("lists a catalog whose cold server start outlasts the settle budget", () => |
| 1221 | Effect.gen(function* () { |
| 1222 | const catalog: ReadonlyArray<OpenCode2Model> = [ |
| 1223 | { providerID: "opencode", id: "big-pickle", name: "Big Pickle", variants: [] }, |
| 1224 | ]; |
| 1225 | let reads = 0; |
| 1226 | // The loader's read includes spawning the server; a loaded host can take 6s to start it. |
| 1227 | const read = Effect.suspend(() => |
| 1228 | reads++ === 0 ? Effect.sleep("6 seconds").pipe(Effect.as(catalog)) : Effect.succeed(catalog), |
| 1229 | ); |
| 1230 | const load = yield* makeOpenCode2ModelLoader(read); |
| 1231 | const fiber = yield* Effect.forkChild(load); |
| 1232 | yield* TestClock.adjust("10 seconds"); |
| 1233 | NodeAssert.deepEqual(yield* Fiber.join(fiber), catalog); |
| 1234 | }), |
| 1235 | ); |