The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; |
| 2 | import * as CodexInstallation from "./CodexInstallation.ts"; |
| 3 | import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts"; |
| 4 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 5 | import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk"; |
| 6 | import { describe, expect, it } from "@effect/vitest"; |
| 7 | import { vi } from "vite-plus/test"; |
| 8 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 9 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 10 | import { |
| 11 | AntigravitySettings, |
| 12 | EnvironmentId, |
| 13 | type ClaudeSettings, |
| 14 | type CodexSettings, |
| 15 | ProviderDriverKind, |
| 16 | type ProviderInstanceConfigMap, |
| 17 | type ResolvedProviderInstanceEnvironment, |
| 18 | ProviderInstanceId, |
| 19 | SecretProviderId, |
| 20 | SettingsSecretValue, |
| 21 | type SecretReference, |
| 22 | } from "@t3tools/contracts"; |
| 23 | import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; |
| 24 | import { OpenCodeSettings } from "@t3tools/provider-opencode/settings"; |
| 25 | import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; |
| 26 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 27 | import * as DateTime from "effect/DateTime"; |
| 28 | import * as Deferred from "effect/Deferred"; |
| 29 | import * as Effect from "effect/Effect"; |
| 30 | import * as Exit from "effect/Exit"; |
| 31 | import * as Scope from "effect/Scope"; |
| 32 | import * as Fiber from "effect/Fiber"; |
| 33 | import * as FileSystem from "effect/FileSystem"; |
| 34 | import * as Layer from "effect/Layer"; |
| 35 | import * as Path from "effect/Path"; |
| 36 | import * as PubSub from "effect/PubSub"; |
| 37 | import * as Schema from "effect/Schema"; |
| 38 | import * as TestClock from "effect/testing/TestClock"; |
| 39 | import { HttpClient, HttpClientResponse } from "effect/http"; |
| 40 | |
| 41 | import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; |
| 42 | import * as ServerConfig from "../config.ts"; |
| 43 | import * as ServerSettings from "../serverSettings.ts"; |
| 44 | import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts"; |
| 45 | import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts"; |
| 46 | import * as ModelManifest from "./ModelManifest.ts"; |
| 47 | import * as ResetCreditCoordinator from "./resetCreditCoordinator.ts"; |
| 48 | import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; |
| 49 | import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistry.ts"; |
| 50 | import { ProviderDriverError } from "./Errors.ts"; |
| 51 | import * as ProviderInstallationGate from "./ProviderInstallationGate.ts"; |
| 52 | import * as ProviderOrchestrationAdapterInfrastructure from "./ProviderOrchestrationAdapterInfrastructure.ts"; |
| 53 | import * as PortScanner from "../preview/PortScanner.ts"; |
| 54 | import * as ProviderHostLive from "./ProviderHostLive.ts"; |
| 55 | import * as SqlitePersistence from "../persistence/Sqlite.ts"; |
| 56 | import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; |
| 57 | import type { AnyProviderDriver, ProviderInstance } from "@t3tools/provider-core/server/driver"; |
| 58 | |
| 59 | vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); |
| 60 | |
| 61 | const layerTestHttpClient = Layer.succeed( |
| 62 | HttpClient.HttpClient, |
| 63 | HttpClient.make((request) => |
| 64 | Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))), |
| 65 | ), |
| 66 | ); |
| 67 | |
| 68 | // The mock CLIs from makeTildeProviderFixtures are scripts Windows cannot execute. |
| 69 | const windowsHost = HostProcess.Platform.defaultValue() === "win32"; |
| 70 | |
| 71 | const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"); |
| 72 | |
| 73 | const layerBackgroundPolicyAlwaysRun = Layer.mock(BackgroundPolicy.BackgroundPolicy)({ |
| 74 | reportClientActivity: () => Effect.void, |
| 75 | removeRpcClient: () => Effect.void, |
| 76 | snapshot: Effect.succeed({ |
| 77 | hostPower: { |
| 78 | source: "unknown", |
| 79 | idle: "unknown", |
| 80 | idleSeconds: null, |
| 81 | locked: "unknown", |
| 82 | suspended: false, |
| 83 | onBattery: "unknown", |
| 84 | lowPowerMode: "unknown", |
| 85 | thermalState: "unknown", |
| 86 | stale: true, |
| 87 | updatedAt: TEST_EPOCH, |
| 88 | }, |
| 89 | leases: [], |
| 90 | activeForegroundLeaseCount: 0, |
| 91 | activeScopeKeys: [], |
| 92 | shouldRunOpportunisticWork: true, |
| 93 | updatedAt: TEST_EPOCH, |
| 94 | }), |
| 95 | shouldRunScopeWork: () => Effect.succeed(true), |
| 96 | shouldRunOpportunisticWork: Effect.succeed(true), |
| 97 | }); |
| 98 | |
| 99 | const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({ |
| 100 | enabled: false, |
| 101 | binaryPath: "codex", |
| 102 | homePath: "", |
| 103 | shadowHomePath: "", |
| 104 | launchArgs: "", |
| 105 | customModels: [], |
| 106 | ...overrides, |
| 107 | }); |
| 108 | |
| 109 | const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings => ({ |
| 110 | enabled: false, |
| 111 | binaryPath: "claude", |
| 112 | homePath: "", |
| 113 | customModels: [], |
| 114 | launchArgs: "", |
| 115 | autoCompactWindow: "", |
| 116 | idleCompaction: "default", |
| 117 | ...overrides, |
| 118 | }); |
| 119 | |
| 120 | const makeTildeProviderFixtures = Effect.fn( |
| 121 | "ProviderInstanceRegistry.test.makeTildeProviderFixtures", |
| 122 | )(function* () { |
| 123 | const fileSystem = yield* FileSystem.FileSystem; |
| 124 | const path = yield* Path.Path; |
| 125 | const homePath = yield* HostProcess.HomeDirectory; |
| 126 | const fixtureDir = yield* fileSystem.makeTempDirectoryScoped({ |
| 127 | directory: homePath, |
| 128 | prefix: ".t3-provider-path-test-", |
| 129 | }); |
| 130 | yield* fileSystem.writeFileString( |
| 131 | path.join(fixtureDir, "package.json"), |
| 132 | JSON.stringify({ type: "commonjs" }), |
| 133 | ); |
| 134 | const codexPath = path.join(fixtureDir, "codex"); |
| 135 | const claudePath = path.join(fixtureDir, "claude.mjs"); |
| 136 | const claudeHomePath = path.join(fixtureDir, "claude-home"); |
| 137 | const codexScriptPath = path.join(fixtureDir, "codex-script.json"); |
| 138 | const codexFixtureDir = path.join(import.meta.dirname, "testFixtures"); |
| 139 | |
| 140 | yield* fileSystem.copyFile(path.join(codexFixtureDir, "codexCollabMockPeer.sh"), codexPath); |
| 141 | yield* fileSystem.copyFile( |
| 142 | path.join(codexFixtureDir, "codexCollabMockPeer.mjs"), |
| 143 | path.join(fixtureDir, "codexCollabMockPeer.mjs"), |
| 144 | ); |
| 145 | yield* fileSystem.copyFile( |
| 146 | path.join(codexFixtureDir, "codexMultiAgentWire.json"), |
| 147 | path.join(fixtureDir, "codexMultiAgentWire.json"), |
| 148 | ); |
| 149 | yield* fileSystem.writeFileString( |
| 150 | codexScriptPath, |
| 151 | JSON.stringify({ rootThreadId: "probe-thread", notifications: [] }), |
| 152 | ); |
| 153 | yield* fileSystem.chmod(codexPath, 0o755); |
| 154 | |
| 155 | yield* fileSystem.copyFile( |
| 156 | yield* path.fromFileUrl( |
| 157 | new URL("./testing/ProviderInstanceRegistryLive.fixture.mjs", import.meta.url), |
| 158 | ), |
| 159 | claudePath, |
| 160 | ); |
| 161 | yield* fileSystem.chmod(claudePath, 0o755); |
| 162 | yield* fileSystem.makeDirectory(claudeHomePath); |
| 163 | |
| 164 | const asTildePath = (filePath: string) => `~/${path.relative(homePath, filePath)}`; |
| 165 | return { |
| 166 | codexBinaryPath: asTildePath(codexPath), |
| 167 | claudeBinaryPath: asTildePath(claudePath), |
| 168 | claudeHomePath, |
| 169 | codexScriptPath, |
| 170 | }; |
| 171 | }); |
| 172 | |
| 173 | describe("ProviderInstanceRegistry — multi-instance codex slice", () => { |
| 174 | const layerBaseDeps = ServerConfig.layerTest(process.cwd(), { |
| 175 | prefix: "provider-instance-registry-test", |
| 176 | }).pipe( |
| 177 | Layer.provideMerge( |
| 178 | Layer.mock(CodexManagedTokenBroker.CodexManagedTokenBroker)({ |
| 179 | endpoint: Effect.succeed("unused-private-pipe"), |
| 180 | }), |
| 181 | ), |
| 182 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 183 | Layer.provideMerge( |
| 184 | Layer.mock(CodexInstallation.CodexInstallation)({ |
| 185 | managedDirectory: "unused-managed-installation", |
| 186 | }), |
| 187 | ), |
| 188 | Layer.provideMerge(Layer.mock(ServerSecretStore.ServerSecretStore)({})), |
| 189 | Layer.provideMerge(Layer.mock(SecretResolver.SecretResolver)({})), |
| 190 | Layer.provideMerge( |
| 191 | Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { |
| 192 | getEnvironmentId: Effect.succeed( |
| 193 | EnvironmentId.make("00000000-0000-4000-8000-000000000001"), |
| 194 | ), |
| 195 | }), |
| 196 | ), |
| 197 | Layer.provideMerge(layerBackgroundPolicyAlwaysRun), |
| 198 | Layer.provideMerge(ServerSettings.layerTest()), |
| 199 | Layer.provideMerge(layerTestHttpClient), |
| 200 | Layer.provideMerge(ServerSettings.layerTest()), |
| 201 | Layer.provideMerge( |
| 202 | Layer.succeed( |
| 203 | ProviderEventLoggers.ProviderEventLoggers, |
| 204 | ProviderEventLoggers.NoOpProviderEventLoggers, |
| 205 | ), |
| 206 | ), |
| 207 | Layer.provideMerge(ProviderLatestVersions.layer), |
| 208 | Layer.provideMerge(McpProviderSessions.layer), |
| 209 | Layer.provideMerge(ProviderInstallationGate.layer), |
| 210 | Layer.provideMerge(ModelManifest.layerTest), |
| 211 | Layer.provideMerge(ResetCreditCoordinator.layerTest), |
| 212 | ); |
| 213 | const layerBase = ProviderHostLive.layer.pipe(Layer.provideMerge(layerBaseDeps)); |
| 214 | const layerTest = ProviderOrchestrationAdapterInfrastructure.layer.pipe( |
| 215 | Layer.provide(SqlitePersistence.layerMemory), |
| 216 | Layer.provideMerge(PortScanner.layerTest), |
| 217 | Layer.provideMerge(layerBase), |
| 218 | ); |
| 219 | |
| 220 | it.effect.each(["replacement", "removal", "creation failure"] as const)( |
| 221 | "detaches retired provider scopes after repeated %s", |
| 222 | (scenario) => |
| 223 | Effect.gen(function* () { |
| 224 | const parent = yield* Scope.make(); |
| 225 | const fileSystem = yield* FileSystem.FileSystem; |
| 226 | const homePath = yield* fileSystem.makeTempDirectoryScoped(); |
| 227 | let creates = 0; |
| 228 | let closes = 0; |
| 229 | const driver: typeof CodexDriver = { |
| 230 | ...CodexDriver, |
| 231 | create: Effect.fn("ProviderInstanceRegistry.test.create")(function* ( |
| 232 | input: Parameters<typeof CodexDriver.create>[0], |
| 233 | ) { |
| 234 | creates++; |
| 235 | yield* Effect.addFinalizer(() => |
| 236 | Effect.sync(() => { |
| 237 | closes++; |
| 238 | }), |
| 239 | ); |
| 240 | if (input.config.binaryPath === "creation-failure") { |
| 241 | return yield* new ProviderDriverError({ |
| 242 | driver: CodexDriver.driverKind, |
| 243 | instanceId: input.instanceId, |
| 244 | detail: "fixture creation failed", |
| 245 | }); |
| 246 | } |
| 247 | return yield* CodexDriver.create(input); |
| 248 | }), |
| 249 | }; |
| 250 | const siblingId = ProviderInstanceId.make("sibling"); |
| 251 | const retiredId = ProviderInstanceId.make("retired"); |
| 252 | const entry = { |
| 253 | driver: CodexDriver.driverKind, |
| 254 | enabled: false, |
| 255 | config: makeCodexConfig({ homePath }), |
| 256 | }; |
| 257 | yield* Effect.gen(function* () { |
| 258 | const { registry, mutator } = yield* makeProviderInstanceRegistry({ |
| 259 | drivers: [driver], |
| 260 | configMap: { [siblingId]: entry }, |
| 261 | }); |
| 262 | const sibling = yield* registry.getInstance(siblingId); |
| 263 | const finalizerCount = () => { |
| 264 | const state = parent.state; |
| 265 | return state._tag === "Open" ? (state.finalizers?.size ?? 1) : 0; |
| 266 | }; |
| 267 | const baseline = finalizerCount(); |
| 268 | for (let index = 0; index < 20; index++) { |
| 269 | yield* mutator.reconcile({ |
| 270 | [siblingId]: entry, |
| 271 | [retiredId]: { |
| 272 | ...entry, |
| 273 | config: makeCodexConfig({ |
| 274 | homePath, |
| 275 | binaryPath: scenario === "creation failure" ? "creation-failure" : "unused-codex", |
| 276 | customModels: [`revision-${index}`], |
| 277 | }), |
| 278 | }, |
| 279 | }); |
| 280 | if (scenario === "removal") yield* mutator.reconcile({ [siblingId]: entry }); |
| 281 | } |
| 282 | yield* mutator.reconcile({ [siblingId]: entry }); |
| 283 | expect(yield* registry.getInstance(siblingId)).toBe(sibling); |
| 284 | expect(closes).toBe(creates - 1); |
| 285 | expect(parent.state._tag).toBe("Open"); |
| 286 | expect(finalizerCount()).toBe(baseline); |
| 287 | }).pipe( |
| 288 | Effect.provideService(Scope.Scope, parent), |
| 289 | Effect.ensuring(Scope.close(parent, Exit.void)), |
| 290 | ); |
| 291 | expect(closes).toBe(creates); |
| 292 | }).pipe(Effect.provide(layerTest)), |
| 293 | ); |
| 294 | |
| 295 | it.effect.each(["replacement", "removal"] as const)( |
| 296 | "hides retired instances during reconcile (%s)", |
| 297 | (scenario) => |
| 298 | Effect.gen(function* () { |
| 299 | let closed = 0; |
| 300 | const replacementStarted = yield* Deferred.make<void>(); |
| 301 | const releaseReplacement = yield* Deferred.make<void>(); |
| 302 | const driver: typeof CodexDriver = { |
| 303 | ...CodexDriver, |
| 304 | create: (input) => |
| 305 | Effect.gen(function* () { |
| 306 | if (input.displayName === "Second") { |
| 307 | yield* Deferred.succeed(replacementStarted, undefined); |
| 308 | yield* Deferred.await(releaseReplacement); |
| 309 | } |
| 310 | const instance = yield* CodexDriver.create(input); |
| 311 | yield* Effect.addFinalizer(() => Effect.sync(() => closed++)); |
| 312 | return instance; |
| 313 | }), |
| 314 | }; |
| 315 | const retiredId = ProviderInstanceId.make("retired"); |
| 316 | const siblingId = ProviderInstanceId.make("sibling"); |
| 317 | const nextId = scenario === "replacement" ? retiredId : ProviderInstanceId.make("new"); |
| 318 | const entry = { |
| 319 | driver: CodexDriver.driverKind, |
| 320 | enabled: false, |
| 321 | config: makeCodexConfig({}), |
| 322 | }; |
| 323 | const { registry, mutator } = yield* makeProviderInstanceRegistry({ |
| 324 | drivers: [driver], |
| 325 | configMap: { [retiredId]: entry, [siblingId]: entry }, |
| 326 | }); |
| 327 | const sibling = yield* registry.getInstance(siblingId); |
| 328 | const reconcile = yield* mutator |
| 329 | .reconcile({ |
| 330 | [siblingId]: entry, |
| 331 | [nextId]: { |
| 332 | ...entry, |
| 333 | displayName: "Second", |
| 334 | config: makeCodexConfig({ customModels: ["replacement-model"] }), |
| 335 | }, |
| 336 | }) |
| 337 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 338 | yield* Deferred.await(replacementStarted); |
| 339 | expect(closed).toBe(1); |
| 340 | expect(yield* registry.getInstance(retiredId)).toBeUndefined(); |
| 341 | expect(yield* registry.listInstances).toEqual([sibling]); |
| 342 | yield* Deferred.succeed(releaseReplacement, undefined); |
| 343 | yield* Fiber.join(reconcile); |
| 344 | expect((yield* registry.getInstance(nextId))?.displayName).toBe("Second"); |
| 345 | expect(yield* registry.getInstance(siblingId)).toBe(sibling); |
| 346 | expect(closed).toBe(1); |
| 347 | }).pipe(Effect.provide(layerTest)), |
| 348 | ); |
| 349 | |
| 350 | it.effect("treats an explicit in-config enabled:false as disabling despite the envelope", () => |
| 351 | Effect.gen(function* () { |
| 352 | const staleId = ProviderInstanceId.make("codex_stale"); |
| 353 | const configMap: ProviderInstanceConfigMap = { |
| 354 | [staleId]: { |
| 355 | driver: ProviderDriverKind.make("codex"), |
| 356 | enabled: true, |
| 357 | config: makeCodexConfig({ enabled: false }), |
| 358 | }, |
| 359 | }; |
| 360 | |
| 361 | const { registry } = yield* makeProviderInstanceRegistry({ |
| 362 | drivers: [CodexDriver], |
| 363 | configMap, |
| 364 | }); |
| 365 | |
| 366 | const instance = yield* registry.getInstance(staleId); |
| 367 | expect(instance).toBeDefined(); |
| 368 | expect(instance!.enabled).toBe(false); |
| 369 | const snapshot = yield* instance!.snapshot.getSnapshot; |
| 370 | expect(snapshot.enabled).toBe(false); |
| 371 | }).pipe(Effect.provide(layerTest)), |
| 372 | ); |
| 373 | |
| 374 | it.effect("lists a blocked driver's instances as unavailable without running them", () => |
| 375 | Effect.gen(function* () { |
| 376 | const instanceId = ProviderInstanceId.make("codex"); |
| 377 | const reason = "Example Corp's policy does not allow the Codex provider."; |
| 378 | const { registry } = yield* makeProviderInstanceRegistry({ |
| 379 | drivers: [CodexDriver], |
| 380 | configMap: { [instanceId]: { driver: ProviderDriverKind.make("codex") } }, |
| 381 | blockedReason: (driver) => (driver === "codex" ? reason : undefined), |
| 382 | }); |
| 383 | |
| 384 | expect(yield* registry.getInstance(instanceId)).toBeUndefined(); |
| 385 | const [unavailable] = yield* registry.listUnavailable; |
| 386 | expect(unavailable?.instanceId).toBe(instanceId); |
| 387 | expect(unavailable?.availability).toBe("unavailable"); |
| 388 | expect(unavailable?.unavailableReason).toBe(reason); |
| 389 | }).pipe(Effect.provide(layerTest)), |
| 390 | ); |
| 391 | |
| 392 | it.live("runs Codex and Claude readiness probes from configured tilde paths", () => |
| 393 | Effect.gen(function* () { |
| 394 | if (yield* HostProcess.isWindows) return; |
| 395 | |
| 396 | const fixtures = yield* makeTildeProviderFixtures(); |
| 397 | |
| 398 | const codexId = ProviderInstanceId.make("codex_tilde"); |
| 399 | const claudeId = ProviderInstanceId.make("claude_tilde"); |
| 400 | const configMap: ProviderInstanceConfigMap = { |
| 401 | [codexId]: { |
| 402 | driver: ProviderDriverKind.make("codex"), |
| 403 | enabled: true, |
| 404 | environment: [ |
| 405 | { |
| 406 | name: "T3_CODEX_COLLAB_SCRIPT", |
| 407 | value: fixtures.codexScriptPath, |
| 408 | sensitive: false, |
| 409 | }, |
| 410 | ], |
| 411 | config: makeCodexConfig({ enabled: true, binaryPath: fixtures.codexBinaryPath }), |
| 412 | }, |
| 413 | [claudeId]: { |
| 414 | driver: ProviderDriverKind.make("claudeAgent"), |
| 415 | enabled: true, |
| 416 | config: makeClaudeConfig({ |
| 417 | enabled: true, |
| 418 | binaryPath: fixtures.claudeBinaryPath, |
| 419 | homePath: fixtures.claudeHomePath, |
| 420 | }), |
| 421 | }, |
| 422 | }; |
| 423 | |
| 424 | const { registry } = yield* makeProviderInstanceRegistry<CodexDriverEnv | ClaudeDriverEnv>({ |
| 425 | drivers: [CodexDriver, ClaudeDriver], |
| 426 | configMap, |
| 427 | }); |
| 428 | const codex = yield* registry.getInstance(codexId); |
| 429 | const claude = yield* registry.getInstance(claudeId); |
| 430 | expect(codex).toBeDefined(); |
| 431 | expect(claude).toBeDefined(); |
| 432 | |
| 433 | const [codexSnapshot, claudeSnapshot] = yield* Effect.all( |
| 434 | [codex!.snapshot.refresh, claude!.snapshot.refresh], |
| 435 | { concurrency: "unbounded" }, |
| 436 | ); |
| 437 | expect(codexSnapshot).toMatchObject({ status: "ready", installed: true, version: "0.0.0" }); |
| 438 | expect(claudeSnapshot).toMatchObject({ |
| 439 | status: "ready", |
| 440 | installed: true, |
| 441 | version: "2.1.219", |
| 442 | }); |
| 443 | }).pipe(Effect.provide(layerTest)), |
| 444 | ); |
| 445 | |
| 446 | it.live("runs Claude instance probes in the server state dir, not the server cwd", () => |
| 447 | Effect.gen(function* () { |
| 448 | if (yield* HostProcess.isWindows) return; |
| 449 | |
| 450 | const fixtures = yield* makeTildeProviderFixtures(); |
| 451 | const { stateDir } = yield* ServerConfig.ServerConfig; |
| 452 | const claudeId = ProviderInstanceId.make("claude_state_dir"); |
| 453 | const { registry } = yield* makeProviderInstanceRegistry<ClaudeDriverEnv>({ |
| 454 | drivers: [ClaudeDriver], |
| 455 | configMap: { |
| 456 | [claudeId]: { |
| 457 | driver: ProviderDriverKind.make("claudeAgent"), |
| 458 | enabled: true, |
| 459 | // Packaged desktop starts in $HOME, where some claude wrappers refuse to run. |
| 460 | environment: [{ name: "T3_CLAUDE_REQUIRED_CWD", value: stateDir, sensitive: false }], |
| 461 | config: makeClaudeConfig({ |
| 462 | enabled: true, |
| 463 | binaryPath: fixtures.claudeBinaryPath, |
| 464 | homePath: fixtures.claudeHomePath, |
| 465 | }), |
| 466 | }, |
| 467 | }, |
| 468 | }); |
| 469 | const claude = yield* registry.getInstance(claudeId); |
| 470 | |
| 471 | expect(yield* claude!.snapshot.refresh).toMatchObject({ |
| 472 | status: "ready", |
| 473 | version: "2.1.219", |
| 474 | auth: { status: "authenticated" }, |
| 475 | }); |
| 476 | }).pipe(Effect.provide(layerTest)), |
| 477 | ); |
| 478 | |
| 479 | it.live("applies the lowest maxEffortLevel across Claude's settings sources", () => |
| 480 | Effect.gen(function* () { |
| 481 | if (yield* HostProcess.isWindows) return; |
| 482 | |
| 483 | const fixtures = yield* makeTildeProviderFixtures(); |
| 484 | const claudeId = ProviderInstanceId.make("claude_source_effort_cap"); |
| 485 | const { registry } = yield* makeProviderInstanceRegistry<ClaudeDriverEnv>({ |
| 486 | drivers: [ClaudeDriver], |
| 487 | configMap: { |
| 488 | [claudeId]: { |
| 489 | driver: ProviderDriverKind.make("claudeAgent"), |
| 490 | enabled: true, |
| 491 | environment: [ |
| 492 | { |
| 493 | name: "T3_CLAUDE_SETTINGS_SOURCES", |
| 494 | // The merged `effective` settings read as exempting Opus 5; the flag tier's |
| 495 | // top-level cap still applies to it. |
| 496 | value: JSON.stringify([ |
| 497 | { |
| 498 | source: "userSettings", |
| 499 | settings: { modelSettings: { "claude-opus-5": { maxEffortLevel: "max" } } }, |
| 500 | }, |
| 501 | { source: "flagSettings", settings: { maxEffortLevel: "high" } }, |
| 502 | ]), |
| 503 | sensitive: false, |
| 504 | }, |
| 505 | ], |
| 506 | config: makeClaudeConfig({ |
| 507 | enabled: true, |
| 508 | binaryPath: fixtures.claudeBinaryPath, |
| 509 | homePath: fixtures.claudeHomePath, |
| 510 | }), |
| 511 | }, |
| 512 | }, |
| 513 | }); |
| 514 | const claude = yield* registry.getInstance(claudeId); |
| 515 | |
| 516 | const snapshot = yield* claude!.snapshot.refresh; |
| 517 | const maxLabel = snapshot.models |
| 518 | .find((model) => model.slug === "claude-opus-5") |
| 519 | ?.capabilities?.optionDescriptors?.flatMap((descriptor) => |
| 520 | descriptor.id === "effort" && descriptor.type === "select" |
| 521 | ? descriptor.options.filter((option) => option.id === "max") |
| 522 | : [], |
| 523 | )[0]?.label; |
| 524 | expect(maxLabel).toBe("Max (capped to High)"); |
| 525 | }).pipe(Effect.provide(layerTest)), |
| 526 | ); |
| 527 | |
| 528 | it.live("keeps usage and uncapped efforts when the CLI rejects get_settings", () => |
| 529 | Effect.gen(function* () { |
| 530 | if (yield* HostProcess.isWindows) return; |
| 531 | |
| 532 | const fixtures = yield* makeTildeProviderFixtures(); |
| 533 | const claudeId = ProviderInstanceId.make("claude_settings_unsupported"); |
| 534 | const { registry } = yield* makeProviderInstanceRegistry<ClaudeDriverEnv>({ |
| 535 | drivers: [ClaudeDriver], |
| 536 | configMap: { |
| 537 | [claudeId]: { |
| 538 | driver: ProviderDriverKind.make("claudeAgent"), |
| 539 | enabled: true, |
| 540 | environment: [{ name: "T3_CLAUDE_SETTINGS_UNSUPPORTED", value: "1", sensitive: false }], |
| 541 | config: makeClaudeConfig({ |
| 542 | enabled: true, |
| 543 | binaryPath: fixtures.claudeBinaryPath, |
| 544 | homePath: fixtures.claudeHomePath, |
| 545 | }), |
| 546 | }, |
| 547 | }, |
| 548 | }); |
| 549 | const claude = yield* registry.getInstance(claudeId); |
| 550 | |
| 551 | const snapshot = yield* claude!.snapshot.refresh; |
| 552 | const effortLabels = snapshot.models.flatMap((model) => |
| 553 | (model.capabilities?.optionDescriptors ?? []).flatMap((descriptor) => |
| 554 | descriptor.id === "effort" && descriptor.type === "select" |
| 555 | ? descriptor.options.map((option) => option.label) |
| 556 | : [], |
| 557 | ), |
| 558 | ); |
| 559 | expect(effortLabels).toContain("Max"); |
| 560 | expect(effortLabels.some((label) => label.includes("capped"))).toBe(false); |
| 561 | expect(snapshot.auth).toMatchObject({ status: "authenticated", email: "test@example.com" }); |
| 562 | expect(snapshot.usageLimits?.windows[0]?.usedPercent).toBe(100); |
| 563 | }).pipe(Effect.provide(layerTest)), |
| 564 | ); |
| 565 | |
| 566 | it.effect("scopes Claude's one-probe fallback to the logged-in organization", () => |
| 567 | Effect.gen(function* () { |
| 568 | if (yield* HostProcess.isWindows) return; |
| 569 | |
| 570 | const fixtures = yield* makeTildeProviderFixtures(); |
| 571 | const fs = yield* FileSystem.FileSystem; |
| 572 | const path = yield* Path.Path; |
| 573 | const accountConfigPath = path.join(fixtures.claudeHomePath, ".claude.json"); |
| 574 | yield* fs.writeFileString( |
| 575 | accountConfigPath, |
| 576 | JSON.stringify({ oauthAccount: { organizationUuid: "org-a" } }), |
| 577 | ); |
| 578 | const claudeId = ProviderInstanceId.make("claude_probe_recovery"); |
| 579 | let probeCount = 0; |
| 580 | let successfulProbeCount = 0; |
| 581 | let failProbe = false; |
| 582 | const query = vi.spyOn(ClaudeSdk, "query").mockImplementation( |
| 583 | () => |
| 584 | ({ |
| 585 | initializationResult: () => { |
| 586 | probeCount++; |
| 587 | if (failProbe) return Promise.reject(new Error("initialization failed")); |
| 588 | successfulProbeCount++; |
| 589 | return Promise.resolve({ |
| 590 | commands: [ |
| 591 | { |
| 592 | name: successfulProbeCount === 1 ? "last-good" : "recovered", |
| 593 | description: "", |
| 594 | argumentHint: "", |
| 595 | }, |
| 596 | ], |
| 597 | account: { |
| 598 | email: |
| 599 | successfulProbeCount === 1 ? "account-a@example.com" : "account-b@example.com", |
| 600 | subscriptionType: "pro", |
| 601 | tokenSource: "oauth", |
| 602 | }, |
| 603 | }); |
| 604 | }, |
| 605 | usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => ({ |
| 606 | rate_limits_available: true, |
| 607 | rate_limits: { |
| 608 | five_hour: { utilization: 12, resets_at: "2026-07-18T14:39:00Z" }, |
| 609 | }, |
| 610 | }), |
| 611 | }) as ReturnType<typeof ClaudeSdk.query>, |
| 612 | ); |
| 613 | yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore())); |
| 614 | |
| 615 | const { registry } = yield* makeProviderInstanceRegistry<ClaudeDriverEnv>({ |
| 616 | drivers: [ClaudeDriver], |
| 617 | configMap: { |
| 618 | [claudeId]: { |
| 619 | driver: ProviderDriverKind.make("claudeAgent"), |
| 620 | enabled: true, |
| 621 | config: makeClaudeConfig({ |
| 622 | enabled: true, |
| 623 | binaryPath: fixtures.claudeBinaryPath, |
| 624 | homePath: fixtures.claudeHomePath, |
| 625 | }), |
| 626 | }, |
| 627 | }, |
| 628 | }); |
| 629 | const claude = yield* registry.getInstance(claudeId); |
| 630 | expect(claude).toBeDefined(); |
| 631 | |
| 632 | const first = yield* claude!.snapshot.refresh; |
| 633 | expect(first).toMatchObject({ |
| 634 | status: "ready", |
| 635 | auth: { status: "authenticated", email: "account-a@example.com", workspaceId: "org-a" }, |
| 636 | slashCommands: expect.arrayContaining([expect.objectContaining({ name: "last-good" })]), |
| 637 | }); |
| 638 | expect(first.usageLimits?.unavailable).toBeUndefined(); |
| 639 | expect(probeCount).toBe(1); |
| 640 | |
| 641 | yield* TestClock.adjust("1 second"); |
| 642 | yield* fs.writeFileString( |
| 643 | accountConfigPath, |
| 644 | JSON.stringify({ oauthAccount: { organizationUuid: "org-b" } }), |
| 645 | ); |
| 646 | yield* claude!.invalidateCaches ?? Effect.void; |
| 647 | failProbe = true; |
| 648 | const accountChangedFailure = yield* claude!.snapshot.refresh; |
| 649 | |
| 650 | expect(accountChangedFailure).toMatchObject({ |
| 651 | status: "warning", |
| 652 | auth: { status: "unknown" }, |
| 653 | message: "Claude Agent CLI failed while checking account status.", |
| 654 | }); |
| 655 | expect(accountChangedFailure.checkedAt).not.toBe(first.checkedAt); |
| 656 | expect(accountChangedFailure.usageLimits).toBeUndefined(); |
| 657 | expect(accountChangedFailure.slashCommands).not.toEqual( |
| 658 | expect.arrayContaining([expect.objectContaining({ name: "last-good" })]), |
| 659 | ); |
| 660 | const failedProbeCount = probeCount; |
| 661 | expect(failedProbeCount).toBeGreaterThan(1); |
| 662 | |
| 663 | failProbe = false; |
| 664 | const recovered = yield* claude!.snapshot.refresh; |
| 665 | expect(recovered).toMatchObject({ |
| 666 | status: "ready", |
| 667 | auth: { status: "authenticated", email: "account-b@example.com", workspaceId: "org-b" }, |
| 668 | slashCommands: expect.arrayContaining([expect.objectContaining({ name: "recovered" })]), |
| 669 | }); |
| 670 | expect(recovered.usageLimits?.unavailable).toBeUndefined(); |
| 671 | const recoveredProbeCount = probeCount; |
| 672 | expect(recoveredProbeCount).toBeGreaterThan(failedProbeCount); |
| 673 | |
| 674 | yield* TestClock.adjust("1 second"); |
| 675 | yield* claude!.invalidateCaches ?? Effect.void; |
| 676 | failProbe = true; |
| 677 | const sameAccountFailure = yield* claude!.snapshot.refresh; |
| 678 | expect(sameAccountFailure).toMatchObject({ |
| 679 | status: "ready", |
| 680 | auth: { status: "authenticated", email: "account-b@example.com", workspaceId: "org-b" }, |
| 681 | slashCommands: expect.arrayContaining([expect.objectContaining({ name: "recovered" })]), |
| 682 | }); |
| 683 | expect(sameAccountFailure.usageLimits?.checkedAt).toBe(recovered.usageLimits?.checkedAt); |
| 684 | expect(sameAccountFailure.usageLimits?.windows).toEqual(recovered.usageLimits?.windows); |
| 685 | const sameAccountFailureProbeCount = probeCount; |
| 686 | expect(sameAccountFailureProbeCount).toBeGreaterThan(recoveredProbeCount); |
| 687 | |
| 688 | const repeatedFailure = yield* claude!.snapshot.refresh; |
| 689 | expect(repeatedFailure).toMatchObject({ |
| 690 | status: "warning", |
| 691 | auth: { status: "unknown" }, |
| 692 | message: "Claude Agent CLI failed while checking account status.", |
| 693 | }); |
| 694 | expect(repeatedFailure.slashCommands).not.toEqual( |
| 695 | expect.arrayContaining([expect.objectContaining({ name: "recovered" })]), |
| 696 | ); |
| 697 | expect(probeCount).toBeGreaterThan(sameAccountFailureProbeCount); |
| 698 | }).pipe(Effect.provide(layerTest)), |
| 699 | ); |
| 700 | |
| 701 | const redeemClaudeReset = (claim: { result: string; usageFailsAfterClaim: boolean }) => |
| 702 | Effect.gen(function* () { |
| 703 | const fs = yield* FileSystem.FileSystem; |
| 704 | const path = yield* Path.Path; |
| 705 | const fixtures = yield* makeTildeProviderFixtures(); |
| 706 | const marker = path.join(fixtures.claudeHomePath, "redeemed"); |
| 707 | yield* fs.writeFileString( |
| 708 | path.join(fixtures.claudeHomePath, ".credentials.json"), |
| 709 | '{"claudeAiOauth":{"accessToken":"fake-token"}}', |
| 710 | ); |
| 711 | yield* fs.writeFileString( |
| 712 | path.join(fixtures.claudeHomePath, ".claude.json"), |
| 713 | '{"oauthAccount":{"organizationUuid":"fake-org"}}', |
| 714 | ); |
| 715 | const client = HttpClient.make((request) => |
| 716 | Effect.gen(function* () { |
| 717 | if (request.url.endsWith("/api/oauth/usage")) { |
| 718 | return HttpClientResponse.fromWeb( |
| 719 | request, |
| 720 | Response.json({ |
| 721 | cedar_ember: { |
| 722 | eligible: true, |
| 723 | next_grant_id: "grant_a", |
| 724 | grants: [{ id: "grant_a", resets_left: 1, usable_now: true }], |
| 725 | }, |
| 726 | }), |
| 727 | ); |
| 728 | } |
| 729 | if (request.url.endsWith("/reset_rate_limits")) { |
| 730 | yield* fs.writeFileString(marker, "redeemed").pipe(Effect.orDie); |
| 731 | return HttpClientResponse.fromWeb(request, Response.json({ result: claim.result })); |
| 732 | } |
| 733 | return HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" })); |
| 734 | }), |
| 735 | ); |
| 736 | const instanceId = ProviderInstanceId.make("claude_reset"); |
| 737 | const { registry } = yield* makeProviderInstanceRegistry({ |
| 738 | drivers: [ClaudeDriver], |
| 739 | configMap: { |
| 740 | [instanceId]: { |
| 741 | driver: ProviderDriverKind.make("claudeAgent"), |
| 742 | enabled: true, |
| 743 | environment: [ |
| 744 | { name: "T3_CLAUDE_RESET_MARKER", value: marker, sensitive: false }, |
| 745 | ...(claim.usageFailsAfterClaim |
| 746 | ? [{ name: "T3_CLAUDE_USAGE_FAILS_AFTER_CLAIM", value: "1", sensitive: false }] |
| 747 | : []), |
| 748 | ], |
| 749 | config: makeClaudeConfig({ |
| 750 | enabled: true, |
| 751 | binaryPath: fixtures.claudeBinaryPath, |
| 752 | homePath: fixtures.claudeHomePath, |
| 753 | }), |
| 754 | }, |
| 755 | }, |
| 756 | }).pipe(Effect.provideService(HttpClient.HttpClient, client)); |
| 757 | const instance = yield* registry.getInstance(instanceId); |
| 758 | expect(instance).toBeDefined(); |
| 759 | const before = yield* instance!.snapshot.refresh; |
| 760 | expect(before.usageLimits?.windows[0]?.usedPercent).toBe(100); |
| 761 | expect(before.usageLimits?.resetCredits?.nextCreditId).toBe("grant_a"); |
| 762 | const outcome = yield* instance!.consumeResetCredit!(undefined).pipe(Effect.result); |
| 763 | return { outcome, after: yield* instance!.snapshot.getSnapshot }; |
| 764 | }).pipe( |
| 765 | // macOS logins live in the Keychain, where resets are never read. |
| 766 | Effect.provideService(HostProcess.Platform, "linux"), |
| 767 | Effect.provide(layerTest), |
| 768 | ); |
| 769 | |
| 770 | it.live.skipIf(windowsHost)("refreshes Claude usage after redeeming a reset", () => |
| 771 | Effect.gen(function* () { |
| 772 | const { outcome, after } = yield* redeemClaudeReset({ |
| 773 | result: "reset", |
| 774 | usageFailsAfterClaim: false, |
| 775 | }); |
| 776 | expect(outcome).toMatchObject({ _tag: "Success", success: "reset" }); |
| 777 | expect(after.usageLimits?.windows[0]?.usedPercent).toBe(0); |
| 778 | }), |
| 779 | ); |
| 780 | |
| 781 | it.live.skipIf(windowsHost)( |
| 782 | "reports Claude's answer when a claim changed nothing and the re-probe fails", |
| 783 | () => |
| 784 | Effect.gen(function* () { |
| 785 | const { outcome } = yield* redeemClaudeReset({ |
| 786 | result: "already_used", |
| 787 | usageFailsAfterClaim: true, |
| 788 | }); |
| 789 | expect(outcome).toMatchObject({ _tag: "Success", success: "alreadyRedeemed" }); |
| 790 | }), |
| 791 | ); |
| 792 | |
| 793 | const makeClaudeCacheFixture = Effect.fnUntraced(function* ( |
| 794 | state: "ready" | "signed-out" | "usage-failed", |
| 795 | ) { |
| 796 | const fs = yield* FileSystem.FileSystem; |
| 797 | const path = yield* Path.Path; |
| 798 | const fixtures = yield* makeTildeProviderFixtures(); |
| 799 | const recovered = path.join(fixtures.claudeHomePath, "recovered"); |
| 800 | const probeLog = path.join(fixtures.claudeHomePath, "probes.log"); |
| 801 | const instanceId = ProviderInstanceId.make("claude_cache"); |
| 802 | const { registry } = yield* makeProviderInstanceRegistry({ |
| 803 | drivers: [ClaudeDriver], |
| 804 | configMap: { |
| 805 | [instanceId]: { |
| 806 | driver: ProviderDriverKind.make("claudeAgent"), |
| 807 | enabled: true, |
| 808 | environment: [ |
| 809 | { name: "T3_CLAUDE_PROBE_LOG", value: probeLog, sensitive: false }, |
| 810 | ...(state === "ready" |
| 811 | ? [] |
| 812 | : [ |
| 813 | { |
| 814 | name: |
| 815 | state === "signed-out" |
| 816 | ? "T3_CLAUDE_LOGIN_MARKER" |
| 817 | : "T3_CLAUDE_USAGE_FAILS_UNTIL", |
| 818 | value: recovered, |
| 819 | sensitive: false, |
| 820 | }, |
| 821 | ]), |
| 822 | ], |
| 823 | config: makeClaudeConfig({ |
| 824 | enabled: true, |
| 825 | binaryPath: fixtures.claudeBinaryPath, |
| 826 | homePath: fixtures.claudeHomePath, |
| 827 | }), |
| 828 | }, |
| 829 | }, |
| 830 | }); |
| 831 | const instance = yield* registry.getInstance(instanceId); |
| 832 | expect(instance).toBeDefined(); |
| 833 | return { |
| 834 | refresh: instance!.snapshot.refresh, |
| 835 | recover: fs.writeFileString(recovered, ""), |
| 836 | probeLog: fs.readFileString(probeLog), |
| 837 | }; |
| 838 | }); |
| 839 | |
| 840 | for (const state of ["signed-out", "usage-failed"] as const) { |
| 841 | it.effect.skipIf(windowsHost)( |
| 842 | state === "signed-out" |
| 843 | ? "shows Claude usage on the first refresh after signing back in" |
| 844 | : "retries Claude usage on the first refresh after a failed usage read", |
| 845 | () => |
| 846 | Effect.gen(function* () { |
| 847 | const fixture = yield* makeClaudeCacheFixture(state); |
| 848 | const before = yield* fixture.refresh; |
| 849 | if (state === "signed-out") { |
| 850 | expect(before.auth.status).toBe("unauthenticated"); |
| 851 | expect(before.usageLimits).toBeUndefined(); |
| 852 | } else { |
| 853 | expect(before.auth.status).toBe("authenticated"); |
| 854 | expect(before.usageLimits?.unavailable?.reason).toBe("probeFailed"); |
| 855 | } |
| 856 | |
| 857 | yield* fixture.recover; |
| 858 | const after = yield* fixture.refresh; |
| 859 | expect(after.auth.status).toBe("authenticated"); |
| 860 | expect(after.usageLimits?.unavailable).toBeUndefined(); |
| 861 | expect(after.usageLimits?.windows.map((window) => window.id)).toEqual(["five_hour"]); |
| 862 | }).pipe(Effect.provide(layerTest)), |
| 863 | ); |
| 864 | } |
| 865 | |
| 866 | it.effect( |
| 867 | "shadows instances whose driver is not registered in this build without failing boot", |
| 868 | () => |
| 869 | Effect.gen(function* () { |
| 870 | const codexId = ProviderInstanceId.make("codex_main"); |
| 871 | const ghostId = ProviderInstanceId.make("ghost_main"); |
| 872 | |
| 873 | const configMap: ProviderInstanceConfigMap = { |
| 874 | [codexId]: { |
| 875 | driver: ProviderDriverKind.make("codex"), |
| 876 | enabled: false, |
| 877 | config: makeCodexConfig({}), |
| 878 | }, |
| 879 | [ghostId]: { |
| 880 | driver: ProviderDriverKind.make("ghostDriver"), |
| 881 | displayName: "A fork-only driver we don't ship", |
| 882 | enabled: false, |
| 883 | config: { arbitrary: "payload", preserved: true }, |
| 884 | }, |
| 885 | }; |
| 886 | |
| 887 | const { registry } = yield* makeProviderInstanceRegistry<CodexDriverEnv>({ |
| 888 | drivers: [CodexDriver], |
| 889 | configMap, |
| 890 | }); |
| 891 | |
| 892 | const instances = yield* registry.listInstances; |
| 893 | expect(instances).toHaveLength(1); |
| 894 | expect(instances[0]!.instanceId).toBe(codexId); |
| 895 | |
| 896 | const unavailable = yield* registry.listUnavailable; |
| 897 | expect(unavailable).toHaveLength(1); |
| 898 | const ghost = unavailable[0]!; |
| 899 | expect(ghost.instanceId).toBe(ghostId); |
| 900 | expect(ghost.driver).toBe("ghostDriver"); |
| 901 | expect(ghost.availability).toBe("unavailable"); |
| 902 | expect(ghost.unavailableReason).toMatch(/ghostDriver/); |
| 903 | }).pipe(Effect.provide(layerTest)), |
| 904 | ); |
| 905 | }); |
| 906 | |
| 907 | const DisabledByDefaultConfig = Schema.Struct({ |
| 908 | enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), |
| 909 | }); |
| 910 | |
| 911 | describe("ProviderInstanceRegistry secret environment", () => { |
| 912 | const driverKind = ProviderDriverKind.make("fake"); |
| 913 | const instanceId = ProviderInstanceId.make("fake_main"); |
| 914 | const secret: SecretReference = { |
| 915 | provider: SecretProviderId.make("personal"), |
| 916 | reference: "op://Private/OpenAI/credential", |
| 917 | }; |
| 918 | |
| 919 | function setup( |
| 920 | initial: Record<string, string>, |
| 921 | configSchema: AnyProviderDriver["configSchema"] = Schema.Unknown, |
| 922 | config: unknown = {}, |
| 923 | ) { |
| 924 | const vault = new Map(Object.entries(initial)); |
| 925 | const reads: Array<ReadonlyArray<string>> = []; |
| 926 | const invalidated: Array<ReadonlyArray<string>> = []; |
| 927 | const created: Array<ResolvedProviderInstanceEnvironment> = []; |
| 928 | const configs: Array<unknown> = []; |
| 929 | const driver: AnyProviderDriver = { |
| 930 | driverKind, |
| 931 | metadata: { displayName: "Fake" }, |
| 932 | configSchema, |
| 933 | defaultConfig: () => ({}), |
| 934 | create: (input) => |
| 935 | Effect.sync(() => { |
| 936 | created.push(input.environment); |
| 937 | configs.push(input.config); |
| 938 | return { instanceId: input.instanceId, enabled: input.enabled } as ProviderInstance; |
| 939 | }), |
| 940 | }; |
| 941 | const gate = Deferred.makeUnsafe<void>(); |
| 942 | const resolver = Layer.succeed(SecretResolver.SecretResolver, { |
| 943 | label: (provider) => Effect.succeed(provider), |
| 944 | read: (references) => |
| 945 | Deferred.await(gate).pipe( |
| 946 | Effect.andThen( |
| 947 | Effect.sync(() => { |
| 948 | reads.push(references.map((reference) => reference.reference)); |
| 949 | return references.map((reference) => vault.get(reference.reference)); |
| 950 | }), |
| 951 | ), |
| 952 | ), |
| 953 | invalidate: (references = []) => |
| 954 | Effect.sync(() => { |
| 955 | invalidated.push(references.map((reference) => reference.reference)); |
| 956 | }), |
| 957 | }); |
| 958 | const configMap: ProviderInstanceConfigMap = { |
| 959 | [instanceId]: { |
| 960 | driver: driverKind, |
| 961 | config, |
| 962 | environment: [ |
| 963 | { name: "OPENAI_API_KEY", value: secret, sensitive: true }, |
| 964 | { name: "BASE_URL", value: "https://example.test", sensitive: false }, |
| 965 | ], |
| 966 | }, |
| 967 | }; |
| 968 | const makeGated = makeProviderInstanceRegistry({ drivers: [driver], configMap }).pipe( |
| 969 | Effect.provide(resolver), |
| 970 | ); |
| 971 | // Secrets are read after startup, so wait for the change that applies them. |
| 972 | const make = Effect.gen(function* () { |
| 973 | const built = yield* makeGated; |
| 974 | const changes = yield* built.registry.subscribeChanges; |
| 975 | yield* Deferred.succeed(gate, undefined); |
| 976 | yield* PubSub.take(changes); |
| 977 | return built; |
| 978 | }); |
| 979 | return { vault, reads, invalidated, created, configs, configMap, make, makeGated, gate }; |
| 980 | } |
| 981 | |
| 982 | it.effect("starts an instance with the secret its environment points at", () => { |
| 983 | const fixture = setup({ [secret.reference]: "sk-live" }); |
| 984 | return Effect.gen(function* () { |
| 985 | const { registry } = yield* fixture.make; |
| 986 | |
| 987 | expect(yield* registry.getInstance(instanceId)).toBeDefined(); |
| 988 | expect(fixture.created).toEqual([ |
| 989 | [ |
| 990 | { name: "OPENAI_API_KEY", value: "sk-live", sensitive: true }, |
| 991 | { name: "BASE_URL", value: "https://example.test", sensitive: false }, |
| 992 | ], |
| 993 | ]); |
| 994 | }); |
| 995 | }); |
| 996 | |
| 997 | // An empty secret must not let a driver fall back to a credential the server inherited. |
| 998 | it.effect.each([ |
| 999 | ["missing", {}], |
| 1000 | ["empty", { [secret.reference]: " " }], |
| 1001 | ] as const)("marks an instance unavailable when its secret is %s", ([, initial]) => { |
| 1002 | const fixture = setup(initial); |
| 1003 | return Effect.gen(function* () { |
| 1004 | const { registry, mutator } = yield* fixture.make; |
| 1005 | const readsAtStartup = fixture.reads.length; |
| 1006 | |
| 1007 | expect(yield* registry.getInstance(instanceId)).toBeUndefined(); |
| 1008 | expect(fixture.created).toEqual([]); |
| 1009 | const [unavailable] = yield* registry.listUnavailable; |
| 1010 | expect(unavailable?.instanceId).toBe(instanceId); |
| 1011 | expect(unavailable?.unavailableReason).toContain("OPENAI_API_KEY"); |
| 1012 | |
| 1013 | // A settings save that leaves it alone does not read the vault again. |
| 1014 | yield* mutator.reconcile({ ...fixture.configMap }); |
| 1015 | expect(fixture.reads).toHaveLength(readsAtStartup); |
| 1016 | expect(yield* registry.listUnavailable).toHaveLength(1); |
| 1017 | }); |
| 1018 | }); |
| 1019 | |
| 1020 | it.effect("does not read the secrets of an instance its config decodes as disabled", () => { |
| 1021 | const fixture = setup({ [secret.reference]: "sk-live" }, DisabledByDefaultConfig); |
| 1022 | return Effect.gen(function* () { |
| 1023 | const { mutator } = yield* fixture.makeGated; |
| 1024 | yield* mutator.reloadSecrets(); |
| 1025 | |
| 1026 | expect(fixture.reads).toEqual([]); |
| 1027 | expect(fixture.invalidated).toEqual([]); |
| 1028 | expect(fixture.created).toHaveLength(1); |
| 1029 | }); |
| 1030 | }); |
| 1031 | |
| 1032 | it.effect("re-reads secrets on reload and rebuilds only when they changed", () => { |
| 1033 | const fixture = setup({}); |
| 1034 | return Effect.gen(function* () { |
| 1035 | const { registry, mutator } = yield* fixture.make; |
| 1036 | |
| 1037 | fixture.vault.set(secret.reference, "sk-live"); |
| 1038 | yield* mutator.reloadSecrets(); |
| 1039 | expect(fixture.invalidated).toEqual([[secret.reference]]); |
| 1040 | expect(yield* registry.getInstance(instanceId)).toBeDefined(); |
| 1041 | expect(yield* registry.listUnavailable).toEqual([]); |
| 1042 | |
| 1043 | yield* mutator.reloadSecrets(instanceId); |
| 1044 | expect(fixture.created).toHaveLength(1); |
| 1045 | |
| 1046 | fixture.vault.set(secret.reference, "sk-rotated"); |
| 1047 | yield* mutator.reloadSecrets(instanceId); |
| 1048 | expect(fixture.created.map((environment) => environment[0]?.value)).toEqual([ |
| 1049 | "sk-live", |
| 1050 | "sk-rotated", |
| 1051 | ]); |
| 1052 | }); |
| 1053 | }); |
| 1054 | |
| 1055 | it.effect("reads a config field typed SettingsSecretValue and rebuilds when it rotates", () => { |
| 1056 | const apiKey: SecretReference = { ...secret, reference: "op://Private/Gateway/key" }; |
| 1057 | const fixture = setup( |
| 1058 | { [secret.reference]: "sk-live", [apiKey.reference]: "gw-live" }, |
| 1059 | Schema.Struct({ apiKey: SettingsSecretValue, model: Schema.String }), |
| 1060 | { apiKey, model: "m" }, |
| 1061 | ); |
| 1062 | return Effect.gen(function* () { |
| 1063 | const { mutator } = yield* fixture.make; |
| 1064 | expect(fixture.reads.at(-1)).toEqual([secret.reference, apiKey.reference]); |
| 1065 | |
| 1066 | fixture.vault.set(apiKey.reference, "gw-rotated"); |
| 1067 | yield* mutator.reloadSecrets(); |
| 1068 | expect(fixture.configs).toEqual([ |
| 1069 | { apiKey: "gw-live", model: "m" }, |
| 1070 | { apiKey: "gw-rotated", model: "m" }, |
| 1071 | ]); |
| 1072 | }); |
| 1073 | }); |
| 1074 | |
| 1075 | it.effect.each([ |
| 1076 | { name: "Antigravity apiKey", schema: AntigravitySettings, field: "apiKey" }, |
| 1077 | { name: "OpenCode serverPassword", schema: OpenCodeSettings, field: "serverPassword" }, |
| 1078 | ])("hands the driver the secret its $name names", ({ schema, field }) => { |
| 1079 | const reference: SecretReference = { ...secret, reference: "op://Private/Provider/key" }; |
| 1080 | const fixture = setup( |
| 1081 | { [secret.reference]: "sk-live", [reference.reference]: "provider-live" }, |
| 1082 | schema, |
| 1083 | { enabled: true, [field]: reference }, |
| 1084 | ); |
| 1085 | return Effect.gen(function* () { |
| 1086 | yield* fixture.make; |
| 1087 | expect(fixture.configs).toEqual([expect.objectContaining({ [field]: "provider-live" })]); |
| 1088 | }); |
| 1089 | }); |
| 1090 | |
| 1091 | it.effect("keeps a working instance live when a reload cannot read its secret", () => { |
| 1092 | const fixture = setup({ [secret.reference]: "sk-live" }); |
| 1093 | return Effect.gen(function* () { |
| 1094 | const { registry, mutator } = yield* fixture.make; |
| 1095 | |
| 1096 | fixture.vault.delete(secret.reference); |
| 1097 | yield* mutator.reloadSecrets(); |
| 1098 | |
| 1099 | expect(yield* registry.getInstance(instanceId)).toBeDefined(); |
| 1100 | expect(yield* registry.listUnavailable).toEqual([]); |
| 1101 | expect(fixture.created).toHaveLength(1); |
| 1102 | }); |
| 1103 | }); |
| 1104 | |
| 1105 | it.effect("starts without waiting for secrets to be read", () => { |
| 1106 | const fixture = setup({ [secret.reference]: "sk-live" }); |
| 1107 | return Effect.gen(function* () { |
| 1108 | const { registry } = yield* fixture.makeGated; |
| 1109 | const changes = yield* registry.subscribeChanges; |
| 1110 | |
| 1111 | expect(yield* registry.getInstance(instanceId)).toBeUndefined(); |
| 1112 | const [pending] = yield* registry.listUnavailable; |
| 1113 | expect(pending?.unavailableReason).toBe("Reading secrets…"); |
| 1114 | |
| 1115 | yield* Deferred.succeed(fixture.gate, undefined); |
| 1116 | yield* PubSub.take(changes); |
| 1117 | expect(yield* registry.getInstance(instanceId)).toBeDefined(); |
| 1118 | expect(yield* registry.listUnavailable).toEqual([]); |
| 1119 | }); |
| 1120 | }); |
| 1121 | }); |