@opengeni/worker-bundle 0.17.2 → 0.20.1

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.
Files changed (78) hide show
  1. package/dist/activities/agent-run-admission.d.ts +12 -0
  2. package/dist/activities/agent-turn.d.ts +49 -1
  3. package/dist/activities/browser-state-artifact-reaper.d.ts +29 -0
  4. package/dist/activities/capabilities.d.ts +6 -0
  5. package/dist/activities/codex-capacity.d.ts +1 -0
  6. package/dist/activities/environment.d.ts +7 -1
  7. package/dist/activities/packs.d.ts +8 -10
  8. package/dist/activities/run-input.d.ts +8 -0
  9. package/dist/activities/session-state.d.ts +7 -3
  10. package/dist/activities/site-auth-maintenance.d.ts +27 -0
  11. package/dist/activities/types.d.ts +43 -0
  12. package/dist/activities/video-generation-admission.d.ts +9 -4
  13. package/dist/activities/video-generation-credential.d.ts +17 -0
  14. package/dist/activities/video-reference-staging.d.ts +7 -1
  15. package/dist/activities/xai-auth.d.ts +23 -0
  16. package/dist/activities/xai-image-generation.d.ts +26 -0
  17. package/dist/activities/xai-video-generation.d.ts +18 -0
  18. package/dist/{activities-control-44KBWLSM.js → activities-control-SMKF2OBE.js} +438 -55
  19. package/dist/activities-control-SMKF2OBE.js.map +1 -0
  20. package/dist/activities-control.d.ts +10 -2
  21. package/dist/{activities-turn-K4CEDEGJ.js → activities-turn-IDS3WEHA.js} +6704 -4847
  22. package/dist/activities-turn-IDS3WEHA.js.map +1 -0
  23. package/dist/activities.d.ts +11 -3
  24. package/dist/{chunk-E3RI3I33.js → chunk-N5TJIFCE.js} +156 -10
  25. package/dist/chunk-N5TJIFCE.js.map +1 -0
  26. package/dist/{chunk-KKCRGAGZ.js → chunk-P6Z2SLAA.js} +99 -98
  27. package/dist/chunk-P6Z2SLAA.js.map +1 -0
  28. package/dist/index.d.ts +14 -1
  29. package/dist/index.js +49 -2
  30. package/dist/index.js.map +1 -1
  31. package/dist/model-checkpoint-memory-collector.d.ts +1 -0
  32. package/dist/model-context-contributions.d.ts +40 -0
  33. package/dist/observability-metrics.d.ts +57 -1
  34. package/dist/sandbox-routing.d.ts +4 -0
  35. package/dist/workflow-bundle.js +232 -18
  36. package/dist/workflows/activities.d.ts +1 -1
  37. package/dist/workflows/session.d.ts +17 -1
  38. package/dist/workflows/site-auth-maintenance.d.ts +2 -0
  39. package/dist/workflows.d.ts +1 -0
  40. package/package.json +16 -15
  41. package/src/activities/agent-run-admission.ts +76 -0
  42. package/src/activities/agent-turn.ts +2777 -1241
  43. package/src/activities/browser-state-artifact-reaper.ts +120 -0
  44. package/src/activities/capabilities.ts +10 -0
  45. package/src/activities/codex-capacity.ts +48 -1
  46. package/src/activities/environment.ts +14 -8
  47. package/src/activities/goals.ts +2 -1
  48. package/src/activities/packs.ts +45 -122
  49. package/src/activities/parent-wake.ts +13 -1
  50. package/src/activities/run-input.ts +137 -45
  51. package/src/activities/scheduled-tasks.ts +30 -73
  52. package/src/activities/session-state.ts +87 -5
  53. package/src/activities/site-auth-maintenance.ts +269 -0
  54. package/src/activities/types.ts +44 -0
  55. package/src/activities/video-generation-admission.ts +37 -4
  56. package/src/activities/video-generation-credential.ts +84 -6
  57. package/src/activities/video-generation-reconciliation.ts +212 -19
  58. package/src/activities/video-media-validation.ts +8 -2
  59. package/src/activities/video-reference-staging.ts +121 -34
  60. package/src/activities/xai-auth.ts +122 -0
  61. package/src/activities/xai-image-generation.ts +86 -0
  62. package/src/activities/xai-video-generation.ts +69 -0
  63. package/src/activities-control.ts +4 -0
  64. package/src/activities.ts +7 -0
  65. package/src/index.ts +51 -0
  66. package/src/model-checkpoint-memory-collector.ts +8 -1
  67. package/src/model-context-contributions.ts +159 -0
  68. package/src/observability-metrics.ts +282 -12
  69. package/src/sandbox-routing.ts +13 -0
  70. package/src/workflows/activities.ts +1 -0
  71. package/src/workflows/file-upload-reaper.ts +8 -2
  72. package/src/workflows/session.ts +219 -14
  73. package/src/workflows/site-auth-maintenance.ts +14 -0
  74. package/src/workflows.ts +1 -0
  75. package/dist/activities-control-44KBWLSM.js.map +0 -1
  76. package/dist/activities-turn-K4CEDEGJ.js.map +0 -1
  77. package/dist/chunk-E3RI3I33.js.map +0 -1
  78. package/dist/chunk-KKCRGAGZ.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/activity-services.ts","../src/activities/codex-capacity.ts","../src/activities/codex-rotation.ts","../src/activities/goals.ts","../src/activities/sandbox-images.ts","../src/activities/packs.ts","../src/activities/streaming.ts","../src/activities/parent-wake.ts","../src/sandbox-resume.ts","../src/sandbox-routing.ts","../src/activities/common.ts"],"sourcesContent":["import { dbSearchPath, getSettings, resolveNatsControlPlaneAuth } from \"@opengeni/config\";\nimport { createDb } from \"@opengeni/db\";\nimport { createNatsEventBus } from \"@opengeni/events\";\nimport { createObservability } from \"@opengeni/observability\";\nimport { createObjectStorage } from \"@opengeni/storage\";\nimport type { ActivityDependencies, SharedActivityServices } from \"./activities/types\";\nimport { observabilityEventLogger } from \"./observability-metrics\";\n\n/**\n * Build the dependency graph common to both worker roles exactly once.\n *\n * This module deliberately has no import edge to @opengeni/runtime or\n * @opengeni/documents. Those graphs are added by the role-specific factories,\n * preventing an idle process from retaining an unused model SDK or parser\n * stack for its entire lifetime.\n */\nexport function createSharedActivityServices(\n dependencies: ActivityDependencies,\n): () => Promise<SharedActivityServices> {\n let servicesPromise: Promise<SharedActivityServices> | null = null;\n\n return async function services(): Promise<SharedActivityServices> {\n servicesPromise ??= (async () => {\n const settings = dependencies.settings ?? getSettings();\n const observability =\n dependencies.observability ?? createObservability(settings, { component: \"worker\" });\n const searchPath = dbSearchPath(settings);\n const dbClient = dependencies.db\n ? null\n : createDb(settings.databaseUrl, {\n ...(searchPath ? { searchPath } : {}),\n rlsStrategy: settings.rlsStrategy,\n });\n const controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n\n return {\n settings,\n db: dependencies.db ?? dbClient!.db,\n bus:\n dependencies.bus ??\n (await createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth\n ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password }\n : undefined,\n { logger: observabilityEventLogger(observability) },\n )),\n objectStorage: dependencies.objectStorage ?? createObjectStorage(settings),\n observability,\n wakeSessionWorkflow: dependencies.wakeSessionWorkflow ?? null,\n signalSessionAttemptQuiesced: dependencies.signalSessionAttemptQuiesced ?? null,\n inspectSessionAttemptActivity: dependencies.inspectSessionAttemptActivity ?? null,\n signalCodexCapacityWorkflow: dependencies.signalCodexCapacityWorkflow ?? null,\n startSandboxReaperWorkflow: dependencies.startSandboxReaperWorkflow ?? null,\n startVideoGenerationWorkflow: dependencies.startVideoGenerationWorkflow ?? null,\n entitlements: dependencies.entitlements ?? null,\n connectionCredentials: dependencies.connectionCredentials ?? null,\n };\n })();\n return await servicesPromise;\n };\n}\n","import {\n fetchCodexUsageForAccount,\n getCodexCapacityWaitForSession,\n listCodexAccountStatuses,\n listPendingCodexCapacityWakeTargets,\n reconcileCodexCapacityWait as reconcileCodexCapacityWaitDb,\n type CodexCapacityWakeTarget,\n type CodexCapacitySelectionContext,\n} from \"@opengeni/db\";\nimport type { Settings } from \"@opengeni/config\";\nimport {\n CODEX_USAGE_EXHAUSTED_PCT,\n authoritativeCodexCapacityResetAt,\n isCodexCredentialEligible,\n isCodexCredentialHealthy,\n selectCodexCredentialLeaseForTurn,\n} from \"./codex-rotation\";\nimport type {\n ControlActivityServices,\n GetCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitResult,\n} from \"./types\";\n\ntype CodexCapacitySignalServices = {\n signalCodexCapacityWorkflow?:\n | NonNullable<ControlActivityServices[\"signalCodexCapacityWorkflow\"]>\n | null\n | undefined;\n wakeSessionWorkflow: ControlActivityServices[\"wakeSessionWorkflow\"];\n};\n\n/**\n * Run a bounded set of usage refreshes, then repair every committed waiter\n * revision even when an individual provider refresh failed. The database\n * outbox remains authoritative; this helper only guarantees that every worker\n * refresh path reaches the same post-commit delivery seam.\n */\nexport async function refreshCodexUsageAndRepairCapacityWaiters(\n refreshes: readonly (() => Promise<unknown>)[],\n repairPendingWakes: () => Promise<void>,\n): Promise<void> {\n await Promise.all(refreshes.map((refresh) => refresh().catch(() => undefined)));\n await repairPendingWakes();\n}\n\n/** Deliver committed waiter revisions; Postgres remains the repairable outbox. */\nexport async function signalCodexCapacityWakeTargets(\n services: CodexCapacitySignalServices,\n targets: readonly CodexCapacityWakeTarget[],\n): Promise<void> {\n await Promise.allSettled(\n targets.map((target) =>\n services.signalCodexCapacityWorkflow\n ? services.signalCodexCapacityWorkflow({\n accountId: target.accountId,\n workspaceId: target.workspaceId,\n sessionId: target.sessionId,\n workflowId: target.workflowId,\n wakeRevision: target.wakeRevision,\n })\n : services.wakeSessionWorkflow\n ? services.wakeSessionWorkflow({\n accountId: target.accountId,\n workspaceId: target.workspaceId,\n sessionId: target.sessionId,\n workflowId: target.workflowId,\n wakeRevision: target.workflowWakeRevision,\n })\n : Promise.resolve(),\n ),\n );\n}\n\n/** Repair a commit/signal crash edge by redelivering every pending revision. */\nexport async function signalPendingCodexCapacityWakeTargets(\n services: CodexCapacitySignalServices & { db: ControlActivityServices[\"db\"] },\n workspaceId: string,\n): Promise<void> {\n const targets = await listPendingCodexCapacityWakeTargets(services.db, workspaceId).catch(\n () => [],\n );\n await signalCodexCapacityWakeTargets(services, targets);\n}\n\nexport function codexCapacityDecision(\n context: CodexCapacitySelectionContext,\n settings: Settings,\n): ReturnType<Parameters<typeof reconcileCodexCapacityWaitDb>[2]> {\n const now = new Date();\n const selected = selectCodexCredentialLeaseForTurn({\n context,\n leasingEnabled: settings.codexCredentialLeasingEnabled,\n sessionId: context.sessionId,\n sessionPinnedCredentialId: context.sessionPinnedCredentialId,\n sessionPinSource: context.sessionPinSource,\n sessionLastCredentialId: context.sessionLastCredentialId,\n now,\n });\n const selectedAccount = selected.credentialId\n ? context.accounts.find((account) => account.id === selected.credentialId)\n : undefined;\n const selectedIsAvailable =\n selectedAccount !== undefined &&\n (selectedAccount.id === context.existingCredentialId\n ? isCodexCredentialHealthy(selectedAccount, now)\n : isCodexCredentialEligible(selectedAccount, now));\n if (selected.credentialId && selectedIsAvailable) {\n return {\n kind: \"available\",\n credentialId: selected.credentialId,\n diagnostic: {\n connectedCount: context.accounts.length,\n eligibleCount: context.accounts.filter((account) => isCodexCredentialEligible(account, now))\n .length,\n },\n };\n }\n const authoritativeReset = authoritativeCodexCapacityResetAt(context.accounts, now);\n return {\n kind: \"unavailable\",\n earliestResetAt: authoritativeReset,\n resetKind: authoritativeReset ? \"authoritative\" : \"bounded_refresh\",\n diagnostic: {\n connectedCount: context.accounts.length,\n allocatorEnabledCount: context.accounts.filter((account) => account.allocatorEnabled).length,\n policyHash: context.policyHash,\n },\n };\n}\n\nasync function refreshCapacityMetadata(\n services: ControlActivityServices,\n workspaceId: string,\n): Promise<void> {\n const accounts = await listCodexAccountStatuses(services.db, workspaceId).catch(() => []);\n const stale = accounts.filter(\n (account) =>\n account.allocatorEnabled &&\n account.status === \"active\" &&\n ((account.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||\n (account.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||\n account.usageCheckedAt === null),\n );\n await refreshCodexUsageAndRepairCapacityWaiters(\n stale.map(\n (account) => () =>\n fetchCodexUsageForAccount(services.db, services.settings, workspaceId, account.id),\n ),\n () => signalPendingCodexCapacityWakeTargets(services, workspaceId),\n );\n}\n\nexport function createCodexCapacityActivities(services: () => Promise<ControlActivityServices>) {\n async function getCodexCapacityWait(input: GetCodexCapacityWaitInput) {\n const { db } = await services();\n const waiter = await getCodexCapacityWaitForSession(db, input.workspaceId, input.sessionId);\n return waiter\n ? {\n waiterId: waiter.id,\n generation: waiter.generation,\n // A capacity mutation may have committed while its Temporal signal\n // was lost or while the workflow continued-as-new. Reconstruct that\n // outbox edge as an immediate re-evaluation rather than waiting for\n // the older timer.\n nextCheckAt:\n waiter.wakeRevision > waiter.observedWakeRevision\n ? new Date(0).toISOString()\n : waiter.nextCheckAt.toISOString(),\n wakeRevision: waiter.wakeRevision,\n }\n : null;\n }\n\n async function reconcileCodexCapacityWait(\n input: ReconcileCodexCapacityWaitInput,\n ): Promise<ReconcileCodexCapacityWaitResult> {\n const resolved = await services();\n const current = await getCodexCapacityWaitForSession(\n resolved.db,\n input.workspaceId,\n input.sessionId,\n );\n if (!current || current.id !== input.waiterId || current.generation !== input.generation) {\n return { action: \"stale\" };\n }\n if (input.cause === \"timer\" && current.nextCheckAt.getTime() <= Date.now()) {\n // This is a bounded secret-safe control-plane quota refresh. It creates no\n // turn, model call, user message, schedule, or entitlement action.\n await refreshCapacityMetadata(resolved, input.workspaceId);\n }\n const result = await reconcileCodexCapacityWaitDb(\n resolved.db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n waiterId: input.waiterId,\n generation: input.generation,\n },\n (context) => codexCapacityDecision(context, resolved.settings),\n );\n if (result.events.length > 0) {\n try {\n await resolved.bus.publish(input.workspaceId, input.sessionId, result.events);\n } catch {\n // Postgres is authoritative; SSE replay/gap fill repairs missed fanout.\n }\n }\n if (result.action === \"resumed\") {\n return { action: \"resumed\" };\n }\n if (result.action === \"waiting\") {\n return {\n action: \"waiting\",\n waiterId: result.waiter.id,\n generation: result.waiter.generation,\n nextCheckAt: result.waiter.nextCheckAt.toISOString(),\n wakeRevision: result.waiter.wakeRevision,\n };\n }\n return { action: result.action };\n }\n\n return { getCodexCapacityWait, reconcileCodexCapacityWait };\n}\n","// Multi-account P3 — the PURE rotation ranker. Zero I/O: no provider calls, no\n// decrypts, no db. It consumes the already-loaded, metadata-only account list\n// (cached usage columns + the exhausted_until cooldown column) and returns the\n// account a turn should run on. The two call sites (turn-start pre-emption and\n// the reactive 429 catch in agent-turn.ts) feed its result into the unchanged\n// `selectCodexCredentialForTurn` precedence gate (pin > active). Keeping the\n// decision pure makes the whole rotation correctness story unit-testable in\n// isolation (see codex-rotation.test.ts).\nimport type {\n CodexAccountStatus,\n CodexCredentialLeaseSelectionContext,\n CodexLeaseAccountStatus,\n CodexPinSource,\n} from \"@opengeni/db\";\n\nexport type CodexRotationAccount = CodexAccountStatus | CodexLeaseAccountStatus;\n\nexport type CodexRotationStrategy =\n | \"most_remaining\"\n | \"round_robin\"\n | \"drain_then_next\"\n | \"sharded\";\n\n/**\n * The ONE strategy rotation-enabled workspaces run: sticky-sharded. The legacy\n * strategies are all strictly dominated post-cache-affinity — session\n * stickiness is worth ~half the prompt-cache hit rate, and round_robin /\n * most_remaining churn accounts per turn while drain_then_next concentrates\n * every concurrent session on ONE account (the measured concurrency-eviction\n * failure sharding replaced). Stored `rotation_strategy` values are therefore\n * NORMALIZED here at every read site: legacy values (and any future unknown\n * string) behave as \"sharded\". The column and the legacy branch code are kept\n * intact for old-binary rollback safety — they are simply unreachable through\n * this normalization. The API accepts-but-ignores strategy writes for the same\n * reason (no SDK caller breaks). User-facing choice is intentionally gone: the\n * remaining real intents are rotation on/off, per-account allocator\n * include/exclude, and manual pins — not algorithm selection.\n */\nexport function effectiveRotationStrategy(_stored: string): CodexRotationStrategy {\n return \"sharded\";\n}\n\n/**\n * How a session's codex pin governs THIS turn's account selection (pure). Encodes the\n * policy-pin LIFECYCLE rule: a 'policy' pin is meaningful ONLY while the sharded policy\n * is active.\n * • \"manual\" — a manual pin: honored under EVERY strategy; never moved or cleared.\n * • \"sharded\" — the sharded policy is active and the pin is non-manual: assign / keep\n * / re-shard the deterministic home (covers an unpinned first turn AND\n * an existing policy pin).\n * • \"clearStale\" — a 'policy' pin while the sharded policy is NOT active: IGNORE it\n * (never honor it as a sticky pin — that is the no-escape trap) and\n * clear it lazily so the session converges to the active strategy.\n * • \"unpinned\" — no pin (or none that applies): follow the active strategy / workspace\n * active pointer, unchanged.\n */\nexport type CodexPinDisposition = \"manual\" | \"sharded\" | \"clearStale\" | \"unpinned\";\n\n/** Classify a session's codex pin against the active rotation regime (see {@link CodexPinDisposition}). */\nexport function classifyCodexPin(args: {\n pinnedCredentialId: string | null;\n pinSource: CodexPinSource | null;\n strategy: CodexRotationStrategy;\n rotationEnabled: boolean;\n}): CodexPinDisposition {\n const { pinnedCredentialId, pinSource, strategy, rotationEnabled } = args;\n const pinned = pinnedCredentialId != null;\n // A manual pin is sacrosanct under every strategy — checked FIRST so sharded never\n // touches it. DEFENSE-IN-DEPTH (fail-safe toward sacredness): a pin whose source is\n // anything OTHER than the explicit 'policy' — including a NULL source (a pre-backfill\n // row, or any pin an unforeseen path wrote without labeling it) — is treated as\n // MANUAL. An unlabeled pin must NEVER be policy-moved; only an explicitly-'policy' pin\n // is re-shardable.\n if (pinned && pinSource !== \"policy\") {\n return \"manual\";\n }\n const shardedActive = rotationEnabled && effectiveRotationStrategy(strategy) === \"sharded\";\n if (shardedActive) {\n return \"sharded\";\n }\n // A policy pin outside the sharded regime is stale → clear it.\n if (pinned && pinSource === \"policy\") {\n return \"clearStale\";\n }\n return \"unpinned\";\n}\n\nexport type RotationDecision =\n // The chosen account. `moved` ⇒ it differs from the current active pointer, so\n // the caller must persist the pointer move (and the switch is a \"rotation\").\n | { kind: \"active\"; credentialId: string; moved: boolean }\n // Every eligible account is capped/cooling: idle until the soonest instant ANY\n // account clears every blocking condition (the multi-account generalization of\n // the single-account idle-until-reset).\n | { kind: \"allCapped\"; earliestResetAt: Date }\n // No connected accounts at all (preserves today's relogin-fail path).\n | { kind: \"none\" };\n\nexport type CodexTurnLeaseSelection = {\n credentialId: string | null;\n decision: RotationDecision;\n /** Policy/manual homes never move the workspace-global legacy pointer. */\n advanceActivePointer?: boolean;\n};\n\n// Invariant 4 (NO THRASH / BOUNDED) safety floors. An all-capped idle MUST be a\n// positive, bounded wait — a null / elapsed / unknown reset can NEVER collapse it\n// into a 0 or a past instant (which the caller would turn into a 0 continueDelayMs\n// and a tight re-dispatch loop that hammers CPU/DB and never runs the model, so the\n// stale usage cache never self-heals).\n/** The minimum all-capped idle: continueDelayMs is clamped to at least this (never 0). */\nexport const MIN_IDLE_MS = 60_000; // 60s\n/**\n * Cooldown applied to an exhausted account whose cached reset is null / unknown\n * / already-elapsed (the turn hot path never refreshes usage, so a capped window's\n * reset reads stale). Treating it as \"available after a default cooldown\" keeps\n * availableAt — and therefore earliestReset — ALWAYS in the future.\n */\nexport const DEFAULT_RESET_COOLDOWN_MS = 60_000; // 60s\n/** Cached provider usage becomes unavailable only at actual exhaustion. */\nexport const CODEX_USAGE_EXHAUSTED_PCT = 100;\n\nfunction effectiveWindowUsed(usedPercent: number | null, resetAt: Date | null, now: Date): number {\n // A completed provider window is eligible immediately even if its last cache\n // sample still says 100%. This is the five-hour reset boundary—not a TTL\n // heuristic—and avoids stranding a reset subscription while another remains\n // healthy. A future/unknown reset keeps the cached percentage authoritative.\n return resetAt && resetAt.getTime() <= now.getTime() ? 0 : (usedPercent ?? 0);\n}\n\n/** The worse live window: weekly binds as hard as 5h. */\nfunction bindingUsedPct(acct: CodexRotationAccount, now: Date): number {\n return Math.max(\n effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now),\n effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now),\n );\n}\n\n/**\n * Remaining quota across the binding window — the P3 rotation key. Mirrors\n * buildCodexUsageWindowFromCache's `remaining = 100 - percent`, taking the MIN\n * across both windows (the scarcer of 5h/weekly). null percent ⇒ 100 remaining.\n */\nfunction bindingRemaining(acct: CodexRotationAccount, now: Date): number {\n const primaryRemaining =\n 100 - effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now);\n const secondaryRemaining =\n 100 - effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now);\n return Math.min(primaryRemaining, secondaryRemaining);\n}\n\nfunction cooling(acct: CodexRotationAccount, now: Date): boolean {\n return acct.exhaustedUntil != null && acct.exhaustedUntil.getTime() > now.getTime();\n}\n\n/**\n * Healthy for an already-leased/in-flight turn = connected/usable (status\n * \"active\", excludes needs_relogin/error), not cooling, and not exhausted in\n * either provider window. Allocator eligibility is\n * deliberately separate so disabling NEW work cannot break an existing live lease.\n */\nexport function isCodexCredentialHealthy(acct: CodexRotationAccount, now: Date): boolean {\n return (\n acct.status === \"active\" &&\n !cooling(acct, now) &&\n bindingUsedPct(acct, now) < CODEX_USAGE_EXHAUSTED_PCT\n );\n}\n\n/** New automatic allocation requires both health and explicit allocator eligibility. */\nexport function isCodexCredentialEligible(acct: CodexRotationAccount, now: Date): boolean {\n return acct.allocatorEnabled && isCodexCredentialHealthy(acct, now);\n}\n\n/**\n * Public eligibility predicate (same definition as the private `eligible`): an\n * account is usable this turn iff it is connected/active, not cooling, and below\n * actual exhaustion on both windows. The worker's sharded home\n * health-check uses this to decide whether a session's existing policy pin is still\n * a valid home or must be re-sharded.\n */\nexport function isCodexAccountEligible(acct: CodexRotationAccount, now: Date): boolean {\n return isCodexCredentialEligible(acct, now);\n}\n\n/** Deterministic 32-bit FNV-1a over a UTF-16 code-unit stream. Pure, allocation-free. */\nfunction fnv1a32(input: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n // 32-bit FNV prime multiply via Math.imul; `>>> 0` keeps it unsigned.\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\n\n/**\n * Session-sharded HOME account (AM-6): the deterministic account a session runs on\n * under the \"sharded\" strategy — `stableAccountList[ hash(sessionId) % N ]` over the\n * ELIGIBLE (connected, not cooling, not exhausted) accounts in stable created_at\n * order (`listCodexAccountStatuses`).\n *\n * Why deterministic hash over \"least-loaded by session count\" (AM-6): it needs ZERO\n * coordination — every worker computes the same home for a given (sessionId,\n * eligible-set), so a burst of concurrent first-turns can't all read the same\n * \"least-loaded\" account and stampede it (read-then-write skew), and there is no\n * shared round-robin cursor to contend on. It is balanced in expectation.\n *\n * Re-shard (AM-5): pass the just-capped account as already-cooling (or simply let it\n * fall over its threshold) and this reshuffles the SURVIVORS deterministically — the\n * sessions that shared a capped account spread across the remaining pool by their own\n * hashes instead of all re-concentrating on one first-eligible failover.\n *\n * Returns null when NO account is eligible (the caller idles until reset).\n */\nexport function shardCredentialForSession(args: {\n sessionId: string;\n accounts: CodexRotationAccount[];\n now: Date;\n}): string | null {\n const { sessionId, accounts, now } = args;\n const eligibles = accounts.filter((acct) => isCodexCredentialEligible(acct, now));\n if (eligibles.length === 0) {\n return null;\n }\n const index = fnv1a32(sessionId) % eligibles.length;\n return eligibles[index]!.id;\n}\n\n/** earliestResetAt across ALL connected accounts — exported for the sharded all-capped idle. */\nexport function earliestCodexReset(accounts: CodexRotationAccount[], now: Date): Date {\n return earliestReset(accounts, now);\n}\n\n/**\n * The proactive SHARDED home decision (pure — zero I/O, like {@link chooseRotationActive}).\n * Decides the account a session should run on THIS turn under the \"sharded\" strategy,\n * given its current POLICY pin (null on the first turn) and the accounts snapshot:\n *\n * - keepPin: the current policy pin is still ELIGIBLE → run there, no rewrite. This\n * is the steady-state cache-warm path (a session stays on its one home account).\n * - reshard: no policy pin yet (first-turn lazy assignment, AM-7) OR the policy pin\n * is capped/ineligible (proactive re-shard, AM-4) → deterministically shard over the\n * ELIGIBLE set (AM-6) and durably (re)write the pin (`rewritePin:true`, AM-3/AM-5).\n * - allCapped: no account is eligible → the caller idles until the earliest reset.\n *\n * A MANUAL pin is handled by the CALLER (it never reaches here); this function only\n * governs policy homes. Pure so the assignment/re-shard/keep logic is unit-testable\n * without a worker/db env; the caller wraps it with a self-heal usage refresh between\n * two evaluations exactly like chooseRotationActive's allCapped path.\n */\nexport function chooseShardedHome(args: {\n sessionId: string;\n currentPolicyPin: string | null;\n accounts: CodexRotationAccount[];\n now: Date;\n}):\n | { kind: \"home\"; credentialId: string; rewritePin: boolean }\n | { kind: \"allCapped\"; earliestResetAt: Date } {\n const { sessionId, currentPolicyPin, accounts, now } = args;\n const pinRow = currentPolicyPin\n ? (accounts.find((acct) => acct.id === currentPolicyPin) ?? null)\n : null;\n if (pinRow && isCodexCredentialEligible(pinRow, now)) {\n return { kind: \"home\", credentialId: currentPolicyPin!, rewritePin: false };\n }\n const home = shardCredentialForSession({ sessionId, accounts, now });\n if (home == null) {\n return { kind: \"allCapped\", earliestResetAt: earliestReset(accounts, now) };\n }\n return { kind: \"home\", credentialId: home, rewritePin: true };\n}\n\n/**\n * The soonest instant `acct` clears EVERY blocking condition: its cooldown end,\n * and each window's reset (only when that window is at/over the threshold). The\n * literal multi-account generalization of #143's single-account resetsInSeconds.\n *\n * GUARANTEE (invariant 4): the result is ALWAYS in the future. A blocking window\n * whose cached reset is null / unknown / already-elapsed does NOT contribute a past\n * instant (the old EPOCH0 seed bug that made earliestReset land in 1970 → a 0\n * continueDelayMs → a tight idle loop). Such a window is treated as clearing after a\n * default cooldown (now + DEFAULT_RESET_COOLDOWN_MS), so the caller always idles a\n * bounded positive time and re-checks (which refreshes usage and self-heals).\n */\nexport function availableAt(acct: CodexRotationAccount, now: Date): Date {\n const nowMs = now.getTime();\n // An unknown/elapsed block clears after a default cooldown, never in the past.\n const defaultClear = new Date(nowMs + DEFAULT_RESET_COOLDOWN_MS);\n const candidates: Date[] = [];\n // An active cooldown only blocks while it is still in the future; a past cooldown\n // self-clears (matches `cooling()`), so it must not pin availableAt to the past.\n if (acct.exhaustedUntil != null && acct.exhaustedUntil.getTime() > nowMs) {\n candidates.push(acct.exhaustedUntil);\n }\n const windowClear = (over: boolean, resetAt: Date | null | undefined) => {\n if (!over) return;\n // Over-threshold window: wait for its KNOWN future reset; a null/elapsed cached\n // reset is unknown → default cooldown (never a past instant).\n candidates.push(resetAt != null && resetAt.getTime() > nowMs ? resetAt : defaultClear);\n };\n windowClear(\n effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now) >=\n CODEX_USAGE_EXHAUSTED_PCT,\n acct.primaryResetAt,\n );\n windowClear(\n effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now) >=\n CODEX_USAGE_EXHAUSTED_PCT,\n acct.secondaryResetAt,\n );\n // Ineligible for a non-quota reason (needs_relogin / error) with no known block, or\n // a cleared cooldown: still idle a bounded cooldown before re-check — never the past.\n if (candidates.length === 0) {\n return defaultClear;\n }\n // Clears EVERY blocking condition ⇒ the MAX of the per-condition clear instants.\n return candidates.reduce((a, b) => (b.getTime() > a.getTime() ? b : a));\n}\n\n/** earliestResetAt across ALL connected accounts (min of each account's availableAt). */\nfunction earliestReset(accounts: CodexRotationAccount[], now: Date): Date {\n return accounts\n .map((acct) => availableAt(acct, now))\n .reduce((a, b) => (b.getTime() < a.getTime() ? b : a));\n}\n\n/**\n * Earliest provider/cooldown timestamp that is actually authoritative. The\n * ranker's `availableAt` deliberately synthesizes a positive default for\n * unknown/stale state; durable capacity waits must distinguish that bounded\n * refresh backoff from a real provider reset timer.\n */\nexport function authoritativeCodexCapacityResetAt(\n accounts: CodexRotationAccount[],\n now: Date,\n): Date | null {\n const future: Date[] = [];\n for (const account of accounts) {\n if (!account.allocatorEnabled || account.status !== \"active\") continue;\n if (account.exhaustedUntil && account.exhaustedUntil.getTime() > now.getTime()) {\n future.push(account.exhaustedUntil);\n }\n if (\n (account.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT &&\n account.primaryResetAt &&\n account.primaryResetAt.getTime() > now.getTime()\n ) {\n future.push(account.primaryResetAt);\n }\n if (\n (account.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT &&\n account.secondaryResetAt &&\n account.secondaryResetAt.getTime() > now.getTime()\n ) {\n future.push(account.secondaryResetAt);\n }\n }\n if (future.length === 0) return null;\n return future.reduce((earliest, candidate) =>\n candidate.getTime() < earliest.getTime() ? candidate : earliest,\n );\n}\n\n/**\n * The bounded all-capped idle delay: clamp(earliestResetAt − now) into\n * [MIN_IDLE_MS, maxMs]. NEVER 0 and NEVER negative, so a null / elapsed / unknown\n * reset cannot collapse the hold into a tight re-dispatch loop (invariant 4). The two\n * agent-turn call sites (proactive turn-start + reactive 429) feed allCapped's\n * earliestResetAt through this before returning continueDelayMs.\n */\nexport function computeIdleDelayMs(earliestResetAt: Date, now: Date, maxMs: number): number {\n const delta = earliestResetAt.getTime() - now.getTime();\n return Math.min(Math.max(delta, MIN_IDLE_MS), maxMs);\n}\n\n// --- P3 reactive-rotation boundedness (Finding 1). The reactive 429 catch, on a\n// LIVE failover candidate, normally returns continueDelayMs:0 (skip the hold and\n// re-dispatch NOW — the just-served account is cooling so the next rank cannot\n// re-pick it). Two independent second-order faults can break that \"cannot\n// re-pick it\" premise and turn the 0-delay re-dispatch into a hot loop, so this\n// pure decision applies two backstops before allowing the 0.\n\n/**\n * Slow-retry floor (Finding 1a) for the double-fault where the just-served\n * account's cooldown write could NOT be confirmed persisted: the next proactive\n * rank might re-select the same capped account (stale-low cached usedPercent, not\n * cooling). A positive floor degrades that to a SLOW retry instead of a\n * model-paced hot loop. A few seconds — long enough to break the loop, short\n * enough to stay responsive once the transient write fault clears.\n */\nexport const REACTIVE_PERSISTENCE_FAULT_FLOOR_MS = 5_000; // 5s\n/**\n * Circuit-breaker slack (Finding 1b) added to the connected-account count to bound\n * consecutive reactive failovers. Each legitimate failover cools one account, so\n * after at most N failovers every account is capped and the reactive path takes the\n * all-capped idle instead; the +margin absorbs benign capacity re-ranks without\n * tripping the breaker in normal use.\n */\nexport const REACTIVE_ROTATION_MARGIN = 2;\n/**\n * The FIXED positive idle the reactive path falls to once consecutive reactive\n * failovers exceed the bound (a double-fault where cooldown writes are not sticking\n * AND the 429s carry no usage headers, so the same account keeps getting re-picked).\n * Mirrors the all-capped floor — a mandatory, bounded hold, never another 0-delay\n * re-dispatch — so the loop can never hammer the capped backend + DB (invariant 4).\n */\nexport const REACTIVE_CIRCUIT_BREAKER_IDLE_MS = MIN_IDLE_MS; // 60s\n\n/** The reactive-resume shape returned to the goal-continuation caller. */\nexport type ReactiveRotationResume = { continueDelayMs: number; idleUntilReset: boolean };\n\n/**\n * Decide the continueDelayMs for a reactive 429 failover onto a LIVE candidate,\n * bounding the (otherwise 0-delay) re-dispatch against two second-order faults:\n *\n * 1. Circuit breaker (1b): if the consecutive reactive-failover streak (prior\n * rotated 429 failovers since the last successful turn, PLUS this one) exceeds\n * `connectedAccountCount + REACTIVE_ROTATION_MARGIN`, fall to a FIXED positive,\n * MANDATORY idle. Covers the double-fault (cooldown write not persisted + a\n * header-less cap 429) where the same capped account is re-picked every turn.\n * 2. Persistence-fault floor (1a): if the just-served account's cooldown could NOT\n * be confirmed persisted, use a positive floor (slow retry) instead of 0.\n *\n * Otherwise (a confirmed cooldown + an in-bounds streak) returns the unchanged\n * 0-delay fast re-dispatch — the happy single-rotation path is byte-identical.\n * Pure so the boundedness contract is unit-testable without a worker/db env.\n */\nexport function computeReactiveRotationResume(args: {\n cooldownPersisted: boolean;\n priorConsecutiveRotations: number; // reactive rotated failovers since last success (excludes this one)\n connectedAccountCount: number;\n}): ReactiveRotationResume {\n const streak = args.priorConsecutiveRotations + 1; // include the failover about to be published\n const bound = args.connectedAccountCount + REACTIVE_ROTATION_MARGIN;\n if (streak > bound) {\n return { continueDelayMs: REACTIVE_CIRCUIT_BREAKER_IDLE_MS, idleUntilReset: true };\n }\n if (!args.cooldownPersisted) {\n return { continueDelayMs: REACTIVE_PERSISTENCE_FAULT_FLOOR_MS, idleUntilReset: false };\n }\n return { continueDelayMs: 0, idleUntilReset: false };\n}\n\n/**\n * THE pure rotation ranker. `accounts` arrives in stable created_at order\n * (listCodexAccountStatuses), which deterministically breaks ranking ties.\n */\nexport function chooseRotationActive(args: {\n rotationStrategy: CodexRotationStrategy;\n activeCredentialId: string | null;\n priorCredentialId: string | null;\n accounts: CodexRotationAccount[];\n now: Date;\n}): RotationDecision {\n const { activeCredentialId, priorCredentialId, accounts, now } = args;\n // Normalize at the entry point: rotation-enabled ALWAYS behaves as sharded\n // (see effectiveRotationStrategy). args keeps the field so call sites and\n // tests can still express stored legacy values.\n const rotationStrategy = effectiveRotationStrategy(args.rotationStrategy);\n const allocatableAccounts = accounts.filter((account) => account.allocatorEnabled);\n\n if (allocatableAccounts.length === 0) {\n return { kind: \"none\" };\n }\n\n const eligibles = allocatableAccounts.filter((acct) => isCodexCredentialEligible(acct, now));\n\n // The active pointer is a cursor/manual preference, NOT a sticky lease. In\n // particular, most_remaining must rank the whole eligible pool every turn;\n // keeping a healthy active account sticky was the production monopolization\n // defect fixed by credential allocator. drain_then_next remains the one explicitly sticky\n // strategy, and a manual pin is handled by the caller as explicit policy.\n const decide = (chosen: CodexRotationAccount | undefined): RotationDecision => {\n if (!chosen) {\n return {\n kind: \"allCapped\",\n earliestResetAt: earliestReset(allocatableAccounts, now),\n };\n }\n return {\n kind: \"active\",\n credentialId: chosen.id,\n moved: chosen.id !== activeCredentialId,\n };\n };\n\n if (rotationStrategy === \"round_robin\") {\n // Next eligible AFTER the prior account in list order (wrap around). When the\n // prior account isn't found, start from the head.\n if (eligibles.length === 0) {\n return {\n kind: \"allCapped\",\n earliestResetAt: earliestReset(allocatableAccounts, now),\n };\n }\n const priorIdx = priorCredentialId\n ? allocatableAccounts.findIndex((acct) => acct.id === priorCredentialId)\n : -1;\n const ordered =\n priorIdx >= 0\n ? [\n ...allocatableAccounts.slice(priorIdx + 1),\n ...allocatableAccounts.slice(0, priorIdx + 1),\n ]\n : allocatableAccounts;\n const chosen = ordered.find((acct) => isCodexCredentialEligible(acct, now));\n return decide(chosen);\n }\n\n if (rotationStrategy === \"drain_then_next\") {\n // Stay on the prior account while it is eligible (drain it), else first eligible.\n const priorRow = priorCredentialId\n ? accounts.find((acct) => acct.id === priorCredentialId)\n : undefined;\n if (priorRow && isCodexCredentialEligible(priorRow, now)) {\n return decide(priorRow);\n }\n return decide(eligibles[0]);\n }\n\n // most_remaining (default + the correctness path). Across the eligible set:\n // 1. least active leases (concurrent turns spread before quota metadata moves),\n // 2. most remaining binding quota,\n // 3. fewest historical selections,\n // 4. least-recently selected, then stable created_at/id input order.\n // Base CodexAccountStatus values (pure legacy tests/reactive rank) default the\n // lease/cursor metadata to zero/null, preserving deterministic stable ties.\n const activeLeases = (acct: CodexRotationAccount): number =>\n \"activeLeaseCount\" in acct ? acct.activeLeaseCount : 0;\n const selections = (acct: CodexRotationAccount): number =>\n \"selectionCount\" in acct ? acct.selectionCount : 0;\n const lastSelected = (acct: CodexRotationAccount): number =>\n \"lastSelectedAt\" in acct && acct.lastSelectedAt ? acct.lastSelectedAt.getTime() : 0;\n const chosen = eligibles.reduce<CodexRotationAccount | undefined>((best, acct) => {\n if (!best) {\n return acct;\n }\n if (activeLeases(acct) !== activeLeases(best)) {\n return activeLeases(acct) < activeLeases(best) ? acct : best;\n }\n if (bindingRemaining(acct, now) !== bindingRemaining(best, now)) {\n return bindingRemaining(acct, now) > bindingRemaining(best, now) ? acct : best;\n }\n if (selections(acct) !== selections(best)) {\n return selections(acct) < selections(best) ? acct : best;\n }\n return lastSelected(acct) < lastSelected(best) ? acct : best;\n }, undefined);\n return decide(chosen);\n}\n\n/**\n * Exact pre-0053 selector used while the lease cutover is off.\n *\n * Old workers keep a healthy `most_remaining` active pointer sticky and know\n * nothing about lease counts or fairness cursors. A compatible worker must do\n * the same until BOTH the deployment flag and workspace cutover are enabled;\n * otherwise a rolling fleet would run two allocators at once. When the active\n * pointer is no longer eligible, zeroing the additive metadata delegates to the\n * same capacity ranking that the old selector used.\n */\nexport function chooseLegacyRotationActive(\n args: Parameters<typeof chooseRotationActive>[0],\n): RotationDecision {\n if (args.rotationStrategy === \"most_remaining\") {\n const active = args.activeCredentialId\n ? args.accounts.find((account) => account.id === args.activeCredentialId)\n : undefined;\n if (active && isCodexCredentialEligible(active, args.now)) {\n return { kind: \"active\", credentialId: active.id, moved: false };\n }\n }\n return chooseRotationActive({\n ...args,\n accounts: args.accounts.map((account) => ({\n ...account,\n activeLeaseCount: 0,\n selectionCount: 0,\n lastSelectedAt: null,\n })),\n });\n}\n\n/**\n * Full pure policy at the transaction boundary. A live same-turn lease is\n * idempotent; the rollout-off/manual path preserves pin>pointer behavior; a\n * healthy pin wins only while eligible, so quota/auth quarantine cannot trap a\n * session on one subscription.\n */\nexport function selectCodexCredentialLeaseForTurn(args: {\n context: CodexCredentialLeaseSelectionContext;\n leasingEnabled: boolean;\n sessionId: string;\n sessionPinnedCredentialId: string | null;\n sessionPinSource: CodexPinSource | null;\n sessionLastCredentialId: string | null;\n now: Date;\n}): CodexTurnLeaseSelection {\n const {\n accounts,\n activeCredentialId,\n rotationEnabled,\n leaseRotationEnabled,\n rotationStrategy,\n existingCredentialId,\n } = args.context;\n const leasingEnabled = args.leasingEnabled && leaseRotationEnabled;\n // Normalized: rotation-enabled always behaves as sharded (see\n // effectiveRotationStrategy); the stored value is only ever legacy residue.\n const strategy = effectiveRotationStrategy(rotationStrategy);\n const existing = existingCredentialId\n ? accounts.find((account) => account.id === existingCredentialId)\n : undefined;\n if (existing && isCodexCredentialHealthy(existing, args.now)) {\n return {\n credentialId: existing.id,\n advanceActivePointer: false,\n decision: {\n kind: \"active\",\n credentialId: existing.id,\n moved: existing.id !== activeCredentialId,\n },\n };\n }\n\n const connectedIds = new Set(\n accounts.filter((account) => account.allocatorEnabled).map((account) => account.id),\n );\n\n const pinDisposition = classifyCodexPin({\n pinnedCredentialId: args.sessionPinnedCredentialId,\n pinSource: args.sessionPinSource,\n strategy,\n rotationEnabled,\n });\n\n // A manual pin is user intent, not a policy hint. Never silently fail it over.\n // We still reject allocator-disabled rows for a NEW turn; a healthy live\n // same-turn lease already returned above before this admission filter.\n if (pinDisposition === \"manual\" && args.sessionPinnedCredentialId) {\n const pinned = accounts.find((account) => account.id === args.sessionPinnedCredentialId);\n if (!pinned?.allocatorEnabled) {\n return { credentialId: null, decision: { kind: \"none\" }, advanceActivePointer: false };\n }\n if (isCodexCredentialHealthy(pinned, args.now)) {\n return {\n credentialId: pinned.id,\n decision: { kind: \"active\", credentialId: pinned.id, moved: false },\n advanceActivePointer: false,\n };\n }\n return {\n credentialId: null,\n decision: {\n kind: \"allCapped\",\n earliestResetAt: availableAt(pinned, args.now),\n },\n advanceActivePointer: false,\n };\n }\n\n // Pin-policy homes compose with the credential allocator by sharding only the candidate list\n // handed to this selector. A future policy filter may therefore choose one\n // primary/fallback pool before this ranker runs; accounts from different pools\n // are never union-ranked here.\n if (pinDisposition === \"sharded\") {\n if (accounts.length === 0) {\n return { credentialId: null, decision: { kind: \"none\" }, advanceActivePointer: false };\n }\n const shard = chooseShardedHome({\n sessionId: args.sessionId,\n currentPolicyPin: args.sessionPinSource === \"policy\" ? args.sessionPinnedCredentialId : null,\n accounts,\n now: args.now,\n });\n if (shard.kind === \"allCapped\") {\n return {\n credentialId: null,\n decision: shard,\n advanceActivePointer: false,\n };\n }\n return {\n credentialId: shard.credentialId,\n decision: {\n kind: \"active\",\n credentialId: shard.credentialId,\n moved: shard.credentialId !== activeCredentialId,\n },\n advanceActivePointer: false,\n };\n }\n\n // A stale policy pin is intentionally ignored here and cleared by the caller\n // after the atomic selection. Rotation-off/unpinned behavior otherwise keeps\n // the pre-lease pin > active-pointer contract. The pointer is preference, not\n // proof of capacity: rotation-off must wait on a capped pointer rather than\n // falsely admitting it or silently failing over to another subscription.\n if (!rotationEnabled) {\n const active = activeCredentialId\n ? accounts.find((account) => account.id === activeCredentialId)\n : undefined;\n if (!active?.allocatorEnabled) {\n return { credentialId: null, decision: { kind: \"none\" }, advanceActivePointer: false };\n }\n if (!isCodexCredentialHealthy(active, args.now)) {\n return {\n credentialId: null,\n decision: { kind: \"allCapped\", earliestResetAt: availableAt(active, args.now) },\n advanceActivePointer: false,\n };\n }\n return {\n credentialId: active.id,\n decision: { kind: \"active\", credentialId: active.id, moved: false },\n advanceActivePointer: false,\n };\n }\n\n // Before the workspace cutover bit is enabled (or after the deployment kill\n // switch is turned off), preserve the exact legacy policy used by old workers:\n // a pin stays sticky; otherwise an enabled workspace runs the pure legacy\n // rotation ranker without touching lease/cursor state.\n if (!leasingEnabled && pinDisposition !== \"clearStale\" && args.sessionPinnedCredentialId) {\n const credentialId = connectedIds.has(args.sessionPinnedCredentialId)\n ? args.sessionPinnedCredentialId\n : activeCredentialId && connectedIds.has(activeCredentialId)\n ? activeCredentialId\n : null;\n return {\n credentialId,\n decision: credentialId ? { kind: \"active\", credentialId, moved: false } : { kind: \"none\" },\n };\n }\n\n const priorId = args.sessionLastCredentialId ?? activeCredentialId;\n const choose = leasingEnabled ? chooseRotationActive : chooseLegacyRotationActive;\n const decision = choose({\n rotationStrategy: strategy,\n activeCredentialId,\n // Per-session continuity is the round-robin/drain cursor. Falling back to\n // the workspace pointer is only correct when this session has never run.\n priorCredentialId: priorId,\n accounts,\n now: args.now,\n });\n return {\n credentialId: decision.kind === \"active\" ? decision.credentialId : null,\n decision,\n };\n}\n","import {\n configuredStaticUsageLimits,\n policyProviderIdForModel,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n evaluateWorkspaceModelPolicy,\n latencyModeForMetadata,\n mergeToolRefs,\n reasoningEffortForMetadata,\n type SessionGoal,\n type ToolRef,\n} from \"@opengeni/contracts\";\nimport { isCodexBilledModel } from \"@opengeni/codex\";\nimport {\n enqueueSessionWorkflowWakeIfRunnable,\n getBillingBalance,\n getLatestStartedSessionTurn,\n getWorkspaceModelPolicy,\n getSessionGoal,\n isCodexBilledTurn,\n materializeGoalContinuation,\n requireSession,\n sumUsageQuantity,\n type Database,\n} from \"@opengeni/db\";\nimport type {\n ControlActivityServices,\n MaybeContinueGoalInput,\n MaybeContinueGoalResult,\n} from \"./types\";\n\nexport function createGoalActivities(services: () => Promise<ControlActivityServices>) {\n async function enqueueGoalRetryWake(input: MaybeContinueGoalInput): Promise<void> {\n const { db } = await services();\n await enqueueSessionWorkflowWakeIfRunnable(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n temporalWorkflowId: input.workflowId,\n reason: \"goal_retry\",\n // A permanently invalid goal must not become a tight workflow loop. One\n // durable retry after a short delay preserves liveness without scanning.\n notBefore: new Date(Date.now() + 30_000),\n });\n }\n\n async function maybeContinueGoal(\n input: MaybeContinueGoalInput,\n ): Promise<MaybeContinueGoalResult> {\n const { settings, db, bus } = await services();\n // Cheap pre-read: the common goal-less session skips the budget queries.\n const existingGoal = await getSessionGoal(db, input.workspaceId, input.sessionId);\n if (!existingGoal || existingGoal.status !== \"active\") {\n return { action: \"none\" };\n }\n // Loaded before the budget check so the codex-billed predicate and the\n // synthesized turn use the SAME effective policy. An explicit per-turn\n // model can differ from the persisted session default; follow-up goal work\n // must preserve the newest policy that actually emitted `turn.started`.\n // Admission-rejected turns have no such event and cannot poison it.\n // Kept below the goal-less fast path so a non-goal session still skips the\n // reads entirely.\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n const latestStartedTurn = await getLatestStartedSessionTurn(\n db,\n input.workspaceId,\n input.sessionId,\n );\n let continuationModel = latestStartedTurn?.model ?? session.model;\n const continuationReasoningEffort =\n latestStartedTurn?.reasoningEffort ??\n reasoningEffortForMetadata(session.metadata, settings.openaiReasoningEffort);\n const continuationLatencyMode =\n latestStartedTurn?.latencyMode ?? latencyModeForMetadata(session.metadata, \"standard\");\n // Workspace model policy: a continuation inherits the last STARTED turn's\n // model, so a single policy-violating turn would otherwise re-arm itself on\n // every continuation (exactly how one bare-model turn kept a goal loop on\n // the paid built-in provider all night). If the inherited model is blocked\n // but the session's own default is allowed, recover to the default; if\n // both are blocked, pause the goal visibly (the budget-pause channel, with\n // a truthful rationale) instead of synthesizing a turn the worker's hard\n // gate would fail over and over.\n let modelPolicyBlocked: string | null = null;\n const workspaceModelPolicy = await getWorkspaceModelPolicy(db, input.workspaceId);\n if (workspaceModelPolicy) {\n const policyBlocks = (modelId: string): boolean =>\n !evaluateWorkspaceModelPolicy(workspaceModelPolicy, {\n providerId: policyProviderIdForModel(settings, modelId),\n modelId,\n }).allowed;\n if (policyBlocks(continuationModel)) {\n if (continuationModel !== session.model && !policyBlocks(session.model)) {\n continuationModel = session.model;\n } else {\n modelPolicyBlocked = `workspace model policy blocks model \"${continuationModel}\"; pick an allowed model or change the workspace model policy`;\n }\n }\n }\n // remote_v2 sessions may only continue on Codex models — refuse synthesis\n // that would leave the portable/non-Codex path (and mixed history shapes).\n if (\n !modelPolicyBlocked &&\n session.codexCompactionMode === \"remote_v2\" &&\n !isCodexBilledModel(continuationModel)\n ) {\n modelPolicyBlocked = `session is locked to Codex remote compaction v2; model \"${continuationModel}\" is not a Codex subscription model`;\n }\n // A codex-model goal continuation is paid by the user's ChatGPT/Codex plan,\n // so it must not be budget-paused for zero OpenGeni credits. This file uses\n // BASE settings (no codex overlay); the predicate does its own credential read.\n const isCodexRun = await isCodexBilledTurn({\n db,\n settings,\n workspaceId: input.workspaceId,\n model: continuationModel,\n });\n // Budget exhaustion pauses the goal visibly instead of failing the\n // session. Computed up front and applied inside the locked decision so a\n // limits pause never consumes continuation budget.\n const budgetBlocked = await goalRunBudgetBlocked(\n settings,\n db,\n input.accountId,\n input.workspaceId,\n isCodexRun,\n );\n const decision = await materializeGoalContinuation(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n workflowId: input.workflowId,\n defaultMaxAutoContinuations: settings.goalMaxAutoContinuations ?? null,\n noProgressLimit: settings.goalNoProgressLimit,\n // A model-policy block takes precedence: it is deterministic (a budget\n // pause can clear on its own; a policy pause needs a model/policy change)\n // and rides the same visible-pause channel.\n budgetBlocked: modelPolicyBlocked ?? budgetBlocked,\n policy: {\n model: continuationModel,\n reasoningEffort: continuationReasoningEffort,\n latencyMode: continuationLatencyMode,\n tools: withFirstPartyTools(settings, session.tools),\n sandboxBackend: session.sandboxBackend,\n },\n prompt: goalContinuationPrompt,\n });\n if (decision.events.length > 0) {\n await bus.publish(input.workspaceId, input.sessionId, decision.events);\n }\n return { action: decision.action };\n }\n\n return {\n enqueueGoalRetryWake,\n maybeContinueGoal,\n };\n}\n\nexport function goalContinuationPrompt(\n goal: SessionGoal,\n autoContinuation: number,\n cap: number | null,\n): string {\n const counter = cap === null ? `${autoContinuation}` : `${autoContinuation}/${cap}`;\n return [\n `[GOAL CONTINUATION ${counter}] The session goal is not done. Goal: ${goal.text}.`,\n `Success criteria: ${goal.successCriteria ?? \"none specified\"}.`,\n \"Continue from the existing conversation state. Do not repeat completed session setup, persistent metadata settings, or context checks merely because this is a new continuation turn.\",\n \"Continue working toward the goal now. If it is actually complete, call opengeni__goal_complete with concrete evidence.\",\n \"If you are blocked or continuing is not productive, call opengeni__goal_pause with your rationale.\",\n \"You may revise the goal with opengeni__goal_update. Do not stop without one of these explicit actions.\",\n ].join(\"\\n\");\n}\n\n/**\n * Ensures a session/turn carries the first-party \"opengeni\" MCP server, which\n * hosts set_session_title, the goal tools, and the permission-gated\n * orchestration/environment/github tools. Attached to EVERY session/turn (not\n * just goal-bearing ones); built-in tool refs are not auto-added to empty tool\n * lists anywhere else in the pipeline. No-op when the server is not configured.\n */\nexport function withFirstPartyTools(settings: Settings, tools: ToolRef[]): ToolRef[] {\n if (!settings.mcpServers.some((server) => server.id === \"opengeni\")) {\n return tools;\n }\n return mergeToolRefs(tools, [{ kind: \"mcp\", id: \"opengeni\" }]);\n}\n\n/**\n * Non-throwing variant of the scheduled-run admission check: returns a human\n * readable reason when balance or monthly caps block another agent run.\n */\nasync function goalRunBudgetBlocked(\n settings: Settings,\n db: Database,\n accountId: string,\n workspaceId: string,\n isCodexRun: boolean,\n): Promise<string | null> {\n // Codex-billed continuations are paid by the user's ChatGPT/Codex plan: skip\n // the credit-balance gate and the monthly model-cost cap. The agent-run COUNT\n // cap below is a volume quota (not a credit/cost gate) and is intentionally kept.\n if (\n !isCodexRun &&\n (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")\n ) {\n const balance = await getBillingBalance(db, accountId);\n if (balance.balanceMicros <= 0) {\n return \"insufficient OpenGeni credits\";\n }\n }\n if (settings.usageLimitsMode === \"static\" || settings.usageLimitsMode === \"managed\") {\n const limits = configuredStaticUsageLimits(settings);\n if (!isCodexRun && limits.maxMonthlyCostMicrosPerAccount) {\n const used = await sumUsageQuantity(db, {\n accountId,\n eventType: \"model.cost\",\n since: startOfUtcMonth(),\n });\n if (used >= limits.maxMonthlyCostMicrosPerAccount) {\n return `monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`;\n }\n }\n if (limits.maxMonthlyAgentRunsPerWorkspace) {\n const used = await sumUsageQuantity(db, {\n workspaceId,\n eventType: \"agent_run.created\",\n since: startOfUtcMonth(),\n });\n if (used + 1 > limits.maxMonthlyAgentRunsPerWorkspace) {\n return `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`;\n }\n }\n }\n return null;\n}\n\nfunction startOfUtcMonth(): Date {\n const now = new Date();\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { CapabilityPack, RigVersion, SandboxBackend } from \"@opengeni/contracts\";\nimport {\n rigProviderImageContentHash,\n rigProviderImageMatchesDefinition,\n rigProviderImageProviderBindingKeyHash,\n} from \"@opengeni/core\";\nimport { resolveModalCheckpointProviderBinding } from \"@opengeni/runtime/sandbox\";\n\nexport function settingsWithPackSandboxImage(\n settings: Settings,\n sandboxImage: string | null,\n sandboxProviderImages: CapabilityPack[\"sandboxProviderImages\"] | null = null,\n): Settings {\n if (!sandboxImage) return settings;\n return {\n ...settings,\n dockerImage: sandboxImage,\n modalImageRef: sandboxImage,\n modalImageId: sandboxProviderImages?.modal?.imageId,\n };\n}\n\nexport function settingsWithRigImage(settings: Settings, rigImage: string | null): Settings {\n if (!rigImage) return settings;\n return {\n ...settings,\n dockerImage: rigImage,\n modalImageRef: rigImage,\n // A logical rig image invalidates a lower-precedence pack/deployment\n // provider ID. A verified version-bound provider ID is applied separately\n // after this precedence step.\n modalImageId: undefined,\n };\n}\n\nexport function rigProviderImageSourceImage(\n settings: Settings,\n backend: SandboxBackend,\n): string | null {\n if (backend === \"modal\") return settings.modalImageId ?? settings.modalImageRef ?? null;\n if (backend === \"docker\") return settings.dockerImage ?? null;\n return null;\n}\n\nexport type RigProviderImageSelectionReason =\n | \"selected\"\n | \"missing\"\n | \"provider_unsupported\"\n | \"not_ready\"\n | \"not_cold_boot_validated\"\n | \"content_mismatch\"\n | \"provider_binding_unavailable\"\n | \"provider_binding_mismatch\";\n\nexport function resolveRigProviderImageSelection(\n settings: Settings,\n version: RigVersion | null,\n backend: SandboxBackend,\n currentProviderBindingKeyHash: string | null,\n): {\n settings: Settings;\n reason: RigProviderImageSelectionReason;\n contentHash: string | null;\n imageId: string | null;\n} {\n if (!version) {\n return { settings, reason: \"missing\", contentHash: null, imageId: null };\n }\n if (backend !== \"modal\") {\n return { settings, reason: \"provider_unsupported\", contentHash: null, imageId: null };\n }\n const image = version.providerImages[backend];\n if (!image) {\n return { settings, reason: \"missing\", contentHash: null, imageId: null };\n }\n if (image.status !== \"ready\" || !image.imageId) {\n return {\n settings,\n reason: \"not_ready\",\n contentHash: image.contentHash,\n imageId: image.imageId,\n };\n }\n if (image.coldBootValidation?.version !== 1) {\n return {\n settings,\n reason: \"not_cold_boot_validated\",\n contentHash: image.contentHash,\n imageId: null,\n };\n }\n const sourceImage = rigProviderImageSourceImage(settings, backend);\n const expectedContentHash = rigProviderImageContentHash({\n backend,\n sourceImage,\n definition: version,\n });\n if (\n image.sourceImage !== sourceImage ||\n image.contentHash !== expectedContentHash ||\n !rigProviderImageMatchesDefinition(image, version)\n ) {\n return {\n settings,\n reason: \"content_mismatch\",\n contentHash: expectedContentHash,\n imageId: null,\n };\n }\n if (!image.providerBindingKeyHash || !currentProviderBindingKeyHash) {\n return {\n settings,\n reason: \"provider_binding_unavailable\",\n contentHash: expectedContentHash,\n imageId: null,\n };\n }\n if (image.providerBindingKeyHash !== currentProviderBindingKeyHash) {\n return {\n settings,\n reason: \"provider_binding_mismatch\",\n contentHash: expectedContentHash,\n imageId: null,\n };\n }\n return {\n // Keep modalImageRef unchanged: the lease continues to fence the logical\n // rig/pack/deployment image, so a newly available build optimization never\n // rotates an already-warm or archive-backed box. modalImageId affects only\n // genuinely fresh provider creation.\n settings: { ...settings, modalImageId: image.imageId },\n reason: \"selected\",\n contentHash: expectedContentHash,\n imageId: image.imageId,\n };\n}\n\nexport async function settingsWithRigProviderImage(\n settings: Settings,\n version: RigVersion | null,\n backend: SandboxBackend,\n resolveBinding: typeof resolveModalCheckpointProviderBinding = resolveModalCheckpointProviderBinding,\n): Promise<Settings> {\n const image = backend === \"modal\" ? version?.providerImages.modal : null;\n if (image?.status !== \"ready\" || !image.providerBindingKeyHash) {\n return resolveRigProviderImageSelection(settings, version, backend, null).settings;\n }\n const structural = resolveRigProviderImageSelection(\n settings,\n version,\n backend,\n image.providerBindingKeyHash,\n );\n if (structural.reason !== \"selected\") return structural.settings;\n let currentProviderBindingKeyHash: string | null = null;\n try {\n const binding = await resolveBinding(settings);\n currentProviderBindingKeyHash = rigProviderImageProviderBindingKeyHash(binding.key);\n } catch {\n // Provider identity is an authority check, not a reason to fail the turn.\n // Preserve the logical image so fresh creation and runtime setup remain the\n // truthful fallback when the identity lookup is unavailable.\n }\n return resolveRigProviderImageSelection(settings, version, backend, currentProviderBindingKeyHash)\n .settings;\n}\n","import { CapabilityPack, type PackInstallation } from \"@opengeni/contracts\";\nimport {\n getWorkspace,\n getWorkspacePack,\n listInstalledPortableSkills,\n listCapabilityInstallations,\n listPackInstallations,\n type Database,\n} from \"@opengeni/db\";\nimport {\n buildPortableSkillArtifact,\n isSkillLibraryEntryId,\n loadSkillLibrarySkill,\n type EffectiveSkillSelection,\n type PackSkill,\n} from \"@opengeni/runtime\";\nexport {\n resolveRigProviderImageSelection,\n rigProviderImageSourceImage,\n settingsWithPackSandboxImage,\n settingsWithRigImage,\n settingsWithRigProviderImage,\n} from \"./sandbox-images\";\n\n/**\n * Legacy pack-scoped runtime compatibility. V2 Pack installations own ordinary\n * Skill components and select an explicit Rig; they contribute nothing here.\n */\nexport type WorkspacePackRuntime = {\n sandboxImage: string | null;\n sandboxProviderImages: CapabilityPack[\"sandboxProviderImages\"] | null;\n skills: PackSkill[];\n};\n\nconst emptyPackRuntime: WorkspacePackRuntime = {\n sandboxImage: null,\n sandboxProviderImages: null,\n skills: [],\n};\n\nexport type WorkspaceSkillLibraryRuntime = {\n skillLibrarySkills: PackSkill[];\n skillLibrarySelections: EffectiveSkillSelection[];\n};\n\ntype SkillLibraryInstallationMetadata = {\n libraryId: string;\n libraryVersion: string;\n contentSha256: string;\n sourceCommit: string;\n provenance: string;\n};\n\n/**\n * Resolves only pre-V2 active Pack installations. A frozen manifest/digest is\n * the protocol marker for V2: inline Skills were migrated into the ordinary\n * Skill ledger and sandboxImage was resolved to selectedRigId during install,\n * so reading either field directly here would duplicate ownership and silently\n * override session compute.\n */\nexport async function resolveWorkspacePackRuntime(\n db: Database,\n workspaceId: string,\n): Promise<WorkspacePackRuntime> {\n const installations = await listPackInstallations(db, workspaceId);\n const active = installations.filter((installation) => installation.status === \"active\");\n if (active.length === 0) {\n return emptyPackRuntime;\n }\n const packs: CapabilityPack[] = [];\n for (const installation of active) {\n if (!packInstallationUsesLegacyRuntime(installation)) {\n continue;\n }\n const registration = await getWorkspacePack(db, workspaceId, installation.packId);\n if (!registration) {\n continue;\n }\n const parsed = CapabilityPack.safeParse(registration.pack);\n if (parsed.success) {\n packs.push(parsed.data);\n }\n }\n return workspacePackRuntimeFromPacks(packs);\n}\n\nexport function packInstallationUsesLegacyRuntime(\n installation: Pick<PackInstallation, \"manifestSnapshot\" | \"manifestDigest\">,\n): boolean {\n return installation.manifestSnapshot === null && installation.manifestDigest === null;\n}\n\n/**\n * Resolves active immutable curated skills separately from pack skills. The\n * capability installation is the workspace selection boundary; it carries\n * only secret-free exact identity metadata, and the runtime loader verifies\n * the pinned artifact hash before any content is materialized.\n */\nexport async function resolveWorkspaceSkillLibraryRuntime(\n db: Database,\n workspaceId: string,\n): Promise<WorkspaceSkillLibraryRuntime> {\n const installations = await listCapabilityInstallations(db, workspaceId);\n const activeSkills = installations\n .filter(\n (installation) =>\n installation.status === \"active\" &&\n installation.kind === \"skill\" &&\n installation.capabilityId.startsWith(\"skill:\") &&\n isSkillLibraryEntryId(installation.capabilityId.slice(\"skill:\".length)),\n )\n .sort((a, b) => a.capabilityId.localeCompare(b.capabilityId));\n const skillLibrarySkills: PackSkill[] = [];\n const skillLibrarySelections: EffectiveSkillSelection[] = [];\n for (const installation of activeSkills) {\n const metadata = parseSkillLibraryInstallationMetadata(\n installation.metadata,\n installation.capabilityId,\n );\n if (installation.capabilityId !== `skill:${metadata.libraryId}`) {\n throw new Error(\n `Skill installation id does not match its library entry: ${installation.capabilityId} -> ${metadata.libraryId}`,\n );\n }\n const loaded = loadSkillLibrarySkill(metadata.libraryId, metadata.libraryVersion);\n if (installation.config.version !== metadata.libraryVersion) {\n throw new Error(\n `Skill installation version mismatch for ${metadata.libraryId}@${metadata.libraryVersion}: config has ${String(installation.config.version)}`,\n );\n }\n if (loaded.entry.contentSha256 !== metadata.contentSha256) {\n throw new Error(\n `Skill installation hash mismatch for ${metadata.libraryId}@${metadata.libraryVersion}: expected ${metadata.contentSha256}, catalog has ${loaded.entry.contentSha256}`,\n );\n }\n if (\n loaded.entry.sourceCommit !== metadata.sourceCommit ||\n loaded.entry.provenance !== metadata.provenance\n ) {\n throw new Error(\n `Skill installation provenance mismatch for ${metadata.libraryId}@${metadata.libraryVersion}; re-enable the skill from the current catalog`,\n );\n }\n skillLibrarySkills.push({\n name: loaded.skill.name,\n description: loaded.skill.description,\n files: loaded.skill.files.map((file) => ({ path: file.path, content: file.content })),\n });\n skillLibrarySelections.push({\n id: loaded.entry.id,\n name: loaded.entry.name,\n source: \"library\",\n version: loaded.entry.version,\n contentSha256: loaded.entry.contentSha256,\n reason: \"enabled workspace capability installation\",\n });\n }\n const importedSkills = await listInstalledPortableSkills(db, workspaceId);\n for (const imported of importedSkills) {\n const artifact = buildPortableSkillArtifact(imported.files);\n if (\n artifact.name !== imported.name ||\n artifact.description !== imported.description ||\n artifact.contentSha256 !== imported.contentSha256\n ) {\n throw new Error(\n `Imported Skill artifact verification failed for ${imported.capabilityId}; reinstall it from the pinned source`,\n );\n }\n skillLibrarySkills.push({\n name: artifact.name,\n description: artifact.description,\n files: artifact.files.map((file) => ({ path: file.path, content: file.content })),\n });\n skillLibrarySelections.push({\n id: imported.capabilityId,\n name: artifact.name,\n source: \"imported\",\n version: imported.sourceCommit,\n contentSha256: artifact.contentSha256,\n reason: `installed from ${imported.sourceUrl}`,\n });\n }\n return { skillLibrarySkills, skillLibrarySelections };\n}\n\nfunction parseSkillLibraryInstallationMetadata(\n metadata: Record<string, unknown>,\n capabilityId: string,\n): SkillLibraryInstallationMetadata {\n const libraryId = stringMetadata(metadata.libraryId);\n const libraryVersion = stringMetadata(metadata.libraryVersion);\n const contentSha256 = stringMetadata(metadata.contentSha256);\n const sourceCommit = stringMetadata(metadata.sourceCommit);\n const provenance = stringMetadata(metadata.provenance);\n if (!libraryId || !libraryVersion || !contentSha256 || !sourceCommit || !provenance) {\n throw new Error(\n `Skill installation ${capabilityId} is missing immutable library metadata; re-enable the skill from the current catalog`,\n );\n }\n return { libraryId, libraryVersion, contentSha256, sourceCommit, provenance };\n}\n\nfunction stringMetadata(value: unknown): string | null {\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : null;\n}\n\n/**\n * Pure pre-V2 compatibility rule for enabled Pack manifests. At most one\n * legacy Pack may declare a sandbox image, and legacy Skill names must be\n * unique. V2 rows never reach this function through runtime resolution.\n */\nexport function workspacePackRuntimeFromPacks(packs: CapabilityPack[]): WorkspacePackRuntime {\n const imagePacks = packs.filter(\n (pack) => typeof pack.sandboxImage === \"string\" && pack.sandboxImage.trim().length > 0,\n );\n if (imagePacks.length > 1) {\n const ids = imagePacks\n .map((pack) => pack.id)\n .sort()\n .join(\", \");\n throw new Error(\n `Multiple enabled packs declare a sandbox image (${ids}). Only one enabled pack per workspace may declare sandboxImage; disable the others and retry.`,\n );\n }\n const skills: PackSkill[] = [];\n // Keyed case-insensitively to match the per-pack uniqueness rule in the\n // CapabilityPack contract (and case-insensitive filesystems).\n const skillOwners = new Map<string, string>();\n for (const pack of [...packs].sort((a, b) => a.id.localeCompare(b.id))) {\n for (const skill of pack.skills) {\n const key = skill.name.toLowerCase();\n const existingOwner = skillOwners.get(key);\n if (existingOwner !== undefined && existingOwner !== pack.id) {\n throw new Error(\n `Enabled packs ${existingOwner} and ${pack.id} both declare a skill named \"${skill.name}\". Pack skill names must be unique across enabled packs; disable one of the packs and retry.`,\n );\n }\n skillOwners.set(key, pack.id);\n skills.push({\n name: skill.name,\n description: skill.description ?? null,\n files: skill.files.map((file) => ({ path: file.path, content: file.content })),\n });\n }\n }\n return {\n sandboxImage: imagePacks[0]?.sandboxImage?.trim() ?? null,\n sandboxProviderImages: imagePacks[0]?.sandboxProviderImages ?? null,\n skills,\n };\n}\n\n/**\n * Resolves the per-workspace agent persona override (the white-label surface).\n * Returns the workspace's stored template when set, else null to mean \"use the\n * deployment default\" (settings.agentInstructionsTemplate). The runtime always\n * injects the non-bypassable CORE regardless, so a null here keeps the\n * byte-identical default and a non-null value only restyles the persona.\n *\n * This is the workspace tier of the session > workspace > deployment-default\n * resolution; per-session overrides do not exist in this slice, so the worker\n * resolves workspace > default and passes the result as instructionsTemplate.\n */\nexport async function resolveWorkspaceAgentInstructions(\n db: Database,\n workspaceId: string,\n): Promise<string | null> {\n const workspace = await getWorkspace(db, workspaceId);\n return workspace?.agentInstructions ?? null;\n}\n\n/**\n * Applies a pack-declared sandbox image to run settings. With no pack image\n * the settings pass through untouched, so deployments without packs keep the\n * global OPENGENI_DOCKER_IMAGE / OPENGENI_MODAL_IMAGE_REF behavior exactly.\n */\n/**\n * Layers the rig version's default variable sets BELOW the session's own set:\n * the session's values WIN on any key collision (explicit precedence). Both maps\n * are already the decrypted-and-merged values (rig defaults merged in listed\n * order upstream). Pure and deterministic — given the same inputs it returns the\n * same env, which is what keeps a session's box-manifest env stable across turns\n * (the rig version is frozen per session, so its default-set list is fixed).\n */\nexport function mergeRigDefaultVariableSetEnvironment(\n rigDefaultValues: Record<string, string>,\n sessionValues: Record<string, string>,\n): Record<string, string> {\n return { ...rigDefaultValues, ...sessionValues };\n}\n","import type { SessionEventType } from \"@opengeni/contracts\";\nimport { TURN_ACTIVITY_CANCELLATION_HEARTBEAT_INTERVAL_MS } from \"@opengeni/core\";\nimport type { AppendEventInput } from \"@opengeni/db\";\nimport { Context } from \"@temporalio/activity\";\n\n// Trailing-flush window. A burst of coalesced deltas followed by model silence\n// must not sit in `pending` unbounded — without a timer, flush fires only on\n// the NEXT push. Matched to the 33ms coalesce window so the client-visible\n// latency added by batching is bounded to ~one window (imperceptible, and far\n// cheaper than the per-delta DB round-trip it replaces).\nconst TRAILING_FLUSH_MS = 33;\nconst MAX_BATCH_EVENTS = 50;\n// Keep model ingestion independent from a slow durable append, but never let a\n// provider outrun storage without bound. At the high-water mark `push` waits for\n// the serialized drain before consuming more provider output.\nconst MAX_BUFFERED_EVENTS = 1_000;\n\n/** Optional metrics seam for the batcher. `onFlush` fires once per flush (on both\n * success and failure) with the coalesced event count and the flush duration, so\n * the worker can meter batch shape without the batcher knowing about Observability.\n * `now` is injectable for deterministic tests. Both are optional; absent ⇒ no-op. */\nexport type RuntimeBatcherOptions = {\n onFlush?: (info: { events: number; durationSeconds: number }) => void;\n now?: () => number;\n};\n\nexport function createRuntimeBatcher(\n flushEvents: (events: AppendEventInput[]) => Promise<void>,\n options: RuntimeBatcherOptions = {},\n) {\n const now = options.now ?? (() => performance.now());\n let pending: AppendEventInput[] = [];\n let lastFlush = Date.now();\n let trailingTimer: ReturnType<typeof setTimeout> | null = null;\n let activeBatchSize = 0;\n // One drain loop owns `flushEvents`, so DB-assigned sequence order always\n // matches push order. Ordinary deltas do not await this promise; structural\n // boundaries, explicit flushes, and the bounded high-water mark do.\n let drainPromise: Promise<void> | null = null;\n // A timer has no direct awaiter. Retain its failure so the next push or final\n // flush terminates the turn instead of silently losing streamed evidence.\n let flushFailed = false;\n let flushFailure: unknown;\n // The high-volume token deltas (agent.message.delta, agent.reasoning.delta,\n // sandbox.command.output.delta) are DELIBERATELY NOT here: they coalesce\n // under the 50-event / 33ms policy into one appendSessionEvents txn + one\n // publish per flush, instead of one DB round-trip per token. Only events that\n // must be delivered promptly stay structural (flush-immediately). PTY bytes\n // stay structural on purpose — an interactive terminal is useless batched\n // 33ms behind (P4.4).\n const structural = new Set<SessionEventType>([\n \"terminal.pty.output.delta\",\n \"agent.toolCall.created\",\n \"agent.toolCall.output\",\n \"agent.message.completed\",\n \"tool.auth_needed\",\n \"credential.auth_needed\",\n \"session.requiresAction\",\n \"turn.completed\",\n \"turn.failed\",\n \"turn.cancelled\",\n ]);\n return {\n push: async (event: { type: SessionEventType; payload: unknown }) => {\n throwIfFlushFailed();\n // Append BEFORE the structural check so a structural event's flush always\n // carries any pending deltas in order (same flush, order preserved).\n pending.push({ type: event.type, payload: event.payload });\n const elapsed = Date.now() - lastFlush;\n if (structural.has(event.type)) {\n await flush();\n return;\n }\n if (pending.length >= MAX_BATCH_EVENTS || elapsed >= TRAILING_FLUSH_MS) {\n // Start the serialized drain, but keep consuming provider deltas while\n // the append/publish round-trip is in flight. The active drain records\n // any failure for the next awaited boundary.\n void startDrain().catch(() => undefined);\n }\n if (activeBatchSize + pending.length >= MAX_BUFFERED_EVENTS) {\n await flush();\n return;\n }\n armTrailingTimer();\n },\n flush,\n };\n\n function armTrailingTimer() {\n if (trailingTimer !== null) {\n return;\n }\n trailingTimer = setTimeout(() => {\n trailingTimer = null;\n // A timer has no awaiter, so prevent an unhandled rejection. startDrain\n // retains the exact error and the next push/final flush rethrows it.\n void flush().catch(() => undefined);\n }, TRAILING_FLUSH_MS);\n if (\"unref\" in trailingTimer && typeof trailingTimer.unref === \"function\") {\n trailingTimer.unref();\n }\n }\n\n function clearTrailingTimer() {\n if (trailingTimer !== null) {\n clearTimeout(trailingTimer);\n trailingTimer = null;\n }\n }\n\n async function flush(): Promise<void> {\n throwIfFlushFailed();\n clearTrailingTimer();\n await startDrain();\n throwIfFlushFailed();\n }\n\n function startDrain(): Promise<void> {\n if (drainPromise) {\n return drainPromise;\n }\n if (flushFailed) {\n return Promise.reject(flushFailure);\n }\n if (pending.length === 0) {\n return Promise.resolve();\n }\n clearTrailingTimer();\n const running = (async () => {\n while (pending.length > 0) {\n const events = pending.splice(0, MAX_BATCH_EVENTS);\n activeBatchSize = events.length;\n lastFlush = Date.now();\n const startedAt = now();\n try {\n await flushEvents(events);\n } catch (error) {\n flushFailed = true;\n flushFailure = error;\n throw error;\n } finally {\n activeBatchSize = 0;\n if (options.onFlush) {\n try {\n options.onFlush({\n events: events.length,\n durationSeconds: Math.max(0, (now() - startedAt) / 1000),\n });\n } catch {\n // Metrics emission must never affect a flush.\n }\n }\n }\n }\n })();\n drainPromise = running.finally(() => {\n drainPromise = null;\n });\n return drainPromise;\n }\n\n function throwIfFlushFailed(): void {\n if (flushFailed) {\n throw flushFailure;\n }\n }\n}\n\nexport function currentActivityContext(): Context | null {\n try {\n return Context.current();\n } catch {\n return null;\n }\n}\n\nexport function startActivityHeartbeat(\n context: Context | null,\n details: Record<string, unknown>,\n schedule: typeof setInterval = setInterval,\n): ReturnType<typeof setInterval> | null {\n if (!context) {\n return null;\n }\n const timer = schedule(() => {\n context.heartbeat({ ...details, at: new Date().toISOString() });\n }, TURN_ACTIVITY_CANCELLATION_HEARTBEAT_INTERVAL_MS);\n if (\"unref\" in timer && typeof timer.unref === \"function\") {\n timer.unref();\n }\n return timer;\n}\n\nexport async function nextStreamEvent<T>(\n iterator: AsyncIterator<T>,\n context: Context | null,\n): Promise<IteratorResult<T>> {\n if (!context) {\n return await iterator.next();\n }\n const signal = context.cancellationSignal;\n if (signal.aborted) {\n throw signal.reason;\n }\n\n // Context.cancelled never settles for a normally completed activity. Racing\n // every token/event read against that lifetime promise leaves one losing\n // Promise reaction attached for every event until the Context itself dies.\n // Use the equivalent Temporal AbortSignal and remove each listener as soon as\n // the iterator wins, so a long stream retains at most its one pending read.\n return await new Promise<IteratorResult<T>>((resolve, reject) => {\n let settled = false;\n const settle = (complete: () => void) => {\n if (settled) return;\n settled = true;\n signal.removeEventListener(\"abort\", onAbort);\n complete();\n };\n const onAbort = () => settle(() => reject(signal.reason));\n\n signal.addEventListener(\"abort\", onAbort, { once: true });\n if (signal.aborted) {\n onAbort();\n return;\n }\n\n let next: PromiseLike<IteratorResult<T>>;\n try {\n next = iterator.next();\n } catch (error) {\n settle(() => reject(error));\n return;\n }\n void Promise.resolve(next).then(\n (result) => settle(() => resolve(result)),\n (error) => settle(() => reject(error)),\n );\n });\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { Session, SessionGoal, SessionSystemUpdatePayload } from \"@opengeni/contracts\";\nimport {\n getSession,\n getSessionGoal,\n getSessionParentPersonalConnectionDelegations,\n addSessionSystemUpdateWithSourceMutation,\n claimPendingSessionSystemUpdateOutbox,\n claimPendingSessionWorkflowWakes,\n getSessionSystemUpdateOutboxByDedupeKey,\n getOrCreateSessionSystemUpdateOutbox,\n markSessionWorkflowWakeFailed,\n markSessionSystemUpdateOutboxDeliveredInTransaction,\n markSessionSystemUpdateOutboxFailed,\n type Database,\n type SessionSystemUpdateOutboxDelivery,\n} from \"@opengeni/db\";\nimport type { EventBus } from \"@opengeni/events\";\nimport type { ActivityServices, WakeSessionWorkflowSignal } from \"./types\";\n\nexport type NotifyServices = {\n db: Database;\n bus: EventBus;\n settings: Settings;\n observability: ActivityServices[\"observability\"];\n wakeSessionWorkflow: WakeSessionWorkflowSignal | null;\n};\n\nexport type ReconcileParentSystemUpdateOverrides = Partial<{\n claimPendingSessionSystemUpdateOutbox: typeof claimPendingSessionSystemUpdateOutbox;\n}>;\n\nexport type ReconcileSessionWorkflowWakeOverrides = Partial<{\n claimPendingSessionWorkflowWakes: typeof claimPendingSessionWorkflowWakes;\n}>;\n\n/**\n * Enrich and deliver the durable idle-boundary row committed by\n * settleSessionIdleWithParentOutbox. Idle has no single owning turn, so its\n * stable episode identity is the newest non-status event sequence.\n */\nexport async function notifyParentOfChildIdle(\n svc: NotifyServices,\n workspaceId: string,\n childSessionId: string,\n episodeKey: string,\n): Promise<void> {\n try {\n const child = await getSession(svc.db, workspaceId, childSessionId);\n if (!child || !child.parentSessionId) {\n return;\n }\n const goal = await getSessionGoal(svc.db, workspaceId, childSessionId);\n // Sacred user pause: if the MANAGER's own goal was paused by the user, the\n // wake must not tell it to \"resume it now\" — that instruction is exactly\n // what re-arms the loop the user just stopped. Suppress the resume nudge and\n // tell the agent to stay paused. Paired with the goal_set reactivation\n // guard so a nudge that slips through still cannot revive the goal.\n const clientEventId = `child-completion:${childSessionId}:${episodeKey}`;\n const payload = childCompletionPayload(child, goal);\n const personalConnectionDelegations = await getSessionParentPersonalConnectionDelegations(\n svc.db,\n workspaceId,\n childSessionId,\n );\n const outbox = await getOrCreateSessionSystemUpdateOutbox(svc.db, {\n accountId: child.accountId,\n workspaceId,\n sourceSessionId: child.id,\n targetSessionId: child.parentSessionId,\n kind: \"child_terminal_result\",\n classification: goal?.status === \"paused\" ? \"action_required\" : \"success\",\n sourceId: child.id,\n dedupeKey: clientEventId,\n summary: childCompletionSummary(child, goal, \"idle\"),\n payload,\n lineage: { childSessionId: child.id, parentSessionId: child.parentSessionId },\n personalConnectionDelegations,\n });\n if (outbox.status === \"delivered\") {\n return;\n }\n await deliverParentSystemUpdateOutbox(svc, outbox);\n } catch (error) {\n // A durable pending outbox row survives this boundary. The global worker\n // reaper retries it; child terminal settlement never depends on this turn.\n svc.observability.error(\"Failed to wake parent session on worker idle boundary\", {\n childSessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Deliver the exact failure row already committed by turn settlement. This\n * layer deliberately cannot create or rewrite the row: the settlement\n * transaction is the sole owner of the failed turn id, payload, and lineage.\n */\nexport async function deliverFailedChildTurnToParent(\n svc: NotifyServices,\n workspaceId: string,\n childSessionId: string,\n turnId: string,\n): Promise<void> {\n try {\n const child = await getSession(svc.db, workspaceId, childSessionId);\n if (!child || !child.parentSessionId) return;\n const dedupeKey = `child-completion:${childSessionId}:turn:${turnId}`;\n const outbox = await getSessionSystemUpdateOutboxByDedupeKey(svc.db, {\n accountId: child.accountId,\n workspaceId,\n dedupeKey,\n });\n if (!outbox) {\n throw new Error(`Committed failed-child outbox disappeared: ${dedupeKey}`);\n }\n if (outbox.status === \"delivered\") return;\n await deliverParentSystemUpdateOutbox(svc, outbox);\n } catch (error) {\n // Settlement already committed the retryable outbox row. The global\n // reconciler remains the recovery path if immediate delivery fails.\n svc.observability.error(\"Failed to deliver committed child-turn failure\", {\n childSessionId,\n turnId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nasync function deliverParentSystemUpdateOutbox(\n svc: NotifyServices,\n outbox: SessionSystemUpdateOutboxDelivery,\n): Promise<void> {\n try {\n const result = await addSessionSystemUpdateWithSourceMutation(\n svc.db,\n {\n accountId: outbox.accountId,\n workspaceId: outbox.workspaceId,\n sessionId: outbox.targetSessionId,\n kind: outbox.kind,\n classification: outbox.classification,\n sourceId: outbox.sourceId,\n dedupeKey: outbox.dedupeKey,\n summary: outbox.summary,\n payload: outbox.payload,\n lineage: outbox.lineage,\n personalConnectionDelegations: outbox.personalConnectionDelegations,\n },\n async (tx) => {\n await markSessionSystemUpdateOutboxDeliveredInTransaction(tx, outbox);\n },\n );\n if (result.reason === \"session_cancelled\") {\n return;\n }\n if (result.added && result.events.length > 0) {\n await svc.bus.publish(outbox.workspaceId, outbox.targetSessionId, result.events);\n }\n if (result.shouldWake && svc.wakeSessionWorkflow) {\n if (result.workflowWakeRevision === null) {\n throw new Error(\"Runnable system update has no workflow wake revision\");\n }\n await svc.wakeSessionWorkflow({\n accountId: outbox.accountId,\n workspaceId: outbox.workspaceId,\n sessionId: outbox.targetSessionId,\n workflowId: result.temporalWorkflowId ?? `session-${outbox.targetSessionId}`,\n wakeRevision: result.workflowWakeRevision,\n });\n }\n svc.observability.info(\"Woke parent session on worker completion\", {\n childSessionId: outbox.sourceSessionId,\n parentSessionId: outbox.targetSessionId,\n dedupeKey: outbox.dedupeKey,\n });\n } catch (error) {\n await markSessionSystemUpdateOutboxFailed(\n svc.db,\n outbox,\n error instanceof Error ? error.message : String(error),\n ).catch(() => undefined);\n throw error;\n }\n}\n\nexport async function reconcilePendingParentSystemUpdates(\n svc: NotifyServices,\n limit = 100,\n overrides: ReconcileParentSystemUpdateOverrides = {},\n): Promise<{ claimed: number; delivered: number; failed: number }> {\n const claimPendingSessionSystemUpdateOutboxFn =\n overrides.claimPendingSessionSystemUpdateOutbox ?? claimPendingSessionSystemUpdateOutbox;\n const rows = await claimPendingSessionSystemUpdateOutboxFn(svc.db, limit);\n let delivered = 0;\n let failed = 0;\n for (const row of rows) {\n try {\n await deliverParentSystemUpdateOutbox(svc, row);\n delivered += 1;\n } catch {\n failed += 1;\n }\n }\n return { claimed: rows.length, delivered, failed };\n}\n\nexport async function reconcilePendingSessionWorkflowWakes(\n svc: NotifyServices,\n limit = 1_000,\n overrides: ReconcileSessionWorkflowWakeOverrides = {},\n): Promise<{ claimed: number; delivered: number; failed: number }> {\n const claimPendingSessionWorkflowWakesFn =\n overrides.claimPendingSessionWorkflowWakes ?? claimPendingSessionWorkflowWakes;\n if (!svc.wakeSessionWorkflow) {\n return { claimed: 0, delivered: 0, failed: 0 };\n }\n const repairs = await claimPendingSessionWorkflowWakesFn(svc.db, limit);\n let delivered = 0;\n let failed = 0;\n const queue = [...repairs];\n const workers = Array.from({ length: Math.min(20, queue.length) }, async () => {\n for (;;) {\n const repair = queue.shift();\n if (!repair) return;\n try {\n await svc.wakeSessionWorkflow!({\n accountId: repair.accountId,\n workspaceId: repair.workspaceId,\n sessionId: repair.sessionId,\n workflowId: repair.temporalWorkflowId,\n wakeRevision: repair.wakeRevision,\n ...(repair.interruptionRequested ? { interruptionRequested: true } : {}),\n });\n delivered += 1;\n } catch (error) {\n failed += 1;\n await markSessionWorkflowWakeFailed(\n svc.db,\n repair,\n error instanceof Error ? error.message : String(error),\n ).catch(() => undefined);\n }\n }\n });\n await Promise.all(workers);\n return { claimed: repairs.length, delivered, failed };\n}\n\nfunction childCompletionPayload(\n child: Session,\n goal: SessionGoal | null,\n): Extract<SessionSystemUpdatePayload, { type: \"child_terminal_result\" }> {\n return {\n type: \"child_terminal_result\",\n childSessionId: child.id,\n status: \"idle\",\n ...(goal\n ? {\n goal: {\n status: goal.status,\n text: goal.text,\n ...(goal.evidence ? { evidence: goal.evidence } : {}),\n ...(goal.rationale ? { rationale: goal.rationale } : {}),\n ...(goal.pausedReason ? { pausedReason: goal.pausedReason } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * The worker-specific lines for one child (what happened + its goal), WITHOUT\n * the trailing \"what to do next\" instruction. Kept separate so N child\n * completions can be coalesced into one internal-update inference: the DB layer\n * stores each child's summary and rebuilds a single numbered digest with one\n * shared trailing instruction instead of running N model calls.\n */\nexport function childCompletionSummary(\n child: Session,\n goal: SessionGoal | null,\n terminalStatus: \"idle\" | \"failed\",\n): string {\n const lines: string[] = [];\n if (terminalStatus === \"failed\") {\n lines.push(`A worker session you spawned has FAILED. Worker session id: ${child.id}.`);\n } else if (goal?.status === \"completed\") {\n lines.push(\n `A worker session you spawned has COMPLETED its goal. Worker session id: ${child.id}.`,\n );\n } else if (goal?.status === \"paused\") {\n lines.push(\n `A worker session you spawned has PAUSED its goal and gone idle. Worker session id: ${child.id}.`,\n );\n } else {\n lines.push(\n `A worker session you spawned has finished its work and gone idle. Worker session id: ${child.id}.`,\n );\n }\n if (goal) {\n lines.push(`Worker goal: ${goal.text}`);\n if (goal.status === \"completed\" && goal.evidence) {\n lines.push(`Completion evidence: ${goal.evidence}`);\n }\n if (goal.status === \"paused\" && goal.rationale) {\n lines.push(`Pause rationale: ${goal.rationale}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * The single trailing instruction appended to a child-completion (or digest)\n * inference. Suppresses the \"resume it now\" nudge when the manager's own goal\n * was paused by the user (paired with the goal_set reactivation guard).\n */\nexport function childCompletionTrailing(parentGoalUserPaused: boolean): string {\n return parentGoalUserPaused\n ? \"Read each worker's session events/notebook output for its result. This session was paused by the user — do NOT resume or replace your goal; summarize the result for the user and remain paused.\"\n : \"Read each worker's session events/notebook output for its result, then continue. If your own goal was paused awaiting these workers, resume it now.\";\n}\n","// apps/worker/src/sandbox-resume.ts — the stateless per-turn resume-by-id path.\n//\n// This is the turn-side half of the P1.2 ownership inversion. There is NO class,\n// NO timers, NO per-session owner, NO Map<id, owner> — every turn is a\n// self-contained critical section run by ANY pool worker:\n//\n// 1. acquireLease (group-keyed) under the DB FOR UPDATE + cold->warming CAS —\n// the SOLE double-spawn guard (P1.1).\n// 2. The cold->warming winner may create/restore. Every attached caller is\n// resume-only; a missing provider box retires the exact warm epoch and\n// re-enters admission instead of creating a rival.\n// 3. (spawner) commitWarmingToWarm (the lease_epoch++ fence + folds the resume\n// envelope onto the lease). Optional desktop work is deliberately absent:\n// the viewer and the first actual computer-use action initialize :0 lazily.\n// 4. the caller injects {client, session, sessionState} NON-OWNED into the run\n// (the SDK never reaps it — the keystone), runs, then in `finally` calls the\n// returned `release()` and drops the in-memory handle. NEVER provider-delete\n// — the box rides the provider idle-timeout; the reaper (P1.3) stop()s it at\n// refcount 0.\n//\n// Liveness between turns is the lease refcount; there is no keepalive loop.\n\nimport {\n sandboxArchiveCaptureTimeoutMs,\n sandboxLifecycleTransitionWaitMs,\n type Settings,\n} from \"@opengeni/config\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n acquireLease,\n adoptLegacyModalCheckpointArtifact,\n beginSandboxRematerialization,\n claimWorkspaceArchiveCapture,\n commitWarmingToWarm,\n failSandboxRematerialization,\n failWarmingToCold,\n getSandboxSessionEnvelope,\n heartbeatLeaseHolder,\n markSandboxRestoreVerifying,\n markWarmLeaseInstanceLost,\n markSandboxCheckpointArtifactDeletePending,\n persistWarmSnapshot,\n readLease,\n registerSandboxCheckpointArtifact,\n recordWarmingSandboxCreated,\n releaseWorkspaceArchiveCapture,\n releaseLeaseHolder,\n touchLeaseHolder,\n SandboxLeaseRecoveryBlockedError,\n SandboxLeaseSupersededError,\n SandboxLeaseTransitionError,\n type Database,\n type LeaseHolderKind,\n} from \"@opengeni/db\";\nimport {\n captureVerifiedWorkspaceArchive,\n describeLegacyNativeSnapshotArchive,\n MODAL_EXEC_READINESS_TIMEOUT_MS,\n SandboxExecReadinessError,\n WorkspaceArchiveIntegrityError,\n establishSandboxSessionFromEnvelope,\n isProviderSandboxNotFoundError,\n parseWorkspaceArchiveDescriptor,\n providerWorkspaceCapturePolicy,\n SandboxProviderContinuityUnavailableError,\n requirePersistableReplacementSandboxEnvelope,\n modalSessionMatchesCheckpointProviderBinding,\n resolveModalCheckpointProviderBindingForSession,\n serializeReplacementSandboxEnvelope,\n tagModalSandbox,\n terminateUnpublishedSandboxSession,\n verifySandboxExecReadiness,\n withoutSandboxProviderIdentity,\n type EstablishedSandboxSession,\n type RuntimeMetricsHooks,\n type WorkspaceArchiveDescriptor,\n} from \"@opengeni/runtime\";\n\n// Re-exported for callers that just want the ack-kind union.\nexport type ResumeHolderKind = LeaseHolderKind;\n\n/**\n * The durable identity of a turn holding a shared sandbox lease.\n *\n * Temporal activity ids cannot satisfy this type: they are workflow-local\n * sequence numbers and collide across sessions that share a sandbox group.\n */\nexport type TurnSandboxLeaseHolderId = `turn-attempt:${string}`;\n\nexport function sandboxLeaseHolderIdForAttempt(attemptId: string): TurnSandboxLeaseHolderId {\n const normalized = attemptId.trim();\n if (!normalized) {\n throw new Error(\"Sandbox lease holder requires a turn attempt id\");\n }\n return `turn-attempt:${normalized}`;\n}\n\nexport function isRetryableDegradedRestore(restore: {\n status: string;\n retryable?: boolean;\n}): boolean {\n return restore.status === \"degraded\" && restore.retryable === true;\n}\n\n/** The minimal services surface resumeBoxForTurn needs. A subset of\n * ActivityServices so a test (and the API later) can pass a lean bag. */\nexport type SandboxResumeServices = {\n db: Database;\n settings: Settings;\n /** Exact settings before a verified rig provider image overlaid the logical\n * pack/deployment image. Fresh-create NotFound fallback must preserve an\n * ID-only logical base instead of selecting the provider default. */\n logicalFallbackSettings?: Settings;\n sandboxMetrics?: RuntimeMetricsHooks;\n /**\n * The logical turn-attempt lifetime, not merely the provider request lifetime.\n * Some provider SDK calls cannot be interrupted. Aborting this signal still\n * releases the durable holder immediately and fences any late provider result.\n */\n cancellationSignal?: AbortSignal;\n /** Test seam for the attached/resumed path. Production uses the one runtime\n * resume primitive; callers must not use this to create a replacement box. */\n establishAttachedSandbox?: typeof establishSandboxSessionFromEnvelope;\n /** Test seam for the bounded command-readiness proof performed before an\n * attached provider box is handed to the agent. */\n verifyAttachedSandboxReadiness?: (established: EstablishedSandboxSession) => Promise<void>;\n /** Called only by the observer that wins the exact warm->cold loss CAS. */\n onSandboxLost?: (input: {\n sandboxGroupId: string;\n instanceId: string;\n leaseEpoch: number;\n }) => Promise<void>;\n};\n\nexport type ResumeBoxIds = {\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n /** The attributing session within the group (holders carry session_id for\n * disclosure/attribution). For a singleton group this == sandboxGroupId. */\n sessionId: string;\n /** The backend the box runs on (sessions.sandbox_backend). */\n backend: string;\n /** The OS axis (sessions.sandbox_os); default 'linux'. */\n os?: string;\n /**\n * The FULL environment the agent will declare for this run (the SAME object\n * passed to runtime.buildAgent's `sandboxEnvironment`). The box's manifest is\n * created with this environment so that when the SDK applies the agent's\n * manifest to this NON-OWNED provided session, the environments match exactly\n * and `validateNoEnvironmentDelta` finds an empty delta (otherwise it throws\n * \"Live sandbox sessions cannot change manifest environment variables\" and the\n * turn dies). Omitted → the leaf falls back to collectSandboxEnvironment(settings)\n * (the legacy default; only the resume/spawn-without-an-agent callers rely on it).\n */\n environment?: Record<string, string>;\n /**\n * IMAGE IS SHARED STATE (B3): the container image this run resolves (Modal image ref\n * / docker image). Threaded to acquireLease, which stamps it on the cold-create and\n * conflicts on a live box already running a DIFFERENT image (a solo holder requests\n * capture-and-drain rotation; N-holders throw SandboxImageConflictError). Omitted ->\n * image is not enforced (the selfhosted path never passes it; a legacy/null-image box\n * never conflicts).\n */\n image?: string;\n /**\n * RIG IS SHARED STATE (M3): the frozen rig version this run rides. Threaded to\n * acquireLease, which stamps it on the cold-create and conflicts on a live box\n * set up under a DIFFERENT rig version (a solo holder requests capture-and-drain\n * rotation; N-holders throw SandboxRigConflictError). Omitted for a rig-less\n * session -> rig is never stamped or enforced (shares exactly as today).\n */\n rigVersionId?: string;\n};\n\n/** What resumeBoxForTurn returns: the live NON-OWNED session to inject, the\n * fence token (lease_epoch) it was established under, and a release function\n * the caller invokes in `finally` (idempotent delete-my-holder-row). */\nexport type ResumedTurnSandbox = {\n /** The live, externally-owned session — inject {client, session, sessionState}\n * NON-OWNED into runStream's `ownedSandbox`; the SDK never reaps it. */\n established: EstablishedSandboxSession;\n /** The lease_epoch this turn holds; the heartbeat/fence token. */\n leaseEpoch: number;\n /** Staged idempotent release. The ordinary form immediately prevents a\n * holder/timer leak. The quiesced form may be called later—even after the\n * ordinary form—to repair null-outcome admissions only after every exact\n * attempt-owned workspace writer has physically drained. NEVER stops the box. */\n release: (options?: { workspaceWritersQuiesced?: boolean }) => Promise<void>;\n};\n\nexport abstract class SandboxWarmingTimeoutError extends Error {\n abstract readonly code: \"sandbox_exec_readiness_timeout\" | \"sandbox_sibling_warming_timeout\";\n\n protected constructor(\n public readonly backend: string,\n public readonly timeoutMs: number,\n public readonly stage: \"exec_readiness\" | \"sibling_warming\",\n public readonly sandboxGroupId: string | null,\n public readonly instanceId: string | null,\n ) {\n const timeoutSeconds = Math.ceil(timeoutMs / 1000);\n const identity = [\n sandboxGroupId ? `group ${sandboxGroupId}` : null,\n instanceId ? `sandbox ${instanceId}` : null,\n ]\n .filter((part): part is string => part !== null)\n .join(\", \");\n const target = identity ? ` (${identity})` : \"\";\n super(\n stage === \"exec_readiness\"\n ? `Sandbox backend \"${backend}\"${target} did not become command-ready within ${timeoutSeconds}s after creation or restore.`\n : `Sandbox backend \"${backend}\"${target} did not finish warming within ${timeoutSeconds}s while waiting for the elected sandbox creator.`,\n );\n this.name = \"SandboxWarmingTimeoutError\";\n }\n}\n\nexport class SandboxExecReadinessTimeoutError extends SandboxWarmingTimeoutError {\n readonly code = \"sandbox_exec_readiness_timeout\" as const;\n\n constructor(\n backend: string,\n timeoutMs: number,\n identity: { sandboxGroupId?: string | null; instanceId?: string | null } = {},\n ) {\n super(\n backend,\n timeoutMs,\n \"exec_readiness\",\n identity.sandboxGroupId ?? null,\n identity.instanceId ?? null,\n );\n this.name = \"SandboxExecReadinessTimeoutError\";\n }\n}\n\nexport class SandboxSiblingWarmingTimeoutError extends SandboxWarmingTimeoutError {\n readonly code = \"sandbox_sibling_warming_timeout\" as const;\n\n constructor(\n backend: string,\n timeoutMs: number,\n identity: { sandboxGroupId: string; instanceId?: string | null },\n ) {\n super(\n backend,\n timeoutMs,\n \"sibling_warming\",\n identity.sandboxGroupId,\n identity.instanceId ?? null,\n );\n this.name = \"SandboxSiblingWarmingTimeoutError\";\n }\n}\n\n/** The exact attached caller that won warm->cold after proving the provider\n * instance gone. It is a lease supersession (the same logical turn recovers),\n * plus the lost id needed for one durable observability event. */\nexport class SandboxLeaseInstanceLostError extends SandboxLeaseSupersededError {\n constructor(\n sandboxGroupId: string,\n leaseEpoch: number,\n public readonly lostInstanceId: string,\n ) {\n super(sandboxGroupId, leaseEpoch);\n this.name = \"SandboxLeaseInstanceLostError\";\n }\n}\n\n// Bounded poll while a sibling spawner is mid cold-restore. The wait budget is\n// user-facing and separate from the lease TTL heartbeat/reaper horizon.\nconst WARMING_POLL_INTERVAL_MS = 250;\n\nasync function sleep(ms: number): Promise<void> {\n await new Promise<void>((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Modal may return a sandbox handle before its command router accepts the first\n * exec. The upstream session's yieldTimeMs starts only after sandbox.exec()\n * returns, so it cannot bound that initial RPC. Probe it before publishing the\n * lease as warm and enforce our own wall-clock deadline.\n */\nexport async function waitForSandboxExecReadiness(\n established: EstablishedSandboxSession,\n timeoutMs = MODAL_EXEC_READINESS_TIMEOUT_MS,\n identity: { sandboxGroupId?: string | null } = {},\n): Promise<void> {\n try {\n await verifySandboxExecReadiness(established, timeoutMs);\n } catch (error) {\n if (error instanceof SandboxExecReadinessError && error.code === \"exec_probe_timeout\") {\n throw new SandboxExecReadinessTimeoutError(established.backendId, timeoutMs, {\n sandboxGroupId: identity.sandboxGroupId ?? null,\n instanceId: established.instanceId,\n });\n }\n throw error;\n }\n}\n\nclass SnapshotTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`workspace snapshot timed out after ${timeoutMs}ms`);\n this.name = \"SnapshotTimeoutError\";\n }\n}\n\nexport function safeSnapshotError(error: unknown): {\n errorClass: \"SnapshotOperationError\";\n errorCode: \"snapshot_operation_failed\";\n status?: number;\n origin: \"sandbox-resume\";\n} {\n const fields: {\n errorClass: \"SnapshotOperationError\";\n errorCode: \"snapshot_operation_failed\";\n status?: number;\n origin: \"sandbox-resume\";\n } = {\n errorClass: \"SnapshotOperationError\",\n errorCode: \"snapshot_operation_failed\",\n origin: \"sandbox-resume\",\n };\n try {\n const rawStatus =\n error && typeof error === \"object\"\n ? ((error as { status?: unknown; statusCode?: unknown }).status ??\n (error as { statusCode?: unknown }).statusCode)\n : undefined;\n const status = Number(rawStatus);\n if (Number.isInteger(status) && status >= 100 && status <= 599) fields.status = status;\n } catch {\n // Public diagnostics are best-effort and must never replace the exact\n // internal snapshot failure.\n }\n return fields;\n}\n\nexport async function waitForWarmSnapshot(\n snapshot: Promise<unknown>,\n timeoutMs: number,\n signal?: AbortSignal,\n): Promise<boolean> {\n if (signal?.aborted) return false;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let cancelListener: (() => void) | undefined;\n try {\n await Promise.race([\n snapshot,\n ...(signal\n ? [\n new Promise<never>((_resolve, reject) => {\n cancelListener = () =>\n reject(signal.reason ?? new Error(\"workspace snapshot wait cancelled\"));\n signal.addEventListener(\"abort\", cancelListener, { once: true });\n if (signal.aborted) cancelListener();\n }),\n ]\n : []),\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new SnapshotTimeoutError(timeoutMs)), timeoutMs);\n if (timeout && \"unref\" in timeout && typeof timeout.unref === \"function\") {\n timeout.unref();\n }\n }),\n ]);\n return true;\n } catch (error) {\n if (signal?.aborted) return false;\n if (error instanceof SnapshotTimeoutError) {\n console.error(\n \"mid-session workspace snapshot wait timed out (turn unaffected)\",\n safeSnapshotError(error),\n );\n return false;\n }\n return true;\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n if (cancelListener) signal?.removeEventListener(\"abort\", cancelListener);\n }\n}\n\nasync function resolveModalCheckpointBindingBeforeCapture(\n settings: SandboxResumeServices[\"settings\"],\n session: unknown,\n signal?: AbortSignal,\n): Promise<Awaited<ReturnType<typeof resolveModalCheckpointProviderBindingForSession>>> {\n if (signal?.aborted) {\n throw signal.reason ?? new Error(\"workspace snapshot identity lookup cancelled\");\n }\n const pending = resolveModalCheckpointProviderBindingForSession(settings, session);\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let cancelListener: (() => void) | undefined;\n try {\n return await Promise.race([\n pending,\n ...(signal\n ? [\n new Promise<never>((_resolve, reject) => {\n cancelListener = () =>\n reject(signal.reason ?? new Error(\"workspace snapshot identity lookup cancelled\"));\n signal.addEventListener(\"abort\", cancelListener, { once: true });\n if (signal.aborted) cancelListener();\n }),\n ]\n : []),\n new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(\n () => reject(new SnapshotTimeoutError(settings.sandboxSnapshotTimeoutMs)),\n settings.sandboxSnapshotTimeoutMs,\n );\n timeout.unref?.();\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n if (cancelListener) signal?.removeEventListener(\"abort\", cancelListener);\n }\n}\n\nasync function terminateEstablishedSandbox(\n established: EstablishedSandboxSession | null,\n): Promise<boolean> {\n if (!established) return true;\n try {\n await terminateUnpublishedSandboxSession(established);\n return true;\n } catch (error) {\n if (isProviderSandboxNotFoundError(established.backendId, error)) {\n return true;\n }\n // Best-effort cleanup. A provider-side orphan sweep is the backstop.\n return false;\n }\n}\n\nfunction recordSandboxWarmingTimeout(\n metrics: RuntimeMetricsHooks | undefined,\n error: unknown,\n): void {\n if (!(error instanceof SandboxWarmingTimeoutError)) {\n return;\n }\n try {\n metrics?.onSandboxWarmingTimeout?.({ backend: error.backend, stage: error.stage });\n } catch {\n // Metrics emission must never affect sandbox recovery or error propagation.\n }\n}\n\nfunction workspaceArchiveFieldsFromEnvelope(\n envelope: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null {\n const sessionState =\n envelope && typeof envelope.sessionState === \"object\" && envelope.sessionState !== null\n ? (envelope.sessionState as Record<string, unknown>)\n : null;\n const archive = sessionState?.workspaceArchive;\n if (typeof archive !== \"string\" || archive.length === 0) {\n return null;\n }\n const previous = sessionState?.workspaceArchivePrev;\n const metadata = sessionState?.workspaceArchiveMeta;\n const previousMetadata = sessionState?.workspaceArchivePrevMeta;\n const capturedAt = sessionState?.workspaceArchiveAt;\n return {\n workspaceArchive: archive,\n ...(metadata !== undefined ? { workspaceArchiveMeta: metadata } : {}),\n ...(typeof previous === \"string\" && previous.length > 0\n ? { workspaceArchivePrev: previous }\n : {}),\n ...(previousMetadata !== undefined ? { workspaceArchivePrevMeta: previousMetadata } : {}),\n ...(typeof capturedAt === \"string\" && capturedAt.length > 0\n ? { workspaceArchiveAt: capturedAt }\n : {}),\n };\n}\n\nfunction legacyNativeArchiveFromEnvelope(envelope: Record<string, unknown> | null | undefined) {\n const sessionState =\n envelope && typeof envelope.sessionState === \"object\" && envelope.sessionState !== null\n ? (envelope.sessionState as Record<string, unknown>)\n : null;\n if (!sessionState) return null;\n const existing = parseWorkspaceArchiveDescriptor(sessionState.workspaceArchiveMeta);\n if (existing?.version === 2) return null;\n return describeLegacyNativeSnapshotArchive(\n sessionState.workspaceArchive,\n existing?.version === 1 ? Date.parse(existing.capturedAt) : Date.now(),\n );\n}\n\n/**\n * MID-SESSION /workspace snapshot (sandbox-file-persistence). The reaper's\n * drain-persist only protects boxes the reaper itself kills; anything else —\n * Modal's hard creation-time timeout catching a session busy past it, provider\n * OOM/infra death — loses everything since the last clean drain (staging\n * session e644e8a8, 2026-07-06: mid-turn box termination cost an unpushed\n * branch + 2 commits). While a turn HOLDS the live box, this folds a fresh\n * snapshot onto the lease through persistWarmSnapshot (the warm sibling of the\n * drain seam: epoch-fenced CAS + atomic throttle re-check) and GCs the\n * superseded snapshot image, bounding worst-case loss of ANY unclean box death\n * to sandboxSnapshotIntervalMs.\n *\n * Never throws and never blocks turn progress semantics: every failure path\n * returns false (the snapshot is protection, not a turn dependency). No-ops\n * when the interval is 0, the backend has no persistWorkspace (selfhosted =\n * the user's machine IS the persistence), or a snapshot newer than the\n * interval already rides the lease.\n */\nexport async function maybePersistWarmWorkspaceSnapshot(\n services: SandboxResumeServices,\n ids: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n sandboxGroupId: string;\n },\n session: unknown,\n leaseEpoch: number,\n signal?: AbortSignal,\n force = false,\n): Promise<boolean> {\n const { db, settings } = services;\n const intervalMs = settings.sandboxSnapshotIntervalMs;\n if (intervalMs <= 0 && !force) {\n return false;\n }\n const persistable = session as {\n persistWorkspace?: () => Promise<Uint8Array | undefined>;\n state?: {\n workspacePersistence?: unknown;\n providerState?: { workspacePersistence?: unknown };\n };\n };\n if (typeof persistable.persistWorkspace !== \"function\") {\n return false;\n }\n // Filesystem and directory snapshots create retained Images without\n // terminating the source Sandbox. (Modal's termination warning applies to\n // memory snapshots.) They are therefore the preferred warm-checkpoint path:\n // the durable capture gate pauses OpenGeni commands while the provider reads\n // the filesystem, then the same live instance continues serving the turn.\n const workspacePersistence =\n persistable.state?.workspacePersistence ??\n persistable.state?.providerState?.workspacePersistence;\n if (signal?.aborted) {\n return false;\n }\n try {\n // Resolve the provider namespace before taking the durable capture gate.\n // This work cannot pause or mutate the box, so keeping it outside the claim\n // minimizes the time that command admission must wait.\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (\n !lease ||\n lease.leaseEpoch !== leaseEpoch ||\n lease.liveness !== \"warm\" ||\n lease.instanceId === null\n ) {\n return false;\n }\n // A checkpoint of this exact mutation generation already protects every\n // settled operation admitted so far. Capturing it again cannot improve the\n // recovery point, even when the wall-clock interval has elapsed.\n if (lease.archiveComplete) {\n return false;\n }\n const instanceId = lease.instanceId;\n const capturePolicy = providerWorkspaceCapturePolicy(lease.backend, session);\n if (!capturePolicy || capturePolicy.liveInstance !== \"preserved\") {\n return false;\n }\n const nativeModalPersistence =\n workspacePersistence === \"snapshot_filesystem\" ||\n workspacePersistence === \"snapshot_directory\";\n const checkpointBinding = nativeModalPersistence\n ? await resolveModalCheckpointBindingBeforeCapture(settings, persistable, signal)\n : null;\n if (signal?.aborted) return false;\n\n const captureId = randomUUID();\n const captureTimeoutMs = sandboxArchiveCaptureTimeoutMs(settings);\n const claimed = await claimWorkspaceArchiveCapture(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n captureId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: instanceId,\n liveness: \"warm\",\n captureTimeoutMs,\n minIntervalMs: force ? 0 : intervalMs,\n providerReplaySafe: capturePolicy.takeover === \"same_request\",\n takeoverSafe: capturePolicy.takeover !== \"exclusive\",\n warmAttempt: {\n sessionId: ids.sessionId,\n turnId: ids.turnId,\n attemptId: ids.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(ids.attemptId),\n },\n });\n if (claimed.status !== \"claimed\") return false;\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n // Stamp WHEN this capture started: persistWarmSnapshot orders warm snapshots\n // by capture-initiation, not land time, so a slower heartbeat capture that\n // started earlier can never overwrite a fresher turn-end capture that landed\n // first (the bounded-wait race Bugbot flagged).\n const capturedAtMs = Date.now();\n const registerCandidate = async (\n archive: Awaited<ReturnType<typeof captureVerifiedWorkspaceArchive>>,\n ): Promise<{ id: string } | null> => {\n if (\n archive.descriptor.version !== 2 ||\n (archive.descriptor.provider !== \"modal_snapshot_filesystem\" &&\n archive.descriptor.provider !== \"modal_snapshot_directory\")\n ) {\n return null;\n }\n if (!checkpointBinding) {\n throw new Error(\"Modal native snapshot has no exact session provider identity\");\n }\n return await registerSandboxCheckpointArtifact(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n sourceLeaseId: claimed.claim.leaseId,\n sourceLeaseEpoch: leaseEpoch,\n sourceInstanceId: instanceId,\n sourceWorkspaceGeneration: claimed.claim.workspaceGeneration,\n providerBindingKey: checkpointBinding.key,\n providerBinding: checkpointBinding.binding,\n workspaceArchive: archive.base64,\n workspaceArchiveMeta: archive.descriptor,\n });\n };\n\n const abandonCandidate = async (artifactId: string, reason: string): Promise<void> => {\n await markSandboxCheckpointArtifactDeletePending(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n artifactId,\n reason,\n }).catch(() => undefined);\n };\n // The SDK capture itself is not cancellable. Keep one owned continuation\n // alive through provider settlement even if this caller's bounded wait or\n // turn signal resolves first. Its finally block is the only normal release\n // of the exact admission gate; a late callback cannot release a successor.\n const captureAndPublish = (async (): Promise<boolean> => {\n let candidate: { id: string } | null = null;\n try {\n const archive = await captureVerifiedWorkspaceArchive(session, capturedAtMs, {\n requestId: claimed.claim.providerRequestId,\n strategy: capturePolicy.strategy,\n });\n candidate = await registerCandidate(archive);\n const { wrote } = await persistWarmSnapshot(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: ids.turnId,\n attemptId: ids.attemptId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: instanceId,\n expectedWorkspaceGeneration: claimed.claim.workspaceGeneration,\n captureId,\n workspaceArchive: archive.base64,\n workspaceArchiveMeta: archive.descriptor,\n checkpointArtifactId: candidate?.id ?? null,\n minIntervalMs: force ? 0 : intervalMs,\n capturedAtMs,\n });\n if (!wrote && candidate) {\n await abandonCandidate(candidate.id, \"snapshot_publication_fenced\");\n }\n return wrote;\n } catch (error) {\n if (candidate) await abandonCandidate(candidate.id, \"snapshot_capture_failed\");\n throw error;\n } finally {\n await releaseWorkspaceArchiveCapture(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n captureId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: instanceId,\n }).catch((error) => {\n console.error(\n \"mid-session workspace capture gate release failed\",\n safeSnapshotError(error),\n );\n });\n }\n })();\n const settled = captureAndPublish.then(\n (persisted) => ({ kind: \"settled\" as const, persisted }),\n (error) => {\n console.error(\n \"mid-session workspace snapshot failed (turn unaffected)\",\n safeSnapshotError(error),\n );\n return { kind: \"settled\" as const, persisted: false };\n },\n );\n let cancelListener: (() => void) | undefined;\n const outcome = await Promise.race([\n settled,\n ...(signal\n ? [\n new Promise<{ kind: \"cancelled\" }>((resolve) => {\n cancelListener = () => resolve({ kind: \"cancelled\" });\n signal.addEventListener(\"abort\", cancelListener, { once: true });\n if (signal.aborted) cancelListener();\n }),\n ]\n : []),\n new Promise<{ kind: \"timed_out\" }>((resolve) => {\n timeout = setTimeout(\n () => resolve({ kind: \"timed_out\" }),\n settings.sandboxSnapshotTimeoutMs,\n );\n }),\n ]).finally(() => {\n if (timeout) clearTimeout(timeout);\n if (cancelListener) signal?.removeEventListener(\"abort\", cancelListener);\n });\n // A timed-out/cancelled local waiter deliberately leaves the already-owned\n // provider continuation running; `settled` has both rejection handling and\n // exact claim cleanup, so it cannot leak an unhandled promise or artifact.\n return outcome.kind === \"settled\" ? outcome.persisted : false;\n } catch (error) {\n // Protection, not a dependency: a failed snapshot must never fail (or slow\n // down retrying) the turn. The next heartbeat/turn-end tick retries.\n console.error(\n \"mid-session workspace snapshot failed (turn unaffected)\",\n safeSnapshotError(error),\n );\n return false;\n }\n}\n\n/**\n * Resume the one box for a single turn (or any worker-side resume op). Returns\n * the live non-owned session + the fence epoch + a release fn. The CALLER owns\n * the lifecycle: inject non-owned, run, then `await release()` and drop the\n * handle in `finally`.\n *\n * holderId is the globally unique durable turn-attempt id. It must not be a\n * Temporal activity id, because activity ids are only workflow-local and\n * collide when sibling sessions share one sandbox group.\n */\nexport async function resumeBoxForTurn(\n services: SandboxResumeServices,\n ids: ResumeBoxIds,\n kind: \"turn\",\n holderId: TurnSandboxLeaseHolderId,\n): Promise<ResumedTurnSandbox> {\n const { db, settings } = services;\n const os = ids.os ?? \"linux\";\n const leaseTtlMs = settings.sandboxLeaseTtlMs;\n const cancellationSignal = services.cancellationSignal;\n\n // The release closure is created eagerly so the caller can always release in\n // finally, even if establish/commit throws after the holder was registered.\n // It is also bound directly to the logical attempt signal: an uninterruptible\n // provider promise must never keep its private warmup timer and holder alive\n // after Temporal has abandoned the activity.\n let releaseStarted = false;\n let holderRelease: Promise<void> | null = null;\n let quiescedRelease: Promise<void> | null = null;\n let holderLivenessTimer: ReturnType<typeof setInterval> | undefined;\n let cancellationListener: (() => void) | undefined;\n const release = (options?: { workspaceWritersQuiesced?: boolean }): Promise<void> => {\n const writersQuiesced = options?.workspaceWritersQuiesced === true;\n // First invocation synchronously closes every in-memory liveness source.\n // A later quiesced invocation is still allowed to enter the DB: cancellation\n // commonly wins this race and drops the holder before the physical writer\n // drain can prove that abandoned turn admissions are safe to settle.\n if (!releaseStarted) {\n releaseStarted = true;\n if (cancellationListener) {\n cancellationSignal?.removeEventListener(\"abort\", cancellationListener);\n cancellationListener = undefined;\n }\n if (holderLivenessTimer) {\n clearInterval(holderLivenessTimer);\n holderLivenessTimer = undefined;\n }\n }\n const persistRelease = async (workspaceWritersQuiesced: boolean): Promise<void> => {\n await releaseLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n idleGraceMs: settings.sandboxIdleGraceMs,\n ...(workspaceWritersQuiesced ? { workspaceWritersQuiesced: true } : {}),\n });\n };\n if (writersQuiesced) {\n if (!quiescedRelease) {\n // Serialize behind an eager cancellation release when one exists. Its\n // failure is intentionally swallowed only as a predecessor: this exact\n // idempotent proof-bearing call retries both holder deletion and\n // admission settlement in one transaction.\n const predecessor = holderRelease;\n const attempt = (predecessor ? predecessor.catch(() => undefined) : Promise.resolve()).then(\n async () => await persistRelease(true),\n );\n const tracked = attempt.catch((error) => {\n if (quiescedRelease === tracked) quiescedRelease = null;\n throw error;\n });\n quiescedRelease = tracked;\n holderRelease = tracked;\n }\n return quiescedRelease;\n }\n if (!holderRelease) {\n const attempt = persistRelease(false);\n const tracked = attempt.catch((error) => {\n if (holderRelease === tracked) holderRelease = null;\n throw error;\n });\n holderRelease = tracked;\n }\n return holderRelease;\n };\n const cancellationError = (): Error =>\n cancellationSignal?.reason instanceof Error\n ? cancellationSignal.reason\n : new Error(\"Sandbox resume was cancelled with its owning turn attempt\");\n const throwIfReleasedOrCancelled = (): void => {\n if (releaseStarted || cancellationSignal?.aborted) {\n throw cancellationError();\n }\n };\n\n const acquired = await acquireLease(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n subjectId: ids.sessionId,\n backend: ids.backend,\n os,\n // IMAGE IS SHARED STATE (B3): thread the resolved image so the lease stamps it +\n // conflicts on a live box already running a different image. A\n // SandboxImageConflictError propagates while another holder is active; a\n // solo change requests a capture-and-drain rotation and this attempt retries\n // after the cold successor can safely stamp the new image.\n ...(ids.image ? { image: ids.image } : {}),\n // RIG IS SHARED STATE (M3): thread the frozen rig version so the lease stamps it\n // + conflicts on a live box under a different rig. A SandboxRigConflictError\n // propagates while another holder is active; a solo change uses the same\n // durable capture-and-drain rotation as an image change.\n ...(ids.rigVersionId ? { rigVersionId: ids.rigVersionId } : {}),\n leaseTtlMs,\n warmingLeaseTtlMs: settings.sandboxLeaseWarmingTtlMs,\n captureWaitMs: sandboxLifecycleTransitionWaitMs(settings),\n ...(cancellationSignal ? { waitSignal: cancellationSignal } : {}),\n });\n\n if (cancellationSignal) {\n cancellationListener = () => {\n // release() flips `releaseStarted` and clears the timer synchronously\n // before its first await. This eager form deliberately carries no writer-\n // quiescence proof; the outer turn supplies that second stage after its\n // physical drain. The detached rejection handler is intentional: the\n // outer turn owns diagnostics, while this listener owns leak prevention.\n void release().catch(() => undefined);\n };\n cancellationSignal.addEventListener(\"abort\", cancellationListener, { once: true });\n }\n if (cancellationSignal?.aborted) {\n await release();\n throw cancellationError();\n }\n\n // HOLDER-LIVENESS loop: refresh OUR holder every 10s from registration.\n // registered until release. The dead-worker turn-holder reap judges liveness\n // by last_heartbeat_at, and the full turn heartbeat (heartbeatLeaseHolder in\n // agent-turn) only starts AFTER this function returns — while waitForWarm and\n // establish/cold-restore can legitimately run for many minutes in here,\n // COMPOUNDING past any fixed reap horizon. With this\n // loop no live holder is ever silent for more than one tick, so the reap\n // horizon is pure defense-in-depth, not a tuned guess about path lengths.\n // The elected spawner also heartbeats the short rolling warming lease; this\n // makes warming expiry a crash detector rather than a fixed upper bound on a\n // legitimate provider create/restore. A warming waiter only touches its own\n // holder so it cannot keep a dead spawner's lease alive. Once the box is warm,\n // every owner uses the normal epoch-fenced lease heartbeat.\n let holderLeaseHeartbeat: { expectedEpoch: number; leaseTtlMs: number } | null =\n acquired.role === \"spawner\"\n ? {\n expectedEpoch: acquired.lease.leaseEpoch,\n leaseTtlMs: settings.sandboxLeaseWarmingTtlMs,\n }\n : (acquired.role === \"attached\" || acquired.role === \"rearmed\") &&\n acquired.lease.liveness === \"warm\"\n ? { expectedEpoch: acquired.lease.leaseEpoch, leaseTtlMs }\n : null;\n holderLivenessTimer = setInterval(() => {\n const heartbeat = holderLeaseHeartbeat;\n const refresh = heartbeat\n ? heartbeatLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n expectedEpoch: heartbeat.expectedEpoch,\n leaseTtlMs: heartbeat.leaseTtlMs,\n })\n : touchLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n });\n void refresh\n .then((touched) => {\n // A canonical turn holder is rejected once its exact attempt is no\n // longer the active writer. Stop this otherwise-unbounded provider\n // operation and idempotently drop any remaining holder state.\n if (!touched && heartbeat === holderLeaseHeartbeat) {\n void release().catch(() => undefined);\n }\n })\n .catch(() => undefined);\n }, 10_000);\n if (\"unref\" in holderLivenessTimer && typeof holderLivenessTimer.unref === \"function\") {\n holderLivenessTimer.unref();\n }\n\n // FENCED: a newer epoch exists (a later turn re-established the box). Back off;\n // NEVER create(). Release our (just-registered) holder so we don't pin a stale\n // lease, then surface the supersession.\n if (acquired.role === \"blocked\") {\n await release();\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n acquired.lease.leaseEpoch,\n acquired.code,\n acquired.lease.recovery,\n );\n }\n if (acquired.role === \"fenced\") {\n await release();\n if (acquired.reason !== \"superseded\") {\n throw new SandboxLeaseTransitionError(\n ids.sandboxGroupId,\n acquired.lease.leaseEpoch,\n acquired.reason,\n acquired.lease.backend,\n acquired.lease.instanceId,\n acquired.lease.liveness,\n );\n }\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, acquired.lease.leaseEpoch, {\n backend: acquired.lease.backend,\n instanceId: acquired.lease.instanceId,\n liveness: acquired.lease.liveness,\n });\n }\n\n // SPAWNER: we won the cold->warming CAS. Establish (cold-restore/create),\n // then commit warm (lease_epoch++). Optional desktop setup is lazy.\n if (acquired.role === \"spawner\") {\n const expectedEpoch = acquired.lease.leaseEpoch;\n let createdEstablished: EstablishedSandboxSession | null = null;\n let rematerialization: {\n id: string;\n selectedRevision: string;\n workspaceGeneration: number;\n providerBindingKey: string | null;\n legacyCheckpoint: NonNullable<ReturnType<typeof legacyNativeArchiveFromEnvelope>> | null;\n legacyProviderBinding: Awaited<\n ReturnType<typeof resolveModalCheckpointProviderBindingForSession>\n > | null;\n } | null = null;\n try {\n const envelope = await getSandboxSessionEnvelope(db, ids.workspaceId, ids.sessionId);\n // The lease is authoritative. A legacy per-session fallback archive may\n // only be used after beginSandboxRematerialization imports its archive\n // fields under the warming-row lock and records one selected revision.\n // Select the fallback only when the lease has no archive truth at all. A\n // lease-carried unverified/invalid archive must fail closed rather than\n // silently substituting another revision.\n const fallbackArchiveEnvelope =\n acquired.lease.recovery.archive.status === \"none\" &&\n workspaceArchiveFieldsFromEnvelope(envelope) !== null\n ? withoutSandboxProviderIdentity(envelope)\n : null;\n let spawnEnvelope = fallbackArchiveEnvelope ?? acquired.lease.resumeState ?? envelope;\n const archiveSource =\n acquired.lease.recovery.archive.status === \"none\"\n ? fallbackArchiveEnvelope\n : acquired.lease.resumeState;\n const continuityRecovery = acquired.lease.recovery.continuity;\n if (\n (acquired.lease.recovery.archive.status === \"available\" &&\n acquired.lease.archiveComplete) ||\n (acquired.lease.recovery.archive.status === \"none\" &&\n workspaceArchiveFieldsFromEnvelope(archiveSource) !== null)\n ) {\n const rematerializationId = crypto.randomUUID();\n const legacyNativeArchive = legacyNativeArchiveFromEnvelope(archiveSource);\n const begun = await beginSandboxRematerialization(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId,\n archiveSource,\n legacyNativeArchive,\n });\n if (begun.status !== \"started\") {\n if (begun.code === \"stale_epoch\" || begun.code === \"attempt_conflict\") {\n throw new SandboxLeaseSupersededError(\n ids.sandboxGroupId,\n begun.lease?.leaseEpoch ?? expectedEpoch,\n );\n }\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n begun.lease?.leaseEpoch ?? expectedEpoch,\n begun.code === \"archive_unverified\" ? \"restore_degraded\" : \"restore_unrecoverable\",\n begun.lease?.recovery ?? acquired.lease.recovery,\n );\n }\n spawnEnvelope = begun.lease.resumeState ?? spawnEnvelope;\n const selectedRevision = begun.lease.recovery.restore.selectedRevision;\n if (!selectedRevision) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_metadata_invalid\",\n \"sandbox rematerialization selected no durable archive revision\",\n );\n }\n rematerialization = {\n id: rematerializationId,\n selectedRevision,\n workspaceGeneration: begun.lease.workspaceGeneration,\n providerBindingKey: begun.checkpointArtifact?.providerBindingKey ?? null,\n legacyCheckpoint: begun.checkpointArtifact === null ? legacyNativeArchive : null,\n legacyProviderBinding: null,\n };\n } else if (acquired.lease.recovery.archive.status !== \"none\" && !continuityRecovery) {\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n expectedEpoch,\n \"restore_degraded\",\n acquired.lease.recovery,\n );\n }\n // Prefer the COLD lease's preserved resume_state when it carries a persisted\n // /workspace snapshot (confirmDrainCold keeps a minimal archive-only envelope\n // across draining->cold for exactly this re-warm). establishSandboxSessionFromEnvelope\n // cold-creates a fresh box and replays the archive via hydrateWorkspace, so\n // /workspace survives box churn (sandbox-file-persistence). No archive ->\n // the bare session envelope (a never-warmed cold start). Mirrors channel-a.ts's\n // spawner branch: the lease's resume_state is authoritative; the session\n // `_sandbox` envelope is the per-session fallback. Without this a turn-first\n // re-warm after a drain->cold would ignore the archive and start an EMPTY box.\n const providerCreateStartedAt = new Date();\n const established = await establishSandboxSessionFromEnvelope(settings, spawnEnvelope, {\n sessionId: ids.sessionId,\n recovery: \"create-or-restore\",\n backendOverride: ids.backend as never,\n ...(ids.environment ? { environment: ids.environment } : {}),\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n ...(services.logicalFallbackSettings\n ? { logicalFallbackSettings: services.logicalFallbackSettings }\n : {}),\n onSandboxCreated: async (created) => {\n createdEstablished = created;\n throwIfReleasedOrCancelled();\n if (\n rematerialization &&\n (rematerialization.providerBindingKey || rematerialization.legacyCheckpoint)\n ) {\n if (created.backendId !== \"modal\") {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Modal checkpoint restore resolved a non-Modal sandbox backend\",\n );\n }\n if (rematerialization.providerBindingKey) {\n if (\n !(await modalSessionMatchesCheckpointProviderBinding(\n settings,\n created.session,\n rematerialization.providerBindingKey,\n ))\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Modal checkpoint restore refused because the authenticated provider workspace changed\",\n );\n }\n } else {\n const resolved = await resolveModalCheckpointProviderBindingForSession(\n settings,\n created.session,\n );\n if (\n rematerialization.legacyProviderBinding &&\n rematerialization.legacyProviderBinding.key !== resolved.key\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Legacy Modal checkpoint restore crossed authenticated provider workspaces\",\n );\n }\n rematerialization.legacyProviderBinding = resolved;\n }\n }\n const resumeEnvelope = requirePersistableReplacementSandboxEnvelope(\n await serializeReplacementSandboxEnvelope(created, spawnEnvelope),\n created.backendId,\n );\n const recorded = await recordWarmingSandboxCreated(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization?.id ?? null,\n ...(created.providerContinuity\n ? { continuityRecovery: created.providerContinuity }\n : {}),\n instanceId: created.instanceId,\n resumeBackendId: created.backendId,\n resumeState: resumeEnvelope,\n ...(created.backendId === \"modal\"\n ? {\n providerCreatedAt: providerCreateStartedAt,\n providerDeadlineAt: new Date(\n providerCreateStartedAt.getTime() + settings.modalTimeoutSeconds * 1000,\n ),\n }\n : {}),\n leaseTtlMs,\n // Keep the warming budget after create(): manifest setup and\n // commitWarmingToWarm still run, and can exceed the 90s turn TTL.\n warmingLeaseTtlMs: settings.sandboxLeaseWarmingTtlMs,\n });\n if (!recorded.recorded) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n if (created.backendId === \"modal\") {\n await tagModalSandbox(settings, created.instanceId, {\n leaseId: acquired.lease.id,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n }).catch(() => undefined);\n }\n throwIfReleasedOrCancelled();\n },\n onWorkspaceRestoreVerifying: async (descriptor: WorkspaceArchiveDescriptor) => {\n if (!rematerialization || descriptor.revision !== rematerialization.selectedRevision) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_metadata_invalid\",\n `hydrated archive revision ${descriptor.revision} does not match the selected rematerialization revision`,\n );\n }\n if (rematerialization.legacyCheckpoint) {\n const binding = rematerialization.legacyProviderBinding;\n if (!binding) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Legacy Modal checkpoint restore produced no authenticated provider identity\",\n );\n }\n const adopted = await adoptLegacyModalCheckpointArtifact(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n leaseId: acquired.lease.id,\n leaseEpoch: expectedEpoch,\n workspaceGeneration: rematerialization.workspaceGeneration,\n slot: \"current\",\n archiveBase64: rematerialization.legacyCheckpoint.archiveBase64,\n descriptor: rematerialization.legacyCheckpoint.descriptor,\n providerBindingKey: binding.key,\n providerBinding: binding.binding,\n rematerializationId: rematerialization.id,\n });\n if (!adopted) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n rematerialization.providerBindingKey = binding.key;\n }\n const verifying = await markSandboxRestoreVerifying(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization.id,\n });\n if (!verifying.wrote) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n },\n });\n createdEstablished = established;\n throwIfReleasedOrCancelled();\n // A sandbox handle is not sufficient evidence that Modal's command router\n // is live. Do not publish a warm lease until one bounded no-op exec works.\n // On timeout the catch below terminates the box and rolls warming -> cold,\n // so the next turn cold-creates instead of hanging forever on first use.\n await waitForSandboxExecReadiness(established, MODAL_EXEC_READINESS_TIMEOUT_MS, {\n sandboxGroupId: ids.sandboxGroupId,\n });\n throwIfReleasedOrCancelled();\n // Fold the LIVE box into a re-resumable envelope and persist it as the\n // lease's resume_state — exactly like the API-direct paths (channel-a.ts /\n // viewer.ts). Without this the turn committed the ORIGINAL session manifest\n // as resume_state, so every LATER op off this lease (Channel-A fs/git/\n // terminal, the desktop viewer, the reaper) cold-restored a FRESH rival box\n // and never saw the turn's live box. Historical state may contribute only\n // durable archive pointers: if live serialization fails, publishing its\n // dead provider identity would pair the replacement instance with the box\n // that initiated recovery.\n // A successful cold hydrate has already proved this archive usable and the\n // replacement box now contains its files. Keep the current + fallback\n // archive pointers on the committed live envelope until a later warm\n // snapshot replaces them. Without this merge, serialization publishes only\n // the new provider id; a second provider loss before the snapshot cadence\n // fires would otherwise make truthful recovery impossible. Failed hydrate\n // attempts terminate the replacement and fail closed; they never publish a\n // clean or mixed workspace.\n const resumeEnvelope = requirePersistableReplacementSandboxEnvelope(\n await serializeReplacementSandboxEnvelope(established, spawnEnvelope),\n established.backendId,\n );\n throwIfReleasedOrCancelled();\n if (\n rematerialization &&\n !established.providerContinuity &&\n established.restoredArchive?.revision !== rematerialization.selectedRevision\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_mismatch\",\n \"sandbox restore completed without the exact selected durable archive revision\",\n );\n }\n const committed = await commitWarmingToWarm(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n instanceId: established.instanceId,\n // Viewer attach resolves and records the tunnel URL lazily. A headless\n // turn must not touch the optional desktop data plane.\n dataPlaneUrl: null,\n resumeBackendId: established.backendId,\n resumeState: resumeEnvelope,\n ...(established.providerContinuity\n ? { continuityRecovery: established.providerContinuity }\n : rematerialization\n ? {\n rematerialization: {\n id: rematerialization.id,\n verifiedRevision: rematerialization.selectedRevision,\n },\n }\n : {}),\n leaseTtlMs,\n });\n if (!committed.committed || !committed.lease) {\n // A reaper reset our warming row (we were too slow) or a sibling\n // re-established and bumped the epoch. Drop the handle; release our\n // holder; surface supersession. This spawner created the box, so stop it\n // before retrying to avoid an untracked running sandbox.\n const terminated = await terminateEstablishedSandbox(established);\n if (terminated && rematerialization && !established.providerContinuity) {\n await failSandboxRematerialization(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization.id,\n failureCode: committed.reason ?? \"warm_commit_rejected\",\n retryable: false,\n });\n } else if (terminated) {\n await failWarmingToCold(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n });\n }\n await release();\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n holderLeaseHeartbeat = {\n expectedEpoch: committed.lease.leaseEpoch,\n leaseTtlMs,\n };\n throwIfReleasedOrCancelled();\n return { established, leaseEpoch: committed.lease.leaseEpoch, release };\n } catch (error) {\n if (error instanceof SandboxLeaseSupersededError) {\n await terminateEstablishedSandbox(createdEstablished);\n await release();\n throw error;\n }\n const terminated = await terminateEstablishedSandbox(createdEstablished);\n // Caught spawn failure: if the just-created sandbox was actually stopped,\n // roll the warming row back to cold so a queued turn can re-acquire and\n // re-spawn. If termination itself failed, keep the recorded instance_id on\n // the warming row; the lease TTL/reaper and Modal orphan sweep are the\n // tracked backstops, and we must not erase the only provider pointer.\n if (terminated) {\n const continuityUnavailable = error instanceof SandboxProviderContinuityUnavailableError;\n if (rematerialization && !createdEstablished?.providerContinuity) {\n await failSandboxRematerialization(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization.id,\n failureCode: continuityUnavailable\n ? \"provider_continuity_unavailable\"\n : error instanceof WorkspaceArchiveIntegrityError\n ? error.code\n : \"sandbox_rematerialization_failed\",\n retryable: continuityUnavailable\n ? error.retryable\n : error instanceof WorkspaceArchiveIntegrityError\n ? error.retryable\n : true,\n ...(continuityUnavailable ? { discardContinuity: true } : {}),\n });\n } else {\n await failWarmingToCold(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n ...(continuityUnavailable ? { discardContinuity: true } : {}),\n });\n }\n }\n await release();\n recordSandboxWarmingTimeout(services.sandboxMetrics, error);\n throw error;\n }\n }\n\n // ATTACHED / REARMED: the box is live (or a sibling is warming it). Resume it\n // BY ID off the committed lease envelope. For an 'attached'-to-warming lease we\n // first wait for the spawner to commit warm, bounded by the explicit warming\n // budget. A cold reset means the spawner died; recover the same turn instead\n // of trying to enter the spawner create path from the attached branch.\n try {\n let leaseEpoch = acquired.lease.leaseEpoch;\n if (acquired.lease.liveness === \"warming\") {\n leaseEpoch = (await waitForWarm(services, ids)).leaseEpoch;\n holderLeaseHeartbeat = { expectedEpoch: leaseEpoch, leaseTtlMs };\n }\n throwIfReleasedOrCancelled();\n\n // Prefer the lease's resume_state (the LIVE box the spawner committed) so we\n // re-attach to the SAME box by id, not cold-restore the original session\n // manifest into a rival. Fall back to the session envelope only when the\n // lease carries no resume_state (matches channel-a.ts's attached branch).\n const live = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (\n !live ||\n live.liveness !== \"warm\" ||\n live.leaseEpoch !== leaseEpoch ||\n live.instanceId === null\n ) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, live?.leaseEpoch ?? leaseEpoch);\n }\n let established: EstablishedSandboxSession;\n try {\n const establish = services.establishAttachedSandbox ?? establishSandboxSessionFromEnvelope;\n established = await establish(settings, live.resumeState, {\n sessionId: ids.sessionId,\n recovery: \"resume-only\",\n backendOverride: ids.backend as never,\n ...(ids.environment ? { environment: ids.environment } : {}),\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n });\n throwIfReleasedOrCancelled();\n // A durable `warm` row is an ownership assertion, not provider liveness.\n // Modal may have ended the exact box at its finite timeout while OpenGeni\n // was idle. Prove the command router before handing the session to the\n // agent so terminal evidence enters the atomic warm->cold recovery path\n // below instead of surfacing inside a model-visible tool call.\n if (services.verifyAttachedSandboxReadiness) {\n await services.verifyAttachedSandboxReadiness(established);\n } else {\n await waitForSandboxExecReadiness(established, MODAL_EXEC_READINESS_TIMEOUT_MS, {\n sandboxGroupId: ids.sandboxGroupId,\n });\n }\n throwIfReleasedOrCancelled();\n } catch (error) {\n if (!isProviderSandboxNotFoundError(ids.backend, error)) {\n throw error;\n }\n const marked = await markWarmLeaseInstanceLost(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: live.instanceId,\n });\n if (marked.status === \"marked\") {\n await services.onSandboxLost?.({\n sandboxGroupId: ids.sandboxGroupId,\n instanceId: live.instanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n throw new SandboxLeaseInstanceLostError(\n ids.sandboxGroupId,\n marked.lease.leaseEpoch,\n live.instanceId,\n );\n }\n throw new SandboxLeaseSupersededError(\n ids.sandboxGroupId,\n marked.lease?.leaseEpoch ?? leaseEpoch,\n );\n }\n throwIfReleasedOrCancelled();\n return { established, leaseEpoch, release };\n } catch (error) {\n await release();\n recordSandboxWarmingTimeout(services.sandboxMetrics, error);\n throw error;\n }\n}\n\n/**\n * Poll a warming lease until the spawner commits warm. If the warming row is\n * reset to cold (the spawner died and the reaper reset it), surface supersession\n * so the turn is re-dispatched and can enter the normal spawner branch from\n * acquireLease. Bounded by OPENGENI_SANDBOX_WARMING_TIMEOUT_MS, not the lease TTL.\n */\nasync function waitForWarm(\n services: SandboxResumeServices,\n ids: ResumeBoxIds,\n): Promise<{ leaseEpoch: number }> {\n const { db, settings } = services;\n const deadline = Date.now() + settings.sandboxWarmingTimeoutMs;\n let instanceId: string | null = null;\n while (Date.now() < deadline) {\n await sleep(WARMING_POLL_INTERVAL_MS);\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (!lease) {\n // Lease vanished (cold-reaped). Re-dispatch from scratch.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, 0);\n }\n instanceId = lease.instanceId;\n if (lease.liveness === \"warm\") {\n return { leaseEpoch: lease.leaseEpoch };\n }\n if (lease.liveness === \"draining\") {\n // The warming attempt either failed into drain or committed+released before\n // this waiter observed it. Re-dispatch so acquireLease can re-arm or spawn\n // through the normal path.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, lease.leaseEpoch);\n }\n if (lease.liveness === \"cold\") {\n if (isRetryableDegradedRestore(lease.recovery.restore)) {\n // The elected spawner hit a transient archive verification failure.\n // Re-enter admission so one caller can become the next fenced spawner;\n // the archive remains authoritative and must not become terminal.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, lease.leaseEpoch);\n }\n if (\n lease.recovery.restore.status === \"degraded\" ||\n lease.recovery.restore.status === \"unrecoverable\"\n ) {\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n lease.leaseEpoch,\n lease.recovery.restore.status === \"degraded\"\n ? \"restore_degraded\"\n : \"restore_unrecoverable\",\n lease.recovery,\n );\n }\n // The spawner died; re-dispatch so the normal acquireLease path can win\n // cold->warming and run the full spawner branch.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, lease.leaseEpoch);\n }\n // still warming — keep polling.\n }\n throw new SandboxSiblingWarmingTimeoutError(ids.backend, settings.sandboxWarmingTimeoutMs, {\n sandboxGroupId: ids.sandboxGroupId,\n instanceId,\n });\n}\n","// apps/worker/src/sandbox-routing.ts — wire the agent-loop-free routing proxy\n// (`@opengeni/runtime` RoutingSandboxSession + makeActiveBackendResolver) to the\n// real DB pointer + the live NATS control plane for the WORKER TURN path (M7).\n//\n// The turn resumes its group box by id (resumeBoxForTurn) and injects it\n// NON-OWNED into the run. With hot-swap, the injected `session` must be the\n// STABLE routing proxy: the SDK binds to it ONCE and calls its\n// methods per tool call; the proxy re-reads `(active_sandbox_id, active_epoch)`\n// per op and dispatches to the currently-active backend (the group Modal box by\n// default, or a swap target — a sibling Modal box or a selfhosted machine).\n//\n// The glue here is the DB-coupled half the leaf cannot own (the leaf must stay\n// agent-loop-free + db-free): readActiveSandbox (the pointer), getSandbox (the\n// target lookup), and the selfhosted ControlRpc built over the events bus's NATS\n// request/reply connection.\n\nimport { sandboxLifecycleTransitionWaitMs, type Settings } from \"@opengeni/config\";\nimport {\n advanceWorkspaceGenerationForRetainedProcess,\n advanceWorkspaceGeneration,\n getRetainedProcess,\n retainWorkspaceMutationProcess,\n retainedProcessSettlementIdentity,\n settleRetainedProcess,\n verifyRetainedProcessMutationSettlement,\n verifyWorkspaceMutationSettlement,\n getSandbox,\n getEnrollment,\n markWarmLeaseInstanceLost,\n readLease,\n readActiveSandbox,\n SandboxRetainedProcessPromotionFencedError,\n type Database,\n type SandboxWorkspaceMutationAdmission,\n} from \"@opengeni/db\";\nimport type { EventBus } from \"@opengeni/events\";\nimport {\n buildSelfhostedBackendSession,\n establishSandboxSessionFromEnvelope,\n isProviderSandboxGoneDuringRoutedOperation,\n isProviderSandboxNotFoundError,\n makeActiveBackendResolver,\n NatsControlRpc,\n NatsOpStreamTransport,\n RoutingBackendRecoveryRequiredError,\n RoutingSandboxSession,\n resolveModalCheckpointProviderBindingForSession,\n sandboxProviderInstanceIdFromEnvelope,\n sandboxBackendForSdkBackendId,\n selectBackend,\n verifySandboxExecReadiness,\n type ControlRpc,\n type EstablishedSandboxSession,\n type NatsRequestConnection,\n type RoutableBackendSession,\n type RoutableSandbox,\n type ResolvedActiveBackend,\n type RoutingMutationSettlementResult,\n type RoutingSandboxOperationObserver,\n type RoutingRetainedProcess,\n type RoutingRetainedProcessTerminalProof,\n type SelfhostedOpObserver,\n type SelfhostedRelayConfig,\n type OpStreamJournal,\n type SelfhostedOpStreamDeps,\n} from \"@opengeni/runtime\";\nimport { sandboxLeaseHolderIdForAttempt } from \"./sandbox-resume\";\n\ntype PersistableMutationAdmission = {\n admission: SandboxWorkspaceMutationAdmission;\n providerBinding: Awaited<\n ReturnType<typeof resolveModalCheckpointProviderBindingForSession>\n > | null;\n};\n\nexport type RoutingWiringServices = {\n db: Database;\n settings: Settings;\n /** The events bus, for the selfhosted control-plane request/reply connection.\n * Optional: when absent (or NATS unconfigured) a selfhosted swap target\n * surfaces agent_offline on its first op rather than failing to build. */\n bus?: EventBus;\n /** The per-op observer wired into every selfhosted session this turn builds\n * (out-of-band telemetry — op metrics + machine.* events). Absent ⇒ no-op. */\n onOp?: SelfhostedOpObserver;\n /** Every physical routed provider call, across cloud and selfhosted homes. */\n onSandboxOperation?: RoutingSandboxOperationObserver;\n /** The op-stream durable-resume journal (the Temporal adaptation from\n * op-journal.ts): attach generation + settled-frontier persistence. Absent ⇒\n * the runtime defaults (generation \"1\", no persistence) — tests / non-turn\n * callers. Only consulted when op-stream is actually enabled for the turn. */\n opJournal?: OpStreamJournal;\n /** Durable lifecycle notification emitted only by the observer that wins the\n * exact warm-instance loss CAS. */\n onHomeSandboxLost?: (input: {\n sandboxGroupId: string;\n instanceId: string;\n leaseEpoch: number;\n }) => Promise<void>;\n /** Called when a route repair replaces the worker's original home handle. */\n onHomeSandboxRebound?: (input: {\n established: EstablishedSandboxSession;\n leaseEpoch: number;\n }) => void;\n /** Cancel bounded capture waits with the owning turn activity. */\n waitSignal?: AbortSignal;\n};\n\n/** Worker-turn routing may final-ack streamed command output, so it must always\n * carry the turn's durable frontier journal. Non-turn helpers may still omit it\n * through the broader service shape above. */\ntype TurnRoutingWiringServices = RoutingWiringServices & {\n opJournal: OpStreamJournal;\n};\n\nexport type RoutingWiringIds = {\n workspaceId: string;\n sessionId: string;\n /** Canonical turn-attempt fence used to admit persistable-home mutations.\n * Omit outside a running worker attempt; mutation hooks then remain disabled. */\n workspaceMutationFence?: {\n accountId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n };\n homeLease?: {\n accountId: string;\n sandboxGroupId: string;\n leaseEpoch: number;\n instanceId: string;\n backend: string;\n };\n /**\n * The run's declared sandbox environment — the SAME object the turn passes to\n * `runtime.buildAgent`'s `sandboxEnvironment` and to `resumeBoxForTurn` (so the\n * group box's manifest carries it too). Threaded into a selfhosted swap target's\n * manifest so its `environment` EQUALS the turn's, making the SDK's per-turn\n * provided-session manifest-env delta empty (validateNoEnvironmentDelta).\n * WITHOUT this a pin-to-vm turn throws \"Live sandbox sessions cannot change\n * manifest environment variables.\" Optional → the resolver defaults to `{}`.\n */\n environment?: Record<string, string>;\n /**\n * Stage D machine-primary: PIN the already-established turn SelfhostedSession\n * (the `established` arg's session) for THIS machine pointer `(sandboxId, epoch)`\n * so the per-op resolver returns that SAME instance instead of building a fresh\n * one — the turn-start manifest write + per-op reads then hit ONE\n * SelfhostedSession/manifest. Set ONLY by the machine-primary establish branch\n * (where `established.session` is the SelfhostedSession bound to this pointer);\n * the group-box/swap path omits it (the default is the modal group box, and a\n * swap target is built fresh).\n */\n pinnedSelfhosted?: { sandboxId: string; epoch: number };\n /**\n * Whether the turn's `defaultBackend` IS the session's home (so the null pointer may\n * resolve to it). Defaults to TRUE (omitted). Set explicitly FALSE on a machine-primary\n * turn of a Modal-HOME session (pinned to a machine, no Modal group box established this\n * turn): the routing resolver's null branch then throws a typed `home_unavailable_this_turn`\n * error on a mid-turn clear-to-null instead of silently serving the pinned machine — the\n * detach's pointer commit stands and takes effect next turn. A genuine machine-HOME turn\n * (home IS the machine) passes true.\n */\n defaultIsHome?: boolean;\n};\n\n/** Map the deployment relay URL to the leaf's `SelfhostedRelayConfig` shape\n * (host/port/tls). M8 wires the real relay; until then a configured/placeholder\n * host yields a well-formed stream-URL shape behind `resolveExposedPort`. */\nexport function relayConfigFromSettings(settings: Settings): SelfhostedRelayConfig {\n const raw = settings.selfhostedRelayUrl?.trim();\n if (!raw) {\n return { host: \"relay.opengeni.local\", port: 443, tls: true };\n }\n try {\n const url = new URL(raw.includes(\"://\") ? raw : `wss://${raw}`);\n const tls = url.protocol === \"wss:\" || url.protocol === \"https:\";\n const port = url.port ? Number(url.port) : tls ? 443 : 80;\n return { host: url.hostname, port, tls };\n } catch {\n return { host: raw, port: 443, tls: true };\n }\n}\n\n/** The selfhosted CONTROL vs EXEC op deadlines for a turn, from settings. Control\n * ops (ping/fs/desktop/pty) stay on the short timeout so machine liveness is never\n * masked by a slow op; exec has its own setting and defaults to no duration wall.\n * Threaded into every turn-path session build + resolver. */\nexport function selfhostedTimeoutsFromSettings(settings: Settings): {\n timeoutMs: number;\n execTimeoutMs: number;\n} {\n return {\n timeoutMs: settings.sandboxSelfhostedControlTimeoutMs,\n execTimeoutMs: settings.sandboxSelfhostedExecTimeoutMs,\n };\n}\n\n/** The same split deadlines shaped for `makeActiveBackendResolver`'s dep names\n * (`selfhostedTimeoutMs` / `selfhostedExecTimeoutMs`), for a swap/pin target. */\nfunction selfhostedResolverTimeouts(settings: Settings): {\n selfhostedTimeoutMs: number;\n selfhostedExecTimeoutMs: number;\n} {\n const { timeoutMs, execTimeoutMs } = selfhostedTimeoutsFromSettings(settings);\n return {\n selfhostedTimeoutMs: timeoutMs,\n selfhostedExecTimeoutMs: execTimeoutMs,\n };\n}\n\ntype HomeRouteLeaseIdentity = {\n accountId: string;\n sandboxGroupId: string;\n backend: string;\n};\n\ntype HomeRouteResolutionIds = HomeRouteLeaseIdentity & {\n workspaceId: string;\n sessionId: string;\n};\n\ntype HomeRouteRecovery = \"pending\" | \"degraded\" | \"unrecoverable\" | \"superseded\";\n\n/**\n * Translate the durable lease/recovery state into the typed disposition the\n * routing proxy exposes when the home cannot be safely resumed. A route repair\n * must never fall back to the old in-memory provider handle when the lease is\n * warming, restoring, unverifiable, or otherwise inconsistent.\n */\nfunction homeRouteRecoveryDisposition(\n lease: Awaited<ReturnType<typeof readLease>>,\n): HomeRouteRecovery {\n if (!lease) return \"unrecoverable\";\n if (lease.liveness === \"warming\") return \"pending\";\n if (lease.liveness === \"draining\") return \"superseded\";\n if (\n lease.recovery.restore.status === \"pending\" ||\n lease.recovery.restore.status === \"restoring\" ||\n lease.recovery.restore.status === \"verifying\"\n ) {\n return \"pending\";\n }\n if (\n lease.recovery.restore.status === \"degraded\" ||\n lease.recovery.workspace.status === \"degraded\" ||\n lease.recovery.archive.status === \"unverified\" ||\n lease.recovery.archive.status === \"invalid\"\n ) {\n return \"degraded\";\n }\n return \"unrecoverable\";\n}\n\nfunction homeRouteRecoveryError(\n lease: Awaited<ReturnType<typeof readLease>>,\n fallbackEpoch: number,\n): RoutingBackendRecoveryRequiredError {\n return new RoutingBackendRecoveryRequiredError(\n \"resolve_home_backend\",\n lease?.leaseEpoch ?? fallbackEpoch,\n homeRouteRecoveryDisposition(lease),\n );\n}\n\nexport function providerIdentityFromResumeState(\n resumeState: Record<string, unknown>,\n): string | null {\n return sandboxProviderInstanceIdFromEnvelope(resumeState);\n}\n\n/**\n * Resolve the current durable home identity after the route epoch changes.\n *\n * Same-target attach/repair can replace the provider instance while a worker\n * turn still holds the stable routing proxy. The proxy must therefore resume\n * the lease's CURRENT identity, not reuse the object captured at turn start.\n * This seam is deliberately resume-only: lease election/rematerialization is\n * owned by the API/lease state machine, and a routed tool call must never create\n * a rival provider or replay an ambiguous mutation.\n */\nasync function resolveCurrentHomeBackend(\n services: RoutingWiringServices,\n ids: HomeRouteResolutionIds,\n established: EstablishedSandboxSession,\n): Promise<ResolvedActiveBackend> {\n const lease = await readLease(services.db, ids.workspaceId, ids.sandboxGroupId);\n const fallbackEpoch = lease?.leaseEpoch ?? 0;\n if (\n !lease ||\n lease.liveness !== \"warm\" ||\n lease.recovery.provider.status !== \"exists\" ||\n lease.instanceId === null ||\n lease.recovery.provider.instanceId !== lease.instanceId ||\n lease.recovery.workspace.status !== \"ready\" ||\n (lease.recovery.restore.status !== \"not_required\" && lease.recovery.restore.status !== \"ready\")\n ) {\n throw homeRouteRecoveryError(lease, fallbackEpoch);\n }\n\n // A route epoch can advance without a provider replacement. Reuse the exact\n // established handle only when its identity still equals the durable one.\n if (lease.instanceId === established.instanceId) {\n services.onHomeSandboxRebound?.({\n established,\n leaseEpoch: lease.leaseEpoch,\n });\n return {\n session: established.session as RoutableBackendSession,\n sandboxId: null,\n kind: established.backendId,\n leaseEpoch: lease.leaseEpoch,\n providerInstanceId: lease.instanceId,\n };\n }\n\n const resumeState = lease.resumeState;\n const durableResumeBackend = lease.resumeBackendId ?? lease.backend ?? ids.backend;\n const resumeBackend = sandboxBackendForSdkBackendId(durableResumeBackend) ?? durableResumeBackend;\n if (\n !resumeState ||\n resumeBackend !== ids.backend ||\n providerIdentityFromResumeState(resumeState) !== lease.instanceId\n ) {\n throw homeRouteRecoveryError(lease, lease.leaseEpoch);\n }\n\n let rebound: EstablishedSandboxSession;\n try {\n rebound = await establishSandboxSessionFromEnvelope(services.settings, resumeState, {\n sessionId: ids.sessionId,\n recovery: \"resume-only\",\n backendOverride: resumeBackend as never,\n });\n // A resumed handle is not enough evidence for the route to use it. Keep the\n // same bounded readiness gate used before publishing a Modal lease warm.\n await verifySandboxExecReadiness(rebound);\n } catch (error) {\n if (!isProviderSandboxNotFoundError(resumeBackend, error)) {\n // The durable identity is present, but a transient resume/provider error\n // did not prove the box gone. Keep the lease untouched and make the next\n // independent route operation retry the resume; never use the old handle.\n throw new RoutingBackendRecoveryRequiredError(\n \"resolve_home_backend\",\n lease.leaseEpoch,\n \"pending\",\n );\n }\n const marked = await markWarmLeaseInstanceLost(services.db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: lease.leaseEpoch,\n expectedInstanceId: lease.instanceId,\n diagnostic: \"provider_not_found_during_home_route_rebind\",\n });\n if (marked.status === \"marked\") {\n await services.onHomeSandboxLost?.({\n sandboxGroupId: ids.sandboxGroupId,\n instanceId: lease.instanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n }\n throw new RoutingBackendRecoveryRequiredError(\n \"resolve_home_backend\",\n marked.lease?.leaseEpoch ?? lease.leaseEpoch,\n marked.status === \"stale\" ? \"superseded\" : homeRouteRecoveryDisposition(marked.lease),\n );\n }\n\n // The provider identity must agree with the exact durable lease row before\n // any caller can publish or route through this rebound handle. A mismatch is\n // unverifiable local state, not permission to try the old handle.\n const reboundBackend = sandboxBackendForSdkBackendId(rebound.backendId) ?? rebound.backendId;\n if (rebound.instanceId !== lease.instanceId || reboundBackend !== resumeBackend) {\n throw homeRouteRecoveryError(lease, lease.leaseEpoch);\n }\n services.onHomeSandboxRebound?.({\n established: rebound,\n leaseEpoch: lease.leaseEpoch,\n });\n // Keep the resolver's mutable home reference on the latest verified handle so\n // a later route epoch does not resume the same replacement again. This is only\n // a worker-side handle update; the SDK-facing RoutingSandboxSession remains the\n // stable object returned below and is never replaced.\n Object.assign(established, rebound);\n return {\n session: rebound.session as RoutableBackendSession,\n sandboxId: null,\n kind: rebound.backendId,\n leaseEpoch: lease.leaseEpoch,\n providerInstanceId: lease.instanceId,\n };\n}\n\nfunction beforePersistableHomeMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n home: { accountId: string; sandboxGroupId: string; backend: string } | undefined,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n }) => Promise<PersistableMutationAdmission | null>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!home || !fence) return undefined;\n return async ({ op, backend }) => {\n // A connected-machine target is intentionally non-persistable: its writes\n // do not dirty the session home's archive. Exact home identity metadata is\n // present only on a verified durable home route.\n if (\n backend.sandboxId !== null ||\n backend.leaseEpoch === undefined ||\n backend.providerInstanceId === undefined\n ) {\n return null;\n }\n const providerBinding =\n home.backend === \"modal\"\n ? await resolveModalCheckpointProviderBindingForSession(services.settings, backend.session)\n : null;\n const admission = await advanceWorkspaceGeneration(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: fence.turnId,\n executionGeneration: fence.executionGeneration,\n attemptId: fence.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(fence.attemptId),\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n operation: op,\n captureWaitMs: sandboxLifecycleTransitionWaitMs(services.settings),\n ...(services.waitSignal ? { waitSignal: services.waitSignal } : {}),\n });\n return { admission, providerBinding };\n };\n}\n\nfunction afterPersistableHomeMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n home: { accountId: string; sandboxGroupId: string; backend: string } | undefined,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n admission: unknown;\n outcome: \"resolved\" | \"rejected\";\n result?: unknown;\n retainedProcess?: RoutingRetainedProcess;\n }) => Promise<void | RoutingMutationSettlementResult>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!home || !fence) return undefined;\n return async ({ op, backend, admission, outcome, retainedProcess }) => {\n if (\n backend.sandboxId !== null ||\n backend.leaseEpoch === undefined ||\n backend.providerInstanceId === undefined ||\n !admission ||\n typeof admission !== \"object\"\n ) {\n return;\n }\n const boundAdmission = admission as Partial<PersistableMutationAdmission>;\n const exactAdmission = boundAdmission.admission;\n if (\n !exactAdmission ||\n typeof exactAdmission.id !== \"string\" ||\n typeof exactAdmission.workspaceGeneration !== \"number\" ||\n !(\"providerBinding\" in boundAdmission)\n ) {\n throw new Error(\"Persistable home mutation settlement lacked its bound admission\");\n }\n if (outcome === \"resolved\" && retainedProcess) {\n try {\n await retainWorkspaceMutationProcess(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: retainedProcess.id,\n providerSessionId: retainedProcess.providerSessionId,\n admissionId: exactAdmission.id,\n admittedWorkspaceGeneration: exactAdmission.workspaceGeneration,\n operation: op,\n providerBinding: boundAdmission.providerBinding ?? null,\n owner: {\n kind: \"turn\",\n turnId: fence.turnId,\n executionGeneration: fence.executionGeneration,\n attemptId: fence.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(fence.attemptId),\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n routeKind: exactAdmission.routeKind,\n routeTargetId: exactAdmission.routeTargetId,\n routeEpoch: exactAdmission.routeEpoch,\n },\n });\n } catch (error) {\n if (!(error instanceof SandboxRetainedProcessPromotionFencedError)) throw error;\n const durable = error.process;\n if (\n durable.id !== retainedProcess.id ||\n durable.providerSessionId !== retainedProcess.providerSessionId ||\n durable.sessionId !== ids.sessionId ||\n durable.sandboxGroupId !== home.sandboxGroupId ||\n durable.parentAdmissionId !== exactAdmission.id ||\n durable.leaseEpoch !== backend.leaseEpoch ||\n durable.providerInstanceId !== backend.providerInstanceId ||\n durable.routeKind !== exactAdmission.routeKind ||\n durable.routeTargetId !== exactAdmission.routeTargetId ||\n durable.routeEpoch !== exactAdmission.routeEpoch ||\n durable.state !== \"active\"\n ) {\n throw new Error(\"Durable retained-process promotion returned a mismatched identity\", {\n cause: error,\n });\n }\n return {\n status: \"retained_process_durable_output_rejected\",\n retainedProcess: {\n id: durable.id,\n providerSessionId: durable.providerSessionId,\n },\n };\n }\n return;\n }\n await verifyWorkspaceMutationSettlement(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: fence.turnId,\n executionGeneration: fence.executionGeneration,\n attemptId: fence.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(fence.attemptId),\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n admission: exactAdmission,\n operation: op,\n outcome,\n });\n };\n}\n\nfunction beforeRetainedProcessMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n }) => Promise<SandboxWorkspaceMutationAdmission>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ op, process }) =>\n await advanceWorkspaceGenerationForRetainedProcess(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n operation: op,\n captureWaitMs: sandboxLifecycleTransitionWaitMs(services.settings),\n ...(services.waitSignal ? { waitSignal: services.waitSignal } : {}),\n });\n}\n\nfunction afterRetainedProcessMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n admission: unknown;\n outcome: \"resolved\" | \"rejected\";\n result?: unknown;\n }) => Promise<void>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ op, process, admission, outcome }) => {\n if (\n !admission ||\n typeof admission !== \"object\" ||\n typeof (admission as Partial<SandboxWorkspaceMutationAdmission>).id !== \"string\" ||\n typeof (admission as Partial<SandboxWorkspaceMutationAdmission>).workspaceGeneration !==\n \"number\"\n ) {\n throw new Error(\"Retained-process mutation settlement lacked its exact admission\");\n }\n await verifyRetainedProcessMutationSettlement(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n admission: admission as SandboxWorkspaceMutationAdmission,\n operation: op,\n outcome,\n });\n };\n}\n\nfunction settleRetainedProcessForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n proof: RoutingRetainedProcessTerminalProof;\n }) => Promise<void>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ backend, process, proof }) => {\n const durable = await getRetainedProcess(services.db, {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n });\n if (\n !durable ||\n durable.providerSessionId !== process.providerSessionId ||\n durable.providerBackend !== backend.kind ||\n durable.providerInstanceId !== backend.providerInstanceId ||\n durable.leaseEpoch !== backend.leaseEpoch ||\n durable.routeKind !== (backend.sandboxId === null ? \"home\" : \"active\") ||\n durable.routeTargetId !== backend.sandboxId ||\n durable.routeEpoch !== backend.activeEpoch\n ) {\n throw new Error(\"Retained-process settlement lost its exact durable backend identity\");\n }\n await settleRetainedProcess(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n expected: retainedProcessSettlementIdentity(durable),\n outcome: proof.outcome,\n exitCode: proof.exitCode,\n reason: proof.reason,\n idleGraceMs: services.settings.sandboxIdleGraceMs,\n });\n };\n}\n\n/** Build the selfhosted `ControlRpc` over the events bus's request/reply\n * connection. A null bus / unconfigured NATS yields a NatsControlRpc whose\n * connection factory returns null → agent_offline on every op (never a throw). */\nfunction controlRpcFactory(bus: EventBus | undefined): () => ControlRpc {\n return () =>\n new NatsControlRpc(async (): Promise<NatsRequestConnection | null> => {\n if (!bus) {\n return null;\n }\n return bus.getRequestConnection();\n });\n}\n\n/**\n * Wrap an established group-box session in a `RoutingSandboxSession` so a mid-turn\n * swap routes the NEXT tool call to the new active sandbox. Returns the SAME\n * established handle with its `session` replaced by the stable proxy; the\n * client/sessionState/instanceId/backendId are preserved (the lease still owns\n * the group box's lifecycle — the proxy is a routing veneer, not an owner).\n *\n * The DEFAULT pointer (active_sandbox_id == null) routes to the established group\n * session unchanged (backward-compat). A swap to a selfhosted machine routes to a\n * SelfhostedSession bound to the target's enrollment agentId, fenced under the\n * swap's active_epoch.\n */\nexport function wrapTurnBoxWithRouting(\n services: TurnRoutingWiringServices,\n ids: RoutingWiringIds,\n established: EstablishedSandboxSession,\n): EstablishedSandboxSession {\n const { db, settings, bus, onOp } = services;\n const beforeMutation = beforePersistableHomeMutation(services, ids, ids.homeLease);\n const afterMutation = afterPersistableHomeMutation(services, ids, ids.homeLease);\n const beforeProcessMutation = beforeRetainedProcessMutation(services, ids);\n const afterProcessMutation = afterRetainedProcessMutation(services, ids);\n const settleProcess = settleRetainedProcessForTurn(services, ids);\n const resolver = makeActiveBackendResolver({\n workspaceId: ids.workspaceId,\n defaultBackend: established.session as RoutableBackendSession,\n defaultKind: established.backendId,\n getSandbox: async (sandboxId): Promise<RoutableSandbox | null> => {\n const sandbox = await getSandbox(db, ids.workspaceId, sandboxId);\n return sandbox\n ? {\n id: sandbox.id,\n kind: sandbox.kind,\n name: sandbox.name,\n enrollmentId: sandbox.enrollmentId,\n }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n resolveSelfhostedOpStream: async (sandbox) => {\n if (!sandbox.enrollmentId) return undefined;\n const enrollment = await getEnrollment(db, ids.workspaceId, sandbox.enrollmentId);\n return opStreamDepsFor(services, enrollment?.opStream === true);\n },\n relay: relayConfigFromSettings(settings),\n // A selfhosted swap target runs real commands too, so give it the same split\n // deadlines the machine-primary establish path uses (short control, long exec).\n ...selfhostedResolverTimeouts(settings),\n ...(onOp !== undefined ? { selfhostedOnOp: onOp } : {}),\n // The turn's declared environment → a selfhosted swap target's manifest, so the\n // SDK's per-turn manifest-env delta is empty (no \"cannot change manifest\n // environment variables\" throw when the turn pins to a vm). Mirrors the group\n // box, which is created WITH this same environment (resumeBoxForTurn).\n ...(ids.environment !== undefined ? { environment: ids.environment } : {}),\n // Stage D machine-primary: pin THIS established SelfhostedSession for the machine\n // pointer so the resolver returns the SAME instance (no two-instance manifest\n // divergence). `established.session` is the SelfhostedSession the establish branch\n // bound to (sandboxId, epoch).\n ...(ids.pinnedSelfhosted\n ? {\n pinnedSelfhosted: {\n sandboxId: ids.pinnedSelfhosted.sandboxId,\n epoch: ids.pinnedSelfhosted.epoch,\n session: established.session as RoutableBackendSession,\n },\n }\n : {}),\n // A modal swap target in the turn path would need its own lease resume-by-id;\n // that is a future cross-group-box concern. Until then a modal swap target is\n // unresolvable (the swap tool validates liveness, so this only triggers if a\n // session points at a sibling modal box the turn cannot resume here) and the\n // op surfaces unresolvable — never a silent wrong-box landing.\n //\n // For a machine-primary turn of a Modal-HOME session (pinned to a machine, no\n // group box established this turn), a mid-turn clear-to-null must NOT fall back to\n // the pinned machine — passing defaultIsHome:false makes the null branch throw typed\n // `home_unavailable_this_turn` instead. Forward the explicit boolean (including false).\n ...(ids.defaultIsHome !== undefined ? { defaultIsHome: ids.defaultIsHome } : {}),\n ...(ids.homeLease\n ? {\n resolveDefaultBackend: () =>\n resolveCurrentHomeBackend(\n services,\n {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n accountId: ids.homeLease!.accountId,\n sandboxGroupId: ids.homeLease!.sandboxGroupId,\n backend: ids.homeLease!.backend,\n },\n established,\n ),\n }\n : {}),\n });\n\n const proxy = new RoutingSandboxSession({\n // Seed the DEFAULT backend (the established group box) at construction so\n // `session.state` is the real backend's state object BEFORE the first op. The\n // SDK reads `session.state.manifest` at turn START (and writes it back); an\n // empty `{}` there crashes serializeManifestEnvironment /\n // validateProvidedSessionManifestUpdate. This is byte-identical to what the\n // resolver returns for the default pointer (`activeSandboxId === null`).\n defaultResolved: {\n session: established.session as RoutableBackendSession,\n sandboxId: null,\n kind: established.backendId,\n ...(ids.homeLease\n ? {\n leaseEpoch: ids.homeLease.leaseEpoch,\n providerInstanceId: ids.homeLease.instanceId,\n }\n : {}),\n },\n readPointer: async () => {\n if (!routingEnabled(settings)) {\n return { activeSandboxId: null, activeEpoch: 0 };\n }\n const pointer = await readActiveSandbox(db, ids.workspaceId, ids.sessionId);\n return pointer ?? { activeSandboxId: null, activeEpoch: 0 };\n },\n resolveActiveBackend: resolver,\n ...(services.onSandboxOperation ? { onOperation: services.onSandboxOperation } : {}),\n ...(beforeMutation ? { beforeMutation } : {}),\n ...(afterMutation ? { afterMutation } : {}),\n ...(beforeProcessMutation ? { beforeProcessMutation } : {}),\n ...(afterProcessMutation ? { afterProcessMutation } : {}),\n ...(settleProcess ? { settleProcess } : {}),\n ...(ids.homeLease\n ? {\n onDefaultBackendError: async ({\n error,\n backend,\n }: {\n error: unknown;\n backend: ResolvedActiveBackend;\n }) => {\n const home = ids.homeLease!;\n if (!isProviderSandboxGoneDuringRoutedOperation(home.backend, error)) return null;\n const expectedEpoch = backend.leaseEpoch ?? home.leaseEpoch;\n const expectedInstanceId = backend.providerInstanceId ?? home.instanceId;\n const marked = await markWarmLeaseInstanceLost(db, {\n accountId: home.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch,\n expectedInstanceId,\n diagnostic: \"provider_not_found_during_routed_operation\",\n });\n if (marked.status === \"marked\") {\n await services.onHomeSandboxLost?.({\n sandboxGroupId: home.sandboxGroupId,\n instanceId: expectedInstanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n }\n const lease = marked.lease;\n const restore = lease?.recovery.restore.status;\n return {\n leaseEpoch: lease?.leaseEpoch ?? expectedEpoch,\n recovery:\n marked.status === \"stale\"\n ? (\"superseded\" as const)\n : restore === \"pending\"\n ? (\"pending\" as const)\n : restore === \"degraded\"\n ? (\"degraded\" as const)\n : (\"unrecoverable\" as const),\n };\n },\n }\n : {}),\n });\n\n return { ...established, session: proxy };\n}\n\nexport function wrapLazyTurnBoxWithRouting(\n services: TurnRoutingWiringServices,\n ids: RoutingWiringIds,\n args: {\n client: EstablishedSandboxSession[\"client\"];\n backendId: string;\n agentDefaultManifest: unknown;\n provisioner: {\n get(): Promise<{\n established: EstablishedSandboxSession;\n leaseEpoch?: number;\n }>;\n };\n homeLeaseIdentity?: {\n accountId: string;\n sandboxGroupId: string;\n backend: string;\n };\n },\n): EstablishedSandboxSession {\n const { db, settings, bus, onOp } = services;\n const beforeMutation = beforePersistableHomeMutation(services, ids, args.homeLeaseIdentity);\n const afterMutation = afterPersistableHomeMutation(services, ids, args.homeLeaseIdentity);\n const beforeProcessMutation = beforeRetainedProcessMutation(services, ids);\n const afterProcessMutation = afterRetainedProcessMutation(services, ids);\n const settleProcess = settleRetainedProcessForTurn(services, ids);\n const defaultBackend = sandboxBackendForSdkBackendId(args.backendId);\n const defaultSupportsPty = defaultBackend\n ? selectBackend(defaultBackend).capabilities.Terminal.pty\n : false;\n const syntheticSession: RoutableBackendSession = {\n state: { manifest: args.agentDefaultManifest },\n // The SDK binds shell tools synchronously before lazy provisioning. Preserve\n // the authoritative descriptor's PTY shape so a Modal home exposes\n // write_stdin on its first turn operation; the async cancellation transport\n // below still resolves the exact live route before executing a command.\n supportsPty: () => defaultSupportsPty,\n };\n const routedResolver = makeActiveBackendResolver({\n workspaceId: ids.workspaceId,\n defaultBackend: syntheticSession,\n defaultKind: \"unprovisioned\",\n getSandbox: async (sandboxId): Promise<RoutableSandbox | null> => {\n const sandbox = await getSandbox(db, ids.workspaceId, sandboxId);\n return sandbox\n ? {\n id: sandbox.id,\n kind: sandbox.kind,\n name: sandbox.name,\n enrollmentId: sandbox.enrollmentId,\n }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n resolveSelfhostedOpStream: async (sandbox) => {\n if (!sandbox.enrollmentId) return undefined;\n const enrollment = await getEnrollment(db, ids.workspaceId, sandbox.enrollmentId);\n return opStreamDepsFor(services, enrollment?.opStream === true);\n },\n relay: relayConfigFromSettings(settings),\n ...selfhostedResolverTimeouts(settings),\n ...(onOp !== undefined ? { selfhostedOnOp: onOp } : {}),\n ...(ids.environment !== undefined ? { environment: ids.environment } : {}),\n });\n\n const proxy = new RoutingSandboxSession({\n // Before the first op the SDK reads `state.manifest`; the synthetic backend\n // points at agent.defaultManifest BY REFERENCE so the provided-session delta is\n // empty. The first default-pointer op resolves the real box through the\n // provisioner and `state` switches to that real backend by reference.\n defaultResolved: {\n session: syntheticSession,\n sandboxId: null,\n kind: \"unprovisioned\",\n },\n readPointer: async () => {\n const pointer = await readActiveSandbox(db, ids.workspaceId, ids.sessionId);\n return pointer ?? { activeSandboxId: null, activeEpoch: 0 };\n },\n resolveActiveBackend: async (pointer) => {\n if (pointer.activeSandboxId === null || !routingEnabled(settings)) {\n const provisioned = await args.provisioner.get();\n if (args.homeLeaseIdentity && provisioned.leaseEpoch !== undefined) {\n return resolveCurrentHomeBackend(\n services,\n {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n accountId: args.homeLeaseIdentity.accountId,\n sandboxGroupId: args.homeLeaseIdentity.sandboxGroupId,\n backend: args.homeLeaseIdentity.backend,\n },\n provisioned.established,\n );\n }\n return {\n session: provisioned.established.session as RoutableBackendSession,\n sandboxId: null,\n kind: provisioned.established.backendId,\n };\n }\n return routedResolver(pointer);\n },\n ...(services.onSandboxOperation ? { onOperation: services.onSandboxOperation } : {}),\n ...(beforeMutation ? { beforeMutation } : {}),\n ...(afterMutation ? { afterMutation } : {}),\n ...(beforeProcessMutation ? { beforeProcessMutation } : {}),\n ...(afterProcessMutation ? { afterProcessMutation } : {}),\n ...(settleProcess ? { settleProcess } : {}),\n ...(args.homeLeaseIdentity\n ? {\n onDefaultBackendError: async ({\n error,\n backend,\n }: {\n error: unknown;\n backend: ResolvedActiveBackend;\n }) => {\n const home = args.homeLeaseIdentity!;\n if (!isProviderSandboxGoneDuringRoutedOperation(home.backend, error)) return null;\n if (backend.leaseEpoch === undefined || backend.providerInstanceId === undefined) {\n return null;\n }\n const marked = await markWarmLeaseInstanceLost(db, {\n accountId: home.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n diagnostic: \"provider_not_found_during_routed_operation\",\n });\n if (marked.status === \"marked\") {\n await services.onHomeSandboxLost?.({\n sandboxGroupId: home.sandboxGroupId,\n instanceId: backend.providerInstanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n }\n const lease = marked.lease;\n const restore = lease?.recovery.restore.status;\n return {\n leaseEpoch: lease?.leaseEpoch ?? backend.leaseEpoch,\n recovery:\n marked.status === \"stale\"\n ? (\"superseded\" as const)\n : restore === \"pending\"\n ? (\"pending\" as const)\n : restore === \"degraded\"\n ? (\"degraded\" as const)\n : (\"unrecoverable\" as const),\n };\n },\n }\n : {}),\n });\n\n return {\n client: args.client,\n session: proxy,\n sessionState: undefined,\n instanceId: \"unprovisioned\",\n backendId: args.backendId,\n };\n}\n\nexport type SelfhostedTurnSessionArgs = {\n workspaceId: string;\n /** The target machine's enrollment id == the agent subject id. */\n agentId: string;\n /** Whether the target machine advertised Capabilities.op_stream in its latest\n * Hello. The runtime-side transport gate must still require the server flag. */\n opStream: boolean;\n /** The active pointer's epoch — the control-op fence echoed to the agent. */\n epoch: number;\n /** The run's declared sandbox environment (the SAME object fed to buildAgent +\n * the manifest), threaded so the SDK's per-turn provided-session env delta is\n * empty. */\n environment: Record<string, string>;\n /** The session working directory (per-session pointer). Null ⇒ workspace_root. */\n workingDir: string | null;\n};\n\n/**\n * Stage D machine-primary establish: bind the live SelfhostedSession for a turn\n * whose ACTIVE sandbox is a connected machine — WITHOUT establishing or leasing a\n * phantom Modal home box. Reuses the SAME relay + ControlRpc wiring `wrapTurnBoxWithRouting`\n * builds (so the turn session and a later swap target dial the machine identically),\n * and the SAME `buildSelfhostedBackendSession` factory the routing resolver uses\n * (one build shape). Returns an `EstablishedSandboxSession` whose:\n * - `client` is the SelfhostedSandboxClient (the OWNED-sandbox client the turn\n * injects; its `serializeSessionState` round-trips `{agentId}`);\n * - `session` is the live SelfhostedSession (the routing default + pin instance);\n * - `backendId` is \"selfhosted\" (drives recording's desktopCapableBackend gate +\n * the warm-rate keying) and `instanceId` is the enrollment/agent id.\n * No NATS round-trip happens here — `resume()` just re-addresses the subject — so a\n * headless/offline machine binds fine; its ops surface agent_offline lazily.\n */\n/**\n * The op-stream injection for a machine-primary turn: present iff the machine\n * advertised `Capabilities.op_stream` in its latest Hello AND the server flag\n * is on AND a bus exists to carry frames. The transport rides the SAME managed\n * NATS connection as the control rpc (the bus's op-stream accessor). A bus\n * without the accessor yields no stream; an unbounded exec then fails before\n * starting instead of silently degrading to request/reply. Swap targets resolve\n * the same enrollment capability through the injected backend-resolver seam.\n */\nfunction opStreamDepsFor(\n services: RoutingWiringServices,\n machineAdvertisesOpStream: boolean,\n): SelfhostedOpStreamDeps | undefined {\n const { settings, bus, opJournal } = services;\n if (!machineAdvertisesOpStream || settings.agentOpStreamEnabled !== true || !bus) {\n return undefined;\n }\n return {\n transport: new NatsOpStreamTransport(async () => bus.getOpStreamConnection?.() ?? null),\n ...(opJournal !== undefined ? { journal: opJournal } : {}),\n };\n}\n\nexport async function establishSelfhostedTurnSession(\n services: RoutingWiringServices,\n args: SelfhostedTurnSessionArgs,\n): Promise<EstablishedSandboxSession> {\n const { settings, bus, onOp } = services;\n const { timeoutMs, execTimeoutMs } = selfhostedTimeoutsFromSettings(settings);\n const opStream = opStreamDepsFor(services, args.opStream);\n const { client, session } = await buildSelfhostedBackendSession({\n workspaceId: args.workspaceId,\n agentId: args.agentId,\n relay: relayConfigFromSettings(settings),\n controlRpcFactory: controlRpcFactory(bus),\n epoch: args.epoch,\n environment: args.environment,\n workingDir: args.workingDir,\n // Give this turn's exec ops the long deadline (control ops stay short) so a real\n // command is not killed at the control wall.\n timeoutMs,\n execTimeoutMs,\n // Meter every control op (out-of-band telemetry) — no-op when unwired.\n ...(onOp !== undefined ? { onOp } : {}),\n // The streaming exec transport — present iff the machine advertised the\n // capability AND the server flag is on. It is required when execTimeoutMs=0;\n // legacy request/reply remains available only for explicitly bounded exec.\n ...(opStream !== undefined ? { opStream } : {}),\n });\n return {\n client,\n session,\n sessionState: { agentId: args.agentId },\n instanceId: args.agentId,\n backendId: \"selfhosted\",\n };\n}\n\n/** Whether the routing proxy should wrap the turn box: the hot-swap feature is\n * gated by the selfhosted flag (the active pointer + swap tools are only\n * meaningful when selfhosted is enabled). With the flag off the established\n * group box is injected unchanged — byte-for-byte today. */\nexport function routingEnabled(settings: Settings): boolean {\n return settings.sandboxSelfhostedEnabled === true;\n}\n\n/** Whether the turn should defer sandbox provisioning to the first dispatched op\n * (the in-process single-flight provisioner behind the routing proxy's\n * resolveActiveBackend). Lazy is a property of the OWNED path only — the SDK never\n * creates/resumes an injected session, so we own establish timing — hence gated on\n * BOTH flags. With either off the turn provisions eagerly at turn start, exactly as\n * today. NB: under lazy the box is ALWAYS wrapped in the routing proxy (the proxy's\n * resolver IS the establish seam), independent of `routingEnabled`. */\nexport function lazyProvisionEnabled(settings: Settings): boolean {\n return settings.sandboxLazyProvisionEnabled === true && settings.sandboxOwnershipEnabled === true;\n}\n","import type {\n ResourceRef,\n SessionStatus,\n SessionSystemUpdatePayload,\n ToolRef,\n} from \"@opengeni/contracts\";\n\nexport {\n mergeResourceRefs,\n mergeToolRefs,\n reasoningEffortForMetadata as reasoningEffortForSession,\n} from \"@opengeni/contracts\";\n\n/**\n * Refuse to revive a terminal reusable session on a scheduled fire. Mirrors the\n * API-level guard in apps/api/src/domain/sessions.ts (post a user message ->\n * 409 when cancelled): \"cancelled\" is the one terminal state, an explicit user\n * act, so a recurring task must NOT silently resurrect and re-bill it. Failed\n * and idle sessions stay revivable (talking to a session is how it resumes), so\n * only \"cancelled\" is rejected. Throwing inside the FOR UPDATE locked-update\n * callback aborts the whole append+enqueue transaction atomically, and the\n * dispatch catch marks the scheduled_task_run \"failed\" rather than dispatched.\n */\nexport function assertReusableSessionRevivable(status: SessionStatus): void {\n if (status === \"cancelled\") {\n throw new Error(\"reusable session is cancelled; refusing to revive on scheduled fire\");\n }\n}\n\nexport function scheduledUserMessagePayload(\n prompt: string,\n resources: ResourceRef[],\n tools: ToolRef[],\n taskId: string,\n runId: string,\n): Extract<SessionSystemUpdatePayload, { type: \"scheduled_occurrence\" }> {\n return {\n type: \"scheduled_occurrence\",\n text: prompt,\n scheduledTaskId: taskId,\n scheduledTaskRunId: runId,\n ...(resources.length ? { resources } : {}),\n ...(tools.length ? { tools } : {}),\n };\n}\n\nexport function workflowIdForSession(sessionId: string): string {\n return `session-${sessionId}`;\n}\n"],"mappings":";;;;;AAAA,SAAS,cAAc,aAAa,mCAAmC;AACvE,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AAY7B,SAAS,6BACd,cACuC;AACvC,MAAI,kBAA0D;AAE9D,SAAO,eAAe,WAA4C;AAChE,yBAAqB,YAAY;AAC/B,YAAM,WAAW,aAAa,YAAY,YAAY;AACtD,YAAM,gBACJ,aAAa,iB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ACA,iBAAAG;AAAA,EAC8B,8BAA9BC;AAAA,OACK;AAYA,SAAS,+BAA+B,QAA6B;AAC1E,MAAI,WAAW,aAAa;AAC1B,UAAM,IAAI,MAAM,qEAAqE;AAAA,EACvF;AACF;AAEO,SAAS,4BACd,QACA,WACA,OACA,QACA,OACuE;AACvE,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM;AAAA,IACN,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,IACpB,GAAI,UAAU,SAAS,EAAE,UAAU,IAAI,CAAC;AAAA,IACxC,GAAI,MAAM,SAAS,EAAE,MAAM,IAAI,CAAC;AAAA,EAClC;AACF;AAEO,SAAS,qBAAqB,WAA2B;AAC9D,SAAO,WAAW,SAAS;AAC7B;","names":["chosen","getSessionGoal","resumeEnvelope","sandboxLifecycleTransitionWaitMs","markWarmLeaseInstanceLost","readLease","establishSandboxSessionFromEnvelope","isProviderSandboxNotFoundError","resolveModalCheckpointProviderBindingForSession","verifySandboxExecReadiness","readLease","establishSandboxSessionFromEnvelope","verifySandboxExecReadiness","isProviderSandboxNotFoundError","markWarmLeaseInstanceLost","resolveModalCheckpointProviderBindingForSession","sandboxLifecycleTransitionWaitMs","mergeToolRefs","reasoningEffortForMetadata"]}