diff --git a/cloud/apps/sandbox-control/src/guardrails.ts b/cloud/apps/sandbox-control/src/guardrails.ts index 53af0905f2e..fb6235ae609 100644 --- a/cloud/apps/sandbox-control/src/guardrails.ts +++ b/cloud/apps/sandbox-control/src/guardrails.ts @@ -1,7 +1,7 @@ // Cost guardrails in front of every start (create, resume, rollover): the operator kill switch, a // global running cap, a per-account concurrency backstop (billing enforces the plan limit too) and a // per-account create rate limit. All are control-plane local, so a billing outage cannot lift them. -import { ACTIVE_STATUSES } from './store' +import { ACTIVE_STATUSES, countActiveSandboxes } from './store' export type GuardrailConfig = { /** Static kill switch from the deploy config (`SANDBOX_CREATES_DISABLED=true`). */ @@ -53,21 +53,16 @@ export function setKillSwitch(db: D1Database, on: boolean, now: number): Promise return setControlState(db, KILL_SWITCH, on ? 'on' : 'off', now) } -async function countActive(db: D1Database, accountId?: string): Promise { +/** Every VM-holding sandbox, all accounts: the global capacity guardrail. */ +export async function countAllActive(db: D1Database): Promise { const placeholders = ACTIVE_STATUSES.map(() => '?').join(', ') const row = await db - .prepare( - `SELECT COUNT(*) AS n FROM sandboxes WHERE status IN (${placeholders}) ${accountId ? 'AND account_id = ?' : ''}` - ) - .bind(...ACTIVE_STATUSES, ...(accountId ? [accountId] : [])) + .prepare(`SELECT COUNT(*) AS n FROM sandboxes WHERE status IN (${placeholders})`) + .bind(...ACTIVE_STATUSES) .first<{ n: number }>() return row?.n ?? 0 } -export function countAllActive(db: D1Database): Promise { - return countActive(db) -} - /** Kill switch + global running cap; checked before billing is asked anything. */ export async function assertStartsOpen(db: D1Database, config: GuardrailConfig): Promise { if (await killSwitchOn(db, config)) { @@ -84,10 +79,12 @@ export async function assertAccountCapacity( db: D1Database, config: GuardrailConfig, accountId: string, - limits: { seats?: number; maxConcurrentSandboxes?: number } = {} + limits: { seats?: number; maxConcurrentSandboxes?: number } = {}, + now: number = Date.now() ): Promise { const cap = limits.maxConcurrentSandboxes ?? config.maxActivePerSeat * Math.max(1, Math.floor(limits.seats ?? 1)) - if ((await countActive(db, accountId)) >= cap) { + // The same count billing was given: a sandbox going to sleep or an abandoned create doesn't refuse a start. + if ((await countActiveSandboxes(db, accountId, now)) >= cap) { throw new GuardrailError('concurrency_limit') } } diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 7bcf03e0ea0..45cb59d83b2 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -1555,7 +1555,7 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {}) { const [{ idleSleepMinutes, ...status }, hints] = await Promise.all([ workspaceStatus(life, row, workspaceConfig(env, deps)), - wakeHintsAware ? wakeHints(life.db, row) : null + wakeHintsAware ? wakeHints(life.db, row, life.now()) : null ]) return json({ sandbox: view(row), diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index 5e8b1ef0fdd..9d3d7e4cf46 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -310,8 +310,8 @@ export function guardrails(deps: LifecycleDeps): GuardrailConfig { export async function requireStart(deps: LifecycleDeps, accountId: string, userId: string, machineSize: MachineSize) { const [, runningSandboxes, runningSandboxesForUser] = await Promise.all([ assertStartsOpen(deps.db, guardrails(deps)), - countActiveSandboxes(deps.db, accountId), - countActiveSandboxesForUser(deps.db, accountId, userId) + countActiveSandboxes(deps.db, accountId, deps.now()), + countActiveSandboxesForUser(deps.db, accountId, userId, deps.now()) ]) const decision = await deps.entitlements.checkStart({ accountId, @@ -326,10 +326,13 @@ export async function requireStart(deps: LifecycleDeps, accountId: string, userI if (!decision.allow) { throw new LifecycleError('entitlement_denied', decision.reason ?? 'denied') } - await assertAccountCapacity(deps.db, guardrails(deps), accountId, { - seats: decision.seats, - maxConcurrentSandboxes: decision.maxConcurrentSandboxes - }) + await assertAccountCapacity( + deps.db, + guardrails(deps), + accountId, + { seats: decision.seats, maxConcurrentSandboxes: decision.maxConcurrentSandboxes }, + deps.now() + ) } function orcadEndpoint(state: ProviderSandboxState): string | null { diff --git a/cloud/apps/sandbox-control/src/reconcile.ts b/cloud/apps/sandbox-control/src/reconcile.ts index ad8ae23caf2..af1d4935220 100644 --- a/cloud/apps/sandbox-control/src/reconcile.ts +++ b/cloud/apps/sandbox-control/src/reconcile.ts @@ -15,7 +15,7 @@ import { import { guardrails } from './lifecycle' import { killSwitchOn } from './guardrails' import { drainAll, housekeeping, openHold, type HousekeepingSummary } from './retention' -import { listByStatus, transition, type SandboxRow } from './store' +import { CREATE_ABANDONED_MS, listByStatus, transition, type SandboxRow } from './store' import { flushUsage, queueUsage } from './usage' import { expiredArchives } from './workspace-lifecycle' import { ACTIVITY_CHECK_BEFORE_LAPSE_MS, ACTIVITY_RENEW_MS, decideFromActivity, readVmActivity } from './vm-activity' @@ -24,9 +24,9 @@ const STUCK_MS = 15 * 60_000 /** * A create's longest legitimate run is a 30 s pooled try, a VM create and the 120 s start command. * Past this its Worker was cut off (the desktop gave up or disconnected): fail it and free the VM - * instead of leaving a billed 'creating' row for the full STUCK_MS. + * instead of leaving a billed 'creating' row for the full STUCK_MS. The start gate stops counting it then too. */ -export const CREATE_STUCK_MS = 5 * 60_000 +export const CREATE_STUCK_MS = CREATE_ABANDONED_MS /** The desktop rolls over at the deadline; the cron steps in only if it did not (provider cap is +10 min). */ const FORCED_STOP_GRACE_MS = 5 * 60_000 diff --git a/cloud/apps/sandbox-control/src/store.ts b/cloud/apps/sandbox-control/src/store.ts index 4b4584964f5..14ec858457b 100644 --- a/cloud/apps/sandbox-control/src/store.ts +++ b/cloud/apps/sandbox-control/src/store.ts @@ -89,9 +89,26 @@ export const NO_SESSION: SessionFields & Pick = { usage_settled_at: null } -/** Counted against the plan's concurrency limit. */ +/** Holding (or about to hold) a VM: capacity guardrails, retention and drains count these. */ export const ACTIVE_STATUSES: readonly SandboxStatus[] = ['creating', 'running', 'resuming', 'suspending'] +/** A create this old never finished: its Worker was cut off, and the cron releases it (reconcile.ts). */ +export const CREATE_ABANDONED_MS = 5 * 60_000 + +/** + * Counted against the plan's concurrency limits (team and per member). Not a sandbox going to sleep + * ('suspending' drains for up to 5 min after someone chose Sleep, and reads as asleep everywhere), and + * not a create abandoned more than CREATE_ABANDONED_MS ago: neither may refuse the next start. + */ +const START_GATE_STATUSES: readonly SandboxStatus[] = ['creating', 'running', 'resuming'] + +function startGateFilter(now: number): { sql: string; binds: (string | number)[] } { + return { + sql: `status IN (${START_GATE_STATUSES.map(() => '?').join(', ')}) AND NOT (status = 'creating' AND updated_at < ?)`, + binds: [...START_GATE_STATUSES, now - CREATE_ABANDONED_MS] + } +} + export async function insertSandbox( db: D1Database, row: Pick< @@ -155,20 +172,27 @@ export async function listAccountSandboxes(db: D1Database, accountId: string): P return results } -export async function countActiveSandboxes(db: D1Database, accountId: string): Promise { - const placeholders = ACTIVE_STATUSES.map(() => '?').join(', ') +/** Sandboxes that count against the account's concurrency limit at `now` (see START_GATE_STATUSES). */ +export async function countActiveSandboxes(db: D1Database, accountId: string, now: number): Promise { + const gate = startGateFilter(now) const row = await db - .prepare(`SELECT COUNT(*) AS n FROM sandboxes WHERE account_id = ? AND status IN (${placeholders})`) - .bind(accountId, ...ACTIVE_STATUSES) + .prepare(`SELECT COUNT(*) AS n FROM sandboxes WHERE account_id = ? AND ${gate.sql}`) + .bind(accountId, ...gate.binds) .first<{ n: number }>() return row?.n ?? 0 } -export async function countActiveSandboxesForUser(db: D1Database, accountId: string, userId: string): Promise { - const placeholders = ACTIVE_STATUSES.map(() => '?').join(', ') +/** The same, for one member's per-member limit. */ +export async function countActiveSandboxesForUser( + db: D1Database, + accountId: string, + userId: string, + now: number +): Promise { + const gate = startGateFilter(now) const row = await db - .prepare(`SELECT COUNT(*) AS n FROM sandboxes WHERE account_id = ? AND user_id = ? AND status IN (${placeholders})`) - .bind(accountId, userId, ...ACTIVE_STATUSES) + .prepare(`SELECT COUNT(*) AS n FROM sandboxes WHERE account_id = ? AND user_id = ? AND ${gate.sql}`) + .bind(accountId, userId, ...gate.binds) .first<{ n: number }>() return row?.n ?? 0 } diff --git a/cloud/apps/sandbox-control/src/workspace-lifecycle.ts b/cloud/apps/sandbox-control/src/workspace-lifecycle.ts index e16b826a85c..838731a3154 100644 --- a/cloud/apps/sandbox-control/src/workspace-lifecycle.ts +++ b/cloud/apps/sandbox-control/src/workspace-lifecycle.ts @@ -418,10 +418,10 @@ export type WakeHints = { running: { owner: number; account: number } } -export async function wakeHints(db: D1Database, row: SandboxRow): Promise { +export async function wakeHints(db: D1Database, row: SandboxRow, now: number = Date.now()): Promise { const [owner, account] = await Promise.all([ - countActiveSandboxesForUser(db, row.account_id, row.user_id), - countActiveSandboxes(db, row.account_id) + countActiveSandboxesForUser(db, row.account_id, row.user_id, now), + countActiveSandboxes(db, row.account_id, now) ]) return { lastUserSleepAt: row.user_slept_at ?? null, running: { owner, account } } } diff --git a/cloud/apps/sandbox-control/test/create-speed.test.ts b/cloud/apps/sandbox-control/test/create-speed.test.ts index 82f0dc8dd4b..cb19f543a76 100644 --- a/cloud/apps/sandbox-control/test/create-speed.test.ts +++ b/cloud/apps/sandbox-control/test/create-speed.test.ts @@ -117,6 +117,26 @@ describe('repo-backed create', () => { expect(starts).toBe(1) }) + it('the start gate counts neither a sandbox going to sleep nor an abandoned create', async () => { + const h = await createHarness() + const ids: string[] = [] + // Billing's cap is 3 here (the guardrail backstop: 3 per seat, 1 seat). + for (const ws of ['ws-a', 'ws-b', 'ws-c']) { + ids.push(String((await h.call('POST', '/v1/sandboxes', { body: { workspaceId: ws, machineSize: 'standard' } })).body.sandbox.id)) + } + // One is draining toward sleep; one is a create whose Worker was cut off 6 minutes ago. + h.raw.prepare(`UPDATE sandboxes SET status = 'suspending' WHERE id = ?`).run(ids[0]!) + h.raw.prepare(`UPDATE sandboxes SET status = 'creating', updated_at = ? WHERE id = ?`).run(h.now() - 6 * MIN, ids[1]!) + h.billing.requests.length = 0 + expect((await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-d', machineSize: 'standard' } })).status).toBe(200) + expect(h.billing.requests[0]).toMatchObject({ runningSandboxes: 1, runningSandboxesForUser: 1 }) + // A create still in flight (recent) does count. + h.raw.prepare(`UPDATE sandboxes SET updated_at = ? WHERE id = ?`).run(h.now() - MIN, ids[1]!) + h.billing.requests.length = 0 + await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-e', machineSize: 'standard' } }) + expect(h.billing.requests[0]).toMatchObject({ runningSandboxes: 3, runningSandboxesForUser: 3 }) + }) + it('a create whose Worker was cut off is failed after 5 minutes, not 15', async () => { const h = await createHarness() const { body } = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' } }) diff --git a/src/main/daemon/pty-subprocess/spawn-environment.ts b/src/main/daemon/pty-subprocess/spawn-environment.ts index 5da6296bc0c..465058e8cd4 100644 --- a/src/main/daemon/pty-subprocess/spawn-environment.ts +++ b/src/main/daemon/pty-subprocess/spawn-environment.ts @@ -6,6 +6,10 @@ import { dropInheritedOrcaFishHistory } from '../../pty/history/fish-history-ses import { removeAppImageRuntimeEnv } from '../../pty/shell-startup/appimage-terminal-env' import { removeChromiumDisabledSessionBus } from '../../pty/shell-startup/chromium-session-bus-env' import { stripInheritedBuildModeEnv } from '../../pty/shell-startup/build-mode-env' +import { + applyCloudSessionEnv, + cachedCloudSessionEnv +} from '../../runtime/secrets/cloud-session-env' import { stripPiProcessOwnerEnv } from '../../pty/shell-startup/pi-process-owner-env' import { dropIncoherentCondaActivationEnv } from '../../pty/shell-startup/conda-activation-env' import { stripLegacyTerminalShimEnv } from '../../pty/shell-startup/legacy-terminal-shim-dir' @@ -181,7 +185,12 @@ export function createDaemonPtyEnvironment(opts: PtySubprocessOptions): Record = { - ...mergeGitConfigEnvProtocol(inheritedEnv, opts.env), + // Orca Cloud: the daemon's env is from orcad's start; lay the live session env over it, under the + // launch's own values and before its requested deletions (an account strip must win). + ...mergeGitConfigEnvProtocol( + applyCloudSessionEnv(inheritedEnv, cachedCloudSessionEnv(inheritedEnv)), + opts.env + ), TERM: 'xterm-256color', COLORTERM: 'truecolor', TERM_PROGRAM: 'Orca', diff --git a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts index e050391680d..ca8e06459a4 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts @@ -1,4 +1,5 @@ import { agentModelCatalogStore } from '../../../native-chat/agent-model-catalog/agent-model-catalog-store' +import { applyCloudSessionEnv, liveCloudSessionEnv } from '../../secrets/cloud-session-env' import { resolveLoginShellEnvironment } from '../../../startup/login-shell-environment' import { refreshAtRestCommandContext } from '../../../native-chat/agent-session-wire/options/at-rest-command-context' import { @@ -203,12 +204,16 @@ export function createStructuredAgentEnvironmentResolvers( if (!injected && sources.prewarm !== false) { void hostShellEnvironment().catch(() => {}) } - const resolveBase = async (cachedOnly = false): Promise> => - structuredAgentBaseEnvironment({ + // Orca Cloud: the shell capture is from orcad's start; the live session env (secrets, account + // placeholders) is reread for every launch. + const resolveBase = async (cachedOnly = false): Promise> => { + const base = structuredAgentBaseEnvironment({ shellEnv: await shellEnvironment(cachedOnly), policy: sources.resolveShellEnvironmentPolicy?.() ?? nativeChatShellEnvironmentPolicy(null), processEnv: sources.processEnvironment }) + return applyCloudSessionEnv(base, await liveCloudSessionEnv(base)) + } return { refreshAfterMissingProgram: injected ? async () => {} diff --git a/src/main/runtime/agent-session/environment/structured-session-child-env.ts b/src/main/runtime/agent-session/environment/structured-session-child-env.ts index 37bec85bfcf..99b1410abef 100644 --- a/src/main/runtime/agent-session/environment/structured-session-child-env.ts +++ b/src/main/runtime/agent-session/environment/structured-session-child-env.ts @@ -4,6 +4,7 @@ * Empty remote selectors to mask the parent env; explicit flags still work, and login profiles can re-export selectors. * Omit pane identity: hooks and mobile status assume a live PTY leaf. Resolve worker identity at every spawn, including recovery and clear. */ +import { cachedCloudSessionEnv } from '../../secrets/cloud-session-env' import { getAppEnvironment, hasAppEnvironment } from '../../../../shared/app-environment' import { ORCA_AGENT_SESSION_ID_ENV, @@ -40,9 +41,14 @@ export function sealStructuredSessionChild(input: { : input.env const identity = childIdentity(input.sessionId, paired) const named = new Set([...Object.keys(identity.commandEnv), ORCA_AGENT_SESSION_SPAWN_TOKEN_ENV]) + // Orca Cloud: orcad's own env still holds values the live session env has since dropped (a revoked + // account placeholder, a deleted secret); the child must not inherit them. + const dropped = (cachedCloudSessionEnv(process.env)?.unset ?? []).filter( + (key) => !(key in paired) + ) return { env: { ...identity.env, [ORCA_AGENT_SESSION_SPAWN_TOKEN_ENV]: input.spawnToken }, - envToDelete: input.inheritedEnvToDelete.filter((key) => !named.has(key)), + envToDelete: [...input.inheritedEnvToDelete, ...dropped].filter((key) => !named.has(key)), commandEnv: identity.commandEnv } } diff --git a/src/main/runtime/secrets/cloud-session-env.test.ts b/src/main/runtime/secrets/cloud-session-env.test.ts new file mode 100644 index 00000000000..13c58e10bd8 --- /dev/null +++ b/src/main/runtime/secrets/cloud-session-env.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'vitest' +import { applyCloudSessionEnv, cloudSessionEnvFromText } from './cloud-session-env' + +const b64 = (value: string): string => Buffer.from(value).toString('base64') +const lay = (env: Record, lines: string[] | null): Record => + applyCloudSessionEnv(env, cloudSessionEnvFromText(env, lines === null ? null : lines.join('\n'))) + +describe('cloud session env overlay (RA-1)', () => { + it('lays the live file over an env captured before a credential was added', () => { + const env = lay({ PATH: '/usr/bin', ORCA_SESSION_ENV_NAMES: '' }, [ + `CLAUDE_CODE_OAUTH_TOKEN=${b64('orca-ph-claude-account-sbx_1')}`, + `NPM_TOKEN=${b64('n')}` + ]) + expect(env).toEqual({ + PATH: '/usr/bin', + CLAUDE_CODE_OAUTH_TOKEN: 'orca-ph-claude-account-sbx_1', + NPM_TOKEN: 'n', + ORCA_SESSION_ENV_NAMES: 'CLAUDE_CODE_OAUTH_TOKEN NPM_TOKEN' + }) + }) + + it('removes names an older session env set that the live one dropped (a revoked account)', () => { + const started = { + CLAUDE_CODE_OAUTH_TOKEN: 'orca-ph-claude-account-sbx_1', + ORCA_SESSION_ENV_NAMES: 'CLAUDE_CODE_OAUTH_TOKEN' + } + expect(cloudSessionEnvFromText(started, '')?.unset).toEqual(['CLAUDE_CODE_OAUTH_TOKEN']) + expect(lay(started, [])).toEqual({ ORCA_SESSION_ENV_NAMES: '' }) + }) + + it('skips the names the shell hook skips', () => { + const env = lay({ PATH: '/usr/bin' }, [ + `PATH=${b64('/evil')}`, + `ORCA_X=${b64('x')}`, + `LD_PRELOAD=${b64('x')}`, + `bad-name=${b64('x')}` + ]) + expect(env).toEqual({ PATH: '/usr/bin', ORCA_SESSION_ENV_NAMES: '' }) + }) + + it('changes nothing before the file exists', () => { + const env = { A: '1' } + expect(lay(env, null)).toBe(env) + }) +}) diff --git a/src/main/runtime/secrets/cloud-session-env.ts b/src/main/runtime/secrets/cloud-session-env.ts new file mode 100644 index 00000000000..b7bea9eace9 --- /dev/null +++ b/src/main/runtime/secrets/cloud-session-env.ts @@ -0,0 +1,147 @@ +// Orca Cloud: the session env (secrets, agent placeholders such as CLAUDE_CODE_OAUTH_TOKEN) lives in a +// tmpfs file that the control plane rewrites live (orca-sandbox-env). Shells pick it up through the +// profile hook, but orcad's own process env and its cached login-shell capture are frozen at start, so +// anything orcad spawns directly (chat agents, PTYs launched without a shell) must lay the current file +// over the env it built. Same rules as the hook (image/vm/orca-session-env.sh). +// +// The file is kept in memory and reread when its directory changes (a watch, no polling), so spawn paths +// read it without blocking on disk. +import { watch, type FSWatcher } from 'node:fs' +import { readFile } from 'node:fs/promises' +import { dirname } from 'node:path' +import { isCloudWorkspaceOrcad, sessionEnvFilePath } from './session-env-names' + +const NAME = /^[A-Z_][A-Z0-9_]*$/ + +function reserved(name: string): boolean { + return ( + name.startsWith('ORCA_') || + name === 'PATH' || + name === 'HOME' || + name.startsWith('LD_') || + name.startsWith('DYLD_') + ) +} + +export type CloudSessionEnv = { + /** Current values, plus ORCA_SESSION_ENV_NAMES listing them. */ + set: Record + /** Names `base` got from an older session env that the current one no longer has. */ + unset: string[] +} + +/** The overlay for `base` from the file's text; null text (no file) changes nothing, as in the hook. */ +export function cloudSessionEnvFromText( + base: Readonly>, + text: string | null +): CloudSessionEnv | null { + if (text === null) { + return null + } + const set: Record = {} + for (const line of text.split('\n')) { + const at = line.indexOf('=') + const name = at > 0 ? line.slice(0, at) : '' + if (!NAME.test(name) || reserved(name)) { + continue + } + set[name] = Buffer.from(line.slice(at + 1), 'base64').toString('utf8') + } + const names = Object.keys(set) + const unset = (base.ORCA_SESSION_ENV_NAMES ?? '') + .split(/\s+/) + .filter((name) => name && !(name in set)) + return { set: { ...set, ORCA_SESSION_ENV_NAMES: names.join(' ') }, unset } +} + +/** `env` with `overlay` laid over it and dropped names removed. */ +export function applyCloudSessionEnv( + env: Record, + overlay: CloudSessionEnv | null +): Record +export function applyCloudSessionEnv( + env: NodeJS.ProcessEnv, + overlay: CloudSessionEnv | null +): NodeJS.ProcessEnv +export function applyCloudSessionEnv( + env: Record, + overlay: CloudSessionEnv | null +): Record { + if (!overlay) { + return env + } + const next: Record = { ...env } + for (const name of overlay.unset) { + delete next[name] + } + return Object.assign(next, overlay.set) +} + +type Cache = { path: string; text: string | null; loaded: Promise; watcher: FSWatcher | null } +let cache: Cache | null = null + +async function reload(into: Cache): Promise { + try { + into.text = await readFile(into.path, 'utf8') + } catch { + into.text = null + } +} + +/** Starts the in-memory copy once per process; null outside a cloud workspace's orcad. */ +function cloudCache(): Cache | null { + if (cache) { + return cache + } + const uid = process.getuid?.() + if (!isCloudWorkspaceOrcad() || uid === undefined) { + return null + } + const created: Cache = { + path: sessionEnvFilePath(uid), + text: null, + loaded: Promise.resolve(), + watcher: null + } + created.loaded = reload(created) + try { + // orca-sandbox-env replaces the file by rename, so watch the directory. + created.watcher = watch(dirname(created.path), { persistent: false }, () => { + created.loaded = reload(created) + }) + created.watcher.on('error', () => {}) + } catch { + // No directory yet: async reads go to disk each time instead. + created.watcher = null + } + cache = created + return created +} + +/** The live overlay for `base`, read fresh when unwatched (async paths: structured agent launches). */ +export async function liveCloudSessionEnv( + base: Readonly> +): Promise { + const current = cloudCache() + if (!current) { + return null + } + if (!current.watcher) { + current.loaded = reload(current) + } + await current.loaded + return cloudSessionEnvFromText(base, current.text) +} + +/** The last-read overlay for `base`, without waiting (sync spawn paths). */ +export function cachedCloudSessionEnv( + base: Readonly> +): CloudSessionEnv | null { + const current = cloudCache() + return current ? cloudSessionEnvFromText(base, current.text) : null +} + +export function resetCloudSessionEnvCacheForTests(): void { + cache?.watcher?.close() + cache = null +}