@opengeni/worker-bundle 2.3.1 → 2.3.2-canary.37090756480001

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 (66) hide show
  1. package/dist/activities/agent-turn/claude-usage-observer.d.ts +30 -6
  2. package/dist/activities/agent-turn/credential-leases.d.ts +5 -32
  3. package/dist/activities/agent-turn/errors.d.ts +3 -0
  4. package/dist/activities/agent-turn/finalization-monitor.d.ts +1 -1
  5. package/dist/activities/agent-turn/finalization.d.ts +2 -0
  6. package/dist/activities/agent-turn/quiescence.d.ts +3 -4
  7. package/dist/activities/agent-turn/subscription-lease.d.ts +38 -0
  8. package/dist/activities/agent-turn/turn-context.d.ts +1 -1
  9. package/dist/activities/model-call-fact-reconciler.d.ts +34 -0
  10. package/dist/activities/session-state.d.ts +2 -2
  11. package/dist/activities/types.d.ts +7 -0
  12. package/dist/{activities-control-3HAH4FMG.js → activities-control-3BY4IJKL.js} +166 -35
  13. package/dist/activities-control-3BY4IJKL.js.map +1 -0
  14. package/dist/activities-control.d.ts +6 -4
  15. package/dist/{activities-turn-KU25J3VQ.js → activities-turn-TTNAVGKN.js} +263 -308
  16. package/dist/activities-turn-TTNAVGKN.js.map +1 -0
  17. package/dist/activities.d.ts +6 -4
  18. package/dist/{chunk-3K3ULWEE.js → chunk-PA7Z55P4.js} +242 -17
  19. package/dist/chunk-PA7Z55P4.js.map +1 -0
  20. package/dist/{chunk-YG27NEMX.js → chunk-YOI3Z3GF.js} +9 -1
  21. package/dist/chunk-YOI3Z3GF.js.map +1 -0
  22. package/dist/http.d.ts +1 -1
  23. package/dist/index.d.ts +6 -2
  24. package/dist/index.js +82 -16
  25. package/dist/index.js.map +1 -1
  26. package/dist/observability-metrics.d.ts +6 -1
  27. package/dist/sandbox-resume.d.ts +3 -0
  28. package/dist/session-event-fanout.d.ts +6 -0
  29. package/dist/worker-service-lifecycle.d.ts +12 -0
  30. package/dist/workflow-bundle.js +3 -2
  31. package/package.json +21 -21
  32. package/src/activities/agent-turn/claim.ts +13 -0
  33. package/src/activities/agent-turn/claude-usage-observer.ts +99 -8
  34. package/src/activities/agent-turn/credential-leases.ts +86 -213
  35. package/src/activities/agent-turn/errors.ts +61 -1
  36. package/src/activities/agent-turn/failure-settlement.ts +59 -5
  37. package/src/activities/agent-turn/finalization-monitor.ts +3 -4
  38. package/src/activities/agent-turn/finalization.ts +8 -3
  39. package/src/activities/agent-turn/quiescence.ts +3 -4
  40. package/src/activities/agent-turn/run.ts +24 -20
  41. package/src/activities/agent-turn/sandbox-establish.ts +2 -0
  42. package/src/activities/agent-turn/sandbox-runtime.ts +5 -1
  43. package/src/activities/agent-turn/skill-selection.ts +2 -0
  44. package/src/activities/agent-turn/subscription-lease.ts +115 -0
  45. package/src/activities/agent-turn/turn-context.ts +1 -4
  46. package/src/activities/codex-rotation.ts +2 -12
  47. package/src/activities/model-call-fact-reconciler.ts +112 -0
  48. package/src/activities/sandbox-lease.ts +59 -8
  49. package/src/activities/session-state.ts +29 -4
  50. package/src/activities/types.ts +7 -0
  51. package/src/activities-control.ts +2 -0
  52. package/src/activities-turn.ts +5 -0
  53. package/src/activities.ts +7 -0
  54. package/src/http.ts +4 -2
  55. package/src/index.ts +39 -9
  56. package/src/observability-metrics.ts +27 -0
  57. package/src/sandbox-resume.ts +9 -0
  58. package/src/sandbox-routing.ts +77 -0
  59. package/src/session-event-fanout.ts +23 -0
  60. package/src/worker-service-lifecycle.ts +53 -0
  61. package/src/workflows/file-upload-reaper.ts +2 -0
  62. package/src/workflows/session.ts +6 -1
  63. package/dist/activities-control-3HAH4FMG.js.map +0 -1
  64. package/dist/activities-turn-KU25J3VQ.js.map +0 -1
  65. package/dist/chunk-3K3ULWEE.js.map +0 -1
  66. package/dist/chunk-YG27NEMX.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/activities/knowledge-indexing.ts","../src/activities/browser-state-artifact-reaper.ts","../src/activities/browser-deadline-checkpoint.ts","../src/activities/automations.ts","../src/activities/file-upload-reaper.ts","../src/activities/retained-screenshot-reaper.ts","../src/activities/rig-verification.ts","../src/retained-process-diagnostics.ts","../src/retained-process-retry.ts","../src/activities/sandbox-lease.ts","../src/activities/scheduled-tasks.ts","../src/scheduled-alert-occurrence.ts","../src/activities/site-auth-maintenance.ts","../src/activities/session-state.ts","../src/activities/workflow-wake.ts","../src/activities-control.ts"],"sourcesContent":["import { configuredStaticUsageLimits } from \"@opengeni/config\";\nimport { documentEmbeddingCostMicros, paidDocumentEmbedding } from \"@opengeni/core\";\nimport {\n applyCreditDebitAfterUse,\n appendKnowledgeIndexChunks,\n claimKnowledgeIndexJobs,\n checkWorkspaceAllowance,\n completeKnowledgeIndexJob,\n continueKnowledgeIndexJob,\n creditDebitAttributionMetadata,\n deferKnowledgeIndexJob,\n freezeKnowledgeIndexBillingMode,\n getBillingBalance,\n guardPaidKnowledgeIndexPublication,\n knowledgeIndexBillingActivationTime,\n readKnowledgeIndexSource,\n recordUsageEvent,\n sumUsageQuantity,\n withWorkspaceUsageLock,\n waitKnowledgeIndexForFunding,\n} from \"@opengeni/db\";\nimport type { DocumentServices } from \"@opengeni/documents\";\nimport type { ControlActivityServices } from \"./types\";\n\n/** The configured monthly indexed-chunk limit, not a provider failure. */\nexport class KnowledgeIndexUsageLimitError extends Error {\n constructor() {\n super(\"monthly document indexing limit reached\");\n this.name = \"KnowledgeIndexUsageLimitError\";\n }\n}\n\nexport type KnowledgeIndexFailureStage = \"embedding\" | \"processing\";\n\n/**\n * Content-free classification for a deferred Knowledge index batch. Only\n * protocol constants, an HTTP status, and a PostgreSQL SQLSTATE are retained;\n * provider messages, bodies, SQL, and identifiers never leave the process.\n * Outside the embedding call, only a PostgreSQL error in the cause chain is\n * attributed to the database; any other failure stays a worker failure.\n */\nexport function knowledgeIndexFailureDiagnostic(\n stage: KnowledgeIndexFailureStage,\n error: unknown,\n): {\n errorClass: \"KnowledgeIndexOperationError\";\n errorCode:\n | \"knowledge_index_usage_limit_reached\"\n | \"knowledge_index_embedding_failed\"\n | \"knowledge_index_persistence_failed\"\n | \"knowledge_index_failed\";\n origin: \"worker\" | \"db\";\n status?: number;\n sqlState?: string;\n} {\n if (error instanceof KnowledgeIndexUsageLimitError) {\n return {\n errorClass: \"KnowledgeIndexOperationError\",\n errorCode: \"knowledge_index_usage_limit_reached\",\n origin: \"worker\",\n };\n }\n if (stage === \"embedding\") {\n const status = ownValue(error, \"status\");\n return {\n errorClass: \"KnowledgeIndexOperationError\",\n errorCode: \"knowledge_index_embedding_failed\",\n origin: \"worker\",\n ...(typeof status === \"number\" && Number.isInteger(status) && status >= 100 && status <= 599\n ? { status }\n : {}),\n };\n }\n const postgres = postgresErrorState(error);\n if (!postgres) {\n return {\n errorClass: \"KnowledgeIndexOperationError\",\n errorCode: \"knowledge_index_failed\",\n origin: \"worker\",\n };\n }\n return {\n errorClass: \"KnowledgeIndexOperationError\",\n errorCode: \"knowledge_index_persistence_failed\",\n origin: \"db\",\n ...(postgres.sqlState ? { sqlState: postgres.sqlState } : {}),\n };\n}\n\nfunction ownValue(value: unknown, key: string): unknown {\n try {\n if (!value || typeof value !== \"object\") return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return descriptor && \"value\" in descriptor ? descriptor.value : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The nearest PostgreSQL error in a short cause chain, with its SQLSTATE\n * when that is a well-formed five-character code. */\nfunction postgresErrorState(error: unknown): { sqlState?: string } | undefined {\n let current = error;\n for (let depth = 0; depth < 4 && current && typeof current === \"object\"; depth += 1) {\n if (ownValue(current, \"name\") === \"PostgresError\") {\n const code = ownValue(current, \"code\");\n return typeof code === \"string\" && /^[0-9A-Z]{5}$/.test(code) ? { sqlState: code } : {};\n }\n current = ownValue(current, \"cause\");\n }\n return undefined;\n}\n\nexport function createKnowledgeIndexingActivities(\n services: () => Promise<ControlActivityServices>,\n resolveDocumentServices?: () => Promise<DocumentServices>,\n) {\n // Unpaid modes retain a conservative first-poll cutoff; paid mode uses the\n // operator's explicit timestamp so process restarts cannot change eligibility.\n let activationTime: Promise<Date> | undefined;\n return {\n indexKnowledge: async () => {\n const result = { completed: 0, advanced: 0, deferred: 0, unavailable: 0 };\n if (!resolveDocumentServices) return result;\n const { db, settings, observability } = await services();\n let policyActivatedAt: Date;\n if (paidDocumentEmbedding(settings)) {\n if (!settings.documentEmbeddingCreditsActivatedAt)\n throw new Error(\"paid Knowledge embedding requires an activation cutoff\");\n policyActivatedAt = new Date(settings.documentEmbeddingCreditsActivatedAt);\n } else {\n activationTime ??= knowledgeIndexBillingActivationTime(db).catch((error) => {\n activationTime = undefined;\n throw error;\n });\n policyActivatedAt = await activationTime;\n }\n const { embedder } = await resolveDocumentServices();\n const { knowledgeIndexChunks } = await import(\"@opengeni/documents\");\n const claims = await claimKnowledgeIndexJobs(db, {\n model: embedder.model,\n dimensions: embedder.dimensions,\n limit: 2,\n });\n for (const claim of claims) {\n let stage: KnowledgeIndexFailureStage = \"processing\";\n try {\n const source = await readKnowledgeIndexSource(db, claim);\n if (!source) {\n result.unavailable++;\n continue;\n }\n // The checkpoint, usage and post-use debit commit together. A new\n // generation requires funding once; committed batches may finish even\n // if their accumulated cost takes the balance below zero.\n await withWorkspaceUsageLock(db, source.billingWorkspaceId, async (lockedDb) => {\n const current = await readKnowledgeIndexSource(lockedDb, claim);\n if (!current) {\n result.unavailable++;\n return;\n }\n const chunks = [];\n let more = false;\n for (const chunk of knowledgeIndexChunks(current.entry)) {\n if (chunk.index < current.nextIndex) continue;\n if (chunks.length === 32) {\n more = true;\n break;\n }\n chunks.push(chunk);\n }\n if (chunks.length) {\n const frozenPolicy = await freezeKnowledgeIndexBillingMode(\n lockedDb,\n claim,\n // Deterministic embeddings incur no provider charge; a valid\n // credits-mode config with zero tariff must still index them.\n // OpenAI shadow keeps its price snapshot for internal estimates.\n settings.documentEmbeddingProvider === \"openai\"\n ? (settings.documentEmbeddingBillingMode ?? \"usage_only\")\n : \"usage_only\",\n policyActivatedAt,\n settings.documentEmbeddingRateMicrosPerMillionBytes ?? 0,\n );\n if (frozenPolicy.mode === \"awaiting_review\") {\n result.deferred++;\n return;\n }\n if (frozenPolicy.mode === \"obsolete\") {\n result.unavailable++;\n return;\n }\n // An already-priced generation cannot become free when the\n // operator turns off paid embedding. Retain its checkpoint and\n // retry only after paid mode is restored; never call the provider\n // or append a batch that the live policy would not debit.\n if (frozenPolicy.mode === \"credits\" && !paidDocumentEmbedding(settings)) {\n await deferKnowledgeIndexJob(lockedDb, claim);\n result.deferred++;\n return;\n }\n const paid = frozenPolicy.mode === \"credits\";\n if (paid && claim.billingAttribution.kind === \"unknown\") {\n // Unknown legacy/source-preparation causality is not service.\n // Keep the checkpoint without making an uncountable paid call.\n observability.warn(\"Paid Knowledge indexing awaits initiating attribution\", {\n errorCode: \"knowledge_index_attribution_unavailable\",\n });\n await deferKnowledgeIndexJob(lockedDb, claim);\n result.deferred++;\n return;\n }\n if (paid && current.nextIndex === 0) {\n const balance = await getBillingBalance(lockedDb, claim.accountId);\n if (balance.balanceMicros <= 0) {\n await waitKnowledgeIndexForFunding(lockedDb, claim);\n result.deferred++;\n return;\n }\n }\n if (paid) {\n const refusal = await checkWorkspaceAllowance(lockedDb, {\n accountId: claim.accountId,\n workspaceId: current.billingWorkspaceId,\n subjectId:\n claim.billingAttribution.kind === \"turn\" ||\n claim.billingAttribution.kind === \"human\"\n ? claim.billingAttribution.initiatingHumanSubjectId\n : null,\n });\n if (refusal) {\n await deferKnowledgeIndexJob(lockedDb, claim);\n result.deferred++;\n return;\n }\n }\n if (settings.usageLimitsMode === \"static\" || settings.usageLimitsMode === \"managed\") {\n const limit =\n configuredStaticUsageLimits(settings).maxDocumentIndexedChunksPerWorkspace;\n if (limit) {\n const now = new Date();\n const used = await sumUsageQuantity(lockedDb, {\n workspaceId: current.billingWorkspaceId,\n eventType: \"document.indexed\",\n since: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)),\n });\n if (used + chunks.length > limit) throw new KnowledgeIndexUsageLimitError();\n }\n }\n const inputs = chunks.map((chunk) => chunk.embeddingInput);\n const bytes = inputs.reduce(\n (sum, input) => sum + Buffer.byteLength(input, \"utf8\"),\n 0,\n );\n stage = \"embedding\";\n const vectors = await embedder.embedMany(inputs);\n if (vectors.length !== chunks.length)\n throw new Error(\"Incomplete Knowledge embeddings\");\n stage = \"processing\";\n // A reviewer may have rejected this revision during the provider\n // call. The DB guard holds its publication row through settlement.\n if (paid) {\n const publication = await guardPaidKnowledgeIndexPublication(lockedDb, claim);\n if (publication !== \"published\") {\n if (publication === \"obsolete\") result.unavailable++;\n else result.deferred++;\n return;\n }\n }\n const appended = await appendKnowledgeIndexChunks(\n lockedDb,\n claim,\n current.nextIndex,\n chunks.map((chunk, index) => ({ ...chunk, embedding: vectors[index]! })),\n );\n if (appended.status !== \"running\") {\n result.unavailable++;\n return;\n }\n await recordUsageEvent(lockedDb, {\n accountId: claim.accountId,\n workspaceId: current.billingWorkspaceId,\n eventType: \"document.indexed\",\n quantity: chunks.length,\n unit: \"chunk\",\n sourceResourceType: \"knowledge_revision\",\n sourceResourceId: claim.revisionId,\n idempotencyKey: `knowledge.indexed:${claim.revisionId}:${claim.generation}:${current.nextIndex}`,\n });\n await recordUsageEvent(lockedDb, {\n accountId: claim.accountId,\n workspaceId: current.billingWorkspaceId,\n eventType: \"document.embedding_bytes\",\n quantity: bytes,\n unit: \"byte\",\n sourceResourceType: \"knowledge_revision\",\n sourceResourceId: claim.revisionId,\n idempotencyKey: `knowledge.embedding_bytes:${claim.revisionId}:${claim.generation}:${current.nextIndex}`,\n });\n if (frozenPolicy.mode === \"shadow\" && frozenPolicy.rateMicrosPerMillionBytes > 0) {\n const estimate = documentEmbeddingCostMicros(\n {\n ...settings,\n documentEmbeddingRateMicrosPerMillionBytes:\n frozenPolicy.rateMicrosPerMillionBytes,\n },\n bytes,\n );\n if (estimate > 0)\n await recordUsageEvent(lockedDb, {\n accountId: claim.accountId,\n workspaceId: current.billingWorkspaceId,\n eventType: \"document.embedding_shadow_estimate\",\n quantity: estimate,\n unit: \"micro_usd\",\n sourceResourceType: \"knowledge_revision\",\n sourceResourceId: claim.revisionId,\n idempotencyKey: `knowledge.embedding_shadow:${claim.revisionId}:${claim.generation}:${current.nextIndex}`,\n });\n }\n if (paid) {\n const cost = documentEmbeddingCostMicros(\n {\n ...settings,\n documentEmbeddingRateMicrosPerMillionBytes:\n frozenPolicy.rateMicrosPerMillionBytes,\n },\n bytes,\n );\n if (cost > 0)\n await applyCreditDebitAfterUse(lockedDb, {\n accountId: claim.accountId,\n workspaceId: current.billingWorkspaceId,\n type: \"document_embedding_debit\",\n amountMicros: cost,\n sourceType: \"knowledge_revision\",\n sourceId: claim.revisionId,\n idempotencyKey: `knowledge.embedding:${claim.revisionId}:${claim.generation}:${current.nextIndex}`,\n metadata: {\n ...creditDebitAttributionMetadata(claim.billingAttribution),\n model: claim.model,\n bytes,\n chunks: chunks.length,\n rateMicrosPerMillionBytes: frozenPolicy.rateMicrosPerMillionBytes,\n },\n });\n }\n }\n if (more) {\n await continueKnowledgeIndexJob(lockedDb, claim);\n result.advanced++;\n } else {\n const completed = await completeKnowledgeIndexJob(\n lockedDb,\n claim,\n current.nextIndex + chunks.length,\n );\n if (completed.status === \"ready\") result.completed++;\n else result.unavailable++;\n }\n });\n } catch (error) {\n // Provider failures retain the last completed projection. The durable\n // queue owns retry/backoff; do not retry an entire activity implicitly.\n // The stored reason stays the SQL lifecycle's fixed code; the log\n // carries the content-free class/code of the actual cause.\n observability.warn(\n \"Knowledge indexing batch deferred\",\n knowledgeIndexFailureDiagnostic(stage, error),\n );\n await deferKnowledgeIndexJob(db, claim).catch((deferError: unknown) => {\n const deferDiagnostic = knowledgeIndexFailureDiagnostic(\"processing\", deferError);\n observability.warn(\"Knowledge indexing batch deferral failed\", {\n ...deferDiagnostic,\n errorCode: \"knowledge_index_defer_failed\",\n });\n });\n result.deferred++;\n }\n }\n return result;\n },\n };\n}\n","import {\n claimBrowserStateArtifactCleanup,\n claimBrowserStateUploadCleanup,\n completeBrowserStateArtifactCleanup,\n completeBrowserStateUploadCleanup,\n type BrowserStateArtifactCleanupClaim,\n type BrowserStateUploadCleanupClaim,\n} from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport type { ControlActivityServices } from \"./types\";\n\nexport const BROWSER_STATE_ARTIFACT_CLAIM_TIMEOUT_MS = 10 * 60 * 1_000;\nexport const BROWSER_STATE_ARTIFACT_CLEANUP_BATCH_SIZE = 100;\n\nconst SAFE_PROVIDER_ERROR_CODES = new Set([\n \"aborted\",\n \"conflict\",\n \"network\",\n \"not_found\",\n \"permission_denied\",\n \"provider\",\n \"timeout\",\n \"unavailable\",\n]);\n\nexport type MaintainBrowserStateArtifactsResult = {\n claimed: number;\n deleted: number;\n retryable: number;\n};\n\nexport type BrowserStateArtifactMaintenanceOptions = {\n claimTimeoutMs?: number;\n batchSize?: number;\n claimArtifacts?: typeof claimBrowserStateArtifactCleanup;\n completeArtifact?: typeof completeBrowserStateArtifactCleanup;\n claimUploads?: typeof claimBrowserStateUploadCleanup;\n completeUpload?: typeof completeBrowserStateUploadCleanup;\n /** Failure-injection seam; production uses the configured provider delete. */\n deleteObject?: (storage: ObjectStorage, key: string) => Promise<void>;\n};\n\n/**\n * Reap retired encrypted private browser checkpoints. Provider deletion happens\n * before terminal settlement; a crash or provider failure leaves the durable\n * claim reclaimable and an already-deleted provider key is safe to retry.\n */\nexport function createBrowserStateArtifactMaintenanceActivities(\n services: () => Promise<ControlActivityServices>,\n options: BrowserStateArtifactMaintenanceOptions = {},\n) {\n const claimTimeoutMs = options.claimTimeoutMs ?? BROWSER_STATE_ARTIFACT_CLAIM_TIMEOUT_MS;\n const batchSize = options.batchSize ?? BROWSER_STATE_ARTIFACT_CLEANUP_BATCH_SIZE;\n const claimArtifacts = options.claimArtifacts ?? claimBrowserStateArtifactCleanup;\n const completeArtifact = options.completeArtifact ?? completeBrowserStateArtifactCleanup;\n const claimUploads = options.claimUploads ?? claimBrowserStateUploadCleanup;\n const completeUpload = options.completeUpload ?? completeBrowserStateUploadCleanup;\n const deleteObject = options.deleteObject ?? ((storage, key) => storage.deleteObject(key));\n\n async function maintainBrowserStateArtifacts(): Promise<MaintainBrowserStateArtifactsResult> {\n const { db, objectStorage, observability } = await services();\n if (!objectStorage) return { claimed: 0, deleted: 0, retryable: 0 };\n\n const [artifactClaims, uploadClaims] = await Promise.all([\n claimArtifacts(db, { claimTimeoutMs, limit: batchSize }),\n claimUploads(db, { claimTimeoutMs, limit: batchSize }),\n ]);\n const result: MaintainBrowserStateArtifactsResult = {\n claimed: artifactClaims.length + uploadClaims.length,\n deleted: 0,\n retryable: 0,\n };\n for (const cleanup of artifactClaims) {\n try {\n await deleteObject(objectStorage, cleanup.objectKey);\n if (!(await completeArtifact(db, cleanup))) {\n throw new Error(\"browser state artifact cleanup claim was superseded\");\n }\n result.deleted += 1;\n } catch (error) {\n result.retryable += 1;\n observability.warn(\"browser state artifact cleanup failed; claim remains reclaimable\", {\n workspaceId: cleanup.workspaceId,\n artifactId: cleanup.artifactId,\n errorCategory: cleanupErrorCategory(error),\n });\n }\n }\n for (const cleanup of uploadClaims) {\n try {\n await deleteObject(objectStorage, cleanup.objectKey);\n if (!(await completeUpload(db, cleanup))) {\n throw new Error(\"browser state upload cleanup claim was superseded\");\n }\n result.deleted += 1;\n } catch (error) {\n result.retryable += 1;\n observability.warn(\"browser state upload cleanup failed; claim remains reclaimable\", {\n workspaceId: cleanup.workspaceId,\n uploadId: cleanup.uploadId,\n errorCategory: cleanupErrorCategory(error),\n });\n }\n }\n if (result.claimed > 0) {\n observability.info(\"browser state artifact maintenance swept\", result);\n }\n return result;\n }\n\n return { maintainBrowserStateArtifacts };\n}\n\nfunction cleanupErrorCategory(error: unknown): string {\n if (!error || typeof error !== \"object\") return \"unknown\";\n const code = (error as { code?: unknown }).code;\n return typeof code === \"string\" && SAFE_PROVIDER_ERROR_CODES.has(code) ? code : \"unknown\";\n}\n\nexport type { BrowserStateArtifactCleanupClaim, BrowserStateUploadCleanupClaim };\n","import { Context } from \"@temporalio/activity\";\nimport {\n environmentsEncryptionKeyBytes,\n resolveFirstPartyDelegationSecret,\n type Settings,\n} from \"@opengeni/config\";\nimport { BROWSER_STATE_ARTIFACT_CONTENT_TYPE } from \"@opengeni/contracts\";\nimport {\n browserDeadlineCheckpoint,\n clearSuspendedBrowserSessionController,\n commitBrowserSessionSuspension,\n dispatchBrowserSessionOperation,\n failBrowserSessionSuspension,\n listBrowserDeadlineCheckpoints,\n readLease,\n releaseLeaseHolder,\n withRlsContext,\n type BrowserDeadlineCheckpointTarget,\n} from \"@opengeni/db\";\nimport { deriveBrowserControllerAdminToken } from \"@opengeni/interaction/browser-controller-authority\";\nimport {\n browserStateArtifactAad,\n browserStateManifestDigest,\n browserStateObjectKey,\n deriveBrowserStateDataKey,\n wrapBrowserStateDataKey,\n} from \"@opengeni/interaction/browser-state-authority\";\nimport {\n BrowserControlClient,\n BrowserControlRequestError,\n createSandboxClientForBackend,\n deserializeSandboxSessionStateEnvelope,\n resumeExactSandboxSession,\n type BrowserControlPlacementSession,\n} from \"@opengeni/runtime\";\nimport type { ControlActivityServices } from \"./types\";\n\nconst UPLOAD_CLEANUP_GRACE_MS = 24 * 60 * 60_000;\n\nfunction heartbeat(): void {\n try {\n Context.current().heartbeat();\n } catch {\n // Direct embedded calls have no Temporal context. In-flight controller\n // operations still settle under their exact durable database claim.\n }\n}\n\nasync function withActivityHeartbeat<T>(run: () => Promise<T>): Promise<T> {\n heartbeat();\n const timer = setInterval(heartbeat, 5_000);\n try {\n return await run();\n } finally {\n clearInterval(timer);\n }\n}\n\ntype CheckpointController = Pick<BrowserControlClient, \"captureState\" | \"endSession\">;\ntype CheckpointPlacement = {\n target: BrowserDeadlineCheckpointTarget;\n lease: NonNullable<Awaited<ReturnType<typeof readLease>>>;\n settings: Settings;\n controllerRoot: string;\n};\n\nasync function resumeCheckpointController({\n target,\n lease,\n settings,\n controllerRoot,\n}: CheckpointPlacement): Promise<CheckpointController> {\n // This edge cannot create a box or route through a user's current machine.\n const provider = createSandboxClientForBackend(\"modal\", settings) as Parameters<\n typeof deserializeSandboxSessionStateEnvelope\n >[0];\n const envelope = lease.resumeState as { sessionState?: unknown };\n const state = await deserializeSandboxSessionStateEnvelope(\n provider,\n envelope.sessionState ?? lease.resumeState,\n target.instanceId,\n );\n const resumed = await resumeExactSandboxSession(provider, \"modal\", state, target.instanceId);\n return new BrowserControlClient(resumed.session as BrowserControlPlacementSession, {\n adminToken: deriveBrowserControllerAdminToken({\n rootSecret: controllerRoot,\n accountId: target.accountId,\n workspaceId: target.workspaceId,\n placement: { kind: \"sandbox_group\", sandboxGroupId: target.sandboxGroupId },\n placementInstanceId: target.instanceId,\n }),\n });\n}\n\nexport function createBrowserDeadlineCheckpointActivities(\n services: () => Promise<ControlActivityServices>,\n connectController: (\n placement: CheckpointPlacement,\n ) => Promise<CheckpointController> = resumeCheckpointController,\n) {\n return {\n async listDueBrowserCheckpoints() {\n return await withActivityHeartbeat(async () => {\n const { db, settings, objectStorage } = await services();\n if (\n !settings.sandboxOwnershipEnabled ||\n !objectStorage ||\n !resolveFirstPartyDelegationSecret(settings)\n )\n return [];\n const root = environmentsEncryptionKeyBytes(settings);\n if (!root) return [];\n root.fill(0);\n return await listBrowserDeadlineCheckpoints(db);\n });\n },\n async checkpointBrowserBeforeDeadline(target: BrowserDeadlineCheckpointTarget) {\n return await withActivityHeartbeat(async () => {\n const { db, settings, objectStorage } = await services();\n const rootKey = environmentsEncryptionKeyBytes(settings);\n const controllerRoot = resolveFirstPartyDelegationSecret(settings);\n if (!rootKey || !objectStorage || !controllerRoot) {\n rootKey?.fill(0);\n throw new Error(\"browser deadline checkpoint storage or encryption is unavailable\");\n }\n let dataKey: Buffer | null = null;\n let aad: Buffer | null = null;\n let timer: ReturnType<typeof setInterval> | null = null;\n try {\n const claim = await browserDeadlineCheckpoint(db, target, { prepare: true, touch: true });\n if (!claim) return { status: \"skipped\" as const };\n let pulseRunning = false;\n let authorityLost = false;\n const pulse = async () => {\n if (pulseRunning) return;\n pulseRunning = true;\n try {\n if (!(await browserDeadlineCheckpoint(db, target, { touch: true })))\n authorityLost = true;\n } finally {\n pulseRunning = false;\n }\n };\n timer = setInterval(() => {\n void pulse().catch(() => undefined);\n }, 5_000);\n const lease = await readLease(db, target.workspaceId, target.sandboxGroupId);\n if (\n !lease ||\n lease.instanceId !== target.instanceId ||\n lease.leaseEpoch !== target.leaseEpoch ||\n !lease.resumeState\n ) {\n throw new Error(\"browser deadline checkpoint placement changed\");\n }\n const placement = {\n kind: \"sandbox_group\" as const,\n sandboxGroupId: target.sandboxGroupId,\n };\n const client = await connectController({ target, lease, settings, controllerRoot });\n if (authorityLost || !(await browserDeadlineCheckpoint(db, target, { touch: true }))) {\n throw new Error(\"browser deadline checkpoint authority changed\");\n }\n if (claim.state !== \"completed\") {\n const scope = { ...target, operationId: claim.operationId };\n const objectKey = browserStateObjectKey(target.workspaceId, claim.operationId);\n dataKey = deriveBrowserStateDataKey(rootKey, { ...scope, objectKey });\n aad = browserStateArtifactAad({ ...scope, objectKey });\n await dispatchBrowserSessionOperation(db, {\n ...scope,\n deadlineTarget: target,\n stateUpload: {\n objectKey,\n cleanupAfter: new Date(Date.now() + UPLOAD_CLEANUP_GRACE_MS),\n },\n });\n const signed = await objectStorage.createPutUrl({\n key: objectKey,\n contentType: BROWSER_STATE_ARTIFACT_CONTENT_TYPE,\n audience: \"sandbox\",\n });\n const receipt = await client\n .captureState({\n ...scope,\n objectKey,\n afterCapture: \"stop\",\n dataKey,\n aad,\n upload: {\n url: signed.url,\n requiredHeaders: signed.requiredHeaders,\n expiresAt: signed.expiresAt.toISOString(),\n },\n })\n .catch(async (error: unknown) => {\n if (\n error instanceof BrowserControlRequestError &&\n (error.error.code === \"outcome_unknown\" || !error.error.retryable)\n ) {\n await failBrowserSessionSuspension(db, { ...scope, error: error.error });\n }\n throw error;\n });\n if (authorityLost) throw new Error(\"browser deadline checkpoint authority changed\");\n const portable = receipt.manifest.profileCrypto !== \"platform_bound\";\n await commitBrowserSessionSuspension(db, {\n ...scope,\n deadlineTarget: target,\n artifact: {\n kind: \"chromium_profile\",\n format: receipt.format,\n objectKey,\n artifactDigest: receipt.artifactDigest,\n contentDigest: receipt.contentDigest,\n manifestDigest: browserStateManifestDigest(receipt.manifest),\n sizeBytes: receipt.sizeBytes,\n encryptedDataKey: wrapBrowserStateDataKey(rootKey, dataKey, {\n ...scope,\n objectKey,\n artifactDigest: receipt.artifactDigest,\n contentDigest: receipt.contentDigest,\n }),\n materialization: {\n portability: portable ? \"portable\" : \"placement_bound\",\n reason: portable\n ? null\n : \"Profile encryption depends on the source operating-system credential store.\",\n platform: receipt.manifest.platform,\n architecture: receipt.manifest.architecture,\n engine: receipt.manifest.engine,\n engineVersion: receipt.manifest.engineVersion,\n driverId: receipt.manifest.driverId,\n driverSchemaVersion: receipt.manifest.driverSchemaVersion,\n profileCrypto: receipt.manifest.profileCrypto,\n providerId: null,\n placement: portable ? null : placement,\n },\n },\n });\n }\n // Only remove the local profile after the encrypted artifact and its\n // authority committed. A crash resumes this cleanup, never capture.\n await client.endSession(target, { removeState: true }).catch((error: unknown) => {\n if (!(error instanceof BrowserControlRequestError && error.status === 404)) throw error;\n });\n await withRlsContext(\n db,\n target,\n async (tx) => {\n if ((await browserDeadlineCheckpoint(tx, target))?.state !== \"completed\") {\n throw new Error(\"browser deadline checkpoint cleanup authority changed\");\n }\n await clearSuspendedBrowserSessionController(tx, {\n ...target,\n expectedControllerGeneration: target.controllerGeneration,\n });\n // One transaction prevents a human resume from acquiring a new\n // same-browser holder between clearing and releasing the old one.\n await releaseLeaseHolder(tx, {\n ...target,\n kind: \"interaction\",\n holderId: `browser-session:${target.browserSessionId}`,\n idleGraceMs: settings.sandboxIdleGraceMs,\n });\n },\n undefined,\n \"none\",\n );\n return { status: \"suspended\" as const };\n } finally {\n if (timer) clearInterval(timer);\n dataKey?.fill(0);\n aad?.fill(0);\n rootKey.fill(0);\n }\n });\n },\n };\n}\n","import {\n resolveTurnExecutionPolicyV1,\n WORKSPACE_GATEWAY_MODEL_ID_PREFIX,\n WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,\n} from \"@opengeni/config\";\nimport {\n agentConfigMayResolve,\n applySessionAgentConfigWriteThrough,\n assertWorkspaceModelPolicyAllows,\n canonicalConfiguredModel,\n resolveSessionAgentConfigForCreate,\n createAndStartSessionWithOutcome,\n recordWorkspaceUsage,\n resolveCatalogSettings,\n resolveWorkspaceCatalogSettings,\n isDeveloperSetupDelegatedPermissionAllowed,\n} from \"@opengeni/core\";\nimport {\n AutomationAuthorityRevokedError,\n assertAutomationRunAuthorityInTransaction,\n claimAutomationRun,\n settleAutomationRun,\n requireWorkspace,\n} from \"@opengeni/db\";\nimport { SessionSkills } from \"@opengeni/contracts\";\nimport { agentRunAdmissionDenial } from \"./agent-run-admission\";\nimport type {\n ControlActivityServices,\n DispatchAutomationRunInput,\n DispatchAutomationRunResult,\n} from \"./types\";\n\nexport type AutomationActivityOptions = {\n claim?: typeof claimAutomationRun;\n settle?: typeof settleAutomationRun;\n assertAuthority?: typeof assertAutomationRunAuthorityInTransaction;\n createSession?: typeof createAndStartSessionWithOutcome;\n /** Workspace read for agent-configuration defaults (tests inject it). */\n readWorkspace?: typeof requireWorkspace;\n admit?: typeof agentRunAdmissionDenial;\n assertModelPolicy?: typeof assertWorkspaceModelPolicyAllows;\n recordUsage?: typeof recordWorkspaceUsage;\n};\n\nexport function createAutomationActivities(\n services: () => Promise<ControlActivityServices>,\n options: AutomationActivityOptions = {},\n) {\n const claim = options.claim ?? claimAutomationRun;\n const settle = options.settle ?? settleAutomationRun;\n const assertAuthority = options.assertAuthority ?? assertAutomationRunAuthorityInTransaction;\n const createSession = options.createSession ?? createAndStartSessionWithOutcome;\n const readWorkspace = options.readWorkspace ?? requireWorkspace;\n const admit = options.admit ?? agentRunAdmissionDenial;\n const assertModelPolicy = options.assertModelPolicy ?? assertWorkspaceModelPolicyAllows;\n const recordUsage = options.recordUsage ?? recordWorkspaceUsage;\n return {\n settleAutomationRunFailure: async (input: DispatchAutomationRunInput): Promise<void> => {\n const service = await services();\n await settle(service.db, {\n workspaceId: input.workspaceId,\n runId: input.runId,\n status: \"failed\",\n errorCode: \"dispatch_failed\",\n });\n },\n dispatchAutomationRun: async (\n input: DispatchAutomationRunInput,\n ): Promise<DispatchAutomationRunResult> => {\n const service = await services();\n const catalogSourceSettings = service.catalogSourceSettings ?? service.settings;\n const deploymentCatalogSettings = (\n await resolveCatalogSettings(service.db, catalogSourceSettings)\n ).settings;\n const run = await claim(service.db, input);\n if (!run) return { action: \"not_found\" };\n if (run.status === \"dispatched\") {\n if (!run.sessionId) throw new Error(\"dispatched automation run is missing its session\");\n return { action: \"already_dispatched\", sessionId: run.sessionId };\n }\n if (run.status === \"skipped\") {\n return {\n action: \"skipped\",\n reason: run.errorCode ?? \"authority_revoked\",\n };\n }\n if (run.status === \"failed\") {\n return { action: \"failed\", reason: run.errorCode ?? \"dispatch_failed\" };\n }\n\n try {\n const accepted = run.acceptedExecution;\n if (\n accepted.accountId !== input.accountId ||\n accepted.workspaceId !== input.workspaceId ||\n accepted.sourceId !== run.sourceId ||\n accepted.triggerId !== run.triggerId ||\n accepted.triggerRevision !== run.triggerRevision ||\n accepted.eventId !== run.eventId\n ) {\n await settle(service.db, {\n workspaceId: input.workspaceId,\n runId: run.id,\n status: \"skipped\",\n errorCode: \"accepted_execution_mismatch\",\n });\n return { action: \"skipped\", reason: \"accepted_execution_mismatch\" };\n }\n\n const template = accepted.sessionTemplate;\n if (\n template.credentialRestriction === \"developer_setup\" &&\n template.firstPartyMcpPermissions.some(\n (permission) => !isDeveloperSetupDelegatedPermissionAllowed(permission),\n )\n ) {\n await settle(service.db, {\n workspaceId: input.workspaceId,\n runId: run.id,\n status: \"failed\",\n errorCode: \"credential_restriction_violation\",\n });\n return { action: \"failed\", reason: \"credential_restriction_violation\" };\n }\n const requestedModel = template.model ?? deploymentCatalogSettings.openaiModel;\n const catalogSettings =\n requestedModel.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||\n requestedModel.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX)\n ? (\n await resolveWorkspaceCatalogSettings(service.db, catalogSourceSettings, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n retainedProductModelId: requestedModel,\n })\n ).settings\n : deploymentCatalogSettings;\n const catalogService = { ...service, settings: catalogSettings };\n let model: string;\n try {\n const configuredModel = canonicalConfiguredModel(catalogSettings, requestedModel);\n if (!configuredModel) throw new Error(\"automation has no configured model\");\n await assertModelPolicy(service.db, catalogSettings, input.workspaceId, configuredModel);\n model = configuredModel;\n } catch (error) {\n if (!isUnprocessableEntity(error)) throw error;\n await settle(service.db, {\n workspaceId: input.workspaceId,\n runId: run.id,\n status: \"failed\",\n errorCode: \"dispatch_failed\",\n });\n return { action: \"failed\", reason: \"dispatch_failed\" };\n }\n const denial = await admit(catalogService, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n model,\n requestedAgentRuns: 1,\n });\n if (denial) {\n await settle(service.db, {\n workspaceId: input.workspaceId,\n runId: run.id,\n status: \"failed\",\n errorCode: denial,\n });\n return { action: \"failed\", reason: denial };\n }\n const reasoningEffort = template.reasoningEffort ?? catalogSettings.openaiReasoningEffort;\n const sandboxBackend = template.sandboxBackend ?? catalogSettings.sandboxBackend;\n if (sandboxBackend === \"selfhosted\") {\n await settle(service.db, {\n workspaceId: input.workspaceId,\n runId: run.id,\n status: \"skipped\",\n errorCode: \"interactive_compute_not_allowed\",\n });\n return {\n action: \"skipped\",\n reason: \"interactive_compute_not_allowed\",\n };\n }\n // Agent configuration for the generated session (null = legacy). The\n // template's explicit tools are its baseline; capabilities only narrow.\n let agentWriteThrough: {\n config: import(\"@opengeni/contracts\").ResolvedAgentConfig | null;\n instructions: string | undefined;\n firstPartyMcpTools: typeof template.firstPartyMcpTools;\n tools: typeof template.tools;\n };\n try {\n const workspaceSettings = agentConfigMayResolve(catalogSettings, template.agent)\n ? (await readWorkspace(service.db, input.workspaceId)).settings\n : {};\n const resolution = resolveSessionAgentConfigForCreate({\n settings: catalogSettings,\n creator: \"automation\",\n request: template.agent,\n instructions: template.instructions ?? undefined,\n workspaceSettings,\n parent: null,\n goal: false,\n });\n const written = applySessionAgentConfigWriteThrough({\n config: resolution.config,\n firstPartyMcpTools: template.firstPartyMcpTools,\n tools: template.tools,\n toolPolicy: { mode: \"explicit\", inheritedFromSessionId: null },\n productServerIds: template.tools.map((tool) => tool.id),\n });\n agentWriteThrough = {\n config: resolution.config,\n instructions: resolution.instructions,\n firstPartyMcpTools: written.firstPartyMcpTools,\n tools: written.tools,\n };\n } catch (error) {\n if (!isUnprocessableEntity(error)) throw error;\n await settle(service.db, {\n workspaceId: input.workspaceId,\n runId: run.id,\n status: \"failed\",\n errorCode: \"dispatch_failed\",\n });\n return { action: \"failed\", reason: \"dispatch_failed\" };\n }\n const resolvedTurnExecutionPolicy = resolveTurnExecutionPolicyV1(catalogSettings, {\n modelId: model,\n requestedModelId: template.model,\n modelSource: template.model ? \"explicit\" : \"deployment\",\n reasoningEffort,\n reasoningSource: template.reasoningEffort ? \"explicit\" : \"deployment\",\n latencyMode: \"standard\",\n latencyModeSource: \"deployment\",\n });\n const turnExecutionPolicy = template.credentialRestriction\n ? {\n ...resolvedTurnExecutionPolicy,\n credentialRestriction: template.credentialRestriction,\n }\n : resolvedTurnExecutionPolicy;\n const created = await createSession({\n db: service.db,\n bus: service.bus,\n workflowClient: {\n wakeSessionWorkflow: async (wake) => {\n await service.wakeSessionWorkflow?.(wake);\n },\n },\n beforeCreateCommit: async (tx, sessionId) => {\n await assertAuthority(tx, {\n workspaceId: input.workspaceId,\n runId: run.id,\n triggerId: accepted.triggerId,\n triggerRevision: accepted.triggerRevision,\n sourceId: accepted.sourceId,\n sourceVersion: accepted.sourceVersion,\n sessionId,\n });\n },\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n initialMessage: accepted.initialMessage,\n surface: \"automation\",\n metrics: service.observability,\n resources: template.resources,\n skills: SessionSkills.parse(template.skills),\n bundledSkillIds: template.bundledSkillIds,\n tools: agentWriteThrough.tools,\n toolPolicy: { mode: \"explicit\", inheritedFromSessionId: null },\n model,\n reasoningEffort,\n turnExecutionPolicy,\n sandboxBackend,\n metadata: {\n ...template.metadata,\n automationRunId: run.id,\n automationSourceId: run.sourceId,\n automationTriggerId: run.triggerId,\n automationTriggerRevision: run.triggerRevision,\n },\n createdBy: {\n kind: \"service\",\n subjectId: accepted.serviceSubjectId,\n label: accepted.serviceLabel,\n },\n createdByContext: accepted.provenance,\n instructions: agentWriteThrough.instructions ?? template.instructions,\n policyRole: template.policyRole,\n firstPartyMcpPermissions: template.firstPartyMcpPermissions,\n firstPartyMcpTools: agentWriteThrough.firstPartyMcpTools,\n ...(agentWriteThrough.config ? { agentConfig: agentWriteThrough.config } : {}),\n retainWorkspaceCustomModel:\n model.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||\n model.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX),\n createIdempotencyKey: `automation-run:${run.id}`,\n subjectId: accepted.serviceSubjectId,\n });\n await recordUsage(\n { db: service.db, settings: catalogSettings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: accepted.serviceSubjectId,\n eventType: \"agent_run.created\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"automation_run\",\n sourceResourceId: run.id,\n sessionId: created.session.id,\n initiator: created.session.createdBy,\n initiatorContext: created.session.createdByContext,\n origin: \"system\",\n idempotencyKey: `agent_run.created:automation:${run.id}`,\n },\n ).catch((error) => {\n service.observability.warn(\"automation usage recording failed\", {\n workspaceId: input.workspaceId,\n runId: run.id,\n errorCategory: error instanceof Error ? error.name : \"unknown\",\n });\n });\n return { action: \"started\", sessionId: created.session.id };\n } catch (error) {\n if (error instanceof AutomationAuthorityRevokedError) {\n await settle(service.db, {\n workspaceId: input.workspaceId,\n runId: run.id,\n status: \"skipped\",\n errorCode: \"authority_revoked\",\n });\n return { action: \"skipped\", reason: \"authority_revoked\" };\n }\n throw error;\n }\n },\n };\n}\n\nfunction isUnprocessableEntity(error: unknown): boolean {\n return (\n error instanceof Error &&\n \"status\" in error &&\n (error as Error & { status?: unknown }).status === 422\n );\n}\n","import {\n claimDueTranscriptionRecordingObjectCleanup,\n claimExpiredFileUploadCleanup,\n completeDueTranscriptionRecordingObjectCleanup,\n completeExpiredFileUploadCleanup,\n claimVideoGenerationOperations,\n purgeExpiredTranscriptionRecordings,\n} from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport type { ControlActivityServices } from \"./types\";\nimport { randomUUID } from \"node:crypto\";\n\nexport const FILE_UPLOAD_CLEANUP_GRACE_MS = 60 * 60 * 1_000;\nexport const FILE_UPLOAD_CLEANUP_CLAIM_TIMEOUT_MS = 10 * 60 * 1_000;\nexport const FILE_UPLOAD_CLEANUP_BATCH_SIZE = 100;\nconst SAFE_CLEANUP_ERROR_CATEGORIES = new Set([\n \"aborted\",\n \"conflict\",\n \"invalid_response\",\n \"network\",\n \"not_found\",\n \"permission_denied\",\n \"provider\",\n \"timeout\",\n \"unavailable\",\n]);\n\nfunction cleanupErrorAttributes(error: unknown): {\n errorCategory: string;\n errorStatus?: number;\n} {\n let errorCategory = \"provider_error\";\n let errorStatus: number | undefined;\n if (error && typeof error === \"object\") {\n const rawCode = (error as { code?: unknown }).code;\n if (typeof rawCode === \"string\" && SAFE_CLEANUP_ERROR_CATEGORIES.has(rawCode)) {\n errorCategory = rawCode;\n } else if (rawCode !== undefined) {\n errorCategory = \"unknown\";\n }\n const rawStatus = Number(\n (error as { status?: unknown; statusCode?: unknown }).status ??\n (error as { statusCode?: unknown }).statusCode,\n );\n if (Number.isInteger(rawStatus) && rawStatus >= 100 && rawStatus <= 599) {\n errorStatus = rawStatus;\n }\n }\n return { errorCategory, ...(errorStatus === undefined ? {} : { errorStatus }) };\n}\n\nexport type ReapExpiredFileUploadsResult = {\n claimed: number;\n deleted: number;\n failed: number;\n};\n\nexport type FileUploadReaperActivityOptions = {\n graceMs?: number;\n claimTimeoutMs?: number;\n batchSize?: number;\n /** Failure-injection seam; production uses the configured provider delete. */\n deleteObject?: (storage: ObjectStorage, key: string) => Promise<void>;\n claimFileUploads?: typeof claimExpiredFileUploadCleanup;\n completeFileUpload?: typeof completeExpiredFileUploadCleanup;\n claimTranscriptionObjects?: typeof claimDueTranscriptionRecordingObjectCleanup;\n completeTranscriptionObject?: typeof completeDueTranscriptionRecordingObjectCleanup;\n purgeTranscriptionRecordings?: typeof purgeExpiredTranscriptionRecordings;\n};\n\n/**\n * Build the provider-neutral expired direct-upload reaper. Claims are durable\n * and reclaimable; object deletion is idempotent; only a successful delete is\n * settled terminally. One provider failure never aborts the rest of the batch.\n */\nexport function createFileUploadReaperActivities(\n services: () => Promise<ControlActivityServices>,\n options: FileUploadReaperActivityOptions = {},\n) {\n const graceMs = options.graceMs ?? FILE_UPLOAD_CLEANUP_GRACE_MS;\n const claimTimeoutMs = options.claimTimeoutMs ?? FILE_UPLOAD_CLEANUP_CLAIM_TIMEOUT_MS;\n const batchSize = options.batchSize ?? FILE_UPLOAD_CLEANUP_BATCH_SIZE;\n const deleteObject = options.deleteObject ?? (async (storage, key) => storage.deleteObject(key));\n const claimFileUploads = options.claimFileUploads ?? claimExpiredFileUploadCleanup;\n const completeFileUpload = options.completeFileUpload ?? completeExpiredFileUploadCleanup;\n const claimTranscriptionObjects =\n options.claimTranscriptionObjects ?? claimDueTranscriptionRecordingObjectCleanup;\n const completeTranscriptionObject =\n options.completeTranscriptionObject ?? completeDueTranscriptionRecordingObjectCleanup;\n const purgeTranscriptionRecordings =\n options.purgeTranscriptionRecordings ?? purgeExpiredTranscriptionRecordings;\n\n async function reapExpiredFileUploads(): Promise<ReapExpiredFileUploadsResult> {\n const { db, objectStorage, observability } = await services();\n if (!objectStorage) {\n try {\n await purgeTranscriptionRecordings(db, { graceMs, limit: batchSize });\n } catch (error) {\n observability.warn(\"expired transcription recording metadata purge failed\", {\n ...cleanupErrorAttributes(error),\n });\n }\n return { claimed: 0, deleted: 0, failed: 0 };\n }\n\n const claims = await claimFileUploads(db, {\n graceMs,\n claimTimeoutMs,\n limit: batchSize,\n });\n let deleted = 0;\n let failed = 0;\n for (const claim of claims) {\n try {\n await deleteObject(objectStorage, claim.objectKey);\n const settled = await completeFileUpload(db, claim);\n if (!settled) {\n throw new Error(\"cleanup claim no longer owns a reclaimable upload\");\n }\n deleted += 1;\n } catch (error) {\n failed += 1;\n observability.warn(\"expired file upload cleanup failed; claim remains reclaimable\", {\n workspaceId: claim.workspaceId,\n uploadId: claim.uploadId,\n fileId: claim.fileId,\n ...cleanupErrorAttributes(error),\n });\n }\n }\n const recordingClaims = await claimTranscriptionObjects(db, {\n graceMs,\n claimTimeoutMs,\n limit: batchSize,\n });\n for (const claim of recordingClaims) {\n try {\n await deleteObject(objectStorage, claim.objectKey);\n const settled = await completeTranscriptionObject(db, claim);\n if (!settled) {\n throw new Error(\"cleanup claim no longer owns a transcription recording object\");\n }\n deleted += 1;\n } catch (error) {\n failed += 1;\n observability.warn(\n \"expired transcription recording object cleanup failed; claim remains reclaimable\",\n {\n workspaceId: claim.workspaceId,\n recordingId: claim.recordingId,\n ...cleanupErrorAttributes(error),\n },\n );\n }\n }\n let transcriptionRecordingsPurged = 0;\n try {\n transcriptionRecordingsPurged = await purgeTranscriptionRecordings(db, {\n graceMs,\n limit: batchSize,\n });\n } catch (error) {\n observability.warn(\"expired transcription recording metadata purge failed\", {\n ...cleanupErrorAttributes(error),\n });\n }\n const claimed = claims.length + recordingClaims.length;\n if (claimed > 0 || transcriptionRecordingsPurged > 0) {\n observability.info(\"expired file upload cleanup swept\", {\n claimed,\n deleted,\n failed,\n fileUploads: claims.length,\n transcriptionRecordingObjects: recordingClaims.length,\n transcriptionRecordingsPurged,\n });\n }\n return { claimed, deleted, failed };\n }\n\n async function recoverVideoGenerationWorkflows(): Promise<{\n claimed: number;\n started: number;\n failed: number;\n }> {\n const { db, startVideoGenerationWorkflow, observability } = await services();\n if (!startVideoGenerationWorkflow) return { claimed: 0, started: 0, failed: 0 };\n const claims = await claimVideoGenerationOperations(db, {\n owner: `video-workflow-recovery:${randomUUID()}`,\n leaseSeconds: 120,\n limit: 100,\n });\n let started = 0;\n let failed = 0;\n for (const claim of claims) {\n try {\n await startVideoGenerationWorkflow(claim);\n started += 1;\n } catch (error) {\n failed += 1;\n observability.warn(\"Video generation workflow recovery start failed\", {\n operationId: claim.operationId,\n errorClass: error instanceof Error ? error.name : \"UnknownError\",\n });\n }\n }\n return { claimed: claims.length, started, failed };\n }\n\n return { reapExpiredFileUploads, recoverVideoGenerationWorkflows };\n}\n","import type { FileAsset } from \"@opengeni/contracts\";\nimport {\n claimRetainedScreenshotMaintenance,\n completeRetainedScreenshotMaintenance,\n promoteRetainedScreenshotMaintenanceCleanup,\n type RetainedScreenshotMaintenanceClaim,\n} from \"@opengeni/db\";\nimport { retryWhileMissing, type ObjectHead, type ObjectStorage } from \"@opengeni/storage\";\nimport type { ControlActivityServices } from \"./types\";\n\nexport const RETAINED_SCREENSHOT_PENDING_GRACE_MS = 15 * 60 * 1_000;\nexport const RETAINED_SCREENSHOT_CLAIM_TIMEOUT_MS = 10 * 60 * 1_000;\nexport const RETAINED_SCREENSHOT_MAINTENANCE_BATCH_SIZE = 100;\n\nexport type MaintainRetainedScreenshotsResult = {\n claimed: number;\n ready: number;\n deleted: number;\n failed: number;\n retryable: number;\n};\n\nexport type RetainedScreenshotMaintenanceActivityOptions = {\n pendingGraceMs?: number;\n claimTimeoutMs?: number;\n batchSize?: number;\n /** Provider seams used by deterministic unit tests. */\n fileExists?: (storage: ObjectStorage, file: FileAsset) => Promise<boolean>;\n headFile?: (storage: ObjectStorage, file: FileAsset) => Promise<ObjectHead>;\n deleteObject?: (storage: ObjectStorage, key: string) => Promise<void>;\n};\n\n/**\n * Reconcile interrupted screenshot writes and reap expired screenshot objects.\n * Claims move rows out of the readable `ready`/writable `pending` states before\n * provider access. Provider failures leave the durable claim reclaimable; DB\n * completion happens only after exact metadata verification or an idempotent\n * object delete.\n */\nexport function createRetainedScreenshotMaintenanceActivities(\n services: () => Promise<ControlActivityServices>,\n options: RetainedScreenshotMaintenanceActivityOptions = {},\n) {\n const pendingGraceMs = options.pendingGraceMs ?? RETAINED_SCREENSHOT_PENDING_GRACE_MS;\n const claimTimeoutMs = options.claimTimeoutMs ?? RETAINED_SCREENSHOT_CLAIM_TIMEOUT_MS;\n const batchSize = options.batchSize ?? RETAINED_SCREENSHOT_MAINTENANCE_BATCH_SIZE;\n const fileExists = options.fileExists ?? ((storage, file) => storage.fileExists(file));\n const headFile = options.headFile ?? ((storage, file) => storage.headFile(file));\n const deleteObject = options.deleteObject ?? ((storage, key) => storage.deleteObject(key));\n\n async function maintainRetainedScreenshots(): Promise<MaintainRetainedScreenshotsResult> {\n const { db, objectStorage, observability } = await services();\n if (!objectStorage) {\n return { claimed: 0, ready: 0, deleted: 0, failed: 0, retryable: 0 };\n }\n\n const claims = await claimRetainedScreenshotMaintenance(db, {\n pendingGraceMs,\n claimTimeoutMs,\n limit: batchSize,\n });\n const result: MaintainRetainedScreenshotsResult = {\n claimed: claims.length,\n ready: 0,\n deleted: 0,\n failed: 0,\n retryable: 0,\n };\n\n for (const claim of claims) {\n try {\n if (claim.action === \"reconcile\") {\n const outcome = await reconcileClaim(db, objectStorage, claim, {\n fileExists,\n headFile,\n deleteObject,\n });\n if (outcome === \"ready\") {\n result.ready += 1;\n } else {\n result.failed += 1;\n }\n continue;\n }\n\n await deleteObject(objectStorage, claim.objectKey);\n const outcome = terminalDeleteOutcome(claim.cleanupReason);\n const settled = await completeRetainedScreenshotMaintenance(db, {\n accountId: claim.accountId,\n workspaceId: claim.workspaceId,\n artifactId: claim.artifactId,\n claimId: claim.claimId,\n outcome,\n });\n if (!settled) throw new Error(\"retained screenshot cleanup claim was superseded\");\n result.deleted += 1;\n } catch (error) {\n result.retryable += 1;\n observability.warn(\"retained screenshot maintenance failed; claim remains reclaimable\", {\n workspaceId: claim.workspaceId,\n sessionId: claim.sessionId,\n artifactId: claim.artifactId,\n action: claim.action,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (claims.length > 0) {\n observability.info(\"retained screenshot maintenance swept\", result);\n }\n return result;\n }\n\n return { maintainRetainedScreenshots };\n}\n\nasync function reconcileClaim(\n db: Parameters<typeof completeRetainedScreenshotMaintenance>[0],\n storage: ObjectStorage,\n claim: RetainedScreenshotMaintenanceClaim,\n provider: Required<\n Pick<RetainedScreenshotMaintenanceActivityOptions, \"fileExists\" | \"headFile\" | \"deleteObject\">\n >,\n): Promise<\"ready\" | \"failed\"> {\n const observation = await observeClaimObject(storage, claim, provider);\n if (observation === \"matches\") {\n const settled = await completeRetainedScreenshotMaintenance(db, {\n accountId: claim.accountId,\n workspaceId: claim.workspaceId,\n artifactId: claim.artifactId,\n claimId: claim.claimId,\n outcome: \"ready\",\n });\n if (!settled) throw new Error(\"retained screenshot reconcile claim was superseded\");\n return \"ready\";\n }\n\n // A mismatch/missing observation cannot authorize provider deletion while\n // the artifact is still eligible for a concurrent ready settlement. Promote\n // the exact claim first; a ready winner clears the claim and makes this stale.\n const promoted = await promoteRetainedScreenshotMaintenanceCleanup(db, {\n accountId: claim.accountId,\n workspaceId: claim.workspaceId,\n artifactId: claim.artifactId,\n claimId: claim.claimId,\n cleanupReason: \"failed\",\n });\n if (!promoted) throw new Error(\"retained screenshot reconcile claim was superseded\");\n\n // Deletes are idempotent. Calling it for an authoritative missing observation\n // also closes a race with a late writer that began before cleanup ownership.\n await provider.deleteObject(storage, claim.objectKey);\n const settled = await completeRetainedScreenshotMaintenance(db, {\n accountId: claim.accountId,\n workspaceId: claim.workspaceId,\n artifactId: claim.artifactId,\n claimId: claim.claimId,\n outcome: \"failed\",\n });\n if (!settled) throw new Error(\"retained screenshot reconcile claim was superseded\");\n return \"failed\";\n}\n\nasync function observeClaimObject(\n storage: ObjectStorage,\n claim: RetainedScreenshotMaintenanceClaim,\n provider: Required<Pick<RetainedScreenshotMaintenanceActivityOptions, \"fileExists\" | \"headFile\">>,\n): Promise<\"matches\" | \"mismatch\" | \"missing\"> {\n const file = claimFile(storage, claim);\n const head = await retryWhileMissing(async () => {\n if (!(await provider.fileExists(storage, file))) return null;\n return await provider.headFile(storage, file);\n });\n if (!head) return \"missing\";\n return head.ContentLength === claim.sizeBytes &&\n head.ContentType === claim.mediaType &&\n head.Metadata?.sha256 === claim.sha256\n ? \"matches\"\n : \"mismatch\";\n}\n\nfunction claimFile(storage: ObjectStorage, claim: RetainedScreenshotMaintenanceClaim): FileAsset {\n const timestamp = new Date(0).toISOString();\n return {\n id: claim.artifactId,\n workspaceId: claim.workspaceId,\n status: \"pending_upload\",\n filename: `computer-screenshot-${claim.artifactId}.png`,\n safeFilename: `computer-screenshot-${claim.artifactId}.png`,\n contentType: claim.mediaType,\n sizeBytes: claim.sizeBytes,\n sha256: claim.sha256,\n bucket: storage.bucket,\n objectKey: claim.objectKey,\n createdAt: timestamp,\n updatedAt: timestamp,\n };\n}\n\nfunction terminalDeleteOutcome(reason: string | null): \"failed\" | \"expired\" | \"deleted\" {\n if (reason === \"expired\") return \"expired\";\n if (reason === \"failed\") return \"failed\";\n return \"deleted\";\n}\n","import type {\n AccessGrant,\n Rig,\n RigChange,\n RigCheck,\n RigProviderImage,\n RigVersion,\n SandboxBackend,\n} from \"@opengeni/contracts\";\nimport { sandboxLifecycleTransitionWaitMs } from \"@opengeni/config\";\nimport {\n appendRigSetupCommand,\n recordRigAuditEvent,\n classifyRigVerificationOutcome,\n promoteSetupAppendChange,\n rigProviderImageBuildRequestId,\n rigProviderImageContentHash,\n rigProviderImageProviderBindingKeyHash,\n rigProviderImageSetupHash,\n type RigProviderImageDefinition,\n} from \"@opengeni/core\";\nimport {\n acquireLease,\n beginRigChangeVerificationAttempt,\n claimRigVersionProviderImageBuild,\n commitWarmingToWarm,\n failWarmingToCold,\n finalizeRigVersionProviderImageBuild,\n getRig,\n getRigChange,\n getRigVersionById,\n markWarmLeaseInstanceLost,\n markSandboxCheckpointArtifactDeletePending,\n recordWarmingSandboxCreated,\n registerSandboxCheckpointArtifact,\n releaseLeaseHolder,\n touchLeaseHolder,\n updateRigChangeStatus,\n SandboxCheckpointArtifactRegistrationConflictError,\n type Database,\n} from \"@opengeni/db\";\nimport {\n buildImmutableProviderImage,\n createTurnToolCancellationController,\n deleteModalCheckpointSnapshot,\n describeNativeSnapshotArchive,\n encodeNativeSnapshotRef,\n establishSandboxSessionFromEnvelope,\n sandboxCommandExitCode,\n sandboxCommandOutput,\n serializeEstablishedSandboxEnvelope,\n providerSupportsImmutableImageBuild,\n tagModalSandbox,\n terminateManagedSandboxSession,\n verifySandboxExecReadiness,\n type EstablishedSandboxSession,\n type TurnSandboxCommandArgs,\n type TurnSandboxCommandSession,\n} from \"@opengeni/runtime/sandbox\";\nimport type { Context } from \"@temporalio/activity\";\nimport type { ControlActivityServices } from \"./types\";\nimport { rigProviderImageSourceImage } from \"./sandbox-images\";\nimport { currentActivityContext } from \"./streaming\";\n\ntype RigSetupHook = typeof import(\"@opengeni/runtime\").runRigSetupHook;\nlet rigSetupHookPromise: Promise<RigSetupHook> | null = null;\n\nasync function runRigSetupHook(...args: Parameters<RigSetupHook>): Promise<void> {\n rigSetupHookPromise ??= import(\"@opengeni/runtime\").then((runtime) => runtime.runRigSetupHook);\n const hook = await rigSetupHookPromise;\n await hook(...args);\n}\n\ntype SandboxLifecycleCommandRunner = (\n session: TurnSandboxCommandSession,\n args: TurnSandboxCommandArgs,\n) => Promise<unknown>;\n\nexport type RigVerificationWorkflowInput =\n | { workspaceId: string; changeId: string; versionId?: never }\n | { workspaceId: string; versionId: string; changeId?: never };\n\ntype CommandResult = {\n exitCode: number | null;\n output: string;\n};\n\nexport type RigPlatformCheckResult = CommandResult & RigCheck;\n\n/**\n * Platform-owned checks run after Rig setup and independently of user-declared\n * checks. They prove that a Rig layered on the deployment image did not remove\n * or replace the Browser, Terminal, or Computer/Desktop services. The commands\n * start each enabled service on its canonical loopback port, wait for its own\n * readiness contract, probe it, and tear it down before provider snapshotting.\n */\nexport function rigPlatformChecksForSettings(\n settings: ControlActivityServices[\"settings\"],\n): RigCheck[] {\n const backend = settings.sandboxBackend as SandboxBackend;\n if (!rigProviderImageSourceImage(settings, backend)) return [];\n\n const checks: RigCheck[] = [\n {\n name: \"opengeni-platform-browser\",\n command: [\n \"set -eu\",\n \"test -x /usr/local/bin/opengeni-browserd\",\n \"test -x /usr/local/bin/opengeni-browserd-up\",\n \"test -x /usr/local/bin/opengeni-browserd-down\",\n \"test -r /etc/opengeni/browser-engine\",\n '__og_browser_engine=\"$(head -n 1 /etc/opengeni/browser-engine)\"',\n 'test -n \"$__og_browser_engine\"',\n 'test -x \"$__og_browser_engine\"',\n '__og_browser_token=\"$(mktemp)\"',\n \"trap 'opengeni-browserd-down >/dev/null 2>&1 || true; rm -f \\\"$__og_browser_token\\\"' EXIT\",\n \"__og_browser_token_value=\\\"$(od -An -N32 -tx1 /dev/urandom | tr -d '[:space:]')\\\"\",\n 'test \"${#__og_browser_token_value}\" -eq 64',\n 'printf \\'%s\\\\n\\' \"$__og_browser_token_value\" > \"$__og_browser_token\"',\n 'chmod 0600 \"$__og_browser_token\"',\n 'OPENGENI_BROWSERD_ADMIN_TOKEN_FILE=\"$__og_browser_token\" OPENGENI_BROWSERD_PORT=7682 OPENGENI_BROWSERD_ALLOWED_ORIGINS= opengeni-browserd-up',\n \"curl --noproxy '*' -fsS http://127.0.0.1:7682/healthz >/dev/null\",\n \"curl --noproxy '*' -fsS -H \\\"Authorization: Bearer $__og_browser_token_value\\\" http://127.0.0.1:7682/v1/browser-sessions >/dev/null\",\n ].join(\"\\n\"),\n },\n ];\n\n if (settings.sandboxTerminalEnabled) {\n checks.push({\n name: \"opengeni-platform-terminal\",\n command: [\n \"set -eu\",\n \"test -x /usr/local/bin/opengeni-terminal-up\",\n \"test -x /usr/local/bin/opengeni-terminal-down\",\n \"command -v ttyd >/dev/null\",\n \"trap 'opengeni-terminal-down >/dev/null 2>&1 || true' EXIT\",\n \"TERMINAL_PORT=7681 opengeni-terminal-up\",\n \"curl --noproxy '*' -fsS http://127.0.0.1:7681/ >/dev/null\",\n ].join(\"\\n\"),\n });\n }\n\n if (settings.sandboxDesktopEnabled) {\n checks.push({\n name: \"opengeni-platform-computer-desktop\",\n command: [\n \"set -eu\",\n \"test -x /usr/local/bin/opengeni-desktop-up\",\n \"test -x /usr/local/bin/opengeni-desktop-down\",\n \"command -v Xvfb >/dev/null\",\n \"command -v x11vnc >/dev/null\",\n \"test -x /opt/noVNC/utils/novnc_proxy\",\n \"command -v scrot >/dev/null\",\n \"command -v xdotool >/dev/null\",\n '__og_desktop_home=\"$(mktemp -d)\"',\n \"trap 'opengeni-desktop-down >/dev/null 2>&1 || true; rm -rf \\\"$__og_desktop_home\\\"' EXIT\",\n 'HOME=\"$__og_desktop_home\" STREAM_PORT=6080 DESKTOP_W=1280 DESKTOP_H=800 opengeni-desktop-up',\n \"curl --noproxy '*' -fsS http://127.0.0.1:6080/vnc.html >/dev/null\",\n \"nc -z 127.0.0.1 5900\",\n ].join(\"\\n\"),\n });\n }\n\n return checks;\n}\n\nconst RIG_VERIFICATION_CLEANUP_RESERVE_MAX_MS = 2 * 60_000;\nconst RIG_VERIFICATION_CLEANUP_OPERATION_MAX_MS = 60_000;\nconst RIG_VERIFICATION_HEARTBEAT_MAX_INTERVAL_MS = 10_000;\nconst RIG_VERIFICATION_HEARTBEAT_MIN_INTERVAL_MS = 250;\n// The Temporal activity has a 15-minute start-to-close timeout. Keep ownership\n// through that complete contract plus five minutes for cancellation delivery\n// and finally cleanup; a dead process then becomes sweep-eligible without any\n// lease-holder fiction or manual recovery.\nexport const RIG_VERIFICATION_OWNER_TTL_MS = 20 * 60_000;\nexport const RIG_VERIFICATION_OWNERS_DISABLED_MESSAGE =\n \"Sandbox Environment verification lease ownership is disabled; refusing to create an unowned verifier sandbox\";\nconst RIG_VERIFICATION_HOLDER_TOUCH_INTERVAL_MS = 10_000;\nconst RIG_VERIFICATION_RELEASE_GRACE_MS = 1;\n\nexport class RigVerificationActivityDeadlineError extends Error {\n readonly name = \"RigVerificationActivityDeadlineError\";\n\n constructor(\n readonly startToCloseTimeoutMs: number,\n readonly cleanupReserveMs: number,\n ) {\n super(\n `Sandbox Environment verification activity-local deadline reached with ${cleanupReserveMs}ms reserved for cleanup before the ${startToCloseTimeoutMs}ms Temporal start-to-close timeout`,\n );\n }\n}\n\nexport type RigVerificationActivityLifecycle = {\n signal: AbortSignal;\n /** Absolute wall-clock boundary before which immediate cleanup may wait. */\n cleanupDeadlineAtMs: number | null;\n dispose(): void;\n};\n\nfunction computeCleanupReserveMs(startToCloseTimeoutMs: number): number {\n return Math.min(\n RIG_VERIFICATION_CLEANUP_RESERVE_MAX_MS,\n Math.max(100, Math.floor(startToCloseTimeoutMs / 4)),\n Math.max(1, startToCloseTimeoutMs - 1),\n );\n}\n\n/**\n * Start the verifier's real Temporal liveness/cancellation contract.\n *\n * The activity-local deadline is deliberately earlier than start-to-close. In\n * production a 15-minute server deadline becomes a 13-minute work deadline,\n * retaining two minutes for command quiescence, exact deactivation, and\n * provider termination. Short integration-test deadlines use the same bounded\n * one-quarter rule instead of a production-only magic value.\n */\nexport function createRigVerificationActivityLifecycle(\n context: Context | null = currentActivityContext(),\n): RigVerificationActivityLifecycle {\n const controller = new AbortController();\n const temporalSignal = context?.cancellationSignal;\n const forwardTemporalCancellation = (): void => {\n if (!controller.signal.aborted) {\n controller.abort(\n temporalSignal?.reason ?? new Error(\"Sandbox Environment verification cancelled\"),\n );\n }\n };\n if (temporalSignal?.aborted) {\n forwardTemporalCancellation();\n } else {\n temporalSignal?.addEventListener(\"abort\", forwardTemporalCancellation, { once: true });\n }\n\n const startedAtMs = Date.now();\n const startToCloseTimeoutMs = context?.info.startToCloseTimeoutMs;\n const reserveMs =\n typeof startToCloseTimeoutMs === \"number\" && startToCloseTimeoutMs > 0\n ? computeCleanupReserveMs(startToCloseTimeoutMs)\n : null;\n const serverDeadlineAtMs =\n reserveMs === null || startToCloseTimeoutMs === undefined\n ? null\n : startedAtMs + startToCloseTimeoutMs;\n // Keep an additional margin after our bounded cleanup waits. If a DB or\n // provider promise remains unresolved, the activity must still report its\n // local deadline before Temporal imposes the hard timeout.\n const serverReportingMarginMs =\n reserveMs === null ? 0 : Math.min(30_000, Math.max(1, Math.floor(reserveMs / 4)));\n const cleanupDeadlineAtMs =\n serverDeadlineAtMs === null ? null : serverDeadlineAtMs - serverReportingMarginMs;\n\n let deadlineTimer: ReturnType<typeof setTimeout> | null = null;\n if (reserveMs !== null && startToCloseTimeoutMs !== undefined && !controller.signal.aborted) {\n deadlineTimer = setTimeout(\n () => {\n if (!controller.signal.aborted) {\n controller.abort(\n new RigVerificationActivityDeadlineError(startToCloseTimeoutMs, reserveMs),\n );\n }\n },\n Math.max(1, startToCloseTimeoutMs - reserveMs),\n );\n }\n\n const heartbeat = (): void => {\n if (!context) return;\n try {\n context.heartbeat({\n activity: \"rig_verification\",\n at: new Date().toISOString(),\n cleanup: controller.signal.aborted,\n cleanupDeadlineAt: cleanupDeadlineAtMs ? new Date(cleanupDeadlineAtMs).toISOString() : null,\n });\n } catch (error) {\n // Context.heartbeat reports delivered cancellation synchronously on some\n // SDK paths. Feed that failure into the same cooperative abort fence, but\n // keep the interval alive through bounded cleanup: the abort signal stops\n // verifier work, not the activity's liveness reporting.\n if (!controller.signal.aborted) controller.abort(error);\n }\n };\n heartbeat();\n const heartbeatTimeoutMs = context?.info.heartbeatTimeoutMs;\n const heartbeatIntervalMs =\n typeof heartbeatTimeoutMs === \"number\" && heartbeatTimeoutMs > 0\n ? Math.min(\n RIG_VERIFICATION_HEARTBEAT_MAX_INTERVAL_MS,\n Math.max(RIG_VERIFICATION_HEARTBEAT_MIN_INTERVAL_MS, Math.floor(heartbeatTimeoutMs / 3)),\n )\n : RIG_VERIFICATION_HEARTBEAT_MAX_INTERVAL_MS;\n const heartbeatTimer = context ? setInterval(heartbeat, heartbeatIntervalMs) : null;\n if (heartbeatTimer && \"unref\" in heartbeatTimer && typeof heartbeatTimer.unref === \"function\") {\n heartbeatTimer.unref();\n }\n\n return {\n signal: controller.signal,\n cleanupDeadlineAtMs,\n dispose: () => {\n temporalSignal?.removeEventListener(\"abort\", forwardTemporalCancellation);\n if (deadlineTimer) clearTimeout(deadlineTimer);\n if (heartbeatTimer) clearInterval(heartbeatTimer);\n deadlineTimer = null;\n },\n };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new Error(\"Sandbox Environment verification cancelled\");\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (signal.aborted) throw abortReason(signal);\n}\n\nasync function waitForAbortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n throwIfAborted(signal);\n let removeAbortListener = (): void => undefined;\n const cancellation = new Promise<never>((_resolve, reject) => {\n const onAbort = (): void => reject(abortReason(signal));\n removeAbortListener = () => signal.removeEventListener(\"abort\", onAbort);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n try {\n return await Promise.race([promise, cancellation]);\n } finally {\n removeAbortListener();\n }\n}\n\ntype BoundedSettlement<T> = { status: \"completed\"; value: T } | { status: \"timed_out\" };\n\nasync function settleWithin<T>(\n promise: Promise<T>,\n timeoutMs: number,\n): Promise<BoundedSettlement<T>> {\n if (timeoutMs <= 0) return { status: \"timed_out\" };\n let timer: ReturnType<typeof setTimeout> | null = null;\n try {\n return await Promise.race([\n promise.then((value) => ({ status: \"completed\" as const, value })),\n new Promise<{ status: \"timed_out\" }>((resolve) => {\n timer = setTimeout(() => resolve({ status: \"timed_out\" }), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nfunction cleanupWaitMs(lifecycle: RigVerificationActivityLifecycle | undefined): number {\n if (lifecycle?.cleanupDeadlineAtMs == null) {\n return RIG_VERIFICATION_CLEANUP_OPERATION_MAX_MS;\n }\n return Math.max(\n 0,\n Math.min(RIG_VERIFICATION_CLEANUP_OPERATION_MAX_MS, lifecycle.cleanupDeadlineAtMs - Date.now()),\n );\n}\n\nfunction systemGrant(rig: Rig): AccessGrant {\n return {\n accountId: rig.accountId,\n workspaceId: rig.workspaceId,\n subjectId: \"system:rig-verification\",\n permissions: [\"rigs:use\", \"rigs:manage\"],\n };\n}\n\nasync function terminateThrowaway(established: EstablishedSandboxSession | null): Promise<boolean> {\n if (!established) return true;\n try {\n await terminateManagedSandboxSession(\n established.client,\n established.sessionState,\n established.session,\n );\n return true;\n } catch {\n return false;\n }\n}\n\nexport type RigVerificationOwnershipDependencies = {\n acquire: typeof acquireLease;\n establish: typeof establishSandboxSessionFromEnvelope;\n recordCreated: typeof recordWarmingSandboxCreated;\n commitWarm: typeof commitWarmingToWarm;\n touchHolder: typeof touchLeaseHolder;\n releaseHolder: typeof releaseLeaseHolder;\n failWarming: typeof failWarmingToCold;\n markWarmLost: typeof markWarmLeaseInstanceLost;\n serialize: typeof serializeEstablishedSandboxEnvelope;\n tag: typeof tagModalSandbox;\n terminate: typeof terminateThrowaway;\n createCancellationController: typeof createTurnToolCancellationController;\n randomUUID: () => string;\n};\n\nconst defaultOwnershipDependencies: RigVerificationOwnershipDependencies = {\n acquire: acquireLease,\n establish: establishSandboxSessionFromEnvelope,\n recordCreated: recordWarmingSandboxCreated,\n commitWarm: commitWarmingToWarm,\n touchHolder: touchLeaseHolder,\n releaseHolder: releaseLeaseHolder,\n failWarming: failWarmingToCold,\n markWarmLost: markWarmLeaseInstanceLost,\n serialize: serializeEstablishedSandboxEnvelope,\n tag: tagModalSandbox,\n terminate: terminateThrowaway,\n createCancellationController: createTurnToolCancellationController,\n randomUUID: () => crypto.randomUUID(),\n};\n\nexport type RigVerificationSandboxRunContext = {\n signal: AbortSignal;\n commandRunner: SandboxLifecycleCommandRunner;\n ownership: {\n leaseId: string;\n leaseEpoch: number;\n workspaceGeneration: number;\n instanceId: string;\n };\n};\n\nexport class RigVerificationLeaseUnavailableError extends Error {\n readonly name = \"RigVerificationLeaseUnavailableError\";\n\n constructor(\n readonly sandboxGroupId: string,\n readonly role: \"attached\" | \"blocked\" | \"rearmed\" | \"fenced\",\n ) {\n super(\n `Sandbox Environment verification requires a new clean sandbox, but lease ${sandboxGroupId} was ${role}`,\n );\n }\n}\n\n/**\n * Run one verifier against one exactly attributed standalone sandbox.\n *\n * Ordering is deliberate and source-of-truth safe:\n * acquire spawner -> create callback -> warming instance record -> warm commit\n * -> setup/checks. The canonical sandbox lease, not provider tags, is durable\n * ownership. Every exact create callback is retained before its DB write so an\n * ambiguous acknowledgement can still be terminated in finally. Provider\n * termination precedes clearing that exact durable pointer; when termination\n * fails the pointer is retained and the holder is released with a one-millisecond\n * drain grace so the normal reaper retries. Temporal cancellation first drains\n * every verifier command. Cleanup waits are bounded inside the server reserve;\n * lease expiry and the provider reaper remain the hard-worker-loss backstops.\n */\nexport async function runWithOwnedRigVerificationSandbox<T>(\n input: {\n settings: ControlActivityServices[\"settings\"];\n db: Database;\n observability: ControlActivityServices[\"observability\"];\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n rigVersionId: string;\n sessionIdPrefix: string;\n lifecycle?: RigVerificationActivityLifecycle;\n },\n run: (\n established: EstablishedSandboxSession,\n context: RigVerificationSandboxRunContext,\n ) => Promise<T>,\n dependencies: RigVerificationOwnershipDependencies = defaultOwnershipDependencies,\n): Promise<T> {\n // Phase B must remain inert throughout its code rollout. A disabled or\n // omitted flag rejects before establish() can invoke any provider create;\n // falling back to the legacy unowned verifier is never safe.\n if (!input.settings.rigVerificationLeaseOwnershipEnabled) {\n throw new Error(RIG_VERIFICATION_OWNERS_DISABLED_MESSAGE);\n }\n\n const holderId = `rig-verification:${dependencies.randomUUID()}`;\n const fallbackController = new AbortController();\n const signal = input.lifecycle?.signal ?? fallbackController.signal;\n const commandController = dependencies.createCancellationController(signal);\n const commandRunner = commandController.runSandboxCommand.bind(commandController);\n let cleanupTarget: EstablishedSandboxSession | null = null;\n let acquired = false;\n let ownsWarmingEpoch = false;\n let expectedEpoch: number | null = null;\n let holderLivenessTimer: ReturnType<typeof setInterval> | null = null;\n let establishmentSettled = false;\n let establishmentPromise: Promise<EstablishedSandboxSession> | null = null;\n\n const warnCleanupTimeout = (operation: string, instanceId: string | null): void => {\n input.observability.warn(\"sandbox environment verifier: ownership cleanup timed out\", {\n holderId,\n instanceId,\n operation,\n error:\n \"cleanup did not settle inside the activity reserve; exact owner expiry and the global provider reaper are the bounded delayed backstop\",\n });\n };\n\n const warnCleanupFailure = (\n operation: string,\n instanceId: string | null,\n error: unknown,\n ): void => {\n input.observability.warn(\"sandbox environment verifier: ownership cleanup failed\", {\n holderId,\n instanceId,\n operation,\n error: error instanceof Error ? error.message : String(error),\n });\n };\n\n const clearTerminatedLeasePointer = async (instanceId: string): Promise<void> => {\n if (expectedEpoch === null) return;\n const cleanupEpoch = expectedEpoch;\n // Exactly one transition can match. Running both covers a commit whose DB\n // acknowledgement was lost: expectedEpoch is still warming, while\n // expectedEpoch+1 is the only possible committed warm epoch.\n const results = await Promise.allSettled([\n Promise.resolve().then(() =>\n dependencies.markWarmLost(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: cleanupEpoch + 1,\n expectedInstanceId: instanceId,\n }),\n ),\n Promise.resolve().then(() =>\n dependencies.failWarming(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: cleanupEpoch,\n }),\n ),\n ]);\n for (const [index, result] of results.entries()) {\n if (result.status === \"rejected\") {\n warnCleanupFailure(\n index === 0 ? \"mark_warm_lost\" : \"fail_warming\",\n instanceId,\n result.reason,\n );\n }\n }\n };\n\n const terminateAndClear = async (created: EstablishedSandboxSession): Promise<boolean> => {\n let terminated = false;\n try {\n terminated = await dependencies.terminate(created);\n } catch (error) {\n warnCleanupFailure(\"terminate\", created.instanceId, error);\n }\n if (!terminated) {\n warnCleanupFailure(\n \"terminate\",\n created.instanceId,\n new Error(\"provider termination was not confirmed; durable lease cleanup remains pending\"),\n );\n return false;\n }\n await clearTerminatedLeasePointer(created.instanceId);\n return true;\n };\n\n try {\n throwIfAborted(signal);\n const lease = await dependencies.acquire(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n kind: \"turn\",\n holderId,\n subjectId: null,\n backend: input.settings.sandboxBackend,\n image: rigProviderImageSourceImage(input.settings, input.settings.sandboxBackend),\n rigVersionId: input.rigVersionId,\n leaseTtlMs: RIG_VERIFICATION_OWNER_TTL_MS,\n warmingLeaseTtlMs: RIG_VERIFICATION_OWNER_TTL_MS,\n captureWaitMs: sandboxLifecycleTransitionWaitMs(input.settings),\n waitSignal: signal,\n });\n acquired = true;\n expectedEpoch = lease.lease.leaseEpoch;\n holderLivenessTimer = setInterval(() => {\n void dependencies\n .touchHolder(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n kind: \"turn\",\n holderId,\n })\n .catch(() => undefined);\n }, RIG_VERIFICATION_HOLDER_TOUCH_INTERVAL_MS);\n if (\"unref\" in holderLivenessTimer && typeof holderLivenessTimer.unref === \"function\") {\n holderLivenessTimer.unref();\n }\n if (lease.role !== \"spawner\") {\n throw new RigVerificationLeaseUnavailableError(input.sandboxGroupId, lease.role);\n }\n ownsWarmingEpoch = true;\n\n establishmentPromise = Promise.resolve().then(() =>\n dependencies.establish(input.settings, null, {\n sessionId: `${input.sessionIdPrefix}-${holderId}`,\n recovery: \"create-or-restore\",\n environment: {},\n onSandboxCreated: async (created) => {\n // Retain the exact handle before the durable write. If registration\n // throws after commit, finally still has the provider identity.\n cleanupTarget = created;\n const resumeState =\n created.backendId === \"modal\" ? null : await dependencies.serialize(created);\n const recorded = await dependencies.recordCreated(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: lease.lease.leaseEpoch,\n instanceId: created.instanceId,\n resumeBackendId: created.backendId,\n resumeState,\n leaseTtlMs: RIG_VERIFICATION_OWNER_TTL_MS,\n warmingLeaseTtlMs: RIG_VERIFICATION_OWNER_TTL_MS,\n });\n if (!recorded.recorded) {\n throw new RigVerificationLeaseUnavailableError(input.sandboxGroupId, \"fenced\");\n }\n\n if (created.backendId === \"modal\" && !signal.aborted) {\n try {\n await waitForAbortable(\n dependencies.tag(input.settings, created.instanceId, {\n leaseId: lease.lease.id,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n }),\n signal,\n );\n } catch (error) {\n if (!signal.aborted) {\n input.observability.warn(\n \"sandbox environment verifier: Modal ownership tag failed\",\n {\n holderId,\n instanceId: created.instanceId,\n error: error instanceof Error ? error.message : String(error),\n },\n );\n }\n }\n }\n\n // Provider create is not abortable. If it returns after cancellation\n // won the outer race, the callback owns an independent exact cleanup\n // path before it throws and triggers the runtime's fail-closed delete.\n if (signal.aborted) {\n await terminateAndClear(created);\n throw abortReason(signal);\n }\n },\n }),\n );\n void establishmentPromise.then(\n () => {\n establishmentSettled = true;\n },\n () => {\n establishmentSettled = true;\n },\n );\n // The losing provider promise retains the callback above and a rejection\n // handler, so a late create can still deactivate/terminate without an\n // unhandled rejection after the activity has reported cancellation.\n void establishmentPromise.catch(() => undefined);\n const established = await waitForAbortable(establishmentPromise, signal);\n cleanupTarget = established;\n await waitForAbortable(verifySandboxExecReadiness(established), signal);\n const resumeState =\n established.backendId === \"modal\" ? null : await dependencies.serialize(established);\n const committed = await dependencies.commitWarm(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: lease.lease.leaseEpoch,\n instanceId: established.instanceId,\n dataPlaneUrl: null,\n resumeBackendId: established.backendId,\n resumeState,\n leaseTtlMs: RIG_VERIFICATION_OWNER_TTL_MS,\n });\n if (!committed.committed || !committed.lease) {\n throw new RigVerificationLeaseUnavailableError(input.sandboxGroupId, \"fenced\");\n }\n const result = await run(established, {\n signal,\n commandRunner,\n ownership: {\n leaseId: committed.lease.id,\n leaseEpoch: committed.lease.leaseEpoch,\n workspaceGeneration: committed.lease.workspaceGeneration,\n instanceId: established.instanceId,\n },\n });\n throwIfAborted(signal);\n return result;\n } catch (error) {\n if (signal.aborted) throw abortReason(signal);\n throw error;\n } finally {\n if (signal.aborted && establishmentPromise && !establishmentSettled) {\n const lateEstablishment = await settleWithin(\n Promise.allSettled([establishmentPromise]),\n cleanupWaitMs(input.lifecycle),\n );\n if (lateEstablishment.status === \"timed_out\") {\n warnCleanupTimeout(\"establish_after_abort\", cleanupTarget?.instanceId ?? null);\n }\n }\n\n if (holderLivenessTimer) {\n clearInterval(holderLivenessTimer);\n holderLivenessTimer = null;\n }\n\n // Physical command quiescence precedes provider teardown. If the provider\n // control plane itself hangs, bound the wait so termination still starts\n // inside the server reserve; terminating the throwaway box is then the\n // stronger final process fence.\n commandController.cancel(signal.aborted ? abortReason(signal) : new Error(\"Verifier complete\"));\n const quiescence = commandController.waitForQuiescence();\n void quiescence.catch(() => undefined);\n const quiescenceResult = await settleWithin(quiescence, cleanupWaitMs(input.lifecycle));\n if (quiescenceResult.status === \"timed_out\") {\n warnCleanupTimeout(\"command_quiescence\", cleanupTarget?.instanceId ?? null);\n }\n\n const providerCleanup = Promise.resolve().then(async () => {\n if (!cleanupTarget) {\n // A provider create that rejects before onSandboxCreated leaves no box\n // pointer to terminate. Roll back only our exact warming epoch so the\n // next verification does not wait for the 20-minute death reaper. If a\n // non-abortable create returns after this transition, its callback is\n // fenced and the runtime's create-failure path terminates that box.\n if (ownsWarmingEpoch && expectedEpoch !== null) {\n await dependencies.failWarming(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n expectedEpoch,\n });\n }\n return true;\n }\n return await terminateAndClear(cleanupTarget);\n });\n void providerCleanup.catch(() => undefined);\n const providerSettlement = await settleWithin(\n Promise.allSettled([providerCleanup]),\n cleanupWaitMs(input.lifecycle),\n );\n if (providerSettlement.status === \"timed_out\") {\n warnCleanupTimeout(\"terminate_and_clear\", cleanupTarget?.instanceId ?? null);\n } else if (providerSettlement.value[0]?.status === \"rejected\") {\n warnCleanupFailure(\n \"terminate_and_clear\",\n cleanupTarget?.instanceId ?? null,\n providerSettlement.value[0].reason,\n );\n }\n\n // Release is independent from provider/DB cleanup. A failed direct\n // termination therefore leaves the exact pointer intact and immediately\n // makes the zero-holder lease eligible for the normal drain/reaper path.\n if (acquired) {\n const release = Promise.resolve().then(() =>\n dependencies.releaseHolder(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n kind: \"turn\",\n holderId,\n idleGraceMs: RIG_VERIFICATION_RELEASE_GRACE_MS,\n }),\n );\n void release.catch(() => undefined);\n const released = await settleWithin(\n Promise.allSettled([release]),\n cleanupWaitMs(input.lifecycle),\n );\n if (released.status === \"timed_out\") {\n warnCleanupTimeout(\"release_holder\", cleanupTarget?.instanceId ?? null);\n } else if (released.value[0]?.status === \"rejected\") {\n warnCleanupFailure(\n \"release_holder\",\n cleanupTarget?.instanceId ?? null,\n released.value[0].reason,\n );\n }\n }\n // Cancellation may be delivered by a heartbeat while finally is already\n // draining. WAIT_CANCELLATION_COMPLETED must observe cancellation only\n // after cleanup, but it must not turn that late cancellation into success.\n throwIfAborted(signal);\n }\n}\n\nasync function runCommand(\n session: TurnSandboxCommandSession,\n command: string,\n timeoutMs: number,\n commandRunner: SandboxLifecycleCommandRunner,\n): Promise<CommandResult> {\n const args = {\n cmd: command,\n workdir: \"/workspace\",\n runAs: \"root\",\n yieldTimeMs: timeoutMs,\n maxOutputTokens: 40_000,\n };\n const result = await commandRunner(session, args);\n return {\n exitCode: sandboxCommandExitCode(result),\n output: sandboxCommandOutput(result),\n };\n}\n\nasync function runRigChecks(\n session: TurnSandboxCommandSession,\n checks: readonly RigCheck[],\n timeoutMs: number,\n commandRunner: SandboxLifecycleCommandRunner,\n): Promise<RigPlatformCheckResult[]> {\n const results: RigPlatformCheckResult[] = [];\n for (const check of checks) {\n results.push({\n name: check.name,\n command: check.command,\n ...(await runCommand(session, check.command, timeoutMs, commandRunner)),\n });\n }\n return results;\n}\n\nfunction setupAppendCommand(change: RigChange): string | null {\n if (change.kind !== \"setup_append\") {\n return null;\n }\n const command = (change.payload as { command?: unknown }).command;\n return typeof command === \"string\" ? command : null;\n}\n\nfunction candidateVersionForChange(baseVersion: RigVersion, change: RigChange): RigVersion {\n if (change.kind !== \"definition_edit\") {\n return { ...baseVersion, image: null, providerImages: {} };\n }\n const payload = change.payload as {\n setupScript?: unknown;\n checks?: unknown;\n credentialHooks?: unknown;\n defaultVariableSetIds?: unknown;\n changelog?: unknown;\n };\n return {\n ...baseVersion,\n image: null,\n setupScript:\n payload.setupScript === undefined\n ? baseVersion.setupScript\n : (payload.setupScript as string | null),\n checks: Array.isArray(payload.checks)\n ? (payload.checks as RigVersion[\"checks\"])\n : baseVersion.checks,\n credentialHooks: Array.isArray(payload.credentialHooks)\n ? (payload.credentialHooks as string[])\n : baseVersion.credentialHooks,\n defaultVariableSetIds: Array.isArray(payload.defaultVariableSetIds)\n ? (payload.defaultVariableSetIds as string[])\n : baseVersion.defaultVariableSetIds,\n changelog: typeof payload.changelog === \"string\" ? payload.changelog : baseVersion.changelog,\n providerImages: {},\n };\n}\n\nfunction providerImageDefinitionForChange(\n baseVersion: RigVersion,\n change: RigChange,\n candidateVersion: RigVersion,\n): RigProviderImageDefinition {\n if (change.kind !== \"setup_append\") return candidateVersion;\n const command = setupAppendCommand(change);\n return {\n setupScript: command\n ? appendRigSetupCommand(baseVersion.setupScript, command)\n : baseVersion.setupScript,\n checks: baseVersion.checks,\n credentialHooks: baseVersion.credentialHooks,\n defaultVariableSetIds: baseVersion.defaultVariableSetIds,\n };\n}\n\nexport function rigProviderImageContentMarkerCommand(\n contentHash: string,\n markerRoot = \"/var/opengeni\",\n): string {\n const { marker, normalizedRoot } = rigProviderImageContentMarker(contentHash, markerRoot);\n return `mkdir -p '${normalizedRoot}' && touch '${marker}'`;\n}\n\nfunction rigProviderImageContentMarker(\n contentHash: string,\n markerRoot = \"/var/opengeni\",\n): { marker: string; normalizedRoot: string } {\n if (!/^sha256:[0-9a-f]{64}$/u.test(contentHash)) {\n throw new Error(\n \"Sandbox Environment provider image content marker requires a canonical SHA-256 value\",\n );\n }\n if (!/^\\/[A-Za-z0-9._/-]+$/u.test(markerRoot)) {\n throw new Error(\"Sandbox Environment provider image marker root must be a safe absolute path\");\n }\n const normalizedRoot = markerRoot.replace(/\\/+$/u, \"\") || \"/\";\n const marker = `${normalizedRoot === \"/\" ? \"\" : normalizedRoot}/rig-setup-content-${contentHash.slice(\"sha256:\".length)}.done`;\n return { marker, normalizedRoot };\n}\n\nexport type RigProviderImageColdBootDependencies = {\n runOwnedSandbox: typeof runWithOwnedRigVerificationSandbox;\n now: () => Date;\n};\n\nconst defaultRigProviderImageColdBootDependencies: RigProviderImageColdBootDependencies = {\n runOwnedSandbox: runWithOwnedRigVerificationSandbox,\n now: () => new Date(),\n};\n\n/** Prove a provider image from a second clean sandbox before runtime selection. */\nexport async function verifyRigProviderImageColdBoot(\n input: {\n settings: ControlActivityServices[\"settings\"];\n db: Database;\n observability: ControlActivityServices[\"observability\"];\n accountId: string;\n workspaceId: string;\n buildRequestId: string;\n rigVersionId: string;\n sessionIdPrefix: string;\n imageId: string;\n contentHash: string;\n checks: RigProviderImageDefinition[\"checks\"];\n lifecycle: RigVerificationActivityLifecycle;\n },\n dependencies: RigProviderImageColdBootDependencies = defaultRigProviderImageColdBootDependencies,\n): Promise<string> {\n const { marker } = rigProviderImageContentMarker(input.contentHash);\n await dependencies.runOwnedSandbox(\n {\n settings: {\n ...input.settings,\n modalImageId: input.imageId,\n // The full-machine provider image is the immutable rig base. Any future\n // workspace recovery must layer /workspace onto it, never replace it.\n modalWorkspacePersistence: \"snapshot_directory\",\n },\n db: input.db,\n observability: input.observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.buildRequestId,\n rigVersionId: input.rigVersionId,\n sessionIdPrefix: input.sessionIdPrefix,\n lifecycle: input.lifecycle,\n },\n async (established, runContext) => {\n const markerResult = await runCommand(\n established.session as TurnSandboxCommandSession,\n `test -f '${marker}'`,\n input.settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n );\n if (markerResult.exitCode !== 0) {\n throw new Error(\n \"built provider image is missing its exact sandbox environment-content marker\",\n );\n }\n for (const check of rigPlatformChecksForSettings(input.settings)) {\n const result = await runCommand(\n established.session as TurnSandboxCommandSession,\n check.command,\n input.settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n );\n if (result.exitCode !== 0) {\n throw new Error(\n `built provider image failed mandatory platform check ${JSON.stringify(check.name)}: ${result.output.slice(-2000)}`,\n );\n }\n }\n for (const check of input.checks) {\n const result = await runCommand(\n established.session as TurnSandboxCommandSession,\n check.command,\n input.settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n );\n if (result.exitCode !== 0) {\n throw new Error(\n `built provider image failed check ${JSON.stringify(check.name)}: ${result.output.slice(-2000)}`,\n );\n }\n }\n },\n );\n return dependencies.now().toISOString();\n}\n\nexport async function buildVerifiedRigProviderImage(input: {\n settings: ControlActivityServices[\"settings\"];\n db: Database;\n observability: ControlActivityServices[\"observability\"];\n accountId: string;\n workspaceId: string;\n existingVersionId?: string;\n definition: RigProviderImageDefinition;\n target: { kind: \"change\" | \"version\"; id: string };\n established: EstablishedSandboxSession;\n ownership: RigVerificationSandboxRunContext[\"ownership\"];\n lifecycle: RigVerificationActivityLifecycle;\n signal: AbortSignal;\n}): Promise<RigProviderImage> {\n const backend = input.settings.sandboxBackend as SandboxBackend;\n const providerSupportsBuild = providerSupportsImmutableImageBuild(backend);\n const sourceImage = rigProviderImageSourceImage(input.settings, backend);\n const contentHash = rigProviderImageContentHash({\n backend,\n sourceImage,\n definition: input.definition,\n });\n const startedAt = new Date().toISOString();\n let building: RigProviderImage = {\n backend,\n provider: backend,\n status: \"building\",\n contentHash,\n setupHash: rigProviderImageSetupHash(input.definition),\n sourceImage,\n buildRequestId: rigProviderImageBuildRequestId({\n targetId: input.target.id,\n backend,\n contentHash,\n }),\n imageId: null,\n imageDigest: null,\n artifactId: null,\n providerBindingKeyHash: null,\n provenance: {\n kind: \"rig_verification\",\n targetKind: input.target.kind,\n targetId: input.target.id,\n },\n startedAt,\n finishedAt: null,\n error: null,\n };\n\n if (input.existingVersionId) {\n const claim = await claimRigVersionProviderImageBuild(input.db, {\n workspaceId: input.workspaceId,\n versionId: input.existingVersionId,\n image: building,\n staleAfterMs: RIG_VERIFICATION_OWNER_TTL_MS,\n retryUnsupported: providerSupportsBuild,\n });\n if (\n claim.status === \"ready\" ||\n claim.status === \"in_progress\" ||\n claim.status === \"unsupported\"\n ) {\n return claim.image;\n }\n if (claim.status === \"conflict\") {\n return {\n ...building,\n status: \"failed\",\n finishedAt: new Date().toISOString(),\n error: {\n code: \"provider_image_content_conflict\",\n message:\n \"this exact sandbox environment version already records a provider image for different effective content; mint and verify a new version\",\n retryable: false,\n },\n };\n }\n building = claim.image;\n }\n\n const finalize = async (image: RigProviderImage): Promise<RigProviderImage> => {\n if (input.existingVersionId) {\n const persisted = await finalizeRigVersionProviderImageBuild(input.db, {\n workspaceId: input.workspaceId,\n versionId: input.existingVersionId,\n image,\n });\n if (!persisted) {\n if (image.artifactId) {\n await markSandboxCheckpointArtifactDeletePending(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: image.artifactId,\n reason: \"rig_provider_image_publication_fenced\",\n }).catch(() => false);\n }\n return {\n ...image,\n status: \"failed\",\n imageId: null,\n imageDigest: null,\n artifactId: null,\n providerBindingKeyHash: null,\n finishedAt: new Date().toISOString(),\n error: {\n code: \"provider_image_publication_fenced\",\n message: \"provider image ownership changed before this build could be published\",\n retryable: true,\n },\n };\n }\n }\n return image;\n };\n\n if (!providerSupportsBuild) {\n return await finalize({\n ...building,\n status: \"unsupported\",\n finishedAt: new Date().toISOString(),\n error: {\n code: \"provider_image_build_unsupported\",\n message: `sandbox backend ${backend} does not support immutable provider image builds`,\n retryable: false,\n },\n });\n }\n\n throwIfAborted(input.signal);\n let builtIdentity: {\n imageId: string;\n providerBindingKey: string;\n } | null = null;\n let artifactId: string | null = null;\n let coldBootValidatedAt: string | null = null;\n try {\n const built = await buildImmutableProviderImage({\n backend,\n settings: input.settings,\n session: input.established.session,\n requestId: building.buildRequestId,\n timeoutMs: input.settings.sandboxSnapshotTimeoutMs,\n });\n if (!built || (!built.imageId && !built.imageDigest)) {\n throw new Error(\"provider image builder returned no immutable image identity\");\n }\n if (backend === \"modal\") {\n if (!built.imageId || !built.providerBindingKey || !built.providerBinding) {\n throw new Error(\"Modal provider image build returned incomplete ownership identity\");\n }\n builtIdentity = {\n imageId: built.imageId,\n providerBindingKey: built.providerBindingKey,\n };\n const archiveBytes = encodeNativeSnapshotRef({\n provider: \"modal_snapshot_filesystem\",\n snapshotId: built.imageId,\n workspacePersistence: \"snapshot_filesystem\",\n });\n const descriptor = describeNativeSnapshotArchive(archiveBytes);\n if (!descriptor) {\n throw new Error(\"Modal provider image build returned an invalid snapshot identity\");\n }\n const artifact = await registerSandboxCheckpointArtifact(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.target.id,\n sourceLeaseId: input.ownership.leaseId,\n sourceLeaseEpoch: input.ownership.leaseEpoch,\n sourceInstanceId: input.ownership.instanceId,\n sourceWorkspaceGeneration: input.ownership.workspaceGeneration,\n providerBindingKey: built.providerBindingKey,\n providerBinding: built.providerBinding,\n workspaceArchive: Buffer.from(archiveBytes).toString(\"base64\"),\n workspaceArchiveMeta: descriptor,\n registrationIdentity: \"provider_object\",\n });\n artifactId = artifact.id;\n\n // A snapshot receipt is not proof that the artifact can cold-start. Boot\n // a second, independently owned sandbox from the exact image before it\n // can become runtime-selectable.\n coldBootValidatedAt = await verifyRigProviderImageColdBoot({\n settings: input.settings,\n db: input.db,\n observability: input.observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n buildRequestId: building.buildRequestId,\n rigVersionId: input.target.id,\n sessionIdPrefix: `rig-provider-image-${input.target.id}`,\n imageId: built.imageId,\n contentHash,\n checks: input.definition.checks,\n lifecycle: input.lifecycle,\n });\n }\n if (!coldBootValidatedAt) {\n throw new Error(`${backend} provider image build has no independent cold-boot validator`);\n }\n if (input.signal.aborted) {\n if (artifactId) {\n await markSandboxCheckpointArtifactDeletePending(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId,\n reason: \"rig_provider_image_build_cancelled\",\n }).catch(() => false);\n }\n throw abortReason(input.signal);\n }\n return await finalize({\n ...building,\n provider: built.provider,\n status: \"ready\",\n imageId: built.imageId,\n imageDigest: built.imageDigest,\n artifactId,\n providerBindingKeyHash: built.providerBindingKey\n ? rigProviderImageProviderBindingKeyHash(built.providerBindingKey)\n : null,\n coldBootValidation: {\n version: 1,\n checkedAt: coldBootValidatedAt,\n },\n finishedAt: new Date().toISOString(),\n error: null,\n });\n } catch (error) {\n if (input.signal.aborted) throw abortReason(input.signal);\n if (artifactId) {\n await markSandboxCheckpointArtifactDeletePending(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId,\n reason: \"rig_provider_image_build_failed\",\n }).catch(() => false);\n } else if (\n backend === \"modal\" &&\n builtIdentity &&\n !(error instanceof SandboxCheckpointArtifactRegistrationConflictError)\n ) {\n await deleteModalCheckpointSnapshot(\n input.settings,\n builtIdentity.providerBindingKey,\n builtIdentity.imageId,\n ).catch(() => \"not_found\" as const);\n }\n const message = (error instanceof Error ? error.message : String(error)).slice(0, 2000);\n return await finalize({\n ...building,\n status: \"failed\",\n artifactId: null,\n finishedAt: new Date().toISOString(),\n error: {\n code: \"provider_image_build_failed\",\n message: message || \"provider image build failed\",\n retryable: true,\n },\n });\n }\n}\n\nexport function settingsForRigVerification(\n settings: ControlActivityServices[\"settings\"],\n rigImage: string | null,\n): ControlActivityServices[\"settings\"] {\n // Rig verification must prove setup and provider-image materialization on\n // the deployment-owned platform base. Historical Rig image values are ignored.\n void rigImage;\n return settings;\n}\n\nasync function loadChangeTarget(\n db: Database,\n workspaceId: string,\n changeId: string,\n): Promise<{ rig: Rig; baseVersion: RigVersion; change: RigChange }> {\n const change = await getRigChange(db, workspaceId, changeId);\n if (!change) {\n throw new Error(`Sandbox Environment change not found: ${changeId}`);\n }\n const rig = await getRig(db, workspaceId, change.rigId);\n if (!rig) {\n throw new Error(`Sandbox Environment not found for change: ${change.rigId}`);\n }\n if (!change.baseVersionId) {\n throw new Error(`Sandbox Environment change ${change.id} has no base version`);\n }\n const baseVersion = await getRigVersionById(db, workspaceId, change.baseVersionId);\n if (!baseVersion || baseVersion.rigId !== rig.id) {\n throw new Error(`Base sandbox environment version not found: ${change.baseVersionId}`);\n }\n return { rig, baseVersion, change };\n}\n\nasync function loadVersionTarget(\n db: Database,\n workspaceId: string,\n versionId: string,\n): Promise<{ rig: Rig; version: RigVersion }> {\n const version = await getRigVersionById(db, workspaceId, versionId);\n if (!version) {\n throw new Error(`Sandbox Environment version not found: ${versionId}`);\n }\n const rig = await getRig(db, workspaceId, version.rigId);\n if (!rig) {\n throw new Error(`Sandbox Environment not found for version: ${version.rigId}`);\n }\n return { rig, version };\n}\n\nasync function withRigVerificationActivityLifecycle<T>(\n run: (lifecycle: RigVerificationActivityLifecycle) => Promise<T>,\n): Promise<T> {\n // Context.current() and the immediate heartbeat happen before lazy service\n // construction, so Temporal can deliver cancellation even while the worker\n // is opening its first database/provider dependencies.\n const lifecycle = createRigVerificationActivityLifecycle();\n try {\n throwIfAborted(lifecycle.signal);\n return await run(lifecycle);\n } finally {\n lifecycle.dispose();\n }\n}\n\nexport function createRigVerificationActivities(services: () => Promise<ControlActivityServices>) {\n return {\n verifyRigChange: (input: { workspaceId: string; changeId: string }) =>\n withRigVerificationActivityLifecycle(async (lifecycle) => {\n const { settings, db, observability } = await services();\n throwIfAborted(lifecycle.signal);\n const { rig, baseVersion, change } = await loadChangeTarget(\n db,\n input.workspaceId,\n input.changeId,\n );\n const grant = systemGrant(rig);\n const startedAt = new Date().toISOString();\n await beginRigChangeVerificationAttempt(db, input.workspaceId, change.id, {\n startedAt,\n allowAlreadyVerifying: true,\n });\n await recordRigAuditEvent(db, {\n grant,\n action: \"rig.verification.started\",\n rigId: rig.id,\n metadata: { changeId: change.id },\n });\n\n const verification: Record<string, unknown> = { startedAt, checkResults: [] };\n try {\n const candidateVersion = candidateVersionForChange(baseVersion, change);\n const providerImageDefinition = providerImageDefinitionForChange(\n baseVersion,\n change,\n candidateVersion,\n );\n const runSettings = settingsForRigVerification(settings, candidateVersion.image);\n const providerImageContentHash = rigProviderImageContentHash({\n backend: runSettings.sandboxBackend,\n sourceImage: rigProviderImageSourceImage(runSettings, runSettings.sandboxBackend),\n definition: providerImageDefinition,\n });\n return await runWithOwnedRigVerificationSandbox(\n {\n settings: runSettings,\n db,\n observability,\n accountId: rig.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: change.id,\n rigVersionId: candidateVersion.id,\n sessionIdPrefix: `rig-verification-${change.id}`,\n lifecycle,\n },\n async (established, runContext) => {\n if ((candidateVersion.setupScript ?? \"\").trim()) {\n await runRigSetupHook(established.session as never, {\n environment: {},\n runAs: \"root\",\n commandRunner: runContext.commandRunner,\n rigSetup: {\n rigId: rig.id,\n rigName: rig.name,\n versionId: candidateVersion.id,\n script: candidateVersion.setupScript ?? \"\",\n timeoutMs: settings.rigSetupTimeoutMs,\n contentHash: providerImageContentHash,\n },\n });\n verification.setupResult = { exitCode: 0, output: \"\" };\n }\n const command = setupAppendCommand(change);\n if (command) {\n const commandResult = await runCommand(\n established.session as TurnSandboxCommandSession,\n command,\n settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n );\n verification.commandResult = commandResult;\n if (commandResult.exitCode !== 0) {\n verification.finishedAt = new Date().toISOString();\n verification.passed = false;\n const updated = await updateRigChangeStatus(db, input.workspaceId, change.id, {\n status: \"rejected\",\n verification,\n });\n await recordRigAuditEvent(db, {\n grant,\n action: \"rig.verification.failed\",\n rigId: rig.id,\n metadata: { changeId: change.id, status: \"rejected\" },\n });\n await recordRigAuditEvent(db, {\n grant,\n action: \"rig.change.rejected\",\n rigId: rig.id,\n metadata: { changeId: change.id },\n });\n return updated;\n }\n }\n const markerResult = await runCommand(\n established.session as TurnSandboxCommandSession,\n rigProviderImageContentMarkerCommand(providerImageContentHash),\n settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n );\n if (markerResult.exitCode !== 0) {\n throw new Error(\n `Failed to seal sandbox environment provider image content marker: ${markerResult.output.slice(-2000)}`,\n );\n }\n const platformCheckResults = await runRigChecks(\n established.session as TurnSandboxCommandSession,\n rigPlatformChecksForSettings(runSettings),\n settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n );\n verification.platformCheckResults = platformCheckResults;\n const checkResults = await runRigChecks(\n established.session as TurnSandboxCommandSession,\n candidateVersion.checks,\n settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n );\n verification.checkResults = checkResults;\n const passed =\n platformCheckResults.every((result) => result.exitCode === 0) &&\n checkResults.every((result) => result.exitCode === 0);\n if (passed) {\n verification.providerImage = await buildVerifiedRigProviderImage({\n settings: runSettings,\n db,\n observability,\n accountId: rig.accountId,\n workspaceId: input.workspaceId,\n definition: providerImageDefinition,\n target: { kind: \"change\", id: change.id },\n established,\n ownership: runContext.ownership,\n lifecycle,\n signal: runContext.signal,\n });\n }\n verification.finishedAt = new Date().toISOString();\n verification.passed = passed;\n const classified = classifyRigVerificationOutcome({ kind: change.kind, passed });\n if (classified.action === \"auto_promote\") {\n // Keep the change `verifying` (NOT `proposed`) across the write→promote\n // gap: promoteSetupAppendChange accepts `verifying`, and leaving it\n // `verifying` keeps beginRigChangeVerificationAttempt blocking a\n // concurrent /verify — resetting to `proposed` would reopen that race\n // (a second run could reject a change whose first verification passed).\n await updateRigChangeStatus(db, input.workspaceId, change.id, {\n status: \"verifying\",\n verification,\n });\n const { change: merged } = await promoteSetupAppendChange({ db }, grant, rig, {\n ...change,\n verification,\n });\n await recordRigAuditEvent(db, {\n grant,\n action: \"rig.verification.passed\",\n rigId: rig.id,\n metadata: { changeId: change.id },\n });\n return merged;\n }\n const updated = await updateRigChangeStatus(db, input.workspaceId, change.id, {\n status: classified.status,\n verification,\n });\n await recordRigAuditEvent(db, {\n grant,\n action: passed ? \"rig.verification.passed\" : \"rig.verification.failed\",\n rigId: rig.id,\n metadata: { changeId: change.id, status: classified.status },\n });\n if (!passed) {\n await recordRigAuditEvent(db, {\n grant,\n action: \"rig.change.rejected\",\n rigId: rig.id,\n metadata: { changeId: change.id },\n });\n }\n return updated;\n },\n );\n } catch (error) {\n verification.finishedAt = new Date().toISOString();\n verification.passed = false;\n verification.error = error instanceof Error ? error.message : String(error);\n const updated = await updateRigChangeStatus(db, input.workspaceId, change.id, {\n status: \"failed\",\n verification,\n });\n await recordRigAuditEvent(db, {\n grant,\n action: \"rig.verification.failed\",\n rigId: rig.id,\n metadata: { changeId: change.id, status: \"failed\" },\n });\n await recordRigAuditEvent(db, {\n grant,\n action: \"rig.change.failed\",\n rigId: rig.id,\n metadata: { changeId: change.id },\n });\n if (lifecycle.signal.aborted) throw abortReason(lifecycle.signal);\n return updated;\n }\n }),\n\n verifyRigVersion: (input: { workspaceId: string; versionId: string }) =>\n withRigVerificationActivityLifecycle(async (lifecycle) => {\n const { settings, db, observability } = await services();\n throwIfAborted(lifecycle.signal);\n const { rig, version } = await loadVersionTarget(db, input.workspaceId, input.versionId);\n const grant = systemGrant(rig);\n const startedAt = new Date().toISOString();\n await recordRigAuditEvent(db, {\n grant,\n action: \"rig.verification.started\",\n rigId: rig.id,\n metadata: { versionId: version.id },\n });\n try {\n const runSettings = settingsForRigVerification(settings, version.image);\n const providerImageContentHash = rigProviderImageContentHash({\n backend: runSettings.sandboxBackend,\n sourceImage: rigProviderImageSourceImage(runSettings, runSettings.sandboxBackend),\n definition: version,\n });\n return await runWithOwnedRigVerificationSandbox(\n {\n settings: runSettings,\n db,\n observability,\n accountId: rig.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: version.id,\n rigVersionId: version.id,\n sessionIdPrefix: `rig-version-verification-${version.id}`,\n lifecycle,\n },\n async (established, runContext) => {\n if ((version.setupScript ?? \"\").trim()) {\n await runRigSetupHook(established.session as never, {\n environment: {},\n runAs: \"root\",\n commandRunner: runContext.commandRunner,\n rigSetup: {\n rigId: rig.id,\n rigName: rig.name,\n versionId: version.id,\n script: version.setupScript ?? \"\",\n timeoutMs: settings.rigSetupTimeoutMs,\n contentHash: providerImageContentHash,\n },\n });\n }\n const markerResult = await runCommand(\n established.session as TurnSandboxCommandSession,\n rigProviderImageContentMarkerCommand(providerImageContentHash),\n settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n );\n if (markerResult.exitCode !== 0) {\n throw new Error(\n `Failed to seal sandbox environment provider image content marker: ${markerResult.output.slice(-2000)}`,\n );\n }\n const platformCheckResults = await runRigChecks(\n established.session as TurnSandboxCommandSession,\n rigPlatformChecksForSettings(runSettings),\n settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n );\n const checkResults = await runRigChecks(\n established.session as TurnSandboxCommandSession,\n version.checks,\n settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n );\n const passed =\n platformCheckResults.every((result) => result.exitCode === 0) &&\n checkResults.every((result) => result.exitCode === 0);\n const providerImage = passed\n ? await buildVerifiedRigProviderImage({\n settings: runSettings,\n db,\n observability,\n accountId: rig.accountId,\n workspaceId: input.workspaceId,\n existingVersionId: version.id,\n definition: version,\n target: { kind: \"version\", id: version.id },\n established,\n ownership: runContext.ownership,\n lifecycle,\n signal: runContext.signal,\n })\n : null;\n await recordRigAuditEvent(db, {\n grant,\n action: passed ? \"rig.verification.passed\" : \"rig.verification.failed\",\n rigId: rig.id,\n metadata: {\n versionId: version.id,\n startedAt,\n finishedAt: new Date().toISOString(),\n passed,\n platformCheckResults,\n checkResults,\n providerImage,\n },\n });\n return {\n versionId: version.id,\n passed,\n platformCheckResults,\n checkResults,\n providerImage,\n };\n },\n );\n } catch (error) {\n // Infra failure (sandbox establish / setup / check exec threw) — record\n // rig.verification.failed so activeVersionHealth reflects the failed\n // re-run instead of staying stale, symmetric to verifyRigChange. Then\n // rethrow so the Temporal activity still surfaces the failure.\n const detail = error instanceof Error ? error.message : String(error);\n await recordRigAuditEvent(db, {\n grant,\n action: \"rig.verification.failed\",\n rigId: rig.id,\n metadata: {\n versionId: version.id,\n startedAt,\n finishedAt: new Date().toISOString(),\n passed: false,\n error: detail,\n },\n });\n throw error;\n }\n }),\n };\n}\n","import {\n databaseFailureCode,\n nestedPostgresSqlState,\n safeDatabaseErrorFacts,\n SandboxWorkspaceMutationFencedError,\n type SandboxRetainedProcess,\n} from \"@opengeni/db\";\nimport type { Observability } from \"@opengeni/observability\";\n\n/** Protected cause locations and schema facts; public logs receive only the diagnostic key. */\nexport function warnRetainedProcessProofFailure(\n observability: Pick<Observability, \"recordFailureDiagnostic\" | \"warn\">,\n error: unknown,\n process: Pick<\n SandboxRetainedProcess,\n \"id\" | \"sessionId\" | \"ownerAttemptId\" | \"ownerTurnId\" | \"reconcileAttempts\"\n >,\n): void {\n let correlationId: string | undefined;\n try {\n const sqlState = nestedPostgresSqlState(error);\n const constraint = safeDatabaseErrorFacts(error).constraint;\n correlationId = observability.recordFailureDiagnostic({\n code:\n error instanceof SandboxWorkspaceMutationFencedError\n ? \"retained_process_fenced\"\n : sqlState\n ? databaseFailureCode(sqlState)\n : \"retained_process_proof_failed\",\n stage: \"sandbox_retained_processes.proof\",\n error,\n processId: process.id,\n sessionId: process.sessionId,\n ...(process.ownerAttemptId ? { attemptId: process.ownerAttemptId } : {}),\n ...(process.ownerTurnId ? { turnId: process.ownerTurnId } : {}),\n attempts: process.reconcileAttempts,\n sqlState,\n ...(constraint ? { constraint } : {}),\n });\n } catch {\n // A diagnostic/export failure must not change reconciliation or release its fence.\n }\n try {\n observability.warn(\"sandbox reaper: retained-process proof checkpoint failed\", {\n ...(correlationId ? { correlationId } : {}),\n });\n } catch {\n // Keep the original failure behavior even when the public sink fails.\n }\n}\n","import type { LeaseSnapshot, SandboxRetainedProcess } from \"@opengeni/db\";\n\n/** Observation backoff must leave the exact provider's rotation window usable.\n * This changes only the next probe time, never cancellation or settlement proof. */\nexport function retainedProcessDeadlineRetryMs(\n process: Pick<\n SandboxRetainedProcess,\n \"leaseId\" | \"leaseEpoch\" | \"providerBackend\" | \"providerInstanceId\" | \"routeTargetId\"\n >,\n lease: Pick<\n LeaseSnapshot,\n \"id\" | \"leaseEpoch\" | \"backend\" | \"instanceId\" | \"providerDeadlineAt\"\n > | null,\n settings: { sandboxRotationLeadMs: number; sandboxLeaseReaperPeriodMs: number },\n retryAfterMs: number,\n now = Date.now(),\n): number {\n if (\n process.providerBackend !== \"modal\" ||\n process.routeTargetId !== null ||\n !lease ||\n lease.id !== process.leaseId ||\n lease.leaseEpoch !== process.leaseEpoch ||\n lease.backend !== process.providerBackend ||\n lease.instanceId !== process.providerInstanceId ||\n !lease.providerDeadlineAt\n )\n return retryAfterMs;\n\n const untilRotation = lease.providerDeadlineAt.getTime() - settings.sandboxRotationLeadMs - now;\n if (!Number.isFinite(untilRotation)) return retryAfterMs;\n return Math.min(\n retryAfterMs,\n Math.max(1_000, settings.sandboxLeaseReaperPeriodMs, untilRotation),\n );\n}\n","// apps/worker/src/activities/sandbox-lease.ts — the sole global lease inventory,\n// GC and cost-stop activity set (P1.3 / OD-3).\n//\n// One scheduled workflow inventories at most the DB reaper's fair 500-row batch,\n// then starts one durable child per exact (workspace, group, epoch). Each child\n// claims, snapshots and terminates only its own provider box. Temporal's control\n// worker bounds real provider concurrency; a slow or dead provider cannot hold\n// the global scan or any sibling drain. Activity heartbeats make worker loss\n// visible promptly, while the DB capture id remains the authoritative teardown\n// fence through provider termination and the final draining->cold commit.\n//\n// The legacy `reapSandboxLeases` composite remains only as a direct/embedded test\n// harness and executes admitted drains concurrently. There is no per-session\n// timer, viewer activity, owner task queue, or provider-specific lifecycle path\n// in the normal drain state machine.\nimport { warnDrainSnapshotFailure } from \"../sandbox-snapshot-diagnostics\";\nimport { warnRetainedProcessProofFailure } from \"../retained-process-diagnostics\";\nimport { retainedProcessDeadlineRetryMs } from \"../retained-process-retry\";\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { requestRetainedProcessDeadlineCancellation } from \"@opengeni/db/retained-provider-commands\";\nimport type { ProviderCommandPersistence, ProviderCommandSession } from \"@opengeni/runtime\";\nimport { Context } from \"@temporalio/activity\";\nimport { OpLostReason, OpState, type OpStatus } from \"@opengeni/agent-proto\";\nimport {\n accrueWarmSeconds,\n retainedProviderCommandPersistence,\n adoptLegacyModalCheckpointArtifact,\n confirmDrainCold,\n appendSessionEventToSandboxGroup,\n bindRetainedProcessProviderIdentity,\n claimWorkspaceArchiveCapture,\n releaseWorkspaceArchiveCapture,\n claimSandboxCheckpointArtifactsForGc,\n claimTerminalRetainedProcesses,\n countActiveRetainedProcessesByOwnerState,\n countSandboxCheckpointArtifactsByState,\n countExpiredDrainingSandboxLeases,\n countQueuedTurns,\n countSandboxLeasesByLiveness,\n deferRetainedProcessReconciliation,\n forceDrainOverLimitViewerOnlyBoxes,\n listCreditBalancesByAccount,\n countActiveUsers,\n readCreditGrantTotals,\n readVerifiedSignupTrialSwitch,\n listLegacyModalCheckpointSlots,\n listLiveModalSandboxLeaseAttributions,\n listPendingModalProviderCreates,\n claimModalProviderCreateRecovery,\n recordRecoveredModalProviderCreate,\n markWarmBillingStopCutoff,\n listMeterableWarmLeases,\n listSandboxViewerForceDrainWorkspaceIds,\n markSandboxCheckpointArtifactDeletePending,\n persistDrainSnapshot,\n pruneDeletedSandboxCheckpointArtifacts,\n registerSandboxCheckpointArtifact,\n recordRetainedProcessReconciliationProof,\n replaceWorkspaceArchiveCaptureAfterProof,\n readLease,\n readWorkspaceArchiveCapturePreflight,\n reapExpiredSessionListSnapshots,\n reapStaleLeaseHoldersGlobal,\n requestDueSandboxRotationsGlobal,\n readSandboxRotationBacklog,\n readRecentSandboxRecoveryObservations,\n workspaceArchiveCaptureDeadlineElapsed,\n retainedProcessReconciliationProof,\n retainedProcessSettlementIdentity,\n settleClaimedConnectedMachineBackgroundCommand,\n settleSandboxCheckpointArtifactGc,\n rlsContextForWorkspace,\n settleRetainedProcess,\n type MeterableWarmLease,\n type ReapDrainable,\n type RetainedProcessProviderProof,\n type SandboxRetainedProcess,\n type LeaseSnapshot,\n} from \"@opengeni/db\";\nimport {\n claimConnectedMachineSessionBackgroundCommands,\n deferConnectedMachineBackgroundCommandReconciliation,\n recordConnectedMachineBackgroundCommandProof,\n type ConnectedMachineBackgroundCommandClaim,\n type ConnectedMachineBackgroundCommandProof,\n} from \"@opengeni/db/session-background-commands\";\nimport { sandboxWarmRateMicrosPerSecond } from \"@opengeni/config\";\nimport { appendSessionCommandOutput } from \"@opengeni/db/session-command-output\";\nimport { captureConnectedCommandOutput } from \"../sandbox-routing\";\nimport { sandboxLeaseTelemetryKey } from \"@opengeni/observability\";\nimport {\n // Normal drain teardown builds the client and resumes the envelope directly:\n // a live box gets its /workspace persisted before termination, while a gone\n // box is typed as provider loss. Stale capture reconciliation separately uses\n // establishSandboxSessionFromEnvelope in strict resume-only mode so it can\n // reuse the runtime's provider-ready proof without ever cold-restoring.\n captureWorkspaceArchiveForStorage,\n disposeWorkspaceArchive,\n type VerifiedWorkspaceArchivePayload,\n type VerifiedHostWorkspaceArchive,\n cancelSelfhostedOp,\n assertConsistentSandboxProviderIdentity,\n createSandboxClientForBackend,\n deleteModalCheckpointSnapshot,\n deserializeSandboxSessionStateEnvelope,\n establishSandboxSessionFromEnvelope,\n inspectModalSandboxLifecycle,\n isExecSessionLostBanner,\n isProviderSandboxNotFoundError,\n isProviderSandboxGoneDuringRoutedOperation,\n NatsControlRpc,\n NatsOpStreamTransport,\n OpStreamExecClient,\n defaultSelfhostedRetryClock,\n stripExecBanner,\n parseExecBannerExitCode,\n prepareProviderForTeardownAfterCapture,\n providerWorkspaceCapturePolicy,\n resolveModalCheckpointProviderBindingForLiveSandbox,\n resolveModalCheckpointProviderBinding,\n findModalProviderCreateReceipt,\n resolveModalCheckpointProviderBindingForSession,\n querySelfhostedOp,\n resumeExactSandboxSession,\n sandboxProviderContinuityForState,\n sandboxBackendForSdkBackendId,\n sandboxProviderInstanceIdFromEnvelope,\n sandboxCommandExitCode,\n sandboxCommandStillRunning,\n SelfhostedControlError,\n subjectFor,\n sweepModalOrphanSandboxes,\n terminateManagedSandboxSession,\n terminateModalSandboxById,\n verifySandboxExecReadiness,\n type ModalOrphanSweepTermination,\n type ModalCheckpointProviderBinding,\n type ProviderWorkspaceCapturePolicy,\n type WorkspaceArchiveDescriptor,\n type ControlRpc,\n type NatsRequestConnection,\n} from \"@opengeni/runtime/sandbox\";\nimport {\n SANDBOX_REAPER_ACTIVITY_HEARTBEAT_INTERVAL_MS,\n SANDBOX_REAPER_CHILD_DISPATCH_LIMIT,\n type SandboxDrainActivityInput,\n type SandboxLeaseSweepMaintenanceInput,\n} from \"../sandbox-reaper-contract\";\nimport { CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES } from \"../concurrency\";\nimport { assertSandboxDrainInputTiming, sandboxDrainTiming } from \"../sandbox-reaper-timeout\";\nimport type { ControlActivityServices as ActivityServices } from \"./types\";\nimport { reconcilePendingParentSystemUpdates } from \"./parent-wake\";\nimport {\n recordActiveUserGauges,\n recordCreditBalanceGauges,\n recordCreditGrantGauges,\n recordCreditMicros,\n recordExpiredDrainingSandboxLeaseGauges,\n recordOpenSandboxKubernetesInventoryGauges,\n recordRetainedProcessInventoryGauges,\n recordRetainedProcessReconciliation,\n recordSandboxCheckpointArtifactGauges,\n recordSandboxCheckpointArtifactOutcome,\n recordSandboxDeadlineRotationsRequested,\n recordSandboxInventoryProjectionFailure,\n recordSandboxInventoryProjectionSuccess,\n type RetainedProcessReconciliationOutcome,\n type SandboxInventoryProjectionDomain,\n recordSandboxLeaseGauges,\n recordSandboxOrphansTerminated,\n recordSandboxProviderMissingBeforeCapture,\n recordSandboxRecoveryObservationGauges,\n recordSandboxRotationBacklogGauges,\n recordTurnsQueuedGauge,\n recordVerifiedSignupTrialDeploymentFlagGauge,\n recordVerifiedSignupTrialSwitchGauge,\n runtimeMetricsHooksForObservability,\n} from \"../observability-metrics\";\nimport {\n inspectOpenSandboxKubernetesInventory,\n type OpenSandboxKubernetesInventory,\n} from \"../opensandbox-kubernetes-inventory\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport {\n persistWorkspaceArchiveCandidate,\n putVersion1TarArchiveOrInline,\n} from \"../sandbox-archive-storage\";\n\nexport { sandboxLeaseTelemetryKey } from \"@opengeni/observability\";\n\nexport type ReapSandboxLeasesResult = {\n /** Stale viewer holders + warming-death rows the sweep touched is folded into\n * the DB pass; here we report the terminate outcomes. */\n examined: number;\n /** Boxes whose provider terminate fired AND whose lease went cold. */\n terminated: number;\n /** Drainable rows skipped because the CAS no longer held (re-armed / newer\n * epoch / already drained by a concurrent sweep) — provider stop() did NOT\n * fire. */\n skipped: number;\n /** Warm viewer-only leases that accrued warm-seconds this tick (P2.1). */\n metered: number;\n /** Holderless boxes accelerated to draining by the optional warm cap. */\n forceDrained: number;\n /** Provider-side Modal orphan sandboxes terminated by the defensive sweep. */\n modalOrphansTerminated: number;\n};\n\ntype CreateSandboxClientForBackendFn = typeof createSandboxClientForBackend;\n\ntype DrainSandboxClient = {\n backendId: string;\n resume?: (state: unknown) => Promise<unknown>;\n deserializeSessionState?: (state: Record<string, unknown>) => Promise<unknown>;\n delete?: (state: unknown) => Promise<void>;\n};\n\n/**\n * The CAS-write the terminate seam calls to PERSIST the captured /workspace\n * archive onto the lease under the epoch fence, BEFORE the box is terminated\n * (sandbox-file-persistence). The caller (`terminateDrainableBox`) closes over\n * db/accountId/row and delegates to persistDrainSnapshot. Returns:\n * `wrote:false` means the CAS missed (re-armed / newer epoch / vanished). The\n * box is wanted again, so the seam MUST NOT terminate it. Provider-native\n * deletion is owned independently by artifact-ledger GC.\n *\n * Pass null for archiveBase64 to CAS-check WITHOUT writing (re-arm guard for\n * backends with no persistWorkspace — ensures a re-arm during the snapshot window\n * aborts the terminate before client.delete()).\n */\nexport type PersistArchiveFn = (\n archiveBase64: string | VerifiedHostWorkspaceArchive | null,\n archiveMetadata?: WorkspaceArchiveDescriptor,\n providerSession?: unknown,\n providerBinding?: Awaited<\n ReturnType<typeof resolveModalCheckpointProviderBindingForSession>\n > | null,\n) => Promise<{\n wrote: boolean;\n archiveRevision?: string | null;\n}>;\n\nexport type ProviderTerminationOutcome = {\n /** false means an epoch/refcount CAS proved the box was re-armed, so it was\n * deliberately left running and the cold commit must not execute. */\n terminated: boolean;\n /** True only when a definitive provider NotFound proved the cloud box had\n * already vanished before this drain could capture its workspace. */\n providerMissingBeforeCapture: boolean;\n};\n\nexport type DrainCaptureDisposition = \"capture_required\" | \"archive_published\";\n\n/** The provider-terminate seam. Production wires the real resume-by-id ->\n * persistWorkspace -> persist-onto-lease (epoch-fenced) -> snapshot-GC ->\n * provider stop() (`terminateProviderBox`); a unit test injects a spy so the\n * drain/CAS logic is exercised against a real DB without a live provider box.\n * Test seams may return the legacy boolean shorthand. Production returns the\n * typed outcome so the cold commit can distinguish a clean stop from definitive\n * provider disappearance before capture. */\nexport type TerminateBoxFn = (\n settings: ActivityServices[\"settings\"],\n lease: NonNullable<Awaited<ReturnType<typeof readLease>>>,\n observability: ActivityServices[\"observability\"],\n persistArchive: PersistArchiveFn,\n providerCaptureRequestId?: string,\n captureDisposition?: DrainCaptureDisposition,\n capturePolicy?: ProviderWorkspaceCapturePolicy | null,\n diskBackedArchives?: boolean,\n releaseFailedCapture?: () => Promise<void>,\n workspaceId?: string,\n beforeProviderStop?: () => Promise<void>,\n) => Promise<boolean | ProviderTerminationOutcome>;\n\nexport type SweepModalOrphansFn = (\n settings: ActivityServices[\"settings\"],\n db: ActivityServices[\"db\"],\n observability: ActivityServices[\"observability\"],\n) => Promise<number>;\n\nexport type InspectOpenSandboxKubernetesInventoryFn = (input: {\n namespace: string;\n}) => Promise<OpenSandboxKubernetesInventory>;\n\nexport type SandboxLeaseActivityOptions = {\n /** Override the provider terminate (tests spy this; defaults to the real\n * resume-by-id + provider stop()). */\n terminateBox?: TerminateBoxFn;\n /** Override the provider-side Modal orphan sweep (tests spy this; defaults to\n * Modal list+tag comparison when Modal is configured). */\n sweepModalOrphans?: SweepModalOrphansFn;\n /** Only provider discovery is injected; durable recovery remains real. */\n findModalProviderCreateReceipt?: typeof findModalProviderCreateReceipt;\n /** Override the read-only bounded OpenSandbox Kubernetes projection. */\n inspectOpenSandboxKubernetesInventory?: InspectOpenSandboxKubernetesInventoryFn;\n /** Override only the read-only provider process probe. The canonical DB\n * settlement remains real in tests and production. */\n probeRetainedProcess?: RetainedProcessProbeFn;\n /** Observe a historical Modal box after its lease row has advanced to a\n * successor identity. Lifecycle-only; a live box remains ambiguous. */\n inspectHistoricalModalSandbox?: HistoricalModalSandboxLifecycleProbeFn;\n /** Override the read-only exact-instance readiness probe used before the\n * reaper settles blockers for a provider that has definitively vanished. */\n probeDrainableProvider?: DrainableProviderProbeFn;\n};\n\nexport type RetainedProcessProbeResult =\n | { status: \"proved\"; proof: RetainedProcessProviderProof }\n | {\n status: \"binding\";\n providerBindingKey: string;\n providerBinding: ModalCheckpointProviderBinding;\n }\n | {\n status: \"deferred\";\n reason:\n | \"identity_mismatch\"\n | \"resume_state_missing\"\n | \"backend_unsupported\"\n | \"provider_running\"\n | \"provider_unknown\"\n | \"provider_timeout\"\n | \"provider_error\"\n | \"provider_binding_missing\"\n | \"provider_binding_mismatch\"\n | \"process_observation_unavailable\";\n /** A running command whose last read still returned a large backlog. */\n outputBacklog?: boolean;\n };\n\nexport type RetainedProcessProbeFn = (\n settings: ActivityServices[\"settings\"],\n lease: LeaseSnapshot,\n process: SandboxRetainedProcess,\n mode?: \"observe\" | \"cancel\",\n captureOutput?: (\n result: unknown,\n chunkId: string,\n stream?: \"stdout\" | \"stderr\",\n streamFidelity?: \"separate\" | \"merged\",\n ) => Promise<void>,\n providerPersistence?: ProviderCommandPersistence,\n drainBudget?: RetainedProcessDrainBudget,\n) => Promise<RetainedProcessProbeResult>;\n\n/** Shared wall-clock bound on output draining within one reconciliation sweep. */\nexport type RetainedProcessDrainBudget = { until: number };\n\nexport type HistoricalModalSandboxLifecycleProbeFn = typeof inspectModalSandboxLifecycle;\n\nexport type DrainableProviderProbeFn = (\n settings: ActivityServices[\"settings\"],\n lease: LeaseSnapshot,\n) => Promise<\"ready\" | \"missing\">;\n\nexport const RETAINED_PROCESS_RECONCILIATION_LIMIT = 20;\nexport const RETAINED_PROCESS_RECONCILIATION_CLAIM_TTL_MS = 5 * 60_000;\nexport const RETAINED_PROCESS_PROVIDER_PROBE_TIMEOUT_MS = 5_000;\n/** Bounds on reading a command's output backlog: per claim, and across one\n * reconciliation sweep so the reaper activity stays well inside its timeout.\n * Each read returns up to one provider page per stream. */\nexport const RETAINED_PROCESS_OUTPUT_DRAIN_MAX_READS = 8;\nexport const RETAINED_PROCESS_OUTPUT_DRAIN_BUDGET_MS = 10_000;\nexport const RETAINED_PROCESS_OUTPUT_DRAIN_SWEEP_BUDGET_MS = 60_000;\n/** A live process whose read returned at least this much output left a backlog\n * behind it. A server or watcher that only trickles output stays on ordinary\n * backoff; a process the provider reports exited is always read to EOF. */\nexport const RETAINED_PROCESS_OUTPUT_BACKLOG_BYTES = 256 * 1024;\nexport const RETAINED_PROCESS_BINDING_QUARANTINE_AFTER_ATTEMPTS = 5;\nexport const RETAINED_PROCESS_BINDING_QUARANTINE_RETRY_MS = 24 * 60 * 60_000;\nexport const CONNECTED_COMMAND_RECONCILIATION_LIMIT = 20;\nexport const CONNECTED_COMMAND_RECONCILIATION_CLAIM_TTL_MS = 5 * 60_000;\n\nexport class SandboxProviderCaptureTimeoutError extends Error {\n readonly name = \"SandboxProviderCaptureTimeoutError\";\n\n constructor(\n public readonly sandboxGroupId: string,\n public readonly backend: string,\n public readonly timeoutMs: number,\n public readonly leaseEpoch: number,\n public readonly instanceId: string,\n ) {\n super(\n `sandbox ${sandboxGroupId} epoch ${leaseEpoch} ${backend} instance ${instanceId} ` +\n `workspace capture exceeded ${timeoutMs}ms; ` +\n \"the exact durable claim remains fenced while its provider response settles\",\n );\n }\n}\n\nexport async function awaitProviderCaptureWithLatePublication<T>(input: {\n capture: Promise<T>;\n timeoutMs: number;\n timeoutError: SandboxProviderCaptureTimeoutError;\n publishLate: (value: T) => Promise<void>;\n observeLateFailure: (error: unknown) => void;\n observeLatePublicationFailure: (error: unknown) => void;\n}): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const timeoutError = input.timeoutError;\n try {\n return await Promise.race([\n input.capture,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(timeoutError), input.timeoutMs);\n }),\n ]);\n } catch (error) {\n if (error !== timeoutError) throw error;\n // Promise cancellation is not a generic SandboxSession contract. Keep the\n // exact failed activity's result path alive in-process, but permit only the\n // durable archive publication: never provider teardown or a cold commit from\n // an activity Temporal has already rejected. A replaced claim fences this\n // callback; Modal candidates then flow to artifact-ledger GC.\n void input.capture\n .then(input.publishLate, input.observeLateFailure)\n .catch(input.observeLatePublicationFailure);\n throw error;\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nfunction startSandboxReaperHeartbeat(details: Record<string, string | number | null>): () => void {\n let context: Context;\n try {\n context = Context.current();\n } catch {\n // Direct unit/embedded harnesses intentionally run without Temporal.\n return () => undefined;\n }\n const heartbeat = (): void => {\n try {\n context.heartbeat({ ...details, heartbeatAt: new Date().toISOString() });\n } catch {\n // Heartbeat can synchronously surface Temporal cancellation. This timer\n // must never turn that into an uncaught process-level exception while an\n // already-issued provider capture/teardown is settling under its durable\n // DB claim. The activity result/cancellation boundary remains Temporal's;\n // claim recovery remains the database's.\n }\n };\n heartbeat();\n const timer = setInterval(heartbeat, SANDBOX_REAPER_ACTIVITY_HEARTBEAT_INTERVAL_MS);\n if (\"unref\" in timer && typeof timer.unref === \"function\") timer.unref();\n return () => clearInterval(timer);\n}\n\nexport type SandboxLeaseSweepPlan = {\n drainable: ReapDrainable[];\n timeoutClass: SandboxDrainActivityInput[\"timeoutClass\"];\n snapshotTimeoutMs: number;\n captureTimeoutMs: number;\n /** Deadline rotations admitted immediately before inventory, so zero-holder\n * boxes enter the same sweep instead of paying another schedule period. */\n rotationsRequested: number;\n};\n\nexport type SandboxLeaseSweepMaintenanceResult = {\n metered: number;\n forceDrained: number;\n rotationsRequested: number;\n modalOrphansTerminated: number;\n};\n\nexport type SandboxDrainActivityResult = { status: \"terminated\" | \"skipped\" };\n\ntype SandboxDrainCaptureAttempt = {\n operationId: string;\n captureId: string;\n attempt: number;\n /** Durable child input, frozen when the workflow was created. Never\n * re-derive this from a later deployment's config/formula. */\n captureTimeoutMs: number;\n};\n\nclass SandboxDrainRecoveryDeferredError extends Error {\n readonly name = \"SandboxDrainRecoveryDeferredError\";\n}\n\n/** Stable UUID per logical operation + Temporal attempt. Attempt one uses the\n * operation id itself; later attempts are SHA-256-derived UUIDv5-shaped values.\n * This makes the DB receipt idempotent even if an activity delivery is replayed. */\nexport function sandboxDrainCaptureId(operationId: string, attempt: number): string {\n if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(operationId)) {\n throw new Error(\"Sandbox drain operation id is invalid\");\n }\n if (!Number.isSafeInteger(attempt) || attempt <= 0) {\n throw new Error(\"Sandbox drain activity attempt is invalid\");\n }\n if (attempt === 1) return operationId.toLowerCase();\n const bytes = createHash(\"sha256\")\n .update(`opengeni:sandbox-drain:${operationId.toLowerCase()}:${attempt}`)\n .digest()\n .subarray(0, 16);\n bytes[6] = (bytes[6]! & 0x0f) | 0x50;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = bytes.toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction sandboxDrainActivityAttempt(): number {\n try {\n const attempt = Context.current().info.attempt;\n return Number.isSafeInteger(attempt) && attempt > 0 ? attempt : 1;\n } catch {\n return 1;\n }\n}\n\nexport function createSandboxLeaseActivities(\n services: () => Promise<ActivityServices>,\n options: SandboxLeaseActivityOptions = {},\n) {\n const terminateBox: TerminateBoxFn =\n (options.terminateBox\n ? async (...args: Parameters<TerminateBoxFn>) => {\n // The injected test seam represents the stop itself; the real\n // implementation invokes this only after capture has succeeded.\n await args[10]?.();\n return options.terminateBox!(...args);\n }\n : null) ??\n (async (\n settings,\n lease,\n observability,\n persistArchive,\n providerCaptureRequestId,\n captureDisposition,\n capturePolicy,\n diskBackedArchives,\n releaseFailedCapture,\n workspaceId,\n beforeProviderStop,\n ) =>\n await terminateProviderBox(\n settings,\n lease,\n observability,\n persistArchive,\n createSandboxClientForBackend,\n terminateModalSandboxById,\n providerCaptureRequestId,\n captureDisposition,\n capturePolicy,\n diskBackedArchives,\n releaseFailedCapture,\n workspaceId,\n beforeProviderStop,\n ));\n const sweepModalOrphans: SweepModalOrphansFn =\n options.sweepModalOrphans ?? sweepModalOrphansForConfiguredBackend;\n const inspectOpenSandboxInventory =\n options.inspectOpenSandboxKubernetesInventory ?? inspectOpenSandboxKubernetesInventory;\n const probeRetainedProcess = options.probeRetainedProcess ?? probeRetainedProcessAtProvider;\n const probeDrainableProvider = options.probeDrainableProvider ?? probeDrainableProviderReadiness;\n async function prepareSandboxLeaseSweep(): Promise<SandboxLeaseSweepPlan> {\n const stopHeartbeat = startSandboxReaperHeartbeat({ phase: \"prepare\" });\n try {\n const { db, settings, observability } = await services();\n const timing = sandboxDrainTiming(settings);\n const onUnobservableCommandDrainError = (error: unknown) => {\n observability.warn(\"sandbox reaper: unobservable command drain inspection failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n };\n if (!settings.sandboxOwnershipEnabled) {\n // Turns skip leases when the flag is off, but Computer/Browser attach\n // still acquire them. Leaving drainable rows untouched strands Desktop\n // behind rotation_in_progress forever. Inventory and drain those rows;\n // do not request NEW deadline rotations or meter warm time.\n const drainableInventory = await reapStaleLeaseHoldersGlobal(db, {\n onUnobservableCommandDrainError,\n viewerHolderTtlMs: settings.sandboxViewerHolderTtlMs,\n turnHolderTtlMs: settings.sandboxLeaseTtlMs,\n interactionHolderTtlMs: settings.sandboxInteractionHolderTtlMs,\n idleGraceMs: settings.sandboxIdleGraceMs,\n });\n const drainable = drainableInventory.slice(0, SANDBOX_REAPER_CHILD_DISPATCH_LIMIT);\n return {\n drainable,\n timeoutClass: timing.timeoutClass,\n snapshotTimeoutMs: timing.snapshotTimeoutMs,\n captureTimeoutMs: timing.captureTimeoutMs,\n rotationsRequested: 0,\n };\n }\n\n // Admit finite-lifetime rotations immediately before inventory. The DB\n // function is bounded and provider-I/O-free; a due zero-holder box becomes\n // draining there and is therefore dispatched in THIS sweep, eliminating\n // the old extra schedule-period availability gap. Failure is isolated: the\n // inventory must still dispatch every row that was already drainable.\n const rotationsRequested = await requestDueSandboxRotationsGlobal(\n db,\n settings.sandboxRotationLeadMs,\n settings.sandboxRotationBatchSize,\n ).catch((error) => {\n observability.warn(\"sandbox reaper: provider-deadline rotation request failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return 0;\n });\n recordSandboxDeadlineRotationsRequested(observability, rotationsRequested);\n\n // Keep the remaining dispatch-critical path to one bounded DB inventory.\n // Billing, reconciliation, provider-orphan cleanup, artifact GC, and gauges\n // run only after every drainable box has its own durable child.\n const drainableInventory = await reapStaleLeaseHoldersGlobal(db, {\n onUnobservableCommandDrainError,\n viewerHolderTtlMs: settings.sandboxViewerHolderTtlMs,\n // Dead-worker turn holders: a live holder is touched every 10s from the\n // moment it is registered (resumeBoxForTurn's holder-liveness loop covers\n // the whole warmup — waitForWarm/establish/display-stack — and the turn\n // heartbeat covers the run), so NO live path is ever silent for more than\n // one tick. The ordinary warm lease TTL is therefore already a generous\n // dead-worker horizon. Canonical holders whose turn is durably closed are\n // removed immediately by the DB function; no path-duration guess belongs\n // in this lifecycle contract.\n turnHolderTtlMs: settings.sandboxLeaseTtlMs,\n interactionHolderTtlMs: settings.sandboxInteractionHolderTtlMs,\n idleGraceMs: settings.sandboxIdleGraceMs,\n });\n const drainable = drainableInventory.slice(0, SANDBOX_REAPER_CHILD_DISPATCH_LIMIT);\n if (drainableInventory.length > drainable.length) {\n observability.info(\"sandbox reaper: drain inventory continues next sweep\", {\n admitted: drainable.length,\n deferred: drainableInventory.length - drainable.length,\n });\n }\n return {\n drainable,\n timeoutClass: timing.timeoutClass,\n snapshotTimeoutMs: timing.snapshotTimeoutMs,\n captureTimeoutMs: timing.captureTimeoutMs,\n rotationsRequested,\n };\n } finally {\n stopHeartbeat();\n }\n }\n\n async function drainSandboxLease(\n input: SandboxDrainActivityInput,\n ): Promise<SandboxDrainActivityResult> {\n const stopHeartbeat = startSandboxReaperHeartbeat({\n phase: \"drain\",\n workspaceId: input.target.workspaceId,\n sandboxGroupId: input.target.sandboxGroupId,\n leaseEpoch: input.target.leaseEpoch,\n instanceId: input.target.instanceId,\n });\n try {\n const { db, settings, observability, objectStorage } = await services();\n assertSandboxDrainInputTiming(input);\n const drainSettings =\n settings.sandboxSnapshotTimeoutMs === input.snapshotTimeoutMs\n ? settings\n : { ...settings, sandboxSnapshotTimeoutMs: input.snapshotTimeoutMs };\n const row = input.target;\n const activityAttempt = sandboxDrainActivityAttempt();\n const captureAttempt: SandboxDrainCaptureAttempt = {\n operationId: input.operationId,\n captureId: sandboxDrainCaptureId(input.operationId, activityAttempt),\n attempt: activityAttempt,\n captureTimeoutMs: input.captureTimeoutMs,\n };\n try {\n const drainedCold = await terminateDrainableBox(\n db,\n drainSettings,\n row,\n observability,\n terminateBox,\n probeDrainableProvider,\n captureAttempt,\n objectStorage,\n );\n return { status: drainedCold ? \"terminated\" : \"skipped\" };\n } catch (error) {\n const lease = await readLease(db, row.workspaceId, row.sandboxGroupId).catch(() => null);\n const details = {\n sandboxLeaseKey: sandboxLeaseTelemetryKey(row.workspaceId, row.sandboxGroupId),\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n leaseEpoch: row.leaseEpoch,\n backend: lease?.backend ?? \"unknown\",\n instanceId: lease?.instanceId ?? row.instanceId,\n captureId: lease?.archiveCapture?.id ?? null,\n captureOperationId: lease?.archiveCapture?.operationId ?? input.operationId,\n captureAttempt: lease?.archiveCapture?.attempt ?? activityAttempt,\n timeoutClass: input.timeoutClass,\n error: error instanceof Error ? error.message : String(error),\n };\n if (error instanceof SandboxDrainRecoveryDeferredError) {\n observability.info(\"sandbox reaper: per-sandbox recovery deferred safely\", details);\n } else {\n observability.warn(\"sandbox reaper: per-sandbox drain failed\", details);\n }\n throw error;\n }\n } finally {\n stopHeartbeat();\n }\n }\n\n async function maintainSandboxLeaseSweep(\n input: SandboxLeaseSweepMaintenanceInput,\n ): Promise<SandboxLeaseSweepMaintenanceResult> {\n const stopHeartbeat = startSandboxReaperHeartbeat({\n phase: \"maintain\",\n examined: input.examined,\n started: input.started,\n });\n try {\n const service = await services();\n const { db, settings, observability } = service;\n const parentUpdates = await reconcilePendingParentSystemUpdates(service, 100).catch(\n (error) => {\n observability.warn(\"system-update outbox reconciliation failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return { claimed: 0, delivered: 0, failed: 1 };\n },\n );\n const expiredSessionListSnapshots = await reapExpiredSessionListSnapshots(db, 500).catch(\n (error) => {\n observability.warn(\"session-list snapshot reconciliation failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return 0;\n },\n );\n if (expiredSessionListSnapshots > 0) {\n observability.info(\"expired session-list snapshots reaped\", {\n deleted: expiredSessionListSnapshots,\n });\n }\n if (parentUpdates.claimed > 0) {\n observability.info(\"system-update outbox reconciled\", parentUpdates);\n }\n\n let metered = 0;\n let forceDrained = 0;\n const rotationsRequested = input.rotationsRequested;\n let modalOrphansTerminated = 0;\n\n // Connected Machine commands are not managed-sandbox lease state. Their\n // immutable launch locators must reconcile even when managed ownership is\n // disabled, otherwise an exact runner exit/loss proof can remain stranded.\n await reconcileConnectedMachineBackgroundCommands(db, settings, observability, service.bus);\n\n // Disabling new lease ownership cannot strand a previously dispatched\n // operation. This only attributes a positive receipt; normal draining\n // already runs in both ownership modes.\n try {\n await reconcileModalProviderCreates(\n db,\n settings,\n observability,\n options.findModalProviderCreateReceipt,\n );\n } catch (error) {\n observability.warn(\"sandbox reaper: Modal create recovery inventory failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n\n if (!settings.sandboxOwnershipEnabled) {\n // Inventory remains useful while provider ownership is intentionally\n // disabled, and this scheduled activity is its single projection owner.\n await refreshQueueLeaseAndCreditGauges(\n db,\n settings,\n observability,\n inspectOpenSandboxInventory,\n );\n return {\n metered,\n forceDrained,\n rotationsRequested,\n modalOrphansTerminated,\n };\n }\n\n // Warm metering and cost-stop run after current drain children launch.\n // Freshly force-drained billing rows are admission-fenced immediately and\n // receive their own provider child on the next bounded schedule tick.\n const meterResult = await accrueWarmTick(db, settings, observability);\n metered = meterResult.accrued;\n const forceDrainWorkspaceIds = new Set<string>();\n if (\n settings.sandboxWarmBillingMode === \"credits\" ||\n settings.sandboxMaxWarmSecondsPerWorkspace > 0\n ) {\n for (const workspaceId of meterResult.workspaceIds) {\n forceDrainWorkspaceIds.add(workspaceId);\n }\n }\n try {\n for (const workspaceId of await listSandboxViewerForceDrainWorkspaceIds(db)) {\n forceDrainWorkspaceIds.add(workspaceId);\n }\n } catch (error) {\n observability.warn(\"sandbox reaper: viewer force-drain workspace read failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n forceDrained = await forceDrainOverLimitWorkspaces(\n db,\n settings,\n forceDrainWorkspaceIds,\n observability,\n );\n\n // Terminal-owner process reconciliation is ancillary to lease dispatch.\n // Exact provider proof is durably checkpointed before settlement; every\n // ambiguous outcome remains claimed/deferred for another sweep.\n await reconcileTerminalRetainedProcesses(\n db,\n settings,\n observability,\n probeRetainedProcess,\n options.inspectHistoricalModalSandbox ?? inspectModalSandboxLifecycle,\n service.bus,\n );\n\n try {\n modalOrphansTerminated = await sweepModalOrphans(settings, db, observability);\n recordSandboxOrphansTerminated(observability, modalOrphansTerminated);\n } catch (error) {\n observability.warn(\"sandbox reaper: Modal orphan sweep failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n\n const checkpointGc = await gcSandboxCheckpointArtifacts(db, settings, observability).catch(\n (error) => {\n observability.warn(\"sandbox reaper: checkpoint artifact GC failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return { claimed: 0, deleted: 0, failed: 0 };\n },\n );\n\n await refreshQueueLeaseAndCreditGauges(\n db,\n settings,\n observability,\n inspectOpenSandboxInventory,\n );\n\n if (\n input.examined > 0 ||\n metered > 0 ||\n forceDrained > 0 ||\n modalOrphansTerminated > 0 ||\n rotationsRequested > 0 ||\n checkpointGc.claimed > 0\n ) {\n observability.info(\"sandbox reaper dispatched\", {\n drainable: input.examined,\n childrenStarted: input.started,\n childrenAlreadyRunning: input.alreadyRunning,\n childrenStartFailed: input.startFailed,\n metered,\n forceDrained,\n modalOrphansTerminated,\n rotationsRequested,\n checkpointArtifactsClaimed: checkpointGc.claimed,\n checkpointArtifactsDeleted: checkpointGc.deleted,\n checkpointArtifactsFailed: checkpointGc.failed,\n });\n }\n\n return {\n metered,\n forceDrained,\n rotationsRequested,\n modalOrphansTerminated,\n };\n } finally {\n stopHeartbeat();\n }\n }\n\n /** Direct/embedded compatibility harness. Production uses the split Temporal\n * workflow above. The production activity is also the rolling-deploy bridge:\n * its workflow command stays byte-for-byte compatible while this activity\n * starts V2 through the injected client edge. Old workers may still execute\n * the bounded composite during rollout; exact DB claims keep both paths safe. */\n async function reapSandboxLeases(): Promise<ReapSandboxLeasesResult> {\n const service = await services();\n if (service.startSandboxReaperWorkflow) {\n const dispatch = await service.startSandboxReaperWorkflow();\n service.observability.info(\"sandbox reaper routed to versioned workflow\", {\n dispatch,\n });\n return {\n examined: 0,\n terminated: 0,\n skipped: 0,\n metered: 0,\n forceDrained: 0,\n modalOrphansTerminated: 0,\n };\n }\n\n const plan = await prepareSandboxLeaseSweep();\n const admitted = plan.drainable.slice(0, CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES);\n const outcomes = await Promise.allSettled(\n admitted.map((target) =>\n drainSandboxLease({\n target,\n timeoutClass: plan.timeoutClass,\n snapshotTimeoutMs: plan.snapshotTimeoutMs,\n captureTimeoutMs: plan.captureTimeoutMs,\n operationId: randomUUID(),\n }),\n ),\n );\n const terminated = outcomes.filter(\n (outcome) => outcome.status === \"fulfilled\" && outcome.value.status === \"terminated\",\n ).length;\n const skipped = outcomes.length - terminated;\n const maintenance = await maintainSandboxLeaseSweep({\n examined: admitted.length,\n started: admitted.length,\n alreadyRunning: 0,\n startFailed: 0,\n rotationsRequested: plan.rotationsRequested,\n });\n return {\n examined: admitted.length,\n terminated,\n skipped,\n metered: maintenance.metered,\n forceDrained: maintenance.forceDrained,\n modalOrphansTerminated: maintenance.modalOrphansTerminated,\n };\n }\n\n return {\n prepareSandboxLeaseSweep,\n drainSandboxLease,\n maintainSandboxLeaseSweep,\n reapSandboxLeases,\n };\n}\n\nconst CHECKPOINT_GC_LIMIT = 50;\nconst CHECKPOINT_GC_CLAIM_TTL_MS = 10 * 60_000;\nconst CHECKPOINT_TOMBSTONE_RETENTION_MS = 30 * 24 * 60 * 60_000;\nconst CHECKPOINT_TOMBSTONE_PRUNE_LIMIT = 500;\nconst SANDBOX_MAINTENANCE_ITEM_CONCURRENCY = 8;\n\ntype ConnectedCommandReconciliationOutcome =\n | \"claim_failed\"\n | \"provider_running\"\n | \"provider_offline\"\n | \"provider_error\"\n | \"proof_exited\"\n | \"proof_lost\"\n | \"proof_checkpoint_failed\"\n | \"settled_exited\"\n | \"settled_lost\"\n | \"settlement_failed\"\n | \"defer_failed\";\n\nfunction recordConnectedCommandReconciliation(\n observability: ActivityServices[\"observability\"],\n outcome: ConnectedCommandReconciliationOutcome,\n): void {\n observability.incrementCounter({\n name: \"opengeni_connected_background_command_reconciliation_total\",\n help: \"Exact-locator Connected Machine background-command reconciliation outcomes.\",\n labels: { outcome },\n });\n}\n\nasync function forEachWithConcurrency<T>(\n values: readonly T[],\n concurrency: number,\n visit: (value: T, index: number) => Promise<void>,\n): Promise<void> {\n if (values.length === 0) return;\n const workerCount = Math.min(values.length, Math.max(1, Math.floor(concurrency)));\n let nextIndex = 0;\n await Promise.all(\n Array.from({ length: workerCount }, async () => {\n while (nextIndex < values.length) {\n const index = nextIndex;\n nextIndex += 1;\n await visit(values[index]!, index);\n }\n }),\n );\n}\n\nasync function gcSandboxCheckpointArtifacts(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n observability: ActivityServices[\"observability\"],\n): Promise<{ claimed: number; deleted: number; failed: number }> {\n // Explicit OPENGENI_MODAL_TOKEN_* settings are optional: the SDK also supports\n // an operator-provisioned Modal profile. Durable artifacts must not become\n // immortal merely because credentials arrive through that supported path.\n const adopted = await adoptLegacyModalCheckpointReceipts(db, settings, observability).catch(\n (error) => {\n observability.warn(\"sandbox reaper: legacy Modal checkpoint discovery failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return 0;\n },\n );\n if (adopted > 0) {\n recordSandboxCheckpointArtifactOutcome(observability, \"legacy_adopted\", adopted);\n observability.info(\"sandbox reaper: adopted legacy Modal checkpoint receipts\", { adopted });\n }\n const claimId = crypto.randomUUID();\n const claims = await claimSandboxCheckpointArtifactsForGc(db, {\n claimId,\n limit: CHECKPOINT_GC_LIMIT,\n claimTtlMs: CHECKPOINT_GC_CLAIM_TTL_MS,\n });\n recordSandboxCheckpointArtifactOutcome(observability, \"claimed\", claims.length);\n let deleted = 0;\n let failed = 0;\n await forEachWithConcurrency(claims, SANDBOX_MAINTENANCE_ITEM_CONCURRENCY, async (claim) => {\n try {\n if (claim.providerBackend !== \"modal\") {\n throw new Error(`Unsupported checkpoint provider ${claim.providerBackend}`);\n }\n await deleteModalCheckpointSnapshot(settings, claim.providerBindingKey, claim.objectId);\n const settled = await settleSandboxCheckpointArtifactGc(db, {\n artifactId: claim.id,\n claimId,\n deleted: true,\n retryAfterMs: 1_000,\n });\n if (settled) {\n deleted += 1;\n recordSandboxCheckpointArtifactOutcome(observability, \"deleted\");\n }\n } catch (error) {\n failed += 1;\n recordSandboxCheckpointArtifactOutcome(observability, \"delete_failed\");\n const retryAfterMs = Math.min(\n 6 * 60 * 60_000,\n 5_000 * 2 ** Math.min(claim.deleteAttempts, 17),\n );\n await settleSandboxCheckpointArtifactGc(db, {\n artifactId: claim.id,\n claimId,\n deleted: false,\n error: error instanceof Error ? error.message : String(error),\n retryAfterMs,\n }).catch(() => false);\n observability.warn(\"sandbox reaper: checkpoint artifact delete failed\", {\n artifactId: claim.id,\n providerBackend: claim.providerBackend,\n objectKind: claim.objectKind,\n attempt: claim.deleteAttempts,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n });\n const pruned = await pruneDeletedSandboxCheckpointArtifacts(\n db,\n CHECKPOINT_TOMBSTONE_RETENTION_MS,\n CHECKPOINT_TOMBSTONE_PRUNE_LIMIT,\n );\n recordSandboxCheckpointArtifactOutcome(observability, \"tombstone_pruned\", pruned);\n return { claimed: claims.length, deleted, failed };\n}\n\nasync function adoptLegacyModalCheckpointReceipts(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n observability: ActivityServices[\"observability\"],\n): Promise<number> {\n const slots = await listLegacyModalCheckpointSlots(db, 25);\n if (slots.length === 0) return 0;\n const bindings = new Map<\n string,\n Promise<Awaited<ReturnType<typeof resolveModalCheckpointProviderBindingForLiveSandbox>>>\n >();\n let adopted = 0;\n await forEachWithConcurrency(slots, SANDBOX_MAINTENANCE_ITEM_CONCURRENCY, async (slot) => {\n try {\n let binding = bindings.get(slot.instanceId);\n if (!binding) {\n binding = resolveModalCheckpointProviderBindingForLiveSandbox(settings, slot.instanceId);\n bindings.set(slot.instanceId, binding);\n }\n const resolvedBinding = await binding;\n if (\n await adoptLegacyModalCheckpointArtifact(db, {\n accountId: slot.accountId,\n workspaceId: slot.workspaceId,\n sandboxGroupId: slot.sandboxGroupId,\n leaseId: slot.leaseId,\n leaseEpoch: slot.leaseEpoch,\n workspaceGeneration: slot.workspaceGeneration,\n slot: slot.slot,\n archiveBase64: slot.archiveBase64,\n descriptor: slot.descriptor,\n providerBindingKey: resolvedBinding.key,\n providerBinding: resolvedBinding.binding,\n })\n ) {\n adopted += 1;\n }\n } catch (error) {\n observability.warn(\"sandbox reaper: legacy Modal checkpoint adoption failed\", {\n workspaceId: slot.workspaceId,\n sandboxGroupId: slot.sandboxGroupId,\n slot: slot.slot,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n });\n return adopted;\n}\n\n/** Reconcile commands only against the immutable physical locator copied at\n * adoption. A successor enrollment connection is intentionally irrelevant: no\n * query or cancellation is ever rebound to it. */\nexport async function reconcileConnectedMachineBackgroundCommands(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n observability: ActivityServices[\"observability\"],\n bus: ActivityServices[\"bus\"],\n controlRpcOverride?: ControlRpc,\n): Promise<void> {\n const dueBefore = new Date();\n const deadline = Date.now() + settings.sandboxLeaseReaperPeriodMs;\n const offlineConnections = new Set<string>();\n const firstConnectionProbes = new Map<string, Promise<void>>();\n // Drain the fixed due frontier with the existing concurrency. Yield to the\n // remaining maintenance work each period; retries belong to a later sweep.\n do {\n const claimId = crypto.randomUUID();\n let claims: ConnectedMachineBackgroundCommandClaim[];\n try {\n claims = await claimConnectedMachineSessionBackgroundCommands(db, {\n claimId,\n dueBefore,\n limit: CONNECTED_COMMAND_RECONCILIATION_LIMIT,\n claimTtlMs: CONNECTED_COMMAND_RECONCILIATION_CLAIM_TTL_MS,\n });\n } catch (error) {\n recordConnectedCommandReconciliation(observability, \"claim_failed\");\n observability.warn(\"sandbox reaper: connected-command claim failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n\n const controlRpc =\n controlRpcOverride ??\n new NatsControlRpc(\n async (): Promise<NatsRequestConnection | null> => bus.getRequestConnection(),\n );\n await forEachWithConcurrency(claims, SANDBOX_MAINTENANCE_ITEM_CONCURRENCY, async (claim) => {\n let proof = claim.proof;\n const connectionKey = JSON.stringify([\n claim.controlWorkspaceId,\n claim.enrollmentId,\n claim.connectionInstanceId,\n ]);\n if (!proof) {\n const firstProbe = firstConnectionProbes.get(connectionKey);\n if (firstProbe) await firstProbe;\n if (offlineConnections.has(connectionKey)) {\n await deferConnectedCommandClaim(db, settings, observability, claim, \"provider_offline\");\n return;\n }\n // Share only the initial connection observation, never another command's result.\n let finishFirstProbe: (() => void) | undefined;\n if (!firstProbe) {\n firstConnectionProbes.set(\n connectionKey,\n new Promise<void>((resolve) => {\n finishFirstProbe = resolve;\n }),\n );\n }\n try {\n proof = await probeConnectedMachineBackgroundCommand(\n claim,\n controlRpc,\n Math.min(\n settings.sandboxSelfhostedControlTimeoutMs,\n RETAINED_PROCESS_PROVIDER_PROBE_TIMEOUT_MS,\n ),\n );\n // Replay currently retained frames for running as well as completed\n // commands. This is attach-only and leaves final ACK/observation alone.\n if (proof?.outcome !== \"lost\") {\n if (!bus.getOpStreamConnection)\n throw new Error(\"Connected command output transport unavailable\");\n const client = new OpStreamExecClient({\n workspaceId: claim.controlWorkspaceId,\n agentId: claim.enrollmentId,\n connectionInstanceId: claim.connectionInstanceId,\n epoch: 0,\n controlRpc,\n rpcSubject: subjectFor(\n claim.controlWorkspaceId,\n claim.enrollmentId,\n claim.connectionInstanceId,\n ),\n transport: new NatsOpStreamTransport(\n async () => bus.getOpStreamConnection?.() ?? null,\n ),\n controlTimeoutMs: Math.min(\n settings.sandboxSelfhostedControlTimeoutMs,\n RETAINED_PROCESS_PROVIDER_PROBE_TIMEOUT_MS,\n ),\n retryClock: defaultSelfhostedRetryClock,\n journal: { attachGeneration: () => String(Date.now()), persistSettled: () => {} },\n });\n await replayConnectedCommandOutput(\n client,\n claim.opId,\n Boolean(proof),\n async (frames) => {\n await captureConnectedCommandOutput(db, claim, bus)(claim.commandId, frames);\n },\n );\n }\n if (!proof) {\n await deferConnectedCommandClaim(\n db,\n settings,\n observability,\n claim,\n \"provider_running\",\n );\n return;\n }\n } catch (error) {\n const offline =\n error instanceof SelfhostedControlError &&\n (error.agentOffline || error.reason === \"agent_reconnecting\" || error.draining);\n if (offline) offlineConnections.add(connectionKey);\n if (!offline) {\n observability.warn(\"sandbox reaper: connected-command provider probe failed\", {\n commandId: claim.commandId,\n enrollmentId: claim.enrollmentId,\n connectionInstanceId: claim.connectionInstanceId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n await deferConnectedCommandClaim(\n db,\n settings,\n observability,\n claim,\n offline ? \"provider_offline\" : \"provider_error\",\n );\n return;\n } finally {\n finishFirstProbe?.();\n }\n\n try {\n await recordConnectedMachineBackgroundCommandProof(db, { claim, proof });\n recordConnectedCommandReconciliation(observability, `proof_${proof.outcome}`);\n } catch (error) {\n recordConnectedCommandReconciliation(observability, \"proof_checkpoint_failed\");\n observability.warn(\"sandbox reaper: connected-command proof checkpoint failed\", {\n commandId: claim.commandId,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n try {\n const settlement = await settleClaimedConnectedMachineBackgroundCommand(db, { claim });\n if (!settlement.settled) {\n throw new Error(\"Connected command settlement lost its exact claim or proof\");\n }\n if (settlement.events.length > 0) {\n try {\n await bus.publish(claim.workspaceId, claim.sessionId, settlement.events);\n } catch (error) {\n observability.warn(\"sandbox reaper: connected-command event fanout failed\", {\n commandId: claim.commandId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n recordConnectedCommandReconciliation(observability, `settled_${proof.outcome}`);\n } catch (error) {\n recordConnectedCommandReconciliation(observability, \"settlement_failed\");\n observability.warn(\"sandbox reaper: connected-command settlement failed\", {\n commandId: claim.commandId,\n error: error instanceof Error ? error.message : String(error),\n });\n await deferConnectedCommandClaim(db, settings, observability, claim, \"settlement_failed\");\n }\n });\n if (claims.length < CONNECTED_COMMAND_RECONCILIATION_LIMIT) break;\n } while (Date.now() < deadline);\n}\n\nexport async function replayConnectedCommandOutput(\n client: Pick<OpStreamExecClient, \"readExisting\">,\n opId: string,\n terminalKnown: boolean,\n capture: Parameters<OpStreamExecClient[\"readExisting\"]>[2],\n): Promise<void> {\n // A completed operation can need several bounded reads to replay its retained\n // frames. Keep the reader's integrity checkpoint until the exit is verified;\n // replacing it after each partial read would restart forever at frame one.\n let capturedThrough = 0n;\n while (true) {\n const before = capturedThrough;\n const replay = await client.readExisting(opId, terminalKnown ? 5_000 : 250, capture);\n if (!terminalKnown || replay.status === \"completed\" || replay.terminal) return;\n // Quiet jobs can retain many heartbeat frames (or an incomplete UTF-8\n // chunk). These are real replay progress even when capture receives no\n // stdout/stderr. Use the reader's verified, contiguous protocol frontier.\n capturedThrough = BigInt(replay.replaySequence);\n // This is a finite terminal drain, not a poller for a running command.\n // Failed persistence, transport/integrity errors, and no-progress reads\n // return control to normal reconciliation without licensing settlement.\n if (capturedThrough === before) {\n throw new Error(\"Connected command terminal output replay has not reached its exit frontier\");\n }\n }\n}\n\nexport async function probeConnectedMachineBackgroundCommand(\n claim: ConnectedMachineBackgroundCommandClaim,\n controlRpc: ControlRpc,\n controlTimeoutMs: number,\n observedAt = new Date(),\n): Promise<ConnectedMachineBackgroundCommandProof | null> {\n const input = {\n controlRpc,\n rpcSubject: subjectFor(\n claim.controlWorkspaceId,\n claim.enrollmentId,\n claim.connectionInstanceId,\n ),\n opId: claim.opId,\n controlTimeoutMs,\n };\n const status =\n claim.state === \"stopping\" ? await cancelSelfhostedOp(input) : await querySelfhostedOp(input);\n return connectedCommandProofFromStatus(status, observedAt);\n}\n\nexport function connectedCommandProofFromStatus(\n status: OpStatus,\n observedAt: Date,\n): ConnectedMachineBackgroundCommandProof | null {\n switch (status.state) {\n case OpState.OP_STATE_ACCEPTED:\n case OpState.OP_STATE_RUNNING:\n return null;\n case OpState.OP_STATE_COMPLETE: {\n const exit = status.exit;\n if (!exit) {\n throw new Error(\"Connected command completed without an exit record\");\n }\n const failureCode = exit.failureCode.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 128);\n const reason = failureCode\n ? `op_failure_${failureCode}`\n : exit.cancelled\n ? \"op_cancelled\"\n : exit.timedOut\n ? \"op_timed_out\"\n : \"op_exit\";\n return {\n outcome: \"exited\",\n exitCode: exit.exitCode,\n reason,\n ...(failureCode\n ? {\n failure: { code: failureCode, detail: exit.failureDetail, retryable: false as const },\n }\n : {}),\n observedAt,\n };\n }\n case OpState.OP_STATE_LOST:\n return {\n outcome: \"lost\",\n exitCode: null,\n reason:\n status.lostReason === OpLostReason.OP_LOST_REASON_EVICTED\n ? \"op_lost_evicted\"\n : status.lostReason === OpLostReason.OP_LOST_REASON_AGENT_RESTARTED\n ? \"op_lost_agent_restarted\"\n : \"op_lost_unspecified\",\n observedAt,\n };\n default:\n throw new Error(`Connected command returned invalid op state ${status.state}`);\n }\n}\n\nasync function deferConnectedCommandClaim(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n observability: ActivityServices[\"observability\"],\n claim: ConnectedMachineBackgroundCommandClaim,\n outcome: \"provider_running\" | \"provider_offline\" | \"provider_error\" | \"settlement_failed\",\n): Promise<void> {\n const exponent = Math.min(4, Math.max(0, claim.reconcileAttempts - 1));\n const retryAfterMs = Math.min(\n 5 * 60_000,\n Math.max(settings.sandboxLeaseReaperPeriodMs, 30_000) * 2 ** exponent,\n );\n try {\n if (\n !(await deferConnectedMachineBackgroundCommandReconciliation(db, {\n claim,\n outcome,\n retryAfterMs,\n }))\n ) {\n throw new Error(\"Connected command defer lost its exact claim\");\n }\n recordConnectedCommandReconciliation(observability, outcome);\n } catch (error) {\n recordConnectedCommandReconciliation(observability, \"defer_failed\");\n observability.warn(\"sandbox reaper: connected-command defer failed\", {\n commandId: claim.commandId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nasync function reconcileTerminalRetainedProcesses(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n observability: ActivityServices[\"observability\"],\n probe: RetainedProcessProbeFn,\n inspectHistoricalModalSandbox: HistoricalModalSandboxLifecycleProbeFn,\n bus: ActivityServices[\"bus\"],\n): Promise<void> {\n const claimId = crypto.randomUUID();\n let claims: Awaited<ReturnType<typeof claimTerminalRetainedProcesses>>;\n try {\n claims = await claimTerminalRetainedProcesses(db, {\n claimId,\n limit: RETAINED_PROCESS_RECONCILIATION_LIMIT,\n claimTtlMs: RETAINED_PROCESS_RECONCILIATION_CLAIM_TTL_MS,\n });\n } catch (error) {\n recordRetainedProcessReconciliation(observability, \"claim_failed\");\n observability.warn(\"sandbox reaper: retained-process claim failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n\n const drainBudget: RetainedProcessDrainBudget = {\n until: Date.now() + RETAINED_PROCESS_OUTPUT_DRAIN_SWEEP_BUDGET_MS,\n };\n for (const claim of claims) {\n let process = claim.process;\n const expected = retainedProcessSettlementIdentity(process);\n let proof = retainedProcessReconciliationProof(process);\n const processScope = {\n accountId: process.accountId,\n workspaceId: process.workspaceId,\n sessionId: process.sessionId,\n processId: process.id,\n };\n const storedCommandPersistence = retainedProviderCommandPersistence(\n db,\n processScope,\n bus ? (events) => bus.publish(process.workspaceId, process.sessionId, events) : undefined,\n );\n const commandPersistence = {\n ...storedCommandPersistence,\n requestCancellation: async (reason: \"provider_deadline\" | \"explicit_stop\") => {\n if (reason === \"provider_deadline\") {\n await requestRetainedProcessDeadlineCancellation(db, processScope);\n if (!(await storedCommandPersistence.cancellationRequested()))\n throw new Error(\n \"Supervised deadline cancellation no longer owns its original rotating lease\",\n );\n } else await storedCommandPersistence.requestCancellation(reason);\n },\n };\n if (proof && process.providerBackend === \"modal\") {\n try {\n const command = await commandPersistence.load();\n if (\n command?.kind === \"modal-router-v1\" &&\n command.supervision &&\n (!(await commandPersistence.loadSupervisionReceipt()) ||\n ![command.streams.stdout, command.streams.stderr].every(\n (stream) => stream.eof && stream.exitCode === 0,\n ))\n )\n proof = null;\n } catch {\n // An earlier terminal observation cannot make missing control/output\n // proof unreachable. Reprobe the original binding; DB remains the gate.\n proof = null;\n }\n }\n if (!proof) {\n let observation: RetainedProcessProbeResult | null = null;\n\n // Legacy rows created before provider bindings existed are adoptable only\n // when the exact historical sandbox resolves in the configured Modal\n // namespace. NotFound is ambiguous here: it can mean either deletion or\n // credential rotation, so it never creates ownership or loss proof.\n if (\n process.providerBackend === \"modal\" &&\n process.routeTargetId === null &&\n !process.providerBindingKey\n ) {\n try {\n const lifecycle = await withRetainedProcessProbeTimeout(\n inspectHistoricalModalSandbox(settings, process.providerInstanceId, null),\n );\n if (lifecycle.status === \"not_found\") {\n observation = {\n status: \"deferred\",\n reason: \"provider_binding_missing\",\n };\n } else {\n process = await bindRetainedProcessProviderIdentity(db, {\n accountId: process.accountId,\n workspaceId: process.workspaceId,\n sessionId: process.sessionId,\n processId: process.id,\n expected,\n claimId: claim.claimId,\n providerBindingKey: lifecycle.providerBindingKey,\n providerBinding: lifecycle.providerBinding,\n });\n recordRetainedProcessReconciliation(observability, \"provider_binding_adopted\");\n if (lifecycle.status === \"terminated\") {\n observation = {\n status: \"proved\",\n proof: {\n outcome: \"lost\",\n exitCode: null,\n reason: \"provider_instance_terminated\",\n },\n };\n }\n }\n } catch (error) {\n observation = {\n status: \"deferred\",\n reason:\n error === RETAINED_PROCESS_PROBE_TIMEOUT ? \"provider_timeout\" : \"provider_error\",\n };\n }\n }\n\n if (\n observation?.status === \"deferred\" &&\n process.providerBackend === \"modal\" &&\n !process.providerBindingKey &&\n !process.deadlineCancellationRequestedAt\n ) {\n // An unbound historical command cannot be signalled safely. Still\n // record deadline intent when its lease matches: a failed observer\n // must not block capture until the provider expires.\n try {\n await requestRetainedProcessDeadlineCancellation(db, processScope);\n } catch (error) {\n observability.warn(\"sandbox reaper: legacy deadline cancellation intent failed\", {\n processId: process.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (observation === null) {\n const lease = await readLease(db, process.workspaceId, process.sandboxGroupId).catch(\n () => null,\n );\n const currentLeaseIdentityMatches =\n Boolean(lease) &&\n lease!.id === process.leaseId &&\n lease!.leaseEpoch === process.leaseEpoch &&\n lease!.backend === process.providerBackend &&\n lease!.instanceId === process.providerInstanceId &&\n process.routeTargetId === null;\n if (!currentLeaseIdentityMatches) {\n // The lease may already be cold or belong to a successor. Its current\n // resume envelope cannot interrogate the historical process, but a\n // bound process can safely inspect the exact old Modal sandbox id.\n if (process.providerBackend !== \"modal\" || process.routeTargetId !== null) {\n observation = { status: \"deferred\", reason: \"identity_mismatch\" };\n } else {\n try {\n const lifecycle = await withRetainedProcessProbeTimeout(\n inspectHistoricalModalSandbox(\n settings,\n process.providerInstanceId,\n process.providerBindingKey,\n ),\n );\n observation =\n lifecycle.status === \"not_found\"\n ? {\n status: \"proved\",\n proof: {\n outcome: \"lost\",\n exitCode: null,\n reason: \"provider_instance_not_found\",\n },\n }\n : lifecycle.status === \"terminated\"\n ? {\n status: \"proved\",\n proof: {\n outcome: \"lost\",\n exitCode: null,\n reason: \"provider_instance_terminated\",\n },\n }\n : { status: \"deferred\", reason: \"identity_mismatch\" };\n } catch (error) {\n observation = {\n status: \"deferred\",\n reason:\n error === RETAINED_PROCESS_PROBE_TIMEOUT ? \"provider_timeout\" : \"provider_error\",\n };\n }\n }\n } else {\n try {\n const command = await commandPersistence.load();\n const supervised = command?.kind === \"modal-router-v1\" && Boolean(command.supervision);\n const supervisionMetric = (outcome: string) =>\n observability.incrementCounter({\n name: \"opengeni_command_supervision_total\",\n help: \"Native retained command supervision reconciliation outcomes.\",\n labels: { outcome },\n });\n if (\n supervised &&\n (lease!.rotationReason === \"provider_deadline\" ||\n claim.ownerState === \"background_stopping\")\n ) {\n await commandPersistence.requestCancellation(\n lease!.rotationReason === \"provider_deadline\"\n ? \"provider_deadline\"\n : \"explicit_stop\",\n );\n supervisionMetric(\"cancellation_intent\");\n }\n const legacyDeadlineStop =\n lease!.rotationReason === \"provider_deadline\" &&\n !supervised &&\n !process.deadlineCancellationRequestedAt;\n const probeOutcome = await probe(\n settings,\n lease!,\n process,\n (claim.ownerState === \"background_stopping\" &&\n !process.deadlineCancellationRequestedAt) ||\n legacyDeadlineStop\n ? \"cancel\"\n : \"observe\",\n async (result, chunkId, stream, streamFidelity) => {\n if (\n typeof result !== \"string\" ||\n (!stream && isExecSessionLostBanner(result, process.providerSessionId))\n )\n return;\n const events = await appendSessionCommandOutput(db, {\n accountId: process.accountId,\n workspaceId: process.workspaceId,\n sessionId: process.sessionId,\n commandId: process.id,\n chunkId,\n stream: stream ?? \"stdout\",\n streamFidelity: streamFidelity ?? (stream ? \"separate\" : \"merged\"),\n chunk: stream ? result : stripExecBanner(result),\n });\n if (events.length && bus)\n await bus\n .publish(process.workspaceId, process.sessionId, events)\n .catch(() => undefined);\n },\n commandPersistence,\n drainBudget,\n ).then(\n (value) => ({ ok: true as const, value }),\n (error: unknown) => ({ ok: false as const, error }),\n );\n // Legacy PTY input reserves Ctrl-C before the cancellation fence.\n // Non-PTY has no command signal in the Modal SDK: probe it without\n // injecting Ctrl-C as data, then fence and save after the grace.\n if (\n legacyDeadlineStop &&\n !(await requestRetainedProcessDeadlineCancellation(db, processScope))\n )\n throw new Error(\"Deadline cancellation no longer owns its rotating lease\");\n if (!probeOutcome.ok) throw probeOutcome.error;\n observation = probeOutcome.value;\n if (supervised) {\n supervisionMetric(\n (await commandPersistence.loadSupervisionReceipt())\n ? \"proof_retained\"\n : \"proof_missing\",\n );\n if (observation.status === \"deferred\")\n supervisionMetric(\n observation.reason === \"provider_running\"\n ? \"checkpoint_blocked\"\n : \"provider_failure\",\n );\n }\n } catch (error) {\n observability.warn(\"sandbox reaper: retained-process provider probe failed\", {\n processId: process.id,\n providerBackend: process.providerBackend,\n error: error instanceof Error ? error.message : String(error),\n });\n observation = { status: \"deferred\", reason: \"provider_error\" };\n }\n }\n }\n if (observation.status === \"binding\") {\n try {\n process = await bindRetainedProcessProviderIdentity(db, {\n accountId: process.accountId,\n workspaceId: process.workspaceId,\n sessionId: process.sessionId,\n processId: process.id,\n expected,\n claimId: claim.claimId,\n providerBindingKey: observation.providerBindingKey,\n providerBinding: observation.providerBinding,\n });\n recordRetainedProcessReconciliation(observability, \"provider_binding_adopted\");\n observation = { status: \"deferred\", reason: \"provider_running\" };\n } catch (error) {\n observability.warn(\"sandbox reaper: retained-process binding adoption failed\", {\n processId: process.id,\n error: error instanceof Error ? error.message : String(error),\n });\n observation = { status: \"deferred\", reason: \"provider_error\" };\n }\n }\n if (observation.status === \"deferred\") {\n await deferRetainedProcessClaim(\n db,\n settings,\n observability,\n process,\n expected,\n claim.claimId,\n observation.reason,\n observation.outputBacklog === true,\n );\n continue;\n }\n try {\n process = await recordRetainedProcessReconciliationProof(db, {\n accountId: process.accountId,\n workspaceId: process.workspaceId,\n sessionId: process.sessionId,\n processId: process.id,\n expected,\n claimId: claim.claimId,\n proof: observation.proof,\n });\n proof = observation.proof;\n recordRetainedProcessReconciliation(observability, `proof_${proof.outcome}`);\n } catch (error) {\n recordRetainedProcessReconciliation(observability, \"proof_checkpoint_failed\");\n warnRetainedProcessProofFailure(observability, error, process);\n continue;\n }\n }\n\n try {\n const settlement = await settleRetainedProcess(db, {\n accountId: process.accountId,\n workspaceId: process.workspaceId,\n sessionId: process.sessionId,\n processId: process.id,\n expected,\n reconciliationClaimId: claim.claimId,\n outcome: proof.outcome,\n exitCode: proof.exitCode,\n reason: proof.reason,\n idleGraceMs: settings.sandboxIdleGraceMs,\n });\n if (settlement.process.state === \"active\") {\n throw new Error(\"Retained-process reconciliation returned an active durable process\");\n }\n if (settlement.backgroundCommandEvents.length > 0) {\n try {\n await bus.publish(\n process.workspaceId,\n process.sessionId,\n settlement.backgroundCommandEvents,\n );\n } catch (error) {\n observability.warn(\"sandbox reaper: retained-command event fanout failed\", {\n processId: process.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n recordRetainedProcessReconciliation(observability, `settled_${proof.outcome}`);\n } catch (error) {\n recordRetainedProcessReconciliation(observability, \"settlement_failed\");\n observability.warn(\"sandbox reaper: retained-process settlement failed\", {\n processId: process.id,\n error: error instanceof Error ? error.message : String(error),\n });\n await deferRetainedProcessClaim(\n db,\n settings,\n observability,\n process,\n expected,\n claim.claimId,\n \"settlement_failed\",\n );\n }\n }\n}\n\nasync function deferRetainedProcessClaim(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n observability: ActivityServices[\"observability\"],\n process: SandboxRetainedProcess,\n expected: ReturnType<typeof retainedProcessSettlementIdentity>,\n claimId: string,\n outcome: RetainedProcessDeferralOutcome,\n outputBacklog = false,\n): Promise<void> {\n const deferral = retainedProcessReconciliationDeferral(settings, process, outcome, outputBacklog);\n try {\n // A healthy long-lived command can already be on a five-minute backoff\n // when rotation becomes due. Wake it at the lead boundary, then at the\n // reaper cadence, so observation does not consume the capture window.\n const lease =\n process.providerBackend === \"modal\" && process.routeTargetId === null\n ? await readLease(db, process.workspaceId, process.sandboxGroupId)\n : null;\n await deferRetainedProcessReconciliation(db, {\n accountId: process.accountId,\n workspaceId: process.workspaceId,\n sessionId: process.sessionId,\n processId: process.id,\n expected,\n claimId,\n outcome: deferral.durableOutcome,\n retryAfterMs: retainedProcessDeadlineRetryMs(process, lease, settings, deferral.retryAfterMs),\n });\n recordRetainedProcessReconciliation(observability, deferral.metricOutcome);\n } catch (error) {\n recordRetainedProcessReconciliation(observability, \"defer_failed\");\n observability.warn(\"sandbox reaper: retained-process defer failed\", {\n processId: process.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\ntype RetainedProcessDeferralOutcome =\n | Extract<RetainedProcessProbeResult, { status: \"deferred\" }>[\"reason\"]\n | \"settlement_failed\";\n\nexport function retainedProcessReconciliationDeferral(\n settings: Pick<ActivityServices[\"settings\"], \"sandboxLeaseReaperPeriodMs\">,\n process: Pick<SandboxRetainedProcess, \"reconcileAttempts\">,\n outcome: RetainedProcessDeferralOutcome,\n outputBacklog = false,\n): {\n durableOutcome: string;\n metricOutcome: RetainedProcessReconciliationOutcome;\n retryAfterMs: number;\n quarantined: boolean;\n} {\n const bindingQuarantine =\n process.reconcileAttempts >= RETAINED_PROCESS_BINDING_QUARANTINE_AFTER_ATTEMPTS &&\n (outcome === \"provider_binding_missing\" ||\n outcome === \"provider_binding_mismatch\" ||\n outcome === \"process_observation_unavailable\");\n if (bindingQuarantine) {\n return {\n durableOutcome: `quarantined_${outcome}`,\n metricOutcome:\n outcome === \"provider_binding_missing\"\n ? \"quarantined_binding_missing\"\n : outcome === \"provider_binding_mismatch\"\n ? \"quarantined_binding_mismatch\"\n : \"quarantined_process_observation_unavailable\",\n retryAfterMs: RETAINED_PROCESS_BINDING_QUARANTINE_RETRY_MS,\n quarantined: true,\n };\n }\n const baseRetryMs = Math.max(settings.sandboxLeaseReaperPeriodMs, 30_000);\n // A backlog still being drained is progress, not an unhealthy provider:\n // come back at the reaper cadence, without backoff.\n const exponent =\n outcome === \"provider_running\" && outputBacklog\n ? 0\n : Math.min(4, Math.max(0, process.reconcileAttempts - 1));\n const retryAfterMs = Math.min(5 * 60_000, baseRetryMs * 2 ** exponent);\n return {\n durableOutcome: outcome,\n metricOutcome: outcome,\n retryAfterMs,\n quarantined: false,\n };\n}\n\ntype RetainedProcessProbeClient = {\n backendId: string;\n resume?: (state: unknown) => Promise<unknown>;\n deserializeSessionState?: (state: Record<string, unknown>) => Promise<unknown>;\n};\n\ntype RetainedProcessProbeSession = ProviderCommandSession & {\n acknowledgeCommandOutput?: (result: string) => Promise<void>;\n writeStdin?: (args: {\n sessionId: number;\n chars: string;\n yieldTimeMs: number;\n maxOutputTokens: number;\n }) => Promise<unknown>;\n};\n\nconst RETAINED_PROCESS_PROBE_TIMEOUT = Symbol(\"retained-process-provider-probe-timeout\");\n\n/** A command's exit is reported only after both output streams reach EOF, so a\n * finished command with a large backlog looks running until it is read. While a\n * backlog remains, keep reading within the per-claim and per-sweep budgets, so\n * it settles in this claim instead of one page per backoff step. Every page,\n * including `first`, is captured here. */\nexport async function drainRetainedCommandBacklog(\n session: RetainedProcessProbeSession,\n providerSessionId: number,\n first: unknown,\n capturePage: (value: unknown) => Promise<void>,\n budget?: RetainedProcessDrainBudget,\n): Promise<RetainedProcessProbeResult> {\n // Measure before capture: capturing a byte-offset page consumes its receipt.\n let backlog = retainedBacklogRemains(session, first);\n await capturePage(first);\n let observation = classifyRetainedProcessPollResult(first, providerSessionId, session);\n if (typeof session.writeStdin !== \"function\") return observation;\n const until = Math.min(\n Date.now() + RETAINED_PROCESS_OUTPUT_DRAIN_BUDGET_MS,\n budget?.until ?? Number.POSITIVE_INFINITY,\n );\n for (\n let reads = 0;\n backlog &&\n observation.status === \"deferred\" &&\n observation.reason === \"provider_running\" &&\n reads < RETAINED_PROCESS_OUTPUT_DRAIN_MAX_READS &&\n Date.now() < until;\n reads++\n ) {\n let next: unknown;\n try {\n next = await withRetainedProcessProbeTimeout(\n session.writeStdin({\n sessionId: providerSessionId,\n chars: \"\",\n yieldTimeMs: 1_000,\n maxOutputTokens: 2_000,\n }),\n );\n } catch {\n // The observation already made stays authoritative; the next sweep\n // classifies any provider failure through the ordinary path.\n break;\n }\n backlog = retainedBacklogRemains(session, next);\n await capturePage(next);\n observation = classifyRetainedProcessPollResult(next, providerSessionId, session);\n }\n return backlog && observation.status === \"deferred\" && observation.reason === \"provider_running\"\n ? { ...observation, outputBacklog: true }\n : observation;\n}\n\n/** Whether a byte-offset page leaves a backlog worth reading now: the provider\n * reports the process exited but its output is not yet read to EOF, or a live\n * process produced a large page. Must run before the page is captured, which\n * consumes its receipt. Supervised commands are left to their proof path. */\nfunction retainedBacklogRemains(session: RetainedProcessProbeSession, result: unknown): boolean {\n const page = session.getProviderCommandOutput?.(result);\n if (!page?.expected || page.command.kind !== \"modal-router-v1\") return false;\n if (page.command.supervision || page.exitCode !== null) return false;\n if (page.providerExited) return true;\n const { command, expected } = page;\n return ([\"stdout\", \"stderr\"] as const).some(\n (stream) =>\n command.streams[stream].byteOffset - expected.streams[stream].byteOffset >=\n RETAINED_PROCESS_OUTPUT_BACKLOG_BYTES,\n );\n}\n\nasync function withRetainedProcessProbeTimeout<T>(promise: Promise<T>): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => reject(RETAINED_PROCESS_PROBE_TIMEOUT),\n RETAINED_PROCESS_PROVIDER_PROBE_TIMEOUT_MS,\n );\n timer.unref?.();\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/** Consumed SDK output cannot be polled again. Retain the receipt across\n * persistence retries in this worker; a worker crash remains unreplayable. */\nconst pendingRetainedProbeOutput = new Map<string, { result: unknown; chunkId: string }>();\n\nexport async function captureRetainedProbeOutput(\n processId: string,\n result: unknown,\n capture: (result: unknown, chunkId: string) => Promise<void>,\n): Promise<void> {\n const pending = pendingRetainedProbeOutput.get(processId) ?? {\n result,\n chunkId: crypto.randomUUID(),\n };\n pendingRetainedProbeOutput.set(processId, pending);\n await capture(pending.result, pending.chunkId);\n pendingRetainedProbeOutput.delete(processId);\n}\n\nexport async function probeRetainedProcessAtProvider(\n settings: ActivityServices[\"settings\"],\n lease: LeaseSnapshot,\n process: SandboxRetainedProcess,\n mode: \"observe\" | \"cancel\" = \"observe\",\n captureOutput?: (\n result: unknown,\n chunkId: string,\n stream?: \"stdout\" | \"stderr\",\n streamFidelity?: \"separate\" | \"merged\",\n ) => Promise<void>,\n providerPersistence?: ProviderCommandPersistence,\n drainBudget?: RetainedProcessDrainBudget,\n): Promise<RetainedProcessProbeResult> {\n if (\n lease.id !== process.leaseId ||\n lease.sandboxGroupId !== process.sandboxGroupId ||\n lease.leaseEpoch !== process.leaseEpoch ||\n lease.backend !== process.providerBackend ||\n lease.instanceId !== process.providerInstanceId ||\n !lease.resumeBackendId ||\n sandboxBackendForSdkBackendId(lease.resumeBackendId) !== process.providerBackend ||\n process.routeTargetId !== null\n ) {\n return { status: \"deferred\", reason: \"identity_mismatch\" };\n }\n if (!lease.resumeState) {\n return { status: \"deferred\", reason: \"resume_state_missing\" };\n }\n const pending = pendingRetainedProbeOutput.get(process.id);\n if (pending) {\n if (!captureOutput) throw new Error(\"Pending command output requires its persistence callback\");\n await captureRetainedProbeOutput(process.id, pending.result, captureOutput);\n const pendingObservation = classifyRetainedProcessPollResult(\n pending.result,\n process.providerSessionId,\n );\n // Capture of a previous page must not consume the only deadline stop\n // attempt. Terminal proof needs no further provider call.\n if (mode !== \"cancel\" || pendingObservation.status === \"proved\") return pendingObservation;\n }\n const envelopeBackend = (lease.resumeState as { backendId?: unknown }).backendId;\n if (\n envelopeBackend !== undefined &&\n (typeof envelopeBackend !== \"string\" ||\n sandboxBackendForSdkBackendId(envelopeBackend) !== process.providerBackend)\n ) {\n return { status: \"deferred\", reason: \"identity_mismatch\" };\n }\n if (sandboxProviderInstanceIdFromEnvelope(lease.resumeState) !== process.providerInstanceId) {\n return { status: \"deferred\", reason: \"identity_mismatch\" };\n }\n\n let configuredModalBinding: Awaited<\n ReturnType<typeof resolveModalCheckpointProviderBinding>\n > | null = null;\n if (process.providerBackend === \"modal\" && process.providerBindingKey) {\n try {\n configuredModalBinding = await withRetainedProcessProbeTimeout(\n resolveModalCheckpointProviderBinding(settings),\n );\n } catch (error) {\n return {\n status: \"deferred\",\n reason: error === RETAINED_PROCESS_PROBE_TIMEOUT ? \"provider_timeout\" : \"provider_error\",\n };\n }\n if (configuredModalBinding.key !== process.providerBindingKey) {\n return { status: \"deferred\", reason: \"provider_binding_mismatch\" };\n }\n }\n\n let client: RetainedProcessProbeClient | undefined;\n try {\n client = createSandboxClientForBackend(process.providerBackend as never, settings) as\n | RetainedProcessProbeClient\n | undefined;\n } catch {\n return { status: \"deferred\", reason: \"provider_error\" };\n }\n if (\n !client ||\n sandboxBackendForSdkBackendId(client.backendId) !== process.providerBackend ||\n !client.resume\n ) {\n return { status: \"deferred\", reason: \"backend_unsupported\" };\n }\n const envelopeSessionState =\n (lease.resumeState as { sessionState?: unknown }).sessionState ?? lease.resumeState;\n let resumedState: unknown;\n try {\n resumedState = await deserializeSandboxSessionStateEnvelope(\n client as never,\n envelopeSessionState,\n process.providerInstanceId,\n );\n } catch {\n return { status: \"deferred\", reason: \"provider_error\" };\n }\n if (resumedState === undefined) {\n return { status: \"deferred\", reason: \"resume_state_missing\" };\n }\n\n let session: RetainedProcessProbeSession;\n try {\n const resumed = await withRetainedProcessProbeTimeout(\n resumeExactSandboxSession(\n client,\n process.providerBackend,\n resumedState,\n process.providerInstanceId,\n ),\n );\n session = resumed.session as RetainedProcessProbeSession;\n } catch (error) {\n if (error === RETAINED_PROCESS_PROBE_TIMEOUT) {\n return { status: \"deferred\", reason: \"provider_timeout\" };\n }\n if (isProviderSandboxNotFoundError(client.backendId, error)) {\n if (process.providerBackend === \"modal\" && !process.providerBindingKey) {\n return { status: \"deferred\", reason: \"provider_binding_missing\" };\n }\n return {\n status: \"proved\",\n proof: {\n outcome: \"lost\",\n exitCode: null,\n reason: \"provider_instance_not_found\",\n },\n };\n }\n return { status: \"deferred\", reason: \"provider_error\" };\n }\n if (typeof session.writeStdin !== \"function\") {\n return { status: \"deferred\", reason: \"backend_unsupported\" };\n }\n let legacyPty = false;\n if (process.providerBackend === \"modal\") {\n let liveBinding: Awaited<ReturnType<typeof resolveModalCheckpointProviderBindingForSession>>;\n try {\n liveBinding = await withRetainedProcessProbeTimeout(\n resolveModalCheckpointProviderBindingForSession(settings, session),\n );\n } catch (error) {\n return {\n status: \"deferred\",\n reason: error === RETAINED_PROCESS_PROBE_TIMEOUT ? \"provider_timeout\" : \"provider_error\",\n };\n }\n if (!process.providerBindingKey) {\n return {\n status: \"binding\",\n providerBindingKey: liveBinding.key,\n providerBinding: liveBinding.binding,\n };\n }\n if (\n liveBinding.key !== process.providerBindingKey ||\n configuredModalBinding?.key !== process.providerBindingKey\n ) {\n return { status: \"deferred\", reason: \"provider_binding_mismatch\" };\n }\n // Legacy SDK-local handles cannot be reconstructed. New commands carry\n // an opaque provider locator retained outside the sandbox's authority.\n const command = await providerPersistence?.load();\n if (!command || !providerPersistence || !session.bindProviderCommand)\n return { status: \"deferred\", reason: \"process_observation_unavailable\" };\n session.bindProviderCommand(process.providerSessionId, command, providerPersistence);\n legacyPty = command.pty === true;\n }\n const capturePage = async (value: unknown): Promise<void> => {\n if (!captureOutput) {\n if (session.getProviderCommandOutput?.(value))\n throw new Error(\"Provider command output requires durable capture before settlement\");\n return;\n }\n const page = session.getProviderCommandOutput?.(value);\n if (page?.command.kind === \"modal-router-v1\" && typeof value === \"string\") {\n if (!session.captureCommandOutput || !(await session.captureCommandOutput(value)))\n throw new Error(\"Byte-offset output requires atomic capture before settlement\");\n return;\n }\n if (page) {\n for (const chunk of page.chunks)\n if (chunk.text)\n await captureOutput(chunk.text, chunk.chunkId, chunk.stream, page.streamFidelity);\n } else {\n await captureRetainedProbeOutput(process.id, value, captureOutput);\n }\n if (typeof value === \"string\") await session.acknowledgeCommandOutput?.(value);\n };\n\n let result: unknown;\n try {\n const supervisedCancelled =\n mode === \"cancel\" || lease.rotationReason === \"provider_deadline\"\n ? ((await session.cancelSupervisedCommand?.(\n process.providerSessionId,\n lease.rotationReason === \"provider_deadline\" ? \"provider_deadline\" : \"explicit_stop\",\n )) ?? false)\n : false;\n result = await withRetainedProcessProbeTimeout(\n session.writeStdin({\n sessionId: process.providerSessionId,\n // Ctrl-C is a signal only through a PTY. For a non-PTY command it is\n // ordinary stdin data and can corrupt the command's input.\n chars:\n mode === \"cancel\" &&\n !supervisedCancelled &&\n (process.providerBackend !== \"modal\" || legacyPty)\n ? \"\\u0003\"\n : \"\",\n yieldTimeMs: 1_000,\n maxOutputTokens: 2_000,\n }),\n );\n } catch (error) {\n if (error === RETAINED_PROCESS_PROBE_TIMEOUT) {\n return { status: \"deferred\", reason: \"provider_timeout\" };\n }\n if (isProviderSandboxGoneDuringRoutedOperation(client.backendId, error)) {\n if (process.providerBackend === \"modal\" && !process.providerBindingKey) {\n return { status: \"deferred\", reason: \"provider_binding_missing\" };\n }\n return {\n status: \"proved\",\n proof: {\n outcome: \"lost\",\n exitCode: null,\n reason: \"provider_instance_not_found\",\n },\n };\n }\n return { status: \"deferred\", reason: \"provider_error\" };\n }\n // Cancellation keeps draining with empty reads too: a stopped command's exit\n // is also reported only after its unread output reaches EOF.\n const observation = await drainRetainedCommandBacklog(\n session,\n process.providerSessionId,\n result,\n capturePage,\n drainBudget,\n );\n if (\n observation.status === \"deferred\" &&\n observation.reason === \"provider_running\" &&\n lease.rotationRequestedAt !== null &&\n mode !== \"cancel\" &&\n !process.cancellationRequestedAt &&\n legacyPty &&\n !(await providerPersistence\n ?.load()\n .then((command) => command?.kind === \"modal-router-v1\" && command.supervision))\n ) {\n // A background PTY cannot outlive the finite provider box. Interrupt only\n // this exact durable provider session after rotation admission is fenced;\n // settlement still requires an exit/loss banner on this or a later sweep.\n try {\n const interrupted = await withRetainedProcessProbeTimeout(\n session.writeStdin({\n sessionId: process.providerSessionId,\n chars: \"\\u0003\",\n yieldTimeMs: 1_000,\n maxOutputTokens: 2_000,\n }),\n );\n await capturePage(interrupted);\n return classifyRetainedProcessPollResult(interrupted, process.providerSessionId, session);\n } catch (error) {\n if (isProviderSandboxGoneDuringRoutedOperation(client.backendId, error)) {\n if (process.providerBackend === \"modal\" && !process.providerBindingKey) {\n return { status: \"deferred\", reason: \"provider_binding_missing\" };\n }\n return {\n status: \"proved\",\n proof: {\n outcome: \"lost\",\n exitCode: null,\n reason: \"provider_instance_not_found\",\n },\n };\n }\n return {\n status: \"deferred\",\n reason: error === RETAINED_PROCESS_PROBE_TIMEOUT ? \"provider_timeout\" : \"provider_error\",\n };\n }\n }\n return observation;\n}\n\n/** Classify only exact SDK control banners. Arbitrary output, malformed text,\n * and a running marker are observations to retry; none is physical exit proof. */\nexport function classifyRetainedProcessPollResult(\n result: unknown,\n providerSessionId: number,\n source?: object,\n): RetainedProcessProbeResult {\n if (typeof result !== \"string\") {\n return { status: \"deferred\", reason: \"provider_unknown\" };\n }\n if (isExecSessionLostBanner(result, providerSessionId, source)) {\n return {\n status: \"proved\",\n proof: {\n outcome: \"lost\",\n exitCode: null,\n reason: \"provider_session_lost_banner\",\n },\n };\n }\n const exitCode = parseExecBannerExitCode(result);\n if (exitCode !== null) {\n return {\n status: \"proved\",\n proof: { outcome: \"exited\", exitCode, reason: \"provider_exit_banner\" },\n };\n }\n return {\n status: \"deferred\",\n reason: result.includes(\"Process running with session ID\")\n ? \"provider_running\"\n : \"provider_unknown\",\n };\n}\n\n/**\n * The reaper-tick warm-meter pass (P2.1). Accrues warm-seconds for every WARM\n * viewer-only lease cross-workspace (the list fn excludes turn-held boxes — those\n * meter on the turn heartbeat). Returns the count accrued + the distinct\n * workspaces touched (so the force-drain pass only checks workspaces that have a\n * live warm box, not the whole fleet). Per-row best-effort: one row's metering\n * error must not abort the sweep.\n */\nasync function accrueWarmTick(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n observability: ActivityServices[\"observability\"],\n): Promise<{ accrued: number; workspaceIds: Set<string> }> {\n const workspaceIds = new Set<string>();\n let accrued = 0;\n let leases: MeterableWarmLease[] = [];\n try {\n leases = await listMeterableWarmLeases(db);\n } catch (error) {\n observability.warn(\"sandbox reaper: warm-lease read failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return { accrued, workspaceIds };\n }\n for (const lease of leases) {\n workspaceIds.add(lease.workspaceId);\n }\n await forEachWithConcurrency(leases, SANDBOX_MAINTENANCE_ITEM_CONCURRENCY, async (lease) => {\n try {\n const rate =\n settings.sandboxWarmBillingMode === \"usage_only\"\n ? 0\n : sandboxWarmRateMicrosPerSecond(settings, lease.backend);\n const result = await accrueWarmSeconds(db, {\n accountId: lease.accountId,\n workspaceId: lease.workspaceId,\n sandboxGroupId: lease.sandboxGroupId,\n expectedEpoch: lease.leaseEpoch,\n warmRateMicrosPerSecond: rate,\n billingMode: settings.sandboxWarmBillingMode,\n subjectId: lease.sandboxGroupId,\n });\n if (result.accrued) {\n accrued += 1;\n }\n if (result.costMicros > 0 && settings.sandboxWarmBillingMode === \"credits\") {\n recordCreditMicros(observability, \"usage\", result.costMicros);\n }\n } catch (error) {\n observability.warn(\"sandbox reaper: warm-seconds accrual failed for lease\", {\n workspaceId: lease.workspaceId,\n sandboxGroupId: lease.sandboxGroupId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n });\n return { accrued, workspaceIds };\n}\n\nasync function refreshQueueLeaseAndCreditGauges(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n observability: ActivityServices[\"observability\"],\n inspectOpenSandboxInventory: InspectOpenSandboxKubernetesInventoryFn,\n): Promise<void> {\n await Promise.all([\n (async () => {\n try {\n recordTurnsQueuedGauge(observability, await countQueuedTurns(db));\n } catch (error) {\n observability.warn(\"sandbox reaper: queued-turn gauge refresh failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n })(),\n refreshSandboxInventoryGauge(observability, \"leases\", \"sandbox-lease\", async () => {\n recordSandboxLeaseGauges(observability, await countSandboxLeasesByLiveness(db));\n }),\n refreshSandboxInventoryGauge(\n observability,\n \"checkpoint_artifacts\",\n \"checkpoint-artifact\",\n async () => {\n recordSandboxCheckpointArtifactGauges(\n observability,\n await countSandboxCheckpointArtifactsByState(db),\n );\n },\n ),\n refreshSandboxInventoryGauge(\n observability,\n \"recovery_observations\",\n \"recovery-observations\",\n async () => {\n recordSandboxRecoveryObservationGauges(\n observability,\n await readRecentSandboxRecoveryObservations(db),\n );\n },\n ),\n refreshSandboxInventoryGauge(\n observability,\n \"rotation_backlog\",\n \"rotation-backlog\",\n async () => {\n recordSandboxRotationBacklogGauges(observability, await readSandboxRotationBacklog(db));\n },\n ),\n refreshSandboxInventoryGauge(\n observability,\n \"retained_processes\",\n \"retained-process\",\n async () => {\n recordRetainedProcessInventoryGauges(\n observability,\n await countActiveRetainedProcessesByOwnerState(db),\n );\n },\n ),\n refreshSandboxInventoryGauge(observability, \"expired_drains\", \"expired-draining\", async () => {\n recordExpiredDrainingSandboxLeaseGauges(\n observability,\n await countExpiredDrainingSandboxLeases(db),\n );\n }),\n ...(settings.sandboxBackend === \"opensandbox\" &&\n settings.openSandboxKubernetesInventoryNamespace\n ? [\n refreshSandboxInventoryGauge(\n observability,\n \"opensandbox_kubernetes\",\n \"OpenSandbox Kubernetes\",\n async () => {\n recordOpenSandboxKubernetesInventoryGauges(\n observability,\n await inspectOpenSandboxInventory({\n namespace: settings.openSandboxKubernetesInventoryNamespace!,\n }),\n );\n },\n ),\n ]\n : []),\n (async () => {\n try {\n recordCreditBalanceGauges(observability, await listCreditBalancesByAccount(db));\n } catch (error) {\n observability.warn(\"sandbox reaper: credit-balance gauge refresh failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n })(),\n (async () => {\n try {\n recordActiveUserGauges(observability, await countActiveUsers(db));\n } catch (error) {\n observability.warn(\"sandbox reaper: active-user gauge refresh failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n })(),\n (async () => {\n try {\n recordCreditGrantGauges(observability, await readCreditGrantTotals(db));\n } catch (error) {\n observability.warn(\"sandbox reaper: credit-grant gauge refresh failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n })(),\n (async () => {\n recordVerifiedSignupTrialDeploymentFlagGauge(\n observability,\n settings.verifiedSignupTrialCreditsEnabled,\n );\n try {\n const trialSwitch = await readVerifiedSignupTrialSwitch(db);\n recordVerifiedSignupTrialSwitchGauge(observability, trialSwitch?.grantsEnabled === true);\n } catch (error) {\n observability.warn(\"sandbox reaper: trial-credit switch gauge refresh failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n })(),\n ]);\n}\n\nasync function refreshSandboxInventoryGauge(\n observability: ActivityServices[\"observability\"],\n domain: SandboxInventoryProjectionDomain,\n diagnosticName: string,\n refresh: () => Promise<void>,\n): Promise<void> {\n try {\n await refresh();\n recordSandboxInventoryProjectionSuccess(observability, domain);\n } catch (error) {\n recordSandboxInventoryProjectionFailure(observability, domain);\n observability.warn(`sandbox reaper: ${diagnosticName} gauge refresh failed`, {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * The per-workspace warm-cap + force-drain pass (P2.1). For each workspace with a\n * live warm box, under the usage lock: if it is over its optional warm cap,\n * accelerate only holderless boxes to draining\n * (guarded turn_holders=0 — a paying turn is never killed). Returns the count of\n * viewer-only boxes force-drained. Per-workspace best-effort.\n */\nasync function forceDrainOverLimitWorkspaces(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n workspaceIds: Set<string>,\n observability: ActivityServices[\"observability\"],\n): Promise<number> {\n const enforceBalance = false;\n const cap = settings.sandboxMaxWarmSecondsPerWorkspace;\n let forceDrained = 0;\n await forEachWithConcurrency(\n [...workspaceIds],\n SANDBOX_MAINTENANCE_ITEM_CONCURRENCY,\n async (workspaceId) => {\n try {\n const result = await forceDrainOverLimitViewerOnlyBoxes(db, {\n workspaceId,\n enforceBalance,\n maxWarmSecondsPerWorkspace: cap,\n idleGraceMs: settings.sandboxIdleGraceMs,\n });\n if (result.overLimit && result.drained.length > 0) {\n forceDrained += result.drained.length;\n observability.info(\"sandbox reaper: force-drained viewer-only boxes (over limit)\", {\n workspaceId,\n reason: result.reason,\n drained: result.drained.length,\n });\n }\n } catch (error) {\n observability.warn(\"sandbox reaper: force-drain check failed for workspace\", {\n workspaceId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n },\n );\n return forceDrained;\n}\n\nexport async function reconcileModalProviderCreates(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n observability: ActivityServices[\"observability\"],\n discover: typeof findModalProviderCreateReceipt = findModalProviderCreateReceipt,\n): Promise<void> {\n if (settings.sandboxBackend !== \"modal\" && !settings.modalTokenId && !settings.modalTokenSecret)\n return;\n const candidates = await listPendingModalProviderCreates(db);\n await forEachWithConcurrency(candidates, 2, async (candidate) => {\n try {\n const { accountId } = await rlsContextForWorkspace(db, candidate.workspaceId);\n const identity = { ...candidate, accountId };\n const attempt = await claimModalProviderCreateRecovery(db, identity);\n if (!attempt) return;\n const instanceId = await discover(settings, attempt);\n if (!instanceId) return; // Absence never settles an unknown dispatch.\n if (await recordRecoveredModalProviderCreate(db, { ...identity, attempt, instanceId })) {\n observability.info(\"sandbox reaper: recovered Modal create receipt\", {\n ...candidate,\n operationId: attempt.operationId,\n instanceId,\n });\n }\n } catch (error) {\n observability.warn(\"sandbox reaper: Modal create remains fenced pending discovery\", {\n ...candidate,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n });\n}\n\nexport function modalOrphanTerminationStillEligible(\n latest: Awaited<ReturnType<typeof listLiveModalSandboxLeaseAttributions>>,\n candidate: ModalOrphanSweepTermination,\n): boolean {\n // The provider may have accepted a create whose reply has not arrived.\n // Before attribution, neither its ID nor its separately-applied tags are\n // available here. Postpone orphan deletion while any such owner exists;\n // age/absence cannot distinguish its provider from an abandoned one.\n if (latest.some((lease) => lease.liveness === \"warming\" && lease.instanceId === null)) {\n return false;\n }\n if (latest.some((lease) => lease.instanceId === candidate.sandboxId)) {\n return false;\n }\n\n const leaseId = candidate.tags.opengeni_lease_id;\n const workspaceId = candidate.tags.opengeni_workspace_id;\n const sandboxGroupId = candidate.tags.opengeni_sandbox_group_id;\n if (!leaseId || !workspaceId || !sandboxGroupId) {\n return true;\n }\n const activeAttribution = latest.find(\n (lease) =>\n lease.leaseId === leaseId &&\n lease.workspaceId === workspaceId &&\n lease.sandboxGroupId === sandboxGroupId,\n );\n return Boolean(\n !activeAttribution ||\n (activeAttribution.instanceId !== null && activeAttribution.instanceId !== candidate.sandboxId),\n );\n}\n\nasync function sweepModalOrphansForConfiguredBackend(\n settings: ActivityServices[\"settings\"],\n db: ActivityServices[\"db\"],\n observability: ActivityServices[\"observability\"],\n): Promise<number> {\n // Keep the provider-side sweep tightly scoped to deployments that have a Modal\n // app path configured. Local/docker-only workers should not attempt Modal API\n // calls just because modalAppName has a default.\n if (settings.sandboxBackend !== \"modal\" && !settings.modalTokenId && !settings.modalTokenSecret) {\n return 0;\n }\n let liveLeases: Awaited<ReturnType<typeof listLiveModalSandboxLeaseAttributions>>;\n try {\n liveLeases = await listLiveModalSandboxLeaseAttributions(db);\n } catch (error) {\n observability.warn(\"sandbox reaper: live Modal lease attribution read failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return 0;\n }\n\n const result = await sweepModalOrphanSandboxes(settings, liveLeases, {\n revalidateTermination: async (candidate) => {\n const latest = await listLiveModalSandboxLeaseAttributions(db);\n return modalOrphanTerminationStillEligible(latest, candidate);\n },\n });\n for (const terminated of result.terminated) {\n observability.warn(\"sandbox reaper: terminated Modal orphan sandbox\", {\n sandboxId: terminated.sandboxId,\n reason: terminated.reason,\n tags: JSON.stringify(terminated.tags),\n });\n }\n if (result.examined > 0) {\n observability.info(\"sandbox reaper: Modal orphan sweep completed\", {\n examined: result.examined,\n terminated: result.terminated.length,\n skipped: result.skipped,\n appName: settings.modalAppName,\n });\n }\n return result.terminated.length;\n}\n\n/**\n * A capture claim whose owning worker disappeared must not fence a workspace\n * forever. The drain reaper reaches this seam only after every holder is gone.\n * It resumes the exact attributed provider without replacement and proves that\n * a no-op command can execute. This distinguishes typed provider loss from a\n * still-addressable instance; it does not prove that an old capture RPC has\n * stopped. The caller applies the provider's durable takeover policy and the\n * claim deadline. Ambiguity preserves the old claim and therefore the files.\n */\nasync function probeDrainableProviderReadiness(\n settings: ActivityServices[\"settings\"],\n lease: LeaseSnapshot,\n): Promise<\"ready\" | \"missing\"> {\n if (!lease.instanceId || !lease.resumeState) {\n throw new Error(\"Expired workspace capture has no resumable provider identity\");\n }\n const durableBackendId = (lease.resumeBackendId ?? lease.backend) as string;\n const backend = sandboxBackendForSdkBackendId(durableBackendId) ?? durableBackendId;\n let established: Awaited<ReturnType<typeof establishSandboxSessionFromEnvelope>>;\n try {\n established = await establishSandboxSessionFromEnvelope(settings, lease.resumeState, {\n sessionId: `sandbox-capture-recovery:${lease.sandboxGroupId}`,\n recovery: \"resume-only\",\n backendOverride: backend as never,\n });\n } catch (error) {\n if (isProviderSandboxNotFoundError(backend, error)) return \"missing\";\n throw error;\n }\n if (established.instanceId !== lease.instanceId) {\n throw new Error(\"Expired workspace capture resumed a different provider instance\");\n }\n try {\n if (established.backendId === \"modal\") {\n await verifySandboxExecReadiness(established, RETAINED_PROCESS_PROVIDER_PROBE_TIMEOUT_MS);\n return \"ready\";\n }\n const session = established.session as {\n exec?: (args: {\n cmd: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<unknown>;\n execCommand?: (args: {\n cmd: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<unknown>;\n };\n const run = session.exec ?? session.execCommand;\n if (!run) throw new Error(\"Expired workspace capture provider has no readiness command\");\n let timer: ReturnType<typeof setTimeout> | undefined;\n const result = await Promise.race([\n run.call(session, {\n cmd: \"true\",\n yieldTimeMs: 1_000,\n maxOutputTokens: 1_000,\n }),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(\"Expired workspace capture readiness probe timed out\")),\n RETAINED_PROCESS_PROVIDER_PROBE_TIMEOUT_MS,\n );\n }),\n ]).finally(() => {\n if (timer) clearTimeout(timer);\n });\n if (sandboxCommandStillRunning(result) || sandboxCommandExitCode(result) !== 0) {\n throw new Error(\"Expired workspace capture provider is not command-ready\");\n }\n return \"ready\";\n } catch (error) {\n if (isProviderSandboxNotFoundError(backend, error)) return \"missing\";\n throw error;\n }\n}\n\nexport type SandboxDrainReason =\n | \"idle\"\n | \"provider_deadline\"\n | \"operator\"\n | \"teardown_claim\"\n | \"rotation_requested\";\n\n/** The bounded drain reason carried on `sandbox.box.terminated`: the lease's\n * rotation reason when a rotation was requested, otherwise the ordinary idle\n * drain. A requested rotation without a recorded reason (legacy rows) is\n * reported as `rotation_requested` rather than guessed. */\nexport function sandboxDrainReason(\n lease: Pick<LeaseSnapshot, \"rotationRequestedAt\" | \"rotationReason\">,\n): SandboxDrainReason {\n if (lease.rotationRequestedAt === null) return \"idle\";\n return lease.rotationReason ?? \"rotation_requested\";\n}\n\n/**\n * Terminate one drainable box by id, then CAS its lease draining->cold under the\n * epoch fence. Returns true when the lease went cold (the box is ours to stop\n * and was stopped), false when a concurrent sweep / re-arm / newer epoch means\n * we must NOT stop it (provider terminate is skipped).\n *\n * The ordering is deliberately receipt-gated on BOTH ends:\n * - BEFORE provider I/O: re-read the exact draining epoch and acquire/retain\n * its durable capture/teardown claim. Before that claim an arrival may\n * re-arm for availability; afterward every arrival waits and cannot race\n * provider termination.\n * - AFTER provider terminate: confirmDrainCold commits only the exact current\n * capture id together with draining->cold. A miss means a recovery attempt\n * or epoch already replaced this callback; it says nothing about provider\n * liveness, so only that durable successor may reconcile and commit cold.\n */\nasync function terminateDrainableBox(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n row: ReapDrainable,\n observability: ActivityServices[\"observability\"],\n terminateBox: TerminateBoxFn,\n probeDrainableProvider: DrainableProviderProbeFn,\n attempt: SandboxDrainCaptureAttempt,\n objectStorage: ObjectStorage | null,\n): Promise<boolean> {\n // Resolve the account for the RLS-scoped confirmDrainCold (the global sweep\n // returns no account_id; the workspace->account map is the bootstrap read).\n const { accountId } = await rlsContextForWorkspace(db, row.workspaceId);\n\n // Re-read the lease for the resume envelope AND the pre-terminate CAS guard.\n const lease = await readLease(db, row.workspaceId, row.sandboxGroupId);\n if (!lease) {\n // Lease vanished (cold-reaped by a concurrent sweep). Nothing to stop.\n return false;\n }\n if (\n lease.liveness !== \"draining\" ||\n (lease.refcount !== 0 && !lease.unobservableCommandDrainIds?.length) ||\n lease.leaseEpoch !== row.leaseEpoch\n ) {\n // Re-armed (warm again) / a newer epoch / already drained by a concurrent\n // sweep. Skip — provider stop() must fire ONLY past the drain grace at\n // refcount=0 on the box we observed, never while a turn or viewer holds it.\n return false;\n }\n\n const durableBackendId = (lease.resumeBackendId ?? lease.backend) as string;\n const backend = sandboxBackendForSdkBackendId(durableBackendId) ?? durableBackendId;\n const managedProvider = backend !== \"none\" && backend !== \"selfhosted\";\n const capturePolicy = providerWorkspaceCapturePolicy(backend, lease.resumeState);\n if (managedProvider && !capturePolicy) {\n throw new Error(`sandbox backend ${backend} declares no workspace capture policy`);\n }\n if (capturePolicy?.liveInstance === \"replaced\") {\n throw new Error(\n `sandbox backend ${backend} workspace capture would replace the fenced live instance`,\n );\n }\n\n const captureTimeoutMs = attempt.captureTimeoutMs;\n let captureClaim:\n | NonNullable<\n Extract<Awaited<ReturnType<typeof claimWorkspaceArchiveCapture>>, { status: \"claimed\" }>\n >[\"claim\"]\n | null = null;\n let providerMissingBeforeCapture = false;\n let captureDisposition: DrainCaptureDisposition = \"capture_required\";\n if (lease.instanceId && managedProvider) {\n if (lease.archiveCapture) {\n const priorCapture = lease.archiveCapture;\n const instanceId = lease.instanceId;\n if (priorCapture.publishedAt) {\n // Publication is an irreversible durable phase transition. The archive\n // already represents this exact fenced generation, so a crash/retry\n // resumes teardown immediately: no deadline wait, provider probe, claim\n // replacement, or duplicate snapshot request.\n captureClaim = {\n ...priorCapture,\n leaseId: lease.id,\n leaseEpoch: lease.leaseEpoch,\n instanceId,\n archiveGeneration: lease.archiveGeneration,\n archiveComplete: lease.archiveComplete,\n };\n captureDisposition = \"archive_published\";\n } else {\n if (\n priorCapture.operationId === attempt.operationId &&\n priorCapture.attempt >= attempt.attempt\n ) {\n // Never let an accepted duplicate/stale delivery complete the durable\n // child while its exact claim still fences the lease. Throwing asks\n // Temporal for a strictly newer attempt; an actually stale task token is\n // rejected by Temporal and cannot affect the workflow either way.\n throw new SandboxDrainRecoveryDeferredError(\n `sandbox ${row.sandboxGroupId} capture ${priorCapture.id} is owned by attempt ${priorCapture.attempt}`,\n );\n }\n const deadlineExpired = await workspaceArchiveCaptureDeadlineElapsed(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n captureId: priorCapture.id,\n expectedEpoch: row.leaseEpoch,\n expectedInstanceId: instanceId,\n });\n const unpublishedWarmingProvider =\n backend === \"modal\" &&\n !sandboxProviderInstanceIdFromEnvelope(lease.resumeState, backend) &&\n lease.recovery.provider.status === \"creating\" &&\n lease.recovery.provider.instanceId === instanceId &&\n lease.recovery.workspace.status === \"not_ready\";\n // Temporal knows that the prior activity attempt is no longer accepted,\n // but it cannot generically cancel provider I/O. Immediate replacement is\n // legal only when BOTH the durable claim and the current adapter declare\n // takeover safety: either the same idempotent request, or an independently\n // repeatable read-only capture. A readiness probe alone never proves an\n // unrelated exclusive snapshot RPC has settled.\n const replace = async () =>\n await replaceWorkspaceArchiveCaptureAfterProof(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n priorCaptureId: priorCapture.id,\n captureId: attempt.captureId,\n operationId: attempt.operationId,\n attempt: attempt.attempt,\n expectedEpoch: row.leaseEpoch,\n expectedInstanceId: instanceId,\n captureTimeoutMs,\n });\n\n // If no durable complete archive exists, replacement is safe only when\n // this exact provider can be recaptured. A typed missing provider before\n // the old deadline may mean the dead worker still holds the sole archive\n // bytes in memory, so preserve its callback until that bounded window.\n const currentTakeoverSafe =\n capturePolicy !== null && capturePolicy.takeover !== \"exclusive\";\n if (!lease.resumeState) {\n if (unpublishedWarmingProvider && priorCapture.takeoverSafe && currentTakeoverSafe) {\n const replacement = await replace();\n if (!replacement) {\n throw new SandboxDrainRecoveryDeferredError(\n `sandbox ${row.sandboxGroupId} capture ${priorCapture.id} changed during safe warming takeover`,\n );\n }\n captureClaim = replacement;\n } else {\n if (!deadlineExpired) {\n throw new SandboxDrainRecoveryDeferredError(\n `sandbox ${row.sandboxGroupId} capture ${priorCapture.id} is still within its recovery window`,\n );\n }\n if (!unpublishedWarmingProvider) {\n throw new SandboxDrainRecoveryDeferredError(\n `sandbox ${row.sandboxGroupId} capture ${priorCapture.id} has no resumable provider state`,\n );\n }\n // Legacy/unrelated owner on a never-published Modal warming box. Its\n // deadline elapsed and no user-visible workspace ever existed. Fence\n // the old callback before the by-id termination below.\n const replacement = await replace();\n if (!replacement) {\n throw new SandboxDrainRecoveryDeferredError(\n `sandbox ${row.sandboxGroupId} capture ${priorCapture.id} changed during warming takeover`,\n );\n }\n captureClaim = replacement;\n }\n } else if (priorCapture.takeoverSafe && currentTakeoverSafe) {\n // The stable lineage reuses the exact external idempotency key where\n // supported. Parallel-read adapters may instead recapture independently;\n // both cases preserve the addressed instance and cannot overlap writes.\n const replacement = await replace();\n if (!replacement) {\n throw new SandboxDrainRecoveryDeferredError(\n `sandbox ${row.sandboxGroupId} takeover-safe capture ${priorCapture.id} changed during takeover`,\n );\n }\n captureClaim = replacement;\n } else {\n if (!deadlineExpired) {\n throw new SandboxDrainRecoveryDeferredError(\n `sandbox ${row.sandboxGroupId} capture ${priorCapture.id} is still within its recovery window`,\n );\n }\n const providerState = await probeDrainableProvider(settings, lease);\n if (providerState === \"missing\") {\n // Take over on the DB clock before committing loss. This fences an\n // old teardown callback. Its provider-request lineage remains\n // durable so a verified late archive can still repair the cold row.\n const replacement = await replace();\n if (!replacement) {\n throw new SandboxDrainRecoveryDeferredError(\n `sandbox ${row.sandboxGroupId} capture ${priorCapture.id} changed during missing-provider takeover`,\n );\n }\n providerMissingBeforeCapture = true;\n captureClaim = replacement;\n } else {\n // An exclusive provider operation can outlive both its Temporal\n // activity and its diagnostic deadline. A live command channel says\n // nothing about whether that operation is still reading/pausing the\n // workspace. Keep the durable fence; an operator/provider-specific\n // receipt is required to resolve this deliberately fail-closed case.\n throw new SandboxDrainRecoveryDeferredError(\n `sandbox ${row.sandboxGroupId} exclusive capture ${priorCapture.id} remains ambiguous on a live provider`,\n );\n }\n }\n }\n } else {\n const claimed = await claimWorkspaceArchiveCapture(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n captureId: attempt.captureId,\n operationId: attempt.operationId,\n attempt: attempt.attempt,\n expectedEpoch: row.leaseEpoch,\n expectedInstanceId: lease.instanceId,\n liveness: \"draining\",\n captureTimeoutMs,\n minIntervalMs: 0,\n providerReplaySafe: capturePolicy?.takeover === \"same_request\",\n takeoverSafe: capturePolicy !== null && capturePolicy.takeover !== \"exclusive\",\n });\n if (claimed.status === \"claimed\") {\n captureClaim = claimed.claim;\n } else if (claimed.status === \"mutation_in_progress\") {\n // An admission is normally authoritative proof that a provider\n // operation may still be running. It cannot, however, pin a draining\n // lease forever after the exact provider has disappeared. Probe the\n // attributed instance without replacement. Only typed NotFound permits\n // the cold commit to reject the exact stale admissions; a live or\n // ambiguous provider remains fenced for a later sweep.\n const providerState = await probeDrainableProvider(settings, lease);\n if (providerState !== \"missing\") return false;\n providerMissingBeforeCapture = true;\n } else if (claimed.status === \"capture_in_progress\") {\n // A legacy activity or a racing delivery installed the durable claim.\n // Its owner may still complete; this child remains the repair owner if\n // it does not. Completing here would recreate a schedule-sized gap.\n throw new SandboxDrainRecoveryDeferredError(\n `sandbox ${row.sandboxGroupId} acquired a concurrent capture owner`,\n );\n } else {\n return false;\n }\n }\n }\n\n // The epoch-fenced PERSIST-onto-lease CAS the terminate seam calls AFTER it has\n // snapshotted the live box and BEFORE it terminates (sandbox-file-persistence).\n // Same exact lease/capture guard as confirmDrainCold. A stale capture owner or\n // newer epoch writes ZERO rows → wrote:false → the seam leaves the box RUNNING\n // and skips the cold-commit below.\n // `persisted` tracks whether a real archive landed on the lease this drain —\n // the durable sandbox.box.terminated event below carries it, so a \"terminated\n // with NOTHING persisted\" (box already dead at drain) is visible in the DB.\n let persisted = captureDisposition === \"archive_published\";\n let archiveRevision: string | null =\n captureDisposition === \"archive_published\"\n ? (lease.recovery.archive.current?.revision ?? null)\n : null;\n const persistArchive: PersistArchiveFn = async (\n archiveBase64: string | VerifiedHostWorkspaceArchive | null,\n archiveMetadata?: WorkspaceArchiveDescriptor,\n _providerSession?: unknown,\n providerBinding?: Awaited<\n ReturnType<typeof resolveModalCheckpointProviderBindingForSession>\n > | null,\n ) => {\n // A live persistable provider must own the exact durable capture claim.\n // Without it we cannot prove that these bytes came from a provider that was\n // admission-fenced for the full pause/capture interval.\n if (!lease.instanceId || !captureClaim) {\n return { wrote: false, archiveRevision: null };\n }\n const archiveMetrics = runtimeMetricsHooksForObservability(observability);\n let checkpointArtifactId: string | null = null;\n if (\n typeof archiveBase64 === \"string\" &&\n archiveBase64 &&\n archiveMetadata?.version === 2 &&\n (archiveMetadata.provider === \"modal_snapshot_filesystem\" ||\n archiveMetadata.provider === \"modal_snapshot_directory\")\n ) {\n if (!providerBinding) {\n throw new Error(\"Modal native snapshot has no exact session provider identity\");\n }\n const candidate = await registerSandboxCheckpointArtifact(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n sourceLeaseId: lease.id,\n sourceLeaseEpoch: row.leaseEpoch,\n sourceInstanceId: lease.instanceId,\n sourceWorkspaceGeneration: captureClaim.workspaceGeneration,\n providerBindingKey: providerBinding.key,\n providerBinding: providerBinding.binding,\n workspaceArchive: archiveBase64,\n workspaceArchiveMeta: archiveMetadata,\n });\n checkpointArtifactId = candidate.id;\n }\n const baseInput = {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n expectedLeaseId: lease.id,\n expectedEpoch: row.leaseEpoch,\n expectedInstanceId: lease.instanceId,\n expectedWorkspaceGeneration: captureClaim.workspaceGeneration,\n captureId: captureClaim.id,\n providerRequestId: captureClaim.providerRequestId,\n };\n let result: Awaited<ReturnType<typeof persistDrainSnapshot>>;\n if (archiveBase64 === null) {\n result = await persistDrainSnapshot(db, {\n ...baseInput,\n workspaceArchive: null,\n });\n } else {\n if (!archiveMetadata) {\n throw new Error(\"Sandbox snapshot publication requires a verified archive descriptor\");\n }\n const published = await putVersion1TarArchiveOrInline({\n backend: lease.backend,\n objectStorage,\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n archive:\n typeof archiveBase64 === \"object\"\n ? archiveBase64\n : {\n bytes: Buffer.from(archiveBase64, \"base64\"),\n descriptor: archiveMetadata,\n base64: archiveBase64,\n },\n metrics: archiveMetrics,\n });\n result = await persistWorkspaceArchiveCandidate({\n objectStorage,\n ...(published.workspaceArchiveRef ? { ref: published.workspaceArchiveRef } : {}),\n persist: () =>\n persistDrainSnapshot(db, {\n ...baseInput,\n workspaceArchiveMeta: archiveMetadata,\n ...published,\n ...(checkpointArtifactId ? { checkpointArtifactId } : {}),\n }),\n });\n }\n if (!result.wrote && checkpointArtifactId) {\n await markSandboxCheckpointArtifactDeletePending(db, {\n accountId,\n workspaceId: row.workspaceId,\n artifactId: checkpointArtifactId,\n reason: \"drain_snapshot_publication_fenced\",\n }).catch(() => undefined);\n }\n if (result.wrote && archiveBase64 !== null) {\n persisted = true;\n archiveRevision = result.archiveRevision;\n }\n return result;\n };\n\n // Resume-by-id -> verified capture -> persist-onto-lease -> provider\n // terminate. Persisting atomically hands any displaced provider snapshot to\n // the provider-bound artifact ledger; its global GC worker owns deletion.\n // Definitive NotFound before capture is a typed loss, not ordinary teardown\n // success: confirmDrainCold preserves any prior archive or marks recovery\n // unrecoverable when none exists. A genuine capture/resume failure leaves the\n // lease draining for a later sweep (NEVER terminate a box whose files we\n // could not capture). A persist CAS miss means the box was re-armed and left\n // running, so the cold commit is skipped.\n // A published capture retry skips persistence. Revalidate legacy containment\n // even on that path: stale enrollment is not native-supervisor exit proof.\n // Typed provider absence is independently fenced by the canonical loss commit.\n if (\n !providerMissingBeforeCapture &&\n backend === \"modal\" &&\n lease.instanceId &&\n !(await readWorkspaceArchiveCapturePreflight(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n expectedEpoch: row.leaseEpoch,\n expectedInstanceId: lease.instanceId,\n liveness: \"draining\",\n }))\n ) {\n return false;\n }\n // Stamp the charge horizon after verified capture and immediately before\n // provider stop. Capture can fail and release its claim, allowing re-arm.\n // A retry after stop success cannot charge post-termination wall time.\n let stopCutoffMarked = false;\n const beforeProviderStop = async (): Promise<void> => {\n const cutoff = await markWarmBillingStopCutoff(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n expectedEpoch: row.leaseEpoch,\n });\n if (!cutoff) throw new Error(\"sandbox stop cutoff was fenced before provider termination\");\n stopCutoffMarked = true;\n };\n const termination: ProviderTerminationOutcome | boolean = providerMissingBeforeCapture\n ? { terminated: true, providerMissingBeforeCapture: true }\n : await terminateBox(\n settings,\n lease,\n observability,\n persistArchive,\n captureClaim?.providerRequestId ?? attempt.operationId,\n captureDisposition,\n capturePolicy,\n Boolean(objectStorage),\n async () => {\n if (!captureClaim || !lease.instanceId) return;\n await releaseWorkspaceArchiveCapture(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n captureId: captureClaim.id,\n expectedEpoch: row.leaseEpoch,\n expectedInstanceId: lease.instanceId,\n });\n },\n row.workspaceId,\n beforeProviderStop,\n );\n const terminated = typeof termination === \"boolean\" ? termination : termination.terminated;\n if (!terminated) {\n return false;\n }\n\n // Self-hosted/none and an unassigned lease have no provider stop callback;\n // finish their usage at logical detach without touching customer compute.\n // A managed instance that was stopped without its callback must fail closed.\n const providerMissingDuringStop =\n providerMissingBeforeCapture ||\n (typeof termination !== \"boolean\" && termination.providerMissingBeforeCapture);\n if (!stopCutoffMarked && !providerMissingDuringStop) {\n if (managedProvider && lease.instanceId) {\n throw new Error(\"managed sandbox stopped without a warm usage cutoff\");\n }\n await beforeProviderStop();\n }\n\n // Stop was confirmed but the lease is not cold yet. This final epoch-fenced\n // tick settles the interval since the last heartbeat/reaper sweep, including\n // a box drained before its first periodic tick. If settlement fails, keep\n // the draining receipt for retry instead of silently losing the charge.\n const finalRate =\n settings.sandboxWarmBillingMode === \"usage_only\"\n ? 0\n : sandboxWarmRateMicrosPerSecond(settings, backend);\n if (!providerMissingDuringStop) {\n const finalTick = await accrueWarmSeconds(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n expectedEpoch: row.leaseEpoch,\n warmRateMicrosPerSecond: finalRate,\n billingMode: settings.sandboxWarmBillingMode,\n finalDrain: true,\n });\n if (finalTick.costMicros > 0 && settings.sandboxWarmBillingMode === \"credits\") {\n recordCreditMicros(observability, \"usage\", finalTick.costMicros);\n }\n }\n\n const providerMissing =\n providerMissingBeforeCapture ||\n (typeof termination === \"boolean\" ? false : termination.providerMissingBeforeCapture);\n // The authoritative commit clears the durable capture/teardown claim together\n // with draining->cold. Until this succeeds, arrivals remain fenced by that\n // exact claim; a timestamp or a failed provider call can never reopen a box\n // while termination may still be in flight.\n const { wentCold } = await confirmDrainCold(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n expectedEpoch: row.leaseEpoch,\n ...(captureClaim ? { expectedCaptureId: captureClaim.id } : {}),\n providerMissingBeforeCapture: providerMissing,\n });\n if (wentCold) {\n // Only the exact successful cold commit counts provider loss. A missing\n // probe, a stale capture, a failed commit, or a retried child is not another\n // observed loss. Keep this outside the best-effort session event writer.\n if (providerMissing) {\n recordSandboxProviderMissingBeforeCapture(observability, backend);\n }\n // Durable termination record (sandbox-file-persistence observability): who\n // ended this box and whether its /workspace was captured first, appended to\n // every session sharing the group's box. Best-effort: attribution must\n // never affect the drain outcome.\n try {\n await appendSessionEventToSandboxGroup(db, row.workspaceId, row.sandboxGroupId, {\n type: \"sandbox.box.terminated\",\n payload: {\n actor: \"reaper\",\n persisted,\n archiveRevision,\n instanceId: lease.instanceId,\n providerMissingBeforeCapture: providerMissing,\n // Why the box drained: the lease's bounded rotation reason when one\n // was requested (provider deadline, operator/image conflict, teardown\n // claim), otherwise the ordinary idle drain. Additive diagnostic\n // fact; no identifiers beyond the ones already carried above.\n drainReason: sandboxDrainReason(lease),\n },\n });\n } catch (eventError) {\n observability.warn(\n \"sandbox reaper: box-terminated event write failed (drain outcome unaffected)\",\n {\n sandboxGroupId: row.sandboxGroupId,\n leaseEpoch: row.leaseEpoch,\n backend: lease.backend,\n instanceId: lease.instanceId,\n error: eventError instanceof Error ? eventError.message : String(eventError),\n },\n );\n }\n }\n return wentCold;\n}\n\n// The persist-capable slice of a live provider session. persistWorkspace()\n// snapshots /workspace (snapshot_filesystem → a Modal snapshot-ref; tar → a tar\n// archive) and returns the archive bytes. The session also carries the Modal SDK\n// client used to bind the snapshot receipt to the exact provider namespace.\ntype PersistableSession = {\n state?: { workspacePersistence?: unknown };\n persistWorkspace?: (options?: { requestId: string }) => Promise<Uint8Array | undefined>;\n runPreStopHooks?: () => Promise<void>;\n preStop?: (options?: { reason?: string }) => Promise<void>;\n stop?: (options?: { reason?: string }) => Promise<void>;\n shutdown?: (options?: { reason?: string }) => Promise<void>;\n delete?: (options?: { reason?: string }) => Promise<void>;\n close?: () => Promise<void>;\n};\n\nfunction providerDrainLogIdentity(\n lease: LeaseSnapshot,\n backend: string,\n): {\n leaseId: string;\n sandboxGroupId: string;\n leaseEpoch: number;\n backend: string;\n instanceId: string | null;\n} {\n return {\n leaseId: lease.id,\n sandboxGroupId: lease.sandboxGroupId,\n leaseEpoch: lease.leaseEpoch,\n backend,\n instanceId: lease.instanceId,\n };\n}\n\n/**\n * Resume/attach the box by id, PERSIST its /workspace, fold the snapshot onto the\n * lease under the epoch fence, hand the superseded snapshot to durable GC, THEN\n * terminate. Resumes DIRECTLY (no cold-restore fallback) so a gone box is a clean\n * no-op, never a wasteful create-then-kill:\n * - build the client for the lease's backend;\n * - deserialize + resume the envelope (warm reattach by id, R4-safe);\n * - session.persistWorkspace() -> capture the /workspace archive;\n * - persistArchive(base64) -> CAS-fold it onto the lease and atomically mark\n * the displaced artifact delete-pending;\n * - the provider-bound global GC deletes that object asynchronously;\n * - terminate the live handle through the standard Agents SDK lifecycle.\n *\n * Returns true when the box was terminated (or was already gone), false when the\n * persist CAS found the lease re-armed and the box was deliberately LEFT RUNNING.\n *\n * Failure discipline (NEVER lose files, NEVER leak a box):\n * - resume NotFound -> the box is already down; SUCCESS (return true), nothing\n * to persist, the caller colds the lease.\n * - a transient/auth/network resume failure on a box that may be ALIVE -> throw\n * (the caller skips; the lease stays draining for the next sweep).\n * - a persistWorkspace failure (snapshot timeout / provider error) -> throw\n * BEFORE any terminate, so the box is NOT torn down with un-captured files;\n * the next sweep retries, and the provider idle-timeout is the ultimate\n * backstop. We never terminate a box whose snapshot we could not capture.\n * A provider-backed row with instance_id but no envelope is never guessed away:\n * Modal has an explicit by-id rescue adapter above; every other backend stays\n * draining until its adapter can prove termination. A truly instance-less or\n * `none`-backed row is a no-op.\n */\nexport async function terminateProviderBox(\n settings: ActivityServices[\"settings\"],\n lease: NonNullable<Awaited<ReturnType<typeof readLease>>>,\n observability: ActivityServices[\"observability\"],\n persistArchive: PersistArchiveFn,\n createClientForBackend: CreateSandboxClientForBackendFn = createSandboxClientForBackend,\n terminateModalById: typeof terminateModalSandboxById = terminateModalSandboxById,\n providerCaptureRequestId?: string,\n captureDisposition: DrainCaptureDisposition = \"capture_required\",\n claimedCapturePolicy?: ProviderWorkspaceCapturePolicy | null,\n diskBackedArchives = false,\n releaseFailedCapture?: () => Promise<void>,\n workspaceId?: string,\n beforeProviderStop?: () => Promise<void>,\n): Promise<ProviderTerminationOutcome> {\n const durableBackendId = (lease.resumeBackendId ?? lease.backend) as string;\n const backend = sandboxBackendForSdkBackendId(durableBackendId) ?? durableBackendId;\n const logIdentity = providerDrainLogIdentity(lease, backend);\n const warnCaptureFailure = (message: string, error: unknown): void =>\n warnDrainSnapshotFailure(observability, message, error, {\n sandboxGroupId: lease.sandboxGroupId,\n leaseEpoch: lease.leaseEpoch,\n ...(workspaceId ? { workspaceId } : {}),\n });\n const releaseAfterCaptureFailure = async (): Promise<void> => {\n try {\n await releaseFailedCapture?.();\n } catch (error) {\n warnCaptureFailure(\"sandbox reaper: failed capture claim release failed\", error);\n }\n };\n // 'none' / no backend -> nothing to terminate.\n if (!backend || backend === \"none\") {\n return { terminated: true, providerMissingBeforeCapture: false };\n }\n\n // CRITICAL SAFETY (bring-your-own-compute): NEVER provider-stop\n // a selfhosted box. The \"box\" is a user's PHYSICAL machine — you cannot kill it,\n // and a delete()/kill() reaching the agent would be catastrophic. The reaper\n // DRAINS the lease to cold only (refcount→0 → draining → this returns true so\n // the caller's confirmDrainCold flips draining→cold) but issues NO provider stop:\n // no client is built, no resume, no persistWorkspace (the machine IS the\n // persistence — nothing to snapshot), no delete/kill. The session simply detaches;\n // the machine stays up under the agent's own process lifetime (§23.0). Checked on\n // BOTH the lease backend and the resume envelope's backend so neither path leaks.\n if (\n backend === \"selfhosted\" ||\n lease.backend === \"selfhosted\" ||\n lease.resumeBackendId === \"selfhosted\"\n ) {\n observability.info(\n \"sandbox reaper: selfhosted lease drained to cold (NEVER provider-stopped — it is the user's machine)\",\n {\n ...logIdentity,\n },\n );\n return { terminated: true, providerMissingBeforeCapture: false };\n }\n\n const durableCapturePolicy =\n claimedCapturePolicy ?? providerWorkspaceCapturePolicy(backend, lease.resumeState);\n if (!durableCapturePolicy) {\n throw new Error(`sandbox backend ${backend} declares no workspace capture policy`);\n }\n if (durableCapturePolicy.liveInstance !== \"preserved\") {\n throw new Error(\n `sandbox backend ${backend} workspace capture would replace the fenced live instance`,\n );\n }\n\n const persistedInstanceId = assertConsistentSandboxProviderIdentity(backend, lease.resumeState);\n // `instance_id` is the lease's authoritative provider address. A recovery\n // envelope without it is archive/config state, never permission to target a\n // provider inferred only from stale JSON. Conversely, a provider identity in\n // the envelope with no authoritative lease identity is inconsistent state:\n // fail closed instead of silently leaving a live provider behind while the\n // caller commits the lease cold.\n if (!lease.instanceId) {\n if (lease.providerCreateAttempt?.instanceId === null) {\n throw new Error(\n \"provider_create_outcome_unknown: cannot infer termination from missing instance ID\",\n );\n }\n if (persistedInstanceId) {\n throw new Error(\n `sandbox backend ${backend} has persisted provider identity ${persistedInstanceId} but no authoritative lease instance; refusing teardown`,\n );\n }\n return { terminated: true, providerMissingBeforeCapture: false };\n }\n if (persistedInstanceId && persistedInstanceId !== lease.instanceId) {\n throw new Error(\n `sandbox backend ${backend} lease instance ${lease.instanceId} does not match persisted provider identity ${persistedInstanceId}; refusing teardown`,\n );\n }\n\n // A warming-death row can have a provider instance id recorded immediately\n // after create() but no resumable envelope yet. For Modal, instance_id is\n // enough to terminate directly; CAS-check first so a re-arm during the sweep\n // leaves the box running.\n const isUnpublishedWarmingProvider =\n backend === \"modal\" &&\n !persistedInstanceId &&\n lease.recovery.provider.status === \"creating\" &&\n lease.recovery.provider.instanceId === lease.instanceId &&\n lease.recovery.workspace.status === \"not_ready\";\n if (isUnpublishedWarmingProvider) {\n const { wrote } = await persistArchive(null);\n if (!wrote) {\n observability.info(\n \"sandbox reaper: Modal lease re-armed before direct terminate — leaving sandbox RUNNING\",\n {\n ...logIdentity,\n },\n );\n return { terminated: false, providerMissingBeforeCapture: false };\n }\n try {\n await beforeProviderStop?.();\n await terminateModalById(\n settings,\n lease.instanceId,\n undefined,\n lease.providerCreateAttempt?.providerBindingKey,\n );\n } catch (error) {\n if (!isProviderSandboxNotFoundError(\"modal\", error)) {\n throw error;\n }\n observability.info(\"sandbox reaper: Modal sandbox already gone during direct terminate\", {\n ...logIdentity,\n });\n }\n // This branch is a warming-death box recorded before any resumable envelope\n // was published. It was never a ready workspace, so a missing instance does\n // not imply loss of a previously exposed workspace revision.\n return { terminated: true, providerMissingBeforeCapture: false };\n }\n\n // resume_state is the folded group box-envelope (the provider sessionState the\n // box was last persisted as). An attributed provider with no envelope may\n // still be live. Only Modal exposes a verified by-id rescue adapter above;\n // never cold another backend merely because generic resume is impossible.\n if (!persistedInstanceId || !lease.resumeState) {\n throw new Error(\n `sandbox backend ${backend} instance ${lease.instanceId} has no resumable provider envelope; refusing unverified teardown`,\n );\n }\n\n const client = createClientForBackend(backend as never, settings) as\n | DrainSandboxClient\n | undefined;\n if (!client) {\n // 'none' backend resolved to no client.\n return { terminated: true, providerMissingBeforeCapture: false };\n }\n\n // Resume by id (warm reattach) — NO cold-restore. A NotFound here = the box is\n // already gone; success.\n let session: PersistableSession | undefined;\n let sessionState: Parameters<typeof terminateManagedSandboxSession>[1] | undefined;\n try {\n if (!client.resume || !client.deserializeSessionState) {\n // A cloud backend that cannot prove provider state is not safely\n // terminable: treating this as success would cold the lease while the\n // provider may still be live. Leave it draining for a later retry.\n throw new Error(`sandbox backend ${backend} cannot resume a drainable provider box`);\n }\n // resume_state is the lease ENVELOPE: `{ backendId, sessionState: {\n // providerState: { sandboxId, ... }, manifest, ... } }` (the shape\n // serializeEstablishedSandboxEnvelope folds onto the lease). The provider\n // payload deserializeSandboxSessionStateEnvelope re-hydrates is the INNER\n // `sessionState` — pass the WHOLE envelope and it reads `state.providerState`\n // at the top level, finds nothing (providerState is nested under\n // `sessionState`), drops `sandboxId`, and `client.resume(state)` throws\n // \"requires a persisted sandboxId\". This is exactly what the working\n // resume-by-id paths (establishSandboxSessionFromEnvelope) avoid: they unwrap\n // `envelope.sessionState` first. Mirror that. (`?? lease.resumeState` keeps a\n // legacy flat envelope — providerState at the top — resumable too.)\n const envelopeSessionState =\n (lease.resumeState as { sessionState?: unknown }).sessionState ?? lease.resumeState;\n const resumedState = await deserializeSandboxSessionStateEnvelope(\n client as never,\n envelopeSessionState,\n lease.instanceId,\n );\n if (resumedState === undefined) {\n throw new Error(`sandbox backend ${backend} returned no resumable provider state`);\n }\n const continuity = sandboxProviderContinuityForState(backend, resumedState, lease.instanceId);\n const resumed = await resumeExactSandboxSession(\n client,\n backend,\n resumedState,\n lease.instanceId,\n continuity ? { continuity } : undefined,\n );\n session = resumed.session as PersistableSession;\n sessionState = resumed.sessionState;\n } catch (error) {\n if (isProviderSandboxNotFoundError(client.backendId, error)) {\n observability.info(\"sandbox reaper: drainable box already gone before workspace capture\", {\n ...logIdentity,\n });\n return {\n terminated: true,\n providerMissingBeforeCapture: captureDisposition !== \"archive_published\",\n };\n }\n // Re-throw a non-NotFound resume failure so the caller SKIPS (the lease stays\n // draining for the next sweep) — never cold a box we could not prove is gone.\n throw error;\n }\n\n const liveCapturePolicy = providerWorkspaceCapturePolicy(backend, session);\n if (\n !liveCapturePolicy ||\n liveCapturePolicy.takeover !== durableCapturePolicy.takeover ||\n liveCapturePolicy.strategy !== durableCapturePolicy.strategy ||\n liveCapturePolicy.liveInstance !== durableCapturePolicy.liveInstance\n ) {\n throw new Error(\n `sandbox backend ${backend} live workspace capture policy differs from its durable lease contract`,\n );\n }\n\n // PERSIST /workspace BEFORE terminating (sandbox-file-persistence). A failure to\n // snapshot must re-throw BEFORE any terminate so files are never lost — the next\n // sweep retries, the provider idle-timeout is the backstop. A NotFound here (the\n // box raced gone between resume and persist) is success: nothing to persist.\n let verifiedArchive: VerifiedWorkspaceArchivePayload | undefined;\n const sessionWorkspacePersistence = (\n session as { state?: { workspacePersistence?: unknown } } | undefined\n )?.state?.workspacePersistence;\n const checkpointBinding =\n captureDisposition === \"capture_required\" &&\n backend === \"modal\" &&\n (sessionWorkspacePersistence === \"snapshot_filesystem\" ||\n sessionWorkspacePersistence === \"snapshot_directory\")\n ? await withRetainedProcessProbeTimeout(\n resolveModalCheckpointProviderBindingForSession(settings, session),\n )\n : null;\n try {\n if (captureDisposition !== \"archive_published\" && session?.persistWorkspace) {\n const capture = captureWorkspaceArchiveForStorage(\n session,\n Date.now(),\n {\n requestId: providerCaptureRequestId ?? randomUUID(),\n strategy: liveCapturePolicy.strategy,\n },\n diskBackedArchives,\n );\n verifiedArchive = await awaitProviderCaptureWithLatePublication({\n capture,\n timeoutMs: settings.sandboxSnapshotTimeoutMs,\n timeoutError: new SandboxProviderCaptureTimeoutError(\n lease.sandboxGroupId,\n backend,\n settings.sandboxSnapshotTimeoutMs,\n lease.leaseEpoch,\n lease.instanceId,\n ),\n publishLate: async (archive) => {\n try {\n const result = await persistArchive(\n archive.kind === \"host_spool\" ? archive : archive.base64,\n archive.descriptor,\n session,\n checkpointBinding,\n );\n observability.info(\n result.wrote\n ? \"sandbox reaper: late workspace capture published under durable claim\"\n : \"sandbox reaper: late workspace capture fenced by successor\",\n {\n ...logIdentity,\n },\n );\n } catch (error) {\n warnCaptureFailure(\"sandbox reaper: late workspace capture publication failed\", error);\n } finally {\n await disposeWorkspaceArchive(archive);\n }\n },\n observeLatePublicationFailure: (error) => {\n warnCaptureFailure(\"sandbox reaper: late capture publication cleanup failed\", error);\n },\n observeLateFailure: (error) => {\n // Capture has now rejected and this timed-out path can never reach\n // provider teardown. Release only our unpublished claim so a waiting\n // turn can re-arm the intact live box; stale callbacks are DB-fenced.\n void releaseAfterCaptureFailure();\n warnCaptureFailure(\"sandbox reaper: timed-out provider capture later failed\", error);\n },\n });\n }\n } catch (error) {\n if (isProviderSandboxNotFoundError(client.backendId, error)) {\n observability.info(\"sandbox reaper: box gone during workspace capture\", {\n ...logIdentity,\n });\n return { terminated: true, providerMissingBeforeCapture: true };\n }\n warnCaptureFailure(\n \"sandbox reaper: persistWorkspace failed — leaving box draining (files NOT lost)\",\n error,\n );\n // An unresolved timeout is not proof of capture failure: retain the fence\n // until its provider promise settles. A settled failure cannot enter the\n // teardown path below, so its unpublished claim may safely be released.\n if (!(error instanceof SandboxProviderCaptureTimeoutError)) {\n await releaseAfterCaptureFailure();\n }\n // NEVER terminate a box whose snapshot we could not capture.\n throw error;\n }\n\n // Fold the captured archive onto the lease under the exact capture fence, then\n // GC the superseded snapshot. A CAS miss means this callback no longer owns\n // teardown — DO NOT terminate (the caller skips confirmDrainCold).\n //\n // Ownership guard for the no-archive path: even when persistWorkspace returns\n // no bytes, require the exact capture receipt before delete(). The null-archive\n // path performs that CAS without changing archive bytes; wrote:false aborts.\n if (captureDisposition === \"archive_published\") {\n observability.info(\"sandbox reaper: resuming teardown from durable archive publication\", {\n ...logIdentity,\n });\n } else if (verifiedArchive) {\n let wrote: boolean;\n try {\n ({ wrote } = await persistArchive(\n verifiedArchive.kind === \"host_spool\" ? verifiedArchive : verifiedArchive.base64,\n verifiedArchive.descriptor,\n session,\n checkpointBinding,\n ));\n } finally {\n await disposeWorkspaceArchive(verifiedArchive);\n }\n if (!wrote) {\n observability.info(\n \"sandbox reaper: lease re-armed during persist — leaving box RUNNING (no terminate)\",\n {\n ...logIdentity,\n },\n );\n return { terminated: false, providerMissingBeforeCapture: false };\n }\n } else {\n // A resumable cloud box that produces no verified archive cannot be safely\n // deleted: it may contain work newer than the lease's last durable revision.\n // Keep the lease draining and retry instead of knowingly discarding bytes.\n throw new Error(\n `sandbox backend ${backend} produced no verified workspace archive during drain`,\n );\n }\n\n // Provider terminate through the declared Agents SDK lifecycle. A terminate\n // that fails because the box is already gone is success.\n try {\n if (!session || !sessionState) {\n throw new Error(`sandbox backend ${backend} returned no terminable session state`);\n }\n prepareProviderForTeardownAfterCapture(backend, session);\n await beforeProviderStop?.();\n await terminateManagedSandboxSession(client, sessionState, session);\n return { terminated: true, providerMissingBeforeCapture: false };\n } catch (error) {\n if (isProviderSandboxNotFoundError(client.backendId, error)) {\n observability.info(\"sandbox reaper: provider already gone during terminate\", {\n ...logIdentity,\n });\n // Capture was already durably folded above, so this is not a\n // missing-before-capture outcome.\n return { terminated: true, providerMissingBeforeCapture: false };\n }\n throw error;\n }\n}\n","import {\n AUTOMATIC_SESSION_TITLE_FALLBACK,\n DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,\n OPENGENI_SLACK_BOT_CREDENTIAL_LABEL,\n OPENGENI_SLACK_BOT_CREDENTIAL_ROLE,\n OPENGENI_SLACK_BOT_SESSION_METADATA_KEY,\n resolveWorkspaceCodexCompactionDefault,\n SCHEDULED_TASK_OCCURRENCE_PAYLOAD_MAX_BYTES,\n ScheduledTaskRunAcceptedExecution,\n SessionAgentAccess,\n SessionMemoryScope,\n normalizeAutomaticSessionTitle,\n metadataWithTurnExecutionPolicyV1,\n scheduledOccurrencePayloadUtf8Bytes,\n stableJson,\n TurnExecutionPolicyV1,\n type ScheduledTask,\n type ScheduledTaskRun,\n AgentConfigError,\n type ResolvedAgentConfig,\n} from \"@opengeni/contracts\";\nimport {\n openGeniSlackBotMetadata,\n requireOpenGeniSlackBotConnection,\n withScheduledSlackBotPostingTools,\n resolveWorkspaceCatalogSettings,\n resolveScheduledTaskDefaultModel,\n resolveSessionToolPolicy,\n workspaceCustomModelReference,\n lockActiveCustomModelForAdmission,\n scheduledSlackBotConnectionId,\n freezeConnectionAccounts,\n ConnectionAccountSelectionError,\n scheduledConnectionSurfaceEligibility,\n scheduledConnectionTools,\n settingsWithEnabledCapabilityMcpServers,\n settingsWithSessionMcpServerMetadata,\n swapActiveSandbox,\n agentConfigMayResolve,\n applySessionAgentConfigWriteThrough,\n resolveSessionAgentConfigForCreate,\n recordSessionCreated,\n recordUserMessageAccepted,\n type ProductUsageMetricsSink,\n} from \"@opengeni/core\";\nimport {\n appendSessionEvents,\n addSessionSystemUpdateWithSourceMutation,\n bindScheduledTaskRunSessionInTransaction,\n createScheduledTaskRun,\n recordScheduledTaskAdmissionFailure,\n recordScheduledTaskAdmissionRefusal,\n type ScheduledTaskAdmissionRefusalReason,\n createSession,\n createSessionWithIdempotencyKeyResult,\n enqueueSessionWorkflowWakeIfRunnable,\n failScheduledGeneratedSessionRoute,\n getScheduledTask,\n getScheduledTaskCreatorPolicy,\n getScheduledTaskRunAcceptedExecution,\n getScheduledTaskRunByProducerKey,\n getScheduledTargetSessionExecution,\n getScheduledTaskRunPersonalResourceAuthority,\n getScheduledTaskPersonalResourceAuthoritySubject,\n getScheduledTaskRevisionAuthority,\n getScheduledTaskXaiProviderAccountAuthoritySnapshot,\n getEnrollment,\n getSandbox,\n getRig,\n getScheduledScopedRigVersionMetadata,\n getNestedAgentDepthDeploymentPolicy,\n getSessionByCreateIdempotencyKey,\n getSessionCreationExecutionPolicy,\n metadataWithAgentConfigCreateIdentity,\n getVariableSet,\n isCodexBilledModel,\n initializeSessionStartAtomically,\n materializeScheduledTaskReusableSessionFromRun,\n listInstalledApiIntegrationServerIdsForDelegations,\n markScheduledTaskRunFailedIfQueued,\n markScheduledTaskRunSkippedIfQueued,\n recordUsageEvent,\n requireScheduledTaskIncidentAuthorityInTransaction,\n requireSession,\n requireWorkspace,\n settleScheduledTaskRunInTransaction,\n SessionSpawnDeniedDbError,\n updateSessionTitleWithEvent,\n upsertScheduledSessionGoalForRun,\n withSessionActivityRlsContext,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport {\n allowedFirstPartyMcpToolsForSession,\n resolveFirstPartyMcpToolPolicy,\n resolveTurnExecutionPolicyV1,\n} from \"@opengeni/config\";\nimport { Context } from \"@temporalio/activity\";\nimport { createHash } from \"node:crypto\";\nimport {\n assertReusableSessionRevivable,\n scheduledUserMessagePayload,\n workflowIdForSession,\n} from \"./common\";\nimport { withFirstPartyTools } from \"./goals\";\nimport { agentRunAdmissionDenial } from \"./agent-run-admission\";\nimport {\n scheduledAlertOccurrenceIdentity,\n scheduledAlertResponderSessionCreateIdempotencyKey,\n} from \"../scheduled-alert-occurrence\";\nimport {\n evaluateIncidentTelemetryPreflight,\n incidentTelemetryAuthorityFence,\n incidentTelemetryPreflightDeclaration,\n INCIDENT_TELEMETRY_AUTHORITY_FENCE_LINEAGE_KEY,\n type IncidentTelemetryPreflightBlockReason,\n} from \"./incident-telemetry-preflight\";\nimport { resolveIncidentTelemetryResponderMetadata } from \"./incident-telemetry-authority\";\nimport type {\n ControlActivityServices,\n DispatchScheduledTaskRunInput,\n DispatchScheduledTaskRunResult,\n WakeSessionWorkflowSignal,\n} from \"./types\";\nimport type { Database } from \"@opengeni/db\";\n\ntype ScheduledTemporalActivityIdentity = {\n namespace: string;\n workflowExecution?: { workflowId: string; runId: string };\n activityId: string;\n};\n\nexport function scheduledTaskRunExecutionPolicy(\n policy: TurnExecutionPolicyV1,\n input: DispatchScheduledTaskRunInput,\n creatorRestriction?: \"developer_setup\",\n): TurnExecutionPolicyV1 {\n return creatorRestriction === \"developer_setup\" ||\n (input.triggerType !== \"scheduled\" && input.credentialRestriction === \"developer_setup\")\n ? { ...policy, credentialRestriction: \"developer_setup\" }\n : policy;\n}\n\n/** Only a creator ceiling is standing; a manual caller ceiling is per-run. */\nexport function scheduledSessionExecutionPolicyMetadata(\n policy: unknown,\n creatorRestriction?: \"developer_setup\",\n): Record<string, unknown> {\n if (policy === undefined || policy === null) return {};\n const acceptedPolicy = TurnExecutionPolicyV1.parse(policy);\n return creatorRestriction === \"developer_setup\" &&\n acceptedPolicy.credentialRestriction === \"developer_setup\"\n ? metadataWithTurnExecutionPolicyV1({}, acceptedPolicy)\n : {};\n}\n\nexport function scheduledTaskRunProducerKey(\n input: DispatchScheduledTaskRunInput,\n suppliedActivityIdentity?: ScheduledTemporalActivityIdentity,\n): string {\n if (input.producerKey) return input.producerKey;\n if (input.triggerType !== \"scheduled\") return input.agentRunUsageIdempotencyKey;\n\n let info = suppliedActivityIdentity;\n if (!info) {\n try {\n info = Context.current().info;\n } catch {\n throw new Error(\n \"scheduled task delivery without a producer key requires a Temporal activity execution\",\n );\n }\n }\n if (!info.workflowExecution) {\n throw new Error(\"scheduled task Temporal activity is missing its workflow execution identity\");\n }\n return `scheduled-temporal:${stableJson({\n namespace: info.namespace,\n workflowId: info.workflowExecution.workflowId,\n })}`;\n}\n\nexport function scheduledTaskGeneratedSessionCreateIdempotencyKey(producerKey: string): string {\n const digest = createHash(\"sha256\")\n .update(\"scheduled-task-run\\0\", \"utf8\")\n .update(producerKey, \"utf8\")\n .digest(\"hex\");\n return `scheduled-task-run:${digest}`;\n}\n\n/**\n * Display title for a session the scheduler generates for a task.\n *\n * A scheduled session's `initialMessage` is the task prompt, byte-identical for\n * every run. The task name is the short human-chosen label that actually\n * identifies it, so that is the title.\n *\n * The title is the task name and NOTHING else. It deliberately does not name the\n * run's fire instant, for two independent reasons:\n *\n * - No run mode guarantees one run per session. `reusable_session` generates\n * its session on the first fire and then reuses it forever, and even under\n * `new_session_per_run` alert-occurrence redelivery converges several runs\n * onto one canonical responder session. `existing_session` never generates a\n * session at all, so the scheduler never titles one. A run-specific fact\n * frozen into the title is therefore right for the generating run and a lie\n * for every run that lands in the same session afterwards.\n * - A title is one stored string shown to every viewer, while every surface\n * that renders a run's fire instant renders it viewer-local: the rail row\n * prints the title beside `relativeTimeLabel(session.updatedAt)`, and the\n * Schedules run list prints `formatTimestamp(run.firedAt)`, which is\n * `toLocaleString()`. A wall clock stored in the title therefore disagrees\n * with the time printed next to it for every viewer outside whichever zone\n * it was rendered in. The task's own `timeZone` is no escape: it labels the\n * schedule rule (\"Mon Wed 09:00 Europe/Oslo\"), not the rendering of a run,\n * which stays viewer-local. No stored clock can agree with a viewer-local\n * one, so the title carries none and the instant stays on the surfaces that\n * already render it correctly.\n *\n * Dropping the clock settles the determinism constraint outright rather than\n * working around it: the same run titled by the normal dispatch or by a later\n * recovery in a different worker process derives one string from `task.name`\n * alone, with no Intl call and so no host ICU or tzdata build to make the two\n * texts differ.\n */\n/** A scheduler-generated run session: a service-created root session. */\nfunction recordScheduledSessionCreated(observability: ProductUsageMetricsSink | undefined): void {\n recordSessionCreated(observability, {\n surface: \"scheduled\",\n createdByKind: \"service\",\n parentSessionId: null,\n });\n}\n\nexport function scheduledTaskSessionTitle(taskName: string): string {\n return normalizeAutomaticSessionTitle(taskName) ?? \"Scheduled run\";\n}\n\n/**\n * Title a session the scheduler generated, and emit the same `session.title_set`\n * event every other title write in the product emits.\n *\n * This uses the same database operation as `@opengeni/core`\n * `updateSessionTitle`: the clobber/CAS guarded row update and its identical\n * `session.title_set` append commit together under the session event lock. A\n * newer writer therefore cannot land between the authoritative row change and\n * an older event. Without the event a live subscriber sees nothing:\n * `packages/react/src/hooks/use-session.ts` patches an open session's title\n * exclusively on `session.title_set`, so a bare row write leaves the viewer on\n * the stale title until an unrelated refetch.\n *\n * The core wrapper itself is not called, because its only additional behavior is\n * `requireSessionAuthorization(grant, ...)` - a check on an HTTP/MCP caller's\n * grant. The scheduler has no such grant; it is naming a session it just created\n * itself moments earlier. Satisfying that gate would mean fabricating a subject,\n * and the gate would then answer for it: a session later transitioned to\n * `user_private` denies any actor whose subject is not the owner\n * (`packages/core/src/session-authorization.ts`), which would turn naming a\n * session into a way to fail a dispatch. Authorization belongs to callers with\n * grants; the durable write and its event are the part that is shared.\n *\n * Only the neutral create fallback is replaced. A keyed create replay can hand\n * back a session that has already run, and recovery re-enters this path for a\n * session the dead dispatch may already have titled; in both cases whatever the\n * agent or a human chose is newer truth than this stamp. The fallback check is\n * part of the UPDATE itself, not a stale session-object precheck, so a title\n * committed between dispatch read and stamp cannot be overwritten.\n *\n * `source: \"agent\"` is deliberate, and is the only system-assigned value the\n * schema offers (`Session.titleSource` is \"user\" | \"agent\" | null). The database\n * clobber guard pins only a `user` title, so this title still lets the agent\n * rename its own session through set_session_title, and a human rename still\n * wins permanently. Writing \"user\" here would quietly make every scheduled\n * session unrenameable by the agent that runs in it.\n *\n * Returns the appended events so the caller can route them through the same\n * defer-or-publish path as every other event this dispatch produces.\n */\nexport async function stampScheduledSessionTitle(\n db: Database,\n input: {\n workspaceId: string;\n sessionId: string;\n taskName: string;\n },\n): Promise<Awaited<ReturnType<typeof updateSessionTitleWithEvent>>[\"events\"]> {\n const title = scheduledTaskSessionTitle(input.taskName);\n const result = await updateSessionTitleWithEvent(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n title,\n source: \"agent\",\n expectedCurrent: {\n title: AUTOMATIC_SESSION_TITLE_FALLBACK,\n source: \"agent\",\n },\n });\n return result.events;\n}\n\nexport function createScheduledTaskActivities(services: () => Promise<ControlActivityServices>) {\n return {\n dispatchScheduledTaskRun: async (\n input: DispatchScheduledTaskRunInput,\n ): Promise<DispatchScheduledTaskRunResult> => {\n const baseService = await services();\n // Histories created before the manual-initiator workflow patch already\n // contain this activity command. Reject their incomplete wire input here\n // so replay consumes the recorded command and the retry loop settles.\n if (input.triggerType !== \"scheduled\" && !input.initiator) {\n return { action: \"blocked\", reason: \"malformed_manual_trigger\" };\n }\n const { db, bus, wakeSessionWorkflow } = baseService;\n const settingsForTask = async (task: ScheduledTask, retainedProductModelId?: string | null) =>\n (\n await resolveWorkspaceCatalogSettings(\n db,\n baseService.catalogSourceSettings ?? baseService.settings,\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n ...(retainedProductModelId !== undefined ? { retainedProductModelId } : {}),\n },\n )\n ).settings;\n const stableProducerKey = scheduledTaskRunProducerKey(input);\n const priorRun = await getScheduledTaskRunByProducerKey(db, {\n workspaceId: input.workspaceId,\n taskId: input.taskId,\n triggerType: input.triggerType,\n producerKey: stableProducerKey,\n });\n if (priorRun?.actionKind === \"agent_turn\") {\n if (priorRun.admissionDiagnostic || priorRun.admissionRefusal) {\n return scheduledAdmissionRefusalResult(priorRun);\n }\n const acceptedExecution = await getScheduledTaskRunAcceptedExecution(db, {\n workspaceId: input.workspaceId,\n runId: priorRun.id,\n });\n if (!acceptedExecution) {\n if (\n priorRun.status === \"succeeded\" ||\n priorRun.status === \"failed\" ||\n priorRun.status === \"skipped\"\n ) {\n return scheduledRunTerminalResult(priorRun.error);\n }\n throw new Error(\"scheduled agent run is missing accepted execution truth\");\n }\n await recordScheduledTaskFiredUsage(db, acceptedExecution, priorRun);\n if (priorRun.status === \"dispatched\") {\n return await replayScheduledTaskDispatch({\n db,\n wakeSessionWorkflow,\n task: acceptedExecution.task,\n run: priorRun,\n acceptedExecution,\n });\n }\n if (priorRun.status === \"queued\") {\n const acceptedPolicy = acceptedExecution.turnExecutionPolicy\n ? TurnExecutionPolicyV1.parse(acceptedExecution.turnExecutionPolicy)\n : null;\n const settings = await settingsForTask(\n acceptedExecution.task,\n acceptedPolicy?.productModelId ??\n acceptedExecution.targetSessionExecution?.model ??\n acceptedExecution.resolvedModel,\n );\n try {\n return await recoverBoundScheduledTaskDispatch({\n db,\n observability: baseService.observability,\n bus,\n settings,\n wakeSessionWorkflow,\n run: priorRun,\n acceptedExecution,\n input,\n });\n } catch (error) {\n const terminalError = scheduledRunRecoveryTerminalError(error);\n if (!terminalError) throw error;\n await markScheduledTaskRunFailedIfQueued(\n db,\n priorRun.workspaceId,\n priorRun.id,\n terminalError.code,\n );\n return scheduledRunTerminalResult(terminalError.code);\n }\n }\n if (priorRun.status === \"succeeded\") {\n if (!priorRun.sessionId || !priorRun.triggerEventId) {\n throw new Error(\"succeeded scheduled run is missing its delivery identity\");\n }\n return {\n action: acceptedExecution.task.runMode === \"new_session_per_run\" ? \"start\" : \"signal\",\n accountId: acceptedExecution.task.accountId,\n workspaceId: acceptedExecution.task.workspaceId,\n sessionId: priorRun.sessionId,\n triggerEventId: priorRun.triggerEventId,\n workflowId: workflowIdForSession(priorRun.sessionId),\n workflowWakeRevision: null,\n };\n }\n if (priorRun.status === \"failed\" || priorRun.status === \"skipped\") {\n return scheduledRunTerminalResult(priorRun.error);\n }\n }\n const task = await getScheduledTask(db, input.workspaceId, input.taskId);\n // Deleting a schedule is authoritative. A fire workflow that was already\n // created may still start afterward; completing it as a no-op prevents an\n // unbounded retry loop for work that no longer exists.\n if (!task) {\n return { action: \"deleted\" };\n }\n if (task.action.kind !== \"agent_turn\") {\n return { action: \"blocked\", reason: \"legacy_source_schedule_requires_migration\" };\n }\n if (task.status !== \"active\") {\n return { action: \"blocked\", reason: \"scheduled_task_paused\" };\n }\n if (task.agentConfig.knowledgeSource && knowledgeSourceSyncEffectivelyPaused(task)) {\n return { action: \"blocked\", reason: \"knowledge_source_paused\" };\n }\n const structuredAlertOccurrence = scheduledAlertOccurrenceIdentity({\n workspaceId: task.workspaceId,\n scheduledTaskId: task.id,\n metadata: task.metadata,\n });\n const alertOccurrence =\n task.runMode === \"new_session_per_run\" ? structuredAlertOccurrence : null;\n const alertResponderSessionCreateIdempotencyKey = alertOccurrence\n ? scheduledAlertResponderSessionCreateIdempotencyKey({\n occurrence: alertOccurrence,\n taskAuthorityRevision: task.authorityRevision,\n taskExecutionDigest: task.executionDigest,\n })\n : null;\n const incidentDeclaration = incidentTelemetryPreflightDeclaration(\n task.agentConfig,\n structuredAlertOccurrence !== null,\n );\n if (incidentDeclaration.action === \"blocked\") {\n return incidentDeclaration;\n }\n const taskPersonalResourceAuthoritySubjectId =\n await getScheduledTaskPersonalResourceAuthoritySubject(db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n taskAuthorityRevision: task.authorityRevision,\n });\n const taskRevisionAuthority = await getScheduledTaskRevisionAuthority(db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n taskAuthorityRevision: task.authorityRevision,\n });\n const taskAuthoritySubjectId = task.ownerSubjectId;\n // Every pre-admission refusal below is recorded as a visible run receipt\n // under this producer identity instead of throwing (a thrown activity is\n // retried to exhaustion and leaves no run) or returning a bare blocked\n // result (the occurrence silently disappears). Terminal refusals are\n // deterministic for this task revision and digest; transient ones\n // (`retryable`) are skipped and a later occurrence is admitted normally.\n // Redelivery replays the same receipt, so no occurrence gets two runs.\n const refuseAdmission = async (\n reason: ScheduledTaskAdmissionRefusalReason,\n retryable: boolean,\n detail: string,\n ): Promise<DispatchScheduledTaskRunResult> => {\n console.warn(\n `[scheduled-task] refused occurrence of ${task.id} (revision ${task.authorityRevision}): ${reason}: ${detail}`,\n );\n const receipt = await recordScheduledTaskAdmissionRefusal(db, {\n workspaceId: task.workspaceId,\n taskId: task.id,\n taskAuthorityRevision: task.authorityRevision,\n taskExecutionDigest: task.executionDigest,\n triggerType: input.triggerType,\n producerKey: stableProducerKey,\n reason,\n retryable,\n });\n if (!receipt.admissionRefusal) {\n // A concurrent delivery accepted this producer first. Follow the\n // existing exact-receipt recovery path, never replace its outcome.\n return createScheduledTaskActivities(services).dispatchScheduledTaskRun(input);\n }\n return scheduledAdmissionRefusalResult(receipt);\n };\n if (\n task.action.kind === \"agent_turn\" &&\n ((taskRevisionAuthority?.subjectId ?? null) !== taskAuthoritySubjectId ||\n [taskPersonalResourceAuthoritySubjectId].some(\n (subject) => subject !== null && subject !== taskAuthoritySubjectId,\n ))\n ) {\n return await refuseAdmission(\n \"scheduled_authority_unavailable\",\n false,\n \"scheduled authority differs from its immutable execution owner\",\n );\n }\n const acceptedTargetSessionId =\n task.runMode === \"existing_session\"\n ? task.targetSessionId\n : task.runMode === \"reusable_session\"\n ? task.reusableSessionId\n : null;\n // A targeted task whose exact session was deleted has no target to\n // resolve; database admission settles that occurrence terminally\n // (`scheduled_target_session_unavailable`) instead of retrying forever.\n // Resolve this before the catalog so an existing session's retired\n // custom Gateway model remains executable without becoming selectable\n // for a new scheduled session.\n const targetSessionExecutionBase = acceptedTargetSessionId\n ? await getScheduledTargetSessionExecution(\n db,\n task.workspaceId,\n acceptedTargetSessionId,\n taskAuthoritySubjectId,\n )\n : null;\n const settings = await settingsForTask(task, targetSessionExecutionBase?.model);\n // A task that names no model resolves the new-chat default at each fresh\n // occurrence (saved workspace default, then a usable connected\n // subscription under the task's frozen SuperGrok authority, then the\n // credits default while the organization holds a credit balance, then the\n // deployment default). A frozen SuperGrok pool that is gone only means\n // SuperGrok is not ready. The accepted execution freezes the result, so\n // retries and recovery never resolve again. Existing-session runs keep\n // that session's model.\n const resolvedDefault =\n task.agentConfig.model || targetSessionExecutionBase\n ? null\n : await resolveScheduledTaskDefaultModel(db, settings, task);\n const model = task.agentConfig.model ?? resolvedDefault?.model ?? settings.openaiModel;\n const reasoningEffort =\n task.agentConfig.reasoningEffort ??\n resolvedDefault?.reasoningEffort ??\n settings.openaiReasoningEffort;\n let sandboxBackend = task.agentConfig.sandboxBackend ?? settings.sandboxBackend;\n let sandboxOs: \"linux\" | \"macos\" | \"windows\" = \"linux\";\n let taskTools = withFirstPartyTools(settings, task.agentConfig.tools);\n // A task created by a live agent attempt froze its creator's effective\n // first-party selection, permission set, and session access policy;\n // its generated sessions inherit that boundary under today's\n // deployment ceiling. A human/API-created task (null policy) keeps the\n // deployment default exactly as before.\n const creatorPolicy = await getScheduledTaskCreatorPolicy(db, task.workspaceId, task.id);\n // A person-chosen Slack channel adds only the two bot posting tools;\n // they post nowhere else, whatever the creator's own selection was.\n let firstPartyMcpTools = withScheduledSlackBotPostingTools(\n creatorPolicy?.firstPartyMcpTools\n ? allowedFirstPartyMcpToolsForSession(settings, creatorPolicy.firstPartyMcpTools)\n : resolveFirstPartyMcpToolPolicy(settings).default,\n task.agentConfig,\n resolveFirstPartyMcpToolPolicy(settings).allowed,\n );\n // Agent configuration for generated sessions (null = legacy). The\n // scheduled baseline above (creator policy or deployment default) is\n // what \"all\" reproduces; capabilities only narrow it. Frozen into the\n // accepted execution so retries and recovery never resolve again.\n let resolvedAgentConfig: ResolvedAgentConfig | null = null;\n let resolvedAgentInstructions: string | undefined;\n try {\n const agentResolution = resolveSessionAgentConfigForCreate({\n settings,\n creator: \"scheduled\",\n request: task.agentConfig.agent,\n instructions: undefined,\n workspaceSettings: agentConfigMayResolve(settings, task.agentConfig.agent)\n ? (await requireWorkspace(db, task.workspaceId)).settings\n : {},\n parent: null,\n goal: task.agentConfig.goal !== undefined,\n });\n resolvedAgentConfig = agentResolution.config;\n resolvedAgentInstructions = agentResolution.instructions;\n const written = applySessionAgentConfigWriteThrough({\n config: resolvedAgentConfig,\n firstPartyMcpTools,\n tools: taskTools,\n toolPolicy: { mode: \"explicit\", inheritedFromSessionId: null },\n productServerIds: task.agentConfig.tools.map((tool) => tool.id),\n });\n firstPartyMcpTools = written.firstPartyMcpTools;\n taskTools = written.tools;\n } catch (error) {\n const status =\n error instanceof Error ? (error as Error & { status?: unknown }).status : undefined;\n if (!(error instanceof Error) || status !== 422) throw error;\n const notEnabled =\n error.cause instanceof AgentConfigError &&\n error.cause.code === \"agent_config_not_enabled\";\n return await refuseAdmission(\n \"scheduled_authority_unavailable\",\n notEnabled,\n `scheduled agent configuration is not admissible: ${error.message}`,\n );\n }\n const firstPartyMcpPermissions = creatorPolicy?.firstPartyMcpPermissions\n ? [...creatorPolicy.firstPartyMcpPermissions]\n : [...DEFAULT_FIRST_PARTY_MCP_PERMISSIONS];\n // A fresh occurrence resolves the immutable owner's current accounts.\n // Retry/recovery above uses the already accepted occurrence snapshot.\n const connectionSettings = await settingsWithEnabledCapabilityMcpServers(\n db,\n task.workspaceId,\n settings,\n taskAuthoritySubjectId ? { subjectId: taskAuthoritySubjectId } : {},\n );\n const connectionTarget =\n acceptedTargetSessionId && targetSessionExecutionBase\n ? await requireSession(db, task.workspaceId, acceptedTargetSessionId)\n : null;\n const connectionTools = await scheduledConnectionTools(\n db,\n task.workspaceId,\n connectionSettings,\n connectionTarget,\n taskTools,\n taskAuthoritySubjectId ?? undefined,\n );\n const taskConnections = await freezeConnectionAccounts({\n db,\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n settings: connectionTarget\n ? settingsWithSessionMcpServerMetadata(connectionSettings, connectionTarget.mcpServers)\n : connectionSettings,\n tools: connectionTools,\n resources: connectionTarget?.resources ?? task.agentConfig.resources,\n source: taskAuthoritySubjectId\n ? { kind: \"subject\", subjectId: taskAuthoritySubjectId, accountId: task.accountId }\n : { kind: \"none\" },\n authoritySelections: task.agentConfig.connectionAccounts ?? [],\n authoritySelectionsFrozen: task.agentConfig.connectionAccountsFrozen === true,\n ...scheduledConnectionSurfaceEligibility(\n settings,\n connectionTarget ?? {\n firstPartyMcpTools,\n firstPartyMcpPermissions,\n },\n ),\n }).catch((error: unknown) => {\n if (error instanceof ConnectionAccountSelectionError) return error;\n throw error;\n });\n if (taskConnections instanceof ConnectionAccountSelectionError) {\n const receipt = await recordScheduledTaskAdmissionFailure(db, {\n workspaceId: task.workspaceId,\n taskId: task.id,\n taskAuthorityRevision: task.authorityRevision,\n taskExecutionDigest: task.executionDigest,\n triggerType: input.triggerType,\n producerKey: stableProducerKey,\n diagnostic: taskConnections.diagnostic,\n });\n if (!receipt.admissionDiagnostic) {\n // A concurrent delivery accepted this producer first. Follow the\n // existing exact-receipt recovery path, never replace its outcome.\n return createScheduledTaskActivities(services).dispatchScheduledTaskRun(input);\n }\n return scheduledAdmissionRefusalResult(receipt);\n }\n const {\n personalConnectionDelegations: taskPersonalConnectionDelegations,\n mcpAccountBindings: taskMcpAccountBindings,\n } = taskConnections;\n const taskConnectionAuthoritySubjectId =\n taskPersonalConnectionDelegations.length > 0 ? taskAuthoritySubjectId : null;\n const creatorSessionPolicy = scheduledCreatorSessionPolicyInput(\n creatorPolicy?.sessionPolicy ?? null,\n );\n const generatedTarget =\n task.runMode === \"new_session_per_run\" ||\n (task.runMode === \"reusable_session\" && task.reusableSessionId === null);\n if (generatedTarget && task.agentConfig.machineTarget) {\n const access = {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n subjectId: taskAuthoritySubjectId ?? task.createdBy.subjectId,\n };\n const machine = await getSandbox(\n db,\n access,\n task.agentConfig.machineTarget.targetSandboxId,\n );\n if (\n !machine ||\n machine.kind !== \"selfhosted\" ||\n !machine.enrollmentId ||\n machine.scope === \"user\"\n ) {\n return await refuseAdmission(\n \"machine_target_unavailable\",\n false,\n \"scheduled Connected Machine target is unavailable\",\n );\n }\n const enrollment = await getEnrollment(db, access, machine.enrollmentId);\n if (!enrollment) {\n return await refuseAdmission(\n \"machine_target_unavailable\",\n false,\n \"scheduled Connected Machine enrollment is gone\",\n );\n }\n if (enrollment.status !== \"active\") {\n // A paused/suspended enrollment can be re-activated; skip this\n // occurrence rather than failing the schedule.\n return await refuseAdmission(\n \"machine_enrollment_inactive\",\n true,\n `scheduled Connected Machine enrollment is ${enrollment.status}`,\n );\n }\n sandboxBackend = \"selfhosted\";\n sandboxOs = enrollment.os;\n } else if (generatedTarget && sandboxBackend === \"selfhosted\") {\n return await refuseAdmission(\n \"machine_target_unavailable\",\n false,\n \"self-hosted scheduled task has no Connected Machine target\",\n );\n }\n const generatedSessionDepthPolicy = generatedTarget\n ? await (async () => {\n const workspace = await requireWorkspace(db, task.workspaceId);\n const deployment = await getNestedAgentDepthDeploymentPolicy(db);\n const taskOverride = task.agentConfig.maxNestedAgentDepth ?? null;\n const workspaceOverride =\n typeof workspace.settings.maxNestedAgentDepth === \"number\"\n ? workspace.settings.maxNestedAgentDepth\n : null;\n return taskOverride !== null\n ? {\n effectiveMaxNestedAgentDepth: taskOverride,\n nestedAgentDepthPolicySource: \"session\" as const,\n codexCompactionMode: isCodexBilledModel(model)\n ? resolveWorkspaceCodexCompactionDefault(workspace.settings)\n : (\"portable\" as const),\n }\n : workspaceOverride !== null\n ? {\n effectiveMaxNestedAgentDepth: workspaceOverride,\n nestedAgentDepthPolicySource: \"workspace\" as const,\n codexCompactionMode: isCodexBilledModel(model)\n ? resolveWorkspaceCodexCompactionDefault(workspace.settings)\n : (\"portable\" as const),\n }\n : {\n effectiveMaxNestedAgentDepth: deployment.maxNestedAgentDepth,\n nestedAgentDepthPolicySource: deployment.policySource,\n codexCompactionMode: isCodexBilledModel(model)\n ? resolveWorkspaceCodexCompactionDefault(workspace.settings)\n : (\"portable\" as const),\n };\n })()\n : null;\n const targetSessionExecution = targetSessionExecutionBase\n ? await (async () => {\n const apiIntegrationServerIds =\n await listInstalledApiIntegrationServerIdsForDelegations(\n db,\n task.workspaceId,\n taskPersonalConnectionDelegations,\n );\n const availableMcpServerIds = new Set([\n ...connectionSettings.mcpServers.map((server) => server.id),\n ...apiIntegrationServerIds,\n ]);\n for (const id of targetSessionExecutionBase.mcpServerIds) {\n availableMcpServerIds.add(id);\n }\n const effective = resolveSessionToolPolicy({\n toolPolicy: targetSessionExecutionBase.toolPolicy,\n sessionTools: targetSessionExecutionBase.tools,\n availableMcpServerIds,\n defaultMcpServerIds: [\n ...connectionTools.map((tool) => tool.id),\n ...apiIntegrationServerIds,\n ],\n });\n return {\n ...targetSessionExecutionBase,\n effectiveMcpServerIds: [\n ...new Set(\n effective.toolRefs.flatMap((tool) => (tool.kind === \"mcp\" ? [tool.id] : [])),\n ),\n ].sort(),\n };\n })()\n : null;\n const acceptedVariableSet =\n generatedTarget && task.variableSetId\n ? await getVariableSet(\n db,\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n // Organization/workspace sets have no personal-resource causal\n // subject. The scoped resolver still permits those common\n // scopes for a service/legacy actor, while a user-owned set can\n // only resolve through the exact frozen 0252 subject.\n subjectId: taskAuthoritySubjectId ?? task.createdBy.subjectId,\n },\n task.variableSetId,\n )\n : null;\n if (generatedTarget && task.variableSetId && !acceptedVariableSet) {\n return await refuseAdmission(\n \"variable_set_unavailable\",\n false,\n `variable set not found: ${task.variableSetId}`,\n );\n }\n const acceptedRig =\n generatedTarget && task.rigId\n ? await getRig(\n db,\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n subjectId: taskAuthoritySubjectId ?? task.createdBy.subjectId,\n },\n task.rigId,\n )\n : null;\n if (generatedTarget && task.rigId && (!acceptedRig || !acceptedRig.activeVersion)) {\n return await refuseAdmission(\n \"rig_version_unavailable\",\n false,\n `sandbox environment has no active version to bind: ${task.rigId}`,\n );\n }\n const acceptedRigDefaultVariableSetRows = acceptedRig?.activeVersion\n ? await Promise.all(\n acceptedRig.activeVersion.defaultVariableSetIds.map(async (variableSetId) => ({\n variableSetId,\n variableSet: await getVariableSet(\n db,\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n subjectId: taskAuthoritySubjectId ?? task.createdBy.subjectId,\n },\n variableSetId,\n ),\n })),\n )\n : [];\n const missingRigDefaultVariableSet = acceptedRigDefaultVariableSetRows.find(\n (row) => !row.variableSet,\n );\n if (missingRigDefaultVariableSet) {\n return await refuseAdmission(\n \"variable_set_unavailable\",\n false,\n `sandbox environment default Variable Set not found: ${missingRigDefaultVariableSet.variableSetId}`,\n );\n }\n const acceptedRigDefaultVariableSets = acceptedRigDefaultVariableSetRows.map(\n ({ variableSet }) => ({ id: variableSet!.id, generation: variableSet!.generation }),\n );\n let incidentPreflightRequired = incidentDeclaration.action === \"required\";\n if (incidentPreflightRequired) {\n const existingSessionId =\n task.runMode === \"existing_session\" ? task.targetSessionId : task.reusableSessionId;\n const canonicalAlertSession =\n task.runMode === \"new_session_per_run\" && alertOccurrence\n ? await getSessionByCreateIdempotencyKey(\n db,\n task.workspaceId,\n alertResponderSessionCreateIdempotencyKey!,\n )\n : null;\n const responderSession = existingSessionId\n ? await requireSession(db, task.workspaceId, existingSessionId)\n : canonicalAlertSession;\n const responder = await resolveIncidentTelemetryResponderMetadata({\n db,\n settings,\n task,\n session: responderSession,\n personalConnectionDelegations: taskPersonalConnectionDelegations,\n personalResourceAuthoritySubjectId: taskAuthoritySubjectId,\n executionPolicy: targetSessionExecution\n ? {\n tools: targetSessionExecution.tools,\n firstPartyMcpTools: targetSessionExecution.firstPartyMcpTools,\n firstPartyMcpPermissions: targetSessionExecution.firstPartyMcpPermissions,\n variableSetIds: targetSessionExecution.variableSets.map(\n (variableSet) => variableSet.id,\n ),\n variableSetId: targetSessionExecution.variableSetId,\n rigId: targetSessionExecution.rigId,\n rigVersionId: targetSessionExecution.rigVersionId,\n toolPolicy: targetSessionExecution.toolPolicy,\n mcpServerIds: targetSessionExecution.mcpServerIds,\n toolPolicyVersion: targetSessionExecution.toolPolicyVersion,\n }\n : {\n tools: taskTools,\n firstPartyMcpTools,\n firstPartyMcpPermissions,\n variableSetId: acceptedVariableSet?.id ?? null,\n rigId: acceptedRig?.id ?? null,\n rigVersionId: acceptedRig?.activeVersion?.id ?? null,\n toolPolicy: responderSession?.toolPolicy ?? {\n mode: \"explicit\",\n inheritedFromSessionId: null,\n },\n mcpServerIds: [],\n toolPolicyVersion: responderSession?.toolPolicyVersion ?? null,\n },\n });\n const preflight = evaluateIncidentTelemetryPreflight({\n agentConfig: task.agentConfig,\n incidentTriggered: structuredAlertOccurrence !== null,\n alertOccurrenceLabels: structuredAlertOccurrence?.labels ?? null,\n responder,\n });\n if (preflight.action === \"blocked\") return preflight;\n incidentPreflightRequired = preflight.action === \"ready\";\n }\n const taskXaiProviderAccountAuthoritySnapshot =\n await getScheduledTaskXaiProviderAccountAuthoritySnapshot(db, task.workspaceId, task.id);\n // A scheduled bot selection was authorized when the task was written,\n // but connection status and tenant/role binding are mutable. Revalidate\n // before any session/model cost and never fall back to a personal Slack\n // OAuth grant when the selected bot has been revoked or changed.\n const slackBotConnection = task.agentConfig.slackBotConnectionId\n ? await requireOpenGeniSlackBotConnection(\n db,\n task.workspaceId,\n task.agentConfig.slackBotConnectionId,\n )\n : null;\n const slackBotMetadata = slackBotConnection\n ? openGeniSlackBotMetadata(slackBotConnection.metadata)\n : null;\n if (slackBotConnection && !slackBotMetadata) {\n throw new Error(\"OpenGeni Slack bot connection metadata is invalid\");\n }\n const xaiAuthoritySubjectId =\n taskXaiProviderAccountAuthoritySnapshot.scope === \"user\" &&\n task.createdBy.kind === \"subject\"\n ? task.createdBy.subjectId\n : null;\n if (taskXaiProviderAccountAuthoritySnapshot.scope === \"user\" && !xaiAuthoritySubjectId) {\n return await refuseAdmission(\n \"scheduled_authority_unavailable\",\n false,\n \"scheduled user-scoped xAI authority has no causal human\",\n );\n }\n if (\n xaiAuthoritySubjectId &&\n taskAuthoritySubjectId &&\n xaiAuthoritySubjectId !== taskAuthoritySubjectId\n ) {\n return await refuseAdmission(\n \"scheduled_authority_unavailable\",\n false,\n \"scheduled authority classes have different causal humans\",\n );\n }\n const causalHumanSubjectId = taskAuthoritySubjectId ?? xaiAuthoritySubjectId;\n if (\n task.agentConfig.knowledgeSource &&\n causalHumanSubjectId !== task.agentConfig.knowledgeSource.initiatingSubjectId\n ) {\n return await refuseAdmission(\n \"scheduled_authority_unavailable\",\n false,\n \"Source schedule requires its connection owner's current human authorization; update the source schedule to authorize it\",\n );\n }\n // Workspace/organization Variable Sets and Rigs run through ordinary\n // workspace authority; only a user-owned resource needs the exact frozen\n // human, and the database admission fence re-proves the same rule for\n // existing/warm targets.\n if (\n (acceptedVariableSet?.scope === \"user\" || acceptedRig?.scope === \"user\") &&\n !causalHumanSubjectId\n ) {\n return await refuseAdmission(\n \"scheduled_authority_unavailable\",\n false,\n \"scheduled personal-resource execution has no causal human\",\n );\n }\n const admissionDenial = await agentRunAdmissionDenial(\n { ...baseService, settings },\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n model: targetSessionExecution?.model ?? model,\n requestedAgentRuns: input.agentRunUsageIdempotencyKey ? 0 : 1,\n initiatingHumanSubjectId: causalHumanSubjectId,\n },\n );\n if (admissionDenial) {\n // Credits and monthly limits clear on their own (top-up, new period):\n // skip this occurrence visibly; a later one is admitted normally.\n return await refuseAdmission(admissionDenial, true, \"agent run admission denied\");\n }\n const acceptedModel = targetSessionExecution?.model ?? model;\n const acceptedReasoningEffort = targetSessionExecution?.reasoningEffort ?? reasoningEffort;\n const acceptedLatencyMode = targetSessionExecution?.latencyMode ?? \"standard\";\n const acceptedCustomModel = generatedTarget\n ? workspaceCustomModelReference(settings, acceptedModel)\n : null;\n const beforeFreshAgentRunCommit = acceptedCustomModel\n ? async (tx: Database): Promise<void> => {\n const active = await lockActiveCustomModelForAdmission(tx, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n reference: acceptedCustomModel,\n });\n if (!active) {\n throw new ScheduledRunTerminalAuthorityError(\n \"scheduled_model_unavailable\",\n `model is not available: ${acceptedModel}`,\n );\n }\n }\n : undefined;\n const turnExecutionPolicy = scheduledTaskRunExecutionPolicy(\n resolveTurnExecutionPolicyV1(settings, {\n modelId: acceptedModel,\n requestedModelId:\n generatedTarget && task.agentConfig.model ? task.agentConfig.model : null,\n modelSource: generatedTarget\n ? task.agentConfig.model\n ? \"explicit\"\n : \"deployment\"\n : \"session\",\n reasoningEffort: acceptedReasoningEffort,\n reasoningSource: generatedTarget\n ? task.agentConfig.reasoningEffort\n ? \"explicit\"\n : \"deployment\"\n : \"session\",\n latencyMode: acceptedLatencyMode,\n latencyModeSource: generatedTarget ? \"deployment\" : \"session\",\n }),\n input,\n creatorPolicy?.credentialRestriction,\n );\n const deferredEvents: Array<{\n sessionId: string;\n events: Awaited<ReturnType<typeof appendSessionEvents>>;\n }> = [];\n const executeDispatch = async (dispatchDb: Database, deferPublications: boolean) => {\n const admittedRunId = crypto.randomUUID();\n const generatedSessionBinding = generatedTarget\n ? {\n createIdempotencyKey:\n alertResponderSessionCreateIdempotencyKey ??\n (task.runMode === \"reusable_session\"\n ? `scheduled-task-reusable:${task.id}:${task.authorityRevision}:${task.executionDigest}`\n : scheduledTaskGeneratedSessionCreateIdempotencyKey(stableProducerKey)),\n effectiveMaxNestedAgentDepth:\n generatedSessionDepthPolicy!.effectiveMaxNestedAgentDepth,\n nestedAgentDepthPolicySource:\n generatedSessionDepthPolicy!.nestedAgentDepthPolicySource,\n codexCompactionMode: generatedSessionDepthPolicy!.codexCompactionMode,\n }\n : null;\n const acceptedExecution: ScheduledTaskRunAcceptedExecution = {\n version: 1,\n task,\n resolvedModel: model,\n resolvedReasoningEffort: reasoningEffort,\n resolvedLatencyMode: \"standard\",\n turnExecutionPolicy,\n resolvedSandboxBackend: sandboxBackend,\n resolvedSandboxOs: sandboxOs,\n resolvedTools: taskTools,\n resolvedFirstPartyMcpTools: firstPartyMcpTools,\n resolvedFirstPartyMcpPermissions: firstPartyMcpPermissions,\n ...(resolvedAgentConfig\n ? {\n resolvedAgentConfig,\n ...(resolvedAgentInstructions !== undefined ? { resolvedAgentInstructions } : {}),\n }\n : {}),\n resolvedVariableSet: acceptedVariableSet\n ? { id: acceptedVariableSet.id, generation: acceptedVariableSet.generation }\n : null,\n resolvedRig: acceptedRig?.activeVersion\n ? {\n id: acceptedRig.id,\n versionId: acceptedRig.activeVersion.id,\n defaultVariableSets: acceptedRigDefaultVariableSets,\n }\n : null,\n resolvedSlackBotConnection:\n slackBotConnection && slackBotMetadata && slackBotConnection.verifiedInstallVersion\n ? {\n id: slackBotConnection.id,\n version: slackBotConnection.version,\n verifiedInstallVersion: slackBotConnection.verifiedInstallVersion,\n metadata: slackBotMetadata,\n }\n : null,\n targetSessionExecution,\n generatedSessionBinding,\n personalConnectionDelegations: taskPersonalConnectionDelegations,\n mcpAccountBindings: taskMcpAccountBindings,\n personalResourceAuthoritySubjectId: taskPersonalResourceAuthoritySubjectId,\n causalHumanSubjectId,\n causalHumanAuthority: taskRevisionAuthority,\n xaiProviderAccountAuthoritySnapshot: taskXaiProviderAccountAuthoritySnapshot,\n xaiAuthoritySubjectId,\n connectionAuthoritySubjectId: taskConnectionAuthoritySubjectId,\n triggerInitiator: input.initiator ?? { kind: \"service\", subjectId: \"scheduler\" },\n agentRunUsageIdempotencyKey: input.agentRunUsageIdempotencyKey ?? null,\n incidentPreflightRequired,\n alertOccurrenceLabels: structuredAlertOccurrence?.labels ?? null,\n };\n // The accepted snapshot is immutable execution truth. A legacy task\n // whose stored shape can no longer be represented as a bounded\n // accepted execution is a deterministic, operator-visible block, not a\n // retryable activity failure that would silently drop the occurrence.\n const acceptedExecutionParse =\n ScheduledTaskRunAcceptedExecution.safeParse(acceptedExecution);\n if (\n !acceptedExecutionParse.success ||\n scheduledOccurrencePayloadUtf8Bytes({\n prompt: task.agentConfig.prompt,\n resources: task.agentConfig.resources,\n tools: taskTools,\n }) > SCHEDULED_TASK_OCCURRENCE_PAYLOAD_MAX_BYTES\n ) {\n return {\n kind: \"blocked\" as const,\n result: {\n action: \"blocked\" as const,\n reason: \"scheduled_execution_unrepresentable\" as const,\n },\n };\n }\n let run = await createScheduledTaskRun(dispatchDb, {\n runId: admittedRunId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n taskAuthorityRevision: task.authorityRevision,\n taskExecutionDigest: task.executionDigest,\n triggerType: input.triggerType,\n producerKey: stableProducerKey,\n scheduledAt: null,\n acceptedExecutionSnapshot: acceptedExecution,\n ...(beforeFreshAgentRunCommit ? { beforeFreshAgentRunCommit } : {}),\n });\n await recordScheduledTaskFiredUsage(dispatchDb, acceptedExecution, run);\n if (run.status === \"failed\" && run.error === \"scheduled_authority_exhausted\") {\n return {\n kind: \"blocked\" as const,\n result: {\n action: \"blocked\" as const,\n reason: \"scheduled_authority_exhausted\" as const,\n },\n run,\n };\n }\n if (run.status === \"failed\" || run.status === \"skipped\") {\n return {\n kind: \"blocked\" as const,\n result: scheduledRunTerminalResult(run.error),\n run,\n };\n }\n const runPersonalResourceAuthority = await getScheduledTaskRunPersonalResourceAuthority(\n dispatchDb,\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n runId: run.id,\n },\n );\n if (run?.status === \"dispatched\" && run.sessionId && run.triggerEventId) {\n if (deferPublications) {\n return { kind: \"replay\" as const, run, acceptedExecution };\n }\n await recordUsageEvent(dispatchDb, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n eventType: \"agent_run.created\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"scheduled_task_run\",\n sourceResourceId: run.id,\n sessionId: run.sessionId,\n initiator: acceptedExecution.triggerInitiator,\n initiatorContext: {\n scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n },\n origin: \"scheduled_task\",\n idempotencyKey:\n acceptedExecution.agentRunUsageIdempotencyKey ??\n `usage:agent_run.created:scheduled:${run.id}`,\n });\n const workflowId = workflowIdForSession(run.sessionId);\n const workflowWakeRevision = await enqueueSessionWorkflowWakeIfRunnable(dispatchDb, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: run.sessionId,\n temporalWorkflowId: workflowId,\n reason: \"scheduled_retry\",\n });\n const result = {\n action: task.runMode === \"new_session_per_run\" ? \"start\" : \"signal\",\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: run.sessionId,\n triggerEventId: run.triggerEventId,\n workflowId,\n workflowWakeRevision,\n } as const;\n return { kind: \"complete\" as const, result, run };\n }\n let result: DispatchScheduledTaskRunResult;\n try {\n if (incidentPreflightRequired) {\n const exactAuthority = await requireScheduledTaskIncidentAuthorityInTransaction(\n dispatchDb,\n {\n workspaceId: task.workspaceId,\n taskId: task.id,\n },\n );\n if (stableJson(exactAuthority) !== stableJson(task)) {\n throw new IncidentTelemetryPreflightBlockedError(\n \"incident_preflight_metadata_missing\",\n );\n }\n }\n const goalSpec = task.agentConfig.goal ?? null;\n // Every dispatch carries the first-party MCP server; runtime visibility\n // still follows the session's exact selection and authorization.\n const existingSessionId =\n task.runMode === \"existing_session\" ? task.targetSessionId : task.reusableSessionId;\n if (task.runMode === \"existing_session\" && !existingSessionId) {\n throw new Error(\"scheduled task target session is unavailable\");\n }\n if (\n task.runMode === \"new_session_per_run\" ||\n (task.runMode === \"reusable_session\" && !existingSessionId)\n ) {\n // The FK on scheduled_tasks.variable_set_id is ON DELETE RESTRICT, so\n // an attached variableSet must still exist here; fail closed if not.\n const variableSet = acceptedVariableSet;\n if (task.variableSetId && !variableSet) {\n throw new Error(`variable set not found: ${task.variableSetId}`);\n }\n // RIG BINDING (M3): resolve the task's rig to its CURRENTLY-ACTIVE\n // version at FIRE time (not task-create time) and freeze that version\n // onto the new session — a task always runs the rig's latest active\n // version. A deleted rig FK-nulls task.rigId (rig-less run); a rig that\n // somehow has no active version fails the fire closed.\n let frozenRigId: string | null = null;\n let frozenRigVersionId: string | null = null;\n if (task.rigId) {\n const rig = acceptedRig;\n if (!rig || !rig.activeVersion) {\n throw new Error(`sandbox environment has no active version to bind: ${task.rigId}`);\n }\n frozenRigId = rig.id;\n frozenRigVersionId =\n runPersonalResourceAuthority?.resources.find(\n (resource) => resource.resourceKind === \"rig\" && resource.resourceId === rig.id,\n )?.resourceVersionId ?? rig.activeVersion.id;\n if (frozenRigVersionId !== rig.activeVersion.id) {\n throw new Error(\n \"scheduled run sandbox environment version changed during admission\",\n );\n }\n }\n let session: Awaited<ReturnType<typeof createSession>>;\n let sessionCreated = true;\n const taskMetadata = { ...task.agentConfig.metadata };\n delete taskMetadata[OPENGENI_SLACK_BOT_SESSION_METADATA_KEY];\n try {\n const sessionInput: Parameters<typeof createSession>[1] = {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n initialMessage: task.agentConfig.prompt,\n resources: task.agentConfig.resources,\n bundledSkillIds: task.agentConfig.bundledSkillIds,\n tools: taskTools,\n firstPartyMcpTools,\n firstPartyMcpPermissions,\n ...(resolvedAgentConfig ? { agentConfig: resolvedAgentConfig } : {}),\n ...(resolvedAgentInstructions !== undefined\n ? { instructions: resolvedAgentInstructions }\n : {}),\n ...creatorSessionPolicy,\n ...(task.agentConfig.knowledgeSource?.destination.kind === \"personal\"\n ? {\n visibility: \"user_private\" as const,\n scheduledSourceRunId: run.id,\n }\n : {}),\n metadata: {\n ...taskMetadata,\n ...scheduledSessionExecutionPolicyMetadata(\n turnExecutionPolicy,\n creatorPolicy?.credentialRestriction,\n ),\n model,\n reasoningEffort,\n scheduledTaskId: task.id,\n scheduledTaskRunMode: task.runMode,\n ...(goalSpec ? { scheduledTaskGoal: goalSpec } : {}),\n ...(run ? { scheduledTaskRunId: run.id } : {}),\n ...(slackBotConnection\n ? {\n [OPENGENI_SLACK_BOT_SESSION_METADATA_KEY]: slackBotConnection.id,\n }\n : {}),\n },\n createdBy: {\n kind: \"service\",\n subjectId: \"scheduler\",\n label: \"OpenGeni scheduler\",\n },\n createdByContext: {\n scheduledTaskId: task.id,\n ...(run ? { scheduledTaskRunId: run.id } : {}),\n },\n model,\n reasoningEffort,\n latencyMode: \"standard\",\n sandboxBackend,\n sandboxOs,\n variableSetId: task.variableSetId ?? null,\n rigId: frozenRigId,\n rigVersionId: frozenRigVersionId,\n personalConnectionDelegations: [],\n initialXaiProviderAccountAuthoritySnapshot: taskXaiProviderAccountAuthoritySnapshot,\n maxNestedAgentDepthOverride: task.agentConfig.maxNestedAgentDepth ?? null,\n frozenNestedAgentDepthPolicy: {\n effectiveMaxNestedAgentDepth:\n generatedSessionBinding!.effectiveMaxNestedAgentDepth,\n nestedAgentDepthPolicySource:\n generatedSessionBinding!.nestedAgentDepthPolicySource,\n },\n frozenCodexCompactionMode: generatedSessionBinding!.codexCompactionMode,\n // The durable agent config was privilege-checked when the task\n // was created/updated. Preserve that explicit policy if a broader\n // workspace/deployment limit is narrowed before a later fire.\n allowNestedAgentDepthIncrease: true,\n subjectId: `scheduled_task:${task.id}`,\n beforeCreateCommit: async (tx, sessionId) => {\n if (incidentPreflightRequired) {\n const exactSession = await requireSession(tx, task.workspaceId, sessionId);\n const exactResponder = await resolveIncidentTelemetryResponderMetadata({\n db: tx,\n settings,\n task: acceptedExecution.task,\n session: exactSession,\n personalConnectionDelegations:\n acceptedExecution.personalConnectionDelegations,\n personalResourceAuthoritySubjectId:\n acceptedExecution.personalResourceAuthoritySubjectId,\n executionPolicy: {\n tools: exactSession.tools,\n firstPartyMcpTools: exactSession.firstPartyMcpTools,\n firstPartyMcpPermissions: exactSession.firstPartyMcpPermissions,\n variableSetId: exactSession.variableSetId,\n rigId: exactSession.rigId,\n rigVersionId: exactSession.rigVersionId,\n toolPolicy: exactSession.toolPolicy,\n mcpServerIds: exactSession.mcpServers.map((server) => server.id),\n toolPolicyVersion: exactSession.toolPolicyVersion,\n },\n });\n const exactPreflight = evaluateIncidentTelemetryPreflight({\n agentConfig: acceptedExecution.task.agentConfig,\n incidentTriggered: structuredAlertOccurrence !== null,\n alertOccurrenceLabels: structuredAlertOccurrence?.labels ?? null,\n responder: exactResponder,\n });\n if (exactPreflight.action === \"blocked\") {\n throw new IncidentTelemetryPreflightBlockedError(exactPreflight.reason);\n }\n }\n await bindScheduledTaskRunSessionInTransaction(tx, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n runId: run.id,\n sessionId,\n });\n },\n };\n const created = await createSessionWithIdempotencyKeyResult(dispatchDb, {\n ...sessionInput,\n createIdempotencyKey: generatedSessionBinding!.createIdempotencyKey,\n });\n if (created.denied) {\n throw new SessionSpawnDeniedDbError(created.denial);\n }\n session = created.session;\n sessionCreated = created.created;\n if (sessionCreated) recordScheduledSessionCreated(baseService.observability);\n if (!sessionCreated) {\n await bindScheduledTaskRunSessionInTransaction(dispatchDb, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n runId: run.id,\n sessionId: session.id,\n });\n run = { ...run, sessionId: session.id };\n }\n } catch (error) {\n if (error instanceof IncidentTelemetryPreflightBlockedError) {\n throw error;\n }\n if (error instanceof SessionSpawnDeniedDbError) {\n throw new Error(`${error.denial.code}: denial=${error.denial.id}`, {\n cause: error,\n });\n }\n throw error;\n }\n const scheduledRun = run;\n if (!sessionCreated) {\n assertReusableSessionRevivable(session.status);\n if ((session.variableSetId ?? null) !== (task.variableSetId ?? null)) {\n throw new Error(\n \"scheduled alert occurrence variableSet attachment does not match its canonical session\",\n );\n }\n if (\n scheduledSlackBotConnectionId(session.metadata) !==\n (task.agentConfig.slackBotConnectionId ?? null)\n ) {\n throw new Error(\n \"scheduled alert occurrence OpenGeni Slack bot binding does not match its canonical session\",\n );\n }\n }\n session = await seedScheduledGeneratedSessionRoute({\n db: dispatchDb,\n bus,\n settings,\n task,\n runId: run.id,\n session,\n deferPublications,\n deferredEvents,\n });\n let workflowId: string;\n if (alertOccurrence) {\n const started = await initializeSessionStartAtomically(dispatchDb, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n reasoningEffortFallback: reasoningEffort,\n createdEventPayload: {\n scheduledTaskId:\n typeof session.metadata.scheduledTaskId === \"string\"\n ? session.metadata.scheduledTaskId\n : task.id,\n scheduledTaskRunId:\n typeof session.metadata.scheduledTaskRunId === \"string\"\n ? session.metadata.scheduledTaskRunId\n : run.id,\n // Names/ids only; never values.\n ...(variableSet\n ? {\n variableSetId: variableSet.id,\n variableSetName: variableSet.name,\n }\n : {}),\n ...(slackBotConnection && slackBotMetadata\n ? {\n slackBotConnection: {\n credentialRole: OPENGENI_SLACK_BOT_CREDENTIAL_ROLE,\n credentialLabel: OPENGENI_SLACK_BOT_CREDENTIAL_LABEL,\n connectionId: slackBotConnection.id,\n slackTeamId: slackBotMetadata.slackTeamId,\n },\n }\n : {}),\n },\n goal: goalSpec\n ? {\n text: goalSpec.text,\n successCriteria: goalSpec.successCriteria ?? null,\n maxAutoContinuations: goalSpec.maxAutoContinuations ?? null,\n ...(goalSpec.mutationPolicy\n ? { mutationPolicy: goalSpec.mutationPolicy }\n : {}),\n createdBy: \"scheduled_task\",\n }\n : null,\n deferInitialTurn: true,\n deferredStatus: \"queued\",\n });\n workflowId = started.temporalWorkflowId;\n if (started.events.length > 0) {\n if (deferPublications) {\n deferredEvents.push({\n sessionId: session.id,\n events: started.events,\n });\n } else {\n await publishDurableSessionEvents(\n bus,\n task.workspaceId,\n session.id,\n started.events,\n );\n }\n }\n } else {\n const started = await initializeSessionStartAtomically(dispatchDb, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n reasoningEffortFallback: reasoningEffort,\n createdEventPayload: {\n scheduledTaskId:\n typeof session.metadata.scheduledTaskId === \"string\"\n ? session.metadata.scheduledTaskId\n : task.id,\n scheduledTaskRunId:\n typeof session.metadata.scheduledTaskRunId === \"string\"\n ? session.metadata.scheduledTaskRunId\n : run.id,\n // Names/ids only; never values.\n ...(variableSet\n ? { variableSetId: variableSet.id, variableSetName: variableSet.name }\n : {}),\n ...(slackBotConnection && slackBotMetadata\n ? {\n slackBotConnection: {\n credentialRole: OPENGENI_SLACK_BOT_CREDENTIAL_ROLE,\n credentialLabel: OPENGENI_SLACK_BOT_CREDENTIAL_LABEL,\n connectionId: slackBotConnection.id,\n slackTeamId: slackBotMetadata.slackTeamId,\n },\n }\n : {}),\n },\n goal: goalSpec\n ? {\n text: goalSpec.text,\n successCriteria: goalSpec.successCriteria ?? null,\n maxAutoContinuations: goalSpec.maxAutoContinuations ?? null,\n ...(goalSpec.mutationPolicy\n ? { mutationPolicy: goalSpec.mutationPolicy }\n : {}),\n createdBy: \"scheduled_task\",\n }\n : null,\n deferInitialTurn: true,\n deferredStatus: \"queued\",\n });\n workflowId = started.temporalWorkflowId;\n if (started.events.length > 0) {\n if (deferPublications) {\n deferredEvents.push({ sessionId: session.id, events: started.events });\n } else {\n await publishDurableSessionEvents(\n bus,\n task.workspaceId,\n session.id,\n started.events,\n );\n }\n }\n if (task.runMode === \"reusable_session\") {\n await materializeScheduledTaskReusableSessionFromRun(dispatchDb, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n runId: run.id,\n sessionId: session.id,\n sourceTaskAuthorityRevision:\n runPersonalResourceAuthority?.taskAuthorityRevision ??\n run.taskAuthorityRevision!,\n sourceExecutionDigest:\n runPersonalResourceAuthority?.executionDigest ?? run.taskExecutionDigest!,\n });\n }\n }\n // After both start branches, so the timeline reads session.created\n // then session.title_set rather than titling a session that has not\n // announced itself yet. `session.created` is what carries the row\n // into the rail, and this lands on its heels.\n const titleEvents = await stampScheduledSessionTitle(dispatchDb, {\n workspaceId: task.workspaceId,\n sessionId: session.id,\n taskName: task.name,\n });\n if (titleEvents.length > 0) {\n if (deferPublications) {\n deferredEvents.push({ sessionId: session.id, events: titleEvents });\n } else {\n await publishDurableSessionEvents(bus, task.workspaceId, session.id, titleEvents);\n }\n }\n const scheduledUpdate = await addSessionSystemUpdateWithSourceMutation(\n dispatchDb,\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n kind: \"scheduled_occurrence\",\n classification: \"info\",\n sourceId: run.id,\n dedupeKey: `scheduled-task-run:${run.id}`,\n summary: task.agentConfig.prompt,\n payload: scheduledUserMessagePayload(\n task.agentConfig.prompt,\n task.agentConfig.resources,\n taskTools,\n task.id,\n run.id,\n ),\n lineage: {\n scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n ...(causalHumanSubjectId ? { causalHumanSubjectId } : {}),\n ...(taskConnectionAuthoritySubjectId\n ? { connectionAuthoritySubjectId: taskConnectionAuthoritySubjectId }\n : {}),\n ...(taskXaiProviderAccountAuthoritySnapshot.scope === \"user\" &&\n task.createdBy.kind === \"subject\"\n ? { xaiAuthoritySubjectId: task.createdBy.subjectId }\n : {}),\n },\n personalConnectionDelegations: taskPersonalConnectionDelegations,\n mcpAccountBindings: taskMcpAccountBindings,\n xaiProviderAccountAuthoritySnapshot: taskXaiProviderAccountAuthoritySnapshot,\n scheduledTaskRunId: run.id,\n },\n async (tx, wakeEventId, _updateId, rejectionReason) => {\n if (!wakeEventId) {\n const error = scheduledSessionRejectionError(rejectionReason);\n await settleScheduledTaskRunInTransaction(tx, {\n workspaceId: task.workspaceId,\n runId: scheduledRun.id,\n sessionId: session.id,\n triggerEventId: null,\n status: \"skipped\",\n error,\n });\n return;\n }\n await settleScheduledTaskRunInTransaction(tx, {\n workspaceId: task.workspaceId,\n runId: scheduledRun.id,\n sessionId: session.id,\n triggerEventId: wakeEventId,\n status: \"dispatched\",\n });\n },\n {\n requireIdleSession: task.overlapPolicy === \"skip\" && !sessionCreated,\n ...(incidentPreflightRequired\n ? {\n prepareSource: async (tx, sessionId) =>\n await prepareIncidentTelemetrySource({\n tx,\n settings,\n taskId: task.id,\n workspaceId: task.workspaceId,\n sessionId,\n alertOccurrenceLabels: structuredAlertOccurrence?.labels ?? null,\n acceptedExecution,\n }),\n }\n : {}),\n },\n );\n if (\n scheduledUpdate.reason === \"session_cancelled\" ||\n scheduledUpdate.reason === \"session_not_idle\"\n ) {\n const error = scheduledSessionRejectionError(scheduledUpdate.reason);\n return {\n kind: \"blocked\" as const,\n result: { action: \"blocked\" as const, reason: \"scheduled_run_terminal\" as const },\n run: { ...run, status: \"skipped\" as const, error },\n };\n }\n if (scheduledUpdate.added) {\n recordUserMessageAccepted(baseService.observability, { surface: \"scheduled\" });\n }\n if (scheduledUpdate.added && scheduledUpdate.events.length > 0) {\n if (deferPublications) {\n deferredEvents.push({\n sessionId: session.id,\n events: scheduledUpdate.events,\n });\n } else {\n await publishDurableSessionEvents(\n bus,\n task.workspaceId,\n session.id,\n scheduledUpdate.events,\n );\n }\n }\n result = {\n action: sessionCreated ? \"start\" : \"signal\",\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n triggerEventId: scheduledUpdate.wakeEventId,\n workflowId,\n workflowWakeRevision: scheduledUpdate.workflowWakeRevision,\n };\n } else {\n if (!run) throw new Error(\"scheduled task run was not created\");\n const scheduledRun = run;\n const session = await requireSession(dispatchDb, task.workspaceId, existingSessionId!);\n await bindScheduledTaskRunSessionInTransaction(dispatchDb, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n runId: run.id,\n sessionId: session.id,\n });\n // A user-cancelled (terminal) reusable session must not be revived and\n // re-billed on the next fire. This cheap check gives an early answer;\n // the locked admission check below remains authoritative. Mirrors\n // apps/api/src/domain/sessions.ts.\n assertReusableSessionRevivable(session.status);\n // Defensive backstop for the API-level 409: a reusable session keeps\n // its creation-time attachment, so a diverged task attachment must\n // fail the run instead of silently running with the wrong secrets.\n assertReusableSessionBindingMatches(session, task);\n const bundled = await addSessionSystemUpdateWithSourceMutation(\n dispatchDb,\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n kind: \"scheduled_occurrence\",\n classification: \"info\",\n sourceId: run.id,\n dedupeKey: `scheduled-task-run:${run.id}`,\n summary: task.agentConfig.prompt,\n payload: scheduledUserMessagePayload(\n task.agentConfig.prompt,\n task.agentConfig.resources,\n taskTools,\n task.id,\n run.id,\n ),\n lineage: {\n scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n ...(causalHumanSubjectId ? { causalHumanSubjectId } : {}),\n ...(taskConnectionAuthoritySubjectId\n ? { connectionAuthoritySubjectId: taskConnectionAuthoritySubjectId }\n : {}),\n ...(taskXaiProviderAccountAuthoritySnapshot.scope === \"user\" &&\n task.createdBy.kind === \"subject\"\n ? { xaiAuthoritySubjectId: task.createdBy.subjectId }\n : {}),\n },\n personalConnectionDelegations: taskPersonalConnectionDelegations,\n mcpAccountBindings: taskMcpAccountBindings,\n xaiProviderAccountAuthoritySnapshot: taskXaiProviderAccountAuthoritySnapshot,\n scheduledTaskRunId: run.id,\n },\n async (tx, wakeEventId, _updateId, rejectionReason) => {\n if (!wakeEventId) {\n const error = scheduledSessionRejectionError(rejectionReason);\n await settleScheduledTaskRunInTransaction(tx, {\n workspaceId: task.workspaceId,\n runId: scheduledRun.id,\n sessionId: session.id,\n triggerEventId: null,\n status: \"skipped\",\n error,\n });\n return;\n }\n await settleScheduledTaskRunInTransaction(tx, {\n workspaceId: task.workspaceId,\n runId: scheduledRun.id,\n sessionId: session.id,\n triggerEventId: wakeEventId,\n status: \"dispatched\",\n });\n },\n {\n requireIdleSession: task.overlapPolicy === \"skip\",\n prepareSource: async (tx, sessionId) => {\n const goalEvents =\n task.runMode === \"reusable_session\" && goalSpec && run.status === \"queued\"\n ? await upsertScheduledSessionGoalForRun(tx, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId,\n runId: run.id,\n text: goalSpec.text,\n successCriteria: goalSpec.successCriteria ?? null,\n maxAutoContinuations: goalSpec.maxAutoContinuations ?? null,\n ...(goalSpec.mutationPolicy\n ? { mutationPolicy: goalSpec.mutationPolicy }\n : {}),\n })\n : [];\n const incidentSource = incidentPreflightRequired\n ? await prepareIncidentTelemetrySource({\n tx,\n settings,\n taskId: task.id,\n workspaceId: task.workspaceId,\n sessionId,\n alertOccurrenceLabels: structuredAlertOccurrence?.labels ?? null,\n acceptedExecution,\n })\n : undefined;\n return {\n ...(incidentSource ?? {}),\n ...(goalEvents.length > 0 ? { events: goalEvents } : {}),\n };\n },\n },\n );\n if (bundled.reason === \"session_cancelled\" || bundled.reason === \"session_not_idle\") {\n const error = scheduledSessionRejectionError(bundled.reason);\n return {\n kind: \"blocked\" as const,\n result: { action: \"blocked\" as const, reason: \"scheduled_run_terminal\" as const },\n run: { ...run, status: \"skipped\" as const, error },\n };\n }\n if (bundled.added) {\n recordUserMessageAccepted(baseService.observability, { surface: \"scheduled\" });\n }\n if (bundled.added && bundled.events.length > 0) {\n if (deferPublications) {\n deferredEvents.push({\n sessionId: session.id,\n events: bundled.events,\n });\n } else {\n await publishDurableSessionEvents(\n bus,\n task.workspaceId,\n session.id,\n bundled.events,\n );\n }\n }\n result = {\n action: \"signal\",\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n triggerEventId: bundled.wakeEventId,\n workflowId: workflowIdForSession(session.id),\n workflowWakeRevision: bundled.workflowWakeRevision,\n };\n }\n } catch (error) {\n const terminalError = scheduledRunRecoveryTerminalError(error);\n if (!terminalError) throw error;\n await markScheduledTaskRunFailedIfQueued(\n dispatchDb,\n task.workspaceId,\n run.id,\n terminalError.code,\n );\n return {\n kind: \"blocked\" as const,\n result: scheduledRunTerminalResult(terminalError.code),\n run: { ...run, status: \"failed\" as const, error: terminalError.code },\n };\n }\n await recordUsageEvent(dispatchDb, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n eventType: \"agent_run.created\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"scheduled_task_run\",\n sourceResourceId: run.id,\n sessionId: result.sessionId,\n initiator: input.initiator ?? {\n kind: \"service\",\n subjectId: \"scheduler\",\n },\n initiatorContext: {\n scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n },\n origin: \"scheduled_task\",\n idempotencyKey:\n input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`,\n });\n return { kind: \"complete\" as const, result, run };\n };\n\n let dispatchOutcome: Awaited<ReturnType<typeof executeDispatch>>;\n try {\n dispatchOutcome = incidentPreflightRequired\n ? await withSessionActivityRlsContext(\n db,\n { accountId: task.accountId, workspaceId: task.workspaceId },\n async (tx) => await executeDispatch(tx, true),\n )\n : await executeDispatch(db, false);\n } catch (error) {\n if (error instanceof IncidentTelemetryPreflightBlockedError) {\n return { action: \"blocked\", reason: error.reason };\n }\n const terminalError = scheduledRunRecoveryTerminalError(error);\n if (terminalError?.code === \"scheduled_model_unavailable\") {\n return scheduledRunTerminalResult(terminalError.code);\n }\n throw error;\n }\n if (dispatchOutcome.kind === \"replay\") {\n return await replayScheduledTaskDispatch({\n db,\n wakeSessionWorkflow,\n task,\n run: dispatchOutcome.run,\n acceptedExecution: dispatchOutcome.acceptedExecution,\n });\n }\n for (const deferred of deferredEvents) {\n await publishDurableSessionEvents(\n bus,\n task.workspaceId,\n deferred.sessionId,\n deferred.events,\n );\n }\n if (dispatchOutcome.kind === \"blocked\") return dispatchOutcome.result;\n const result = dispatchOutcome.result;\n if (wakeSessionWorkflow && result.workflowWakeRevision !== null) {\n await wakeSessionWorkflow({\n accountId: result.accountId,\n workspaceId: result.workspaceId,\n sessionId: result.sessionId,\n workflowId: result.workflowId,\n wakeRevision: result.workflowWakeRevision,\n });\n }\n return result;\n },\n };\n}\n\nclass IncidentTelemetryPreflightBlockedError extends Error {\n constructor(readonly reason: IncidentTelemetryPreflightBlockReason) {\n super(reason);\n this.name = \"IncidentTelemetryPreflightBlockedError\";\n }\n}\n\n/**\n * Defensive backstop for the API-level 409: a reusable/existing target session\n * keeps its creation-time attachment, so a diverged task attachment or Slack\n * bot binding must settle the run terminally instead of silently running with\n * the wrong secrets - on the first attempt and on every recovery attempt.\n */\nfunction assertReusableSessionBindingMatches(\n session: { variableSetId: string | null; metadata: Record<string, unknown> },\n task: Pick<ScheduledTask, \"variableSetId\" | \"agentConfig\">,\n): void {\n if ((session.variableSetId ?? null) !== (task.variableSetId ?? null)) {\n throw new ScheduledRunTerminalAuthorityError(\n \"scheduled_reusable_binding_changed\",\n \"scheduled task variableSet attachment does not match its reusable session\",\n );\n }\n if (\n scheduledSlackBotConnectionId(session.metadata) !==\n (task.agentConfig.slackBotConnectionId ?? null)\n ) {\n throw new ScheduledRunTerminalAuthorityError(\n \"scheduled_reusable_binding_changed\",\n \"scheduled task OpenGeni Slack bot binding does not match its reusable session\",\n );\n }\n}\n\nclass ScheduledRunTerminalAuthorityError extends Error {\n constructor(\n readonly code: string,\n message: string,\n ) {\n super(message);\n this.name = \"ScheduledRunTerminalAuthorityError\";\n }\n}\n\nfunction scheduledRunRecoveryTerminalError(\n error: unknown,\n): ScheduledRunTerminalAuthorityError | null {\n if (\n error instanceof Error &&\n \"cause\" in error &&\n error.cause !== undefined &&\n error.cause !== error\n ) {\n const nested = scheduledRunRecoveryTerminalError(error.cause);\n if (nested) return nested;\n }\n if (error instanceof ScheduledRunTerminalAuthorityError) return error;\n if (error instanceof IncidentTelemetryPreflightBlockedError) {\n return new ScheduledRunTerminalAuthorityError(\n `scheduled_incident_${error.reason}`,\n error.message,\n );\n }\n if (error instanceof SessionSpawnDeniedDbError) {\n return new ScheduledRunTerminalAuthorityError(\"scheduled_session_spawn_denied\", error.message);\n }\n if (error instanceof Error && error.message.startsWith(\"Session not found:\")) {\n return new ScheduledRunTerminalAuthorityError(\n \"scheduled_target_session_unavailable\",\n error.message,\n );\n }\n if (typeof error === \"object\" && error !== null && \"status\" in error && error.status === 422) {\n return new ScheduledRunTerminalAuthorityError(\n \"scheduled_slack_authority_unavailable\",\n error instanceof Error ? error.message : \"scheduled Slack authority is unavailable\",\n );\n }\n if (typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"42501\") {\n return new ScheduledRunTerminalAuthorityError(\n \"scheduled_run_authority_proof_rejected\",\n error instanceof Error ? error.message : \"scheduled run authority proof was rejected\",\n );\n }\n return null;\n}\n\n/** The blocked result of a diagnostic (refused) run receipt, fresh or replayed. */\nfunction scheduledAdmissionRefusalResult(\n run: Pick<ScheduledTaskRun, \"id\" | \"admissionDiagnostic\" | \"admissionRefusal\">,\n): Extract<DispatchScheduledTaskRunResult, { action: \"blocked\" }> {\n if (run.admissionRefusal) {\n return {\n action: \"blocked\",\n reason: run.admissionRefusal.reason as ScheduledTaskAdmissionRefusalReason,\n runId: run.id,\n refusal: run.admissionRefusal,\n };\n }\n return {\n action: \"blocked\",\n reason: \"connection_account_unavailable\",\n runId: run.id,\n ...(run.admissionDiagnostic ? { diagnostic: run.admissionDiagnostic } : {}),\n };\n}\n\nfunction scheduledRunTerminalResult(\n error: string | null,\n): Extract<DispatchScheduledTaskRunResult, { action: \"blocked\" }> {\n if (error === \"scheduled_authority_exhausted\") {\n return { action: \"blocked\", reason: \"scheduled_authority_exhausted\" };\n }\n if (error === \"scheduled_incident_incident_preflight_metadata_missing\") {\n return { action: \"blocked\", reason: \"incident_preflight_metadata_missing\" };\n }\n if (error === \"scheduled_incident_incident_responder_under_capable\") {\n return { action: \"blocked\", reason: \"incident_responder_under_capable\" };\n }\n if (error === \"scheduled_incident_incident_data_source_unsuitable\") {\n return { action: \"blocked\", reason: \"incident_data_source_unsuitable\" };\n }\n return { action: \"blocked\", reason: \"scheduled_run_terminal\" };\n}\n\nfunction scheduledSessionRejectionError(\n rejectionReason: \"session_cancelled\" | \"session_not_idle\" | null,\n): \"session_cancelled\" | \"scheduled_session_not_idle\" {\n return rejectionReason === \"session_not_idle\"\n ? \"scheduled_session_not_idle\"\n : \"session_cancelled\";\n}\n\nasync function prepareIncidentTelemetrySource(input: {\n tx: Database;\n settings: ControlActivityServices[\"settings\"];\n taskId: string;\n workspaceId: string;\n sessionId: string;\n alertOccurrenceLabels: Readonly<Record<string, string>> | null;\n acceptedExecution: ScheduledTaskRunAcceptedExecution;\n}) {\n const session = await requireSession(input.tx, input.workspaceId, input.sessionId);\n const { task, personalConnectionDelegations } = input.acceptedExecution;\n const responder = await resolveIncidentTelemetryResponderMetadata({\n db: input.tx,\n settings: input.settings,\n task,\n session,\n personalConnectionDelegations,\n personalResourceAuthoritySubjectId:\n input.acceptedExecution.personalResourceAuthoritySubjectId ?? null,\n executionPolicy: input.acceptedExecution.targetSessionExecution\n ? {\n tools: input.acceptedExecution.targetSessionExecution.tools,\n firstPartyMcpTools: input.acceptedExecution.targetSessionExecution.firstPartyMcpTools,\n firstPartyMcpPermissions:\n input.acceptedExecution.targetSessionExecution.firstPartyMcpPermissions,\n variableSetIds: input.acceptedExecution.targetSessionExecution.variableSets.map(\n (variableSet) => variableSet.id,\n ),\n variableSetId: input.acceptedExecution.targetSessionExecution.variableSetId,\n rigId: input.acceptedExecution.targetSessionExecution.rigId,\n rigVersionId: input.acceptedExecution.targetSessionExecution.rigVersionId,\n toolPolicy: input.acceptedExecution.targetSessionExecution.toolPolicy,\n mcpServerIds: input.acceptedExecution.targetSessionExecution.mcpServerIds,\n toolPolicyVersion: input.acceptedExecution.targetSessionExecution.toolPolicyVersion,\n }\n : {\n tools: input.acceptedExecution.resolvedTools,\n firstPartyMcpTools: input.acceptedExecution.resolvedFirstPartyMcpTools,\n firstPartyMcpPermissions: input.acceptedExecution.resolvedFirstPartyMcpPermissions,\n variableSetId: input.acceptedExecution.resolvedVariableSet?.id ?? null,\n rigId: input.acceptedExecution.resolvedRig?.id ?? null,\n rigVersionId: input.acceptedExecution.resolvedRig?.versionId ?? null,\n toolPolicy: session.toolPolicy,\n mcpServerIds: [],\n toolPolicyVersion: session.toolPolicyVersion,\n },\n });\n const preflight = evaluateIncidentTelemetryPreflight({\n agentConfig: task.agentConfig,\n incidentTriggered: input.alertOccurrenceLabels !== null,\n alertOccurrenceLabels: input.alertOccurrenceLabels,\n responder,\n });\n if (preflight.action === \"blocked\") {\n throw new IncidentTelemetryPreflightBlockedError(preflight.reason);\n }\n const fence = incidentTelemetryAuthorityFence({\n task,\n responder,\n alertOccurrenceLabels: input.alertOccurrenceLabels,\n });\n if (!fence) {\n throw new IncidentTelemetryPreflightBlockedError(\"incident_preflight_metadata_missing\");\n }\n return {\n lineage: {\n [INCIDENT_TELEMETRY_AUTHORITY_FENCE_LINEAGE_KEY]: fence,\n },\n };\n}\n\nasync function recordScheduledTaskFiredUsage(\n db: Database,\n acceptedExecution: ScheduledTaskRunAcceptedExecution,\n run: ScheduledTaskRun,\n): Promise<void> {\n const task = acceptedExecution.task;\n await recordUsageEvent(db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n eventType: \"scheduled_task.fired\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"scheduled_task_run\",\n sourceResourceId: run.id,\n initiator: acceptedExecution.triggerInitiator,\n initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },\n origin: \"scheduled_task\",\n idempotencyKey: `usage:scheduled_task.fired:${run.id}`,\n });\n}\n\nasync function seedScheduledGeneratedSessionRoute(input: {\n db: Database;\n bus: ControlActivityServices[\"bus\"];\n settings: ControlActivityServices[\"settings\"];\n task: ScheduledTask;\n runId: string;\n session: Awaited<ReturnType<typeof createSession>>;\n deferPublications: boolean;\n deferredEvents: Array<{\n sessionId: string;\n events: Awaited<ReturnType<typeof appendSessionEvents>>;\n }>;\n}): Promise<Awaited<ReturnType<typeof createSession>>> {\n const target = input.task.agentConfig.machineTarget;\n if (!target) return input.session;\n const seeded = await swapActiveSandbox(\n {\n db: input.db,\n settings: input.settings,\n bus: input.bus,\n },\n {\n accountId: input.task.accountId,\n workspaceId: input.task.workspaceId,\n sessionId: input.session.id,\n sessionBackend: input.session.sandboxBackend,\n sessionGroupId: input.session.sandboxGroupId,\n },\n target.targetSandboxId,\n target.workingDir ?? null,\n );\n if (seeded.swapped) {\n return await requireSession(input.db, input.task.workspaceId, input.session.id);\n }\n\n const failed = await failScheduledGeneratedSessionRoute(input.db, {\n accountId: input.task.accountId,\n workspaceId: input.task.workspaceId,\n taskId: input.task.id,\n runId: input.runId,\n sessionId: input.session.id,\n error: \"scheduled_machine_unavailable\",\n });\n if (failed.action === \"advanced\") {\n throw new Error(\n `scheduled run advanced to ${failed.status} while its Connected Machine route was being established`,\n );\n }\n if (failed.events.length > 0) {\n if (input.deferPublications) {\n input.deferredEvents.push({ sessionId: input.session.id, events: failed.events });\n } else {\n await publishDurableSessionEvents(\n input.bus,\n input.task.workspaceId,\n input.session.id,\n failed.events,\n );\n }\n }\n const error =\n failed.action === \"terminal\" ? (failed.error ?? \"scheduled_run_terminal\") : failed.error;\n throw new ScheduledRunTerminalAuthorityError(\n error,\n seeded.reason ?? \"scheduled Connected Machine target is unavailable\",\n );\n}\n\nasync function recoverBoundScheduledTaskDispatch(input: {\n db: Database;\n observability?: ProductUsageMetricsSink | undefined;\n bus: ControlActivityServices[\"bus\"];\n settings: ControlActivityServices[\"settings\"];\n wakeSessionWorkflow: WakeSessionWorkflowSignal | null;\n run: ScheduledTaskRun;\n acceptedExecution: ScheduledTaskRunAcceptedExecution;\n input: DispatchScheduledTaskRunInput;\n}): Promise<DispatchScheduledTaskRunResult> {\n const { task } = input.acceptedExecution;\n if (input.run.status !== \"queued\") {\n throw new Error(\"scheduled run is not an exact queued recovery\");\n }\n const generatedSession =\n task.runMode === \"new_session_per_run\" ||\n (task.runMode === \"reusable_session\" && task.reusableSessionId === null);\n // The immutable creator policy determines standing session authority, not\n // a manual caller's per-run ceiling. Read it for creation and recovery checks.\n const recoveredCreatorPolicy = generatedSession\n ? await getScheduledTaskCreatorPolicy(input.db, task.workspaceId, task.id)\n : null;\n const frozenSlack = input.acceptedExecution.resolvedSlackBotConnection;\n if (frozenSlack) {\n const currentSlack = await requireOpenGeniSlackBotConnection(\n input.db,\n task.workspaceId,\n frozenSlack.id,\n );\n const currentMetadata = openGeniSlackBotMetadata(currentSlack.metadata);\n if (\n currentSlack.version !== frozenSlack.version ||\n currentSlack.verifiedInstallVersion !== frozenSlack.verifiedInstallVersion ||\n stableJson(currentMetadata) !== stableJson(frozenSlack.metadata)\n ) {\n throw new ScheduledRunTerminalAuthorityError(\n \"scheduled_slack_authority_changed\",\n \"scheduled Slack bot authority changed after run admission\",\n );\n }\n }\n let session: Awaited<ReturnType<typeof createSession>>;\n if (input.run.sessionId) {\n session = await requireSession(input.db, task.workspaceId, input.run.sessionId);\n // A bound existing/reusable target must still carry the exact Variable Set\n // and Slack bot binding frozen with this occurrence; recovery must fail the\n // run terminally rather than deliver into a diverged session.\n if (!generatedSession) assertReusableSessionBindingMatches(session, task);\n } else if (generatedSession) {\n const variableSet = input.acceptedExecution.resolvedVariableSet;\n if (variableSet) {\n const current = await getVariableSet(\n input.db,\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n subjectId:\n input.acceptedExecution.personalResourceAuthoritySubjectId ?? task.createdBy.subjectId,\n },\n variableSet.id,\n );\n if (!current || current.generation !== variableSet.generation) {\n throw new ScheduledRunTerminalAuthorityError(\n \"scheduled_variable_set_authority_changed\",\n \"scheduled variable set changed after run admission\",\n );\n }\n }\n const rig = input.acceptedExecution.resolvedRig;\n if (rig) {\n const retained = await getScheduledScopedRigVersionMetadata(\n input.db,\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n subjectId:\n input.acceptedExecution.personalResourceAuthoritySubjectId ?? task.createdBy.subjectId,\n },\n rig.id,\n rig.versionId,\n );\n if (!retained) {\n throw new ScheduledRunTerminalAuthorityError(\n \"scheduled_rig_authority_changed\",\n \"scheduled rig changed after run admission\",\n );\n }\n }\n const taskMetadata = { ...task.agentConfig.metadata };\n delete taskMetadata[OPENGENI_SLACK_BOT_SESSION_METADATA_KEY];\n const created = await createSessionWithIdempotencyKeyResult(input.db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n initialMessage: task.agentConfig.prompt,\n resources: task.agentConfig.resources,\n bundledSkillIds: task.agentConfig.bundledSkillIds,\n tools: input.acceptedExecution.resolvedTools,\n firstPartyMcpTools: input.acceptedExecution.resolvedFirstPartyMcpTools,\n firstPartyMcpPermissions: input.acceptedExecution.resolvedFirstPartyMcpPermissions,\n ...(input.acceptedExecution.resolvedAgentConfig\n ? { agentConfig: input.acceptedExecution.resolvedAgentConfig }\n : {}),\n ...(input.acceptedExecution.resolvedAgentInstructions !== undefined\n ? { instructions: input.acceptedExecution.resolvedAgentInstructions }\n : {}),\n ...scheduledCreatorSessionPolicyInput(recoveredCreatorPolicy?.sessionPolicy ?? null),\n ...(task.agentConfig.knowledgeSource?.destination.kind === \"personal\"\n ? {\n visibility: \"user_private\" as const,\n scheduledSourceRunId: input.run.id,\n }\n : {}),\n metadata: {\n ...taskMetadata,\n ...scheduledSessionExecutionPolicyMetadata(\n input.acceptedExecution.turnExecutionPolicy,\n recoveredCreatorPolicy?.credentialRestriction,\n ),\n model: input.acceptedExecution.resolvedModel,\n reasoningEffort: input.acceptedExecution.resolvedReasoningEffort,\n scheduledTaskId: task.id,\n scheduledTaskRunMode: task.runMode,\n ...(task.agentConfig.goal ? { scheduledTaskGoal: task.agentConfig.goal } : {}),\n scheduledTaskRunId: input.run.id,\n ...(frozenSlack ? { [OPENGENI_SLACK_BOT_SESSION_METADATA_KEY]: frozenSlack.id } : {}),\n },\n createdBy: {\n kind: \"service\",\n subjectId: \"scheduler\",\n label: \"OpenGeni scheduler\",\n },\n createdByContext: {\n scheduledTaskId: task.id,\n scheduledTaskRunId: input.run.id,\n },\n model: input.acceptedExecution.resolvedModel,\n reasoningEffort: input.acceptedExecution.resolvedReasoningEffort,\n latencyMode: input.acceptedExecution.resolvedLatencyMode,\n sandboxBackend: input.acceptedExecution.resolvedSandboxBackend,\n sandboxOs: input.acceptedExecution.resolvedSandboxOs,\n variableSetId: variableSet?.id ?? null,\n rigId: rig?.id ?? null,\n rigVersionId: rig?.versionId ?? null,\n personalConnectionDelegations: [],\n initialXaiProviderAccountAuthoritySnapshot:\n input.acceptedExecution.xaiProviderAccountAuthoritySnapshot,\n maxNestedAgentDepthOverride: task.agentConfig.maxNestedAgentDepth ?? null,\n frozenNestedAgentDepthPolicy: {\n effectiveMaxNestedAgentDepth:\n input.acceptedExecution.generatedSessionBinding!.effectiveMaxNestedAgentDepth,\n nestedAgentDepthPolicySource:\n input.acceptedExecution.generatedSessionBinding!.nestedAgentDepthPolicySource,\n },\n frozenCodexCompactionMode:\n input.acceptedExecution.generatedSessionBinding!.codexCompactionMode,\n allowNestedAgentDepthIncrease: true,\n subjectId: `scheduled_task:${task.id}`,\n createIdempotencyKey:\n input.acceptedExecution.generatedSessionBinding?.createIdempotencyKey ??\n (() => {\n throw new ScheduledRunTerminalAuthorityError(\n \"scheduled_generated_session_binding_missing\",\n \"scheduled generated session binding is missing\",\n );\n })(),\n beforeCreateCommit: async (tx, sessionId) => {\n await bindScheduledTaskRunSessionInTransaction(tx, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n runId: input.run.id,\n sessionId,\n });\n },\n });\n if (created.denied) throw new SessionSpawnDeniedDbError(created.denial);\n session = created.session;\n if (created.created) recordScheduledSessionCreated(input.observability);\n if (!created.created) {\n await bindScheduledTaskRunSessionInTransaction(input.db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n runId: input.run.id,\n sessionId: session.id,\n });\n }\n } else {\n const targetSessionId =\n task.runMode === \"existing_session\" ? task.targetSessionId : task.reusableSessionId;\n if (!targetSessionId) {\n throw new ScheduledRunTerminalAuthorityError(\n \"scheduled_target_session_unavailable\",\n \"scheduled accepted target session is unavailable\",\n );\n }\n session = await requireSession(input.db, task.workspaceId, targetSessionId);\n // Same backstop for a first attempt that died before its bind landed.\n assertReusableSessionBindingMatches(session, task);\n await bindScheduledTaskRunSessionInTransaction(input.db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n runId: input.run.id,\n sessionId: session.id,\n });\n }\n if (generatedSession) {\n session = await seedScheduledGeneratedSessionRoute({\n db: input.db,\n bus: input.bus,\n settings: input.settings,\n task,\n runId: input.run.id,\n session,\n deferPublications: false,\n deferredEvents: [],\n });\n }\n if (session.status === \"cancelled\") {\n await markScheduledTaskRunSkippedIfQueued(input.db, {\n workspaceId: task.workspaceId,\n runId: input.run.id,\n sessionId: session.id,\n error: \"session_cancelled\",\n });\n return { action: \"blocked\", reason: \"scheduled_run_terminal\" };\n }\n if (generatedSession) {\n const expectedCreateKey = input.acceptedExecution.generatedSessionBinding?.createIdempotencyKey;\n if (!expectedCreateKey) {\n throw new ScheduledRunTerminalAuthorityError(\n \"scheduled_generated_session_binding_missing\",\n \"scheduled generated session binding is missing\",\n );\n }\n const generatedBinding = input.acceptedExecution.generatedSessionBinding!;\n const canonicalGeneratedRunId =\n task.runMode === \"reusable_session\" && typeof session.metadata.scheduledTaskRunId === \"string\"\n ? session.metadata.scheduledTaskRunId\n : input.run.id;\n // The public Session policy follows the latest started turn. Recovery must\n // instead validate the immutable creation binding accepted by this run.\n const creationPolicy = await getSessionCreationExecutionPolicy(\n input.db,\n task.workspaceId,\n session.id,\n );\n const expectedTaskMetadata = { ...task.agentConfig.metadata };\n delete expectedTaskMetadata[OPENGENI_SLACK_BOT_SESSION_METADATA_KEY];\n const expectedMetadata = metadataWithAgentConfigCreateIdentity(\n {\n ...expectedTaskMetadata,\n ...scheduledSessionExecutionPolicyMetadata(\n input.acceptedExecution.turnExecutionPolicy,\n recoveredCreatorPolicy?.credentialRestriction,\n ),\n model: input.acceptedExecution.resolvedModel,\n reasoningEffort: input.acceptedExecution.resolvedReasoningEffort,\n scheduledTaskId: task.id,\n scheduledTaskRunMode: task.runMode,\n ...(task.agentConfig.goal ? { scheduledTaskGoal: task.agentConfig.goal } : {}),\n scheduledTaskRunId: canonicalGeneratedRunId,\n ...(frozenSlack ? { [OPENGENI_SLACK_BOT_SESSION_METADATA_KEY]: frozenSlack.id } : {}),\n },\n input.acceptedExecution.resolvedAgentConfig,\n );\n if (\n session.createIdempotencyKey !== expectedCreateKey ||\n session.initialMessage !== task.agentConfig.prompt ||\n session.instructions !== (input.acceptedExecution.resolvedAgentInstructions ?? null) ||\n session.policyRole !== null ||\n stableJson(session.skills) !== \"[]\" ||\n stableJson(session.toolPolicy) !==\n stableJson({ mode: \"explicit\", inheritedFromSessionId: null }) ||\n session.toolPolicyVersion !== 1 ||\n session.mcpServers.length !== 0 ||\n session.parentSessionId !== null ||\n session.rootSessionId !== session.id ||\n session.nestedAgentDepth !== 0 ||\n session.effectiveMaxNestedAgentDepth !== generatedBinding.effectiveMaxNestedAgentDepth ||\n session.nestedAgentDepthPolicySource !== generatedBinding.nestedAgentDepthPolicySource ||\n session.nestedAgentDepthPolicySessionId !==\n (generatedBinding.nestedAgentDepthPolicySource === \"session\" ? session.id : null) ||\n session.sandboxGroupId !== session.id ||\n session.channelId !== null ||\n session.codexCompactionMode !== generatedBinding.codexCompactionMode ||\n stableJson(session.metadata) !== stableJson(expectedMetadata) ||\n session.createdBy.kind !== \"service\" ||\n session.createdBy.subjectId !== \"scheduler\" ||\n stableJson(session.createdByContext) !==\n stableJson({\n label: \"OpenGeni scheduler\",\n scheduledTaskId: task.id,\n scheduledTaskRunId: canonicalGeneratedRunId,\n }) ||\n (task.runMode === \"new_session_per_run\" &&\n input.acceptedExecution.alertOccurrenceLabels === null &&\n (session.metadata.scheduledTaskRunId !== input.run.id ||\n session.createdByContext.scheduledTaskRunId !== input.run.id)) ||\n creationPolicy?.model !== input.acceptedExecution.resolvedModel ||\n creationPolicy.reasoningEffort !== input.acceptedExecution.resolvedReasoningEffort ||\n creationPolicy.latencyMode !== input.acceptedExecution.resolvedLatencyMode ||\n session.sandboxBackend !== input.acceptedExecution.resolvedSandboxBackend ||\n session.sandboxOs !== input.acceptedExecution.resolvedSandboxOs ||\n session.activeSandboxId !== (task.agentConfig.machineTarget?.targetSandboxId ?? null) ||\n stableJson(session.resources) !== stableJson(task.agentConfig.resources) ||\n stableJson(session.tools) !== stableJson(input.acceptedExecution.resolvedTools) ||\n stableJson(session.firstPartyMcpTools) !==\n stableJson(input.acceptedExecution.resolvedFirstPartyMcpTools) ||\n stableJson(session.firstPartyMcpPermissions) !==\n stableJson(input.acceptedExecution.resolvedFirstPartyMcpPermissions) ||\n stableJson(session.agent) !==\n stableJson(input.acceptedExecution.resolvedAgentConfig ?? null) ||\n session.maxNestedAgentDepthOverride !== (task.agentConfig.maxNestedAgentDepth ?? null) ||\n (session.variableSetId ?? null) !==\n (input.acceptedExecution.resolvedVariableSet?.id ?? null) ||\n (session.rigId ?? null) !== (input.acceptedExecution.resolvedRig?.id ?? null) ||\n (session.rigVersionId ?? null) !== (input.acceptedExecution.resolvedRig?.versionId ?? null) ||\n scheduledSlackBotConnectionId(session.metadata) !== (frozenSlack?.id ?? null)\n ) {\n throw new ScheduledRunTerminalAuthorityError(\n \"scheduled_generated_session_changed\",\n \"scheduled generated session differs from accepted execution\",\n );\n }\n }\n let workflowId = workflowIdForSession(session.id);\n if (generatedSession) {\n const goalSpec = task.agentConfig.goal ?? null;\n const started = await initializeSessionStartAtomically(input.db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n reasoningEffortFallback: input.acceptedExecution.resolvedReasoningEffort,\n createdEventPayload: {\n scheduledTaskId: task.id,\n scheduledTaskRunId: input.run.id,\n },\n goal: goalSpec\n ? {\n text: goalSpec.text,\n successCriteria: goalSpec.successCriteria ?? null,\n maxAutoContinuations: goalSpec.maxAutoContinuations ?? null,\n ...(goalSpec.mutationPolicy ? { mutationPolicy: goalSpec.mutationPolicy } : {}),\n createdBy: \"scheduled_task\",\n }\n : null,\n deferInitialTurn: true,\n deferredStatus: \"queued\",\n });\n workflowId = started.temporalWorkflowId;\n if (started.events.length > 0) {\n await publishDurableSessionEvents(input.bus, task.workspaceId, session.id, started.events);\n }\n if (task.runMode === \"reusable_session\") {\n await materializeScheduledTaskReusableSessionFromRun(input.db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n runId: input.run.id,\n sessionId: session.id,\n sourceTaskAuthorityRevision: input.run.taskAuthorityRevision!,\n sourceExecutionDigest: input.run.taskExecutionDigest!,\n });\n }\n // Same title the normal dispatch writes, from the same durable task row, in\n // the same position relative to session.created. A session the dead dispatch\n // already titled is left alone.\n const titleEvents = await stampScheduledSessionTitle(input.db, {\n workspaceId: task.workspaceId,\n sessionId: session.id,\n taskName: task.name,\n });\n if (titleEvents.length > 0) {\n await publishDurableSessionEvents(input.bus, task.workspaceId, session.id, titleEvents);\n }\n }\n const scheduledUpdate = await addSessionSystemUpdateWithSourceMutation(\n input.db,\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n kind: \"scheduled_occurrence\",\n classification: \"info\",\n sourceId: input.run.id,\n dedupeKey: `scheduled-task-run:${input.run.id}`,\n summary: task.agentConfig.prompt,\n payload: scheduledUserMessagePayload(\n task.agentConfig.prompt,\n task.agentConfig.resources,\n input.acceptedExecution.resolvedTools,\n task.id,\n input.run.id,\n ),\n lineage: {\n scheduledTaskId: task.id,\n scheduledTaskRunId: input.run.id,\n ...(input.acceptedExecution.causalHumanSubjectId\n ? { causalHumanSubjectId: input.acceptedExecution.causalHumanSubjectId }\n : {}),\n ...(input.acceptedExecution.connectionAuthoritySubjectId\n ? {\n connectionAuthoritySubjectId: input.acceptedExecution.connectionAuthoritySubjectId,\n }\n : {}),\n ...(input.acceptedExecution.xaiAuthoritySubjectId\n ? { xaiAuthoritySubjectId: input.acceptedExecution.xaiAuthoritySubjectId }\n : {}),\n },\n personalConnectionDelegations: input.acceptedExecution.personalConnectionDelegations,\n mcpAccountBindings: input.acceptedExecution.mcpAccountBindings ?? null,\n xaiProviderAccountAuthoritySnapshot:\n input.acceptedExecution.xaiProviderAccountAuthoritySnapshot,\n scheduledTaskRunId: input.run.id,\n },\n async (tx, wakeEventId, _updateId, rejectionReason) => {\n if (!wakeEventId) {\n const error = scheduledSessionRejectionError(rejectionReason);\n await settleScheduledTaskRunInTransaction(tx, {\n workspaceId: task.workspaceId,\n runId: input.run.id,\n sessionId: session.id,\n triggerEventId: null,\n status: \"skipped\",\n error,\n });\n return;\n }\n await settleScheduledTaskRunInTransaction(tx, {\n workspaceId: task.workspaceId,\n runId: input.run.id,\n sessionId: session.id,\n triggerEventId: wakeEventId,\n status: \"dispatched\",\n });\n },\n {\n requireIdleSession: task.overlapPolicy === \"skip\" && !generatedSession,\n prepareSource: async (tx, sessionId) => {\n const goal = task.agentConfig.goal;\n const goalEvents =\n !generatedSession && task.runMode === \"reusable_session\" && goal\n ? await upsertScheduledSessionGoalForRun(tx, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId,\n runId: input.run.id,\n text: goal.text,\n successCriteria: goal.successCriteria ?? null,\n maxAutoContinuations: goal.maxAutoContinuations ?? null,\n ...(goal.mutationPolicy ? { mutationPolicy: goal.mutationPolicy } : {}),\n })\n : [];\n const incidentSource = input.acceptedExecution.incidentPreflightRequired\n ? await prepareIncidentTelemetrySource({\n tx,\n settings: input.settings,\n taskId: task.id,\n workspaceId: task.workspaceId,\n sessionId,\n alertOccurrenceLabels: input.acceptedExecution.alertOccurrenceLabels,\n acceptedExecution: input.acceptedExecution,\n })\n : undefined;\n return {\n ...(incidentSource ?? {}),\n ...(goalEvents.length > 0 ? { events: goalEvents } : {}),\n };\n },\n },\n );\n if (\n scheduledUpdate.reason === \"session_cancelled\" ||\n scheduledUpdate.reason === \"session_not_idle\"\n ) {\n return { action: \"blocked\", reason: \"scheduled_run_terminal\" };\n }\n if (scheduledUpdate.added) {\n recordUserMessageAccepted(input.observability, { surface: \"scheduled\" });\n }\n if (scheduledUpdate.added && scheduledUpdate.events.length > 0) {\n await publishDurableSessionEvents(\n input.bus,\n task.workspaceId,\n session.id,\n scheduledUpdate.events,\n );\n }\n await recordUsageEvent(input.db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n eventType: \"agent_run.created\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"scheduled_task_run\",\n sourceResourceId: input.run.id,\n sessionId: session.id,\n initiator: input.acceptedExecution.triggerInitiator,\n initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: input.run.id },\n origin: \"scheduled_task\",\n idempotencyKey:\n input.acceptedExecution.agentRunUsageIdempotencyKey ??\n `usage:agent_run.created:scheduled:${input.run.id}`,\n });\n const workflowWakeRevision = await enqueueSessionWorkflowWakeIfRunnable(input.db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n temporalWorkflowId: workflowId,\n reason: \"scheduled_retry\",\n });\n const result = {\n action: generatedSession ? \"start\" : \"signal\",\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n triggerEventId: scheduledUpdate.wakeEventId,\n workflowId,\n workflowWakeRevision,\n } as const;\n if (input.wakeSessionWorkflow && workflowWakeRevision !== null) {\n await input.wakeSessionWorkflow({\n accountId: result.accountId,\n workspaceId: result.workspaceId,\n sessionId: result.sessionId,\n workflowId: result.workflowId,\n wakeRevision: workflowWakeRevision,\n });\n }\n return result;\n}\n\nasync function replayScheduledTaskDispatch(input: {\n db: Database;\n wakeSessionWorkflow: WakeSessionWorkflowSignal | null;\n task: ScheduledTask;\n run: ScheduledTaskRun;\n acceptedExecution: ScheduledTaskRunAcceptedExecution;\n}): Promise<DispatchScheduledTaskRunResult> {\n if (!input.run.sessionId || !input.run.triggerEventId) {\n throw new Error(\"dispatched scheduled task run is missing its delivery identity\");\n }\n const sessionId = input.run.sessionId;\n const triggerEventId = input.run.triggerEventId;\n await requireSession(input.db, input.task.workspaceId, sessionId);\n await recordUsageEvent(input.db, {\n accountId: input.task.accountId,\n workspaceId: input.task.workspaceId,\n eventType: \"agent_run.created\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"scheduled_task_run\",\n sourceResourceId: input.run.id,\n sessionId,\n initiator: input.acceptedExecution.triggerInitiator,\n initiatorContext: {\n scheduledTaskId: input.task.id,\n scheduledTaskRunId: input.run.id,\n },\n origin: \"scheduled_task\",\n idempotencyKey:\n input.acceptedExecution.agentRunUsageIdempotencyKey ??\n `usage:agent_run.created:scheduled:${input.run.id}`,\n });\n const workflowId = workflowIdForSession(sessionId);\n const workflowWakeRevision = await enqueueSessionWorkflowWakeIfRunnable(input.db, {\n accountId: input.task.accountId,\n workspaceId: input.task.workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n reason: \"scheduled_retry\",\n });\n const result = {\n action: input.acceptedExecution.task.runMode === \"new_session_per_run\" ? \"start\" : \"signal\",\n accountId: input.task.accountId,\n workspaceId: input.task.workspaceId,\n sessionId,\n triggerEventId,\n workflowId,\n workflowWakeRevision,\n } as const;\n if (input.wakeSessionWorkflow && workflowWakeRevision !== null) {\n await input.wakeSessionWorkflow({\n accountId: result.accountId,\n workspaceId: result.workspaceId,\n sessionId: result.sessionId,\n workflowId: result.workflowId,\n wakeRevision: workflowWakeRevision,\n });\n }\n return result;\n}\n\n/**\n * Session-create fields carried by a frozen creator session policy. Only the\n * facts the creating session projection exposed at task creation are set;\n * a null (or no longer valid) key leaves the generated session on its own\n * default. The field names are the session access-scope contract\n * (`agentAccess`, `scopeSubjectId`, `memoryScope`) consumed by session create.\n */\nfunction scheduledCreatorSessionPolicyInput(\n policy: {\n agentAccess: string | null;\n scopeSubjectId: string | null;\n memoryScope: string | null;\n } | null,\n): {\n agentAccess?: SessionAgentAccess;\n scopeSubjectId?: string;\n memoryScope?: SessionMemoryScope;\n} {\n if (!policy) return {};\n const agentAccess = SessionAgentAccess.safeParse(policy.agentAccess);\n const memoryScope = SessionMemoryScope.safeParse(policy.memoryScope);\n return {\n ...(agentAccess.success ? { agentAccess: agentAccess.data } : {}),\n // This is a trusted DB admission input, not the public create payload.\n // Preserve the immutable creator policy through scheduled materialization.\n ...(policy.scopeSubjectId && /^(?:user:|external_user:).+/u.test(policy.scopeSubjectId)\n ? { scopeSubjectId: policy.scopeSubjectId }\n : {}),\n ...(memoryScope.success ? { memoryScope: memoryScope.data } : {}),\n };\n}\n\nfunction knowledgeSourceSyncEffectivelyPaused(task: {\n status: \"active\" | \"paused\";\n metadata: Record<string, unknown>;\n}): boolean {\n if (task.status === \"paused\") return true;\n const value = task.metadata.knowledgeSourceSync;\n if (!value || typeof value !== \"object\") return false;\n const control = value as Record<string, unknown>;\n return control.sourceEnabled === false || control.connectionPaused === true;\n}\n","import { createHash } from \"node:crypto\";\n\nconst MAX_SCHEDULED_TASK_ID_BYTES = 256;\nconst MAX_STARTS_AT_BYTES = 256;\nconst MAX_PROVIDER_BYTES = 256;\nconst MAX_FINGERPRINT_BYTES = 1_024;\nconst MAX_LABELS = 256;\nconst MAX_LABEL_KEY_BYTES = 256;\nconst MAX_LABEL_VALUE_BYTES = 4_096;\nconst OFFSET_TIMESTAMP =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?(?:Z|[+-](\\d{2}):(\\d{2}))$/;\n\nexport type ScheduledAlertOccurrenceDeclaration = {\n status: \"firing\" | \"resolved\";\n startsAt: string;\n fingerprint: string;\n labels: Record<string, string>;\n provider?: string;\n};\n\nexport type ScheduledAlertOccurrenceIdentity = {\n status: \"firing\" | \"resolved\";\n sessionCreateIdempotencyKey: string;\n /** Exact bounded labels from the validated structured occurrence. */\n labels: Readonly<Record<string, string>>;\n};\n\n/**\n * Bind the series-stable occurrence identity to one accepted task execution\n * definition. A later task revision must not adopt the prior responder root,\n * because that session has already frozen the old prompt/tool/authority policy.\n */\nexport function scheduledAlertResponderSessionCreateIdempotencyKey(input: {\n occurrence: ScheduledAlertOccurrenceIdentity;\n taskAuthorityRevision: number;\n taskExecutionDigest: string;\n}): string {\n const digest = createHash(\"sha256\")\n .update(\n JSON.stringify({\n version: 1,\n occurrenceKey: input.occurrence.sessionCreateIdempotencyKey,\n taskAuthorityRevision: input.taskAuthorityRevision,\n taskExecutionDigest: input.taskExecutionDigest,\n }),\n )\n .digest(\"hex\");\n return `scheduled-alert-occurrence:v1:${digest}`;\n}\n\n/**\n * Derive one content-free, workspace-bound identity for an Alertmanager-style\n * alert occurrence. Missing or malformed metadata deliberately returns null so\n * ordinary scheduled tasks retain their existing new-session-per-run behavior.\n */\nexport function scheduledAlertOccurrenceIdentity(input: {\n workspaceId: string;\n scheduledTaskId: string;\n metadata: Record<string, unknown>;\n}): ScheduledAlertOccurrenceIdentity | null {\n const scheduledTaskId = boundedString(input.scheduledTaskId, MAX_SCHEDULED_TASK_ID_BYTES);\n if (!scheduledTaskId) return null;\n\n const alert = record(input.metadata.alert);\n if (!alert) return null;\n\n const status = alert.status;\n if (status !== \"firing\" && status !== \"resolved\") return null;\n\n const startsAt = canonicalTimestamp(alert.startsAt);\n const fingerprint = boundedString(alert.fingerprint, MAX_FINGERPRINT_BYTES);\n const labels = canonicalLabels(alert.labels);\n if (!startsAt || !fingerprint || !labels) return null;\n\n const provider = boundedString(\n alert.provider ?? input.metadata.alertProvider ?? input.metadata.provider ?? \"alertmanager\",\n MAX_PROVIDER_BYTES,\n );\n if (!provider) return null;\n const digest = createHash(\"sha256\")\n .update(\n JSON.stringify({\n version: 1,\n workspaceId: input.workspaceId,\n scheduledTaskId,\n provider,\n fingerprint,\n startsAt,\n labels,\n }),\n )\n .digest(\"hex\");\n return {\n status,\n sessionCreateIdempotencyKey: `scheduled-alert-occurrence:v1:${digest}`,\n labels: Object.fromEntries(labels),\n };\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction boundedString(value: unknown, maxBytes: number): string | null {\n if (typeof value !== \"string\") return null;\n const normalized = value.trim();\n if (!normalized || Buffer.byteLength(normalized, \"utf8\") > maxBytes) return null;\n return normalized;\n}\n\nfunction canonicalTimestamp(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n if (!trimmed || Buffer.byteLength(trimmed, \"utf8\") > MAX_STARTS_AT_BYTES) return null;\n const match = OFFSET_TIMESTAMP.exec(trimmed);\n if (!match) return null;\n const [\n ,\n yearText,\n monthText,\n dayText,\n hourText,\n minuteText,\n secondText,\n ,\n offsetHourText,\n offsetMinuteText,\n ] = match;\n const year = Number(yearText);\n const month = Number(monthText);\n const day = Number(dayText);\n const hour = Number(hourText);\n const minute = Number(minuteText);\n const second = secondText === undefined ? 0 : Number(secondText);\n const offsetHour = offsetHourText === undefined ? 0 : Number(offsetHourText);\n const offsetMinute = offsetMinuteText === undefined ? 0 : Number(offsetMinuteText);\n const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n if (\n month < 1 ||\n month > 12 ||\n day < 1 ||\n day > daysInMonth[month - 1]! ||\n hour > 23 ||\n minute > 59 ||\n second > 59 ||\n offsetHour > 23 ||\n offsetMinute > 59\n ) {\n return null;\n }\n const parsed = new Date(trimmed);\n return Number.isFinite(parsed.getTime()) ? trimmed : null;\n}\n\nfunction canonicalLabels(value: unknown): Array<readonly [string, string]> | null {\n const labels = record(value);\n if (!labels) return null;\n const entries = Object.entries(labels);\n if (entries.length === 0 || entries.length > MAX_LABELS) return null;\n const canonical: Array<readonly [string, string]> = [];\n for (const [key, rawValue] of entries) {\n if (\n !key ||\n Buffer.byteLength(key, \"utf8\") > MAX_LABEL_KEY_BYTES ||\n typeof rawValue !== \"string\" ||\n Buffer.byteLength(rawValue, \"utf8\") > MAX_LABEL_VALUE_BYTES\n ) {\n return null;\n }\n canonical.push([key, rawValue]);\n }\n return canonical.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n}\n","import { resolveTurnExecutionPolicyV1 } from \"@opengeni/config\";\nimport {\n DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,\n SITE_AUTH_MAINTENANCE_CONNECTION_CONTEXT_KEY,\n SITE_AUTH_MAINTENANCE_OPERATION_CONTEXT_KEY,\n type FirstPartyMcpToolName,\n} from \"@opengeni/contracts\";\nimport {\n assertWorkspaceModelPolicyAllows,\n canonicalConfiguredModel,\n createAndStartSessionWithOutcome,\n recordWorkspaceUsage,\n resolveCatalogSettings,\n} from \"@opengeni/core\";\nimport {\n claimSiteAuthMaintenance,\n confirmSiteAuthMaintenanceSessionInTransaction,\n deferSiteAuthMaintenance,\n type SiteAuthMaintenanceClaim,\n} from \"@opengeni/db\";\nimport { agentRunAdmissionDenial } from \"./agent-run-admission\";\nimport type { ControlActivityServices } from \"./types\";\n\nexport const SITE_AUTH_MAINTENANCE_CLAIM_TIMEOUT_MS = 10 * 60 * 1_000;\nexport const SITE_AUTH_MAINTENANCE_BATCH_SIZE = 16;\n\nconst MAINTENANCE_TOOLS = [\n \"interaction_discover\",\n \"browser_open\",\n \"browser_tabs\",\n \"browser_observe\",\n \"browser_act\",\n \"browser_debug\",\n \"browser_auth\",\n \"interaction_request_human\",\n \"browser_identity\",\n \"browser_lifecycle\",\n] as const satisfies readonly FirstPartyMcpToolName[];\n\nexport type MaintainSiteAuthConnectionsResult = {\n claimed: number;\n started: number;\n deferred: number;\n};\n\nexport type SiteAuthMaintenanceOptions = {\n claimTimeoutMs?: number;\n batchSize?: number;\n claim?: typeof claimSiteAuthMaintenance;\n confirm?: typeof confirmSiteAuthMaintenanceSessionInTransaction;\n defer?: typeof deferSiteAuthMaintenance;\n createSession?: typeof createAndStartSessionWithOutcome;\n admit?: typeof agentRunAdmissionDenial;\n recordUsage?: typeof recordWorkspaceUsage;\n assertModelPolicy?: typeof assertWorkspaceModelPolicyAllows;\n};\n\n/** Dispatch bounded, auditable agent sessions for due authentication checks.\n * A hidden claim id/session id pair makes every crash point replayable. */\nexport function createSiteAuthMaintenanceActivities(\n services: () => Promise<ControlActivityServices>,\n options: SiteAuthMaintenanceOptions = {},\n) {\n const claimTimeoutMs = options.claimTimeoutMs ?? SITE_AUTH_MAINTENANCE_CLAIM_TIMEOUT_MS;\n const batchSize = options.batchSize ?? SITE_AUTH_MAINTENANCE_BATCH_SIZE;\n const claim = options.claim ?? claimSiteAuthMaintenance;\n const confirm = options.confirm ?? confirmSiteAuthMaintenanceSessionInTransaction;\n const defer = options.defer ?? deferSiteAuthMaintenance;\n const createSession = options.createSession ?? createAndStartSessionWithOutcome;\n const admit = options.admit ?? agentRunAdmissionDenial;\n const recordUsage = options.recordUsage ?? recordWorkspaceUsage;\n const assertModelPolicy = options.assertModelPolicy ?? assertWorkspaceModelPolicyAllows;\n\n async function maintainSiteAuthConnections(): Promise<MaintainSiteAuthConnectionsResult> {\n const service = await services();\n const claims = await claim(service.db, { claimTimeoutMs, limit: batchSize });\n const result: MaintainSiteAuthConnectionsResult = {\n claimed: claims.length,\n started: 0,\n deferred: 0,\n };\n for (const maintenance of claims) {\n try {\n await dispatchMaintenanceSession(service, maintenance, {\n confirm,\n createSession,\n admit,\n recordUsage,\n assertModelPolicy,\n });\n result.started += 1;\n } catch (error) {\n const released = await defer(service.db, {\n accountId: maintenance.accountId,\n workspaceId: maintenance.workspaceId,\n siteAuthConnectionId: maintenance.siteAuthConnectionId,\n operationId: maintenance.operationId,\n sessionId: maintenance.sessionId,\n retryAt: maintenanceRetryAt(maintenance),\n }).catch(() => false);\n if (released) result.deferred += 1;\n service.observability.warn(\"site auth maintenance dispatch deferred\", {\n workspaceId: maintenance.workspaceId,\n siteAuthConnectionId: maintenance.siteAuthConnectionId,\n action: maintenance.action,\n errorCategory: maintenanceErrorCategory(error),\n claimReleased: released,\n });\n }\n }\n if (result.claimed > 0) {\n service.observability.info(\"site auth maintenance swept\", result);\n }\n return result;\n }\n\n return { maintainSiteAuthConnections };\n}\n\nasync function dispatchMaintenanceSession(\n service: ControlActivityServices,\n maintenance: SiteAuthMaintenanceClaim,\n dependencies: {\n confirm: typeof confirmSiteAuthMaintenanceSessionInTransaction;\n createSession: typeof createAndStartSessionWithOutcome;\n admit: typeof agentRunAdmissionDenial;\n recordUsage: typeof recordWorkspaceUsage;\n assertModelPolicy: typeof assertWorkspaceModelPolicyAllows;\n },\n): Promise<void> {\n const catalogSettings = (\n await resolveCatalogSettings(service.db, service.catalogSourceSettings ?? service.settings)\n ).settings;\n const catalogService = { ...service, settings: catalogSettings };\n const model = canonicalConfiguredModel(catalogSettings, catalogSettings.openaiModel);\n if (!model) throw new Error(\"site auth maintenance has no configured model\");\n await dependencies.assertModelPolicy(service.db, catalogSettings, maintenance.workspaceId, model);\n const denial = await dependencies.admit(catalogService, {\n accountId: maintenance.accountId,\n workspaceId: maintenance.workspaceId,\n model,\n requestedAgentRuns: 1,\n });\n if (denial) throw new Error(`site auth maintenance admission denied: ${denial}`);\n const reasoningEffort = catalogSettings.openaiReasoningEffort;\n const turnExecutionPolicy = resolveTurnExecutionPolicyV1(catalogSettings, {\n modelId: model,\n requestedModelId: null,\n modelSource: \"deployment\",\n reasoningEffort,\n reasoningSource: \"deployment\",\n latencyMode: \"standard\",\n latencyModeSource: \"deployment\",\n });\n const created = await dependencies.createSession({\n requestedSessionId: maintenance.sessionId,\n db: service.db,\n bus: service.bus,\n workflowClient: {\n wakeSessionWorkflow: async (input) => {\n await service.wakeSessionWorkflow?.(input);\n },\n },\n beforeCreateCommit: async (tx, sessionId) => {\n const confirmed = await dependencies.confirm(tx, {\n accountId: maintenance.accountId,\n workspaceId: maintenance.workspaceId,\n siteAuthConnectionId: maintenance.siteAuthConnectionId,\n operationId: maintenance.operationId,\n sessionId,\n });\n if (!confirmed) throw new Error(\"site auth maintenance claim changed before session start\");\n },\n accountId: maintenance.accountId,\n workspaceId: maintenance.workspaceId,\n initialMessage: maintenancePrompt(maintenance),\n // OpenGeni's own periodic check: no human or product surface entered it.\n surface: \"system\",\n metrics: service.observability,\n resources: [],\n tools: [{ kind: \"mcp\", id: \"opengeni\" }],\n toolPolicy: { mode: \"explicit\", inheritedFromSessionId: null },\n model,\n reasoningEffort,\n turnExecutionPolicy,\n sandboxBackend: catalogSettings.sandboxBackend,\n metadata: {\n role: \"site_auth_maintenance\",\n [SITE_AUTH_MAINTENANCE_CONNECTION_CONTEXT_KEY]: maintenance.siteAuthConnectionId,\n [SITE_AUTH_MAINTENANCE_OPERATION_CONTEXT_KEY]: maintenance.operationId,\n },\n createdBy: {\n kind: \"service\",\n subjectId: \"site-auth-maintenance\",\n label: \"OpenGeni authentication maintenance\",\n },\n createdByContext: {\n [SITE_AUTH_MAINTENANCE_CONNECTION_CONTEXT_KEY]: maintenance.siteAuthConnectionId,\n [SITE_AUTH_MAINTENANCE_OPERATION_CONTEXT_KEY]: maintenance.operationId,\n },\n instructions:\n \"Complete only the exact browser-auth maintenance run in the initial request. Use the canonical browser/auth tools, preserve their causal fences, expose no secrets, never publish a BrowserIdentity revision, and do not perform unrelated work.\",\n policyRole: \"site_auth_maintenance\",\n firstPartyMcpPermissions: [...DEFAULT_FIRST_PARTY_MCP_PERMISSIONS],\n firstPartyMcpTools: [...MAINTENANCE_TOOLS],\n createIdempotencyKey: `site-auth-maintenance:${maintenance.operationId}`,\n subjectId: \"site-auth-maintenance\",\n });\n try {\n await dependencies.recordUsage(\n { db: service.db, settings: catalogSettings },\n {\n accountId: maintenance.accountId,\n workspaceId: maintenance.workspaceId,\n subjectId: \"site-auth-maintenance\",\n eventType: \"agent_run.created\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"site_auth_connection\",\n sourceResourceId: maintenance.siteAuthConnectionId,\n sessionId: created.session.id,\n initiator: created.session.createdBy,\n initiatorContext: created.session.createdByContext,\n origin: \"system\",\n idempotencyKey: `agent_run.created:site-auth-maintenance:${maintenance.operationId}`,\n },\n );\n } catch (error) {\n service.observability.warn(\"site auth maintenance usage recording failed\", {\n workspaceId: maintenance.workspaceId,\n siteAuthConnectionId: maintenance.siteAuthConnectionId,\n errorCategory: maintenanceErrorCategory(error),\n });\n }\n}\n\nfunction maintenancePrompt(maintenance: SiteAuthMaintenanceClaim): string {\n const action = maintenance.action === \"repair\" ? \"repair authentication\" : \"check authentication\";\n return [\n `Perform one scheduled SiteAuthConnection maintenance run: ${action}.`,\n `Connection id: ${maintenance.siteAuthConnectionId}`,\n `Connection: ${maintenance.name} (${maintenance.accountLabel})`,\n `Purpose: ${maintenance.action}`,\n maintenance.loginUrl ? `Login URL: ${maintenance.loginUrl}` : null,\n maintenance.verificationUrlPrefixes.length > 0\n ? `Verification URL prefixes: ${maintenance.verificationUrlPrefixes.join(\", \")}`\n : \"No dedicated verification URL is configured; use the connection's allowed origins.\",\n maintenance.preferredIdentityId\n ? `Preferred BrowserIdentity: ${maintenance.preferredIdentityId}`\n : \"No preferred BrowserIdentity is configured.\",\n maintenance.preferredPlacement\n ? `Preferred placement: ${JSON.stringify(maintenance.preferredPlacement)}`\n : \"Use the normal managed-browser placement.\",\n maintenance.preferredNetworkRouteId\n ? `Preferred NetworkRoute: ${maintenance.preferredNetworkRouteId}`\n : \"No preferred NetworkRoute is configured.\",\n \"First call browser_auth get_connection and ensure this exact maintenance action is still active. Open a new browser (do not reuse an unrelated session) with the preferred identity, placement, and network route. Observe the current page, start one AuthRun with the exact purpose above, and settle it as verified, failed, cancelled, or a durable human intervention. For an external_provider authority use advance_external. If authentication is already valid, verify it without logging in again. If a health check finds invalid authentication, report it failed; automatic repair, when enabled, is a separate maintenance run. Never save/publish browser state in this run.\",\n ]\n .filter((line): line is string => line !== null)\n .join(\"\\n\");\n}\n\nfunction maintenanceRetryAt(maintenance: SiteAuthMaintenanceClaim): Date {\n const retrySeconds = Math.min(maintenance.healthPolicy.intervalSeconds ?? 300, 15 * 60);\n return new Date(Date.now() + retrySeconds * 1_000);\n}\n\nfunction maintenanceErrorCategory(error: unknown): string {\n if (!error || typeof error !== \"object\") return \"unknown\";\n const name = (error as { name?: unknown }).name;\n return typeof name === \"string\" && name.length <= 100 ? name : \"unknown\";\n}\n","import {\n settleSessionAttemptInterruptions,\n applySessionTurnSettlement,\n enqueueSessionWorkflowWake,\n failSessionWorkBeforeAttemptClaim,\n blockSessionWorkBeforeAttemptClaim,\n requestSessionTurnRecovery,\n recoverSessionDispatch,\n reconcileSessionAttemptQuiescence,\n peekSessionWork as peekSessionWorkDb,\n settleSessionInputWait as settleSessionInputWaitDb,\n countQueuedTurns,\n getSessionAttemptActivityRef,\n getSessionEvent,\n getSessionTurnForAttempt,\n expireSessionInteractionIntervention as expireSessionInteractionInterventionDb,\n expireScheduledRunHumanWait as expireScheduledRunHumanWaitDb,\n expireSessionHumanInputRequest,\n markSessionAttemptQuiesced,\n requireSession,\n settleSessionIdleWithParentOutbox,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport { CancelledFailure } from \"@temporalio/activity\";\nimport { currentActivityContext } from \"./streaming\";\nimport { deliverFailedChildTurnToParent, notifyParentOfChildIdle } from \"./parent-wake\";\nimport { recordTurnsQueuedGauge, recordWorkerDeathRecoveryMetrics } from \"../observability-metrics\";\nimport {\n MAX_AUTOMATIC_PROVIDER_RECOVERIES,\n providerRecoveryCountFromMetadata,\n} from \"./agent-turn/errors\";\nimport type {\n ControlActivityServices,\n ExpireSessionHumanInputInput,\n ExpireSessionHumanInputResult,\n ExpireSessionInteractionInterventionInput,\n ExpireScheduledRunHumanWaitInput,\n ExpireScheduledRunHumanWaitResult,\n ExpireSessionInteractionInterventionResult,\n PeekSessionWorkInput,\n FailSessionAttemptInput,\n FailSessionAttemptResult,\n SettleSessionInterruptionsInput,\n MarkSessionIdleInput,\n PersistSessionAttemptQuiescenceInput,\n ReconcileSessionAttemptQuiescenceInput,\n ReconcileSessionAttemptQuiescenceResult,\n RecoverDispatchInput,\n RecoverDispatchResult,\n RecoverEscapedMcpTimeoutInput,\n RecoverEscapedMcpTimeoutResult,\n SettleSessionInputWaitInput,\n SettleSessionInputWaitResult,\n} from \"./types\";\n\nexport type SessionStateActivityOverrides = Partial<{\n settleSessionAttemptInterruptions: typeof settleSessionAttemptInterruptions;\n applySessionTurnSettlement: typeof applySessionTurnSettlement;\n enqueueSessionWorkflowWake: typeof enqueueSessionWorkflowWake;\n failSessionWorkBeforeAttemptClaim: typeof failSessionWorkBeforeAttemptClaim;\n blockSessionWorkBeforeAttemptClaim: typeof blockSessionWorkBeforeAttemptClaim;\n requestSessionTurnRecovery: typeof requestSessionTurnRecovery;\n recoverSessionDispatch: typeof recoverSessionDispatch;\n reconcileSessionAttemptQuiescence: typeof reconcileSessionAttemptQuiescence;\n peekSessionWork: typeof peekSessionWorkDb;\n settleSessionInputWait: typeof settleSessionInputWaitDb;\n countQueuedTurns: typeof countQueuedTurns;\n getSessionAttemptActivityRef: typeof getSessionAttemptActivityRef;\n getSessionEvent: typeof getSessionEvent;\n getSessionTurnForAttempt: typeof getSessionTurnForAttempt;\n expireSessionHumanInputRequest: typeof expireSessionHumanInputRequest;\n expireSessionInteractionIntervention: typeof expireSessionInteractionInterventionDb;\n expireScheduledRunHumanWait: typeof expireScheduledRunHumanWaitDb;\n requireSession: typeof requireSession;\n settleSessionIdleWithParentOutbox: typeof settleSessionIdleWithParentOutbox;\n markSessionAttemptQuiesced: typeof markSessionAttemptQuiesced;\n publishDurableSessionEvents: typeof publishDurableSessionEvents;\n deliverFailedChildTurnToParent: typeof deliverFailedChildTurnToParent;\n notifyParentOfChildIdle: typeof notifyParentOfChildIdle;\n recordTurnsQueuedGauge: typeof recordTurnsQueuedGauge;\n recordWorkerDeathRecoveryMetrics: typeof recordWorkerDeathRecoveryMetrics;\n}>;\n\n// Crash-loop guard for worker-death re-dispatch: a turn that takes a worker\n// down this many times in a row is assumed to be the cause, not the victim,\n// and the session fails for real on the next death. A plain constant by\n// design — this is a pathology bound, not a run-length limit.\nexport const WORKER_DEATH_MAX_REDISPATCHES = 3;\n\nexport function createSessionStateActivities(\n services: () => Promise<ControlActivityServices>,\n overrides: SessionStateActivityOverrides = {},\n) {\n const settleSessionAttemptInterruptionsFn =\n overrides.settleSessionAttemptInterruptions ?? settleSessionAttemptInterruptions;\n const applySessionTurnSettlementFn =\n overrides.applySessionTurnSettlement ?? applySessionTurnSettlement;\n const enqueueSessionWorkflowWakeFn =\n overrides.enqueueSessionWorkflowWake ?? enqueueSessionWorkflowWake;\n const failSessionWorkBeforeAttemptClaimFn =\n overrides.failSessionWorkBeforeAttemptClaim ?? failSessionWorkBeforeAttemptClaim;\n const blockSessionWorkBeforeAttemptClaimFn =\n overrides.blockSessionWorkBeforeAttemptClaim ?? blockSessionWorkBeforeAttemptClaim;\n const requestSessionTurnRecoveryFn =\n overrides.requestSessionTurnRecovery ?? requestSessionTurnRecovery;\n const recoverSessionDispatchFn = overrides.recoverSessionDispatch ?? recoverSessionDispatch;\n const reconcileSessionAttemptQuiescenceFn =\n overrides.reconcileSessionAttemptQuiescence ?? reconcileSessionAttemptQuiescence;\n const peekSessionWorkFn = overrides.peekSessionWork ?? peekSessionWorkDb;\n const settleSessionInputWaitFn = overrides.settleSessionInputWait ?? settleSessionInputWaitDb;\n const countQueuedTurnsFn = overrides.countQueuedTurns ?? countQueuedTurns;\n const getSessionAttemptActivityRefFn =\n overrides.getSessionAttemptActivityRef ?? getSessionAttemptActivityRef;\n const getSessionEventFn = overrides.getSessionEvent ?? getSessionEvent;\n const getSessionTurnForAttemptFn = overrides.getSessionTurnForAttempt ?? getSessionTurnForAttempt;\n const expireSessionHumanInputRequestFn =\n overrides.expireSessionHumanInputRequest ?? expireSessionHumanInputRequest;\n const expireSessionInteractionInterventionFn =\n overrides.expireSessionInteractionIntervention ?? expireSessionInteractionInterventionDb;\n const expireScheduledRunHumanWaitFn =\n overrides.expireScheduledRunHumanWait ?? expireScheduledRunHumanWaitDb;\n const requireSessionFn = overrides.requireSession ?? requireSession;\n const settleSessionIdleWithParentOutboxFn =\n overrides.settleSessionIdleWithParentOutbox ?? settleSessionIdleWithParentOutbox;\n const markSessionAttemptQuiescedFn =\n overrides.markSessionAttemptQuiesced ?? markSessionAttemptQuiesced;\n const publishDurableSessionEventsFn =\n overrides.publishDurableSessionEvents ?? publishDurableSessionEvents;\n const deliverFailedChildTurnToParentFn =\n overrides.deliverFailedChildTurnToParent ?? deliverFailedChildTurnToParent;\n const notifyParentOfChildIdleFn = overrides.notifyParentOfChildIdle ?? notifyParentOfChildIdle;\n const recordTurnsQueuedGaugeFn = overrides.recordTurnsQueuedGauge ?? recordTurnsQueuedGauge;\n const recordWorkerDeathRecoveryMetricsFn =\n overrides.recordWorkerDeathRecoveryMetrics ?? recordWorkerDeathRecoveryMetrics;\n\n async function failSessionAttempt(\n input: FailSessionAttemptInput,\n ): Promise<FailSessionAttemptResult> {\n const { db, bus, settings, observability, wakeSessionWorkflow } = await services();\n const session = await requireSessionFn(db, input.workspaceId, input.sessionId);\n if (session.status === \"failed\" || session.status === \"cancelled\") {\n // The activity may be retried after failure settlement committed but its\n // response or event fanout was lost. Preserve terminal session truth so\n // the workflow cannot interpret an idle peek as permission to synthesize\n // an active-goal continuation.\n return { action: \"terminal\" };\n }\n const workflowId =\n input.workflowId ?? session.temporalWorkflowId ?? `session-${input.sessionId}`;\n const turn = await getSessionTurnForAttemptFn(\n db,\n input.workspaceId,\n input.sessionId,\n input.attemptId,\n );\n if (!turn) {\n const attempt = await getSessionAttemptActivityRefFn(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n temporalWorkflowId: workflowId,\n });\n if (attempt) return { action: \"stale\" };\n\n const preClaimFailureDisposition =\n input.preClaimFailure?.disposition ?? input.preClaimFailureDisposition;\n if (\n preClaimFailureDisposition === \"blocked\" &&\n input.admissionFence &&\n input.preClaimFailure?.reason\n ) {\n const blocked = await blockSessionWorkBeforeAttemptClaimFn(db, input.workspaceId, {\n accountId: input.accountId,\n sessionId: input.sessionId,\n workflowId,\n attemptId: input.attemptId,\n fence: input.admissionFence,\n reason: input.preClaimFailure.reason,\n sqlState: input.preClaimFailure.sqlState ?? null,\n });\n await publishDurableSessionEventsFn(\n bus,\n input.workspaceId,\n input.sessionId,\n blocked.events,\n );\n return { action: blocked.action };\n }\n if (preClaimFailureDisposition === \"permanent\" && input.trigger) {\n const failed = await failSessionWorkBeforeAttemptClaimFn(db, input.workspaceId, {\n accountId: input.accountId,\n sessionId: input.sessionId,\n workflowId,\n trigger: input.trigger,\n error: input.error ?? \"Agent turn admission failed before attempt claim.\",\n ...(input.preClaimFailure?.disposition === \"permanent\"\n ? {\n admissionFailure: {\n disposition: \"permanent\" as const,\n code: input.preClaimFailure.code,\n },\n }\n : {}),\n });\n if (failed.action === \"terminal\") return { action: \"terminal\" };\n if (failed.action === \"stale\") return { action: \"stale\" };\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, failed.events);\n if (failed.turnId) {\n await deliverFailedChildTurnToParentFn(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n failed.turnId,\n );\n }\n return { action: \"failed\" };\n }\n\n const requestedRetryDelayMs = input.retryDelayMs;\n const retryDelayMs =\n typeof requestedRetryDelayMs === \"number\" && Number.isFinite(requestedRetryDelayMs)\n ? Math.max(1_000, Math.min(60_000, Math.trunc(requestedRetryDelayMs)))\n : 60_000;\n await enqueueSessionWorkflowWakeFn(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n temporalWorkflowId: workflowId,\n reason: \"turn_activity_failed_before_attempt_claim\",\n notBefore: new Date(Date.now() + retryDelayMs),\n });\n return { action: \"unclaimed\" };\n }\n const postClaimRecovery = input.postClaimDatabaseRecovery;\n const postClaimIdentityMatches = Boolean(\n postClaimRecovery &&\n turn.id === postClaimRecovery.turnId &&\n turn.triggerEventId === postClaimRecovery.triggerEventId &&\n turn.executionGeneration === postClaimRecovery.executionGeneration,\n );\n const providerRecoveryCount = postClaimIdentityMatches\n ? postClaimRecovery?.providerRecoveryCount\n : undefined;\n const providerFailureCode = postClaimIdentityMatches\n ? postClaimRecovery?.providerFailureCode\n : undefined;\n const hasProviderRecoveryCount = providerRecoveryCount !== undefined;\n const hasProviderFailureCode = providerFailureCode !== undefined;\n const setupOutcomeUnknown =\n postClaimIdentityMatches && postClaimRecovery?.sandboxSetupOutcomeUnknown === true;\n if (setupOutcomeUnknown && (hasProviderRecoveryCount || hasProviderFailureCode)) {\n return { action: \"stale\" };\n }\n if (hasProviderRecoveryCount !== hasProviderFailureCode) {\n return { action: \"stale\" };\n }\n if (\n providerRecoveryCount !== undefined &&\n (!Number.isSafeInteger(providerRecoveryCount) ||\n providerRecoveryCount <= 0 ||\n providerRecoveryCount !== providerRecoveryCountFromMetadata(turn.metadata ?? {}) + 1 ||\n providerRecoveryCount > MAX_AUTOMATIC_PROVIDER_RECOVERIES ||\n typeof providerFailureCode !== \"string\" ||\n !/^[a-z][a-z0-9_]{0,63}$/.test(providerFailureCode))\n ) {\n return { action: \"stale\" };\n }\n const recoveredClaimCode = postClaimIdentityMatches\n ? postClaimRecovery!.code\n : input.preClaimFailure?.disposition === \"retryable\" &&\n input.preClaimFailure.code !== \"claim_invariant\"\n ? input.preClaimFailure.code\n : input.preClaimFailureDisposition === \"retryable\"\n ? \"legacy_retryable_preclaim_database_failure\"\n : null;\n if (recoveredClaimCode) {\n const recovery = await requestSessionTurnRecoveryFn(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: turn.id,\n triggerEventId: turn.triggerEventId,\n attemptId: input.attemptId,\n reason: setupOutcomeUnknown\n ? \"sandbox_command_start_outcome_unknown\"\n : (providerFailureCode ?? \"claimed_attempt_database_failure\"),\n ...(setupOutcomeUnknown ? { sandboxSetupOutcomeUnknown: true } : {}),\n ...(providerRecoveryCount !== undefined ? { providerRecoveryCount } : {}),\n detail: {\n code: setupOutcomeUnknown\n ? \"sandbox_command_start_outcome_unknown\"\n : (providerFailureCode ?? recoveredClaimCode),\n retryable: !setupOutcomeUnknown,\n ...(setupOutcomeUnknown ? { setupOutcome: \"unknown\", replay: \"blocked\" } : {}),\n ...(providerRecoveryCount !== undefined\n ? {\n databaseFailureCode: recoveredClaimCode,\n providerRecoveryCount,\n }\n : {}),\n recoverySource: \"workflow_activity_failure\",\n },\n fromStatuses: [\"running\"],\n });\n if (recovery.action !== \"recovering\") return { action: \"stale\" };\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, recovery.events);\n await refreshQueuedTurnsGauge(\n db,\n observability,\n countQueuedTurnsFn,\n recordTurnsQueuedGaugeFn,\n );\n return { action: \"recovering\" };\n }\n const trigger = await getSessionEventFn(db, input.workspaceId, turn.triggerEventId);\n const result = await applySessionTurnSettlementFn(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: turn.id,\n triggerEventId: turn.triggerEventId,\n attemptId: input.attemptId,\n turnStatus: \"failed\",\n sessionStatus: \"failed\",\n activeTurnId: null,\n events: [\n {\n type: \"turn.failed\",\n payload: {\n triggerEventId: turn.triggerEventId,\n trigger: trigger?.payload ?? null,\n error: input.error ?? \"Agent activity failed before it could report a terminal state.\",\n },\n },\n { type: \"session.status.changed\", payload: { status: \"failed\" } },\n ],\n });\n if (result.action === \"stale\") {\n return { action: \"stale\" };\n }\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, result.events);\n await deliverFailedChildTurnToParentFn(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n turn.id,\n );\n return { action: \"failed\" };\n }\n\n async function settleSessionInterruptions(\n input: SettleSessionInterruptionsInput,\n ): Promise<{ action: \"paused\" | \"continue\" | \"stale\" }> {\n const { db, bus, observability } = await services();\n if (input.phase === \"attempt_quiesced\") {\n // Replay compatibility only: v1 histories scheduled this idempotent\n // fallback after WAIT_CANCELLATION_COMPLETED. Receipt-gated v2 workflows\n // never call it; runAgentTurn writes immediately after its hard fence.\n const events = await markSessionAttemptQuiescedFn(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n temporalWorkflowId: input.workflowId,\n });\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, events);\n return { action: \"stale\" };\n }\n const applied = await settleSessionAttemptInterruptionsFn(\n db,\n input.workspaceId,\n input.sessionId,\n input.attemptId,\n );\n if (applied.events.length > 0) {\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, applied.events);\n }\n await refreshQueuedTurnsGauge(db, observability, countQueuedTurnsFn, recordTurnsQueuedGaugeFn);\n return { action: applied.action };\n }\n\n /** Persist an exact activity-owned physical-quiescence proof through the\n * workflow control-activity retry policy. The DB transaction remains the\n * sole receipt/wake authority; duplicate signals and activity retries reuse\n * its attempt-scoped idempotency key. */\n async function persistSessionAttemptQuiescence(\n input: PersistSessionAttemptQuiescenceInput,\n ): Promise<void> {\n const { db, bus, observability } = await services();\n const events = await markSessionAttemptQuiescedFn(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n temporalWorkflowId: input.workflowId,\n temporalWorkflowRunId: input.workflowRunId,\n temporalActivityId: input.activityId,\n allowUninterrupted: true,\n });\n try {\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, events);\n } catch (error) {\n // The receipt and exact workflow wake already committed atomically in\n // Postgres. NATS is best-effort live fanout and must not keep this\n // control activity retrying or delay receipt-gated admission.\n observability.error(\"session-attempt quiescence event fanout failed\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.attempt_id\": input.attemptId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n async function reconcileSessionAttemptQuiescenceActivity(\n input: ReconcileSessionAttemptQuiescenceInput,\n ): Promise<ReconcileSessionAttemptQuiescenceResult> {\n const { db, bus, inspectSessionAttemptActivity } = await services();\n const activityRef = await getSessionAttemptActivityRefFn(db, {\n ...input,\n temporalWorkflowId: input.workflowId,\n });\n if (!activityRef) return { action: \"stale\" };\n if (!activityRef.quiesced) {\n if (!inspectSessionAttemptActivity) return { action: \"pending\" };\n const state = await inspectSessionAttemptActivity(activityRef);\n if (state === \"pending\") return { action: \"pending\" };\n }\n const result = await reconcileSessionAttemptQuiescenceFn(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n temporalWorkflowId: input.workflowId,\n temporalWorkflowRunId: activityRef.workflowRunId,\n temporalActivityId: activityRef.activityId,\n activitySettled: true,\n });\n if (result.events.length > 0) {\n await publishDurableSessionEventsFn(\n bus,\n input.workspaceId,\n input.sessionId,\n result.events,\n ).catch(() => undefined);\n }\n return { action: result.action };\n }\n\n /**\n * Recover the same current inference when its worker dies without completing\n * a graceful checkpoint (heartbeat timeout, SIGKILL, OOM, or node loss).\n * Durable conversation truth and the original trigger stay attached to the\n * same turn; recovery creates a new fenced attempt, never a prompt-queue row\n * or a synthetic resume message. Repeated worker deaths are bounded per turn.\n */\n async function recoverDispatch(input: RecoverDispatchInput): Promise<RecoverDispatchResult> {\n const { settings, db, bus, observability, wakeSessionWorkflow } = await services();\n const result = await recoverSessionDispatchFn(db, input.workspaceId, {\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n timeoutType: input.timeoutType,\n maxRedispatches: WORKER_DEATH_MAX_REDISPATCHES,\n });\n if (result.action === \"stale\" || result.action === \"unclaimed\") {\n return { action: result.action };\n }\n recordWorkerDeathRecoveryMetricsFn(observability, {\n outcome: result.action === \"exceeded\" ? \"exhausted\" : \"recovering\",\n timeoutType: input.timeoutType,\n });\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, result.events);\n await refreshQueuedTurnsGauge(db, observability, countQueuedTurnsFn, recordTurnsQueuedGaugeFn);\n if (result.action === \"exceeded\") {\n await deliverFailedChildTurnToParentFn(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n result.turnId,\n );\n return {\n action: \"exceeded\",\n turnId: result.turnId,\n redispatches: result.redispatches,\n };\n }\n return {\n action: \"recovering\",\n turnId: result.turnId,\n redispatches: result.redispatches,\n };\n }\n\n /**\n * Finish a retryable MCP timeout checkpoint that escaped a recovered turn's\n * activity before any model request. Temporal carries the immutable turn\n * identity in ApplicationFailure details; this activity re-reads and fences\n * every field before mutating the exact still-owned attempt. A checkpoint\n * that committed before event fanout failed is already recovering and\n * therefore returns stale without another event or child callback.\n */\n async function recoverEscapedMcpTimeout(\n input: RecoverEscapedMcpTimeoutInput,\n ): Promise<RecoverEscapedMcpTimeoutResult> {\n const { db, bus, observability } = await services();\n const turn = await getSessionTurnForAttemptFn(\n db,\n input.workspaceId,\n input.sessionId,\n input.attemptId,\n );\n if (!turn) return { action: \"stale\" };\n if (\n turn.id !== input.turnId ||\n turn.triggerEventId !== input.triggerEventId ||\n turn.executionGeneration !== input.executionGeneration ||\n input.executionGeneration <= 1 ||\n input.providerRecoveryCount !== providerRecoveryCountFromMetadata(turn.metadata) + 1 ||\n input.providerRecoveryCount > MAX_AUTOMATIC_PROVIDER_RECOVERIES\n ) {\n return { action: \"ineligible\" };\n }\n const recovery = await requestSessionTurnRecoveryFn(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: input.turnId,\n triggerEventId: input.triggerEventId,\n attemptId: input.attemptId,\n reason: \"mcp_transport_timeout\",\n providerRecoveryCount: input.providerRecoveryCount,\n detail: {\n code: \"mcp_transport_timeout\",\n retryable: true,\n continueDelayMs: input.continueDelayMs,\n providerRecoveryCount: input.providerRecoveryCount,\n recoverySource: \"workflow_activity_failure\",\n },\n fromStatuses: [\"running\"],\n });\n if (recovery.action !== \"recovering\") {\n return { action: \"stale\" };\n }\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, recovery.events);\n await refreshQueuedTurnsGauge(db, observability, countQueuedTurnsFn, recordTurnsQueuedGaugeFn);\n return { action: \"recovering\" };\n }\n\n async function peekSessionWork(input: PeekSessionWorkInput) {\n const { db, observability, inspectSessionAttemptActivity } = await services();\n const peek = await peekSessionWorkFn(\n db,\n input.workspaceId,\n input.sessionId,\n input.includeAdmissionFence,\n input.observerAccountId,\n );\n if (peek.kind === \"unavailable\") return peek;\n if (peek.kind === \"attempt-owned\") {\n // Observation never revokes a writer or recovers a live owner. In\n // particular, a settled Temporal activity is not physical-writer proof.\n let ownerActivityState: \"pending\" | \"settled\" | \"unknown\" = \"unknown\";\n if (inspectSessionAttemptActivity) {\n try {\n ownerActivityState = await inspectSessionAttemptActivity(peek.activityRef);\n } catch (error) {\n if (error instanceof CancelledFailure) throw error;\n if (currentActivityContext()?.cancellationSignal.aborted)\n throw new CancelledFailure(\"Control observation cancelled\");\n // This optional metadata observation grants no recovery authority.\n // An unavailable inspector must not pin the control activity in\n // retries and prevent a fresh Pause/owner/visibility observation.\n // Database reads below remain outside this catch and retry normally.\n }\n }\n if (currentActivityContext()?.cancellationSignal.aborted)\n throw new CancelledFailure(\"Control observation cancelled\");\n const current = await peekSessionWorkFn(\n db,\n input.workspaceId,\n input.sessionId,\n input.includeAdmissionFence,\n input.observerAccountId,\n );\n if (\n current.kind !== \"attempt-owned\" ||\n current.turnId !== peek.turnId ||\n current.attemptId !== peek.attemptId ||\n current.executionGeneration !== peek.executionGeneration ||\n current.activityRef.workflowId !== peek.activityRef.workflowId ||\n current.activityRef.workflowRunId !== peek.activityRef.workflowRunId ||\n current.activityRef.activityId !== peek.activityRef.activityId\n )\n return current;\n return { ...current, ownerActivityState };\n }\n await refreshQueuedTurnsGauge(db, observability, countQueuedTurnsFn, recordTurnsQueuedGaugeFn);\n return peek;\n }\n\n async function settleSessionInputWait(\n input: SettleSessionInputWaitInput,\n ): Promise<SettleSessionInputWaitResult> {\n const { db, bus } = await services();\n const result = await settleSessionInputWaitFn(db, input);\n if (result.events.length > 0) {\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, result.events);\n }\n return { action: result.action };\n }\n\n async function expireSessionHumanInput(\n input: ExpireSessionHumanInputInput,\n ): Promise<ExpireSessionHumanInputResult> {\n const { db, bus } = await services();\n const result = await expireSessionHumanInputRequestFn(db, input);\n if (result.action === \"not_found\") return { action: \"not_found\" };\n if (result.events.length > 0) {\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, result.events);\n }\n return {\n action: result.request.status === \"expired\" ? \"expired\" : \"stale\",\n };\n }\n\n async function expireSessionInteractionIntervention(\n input: ExpireSessionInteractionInterventionInput,\n ): Promise<ExpireSessionInteractionInterventionResult> {\n const { db, bus } = await services();\n const result = await expireSessionInteractionInterventionFn(db, input);\n if (result.events.length > 0) {\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, result.events);\n }\n return { action: result.action };\n }\n\n /** A scheduled run's approval timeout answers for its unanswered human wait. */\n async function expireScheduledRunHumanWait(\n input: ExpireScheduledRunHumanWaitInput,\n ): Promise<ExpireScheduledRunHumanWaitResult> {\n const { db, bus } = await services();\n const result = await expireScheduledRunHumanWaitFn(db, input);\n if (result.events.length > 0) {\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, result.events);\n }\n return { action: result.action };\n }\n\n async function markSessionIdle(input: MarkSessionIdleInput): Promise<void> {\n const { db, bus, settings, observability, wakeSessionWorkflow } = await services();\n const settled = await settleSessionIdleWithParentOutboxFn(\n db,\n input.workspaceId,\n input.sessionId,\n );\n if (settled.events.length > 0) {\n await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, settled.events);\n }\n await refreshQueuedTurnsGauge(db, observability, countQueuedTurnsFn, recordTurnsQueuedGaugeFn);\n if (settled.action === \"stale\" || !settled.notifyParent) {\n return;\n }\n // The idle transaction distinguishes parked wait/goal obligations from\n // completed work. Only a terminal idle boundary may notify the parent;\n // workflow closure while waiting retains its durable wake without a result.\n await notifyParentOfChildIdleFn(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n settled.episodeKey,\n );\n }\n\n return {\n failSessionAttempt,\n settleSessionInterruptions,\n persistSessionAttemptQuiescence,\n reconcileSessionAttemptQuiescence: reconcileSessionAttemptQuiescenceActivity,\n recoverDispatch,\n recoverEscapedMcpTimeout,\n peekSessionWork,\n settleSessionInputWait,\n expireSessionHumanInput,\n expireSessionInteractionIntervention,\n expireScheduledRunHumanWait,\n markSessionIdle,\n };\n}\n\nasync function refreshQueuedTurnsGauge(\n db: ControlActivityServices[\"db\"],\n observability: ControlActivityServices[\"observability\"],\n countQueuedTurnsFn: typeof countQueuedTurns,\n recordTurnsQueuedGaugeFn: typeof recordTurnsQueuedGauge,\n): Promise<void> {\n try {\n recordTurnsQueuedGaugeFn(observability, await countQueuedTurnsFn(db));\n } catch {\n // Best-effort telemetry; session state transitions remain authoritative.\n }\n}\n","import {\n fireWorkspacePauseTimerInTransaction,\n listDueWorkspacePauseTimers,\n withWorkspaceRls,\n getWorkspaceControlEvent,\n type Database,\n} from \"@opengeni/db\";\nimport { publishDurableWorkspaceControlEvent } from \"@opengeni/events\";\nimport { recordWorkflowWakeReconciliation } from \"@opengeni/observability\";\nimport type { ControlActivityServices } from \"./types\";\nimport {\n reconcileAutomaticSessionTitleFanout,\n reconcilePendingSessionWorkflowWakes,\n type WorkflowWakeReconciliationResult,\n} from \"./parent-wake\";\n\nconst BATCH_SIZE = 1_000;\nconst MAX_DELIVERIES_PER_ACTIVITY = 10_000;\nconst MAX_TITLE_FANOUT_PER_ACTIVITY = 1_000;\n\nexport type DispatchSessionWorkflowWakesResult = WorkflowWakeReconciliationResult & {\n exhaustedBatchLimit: boolean;\n};\n\n/**\n * Drain committed session-workflow wake revisions through the same signal and\n * acknowledgement path used by immediate delivery. This is a repair path, not\n * an eligibility scan: producers have already decided what must be delivered.\n */\nexport function createWorkflowWakeActivities(services: () => Promise<ControlActivityServices>) {\n return {\n async dispatchSessionWorkflowWakes(): Promise<DispatchSessionWorkflowWakesResult> {\n const service = await services();\n // Timer commits produce ordinary durable wakes; drain those below in the same sweep.\n const timers = await listDueWorkspacePauseTimers(service.db, 100);\n for (const timer of timers) {\n try {\n const result = await withWorkspaceRls(service.db, timer.workspace_id, (scoped) =>\n scoped.transaction((tx) =>\n fireWorkspacePauseTimerInTransaction(tx as unknown as Database, {\n workspaceId: timer.workspace_id,\n timerId: timer.timer_id,\n }),\n ),\n );\n if (result?.workspaceControlEventId) {\n const event = await getWorkspaceControlEvent(\n service.db,\n timer.workspace_id,\n result.workspaceControlEventId,\n );\n if (event)\n await publishDurableWorkspaceControlEvent(service.bus, timer.workspace_id, event);\n }\n } catch (error) {\n service.observability.warn(\"Workspace pause timer will retry\", {\n workspaceId: timer.workspace_id,\n error: String(error),\n });\n }\n }\n let claimed = 0;\n let signaled = 0;\n let pendingAdmission = 0;\n let unconfirmed = 0;\n const pendingAdmissionBlockers: WorkflowWakeReconciliationResult[\"pendingAdmissionBlockers\"] =\n {};\n let delivered = 0;\n let failed = 0;\n let exhaustedBatchLimit = false;\n for (;;) {\n const remaining = MAX_DELIVERIES_PER_ACTIVITY - claimed;\n if (remaining <= 0) {\n exhaustedBatchLimit = true;\n break;\n }\n const limit = Math.min(BATCH_SIZE, remaining);\n const batch = await reconcilePendingSessionWorkflowWakes(service, limit);\n claimed += batch.claimed;\n signaled += batch.signaled;\n delivered += batch.delivered;\n pendingAdmission += batch.pendingAdmission;\n unconfirmed += batch.unconfirmed;\n for (const [blocker, count] of Object.entries(batch.pendingAdmissionBlockers)) {\n const key = blocker as keyof typeof pendingAdmissionBlockers;\n pendingAdmissionBlockers[key] = (pendingAdmissionBlockers[key] ?? 0) + count;\n }\n failed += batch.failed;\n if (batch.claimed < limit) break;\n }\n\n // Migration fanout is lower priority than ordinary workflow wakes and is\n // independently capped. Delivery acknowledgements run with bounded\n // concurrency in the reconciler, so a broker timeout cannot occupy the\n // five-minute activity budget once per quarantined session. Managed NATS\n // uses its bounded confirmed publish; embedding buses use their required\n // publish promise.\n const titleFanout = await reconcileAutomaticSessionTitleFanout(\n service,\n MAX_TITLE_FANOUT_PER_ACTIVITY,\n );\n if (titleFanout.claimed > 0) {\n service.observability.info(\"automatic-title migration event fanout reconciled\", {\n claimed: titleFanout.claimed,\n delivered: titleFanout.delivered,\n failed: titleFanout.failed,\n });\n }\n const result = {\n claimed,\n signaled,\n delivered,\n pendingAdmission,\n unconfirmed,\n failed,\n pendingAdmissionBlockers,\n exhaustedBatchLimit,\n };\n recordWorkflowWakeReconciliation(service.observability, result);\n return result;\n },\n };\n}\n","import { createKnowledgeIndexingActivities } from \"./activities/knowledge-indexing\";\nimport { createSharedActivityServices } from \"./activity-services\";\nimport { createCodexCapacityActivities } from \"./activities/codex-capacity\";\nimport { createBrowserStateArtifactMaintenanceActivities } from \"./activities/browser-state-artifact-reaper\";\nimport { createBrowserDeadlineCheckpointActivities } from \"./activities/browser-deadline-checkpoint\";\nimport { createAutomationActivities } from \"./activities/automations\";\nimport { createDocumentActivities } from \"./activities/documents\";\nimport { createFileUploadReaperActivities } from \"./activities/file-upload-reaper\";\nimport { createGoalActivities } from \"./activities/goals\";\nimport { createKnowledgeSourceSyncActivities } from \"./activities/knowledge-source-sync\";\nimport { createRetainedScreenshotMaintenanceActivities } from \"./activities/retained-screenshot-reaper\";\nimport { createRigVerificationActivities } from \"./activities/rig-verification\";\nimport { createSandboxLeaseActivities } from \"./activities/sandbox-lease\";\nimport { createScheduledTaskActivities } from \"./activities/scheduled-tasks\";\nimport { createSiteAuthMaintenanceActivities } from \"./activities/site-auth-maintenance\";\nimport { createSessionStateActivities } from \"./activities/session-state\";\nimport type { ActivityDependencies, ControlActivityServices } from \"./activities/types\";\nimport { createWorkflowWakeActivities } from \"./activities/workflow-wake\";\n\nfunction createControlActivityServices(\n dependencies: ActivityDependencies,\n): () => Promise<ControlActivityServices> {\n const shared = createSharedActivityServices(dependencies);\n return shared;\n}\n\nexport function createControlActivitiesFromServices(\n services: () => Promise<ControlActivityServices>,\n resolveDocumentServices?: () => Promise<import(\"@opengeni/documents\").DocumentServices>,\n) {\n return {\n ...createAutomationActivities(services),\n ...createDocumentActivities(services, resolveDocumentServices),\n ...createKnowledgeIndexingActivities(services, resolveDocumentServices),\n ...createKnowledgeSourceSyncActivities(services, resolveDocumentServices),\n ...createSessionStateActivities(services),\n ...createScheduledTaskActivities(services),\n ...createSiteAuthMaintenanceActivities(services),\n ...createGoalActivities(services),\n ...createCodexCapacityActivities(services),\n ...createRigVerificationActivities(services),\n ...createBrowserStateArtifactMaintenanceActivities(services),\n ...createBrowserDeadlineCheckpointActivities(services),\n ...createFileUploadReaperActivities(services),\n ...createRetainedScreenshotMaintenanceActivities(services),\n ...createWorkflowWakeActivities(services),\n ...createSandboxLeaseActivities(services),\n };\n}\n\nexport function createControlActivities(dependencies: ActivityDependencies = {}) {\n const services = createControlActivityServices(dependencies);\n let documentServicesPromise: Promise<import(\"@opengeni/documents\").DocumentServices> | null =\n null;\n const resolveDocumentServices = async () => {\n documentServicesPromise ??= dependencies.documentServices\n ? Promise.resolve(dependencies.documentServices)\n : import(\"@opengeni/documents\").then(async ({ createDocumentServices }) =>\n createDocumentServices((await services()).settings),\n );\n return await documentServicesPromise;\n };\n return createControlActivitiesFromServices(services, resolveDocumentServices);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,mCAAmC;AAC5C,SAAS,6BAA6B,6BAA6B;AACnE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKA,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACvD,cAAc;AACZ,UAAM,yCAAyC;AAC/C,SAAK,OAAO;AAAA,EACd;AACF;AAWO,SAAS,gCACd,OACA,OAWA;AACA,MAAI,iBAAiB,+BAA+B;AAClD,WAAO;AAAA,MACL,YAAY;AAAA,MACZ,WAAW;AAAA,MACX,QAAQ;AAAA,IACV;A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AS,oCACd,UACA,yBACA;AACA,SAAO;AAAA,IACL,GAAG,2BAA2B,QAAQ;AAAA,IACtC,GAAG,yBAAyB,UAAU,uBAAuB;AAAA,IAC7D,GAAG,kCAAkC,UAAU,uBAAuB;AAAA,IACtE,GAAG,oCAAoC,UAAU,uBAAuB;AAAA,IACxE,GAAG,6BAA6B,QAAQ;AAAA,IACxC,GAAG,8BAA8B,QAAQ;AAAA,IACzC,GAAG,oCAAoC,QAAQ;AAAA,IAC/C,GAAG,qBAAqB,QAAQ;AAAA,IAChC,GAAG,8BAA8B,QAAQ;AAAA,IACzC,GAAG,gCAAgC,QAAQ;AAAA,IAC3C,GAAG,gDAAgD,QAAQ;AAAA,IAC3D,GAAG,0CAA0C,QAAQ;AAAA,IACrD,GAAG,iCAAiC,QAAQ;AAAA,IAC5C,GAAG,8CAA8C,QAAQ;AAAA,IACzD,GAAG,6BAA6B,QAAQ;AAAA,IACxC,GAAG,6BAA6B,QAAQ;AAAA,EAC1C;AACF;AAEO,SAAS,wBAAwB,eAAqC,CAAC,GAAG;AAC/E,QAAM,WAAW,8BAA8B,YAAY;AAC3D,MAAI,0BACF;AACF,QAAM,0BAA0B,YAAY;AAC1C,gCAA4B,aAAa,mBACrC,QAAQ,QAAQ,aAAa,gBAAgB,IAC7C,OAAO,qBAAqB,EAAE;AAAA,MAAK,OAAO,EAAE,uBAAuB,MACjE,wBAAwB,MAAM,SAAS,GAAG,QAAQ;AAAA,IACpD;AACJ,WAAO,MAAM;AAAA,EACf;AACA,SAAO,oCAAoC,UAAU,uBAAuB;AAC9E;","names":["createSession","outcome","settled","releaseLeaseHolder","heartbeat","releaseLeaseHolder","resumeState","updated","randomUUID","Context","markSandboxCheckpointArtifactDeletePending","registerSandboxCheckpointArtifact","readLease","createSandboxClientForBackend","deleteModalCheckpointSnapshot","deserializeSandboxSessionStateEnvelope","establishSandboxSessionFromEnvelope","resumeExactSandboxSession","sandboxCommandExitCode","terminateManagedSandboxSession","verifySandboxExecReadiness","sandboxLeaseTelemetryKey","Context","heartbeat","createSandboxClientForBackend","drainableInventory","drainable","readLease","randomUUID","deleteModalCheckpointSnapshot","deserializeSandboxSessionStateEnvelope","resumeExactSandboxSession","establishSandboxSessionFromEnvelope","verifySandboxExecReadiness","sandboxCommandExitCode","registerSandboxCheckpointArtifact","markSandboxCheckpointArtifactDeletePending","terminateManagedSandboxSession","resolveWorkspaceCatalogSettings","agentConfigMayResolve","applySessionAgentConfigWriteThrough","resolveSessionAgentConfigForCreate","getRig","recordUsageEvent","requireWorkspace","resolveTurnExecutionPolicyV1","Context","createHash","createHash","Context","createHash","task","resolveWorkspaceCatalogSettings","settings","resolveSessionAgentConfigForCreate","agentConfigMayResolve","requireWorkspace","applySessionAgentConfigWriteThrough","getRig","resolveTurnExecutionPolicyV1","recordUsageEvent","result","resolveTurnExecutionPolicyV1","DEFAULT_FIRST_PARTY_MCP_PERMISSIONS","assertWorkspaceModelPolicyAllows","canonicalConfiguredModel","createAndStartSessionWithOutcome","recordWorkspaceUsage","resolveCatalogSettings","createSession","createAndStartSessionWithOutcome","recordWorkspaceUsage","assertWorkspaceModelPolicyAllows","resolveCatalogSettings","canonicalConfiguredModel","resolveTurnExecutionPolicyV1","DEFAULT_FIRST_PARTY_MCP_PERMISSIONS","countQueuedTurns","requireSession","publishDurableSessionEvents","countQueuedTurns","requireSession","publishDurableSessionEvents","result"]}