@opengeni/worker-bundle 3.3.0 → 3.4.0

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 (35) hide show
  1. package/dist/{activities-control-G2W4FEFP.js → activities-control-EWP3UDZP.js} +5 -5
  2. package/dist/{activities-turn-CE2VIWIS.js → activities-turn-COUX2R3A.js} +16 -4
  3. package/dist/activities-turn-COUX2R3A.js.map +1 -0
  4. package/dist/artifact-materializer-entry.js +1 -0
  5. package/dist/artifact-materializer-entry.js.map +1 -1
  6. package/dist/artifact-outbox-entry.js +3 -1
  7. package/dist/artifact-outbox-entry.js.map +1 -1
  8. package/dist/{chunk-5NNS4327.js → chunk-BX3KRGDM.js} +10 -4
  9. package/dist/{chunk-5NNS4327.js.map → chunk-BX3KRGDM.js.map} +1 -1
  10. package/dist/{chunk-5DF4V5RD.js → chunk-PFCSGZGA.js} +7 -4
  11. package/dist/{chunk-5DF4V5RD.js.map → chunk-PFCSGZGA.js.map} +1 -1
  12. package/dist/{chunk-RSI63RZG.js → chunk-PG66GHGH.js} +3 -3
  13. package/dist/{chunk-R5BHILMQ.js → chunk-XUIWRRTY.js} +5 -4
  14. package/dist/chunk-XUIWRRTY.js.map +1 -0
  15. package/dist/editable-artifact-outbox-dispatcher.d.ts +2 -0
  16. package/dist/index.js +30 -5
  17. package/dist/index.js.map +1 -1
  18. package/dist/internal-maintenance.d.ts +3 -1
  19. package/dist/observability-metrics.d.ts +14 -0
  20. package/dist/{sandbox-lease-2IV3DNXR.js → sandbox-lease-XBZWILZ3.js} +4 -4
  21. package/package.json +26 -26
  22. package/src/activities/agent-turn/run.ts +15 -0
  23. package/src/activity-services.ts +3 -0
  24. package/src/editable-artifact-materializer-service.ts +3 -0
  25. package/src/editable-artifact-outbox-dispatcher.ts +5 -0
  26. package/src/editable-artifact-outbox-service.ts +3 -0
  27. package/src/index.ts +6 -0
  28. package/src/internal-maintenance.ts +24 -0
  29. package/src/observability-metrics.ts +20 -3
  30. package/src/sandbox-routing.ts +3 -0
  31. package/dist/activities-turn-CE2VIWIS.js.map +0 -1
  32. package/dist/chunk-R5BHILMQ.js.map +0 -1
  33. /package/dist/{activities-control-G2W4FEFP.js.map → activities-control-EWP3UDZP.js.map} +0 -0
  34. /package/dist/{chunk-RSI63RZG.js.map → chunk-PG66GHGH.js.map} +0 -0
  35. /package/dist/{sandbox-lease-2IV3DNXR.js.map → sandbox-lease-XBZWILZ3.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sandbox-snapshot-diagnostics.ts","../src/session-event-fanout.ts","../src/sandbox-archive-storage.ts","../src/sandbox-resume.ts","../src/warm-capture-holder.ts","../src/sandbox-routing.ts"],"sourcesContent":["import { sandboxLeaseTelemetryKey, type Observability } from \"@opengeni/observability\";\n\ntype SafeSnapshotError = {\n errorClass: \"SnapshotOperationError\";\n errorCode: \"snapshot_operation_failed\";\n status?: number;\n origin: \"sandbox-resume\" | \"worker-lifecycle\";\n causeName?: string;\n integrityCode?: string;\n providerErrorName?: string;\n providerGrpcCode?: number;\n providerHttpStatus?: number;\n providerRetryable?: boolean;\n};\n\nexport function safeSnapshotError(\n error: unknown,\n origin: SafeSnapshotError[\"origin\"] = \"sandbox-resume\",\n): SafeSnapshotError {\n const fields: SafeSnapshotError = {\n errorClass: \"SnapshotOperationError\",\n errorCode: \"snapshot_operation_failed\",\n origin,\n };\n try {\n if (error && typeof error === \"object\") {\n const candidate = error as {\n name?: unknown;\n code?: unknown;\n status?: unknown;\n statusCode?: unknown;\n };\n if (\n typeof candidate.name === \"string\" &&\n /^[A-Z][A-Za-z0-9]{2,62}Error$/u.test(candidate.name)\n ) {\n fields.causeName = candidate.name;\n }\n if (typeof candidate.code === \"string\" && /^[a-z0-9_]{1,64}$/u.test(candidate.code)) {\n fields.integrityCode = candidate.code;\n }\n const status = Number(candidate.status ?? candidate.statusCode);\n if (Number.isInteger(status) && status >= 100 && status <= 599) fields.status = status;\n }\n } catch {\n // Diagnostics must never replace the exact internal snapshot failure.\n }\n // The SDK wraps provider classification in details, not Error.cause. Never\n // project free-form messages, causes, request IDs or payloads. Read fields\n // independently so a hostile getter cannot hide other safe classifications.\n const read = (value: unknown, key: string): unknown => {\n try {\n return value && typeof value === \"object\" ? Reflect.get(value, key) : undefined;\n } catch {\n return undefined;\n }\n };\n const details = read(error, \"details\");\n const providerName = read(details, \"errorName\");\n if (\n typeof providerName === \"string\" &&\n [\n \"ClientError\",\n \"TimeoutError\",\n \"ConnectionError\",\n \"AuthError\",\n \"NotFoundError\",\n \"InvalidError\",\n \"RemoteError\",\n \"AbortError\",\n ].includes(providerName)\n )\n fields.providerErrorName = providerName;\n const grpcCode = read(details, \"errorCode\");\n if (\n providerName === \"ClientError\" &&\n typeof grpcCode === \"number\" &&\n Number.isInteger(grpcCode) &&\n grpcCode >= 0 &&\n grpcCode <= 16\n )\n fields.providerGrpcCode = grpcCode;\n for (const key of [\"status\", \"httpStatus\", \"responseStatus\"]) {\n const status = read(details, key);\n if (typeof status === \"number\" && Number.isInteger(status) && status >= 100 && status <= 599) {\n fields.providerHttpStatus = status;\n break;\n }\n }\n const retryable = read(error, \"retryable\");\n if (typeof retryable === \"boolean\") fields.providerRetryable = retryable;\n return fields;\n}\n\nexport function warnDrainSnapshotFailure(\n observability: Pick<Observability, \"warn\">,\n message: string,\n error: unknown,\n lease: { workspaceId?: string; sandboxGroupId: string; leaseEpoch: number },\n): void {\n try {\n observability.warn(message, {\n ...safeSnapshotError(error, \"worker-lifecycle\"),\n ...(lease.workspaceId\n ? { sandboxLeaseKey: sandboxLeaseTelemetryKey(lease.workspaceId, lease.sandboxGroupId) }\n : {}),\n leaseEpoch: lease.leaseEpoch,\n });\n } catch {\n // Logging cannot replace the provider failure or prevent claim release.\n }\n}\n","import type { SessionEvent } from \"@opengeni/contracts\";\nimport type { EventBus } from \"@opengeni/events\";\n\n/** Best-effort live fanout of events that are already durable, grouped by\n * session. Durable catch-up remains the source of truth, so failures are only\n * reported. */\nexport async function publishDurableSessionEvents(\n bus: EventBus | null | undefined,\n workspaceId: string,\n events: readonly SessionEvent[] | undefined,\n onError: (error: unknown) => void = () => undefined,\n): Promise<void> {\n if (!bus || !events?.length) return;\n for (const sessionId of new Set(events.map((event) => event.sessionId))) {\n await bus\n .publish(\n workspaceId,\n sessionId,\n events.filter((event) => event.sessionId === sessionId),\n )\n .catch(onError);\n }\n}\n","import { uploadWorkspaceArchiveSpool, type ObjectStorage } from \"@opengeni/storage\";\nimport { randomUUID } from \"node:crypto\";\nimport type { VerifiedHostWorkspaceArchive } from \"@opengeni/runtime/sandbox\";\nimport {\n parseWorkspaceArchiveObjectRef,\n workspaceArchiveObjectKey,\n type WorkspaceArchiveDescriptor,\n type WorkspaceArchiveObjectRef,\n} from \"@opengeni/contracts\";\n\nexport class WorkspaceArchiveObjectStorageRequiredError extends Error {\n readonly code = \"workspace_archive_object_storage_required\" as const;\n\n constructor(backend: string) {\n super(`${backend} workspace archives require object storage`);\n this.name = \"WorkspaceArchiveObjectStorageRequiredError\";\n }\n}\n\nexport function collectWorkspaceArchiveObjectKeys(\n resumeState: Record<string, unknown> | null | undefined,\n): Set<string> {\n const sessionState =\n resumeState?.sessionState && typeof resumeState.sessionState === \"object\"\n ? (resumeState.sessionState as Record<string, unknown>)\n : null;\n const keys = new Set<string>();\n for (const value of [sessionState?.workspaceArchiveRef, sessionState?.workspaceArchivePrevRef]) {\n const ref = parseWorkspaceArchiveObjectRef(value);\n if (ref) keys.add(ref.key);\n }\n return keys;\n}\n\nexport async function putTarWorkspaceArchiveObject(input: {\n objectStorage: ObjectStorage;\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n archive:\n | { bytes: Uint8Array; descriptor: WorkspaceArchiveDescriptor }\n | VerifiedHostWorkspaceArchive;\n}): Promise<WorkspaceArchiveObjectRef> {\n // Snapshot caller-owned metadata before any provider callback can mutate it.\n const descriptor = structuredClone(input.archive.descriptor);\n if (descriptor.version !== 1) {\n throw new Error(\"Object-storage workspace archives are portable tar only\");\n }\n const key = workspaceArchiveObjectKey({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n revision: descriptor.revision,\n uploadId: randomUUID(),\n });\n const archive = input.archive;\n if (\"spool\" in archive) {\n if (\n archive.spool.byteSize !== descriptor.archiveBytes ||\n archive.spool.sha256 !== descriptor.archiveSha256\n ) {\n throw new Error(\"Workspace archive spool does not match its verified descriptor\");\n }\n }\n const source =\n \"spool\" in archive\n ? archive.spool\n : {\n path: \"\",\n byteSize: archive.bytes.byteLength,\n sha256: descriptor.archiveSha256,\n async *open() {\n for (let offset = 0; offset < archive.bytes.length; offset += 1024 * 1024)\n yield archive.bytes.subarray(offset, offset + 1024 * 1024);\n },\n async dispose() {},\n };\n try {\n await uploadWorkspaceArchiveSpool(input.objectStorage, key, {\n ...source,\n byteSize: descriptor.archiveBytes,\n sha256: descriptor.archiveSha256,\n open: source.open.bind(source),\n });\n } catch (error) {\n // This fresh locator has never been offered to database publication. An\n // ambiguous provider upload can leave an orphan, never overwrite a retained\n // archive or justify deleting another attempt's object.\n await input.objectStorage.deleteObject(key).catch(() => undefined);\n throw error;\n }\n return {\n schema: \"sandbox_archive_object_v1\",\n key,\n sha256: descriptor.archiveSha256,\n bytes: descriptor.archiveBytes,\n backend: input.objectStorage.backend,\n };\n}\n\n/** The caller owns a fresh candidate returned by this module. A thrown or lost\n * database response is UNKNOWN: it may have committed, so never delete on catch.\n * Only the transaction's exact candidate disposition can authorize cleanup. */\nexport async function persistWorkspaceArchiveCandidate<\n T extends {\n wrote: boolean;\n candidateDisposition?: \"adopted\" | \"already_referenced\" | \"unused\";\n },\n>(input: {\n objectStorage?: ObjectStorage | null;\n ref?: WorkspaceArchiveObjectRef;\n persist: () => Promise<T>;\n}): Promise<T> {\n const objectStorage = input.objectStorage;\n const ref = input.ref ? { ...input.ref } : undefined;\n const result = await input.persist();\n if (objectStorage && ref && result.candidateDisposition === \"unused\") {\n await deleteUnpublishedWorkspaceArchiveObject(objectStorage, ref);\n }\n return result;\n}\n\nexport async function putVersion1TarArchiveOrInline(input: {\n backend: string;\n objectStorage?: ObjectStorage | null | undefined;\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n archive:\n | VerifiedHostWorkspaceArchive\n | {\n bytes: Uint8Array;\n descriptor: WorkspaceArchiveDescriptor;\n base64: string;\n };\n metrics?: {\n onWorkspaceArchiveObject?: (input: {\n outcome: \"put\" | \"put_failed\" | \"deleted_unpublished\";\n backend: string;\n }) => void;\n };\n}): Promise<{\n workspaceArchive?: string;\n workspaceArchiveRef?: WorkspaceArchiveObjectRef;\n}> {\n if (input.archive.descriptor.version !== 1) {\n if (\"spool\" in input.archive) throw new Error(\"Native snapshots cannot use a portable spool\");\n return { workspaceArchive: input.archive.base64 };\n }\n if (input.backend === \"opensandbox\" && !input.objectStorage) {\n throw new WorkspaceArchiveObjectStorageRequiredError(\"opensandbox\");\n }\n if (!input.objectStorage) {\n if (\"spool\" in input.archive)\n throw new WorkspaceArchiveObjectStorageRequiredError(input.backend);\n return { workspaceArchive: input.archive.base64 };\n }\n try {\n const workspaceArchiveRef = await putTarWorkspaceArchiveObject({\n objectStorage: input.objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n archive: input.archive,\n });\n try {\n input.metrics?.onWorkspaceArchiveObject?.({\n outcome: \"put\",\n backend: input.objectStorage.backend,\n });\n } catch {\n /* metrics must not affect persist */\n }\n console.info(\"workspace archive object put\", {\n key: workspaceArchiveRef.key,\n bytes: workspaceArchiveRef.bytes,\n sha256: workspaceArchiveRef.sha256,\n });\n return { workspaceArchiveRef };\n } catch (error) {\n try {\n input.metrics?.onWorkspaceArchiveObject?.({\n outcome: \"put_failed\",\n backend: input.objectStorage.backend,\n });\n } catch {\n /* metrics must not affect persist */\n }\n throw error;\n }\n}\n\nexport async function deleteUnpublishedWorkspaceArchiveObject(\n objectStorage: ObjectStorage | null | undefined,\n ref: WorkspaceArchiveObjectRef | undefined,\n metrics?: {\n onWorkspaceArchiveObject?: (input: { outcome: \"deleted_unpublished\"; backend: string }) => void;\n },\n): Promise<void> {\n if (!objectStorage || !ref) return;\n try {\n await objectStorage.deleteObject(ref.key);\n try {\n metrics?.onWorkspaceArchiveObject?.({\n outcome: \"deleted_unpublished\",\n backend: objectStorage.backend,\n });\n } catch {\n /* metrics must not affect persist */\n }\n } catch {\n console.error(\"unpublished workspace archive object delete failed\", { key: ref.key });\n }\n}\n\nexport async function deleteWorkspaceArchiveObjectKeys(\n objectStorage: ObjectStorage,\n keys: Iterable<string>,\n): Promise<void> {\n for (const key of keys) {\n await objectStorage.deleteObject(key);\n }\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// viewers and managed ComputerSession operations initialize it 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 type { EventBus } from \"@opengeni/events\";\nimport { publishDurableSessionEvents } from \"./session-event-fanout\";\nimport {\n effectiveSandboxLifecycle,\n sandboxArchiveCaptureTimeoutMs,\n sandboxLifecycleTransitionWaitMs,\n sandboxWarmRateMicrosPerSecond,\n type Settings,\n} from \"@opengeni/config\";\nimport { randomUUID } from \"node:crypto\";\nimport { retainsHolderForWarmCapture } from \"./warm-capture-holder\";\nimport {\n acquireLease,\n adoptLegacyModalCheckpointArtifact,\n beginSandboxRematerialization,\n sessionHoldsFreshWorkspaceRecovery,\n claimWorkspaceArchiveCapture,\n commitWarmingToWarm,\n failSandboxRematerialization,\n failWarmingToCold,\n beginModalProviderCreate,\n getSandboxSessionEnvelope,\n heartbeatLeaseHolderStatus,\n markSandboxRestoreVerifying,\n markWarmLeaseInstanceLost,\n markSandboxCheckpointArtifactDeletePending,\n persistWarmSnapshot,\n readLease,\n registerSandboxCheckpointArtifact,\n recordWarmingSandboxCreated,\n reinstateTurnLeaseHolder,\n leaseMayHaveUntrackedWriters,\n releaseWorkspaceArchiveCapture,\n releaseLeaseHolder,\n touchLeaseHolder,\n SandboxLeaseRecoveryBlockedError,\n SandboxLeaseSupersededError,\n SandboxLeaseTransitionError,\n type Database,\n type LeaseHolderKind,\n} from \"@opengeni/db\";\nimport {\n captureWorkspaceArchiveForStorage,\n disposeWorkspaceArchive,\n type VerifiedWorkspaceArchivePayload,\n describeLegacyNativeSnapshotArchive,\n inlineWorkspaceArchiveForRestore,\n MODAL_EXEC_READINESS_TIMEOUT_MS,\n SandboxExecReadinessError,\n WorkspaceArchiveIntegrityError,\n establishSandboxSessionFromEnvelope,\n isProviderSandboxNotFoundError,\n parseWorkspaceArchiveDescriptor,\n providerWorkspaceCapturePolicy,\n SandboxProviderContinuityUnavailableError,\n requirePersistableReplacementSandboxEnvelope,\n renewSandboxProviderExpiration,\n modalSessionMatchesCheckpointProviderBinding,\n resolveModalCheckpointProviderBindingForSession,\n serializeReplacementSandboxEnvelope,\n tagModalSandbox,\n terminateUnpublishedSandboxSession,\n verifySandboxExecReadiness,\n withoutSandboxProviderIdentity,\n workspaceArchiveDownloadTemporaryDirectory,\n type EstablishedSandboxSession,\n type RuntimeMetricsHooks,\n type WorkspaceCaptureSkipReason,\n type SandboxReadinessReplacementOutcome,\n type WorkspaceArchiveDescriptor,\n} from \"@opengeni/runtime\";\nimport {\n downloadWorkspaceArchiveSpool,\n WorkspaceArchiveStorageError,\n type ObjectStorage,\n} from \"@opengeni/storage\";\nimport { sandboxLeaseTelemetryKey, type Observability } from \"@opengeni/observability\";\nimport { safeSnapshotError } from \"./sandbox-snapshot-diagnostics\";\nexport { safeSnapshotError } from \"./sandbox-snapshot-diagnostics\";\nimport { parseWorkspaceArchiveObjectRef } from \"@opengeni/contracts\";\nimport {\n persistWorkspaceArchiveCandidate,\n putVersion1TarArchiveOrInline,\n} from \"./sandbox-archive-storage\";\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 objectStorage?: ObjectStorage | null;\n\n logicalFallbackSettings?: Settings;\n sandboxMetrics?: RuntimeMetricsHooks;\n /** Structured logger for lifecycle decisions (holder release reasons). Falls\n * back to the console when a lean caller passes none. */\n observability?: Pick<Observability, \"info\" | \"warn\">;\n /** Test seam only: cadence of the private holder-liveness loop (default 10 s).\n * Production keeps the default; the dead-worker reap horizon assumes it. */\n holderLivenessIntervalMs?: number;\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 /** Test seam for the bounded command-readiness proof the elected spawner runs\n * on its freshly created box before publishing the lease warm. Production\n * uses {@link waitForSandboxExecReadiness} with the shared 60 s budget. */\n verifySpawnedSandboxReadiness?: (\n established: EstablishedSandboxSession,\n identity: { sandboxGroupId: string },\n ) => Promise<void>;\n /** Test seam for the jittered pause before the single fresh-box readiness\n * replacement. Production uses {@link freshSandboxReadinessReplacementDelayMs}.\n * It may be async so a test can observe the rolled-back lease in between. */\n freshSandboxReadinessReplacementDelayMs?: () => number | Promise<number>;\n /** Test seam: runs immediately after the elected spawner published its box\n * warm, before the final cancellation check. */\n onSpawnedSandboxPublished?: () => void | Promise<void>;\n /**\n * The turn attempt's fresh-box readiness replacement budget. The lazy\n * provisioner may call resumeBoxForTurn again after a typed lease\n * supersession, so the turn creates the budget once and shares it with every\n * call. Absent, the call gets its own single replacement.\n */\n freshSandboxReadinessReplacementBudget?: FreshSandboxReadinessReplacementBudget;\n /** Live fanout for background commands a provider loss settled. */\n bus?: EventBus | null;\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: Settings[\"sandboxBackend\"];\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 /** Deployment/workspace image pins apply only to new creates; an existing\n * group keeps its image. Omission preserves explicit image matching (B3). */\n imagePolicy?: \"require_match\" | \"new_creates_only\";\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\n/**\n * Structural ownership of the provider boundary that failed while establishing\n * a logical sandbox provision. Object errors retain their identity and receive\n * an out-of-band stage; primitive thrown values use a typed wrapper. In both\n * cases the source diagnostic is unchanged and the stage is never guessed from\n * prose.\n */\nexport type SandboxProvisionFailureStage = \"create\" | \"resume\" | \"archive_recovery\";\n\nexport class SandboxProvisionStageError extends Error {\n readonly name = \"SandboxProvisionStageError\";\n\n constructor(\n public readonly stage: SandboxProvisionFailureStage,\n public readonly source: unknown,\n ) {\n super(source instanceof Error ? source.message : String(source), { cause: source });\n }\n}\n\nconst sandboxProvisionFailureStages = new WeakMap<object, SandboxProvisionFailureStage>();\n\nexport function sandboxProvisionFailureStage(error: unknown): SandboxProvisionFailureStage | null {\n if (!error || typeof error !== \"object\") return null;\n return (\n sandboxProvisionFailureStages.get(error) ??\n (error instanceof SandboxProvisionStageError ? error.stage : null)\n );\n}\n\nfunction sandboxProvisionStageError(stage: SandboxProvisionFailureStage, error: unknown): unknown {\n if (error && typeof error === \"object\") {\n sandboxProvisionFailureStages.set(error, stage);\n return error;\n }\n return new SandboxProvisionStageError(stage, error);\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/**\n * Out-of-band proof attached to one exact {@link SandboxExecReadinessTimeoutError}\n * thrown by the elected spawner: the box that missed its readiness budget was\n * freshly created by this caller (not an attached, resumed, or provider-continuity\n * box), it was never published warm, the provider terminated it, and the holder\n * was released. Only such an error may be replaced by re-entering admission.\n */\nconst disposedUnreadyFreshSandboxErrors = new WeakSet<object>();\n\n/** True only for a spawner readiness timeout whose unready fresh box is proven gone. */\nexport function isReplaceableFreshSandboxReadinessTimeout(error: unknown): boolean {\n return (\n error instanceof SandboxExecReadinessTimeoutError &&\n disposedUnreadyFreshSandboxErrors.has(error)\n );\n}\n\n/**\n * A burst of simultaneous turn starts can leave many freshly created provider\n * boxes command-unready at once. The single replacement re-enters admission\n * after a jittered pause so the replacement creates do not re-synchronize into\n * the same burst. Bounded to [2 s, 10 s).\n */\nexport const FRESH_SANDBOX_READINESS_REPLACEMENT_BASE_DELAY_MS = 2_000;\nexport const FRESH_SANDBOX_READINESS_REPLACEMENT_JITTER_MS = 8_000;\n\nexport function freshSandboxReadinessReplacementDelayMs(\n random: () => number = Math.random,\n): number {\n const sample = random();\n const unit = Number.isFinite(sample) ? Math.min(Math.max(sample, 0), 1 - Number.EPSILON) : 0;\n return (\n FRESH_SANDBOX_READINESS_REPLACEMENT_BASE_DELAY_MS +\n Math.floor(unit * FRESH_SANDBOX_READINESS_REPLACEMENT_JITTER_MS)\n );\n}\n\n/** Replacements allowed per turn attempt, across every resumeBoxForTurn call. */\nexport const FRESH_SANDBOX_READINESS_REPLACEMENTS_PER_TURN_ATTEMPT = 1;\n\nexport type FreshSandboxReadinessReplacementBudget = { remaining: number };\n\nexport function createFreshSandboxReadinessReplacementBudget(): FreshSandboxReadinessReplacementBudget {\n return { remaining: FRESH_SANDBOX_READINESS_REPLACEMENTS_PER_TURN_ATTEMPT };\n}\n\nfunction recordFreshSandboxReadinessReplacement(\n metrics: RuntimeMetricsHooks | undefined,\n backend: string,\n outcome: SandboxReadinessReplacementOutcome,\n): void {\n try {\n metrics?.onSandboxReadinessReplacement?.({ backend, outcome });\n } catch {\n // Metrics emission must never affect sandbox recovery or error propagation.\n }\n}\n\nasync function sleepUnlessCancelled(ms: number, signal: AbortSignal | undefined): Promise<boolean> {\n if (signal?.aborted) return false;\n if (ms <= 0) return true;\n return await new Promise<boolean>((resolve) => {\n const onAbort = () => {\n clearTimeout(timer);\n resolve(false);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(true);\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\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\n/**\n * A remote provider may return a sandbox handle before its command router\n * accepts the first exec. The upstream session's yieldTimeMs starts only after\n * sandbox.exec() returns, so it cannot bound that initial RPC. Probe it before\n * publishing the 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 signal?: AbortSignal,\n): Promise<void> {\n try {\n await verifySandboxExecReadiness(established, timeoutMs, signal);\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 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 const archiveRef = parseWorkspaceArchiveObjectRef(sessionState?.workspaceArchiveRef);\n const hasInline = typeof archive === \"string\" && archive.length > 0;\n if (!hasInline && !archiveRef) {\n return null;\n }\n const previous = sessionState?.workspaceArchivePrev;\n const previousRef = parseWorkspaceArchiveObjectRef(sessionState?.workspaceArchivePrevRef);\n const metadata = sessionState?.workspaceArchiveMeta;\n const previousMetadata = sessionState?.workspaceArchivePrevMeta;\n const capturedAt = sessionState?.workspaceArchiveAt;\n return {\n ...(hasInline && !archiveRef ? { workspaceArchive: archive } : {}),\n ...(archiveRef ? { workspaceArchiveRef: archiveRef } : {}),\n ...(metadata !== undefined ? { workspaceArchiveMeta: metadata } : {}),\n ...(typeof previous === \"string\" && previous.length > 0 && !previousRef\n ? { workspaceArchivePrev: previous }\n : {}),\n ...(previousRef ? { workspaceArchivePrevRef: previousRef } : {}),\n ...(previousMetadata !== undefined ? { workspaceArchivePrevMeta: previousMetadata } : {}),\n ...(typeof capturedAt === \"string\" && capturedAt.length > 0\n ? { workspaceArchiveAt: capturedAt }\n : {}),\n };\n}\n\nasync function materializeSpawnEnvelopeArchive(\n envelope: unknown,\n objectStorage: ObjectStorage | null | undefined,\n): Promise<unknown> {\n if (!envelope || typeof envelope !== \"object\") return envelope;\n const record = envelope as Record<string, unknown>;\n const sessionState =\n record.sessionState &&\n typeof record.sessionState === \"object\" &&\n !Array.isArray(record.sessionState)\n ? (record.sessionState as Record<string, unknown>)\n : null;\n if (!sessionState || !parseWorkspaceArchiveObjectRef(sessionState.workspaceArchiveRef)) {\n return envelope;\n }\n if (!objectStorage) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_storage_unavailable\",\n \"workspace archive object storage is not configured\",\n { retryable: true },\n );\n }\n const descriptor = parseWorkspaceArchiveDescriptor(sessionState.workspaceArchiveMeta);\n if (\n process.platform === \"linux\" &&\n descriptor?.version === 1 &&\n descriptor.workspace.projection === \"sdk_local_archive_v1\"\n ) {\n return envelope;\n }\n return {\n ...record,\n sessionState: await inlineWorkspaceArchiveForRestore(sessionState, (key) =>\n objectStorage.getObjectBytes(key),\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\nexport type SandboxDeadlineRotationCheckpointResult = {\n /** The exact established epoch still carries a requested rotation and a\n * complete current-generation archive: the turn may abort orderly. */\n checkpointed: boolean;\n /** What the defense-in-depth holder step observed before the capture. */\n holder: Awaited<ReturnType<typeof reinstateTurnLeaseHolder>>[\"status\"];\n lease: Awaited<ReturnType<typeof readLease>>;\n};\n\n/**\n * The orderly provider-deadline rotation checkpoint for one running turn. The\n * turn-side lease heartbeat calls this once it observes a rotation-fenced lease\n * at its established epoch/instance; `checkpointed: true` licenses the\n * SandboxDeadlineRotationError abort that hands the same logical turn to the\n * cold successor.\n *\n * Defense in depth: the warm capture claim requires exactly this turn's holder.\n * If that holder was lost while the attempt is still the active writer (a stale\n * release, a reap race), `reinstateTurnLeaseHolder` puts it back under the\n * exact epoch/instance fence before the capture, so a lost holder cannot\n * silently disable the orderly abort and leave the reaper to terminate the box\n * under the running turn. Never captures when the epoch/instance changed.\n */\nexport async function persistSandboxDeadlineRotationCheckpoint(\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 expected: { leaseEpoch: number; instanceId: string },\n signal?: AbortSignal,\n): Promise<SandboxDeadlineRotationCheckpointResult> {\n const { db, settings } = services;\n // A cancelled attempt must never briefly regain its holder: its eager\n // cancellation listener may already have released it, and reinstating here\n // would pin the lease behind an attempt that is being torn down.\n if (signal?.aborted) {\n return { checkpointed: false, holder: \"attempt_fenced\", lease: null };\n }\n const reinstated = await reinstateTurnLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n sessionId: ids.sessionId,\n attemptId: ids.attemptId,\n expectedEpoch: expected.leaseEpoch,\n expectedInstanceId: expected.instanceId,\n leaseTtlMs: settings.sandboxLeaseTtlMs,\n });\n if (reinstated.status === \"reinstated\") {\n const message = \"sandbox rotation checkpoint reinstated the live turn holder\";\n const fields = {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n sandboxGroupId: ids.sandboxGroupId,\n leaseEpoch: expected.leaseEpoch,\n liveness: reinstated.lease.liveness,\n };\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n }\n if (reinstated.status !== \"present\" && reinstated.status !== \"reinstated\") {\n return { checkpointed: false, holder: reinstated.status, lease: null };\n }\n await maybePersistWarmWorkspaceSnapshot(\n services,\n ids,\n session,\n expected.leaseEpoch,\n signal,\n true,\n );\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n const checkpointed =\n lease?.leaseEpoch === expected.leaseEpoch &&\n lease.instanceId === expected.instanceId &&\n lease.rotationRequestedAt !== null &&\n lease.archiveComplete &&\n signal?.aborted !== true;\n return { checkpointed, holder: reinstated.status, lease };\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 type WarmWorkspaceSnapshotPromise = Promise<boolean> & {\n /** Settles only after any provider capture continuation has published or\n * failed and released its exact workspace-capture admission. */\n readonly settled: Promise<void>;\n};\n\n/** Who owns a warm checkpoint: the exact turn attempt holding the box, or\n * (`idleCheckpoint`) the reaper checkpointing a box that no turn holds and\n * viewers, interactions or running background commands keep warm. The idle\n * owner is fenced by its exact capture claim alone and is limited to\n * point-in-time Modal captures. */\nexport type WarmWorkspaceSnapshotOwner = {\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n} & (\n | { sessionId: string; turnId: string; attemptId: string; idleCheckpoint?: never }\n | { idleCheckpoint: true; sessionId?: never; turnId?: never; attemptId?: never }\n);\n\nexport function maybePersistWarmWorkspaceSnapshot(\n services: SandboxResumeServices,\n ids: WarmWorkspaceSnapshotOwner,\n session: unknown,\n leaseEpoch: number,\n signal?: AbortSignal,\n force = false,\n): WarmWorkspaceSnapshotPromise {\n let continuationRegistered = false;\n let resolvePhysicalSettlement: () => void = () => undefined;\n const physicalSettlement = new Promise<void>((resolve) => {\n resolvePhysicalSettlement = resolve;\n });\n const result = persistWarmWorkspaceSnapshot(\n services,\n ids,\n session,\n leaseEpoch,\n signal,\n force,\n (continuation) => {\n continuationRegistered = true;\n void continuation.then(resolvePhysicalSettlement, resolvePhysicalSettlement);\n },\n );\n void result.then(\n () => {\n if (!continuationRegistered) resolvePhysicalSettlement();\n },\n () => {\n if (!continuationRegistered) resolvePhysicalSettlement();\n },\n );\n return Object.assign(result, { settled: physicalSettlement });\n}\n\nasync function persistWarmWorkspaceSnapshot(\n services: SandboxResumeServices,\n ids: WarmWorkspaceSnapshotOwner,\n session: unknown,\n leaseEpoch: number,\n signal: AbortSignal | undefined,\n force: boolean,\n registerOwnedContinuation: (continuation: Promise<void>) => void,\n): Promise<boolean> {\n const { db, settings } = services;\n const warnSnapshotFailure = (message: string, error: unknown): void => {\n const fields = {\n ...safeSnapshotError(error),\n sandboxLeaseKey: sandboxLeaseTelemetryKey(ids.workspaceId, ids.sandboxGroupId),\n leaseEpoch,\n };\n try {\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n } catch {\n // Diagnostics cannot change provider settlement or capture-gate cleanup.\n }\n };\n const reportSkipped = (backend: unknown, reason: WorkspaceCaptureSkipReason): void => {\n try {\n services.sandboxMetrics?.onWorkspaceCaptureSkipped?.({\n backend: typeof backend === \"string\" ? backend : \"unknown\",\n reason,\n });\n } catch {\n // Telemetry never changes whether a checkpoint is attempted.\n }\n };\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 persistWorkspaceTar?: () => Promise<Uint8Array | undefined>;\n backendId?: unknown;\n state?: {\n workspacePersistence?: unknown;\n providerState?: { workspacePersistence?: unknown };\n };\n };\n if (\n typeof persistable.persistWorkspace !== \"function\" &&\n typeof persistable.persistWorkspaceTar !== \"function\"\n ) {\n console.error(\"mid-session workspace snapshot skipped (no persist primitive)\", {\n backendId: typeof persistable.backendId === \"string\" ? persistable.backendId : null,\n });\n reportSkipped(persistable.backendId, \"no_persist_primitive\");\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 const canWarmCapture =\n lease?.liveness === \"warm\" && lease.instanceId !== null && lease.leaseEpoch === leaseEpoch;\n const canForceDrainingCapture =\n force === true &&\n lease?.liveness === \"draining\" &&\n lease.instanceId !== null &&\n lease.leaseEpoch === leaseEpoch;\n const turnOwner = ids.idleCheckpoint === true ? null : ids;\n if (!lease || (!canWarmCapture && (!canForceDrainingCapture || !turnOwner))) {\n console.error(\"mid-session workspace snapshot skipped (lease not warm)\", {\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n liveness: lease?.liveness ?? null,\n leaseEpoch: lease?.leaseEpoch ?? null,\n hasInstance: lease?.instanceId !== null && lease?.instanceId !== undefined,\n });\n reportSkipped(lease?.backend ?? persistable.backendId, \"lease_not_warm\");\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. An\n // attached viewer or interaction can write without advancing the\n // generation; the claim then decides whether the box is really clean.\n if (lease.archiveComplete && !leaseMayHaveUntrackedWriters(lease)) {\n return false;\n }\n if (lease.instanceId === null) {\n return false;\n }\n const instanceId = lease.instanceId;\n const captureLiveness: \"warm\" | \"draining\" = canWarmCapture ? \"warm\" : \"draining\";\n const capturePolicy = providerWorkspaceCapturePolicy(lease.backend, session);\n if (!capturePolicy || capturePolicy.liveInstance !== \"preserved\") {\n console.error(\"mid-session workspace snapshot skipped (capture policy)\", {\n sandboxGroupId: ids.sandboxGroupId,\n backend: lease.backend,\n liveInstance: capturePolicy?.liveInstance ?? null,\n });\n reportSkipped(lease.backend, \"capture_policy\");\n return false;\n }\n const nativeModalPersistence =\n workspacePersistence === \"snapshot_filesystem\" ||\n workspacePersistence === \"snapshot_directory\";\n if (!turnOwner && !nativeModalPersistence) {\n // Only a paused-box image may run around the commands keeping an idle\n // box warm; a file-by-file read of the running box could tear.\n reportSkipped(lease.backend, \"capture_policy\");\n return false;\n }\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: captureLiveness,\n captureTimeoutMs,\n minIntervalMs: force ? 0 : intervalMs,\n providerReplaySafe: capturePolicy.takeover === \"same_request\",\n takeoverSafe: capturePolicy.takeover !== \"exclusive\",\n // Modal pauses the box for a native snapshot, so the image is one\n // instant even while background commands run.\n pointInTimeCapture: nativeModalPersistence,\n ...(captureLiveness !== \"warm\"\n ? {}\n : turnOwner\n ? {\n warmAttempt: {\n sessionId: turnOwner.sessionId,\n turnId: turnOwner.turnId,\n attemptId: turnOwner.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(turnOwner.attemptId),\n },\n }\n : { idleCheckpoint: true }),\n });\n if (claimed.status !== \"claimed\") {\n // A scheduled interval not being due is normal, including after a failed\n // attempt. Do not turn every ten-second heartbeat into an error log.\n if (claimed.status === \"throttled\" || claimed.status === \"clean\") return false;\n console.error(\"mid-session workspace snapshot skipped (capture claim)\", {\n sandboxGroupId: ids.sandboxGroupId,\n status: claimed.status,\n });\n reportSkipped(lease.backend, claimed.status);\n return false;\n }\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: VerifiedWorkspaceArchivePayload,\n ): Promise<{ id: string } | null> => {\n if (\n archive.kind === \"host_spool\" ||\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 // A provider-native capture 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 // A host-backed spool capture reads the workspace locally, so it is\n // stopped at the snapshot timeout instead: its rejection is the physical\n // end of the reads, and holding the write fence for an unbounded local\n // read would turn a slow host into failed workspace writes.\n const captureAbort = new AbortController();\n const captureAbortTimer = setTimeout(\n () => captureAbort.abort(new SnapshotTimeoutError(settings.sandboxSnapshotTimeoutMs)),\n settings.sandboxSnapshotTimeoutMs,\n );\n captureAbortTimer.unref?.();\n const captureAndPublish = (async (): Promise<boolean> => {\n const captureStarted = performance.now();\n let captureOutcome: \"completed\" | \"failed\" = \"failed\";\n let archive: VerifiedWorkspaceArchivePayload | undefined;\n let candidate: { id: string } | null = null;\n let publicationAttempted = false;\n try {\n archive = await captureWorkspaceArchiveForStorage(\n session,\n capturedAtMs,\n {\n requestId: claimed.claim.providerRequestId,\n strategy: capturePolicy.strategy,\n signal: captureAbort.signal,\n },\n Boolean(services.objectStorage),\n );\n clearTimeout(captureAbortTimer);\n candidate = await registerCandidate(archive);\n const archiveDescriptor = archive.descriptor;\n const published = await putVersion1TarArchiveOrInline({\n backend: lease.backend,\n objectStorage: services.objectStorage,\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n archive,\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n });\n publicationAttempted = true;\n const { wrote } = await persistWorkspaceArchiveCandidate({\n ...(services.objectStorage ? { objectStorage: services.objectStorage } : {}),\n ...(published.workspaceArchiveRef ? { ref: published.workspaceArchiveRef } : {}),\n persist: () =>\n persistWarmSnapshot(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n ...(turnOwner\n ? {\n sessionId: turnOwner.sessionId,\n turnId: turnOwner.turnId,\n attemptId: turnOwner.attemptId,\n }\n : { idleCheckpoint: true as const }),\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: instanceId,\n expectedWorkspaceGeneration: claimed.claim.workspaceGeneration,\n captureId,\n workspaceArchiveMeta: archiveDescriptor,\n ...published,\n checkpointArtifactId: candidate?.id ?? null,\n minIntervalMs: force ? 0 : intervalMs,\n capturedAtMs,\n }),\n });\n if (!wrote && candidate) {\n await abandonCandidate(candidate.id, \"snapshot_publication_fenced\");\n }\n if (wrote) captureOutcome = \"completed\";\n return wrote;\n } catch (error) {\n if (candidate && !publicationAttempted)\n await abandonCandidate(candidate.id, \"snapshot_capture_failed\");\n throw error;\n } finally {\n clearTimeout(captureAbortTimer);\n await disposeWorkspaceArchive(archive).catch(() => {\n console.warn(\"workspace archive spool cleanup failed\");\n });\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 captureOutcome = \"failed\";\n warnSnapshotFailure(\"mid-session workspace capture gate release failed\", error);\n });\n try {\n services.sandboxMetrics?.onWorkspaceCapture?.({\n backend: lease.backend,\n outcome: captureOutcome,\n durationSeconds: Math.max(0, performance.now() - captureStarted) / 1_000,\n });\n } catch {\n // A completed capture and released gate cannot depend on telemetry.\n }\n }\n })();\n const settled = captureAndPublish.then(\n (persisted) => ({ kind: \"settled\" as const, persisted }),\n (error) => {\n warnSnapshotFailure(\"mid-session workspace snapshot failed (turn unaffected)\", error);\n return { kind: \"settled\" as const, persisted: false };\n },\n );\n registerOwnedContinuation(settled.then(() => undefined));\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 // A failed snapshot does not fail the turn. Physical captures can still\n // fence commands until their exact gate settles; the caller timeout is not\n // permission to release that gate. The next eligible tick can retry.\n warnSnapshotFailure(\"mid-session workspace snapshot failed (turn unaffected)\", error);\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 *\n * A freshly created box that misses its bounded command-readiness budget is\n * replaced at most once per turn attempt (the budget is shared by every call\n * the turn's provisioner makes). The first establish has already terminated that exact\n * unpublished box, rolled its exact warming epoch back to cold (advancing the\n * epoch), and released its holder, so the replacement is an ordinary new\n * admission: it re-runs the cold->warming CAS, persists its own provider\n * instance before readiness, and may instead attach to a sibling that won the\n * CAS first. Nothing model- or tool-visible ran on the discarded box, so no\n * side effect is replayed. A second readiness timeout fails the turn exactly\n * as before; attached/resumed boxes and unconfirmed terminations never\n * replace.\n */\nexport async function resumeBoxForTurn(\n services: SandboxResumeServices,\n ids: ResumeBoxIds,\n kind: \"turn\",\n holderId: TurnSandboxLeaseHolderId,\n): Promise<ResumedTurnSandbox> {\n try {\n return await resumeBoxForTurnOnce(services, ids, kind, holderId);\n } catch (error) {\n if (!isReplaceableFreshSandboxReadinessTimeout(error)) throw error;\n const readiness = error as SandboxExecReadinessTimeoutError;\n const warn = (message: string, fields: Parameters<Observability[\"warn\"]>[1]) => {\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n };\n const identity = {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n sandboxGroupId: ids.sandboxGroupId,\n backend: readiness.backend,\n instanceId: readiness.instanceId,\n readinessTimeoutMs: readiness.timeoutMs,\n };\n const budget =\n services.freshSandboxReadinessReplacementBudget ??\n createFreshSandboxReadinessReplacementBudget();\n if (budget.remaining <= 0) {\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n \"budget_spent\",\n );\n warn(\n \"sandbox command-readiness timed out on a fresh box; this turn attempt already used its replacement\",\n identity,\n );\n throw error;\n }\n budget.remaining -= 1;\n const delayMs = await (\n services.freshSandboxReadinessReplacementDelayMs ?? freshSandboxReadinessReplacementDelayMs\n )();\n warn(\"sandbox command-readiness timed out on a fresh box; replacing it once after jitter\", {\n ...identity,\n replacementDelayMs: delayMs,\n });\n if (!(await sleepUnlessCancelled(delayMs, services.cancellationSignal))) {\n // Cancellation owns the turn boundary; surface the original typed\n // readiness failure rather than starting a replacement.\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n \"cancelled\",\n );\n throw error;\n }\n try {\n const replaced = await resumeBoxForTurnOnce(services, ids, kind, holderId);\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n \"replaced\",\n );\n return replaced;\n } catch (replacementError) {\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n services.cancellationSignal?.aborted\n ? \"cancelled\"\n : replacementError instanceof SandboxExecReadinessTimeoutError\n ? \"failed_again\"\n : \"replacement_failed\",\n );\n throw replacementError;\n }\n }\n}\n\nasync function resumeBoxForTurnOnce(\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 warmBilling: {\n mode: settings.sandboxWarmBillingMode,\n rateMicrosPerSecond: sandboxWarmRateMicrosPerSecond(settings, ids.backend),\n },\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 required 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 ...(ids.imagePolicy ? { imagePolicy: ids.imagePolicy } : {}),\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 let providerRenewalTarget: { backend: Settings[\"sandboxBackend\"]; instanceId: string } | null =\n acquired.lease.liveness === \"warm\" && acquired.lease.instanceId\n ? {\n backend: ids.backend,\n instanceId: acquired.lease.instanceId,\n }\n : null;\n let providerRenewedAtMs = Date.now();\n let providerRenewalInFlight: Promise<void> | null = null;\n const maybeRenewProviderExpiration = async (force = false): Promise<void> => {\n const target = providerRenewalTarget;\n if (!target || providerRenewalInFlight) return;\n const ttlSeconds = effectiveSandboxLifecycle(settings, target.backend).renewableTtlSeconds;\n if (ttlSeconds === null) return;\n const intervalMs = Math.max(10_000, Math.floor((ttlSeconds * 1000) / 3));\n if (!force && Date.now() - providerRenewedAtMs < intervalMs) return;\n providerRenewalInFlight = renewSandboxProviderExpiration({\n backend: target.backend,\n settings,\n instanceId: target.instanceId,\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n })\n .then(() => {\n providerRenewedAtMs = Date.now();\n })\n .finally(() => {\n providerRenewalInFlight = null;\n });\n await providerRenewalInFlight;\n };\n // Release ONLY on holder death. `heartbeatLeaseHolderStatus` separates \"this\n // holder is gone / its attempt is no longer the active writer\" from \"the lease\n // could not be extended\" (rotation requested, draining, another epoch). The\n // second is NOT a reason to release: once a provider-deadline rotation is\n // requested the turn-side heartbeat immediately preempts the attempt, whose\n // finalizer retains this holder until every attempt-owned writer is physically\n // drained. Dropping it here would let the reaper capture or terminate while a\n // provider operation may still be mutating /workspace. Both loops therefore\n // converge on \"holder alive -> never release\"; finalization performs the\n // proof-bearing release.\n const releaseDeadHolder = async (reason: string): Promise<void> => {\n // Logical closure deliberately fences heartbeat authority. It is not proof\n // that the already-admitted capture has physically settled: the finalizer\n // owns that wait and the original deadline bounds dead-worker recovery.\n // Match the reaper's retention rule without touching holder/lease TTLs.\n if (reason === \"holder_gone\" && kind === \"turn\" && holderLeaseHeartbeat) {\n const expectedEpoch = holderLeaseHeartbeat.expectedEpoch;\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (retainsHolderForWarmCapture(lease, expectedEpoch)) return;\n }\n const message = \"sandbox resume holder released: holder no longer live\";\n const fields = {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n sandboxGroupId: ids.sandboxGroupId,\n holderKind: kind,\n reason,\n };\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n void release().catch(() => undefined);\n };\n holderLivenessTimer = setInterval(() => {\n const heartbeat = holderLeaseHeartbeat;\n if (heartbeat) {\n void heartbeatLeaseHolderStatus(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 billingMode: services.settings.sandboxWarmBillingMode,\n })\n .then(async (status) => {\n if (heartbeat !== holderLeaseHeartbeat) return;\n if (!status.holderAlive) {\n // Reaped, released, or its exact attempt is no longer the active\n // writer. Stop this otherwise-unbounded provider operation and\n // idempotently drop any remaining holder state.\n await releaseDeadHolder(status.fence);\n return;\n }\n if (status.fence === \"epoch\") {\n // The lease epoch never regresses: a newer epoch means the box this\n // holder was registered against is definitively superseded (lost\n // instance replaced, re-established by a later turn). The holder\n // row is stale authority for an instance that no longer exists;\n // drop it promptly instead of pinning a successor's lease.\n await releaseDeadHolder(status.fence);\n return;\n }\n // The box is still serving this live holder: keep the provider TTL\n // renewed while the lease is ours (extended, or only rotation-fenced at\n // the same epoch). A liveness fence (draining at our epoch) means the\n // reaper now governs the instance; keep the holder but leave its\n // expiry alone.\n if (status.leaseExtended || status.fence === \"rotation_requested\") {\n void maybeRenewProviderExpiration().catch(() => undefined);\n }\n })\n .catch(() => undefined);\n return;\n }\n void touchLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n })\n .then(async (touched) => {\n if (heartbeat !== holderLeaseHeartbeat) return;\n // A canonical turn holder is rejected once its exact attempt is no\n // longer the active writer (touch is attempt-fenced only; it never\n // consults lease authority, so false here always means holder death).\n if (!touched) {\n await releaseDeadHolder(\"holder_gone\");\n return;\n }\n void maybeRenewProviderExpiration().catch(() => undefined);\n })\n .catch(() => undefined);\n }, services.holderLivenessIntervalMs ?? 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 // Set once commitWarmingToWarm publishes this box. From then on the box is\n // the group's shared, attachable workspace: a later cancellation (Pause,\n // Steer, worker shutdown) only drops this attempt's holder. Terminating it\n // here would hand the next attempt a warm lease naming a dead box, whose\n // exact-id resume then records a lost workspace that never lost anything.\n let published = false;\n let providerCreateOperationId: string | undefined;\n let providerCreateBindingKey: string | undefined;\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 // An audited decision to continue a definitively lost workspace on a new\n // EMPTY box: hydrate nothing (not even a per-session legacy archive) and\n // resume no prior provider identity. Every group member was already told\n // the workspace is empty; the DB accepts only this exact publication.\n const freshWorkspaceRecoveryId = acquired.lease.freshWorkspaceRecoveryId ?? null;\n const envelope = freshWorkspaceRecoveryId\n ? null\n : 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 // Backstop: a session already told its workspace is empty never gets a\n // legacy per-session archive back, even if the lease marker was lost.\n const legacyFallbackRefused =\n !freshWorkspaceRecoveryId &&\n acquired.lease.recovery.archive.status === \"none\" &&\n workspaceArchiveFieldsFromEnvelope(envelope) !== null &&\n (await sessionHoldsFreshWorkspaceRecovery(db, ids.workspaceId, ids.sessionId));\n const fallbackArchiveEnvelope =\n !freshWorkspaceRecoveryId &&\n !legacyFallbackRefused &&\n acquired.lease.recovery.archive.status === \"none\" &&\n workspaceArchiveFieldsFromEnvelope(envelope) !== null\n ? withoutSandboxProviderIdentity(envelope)\n : null;\n let spawnEnvelope = freshWorkspaceRecoveryId\n ? null\n : legacyFallbackRefused\n ? (acquired.lease.resumeState ?? null)\n : (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 // A fresh-workspace spawn is deliberately archive-free; commitWarmingToWarm\n // verifies the exact decision before publication.\n if (\n !freshWorkspaceRecoveryId &&\n ((acquired.lease.recovery.archive.status === \"available\" &&\n (acquired.lease.archiveComplete ||\n acquired.lease.historicalRecoveryAuthorized === true)) ||\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 (\n !freshWorkspaceRecoveryId &&\n acquired.lease.recovery.archive.status !== \"none\" &&\n !continuityRecovery\n ) {\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 persistArchiveSource =\n spawnEnvelope && typeof spawnEnvelope === \"object\"\n ? (spawnEnvelope as Record<string, unknown>)\n : null;\n const hydrateEnvelopeRaw = await materializeSpawnEnvelopeArchive(\n persistArchiveSource,\n services.objectStorage,\n );\n const hydrateEnvelope =\n hydrateEnvelopeRaw && typeof hydrateEnvelopeRaw === \"object\"\n ? (hydrateEnvelopeRaw as Record<string, unknown>)\n : null;\n const established = await establishSandboxSessionFromEnvelope(settings, hydrateEnvelope, {\n sessionId: ids.sessionId,\n recovery: \"create-or-restore\",\n ...(services.objectStorage\n ? {\n loadHostWorkspaceArchive: async (ref) => {\n try {\n return await downloadWorkspaceArchiveSpool(\n services.objectStorage!,\n ref.key,\n { bytes: ref.bytes, sha256: ref.sha256 },\n { temporaryDirectory: workspaceArchiveDownloadTemporaryDirectory },\n );\n } catch (error) {\n if (error instanceof WorkspaceArchiveStorageError) {\n throw new WorkspaceArchiveIntegrityError(error.code, error.message, {\n retryable: error.retryable,\n cause: error,\n });\n }\n throw error;\n }\n },\n }\n : {}),\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 onBeforeSandboxCreate: async (createSettings, intent, providerContext) => {\n if (ids.backend !== \"modal\") return;\n if (!intent || !providerContext)\n throw new Error(\"Modal create requires the provider dispatch boundary\");\n throwIfReleasedOrCancelled();\n const binding = await resolveModalCheckpointProviderBindingForSession(\n createSettings,\n providerContext,\n );\n const operationId = intent.operationId;\n await beginModalProviderCreate(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n operationId,\n providerBindingKey: binding.key,\n rematerializationId: rematerialization?.id ?? null,\n selectedRevision: rematerialization?.selectedRevision ?? null,\n imageId: intent.imageId,\n imageRef: createSettings.modalImageRef ?? null,\n appId: intent.appId,\n providerName: intent.name,\n requestSha256: intent.requestSha256,\n });\n providerCreateOperationId = operationId;\n providerCreateBindingKey = binding.key;\n },\n onSandboxCreated: async (created) => {\n createdEstablished = created;\n providerRenewalTarget = {\n backend: ids.backend,\n instanceId: created.instanceId,\n };\n providerRenewedAtMs = Date.now();\n if (\n providerCreateBindingKey &&\n !(await modalSessionMatchesCheckpointProviderBinding(\n settings,\n created.session,\n providerCreateBindingKey,\n ))\n ) {\n throw new Error(\"Modal creation receipt crossed the fenced provider namespace\");\n }\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, persistArchiveSource),\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 ...(providerCreateOperationId ? { providerCreateOperationId } : {}),\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 an asynchronous\n // provider's command router is live. Do not publish a warm lease until\n // one bounded no-op exec works.\n // On timeout the catch below terminates the box and rolls warming -> cold;\n // resumeBoxForTurn may then replace a proven-terminated fresh box once.\n if (services.verifySpawnedSandboxReadiness) {\n await services.verifySpawnedSandboxReadiness(established, {\n sandboxGroupId: ids.sandboxGroupId,\n });\n } else {\n await waitForSandboxExecReadiness(\n established,\n MODAL_EXEC_READINESS_TIMEOUT_MS,\n {\n sandboxGroupId: ids.sandboxGroupId,\n },\n cancellationSignal,\n );\n }\n await maybeRenewProviderExpiration(true);\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, persistArchiveSource),\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 ...(freshWorkspaceRecoveryId\n ? { freshWorkspace: { operationId: freshWorkspaceRecoveryId } }\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 published = true;\n holderLeaseHeartbeat = {\n expectedEpoch: committed.lease.leaseEpoch,\n leaseTtlMs,\n };\n await services.onSpawnedSandboxPublished?.();\n throwIfReleasedOrCancelled();\n return { established, leaseEpoch: committed.lease.leaseEpoch, release };\n } catch (error) {\n if (published) {\n // The published warm box stays for the replacement attempt to resume\n // by exact provider id; ordinary idle drain owns its capture/teardown.\n await release();\n throw error;\n }\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 if (\n terminated &&\n createdEstablished &&\n error instanceof SandboxExecReadinessTimeoutError &&\n error.instanceId === createdEstablished.instanceId &&\n (createdEstablished.origin === \"created\" || createdEstablished.origin === \"restored\") &&\n !createdEstablished.providerContinuity\n ) {\n disposedUnreadyFreshSandboxErrors.add(error);\n }\n throw sandboxProvisionStageError(rematerialization ? \"archive_recovery\" : \"create\", 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 // A provider may have ended the exact box while Opengeni was idle. Prove\n // 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(\n established,\n MODAL_EXEC_READINESS_TIMEOUT_MS,\n {\n sandboxGroupId: ids.sandboxGroupId,\n },\n cancellationSignal,\n );\n }\n providerRenewalTarget = {\n backend: ids.backend,\n instanceId: established.instanceId,\n };\n await maybeRenewProviderExpiration(true);\n throwIfReleasedOrCancelled();\n } catch (error) {\n if (!isProviderSandboxNotFoundError(ids.backend, error)) {\n throw sandboxProvisionStageError(\"resume\", 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 expectedBackend: ids.backend,\n });\n if (marked.status === \"marked\") {\n await publishDurableSessionEvents(\n services.bus,\n ids.workspaceId,\n marked.backgroundCommandEvents,\n );\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 // A cancelled waiter owns no box and must not keep polling for up to the\n // warming budget: its activity finalizer joins this exact promise.\n if (!(await sleepUnlessCancelled(WARMING_POLL_INTERVAL_MS, services.cancellationSignal))) {\n throw services.cancellationSignal?.reason instanceof Error\n ? services.cancellationSignal.reason\n : new Error(\"Sandbox warming wait was cancelled with its owning turn attempt\");\n }\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","import type { LeaseSnapshot } from \"@opengeni/db\";\n\n/** Physical capture retention is not permission to heartbeat or execute a closed turn. */\nexport function retainsHolderForWarmCapture(\n lease: Pick<LeaseSnapshot, \"liveness\" | \"leaseEpoch\" | \"archiveCapture\"> | null,\n expectedEpoch: number,\n now = Date.now(),\n): boolean {\n return Boolean(\n lease?.liveness === \"warm\" &&\n lease.leaseEpoch === expectedEpoch &&\n lease.archiveCapture &&\n lease.archiveCapture.deadlineAt.getTime() > now,\n );\n}\n","import { isDeepStrictEqual } from \"node:util\";\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 createProviderCommandRetainer,\n supervisedCommandProtocolReady,\n} from \"@opengeni/db/retained-provider-commands\";\nimport {\n adoptConnectedMachineSessionBackgroundCommand,\n adoptManagedSessionBackgroundCommand,\n advanceWorkspaceGenerationForRetainedProcess,\n retainedProviderCommandPersistence,\n advanceWorkspaceGeneration,\n getRetainedProcess,\n retainWorkspaceMutationProcess,\n retainedProcessSettlementIdentity,\n settleConnectedMachineSessionBackgroundCommand,\n settleRetainedProcess,\n verifyRetainedProcessMutationSettlement,\n verifyWorkspaceMutationSettlement,\n getSandbox,\n getLiveEnrollmentConnection,\n markWarmLeaseInstanceLost,\n readLease,\n readActiveSandbox,\n resolvePersonalMachineConnectionForAttempt,\n SandboxRetainedProcessPromotionFencedError,\n SandboxRetainedProcessTerminalError,\n SandboxWorkspaceMutationOutputRejectedError,\n type Database,\n type EnrollmentRecord,\n type SandboxWorkspaceMutationAdmission,\n} from \"@opengeni/db\";\nimport {\n observeSessionBackgroundCommandCompletion,\n recordConnectedCommandOutputConsumption,\n} from \"@opengeni/db/session-background-commands\";\nimport { appendSessionCommandOutput } from \"@opengeni/db/session-command-output\";\nimport type { OpStreamOutputFrame } from \"@opengeni/runtime/sandbox\";\nimport type { EventBus } from \"@opengeni/events\";\nimport { publishDurableSessionEvents } from \"./session-event-fanout\";\nimport {\n buildSelfhostedBackendSession,\n ActiveBackendUnresolvableError,\n establishSandboxSessionFromEnvelope,\n isProviderSandboxGoneDuringRoutedOperation,\n isProviderSandboxNotFoundError,\n makeActiveBackendResolver,\n NatsControlRpc,\n NatsOpStreamTransport,\n RoutingBackendRecoveryRequiredError,\n RoutingSandboxSession,\n RoutingMutationOutputRejectedError,\n resolveModalCheckpointProviderBindingForSession,\n resolveConnectedMachineWorkspaceRoot,\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 RoutingSandboxFirstOperationObserver,\n type RoutingSandboxOperationObserver,\n type RoutingSandboxCaptureWaitObserver,\n type RoutingSandboxWaitObservation,\n type RoutingRetainedProcess,\n type RoutingRetainedProcessTerminalProof,\n type SelfhostedOpObserver,\n type SelfhostedConnectionBinding,\n type SelfhostedRelayConfig,\n type OpStreamJournal,\n type SelfhostedOpStreamDeps,\n} from \"@opengeni/runtime\";\nimport { sandboxLeaseHolderIdForAttempt } from \"./sandbox-resume\";\n\nconst retainWorkspaceProviderCommand = createProviderCommandRetainer(\n retainWorkspaceMutationProcess,\n (error) => (error instanceof SandboxRetainedProcessPromotionFencedError ? error.process : null),\n);\n\ntype PersistableMutationAdmission = {\n admission: SandboxWorkspaceMutationAdmission;\n providerBinding: Awaited<\n ReturnType<typeof resolveModalCheckpointProviderBindingForSession>\n > | null;\n};\n\nfunction admittedCommandHandle(value: unknown): number | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n return (value as PersistableMutationAdmission).admission?.workspaceGeneration;\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 onSandboxCaptureWait?: RoutingSandboxCaptureWaitObserver;\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 /** Prepare and publish the worker's home handle. Rejection leaves the route\n * unpublished; replacement preparation must settle before the first tool op. */\n onHomeSandboxRebound?: (input: {\n established: EstablishedSandboxSession;\n leaseEpoch: number;\n }) => void | Promise<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 resourceAccountId?: string;\n resourceSubjectId?: string;\n /** Frozen initiating-human authority for personal Connected Machine use.\n * Every routed operation reasserts this exact accepted attempt before the\n * control-plane connection is resolved. */\n personalMachineAttempt?: {\n accountId: string;\n subjectId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n };\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 /** Attempt-local values projected only onto Connected Machine child execs. */\n transientExecEnvironment?: () => Readonly<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 await 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 expectedBackend: lease.backend,\n diagnostic: \"provider_not_found_during_home_route_rebind\",\n });\n if (marked.status === \"marked\") {\n await publishDurableSessionEvents(\n services.bus,\n ids.workspaceId,\n marked.backgroundCommandEvents,\n );\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 await 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 onCaptureWait?: (observation: RoutingSandboxWaitObservation) => void;\n }) => Promise<PersistableMutationAdmission | null>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!home || !fence) return undefined;\n return async ({ op, backend, onCaptureWait }) => {\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 ...(onCaptureWait ? { onCaptureWait } : {}),\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\" | \"outcome_unknown\";\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\" || outcome === \"outcome_unknown\") && retainedProcess) {\n try {\n await retainWorkspaceProviderCommand(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: retainedProcess.id,\n providerSessionId: retainedProcess.providerSessionId,\n ...(retainedProcess.providerCommand\n ? { providerCommand: retainedProcess.providerCommand }\n : {}),\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 if (outcome === \"outcome_unknown\")\n throw new Error(\"Outcome-unknown command settlement requires its exact retained invocation\");\n try {\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 } catch (error) {\n if (\n error instanceof SandboxWorkspaceMutationOutputRejectedError &&\n error.matchesPhysicalSettlement({\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n admission: exactAdmission,\n operation: op,\n outcome,\n })\n ) {\n throw new RoutingMutationOutputRejectedError(op, error.code, { cause: error });\n }\n throw error;\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 try {\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 } catch (error) {\n if (\n error instanceof SandboxWorkspaceMutationOutputRejectedError &&\n error.matchesPhysicalSettlement({\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n admission: admission as SandboxWorkspaceMutationAdmission,\n operation: op,\n outcome,\n })\n ) {\n if (error.retainedProcessTerminal) {\n // Another authority (the reaper's exact-proof reconciliation) settled\n // this retained process terminal between admission and settlement.\n // The admission is physically settled and its output stays rejected;\n // surface the durable terminal truth so routing reports completion\n // instead of failing the turn. Nothing is replayed.\n throw new SandboxRetainedProcessTerminalError(\n error.retainedProcessTerminal.state,\n error.retainedProcessTerminal.exitCode,\n );\n }\n throw new RoutingMutationOutputRejectedError(op, error.code, { cause: error });\n }\n throw error;\n }\n };\n}\n\nexport function captureConnectedCommandOutput(\n db: Database,\n ids: { accountId: string; workspaceId: string; sessionId: string },\n bus?: EventBus,\n) {\n return async (commandId: string, frames: OpStreamOutputFrame[]) => {\n for (const frame of frames) {\n const events = await appendSessionCommandOutput(db, {\n ...ids,\n commandId,\n chunkId: `op-frame:${frame.sequence}`,\n stream: frame.stream,\n chunk: frame.chunk,\n });\n if (events.length && bus)\n await bus.publish(ids.workspaceId, ids.sessionId, events).catch(() => undefined);\n }\n };\n}\n\nfunction captureRetainedProcessOutputForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n) {\n const accountId = ids.workspaceMutationFence?.accountId;\n if (!accountId) return undefined;\n return async ({\n process,\n chunkId,\n chunk,\n stream,\n streamFidelity,\n }: {\n process: RoutingRetainedProcess;\n chunkId: string;\n chunk: string;\n stream: \"stdout\" | \"stderr\";\n streamFidelity: \"separate\" | \"merged\";\n }) => {\n const events = await appendSessionCommandOutput(services.db, {\n accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: process.id,\n chunkId,\n chunk,\n stream,\n streamFidelity,\n });\n if (events.length && services.bus)\n await services.bus.publish(ids.workspaceId, ids.sessionId, events).catch(() => undefined);\n };\n}\n\nfunction observeRetainedProcessTerminalForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n) {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ process }: { process: RoutingRetainedProcess }) => {\n await observeSessionBackgroundCommandCompletion(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: process.id,\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 !== (sandboxBackendForSdkBackendId(backend.kind) ?? 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 const settlement = 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 if (settlement.process.state === \"active\") {\n throw new Error(\"Retained-process settlement returned an active durable process\");\n }\n if (settlement.backgroundCommandEvents.length > 0 && services.bus) {\n await services.bus\n .publish(ids.workspaceId, ids.sessionId, settlement.backgroundCommandEvents)\n .catch(() => undefined);\n }\n };\n}\n\n/** Cleanup can observe the independently settled row even when this worker's\n * pending output receipt or original provider transport can no longer advance. */\nfunction isRetainedProcessSettledForTurn(services: RoutingWiringServices, ids: RoutingWiringIds) {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({\n backend,\n process,\n }: {\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n }): Promise<boolean> => {\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.state === \"active\" ||\n durable.providerSessionId !== process.providerSessionId ||\n durable.providerBackend !== (sandboxBackendForSdkBackendId(backend.kind) ?? 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 return false;\n if (process.providerCommand) {\n // The general process projection deliberately omits the provider locator.\n // Load its immutable identity through the exact protected persistence seam.\n const command = await retainedProviderCommandPersistence(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n }).load();\n if (\n !command ||\n command.kind !== process.providerCommand.kind ||\n command.execId !== process.providerCommand.execId ||\n command.taskId !== process.providerCommand.taskId ||\n command.sandboxId !== process.providerCommand.sandboxId ||\n Boolean(command.pty) !== Boolean(process.providerCommand.pty) ||\n (command.kind === \"modal-router-v1\" &&\n process.providerCommand.kind === \"modal-router-v1\" &&\n !isDeepStrictEqual(command.supervision, process.providerCommand.supervision))\n )\n return false;\n }\n // Terminal rows are written only through proof-gated physical settlement.\n return true;\n };\n}\n\nfunction adoptRetainedProcessAsBackgroundCommandForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n command?: string | undefined;\n }) => Promise<void>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ backend, process, command }) => {\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 !== (sandboxBackendForSdkBackendId(backend.kind) ?? 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(\"Background command adoption lost its exact retained-process identity\");\n }\n await adoptManagedSessionBackgroundCommand(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 processId: process.id,\n expected: retainedProcessSettlementIdentity(durable),\n command: command ?? \"Background command\",\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 backgroundCommandAccountId = ids.workspaceMutationFence?.accountId;\n const backgroundCommandAttempt = ids.workspaceMutationFence;\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 isProcessSettled = isRetainedProcessSettledForTurn(services, ids);\n const adoptProcessAsBackgroundCommand = adoptRetainedProcessAsBackgroundCommandForTurn(\n services,\n ids,\n );\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(\n db,\n ids.resourceAccountId && ids.resourceSubjectId\n ? {\n accountId: ids.resourceAccountId,\n workspaceId: ids.workspaceId,\n subjectId: ids.resourceSubjectId,\n }\n : ids.workspaceId,\n sandboxId,\n );\n return sandbox\n ? {\n id: sandbox.id,\n workspaceId: sandbox.workspaceId,\n kind: sandbox.kind,\n name: sandbox.name,\n ...(sandbox.scope ? { scope: sandbox.scope } : {}),\n enrollmentId: sandbox.enrollmentId,\n }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n resolveSelfhostedConnection: async (sandbox) => {\n if (!sandbox.enrollmentId) return null;\n const enrollment = await resolveRoutedMachineConnection(db, ids, sandbox);\n return connectionBindingFor(services, enrollment);\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 ...(backgroundCommandAccountId && backgroundCommandAttempt\n ? {\n selfhostedAdoptBackgroundCommand: async (command) => {\n const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: backgroundCommandAttempt.turnId,\n executionGeneration: backgroundCommandAttempt.executionGeneration,\n attemptId: backgroundCommandAttempt.attemptId,\n commandId: crypto.randomUUID(),\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n command: command.command,\n });\n return { commandId: adopted.id };\n },\n selfhostedSettleBackgroundCommand: async (command) => {\n const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: command.commandId,\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n outcome: command.outcome,\n exitCode: command.exitCode,\n reason: command.reason,\n ...(command.failure ? { failure: command.failure } : {}),\n });\n if (settlement && bus) {\n await bus\n .publish(ids.workspaceId, ids.sessionId, settlement.events)\n .catch(() => undefined);\n }\n },\n selfhostedCaptureBackgroundCommandOutput: captureConnectedCommandOutput(\n db,\n {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n },\n bus,\n ),\n }\n : {}),\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 ...(ids.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: ids.transientExecEnvironment }\n : {}),\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 ...(services.onSandboxCaptureWait ? { onCaptureWait: services.onSandboxCaptureWait } : {}),\n providerCommandHandle: admittedCommandHandle,\n providerSupervisionReady: async () =>\n settings.modalCommandSupervisionEnabled && (await supervisedCommandProtocolReady(db)),\n ...(ids.workspaceMutationFence\n ? {\n providerCommandPersistence: (process: RoutingRetainedProcess) =>\n retainedProviderCommandPersistence(\n db,\n {\n accountId: ids.workspaceMutationFence!.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n },\n services.bus\n ? (events) => services.bus!.publish(ids.workspaceId, ids.sessionId, events)\n : undefined,\n ),\n }\n : {}),\n ...(beforeMutation ? { beforeMutation } : {}),\n ...(afterMutation ? { afterMutation } : {}),\n ...(beforeProcessMutation ? { beforeProcessMutation } : {}),\n ...(afterProcessMutation ? { afterProcessMutation } : {}),\n ...(settleProcess ? { settleProcess } : {}),\n ...(isProcessSettled ? { isProcessSettled } : {}),\n ...(ids.workspaceMutationFence\n ? { observeProcessTerminal: observeRetainedProcessTerminalForTurn(services, ids)! }\n : {}),\n ...(ids.workspaceMutationFence\n ? { captureProcessOutput: captureRetainedProcessOutputForTurn(services, ids)! }\n : {}),\n ...(adoptProcessAsBackgroundCommand ? { adoptProcessAsBackgroundCommand } : {}),\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 expectedBackend: home.backend,\n diagnostic: \"provider_not_found_during_routed_operation\",\n });\n if (marked.status === \"marked\") {\n await publishDurableSessionEvents(\n services.bus,\n ids.workspaceId,\n marked.backgroundCommandEvents,\n );\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 onFirstOperation?: RoutingSandboxFirstOperationObserver;\n },\n): EstablishedSandboxSession {\n const { db, settings, bus, onOp } = services;\n const backgroundCommandAccountId = ids.workspaceMutationFence?.accountId;\n const backgroundCommandAttempt = ids.workspaceMutationFence;\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 isProcessSettled = isRetainedProcessSettledForTurn(services, ids);\n const adoptProcessAsBackgroundCommand = adoptRetainedProcessAsBackgroundCommandForTurn(\n services,\n ids,\n );\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(\n db,\n ids.resourceAccountId && ids.resourceSubjectId\n ? {\n accountId: ids.resourceAccountId,\n workspaceId: ids.workspaceId,\n subjectId: ids.resourceSubjectId,\n }\n : ids.workspaceId,\n sandboxId,\n );\n return sandbox\n ? {\n id: sandbox.id,\n workspaceId: sandbox.workspaceId,\n kind: sandbox.kind,\n name: sandbox.name,\n ...(sandbox.scope ? { scope: sandbox.scope } : {}),\n enrollmentId: sandbox.enrollmentId,\n }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n resolveSelfhostedConnection: async (sandbox) => {\n if (!sandbox.enrollmentId) return null;\n const enrollment = await resolveRoutedMachineConnection(db, ids, sandbox);\n return connectionBindingFor(services, enrollment);\n },\n relay: relayConfigFromSettings(settings),\n ...selfhostedResolverTimeouts(settings),\n ...(onOp !== undefined ? { selfhostedOnOp: onOp } : {}),\n ...(backgroundCommandAccountId && backgroundCommandAttempt\n ? {\n selfhostedAdoptBackgroundCommand: async (command) => {\n const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: backgroundCommandAttempt.turnId,\n executionGeneration: backgroundCommandAttempt.executionGeneration,\n attemptId: backgroundCommandAttempt.attemptId,\n commandId: crypto.randomUUID(),\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n command: command.command,\n });\n return { commandId: adopted.id };\n },\n selfhostedSettleBackgroundCommand: async (command) => {\n const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: command.commandId,\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n outcome: command.outcome,\n exitCode: command.exitCode,\n reason: command.reason,\n ...(command.failure ? { failure: command.failure } : {}),\n });\n if (settlement && bus) {\n await bus\n .publish(ids.workspaceId, ids.sessionId, settlement.events)\n .catch(() => undefined);\n }\n },\n selfhostedCaptureBackgroundCommandOutput: captureConnectedCommandOutput(\n db,\n {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n },\n bus,\n ),\n }\n : {}),\n ...(ids.environment !== undefined ? { environment: ids.environment } : {}),\n ...(ids.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: ids.transientExecEnvironment }\n : {}),\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 ...(services.onSandboxCaptureWait ? { onCaptureWait: services.onSandboxCaptureWait } : {}),\n ...(args.onFirstOperation ? { onFirstOperation: args.onFirstOperation } : {}),\n providerCommandHandle: admittedCommandHandle,\n providerSupervisionReady: async () =>\n settings.modalCommandSupervisionEnabled && (await supervisedCommandProtocolReady(db)),\n ...(ids.workspaceMutationFence\n ? {\n providerCommandPersistence: (process: RoutingRetainedProcess) =>\n retainedProviderCommandPersistence(\n db,\n {\n accountId: ids.workspaceMutationFence!.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n },\n services.bus\n ? (events) => services.bus!.publish(ids.workspaceId, ids.sessionId, events)\n : undefined,\n ),\n }\n : {}),\n ...(beforeMutation ? { beforeMutation } : {}),\n ...(afterMutation ? { afterMutation } : {}),\n ...(beforeProcessMutation ? { beforeProcessMutation } : {}),\n ...(afterProcessMutation ? { afterProcessMutation } : {}),\n ...(settleProcess ? { settleProcess } : {}),\n ...(isProcessSettled ? { isProcessSettled } : {}),\n ...(ids.workspaceMutationFence\n ? { observeProcessTerminal: observeRetainedProcessTerminalForTurn(services, ids)! }\n : {}),\n ...(ids.workspaceMutationFence\n ? { captureProcessOutput: captureRetainedProcessOutputForTurn(services, ids)! }\n : {}),\n ...(adoptProcessAsBackgroundCommand ? { adoptProcessAsBackgroundCommand } : {}),\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 expectedBackend: home.backend,\n diagnostic: \"provider_not_found_during_routed_operation\",\n });\n if (marked.status === \"marked\") {\n await publishDurableSessionEvents(\n services.bus,\n ids.workspaceId,\n marked.backgroundCommandEvents,\n );\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 accountId: string;\n /** Authorization/session workspace. */\n workspaceId: string;\n sessionId: string;\n /** Physical machine-origin workspace used in control-plane routing. */\n controlWorkspaceId?: string;\n /** Exact launching attempt required before a live Connected Machine command\n * can transfer into session ownership. Omitted by non-turn/test callers,\n * which therefore cannot yield a durable background command. */\n backgroundCommandAttempt?: Pick<\n NonNullable<RoutingWiringIds[\"workspaceMutationFence\"]>,\n \"turnId\" | \"executionGeneration\" | \"attemptId\"\n >;\n /** The target machine's enrollment id == the agent subject id. */\n agentId: string;\n /** Exact daemon process currently leased for the enrollment. */\n connectionInstanceId: 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 /** Desired per-enrollment command policy and capability from the same live\n * enrollment snapshot as the process identity. */\n operationResourcePolicy: EnrollmentRecord[\"operationPolicy\"];\n operationResourcePolicySupported: boolean;\n operationCpuQuotaSupported: boolean;\n /** Feature advertisement only; refreshed by exact live admission for each operation. */\n transactionalFsWriteSupported?: boolean;\n browserControlHttpSupported?: 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 /** Attempt-local values projected only onto this machine's child execs. */\n transientExecEnvironment?: () => Readonly<Record<string, string>>;\n /** The session working directory (per-session pointer). Null ⇒ workspace_root. */\n workingDir: string | null;\n /** Effective absolute host-native root frozen for this attempt. */\n workspaceRoot: string;\n /** Present whenever the turn has an initiating human. A machine can become\n * Only me during the turn, so every provider operation reads the current\n * scope and rechecks this frozen accepted-attempt authority immediately\n * before dispatch while the machine is user-owned. */\n personalMachineAttempt?: NonNullable<RoutingWiringIds[\"personalMachineAttempt\"]> & {\n sessionId: string;\n };\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\n/** Project one enrollment read into one exact runtime route. Capability and\n * process identity must be taken from the same snapshot. */\nexport function connectionBindingFor(\n services: RoutingWiringServices,\n enrollment: EnrollmentRecord | null,\n): SelfhostedConnectionBinding | null {\n if (!enrollment?.connectionInstanceId) return null;\n const opStream = opStreamDepsFor(services, enrollment.opStream === true);\n return {\n workspaceId: enrollment.workspaceId,\n connectionInstanceId: enrollment.connectionInstanceId,\n workspaceRoot: enrollment.workspaceRoot,\n ...(opStream !== undefined ? { opStream } : {}),\n operationResourcePolicy: enrollment.operationPolicy,\n operationResourcePolicySupported: enrollment.agentCapabilities.operationResourcePolicy === true,\n operationCpuQuotaSupported: enrollment.agentCapabilities.operationCpuQuota === true,\n transactionalFsWriteSupported: enrollment.agentCapabilities.transactionalFsWrite === true,\n browserControlHttpSupported: enrollment.agentCapabilities.browserControlHttp === true,\n };\n}\n\n/** Personal-machine discovery is not execution authority. A machine's audience\n * can change in place while a routed session is cached, so the current scope is\n * read from the enrollment itself, never from the sandbox snapshot taken when\n * the session was built. A machine that is Only me now rechecks the frozen\n * initiating human, exact current attempt, authorization snapshot and current\n * visibility-keyed grant immediately before each routed operation resolves a\n * live control-plane connection. */\nasync function resolveRoutedMachineConnection(\n db: Database,\n ids: RoutingWiringIds,\n sandbox: RoutableSandbox,\n): Promise<EnrollmentRecord | null> {\n if (!sandbox.enrollmentId) return null;\n const current = await getLiveEnrollmentConnection(db, sandbox.workspaceId, sandbox.enrollmentId);\n if (!current) return null;\n if (current.scope === \"user\") {\n const authority = ids.personalMachineAttempt;\n if (!authority) return null;\n return await resolvePersonalMachineConnectionForAttempt(db, {\n accountId: authority.accountId,\n workspaceId: ids.workspaceId,\n subjectId: authority.subjectId,\n sessionId: ids.sessionId,\n turnId: authority.turnId,\n attemptId: authority.attemptId,\n executionGeneration: authority.executionGeneration,\n enrollmentId: sandbox.enrollmentId,\n requireActiveSandbox: true,\n });\n }\n if (!ids.resourceAccountId || !ids.resourceSubjectId) return current;\n return await getLiveEnrollmentConnection(\n db,\n {\n accountId: ids.resourceAccountId,\n workspaceId: ids.workspaceId,\n subjectId: ids.resourceSubjectId,\n },\n sandbox.enrollmentId,\n );\n}\n\nexport async function establishSelfhostedTurnSession(\n services: RoutingWiringServices,\n args: SelfhostedTurnSessionArgs,\n): Promise<EstablishedSandboxSession> {\n const { db, 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 ...(args.controlWorkspaceId !== undefined\n ? { controlWorkspaceId: args.controlWorkspaceId }\n : {}),\n agentId: args.agentId,\n connectionInstanceId: args.connectionInstanceId,\n workspaceRoot: args.workspaceRoot,\n relay: relayConfigFromSettings(settings),\n controlRpcFactory: controlRpcFactory(bus),\n epoch: args.epoch,\n environment: args.environment,\n ...(args.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: args.transientExecEnvironment }\n : {}),\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 operationResourcePolicy: args.operationResourcePolicy,\n operationResourcePolicySupported: args.operationResourcePolicySupported,\n operationCpuQuotaSupported: args.operationCpuQuotaSupported,\n transactionalFsWriteSupported: args.transactionalFsWriteSupported === true,\n browserControlHttpSupported: args.browserControlHttpSupported === true,\n resolveOperationAdmission: async () => {\n // The machine's audience can change in place during a turn. Read the\n // current scope on every admitted operation: a machine that is Only me now\n // needs the frozen accepted-attempt authority, a shared one does not.\n const current = await getLiveEnrollmentConnection(\n db,\n args.controlWorkspaceId ?? args.workspaceId,\n args.agentId,\n );\n const enrollment =\n current?.scope !== \"user\"\n ? current\n : args.personalMachineAttempt\n ? await resolvePersonalMachineConnectionForAttempt(db, {\n accountId: args.personalMachineAttempt.accountId,\n workspaceId: args.workspaceId,\n subjectId: args.personalMachineAttempt.subjectId,\n sessionId: args.personalMachineAttempt.sessionId,\n turnId: args.personalMachineAttempt.turnId,\n attemptId: args.personalMachineAttempt.attemptId,\n executionGeneration: args.personalMachineAttempt.executionGeneration,\n enrollmentId: args.agentId,\n requireActiveSandbox: true,\n })\n : null;\n const binding = connectionBindingFor(services, enrollment);\n if (!binding) return null;\n if (!binding.workspaceRoot) {\n throw new ActiveBackendUnresolvableError(\n \"workspace_root_unavailable\",\n \"Connected Machine no longer has a reported workspace root\",\n );\n }\n return {\n ...binding,\n workspaceRoot: resolveConnectedMachineWorkspaceRoot(binding.workspaceRoot, args.workingDir),\n };\n },\n ...(args.backgroundCommandAttempt\n ? {\n adoptBackgroundCommand: async (command) => {\n const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n turnId: args.backgroundCommandAttempt!.turnId,\n executionGeneration: args.backgroundCommandAttempt!.executionGeneration,\n attemptId: args.backgroundCommandAttempt!.attemptId,\n commandId: crypto.randomUUID(),\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n command: command.command,\n });\n return { commandId: adopted.id };\n },\n }\n : {}),\n captureBackgroundCommandOutput: captureConnectedCommandOutput(\n db,\n {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n },\n bus,\n ),\n settleBackgroundCommand: async (command) => {\n const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n commandId: command.commandId,\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n outcome: command.outcome,\n exitCode: command.exitCode,\n reason: command.reason,\n ...(command.failure ? { failure: command.failure } : {}),\n });\n if (command.outputReceipt && command.outcome === \"exited\" && command.exitCode !== null) {\n await recordConnectedCommandOutputConsumption(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n commandId: command.commandId,\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n receipt: command.outputReceipt,\n exitCode: command.exitCode,\n });\n }\n if (settlement && bus) {\n await bus\n .publish(args.workspaceId, args.sessionId, settlement.events)\n .catch(() => undefined);\n }\n },\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. Connected Machine exec fails closed\n // when it is absent; there is no request/reply downgrade.\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"],"mappings":";AAAA,SAAS,gCAAoD;AAetD,SAAS,kBACd,OACA,SAAsC,kBACnB;AACnB,QAAM,SAA4B;AAAA,IAChC,YAAY;AAAA,IACZ,WAAW;AAAA,IACX;AAAA,EACF;AACA,MAAI;AACF,QAAI,SAAS,OAAO,UAAU,UAAU;AACtC,YAAM,YAAY;AAMlB,UACE,OAAO,UAAU,SAAS,YAC1B,iCAAiC,KAAK,UAAU,IAAI,GACpD;AACA,eAAO,YAAY,UAAU;AAAA,MAC/B;AACA,UAAI,OAAO,UAAU,SAAS,YAAY,qBAAqB,KAAK,UAAU,IAAI,GAAG;AACnF,eAAO,gBAAgB,UAAU;AAAA,MACnC;AACA,YAAM,SAAS,OAAO,UAAU,UAAU,UAAU,UAAU;AAC9D,UAAI,OAAO,UAAU,MAAM,KAAK,UAAU,OAAO,UAAU,IAAK,QAAO,SAAS;AAAA,IAClF;AAAA,EACF,QAAQ;AAAA,EAER;AAIA,QAAM,OAAO,CAAC,OAAgB,QAAyB;AACrD,QAAI;AACF,aAAO,SAAS,OAAO,UAAU,WAAW,QAAQ,IAAI,OAAO,GAAG,IAAI;AAAA,IACxE,QAAQ;AACN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UUID","sandboxLeaseTelemetryKey","parseWorkspaceArchiveObjectRef","parseWorkspaceArchiveObjectRef","sandboxLeaseTelemetryKey","randomUUID","resumeEnvelope","sandboxLifecycleTransitionWaitMs","markWarmLeaseInstanceLost","readLease","establishSandboxSessionFromEnvelope","isProviderSandboxNotFoundError","resolveModalCheckpointProviderBindingForSession","verifySandboxExecReadiness","readLease","establishSandboxSessionFromEnvelope","verifySandboxExecReadiness","isProviderSandboxNotFoundError","markWarmLeaseInstanceLost","resolveModalCheckpointProviderBindingForSession","sandboxLifecycleTransitionWaitMs","process"]}
1
+ {"version":3,"sources":["../src/sandbox-snapshot-diagnostics.ts","../src/session-event-fanout.ts","../src/sandbox-archive-storage.ts","../src/sandbox-resume.ts","../src/warm-capture-holder.ts","../src/sandbox-routing.ts"],"sourcesContent":["import { sandboxLeaseTelemetryKey, type Observability } from \"@opengeni/observability\";\n\ntype SafeSnapshotError = {\n errorClass: \"SnapshotOperationError\";\n errorCode: \"snapshot_operation_failed\";\n status?: number;\n origin: \"sandbox-resume\" | \"worker-lifecycle\";\n causeName?: string;\n integrityCode?: string;\n providerErrorName?: string;\n providerGrpcCode?: number;\n providerHttpStatus?: number;\n providerRetryable?: boolean;\n};\n\nexport function safeSnapshotError(\n error: unknown,\n origin: SafeSnapshotError[\"origin\"] = \"sandbox-resume\",\n): SafeSnapshotError {\n const fields: SafeSnapshotError = {\n errorClass: \"SnapshotOperationError\",\n errorCode: \"snapshot_operation_failed\",\n origin,\n };\n try {\n if (error && typeof error === \"object\") {\n const candidate = error as {\n name?: unknown;\n code?: unknown;\n status?: unknown;\n statusCode?: unknown;\n };\n if (\n typeof candidate.name === \"string\" &&\n /^[A-Z][A-Za-z0-9]{2,62}Error$/u.test(candidate.name)\n ) {\n fields.causeName = candidate.name;\n }\n if (typeof candidate.code === \"string\" && /^[a-z0-9_]{1,64}$/u.test(candidate.code)) {\n fields.integrityCode = candidate.code;\n }\n const status = Number(candidate.status ?? candidate.statusCode);\n if (Number.isInteger(status) && status >= 100 && status <= 599) fields.status = status;\n }\n } catch {\n // Diagnostics must never replace the exact internal snapshot failure.\n }\n // The SDK wraps provider classification in details, not Error.cause. Never\n // project free-form messages, causes, request IDs or payloads. Read fields\n // independently so a hostile getter cannot hide other safe classifications.\n const read = (value: unknown, key: string): unknown => {\n try {\n return value && typeof value === \"object\" ? Reflect.get(value, key) : undefined;\n } catch {\n return undefined;\n }\n };\n const details = read(error, \"details\");\n const providerName = read(details, \"errorName\");\n if (\n typeof providerName === \"string\" &&\n [\n \"ClientError\",\n \"TimeoutError\",\n \"ConnectionError\",\n \"AuthError\",\n \"NotFoundError\",\n \"InvalidError\",\n \"RemoteError\",\n \"AbortError\",\n ].includes(providerName)\n )\n fields.providerErrorName = providerName;\n const grpcCode = read(details, \"errorCode\");\n if (\n providerName === \"ClientError\" &&\n typeof grpcCode === \"number\" &&\n Number.isInteger(grpcCode) &&\n grpcCode >= 0 &&\n grpcCode <= 16\n )\n fields.providerGrpcCode = grpcCode;\n for (const key of [\"status\", \"httpStatus\", \"responseStatus\"]) {\n const status = read(details, key);\n if (typeof status === \"number\" && Number.isInteger(status) && status >= 100 && status <= 599) {\n fields.providerHttpStatus = status;\n break;\n }\n }\n const retryable = read(error, \"retryable\");\n if (typeof retryable === \"boolean\") fields.providerRetryable = retryable;\n return fields;\n}\n\nexport function warnDrainSnapshotFailure(\n observability: Pick<Observability, \"warn\">,\n message: string,\n error: unknown,\n lease: { workspaceId?: string; sandboxGroupId: string; leaseEpoch: number },\n): void {\n try {\n observability.warn(message, {\n ...safeSnapshotError(error, \"worker-lifecycle\"),\n ...(lease.workspaceId\n ? { sandboxLeaseKey: sandboxLeaseTelemetryKey(lease.workspaceId, lease.sandboxGroupId) }\n : {}),\n leaseEpoch: lease.leaseEpoch,\n });\n } catch {\n // Logging cannot replace the provider failure or prevent claim release.\n }\n}\n","import type { SessionEvent } from \"@opengeni/contracts\";\nimport type { EventBus } from \"@opengeni/events\";\n\n/** Best-effort live fanout of events that are already durable, grouped by\n * session. Durable catch-up remains the source of truth, so failures are only\n * reported. */\nexport async function publishDurableSessionEvents(\n bus: EventBus | null | undefined,\n workspaceId: string,\n events: readonly SessionEvent[] | undefined,\n onError: (error: unknown) => void = () => undefined,\n): Promise<void> {\n if (!bus || !events?.length) return;\n for (const sessionId of new Set(events.map((event) => event.sessionId))) {\n await bus\n .publish(\n workspaceId,\n sessionId,\n events.filter((event) => event.sessionId === sessionId),\n )\n .catch(onError);\n }\n}\n","import { uploadWorkspaceArchiveSpool, type ObjectStorage } from \"@opengeni/storage\";\nimport { randomUUID } from \"node:crypto\";\nimport type { VerifiedHostWorkspaceArchive } from \"@opengeni/runtime/sandbox\";\nimport {\n parseWorkspaceArchiveObjectRef,\n workspaceArchiveObjectKey,\n type WorkspaceArchiveDescriptor,\n type WorkspaceArchiveObjectRef,\n} from \"@opengeni/contracts\";\n\nexport class WorkspaceArchiveObjectStorageRequiredError extends Error {\n readonly code = \"workspace_archive_object_storage_required\" as const;\n\n constructor(backend: string) {\n super(`${backend} workspace archives require object storage`);\n this.name = \"WorkspaceArchiveObjectStorageRequiredError\";\n }\n}\n\nexport function collectWorkspaceArchiveObjectKeys(\n resumeState: Record<string, unknown> | null | undefined,\n): Set<string> {\n const sessionState =\n resumeState?.sessionState && typeof resumeState.sessionState === \"object\"\n ? (resumeState.sessionState as Record<string, unknown>)\n : null;\n const keys = new Set<string>();\n for (const value of [sessionState?.workspaceArchiveRef, sessionState?.workspaceArchivePrevRef]) {\n const ref = parseWorkspaceArchiveObjectRef(value);\n if (ref) keys.add(ref.key);\n }\n return keys;\n}\n\nexport async function putTarWorkspaceArchiveObject(input: {\n objectStorage: ObjectStorage;\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n archive:\n | { bytes: Uint8Array; descriptor: WorkspaceArchiveDescriptor }\n | VerifiedHostWorkspaceArchive;\n}): Promise<WorkspaceArchiveObjectRef> {\n // Snapshot caller-owned metadata before any provider callback can mutate it.\n const descriptor = structuredClone(input.archive.descriptor);\n if (descriptor.version !== 1) {\n throw new Error(\"Object-storage workspace archives are portable tar only\");\n }\n const key = workspaceArchiveObjectKey({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n revision: descriptor.revision,\n uploadId: randomUUID(),\n });\n const archive = input.archive;\n if (\"spool\" in archive) {\n if (\n archive.spool.byteSize !== descriptor.archiveBytes ||\n archive.spool.sha256 !== descriptor.archiveSha256\n ) {\n throw new Error(\"Workspace archive spool does not match its verified descriptor\");\n }\n }\n const source =\n \"spool\" in archive\n ? archive.spool\n : {\n path: \"\",\n byteSize: archive.bytes.byteLength,\n sha256: descriptor.archiveSha256,\n async *open() {\n for (let offset = 0; offset < archive.bytes.length; offset += 1024 * 1024)\n yield archive.bytes.subarray(offset, offset + 1024 * 1024);\n },\n async dispose() {},\n };\n try {\n await uploadWorkspaceArchiveSpool(input.objectStorage, key, {\n ...source,\n byteSize: descriptor.archiveBytes,\n sha256: descriptor.archiveSha256,\n open: source.open.bind(source),\n });\n } catch (error) {\n // This fresh locator has never been offered to database publication. An\n // ambiguous provider upload can leave an orphan, never overwrite a retained\n // archive or justify deleting another attempt's object.\n await input.objectStorage.deleteObject(key).catch(() => undefined);\n throw error;\n }\n return {\n schema: \"sandbox_archive_object_v1\",\n key,\n sha256: descriptor.archiveSha256,\n bytes: descriptor.archiveBytes,\n backend: input.objectStorage.backend,\n };\n}\n\n/** The caller owns a fresh candidate returned by this module. A thrown or lost\n * database response is UNKNOWN: it may have committed, so never delete on catch.\n * Only the transaction's exact candidate disposition can authorize cleanup. */\nexport async function persistWorkspaceArchiveCandidate<\n T extends {\n wrote: boolean;\n candidateDisposition?: \"adopted\" | \"already_referenced\" | \"unused\";\n },\n>(input: {\n objectStorage?: ObjectStorage | null;\n ref?: WorkspaceArchiveObjectRef;\n persist: () => Promise<T>;\n}): Promise<T> {\n const objectStorage = input.objectStorage;\n const ref = input.ref ? { ...input.ref } : undefined;\n const result = await input.persist();\n if (objectStorage && ref && result.candidateDisposition === \"unused\") {\n await deleteUnpublishedWorkspaceArchiveObject(objectStorage, ref);\n }\n return result;\n}\n\nexport async function putVersion1TarArchiveOrInline(input: {\n backend: string;\n objectStorage?: ObjectStorage | null | undefined;\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n archive:\n | VerifiedHostWorkspaceArchive\n | {\n bytes: Uint8Array;\n descriptor: WorkspaceArchiveDescriptor;\n base64: string;\n };\n metrics?: {\n onWorkspaceArchiveObject?: (input: {\n outcome: \"put\" | \"put_failed\" | \"deleted_unpublished\";\n backend: string;\n }) => void;\n };\n}): Promise<{\n workspaceArchive?: string;\n workspaceArchiveRef?: WorkspaceArchiveObjectRef;\n}> {\n if (input.archive.descriptor.version !== 1) {\n if (\"spool\" in input.archive) throw new Error(\"Native snapshots cannot use a portable spool\");\n return { workspaceArchive: input.archive.base64 };\n }\n if (input.backend === \"opensandbox\" && !input.objectStorage) {\n throw new WorkspaceArchiveObjectStorageRequiredError(\"opensandbox\");\n }\n if (!input.objectStorage) {\n if (\"spool\" in input.archive)\n throw new WorkspaceArchiveObjectStorageRequiredError(input.backend);\n return { workspaceArchive: input.archive.base64 };\n }\n try {\n const workspaceArchiveRef = await putTarWorkspaceArchiveObject({\n objectStorage: input.objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n archive: input.archive,\n });\n try {\n input.metrics?.onWorkspaceArchiveObject?.({\n outcome: \"put\",\n backend: input.objectStorage.backend,\n });\n } catch {\n /* metrics must not affect persist */\n }\n console.info(\"workspace archive object put\", {\n key: workspaceArchiveRef.key,\n bytes: workspaceArchiveRef.bytes,\n sha256: workspaceArchiveRef.sha256,\n });\n return { workspaceArchiveRef };\n } catch (error) {\n try {\n input.metrics?.onWorkspaceArchiveObject?.({\n outcome: \"put_failed\",\n backend: input.objectStorage.backend,\n });\n } catch {\n /* metrics must not affect persist */\n }\n throw error;\n }\n}\n\nexport async function deleteUnpublishedWorkspaceArchiveObject(\n objectStorage: ObjectStorage | null | undefined,\n ref: WorkspaceArchiveObjectRef | undefined,\n metrics?: {\n onWorkspaceArchiveObject?: (input: { outcome: \"deleted_unpublished\"; backend: string }) => void;\n },\n): Promise<void> {\n if (!objectStorage || !ref) return;\n try {\n await objectStorage.deleteObject(ref.key);\n try {\n metrics?.onWorkspaceArchiveObject?.({\n outcome: \"deleted_unpublished\",\n backend: objectStorage.backend,\n });\n } catch {\n /* metrics must not affect persist */\n }\n } catch {\n console.error(\"unpublished workspace archive object delete failed\", { key: ref.key });\n }\n}\n\nexport async function deleteWorkspaceArchiveObjectKeys(\n objectStorage: ObjectStorage,\n keys: Iterable<string>,\n): Promise<void> {\n for (const key of keys) {\n await objectStorage.deleteObject(key);\n }\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// viewers and managed ComputerSession operations initialize it 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 type { EventBus } from \"@opengeni/events\";\nimport { publishDurableSessionEvents } from \"./session-event-fanout\";\nimport {\n effectiveSandboxLifecycle,\n sandboxArchiveCaptureTimeoutMs,\n sandboxLifecycleTransitionWaitMs,\n sandboxWarmRateMicrosPerSecond,\n type Settings,\n} from \"@opengeni/config\";\nimport { randomUUID } from \"node:crypto\";\nimport { retainsHolderForWarmCapture } from \"./warm-capture-holder\";\nimport {\n acquireLease,\n adoptLegacyModalCheckpointArtifact,\n beginSandboxRematerialization,\n sessionHoldsFreshWorkspaceRecovery,\n claimWorkspaceArchiveCapture,\n commitWarmingToWarm,\n failSandboxRematerialization,\n failWarmingToCold,\n beginModalProviderCreate,\n getSandboxSessionEnvelope,\n heartbeatLeaseHolderStatus,\n markSandboxRestoreVerifying,\n markWarmLeaseInstanceLost,\n markSandboxCheckpointArtifactDeletePending,\n persistWarmSnapshot,\n readLease,\n registerSandboxCheckpointArtifact,\n recordWarmingSandboxCreated,\n reinstateTurnLeaseHolder,\n leaseMayHaveUntrackedWriters,\n releaseWorkspaceArchiveCapture,\n releaseLeaseHolder,\n touchLeaseHolder,\n SandboxLeaseRecoveryBlockedError,\n SandboxLeaseSupersededError,\n SandboxLeaseTransitionError,\n type Database,\n type LeaseHolderKind,\n} from \"@opengeni/db\";\nimport {\n captureWorkspaceArchiveForStorage,\n disposeWorkspaceArchive,\n type VerifiedWorkspaceArchivePayload,\n describeLegacyNativeSnapshotArchive,\n inlineWorkspaceArchiveForRestore,\n MODAL_EXEC_READINESS_TIMEOUT_MS,\n SandboxExecReadinessError,\n WorkspaceArchiveIntegrityError,\n establishSandboxSessionFromEnvelope,\n isProviderSandboxNotFoundError,\n parseWorkspaceArchiveDescriptor,\n providerWorkspaceCapturePolicy,\n SandboxProviderContinuityUnavailableError,\n requirePersistableReplacementSandboxEnvelope,\n renewSandboxProviderExpiration,\n modalSessionMatchesCheckpointProviderBinding,\n resolveModalCheckpointProviderBindingForSession,\n serializeReplacementSandboxEnvelope,\n tagModalSandbox,\n terminateUnpublishedSandboxSession,\n verifySandboxExecReadiness,\n withoutSandboxProviderIdentity,\n workspaceArchiveDownloadTemporaryDirectory,\n type EstablishedSandboxSession,\n type RuntimeMetricsHooks,\n type WorkspaceCaptureSkipReason,\n type SandboxReadinessReplacementOutcome,\n type WorkspaceArchiveDescriptor,\n} from \"@opengeni/runtime\";\nimport {\n downloadWorkspaceArchiveSpool,\n WorkspaceArchiveStorageError,\n type ObjectStorage,\n} from \"@opengeni/storage\";\nimport { sandboxLeaseTelemetryKey, type Observability } from \"@opengeni/observability\";\nimport { safeSnapshotError } from \"./sandbox-snapshot-diagnostics\";\nexport { safeSnapshotError } from \"./sandbox-snapshot-diagnostics\";\nimport { parseWorkspaceArchiveObjectRef } from \"@opengeni/contracts\";\nimport {\n persistWorkspaceArchiveCandidate,\n putVersion1TarArchiveOrInline,\n} from \"./sandbox-archive-storage\";\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 objectStorage?: ObjectStorage | null;\n\n logicalFallbackSettings?: Settings;\n sandboxMetrics?: RuntimeMetricsHooks;\n /** Structured logger for lifecycle decisions (holder release reasons). Falls\n * back to the console when a lean caller passes none. */\n observability?: Pick<Observability, \"info\" | \"warn\">;\n /** Test seam only: cadence of the private holder-liveness loop (default 10 s).\n * Production keeps the default; the dead-worker reap horizon assumes it. */\n holderLivenessIntervalMs?: number;\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 /** Test seam for the bounded command-readiness proof the elected spawner runs\n * on its freshly created box before publishing the lease warm. Production\n * uses {@link waitForSandboxExecReadiness} with the shared 60 s budget. */\n verifySpawnedSandboxReadiness?: (\n established: EstablishedSandboxSession,\n identity: { sandboxGroupId: string },\n ) => Promise<void>;\n /** Test seam for the jittered pause before the single fresh-box readiness\n * replacement. Production uses {@link freshSandboxReadinessReplacementDelayMs}.\n * It may be async so a test can observe the rolled-back lease in between. */\n freshSandboxReadinessReplacementDelayMs?: () => number | Promise<number>;\n /** Test seam: runs immediately after the elected spawner published its box\n * warm, before the final cancellation check. */\n onSpawnedSandboxPublished?: () => void | Promise<void>;\n /**\n * The turn attempt's fresh-box readiness replacement budget. The lazy\n * provisioner may call resumeBoxForTurn again after a typed lease\n * supersession, so the turn creates the budget once and shares it with every\n * call. Absent, the call gets its own single replacement.\n */\n freshSandboxReadinessReplacementBudget?: FreshSandboxReadinessReplacementBudget;\n /** Live fanout for background commands a provider loss settled. */\n bus?: EventBus | null;\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: Settings[\"sandboxBackend\"];\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 /** Deployment/workspace image pins apply only to new creates; an existing\n * group keeps its image. Omission preserves explicit image matching (B3). */\n imagePolicy?: \"require_match\" | \"new_creates_only\";\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\n/**\n * Structural ownership of the provider boundary that failed while establishing\n * a logical sandbox provision. Object errors retain their identity and receive\n * an out-of-band stage; primitive thrown values use a typed wrapper. In both\n * cases the source diagnostic is unchanged and the stage is never guessed from\n * prose.\n */\nexport type SandboxProvisionFailureStage = \"create\" | \"resume\" | \"archive_recovery\";\n\nexport class SandboxProvisionStageError extends Error {\n readonly name = \"SandboxProvisionStageError\";\n\n constructor(\n public readonly stage: SandboxProvisionFailureStage,\n public readonly source: unknown,\n ) {\n super(source instanceof Error ? source.message : String(source), { cause: source });\n }\n}\n\nconst sandboxProvisionFailureStages = new WeakMap<object, SandboxProvisionFailureStage>();\n\nexport function sandboxProvisionFailureStage(error: unknown): SandboxProvisionFailureStage | null {\n if (!error || typeof error !== \"object\") return null;\n return (\n sandboxProvisionFailureStages.get(error) ??\n (error instanceof SandboxProvisionStageError ? error.stage : null)\n );\n}\n\nfunction sandboxProvisionStageError(stage: SandboxProvisionFailureStage, error: unknown): unknown {\n if (error && typeof error === \"object\") {\n sandboxProvisionFailureStages.set(error, stage);\n return error;\n }\n return new SandboxProvisionStageError(stage, error);\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/**\n * Out-of-band proof attached to one exact {@link SandboxExecReadinessTimeoutError}\n * thrown by the elected spawner: the box that missed its readiness budget was\n * freshly created by this caller (not an attached, resumed, or provider-continuity\n * box), it was never published warm, the provider terminated it, and the holder\n * was released. Only such an error may be replaced by re-entering admission.\n */\nconst disposedUnreadyFreshSandboxErrors = new WeakSet<object>();\n\n/** True only for a spawner readiness timeout whose unready fresh box is proven gone. */\nexport function isReplaceableFreshSandboxReadinessTimeout(error: unknown): boolean {\n return (\n error instanceof SandboxExecReadinessTimeoutError &&\n disposedUnreadyFreshSandboxErrors.has(error)\n );\n}\n\n/**\n * A burst of simultaneous turn starts can leave many freshly created provider\n * boxes command-unready at once. The single replacement re-enters admission\n * after a jittered pause so the replacement creates do not re-synchronize into\n * the same burst. Bounded to [2 s, 10 s).\n */\nexport const FRESH_SANDBOX_READINESS_REPLACEMENT_BASE_DELAY_MS = 2_000;\nexport const FRESH_SANDBOX_READINESS_REPLACEMENT_JITTER_MS = 8_000;\n\nexport function freshSandboxReadinessReplacementDelayMs(\n random: () => number = Math.random,\n): number {\n const sample = random();\n const unit = Number.isFinite(sample) ? Math.min(Math.max(sample, 0), 1 - Number.EPSILON) : 0;\n return (\n FRESH_SANDBOX_READINESS_REPLACEMENT_BASE_DELAY_MS +\n Math.floor(unit * FRESH_SANDBOX_READINESS_REPLACEMENT_JITTER_MS)\n );\n}\n\n/** Replacements allowed per turn attempt, across every resumeBoxForTurn call. */\nexport const FRESH_SANDBOX_READINESS_REPLACEMENTS_PER_TURN_ATTEMPT = 1;\n\nexport type FreshSandboxReadinessReplacementBudget = { remaining: number };\n\nexport function createFreshSandboxReadinessReplacementBudget(): FreshSandboxReadinessReplacementBudget {\n return { remaining: FRESH_SANDBOX_READINESS_REPLACEMENTS_PER_TURN_ATTEMPT };\n}\n\nfunction recordFreshSandboxReadinessReplacement(\n metrics: RuntimeMetricsHooks | undefined,\n backend: string,\n outcome: SandboxReadinessReplacementOutcome,\n): void {\n try {\n metrics?.onSandboxReadinessReplacement?.({ backend, outcome });\n } catch {\n // Metrics emission must never affect sandbox recovery or error propagation.\n }\n}\n\nasync function sleepUnlessCancelled(ms: number, signal: AbortSignal | undefined): Promise<boolean> {\n if (signal?.aborted) return false;\n if (ms <= 0) return true;\n return await new Promise<boolean>((resolve) => {\n const onAbort = () => {\n clearTimeout(timer);\n resolve(false);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(true);\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\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\n/**\n * A remote provider may return a sandbox handle before its command router\n * accepts the first exec. The upstream session's yieldTimeMs starts only after\n * sandbox.exec() returns, so it cannot bound that initial RPC. Probe it before\n * publishing the 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 signal?: AbortSignal,\n): Promise<void> {\n try {\n await verifySandboxExecReadiness(established, timeoutMs, signal);\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 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 const archiveRef = parseWorkspaceArchiveObjectRef(sessionState?.workspaceArchiveRef);\n const hasInline = typeof archive === \"string\" && archive.length > 0;\n if (!hasInline && !archiveRef) {\n return null;\n }\n const previous = sessionState?.workspaceArchivePrev;\n const previousRef = parseWorkspaceArchiveObjectRef(sessionState?.workspaceArchivePrevRef);\n const metadata = sessionState?.workspaceArchiveMeta;\n const previousMetadata = sessionState?.workspaceArchivePrevMeta;\n const capturedAt = sessionState?.workspaceArchiveAt;\n return {\n ...(hasInline && !archiveRef ? { workspaceArchive: archive } : {}),\n ...(archiveRef ? { workspaceArchiveRef: archiveRef } : {}),\n ...(metadata !== undefined ? { workspaceArchiveMeta: metadata } : {}),\n ...(typeof previous === \"string\" && previous.length > 0 && !previousRef\n ? { workspaceArchivePrev: previous }\n : {}),\n ...(previousRef ? { workspaceArchivePrevRef: previousRef } : {}),\n ...(previousMetadata !== undefined ? { workspaceArchivePrevMeta: previousMetadata } : {}),\n ...(typeof capturedAt === \"string\" && capturedAt.length > 0\n ? { workspaceArchiveAt: capturedAt }\n : {}),\n };\n}\n\nasync function materializeSpawnEnvelopeArchive(\n envelope: unknown,\n objectStorage: ObjectStorage | null | undefined,\n): Promise<unknown> {\n if (!envelope || typeof envelope !== \"object\") return envelope;\n const record = envelope as Record<string, unknown>;\n const sessionState =\n record.sessionState &&\n typeof record.sessionState === \"object\" &&\n !Array.isArray(record.sessionState)\n ? (record.sessionState as Record<string, unknown>)\n : null;\n if (!sessionState || !parseWorkspaceArchiveObjectRef(sessionState.workspaceArchiveRef)) {\n return envelope;\n }\n if (!objectStorage) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_storage_unavailable\",\n \"workspace archive object storage is not configured\",\n { retryable: true },\n );\n }\n const descriptor = parseWorkspaceArchiveDescriptor(sessionState.workspaceArchiveMeta);\n if (\n process.platform === \"linux\" &&\n descriptor?.version === 1 &&\n descriptor.workspace.projection === \"sdk_local_archive_v1\"\n ) {\n return envelope;\n }\n return {\n ...record,\n sessionState: await inlineWorkspaceArchiveForRestore(sessionState, (key) =>\n objectStorage.getObjectBytes(key),\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\nexport type SandboxDeadlineRotationCheckpointResult = {\n /** The exact established epoch still carries a requested rotation and a\n * complete current-generation archive: the turn may abort orderly. */\n checkpointed: boolean;\n /** What the defense-in-depth holder step observed before the capture. */\n holder: Awaited<ReturnType<typeof reinstateTurnLeaseHolder>>[\"status\"];\n lease: Awaited<ReturnType<typeof readLease>>;\n};\n\n/**\n * The orderly provider-deadline rotation checkpoint for one running turn. The\n * turn-side lease heartbeat calls this once it observes a rotation-fenced lease\n * at its established epoch/instance; `checkpointed: true` licenses the\n * SandboxDeadlineRotationError abort that hands the same logical turn to the\n * cold successor.\n *\n * Defense in depth: the warm capture claim requires exactly this turn's holder.\n * If that holder was lost while the attempt is still the active writer (a stale\n * release, a reap race), `reinstateTurnLeaseHolder` puts it back under the\n * exact epoch/instance fence before the capture, so a lost holder cannot\n * silently disable the orderly abort and leave the reaper to terminate the box\n * under the running turn. Never captures when the epoch/instance changed.\n */\nexport async function persistSandboxDeadlineRotationCheckpoint(\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 expected: { leaseEpoch: number; instanceId: string },\n signal?: AbortSignal,\n): Promise<SandboxDeadlineRotationCheckpointResult> {\n const { db, settings } = services;\n // A cancelled attempt must never briefly regain its holder: its eager\n // cancellation listener may already have released it, and reinstating here\n // would pin the lease behind an attempt that is being torn down.\n if (signal?.aborted) {\n return { checkpointed: false, holder: \"attempt_fenced\", lease: null };\n }\n const reinstated = await reinstateTurnLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n sessionId: ids.sessionId,\n attemptId: ids.attemptId,\n expectedEpoch: expected.leaseEpoch,\n expectedInstanceId: expected.instanceId,\n leaseTtlMs: settings.sandboxLeaseTtlMs,\n });\n if (reinstated.status === \"reinstated\") {\n const message = \"sandbox rotation checkpoint reinstated the live turn holder\";\n const fields = {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n sandboxGroupId: ids.sandboxGroupId,\n leaseEpoch: expected.leaseEpoch,\n liveness: reinstated.lease.liveness,\n };\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n }\n if (reinstated.status !== \"present\" && reinstated.status !== \"reinstated\") {\n return { checkpointed: false, holder: reinstated.status, lease: null };\n }\n await maybePersistWarmWorkspaceSnapshot(\n services,\n ids,\n session,\n expected.leaseEpoch,\n signal,\n true,\n );\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n const checkpointed =\n lease?.leaseEpoch === expected.leaseEpoch &&\n lease.instanceId === expected.instanceId &&\n lease.rotationRequestedAt !== null &&\n lease.archiveComplete &&\n signal?.aborted !== true;\n return { checkpointed, holder: reinstated.status, lease };\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 type WarmWorkspaceSnapshotPromise = Promise<boolean> & {\n /** Settles only after any provider capture continuation has published or\n * failed and released its exact workspace-capture admission. */\n readonly settled: Promise<void>;\n};\n\n/** Who owns a warm checkpoint: the exact turn attempt holding the box, or\n * (`idleCheckpoint`) the reaper checkpointing a box that no turn holds and\n * viewers, interactions or running background commands keep warm. The idle\n * owner is fenced by its exact capture claim alone and is limited to\n * point-in-time Modal captures. */\nexport type WarmWorkspaceSnapshotOwner = {\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n} & (\n | { sessionId: string; turnId: string; attemptId: string; idleCheckpoint?: never }\n | { idleCheckpoint: true; sessionId?: never; turnId?: never; attemptId?: never }\n);\n\nexport function maybePersistWarmWorkspaceSnapshot(\n services: SandboxResumeServices,\n ids: WarmWorkspaceSnapshotOwner,\n session: unknown,\n leaseEpoch: number,\n signal?: AbortSignal,\n force = false,\n): WarmWorkspaceSnapshotPromise {\n let continuationRegistered = false;\n let resolvePhysicalSettlement: () => void = () => undefined;\n const physicalSettlement = new Promise<void>((resolve) => {\n resolvePhysicalSettlement = resolve;\n });\n const result = persistWarmWorkspaceSnapshot(\n services,\n ids,\n session,\n leaseEpoch,\n signal,\n force,\n (continuation) => {\n continuationRegistered = true;\n void continuation.then(resolvePhysicalSettlement, resolvePhysicalSettlement);\n },\n );\n void result.then(\n () => {\n if (!continuationRegistered) resolvePhysicalSettlement();\n },\n () => {\n if (!continuationRegistered) resolvePhysicalSettlement();\n },\n );\n return Object.assign(result, { settled: physicalSettlement });\n}\n\nasync function persistWarmWorkspaceSnapshot(\n services: SandboxResumeServices,\n ids: WarmWorkspaceSnapshotOwner,\n session: unknown,\n leaseEpoch: number,\n signal: AbortSignal | undefined,\n force: boolean,\n registerOwnedContinuation: (continuation: Promise<void>) => void,\n): Promise<boolean> {\n const { db, settings } = services;\n const warnSnapshotFailure = (message: string, error: unknown): void => {\n const fields = {\n ...safeSnapshotError(error),\n sandboxLeaseKey: sandboxLeaseTelemetryKey(ids.workspaceId, ids.sandboxGroupId),\n leaseEpoch,\n };\n try {\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n } catch {\n // Diagnostics cannot change provider settlement or capture-gate cleanup.\n }\n };\n const reportSkipped = (backend: unknown, reason: WorkspaceCaptureSkipReason): void => {\n try {\n services.sandboxMetrics?.onWorkspaceCaptureSkipped?.({\n backend: typeof backend === \"string\" ? backend : \"unknown\",\n reason,\n });\n } catch {\n // Telemetry never changes whether a checkpoint is attempted.\n }\n };\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 persistWorkspaceTar?: () => Promise<Uint8Array | undefined>;\n backendId?: unknown;\n state?: {\n workspacePersistence?: unknown;\n providerState?: { workspacePersistence?: unknown };\n };\n };\n if (\n typeof persistable.persistWorkspace !== \"function\" &&\n typeof persistable.persistWorkspaceTar !== \"function\"\n ) {\n console.error(\"mid-session workspace snapshot skipped (no persist primitive)\", {\n backendId: typeof persistable.backendId === \"string\" ? persistable.backendId : null,\n });\n reportSkipped(persistable.backendId, \"no_persist_primitive\");\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 const canWarmCapture =\n lease?.liveness === \"warm\" && lease.instanceId !== null && lease.leaseEpoch === leaseEpoch;\n const canForceDrainingCapture =\n force === true &&\n lease?.liveness === \"draining\" &&\n lease.instanceId !== null &&\n lease.leaseEpoch === leaseEpoch;\n const turnOwner = ids.idleCheckpoint === true ? null : ids;\n if (!lease || (!canWarmCapture && (!canForceDrainingCapture || !turnOwner))) {\n console.error(\"mid-session workspace snapshot skipped (lease not warm)\", {\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n liveness: lease?.liveness ?? null,\n leaseEpoch: lease?.leaseEpoch ?? null,\n hasInstance: lease?.instanceId !== null && lease?.instanceId !== undefined,\n });\n reportSkipped(lease?.backend ?? persistable.backendId, \"lease_not_warm\");\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. An\n // attached viewer or interaction can write without advancing the\n // generation; the claim then decides whether the box is really clean.\n if (lease.archiveComplete && !leaseMayHaveUntrackedWriters(lease)) {\n return false;\n }\n if (lease.instanceId === null) {\n return false;\n }\n const instanceId = lease.instanceId;\n const captureLiveness: \"warm\" | \"draining\" = canWarmCapture ? \"warm\" : \"draining\";\n const capturePolicy = providerWorkspaceCapturePolicy(lease.backend, session);\n if (!capturePolicy || capturePolicy.liveInstance !== \"preserved\") {\n console.error(\"mid-session workspace snapshot skipped (capture policy)\", {\n sandboxGroupId: ids.sandboxGroupId,\n backend: lease.backend,\n liveInstance: capturePolicy?.liveInstance ?? null,\n });\n reportSkipped(lease.backend, \"capture_policy\");\n return false;\n }\n const nativeModalPersistence =\n workspacePersistence === \"snapshot_filesystem\" ||\n workspacePersistence === \"snapshot_directory\";\n if (!turnOwner && !nativeModalPersistence) {\n // Only a paused-box image may run around the commands keeping an idle\n // box warm; a file-by-file read of the running box could tear.\n reportSkipped(lease.backend, \"capture_policy\");\n return false;\n }\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: captureLiveness,\n captureTimeoutMs,\n minIntervalMs: force ? 0 : intervalMs,\n providerReplaySafe: capturePolicy.takeover === \"same_request\",\n takeoverSafe: capturePolicy.takeover !== \"exclusive\",\n // Modal pauses the box for a native snapshot, so the image is one\n // instant even while background commands run.\n pointInTimeCapture: nativeModalPersistence,\n ...(captureLiveness !== \"warm\"\n ? {}\n : turnOwner\n ? {\n warmAttempt: {\n sessionId: turnOwner.sessionId,\n turnId: turnOwner.turnId,\n attemptId: turnOwner.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(turnOwner.attemptId),\n },\n }\n : { idleCheckpoint: true }),\n });\n if (claimed.status !== \"claimed\") {\n // A scheduled interval not being due is normal, including after a failed\n // attempt. Do not turn every ten-second heartbeat into an error log.\n if (claimed.status === \"throttled\" || claimed.status === \"clean\") return false;\n console.error(\"mid-session workspace snapshot skipped (capture claim)\", {\n sandboxGroupId: ids.sandboxGroupId,\n status: claimed.status,\n });\n reportSkipped(lease.backend, claimed.status);\n return false;\n }\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: VerifiedWorkspaceArchivePayload,\n ): Promise<{ id: string } | null> => {\n if (\n archive.kind === \"host_spool\" ||\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 // A provider-native capture 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 // A host-backed spool capture reads the workspace locally, so it is\n // stopped at the snapshot timeout instead: its rejection is the physical\n // end of the reads, and holding the write fence for an unbounded local\n // read would turn a slow host into failed workspace writes.\n const captureAbort = new AbortController();\n const captureAbortTimer = setTimeout(\n () => captureAbort.abort(new SnapshotTimeoutError(settings.sandboxSnapshotTimeoutMs)),\n settings.sandboxSnapshotTimeoutMs,\n );\n captureAbortTimer.unref?.();\n const captureAndPublish = (async (): Promise<boolean> => {\n const captureStarted = performance.now();\n let captureOutcome: \"completed\" | \"failed\" = \"failed\";\n let archive: VerifiedWorkspaceArchivePayload | undefined;\n let candidate: { id: string } | null = null;\n let publicationAttempted = false;\n try {\n archive = await captureWorkspaceArchiveForStorage(\n session,\n capturedAtMs,\n {\n requestId: claimed.claim.providerRequestId,\n strategy: capturePolicy.strategy,\n signal: captureAbort.signal,\n },\n Boolean(services.objectStorage),\n );\n clearTimeout(captureAbortTimer);\n candidate = await registerCandidate(archive);\n const archiveDescriptor = archive.descriptor;\n const published = await putVersion1TarArchiveOrInline({\n backend: lease.backend,\n objectStorage: services.objectStorage,\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n archive,\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n });\n publicationAttempted = true;\n const { wrote } = await persistWorkspaceArchiveCandidate({\n ...(services.objectStorage ? { objectStorage: services.objectStorage } : {}),\n ...(published.workspaceArchiveRef ? { ref: published.workspaceArchiveRef } : {}),\n persist: () =>\n persistWarmSnapshot(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n ...(turnOwner\n ? {\n sessionId: turnOwner.sessionId,\n turnId: turnOwner.turnId,\n attemptId: turnOwner.attemptId,\n }\n : { idleCheckpoint: true as const }),\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: instanceId,\n expectedWorkspaceGeneration: claimed.claim.workspaceGeneration,\n captureId,\n workspaceArchiveMeta: archiveDescriptor,\n ...published,\n checkpointArtifactId: candidate?.id ?? null,\n minIntervalMs: force ? 0 : intervalMs,\n capturedAtMs,\n }),\n });\n if (!wrote && candidate) {\n await abandonCandidate(candidate.id, \"snapshot_publication_fenced\");\n }\n if (wrote) captureOutcome = \"completed\";\n return wrote;\n } catch (error) {\n if (candidate && !publicationAttempted)\n await abandonCandidate(candidate.id, \"snapshot_capture_failed\");\n throw error;\n } finally {\n clearTimeout(captureAbortTimer);\n await disposeWorkspaceArchive(archive).catch(() => {\n console.warn(\"workspace archive spool cleanup failed\");\n });\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 captureOutcome = \"failed\";\n warnSnapshotFailure(\"mid-session workspace capture gate release failed\", error);\n });\n try {\n services.sandboxMetrics?.onWorkspaceCapture?.({\n backend: lease.backend,\n outcome: captureOutcome,\n durationSeconds: Math.max(0, performance.now() - captureStarted) / 1_000,\n });\n } catch {\n // A completed capture and released gate cannot depend on telemetry.\n }\n }\n })();\n const settled = captureAndPublish.then(\n (persisted) => ({ kind: \"settled\" as const, persisted }),\n (error) => {\n warnSnapshotFailure(\"mid-session workspace snapshot failed (turn unaffected)\", error);\n return { kind: \"settled\" as const, persisted: false };\n },\n );\n registerOwnedContinuation(settled.then(() => undefined));\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 // A failed snapshot does not fail the turn. Physical captures can still\n // fence commands until their exact gate settles; the caller timeout is not\n // permission to release that gate. The next eligible tick can retry.\n warnSnapshotFailure(\"mid-session workspace snapshot failed (turn unaffected)\", error);\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 *\n * A freshly created box that misses its bounded command-readiness budget is\n * replaced at most once per turn attempt (the budget is shared by every call\n * the turn's provisioner makes). The first establish has already terminated that exact\n * unpublished box, rolled its exact warming epoch back to cold (advancing the\n * epoch), and released its holder, so the replacement is an ordinary new\n * admission: it re-runs the cold->warming CAS, persists its own provider\n * instance before readiness, and may instead attach to a sibling that won the\n * CAS first. Nothing model- or tool-visible ran on the discarded box, so no\n * side effect is replayed. A second readiness timeout fails the turn exactly\n * as before; attached/resumed boxes and unconfirmed terminations never\n * replace.\n */\nexport async function resumeBoxForTurn(\n services: SandboxResumeServices,\n ids: ResumeBoxIds,\n kind: \"turn\",\n holderId: TurnSandboxLeaseHolderId,\n): Promise<ResumedTurnSandbox> {\n try {\n return await resumeBoxForTurnOnce(services, ids, kind, holderId);\n } catch (error) {\n if (!isReplaceableFreshSandboxReadinessTimeout(error)) throw error;\n const readiness = error as SandboxExecReadinessTimeoutError;\n const warn = (message: string, fields: Parameters<Observability[\"warn\"]>[1]) => {\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n };\n const identity = {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n sandboxGroupId: ids.sandboxGroupId,\n backend: readiness.backend,\n instanceId: readiness.instanceId,\n readinessTimeoutMs: readiness.timeoutMs,\n };\n const budget =\n services.freshSandboxReadinessReplacementBudget ??\n createFreshSandboxReadinessReplacementBudget();\n if (budget.remaining <= 0) {\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n \"budget_spent\",\n );\n warn(\n \"sandbox command-readiness timed out on a fresh box; this turn attempt already used its replacement\",\n identity,\n );\n throw error;\n }\n budget.remaining -= 1;\n const delayMs = await (\n services.freshSandboxReadinessReplacementDelayMs ?? freshSandboxReadinessReplacementDelayMs\n )();\n warn(\"sandbox command-readiness timed out on a fresh box; replacing it once after jitter\", {\n ...identity,\n replacementDelayMs: delayMs,\n });\n if (!(await sleepUnlessCancelled(delayMs, services.cancellationSignal))) {\n // Cancellation owns the turn boundary; surface the original typed\n // readiness failure rather than starting a replacement.\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n \"cancelled\",\n );\n throw error;\n }\n try {\n const replaced = await resumeBoxForTurnOnce(services, ids, kind, holderId);\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n \"replaced\",\n );\n return replaced;\n } catch (replacementError) {\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n services.cancellationSignal?.aborted\n ? \"cancelled\"\n : replacementError instanceof SandboxExecReadinessTimeoutError\n ? \"failed_again\"\n : \"replacement_failed\",\n );\n throw replacementError;\n }\n }\n}\n\nasync function resumeBoxForTurnOnce(\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 warmBilling: {\n mode: settings.sandboxWarmBillingMode,\n rateMicrosPerSecond: sandboxWarmRateMicrosPerSecond(settings, ids.backend),\n },\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 required 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 ...(ids.imagePolicy ? { imagePolicy: ids.imagePolicy } : {}),\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 let providerRenewalTarget: { backend: Settings[\"sandboxBackend\"]; instanceId: string } | null =\n acquired.lease.liveness === \"warm\" && acquired.lease.instanceId\n ? {\n backend: ids.backend,\n instanceId: acquired.lease.instanceId,\n }\n : null;\n let providerRenewedAtMs = Date.now();\n let providerRenewalInFlight: Promise<void> | null = null;\n const maybeRenewProviderExpiration = async (force = false): Promise<void> => {\n const target = providerRenewalTarget;\n if (!target || providerRenewalInFlight) return;\n const ttlSeconds = effectiveSandboxLifecycle(settings, target.backend).renewableTtlSeconds;\n if (ttlSeconds === null) return;\n const intervalMs = Math.max(10_000, Math.floor((ttlSeconds * 1000) / 3));\n if (!force && Date.now() - providerRenewedAtMs < intervalMs) return;\n providerRenewalInFlight = renewSandboxProviderExpiration({\n backend: target.backend,\n settings,\n instanceId: target.instanceId,\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n })\n .then(() => {\n providerRenewedAtMs = Date.now();\n })\n .finally(() => {\n providerRenewalInFlight = null;\n });\n await providerRenewalInFlight;\n };\n // Release ONLY on holder death. `heartbeatLeaseHolderStatus` separates \"this\n // holder is gone / its attempt is no longer the active writer\" from \"the lease\n // could not be extended\" (rotation requested, draining, another epoch). The\n // second is NOT a reason to release: once a provider-deadline rotation is\n // requested the turn-side heartbeat immediately preempts the attempt, whose\n // finalizer retains this holder until every attempt-owned writer is physically\n // drained. Dropping it here would let the reaper capture or terminate while a\n // provider operation may still be mutating /workspace. Both loops therefore\n // converge on \"holder alive -> never release\"; finalization performs the\n // proof-bearing release.\n const releaseDeadHolder = async (reason: string): Promise<void> => {\n // Logical closure deliberately fences heartbeat authority. It is not proof\n // that the already-admitted capture has physically settled: the finalizer\n // owns that wait and the original deadline bounds dead-worker recovery.\n // Match the reaper's retention rule without touching holder/lease TTLs.\n if (reason === \"holder_gone\" && kind === \"turn\" && holderLeaseHeartbeat) {\n const expectedEpoch = holderLeaseHeartbeat.expectedEpoch;\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (retainsHolderForWarmCapture(lease, expectedEpoch)) return;\n }\n const message = \"sandbox resume holder released: holder no longer live\";\n const fields = {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n sandboxGroupId: ids.sandboxGroupId,\n holderKind: kind,\n reason,\n };\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n void release().catch(() => undefined);\n };\n holderLivenessTimer = setInterval(() => {\n const heartbeat = holderLeaseHeartbeat;\n if (heartbeat) {\n void heartbeatLeaseHolderStatus(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 billingMode: services.settings.sandboxWarmBillingMode,\n })\n .then(async (status) => {\n if (heartbeat !== holderLeaseHeartbeat) return;\n if (!status.holderAlive) {\n // Reaped, released, or its exact attempt is no longer the active\n // writer. Stop this otherwise-unbounded provider operation and\n // idempotently drop any remaining holder state.\n await releaseDeadHolder(status.fence);\n return;\n }\n if (status.fence === \"epoch\") {\n // The lease epoch never regresses: a newer epoch means the box this\n // holder was registered against is definitively superseded (lost\n // instance replaced, re-established by a later turn). The holder\n // row is stale authority for an instance that no longer exists;\n // drop it promptly instead of pinning a successor's lease.\n await releaseDeadHolder(status.fence);\n return;\n }\n // The box is still serving this live holder: keep the provider TTL\n // renewed while the lease is ours (extended, or only rotation-fenced at\n // the same epoch). A liveness fence (draining at our epoch) means the\n // reaper now governs the instance; keep the holder but leave its\n // expiry alone.\n if (status.leaseExtended || status.fence === \"rotation_requested\") {\n void maybeRenewProviderExpiration().catch(() => undefined);\n }\n })\n .catch(() => undefined);\n return;\n }\n void touchLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n })\n .then(async (touched) => {\n if (heartbeat !== holderLeaseHeartbeat) return;\n // A canonical turn holder is rejected once its exact attempt is no\n // longer the active writer (touch is attempt-fenced only; it never\n // consults lease authority, so false here always means holder death).\n if (!touched) {\n await releaseDeadHolder(\"holder_gone\");\n return;\n }\n void maybeRenewProviderExpiration().catch(() => undefined);\n })\n .catch(() => undefined);\n }, services.holderLivenessIntervalMs ?? 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 // Set once commitWarmingToWarm publishes this box. From then on the box is\n // the group's shared, attachable workspace: a later cancellation (Pause,\n // Steer, worker shutdown) only drops this attempt's holder. Terminating it\n // here would hand the next attempt a warm lease naming a dead box, whose\n // exact-id resume then records a lost workspace that never lost anything.\n let published = false;\n let providerCreateOperationId: string | undefined;\n let providerCreateBindingKey: string | undefined;\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 // An audited decision to continue a definitively lost workspace on a new\n // EMPTY box: hydrate nothing (not even a per-session legacy archive) and\n // resume no prior provider identity. Every group member was already told\n // the workspace is empty; the DB accepts only this exact publication.\n const freshWorkspaceRecoveryId = acquired.lease.freshWorkspaceRecoveryId ?? null;\n const envelope = freshWorkspaceRecoveryId\n ? null\n : 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 // Backstop: a session already told its workspace is empty never gets a\n // legacy per-session archive back, even if the lease marker was lost.\n const legacyFallbackRefused =\n !freshWorkspaceRecoveryId &&\n acquired.lease.recovery.archive.status === \"none\" &&\n workspaceArchiveFieldsFromEnvelope(envelope) !== null &&\n (await sessionHoldsFreshWorkspaceRecovery(db, ids.workspaceId, ids.sessionId));\n const fallbackArchiveEnvelope =\n !freshWorkspaceRecoveryId &&\n !legacyFallbackRefused &&\n acquired.lease.recovery.archive.status === \"none\" &&\n workspaceArchiveFieldsFromEnvelope(envelope) !== null\n ? withoutSandboxProviderIdentity(envelope)\n : null;\n let spawnEnvelope = freshWorkspaceRecoveryId\n ? null\n : legacyFallbackRefused\n ? (acquired.lease.resumeState ?? null)\n : (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 // A fresh-workspace spawn is deliberately archive-free; commitWarmingToWarm\n // verifies the exact decision before publication.\n if (\n !freshWorkspaceRecoveryId &&\n ((acquired.lease.recovery.archive.status === \"available\" &&\n (acquired.lease.archiveComplete ||\n acquired.lease.historicalRecoveryAuthorized === true)) ||\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 (\n !freshWorkspaceRecoveryId &&\n acquired.lease.recovery.archive.status !== \"none\" &&\n !continuityRecovery\n ) {\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 persistArchiveSource =\n spawnEnvelope && typeof spawnEnvelope === \"object\"\n ? (spawnEnvelope as Record<string, unknown>)\n : null;\n const hydrateEnvelopeRaw = await materializeSpawnEnvelopeArchive(\n persistArchiveSource,\n services.objectStorage,\n );\n const hydrateEnvelope =\n hydrateEnvelopeRaw && typeof hydrateEnvelopeRaw === \"object\"\n ? (hydrateEnvelopeRaw as Record<string, unknown>)\n : null;\n const established = await establishSandboxSessionFromEnvelope(settings, hydrateEnvelope, {\n sessionId: ids.sessionId,\n recovery: \"create-or-restore\",\n ...(services.objectStorage\n ? {\n loadHostWorkspaceArchive: async (ref) => {\n try {\n return await downloadWorkspaceArchiveSpool(\n services.objectStorage!,\n ref.key,\n { bytes: ref.bytes, sha256: ref.sha256 },\n { temporaryDirectory: workspaceArchiveDownloadTemporaryDirectory },\n );\n } catch (error) {\n if (error instanceof WorkspaceArchiveStorageError) {\n throw new WorkspaceArchiveIntegrityError(error.code, error.message, {\n retryable: error.retryable,\n cause: error,\n });\n }\n throw error;\n }\n },\n }\n : {}),\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 onBeforeSandboxCreate: async (createSettings, intent, providerContext) => {\n if (ids.backend !== \"modal\") return;\n if (!intent || !providerContext)\n throw new Error(\"Modal create requires the provider dispatch boundary\");\n throwIfReleasedOrCancelled();\n const binding = await resolveModalCheckpointProviderBindingForSession(\n createSettings,\n providerContext,\n );\n const operationId = intent.operationId;\n await beginModalProviderCreate(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n operationId,\n providerBindingKey: binding.key,\n rematerializationId: rematerialization?.id ?? null,\n selectedRevision: rematerialization?.selectedRevision ?? null,\n imageId: intent.imageId,\n imageRef: createSettings.modalImageRef ?? null,\n appId: intent.appId,\n providerName: intent.name,\n requestSha256: intent.requestSha256,\n });\n providerCreateOperationId = operationId;\n providerCreateBindingKey = binding.key;\n },\n onSandboxCreated: async (created) => {\n createdEstablished = created;\n providerRenewalTarget = {\n backend: ids.backend,\n instanceId: created.instanceId,\n };\n providerRenewedAtMs = Date.now();\n if (\n providerCreateBindingKey &&\n !(await modalSessionMatchesCheckpointProviderBinding(\n settings,\n created.session,\n providerCreateBindingKey,\n ))\n ) {\n throw new Error(\"Modal creation receipt crossed the fenced provider namespace\");\n }\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, persistArchiveSource),\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 ...(providerCreateOperationId ? { providerCreateOperationId } : {}),\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 an asynchronous\n // provider's command router is live. Do not publish a warm lease until\n // one bounded no-op exec works.\n // On timeout the catch below terminates the box and rolls warming -> cold;\n // resumeBoxForTurn may then replace a proven-terminated fresh box once.\n if (services.verifySpawnedSandboxReadiness) {\n await services.verifySpawnedSandboxReadiness(established, {\n sandboxGroupId: ids.sandboxGroupId,\n });\n } else {\n await waitForSandboxExecReadiness(\n established,\n MODAL_EXEC_READINESS_TIMEOUT_MS,\n {\n sandboxGroupId: ids.sandboxGroupId,\n },\n cancellationSignal,\n );\n }\n await maybeRenewProviderExpiration(true);\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, persistArchiveSource),\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 ...(freshWorkspaceRecoveryId\n ? { freshWorkspace: { operationId: freshWorkspaceRecoveryId } }\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 published = true;\n holderLeaseHeartbeat = {\n expectedEpoch: committed.lease.leaseEpoch,\n leaseTtlMs,\n };\n await services.onSpawnedSandboxPublished?.();\n throwIfReleasedOrCancelled();\n return { established, leaseEpoch: committed.lease.leaseEpoch, release };\n } catch (error) {\n if (published) {\n // The published warm box stays for the replacement attempt to resume\n // by exact provider id; ordinary idle drain owns its capture/teardown.\n await release();\n throw error;\n }\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 if (\n terminated &&\n createdEstablished &&\n error instanceof SandboxExecReadinessTimeoutError &&\n error.instanceId === createdEstablished.instanceId &&\n (createdEstablished.origin === \"created\" || createdEstablished.origin === \"restored\") &&\n !createdEstablished.providerContinuity\n ) {\n disposedUnreadyFreshSandboxErrors.add(error);\n }\n throw sandboxProvisionStageError(rematerialization ? \"archive_recovery\" : \"create\", 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 // A provider may have ended the exact box while Opengeni was idle. Prove\n // 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(\n established,\n MODAL_EXEC_READINESS_TIMEOUT_MS,\n {\n sandboxGroupId: ids.sandboxGroupId,\n },\n cancellationSignal,\n );\n }\n providerRenewalTarget = {\n backend: ids.backend,\n instanceId: established.instanceId,\n };\n await maybeRenewProviderExpiration(true);\n throwIfReleasedOrCancelled();\n } catch (error) {\n if (!isProviderSandboxNotFoundError(ids.backend, error)) {\n throw sandboxProvisionStageError(\"resume\", 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 expectedBackend: ids.backend,\n });\n if (marked.status === \"marked\") {\n await publishDurableSessionEvents(\n services.bus,\n ids.workspaceId,\n marked.backgroundCommandEvents,\n );\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 // A cancelled waiter owns no box and must not keep polling for up to the\n // warming budget: its activity finalizer joins this exact promise.\n if (!(await sleepUnlessCancelled(WARMING_POLL_INTERVAL_MS, services.cancellationSignal))) {\n throw services.cancellationSignal?.reason instanceof Error\n ? services.cancellationSignal.reason\n : new Error(\"Sandbox warming wait was cancelled with its owning turn attempt\");\n }\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","import type { LeaseSnapshot } from \"@opengeni/db\";\n\n/** Physical capture retention is not permission to heartbeat or execute a closed turn. */\nexport function retainsHolderForWarmCapture(\n lease: Pick<LeaseSnapshot, \"liveness\" | \"leaseEpoch\" | \"archiveCapture\"> | null,\n expectedEpoch: number,\n now = Date.now(),\n): boolean {\n return Boolean(\n lease?.liveness === \"warm\" &&\n lease.leaseEpoch === expectedEpoch &&\n lease.archiveCapture &&\n lease.archiveCapture.deadlineAt.getTime() > now,\n );\n}\n","import { isDeepStrictEqual } from \"node:util\";\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 createProviderCommandRetainer,\n supervisedCommandProtocolReady,\n} from \"@opengeni/db/retained-provider-commands\";\nimport {\n adoptConnectedMachineSessionBackgroundCommand,\n adoptManagedSessionBackgroundCommand,\n advanceWorkspaceGenerationForRetainedProcess,\n retainedProviderCommandPersistence,\n advanceWorkspaceGeneration,\n getRetainedProcess,\n retainWorkspaceMutationProcess,\n retainedProcessSettlementIdentity,\n settleConnectedMachineSessionBackgroundCommand,\n settleRetainedProcess,\n verifyRetainedProcessMutationSettlement,\n verifyWorkspaceMutationSettlement,\n getSandbox,\n getLiveEnrollmentConnection,\n markWarmLeaseInstanceLost,\n readLease,\n readActiveSandbox,\n resolvePersonalMachineConnectionForAttempt,\n SandboxRetainedProcessPromotionFencedError,\n SandboxRetainedProcessTerminalError,\n SandboxWorkspaceMutationOutputRejectedError,\n type Database,\n type EnrollmentRecord,\n type SandboxWorkspaceMutationAdmission,\n} from \"@opengeni/db\";\nimport {\n observeSessionBackgroundCommandCompletion,\n recordConnectedCommandOutputConsumption,\n} from \"@opengeni/db/session-background-commands\";\nimport { appendSessionCommandOutput } from \"@opengeni/db/session-command-output\";\nimport type { OpStreamOutputFrame } from \"@opengeni/runtime/sandbox\";\nimport type { EventBus } from \"@opengeni/events\";\nimport { publishDurableSessionEvents } from \"./session-event-fanout\";\nimport {\n buildSelfhostedBackendSession,\n ActiveBackendUnresolvableError,\n establishSandboxSessionFromEnvelope,\n isProviderSandboxGoneDuringRoutedOperation,\n isProviderSandboxNotFoundError,\n makeActiveBackendResolver,\n NatsControlRpc,\n NatsOpStreamTransport,\n RoutingBackendRecoveryRequiredError,\n RoutingSandboxSession,\n RoutingMutationOutputRejectedError,\n resolveModalCheckpointProviderBindingForSession,\n resolveConnectedMachineWorkspaceRoot,\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 RoutingSandboxFirstOperationObserver,\n type RoutingSandboxOperationObserver,\n type RoutingSandboxCaptureWaitObserver,\n type RoutingSandboxWaitObservation,\n type RoutingRetainedProcess,\n type RoutingRetainedProcessTerminalProof,\n type SelfhostedOpObserver,\n type SelfhostedConnectionBinding,\n type SelfhostedRelayConfig,\n type OpStreamJournal,\n type SelfhostedOpStreamDeps,\n} from \"@opengeni/runtime\";\nimport { sandboxLeaseHolderIdForAttempt } from \"./sandbox-resume\";\n\nconst retainWorkspaceProviderCommand = createProviderCommandRetainer(\n retainWorkspaceMutationProcess,\n (error) => (error instanceof SandboxRetainedProcessPromotionFencedError ? error.process : null),\n);\n\ntype PersistableMutationAdmission = {\n admission: SandboxWorkspaceMutationAdmission;\n providerBinding: Awaited<\n ReturnType<typeof resolveModalCheckpointProviderBindingForSession>\n > | null;\n};\n\nfunction admittedCommandHandle(value: unknown): number | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n return (value as PersistableMutationAdmission).admission?.workspaceGeneration;\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 onSandboxCaptureWait?: RoutingSandboxCaptureWaitObserver;\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 /** Prepare and publish the worker's home handle. Rejection leaves the route\n * unpublished; replacement preparation must settle before the first tool op. */\n onHomeSandboxRebound?: (input: {\n established: EstablishedSandboxSession;\n leaseEpoch: number;\n }) => void | Promise<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 resourceAccountId?: string;\n resourceSubjectId?: string;\n /** Frozen initiating-human authority for personal Connected Machine use.\n * Every routed operation reasserts this exact accepted attempt before the\n * control-plane connection is resolved. */\n personalMachineAttempt?: {\n accountId: string;\n subjectId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n };\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 /** Attempt-local values projected only onto Connected Machine child execs. */\n transientExecEnvironment?: () => Readonly<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 await 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 expectedBackend: lease.backend,\n diagnostic: \"provider_not_found_during_home_route_rebind\",\n });\n if (marked.status === \"marked\") {\n await publishDurableSessionEvents(\n services.bus,\n ids.workspaceId,\n marked.backgroundCommandEvents,\n );\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 await 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 onCaptureWait?: (observation: RoutingSandboxWaitObservation) => void;\n }) => Promise<PersistableMutationAdmission | null>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!home || !fence) return undefined;\n return async ({ op, backend, onCaptureWait }) => {\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 ...(onCaptureWait ? { onCaptureWait } : {}),\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\" | \"outcome_unknown\";\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\" || outcome === \"outcome_unknown\") && retainedProcess) {\n try {\n await retainWorkspaceProviderCommand(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: retainedProcess.id,\n providerSessionId: retainedProcess.providerSessionId,\n ...(retainedProcess.providerCommand\n ? { providerCommand: retainedProcess.providerCommand }\n : {}),\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 if (outcome === \"outcome_unknown\")\n throw new Error(\"Outcome-unknown command settlement requires its exact retained invocation\");\n try {\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 } catch (error) {\n if (\n error instanceof SandboxWorkspaceMutationOutputRejectedError &&\n error.matchesPhysicalSettlement({\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n admission: exactAdmission,\n operation: op,\n outcome,\n })\n ) {\n throw new RoutingMutationOutputRejectedError(op, error.code, { cause: error });\n }\n throw error;\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 try {\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 } catch (error) {\n if (\n error instanceof SandboxWorkspaceMutationOutputRejectedError &&\n error.matchesPhysicalSettlement({\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n admission: admission as SandboxWorkspaceMutationAdmission,\n operation: op,\n outcome,\n })\n ) {\n if (error.retainedProcessTerminal) {\n // Another authority (the reaper's exact-proof reconciliation) settled\n // this retained process terminal between admission and settlement.\n // The admission is physically settled and its output stays rejected;\n // surface the durable terminal truth so routing reports completion\n // instead of failing the turn. Nothing is replayed.\n throw new SandboxRetainedProcessTerminalError(\n error.retainedProcessTerminal.state,\n error.retainedProcessTerminal.exitCode,\n );\n }\n throw new RoutingMutationOutputRejectedError(op, error.code, { cause: error });\n }\n throw error;\n }\n };\n}\n\nexport function captureConnectedCommandOutput(\n db: Database,\n ids: { accountId: string; workspaceId: string; sessionId: string },\n bus?: EventBus,\n) {\n return async (commandId: string, frames: OpStreamOutputFrame[]) => {\n for (const frame of frames) {\n const events = await appendSessionCommandOutput(db, {\n ...ids,\n commandId,\n chunkId: `op-frame:${frame.sequence}`,\n stream: frame.stream,\n chunk: frame.chunk,\n });\n if (events.length && bus)\n await bus.publish(ids.workspaceId, ids.sessionId, events).catch(() => undefined);\n }\n };\n}\n\nfunction captureRetainedProcessOutputForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n) {\n const accountId = ids.workspaceMutationFence?.accountId;\n if (!accountId) return undefined;\n return async ({\n process,\n chunkId,\n chunk,\n stream,\n streamFidelity,\n }: {\n process: RoutingRetainedProcess;\n chunkId: string;\n chunk: string;\n stream: \"stdout\" | \"stderr\";\n streamFidelity: \"separate\" | \"merged\";\n }) => {\n const events = await appendSessionCommandOutput(services.db, {\n accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: process.id,\n chunkId,\n chunk,\n stream,\n streamFidelity,\n });\n if (events.length && services.bus)\n await services.bus.publish(ids.workspaceId, ids.sessionId, events).catch(() => undefined);\n };\n}\n\nfunction observeRetainedProcessTerminalForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n) {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ process }: { process: RoutingRetainedProcess }) => {\n await observeSessionBackgroundCommandCompletion(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: process.id,\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 !== (sandboxBackendForSdkBackendId(backend.kind) ?? 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 const settlement = 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 if (settlement.process.state === \"active\") {\n throw new Error(\"Retained-process settlement returned an active durable process\");\n }\n if (settlement.backgroundCommandEvents.length > 0 && services.bus) {\n await services.bus\n .publish(ids.workspaceId, ids.sessionId, settlement.backgroundCommandEvents)\n .catch(() => undefined);\n }\n };\n}\n\n/** Cleanup can observe the independently settled row even when this worker's\n * pending output receipt or original provider transport can no longer advance. */\nfunction isRetainedProcessSettledForTurn(services: RoutingWiringServices, ids: RoutingWiringIds) {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({\n backend,\n process,\n }: {\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n }): Promise<boolean> => {\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.state === \"active\" ||\n durable.providerSessionId !== process.providerSessionId ||\n durable.providerBackend !== (sandboxBackendForSdkBackendId(backend.kind) ?? 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 return false;\n if (process.providerCommand) {\n // The general process projection deliberately omits the provider locator.\n // Load its immutable identity through the exact protected persistence seam.\n const command = await retainedProviderCommandPersistence(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n }).load();\n if (\n !command ||\n command.kind !== process.providerCommand.kind ||\n command.execId !== process.providerCommand.execId ||\n command.taskId !== process.providerCommand.taskId ||\n command.sandboxId !== process.providerCommand.sandboxId ||\n Boolean(command.pty) !== Boolean(process.providerCommand.pty) ||\n (command.kind === \"modal-router-v1\" &&\n process.providerCommand.kind === \"modal-router-v1\" &&\n !isDeepStrictEqual(command.supervision, process.providerCommand.supervision))\n )\n return false;\n }\n // Terminal rows are written only through proof-gated physical settlement.\n return true;\n };\n}\n\nfunction adoptRetainedProcessAsBackgroundCommandForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n command?: string | undefined;\n }) => Promise<void>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ backend, process, command }) => {\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 !== (sandboxBackendForSdkBackendId(backend.kind) ?? 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(\"Background command adoption lost its exact retained-process identity\");\n }\n await adoptManagedSessionBackgroundCommand(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 processId: process.id,\n expected: retainedProcessSettlementIdentity(durable),\n command: command ?? \"Background command\",\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 backgroundCommandAccountId = ids.workspaceMutationFence?.accountId;\n const backgroundCommandAttempt = ids.workspaceMutationFence;\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 isProcessSettled = isRetainedProcessSettledForTurn(services, ids);\n const adoptProcessAsBackgroundCommand = adoptRetainedProcessAsBackgroundCommandForTurn(\n services,\n ids,\n );\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(\n db,\n ids.resourceAccountId && ids.resourceSubjectId\n ? {\n accountId: ids.resourceAccountId,\n workspaceId: ids.workspaceId,\n subjectId: ids.resourceSubjectId,\n }\n : ids.workspaceId,\n sandboxId,\n );\n return sandbox\n ? {\n id: sandbox.id,\n workspaceId: sandbox.workspaceId,\n kind: sandbox.kind,\n name: sandbox.name,\n ...(sandbox.scope ? { scope: sandbox.scope } : {}),\n enrollmentId: sandbox.enrollmentId,\n }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n resolveSelfhostedConnection: async (sandbox) => {\n if (!sandbox.enrollmentId) return null;\n const enrollment = await resolveRoutedMachineConnection(db, ids, sandbox);\n return connectionBindingFor(services, enrollment);\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 ...(backgroundCommandAccountId && backgroundCommandAttempt\n ? {\n selfhostedAdoptBackgroundCommand: async (command) => {\n const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: backgroundCommandAttempt.turnId,\n executionGeneration: backgroundCommandAttempt.executionGeneration,\n attemptId: backgroundCommandAttempt.attemptId,\n commandId: crypto.randomUUID(),\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n command: command.command,\n ...(command.abandoned ? { abandoned: true } : {}),\n });\n return { commandId: adopted.id };\n },\n selfhostedSettleBackgroundCommand: async (command) => {\n const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: command.commandId,\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n outcome: command.outcome,\n exitCode: command.exitCode,\n reason: command.reason,\n ...(command.failure ? { failure: command.failure } : {}),\n });\n if (settlement && bus) {\n await bus\n .publish(ids.workspaceId, ids.sessionId, settlement.events)\n .catch(() => undefined);\n }\n },\n selfhostedCaptureBackgroundCommandOutput: captureConnectedCommandOutput(\n db,\n {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n },\n bus,\n ),\n }\n : {}),\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 ...(ids.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: ids.transientExecEnvironment }\n : {}),\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 ...(services.onSandboxCaptureWait ? { onCaptureWait: services.onSandboxCaptureWait } : {}),\n providerCommandHandle: admittedCommandHandle,\n providerSupervisionReady: async () =>\n settings.modalCommandSupervisionEnabled && (await supervisedCommandProtocolReady(db)),\n ...(ids.workspaceMutationFence\n ? {\n providerCommandPersistence: (process: RoutingRetainedProcess) =>\n retainedProviderCommandPersistence(\n db,\n {\n accountId: ids.workspaceMutationFence!.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n },\n services.bus\n ? (events) => services.bus!.publish(ids.workspaceId, ids.sessionId, events)\n : undefined,\n ),\n }\n : {}),\n ...(beforeMutation ? { beforeMutation } : {}),\n ...(afterMutation ? { afterMutation } : {}),\n ...(beforeProcessMutation ? { beforeProcessMutation } : {}),\n ...(afterProcessMutation ? { afterProcessMutation } : {}),\n ...(settleProcess ? { settleProcess } : {}),\n ...(isProcessSettled ? { isProcessSettled } : {}),\n ...(ids.workspaceMutationFence\n ? { observeProcessTerminal: observeRetainedProcessTerminalForTurn(services, ids)! }\n : {}),\n ...(ids.workspaceMutationFence\n ? { captureProcessOutput: captureRetainedProcessOutputForTurn(services, ids)! }\n : {}),\n ...(adoptProcessAsBackgroundCommand ? { adoptProcessAsBackgroundCommand } : {}),\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 expectedBackend: home.backend,\n diagnostic: \"provider_not_found_during_routed_operation\",\n });\n if (marked.status === \"marked\") {\n await publishDurableSessionEvents(\n services.bus,\n ids.workspaceId,\n marked.backgroundCommandEvents,\n );\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 onFirstOperation?: RoutingSandboxFirstOperationObserver;\n },\n): EstablishedSandboxSession {\n const { db, settings, bus, onOp } = services;\n const backgroundCommandAccountId = ids.workspaceMutationFence?.accountId;\n const backgroundCommandAttempt = ids.workspaceMutationFence;\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 isProcessSettled = isRetainedProcessSettledForTurn(services, ids);\n const adoptProcessAsBackgroundCommand = adoptRetainedProcessAsBackgroundCommandForTurn(\n services,\n ids,\n );\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(\n db,\n ids.resourceAccountId && ids.resourceSubjectId\n ? {\n accountId: ids.resourceAccountId,\n workspaceId: ids.workspaceId,\n subjectId: ids.resourceSubjectId,\n }\n : ids.workspaceId,\n sandboxId,\n );\n return sandbox\n ? {\n id: sandbox.id,\n workspaceId: sandbox.workspaceId,\n kind: sandbox.kind,\n name: sandbox.name,\n ...(sandbox.scope ? { scope: sandbox.scope } : {}),\n enrollmentId: sandbox.enrollmentId,\n }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n resolveSelfhostedConnection: async (sandbox) => {\n if (!sandbox.enrollmentId) return null;\n const enrollment = await resolveRoutedMachineConnection(db, ids, sandbox);\n return connectionBindingFor(services, enrollment);\n },\n relay: relayConfigFromSettings(settings),\n ...selfhostedResolverTimeouts(settings),\n ...(onOp !== undefined ? { selfhostedOnOp: onOp } : {}),\n ...(backgroundCommandAccountId && backgroundCommandAttempt\n ? {\n selfhostedAdoptBackgroundCommand: async (command) => {\n const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: backgroundCommandAttempt.turnId,\n executionGeneration: backgroundCommandAttempt.executionGeneration,\n attemptId: backgroundCommandAttempt.attemptId,\n commandId: crypto.randomUUID(),\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n command: command.command,\n ...(command.abandoned ? { abandoned: true } : {}),\n });\n return { commandId: adopted.id };\n },\n selfhostedSettleBackgroundCommand: async (command) => {\n const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: command.commandId,\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n outcome: command.outcome,\n exitCode: command.exitCode,\n reason: command.reason,\n ...(command.failure ? { failure: command.failure } : {}),\n });\n if (settlement && bus) {\n await bus\n .publish(ids.workspaceId, ids.sessionId, settlement.events)\n .catch(() => undefined);\n }\n },\n selfhostedCaptureBackgroundCommandOutput: captureConnectedCommandOutput(\n db,\n {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n },\n bus,\n ),\n }\n : {}),\n ...(ids.environment !== undefined ? { environment: ids.environment } : {}),\n ...(ids.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: ids.transientExecEnvironment }\n : {}),\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 ...(services.onSandboxCaptureWait ? { onCaptureWait: services.onSandboxCaptureWait } : {}),\n ...(args.onFirstOperation ? { onFirstOperation: args.onFirstOperation } : {}),\n providerCommandHandle: admittedCommandHandle,\n providerSupervisionReady: async () =>\n settings.modalCommandSupervisionEnabled && (await supervisedCommandProtocolReady(db)),\n ...(ids.workspaceMutationFence\n ? {\n providerCommandPersistence: (process: RoutingRetainedProcess) =>\n retainedProviderCommandPersistence(\n db,\n {\n accountId: ids.workspaceMutationFence!.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n },\n services.bus\n ? (events) => services.bus!.publish(ids.workspaceId, ids.sessionId, events)\n : undefined,\n ),\n }\n : {}),\n ...(beforeMutation ? { beforeMutation } : {}),\n ...(afterMutation ? { afterMutation } : {}),\n ...(beforeProcessMutation ? { beforeProcessMutation } : {}),\n ...(afterProcessMutation ? { afterProcessMutation } : {}),\n ...(settleProcess ? { settleProcess } : {}),\n ...(isProcessSettled ? { isProcessSettled } : {}),\n ...(ids.workspaceMutationFence\n ? { observeProcessTerminal: observeRetainedProcessTerminalForTurn(services, ids)! }\n : {}),\n ...(ids.workspaceMutationFence\n ? { captureProcessOutput: captureRetainedProcessOutputForTurn(services, ids)! }\n : {}),\n ...(adoptProcessAsBackgroundCommand ? { adoptProcessAsBackgroundCommand } : {}),\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 expectedBackend: home.backend,\n diagnostic: \"provider_not_found_during_routed_operation\",\n });\n if (marked.status === \"marked\") {\n await publishDurableSessionEvents(\n services.bus,\n ids.workspaceId,\n marked.backgroundCommandEvents,\n );\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 accountId: string;\n /** Authorization/session workspace. */\n workspaceId: string;\n sessionId: string;\n /** Physical machine-origin workspace used in control-plane routing. */\n controlWorkspaceId?: string;\n /** Exact launching attempt required before a live Connected Machine command\n * can transfer into session ownership. Omitted by non-turn/test callers,\n * which therefore cannot yield a durable background command. */\n backgroundCommandAttempt?: Pick<\n NonNullable<RoutingWiringIds[\"workspaceMutationFence\"]>,\n \"turnId\" | \"executionGeneration\" | \"attemptId\"\n >;\n /** The target machine's enrollment id == the agent subject id. */\n agentId: string;\n /** Exact daemon process currently leased for the enrollment. */\n connectionInstanceId: 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 /** Desired per-enrollment command policy and capability from the same live\n * enrollment snapshot as the process identity. */\n operationResourcePolicy: EnrollmentRecord[\"operationPolicy\"];\n operationResourcePolicySupported: boolean;\n operationCpuQuotaSupported: boolean;\n /** Feature advertisement only; refreshed by exact live admission for each operation. */\n transactionalFsWriteSupported?: boolean;\n browserControlHttpSupported?: 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 /** Attempt-local values projected only onto this machine's child execs. */\n transientExecEnvironment?: () => Readonly<Record<string, string>>;\n /** The session working directory (per-session pointer). Null ⇒ workspace_root. */\n workingDir: string | null;\n /** Effective absolute host-native root frozen for this attempt. */\n workspaceRoot: string;\n /** Present whenever the turn has an initiating human. A machine can become\n * Only me during the turn, so every provider operation reads the current\n * scope and rechecks this frozen accepted-attempt authority immediately\n * before dispatch while the machine is user-owned. */\n personalMachineAttempt?: NonNullable<RoutingWiringIds[\"personalMachineAttempt\"]> & {\n sessionId: string;\n };\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\n/** Project one enrollment read into one exact runtime route. Capability and\n * process identity must be taken from the same snapshot. */\nexport function connectionBindingFor(\n services: RoutingWiringServices,\n enrollment: EnrollmentRecord | null,\n): SelfhostedConnectionBinding | null {\n if (!enrollment?.connectionInstanceId) return null;\n const opStream = opStreamDepsFor(services, enrollment.opStream === true);\n return {\n workspaceId: enrollment.workspaceId,\n connectionInstanceId: enrollment.connectionInstanceId,\n workspaceRoot: enrollment.workspaceRoot,\n ...(opStream !== undefined ? { opStream } : {}),\n operationResourcePolicy: enrollment.operationPolicy,\n operationResourcePolicySupported: enrollment.agentCapabilities.operationResourcePolicy === true,\n operationCpuQuotaSupported: enrollment.agentCapabilities.operationCpuQuota === true,\n transactionalFsWriteSupported: enrollment.agentCapabilities.transactionalFsWrite === true,\n browserControlHttpSupported: enrollment.agentCapabilities.browserControlHttp === true,\n };\n}\n\n/** Personal-machine discovery is not execution authority. A machine's audience\n * can change in place while a routed session is cached, so the current scope is\n * read from the enrollment itself, never from the sandbox snapshot taken when\n * the session was built. A machine that is Only me now rechecks the frozen\n * initiating human, exact current attempt, authorization snapshot and current\n * visibility-keyed grant immediately before each routed operation resolves a\n * live control-plane connection. */\nasync function resolveRoutedMachineConnection(\n db: Database,\n ids: RoutingWiringIds,\n sandbox: RoutableSandbox,\n): Promise<EnrollmentRecord | null> {\n if (!sandbox.enrollmentId) return null;\n const current = await getLiveEnrollmentConnection(db, sandbox.workspaceId, sandbox.enrollmentId);\n if (!current) return null;\n if (current.scope === \"user\") {\n const authority = ids.personalMachineAttempt;\n if (!authority) return null;\n return await resolvePersonalMachineConnectionForAttempt(db, {\n accountId: authority.accountId,\n workspaceId: ids.workspaceId,\n subjectId: authority.subjectId,\n sessionId: ids.sessionId,\n turnId: authority.turnId,\n attemptId: authority.attemptId,\n executionGeneration: authority.executionGeneration,\n enrollmentId: sandbox.enrollmentId,\n requireActiveSandbox: true,\n });\n }\n if (!ids.resourceAccountId || !ids.resourceSubjectId) return current;\n return await getLiveEnrollmentConnection(\n db,\n {\n accountId: ids.resourceAccountId,\n workspaceId: ids.workspaceId,\n subjectId: ids.resourceSubjectId,\n },\n sandbox.enrollmentId,\n );\n}\n\nexport async function establishSelfhostedTurnSession(\n services: RoutingWiringServices,\n args: SelfhostedTurnSessionArgs,\n): Promise<EstablishedSandboxSession> {\n const { db, 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 ...(args.controlWorkspaceId !== undefined\n ? { controlWorkspaceId: args.controlWorkspaceId }\n : {}),\n agentId: args.agentId,\n connectionInstanceId: args.connectionInstanceId,\n workspaceRoot: args.workspaceRoot,\n relay: relayConfigFromSettings(settings),\n controlRpcFactory: controlRpcFactory(bus),\n epoch: args.epoch,\n environment: args.environment,\n ...(args.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: args.transientExecEnvironment }\n : {}),\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 operationResourcePolicy: args.operationResourcePolicy,\n operationResourcePolicySupported: args.operationResourcePolicySupported,\n operationCpuQuotaSupported: args.operationCpuQuotaSupported,\n transactionalFsWriteSupported: args.transactionalFsWriteSupported === true,\n browserControlHttpSupported: args.browserControlHttpSupported === true,\n resolveOperationAdmission: async () => {\n // The machine's audience can change in place during a turn. Read the\n // current scope on every admitted operation: a machine that is Only me now\n // needs the frozen accepted-attempt authority, a shared one does not.\n const current = await getLiveEnrollmentConnection(\n db,\n args.controlWorkspaceId ?? args.workspaceId,\n args.agentId,\n );\n const enrollment =\n current?.scope !== \"user\"\n ? current\n : args.personalMachineAttempt\n ? await resolvePersonalMachineConnectionForAttempt(db, {\n accountId: args.personalMachineAttempt.accountId,\n workspaceId: args.workspaceId,\n subjectId: args.personalMachineAttempt.subjectId,\n sessionId: args.personalMachineAttempt.sessionId,\n turnId: args.personalMachineAttempt.turnId,\n attemptId: args.personalMachineAttempt.attemptId,\n executionGeneration: args.personalMachineAttempt.executionGeneration,\n enrollmentId: args.agentId,\n requireActiveSandbox: true,\n })\n : null;\n const binding = connectionBindingFor(services, enrollment);\n if (!binding) return null;\n if (!binding.workspaceRoot) {\n throw new ActiveBackendUnresolvableError(\n \"workspace_root_unavailable\",\n \"Connected Machine no longer has a reported workspace root\",\n );\n }\n return {\n ...binding,\n workspaceRoot: resolveConnectedMachineWorkspaceRoot(binding.workspaceRoot, args.workingDir),\n };\n },\n ...(args.backgroundCommandAttempt\n ? {\n adoptBackgroundCommand: async (command) => {\n const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n turnId: args.backgroundCommandAttempt!.turnId,\n executionGeneration: args.backgroundCommandAttempt!.executionGeneration,\n attemptId: args.backgroundCommandAttempt!.attemptId,\n commandId: crypto.randomUUID(),\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n command: command.command,\n ...(command.abandoned ? { abandoned: true } : {}),\n });\n return { commandId: adopted.id };\n },\n }\n : {}),\n captureBackgroundCommandOutput: captureConnectedCommandOutput(\n db,\n {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n },\n bus,\n ),\n settleBackgroundCommand: async (command) => {\n const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n commandId: command.commandId,\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n outcome: command.outcome,\n exitCode: command.exitCode,\n reason: command.reason,\n ...(command.failure ? { failure: command.failure } : {}),\n });\n if (command.outputReceipt && command.outcome === \"exited\" && command.exitCode !== null) {\n await recordConnectedCommandOutputConsumption(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n commandId: command.commandId,\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n receipt: command.outputReceipt,\n exitCode: command.exitCode,\n });\n }\n if (settlement && bus) {\n await bus\n .publish(args.workspaceId, args.sessionId, settlement.events)\n .catch(() => undefined);\n }\n },\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. Connected Machine exec fails closed\n // when it is absent; there is no request/reply downgrade.\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"],"mappings":";AAAA,SAAS,gCAAoD;AAetD,SAAS,kBACd,OACA,SAAsC,kBACnB;AACnB,QAAM,SAA4B;AAAA,IAChC,YAAY;AAAA,IACZ,WAAW;AAAA,IACX;AAAA,EACF;AACA,MAAI;AACF,QAAI,SAAS,OAAO,UAAU,UAAU;AACtC,YAAM,YAAY;AAMlB,UACE,OAAO,UAAU,SAAS,YAC1B,iCAAiC,KAAK,UAAU,IAAI,GACpD;AACA,eAAO,YAAY,UAAU;AAAA,MAC/B;AACA,UAAI,OAAO,UAAU,SAAS,YAAY,qBAAqB,KAAK,UAAU,IAAI,GAAG;AACnF,eAAO,gBAAgB,UAAU;AAAA,MACnC;AACA,YAAM,SAAS,OAAO,UAAU,UAAU,UAAU,UAAU;AAC9D,UAAI,OAAO,UAAU,MAAM,KAAK,UAAU,OAAO,UAAU,IAAK,QAAO,SAAS;AAAA,IAClF;AAAA,EACF,QAAQ;AAAA,EAER;A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AE,SAAS,IAAI,CAAC;AAAA,EAC/C,CAAC;AACD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,cAAc,EAAE,SAAS,KAAK,QAAQ;AAAA,IACtC,YAAY,KAAK;AAAA,IACjB,WAAW;AAAA,EACb;AACF;AAMO,SAAS,eAAe,UAA6B;AAC1D,SAAO,SAAS,6BAA6B;AAC/C;AASO,SAAS,qBAAqB,UAA6B;AAChE,SAAO,SAAS,gCAAgC,QAAQ,SAAS,4BAA4B;AAC/F;","names":["randomUUID","sandboxLeaseTelemetryKey","parseWorkspaceArchiveObjectRef","parseWorkspaceArchiveObjectRef","sandboxLeaseTelemetryKey","randomUUID","resumeEnvelope","sandboxLifecycleTransitionWaitMs","markWarmLeaseInstanceLost","readLease","establishSandboxSessionFromEnvelope","isProviderSandboxNotFoundError","resolveModalCheckpointProviderBindingForSession","verifySandboxExecReadiness","readLease","establishSandboxSessionFromEnvelope","verifySandboxExecReadiness","isProviderSandboxNotFoundError","markWarmLeaseInstanceLost","resolveModalCheckpointProviderBindingForSession","sandboxLifecycleTransitionWaitMs","process"]}