@algosuite/vo-mcp 0.2.0-beta.64 → 0.2.0-beta.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/runner/control-plane-auth-stub.mjs", "../src/runner-supervisor.mjs", "../../../scripts/virtual-office/code-runner/installation-token.mjs", "../../../scripts/virtual-office/code-runner/control-plane-heartbeat-body.mjs", "../../../scripts/virtual-office/code-runner/control-plane-promote.mjs", "../../../scripts/virtual-office/code-runner/control-plane-task-list.mjs", "../../../scripts/virtual-office/code-runner/control-plane-resume.mjs", "../../../scripts/virtual-office/code-runner/control-plane-autonomous-admission.mjs", "../../../scripts/virtual-office/code-runner/control-plane-merge.mjs", "../../../scripts/virtual-office/code-runner/control-plane-weekly-tokens.mjs", "../../../scripts/virtual-office/code-runner/control-plane-telemetry-relay.mjs", "../../../scripts/virtual-office/code-runner/claim-gate-notice.mjs", "../../../scripts/virtual-office/code-runner/control-plane-knowledge-context.mjs", "../../../scripts/virtual-office/code-runner/control-plane-prepared-job.mjs", "../../../scripts/virtual-office/code-runner/control-plane-client.mjs", "../../../scripts/virtual-office/code-runner/runner-host-maintenance.mjs", "../src/runner/bundled-runtime-updater.mjs", "../../../scripts/virtual-office/runner-bootstrap/runtime-authorization.mjs", "../../../scripts/virtual-office/runner-bootstrap/runtime-staged-tree.mjs", "../src/runner/bundled-runtime-store.mjs", "../../../scripts/virtual-office/code-runner/legacy-orphan-sweep.mjs", "../../../scripts/virtual-office/code-runner/orphan-agent-reaper.mjs", "../src/runner/supervisor-activation.mjs", "../src/runner/supervisor-child-entry.mjs", "../src/runner/update-drain-gate.mjs", "../src/runner/supervisor-child-env.mjs", "../src/runner-readiness.mjs", "../src/runner/supervisor-credential-reader.mjs", "../src/runner/respawn-circuit.mjs", "../src/runner/supervisor-child-health.mjs"],
4
- "sourcesContent": ["/**\n * Control-plane auth stub for the bundled `vo-mcp runner`.\n *\n * Replaces the daemon's lazy Firebase/SMOKE_* fallback\n * (`scripts/virtual-office/orchestrator-firestore/auth.mjs`), which pulls\n * `vo-config.mjs` (hardcoded Nexus Firebase project) + the firebase-admin chain.\n * A BYO runner ALWAYS authenticates with its own scoped `vo_credential` \u2014 read\n * from the OS keychain by `runner-cli.mjs` and injected as\n * `VO_CONTROL_PLANE_ADMIN_TOKEN` \u2014 so `control-plane-client.mjs`'s `resolveBearer`\n * returns early on the token and NEVER reaches this fallback. It exists only so\n * the bundle has nothing to resolve into the firebase chain; if it ever runs,\n * it fails LOUDLY with the fix.\n *\n * esbuild swaps this in for the heavy original at bundle time (see scripts/bundle.mjs).\n */\nexport async function getFirebaseAuth() {\n throw new Error(\n 'vo-mcp runner: no control-plane credential. Run `vo-mcp login` first \u2014 the runner ' +\n 'authenticates with your stored vo_credential (or set VO_CONTROL_PLANE_ADMIN_TOKEN).',\n );\n}\n", "/**\n * Persistent host supervisor for remote Mission Control maintenance.\n * The task daemon is a replaceable child; this process stays alive while it is\n * updated or repaired. Pairing credentials remain in the existing OS store.\n */\nimport { spawn } from 'node:child_process';\nimport { randomUUID } from 'node:crypto';\nimport { createRequire } from 'node:module';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport { createControlPlaneClient } from '../../../scripts/virtual-office/code-runner/control-plane-client.mjs';\nimport { runHostMaintenance } from '../../../scripts/virtual-office/code-runner/runner-host-maintenance.mjs';\nimport { stageAndActivateBundledUpdate } from './runner/bundled-runtime-updater.mjs';\nimport { runLegacyOrphanSweep } from '../../../scripts/virtual-office/code-runner/legacy-orphan-sweep.mjs';\nimport { activationSupervisorInstanceId, runtimeRootFromEnv } from './runner/bundled-runtime-store.mjs';\nimport { finishPendingActivation } from './runner/supervisor-activation.mjs';\nimport { resolveSupervisorChildEntry } from './runner/supervisor-child-entry.mjs';\nimport { awaitRunnerUpdateDrain } from './runner/update-drain-gate.mjs';\nimport { prepareSupervisorAuth, resolveSupervisorRunnerId } from './runner/supervisor-child-env.mjs';\nimport {\n RUNNER_GITHUB_READINESS_TIMEOUT_MS,\n RUNNER_IDENTITY_READINESS_TIMEOUT_MS,\n RUNNER_READINESS_DEFERRAL_ACK_TYPE,\n parseRunnerReadinessDeferralRequest,\n} from './runner-readiness.mjs';\nimport { readStoredCredentialIsolated } from './runner/supervisor-credential-reader.mjs';\nimport { createRespawnCircuit } from './runner/respawn-circuit.mjs';\nimport {\n attachSupervisorChildTerminationCustody,\n beginSupervisorHealthyStateCommit,\n createSupervisorDegradationState,\n createSupervisorControlRecoveryFence,\n createSupervisorReadinessDeferralTracker,\n createSupervisorStartupDeferral,\n resolveSupervisorChildStartAuthority,\n shouldRespawnSupervisorChild,\n shouldRecoverSupervisorChildAfterAction,\n supervisorChildHasExited,\n supervisorChildIsRunning,\n verifySupervisorChildHealth,\n} from './runner/supervisor-child-health.mjs';\n\nconst DEFAULT_CONTROL_PLANE_URL = 'https://vo-control-plane-bzjphrajaq-uc.a.run.app';\nconst POLL_MS = 5000;\nconst CHILD_START_MS = 1500;\n// The child performs identity auth plus the bounded GitHub preflight before\n// opening its local status port. Cover both transport deadlines plus startup\n// margin without changing the independent child-stop deadlines.\nconst CHILD_READINESS_TIMEOUT_MS = RUNNER_IDENTITY_READINESS_TIMEOUT_MS\n + RUNNER_GITHUB_READINESS_TIMEOUT_MS\n + 10_000;\nconst SUPERVISOR_CAPABILITIES = ['bundled-runtime-slots-v1', 'legacy-orphan-purge-v1'];\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\nconst selfPath = fileURLToPath(import.meta.url);\nconst bundledChildEntry = join(dirname(selfPath), 'runner-cli.js');\nconst supervisorRuntimeRoot = runtimeRootFromEnv(process.env);\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst runnerId = resolveSupervisorRunnerId(process.env);\n\nfunction packageVersion() {\n try { return createRequire(import.meta.url)('../package.json').version || 'unknown'; } catch { return 'unknown'; }\n}\n\nconst requestedSupervisorInstanceId = UUID_RE.test(String(process.env.VO_RUNNER_SUPERVISOR_INSTANCE_ID || ''))\n ? process.env.VO_RUNNER_SUPERVISOR_INSTANCE_ID\n : randomUUID();\nconst supervisorInstanceId = activationSupervisorInstanceId(\n runtimeRootFromEnv(process.env), requestedSupervisorInstanceId,\n);\nconst supervisorVersion = packageVersion();\nconst supervisorControlIdentity = {\n supervisorInstanceId,\n supervisorVersion,\n capabilities: SUPERVISOR_CAPABILITIES,\n};\n\nlet lastResolvedChildDescriptor = null;\n\n/**\n * Resolved on EVERY spawn, never cached at module scope: a slot activated after\n * this process started must take effect on the next child restart, not on the\n * next whole-app restart (nothing forces one).\n */\nfunction spawnChild(childEnv) {\n const resolved = resolveSupervisorChildEntry({\n runtimeRoot: supervisorRuntimeRoot,\n bundledEntry: bundledChildEntry,\n bundledVersion: supervisorVersion,\n });\n if (resolved.descriptor !== lastResolvedChildDescriptor) {\n console.error(`[vo-runner supervisor] child entry -> ${resolved.descriptor} (${resolved.detail})`);\n lastResolvedChildDescriptor = resolved.descriptor;\n }\n return spawn(process.execPath, resolved.args, {\n env: childEnv,\n stdio: ['inherit', 'inherit', 'inherit', 'ipc'],\n windowsHide: true,\n });\n}\n\nfunction spawnPreviousChild(entry, childEnv) {\n const previous = spawn(process.execPath, [entry, 'runner'], {\n env: childEnv,\n stdio: ['inherit', 'inherit', 'inherit', 'ipc'],\n windowsHide: true,\n });\n attachSupervisorChildTerminationCustody(\n previous,\n () => {},\n (error) => {\n console.error(\n `[vo-runner supervisor] rollback child process error: ${error instanceof Error ? error.message : String(error)}`,\n );\n },\n );\n return previous;\n}\n\nasync function localStatus() {\n try {\n const port = Number(process.env.VO_CODE_RUNNER_CONTROL_PORT || 7787);\n const response = await fetch(`http://127.0.0.1:${port}/status`, { signal: AbortSignal.timeout(800) });\n if (!response.ok) return null;\n const body = await response.json();\n return body?.ok === true ? body : null;\n } catch {\n return null;\n }\n}\n\nasync function waitForLocalRunner(child) {\n const deadline = Date.now() + CHILD_READINESS_TIMEOUT_MS;\n while (Date.now() < deadline) {\n if (supervisorChildHasExited(child)) return false;\n const status = await localStatus();\n if (status?.running === true && Number(status.pid) === Number(child.pid)) return true;\n await sleep(500);\n }\n return false;\n}\n\nasync function waitForChildExit(child, timeoutMs) {\n if (!child || supervisorChildHasExited(child)) return true;\n return new Promise((resolve) => {\n let settled = false;\n const finish = (exited) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n child.off('exit', onExit);\n resolve(exited);\n };\n const onExit = () => finish(true);\n const timer = setTimeout(() => finish(false), timeoutMs);\n child.once('exit', onExit);\n if (supervisorChildHasExited(child)) finish(true);\n });\n}\n\nasync function stopChild(child) {\n if (!child || supervisorChildHasExited(child)) return;\n child.kill(process.platform === 'win32' ? undefined : 'SIGTERM');\n if (await waitForChildExit(child, 15_000)) return;\n if (supervisorChildIsRunning(child)) child.kill('SIGKILL');\n // Keep the deliberate-stop fence through the forced-kill exit. Returning\n // immediately after kill() lets a later exit look like a crash and consume\n // breaker budget during legitimate maintenance.\n await waitForChildExit(child, 5_000);\n}\n\nasync function main() {\n // Read keychain-backed credentials in a process that exits before npm ever\n // attempts to replace this package. Windows otherwise keeps the keyring DLL\n // locked for the full supervisor lifetime and global self-updates fail.\n const stored = readStoredCredentialIsolated();\n const controlPlaneUrl = process.env.VO_CONTROL_PLANE_URL || DEFAULT_CONTROL_PLANE_URL;\n const pairedSupervisor = !String(process.env.VO_CONTROL_PLANE_ADMIN_TOKEN || '').trim();\n const supervisorAuthInput = {\n baseEnv: process.env,\n storedCredential: stored,\n controlPlaneUrl,\n };\n const {\n childEnv,\n clientEnv,\n operatorId,\n startupRetryAfterMs,\n } = await prepareSupervisorAuth(supervisorAuthInput);\n Object.assign(childEnv, {\n VO_RUNNER_SUPERVISOR_INSTANCE_ID: supervisorInstanceId,\n VO_RUNNER_SUPERVISOR_VERSION: supervisorVersion,\n VO_RUNNER_SUPERVISOR_CAPABILITIES: SUPERVISOR_CAPABILITIES.join(','),\n });\n const client = createControlPlaneClient({ baseUrl: controlPlaneUrl, env: clientEnv });\n const runtimeRoot = runtimeRootFromEnv(process.env);\n let child = null;\n let stopping = false;\n let handling = false;\n const expectedChildStops = new WeakSet();\n const healthNeutralizedChildren = new WeakSet();\n // Activation failed but the process stays alive to accept remote repair.\n // Distinct from `stopping`: we refuse to SERVE work, we do not refuse to be FIXED.\n const degradationState = createSupervisorDegradationState();\n const markSupervisorDegraded = () => {\n degradationState.markDegraded();\n process.exitCode = 1;\n };\n const respawnCircuit = createRespawnCircuit();\n const controlRecoveryFence = createSupervisorControlRecoveryFence();\n const startupDeferral = createSupervisorStartupDeferral({\n retryAfterMs: startupRetryAfterMs,\n });\n let startupNeedsReadinessRefresh = startupRetryAfterMs !== null;\n let deferredControlRecoveryGeneration = null;\n\n const stopChildExpectedly = async (target) => {\n if (!target) return;\n expectedChildStops.add(target);\n healthNeutralizedChildren.add(target);\n try {\n await stopChild(target);\n } finally {\n // If a pathological process still has not emitted exit after SIGKILL,\n // retain its exact-child tag. WeakSet ownership disappears with the\n // process object and cannot mask a different child's real crash.\n if (supervisorChildHasExited(target)) expectedChildStops.delete(target);\n }\n };\n\n const readinessDeferrals = createSupervisorReadinessDeferralTracker({\n currentChild: () => child,\n releaseCurrentChild: (target) => {\n if (child === target) child = null;\n },\n onCaptured: ({ retryAfterMs, recoveryGeneration }) => {\n startupNeedsReadinessRefresh = true;\n if (Number.isInteger(recoveryGeneration)\n && degradationState.snapshot().generation === recoveryGeneration) {\n deferredControlRecoveryGeneration = recoveryGeneration;\n }\n startupDeferral.reopen(retryAfterMs);\n console.warn(\n `[vo-runner supervisor] child deferred by GitHub readiness for ${retryAfterMs}ms; `\n + 'preserving control polling without consuming rapid-exit breaker budget',\n );\n },\n });\n const isChildReadinessDeferred = (target) => readinessDeferrals.isDeferred(target);\n const captureChildReadinessDeferral = (target) => readinessDeferrals.capture(target);\n\n const respawn = () => {\n if (!startupDeferral.hasStarted()) return;\n if (!shouldRespawnSupervisorChild({\n stopping,\n degraded: degradationState.isDegraded(),\n handling,\n child,\n })) return;\n try {\n child = launchChild();\n void verifyChildHealth(child, false, 'automatic relaunch');\n } catch (error) {\n markSupervisorDegraded();\n console.error(\n `[vo-runner supervisor] child relaunch failed; entering degraded mode: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n };\n const launchChild = () => {\n const next = spawnChild(childEnv);\n const startedAt = Date.now();\n next.on('message', (message) => {\n const request = parseRunnerReadinessDeferralRequest(message);\n if (!request || !readinessDeferrals.recordPending(next, request)) return;\n // The request is exact-child state before the ACK is attempted. Only a\n // matching ACK received by the child authorizes its reserved exit 75.\n try {\n next.send({\n type: RUNNER_READINESS_DEFERRAL_ACK_TYPE,\n nonce: request.nonce,\n }, (error) => {\n if (error) console.warn(`[vo-runner supervisor] readiness deferral ACK failed: ${error.message}`);\n });\n } catch (error) {\n console.warn(\n `[vo-runner supervisor] readiness deferral ACK failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n });\n attachSupervisorChildTerminationCustody(\n next,\n () => {\n // A supervisor-requested stop is not a crash and must not consume the\n // breaker. Every otherwise-unexpected termination can form a loop,\n // including an asynchronous spawn error, external signal, or a faulty\n // child reporting a misleading zero code.\n if (stopping || expectedChildStops.delete(next)) {\n readinessDeferrals.forget(next);\n return;\n }\n if (captureChildReadinessDeferral(next)) return;\n readinessDeferrals.forget(next);\n const decision = respawnCircuit.recordExit(startedAt, Date.now());\n if (decision.tripped) {\n markSupervisorDegraded();\n console.error(\n `[vo-runner supervisor] child exited rapidly ${decision.rapidExits} times; `\n + 'entering degraded mode to stop startup/token churn while remote repair remains available',\n );\n return;\n }\n setTimeout(respawn, decision.delayMs);\n },\n (error) => {\n console.error(\n `[vo-runner supervisor] child process error: ${error instanceof Error ? error.message : String(error)}`,\n );\n },\n );\n return next;\n };\n\n const verifyChildHealth = async (target, degradeOnExit, context) => {\n const commitSupervisorHealthyState = beginSupervisorHealthyStateCommit({\n degradationState,\n target,\n currentChild: () => child,\n allowRecovery: degradeOnExit,\n clearStaleExitCode: () => {\n process.exitCode = undefined;\n },\n });\n const commitSupervisorDegradedState = degradationState.beginDegradationProof({\n target,\n currentChild: () => child,\n onDegraded: (message) => {\n markSupervisorDegraded();\n console.error(`[vo-runner supervisor] ${message}`);\n },\n });\n return verifySupervisorChildHealth({\n target,\n degradeOnExit,\n context,\n waitBeforeProbe: () => sleep(CHILD_START_MS),\n waitForLocalRunner,\n stopExpectedly: stopChildExpectedly,\n isReadinessDeferredExit: isChildReadinessDeferred,\n isExpectedStop: (candidate) => healthNeutralizedChildren.has(candidate),\n markHealthy: commitSupervisorHealthyState,\n markDegraded: commitSupervisorDegradedState,\n });\n };\n\n const deferChildAdmission = (retryAfterMs) => {\n startupNeedsReadinessRefresh = true;\n if (startupDeferral.hasStarted()) startupDeferral.reopen(retryAfterMs);\n else startupDeferral.defer(retryAfterMs);\n console.warn(\n `[vo-runner supervisor] GitHub readiness embargoed child startup for ${retryAfterMs}ms; `\n + 'control polling remains active',\n );\n };\n\n const refreshSupervisorChildAdmission = async () => {\n if (!pairedSupervisor) return true;\n const refreshed = await prepareSupervisorAuth({\n ...supervisorAuthInput,\n baseEnv: childEnv,\n });\n if (refreshed.operatorId !== operatorId) {\n throw new Error('runner readiness operator identity changed during supervisor admission');\n }\n if (refreshed.startupRetryAfterMs !== null) {\n deferChildAdmission(refreshed.startupRetryAfterMs);\n return false;\n }\n if (refreshed.repositoryScope.length > 0) {\n const repositoryScope = refreshed.repositoryScope.join(',');\n childEnv.VO_CODE_RUNNER_REPOS = repositoryScope;\n clientEnv.VO_CODE_RUNNER_REPOS = repositoryScope;\n }\n startupNeedsReadinessRefresh = false;\n return true;\n };\n\n const ensureHealthyChildAfterControl = async () => {\n if (!child || supervisorChildHasExited(child)) {\n const recoveryGeneration = degradationState.snapshot().generation;\n if (!startupDeferral.hasStarted() && startupDeferral.isPending()) {\n deferredControlRecoveryGeneration = recoveryGeneration;\n return false;\n }\n try {\n if (!(await refreshSupervisorChildAdmission())) {\n deferredControlRecoveryGeneration = recoveryGeneration;\n return false;\n }\n if (!startupDeferral.hasStarted() && !startupDeferral.consumeIfReady()) return false;\n child = launchChild();\n readinessDeferrals.recordRecoveryGeneration(child, recoveryGeneration);\n } catch (error) {\n markSupervisorDegraded();\n console.error(\n `[vo-runner supervisor] control recovery relaunch failed; entering degraded mode: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n return false;\n }\n }\n return verifyChildHealth(child, true, 'control recovery relaunch');\n };\n\n const startInitialChild = async (recoveryGeneration = null) => {\n const activationChild = launchChild();\n child = activationChild;\n if (Number.isInteger(recoveryGeneration)) {\n readinessDeferrals.recordRecoveryGeneration(activationChild, recoveryGeneration);\n }\n void verifyChildHealth(\n activationChild,\n Number.isInteger(recoveryGeneration),\n Number.isInteger(recoveryGeneration) ? 'deferred control recovery' : 'initial child',\n );\n\n if (!(await finishPendingActivation({\n client,\n child: activationChild,\n runtimeRoot,\n operatorId,\n runnerId,\n selfPath,\n packageVersion: supervisorVersion,\n supervisorIdentity: supervisorControlIdentity,\n waitForLocalRunner,\n isReadinessDeferred: isChildReadinessDeferred,\n localStatus,\n stopChild: stopChildExpectedly,\n launchPreviousChild: (entry) => spawnPreviousChild(entry, childEnv),\n log: (message) => console.error(`[vo-runner supervisor] ${message}`),\n }))) {\n // A child-reported GitHub embargo is not an activation verdict. Its exact\n // exit handler re-opened admission, so leave the pending slot durable and\n // retry attestation only after that deadline.\n if (captureChildReadinessDeferral(activationChild)) {\n console.warn('[vo-runner supervisor] activation attestation deferred with GitHub readiness; pending slot remains durable');\n return false;\n }\n // DO NOT EXIT HERE. The control-action poll loop below is the ONLY remote\n // repair channel this host has \u2014 the daemon never opens an inbound port by\n // design. Degrade instead: refuse to SERVE work, but stay available to BE FIXED.\n markSupervisorDegraded();\n await stopChildExpectedly(activationChild);\n if (child === activationChild) child = null;\n console.error('[vo-runner supervisor] activation FAILED \u2014 entering degraded mode: not serving tasks, still polling for remote control actions');\n return false;\n }\n return true;\n };\n\n const attemptInitialChildStart = async () => {\n if (startupDeferral.hasStarted() || startupDeferral.isPending()) return false;\n const beforeRefresh = resolveSupervisorChildStartAuthority({\n degradationState,\n deferredRecoveryGeneration: deferredControlRecoveryGeneration,\n });\n if (!beforeRefresh.allowed) return false;\n if (startupNeedsReadinessRefresh) {\n try {\n if (!(await refreshSupervisorChildAdmission())) return false;\n } catch (error) {\n markSupervisorDegraded();\n deferredControlRecoveryGeneration = null;\n startupDeferral.consumeIfReady();\n console.error(\n `[vo-runner supervisor] deferred readiness refresh failed; entering degraded mode: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n return false;\n }\n }\n const afterRefresh = resolveSupervisorChildStartAuthority({\n degradationState,\n deferredRecoveryGeneration: deferredControlRecoveryGeneration,\n });\n if (!afterRefresh.allowed) return false;\n if (!startupDeferral.consumeIfReady()) return false;\n deferredControlRecoveryGeneration = null;\n return startInitialChild(afterRefresh.recoveryGeneration);\n };\n\n await attemptInitialChildStart();\n\n const shutdown = async () => {\n if (stopping) return;\n stopping = true;\n await stopChild(child);\n };\n process.on('SIGINT', () => { void shutdown().finally(() => process.exit(0)); });\n process.on('SIGTERM', () => { void shutdown().finally(() => process.exit(0)); });\n\n while (!stopping) {\n try {\n await attemptInitialChildStart();\n const action = await client.pollRunnerControl({\n runnerId,\n ...(operatorId ? { operatorId } : {}),\n ...supervisorControlIdentity,\n });\n if (!action) {\n await sleep(POLL_MS);\n continue;\n }\n // Any newer control action supersedes delayed recovery authority from an\n // earlier action. A fresh exact-action fence may establish a new one.\n deferredControlRecoveryGeneration = null;\n handling = true;\n const controlIdentity = { runnerId, ...(operatorId ? { operatorId } : {}), ...supervisorControlIdentity };\n // D9 (incident 2026-08-30): an update restart must DRAIN in-flight tasks\n // first, and at the cap must name itself on every task it kills.\n const bundledAction = action.kind === 'update' || action.kind === 'reinstall';\n const drain = await awaitRunnerUpdateDrain({\n readStatus: localStatus, drainable: bundledAction, env: process.env,\n isChildRunning: () => supervisorChildIsRunning(child),\n failInFlightTask: (taskId, patch) => client.postProgress(taskId, { status: 'failed', message: patch.message, result: patch.result, ...(patch.runnerId ? { runner_id: patch.runnerId } : {}), ...(patch.runnerInstanceId ? { runner_instance_id: patch.runnerInstanceId } : {}) }),\n log: (message) => console.warn(`[vo-runner supervisor] ${message}`),\n });\n if (!drain.proceed) {\n await client.completeRunnerControl(action.actionId, { ...controlIdentity, status: 'failed', detail: drain.detail });\n handling = false;\n respawn();\n continue;\n }\n controlRecoveryFence.markBeforeStop(child);\n await stopChildExpectedly(child);\n const result = bundledAction\n ? stageAndActivateBundledUpdate({\n runtimeRoot,\n packageSpec: `@algosuite/vo-mcp@${action.desired_package_version}`,\n expectedVersion: action.desired_package_version,\n expectedIntegrity: action.desired_package_integrity,\n action: {\n actionId: action.actionId,\n runnerId,\n operatorId: operatorId || '',\n supervisorInstanceId,\n },\n env: process.env,\n force: action.kind === 'reinstall',\n })\n : action.kind === 'purge-orphans'\n ? runLegacyOrphanSweep({\n protectedPids: [process.pid],\n log: (message) => console.warn(`[vo-runner supervisor] ${message}`),\n })\n : runHostMaintenance(action.kind, {\n env: clientEnv,\n log: (message) => console.warn(`[vo-runner supervisor] ${message}`),\n });\n if (result.ok && result.handoff) {\n if (drain.capped) console.warn(`[vo-runner supervisor] ${drain.detail}`);\n console.warn(`[vo-runner supervisor] activated ${result.active.version}; exiting for new-process attestation`);\n return;\n }\n // The normal action path consumes any exact-child fence before awaiting,\n // so reporting errors cannot trigger it again. A childless pre-existing\n // degradation requires a successful repair/reconnect action; cleanup or\n // failed maintenance cannot silently re-enable service.\n const recoveryAuthorized = shouldRecoverSupervisorChildAfterAction({\n stoppedChild: controlRecoveryFence.consume(),\n actionKind: action.kind,\n actionSucceeded: result.ok,\n });\n const relaunchedHealthy = recoveryAuthorized\n ? await ensureHealthyChildAfterControl()\n : false;\n if (!relaunchedHealthy) result.ok = false;\n await client.completeRunnerControl(action.actionId, {\n ...controlIdentity,\n status: result.ok ? 'succeeded' : 'failed',\n detail: result.ok\n ? (result.detail ? `${result.detail}; runner ${packageVersion()} reconnected`.slice(0, 1000) : `runner ${packageVersion()} reconnected`)\n : `maintenance exited ${result.status}${result.detail ? `: ${result.detail}` : ''}${\n relaunchedHealthy ? '' : '; runner relaunch did not become healthy'\n }`,\n });\n handling = false;\n respawn();\n } catch (error) {\n console.error(`[vo-runner supervisor] ${error instanceof Error ? error.message : String(error)}`);\n // Recover only when this exact control iteration fenced a live child\n // before stopping it. Poll/defer/reporting failures have no such token\n // and must not clear a pre-existing activation or breaker degradation.\n await controlRecoveryFence.recoverOnce(() => ensureHealthyChildAfterControl());\n handling = false;\n await sleep(POLL_MS);\n }\n }\n}\n\nmain().catch((error) => {\n console.error(`[vo-runner supervisor] fatal: ${error instanceof Error ? error.message : String(error)}`);\n process.exitCode = 1;\n});\n", "/**\n * GitHub App installation-token minting for the runner (M3).\n *\n * Split out of control-plane-client.mjs, which sits at its 400-line cap.\n *\n * The control plane keys the mint on the authenticated operator\n * (ctx.operator_id), so a token covers only that operator's installation.\n *\n * Two distinct grants come out of here:\n * - the DEFAULT full grant, used by the daemon to push and run `gh pr create`.\n * It only works if the App grants BOTH `Contents: write` and\n * `Pull requests: write` \u2014 see docs/vo/github-app-setup-2026-06-18.md.\n * - a READ-ONLY grant (`readOnly: true`), used for the token handed to an\n * agent process so it can read a PRIVATE repo without being able to publish.\n */\n\n/** Ceiling for the OPTIONAL read-token mint, so a hung plane can't stall a task. */\nconst READ_TOKEN_TIMEOUT_MS = 15_000;\n\n/**\n * @param {object} opts\n * @param {(method: string, path: string, body?: unknown) => Promise<Response>} opts.req\n * @param {boolean} [opts.required] fail closed instead of returning null on a miss\n * @param {boolean} [opts.readOnly] ask for a narrowed, non-publishing grant\n * @param {string|null} [opts.repo] narrow the grant to this one `owner/name`\n * @returns {Promise<{ token: string, expiresAt: string | null } | null>}\n */\nexport async function fetchInstallationToken({ req, required = false, readOnly = false, repo = null }) {\n const fail = (reason) => {\n if (required) throw new Error(`installation-token required: ${reason}`);\n return null;\n };\n try {\n // The read-only grant gets a longer explicit ceiling. The client also\n // supplies its default task-request ceiling for the publish mint; required\n // mode propagates that timeout and therefore cannot silently fall back.\n const res = await req(\n 'POST',\n '/api/v1/github/installation-token',\n readOnly ? { scope: 'read', ...(repo ? { repo } : {}) } : {},\n readOnly ? { timeoutMs: READ_TOKEN_TIMEOUT_MS } : {},\n );\n if (!res.ok) return fail(`HTTP ${res.status}`);\n const json = await res.json();\n if (!json || !json.token) return fail('missing token');\n // Fail CLOSED when a read-only grant can't be confirmed. The runner and the\n // control plane deploy independently, so a new runner can reach an older\n // revision that ignores `scope` and hands back a FULL write token. Injecting\n // that into an agent process is the exact failure this token exists to\n // prevent, so drop it: no token is the safe, pre-change state.\n if (readOnly && json.scope !== 'read') return fail('control plane did not confirm a read-only grant');\n // ci_readable (plane 2026-08-16): false while the App installation has not\n // accepted checks:read/statuses:read \u2014 the watcher logs it so the gap is visible.\n return { token: json.token, expiresAt: json.expires_at || null, ...(typeof json.ci_readable === 'boolean' ? { ciReadable: json.ci_readable } : {}) };\n } catch (err) {\n if (required) throw err;\n return null;\n }\n}\n", "/**\n * control-plane-heartbeat-body \u2014 the runner heartbeat's request body, built pure.\n *\n * Split out of `control-plane-client.mjs` on 2026-09-04 (PR #10336 steward pass)\n * when that module crossed its 400-line VO orchestration cap. The construction\n * is the part worth isolating anyway: it is pure, it is the exact surface the\n * plane's strict schema validates, and every field here is OMITTED rather than\n * sent null \u2014 a null on this route is a 400, and the 2026-07-25 outage was hours\n * of diagnosis because a rejected field looked identical to a powered-off host.\n *\n * Adding a field is therefore a three-place change, all in the same PR: this\n * builder, the plane's `runner-heartbeat-v1` schema, and the status type the\n * dashboard reads. The lockstep test pins that.\n */\n\n/**\n * @param {object} input heartbeat inputs as the daemon's loop tick collects them.\n * @returns {object} the wire body, with absent/empty fields omitted.\n */\nexport function buildRunnerHeartbeatBody({\n runnerId,\n runnerInstanceId,\n operatorId,\n uptimeSec,\n activeTasks,\n maxConcurrency,\n effectiveConcurrency,\n measuredTaskSlots,\n measuredCpuSlots,\n measuredMemorySlots,\n version,\n daemonVersion,\n nodeVersion,\n defaultAgent,\n supervisorInstanceId,\n supervisorVersion,\n supervisorCapabilities,\n servedRepos,\n servedOperators,\n availableAgents,\n accountUsage,\n availableLocalModels,\n prepared_job_shadow: preparedJobShadow,\n} = {}) {\n // ADR-004 \u00A7 11.1b-2 counts-only tally rides along when the shadow pass produced one.\n const body = { runner_id: runnerId, ...(preparedJobShadow ? { prepared_job_shadow: preparedJobShadow } : {}) };\n if (runnerInstanceId) body.runner_instance_id = runnerInstanceId;\n if (operatorId) body.operator_id = operatorId;\n if (typeof uptimeSec === 'number') body.uptime_sec = uptimeSec;\n if (typeof activeTasks === 'number') body.active_tasks = activeTasks;\n if (typeof maxConcurrency === 'number') body.max_concurrency = maxConcurrency;\n if (typeof effectiveConcurrency === 'number') body.effective_concurrency = effectiveConcurrency;\n if (typeof measuredTaskSlots === 'number') body.measured_task_slots = measuredTaskSlots;\n if (typeof measuredCpuSlots === 'number') body.measured_cpu_slots = measuredCpuSlots;\n if (typeof measuredMemorySlots === 'number') body.measured_memory_slots = measuredMemorySlots;\n if (version) body.version = version;\n if (daemonVersion) body.daemon_version = daemonVersion;\n // The Node runtime this daemon RUNS on, so a runtime-level abort is\n // attributable to a build. Public version string only, no host detail.\n if (nodeVersion) body.node_version = nodeVersion;\n if (defaultAgent) body.default_agent = defaultAgent;\n if (supervisorInstanceId) body.supervisor_instance_id = supervisorInstanceId;\n if (supervisorVersion) body.supervisor_version = supervisorVersion;\n if (Array.isArray(supervisorCapabilities) && supervisorCapabilities.length > 0) {\n body.supervisor_capabilities = supervisorCapabilities;\n }\n if (Array.isArray(servedRepos) && servedRepos.length > 0) body.served_repos = servedRepos;\n if (Array.isArray(servedOperators) && servedOperators.length > 0) {\n body.served_operator_ids = servedOperators;\n }\n if (Array.isArray(availableAgents) && availableAgents.length > 0) {\n body.available_agents = availableAgents;\n }\n if (Array.isArray(accountUsage) && accountUsage.length > 0) {\n body.account_usage = accountUsage;\n }\n if (Array.isArray(availableLocalModels) && availableLocalModels.length > 0) {\n body.available_local_models = availableLocalModels;\n }\n return body;\n}\n", "/**\n * F35 (2026-08-17): ask the plane to mark a PARTIAL draft READY once its lineage cannot continue\n * and CI is green (`POST /api/v1/admin/pr/promote-draft`, admin-only \u2014 the plane-side sweep is\n * the caller). The plane re-checks every precondition server-side and never merges; the ordinary\n * receipt-gated merge decides afterwards. Errors carry the plane's status + code like resume.\n */\nexport async function promoteDraftPrRequest(req, prNumber, automationContext, onUnauthorized = () => {}) {\n const res = await req('POST', '/api/v1/admin/pr/promote-draft', { prNumber, automationContext }, { timeoutMs: 60_000 });\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('promote-draft unauthorized (401)');\n }\n const json = await res.json().catch(() => ({}));\n if (res.ok && json?.ok === true) {\n return {\n status: json.promoted === true ? (json.auto_merge_disarmed === true ? 'promoted (auto-merge disarmed)' : 'promoted') : json.already_ready === true ? 'already_ready' : 'unchanged',\n headSha: typeof json.head_sha === 'string' ? json.head_sha : null,\n reason: typeof json.blocked_reason === 'string' ? json.blocked_reason : null,\n };\n }\n const code = typeof json?.error === 'string' ? json.error : null;\n const err = new Error(`promote-draft failed: HTTP ${res.status}${code ? ` (${code})` : ''}${json?.reason ? ` \u2014 ${json.reason}` : ''}`);\n err.status = res.status;\n err.code = code;\n throw err;\n}\n", "const PAGE_SIZE = 500;\n\n/** Paginate the runner-only raw adoption view; it deliberately skips PR reconciliation. */\nexport async function listAllPrOpenedTasks(request) {\n const tasks = [];\n let beforeCreatedAt = '';\n let beforeId = '';\n for (;;) {\n const params = new URLSearchParams({\n status: 'pr_opened', limit: String(PAGE_SIZE), runner_adoption: '1',\n });\n if (beforeCreatedAt) {\n params.set('before_created_at', beforeCreatedAt);\n params.set('before_id', beforeId);\n }\n const res = await request('GET', `/api/v1/code-task?${params}`);\n if (!res.ok) throw new Error(`listPrOpenedTasks failed: HTTP ${res.status}`);\n const json = await res.json();\n const page = Array.isArray(json?.tasks) ? json.tasks : [];\n tasks.push(...page);\n if (page.length < PAGE_SIZE) return tasks;\n const last = page.at(-1);\n if (!last?.created_at || !last?.code_task_id) {\n throw new Error('listPrOpenedTasks pagination cursor missing');\n }\n beforeCreatedAt = last.created_at;\n beforeId = last.code_task_id;\n }\n}\n", "export async function resumeCodeTaskRequest(\n req,\n taskId,\n { automaticRateLimit = false, automaticContinuation = false } = {},\n onUnauthorized = () => {},\n) {\n const res = await req(\n 'POST',\n `/api/v1/code-task/${encodeURIComponent(taskId)}/resume`,\n automaticRateLimit\n ? { automatic_rate_limit: true }\n : automaticContinuation ? { automatic_continuation: true } : {},\n );\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('resume unauthorized (401)');\n }\n if (!res.ok) {\n // Carry the plane's refusal code so the watcher can tell a TERMINAL refusal\n // (budget too small / ceiling reached / exhausted \u2014 no retry will ever\n // succeed) from a transient coordination failure it should back off on.\n let code = null;\n try {\n const body = await res.json();\n code = typeof body?.error === 'string' ? body.error : null;\n } catch { /* non-JSON body: keep code null */ }\n const err = new Error(`resume failed: HTTP ${res.status}${code ? ` (${code})` : ''}`);\n err.status = res.status;\n err.code = code;\n throw err;\n }\n const json = await res.json();\n const task = json && json.task ? json.task : null;\n // A 200 with an EXISTING active child (`deduplicated: true`) is not a new continuation; the flag\n // rides along non-enumerably so persisted/logged task shapes stay byte-identical.\n if (task && typeof json.deduplicated === 'boolean') Object.defineProperty(task, 'deduplicated', { value: json.deduplicated, enumerable: false });\n return task;\n}\n", "export function makeAutonomousDispatchAdmissionClient(req, timeoutMs, onUnauthorized = () => {}) {\n return {\n async reserveAutonomousDispatchBudget({ requestedBudgetUsd, reservationId, occurrenceKey }) {\n const res = await req('POST', '/api/v1/autonomous-dispatch/admission', {\n requested_budget_usd: requestedBudgetUsd,\n reservation_id: reservationId,\n dispatch_occurrence_key: occurrenceKey,\n }, { timeoutMs });\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('autonomous dispatch admission unauthorized (401)');\n }\n if (!res.ok) throw new Error(`autonomous dispatch admission failed: HTTP ${res.status}`);\n const body = await res.json();\n return {\n allowed: body?.allowed === true,\n reason: typeof body?.reason === 'string' ? body.reason : '',\n };\n },\n\n async releaseAutonomousDispatchBudget(reservationId) {\n const res = await req('POST', '/api/v1/autonomous-dispatch/reservation/release', {\n reservation_id: reservationId,\n }, { timeoutMs });\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('autonomous dispatch release unauthorized (401)');\n }\n if (!res.ok) throw new Error(`autonomous dispatch release failed: HTTP ${res.status}`);\n return true;\n },\n };\n}\n", "export async function mergeVerifiedPrRequest(req, prNumber, automationContext, onUnauthorized) {\n const res = await req(\n 'POST', '/api/v1/admin/pr/merge', { prNumber, automationContext }, { timeoutMs: 120_000 },\n );\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('gated merge unauthorized (401)');\n }\n const json = await res.json().catch(() => ({}));\n if (res.ok && json?.ok === true) {\n const result = json?.result && typeof json.result === 'object' ? json.result : {};\n const status = result.merged === true || result.status === 'merged'\n ? 'merged'\n : result.status === 'auto-merge-enabled' || String(result.action || '').includes('auto-merge')\n ? 'queued'\n : 'accepted';\n return {\n status,\n detail: typeof result.detail === 'string' ? result.detail : null,\n actionReceiptId: typeof json.action_receipt_id === 'string' ? json.action_receipt_id : null,\n };\n }\n const captureStoreRetry = json?.action_status === 'not_attempted'\n && (json?.error === 'capture_preflight_unavailable'\n || json?.error === 'decision_outcome_intent_failed');\n if (res.status === 503\n && (json?.error === 'verify_unavailable' || json?.error === 'merge_unavailable'\n || captureStoreRetry)) {\n return { status: 'retry', reason: json.reason || json.message || json.error || 'verification unavailable' };\n }\n return {\n status: 'blocked',\n reason: json?.reason || json?.message || json?.error || `HTTP ${res.status}`,\n actionReceiptId: typeof json?.action_receipt_id === 'string' ? json.action_receipt_id : null,\n };\n}\n", "/**\n * control-plane-weekly-tokens \u2014 `POST /api/v1/weekly-tokens` request helper,\n * extracted from control-plane-client.mjs (at its 400-line cap) so the client\n * could grow a sibling telemetry-relay method. Behaviour is unchanged.\n *\n * Report this machine's rolling-7-day Claude Code token usage (the real\n * weekly-capacity gauge) PLUS the operator's real Claude weekly % (when\n * available). The daemon authenticates as admin, so the target `operatorId`\n * is named explicitly. Best-effort; throws on a non-2xx so the caller can\n * log + move on.\n *\n * `tokens` = { input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens }.\n * Optional: `claudeWeeklyPct` (number) + `claudeWeeklyResetsAt` (ISO string | null).\n */\nexport async function postWeeklyTokensRequest(\n taskReq,\n { operatorId, runnerId, tokens, claudeWeeklyPct, claudeWeeklyResetsAt },\n onUnauthorized = () => {},\n) {\n const body = {\n operator_id: operatorId,\n runner_id: runnerId,\n input_tokens: tokens.input_tokens,\n output_tokens: tokens.output_tokens,\n cache_creation_tokens: tokens.cache_creation_tokens,\n cache_read_tokens: tokens.cache_read_tokens,\n };\n if (typeof claudeWeeklyPct === 'number') {\n body.claude_weekly_pct = claudeWeeklyPct;\n }\n if (claudeWeeklyResetsAt !== undefined) {\n body.claude_weekly_resets_at = claudeWeeklyResetsAt;\n }\n const res = await taskReq('POST', '/api/v1/weekly-tokens', body);\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('weekly-tokens unauthorized (401)');\n }\n if (!res.ok) throw new Error(`weekly-tokens failed: HTTP ${res.status}`);\n return true;\n}\n", "/**\n * control-plane-telemetry-relay \u2014 `POST /api/v1/telemetry/relay` request\n * helper for the runner's telemetry forwarder (telemetry-forwarder.mjs).\n *\n * The daemon never holds the vo-telemetry ingest token: it hands a batch of\n * local vo-mcp events to the control plane, which relays each one to\n * vo-telemetry and returns per-event results (a PREFIX of the batch \u2014 the\n * relay halts on the first upstream fault so the forwarder's byte cursor can\n * never advance past an event the store did not accept).\n *\n * Returns `{ status, body }` and never throws on HTTP status \u2014 the forwarder\n * owns the backoff/disable policy. Network errors DO throw (fetch rejects).\n * A 30 s timeout covers up to MAX_EVENTS_PER_RELAY sequential upstream POSTs.\n */\nexport const TELEMETRY_RELAY_TIMEOUT_MS = 30_000;\n\nexport async function relayTelemetryEventsRequest(req, { events, source }, onUnauthorized = () => {}) {\n const res = await req('POST', '/api/v1/telemetry/relay', { events, ...(source ? { source } : {}) }, {\n timeoutMs: TELEMETRY_RELAY_TIMEOUT_MS,\n });\n if (res.status === 401) onUnauthorized();\n let body = null;\n try { body = await res.json(); } catch { body = null; }\n return { status: res.status, body };\n}\n", "// Runner-side display of the control plane's claim-admission gate (2026-08-15).\n//\n// The claim route answers a DENIED runner with the benign queue-empty shape\n// (`task: null`) plus a `claim_gate` reason \u2014 by design, so pre-gate daemons keep\n// polling instead of crashing. Before this module the daemon dropped that field\n// on the floor and a below-target runner simply looked idle forever (\"no\n// pending task\" every 5s) with nothing on the host saying WHY. Now the reason is\n// logged once per distinct verdict (not every poll) and kept for /status.\n//\n// Pure apart from the injected `log`; the daemon's claim loop stays untouched.\n\nconst REASON_HELP = {\n daemon_version_below_floor: 'this daemon is older than the approved release target \u2014 it idles until the governed updater brings it current (operator override: VO_RUNNER_CLAIM_MIN_DAEMON_VERSION / VO_RUNNER_CLAIM_VERSION_GATE=off on the control plane)',\n daemon_version_unreported: 'this daemon reports no parseable version in its heartbeat \u2014 too old for the updater to manage, so it may not claim work',\n no_fresh_heartbeat: 'the control plane has no fresh heartbeat from this runner \u2014 claims resume once heartbeats land',\n runner_denylisted: 'this runner id is on the operator quarantine list (VO_RUNNER_CLAIM_DENYLIST)',\n};\n\nexport function describeClaimGate(gate) {\n if (!gate || gate.allowed !== false) return null;\n const reason = String(gate.reason || 'denied');\n const floor = gate.floor_version ? ` (floor ${gate.floor_version})` : '';\n return `claim gate: DENIED \u2014 ${reason}${floor}: ${(Object.hasOwn(REASON_HELP, reason) ? REASON_HELP[reason] : null) ?? 'the control plane refused this runner\\'s claims'}`;\n}\n\n/**\n * Track the latest verdict and log only on change (denied\u2192allowed logs the recovery too).\n * @returns {{ current: () => (object|null), observe: (json: unknown) => void }}\n */\nexport function makeClaimGateNotice({ log = () => {} } = {}) {\n let last = null; // last DENIED verdict signature, or null when allowed\n let current = null;\n return {\n current: () => current,\n observe(json) {\n const gate = json && typeof json === 'object' ? json.claim_gate : null;\n const denied = gate && gate.allowed === false ? gate : null;\n current = denied ? { ...denied, observed_at: new Date().toISOString() } : null;\n const signature = denied ? `${denied.reason}|${denied.floor_version ?? ''}` : null;\n if (signature === last) return;\n if (denied) log(describeClaimGate(denied));\n else if (last !== null) log('claim gate: allowed again \u2014 this runner may claim work');\n last = signature;\n },\n };\n}\n", "/**\n * getTaskKnowledgeContext resilience.\n *\n * Incident 2026-08-29: tasks 8ca414ed (05:11:57Z) and eb5fd089 (05:28Z) both\n * failed at preparing_worktree because the knowledge-context fetch timed out\n * at the shared 5000ms task-request cap while the server itself measured\n * 3.4s/4.9s/6.99s over the same window (an embeddings leg was added\n * 2026-08-27). A single 5s-capped attempt was a coin flip. The fail-closed\n * refusal in task-prompt.mjs is deliberate and stays \u2014 this module only\n * widens the single attempt into a per-endpoint timeout floor plus a bounded\n * retry, so a slow-but-healthy server response is no longer indistinguishable\n * from a hung one. Every other control-plane endpoint is untouched and keeps\n * its original single-attempt policy.\n */\n\nexport const MIN_KNOWLEDGE_CONTEXT_TIMEOUT_MS = 15_000;\nconst RETRY_DELAYS_MS = [2_000, 6_000];\nconst MAX_ATTEMPTS = RETRY_DELAYS_MS.length + 1;\n\nfunction isRetryableStatus(status) {\n return status >= 500 && status <= 599;\n}\n\nfunction defaultSleep(ms) {\n return new Promise((resolve) => { setTimeout(resolve, ms); });\n}\n\n/**\n * `req` is the control-plane client's low-level request function:\n * `(method, path, body, { timeoutMs }) => Promise<Response-like>`. It throws\n * on timeout or transport failure and resolves (never rejects) for any HTTP\n * status, including 4xx/5xx \u2014 matching `control-plane-client.mjs`'s `req()`.\n */\nexport async function getTaskKnowledgeContextRequest(req, taskId, { query } = {}, {\n taskRequestTimeoutMs,\n invalidateToken = () => {},\n sleep = defaultSleep,\n log = () => {},\n} = {}) {\n const body = {};\n if (typeof query === 'string' && query.trim()) body.query = query;\n const path = `/api/v1/code-task/${encodeURIComponent(taskId)}/knowledge-context`;\n const timeoutMs = Math.max(Number(taskRequestTimeoutMs) || 0, MIN_KNOWLEDGE_CONTEXT_TIMEOUT_MS);\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {\n let res;\n let cause;\n try {\n res = await req('POST', path, body, { timeoutMs });\n } catch (err) {\n cause = err;\n }\n if (!cause) {\n if (res.status === 401) {\n invalidateToken();\n throw new Error('knowledge-context unauthorized (401)');\n }\n if (res.status === 404) return null;\n if (res.ok) return res.json();\n if (!isRetryableStatus(res.status)) {\n throw new Error(`knowledge-context failed: HTTP ${res.status}`);\n }\n cause = new Error(`knowledge-context failed: HTTP ${res.status}`);\n }\n if (attempt === MAX_ATTEMPTS) throw cause;\n const delayMs = RETRY_DELAYS_MS[attempt - 1];\n log(`knowledge-context attempt ${attempt}/${MAX_ATTEMPTS} failed (${cause.message}); retrying in ${delayMs}ms`);\n await sleep(delayMs);\n }\n /* c8 ignore next */\n throw new Error('knowledge-context retry loop exited unexpectedly');\n}\n", "/**\n * control-plane-prepared-job \u2014 ADR-004 \u00A7 11.1 slice B, the fetch half.\n *\n * Reads the plane's PREPARED JOB for one code task from\n * `GET /api/v1/code-task/:id/prepared-job` (shipped DARK in slice A, PR #10218)\n * so the runner can compare it against its OWN local composition.\n *\n * SHADOW-ONLY: nothing here may change what the runner spawns. This module\n * therefore NEVER throws. Every fault \u2014 transport, timeout, 401, the 409\n * `router_mode_unsupported` refusal, a 5xx, a non-JSON body \u2014 comes back as a\n * structured refusal the caller records as a shadow observation. A dispatch is\n * never failed by a shadow read.\n */\n\n/**\n * Runner-local env knobs the plane must be TOLD about; it does not share the\n * runner's process.\n *\n * This list MUST stay byte-identical to `ENV_QUERY_KEYS` in\n * `cloud-run/vo-control-plane/src/routes/code-task-prepared-job.ts`. A key\n * present on one side only makes the plane compose a DIFFERENT job for a\n * reason that has nothing to do with drift \u2014 which is exactly the signal this\n * slice exists to measure, so the two lists are pinned equal by\n * prepared-job-shadow.test.mjs rather than left to review.\n */\nexport const PREPARED_JOB_ENV_QUERY_KEYS = [\n 'VO_CODE_RUNNER_NO_WEB',\n 'VO_CODE_RUNNER_NO_WORKFLOW',\n 'VO_CODE_RUNNER_NO_CONSENSUS',\n 'VO_CODE_RUNNER_PERMISSION_MODE',\n 'VO_CODE_RUNNER_DEFAULT_BUDGET_USD',\n 'VO_CODE_RUNNER_META_REASONING_EFFORT',\n 'VO_CODE_RUNNER_ALLOW_MISSING_KNOWLEDGE_CONTEXT',\n 'VO_ENABLE_CONTEXT7',\n];\n\n/** The plane accepts a query env value only when 0 < length <= 64 (same route). */\nexport const PREPARED_JOB_ENV_VALUE_MAX = 64;\n\n/**\n * Build the query string for one prepared-job read.\n *\n * Returns `{ query, sent, dropped }`. `dropped` names any allow-listed key the\n * runner HAS set but the plane will refuse for length \u2014 a real divergence\n * cause that must be visible in the record rather than inferred from a\n * mismatching prompt.\n */\nexport function preparedJobQuery({ agent = 'claude', env = {} } = {}) {\n const params = new URLSearchParams();\n params.set('agent', String(agent));\n const sent = [];\n const dropped = [];\n for (const key of PREPARED_JOB_ENV_QUERY_KEYS) {\n const raw = env?.[key];\n if (typeof raw !== 'string' || raw.length === 0) continue;\n if (raw.length > PREPARED_JOB_ENV_VALUE_MAX) { dropped.push(key); continue; }\n params.set(key, raw);\n sent.push(key);\n }\n return { query: params.toString(), sent, dropped };\n}\n\n/** Read the plane's error code out of a non-2xx body without ever throwing. */\nasync function refusalCode(res) {\n try {\n const body = await res.json();\n return typeof body?.error === 'string' && body.error ? body.error : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Fetch the prepared job. Resolves to\n * { ok: true, job, composition, envSent, envDropped }\n * { ok: false, reason, status, envSent, envDropped }\n * and never rejects.\n *\n * @param {Function} req the control-plane client's raw request fn\n * @param {string} taskId\n * @param {object} [options] { agent, env, timeoutMs }\n * @param {Function} [invalidateToken] called on 401 so the next real call re-auths\n */\nexport async function getPreparedJobRequest(req, taskId, options = {}, invalidateToken = () => {}) {\n const { agent = 'claude', env = {}, timeoutMs = 15_000 } = options;\n const { query, sent, dropped } = preparedJobQuery({ agent, env });\n const envMeta = { envSent: sent, envDropped: dropped };\n if (typeof taskId !== 'string' || taskId.length === 0) {\n return { ok: false, reason: 'missing_task_id', status: 0, ...envMeta };\n }\n const path = `/api/v1/code-task/${encodeURIComponent(taskId)}/prepared-job?${query}`;\n let res;\n try {\n res = await req('GET', path, undefined, { timeoutMs });\n } catch (err) {\n return { ok: false, reason: `transport: ${err?.message || String(err)}`, status: 0, ...envMeta };\n }\n if (res?.status === 401) {\n try { invalidateToken(); } catch { /* shadow-only */ }\n return { ok: false, reason: 'unauthorized', status: 401, ...envMeta };\n }\n if (!res?.ok) {\n const code = await refusalCode(res);\n return { ok: false, reason: code || `http_${res?.status ?? 'unknown'}`, status: res?.status ?? 0, ...envMeta };\n }\n let body;\n try {\n body = await res.json();\n } catch (err) {\n return { ok: false, reason: `unreadable_body: ${err?.message || String(err)}`, status: res.status, ...envMeta };\n }\n const job = body?.prepared_job;\n if (!job || typeof job !== 'object') {\n return { ok: false, reason: 'no_prepared_job_in_body', status: res.status, ...envMeta };\n }\n return {\n ok: true,\n job,\n composition: body?.composition && typeof body.composition === 'object' ? body.composition : {},\n ...envMeta,\n };\n}\n", "/**\n * control-plane-client \u2014 the runner's OUTBOUND link to vo-control-plane.\n *\n * Increment 6 (Code-from-Anywhere). The daemon never exposes a port; it reaches\n * OUT to the control-plane (no inbound hole, no Tailscale \u2014 design \u00A72). Auth:\n * prefer the static admin token (`VO_CONTROL_PLANE_ADMIN_TOKEN`, the V1 local\n * dogfood path); fall back to a per-user Firebase ID token via the shared\n * orchestrator auth (`SMOKE_*` creds \u2192 allow-listed operator \u2192 admin).\n *\n * Covers task claim/progress/context/private attachments/resume and governed merge.\n */\n\nimport { fetchInstallationToken } from './installation-token.mjs';\nimport { buildRunnerHeartbeatBody } from './control-plane-heartbeat-body.mjs';\nimport { promoteDraftPrRequest } from './control-plane-promote.mjs';\nimport { listAllPrOpenedTasks } from './control-plane-task-list.mjs';\nimport { resumeCodeTaskRequest } from './control-plane-resume.mjs';\nimport { makeAutonomousDispatchAdmissionClient } from './control-plane-autonomous-admission.mjs';\nimport { mergeVerifiedPrRequest } from './control-plane-merge.mjs';\nimport { postWeeklyTokensRequest } from './control-plane-weekly-tokens.mjs';\nimport { relayTelemetryEventsRequest } from './control-plane-telemetry-relay.mjs';\nimport { makeClaimGateNotice } from './claim-gate-notice.mjs';\nimport { getTaskKnowledgeContextRequest } from './control-plane-knowledge-context.mjs'; import { getPreparedJobRequest } from './control-plane-prepared-job.mjs';\n\nlet cachedFirebaseToken = null;\nexport class ClaimAuthorityChangedError extends Error {\n constructor() {\n super('code-task claim authority changed');\n this.name = 'ClaimAuthorityChangedError'; this.code = 'code_task_claim_authority_changed';\n }\n}\n\nasync function resolveBearer(env) {\n const adminToken = env.VO_CONTROL_PLANE_ADMIN_TOKEN;\n if (adminToken) return adminToken;\n if (cachedFirebaseToken) return cachedFirebaseToken;\n // Lazy import \u2014 Firebase auth is only needed when no admin token is present.\n const { getFirebaseAuth } = await import('../orchestrator-firestore/auth.mjs');\n const auth = await getFirebaseAuth({ env });\n if (!auth || !auth.idToken) {\n throw new Error(\n 'no control-plane credential: set VO_CONTROL_PLANE_ADMIN_TOKEN, or SMOKE_EMAIL/SMOKE_PASSWORD/SMOKE_API_KEY',\n );\n }\n cachedFirebaseToken = auth.idToken;\n return cachedFirebaseToken;\n}\n\n/**\n * Build a client. `baseUrl` defaults to `env.VO_CONTROL_PLANE_URL`. `fetchImpl`,\n * `env`, and `sleep` (the retry backoff delay function) are injectable for\n * tests and packaged runner handoff.\n */\nexport function createControlPlaneClient({\n baseUrl,\n env = process.env,\n fetchImpl = fetch,\n heartbeatTimeoutMs = Math.min(\n Math.max(Number(env.VO_CODE_RUNNER_HEARTBEAT_TIMEOUT_MS) || 15_000, 1_000),\n 60_000,\n ),\n taskRequestTimeoutMs = Math.min(\n Math.max(Number(env.VO_CODE_RUNNER_TASK_REQUEST_TIMEOUT_MS) || 5_000, 100),\n 60_000,\n ),\n runnerId,\n runnerInstanceId,\n sleep,\n} = {}) {\n const resolvedBaseUrl = baseUrl ?? env.VO_CONTROL_PLANE_URL ?? '';\n if (!resolvedBaseUrl) throw new Error('VO_CONTROL_PLANE_URL is required for the code-runner daemon');\n const root = resolvedBaseUrl.replace(/\\/+$/, '');\n\n async function req(method, path, body, { timeoutMs } = {}) {\n const bearer = await resolveBearer(env);\n const controller = timeoutMs ? new AbortController() : null;\n let timeoutId;\n const request = Promise.resolve(fetchImpl(`${root}${path}`, {\n method,\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${bearer}`,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n ...(controller ? { signal: controller.signal } : {}),\n }));\n if (!timeoutMs) return request;\n const timeout = new Promise((_, reject) => {\n timeoutId = setTimeout(() => {\n controller.abort();\n reject(new Error(`control-plane ${path} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n try {\n return await Promise.race([request, timeout]);\n } finally {\n clearTimeout(timeoutId);\n }\n }\n const taskReq = (method, path, body, options = {}) => req(method, path, body, { timeoutMs: taskRequestTimeoutMs, ...options }); const claimGate = makeClaimGateNotice({ log: (m) => console.warn(`[code-runner ${new Date().toISOString()}] ${m}`) }); // deny-site visibility\n return { getClaimGate: () => claimGate.current(), // last DENIED claim-gate verdict (null when allowed) \u2014 for /status + tests\n ...makeAutonomousDispatchAdmissionClient(\n req, taskRequestTimeoutMs, () => { cachedFirebaseToken = null; },\n ),\n /**\n * Claim the next pending task. Returns the task or null (empty queue).\n * `repos` (optional `owner/name` list) and `operatorIds` (optional\n * `operator_id` list) scope the claim so this daemon only picks up tasks it\n * serves \u2014 the control-plane filters by both (logical AND), so another\n * operator's task never lands on (or bills) this machine.\n */\n async claim(runnerId, repos, operatorIds, session = {}) {\n const body = { runner_id: runnerId };\n if (Array.isArray(repos) && repos.length > 0) body.repos = repos;\n if (Array.isArray(operatorIds) && operatorIds.length > 0) body.operator_ids = operatorIds;\n if (session.runnerInstanceId) { body.runner_instance_id = session.runnerInstanceId; body.runner_progress_protocol_version = 2; }\n if (session.runnerInstanceId && session.reconcileStale) body.reconcile_stale = true;\n if (session.defaultAgent) body.default_agent = session.defaultAgent;\n if (Array.isArray(session.availableAgents)) {\n body.available_agents = session.availableAgents\n .filter((entry) => entry?.installed === true && entry?.authenticated === true)\n .map((entry) => entry.agent);\n }\n const res = await taskReq('POST', '/api/v1/code-task/claim', body);\n if (res.status === 401) {\n cachedFirebaseToken = null; // force re-auth next call\n throw new Error('claim unauthorized (401)');\n }\n if (!res.ok) throw new Error(`claim failed: HTTP ${res.status}`);\n const json = await res.json(); claimGate.observe(json); // 2026-08-15: a DENIED verdict is logged once + kept for /status instead of reading as an idle queue\n return json && json.task ? json.task : null;\n },\n\n /**\n * Enqueue a new code-task (used by the PR watcher to auto-dispatch a CI fix).\n * Server derives operator/tenant from the daemon's authenticated principal.\n * Returns the created task, or throws on a non-2xx response.\n */\n async enqueueCodeTask({ repo, prompt, max_budget_usd, max_turns, dispatch_mode, tier, agent, model, dispatch_occurrence_key, autonomous_reservation_id, on_behalf_of_operator_id, repair_pr_number, repair_kind, repair_head_sha, repair_chain }) {\n const body = { repo, prompt };\n if (typeof max_budget_usd === 'number') body.max_budget_usd = max_budget_usd;\n if (typeof max_turns === 'number') body.max_turns = max_turns;\n for (const [key, value] of Object.entries({ dispatch_mode, tier, agent, model, repair_kind, repair_head_sha })) {\n if (value) body[key] = value;\n }\n if (dispatch_occurrence_key) body.dispatch_occurrence_key = dispatch_occurrence_key;\n if (autonomous_reservation_id) body.autonomous_reservation_id = autonomous_reservation_id; if (on_behalf_of_operator_id) body.on_behalf_of_operator_id = on_behalf_of_operator_id;\n if (Number.isInteger(repair_pr_number) && repair_pr_number > 0) body.repair_pr_number = repair_pr_number;\n if (repair_chain) body.repair_chain = repair_chain;\n const res = await taskReq('POST', '/api/v1/code-task', body);\n if (res.status === 401) {\n cachedFirebaseToken = null;\n throw new Error('enqueue unauthorized (401)');\n }\n if (!res.ok) {\n // Carry the plane's refusal code (repair_not_needed / dispatch_occurrence_exists /\n // repair_state_unavailable / autonomous_reservation_invalid \u2026) so callers can tell a\n // policy answer from a real fault \u2014 same contract as control-plane-resume.mjs.\n let code = null;\n try { const errBody = await res.json(); code = typeof errBody?.error === 'string' ? errBody.error : null; } catch { /* non-JSON body */ }\n const err = new Error(`enqueue failed: HTTP ${res.status}${code ? ` (${code})` : ''}`);\n err.status = res.status; err.code = code;\n throw err;\n }\n const json = await res.json();\n const task = json && json.task ? json.task : null;\n // `deduplicated` (plane returned an EXISTING task for this occurrence/repair) rides along\n // non-enumerably so logs/persistence of the task stay byte-identical.\n if (task && typeof json.deduplicated === 'boolean') Object.defineProperty(task, 'deduplicated', { value: json.deduplicated, enumerable: false });\n return task;\n },\n\n /**\n * Resume a failed/cancelled/max-turn partial code-task. The PR watcher uses\n * this after the runner opens a partial draft PR and CI is no longer pending.\n */\n async resumeCodeTask(taskId, { automaticRateLimit = false, automaticContinuation = false } = {}) {\n return resumeCodeTaskRequest(taskReq, taskId, { automaticRateLimit, automaticContinuation }, () => {\n cachedFirebaseToken = null;\n });\n },\n\n /**\n * Send a CI-green PR through the production verify-before-act merge route.\n * The server inspects the current diff, applies deterministic blockers, runs\n * consensus, records a receipt, and direct-merges only the inspected SHA.\n */\n /** F35: promote a PARTIAL draft to READY via the plane (admin-only; server re-checks; never merges). */\n promoteDraftPr: (prNumber, automationContext) => promoteDraftPrRequest(req, prNumber, automationContext, () => { cachedFirebaseToken = null; }),\n async mergeVerifiedPr(prNumber, automationContext) {\n return mergeVerifiedPrRequest(\n req, prNumber, automationContext, () => { cachedFirebaseToken = null; },\n );\n },\n\n /**\n * Append progress / set terminal status. Returns\n * { task } \u2014 applied\n * { terminal: true } \u2014 task already terminal (operator cancelled): STOP\n */\n async postProgress(taskId, patch) {\n const progress = {\n ...patch,\n ...(patch.runner_id ? {} : runnerId ? { runner_id: runnerId } : {}),\n ...(patch.runner_instance_id ? {} : runnerInstanceId ? { runner_instance_id: runnerInstanceId } : {}),\n };\n const res = await taskReq('PATCH', `/api/v1/code-task/${taskId}/progress`, progress);\n if (res.status === 409) {\n const conflict = await res.json().catch(() => ({}));\n if (conflict?.error === 'code_task_claim_authority_changed') {\n throw new ClaimAuthorityChangedError();\n }\n return { terminal: true };\n }\n if (res.status === 404) return { terminal: true, missing: true };\n if (!res.ok) throw new Error(`progress failed: HTTP ${res.status}`);\n const json = await res.json();\n return { task: json && json.task };\n },\n\n async getTask(taskId) {\n const res = await taskReq('GET', `/api/v1/code-task/${taskId}`);\n if (res.status === 404) return null;\n if (!res.ok) throw new Error(`getTask failed: HTTP ${res.status}`);\n const json = await res.json();\n return json ? json.task : null;\n },\n async listPrOpenedTasks() {\n return listAllPrOpenedTasks(taskReq);\n },\n async downloadTaskAttachment(taskId, attachmentId) {\n const path = `/api/v1/code-task/${encodeURIComponent(taskId)}/attachment/${encodeURIComponent(attachmentId)}`;\n const res = await taskReq('GET', path);\n if (res.status === 401) cachedFirebaseToken = null;\n if (!res.ok) throw new Error(`attachment download failed: HTTP ${res.status}`);\n return Buffer.from(await res.arrayBuffer());\n },\n\n // Raised per-attempt timeout (>=15s) + bounded retry \u2014 see control-plane-knowledge-context.mjs.\n async getTaskKnowledgeContext(taskId, { query } = {}) {\n return getTaskKnowledgeContextRequest(req, taskId, { query }, {\n taskRequestTimeoutMs,\n invalidateToken: () => { cachedFirebaseToken = null; },\n sleep,\n log: (m) => console.warn(`[code-runner ${new Date().toISOString()}] ${m}`),\n });\n },\n\n /** ADR-004 \u00A7 11.1b: the plane's prepared job, for SHADOW comparison. Never throws. */\n getPreparedJob: (taskId, options) => getPreparedJobRequest(req, taskId, options, () => { cachedFirebaseToken = null; }),\n /** Weekly Claude token usage report \u2014 see control-plane-weekly-tokens.mjs. */\n async postWeeklyTokens(report) {\n return postWeeklyTokensRequest(taskReq, report, () => { cachedFirebaseToken = null; });\n },\n\n /**\n * Relay a batch of this machine's local vo-mcp events to vo-telemetry via\n * the control plane (telemetry-forwarder.mjs). Returns { status, body };\n * the forwarder owns backoff/disable policy. See control-plane-telemetry-relay.mjs.\n */\n async relayTelemetryEvents(batch) {\n return relayTelemetryEventsRequest(req, batch, () => { cachedFirebaseToken = null; });\n },\n\n /**\n * Send a liveness heartbeat (M2). The control-plane upserts it under the\n * authenticated operator so the web shows a TRUE \"runner online\" signal.\n * Best-effort caller; throws on 401/non-ok so the daemon can log + retry.\n */\n async postHeartbeat(heartbeat) {\n const body = buildRunnerHeartbeatBody(heartbeat);\n const res = await req('POST', '/api/v1/runner/heartbeat', body, {\n timeoutMs: heartbeatTimeoutMs,\n });\n if (res.status === 401) {\n cachedFirebaseToken = null;\n throw new Error('heartbeat unauthorized (401)');\n }\n if (!res.ok) {\n // Surface WHICH field the server rejected. `HTTP 400` alone is what made\n // the 2026-07-25 outage take hours to diagnose: the runner looked\n // identical to a powered-off machine from the control plane, and the\n // operator's only clue was a bare status code.\n //\n // The server returns issue PATHS and CODES only (never values), so this\n // is safe to log.\n let detail = '';\n try {\n const body = await res.json();\n if (Array.isArray(body?.issue_paths) && body.issue_paths.length > 0) {\n detail = ` (rejected fields: ${body.issue_paths.join(', ')})`;\n }\n } catch { /* non-JSON body \u2014 the status code is all we have */ }\n throw new Error(`heartbeat failed: HTTP ${res.status}${detail}`);\n }\n return res.json();\n },\n\n async getRunnerStatus({ operatorId } = {}) {\n const query = operatorId ? `?operator_id=${encodeURIComponent(operatorId)}` : '';\n const res = await req('GET', `/api/v1/runner/status${query}`, undefined, {\n timeoutMs: heartbeatTimeoutMs,\n });\n if (res.status === 401) {\n cachedFirebaseToken = null;\n throw new Error('runner status unauthorized (401)');\n }\n if (!res.ok) throw new Error(`runner status failed: HTTP ${res.status}`);\n const body = await res.json();\n return Array.isArray(body?.runners) ? body.runners : [];\n },\n\n async pollRunnerControl({ runnerId, operatorId, supervisorInstanceId, supervisorVersion, capabilities }) {\n const body = { runner_id: runnerId };\n if (operatorId) body.operator_id = operatorId;\n if (supervisorInstanceId) body.supervisor_instance_id = supervisorInstanceId;\n if (supervisorVersion) body.supervisor_version = supervisorVersion;\n if (Array.isArray(capabilities) && capabilities.length > 0) body.capabilities = capabilities;\n const res = await taskReq('POST', '/api/v1/runner/control/poll', body);\n if (res.status === 401) {\n cachedFirebaseToken = null;\n throw new Error('runner control poll unauthorized (401)');\n }\n if (!res.ok) throw new Error(`runner control poll failed: HTTP ${res.status}`);\n const json = await res.json();\n const action = json?.action;\n return action && typeof action.action_id === 'string' && action.action_id\n ? { ...action, actionId: action.action_id }\n : null;\n },\n\n async completeRunnerControl(actionId, { runnerId, operatorId, supervisorInstanceId, supervisorVersion, capabilities, status, detail }) {\n const body = { runner_id: runnerId, status };\n if (operatorId) body.operator_id = operatorId;\n if (supervisorInstanceId) body.supervisor_instance_id = supervisorInstanceId;\n if (supervisorVersion) body.supervisor_version = supervisorVersion;\n if (Array.isArray(capabilities) && capabilities.length > 0) body.capabilities = capabilities;\n if (detail) body.detail = detail;\n const res = await taskReq('POST', `/api/v1/runner/control/${encodeURIComponent(actionId)}/complete`, body);\n if (res.status === 401) {\n cachedFirebaseToken = null;\n throw new Error('runner control completion unauthorized (401)');\n }\n if (!res.ok) throw new Error(`runner control completion failed: HTTP ${res.status}`);\n const json = await res.json();\n return json?.action || null;\n },\n\n /** Mint a GitHub App installation token \u2014 see installation-token.mjs. */\n async getInstallationToken({ required = false, readOnly = false, repo = null } = {}) {\n return fetchInstallationToken({ req: taskReq, required, readOnly, repo });\n },\n\n /**\n * Read the operator's dispatch-mode config (Fast\u2192Ultracode effort setting).\n * Returns the mode string ('fast'|'standard'|'deep'|'ultra'|'marathon'; 'ultracode' legacy),\n * defaulting to 'standard' on any error. Never throws \u2014 best-effort.\n */\n async getDispatchMode() {\n try {\n const res = await taskReq('GET', '/api/v1/dispatch-mode-config');\n if (!res.ok) return 'standard';\n const json = await res.json();\n return json?.dispatchMode || 'standard';\n } catch {\n return 'standard';\n }\n },\n };\n}\n", "/** Allow-listed host maintenance operations used by the runner supervisor. */\nimport { spawnSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { win32 } from 'node:path';\n\nexport const DEFAULT_RUNNER_PACKAGE = '@algosuite/vo-mcp@beta';\nconst PACKAGE_SPEC_RE = /^@algosuite\\/vo-mcp@(beta|latest|\\d+(?:\\.\\d+){0,2}(?:-[\\w.-]+)?)$/u;\nconst MAX_DIAGNOSTIC_CHARS = 800;\nconst NPM_CLI_SUFFIX = `\\\\${win32.join('node_modules', 'npm', 'bin', 'npm-cli.js').toLowerCase()}`;\n\nfunction escapeRegExp(value) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/gu, '\\\\$&');\n}\n\n/** Keep action detail useful without ever returning credentials or tokens. */\nexport function sanitizeMaintenanceDiagnostic(raw, env = {}) {\n let value = String(raw || '')\n .replace(/\\b(?:vocred|npm|gh[oprsu])_[A-Za-z0-9._-]+\\b/gu, '[REDACTED]')\n .replace(/\\bBearer\\s+\\S+/giu, 'Bearer [REDACTED]')\n .replace(/\\b(_?authToken|token|password|secret|credential)(\\s*[=:]\\s*)\\S+/giu, '$1$2[REDACTED]');\n for (const [name, secret] of Object.entries(env)) {\n if (!/(?:TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL)/iu.test(name)) continue;\n const text = String(secret || '');\n if (text.length < 4) continue;\n value = value.replace(new RegExp(escapeRegExp(text), 'gu'), '[REDACTED]');\n }\n value = value.replace(/\\s+/gu, ' ').trim();\n if (value.length <= MAX_DIAGNOSTIC_CHARS) return value;\n return `${value.slice(0, MAX_DIAGNOSTIC_CHARS - 1)}\u2026`;\n}\n\nfunction isNpmCliPath(value) {\n return typeof value === 'string'\n && win32.isAbsolute(value)\n && win32.normalize(value).toLowerCase().endsWith(NPM_CLI_SUFFIX);\n}\n\n/**\n * Resolve npm's JavaScript entrypoint without executing a Windows `.cmd` shim.\n *\n * The desktop app can run from a bundled node.exe that does not carry npm, so\n * resolution also checks the exact npm layout below absolute PATH entries. No\n * candidate controls the executable or package argv: process.execPath remains\n * the executable and the package spec remains allow-listed below.\n */\nexport function resolveNpmCli({\n env = process.env,\n execPath = process.execPath,\n fileExists = existsSync,\n} = {}) {\n const candidates = [];\n if (isNpmCliPath(env.npm_execpath)) candidates.push(env.npm_execpath);\n candidates.push(win32.join(win32.dirname(execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js'));\n\n const pathValue = env.PATH ?? env.Path ?? env.path ?? '';\n for (const entry of pathValue.split(';')) {\n const trimmed = entry.trim();\n if (!win32.isAbsolute(trimmed)) continue;\n candidates.push(win32.join(trimmed, 'node_modules', 'npm', 'bin', 'npm-cli.js'));\n }\n\n const seen = new Set();\n for (const candidate of candidates) {\n const normalized = win32.normalize(candidate);\n const key = normalized.toLowerCase();\n if (seen.has(key) || !isNpmCliPath(normalized)) continue;\n seen.add(key);\n if (fileExists(normalized)) return normalized;\n }\n return null;\n}\n\nexport function buildMaintenanceCommand(kind, {\n platform = process.platform,\n packageSpec = DEFAULT_RUNNER_PACKAGE,\n env = process.env,\n execPath = process.execPath,\n fileExists = existsSync,\n} = {}) {\n if (!['update', 'reinstall'].includes(kind)) return null;\n if (!PACKAGE_SPEC_RE.test(packageSpec)) throw new Error('unsafe runner package spec');\n const npmCli = platform === 'win32' ? resolveNpmCli({ env, execPath, fileExists }) : null;\n if (platform === 'win32' && !npmCli) throw new Error('trusted npm CLI not found');\n const command = platform === 'win32' ? execPath : 'npm';\n const args = [...(npmCli ? [npmCli] : []), 'install', '-g', packageSpec];\n if (kind === 'reinstall') args.push('--force');\n return { command, args };\n}\n\nexport function runHostMaintenance(kind, {\n platform = process.platform,\n packageSpec = DEFAULT_RUNNER_PACKAGE,\n env = process.env,\n execPath = process.execPath,\n fileExists = existsSync,\n spawn = spawnSync,\n log = () => {},\n} = {}) {\n if (kind === 'reconnect') return { ok: true, status: 0, command: null, args: [] };\n let command;\n try {\n command = buildMaintenanceCommand(kind, { platform, packageSpec, env, execPath, fileExists });\n } catch (error) {\n return {\n ok: false,\n status: 2,\n command: null,\n args: [],\n detail: sanitizeMaintenanceDiagnostic(error instanceof Error ? error.message : String(error), env),\n };\n }\n if (!command) return { ok: false, status: 2, command: null, args: [] };\n log(`runner maintenance: ${command.command} ${command.args.join(' ')}`);\n const result = spawn(command.command, command.args, {\n stdio: ['ignore', 'pipe', 'pipe'],\n encoding: 'utf8',\n env,\n shell: false,\n windowsHide: true,\n });\n const status = typeof result.status === 'number' ? result.status : 1;\n const detail = sanitizeMaintenanceDiagnostic(\n [result.stderr, result.stdout, result.error?.message].filter(Boolean).join('\\n'),\n env,\n );\n if (detail) log(`runner maintenance result: ${detail}`);\n return { ok: status === 0, status, command: command.command, args: command.args, detail };\n}\n", "import { createHash, randomUUID } from 'node:crypto';\nimport {\n existsSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs';\nimport { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { resolveNpmCli, sanitizeMaintenanceDiagnostic } from '../../../../scripts/virtual-office/code-runner/runner-host-maintenance.mjs';\nimport {\n validateRuntimeAuthorization,\n validateStagedRuntimeAuthorization,\n} from '../../../../scripts/virtual-office/runner-bootstrap/runtime-authorization.mjs';\nimport { activateSlot, atomicWriteJson, hashFileSha512, hashRuntimeTree, slotPaths, validateSlot } from './bundled-runtime-store.mjs';\n\nconst PACKAGE_NAME = '@algosuite/vo-mcp';\nconst PACKAGE_SPEC_RE = /^@algosuite\\/vo-mcp@\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u;\nconst INTEGRITY_RE = /^sha512-[A-Za-z0-9+/]{86}==$/u;\nconst MAX_TARBALL_BYTES = 100 * 1024 * 1024;\nconst PUBLIC_REGISTRY = 'https://registry.npmjs.org/';\n\nexport function buildMinimalMaintenanceEnv(env = process.env, runtimeRoot = '') {\n const allowed = new Set([\n 'PATH', 'Path', 'path', 'PATHEXT', 'SystemRoot', 'SYSTEMROOT', 'WINDIR', 'COMSPEC',\n 'TEMP', 'TMP', 'TMPDIR', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA',\n 'ProgramFiles', 'ProgramFiles(x86)', 'ProgramW6432', 'LANG', 'LC_ALL',\n ]);\n const clean = {};\n for (const [key, value] of Object.entries(env)) {\n if (allowed.has(key) && typeof value === 'string') clean[key] = value;\n }\n return {\n ...clean,\n npm_config_ignore_scripts: 'true',\n npm_config_bin_links: 'false',\n npm_config_audit: 'false',\n npm_config_fund: 'false',\n npm_config_update_notifier: 'false',\n npm_config_registry: PUBLIC_REGISTRY,\n ...(runtimeRoot ? {\n npm_config_userconfig: join(runtimeRoot, 'maintenance', 'user.npmrc'),\n npm_config_globalconfig: join(runtimeRoot, 'maintenance', 'global.npmrc'),\n npm_config_cache: join(runtimeRoot, 'maintenance', 'npm-cache'),\n } : {}),\n };\n}\n\nfunction defaultRun(command, args, options) {\n return spawnSync(command, args, {\n cwd: options.cwd,\n encoding: 'utf8',\n env: options.env,\n shell: false,\n windowsHide: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n timeout: options.timeout ?? 120_000,\n });\n}\n\nfunction commandRunner({ platform, execPath, env, fileExists, run }) {\n const npmCli = platform === 'win32' ? resolveNpmCli({ env, execPath, fileExists }) : null;\n if (platform === 'win32' && !npmCli) throw new Error('trusted npm CLI not found');\n const npmCommand = platform === 'win32' ? execPath : 'npm';\n const prefix = npmCli ? [npmCli] : [];\n return {\n npm(args, options) { return run(npmCommand, [...prefix, ...args], options); },\n node(args, options) { return run(execPath, args, options); },\n };\n}\n\nfunction parseJsonOutput(result, operation) {\n if (result?.status !== 0) {\n throw new Error(`${operation} failed: ${String(result?.stderr || result?.error?.message || `exit ${result?.status ?? 1}`)}`);\n }\n try { return JSON.parse(String(result.stdout || '')); } catch { throw new Error(`${operation} returned invalid JSON`); }\n}\n\nfunction tarballIntegrity(file) {\n return `sha512-${createHash('sha512').update(readFileSync(file)).digest('base64')}`;\n}\n\nfunction assertNoLinks(root) {\n const pending = [root];\n while (pending.length) {\n const current = pending.pop();\n const stat = lstatSync(current);\n if (stat.isSymbolicLink()) throw new Error('installed runtime contains a link/reparse point');\n if (!stat.isDirectory()) continue;\n for (const entry of readdirSync(current)) pending.push(join(current, entry));\n }\n}\n\nexport function validateDependencyLock(payloadRoot, expected) {\n const lock = JSON.parse(readFileSync(join(payloadRoot, 'package-lock.json'), 'utf8'));\n if (Number(lock.lockfileVersion) < 3 || !lock.packages || typeof lock.packages !== 'object') {\n throw new Error('runtime dependency lock is missing or unsupported');\n }\n let foundPackage = false;\n for (const [key, item] of Object.entries(lock.packages)) {\n if (!key) continue;\n if (item?.link === true) throw new Error(`runtime dependency lock contains link: ${key}`);\n const isRunner = key.replaceAll('\\\\', '/').endsWith('node_modules/@algosuite/vo-mcp');\n if (isRunner) {\n foundPackage = item.version === expected.version && item.integrity === expected.integrity;\n continue;\n }\n if (!INTEGRITY_RE.test(String(item?.integrity || ''))) throw new Error(`dependency lacks sha512 integrity: ${key}`);\n if (!String(item?.resolved || '').startsWith('https://registry.npmjs.org/')) {\n throw new Error(`dependency is not registry-pinned: ${key}`);\n }\n }\n if (!foundPackage) throw new Error('installed runner package does not match registry integrity');\n}\n\nexport function writeAuthorizedInstallSeed(payloadRoot, tarball, runtimeAuthorization) {\n const authorization = validateRuntimeAuthorization(runtimeAuthorization);\n const stagingRoot = resolve(payloadRoot, '..', '..');\n const tarballFromStaging = relative(stagingRoot, resolve(tarball));\n if (!tarballFromStaging || tarballFromStaging === '..'\n || tarballFromStaging.startsWith(`..${sep}`)\n || isAbsolute(tarballFromStaging)) {\n throw new Error('authorized runtime tarball escaped staging root');\n }\n const relativeTarball = relative(payloadRoot, resolve(tarball)).replaceAll('\\\\', '/');\n if (!relativeTarball || isAbsolute(relativeTarball)\n || relativeTarball.includes('\\n') || relativeTarball.includes('\\r')) {\n throw new Error('authorized runtime tarball path invalid');\n }\n const fileSpec = `file:${relativeTarball}`;\n const packageRecord = { name: 'algohq-runner-runtime', version: '0.0.0', private: true,\n dependencies: { [PACKAGE_NAME]: fileSpec } };\n const packages = structuredClone(authorization.dependency_lock.packages);\n packages[`node_modules/${PACKAGE_NAME}`].resolved = fileSpec;\n const lock = { name: packageRecord.name, version: packageRecord.version,\n lockfileVersion: authorization.dependency_lock.source_lockfile_version,\n requires: true, packages: { '': packageRecord, ...packages } };\n writeFileSync(join(payloadRoot, 'package.json'), `${JSON.stringify(packageRecord)}\\n`, { mode: 0o600 });\n writeFileSync(join(payloadRoot, 'package-lock.json'), `${JSON.stringify(lock)}\\n`, { mode: 0o600 });\n return { fileSpec, lock };\n}\n\nfunction buildActive(slotId, metadata, paths) {\n return {\n slot_id: slotId,\n version: metadata.version,\n integrity: metadata.integrity,\n entry_sha512: hashFileSha512(paths.entry),\n supervisor_sha512: hashFileSha512(paths.supervisor),\n tree_sha512: hashRuntimeTree(paths.slotRoot ?? paths.payloadRoot),\n };\n}\n\nfunction installSlot({\n runtimeRoot, metadata, tarball, runner, npmEnv, runOptions, force, runtimeAuthorization,\n}) {\n const digest = createHash('sha256').update(metadata.integrity).digest('hex').slice(0, 16);\n const suffix = force ? `${digest}-${randomUUID().slice(0, 8)}` : digest;\n const slotId = `vo-mcp-${metadata.version}-${suffix}`;\n const finalPaths = slotPaths(runtimeRoot, slotId);\n if (!force && existsSync(finalPaths.slotRoot)) {\n const manifest = JSON.parse(readFileSync(finalPaths.manifest, 'utf8'));\n const active = buildActive(slotId, metadata, finalPaths);\n const validated = validateSlot(runtimeRoot, active);\n if (validated.ok && manifest.integrity === metadata.integrity) {\n if (runtimeAuthorization) {\n validateStagedRuntimeAuthorization({\n payloadRoot: finalPaths.slotRoot, authorization: runtimeAuthorization,\n });\n }\n return { active, created: false };\n }\n }\n\n const staging = join(runtimeRoot, 'staging', randomUUID());\n const payload = join(staging, 'payload');\n let installedSlot = false;\n try {\n mkdirSync(payload, { recursive: true });\n let installArgs;\n if (runtimeAuthorization) {\n writeAuthorizedInstallSeed(payload, tarball, runtimeAuthorization);\n installArgs = ['ci', '--ignore-scripts', '--no-bin-links', '--no-audit', '--no-fund',\n `--registry=${PUBLIC_REGISTRY}`];\n } else {\n writeFileSync(join(payload, 'package.json'), `${JSON.stringify({\n name: 'algohq-runner-runtime', version: '0.0.0', private: true,\n })}\\n`);\n installArgs = ['install', '--ignore-scripts', '--no-bin-links', '--no-audit', '--no-fund',\n '--package-lock=true', '--save-exact', `--registry=${PUBLIC_REGISTRY}`, tarball];\n }\n const install = runner.npm(installArgs,\n { ...runOptions, cwd: payload, env: npmEnv, timeout: 180_000 });\n if (install.status !== 0) throw new Error(`npm install failed: ${install.stderr || install.error?.message || install.status}`);\n assertNoLinks(payload);\n validateDependencyLock(payload, metadata);\n if (runtimeAuthorization) {\n validateStagedRuntimeAuthorization({ payloadRoot: payload, authorization: runtimeAuthorization });\n }\n\n const stagedPaths = {\n entry: join(payload, 'node_modules', '@algosuite', 'vo-mcp', 'bin', 'vo-mcp'),\n supervisor: join(payload, 'node_modules', '@algosuite', 'vo-mcp', 'dist', 'runner-supervisor.js'),\n packageJson: join(payload, 'node_modules', '@algosuite', 'vo-mcp', 'package.json'),\n credentialHelper: join(payload, 'node_modules', '@algosuite', 'vo-mcp', 'dist', 'supervisor-credential-helper.js'),\n slotRoot: payload,\n };\n const pkg = JSON.parse(readFileSync(stagedPaths.packageJson, 'utf8'));\n if (pkg.name !== PACKAGE_NAME || pkg.version !== metadata.version) throw new Error('installed package identity mismatch');\n if (!lstatSync(stagedPaths.credentialHelper).isFile()) throw new Error('installed credential helper is missing');\n const smoke = runner.node([stagedPaths.entry, 'runner', '--version'], { ...runOptions, cwd: payload, env: npmEnv, timeout: 30_000 });\n if (smoke.status !== 0 || String(smoke.stdout || '').trim() !== `vo-mcp runner ${metadata.version}`) {\n throw new Error('bundled runtime smoke check failed');\n }\n const active = buildActive(slotId, metadata, stagedPaths);\n atomicWriteJson(join(payload, 'runtime-manifest.json'), { schema_version: 1, ...active });\n mkdirSync(join(runtimeRoot, 'slots'), { recursive: true });\n if (existsSync(finalPaths.slotRoot)) throw new Error('immutable runtime slot already exists');\n renameSync(payload, finalPaths.slotRoot);\n installedSlot = true;\n const validated = validateSlot(runtimeRoot, active);\n if (!validated.ok) throw new Error(`staged runtime validation failed: ${validated.detail}`);\n return { active, created: true };\n } catch (error) {\n if (installedSlot) rmSync(finalPaths.slotRoot, { recursive: true, force: true });\n throw error;\n } finally {\n rmSync(staging, { recursive: true, force: true });\n }\n}\n\nexport function stageBundledRuntimeSlot(options) {\n const {\n runtimeRoot,\n packageSpec,\n expectedVersion,\n expectedIntegrity,\n platform = process.platform,\n execPath = process.execPath,\n env = process.env,\n fileExists = existsSync,\n run = defaultRun,\n force = false,\n runtimeAuthorization = null,\n } = options;\n if (!runtimeRoot || !isAbsolute(runtimeRoot)) return { ok: false, status: 2, detail: 'bundled runtime root unavailable' };\n if (!expectedVersion || !PACKAGE_SPEC_RE.test(`${PACKAGE_NAME}@${expectedVersion}`)) {\n return { ok: false, status: 2, detail: 'invalid expected runner version' };\n }\n if (!expectedIntegrity || !INTEGRITY_RE.test(expectedIntegrity)) {\n return { ok: false, status: 2, detail: 'invalid expected runner integrity' };\n }\n const exactSpec = `${PACKAGE_NAME}@${expectedVersion}`;\n if (packageSpec !== exactSpec) return { ok: false, status: 2, detail: 'runner package spec does not match authorized version' };\n const resolvedRoot = resolve(runtimeRoot);\n const npmEnv = buildMinimalMaintenanceEnv(env, resolvedRoot);\n const runOptions = { env: npmEnv, cwd: resolvedRoot };\n let tarDir = null;\n try {\n mkdirSync(resolvedRoot, { recursive: true });\n mkdirSync(join(resolvedRoot, 'maintenance'), { recursive: true });\n writeFileSync(npmEnv.npm_config_userconfig, '', { mode: 0o600 });\n writeFileSync(npmEnv.npm_config_globalconfig, '', { mode: 0o600 });\n const runner = commandRunner({ platform, execPath, env: npmEnv, fileExists, run });\n const metadata = { version: expectedVersion, integrity: expectedIntegrity };\n tarDir = join(resolvedRoot, 'staging', randomUUID());\n mkdirSync(tarDir, { recursive: true });\n const packed = parseJsonOutput(runner.npm([\n 'pack', exactSpec, '--ignore-scripts', '--json', '--pack-destination', tarDir, `--registry=${PUBLIC_REGISTRY}`,\n ], runOptions), 'npm pack');\n const record = Array.isArray(packed) ? packed[0] : packed;\n const tarball = join(tarDir, basename(String(record?.filename || '')));\n if (!existsSync(tarball) || !basename(tarball).endsWith('.tgz')) throw new Error('npm pack returned no tarball');\n if (lstatSync(tarball).size > MAX_TARBALL_BYTES) throw new Error('runner package tarball exceeds size limit');\n if (record.integrity !== metadata.integrity || tarballIntegrity(tarball) !== metadata.integrity) {\n throw new Error('runner package sha512 integrity mismatch');\n }\n const installed = installSlot({\n runtimeRoot: resolvedRoot, metadata, tarball, runner, npmEnv, runOptions, force,\n runtimeAuthorization,\n });\n return { ok: true, status: 0, ...installed };\n } catch (error) {\n return { ok: false, status: 1, detail: sanitizeMaintenanceDiagnostic(error instanceof Error ? error.message : String(error), env) };\n } finally {\n if (tarDir) rmSync(tarDir, { recursive: true, force: true });\n }\n}\n\nexport function stageAndActivateBundledUpdate(options) {\n const staged = stageBundledRuntimeSlot(options);\n if (!staged.ok) return staged;\n try {\n activateSlot(resolve(options.runtimeRoot), staged.active, options.action);\n return { ...staged, handoff: true };\n } catch (error) {\n return {\n ok: false,\n status: 1,\n detail: sanitizeMaintenanceDiagnostic(error instanceof Error ? error.message : String(error), options.env ?? process.env),\n };\n }\n}\n\nexport const __test = { INTEGRITY_RE, PACKAGE_SPEC_RE, PUBLIC_REGISTRY, assertNoLinks, tarballIntegrity };\n", "import { createHash } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nimport { dirname, posix, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n compareStagedRuntime,\n isOmittedOptionalPackage,\n} from './runtime-staged-tree.mjs';\n\nconst HERE = dirname(fileURLToPath(import.meta.url));\nexport const BETA13_WINDOWS_X64_AUTHORIZATION = resolve(\n HERE,\n 'authorizations',\n 'vo-mcp-0.2.0-beta.13-win32-x64.json',\n);\n\nconst EXPECTED = Object.freeze({\n authorizationId: 'vo-mcp-0.2.0-beta.13-win32-x64-v1',\n packageName: '@algosuite/vo-mcp',\n version: '0.2.0-beta.13',\n registry: 'https://registry.npmjs.org/',\n tarballUrl: 'https://registry.npmjs.org/@algosuite/vo-mcp/-/vo-mcp-0.2.0-beta.13.tgz',\n integrity: 'sha512-TQa5VaEFsaleHbAZZp+zS4u5U/0zQBIGOiPDGn9IqfZfdMltH2dY81nTftvu5EUABthE1xTCrdSzJjO9mzkNag==',\n tarballSha256: 'c1e39e8bb2df7f53f48e46e77ffb617452a01849469ff4757b4384a478c1cbff',\n npmShasumSha1: 'f076649b31294aa38deb7852f38a889e0d0fbe44',\n gitHead: 'ba00db90720416fa7474581eb823c6255221880f',\n sourceLockSha256: 'f8bbb5e81a0057ee2d60145580ec07f7e7055d999bdd038515c6c4e88af6cc92',\n canonicalEntriesSha256: '7f6b2f93ccb93ad625ed244dc59ac556792e478178fc690ad2ca2c6f3a2325d2',\n entryCount: 107,\n optionalEntryCount: 13,\n installedEntryCount: 96,\n treeAlgorithm: 'algohq-node-modules-manifest-sha256-v1',\n treeSha256: '9c8b0749d7ae1e2c132ef08c5b5655673ae88432859c561806276c9eb18f4874',\n treeFileCount: 3538,\n treeDirectoryCount: 553,\n treeByteCount: 20566445,\n treeManifestByteCount: 412062,\n});\n\nconst SRI_RE = /^sha512-[A-Za-z0-9+/]{86}==$/u;\nconst SHA256_RE = /^[a-f0-9]{64}$/u;\n\nfunction canonical(value) {\n if (Array.isArray(value)) return value.map(canonical);\n if (value && typeof value === 'object') {\n return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));\n }\n return value;\n}\n\nfunction sha256Canonical(value) {\n return createHash('sha256').update(`${JSON.stringify(canonical(value))}\\n`, 'utf8').digest('hex');\n}\n\nfunction assertEqual(actual, expected, label) {\n if (actual !== expected) throw new Error(`runtime authorization ${label} mismatch`);\n}\n\nfunction isOmittedOnWindowsX64(entry) {\n return isOmittedOptionalPackage(entry, { os: 'win32', arch: 'x64' });\n}\n\nexport function validateRuntimeAuthorization(value) {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('runtime authorization must be an object');\n }\n assertEqual(value.schema_version, 1, 'schema version');\n assertEqual(value.authorization_id, EXPECTED.authorizationId, 'id');\n assertEqual(value.package?.name, EXPECTED.packageName, 'package name');\n assertEqual(value.package?.version, EXPECTED.version, 'package version');\n assertEqual(value.package?.registry, EXPECTED.registry, 'registry');\n assertEqual(value.package?.tarball_url, EXPECTED.tarballUrl, 'tarball URL');\n assertEqual(value.package?.sri_sha512, EXPECTED.integrity, 'package integrity');\n assertEqual(value.package?.tarball_sha256, EXPECTED.tarballSha256, 'tarball sha256');\n assertEqual(value.package?.npm_shasum_sha1, EXPECTED.npmShasumSha1, 'npm shasum');\n assertEqual(value.package?.git_head, EXPECTED.gitHead, 'git head');\n assertEqual(value.package?.packed_file_count, 25, 'packed file count');\n assertEqual(value.package?.packed_bytes, 846151, 'packed byte count');\n assertEqual(value.package?.unpacked_bytes, 3350387, 'unpacked byte count');\n\n assertEqual(value.platform?.os, 'win32', 'operating system');\n assertEqual(value.platform?.arch, 'x64', 'architecture');\n assertEqual(value.platform?.package_node_engine, '>=22.5.0', 'package node engine');\n if (!/^24\\.15\\.0$/u.test(String(value.platform?.authorization_builder_node || ''))\n || value.platform?.authorization_builder_npm !== '11.12.1') {\n throw new Error('runtime authorization builder toolchain mismatch');\n }\n\n for (const [key, expected] of Object.entries({\n ignore_scripts: true,\n bin_links: false,\n include_optional: true,\n omit_dev: true,\n audit: false,\n fund: false,\n reject_links_reparse_points: true,\n reject_hardlinks: true,\n remove_generated_node_modules_package_lock_before_tree_validation: true,\n })) assertEqual(value.install_contract?.[key], expected, `install contract ${key}`);\n assertEqual(value.install_contract?.allowed_registry_prefix, EXPECTED.registry, 'registry prefix');\n\n const lock = value.dependency_lock;\n if (!lock?.packages || typeof lock.packages !== 'object' || Array.isArray(lock.packages)) {\n throw new Error('runtime authorization dependency set missing');\n }\n assertEqual(lock.source_lockfile_version, 3, 'lockfile version');\n assertEqual(lock.source_lock_sha256, EXPECTED.sourceLockSha256, 'source lock sha256');\n assertEqual(lock.canonical_entries_sha256, EXPECTED.canonicalEntriesSha256, 'entry-set sha256');\n assertEqual(lock.entry_count, EXPECTED.entryCount, 'entry count');\n assertEqual(lock.integrity_entry_count, EXPECTED.entryCount, 'integrity count');\n assertEqual(lock.optional_entry_count, EXPECTED.optionalEntryCount, 'optional count');\n assertEqual(lock.windows_x64_installed_entry_count, EXPECTED.installedEntryCount, 'installed count');\n\n const entries = Object.entries(lock.packages);\n assertEqual(entries.length, EXPECTED.entryCount, 'package map count');\n for (const [key, entry] of entries) {\n if (!key.startsWith('node_modules/') || key.includes('\\\\') || posix.normalize(key) !== key\n || key.split('/').includes('..')) {\n throw new Error(`runtime authorization has unsafe package path: ${key}`);\n }\n if (!entry || typeof entry !== 'object' || entry.link === true) {\n throw new Error(`runtime authorization contains a linked package: ${key}`);\n }\n if (!SRI_RE.test(String(entry.integrity || ''))) {\n throw new Error(`runtime authorization package lacks sha512 integrity: ${key}`);\n }\n if (!String(entry.resolved || '').startsWith(EXPECTED.registry)) {\n throw new Error(`runtime authorization package is outside the public registry: ${key}`);\n }\n if (entry.hasInstallScript === true) {\n throw new Error(`runtime authorization package declares an install script: ${key}`);\n }\n }\n const runner = lock.packages['node_modules/@algosuite/vo-mcp'];\n assertEqual(runner?.version, EXPECTED.version, 'runner dependency version');\n assertEqual(runner?.integrity, EXPECTED.integrity, 'runner dependency integrity');\n assertEqual(sha256Canonical(lock.packages), EXPECTED.canonicalEntriesSha256, 'computed entry-set sha256');\n\n const omitted = entries.filter(([, entry]) => isOmittedOnWindowsX64(entry)).map(([key]) => key).sort();\n const declaredOmitted = [...(lock.windows_x64_omitted_optional_entries || [])].sort();\n assertEqual(JSON.stringify(declaredOmitted), JSON.stringify(omitted), 'omitted optional entries');\n assertEqual(entries.length - omitted.length, EXPECTED.installedEntryCount, 'derived installed count');\n\n const tree = value.installed_tree;\n assertEqual(tree?.algorithm, EXPECTED.treeAlgorithm, 'tree algorithm');\n if (!SHA256_RE.test(String(tree?.sha256 || ''))) throw new Error('runtime authorization tree hash invalid');\n assertEqual(tree.sha256, EXPECTED.treeSha256, 'tree sha256');\n assertEqual(tree.file_count, EXPECTED.treeFileCount, 'tree file count');\n assertEqual(tree.directory_count, EXPECTED.treeDirectoryCount, 'tree directory count');\n assertEqual(tree.byte_count, EXPECTED.treeByteCount, 'tree byte count');\n assertEqual(tree.canonical_manifest_byte_count, EXPECTED.treeManifestByteCount, 'tree manifest byte count');\n assertEqual(tree.reparse_point_count, 0, 'tree reparse count');\n assertEqual(tree.hardlinked_file_count, 0, 'tree hardlink count');\n return value;\n}\n\nexport function readRuntimeAuthorization(file = BETA13_WINDOWS_X64_AUTHORIZATION) {\n return validateRuntimeAuthorization(JSON.parse(readFileSync(file, 'utf8')));\n}\n\nexport function validateStagedRuntimeAuthorization(options) {\n const authorization = validateRuntimeAuthorization(options?.authorization || readRuntimeAuthorization());\n return compareStagedRuntime({ ...options, authorization });\n}\n\nif (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {\n readRuntimeAuthorization(process.argv[2] ? resolve(process.argv[2]) : undefined);\n process.stdout.write('AlgoHQ runtime authorization valid\\n');\n}\n\nexport const __test = { canonical, isOmittedOnWindowsX64, sha256Canonical };\n", "import { execFileSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport {\n existsSync,\n lstatSync,\n readFileSync,\n readdirSync,\n} from 'node:fs';\nimport { isAbsolute, join, relative, resolve, sep, win32 } from 'node:path';\n\nconst WINDOWS_REPARSE_ATTRIBUTE = 0x400;\nconst RUNNER_LOCK_KEY = 'node_modules/@algosuite/vo-mcp';\nexport const INSTALLED_TREE_ALGORITHM = 'algohq-node-modules-manifest-sha256-v1';\n\nfunction canonical(value) {\n if (Array.isArray(value)) return value.map(canonical);\n if (value && typeof value === 'object') {\n return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));\n }\n return value;\n}\n\nfunction canonicalJson(value) {\n return JSON.stringify(canonical(value));\n}\n\nfunction hasFileAttribute(value, bit) {\n if (typeof value === 'bigint') return (value & BigInt(bit)) !== 0n;\n return Number.isSafeInteger(value) && (value & bit) !== 0;\n}\n\nexport function isReparseStat(stats) {\n if (!stats || typeof stats !== 'object') return false;\n if (typeof stats.isSymbolicLink === 'function' && stats.isSymbolicLink()) return true;\n if (stats.reparseTag !== undefined && stats.reparseTag !== null && stats.reparseTag !== 0) return true;\n return ['fileAttributes', 'fileAttribute', 'attributes']\n .some((key) => hasFileAttribute(stats[key], WINDOWS_REPARSE_ATTRIBUTE));\n}\n\nexport function platformConstraintAllows(values, target) {\n if (!Array.isArray(values) || values.length === 0) return true;\n if (values.some((value) => value === `!${target}`)) return false;\n const positive = values.filter((value) => typeof value === 'string' && !value.startsWith('!'));\n return positive.length === 0 || positive.includes(target);\n}\n\nexport function isOmittedOptionalPackage(entry, platform = { os: 'win32', arch: 'x64' }) {\n return entry?.optional === true && (\n !platformConstraintAllows(entry.os, platform.os)\n || !platformConstraintAllows(entry.cpu, platform.arch)\n );\n}\n\nfunction assertContained(root, candidate, label) {\n const rel = relative(root, candidate);\n if (rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel))) return;\n throw new Error(`staged runtime ${label} escapes the payload root`);\n}\n\nfunction normalizeReportedPath(root, candidate) {\n const absolute = resolve(String(candidate || ''));\n assertContained(root, absolute, 'reparse point');\n return absolute;\n}\n\nexport function listWindowsReparsePoints(root, {\n execFile = execFileSync, env = process.env, platform = process.platform,\n} = {}) {\n if (platform !== 'win32') return [];\n const systemRoot = String(env.SystemRoot || env.SYSTEMROOT || '');\n if (!win32.isAbsolute(systemRoot) || win32.normalize(systemRoot) !== systemRoot) {\n throw new Error('staged runtime trusted PowerShell root unavailable');\n }\n const system32 = win32.join(systemRoot, 'System32');\n const powershell = win32.join(system32, 'WindowsPowerShell', 'v1.0', 'powershell.exe');\n const script = [\n '$ErrorActionPreference = \"Stop\"',\n '$root = [IO.Path]::GetFullPath($env:ALGOHQ_REPARSE_ROOT)',\n '$items = @((Get-Item -LiteralPath $root -Force)) + @(Get-ChildItem -LiteralPath $root -Force -Recurse)',\n 'foreach ($item in $items) {',\n ' if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {',\n ' [Console]::Out.WriteLine($item.FullName)',\n ' }',\n '}',\n ].join('; ');\n const output = execFile(powershell, [\n '-NoLogo',\n '-NoProfile',\n '-NonInteractive',\n '-Command',\n script,\n ], {\n cwd: system32,\n encoding: 'utf8',\n env: { SystemRoot: systemRoot, ALGOHQ_REPARSE_ROOT: win32.resolve(root) },\n windowsHide: true,\n });\n return String(output || '').split(/\\r?\\n/u).filter(Boolean)\n .map((item) => normalizeReportedPath(root, item));\n}\n\nfunction normalizedRunnerRecord(actual, expected) {\n const normalized = structuredClone(actual);\n if (normalized?.resolved === expected?.resolved) return normalized;\n if (typeof normalized?.resolved !== 'string' || !normalized.resolved.startsWith('file:')) {\n return normalized;\n }\n const fileName = normalized.resolved.slice('file:'.length).replaceAll('\\\\', '/').split('/').at(-1);\n const expectedFileNames = new Set([\n String(expected.resolved || '').split('/').at(-1),\n `algosuite-vo-mcp-${expected.version}.tgz`,\n ]);\n if (expectedFileNames.has(fileName)) normalized.resolved = expected.resolved;\n return normalized;\n}\n\nfunction validateLock(lock, authorization) {\n if (!lock || typeof lock !== 'object' || Array.isArray(lock)) {\n throw new Error('staged runtime package-lock must be an object');\n }\n if (lock.lockfileVersion !== authorization.dependency_lock.source_lockfile_version) {\n throw new Error('staged runtime package-lock version mismatch');\n }\n if (!lock.packages || typeof lock.packages !== 'object' || Array.isArray(lock.packages)) {\n throw new Error('staged runtime package-lock package map missing');\n }\n const expected = authorization.dependency_lock.packages;\n const actual = Object.fromEntries(Object.entries(lock.packages).filter(([key]) => key !== ''));\n const expectedKeys = Object.keys(expected).sort();\n const actualKeys = Object.keys(actual).sort();\n if (canonicalJson(actualKeys) !== canonicalJson(expectedKeys)) {\n throw new Error('staged runtime package-lock package set mismatch');\n }\n for (const key of expectedKeys) {\n const record = key === RUNNER_LOCK_KEY\n ? normalizedRunnerRecord(actual[key], expected[key])\n : actual[key];\n if (canonicalJson(record) !== canonicalJson(expected[key])) {\n throw new Error(`staged runtime package-lock record mismatch: ${key}`);\n }\n }\n return { actual, expected };\n}\n\nfunction checkPathKind(path, expectedKind, fsOps, label) {\n if (!fsOps.exists(path)) throw new Error(`staged runtime ${label} missing`);\n const stats = fsOps.lstat(path);\n if (isReparseStat(stats) || fsOps.isReparsePoint(path, stats)) {\n throw new Error(`staged runtime ${label} is a reparse point`);\n }\n if (expectedKind === 'directory' && !stats.isDirectory()) {\n throw new Error(`staged runtime ${label} is not a directory`);\n }\n if (expectedKind === 'file' && !stats.isFile()) {\n throw new Error(`staged runtime ${label} is not a regular file`);\n }\n if (expectedKind === 'file' && Number(stats.nlink) > 1) {\n throw new Error(`staged runtime ${label} is hardlinked`);\n }\n return stats;\n}\n\nfunction verifyInstalledPackages(payloadRoot, packageRecords, platform, fsOps) {\n const omitted = [];\n let installed = 0;\n for (const [key, entry] of Object.entries(packageRecords)) {\n const path = resolve(payloadRoot, key);\n assertContained(payloadRoot, path, 'package path');\n const shouldOmit = isOmittedOptionalPackage(entry, platform);\n if (shouldOmit) {\n omitted.push(key);\n if (fsOps.exists(path)) throw new Error(`staged runtime optional package should be omitted: ${key}`);\n continue;\n }\n checkPathKind(path, 'directory', fsOps, `installed package ${key}`);\n installed += 1;\n }\n return { installed, omitted: omitted.sort() };\n}\n\nfunction treeRecord(kind, path, stats, fileHash = '') {\n if (kind === 'd') return `d\\t${path}\\r\\n`;\n return `f\\t${path}\\t${stats.size}\\t${fileHash}\\r\\n`;\n}\n\nexport function computeInstalledTree(nodeModulesRoot, fsOps = {}) {\n const ops = {\n exists: existsSync,\n lstat: lstatSync,\n readdir: (path) => readdirSync(path, { withFileTypes: true }),\n readFile: readFileSync,\n isReparsePoint: () => false,\n listReparsePoints: listWindowsReparsePoints,\n ...fsOps,\n };\n const root = resolve(nodeModulesRoot);\n checkPathKind(root, 'directory', ops, 'node_modules root');\n const reported = ops.listReparsePoints(root);\n if (!Array.isArray(reported)) throw new Error('staged runtime reparse probe returned an invalid result');\n if (reported.length > 0) throw new Error('staged runtime tree contains a Windows reparse point');\n\n let fileCount = 0;\n let directoryCount = 1;\n let byteCount = 0;\n const entries = [];\n function walk(absolute, relativePath) {\n for (const entry of ops.readdir(absolute)) {\n const childRelative = relativePath ? `${relativePath}/${entry.name}` : entry.name;\n if (childRelative === '.package-lock.json') continue;\n const child = resolve(absolute, entry.name);\n assertContained(root, child, 'tree entry');\n const stats = ops.lstat(child);\n if (isReparseStat(stats) || ops.isReparsePoint(child, stats)) {\n throw new Error(`staged runtime tree contains a reparse point: ${childRelative}`);\n }\n if (stats.isDirectory()) {\n directoryCount += 1;\n entries.push({ kind: 'd', path: childRelative, stats });\n walk(child, childRelative);\n } else if (stats.isFile()) {\n if (Number(stats.nlink) > 1) {\n throw new Error(`staged runtime tree contains a hardlinked file: ${childRelative}`);\n }\n fileCount += 1;\n byteCount += Number(stats.size);\n const digest = createHash('sha256').update(ops.readFile(child)).digest('hex');\n entries.push({ kind: 'f', path: childRelative, stats, digest });\n } else {\n throw new Error(`staged runtime tree contains a non-file entry: ${childRelative}`);\n }\n }\n }\n walk(root, '');\n entries.sort((left, right) => Buffer.compare(Buffer.from(left.path), Buffer.from(right.path)));\n const manifest = treeRecord('d', '', { size: 0 }) + entries\n .map((entry) => treeRecord(entry.kind, entry.path, entry.stats, entry.digest))\n .join('');\n return {\n algorithm: INSTALLED_TREE_ALGORITHM,\n sha256: createHash('sha256').update(manifest, 'utf8').digest('hex'),\n file_count: fileCount,\n directory_count: directoryCount,\n byte_count: byteCount,\n canonical_manifest_byte_count: Buffer.byteLength(manifest),\n reparse_point_count: 0,\n hardlinked_file_count: 0,\n };\n}\n\nexport function compareStagedRuntime({\n payloadRoot,\n nodeModulesRoot = join(payloadRoot, 'node_modules'),\n packageLockFile = join(payloadRoot, 'package-lock.json'),\n authorization,\n fsOps = {},\n}) {\n const payload = resolve(payloadRoot);\n const modules = resolve(nodeModulesRoot);\n const lockFile = resolve(packageLockFile);\n if (modules !== resolve(payload, 'node_modules') || lockFile !== resolve(payload, 'package-lock.json')) {\n throw new Error('staged runtime paths do not identify one canonical payload');\n }\n const ops = {\n exists: existsSync,\n lstat: lstatSync,\n readFile: readFileSync,\n isReparsePoint: () => false,\n ...fsOps,\n };\n checkPathKind(lockFile, 'file', ops, 'package-lock');\n const lock = JSON.parse(ops.readFile(lockFile, 'utf8'));\n const { expected } = validateLock(lock, authorization);\n const platform = { os: authorization.platform.os, arch: authorization.platform.arch };\n const packages = verifyInstalledPackages(payload, expected, platform, ops);\n const declaredOmitted = [...authorization.dependency_lock.windows_x64_omitted_optional_entries].sort();\n if (canonicalJson(packages.omitted) !== canonicalJson(declaredOmitted)) {\n throw new Error('staged runtime optional omission list mismatch');\n }\n if (packages.installed !== Object.keys(expected).length - packages.omitted.length) {\n throw new Error('staged runtime installed package count mismatch');\n }\n const tree = computeInstalledTree(modules, fsOps);\n if (canonicalJson(tree) !== canonicalJson(authorization.installed_tree)) {\n throw new Error('staged runtime installed tree mismatch');\n }\n return { ok: true, packageCount: Object.keys(expected).length, ...packages, tree };\n}\n\nexport const __test = { canonical, canonicalJson, normalizeReportedPath, normalizedRunnerRecord };\n", "import { createHash, randomUUID } from 'node:crypto';\nimport {\n closeSync,\n existsSync,\n fsyncSync,\n lstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n readdirSync,\n realpathSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\n\nconst SLOT_ID_RE = /^vo-mcp-[0-9A-Za-z._-]{1,96}$/u;\nconst ACTION_ID_RE = /^[0-9A-Za-z._-]{1,128}$/u;\nconst INTEGRITY_RE = /^sha512-[A-Za-z0-9+/]{86}==$/u;\nconst VERSION_RE = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u;\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\nconst ENTRY_REL = join('node_modules', '@algosuite', 'vo-mcp', 'bin', 'vo-mcp');\nconst SUPERVISOR_REL = join('node_modules', '@algosuite', 'vo-mcp', 'dist', 'runner-supervisor.js');\nconst PACKAGE_REL = join('node_modules', '@algosuite', 'vo-mcp', 'package.json');\nconst CREDENTIAL_HELPER_REL = join('node_modules', '@algosuite', 'vo-mcp', 'dist', 'supervisor-credential-helper.js');\nconst MANIFEST_FILE = 'runtime-manifest.json';\n\nfunction within(parent, candidate) {\n const rel = relative(resolve(parent), resolve(candidate));\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));\n}\n\n/**\n * Mirror of the desktop app's runtime-root resolution: RUNNER_RUNTIME_DIR\n * under Tauri's BaseDirectory::AppData for the app identifier. MUST stay in\n * lockstep with packages/vo-runner-app/src-tauri/src/runtime_slots.rs\n * (`RUNNER_RUNTIME_DIR`) and tauri.conf.json (`identifier`), or supervisors\n * and the app would stage/read different roots.\n */\nconst APP_IDENTIFIER = 'ai.algosuite.vo-runner';\nconst RUNNER_RUNTIME_DIR = 'runner-runtime';\n\nexport function defaultRuntimeRoot({ platform = process.platform, env = process.env, home = homedir() } = {}) {\n if (platform === 'win32') {\n const appData = String(env.APPDATA || '').trim();\n return appData && isAbsolute(appData) ? join(appData, APP_IDENTIFIER, RUNNER_RUNTIME_DIR) : null;\n }\n if (!home) return null;\n if (platform === 'darwin') {\n return join(home, 'Library', 'Application Support', APP_IDENTIFIER, RUNNER_RUNTIME_DIR);\n }\n const xdg = String(env.XDG_CONFIG_HOME || '').trim();\n const base = xdg && isAbsolute(xdg) ? xdg : join(home, '.config');\n return join(base, APP_IDENTIFIER, RUNNER_RUNTIME_DIR);\n}\n\n/**\n * Explicit VO_RUNNER_RUNTIME_ROOT always wins, and a SET-but-invalid value\n * still fails closed (null \u2014 a misconfiguration must not silently fall back).\n * When the variable is ABSENT, derive the app-convention default: a\n * supervisor launched by an env-stripping wrapper (live-observed on\n * vo-code-runner-JacksPC, 2026-07-21: every bundled update hard-failed\n * \"bundled runtime root unavailable\") can then still stage/activate the\n * governed update into the exact directory the desktop app reads.\n */\nexport function runtimeRootFromEnv(env = process.env, { platform, home } = {}) {\n const value = String(env.VO_RUNNER_RUNTIME_ROOT || '').trim();\n if (value) return isAbsolute(value) ? resolve(value) : null;\n const derived = defaultRuntimeRoot({ platform, env, home });\n return derived ? resolve(derived) : null;\n}\n\nexport function hashFileSha512(file) {\n return `sha512-${createHash('sha512').update(readFileSync(file)).digest('base64')}`;\n}\n\n/** Digest every executable payload byte and relative path, excluding only the self-referential manifest. */\nexport function hashRuntimeTree(root) {\n const hasher = createHash('sha512');\n const files = [];\n const visit = (directory, prefix = '') => {\n const rootStat = lstatSync(directory);\n if (rootStat.isSymbolicLink()) throw new Error('runtime tree contains a link/reparse point');\n if (!rootStat.isDirectory()) throw new Error('runtime tree root is not a directory');\n for (const name of readdirSync(directory).sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)))) {\n const absolute = join(directory, name);\n const relativePath = prefix ? `${prefix}/${name}` : name;\n const stat = lstatSync(absolute);\n if (stat.isSymbolicLink()) throw new Error('runtime tree contains a link/reparse point');\n if (stat.isDirectory()) visit(absolute, relativePath);\n else if (stat.isFile() && relativePath !== MANIFEST_FILE) files.push({ absolute, relativePath, size: stat.size });\n else if (!stat.isFile()) throw new Error('runtime tree contains a non-regular file');\n }\n };\n visit(root);\n files.sort((a, b) => Buffer.compare(Buffer.from(a.relativePath), Buffer.from(b.relativePath)));\n for (const file of files) {\n const pathBytes = Buffer.from(file.relativePath, 'utf8');\n hasher.update(`${pathBytes.length}:`);\n hasher.update(pathBytes);\n hasher.update(`:${file.size}:`);\n hasher.update(readFileSync(file.absolute));\n hasher.update('\\n');\n }\n return `sha512-${hasher.digest('base64')}`;\n}\n\nexport function atomicWriteJson(file, value) {\n mkdirSync(dirname(file), { recursive: true });\n const temp = join(dirname(file), `.${randomUUID()}.tmp`);\n const fd = openSync(temp, 'wx', 0o600);\n try {\n writeFileSync(fd, `${JSON.stringify(value, null, 2)}\\n`, 'utf8');\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n try {\n renameSync(temp, file);\n // A file fsync does not make the directory entry durable on POSIX. Windows\n // cannot open directories this way, so keep the durability upgrade best-effort.\n if (process.platform !== 'win32') {\n try {\n const parentFd = openSync(dirname(file), 'r');\n try { fsyncSync(parentFd); } finally { closeSync(parentFd); }\n } catch { /* current.json remains atomically committed */ }\n }\n } finally {\n rmSync(temp, { force: true });\n }\n}\n\nexport function readActivation(runtimeRoot) {\n const file = join(runtimeRoot, 'current.json');\n if (!existsSync(file)) return null;\n try {\n const value = JSON.parse(readFileSync(file, 'utf8'));\n return value?.schema_version === 1 ? value : null;\n } catch {\n return null;\n }\n}\n\nexport function slotPaths(runtimeRoot, slotId) {\n if (!SLOT_ID_RE.test(slotId)) throw new Error('invalid runtime slot id');\n const slotRoot = join(runtimeRoot, 'slots', slotId);\n return {\n slotRoot,\n entry: join(slotRoot, ENTRY_REL),\n supervisor: join(slotRoot, SUPERVISOR_REL),\n packageJson: join(slotRoot, PACKAGE_REL),\n credentialHelper: join(slotRoot, CREDENTIAL_HELPER_REL),\n manifest: join(slotRoot, MANIFEST_FILE),\n };\n}\n\nfunction validActive(active) {\n return active\n && SLOT_ID_RE.test(active.slot_id)\n && VERSION_RE.test(active.version)\n && INTEGRITY_RE.test(active.integrity)\n && INTEGRITY_RE.test(active.entry_sha512)\n && INTEGRITY_RE.test(active.supervisor_sha512)\n && INTEGRITY_RE.test(active.tree_sha512);\n}\n\nexport function validateSlot(runtimeRoot, active) {\n if (!validActive(active)) return { ok: false, detail: 'invalid activation metadata' };\n const paths = slotPaths(runtimeRoot, active.slot_id);\n try {\n const manifest = JSON.parse(readFileSync(paths.manifest, 'utf8'));\n const pkg = JSON.parse(readFileSync(paths.packageJson, 'utf8'));\n const expected = {\n slot_id: active.slot_id,\n version: active.version,\n integrity: active.integrity,\n entry_sha512: active.entry_sha512,\n supervisor_sha512: active.supervisor_sha512,\n tree_sha512: active.tree_sha512,\n };\n for (const [key, value] of Object.entries(expected)) {\n if (manifest?.[key] !== value) return { ok: false, detail: `manifest ${key} mismatch` };\n }\n if (manifest?.schema_version !== 1 || pkg?.name !== '@algosuite/vo-mcp' || pkg?.version !== active.version) {\n return { ok: false, detail: 'package identity mismatch' };\n }\n if (lstatSync(paths.entry).isSymbolicLink() || lstatSync(paths.supervisor).isSymbolicLink()\n || lstatSync(paths.credentialHelper).isSymbolicLink()) {\n return { ok: false, detail: 'runtime entry cannot be a link' };\n }\n if (!within(paths.slotRoot, realpathSync(paths.entry)) || !within(paths.slotRoot, realpathSync(paths.supervisor))\n || !within(paths.slotRoot, realpathSync(paths.credentialHelper))) {\n return { ok: false, detail: 'runtime entry escaped its slot' };\n }\n if (hashFileSha512(paths.entry) !== active.entry_sha512) return { ok: false, detail: 'entry hash mismatch' };\n if (hashFileSha512(paths.supervisor) !== active.supervisor_sha512) return { ok: false, detail: 'supervisor hash mismatch' };\n if (hashRuntimeTree(paths.slotRoot) !== active.tree_sha512) return { ok: false, detail: 'runtime tree hash mismatch' };\n return { ok: true, paths, manifest };\n } catch (error) {\n return { ok: false, detail: error instanceof Error ? error.message : String(error) };\n }\n}\n\nexport function journalActivation(runtimeRoot, actionId, state, detail = '') {\n if (!ACTION_ID_RE.test(actionId)) throw new Error('invalid runner action id');\n atomicWriteJson(join(runtimeRoot, 'transactions', `${actionId}.json`), {\n schema_version: 1,\n action_id: actionId,\n state,\n detail: String(detail).slice(0, 400),\n updated_at: new Date().toISOString(),\n });\n}\n\nexport function activateSlot(runtimeRoot, active, action) {\n if (!validActive(active)) throw new Error('cannot activate invalid runtime metadata');\n if (!ACTION_ID_RE.test(action.actionId)) throw new Error('invalid runner action id');\n if (!UUID_RE.test(String(action.supervisorInstanceId || ''))) throw new Error('invalid claiming supervisor instance id');\n const validated = validateSlot(runtimeRoot, active);\n if (!validated.ok) throw new Error(`cannot activate invalid runtime slot: ${validated.detail}`);\n const current = readActivation(runtimeRoot);\n if (current?.pending) throw new Error('another runtime activation is still pending');\n const pointer = {\n schema_version: 1,\n generation: randomUUID(),\n active,\n previous: validActive(current?.active) ? current.active : null,\n pending: {\n action_id: action.actionId,\n runner_id: String(action.runnerId || ''),\n operator_id: String(action.operatorId || ''),\n supervisor_instance_id: action.supervisorInstanceId,\n activated_at: new Date().toISOString(),\n ack_attempts: 0,\n },\n };\n // The pointer rename is the transaction commit and therefore the last\n // fallible write. A crash before it leaves the previous runtime selected.\n journalActivation(runtimeRoot, action.actionId, 'prepared', `${active.version} ${active.integrity}`);\n atomicWriteJson(join(runtimeRoot, 'current.json'), pointer);\n return pointer;\n}\n\nexport function activationSupervisorInstanceId(runtimeRoot, fallback) {\n const current = runtimeRoot ? readActivation(runtimeRoot) : null;\n const pending = String(current?.pending?.supervisor_instance_id || '');\n if (UUID_RE.test(pending)) return pending;\n return UUID_RE.test(String(fallback || '')) ? fallback : null;\n}\n\nexport function recordActivationRetry(runtimeRoot, pointer, detail) {\n const current = readActivation(runtimeRoot);\n if (current?.generation !== pointer?.generation\n || current?.pending?.action_id !== pointer?.pending?.action_id) {\n throw new Error('runtime activation generation changed before retry');\n }\n const attempts = Math.max(0, Number(current.pending.ack_attempts || 0)) + 1;\n const updated = {\n ...current,\n pending: { ...current.pending, ack_attempts: attempts, last_error: String(detail).slice(0, 240) },\n };\n atomicWriteJson(join(runtimeRoot, 'current.json'), updated);\n journalActivation(runtimeRoot, current.pending.action_id, 'ack-retry', `attempt ${attempts}: ${detail}`);\n return updated;\n}\n\n/** One-time migration for an old desktop launcher that has no control action. */\nexport function bootstrapSlot(runtimeRoot, active, bootstrapId) {\n if (!ACTION_ID_RE.test(bootstrapId)) throw new Error('invalid bootstrap id');\n const validated = validateSlot(runtimeRoot, active);\n if (!validated.ok) throw new Error(`cannot bootstrap invalid runtime slot: ${validated.detail}`);\n const current = readActivation(runtimeRoot);\n if (current?.pending) throw new Error('another runtime activation is still pending');\n if (current?.active?.slot_id === active.slot_id && current.active.integrity === active.integrity) return current;\n const pointer = {\n schema_version: 1,\n generation: randomUUID(),\n active,\n previous: validActive(current?.active) ? current.active : null,\n pending: null,\n };\n journalActivation(runtimeRoot, bootstrapId, 'bootstrap-prepared', `${active.version} ${active.integrity}`);\n atomicWriteJson(join(runtimeRoot, 'current.json'), pointer);\n try { journalActivation(runtimeRoot, bootstrapId, 'bootstrap-activated', `${active.version} active`); } catch { /* best effort */ }\n return pointer;\n}\n\n/** Restore the exact pre-bootstrap pointer without overwriting a newer activation. */\nexport function restoreBootstrapActivation(runtimeRoot, expectedActive, prior, rollbackId) {\n if (!ACTION_ID_RE.test(rollbackId)) throw new Error('invalid bootstrap rollback id');\n const current = readActivation(runtimeRoot);\n if (current?.active?.slot_id !== expectedActive?.slot_id\n || current?.active?.tree_sha512 !== expectedActive?.tree_sha512) {\n throw new Error('bootstrap activation changed before rollback');\n }\n if (prior?.schema_version === 1) {\n atomicWriteJson(join(runtimeRoot, 'current.json'), prior);\n } else {\n const quarantine = join(runtimeRoot, 'quarantine', `${rollbackId}-current.json`);\n mkdirSync(dirname(quarantine), { recursive: true });\n renameSync(join(runtimeRoot, 'current.json'), quarantine);\n }\n try { journalActivation(runtimeRoot, rollbackId, 'bootstrap-pointer-restored', expectedActive.version); }\n catch { /* the restored pointer is authoritative */ }\n}\n\nexport function attestCurrentSupervisor({ runtimeRoot, selfPath, version }) {\n const pointer = readActivation(runtimeRoot);\n if (!pointer?.pending || !validActive(pointer.active)) return { ok: false, detail: 'no pending activation' };\n const validated = validateSlot(runtimeRoot, pointer.active);\n if (!validated.ok) return validated;\n try {\n if (realpathSync(selfPath) !== realpathSync(validated.paths.supervisor)) {\n return { ok: false, detail: 'running supervisor is not the activated supervisor' };\n }\n } catch {\n return { ok: false, detail: 'could not resolve running supervisor path' };\n }\n if (version !== pointer.active.version) return { ok: false, detail: 'running supervisor version mismatch' };\n return { ok: true, pointer, active: pointer.active, paths: validated.paths };\n}\n\nexport function finalizeActivation(runtimeRoot, pointer) {\n const current = readActivation(runtimeRoot);\n if (current?.generation !== pointer?.generation\n || current?.pending?.action_id !== pointer?.pending?.action_id) {\n throw new Error('runtime activation generation changed before finalization');\n }\n journalActivation(runtimeRoot, pointer.pending.action_id, 'attesting', `${pointer.active.version} verified`);\n atomicWriteJson(join(runtimeRoot, 'current.json'), {\n schema_version: 1,\n generation: pointer.generation,\n active: pointer.active,\n previous: pointer.previous || null,\n pending: null,\n });\n // current.json is authoritative. A journal-only failure must never turn a\n // committed activation into a false update failure.\n try { journalActivation(runtimeRoot, pointer.pending.action_id, 'attested', `${pointer.active.version} active`); } catch { /* best effort */ }\n}\n\nexport function rollbackActivation(runtimeRoot, pointer, detail) {\n const current = readActivation(runtimeRoot);\n if (current?.generation !== pointer?.generation\n || current?.pending?.action_id !== pointer?.pending?.action_id) {\n throw new Error('runtime activation generation changed before rollback');\n }\n journalActivation(runtimeRoot, pointer.pending.action_id, 'rolling-back', detail);\n const rolledBack = {\n schema_version: 1,\n generation: randomUUID(),\n active: validActive(pointer?.previous) ? pointer.previous : null,\n previous: null,\n pending: {\n ...pointer.pending,\n terminal_status: 'failed',\n terminal_detail: String(detail).slice(0, 400),\n rolled_back_at: new Date().toISOString(),\n },\n };\n atomicWriteJson(join(runtimeRoot, 'current.json'), rolledBack);\n try { journalActivation(runtimeRoot, pointer.pending.action_id, 'rolled-back', detail); } catch { /* best effort */ }\n return rolledBack;\n}\n\nexport function acknowledgeActivationFailure(runtimeRoot, pointer) {\n const current = readActivation(runtimeRoot);\n if (current?.generation !== pointer?.generation\n || current?.pending?.action_id !== pointer?.pending?.action_id\n || current?.pending?.terminal_status !== 'failed') {\n throw new Error('runtime rollback acknowledgement obligation changed');\n }\n atomicWriteJson(join(runtimeRoot, 'current.json'), { ...current, pending: null });\n try { journalActivation(runtimeRoot, pointer.pending.action_id, 'failure-acknowledged', pointer.pending.terminal_detail); }\n catch { /* current.json is authoritative */ }\n}\n\nexport const __test = { ACTION_ID_RE, ENTRY_REL, INTEGRITY_RE, SLOT_ID_RE, SUPERVISOR_REL, UUID_RE, VERSION_RE, validActive, within };\n", "/**\n * legacy-orphan-sweep \u2014 operator-triggered reclamation of agent processes\n * leaked by PRE-REAPER daemons (they never recorded their spawns, so the\n * recorded-PID orphan-agent-reaper can NEVER touch them by design).\n *\n * This is deliberately NOT automatic: it runs only when a human presses the\n * \"Clear stuck agents\" control in AlgoHQ (a governed `purge-orphans` runner\n * control action), and only a supervisor advertising the\n * `legacy-orphan-purge-v1` capability will claim one.\n *\n * Because there are no records to trust, selection is by evidence that ALL\n * hold simultaneously:\n * 1. The command line matches a RUNNER-ONLY agent spawn signature\n * (`claude \u2026 --output-format stream-json` headless / `codex exec --json`).\n * Interactive agent sessions and detached watchers never match.\n * 2. The parent process is dead \u2014 absent, or its pid was reused by a process\n * created AFTER the child (an orphan's parent can never be younger).\n * A live daemon's agents always have a live parent, so a running peer\n * runner's work is structurally unselectable.\n * 3. The process predates the sweep cutoff (nothing racing the relaunch).\n * 4. The pid is not the supervisor itself or otherwise protected.\n * Selection is capped, oldest-first, and every kill is logged with its\n * command-line evidence. The decision core is pure and unit-tested; OS shims\n * are injected. Reuses the reaper's hardened epoch conversion + tree kill.\n */\nimport { spawnSync } from 'node:child_process';\nimport { killProcessTree, windowsPowershellExe } from './orphan-agent-reaper.mjs';\n\nexport const LEGACY_PURGE_CAPABILITY = 'legacy-orphan-purge-v1';\nexport const MAX_LEGACY_KILLS = 50;\n/** Ignore anything created within this window before the sweep (races). */\nexport const SWEEP_RECENCY_BUFFER_MS = 5_000;\n\nconst SIGNATURES = [\n {\n signature: 'claude-headless',\n // claude-args.mjs always emits `-p --output-format stream-json --verbose`.\n test: (cl) => /(?:^|[\\\\/\"\\s])claude(?:\\.exe|\\.cmd|\\.ps1)?(?:\"|\\s)/iu.test(cl) && /--output-format[\\s\"=]+stream-json/iu.test(cl),\n },\n {\n signature: 'codex-headless',\n // openai-compatible-runner always emits `exec --json`.\n test: (cl) => /(?:^|[\\\\/\"\\s])codex(?:\\.exe|\\.cmd|\\.ps1)?(?:\"|\\s)/iu.test(cl) && /\\bexec\\b/u.test(cl) && /--json\\b/u.test(cl),\n },\n];\n\n/** Which runner-agent signature (if any) a raw command line matches. */\nexport function matchAgentSignature(commandLine) {\n if (typeof commandLine !== 'string' || !commandLine) return null;\n for (const { signature, test } of SIGNATURES) {\n if (test(commandLine)) return signature;\n }\n return null;\n}\n\n/**\n * Pure selection. `processes` is an array of\n * `{ pid, ppid, creationMs, commandLine }`; returns `{ kills }` where each\n * kill is `{ pid, signature, commandLine }`, oldest-first, capped.\n */\nexport function selectLegacyOrphans({ processes, cutoffMs, protectedPids = new Set() }) {\n const byPid = new Map();\n for (const proc of processes) {\n if (Number.isInteger(proc?.pid) && proc.pid > 0) byPid.set(proc.pid, proc);\n }\n const kills = [];\n for (const proc of byPid.values()) {\n if (protectedPids.has(proc.pid)) continue;\n if (!(Number.isFinite(proc.creationMs) && proc.creationMs < cutoffMs)) continue;\n const signature = matchAgentSignature(proc.commandLine);\n if (!signature) continue;\n const parent = Number.isInteger(proc.ppid) && proc.ppid > 0 ? byPid.get(proc.ppid) : undefined;\n const parentDead = !parent || (Number.isFinite(parent.creationMs) && parent.creationMs > proc.creationMs);\n if (!parentDead) continue;\n kills.push({ pid: proc.pid, creationMs: proc.creationMs, signature, commandLine: proc.commandLine });\n }\n kills.sort((a, b) => a.creationMs - b.creationMs);\n return { kills: kills.slice(0, MAX_LEGACY_KILLS) };\n}\n\n/** One `ps -eo pid=,ppid=,etimes=,args=` line \u2192 process row (null on junk). */\nexport function parsePosixSweepLine(line, nowMs) {\n const match = /^\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(.+)$/u.exec(line ?? '');\n if (!match) return null;\n const pid = Number(match[1]);\n if (!Number.isInteger(pid) || pid <= 0) return null;\n return {\n pid,\n ppid: Number(match[2]),\n creationMs: nowMs - Number(match[3]) * 1000,\n commandLine: match[4],\n };\n}\n\n/**\n * Enumerate `{ pid, ppid, creationMs, commandLine }` for every visible\n * process. Windows via CIM (one compact JSON object per line so arbitrary\n * command-line content cannot break parsing; epoch via\n * DateTimeOffset.ToUnixTimeMilliseconds() \u2014 the manual UTC-offset form was\n * empirically \u22128h and silently disabled the recorded reaper before the same\n * guard was added there). Unenumerable rows are skipped (safe direction).\n */\nexport function listProcessesForSweep({ platform = process.platform, spawn = spawnSync, nowMs = Date.now(), env = process.env, warn = console.warn } = {}) {\n const rows = [];\n if (platform === 'win32') {\n const ps =\n \"Get-CimInstance Win32_Process | Where-Object { $_.CreationDate } | ForEach-Object { @{ p = $_.ProcessId; pp = $_.ParentProcessId; c = (([DateTimeOffset]$_.CreationDate.ToUniversalTime()).ToUnixTimeMilliseconds()); cl = [string]$_.CommandLine } | ConvertTo-Json -Compress }\";\n const result = spawn(windowsPowershellExe(env), ['-NoProfile', '-NonInteractive', '-Command', ps], {\n windowsHide: true,\n encoding: 'utf8',\n timeout: 30_000,\n maxBuffer: 64 * 1024 * 1024,\n });\n if (result.error || result.status !== 0) {\n // Failure must remain a NO-KILL sweep (safe direction) but never a silent\n // one: an empty enumeration is indistinguishable from \"no orphans\", so a\n // permanently broken shim would look healthy while processes accumulate.\n // Throwing (not returning []) makes runLegacyOrphanSweep report the\n // operator-triggered purge action as FAILED instead of \"0 scanned\".\n const cause = result.error ? result.error.message : `powershell exit ${result.status}`;\n warn(`[orphan-sweep] process enumeration failed (${cause}); sweeping nothing this cycle`);\n throw new Error(`process enumeration failed (${cause}); swept nothing`);\n }\n for (const line of String(result.stdout ?? '').split(/\\r?\\n/u)) {\n if (!line.trim()) continue;\n try {\n const parsed = JSON.parse(line);\n const pid = Number(parsed?.p);\n if (!Number.isInteger(pid) || pid <= 0) continue;\n rows.push({\n pid,\n ppid: Number(parsed.pp),\n creationMs: Number(parsed.c),\n commandLine: typeof parsed.cl === 'string' ? parsed.cl : '',\n });\n } catch {\n // one unparseable row must never abort the sweep enumeration\n }\n }\n return rows;\n }\n const result = spawn('ps', ['-eo', 'pid=,ppid=,etimes=,args='], { encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024 * 1024 });\n if (result.error || result.status !== 0) {\n const cause = result.error ? result.error.message : `ps exit ${result.status}`;\n warn(`[orphan-sweep] process enumeration failed (${cause}); sweeping nothing this cycle`);\n throw new Error(`process enumeration failed (${cause}); swept nothing`);\n }\n for (const line of String(result.stdout ?? '').split('\\n')) {\n const row = parsePosixSweepLine(line, nowMs);\n if (row) rows.push(row);\n }\n return rows;\n}\n\n/**\n * Execute the sweep. Never throws; returns\n * `{ ok, status, detail, killed: [{ pid, signature }] }` shaped for the\n * supervisor's action-completion contract. `detail` carries the evidence\n * summary that ends up on the AlgoHQ action record.\n */\nexport function runLegacyOrphanSweep({\n nowMs = Date.now(),\n protectedPids = [process.pid],\n listProcesses = listProcessesForSweep,\n killTree = killProcessTree,\n log = () => {},\n} = {}) {\n try {\n const processes = listProcesses({ nowMs });\n const { kills } = selectLegacyOrphans({\n processes,\n cutoffMs: nowMs - SWEEP_RECENCY_BUFFER_MS,\n protectedPids: new Set(protectedPids),\n });\n const killed = [];\n for (const kill of kills) {\n const done = killTree(kill.pid);\n log(`legacy-orphan-sweep ${done ? 'killed' : 'FAILED to kill'} pid=${kill.pid} sig=${kill.signature} cmd=${String(kill.commandLine).slice(0, 200)}`);\n if (done) killed.push({ pid: kill.pid, signature: kill.signature });\n }\n const failed = kills.length - killed.length;\n const detail = kills.length === 0\n ? `no orphaned agent processes matched the sweep criteria (${processes.length} scanned)`\n : `purged ${killed.length} of ${kills.length} orphaned agent process tree(s)${failed > 0 ? ` (${failed} kill(s) failed)` : ''}: ${killed.map((k) => `${k.pid}:${k.signature}`).join(', ').slice(0, 700)}`;\n return { ok: true, status: 0, detail, killed };\n } catch (error) {\n return { ok: false, status: 1, detail: `legacy sweep error: ${error instanceof Error ? error.message : String(error)}`.slice(0, 500), killed: [] };\n }\n}\n", "/**\n * Orphaned-agent process reaper.\n *\n * The runner spawns agent CLIs (claude/codex/\u2026) as child processes. When the\n * DAEMON itself restarts (crash, `update`/`reinstall` control, host reboot mid-\n * task), any still-running agent children are detached from the new daemon and\n * are never reclaimed \u2014 they leak RAM until the machine is rebooted. The\n * existing `terminal-process-cleanup` only kills the child the CURRENT process\n * still tracks; it deliberately never scans for unrelated processes.\n *\n * This module closes that gap SAFELY. Every spawned agent records its pid, its\n * spawning daemon instance id, and its spawn time under a per-instance registry\n * directory. On daemon startup the reaper considers only OTHER instances'\n * records and kills a process ONLY when ALL of these hold:\n *\n * 1. the recording daemon instance is provably DEAD (its recorded daemon pid\n * is not live, or its creation time no longer matches) \u2014 so a concurrent\n * live peer runner's agents are never touched;\n * 2. the agent pid is still live; AND\n * 3. the live process's OS creation time still matches the recorded spawn\n * time within tolerance \u2014 so a REUSED pid (now some innocent process)\n * is never killed.\n *\n * It never matches by process name and never touches a pid it did not itself\n * record. Decision logic is pure (`selectOrphanKills`) and fully unit-tested;\n * the OS shims (`listProcessCreationTimes`, `killProcessTree`) are injected.\n */\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nconst REGISTRY_ROOT_NAME = 'algohq-runner-agent-pids';\nconst DAEMON_RECORD = 'daemon.json';\n/** A reused pid is created long after the original; 30s covers spawn/clock skew. */\nexport const CREATION_MATCH_TOLERANCE_MS = 30_000;\n\nexport function registryRoot(tmp = os.tmpdir()) {\n return path.join(tmp, REGISTRY_ROOT_NAME);\n}\n\nfunction instanceDir(root, instanceId) {\n return path.join(root, String(instanceId).replace(/[^A-Za-z0-9_-]/g, ''));\n}\n\n/** Record this daemon instance so peers can tell it is alive vs. orphaned. */\nexport function registerDaemonInstance({\n root = registryRoot(),\n instanceId,\n daemonPid = process.pid,\n daemonStartedAtMs = Date.now(),\n} = {}) {\n if (!instanceId) return null;\n const dir = instanceDir(root, instanceId);\n mkdirSync(dir, { recursive: true });\n const file = path.join(dir, DAEMON_RECORD);\n writeFileSync(file, JSON.stringify({ daemonPid, daemonStartedAtMs, instanceId }), {\n encoding: 'utf8',\n mode: 0o600,\n });\n return file;\n}\n\n/** Record a spawned agent's pid under its daemon instance. Never throws. */\nexport function recordAgentPid({\n root = registryRoot(),\n instanceId = process.env.VO_RUNNER_INSTANCE_ID,\n pid,\n agentId = '',\n startedAtMs = Date.now(),\n} = {}) {\n if (!instanceId || !Number.isInteger(pid) || pid <= 0) return false;\n try {\n const dir = instanceDir(root, instanceId);\n mkdirSync(dir, { recursive: true });\n writeFileSync(\n path.join(dir, `${pid}.json`),\n JSON.stringify({ pid, agentId, startedAtMs, instanceId }),\n { encoding: 'utf8', mode: 0o600 },\n );\n return true;\n } catch {\n return false;\n }\n}\n\n/** Drop an agent record once its own process tree has been reaped. Never throws. */\nexport function unrecordAgentPid({\n root = registryRoot(),\n instanceId = process.env.VO_RUNNER_INSTANCE_ID,\n pid,\n} = {}) {\n if (!instanceId || !Number.isInteger(pid)) return false;\n try {\n rmSync(path.join(instanceDir(root, instanceId), `${pid}.json`), { force: true });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * One-call daemon startup hook: publishes this instance id (so in-process\n * spawns can self-record), records the daemon, and reaps orphaned agent trees\n * left by dead prior instances. Synchronous and swallow-safe \u2014 never blocks the\n * runner from coming up.\n */\nexport function bootstrapOrphanReaper({ instanceId, log = () => {} } = {}) {\n if (!instanceId) return { killed: 0, prunedDirs: 0 };\n process.env.VO_RUNNER_INSTANCE_ID = instanceId;\n try {\n registerDaemonInstance({ instanceId });\n } catch {\n /* best effort \u2014 reap still runs */\n }\n return reapOrphanedAgents({ currentInstanceId: instanceId, log });\n}\n\n/** Read every instance's records from disk into the shape selectOrphanKills wants. */\nexport function readRegistry({ root = registryRoot(), currentInstanceId } = {}) {\n const instances = [];\n if (!existsSync(root)) return instances;\n let dirents;\n try {\n dirents = readdirSync(root, { withFileTypes: true });\n } catch {\n return instances;\n }\n for (const dirent of dirents) {\n if (!dirent.isDirectory()) continue;\n if (currentInstanceId && dirent.name === instanceDirName(currentInstanceId)) continue;\n const dir = path.join(root, dirent.name);\n let daemon = null;\n const agents = [];\n let files;\n try {\n files = readdirSync(dir);\n } catch {\n continue;\n }\n for (const name of files) {\n let parsed;\n try {\n parsed = JSON.parse(readFileSync(path.join(dir, name), 'utf8'));\n } catch {\n continue;\n }\n if (name === DAEMON_RECORD) {\n if (Number.isInteger(parsed?.daemonPid)) {\n daemon = { pid: parsed.daemonPid, startedAtMs: Number(parsed.daemonStartedAtMs) || 0 };\n }\n } else if (Number.isInteger(parsed?.pid)) {\n agents.push({ pid: parsed.pid, agentId: String(parsed.agentId || ''), startedAtMs: Number(parsed.startedAtMs) || 0 });\n }\n }\n instances.push({ instanceId: dirent.name, dir, daemon, agents });\n }\n return instances;\n}\n\nfunction instanceDirName(instanceId) {\n return String(instanceId).replace(/[^A-Za-z0-9_-]/g, '');\n}\n\nfunction creationMatches(live, recordedStartedAtMs, toleranceMs) {\n if (!live || !Number.isFinite(live.creationMs)) return false;\n if (!Number.isFinite(recordedStartedAtMs) || recordedStartedAtMs <= 0) return false;\n return Math.abs(live.creationMs - recordedStartedAtMs) <= toleranceMs;\n}\n\n/**\n * PURE decision core. Given the on-disk registry (other instances only) and a\n * map of live pid \u2192 { creationMs }, decide which pids to kill and which\n * instance dirs to prune.\n *\n * - An instance whose daemon record is still live (pid alive + creation match)\n * is a running PEER: skip it entirely (no kills, no prune).\n * - Otherwise the instance is dead: kill each recorded agent that is still live\n * AND whose creation time matches (guards pid reuse), then prune its dir.\n */\nexport function selectOrphanKills({ instances = [], liveProcesses = new Map(), toleranceMs = CREATION_MATCH_TOLERANCE_MS } = {}) {\n const kills = [];\n const pruneDirs = [];\n for (const instance of instances) {\n // Require a PRESENT daemon record before killing anything. Without it we\n // cannot distinguish a truly-crashed instance from a peer that just created\n // its dir and has not written daemon.json yet, so we conservatively prune\n // the stale/malformed dir but never kill. (registerDaemonInstance writes\n // daemon.json before any agent is spawned, so a real instance with agent\n // records always has one.)\n if (!instance.daemon) {\n if (instance.dir) pruneDirs.push(instance.dir);\n continue;\n }\n const daemonLive =\n liveProcesses.has(instance.daemon.pid) &&\n creationMatches(liveProcesses.get(instance.daemon.pid), instance.daemon.startedAtMs, toleranceMs);\n if (daemonLive) continue; // live peer runner \u2014 never touch its agents\n for (const agent of instance.agents) {\n const live = liveProcesses.get(agent.pid);\n if (live && creationMatches(live, agent.startedAtMs, toleranceMs)) {\n kills.push({ pid: agent.pid, agentId: agent.agentId, instanceId: instance.instanceId });\n }\n }\n if (instance.dir) pruneDirs.push(instance.dir);\n }\n return { kills, pruneDirs };\n}\n\nfunction windowsSystemRoot(env = process.env) {\n return env.SystemRoot || env.WINDIR || 'C:\\\\Windows';\n}\n\n/**\n * Absolute Windows PowerShell path. Never resolve `powershell` from PATH: the\n * reaper runs with the daemon's privileges, so a PATH-planted powershell.exe\n * would receive every process command line on the host. Same resolution as\n * runner-bootstrap/windows-bound-process-termination.mjs.\n */\nexport function windowsPowershellExe(env = process.env) {\n return path.join(windowsSystemRoot(env), 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');\n}\n\n/** Windows: map every process to its creation time in epoch ms via CIM. */\nexport function listProcessCreationTimes({ platform = process.platform, spawn = spawnSync, env = process.env, warn = console.warn } = {}) {\n const map = new Map();\n if (platform === 'win32') {\n // Epoch conversion via DateTimeOffset.ToUnixTimeMilliseconds() \u2014 the manual\n // `(CreationDate - Get-Date '1970-01-01Z')` form is off by the local UTC\n // offset (empirically \u22128h on a PST host), which would push every creation\n // time outside the match window and silently disable the reaper.\n const ps =\n \"Get-CimInstance Win32_Process | ForEach-Object { '{0} {1}' -f $_.ProcessId, (([DateTimeOffset]$_.CreationDate.ToUniversalTime()).ToUnixTimeMilliseconds()) }\";\n const result = spawn(windowsPowershellExe(env), ['-NoProfile', '-NonInteractive', '-Command', ps], {\n windowsHide: true,\n encoding: 'utf8',\n timeout: 20_000,\n maxBuffer: 32 * 1024 * 1024,\n });\n if (result.error || result.status !== 0 || typeof result.stdout !== 'string') {\n // An enumeration failure must stay a NO-KILL cycle (safe direction), but\n // never a silent one \u2014 a permanently failing shim reads as \"no orphans\"\n // and the fleet leaks agent processes until reboot.\n warn(`[orphan-reaper] process enumeration failed (${result.error ? result.error.message : `powershell exit ${result.status}`}); reaping nothing this cycle`);\n return map;\n }\n for (const line of result.stdout.split(/\\r?\\n/)) {\n const m = line.trim().match(/^(\\d+)\\s+(-?\\d+)$/);\n if (m) map.set(Number(m[1]), { creationMs: Number(m[2]) });\n }\n return map;\n }\n // POSIX: ps lstart \u2192 epoch ms (macOS/Linux runner). Windows is the primary\n // target and is verified end-to-end; this branch is validated via the pure\n // parsePosixPsLine() unit tests.\n const result = spawn('ps', ['-eo', 'pid=,lstart='], { encoding: 'utf8', timeout: 20_000, maxBuffer: 32 * 1024 * 1024 });\n if (result.error || result.status !== 0 || typeof result.stdout !== 'string') {\n warn(`[orphan-reaper] process enumeration failed (${result.error ? result.error.message : `ps exit ${result.status}`}); reaping nothing this cycle`);\n return map;\n }\n for (const line of result.stdout.split(/\\r?\\n/)) {\n const parsed = parsePosixPsLine(line);\n if (parsed) map.set(parsed.pid, { creationMs: parsed.creationMs });\n }\n return map;\n}\n\n/**\n * Parse one `ps -eo pid=,lstart=` line into { pid, creationMs } or null.\n * Handles padded pids, the single-digit-day double space (\"Mon Jan 5 \u2026\"), and\n * unparseable lines (\u2192 null, so the caller skips them \u2014 the safe direction).\n */\nexport function parsePosixPsLine(line) {\n const trimmed = String(line ?? '').trim();\n const sp = trimmed.indexOf(' ');\n if (sp <= 0) return null;\n const pid = Number(trimmed.slice(0, sp));\n const when = Date.parse(trimmed.slice(sp + 1).trim());\n if (!Number.isInteger(pid) || pid <= 0 || !Number.isFinite(when)) return null;\n return { pid, creationMs: when };\n}\n\n/** Kill an exact pid's whole tree. Windows taskkill /T /F, else SIGKILL by pgid. */\nexport function killProcessTree(pid, { platform = process.platform, spawn = spawnSync, env = process.env } = {}) {\n if (!Number.isInteger(pid) || pid <= 0) return false;\n if (platform === 'win32') {\n // Absolute path for the same reason as windowsPowershellExe(): a PATH-planted\n // taskkill.exe would execute with daemon privileges and could silently no-op\n // every kill while the sweep logs success.\n const taskkill = path.join(windowsSystemRoot(env), 'System32', 'taskkill.exe');\n const r = spawn(taskkill, ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore', timeout: 15_000 });\n return !r.error && r.status === 0;\n }\n try {\n process.kill(-pid, 'SIGKILL');\n return true;\n } catch {\n try {\n process.kill(pid, 'SIGKILL');\n return true;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * EFFECTFUL entry point: run at daemon startup. Reaps orphaned agent trees from\n * dead prior instances and prunes their registry dirs. Never throws \u2014 a reaper\n * failure must not block the runner from coming up.\n */\nexport function reapOrphanedAgents({\n root = registryRoot(),\n currentInstanceId = process.env.VO_RUNNER_INSTANCE_ID,\n toleranceMs = CREATION_MATCH_TOLERANCE_MS,\n listProcesses = listProcessCreationTimes,\n killTree = killProcessTree,\n log = () => {},\n} = {}) {\n try {\n const instances = readRegistry({ root, currentInstanceId });\n if (instances.length === 0) return { killed: 0, prunedDirs: 0 };\n const liveProcesses = listProcesses();\n const { kills, pruneDirs } = selectOrphanKills({ instances, liveProcesses, toleranceMs });\n let killed = 0;\n for (const kill of kills) {\n if (killTree(kill.pid)) {\n killed += 1;\n log(`reaped orphaned agent pid ${kill.pid}${kill.agentId ? ` (${kill.agentId})` : ''} from dead instance ${kill.instanceId}`);\n }\n }\n let prunedDirs = 0;\n for (const dir of pruneDirs) {\n try {\n rmSync(dir, { recursive: true, force: true });\n prunedDirs += 1;\n } catch {\n /* leave it; next startup retries */\n }\n }\n if (killed > 0 || prunedDirs > 0) log(`orphan reap: killed ${killed} agent tree(s), pruned ${prunedDirs} dead instance record(s)`);\n return { killed, prunedDirs };\n } catch (error) {\n log(`orphan reap skipped: ${error instanceof Error ? error.message : String(error)}`);\n return { killed: 0, prunedDirs: 0 };\n }\n}\n", "import {\n acknowledgeActivationFailure,\n attestCurrentSupervisor,\n finalizeActivation,\n readActivation,\n recordActivationRetry,\n rollbackActivation,\n validateSlot,\n} from './bundled-runtime-store.mjs';\n\nconst MAX_ACK_ATTEMPTS = 3;\nconst delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nexport async function waitForAuthoritativeRunnerHeartbeat({\n client,\n runnerId,\n operatorId,\n runnerInstanceId,\n excludeRunnerInstanceId,\n daemonVersion,\n supervisorIdentity,\n timeoutMs = 60_000,\n pollMs = 1_000,\n}) {\n if (!runnerInstanceId && !excludeRunnerInstanceId) throw new Error('runner instance identity proof unavailable');\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n try {\n const runners = await client.getRunnerStatus({ ...(operatorId ? { operatorId } : {}) });\n const runner = runners.find((item) => item?.runner_id === runnerId\n && item.status === 'online'\n && (runnerInstanceId\n ? item.runner_meta?.runner_instance_id === runnerInstanceId\n : Boolean(item.runner_meta?.runner_instance_id)\n && item.runner_meta.runner_instance_id !== excludeRunnerInstanceId)\n && item.runner_meta?.daemon_version === daemonVersion\n && item.runner_meta?.supervisor_instance_id === supervisorIdentity.supervisorInstanceId\n && item.runner_meta?.supervisor_version === supervisorIdentity.supervisorVersion\n && supervisorIdentity.capabilities.every((value) => item.runner_meta?.supervisor_capabilities?.includes(value))\n && Array.isArray(item.runner_meta?.available_agents)\n // The default agent must be INSTALLED for the activated runtime to be the\n // one that will serve. Whether it is AUTHENTICATED is a serving gate the\n // heartbeat already reports (available_agents[].authenticated) and the\n // plane already dispatches on; it is not part of the runtime's identity.\n // Requiring it here made an expired or never-done agent login fail every\n // activation closed: the child was stopped after 60 s, the supervisor\n // degraded, and the host went silent until a human restarted the app\n // (FintonLaptop, 2026-09-04: claude installed, authenticated:false).\n && item.runner_meta.available_agents.some((agent) => agent.agent === item.runner_meta.default_agent\n && agent.installed === true));\n if (runner) return runner;\n } catch { /* bounded retry */ }\n await delay(pollMs);\n }\n throw new Error('authoritative child heartbeat attestation timed out');\n}\n\n/**\n * Complete a slot handoff only from the activated package and logical Tauri\n * supervisor lease. Local path/version/hash and child readiness are proven\n * before a cloud heartbeat or terminal action acknowledgement is emitted.\n */\nexport async function finishPendingActivation({\n client,\n child,\n runtimeRoot,\n operatorId,\n runnerId,\n selfPath,\n packageVersion,\n supervisorIdentity,\n waitForLocalRunner,\n isReadinessDeferred = () => false,\n localStatus,\n waitForCloudRunner = waitForAuthoritativeRunnerHeartbeat,\n cloudTimeoutMs,\n cloudPollMs,\n stopChild,\n launchPreviousChild,\n log = () => {},\n}) {\n const pointer = runtimeRoot ? readActivation(runtimeRoot) : null;\n if (!pointer?.pending) return true;\n const runnerIdForAction = pointer.pending.runner_id || runnerId;\n const operatorIdForAction = pointer.pending.operator_id || operatorId;\n if (pointer.pending.terminal_status === 'failed') {\n try {\n await client.completeRunnerControl(pointer.pending.action_id, {\n runnerId: runnerIdForAction,\n ...(operatorIdForAction ? { operatorId: operatorIdForAction } : {}),\n ...supervisorIdentity,\n status: 'failed',\n detail: pointer.pending.terminal_detail,\n });\n acknowledgeActivationFailure(runtimeRoot, pointer);\n return true;\n } catch (error) {\n log(`activation failure acknowledgement remains pending: ${error instanceof Error ? error.message : String(error)}`);\n await stopChild(child);\n return false;\n }\n }\n let attestation;\n try {\n attestation = attestCurrentSupervisor({ runtimeRoot, selfPath, version: packageVersion });\n if (!attestation.ok) throw new Error(attestation.detail);\n if (!(await waitForLocalRunner(child))) {\n // A supervisor-authenticated exit-75 readiness embargo is neither a bad\n // runtime nor an attestation failure. Preserve the active/pending pointer\n // exactly; the supervisor will re-probe and retry this same slot later.\n if (isReadinessDeferred(child)) return false;\n throw new Error('activated runner did not become locally ready');\n }\n } catch (error) {\n let detail = `activation attestation failed: ${error instanceof Error ? error.message : String(error)}`.slice(0, 400);\n let rolledBack = null;\n try {\n rolledBack = rollbackActivation(runtimeRoot, pointer, detail);\n } catch (rollbackError) {\n detail = `${detail}; rollback pending: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`.slice(0, 400);\n }\n try {\n await client.completeRunnerControl(pointer.pending.action_id, {\n runnerId: runnerIdForAction,\n ...(operatorIdForAction ? { operatorId: operatorIdForAction } : {}),\n ...supervisorIdentity,\n status: 'failed',\n detail,\n });\n if (rolledBack) acknowledgeActivationFailure(runtimeRoot, rolledBack);\n } catch {\n // current.json retains the terminal acknowledgement obligation.\n } finally {\n await stopChild(child);\n }\n return false;\n }\n\n let activatedRunnerInstanceId = null;\n try {\n const status = await localStatus();\n activatedRunnerInstanceId = status?.runnerInstanceId || null;\n await waitForCloudRunner({\n client,\n runnerId: runnerIdForAction,\n operatorId: operatorIdForAction,\n runnerInstanceId: status?.runnerInstanceId,\n daemonVersion: `vo-mcp/${attestation.active.version}`,\n supervisorIdentity,\n timeoutMs: cloudTimeoutMs,\n pollMs: cloudPollMs,\n });\n await client.completeRunnerControl(pointer.pending.action_id, {\n runnerId: runnerIdForAction,\n ...(operatorIdForAction ? { operatorId: operatorIdForAction } : {}),\n ...supervisorIdentity,\n status: 'succeeded',\n detail: `attested new supervisor ${attestation.active.version} ${attestation.active.integrity}`,\n });\n finalizeActivation(runtimeRoot, attestation.pointer);\n return true;\n } catch (error) {\n const failure = `activation acknowledgement failed: ${error instanceof Error ? error.message : String(error)}`.slice(0, 400);\n let retry;\n try { retry = recordActivationRetry(runtimeRoot, attestation.pointer, failure); }\n catch (retryError) {\n log(`activation retry could not be recorded: ${retryError instanceof Error ? retryError.message : String(retryError)}`);\n await stopChild(child);\n return false;\n }\n if (retry.pending.ack_attempts < MAX_ACK_ATTEMPTS) {\n log(`activation acknowledgement pending (${retry.pending.ack_attempts}/${MAX_ACK_ATTEMPTS})`);\n await stopChild(child);\n return false;\n }\n\n const previous = validateSlot(runtimeRoot, retry.previous);\n let detail = `${failure}; retry limit reached; previous runtime restored`.slice(0, 400);\n let rollbackChild = null;\n let rolledBack = null;\n try {\n if (!previous.ok) throw new Error(`previous runtime invalid: ${previous.detail}`, { cause: error });\n rolledBack = rollbackActivation(runtimeRoot, retry, detail);\n await stopChild(child);\n rollbackChild = launchPreviousChild(previous.paths.entry);\n if (!(await waitForLocalRunner(rollbackChild))) throw new Error('previous runner did not become locally ready', { cause: error });\n const status = await localStatus();\n await waitForCloudRunner({\n client,\n runnerId: runnerIdForAction,\n operatorId: operatorIdForAction,\n runnerInstanceId: status?.runnerInstanceId,\n excludeRunnerInstanceId: status?.runnerInstanceId ? undefined : activatedRunnerInstanceId,\n daemonVersion: `vo-mcp/${retry.previous.version}`,\n supervisorIdentity,\n timeoutMs: cloudTimeoutMs,\n pollMs: cloudPollMs,\n });\n } catch (rollbackError) {\n detail = `${detail}; rollback proof failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`.slice(0, 400);\n }\n try {\n await client.completeRunnerControl(retry.pending.action_id, {\n runnerId: runnerIdForAction,\n ...(operatorIdForAction ? { operatorId: operatorIdForAction } : {}),\n ...supervisorIdentity,\n status: 'failed',\n detail,\n });\n if (rolledBack) acknowledgeActivationFailure(runtimeRoot, rolledBack);\n } catch { /* current.json retains the terminal acknowledgement obligation */ }\n if (rollbackChild) await stopChild(rollbackChild);\n else await stopChild(child);\n return false;\n }\n}\n\nexport const __test = { MAX_ACK_ATTEMPTS };\n", "/**\n * Resolve the runner child entry on EVERY (re)spawn instead of once at module\n * load.\n *\n * The supervisor used to compute `join(dirname(selfPath), 'runner-cli.js')` at\n * module scope and reuse that single path for every child it ever spawned. A\n * staged runtime slot could therefore be activated (current.json rewritten,\n * child restarted) and the host would keep running the OLD daemon until the\n * whole desktop app was restarted \u2014 which nothing forces. That is the same\n * silently-inert-update class as the 2026-08-06 slot-cache-poisoning incident:\n * the update reports success, the bytes on disk are new, and the process\n * serving work is unchanged.\n *\n * Rules encoded here:\n * - Re-read the activation pointer on every call; never cache.\n * - Fall back to the bundled self-relative entry whenever there is no slot,\n * the pointer is unreadable, an activation is still mid-transaction, or the\n * slot fails full hash validation. Fail closed, never fail open.\n * - NEVER downgrade: an active slot older than (or equal to) the bundled\n * version keeps the bundled path. Mirrors the strictly-newer compare in\n * cloud-run/vo-control-plane/src/routes/runner-auto-update.ts.\n */\nimport { readActivation, validateSlot } from './bundled-runtime-store.mjs';\n\n/** Tolerates an optional \"name/\" prefix so `vo-mcp/0.2.0` parses too. */\nconst VERSION_RE = /^(?:[\\w.-]+\\/)?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?$/u;\n\nexport function parseRuntimeVersion(value) {\n if (typeof value !== 'string') return null;\n const match = VERSION_RE.exec(value.trim());\n if (!match) return null;\n const prerelease = match[4]\n ? match[4].split('.').map((part) => (/^\\d+$/u.test(part) ? Number(part) : part))\n : null;\n return { release: [Number(match[1]), Number(match[2]), Number(match[3])], prerelease };\n}\n\n/** semver-style compare: -1 when a < b, 0 when equal, 1 when a > b. */\nexport function compareRuntimeVersions(a, b) {\n for (let i = 0; i < 3; i += 1) {\n const av = a.release[i] ?? 0;\n const bv = b.release[i] ?? 0;\n if (av !== bv) return av < bv ? -1 : 1;\n }\n if (!a.prerelease && !b.prerelease) return 0;\n if (!a.prerelease) return 1; // release > any prerelease of the same core\n if (!b.prerelease) return -1;\n const len = Math.max(a.prerelease.length, b.prerelease.length);\n for (let i = 0; i < len; i += 1) {\n const av = a.prerelease[i];\n const bv = b.prerelease[i];\n if (av === undefined) return -1; // shorter prerelease sorts first\n if (bv === undefined) return 1;\n if (av === bv) continue;\n const aNum = typeof av === 'number';\n const bNum = typeof bv === 'number';\n if (aNum && bNum) return av < bv ? -1 : 1;\n if (aNum !== bNum) return aNum ? -1 : 1; // numeric identifiers sort first\n return String(av) < String(bv) ? -1 : 1;\n }\n return 0;\n}\n\n/**\n * @returns {{ args: string[], entry: string, source: 'bundled'|'active-slot',\n * version: string, descriptor: string, detail: string }}\n * `descriptor` is a stable identity for change detection/logging.\n */\nexport function resolveSupervisorChildEntry({\n runtimeRoot,\n bundledEntry,\n bundledVersion,\n readPointer = readActivation,\n validate = validateSlot,\n}) {\n const bundled = (detail) => ({\n // The bundled entry is `dist/runner-cli.js`, which IS the daemon and takes\n // no subcommand. The slot entry is `bin/vo-mcp`, the multiplexed CLI, which\n // needs the `runner` subcommand \u2014 the same argv the proven rollback path\n // (`launchPreviousChild`) uses.\n args: [bundledEntry],\n entry: bundledEntry,\n source: 'bundled',\n version: String(bundledVersion || 'unknown'),\n descriptor: `bundled ${bundledVersion || 'unknown'} ${bundledEntry}`,\n detail,\n });\n\n if (!runtimeRoot) return bundled('no runtime root');\n\n let pointer;\n try {\n pointer = readPointer(runtimeRoot);\n } catch (error) {\n return bundled(`activation pointer unreadable: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (!pointer?.active) return bundled('no activated runtime slot');\n // Mid-transaction. finishPendingActivation() owns that handoff (it attests\n // from the NEW supervisor process); adopting the slot here would run a new\n // daemon under an un-attested old supervisor.\n if (pointer.pending) return bundled('runtime activation still pending');\n\n const activeVersion = parseRuntimeVersion(pointer.active.version);\n const currentVersion = parseRuntimeVersion(bundledVersion);\n // An unparseable version on either side means the never-downgrade rule cannot\n // be PROVEN, so it is enforced by refusing the slot.\n if (!activeVersion) return bundled(`active slot version unparseable: ${String(pointer.active.version)}`);\n if (!currentVersion) return bundled(`bundled version unparseable: ${String(bundledVersion)}`);\n if (compareRuntimeVersions(activeVersion, currentVersion) <= 0) {\n return bundled(`active slot ${pointer.active.version} is not newer than bundled ${bundledVersion}`);\n }\n\n let validated;\n try {\n validated = validate(runtimeRoot, pointer.active);\n } catch (error) {\n return bundled(`slot validation threw: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (!validated?.ok) return bundled(`active slot invalid: ${validated?.detail || 'unknown'}`);\n\n const entry = validated.paths.entry;\n return {\n args: [entry, 'runner'],\n entry,\n source: 'active-slot',\n version: pointer.active.version,\n descriptor: `active-slot ${pointer.active.version} ${entry}`,\n detail: `activated slot ${pointer.active.slot_id}`,\n };\n}\n", "/**\n * Drain in-flight code tasks BEFORE a staged update restarts the runner child.\n *\n * Incident 2026-08-30 ~08:0x: both fleet runners (FintonLaptop, JacksPC)\n * restarted near-simultaneously on a staged-update delivery and killed the\n * in-flight continuations of two tasks (7f98ab24 at preparing_worktree,\n * 2c7ea978 at agent_working). Both went status=failed with NO error_message on\n * the plane, and both runners heartbeated fresh seconds later \u2014 so the plane\n * recorded a silent death with no cause. Cost: two $2 recovery resumes.\n *\n * The pre-existing guard in runner-supervisor.mjs was a SINGLE check that\n * failed the control action outright, and it read\n * `beforeStop && activeTasks > 0` \u2014 an unreadable `/status` (null) fell\n * through to the restart, which is exactly the fail-open shape that kills work.\n *\n * What this module changes, and nothing else (the two-track staging/delivery\n * mechanism is untouched \u2014 this gates only the APPLICATION of the restart):\n * - update/reinstall actions WAIT for the child to go idle, re-checking on an\n * interval, instead of failing the action on the first busy check.\n * - An unreadable `/status` from a RUNNING child counts as busy, not idle.\n * A child that is not running has nothing to drain and proceeds at once, so\n * the supervisor's only remote repair channel can never be self-blocked.\n * - The wait is hard-capped (default 45 min). At the cap the restart proceeds,\n * but every in-flight task is first marked terminal on the plane with a\n * message that NAMES the update restart. Never kill silently.\n * - Non-update control actions (repair/maintenance/purge) keep the legacy\n * single-check defer, including its legacy fail-open on an unreadable\n * status: blocking remote repair for up to 45 minutes behind an\n * unresponsive status port would be a worse failure than the one fixed here.\n *\n * Task ids come from the runner's OWN in-flight registry, surfaced on\n * `GET /status` as `activeTaskIds` (scripts/virtual-office/code-runner-daemon.mjs\n * \u2192 control-server.mjs). The same status snapshot carries `runnerId` /\n * `runnerInstanceId`, which the terminal patch MUST echo: the plane rejects a\n * protocol-v2 progress patch that omits them\n * (cloud-run/vo-control-plane/src/storage/code-task-progress-merge.ts:63).\n */\n\nexport const DEFAULT_DRAIN_CAP_MS = 45 * 60 * 1000;\nexport const DEFAULT_DRAIN_CHECK_MS = 30_000;\nconst MAX_DRAIN_CAP_MS = 6 * 60 * 60 * 1000;\nconst MIN_DRAIN_CHECK_MS = 1_000;\nconst MAX_DRAIN_CHECK_MS = 5 * 60 * 1000;\n\n/** Terminal message + result stamped on tasks killed by a capped drain. */\nexport const UPDATE_RESTART_ERROR_MESSAGE = 'runner update restart after drain timeout';\nexport const UPDATE_RESTART_RESULT = 'runner_update_restart';\n\nconst sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nfunction positiveNumber(raw) {\n if (raw === undefined || raw === null || String(raw).trim() === '') return null;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0 ? value : null;\n}\n\n/**\n * `VO_RUNNER_UPDATE_DRAIN_CAP_MIN` (minutes) is the operator-facing knob;\n * `VO_RUNNER_UPDATE_DRAIN_CAP_MS` wins when both are set (tests use it).\n * 0 disables draining entirely \u2014 the restart proceeds immediately, but the\n * cap path still marks in-flight tasks, so nothing dies unexplained.\n */\nexport function resolveDrainCapMs(env = {}) {\n const ms = positiveNumber(env.VO_RUNNER_UPDATE_DRAIN_CAP_MS);\n if (ms !== null) return Math.min(ms, MAX_DRAIN_CAP_MS);\n const minutes = positiveNumber(env.VO_RUNNER_UPDATE_DRAIN_CAP_MIN);\n if (minutes !== null) return Math.min(minutes * 60_000, MAX_DRAIN_CAP_MS);\n return DEFAULT_DRAIN_CAP_MS;\n}\n\nexport function resolveDrainCheckMs(env = {}) {\n const ms = positiveNumber(env.VO_RUNNER_UPDATE_DRAIN_CHECK_MS);\n if (ms === null) return DEFAULT_DRAIN_CHECK_MS;\n return Math.min(Math.max(ms, MIN_DRAIN_CHECK_MS), MAX_DRAIN_CHECK_MS);\n}\n\n/**\n * Normalize one `/status` snapshot into the drain view.\n * `known:false` means \"a child is running but did not answer\" \u2014 busy for the\n * update path, idle for the legacy path (see the module header).\n * @returns {{ count: number, ids: string[], known: boolean,\n * runnerId: string|null, runnerInstanceId: string|null }}\n */\nexport function readActiveTasks(status, { childRunning = true } = {}) {\n if (!childRunning) {\n return { count: 0, ids: [], known: true, runnerId: null, runnerInstanceId: null };\n }\n if (!status || status.ok === false) {\n return { count: 0, ids: [], known: false, runnerId: null, runnerInstanceId: null };\n }\n const ids = Array.isArray(status.activeTaskIds)\n ? status.activeTaskIds.map((id) => String(id)).filter(Boolean)\n : [];\n const reported = Number(status.activeTasks);\n const count = Number.isFinite(reported) && reported >= 0 ? reported : ids.length;\n return {\n count: Math.max(count, ids.length),\n ids,\n known: true,\n runnerId: status.runnerId ? String(status.runnerId) : null,\n runnerInstanceId: status.runnerInstanceId ? String(status.runnerInstanceId) : null,\n };\n}\n\n/**\n * Pure one-iteration decision.\n * @returns {{ action: 'proceed'|'wait'|'cap', busy: number|'unknown' }}\n */\nexport function decideDrainStep({ active, elapsedMs, capMs }) {\n const busy = active.known ? active.count : 'unknown';\n if (active.known && active.count === 0) return { action: 'proceed', busy };\n if (elapsedMs >= capMs) return { action: 'cap', busy };\n return { action: 'wait', busy };\n}\n\nfunction describeBusy(active) {\n if (!active.known) return 'status unreadable from a running child (assumed busy)';\n const ids = active.ids.length > 0 ? ` [${active.ids.join(', ')}]` : ' [ids unavailable]';\n return `${active.count} active task(s)${ids}`;\n}\n\nasync function markCappedTasks({ active, failInFlightTask, log }) {\n if (active.ids.length === 0) {\n if (active.count > 0 || !active.known) {\n log(`update drain cap reached with ${describeBusy(active)} \u2014 cannot annotate tasks the runner did not name`);\n }\n return [];\n }\n const marked = [];\n for (const taskId of active.ids) {\n try {\n await failInFlightTask(taskId, {\n message: UPDATE_RESTART_ERROR_MESSAGE,\n result: UPDATE_RESTART_RESULT,\n runnerId: active.runnerId,\n runnerInstanceId: active.runnerInstanceId,\n });\n marked.push(taskId);\n } catch (error) {\n log(`could not mark task ${taskId} before update restart: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return marked;\n}\n\n/**\n * Gate the application of a staged-update restart on the runner going idle.\n *\n * @param {object} options\n * @param {() => Promise<object|null>} options.readStatus local `GET /status`\n * @param {() => boolean} options.isChildRunning live child liveness\n * @param {(taskId: string, patch: object) => Promise<unknown>} options.failInFlightTask\n * @param {boolean} options.drainable true only for update/reinstall actions\n * @param {object} [options.env] cap/interval knobs\n * @param {() => number} [options.now] injected clock (tests)\n * @param {(ms: number) => Promise<void>} [options.sleep] injected sleep (tests)\n * @param {(message: string) => void} [options.log]\n * @returns {Promise<{ proceed: boolean, detail: string, capped: boolean,\n * waitedMs: number, checks: number, markedTaskIds: string[] }>}\n */\nexport async function awaitRunnerUpdateDrain({\n readStatus,\n isChildRunning = () => true,\n failInFlightTask = async () => {},\n drainable = false,\n env = {},\n now = Date.now,\n sleep = sleepMs,\n log = () => {},\n} = {}) {\n const capMs = resolveDrainCapMs(env);\n const checkMs = resolveDrainCheckMs(env);\n const startedAt = now();\n let checks = 0;\n let lastReported = null;\n\n const snapshot = async () => {\n checks += 1;\n const childRunning = Boolean(isChildRunning());\n let status;\n try {\n status = await readStatus();\n } catch {\n status = null;\n }\n return readActiveTasks(status, { childRunning });\n };\n\n // Legacy single-check defer for non-update actions. Unchanged on purpose:\n // an unreadable status still proceeds so remote repair is never self-blocked.\n if (!drainable) {\n const active = await snapshot();\n if (active.known && active.count > 0) {\n return {\n proceed: false,\n detail: `deferred safely: ${active.count} active task(s); retry when the runner is idle`,\n capped: false,\n waitedMs: 0,\n checks,\n markedTaskIds: [],\n };\n }\n return { proceed: true, detail: 'runner idle', capped: false, waitedMs: 0, checks, markedTaskIds: [] };\n }\n\n for (;;) {\n const active = await snapshot();\n const elapsedMs = now() - startedAt;\n const step = decideDrainStep({ active, elapsedMs, capMs });\n\n if (step.action === 'proceed') {\n if (lastReported !== null) {\n log(`update drain complete after ${Math.round(elapsedMs / 1000)}s \u2014 runner idle, applying staged update restart`);\n }\n return { proceed: true, detail: 'runner idle', capped: false, waitedMs: elapsedMs, checks, markedTaskIds: [] };\n }\n\n if (step.action === 'cap') {\n log(`update drain cap reached after ${Math.round(elapsedMs / 1000)}s (cap ${Math.round(capMs / 1000)}s) \u2014 ${describeBusy(active)}; marking task(s) before restart`);\n const markedTaskIds = await markCappedTasks({ active, failInFlightTask, log });\n return {\n proceed: true,\n capped: true,\n detail: `update restart applied after drain cap; marked ${markedTaskIds.length} task(s) as \"${UPDATE_RESTART_ERROR_MESSAGE}\"`,\n waitedMs: elapsedMs,\n checks,\n markedTaskIds,\n };\n }\n\n // Log the first deferral and every real change, not every poll: a 45-minute\n // cap at a 30s interval would otherwise emit ~90 identical lines.\n const fingerprint = `${step.busy}:${active.ids.join(',')}`;\n if (fingerprint !== lastReported) {\n lastReported = fingerprint;\n log(`deferring staged update restart \u2014 ${describeBusy(active)}; re-checking every ${Math.round(checkMs / 1000)}s until idle (cap ${Math.round(capMs / 1000)}s)`);\n }\n await sleep(Math.max(1, Math.min(checkMs, capMs - elapsedMs)));\n }\n}\n", "import { hostname as systemHostname } from 'node:os';\nimport {\n pairedOperatorScope,\n probeRunnerReadiness,\n runnerReadinessRetryDelayMs,\n runnerRepositoryScopeFromEnv,\n} from '../runner-readiness.mjs';\n\n/** Keep the supervisor's control-queue identity byte-identical to the daemon. */\nexport function resolveSupervisorRunnerId(env = {}, hostname = systemHostname) {\n const explicit = String(env.VO_CODE_RUNNER_ID || '').trim();\n return explicit || `vo-code-runner-${hostname()}`;\n}\n\n/** Build the daemon environment without mislabeling a paired credential as admin. */\nexport function buildSupervisorChildEnv({\n baseEnv = {},\n controlPlaneUrl,\n explicitAdminToken = null,\n pairedOperatorId = null,\n} = {}) {\n const childEnv = {\n ...baseEnv,\n VO_CONTROL_PLANE_URL: controlPlaneUrl,\n };\n const adminToken = typeof explicitAdminToken === 'string' ? explicitAdminToken.trim() : '';\n const operatorId = typeof pairedOperatorId === 'string' ? pairedOperatorId.trim() : '';\n\n if (adminToken) childEnv.VO_CONTROL_PLANE_ADMIN_TOKEN = adminToken;\n else delete childEnv.VO_CONTROL_PLANE_ADMIN_TOKEN;\n\n if (operatorId) childEnv.VO_CODE_RUNNER_OPERATOR_IDS = operatorId;\n return childEnv;\n}\n\n/** Resolve auth provenance once so the supervisor and child use the same scope. */\nexport async function prepareSupervisorAuth({\n baseEnv = {},\n storedCredential = null,\n controlPlaneUrl,\n probeReadiness = probeRunnerReadiness,\n} = {}) {\n const explicitAdminToken = baseEnv.VO_CONTROL_PLANE_ADMIN_TOKEN?.trim();\n const token = explicitAdminToken || storedCredential?.vo_credential;\n if (!token) throw new Error('runner is not paired; run `vo-mcp pair` once on this host');\n\n let operatorId = String(baseEnv.VO_CODE_RUNNER_OPERATOR_IDS || '')\n .split(/[\\s,]+/u)\n .filter(Boolean)[0] || undefined;\n let repositoryScope = runnerRepositoryScopeFromEnv(baseEnv);\n let startupRetryAfterMs = null;\n let githubReady = null;\n let readinessError = null;\n if (!explicitAdminToken) {\n const readiness = await probeReadiness({\n controlPlaneUrl,\n token,\n requireGithub: true,\n repositories: repositoryScope,\n });\n const pairedScope = pairedOperatorScope(readiness)\n || (readiness?.paired === true && typeof readiness.operatorId === 'string'\n ? readiness.operatorId.trim()\n : '');\n operatorId = pairedScope || undefined;\n if (!operatorId) throw new Error('runner readiness failed: paired operator scope is missing');\n if (readiness.ok && Array.isArray(readiness.repositoryScope)) {\n repositoryScope = [...readiness.repositoryScope];\n githubReady = true;\n } else {\n githubReady = false;\n readinessError = typeof readiness?.error === 'string' ? readiness.error : 'github_not_ready';\n startupRetryAfterMs = runnerReadinessRetryDelayMs(readiness);\n }\n }\n\n const effectiveBaseEnv = repositoryScope.length > 0\n ? { ...baseEnv, VO_CODE_RUNNER_REPOS: repositoryScope.join(',') }\n : baseEnv;\n\n const childEnv = buildSupervisorChildEnv({\n baseEnv: effectiveBaseEnv,\n controlPlaneUrl,\n explicitAdminToken,\n pairedOperatorId: explicitAdminToken ? null : operatorId,\n });\n const clientEnv = {\n ...effectiveBaseEnv,\n VO_CONTROL_PLANE_ADMIN_TOKEN: token,\n VO_CONTROL_PLANE_URL: controlPlaneUrl,\n ...(operatorId ? { VO_CODE_RUNNER_OPERATOR_IDS: operatorId } : {}),\n };\n return {\n childEnv,\n clientEnv,\n operatorId,\n repositoryScope,\n githubReady,\n readinessError,\n startupRetryAfterMs,\n };\n}\n", "/**\n * Server-backed readiness probe for a paired BYO runner.\n *\n * The credential itself is opaque, so its mere presence is not proof that it is\n * usable or still bound to an operator. `/auth/me` supplies that truth from the\n * authenticated control-plane context. Before daemon startup, the optional\n * GitHub probe uses App-JWT GETs to verify the caller-owned installation,\n * publication grants, and selected repositories without minting a one-hour\n * token. Read/publish tokens are created only for actual task work.\n */\nimport { createHash, randomUUID } from 'node:crypto';\n\nexport const RUNNER_GITHUB_READINESS_TIMEOUT_MS = 50_000;\nexport const RUNNER_IDENTITY_READINESS_TIMEOUT_MS = 10_000;\nexport const RUNNER_READINESS_MAX_REPOSITORIES = 4;\nexport const RUNNER_READINESS_MAX_TIMER_DELAY_MS = 2_147_000_000;\nexport const RUNNER_READINESS_TRANSIENT_MAX_RETRY_AFTER_MS = 300_000;\nexport const RUNNER_READINESS_IPC_ACK_TIMEOUT_MS = 5_000;\nexport const RUNNER_READINESS_DEFERRAL_MESSAGE_TYPE = 'vo-runner-readiness-deferred-v1';\nexport const RUNNER_READINESS_DEFERRAL_ACK_TYPE = 'vo-runner-readiness-deferred-ack-v1';\nconst RUNNER_REPOSITORY = /^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u;\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\nexport function runnerRepositoryScopeFromEnv(env = {}) {\n return String(env.VO_CODE_RUNNER_REPOS || '')\n .split(/[\\s,]+/u)\n .map((repo) => repo.trim())\n .filter(Boolean);\n}\n\nexport function normalizeRunnerRepositoryScope(repositories) {\n if (!Array.isArray(repositories) || repositories.length < 1) {\n throw new Error('VO_CODE_RUNNER_REPOS must name at least one owner/name repository');\n }\n if (repositories.length > RUNNER_READINESS_MAX_REPOSITORIES) {\n throw new Error(`VO_CODE_RUNNER_REPOS supports at most ${RUNNER_READINESS_MAX_REPOSITORIES} repositories`);\n }\n const normalized = repositories.map((repo) => {\n const [owner, name] = typeof repo === 'string' ? repo.split('/') : [];\n if (typeof repo !== 'string' || repo.length > 140 || !RUNNER_REPOSITORY.test(repo)\n || owner === '.' || owner === '..' || name === '.' || name === '..') {\n throw new Error('VO_CODE_RUNNER_REPOS entries must be canonical owner/name repositories');\n }\n return repo.toLowerCase();\n });\n if (new Set(normalized).size !== normalized.length) {\n throw new Error('VO_CODE_RUNNER_REPOS entries must be unique');\n }\n const owners = new Set(normalized.map((repo) => repo.split('/')[0]));\n if (owners.size !== 1) {\n throw new Error('VO_CODE_RUNNER_REPOS entries must share one owner');\n }\n return Object.freeze(normalized.sort());\n}\n\nexport function runnerRepositoryScopeDigest(repositories) {\n const scope = normalizeRunnerRepositoryScope(repositories);\n return createHash('sha256').update(JSON.stringify({\n version: 1,\n repositories: scope,\n }), 'utf8').digest('hex');\n}\n\nexport function runnerReadinessRetryDelayMs(readiness) {\n if (readiness?.paired !== true || readiness?.githubReady !== false) return null;\n if (Number.isFinite(readiness.retryAfterMs) && readiness.retryAfterMs > 0) {\n return Math.ceil(readiness.retryAfterMs);\n }\n return null;\n}\n\n/**\n * One shared CLI/supervisor failure disposition. Only a parent-ACKed,\n * server-authorized readiness deferral may use reserved exit 75; ordinary\n * readiness failures and failed IPC custody remain ordinary exit 1 and\n * therefore consume breaker budget.\n */\nexport function runnerReadinessFailureDisposition(readiness, delivery = null) {\n const retryAfterMs = runnerReadinessRetryDelayMs(readiness);\n if (retryAfterMs === null) {\n return Object.freeze({ action: 'exit', exitCode: 1, retryAfterMs: null });\n }\n if (delivery?.attempted === true) {\n return Object.freeze({\n action: 'exit',\n exitCode: delivery.delivered === true ? 75 : 1,\n retryAfterMs,\n });\n }\n return Object.freeze({ action: 'wait', exitCode: null, retryAfterMs });\n}\n\nexport function parseRunnerReadinessDeferralRequest(message) {\n if (message?.type !== RUNNER_READINESS_DEFERRAL_MESSAGE_TYPE\n || !UUID_RE.test(String(message.nonce || ''))\n || !Number.isFinite(message.retryAfterMs)\n || message.retryAfterMs <= 0) return null;\n return Object.freeze({\n nonce: message.nonce,\n retryAfterMs: Math.ceil(message.retryAfterMs),\n error: typeof message.error === 'string' ? message.error : null,\n });\n}\n\nexport async function notifySupervisorReadinessDeferral({\n processLike,\n retryAfterMs,\n error = null,\n ackTimeoutMs = RUNNER_READINESS_IPC_ACK_TIMEOUT_MS,\n}) {\n if (processLike?.connected !== true || typeof processLike.send !== 'function') {\n return Object.freeze({ attempted: false, delivered: false });\n }\n if (typeof processLike.on !== 'function' || typeof processLike.off !== 'function') {\n return Object.freeze({ attempted: true, delivered: false });\n }\n const nonce = randomUUID();\n const delivered = await new Promise((resolve) => {\n let settled = false;\n const onMessage = (message) => {\n if (message?.type === RUNNER_READINESS_DEFERRAL_ACK_TYPE && message.nonce === nonce) {\n finish(true);\n }\n };\n const onDisconnect = () => finish(false);\n const finish = (value) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n processLike.off('message', onMessage);\n processLike.off('disconnect', onDisconnect);\n resolve(value);\n };\n const timer = setTimeout(() => finish(false), ackTimeoutMs);\n processLike.on('message', onMessage);\n processLike.on('disconnect', onDisconnect);\n try {\n processLike.send({\n type: RUNNER_READINESS_DEFERRAL_MESSAGE_TYPE,\n nonce,\n retryAfterMs,\n error,\n }, (sendError) => {\n if (sendError) finish(false);\n });\n } catch {\n finish(false);\n }\n });\n return Object.freeze({ attempted: true, delivered });\n}\n\nexport async function waitForRunnerReadinessRetry(delayMs, {\n nowMs = () => Date.now(),\n wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n} = {}) {\n if (!Number.isFinite(delayMs) || delayMs <= 0) {\n throw new TypeError('runner readiness retry delay is invalid');\n }\n const deadline = nowMs() + Math.ceil(delayMs);\n while (nowMs() < deadline) {\n await wait(Math.min(RUNNER_READINESS_MAX_TIMER_DELAY_MS, deadline - nowMs()));\n }\n}\n\nfunction failed({\n paired = false,\n operatorId = null,\n tenantId = null,\n githubReady = null,\n retryAfterMs = null,\n error,\n message,\n}) {\n return {\n ok: false,\n paired,\n operatorId,\n tenantId,\n githubReady,\n ...(Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? { retryAfterMs } : {}),\n error,\n message,\n };\n}\n\nfunction responseRetryAfterMs(response, body) {\n const transientReadinessFailure = response.status === 503\n && body?.error === 'github_installation_readiness_retryable';\n if (response.status !== 429 && !transientReadinessFailure) return null;\n const bound = (retryAfterMs) => transientReadinessFailure\n ? Math.min(RUNNER_READINESS_TRANSIENT_MAX_RETRY_AFTER_MS, retryAfterMs)\n : retryAfterMs;\n const value = response.headers?.get?.('retry-after')?.trim() ?? '';\n const seconds = Number(value);\n if (value && Number.isFinite(seconds) && seconds >= 0) {\n return bound(Math.max(1_000, Math.ceil(seconds * 1_000)));\n }\n const at = value ? Date.parse(value) : Number.NaN;\n if (Number.isFinite(at)) {\n return bound(Math.max(1_000, Math.ceil(at - Date.now())));\n }\n return bound(60_000);\n}\n\nasync function responseBody(response) {\n try {\n const value = await response.json();\n return value && typeof value === 'object' ? value : {};\n } catch {\n return {};\n }\n}\n\nfunction serverMessage(body, fallback) {\n return typeof body.message === 'string' && body.message.trim() ? body.message.trim() : fallback;\n}\n\nasync function fetchJsonWithTimeout(fetchImpl, url, init, timeoutMs) {\n const controller = new AbortController();\n let timer;\n const timeout = new Promise((_, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new Error(`request aborted after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n try {\n const requestAndBody = (async () => {\n const response = await fetchImpl(url, { ...init, signal: controller.signal });\n return { response, body: await responseBody(response) };\n })();\n return await Promise.race([requestAndBody, timeout]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * @param {{\n * controlPlaneUrl: string,\n * token: string,\n * fetchImpl?: typeof fetch,\n * requireGithub?: boolean,\n * repositories?: readonly string[],\n * timeoutMs?: number,\n * githubTimeoutMs?: number,\n * }} input\n */\nexport async function probeRunnerReadiness({\n controlPlaneUrl,\n token,\n fetchImpl = fetch,\n requireGithub = false,\n repositories = [],\n timeoutMs = RUNNER_IDENTITY_READINESS_TIMEOUT_MS,\n // The server performs at most five sequential App-JWT GETs (installation plus\n // every one of at most four configured repositories), each bounded at 8s.\n // Keep a transport margin while preventing a stuck proof from hanging startup.\n githubTimeoutMs = RUNNER_GITHUB_READINESS_TIMEOUT_MS,\n}) {\n const base = controlPlaneUrl.replace(/\\/+$/u, '');\n const headers = { authorization: `Bearer ${token}` };\n let identityResponse;\n let identity;\n try {\n ({ response: identityResponse, body: identity } = await fetchJsonWithTimeout(\n fetchImpl,\n `${base}/api/v1/auth/me`,\n { headers },\n timeoutMs,\n ));\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n return failed({\n error: 'control_plane_unreachable',\n message: `AlgoHQ could not be reached: ${detail}`,\n });\n }\n\n if (!identityResponse.ok) {\n return failed({\n error: 'credential_rejected',\n message: 'The saved pairing is expired or revoked. Pair this computer again.',\n });\n }\n if (\n identity.provisioned !== true ||\n identity.role !== 'operator' ||\n typeof identity.operator_id !== 'string' ||\n !identity.operator_id.trim() ||\n typeof identity.tenant_id !== 'string' ||\n !identity.tenant_id.trim()\n ) {\n return failed({\n error: 'operator_identity_missing',\n message: 'The pairing credential is valid but has no operator identity. Pair this computer again.',\n });\n }\n\n const operatorId = identity.operator_id.trim();\n const tenantId = identity.tenant_id.trim();\n if (!requireGithub) {\n return {\n ok: true,\n paired: true,\n operatorId,\n tenantId,\n githubReady: null,\n error: null,\n message: 'Paired to AlgoHQ.',\n };\n }\n\n let repositoryScope = null;\n try {\n if (!Array.isArray(repositories)) {\n throw new Error('VO_CODE_RUNNER_REPOS must be a repository array');\n }\n if (repositories.length > 0) repositoryScope = normalizeRunnerRepositoryScope(repositories);\n } catch (error) {\n return failed({\n paired: true,\n operatorId,\n tenantId,\n githubReady: false,\n error: 'github_repository_scope_invalid',\n message: error instanceof Error ? error.message : String(error),\n });\n }\n\n let githubResponse;\n let github;\n try {\n const readinessUrl = new URL(`${base}/api/v1/github/installation-readiness`);\n for (const repo of repositoryScope ?? []) readinessUrl.searchParams.append('repo', repo);\n ({ response: githubResponse, body: github } = await fetchJsonWithTimeout(\n fetchImpl,\n readinessUrl.toString(),\n { headers },\n githubTimeoutMs,\n ));\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n return failed({\n paired: true,\n operatorId,\n tenantId,\n githubReady: false,\n error: 'github_preflight_unreachable',\n message: `GitHub publication readiness could not be checked: ${detail}`,\n });\n }\n\n const repositorySelection = github.repository_selection;\n const repositoriesVerified = github.repositories_verified;\n const returnedScope = github.repository_scope;\n let normalizedReturnedScope = null;\n try {\n normalizedReturnedScope = normalizeRunnerRepositoryScope(returnedScope);\n } catch {\n // The shape check below fails closed with the server's actionable response.\n }\n const effectiveScope = repositoryScope ?? normalizedReturnedScope;\n const sourceVerified = repositoryScope === null\n ? github.repository_scope_source === 'persisted_installation_singleton'\n && normalizedReturnedScope?.length === 1\n : github.repository_scope_source === 'runner_config';\n const repositoryScopeVerified = effectiveScope !== null\n && normalizedReturnedScope !== null\n && Array.isArray(returnedScope)\n && returnedScope.length === normalizedReturnedScope.length\n && returnedScope.every((repo, index) => repo === normalizedReturnedScope[index])\n && normalizedReturnedScope.length === effectiveScope.length\n && normalizedReturnedScope.every((repo, index) => repo === effectiveScope[index])\n && github.repository_scope_sha256 === runnerRepositoryScopeDigest(effectiveScope)\n && repositoriesVerified === effectiveScope.length\n && sourceVerified\n && (repositorySelection === 'all' || repositorySelection === 'selected');\n if (!githubResponse.ok || github.configured !== true || github.verified !== true\n || github.publication_ready !== true\n || !repositoryScopeVerified) {\n const error = typeof github.error === 'string' && github.error ? github.error : 'github_not_ready';\n return failed({\n paired: true,\n operatorId,\n tenantId,\n githubReady: false,\n retryAfterMs: responseRetryAfterMs(githubResponse, github),\n error,\n message: serverMessage(github, `GitHub publication preflight failed (HTTP ${githubResponse.status}).`),\n });\n }\n\n return {\n ok: true,\n paired: true,\n operatorId,\n tenantId,\n githubReady: true,\n repositoryScope: effectiveScope,\n repositoryScopeSource: github.repository_scope_source,\n error: null,\n message: `Paired with a verified Algosuite GitHub App installation (${repositoriesVerified} repos).`,\n };\n}\n\nexport function pairedOperatorScope(readiness) {\n return readiness?.ok === true &&\n readiness?.paired === true &&\n typeof readiness.operatorId === 'string' &&\n readiness.operatorId.trim()\n ? readiness.operatorId.trim()\n : null;\n}\n", "import { spawnSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport function defaultCredentialHelperPath(metaUrl = import.meta.url) {\n const moduleDir = dirname(fileURLToPath(metaUrl));\n const bundled = join(moduleDir, 'supervisor-credential-helper.js');\n const source = join(moduleDir, '..', 'supervisor-credential-helper.mjs');\n return existsSync(source) ? source : bundled;\n}\n\n/** Read the OS-keychain credential without loading its native module here. */\nexport function readStoredCredentialIsolated({\n spawn = spawnSync,\n execPath = process.execPath,\n helperPath = defaultCredentialHelperPath(),\n helperArgs = [],\n env = process.env,\n} = {}) {\n const result = spawn(execPath, [helperPath, ...helperArgs], {\n env,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'pipe'],\n shell: false,\n windowsHide: true,\n timeout: 10_000,\n });\n if (result.status !== 0) {\n throw new Error('runner credential helper could not read the paired credential');\n }\n try {\n const parsed = JSON.parse(String(result.stdout || ''));\n return parsed && typeof parsed === 'object' ? parsed : null;\n } catch {\n throw new Error('runner credential helper returned an invalid credential');\n }\n}\n", "/** Pure rapid-exit circuit used by the persistent runner supervisor. */\nexport const DEFAULT_RESPAWN_CIRCUIT = Object.freeze({\n baseDelayMs: 2_000,\n maxDelayMs: 30_000,\n healthyResetMs: 60_000,\n maxRapidExits: 5,\n});\n\nexport function createRespawnCircuit(options = {}) {\n const config = { ...DEFAULT_RESPAWN_CIRCUIT, ...options };\n for (const [key, value] of Object.entries(config)) {\n if (!Number.isInteger(value) || value < 1) throw new Error(`${key} must be a positive integer`);\n }\n let rapidExits = 0;\n\n return Object.freeze({\n recordExit(startedAt, exitedAt) {\n if (!Number.isFinite(startedAt) || !Number.isFinite(exitedAt) || exitedAt < startedAt) {\n throw new Error('respawn circuit timestamps are invalid');\n }\n const uptimeMs = exitedAt - startedAt;\n rapidExits = uptimeMs >= config.healthyResetMs ? 0 : rapidExits + 1;\n const tripped = rapidExits >= config.maxRapidExits;\n const delayMs = Math.min(\n config.maxDelayMs,\n config.baseDelayMs * (2 ** Math.max(0, rapidExits - 1)),\n );\n return Object.freeze({ rapidExits, uptimeMs, delayMs, tripped });\n },\n snapshot() {\n return Object.freeze({ rapidExits, tripped: rapidExits >= config.maxRapidExits });\n },\n });\n}\n", "/**\n * Readiness proof for one supervisor-owned runner child.\n *\n * All timing and state effects are injected so the race between an asynchronous\n * health probe and process exit can be exercised without starting a real child.\n */\nconst terminatedChildren = new WeakSet();\n\n/**\n * Install one exact-child terminal-event account while retaining an `error`\n * listener for the child's full lifetime. Node may emit an asynchronous spawn\n * `error` without `exit`, or may emit both; only the first terminal event\n * receives termination authority.\n */\nexport function attachSupervisorChildTerminationCustody(\n target,\n onTerminated,\n onObservedError = () => {},\n) {\n let accounted = false;\n const account = (kind, error = null) => {\n terminatedChildren.add(target);\n if (accounted) return false;\n accounted = true;\n onTerminated(Object.freeze({ target, kind, error }));\n return true;\n };\n target.on('error', (error) => {\n onObservedError(error);\n // ChildProcess also uses `error` for failed IPC sends and failed kills.\n // Those do not prove a live process terminated. A spawn failure is the\n // narrow terminal case: Node leaves pid unset and may emit exit afterward.\n if (target.pid === undefined || target.pid === null) account('error', error);\n });\n target.on('exit', () => { account('exit'); });\n return Object.freeze({ accounted: () => accounted });\n}\n\nexport function supervisorChildHasExited(target) {\n // Node preserves exitCode=null for signal-terminated children and reports the\n // terminal state through signalCode instead. An asynchronous spawn error can\n // leave both fields null, so exact-object error custody is terminal too.\n return terminatedChildren.has(target)\n || target.exitCode !== null\n || (target.signalCode ?? null) !== null;\n}\n\nexport function supervisorChildIsRunning(target) {\n return !supervisorChildHasExited(target);\n}\n\nexport function shouldRespawnSupervisorChild({ stopping, degraded, handling, child }) {\n return !stopping && !degraded && !handling && (!child || supervisorChildHasExited(child));\n}\n\nexport function shouldDeferSupervisorReadinessExit({\n target,\n currentChild,\n retryAfterMs,\n}) {\n return target === currentChild\n && target?.exitCode === 75\n && Number.isFinite(retryAfterMs)\n && retryAfterMs > 0;\n}\n\n/**\n * Exact-child custody for a child-reported GitHub readiness embargo. The\n * supervisor records the nonce before acknowledging it to the child, then one\n * idempotent capture transition is shared by health, activation, and exit-event\n * orderings. A later exit listener can therefore never reinterpret an already\n * captured exit as a crash.\n */\nexport function createSupervisorReadinessDeferralTracker({\n currentChild,\n releaseCurrentChild,\n onCaptured,\n}) {\n const pending = new WeakMap();\n const terminal = new WeakSet();\n const recoveryGenerations = new WeakMap();\n\n return Object.freeze({\n recordPending(target, request) {\n if (!target || target !== currentChild() || terminal.has(target) || pending.has(target)\n || typeof request?.nonce !== 'string' || !request.nonce\n || !Number.isFinite(request.retryAfterMs) || request.retryAfterMs <= 0) return false;\n pending.set(target, Object.freeze({\n nonce: request.nonce,\n retryAfterMs: Math.ceil(request.retryAfterMs),\n }));\n return true;\n },\n recordRecoveryGeneration(target, generation) {\n if (!target || !Number.isInteger(generation)) return false;\n recoveryGenerations.set(target, generation);\n return true;\n },\n isDeferred(target) {\n const request = target ? pending.get(target) : null;\n return Boolean(target) && (terminal.has(target) || shouldDeferSupervisorReadinessExit({\n target,\n currentChild: currentChild(),\n retryAfterMs: request?.retryAfterMs,\n }));\n },\n capture(target) {\n if (!target) return false;\n if (terminal.has(target)) return true;\n const request = pending.get(target);\n if (!shouldDeferSupervisorReadinessExit({\n target,\n currentChild: currentChild(),\n retryAfterMs: request?.retryAfterMs,\n })) return false;\n const recoveryGeneration = recoveryGenerations.get(target);\n terminal.add(target);\n pending.delete(target);\n recoveryGenerations.delete(target);\n releaseCurrentChild(target);\n onCaptured(Object.freeze({\n target,\n retryAfterMs: request.retryAfterMs,\n recoveryGeneration: Number.isInteger(recoveryGeneration) ? recoveryGeneration : null,\n }));\n return true;\n },\n forget(target) {\n if (!target) return;\n pending.delete(target);\n recoveryGenerations.delete(target);\n },\n });\n}\n\nexport function resolveSupervisorChildStartAuthority({\n degradationState,\n deferredRecoveryGeneration,\n}) {\n const snapshot = degradationState.snapshot();\n const exactRecovery = Number.isInteger(deferredRecoveryGeneration)\n && deferredRecoveryGeneration === snapshot.generation;\n return Object.freeze({\n allowed: !snapshot.degraded || exactRecovery,\n recoveryGeneration: exactRecovery ? deferredRecoveryGeneration : null,\n });\n}\n\n/**\n * One-shot startup gate for a server-provided readiness Retry-After deadline.\n * Waiting behind this gate never spawns a process, so it cannot consume the\n * rapid-exit breaker. A later upstream response may extend the same unspent\n * start authority; once consumed it can never be reused by another poll.\n */\nexport function createSupervisorStartupDeferral({\n retryAfterMs = null,\n nowMs = () => Date.now(),\n} = {}) {\n let started = false;\n let notBefore = null;\n const defer = (delayMs) => {\n if (started || !Number.isFinite(delayMs) || delayMs <= 0) return false;\n const candidate = nowMs() + Math.ceil(delayMs);\n notBefore = notBefore === null ? candidate : Math.max(notBefore, candidate);\n return true;\n };\n defer(retryAfterMs);\n\n return Object.freeze({\n defer,\n reopen(delayMs) {\n if (!Number.isFinite(delayMs) || delayMs <= 0) return false;\n started = false;\n notBefore = null;\n return defer(delayMs);\n },\n isPending() {\n return !started && notBefore !== null && nowMs() < notBefore;\n },\n remainingMs() {\n return started || notBefore === null ? 0 : Math.max(0, notBefore - nowMs());\n },\n consumeIfReady() {\n if (started || (notBefore !== null && nowMs() < notBefore)) return false;\n started = true;\n notBefore = null;\n return true;\n },\n hasStarted() {\n return started;\n },\n });\n}\n\n/**\n * Generation-fenced degradation state. A health proof may clear only the\n * generation it observed when it began, and only for the same current child.\n */\nexport function createSupervisorDegradationState() {\n let degraded = false;\n let generation = 0;\n\n return {\n isDegraded() {\n return degraded;\n },\n markDegraded() {\n degraded = true;\n generation += 1;\n },\n beginHealthProof({ target, currentChild, allowRecovery, onRecovery }) {\n const observedGeneration = generation;\n return () => {\n if (currentChild() !== target || generation !== observedGeneration) return false;\n if (degraded && !allowRecovery) return false;\n const recovered = degraded;\n degraded = false;\n if (recovered) onRecovery?.();\n return true;\n };\n },\n beginDegradationProof({ target, currentChild, onDegraded }) {\n const observedGeneration = generation;\n return (message) => {\n if (currentChild() !== target || generation !== observedGeneration) return false;\n onDegraded(message);\n return true;\n };\n },\n snapshot() {\n return { degraded, generation };\n },\n };\n}\n\n/**\n * Begin one exact-child, exact-generation healthy-state commit. The stale\n * non-zero supervisor exit status is cleared only inside the same successful\n * commit that recovers degradation; stale or wrong-child proofs have no exit\n * status authority.\n */\nexport function beginSupervisorHealthyStateCommit({\n degradationState,\n target,\n currentChild,\n allowRecovery,\n clearStaleExitCode,\n}) {\n return degradationState.beginHealthProof({\n target,\n currentChild,\n allowRecovery,\n onRecovery: clearStaleExitCode,\n });\n}\n\nconst RUNNER_RECOVERY_ACTIONS = new Set(['update', 'reinstall', 'reconnect']);\n\nexport function shouldRecoverSupervisorChildAfterAction({\n stoppedChild,\n actionKind,\n actionSucceeded,\n}) {\n // An action that deliberately stopped a live child must restore service even\n // when its maintenance work failed. With no such child, only a successful\n // runner repair/reconnect may clear pre-existing degradation; unrelated host\n // cleanup and failed maintenance are not recovery authority.\n return Boolean(stoppedChild)\n || (actionSucceeded === true && RUNNER_RECOVERY_ACTIONS.has(actionKind));\n}\n\n/**\n * One-shot proof that the current control action took responsibility for a\n * live child before stopping it. Generic polling failures never arm this\n * fence, so they cannot accidentally relaunch a previously degraded runner.\n */\nexport function createSupervisorControlRecoveryFence() {\n let targetStoppedForControl = null;\n const consume = () => {\n const target = targetStoppedForControl;\n targetStoppedForControl = null;\n return target;\n };\n\n return {\n markBeforeStop(target) {\n targetStoppedForControl = target && supervisorChildIsRunning(target) ? target : null;\n return targetStoppedForControl !== null;\n },\n consume,\n async recoverOnce(recover) {\n // Consume before awaiting so a failed recovery cannot leak authority into\n // a later, unrelated poll iteration.\n const target = consume();\n if (!target) return false;\n await recover(target);\n return true;\n },\n };\n}\n\nexport async function verifySupervisorChildHealth({\n target,\n degradeOnExit,\n context,\n waitBeforeProbe,\n waitForLocalRunner,\n stopExpectedly,\n markHealthy,\n markDegraded,\n isReadinessDeferredExit = () => false,\n isExpectedStop = () => false,\n}) {\n try {\n await waitBeforeProbe();\n const healthy = supervisorChildIsRunning(target) && await waitForLocalRunner(target);\n // The health probe is asynchronous. Node may publish exitCode or signalCode\n // while it is pending, so decisions below must use a fresh observation,\n // not the value from before the await.\n const exited = supervisorChildHasExited(target);\n if (isExpectedStop(target)) return false;\n if (exited && isReadinessDeferredExit(target)) return false;\n if (healthy && !exited) {\n // A caller may reject a stale success when a newer degradation or child\n // generation superseded this asynchronous proof.\n if (markHealthy() !== false) return true;\n if (supervisorChildIsRunning(target)) await stopExpectedly(target);\n return false;\n }\n // Ordinary rapid exits remain governed by the backoff circuit. A live\n // child that never proves readiness, or any failed control-action\n // recovery, must fail closed immediately instead of occupying the slot.\n if (!exited || degradeOnExit) {\n const committed = markDegraded(`${context} did not become healthy; entering degraded mode`) !== false;\n if (!committed) return false;\n if (supervisorChildIsRunning(target)) await stopExpectedly(target);\n }\n return false;\n } catch (error) {\n if (isExpectedStop(target)) return false;\n const committed = markDegraded(\n `${context} health proof failed; entering degraded mode: ${\n error instanceof Error ? error.message : String(error)\n }`,\n ) !== false;\n if (!committed) return false;\n if (supervisorChildIsRunning(target)) await stopExpectedly(target).catch(() => {});\n return false;\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAeA,eAAsB,kBAAkB;AACtC,QAAM,IAAI;AAAA,IACR;AAAA,EAEF;AACF;AApBA;AAAA;AAAA;AAAA;;;ACKA,SAAS,aAAa;AACtB,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,WAAAC,UAAS,QAAAC,aAAY;;;ACQ9B,IAAM,wBAAwB;AAU9B,eAAsB,uBAAuB,EAAE,KAAK,WAAW,OAAO,WAAW,OAAO,OAAO,KAAK,GAAG;AACrG,QAAM,OAAO,CAAC,WAAW;AACvB,QAAI,SAAU,OAAM,IAAI,MAAM,gCAAgC,MAAM,EAAE;AACtE,WAAO;AAAA,EACT;AACA,MAAI;AAIF,UAAM,MAAM,MAAM;AAAA,MAChB;AAAA,MACA;AAAA,MACA,WAAW,EAAE,OAAO,QAAQ,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC,EAAG,IAAI,CAAC;AAAA,MAC3D,WAAW,EAAE,WAAW,sBAAsB,IAAI,CAAC;AAAA,IACrD;AACA,QAAI,CAAC,IAAI,GAAI,QAAO,KAAK,QAAQ,IAAI,MAAM,EAAE;AAC7C,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,QAAI,CAAC,QAAQ,CAAC,KAAK,MAAO,QAAO,KAAK,eAAe;AAMrD,QAAI,YAAY,KAAK,UAAU,OAAQ,QAAO,KAAK,iDAAiD;AAGpG,WAAO,EAAE,OAAO,KAAK,OAAO,WAAW,KAAK,cAAc,MAAM,GAAI,OAAO,KAAK,gBAAgB,YAAY,EAAE,YAAY,KAAK,YAAY,IAAI,CAAC,EAAG;AAAA,E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CAAC,EAAE;AAIhG,YAAM,qBAAqB,YAAY,MAAM,+BAA+B,CAAC;AAC7E,iBAAW;AACX,YAAM,MAAM,OAAO;AAAA,IACrB;AAAA,EACF;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAM,iCAAiC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACvG,UAAQ,WAAW;AACrB,CAAC;",
4
+ "sourcesContent": ["/**\n * Control-plane auth stub for the bundled `vo-mcp runner`.\n *\n * Replaces the daemon's lazy Firebase/SMOKE_* fallback\n * (`scripts/virtual-office/orchestrator-firestore/auth.mjs`), which pulls\n * `vo-config.mjs` (hardcoded Nexus Firebase project) + the firebase-admin chain.\n * A BYO runner ALWAYS authenticates with its own scoped `vo_credential` \u2014 read\n * from the OS keychain by `runner-cli.mjs` and injected as\n * `VO_CONTROL_PLANE_ADMIN_TOKEN` \u2014 so `control-plane-client.mjs`'s `resolveBearer`\n * returns early on the token and NEVER reaches this fallback. It exists only so\n * the bundle has nothing to resolve into the firebase chain; if it ever runs,\n * it fails LOUDLY with the fix.\n *\n * esbuild swaps this in for the heavy original at bundle time (see scripts/bundle.mjs).\n */\nexport async function getFirebaseAuth() {\n throw new Error(\n 'vo-mcp runner: no control-plane credential. Run `vo-mcp login` first \u2014 the runner ' +\n 'authenticates with your stored vo_credential (or set VO_CONTROL_PLANE_ADMIN_TOKEN).',\n );\n}\n", "/**\n * Persistent host supervisor for remote Mission Control maintenance.\n * The task daemon is a replaceable child; this process stays alive while it is\n * updated or repaired. Pairing credentials remain in the existing OS store.\n */\nimport { spawn } from 'node:child_process';\nimport { randomUUID } from 'node:crypto';\nimport { createRequire } from 'node:module';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join } from 'node:path';\nimport { createControlPlaneClient } from '../../../scripts/virtual-office/code-runner/control-plane-client.mjs';\nimport { runHostMaintenance } from '../../../scripts/virtual-office/code-runner/runner-host-maintenance.mjs';\nimport { stageAndActivateBundledUpdate } from './runner/bundled-runtime-updater.mjs';\nimport { runLegacyOrphanSweep } from '../../../scripts/virtual-office/code-runner/legacy-orphan-sweep.mjs';\nimport { activationSupervisorInstanceId, runtimeRootFromEnv } from './runner/bundled-runtime-store.mjs';\nimport { finishPendingActivation } from './runner/supervisor-activation.mjs';\nimport { resolveSupervisorChildEntry } from './runner/supervisor-child-entry.mjs';\nimport { awaitRunnerUpdateDrain } from './runner/update-drain-gate.mjs';\nimport { prepareSupervisorAuth, resolveSupervisorRunnerId } from './runner/supervisor-child-env.mjs';\nimport {\n RUNNER_GITHUB_READINESS_TIMEOUT_MS,\n RUNNER_IDENTITY_READINESS_TIMEOUT_MS,\n RUNNER_READINESS_DEFERRAL_ACK_TYPE,\n parseRunnerReadinessDeferralRequest,\n} from './runner-readiness.mjs';\nimport { readStoredCredentialIsolated } from './runner/supervisor-credential-reader.mjs';\nimport { createRespawnCircuit } from './runner/respawn-circuit.mjs';\nimport {\n attachSupervisorChildTerminationCustody,\n describeChildTermination,\n beginSupervisorHealthyStateCommit,\n createSupervisorDegradationState,\n createSupervisorControlRecoveryFence,\n createSupervisorReadinessDeferralTracker,\n createSupervisorStartupDeferral,\n resolveSupervisorChildStartAuthority,\n shouldRespawnSupervisorChild,\n shouldRecoverSupervisorChildAfterAction,\n supervisorChildHasExited,\n supervisorChildIsRunning,\n verifySupervisorChildHealth,\n} from './runner/supervisor-child-health.mjs';\n\nconst DEFAULT_CONTROL_PLANE_URL = 'https://vo-control-plane-bzjphrajaq-uc.a.run.app';\nconst POLL_MS = 5000;\nconst CHILD_START_MS = 1500;\n// The child performs identity auth plus the bounded GitHub preflight before\n// opening its local status port. Cover both transport deadlines plus startup\n// margin without changing the independent child-stop deadlines.\nconst CHILD_READINESS_TIMEOUT_MS = RUNNER_IDENTITY_READINESS_TIMEOUT_MS\n + RUNNER_GITHUB_READINESS_TIMEOUT_MS\n + 10_000;\nconst SUPERVISOR_CAPABILITIES = ['bundled-runtime-slots-v1', 'legacy-orphan-purge-v1'];\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\nconst selfPath = fileURLToPath(import.meta.url);\nconst bundledChildEntry = join(dirname(selfPath), 'runner-cli.js');\nconst supervisorRuntimeRoot = runtimeRootFromEnv(process.env);\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst runnerId = resolveSupervisorRunnerId(process.env);\n\nfunction packageVersion() {\n try { return createRequire(import.meta.url)('../package.json').version || 'unknown'; } catch { return 'unknown'; }\n}\n\nconst requestedSupervisorInstanceId = UUID_RE.test(String(process.env.VO_RUNNER_SUPERVISOR_INSTANCE_ID || ''))\n ? process.env.VO_RUNNER_SUPERVISOR_INSTANCE_ID\n : randomUUID();\nconst supervisorInstanceId = activationSupervisorInstanceId(\n runtimeRootFromEnv(process.env), requestedSupervisorInstanceId,\n);\nconst supervisorVersion = packageVersion();\nconst supervisorControlIdentity = {\n supervisorInstanceId,\n supervisorVersion,\n capabilities: SUPERVISOR_CAPABILITIES,\n};\n\nlet lastResolvedChildDescriptor = null;\n\n/**\n * Resolved on EVERY spawn, never cached at module scope: a slot activated after\n * this process started must take effect on the next child restart, not on the\n * next whole-app restart (nothing forces one).\n */\nfunction spawnChild(childEnv) {\n const resolved = resolveSupervisorChildEntry({\n runtimeRoot: supervisorRuntimeRoot,\n bundledEntry: bundledChildEntry,\n bundledVersion: supervisorVersion,\n });\n if (resolved.descriptor !== lastResolvedChildDescriptor) {\n console.error(`[vo-runner supervisor] child entry -> ${resolved.descriptor} (${resolved.detail})`);\n lastResolvedChildDescriptor = resolved.descriptor;\n }\n return spawn(process.execPath, resolved.args, {\n env: childEnv,\n stdio: ['inherit', 'inherit', 'inherit', 'ipc'],\n windowsHide: true,\n });\n}\n\nfunction spawnPreviousChild(entry, childEnv) {\n const previous = spawn(process.execPath, [entry, 'runner'], {\n env: childEnv,\n stdio: ['inherit', 'inherit', 'inherit', 'ipc'],\n windowsHide: true,\n });\n attachSupervisorChildTerminationCustody(\n previous,\n () => {},\n (error) => {\n console.error(\n `[vo-runner supervisor] rollback child process error: ${error instanceof Error ? error.message : String(error)}`,\n );\n },\n );\n return previous;\n}\n\nasync function localStatus() {\n try {\n const port = Number(process.env.VO_CODE_RUNNER_CONTROL_PORT || 7787);\n const response = await fetch(`http://127.0.0.1:${port}/status`, { signal: AbortSignal.timeout(800) });\n if (!response.ok) return null;\n const body = await response.json();\n return body?.ok === true ? body : null;\n } catch {\n return null;\n }\n}\n\nasync function waitForLocalRunner(child) {\n const deadline = Date.now() + CHILD_READINESS_TIMEOUT_MS;\n while (Date.now() < deadline) {\n if (supervisorChildHasExited(child)) return false;\n const status = await localStatus();\n if (status?.running === true && Number(status.pid) === Number(child.pid)) return true;\n await sleep(500);\n }\n return false;\n}\n\nasync function waitForChildExit(child, timeoutMs) {\n if (!child || supervisorChildHasExited(child)) return true;\n return new Promise((resolve) => {\n let settled = false;\n const finish = (exited) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n child.off('exit', onExit);\n resolve(exited);\n };\n const onExit = () => finish(true);\n const timer = setTimeout(() => finish(false), timeoutMs);\n child.once('exit', onExit);\n if (supervisorChildHasExited(child)) finish(true);\n });\n}\n\nasync function stopChild(child) {\n if (!child || supervisorChildHasExited(child)) return;\n child.kill(process.platform === 'win32' ? undefined : 'SIGTERM');\n if (await waitForChildExit(child, 15_000)) return;\n if (supervisorChildIsRunning(child)) child.kill('SIGKILL');\n // Keep the deliberate-stop fence through the forced-kill exit. Returning\n // immediately after kill() lets a later exit look like a crash and consume\n // breaker budget during legitimate maintenance.\n await waitForChildExit(child, 5_000);\n}\n\nasync function main() {\n // Read keychain-backed credentials in a process that exits before npm ever\n // attempts to replace this package. Windows otherwise keeps the keyring DLL\n // locked for the full supervisor lifetime and global self-updates fail.\n const stored = readStoredCredentialIsolated();\n const controlPlaneUrl = process.env.VO_CONTROL_PLANE_URL || DEFAULT_CONTROL_PLANE_URL;\n const pairedSupervisor = !String(process.env.VO_CONTROL_PLANE_ADMIN_TOKEN || '').trim();\n const supervisorAuthInput = {\n baseEnv: process.env,\n storedCredential: stored,\n controlPlaneUrl,\n };\n const {\n childEnv,\n clientEnv,\n operatorId,\n startupRetryAfterMs,\n } = await prepareSupervisorAuth(supervisorAuthInput);\n Object.assign(childEnv, {\n VO_RUNNER_SUPERVISOR_INSTANCE_ID: supervisorInstanceId,\n VO_RUNNER_SUPERVISOR_VERSION: supervisorVersion,\n VO_RUNNER_SUPERVISOR_CAPABILITIES: SUPERVISOR_CAPABILITIES.join(','),\n });\n const client = createControlPlaneClient({ baseUrl: controlPlaneUrl, env: clientEnv });\n const runtimeRoot = runtimeRootFromEnv(process.env);\n let child = null;\n let stopping = false;\n let handling = false;\n const expectedChildStops = new WeakSet();\n const healthNeutralizedChildren = new WeakSet();\n // Activation failed but the process stays alive to accept remote repair.\n // Distinct from `stopping`: we refuse to SERVE work, we do not refuse to be FIXED.\n const degradationState = createSupervisorDegradationState();\n const markSupervisorDegraded = () => {\n degradationState.markDegraded();\n process.exitCode = 1;\n };\n const respawnCircuit = createRespawnCircuit();\n const controlRecoveryFence = createSupervisorControlRecoveryFence();\n const startupDeferral = createSupervisorStartupDeferral({\n retryAfterMs: startupRetryAfterMs,\n });\n let startupNeedsReadinessRefresh = startupRetryAfterMs !== null;\n let deferredControlRecoveryGeneration = null;\n\n const stopChildExpectedly = async (target) => {\n if (!target) return;\n expectedChildStops.add(target);\n healthNeutralizedChildren.add(target);\n try {\n await stopChild(target);\n } finally {\n // If a pathological process still has not emitted exit after SIGKILL,\n // retain its exact-child tag. WeakSet ownership disappears with the\n // process object and cannot mask a different child's real crash.\n if (supervisorChildHasExited(target)) expectedChildStops.delete(target);\n }\n };\n\n const readinessDeferrals = createSupervisorReadinessDeferralTracker({\n currentChild: () => child,\n releaseCurrentChild: (target) => {\n if (child === target) child = null;\n },\n onCaptured: ({ retryAfterMs, recoveryGeneration }) => {\n startupNeedsReadinessRefresh = true;\n if (Number.isInteger(recoveryGeneration)\n && degradationState.snapshot().generation === recoveryGeneration) {\n deferredControlRecoveryGeneration = recoveryGeneration;\n }\n startupDeferral.reopen(retryAfterMs);\n console.warn(\n `[vo-runner supervisor] child deferred by GitHub readiness for ${retryAfterMs}ms; `\n + 'preserving control polling without consuming rapid-exit breaker budget',\n );\n },\n });\n const isChildReadinessDeferred = (target) => readinessDeferrals.isDeferred(target);\n const captureChildReadinessDeferral = (target) => readinessDeferrals.capture(target);\n\n const respawn = () => {\n if (!startupDeferral.hasStarted()) return;\n if (!shouldRespawnSupervisorChild({\n stopping,\n degraded: degradationState.isDegraded(),\n handling,\n child,\n })) return;\n try {\n child = launchChild();\n void verifyChildHealth(child, false, 'automatic relaunch');\n } catch (error) {\n markSupervisorDegraded();\n console.error(\n `[vo-runner supervisor] child relaunch failed; entering degraded mode: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n };\n const launchChild = () => {\n const next = spawnChild(childEnv);\n const startedAt = Date.now();\n next.on('message', (message) => {\n const request = parseRunnerReadinessDeferralRequest(message);\n if (!request || !readinessDeferrals.recordPending(next, request)) return;\n // The request is exact-child state before the ACK is attempted. Only a\n // matching ACK received by the child authorizes its reserved exit 75.\n try {\n next.send({\n type: RUNNER_READINESS_DEFERRAL_ACK_TYPE,\n nonce: request.nonce,\n }, (error) => {\n if (error) console.warn(`[vo-runner supervisor] readiness deferral ACK failed: ${error.message}`);\n });\n } catch (error) {\n console.warn(\n `[vo-runner supervisor] readiness deferral ACK failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n });\n attachSupervisorChildTerminationCustody(\n next,\n (record) => {\n // A supervisor-requested stop is not a crash and must not consume the\n // breaker. Every otherwise-unexpected termination can form a loop,\n // including an asynchronous spawn error, external signal, or a faulty\n // child reporting a misleading zero code.\n if (stopping || expectedChildStops.delete(next)) {\n readinessDeferrals.forget(next);\n return;\n }\n if (captureChildReadinessDeferral(next)) return;\n readinessDeferrals.forget(next);\n // Say HOW it died, before any respawn decision. Without this the\n // Windows libuv abort leaves no trace the operator or a later\n // investigation can read: the process is simply gone and the next\n // child starts. Names the runtime, because the daemon runs the\n // bundled Node rather than whatever is on the operator's PATH.\n console.error(`[vo-runner supervisor] child ${describeChildTermination(record)}`);\n const decision = respawnCircuit.recordExit(startedAt, Date.now());\n if (decision.tripped) {\n markSupervisorDegraded();\n console.error(\n `[vo-runner supervisor] child exited rapidly ${decision.rapidExits} times; `\n + 'entering degraded mode to stop startup/token churn while remote repair remains available',\n );\n return;\n }\n setTimeout(respawn, decision.delayMs);\n },\n (error) => {\n console.error(\n `[vo-runner supervisor] child process error: ${error instanceof Error ? error.message : String(error)}`,\n );\n },\n );\n return next;\n };\n\n const verifyChildHealth = async (target, degradeOnExit, context) => {\n const commitSupervisorHealthyState = beginSupervisorHealthyStateCommit({\n degradationState,\n target,\n currentChild: () => child,\n allowRecovery: degradeOnExit,\n clearStaleExitCode: () => {\n process.exitCode = undefined;\n },\n });\n const commitSupervisorDegradedState = degradationState.beginDegradationProof({\n target,\n currentChild: () => child,\n onDegraded: (message) => {\n markSupervisorDegraded();\n console.error(`[vo-runner supervisor] ${message}`);\n },\n });\n return verifySupervisorChildHealth({\n target,\n degradeOnExit,\n context,\n waitBeforeProbe: () => sleep(CHILD_START_MS),\n waitForLocalRunner,\n stopExpectedly: stopChildExpectedly,\n isReadinessDeferredExit: isChildReadinessDeferred,\n isExpectedStop: (candidate) => healthNeutralizedChildren.has(candidate),\n markHealthy: commitSupervisorHealthyState,\n markDegraded: commitSupervisorDegradedState,\n });\n };\n\n const deferChildAdmission = (retryAfterMs) => {\n startupNeedsReadinessRefresh = true;\n if (startupDeferral.hasStarted()) startupDeferral.reopen(retryAfterMs);\n else startupDeferral.defer(retryAfterMs);\n console.warn(\n `[vo-runner supervisor] GitHub readiness embargoed child startup for ${retryAfterMs}ms; `\n + 'control polling remains active',\n );\n };\n\n const refreshSupervisorChildAdmission = async () => {\n if (!pairedSupervisor) return true;\n const refreshed = await prepareSupervisorAuth({\n ...supervisorAuthInput,\n baseEnv: childEnv,\n });\n if (refreshed.operatorId !== operatorId) {\n throw new Error('runner readiness operator identity changed during supervisor admission');\n }\n if (refreshed.startupRetryAfterMs !== null) {\n deferChildAdmission(refreshed.startupRetryAfterMs);\n return false;\n }\n if (refreshed.repositoryScope.length > 0) {\n const repositoryScope = refreshed.repositoryScope.join(',');\n childEnv.VO_CODE_RUNNER_REPOS = repositoryScope;\n clientEnv.VO_CODE_RUNNER_REPOS = repositoryScope;\n }\n startupNeedsReadinessRefresh = false;\n return true;\n };\n\n const ensureHealthyChildAfterControl = async () => {\n if (!child || supervisorChildHasExited(child)) {\n const recoveryGeneration = degradationState.snapshot().generation;\n if (!startupDeferral.hasStarted() && startupDeferral.isPending()) {\n deferredControlRecoveryGeneration = recoveryGeneration;\n return false;\n }\n try {\n if (!(await refreshSupervisorChildAdmission())) {\n deferredControlRecoveryGeneration = recoveryGeneration;\n return false;\n }\n if (!startupDeferral.hasStarted() && !startupDeferral.consumeIfReady()) return false;\n child = launchChild();\n readinessDeferrals.recordRecoveryGeneration(child, recoveryGeneration);\n } catch (error) {\n markSupervisorDegraded();\n console.error(\n `[vo-runner supervisor] control recovery relaunch failed; entering degraded mode: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n return false;\n }\n }\n return verifyChildHealth(child, true, 'control recovery relaunch');\n };\n\n const startInitialChild = async (recoveryGeneration = null) => {\n const activationChild = launchChild();\n child = activationChild;\n if (Number.isInteger(recoveryGeneration)) {\n readinessDeferrals.recordRecoveryGeneration(activationChild, recoveryGeneration);\n }\n void verifyChildHealth(\n activationChild,\n Number.isInteger(recoveryGeneration),\n Number.isInteger(recoveryGeneration) ? 'deferred control recovery' : 'initial child',\n );\n\n if (!(await finishPendingActivation({\n client,\n child: activationChild,\n runtimeRoot,\n operatorId,\n runnerId,\n selfPath,\n packageVersion: supervisorVersion,\n supervisorIdentity: supervisorControlIdentity,\n waitForLocalRunner,\n isReadinessDeferred: isChildReadinessDeferred,\n localStatus,\n stopChild: stopChildExpectedly,\n launchPreviousChild: (entry) => spawnPreviousChild(entry, childEnv),\n log: (message) => console.error(`[vo-runner supervisor] ${message}`),\n }))) {\n // A child-reported GitHub embargo is not an activation verdict. Its exact\n // exit handler re-opened admission, so leave the pending slot durable and\n // retry attestation only after that deadline.\n if (captureChildReadinessDeferral(activationChild)) {\n console.warn('[vo-runner supervisor] activation attestation deferred with GitHub readiness; pending slot remains durable');\n return false;\n }\n // DO NOT EXIT HERE. The control-action poll loop below is the ONLY remote\n // repair channel this host has \u2014 the daemon never opens an inbound port by\n // design. Degrade instead: refuse to SERVE work, but stay available to BE FIXED.\n markSupervisorDegraded();\n await stopChildExpectedly(activationChild);\n if (child === activationChild) child = null;\n console.error('[vo-runner supervisor] activation FAILED \u2014 entering degraded mode: not serving tasks, still polling for remote control actions');\n return false;\n }\n return true;\n };\n\n const attemptInitialChildStart = async () => {\n if (startupDeferral.hasStarted() || startupDeferral.isPending()) return false;\n const beforeRefresh = resolveSupervisorChildStartAuthority({\n degradationState,\n deferredRecoveryGeneration: deferredControlRecoveryGeneration,\n });\n if (!beforeRefresh.allowed) return false;\n if (startupNeedsReadinessRefresh) {\n try {\n if (!(await refreshSupervisorChildAdmission())) return false;\n } catch (error) {\n markSupervisorDegraded();\n deferredControlRecoveryGeneration = null;\n startupDeferral.consumeIfReady();\n console.error(\n `[vo-runner supervisor] deferred readiness refresh failed; entering degraded mode: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n return false;\n }\n }\n const afterRefresh = resolveSupervisorChildStartAuthority({\n degradationState,\n deferredRecoveryGeneration: deferredControlRecoveryGeneration,\n });\n if (!afterRefresh.allowed) return false;\n if (!startupDeferral.consumeIfReady()) return false;\n deferredControlRecoveryGeneration = null;\n return startInitialChild(afterRefresh.recoveryGeneration);\n };\n\n await attemptInitialChildStart();\n\n const shutdown = async () => {\n if (stopping) return;\n stopping = true;\n await stopChild(child);\n };\n process.on('SIGINT', () => { void shutdown().finally(() => process.exit(0)); });\n process.on('SIGTERM', () => { void shutdown().finally(() => process.exit(0)); });\n\n while (!stopping) {\n try {\n await attemptInitialChildStart();\n const action = await client.pollRunnerControl({\n runnerId,\n ...(operatorId ? { operatorId } : {}),\n ...supervisorControlIdentity,\n });\n if (!action) {\n await sleep(POLL_MS);\n continue;\n }\n // Any newer control action supersedes delayed recovery authority from an\n // earlier action. A fresh exact-action fence may establish a new one.\n deferredControlRecoveryGeneration = null;\n handling = true;\n const controlIdentity = { runnerId, ...(operatorId ? { operatorId } : {}), ...supervisorControlIdentity };\n // D9 (incident 2026-08-30): an update restart must DRAIN in-flight tasks\n // first, and at the cap must name itself on every task it kills.\n const bundledAction = action.kind === 'update' || action.kind === 'reinstall';\n const drain = await awaitRunnerUpdateDrain({\n readStatus: localStatus, drainable: bundledAction, env: process.env,\n isChildRunning: () => supervisorChildIsRunning(child),\n failInFlightTask: (taskId, patch) => client.postProgress(taskId, { status: 'failed', message: patch.message, result: patch.result, ...(patch.runnerId ? { runner_id: patch.runnerId } : {}), ...(patch.runnerInstanceId ? { runner_instance_id: patch.runnerInstanceId } : {}) }),\n log: (message) => console.warn(`[vo-runner supervisor] ${message}`),\n });\n if (!drain.proceed) {\n await client.completeRunnerControl(action.actionId, { ...controlIdentity, status: 'failed', detail: drain.detail });\n handling = false;\n respawn();\n continue;\n }\n controlRecoveryFence.markBeforeStop(child);\n await stopChildExpectedly(child);\n const result = bundledAction\n ? stageAndActivateBundledUpdate({\n runtimeRoot,\n packageSpec: `@algosuite/vo-mcp@${action.desired_package_version}`,\n expectedVersion: action.desired_package_version,\n expectedIntegrity: action.desired_package_integrity,\n action: {\n actionId: action.actionId,\n runnerId,\n operatorId: operatorId || '',\n supervisorInstanceId,\n },\n env: process.env,\n force: action.kind === 'reinstall',\n })\n : action.kind === 'purge-orphans'\n ? runLegacyOrphanSweep({\n protectedPids: [process.pid],\n log: (message) => console.warn(`[vo-runner supervisor] ${message}`),\n })\n : runHostMaintenance(action.kind, {\n env: clientEnv,\n log: (message) => console.warn(`[vo-runner supervisor] ${message}`),\n });\n if (result.ok && result.handoff) {\n if (drain.capped) console.warn(`[vo-runner supervisor] ${drain.detail}`);\n console.warn(`[vo-runner supervisor] activated ${result.active.version}; exiting for new-process attestation`);\n return;\n }\n // The normal action path consumes any exact-child fence before awaiting,\n // so reporting errors cannot trigger it again. A childless pre-existing\n // degradation requires a successful repair/reconnect action; cleanup or\n // failed maintenance cannot silently re-enable service.\n const recoveryAuthorized = shouldRecoverSupervisorChildAfterAction({\n stoppedChild: controlRecoveryFence.consume(),\n actionKind: action.kind,\n actionSucceeded: result.ok,\n });\n const relaunchedHealthy = recoveryAuthorized\n ? await ensureHealthyChildAfterControl()\n : false;\n if (!relaunchedHealthy) result.ok = false;\n await client.completeRunnerControl(action.actionId, {\n ...controlIdentity,\n status: result.ok ? 'succeeded' : 'failed',\n detail: result.ok\n ? (result.detail ? `${result.detail}; runner ${packageVersion()} reconnected`.slice(0, 1000) : `runner ${packageVersion()} reconnected`)\n : `maintenance exited ${result.status}${result.detail ? `: ${result.detail}` : ''}${\n relaunchedHealthy ? '' : '; runner relaunch did not become healthy'\n }`,\n });\n handling = false;\n respawn();\n } catch (error) {\n console.error(`[vo-runner supervisor] ${error instanceof Error ? error.message : String(error)}`);\n // Recover only when this exact control iteration fenced a live child\n // before stopping it. Poll/defer/reporting failures have no such token\n // and must not clear a pre-existing activation or breaker degradation.\n await controlRecoveryFence.recoverOnce(() => ensureHealthyChildAfterControl());\n handling = false;\n await sleep(POLL_MS);\n }\n }\n}\n\nmain().catch((error) => {\n console.error(`[vo-runner supervisor] fatal: ${error instanceof Error ? error.message : String(error)}`);\n process.exitCode = 1;\n});\n", "/**\n * GitHub App installation-token minting for the runner (M3).\n *\n * Split out of control-plane-client.mjs, which sits at its 400-line cap.\n *\n * The control plane keys the mint on the authenticated operator\n * (ctx.operator_id), so a token covers only that operator's installation.\n *\n * Two distinct grants come out of here:\n * - the DEFAULT full grant, used by the daemon to push and run `gh pr create`.\n * It only works if the App grants BOTH `Contents: write` and\n * `Pull requests: write` \u2014 see docs/vo/github-app-setup-2026-06-18.md.\n * - a READ-ONLY grant (`readOnly: true`), used for the token handed to an\n * agent process so it can read a PRIVATE repo without being able to publish.\n */\n\n/** Ceiling for the OPTIONAL read-token mint, so a hung plane can't stall a task. */\nconst READ_TOKEN_TIMEOUT_MS = 15_000;\n\n/**\n * @param {object} opts\n * @param {(method: string, path: string, body?: unknown) => Promise<Response>} opts.req\n * @param {boolean} [opts.required] fail closed instead of returning null on a miss\n * @param {boolean} [opts.readOnly] ask for a narrowed, non-publishing grant\n * @param {string|null} [opts.repo] narrow the grant to this one `owner/name`\n * @returns {Promise<{ token: string, expiresAt: string | null } | null>}\n */\nexport async function fetchInstallationToken({ req, required = false, readOnly = false, repo = null }) {\n const fail = (reason) => {\n if (required) throw new Error(`installation-token required: ${reason}`);\n return null;\n };\n try {\n // The read-only grant gets a longer explicit ceiling. The client also\n // supplies its default task-request ceiling for the publish mint; required\n // mode propagates that timeout and therefore cannot silently fall back.\n const res = await req(\n 'POST',\n '/api/v1/github/installation-token',\n readOnly ? { scope: 'read', ...(repo ? { repo } : {}) } : {},\n readOnly ? { timeoutMs: READ_TOKEN_TIMEOUT_MS } : {},\n );\n if (!res.ok) return fail(`HTTP ${res.status}`);\n const json = await res.json();\n if (!json || !json.token) return fail('missing token');\n // Fail CLOSED when a read-only grant can't be confirmed. The runner and the\n // control plane deploy independently, so a new runner can reach an older\n // revision that ignores `scope` and hands back a FULL write token. Injecting\n // that into an agent process is the exact failure this token exists to\n // prevent, so drop it: no token is the safe, pre-change state.\n if (readOnly && json.scope !== 'read') return fail('control plane did not confirm a read-only grant');\n // ci_readable (plane 2026-08-16): false while the App installation has not\n // accepted checks:read/statuses:read \u2014 the watcher logs it so the gap is visible.\n return { token: json.token, expiresAt: json.expires_at || null, ...(typeof json.ci_readable === 'boolean' ? { ciReadable: json.ci_readable } : {}) };\n } catch (err) {\n if (required) throw err;\n return null;\n }\n}\n", "/**\n * control-plane-heartbeat-body \u2014 the runner heartbeat's request body, built pure.\n *\n * Split out of `control-plane-client.mjs` on 2026-09-04 (PR #10336 steward pass)\n * when that module crossed its 400-line VO orchestration cap. The construction\n * is the part worth isolating anyway: it is pure, it is the exact surface the\n * plane's strict schema validates, and every field here is OMITTED rather than\n * sent null \u2014 a null on this route is a 400, and the 2026-07-25 outage was hours\n * of diagnosis because a rejected field looked identical to a powered-off host.\n *\n * Adding a field is therefore a three-place change, all in the same PR: this\n * builder, the plane's `runner-heartbeat-v1` schema, and the status type the\n * dashboard reads. The lockstep test pins that.\n */\n\n/**\n * @param {object} input heartbeat inputs as the daemon's loop tick collects them.\n * @returns {object} the wire body, with absent/empty fields omitted.\n */\nexport function buildRunnerHeartbeatBody({\n runnerId,\n runnerInstanceId,\n operatorId,\n uptimeSec,\n activeTasks,\n maxConcurrency,\n effectiveConcurrency,\n measuredTaskSlots,\n measuredCpuSlots,\n measuredMemorySlots,\n version,\n daemonVersion,\n nodeVersion,\n defaultAgent,\n supervisorInstanceId,\n supervisorVersion,\n supervisorCapabilities,\n servedRepos,\n servedOperators,\n availableAgents,\n accountUsage,\n availableLocalModels,\n prepared_job_shadow: preparedJobShadow,\n} = {}) {\n // ADR-004 \u00A7 11.1b-2 counts-only tally rides along when the shadow pass produced one.\n const body = { runner_id: runnerId, ...(preparedJobShadow ? { prepared_job_shadow: preparedJobShadow } : {}) };\n if (runnerInstanceId) body.runner_instance_id = runnerInstanceId;\n if (operatorId) body.operator_id = operatorId;\n if (typeof uptimeSec === 'number') body.uptime_sec = uptimeSec;\n if (typeof activeTasks === 'number') body.active_tasks = activeTasks;\n if (typeof maxConcurrency === 'number') body.max_concurrency = maxConcurrency;\n if (typeof effectiveConcurrency === 'number') body.effective_concurrency = effectiveConcurrency;\n if (typeof measuredTaskSlots === 'number') body.measured_task_slots = measuredTaskSlots;\n if (typeof measuredCpuSlots === 'number') body.measured_cpu_slots = measuredCpuSlots;\n if (typeof measuredMemorySlots === 'number') body.measured_memory_slots = measuredMemorySlots;\n if (version) body.version = version;\n if (daemonVersion) body.daemon_version = daemonVersion;\n // The Node runtime this daemon RUNS on, so a runtime-level abort is\n // attributable to a build. Public version string only, no host detail.\n if (nodeVersion) body.node_version = nodeVersion;\n if (defaultAgent) body.default_agent = defaultAgent;\n if (supervisorInstanceId) body.supervisor_instance_id = supervisorInstanceId;\n if (supervisorVersion) body.supervisor_version = supervisorVersion;\n if (Array.isArray(supervisorCapabilities) && supervisorCapabilities.length > 0) {\n body.supervisor_capabilities = supervisorCapabilities;\n }\n if (Array.isArray(servedRepos) && servedRepos.length > 0) body.served_repos = servedRepos;\n if (Array.isArray(servedOperators) && servedOperators.length > 0) {\n body.served_operator_ids = servedOperators;\n }\n if (Array.isArray(availableAgents) && availableAgents.length > 0) {\n body.available_agents = availableAgents;\n }\n if (Array.isArray(accountUsage) && accountUsage.length > 0) {\n body.account_usage = accountUsage;\n }\n if (Array.isArray(availableLocalModels) && availableLocalModels.length > 0) {\n body.available_local_models = availableLocalModels;\n }\n return body;\n}\n", "/**\n * F35 (2026-08-17): ask the plane to mark a PARTIAL draft READY once its lineage cannot continue\n * and CI is green (`POST /api/v1/admin/pr/promote-draft`, admin-only \u2014 the plane-side sweep is\n * the caller). The plane re-checks every precondition server-side and never merges; the ordinary\n * receipt-gated merge decides afterwards. Errors carry the plane's status + code like resume.\n */\nexport async function promoteDraftPrRequest(req, prNumber, automationContext, onUnauthorized = () => {}) {\n const res = await req('POST', '/api/v1/admin/pr/promote-draft', { prNumber, automationContext }, { timeoutMs: 60_000 });\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('promote-draft unauthorized (401)');\n }\n const json = await res.json().catch(() => ({}));\n if (res.ok && json?.ok === true) {\n return {\n status: json.promoted === true ? (json.auto_merge_disarmed === true ? 'promoted (auto-merge disarmed)' : 'promoted') : json.already_ready === true ? 'already_ready' : 'unchanged',\n headSha: typeof json.head_sha === 'string' ? json.head_sha : null,\n reason: typeof json.blocked_reason === 'string' ? json.blocked_reason : null,\n };\n }\n const code = typeof json?.error === 'string' ? json.error : null;\n const err = new Error(`promote-draft failed: HTTP ${res.status}${code ? ` (${code})` : ''}${json?.reason ? ` \u2014 ${json.reason}` : ''}`);\n err.status = res.status;\n err.code = code;\n throw err;\n}\n", "const PAGE_SIZE = 500;\n\n/** Paginate the runner-only raw adoption view; it deliberately skips PR reconciliation. */\nexport async function listAllPrOpenedTasks(request) {\n const tasks = [];\n let beforeCreatedAt = '';\n let beforeId = '';\n for (;;) {\n const params = new URLSearchParams({\n status: 'pr_opened', limit: String(PAGE_SIZE), runner_adoption: '1',\n });\n if (beforeCreatedAt) {\n params.set('before_created_at', beforeCreatedAt);\n params.set('before_id', beforeId);\n }\n const res = await request('GET', `/api/v1/code-task?${params}`);\n if (!res.ok) throw new Error(`listPrOpenedTasks failed: HTTP ${res.status}`);\n const json = await res.json();\n const page = Array.isArray(json?.tasks) ? json.tasks : [];\n tasks.push(...page);\n if (page.length < PAGE_SIZE) return tasks;\n const last = page.at(-1);\n if (!last?.created_at || !last?.code_task_id) {\n throw new Error('listPrOpenedTasks pagination cursor missing');\n }\n beforeCreatedAt = last.created_at;\n beforeId = last.code_task_id;\n }\n}\n", "export async function resumeCodeTaskRequest(\n req,\n taskId,\n { automaticRateLimit = false, automaticContinuation = false } = {},\n onUnauthorized = () => {},\n) {\n const res = await req(\n 'POST',\n `/api/v1/code-task/${encodeURIComponent(taskId)}/resume`,\n automaticRateLimit\n ? { automatic_rate_limit: true }\n : automaticContinuation ? { automatic_continuation: true } : {},\n );\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('resume unauthorized (401)');\n }\n if (!res.ok) {\n // Carry the plane's refusal code so the watcher can tell a TERMINAL refusal\n // (budget too small / ceiling reached / exhausted \u2014 no retry will ever\n // succeed) from a transient coordination failure it should back off on.\n let code = null;\n try {\n const body = await res.json();\n code = typeof body?.error === 'string' ? body.error : null;\n } catch { /* non-JSON body: keep code null */ }\n const err = new Error(`resume failed: HTTP ${res.status}${code ? ` (${code})` : ''}`);\n err.status = res.status;\n err.code = code;\n throw err;\n }\n const json = await res.json();\n const task = json && json.task ? json.task : null;\n // A 200 with an EXISTING active child (`deduplicated: true`) is not a new continuation; the flag\n // rides along non-enumerably so persisted/logged task shapes stay byte-identical.\n if (task && typeof json.deduplicated === 'boolean') Object.defineProperty(task, 'deduplicated', { value: json.deduplicated, enumerable: false });\n return task;\n}\n", "export function makeAutonomousDispatchAdmissionClient(req, timeoutMs, onUnauthorized = () => {}) {\n return {\n async reserveAutonomousDispatchBudget({ requestedBudgetUsd, reservationId, occurrenceKey }) {\n const res = await req('POST', '/api/v1/autonomous-dispatch/admission', {\n requested_budget_usd: requestedBudgetUsd,\n reservation_id: reservationId,\n dispatch_occurrence_key: occurrenceKey,\n }, { timeoutMs });\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('autonomous dispatch admission unauthorized (401)');\n }\n if (!res.ok) throw new Error(`autonomous dispatch admission failed: HTTP ${res.status}`);\n const body = await res.json();\n return {\n allowed: body?.allowed === true,\n reason: typeof body?.reason === 'string' ? body.reason : '',\n };\n },\n\n async releaseAutonomousDispatchBudget(reservationId) {\n const res = await req('POST', '/api/v1/autonomous-dispatch/reservation/release', {\n reservation_id: reservationId,\n }, { timeoutMs });\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('autonomous dispatch release unauthorized (401)');\n }\n if (!res.ok) throw new Error(`autonomous dispatch release failed: HTTP ${res.status}`);\n return true;\n },\n };\n}\n", "export async function mergeVerifiedPrRequest(req, prNumber, automationContext, onUnauthorized) {\n const res = await req(\n 'POST', '/api/v1/admin/pr/merge', { prNumber, automationContext }, { timeoutMs: 120_000 },\n );\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('gated merge unauthorized (401)');\n }\n const json = await res.json().catch(() => ({}));\n if (res.ok && json?.ok === true) {\n const result = json?.result && typeof json.result === 'object' ? json.result : {};\n const status = result.merged === true || result.status === 'merged'\n ? 'merged'\n : result.status === 'auto-merge-enabled' || String(result.action || '').includes('auto-merge')\n ? 'queued'\n : 'accepted';\n return {\n status,\n detail: typeof result.detail === 'string' ? result.detail : null,\n actionReceiptId: typeof json.action_receipt_id === 'string' ? json.action_receipt_id : null,\n };\n }\n const captureStoreRetry = json?.action_status === 'not_attempted'\n && (json?.error === 'capture_preflight_unavailable'\n || json?.error === 'decision_outcome_intent_failed');\n if (res.status === 503\n && (json?.error === 'verify_unavailable' || json?.error === 'merge_unavailable'\n || captureStoreRetry)) {\n return { status: 'retry', reason: json.reason || json.message || json.error || 'verification unavailable' };\n }\n return {\n status: 'blocked',\n reason: json?.reason || json?.message || json?.error || `HTTP ${res.status}`,\n actionReceiptId: typeof json?.action_receipt_id === 'string' ? json.action_receipt_id : null,\n };\n}\n", "/**\n * control-plane-weekly-tokens \u2014 `POST /api/v1/weekly-tokens` request helper,\n * extracted from control-plane-client.mjs (at its 400-line cap) so the client\n * could grow a sibling telemetry-relay method. Behaviour is unchanged.\n *\n * Report this machine's rolling-7-day Claude Code token usage (the real\n * weekly-capacity gauge) PLUS the operator's real Claude weekly % (when\n * available). The daemon authenticates as admin, so the target `operatorId`\n * is named explicitly. Best-effort; throws on a non-2xx so the caller can\n * log + move on.\n *\n * `tokens` = { input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens }.\n * Optional: `claudeWeeklyPct` (number) + `claudeWeeklyResetsAt` (ISO string | null).\n */\nexport async function postWeeklyTokensRequest(\n taskReq,\n { operatorId, runnerId, tokens, claudeWeeklyPct, claudeWeeklyResetsAt },\n onUnauthorized = () => {},\n) {\n const body = {\n operator_id: operatorId,\n runner_id: runnerId,\n input_tokens: tokens.input_tokens,\n output_tokens: tokens.output_tokens,\n cache_creation_tokens: tokens.cache_creation_tokens,\n cache_read_tokens: tokens.cache_read_tokens,\n };\n if (typeof claudeWeeklyPct === 'number') {\n body.claude_weekly_pct = claudeWeeklyPct;\n }\n if (claudeWeeklyResetsAt !== undefined) {\n body.claude_weekly_resets_at = claudeWeeklyResetsAt;\n }\n const res = await taskReq('POST', '/api/v1/weekly-tokens', body);\n if (res.status === 401) {\n onUnauthorized();\n throw new Error('weekly-tokens unauthorized (401)');\n }\n if (!res.ok) throw new Error(`weekly-tokens failed: HTTP ${res.status}`);\n return true;\n}\n", "/**\n * control-plane-telemetry-relay \u2014 `POST /api/v1/telemetry/relay` request\n * helper for the runner's telemetry forwarder (telemetry-forwarder.mjs).\n *\n * The daemon never holds the vo-telemetry ingest token: it hands a batch of\n * local vo-mcp events to the control plane, which relays each one to\n * vo-telemetry and returns per-event results (a PREFIX of the batch \u2014 the\n * relay halts on the first upstream fault so the forwarder's byte cursor can\n * never advance past an event the store did not accept).\n *\n * Returns `{ status, body }` and never throws on HTTP status \u2014 the forwarder\n * owns the backoff/disable policy. Network errors DO throw (fetch rejects).\n * A 30 s timeout covers up to MAX_EVENTS_PER_RELAY sequential upstream POSTs.\n */\nexport const TELEMETRY_RELAY_TIMEOUT_MS = 30_000;\n\nexport async function relayTelemetryEventsRequest(req, { events, source }, onUnauthorized = () => {}) {\n const res = await req('POST', '/api/v1/telemetry/relay', { events, ...(source ? { source } : {}) }, {\n timeoutMs: TELEMETRY_RELAY_TIMEOUT_MS,\n });\n if (res.status === 401) onUnauthorized();\n let body = null;\n try { body = await res.json(); } catch { body = null; }\n return { status: res.status, body };\n}\n", "// Runner-side display of the control plane's claim-admission gate (2026-08-15).\n//\n// The claim route answers a DENIED runner with the benign queue-empty shape\n// (`task: null`) plus a `claim_gate` reason \u2014 by design, so pre-gate daemons keep\n// polling instead of crashing. Before this module the daemon dropped that field\n// on the floor and a below-target runner simply looked idle forever (\"no\n// pending task\" every 5s) with nothing on the host saying WHY. Now the reason is\n// logged once per distinct verdict (not every poll) and kept for /status.\n//\n// Pure apart from the injected `log`; the daemon's claim loop stays untouched.\n\nconst REASON_HELP = {\n daemon_version_below_floor: 'this daemon is older than the approved release target \u2014 it idles until the governed updater brings it current (operator override: VO_RUNNER_CLAIM_MIN_DAEMON_VERSION / VO_RUNNER_CLAIM_VERSION_GATE=off on the control plane)',\n daemon_version_unreported: 'this daemon reports no parseable version in its heartbeat \u2014 too old for the updater to manage, so it may not claim work',\n no_fresh_heartbeat: 'the control plane has no fresh heartbeat from this runner \u2014 claims resume once heartbeats land',\n runner_denylisted: 'this runner id is on the operator quarantine list (VO_RUNNER_CLAIM_DENYLIST)',\n};\n\nexport function describeClaimGate(gate) {\n if (!gate || gate.allowed !== false) return null;\n const reason = String(gate.reason || 'denied');\n const floor = gate.floor_version ? ` (floor ${gate.floor_version})` : '';\n return `claim gate: DENIED \u2014 ${reason}${floor}: ${(Object.hasOwn(REASON_HELP, reason) ? REASON_HELP[reason] : null) ?? 'the control plane refused this runner\\'s claims'}`;\n}\n\n/**\n * Track the latest verdict and log only on change (denied\u2192allowed logs the recovery too).\n * @returns {{ current: () => (object|null), observe: (json: unknown) => void }}\n */\nexport function makeClaimGateNotice({ log = () => {} } = {}) {\n let last = null; // last DENIED verdict signature, or null when allowed\n let current = null;\n return {\n current: () => current,\n observe(json) {\n const gate = json && typeof json === 'object' ? json.claim_gate : null;\n const denied = gate && gate.allowed === false ? gate : null;\n current = denied ? { ...denied, observed_at: new Date().toISOString() } : null;\n const signature = denied ? `${denied.reason}|${denied.floor_version ?? ''}` : null;\n if (signature === last) return;\n if (denied) log(describeClaimGate(denied));\n else if (last !== null) log('claim gate: allowed again \u2014 this runner may claim work');\n last = signature;\n },\n };\n}\n", "/**\n * getTaskKnowledgeContext resilience.\n *\n * Incident 2026-08-29: tasks 8ca414ed (05:11:57Z) and eb5fd089 (05:28Z) both\n * failed at preparing_worktree because the knowledge-context fetch timed out\n * at the shared 5000ms task-request cap while the server itself measured\n * 3.4s/4.9s/6.99s over the same window (an embeddings leg was added\n * 2026-08-27). A single 5s-capped attempt was a coin flip. The fail-closed\n * refusal in task-prompt.mjs is deliberate and stays \u2014 this module only\n * widens the single attempt into a per-endpoint timeout floor plus a bounded\n * retry, so a slow-but-healthy server response is no longer indistinguishable\n * from a hung one. Every other control-plane endpoint is untouched and keeps\n * its original single-attempt policy.\n */\n\nexport const MIN_KNOWLEDGE_CONTEXT_TIMEOUT_MS = 15_000;\nconst RETRY_DELAYS_MS = [2_000, 6_000];\nconst MAX_ATTEMPTS = RETRY_DELAYS_MS.length + 1;\n\nfunction isRetryableStatus(status) {\n return status >= 500 && status <= 599;\n}\n\nfunction defaultSleep(ms) {\n return new Promise((resolve) => { setTimeout(resolve, ms); });\n}\n\n/**\n * `req` is the control-plane client's low-level request function:\n * `(method, path, body, { timeoutMs }) => Promise<Response-like>`. It throws\n * on timeout or transport failure and resolves (never rejects) for any HTTP\n * status, including 4xx/5xx \u2014 matching `control-plane-client.mjs`'s `req()`.\n */\nexport async function getTaskKnowledgeContextRequest(req, taskId, { query } = {}, {\n taskRequestTimeoutMs,\n invalidateToken = () => {},\n sleep = defaultSleep,\n log = () => {},\n} = {}) {\n const body = {};\n if (typeof query === 'string' && query.trim()) body.query = query;\n const path = `/api/v1/code-task/${encodeURIComponent(taskId)}/knowledge-context`;\n const timeoutMs = Math.max(Number(taskRequestTimeoutMs) || 0, MIN_KNOWLEDGE_CONTEXT_TIMEOUT_MS);\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {\n let res;\n let cause;\n try {\n res = await req('POST', path, body, { timeoutMs });\n } catch (err) {\n cause = err;\n }\n if (!cause) {\n if (res.status === 401) {\n invalidateToken();\n throw new Error('knowledge-context unauthorized (401)');\n }\n if (res.status === 404) return null;\n if (res.ok) return res.json();\n if (!isRetryableStatus(res.status)) {\n throw new Error(`knowledge-context failed: HTTP ${res.status}`);\n }\n cause = new Error(`knowledge-context failed: HTTP ${res.status}`);\n }\n if (attempt === MAX_ATTEMPTS) throw cause;\n const delayMs = RETRY_DELAYS_MS[attempt - 1];\n log(`knowledge-context attempt ${attempt}/${MAX_ATTEMPTS} failed (${cause.message}); retrying in ${delayMs}ms`);\n await sleep(delayMs);\n }\n /* c8 ignore next */\n throw new Error('knowledge-context retry loop exited unexpectedly');\n}\n", "/**\n * control-plane-prepared-job \u2014 ADR-004 \u00A7 11.1 slice B, the fetch half.\n *\n * Reads the plane's PREPARED JOB for one code task from\n * `GET /api/v1/code-task/:id/prepared-job` (shipped DARK in slice A, PR #10218)\n * so the runner can compare it against its OWN local composition.\n *\n * SHADOW-ONLY: nothing here may change what the runner spawns. This module\n * therefore NEVER throws. Every fault \u2014 transport, timeout, 401, the 409\n * `router_mode_unsupported` refusal, a 5xx, a non-JSON body \u2014 comes back as a\n * structured refusal the caller records as a shadow observation. A dispatch is\n * never failed by a shadow read.\n */\n\n/**\n * Runner-local env knobs the plane must be TOLD about; it does not share the\n * runner's process.\n *\n * This list MUST stay byte-identical to `ENV_QUERY_KEYS` in\n * `cloud-run/vo-control-plane/src/routes/code-task-prepared-job.ts`. A key\n * present on one side only makes the plane compose a DIFFERENT job for a\n * reason that has nothing to do with drift \u2014 which is exactly the signal this\n * slice exists to measure, so the two lists are pinned equal by\n * prepared-job-shadow.test.mjs rather than left to review.\n */\nexport const PREPARED_JOB_ENV_QUERY_KEYS = [\n 'VO_CODE_RUNNER_NO_WEB',\n 'VO_CODE_RUNNER_NO_WORKFLOW',\n 'VO_CODE_RUNNER_NO_CONSENSUS',\n 'VO_CODE_RUNNER_PERMISSION_MODE',\n 'VO_CODE_RUNNER_DEFAULT_BUDGET_USD',\n 'VO_CODE_RUNNER_META_REASONING_EFFORT',\n 'VO_CODE_RUNNER_ALLOW_MISSING_KNOWLEDGE_CONTEXT',\n 'VO_ENABLE_CONTEXT7',\n];\n\n/** The plane accepts a query env value only when 0 < length <= 64 (same route). */\nexport const PREPARED_JOB_ENV_VALUE_MAX = 64;\n\n/**\n * Build the query string for one prepared-job read.\n *\n * Returns `{ query, sent, dropped }`. `dropped` names any allow-listed key the\n * runner HAS set but the plane will refuse for length \u2014 a real divergence\n * cause that must be visible in the record rather than inferred from a\n * mismatching prompt.\n */\nexport function preparedJobQuery({ agent = 'claude', env = {} } = {}) {\n const params = new URLSearchParams();\n params.set('agent', String(agent));\n const sent = [];\n const dropped = [];\n for (const key of PREPARED_JOB_ENV_QUERY_KEYS) {\n const raw = env?.[key];\n if (typeof raw !== 'string' || raw.length === 0) continue;\n if (raw.length > PREPARED_JOB_ENV_VALUE_MAX) { dropped.push(key); continue; }\n params.set(key, raw);\n sent.push(key);\n }\n return { query: params.toString(), sent, dropped };\n}\n\n/** Read the plane's error code out of a non-2xx body without ever throwing. */\nasync function refusalCode(res) {\n try {\n const body = await res.json();\n return typeof body?.error === 'string' && body.error ? body.error : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Fetch the prepared job. Resolves to\n * { ok: true, job, composition, envSent, envDropped }\n * { ok: false, reason, status, envSent, envDropped }\n * and never rejects.\n *\n * @param {Function} req the control-plane client's raw request fn\n * @param {string} taskId\n * @param {object} [options] { agent, env, timeoutMs }\n * @param {Function} [invalidateToken] called on 401 so the next real call re-auths\n */\nexport async function getPreparedJobRequest(req, taskId, options = {}, invalidateToken = () => {}) {\n const { agent = 'claude', env = {}, timeoutMs = 15_000 } = options;\n const { query, sent, dropped } = preparedJobQuery({ agent, env });\n const envMeta = { envSent: sent, envDropped: dropped };\n if (typeof taskId !== 'string' || taskId.length === 0) {\n return { ok: false, reason: 'missing_task_id', status: 0, ...envMeta };\n }\n const path = `/api/v1/code-task/${encodeURIComponent(taskId)}/prepared-job?${query}`;\n let res;\n try {\n res = await req('GET', path, undefined, { timeoutMs });\n } catch (err) {\n return { ok: false, reason: `transport: ${err?.message || String(err)}`, status: 0, ...envMeta };\n }\n if (res?.status === 401) {\n try { invalidateToken(); } catch { /* shadow-only */ }\n return { ok: false, reason: 'unauthorized', status: 401, ...envMeta };\n }\n if (!res?.ok) {\n const code = await refusalCode(res);\n return { ok: false, reason: code || `http_${res?.status ?? 'unknown'}`, status: res?.status ?? 0, ...envMeta };\n }\n let body;\n try {\n body = await res.json();\n } catch (err) {\n return { ok: false, reason: `unreadable_body: ${err?.message || String(err)}`, status: res.status, ...envMeta };\n }\n const job = body?.prepared_job;\n if (!job || typeof job !== 'object') {\n return { ok: false, reason: 'no_prepared_job_in_body', status: res.status, ...envMeta };\n }\n return {\n ok: true,\n job,\n composition: body?.composition && typeof body.composition === 'object' ? body.composition : {},\n ...envMeta,\n };\n}\n", "/**\n * control-plane-client \u2014 the runner's OUTBOUND link to vo-control-plane.\n *\n * Increment 6 (Code-from-Anywhere). The daemon never exposes a port; it reaches\n * OUT to the control-plane (no inbound hole, no Tailscale \u2014 design \u00A72). Auth:\n * prefer the static admin token (`VO_CONTROL_PLANE_ADMIN_TOKEN`, the V1 local\n * dogfood path); fall back to a per-user Firebase ID token via the shared\n * orchestrator auth (`SMOKE_*` creds \u2192 allow-listed operator \u2192 admin).\n *\n * Covers task claim/progress/context/private attachments/resume and governed merge.\n */\n\nimport { fetchInstallationToken } from './installation-token.mjs';\nimport { buildRunnerHeartbeatBody } from './control-plane-heartbeat-body.mjs';\nimport { promoteDraftPrRequest } from './control-plane-promote.mjs';\nimport { listAllPrOpenedTasks } from './control-plane-task-list.mjs';\nimport { resumeCodeTaskRequest } from './control-plane-resume.mjs';\nimport { makeAutonomousDispatchAdmissionClient } from './control-plane-autonomous-admission.mjs';\nimport { mergeVerifiedPrRequest } from './control-plane-merge.mjs';\nimport { postWeeklyTokensRequest } from './control-plane-weekly-tokens.mjs';\nimport { relayTelemetryEventsRequest } from './control-plane-telemetry-relay.mjs';\nimport { makeClaimGateNotice } from './claim-gate-notice.mjs';\nimport { getTaskKnowledgeContextRequest } from './control-plane-knowledge-context.mjs'; import { getPreparedJobRequest } from './control-plane-prepared-job.mjs';\n\nlet cachedFirebaseToken = null;\nexport class ClaimAuthorityChangedError extends Error {\n constructor() {\n super('code-task claim authority changed');\n this.name = 'ClaimAuthorityChangedError'; this.code = 'code_task_claim_authority_changed';\n }\n}\n\nasync function resolveBearer(env) {\n const adminToken = env.VO_CONTROL_PLANE_ADMIN_TOKEN;\n if (adminToken) return adminToken;\n if (cachedFirebaseToken) return cachedFirebaseToken;\n // Lazy import \u2014 Firebase auth is only needed when no admin token is present.\n const { getFirebaseAuth } = await import('../orchestrator-firestore/auth.mjs');\n const auth = await getFirebaseAuth({ env });\n if (!auth || !auth.idToken) {\n throw new Error(\n 'no control-plane credential: set VO_CONTROL_PLANE_ADMIN_TOKEN, or SMOKE_EMAIL/SMOKE_PASSWORD/SMOKE_API_KEY',\n );\n }\n cachedFirebaseToken = auth.idToken;\n return cachedFirebaseToken;\n}\n\n/**\n * Build a client. `baseUrl` defaults to `env.VO_CONTROL_PLANE_URL`. `fetchImpl`,\n * `env`, and `sleep` (the retry backoff delay function) are injectable for\n * tests and packaged runner handoff.\n */\nexport function createControlPlaneClient({\n baseUrl,\n env = process.env,\n fetchImpl = fetch,\n heartbeatTimeoutMs = Math.min(\n Math.max(Number(env.VO_CODE_RUNNER_HEARTBEAT_TIMEOUT_MS) || 15_000, 1_000),\n 60_000,\n ),\n taskRequestTimeoutMs = Math.min(\n Math.max(Number(env.VO_CODE_RUNNER_TASK_REQUEST_TIMEOUT_MS) || 5_000, 100),\n 60_000,\n ),\n runnerId,\n runnerInstanceId,\n sleep,\n} = {}) {\n const resolvedBaseUrl = baseUrl ?? env.VO_CONTROL_PLANE_URL ?? '';\n if (!resolvedBaseUrl) throw new Error('VO_CONTROL_PLANE_URL is required for the code-runner daemon');\n const root = resolvedBaseUrl.replace(/\\/+$/, '');\n\n async function req(method, path, body, { timeoutMs } = {}) {\n const bearer = await resolveBearer(env);\n const controller = timeoutMs ? new AbortController() : null;\n let timeoutId;\n const request = Promise.resolve(fetchImpl(`${root}${path}`, {\n method,\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${bearer}`,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n ...(controller ? { signal: controller.signal } : {}),\n }));\n if (!timeoutMs) return request;\n const timeout = new Promise((_, reject) => {\n timeoutId = setTimeout(() => {\n controller.abort();\n reject(new Error(`control-plane ${path} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n try {\n return await Promise.race([request, timeout]);\n } finally {\n clearTimeout(timeoutId);\n }\n }\n const taskReq = (method, path, body, options = {}) => req(method, path, body, { timeoutMs: taskRequestTimeoutMs, ...options }); const claimGate = makeClaimGateNotice({ log: (m) => console.warn(`[code-runner ${new Date().toISOString()}] ${m}`) }); // deny-site visibility\n return { getClaimGate: () => claimGate.current(), // last DENIED claim-gate verdict (null when allowed) \u2014 for /status + tests\n ...makeAutonomousDispatchAdmissionClient(\n req, taskRequestTimeoutMs, () => { cachedFirebaseToken = null; },\n ),\n /**\n * Claim the next pending task. Returns the task or null (empty queue).\n * `repos` (optional `owner/name` list) and `operatorIds` (optional\n * `operator_id` list) scope the claim so this daemon only picks up tasks it\n * serves \u2014 the control-plane filters by both (logical AND), so another\n * operator's task never lands on (or bills) this machine.\n */\n async claim(runnerId, repos, operatorIds, session = {}) {\n const body = { runner_id: runnerId };\n if (Array.isArray(repos) && repos.length > 0) body.repos = repos;\n if (Array.isArray(operatorIds) && operatorIds.length > 0) body.operator_ids = operatorIds;\n if (session.runnerInstanceId) { body.runner_instance_id = session.runnerInstanceId; body.runner_progress_protocol_version = 2; }\n if (session.runnerInstanceId && session.reconcileStale) body.reconcile_stale = true;\n if (session.defaultAgent) body.default_agent = session.defaultAgent;\n if (Array.isArray(session.availableAgents)) {\n body.available_agents = session.availableAgents\n .filter((entry) => entry?.installed === true && entry?.authenticated === true)\n .map((entry) => entry.agent);\n }\n const res = await taskReq('POST', '/api/v1/code-task/claim', body);\n if (res.status === 401) {\n cachedFirebaseToken = null; // force re-auth next call\n throw new Error('claim unauthorized (401)');\n }\n if (!res.ok) throw new Error(`claim failed: HTTP ${res.status}`);\n const json = await res.json(); claimGate.observe(json); // 2026-08-15: a DENIED verdict is logged once + kept for /status instead of reading as an idle queue\n return json && json.task ? json.task : null;\n },\n\n /**\n * Enqueue a new code-task (used by the PR watcher to auto-dispatch a CI fix).\n * Server derives operator/tenant from the daemon's authenticated principal.\n * Returns the created task, or throws on a non-2xx response.\n */\n async enqueueCodeTask({ repo, prompt, max_budget_usd, max_turns, dispatch_mode, tier, agent, model, dispatch_occurrence_key, autonomous_reservation_id, on_behalf_of_operator_id, repair_pr_number, repair_kind, repair_head_sha, repair_chain }) {\n const body = { repo, prompt };\n if (typeof max_budget_usd === 'number') body.max_budget_usd = max_budget_usd;\n if (typeof max_turns === 'number') body.max_turns = max_turns;\n for (const [key, value] of Object.entries({ dispatch_mode, tier, agent, model, repair_kind, repair_head_sha })) {\n if (value) body[key] = value;\n }\n if (dispatch_occurrence_key) body.dispatch_occurrence_key = dispatch_occurrence_key;\n if (autonomous_reservation_id) body.autonomous_reservation_id = autonomous_reservation_id; if (on_behalf_of_operator_id) body.on_behalf_of_operator_id = on_behalf_of_operator_id;\n if (Number.isInteger(repair_pr_number) && repair_pr_number > 0) body.repair_pr_number = repair_pr_number;\n if (repair_chain) body.repair_chain = repair_chain;\n const res = await taskReq('POST', '/api/v1/code-task', body);\n if (res.status === 401) {\n cachedFirebaseToken = null;\n throw new Error('enqueue unauthorized (401)');\n }\n if (!res.ok) {\n // Carry the plane's refusal code (repair_not_needed / dispatch_occurrence_exists /\n // repair_state_unavailable / autonomous_reservation_invalid \u2026) so callers can tell a\n // policy answer from a real fault \u2014 same contract as control-plane-resume.mjs.\n let code = null;\n try { const errBody = await res.json(); code = typeof errBody?.error === 'string' ? errBody.error : null; } catch { /* non-JSON body */ }\n const err = new Error(`enqueue failed: HTTP ${res.status}${code ? ` (${code})` : ''}`);\n err.status = res.status; err.code = code;\n throw err;\n }\n const json = await res.json();\n const task = json && json.task ? json.task : null;\n // `deduplicated` (plane returned an EXISTING task for this occurrence/repair) rides along\n // non-enumerably so logs/persistence of the task stay byte-identical.\n if (task && typeof json.deduplicated === 'boolean') Object.defineProperty(task, 'deduplicated', { value: json.deduplicated, enumerable: false });\n return task;\n },\n\n /**\n * Resume a failed/cancelled/max-turn partial code-task. The PR watcher uses\n * this after the runner opens a partial draft PR and CI is no longer pending.\n */\n async resumeCodeTask(taskId, { automaticRateLimit = false, automaticContinuation = false } = {}) {\n return resumeCodeTaskRequest(taskReq, taskId, { automaticRateLimit, automaticContinuation }, () => {\n cachedFirebaseToken = null;\n });\n },\n\n /**\n * Send a CI-green PR through the production verify-before-act merge route.\n * The server inspects the current diff, applies deterministic blockers, runs\n * consensus, records a receipt, and direct-merges only the inspected SHA.\n */\n /** F35: promote a PARTIAL draft to READY via the plane (admin-only; server re-checks; never merges). */\n promoteDraftPr: (prNumber, automationContext) => promoteDraftPrRequest(req, prNumber, automationContext, () => { cachedFirebaseToken = null; }),\n async mergeVerifiedPr(prNumber, automationContext) {\n return mergeVerifiedPrRequest(\n req, prNumber, automationContext, () => { cachedFirebaseToken = null; },\n );\n },\n\n /**\n * Append progress / set terminal status. Returns\n * { task } \u2014 applied\n * { terminal: true } \u2014 task already terminal (operator cancelled): STOP\n */\n async postProgress(taskId, patch) {\n const progress = {\n ...patch,\n ...(patch.runner_id ? {} : runnerId ? { runner_id: runnerId } : {}),\n ...(patch.runner_instance_id ? {} : runnerInstanceId ? { runner_instance_id: runnerInstanceId } : {}),\n };\n const res = await taskReq('PATCH', `/api/v1/code-task/${taskId}/progress`, progress);\n if (res.status === 409) {\n const conflict = await res.json().catch(() => ({}));\n if (conflict?.error === 'code_task_claim_authority_changed') {\n throw new ClaimAuthorityChangedError();\n }\n return { terminal: true };\n }\n if (res.status === 404) return { terminal: true, missing: true };\n if (!res.ok) throw new Error(`progress failed: HTTP ${res.status}`);\n const json = await res.json();\n return { task: json && json.task };\n },\n\n async getTask(taskId) {\n const res = await taskReq('GET', `/api/v1/code-task/${taskId}`);\n if (res.status === 404) return null;\n if (!res.ok) throw new Error(`getTask failed: HTTP ${res.status}`);\n const json = await res.json();\n return json ? json.task : null;\n },\n async listPrOpenedTasks() {\n return listAllPrOpenedTasks(taskReq);\n },\n async downloadTaskAttachment(taskId, attachmentId) {\n const path = `/api/v1/code-task/${encodeURIComponent(taskId)}/attachment/${encodeURIComponent(attachmentId)}`;\n const res = await taskReq('GET', path);\n if (res.status === 401) cachedFirebaseToken = null;\n if (!res.ok) throw new Error(`attachment download failed: HTTP ${res.status}`);\n return Buffer.from(await res.arrayBuffer());\n },\n\n // Raised per-attempt timeout (>=15s) + bounded retry \u2014 see control-plane-knowledge-context.mjs.\n async getTaskKnowledgeContext(taskId, { query } = {}) {\n return getTaskKnowledgeContextRequest(req, taskId, { query }, {\n taskRequestTimeoutMs,\n invalidateToken: () => { cachedFirebaseToken = null; },\n sleep,\n log: (m) => console.warn(`[code-runner ${new Date().toISOString()}] ${m}`),\n });\n },\n\n /** ADR-004 \u00A7 11.1b: the plane's prepared job, for SHADOW comparison. Never throws. */\n getPreparedJob: (taskId, options) => getPreparedJobRequest(req, taskId, options, () => { cachedFirebaseToken = null; }),\n /** Weekly Claude token usage report \u2014 see control-plane-weekly-tokens.mjs. */\n async postWeeklyTokens(report) {\n return postWeeklyTokensRequest(taskReq, report, () => { cachedFirebaseToken = null; });\n },\n\n /**\n * Relay a batch of this machine's local vo-mcp events to vo-telemetry via\n * the control plane (telemetry-forwarder.mjs). Returns { status, body };\n * the forwarder owns backoff/disable policy. See control-plane-telemetry-relay.mjs.\n */\n async relayTelemetryEvents(batch) {\n return relayTelemetryEventsRequest(req, batch, () => { cachedFirebaseToken = null; });\n },\n\n /**\n * Send a liveness heartbeat (M2). The control-plane upserts it under the\n * authenticated operator so the web shows a TRUE \"runner online\" signal.\n * Best-effort caller; throws on 401/non-ok so the daemon can log + retry.\n */\n async postHeartbeat(heartbeat) {\n const body = buildRunnerHeartbeatBody(heartbeat);\n const res = await req('POST', '/api/v1/runner/heartbeat', body, {\n timeoutMs: heartbeatTimeoutMs,\n });\n if (res.status === 401) {\n cachedFirebaseToken = null;\n throw new Error('heartbeat unauthorized (401)');\n }\n if (!res.ok) {\n // Surface WHICH field the server rejected. `HTTP 400` alone is what made\n // the 2026-07-25 outage take hours to diagnose: the runner looked\n // identical to a powered-off machine from the control plane, and the\n // operator's only clue was a bare status code.\n //\n // The server returns issue PATHS and CODES only (never values), so this\n // is safe to log.\n let detail = '';\n try {\n const body = await res.json();\n if (Array.isArray(body?.issue_paths) && body.issue_paths.length > 0) {\n detail = ` (rejected fields: ${body.issue_paths.join(', ')})`;\n }\n } catch { /* non-JSON body \u2014 the status code is all we have */ }\n throw new Error(`heartbeat failed: HTTP ${res.status}${detail}`);\n }\n return res.json();\n },\n\n async getRunnerStatus({ operatorId } = {}) {\n const query = operatorId ? `?operator_id=${encodeURIComponent(operatorId)}` : '';\n const res = await req('GET', `/api/v1/runner/status${query}`, undefined, {\n timeoutMs: heartbeatTimeoutMs,\n });\n if (res.status === 401) {\n cachedFirebaseToken = null;\n throw new Error('runner status unauthorized (401)');\n }\n if (!res.ok) throw new Error(`runner status failed: HTTP ${res.status}`);\n const body = await res.json();\n return Array.isArray(body?.runners) ? body.runners : [];\n },\n\n async pollRunnerControl({ runnerId, operatorId, supervisorInstanceId, supervisorVersion, capabilities }) {\n const body = { runner_id: runnerId };\n if (operatorId) body.operator_id = operatorId;\n if (supervisorInstanceId) body.supervisor_instance_id = supervisorInstanceId;\n if (supervisorVersion) body.supervisor_version = supervisorVersion;\n if (Array.isArray(capabilities) && capabilities.length > 0) body.capabilities = capabilities;\n const res = await taskReq('POST', '/api/v1/runner/control/poll', body);\n if (res.status === 401) {\n cachedFirebaseToken = null;\n throw new Error('runner control poll unauthorized (401)');\n }\n if (!res.ok) throw new Error(`runner control poll failed: HTTP ${res.status}`);\n const json = await res.json();\n const action = json?.action;\n return action && typeof action.action_id === 'string' && action.action_id\n ? { ...action, actionId: action.action_id }\n : null;\n },\n\n async completeRunnerControl(actionId, { runnerId, operatorId, supervisorInstanceId, supervisorVersion, capabilities, status, detail }) {\n const body = { runner_id: runnerId, status };\n if (operatorId) body.operator_id = operatorId;\n if (supervisorInstanceId) body.supervisor_instance_id = supervisorInstanceId;\n if (supervisorVersion) body.supervisor_version = supervisorVersion;\n if (Array.isArray(capabilities) && capabilities.length > 0) body.capabilities = capabilities;\n if (detail) body.detail = detail;\n const res = await taskReq('POST', `/api/v1/runner/control/${encodeURIComponent(actionId)}/complete`, body);\n if (res.status === 401) {\n cachedFirebaseToken = null;\n throw new Error('runner control completion unauthorized (401)');\n }\n if (!res.ok) throw new Error(`runner control completion failed: HTTP ${res.status}`);\n const json = await res.json();\n return json?.action || null;\n },\n\n /** Mint a GitHub App installation token \u2014 see installation-token.mjs. */\n async getInstallationToken({ required = false, readOnly = false, repo = null } = {}) {\n return fetchInstallationToken({ req: taskReq, required, readOnly, repo });\n },\n\n /**\n * Read the operator's dispatch-mode config (Fast\u2192Ultracode effort setting).\n * Returns the mode string ('fast'|'standard'|'deep'|'ultra'|'marathon'; 'ultracode' legacy),\n * defaulting to 'standard' on any error. Never throws \u2014 best-effort.\n */\n async getDispatchMode() {\n try {\n const res = await taskReq('GET', '/api/v1/dispatch-mode-config');\n if (!res.ok) return 'standard';\n const json = await res.json();\n return json?.dispatchMode || 'standard';\n } catch {\n return 'standard';\n }\n },\n };\n}\n", "/** Allow-listed host maintenance operations used by the runner supervisor. */\nimport { spawnSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { win32 } from 'node:path';\n\nexport const DEFAULT_RUNNER_PACKAGE = '@algosuite/vo-mcp@beta';\nconst PACKAGE_SPEC_RE = /^@algosuite\\/vo-mcp@(beta|latest|\\d+(?:\\.\\d+){0,2}(?:-[\\w.-]+)?)$/u;\nconst MAX_DIAGNOSTIC_CHARS = 800;\nconst NPM_CLI_SUFFIX = `\\\\${win32.join('node_modules', 'npm', 'bin', 'npm-cli.js').toLowerCase()}`;\n\nfunction escapeRegExp(value) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/gu, '\\\\$&');\n}\n\n/** Keep action detail useful without ever returning credentials or tokens. */\nexport function sanitizeMaintenanceDiagnostic(raw, env = {}) {\n let value = String(raw || '')\n .replace(/\\b(?:vocred|npm|gh[oprsu])_[A-Za-z0-9._-]+\\b/gu, '[REDACTED]')\n .replace(/\\bBearer\\s+\\S+/giu, 'Bearer [REDACTED]')\n .replace(/\\b(_?authToken|token|password|secret|credential)(\\s*[=:]\\s*)\\S+/giu, '$1$2[REDACTED]');\n for (const [name, secret] of Object.entries(env)) {\n if (!/(?:TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL)/iu.test(name)) continue;\n const text = String(secret || '');\n if (text.length < 4) continue;\n value = value.replace(new RegExp(escapeRegExp(text), 'gu'), '[REDACTED]');\n }\n value = value.replace(/\\s+/gu, ' ').trim();\n if (value.length <= MAX_DIAGNOSTIC_CHARS) return value;\n return `${value.slice(0, MAX_DIAGNOSTIC_CHARS - 1)}\u2026`;\n}\n\nfunction isNpmCliPath(value) {\n return typeof value === 'string'\n && win32.isAbsolute(value)\n && win32.normalize(value).toLowerCase().endsWith(NPM_CLI_SUFFIX);\n}\n\n/**\n * Resolve npm's JavaScript entrypoint without executing a Windows `.cmd` shim.\n *\n * The desktop app can run from a bundled node.exe that does not carry npm, so\n * resolution also checks the exact npm layout below absolute PATH entries. No\n * candidate controls the executable or package argv: process.execPath remains\n * the executable and the package spec remains allow-listed below.\n */\nexport function resolveNpmCli({\n env = process.env,\n execPath = process.execPath,\n fileExists = existsSync,\n} = {}) {\n const candidates = [];\n if (isNpmCliPath(env.npm_execpath)) candidates.push(env.npm_execpath);\n candidates.push(win32.join(win32.dirname(execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js'));\n\n const pathValue = env.PATH ?? env.Path ?? env.path ?? '';\n for (const entry of pathValue.split(';')) {\n const trimmed = entry.trim();\n if (!win32.isAbsolute(trimmed)) continue;\n candidates.push(win32.join(trimmed, 'node_modules', 'npm', 'bin', 'npm-cli.js'));\n }\n\n const seen = new Set();\n for (const candidate of candidates) {\n const normalized = win32.normalize(candidate);\n const key = normalized.toLowerCase();\n if (seen.has(key) || !isNpmCliPath(normalized)) continue;\n seen.add(key);\n if (fileExists(normalized)) return normalized;\n }\n return null;\n}\n\nexport function buildMaintenanceCommand(kind, {\n platform = process.platform,\n packageSpec = DEFAULT_RUNNER_PACKAGE,\n env = process.env,\n execPath = process.execPath,\n fileExists = existsSync,\n} = {}) {\n if (!['update', 'reinstall'].includes(kind)) return null;\n if (!PACKAGE_SPEC_RE.test(packageSpec)) throw new Error('unsafe runner package spec');\n const npmCli = platform === 'win32' ? resolveNpmCli({ env, execPath, fileExists }) : null;\n if (platform === 'win32' && !npmCli) throw new Error('trusted npm CLI not found');\n const command = platform === 'win32' ? execPath : 'npm';\n const args = [...(npmCli ? [npmCli] : []), 'install', '-g', packageSpec];\n if (kind === 'reinstall') args.push('--force');\n return { command, args };\n}\n\nexport function runHostMaintenance(kind, {\n platform = process.platform,\n packageSpec = DEFAULT_RUNNER_PACKAGE,\n env = process.env,\n execPath = process.execPath,\n fileExists = existsSync,\n spawn = spawnSync,\n log = () => {},\n} = {}) {\n if (kind === 'reconnect') return { ok: true, status: 0, command: null, args: [] };\n let command;\n try {\n command = buildMaintenanceCommand(kind, { platform, packageSpec, env, execPath, fileExists });\n } catch (error) {\n return {\n ok: false,\n status: 2,\n command: null,\n args: [],\n detail: sanitizeMaintenanceDiagnostic(error instanceof Error ? error.message : String(error), env),\n };\n }\n if (!command) return { ok: false, status: 2, command: null, args: [] };\n log(`runner maintenance: ${command.command} ${command.args.join(' ')}`);\n const result = spawn(command.command, command.args, {\n stdio: ['ignore', 'pipe', 'pipe'],\n encoding: 'utf8',\n env,\n shell: false,\n windowsHide: true,\n });\n const status = typeof result.status === 'number' ? result.status : 1;\n const detail = sanitizeMaintenanceDiagnostic(\n [result.stderr, result.stdout, result.error?.message].filter(Boolean).join('\\n'),\n env,\n );\n if (detail) log(`runner maintenance result: ${detail}`);\n return { ok: status === 0, status, command: command.command, args: command.args, detail };\n}\n", "import { createHash, randomUUID } from 'node:crypto';\nimport {\n existsSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs';\nimport { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { resolveNpmCli, sanitizeMaintenanceDiagnostic } from '../../../../scripts/virtual-office/code-runner/runner-host-maintenance.mjs';\nimport {\n validateRuntimeAuthorization,\n validateStagedRuntimeAuthorization,\n} from '../../../../scripts/virtual-office/runner-bootstrap/runtime-authorization.mjs';\nimport { activateSlot, atomicWriteJson, hashFileSha512, hashRuntimeTree, slotPaths, validateSlot } from './bundled-runtime-store.mjs';\n\nconst PACKAGE_NAME = '@algosuite/vo-mcp';\nconst PACKAGE_SPEC_RE = /^@algosuite\\/vo-mcp@\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u;\nconst INTEGRITY_RE = /^sha512-[A-Za-z0-9+/]{86}==$/u;\nconst MAX_TARBALL_BYTES = 100 * 1024 * 1024;\nconst PUBLIC_REGISTRY = 'https://registry.npmjs.org/';\n\nexport function buildMinimalMaintenanceEnv(env = process.env, runtimeRoot = '') {\n const allowed = new Set([\n 'PATH', 'Path', 'path', 'PATHEXT', 'SystemRoot', 'SYSTEMROOT', 'WINDIR', 'COMSPEC',\n 'TEMP', 'TMP', 'TMPDIR', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA',\n 'ProgramFiles', 'ProgramFiles(x86)', 'ProgramW6432', 'LANG', 'LC_ALL',\n ]);\n const clean = {};\n for (const [key, value] of Object.entries(env)) {\n if (allowed.has(key) && typeof value === 'string') clean[key] = value;\n }\n return {\n ...clean,\n npm_config_ignore_scripts: 'true',\n npm_config_bin_links: 'false',\n npm_config_audit: 'false',\n npm_config_fund: 'false',\n npm_config_update_notifier: 'false',\n npm_config_registry: PUBLIC_REGISTRY,\n ...(runtimeRoot ? {\n npm_config_userconfig: join(runtimeRoot, 'maintenance', 'user.npmrc'),\n npm_config_globalconfig: join(runtimeRoot, 'maintenance', 'global.npmrc'),\n npm_config_cache: join(runtimeRoot, 'maintenance', 'npm-cache'),\n } : {}),\n };\n}\n\nfunction defaultRun(command, args, options) {\n return spawnSync(command, args, {\n cwd: options.cwd,\n encoding: 'utf8',\n env: options.env,\n shell: false,\n windowsHide: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n timeout: options.timeout ?? 120_000,\n });\n}\n\nfunction commandRunner({ platform, execPath, env, fileExists, run }) {\n const npmCli = platform === 'win32' ? resolveNpmCli({ env, execPath, fileExists }) : null;\n if (platform === 'win32' && !npmCli) throw new Error('trusted npm CLI not found');\n const npmCommand = platform === 'win32' ? execPath : 'npm';\n const prefix = npmCli ? [npmCli] : [];\n return {\n npm(args, options) { return run(npmCommand, [...prefix, ...args], options); },\n node(args, options) { return run(execPath, args, options); },\n };\n}\n\nfunction parseJsonOutput(result, operation) {\n if (result?.status !== 0) {\n throw new Error(`${operation} failed: ${String(result?.stderr || result?.error?.message || `exit ${result?.status ?? 1}`)}`);\n }\n try { return JSON.parse(String(result.stdout || '')); } catch { throw new Error(`${operation} returned invalid JSON`); }\n}\n\nfunction tarballIntegrity(file) {\n return `sha512-${createHash('sha512').update(readFileSync(file)).digest('base64')}`;\n}\n\nfunction assertNoLinks(root) {\n const pending = [root];\n while (pending.length) {\n const current = pending.pop();\n const stat = lstatSync(current);\n if (stat.isSymbolicLink()) throw new Error('installed runtime contains a link/reparse point');\n if (!stat.isDirectory()) continue;\n for (const entry of readdirSync(current)) pending.push(join(current, entry));\n }\n}\n\nexport function validateDependencyLock(payloadRoot, expected) {\n const lock = JSON.parse(readFileSync(join(payloadRoot, 'package-lock.json'), 'utf8'));\n if (Number(lock.lockfileVersion) < 3 || !lock.packages || typeof lock.packages !== 'object') {\n throw new Error('runtime dependency lock is missing or unsupported');\n }\n let foundPackage = false;\n for (const [key, item] of Object.entries(lock.packages)) {\n if (!key) continue;\n if (item?.link === true) throw new Error(`runtime dependency lock contains link: ${key}`);\n const isRunner = key.replaceAll('\\\\', '/').endsWith('node_modules/@algosuite/vo-mcp');\n if (isRunner) {\n foundPackage = item.version === expected.version && item.integrity === expected.integrity;\n continue;\n }\n if (!INTEGRITY_RE.test(String(item?.integrity || ''))) throw new Error(`dependency lacks sha512 integrity: ${key}`);\n if (!String(item?.resolved || '').startsWith('https://registry.npmjs.org/')) {\n throw new Error(`dependency is not registry-pinned: ${key}`);\n }\n }\n if (!foundPackage) throw new Error('installed runner package does not match registry integrity');\n}\n\nexport function writeAuthorizedInstallSeed(payloadRoot, tarball, runtimeAuthorization) {\n const authorization = validateRuntimeAuthorization(runtimeAuthorization);\n const stagingRoot = resolve(payloadRoot, '..', '..');\n const tarballFromStaging = relative(stagingRoot, resolve(tarball));\n if (!tarballFromStaging || tarballFromStaging === '..'\n || tarballFromStaging.startsWith(`..${sep}`)\n || isAbsolute(tarballFromStaging)) {\n throw new Error('authorized runtime tarball escaped staging root');\n }\n const relativeTarball = relative(payloadRoot, resolve(tarball)).replaceAll('\\\\', '/');\n if (!relativeTarball || isAbsolute(relativeTarball)\n || relativeTarball.includes('\\n') || relativeTarball.includes('\\r')) {\n throw new Error('authorized runtime tarball path invalid');\n }\n const fileSpec = `file:${relativeTarball}`;\n const packageRecord = { name: 'algohq-runner-runtime', version: '0.0.0', private: true,\n dependencies: { [PACKAGE_NAME]: fileSpec } };\n const packages = structuredClone(authorization.dependency_lock.packages);\n packages[`node_modules/${PACKAGE_NAME}`].resolved = fileSpec;\n const lock = { name: packageRecord.name, version: packageRecord.version,\n lockfileVersion: authorization.dependency_lock.source_lockfile_version,\n requires: true, packages: { '': packageRecord, ...packages } };\n writeFileSync(join(payloadRoot, 'package.json'), `${JSON.stringify(packageRecord)}\\n`, { mode: 0o600 });\n writeFileSync(join(payloadRoot, 'package-lock.json'), `${JSON.stringify(lock)}\\n`, { mode: 0o600 });\n return { fileSpec, lock };\n}\n\nfunction buildActive(slotId, metadata, paths) {\n return {\n slot_id: slotId,\n version: metadata.version,\n integrity: metadata.integrity,\n entry_sha512: hashFileSha512(paths.entry),\n supervisor_sha512: hashFileSha512(paths.supervisor),\n tree_sha512: hashRuntimeTree(paths.slotRoot ?? paths.payloadRoot),\n };\n}\n\nfunction installSlot({\n runtimeRoot, metadata, tarball, runner, npmEnv, runOptions, force, runtimeAuthorization,\n}) {\n const digest = createHash('sha256').update(metadata.integrity).digest('hex').slice(0, 16);\n const suffix = force ? `${digest}-${randomUUID().slice(0, 8)}` : digest;\n const slotId = `vo-mcp-${metadata.version}-${suffix}`;\n const finalPaths = slotPaths(runtimeRoot, slotId);\n if (!force && existsSync(finalPaths.slotRoot)) {\n const manifest = JSON.parse(readFileSync(finalPaths.manifest, 'utf8'));\n const active = buildActive(slotId, metadata, finalPaths);\n const validated = validateSlot(runtimeRoot, active);\n if (validated.ok && manifest.integrity === metadata.integrity) {\n if (runtimeAuthorization) {\n validateStagedRuntimeAuthorization({\n payloadRoot: finalPaths.slotRoot, authorization: runtimeAuthorization,\n });\n }\n return { active, created: false };\n }\n }\n\n const staging = join(runtimeRoot, 'staging', randomUUID());\n const payload = join(staging, 'payload');\n let installedSlot = false;\n try {\n mkdirSync(payload, { recursive: true });\n let installArgs;\n if (runtimeAuthorization) {\n writeAuthorizedInstallSeed(payload, tarball, runtimeAuthorization);\n installArgs = ['ci', '--ignore-scripts', '--no-bin-links', '--no-audit', '--no-fund',\n `--registry=${PUBLIC_REGISTRY}`];\n } else {\n writeFileSync(join(payload, 'package.json'), `${JSON.stringify({\n name: 'algohq-runner-runtime', version: '0.0.0', private: true,\n })}\\n`);\n installArgs = ['install', '--ignore-scripts', '--no-bin-links', '--no-audit', '--no-fund',\n '--package-lock=true', '--save-exact', `--registry=${PUBLIC_REGISTRY}`, tarball];\n }\n const install = runner.npm(installArgs,\n { ...runOptions, cwd: payload, env: npmEnv, timeout: 180_000 });\n if (install.status !== 0) throw new Error(`npm install failed: ${install.stderr || install.error?.message || install.status}`);\n assertNoLinks(payload);\n validateDependencyLock(payload, metadata);\n if (runtimeAuthorization) {\n validateStagedRuntimeAuthorization({ payloadRoot: payload, authorization: runtimeAuthorization });\n }\n\n const stagedPaths = {\n entry: join(payload, 'node_modules', '@algosuite', 'vo-mcp', 'bin', 'vo-mcp'),\n supervisor: join(payload, 'node_modules', '@algosuite', 'vo-mcp', 'dist', 'runner-supervisor.js'),\n packageJson: join(payload, 'node_modules', '@algosuite', 'vo-mcp', 'package.json'),\n credentialHelper: join(payload, 'node_modules', '@algosuite', 'vo-mcp', 'dist', 'supervisor-credential-helper.js'),\n slotRoot: payload,\n };\n const pkg = JSON.parse(readFileSync(stagedPaths.packageJson, 'utf8'));\n if (pkg.name !== PACKAGE_NAME || pkg.version !== metadata.version) throw new Error('installed package identity mismatch');\n if (!lstatSync(stagedPaths.credentialHelper).isFile()) throw new Error('installed credential helper is missing');\n const smoke = runner.node([stagedPaths.entry, 'runner', '--version'], { ...runOptions, cwd: payload, env: npmEnv, timeout: 30_000 });\n if (smoke.status !== 0 || String(smoke.stdout || '').trim() !== `vo-mcp runner ${metadata.version}`) {\n throw new Error('bundled runtime smoke check failed');\n }\n const active = buildActive(slotId, metadata, stagedPaths);\n atomicWriteJson(join(payload, 'runtime-manifest.json'), { schema_version: 1, ...active });\n mkdirSync(join(runtimeRoot, 'slots'), { recursive: true });\n if (existsSync(finalPaths.slotRoot)) throw new Error('immutable runtime slot already exists');\n renameSync(payload, finalPaths.slotRoot);\n installedSlot = true;\n const validated = validateSlot(runtimeRoot, active);\n if (!validated.ok) throw new Error(`staged runtime validation failed: ${validated.detail}`);\n return { active, created: true };\n } catch (error) {\n if (installedSlot) rmSync(finalPaths.slotRoot, { recursive: true, force: true });\n throw error;\n } finally {\n rmSync(staging, { recursive: true, force: true });\n }\n}\n\nexport function stageBundledRuntimeSlot(options) {\n const {\n runtimeRoot,\n packageSpec,\n expectedVersion,\n expectedIntegrity,\n platform = process.platform,\n execPath = process.execPath,\n env = process.env,\n fileExists = existsSync,\n run = defaultRun,\n force = false,\n runtimeAuthorization = null,\n } = options;\n if (!runtimeRoot || !isAbsolute(runtimeRoot)) return { ok: false, status: 2, detail: 'bundled runtime root unavailable' };\n if (!expectedVersion || !PACKAGE_SPEC_RE.test(`${PACKAGE_NAME}@${expectedVersion}`)) {\n return { ok: false, status: 2, detail: 'invalid expected runner version' };\n }\n if (!expectedIntegrity || !INTEGRITY_RE.test(expectedIntegrity)) {\n return { ok: false, status: 2, detail: 'invalid expected runner integrity' };\n }\n const exactSpec = `${PACKAGE_NAME}@${expectedVersion}`;\n if (packageSpec !== exactSpec) return { ok: false, status: 2, detail: 'runner package spec does not match authorized version' };\n const resolvedRoot = resolve(runtimeRoot);\n const npmEnv = buildMinimalMaintenanceEnv(env, resolvedRoot);\n const runOptions = { env: npmEnv, cwd: resolvedRoot };\n let tarDir = null;\n try {\n mkdirSync(resolvedRoot, { recursive: true });\n mkdirSync(join(resolvedRoot, 'maintenance'), { recursive: true });\n writeFileSync(npmEnv.npm_config_userconfig, '', { mode: 0o600 });\n writeFileSync(npmEnv.npm_config_globalconfig, '', { mode: 0o600 });\n const runner = commandRunner({ platform, execPath, env: npmEnv, fileExists, run });\n const metadata = { version: expectedVersion, integrity: expectedIntegrity };\n tarDir = join(resolvedRoot, 'staging', randomUUID());\n mkdirSync(tarDir, { recursive: true });\n const packed = parseJsonOutput(runner.npm([\n 'pack', exactSpec, '--ignore-scripts', '--json', '--pack-destination', tarDir, `--registry=${PUBLIC_REGISTRY}`,\n ], runOptions), 'npm pack');\n const record = Array.isArray(packed) ? packed[0] : packed;\n const tarball = join(tarDir, basename(String(record?.filename || '')));\n if (!existsSync(tarball) || !basename(tarball).endsWith('.tgz')) throw new Error('npm pack returned no tarball');\n if (lstatSync(tarball).size > MAX_TARBALL_BYTES) throw new Error('runner package tarball exceeds size limit');\n if (record.integrity !== metadata.integrity || tarballIntegrity(tarball) !== metadata.integrity) {\n throw new Error('runner package sha512 integrity mismatch');\n }\n const installed = installSlot({\n runtimeRoot: resolvedRoot, metadata, tarball, runner, npmEnv, runOptions, force,\n runtimeAuthorization,\n });\n return { ok: true, status: 0, ...installed };\n } catch (error) {\n return { ok: false, status: 1, detail: sanitizeMaintenanceDiagnostic(error instanceof Error ? error.message : String(error), env) };\n } finally {\n if (tarDir) rmSync(tarDir, { recursive: true, force: true });\n }\n}\n\nexport function stageAndActivateBundledUpdate(options) {\n const staged = stageBundledRuntimeSlot(options);\n if (!staged.ok) return staged;\n try {\n activateSlot(resolve(options.runtimeRoot), staged.active, options.action);\n return { ...staged, handoff: true };\n } catch (error) {\n return {\n ok: false,\n status: 1,\n detail: sanitizeMaintenanceDiagnostic(error instanceof Error ? error.message : String(error), options.env ?? process.env),\n };\n }\n}\n\nexport const __test = { INTEGRITY_RE, PACKAGE_SPEC_RE, PUBLIC_REGISTRY, assertNoLinks, tarballIntegrity };\n", "import { createHash } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nimport { dirname, posix, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport {\n compareStagedRuntime,\n isOmittedOptionalPackage,\n} from './runtime-staged-tree.mjs';\n\nconst HERE = dirname(fileURLToPath(import.meta.url));\nexport const BETA13_WINDOWS_X64_AUTHORIZATION = resolve(\n HERE,\n 'authorizations',\n 'vo-mcp-0.2.0-beta.13-win32-x64.json',\n);\n\nconst EXPECTED = Object.freeze({\n authorizationId: 'vo-mcp-0.2.0-beta.13-win32-x64-v1',\n packageName: '@algosuite/vo-mcp',\n version: '0.2.0-beta.13',\n registry: 'https://registry.npmjs.org/',\n tarballUrl: 'https://registry.npmjs.org/@algosuite/vo-mcp/-/vo-mcp-0.2.0-beta.13.tgz',\n integrity: 'sha512-TQa5VaEFsaleHbAZZp+zS4u5U/0zQBIGOiPDGn9IqfZfdMltH2dY81nTftvu5EUABthE1xTCrdSzJjO9mzkNag==',\n tarballSha256: 'c1e39e8bb2df7f53f48e46e77ffb617452a01849469ff4757b4384a478c1cbff',\n npmShasumSha1: 'f076649b31294aa38deb7852f38a889e0d0fbe44',\n gitHead: 'ba00db90720416fa7474581eb823c6255221880f',\n sourceLockSha256: 'f8bbb5e81a0057ee2d60145580ec07f7e7055d999bdd038515c6c4e88af6cc92',\n canonicalEntriesSha256: '7f6b2f93ccb93ad625ed244dc59ac556792e478178fc690ad2ca2c6f3a2325d2',\n entryCount: 107,\n optionalEntryCount: 13,\n installedEntryCount: 96,\n treeAlgorithm: 'algohq-node-modules-manifest-sha256-v1',\n treeSha256: '9c8b0749d7ae1e2c132ef08c5b5655673ae88432859c561806276c9eb18f4874',\n treeFileCount: 3538,\n treeDirectoryCount: 553,\n treeByteCount: 20566445,\n treeManifestByteCount: 412062,\n});\n\nconst SRI_RE = /^sha512-[A-Za-z0-9+/]{86}==$/u;\nconst SHA256_RE = /^[a-f0-9]{64}$/u;\n\nfunction canonical(value) {\n if (Array.isArray(value)) return value.map(canonical);\n if (value && typeof value === 'object') {\n return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));\n }\n return value;\n}\n\nfunction sha256Canonical(value) {\n return createHash('sha256').update(`${JSON.stringify(canonical(value))}\\n`, 'utf8').digest('hex');\n}\n\nfunction assertEqual(actual, expected, label) {\n if (actual !== expected) throw new Error(`runtime authorization ${label} mismatch`);\n}\n\nfunction isOmittedOnWindowsX64(entry) {\n return isOmittedOptionalPackage(entry, { os: 'win32', arch: 'x64' });\n}\n\nexport function validateRuntimeAuthorization(value) {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('runtime authorization must be an object');\n }\n assertEqual(value.schema_version, 1, 'schema version');\n assertEqual(value.authorization_id, EXPECTED.authorizationId, 'id');\n assertEqual(value.package?.name, EXPECTED.packageName, 'package name');\n assertEqual(value.package?.version, EXPECTED.version, 'package version');\n assertEqual(value.package?.registry, EXPECTED.registry, 'registry');\n assertEqual(value.package?.tarball_url, EXPECTED.tarballUrl, 'tarball URL');\n assertEqual(value.package?.sri_sha512, EXPECTED.integrity, 'package integrity');\n assertEqual(value.package?.tarball_sha256, EXPECTED.tarballSha256, 'tarball sha256');\n assertEqual(value.package?.npm_shasum_sha1, EXPECTED.npmShasumSha1, 'npm shasum');\n assertEqual(value.package?.git_head, EXPECTED.gitHead, 'git head');\n assertEqual(value.package?.packed_file_count, 25, 'packed file count');\n assertEqual(value.package?.packed_bytes, 846151, 'packed byte count');\n assertEqual(value.package?.unpacked_bytes, 3350387, 'unpacked byte count');\n\n assertEqual(value.platform?.os, 'win32', 'operating system');\n assertEqual(value.platform?.arch, 'x64', 'architecture');\n assertEqual(value.platform?.package_node_engine, '>=22.5.0', 'package node engine');\n if (!/^24\\.15\\.0$/u.test(String(value.platform?.authorization_builder_node || ''))\n || value.platform?.authorization_builder_npm !== '11.12.1') {\n throw new Error('runtime authorization builder toolchain mismatch');\n }\n\n for (const [key, expected] of Object.entries({\n ignore_scripts: true,\n bin_links: false,\n include_optional: true,\n omit_dev: true,\n audit: false,\n fund: false,\n reject_links_reparse_points: true,\n reject_hardlinks: true,\n remove_generated_node_modules_package_lock_before_tree_validation: true,\n })) assertEqual(value.install_contract?.[key], expected, `install contract ${key}`);\n assertEqual(value.install_contract?.allowed_registry_prefix, EXPECTED.registry, 'registry prefix');\n\n const lock = value.dependency_lock;\n if (!lock?.packages || typeof lock.packages !== 'object' || Array.isArray(lock.packages)) {\n throw new Error('runtime authorization dependency set missing');\n }\n assertEqual(lock.source_lockfile_version, 3, 'lockfile version');\n assertEqual(lock.source_lock_sha256, EXPECTED.sourceLockSha256, 'source lock sha256');\n assertEqual(lock.canonical_entries_sha256, EXPECTED.canonicalEntriesSha256, 'entry-set sha256');\n assertEqual(lock.entry_count, EXPECTED.entryCount, 'entry count');\n assertEqual(lock.integrity_entry_count, EXPECTED.entryCount, 'integrity count');\n assertEqual(lock.optional_entry_count, EXPECTED.optionalEntryCount, 'optional count');\n assertEqual(lock.windows_x64_installed_entry_count, EXPECTED.installedEntryCount, 'installed count');\n\n const entries = Object.entries(lock.packages);\n assertEqual(entries.length, EXPECTED.entryCount, 'package map count');\n for (const [key, entry] of entries) {\n if (!key.startsWith('node_modules/') || key.includes('\\\\') || posix.normalize(key) !== key\n || key.split('/').includes('..')) {\n throw new Error(`runtime authorization has unsafe package path: ${key}`);\n }\n if (!entry || typeof entry !== 'object' || entry.link === true) {\n throw new Error(`runtime authorization contains a linked package: ${key}`);\n }\n if (!SRI_RE.test(String(entry.integrity || ''))) {\n throw new Error(`runtime authorization package lacks sha512 integrity: ${key}`);\n }\n if (!String(entry.resolved || '').startsWith(EXPECTED.registry)) {\n throw new Error(`runtime authorization package is outside the public registry: ${key}`);\n }\n if (entry.hasInstallScript === true) {\n throw new Error(`runtime authorization package declares an install script: ${key}`);\n }\n }\n const runner = lock.packages['node_modules/@algosuite/vo-mcp'];\n assertEqual(runner?.version, EXPECTED.version, 'runner dependency version');\n assertEqual(runner?.integrity, EXPECTED.integrity, 'runner dependency integrity');\n assertEqual(sha256Canonical(lock.packages), EXPECTED.canonicalEntriesSha256, 'computed entry-set sha256');\n\n const omitted = entries.filter(([, entry]) => isOmittedOnWindowsX64(entry)).map(([key]) => key).sort();\n const declaredOmitted = [...(lock.windows_x64_omitted_optional_entries || [])].sort();\n assertEqual(JSON.stringify(declaredOmitted), JSON.stringify(omitted), 'omitted optional entries');\n assertEqual(entries.length - omitted.length, EXPECTED.installedEntryCount, 'derived installed count');\n\n const tree = value.installed_tree;\n assertEqual(tree?.algorithm, EXPECTED.treeAlgorithm, 'tree algorithm');\n if (!SHA256_RE.test(String(tree?.sha256 || ''))) throw new Error('runtime authorization tree hash invalid');\n assertEqual(tree.sha256, EXPECTED.treeSha256, 'tree sha256');\n assertEqual(tree.file_count, EXPECTED.treeFileCount, 'tree file count');\n assertEqual(tree.directory_count, EXPECTED.treeDirectoryCount, 'tree directory count');\n assertEqual(tree.byte_count, EXPECTED.treeByteCount, 'tree byte count');\n assertEqual(tree.canonical_manifest_byte_count, EXPECTED.treeManifestByteCount, 'tree manifest byte count');\n assertEqual(tree.reparse_point_count, 0, 'tree reparse count');\n assertEqual(tree.hardlinked_file_count, 0, 'tree hardlink count');\n return value;\n}\n\nexport function readRuntimeAuthorization(file = BETA13_WINDOWS_X64_AUTHORIZATION) {\n return validateRuntimeAuthorization(JSON.parse(readFileSync(file, 'utf8')));\n}\n\nexport function validateStagedRuntimeAuthorization(options) {\n const authorization = validateRuntimeAuthorization(options?.authorization || readRuntimeAuthorization());\n return compareStagedRuntime({ ...options, authorization });\n}\n\nif (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {\n readRuntimeAuthorization(process.argv[2] ? resolve(process.argv[2]) : undefined);\n process.stdout.write('AlgoHQ runtime authorization valid\\n');\n}\n\nexport const __test = { canonical, isOmittedOnWindowsX64, sha256Canonical };\n", "import { execFileSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport {\n existsSync,\n lstatSync,\n readFileSync,\n readdirSync,\n} from 'node:fs';\nimport { isAbsolute, join, relative, resolve, sep, win32 } from 'node:path';\n\nconst WINDOWS_REPARSE_ATTRIBUTE = 0x400;\nconst RUNNER_LOCK_KEY = 'node_modules/@algosuite/vo-mcp';\nexport const INSTALLED_TREE_ALGORITHM = 'algohq-node-modules-manifest-sha256-v1';\n\nfunction canonical(value) {\n if (Array.isArray(value)) return value.map(canonical);\n if (value && typeof value === 'object') {\n return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));\n }\n return value;\n}\n\nfunction canonicalJson(value) {\n return JSON.stringify(canonical(value));\n}\n\nfunction hasFileAttribute(value, bit) {\n if (typeof value === 'bigint') return (value & BigInt(bit)) !== 0n;\n return Number.isSafeInteger(value) && (value & bit) !== 0;\n}\n\nexport function isReparseStat(stats) {\n if (!stats || typeof stats !== 'object') return false;\n if (typeof stats.isSymbolicLink === 'function' && stats.isSymbolicLink()) return true;\n if (stats.reparseTag !== undefined && stats.reparseTag !== null && stats.reparseTag !== 0) return true;\n return ['fileAttributes', 'fileAttribute', 'attributes']\n .some((key) => hasFileAttribute(stats[key], WINDOWS_REPARSE_ATTRIBUTE));\n}\n\nexport function platformConstraintAllows(values, target) {\n if (!Array.isArray(values) || values.length === 0) return true;\n if (values.some((value) => value === `!${target}`)) return false;\n const positive = values.filter((value) => typeof value === 'string' && !value.startsWith('!'));\n return positive.length === 0 || positive.includes(target);\n}\n\nexport function isOmittedOptionalPackage(entry, platform = { os: 'win32', arch: 'x64' }) {\n return entry?.optional === true && (\n !platformConstraintAllows(entry.os, platform.os)\n || !platformConstraintAllows(entry.cpu, platform.arch)\n );\n}\n\nfunction assertContained(root, candidate, label) {\n const rel = relative(root, candidate);\n if (rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel))) return;\n throw new Error(`staged runtime ${label} escapes the payload root`);\n}\n\nfunction normalizeReportedPath(root, candidate) {\n const absolute = resolve(String(candidate || ''));\n assertContained(root, absolute, 'reparse point');\n return absolute;\n}\n\nexport function listWindowsReparsePoints(root, {\n execFile = execFileSync, env = process.env, platform = process.platform,\n} = {}) {\n if (platform !== 'win32') return [];\n const systemRoot = String(env.SystemRoot || env.SYSTEMROOT || '');\n if (!win32.isAbsolute(systemRoot) || win32.normalize(systemRoot) !== systemRoot) {\n throw new Error('staged runtime trusted PowerShell root unavailable');\n }\n const system32 = win32.join(systemRoot, 'System32');\n const powershell = win32.join(system32, 'WindowsPowerShell', 'v1.0', 'powershell.exe');\n const script = [\n '$ErrorActionPreference = \"Stop\"',\n '$root = [IO.Path]::GetFullPath($env:ALGOHQ_REPARSE_ROOT)',\n '$items = @((Get-Item -LiteralPath $root -Force)) + @(Get-ChildItem -LiteralPath $root -Force -Recurse)',\n 'foreach ($item in $items) {',\n ' if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {',\n ' [Console]::Out.WriteLine($item.FullName)',\n ' }',\n '}',\n ].join('; ');\n const output = execFile(powershell, [\n '-NoLogo',\n '-NoProfile',\n '-NonInteractive',\n '-Command',\n script,\n ], {\n cwd: system32,\n encoding: 'utf8',\n env: { SystemRoot: systemRoot, ALGOHQ_REPARSE_ROOT: win32.resolve(root) },\n windowsHide: true,\n });\n return String(output || '').split(/\\r?\\n/u).filter(Boolean)\n .map((item) => normalizeReportedPath(root, item));\n}\n\nfunction normalizedRunnerRecord(actual, expected) {\n const normalized = structuredClone(actual);\n if (normalized?.resolved === expected?.resolved) return normalized;\n if (typeof normalized?.resolved !== 'string' || !normalized.resolved.startsWith('file:')) {\n return normalized;\n }\n const fileName = normalized.resolved.slice('file:'.length).replaceAll('\\\\', '/').split('/').at(-1);\n const expectedFileNames = new Set([\n String(expected.resolved || '').split('/').at(-1),\n `algosuite-vo-mcp-${expected.version}.tgz`,\n ]);\n if (expectedFileNames.has(fileName)) normalized.resolved = expected.resolved;\n return normalized;\n}\n\nfunction validateLock(lock, authorization) {\n if (!lock || typeof lock !== 'object' || Array.isArray(lock)) {\n throw new Error('staged runtime package-lock must be an object');\n }\n if (lock.lockfileVersion !== authorization.dependency_lock.source_lockfile_version) {\n throw new Error('staged runtime package-lock version mismatch');\n }\n if (!lock.packages || typeof lock.packages !== 'object' || Array.isArray(lock.packages)) {\n throw new Error('staged runtime package-lock package map missing');\n }\n const expected = authorization.dependency_lock.packages;\n const actual = Object.fromEntries(Object.entries(lock.packages).filter(([key]) => key !== ''));\n const expectedKeys = Object.keys(expected).sort();\n const actualKeys = Object.keys(actual).sort();\n if (canonicalJson(actualKeys) !== canonicalJson(expectedKeys)) {\n throw new Error('staged runtime package-lock package set mismatch');\n }\n for (const key of expectedKeys) {\n const record = key === RUNNER_LOCK_KEY\n ? normalizedRunnerRecord(actual[key], expected[key])\n : actual[key];\n if (canonicalJson(record) !== canonicalJson(expected[key])) {\n throw new Error(`staged runtime package-lock record mismatch: ${key}`);\n }\n }\n return { actual, expected };\n}\n\nfunction checkPathKind(path, expectedKind, fsOps, label) {\n if (!fsOps.exists(path)) throw new Error(`staged runtime ${label} missing`);\n const stats = fsOps.lstat(path);\n if (isReparseStat(stats) || fsOps.isReparsePoint(path, stats)) {\n throw new Error(`staged runtime ${label} is a reparse point`);\n }\n if (expectedKind === 'directory' && !stats.isDirectory()) {\n throw new Error(`staged runtime ${label} is not a directory`);\n }\n if (expectedKind === 'file' && !stats.isFile()) {\n throw new Error(`staged runtime ${label} is not a regular file`);\n }\n if (expectedKind === 'file' && Number(stats.nlink) > 1) {\n throw new Error(`staged runtime ${label} is hardlinked`);\n }\n return stats;\n}\n\nfunction verifyInstalledPackages(payloadRoot, packageRecords, platform, fsOps) {\n const omitted = [];\n let installed = 0;\n for (const [key, entry] of Object.entries(packageRecords)) {\n const path = resolve(payloadRoot, key);\n assertContained(payloadRoot, path, 'package path');\n const shouldOmit = isOmittedOptionalPackage(entry, platform);\n if (shouldOmit) {\n omitted.push(key);\n if (fsOps.exists(path)) throw new Error(`staged runtime optional package should be omitted: ${key}`);\n continue;\n }\n checkPathKind(path, 'directory', fsOps, `installed package ${key}`);\n installed += 1;\n }\n return { installed, omitted: omitted.sort() };\n}\n\nfunction treeRecord(kind, path, stats, fileHash = '') {\n if (kind === 'd') return `d\\t${path}\\r\\n`;\n return `f\\t${path}\\t${stats.size}\\t${fileHash}\\r\\n`;\n}\n\nexport function computeInstalledTree(nodeModulesRoot, fsOps = {}) {\n const ops = {\n exists: existsSync,\n lstat: lstatSync,\n readdir: (path) => readdirSync(path, { withFileTypes: true }),\n readFile: readFileSync,\n isReparsePoint: () => false,\n listReparsePoints: listWindowsReparsePoints,\n ...fsOps,\n };\n const root = resolve(nodeModulesRoot);\n checkPathKind(root, 'directory', ops, 'node_modules root');\n const reported = ops.listReparsePoints(root);\n if (!Array.isArray(reported)) throw new Error('staged runtime reparse probe returned an invalid result');\n if (reported.length > 0) throw new Error('staged runtime tree contains a Windows reparse point');\n\n let fileCount = 0;\n let directoryCount = 1;\n let byteCount = 0;\n const entries = [];\n function walk(absolute, relativePath) {\n for (const entry of ops.readdir(absolute)) {\n const childRelative = relativePath ? `${relativePath}/${entry.name}` : entry.name;\n if (childRelative === '.package-lock.json') continue;\n const child = resolve(absolute, entry.name);\n assertContained(root, child, 'tree entry');\n const stats = ops.lstat(child);\n if (isReparseStat(stats) || ops.isReparsePoint(child, stats)) {\n throw new Error(`staged runtime tree contains a reparse point: ${childRelative}`);\n }\n if (stats.isDirectory()) {\n directoryCount += 1;\n entries.push({ kind: 'd', path: childRelative, stats });\n walk(child, childRelative);\n } else if (stats.isFile()) {\n if (Number(stats.nlink) > 1) {\n throw new Error(`staged runtime tree contains a hardlinked file: ${childRelative}`);\n }\n fileCount += 1;\n byteCount += Number(stats.size);\n const digest = createHash('sha256').update(ops.readFile(child)).digest('hex');\n entries.push({ kind: 'f', path: childRelative, stats, digest });\n } else {\n throw new Error(`staged runtime tree contains a non-file entry: ${childRelative}`);\n }\n }\n }\n walk(root, '');\n entries.sort((left, right) => Buffer.compare(Buffer.from(left.path), Buffer.from(right.path)));\n const manifest = treeRecord('d', '', { size: 0 }) + entries\n .map((entry) => treeRecord(entry.kind, entry.path, entry.stats, entry.digest))\n .join('');\n return {\n algorithm: INSTALLED_TREE_ALGORITHM,\n sha256: createHash('sha256').update(manifest, 'utf8').digest('hex'),\n file_count: fileCount,\n directory_count: directoryCount,\n byte_count: byteCount,\n canonical_manifest_byte_count: Buffer.byteLength(manifest),\n reparse_point_count: 0,\n hardlinked_file_count: 0,\n };\n}\n\nexport function compareStagedRuntime({\n payloadRoot,\n nodeModulesRoot = join(payloadRoot, 'node_modules'),\n packageLockFile = join(payloadRoot, 'package-lock.json'),\n authorization,\n fsOps = {},\n}) {\n const payload = resolve(payloadRoot);\n const modules = resolve(nodeModulesRoot);\n const lockFile = resolve(packageLockFile);\n if (modules !== resolve(payload, 'node_modules') || lockFile !== resolve(payload, 'package-lock.json')) {\n throw new Error('staged runtime paths do not identify one canonical payload');\n }\n const ops = {\n exists: existsSync,\n lstat: lstatSync,\n readFile: readFileSync,\n isReparsePoint: () => false,\n ...fsOps,\n };\n checkPathKind(lockFile, 'file', ops, 'package-lock');\n const lock = JSON.parse(ops.readFile(lockFile, 'utf8'));\n const { expected } = validateLock(lock, authorization);\n const platform = { os: authorization.platform.os, arch: authorization.platform.arch };\n const packages = verifyInstalledPackages(payload, expected, platform, ops);\n const declaredOmitted = [...authorization.dependency_lock.windows_x64_omitted_optional_entries].sort();\n if (canonicalJson(packages.omitted) !== canonicalJson(declaredOmitted)) {\n throw new Error('staged runtime optional omission list mismatch');\n }\n if (packages.installed !== Object.keys(expected).length - packages.omitted.length) {\n throw new Error('staged runtime installed package count mismatch');\n }\n const tree = computeInstalledTree(modules, fsOps);\n if (canonicalJson(tree) !== canonicalJson(authorization.installed_tree)) {\n throw new Error('staged runtime installed tree mismatch');\n }\n return { ok: true, packageCount: Object.keys(expected).length, ...packages, tree };\n}\n\nexport const __test = { canonical, canonicalJson, normalizeReportedPath, normalizedRunnerRecord };\n", "import { createHash, randomUUID } from 'node:crypto';\nimport {\n closeSync,\n existsSync,\n fsyncSync,\n lstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n readdirSync,\n realpathSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path';\n\nconst SLOT_ID_RE = /^vo-mcp-[0-9A-Za-z._-]{1,96}$/u;\nconst ACTION_ID_RE = /^[0-9A-Za-z._-]{1,128}$/u;\nconst INTEGRITY_RE = /^sha512-[A-Za-z0-9+/]{86}==$/u;\nconst VERSION_RE = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u;\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\nconst ENTRY_REL = join('node_modules', '@algosuite', 'vo-mcp', 'bin', 'vo-mcp');\nconst SUPERVISOR_REL = join('node_modules', '@algosuite', 'vo-mcp', 'dist', 'runner-supervisor.js');\nconst PACKAGE_REL = join('node_modules', '@algosuite', 'vo-mcp', 'package.json');\nconst CREDENTIAL_HELPER_REL = join('node_modules', '@algosuite', 'vo-mcp', 'dist', 'supervisor-credential-helper.js');\nconst MANIFEST_FILE = 'runtime-manifest.json';\n\nfunction within(parent, candidate) {\n const rel = relative(resolve(parent), resolve(candidate));\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));\n}\n\n/**\n * Mirror of the desktop app's runtime-root resolution: RUNNER_RUNTIME_DIR\n * under Tauri's BaseDirectory::AppData for the app identifier. MUST stay in\n * lockstep with packages/vo-runner-app/src-tauri/src/runtime_slots.rs\n * (`RUNNER_RUNTIME_DIR`) and tauri.conf.json (`identifier`), or supervisors\n * and the app would stage/read different roots.\n */\nconst APP_IDENTIFIER = 'ai.algosuite.vo-runner';\nconst RUNNER_RUNTIME_DIR = 'runner-runtime';\n\nexport function defaultRuntimeRoot({ platform = process.platform, env = process.env, home = homedir() } = {}) {\n if (platform === 'win32') {\n const appData = String(env.APPDATA || '').trim();\n return appData && isAbsolute(appData) ? join(appData, APP_IDENTIFIER, RUNNER_RUNTIME_DIR) : null;\n }\n if (!home) return null;\n if (platform === 'darwin') {\n return join(home, 'Library', 'Application Support', APP_IDENTIFIER, RUNNER_RUNTIME_DIR);\n }\n const xdg = String(env.XDG_CONFIG_HOME || '').trim();\n const base = xdg && isAbsolute(xdg) ? xdg : join(home, '.config');\n return join(base, APP_IDENTIFIER, RUNNER_RUNTIME_DIR);\n}\n\n/**\n * Explicit VO_RUNNER_RUNTIME_ROOT always wins, and a SET-but-invalid value\n * still fails closed (null \u2014 a misconfiguration must not silently fall back).\n * When the variable is ABSENT, derive the app-convention default: a\n * supervisor launched by an env-stripping wrapper (live-observed on\n * vo-code-runner-JacksPC, 2026-07-21: every bundled update hard-failed\n * \"bundled runtime root unavailable\") can then still stage/activate the\n * governed update into the exact directory the desktop app reads.\n */\nexport function runtimeRootFromEnv(env = process.env, { platform, home } = {}) {\n const value = String(env.VO_RUNNER_RUNTIME_ROOT || '').trim();\n if (value) return isAbsolute(value) ? resolve(value) : null;\n const derived = defaultRuntimeRoot({ platform, env, home });\n return derived ? resolve(derived) : null;\n}\n\nexport function hashFileSha512(file) {\n return `sha512-${createHash('sha512').update(readFileSync(file)).digest('base64')}`;\n}\n\n/** Digest every executable payload byte and relative path, excluding only the self-referential manifest. */\nexport function hashRuntimeTree(root) {\n const hasher = createHash('sha512');\n const files = [];\n const visit = (directory, prefix = '') => {\n const rootStat = lstatSync(directory);\n if (rootStat.isSymbolicLink()) throw new Error('runtime tree contains a link/reparse point');\n if (!rootStat.isDirectory()) throw new Error('runtime tree root is not a directory');\n for (const name of readdirSync(directory).sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)))) {\n const absolute = join(directory, name);\n const relativePath = prefix ? `${prefix}/${name}` : name;\n const stat = lstatSync(absolute);\n if (stat.isSymbolicLink()) throw new Error('runtime tree contains a link/reparse point');\n if (stat.isDirectory()) visit(absolute, relativePath);\n else if (stat.isFile() && relativePath !== MANIFEST_FILE) files.push({ absolute, relativePath, size: stat.size });\n else if (!stat.isFile()) throw new Error('runtime tree contains a non-regular file');\n }\n };\n visit(root);\n files.sort((a, b) => Buffer.compare(Buffer.from(a.relativePath), Buffer.from(b.relativePath)));\n for (const file of files) {\n const pathBytes = Buffer.from(file.relativePath, 'utf8');\n hasher.update(`${pathBytes.length}:`);\n hasher.update(pathBytes);\n hasher.update(`:${file.size}:`);\n hasher.update(readFileSync(file.absolute));\n hasher.update('\\n');\n }\n return `sha512-${hasher.digest('base64')}`;\n}\n\nexport function atomicWriteJson(file, value) {\n mkdirSync(dirname(file), { recursive: true });\n const temp = join(dirname(file), `.${randomUUID()}.tmp`);\n const fd = openSync(temp, 'wx', 0o600);\n try {\n writeFileSync(fd, `${JSON.stringify(value, null, 2)}\\n`, 'utf8');\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n try {\n renameSync(temp, file);\n // A file fsync does not make the directory entry durable on POSIX. Windows\n // cannot open directories this way, so keep the durability upgrade best-effort.\n if (process.platform !== 'win32') {\n try {\n const parentFd = openSync(dirname(file), 'r');\n try { fsyncSync(parentFd); } finally { closeSync(parentFd); }\n } catch { /* current.json remains atomically committed */ }\n }\n } finally {\n rmSync(temp, { force: true });\n }\n}\n\nexport function readActivation(runtimeRoot) {\n const file = join(runtimeRoot, 'current.json');\n if (!existsSync(file)) return null;\n try {\n const value = JSON.parse(readFileSync(file, 'utf8'));\n return value?.schema_version === 1 ? value : null;\n } catch {\n return null;\n }\n}\n\nexport function slotPaths(runtimeRoot, slotId) {\n if (!SLOT_ID_RE.test(slotId)) throw new Error('invalid runtime slot id');\n const slotRoot = join(runtimeRoot, 'slots', slotId);\n return {\n slotRoot,\n entry: join(slotRoot, ENTRY_REL),\n supervisor: join(slotRoot, SUPERVISOR_REL),\n packageJson: join(slotRoot, PACKAGE_REL),\n credentialHelper: join(slotRoot, CREDENTIAL_HELPER_REL),\n manifest: join(slotRoot, MANIFEST_FILE),\n };\n}\n\nfunction validActive(active) {\n return active\n && SLOT_ID_RE.test(active.slot_id)\n && VERSION_RE.test(active.version)\n && INTEGRITY_RE.test(active.integrity)\n && INTEGRITY_RE.test(active.entry_sha512)\n && INTEGRITY_RE.test(active.supervisor_sha512)\n && INTEGRITY_RE.test(active.tree_sha512);\n}\n\nexport function validateSlot(runtimeRoot, active) {\n if (!validActive(active)) return { ok: false, detail: 'invalid activation metadata' };\n const paths = slotPaths(runtimeRoot, active.slot_id);\n try {\n const manifest = JSON.parse(readFileSync(paths.manifest, 'utf8'));\n const pkg = JSON.parse(readFileSync(paths.packageJson, 'utf8'));\n const expected = {\n slot_id: active.slot_id,\n version: active.version,\n integrity: active.integrity,\n entry_sha512: active.entry_sha512,\n supervisor_sha512: active.supervisor_sha512,\n tree_sha512: active.tree_sha512,\n };\n for (const [key, value] of Object.entries(expected)) {\n if (manifest?.[key] !== value) return { ok: false, detail: `manifest ${key} mismatch` };\n }\n if (manifest?.schema_version !== 1 || pkg?.name !== '@algosuite/vo-mcp' || pkg?.version !== active.version) {\n return { ok: false, detail: 'package identity mismatch' };\n }\n if (lstatSync(paths.entry).isSymbolicLink() || lstatSync(paths.supervisor).isSymbolicLink()\n || lstatSync(paths.credentialHelper).isSymbolicLink()) {\n return { ok: false, detail: 'runtime entry cannot be a link' };\n }\n if (!within(paths.slotRoot, realpathSync(paths.entry)) || !within(paths.slotRoot, realpathSync(paths.supervisor))\n || !within(paths.slotRoot, realpathSync(paths.credentialHelper))) {\n return { ok: false, detail: 'runtime entry escaped its slot' };\n }\n if (hashFileSha512(paths.entry) !== active.entry_sha512) return { ok: false, detail: 'entry hash mismatch' };\n if (hashFileSha512(paths.supervisor) !== active.supervisor_sha512) return { ok: false, detail: 'supervisor hash mismatch' };\n if (hashRuntimeTree(paths.slotRoot) !== active.tree_sha512) return { ok: false, detail: 'runtime tree hash mismatch' };\n return { ok: true, paths, manifest };\n } catch (error) {\n return { ok: false, detail: error instanceof Error ? error.message : String(error) };\n }\n}\n\nexport function journalActivation(runtimeRoot, actionId, state, detail = '') {\n if (!ACTION_ID_RE.test(actionId)) throw new Error('invalid runner action id');\n atomicWriteJson(join(runtimeRoot, 'transactions', `${actionId}.json`), {\n schema_version: 1,\n action_id: actionId,\n state,\n detail: String(detail).slice(0, 400),\n updated_at: new Date().toISOString(),\n });\n}\n\nexport function activateSlot(runtimeRoot, active, action) {\n if (!validActive(active)) throw new Error('cannot activate invalid runtime metadata');\n if (!ACTION_ID_RE.test(action.actionId)) throw new Error('invalid runner action id');\n if (!UUID_RE.test(String(action.supervisorInstanceId || ''))) throw new Error('invalid claiming supervisor instance id');\n const validated = validateSlot(runtimeRoot, active);\n if (!validated.ok) throw new Error(`cannot activate invalid runtime slot: ${validated.detail}`);\n const current = readActivation(runtimeRoot);\n if (current?.pending) throw new Error('another runtime activation is still pending');\n const pointer = {\n schema_version: 1,\n generation: randomUUID(),\n active,\n previous: validActive(current?.active) ? current.active : null,\n pending: {\n action_id: action.actionId,\n runner_id: String(action.runnerId || ''),\n operator_id: String(action.operatorId || ''),\n supervisor_instance_id: action.supervisorInstanceId,\n activated_at: new Date().toISOString(),\n ack_attempts: 0,\n },\n };\n // The pointer rename is the transaction commit and therefore the last\n // fallible write. A crash before it leaves the previous runtime selected.\n journalActivation(runtimeRoot, action.actionId, 'prepared', `${active.version} ${active.integrity}`);\n atomicWriteJson(join(runtimeRoot, 'current.json'), pointer);\n return pointer;\n}\n\nexport function activationSupervisorInstanceId(runtimeRoot, fallback) {\n const current = runtimeRoot ? readActivation(runtimeRoot) : null;\n const pending = String(current?.pending?.supervisor_instance_id || '');\n if (UUID_RE.test(pending)) return pending;\n return UUID_RE.test(String(fallback || '')) ? fallback : null;\n}\n\nexport function recordActivationRetry(runtimeRoot, pointer, detail) {\n const current = readActivation(runtimeRoot);\n if (current?.generation !== pointer?.generation\n || current?.pending?.action_id !== pointer?.pending?.action_id) {\n throw new Error('runtime activation generation changed before retry');\n }\n const attempts = Math.max(0, Number(current.pending.ack_attempts || 0)) + 1;\n const updated = {\n ...current,\n pending: { ...current.pending, ack_attempts: attempts, last_error: String(detail).slice(0, 240) },\n };\n atomicWriteJson(join(runtimeRoot, 'current.json'), updated);\n journalActivation(runtimeRoot, current.pending.action_id, 'ack-retry', `attempt ${attempts}: ${detail}`);\n return updated;\n}\n\n/** One-time migration for an old desktop launcher that has no control action. */\nexport function bootstrapSlot(runtimeRoot, active, bootstrapId) {\n if (!ACTION_ID_RE.test(bootstrapId)) throw new Error('invalid bootstrap id');\n const validated = validateSlot(runtimeRoot, active);\n if (!validated.ok) throw new Error(`cannot bootstrap invalid runtime slot: ${validated.detail}`);\n const current = readActivation(runtimeRoot);\n if (current?.pending) throw new Error('another runtime activation is still pending');\n if (current?.active?.slot_id === active.slot_id && current.active.integrity === active.integrity) return current;\n const pointer = {\n schema_version: 1,\n generation: randomUUID(),\n active,\n previous: validActive(current?.active) ? current.active : null,\n pending: null,\n };\n journalActivation(runtimeRoot, bootstrapId, 'bootstrap-prepared', `${active.version} ${active.integrity}`);\n atomicWriteJson(join(runtimeRoot, 'current.json'), pointer);\n try { journalActivation(runtimeRoot, bootstrapId, 'bootstrap-activated', `${active.version} active`); } catch { /* best effort */ }\n return pointer;\n}\n\n/** Restore the exact pre-bootstrap pointer without overwriting a newer activation. */\nexport function restoreBootstrapActivation(runtimeRoot, expectedActive, prior, rollbackId) {\n if (!ACTION_ID_RE.test(rollbackId)) throw new Error('invalid bootstrap rollback id');\n const current = readActivation(runtimeRoot);\n if (current?.active?.slot_id !== expectedActive?.slot_id\n || current?.active?.tree_sha512 !== expectedActive?.tree_sha512) {\n throw new Error('bootstrap activation changed before rollback');\n }\n if (prior?.schema_version === 1) {\n atomicWriteJson(join(runtimeRoot, 'current.json'), prior);\n } else {\n const quarantine = join(runtimeRoot, 'quarantine', `${rollbackId}-current.json`);\n mkdirSync(dirname(quarantine), { recursive: true });\n renameSync(join(runtimeRoot, 'current.json'), quarantine);\n }\n try { journalActivation(runtimeRoot, rollbackId, 'bootstrap-pointer-restored', expectedActive.version); }\n catch { /* the restored pointer is authoritative */ }\n}\n\nexport function attestCurrentSupervisor({ runtimeRoot, selfPath, version }) {\n const pointer = readActivation(runtimeRoot);\n if (!pointer?.pending || !validActive(pointer.active)) return { ok: false, detail: 'no pending activation' };\n const validated = validateSlot(runtimeRoot, pointer.active);\n if (!validated.ok) return validated;\n try {\n if (realpathSync(selfPath) !== realpathSync(validated.paths.supervisor)) {\n return { ok: false, detail: 'running supervisor is not the activated supervisor' };\n }\n } catch {\n return { ok: false, detail: 'could not resolve running supervisor path' };\n }\n if (version !== pointer.active.version) return { ok: false, detail: 'running supervisor version mismatch' };\n return { ok: true, pointer, active: pointer.active, paths: validated.paths };\n}\n\nexport function finalizeActivation(runtimeRoot, pointer) {\n const current = readActivation(runtimeRoot);\n if (current?.generation !== pointer?.generation\n || current?.pending?.action_id !== pointer?.pending?.action_id) {\n throw new Error('runtime activation generation changed before finalization');\n }\n journalActivation(runtimeRoot, pointer.pending.action_id, 'attesting', `${pointer.active.version} verified`);\n atomicWriteJson(join(runtimeRoot, 'current.json'), {\n schema_version: 1,\n generation: pointer.generation,\n active: pointer.active,\n previous: pointer.previous || null,\n pending: null,\n });\n // current.json is authoritative. A journal-only failure must never turn a\n // committed activation into a false update failure.\n try { journalActivation(runtimeRoot, pointer.pending.action_id, 'attested', `${pointer.active.version} active`); } catch { /* best effort */ }\n}\n\nexport function rollbackActivation(runtimeRoot, pointer, detail) {\n const current = readActivation(runtimeRoot);\n if (current?.generation !== pointer?.generation\n || current?.pending?.action_id !== pointer?.pending?.action_id) {\n throw new Error('runtime activation generation changed before rollback');\n }\n journalActivation(runtimeRoot, pointer.pending.action_id, 'rolling-back', detail);\n const rolledBack = {\n schema_version: 1,\n generation: randomUUID(),\n active: validActive(pointer?.previous) ? pointer.previous : null,\n previous: null,\n pending: {\n ...pointer.pending,\n terminal_status: 'failed',\n terminal_detail: String(detail).slice(0, 400),\n rolled_back_at: new Date().toISOString(),\n },\n };\n atomicWriteJson(join(runtimeRoot, 'current.json'), rolledBack);\n try { journalActivation(runtimeRoot, pointer.pending.action_id, 'rolled-back', detail); } catch { /* best effort */ }\n return rolledBack;\n}\n\nexport function acknowledgeActivationFailure(runtimeRoot, pointer) {\n const current = readActivation(runtimeRoot);\n if (current?.generation !== pointer?.generation\n || current?.pending?.action_id !== pointer?.pending?.action_id\n || current?.pending?.terminal_status !== 'failed') {\n throw new Error('runtime rollback acknowledgement obligation changed');\n }\n atomicWriteJson(join(runtimeRoot, 'current.json'), { ...current, pending: null });\n try { journalActivation(runtimeRoot, pointer.pending.action_id, 'failure-acknowledged', pointer.pending.terminal_detail); }\n catch { /* current.json is authoritative */ }\n}\n\nexport const __test = { ACTION_ID_RE, ENTRY_REL, INTEGRITY_RE, SLOT_ID_RE, SUPERVISOR_REL, UUID_RE, VERSION_RE, validActive, within };\n", "/**\n * legacy-orphan-sweep \u2014 operator-triggered reclamation of agent processes\n * leaked by PRE-REAPER daemons (they never recorded their spawns, so the\n * recorded-PID orphan-agent-reaper can NEVER touch them by design).\n *\n * This is deliberately NOT automatic: it runs only when a human presses the\n * \"Clear stuck agents\" control in AlgoHQ (a governed `purge-orphans` runner\n * control action), and only a supervisor advertising the\n * `legacy-orphan-purge-v1` capability will claim one.\n *\n * Because there are no records to trust, selection is by evidence that ALL\n * hold simultaneously:\n * 1. The command line matches a RUNNER-ONLY agent spawn signature\n * (`claude \u2026 --output-format stream-json` headless / `codex exec --json`).\n * Interactive agent sessions and detached watchers never match.\n * 2. The parent process is dead \u2014 absent, or its pid was reused by a process\n * created AFTER the child (an orphan's parent can never be younger).\n * A live daemon's agents always have a live parent, so a running peer\n * runner's work is structurally unselectable.\n * 3. The process predates the sweep cutoff (nothing racing the relaunch).\n * 4. The pid is not the supervisor itself or otherwise protected.\n * Selection is capped, oldest-first, and every kill is logged with its\n * command-line evidence. The decision core is pure and unit-tested; OS shims\n * are injected. Reuses the reaper's hardened epoch conversion + tree kill.\n */\nimport { spawnSync } from 'node:child_process';\nimport { killProcessTree, windowsPowershellExe } from './orphan-agent-reaper.mjs';\n\nexport const LEGACY_PURGE_CAPABILITY = 'legacy-orphan-purge-v1';\nexport const MAX_LEGACY_KILLS = 50;\n/** Ignore anything created within this window before the sweep (races). */\nexport const SWEEP_RECENCY_BUFFER_MS = 5_000;\n\nconst SIGNATURES = [\n {\n signature: 'claude-headless',\n // claude-args.mjs always emits `-p --output-format stream-json --verbose`.\n test: (cl) => /(?:^|[\\\\/\"\\s])claude(?:\\.exe|\\.cmd|\\.ps1)?(?:\"|\\s)/iu.test(cl) && /--output-format[\\s\"=]+stream-json/iu.test(cl),\n },\n {\n signature: 'codex-headless',\n // openai-compatible-runner always emits `exec --json`.\n test: (cl) => /(?:^|[\\\\/\"\\s])codex(?:\\.exe|\\.cmd|\\.ps1)?(?:\"|\\s)/iu.test(cl) && /\\bexec\\b/u.test(cl) && /--json\\b/u.test(cl),\n },\n];\n\n/** Which runner-agent signature (if any) a raw command line matches. */\nexport function matchAgentSignature(commandLine) {\n if (typeof commandLine !== 'string' || !commandLine) return null;\n for (const { signature, test } of SIGNATURES) {\n if (test(commandLine)) return signature;\n }\n return null;\n}\n\n/**\n * Pure selection. `processes` is an array of\n * `{ pid, ppid, creationMs, commandLine }`; returns `{ kills }` where each\n * kill is `{ pid, signature, commandLine }`, oldest-first, capped.\n */\nexport function selectLegacyOrphans({ processes, cutoffMs, protectedPids = new Set() }) {\n const byPid = new Map();\n for (const proc of processes) {\n if (Number.isInteger(proc?.pid) && proc.pid > 0) byPid.set(proc.pid, proc);\n }\n const kills = [];\n for (const proc of byPid.values()) {\n if (protectedPids.has(proc.pid)) continue;\n if (!(Number.isFinite(proc.creationMs) && proc.creationMs < cutoffMs)) continue;\n const signature = matchAgentSignature(proc.commandLine);\n if (!signature) continue;\n const parent = Number.isInteger(proc.ppid) && proc.ppid > 0 ? byPid.get(proc.ppid) : undefined;\n const parentDead = !parent || (Number.isFinite(parent.creationMs) && parent.creationMs > proc.creationMs);\n if (!parentDead) continue;\n kills.push({ pid: proc.pid, creationMs: proc.creationMs, signature, commandLine: proc.commandLine });\n }\n kills.sort((a, b) => a.creationMs - b.creationMs);\n return { kills: kills.slice(0, MAX_LEGACY_KILLS) };\n}\n\n/** One `ps -eo pid=,ppid=,etimes=,args=` line \u2192 process row (null on junk). */\nexport function parsePosixSweepLine(line, nowMs) {\n const match = /^\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(.+)$/u.exec(line ?? '');\n if (!match) return null;\n const pid = Number(match[1]);\n if (!Number.isInteger(pid) || pid <= 0) return null;\n return {\n pid,\n ppid: Number(match[2]),\n creationMs: nowMs - Number(match[3]) * 1000,\n commandLine: match[4],\n };\n}\n\n/**\n * Enumerate `{ pid, ppid, creationMs, commandLine }` for every visible\n * process. Windows via CIM (one compact JSON object per line so arbitrary\n * command-line content cannot break parsing; epoch via\n * DateTimeOffset.ToUnixTimeMilliseconds() \u2014 the manual UTC-offset form was\n * empirically \u22128h and silently disabled the recorded reaper before the same\n * guard was added there). Unenumerable rows are skipped (safe direction).\n */\nexport function listProcessesForSweep({ platform = process.platform, spawn = spawnSync, nowMs = Date.now(), env = process.env, warn = console.warn } = {}) {\n const rows = [];\n if (platform === 'win32') {\n const ps =\n \"Get-CimInstance Win32_Process | Where-Object { $_.CreationDate } | ForEach-Object { @{ p = $_.ProcessId; pp = $_.ParentProcessId; c = (([DateTimeOffset]$_.CreationDate.ToUniversalTime()).ToUnixTimeMilliseconds()); cl = [string]$_.CommandLine } | ConvertTo-Json -Compress }\";\n const result = spawn(windowsPowershellExe(env), ['-NoProfile', '-NonInteractive', '-Command', ps], {\n windowsHide: true,\n encoding: 'utf8',\n timeout: 30_000,\n maxBuffer: 64 * 1024 * 1024,\n });\n if (result.error || result.status !== 0) {\n // Failure must remain a NO-KILL sweep (safe direction) but never a silent\n // one: an empty enumeration is indistinguishable from \"no orphans\", so a\n // permanently broken shim would look healthy while processes accumulate.\n // Throwing (not returning []) makes runLegacyOrphanSweep report the\n // operator-triggered purge action as FAILED instead of \"0 scanned\".\n const cause = result.error ? result.error.message : `powershell exit ${result.status}`;\n warn(`[orphan-sweep] process enumeration failed (${cause}); sweeping nothing this cycle`);\n throw new Error(`process enumeration failed (${cause}); swept nothing`);\n }\n for (const line of String(result.stdout ?? '').split(/\\r?\\n/u)) {\n if (!line.trim()) continue;\n try {\n const parsed = JSON.parse(line);\n const pid = Number(parsed?.p);\n if (!Number.isInteger(pid) || pid <= 0) continue;\n rows.push({\n pid,\n ppid: Number(parsed.pp),\n creationMs: Number(parsed.c),\n commandLine: typeof parsed.cl === 'string' ? parsed.cl : '',\n });\n } catch {\n // one unparseable row must never abort the sweep enumeration\n }\n }\n return rows;\n }\n const result = spawn('ps', ['-eo', 'pid=,ppid=,etimes=,args='], { encoding: 'utf8', timeout: 30_000, maxBuffer: 64 * 1024 * 1024 });\n if (result.error || result.status !== 0) {\n const cause = result.error ? result.error.message : `ps exit ${result.status}`;\n warn(`[orphan-sweep] process enumeration failed (${cause}); sweeping nothing this cycle`);\n throw new Error(`process enumeration failed (${cause}); swept nothing`);\n }\n for (const line of String(result.stdout ?? '').split('\\n')) {\n const row = parsePosixSweepLine(line, nowMs);\n if (row) rows.push(row);\n }\n return rows;\n}\n\n/**\n * Execute the sweep. Never throws; returns\n * `{ ok, status, detail, killed: [{ pid, signature }] }` shaped for the\n * supervisor's action-completion contract. `detail` carries the evidence\n * summary that ends up on the AlgoHQ action record.\n */\nexport function runLegacyOrphanSweep({\n nowMs = Date.now(),\n protectedPids = [process.pid],\n listProcesses = listProcessesForSweep,\n killTree = killProcessTree,\n log = () => {},\n} = {}) {\n try {\n const processes = listProcesses({ nowMs });\n const { kills } = selectLegacyOrphans({\n processes,\n cutoffMs: nowMs - SWEEP_RECENCY_BUFFER_MS,\n protectedPids: new Set(protectedPids),\n });\n const killed = [];\n for (const kill of kills) {\n const done = killTree(kill.pid);\n log(`legacy-orphan-sweep ${done ? 'killed' : 'FAILED to kill'} pid=${kill.pid} sig=${kill.signature} cmd=${String(kill.commandLine).slice(0, 200)}`);\n if (done) killed.push({ pid: kill.pid, signature: kill.signature });\n }\n const failed = kills.length - killed.length;\n const detail = kills.length === 0\n ? `no orphaned agent processes matched the sweep criteria (${processes.length} scanned)`\n : `purged ${killed.length} of ${kills.length} orphaned agent process tree(s)${failed > 0 ? ` (${failed} kill(s) failed)` : ''}: ${killed.map((k) => `${k.pid}:${k.signature}`).join(', ').slice(0, 700)}`;\n return { ok: true, status: 0, detail, killed };\n } catch (error) {\n return { ok: false, status: 1, detail: `legacy sweep error: ${error instanceof Error ? error.message : String(error)}`.slice(0, 500), killed: [] };\n }\n}\n", "/**\n * Orphaned-agent process reaper.\n *\n * The runner spawns agent CLIs (claude/codex/\u2026) as child processes. When the\n * DAEMON itself restarts (crash, `update`/`reinstall` control, host reboot mid-\n * task), any still-running agent children are detached from the new daemon and\n * are never reclaimed \u2014 they leak RAM until the machine is rebooted. The\n * existing `terminal-process-cleanup` only kills the child the CURRENT process\n * still tracks; it deliberately never scans for unrelated processes.\n *\n * This module closes that gap SAFELY. Every spawned agent records its pid, its\n * spawning daemon instance id, and its spawn time under a per-instance registry\n * directory. On daemon startup the reaper considers only OTHER instances'\n * records and kills a process ONLY when ALL of these hold:\n *\n * 1. the recording daemon instance is provably DEAD (its recorded daemon pid\n * is not live, or its creation time no longer matches) \u2014 so a concurrent\n * live peer runner's agents are never touched;\n * 2. the agent pid is still live; AND\n * 3. the live process's OS creation time still matches the recorded spawn\n * time within tolerance \u2014 so a REUSED pid (now some innocent process)\n * is never killed.\n *\n * It never matches by process name and never touches a pid it did not itself\n * record. Decision logic is pure (`selectOrphanKills`) and fully unit-tested;\n * the OS shims (`listProcessCreationTimes`, `killProcessTree`) are injected.\n */\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nconst REGISTRY_ROOT_NAME = 'algohq-runner-agent-pids';\nconst DAEMON_RECORD = 'daemon.json';\n/** A reused pid is created long after the original; 30s covers spawn/clock skew. */\nexport const CREATION_MATCH_TOLERANCE_MS = 30_000;\n\nexport function registryRoot(tmp = os.tmpdir()) {\n return path.join(tmp, REGISTRY_ROOT_NAME);\n}\n\nfunction instanceDir(root, instanceId) {\n return path.join(root, String(instanceId).replace(/[^A-Za-z0-9_-]/g, ''));\n}\n\n/** Record this daemon instance so peers can tell it is alive vs. orphaned. */\nexport function registerDaemonInstance({\n root = registryRoot(),\n instanceId,\n daemonPid = process.pid,\n daemonStartedAtMs = Date.now(),\n} = {}) {\n if (!instanceId) return null;\n const dir = instanceDir(root, instanceId);\n mkdirSync(dir, { recursive: true });\n const file = path.join(dir, DAEMON_RECORD);\n writeFileSync(file, JSON.stringify({ daemonPid, daemonStartedAtMs, instanceId }), {\n encoding: 'utf8',\n mode: 0o600,\n });\n return file;\n}\n\n/** Record a spawned agent's pid under its daemon instance. Never throws. */\nexport function recordAgentPid({\n root = registryRoot(),\n instanceId = process.env.VO_RUNNER_INSTANCE_ID,\n pid,\n agentId = '',\n startedAtMs = Date.now(),\n} = {}) {\n if (!instanceId || !Number.isInteger(pid) || pid <= 0) return false;\n try {\n const dir = instanceDir(root, instanceId);\n mkdirSync(dir, { recursive: true });\n writeFileSync(\n path.join(dir, `${pid}.json`),\n JSON.stringify({ pid, agentId, startedAtMs, instanceId }),\n { encoding: 'utf8', mode: 0o600 },\n );\n return true;\n } catch {\n return false;\n }\n}\n\n/** Drop an agent record once its own process tree has been reaped. Never throws. */\nexport function unrecordAgentPid({\n root = registryRoot(),\n instanceId = process.env.VO_RUNNER_INSTANCE_ID,\n pid,\n} = {}) {\n if (!instanceId || !Number.isInteger(pid)) return false;\n try {\n rmSync(path.join(instanceDir(root, instanceId), `${pid}.json`), { force: true });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * One-call daemon startup hook: publishes this instance id (so in-process\n * spawns can self-record), records the daemon, and reaps orphaned agent trees\n * left by dead prior instances. Synchronous and swallow-safe \u2014 never blocks the\n * runner from coming up.\n */\nexport function bootstrapOrphanReaper({ instanceId, log = () => {} } = {}) {\n if (!instanceId) return { killed: 0, prunedDirs: 0 };\n process.env.VO_RUNNER_INSTANCE_ID = instanceId;\n try {\n registerDaemonInstance({ instanceId });\n } catch {\n /* best effort \u2014 reap still runs */\n }\n return reapOrphanedAgents({ currentInstanceId: instanceId, log });\n}\n\n/** Read every instance's records from disk into the shape selectOrphanKills wants. */\nexport function readRegistry({ root = registryRoot(), currentInstanceId } = {}) {\n const instances = [];\n if (!existsSync(root)) return instances;\n let dirents;\n try {\n dirents = readdirSync(root, { withFileTypes: true });\n } catch {\n return instances;\n }\n for (const dirent of dirents) {\n if (!dirent.isDirectory()) continue;\n if (currentInstanceId && dirent.name === instanceDirName(currentInstanceId)) continue;\n const dir = path.join(root, dirent.name);\n let daemon = null;\n const agents = [];\n let files;\n try {\n files = readdirSync(dir);\n } catch {\n continue;\n }\n for (const name of files) {\n let parsed;\n try {\n parsed = JSON.parse(readFileSync(path.join(dir, name), 'utf8'));\n } catch {\n continue;\n }\n if (name === DAEMON_RECORD) {\n if (Number.isInteger(parsed?.daemonPid)) {\n daemon = { pid: parsed.daemonPid, startedAtMs: Number(parsed.daemonStartedAtMs) || 0 };\n }\n } else if (Number.isInteger(parsed?.pid)) {\n agents.push({ pid: parsed.pid, agentId: String(parsed.agentId || ''), startedAtMs: Number(parsed.startedAtMs) || 0 });\n }\n }\n instances.push({ instanceId: dirent.name, dir, daemon, agents });\n }\n return instances;\n}\n\nfunction instanceDirName(instanceId) {\n return String(instanceId).replace(/[^A-Za-z0-9_-]/g, '');\n}\n\nfunction creationMatches(live, recordedStartedAtMs, toleranceMs) {\n if (!live || !Number.isFinite(live.creationMs)) return false;\n if (!Number.isFinite(recordedStartedAtMs) || recordedStartedAtMs <= 0) return false;\n return Math.abs(live.creationMs - recordedStartedAtMs) <= toleranceMs;\n}\n\n/**\n * PURE decision core. Given the on-disk registry (other instances only) and a\n * map of live pid \u2192 { creationMs }, decide which pids to kill and which\n * instance dirs to prune.\n *\n * - An instance whose daemon record is still live (pid alive + creation match)\n * is a running PEER: skip it entirely (no kills, no prune).\n * - Otherwise the instance is dead: kill each recorded agent that is still live\n * AND whose creation time matches (guards pid reuse), then prune its dir.\n */\nexport function selectOrphanKills({ instances = [], liveProcesses = new Map(), toleranceMs = CREATION_MATCH_TOLERANCE_MS } = {}) {\n const kills = [];\n const pruneDirs = [];\n for (const instance of instances) {\n // Require a PRESENT daemon record before killing anything. Without it we\n // cannot distinguish a truly-crashed instance from a peer that just created\n // its dir and has not written daemon.json yet, so we conservatively prune\n // the stale/malformed dir but never kill. (registerDaemonInstance writes\n // daemon.json before any agent is spawned, so a real instance with agent\n // records always has one.)\n if (!instance.daemon) {\n if (instance.dir) pruneDirs.push(instance.dir);\n continue;\n }\n const daemonLive =\n liveProcesses.has(instance.daemon.pid) &&\n creationMatches(liveProcesses.get(instance.daemon.pid), instance.daemon.startedAtMs, toleranceMs);\n if (daemonLive) continue; // live peer runner \u2014 never touch its agents\n for (const agent of instance.agents) {\n const live = liveProcesses.get(agent.pid);\n if (live && creationMatches(live, agent.startedAtMs, toleranceMs)) {\n kills.push({ pid: agent.pid, agentId: agent.agentId, instanceId: instance.instanceId });\n }\n }\n if (instance.dir) pruneDirs.push(instance.dir);\n }\n return { kills, pruneDirs };\n}\n\nfunction windowsSystemRoot(env = process.env) {\n return env.SystemRoot || env.WINDIR || 'C:\\\\Windows';\n}\n\n/**\n * Absolute Windows PowerShell path. Never resolve `powershell` from PATH: the\n * reaper runs with the daemon's privileges, so a PATH-planted powershell.exe\n * would receive every process command line on the host. Same resolution as\n * runner-bootstrap/windows-bound-process-termination.mjs.\n */\nexport function windowsPowershellExe(env = process.env) {\n return path.join(windowsSystemRoot(env), 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');\n}\n\n/** Windows: map every process to its creation time in epoch ms via CIM. */\nexport function listProcessCreationTimes({ platform = process.platform, spawn = spawnSync, env = process.env, warn = console.warn } = {}) {\n const map = new Map();\n if (platform === 'win32') {\n // Epoch conversion via DateTimeOffset.ToUnixTimeMilliseconds() \u2014 the manual\n // `(CreationDate - Get-Date '1970-01-01Z')` form is off by the local UTC\n // offset (empirically \u22128h on a PST host), which would push every creation\n // time outside the match window and silently disable the reaper.\n const ps =\n \"Get-CimInstance Win32_Process | ForEach-Object { '{0} {1}' -f $_.ProcessId, (([DateTimeOffset]$_.CreationDate.ToUniversalTime()).ToUnixTimeMilliseconds()) }\";\n const result = spawn(windowsPowershellExe(env), ['-NoProfile', '-NonInteractive', '-Command', ps], {\n windowsHide: true,\n encoding: 'utf8',\n timeout: 20_000,\n maxBuffer: 32 * 1024 * 1024,\n });\n if (result.error || result.status !== 0 || typeof result.stdout !== 'string') {\n // An enumeration failure must stay a NO-KILL cycle (safe direction), but\n // never a silent one \u2014 a permanently failing shim reads as \"no orphans\"\n // and the fleet leaks agent processes until reboot.\n warn(`[orphan-reaper] process enumeration failed (${result.error ? result.error.message : `powershell exit ${result.status}`}); reaping nothing this cycle`);\n return map;\n }\n for (const line of result.stdout.split(/\\r?\\n/)) {\n const m = line.trim().match(/^(\\d+)\\s+(-?\\d+)$/);\n if (m) map.set(Number(m[1]), { creationMs: Number(m[2]) });\n }\n return map;\n }\n // POSIX: ps lstart \u2192 epoch ms (macOS/Linux runner). Windows is the primary\n // target and is verified end-to-end; this branch is validated via the pure\n // parsePosixPsLine() unit tests.\n const result = spawn('ps', ['-eo', 'pid=,lstart='], { encoding: 'utf8', timeout: 20_000, maxBuffer: 32 * 1024 * 1024 });\n if (result.error || result.status !== 0 || typeof result.stdout !== 'string') {\n warn(`[orphan-reaper] process enumeration failed (${result.error ? result.error.message : `ps exit ${result.status}`}); reaping nothing this cycle`);\n return map;\n }\n for (const line of result.stdout.split(/\\r?\\n/)) {\n const parsed = parsePosixPsLine(line);\n if (parsed) map.set(parsed.pid, { creationMs: parsed.creationMs });\n }\n return map;\n}\n\n/**\n * Parse one `ps -eo pid=,lstart=` line into { pid, creationMs } or null.\n * Handles padded pids, the single-digit-day double space (\"Mon Jan 5 \u2026\"), and\n * unparseable lines (\u2192 null, so the caller skips them \u2014 the safe direction).\n */\nexport function parsePosixPsLine(line) {\n const trimmed = String(line ?? '').trim();\n const sp = trimmed.indexOf(' ');\n if (sp <= 0) return null;\n const pid = Number(trimmed.slice(0, sp));\n const when = Date.parse(trimmed.slice(sp + 1).trim());\n if (!Number.isInteger(pid) || pid <= 0 || !Number.isFinite(when)) return null;\n return { pid, creationMs: when };\n}\n\n/** Kill an exact pid's whole tree. Windows taskkill /T /F, else SIGKILL by pgid. */\nexport function killProcessTree(pid, { platform = process.platform, spawn = spawnSync, env = process.env } = {}) {\n if (!Number.isInteger(pid) || pid <= 0) return false;\n if (platform === 'win32') {\n // Absolute path for the same reason as windowsPowershellExe(): a PATH-planted\n // taskkill.exe would execute with daemon privileges and could silently no-op\n // every kill while the sweep logs success.\n const taskkill = path.join(windowsSystemRoot(env), 'System32', 'taskkill.exe');\n const r = spawn(taskkill, ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore', timeout: 15_000 });\n return !r.error && r.status === 0;\n }\n try {\n process.kill(-pid, 'SIGKILL');\n return true;\n } catch {\n try {\n process.kill(pid, 'SIGKILL');\n return true;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * EFFECTFUL entry point: run at daemon startup. Reaps orphaned agent trees from\n * dead prior instances and prunes their registry dirs. Never throws \u2014 a reaper\n * failure must not block the runner from coming up.\n */\nexport function reapOrphanedAgents({\n root = registryRoot(),\n currentInstanceId = process.env.VO_RUNNER_INSTANCE_ID,\n toleranceMs = CREATION_MATCH_TOLERANCE_MS,\n listProcesses = listProcessCreationTimes,\n killTree = killProcessTree,\n log = () => {},\n} = {}) {\n try {\n const instances = readRegistry({ root, currentInstanceId });\n if (instances.length === 0) return { killed: 0, prunedDirs: 0 };\n const liveProcesses = listProcesses();\n const { kills, pruneDirs } = selectOrphanKills({ instances, liveProcesses, toleranceMs });\n let killed = 0;\n for (const kill of kills) {\n if (killTree(kill.pid)) {\n killed += 1;\n log(`reaped orphaned agent pid ${kill.pid}${kill.agentId ? ` (${kill.agentId})` : ''} from dead instance ${kill.instanceId}`);\n }\n }\n let prunedDirs = 0;\n for (const dir of pruneDirs) {\n try {\n rmSync(dir, { recursive: true, force: true });\n prunedDirs += 1;\n } catch {\n /* leave it; next startup retries */\n }\n }\n if (killed > 0 || prunedDirs > 0) log(`orphan reap: killed ${killed} agent tree(s), pruned ${prunedDirs} dead instance record(s)`);\n return { killed, prunedDirs };\n } catch (error) {\n log(`orphan reap skipped: ${error instanceof Error ? error.message : String(error)}`);\n return { killed: 0, prunedDirs: 0 };\n }\n}\n", "import {\n acknowledgeActivationFailure,\n attestCurrentSupervisor,\n finalizeActivation,\n readActivation,\n recordActivationRetry,\n rollbackActivation,\n validateSlot,\n} from './bundled-runtime-store.mjs';\n\nconst MAX_ACK_ATTEMPTS = 3;\nconst delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nexport async function waitForAuthoritativeRunnerHeartbeat({\n client,\n runnerId,\n operatorId,\n runnerInstanceId,\n excludeRunnerInstanceId,\n daemonVersion,\n supervisorIdentity,\n timeoutMs = 60_000,\n pollMs = 1_000,\n}) {\n if (!runnerInstanceId && !excludeRunnerInstanceId) throw new Error('runner instance identity proof unavailable');\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n try {\n const runners = await client.getRunnerStatus({ ...(operatorId ? { operatorId } : {}) });\n const runner = runners.find((item) => item?.runner_id === runnerId\n && item.status === 'online'\n && (runnerInstanceId\n ? item.runner_meta?.runner_instance_id === runnerInstanceId\n : Boolean(item.runner_meta?.runner_instance_id)\n && item.runner_meta.runner_instance_id !== excludeRunnerInstanceId)\n && item.runner_meta?.daemon_version === daemonVersion\n && item.runner_meta?.supervisor_instance_id === supervisorIdentity.supervisorInstanceId\n && item.runner_meta?.supervisor_version === supervisorIdentity.supervisorVersion\n && supervisorIdentity.capabilities.every((value) => item.runner_meta?.supervisor_capabilities?.includes(value))\n && Array.isArray(item.runner_meta?.available_agents)\n // The default agent must be INSTALLED for the activated runtime to be the\n // one that will serve. Whether it is AUTHENTICATED is a serving gate the\n // heartbeat already reports (available_agents[].authenticated) and the\n // plane already dispatches on; it is not part of the runtime's identity.\n // Requiring it here made an expired or never-done agent login fail every\n // activation closed: the child was stopped after 60 s, the supervisor\n // degraded, and the host went silent until a human restarted the app\n // (FintonLaptop, 2026-09-04: claude installed, authenticated:false).\n && item.runner_meta.available_agents.some((agent) => agent.agent === item.runner_meta.default_agent\n && agent.installed === true));\n if (runner) return runner;\n } catch { /* bounded retry */ }\n await delay(pollMs);\n }\n throw new Error('authoritative child heartbeat attestation timed out');\n}\n\n/**\n * Complete a slot handoff only from the activated package and logical Tauri\n * supervisor lease. Local path/version/hash and child readiness are proven\n * before a cloud heartbeat or terminal action acknowledgement is emitted.\n */\nexport async function finishPendingActivation({\n client,\n child,\n runtimeRoot,\n operatorId,\n runnerId,\n selfPath,\n packageVersion,\n supervisorIdentity,\n waitForLocalRunner,\n isReadinessDeferred = () => false,\n localStatus,\n waitForCloudRunner = waitForAuthoritativeRunnerHeartbeat,\n cloudTimeoutMs,\n cloudPollMs,\n stopChild,\n launchPreviousChild,\n log = () => {},\n}) {\n const pointer = runtimeRoot ? readActivation(runtimeRoot) : null;\n if (!pointer?.pending) return true;\n const runnerIdForAction = pointer.pending.runner_id || runnerId;\n const operatorIdForAction = pointer.pending.operator_id || operatorId;\n if (pointer.pending.terminal_status === 'failed') {\n try {\n await client.completeRunnerControl(pointer.pending.action_id, {\n runnerId: runnerIdForAction,\n ...(operatorIdForAction ? { operatorId: operatorIdForAction } : {}),\n ...supervisorIdentity,\n status: 'failed',\n detail: pointer.pending.terminal_detail,\n });\n acknowledgeActivationFailure(runtimeRoot, pointer);\n return true;\n } catch (error) {\n log(`activation failure acknowledgement remains pending: ${error instanceof Error ? error.message : String(error)}`);\n await stopChild(child);\n return false;\n }\n }\n let attestation;\n try {\n attestation = attestCurrentSupervisor({ runtimeRoot, selfPath, version: packageVersion });\n if (!attestation.ok) throw new Error(attestation.detail);\n if (!(await waitForLocalRunner(child))) {\n // A supervisor-authenticated exit-75 readiness embargo is neither a bad\n // runtime nor an attestation failure. Preserve the active/pending pointer\n // exactly; the supervisor will re-probe and retry this same slot later.\n if (isReadinessDeferred(child)) return false;\n throw new Error('activated runner did not become locally ready');\n }\n } catch (error) {\n let detail = `activation attestation failed: ${error instanceof Error ? error.message : String(error)}`.slice(0, 400);\n let rolledBack = null;\n try {\n rolledBack = rollbackActivation(runtimeRoot, pointer, detail);\n } catch (rollbackError) {\n detail = `${detail}; rollback pending: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`.slice(0, 400);\n }\n try {\n await client.completeRunnerControl(pointer.pending.action_id, {\n runnerId: runnerIdForAction,\n ...(operatorIdForAction ? { operatorId: operatorIdForAction } : {}),\n ...supervisorIdentity,\n status: 'failed',\n detail,\n });\n if (rolledBack) acknowledgeActivationFailure(runtimeRoot, rolledBack);\n } catch {\n // current.json retains the terminal acknowledgement obligation.\n } finally {\n await stopChild(child);\n }\n return false;\n }\n\n let activatedRunnerInstanceId = null;\n try {\n const status = await localStatus();\n activatedRunnerInstanceId = status?.runnerInstanceId || null;\n await waitForCloudRunner({\n client,\n runnerId: runnerIdForAction,\n operatorId: operatorIdForAction,\n runnerInstanceId: status?.runnerInstanceId,\n daemonVersion: `vo-mcp/${attestation.active.version}`,\n supervisorIdentity,\n timeoutMs: cloudTimeoutMs,\n pollMs: cloudPollMs,\n });\n await client.completeRunnerControl(pointer.pending.action_id, {\n runnerId: runnerIdForAction,\n ...(operatorIdForAction ? { operatorId: operatorIdForAction } : {}),\n ...supervisorIdentity,\n status: 'succeeded',\n detail: `attested new supervisor ${attestation.active.version} ${attestation.active.integrity}`,\n });\n finalizeActivation(runtimeRoot, attestation.pointer);\n return true;\n } catch (error) {\n const failure = `activation acknowledgement failed: ${error instanceof Error ? error.message : String(error)}`.slice(0, 400);\n let retry;\n try { retry = recordActivationRetry(runtimeRoot, attestation.pointer, failure); }\n catch (retryError) {\n log(`activation retry could not be recorded: ${retryError instanceof Error ? retryError.message : String(retryError)}`);\n await stopChild(child);\n return false;\n }\n if (retry.pending.ack_attempts < MAX_ACK_ATTEMPTS) {\n log(`activation acknowledgement pending (${retry.pending.ack_attempts}/${MAX_ACK_ATTEMPTS})`);\n await stopChild(child);\n return false;\n }\n\n const previous = validateSlot(runtimeRoot, retry.previous);\n let detail = `${failure}; retry limit reached; previous runtime restored`.slice(0, 400);\n let rollbackChild = null;\n let rolledBack = null;\n try {\n if (!previous.ok) throw new Error(`previous runtime invalid: ${previous.detail}`, { cause: error });\n rolledBack = rollbackActivation(runtimeRoot, retry, detail);\n await stopChild(child);\n rollbackChild = launchPreviousChild(previous.paths.entry);\n if (!(await waitForLocalRunner(rollbackChild))) throw new Error('previous runner did not become locally ready', { cause: error });\n const status = await localStatus();\n await waitForCloudRunner({\n client,\n runnerId: runnerIdForAction,\n operatorId: operatorIdForAction,\n runnerInstanceId: status?.runnerInstanceId,\n excludeRunnerInstanceId: status?.runnerInstanceId ? undefined : activatedRunnerInstanceId,\n daemonVersion: `vo-mcp/${retry.previous.version}`,\n supervisorIdentity,\n timeoutMs: cloudTimeoutMs,\n pollMs: cloudPollMs,\n });\n } catch (rollbackError) {\n detail = `${detail}; rollback proof failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`.slice(0, 400);\n }\n try {\n await client.completeRunnerControl(retry.pending.action_id, {\n runnerId: runnerIdForAction,\n ...(operatorIdForAction ? { operatorId: operatorIdForAction } : {}),\n ...supervisorIdentity,\n status: 'failed',\n detail,\n });\n if (rolledBack) acknowledgeActivationFailure(runtimeRoot, rolledBack);\n } catch { /* current.json retains the terminal acknowledgement obligation */ }\n if (rollbackChild) await stopChild(rollbackChild);\n else await stopChild(child);\n return false;\n }\n}\n\nexport const __test = { MAX_ACK_ATTEMPTS };\n", "/**\n * Resolve the runner child entry on EVERY (re)spawn instead of once at module\n * load.\n *\n * The supervisor used to compute `join(dirname(selfPath), 'runner-cli.js')` at\n * module scope and reuse that single path for every child it ever spawned. A\n * staged runtime slot could therefore be activated (current.json rewritten,\n * child restarted) and the host would keep running the OLD daemon until the\n * whole desktop app was restarted \u2014 which nothing forces. That is the same\n * silently-inert-update class as the 2026-08-06 slot-cache-poisoning incident:\n * the update reports success, the bytes on disk are new, and the process\n * serving work is unchanged.\n *\n * Rules encoded here:\n * - Re-read the activation pointer on every call; never cache.\n * - Fall back to the bundled self-relative entry whenever there is no slot,\n * the pointer is unreadable, an activation is still mid-transaction, or the\n * slot fails full hash validation. Fail closed, never fail open.\n * - NEVER downgrade: an active slot older than (or equal to) the bundled\n * version keeps the bundled path. Mirrors the strictly-newer compare in\n * cloud-run/vo-control-plane/src/routes/runner-auto-update.ts.\n */\nimport { readActivation, validateSlot } from './bundled-runtime-store.mjs';\n\n/** Tolerates an optional \"name/\" prefix so `vo-mcp/0.2.0` parses too. */\nconst VERSION_RE = /^(?:[\\w.-]+\\/)?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?$/u;\n\nexport function parseRuntimeVersion(value) {\n if (typeof value !== 'string') return null;\n const match = VERSION_RE.exec(value.trim());\n if (!match) return null;\n const prerelease = match[4]\n ? match[4].split('.').map((part) => (/^\\d+$/u.test(part) ? Number(part) : part))\n : null;\n return { release: [Number(match[1]), Number(match[2]), Number(match[3])], prerelease };\n}\n\n/** semver-style compare: -1 when a < b, 0 when equal, 1 when a > b. */\nexport function compareRuntimeVersions(a, b) {\n for (let i = 0; i < 3; i += 1) {\n const av = a.release[i] ?? 0;\n const bv = b.release[i] ?? 0;\n if (av !== bv) return av < bv ? -1 : 1;\n }\n if (!a.prerelease && !b.prerelease) return 0;\n if (!a.prerelease) return 1; // release > any prerelease of the same core\n if (!b.prerelease) return -1;\n const len = Math.max(a.prerelease.length, b.prerelease.length);\n for (let i = 0; i < len; i += 1) {\n const av = a.prerelease[i];\n const bv = b.prerelease[i];\n if (av === undefined) return -1; // shorter prerelease sorts first\n if (bv === undefined) return 1;\n if (av === bv) continue;\n const aNum = typeof av === 'number';\n const bNum = typeof bv === 'number';\n if (aNum && bNum) return av < bv ? -1 : 1;\n if (aNum !== bNum) return aNum ? -1 : 1; // numeric identifiers sort first\n return String(av) < String(bv) ? -1 : 1;\n }\n return 0;\n}\n\n/**\n * @returns {{ args: string[], entry: string, source: 'bundled'|'active-slot',\n * version: string, descriptor: string, detail: string }}\n * `descriptor` is a stable identity for change detection/logging.\n */\nexport function resolveSupervisorChildEntry({\n runtimeRoot,\n bundledEntry,\n bundledVersion,\n readPointer = readActivation,\n validate = validateSlot,\n}) {\n const bundled = (detail) => ({\n // The bundled entry is `dist/runner-cli.js`, which IS the daemon and takes\n // no subcommand. The slot entry is `bin/vo-mcp`, the multiplexed CLI, which\n // needs the `runner` subcommand \u2014 the same argv the proven rollback path\n // (`launchPreviousChild`) uses.\n args: [bundledEntry],\n entry: bundledEntry,\n source: 'bundled',\n version: String(bundledVersion || 'unknown'),\n descriptor: `bundled ${bundledVersion || 'unknown'} ${bundledEntry}`,\n detail,\n });\n\n if (!runtimeRoot) return bundled('no runtime root');\n\n let pointer;\n try {\n pointer = readPointer(runtimeRoot);\n } catch (error) {\n return bundled(`activation pointer unreadable: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (!pointer?.active) return bundled('no activated runtime slot');\n // Mid-transaction. finishPendingActivation() owns that handoff (it attests\n // from the NEW supervisor process); adopting the slot here would run a new\n // daemon under an un-attested old supervisor.\n if (pointer.pending) return bundled('runtime activation still pending');\n\n const activeVersion = parseRuntimeVersion(pointer.active.version);\n const currentVersion = parseRuntimeVersion(bundledVersion);\n // An unparseable version on either side means the never-downgrade rule cannot\n // be PROVEN, so it is enforced by refusing the slot.\n if (!activeVersion) return bundled(`active slot version unparseable: ${String(pointer.active.version)}`);\n if (!currentVersion) return bundled(`bundled version unparseable: ${String(bundledVersion)}`);\n if (compareRuntimeVersions(activeVersion, currentVersion) <= 0) {\n return bundled(`active slot ${pointer.active.version} is not newer than bundled ${bundledVersion}`);\n }\n\n let validated;\n try {\n validated = validate(runtimeRoot, pointer.active);\n } catch (error) {\n return bundled(`slot validation threw: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (!validated?.ok) return bundled(`active slot invalid: ${validated?.detail || 'unknown'}`);\n\n const entry = validated.paths.entry;\n return {\n args: [entry, 'runner'],\n entry,\n source: 'active-slot',\n version: pointer.active.version,\n descriptor: `active-slot ${pointer.active.version} ${entry}`,\n detail: `activated slot ${pointer.active.slot_id}`,\n };\n}\n", "/**\n * Drain in-flight code tasks BEFORE a staged update restarts the runner child.\n *\n * Incident 2026-08-30 ~08:0x: both fleet runners (FintonLaptop, JacksPC)\n * restarted near-simultaneously on a staged-update delivery and killed the\n * in-flight continuations of two tasks (7f98ab24 at preparing_worktree,\n * 2c7ea978 at agent_working). Both went status=failed with NO error_message on\n * the plane, and both runners heartbeated fresh seconds later \u2014 so the plane\n * recorded a silent death with no cause. Cost: two $2 recovery resumes.\n *\n * The pre-existing guard in runner-supervisor.mjs was a SINGLE check that\n * failed the control action outright, and it read\n * `beforeStop && activeTasks > 0` \u2014 an unreadable `/status` (null) fell\n * through to the restart, which is exactly the fail-open shape that kills work.\n *\n * What this module changes, and nothing else (the two-track staging/delivery\n * mechanism is untouched \u2014 this gates only the APPLICATION of the restart):\n * - update/reinstall actions WAIT for the child to go idle, re-checking on an\n * interval, instead of failing the action on the first busy check.\n * - An unreadable `/status` from a RUNNING child counts as busy, not idle.\n * A child that is not running has nothing to drain and proceeds at once, so\n * the supervisor's only remote repair channel can never be self-blocked.\n * - The wait is hard-capped (default 45 min). At the cap the restart proceeds,\n * but every in-flight task is first marked terminal on the plane with a\n * message that NAMES the update restart. Never kill silently.\n * - Non-update control actions (repair/maintenance/purge) keep the legacy\n * single-check defer, including its legacy fail-open on an unreadable\n * status: blocking remote repair for up to 45 minutes behind an\n * unresponsive status port would be a worse failure than the one fixed here.\n *\n * Task ids come from the runner's OWN in-flight registry, surfaced on\n * `GET /status` as `activeTaskIds` (scripts/virtual-office/code-runner-daemon.mjs\n * \u2192 control-server.mjs). The same status snapshot carries `runnerId` /\n * `runnerInstanceId`, which the terminal patch MUST echo: the plane rejects a\n * protocol-v2 progress patch that omits them\n * (cloud-run/vo-control-plane/src/storage/code-task-progress-merge.ts:63).\n */\n\nexport const DEFAULT_DRAIN_CAP_MS = 45 * 60 * 1000;\nexport const DEFAULT_DRAIN_CHECK_MS = 30_000;\nconst MAX_DRAIN_CAP_MS = 6 * 60 * 60 * 1000;\nconst MIN_DRAIN_CHECK_MS = 1_000;\nconst MAX_DRAIN_CHECK_MS = 5 * 60 * 1000;\n\n/** Terminal message + result stamped on tasks killed by a capped drain. */\nexport const UPDATE_RESTART_ERROR_MESSAGE = 'runner update restart after drain timeout';\nexport const UPDATE_RESTART_RESULT = 'runner_update_restart';\n\nconst sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\nfunction positiveNumber(raw) {\n if (raw === undefined || raw === null || String(raw).trim() === '') return null;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0 ? value : null;\n}\n\n/**\n * `VO_RUNNER_UPDATE_DRAIN_CAP_MIN` (minutes) is the operator-facing knob;\n * `VO_RUNNER_UPDATE_DRAIN_CAP_MS` wins when both are set (tests use it).\n * 0 disables draining entirely \u2014 the restart proceeds immediately, but the\n * cap path still marks in-flight tasks, so nothing dies unexplained.\n */\nexport function resolveDrainCapMs(env = {}) {\n const ms = positiveNumber(env.VO_RUNNER_UPDATE_DRAIN_CAP_MS);\n if (ms !== null) return Math.min(ms, MAX_DRAIN_CAP_MS);\n const minutes = positiveNumber(env.VO_RUNNER_UPDATE_DRAIN_CAP_MIN);\n if (minutes !== null) return Math.min(minutes * 60_000, MAX_DRAIN_CAP_MS);\n return DEFAULT_DRAIN_CAP_MS;\n}\n\nexport function resolveDrainCheckMs(env = {}) {\n const ms = positiveNumber(env.VO_RUNNER_UPDATE_DRAIN_CHECK_MS);\n if (ms === null) return DEFAULT_DRAIN_CHECK_MS;\n return Math.min(Math.max(ms, MIN_DRAIN_CHECK_MS), MAX_DRAIN_CHECK_MS);\n}\n\n/**\n * Normalize one `/status` snapshot into the drain view.\n * `known:false` means \"a child is running but did not answer\" \u2014 busy for the\n * update path, idle for the legacy path (see the module header).\n * @returns {{ count: number, ids: string[], known: boolean,\n * runnerId: string|null, runnerInstanceId: string|null }}\n */\nexport function readActiveTasks(status, { childRunning = true } = {}) {\n if (!childRunning) {\n return { count: 0, ids: [], known: true, runnerId: null, runnerInstanceId: null };\n }\n if (!status || status.ok === false) {\n return { count: 0, ids: [], known: false, runnerId: null, runnerInstanceId: null };\n }\n const ids = Array.isArray(status.activeTaskIds)\n ? status.activeTaskIds.map((id) => String(id)).filter(Boolean)\n : [];\n const reported = Number(status.activeTasks);\n const count = Number.isFinite(reported) && reported >= 0 ? reported : ids.length;\n return {\n count: Math.max(count, ids.length),\n ids,\n known: true,\n runnerId: status.runnerId ? String(status.runnerId) : null,\n runnerInstanceId: status.runnerInstanceId ? String(status.runnerInstanceId) : null,\n };\n}\n\n/**\n * Pure one-iteration decision.\n * @returns {{ action: 'proceed'|'wait'|'cap', busy: number|'unknown' }}\n */\nexport function decideDrainStep({ active, elapsedMs, capMs }) {\n const busy = active.known ? active.count : 'unknown';\n if (active.known && active.count === 0) return { action: 'proceed', busy };\n if (elapsedMs >= capMs) return { action: 'cap', busy };\n return { action: 'wait', busy };\n}\n\nfunction describeBusy(active) {\n if (!active.known) return 'status unreadable from a running child (assumed busy)';\n const ids = active.ids.length > 0 ? ` [${active.ids.join(', ')}]` : ' [ids unavailable]';\n return `${active.count} active task(s)${ids}`;\n}\n\nasync function markCappedTasks({ active, failInFlightTask, log }) {\n if (active.ids.length === 0) {\n if (active.count > 0 || !active.known) {\n log(`update drain cap reached with ${describeBusy(active)} \u2014 cannot annotate tasks the runner did not name`);\n }\n return [];\n }\n const marked = [];\n for (const taskId of active.ids) {\n try {\n await failInFlightTask(taskId, {\n message: UPDATE_RESTART_ERROR_MESSAGE,\n result: UPDATE_RESTART_RESULT,\n runnerId: active.runnerId,\n runnerInstanceId: active.runnerInstanceId,\n });\n marked.push(taskId);\n } catch (error) {\n log(`could not mark task ${taskId} before update restart: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return marked;\n}\n\n/**\n * Gate the application of a staged-update restart on the runner going idle.\n *\n * @param {object} options\n * @param {() => Promise<object|null>} options.readStatus local `GET /status`\n * @param {() => boolean} options.isChildRunning live child liveness\n * @param {(taskId: string, patch: object) => Promise<unknown>} options.failInFlightTask\n * @param {boolean} options.drainable true only for update/reinstall actions\n * @param {object} [options.env] cap/interval knobs\n * @param {() => number} [options.now] injected clock (tests)\n * @param {(ms: number) => Promise<void>} [options.sleep] injected sleep (tests)\n * @param {(message: string) => void} [options.log]\n * @returns {Promise<{ proceed: boolean, detail: string, capped: boolean,\n * waitedMs: number, checks: number, markedTaskIds: string[] }>}\n */\nexport async function awaitRunnerUpdateDrain({\n readStatus,\n isChildRunning = () => true,\n failInFlightTask = async () => {},\n drainable = false,\n env = {},\n now = Date.now,\n sleep = sleepMs,\n log = () => {},\n} = {}) {\n const capMs = resolveDrainCapMs(env);\n const checkMs = resolveDrainCheckMs(env);\n const startedAt = now();\n let checks = 0;\n let lastReported = null;\n\n const snapshot = async () => {\n checks += 1;\n const childRunning = Boolean(isChildRunning());\n let status;\n try {\n status = await readStatus();\n } catch {\n status = null;\n }\n return readActiveTasks(status, { childRunning });\n };\n\n // Legacy single-check defer for non-update actions. Unchanged on purpose:\n // an unreadable status still proceeds so remote repair is never self-blocked.\n if (!drainable) {\n const active = await snapshot();\n if (active.known && active.count > 0) {\n return {\n proceed: false,\n detail: `deferred safely: ${active.count} active task(s); retry when the runner is idle`,\n capped: false,\n waitedMs: 0,\n checks,\n markedTaskIds: [],\n };\n }\n return { proceed: true, detail: 'runner idle', capped: false, waitedMs: 0, checks, markedTaskIds: [] };\n }\n\n for (;;) {\n const active = await snapshot();\n const elapsedMs = now() - startedAt;\n const step = decideDrainStep({ active, elapsedMs, capMs });\n\n if (step.action === 'proceed') {\n if (lastReported !== null) {\n log(`update drain complete after ${Math.round(elapsedMs / 1000)}s \u2014 runner idle, applying staged update restart`);\n }\n return { proceed: true, detail: 'runner idle', capped: false, waitedMs: elapsedMs, checks, markedTaskIds: [] };\n }\n\n if (step.action === 'cap') {\n log(`update drain cap reached after ${Math.round(elapsedMs / 1000)}s (cap ${Math.round(capMs / 1000)}s) \u2014 ${describeBusy(active)}; marking task(s) before restart`);\n const markedTaskIds = await markCappedTasks({ active, failInFlightTask, log });\n return {\n proceed: true,\n capped: true,\n detail: `update restart applied after drain cap; marked ${markedTaskIds.length} task(s) as \"${UPDATE_RESTART_ERROR_MESSAGE}\"`,\n waitedMs: elapsedMs,\n checks,\n markedTaskIds,\n };\n }\n\n // Log the first deferral and every real change, not every poll: a 45-minute\n // cap at a 30s interval would otherwise emit ~90 identical lines.\n const fingerprint = `${step.busy}:${active.ids.join(',')}`;\n if (fingerprint !== lastReported) {\n lastReported = fingerprint;\n log(`deferring staged update restart \u2014 ${describeBusy(active)}; re-checking every ${Math.round(checkMs / 1000)}s until idle (cap ${Math.round(capMs / 1000)}s)`);\n }\n await sleep(Math.max(1, Math.min(checkMs, capMs - elapsedMs)));\n }\n}\n", "import { hostname as systemHostname } from 'node:os';\nimport {\n pairedOperatorScope,\n probeRunnerReadiness,\n runnerReadinessRetryDelayMs,\n runnerRepositoryScopeFromEnv,\n} from '../runner-readiness.mjs';\n\n/** Keep the supervisor's control-queue identity byte-identical to the daemon. */\nexport function resolveSupervisorRunnerId(env = {}, hostname = systemHostname) {\n const explicit = String(env.VO_CODE_RUNNER_ID || '').trim();\n return explicit || `vo-code-runner-${hostname()}`;\n}\n\n/** Build the daemon environment without mislabeling a paired credential as admin. */\nexport function buildSupervisorChildEnv({\n baseEnv = {},\n controlPlaneUrl,\n explicitAdminToken = null,\n pairedOperatorId = null,\n} = {}) {\n const childEnv = {\n ...baseEnv,\n VO_CONTROL_PLANE_URL: controlPlaneUrl,\n };\n const adminToken = typeof explicitAdminToken === 'string' ? explicitAdminToken.trim() : '';\n const operatorId = typeof pairedOperatorId === 'string' ? pairedOperatorId.trim() : '';\n\n if (adminToken) childEnv.VO_CONTROL_PLANE_ADMIN_TOKEN = adminToken;\n else delete childEnv.VO_CONTROL_PLANE_ADMIN_TOKEN;\n\n if (operatorId) childEnv.VO_CODE_RUNNER_OPERATOR_IDS = operatorId;\n return childEnv;\n}\n\n/** Resolve auth provenance once so the supervisor and child use the same scope. */\nexport async function prepareSupervisorAuth({\n baseEnv = {},\n storedCredential = null,\n controlPlaneUrl,\n probeReadiness = probeRunnerReadiness,\n} = {}) {\n const explicitAdminToken = baseEnv.VO_CONTROL_PLANE_ADMIN_TOKEN?.trim();\n const token = explicitAdminToken || storedCredential?.vo_credential;\n if (!token) throw new Error('runner is not paired; run `vo-mcp pair` once on this host');\n\n let operatorId = String(baseEnv.VO_CODE_RUNNER_OPERATOR_IDS || '')\n .split(/[\\s,]+/u)\n .filter(Boolean)[0] || undefined;\n let repositoryScope = runnerRepositoryScopeFromEnv(baseEnv);\n let startupRetryAfterMs = null;\n let githubReady = null;\n let readinessError = null;\n if (!explicitAdminToken) {\n const readiness = await probeReadiness({\n controlPlaneUrl,\n token,\n requireGithub: true,\n repositories: repositoryScope,\n });\n const pairedScope = pairedOperatorScope(readiness)\n || (readiness?.paired === true && typeof readiness.operatorId === 'string'\n ? readiness.operatorId.trim()\n : '');\n operatorId = pairedScope || undefined;\n if (!operatorId) throw new Error('runner readiness failed: paired operator scope is missing');\n if (readiness.ok && Array.isArray(readiness.repositoryScope)) {\n repositoryScope = [...readiness.repositoryScope];\n githubReady = true;\n } else {\n githubReady = false;\n readinessError = typeof readiness?.error === 'string' ? readiness.error : 'github_not_ready';\n startupRetryAfterMs = runnerReadinessRetryDelayMs(readiness);\n }\n }\n\n const effectiveBaseEnv = repositoryScope.length > 0\n ? { ...baseEnv, VO_CODE_RUNNER_REPOS: repositoryScope.join(',') }\n : baseEnv;\n\n const childEnv = buildSupervisorChildEnv({\n baseEnv: effectiveBaseEnv,\n controlPlaneUrl,\n explicitAdminToken,\n pairedOperatorId: explicitAdminToken ? null : operatorId,\n });\n const clientEnv = {\n ...effectiveBaseEnv,\n VO_CONTROL_PLANE_ADMIN_TOKEN: token,\n VO_CONTROL_PLANE_URL: controlPlaneUrl,\n ...(operatorId ? { VO_CODE_RUNNER_OPERATOR_IDS: operatorId } : {}),\n };\n return {\n childEnv,\n clientEnv,\n operatorId,\n repositoryScope,\n githubReady,\n readinessError,\n startupRetryAfterMs,\n };\n}\n", "/**\n * Server-backed readiness probe for a paired BYO runner.\n *\n * The credential itself is opaque, so its mere presence is not proof that it is\n * usable or still bound to an operator. `/auth/me` supplies that truth from the\n * authenticated control-plane context. Before daemon startup, the optional\n * GitHub probe uses App-JWT GETs to verify the caller-owned installation,\n * publication grants, and selected repositories without minting a one-hour\n * token. Read/publish tokens are created only for actual task work.\n */\nimport { createHash, randomUUID } from 'node:crypto';\n\nexport const RUNNER_GITHUB_READINESS_TIMEOUT_MS = 50_000;\nexport const RUNNER_IDENTITY_READINESS_TIMEOUT_MS = 10_000;\nexport const RUNNER_READINESS_MAX_REPOSITORIES = 4;\nexport const RUNNER_READINESS_MAX_TIMER_DELAY_MS = 2_147_000_000;\nexport const RUNNER_READINESS_TRANSIENT_MAX_RETRY_AFTER_MS = 300_000;\nexport const RUNNER_READINESS_IPC_ACK_TIMEOUT_MS = 5_000;\nexport const RUNNER_READINESS_DEFERRAL_MESSAGE_TYPE = 'vo-runner-readiness-deferred-v1';\nexport const RUNNER_READINESS_DEFERRAL_ACK_TYPE = 'vo-runner-readiness-deferred-ack-v1';\nconst RUNNER_REPOSITORY = /^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u;\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\nexport function runnerRepositoryScopeFromEnv(env = {}) {\n return String(env.VO_CODE_RUNNER_REPOS || '')\n .split(/[\\s,]+/u)\n .map((repo) => repo.trim())\n .filter(Boolean);\n}\n\nexport function normalizeRunnerRepositoryScope(repositories) {\n if (!Array.isArray(repositories) || repositories.length < 1) {\n throw new Error('VO_CODE_RUNNER_REPOS must name at least one owner/name repository');\n }\n if (repositories.length > RUNNER_READINESS_MAX_REPOSITORIES) {\n throw new Error(`VO_CODE_RUNNER_REPOS supports at most ${RUNNER_READINESS_MAX_REPOSITORIES} repositories`);\n }\n const normalized = repositories.map((repo) => {\n const [owner, name] = typeof repo === 'string' ? repo.split('/') : [];\n if (typeof repo !== 'string' || repo.length > 140 || !RUNNER_REPOSITORY.test(repo)\n || owner === '.' || owner === '..' || name === '.' || name === '..') {\n throw new Error('VO_CODE_RUNNER_REPOS entries must be canonical owner/name repositories');\n }\n return repo.toLowerCase();\n });\n if (new Set(normalized).size !== normalized.length) {\n throw new Error('VO_CODE_RUNNER_REPOS entries must be unique');\n }\n const owners = new Set(normalized.map((repo) => repo.split('/')[0]));\n if (owners.size !== 1) {\n throw new Error('VO_CODE_RUNNER_REPOS entries must share one owner');\n }\n return Object.freeze(normalized.sort());\n}\n\nexport function runnerRepositoryScopeDigest(repositories) {\n const scope = normalizeRunnerRepositoryScope(repositories);\n return createHash('sha256').update(JSON.stringify({\n version: 1,\n repositories: scope,\n }), 'utf8').digest('hex');\n}\n\nexport function runnerReadinessRetryDelayMs(readiness) {\n if (readiness?.paired !== true || readiness?.githubReady !== false) return null;\n if (Number.isFinite(readiness.retryAfterMs) && readiness.retryAfterMs > 0) {\n return Math.ceil(readiness.retryAfterMs);\n }\n return null;\n}\n\n/**\n * One shared CLI/supervisor failure disposition. Only a parent-ACKed,\n * server-authorized readiness deferral may use reserved exit 75; ordinary\n * readiness failures and failed IPC custody remain ordinary exit 1 and\n * therefore consume breaker budget.\n */\nexport function runnerReadinessFailureDisposition(readiness, delivery = null) {\n const retryAfterMs = runnerReadinessRetryDelayMs(readiness);\n if (retryAfterMs === null) {\n return Object.freeze({ action: 'exit', exitCode: 1, retryAfterMs: null });\n }\n if (delivery?.attempted === true) {\n return Object.freeze({\n action: 'exit',\n exitCode: delivery.delivered === true ? 75 : 1,\n retryAfterMs,\n });\n }\n return Object.freeze({ action: 'wait', exitCode: null, retryAfterMs });\n}\n\nexport function parseRunnerReadinessDeferralRequest(message) {\n if (message?.type !== RUNNER_READINESS_DEFERRAL_MESSAGE_TYPE\n || !UUID_RE.test(String(message.nonce || ''))\n || !Number.isFinite(message.retryAfterMs)\n || message.retryAfterMs <= 0) return null;\n return Object.freeze({\n nonce: message.nonce,\n retryAfterMs: Math.ceil(message.retryAfterMs),\n error: typeof message.error === 'string' ? message.error : null,\n });\n}\n\nexport async function notifySupervisorReadinessDeferral({\n processLike,\n retryAfterMs,\n error = null,\n ackTimeoutMs = RUNNER_READINESS_IPC_ACK_TIMEOUT_MS,\n}) {\n if (processLike?.connected !== true || typeof processLike.send !== 'function') {\n return Object.freeze({ attempted: false, delivered: false });\n }\n if (typeof processLike.on !== 'function' || typeof processLike.off !== 'function') {\n return Object.freeze({ attempted: true, delivered: false });\n }\n const nonce = randomUUID();\n const delivered = await new Promise((resolve) => {\n let settled = false;\n const onMessage = (message) => {\n if (message?.type === RUNNER_READINESS_DEFERRAL_ACK_TYPE && message.nonce === nonce) {\n finish(true);\n }\n };\n const onDisconnect = () => finish(false);\n const finish = (value) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n processLike.off('message', onMessage);\n processLike.off('disconnect', onDisconnect);\n resolve(value);\n };\n const timer = setTimeout(() => finish(false), ackTimeoutMs);\n processLike.on('message', onMessage);\n processLike.on('disconnect', onDisconnect);\n try {\n processLike.send({\n type: RUNNER_READINESS_DEFERRAL_MESSAGE_TYPE,\n nonce,\n retryAfterMs,\n error,\n }, (sendError) => {\n if (sendError) finish(false);\n });\n } catch {\n finish(false);\n }\n });\n return Object.freeze({ attempted: true, delivered });\n}\n\nexport async function waitForRunnerReadinessRetry(delayMs, {\n nowMs = () => Date.now(),\n wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n} = {}) {\n if (!Number.isFinite(delayMs) || delayMs <= 0) {\n throw new TypeError('runner readiness retry delay is invalid');\n }\n const deadline = nowMs() + Math.ceil(delayMs);\n while (nowMs() < deadline) {\n await wait(Math.min(RUNNER_READINESS_MAX_TIMER_DELAY_MS, deadline - nowMs()));\n }\n}\n\nfunction failed({\n paired = false,\n operatorId = null,\n tenantId = null,\n githubReady = null,\n retryAfterMs = null,\n error,\n message,\n}) {\n return {\n ok: false,\n paired,\n operatorId,\n tenantId,\n githubReady,\n ...(Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? { retryAfterMs } : {}),\n error,\n message,\n };\n}\n\nfunction responseRetryAfterMs(response, body) {\n const transientReadinessFailure = response.status === 503\n && body?.error === 'github_installation_readiness_retryable';\n if (response.status !== 429 && !transientReadinessFailure) return null;\n const bound = (retryAfterMs) => transientReadinessFailure\n ? Math.min(RUNNER_READINESS_TRANSIENT_MAX_RETRY_AFTER_MS, retryAfterMs)\n : retryAfterMs;\n const value = response.headers?.get?.('retry-after')?.trim() ?? '';\n const seconds = Number(value);\n if (value && Number.isFinite(seconds) && seconds >= 0) {\n return bound(Math.max(1_000, Math.ceil(seconds * 1_000)));\n }\n const at = value ? Date.parse(value) : Number.NaN;\n if (Number.isFinite(at)) {\n return bound(Math.max(1_000, Math.ceil(at - Date.now())));\n }\n return bound(60_000);\n}\n\nasync function responseBody(response) {\n try {\n const value = await response.json();\n return value && typeof value === 'object' ? value : {};\n } catch {\n return {};\n }\n}\n\nfunction serverMessage(body, fallback) {\n return typeof body.message === 'string' && body.message.trim() ? body.message.trim() : fallback;\n}\n\nasync function fetchJsonWithTimeout(fetchImpl, url, init, timeoutMs) {\n const controller = new AbortController();\n let timer;\n const timeout = new Promise((_, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new Error(`request aborted after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n try {\n const requestAndBody = (async () => {\n const response = await fetchImpl(url, { ...init, signal: controller.signal });\n return { response, body: await responseBody(response) };\n })();\n return await Promise.race([requestAndBody, timeout]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * @param {{\n * controlPlaneUrl: string,\n * token: string,\n * fetchImpl?: typeof fetch,\n * requireGithub?: boolean,\n * repositories?: readonly string[],\n * timeoutMs?: number,\n * githubTimeoutMs?: number,\n * }} input\n */\nexport async function probeRunnerReadiness({\n controlPlaneUrl,\n token,\n fetchImpl = fetch,\n requireGithub = false,\n repositories = [],\n timeoutMs = RUNNER_IDENTITY_READINESS_TIMEOUT_MS,\n // The server performs at most five sequential App-JWT GETs (installation plus\n // every one of at most four configured repositories), each bounded at 8s.\n // Keep a transport margin while preventing a stuck proof from hanging startup.\n githubTimeoutMs = RUNNER_GITHUB_READINESS_TIMEOUT_MS,\n}) {\n const base = controlPlaneUrl.replace(/\\/+$/u, '');\n const headers = { authorization: `Bearer ${token}` };\n let identityResponse;\n let identity;\n try {\n ({ response: identityResponse, body: identity } = await fetchJsonWithTimeout(\n fetchImpl,\n `${base}/api/v1/auth/me`,\n { headers },\n timeoutMs,\n ));\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n return failed({\n error: 'control_plane_unreachable',\n message: `AlgoHQ could not be reached: ${detail}`,\n });\n }\n\n if (!identityResponse.ok) {\n return failed({\n error: 'credential_rejected',\n message: 'The saved pairing is expired or revoked. Pair this computer again.',\n });\n }\n if (\n identity.provisioned !== true ||\n identity.role !== 'operator' ||\n typeof identity.operator_id !== 'string' ||\n !identity.operator_id.trim() ||\n typeof identity.tenant_id !== 'string' ||\n !identity.tenant_id.trim()\n ) {\n return failed({\n error: 'operator_identity_missing',\n message: 'The pairing credential is valid but has no operator identity. Pair this computer again.',\n });\n }\n\n const operatorId = identity.operator_id.trim();\n const tenantId = identity.tenant_id.trim();\n if (!requireGithub) {\n return {\n ok: true,\n paired: true,\n operatorId,\n tenantId,\n githubReady: null,\n error: null,\n message: 'Paired to AlgoHQ.',\n };\n }\n\n let repositoryScope = null;\n try {\n if (!Array.isArray(repositories)) {\n throw new Error('VO_CODE_RUNNER_REPOS must be a repository array');\n }\n if (repositories.length > 0) repositoryScope = normalizeRunnerRepositoryScope(repositories);\n } catch (error) {\n return failed({\n paired: true,\n operatorId,\n tenantId,\n githubReady: false,\n error: 'github_repository_scope_invalid',\n message: error instanceof Error ? error.message : String(error),\n });\n }\n\n let githubResponse;\n let github;\n try {\n const readinessUrl = new URL(`${base}/api/v1/github/installation-readiness`);\n for (const repo of repositoryScope ?? []) readinessUrl.searchParams.append('repo', repo);\n ({ response: githubResponse, body: github } = await fetchJsonWithTimeout(\n fetchImpl,\n readinessUrl.toString(),\n { headers },\n githubTimeoutMs,\n ));\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n return failed({\n paired: true,\n operatorId,\n tenantId,\n githubReady: false,\n error: 'github_preflight_unreachable',\n message: `GitHub publication readiness could not be checked: ${detail}`,\n });\n }\n\n const repositorySelection = github.repository_selection;\n const repositoriesVerified = github.repositories_verified;\n const returnedScope = github.repository_scope;\n let normalizedReturnedScope = null;\n try {\n normalizedReturnedScope = normalizeRunnerRepositoryScope(returnedScope);\n } catch {\n // The shape check below fails closed with the server's actionable response.\n }\n const effectiveScope = repositoryScope ?? normalizedReturnedScope;\n const sourceVerified = repositoryScope === null\n ? github.repository_scope_source === 'persisted_installation_singleton'\n && normalizedReturnedScope?.length === 1\n : github.repository_scope_source === 'runner_config';\n const repositoryScopeVerified = effectiveScope !== null\n && normalizedReturnedScope !== null\n && Array.isArray(returnedScope)\n && returnedScope.length === normalizedReturnedScope.length\n && returnedScope.every((repo, index) => repo === normalizedReturnedScope[index])\n && normalizedReturnedScope.length === effectiveScope.length\n && normalizedReturnedScope.every((repo, index) => repo === effectiveScope[index])\n && github.repository_scope_sha256 === runnerRepositoryScopeDigest(effectiveScope)\n && repositoriesVerified === effectiveScope.length\n && sourceVerified\n && (repositorySelection === 'all' || repositorySelection === 'selected');\n if (!githubResponse.ok || github.configured !== true || github.verified !== true\n || github.publication_ready !== true\n || !repositoryScopeVerified) {\n const error = typeof github.error === 'string' && github.error ? github.error : 'github_not_ready';\n return failed({\n paired: true,\n operatorId,\n tenantId,\n githubReady: false,\n retryAfterMs: responseRetryAfterMs(githubResponse, github),\n error,\n message: serverMessage(github, `GitHub publication preflight failed (HTTP ${githubResponse.status}).`),\n });\n }\n\n return {\n ok: true,\n paired: true,\n operatorId,\n tenantId,\n githubReady: true,\n repositoryScope: effectiveScope,\n repositoryScopeSource: github.repository_scope_source,\n error: null,\n message: `Paired with a verified Algosuite GitHub App installation (${repositoriesVerified} repos).`,\n };\n}\n\nexport function pairedOperatorScope(readiness) {\n return readiness?.ok === true &&\n readiness?.paired === true &&\n typeof readiness.operatorId === 'string' &&\n readiness.operatorId.trim()\n ? readiness.operatorId.trim()\n : null;\n}\n", "import { spawnSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport function defaultCredentialHelperPath(metaUrl = import.meta.url) {\n const moduleDir = dirname(fileURLToPath(metaUrl));\n const bundled = join(moduleDir, 'supervisor-credential-helper.js');\n const source = join(moduleDir, '..', 'supervisor-credential-helper.mjs');\n return existsSync(source) ? source : bundled;\n}\n\n/** Read the OS-keychain credential without loading its native module here. */\nexport function readStoredCredentialIsolated({\n spawn = spawnSync,\n execPath = process.execPath,\n helperPath = defaultCredentialHelperPath(),\n helperArgs = [],\n env = process.env,\n} = {}) {\n const result = spawn(execPath, [helperPath, ...helperArgs], {\n env,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'pipe'],\n shell: false,\n windowsHide: true,\n timeout: 10_000,\n });\n if (result.status !== 0) {\n throw new Error('runner credential helper could not read the paired credential');\n }\n try {\n const parsed = JSON.parse(String(result.stdout || ''));\n return parsed && typeof parsed === 'object' ? parsed : null;\n } catch {\n throw new Error('runner credential helper returned an invalid credential');\n }\n}\n", "/** Pure rapid-exit circuit used by the persistent runner supervisor. */\nexport const DEFAULT_RESPAWN_CIRCUIT = Object.freeze({\n baseDelayMs: 2_000,\n maxDelayMs: 30_000,\n healthyResetMs: 60_000,\n maxRapidExits: 5,\n});\n\nexport function createRespawnCircuit(options = {}) {\n const config = { ...DEFAULT_RESPAWN_CIRCUIT, ...options };\n for (const [key, value] of Object.entries(config)) {\n if (!Number.isInteger(value) || value < 1) throw new Error(`${key} must be a positive integer`);\n }\n let rapidExits = 0;\n\n return Object.freeze({\n recordExit(startedAt, exitedAt) {\n if (!Number.isFinite(startedAt) || !Number.isFinite(exitedAt) || exitedAt < startedAt) {\n throw new Error('respawn circuit timestamps are invalid');\n }\n const uptimeMs = exitedAt - startedAt;\n rapidExits = uptimeMs >= config.healthyResetMs ? 0 : rapidExits + 1;\n const tripped = rapidExits >= config.maxRapidExits;\n const delayMs = Math.min(\n config.maxDelayMs,\n config.baseDelayMs * (2 ** Math.max(0, rapidExits - 1)),\n );\n return Object.freeze({ rapidExits, uptimeMs, delayMs, tripped });\n },\n snapshot() {\n return Object.freeze({ rapidExits, tripped: rapidExits >= config.maxRapidExits });\n },\n });\n}\n", "/**\n * Readiness proof for one supervisor-owned runner child.\n *\n * All timing and state effects are injected so the race between an asynchronous\n * health probe and process exit can be exercised without starting a real child.\n */\nconst terminatedChildren = new WeakSet();\n\n/**\n * Install one exact-child terminal-event account while retaining an `error`\n * listener for the child's full lifetime. Node may emit an asynchronous spawn\n * `error` without `exit`, or may emit both; only the first terminal event\n * receives termination authority.\n *\n * The record carries HOW the child died, not merely that it did. Node hands the\n * exit listener `(code, signal)` and this used to discard both, which is why the\n * Windows libuv abort\n * (`Assertion failed: !(handle->flags & UV_HANDLE_CLOSING), src\\win\\async.c`)\n * has only ever been an anecdote: the supervisor knew the daemon exited and\n * nothing about whether it aborted, was signalled, or returned cleanly. An\n * abort() on Windows surfaces as a non-zero code with no signal, which is\n * indistinguishable from a clean exit once the code is thrown away.\n */\nexport function attachSupervisorChildTerminationCustody(\n target,\n onTerminated,\n onObservedError = () => {},\n) {\n let accounted = false;\n const account = (kind, { error = null, code = null, signal = null } = {}) => {\n terminatedChildren.add(target);\n if (accounted) return false;\n accounted = true;\n onTerminated(Object.freeze({ target, kind, error, code, signal }));\n return true;\n };\n target.on('error', (error) => {\n onObservedError(error);\n // ChildProcess also uses `error` for failed IPC sends and failed kills.\n // Those do not prove a live process terminated. A spawn failure is the\n // narrow terminal case: Node leaves pid unset and may emit exit afterward.\n // No code/signal exists for a process that never started.\n if (target.pid === undefined || target.pid === null) account('error', { error });\n });\n target.on('exit', (code, signal) => {\n account('exit', { code: code ?? null, signal: signal ?? null });\n });\n return Object.freeze({ accounted: () => accounted });\n}\n\n/**\n * One line describing how a child died, for the supervisor's log.\n *\n * Names the runtime because that is the attribution the abort investigation\n * lacked: the daemon runs the BUNDLED Node, not whatever is on the operator's\n * PATH, and a crash blamed on the wrong build is worse than an unattributed one\n * (docs/vo/roadmap-log/2026-09-04-runner-exit-abort.md).\n */\nexport function describeChildTermination(record, runtime = process.version) {\n if (!record || typeof record !== 'object') return `unknown termination on Node ${runtime}`;\n if (record.kind === 'error') {\n const detail = record.error instanceof Error ? record.error.message : String(record.error ?? 'no detail');\n return `spawn error on Node ${runtime}: ${detail}`;\n }\n if (record.signal) return `killed by ${record.signal} on Node ${runtime}`;\n if (record.code === 0) return `exited cleanly (code 0) on Node ${runtime}`;\n if (record.code === null) return `exited with no reported code or signal on Node ${runtime}`;\n return `exited with code ${record.code} on Node ${runtime}`;\n}\n\nexport function supervisorChildHasExited(target) {\n // Node preserves exitCode=null for signal-terminated children and reports the\n // terminal state through signalCode instead. An asynchronous spawn error can\n // leave both fields null, so exact-object error custody is terminal too.\n return terminatedChildren.has(target)\n || target.exitCode !== null\n || (target.signalCode ?? null) !== null;\n}\n\nexport function supervisorChildIsRunning(target) {\n return !supervisorChildHasExited(target);\n}\n\nexport function shouldRespawnSupervisorChild({ stopping, degraded, handling, child }) {\n return !stopping && !degraded && !handling && (!child || supervisorChildHasExited(child));\n}\n\nexport function shouldDeferSupervisorReadinessExit({\n target,\n currentChild,\n retryAfterMs,\n}) {\n return target === currentChild\n && target?.exitCode === 75\n && Number.isFinite(retryAfterMs)\n && retryAfterMs > 0;\n}\n\n/**\n * Exact-child custody for a child-reported GitHub readiness embargo. The\n * supervisor records the nonce before acknowledging it to the child, then one\n * idempotent capture transition is shared by health, activation, and exit-event\n * orderings. A later exit listener can therefore never reinterpret an already\n * captured exit as a crash.\n */\nexport function createSupervisorReadinessDeferralTracker({\n currentChild,\n releaseCurrentChild,\n onCaptured,\n}) {\n const pending = new WeakMap();\n const terminal = new WeakSet();\n const recoveryGenerations = new WeakMap();\n\n return Object.freeze({\n recordPending(target, request) {\n if (!target || target !== currentChild() || terminal.has(target) || pending.has(target)\n || typeof request?.nonce !== 'string' || !request.nonce\n || !Number.isFinite(request.retryAfterMs) || request.retryAfterMs <= 0) return false;\n pending.set(target, Object.freeze({\n nonce: request.nonce,\n retryAfterMs: Math.ceil(request.retryAfterMs),\n }));\n return true;\n },\n recordRecoveryGeneration(target, generation) {\n if (!target || !Number.isInteger(generation)) return false;\n recoveryGenerations.set(target, generation);\n return true;\n },\n isDeferred(target) {\n const request = target ? pending.get(target) : null;\n return Boolean(target) && (terminal.has(target) || shouldDeferSupervisorReadinessExit({\n target,\n currentChild: currentChild(),\n retryAfterMs: request?.retryAfterMs,\n }));\n },\n capture(target) {\n if (!target) return false;\n if (terminal.has(target)) return true;\n const request = pending.get(target);\n if (!shouldDeferSupervisorReadinessExit({\n target,\n currentChild: currentChild(),\n retryAfterMs: request?.retryAfterMs,\n })) return false;\n const recoveryGeneration = recoveryGenerations.get(target);\n terminal.add(target);\n pending.delete(target);\n recoveryGenerations.delete(target);\n releaseCurrentChild(target);\n onCaptured(Object.freeze({\n target,\n retryAfterMs: request.retryAfterMs,\n recoveryGeneration: Number.isInteger(recoveryGeneration) ? recoveryGeneration : null,\n }));\n return true;\n },\n forget(target) {\n if (!target) return;\n pending.delete(target);\n recoveryGenerations.delete(target);\n },\n });\n}\n\nexport function resolveSupervisorChildStartAuthority({\n degradationState,\n deferredRecoveryGeneration,\n}) {\n const snapshot = degradationState.snapshot();\n const exactRecovery = Number.isInteger(deferredRecoveryGeneration)\n && deferredRecoveryGeneration === snapshot.generation;\n return Object.freeze({\n allowed: !snapshot.degraded || exactRecovery,\n recoveryGeneration: exactRecovery ? deferredRecoveryGeneration : null,\n });\n}\n\n/**\n * One-shot startup gate for a server-provided readiness Retry-After deadline.\n * Waiting behind this gate never spawns a process, so it cannot consume the\n * rapid-exit breaker. A later upstream response may extend the same unspent\n * start authority; once consumed it can never be reused by another poll.\n */\nexport function createSupervisorStartupDeferral({\n retryAfterMs = null,\n nowMs = () => Date.now(),\n} = {}) {\n let started = false;\n let notBefore = null;\n const defer = (delayMs) => {\n if (started || !Number.isFinite(delayMs) || delayMs <= 0) return false;\n const candidate = nowMs() + Math.ceil(delayMs);\n notBefore = notBefore === null ? candidate : Math.max(notBefore, candidate);\n return true;\n };\n defer(retryAfterMs);\n\n return Object.freeze({\n defer,\n reopen(delayMs) {\n if (!Number.isFinite(delayMs) || delayMs <= 0) return false;\n started = false;\n notBefore = null;\n return defer(delayMs);\n },\n isPending() {\n return !started && notBefore !== null && nowMs() < notBefore;\n },\n remainingMs() {\n return started || notBefore === null ? 0 : Math.max(0, notBefore - nowMs());\n },\n consumeIfReady() {\n if (started || (notBefore !== null && nowMs() < notBefore)) return false;\n started = true;\n notBefore = null;\n return true;\n },\n hasStarted() {\n return started;\n },\n });\n}\n\n/**\n * Generation-fenced degradation state. A health proof may clear only the\n * generation it observed when it began, and only for the same current child.\n */\nexport function createSupervisorDegradationState() {\n let degraded = false;\n let generation = 0;\n\n return {\n isDegraded() {\n return degraded;\n },\n markDegraded() {\n degraded = true;\n generation += 1;\n },\n beginHealthProof({ target, currentChild, allowRecovery, onRecovery }) {\n const observedGeneration = generation;\n return () => {\n if (currentChild() !== target || generation !== observedGeneration) return false;\n if (degraded && !allowRecovery) return false;\n const recovered = degraded;\n degraded = false;\n if (recovered) onRecovery?.();\n return true;\n };\n },\n beginDegradationProof({ target, currentChild, onDegraded }) {\n const observedGeneration = generation;\n return (message) => {\n if (currentChild() !== target || generation !== observedGeneration) return false;\n onDegraded(message);\n return true;\n };\n },\n snapshot() {\n return { degraded, generation };\n },\n };\n}\n\n/**\n * Begin one exact-child, exact-generation healthy-state commit. The stale\n * non-zero supervisor exit status is cleared only inside the same successful\n * commit that recovers degradation; stale or wrong-child proofs have no exit\n * status authority.\n */\nexport function beginSupervisorHealthyStateCommit({\n degradationState,\n target,\n currentChild,\n allowRecovery,\n clearStaleExitCode,\n}) {\n return degradationState.beginHealthProof({\n target,\n currentChild,\n allowRecovery,\n onRecovery: clearStaleExitCode,\n });\n}\n\nconst RUNNER_RECOVERY_ACTIONS = new Set(['update', 'reinstall', 'reconnect']);\n\nexport function shouldRecoverSupervisorChildAfterAction({\n stoppedChild,\n actionKind,\n actionSucceeded,\n}) {\n // An action that deliberately stopped a live child must restore service even\n // when its maintenance work failed. With no such child, only a successful\n // runner repair/reconnect may clear pre-existing degradation; unrelated host\n // cleanup and failed maintenance are not recovery authority.\n return Boolean(stoppedChild)\n || (actionSucceeded === true && RUNNER_RECOVERY_ACTIONS.has(actionKind));\n}\n\n/**\n * One-shot proof that the current control action took responsibility for a\n * live child before stopping it. Generic polling failures never arm this\n * fence, so they cannot accidentally relaunch a previously degraded runner.\n */\nexport function createSupervisorControlRecoveryFence() {\n let targetStoppedForControl = null;\n const consume = () => {\n const target = targetStoppedForControl;\n targetStoppedForControl = null;\n return target;\n };\n\n return {\n markBeforeStop(target) {\n targetStoppedForControl = target && supervisorChildIsRunning(target) ? target : null;\n return targetStoppedForControl !== null;\n },\n consume,\n async recoverOnce(recover) {\n // Consume before awaiting so a failed recovery cannot leak authority into\n // a later, unrelated poll iteration.\n const target = consume();\n if (!target) return false;\n await recover(target);\n return true;\n },\n };\n}\n\nexport async function verifySupervisorChildHealth({\n target,\n degradeOnExit,\n context,\n waitBeforeProbe,\n waitForLocalRunner,\n stopExpectedly,\n markHealthy,\n markDegraded,\n isReadinessDeferredExit = () => false,\n isExpectedStop = () => false,\n}) {\n try {\n await waitBeforeProbe();\n const healthy = supervisorChildIsRunning(target) && await waitForLocalRunner(target);\n // The health probe is asynchronous. Node may publish exitCode or signalCode\n // while it is pending, so decisions below must use a fresh observation,\n // not the value from before the await.\n const exited = supervisorChildHasExited(target);\n if (isExpectedStop(target)) return false;\n if (exited && isReadinessDeferredExit(target)) return false;\n if (healthy && !exited) {\n // A caller may reject a stale success when a newer degradation or child\n // generation superseded this asynchronous proof.\n if (markHealthy() !== false) return true;\n if (supervisorChildIsRunning(target)) await stopExpectedly(target);\n return false;\n }\n // Ordinary rapid exits remain governed by the backoff circuit. A live\n // child that never proves readiness, or any failed control-action\n // recovery, must fail closed immediately instead of occupying the slot.\n if (!exited || degradeOnExit) {\n const committed = markDegraded(`${context} did not become healthy; entering degraded mode`) !== false;\n if (!committed) return false;\n if (supervisorChildIsRunning(target)) await stopExpectedly(target);\n }\n return false;\n } catch (error) {\n if (isExpectedStop(target)) return false;\n const committed = markDegraded(\n `${context} health proof failed; entering degraded mode: ${\n error instanceof Error ? error.message : String(error)\n }`,\n ) !== false;\n if (!committed) return false;\n if (supervisorChildIsRunning(target)) await stopExpectedly(target).catch(() => {});\n return false;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAeA,eAAsB,kBAAkB;AACtC,QAAM,IAAI;AAAA,IACR;AAAA,EAEF;AACF;AApBA;AAAA;AAAA;AAAA;;;ACKA,SAAS,aAAa;AACtB,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,WAAAC,UAAS,QAAAC,aAAY;;;ACQ9B,IAAM,wBAAwB;AAU9B,eAAsB,uBAAuB,EAAE,KAAK,WAAW,OAAO,WAAW,OAAO,OAAO,KAAK,GAAG;AACrG,QAAM,OAAO,CAAC,WAAW;AACvB,QAAI,SAAU,OAAM,IAAI,MAAM,gCAAgC,MAAM,EAAE;AACtE,WAAO;AAAA,EACT;AACA,MAAI;AAIF,UAAM,MAAM,MAAM;AAAA,MAChB;AAAA,MACA;AAAA,MACA,WAAW,EAAE,OAAO,QAAQ,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC,EAAG,IAAI,CAAC;AAAA,MAC3D,WAAW,EAAE,WAAW,sBAAsB,IAAI,CAAC;AAAA,IACrD;AACA,QAAI,CAAC,IAAI,GAAI,QAAO,KAAK,QAAQ,IAAI,MAAM,EAAE;AAC7C,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,QAAI,CAAC,QAAQ,CAAC,KAAK,MAAO,QAAO,KAAK,eAAe;AAMrD,QAAI,YAAY,KAAK,UAAU,OAAQ,QAAO,KAAK,iDAAiD;AAGpG,WAAO,EAAE,OAA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I,MAAM,OAAQ,SAAQ,KAAK,0BAA0B,MAAM,MAAM,EAAE;AACvE,gBAAQ,KAAK,oCAAoC,OAAO,OAAO,OAAO,uCAAuC;AAC7G;AAAA,MACF;AAKA,YAAM,qBAAqB,wCAAwC;AAAA,QACjE,cAAc,qBAAqB,QAAQ;AAAA,QAC3C,YAAY,OAAO;AAAA,QACnB,iBAAiB,OAAO;AAAA,MAC1B,CAAC;AACD,YAAM,oBAAoB,qBACtB,MAAM,+BAA+B,IACrC;AACJ,UAAI,CAAC,kBAAmB,QAAO,KAAK;AACpC,YAAM,OAAO,sBAAsB,OAAO,UAAU;AAAA,QAClD,GAAG;AAAA,QACH,QAAQ,OAAO,KAAK,cAAc;AAAA,QAClC,QAAQ,OAAO,KACV,OAAO,SAAS,GAAG,OAAO,MAAM,YAAY,eAAe,CAAC,eAAe,MAAM,GAAG,GAAI,IAAI,UAAU,eAAe,CAAC,iBACvH,sBAAsB,OAAO,MAAM,GAAG,OAAO,SAAS,KAAK,OAAO,MAAM,KAAK,EAAE,GAC/E,oBAAoB,KAAK,0CAC3B;AAAA,MACJ,CAAC;AACD,iBAAW;AACX,cAAQ;AAAA,IACV,SAAS,OAAO;AACd,cAAQ,MAAM,0BAA0B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAIhG,YAAM,qBAAqB,YAAY,MAAM,+BAA+B,CAAC;AAC7E,iBAAW;AACX,YAAM,MAAM,OAAO;AAAA,IACrB;AAAA,EACF;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAM,iCAAiC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACvG,UAAQ,WAAW;AACrB,CAAC;",
6
6
  "names": ["randomUUID", "fileURLToPath", "dirname", "join", "runnerId", "supervisorInstanceId", "supervisorVersion", "runnerId", "resolve", "sleep", "path", "path", "getFirebaseAuth", "runnerId", "sleep", "path", "body", "supervisorInstanceId", "supervisorVersion", "spawn", "createHash", "randomUUID", "existsSync", "lstatSync", "mkdirSync", "readFileSync", "readdirSync", "renameSync", "rmSync", "writeFileSync", "isAbsolute", "join", "relative", "resolve", "sep", "spawnSync", "createHash", "readFileSync", "resolve", "existsSync", "win32", "path", "resolve", "canonical", "createHash", "readFileSync", "createHash", "existsSync", "lstatSync", "readFileSync", "readdirSync", "dirname", "isAbsolute", "join", "relative", "resolve", "selfPath", "join", "PACKAGE_SPEC_RE", "INTEGRITY_RE", "join", "spawnSync", "createHash", "readFileSync", "lstatSync", "readdirSync", "resolve", "relative", "sep", "isAbsolute", "writeFileSync", "randomUUID", "existsSync", "mkdirSync", "renameSync", "rmSync", "spawnSync", "spawnSync", "existsSync", "mkdirSync", "readdirSync", "readFileSync", "rmSync", "writeFileSync", "spawn", "spawnSync", "spawn", "spawnSync", "result", "failed", "resolve", "runnerId", "selfPath", "packageVersion", "waitForLocalRunner", "localStatus", "stopChild", "VERSION_RE", "resolve", "sleep", "createHash", "randomUUID", "UUID_RE", "createHash", "UUID_RE", "spawnSync", "existsSync", "dirname", "join", "fileURLToPath", "spawn", "waitForLocalRunner", "UUID_RE", "fileURLToPath", "join", "dirname", "resolve", "randomUUID"]
7
7
  }