@opengeni/worker-bundle 0.16.21 → 0.17.2

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 (180) hide show
  1. package/dist/activities/agent-turn.d.ts +145 -32
  2. package/dist/activities/api-integrations.d.ts +21 -0
  3. package/dist/activities/codemode-dispatcher.d.ts +35 -0
  4. package/dist/activities/codemode-token-renewal.d.ts +23 -0
  5. package/dist/activities/codex-capacity.d.ts +5 -5
  6. package/dist/activities/codex-image-generation.d.ts +21 -0
  7. package/dist/activities/context-compaction.d.ts +3 -0
  8. package/dist/activities/documents.d.ts +3 -2
  9. package/dist/activities/environment.d.ts +11 -7
  10. package/dist/activities/expiring-material-renewal.d.ts +5 -3
  11. package/dist/activities/file-upload-reaper.d.ts +7 -2
  12. package/dist/activities/gateway-image-generation.d.ts +39 -0
  13. package/dist/activities/gateway-video-generation.d.ts +53 -0
  14. package/dist/activities/generated-images.d.ts +112 -0
  15. package/dist/activities/git-credential-renewal.d.ts +2 -2
  16. package/dist/activities/goals.d.ts +2 -2
  17. package/dist/activities/google-drive-changes.d.ts +99 -0
  18. package/dist/activities/image-generation-operation.d.ts +74 -0
  19. package/dist/activities/image-generation-references.d.ts +25 -0
  20. package/dist/activities/knowledge-source-sync-driver.d.ts +23 -0
  21. package/dist/activities/knowledge-source-sync.d.ts +75 -0
  22. package/dist/activities/packs.d.ts +13 -26
  23. package/dist/activities/parent-wake.d.ts +1 -1
  24. package/dist/activities/retained-screenshot-reaper.d.ts +32 -0
  25. package/dist/activities/retained-screenshots.d.ts +129 -0
  26. package/dist/activities/rig-verification.d.ts +82 -5
  27. package/dist/activities/run-credential-renewal.d.ts +2 -2
  28. package/dist/activities/run-input.d.ts +5 -1
  29. package/dist/activities/sandbox-images.d.ts +14 -0
  30. package/dist/activities/sandbox-lease.d.ts +47 -9
  31. package/dist/activities/scheduled-tasks.d.ts +2 -2
  32. package/dist/activities/session-state.d.ts +4 -4
  33. package/dist/activities/streaming.d.ts +1 -1
  34. package/dist/activities/types.d.ts +71 -5
  35. package/dist/activities/video-generation-admission.d.ts +38 -0
  36. package/dist/activities/video-generation-credential.d.ts +7 -0
  37. package/dist/activities/video-generation-reconciliation.d.ts +13 -0
  38. package/dist/activities/video-media-validation.d.ts +34 -0
  39. package/dist/activities/video-output-retention.d.ts +36 -0
  40. package/dist/activities/video-reference-staging.d.ts +49 -0
  41. package/dist/activities/workflow-wake.d.ts +2 -2
  42. package/dist/activities/workspace-capture.d.ts +11 -1
  43. package/dist/activities-control-44KBWLSM.js +6885 -0
  44. package/dist/activities-control-44KBWLSM.js.map +1 -0
  45. package/dist/activities-control.d.ts +289 -0
  46. package/dist/activities-turn-K4CEDEGJ.js +14675 -0
  47. package/dist/activities-turn-K4CEDEGJ.js.map +1 -0
  48. package/dist/activities-turn.d.ts +17 -0
  49. package/dist/activities.d.ts +130 -147
  50. package/dist/activity-services.d.ts +10 -0
  51. package/dist/artifact-materializer-entry.d.ts +6 -0
  52. package/dist/artifact-materializer-entry.js +2662 -0
  53. package/dist/artifact-materializer-entry.js.map +1 -0
  54. package/dist/artifact-outbox-entry.d.ts +2 -0
  55. package/dist/artifact-outbox-entry.js +681 -0
  56. package/dist/artifact-outbox-entry.js.map +1 -0
  57. package/dist/chunk-E3RI3I33.js +828 -0
  58. package/dist/chunk-E3RI3I33.js.map +1 -0
  59. package/dist/chunk-GRFQTTSQ.js +448 -0
  60. package/dist/chunk-GRFQTTSQ.js.map +1 -0
  61. package/dist/chunk-KKCRGAGZ.js +3091 -0
  62. package/dist/chunk-KKCRGAGZ.js.map +1 -0
  63. package/dist/{chunk-BJUW5LCM.js → chunk-RAMNYSAW.js} +15 -12
  64. package/dist/chunk-RAMNYSAW.js.map +1 -0
  65. package/dist/concurrency.d.ts +108 -5
  66. package/dist/editable-artifact-hint-broker.d.ts +49 -0
  67. package/dist/editable-artifact-materializer-launcher.d.ts +49 -0
  68. package/dist/editable-artifact-materializer-service.d.ts +108 -0
  69. package/dist/editable-artifact-materializer-storage.d.ts +12 -0
  70. package/dist/editable-artifact-materializer-subprocess.d.ts +50 -0
  71. package/dist/editable-artifact-materializer.d.ts +262 -0
  72. package/dist/editable-artifact-outbox-dispatcher.d.ts +44 -0
  73. package/dist/editable-artifact-outbox-service.d.ts +70 -0
  74. package/dist/host-export.d.ts +1 -1
  75. package/dist/host-export.js +1 -1
  76. package/dist/index.d.ts +176 -10
  77. package/dist/index.js +675 -16460
  78. package/dist/index.js.map +1 -1
  79. package/dist/memory-pressure-guard.d.ts +57 -0
  80. package/dist/model-checkpoint-memory-collector.d.ts +22 -0
  81. package/dist/observability-metrics.d.ts +33 -0
  82. package/dist/sandbox-reaper-contract.d.ts +40 -0
  83. package/dist/sandbox-reaper-timeout.d.ts +14 -0
  84. package/dist/sandbox-resume.d.ts +40 -7
  85. package/dist/sandbox-routing.d.ts +13 -6
  86. package/dist/worker-service-lifecycle.d.ts +6 -2
  87. package/dist/workflow-bundle.js +1044 -363
  88. package/dist/workflows/activities.d.ts +7 -1
  89. package/dist/workflows/document-index.d.ts +1 -1
  90. package/dist/workflows/knowledge-source-sync.d.ts +13 -0
  91. package/dist/workflows/rig-verification.d.ts +1 -1
  92. package/dist/workflows/sandbox-reaper.d.ts +8 -0
  93. package/dist/workflows/scheduled-tasks.d.ts +1 -1
  94. package/dist/workflows/session.d.ts +2 -2
  95. package/dist/workflows/video-generation.d.ts +10 -0
  96. package/dist/workflows/workflow-wake.d.ts +1 -1
  97. package/dist/workflows.d.ts +9 -7
  98. package/package.json +34 -15
  99. package/src/activities/agent-turn.ts +1905 -559
  100. package/src/activities/api-integrations.ts +138 -0
  101. package/src/activities/codemode-dispatcher.ts +335 -0
  102. package/src/activities/codemode-token-renewal.ts +64 -0
  103. package/src/activities/codex-capacity.ts +16 -7
  104. package/src/activities/codex-image-generation.ts +56 -0
  105. package/src/activities/codex-rotation.ts +19 -5
  106. package/src/activities/context-compaction.ts +47 -6
  107. package/src/activities/documents.ts +14 -4
  108. package/src/activities/environment.ts +52 -60
  109. package/src/activities/expiring-material-renewal.ts +16 -7
  110. package/src/activities/file-upload-reaper.ts +34 -3
  111. package/src/activities/gateway-image-generation.ts +146 -0
  112. package/src/activities/gateway-video-generation.ts +298 -0
  113. package/src/activities/generated-images.ts +860 -0
  114. package/src/activities/git-credential-renewal.ts +3 -3
  115. package/src/activities/goals.ts +6 -2
  116. package/src/activities/google-drive-changes.ts +454 -0
  117. package/src/activities/image-generation-operation.ts +333 -0
  118. package/src/activities/image-generation-references.ts +118 -0
  119. package/src/activities/knowledge-source-sync-driver.ts +27 -0
  120. package/src/activities/knowledge-source-sync.ts +2840 -0
  121. package/src/activities/mcp-credentials.ts +1 -0
  122. package/src/activities/packs.ts +55 -55
  123. package/src/activities/recording.ts +4 -5
  124. package/src/activities/retained-screenshot-reaper.ts +202 -0
  125. package/src/activities/retained-screenshots.ts +1317 -0
  126. package/src/activities/rig-verification.ts +567 -77
  127. package/src/activities/run-credential-renewal.ts +9 -2
  128. package/src/activities/run-input.ts +40 -10
  129. package/src/activities/sandbox-images.ts +167 -0
  130. package/src/activities/sandbox-lease.ts +1065 -483
  131. package/src/activities/scheduled-tasks.ts +96 -7
  132. package/src/activities/session-state.ts +4 -4
  133. package/src/activities/streaming.ts +42 -3
  134. package/src/activities/types.ts +87 -5
  135. package/src/activities/video-generation-admission.ts +270 -0
  136. package/src/activities/video-generation-credential.ts +34 -0
  137. package/src/activities/video-generation-reconciliation.ts +578 -0
  138. package/src/activities/video-media-validation.ts +326 -0
  139. package/src/activities/video-output-retention.ts +314 -0
  140. package/src/activities/video-reference-staging.ts +263 -0
  141. package/src/activities/workflow-wake.ts +2 -2
  142. package/src/activities/workspace-capture.ts +77 -13
  143. package/src/activities-control.ts +54 -0
  144. package/src/activities-turn.ts +40 -0
  145. package/src/activities.ts +50 -118
  146. package/src/activity-services.ts +62 -0
  147. package/src/artifact-materializer-entry.ts +35 -0
  148. package/src/artifact-outbox-entry.ts +29 -0
  149. package/src/concurrency.ts +484 -6
  150. package/src/editable-artifact-hint-broker.ts +235 -0
  151. package/src/editable-artifact-materializer-launcher.ts +515 -0
  152. package/src/editable-artifact-materializer-service.ts +787 -0
  153. package/src/editable-artifact-materializer-storage.ts +413 -0
  154. package/src/editable-artifact-materializer-subprocess.ts +956 -0
  155. package/src/editable-artifact-materializer.ts +1289 -0
  156. package/src/editable-artifact-outbox-dispatcher.ts +244 -0
  157. package/src/editable-artifact-outbox-service.ts +438 -0
  158. package/src/host-export-pump.ts +28 -11
  159. package/src/http.ts +3 -6
  160. package/src/index.ts +277 -72
  161. package/src/memory-pressure-guard.ts +489 -0
  162. package/src/model-checkpoint-memory-collector.ts +116 -0
  163. package/src/observability-metrics.ts +202 -7
  164. package/src/sandbox-reaper-contract.ts +73 -0
  165. package/src/sandbox-reaper-timeout.ts +79 -0
  166. package/src/sandbox-resume.ts +331 -157
  167. package/src/sandbox-routing.ts +49 -39
  168. package/src/worker-service-lifecycle.ts +82 -12
  169. package/src/workflows/activities.ts +30 -0
  170. package/src/workflows/file-upload-reaper.ts +6 -1
  171. package/src/workflows/knowledge-source-sync.ts +83 -0
  172. package/src/workflows/sandbox-reaper.ts +183 -21
  173. package/src/workflows/scheduled-tasks.ts +42 -6
  174. package/src/workflows/video-generation.ts +36 -0
  175. package/src/workflows.ts +17 -1
  176. package/dist/activities/redaction.d.ts +0 -1
  177. package/dist/activities/toolspace-token-renewal.d.ts +0 -23
  178. package/dist/chunk-BJUW5LCM.js.map +0 -1
  179. package/src/activities/redaction.ts +0 -9
  180. package/src/activities/toolspace-token-renewal.ts +0 -57
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/activities.ts","../src/activities/agent-turn.ts","../src/activities/mcp-credentials.ts","../src/activities/capabilities.ts","../src/activities/codex-rotation.ts","../src/activities/codex-fleet-shadow.ts","../src/activities/turn-attempt-fenced.ts","../src/activities/codex-auth.ts","../src/activities/codex-capacity.ts","../src/activities/common.ts","../src/activities/context-compaction.ts","../src/activities/run-input.ts","../src/activities/environment.ts","../src/activities/git-credential-renewal.ts","../src/activities/expiring-material-renewal.ts","../src/activities/run-credential-renewal.ts","../src/activities/toolspace-token-renewal.ts","../src/activities/run-credentials.ts","../src/activities/goals.ts","../src/activities/packs.ts","../src/activities/parent-wake.ts","../src/activities/redaction.ts","../src/activities/streaming.ts","../src/activities/types.ts","../src/sandbox-resume.ts","../src/sandbox-routing.ts","../src/op-journal.ts","../src/observability-metrics.ts","../src/activities/recording.ts","../src/activities/workspace-capture.ts","../src/activities/documents.ts","../src/activities/file-upload-reaper.ts","../src/activities/sandbox-lease.ts","../src/activities/scheduled-tasks.ts","../src/activities/session-state.ts","../src/activities/workflow-wake.ts","../src/activities/rig-verification.ts","../src/workflows/activities.ts","../src/http.ts","../src/concurrency.ts","../src/worker-service-lifecycle.ts"],"sourcesContent":["import {\n dbSearchPath,\n getSettings,\n resolveNatsControlPlaneAuth,\n retryStartupDependency,\n startupRetryOptions,\n temporalConnectionOptions,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n assertRuntimeDatabasePosture,\n createDb,\n markSessionWorkflowWakeDelivered,\n type Database,\n type RuntimeDatabasePostureOptions,\n} from \"@opengeni/db\";\nimport { createNatsEventBus, type EventBus } from \"@opengeni/events\";\nimport {\n createObservability,\n logStartupDependencyRetry,\n type Observability,\n} from \"@opengeni/observability\";\nimport {\n Connection,\n isGrpcServiceError,\n ScheduleAlreadyRunning,\n ScheduleOverlapPolicy,\n Client as TemporalClient,\n} from \"@temporalio/client\";\nimport { NativeConnection, Worker, type WorkflowBundleOption } from \"@temporalio/worker\";\nimport { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { ensureModalRegistryImage } from \"@opengeni/runtime\";\nimport {\n createControlActivities,\n createTurnActivities,\n type ActivityDependencies,\n} from \"./activities\";\nimport type {\n InspectSessionAttemptActivity,\n SignalCodexCapacityWorkflow,\n SignalSessionAttemptQuiesced,\n WakeSessionWorkflowSignal,\n} from \"./activities/types\";\nimport { turnTaskQueue } from \"./workflows/activities\";\nimport {\n dbReadyCheck,\n natsReadyCheck,\n startWorkerHttpServer,\n temporalReadyCheck,\n type WorkerLifecycleState,\n} from \"./http\";\nimport { observabilityEventLogger } from \"./observability-metrics\";\nimport {\n SESSION_WORKFLOW_WAKE_DISPATCHER_PERIOD_MS,\n SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID,\n SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_TYPE,\n} from \"@opengeni/core\";\nimport {\n CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES,\n CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS,\n turnWorkerConcurrencyLogFields,\n turnWorkerConcurrencyOptions,\n} from \"./concurrency\";\nimport {\n constructWithOwnedConnection,\n createWorkerServiceLifecycle,\n type WorkerServiceLifecycle,\n} from \"./worker-service-lifecycle\";\n\nexport {\n createHostExportPump,\n type HostExportDrainResult,\n type HostExportPump,\n type HostExportPumpOptions,\n type HostEventExport,\n type HostEventExportBatch,\n type HostEventSink,\n type HostUsageExport,\n type HostUsageExportBatch,\n type HostUsageSink,\n} from \"./host-export\";\n\n// The deterministic id of the ONE global reaper Schedule. A single id means\n// create() is idempotent across every worker in the pool: the first worker to\n// boot creates it, all others collide on this id (ScheduleAlreadyRunning) and\n// no-op — so the Schedule is registered EXACTLY ONCE per deployment regardless\n// of replica count.\nconst SANDBOX_REAPER_SCHEDULE_ID = \"opengeni-sandbox-lease-reaper\";\nexport const FILE_UPLOAD_REAPER_SCHEDULE_ID = \"opengeni-file-upload-reaper\";\nexport const FILE_UPLOAD_REAPER_PERIOD_MS = 15 * 60 * 1_000;\nexport type OpenGeniWorkerRole = \"control\" | \"turn\";\n\nexport type WorkerOptions = {\n role: OpenGeniWorkerRole;\n settings?: Settings;\n activities?: ReturnType<typeof createControlActivities> | ReturnType<typeof createTurnActivities>;\n activityDependencies?: ActivityDependencies;\n /** Override the release-coherent workflow artifact. Most hosts should omit this. */\n workflowBundle?: WorkflowBundleOption;\n};\n\ntype TemporalActivityLease = {\n lastHeartbeatTime?: { seconds?: unknown; nanos?: number | null } | null;\n lastStartedTime?: { seconds?: unknown; nanos?: number | null } | null;\n activityOptions?: {\n heartbeatTimeout?: { seconds?: unknown; nanos?: number | null } | null;\n } | null;\n};\n\nfunction temporalTimeMs(\n value: { seconds?: unknown; nanos?: number | null } | null | undefined,\n): number | null {\n if (value?.seconds === undefined || value.seconds === null) return null;\n return Number(String(value.seconds)) * 1_000 + Math.floor((value.nanos ?? 0) / 1_000_000);\n}\n\nexport function temporalActivityLeaseSettled(\n pending: TemporalActivityLease | null | undefined,\n nowMs = Date.now(),\n): boolean {\n if (!pending) return true;\n const heartbeatAt =\n temporalTimeMs(pending.lastHeartbeatTime) ?? temporalTimeMs(pending.lastStartedTime);\n const heartbeatTimeoutMs = temporalTimeMs(pending.activityOptions?.heartbeatTimeout);\n return (\n heartbeatAt !== null && heartbeatTimeoutMs !== null && nowMs >= heartbeatAt + heartbeatTimeoutMs\n );\n}\n\n/** The exact Temporal workflow run is absent, so it cannot retain an activity. */\nexport function temporalWorkflowExecutionNotFound(error: unknown): boolean {\n // gRPC status code 5 is NOT_FOUND. The typed guard prevents unrelated\n // provider/HTTP errors carrying a numeric code from proving quiescence.\n return isGrpcServiceError(error) && error.code === 5;\n}\n\ntype WorkerWorkflowDefinition =\n | { workflowBundle: WorkflowBundleOption }\n | { workflowsPath: string };\n\n/**\n * Resolve the deterministic workflow graph without asking installed hosts to\n * transpile or relocate package TypeScript. Monorepo source execution retains\n * the source path for the local development loop; published dist execution\n * fails closed unless the build-generated sibling artifact is present.\n */\nexport function resolveOpenGeniWorkflowDefinition(\n moduleUrl: string = import.meta.url,\n): WorkerWorkflowDefinition {\n const modulePath = fileURLToPath(moduleUrl).replaceAll(\"\\\\\", \"/\");\n if (modulePath.endsWith(\"/src/index.ts\")) {\n return { workflowsPath: fileURLToPath(new URL(\"./workflows.ts\", moduleUrl)) };\n }\n const codePath = fileURLToPath(new URL(\"./workflow-bundle.js\", moduleUrl));\n if (!existsSync(codePath)) {\n throw new Error(\n `OpenGeni workflow bundle is missing at ${codePath}; rebuild or reinstall @opengeni/worker-bundle`,\n );\n }\n return { workflowBundle: { codePath } };\n}\n\nexport async function createOpenGeniWorker(options: WorkerOptions): Promise<{\n worker: Worker;\n connection: NativeConnection;\n}> {\n const settings = options.settings ?? getSettings();\n const observability =\n options.activityDependencies?.observability ??\n createObservability(settings, { component: `worker-${options.role}` });\n if (options.role === \"turn\" && options.workflowBundle) {\n throw new Error(\"workflowBundle is valid only for the control worker role\");\n }\n // Pre-resolve a PRIVATE-registry sandbox image before any turn creates a box.\n // A provider-native OPENGENI_MODAL_IMAGE_ID intentionally bypasses this\n // registry path and is resolved by ModalImageSelector.fromId at create time.\n // Otherwise this is a no-op unless the registry secret + logical ref are both\n // set. Memoized in the provider, so it runs once per process.\n if (options.role === \"turn\") {\n await retryStartupDependency(\n \"Modal private-registry image\",\n () => ensureModalRegistryImage(settings),\n {\n ...startupRetryOptions(settings),\n onRetry: (event) => logStartupDependencyRetry(observability, event),\n },\n );\n }\n return constructWithOwnedConnection(\n () =>\n retryStartupDependency(\n \"Temporal\",\n () => NativeConnection.connect(temporalConnectionOptions(settings)),\n {\n ...startupRetryOptions(settings),\n onRetry: (event) => logStartupDependencyRetry(observability, event),\n },\n ),\n async (connection) => {\n const activities =\n options.activities ??\n (options.role === \"control\" ? createControlActivities : createTurnActivities)({\n ...options.activityDependencies,\n settings,\n observability,\n });\n const worker = await Worker.create({\n connection,\n namespace: settings.temporalNamespace,\n taskQueue:\n options.role === \"control\"\n ? settings.temporalTaskQueue\n : turnTaskQueue(settings.temporalTaskQueue),\n ...(options.role === \"control\"\n ? {\n ...(options.workflowBundle\n ? { workflowBundle: options.workflowBundle }\n : resolveOpenGeniWorkflowDefinition()),\n maxConcurrentWorkflowTaskExecutions: CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS,\n maxConcurrentActivityTaskExecutions: CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES,\n }\n : turnWorkerConcurrencyOptions(settings)),\n activities,\n // Cancellation is delivered through an activity heartbeat. The SDK would\n // otherwise throttle a two-minute heartbeat timeout to its 60-second cap,\n // making Pause/Steer take roughly a minute even though runAgentTurn emits a\n // heartbeat every ten seconds. Keep delivery bounded independently of the\n // heartbeat timeout and local timer cadence.\n maxHeartbeatThrottleInterval: \"5s\",\n defaultHeartbeatThrottleInterval: \"5s\",\n // GRACEFUL DEPLOY SHUTDOWN (with the SIGTERM handler in startWorker):\n // after shutdown() stops polling, in-flight activities get this long to\n // finish naturally; the rest are then CANCELLED with WORKER_SHUTDOWN —\n // which triggers agent-turn's same-turn recovery checkpoint instead of a\n // heartbeat-timeout worker_death. Short on purpose: a long grace here\n // only delays the checkpoint window long turns actually need.\n shutdownGraceTime: \"5s\",\n // Hard ceiling INSIDE the pod's terminationGracePeriodSeconds (120s): a\n // wedged checkpoint force-stops here, on our terms, rather than riding\n // into the kubelet's SIGKILL mid-DB-write.\n shutdownForceTime: \"100s\",\n });\n return { worker, connection };\n },\n (connection) => connection.close(),\n );\n}\n\n// A signalWithStart capability so a worker activity can wake a PARENT\n// session's workflow when a spawned worker completes (the parent may have\n// idled and let its run finish, so a plain signal would not start one).\n// Separate from the worker's NativeConnection: the @temporalio/client\n// Connection is what exposes workflow.signalWithStart.\nexport async function createWorkerWorkflowSignaler(\n settings: Settings,\n db: Database,\n): Promise<{\n wakeSessionWorkflow: WakeSessionWorkflowSignal;\n signalSessionAttemptQuiesced: SignalSessionAttemptQuiesced;\n inspectSessionAttemptActivity: InspectSessionAttemptActivity;\n signalCodexCapacityWorkflow: SignalCodexCapacityWorkflow;\n check: () => Promise<void>;\n close: () => Promise<void>;\n}> {\n const connection = await Connection.connect(temporalConnectionOptions(settings));\n const temporal = new TemporalClient({ connection, namespace: settings.temporalNamespace });\n return {\n wakeSessionWorkflow: async ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n interruptionRequested,\n }) => {\n if (interruptionRequested) {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"sessionControl\",\n signalArgs: [],\n });\n } else {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"queueChanged\",\n });\n }\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision,\n });\n },\n signalSessionAttemptQuiesced: async (proof) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId: proof.workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [\n {\n accountId: proof.accountId,\n workspaceId: proof.workspaceId,\n sessionId: proof.sessionId,\n },\n ],\n signal: \"sessionAttemptQuiesced\",\n signalArgs: [proof],\n });\n // No wake-outbox row exists yet: the direct receipt transaction failed.\n // The signalled workflow's DB-only control activity owns committing the\n // receipt and its exact wake revision atomically.\n },\n inspectSessionAttemptActivity: async ({ workflowId, workflowRunId, activityId }) => {\n let description;\n try {\n description = await connection.workflowService.describeWorkflowExecution({\n namespace: settings.temporalNamespace,\n execution: { workflowId, runId: workflowRunId },\n });\n } catch (error) {\n if (temporalWorkflowExecutionNotFound(error)) return \"settled\";\n throw error;\n }\n const pending = description.pendingActivities?.find(\n (activity) => activity.activityId === activityId,\n );\n return temporalActivityLeaseSettled(pending) ? \"settled\" : \"pending\";\n },\n signalCodexCapacityWorkflow: async ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"codexCapacityChanged\",\n signalArgs: [wakeRevision],\n });\n // A typed capacity signal cannot acknowledge the generic outbox row:\n // another producer may have advanced it with a Pause/Steer that requires\n // sessionControl. The global dispatcher owns that acknowledgement.\n },\n check: async () => {\n await connection.workflowService.getSystemInfo({});\n },\n close: async () => {\n await connection.close();\n },\n };\n}\n\n/**\n * Register the ONE global reaper Temporal Schedule (the sole liveness/GC/cost-stop\n * driver — P1.3 / OD-3) and durable system-update outbox repair cadence. With\n * sandbox ownership off the activity performs bounded DB outbox repair and\n * read-only observability projections; it never mutates or terminates sandbox leases.\n *\n * The Schedule fires sandboxReaperWorkflow on the worker's global task queue\n * every settings.sandboxLeaseReaperPeriodMs (the SAME cadence the boot invariant\n * `reaperPeriod < viewerHolderTTL` and `reaperPeriod + idleGrace < providerLifetime`\n * validates in packages/config — wiring the schedule period to it). SKIP overlap means a slow\n * sweep never overlaps itself. Idempotent: a duplicate scheduleId across the\n * worker pool collides on ScheduleAlreadyRunning and no-ops, so the Schedule is\n * registered exactly once per deployment.\n *\n * Returns a `close()` for the dedicated client connection (separate from the\n * worker's NativeConnection — the Schedule client is a @temporalio/client).\n */\nexport async function registerSandboxReaperSchedule(\n settings: Settings,\n observability: Observability,\n): Promise<{ registered: boolean; close: () => Promise<void> }> {\n const connection = await Connection.connect(temporalConnectionOptions(settings));\n const temporal = new TemporalClient({ connection, namespace: settings.temporalNamespace });\n try {\n await temporal.schedule.create({\n scheduleId: SANDBOX_REAPER_SCHEDULE_ID,\n spec: {\n // @every-style interval: fire once per reaper period. The boot invariant\n // (config) guarantees reaperPeriod < viewerHolderTTL and\n // reaperPeriod + idleGrace < providerLifetime.\n intervals: [{ every: settings.sandboxLeaseReaperPeriodMs }],\n },\n action: {\n type: \"startWorkflow\",\n workflowType: \"sandboxReaperWorkflow\",\n taskQueue: settings.temporalTaskQueue,\n args: [],\n },\n policies: {\n // A slow sweep must never overlap itself; the next fire is skipped.\n overlap: ScheduleOverlapPolicy.SKIP,\n catchupWindow: \"1m\",\n pauseOnFailure: false,\n },\n });\n observability.info(\"Registered the global sandbox-lease reaper Schedule\", {\n scheduleId: SANDBOX_REAPER_SCHEDULE_ID,\n reaperPeriodMs: settings.sandboxLeaseReaperPeriodMs,\n });\n return {\n registered: true,\n close: async () => {\n await connection.close();\n },\n };\n } catch (error) {\n if (error instanceof ScheduleAlreadyRunning) {\n // Another worker in the pool already created it. The Schedule exists\n // exactly once — this is the expected no-op on every replica after the\n // first. (We do NOT update the spec here: a redeploy with a changed cadence\n // is an operational concern handled by deleting+recreating the Schedule.)\n observability.info(\"Global sandbox-lease reaper Schedule already registered\", {\n scheduleId: SANDBOX_REAPER_SCHEDULE_ID,\n });\n return {\n registered: false,\n close: async () => {\n await connection.close();\n },\n };\n }\n await connection.close().catch(() => undefined);\n throw error;\n }\n}\n\n/**\n * Register the one provider-neutral expired direct-upload cleanup Schedule.\n * Unlike sandbox GC this is always registered: file uploads can be enabled in\n * deployments where sandbox ownership is disabled. The activity is a cheap\n * no-op when object storage is not configured.\n */\nexport async function registerFileUploadReaperSchedule(\n settings: Settings,\n observability: Observability,\n): Promise<{ registered: boolean; close: () => Promise<void> }> {\n const connection = await Connection.connect(temporalConnectionOptions(settings));\n const temporal = new TemporalClient({ connection, namespace: settings.temporalNamespace });\n try {\n await temporal.schedule.create({\n scheduleId: FILE_UPLOAD_REAPER_SCHEDULE_ID,\n spec: { intervals: [{ every: FILE_UPLOAD_REAPER_PERIOD_MS }] },\n action: {\n type: \"startWorkflow\",\n workflowType: \"fileUploadReaperWorkflow\",\n taskQueue: settings.temporalTaskQueue,\n args: [],\n },\n policies: {\n overlap: ScheduleOverlapPolicy.SKIP,\n catchupWindow: \"1m\",\n pauseOnFailure: false,\n },\n });\n observability.info(\"Registered the global file-upload reaper Schedule\", {\n scheduleId: FILE_UPLOAD_REAPER_SCHEDULE_ID,\n reaperPeriodMs: FILE_UPLOAD_REAPER_PERIOD_MS,\n });\n return { registered: true, close: async () => connection.close() };\n } catch (error) {\n if (error instanceof ScheduleAlreadyRunning) {\n observability.info(\"Global file-upload reaper Schedule already registered\", {\n scheduleId: FILE_UPLOAD_REAPER_SCHEDULE_ID,\n });\n return { registered: false, close: async () => connection.close() };\n }\n await connection.close().catch(() => undefined);\n throw error;\n }\n}\n\n/**\n * Register the one repair cadence for committed workflow-wake revisions. The\n * activity only reads the transactional outbox and sends revision-scoped\n * signals; it is independent of sandbox ownership and child-agent features.\n */\nexport async function registerSessionWorkflowWakeDispatcherSchedule(\n settings: Settings,\n observability: Observability,\n): Promise<{ registered: boolean; close: () => Promise<void> }> {\n const connection = await Connection.connect(temporalConnectionOptions(settings));\n const temporal = new TemporalClient({ connection, namespace: settings.temporalNamespace });\n try {\n await temporal.schedule.create({\n scheduleId: SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID,\n spec: { intervals: [{ every: SESSION_WORKFLOW_WAKE_DISPATCHER_PERIOD_MS }] },\n action: {\n type: \"startWorkflow\",\n workflowType: SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_TYPE,\n taskQueue: settings.temporalTaskQueue,\n args: [],\n },\n policies: {\n overlap: ScheduleOverlapPolicy.SKIP,\n catchupWindow: \"1m\",\n pauseOnFailure: false,\n },\n });\n observability.info(\"Registered the session-workflow wake dispatcher Schedule\", {\n scheduleId: SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID,\n periodMs: SESSION_WORKFLOW_WAKE_DISPATCHER_PERIOD_MS,\n });\n return { registered: true, close: async () => connection.close() };\n } catch (error) {\n if (error instanceof ScheduleAlreadyRunning) {\n observability.info(\"Session-workflow wake dispatcher Schedule already registered\", {\n scheduleId: SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID,\n });\n return { registered: false, close: async () => connection.close() };\n }\n await connection.close().catch(() => undefined);\n throw error;\n }\n}\n\nexport type OpenGeniWorkerServiceOptions = Omit<WorkerOptions, \"activityDependencies\"> & {\n activityDependencies: ActivityDependencies & { db: Database; bus: EventBus };\n /**\n * Exact catalog posture required by the standalone runtime. Embedded hosts\n * may omit this when they own an equivalent database isolation contract.\n */\n databasePosture?: RuntimeDatabasePostureOptions;\n /**\n * `role-default` registers OpenGeni's internal maintenance schedules on a\n * control worker only. These are engine maintenance schedules, not a host's\n * product-level scheduled-agent jobs. Use `none` when another control worker\n * in the same deployment owns them.\n */\n internalSchedules?: \"role-default\" | \"none\";\n /** Set false only when the host exposes equivalent lifecycle endpoints itself. */\n http?: false | { readinessTimeoutMs?: number };\n};\n\nexport type OpenGeniWorkerService = {\n readonly role: OpenGeniWorkerRole;\n readonly worker: Worker;\n readonly connection: NativeConnection;\n state(): WorkerLifecycleState;\n run(): Promise<void>;\n drain(reason?: string): void;\n close(): Promise<void>;\n};\n\nexport function workerOwnsInternalSchedules(\n role: OpenGeniWorkerRole,\n policy: OpenGeniWorkerServiceOptions[\"internalSchedules\"] = \"role-default\",\n): boolean {\n return role === \"control\" && policy !== \"none\";\n}\n\n/**\n * Construct one role-specific worker process around the lower-level Temporal\n * worker factory. The service owns every Temporal client and HTTP listener it\n * creates. The embedding host retains ownership of its injected DB and EventBus\n * handles and closes those only after this service has drained.\n */\nexport async function createOpenGeniWorkerService(\n options: OpenGeniWorkerServiceOptions,\n): Promise<OpenGeniWorkerService> {\n const settings = options.settings ?? getSettings();\n const observability =\n options.activityDependencies.observability ??\n createObservability(settings, { component: `worker-${options.role}` });\n const retryOptions = startupRetryOptions(settings);\n const onRetry = (event: Parameters<typeof logStartupDependencyRetry>[1]) =>\n logStartupDependencyRetry(observability, event);\n let lifecycle: WorkerServiceLifecycle | undefined;\n let signaler: Awaited<ReturnType<typeof createWorkerWorkflowSignaler>> | undefined;\n let workerBundle: Awaited<ReturnType<typeof createOpenGeniWorker>> | undefined;\n const schedules: Array<{ close: () => Promise<void> }> = [];\n let httpServer: ReturnType<typeof startWorkerHttpServer> | undefined;\n\n try {\n const needsSignaler =\n !options.activityDependencies.wakeSessionWorkflow ||\n !options.activityDependencies.signalSessionAttemptQuiesced ||\n !options.activityDependencies.inspectSessionAttemptActivity ||\n !options.activityDependencies.signalCodexCapacityWorkflow;\n if (needsSignaler) {\n signaler = await retryStartupDependency(\n \"Temporal client\",\n () => createWorkerWorkflowSignaler(settings, options.activityDependencies.db),\n { ...retryOptions, onRetry },\n );\n }\n const wakeSessionWorkflow =\n options.activityDependencies.wakeSessionWorkflow ?? signaler?.wakeSessionWorkflow;\n const signalSessionAttemptQuiesced =\n options.activityDependencies.signalSessionAttemptQuiesced ??\n signaler?.signalSessionAttemptQuiesced;\n const inspectSessionAttemptActivity =\n options.activityDependencies.inspectSessionAttemptActivity ??\n signaler?.inspectSessionAttemptActivity;\n const signalCodexCapacityWorkflow =\n options.activityDependencies.signalCodexCapacityWorkflow ??\n signaler?.signalCodexCapacityWorkflow;\n if (\n !wakeSessionWorkflow ||\n !signalSessionAttemptQuiesced ||\n !inspectSessionAttemptActivity ||\n !signalCodexCapacityWorkflow\n ) {\n throw new Error(\"OpenGeni worker lifecycle could not resolve its workflow signalers\");\n }\n workerBundle = await createOpenGeniWorker({\n role: options.role,\n settings,\n ...(options.activities ? { activities: options.activities } : {}),\n ...(options.workflowBundle ? { workflowBundle: options.workflowBundle } : {}),\n activityDependencies: {\n ...options.activityDependencies,\n settings,\n observability,\n wakeSessionWorkflow,\n signalSessionAttemptQuiesced,\n inspectSessionAttemptActivity,\n signalCodexCapacityWorkflow,\n },\n });\n\n if (workerOwnsInternalSchedules(options.role, options.internalSchedules)) {\n schedules.push(\n await retryStartupDependency(\n \"Temporal schedule (sandbox reaper)\",\n () => registerSandboxReaperSchedule(settings, observability),\n { ...retryOptions, onRetry },\n ),\n );\n schedules.push(\n await retryStartupDependency(\n \"Temporal schedule (file upload reaper)\",\n () => registerFileUploadReaperSchedule(settings, observability),\n { ...retryOptions, onRetry },\n ),\n );\n schedules.push(\n await retryStartupDependency(\n \"Temporal schedule (session-workflow wake dispatcher)\",\n () => registerSessionWorkflowWakeDispatcherSchedule(settings, observability),\n { ...retryOptions, onRetry },\n ),\n );\n }\n\n if (options.http !== false) {\n httpServer = startWorkerHttpServer({\n settings,\n observability,\n checks: {\n db: dbReadyCheck(options.activityDependencies.db, options.databasePosture),\n nats: natsReadyCheck(options.activityDependencies.bus),\n temporal: temporalReadyCheck(workerBundle.connection),\n },\n ...(options.http?.readinessTimeoutMs ? { timeoutMs: options.http.readinessTimeoutMs } : {}),\n lifecycle: { role: options.role, state: () => lifecycle?.state() ?? \"starting\" },\n });\n }\n } catch (error) {\n httpServer?.stop(true);\n await Promise.allSettled([\n workerBundle?.connection.close(),\n signaler?.close(),\n ...schedules.map((schedule) => schedule.close()),\n ]);\n throw error;\n }\n\n const activeWorkerBundle = workerBundle;\n const activeSignaler = signaler;\n if (!activeWorkerBundle) {\n throw new Error(\"OpenGeni worker service initialization did not complete\");\n }\n\n lifecycle = createWorkerServiceLifecycle({\n role: options.role,\n worker: activeWorkerBundle.worker,\n observability,\n closeOwnedResources: async () => {\n httpServer?.stop(true);\n await Promise.allSettled([\n activeWorkerBundle.connection.close(),\n activeSignaler?.close(),\n ...schedules.map((schedule) => schedule.close()),\n ]);\n },\n onReady: () => {\n observability.info(\"OpenGeni worker listening\", {\n role: options.role,\n temporalTaskQueue:\n options.role === \"control\"\n ? settings.temporalTaskQueue\n : turnTaskQueue(settings.temporalTaskQueue),\n ...(options.role === \"turn\"\n ? turnWorkerConcurrencyLogFields(settings)\n : {\n concurrencyMode: \"fixed\",\n maxConcurrentTurns: CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES,\n targetCpuUsage: null,\n targetMemoryUsage: null,\n }),\n maxConcurrentWorkflowTaskExecutions:\n options.role === \"control\" ? CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS : 0,\n httpPort: options.http === false ? null : settings.workerHttpPort,\n });\n },\n });\n\n return {\n role: options.role,\n worker: activeWorkerBundle.worker,\n connection: activeWorkerBundle.connection,\n state: lifecycle.state,\n run: lifecycle.run,\n drain: lifecycle.drain,\n close: lifecycle.close,\n };\n}\n\nexport type RunOpenGeniWorkerOptions = OpenGeniWorkerServiceOptions & {\n /** Defaults to SIGTERM and SIGINT. Pass false when the host owns process signals. */\n shutdownSignals?: false | ReadonlyArray<\"SIGTERM\" | \"SIGINT\">;\n};\n\n/** Start, drain, and close one embedded worker process. */\nexport async function runOpenGeniWorker(options: RunOpenGeniWorkerOptions): Promise<void> {\n const service = await createOpenGeniWorkerService(options);\n const signals =\n options.shutdownSignals === false ? [] : (options.shutdownSignals ?? [\"SIGTERM\", \"SIGINT\"]);\n const handlers = signals.map((signal) => {\n const handler = () => service.drain(signal);\n process.on(signal, handler);\n return { signal, handler };\n });\n try {\n await service.run();\n } finally {\n for (const { signal, handler } of handlers) {\n process.off(signal, handler);\n }\n await service.close();\n }\n}\n\nexport async function startWorker() {\n const role = process.env.OPENGENI_WORKER_ROLE;\n if (role !== \"control\" && role !== \"turn\") {\n throw new Error(\"OPENGENI_WORKER_ROLE must be explicitly set to 'control' or 'turn'\");\n }\n const settings = getSettings();\n const observability = createObservability(settings, { component: `worker-${role}` });\n const retryOptions = startupRetryOptions(settings);\n const onRetry = (event: Parameters<typeof logStartupDependencyRetry>[1]) =>\n logStartupDependencyRetry(observability, event);\n const searchPath = dbSearchPath(settings);\n const dbClient = createDb(settings.databaseUrl, {\n ...(searchPath ? { searchPath } : {}),\n rlsStrategy: settings.rlsStrategy,\n });\n const databasePosture = {\n rlsStrategy: settings.rlsStrategy,\n expectedRole: settings.runtimeDatabaseRole,\n targetSchema: settings.dbSchema.trim() || \"public\",\n } as const;\n const controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n let bus: Awaited<ReturnType<typeof createNatsEventBus>> | undefined;\n try {\n await retryStartupDependency(\n \"PostgreSQL runtime posture\",\n () => assertRuntimeDatabasePosture(dbClient.db, databasePosture),\n { ...retryOptions, onRetry },\n );\n bus = await retryStartupDependency(\n \"NATS\",\n () =>\n createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth\n ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password }\n : undefined,\n { logger: observabilityEventLogger(observability) },\n ),\n { ...retryOptions, onRetry },\n );\n await runOpenGeniWorker({\n role,\n settings,\n databasePosture,\n activityDependencies: {\n observability,\n db: dbClient.db,\n bus,\n },\n });\n } finally {\n await Promise.allSettled([bus?.close(), dbClient.close()]);\n }\n}\n\nif (import.meta.main) {\n await startWorker();\n}\n","import { dbSearchPath, getSettings, resolveNatsControlPlaneAuth } from \"@opengeni/config\";\nimport { createDb } from \"@opengeni/db\";\nimport { createDocumentServices } from \"@opengeni/documents\";\nimport { createNatsEventBus } from \"@opengeni/events\";\nimport { createObservability } from \"@opengeni/observability\";\nimport { createProductionAgentRuntime } from \"@opengeni/runtime\";\nimport { createObjectStorage } from \"@opengeni/storage\";\nimport { createRunAgentTurnActivity } from \"./activities/agent-turn\";\nimport { createCodexCapacityActivities } from \"./activities/codex-capacity\";\nimport { createDocumentActivities } from \"./activities/documents\";\nimport { createFileUploadReaperActivities } from \"./activities/file-upload-reaper\";\nimport { createGoalActivities } from \"./activities/goals\";\nimport { createSandboxLeaseActivities } from \"./activities/sandbox-lease\";\nimport { createScheduledTaskActivities } from \"./activities/scheduled-tasks\";\nimport { createSessionStateActivities } from \"./activities/session-state\";\nimport { createWorkflowWakeActivities } from \"./activities/workflow-wake\";\nimport { createRigVerificationActivities } from \"./activities/rig-verification\";\nimport type { ActivityDependencies, ActivityServices } from \"./activities/types\";\nimport {\n observabilityEventLogger,\n runtimeMetricsHooksForObservability,\n} from \"./observability-metrics\";\n\nexport type {\n ActivityDependencies,\n DispatchScheduledTaskRunInput,\n DispatchScheduledTaskRunResult,\n ExpireSessionHumanInputInput,\n ExpireSessionHumanInputResult,\n IndexDocumentInput,\n MaybeContinueGoalInput,\n MaybeContinueGoalResult,\n CodexCapacityWaitRef,\n GetCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitResult,\n RecoverDispatchInput,\n RecoverDispatchResult,\n RecoverEscapedMcpTimeoutInput,\n RecoverEscapedMcpTimeoutResult,\n PersistSessionAttemptQuiescenceInput,\n ReconcileSessionAttemptQuiescenceInput,\n ReconcileSessionAttemptQuiescenceResult,\n RunAgentTurnInput,\n RunAgentTurnResult,\n SessionAttemptQuiescenceProof,\n} from \"./activities/types\";\n\nfunction createActivityServices(\n dependencies: ActivityDependencies,\n): () => Promise<ActivityServices> {\n let servicesPromise: Promise<ActivityServices> | null = null;\n\n async function services(): Promise<ActivityServices> {\n servicesPromise ??= (async () => {\n const settings = dependencies.settings ?? getSettings();\n const observability =\n dependencies.observability ?? createObservability(settings, { component: \"worker\" });\n // Step I: when not injected, build the standalone handle — searchPath\n // undefined for standalone (public), scoped to the dedicated schema +\n // host RLS strategy when embedded config is set. An embedded host injects\n // `dependencies.db` directly and this branch is skipped.\n const searchPath = dbSearchPath(settings);\n const dbClient = dependencies.db\n ? null\n : createDb(settings.databaseUrl, {\n ...(searchPath ? { searchPath } : {}),\n rlsStrategy: settings.rlsStrategy,\n });\n // The PRIVILEGED control-plane NATS login (M-AUTH): the worker resolves the\n // SAME static account user the API uses to request `agent.*.rpc`. Null in\n // local dev → anonymous connect (the bus default).\n const controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n return {\n settings,\n db: dependencies.db ?? dbClient!.db,\n // §7 Step G — EventBus binding contract. `bus` is the INJECTED\n // live-fanout port; the ONE production impl is `createNatsEventBus`,\n // the default on BOTH processes (this worker edge + the API edge in\n // `apps/api/src/index.ts`). A host that embeds OpenGeni injects ONE\n // broker binding (the same `createNatsEventBus(natsUrl)`) here AND on\n // the mounted API, so the two SEPARATE processes share one broker and\n // derive the IDENTICAL `sessionSubject` — the only way live fanout\n // (worker emit → API SSE) works cross-process (schema-isolation contract F5/F6, proven).\n // NEVER default to an in-memory bus: it fans out intra-process only and\n // would silently break live SSE. unset → today's NATS default,\n // byte-for-byte. The bus is live-fanout ONLY — the durable Postgres\n // `session_events` log is source-of-truth (the API backfills missed\n // events by sequence). See `.agents/skills/opengeni/references/eventbus-binding-contract.md`.\n bus:\n dependencies.bus ??\n (await createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth\n ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password }\n : undefined,\n { logger: observabilityEventLogger(observability) },\n )),\n runtime:\n dependencies.runtime ??\n createProductionAgentRuntime({\n metrics: runtimeMetricsHooksForObservability(observability),\n }),\n objectStorage: dependencies.objectStorage ?? createObjectStorage(settings),\n documentServices: dependencies.documentServices ?? createDocumentServices(settings),\n observability,\n wakeSessionWorkflow: dependencies.wakeSessionWorkflow ?? null,\n signalSessionAttemptQuiesced: dependencies.signalSessionAttemptQuiesced ?? null,\n inspectSessionAttemptActivity: dependencies.inspectSessionAttemptActivity ?? null,\n signalCodexCapacityWorkflow: dependencies.signalCodexCapacityWorkflow ?? null,\n // §7.5 P3 — host-entitlements port. No constructed default: standalone\n // has no host meter, so unset → null → `ensureRunAllowed` reads the\n // local ledger exactly as today (mirrors `wakeSessionWorkflow`'s\n // null-degrades-gracefully shape, not a `createX(settings)` default).\n entitlements: dependencies.entitlements ?? null,\n // §7.6 connection-credential provider — host connection-credential provider. No constructed\n // default: standalone owns its own GitHub App + encryption key, so unset\n // → null → the per-run credential mint self-mints from `settings`\n // (createGitHubAppInstallationToken + environmentsEncryptionKeyBytes)\n // exactly as today. Same null-degrades shape as `entitlements`.\n connectionCredentials: dependencies.connectionCredentials ?? null,\n };\n })();\n return servicesPromise;\n }\n\n return services;\n}\n\nfunction controlActivities(services: () => Promise<ActivityServices>) {\n return {\n ...createDocumentActivities(services),\n ...createSessionStateActivities(services),\n ...createScheduledTaskActivities(services),\n ...createGoalActivities(services),\n ...createCodexCapacityActivities(services),\n ...createRigVerificationActivities(services),\n ...createFileUploadReaperActivities(services),\n ...createWorkflowWakeActivities(services),\n // P1.3: the SOLE liveness/GC/cost-stop driver. Only reapSandboxLeases — no\n // *ForViewer activities, no ownerHeartbeat, no resolveOwnerTaskQueue.\n ...createSandboxLeaseActivities(services),\n };\n}\n\nexport function createControlActivities(dependencies: ActivityDependencies = {}) {\n return controlActivities(createActivityServices(dependencies));\n}\n\nexport function createTurnActivities(dependencies: ActivityDependencies = {}) {\n return { runAgentTurn: createRunAgentTurnActivity(createActivityServices(dependencies)) };\n}\n\n/** Direct activity harness for tests; production workers always choose one role. */\nexport function createActivityTestHarness(dependencies: ActivityDependencies = {}) {\n const services = createActivityServices(dependencies);\n return { runAgentTurn: createRunAgentTurnActivity(services), ...controlActivities(services) };\n}\n\nconst defaultControlActivities = createControlActivities();\nconst defaultTurnActivities = createTurnActivities();\n\nexport const runAgentTurn = defaultTurnActivities.runAgentTurn;\nexport const indexDocument = defaultControlActivities.indexDocument;\nexport const failSessionAttempt = defaultControlActivities.failSessionAttempt;\nexport const settleSessionInterruptions = defaultControlActivities.settleSessionInterruptions;\nexport const persistSessionAttemptQuiescence =\n defaultControlActivities.persistSessionAttemptQuiescence;\nexport const reconcileSessionAttemptQuiescence =\n defaultControlActivities.reconcileSessionAttemptQuiescence;\nexport const recoverDispatch = defaultControlActivities.recoverDispatch;\nexport const recoverEscapedMcpTimeout = defaultControlActivities.recoverEscapedMcpTimeout;\nexport const peekSessionWork = defaultControlActivities.peekSessionWork;\nexport const expireSessionHumanInput = defaultControlActivities.expireSessionHumanInput;\nexport const markSessionIdle = defaultControlActivities.markSessionIdle;\nexport const dispatchScheduledTaskRun = defaultControlActivities.dispatchScheduledTaskRun;\nexport const enqueueGoalRetryWake = defaultControlActivities.enqueueGoalRetryWake;\nexport const maybeContinueGoal = defaultControlActivities.maybeContinueGoal;\nexport const getCodexCapacityWait = defaultControlActivities.getCodexCapacityWait;\nexport const reconcileCodexCapacityWait = defaultControlActivities.reconcileCodexCapacityWait;\nexport const reapSandboxLeases = defaultControlActivities.reapSandboxLeases;\nexport const reapExpiredFileUploads = defaultControlActivities.reapExpiredFileUploads;\nexport const dispatchSessionWorkflowWakes = defaultControlActivities.dispatchSessionWorkflowWakes;\nexport const verifyRigChange = defaultControlActivities.verifyRigChange;\nexport const verifyRigVersion = defaultControlActivities.verifyRigVersion;\n","import {\n advanceWorkspaceGeneration,\n verifyWorkspaceMutationSettlement,\n applySessionTurnSettlement,\n requestSessionTurnRecovery,\n claimSessionWorkForAttempt,\n applyCreditDebitUpToBalance,\n getBillingBalance,\n getRigName,\n getRigVersion,\n getSandbox,\n readActiveSandbox,\n setActiveSandbox,\n requireFile,\n getSessionEvent,\n getSessionRootId,\n getSessionGoal,\n getHumanInputResumeForEvent,\n getSessionHumanInputRequest,\n installOrReadTurnExecutionPolicyForAttempt,\n workspaceCodexSubscriptionActive,\n acquireCodexCredentialLease,\n armCodexCapacityWait,\n heartbeatCodexCredentialLeaseUntil,\n releaseCodexCredentialLease,\n CODEX_CREDENTIAL_LEASE_TTL_MS,\n getCodexRotationSettings,\n getWorkspaceModelPolicy,\n getWorkspaceGrant,\n listCodexAccountStatuses,\n fetchCodexUsageForAccount,\n getSessionCodexState,\n recordSessionActiveCodexCredential,\n setSessionCodexPin,\n recordCodexAccountUsageWithWakeTargets,\n quarantineCodexCredentialForLease,\n setActiveCodexCredential,\n resolveWorkspaceMemoryBlock,\n setCodexCredentialExhaustedWithWakeTargets,\n withCodexCapacityMutation,\n countConsecutiveReactiveRotations,\n requireSession,\n recordUsageEvent,\n recordModelCallFact,\n registerPendingSessionToolCall,\n recordPendingSessionToolCallResult,\n clearDurablePendingSessionToolCalls,\n appendSessionHistoryItems,\n isSessionCompactionRequested,\n countSessionHistoryItems,\n getActiveSessionHistoryItems,\n nextSessionHistoryPosition,\n settleCodexCredentialLeaseLoss,\n settleCodexCredentialFailover,\n upsertSandboxSessionEnvelope,\n setSessionLastInputTokensForTurnAttempt,\n sumUsageQuantity,\n heartbeatLeaseHolder,\n readLease,\n accrueWarmSeconds,\n getMaterializedSandboxFileResources,\n markSandboxFileResourcesMaterialized,\n areGitHubRepositoriesAllowedForWorkspace,\n SandboxLeaseRecoveryBlockedError,\n SandboxLeaseSupersededError,\n SandboxImageConflictError,\n isSessionEventPersistenceError,\n getEnrollment,\n abandonRecordingForTurnAttempt,\n markSessionAttemptQuiesced,\n getOrCreatePreferenceRegistrySnapshot,\n getOrCreateWorkspaceInstructionPolicySnapshot,\n PreferenceRegistryInitiatorError,\n beginConnectorActionExecution,\n completeConnectorActionExecution,\n prepareConnectorActionApproval,\n withCodexAppsRequestAuthorization,\n type AppendEventInput,\n type ActiveSandboxPointer,\n type SandboxRecord,\n type CodexCredentialLeaseResult,\n type CodexCredentialLeaseSelectionContext,\n type ApplySessionTurnSettlementInput,\n type SessionTurnRecordingSettlement,\n} from \"@opengeni/db\";\nimport { appendAndPublishTurnEventsFenced, publishDurableSessionEvents } from \"@opengeni/events\";\nimport { sandboxOperationMetricObserver } from \"@opengeni/observability\";\nimport {\n sandboxStateEntryFromRunState,\n maxTurnsExceededRunState,\n modelResponseServiceTierFromSdkEvent,\n modelTerminalResponseFromSdkEvent,\n normalizeModelCallUsage,\n normalizeSdkEvent,\n projectHistoryForProvider,\n sanitizeHistoryItemsForModel,\n projectModelInputForCapabilities,\n appendPersistentSessionSettings,\n appendSessionInstructions,\n appendWorkspaceGovernance,\n appendWorkspaceMemory,\n composeAgentInstructions,\n hasActiveWorkspaceInstructionPolicy,\n renderWorkspaceGovernanceContext,\n summarizeForCompaction,\n requestRemoteCompactionV2,\n serializedToolsForRemoteCompaction,\n REMOTE_COMPACTION_V2_BETA_FEATURE,\n REMOTE_COMPACTION_V2_IMPLEMENTATION,\n CompactionProviderResponseError,\n EmptyCompactionSummaryError,\n ensureModalRegistryImage,\n findCompactionNeededError,\n materializeSandboxFileDownloads,\n materializeRunCredentials,\n clearRunCredentials,\n clearRunCredentialsForAttempt,\n withRunCredentialsSession,\n refreshGitCredentialBindingTokenFiles,\n refreshToolspaceTokenFile,\n toolspaceTokenFileFromEnvironment,\n sandboxFileDownloadFailureNote,\n SUMMARY_BUFFER_TOKENS,\n isMcpRequestTimeoutError,\n isMcpTransportConnectivityError,\n runOwnedSandboxSetup,\n RoutingMutationOutcomeUnknownError,\n WorkspaceArchiveIntegrityError,\n sdkBackendIdForSandboxBackend,\n swapTargetEstablishability,\n type SandboxFileDownload,\n type SandboxFileDownloadFailure,\n type OpenGeniRuntime,\n type ComputerToolMode,\n type ModelResponseUsage,\n type ModelCallUsageInput,\n type ModelCallUsageNormalization,\n type BuildAgentOptions,\n type ConnectorActionPolicyHooks,\n type RunAgentStreamOptions,\n type TurnToolCancellationFence,\n type BackendUnresolvableCode,\n type EstablishedSandboxSession,\n type GitCredentialTokenWriterSession,\n type NormalizedRunCredentialMaterial,\n type RunCredentialCommandSession,\n type ToolspaceTokenWriterSession,\n deleteRecordingArtifacts,\n stopRecording as stopRecordingOnBox,\n} from \"@opengeni/runtime\";\nimport { connectionTokenResolverForTurn } from \"./mcp-credentials\";\nimport {\n assertTurnExecutionPolicyMatchesConfigV1,\n calculateGatewayReportedCostMicros,\n calculateModelUsageCostMicros,\n configuredModelPricing,\n configuredStaticUsageLimits,\n responseSatisfiesLatencyMode,\n sandboxArchiveCaptureTimeoutMs,\n sandboxWarmRateMicrosPerSecond,\n serviceTierForLatencyMode,\n settingsWithResolvedModelContext,\n resolveTurnExecutionPolicyV1,\n OPENGENI_GATEWAY_MODELS,\n OPENGENI_GATEWAY_PROVIDER_ID,\n type ModelUsageInput,\n type ModelProviderApi,\n type RegistryProviderKind,\n type Settings,\n} from \"@opengeni/config\";\nimport { ApplicationFailure, CancelledFailure } from \"@temporalio/activity\";\nimport {\n settingsWithCodexCredential,\n settingsWithEnabledCapabilityMcpServers,\n settingsWithSessionMcpServersForRun,\n settingsWithWorkspaceGatewayCredential,\n} from \"./capabilities\";\nimport {\n CODEX_USAGE_EXHAUSTED_PCT,\n authoritativeCodexCapacityResetAt,\n chooseRotationActive,\n classifyCodexPin,\n computeIdleDelayMs,\n computeReactiveRotationResume,\n shardCredentialForSession,\n earliestCodexReset,\n isCodexCredentialEligible,\n selectCodexCredentialLeaseForTurn,\n type CodexRotationStrategy,\n type RotationDecision,\n} from \"./codex-rotation\";\nimport {\n codexFleetShadowDecisionMetricLabelsV1,\n codexFleetShadowErrorMetricLabelsV1,\n publishCodexFleetShadowDecisionV1,\n} from \"./codex-fleet-shadow\";\nimport type { CodexAccountStatus } from \"@opengeni/db\";\nimport { buildCodexTokenResolver } from \"./codex-auth\";\nimport {\n refreshCodexUsageAndRepairCapacityWaiters,\n signalCodexCapacityWakeTargets,\n signalPendingCodexCapacityWakeTargets,\n} from \"./codex-capacity\";\nimport {\n buildModelResolver,\n CODEX_CLIENT_VERSION,\n CODEX_FALLBACK_MODEL_SLUGS,\n CODEX_PROVIDER_ID,\n CodexReloginRequired,\n classifyCodexEncryptedArtifactRejection,\n classifyCodexResponseTimeoutError,\n classifyCodexUsageLimitError,\n codexRequestStorage,\n isCodexTransportError,\n opaqueProviderArtifactFingerprint,\n withCodexRequestOverrides,\n selectCodexCredentialId,\n type CodexRequestContext,\n type CodexUsageHeaderSnapshot,\n} from \"@opengeni/codex\";\nimport { mergeResourceRefs } from \"./common\";\nimport {\n assertSessionAllowsProductModel,\n defaultSessionMcpServerIds,\n directPersonalConnectionSubjectId,\n resolveCodexAppsCredentialIdForRun,\n withFrozenPersonalConnectionDelegations,\n resolveSessionToolPolicy,\n} from \"@opengeni/core\";\nimport { maybeCompactContext, settleFailedContextCompactionLandmark } from \"./context-compaction\";\nimport { TurnAttemptFencedError } from \"./turn-attempt-fenced\";\nimport {\n assertGitCredentialRenewalTransportUnchanged,\n gitCredentialAuthorityForTurn,\n gitHubTokenMintSelections,\n loadWorkspaceEnvironmentForRunWithCredentials,\n mintSandboxToolspaceToken,\n mintRunGitCredentials,\n mintRunGitCredentialBinding,\n sandboxEnvironmentForRun,\n type GitHubTokenMintAuthorization,\n type MintedRunGitCredentials,\n} from \"./environment\";\nimport {\n startGitCredentialRenewalLoop,\n type GitCredentialRenewalController,\n} from \"./git-credential-renewal\";\nimport {\n RUN_CREDENTIAL_EXPIRY_LEAD_MS,\n startRunCredentialRenewalLoop,\n type RunCredentialRenewalController,\n} from \"./run-credential-renewal\";\nimport {\n TOOLSPACE_TOKEN_EXPIRY_LEAD_MS,\n startToolspaceTokenRenewalLoop,\n type ToolspaceTokenRenewalController,\n} from \"./toolspace-token-renewal\";\nimport {\n bindRunCredentialResolver,\n runCredentialAuthNeededPayloads,\n runCredentialModelNote,\n} from \"./run-credentials\";\nimport { withFirstPartyTools } from \"./goals\";\nimport {\n mergeRigDefaultVariableSetEnvironment,\n resolveWorkspaceAgentInstructions,\n resolveWorkspacePackRuntime,\n resolveWorkspaceSkillLibraryRuntime,\n settingsWithPackSandboxImage,\n settingsWithRigImage,\n} from \"./packs\";\nimport { deliverFailedChildTurnToParent } from \"./parent-wake\";\nimport {\n createSecretRedactor,\n isCredentialHeaderName,\n redactSensitiveText,\n type SecretForRedaction,\n} from \"./redaction\";\nimport {\n createModelHistoryAttachmentProjector,\n turnInput,\n type ModelAttachmentInputPolicy,\n} from \"./run-input\";\nimport {\n createRuntimeBatcher,\n currentActivityContext,\n nextStreamEvent,\n startActivityHeartbeat,\n} from \"./streaming\";\nimport type {\n ActivityServices,\n EscapedMcpTimeoutRecoveryDetail,\n RunAgentTurnInput,\n RunAgentTurnResult,\n SessionAttemptQuiescenceProof,\n} from \"./types\";\nimport {\n ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_MESSAGE,\n ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_TYPE,\n} from \"./types\";\nimport {\n resumeBoxForTurn,\n sandboxLeaseHolderIdForAttempt,\n maybePersistWarmWorkspaceSnapshot,\n waitForWarmSnapshot,\n SandboxWarmingTimeoutError,\n type ResumedTurnSandbox,\n type TurnSandboxLeaseHolderId,\n} from \"../sandbox-resume\";\nimport {\n wrapTurnBoxWithRouting,\n wrapLazyTurnBoxWithRouting,\n establishSelfhostedTurnSession,\n routingEnabled,\n lazyProvisionEnabled,\n} from \"../sandbox-routing\";\nimport { makeTurnOpJournal, type TurnHeartbeatDetails } from \"../op-journal\";\nimport {\n makeMachineOpObserver,\n modelCallAccountContext,\n recordBatchFlush,\n recordContextCompaction,\n recordCreditMicros,\n recordModelCacheTokens,\n recordModelInputTokens,\n runtimeMetricsHooksForObservability,\n StreamTimingMetrics,\n turnLifecycleMetricsFor,\n type TurnOutcome,\n} from \"../observability-metrics\";\nimport {\n beginRecording,\n discardUnpublishedRecording,\n prepareRecordingForSettlement,\n type ActiveRecording,\n} from \"./recording\";\nimport { captureWorkspaceRevision, openFreshWorkspaceCaptureSession } from \"./workspace-capture\";\nimport type { ChannelASession } from \"@opengeni/runtime/sandbox\";\nimport { createObjectStorage, type ObjectStorage } from \"@opengeni/storage\";\nimport {\n desktopCapableBackend,\n sandboxRunAs,\n WorkspaceModelPolicyBlockedError,\n} from \"@opengeni/runtime\";\nimport {\n CAPABILITY_DESCRIPTORS,\n DEFAULT_FIRST_PARTY_MCP_TOOLS,\n evaluateWorkspaceModelPolicy,\n readTurnExecutionPolicyV1,\n resourceMountPath,\n type LatencyMode,\n type ResourceRef,\n type SessionEvent,\n type SessionEventType,\n type SessionStatus,\n type SessionTurn,\n type ToolAuthNeededPayload,\n type TurnExecutionPolicyV1,\n} from \"@opengeni/contracts\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\n// Retryable provider connectivity/5xx failures start quickly and back off to\n// this ceiling. Explicit rate limits retain the minute-granular fallback.\nexport const PROVIDER_BACKPRESSURE_DELAY_MS = 60_000;\nconst PROVIDER_CONNECTIVITY_BACKOFF_MS = [2_000, 5_000, 15_000, 30_000, 60_000] as const;\n\n/** Broad personal lookup is allowed only for a direct human/API command. */\nexport function credentialSubjectIdForTurnInitiator(\n turn: Pick<SessionTurn, \"source\" | \"initiator\" | \"initiatorContext\">,\n): string | undefined {\n return directPersonalConnectionSubjectId(turn);\n}\n\n/**\n * Direct authenticated-human work is the persisted human source with subject\n * authority and no inherited agent or legacy provenance. Use this complete\n * immutable turn authority instead of inferring causality from a\n * `user.message` event shape or the root initiator alone.\n */\nexport function isDirectHumanTurnInitiation(\n turn: Pick<SessionTurn, \"source\" | \"initiator\" | \"initiatorContext\">,\n): boolean {\n if ((turn.source !== \"user\" && turn.source !== \"api\") || turn.initiator.kind !== \"subject\") {\n return false;\n }\n return ![\"via\", \"viaTruncated\", \"provenanceError\", \"backfill\"].some((key) =>\n Object.prototype.hasOwnProperty.call(turn.initiatorContext, key),\n );\n}\n\n/**\n * A disconnected personal Slack server is prepared best-effort before the model\n * runs. Its initialize/tools-list credential miss is setup state, not evidence\n * that an unrelated turn wants Slack. Keep concrete tool-call failures\n * actionable, but gate setup-time Slack prompts to a human message that names\n * Slack explicitly. Other providers retain the existing generic behavior.\n */\nexport function shouldPublishToolAuthNeededForTurn(\n payload: Pick<ToolAuthNeededPayload, \"providerDomain\" | \"toolName\">,\n trigger: Pick<SessionEvent, \"type\" | \"payload\">,\n turn: Pick<SessionTurn, \"source\" | \"initiator\" | \"initiatorContext\">,\n): boolean {\n if (typeof payload.toolName === \"string\" && payload.toolName.trim().length > 0) {\n return true;\n }\n const providerDomain = payload.providerDomain.trim().toLowerCase();\n const isSlack = providerDomain === \"slack.com\" || providerDomain.endsWith(\".slack.com\");\n if (!isSlack) {\n return true;\n }\n if (!isDirectHumanTurnInitiation(turn) || trigger.type !== \"user.message\") {\n return false;\n }\n const text = (trigger.payload as { text?: unknown }).text;\n return typeof text === \"string\" && /\\bslack\\b/i.test(text);\n}\n\nexport function turnExecutionPolicyBillingIdentity(policy: TurnExecutionPolicyV1): {\n externallyBilled: boolean;\n codexSubscription: boolean;\n} {\n return {\n externallyBilled: policy.billing.metering === \"external\",\n codexSubscription:\n policy.providerId === \"codex-subscription\" &&\n policy.credentialSource.kind === \"connected_subscription\" &&\n policy.credentialSource.provider === \"codex\",\n };\n}\n\nexport function legacyTurnExecutionPolicyInput(\n turn: Pick<SessionTurn, \"source\" | \"model\" | \"reasoningEffort\" | \"latencyMode\">,\n): Parameters<typeof resolveTurnExecutionPolicyV1>[1] {\n const explicit = turn.source === \"user\" || turn.source === \"api\";\n return {\n modelId: turn.model,\n requestedModelId: explicit ? turn.model : null,\n modelSource: explicit ? \"explicit\" : \"continuation\",\n reasoningEffort: turn.reasoningEffort,\n reasoningSource: explicit ? \"explicit\" : \"continuation\",\n latencyMode: turn.latencyMode,\n latencyModeSource: explicit ? \"explicit\" : \"continuation\",\n };\n}\n\n/** A retryable provider fault recovers the accepted turn itself. Goal state is\n * irrelevant: autonomous continuation and infrastructure recovery are separate\n * concerns. */\nexport function providerRecoveryResult(input: {\n failureCode: string | undefined;\n attemptNumber: number;\n retryAfterMs?: number | null;\n}): {\n status: \"recovering\";\n continueDelayMs: number;\n} {\n const providerDelay =\n input.retryAfterMs !== null &&\n input.retryAfterMs !== undefined &&\n Number.isFinite(input.retryAfterMs) &&\n input.retryAfterMs > 0\n ? Math.ceil(input.retryAfterMs)\n : null;\n const continueDelayMs =\n input.failureCode === \"provider_rate_limited\"\n ? (providerDelay ?? PROVIDER_BACKPRESSURE_DELAY_MS)\n : input.failureCode === \"provider_unavailable\" ||\n input.failureCode === \"upstream_connectivity_unavailable\" ||\n input.failureCode === \"mcp_transport_unavailable\"\n ? Math.max(\n providerDelay ?? 0,\n PROVIDER_CONNECTIVITY_BACKOFF_MS[\n Math.min(\n Math.max(Math.trunc(input.attemptNumber) - 1, 0),\n PROVIDER_CONNECTIVITY_BACKOFF_MS.length - 1,\n )\n ]!,\n )\n : PROVIDER_BACKPRESSURE_DELAY_MS;\n return {\n status: \"recovering\",\n continueDelayMs,\n };\n}\n\nexport function providerRecoveryCountFromMetadata(metadata: Record<string, unknown>): number {\n const value = metadata.providerRecoveryCount;\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 ? value : 0;\n}\n\nfunction headerValue(headers: unknown, name: string): string | null {\n if (!headers || typeof headers !== \"object\") return null;\n const getter = (headers as { get?: unknown }).get;\n if (typeof getter === \"function\") {\n const value = getter.call(headers, name);\n return typeof value === \"string\" ? value : null;\n }\n const target = name.toLowerCase();\n const entry = Object.entries(headers as Record<string, unknown>).find(\n ([key, value]) => key.toLowerCase() === target && typeof value === \"string\",\n );\n return typeof entry?.[1] === \"string\" ? entry[1] : null;\n}\n\n/** Read a provider Retry-After hint without retaining response headers/body. */\nexport function providerRetryAfterMs(error: unknown, nowMs = Date.now()): number | null {\n let current: unknown = error;\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n const value = current as Record<string, unknown>;\n const body =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : null;\n const directSeconds = Number(\n value.retry_after_seconds ?? body?.retry_after_seconds ?? value.retryAfterSeconds,\n );\n const header =\n headerValue(value.headers, \"retry-after\") ??\n headerValue(value.responseHeaders, \"retry-after\") ??\n headerValue(body?.headers, \"retry-after\");\n const headerSeconds = header === null ? Number.NaN : Number(header);\n const headerDate =\n header !== null && !Number.isFinite(headerSeconds) ? Date.parse(header) : Number.NaN;\n const seconds = Number.isFinite(directSeconds)\n ? directSeconds\n : Number.isFinite(headerSeconds)\n ? headerSeconds\n : Number.isFinite(headerDate)\n ? Math.max(0, (headerDate - nowMs) / 1_000)\n : Number.NaN;\n if (Number.isFinite(seconds) && seconds > 0) return Math.ceil(seconds * 1_000);\n current = value.cause;\n }\n return null;\n}\n\n/**\n * Tell the model when durable MCP policy references are unavailable for this\n * exact turn. The policy projection already bounds and validates these ids;\n * this notice prevents a graceful runtime drop from becoming a silent source-\n * of-truth substitution or a false claim that the disconnected system was read.\n */\nexport function unavailableMcpTurnInstructions(input: {\n droppedIds: readonly string[];\n droppedCount: number;\n}): string | undefined {\n if (input.droppedCount <= 0) {\n return undefined;\n }\n const omittedCount = Math.max(0, input.droppedCount - input.droppedIds.length);\n const listed = input.droppedIds.map((id) => `\"${id}\"`).join(\", \");\n const inventory = listed\n ? `${listed}${omittedCount > 0 ? `, plus ${omittedCount} additional unavailable server(s)` : \"\"}`\n : `${input.droppedCount} unavailable server(s)`;\n return `MCP capability availability for this turn: the following session-selected server(s) are disconnected or no longer registered and were skipped: ${inventory}. Do not claim to have read or updated those systems. If the task depends on one as a source of truth, explain the limitation and ask the user to reconnect it or select another authoritative source; continue with unaffected work only when safe.`;\n}\n\n/**\n * Preserve one precise recovery obligation across Temporal's activity boundary.\n * This is intentionally narrower than the ordinary retryable-provider path:\n * only a recovered turn (generation > 1) whose MCP timeout happened before a\n * model request may ask the workflow's DB-only control activity to finish the\n * same-turn checkpoint. The original transport/recovery errors are excluded\n * from details so raw MCP response data can never enter workflow history.\n */\nexport function escapedMcpTimeoutRecoveryFailure(input: {\n failureCode: string | undefined;\n modelRequestStarted: boolean;\n detail: EscapedMcpTimeoutRecoveryDetail;\n}): ApplicationFailure | null {\n if (\n input.failureCode !== \"mcp_transport_timeout\" ||\n input.modelRequestStarted ||\n !Number.isSafeInteger(input.detail.executionGeneration) ||\n input.detail.executionGeneration <= 1\n ) {\n return null;\n }\n return ApplicationFailure.create({\n message: ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_MESSAGE,\n type: ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_TYPE,\n nonRetryable: true,\n details: [input.detail],\n });\n}\n\n/**\n * Resolve which Codex account a turn runs on (multi-account P1): session-pin >\n * workspace-active. No rotation in P1. The selected id must still be in the\n * connected set — a disconnected pin was FK-nulled, so a stale id can't appear,\n * but we guard anyway. Returns null when there is no usable account (the turn\n * then fails with the existing relogin error path).\n */\nexport function selectCodexCredentialForTurn(args: {\n sessionPinnedCredentialId: string | null;\n activeCredentialId: string | null;\n connectedIds: Set<string>;\n}): string | null {\n return selectCodexCredentialId(args);\n}\n\nexport function filterUnmaterializedSandboxFileDownloads(\n downloads: SandboxFileDownload[],\n materializedFileIds: Set<string>,\n): SandboxFileDownload[] {\n if (downloads.length === 0 || materializedFileIds.size === 0) {\n return downloads;\n }\n return downloads.filter((download) => !materializedFileIds.has(download.fileId));\n}\n\n/** Fixed-length one-way tenant correlation for metrics/alerts; never a raw id. */\nexport function codexWorkspaceMetricKey(workspaceId: string): string {\n return createHash(\"sha256\").update(workspaceId).digest(\"hex\").slice(0, 12);\n}\n\n/** Stable public request identity across partial resumes and activity retries. */\nexport function stableHumanInputRequestId(\n sessionId: string,\n turnId: string,\n toolCallId: string,\n): string {\n const hex = createHash(\"sha256\")\n .update(\"opengeni-human-input-v1\\0\")\n .update(sessionId)\n .update(\"\\0\")\n .update(turnId)\n .update(\"\\0\")\n .update(toolCallId)\n .digest(\"hex\")\n .slice(0, 32)\n .split(\"\");\n hex[12] = \"5\";\n hex[16] = [\"8\", \"9\", \"a\", \"b\"][Number.parseInt(hex[16] ?? \"0\", 16) % 4] ?? \"8\";\n const value = hex.join(\"\");\n return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;\n}\n\n/**\n * True when this activity attempt was cancelled because its hosting worker is\n * shutting down gracefully (SIGTERM during a deploy), as opposed to a\n * workflow-requested Pause/Steer cancellation or a server-side timeout.\n */\nexport function isWorkerShutdownCancellation(error: unknown): boolean {\n return error instanceof CancelledFailure && error.message === \"WORKER_SHUTDOWN\";\n}\n\n/**\n * Review captures and protective snapshots are cache/persistence housekeeping,\n * never part of cancellation correctness. A control-fenced or Temporal-cancelled\n * attempt must release its physical activity promptly so Steer/Pause can advance.\n */\nexport function shouldRunTurnEndWorkspacePersistence(input: {\n activityStatus: RunAgentTurnResult[\"status\"] | \"unknown\";\n cancellationRequested: boolean;\n}): boolean {\n return input.activityStatus !== \"cancelled\" && !input.cancellationRequested;\n}\n\n/**\n * Temporal cancellation is delivery/transport state, never proof that the\n * dying activity crossed its mandatory sandbox-tool fence. If that fence\n * fails, surface the fence failure instead of retaining a misleading typed\n * cancellation; replacement admission remains closed because no durable\n * quiescence receipt was written.\n */\nexport function assertPhysicalToolQuiescenceForCancellation(input: {\n acknowledgeQuiescence: boolean;\n physicalToolQuiescenceConfirmed: boolean;\n failure: unknown;\n}): void {\n if (!input.acknowledgeQuiescence || input.physicalToolQuiescenceConfirmed) return;\n if (input.failure instanceof Error) throw input.failure;\n throw new Error(\"Physical sandbox-tool quiescence could not be confirmed\", {\n cause: input.failure,\n });\n}\n\n/** A physically drained attempt must leave one durable recovery producer. The\n * direct Postgres receipt is preferred; after its bounded retries exhaust, an\n * exact Temporal proof signal is sufficient because the workflow persists it\n * through an independently retrying DB-only control activity. */\nexport function assertSessionAttemptQuiescenceRecoveryDurable(input: {\n acknowledgeQuiescence: boolean;\n physicalToolQuiescenceConfirmed: boolean;\n receiptOrProofDurable: boolean;\n failure: unknown;\n}): void {\n if (\n !input.acknowledgeQuiescence ||\n !input.physicalToolQuiescenceConfirmed ||\n input.receiptOrProofDurable\n ) {\n return;\n }\n if (input.failure instanceof Error) throw input.failure;\n throw new Error(\"Physical quiescence had no durable receipt or recovery proof\", {\n cause: input.failure,\n });\n}\n\nconst QUIESCENCE_PROOF_SIGNAL_INITIAL_RETRY_MS = 250;\nconst QUIESCENCE_PROOF_SIGNAL_MAX_RETRY_MS = 5_000;\n\n/** Persist the authoritative receipt or durably hand the exact physical proof\n * to Temporal. This retries signal delivery, not DB eligibility or workflow\n * state. The proof object never changes between attempts. */\nexport async function persistOrSignalSessionAttemptQuiescence(input: {\n proof: SessionAttemptQuiescenceProof;\n persistReceipt: () => Promise<SessionEvent[]>;\n publishEvents: (events: SessionEvent[]) => Promise<unknown>;\n signalProof: ActivityServices[\"signalSessionAttemptQuiesced\"];\n sleep?: (ms: number) => Promise<void>;\n heartbeat?: (attempt: number, delayMs: number) => void;\n onReceiptFailure?: (error: unknown) => void;\n onPublishFailure?: (error: unknown) => void;\n onSignalFailure?: (error: unknown, attempt: number, delayMs: number) => void;\n}): Promise<\"receipt\" | \"signal\"> {\n let events: SessionEvent[];\n try {\n events = await input.persistReceipt();\n } catch (receiptError) {\n input.onReceiptFailure?.(receiptError);\n if (!input.signalProof) {\n throw new Error(\"Session-attempt quiescence proof signaler is unavailable\", {\n cause: receiptError,\n });\n }\n const delay = input.sleep ?? sleep;\n let retryMs = QUIESCENCE_PROOF_SIGNAL_INITIAL_RETRY_MS;\n let attempt = 1;\n for (;;) {\n try {\n await input.signalProof(input.proof);\n return \"signal\";\n } catch (signalError) {\n input.onSignalFailure?.(signalError, attempt, retryMs);\n try {\n input.heartbeat?.(attempt, retryMs);\n } catch {\n // Heartbeat telemetry is not proof delivery and cannot replace or\n // interrupt the exact signal retry loop.\n }\n await delay(retryMs);\n retryMs = Math.min(retryMs * 2, QUIESCENCE_PROOF_SIGNAL_MAX_RETRY_MS);\n attempt += 1;\n }\n }\n }\n\n try {\n await input.publishEvents(events);\n } catch (publishError) {\n // Postgres already committed quiesced_at, the queue event, and the wake.\n // NATS is live fanout only; never misclassify its failure as receipt loss.\n input.onPublishFailure?.(publishError);\n }\n return \"receipt\";\n}\n\n/**\n * Cross the non-detachable physical boundary for one dying attempt. Temporal's\n * cancellation signal is intentionally absent: cancellation is transport, not\n * proof that sandbox tools and attempt-owned credential writers have drained.\n * A replacement may be admitted only after this function resolves and the\n * caller durably persists or signals the exact quiescence receipt.\n */\nexport async function drainAttemptOwnedSandboxWriters(input: {\n toolCancellationFence: Pick<TurnToolCancellationFence, \"cancel\" | \"waitForQuiescence\"> | null;\n cancellationReason?: unknown;\n gitCredentialRenewals: readonly Pick<GitCredentialRenewalController, \"stop\">[];\n toolspaceTokenRenewal: Pick<ToolspaceTokenRenewalController, \"stop\"> | null;\n runCredentialRenewal: Pick<RunCredentialRenewalController, \"stop\"> | null;\n}): Promise<void> {\n if (input.toolCancellationFence) {\n input.toolCancellationFence.cancel(\n input.cancellationReason ?? new Error(\"TURN_ATTEMPT_FENCED\"),\n );\n await input.toolCancellationFence.waitForQuiescence();\n }\n await Promise.all(input.gitCredentialRenewals.map(async (renewal) => await renewal.stop()));\n await input.toolspaceTokenRenewal?.stop();\n await input.runCredentialRenewal?.stop();\n}\n\n/**\n * Await a finalizer operation only while this Temporal activity still owns its\n * execution window. Once Pause/Steer cancellation arrives, the operation keeps\n * its own rejection handler and may finish its idempotent, attempt-scoped\n * cleanup in the background, but it cannot pin activity terminalization or\n * delay the separately receipt-gated replacement dispatch.\n */\nexport async function waitForTurnFinalizerStep<T>(\n operation: Promise<T>,\n signal: AbortSignal | undefined,\n): Promise<T | undefined> {\n if (!signal) return await operation;\n if (signal.aborted) {\n void operation.catch(() => undefined);\n return undefined;\n }\n\n let resolveCancellation: (() => void) | undefined;\n const cancelled = new Promise<undefined>((resolve) => {\n resolveCancellation = () => resolve(undefined);\n });\n const cancel = (): void => {\n void operation.catch(() => undefined);\n resolveCancellation?.();\n };\n signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n return await Promise.race([operation, cancelled]);\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n }\n}\n\n/**\n * Flush provider-facing stream state while the attempt still owns its activity\n * window. On Pause/Steer, both promises are detached with rejection handlers:\n * neither a runtime batcher nor an uncooperative provider completion promise\n * may pin the activity behind cancellation after durable writes are fenced.\n */\nexport async function waitForTurnStreamCleanup(\n batcherFlush: Promise<unknown>,\n providerCompleted: Promise<unknown>,\n signal: AbortSignal | undefined,\n): Promise<void> {\n await waitForTurnFinalizerStep(batcherFlush, signal);\n await waitForTurnFinalizerStep(providerCompleted, signal);\n}\n\nfunction turnFinalizerCancellationSignal(\n temporalSignal: AbortSignal | undefined,\n activityStatus: RunAgentTurnResult[\"status\"] | \"unknown\",\n): AbortSignal | undefined {\n if (activityStatus !== \"cancelled\" || temporalSignal?.aborted) return temporalSignal;\n const fenced = new AbortController();\n fenced.abort(new Error(\"TURN_ATTEMPT_FENCED\"));\n return fenced.signal;\n}\n\nfunction compactionFailureReason(reason: string): string {\n return reason.startsWith(\"compaction summarization failed:\")\n ? reason\n : `compaction summarization failed: ${reason}`;\n}\n\nexport type SafeErrorDiagnostic = {\n name: string;\n message: string;\n status?: number;\n code?: string;\n};\n\n/**\n * Produce the only exception shape allowed in worker logs. It deliberately\n * excludes stack, cause, response/request bodies, and arbitrary enumerable\n * properties while retaining bounded, redacted diagnostics.\n */\nexport function safeErrorDiagnostic(\n error: unknown,\n redactText: (value: string) => string = redactSensitiveText,\n): SafeErrorDiagnostic {\n const rawName = error instanceof Error ? error.name : \"Error\";\n const name = /^[A-Za-z][A-Za-z0-9_.-]{0,79}$/.test(rawName) ? rawName : \"Error\";\n const rawMessage = error instanceof Error ? error.message : String(error);\n const diagnostic: SafeErrorDiagnostic = {\n name,\n message: redactText(rawMessage).slice(0, 2_048),\n };\n if (error && typeof error === \"object\") {\n const status = Number(\n (error as { status?: unknown; statusCode?: unknown }).status ??\n (error as { statusCode?: unknown }).statusCode,\n );\n if (Number.isInteger(status) && status >= 100 && status <= 599) {\n diagnostic.status = status;\n }\n const rawCode = (error as { code?: unknown }).code;\n if (typeof rawCode === \"string\" || typeof rawCode === \"number\") {\n const code = redactText(String(rawCode)).slice(0, 80);\n if (/^[A-Za-z0-9_.:-]+$/.test(code)) diagnostic.code = code;\n }\n }\n return diagnostic;\n}\n\nfunction safeErrorForTelemetry(error: unknown, redactText: (value: string) => string): Error {\n const diagnostic = safeErrorDiagnostic(error, redactText);\n const safe = new Error(diagnostic.message);\n safe.name = diagnostic.name;\n return safe;\n}\n\nexport function headerSecretRedactions(\n prefix: string,\n headers: Readonly<Record<string, string>> | undefined,\n credentialHeaderNames?: Iterable<string>,\n): SecretForRedaction[] {\n const discovered: SecretForRedaction[] = [];\n const explicitCredentialHeaders = credentialHeaderNames\n ? new Set([...credentialHeaderNames].map((name) => name.toLowerCase()))\n : null;\n for (const [headerName, value] of Object.entries(headers ?? {})) {\n if (\n !explicitCredentialHeaders?.has(headerName.toLowerCase()) &&\n !isCredentialHeaderName(headerName)\n ) {\n continue;\n }\n const safeHeaderName = headerName.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\");\n discovered.push({ name: `${prefix}_${safeHeaderName || \"HEADER\"}`, value });\n if (/^(?:proxy-)?authorization$/i.test(headerName)) {\n const credential = value.match(/^\\s*[A-Za-z][A-Za-z0-9_-]*\\s+(.+)\\s*$/)?.[1];\n if (credential) {\n discovered.push({\n name: `${prefix}_${safeHeaderName || \"AUTHORIZATION\"}_CREDENTIAL`,\n value: credential,\n });\n }\n }\n }\n return discovered;\n}\n\nfunction compactionFailureReasonFromError(error: unknown): string {\n if (\n error instanceof CompactionProviderResponseError ||\n error instanceof EmptyCompactionSummaryError\n ) {\n return compactionFailureReason(error.message);\n }\n const errorName = error instanceof Error && error.name ? error.name : \"unknown error\";\n return compactionFailureReason(`unexpected ${errorName}`);\n}\n\nfunction isCompactionSummaryFailure(error: unknown): boolean {\n return (\n error instanceof CompactionProviderResponseError || error instanceof EmptyCompactionSummaryError\n );\n}\n\nexport function shouldRecoverCompactionProviderFailure(error: unknown): boolean {\n if (!(error instanceof CompactionProviderResponseError)) return false;\n if (isCodexTransportError(error) && classifyCodexUsageLimitError(error)) return true;\n return agentRunFailurePayload(error).retryable === true;\n}\n\nexport function classifyContextWindowOverflowError(\n error: unknown,\n): { message: string; code?: string; detail?: string } | null {\n const fields = collectErrorStrings(error);\n const matched = fields.find(\n (value) =>\n /context[_\\s-]*length[_\\s-]*exceeded/i.test(value) ||\n /exceeds?\\s+(?:the\\s+)?context\\s+window/i.test(value) ||\n /maximum\\s+context\\s+length/i.test(value) ||\n /context\\s+window[^.]*exceed/i.test(value),\n );\n if (!matched) {\n return null;\n }\n const message = error instanceof Error ? error.message : String(error);\n const code = fields.find((value) => /context[_\\s-]*length[_\\s-]*exceeded/i.test(value));\n return {\n message,\n ...(code ? { code } : {}),\n ...(matched && matched !== message ? { detail: matched } : {}),\n };\n}\n\n/**\n * Recognize an MCP transport/request timeout that escaped the SDK's per-tool\n * `mcpConfig.errorFunction` boundary. A thrown tool invocation is normally\n * converted to an `{isError:true}` tool output; however, connect/tools-list or\n * next-loop transport work can reject the stream iterator after a prior tool\n * output was already published. That is transient external backpressure, not a\n * terminal session error. Match MCP-qualified timeout text only: an unrelated\n * sandbox/model timeout and MCP's application-defined Authentication required signal must\n * retain their existing semantics.\n */\nexport function classifyMcpTransportTimeoutError(\n error: unknown,\n): { message: string; detail?: string } | null {\n const fields = collectErrorStrings(error);\n const matchedText = fields.find(\n (value) =>\n /\\bmcp\\b/i.test(value) &&\n /(?:request\\s+timed\\s+out|request\\s+timeout|\\btimed\\s+out\\b|\\btimeout\\b|ETIMEDOUT)/i.test(\n value,\n ) &&\n !/authentication\\s+required/i.test(value),\n );\n const sanitizedSdkTimeout = isMcpRequestTimeoutError(error);\n if (!matchedText && !sanitizedSdkTimeout) {\n return null;\n }\n const message = error instanceof Error ? error.message : String(error);\n const matched = matchedText ?? fields.find((value) => /\\bmcp\\b/i.test(value));\n return {\n message,\n ...(matched && matched !== message ? { detail: matched } : {}),\n };\n}\n\nfunction collectErrorStrings(value: unknown, seen = new WeakSet<object>()): string[] {\n if (typeof value === \"string\") {\n return [value];\n }\n if (!value || typeof value !== \"object\") {\n return [];\n }\n if (seen.has(value)) {\n return [];\n }\n seen.add(value);\n const out: string[] = [];\n const record = value as Record<string, unknown>;\n for (const key of [\"message\", \"code\", \"type\", \"name\", \"param\"]) {\n const field = record[key];\n if (typeof field === \"string\" && field.length > 0) {\n out.push(field);\n }\n }\n for (const key of [\"error\", \"cause\", \"response\", \"data\"]) {\n out.push(...collectErrorStrings(record[key], seen));\n }\n return out;\n}\n\n/**\n * Compute the conversation-truth rows a reconcile pass should append, given the\n * SDK's current `state.history` and the count already persisted.\n *\n * `state.history` is a computed getter that runs the SDK's orphan-tool-call\n * pruning on every access, so it is non-monotonic: a `function_call` with no\n * settling result yet is transiently absent and a later access yields a\n * different, possibly shorter/reordered list. The old code sliced this list by\n * a blind length watermark and appended at fixed positions with\n * onConflictDoNothing, which could freeze a position with one shape and later\n * persist a `function_call_result` whose `function_call` had been pruned away in\n * an earlier slice — the orphaned tool output that 400s the Responses API and\n * bricks the session on every replay.\n *\n * Defending: sanitize the full current history into an API-valid sequence (the\n * same pure rules the read path uses), then append only the new tail beyond the\n * watermark. A trailing dangling call is dropped here and re-evaluated next\n * pass once its result lands, so a call and its result are written together at\n * consecutive positions and a result is never persisted without its call. The\n * watermark advances to the sanitized length — never past anything unwritten —\n * so a non-monotonic history can never desync it. When previously-persisted\n * rows already exceed the sanitized length (e.g. legacy orphans written before\n * this fix), nothing new is appended and the watermark holds steady.\n */\n/**\n * Stable+unique usage source key for one model call, used to build the per-call\n * idempotency key (`usage:model.tokens:${turnId}:${sourceKey}`). The turnId is\n * shared across a new attempt of the SAME turn (recovery, approval\n * rerun, activity retry), so the sourceKey alone must distinguish calls.\n *\n * - A provider responseId is globally stable+unique, so reuse it verbatim: a\n * true activity retry that re-emits the same responseId correctly DEDUPES\n * (one charge), while two distinct calls get distinct ids.\n * - Without a responseId the old synthesized key was only POSITIONAL (\"response-1\",\n * \"aggregate\"), which collides across a re-dispatch — dispatch B's first\n * call reuses dispatch A's \"response-1\" key and its charge is silently\n * dropped (undercharge). Qualifying the synthesized key with the\n * per-execution dispatch id (the Temporal activityId, unique per scheduled\n * execution) makes re-dispatched calls distinct while still deduping a\n * same-execution retry.\n */\nexport function modelUsageSourceKey(input: {\n responseId?: string | null | undefined;\n dispatchId: string | null;\n positionalKey: string;\n}): string {\n if (input.responseId) {\n return input.responseId;\n }\n return input.dispatchId ? `${input.dispatchId}:${input.positionalKey}` : input.positionalKey;\n}\n\nexport function providerContextTokens(\n usage:\n | {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n }\n | null\n | undefined,\n): number | null {\n const total = normalizeModelCallUsage(usage).totalTokens;\n return total !== null && total > 0 ? total : null;\n}\n\n/**\n * A provider call has already consumed tokens by the time its usage frame is\n * available. Losing the Codex credential lease at the renewal checkpoint must\n * stop the result from becoming authoritative, but it must not erase accounting\n * truth for the call that already happened. Meter first, then surface the lost\n * lease, then write attempt-owned token/context signals. A replaced attempt can\n * reject those signals without erasing the provider usage already incurred.\n */\nexport async function recordCompletedModelCallBeforeOwnershipFences(input: {\n renewLease: () => Promise<void>;\n recordUsage: () => Promise<void>;\n leaseLost: () => boolean;\n leaseLostMessage: string;\n recordAttemptSignals?: () => Promise<void>;\n}): Promise<void> {\n await input.renewLease();\n await input.recordUsage();\n if (input.leaseLost()) {\n throw new Error(input.leaseLostMessage);\n }\n await input.recordAttemptSignals?.();\n}\n\ntype TurnEventPublisher = (\n events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>,\n immediate?: boolean,\n) => Promise<{ events: SessionEvent[]; accepted: boolean }>;\n\nexport type ModelResponseEventState = {\n responseCount: number;\n contextSignal: { revision: number; totalTokens: number } | null;\n claimedSourceKeys: Set<string>;\n};\n\nexport type CompactionModelUsageEventState = {\n usageCount: number;\n claimedSourceKeys: Set<string>;\n};\n\nexport function createModelResponseEventState(\n claimedSourceKeys: Set<string> = new Set<string>(),\n): ModelResponseEventState {\n return {\n responseCount: 0,\n contextSignal: null,\n claimedSourceKeys,\n };\n}\n\nexport function createCompactionModelUsageEventState(\n claimedSourceKeys: Set<string> = new Set<string>(),\n): CompactionModelUsageEventState {\n return { usageCount: 0, claimedSourceKeys };\n}\n\nexport function modelResponseContextSignal(\n state: ModelResponseEventState,\n): { revision: number; totalTokens: number } | null {\n return state.contextSignal;\n}\n\nexport function assertModelResponseLatencyMode(input: {\n event: Parameters<typeof modelResponseServiceTierFromSdkEvent>[0];\n requested: LatencyMode;\n model: string;\n /** When set to Codex ChatGPT auth, response `service_tier` is not an honor signal. */\n providerId?: string;\n}): void {\n if (input.requested === \"standard\") {\n return;\n }\n // ChatGPT-auth Codex (subscription): Fast maps to request `service_tier=priority`\n // (see openai/codex ServiceTier::Fast.request_value). The backend may still return\n // `response.service_tier=default`; OpenAI maintainers document that this does not\n // mean Fast was ignored. Native CLI also does not fail closed on that field.\n if (input.providerId === CODEX_PROVIDER_ID) {\n return;\n }\n const serviceTierEvent = modelResponseServiceTierFromSdkEvent(input.event);\n if (\n !serviceTierEvent ||\n (serviceTierEvent.source === \"normalized\" && serviceTierEvent.serviceTier === null)\n ) {\n return;\n }\n if (!responseSatisfiesLatencyMode(input.requested, serviceTierEvent.serviceTier)) {\n throw new Error(\n `Provider did not honor ${input.requested} latency mode for ${input.model}: response service_tier=${serviceTierEvent.serviceTier ?? \"missing\"}`,\n );\n }\n}\n\n/**\n * Process one SDK terminal-response event through the production authority path.\n *\n * The pinned Responses SDK mirrors one provider terminal response as both a\n * normalized `response_done` and a raw `model/response.completed` event. Claim\n * the stable response/source key before lease renewal or any side effect, and\n * use that one positional ordinal for both response identity and same-run\n * context binding. A response without usage still clears attempt-owned token\n * state. When usage exists, the durable `agent.model.usage` source-key fence\n * remains the cross-restart authority: a replay may retry the idempotent billing\n * write, but it cannot advance metrics, context, or attempt-owned signals.\n */\nexport async function processModelResponseTerminalEvent(input: {\n event: Parameters<typeof modelTerminalResponseFromSdkEvent>[0];\n state: ModelResponseEventState;\n dispatchId: string | null;\n settings: Settings;\n db: ActivityServices[\"db\"];\n observability: ActivityServices[\"observability\"];\n publish: TurnEventPublisher | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n latencyMode?: LatencyMode;\n metricProvider: string;\n externallyBilled: boolean;\n servingCredentialId: string | null;\n priorSessionCredentialId: string | null;\n emittedSourceKeys: Set<string>;\n renewLease: () => Promise<void>;\n leaseLost: () => boolean;\n leaseLostMessage: string;\n setLastInputTokens: (tokens: number | null) => Promise<void>;\n}): Promise<\n | { status: \"not_response\" }\n | { status: \"duplicate\"; sourceKey: string }\n | {\n status: \"processed\";\n sourceKey: string;\n authoritative: boolean;\n usageReported: boolean;\n }\n> {\n const terminal = modelTerminalResponseFromSdkEvent(input.event);\n if (!terminal) {\n return { status: \"not_response\" };\n }\n\n const responseOrdinal = input.state.responseCount + 1;\n const sourceKey = modelUsageSourceKey({\n responseId: terminal.responseId,\n dispatchId: input.dispatchId,\n positionalKey: `response-${responseOrdinal}`,\n });\n if (input.state.claimedSourceKeys.has(sourceKey)) {\n return { status: \"duplicate\", sourceKey };\n }\n input.state.claimedSourceKeys.add(sourceKey);\n input.state.responseCount = responseOrdinal;\n\n const responseUsage = terminal.usage;\n\n const normalizedUsage = normalizeModelCallUsage(responseUsage?.usage);\n const accountContext = modelCallAccountContext({\n servingCredentialId: input.servingCredentialId,\n priorSessionCredentialId: input.priorSessionCredentialId,\n isFirstCallOfTurn: responseOrdinal === 1,\n });\n // A terminal response without usage still authoritatively replaces the\n // attempt-owned context signal. There is simply no billing event to claim.\n let authoritative = responseUsage === null;\n await recordCompletedModelCallBeforeOwnershipFences({\n renewLease: input.renewLease,\n leaseLost: input.leaseLost,\n leaseLostMessage: input.leaseLostMessage,\n recordUsage: async () => {\n if (!responseUsage) return;\n const billing = await recordModelUsageAndDebitCredits(input.settings, input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n model: input.model,\n externallyBilled: input.externallyBilled,\n usage: responseUsage.usage,\n normalizedUsage,\n gatewayManaged: input.provider === OPENGENI_GATEWAY_PROVIDER_ID,\n gatewayBilling: responseUsage.gatewayBilling,\n sourceKey,\n ...(input.latencyMode ? { latencyMode: input.latencyMode } : {}),\n observability: input.observability,\n });\n authoritative = await emitModelCallUsage({\n observability: input.observability,\n publish: input.publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n sourceKey,\n usage: responseUsage,\n normalizedUsage,\n servingAccountHash: accountContext.servingAccountHash,\n accountChangedFromPrevCall: accountContext.accountChangedFromPrevCall,\n emittedSourceKeys: input.emittedSourceKeys,\n });\n if (authoritative && billing) {\n await recordAuthoritativeModelCallFact({\n db: input.db,\n observability: input.observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n sourceKey,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n billing,\n });\n }\n const observedInput = normalizedUsage.telemetry.inputTokens;\n if (authoritative && observedInput !== null && observedInput > 0) {\n recordModelInputTokens(input.observability, input.metricProvider, observedInput);\n }\n },\n recordAttemptSignals: async () => {\n if (!authoritative) return;\n const observedTotal = normalizedUsage.totalTokens;\n input.state.contextSignal =\n observedTotal !== null && observedTotal > 0\n ? { revision: responseOrdinal, totalTokens: observedTotal }\n : null;\n const observedInput = normalizedUsage.telemetry.inputTokens;\n await input.setLastInputTokens(\n observedInput !== null && observedInput > 0 ? observedInput : null,\n );\n },\n });\n return {\n status: \"processed\",\n sourceKey,\n authoritative,\n usageReported: responseUsage !== null,\n };\n}\n\n/**\n * Apply the same source-key authority ordering to the compaction summarizer's\n * usage callback. The summarizer can retry or mirror a terminal response just\n * like the main stream, so claim before lease renewal, billing, durable usage,\n * logging, or cache metrics. Durable source-key idempotency remains the\n * cross-process authority after a worker restart.\n */\nexport async function processCompactionModelUsageEvent(input: {\n usage: ModelResponseUsage;\n state: CompactionModelUsageEventState;\n dispatchId: string | null;\n settings: Settings;\n db: ActivityServices[\"db\"];\n observability: ActivityServices[\"observability\"];\n publish: TurnEventPublisher | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n externallyBilled: boolean;\n servingCredentialId: string | null;\n priorSessionCredentialId: string | null;\n emittedSourceKeys: Set<string>;\n renewLease: () => Promise<void>;\n leaseLost: () => boolean;\n leaseLostMessage: string;\n}): Promise<\n | { status: \"duplicate\"; sourceKey: string }\n | { status: \"processed\"; sourceKey: string; authoritative: boolean }\n> {\n const usageOrdinal = input.state.usageCount + 1;\n const sourceKey = modelUsageSourceKey({\n responseId: input.usage.responseId,\n dispatchId: input.dispatchId,\n positionalKey: `compaction-${usageOrdinal}`,\n });\n if (input.state.claimedSourceKeys.has(sourceKey)) {\n return { status: \"duplicate\", sourceKey };\n }\n input.state.claimedSourceKeys.add(sourceKey);\n input.state.usageCount = usageOrdinal;\n\n const accountContext = modelCallAccountContext({\n servingCredentialId: input.servingCredentialId,\n priorSessionCredentialId: input.priorSessionCredentialId,\n isFirstCallOfTurn: usageOrdinal === 1,\n });\n const normalizedUsage = normalizeModelCallUsage(input.usage.usage);\n let authoritative = false;\n await recordCompletedModelCallBeforeOwnershipFences({\n renewLease: input.renewLease,\n leaseLost: input.leaseLost,\n leaseLostMessage: input.leaseLostMessage,\n recordUsage: async () => {\n const billing = await recordModelUsageAndDebitCredits(input.settings, input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n model: input.model,\n externallyBilled: input.externallyBilled,\n usage: input.usage.usage,\n normalizedUsage,\n gatewayManaged: input.provider === OPENGENI_GATEWAY_PROVIDER_ID,\n gatewayBilling: input.usage.gatewayBilling,\n sourceKey,\n observability: input.observability,\n });\n authoritative = await emitModelCallUsage({\n observability: input.observability,\n publish: input.publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n sourceKey,\n usage: input.usage,\n normalizedUsage,\n servingAccountHash: accountContext.servingAccountHash,\n accountChangedFromPrevCall: accountContext.accountChangedFromPrevCall,\n emittedSourceKeys: input.emittedSourceKeys,\n });\n if (authoritative && billing) {\n await recordAuthoritativeModelCallFact({\n db: input.db,\n observability: input.observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n sourceKey,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n billing,\n });\n }\n },\n });\n return { status: \"processed\", sourceKey, authoritative };\n}\n\nexport async function emitModelCallUsage(input: {\n observability: ActivityServices[\"observability\"];\n publish: TurnEventPublisher | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n sourceKey: string;\n usage: ModelResponseUsage | { usage?: unknown | null } | null;\n normalizedUsage?: ModelCallUsageNormalization;\n // Prompt-cache research dimensions (log-only; NEVER on a metric label or a\n // durable event). The opaque serving-account tag and whether it changed since\n // the session's previous call — the account-switch hypothesis for cache misses.\n servingAccountHash?: string;\n accountChangedFromPrevCall?: boolean;\n emittedSourceKeys?: Set<string>;\n}): Promise<boolean> {\n const usage =\n input.usage && typeof input.usage === \"object\" && \"usage\" in input.usage\n ? (input.usage as { usage?: unknown }).usage\n : null;\n if (!usage || typeof usage !== \"object\") {\n return false;\n }\n if (input.emittedSourceKeys?.has(input.sourceKey)) return false;\n const normalizedUsage =\n input.normalizedUsage ?? normalizeModelCallUsage(usage as ModelCallUsageInput);\n const telemetry = normalizedUsage.telemetry;\n const appended = await input.publish?.(\n [\n {\n type: \"agent.model.usage\",\n payload: {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n sourceKey: input.sourceKey,\n ...telemetry,\n },\n },\n ],\n true,\n );\n input.emittedSourceKeys?.add(input.sourceKey);\n const authoritative = appended?.events.some(\n (event) =>\n event.type === \"agent.model.usage\" &&\n event.turnAssociation === \"current\" &&\n event.payload !== null &&\n typeof event.payload === \"object\" &&\n (event.payload as Record<string, unknown>).sourceKey === input.sourceKey,\n );\n if (!authoritative) return false;\n try {\n input.observability.info(\"model call usage\", {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n sourceKey: input.sourceKey,\n inputTokens: telemetry.inputTokens,\n outputTokens: telemetry.outputTokens,\n cachedTokens: telemetry.cachedTokens,\n cacheWriteTokens: telemetry.cacheWriteTokens,\n reasoningTokens: telemetry.reasoningTokens,\n ...(input.servingAccountHash !== undefined\n ? { servingAccountHash: input.servingAccountHash }\n : {}),\n ...(input.accountChangedFromPrevCall !== undefined\n ? { accountChangedFromPrevCall: input.accountChangedFromPrevCall }\n : {}),\n });\n if (normalizedUsage.rejectedFields.length > 0) {\n input.observability.warn(\"model call usage fields rejected\", {\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n sourceKey: input.sourceKey,\n rejectedFields: normalizedUsage.rejectedFields.join(\",\"),\n });\n }\n } catch {\n // Durable event + billing already committed; logging is best-effort only.\n }\n try {\n applyCodexCacheTelemetry(input.observability, input.provider, normalizedUsage);\n } catch {\n // Durable event + billing already committed; metrics are best-effort only.\n }\n return true;\n}\n\n/**\n * Apply one authoritative, normalized model-call usage frame to the shared\n * prompt-cache metrics. The durable source-key fence in `emitModelCallUsage`\n * owns idempotency; this helper must never receive raw provider values.\n */\nexport function applyCodexCacheTelemetry(\n observability: ActivityServices[\"observability\"],\n provider: string,\n normalizedUsage: ModelCallUsageNormalization,\n): void {\n recordModelCacheTokens(observability, provider, {\n cachedTokens: normalizedUsage.telemetry.cachedTokens,\n cacheWriteTokens: normalizedUsage.telemetry.cacheWriteTokens,\n promptTokens: normalizedUsage.telemetry.inputTokens,\n });\n}\n\nexport function historyRowsToAppend(\n rawHistory: Array<Record<string, unknown>>,\n // How many items of the CURRENT in-memory history are already persisted (the\n // slice index into `sanitized`). This is the in-memory history length, NOT the\n // total persisted-row count: after a compaction the in-memory history is the\n // short [summary, ...tail, ...new] list, far shorter than the total rows in\n // the table (which still hold the superseded prefix).\n persistedHistoryCount: number,\n // Next free WHOLE-NUMBER absolute position to write at. Decoupled from the\n // slice index because compaction inserts a fractional summary position, so the\n // total-row count no longer equals max(position)+1. Defaults to\n // persistedHistoryCount to preserve the pre-compaction behaviour (contiguous\n // positions from 0) when callers do not pass an explicit next position.\n nextPosition: number = persistedHistoryCount,\n toolOutputTruncationTokens?: number,\n redactValue: (value: unknown) => unknown = (value) => value,\n): {\n rows: Array<{ position: number; item: Record<string, unknown> }>;\n nextWatermark: number;\n nextPosition: number;\n} {\n const sanitized = sanitizeHistoryItemsForModel(rawHistory, toolOutputTruncationTokens).map(\n (item) => redactValue(item) as Record<string, unknown>,\n );\n if (sanitized.length <= persistedHistoryCount) {\n return { rows: [], nextWatermark: persistedHistoryCount, nextPosition };\n }\n // Canonical model-facing inputs (including machine-input batches) are\n // persisted before inference and therefore live inside the prefix represented\n // by persistedHistoryCount. System messages synthesized only for this\n // attempt—recovery diagnostics, credential notices, attachment materialization\n // notes—must not accidentally become conversation memory during reconciliation.\n // Advance the in-memory watermark past them, but only allocate durable\n // positions to actual model/tool output.\n const rows = sanitized\n .slice(persistedHistoryCount)\n .filter((item) => !(item.type === \"message\" && item.role === \"system\"))\n .map((item, offset) => ({\n position: nextPosition + offset,\n item: item as Record<string, unknown>,\n }));\n return {\n rows,\n nextWatermark: sanitized.length,\n nextPosition: nextPosition + rows.length,\n };\n}\n\n/** Select only opaque rows that participated in the provider's rejected wire request. */\nexport function selectRejectedProviderArtifactHistoryIds(\n activeHistory: ReadonlyArray<{\n id: string;\n item: Record<string, unknown>;\n providerArtifactInvalidatedAt: Date | null;\n }>,\n candidates: {\n knownHistoryItemIds: readonly string[];\n historyItemIds: readonly string[];\n },\n wireFingerprints: readonly string[],\n): string[] {\n const remainingWireArtifacts = new Map<string, number>();\n for (const fingerprint of wireFingerprints) {\n remainingWireArtifacts.set(fingerprint, (remainingWireArtifacts.get(fingerprint) ?? 0) + 1);\n }\n const knownHistoryItemIds = new Set(candidates.knownHistoryItemIds);\n const initialCandidateIds = new Set(candidates.historyItemIds);\n const selected: string[] = [];\n for (const row of activeHistory) {\n if (row.providerArtifactInvalidatedAt !== null) continue;\n // A row present before this attempt is eligible only when the exact\n // model-facing projection retained it. Rows appended during this run are\n // eligible after durable reconciliation.\n if (knownHistoryItemIds.has(row.id) && !initialCandidateIds.has(row.id)) continue;\n const fingerprint = opaqueProviderArtifactFingerprint(row.item);\n if (!fingerprint) continue;\n const remaining = remainingWireArtifacts.get(fingerprint) ?? 0;\n if (remaining === 0) continue;\n selected.push(row.id);\n remainingWireArtifacts.set(fingerprint, remaining - 1);\n }\n return selected;\n}\n\n/** Literal final per-call boundary for replayed and current-turn model input. */\nexport function secretRedactionModelInputFilter(\n redactValue: (value: unknown) => unknown,\n): NonNullable<RunAgentStreamOptions[\"callModelInputFilter\"]> {\n return ({ modelData }) => ({\n ...modelData,\n input: redactValue(modelData.input) as typeof modelData.input,\n });\n}\n\nfunction isModelOrToolProgressHistoryItem(item: Record<string, unknown>): boolean {\n if (item.type === \"message\") {\n return item.role === \"assistant\";\n }\n if (item.type === \"reasoning\" || item.type === \"compaction\") {\n return true;\n }\n if (typeof item.type === \"string\") {\n return item.type !== \"message\";\n }\n return false;\n}\n\n/**\n * Resolve the EFFECTIVE/active compute backend a turn should gate\n * filesystem-touching agent lifecycle hooks on (today: the repository clone).\n *\n * WHY (Case B — clone-onto-real-disk hazard): a session keeps its CLOUD HOME\n * backend (`settings.sandboxBackend`, e.g. \"modal\") but its ACTIVE sandbox may\n * have been swapped to a connected machine (`active_sandbox_id` → a selfhosted\n * lease). `runtime.buildAgent`'s repository-clone hook keys off the backend it is\n * told; if the worker passes nothing it defaults to the HOME backend and the hook\n * would `git clone` a private GitHub-App repo onto the user's REAL disk — a\n * bring-your-own machine owns its own filesystem and must NEVER be cloned onto. So\n * we look at where the agent ACTUALLY runs, not where the session was created.\n *\n * Returns \"selfhosted\" ONLY when the selfhosted feature is on AND the session has\n * a non-null active pointer whose sandbox `kind` is \"selfhosted\". Otherwise\n * returns undefined so buildAgent falls back to the home backend — byte-for-byte\n * unchanged cloud behavior.\n *\n * Total + best-effort by contract: it NEVER throws (a lookup failure is logged and\n * falls back to the home default), so wiring it at turn start can't fail the turn.\n * The DB I/O is injected (the real call site passes readActiveSandbox + getSandbox,\n * the same helpers wrapTurnBoxWithRouting reuses) so the gate/decision/safety\n * contract is unit-testable without a live database.\n */\nexport async function resolveActiveSandboxBackend(\n routingOn: boolean,\n loadPointer: () => Promise<{ activeSandboxId: string | null } | null>,\n loadSandboxKind: (sandboxId: string) => Promise<string | null>,\n): Promise<Settings[\"sandboxBackend\"] | undefined> {\n // The active pointer + swap tools only exist when selfhosted routing is on; with\n // the flag off there is nothing to resolve and we keep the home-backend default.\n if (!routingOn) {\n return undefined;\n }\n try {\n const pointer = await loadPointer();\n // A null pointer (no swap) means \"use the session's own cloud group box\" — the\n // home backend already governs that path, so leave the override unset.\n if (!pointer?.activeSandboxId) {\n return undefined;\n }\n const kind = await loadSandboxKind(pointer.activeSandboxId);\n return kind === \"selfhosted\" ? \"selfhosted\" : undefined;\n } catch (error) {\n console.error(\n \"active sandbox backend resolution failed (turn proceeds on home backend)\",\n safeErrorDiagnostic(error),\n );\n return undefined;\n }\n}\n\n/**\n * Managed-sandbox ownership exists only when this turn actually uses the\n * managed home. A Connected Machine is fenced by its active-route epoch and\n * must remain independent from cloud recovery state for the same session.\n */\nexport function managedSandboxOwnershipForTurn(\n machinePrimary: boolean,\n attemptId: string,\n sandboxGroupId: string,\n): { holderId: TurnSandboxLeaseHolderId; sandboxGroupId: string } | null {\n if (machinePrimary) return null;\n return {\n holderId: sandboxLeaseHolderIdForAttempt(attemptId),\n sandboxGroupId,\n };\n}\n\n/**\n * Classify a persisted active-sandbox pointer for TURN-START RECONCILE (issue #341\n * invariant B). Returns the typed reason to RESET the pointer to the session HOME,\n * or null to leave it in place. STRUCTURAL unestablishability only:\n * - no record → the pointed-at sandbox row is gone (`stale_pointer`);\n * - an unestablishable kind (a non-group Modal sibling, or an unknown backend) per\n * the SHARED `swapTargetEstablishability` predicate (`unsupported_backend_context`);\n * - a selfhosted sandbox with no enrollment id to address (`offline_enrollment`).\n * A selfhosted sandbox WITH an enrollment is deliberately left in place even when it\n * is momentarily offline: the machine may recover mid-turn and its ops surface\n * agent_offline lazily, so the user's explicit machine target is never abandoned for\n * a transient control-plane blip (that is #339's concern, not this one).\n */\nexport function pointerReconcileReason(\n record: { kind: string; enrollmentId: string | null } | null,\n): BackendUnresolvableCode | null {\n if (!record) {\n return \"stale_pointer\";\n }\n const establishable = swapTargetEstablishability({\n kind: record.kind,\n isSessionGroup: false,\n });\n if (!establishable.ok) {\n return establishable.code;\n }\n if (record.kind === \"selfhosted\" && !record.enrollmentId) {\n return \"offline_enrollment\";\n }\n return null;\n}\n\n/** The active pointer + its sandbox row, loaded once at turn start and threaded\n * through the reconcile so the establish branch reads the SAME (possibly reset)\n * values with no second query. */\nexport type LoadedActivePointer = {\n pointer: ActiveSandboxPointer | null;\n record: SandboxRecord | null;\n};\n\n/**\n * TURN-START RECONCILE (issue #341 invariant B / Shapes 1+2). If the persisted pointer's\n * target is STRUCTURALLY unestablishable ({@link pointerReconcileReason}) reset the pointer\n * to the session HOME (null) under the epoch fence, emit a VISIBLE `session.route.reconciled`\n * event, and return the reconciled pointer/record so the rest of the turn runs on home. NEVER\n * a silent downgrade. Bounded to ONE attempt: a lost CAS means a concurrent user swap won a\n * higher epoch, so re-read + honor it rather than clobber a newer, user-directed pointer. The\n * event publish is best-effort — a publish failure never fails the turn.\n *\n * FAIL-OPEN on a lookup failure (issue #341 review): the sandbox row is fetched HERE via the\n * caller's NON-swallowing `loadRecord`, so a null decision means the row is genuinely absent,\n * never a suppressed transient DB error. If `loadRecord` THROWS, reconciliation is skipped\n * entirely this turn — the pointer is left UNTOUCHED (record null → the turn runs\n * machinePrimary:false on the group box exactly as before reconcile existed), no CAS, no\n * event — and the next turn retries. A TRANSIENT LOOKUP FAILURE MUST NEVER MUTATE THE POINTER.\n */\nexport async function reconcileActiveSandboxPointer(\n db: ActivityServices[\"db\"],\n ids: { accountId: string; workspaceId: string; sessionId: string },\n pointer: ActiveSandboxPointer | null,\n loadRecord: (sandboxId: string) => Promise<SandboxRecord | null>,\n publish?: (events: Array<{ type: SessionEventType; payload: unknown }>) => Promise<void> | void,\n): Promise<LoadedActivePointer> {\n if (!pointer?.activeSandboxId) {\n return { pointer, record: null };\n }\n // Re-fetch the row WITHOUT error swallowing. A throw here (a transient DB blip) is NOT\n // \"row absent\": fail open — skip reconciliation, leave the pointer untouched.\n let record: SandboxRecord | null;\n try {\n record = await loadRecord(pointer.activeSandboxId);\n } catch {\n return { pointer, record: null };\n }\n const reason = pointerReconcileReason(record);\n if (!reason) {\n return { pointer, record };\n }\n const fromEpoch = pointer.activeEpoch;\n const reset = await setActiveSandbox(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n targetSandboxId: null,\n expectedEpoch: fromEpoch,\n }).catch(\n () => ({ swapped: false, pointer: null }) as Awaited<ReturnType<typeof setActiveSandbox>>,\n );\n if (reset.swapped && reset.pointer) {\n await Promise.resolve(\n publish?.([\n {\n type: \"session.route.reconciled\",\n payload: { reason, fromEpoch, toEpoch: reset.pointer.activeEpoch },\n },\n ]),\n ).catch(() => undefined);\n return { pointer: reset.pointer, record: null };\n }\n // The fence was lost: a concurrent higher-epoch swap won. Honor the newer pointer; its\n // record is re-fetched fail-open too (a transient failure leaves record null, never a\n // mutation — we already did not win the CAS).\n const reread = await readActiveSandbox(db, ids.workspaceId, ids.sessionId).catch(() => null);\n if (!reread) {\n return { pointer, record: null };\n }\n let rereadRecord: SandboxRecord | null = null;\n if (reread.activeSandboxId) {\n try {\n rereadRecord = await loadRecord(reread.activeSandboxId);\n } catch {\n rereadRecord = null;\n }\n }\n return { pointer: reread, record: rereadRecord };\n}\n\n/**\n * Warm the Modal private-registry image for the image ref this turn actually\n * resolved, not only the deployment-global OPENGENI_MODAL_IMAGE_REF warmed at\n * worker boot. A provider-native modalImageId bypasses registry import and is\n * resolved by ModalImageSelector.fromId during create. Otherwise packs can\n * override `modalImageRef` per workspace/turn, so a private pack image must be\n * resolved before sandbox creation or Modal falls back to the unauthenticated\n * `fromTag` path.\n */\nexport async function ensureTurnModalRegistryImage(\n runSettings: Settings,\n sandboxCreationBackend: Settings[\"sandboxBackend\"] | undefined,\n ensureRegistryImage: (settings: Settings) => Promise<void> = ensureModalRegistryImage,\n): Promise<void> {\n if (sandboxCreationBackend !== \"modal\") {\n return;\n }\n if (runSettings.modalImageId) {\n return;\n }\n if (!runSettings.modalImageRegistrySecret || !runSettings.modalImageRef) {\n return;\n }\n await ensureRegistryImage(runSettings);\n}\n\n/**\n * Decide whether the first actual computer action may start a proof recording.\n *\n * On-turn recording runs ffmpeg/x11grab INSIDE the box and reads the .mp4 back\n * out of the box's /tmp — plumbing that exists only for OpenGeni-operated cloud\n * boxes (the Modal desktop backend). A turn whose EFFECTIVE backend is a connected\n * machine (\"selfhosted\") runs on the user's REAL computer, which has none of that\n * capture plumbing (and the platform must never shell ffmpeg onto a user's machine\n * — the same reason the runtime skips its setup hooks for selfhosted). Left ungated\n * it films nothing, finds no /tmp file, and emits recording.started followed by\n * recording.failed{box-death} on EVERY machine-primary turn — misleading timeline\n * noise + wasted work. So gate it off, exactly like a recording-disabled deployment:\n * skip silently, emit nothing (no new event shape).\n *\n * `effectiveBackend` is the resolved ACTIVE backend for the turn\n * (resolveActiveSandboxBackend) — NOT the session's home backend. A modal-home\n * session actively swapped onto a machine resolves to \"selfhosted\" here and\n * correctly skips; a machine-home turn that degraded back to its cloud group box\n * (swap-away / flag-off) resolves to undefined and records as before.\n *\n * EDGE — mid-turn swap: this is evaluated once when computer-use first runs. A swap\n * after recording starts is deliberately ignored; the partial recording already has\n * defined failure semantics, so there is no stop/restart machinery.\n */\nexport function shouldStartOnTurnRecording(params: {\n recordingEnabled: boolean;\n desktopEnabled: boolean;\n establishedBackendId: string;\n effectiveBackend: Settings[\"sandboxBackend\"] | undefined;\n}): boolean {\n return (\n params.recordingEnabled &&\n params.desktopEnabled &&\n desktopCapableBackend(params.establishedBackendId) &&\n params.effectiveBackend !== \"selfhosted\"\n );\n}\n\n/**\n * Decide the EXPLICIT computer-use tool transport for THIS turn.\n *\n * The runtime's SDK-mirrored capability would otherwise pick hosted-vs-function\n * tools by string-sniffing the bound model instance's constructor name for\n * \"ChatCompletions\" (supportsStructuredToolOutputTransport). That is fragile: a\n * wrapped / proxied / minified model instance defeats the sniff and a\n * chat-completions provider would silently get the HOSTED `computer_use_preview`\n * tool it 400s on every turn. So the mode is decided HERE — the worker's model\n * resolution is the ONE place a provider's true wire identity is authoritative —\n * and threaded to the runtime as an explicit flag (buildAgent → computerToolMode):\n * • codex-subscription → \"function-image\": the ChatGPT/Codex backend rejects\n * hosted tool types but SEES structured `input_image` tool results.\n * • a \"chat\" (OpenAIChatCompletionsModel wire) provider → \"disabled\": it cannot\n * receive a screenshot through a proven visual transport, so computer use fails\n * closed instead of serializing the image as text.\n * • Vercel Gateway providers → \"disabled\": their curated models support ordinary\n * function tools and vision input, not OpenAI's hosted computer tool.\n * • everything else — built-in Azure/OpenAI responses, registry \"responses\"\n * providers, AND the LEGACY global-client fallback (resolveTurnModel returned\n * null) — → \"hosted\": real Responses hosted-tool support.\n *\n * Pure + exported so the mapping is unit-testable without a live turn.\n */\nexport function computerToolModeForTurn(\n resolvedModel: {\n provider: { kind: RegistryProviderKind; api: ModelProviderApi };\n configured: { capabilities: { inputModalities: string[] } };\n } | null,\n): ComputerToolMode {\n if (!resolvedModel) {\n return \"hosted\"; // legacy built-in Responses client — real hosted support\n }\n if (!modelSupportsImageInputForTurn(resolvedModel)) {\n return \"disabled\";\n }\n if (resolvedModel.provider.kind === \"codex-subscription\") {\n return \"function-image\";\n }\n if (\n resolvedModel.provider.kind === \"vercel-gateway-managed\" ||\n resolvedModel.provider.kind === \"vercel-gateway-workspace\"\n ) {\n return \"disabled\";\n }\n if (resolvedModel.provider.api === \"chat\") {\n return \"disabled\";\n }\n return \"hosted\";\n}\n\n/** Gateway models do not advertise OpenAI's hosted apply_patch/view_image tool types. */\nexport function structuredToolTransportForTurn(\n resolvedModel: { provider: { kind: RegistryProviderKind } } | null,\n): boolean {\n if (!resolvedModel) return true;\n return ![\"codex-subscription\", \"vercel-gateway-managed\", \"vercel-gateway-workspace\"].includes(\n resolvedModel.provider.kind,\n );\n}\n\n/**\n * Native web search is a runtime capability, not part of the session's MCP\n * allow-list. Attach it whenever the resolved provider advertises runnable\n * support. The null model is the legacy built-in Responses path, whose\n * deployment flag is its provider capability gate. There is deliberately no\n * cross-provider or sandbox/curl fallback.\n */\nexport function hostedWebSearchForTurn(\n resolvedModel: { configured: { hostedWebSearch: boolean } } | null,\n deploymentWebSearchEnabled: boolean,\n): boolean {\n return resolvedModel?.configured.hostedWebSearch ?? deploymentWebSearchEnabled;\n}\n\n/** Exact model-catalog modality gate; null preserves the legacy built-in path. */\nexport function modelSupportsImageInputForTurn(\n resolvedModel: {\n configured: { capabilities?: { inputModalities: string[] } };\n } | null,\n): boolean {\n return (\n resolvedModel === null ||\n resolvedModel.configured.capabilities?.inputModalities.includes(\"image\") !== false\n );\n}\n\nconst LEGACY_INPUT_FILE_MEDIA_TYPES = [\n \"application/json\",\n \"application/pdf\",\n \"application/x-yaml\",\n \"application/yaml\",\n \"text/*\",\n] as const;\n\n/** Image and file input are independent catalogue capabilities. */\nexport function modelAttachmentInputPolicyForTurn(\n resolvedModel: {\n provider: { api: ModelProviderApi };\n configured: {\n capabilities?: { inputModalities: string[]; inputFileMediaTypes?: string[] };\n };\n } | null,\n): ModelAttachmentInputPolicy {\n const typedTransport = resolvedModel === null || resolvedModel.provider.api === \"responses\";\n return {\n supportsImageInput: typedTransport && modelSupportsImageInputForTurn(resolvedModel),\n inputFileMediaTypes: typedTransport\n ? (resolvedModel?.configured.capabilities?.inputFileMediaTypes ??\n LEGACY_INPUT_FILE_MEDIA_TYPES)\n : [],\n };\n}\n\nexport type TurnSandboxProvisioner<T> = {\n get(): Promise<T>;\n hasStarted(): boolean;\n waitForSettled(timeoutMs: number): Promise<T | null>;\n};\n\nexport class TurnOperationCancelledError extends Error {\n readonly name = \"TurnOperationCancelledError\";\n\n constructor(readonly reason: unknown) {\n super(\"Turn operation was cancelled with its owning turn\", {\n ...(reason instanceof Error ? { cause: reason } : {}),\n });\n }\n}\n\nexport class SandboxDeadlineRotationError extends Error {\n readonly name = \"SandboxDeadlineRotationError\";\n\n constructor(\n readonly sandboxGroupId: string,\n readonly leaseEpoch: number,\n ) {\n super(\n `Sandbox ${sandboxGroupId} reached its provider rotation boundary at lease epoch ${leaseEpoch}`,\n );\n }\n}\n\n/**\n * Normalize a preparation/provisioning cancellation race back to the Temporal\n * cancellation that owns the activity. Several provider APIs expose no portable\n * abort primitive, so the worker stops awaiting them and disposes any late\n * resource. The wrapper error must never fall through as an ordinary turn\n * failure: doing so would omit the quiescence receipt and strand a committed\n * Steer/Pause behind `control-pending`.\n */\nexport function turnOperationCancellationFailure(error: unknown): CancelledFailure | null {\n if (error instanceof CancelledFailure) return error;\n if (!(error instanceof TurnOperationCancelledError)) return null;\n return error.reason instanceof CancelledFailure\n ? error.reason\n : new CancelledFailure(\"TURN_SANDBOX_PROVISION_CANCELLED\", [], error);\n}\n\nfunction throwIfTurnOperationCancelled(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw new TurnOperationCancelledError(signal.reason);\n }\n}\n\nexport async function waitForTurnOperation<T>(\n operation: Promise<T>,\n signal: AbortSignal | undefined,\n disposeLateResult: ((result: T) => Promise<void> | void) | undefined,\n): Promise<T> {\n if (!signal) return await operation;\n\n let rejectCancellation: ((error: TurnOperationCancelledError) => void) | undefined;\n const cancelled = new Promise<never>((_resolve, reject) => {\n rejectCancellation = reject;\n });\n const cancel = (): void => {\n rejectCancellation?.(new TurnOperationCancelledError(signal.reason));\n };\n signal.addEventListener(\"abort\", cancel, { once: true });\n if (signal.aborted) cancel();\n\n try {\n const result = await Promise.race([operation, cancelled]);\n // Cancellation owns an exact turn boundary even when the provider result\n // and AbortSignal settle in the same microtask checkpoint. Never let a\n // just-resolved lease escape after the control was already committed.\n if (signal.aborted) {\n throw new TurnOperationCancelledError(signal.reason);\n }\n return result;\n } catch (error) {\n if (signal.aborted) {\n // The provider establish call has no universal cancellation seam. It may\n // finish after the Temporal activity has correctly stopped; dispose its\n // late lease instead of letting a cancelled turn resurrect a holder/box.\n void operation\n .then(async (result) => await disposeLateResult?.(result))\n .catch(() => undefined);\n // A provider failure may settle in the same checkpoint as the committed\n // control. The control is authoritative; retain its cancellation shape\n // so the activity publishes quiescence instead of looking like an\n // unrelated turn failure.\n if (!(error instanceof TurnOperationCancelledError)) {\n throw new TurnOperationCancelledError(signal.reason);\n }\n }\n throw error;\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function isLazySandboxProvisionRetryable(error: unknown): boolean {\n if (\n error instanceof SandboxImageConflictError ||\n error instanceof SandboxLeaseRecoveryBlockedError\n ) {\n return false;\n }\n if (error instanceof WorkspaceArchiveIntegrityError) {\n return error.retryable;\n }\n if (error instanceof SandboxLeaseSupersededError || error instanceof SandboxWarmingTimeoutError) {\n return true;\n }\n const message = error instanceof Error ? error.message : String(error);\n return /(?:capacity|create|creation|provider|sandbox).*(?:timeout|timed out)|(?:timeout|timed out).*(?:capacity|create|creation|provider|sandbox)|ECONNRESET|ETIMEDOUT|EAI_AGAIN|temporar/i.test(\n message,\n );\n}\n\n/**\n * Deadline recovery cannot re-admit the same turn until the global reaper has\n * observed the released holder, captured the final archive, terminated the old\n * provider box, and committed the lease cold. Give that full sequence one\n * snapshot budget plus two schedule periods. This is workflow-visible pacing,\n * not an in-memory sleep, so Pause/Steer/new user intent can still wake the\n * durable session immediately.\n */\nexport function sandboxDeadlineRotationRecoveryDelayMs(\n settings: Pick<Settings, \"sandboxLeaseReaperPeriodMs\" | \"sandboxSnapshotTimeoutMs\">,\n): number {\n return settings.sandboxSnapshotTimeoutMs + settings.sandboxLeaseReaperPeriodMs * 2;\n}\n\nexport function createTurnSandboxProvisioner<T>(\n establish: () => Promise<T>,\n options: {\n maxRetries?: number;\n backoffMs?: number;\n signal?: AbortSignal;\n onStarted?: () => Promise<void> | void;\n onCompleted?: (result: T) => Promise<void> | void;\n onFailed?: (error: unknown) => Promise<void> | void;\n disposeResult?: (result: T) => Promise<void> | void;\n } = {},\n): TurnSandboxProvisioner<T> {\n const maxRetries = options.maxRetries ?? 2;\n const backoffMs = options.backoffMs ?? 250;\n let memo: Promise<T> | null = null;\n\n const run = async (): Promise<T> => {\n let attempt = 0;\n while (true) {\n try {\n throwIfTurnOperationCancelled(options.signal);\n const operation = establish();\n return await waitForTurnOperation(operation, options.signal, options.disposeResult);\n } catch (error) {\n if (\n error instanceof TurnOperationCancelledError ||\n attempt >= maxRetries ||\n !isLazySandboxProvisionRetryable(error)\n ) {\n throw error;\n }\n attempt += 1;\n await sleep(backoffMs * attempt);\n }\n }\n };\n\n return {\n get(): Promise<T> {\n if (!memo) {\n memo = (async () => {\n throwIfTurnOperationCancelled(options.signal);\n await options.onStarted?.();\n throwIfTurnOperationCancelled(options.signal);\n let result: T | undefined;\n let hasResult = false;\n try {\n result = await run();\n hasResult = true;\n throwIfTurnOperationCancelled(options.signal);\n await options.onCompleted?.(result);\n return result;\n } catch (error) {\n if (hasResult) {\n await options.disposeResult?.(result as T);\n }\n if (!(error instanceof TurnOperationCancelledError)) {\n await options.onFailed?.(error);\n }\n throw error;\n }\n })().catch((error) => {\n // A terminal lease/archive/configuration result cannot change within\n // this frozen turn. Keep its rejected promise memoized so later model\n // tool calls observe the same typed result without re-entering\n // provisioning, emitting another failure event, or creating another\n // provider attempt. Only a retryable failure releases the single-flight\n // for a later operation to re-read the lease/provider state.\n if (isLazySandboxProvisionRetryable(error)) {\n memo = null;\n }\n throw error;\n });\n }\n return memo;\n },\n hasStarted(): boolean {\n return memo !== null;\n },\n async waitForSettled(timeoutMs: number): Promise<T | null> {\n if (!memo) {\n return null;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n memo.catch(() => null),\n new Promise<null>((resolve) => {\n timer = setTimeout(() => resolve(null), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n },\n };\n}\n\n/**\n * Decide whether THIS turn may send OpenAI's `prompt_cache_key` request field.\n *\n * Accepted transports:\n * - legacy/built-in OpenAI or Azure Responses fallback (resolvedModel null);\n * - resolved built-in OpenAI/Azure providers;\n * - ChatGPT/Codex subscription backend (its strict allowlist permits the field).\n *\n * Registry API-key providers are intentionally excluded. Fireworks' prompt-cache\n * docs prescribe `user` or `x-session-affinity`, not `prompt_cache_key`; Z.AI/GLM\n * documents automatic context caching plus `user_id`. Sending OpenAI-only fields\n * to unknown OpenAI-compatible providers risks unsupported-parameter 400s.\n */\nexport function acceptsPromptCacheKeyForTurn(\n resolvedModel: {\n provider: { kind: RegistryProviderKind; builtin?: boolean };\n } | null,\n): boolean {\n if (!resolvedModel) {\n return true;\n }\n return (\n resolvedModel.provider.builtin === true || resolvedModel.provider.kind === \"codex-subscription\"\n );\n}\n\n/**\n * SELF-HEAL helper for the all-capped rotation idle (invariant 4: BOUNDED, no thrash).\n * The turn hot path never refreshes Codex usage — only the usage API route does — so a\n * window that has actually reset still reads OVER-threshold from the stale cache, which\n * would idle-loop forever. Before idling, refresh LIVE usage for every connected account\n * the cache marks exhausted (bounded to the account count), which re-writes the\n * cache columns, then return the re-read rows so the ranker can pick up a genuinely-reset\n * window THIS turn. A refresh/read failure is swallowed (fall back to the pre-refresh rows\n * + the bounded idle). Cooling (429'd) accounts are NOT refreshed: their exhaustedUntil\n * cooldown is authoritative, and refreshing them would burn a provider call for nothing.\n */\nasync function refreshCappedCodexUsageRows(\n db: ActivityServices[\"db\"],\n settings: Settings,\n workspaceId: string,\n accounts: Array<\n Pick<\n CodexAccountStatus,\n \"id\" | \"status\" | \"primaryUsedPercent\" | \"secondaryUsedPercent\" | \"exhaustedUntil\"\n >\n >,\n capacitySignals: {\n signalCodexCapacityWorkflow?: ActivityServices[\"signalCodexCapacityWorkflow\"] | undefined;\n wakeSessionWorkflow: ActivityServices[\"wakeSessionWorkflow\"];\n },\n): Promise<\n Array<\n Pick<\n CodexAccountStatus,\n \"id\" | \"status\" | \"primaryUsedPercent\" | \"secondaryUsedPercent\" | \"exhaustedUntil\"\n >\n >\n> {\n const stale = accounts.filter(\n (a) =>\n a.status === \"active\" &&\n ((a.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||\n (a.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT),\n );\n if (stale.length === 0) {\n return accounts;\n }\n await refreshCodexUsageAndRepairCapacityWaiters(\n stale.map((account) => () => fetchCodexUsageForAccount(db, settings, workspaceId, account.id)),\n () => signalPendingCodexCapacityWakeTargets({ db, ...capacitySignals }, workspaceId),\n );\n return listCodexAccountStatuses(db, workspaceId).catch(() => accounts);\n}\n\n/**\n * True once the lifetime last confirmed by Postgres is no longer trustworthy.\n * A missing or malformed deadline fails closed for a holder that claims to be\n * leased; callers check this before accepting an in-flight heartbeat promise.\n */\nexport function codexCredentialLeaseDeadlineExpired(\n confirmedUntilMs: number | null,\n nowMs: number = performance.now(),\n): boolean {\n return (\n confirmedUntilMs === null || !Number.isFinite(confirmedUntilMs) || confirmedUntilMs <= nowMs\n );\n}\n\nexport function createRunAgentTurnActivity(services: () => Promise<ActivityServices>) {\n return async function runAgentTurn(input: RunAgentTurnInput): Promise<RunAgentTurnResult> {\n const {\n settings,\n db,\n bus,\n runtime,\n objectStorage,\n observability,\n wakeSessionWorkflow,\n signalSessionAttemptQuiesced,\n signalCodexCapacityWorkflow,\n entitlements,\n connectionCredentials,\n } = await services();\n const activityContext = currentActivityContext();\n const cancellationSignal = activityContext?.cancellationSignal;\n // Temporal cancellation is not the only way an activity loses ownership:\n // a database attempt fence or workflow abandonment can finalize the logical\n // turn while the SDK cancellation signal remains open. Bind sandbox\n // provisioning to both lifetimes so an uninterruptible, late provider\n // promise cannot resurrect a holder after this activity has finalized.\n const sandboxResumeController = new AbortController();\n const sandboxResumeSignal = cancellationSignal\n ? AbortSignal.any([cancellationSignal, sandboxResumeController.signal])\n : sandboxResumeController.signal;\n const sandboxRotationController = new AbortController();\n const runtimeCancellationSignal = cancellationSignal\n ? AbortSignal.any([cancellationSignal, sandboxRotationController.signal])\n : sandboxRotationController.signal;\n let cancellationRequestedAt: number | null = cancellationSignal?.aborted\n ? performance.now()\n : null;\n const noteCancellationRequested = (): void => {\n cancellationRequestedAt ??= performance.now();\n };\n cancellationSignal?.addEventListener(\"abort\", noteCancellationRequested, {\n once: true,\n });\n const dispatchId = activityContext?.info.activityId ?? randomUUID();\n const activityStarted = performance.now();\n const activitySpan = observability.startSpan(\"worker.run_agent_segment\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.workflow_id\": input.workflowId,\n \"opengeni.trigger_kind\": input.trigger.kind,\n });\n let activityStatus: RunAgentTurnResult[\"status\"] | \"unknown\" = \"unknown\";\n let turnMetricOutcome: TurnOutcome | null = null;\n let activityError: unknown;\n let acknowledgeQuiescence = false;\n const acknowledgeLostAttemptOwnership = (): void => {\n // A stale terminal/recovery settlement can lose either to a benign\n // successor or to Pause/Steer closing this exact attempt. Only the\n // receipt transaction can distinguish those cases after the hard tool\n // fence: allowUninterrupted makes the benign case an event-free no-op.\n acknowledgeQuiescence = true;\n noteCancellationRequested();\n };\n let turnId: string | undefined;\n let triggerEventId: string | undefined;\n const claimedResult = (\n result: Omit<\n Extract<RunAgentTurnResult, { status: Exclude<RunAgentTurnResult[\"status\"], \"unclaimed\"> }>,\n \"turnId\" | \"attemptId\"\n >,\n ): RunAgentTurnResult => {\n if (!turnId) throw new Error(\"Claimed activity result produced before turn admission\");\n return {\n ...result,\n turnId,\n attemptId: input.attemptId,\n } as RunAgentTurnResult;\n };\n // The Connected Machine op observer for this turn: meters every op AND buffers\n // the eventable ones (infra failures + healed recoveries) as machine.op.* session\n // events, drained (awaited) at turn end in the finally below. ONE instance shared\n // by the machine-primary establish + both routing wraps.\n const machineOpObserver = makeMachineOpObserver(\n runtimeMetricsHooksForObservability(observability),\n );\n const sandboxOperationObserver = sandboxOperationMetricObserver(observability);\n let isCodexTurn = false;\n let isExternallyBilledTurn = false;\n let executionGeneration = 0;\n let providerRecoveryCount = 0;\n let modelRequestStarted = false;\n // Still required by credential-loss/capacity settlements, whose own\n // recovery transactions fence against worker-death redispatches.\n let redispatchesAtDispatch = 0;\n const setLastInputTokensFenced = async (lastInputTokens: number | null): Promise<void> => {\n if (!turnId || executionGeneration <= 0) {\n throw new Error(\"Turn attempt was not initialized before token accounting\");\n }\n if (\n !(await setSessionLastInputTokensForTurnAttempt(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n expectedExecutionGeneration: executionGeneration,\n expectedAttemptId: input.attemptId,\n lastInputTokens,\n }))\n ) {\n throw new TurnAttemptFencedError(\"turn attempt was fenced while recording input tokens\");\n }\n };\n let heartbeatTimer: ReturnType<typeof startActivityHeartbeat> | undefined;\n // credential allocator: one workspace-local idempotent credential holder per running\n // Codex turn. The DB row is the cross-replica fairness primitive; this timer\n // only extends its short TTL. A killed worker stops heartbeating and the\n // holder self-expires. Other workspaces never see or share this holder.\n let codexLeaseHeld = false;\n let codexLeaseLost = false;\n let codexLeaseHolderId: string | null = null;\n let codexLeaseGeneration: number | null = null;\n // Monotonic worker deadline, not a comparison between the Postgres and\n // worker wall clocks. It is advanced only after a database renewal confirms,\n // from the request START + TTL; slow queries therefore shorten (never extend)\n // the conservative ownership window.\n let codexLeaseConfirmedUntilMs: number | null = null;\n let codexLeaseHeartbeatInFlight = false;\n let codexLeaseHeartbeatTimer: ReturnType<typeof setInterval> | undefined;\n const codexWorkspaceKey = codexWorkspaceMetricKey(input.workspaceId);\n const markCodexLeaseLost = (reason: \"deadline\" | \"not_found\"): void => {\n if (codexLeaseLost) return;\n codexLeaseLost = true;\n observability.incrementCounter({\n name: \"opengeni_codex_lease_renewals_total\",\n help: \"Codex lease renewal checkpoints by outcome and reason.\",\n labels: { workspace_key: codexWorkspaceKey, outcome: \"lost\", reason },\n });\n observability.warn(\"Codex credential lease was lost during an active turn\", {\n workspaceId: input.workspaceId,\n turnId,\n reason,\n });\n };\n const renewCodexLease = async (reason: \"timer\" | \"runtime_event\" | \"model_usage\") => {\n if (\n !turnId ||\n !codexLeaseHeld ||\n !codexLeaseHolderId ||\n codexLeaseGeneration === null ||\n codexLeaseLost\n )\n return;\n // Check the last expiry the database actually returned BEFORE the\n // single-flight guard. A hung heartbeat must not make later model/runtime\n // checkpoints trust a lease whose last proven lifetime already elapsed.\n if (codexCredentialLeaseDeadlineExpired(codexLeaseConfirmedUntilMs)) {\n markCodexLeaseLost(\"deadline\");\n return;\n }\n if (codexLeaseHeartbeatInFlight) return;\n codexLeaseHeartbeatInFlight = true;\n const renewalStartedAtMs = performance.now();\n try {\n const renewedUntil = await heartbeatCodexCredentialLeaseUntil(\n db,\n input.accountId,\n input.workspaceId,\n turnId,\n codexLeaseHolderId,\n codexLeaseGeneration,\n CODEX_CREDENTIAL_LEASE_TTL_MS,\n );\n if (!renewedUntil) {\n markCodexLeaseLost(\"not_found\");\n } else {\n codexLeaseConfirmedUntilMs = renewalStartedAtMs + CODEX_CREDENTIAL_LEASE_TTL_MS;\n observability.incrementCounter({\n name: \"opengeni_codex_lease_renewals_total\",\n help: \"Codex lease renewal checkpoints by outcome and reason.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n outcome: \"completed\",\n reason,\n },\n });\n }\n } catch (error) {\n // A transient DB failure does not immediately abandon a still-live row,\n // but it also cannot extend the last database-confirmed deadline.\n if (codexCredentialLeaseDeadlineExpired(codexLeaseConfirmedUntilMs)) {\n markCodexLeaseLost(\"deadline\");\n return;\n }\n observability.warn(\"Codex credential lease heartbeat failed\", {\n workspaceId: input.workspaceId,\n turnId,\n reason,\n errorName: error instanceof Error ? error.name : \"unknown\",\n });\n observability.incrementCounter({\n name: \"opengeni_codex_lease_renewals_total\",\n help: \"Codex lease renewal checkpoints by outcome and reason.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n outcome: \"error\",\n reason,\n },\n });\n } finally {\n codexLeaseHeartbeatInFlight = false;\n }\n };\n const startCodexLeaseHeartbeat = (): void => {\n if (!turnId || codexLeaseHeartbeatTimer) return;\n codexLeaseHeartbeatTimer = setInterval(() => {\n void renewCodexLease(\"timer\");\n }, 60_000);\n codexLeaseHeartbeatTimer.unref?.();\n };\n // P1.2 ownership inversion: when sandboxOwnershipEnabled, the turn resolves\n // the one box by id from the group lease and injects it NON-OWNED into the\n // run. null when the flag is off (byte-for-byte the legacy build-and-discard\n // path) OR when the backend is \"none\". Released + dropped in `finally`.\n let resolvedSandbox: ResumedTurnSandbox | null = null;\n const requireResolvedSandboxForMutation = (message: string): ResumedTurnSandbox => {\n if (!resolvedSandbox) throw new Error(message);\n return resolvedSandbox;\n };\n // The machine-primary SelfhostedSession (the UNWRAPPED backend, not the\n // routing proxy): held so the turn's completion can final-ack this turn's\n // settled op-stream ops AFTER the results are durably persisted.\n let machinePrimarySession: import(\"@opengeni/runtime\").SelfhostedSession | null = null;\n let lazyOwnedSandbox: EstablishedSandboxSession | null = null;\n let turnSandboxProvisioner: TurnSandboxProvisioner<ResumedTurnSandbox> | null = null;\n // The UN-PROXIED established box session, captured BEFORE wrapTurnBoxWithRouting.\n // Platform setup (beforeAgentStart hooks + file materialization) execs against\n // THIS handle so a mid-turn sandbox_swap can never re-route those execs onto a\n // connected machine (the user's real computer).\n let setupBoxSession: unknown = null;\n // A same-target API repair can replace the home provider while this turn is\n // alive. Keep setup/snapshot persistence on the rebound raw session while\n // preserving the SDK-owned routing proxy for eager turns. Lazy turns hold the\n // proxy separately, so their worker-side handle may replace its raw session.\n const onHomeSandboxRebound = (rebound: {\n established: EstablishedSandboxSession;\n leaseEpoch: number;\n }): void => {\n const current = resolvedSandbox;\n const previousSession = current?.established.session;\n const preserveRoutingProxy = current !== null && previousSession !== setupBoxSession;\n setupBoxSession = rebound.established.session;\n if (!current) return;\n current.leaseEpoch = rebound.leaseEpoch;\n current.established = preserveRoutingProxy\n ? {\n ...current.established,\n client: rebound.established.client,\n // Keep the stable SDK-facing proxy; only its resolver changes the\n // underlying backend. The worker's setupBoxSession above is raw.\n session: previousSession,\n sessionState: rebound.established.sessionState,\n instanceId: rebound.established.instanceId,\n backendId: rebound.established.backendId,\n ...(rebound.established.origin ? { origin: rebound.established.origin } : {}),\n ...(rebound.established.restoredArchive\n ? { restoredArchive: rebound.established.restoredArchive }\n : {}),\n }\n : rebound.established;\n };\n // The globally unique durable turn-attempt holder id + the group id,\n // captured so the lease heartbeat can refresh the lease TTL epoch-fenced\n // (a superseded owner self-evicts) and finally can release.\n let sandboxHolderId: TurnSandboxLeaseHolderId | null = null;\n let sandboxGroupId: string | null = null;\n const runWorkspaceMutationForSandbox = async <T>(\n sandbox: ResumedTurnSandbox,\n operation: string,\n mutation: () => Promise<T>,\n ): Promise<T> => {\n // Connected machines are the user's own persistence and never dirty the\n // cloud home archive. Every persistable raw-session write batch is fenced\n // against the exact current lease/provider before the provider sees it.\n if (sandbox.established.backendId === \"selfhosted\") return await mutation();\n if (!sandboxGroupId || !sandboxHolderId || !turnId || executionGeneration <= 0) {\n throw new Error(\"Workspace mutation attempted before exact turn sandbox admission\");\n }\n const identity = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n executionGeneration,\n attemptId: input.attemptId,\n holderId: sandboxHolderId,\n sandboxGroupId,\n expectedEpoch: sandbox.leaseEpoch,\n expectedInstanceId: sandbox.established.instanceId,\n operation,\n captureWaitMs: sandboxArchiveCaptureTimeoutMs(settings),\n };\n const admission = await advanceWorkspaceGeneration(db, identity);\n let result: T;\n try {\n result = await mutation();\n } catch (providerError) {\n try {\n await verifyWorkspaceMutationSettlement(db, {\n ...identity,\n admission,\n outcome: \"rejected\",\n });\n } catch (settlementError) {\n throw new RoutingMutationOutcomeUnknownError(\n operation,\n `Platform workspace mutation \"${operation}\" rejected at the provider but lost its durable physical settlement; its outcome is unknown and it was not replayed`,\n { cause: settlementError },\n );\n }\n throw providerError;\n }\n try {\n await verifyWorkspaceMutationSettlement(db, {\n ...identity,\n admission,\n outcome: \"resolved\",\n });\n } catch (settlementError) {\n throw new RoutingMutationOutcomeUnknownError(\n operation,\n `Platform workspace mutation \"${operation}\" returned from the provider but lost its durable settlement fence; its outcome is unknown and it was not replayed`,\n { cause: settlementError },\n );\n }\n return result;\n };\n // Lease-TTL refresh timer (parallels the activity heartbeat): while the turn\n // runs it refreshes expires_at epoch-fenced so a legit multi-day turn is\n // never TTL-reaped. Cleared in finally. Only set when the flag resolved a box.\n let leaseHeartbeatTimer: ReturnType<typeof setInterval> | undefined;\n const stopLeaseHeartbeat = (): void => {\n if (!leaseHeartbeatTimer) return;\n clearInterval(leaseHeartbeatTimer);\n leaseHeartbeatTimer = undefined;\n };\n let rotationInFlight: Promise<void> | null = null;\n // credential-renewal policy: the worker, not the model, owns renewal of run-scoped Git\n // credentials for a multi-day turn. The controller is attached only after\n // the initial seed reached a real cloud box and is drained before capture.\n let gitCredentialRenewals: GitCredentialRenewalController[] = [];\n let gitCredentialRenewalClosed = false;\n // Generic host-owned run material has its own attempt-scoped renewal and\n // write handle. It is always drained and wiped before workspace capture.\n let runCredentialRenewal: RunCredentialRenewalController | null = null;\n let runCredentialRenewalClosed = false;\n let runCredentialSession: RunCredentialCommandSession | null = null;\n // The delegated Toolspace bearer has a one-hour TTL. Renewal is attempt-\n // owned and attaches only after the initial token file reached a real\n // sandbox session; finalization drains an in-flight replacement.\n let toolspaceTokenRenewal: ToolspaceTokenRenewalController | null = null;\n let toolspaceTokenRenewalClosed = false;\n // MID-SESSION snapshot single-flight guard: the heartbeat tick fires every\n // 10s but a Modal filesystem snapshot can take longer — never overlap two\n // captures on one box. The in-flight capture's promise is held so the\n // turn-end persist can await it (its capture predates the turn's final\n // writes; landing after the fresher turn-end capture started would make\n // the atomic DB throttle discard the fresher one). Interval throttling\n // itself lives in maybePersistWarmWorkspaceSnapshot / persistWarmSnapshot.\n let snapshotInFlight: Promise<void> | null = null;\n // Turn-end capture needs the lease heartbeat to keep its holder alive, but\n // must prevent that same timer from starting another periodic snapshot\n // while it reads. This gate separates those two responsibilities.\n let turnEndCaptureInProgress = false;\n // Computer-use-only recording. Ordinary shell/filesystem turns leave this\n // null; the first actual computer action starts it after :0 is ready.\n let activeRecording: ActiveRecording | null = null;\n let computerUseRecordingStart: Promise<void> | null = null;\n // P4.3 recording gate: flips true in `onComputerUseReady`, the runtime's\n // execution-time callback for the first real computer action. It must flip\n // BEFORE awaiting recording startup: the SDK tool-call stream item can arrive\n // before ffmpeg has finished starting. A plain text turn (\"hey\"/\"continue\")\n // never invokes the callback, so settlement performs no storage PUT.\n let didComputerUse = false;\n const abandonActiveRecording = async (\n reason: string,\n disposition: \"failed\" | \"discard\" = \"failed\",\n ): Promise<void> => {\n const recording = activeRecording as ActiveRecording | null;\n if (!recording) return;\n activeRecording = null;\n if (resolvedSandbox) {\n await stopRecordingOnBox(resolvedSandbox.established.session, recording.proc).catch(\n () => undefined,\n );\n }\n if (!turnId || executionGeneration <= 0) return;\n await abandonRecordingForTurnAttempt(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n executionGeneration,\n attemptId: input.attemptId,\n recordingId: recording.recordingId,\n disposition,\n reason,\n }).catch(() => undefined);\n };\n let batcher: ReturnType<typeof createRuntimeBatcher> | null = null;\n const flushRuntimeBatcher = async () => {\n const current = batcher as ReturnType<typeof createRuntimeBatcher> | null;\n await current?.flush().catch(() => undefined);\n };\n let preparedTools: Awaited<ReturnType<OpenGeniRuntime[\"prepareTools\"]>> | null = null;\n const toolCancellationFenceRef: {\n current: TurnToolCancellationFence | null;\n } = {\n current: null,\n };\n let publish: TurnEventPublisher | null = null;\n let settle:\n | ((input: {\n events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>;\n turnStatus:\n | \"queued\"\n | \"running\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n | \"requires_action\";\n sessionStatus: SessionStatus;\n activeTurnId: string | null;\n consumeRequestedCompactionFailure?: boolean;\n runState?: ApplySessionTurnSettlementInput[\"runState\"];\n }) => Promise<boolean>)\n | null = null;\n let turnStartedPublished = false;\n let stream: Awaited<ReturnType<OpenGeniRuntime[\"runStream\"]>> | undefined;\n // Reconciliation is declared before provider routing so every turn-end path\n // can share one closure. It cannot run until `stream` exists, by which time\n // this value has been rebound to the turn's resolved model policy.\n let modelRunSettings: Settings = settings;\n const publishSandboxLifecycleEvents = async (sandbox: ResumedTurnSandbox): Promise<void> => {\n const established = sandbox.established;\n if (publish && established.origin && established.origin !== \"resumed\") {\n const lifecycleEvents: Array<{\n type: \"sandbox.box.lost\" | \"sandbox.box.created\";\n payload: unknown;\n }> = [];\n if (established.lostInstanceId) {\n lifecycleEvents.push({\n type: \"sandbox.box.lost\",\n payload: { sandboxId: established.lostInstanceId },\n });\n }\n lifecycleEvents.push({\n type: \"sandbox.box.created\",\n payload: {\n sandboxId: established.instanceId,\n hydrated: established.origin === \"restored\" ? \"archive\" : \"none\",\n },\n });\n await publish(lifecycleEvents).catch(() => undefined);\n }\n };\n const publishSandboxLost = async (lostSandbox: { instanceId: string }): Promise<void> => {\n if (!publish) return;\n await publish([\n {\n type: \"sandbox.box.lost\",\n payload: { sandboxId: lostSandbox.instanceId },\n },\n ]).catch((publishError) => {\n // The lease transition is already authoritative. A fenced/failed audit\n // append must not prevent the same logical turn from recovering.\n console.error(\"sandbox box lost event publish failed\", safeErrorDiagnostic(publishError));\n });\n };\n const startLeaseHeartbeat = (\n sandbox: ResumedTurnSandbox,\n warmBackend: Settings[\"sandboxBackend\"] | undefined,\n ): void => {\n if (!sandboxHolderId || !sandboxGroupId) {\n return;\n }\n // Refresh the lease TTL on the activity-heartbeat cadence (10s, well\n // inside the 90s lease TTL). EPOCH-FENCED: a superseded owner's refresh\n // is rejected (returns false) and we stop refreshing — the box rides the\n // provider idle-timeout and the next dispatch re-establishes it. Best-\n // effort: a transient DB error must never fail the turn.\n const heartbeatEpoch = sandbox.leaseEpoch;\n const heartbeatHolderId = sandboxHolderId;\n const heartbeatGroupId = sandboxGroupId;\n // P2.1 warm-meter (tick A): while a turn runs, the heartbeat is also the\n // warm-seconds tick. GROUP+epoch+tick keyed (one box = one stream, shared\n // box metered once); epoch-fenced (a stale tick no-ops). Warm-cost is\n // metered when a per-backend rate is configured. Best-effort: a metering\n // failure must never fail the turn.\n //\n // Keyed off the EFFECTIVE backend (Stage D): a machine-primary turn has NO\n // Modal box, so it must accrue ZERO cloud warm-seconds — `selfhosted` has no\n // configured warm rate (0). Keying off turn.sandboxBackend (modal) would bill\n // cloud seconds for a box that does not exist (a real money bug). Non-machine\n // turns fall back to groupBoxBackend (the REAL box that ran): for a machine-\n // home turn that degraded to the cloud group box (swap-away / flag-off), that\n // is the deployment default (modal), so the fallback box is warm-metered at\n // the cloud rate instead of selfhosted's rate-0 (which would under-bill).\n const warmRate = sandboxWarmRateMicrosPerSecond(\n settings,\n warmBackend ?? (sandbox.established.backendId as Settings[\"sandboxBackend\"]),\n );\n leaseHeartbeatTimer = setInterval(() => {\n void heartbeatLeaseHolder(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: heartbeatGroupId,\n kind: \"turn\",\n holderId: heartbeatHolderId,\n leaseTtlMs: settings.sandboxLeaseTtlMs,\n expectedEpoch: heartbeatEpoch,\n })\n .then(async (alive) => {\n if (alive || rotationInFlight || sandboxRotationController.signal.aborted) return;\n const rotatingLease = await readLease(db, input.workspaceId, heartbeatGroupId).catch(\n () => null,\n );\n if (\n !rotatingLease ||\n rotatingLease.leaseEpoch !== heartbeatEpoch ||\n rotatingLease.instanceId !== sandbox.established.instanceId ||\n rotatingLease.rotationRequestedAt === null\n ) {\n // The holder was reaped, the exact attempt closed, the epoch was\n // superseded, or the lease began draining. Do not leave a dead\n // interval issuing DB writes and snapshot probes forever.\n stopLeaseHeartbeat();\n return;\n }\n rotationInFlight = (async () => {\n // Rotation admission already fenced all new workspace mutations.\n // Wait for an earlier periodic capture, then produce the exact\n // generation-complete checkpoint that licenses aborting this run.\n if (snapshotInFlight) {\n await waitForWarmSnapshot(\n snapshotInFlight,\n settings.sandboxSnapshotTimeoutMs,\n cancellationSignal,\n );\n }\n const snapshotSession = setupBoxSession;\n const snapshotTurnId = turnId;\n if (snapshotSession && snapshotTurnId) {\n await maybePersistWarmWorkspaceSnapshot(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: snapshotTurnId,\n attemptId: input.attemptId,\n sandboxGroupId: heartbeatGroupId,\n },\n snapshotSession,\n heartbeatEpoch,\n cancellationSignal,\n true,\n );\n }\n const checkpointed = await readLease(db, input.workspaceId, heartbeatGroupId);\n if (\n checkpointed?.leaseEpoch === heartbeatEpoch &&\n checkpointed.rotationRequestedAt !== null &&\n checkpointed.archiveComplete &&\n !cancellationSignal?.aborted\n ) {\n sandboxRotationController.abort(\n new SandboxDeadlineRotationError(heartbeatGroupId, heartbeatEpoch),\n );\n }\n })()\n .catch((error) => {\n observability.warn(\"sandbox deadline rotation checkpoint failed; retrying\", {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n sandboxGroupId: heartbeatGroupId,\n leaseEpoch: heartbeatEpoch,\n error: error instanceof Error ? error.message : String(error),\n });\n })\n .finally(() => {\n rotationInFlight = null;\n });\n await rotationInFlight;\n })\n .catch(() => undefined);\n void accrueWarmSeconds(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: heartbeatGroupId,\n expectedEpoch: heartbeatEpoch,\n warmRateMicrosPerSecond: warmRate,\n subjectId: input.sessionId,\n })\n .then((result) => recordCreditMicros(observability, \"usage\", result.costMicros))\n .catch(() => undefined);\n // MID-SESSION snapshot (sandbox-file-persistence): while the turn holds\n // the box, fold a fresh /workspace snapshot onto the lease every\n // sandboxSnapshotIntervalMs, so a box death the reaper never sees\n // (Modal hard timeout mid-busy, OOM, infra) costs at most one interval\n // of work — a legit multi-day turn is otherwise completely unprotected\n // (the reaper only drain-persists IDLE leases). Uses the UN-proxied box\n // session (setupBoxSession): the routing veneer could swap mid-op and a\n // selfhosted target has no persistWorkspace anyway. Best-effort +\n // single-flight; throttling lives in the helper.\n const snapshotSession = setupBoxSession;\n const snapshotTurnId = turnId;\n if (snapshotSession && snapshotTurnId && !snapshotInFlight && !turnEndCaptureInProgress) {\n snapshotInFlight = maybePersistWarmWorkspaceSnapshot(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: snapshotTurnId,\n attemptId: input.attemptId,\n sandboxGroupId: heartbeatGroupId,\n },\n snapshotSession,\n heartbeatEpoch,\n activityContext?.cancellationSignal,\n )\n .then(async (persisted) => {\n if (persisted && publish) {\n await publish([\n {\n type: \"sandbox.box.snapshot\",\n payload: { trigger: \"heartbeat\" },\n },\n ]);\n }\n })\n .catch(() => undefined)\n .finally(() => {\n snapshotInFlight = null;\n });\n }\n }, 10_000);\n if (\"unref\" in leaseHeartbeatTimer && typeof leaseHeartbeatTimer.unref === \"function\") {\n leaseHeartbeatTimer.unref();\n }\n };\n const maybeStartOnTurnRecording = async (\n sandbox: ResumedTurnSandbox,\n effectiveBackend: Settings[\"sandboxBackend\"] | undefined,\n ): Promise<void> => {\n if (activeRecording) {\n return;\n }\n if (computerUseRecordingStart) {\n await computerUseRecordingStart;\n return;\n }\n // Called only by the runtime's first-computer-action hook. Plain sandbox\n // operations never start ffmpeg and never boot a display merely to record\n // an unused desktop. Recording failure never fails the computer action.\n if (\n shouldStartOnTurnRecording({\n recordingEnabled: settings.recordingEnabled,\n desktopEnabled: settings.sandboxDesktopEnabled,\n establishedBackendId: sandbox.established.backendId,\n // EFFECTIVE (active) backend, not the session home: a machine-primary turn\n // resolves to \"selfhosted\" and skips; a swap back to the cloud group box\n // resolves to undefined and records as before.\n effectiveBackend,\n })\n ) {\n computerUseRecordingStart = (async () => {\n let begun: Awaited<ReturnType<typeof beginRecording>> | null = null;\n try {\n begun = await beginRecording({\n settings,\n db,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turnId!,\n recordingId: randomUUID(),\n mode: \"on-turn\",\n session: sandbox.established.session,\n runAs: sandboxRunAs(settings),\n reason: null,\n });\n if (!publish) {\n throw new Error(\"recording started before the turn event publisher was ready\");\n }\n await publish([{ type: \"recording.started\", payload: begun.started }]);\n activeRecording = begun.active;\n } catch (recordingError) {\n activeRecording = null;\n if (begun) {\n await discardUnpublishedRecording({\n db,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n active: begun.active,\n session: sandbox.established.session,\n });\n }\n console.error(\n \"computer-use recording start failed (action outcome unaffected)\",\n safeErrorDiagnostic(recordingError),\n );\n }\n })();\n await computerUseRecordingStart;\n }\n };\n // Dual-write of conversation truth (issue #35): completed items are\n // reconciled into session_history_items after every model response and at\n // every turn-end path (idempotent on position), and the sandbox recovery\n // envelope is upserted alongside. Best-effort by design: persistence\n // problems must never fail the run.\n //\n // Orphaned-tool-output guard: `stream.state.history` is NOT a plain\n // append-only array — it is a computed getter\n // (`getTurnInput(originalInput, generatedItems)`) that runs the SDK's\n // `dropOrphanToolCalls` on every access, so a `function_call` with no\n // settling result yet is transiently ABSENT from history and a later\n // reconcile sees a DIFFERENT, shorter/reordered list. A blind length\n // watermark with onConflictDoNothing-on-position then freezes the first\n // shape of a position and can persist a `function_call_result` at a tail\n // position while its `function_call` was pruned away in an earlier slice\n // and never written — the orphan that bricks the session. We defend against\n // it at the stream boundary with the turn-scoped pending-tool ledger. A\n // partial parallel batch records raw results but does not call this\n // reconciler. Once every registered call has a result, the SDK history is\n // stable and this scalar append watermark is valid again. The sanitizer\n // remains the final call/result pairing guard for every other reconcile.\n let persistedHistoryCount = 0;\n let providerArtifactCandidates: Awaited<\n ReturnType<typeof turnInput>\n >[\"providerArtifactCandidates\"] = {\n knownHistoryItemIds: [],\n historyItemIds: [],\n };\n // Next free WHOLE-NUMBER absolute position to append at. Tracked separately\n // from persistedHistoryCount (the in-memory slice index) because a compaction\n // inserts a fractional summary position, so total rows no longer equal\n // max(position)+1 and the slice index can no longer double as the position.\n let nextHistoryPosition = 0;\n const reconcileConversationTruth = async (\n options: { skipInputOnlyRows?: boolean; requireDurable?: boolean } = {},\n ) => {\n if (!stream || !turnId) {\n return;\n }\n try {\n const rawHistory = (stream.state as { history?: unknown[] }).history;\n if (Array.isArray(rawHistory)) {\n const { rows, nextWatermark, nextPosition } = historyRowsToAppend(\n rawHistory as Array<Record<string, unknown>>,\n persistedHistoryCount,\n nextHistoryPosition,\n modelRunSettings.modelToolOutputTruncationTokens,\n (value) => redact(value),\n );\n const hasModelOrToolProgress = rows.some((row) =>\n isModelOrToolProgressHistoryItem(row.item),\n );\n const shouldAppendRows =\n rows.length > 0 && (!options.skipInputOnlyRows || hasModelOrToolProgress);\n if (shouldAppendRows) {\n const appended = await appendSessionHistoryItems(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n expectedExecutionGeneration: executionGeneration,\n expectedAttemptId: input.attemptId,\n modelToolOutputTruncationTokens: modelRunSettings.modelToolOutputTruncationTokens,\n items: rows,\n });\n if (!appended) {\n throw new TurnAttemptFencedError(\n \"turn execution generation was fenced while saving conversation history\",\n );\n }\n }\n if (shouldAppendRows || !options.skipInputOnlyRows) {\n persistedHistoryCount = nextWatermark;\n nextHistoryPosition = nextPosition;\n }\n }\n const envelope = sandboxStateEntryFromRunState(stream.state);\n if (envelope) {\n await upsertSandboxSessionEnvelope(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n envelope,\n });\n }\n } catch (persistError) {\n console.error(\n \"session history dual-write failed (run unaffected)\",\n safeErrorDiagnostic(persistError, (value) => String(redact(value))),\n );\n if (options.requireDurable) throw persistError;\n }\n };\n // Reassigned after the variable set loads; the publish closure is\n // created (and used for turn.started) before the variableSet is available.\n // Generic auth/cookie/signed-URL/token classification is active before any\n // exact run-secret provenance is available. Registered values strengthen\n // this boundary as credentials are resolved and renewed during the turn.\n let redact: (payload: unknown) => unknown = createSecretRedactor([]);\n const secretRedactions = new Map<string, string>();\n const publishedRunCredentialNotices = new Set<string>();\n const registerSecretRedactions = (secrets: SecretForRedaction[]): void => {\n for (const secret of secrets) {\n if (!secretRedactions.has(secret.value)) secretRedactions.set(secret.value, secret.name);\n }\n redact = createSecretRedactor(\n [...secretRedactions].map(([value, name]) => ({ name, value })),\n );\n };\n let variableSetId = \"\";\n // Rig telemetry (M3): set once the session loads; empty string for a rig-less\n // turn (mirrors variableSetId). Read by the activity span's finally block.\n let rigId = \"\";\n let rigVersionId = \"\";\n // The Codex account this turn runs on (pin > workspace active), resolved once\n // a codex-billed turn is confirmed and threaded into the token resolver below.\n let effectiveCodexCredentialId: string | null = null;\n // The session's Codex credential BEFORE this turn resolved its own — captured\n // before recordSessionActiveCodexCredential overwrites the durable pointer, so\n // a per-call usage log can report whether the serving account CHANGED since the\n // session's previous call (the prompt-cache account-switch hypothesis).\n let priorSessionCodexCredentialId: string | null = null;\n // The latest usage-header snapshot scraped for free\n // off this turn's `/codex/responses` responses (a turn issues many model calls;\n // latest wins). Flushed ONCE into the P2 usage cache for the serving account in\n // the `finally` — cheaper than a /wham/usage poll AND it self-heals P3 rotation\n // (the proactive + 429 rankers read these exact columns). null ⇒ nothing scraped.\n // Hoisted to activity scope so the finally flush (below) sees it. The sink is\n // wired into codexContext.onUsageHeaders inside the try.\n let latestCodexUsage: CodexUsageHeaderSnapshot | null = null;\n let lastCodexRequestOpaqueArtifacts: readonly string[] = [];\n // Hoisted for same-turn recovery: an approval-decision rerun must\n // re-enter through the approval resume path (its frozen mid-flight state\n // only exists in the RunState blob), never through a swapped trigger.\n let triggerType: string | null = null;\n try {\n const mcpSettings = await settingsWithEnabledCapabilityMcpServers(\n db,\n input.workspaceId,\n settings,\n );\n // Read the active-credential flag once for the runtime capability overlay.\n // Accepted billing/provider identity comes from the turn policy below,\n // never from this mutable health snapshot.\n const codexSubscriptionActive = await workspaceCodexSubscriptionActive(\n db,\n mcpSettings,\n input.workspaceId,\n );\n const codexSettings = await settingsWithCodexCredential(\n db,\n input.workspaceId,\n mcpSettings,\n codexSubscriptionActive,\n );\n const capabilitySettings = await settingsWithWorkspaceGatewayCredential(\n db,\n input.workspaceId,\n codexSettings,\n );\n const codexAppsCredentialId = capabilitySettings.codexConnectedAppsEnabled\n ? await resolveCodexAppsCredentialIdForRun(db, input.workspaceId)\n : null;\n runtime.configure(capabilitySettings);\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n const claim = await claimSessionWorkForAttempt(db, input.workspaceId, {\n sessionId: input.sessionId,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n attemptId: input.attemptId,\n dispatchId,\n trigger: input.trigger,\n });\n if (claim.action === \"unclaimed\") {\n activityStatus = \"unclaimed\";\n return { status: \"unclaimed\", reason: claim.reason };\n }\n const turn = claim.turn;\n turnId = turn.id;\n executionGeneration = turn.executionGeneration;\n providerRecoveryCount = providerRecoveryCountFromMetadata(turn.metadata);\n const claimedPolicy = readTurnExecutionPolicyV1(turn.metadata);\n const policyForAbsent =\n claimedPolicy.kind === \"valid\"\n ? claimedPolicy.policy\n : resolveTurnExecutionPolicyV1(capabilitySettings, legacyTurnExecutionPolicyInput(turn));\n const installedPolicy = await installOrReadTurnExecutionPolicyForAttempt(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n executionGeneration,\n attemptId: input.attemptId,\n policyForAbsent,\n });\n if (!installedPolicy.accepted) {\n throw new TurnAttemptFencedError(\n `turn execution policy was fenced: ${installedPolicy.reason}`,\n );\n }\n const verifiedExecutionPolicy = assertTurnExecutionPolicyMatchesConfigV1(\n capabilitySettings,\n installedPolicy.policy,\n {\n modelId: turn.model,\n reasoningEffort: turn.reasoningEffort,\n latencyMode: turn.latencyMode,\n },\n );\n const turnExecutionPolicy = verifiedExecutionPolicy.policy;\n assertSessionAllowsProductModel(session, turnExecutionPolicy.productModelId);\n const billingIdentity = turnExecutionPolicyBillingIdentity(turnExecutionPolicy);\n isExternallyBilledTurn = billingIdentity.externallyBilled;\n isCodexTurn = billingIdentity.codexSubscription;\n triggerEventId = turn.triggerEventId;\n const trigger = await getSessionEvent(db, input.workspaceId, triggerEventId);\n if (!trigger) {\n throw new Error(`Trigger event not found: ${triggerEventId}`);\n }\n const humanInputResume = await getHumanInputResumeForEvent(\n db,\n input.workspaceId,\n input.sessionId,\n trigger,\n );\n triggerType = trigger.type;\n redispatchesAtDispatch = Number(\n (turn.metadata as { workerDeathRedispatches?: number } | null)?.workerDeathRedispatches ??\n 0,\n );\n turnLifecycleMetricsFor(observability).start(turnId);\n // §7.5 P3 — pass the accepted billing attribution (externally funded turns\n // bypass OpenGeni credit/token gates)\n // AND the optional host `entitlements` port (when bound, its admitRun replaces\n // the local credit read). Unset port → today's local-ledger path.\n await waitForTurnOperation(\n ensureRunAllowed(\n settings,\n db,\n input.accountId,\n input.workspaceId,\n isExternallyBilledTurn,\n entitlements,\n ),\n cancellationSignal,\n undefined,\n );\n // Setup (variableSet load, MCP connects, sandbox restore) does not\n // stream and so never observes cancellation on its own; these explicit\n // checks let a graceful shutdown checkpoint the turn before the worker is\n // force-killed instead of riding the setup to a heartbeat timeout.\n const throwIfWorkerShuttingDown = () => {\n const reason = activityContext?.cancellationSignal.reason;\n if (isWorkerShutdownCancellation(reason)) {\n throw reason;\n }\n };\n const throwIfTurnCancelled = () => throwIfTurnOperationCancelled(cancellationSignal);\n // ONE shared details object for every heartbeat this activity sends (each\n // site spreads it + its own phase), so cross-site fields — the op-stream\n // settled roster in particular — survive last-write-wins instead of being\n // clobbered by whichever site heartbeated most recently.\n const heartbeatDetails: TurnHeartbeatDetails = {\n phase: \"running\",\n sessionId: input.sessionId,\n turnId,\n opAcks: {},\n };\n const opJournal = makeTurnOpJournal(activityContext, heartbeatDetails);\n heartbeatTimer = startActivityHeartbeat(activityContext, heartbeatDetails);\n let producerSeq = 0;\n // One producer per activity execution, not per turn: a turn can run\n // again on the same workflow (recovery, approval rerun), and\n // each execution restarts producerSeq at 1 — a shared producer id would\n // trip the per-producer uniqueness constraint on the event log. The\n // Temporal activity id is unique per scheduled execution.\n const producerId = `${input.workflowId}:${turnId}${activityContext ? `:${activityContext.info.activityId}` : \"\"}`;\n // Unique per scheduled activity execution (Temporal activityId). Folded\n // into positional usage source keys so a re-dispatch of this turn does\n // not collide its model-call charges with the prior dispatch's. A genuine\n // activity retry reuses the same activityId, so its re-emitted calls keep\n // deduping (no double charge).\n // Local/tests have no Temporal activity id; still generate an execution-\n // unique holder so a second dispatch of the same durable turn fences this\n // one exactly like production.\n codexLeaseHolderId = dispatchId;\n const modelUsageDispatchId = activityContext?.info.activityId ?? dispatchId;\n const claimedModelUsageSourceKeys = new Set<string>();\n const emittedModelUsageSourceKeys = new Set<string>();\n publish = async (\n events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>,\n immediate = false,\n ) => {\n const inputs = events.map((event) => ({\n ...event,\n payload: redact(event.payload),\n turnId: turnId!,\n producerId,\n producerSeq: ++producerSeq,\n }));\n const appended = await appendAndPublishTurnEventsFenced(\n db,\n bus,\n input.workspaceId,\n input.sessionId,\n turnId!,\n executionGeneration,\n input.attemptId,\n inputs,\n );\n if (inputs.length > 0 && !appended.accepted) {\n throw new TurnAttemptFencedError(\"turn execution generation was fenced\");\n }\n activityContext?.heartbeat({\n ...heartbeatDetails,\n phase: \"events_published\",\n producerSeq,\n });\n if (immediate) {\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n }\n return appended;\n };\n settle = async (inputSettlement) => {\n const attemptClosing = [\"completed\", \"failed\", \"cancelled\", \"requires_action\"].includes(\n inputSettlement.turnStatus,\n );\n const recordingForSettlement =\n attemptClosing && activeRecording && resolvedSandbox\n ? (activeRecording as ActiveRecording)\n : null;\n const preparedRecording = recordingForSettlement\n ? await prepareRecordingForSettlement({\n settings,\n objectStorage,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n active: recordingForSettlement,\n session: resolvedSandbox!.established.session,\n didComputerUse,\n })\n : null;\n let recordingMutation: SessionTurnRecordingSettlement | undefined;\n if (preparedRecording) {\n const mutation = preparedRecording.mutation;\n recordingMutation =\n mutation.action === \"discard\"\n ? mutation\n : {\n ...mutation,\n producerId,\n producerSeq: ++producerSeq,\n };\n }\n const compactionRequestFailure = inputSettlement.consumeRequestedCompactionFailure\n ? {\n reason: \"summarization_failed\" as const,\n producerId,\n producerSeq: ++producerSeq,\n }\n : undefined;\n const inputs = inputSettlement.events.map((event) => ({\n ...event,\n payload: redact(event.payload),\n turnId: turnId!,\n producerId,\n producerSeq: ++producerSeq,\n }));\n const redactedRunState = inputSettlement.runState\n ? (redact(inputSettlement.runState) as typeof inputSettlement.runState)\n : undefined;\n const result = await applySessionTurnSettlement(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: turnId!,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n turnStatus: inputSettlement.turnStatus,\n sessionStatus: inputSettlement.sessionStatus,\n activeTurnId: inputSettlement.activeTurnId,\n events: inputs,\n ...(redactedRunState ? { runState: redactedRunState } : {}),\n ...(recordingMutation ? { recording: recordingMutation } : {}),\n ...(compactionRequestFailure ? { compactionRequestFailure } : {}),\n });\n if (result.action === \"stale\") {\n // The terminal write can lose to a control transaction before the\n // workflow delivers Temporal cancellation. That control may settle\n // the already-closed attempt as rejected_stale, so returning without\n // this flag would strand its replacement behind quiesced_at forever.\n // Enter the same hard tool-fence/receipt path as an explicit\n // TurnAttemptFencedError. If ownership was lost for an unrelated\n // reason, allowUninterrupted makes the receipt transaction a no-op.\n acknowledgeLostAttemptOwnership();\n if (recordingForSettlement) {\n await abandonActiveRecording(\n \"recording settlement lost attempt ownership\",\n preparedRecording?.mutation.action === \"discard\" ? \"discard\" : \"failed\",\n );\n }\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return false;\n }\n if (recordingForSettlement && preparedRecording) {\n if (result.recordingMutationApplied) {\n activeRecording = null;\n if (preparedRecording.deleteArtifactsAfterCommit) {\n await deleteRecordingArtifacts(\n resolvedSandbox!.established.session,\n recordingForSettlement.proc,\n );\n }\n } else {\n await abandonActiveRecording(\"recording row was unavailable during turn settlement\");\n }\n }\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, result.events);\n activityContext?.heartbeat({\n ...heartbeatDetails,\n phase: \"events_published\",\n producerSeq,\n });\n return true;\n };\n activityContext?.heartbeat({\n ...heartbeatDetails,\n phase: \"turn_started\",\n });\n\n // A shutdown that landed during claim/billing setup stops before the turn\n // visibly starts: nothing ran yet, so the same inference starts cleanly\n // on a healthy worker.\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n if (\n !(await settle({\n events: [\n { type: \"session.status.changed\", payload: { status: \"running\" } },\n {\n type: \"turn.started\",\n payload: { triggerEventId },\n },\n ],\n turnStatus: \"running\",\n sessionStatus: \"running\",\n activeTurnId: turnId,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnStartedPublished = true;\n\n // Multi-account (P1): resolve the effective Codex account for this turn\n // (session-pin > workspace active) and stamp it on the session so the\n // in-session \"Running on:\" indicator reflects reality. Emit a switch event\n // when it changed from the prior run's account so the pill flips live.\n // Gated on the codex-billed predicate — non-codex turns never touch this.\n if (isCodexTurn) {\n const sessionCodex = await getSessionCodexState(db, input.workspaceId, input.sessionId);\n const sessionPin = sessionCodex?.pinnedCredentialId ?? null;\n const sessionPinSource = sessionCodex?.pinSource ?? null;\n const selectForTurn = (context: CodexCredentialLeaseSelectionContext) =>\n selectCodexCredentialLeaseForTurn({\n context,\n leasingEnabled: settings.codexCredentialLeasingEnabled,\n sessionId: input.sessionId,\n sessionPinnedCredentialId: sessionPin,\n sessionPinSource,\n sessionLastCredentialId: sessionCodex?.lastCredentialId ?? null,\n now: new Date(),\n });\n\n // Rollout/rollback path is intentionally table-inert. With the flag off,\n // old and new workers both use legacy pin > active-pointer selection and\n // neither reads nor writes the additive lease/cursor schema.\n let leased: CodexCredentialLeaseResult<RotationDecision>;\n let leaseAcquisitionStartedAtMs: number | null = null;\n if (settings.codexCredentialLeasingEnabled) {\n leaseAcquisitionStartedAtMs = performance.now();\n leased = await acquireCodexCredentialLease(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n turnId,\n holderId: codexLeaseHolderId,\n advanceActivePointer: sessionPin === null,\n },\n selectForTurn,\n );\n } else {\n const [rotation, accounts] = await Promise.all([\n getCodexRotationSettings(db, input.workspaceId),\n listCodexAccountStatuses(db, input.workspaceId),\n ]);\n const leaseAccounts = accounts.map((account) => ({\n ...account,\n activeLeaseCount: 0,\n selectionCount: 0,\n lastSelectedAt: null,\n }));\n const activeCredentialId = rotation?.activeCredentialId ?? null;\n const selected = selectForTurn({\n accounts: leaseAccounts,\n activeCredentialId,\n rotationEnabled: rotation?.rotationEnabled ?? false,\n leaseRotationEnabled: false,\n rotationStrategy: rotation?.rotationStrategy ?? \"most_remaining\",\n existingCredentialId: null,\n policyScope: null,\n unavailableDiagnostics: [],\n });\n leased = {\n ...selected,\n accounts: leaseAccounts,\n activeCredentialId,\n rotationEnabled: rotation?.rotationEnabled ?? false,\n rotationStrategy: rotation?.rotationStrategy ?? \"most_remaining\",\n reused: false,\n holderId: null,\n generation: null,\n leasedUntil: null,\n unavailableDiagnostics: [],\n advanceActivePointer: selected.advanceActivePointer !== false,\n };\n }\n if (leased.decision.kind === \"allCapped\") {\n // Bounded self-heal of stale usage cache, then ONE new atomic selection.\n await refreshCappedCodexUsageRows(db, settings, input.workspaceId, leased.accounts, {\n signalCodexCapacityWorkflow,\n wakeSessionWorkflow,\n });\n if (settings.codexCredentialLeasingEnabled) {\n leaseAcquisitionStartedAtMs = performance.now();\n leased = await acquireCodexCredentialLease(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n turnId,\n holderId: codexLeaseHolderId,\n advanceActivePointer: sessionPin === null,\n },\n selectForTurn,\n );\n } else {\n const [rotation, accounts] = await Promise.all([\n getCodexRotationSettings(db, input.workspaceId),\n listCodexAccountStatuses(db, input.workspaceId),\n ]);\n const leaseAccounts = accounts.map((account) => ({\n ...account,\n activeLeaseCount: 0,\n selectionCount: 0,\n lastSelectedAt: null,\n }));\n const selected = selectForTurn({\n accounts: leaseAccounts,\n activeCredentialId: rotation?.activeCredentialId ?? null,\n rotationEnabled: rotation?.rotationEnabled ?? false,\n leaseRotationEnabled: false,\n rotationStrategy: rotation?.rotationStrategy ?? \"most_remaining\",\n existingCredentialId: null,\n policyScope: null,\n unavailableDiagnostics: [],\n });\n leased = {\n ...selected,\n accounts: leaseAccounts,\n activeCredentialId: rotation?.activeCredentialId ?? null,\n rotationEnabled: rotation?.rotationEnabled ?? false,\n rotationStrategy: rotation?.rotationStrategy ?? \"most_remaining\",\n reused: false,\n holderId: null,\n generation: null,\n leasedUntil: null,\n unavailableDiagnostics: [],\n advanceActivePointer: selected.advanceActivePointer !== false,\n };\n }\n }\n const rotationDecision = leased.decision;\n const selectedPinDisposition = classifyCodexPin({\n pinnedCredentialId: sessionPin,\n pinSource: sessionPinSource,\n strategy: leased.rotationStrategy as CodexRotationStrategy,\n rotationEnabled: leased.rotationEnabled,\n });\n // pin policy pin persistence follows the atomic credential allocator selection. The selector\n // already ran exact-turn reuse before policy filtering and vetoed pointer\n // movement for manual/policy homes; this write only records the NEXT turn's\n // policy home (or clears a policy pin whose strategy is no longer active).\n if (\n selectedPinDisposition === \"sharded\" &&\n leased.credentialId !== null &&\n (sessionPinSource !== \"policy\" || sessionPin !== leased.credentialId)\n ) {\n const pinMutation = await withCodexCapacityMutation(\n db,\n {\n workspaceId: input.workspaceId,\n reason: \"codex_policy_pin_changed\",\n },\n async (tx) => {\n const changed = await setSessionCodexPin(\n tx,\n input.workspaceId,\n input.sessionId,\n leased.credentialId,\n \"policy\",\n {\n expected: {\n pinnedCredentialId: sessionPin,\n pinSource: sessionPinSource,\n },\n },\n );\n return { result: changed, changed };\n },\n );\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n pinMutation.wakeTargets,\n );\n } else if (selectedPinDisposition === \"clearStale\") {\n const pinMutation = await withCodexCapacityMutation(\n db,\n {\n workspaceId: input.workspaceId,\n reason: \"codex_stale_policy_pin_cleared\",\n },\n async (tx) => {\n const changed = await setSessionCodexPin(\n tx,\n input.workspaceId,\n input.sessionId,\n null,\n \"policy\",\n {\n expected: {\n pinnedCredentialId: sessionPin,\n pinSource: sessionPinSource,\n },\n },\n );\n return { result: changed, changed };\n },\n );\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n pinMutation.wakeTargets,\n );\n }\n if (\n !settings.codexCredentialLeasingEnabled &&\n leased.advanceActivePointer &&\n sessionPin === null &&\n rotationDecision.kind === \"active\" &&\n rotationDecision.moved\n ) {\n await setActiveCodexCredential(db, input.workspaceId, rotationDecision.credentialId);\n }\n effectiveCodexCredentialId = leased.credentialId;\n codexLeaseGeneration = leased.generation;\n codexLeaseConfirmedUntilMs =\n leased.leasedUntil && leaseAcquisitionStartedAtMs !== null\n ? leaseAcquisitionStartedAtMs + CODEX_CREDENTIAL_LEASE_TTL_MS\n : null;\n codexLeaseHeld =\n effectiveCodexCredentialId !== null &&\n leased.holderId !== null &&\n leased.generation !== null &&\n codexLeaseConfirmedUntilMs !== null;\n if (codexLeaseHeld) startCodexLeaseHeartbeat();\n\n const actualOutcome = effectiveCodexCredentialId\n ? \"selected\"\n : rotationDecision.kind === \"allCapped\"\n ? \"waiting\"\n : \"none\";\n const actualReason = effectiveCodexCredentialId\n ? leased.reused\n ? \"lease_reused\"\n : sessionPin === effectiveCodexCredentialId\n ? \"pin\"\n : rotationDecision.kind === \"active\" && rotationDecision.moved\n ? \"rotation\"\n : \"active\"\n : rotationDecision.kind === \"allCapped\"\n ? \"all_capped\"\n : \"none\";\n const fencedInFlight = leased.reused;\n const shadowResult = await publishCodexFleetShadowDecisionV1({\n enabled: settings.codexFleetPolicyShadowEnabled,\n decision: {\n accounts: leased.accounts,\n actualCredentialId: effectiveCodexCredentialId,\n actualOutcome,\n actualReason,\n affinityCredentialId: fencedInFlight\n ? effectiveCodexCredentialId\n : (sessionPin ?? sessionCodex?.lastCredentialId ?? null),\n fencedInFlight,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\n now: new Date(),\n aliasSeed: randomUUID(),\n },\n publish,\n });\n if (shadowResult.outcome === \"published\") {\n const shadowPayload = shadowResult.payload;\n observability.incrementCounter({\n name: \"opengeni_codex_fleet_shadow_decisions_total\",\n help: \"Shadow decisions by bounded actual/shadow outcome and comparison.\",\n labels: codexFleetShadowDecisionMetricLabelsV1(shadowPayload),\n });\n observability.info(\"Codex adaptive fleet shadow decision\", {\n workspaceId: input.workspaceId,\n policyVersion: shadowPayload.replay.policyVersion,\n inputFingerprint: shadowPayload.replay.inputFingerprint,\n decisionFingerprint: shadowPayload.replay.decisionFingerprint,\n actualOutcome: shadowPayload.actual.outcome,\n shadowOutcome: shadowPayload.replay.decision.outcome,\n comparison: shadowPayload.comparison,\n candidateCount: shadowPayload.replay.input.candidates.length,\n truncatedCandidateCount: shadowPayload.replay.truncatedCandidateCount,\n payloadBytes: shadowResult.payloadBytes,\n });\n } else if (shadowResult.outcome === \"failed\") {\n // Shadow observability is explicitly non-authoritative. A malformed\n // snapshot or event-write fault must never change the authoritative lease,\n // capacity wait, failover, or the account serving this fenced turn.\n observability.incrementCounter({\n name: \"opengeni_codex_fleet_shadow_errors_total\",\n help: \"Shadow decision build/publication failures.\",\n labels: codexFleetShadowErrorMetricLabelsV1(shadowResult),\n });\n observability.warn(\"Codex adaptive fleet shadow decision failed open\", {\n workspaceId: input.workspaceId,\n stage: shadowResult.stage,\n reason: shadowResult.reason,\n errorName: shadowResult.errorName,\n payloadBytes: shadowResult.payloadBytes,\n });\n }\n\n const eligibleCount = leased.accounts.filter((account) =>\n isCodexCredentialEligible(account, new Date()),\n ).length;\n const poolDepth = eligibleCount === 0 ? \"zero\" : eligibleCount === 1 ? \"one\" : \"many\";\n observability.incrementCounter({\n name: \"opengeni_codex_pool_observations_total\",\n help: \"Observed eligible Codex pool depth buckets at turn selection.\",\n labels: { workspace_key: codexWorkspaceKey, depth: poolDepth },\n });\n if (eligibleCount <= 1) {\n observability.incrementCounter({\n name: \"opengeni_codex_pool_low_total\",\n help: \"Alert signal emitted when the eligible Codex pool is zero or one.\",\n labels: { workspace_key: codexWorkspaceKey, depth: poolDepth },\n });\n observability.warn(\"Codex eligible credential pool is low\", {\n workspaceId: input.workspaceId,\n eligibleCount,\n connectedCount: leased.accounts.length,\n depth: poolDepth,\n });\n }\n\n if (\n effectiveCodexCredentialId === null &&\n leased.accounts.length > 0 &&\n leased.accounts.every((account) => !account.allocatorEnabled) &&\n turnId\n ) {\n if (turn.source === \"compaction\") {\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.cancelled\",\n payload: {\n maintenance: \"context_compaction\",\n reason: \"codex_allocator_disabled\",\n requestPreserved: true,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"cancelled\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"cancelled\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\", deferredUntilWake: true });\n }\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId).catch(\n () => null,\n );\n const activeGoal = goal?.status === \"active\" ? goal : null;\n const armed = await armCodexCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n goalId: activeGoal?.id ?? null,\n goalVersion: activeGoal?.version ?? null,\n earliestResetAt: null,\n resetKind: \"bounded_refresh\",\n failurePayload: {\n error: \"All connected Codex subscriptions are disabled for new allocations.\",\n code: \"codex_allocator_disabled\",\n detail: \"waiting for a credential to be re-enabled, reconnected, or added\",\n },\n });\n if (armed.action === \"waiting\") {\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n armed.events,\n );\n turnMetricOutcome = \"recovering\";\n activityStatus = \"waiting_capacity\";\n return claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n waiterId: armed.waiter.id,\n generation: armed.waiter.generation,\n nextCheckAt: armed.waiter.nextCheckAt.toISOString(),\n wakeRevision: armed.waiter.wakeRevision,\n },\n });\n }\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: \"All connected Codex subscriptions are disabled for new allocations.\",\n code: \"codex_allocator_disabled\",\n retryable: false,\n recovery: \"user_message\",\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n\n if (rotationDecision.kind === \"allCapped\" && turnId) {\n if (turn.source === \"compaction\") {\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.cancelled\",\n payload: {\n maintenance: \"context_compaction\",\n reason: \"codex_capacity_unavailable\",\n requestPreserved: true,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"cancelled\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"cancelled\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\", deferredUntilWake: true });\n }\n // Every eligible account is capped/cooling (and a usage refresh did NOT\n // surface a reset): idle the turn AT THE BOUNDARY (no wasted model/sandbox\n // build) until the EARLIEST reset across all accounts — the multi-account\n // generalization of #143's single-account idle-until-reset. No saveRunState:\n // no model ran, nothing to freeze.\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId).catch(\n () => null,\n );\n const goalActive = Boolean(goal && goal.status === \"active\");\n // BOUNDED + POSITIVE: clamp to [MIN_IDLE_MS, max] so a null/elapsed/unknown\n // reset can never yield a 0 (which session.ts would treat as \"continue now\",\n // re-entering this path in a tight CPU/DB-hammering loop).\n const resumeMs = computeIdleDelayMs(\n rotationDecision.earliestResetAt,\n new Date(),\n CODEX_USAGE_LIMIT_MAX_RESUME_MS,\n );\n const failurePayload = codexUsageLimitFailurePayload(\n { resetsInSeconds: Math.ceil(resumeMs / 1000) },\n \"all connected Codex subscriptions are rate-limited\",\n { allAccounts: true },\n );\n const authoritativeResetAt = authoritativeCodexCapacityResetAt(\n leased.accounts,\n new Date(),\n );\n const armed = await armCodexCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n goalId: goalActive && goal ? goal.id : null,\n goalVersion: goalActive && goal ? goal.version : null,\n earliestResetAt: authoritativeResetAt,\n resetKind: authoritativeResetAt ? \"authoritative\" : \"bounded_refresh\",\n failurePayload,\n });\n if (armed.action === \"waiting\") {\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n armed.events,\n );\n turnMetricOutcome = \"recovering\";\n activityStatus = \"waiting_capacity\";\n return claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n waiterId: armed.waiter.id,\n generation: armed.waiter.generation,\n nextCheckAt: armed.waiter.nextCheckAt.toISOString(),\n wakeRevision: armed.waiter.wakeRevision,\n },\n });\n }\n if (\n !(await settle!({\n events: [\n // `rotated:true` (Finding 2): the proactive all-capped wait is the SAME\n // rotation-wait state as the reactive all-capped path, so it must freeze\n // autoContinuations identically (evaluateGoalContinuation reads this marker)\n // — a goal waiting out a long reset must not burn its continuation budget on\n // the proactive path while the reactive path spares it.\n {\n type: \"turn.failed\",\n payload: {\n ...failurePayload,\n recovery: goalActive ? \"goal_continuation\" : \"user_message\",\n rotated: true,\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n // idleUntilReset marks this a MANDATORY hold: session.ts must wait the full\n // resumeMs even if a future change made it 0 — never a tight re-dispatch.\n return claimedResult(\n goalActive\n ? {\n status: \"idle\",\n continueDelayMs: resumeMs,\n idleUntilReset: true,\n }\n : { status: \"idle\" },\n );\n }\n if (effectiveCodexCredentialId) {\n const priorAccountId = sessionCodex?.lastCredentialId ?? null;\n await recordSessionActiveCodexCredential(\n db,\n input.workspaceId,\n input.sessionId,\n effectiveCodexCredentialId,\n );\n if (priorAccountId !== effectiveCodexCredentialId) {\n const rotated = rotationDecision.kind === \"active\" && rotationDecision.moved;\n await publish([\n {\n type: \"codex.account.switched\",\n payload: {\n fromAccountId: priorAccountId,\n toAccountId: effectiveCodexCredentialId,\n reason: rotated ? \"rotation\" : \"manual\",\n },\n },\n ]);\n }\n\n const selectionReason = leased.reused\n ? \"lease_reused\"\n : sessionPin === effectiveCodexCredentialId\n ? \"pin\"\n : rotationDecision.kind === \"active\" && rotationDecision.moved\n ? \"rotation\"\n : \"active\";\n observability.incrementCounter({\n name: \"opengeni_codex_credential_selections_total\",\n help: \"Codex credential selections by strategy and reason.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n strategy: leased.rotationStrategy,\n reason: selectionReason,\n },\n });\n await publish([\n {\n type: \"codex.credential.selected\",\n payload: {\n credentialId: effectiveCodexCredentialId,\n strategy: leased.rotationStrategy,\n reason: selectionReason,\n eligibleCount,\n connectedCount: leased.accounts.length,\n reused: leased.reused,\n },\n },\n ]);\n }\n }\n\n // Pack-scoped runtime: enabled packs may declare the sandbox image this\n // workspace's sessions run in and skills for the sandbox skill index.\n // Resolved after turn.started so a composition conflict (two enabled\n // packs declaring images) fails the turn with its plain error instead\n // of failing the activity opaquely.\n const [packRuntime, skillLibraryRuntime] = await Promise.all([\n resolveWorkspacePackRuntime(db, input.workspaceId),\n resolveWorkspaceSkillLibraryRuntime(db, input.workspaceId),\n ]);\n // RIG BINDING (M3): load the session's FROZEN rig version (resolved+frozen\n // at create). Everything rig-derived below (image precedence, env default\n // sets, setup hook, credential hooks, doctrine, lease/telemetry stamps) is\n // gated on this being non-null, so a rig-less session takes a zero-cost\n // branch that is byte-for-byte today's turn. Both ids are frozen together;\n // a defensive null (e.g. a since-deleted rig FK-nulled the columns) simply\n // runs the turn rig-less.\n const rigVersion =\n session.rigId && session.rigVersionId\n ? await getRigVersion(db, input.workspaceId, session.rigId, session.rigVersionId)\n : null;\n // Rig display name for the doctrine block + setup events/errors (only on a\n // rig-bound turn; null-safe fallback keeps the turn alive if the rig row is\n // gone). Loaded once here alongside the version.\n const rigName =\n rigVersion && session.rigId\n ? ((await getRigName(db, input.workspaceId, session.rigId)) ?? \"rig\")\n : null;\n // Telemetry: stamp the frozen rig binding (empty for a rig-less turn).\n rigId = session.rigId ?? \"\";\n rigVersionId = session.rigVersionId ?? \"\";\n // Workspace tier of the agent-persona resolution (session > workspace >\n // deployment default). null means the workspace has no override, so the\n // runtime falls back to runSettings.agentInstructionsTemplate (the\n // deployment default, byte-identical to the historical preamble).\n const governanceClaims = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: turn.executionGeneration,\n };\n const [workspaceAgentInstructions, instructionPolicySnapshot, preferenceSnapshot] =\n await Promise.all([\n resolveWorkspaceAgentInstructions(db, input.workspaceId),\n getOrCreateWorkspaceInstructionPolicySnapshot(db, governanceClaims),\n getOrCreatePreferenceRegistrySnapshot(db, governanceClaims).catch((error) => {\n if (error instanceof PreferenceRegistryInitiatorError) return null;\n throw error;\n }),\n ]);\n const workspaceGovernance = renderWorkspaceGovernanceContext({\n instructionPolicy: instructionPolicySnapshot,\n preferences: preferenceSnapshot,\n });\n const structuredWorkspacePolicyActive =\n hasActiveWorkspaceInstructionPolicy(instructionPolicySnapshot);\n const workspaceMemory = await resolveWorkspaceMemoryBlock(db, input.workspaceId);\n const baseRunSettings = {\n // IMAGE PRECEDENCE (M3): rig > pack > deployment. settingsWithRigImage runs\n // OUTERMOST so a rig-pinned image overrides both the pack image and the\n // deployment default; a rig with no image (or a rig-less turn) is a\n // pass-through, leaving the pack/deployment chain exactly as today.\n ...settingsWithRigImage(\n settingsWithPackSandboxImage(\n capabilitySettings,\n packRuntime.sandboxImage,\n packRuntime.sandboxProviderImages,\n ),\n rigVersion?.image ?? null,\n ),\n openaiModel: turn.model,\n openaiReasoningEffort: turn.reasoningEffort,\n sandboxBackend: turn.sandboxBackend,\n };\n const sessionMcpHeaderNames = new Map<string, readonly string[]>();\n const runSettings = await settingsWithSessionMcpServersForRun(\n db,\n input.workspaceId,\n input.sessionId,\n input.attemptId,\n baseRunSettings,\n {\n onResolvedServers: (servers) => {\n for (const server of servers) {\n sessionMcpHeaderNames.set(server.id, server.headerNames);\n }\n },\n },\n );\n registerSecretRedactions([\n ...(runSettings.accessKey\n ? [{ name: \"OPENGENI_ACCESS_KEY\", value: runSettings.accessKey }]\n : []),\n ...runSettings.mcpServers.flatMap((server) => {\n return headerSecretRedactions(\n `MCP_${server.id.toUpperCase()}_STATIC`,\n server.headers,\n sessionMcpHeaderNames.get(server.id),\n );\n }),\n ]);\n // Multi-provider per-turn routing → the provider gating (compaction mode,\n // hosted web search, encrypted reasoning, context window) the agent and\n // compaction summarizer must use; null falls back to the legacy global\n // client. Resolve against `capabilitySettings` (whose openaiModel is the\n // deployment default), NOT `runSettings`: runSettings.openaiModel is the\n // turn's model, so for a turn ON a registry model the built-in provider\n // would otherwise claim that id (configuredModels builds the built-in's\n // models from openaiModel) and shadow the registry entry — resolving the\n // turn to the built-in (Azure) gating while the global model router routes\n // the name to its registry provider. That mismatch attaches web_search to\n // a chat-only Fireworks model. Resolving against the default-model settings\n // keeps gating consistent with the router. Cost accounting covers registry\n // models via configuredModelPricing.\n const resolvedModel = runtime.resolveTurnModel(\n capabilitySettings,\n turnExecutionPolicy.productModelId,\n );\n const supportsImageInput = modelSupportsImageInputForTurn(resolvedModel);\n const providerApi = resolvedModel?.provider.api ?? \"responses\";\n const modelInputPolicy = modelAttachmentInputPolicyForTurn(resolvedModel);\n const attachmentProjector = createModelHistoryAttachmentProjector(\n db,\n input.workspaceId,\n modelInputPolicy,\n objectStorage ? (file) => objectStorage.getFileBytes(file) : undefined,\n );\n const modelHistoryProjector = async (items: Array<Record<string, unknown>>) =>\n projectModelInputForCapabilities(await attachmentProjector(items), modelInputPolicy);\n const compactionModelHistoryProjector = async (items: Array<Record<string, unknown>>) =>\n await modelHistoryProjector(projectHistoryForProvider(items, providerApi));\n const selectedProvider = resolvedModel?.provider;\n const publicProviderHeaders = new Set(\n selectedProvider?.publicDefaultHeaderNames?.map((name) => name.toLowerCase()) ?? [],\n );\n const publicProviderQueries = new Set(\n selectedProvider?.publicDefaultQueryNames?.map((name) => name.toLowerCase()) ?? [],\n );\n const fallbackProviderApiKey =\n capabilitySettings.openaiProvider === \"azure\"\n ? (capabilitySettings.azureOpenaiApiKey ?? capabilitySettings.azureOpenaiAdToken)\n : capabilitySettings.openaiApiKey;\n registerSecretRedactions([\n ...(selectedProvider?.apiKey\n ? [\n {\n name: `MODEL_${selectedProvider.id.toUpperCase()}_API_KEY`,\n value: selectedProvider.apiKey,\n },\n ]\n : !resolvedModel && fallbackProviderApiKey\n ? [\n {\n name: \"MODEL_PROVIDER_API_KEY\",\n value: fallbackProviderApiKey,\n },\n ]\n : []),\n ...Object.entries(selectedProvider?.defaultHeaders ?? {}).flatMap(([name, value]) =>\n publicProviderHeaders.has(name.toLowerCase())\n ? []\n : [\n {\n name: `MODEL_PROVIDER_HEADER_${name.toUpperCase()}`,\n value,\n },\n ],\n ),\n ...Object.entries(selectedProvider?.defaultQuery ?? {}).flatMap(([name, value]) =>\n publicProviderQueries.has(name.toLowerCase())\n ? []\n : [{ name: `MODEL_PROVIDER_QUERY_${name.toUpperCase()}`, value }],\n ),\n ]);\n // Bind the provider/model catalog's context policy to every model-facing\n // path for this turn. In particular, Codex subscription turns must not\n // inherit the deployment's OpenAI/Azure mode or 1.05M context defaults:\n // raw window, effective ceiling, and auto-compact limit are distinct live\n // catalog values and must reach pre-turn compaction, history guards, and\n // every model call together.\n modelRunSettings = resolvedModel\n ? settingsWithResolvedModelContext(runSettings, resolvedModel.configured)\n : runSettings;\n // WORKSPACE MODEL POLICY — the authoritative hard gate. Runs immediately\n // after resolution and BEFORE any model call (the compaction summarizer\n // and the main run both come later in this scope), so a blocked\n // provider/model can never be reached through ANY stamp path: explicit\n // turn model, inherited session default, goal-continuation inheritance,\n // or the legacy null-resolution fallback. The frozen execution policy is\n // the attribution source even if an injected test runtime returns no\n // concrete resolved model. Fail-loud, never a silent remap.\n {\n const workspaceModelPolicy = await getWorkspaceModelPolicy(db, input.workspaceId);\n if (workspaceModelPolicy) {\n const verdict = evaluateWorkspaceModelPolicy(workspaceModelPolicy, {\n providerId: turnExecutionPolicy.providerId,\n modelId: turnExecutionPolicy.productModelId,\n });\n if (!verdict.allowed) {\n throw new WorkspaceModelPolicyBlockedError(\n turnExecutionPolicy.productModelId,\n turnExecutionPolicy.providerId,\n verdict.reason,\n );\n }\n }\n }\n // A codex-subscription turn resolves the bearer for THIS turn's effective\n // codex account (effectiveCodexCredentialId; pin > workspace-active) at\n // model-call time — multi-account P1 means a workspace can hold N accounts,\n // so the bearer is per-account, not per-workspace. codexSubscriptionFetch\n // (on the provider's OpenAI client) reads this AsyncLocalStorage context.\n // Build it once and wrap BOTH the compaction summarizer (a separate model\n // call on the same codex client) and the main run; otherwise the summarizer\n // would hit the codex backend unauthenticated.\n let codexModelRequestSequence = 0;\n const codexContext: CodexRequestContext | null =\n resolvedModel?.provider.kind === \"codex-subscription\"\n ? ((): CodexRequestContext => {\n // The empty-string fallback yields no row → null credential → the\n // existing CodexReloginRequired path (a codex turn with no usable\n // account fails closed, exactly as before multi-account).\n const resolver = buildCodexTokenResolver(\n db,\n runSettings,\n input.workspaceId,\n effectiveCodexCredentialId ?? \"\",\n );\n const registerSnapshot = async (\n snapshotPromise: ReturnType<typeof resolver.getToken>,\n ) => {\n const snapshot = await snapshotPromise;\n registerSecretRedactions([\n { name: \"CODEX_ACCESS_TOKEN\", value: snapshot.accessToken },\n ]);\n return snapshot;\n };\n return {\n clientVersion: CODEX_CLIENT_VERSION,\n // Backend sticky cache-routing key — the SAME id as the body's\n // prompt_cache_key (set from input.sessionId for codex turns),\n // so routing and cache key agree. Without this header on the\n // wire, byte-identical resends hit the prompt cache ~50%\n // (per-request shard lottery = prod's measured 48.6% on sol);\n // with it, resends pin to the warm shard (Codex CLI parity).\n sessionId: input.sessionId,\n getToken: () => registerSnapshot(resolver.getToken()),\n refresh: () => registerSnapshot(resolver.refresh()),\n resolveModel: buildModelResolver(\n CODEX_FALLBACK_MODEL_SLUGS,\n CODEX_FALLBACK_MODEL_SLUGS[0],\n ),\n onUsageHeaders: (snapshot) => {\n latestCodexUsage = snapshot;\n }, // latest wins; flushed once in finally\n onRequestOpaqueArtifacts: ({ fingerprints }) => {\n lastCodexRequestOpaqueArtifacts = fingerprints;\n },\n nextRequestId: () => `${dispatchId}:${++codexModelRequestSequence}`,\n onModelRequestEvent: async (event) => {\n if (!publish || !turnId) {\n throw new Error(\"Codex model request started before the turn event producer\");\n }\n await publish([\n {\n type: \"agent.model.request\",\n payload: {\n ...event,\n provider: \"codex-subscription\",\n turnId,\n attemptId: input.attemptId,\n dispatchId,\n executionGeneration,\n },\n },\n ]);\n },\n };\n })()\n : null;\n const withCodex = <T>(fn: () => Promise<T>): Promise<T> =>\n codexContext ? codexRequestStorage.run(codexContext, fn) : fn();\n const withCodexRemoteCompaction = <T>(fn: () => Promise<T>): Promise<T> =>\n withCodex(() =>\n withCodexRequestOverrides(\n {\n betaFeatures: [REMOTE_COMPACTION_V2_BETA_FEATURE],\n turnMetadata: {\n request_kind: \"compaction\",\n compaction: {\n implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION,\n strategy: \"memento\",\n },\n },\n },\n fn,\n ),\n );\n const promptCacheKey = acceptsPromptCacheKeyForTurn(resolvedModel)\n ? input.sessionId\n : undefined;\n const compactionUsageState = createCompactionModelUsageEventState(\n claimedModelUsageSourceKeys,\n );\n const recordCompactionUsage = async (usage: ModelResponseUsage) => {\n await processCompactionModelUsageEvent({\n usage,\n state: compactionUsageState,\n dispatchId: modelUsageDispatchId,\n settings,\n db,\n observability,\n publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n provider: resolvedModel?.provider.id ?? settings.openaiProvider,\n providerApi: resolvedModel?.provider.api ?? \"responses\",\n model: resolvedModel?.configured.id ?? turn.model,\n externallyBilled: isExternallyBilledTurn,\n turnAttemptId: input.attemptId,\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n renewLease: () => renewCodexLease(\"model_usage\"),\n leaseLost: () => codexLeaseLost,\n leaseLostMessage: \"Codex credential lease expired during context compaction\",\n });\n };\n const compactionSummarizerFor = (systemInstructions?: string) =>\n resolvedModel\n ? (s: Settings, m: Array<Record<string, unknown>>) =>\n withCodex(() =>\n summarizeForCompaction(s, m, {\n client: resolvedModel.client,\n api: resolvedModel.provider.api,\n model: turnExecutionPolicy.upstreamModelId,\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n onUsage: recordCompactionUsage,\n ...(systemInstructions ? { systemInstructions } : {}),\n ...(promptCacheKey ? { promptCacheKey } : {}),\n }),\n )\n : (s: Settings, m: Array<Record<string, unknown>>) =>\n summarizeForCompaction(s, m, {\n model: turnExecutionPolicy.upstreamModelId,\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n onUsage: recordCompactionUsage,\n ...(systemInstructions ? { systemInstructions } : {}),\n ...(promptCacheKey ? { promptCacheKey } : {}),\n });\n // Prompt-cache prefix for remote_v2 MUST match ordinary turns:\n // tools → instructions → history. Filled after buildAgent for every\n // compact path (including operator /compact, which now builds the agent\n // first so it does not send empty tools/instructions).\n let remoteCompactionTools: Awaited<ReturnType<typeof serializedToolsForRemoteCompaction>> =\n [];\n let remoteCompactionInstructions = \"\";\n let remoteCompactionToolsReady = false;\n let remoteCompactionAgent: Parameters<typeof serializedToolsForRemoteCompaction>[0] | null =\n null;\n const remoteCompactionRequester =\n resolvedModel && isCodexTurn\n ? (s: Settings, m: Array<Record<string, unknown>>) =>\n withCodexRemoteCompaction(async () => {\n // Lazily serialize tools here so EmptyCompactionSummaryError is\n // thrown inside the compaction try/settlement handlers, not as a\n // raw activity failure before maybeCompactContext runs.\n if (!remoteCompactionInstructions.trim()) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_instructions\",\n reason: \"agent_missing_system_instructions\",\n });\n }\n if (!remoteCompactionToolsReady) {\n if (!remoteCompactionAgent) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_tools\",\n reason: \"agent_missing_for_tools\",\n });\n }\n try {\n remoteCompactionTools =\n await serializedToolsForRemoteCompaction(remoteCompactionAgent);\n } catch (error) {\n // Tool schemas sit before instructions in the cache prefix.\n // Failing open to [] would reintroduce a massive pre-compact\n // cache bust — fail closed so we never send a tools mismatch\n // on purpose.\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_tools\",\n reason: \"serialize_tools_failed\",\n error: String(error),\n });\n }\n remoteCompactionToolsReady = true;\n }\n return requestRemoteCompactionV2(s, m, {\n client: resolvedModel.client,\n model: turnExecutionPolicy.upstreamModelId,\n systemInstructions: remoteCompactionInstructions,\n onUsage: recordCompactionUsage,\n tools: remoteCompactionTools,\n ...(promptCacheKey ? { promptCacheKey } : {}),\n });\n })\n : undefined;\n const publishCompactionLiveEvents = async (events: SessionEvent[]) => {\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, events);\n };\n const publishCompactionOutcomeEvents = async (events: SessionEvent[]) => {\n // `compaction.started` was already fanout via publishCompactionLiveEvents.\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n events.filter((event) => event.type !== \"session.context.compaction.started\"),\n );\n };\n const compactionModeOptions = {\n codexCompactionMode: session.codexCompactionMode,\n isCodexSubscriptionTurn: isCodexTurn,\n publishLiveEvents: publishCompactionLiveEvents,\n ...(remoteCompactionRequester\n ? { requestRemoteCompactionV2: remoteCompactionRequester }\n : {}),\n } as const;\n\n // Operator /compact:\n // - portable (incl. Codex portable): early maintenance path — no\n // prepareTools/sandbox; summarizer only needs composed instructions.\n // - remote_v2: fall through to prepareTools/buildAgent so the compact\n // request reuses the ordinary tools→instructions cache prefix, then\n // settle without inference. (Requester is also wired for Codex portable\n // turns but unused there — gate on the frozen session mode.)\n const compactionOnlyTurn = turn.source === \"compaction\";\n const remoteV2CompactionNeedsAgentPrefix =\n Boolean(remoteCompactionRequester) && session.codexCompactionMode === \"remote_v2\";\n if (compactionOnlyTurn && !remoteV2CompactionNeedsAgentPrefix) {\n const persistentSessionSettings = {\n titleIsSet: Boolean(session.title?.trim()),\n };\n const compactionInstructions = appendWorkspaceMemory(\n appendPersistentSessionSettings(\n appendSessionInstructions(\n appendWorkspaceGovernance(\n composeAgentInstructions(\n structuredWorkspacePolicyActive\n ? modelRunSettings.agentInstructionsTemplate\n : (workspaceAgentInstructions ?? modelRunSettings.agentInstructionsTemplate),\n undefined,\n rigVersion && rigName\n ? { name: rigName, version: rigVersion.version }\n : undefined,\n ),\n workspaceGovernance ?? undefined,\n ),\n session.instructions ?? undefined,\n ),\n persistentSessionSettings,\n ),\n workspaceMemory ?? undefined,\n );\n const requested = await isSessionCompactionRequested(\n db,\n input.workspaceId,\n input.sessionId,\n );\n let outcome: Awaited<ReturnType<typeof maybeCompactContext>> | null = null;\n if (requested) {\n try {\n outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n session.lastInputTokens,\n compactionSummarizerFor(compactionInstructions),\n {\n force: true,\n clearRequestedCompaction: true,\n trigger: \"operator\",\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n } catch (error) {\n // Codex retries retryable checkpoint-provider failures rather than\n // treating them as a semantic compaction result. Keep the operator\n // request pending and let the ordinary same-turn provider/capacity\n // recovery path re-dispatch this exact maintenance execution.\n if (shouldRecoverCompactionProviderFailure(error)) throw error;\n if (error instanceof TurnAttemptFencedError) throw error;\n // `compaction.started` may already be live — settle skipped before\n // failing the turn so the timeline cannot stick on Compacting…\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: true,\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n if (!isCompactionSummaryFailure(error)) throw error;\n const errorMessage = String(redact(compactionFailureReasonFromError(error)));\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(landmark.requestConsumed ? {} : { consumeRequestedCompactionFailure: true }),\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = error;\n return claimedResult({ status: \"idle\" });\n }\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, \"operator\");\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n }\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: {\n maintenance: \"context_compaction\",\n result: outcome?.compacted ? \"compacted\" : (outcome?.reason ?? \"already_applied\"),\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"completed\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n\n const turnResources = mergeResourceRefs(session.resources, turn.resources);\n // Attach the first-party MCP server to EVERY turn, regardless of how/when\n // the session was created (API, scheduled task, or a pre-existing session\n // whose stored tools predate this). The server registration is then\n // narrowed by the session's exact firstPartyMcpTools selection and\n // authorization. Idempotent: mergeToolRefs dedupes if already present.\n // Resolve the durable policy at the turn boundary. Workspace-default\n // sessions follow the current configured MCP set,\n // while explicit, inherited-fixed, and legacy sessions remain narrowed\n // to their stored materialized allow-list.\n const resolvedToolPolicy = resolveSessionToolPolicy({\n toolPolicy: session.toolPolicy,\n sessionTools: session.tools,\n availableMcpServerIds: runSettings.mcpServers.map((server) => server.id),\n defaultMcpServerIds: defaultSessionMcpServerIds(capabilitySettings.mcpServers),\n });\n const mcpAvailabilityInstructions = unavailableMcpTurnInstructions({\n droppedIds: resolvedToolPolicy.effectivePolicy.droppedIds,\n droppedCount: resolvedToolPolicy.effectivePolicy.counts.dropped,\n });\n const effectivePolicyTools = resolvedToolPolicy.toolRefs;\n const turnTools = withFirstPartyTools(runSettings, effectivePolicyTools);\n // §7.6 connection-credential provider — load (and decrypt) the variable set via the host\n // `sandboxSecrets` provider when bound; unset → today's local decrypt.\n const connectionScope = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n };\n const workspaceVariableSet = await waitForTurnOperation(\n loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n session.variableSetId,\n connectionCredentials?.sandboxSecrets,\n ),\n cancellationSignal,\n undefined,\n );\n variableSetId = workspaceVariableSet?.id ?? \"\";\n // RIG DEFAULT VARIABLE SETS (M3): decrypt the frozen rig version's default\n // variable sets and layer them BELOW the session's own set — the session's\n // values WIN on any key collision. Loaded through the SAME host-secrets\n // provider path as the session set (embedded-topology parity). Precedence\n // WITHIN the rig defaults is listed order (a later set overrides an earlier\n // one), then the session set overrides all. STABLE-ENV INVARIANT: the rig\n // VERSION is frozen per session, so the SET of default variable sets is\n // fixed for the session's life — the merged manifest env is therefore stable\n // across the session's turns (the same guarantee the session's own variable\n // set already relies on), keeping validateNoEnvironmentDelta empty.\n const rigDefaultEnvironmentValues: Record<string, string> = {};\n for (const rigDefaultVariableSetId of rigVersion?.defaultVariableSetIds ?? []) {\n const rigDefaultSet = await waitForTurnOperation(\n loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n rigDefaultVariableSetId,\n connectionCredentials?.sandboxSecrets,\n ),\n cancellationSignal,\n undefined,\n );\n Object.assign(rigDefaultEnvironmentValues, rigDefaultSet?.values ?? {});\n }\n // Session set wins collisions with the rig defaults (explicit precedence).\n const sandboxWorkspaceEnvironmentValues = mergeRigDefaultVariableSetEnvironment(\n rigDefaultEnvironmentValues,\n workspaceVariableSet?.values ?? {},\n );\n // Redact EVERY exported secret value (rig defaults + session set) from turn\n // output, not just the session set's.\n registerSecretRedactions(\n Object.entries(sandboxWorkspaceEnvironmentValues).map(([name, value]) => ({ name, value })),\n );\n // EFFECTIVE compute backend, resolved ONCE at turn start (Case B + Stage D\n // D1-lite) and reused for EVERY downstream decision: the env mint (skip\n // inert platform git tokens for a machine turn), the establish path (no phantom Modal\n // home box for a machine-primary turn), buildAgent (skip the repository clone\n // hook so a private repo is never `git clone`d onto the user's real disk), and\n // the warm-rate (a machine accrues ZERO cloud warm-seconds). The active pointer\n // + its sandbox row are loaded ONCE here (best-effort, never throwing) and the\n // SAME values feed resolveActiveSandboxBackend (the tested gate) AND the\n // machine-primary establish branch (enrollmentId/epoch/workingDir) below — no\n // double read, no read-skew between the gate decision and the establish. With\n // routing OFF this is byte-for-byte the legacy path: no reads, undefined backend.\n const routingOn = routingEnabled(settings);\n let activeSandboxPointer = routingOn\n ? await readActiveSandbox(db, input.workspaceId, input.sessionId).catch(() => null)\n : null;\n // TURN-START RECONCILE (issue #341 invariant B / Shapes 1+2): a persisted\n // pointer whose target is STRUCTURALLY unestablishable at turn start would strand\n // EVERY op of this turn — reset it to the session HOME under the epoch fence +\n // emit a visible event, honoring a concurrent higher-epoch swap. The sandbox row\n // is loaded HERE, inside reconcile, via a NON-swallowing lookup: a null decision\n // then means the row is genuinely absent, never a suppressed transient DB error\n // (which would wrongly clear a healthy user-chosen pointer). On a lookup throw the\n // reconcile fails open — pointer untouched, record null (machinePrimary:false),\n // no event — and the establish branch below reads the returned values.\n let activeSandboxRecord: SandboxRecord | null = null;\n if (routingOn) {\n const reconciled = await reconcileActiveSandboxPointer(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n },\n activeSandboxPointer,\n (sandboxId) => getSandbox(db, input.workspaceId, sandboxId),\n publish\n ? async (events) => {\n await publish!(events);\n }\n : undefined,\n );\n activeSandboxPointer = reconciled.pointer;\n activeSandboxRecord = reconciled.record;\n }\n const activeSandboxBackend = await resolveActiveSandboxBackend(\n routingOn,\n async () => activeSandboxPointer,\n async () => activeSandboxRecord?.kind ?? null,\n );\n // A machine-primary turn = the effective backend is selfhosted AND we have the\n // machine's enrollment (agent id) + a non-null pointer to bind it. Anything\n // missing (should not happen — the DB enforces selfhosted⇒enrollmentId) falls\n // back to the cloud establish path (a correct, if phantom, box) rather than\n // crashing the turn.\n const machinePrimary =\n activeSandboxBackend === \"selfhosted\" &&\n Boolean(activeSandboxPointer?.activeSandboxId) &&\n Boolean(activeSandboxRecord?.enrollmentId);\n // The backend that can actually create a sandbox for this turn. In the\n // common path this is runSettings.sandboxBackend. A selfhosted home turn\n // that is NOT machine-primary falls back to the deployment cloud backend\n // so swap-away / flag-off degrade to a real group box.\n const groupBoxBackend: Settings[\"sandboxBackend\"] =\n runSettings.sandboxBackend === \"selfhosted\" && !machinePrimary\n ? settings.sandboxBackend\n : runSettings.sandboxBackend;\n const sandboxCreationBackend: Settings[\"sandboxBackend\"] =\n settings.sandboxOwnershipEnabled && runSettings.sandboxBackend !== \"none\"\n ? groupBoxBackend\n : runSettings.sandboxBackend;\n const effectiveRunCredentialBackend = activeSandboxBackend ?? groupBoxBackend;\n const runCredentialResolver =\n effectiveRunCredentialBackend === \"none\"\n ? null\n : await waitForTurnOperation(\n bindRunCredentialResolver({\n db,\n connectionCredentials: connectionCredentials ?? null,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n session,\n turn,\n attemptId: input.attemptId,\n effectiveSandboxBackend: effectiveRunCredentialBackend,\n variableSet: workspaceVariableSet\n ? {\n id: workspaceVariableSet.id,\n name: workspaceVariableSet.name,\n }\n : null,\n }),\n cancellationSignal,\n undefined,\n );\n const initialRunCredentialMaterial = runCredentialResolver\n ? await waitForTurnOperation(\n runCredentialResolver.resolve({\n purpose: \"provision\",\n forceRefresh: false,\n }),\n cancellationSignal,\n undefined,\n )\n : null;\n if (initialRunCredentialMaterial) {\n registerSecretRedactions(initialRunCredentialMaterial.redactions);\n for (const payload of runCredentialAuthNeededPayloads(initialRunCredentialMaterial)) {\n publishedRunCredentialNotices.add(JSON.stringify(payload));\n await publish!([{ type: \"credential.auth_needed\", payload }], true);\n }\n }\n const runCredentialsNote = initialRunCredentialMaterial\n ? runCredentialModelNote(initialRunCredentialMaterial)\n : undefined;\n throwIfTurnOperationCancelled(cancellationSignal);\n await waitForTurnOperation(\n ensureTurnModalRegistryImage(runSettings, sandboxCreationBackend),\n cancellationSignal,\n undefined,\n );\n const establishPolicy: \"eager\" | \"on-demand\" =\n lazyProvisionEnabled(settings) && !machinePrimary && runSettings.sandboxBackend !== \"none\"\n ? \"on-demand\"\n : \"eager\";\n // Computed exactly ONCE per turn and reused for BOTH the box manifest\n // (resumeBoxForTurn -> establishSandboxSessionFromEnvelope, below) AND the\n // agent (runtime.buildAgent, below). sandboxEnvironmentForRun mints a FRESH\n // run-scoped git provider tokens on every call, so a second call would\n // yield DIFFERENT token values and re-introduce the manifest-env delta the\n // SDK's provided-session guard throws on — the box and the agent MUST share\n // this same object. A machine-primary turn skips the (inert) token mint entirely\n // (the machine uses its own git creds); the SAME base env still feeds the box +\n // the agent, so env-parity holds.\n // TOKEN-BROKER (B1): sandboxEnvironmentForRun now returns the STABLE manifest\n // env (no rotating GH_TOKEN/GITHUB_TOKEN/GIT_CONFIG_* extraheader) PLUS the\n // run-scoped git tokens minted ONCE per turn as provider seeds, with `gitToken`\n // retained as the GitHub alias. The env feeds BOTH the box manifest AND the\n // agent (env-parity, as before); tokens are threaded OFF-MANIFEST as\n // clone-seeds to buildAgent (below) so the box never carries rotating values\n // on its manifest. When a platform token IS minted, the host `gitCredentials`\n // provider may supply it; unset still self-mints GitHub from settings.\n // gitToken/gitTokens are undefined on the selfhosted skip path (the machine\n // uses its own git creds).\n if (activeSandboxBackend !== \"selfhosted\") {\n await assertGitHubResourcesRemainAuthorized(db, input.workspaceId, turnResources);\n }\n const authorizeGitHubTokenMint: GitHubTokenMintAuthorization = async (selection) => {\n await assertGitHubTokenMintSelectionAuthorized(\n db,\n input.workspaceId,\n selection.installationId,\n selection.repositoryIds,\n );\n };\n // Git and MCP credentials share one lineage snapshot for this turn. A\n // host that supplies both ports must never see two independently resolved\n // roots for the same execution merely because the call sites are far apart.\n const needsHostCredentialRoot = Boolean(\n connectionCredentials?.gitCredentials || connectionCredentials?.mcpCredentials,\n );\n const hostCredentialRootSessionId = needsHostCredentialRoot\n ? await getSessionRootId(db, input.workspaceId, input.sessionId)\n : null;\n if (needsHostCredentialRoot && !hostCredentialRootSessionId) {\n throw new Error(`cannot resolve host credentials for missing session ${input.sessionId}`);\n }\n const gitCredentialAuthority =\n connectionCredentials?.gitCredentials && hostCredentialRootSessionId\n ? gitCredentialAuthorityForTurn({\n sessionId: input.sessionId,\n rootSessionId: hostCredentialRootSessionId,\n attemptId: input.attemptId,\n turn,\n })\n : undefined;\n const toolspaceAuthority = {\n sessionId: input.sessionId,\n };\n const {\n environment: sandboxEnvironment,\n gitToken: sandboxGitToken,\n gitTokens: sandboxGitTokens,\n gitTokenExpiresAt: sandboxGitTokenExpiresAt,\n gitCredentialBindings: sandboxGitCredentialBindings,\n toolspaceToken: sandboxToolspaceToken,\n toolspaceTokenExpiresAt: sandboxToolspaceTokenExpiresAt,\n } = await waitForTurnOperation(\n sandboxEnvironmentForRun(\n runSettings,\n turnResources,\n // Rig default sets merged BELOW the session set (session wins); rig-less\n // turns pass exactly workspaceVariableSet?.values (byte-for-byte today).\n sandboxWorkspaceEnvironmentValues,\n {\n skipGitHubToken: activeSandboxBackend === \"selfhosted\",\n deferGitHubToken:\n activeSandboxBackend !== \"selfhosted\" && establishPolicy === \"on-demand\",\n scope: connectionScope,\n ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),\n gitCredentials: connectionCredentials?.gitCredentials,\n authorizeGitHubTokenMint,\n toolspaceAuthority,\n },\n ),\n cancellationSignal,\n undefined,\n );\n registerSecretRedactions([\n ...Object.entries(sandboxGitTokens ?? {}).flatMap(([provider, value]) =>\n value ? [{ name: `GIT_${provider.toUpperCase()}_TOKEN`, value }] : [],\n ),\n ...(sandboxGitToken ? [{ name: \"GIT_TOKEN\", value: sandboxGitToken }] : []),\n ...((sandboxGitCredentialBindings ?? []).map((binding) => ({\n name: `GIT_${binding.provider.toUpperCase()}_BINDING_TOKEN`,\n value: binding.token,\n })) satisfies SecretForRedaction[]),\n ...(sandboxToolspaceToken\n ? [{ name: \"TOOLSPACE_TOKEN\", value: sandboxToolspaceToken }]\n : []),\n ]);\n const sandboxToolspaceTokenFile = sandboxToolspaceToken\n ? toolspaceTokenFileFromEnvironment(sandboxEnvironment, input.sessionId)\n : undefined;\n\n const initialGitCredentials: MintedRunGitCredentials | undefined =\n sandboxGitCredentialBindings\n ? {\n bindings: sandboxGitCredentialBindings,\n gitTokens: sandboxGitTokens ?? {},\n expiresAt: sandboxGitTokenExpiresAt ?? {},\n }\n : undefined;\n const attachGitCredentialRenewal = async (\n tokenSession: GitCredentialTokenWriterSession,\n initial: MintedRunGitCredentials | undefined,\n initialSandbox?: ResumedTurnSandbox,\n ): Promise<void> => {\n if (!initial || initial.bindings.length === 0) return;\n const previous = gitCredentialRenewals;\n gitCredentialRenewals = [];\n await Promise.all(previous.map(async (controller) => await controller.stop()));\n if (gitCredentialRenewalClosed) return;\n\n const controllers = initial.bindings.map((initialBinding) => {\n let pendingBinding: typeof initialBinding | undefined;\n return startGitCredentialRenewalLoop({\n expectedProviders: [initialBinding.provider],\n initialExpiresAt: initialBinding.expiresAt\n ? { [initialBinding.provider]: initialBinding.expiresAt }\n : {},\n mint: async () => {\n const binding = await mintRunGitCredentialBinding(\n runSettings,\n turnResources,\n initialBinding.provider,\n initialBinding.credentialBindingId,\n {\n scope: connectionScope,\n ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),\n gitCredentials: connectionCredentials?.gitCredentials,\n authorizeGitHubTokenMint,\n },\n );\n if (binding) {\n assertGitCredentialRenewalTransportUnchanged(initialBinding, binding);\n registerSecretRedactions([\n {\n name: `GIT_${binding.provider.toUpperCase()}_BINDING_TOKEN`,\n value: binding.token,\n },\n ]);\n }\n pendingBinding = binding;\n return binding\n ? {\n bindings: [binding],\n gitTokens: { [binding.provider]: binding.token },\n expiresAt: binding.expiresAt ? { [binding.provider]: binding.expiresAt } : {},\n }\n : undefined;\n },\n write: async () => {\n if (!pendingBinding) {\n throw new Error(\"credential renewal produced no binding token\");\n }\n const runAs = sandboxRunAs(runSettings);\n const targetSandbox = resolvedSandbox ?? initialSandbox;\n if (!targetSandbox) {\n throw new Error(\"Git credential renewal has no exact sandbox lease target\");\n }\n await runWorkspaceMutationForSandbox(\n targetSandbox,\n \"gitCredentialRenewal\",\n async () =>\n await refreshGitCredentialBindingTokenFiles(tokenSession, [pendingBinding!], {\n ...(runAs ? { runAs } : {}),\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n }),\n );\n },\n onSuccess: ({ providers: renewedProviders }) => {\n for (const provider of renewedProviders) {\n observability.incrementCounter({\n name: \"opengeni_git_credential_renewals_total\",\n help: \"Host-managed Git credential renewal attempts by provider and outcome.\",\n labels: { provider, outcome: \"completed\" },\n });\n }\n },\n onFailure: ({ providers: failedProviders, retryDelayMs, errorClass }) => {\n for (const provider of failedProviders) {\n observability.incrementCounter({\n name: \"opengeni_git_credential_renewals_total\",\n help: \"Host-managed Git credential renewal attempts by provider and outcome.\",\n labels: { provider, outcome: \"error\" },\n });\n }\n observability.warn(\"Sandbox Git credential renewal failed; retry scheduled\", {\n sessionId: input.sessionId,\n turnId,\n providers: failedProviders.join(\",\"),\n errorClass,\n retryDelayMs,\n });\n },\n });\n });\n if (gitCredentialRenewalClosed) {\n await Promise.all(controllers.map(async (controller) => await controller.stop()));\n return;\n }\n gitCredentialRenewals = controllers;\n };\n\n const attachToolspaceTokenRenewal = async (\n tokenSession: ToolspaceTokenWriterSession,\n initialExpiresAt = sandboxToolspaceTokenExpiresAt,\n initialSandbox?: ResumedTurnSandbox,\n ): Promise<void> => {\n if (!sandboxToolspaceToken || !initialExpiresAt) return;\n const previous = toolspaceTokenRenewal;\n toolspaceTokenRenewal = null;\n await previous?.stop();\n if (toolspaceTokenRenewalClosed) return;\n\n const mint = async () => {\n const material = await mintSandboxToolspaceToken(\n runSettings,\n connectionScope,\n toolspaceAuthority,\n );\n if (material) {\n registerSecretRedactions([{ name: \"TOOLSPACE_TOKEN\", value: material.token }]);\n }\n return material;\n };\n const write = async (material: NonNullable<Awaited<ReturnType<typeof mint>>>) => {\n const runAs = sandboxRunAs(runSettings);\n const targetSandbox = resolvedSandbox ?? initialSandbox;\n if (!targetSandbox) {\n throw new Error(\"Toolspace token renewal has no exact sandbox lease target\");\n }\n await runWorkspaceMutationForSandbox(\n targetSandbox,\n \"toolspaceTokenRenewal\",\n async () =>\n await refreshToolspaceTokenFile(tokenSession, material.token, {\n ...(runAs ? { runAs } : {}),\n ...(sandboxToolspaceTokenFile\n ? {\n tokenFile: sandboxToolspaceTokenFile,\n legacyTokenFile: sandboxEnvironment.OPENGENI_TOOLSPACE_TOKEN_FILE!,\n }\n : {}),\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n }),\n );\n };\n let renewalExpiresAt = initialExpiresAt;\n if (renewalExpiresAt.getTime() <= Date.now() + TOOLSPACE_TOKEN_EXPIRY_LEAD_MS) {\n const fresh = await mint();\n if (!fresh) {\n throw new Error(\"Toolspace token mint became unavailable during sandbox setup\");\n }\n await write(fresh);\n renewalExpiresAt = fresh.expiresAt;\n }\n const controller = startToolspaceTokenRenewalLoop({\n initialExpiresAt: renewalExpiresAt,\n mint,\n write,\n onSuccess: () => {\n observability.incrementCounter({\n name: \"opengeni_toolspace_token_renewals_total\",\n help: \"Sandbox Toolspace token renewal attempts by outcome.\",\n labels: { outcome: \"completed\" },\n });\n },\n onFailure: ({ retryDelayMs, errorClass }) => {\n observability.incrementCounter({\n name: \"opengeni_toolspace_token_renewals_total\",\n help: \"Sandbox Toolspace token renewal attempts by outcome.\",\n labels: { outcome: \"error\" },\n });\n observability.warn(\"Sandbox Toolspace token renewal failed; retry scheduled\", {\n sessionId: input.sessionId,\n turnId,\n errorClass,\n retryDelayMs,\n });\n },\n });\n if (toolspaceTokenRenewalClosed) {\n await controller.stop();\n return;\n }\n toolspaceTokenRenewal = controller;\n };\n\n const attachRunCredentialRenewal = async (\n credentialSession: RunCredentialCommandSession,\n initialSandbox?: ResumedTurnSandbox,\n ): Promise<void> => {\n if (!runCredentialResolver) return;\n const previous = runCredentialRenewal;\n runCredentialRenewal = null;\n await previous?.stop();\n if (runCredentialRenewalClosed) return;\n runCredentialSession = credentialSession;\n\n const requireTargetSandbox = (): ResumedTurnSandbox => {\n const targetSandbox = resolvedSandbox ?? initialSandbox;\n if (!targetSandbox) {\n throw new Error(\"Run credential mutation has no exact sandbox lease target\");\n }\n return targetSandbox;\n };\n\n if (!initialRunCredentialMaterial) {\n await runWorkspaceMutationForSandbox(\n requireTargetSandbox(),\n \"runCredentialClear\",\n async () =>\n await clearRunCredentials(\n credentialSession,\n input.sessionId,\n toolCancellationFenceRef.current\n ? toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n )\n : undefined,\n ),\n );\n return;\n }\n\n const write = async (\n material: NormalizedRunCredentialMaterial | null,\n pruneOtherAttempts = false,\n ): Promise<void> => {\n if (!material) {\n await runWorkspaceMutationForSandbox(\n requireTargetSandbox(),\n \"runCredentialAttemptClear\",\n async () =>\n await clearRunCredentialsForAttempt(credentialSession, {\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n executionGeneration,\n }),\n );\n return;\n }\n registerSecretRedactions(material.redactions);\n await runWorkspaceMutationForSandbox(\n requireTargetSandbox(),\n \"runCredentialMaterialization\",\n async () =>\n await materializeRunCredentials(credentialSession, material, {\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n executionGeneration,\n ...(pruneOtherAttempts ? { pruneOtherAttempts: true } : {}),\n ...(!pruneOtherAttempts ? { pruneSupersededGenerations: true } : {}),\n ...(material.authNeeded.length > 0 &&\n Object.keys(material.environment).length === 0 &&\n material.files.length === 0\n ? { prunePreviousGenerations: true }\n : {}),\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n }),\n );\n for (const payload of runCredentialAuthNeededPayloads(material)) {\n const key = JSON.stringify(payload);\n if (publishedRunCredentialNotices.has(key)) continue;\n publishedRunCredentialNotices.add(key);\n await publish!([{ type: \"credential.auth_needed\", payload }], true);\n }\n };\n\n const initialExpiryMs = initialRunCredentialMaterial.expiresAt?.getTime() ?? null;\n const seed =\n initialExpiryMs !== null && initialExpiryMs <= Date.now() + RUN_CREDENTIAL_EXPIRY_LEAD_MS\n ? await runCredentialResolver.resolve({\n purpose: \"provision\",\n forceRefresh: true,\n })\n : initialRunCredentialMaterial;\n await write(seed, true);\n if (runCredentialRenewalClosed) return;\n const controller = startRunCredentialRenewalLoop({\n initialExpiresAt: seed?.expiresAt ?? null,\n resolve: async () =>\n await runCredentialResolver.resolve({\n purpose: \"renewal\",\n forceRefresh: true,\n }),\n write: async (material) => await write(material),\n onSuccess: ({ authNeeded }) => {\n observability.incrementCounter({\n name: \"opengeni_run_credential_renewals_total\",\n help: \"Host-managed run credential renewal attempts by outcome.\",\n labels: { outcome: authNeeded ? \"auth_needed\" : \"completed\" },\n });\n },\n onFailure: ({ retryDelayMs, errorClass }) => {\n observability.incrementCounter({\n name: \"opengeni_run_credential_renewals_total\",\n help: \"Host-managed run credential renewal attempts by outcome.\",\n labels: { outcome: \"error\" },\n });\n observability.warn(\"Host run credential renewal failed; retry scheduled\", {\n sessionId: input.sessionId,\n turnId,\n errorClass,\n retryDelayMs,\n });\n },\n });\n if (runCredentialRenewalClosed) {\n await controller.stop();\n return;\n }\n runCredentialRenewal = controller;\n };\n\n // P1.2 ownership inversion (gated, default OFF). With the flag off this\n // block is skipped entirely: resolvedSandbox stays null and runStream\n // takes the legacy per-run build-and-discard path — byte-for-byte today.\n // With it on, acquire the group lease (holder = the durable attempt id),\n // resume the one box by id, and inject it NON-OWNED into the run. The box\n // backend is \"none\" -> never resolve (no box to touch).\n //\n // Established AFTER sandboxEnvironment is computed (not before) so the box's\n // manifest is created with the SAME variableSet the agent declares — the SDK\n // applies the agent's manifest to this provided session and throws on ANY\n // variableSet delta (validateNoEnvironmentDelta). Passing sandboxEnvironment\n // here makes current==target so the delta is empty.\n if (settings.sandboxOwnershipEnabled && turn.sandboxBackend !== \"none\") {\n const managedOwnership = managedSandboxOwnershipForTurn(\n machinePrimary,\n input.attemptId,\n session.sandboxGroupId,\n );\n sandboxHolderId = managedOwnership?.holderId ?? null;\n sandboxGroupId = managedOwnership?.sandboxGroupId ?? null;\n // STAGE D honest-label guard: a machine-home session carries\n // turn.sandboxBackend \"selfhosted\", but a turn is only machine-PRIMARY\n // when a live machine pointer resolves (activeSandboxBackend==='selfhosted'\n // + enrollmentId). When it is NOT primary — the agent swapped back to the\n // group box (sandbox_swap 'session'/'default'/groupId clears the pointer) or\n // selfhosted routing is flag-OFF (the pointer is ignored) — the else-branch\n // must resume a REAL cloud group box, not a \"selfhosted\" one: the registry\n // SelfhostedSandboxClient has no bound agentId and throws. Fall the group-box\n // backend back to the deployment default cloud backend so swap-away / flag-off\n // degrade to a genuine cloud box exactly like today (home=modal did).\n if (machinePrimary) {\n // STAGE D D1-lite: the active sandbox is a connected machine, so DO NOT\n // establish OR lease the managed home box. The active-sandbox pointer is\n // the machine route's own epoch fence; the managed-home lease separately\n // owns cloud recovery, snapshots, billing, and reaping. Mixing those two\n // ownership domains lets an unrelated degraded cloud archive block a\n // healthy explicitly selected machine.\n // Whether the machine's latest Hello advertised the op-stream engine\n // (refreshed on every connect). Read only when the server flag is on —\n // one indexed lookup, and the flag off keeps this path byte-identical.\n const machineOpStream =\n settings.agentOpStreamEnabled === true\n ? (await getEnrollment(db, input.workspaceId, activeSandboxRecord!.enrollmentId!))\n ?.opStream === true\n : false;\n const established = await establishSelfhostedTurnSession(\n {\n db,\n settings,\n bus,\n onOp: machineOpObserver.observer,\n onSandboxOperation: sandboxOperationObserver,\n opJournal,\n },\n {\n workspaceId: input.workspaceId,\n agentId: activeSandboxRecord!.enrollmentId!,\n opStream: machineOpStream,\n epoch: activeSandboxPointer!.activeEpoch,\n environment: sandboxEnvironment,\n workingDir: activeSandboxPointer!.workingDir,\n },\n );\n // The machine-primary establish narrows `session` to SelfhostedSession\n // (buildSelfhostedBackendSession); EstablishedSandboxSession widens it.\n machinePrimarySession =\n established.session as import(\"@opengeni/runtime\").SelfhostedSession;\n setupBoxSession = established.session;\n resolvedSandbox = {\n // Wrap in the SAME routing proxy so a mid-turn swap (to another machine\n // or back to the group box) still re-routes per op. PIN this established\n // SelfhostedSession for the machine pointer so the turn-start manifest\n // write (via the proxy's `state` getter) and the per-op reads hit ONE\n // instance — no two-instance manifest divergence.\n established: wrapTurnBoxWithRouting(\n {\n db,\n settings,\n bus,\n onOp: machineOpObserver.observer,\n onSandboxOperation: sandboxOperationObserver,\n onHomeSandboxRebound,\n },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\n workspaceMutationFence: {\n accountId: input.accountId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n pinnedSelfhosted: {\n sandboxId: activeSandboxPointer!.activeSandboxId!,\n epoch: activeSandboxPointer!.activeEpoch,\n },\n // HOME semantics for a mid-turn clear-to-null: only a genuine\n // machine-HOME session (its home IS this machine, session.sandboxBackend\n // === \"selfhosted\") resolves null back to the pinned machine. A Modal-HOME\n // session merely PINNED to a machine this turn never established its group\n // box, so defaultIsHome:false makes a clear-to-null fail typed\n // (`home_unavailable_this_turn`) rather than silently serving the machine;\n // the detach takes effect next turn. (Lazy home-box establishment on such a\n // clear is a deferred follow-up; issue #341.)\n defaultIsHome: session.sandboxBackend === \"selfhosted\",\n },\n established,\n ),\n // For a machine route this is the active-pointer epoch, not a cloud\n // lease epoch. Cloud-only heartbeat/snapshot/capture paths require\n // sandboxGroupId and remain disabled for this branch.\n leaseEpoch: activeSandboxPointer!.activeEpoch,\n release: async () => undefined,\n };\n } else if (establishPolicy === \"on-demand\") {\n // Lazy sandbox provisioning: holder/group ids are fixed at turn start,\n // but the lease acquire + box establish + setup move behind the routing\n // proxy's first default-pointer op. A chat-only turn never calls it, so\n // no lease row, no provider box, no warm-meter interval.\n } else {\n resolvedSandbox = await waitForTurnOperation(\n resumeBoxForTurn(\n {\n db,\n settings: runSettings,\n cancellationSignal: sandboxResumeSignal,\n sandboxMetrics: runtimeMetricsHooksForObservability(observability),\n onSandboxLost: publishSandboxLost,\n },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n sessionId: input.sessionId,\n // groupBoxBackend, not turn.sandboxBackend: a machine-home turn that\n // is not machine-primary resumes a real cloud group box (the\n // deployment default), never a \"selfhosted\" box (which would throw\n // for lack of a bound agentId).\n backend: groupBoxBackend,\n os: session.sandboxOs,\n environment: sandboxEnvironment,\n // IMAGE IS SHARED STATE (B3, Modal warm-box path only): the container image\n // this run resolves. The lease stamps it + conflicts on a live shared box\n // running a DIFFERENT image (solo → durable rotation; N-holders →\n // SandboxImageConflictError surfaced as an actionable turn error). Prefer\n // the explicit Modal image ref, else the docker image. The selfhosted branch\n // (establishSelfhostedTurnSession) NEVER passes\n // an image — B3 lives only on this Modal else-branch.\n ...((runSettings.modalImageRef ?? runSettings.dockerImage)\n ? {\n image: runSettings.modalImageRef ?? runSettings.dockerImage,\n }\n : {}),\n // RIG IS SHARED STATE (M3): stamp the frozen rig version so the lease\n // conflicts on a live shared box set up under a different rig (solo\n // durable rotation / N-holders SandboxRigConflictError). Omitted for a\n // rig-less turn -> never stamped or enforced (shares exactly as today).\n ...(rigVersion ? { rigVersionId: rigVersion.id } : {}),\n },\n \"turn\",\n managedOwnership!.holderId,\n ),\n sandboxResumeSignal,\n async (lateSandbox) => await lateSandbox.release(),\n );\n setupBoxSession = resolvedSandbox.established.session;\n // Durable box-lifecycle events (sandbox-file-persistence observability):\n // record every box transition in session_events so the NEXT box loss is\n // attributable from the DB alone — worker logs rotate within hours, which\n // left both 2026-07-06 incidents without a durable trace. Best-effort.\n await publishSandboxLifecycleEvents(resolvedSandbox);\n // M7 hot-swap: when the selfhosted feature is on, wrap the established\n // group box in the STABLE routing proxy before it is injected NON-OWNED\n // into the run. The SDK binds to this ONE object once and calls its\n // methods per tool call; the proxy re-reads (active_sandbox_id,\n // active_epoch) per op and dispatches to the currently-active backend, so\n // a sandbox_swap mid-turn lands the NEXT tool call on the new box. With\n // the flag off the established group box is injected unchanged (today's\n // path). The lease still owns the group box lifecycle — the proxy is a\n // routing veneer, not an owner.\n resolvedSandbox = {\n ...resolvedSandbox,\n established: wrapTurnBoxWithRouting(\n {\n db,\n settings,\n bus,\n onSandboxOperation: sandboxOperationObserver,\n onHomeSandboxLost: publishSandboxLost,\n onHomeSandboxRebound,\n },\n // Thread the SAME declared environment the group box was created with\n // (resumeBoxForTurn, above) so a selfhosted swap target's manifest\n // carries it too — the SDK's per-turn manifest-env delta stays empty\n // (no \"cannot change manifest environment variables\" throw).\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\n workspaceMutationFence: {\n accountId: input.accountId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n homeLease: {\n accountId: input.accountId,\n sandboxGroupId: session.sandboxGroupId,\n leaseEpoch: resolvedSandbox.leaseEpoch,\n instanceId: resolvedSandbox.established.instanceId,\n backend: groupBoxBackend,\n },\n },\n resolvedSandbox.established,\n ),\n };\n }\n if (resolvedSandbox) {\n startLeaseHeartbeat(resolvedSandbox, activeSandboxBackend ?? groupBoxBackend);\n }\n }\n\n const fileResourceDownloads = await waitForTurnOperation(\n sandboxFileDownloadsForRun(\n runSettings,\n db,\n objectStorage,\n input.workspaceId,\n turnResources,\n activeSandboxBackend ?? groupBoxBackend,\n ),\n cancellationSignal,\n undefined,\n );\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n const mcpCredentialRootSessionId =\n connectionCredentials?.mcpCredentials && hostCredentialRootSessionId\n ? hostCredentialRootSessionId\n : input.sessionId;\n // Connection credentials and the optional Apps credential are resolved\n // independently. Inference auth is never an Apps fallback.\n const rawResolveCredential = connectionTokenResolverForTurn({\n db,\n settings: runSettings,\n connectionCredentials: connectionCredentials ?? null,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n rootSessionId: mcpCredentialRootSessionId,\n attemptId: input.attemptId,\n turn,\n });\n const personalConnectionDelegations = turn.personalConnectionDelegations;\n const delegatedMembershipChecks = new Map<string, Promise<boolean>>();\n const delegatedOwnerHasMembership = async (subjectId: string): Promise<boolean> => {\n const existing = delegatedMembershipChecks.get(subjectId);\n if (existing) return await existing;\n const check = getWorkspaceGrant(db, subjectId, input.workspaceId).then(Boolean);\n delegatedMembershipChecks.set(subjectId, check);\n return await check;\n };\n const resolveFrozenCredential = withFrozenPersonalConnectionDelegations({\n resolveCredential: rawResolveCredential,\n settings: runSettings,\n personalConnectionDelegations,\n ownerHasWorkspaceMembership: delegatedOwnerHasMembership,\n });\n const resolveCredential: typeof rawResolveCredential = async (request) => {\n const result = await resolveFrozenCredential(request);\n if (result.status === \"ok\") {\n registerSecretRedactions(\n headerSecretRedactions(\"MCP\", result.headers, Object.keys(result.headers)),\n );\n }\n return result;\n };\n const credentialSubjectId = credentialSubjectIdForTurnInitiator(turn);\n const codexAppsAuth = codexAppsCredentialId\n ? (() => {\n const resolver = buildCodexTokenResolver(\n db,\n runSettings,\n input.workspaceId,\n codexAppsCredentialId,\n );\n return {\n clientVersion: CODEX_CLIENT_VERSION,\n withAuthorization: async <T>(\n use: (token: {\n accessToken: string;\n chatgptAccountId: string | null;\n }) => Promise<T>,\n ): Promise<T> => {\n const snapshot = await resolver.getToken();\n registerSecretRedactions([\n { name: \"CODEX_APPS_ACCESS_TOKEN\", value: snapshot.accessToken },\n ]);\n return await withCodexAppsRequestAuthorization(\n db,\n { workspaceId: input.workspaceId, credentialId: codexAppsCredentialId },\n async () => await use(snapshot),\n );\n },\n };\n })()\n : undefined;\n preparedTools = await waitForTurnOperation(\n runtime.prepareTools(runSettings, turnTools, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n // Sign the calling turn into the first-party token so tools classify\n // the caller by its own identity (sacred-pause guard), not the racy\n // live active pointer.\n ...(turnId ? { turnId } : {}),\n attemptId: input.attemptId,\n executionGeneration,\n subjectId: \"worker:first-party-mcp\",\n subjectLabel: \"OpenGeni worker\",\n ...(credentialSubjectId ? { credentialSubjectId } : {}),\n ...(codexAppsAuth ? { codexAppsAuth } : {}),\n resolveCredential,\n onAuthNeeded: async (payload) => {\n if (!shouldPublishToolAuthNeededForTurn(payload, trigger, turn)) {\n return;\n }\n await publish!([{ type: \"tool.auth_needed\", payload }], true);\n },\n // Manager-style sessions carry a creation-validated permission set\n // for their first-party MCP token; null keeps the fixed default.\n ...(session.firstPartyMcpPermissions?.length\n ? { firstPartyPermissions: session.firstPartyMcpPermissions }\n : {}),\n firstPartyTools: session.firstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS],\n }),\n cancellationSignal,\n async (latePreparedTools) => await latePreparedTools.close().catch(() => undefined),\n );\n // Genesis turn = the first user turn (no assistant history reconciled\n // yet). Durable Postgres state (countSessionHistoryItems includes\n // superseded rows after compaction), NOT a workflow counter (turnsThisRun\n // resets on continueAsNew). Drives the one-shot title hint appended to the\n // agent's instructions; later attempts and goal continuations never match.\n const isGenesisTurn =\n triggerType === \"user.message\" &&\n (await countSessionHistoryItems(db, input.workspaceId, input.sessionId)) === 0;\n // Clone-onto-real-disk hazard (Case B). A session keeps its CLOUD HOME\n // backend (runSettings.sandboxBackend, e.g. \"modal\") but its ACTIVE sandbox\n // may have been swapped to a connected machine (active_sandbox_id → a\n // selfhosted lease). buildAgent's repository-clone lifecycle hook keys off\n // the EFFECTIVE backend; if we let it default to the home backend it would\n // `git clone` a private GitHub-App repo onto the user's REAL disk. So pass\n // \"selfhosted\" through when the active sandbox is a connected machine;\n // otherwise leave it undefined so buildAgent defaults to the home backend\n // (byte-for-byte unchanged cloud behavior). `activeSandboxBackend` was\n // resolved ONCE at turn start (above) via resolveActiveSandboxBackend (the\n // tested gate) and is reused here — resolving once is correct because the\n // clone hook runs at beforeAgentStart, so a mid-turn swap can't affect it.\n // buildAgent's option key is `workspaceEnvironment` (internal runtime\n // symbol; the product concept is a variable set). Built as a TYPED const —\n // a direct literal assignment to Pick<BuildAgentOptions,...> IS excess-\n // property-checked, so a wrong key fails tsc. A bare conditional spread\n // inside the options literal is NOT checked, which is exactly how the M1\n // key regression (workspaceVariableSet vs workspaceEnvironment) slipped\n // through and silently dropped the variable-set instructions block.\n const workspaceEnvironmentOption: Pick<BuildAgentOptions, \"workspaceEnvironment\"> =\n workspaceVariableSet\n ? {\n workspaceEnvironment: {\n name: workspaceVariableSet.name,\n description: workspaceVariableSet.description,\n variableNames: Object.keys(workspaceVariableSet.values),\n },\n }\n : {};\n const hostedWebSearch = hostedWebSearchForTurn(resolvedModel, runSettings.webSearchEnabled);\n const serviceTier = serviceTierForLatencyMode(\n turnExecutionPolicy.providerId,\n turnExecutionPolicy.latencyMode,\n );\n const connectorActionIdentity = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n executionGeneration,\n initiator: {\n kind: turn.initiator.kind,\n subjectId: turn.initiator.subjectId,\n },\n } as const;\n const connectorActionPolicy: ConnectorActionPolicyHooks = {\n prepare: async (call) =>\n await prepareConnectorActionApproval(db, connectorActionIdentity, call),\n begin: async (call) =>\n await beginConnectorActionExecution(db, connectorActionIdentity, call),\n complete: async ({ requestId, outcome }) =>\n await completeConnectorActionExecution(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n requestId,\n attemptId: input.attemptId,\n outcome,\n }),\n };\n const agent = runtime.buildAgent(modelRunSettings, turnResources, {\n reasoningEffort: turn.reasoningEffort,\n latencyMode: turnExecutionPolicy.latencyMode,\n ...(serviceTier ? { serviceTier } : {}),\n ...(humanInputResume ? { humanInputResponse: humanInputResume } : {}),\n genesisTitleHint: isGenesisTurn,\n persistentSessionSettings: {\n titleIsSet: Boolean(session.title?.trim()),\n },\n sandboxEnvironment,\n ...(cancellationSignal ? { turnCancellationSignal: cancellationSignal } : {}),\n onToolCancellationFence: (fence) => {\n toolCancellationFenceRef.current = fence;\n },\n // TOKEN-BROKER (B1): forward the per-turn git token OFF-MANIFEST as the clone\n // seed. ONLY when the effective backend is NOT selfhosted (the connected\n // machine uses its own git creds — mirrors the skipGitHubToken gate above)\n // AND the mint actually produced a token (repo resources present). The runtime\n // seeds it to the box's token file before the repository-clone runs; it never\n // touches the box/agent manifest env.\n ...(activeSandboxBackend !== \"selfhosted\" && sandboxGitTokens\n ? { gitTokenSeeds: sandboxGitTokens }\n : {}),\n ...(activeSandboxBackend !== \"selfhosted\" && sandboxGitCredentialBindings\n ? { gitCredentialBindings: sandboxGitCredentialBindings }\n : {}),\n ...(activeSandboxBackend !== \"selfhosted\" && !sandboxGitTokens && sandboxGitToken\n ? { gitTokenSeed: sandboxGitToken }\n : {}),\n // Toolspace is delivered on EVERY backend including selfhosted. The git-\n // token skip does NOT transfer: that token is inert on a connected\n // machine (it uses its own git creds), but the toolspace token is the\n // machine's ONLY path to programmatic tool calling and grants no more\n // than toolspace:call for its own session (own-session-bound,\n // short-lived and renewable, per-active-turn budgeted, approval-tools\n // excluded). The runtime seeds it to the box's token file over the same\n // exec channel, off-manifest, on every backend.\n ...(sandboxToolspaceToken\n ? {\n toolspaceTokenSeed: sandboxToolspaceToken,\n toolspaceTokenSessionId: input.sessionId,\n }\n : {}),\n ...(activeSandboxBackend ? { activeSandboxBackend } : {}),\n fileResourceDownloads,\n mcpServers: preparedTools.mcpServers,\n resolvedMcpConnectionIds: preparedTools.resolvedMcpConnectionIds,\n connectorActionPolicy,\n // LIVE by-reference connector namespaces (fills during this turn's\n // codex_apps tools/list): the codex tool_search description reads it per\n // model call so the model sees the account's real connected sources.\n codexConnectorNamespaces: preparedTools.codexConnectorNamespaces,\n // Resolved-model routing + gating (legacy defaults when null). The model\n // is passed as the model *string* (agent.model = runSettings.openaiModel),\n // NOT a Model instance: an instance only survives the in-process\n // (\"none\") run, whereas the SandboxAgent/Modal path drops it and\n // re-resolves the model *name* through the global MultiProviderModelProvider\n // configureOpenAI installed — so registry models (Fireworks GLM) route to\n // their own client instead of 404ing against the built-in Azure/OpenAI\n // client. The gating still comes from the resolved provider: server-side\n // store/compaction follow the provider's compaction mode (registry\n // providers resolve to \"client\"); encrypted reasoning is only\n // round-tripped on the Responses wire API; hosted web search is attached\n // whenever the provider declares it runnable and is independent of the\n // session's MCP allow-list; the effective context window drives the\n // compaction threshold.\n hostedWebSearch,\n supportsImageInput,\n inputFileMediaTypes: modelInputPolicy.inputFileMediaTypes,\n ...(resolvedModel\n ? {\n encryptedReasoning:\n resolvedModel.provider.api === \"responses\" &&\n runSettings.openaiReasoningEncryptedContent,\n contextWindowTokens:\n resolvedModel.configured.contextWindowTokens ?? runSettings.contextWindowTokens,\n // The ChatGPT/Codex backend rejects the SDK's HOSTED sandbox tools —\n // the `apply_patch` tool type (\"Unsupported tool type: apply_patch\")\n // and structured tool output — which the OpenAIResponsesModel the SDK\n // binds would otherwise select. Tell buildAgent to emit the function\n // `apply_patch` + text `view_image` variants the backend accepts. Only\n // the codex-subscription provider needs this; every other backend\n // (built-in OpenAI/Azure = real hosted support; registry \"chat\"\n // providers = the SDK's own ChatCompletions detection) keeps the SDK\n // default.\n structuredToolTransport: structuredToolTransportForTurn(resolvedModel),\n // EXPLICIT computer-use tool transport, derived from the resolved provider's\n // authoritative wire identity (codex → function-image, chat → disabled,\n // responses → hosted) so the runtime never string-sniffs the model instance's\n // constructor name. See {@link computerToolModeForTurn}.\n computerToolMode: computerToolModeForTurn(resolvedModel),\n ...(promptCacheKey ? { promptCacheKey } : {}),\n }\n : // LEGACY global-client fallback (resolveTurnModel returned null → the model\n // is not in the registry, served by the built-in OpenAI/Azure Responses\n // client). That backend has real hosted support, so pin computerToolMode to\n // \"hosted\" EXPLICITLY rather than leaving the runtime to sniff the instance.\n {\n computerToolMode: computerToolModeForTurn(null),\n promptCacheKey: input.sessionId,\n }),\n // Lazy computer-use seam: runtime first brings up :0 only after the model\n // selects a computer tool, then this hook begins the optional proof\n // recording. Shell/filesystem turns never invoke either operation.\n onComputerUseReady: async () => {\n if (!resolvedSandbox) {\n throw new Error(\"Computer-use display became ready without a resolved sandbox\");\n }\n // This callback is the authoritative execution boundary. Record the\n // action before async ffmpeg startup so transport-event ordering cannot\n // make settlement misclassify a real computer turn as unused.\n didComputerUse = true;\n await maybeStartOnTurnRecording(resolvedSandbox, activeSandboxBackend);\n },\n ...(packRuntime.skills.length > 0 ? { packSkills: packRuntime.skills } : {}),\n ...(session.skills.length > 0 ? { sessionSkills: session.skills } : {}),\n ...(skillLibraryRuntime.skillLibrarySkills.length > 0\n ? {\n skillLibrarySkills: skillLibraryRuntime.skillLibrarySkills,\n skillLibrarySelections: skillLibraryRuntime.skillLibrarySelections,\n }\n : {}),\n ...(!structuredWorkspacePolicyActive && workspaceAgentInstructions\n ? { instructionsTemplate: workspaceAgentInstructions }\n : {}),\n ...(workspaceGovernance ? { workspaceGovernance } : {}),\n ...(workspaceMemory ? { workspaceMemory } : {}),\n // Per-session persona tier (session > workspace > deployment default).\n // Composed system-level AFTER the workspace persona so it refines it for\n // this one session; absent ⇒ byte-identical to today's composition.\n ...(session.instructions ? { sessionInstructions: session.instructions } : {}),\n // Exact host context captured when this turn was accepted. It is\n // system-level and disappears with the turn rather than entering chat.\n ...(turn.turnInstructions || mcpAvailabilityInstructions\n ? {\n turnInstructions: [turn.turnInstructions, mcpAvailabilityInstructions]\n .filter((value): value is string => Boolean(value))\n .join(\" \"),\n }\n : {}),\n ...workspaceEnvironmentOption,\n // RIG RUNTIME (M3): the doctrine block, the setup-script hook (only when\n // the frozen version carries a non-empty script), and the rig credential\n // hooks. All absent for a rig-less turn (byte-for-byte today).\n ...(rigVersion && rigName\n ? {\n rig: { name: rigName, version: rigVersion.version },\n ...(rigVersion.setupScript && rigVersion.setupScript.trim().length > 0\n ? {\n rigSetup: {\n rigId: session.rigId!,\n versionId: rigVersion.id,\n rigName,\n script: rigVersion.setupScript,\n timeoutMs: runSettings.rigSetupTimeoutMs,\n },\n }\n : {}),\n ...(rigVersion.credentialHooks.length > 0\n ? { rigCredentialHookIds: rigVersion.credentialHooks }\n : {}),\n }\n : {}),\n });\n if (modelRunSettings.sandboxBackend !== \"none\" && toolCancellationFenceRef.current === null) {\n throw new Error(\n \"Sandbox agent construction did not install the mandatory turn tool cancellation fence\",\n );\n }\n if (establishPolicy === \"on-demand\" && sandboxHolderId && sandboxGroupId) {\n const lazyHolderId = sandboxHolderId;\n const lazyGroupId = sandboxGroupId;\n const agentDefaultManifest = (agent as { defaultManifest?: unknown }).defaultManifest;\n if (!agentDefaultManifest) {\n throw new Error(\"Lazy sandbox provisioning requires a SandboxAgent defaultManifest\");\n }\n const lazyClient = {\n backendId: sdkBackendIdForSandboxBackend(groupBoxBackend),\n } as EstablishedSandboxSession[\"client\"];\n turnSandboxProvisioner = createTurnSandboxProvisioner<ResumedTurnSandbox>(\n async () => {\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n const lazyGitCredentials =\n activeSandboxBackend === \"selfhosted\"\n ? undefined\n : await mintRunGitCredentials(runSettings, turnResources, {\n scope: connectionScope,\n ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),\n gitCredentials: connectionCredentials?.gitCredentials,\n authorizeGitHubTokenMint,\n });\n const lazyGitTokens = lazyGitCredentials?.gitTokens;\n const lazyToolspaceToken = sandboxToolspaceToken\n ? await mintSandboxToolspaceToken(runSettings, connectionScope, toolspaceAuthority)\n : undefined;\n const provisioned = await resumeBoxForTurn(\n {\n db,\n settings: runSettings,\n cancellationSignal: sandboxResumeSignal,\n sandboxMetrics: runtimeMetricsHooksForObservability(observability),\n onSandboxLost: publishSandboxLost,\n },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: lazyGroupId,\n sessionId: input.sessionId,\n backend: groupBoxBackend,\n os: session.sandboxOs,\n environment: sandboxEnvironment,\n ...((runSettings.modalImageRef ?? runSettings.dockerImage)\n ? {\n image: runSettings.modalImageRef ?? runSettings.dockerImage,\n }\n : {}),\n },\n \"turn\",\n lazyHolderId,\n );\n await publishSandboxLifecycleEvents(provisioned);\n await attachRunCredentialRenewal(\n provisioned.established.session as RunCredentialCommandSession,\n provisioned,\n );\n const provisionedSetupSession = initialRunCredentialMaterial\n ? withRunCredentialsSession(\n provisioned.established.session as object,\n input.sessionId,\n )\n : provisioned.established.session;\n await runWorkspaceMutationForSandbox(\n provisioned,\n \"lazyOwnedSandboxSetup\",\n async () =>\n await runOwnedSandboxSetup(\n agent,\n provisioned.established.session as never,\n provisionedSetupSession as never,\n {\n settings: runSettings,\n environment: sandboxEnvironment,\n onRuntimeEvent: async (event) => {\n await publish?.([{ type: event.type, payload: event.payload }], true);\n },\n ...(lazyGitTokens ? { gitTokenSeedsOverride: lazyGitTokens } : {}),\n ...(lazyGitCredentials?.bindings\n ? {\n gitCredentialBindingsOverride: lazyGitCredentials.bindings,\n }\n : {}),\n ...(lazyToolspaceToken\n ? {\n toolspaceTokenSeedOverride: lazyToolspaceToken.token,\n }\n : {}),\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n },\n ),\n );\n await attachToolspaceTokenRenewal(\n provisioned.established.session as ToolspaceTokenWriterSession,\n lazyToolspaceToken?.expiresAt,\n provisioned,\n );\n await attachGitCredentialRenewal(\n provisioned.established.session as GitCredentialTokenWriterSession,\n lazyGitCredentials,\n provisioned,\n );\n // Return the REAL established box (NOT a copy whose session is the routing\n // proxy). resolveActiveBackend dispatches ops to `provisioned.established.session`;\n // if that were the proxy itself, proxy.exec -> dispatch -> resolve ->\n // provisioner.get() -> proxy.exec -> ... loops forever (an async infinite\n // recursion that HANGS the turn — caught live on staging 2026-07-08). The SDK\n // already holds the proxy directly (injected as lazyOwnedSandbox.session), so it\n // gets per-op routing; the worker-side handle (resolvedSandbox: release,\n // heartbeat, computer-use recording) wants the real box, unproxied.\n return provisioned;\n },\n {\n signal: sandboxResumeSignal,\n onStarted: async () => {\n await publish?.(\n [\n {\n type: \"sandbox.operation.started\",\n payload: { name: \"sandbox.provision\" },\n },\n ],\n true,\n );\n },\n onCompleted: async (provisioned) => {\n await publish?.(\n [\n {\n type: \"sandbox.operation.completed\",\n payload: {\n name: \"sandbox.provision\",\n ...(provisioned.established.origin\n ? { origin: provisioned.established.origin }\n : {}),\n },\n },\n ],\n true,\n );\n throwIfTurnOperationCancelled(sandboxResumeSignal);\n startLeaseHeartbeat(provisioned, activeSandboxBackend ?? groupBoxBackend);\n setupBoxSession = provisioned.established.session;\n resolvedSandbox = provisioned;\n },\n onFailed: async (error) => {\n await publish?.(\n [\n {\n type: \"sandbox.operation.failed\",\n payload: {\n name: \"sandbox.provision\",\n error: error instanceof Error ? error.message : String(error),\n },\n },\n ],\n true,\n );\n },\n disposeResult: async (provisioned) => {\n await provisioned.release().catch(() => undefined);\n },\n },\n );\n lazyOwnedSandbox = wrapLazyTurnBoxWithRouting(\n {\n db,\n settings,\n bus,\n onOp: machineOpObserver.observer,\n onSandboxOperation: sandboxOperationObserver,\n onHomeSandboxLost: publishSandboxLost,\n onHomeSandboxRebound,\n },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\n workspaceMutationFence: {\n accountId: input.accountId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n },\n {\n client: lazyClient,\n backendId: sdkBackendIdForSandboxBackend(groupBoxBackend),\n agentDefaultManifest,\n provisioner: turnSandboxProvisioner,\n homeLeaseIdentity: {\n accountId: input.accountId,\n sandboxGroupId: session.sandboxGroupId,\n backend: groupBoxBackend,\n },\n },\n );\n }\n const agentInstructions = typeof agent.instructions === \"string\" ? agent.instructions : \"\";\n const compactSummarizer = compactionSummarizerFor(\n agentInstructions.trim() ? agentInstructions : undefined,\n );\n if (remoteCompactionRequester) {\n // Exact byte match with the ordinary turn prefix (CLI base_instructions).\n // Tools serialize lazily inside the requester so setup failures settle as\n // compaction failures rather than raw activity crashes.\n remoteCompactionInstructions = agentInstructions;\n remoteCompactionAgent = agent;\n }\n\n if (compactionOnlyTurn) {\n const requested = await isSessionCompactionRequested(\n db,\n input.workspaceId,\n input.sessionId,\n );\n let outcome: Awaited<ReturnType<typeof maybeCompactContext>> | null = null;\n if (requested) {\n try {\n outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n session.lastInputTokens,\n compactSummarizer,\n {\n force: true,\n clearRequestedCompaction: true,\n trigger: \"operator\",\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n } catch (error) {\n // Codex retries retryable checkpoint-provider failures rather than\n // treating them as a semantic compaction result. Keep the operator\n // request pending and let the ordinary same-turn provider/capacity\n // recovery path re-dispatch this exact maintenance execution.\n if (shouldRecoverCompactionProviderFailure(error)) throw error;\n if (error instanceof TurnAttemptFencedError) throw error;\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: true,\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n if (!isCompactionSummaryFailure(error)) throw error;\n const errorMessage = String(redact(compactionFailureReasonFromError(error)));\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(landmark.requestConsumed ? {} : { consumeRequestedCompactionFailure: true }),\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = error;\n return claimedResult({ status: \"idle\" });\n }\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, \"operator\");\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n }\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: {\n maintenance: \"context_compaction\",\n result: outcome?.compacted ? \"compacted\" : (outcome?.reason ?? \"already_applied\"),\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"completed\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n\n // Pre-turn durable context compaction. When the single Codex-parity\n // threshold is crossed, this summarizes active history and rebuilds active\n // history as [user messages..., summary] BEFORE the model input is read.\n // Summarizer context overflows drop one oldest summarizer-input item and\n // retry, exactly like Codex. Other failures end this turn honestly.\n // Run before every fresh inference. Approval resumes replay their frozen\n // RunState verbatim and recovering attempts already compacted, if needed,\n // before the first attempt's model boundary.\n if (triggerType === \"user.message\" || triggerType === \"system.update.delivered\") {\n let forced = false;\n try {\n // Operator /compact (the slash command) sets a durable request flag;\n // observe it without consuming it so a failed/stale attempt cannot\n // lose the request. The replacement transaction clears it on success.\n forced = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);\n const outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turnId!,\n executionGeneration,\n attemptId: input.attemptId,\n },\n session.lastInputTokens,\n // Provider-aware summarizer: when the turn's model resolved to a\n // registry provider, summarize on THAT provider's client + wire API\n // (a chat provider can't summarize through OpenAI/Azure). Null\n // resolution uses the built-in Responses summarizer with the same\n // session prompt-cache key as the main model calls.\n compactSummarizer,\n forced\n ? {\n force: true,\n clearRequestedCompaction: true,\n trigger: \"operator\",\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n }\n : {\n trigger: \"auto\",\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n const compactionTrigger = forced ? \"operator\" : undefined;\n recordContextCompaction(observability, compactionTrigger ?? \"auto\");\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n } catch (compactError) {\n if (shouldRecoverCompactionProviderFailure(compactError)) throw compactError;\n if (compactError instanceof TurnAttemptFencedError) throw compactError;\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turnId!,\n executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: forced,\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n if (!isCompactionSummaryFailure(compactError)) throw compactError;\n const errorMessage = String(redact(compactionFailureReasonFromError(compactError)));\n observability.error(\"context compaction failed\", {\n sessionId: input.sessionId,\n turnId,\n error: errorMessage,\n });\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(forced && !landmark.requestConsumed\n ? { consumeRequestedCompactionFailure: true }\n : {}),\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = compactError;\n return claimedResult({ status: \"idle\" });\n }\n }\n let fileMaterializationFailures: SandboxFileDownloadFailure[] = [];\n let fileDownloadsMaterializedForRun = false;\n if (resolvedSandbox && setupBoxSession && fileResourceDownloads.length > 0) {\n const boxInstanceId = resolvedSandbox.established.instanceId;\n // Managed boxes are immutable platform state, so their durable lease can\n // memoize successful downloads. A connected machine is user-owned: files\n // can be changed or removed between turns, so verify/materialize every\n // attached file each turn instead of trusting the managed-box cache.\n const cacheMaterialization = resolvedSandbox.established.backendId !== \"selfhosted\";\n const alreadyMaterialized = cacheMaterialization\n ? await getMaterializedSandboxFileResources(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n expectedEpoch: resolvedSandbox.leaseEpoch,\n instanceId: boxInstanceId,\n })\n : new Set<string>();\n const downloadsToMaterialize = filterUnmaterializedSandboxFileDownloads(\n fileResourceDownloads,\n alreadyMaterialized,\n );\n const runAs = sandboxRunAs(runSettings);\n if (downloadsToMaterialize.length > 0) {\n const materialized = await runWorkspaceMutationForSandbox(\n resolvedSandbox,\n \"fileMaterialization\",\n async () =>\n await materializeSandboxFileDownloads(\n setupBoxSession as any,\n downloadsToMaterialize,\n {\n onRuntimeEvent: async (event) => {\n await publish!([{ type: event.type, payload: event.payload }], true);\n },\n ...(runAs ? { runAs } : {}),\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n },\n ),\n );\n fileMaterializationFailures = materialized.failures;\n const failedFileIds = new Set(materialized.failures.map((failure) => failure.fileId));\n const succeededFileIds = downloadsToMaterialize\n .map((download) => download.fileId)\n .filter((fileId) => !failedFileIds.has(fileId));\n if (cacheMaterialization && succeededFileIds.length > 0) {\n await markSandboxFileResourcesMaterialized(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n expectedEpoch: resolvedSandbox.leaseEpoch,\n instanceId: boxInstanceId,\n fileIds: succeededFileIds,\n });\n }\n }\n fileDownloadsMaterializedForRun = true;\n }\n const unavailableSandboxFilesNote = sandboxFileDownloadFailureNote(\n fileMaterializationFailures,\n );\n // Build one attempt from canonical history. The provider adapter creates\n // only the temporary wire view required by this turn's selected API;\n // subscription identity never edits or filters durable history.\n const activeTurnId = turnId;\n if (!activeTurnId) {\n throw new Error(\"Turn id was not initialized\");\n }\n let runInput: Awaited<ReturnType<typeof turnInput>>[\"input\"] | null = null;\n const prepareRunAttemptInput = async () => {\n const prepared = await turnInput(db, runtime, agent, trigger, {\n turnId: activeTurnId,\n recovering: turn.executionGeneration > 1,\n ...(unavailableSandboxFilesNote ? { unavailableSandboxFilesNote } : {}),\n ...(runCredentialsNote ? { runCredentialsNote } : {}),\n providerApi,\n projectModelHistory: modelHistoryProjector,\n });\n runInput = prepared.input;\n providerArtifactCandidates = prepared.providerArtifactCandidates;\n // Slice index = the length of the model-facing (active) history this turn\n // is seeded from; new items beyond it (the trigger message + this turn's\n // generated items) are the ones to persist. After a compaction this is the\n // short [summary, ...tail] active set, NOT the total row count. The\n // absolute write position is tracked separately (next whole number past\n // the max existing position) because the fractional summary row means\n // total rows no longer equal max(position)+1. Pre-compaction both reduce to\n // the old total-count value, so the common path is unchanged.\n //\n // CRITICAL: seed from the SANITIZED active-row length, not the raw active\n // count. `prepareRunInput` builds `state.history` from\n // `sanitizeHistoryItemsForModel(activeRows)`, so when sanitization drops K\n // rows (a legacy orphan/dangling pair), the in-memory history this turn\n // starts from is K shorter than the raw row count. The reconcile slices the\n // re-sanitized `state.history` off `persistedHistoryCount`; seeding it from\n // the raw count (K too high) skips K genuinely-new items, and a\n // `function_call` left in that skipped region can later have its\n // `function_call_result` persisted alone — the orphan that 400s on replay\n // and bricks the session (issue-61). The sanitized seed is already\n // orphan-free, so it is a stable prefix of the re-sanitized history and the\n // slice begins exactly at the first genuinely-new item.\n persistedHistoryCount = prepared.persistedHistoryCount;\n nextHistoryPosition = await nextSessionHistoryPosition(\n db,\n input.workspaceId,\n input.sessionId,\n );\n };\n\n const forceContextCompaction = async (\n triggerLabel: \"overflow\" | \"proactive\" | \"operator\",\n recoverySignalTokens: number | null,\n ) => {\n const outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration,\n attemptId: input.attemptId,\n },\n // Never reuse the persisted prior-turn signal for recovery. Proactive\n // guards provide their exact current provider-based signal; provider\n // overflows do not, so their diagnostic signal stays unknown/zero.\n // Forced recovery proves progress separately by comparing the\n // replacement with the current active-history estimate.\n recoverySignalTokens,\n compactSummarizer,\n {\n force: true,\n ...(triggerLabel === \"operator\" ? { clearRequestedCompaction: true } : {}),\n trigger: triggerLabel,\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, triggerLabel);\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n return outcome;\n };\n\n // Keep response identity across every stream attempt in this\n // activity. Context compaction retries the same logical dispatch by\n // calling runStreamAttempt again; resetting this state there would reuse\n // the first no-response-ID fallback key and suppress a real model call.\n const modelResponseState = createModelResponseEventState(claimedModelUsageSourceKeys);\n const runStreamAttempt = async (): Promise<RunAgentTurnResult> => {\n if (!runInput) {\n throw new Error(\"Run input was not prepared\");\n }\n stream = undefined;\n batcher = null;\n // The SDK emits every processed call item for one model response before\n // it emits any result for that response. Keep that response-local batch\n // in memory so an orphan from an older response cannot pin later stable\n // calls. Durable recovery remains call/result based and needs no batch\n // schema or compatibility state.\n let currentToolBatchCallIds = new Set<string>();\n let currentToolBatchCompletedCallIds = new Set<string>();\n let streamSawPerResponseUsage = false;\n // Actual input tokens of the most recent model response this turn; the\n // pre-read trigger for the NEXT turn. Persisted at every turn-end path.\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n const ownedEstablished = resolvedSandbox?.established ?? lazyOwnedSandbox;\n const runStreamOnce = async (): ReturnType<OpenGeniRuntime[\"runStream\"]> => {\n // Eager owned sessions must settle the exact platform-setup provider\n // promise before the long model stream starts; otherwise one admission\n // would remain in flight for the entire turn and suppress every\n // heartbeat capture. Lazy setup already runs under the same wrapper in\n // its first-operation provisioner above.\n if (resolvedSandbox && !lazyOwnedSandbox && ownedEstablished) {\n const eagerSetupSession = setupBoxSession ?? ownedEstablished.session;\n await runWorkspaceMutationForSandbox(\n resolvedSandbox,\n \"eagerOwnedSandboxSetup\",\n async () =>\n await runOwnedSandboxSetup(\n agent,\n ownedEstablished.session as never,\n eagerSetupSession as never,\n {\n settings: runSettings,\n environment: sandboxEnvironment,\n preparedInput: runInput!,\n ...(fileDownloadsMaterializedForRun ? { fileDownloadsMaterialized: true } : {}),\n onRuntimeEvent: async (event) => {\n await renewCodexLease(\"runtime_event\");\n if (codexLeaseLost) {\n throw new Error(\"Codex credential lease expired during sandbox setup\");\n }\n await publish!([{ type: event.type, payload: event.payload }], true);\n },\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n },\n ),\n );\n await attachGitCredentialRenewal(\n eagerSetupSession as GitCredentialTokenWriterSession,\n initialGitCredentials,\n );\n }\n // Conservative request boundary: once control enters runStream, the\n // provider may have accepted work even if no response/event follows.\n // Escaped MCP setup timeouts are automatically recoverable only\n // before this line.\n modelRequestStarted = true;\n return await runtime.runStream(agent, runInput!, modelRunSettings, {\n signal: runtimeCancellationSignal,\n sandboxEnvironment,\n onRuntimeEvent: async (event) => {\n await renewCodexLease(\"runtime_event\");\n if (codexLeaseLost) {\n throw new Error(\"Codex credential lease expired during the active turn\");\n }\n await publish!([{ type: event.type, payload: event.payload }], true);\n },\n // P1.2: inject the resumed box NON-OWNED (the SDK never reaps it — the\n // keystone). Absent when the flag is off -> legacy build-and-discard.\n ...(ownedEstablished\n ? {\n ownedSandbox: {\n client: ownedEstablished.client,\n session: ownedEstablished.session,\n ...(resolvedSandbox?.established.sessionState\n ? {\n sessionState: resolvedSandbox.established.sessionState,\n }\n : {}),\n // Pin platform setup (hooks + file materialization) to the un-proxied\n // established box — never through the routing proxy, which would\n // re-route those execs onto a machine swapped in mid-turn.\n ...(setupBoxSession ? { setupSession: setupBoxSession } : {}),\n ...(fileDownloadsMaterializedForRun ? { fileDownloadsMaterialized: true } : {}),\n // Both owned paths execute setup outside runStream: eager just\n // above under its exact admission, lazy in the provisioner.\n deferredSetup: true,\n },\n }\n : {}),\n ...(sandboxToolspaceToken && sandboxToolspaceTokenExpiresAt && !lazyOwnedSandbox\n ? {\n onToolspaceTokenSessionReady: async (\n tokenSession: ToolspaceTokenWriterSession,\n ) => {\n const renewalSession =\n activeSandboxBackend === \"selfhosted\"\n ? tokenSession\n : ((setupBoxSession as ToolspaceTokenWriterSession | null) ?? tokenSession);\n await attachToolspaceTokenRenewal(renewalSession);\n },\n }\n : {}),\n ...(runCredentialResolver\n ? {\n runCredentialSessionId: input.sessionId,\n ...(!lazyOwnedSandbox\n ? {\n onRunCredentialSessionReady: async (\n credentialSession: RunCredentialCommandSession,\n ) => {\n const pinnedCredentialSession = setupBoxSession\n ? (setupBoxSession as RunCredentialCommandSession)\n : credentialSession;\n await attachRunCredentialRenewal(pinnedCredentialSession);\n },\n }\n : {}),\n }\n : {}),\n contextCompactionSignal: () => modelResponseContextSignal(modelResponseState),\n contextCompactionRequested: () =>\n isSessionCompactionRequested(db, input.workspaceId, input.sessionId),\n callModelInputFilter: secretRedactionModelInputFilter((value) => redact(value)),\n ...(toolCancellationFenceRef.current\n ? { turnToolCancellationFence: toolCancellationFenceRef.current }\n : {}),\n });\n };\n if (codexLeaseLost) {\n throw new Error(\"Codex credential lease expired before the model run\");\n }\n stream = await withCodex(runStreamOnce);\n // Bounded provider label for the streaming SLIs — the resolved registry\n // provider id (or the built-in OpenAI/Azure provider), never a raw\n // user-supplied model string.\n const streamProvider = resolvedModel?.provider.id ?? settings.openaiProvider ?? \"openai\";\n const streamTiming = new StreamTimingMetrics(observability, {\n provider: streamProvider,\n });\n batcher = createRuntimeBatcher(\n async (events) => {\n await publish!(events);\n },\n {\n onFlush: ({ events, durationSeconds }) =>\n recordBatchFlush(observability, { events, durationSeconds }),\n },\n );\n\n const iterator = stream.toStream()[Symbol.asyncIterator]();\n let streamDone = false;\n try {\n while (true) {\n const next = await nextStreamEvent(iterator, activityContext);\n if (next.done) {\n streamDone = true;\n break;\n }\n let stableToolCallIdsToClear: string[] | null = null;\n let completedCurrentToolBatch = false;\n const responseResult = await processModelResponseTerminalEvent({\n event: next.value,\n state: modelResponseState,\n dispatchId: modelUsageDispatchId,\n settings,\n db,\n observability,\n publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n provider: resolvedModel?.provider.id ?? settings.openaiProvider,\n providerApi: resolvedModel?.provider.api ?? \"responses\",\n model: turn.model,\n latencyMode: turnExecutionPolicy.latencyMode,\n metricProvider: streamProvider,\n externallyBilled: isExternallyBilledTurn,\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n renewLease: () => renewCodexLease(\"model_usage\"),\n leaseLost: () => codexLeaseLost,\n leaseLostMessage: \"Codex credential lease expired during the active turn\",\n setLastInputTokens: setLastInputTokensFenced,\n });\n assertModelResponseLatencyMode({\n event: next.value,\n requested: turnExecutionPolicy.latencyMode,\n model: turn.model,\n ...(resolvedModel?.provider.id ? { providerId: resolvedModel.provider.id } : {}),\n });\n if (responseResult.status === \"processed\") {\n streamSawPerResponseUsage ||= responseResult.usageReported;\n currentToolBatchCallIds = new Set<string>();\n currentToolBatchCompletedCallIds = new Set<string>();\n await reconcileConversationTruth();\n try {\n await ensureRunAllowed(\n settings,\n db,\n input.accountId,\n input.workspaceId,\n isExternallyBilledTurn,\n entitlements,\n );\n } catch (limitError) {\n // Capture the run state at the boundary so the budget valve in\n // the outer catch can end this segment gracefully with full\n // conversation context preserved for the post-top-up resume.\n let serializedRunState: string | null = null;\n try {\n serializedRunState = String(redact(stream.state.toString()));\n } catch {\n serializedRunState = null;\n }\n throw new BudgetExhaustedError(\n limitError instanceof Error ? limitError.message : String(limitError),\n serializedRunState,\n );\n }\n }\n const pendingToolCall = pendingToolCallFromSdkEvent(next.value);\n if (pendingToolCall) {\n const registered = await registerPendingSessionToolCall(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration,\n attemptId: input.attemptId,\n modelToolOutputTruncationTokens: modelRunSettings.modelToolOutputTruncationTokens,\n callId: pendingToolCall.callId,\n callType: pendingToolCall.callType,\n callItem: redact(pendingToolCall.callItem) as Record<string, unknown>,\n });\n if (!registered.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while recording an in-flight tool call\",\n );\n }\n currentToolBatchCallIds.add(pendingToolCall.callId);\n }\n const completedToolCall = completedToolCallFromSdkEvent(next.value);\n if (completedToolCall) {\n // Keep every parallel result in the attempt ledger until the full\n // call batch has settled. The SDK's computed history is\n // non-monotonic while parallel calls complete (a later call may\n // appear before an earlier persisted pair), so reconciling a\n // partial batch through a scalar watermark can create an orphan.\n const recorded = await recordPendingSessionToolCallResult(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration,\n attemptId: input.attemptId,\n callId: completedToolCall.callId,\n modelToolOutputTruncationTokens: modelRunSettings.modelToolOutputTruncationTokens,\n resultItem: redact(completedToolCall.resultItem) as Record<string, unknown>,\n });\n if (!recorded.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while recording a tool-call result\",\n );\n }\n const belongsToCurrentBatch = currentToolBatchCallIds.has(completedToolCall.callId);\n if (belongsToCurrentBatch) {\n currentToolBatchCompletedCallIds.add(completedToolCall.callId);\n }\n const currentBatchIsStable =\n belongsToCurrentBatch &&\n currentToolBatchCallIds.size > 0 &&\n currentToolBatchCompletedCallIds.size === currentToolBatchCallIds.size;\n const standaloneStableResult =\n !belongsToCurrentBatch && currentToolBatchCallIds.size === 0;\n if (currentBatchIsStable || standaloneStableResult) {\n // Persist the SDK's now-stable complete call/result batch. Keep\n // the receipts until the normalized tool-output event below is\n // durably flushed: recovery then covers every crash boundary\n // without either losing or duplicating the UI projection.\n await reconcileConversationTruth({ requireDurable: true });\n stableToolCallIdsToClear = currentBatchIsStable\n ? [...currentToolBatchCallIds]\n : [completedToolCall.callId];\n completedCurrentToolBatch = currentBatchIsStable;\n }\n }\n const normalized = normalizeSdkEvent(next.value);\n for (const event of normalized) {\n streamTiming.onEvent(event.type);\n await batcher.push(event);\n }\n if (stableToolCallIdsToClear) {\n const cleared = await clearDurablePendingSessionToolCalls(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration,\n attemptId: input.attemptId,\n callIds: stableToolCallIdsToClear,\n });\n if (!cleared.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while finalizing tool-call results\",\n );\n }\n if (completedCurrentToolBatch) {\n currentToolBatchCallIds = new Set<string>();\n currentToolBatchCompletedCallIds = new Set<string>();\n }\n }\n }\n } finally {\n if (!streamDone) {\n // ReadableStream cancellation synchronously trips the Agents SDK's\n // abort controller, but its returned promise may wait for an\n // uncooperative provider producer. Once this attempt is fenced,\n // awaiting that provider-side cleanup pins the Temporal activity\n // (and therefore Pause) even though every late write is already\n // rejected. Start cancellation and detach only its cleanup wait;\n // the SDK abort signal stops the producer and the durable attempt\n // fence remains the authority for every callback that arrives late.\n void iterator.return?.().catch(() => undefined);\n }\n }\n await waitForTurnStreamCleanup(\n batcher.flush(),\n stream.completed.catch(() => undefined),\n cancellationSignal,\n );\n if (!streamSawPerResponseUsage) {\n const aggregateUsage = stream.state.usage;\n const normalizedAggregateUsage = normalizeModelCallUsage(aggregateUsage);\n const aggregateInput = normalizedAggregateUsage.telemetry.inputTokens;\n const aggregateSourceKey = modelUsageSourceKey({\n responseId: null,\n dispatchId: modelUsageDispatchId,\n positionalKey: \"aggregate\",\n });\n if (!claimedModelUsageSourceKeys.has(aggregateSourceKey)) {\n claimedModelUsageSourceKeys.add(aggregateSourceKey);\n // The aggregate frame is only a billing fallback when no terminal\n // response exposed usage. It is not final-request context authority.\n const aggregateAccountCtx = modelCallAccountContext({\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n isFirstCallOfTurn: true,\n });\n let aggregateAuthoritative = false;\n await recordCompletedModelCallBeforeOwnershipFences({\n renewLease: () => renewCodexLease(\"model_usage\"),\n leaseLost: () => codexLeaseLost,\n leaseLostMessage: \"Codex credential lease expired during the active turn\",\n recordUsage: async () => {\n const billing = await recordModelUsageAndDebitCredits(settings, db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n model: turn.model,\n externallyBilled: isExternallyBilledTurn,\n usage: aggregateUsage,\n normalizedUsage: normalizedAggregateUsage,\n sourceKey: aggregateSourceKey,\n latencyMode: turnExecutionPolicy.latencyMode,\n observability,\n });\n const aggregateProvider = resolvedModel?.provider.id ?? settings.openaiProvider;\n const aggregateProviderApi = resolvedModel?.provider.api ?? \"responses\";\n aggregateAuthoritative = await emitModelCallUsage({\n observability,\n publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n provider: aggregateProvider,\n providerApi: aggregateProviderApi,\n model: turn.model,\n sourceKey: aggregateSourceKey,\n usage: { usage: aggregateUsage },\n normalizedUsage: normalizedAggregateUsage,\n servingAccountHash: aggregateAccountCtx.servingAccountHash,\n accountChangedFromPrevCall: aggregateAccountCtx.accountChangedFromPrevCall,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n });\n if (aggregateAuthoritative && billing) {\n await recordAuthoritativeModelCallFact({\n db,\n observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n sourceKey: aggregateSourceKey,\n provider: aggregateProvider,\n providerApi: aggregateProviderApi,\n model: turn.model,\n billing,\n });\n }\n if (aggregateAuthoritative && aggregateInput !== null && aggregateInput > 0) {\n recordModelInputTokens(observability, streamProvider, aggregateInput);\n }\n },\n recordAttemptSignals: async () => {\n if (!aggregateAuthoritative) return;\n // Stream aggregates can cover multiple requests and therefore\n // cannot identify the final request that compaction must bind.\n // They remain billing/telemetry fallback data only.\n modelResponseState.contextSignal = null;\n await setLastInputTokensFenced(null);\n },\n });\n }\n }\n if (stream.interruptions.length > 0) {\n await reconcileConversationTruth();\n const approvals = runtime.serializeApprovals(stream.interruptions);\n const humanInputInterruptions =\n runtime.serializeHumanInputRequests?.(stream.interruptions) ?? [];\n const humanInputRequests = await Promise.all(\n humanInputInterruptions.map(async (interruption) => {\n const id = stableHumanInputRequestId(\n input.sessionId,\n activeTurnId,\n interruption.toolCallId,\n );\n const existing = await getSessionHumanInputRequest(\n db,\n input.workspaceId,\n input.sessionId,\n id,\n );\n if (existing && existing.status !== \"pending\") {\n throw new Error(`Settled human-input request ${id} reappeared as an interruption`);\n }\n const expiresAt = existing?.expiresAt\n ? new Date(existing.expiresAt)\n : interruption.input.expiresInSeconds\n ? new Date(Date.now() + interruption.input.expiresInSeconds * 1000)\n : null;\n return {\n id,\n toolCallId: interruption.toolCallId,\n questions: interruption.input.questions,\n allowSkip: interruption.input.allowSkip,\n expiresAt,\n isNew: existing === null,\n };\n }),\n );\n const requestEvents = humanInputRequests\n .filter((request) => request.isNew)\n .map((request) => ({\n type: \"session.humanInput.requested\" as const,\n payload: {\n request: {\n id: request.id,\n questions: request.questions,\n allowSkip: request.allowSkip,\n expiresAt: request.expiresAt?.toISOString() ?? null,\n },\n },\n }));\n if (\n !(await settle!({\n events: [\n ...requestEvents,\n ...(approvals.length > 0\n ? [\n {\n type: \"session.requiresAction\" as const,\n payload: { approvals },\n },\n ]\n : []),\n {\n type: \"session.status.changed\",\n payload: { status: \"requires_action\" },\n },\n ],\n turnStatus: \"requires_action\",\n sessionStatus: \"requires_action\",\n activeTurnId,\n runState: {\n serializedRunState: stream.state.toString(),\n pendingApprovals: approvals,\n humanInputRequests: humanInputRequests.map(\n ({ isNew: _isNew, ...request }) => request,\n ),\n },\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n activityStatus = \"requires_action\";\n return claimedResult({ status: \"requires_action\" });\n }\n\n const finalOutput = String(redact(String(stream.finalOutput ?? \"\")));\n await reconcileConversationTruth();\n // Op-stream durability fence: the tool outputs are now durably in the\n // history store (a redispatch would NOT re-execute them), so this\n // turn's settled ops may advance their acked frontier — journal persist\n // then wire final ack (licensing the runner to GC its retained\n // frames). Best-effort: a miss leaves the runner's retention TTL to\n // reap, never fails a completed turn.\n if (machinePrimarySession) {\n try {\n await machinePrimarySession.finalizeOpStreamOps();\n } catch {\n // The runner's retention TTL owns the fallback.\n }\n }\n if (\n !(await settle!({\n events: [\n {\n type: \"agent.message.completed\",\n payload: { text: finalOutput },\n },\n { type: \"turn.completed\", payload: { output: finalOutput } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"completed\";\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"agent_run.completed\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"session_turn\",\n sourceResourceId: activeTurnId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n idempotencyKey: `usage:agent_run.completed:${activeTurnId}`,\n });\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n };\n\n await prepareRunAttemptInput();\n let retriedAfterCompaction = false;\n while (true) {\n try {\n const result = await runStreamAttempt();\n if (retriedAfterCompaction) {\n observability.info(\"context compaction recovery succeeded after in-activity retry\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n });\n }\n return result;\n } catch (attemptError) {\n const overflow = classifyContextWindowOverflowError(attemptError);\n const compactionNeeded = findCompactionNeededError(attemptError);\n const recoveryKind = compactionNeeded\n ? compactionNeeded.trigger === \"operator\"\n ? \"operator\"\n : \"proactive\"\n : overflow\n ? \"overflow\"\n : null;\n if (!recoveryKind || !publish || !turnStartedPublished) {\n throw attemptError;\n }\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ skipInputOnlyRows: true });\n observability.warn(\"context compaction recovery attempted\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n code: overflow?.code ? String(redact(overflow.code)) : undefined,\n error: String(redact(overflow?.message ?? compactionNeeded?.message ?? \"\")),\n signalTokens: compactionNeeded?.signalTokens,\n thresholdTokens: compactionNeeded?.thresholdTokens,\n });\n let compacted = false;\n let compactionHandled = false;\n let compactionFailureMessage: string | null = null;\n let compactionRequestCleared = false;\n try {\n const outcome = await forceContextCompaction(\n recoveryKind,\n compactionNeeded?.signalTokens ?? null,\n );\n compacted = outcome.compacted;\n if (outcome.compacted) {\n compactionHandled = true;\n } else {\n compactionHandled = recoveryKind === \"operator\" && outcome.requestConsumed;\n if (!compactionHandled) {\n compactionFailureMessage = compactionFailureReason(outcome.reason);\n }\n }\n } catch (compactError) {\n // Transient checkpoint-provider failures recover this same accepted\n // turn through the normal provider/capacity path. They are not an\n // empty summary and must not create a new goal continuation.\n if (shouldRecoverCompactionProviderFailure(compactError)) throw compactError;\n if (compactError instanceof TurnAttemptFencedError) throw compactError;\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId!,\n executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: recoveryKind === \"operator\",\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n compactionRequestCleared = landmark.requestConsumed;\n if (!isCompactionSummaryFailure(compactError)) throw compactError;\n compactionFailureMessage = String(\n redact(compactionFailureReasonFromError(compactError)),\n );\n observability.warn(\"context compaction recovery compaction failed\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n error: compactionFailureMessage,\n });\n }\n if (!compactionHandled) {\n const errorMessage =\n compactionFailureMessage ??\n \"compaction summarization failed: compaction produced no replacement history\";\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(recoveryKind === \"operator\" && !compactionRequestCleared\n ? { consumeRequestedCompactionFailure: true }\n : {}),\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = attemptError;\n // The failed turn settlement already defers ordinary internal\n // updates and makes the delivered goal-continuation receipt\n // terminal. End this workflow run as well: returning plain idle\n // would immediately synthesize another goal continuation against\n // the unchanged active history and repeat the same failed\n // compaction. A new human/API prompt, Steer, or explicitly requested\n // Compact remains a durable explicit wake and may retry; ordinary\n // machine updates stay pending for that actionable wake.\n return claimedResult({ status: \"idle\", deferredUntilWake: true });\n }\n // Codex parity: compaction remains inside the same logical turn and\n // the same activity. Rebuild the model-visible history from the\n // durable replacement and continue the sampling loop; do not create\n // a recovery event, a queue row, a fake user message, or a sandbox.\n retriedAfterCompaction = true;\n observability.info(\"context compaction recovery retrying turn after compaction\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n compacted,\n });\n await prepareRunAttemptInput();\n }\n }\n } catch (error) {\n // Graceful worker shutdown (deploy / rollout restart): checkpoint the\n // same current inference for a new fenced attempt instead of failing the\n // session. Conversation truth is already persisted per model response;\n // the final reconcile bounds loss to the one in-flight model step.\n //\n // The branch deliberately does NOT require turn.started to have been\n // published: a shutdown landing during setup (claim/billing, before the\n // turn visibly started) must also recover, not fail the session. In that\n // early case nothing ran, so the new attempt uses the original trigger.\n // The turn id falls\n // back to the workflow-claimed turn when the local lookup had not\n // finished yet.\n const recoveryTurnId = turnId;\n // P1.2: a lease supersession during resume (a newer epoch re-established\n // the box concurrently) is NOT a session failure. Recover the same turn\n // so its next attempt reattaches under the current epoch.\n if (error instanceof SandboxLeaseSupersededError && recoveryTurnId) {\n try {\n const fencedLease = await readLease(db, input.workspaceId, error.sandboxGroupId).catch(\n () => null,\n );\n const rotationPending = fencedLease?.rotationRequestedAt != null;\n const deadlineRotationPending =\n rotationPending && fencedLease?.rotationReason === \"provider_deadline\";\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: deadlineRotationPending\n ? \"sandbox_deadline_rotation\"\n : \"sandbox_lease_superseded\",\n ...(rotationPending\n ? {\n detail: {\n sandboxGroupId: error.sandboxGroupId,\n leaseEpoch: error.leaseEpoch,\n rotationReason: fencedLease?.rotationReason ?? \"operator\",\n },\n }\n : {}),\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n recovery.events,\n );\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({\n status: \"recovering\",\n ...(rotationPending\n ? {\n continueDelayMs: sandboxDeadlineRotationRecoveryDelayMs(settings),\n }\n : {}),\n });\n } catch (recoveryError) {\n console.error(\n \"sandbox lease supersession recovery failed\",\n safeErrorDiagnostic(recoveryError, (value) => String(redact(value))),\n );\n throw recoveryError;\n }\n }\n if (\n sandboxRotationController.signal.aborted &&\n sandboxRotationController.signal.reason instanceof SandboxDeadlineRotationError &&\n !cancellationSignal?.aborted &&\n recoveryTurnId\n ) {\n try {\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n const rotation = sandboxRotationController.signal.reason;\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: \"sandbox_deadline_rotation\",\n detail: {\n sandboxGroupId: rotation.sandboxGroupId,\n leaseEpoch: rotation.leaseEpoch,\n },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n recovery.events,\n );\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({\n status: \"recovering\",\n continueDelayMs: sandboxDeadlineRotationRecoveryDelayMs(settings),\n });\n } catch (recoveryError) {\n console.error(\n \"sandbox deadline rotation recovery failed\",\n safeErrorDiagnostic(recoveryError, (value) => String(redact(value))),\n );\n throw recoveryError;\n }\n }\n const cancellationFailure = turnOperationCancellationFailure(error);\n if (\n cancellationFailure &&\n isWorkerShutdownCancellation(cancellationFailure) &&\n recoveryTurnId\n ) {\n try {\n await flushRuntimeBatcher();\n await reconcileConversationTruth();\n // An approval-decision rerun always replays its original trigger:\n // the decision is applied through the approval resume path reading\n // the frozen RunState blob (the only representation of a turn\n // paused mid-flight), so swapping the trigger for a resume notice\n // could drop the user's decision. Re-applying an already-consumed\n // approval re-executes at most the single approved step — the same\n // bound every recovery already accepts.\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: \"worker_shutdown\",\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n recovery.events,\n );\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n } catch (recoveryError) {\n // The database transition is atomic. If it could not commit, surface\n // the failure so Temporal can retry on a healthy worker; never mutate\n // the turn through a second cancellation path.\n console.error(\n \"worker-shutdown recovery checkpoint failed\",\n safeErrorDiagnostic(recoveryError, (value) => String(redact(value))),\n );\n throw recoveryError;\n }\n }\n if (error instanceof TurnAttemptFencedError) {\n activityStatus = \"cancelled\";\n activityError = error;\n acknowledgeQuiescence = true;\n noteCancellationRequested();\n await waitForTurnFinalizerStep(\n flushRuntimeBatcher(),\n turnFinalizerCancellationSignal(cancellationSignal, activityStatus),\n );\n // Ownership already moved to a newer attempt or an authoritative\n // control transaction. Surface the exact transport cancellation rather\n // than a normal result. Temporal terminalization remains diagnostic\n // only; replacement admission waits for the activity-owned durable\n // quiescence receipt written from the hard tool fence below.\n turnMetricOutcome = \"cancelled\";\n throw new CancelledFailure(\"TURN_ATTEMPT_FENCED\", [], error);\n }\n if (cancellationFailure) {\n activityStatus = \"cancelled\";\n activityError = error;\n acknowledgeQuiescence = true;\n noteCancellationRequested();\n await waitForTurnFinalizerStep(\n flushRuntimeBatcher(),\n turnFinalizerCancellationSignal(cancellationSignal, activityStatus),\n );\n // The workflow owns cancellation settlement: Pause/Steer controls use\n // settleSessionControl, and heartbeat timeouts use worker-death\n // recovery. A dying activity must never append a\n // competing cancellation or mutate the turn/session on its own.\n turnMetricOutcome = \"cancelled\";\n throw cancellationFailure;\n }\n // The SDK's per-segment turn cap is a pacing valve, not a failure: end\n // the turn gracefully and idle the session so an active goal continues\n // via a synthesized continuation turn (or a user message resumes work).\n // The run state captured at the cap keeps full conversation context for\n // that resumption.\n const maxTurns = maxTurnsExceededRunState(error);\n if (maxTurns && publish && turnId && turnStartedPublished) {\n await flushRuntimeBatcher();\n // The SDK attaches the run state at the throw site; persisting it lets\n // the continuation resume with this segment's full context. If capture\n // ever fails, the continuation falls back to the previous snapshot --\n // degraded context, flagged on the event, but still strictly better\n // than a terminal failed session: the sandbox filesystem state\n // persists independently and the agent re-derives from it.\n await reconcileConversationTruth();\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: { output: \"\", segmentLimit: \"max_turns\" },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"completed\";\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"agent_run.completed\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"session_turn\",\n sourceResourceId: turnId,\n sessionId: input.sessionId,\n turnId,\n turnAttemptId: input.attemptId,\n idempotencyKey: `usage:agent_run.completed:${turnId}`,\n });\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n const settleLostCodexAttempt = async (\n lostTurnId: string,\n holderId: string,\n generation: number,\n historyCheckpointDurable = false,\n ): Promise<RunAgentTurnResult> => {\n let checkpointDurable = historyCheckpointDurable;\n try {\n if (!historyCheckpointDurable) {\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n }\n checkpointDurable = true;\n } catch (checkpointError) {\n observability.warn(\"Codex lease-loss checkpoint failed; refusing automatic turn replay\", {\n workspaceId: input.workspaceId,\n turnId: lostTurnId,\n errorName: checkpointError instanceof Error ? checkpointError.name : \"unknown\",\n });\n }\n\n const settlement = await settleCodexCredentialLeaseLoss(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: lostTurnId,\n attemptId: input.attemptId,\n holderId,\n generation,\n expectedRedispatches: redispatchesAtDispatch,\n checkpointDurable,\n recoveryPayload: {\n triggerEventId: triggerEventId!,\n reason: \"codex_lease_lost\",\n credentialId: effectiveCodexCredentialId,\n },\n failedPayload: {\n error:\n \"The Codex credential lease was lost and the latest conversation checkpoint could not be persisted. Automatic replay was refused.\",\n code: \"codex_lease_checkpoint_failed\",\n retryable: false,\n },\n });\n codexLeaseHeld = false;\n observability.incrementCounter({\n name: \"opengeni_codex_lease_loss_settlements_total\",\n help: \"Fenced Codex lease-loss settlements by outcome.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n outcome: settlement.action,\n },\n });\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n settlement.events,\n );\n activityError = error;\n if (settlement.action === \"failed\") {\n activityStatus = \"failed\";\n turnMetricOutcome = \"failed\";\n await deliverFailedChildTurnToParent(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n lostTurnId,\n );\n return claimedResult({ status: \"failed\" });\n }\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n };\n\n // A missing/expired/superseded lease is an execution-ownership failure,\n // not a provider failure. Settle it before credential quarantine or the\n // generic terminal path: the DB transaction marks a still-current turn\n // recoverable, but a successor attempt or worker recovery makes this activity\n // stale and unable to clobber the shared turn/session.\n if (\n codexLeaseLost &&\n settings.codexCredentialLeasingEnabled &&\n isCodexTurn &&\n publish &&\n turnId &&\n turnStartedPublished &&\n codexLeaseHolderId &&\n codexLeaseGeneration !== null\n ) {\n return await settleLostCodexAttempt(turnId, codexLeaseHolderId, codexLeaseGeneration);\n }\n // Definitive Codex credential/account refusals are the only provider\n // errors that may walk the pool. This is an explicit checkpoint + SAME\n // turn recovery, never an SDK/Temporal blind retry. A network break,\n // malformed/partial 200 stream, invalid content, prompt 4xx, or provider\n // 5xx does not classify here and therefore cannot consume another\n // subscription or duplicate a side effect.\n const codexCredentialFailure =\n settings.codexCredentialLeasingEnabled && isCodexTurn && effectiveCodexCredentialId\n ? classifyCodexCredentialFailure(error)\n : null;\n if (\n codexCredentialFailure &&\n effectiveCodexCredentialId &&\n publish &&\n turnId &&\n turnStartedPublished\n ) {\n observability.incrementCounter({\n name: \"opengeni_codex_credential_failures_total\",\n help: \"Definitive Codex credential failures classified for safe failover.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n kind: codexCredentialFailure.kind,\n outcome: \"classified\",\n },\n });\n const failoverStartedAt = performance.now();\n let checkpointDurable = false;\n try {\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n checkpointDurable = true;\n } catch (checkpointError) {\n observability.incrementCounter({\n name: \"opengeni_codex_failover_checkpoints_total\",\n help: \"Durable Codex failover checkpoint attempts by outcome.\",\n labels: { workspace_key: codexWorkspaceKey, outcome: \"failed\" },\n });\n observability.warn(\"Codex failover checkpoint failed; refusing automatic replay\", {\n workspaceId: input.workspaceId,\n turnId,\n errorName: checkpointError instanceof Error ? checkpointError.name : \"unknown\",\n });\n }\n\n if (checkpointDurable) {\n observability.incrementCounter({\n name: \"opengeni_codex_failover_checkpoints_total\",\n help: \"Durable Codex failover checkpoint attempts by outcome.\",\n labels: { workspace_key: codexWorkspaceKey, outcome: \"completed\" },\n });\n const now = new Date();\n const before = await listCodexAccountStatuses(db, input.workspaceId).catch(() => []);\n const servingCached = before.find((account) => account.id === effectiveCodexCredentialId);\n const usageSnapshot = latestCodexUsage as CodexUsageHeaderSnapshot | null;\n const serving = servingCached\n ? {\n ...servingCached,\n ...(usageSnapshot\n ? {\n primaryUsedPercent: usageSnapshot.primaryUsedPercent,\n primaryResetAt: usageSnapshot.primaryResetAt,\n secondaryUsedPercent: usageSnapshot.secondaryUsedPercent,\n secondaryResetAt: usageSnapshot.secondaryResetAt,\n }\n : {}),\n }\n : null;\n const cooldownUntil = codexCredentialCooldownUntil(codexCredentialFailure, serving, now);\n const statePersisted =\n codexLeaseHolderId && codexLeaseGeneration !== null\n ? await quarantineCodexCredentialForLease(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n turnId,\n credentialId: effectiveCodexCredentialId,\n holderId: codexLeaseHolderId,\n generation: codexLeaseGeneration,\n quarantine:\n codexCredentialFailure.kind === \"auth\"\n ? {\n kind: \"status\",\n status: \"needs_relogin\",\n lastError: \"model request remained unauthorized after refresh\",\n }\n : codexCredentialFailure.kind === \"forbidden\"\n ? {\n kind: \"status\",\n status: \"error\",\n lastError: \"model request was forbidden for this credential\",\n }\n : { kind: \"cooldown\", until: cooldownUntil! },\n })\n : false;\n if (!statePersisted && codexLeaseHolderId && codexLeaseGeneration !== null) {\n codexLeaseLost = true;\n return await settleLostCodexAttempt(\n turnId,\n codexLeaseHolderId,\n codexLeaseGeneration,\n true,\n );\n }\n const [rotation, accounts] = await Promise.all([\n getCodexRotationSettings(db, input.workspaceId).catch(() => null),\n listCodexAccountStatuses(db, input.workspaceId).catch(() => []),\n ]);\n const decision = rotation\n ? chooseRotationActive({\n rotationStrategy: rotation.rotationStrategy as CodexRotationStrategy,\n activeCredentialId: rotation.activeCredentialId,\n priorCredentialId: effectiveCodexCredentialId,\n accounts,\n now: new Date(),\n })\n : ({ kind: \"none\" } as const);\n const candidateAvailable =\n statePersisted &&\n Boolean(rotation?.rotationEnabled && rotation?.leaseRotationEnabled) &&\n decision.kind === \"active\" &&\n decision.credentialId !== effectiveCodexCredentialId;\n\n if (candidateAvailable && codexLeaseHolderId && codexLeaseGeneration !== null) {\n const settlement = await settleCodexCredentialFailover(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n holderId: codexLeaseHolderId,\n generation: codexLeaseGeneration,\n expectedRedispatches: redispatchesAtDispatch,\n maxFailovers: Math.max(1, accounts.length),\n recoveryPayload: {\n triggerEventId: triggerEventId!,\n reason: \"codex_credential_failover\",\n credentialId: effectiveCodexCredentialId,\n failureKind: codexCredentialFailure.kind,\n ...(cooldownUntil ? { cooldownUntil: cooldownUntil.toISOString() } : {}),\n },\n });\n observability.incrementCounter({\n name: \"opengeni_codex_failover_settlements_total\",\n help: \"Atomic Codex failover settlements by outcome.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n outcome: settlement.action,\n },\n });\n if (settlement.action === \"recovering\") {\n codexLeaseHeld = false;\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n settlement.events,\n );\n observability.observeHistogram({\n name: \"opengeni_codex_failover_recovery_seconds\",\n help: \"Time from credential refusal to durable same-turn recovery.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n kind: codexCredentialFailure.kind,\n },\n value: Math.max(0, (performance.now() - failoverStartedAt) / 1000),\n });\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n }\n if (settlement.action === \"stale\") {\n // One transaction proves both exact-holder recovery (including a\n // just-expired or reaped lease row) and successor/control-gate\n // rejection. Cross the hard tool fence so a control-gate loss can\n // write its quiescence receipt; a successor-only loss is a no-op.\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"recovering\" });\n }\n }\n }\n }\n // A ChatGPT/Codex usage cap (429 usage_limit_reached) is account state,\n // NOT an agent failure: surface the precise, actionable message (so the\n // user sees the reset window) but idle the session — never go terminal,\n // which would reject the user's next message after the cap lifts. The\n // payload is retryable:false so the generic provider-backpressure auto-retry\n // does not loop. For an active goal we hold the continuation for the reported\n // reset window (capped) so it resumes itself when access returns, instead of\n // hammering the capped backend.\n const usageLimit = isCodexTransportError(error) ? classifyCodexUsageLimitError(error) : null;\n if (usageLimit && publish && turnId && turnStartedPublished) {\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId).catch(() => null);\n const goalActive = Boolean(goal && goal.status === \"active\");\n await flushRuntimeBatcher();\n await reconcileConversationTruth();\n // --- P3 reactive rotation (gated; re-fetch fresh state on this already-failed,\n // already-idling path). Mark THIS account cooling until its reset, then CONSULT the\n // engine over fresh accounts to decide continueDelayMs: a fast 0-delay re-dispatch\n // when another account is available, or idle-until-earliest when all are capped. The\n // catch deliberately does NOT move the active pointer — the re-dispatched turn's\n // proactive seam (turn-start) is the single authoritative pointer-move + strip site.\n let rotated = false;\n let rotationResumeMs: number | null = null; // 0 ⇒ a candidate is available; re-dispatch now\n let rotationResumeIdleUntilReset = false; // circuit-breaker fall (Finding 1b) ⇒ MANDATORY hold\n let allCappedResetAt: Date | null = null; // set ⇒ every account capped; idle until this\n let capacityAuthoritativeResetAt: Date | null = null;\n if (effectiveCodexCredentialId) {\n const [rotation, sessionCodex] = await Promise.all([\n getCodexRotationSettings(db, input.workspaceId).catch(() => null),\n getSessionCodexState(db, input.workspaceId, input.sessionId).catch(() => null),\n ]);\n const reactiveStrategy = (rotation?.rotationStrategy ??\n \"most_remaining\") as CodexRotationStrategy;\n const reactiveDisposition = classifyCodexPin({\n pinnedCredentialId: sessionCodex?.pinnedCredentialId ?? null,\n pinSource: sessionCodex?.pinSource ?? null,\n strategy: reactiveStrategy,\n rotationEnabled: Boolean(rotation?.rotationEnabled),\n });\n const reactiveSharded = reactiveDisposition === \"sharded\";\n const rotating =\n Boolean(rotation?.rotationEnabled || rotation?.leaseRotationEnabled) &&\n reactiveDisposition !== \"manual\";\n if (rotating && rotation) {\n const accounts = await listCodexAccountStatuses(db, input.workspaceId).catch(() => []);\n const serving = accounts.find((a) => a.id === effectiveCodexCredentialId) ?? null;\n // Both provider allowance windows bind. Use the same canonical\n // quarantine calculation as the fenced failover path so a short\n // five-hour reset can never overwrite a later weekly reset.\n const until = codexCredentialCooldownUntil(\n { kind: \"quota\", cooldownSeconds: usageLimit.resetsInSeconds },\n serving,\n new Date(),\n )!;\n // Finding 1a: INSPECT the cooldown-write result. A swallowed best-effort\n // write whose failure went unnoticed is exactly what lets the next proactive\n // rank re-pick this just-capped account (stale-low cached usedPercent, not\n // cooling) — so capture whether it PERSISTED and feed it into the resume floor.\n const cooldownMutation = await setCodexCredentialExhaustedWithWakeTargets(\n db,\n input.workspaceId,\n effectiveCodexCredentialId,\n until,\n ).catch(() => null);\n const cooldownPersisted = cooldownMutation?.result ?? false;\n if (cooldownMutation) {\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n cooldownMutation.wakeTargets,\n );\n }\n // Re-rank over the fresh accounts; the in-memory list predates the cooldown\n // write, so stamp the just-cooled account so the engine excludes it now. The\n // serving account is thus walked AT MOST ONCE per turn (invariant 4: bounded).\n const fresh = accounts.map((a) =>\n a.id === effectiveCodexCredentialId ? { ...a, exhaustedUntil: until } : a,\n );\n if (reactiveSharded) {\n // AM-5: RE-SHARD over the healthy survivors (the just-capped serving account is\n // marked cooling in `fresh` → excluded) so sessions sharing a capped account\n // spread across the pool rather than re-concentrating on one first-eligible\n // failover. AM-3: DURABLY REWRITE the session's POLICY pin to the new home —\n // selectCodexCredentialForTurn returns a cooling pinned account with NO\n // exhaustion check, so a pointer-only move would leave the re-dispatched turn on\n // the capped pin. Like the classic path we do NOT touch the workspace active\n // pointer; the session pin is the sharded home.\n const newHome = shardCredentialForSession({\n sessionId: input.sessionId,\n accounts: fresh,\n now: new Date(),\n });\n if (newHome) {\n rotated = true;\n const pinMutation = await withCodexCapacityMutation(\n db,\n {\n workspaceId: input.workspaceId,\n reason: \"codex_policy_pin_resharded\",\n },\n async (tx) => {\n const changed = await setSessionCodexPin(\n tx,\n input.workspaceId,\n input.sessionId,\n newHome,\n \"policy\",\n {\n expected: {\n pinnedCredentialId: sessionCodex?.pinnedCredentialId ?? null,\n pinSource: sessionCodex?.pinSource ?? null,\n },\n },\n );\n return { result: changed, changed };\n },\n ).catch(() => null);\n if (pinMutation) {\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n pinMutation.wakeTargets,\n );\n }\n const priorConsecutiveRotations = await countConsecutiveReactiveRotations(\n db,\n input.workspaceId,\n input.sessionId,\n ).catch(() => 0);\n const resume = computeReactiveRotationResume({\n cooldownPersisted,\n priorConsecutiveRotations,\n connectedAccountCount: accounts.length,\n });\n rotationResumeMs = resume.continueDelayMs;\n rotationResumeIdleUntilReset = resume.idleUntilReset;\n } else {\n // Every account capped/cooling → idle until the earliest reset across all.\n rotated = true;\n allCappedResetAt = earliestCodexReset(fresh, new Date());\n capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(fresh, new Date());\n }\n } else {\n const decision = chooseRotationActive({\n rotationStrategy: reactiveStrategy,\n activeCredentialId: rotation.activeCredentialId,\n priorCredentialId: effectiveCodexCredentialId,\n accounts: fresh,\n now: new Date(),\n });\n if (decision.kind === \"active\") {\n rotated = true;\n // Finding 1: a live candidate normally re-dispatches NOW (0). Two second-order\n // faults would turn that 0 into a hot loop, so bound it. Count the consecutive\n // reactive failovers since the last successful turn (this one is not yet\n // published) and combine with the cooldown-persistence result.\n const priorConsecutiveRotations = await countConsecutiveReactiveRotations(\n db,\n input.workspaceId,\n input.sessionId,\n ).catch(() => 0);\n const resume = computeReactiveRotationResume({\n cooldownPersisted,\n priorConsecutiveRotations,\n connectedAccountCount: accounts.length,\n });\n rotationResumeMs = resume.continueDelayMs; // 0 (happy path), a slow-retry floor, or the circuit-breaker idle\n rotationResumeIdleUntilReset = resume.idleUntilReset; // true only on the circuit-breaker fall (MANDATORY hold)\n } else if (decision.kind === \"allCapped\") {\n rotated = true;\n allCappedResetAt = decision.earliestResetAt;\n capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(fresh, new Date());\n }\n // kind:\"none\" → fall through to today's single-account idle.\n }\n }\n }\n\n const failurePayload = allCappedResetAt\n ? codexUsageLimitFailurePayload(\n {\n resetsInSeconds: Math.ceil(\n Math.max(0, allCappedResetAt.getTime() - Date.now()) / 1000,\n ),\n },\n error instanceof Error ? error.message : String(error),\n { allAccounts: true },\n )\n : codexUsageLimitFailurePayload(\n usageLimit,\n error instanceof Error ? error.message : String(error),\n );\n // A live alternate is still handled by the existing immediate,\n // same-policy continuation path. When no alternate exists (all capped,\n // or a single non-rotating account), persist the native capacity wait\n // instead of an in-memory delay/user-message recovery.\n if (rotationResumeMs === null) {\n const providerResetAt =\n capacityAuthoritativeResetAt ??\n (usageLimit.resetsInSeconds !== null &&\n Number.isFinite(usageLimit.resetsInSeconds) &&\n usageLimit.resetsInSeconds > 0\n ? new Date(Date.now() + Math.ceil(usageLimit.resetsInSeconds) * 1000)\n : null);\n const armed = await armCodexCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n goalId: goalActive && goal ? goal.id : null,\n goalVersion: goalActive && goal ? goal.version : null,\n earliestResetAt: providerResetAt,\n resetKind: providerResetAt ? \"authoritative\" : \"bounded_refresh\",\n failurePayload,\n ...(codexLeaseHolderId && codexLeaseGeneration !== null\n ? {\n leaseFence: {\n holderId: codexLeaseHolderId,\n generation: codexLeaseGeneration,\n },\n expectedRedispatches: redispatchesAtDispatch,\n }\n : {}),\n });\n if (armed.action === \"waiting\") {\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n armed.events,\n );\n turnMetricOutcome = \"recovering\";\n activityStatus = \"waiting_capacity\";\n activityError = error;\n return claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n waiterId: armed.waiter.id,\n generation: armed.waiter.generation,\n nextCheckAt: armed.waiter.nextCheckAt.toISOString(),\n wakeRevision: armed.waiter.wakeRevision,\n },\n });\n }\n }\n if (\n !(await settle!({\n events: [\n // `rotated:true` ONLY on the reactive rotation path tells evaluateGoalContinuation to\n // freeze autoContinuations (a rotation walk must not burn the goal's continuation budget).\n {\n type: \"turn.failed\",\n payload: {\n ...failurePayload,\n recovery: goalActive ? \"goal_continuation\" : \"user_message\",\n ...(rotated ? { rotated: true } : {}),\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = error;\n if (goalActive) {\n // Rotation: a candidate is available → continue NOW (0). All-capped → idle until the\n // earliest reset across all accounts (capped at 1h). Else the unchanged single-account idle.\n if (rotationResumeMs !== null) {\n // A candidate IS available. Normally the just-failed account is now cooling so\n // the ranker cannot re-pick it → 0 (re-dispatch NOW, the legitimate skip-the-hold\n // case). Finding 1 bounds the two exceptions: a persistence fault yields a positive\n // slow-retry floor, and once consecutive failovers exceed the account count + margin\n // the circuit breaker returns a fixed MANDATORY idle (idleUntilReset) — never a 0-delay\n // hot loop against a capped backend + DB.\n return claimedResult({\n status: \"idle\",\n continueDelayMs: rotationResumeMs,\n ...(rotationResumeIdleUntilReset ? { idleUntilReset: true } : {}),\n });\n }\n // All-capped: clamp to [MIN_IDLE_MS, max] — a POSITIVE, BOUNDED hold (never 0,\n // so session.ts can never tight-loop). The post-idle continuation re-dispatch\n // hits the proactive seam, which refreshes usage and self-heals.\n const resumeMs = allCappedResetAt\n ? computeIdleDelayMs(allCappedResetAt, new Date(), CODEX_USAGE_LIMIT_MAX_RESUME_MS)\n : usageLimit.resetsInSeconds !== null &&\n Number.isFinite(usageLimit.resetsInSeconds) &&\n usageLimit.resetsInSeconds > 0\n ? Math.min(\n Math.ceil(usageLimit.resetsInSeconds) * 1000,\n CODEX_USAGE_LIMIT_MAX_RESUME_MS,\n )\n : CODEX_USAGE_LIMIT_MAX_RESUME_MS;\n return claimedResult({\n status: \"idle\",\n continueDelayMs: resumeMs,\n ...(allCappedResetAt ? { idleUntilReset: true } : {}),\n });\n }\n return claimedResult({ status: \"idle\" });\n }\n // Budget/limit exhaustion between model calls is account state, not an\n // agent failure: idle the session for goal-bearing and goal-less runs\n // alike (a failed session would reject the user's next message after a\n // top-up). An active goal pauses visibly with reason \"limits\" at the\n // next continuation evaluation, without consuming continuation budget.\n if (error instanceof BudgetExhaustedError && publish && turnId && turnStartedPublished) {\n await flushRuntimeBatcher();\n await reconcileConversationTruth();\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: {\n output: \"\",\n segmentLimit: \"budget_exhausted\",\n detail: error.message,\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"completed\";\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"agent_run.completed\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"session_turn\",\n sourceResourceId: turnId,\n sessionId: input.sessionId,\n turnId,\n turnAttemptId: input.attemptId,\n idempotencyKey: `usage:agent_run.completed:${turnId}`,\n });\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n // The Codex backend can reject an opaque reasoning artifact that it\n // minted on the immediately preceding successful request, even when the\n // credential-row UUID is unchanged. HTTP 400 + the exact provider\n // semantic proves this request never entered inference. Atomically mark\n // the active opaque artifacts rejected and recover the SAME logical turn\n // from durable history; messages, tool calls/results, readable reasoning,\n // and the original audit rows remain intact. Opaque remote compaction has\n // no portable plaintext representation. If no artifact can be invalidated,\n // fall through to the terminal path rather than resend an equivalent\n // request forever.\n const encryptedArtifactRejection =\n isCodexTurn && effectiveCodexCredentialId\n ? classifyCodexEncryptedArtifactRejection(error)\n : null;\n if (\n encryptedArtifactRejection &&\n effectiveCodexCredentialId &&\n publish &&\n turnId &&\n turnStartedPublished\n ) {\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n const activeHistory = await getActiveSessionHistoryItems(\n db,\n input.workspaceId,\n input.sessionId,\n );\n const rejectedHistoryItemIds = selectRejectedProviderArtifactHistoryIds(\n activeHistory,\n providerArtifactCandidates,\n lastCodexRequestOpaqueArtifacts,\n );\n const rejectedRunStateId =\n providerArtifactCandidates.runStateId && lastCodexRequestOpaqueArtifacts.length > 0\n ? providerArtifactCandidates.runStateId\n : undefined;\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: encryptedArtifactRejection.kind,\n detail: {\n code: encryptedArtifactRejection.kind,\n retryable: true,\n },\n providerArtifactInvalidation: {\n historyItemIds: rejectedHistoryItemIds,\n ...(rejectedRunStateId ? { runStateId: rejectedRunStateId } : {}),\n reason: encryptedArtifactRejection.kind,\n },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n if (recovery.action === \"recovering\") {\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n recovery.events,\n );\n turnMetricOutcome = \"recovering\";\n activityStatus = \"recovering\";\n activityError = error;\n return claimedResult({ status: \"recovering\" });\n }\n }\n // A retryable provider/MCP failure is transient external backpressure,\n // not a session or goal failure. The in-client retry budget is already\n // exhausted by the time the error reaches here. Checkpoint conversation\n // truth, recover this SAME accepted turn, then let the workflow re-claim\n // it after a pacing delay. This is independent of goal state and never\n // relies on a synthetic continuation prompt.\n const failure = redact(agentRunFailurePayload(error, { isCodexTurn })) as ReturnType<\n typeof agentRunFailurePayload\n >;\n if (isSessionEventPersistenceError(error)) {\n // Never pass the original Drizzle/postgres-js error to telemetry: its\n // nested cause may contain raw SQL and bound parameters. The typed DB\n // boundary retains only SQLSTATE, stage, correlation, and safe catalog\n // identifiers. Provider inference has already happened and is NOT\n // retried by this terminal classification.\n observability.error(\"session event persistence failed\", {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n code: error.details.code,\n sqlState: error.details.sqlState ?? \"unknown\",\n stage: error.details.stage,\n eventTypes: error.details.eventTypes.join(\",\"),\n correlationId: error.details.correlationId,\n attempts: error.details.attempts,\n retryOutcome: error.details.retryOutcome,\n dbSeverity: error.details.database.severity,\n dbSchema: error.details.database.schema,\n dbTable: error.details.database.table,\n dbColumn: error.details.database.column,\n dbDataType: error.details.database.dataType,\n dbConstraint: error.details.database.constraint,\n dbRoutine: error.details.database.routine,\n });\n }\n if (failure.retryable && publish && turnId && turnStartedPublished) {\n try {\n const nextProviderRecoveryCount = providerRecoveryCount + 1;\n const recoveryResult = providerRecoveryResult({\n failureCode: failure.code,\n attemptNumber: nextProviderRecoveryCount,\n retryAfterMs: providerRetryAfterMs(error),\n });\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: failure.code ?? \"provider_unavailable\",\n providerRecoveryCount: nextProviderRecoveryCount,\n detail: {\n ...failure,\n continueDelayMs: recoveryResult.continueDelayMs,\n providerRecoveryCount: nextProviderRecoveryCount,\n },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n recovery.events,\n );\n turnMetricOutcome = \"recovering\";\n activityStatus = \"recovering\";\n activityError = error;\n return claimedResult(recoveryResult);\n } catch (recoveryError) {\n const escaped = escapedMcpTimeoutRecoveryFailure({\n failureCode: failure.code,\n modelRequestStarted,\n detail: {\n turnId,\n triggerEventId: triggerEventId!,\n executionGeneration,\n },\n });\n if (escaped) {\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n activityError = error;\n throw escaped;\n }\n throw recoveryError;\n }\n }\n activityStatus = \"failed\";\n activityError = error;\n if (!publish || !turnId || !turnStartedPublished) {\n throw error;\n }\n // A partial/malformed stream may have emitted assistant/tool items (and\n // external side effects) before its terminal error. Persist every item the\n // SDK state observed before marking the turn failed so a later user revive\n // never replays work from an incomplete history. This does not retry or\n // rotate the ambiguous request.\n await flushRuntimeBatcher();\n await reconcileConversationTruth();\n if (\n !(await settle!({\n events: [\n { type: \"turn.failed\", payload: failure },\n { type: \"session.status.changed\", payload: { status: \"failed\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"failed\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n // The common failure path ends here: runAgentTurn marks the session\n // failed and returns \"failed\", and the session workflow then exits\n // WITHOUT calling failSession/markSessionIdle. Wake a spawned worker's\n // parent here too, so a manager learns of a worker that died inside its\n // turn (not just one failed by the workflow's failSession path). Turn\n // settlement already owns the durable outbox payload; this call only\n // delivers that exact turn-scoped row.\n await deliverFailedChildTurnToParent(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n turnId,\n );\n return claimedResult({ status: \"failed\" });\n } finally {\n // This is the logical ownership boundary. Abort before any fallible\n // housekeeping so a still-pending provider establish releases its private\n // holder/timer even when Temporal itself never delivered cancellation.\n if (resolvedSandbox === null && !sandboxResumeController.signal.aborted) {\n sandboxResumeController.abort(\n cancellationSignal?.reason ?? new Error(\"TURN_ATTEMPT_FINALIZED\"),\n );\n }\n const finalizationStarted = performance.now();\n let finalizationError: unknown;\n let physicalToolQuiescenceConfirmed = !acknowledgeQuiescence;\n let quiescenceReceiptOrProofDurable = !acknowledgeQuiescence;\n const finalizerSignal = turnFinalizerCancellationSignal(cancellationSignal, activityStatus);\n try {\n const toolCancellationFence = toolCancellationFenceRef.current;\n // Every renewal controller is an attempt-owned sandbox writer. Capture\n // and close all of them before the tool/run-writer drain and before the\n // quiescence receipt; none may start another admitted write afterward.\n gitCredentialRenewalClosed = true;\n const gitRenewalsToStop = gitCredentialRenewals;\n gitCredentialRenewals = [];\n toolspaceTokenRenewalClosed = true;\n const toolspaceRenewalToStop =\n toolspaceTokenRenewal as ToolspaceTokenRenewalController | null;\n toolspaceTokenRenewal = null;\n runCredentialRenewalClosed = true;\n const runRenewalToStop = runCredentialRenewal as RunCredentialRenewalController | null;\n runCredentialRenewal = null;\n\n // Attempt-qualified credential deletion is also a real workspace write.\n // Perform it under the same admission fence before publishing physical\n // quiescence; a failure deliberately keeps the receipt closed.\n const credentialSessionToClear = runCredentialSession;\n runCredentialSession = null;\n if (credentialSessionToClear) {\n await runWorkspaceMutationForSandbox(\n requireResolvedSandboxForMutation(\n \"Run credential cleanup has no exact sandbox lease target\",\n ),\n \"runCredentialAttemptClear\",\n async () =>\n await clearRunCredentialsForAttempt(credentialSessionToClear, {\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n executionGeneration,\n }),\n );\n }\n await drainAttemptOwnedSandboxWriters({\n // Normal turn completion owns the same process boundary as\n // Pause/Steer: yielded provider shells must be terminated, polled,\n // and durably settled before workspace capture. Only receipt\n // publication remains conditional on acknowledgeQuiescence.\n toolCancellationFence,\n cancellationReason: cancellationSignal?.reason ?? new Error(\"TURN_ATTEMPT_FINALIZED\"),\n gitCredentialRenewals: gitRenewalsToStop,\n toolspaceTokenRenewal: toolspaceRenewalToStop,\n runCredentialRenewal: runRenewalToStop,\n });\n if (acknowledgeQuiescence) {\n // A cancellation before sandbox-backed capabilities exist still has\n // no tool controller to drain. Sandbox agent construction fails closed\n // when a backend exists but no controller was installed. Renewal\n // writers, when present, were drained above in either case.\n physicalToolQuiescenceConfirmed = true;\n }\n if (acknowledgeQuiescence && physicalToolQuiescenceConfirmed) {\n // This receipt is part of the hard cancellation boundary, not\n // housekeeping. Persist it immediately after the sandbox/tool fence\n // and before lease, cache, recording, or provider cleanup. Its\n // transaction also enqueues the exact workflow wake that will admit\n // the replacement; Temporal activity terminalization does neither.\n const proof: SessionAttemptQuiescenceProof = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n activityId: dispatchId,\n };\n const recoveryMode = await persistOrSignalSessionAttemptQuiescence({\n proof,\n persistReceipt: async () =>\n await markSessionAttemptQuiesced(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: dispatchId,\n allowUninterrupted: true,\n }),\n publishEvents: async (events) => {\n await waitForTurnFinalizerStep(\n publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, events),\n finalizerSignal,\n );\n },\n signalProof: signalSessionAttemptQuiesced,\n heartbeat: (attempt, retryMs) => {\n activityContext?.heartbeat({\n phase: \"quiescence-proof-delivery\",\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n deliveryAttempt: attempt,\n retryMs,\n at: new Date().toISOString(),\n });\n },\n onReceiptFailure: (error) => {\n console.error(\n \"agent turn quiescence receipt exhausted; signalling proof\",\n safeErrorDiagnostic(error, (value) => String(redact(value))),\n );\n },\n onPublishFailure: (error) => {\n console.error(\n \"agent turn quiescence event fanout failed\",\n safeErrorDiagnostic(error, (value) => String(redact(value))),\n );\n },\n onSignalFailure: (error, attempt, retryMs) => {\n console.error(\"agent turn quiescence proof signal failed; retrying\", {\n error: safeErrorDiagnostic(error, (value) => String(redact(value))),\n attempt,\n retryMs,\n });\n },\n });\n quiescenceReceiptOrProofDurable = true;\n if (recoveryMode === \"signal\") {\n observability.info(\"agent turn quiescence proof handed to workflow recovery\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.attempt_id\": input.attemptId,\n \"opengeni.workflow_run_id\": input.workflowRunId,\n \"opengeni.activity_id\": dispatchId,\n });\n }\n }\n // Drain the buffered Connected Machine op events (infra failures + healed\n // recoveries) to durable session events — awaited, best-effort, never blocking\n // the turn. Sync observer → buffer → single awaited append here (no unawaited\n // DB write inside the activity). Scoped to this turn; skipped if no turnId\n // (the op ran under a turn, so on the normal path turnId is set).\n const machineOpEvents = machineOpObserver.drainEvents();\n if (machineOpEvents.length > 0 && turnId && executionGeneration > 0) {\n await waitForTurnFinalizerStep(\n appendAndPublishTurnEventsFenced(\n db,\n bus,\n input.workspaceId,\n input.sessionId,\n turnId,\n executionGeneration,\n input.attemptId,\n machineOpEvents.map((event) => ({\n ...event,\n turnId: turnId ?? null,\n })),\n ).catch(() => undefined),\n finalizerSignal,\n );\n }\n // Multi-account P4: flush the serving account's free per-turn caches ONCE,\n // best-effort (same discipline as today's usage write). Both writers skip\n // version/updatedAt, so neither can race the token-refresh CAS.\n if (effectiveCodexCredentialId) {\n // Part A: the latest scraped usage-header snapshot → the P2 usage cache. A\n // full both-windows snapshot (parseCodexUsageHeaders gates on both), so this\n // is byte-identical to the /wham/usage write — no partial-window clobber.\n if (latestCodexUsage) {\n const usageMutation = await waitForTurnFinalizerStep(\n recordCodexAccountUsageWithWakeTargets(\n db,\n input.workspaceId,\n effectiveCodexCredentialId,\n latestCodexUsage,\n ).catch(() => null),\n finalizerSignal,\n );\n if (usageMutation) {\n await waitForTurnFinalizerStep(\n signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n usageMutation.wakeTargets,\n ),\n finalizerSignal,\n );\n }\n }\n }\n if (codexLeaseHeartbeatTimer) {\n clearInterval(codexLeaseHeartbeatTimer);\n codexLeaseHeartbeatTimer = undefined;\n }\n if (codexLeaseHeld && turnId && codexLeaseHolderId && codexLeaseGeneration !== null) {\n await waitForTurnFinalizerStep(\n releaseCodexCredentialLease(\n db,\n input.accountId,\n input.workspaceId,\n turnId,\n codexLeaseHolderId,\n codexLeaseGeneration,\n ).catch(() => undefined),\n finalizerSignal,\n );\n codexLeaseHeld = false;\n }\n // Workbench v2 turn-end workspace capture — runs FIRST in\n // the turn-end finally, while the box is MAXIMALLY ALIVE. The agent's last\n // tool ran before this finally, so /workspace is already final; capture is\n // FS-equivalent to the already-settled recording preparation and the warm\n // snapshot (neither mutates workspace files). Running it here — BEFORE\n // preparedTools.close() (which tears down tools / computer-use / the display\n // stack and is what starts the Modal box exiting a few seconds later) —\n // gives capture the full live-box margin instead of racing the teardown\n // tail, which was dropping 100% of captures on real Modal desktop boxes\n // (\"request cancelled due to container exiting\", 0 rows). External module:\n // self-capped at 120s, best-effort (never throws past its boundary),\n // epoch-fenced, and it NEVER closes the box. The emitted\n // workspace.revision.captured event is ANNOUNCE-ONLY (metadata, never\n // content).\n if (process.env.OPENGENI_TEST_SCENARIO === \"sandbox\") {\n console.log(\n `[sandbox-e2e] capture preflight ownership=${settings.sandboxOwnershipEnabled} enabled=${settings.workspaceCaptureEnabled} resolved=${Boolean(resolvedSandbox)} session=${Boolean(setupBoxSession)} group=${Boolean(sandboxGroupId)} storage=${Boolean(objectStorage)}`,\n );\n }\n const runTurnEndPersistence = shouldRunTurnEndWorkspacePersistence({\n activityStatus,\n cancellationRequested: finalizerSignal?.aborted === true,\n });\n if (\n runTurnEndPersistence &&\n turnId &&\n resolvedSandbox &&\n setupBoxSession &&\n sandboxGroupId\n ) {\n // Block new periodic snapshots, then drain any one already in flight.\n // Keep the lease heartbeat itself running: capture may legitimately\n // exceed the 90s holder TTL, and the reaper must remain unable to drain\n // the exact box while this holder still reads it.\n turnEndCaptureInProgress = true;\n if (snapshotInFlight) {\n await waitForWarmSnapshot(\n snapshotInFlight,\n settings.sandboxSnapshotTimeoutMs,\n finalizerSignal,\n );\n }\n const captureEstablished = resolvedSandbox.established;\n await captureWorkspaceRevision({\n db,\n objectStorage,\n settings,\n publish: async (events) => {\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, events);\n },\n session: setupBoxSession as ChannelASession,\n openReadSession: async () =>\n await openFreshWorkspaceCaptureSession({\n backendId: captureEstablished.backendId,\n client: captureEstablished.client,\n session: setupBoxSession as ChannelASession,\n expectedInstanceId: captureEstablished.instanceId,\n }),\n leaseEpoch: resolvedSandbox.leaseEpoch,\n sandboxGroupId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n observability,\n ...(finalizerSignal ? { signal: finalizerSignal } : {}),\n });\n }\n if (preparedTools) {\n await waitForTurnFinalizerStep(\n preparedTools.close().catch(() => undefined),\n finalizerSignal,\n );\n }\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\n }\n if (turnSandboxProvisioner?.hasStarted()) {\n await waitForTurnFinalizerStep(\n turnSandboxProvisioner.waitForSettled(30_000),\n finalizerSignal,\n );\n }\n // P1.2: stop the lease-TTL refresh, release the turn holder (idempotent\n // delete-my-row; refcount-- and warm->draining if it hit 0 with no turns),\n // and DROP the in-memory handle. Release NEVER stops the box — the reaper\n // (P1.3) issues the provider stop() past the drain grace at refcount 0; the\n // box rides the provider idle-timeout in the meantime. Best-effort: a\n // release failure must never mask the turn's real outcome.\n if (leaseHeartbeatTimer) {\n stopLeaseHeartbeat();\n }\n if (rotationInFlight) {\n await waitForTurnFinalizerStep(rotationInFlight, finalizerSignal).catch(() => undefined);\n }\n // A recording normally closes inside the attempt-fenced turn settlement.\n // Reaching finally with one still active means settlement threw, never ran,\n // or lost ownership. Stop ffmpeg and mark only this exact attempt-owned row\n // failed; publish no event and leave the artifact recoverable on the box.\n await waitForTurnFinalizerStep(\n abandonActiveRecording(\n \"activity ended without recording settlement\",\n didComputerUse ? \"failed\" : \"discard\",\n ),\n finalizerSignal,\n );\n if (resolvedSandbox) {\n // TURN-END mid-session snapshot (sandbox-file-persistence): fold the\n // turn's finished /workspace onto the lease before releasing the holder,\n // so the work this turn just produced survives any unclean box death in\n // the idle window ahead. Throttled by the same interval as the heartbeat\n // tick (a short turn right after a snapshot skips — bounded-loss contract\n // is the interval, not per-turn). Best-effort and time-capped by the\n // helper's own failure discipline; never delays release on failure.\n const settledTurnId = turnId;\n if (runTurnEndPersistence && setupBoxSession && sandboxGroupId && settledTurnId) {\n // Single-flight vs the heartbeat capture: the timer is already cleared\n // above, but a capture it launched may still be in flight — and that\n // capture predates the turn's final writes. Wait for it, but only up\n // to the snapshot timeout: release must never depend on an unbounded\n // provider capture.\n if (snapshotInFlight) {\n await waitForWarmSnapshot(\n snapshotInFlight,\n settings.sandboxSnapshotTimeoutMs,\n finalizerSignal,\n );\n }\n const persisted = await maybePersistWarmWorkspaceSnapshot(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: settledTurnId,\n attemptId: input.attemptId,\n sandboxGroupId,\n },\n setupBoxSession,\n resolvedSandbox.leaseEpoch,\n finalizerSignal,\n );\n if (persisted && publish) {\n await publish([\n {\n type: \"sandbox.box.snapshot\",\n payload: { trigger: \"turn-end\" },\n },\n ]).catch(() => undefined);\n }\n // NB workspace capture no longer runs here — it moved to\n // the TOP of this finally (before preparedTools.close) so it completes\n // while the box is still solidly alive, instead of racing the turn-end\n // teardown that was killing 100% of captures on real Modal desktop boxes.\n }\n const sandboxToRelease = resolvedSandbox;\n resolvedSandbox = null; // drop ownership now; the exact-holder release may finish later\n await waitForTurnFinalizerStep(\n sandboxToRelease.release().catch((releaseError) => {\n console.error(\n \"sandbox lease release failed (turn outcome unaffected)\",\n safeErrorDiagnostic(releaseError, (value) => String(redact(value))),\n );\n }),\n finalizerSignal,\n );\n }\n } catch (error) {\n finalizationError ??= error;\n console.error(\n \"agent turn finalization failed (turn outcome unaffected)\",\n safeErrorDiagnostic(error, (value) => String(redact(value))),\n );\n } finally {\n // If fallible finalization exited before the ordinary exact-holder\n // release, the resume signal is the unconditional last line of defense.\n // Normal finalization already removed its listener in release().\n if (!sandboxResumeController.signal.aborted) {\n sandboxResumeController.abort(\n cancellationSignal?.reason ?? new Error(\"TURN_ATTEMPT_FINALIZED\"),\n );\n }\n cancellationSignal?.removeEventListener(\"abort\", noteCancellationRequested);\n const completedAt = performance.now();\n const durationSeconds = (completedAt - activityStarted) / 1000;\n const finalizationDurationSeconds = (completedAt - finalizationStarted) / 1000;\n observability.observeHistogram({\n name: \"opengeni_turn_finalization_duration_seconds\",\n help: \"Agent turn finalization duration, including workspace housekeeping and lease release.\",\n labels: {\n cancellation_requested: String(cancellationRequestedAt !== null),\n },\n value: finalizationDurationSeconds,\n });\n if (cancellationRequestedAt !== null) {\n const physicalCancellationDurationSeconds =\n (completedAt - cancellationRequestedAt) / 1000;\n observability.observeHistogram({\n name: \"opengeni_turn_physical_cancellation_duration_seconds\",\n help: \"Time from Temporal cancellation delivery until the activity physically stops.\",\n value: physicalCancellationDurationSeconds,\n });\n observability.info(\"agent turn physical cancellation completed\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": turnId ?? \"\",\n \"opengeni.attempt_id\": input.attemptId,\n \"opengeni.physical_cancellation_duration_ms\": Math.round(\n physicalCancellationDurationSeconds * 1000,\n ),\n });\n }\n observability.recordWorkerActivity({\n activity: \"runAgentTurn\",\n status: finalizationError ? \"cleanup_failed\" : activityStatus,\n durationSeconds,\n });\n if (turnId && activityStatus !== \"unknown\") {\n turnLifecycleMetricsFor(observability).finish(turnId, turnMetricOutcome, durationSeconds);\n }\n activitySpan.end({\n attributes: {\n \"opengeni.turn_id\": turnId ?? \"\",\n \"opengeni.status\": activityStatus,\n \"opengeni.variable_set_id\": variableSetId,\n \"opengeni.rig_id\": rigId,\n \"opengeni.rig_version_id\": rigVersionId,\n \"opengeni.codex_credential_id\": effectiveCodexCredentialId ?? \"\",\n \"opengeni.duration_ms\": Math.round(durationSeconds * 1000),\n \"opengeni.finalization_duration_ms\": Math.round(finalizationDurationSeconds * 1000),\n },\n error:\n finalizationError || activityError\n ? safeErrorForTelemetry(finalizationError ?? activityError, (value) =>\n String(redact(value)),\n )\n : undefined,\n });\n assertPhysicalToolQuiescenceForCancellation({\n acknowledgeQuiescence,\n physicalToolQuiescenceConfirmed,\n failure: finalizationError,\n });\n assertSessionAttemptQuiescenceRecoveryDurable({\n acknowledgeQuiescence,\n physicalToolQuiescenceConfirmed,\n receiptOrProofDurable: quiescenceReceiptOrProofDurable,\n failure: finalizationError,\n });\n }\n }\n };\n}\n\nasync function assertGitHubResourcesRemainAuthorized(\n db: Parameters<typeof areGitHubRepositoriesAllowedForWorkspace>[0],\n workspaceId: string,\n resources: import(\"@opengeni/contracts\").ResourceRef[],\n): Promise<void> {\n // Must check exactly what sandboxEnvironmentForRun would mint a token for,\n // so the selection is derived from the same extraction as the mint path.\n for (const selection of gitHubTokenMintSelections(resources)) {\n await assertGitHubTokenMintSelectionAuthorized(\n db,\n workspaceId,\n selection.installationId,\n selection.repositoryIds,\n );\n }\n}\n\nasync function assertGitHubTokenMintSelectionAuthorized(\n db: Parameters<typeof areGitHubRepositoriesAllowedForWorkspace>[0],\n workspaceId: string,\n installationId: number,\n repositoryIds: number[],\n): Promise<void> {\n if (\n !(await areGitHubRepositoriesAllowedForWorkspace(\n db,\n workspaceId,\n installationId,\n repositoryIds,\n ))\n ) {\n throw new Error(\n \"This workspace no longer authorizes one or more GitHub repositories attached to the session\",\n );\n }\n}\n\n/**\n * True when the error is transient upstream backpressure — a model-provider 5xx,\n * a \"server had a bad minute\" body, or a dropped/again-able network connection —\n * rather than a request the session got wrong. These are safe to recover as a new\n * fenced attempt of the SAME turn after PROVIDER_BACKPRESSURE_DELAY_MS. Durable\n * tool results are preserved and ambiguous in-flight effects are closed before\n * the new attempt, independent of whether the session has an active goal.\n *\n * This is the classification gap that hard-failed a fleet of prod sessions during a\n * provider degradation window: their errors (\"Our servers are currently overloaded\",\n * the generic 500 \"An error occurred while processing your request\", \"Connection\n * error\") carried no retryable marker and fell through to a terminal session.failed.\n *\n * HTTP status is authoritative when present — EVERY 5xx is a server-side failure that\n * is safe to retry, while 4xx (validation, auth, 404) is a request fault that must\n * still hard-fail. The code/message matches are the fallback for network faults and\n * SDK-rethrown bare Errors that carry no status. A ChatGPT/Codex usage cap (a 429\n * that will NOT clear on retry) is classified and returned BEFORE this in\n * agentRunFailurePayload, so it never reaches here.\n */\nconst STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGE =\n \"unable to connect. is the computer able to access the url?\";\n\nfunction isExactStatuslessUpstreamConnectivityMessage(message: string): boolean {\n return message.trim().toLowerCase() === STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGE;\n}\n\nexport function isTransientProviderError(error: unknown): boolean {\n const status =\n typeof error === \"object\" && error !== null\n ? Number(\n (error as { status?: unknown; statusCode?: unknown }).status ??\n (error as { statusCode?: unknown }).statusCode,\n )\n : undefined;\n // A real HTTP status is AUTHORITATIVE: a 5xx is transient, and ANY other status\n // (4xx validation/auth/404, plus the 429 the earlier branches already handled) is\n // a request fault that must NOT auto-retry — even if its body happens to read like\n // \"connection error\" or \"overloaded\". The code/message heuristics below apply ONLY\n // when no status survived: a network fault or an SDK-rethrown bare Error.\n if (status !== undefined && Number.isFinite(status)) {\n return status >= 500 && status < 600;\n }\n const code =\n typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n if (code && /^(?:ECONNRESET|ETIMEDOUT|EAI_AGAIN|ECONNREFUSED|EPIPE)$/i.test(code)) {\n return true;\n }\n const message = error instanceof Error ? error.message : String(error);\n if (isExactStatuslessUpstreamConnectivityMessage(message)) {\n return true;\n }\n return /overloaded|an error occurred while processing your request|connection error|service unavailable|bad gateway|gateway timeout/i.test(\n message,\n );\n}\n\nexport function agentRunFailurePayload(\n error: unknown,\n options: { isCodexTurn?: boolean } = {},\n): {\n error: string;\n code?: string;\n retryable?: boolean;\n detail?: string;\n timeoutClass?: string;\n responseObserved?: boolean;\n requestId?: string;\n correlationId?: string;\n stage?: string;\n sqlState?: string | null;\n attempts?: number;\n retryOutcome?: string;\n database?: Record<string, string>;\n} {\n const message = error instanceof Error ? error.message : String(error);\n const status =\n typeof error === \"object\" && error !== null\n ? Number(\n (error as { status?: unknown; statusCode?: unknown }).status ??\n (error as { statusCode?: unknown }).statusCode,\n )\n : undefined;\n const code =\n typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n // An accepted Codex stream with no terminal response is malformed/partial,\n // not provider backpressure. Replaying the same accepted turn could repeat\n // model or tool effects, so this marked transport failure must outrank the\n // generic 5xx retry classifier (CodexStreamingTerminalError uses status 502).\n if (isCodexTransportError(error) && code === \"invalid_sse_terminal\") {\n return {\n error: \"The Codex response stream ended without a terminal response\",\n code: \"invalid_sse_terminal\",\n retryable: false,\n };\n }\n if (isSessionEventPersistenceError(error)) {\n const { details } = error;\n const eventLabel = details.eventTypes.join(\", \") || \"session events\";\n const failureLabel =\n details.code === \"db_deadlock\"\n ? \"Database deadlock\"\n : details.code === \"db_serialization_failure\"\n ? \"Database serialization failure\"\n : \"Database failure\";\n return {\n error: `${failureLabel} while persisting ${eventLabel}. The completed provider call and external effects were not retried.`,\n code: details.code,\n detail:\n details.retryOutcome === \"exhausted\"\n ? `The idempotent persistence transaction failed after ${details.attempts} attempts.`\n : \"The database rejected the idempotent persistence transaction.\",\n correlationId: details.correlationId,\n stage: details.stage,\n sqlState: details.sqlState,\n attempts: details.attempts,\n retryOutcome: details.retryOutcome,\n ...(Object.keys(details.database).length > 0 ? { database: details.database } : {}),\n };\n }\n // A ChatGPT/Codex usage cap is a HARD limit, not transient backpressure: it\n // must NOT be reported as a generic, retryable rate-limit (which would loop a\n // goal against a capped backend). Surface a precise, actionable message with\n // the humanized reset window and code, non-retryable. Checked BEFORE the\n // generic 429 branch below (a usage cap is also a 429).\n // This terminal payload classifier may receive a plain SDK-shaped error in\n // tests or after wrapper metadata was stripped. An explicit\n // `usage_limit_reached` shape must still outrank generic 429 retryability.\n // Credential quarantine/failover remains separately provenance-gated by\n // `isCodexTransportError`; this branch only chooses the truthful user payload.\n const usageLimit = classifyCodexUsageLimitError(error);\n if (usageLimit) {\n return codexUsageLimitFailurePayload(usageLimit, message);\n }\n const codexTimeout = classifyCodexResponseTimeoutError(error, {\n allowLegacyRequestTimeout: options.isCodexTurn === true,\n });\n if (codexTimeout) {\n return {\n error: codexTimeout.responseObserved\n ? \"The Codex response timed out after streaming began. Observed output was checkpointed; automatic replay is disabled because the upstream operation may still be active.\"\n : \"The Codex response timed out before any response was observed. Upstream acceptance is unknown, so automatic replay is disabled.\",\n code: \"codex_response_timeout\",\n retryable: false,\n timeoutClass: codexTimeout.timeoutClass,\n responseObserved: codexTimeout.responseObserved,\n ...(codexTimeout.requestId ? { requestId: codexTimeout.requestId } : {}),\n ...(codexTimeout.message ? { detail: codexTimeout.message } : {}),\n };\n }\n const mcpTimeout = classifyMcpTransportTimeoutError(error);\n if (mcpTimeout) {\n return {\n error:\n \"An MCP server request timed out. Any completed tool output was checkpointed; the session can continue safely.\",\n code: \"mcp_transport_timeout\",\n retryable: true,\n ...(mcpTimeout.detail || mcpTimeout.message\n ? { detail: mcpTimeout.detail ?? mcpTimeout.message }\n : {}),\n };\n }\n if (isMcpTransportConnectivityError(error)) {\n return {\n error:\n \"A required MCP server was temporarily unreachable. The same turn will retry after a short delay.\",\n code: \"mcp_transport_unavailable\",\n retryable: true,\n };\n }\n if (\n status === 429 ||\n code === \"rate_limit_exceeded\" ||\n /(?:too many requests|rate.?limit|\\b429\\b)/i.test(message)\n ) {\n return {\n error: \"Model provider rate limit hit. Try again in a minute or lower the reasoning effort.\",\n code: \"provider_rate_limited\",\n retryable: true,\n ...(message && message !== \"Too Many Requests\" ? { detail: message } : {}),\n };\n }\n // Transient upstream backpressure (5xx / overloaded / dropped connection): keep\n // the provider's own message (it is already user-meaningful) but mark it\n // retryable so a goal-bearing session idles and auto-continues instead of going\n // terminal on a provider's bad minute. See isTransientProviderError.\n if (isTransientProviderError(error)) {\n if (isExactStatuslessUpstreamConnectivityMessage(message)) {\n return {\n error:\n \"OpenGeni could not reach an upstream service. The same turn will retry after a short delay.\",\n code: \"upstream_connectivity_unavailable\",\n retryable: true,\n };\n }\n return { error: message, code: \"provider_unavailable\", retryable: true };\n }\n return { error: message };\n}\n\nexport type CodexCredentialFailure = {\n kind: \"auth\" | \"forbidden\" | \"rate_limit\" | \"quota\";\n cooldownSeconds: number | null;\n};\n\nexport const CODEX_ALLOWANCE_FALLBACK_MS = 5 * 60 * 60_000;\n\n/**\n * Resolve a deterministic quarantine end. Generic request throttling honors\n * provider retry-after (or one minute); allowance/quota refusal waits for the\n * LAST of provider reset and every still-binding cached window (five-hour and\n * weekly both bind), falling back to one complete five-hour window when no reset\n * metadata exists.\n */\nexport function codexCredentialCooldownUntil(\n failure: CodexCredentialFailure,\n account: Pick<\n CodexAccountStatus,\n \"primaryUsedPercent\" | \"primaryResetAt\" | \"secondaryUsedPercent\" | \"secondaryResetAt\"\n > | null,\n now: Date,\n): Date | null {\n if (failure.kind === \"auth\" || failure.kind === \"forbidden\") {\n return null;\n }\n const providerReset =\n failure.cooldownSeconds !== null &&\n Number.isFinite(failure.cooldownSeconds) &&\n failure.cooldownSeconds > 0\n ? new Date(now.getTime() + Math.ceil(failure.cooldownSeconds) * 1000)\n : null;\n if (failure.kind === \"rate_limit\") {\n return providerReset ?? new Date(now.getTime() + PROVIDER_BACKPRESSURE_DELAY_MS);\n }\n const blockingResets = account\n ? [\n { used: account.primaryUsedPercent, reset: account.primaryResetAt },\n { used: account.secondaryUsedPercent, reset: account.secondaryResetAt },\n ]\n .filter(\n (window): window is { used: number; reset: Date } =>\n (window.used ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT &&\n window.reset instanceof Date &&\n window.reset.getTime() > now.getTime(),\n )\n .map((window) => window.reset)\n : [];\n const quotaResets = providerReset ? [...blockingResets, providerReset] : blockingResets;\n if (quotaResets.length === 0) {\n return new Date(now.getTime() + CODEX_ALLOWANCE_FALLBACK_MS);\n }\n return quotaResets.reduce((latest, reset) =>\n reset.getTime() > latest.getTime() ? reset : latest,\n );\n}\n\n/**\n * Only definitive credential/account refusals are safe rotation signals.\n * Ambiguous network failures, malformed/partial streams, invalid model content,\n * prompt 4xx, and provider 5xx may already have consumed tokens or persisted\n * progress and therefore MUST NOT walk the credential pool automatically.\n */\nexport function classifyCodexCredentialFailure(error: unknown): CodexCredentialFailure | null {\n // A permanent OAuth refresh failure is definitive and the shared resolver has\n // already fenced/stamped the exact credential version. The OpenAI client can\n // wrap a rejection from its custom fetch in APIConnectionError, so recognize\n // the typed exception through the same bounded cause chain used below.\n let refreshError: unknown = error;\n for (let depth = 0; depth < 6 && refreshError && typeof refreshError === \"object\"; depth += 1) {\n if (refreshError instanceof CodexReloginRequired) {\n return { kind: \"auth\", cooldownSeconds: null };\n }\n refreshError = (refreshError as Record<string, unknown>).cause;\n }\n // The activity catch also receives sandbox, MCP, storage, and tool failures.\n // Their HTTP status codes are not Codex account state and must never walk the\n // subscription pool or replay a tool on another credential.\n if (!isCodexTransportError(error)) {\n return null;\n }\n const usageLimit = classifyCodexUsageLimitError(error);\n if (usageLimit) {\n return { kind: \"quota\", cooldownSeconds: usageLimit.resetsInSeconds };\n }\n let cur: unknown = error;\n for (let depth = 0; depth < 6 && cur && typeof cur === \"object\"; depth++) {\n const value = cur as Record<string, unknown>;\n const body =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : null;\n const status = Number(value.status ?? value.statusCode ?? body?.status ?? body?.statusCode);\n const code = String(value.code ?? body?.code ?? \"\").toLowerCase();\n const directRetryAfter = Number(\n value.retry_after_seconds ?? body?.retry_after_seconds ?? value.retryAfterSeconds,\n );\n const retryAfterHeader =\n headerValue(value.headers, \"retry-after\") ??\n headerValue(value.responseHeaders, \"retry-after\") ??\n headerValue(body?.headers, \"retry-after\");\n const retryAfterNumber = retryAfterHeader === null ? Number.NaN : Number(retryAfterHeader);\n const retryAfterDate =\n retryAfterHeader !== null && !Number.isFinite(retryAfterNumber)\n ? Date.parse(retryAfterHeader)\n : Number.NaN;\n const retryAfter = Number.isFinite(directRetryAfter)\n ? directRetryAfter\n : Number.isFinite(retryAfterNumber)\n ? retryAfterNumber\n : Number.isFinite(retryAfterDate)\n ? Math.max(0, (retryAfterDate - Date.now()) / 1000)\n : Number.NaN;\n const cooldownSeconds =\n Number.isFinite(retryAfter) && retryAfter > 0 ? Math.ceil(retryAfter) : null;\n // Provider quota codes are more specific than their HTTP transport status.\n // A permanent allowance refusal commonly arrives as HTTP 429; classify it\n // before generic backpressure so it receives the binding-window cooldown.\n if (\n code === \"insufficient_quota\" ||\n code === \"quota_exceeded\" ||\n code === \"billing_hard_limit_reached\"\n ) {\n return { kind: \"quota\", cooldownSeconds };\n }\n if (status === 401 || code === \"unauthorized\" || code === \"invalid_api_key\") {\n return { kind: \"auth\", cooldownSeconds };\n }\n if (status === 403) {\n return { kind: \"forbidden\", cooldownSeconds };\n }\n if (status === 429 || code === \"rate_limit_exceeded\" || code === \"too_many_requests\") {\n return { kind: \"rate_limit\", cooldownSeconds };\n }\n cur = value.cause;\n }\n return null;\n}\n\n/** Humanize a seconds duration into a short \"2h 5m\" / \"9m\" / \"in under a minute\" string. */\nexport function humanizeResetWindow(resetsInSeconds: number | null): string {\n if (resetsInSeconds === null || !Number.isFinite(resetsInSeconds) || resetsInSeconds <= 0) {\n return \"shortly\";\n }\n const total = Math.ceil(resetsInSeconds);\n if (total < 60) {\n return \"in under a minute\";\n }\n const hours = Math.floor(total / 3600);\n const minutes = Math.round((total % 3600) / 60);\n if (hours > 0) {\n return minutes > 0 ? `in about ${hours}h ${minutes}m` : `in about ${hours}h`;\n }\n return `in about ${minutes}m`;\n}\n\n/**\n * Build the turn.failed payload for a ChatGPT/Codex usage cap: a precise,\n * actionable message naming the reset window, the stable `codex_usage_limit_reached`\n * code, and retryable:false (an auto-retry would just re-hit the cap).\n */\nexport function codexUsageLimitFailurePayload(\n info: { resetsInSeconds: number | null },\n detail: string,\n opts?: { allAccounts?: boolean },\n): { error: string; code: string; retryable: boolean; detail?: string } {\n // P3: when EVERY connected subscription is rate-limited the message names the\n // earliest reset across accounts; the single-account message is unchanged.\n const error = opts?.allAccounts\n ? `All connected ChatGPT/Codex subscriptions are rate-limited. Access returns ${humanizeResetWindow(info.resetsInSeconds)}. ` +\n `You can switch this session to a different model in the meantime, or wait for a subscription to reset.`\n : `Your ChatGPT/Codex subscription usage limit has been reached. Access resets ${humanizeResetWindow(info.resetsInSeconds)}. ` +\n `You can switch this session to a different model in the meantime, or wait for the limit to reset.`;\n return {\n error,\n code: \"codex_usage_limit_reached\",\n retryable: false,\n ...(detail ? { detail } : {}),\n };\n}\n\n// A usage cap that won't reset for a long time should not pin a Temporal timer\n// open indefinitely for a goal-bearing session; cap the continuation hold so the\n// goal re-evaluates at most this far out (it will re-pause if still capped).\nconst CODEX_USAGE_LIMIT_MAX_RESUME_MS = 60 * 60_000; // 1h\n\nfunction pendingToolCallFromSdkEvent(event: unknown): {\n callId: string;\n callType: string;\n callItem: Record<string, unknown>;\n} | null {\n if (!event || typeof event !== \"object\") return null;\n if ((event as { type?: unknown }).type !== \"run_item_stream_event\") return null;\n const item = (event as { item?: { type?: unknown; rawItem?: unknown } }).item;\n if (\n !item ||\n (item.type !== \"tool_call_item\" && item.type !== \"tool_search_call_item\") ||\n !item.rawItem ||\n typeof item.rawItem !== \"object\" ||\n Array.isArray(item.rawItem)\n ) {\n return null;\n }\n const raw = item.rawItem as Record<string, unknown>;\n const callId = raw.callId ?? raw.call_id ?? raw.id;\n const callType = raw.type;\n if (typeof callId !== \"string\" || callId.length === 0 || typeof callType !== \"string\") {\n return null;\n }\n return { callId, callType, callItem: raw };\n}\n\nfunction completedToolCallFromSdkEvent(event: unknown): {\n callId: string;\n resultItem: Record<string, unknown>;\n} | null {\n if (!event || typeof event !== \"object\") return null;\n if ((event as { type?: unknown }).type !== \"run_item_stream_event\") return null;\n const item = (event as { item?: { type?: unknown; rawItem?: unknown; id?: unknown } }).item;\n if (!item || (item.type !== \"tool_call_output_item\" && item.type !== \"tool_search_output_item\")) {\n return null;\n }\n const raw =\n item.rawItem && typeof item.rawItem === \"object\" && !Array.isArray(item.rawItem)\n ? (item.rawItem as Record<string, unknown>)\n : {};\n const callId = raw.callId ?? raw.call_id ?? item.id;\n return typeof callId === \"string\" && callId.length > 0 ? { callId, resultItem: raw } : null;\n}\n\n/**\n * Budget/limit exhaustion detected between model calls. This is account\n * state, not an agent failure: the segment ends gracefully (session idles,\n * run state preserved) so a top-up or limit reset lets the same session\n * continue — a failed session would reject the user's next message. An\n * active goal pauses visibly (reason \"limits\") at the next continuation\n * evaluation without consuming continuation budget.\n */\nclass BudgetExhaustedError extends Error {\n constructor(\n message: string,\n readonly serializedRunState: string | null,\n ) {\n super(message);\n this.name = \"BudgetExhaustedError\";\n }\n}\n\n// Exported for unit testing the external-billing bypass (codex-billing.test.ts); not\n// part of the activity surface. Takes the accepted policy's billing attribution and\n// the optional §7.5 P3 host `entitlements` port (when bound, its `admitRun` REPLACES\n// the local credit read for an OpenGeni-metered turn; unset → local ledger).\nexport async function ensureRunAllowed(\n settings: Settings,\n db: ActivityServices[\"db\"],\n accountId: string,\n workspaceId: string,\n isExternallyBilledTurn: boolean,\n entitlements?: ActivityServices[\"entitlements\"],\n): Promise<void> {\n // Externally billed turns are paid outside OpenGeni: skip the credit-balance\n // gate and monthly token cap. The agent-run COUNT cap below is a\n // volume/fairness quota (not a credit/cost gate) and is intentionally kept.\n //\n // §7.5 P3 — host-entitlements DELEGATION (the worker half of the same seam the\n // API edge exposes). For a non-codex turn, when the host binds `entitlements`, its\n // `admitRun` decision REPLACES the local credit-balance read below: a host that owns\n // its ledger/meter is the funding authority. A deny throws the SAME Error the local\n // read throws, so the mid-stream budget-valve at :727 wraps it in a\n // `BudgetExhaustedError` and pauses identically — the valve never learns whether the\n // deny came from the local ledger or the host meter.\n //\n // This is an admission READ only; it records NO usage (metering stays the sole,\n // idempotency-keyed writer at recordModelUsageAndDebitCredits), so a PULL host meter\n // is consulted without ever double-charging.\n if (\n !isExternallyBilledTurn &&\n entitlements &&\n (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")\n ) {\n const decision = await entitlements.admitRun({\n accountId,\n workspaceId,\n action: \"agent_run:create\",\n quantity: 1,\n });\n if (!decision.allowed) {\n throw new Error(decision.reason || \"insufficient OpenGeni credits\");\n }\n } else if (\n !isExternallyBilledTurn &&\n (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")\n ) {\n const balance = await getBillingBalance(db, accountId);\n if (balance.balanceMicros <= 0) {\n throw new Error(\"insufficient OpenGeni credits\");\n }\n }\n if (settings.usageLimitsMode === \"static\" || settings.usageLimitsMode === \"managed\") {\n const limits = configuredStaticUsageLimits(settings);\n if (limits.maxMonthlyAgentRunsPerWorkspace) {\n const used = await sumUsageQuantity(db, {\n workspaceId,\n eventType: \"agent_run.created\",\n since: startOfUtcMonth(),\n });\n // Agent turns are admitted and recorded before this worker activity starts.\n // Equality means this accepted turn is exactly at the cap; greater-than is\n // the race/backstop case where another admission already exceeded the cap.\n if (used > limits.maxMonthlyAgentRunsPerWorkspace) {\n throw new Error(\n `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`,\n );\n }\n }\n if (!isExternallyBilledTurn && limits.maxMonthlyTokensPerWorkspace) {\n const used = await sumUsageQuantity(db, {\n workspaceId,\n eventType: \"model.tokens\",\n since: startOfUtcMonth(),\n });\n if (used >= limits.maxMonthlyTokensPerWorkspace) {\n throw new Error(`monthly token limit reached (${limits.maxMonthlyTokensPerWorkspace})`);\n }\n }\n }\n}\n\nexport type ModelUsageBillingRecord = {\n billingPath: \"opengeni_credits\" | \"external\";\n /** Same quantity written to usage_events.model.cost when present; else 0. */\n pricedCostMicros: number;\n normalizedUsage: ModelCallUsageNormalization;\n upstreamProvider?: string;\n};\n\n// Exported for unit testing the external-billing bypass; not part of the activity surface.\nexport async function recordModelUsageAndDebitCredits(\n settings: Settings,\n db: ActivityServices[\"db\"],\n input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n model: string;\n externallyBilled: boolean;\n gatewayManaged?: boolean;\n gatewayBilling?: ModelResponseUsage[\"gatewayBilling\"];\n usage?: ModelUsageInput | ModelCallUsageInput | null;\n normalizedUsage?: ModelCallUsageNormalization;\n sourceKey: string;\n latencyMode?: LatencyMode;\n observability?: ActivityServices[\"observability\"];\n },\n): Promise<ModelUsageBillingRecord | null> {\n if (!input.usage) {\n return null;\n }\n const normalizedUsage = input.normalizedUsage ?? normalizeModelCallUsage(input.usage);\n const sanitizedUsage = sanitizedModelUsageInput(normalizedUsage);\n const inputTokens = sanitizedUsage.inputTokens ?? 0;\n const outputTokens = sanitizedUsage.outputTokens ?? 0;\n const totalTokens = sanitizedUsage.totalTokens ?? 0;\n const gatewayBilling = input.gatewayManaged ? input.gatewayBilling : undefined;\n if (gatewayBilling) {\n const gatewayModel = Object.values(OPENGENI_GATEWAY_MODELS).find(\n (candidate) => candidate.productId === input.model,\n );\n if (\n !gatewayModel ||\n !(gatewayModel.providers as readonly string[]).includes(gatewayBilling.finalProvider)\n ) {\n throw new Error(\n `AI Gateway reported unapproved provider ${gatewayBilling.finalProvider} for ${input.model}`,\n );\n }\n }\n // An externally billed turn is paid outside OpenGeni, so it\n // consumes ZERO OpenGeni credits and must never feed an OpenGeni cap. A\n // codex/<slug> model has no entry in configuredModelPricing, so the normal path\n // below would throw \"Missing model pricing\". We:\n // - do NOT emit the cap-feeding `model.tokens` event (ensureRunAllowed and\n // the API tokens:consume cap sum `model.tokens` with NO cost dimension, so\n // any row would count against maxMonthlyTokensPerWorkspace);\n // - record a `model.cost = 0` audit marker (harmless to the monthly cost cap);\n // - never look up pricing and never debit credits.\n if (input.externallyBilled) {\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"model.cost\",\n quantity: 0,\n unit: \"usd_micros\",\n sourceResourceType: \"model_response\",\n sourceResourceId: `${input.turnId}:${input.sourceKey}`,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`,\n });\n return {\n billingPath: \"external\",\n pricedCostMicros: 0,\n normalizedUsage,\n };\n }\n if (totalTokens > 0) {\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"model.tokens\",\n quantity: totalTokens,\n unit: \"tokens\",\n sourceResourceType: \"model_response\",\n sourceResourceId: `${input.turnId}:${input.sourceKey}`,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n idempotencyKey: `usage:model.tokens:${input.turnId}:${input.sourceKey}`,\n });\n }\n const shouldDebit = settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\";\n if (!shouldDebit || (totalTokens === 0 && !gatewayBilling)) {\n return {\n billingPath: \"opengeni_credits\",\n pricedCostMicros: 0,\n normalizedUsage,\n ...(gatewayBilling ? { upstreamProvider: gatewayBilling.finalProvider } : {}),\n };\n }\n if (!configuredModelPricing(settings)[input.model]) {\n throw new Error(`Missing model pricing for ${input.model}`);\n }\n const costMicros = gatewayBilling\n ? calculateGatewayReportedCostMicros(settings, input.model, gatewayBilling.inferenceCostUsd, {\n inputTokens,\n })\n : calculateModelUsageCostMicros(settings, input.model, sanitizedUsage, {\n latencyMode: input.latencyMode ?? \"standard\",\n });\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"model.cost\",\n quantity: costMicros,\n unit: \"usd_micros\",\n sourceResourceType: \"model_response\",\n sourceResourceId: `${input.turnId}:${input.sourceKey}`,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`,\n });\n if (costMicros > 0) {\n const result = await applyCreditDebitUpToBalance(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n type: \"model_usage_debit\",\n requestedAmountMicros: costMicros,\n sourceType: \"model_response\",\n sourceId: `${input.turnId}:${input.sourceKey}`,\n idempotencyKey: `credit:model_usage_debit:${input.turnId}:${input.sourceKey}`,\n metadata: {\n model: input.model,\n sessionId: input.sessionId,\n turnId: input.turnId,\n sourceKey: input.sourceKey,\n latencyMode: input.latencyMode ?? \"standard\",\n inputTokens,\n outputTokens,\n totalTokens,\n // Additive: the prompt-cache slice of this call's input tokens, so the\n // per-call debit record carries cache efficiency alongside the token\n // counts. 0 when the provider did not report cached tokens.\n cachedTokens: normalizedUsage.telemetry.cachedTokens ?? 0,\n ...(gatewayBilling ? { gatewayProvider: gatewayBilling.finalProvider } : {}),\n },\n });\n recordCreditMicros(input.observability, \"usage\", result.debitedMicros);\n }\n return {\n billingPath: \"opengeni_credits\",\n pricedCostMicros: costMicros,\n normalizedUsage,\n ...(gatewayBilling ? { upstreamProvider: gatewayBilling.finalProvider } : {}),\n };\n}\n\n/** Soft-fail Insights fact write — never throws into the billing/emit path. */\nexport async function recordAuthoritativeModelCallFact(input: {\n db: ActivityServices[\"db\"];\n observability: ActivityServices[\"observability\"];\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n sourceKey: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n billing: ModelUsageBillingRecord;\n}): Promise<void> {\n try {\n const telemetry = input.billing.normalizedUsage.telemetry;\n await recordModelCallFact(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n sourceKey: input.sourceKey,\n provider: input.billing.upstreamProvider ?? input.provider,\n providerApi: input.providerApi,\n model: input.model,\n billingPath: input.billing.billingPath,\n pricedCostMicros: input.billing.pricedCostMicros,\n inputTokens: telemetry.inputTokens,\n outputTokens: telemetry.outputTokens,\n cachedTokens: telemetry.cachedTokens,\n cacheWriteTokens: telemetry.cacheWriteTokens,\n reasoningTokens: telemetry.reasoningTokens,\n totalTokens: input.billing.normalizedUsage.totalTokens,\n });\n } catch (error) {\n input.observability.warn(\"model call fact persist failed\", {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n sourceKey: input.sourceKey,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nfunction sanitizedModelUsageInput(normalized: ModelCallUsageNormalization): ModelUsageInput {\n return {\n ...(normalized.telemetry.inputTokens !== null\n ? { inputTokens: normalized.telemetry.inputTokens }\n : {}),\n ...(normalized.telemetry.outputTokens !== null\n ? { outputTokens: normalized.telemetry.outputTokens }\n : {}),\n ...(normalized.totalTokens !== null ? { totalTokens: normalized.totalTokens } : {}),\n ...(normalized.telemetry.cachedTokens !== null\n ? {\n inputTokensDetails: {\n cached_tokens: normalized.telemetry.cachedTokens,\n },\n }\n : {}),\n };\n}\n\nfunction startOfUtcMonth(): Date {\n const now = new Date();\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));\n}\n\nasync function sandboxFileDownloadsForRun(\n settings: Settings,\n db: ActivityServices[\"db\"],\n objectStorage: ObjectStorage | null,\n workspaceId: string,\n resources: ResourceRef[],\n activeSandboxBackend: Settings[\"sandboxBackend\"] = settings.sandboxBackend,\n): Promise<SandboxFileDownload[]> {\n if (!requiresSignedFileResourceDownloads(settings, activeSandboxBackend)) {\n return [];\n }\n const fileResources = resources.filter(\n (resource): resource is Extract<ResourceRef, { kind: \"file\" }> => resource.kind === \"file\",\n );\n if (fileResources.length === 0) {\n return [];\n }\n if (!objectStorage) {\n throw new Error(\n `${settings.objectStorageBackend} file resources require configured object storage`,\n );\n }\n const downloadStorage = objectStorageForSandboxDownloads(settings, objectStorage);\n const downloads: SandboxFileDownload[] = [];\n for (const resource of fileResources) {\n const file = await requireFile(db, workspaceId, resource.fileId);\n const url = await downloadStorage.createGetUrl({ key: file.objectKey });\n downloads.push({\n fileId: file.id,\n mountPath: resourceMountPath(resource),\n filename: file.safeFilename,\n url: url.url,\n expiresAt: url.expiresAt,\n sizeBytes: file.sizeBytes,\n ...(file.sha256 ? { sha256: file.sha256 } : {}),\n });\n }\n return downloads;\n}\n\nexport function requiresSignedFileResourceDownloads(\n settings: Settings,\n activeSandboxBackend: Settings[\"sandboxBackend\"] = settings.sandboxBackend,\n): boolean {\n if (activeSandboxBackend === \"none\") {\n return false;\n }\n // A selfhosted machine (bring-your-own-compute) can NEVER mount ANY object store\n // — it is a remote user machine reached only over NATS, so file resources are\n // ALWAYS delivered by exec-curling a pre-signed URL onto it. Without this a\n // machine-home turn (sandbox_backend \"selfhosted\") would silently drop file\n // resources on an azure-blob / s3-compatible store (nativeBucketMount=false),\n // a regression from the pre-honest-label path where the same turn ran home=modal\n // and modal's descriptor forced signed downloads.\n if (activeSandboxBackend === \"selfhosted\") {\n return true;\n }\n // A nativeBucketMount backend (modal) cannot mount Azure Blob entries, so it\n // needs pre-signed downloads for that store. Keying on the descriptor (not the\n // \"modal\" literal) keeps this correct as bucket-mount backends are added.\n const nativeBucketMount = CAPABILITY_DESCRIPTORS[activeSandboxBackend].nativeBucketMount;\n return (\n (activeSandboxBackend === \"docker\" && settings.objectStorageBackend === \"s3-compatible\") ||\n settings.objectStorageBackend === \"aws-s3\" ||\n settings.objectStorageBackend === \"gcs\" ||\n (nativeBucketMount && settings.objectStorageBackend === \"azure-blob\")\n );\n}\n\nfunction objectStorageForSandboxDownloads(\n settings: Settings,\n objectStorage: ObjectStorage,\n): ObjectStorage {\n if (settings.objectStorageBackend !== \"s3-compatible\" || !settings.objectStorageSandboxEndpoint) {\n return objectStorage;\n }\n return (\n createObjectStorage({\n ...settings,\n objectStorageEndpoint: settings.objectStorageSandboxEndpoint,\n }) ?? objectStorage\n );\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { ConnectionCredentialsPort, SessionTurn } from \"@opengeni/contracts\";\nimport {\n buildConnectionTokenResolver,\n buildHostConnectionTokenResolver,\n type Database,\n type ResolveConnectionCredentialInput,\n type ResolveConnectionCredentialResult,\n} from \"@opengeni/db\";\n\nexport function connectionTokenResolverForTurn(input: {\n db: Database;\n settings: Settings;\n connectionCredentials?: ConnectionCredentialsPort | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n rootSessionId: string;\n attemptId: string;\n turn: SessionTurn;\n}): (request: ResolveConnectionCredentialInput) => Promise<ResolveConnectionCredentialResult> {\n const hostResolver = input.connectionCredentials?.mcpCredentials;\n if (!hostResolver) {\n return buildConnectionTokenResolver(input.db, input.settings);\n }\n return buildHostConnectionTokenResolver(hostResolver, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n rootSessionId: input.rootSessionId,\n turnId: input.turn.id,\n attemptId: input.attemptId,\n executionGeneration: input.turn.executionGeneration,\n initiator: input.turn.initiator,\n initiatorContext: input.turn.initiatorContext,\n surface: \"model\",\n });\n}\n","import {\n environmentsEncryptionKeyBytes,\n type Settings,\n withCodexCatalogProvider,\n withWorkspaceGatewayCatalogProvider,\n withWorkspaceGatewayCredential,\n} from \"@opengeni/config\";\nimport { settingsWithEnabledCapabilityMcpServers } from \"@opengeni/core\";\nimport {\n listSessionMcpServerMetadata,\n listSessionMcpServersForRun,\n workspaceCodexSubscriptionActive,\n loadWorkspaceVercelAiGatewayApiKey,\n type Database,\n type SessionMcpServerForRun,\n} from \"@opengeni/db\";\n\nexport { settingsWithEnabledCapabilityMcpServers };\n\nexport async function settingsWithSessionMcpServersForRun(\n db: Database,\n workspaceId: string,\n sessionId: string,\n attemptId: string,\n settings: Settings,\n options?: {\n onResolvedServers?: (servers: readonly SessionMcpServerForRun[]) => void;\n },\n): Promise<Settings> {\n const encryptionKey = environmentsEncryptionKeyBytes(settings);\n if (!encryptionKey) {\n const metadata = await listSessionMcpServerMetadata(db, workspaceId, sessionId);\n if (metadata.length === 0) {\n return settings;\n }\n if (metadata.some((server) => server.headerNames.length > 0)) {\n throw new Error(\n \"session MCP server credentials require OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\",\n );\n }\n }\n const servers = await listSessionMcpServersForRun(\n db,\n workspaceId,\n sessionId,\n attemptId,\n encryptionKey ?? null,\n );\n // Keep credential provenance coupled to the exact decrypted rows that are\n // overlaid into settings. A session projection read earlier in the turn can\n // be stale after a concurrent mcpCredentialUpdates renewal.\n options?.onResolvedServers?.(servers);\n return settingsWithSessionMcpServers(settings, servers);\n}\n\nexport function settingsWithSessionMcpServers(\n settings: Settings,\n servers: SessionMcpServerForRun[],\n): Settings {\n if (servers.length === 0) {\n return settings;\n }\n const sessionIds = new Set(servers.map((server) => server.id));\n return {\n ...settings,\n mcpServers: [\n ...settings.mcpServers.filter((server) => !sessionIds.has(server.id)),\n ...servers.map((server) => ({\n id: server.id,\n ...(server.name ? { name: server.name } : {}),\n url: server.url,\n ...(server.allowedTools ? { allowedTools: server.allowedTools } : {}),\n ...(server.timeoutMs ? { timeoutMs: server.timeoutMs } : {}),\n cacheToolsList: server.cacheToolsList ?? false,\n ...(server.requireApproval !== undefined\n ? { requireApproval: server.requireApproval }\n : {}),\n ...(server.connectionRef ? { connectionRef: server.connectionRef } : {}),\n headers: server.headers,\n })),\n ],\n };\n}\n\n/**\n * When the workspace has an active Codex subscription connected and the feature\n * is enabled, inject a synthetic \"codex-subscription\" registry provider so a\n * `codex/<slug>` model id routes through the ChatGPT backend. No secrets touch\n * this overlay (metadata-only read); the per-request bearer is resolved later via\n * codexRequestStorage. Idempotent and a no-op when not applicable.\n */\nexport async function settingsWithCodexCredential(\n db: Database,\n workspaceId: string,\n settings: Settings,\n activeOverride?: boolean,\n): Promise<Settings> {\n // Same active-credential predicate the billing bypass uses, so provider\n // injection and billing can never disagree on what an \"active codex\" turn is.\n // The caller may pass `activeOverride` (a single, shared read; P2-b) so routing\n // and billing decide from the exact same observation, immune to a concurrent\n // disconnect/reconnect landing between two independent reads.\n const active =\n activeOverride ?? (await workspaceCodexSubscriptionActive(db, settings, workspaceId));\n if (!active) {\n return settings; // disabled / not connected / needs_relogin / error -> leave settings unchanged\n }\n const withProvider = withCodexProvider(settings);\n return withProvider;\n}\n\n/** Pure: append the synthetic codex-subscription provider, idempotently. */\nexport function withCodexProvider(settings: Settings): Settings {\n return withCodexCatalogProvider(settings);\n}\n\nexport async function settingsWithWorkspaceGatewayCredential(\n db: Database,\n workspaceId: string,\n settings: Settings,\n): Promise<Settings> {\n const catalogSettings = withWorkspaceGatewayCatalogProvider(settings);\n const apiKey = await loadWorkspaceVercelAiGatewayApiKey(db, settings, workspaceId);\n return apiKey ? withWorkspaceGatewayCredential(catalogSettings, apiKey) : catalogSettings;\n}\n","// Multi-account P3 — the PURE rotation ranker. Zero I/O: no provider calls, no\n// decrypts, no db. It consumes the already-loaded, metadata-only account list\n// (cached usage columns + the exhausted_until cooldown column) and returns the\n// account a turn should run on. The two call sites (turn-start pre-emption and\n// the reactive 429 catch in agent-turn.ts) feed its result into the unchanged\n// `selectCodexCredentialForTurn` precedence gate (pin > active). Keeping the\n// decision pure makes the whole rotation correctness story unit-testable in\n// isolation (see codex-rotation.test.ts).\nimport type {\n CodexAccountStatus,\n CodexCredentialLeaseSelectionContext,\n CodexLeaseAccountStatus,\n CodexPinSource,\n} from \"@opengeni/db\";\n\nexport type CodexRotationAccount = CodexAccountStatus | CodexLeaseAccountStatus;\n\nexport type CodexRotationStrategy =\n | \"most_remaining\"\n | \"round_robin\"\n | \"drain_then_next\"\n | \"sharded\";\n\n/**\n * The ONE strategy rotation-enabled workspaces run: sticky-sharded. The legacy\n * strategies are all strictly dominated post-cache-affinity — session\n * stickiness is worth ~half the prompt-cache hit rate, and round_robin /\n * most_remaining churn accounts per turn while drain_then_next concentrates\n * every concurrent session on ONE account (the measured concurrency-eviction\n * failure sharding replaced). Stored `rotation_strategy` values are therefore\n * NORMALIZED here at every read site: legacy values (and any future unknown\n * string) behave as \"sharded\". The column and the legacy branch code are kept\n * intact for old-binary rollback safety — they are simply unreachable through\n * this normalization. The API accepts-but-ignores strategy writes for the same\n * reason (no SDK caller breaks). User-facing choice is intentionally gone: the\n * remaining real intents are rotation on/off, per-account allocator\n * include/exclude, and manual pins — not algorithm selection.\n */\nexport function effectiveRotationStrategy(_stored: string): CodexRotationStrategy {\n return \"sharded\";\n}\n\n/**\n * How a session's codex pin governs THIS turn's account selection (pure). Encodes the\n * policy-pin LIFECYCLE rule: a 'policy' pin is meaningful ONLY while the sharded policy\n * is active.\n * • \"manual\" — a manual pin: honored under EVERY strategy; never moved or cleared.\n * • \"sharded\" — the sharded policy is active and the pin is non-manual: assign / keep\n * / re-shard the deterministic home (covers an unpinned first turn AND\n * an existing policy pin).\n * • \"clearStale\" — a 'policy' pin while the sharded policy is NOT active: IGNORE it\n * (never honor it as a sticky pin — that is the no-escape trap) and\n * clear it lazily so the session converges to the active strategy.\n * • \"unpinned\" — no pin (or none that applies): follow the active strategy / workspace\n * active pointer, unchanged.\n */\nexport type CodexPinDisposition = \"manual\" | \"sharded\" | \"clearStale\" | \"unpinned\";\n\n/** Classify a session's codex pin against the active rotation regime (see {@link CodexPinDisposition}). */\nexport function classifyCodexPin(args: {\n pinnedCredentialId: string | null;\n pinSource: CodexPinSource | null;\n strategy: CodexRotationStrategy;\n rotationEnabled: boolean;\n}): CodexPinDisposition {\n const { pinnedCredentialId, pinSource, strategy, rotationEnabled } = args;\n const pinned = pinnedCredentialId != null;\n // A manual pin is sacrosanct under every strategy — checked FIRST so sharded never\n // touches it. DEFENSE-IN-DEPTH (fail-safe toward sacredness): a pin whose source is\n // anything OTHER than the explicit 'policy' — including a NULL source (a pre-backfill\n // row, or any pin an unforeseen path wrote without labeling it) — is treated as\n // MANUAL. An unlabeled pin must NEVER be policy-moved; only an explicitly-'policy' pin\n // is re-shardable.\n if (pinned && pinSource !== \"policy\") {\n return \"manual\";\n }\n const shardedActive = rotationEnabled && effectiveRotationStrategy(strategy) === \"sharded\";\n if (shardedActive) {\n return \"sharded\";\n }\n // A policy pin outside the sharded regime is stale → clear it.\n if (pinned && pinSource === \"policy\") {\n return \"clearStale\";\n }\n return \"unpinned\";\n}\n\nexport type RotationDecision =\n // The chosen account. `moved` ⇒ it differs from the current active pointer, so\n // the caller must persist the pointer move (and the switch is a \"rotation\").\n | { kind: \"active\"; credentialId: string; moved: boolean }\n // Every eligible account is capped/cooling: idle until the soonest instant ANY\n // account clears every blocking condition (the multi-account generalization of\n // the single-account idle-until-reset).\n | { kind: \"allCapped\"; earliestResetAt: Date }\n // No connected accounts at all (preserves today's relogin-fail path).\n | { kind: \"none\" };\n\nexport type CodexTurnLeaseSelection = {\n credentialId: string | null;\n decision: RotationDecision;\n /** Policy/manual homes never move the workspace-global legacy pointer. */\n advanceActivePointer?: boolean;\n};\n\n// Invariant 4 (NO THRASH / BOUNDED) safety floors. An all-capped idle MUST be a\n// positive, bounded wait — a null / elapsed / unknown reset can NEVER collapse it\n// into a 0 or a past instant (which the caller would turn into a 0 continueDelayMs\n// and a tight re-dispatch loop that hammers CPU/DB and never runs the model, so the\n// stale usage cache never self-heals).\n/** The minimum all-capped idle: continueDelayMs is clamped to at least this (never 0). */\nexport const MIN_IDLE_MS = 60_000; // 60s\n/**\n * Cooldown applied to an exhausted account whose cached reset is null / unknown\n * / already-elapsed (the turn hot path never refreshes usage, so a capped window's\n * reset reads stale). Treating it as \"available after a default cooldown\" keeps\n * availableAt — and therefore earliestReset — ALWAYS in the future.\n */\nexport const DEFAULT_RESET_COOLDOWN_MS = 60_000; // 60s\n/** Cached provider usage becomes unavailable only at actual exhaustion. */\nexport const CODEX_USAGE_EXHAUSTED_PCT = 100;\n\nfunction effectiveWindowUsed(usedPercent: number | null, resetAt: Date | null, now: Date): number {\n // A completed provider window is eligible immediately even if its last cache\n // sample still says 100%. This is the five-hour reset boundary—not a TTL\n // heuristic—and avoids stranding a reset subscription while another remains\n // healthy. A future/unknown reset keeps the cached percentage authoritative.\n return resetAt && resetAt.getTime() <= now.getTime() ? 0 : (usedPercent ?? 0);\n}\n\n/** The worse live window: weekly binds as hard as 5h. */\nfunction bindingUsedPct(acct: CodexRotationAccount, now: Date): number {\n return Math.max(\n effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now),\n effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now),\n );\n}\n\n/**\n * Remaining quota across the binding window — the P3 rotation key. Mirrors\n * buildCodexUsageWindowFromCache's `remaining = 100 - percent`, taking the MIN\n * across both windows (the scarcer of 5h/weekly). null percent ⇒ 100 remaining.\n */\nfunction bindingRemaining(acct: CodexRotationAccount, now: Date): number {\n const primaryRemaining =\n 100 - effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now);\n const secondaryRemaining =\n 100 - effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now);\n return Math.min(primaryRemaining, secondaryRemaining);\n}\n\nfunction cooling(acct: CodexRotationAccount, now: Date): boolean {\n return acct.exhaustedUntil != null && acct.exhaustedUntil.getTime() > now.getTime();\n}\n\n/**\n * Healthy for an already-leased/in-flight turn = connected/usable (status\n * \"active\", excludes needs_relogin/error), not cooling, and not exhausted in\n * either provider window. Allocator eligibility is\n * deliberately separate so disabling NEW work cannot break an existing live lease.\n */\nexport function isCodexCredentialHealthy(acct: CodexRotationAccount, now: Date): boolean {\n return (\n acct.status === \"active\" &&\n !cooling(acct, now) &&\n bindingUsedPct(acct, now) < CODEX_USAGE_EXHAUSTED_PCT\n );\n}\n\n/** New automatic allocation requires both health and explicit allocator eligibility. */\nexport function isCodexCredentialEligible(acct: CodexRotationAccount, now: Date): boolean {\n return acct.allocatorEnabled && isCodexCredentialHealthy(acct, now);\n}\n\n/**\n * Public eligibility predicate (same definition as the private `eligible`): an\n * account is usable this turn iff it is connected/active, not cooling, and below\n * actual exhaustion on both windows. The worker's sharded home\n * health-check uses this to decide whether a session's existing policy pin is still\n * a valid home or must be re-sharded.\n */\nexport function isCodexAccountEligible(acct: CodexRotationAccount, now: Date): boolean {\n return isCodexCredentialEligible(acct, now);\n}\n\n/** Deterministic 32-bit FNV-1a over a UTF-16 code-unit stream. Pure, allocation-free. */\nfunction fnv1a32(input: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n // 32-bit FNV prime multiply via Math.imul; `>>> 0` keeps it unsigned.\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\n\n/**\n * Session-sharded HOME account (AM-6): the deterministic account a session runs on\n * under the \"sharded\" strategy — `stableAccountList[ hash(sessionId) % N ]` over the\n * ELIGIBLE (connected, not cooling, not exhausted) accounts in stable created_at\n * order (`listCodexAccountStatuses`).\n *\n * Why deterministic hash over \"least-loaded by session count\" (AM-6): it needs ZERO\n * coordination — every worker computes the same home for a given (sessionId,\n * eligible-set), so a burst of concurrent first-turns can't all read the same\n * \"least-loaded\" account and stampede it (read-then-write skew), and there is no\n * shared round-robin cursor to contend on. It is balanced in expectation.\n *\n * Re-shard (AM-5): pass the just-capped account as already-cooling (or simply let it\n * fall over its threshold) and this reshuffles the SURVIVORS deterministically — the\n * sessions that shared a capped account spread across the remaining pool by their own\n * hashes instead of all re-concentrating on one first-eligible failover.\n *\n * Returns null when NO account is eligible (the caller idles until reset).\n */\nexport function shardCredentialForSession(args: {\n sessionId: string;\n accounts: CodexRotationAccount[];\n now: Date;\n}): string | null {\n const { sessionId, accounts, now } = args;\n const eligibles = accounts.filter((acct) => isCodexCredentialEligible(acct, now));\n if (eligibles.length === 0) {\n return null;\n }\n const index = fnv1a32(sessionId) % eligibles.length;\n return eligibles[index]!.id;\n}\n\n/** earliestResetAt across ALL connected accounts — exported for the sharded all-capped idle. */\nexport function earliestCodexReset(accounts: CodexRotationAccount[], now: Date): Date {\n return earliestReset(accounts, now);\n}\n\n/**\n * The proactive SHARDED home decision (pure — zero I/O, like {@link chooseRotationActive}).\n * Decides the account a session should run on THIS turn under the \"sharded\" strategy,\n * given its current POLICY pin (null on the first turn) and the accounts snapshot:\n *\n * - keepPin: the current policy pin is still ELIGIBLE → run there, no rewrite. This\n * is the steady-state cache-warm path (a session stays on its one home account).\n * - reshard: no policy pin yet (first-turn lazy assignment, AM-7) OR the policy pin\n * is capped/ineligible (proactive re-shard, AM-4) → deterministically shard over the\n * ELIGIBLE set (AM-6) and durably (re)write the pin (`rewritePin:true`, AM-3/AM-5).\n * - allCapped: no account is eligible → the caller idles until the earliest reset.\n *\n * A MANUAL pin is handled by the CALLER (it never reaches here); this function only\n * governs policy homes. Pure so the assignment/re-shard/keep logic is unit-testable\n * without a worker/db env; the caller wraps it with a self-heal usage refresh between\n * two evaluations exactly like chooseRotationActive's allCapped path.\n */\nexport function chooseShardedHome(args: {\n sessionId: string;\n currentPolicyPin: string | null;\n accounts: CodexRotationAccount[];\n now: Date;\n}):\n | { kind: \"home\"; credentialId: string; rewritePin: boolean }\n | { kind: \"allCapped\"; earliestResetAt: Date } {\n const { sessionId, currentPolicyPin, accounts, now } = args;\n const pinRow = currentPolicyPin\n ? (accounts.find((acct) => acct.id === currentPolicyPin) ?? null)\n : null;\n if (pinRow && isCodexCredentialEligible(pinRow, now)) {\n return { kind: \"home\", credentialId: currentPolicyPin!, rewritePin: false };\n }\n const home = shardCredentialForSession({ sessionId, accounts, now });\n if (home == null) {\n return { kind: \"allCapped\", earliestResetAt: earliestReset(accounts, now) };\n }\n return { kind: \"home\", credentialId: home, rewritePin: true };\n}\n\n/**\n * The soonest instant `acct` clears EVERY blocking condition: its cooldown end,\n * and each window's reset (only when that window is at/over the threshold). The\n * literal multi-account generalization of #143's single-account resetsInSeconds.\n *\n * GUARANTEE (invariant 4): the result is ALWAYS in the future. A blocking window\n * whose cached reset is null / unknown / already-elapsed does NOT contribute a past\n * instant (the old EPOCH0 seed bug that made earliestReset land in 1970 → a 0\n * continueDelayMs → a tight idle loop). Such a window is treated as clearing after a\n * default cooldown (now + DEFAULT_RESET_COOLDOWN_MS), so the caller always idles a\n * bounded positive time and re-checks (which refreshes usage and self-heals).\n */\nexport function availableAt(acct: CodexRotationAccount, now: Date): Date {\n const nowMs = now.getTime();\n // An unknown/elapsed block clears after a default cooldown, never in the past.\n const defaultClear = new Date(nowMs + DEFAULT_RESET_COOLDOWN_MS);\n const candidates: Date[] = [];\n // An active cooldown only blocks while it is still in the future; a past cooldown\n // self-clears (matches `cooling()`), so it must not pin availableAt to the past.\n if (acct.exhaustedUntil != null && acct.exhaustedUntil.getTime() > nowMs) {\n candidates.push(acct.exhaustedUntil);\n }\n const windowClear = (over: boolean, resetAt: Date | null | undefined) => {\n if (!over) return;\n // Over-threshold window: wait for its KNOWN future reset; a null/elapsed cached\n // reset is unknown → default cooldown (never a past instant).\n candidates.push(resetAt != null && resetAt.getTime() > nowMs ? resetAt : defaultClear);\n };\n windowClear(\n effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now) >=\n CODEX_USAGE_EXHAUSTED_PCT,\n acct.primaryResetAt,\n );\n windowClear(\n effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now) >=\n CODEX_USAGE_EXHAUSTED_PCT,\n acct.secondaryResetAt,\n );\n // Ineligible for a non-quota reason (needs_relogin / error) with no known block, or\n // a cleared cooldown: still idle a bounded cooldown before re-check — never the past.\n if (candidates.length === 0) {\n return defaultClear;\n }\n // Clears EVERY blocking condition ⇒ the MAX of the per-condition clear instants.\n return candidates.reduce((a, b) => (b.getTime() > a.getTime() ? b : a));\n}\n\n/** earliestResetAt across ALL connected accounts (min of each account's availableAt). */\nfunction earliestReset(accounts: CodexRotationAccount[], now: Date): Date {\n return accounts\n .map((acct) => availableAt(acct, now))\n .reduce((a, b) => (b.getTime() < a.getTime() ? b : a));\n}\n\n/**\n * Earliest provider/cooldown timestamp that is actually authoritative. The\n * ranker's `availableAt` deliberately synthesizes a positive default for\n * unknown/stale state; durable capacity waits must distinguish that bounded\n * refresh backoff from a real provider reset timer.\n */\nexport function authoritativeCodexCapacityResetAt(\n accounts: CodexRotationAccount[],\n now: Date,\n): Date | null {\n const future: Date[] = [];\n for (const account of accounts) {\n if (!account.allocatorEnabled || account.status !== \"active\") continue;\n if (account.exhaustedUntil && account.exhaustedUntil.getTime() > now.getTime()) {\n future.push(account.exhaustedUntil);\n }\n if (\n (account.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT &&\n account.primaryResetAt &&\n account.primaryResetAt.getTime() > now.getTime()\n ) {\n future.push(account.primaryResetAt);\n }\n if (\n (account.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT &&\n account.secondaryResetAt &&\n account.secondaryResetAt.getTime() > now.getTime()\n ) {\n future.push(account.secondaryResetAt);\n }\n }\n if (future.length === 0) return null;\n return future.reduce((earliest, candidate) =>\n candidate.getTime() < earliest.getTime() ? candidate : earliest,\n );\n}\n\n/**\n * The bounded all-capped idle delay: clamp(earliestResetAt − now) into\n * [MIN_IDLE_MS, maxMs]. NEVER 0 and NEVER negative, so a null / elapsed / unknown\n * reset cannot collapse the hold into a tight re-dispatch loop (invariant 4). The two\n * agent-turn call sites (proactive turn-start + reactive 429) feed allCapped's\n * earliestResetAt through this before returning continueDelayMs.\n */\nexport function computeIdleDelayMs(earliestResetAt: Date, now: Date, maxMs: number): number {\n const delta = earliestResetAt.getTime() - now.getTime();\n return Math.min(Math.max(delta, MIN_IDLE_MS), maxMs);\n}\n\n// --- P3 reactive-rotation boundedness (Finding 1). The reactive 429 catch, on a\n// LIVE failover candidate, normally returns continueDelayMs:0 (skip the hold and\n// re-dispatch NOW — the just-served account is cooling so the next rank cannot\n// re-pick it). Two independent second-order faults can break that \"cannot\n// re-pick it\" premise and turn the 0-delay re-dispatch into a hot loop, so this\n// pure decision applies two backstops before allowing the 0.\n\n/**\n * Slow-retry floor (Finding 1a) for the double-fault where the just-served\n * account's cooldown write could NOT be confirmed persisted: the next proactive\n * rank might re-select the same capped account (stale-low cached usedPercent, not\n * cooling). A positive floor degrades that to a SLOW retry instead of a\n * model-paced hot loop. A few seconds — long enough to break the loop, short\n * enough to stay responsive once the transient write fault clears.\n */\nexport const REACTIVE_PERSISTENCE_FAULT_FLOOR_MS = 5_000; // 5s\n/**\n * Circuit-breaker slack (Finding 1b) added to the connected-account count to bound\n * consecutive reactive failovers. Each legitimate failover cools one account, so\n * after at most N failovers every account is capped and the reactive path takes the\n * all-capped idle instead; the +margin absorbs benign capacity re-ranks without\n * tripping the breaker in normal use.\n */\nexport const REACTIVE_ROTATION_MARGIN = 2;\n/**\n * The FIXED positive idle the reactive path falls to once consecutive reactive\n * failovers exceed the bound (a double-fault where cooldown writes are not sticking\n * AND the 429s carry no usage headers, so the same account keeps getting re-picked).\n * Mirrors the all-capped floor — a mandatory, bounded hold, never another 0-delay\n * re-dispatch — so the loop can never hammer the capped backend + DB (invariant 4).\n */\nexport const REACTIVE_CIRCUIT_BREAKER_IDLE_MS = MIN_IDLE_MS; // 60s\n\n/** The reactive-resume shape returned to the goal-continuation caller. */\nexport type ReactiveRotationResume = { continueDelayMs: number; idleUntilReset: boolean };\n\n/**\n * Decide the continueDelayMs for a reactive 429 failover onto a LIVE candidate,\n * bounding the (otherwise 0-delay) re-dispatch against two second-order faults:\n *\n * 1. Circuit breaker (1b): if the consecutive reactive-failover streak (prior\n * rotated 429 failovers since the last successful turn, PLUS this one) exceeds\n * `connectedAccountCount + REACTIVE_ROTATION_MARGIN`, fall to a FIXED positive,\n * MANDATORY idle. Covers the double-fault (cooldown write not persisted + a\n * header-less cap 429) where the same capped account is re-picked every turn.\n * 2. Persistence-fault floor (1a): if the just-served account's cooldown could NOT\n * be confirmed persisted, use a positive floor (slow retry) instead of 0.\n *\n * Otherwise (a confirmed cooldown + an in-bounds streak) returns the unchanged\n * 0-delay fast re-dispatch — the happy single-rotation path is byte-identical.\n * Pure so the boundedness contract is unit-testable without a worker/db env.\n */\nexport function computeReactiveRotationResume(args: {\n cooldownPersisted: boolean;\n priorConsecutiveRotations: number; // reactive rotated failovers since last success (excludes this one)\n connectedAccountCount: number;\n}): ReactiveRotationResume {\n const streak = args.priorConsecutiveRotations + 1; // include the failover about to be published\n const bound = args.connectedAccountCount + REACTIVE_ROTATION_MARGIN;\n if (streak > bound) {\n return { continueDelayMs: REACTIVE_CIRCUIT_BREAKER_IDLE_MS, idleUntilReset: true };\n }\n if (!args.cooldownPersisted) {\n return { continueDelayMs: REACTIVE_PERSISTENCE_FAULT_FLOOR_MS, idleUntilReset: false };\n }\n return { continueDelayMs: 0, idleUntilReset: false };\n}\n\n/**\n * THE pure rotation ranker. `accounts` arrives in stable created_at order\n * (listCodexAccountStatuses), which deterministically breaks ranking ties.\n */\nexport function chooseRotationActive(args: {\n rotationStrategy: CodexRotationStrategy;\n activeCredentialId: string | null;\n priorCredentialId: string | null;\n accounts: CodexRotationAccount[];\n now: Date;\n}): RotationDecision {\n const { activeCredentialId, priorCredentialId, accounts, now } = args;\n // Normalize at the entry point: rotation-enabled ALWAYS behaves as sharded\n // (see effectiveRotationStrategy). args keeps the field so call sites and\n // tests can still express stored legacy values.\n const rotationStrategy = effectiveRotationStrategy(args.rotationStrategy);\n const allocatableAccounts = accounts.filter((account) => account.allocatorEnabled);\n\n if (allocatableAccounts.length === 0) {\n return { kind: \"none\" };\n }\n\n const eligibles = allocatableAccounts.filter((acct) => isCodexCredentialEligible(acct, now));\n\n // The active pointer is a cursor/manual preference, NOT a sticky lease. In\n // particular, most_remaining must rank the whole eligible pool every turn;\n // keeping a healthy active account sticky was the production monopolization\n // defect fixed by credential allocator. drain_then_next remains the one explicitly sticky\n // strategy, and a manual pin is handled by the caller as explicit policy.\n const decide = (chosen: CodexRotationAccount | undefined): RotationDecision => {\n if (!chosen) {\n return {\n kind: \"allCapped\",\n earliestResetAt: earliestReset(allocatableAccounts, now),\n };\n }\n return {\n kind: \"active\",\n credentialId: chosen.id,\n moved: chosen.id !== activeCredentialId,\n };\n };\n\n if (rotationStrategy === \"round_robin\") {\n // Next eligible AFTER the prior account in list order (wrap around). When the\n // prior account isn't found, start from the head.\n if (eligibles.length === 0) {\n return {\n kind: \"allCapped\",\n earliestResetAt: earliestReset(allocatableAccounts, now),\n };\n }\n const priorIdx = priorCredentialId\n ? allocatableAccounts.findIndex((acct) => acct.id === priorCredentialId)\n : -1;\n const ordered =\n priorIdx >= 0\n ? [\n ...allocatableAccounts.slice(priorIdx + 1),\n ...allocatableAccounts.slice(0, priorIdx + 1),\n ]\n : allocatableAccounts;\n const chosen = ordered.find((acct) => isCodexCredentialEligible(acct, now));\n return decide(chosen);\n }\n\n if (rotationStrategy === \"drain_then_next\") {\n // Stay on the prior account while it is eligible (drain it), else first eligible.\n const priorRow = priorCredentialId\n ? accounts.find((acct) => acct.id === priorCredentialId)\n : undefined;\n if (priorRow && isCodexCredentialEligible(priorRow, now)) {\n return decide(priorRow);\n }\n return decide(eligibles[0]);\n }\n\n // most_remaining (default + the correctness path). Across the eligible set:\n // 1. least active leases (concurrent turns spread before quota metadata moves),\n // 2. most remaining binding quota,\n // 3. fewest historical selections,\n // 4. least-recently selected, then stable created_at/id input order.\n // Base CodexAccountStatus values (pure legacy tests/reactive rank) default the\n // lease/cursor metadata to zero/null, preserving deterministic stable ties.\n const activeLeases = (acct: CodexRotationAccount): number =>\n \"activeLeaseCount\" in acct ? acct.activeLeaseCount : 0;\n const selections = (acct: CodexRotationAccount): number =>\n \"selectionCount\" in acct ? acct.selectionCount : 0;\n const lastSelected = (acct: CodexRotationAccount): number =>\n \"lastSelectedAt\" in acct && acct.lastSelectedAt ? acct.lastSelectedAt.getTime() : 0;\n const chosen = eligibles.reduce<CodexRotationAccount | undefined>((best, acct) => {\n if (!best) {\n return acct;\n }\n if (activeLeases(acct) !== activeLeases(best)) {\n return activeLeases(acct) < activeLeases(best) ? acct : best;\n }\n if (bindingRemaining(acct, now) !== bindingRemaining(best, now)) {\n return bindingRemaining(acct, now) > bindingRemaining(best, now) ? acct : best;\n }\n if (selections(acct) !== selections(best)) {\n return selections(acct) < selections(best) ? acct : best;\n }\n return lastSelected(acct) < lastSelected(best) ? acct : best;\n }, undefined);\n return decide(chosen);\n}\n\n/**\n * Exact pre-0053 selector used while the lease cutover is off.\n *\n * Old workers keep a healthy `most_remaining` active pointer sticky and know\n * nothing about lease counts or fairness cursors. A compatible worker must do\n * the same until BOTH the deployment flag and workspace cutover are enabled;\n * otherwise a rolling fleet would run two allocators at once. When the active\n * pointer is no longer eligible, zeroing the additive metadata delegates to the\n * same capacity ranking that the old selector used.\n */\nexport function chooseLegacyRotationActive(\n args: Parameters<typeof chooseRotationActive>[0],\n): RotationDecision {\n if (args.rotationStrategy === \"most_remaining\") {\n const active = args.activeCredentialId\n ? args.accounts.find((account) => account.id === args.activeCredentialId)\n : undefined;\n if (active && isCodexCredentialEligible(active, args.now)) {\n return { kind: \"active\", credentialId: active.id, moved: false };\n }\n }\n return chooseRotationActive({\n ...args,\n accounts: args.accounts.map((account) => ({\n ...account,\n activeLeaseCount: 0,\n selectionCount: 0,\n lastSelectedAt: null,\n })),\n });\n}\n\n/**\n * Full pure policy at the transaction boundary. A live same-turn lease is\n * idempotent; the rollout-off/manual path preserves pin>pointer behavior; a\n * healthy pin wins only while eligible, so quota/auth quarantine cannot trap a\n * session on one subscription.\n */\nexport function selectCodexCredentialLeaseForTurn(args: {\n context: CodexCredentialLeaseSelectionContext;\n leasingEnabled: boolean;\n sessionId: string;\n sessionPinnedCredentialId: string | null;\n sessionPinSource: CodexPinSource | null;\n sessionLastCredentialId: string | null;\n now: Date;\n}): CodexTurnLeaseSelection {\n const {\n accounts,\n activeCredentialId,\n rotationEnabled,\n leaseRotationEnabled,\n rotationStrategy,\n existingCredentialId,\n } = args.context;\n const leasingEnabled = args.leasingEnabled && leaseRotationEnabled;\n // Normalized: rotation-enabled always behaves as sharded (see\n // effectiveRotationStrategy); the stored value is only ever legacy residue.\n const strategy = effectiveRotationStrategy(rotationStrategy);\n const existing = existingCredentialId\n ? accounts.find((account) => account.id === existingCredentialId)\n : undefined;\n if (existing && isCodexCredentialHealthy(existing, args.now)) {\n return {\n credentialId: existing.id,\n advanceActivePointer: false,\n decision: {\n kind: \"active\",\n credentialId: existing.id,\n moved: existing.id !== activeCredentialId,\n },\n };\n }\n\n const connectedIds = new Set(\n accounts.filter((account) => account.allocatorEnabled).map((account) => account.id),\n );\n\n const pinDisposition = classifyCodexPin({\n pinnedCredentialId: args.sessionPinnedCredentialId,\n pinSource: args.sessionPinSource,\n strategy,\n rotationEnabled,\n });\n\n // A manual pin is user intent, not a policy hint. Never silently fail it over.\n // We still reject allocator-disabled rows for a NEW turn; a healthy live\n // same-turn lease already returned above before this admission filter.\n if (pinDisposition === \"manual\" && args.sessionPinnedCredentialId) {\n const pinned = accounts.find((account) => account.id === args.sessionPinnedCredentialId);\n if (!pinned?.allocatorEnabled) {\n return { credentialId: null, decision: { kind: \"none\" }, advanceActivePointer: false };\n }\n if (isCodexCredentialHealthy(pinned, args.now)) {\n return {\n credentialId: pinned.id,\n decision: { kind: \"active\", credentialId: pinned.id, moved: false },\n advanceActivePointer: false,\n };\n }\n return {\n credentialId: null,\n decision: {\n kind: \"allCapped\",\n earliestResetAt: availableAt(pinned, args.now),\n },\n advanceActivePointer: false,\n };\n }\n\n // Pin-policy homes compose with the credential allocator by sharding only the candidate list\n // handed to this selector. A future policy filter may therefore choose one\n // primary/fallback pool before this ranker runs; accounts from different pools\n // are never union-ranked here.\n if (pinDisposition === \"sharded\") {\n if (accounts.length === 0) {\n return { credentialId: null, decision: { kind: \"none\" }, advanceActivePointer: false };\n }\n const shard = chooseShardedHome({\n sessionId: args.sessionId,\n currentPolicyPin: args.sessionPinSource === \"policy\" ? args.sessionPinnedCredentialId : null,\n accounts,\n now: args.now,\n });\n if (shard.kind === \"allCapped\") {\n return {\n credentialId: null,\n decision: shard,\n advanceActivePointer: false,\n };\n }\n return {\n credentialId: shard.credentialId,\n decision: {\n kind: \"active\",\n credentialId: shard.credentialId,\n moved: shard.credentialId !== activeCredentialId,\n },\n advanceActivePointer: false,\n };\n }\n\n // A stale policy pin is intentionally ignored here and cleared by the caller\n // after the atomic selection. Rotation-off/unpinned behavior otherwise keeps\n // the pre-lease pin > active-pointer contract.\n if (!rotationEnabled) {\n const credentialId =\n activeCredentialId && connectedIds.has(activeCredentialId) ? activeCredentialId : null;\n return {\n credentialId,\n decision: credentialId ? { kind: \"active\", credentialId, moved: false } : { kind: \"none\" },\n };\n }\n\n // Before the workspace cutover bit is enabled (or after the deployment kill\n // switch is turned off), preserve the exact legacy policy used by old workers:\n // a pin stays sticky; otherwise an enabled workspace runs the pure legacy\n // rotation ranker without touching lease/cursor state.\n if (!leasingEnabled && pinDisposition !== \"clearStale\" && args.sessionPinnedCredentialId) {\n const credentialId = connectedIds.has(args.sessionPinnedCredentialId)\n ? args.sessionPinnedCredentialId\n : activeCredentialId && connectedIds.has(activeCredentialId)\n ? activeCredentialId\n : null;\n return {\n credentialId,\n decision: credentialId ? { kind: \"active\", credentialId, moved: false } : { kind: \"none\" },\n };\n }\n\n const priorId = args.sessionLastCredentialId ?? activeCredentialId;\n const choose = leasingEnabled ? chooseRotationActive : chooseLegacyRotationActive;\n const decision = choose({\n rotationStrategy: strategy,\n activeCredentialId,\n // Per-session continuity is the round-robin/drain cursor. Falling back to\n // the workspace pointer is only correct when this session has never run.\n priorCredentialId: priorId,\n accounts,\n now: args.now,\n });\n return {\n credentialId: decision.kind === \"active\" ? decision.credentialId : null,\n decision,\n };\n}\n","import {\n DEFAULT_CODEX_FLEET_POLICY_V1,\n compareCodexFleetCanonicalStringsV1,\n createCodexFleetReplayRecordV1,\n type CodexFleetCandidateStatus,\n type CodexFleetDecisionInputV1,\n type CodexFleetReplayRecordV1,\n} from \"@opengeni/contracts\";\nimport type { CodexLeaseAccountStatus } from \"@opengeni/db\";\nimport { CancelledFailure } from \"@temporalio/activity\";\nimport { createHmac } from \"node:crypto\";\nimport { TurnAttemptFencedError } from \"./turn-attempt-fenced\";\n\nexport const CODEX_FLEET_SHADOW_MAX_PAYLOAD_BYTES = 34 * 1_024;\n\nexport type CodexFleetActualDecisionV1 = {\n outcome: \"selected\" | \"waiting\" | \"none\";\n candidateKey: string | null;\n reason: \"lease_reused\" | \"pin\" | \"rotation\" | \"active\" | \"all_capped\" | \"none\";\n};\n\nexport type CodexFleetShadowComparisonV1 =\n | \"match\"\n | \"different_candidate\"\n | \"different_outcome\"\n | \"not_comparable_truncated\";\n\nexport type CodexFleetShadowPayloadV1 = {\n schemaVersion: 1;\n mode: \"shadow\";\n actual: CodexFleetActualDecisionV1;\n comparison: CodexFleetShadowComparisonV1;\n replay: CodexFleetReplayRecordV1;\n};\n\nexport type CodexFleetShadowBuildInputV1 = {\n accounts: readonly CodexLeaseAccountStatus[];\n actualCredentialId: string | null;\n actualOutcome: CodexFleetActualDecisionV1[\"outcome\"];\n actualReason: CodexFleetActualDecisionV1[\"reason\"];\n affinityCredentialId: string | null;\n fencedInFlight: boolean;\n nearExhaustionPct: number;\n now: Date;\n /** Per-event entropy used only to unlink account aliases; never persisted. */\n aliasSeed: string;\n};\n\nexport type CodexFleetShadowPublicationResultV1 =\n | { outcome: \"disabled\" }\n | {\n outcome: \"published\";\n payload: CodexFleetShadowPayloadV1;\n payloadBytes: number;\n }\n | {\n outcome: \"failed\";\n stage: \"build\" | \"serialize\" | \"publish\";\n reason: \"payload_too_large\" | \"unexpected\";\n errorName: string;\n payloadBytes: number | null;\n };\n\nexport const CODEX_FLEET_SHADOW_DECISION_MAX_METRIC_SERIES = 3 * 3 * 4 * 4 * 2;\nexport const CODEX_FLEET_SHADOW_ERROR_MAX_METRIC_SERIES = 3 * 2;\n\n/** Fixed low-cardinality labels; workspace/account/tenant identity is structurally absent. */\nexport function codexFleetShadowDecisionMetricLabelsV1(payload: CodexFleetShadowPayloadV1) {\n return {\n actual_outcome: payload.actual.outcome,\n shadow_outcome: payload.replay.decision.outcome,\n comparison: payload.comparison,\n confidence: payload.replay.decision.confidence,\n truncated: payload.replay.truncatedCandidateCount > 0 ? \"true\" : \"false\",\n } as const;\n}\n\nexport function codexFleetShadowErrorMetricLabelsV1(\n result: Extract<CodexFleetShadowPublicationResultV1, { outcome: \"failed\" }>,\n) {\n return { stage: result.stage, reason: result.reason } as const;\n}\n\n/**\n * Default-off, bounded, fail-open runtime seam for the shadow record.\n *\n * The typed result intentionally carries no error message: provider, database,\n * or transport errors can include private metadata. Callers may count/log only\n * the bounded stage, reason, name, and size fields returned here. A failure can\n * never replace or clear the credential already selected by the allocator.\n */\nexport async function publishCodexFleetShadowDecisionV1(input: {\n enabled: boolean;\n decision: CodexFleetShadowBuildInputV1;\n publish: (\n events: Array<{\n type: \"codex.fleet.decision\";\n payload: CodexFleetShadowPayloadV1;\n }>,\n ) => Promise<unknown>;\n}): Promise<CodexFleetShadowPublicationResultV1> {\n if (!input.enabled) return { outcome: \"disabled\" };\n\n let stage: \"build\" | \"serialize\" | \"publish\" = \"build\";\n let payloadBytes: number | null = null;\n try {\n const payload = buildCodexFleetShadowPayloadV1(input.decision);\n stage = \"serialize\";\n payloadBytes = new TextEncoder().encode(JSON.stringify(payload)).byteLength;\n if (payloadBytes > CODEX_FLEET_SHADOW_MAX_PAYLOAD_BYTES) {\n return {\n outcome: \"failed\",\n stage,\n reason: \"payload_too_large\",\n errorName: \"CodexFleetShadowPayloadTooLargeError\",\n payloadBytes,\n };\n }\n stage = \"publish\";\n await input.publish([{ type: \"codex.fleet.decision\", payload }]);\n return { outcome: \"published\", payload, payloadBytes };\n } catch (error) {\n // These are authoritative activity lifecycle signals, not shadow failures.\n // Swallowing either would allow a superseded attempt to continue mutating.\n if (error instanceof TurnAttemptFencedError || error instanceof CancelledFailure) throw error;\n return {\n outcome: \"failed\",\n stage,\n reason: \"unexpected\",\n errorName: safeErrorName(error),\n payloadBytes,\n };\n }\n}\n\nexport function buildCodexFleetShadowPayloadV1(\n input: CodexFleetShadowBuildInputV1,\n): CodexFleetShadowPayloadV1 {\n // Randomized keyed ordering makes c00/c01 unlinkable across events while the\n // supplied event seed keeps this one replay/payload build deterministic.\n const eventAccounts = [...input.accounts].sort(\n (left, right) =>\n compareCodexFleetCanonicalStringsV1(\n aliasSortKey(input.aliasSeed, left.id),\n aliasSortKey(input.aliasSeed, right.id),\n ) || compareCodexFleetCanonicalStringsV1(left.id, right.id),\n );\n const aliases = new Map(\n eventAccounts.map((account, index) => [account.id, candidateAlias(index)] as const),\n );\n const actualCandidateKey = input.actualCredentialId\n ? (aliases.get(input.actualCredentialId) ?? null)\n : null;\n const currentCandidateKey = input.affinityCredentialId\n ? (aliases.get(input.affinityCredentialId) ?? null)\n : null;\n const decisionInput: CodexFleetDecisionInputV1 = {\n observedAtMs: input.now.getTime(),\n request: {\n placement: input.fencedInFlight ? \"fenced_in_flight\" : \"new\",\n priority: \"standard\",\n currentCandidateKey: input.fencedInFlight ? actualCandidateKey : currentCandidateKey,\n waitAgeMs: 0,\n overlayKey: null,\n overlayMode: \"none\",\n },\n admission: {\n // The shadow policy does not invent hard capacity from account count. A later typed\n // admission snapshot supplies dynamic capacity; shadow v1 records unknown.\n dynamicCapacityUnits: null,\n inUseUnits: input.accounts.reduce((sum, account) => sum + account.activeLeaseCount, 0),\n queuedManagerCount: 0,\n emergencyFuseActive: false,\n },\n candidates: eventAccounts.map((account, index) => ({\n key: candidateAlias(index),\n status: normalizeStatus(account.status),\n allocatorEnabled: account.allocatorEnabled,\n cooldownRemainingMs: remainingMs(account.exhaustedUntil, input.now),\n activeLeaseCount: account.activeLeaseCount,\n quota: {\n primary: {\n usedPercent: account.primaryUsedPercent,\n resetRemainingMs: remainingMs(account.primaryResetAt, input.now),\n },\n secondary: {\n usedPercent: account.secondaryUsedPercent,\n resetRemainingMs: remainingMs(account.secondaryResetAt, input.now),\n },\n checkedAgeMs: ageMs(account.usageCheckedAt, input.now),\n confidence: quotaConfidence(account),\n },\n // Current production cache evidence is aggregate metric + opaque log data,\n // not allocator state. Preserve that gap as unknown instead of fabricating 0.\n cache: {\n hitRatio: null,\n sampledTokens: null,\n checkedAgeMs: null,\n confidence: \"unknown\",\n state: \"unknown\",\n thresholdObservedForMs: null,\n },\n // The shadow policy has no typed workspace-local burn feed at this boundary yet.\n observedBurn: {\n primaryPercentPerHour: null,\n secondaryPercentPerHour: null,\n confidence: \"unknown\",\n },\n // Provider accounting has not supplied a typed burn observation yet.\n // Unknown inference is explicit and contributes no fabricated tenant truth.\n inferredUnexplainedBurn: {\n primaryPercentPerHour: null,\n secondaryPercentPerHour: null,\n confidence: \"unknown\",\n },\n overlayKeys: [],\n })),\n };\n const replay = createCodexFleetReplayRecordV1(decisionInput, {\n ...DEFAULT_CODEX_FLEET_POLICY_V1,\n placementUsageCeilingPercent: input.nearExhaustionPct,\n });\n const actual: CodexFleetActualDecisionV1 = {\n outcome: input.actualOutcome,\n candidateKey: actualCandidateKey,\n reason: input.actualReason,\n };\n return {\n schemaVersion: 1,\n mode: \"shadow\",\n actual,\n comparison: compareDecision(actual, replay),\n replay,\n };\n}\n\nfunction compareDecision(\n actual: CodexFleetActualDecisionV1,\n replay: CodexFleetReplayRecordV1,\n): CodexFleetShadowComparisonV1 {\n if (\n replay.truncatedCandidateCount > 0 &&\n actual.candidateKey !== null &&\n !replay.input.candidates.some((candidate) => candidate.key === actual.candidateKey)\n ) {\n return \"not_comparable_truncated\";\n }\n const shadowOutcome = replay.decision.outcome === \"selected\" ? \"selected\" : \"none\";\n const actualComparableOutcome = actual.outcome === \"selected\" ? \"selected\" : \"none\";\n if (shadowOutcome !== actualComparableOutcome) return \"different_outcome\";\n if (shadowOutcome === \"selected\") {\n return replay.decision.selectedCandidateKey === actual.candidateKey\n ? \"match\"\n : \"different_candidate\";\n }\n return \"match\";\n}\n\nfunction normalizeStatus(status: string): CodexFleetCandidateStatus {\n if (status === \"active\" || status === \"needs_relogin\" || status === \"error\") return status;\n return \"unknown\";\n}\n\nfunction candidateAlias(index: number): string {\n return `c${index.toString(36).padStart(2, \"0\")}`;\n}\n\nfunction aliasSortKey(seed: string, credentialId: string): string {\n return createHmac(\"sha256\", seed).update(credentialId).digest(\"hex\");\n}\n\nfunction quotaConfidence(account: CodexLeaseAccountStatus): \"unknown\" | \"low\" | \"medium\" | \"high\" {\n if (!account.usageCheckedAt) return \"unknown\";\n const windows = [\n [account.primaryUsedPercent, account.primaryResetAt],\n [account.secondaryUsedPercent, account.secondaryResetAt],\n ] as const;\n const complete = windows.filter(([used, reset]) => used !== null && reset !== null).length;\n const partial = windows.some(([used, reset]) => (used === null) !== (reset === null));\n if (complete === 0) return \"unknown\";\n if (partial) return \"low\";\n return complete === windows.length ? \"high\" : \"medium\";\n}\n\nfunction remainingMs(value: Date | null, now: Date): number | null {\n return value ? Math.max(0, value.getTime() - now.getTime()) : null;\n}\n\nfunction ageMs(value: Date | null, now: Date): number | null {\n return value ? Math.max(0, now.getTime() - value.getTime()) : null;\n}\n\nfunction safeErrorName(error: unknown): string {\n if (!(error instanceof Error)) return \"UnknownError\";\n return /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(error.name) ? error.name : \"Error\";\n}\n","/**\n * The activity lost ownership of its exact turn generation/attempt.\n *\n * This is an ordinary stale-writer outcome, not a Temporal cancellation. The\n * current owner or control transaction already holds authoritative state, so\n * the losing activity must stop locally without asking the workflow to settle\n * or fail the turn again.\n */\nexport class TurnAttemptFencedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TurnAttemptFencedError\";\n }\n}\n","// db-backed Codex token lifecycle for a turn: proactive refresh, single-flight\n// per credential instance, and permanent-failure status surfacing.\n//\n// The implementation now lives in @opengeni/db (packages/db/src/codex-token-resolver.ts)\n// so the API process can drive the SAME refreshing resolver for the P2 /wham/usage\n// quota-bar reads without duplicating the refresh-CAS / single-flight / RLS logic.\n// This module re-exports it for back-compat, keeping the agent-turn.ts call site\n// (buildCodexTokenResolver) unchanged.\nexport { buildCodexTokenResolver, type CodexAuthDeps } from \"@opengeni/db\";\n","import {\n fetchCodexUsageForAccount,\n getCodexCapacityWaitForSession,\n listCodexAccountStatuses,\n listPendingCodexCapacityWakeTargets,\n reconcileCodexCapacityWait as reconcileCodexCapacityWaitDb,\n type CodexCapacityWakeTarget,\n type CodexCapacitySelectionContext,\n} from \"@opengeni/db\";\nimport type { Settings } from \"@opengeni/config\";\nimport {\n CODEX_USAGE_EXHAUSTED_PCT,\n authoritativeCodexCapacityResetAt,\n isCodexCredentialEligible,\n selectCodexCredentialLeaseForTurn,\n} from \"./codex-rotation\";\nimport type {\n ActivityServices,\n GetCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitResult,\n} from \"./types\";\n\ntype CodexCapacitySignalServices = {\n signalCodexCapacityWorkflow?:\n | NonNullable<ActivityServices[\"signalCodexCapacityWorkflow\"]>\n | null\n | undefined;\n wakeSessionWorkflow: ActivityServices[\"wakeSessionWorkflow\"];\n};\n\n/**\n * Run a bounded set of usage refreshes, then repair every committed waiter\n * revision even when an individual provider refresh failed. The database\n * outbox remains authoritative; this helper only guarantees that every worker\n * refresh path reaches the same post-commit delivery seam.\n */\nexport async function refreshCodexUsageAndRepairCapacityWaiters(\n refreshes: readonly (() => Promise<unknown>)[],\n repairPendingWakes: () => Promise<void>,\n): Promise<void> {\n await Promise.all(refreshes.map((refresh) => refresh().catch(() => undefined)));\n await repairPendingWakes();\n}\n\n/** Deliver committed waiter revisions; Postgres remains the repairable outbox. */\nexport async function signalCodexCapacityWakeTargets(\n services: CodexCapacitySignalServices,\n targets: readonly CodexCapacityWakeTarget[],\n): Promise<void> {\n await Promise.allSettled(\n targets.map((target) =>\n services.signalCodexCapacityWorkflow\n ? services.signalCodexCapacityWorkflow({\n accountId: target.accountId,\n workspaceId: target.workspaceId,\n sessionId: target.sessionId,\n workflowId: target.workflowId,\n wakeRevision: target.wakeRevision,\n })\n : services.wakeSessionWorkflow\n ? services.wakeSessionWorkflow({\n accountId: target.accountId,\n workspaceId: target.workspaceId,\n sessionId: target.sessionId,\n workflowId: target.workflowId,\n wakeRevision: target.workflowWakeRevision,\n })\n : Promise.resolve(),\n ),\n );\n}\n\n/** Repair a commit/signal crash edge by redelivering every pending revision. */\nexport async function signalPendingCodexCapacityWakeTargets(\n services: CodexCapacitySignalServices & { db: ActivityServices[\"db\"] },\n workspaceId: string,\n): Promise<void> {\n const targets = await listPendingCodexCapacityWakeTargets(services.db, workspaceId).catch(\n () => [],\n );\n await signalCodexCapacityWakeTargets(services, targets);\n}\n\nexport function codexCapacityDecision(\n context: CodexCapacitySelectionContext,\n settings: Settings,\n): ReturnType<Parameters<typeof reconcileCodexCapacityWaitDb>[2]> {\n const now = new Date();\n const selected = selectCodexCredentialLeaseForTurn({\n context,\n leasingEnabled: settings.codexCredentialLeasingEnabled,\n sessionId: context.sessionId,\n sessionPinnedCredentialId: context.sessionPinnedCredentialId,\n sessionPinSource: context.sessionPinSource,\n sessionLastCredentialId: context.sessionLastCredentialId,\n now,\n });\n if (selected.credentialId) {\n return {\n kind: \"available\",\n credentialId: selected.credentialId,\n diagnostic: {\n connectedCount: context.accounts.length,\n eligibleCount: context.accounts.filter((account) => isCodexCredentialEligible(account, now))\n .length,\n },\n };\n }\n const authoritativeReset = authoritativeCodexCapacityResetAt(context.accounts, now);\n return {\n kind: \"unavailable\",\n earliestResetAt: authoritativeReset,\n resetKind: authoritativeReset ? \"authoritative\" : \"bounded_refresh\",\n diagnostic: {\n connectedCount: context.accounts.length,\n allocatorEnabledCount: context.accounts.filter((account) => account.allocatorEnabled).length,\n policyHash: context.policyHash,\n },\n };\n}\n\nasync function refreshCapacityMetadata(\n services: ActivityServices,\n workspaceId: string,\n): Promise<void> {\n const accounts = await listCodexAccountStatuses(services.db, workspaceId).catch(() => []);\n const stale = accounts.filter(\n (account) =>\n account.allocatorEnabled &&\n account.status === \"active\" &&\n ((account.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||\n (account.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||\n account.usageCheckedAt === null),\n );\n await refreshCodexUsageAndRepairCapacityWaiters(\n stale.map(\n (account) => () =>\n fetchCodexUsageForAccount(services.db, services.settings, workspaceId, account.id),\n ),\n () => signalPendingCodexCapacityWakeTargets(services, workspaceId),\n );\n}\n\nexport function createCodexCapacityActivities(services: () => Promise<ActivityServices>) {\n async function getCodexCapacityWait(input: GetCodexCapacityWaitInput) {\n const { db } = await services();\n const waiter = await getCodexCapacityWaitForSession(db, input.workspaceId, input.sessionId);\n return waiter\n ? {\n waiterId: waiter.id,\n generation: waiter.generation,\n // A capacity mutation may have committed while its Temporal signal\n // was lost or while the workflow continued-as-new. Reconstruct that\n // outbox edge as an immediate re-evaluation rather than waiting for\n // the older timer.\n nextCheckAt:\n waiter.wakeRevision > waiter.observedWakeRevision\n ? new Date(0).toISOString()\n : waiter.nextCheckAt.toISOString(),\n wakeRevision: waiter.wakeRevision,\n }\n : null;\n }\n\n async function reconcileCodexCapacityWait(\n input: ReconcileCodexCapacityWaitInput,\n ): Promise<ReconcileCodexCapacityWaitResult> {\n const resolved = await services();\n const current = await getCodexCapacityWaitForSession(\n resolved.db,\n input.workspaceId,\n input.sessionId,\n );\n if (!current || current.id !== input.waiterId || current.generation !== input.generation) {\n return { action: \"stale\" };\n }\n if (input.cause === \"timer\" && current.nextCheckAt.getTime() <= Date.now()) {\n // This is a bounded secret-safe control-plane quota refresh. It creates no\n // turn, model call, user message, schedule, or entitlement action.\n await refreshCapacityMetadata(resolved, input.workspaceId);\n }\n const result = await reconcileCodexCapacityWaitDb(\n resolved.db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n waiterId: input.waiterId,\n generation: input.generation,\n },\n (context) => codexCapacityDecision(context, resolved.settings),\n );\n if (result.events.length > 0) {\n try {\n await resolved.bus.publish(input.workspaceId, input.sessionId, result.events);\n } catch {\n // Postgres is authoritative; SSE replay/gap fill repairs missed fanout.\n }\n }\n if (result.action === \"resumed\") {\n return { action: \"resumed\" };\n }\n if (result.action === \"waiting\") {\n return {\n action: \"waiting\",\n waiterId: result.waiter.id,\n generation: result.waiter.generation,\n nextCheckAt: result.waiter.nextCheckAt.toISOString(),\n wakeRevision: result.waiter.wakeRevision,\n };\n }\n return { action: result.action };\n }\n\n return { getCodexCapacityWait, reconcileCodexCapacityWait };\n}\n","import type {\n ResourceRef,\n SessionStatus,\n SessionSystemUpdatePayload,\n ToolRef,\n} from \"@opengeni/contracts\";\n\nexport {\n mergeResourceRefs,\n mergeToolRefs,\n reasoningEffortForMetadata as reasoningEffortForSession,\n} from \"@opengeni/contracts\";\n\n/**\n * Refuse to revive a terminal reusable session on a scheduled fire. Mirrors the\n * API-level guard in apps/api/src/domain/sessions.ts (post a user message ->\n * 409 when cancelled): \"cancelled\" is the one terminal state, an explicit user\n * act, so a recurring task must NOT silently resurrect and re-bill it. Failed\n * and idle sessions stay revivable (talking to a session is how it resumes), so\n * only \"cancelled\" is rejected. Throwing inside the FOR UPDATE locked-update\n * callback aborts the whole append+enqueue transaction atomically, and the\n * dispatch catch marks the scheduled_task_run \"failed\" rather than dispatched.\n */\nexport function assertReusableSessionRevivable(status: SessionStatus): void {\n if (status === \"cancelled\") {\n throw new Error(\"reusable session is cancelled; refusing to revive on scheduled fire\");\n }\n}\n\nexport function scheduledUserMessagePayload(\n prompt: string,\n resources: ResourceRef[],\n tools: ToolRef[],\n taskId: string,\n runId: string,\n): Extract<SessionSystemUpdatePayload, { type: \"scheduled_occurrence\" }> {\n return {\n type: \"scheduled_occurrence\",\n text: prompt,\n scheduledTaskId: taskId,\n scheduledTaskRunId: runId,\n ...(resources.length ? { resources } : {}),\n ...(tools.length ? { tools } : {}),\n };\n}\n\nexport function workflowIdForSession(sessionId: string): string {\n return `session-${sessionId}`;\n}\n","import {\n applyContextCompaction,\n getActiveSessionHistoryItems,\n recordSkippedContextCompaction,\n recordStartedContextCompaction,\n type Database,\n} from \"@opengeni/db\";\nimport {\n EmptyCompactionSummaryError,\n REMOTE_COMPACTION_V2_IMPLEMENTATION,\n SUMMARY_BUFFER_TOKENS,\n buildCompactionReplacementHistory,\n buildRemoteV2ReplacementHistory,\n compactionReplacementFingerprint,\n decideCompaction,\n estimateTokens,\n latestCompactionReplacementFingerprint,\n prepareCompactionPromptInput,\n sanitizeHistoryItemsForModel,\n summarizeForCompaction,\n type CompactionItem,\n} from \"@opengeni/runtime\";\nimport { contextInputBudgetTokens, type Settings } from \"@opengeni/config\";\nimport type { SessionEvent } from \"@opengeni/contracts\";\nimport { projectRejectedProviderArtifacts } from \"./run-input\";\nimport { TurnAttemptFencedError } from \"./turn-attempt-fenced\";\n\nexport type MaybeCompactResult =\n | {\n compacted: false;\n reason: string;\n events: SessionEvent[];\n requestConsumed: boolean;\n }\n | {\n compacted: true;\n supersededFrom: number;\n summaryPosition: number;\n signalTokens: number;\n thresholdTokens: number;\n estimatedTokensBefore: number;\n estimatedTokensAfter: number;\n replacementFingerprint: string;\n events: SessionEvent[];\n };\n\n/**\n * Durable context compaction.\n *\n * Portable path: Codex CLI local plaintext checkpoint for every provider and\n * for Codex sessions frozen on `portable`.\n *\n * Remote v2 path: when the session is frozen on `remote_v2` and the turn is\n * Codex, call Codex `/codex/responses` with `compaction_trigger` and persist the\n * opaque compaction item. Fail closed — never silently fall back to portable.\n */\nexport type CompactionSummarizer = (settings: Settings, input: CompactionItem[]) => Promise<string>;\n\n/** Returns the opaque Codex remote compaction v2 item. */\nexport type RemoteCompactionV2Requester = (\n settings: Settings,\n input: CompactionItem[],\n) => Promise<CompactionItem>;\n\nexport async function maybeCompactContext(\n db: Database,\n settings: Settings,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n lastInputTokens: number | null,\n // Injectable for tests; defaults to the real provider-aware model call.\n summarize: CompactionSummarizer = (s, m) =>\n summarizeForCompaction(s, m, {\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n }),\n // Operator-forced (the /compact command): bypass the budget trigger and\n // compact now if there is anything to summarize. Structural guards still hold.\n options: {\n force?: boolean;\n clearRequestedCompaction?: boolean;\n trigger?: \"auto\" | \"operator\" | \"proactive\" | \"overflow\";\n /** Frozen session mode; remote_v2 selects the Codex opaque path. */\n codexCompactionMode?: \"remote_v2\" | \"portable\";\n /** True when this turn's resolved provider is codex-subscription. */\n isCodexSubscriptionTurn?: boolean;\n /** Injected remote requester; required for the remote_v2 branch. */\n requestRemoteCompactionV2?: RemoteCompactionV2Requester;\n /**\n * Live fanout for the attempt-fenced `compaction.started` event so the\n * timeline can show progress before the provider call returns. Must never\n * append again — the event is already durable.\n */\n publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;\n /** Turn-scoped attachment/modality view; canonical persisted rows stay untouched. */\n projectModelInput?: (items: CompactionItem[]) => Promise<CompactionItem[]>;\n } = {},\n): Promise<MaybeCompactResult> {\n if (options.codexCompactionMode === \"remote_v2\" && options.isCodexSubscriptionTurn !== true) {\n // Fail closed: a V2-locked session must never silently take the portable path\n // (mixed history shapes). Admission should have blocked this already.\n throw new Error(\n \"session is locked to Codex remote compaction v2 but this turn is not a Codex subscription turn\",\n );\n }\n const useRemoteV2 = options.codexCompactionMode === \"remote_v2\";\n\n const active = await getActiveSessionHistoryItems(db, scope.workspaceId, scope.sessionId);\n if (active.length === 0) {\n let requestConsumed = false;\n if (options.clearRequestedCompaction) {\n const skipped = await recordSkippedContextCompaction(db, {\n ...scope,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n reason: \"no_history\",\n });\n if (!skipped.recorded) {\n throw new TurnAttemptFencedError(\n \"turn attempt was fenced while consuming an empty context compaction request\",\n );\n }\n requestConsumed = true;\n return {\n compacted: false,\n reason: \"no_history\",\n events: skipped.events,\n requestConsumed,\n };\n }\n return {\n compacted: false,\n reason: \"no_history\",\n events: [],\n requestConsumed,\n };\n }\n\n const canonicalItems = projectRejectedProviderArtifacts(active) as CompactionItem[];\n const projectForWire = async (input: CompactionItem[]): Promise<CompactionItem[]> =>\n sanitizeHistoryItemsForModel(\n options.projectModelInput ? await options.projectModelInput(input) : input,\n settings.modelToolOutputTruncationTokens,\n ) as CompactionItem[];\n const items = await projectForWire(canonicalItems);\n const decision = decideCompaction({\n items,\n lastInputTokens,\n contextWindowTokens: settings.contextWindowTokens,\n contextReservedOutputTokens: settings.contextReservedOutputTokens,\n contextAutoCompactThresholdTokens: settings.contextAutoCompactThresholdTokens,\n contextCompactionThresholdRatio: settings.contextCompactionThresholdRatio,\n ...(options.force ? { force: true } : {}),\n });\n if (!decision.shouldCompact) {\n return {\n compacted: false,\n reason: decision.reason,\n events: [],\n requestConsumed: false,\n };\n }\n\n const trigger = options.trigger ?? \"auto\";\n const estimatedTokensBefore = estimateTokens(items);\n const started = await recordStartedContextCompaction(db, {\n ...scope,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n trigger,\n estimatedTokensBefore,\n ...(useRemoteV2 ? { implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION } : {}),\n });\n if (!started.recorded) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced while recording context compaction start: ${started.reason}`,\n );\n }\n await options.publishLiveEvents?.(started.events);\n\n if (useRemoteV2) {\n const outcome = await compactContextRemoteV2(\n db,\n settings,\n scope,\n canonicalItems,\n items,\n decision,\n options,\n projectForWire,\n );\n return prependCompactionEvents(started.events, outcome);\n }\n\n const outcome = await compactContextPortable(\n db,\n settings,\n scope,\n canonicalItems,\n items,\n decision,\n summarize,\n options,\n projectForWire,\n );\n return prependCompactionEvents(started.events, outcome);\n}\n\n/**\n * After `compaction.started`, record a visible skip so the timeline cannot\n * stick on \"Compacting…\". Used when the provider/summarizer throws a terminal\n * (non-retryable) failure — including auto/overflow paths that never set\n * `compactRequested`.\n */\nexport async function settleFailedContextCompactionLandmark(\n db: Database,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n options: {\n clearRequestedCompaction?: boolean;\n publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;\n } = {},\n): Promise<Extract<MaybeCompactResult, { compacted: false }>> {\n const settled = await settleSkippedAfterStart(db, scope, options, \"summarization_failed\");\n await options.publishLiveEvents?.(settled.events);\n return settled;\n}\n\nfunction prependCompactionEvents(\n prefix: SessionEvent[],\n outcome: MaybeCompactResult,\n): MaybeCompactResult {\n if (prefix.length === 0) return outcome;\n return { ...outcome, events: [...prefix, ...outcome.events] };\n}\n\nasync function settleSkippedAfterStart(\n db: Database,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n options: {\n clearRequestedCompaction?: boolean;\n },\n reason:\n | \"no_history\"\n | \"replacement_not_smaller\"\n | \"replacement_unchanged\"\n | \"summarization_failed\",\n): Promise<Extract<MaybeCompactResult, { compacted: false }>> {\n const clearRequestedCompaction = options.clearRequestedCompaction === true;\n const skipped = await recordSkippedContextCompaction(db, {\n ...scope,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n reason,\n // After `compaction.started`, always settle the landmark. Do not require\n // an operator `/compact` flag — auto/overflow never set one.\n requirePendingRequest: false,\n clearRequestedCompaction,\n });\n if (!skipped.recorded) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced while recording a context compaction skip (${reason}): ${skipped.reason}`,\n );\n }\n return {\n compacted: false,\n reason,\n events: skipped.events,\n requestConsumed: clearRequestedCompaction,\n };\n}\n\nasync function compactContextRemoteV2(\n db: Database,\n settings: Settings,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n canonicalItems: CompactionItem[],\n items: CompactionItem[],\n decision: { signalTokens: number; thresholdTokens: number },\n options: {\n clearRequestedCompaction?: boolean;\n trigger?: \"auto\" | \"operator\" | \"proactive\" | \"overflow\";\n requestRemoteCompactionV2?: RemoteCompactionV2Requester;\n },\n projectForWire: (items: CompactionItem[]) => Promise<CompactionItem[]>,\n): Promise<MaybeCompactResult> {\n if (!options.requestRemoteCompactionV2) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_requester\",\n reason: \"missing_requester\",\n });\n }\n const estimatedTokensBefore = estimateTokens(items);\n // Codex remote_v2: on a valid compaction item, install and recompute usage.\n // No local \"must shrink / must differ\" gate — that is portable-only.\n // Fail closed on provider/extract failure — no portable fallback.\n const compactionItem = await options.requestRemoteCompactionV2(settings, items);\n const replacementHistory = buildRemoteV2ReplacementHistory(canonicalItems, compactionItem);\n const estimatedTokensAfter = estimateTokens(await projectForWire(replacementHistory));\n const replacementFingerprint = compactionReplacementFingerprint(replacementHistory);\n const tailItem = replacementHistory.at(-1);\n if (!tailItem) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_replacement\",\n reason: \"no_replacement_history\",\n });\n }\n const applied = await applyContextCompaction(db, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n sessionId: scope.sessionId,\n turnId: scope.turnId,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n replacementItems: replacementHistory.slice(0, -1),\n summaryItem: tailItem as Record<string, unknown>,\n ...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),\n eventPayload: {\n trigger: options.trigger ?? \"auto\",\n implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION,\n estimatedTokensBefore,\n estimatedTokensAfter,\n },\n });\n if (!applied.applied) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced during remote context compaction: ${applied.reason}`,\n );\n }\n return {\n compacted: true,\n supersededFrom: applied.supersededFrom,\n summaryPosition: applied.summaryPosition,\n signalTokens: decision.signalTokens,\n thresholdTokens: decision.thresholdTokens,\n estimatedTokensBefore,\n estimatedTokensAfter,\n replacementFingerprint,\n events: applied.events,\n };\n}\n\nasync function compactContextPortable(\n db: Database,\n settings: Settings,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n canonicalItems: CompactionItem[],\n items: CompactionItem[],\n decision: { signalTokens: number; thresholdTokens: number },\n summarize: CompactionSummarizer,\n options: {\n clearRequestedCompaction?: boolean;\n trigger?: \"auto\" | \"operator\" | \"proactive\" | \"overflow\";\n },\n projectForWire: (items: CompactionItem[]) => Promise<CompactionItem[]>,\n): Promise<MaybeCompactResult> {\n const estimatedTokensBefore = estimateTokens(items);\n const summarized = await summarizeWithCodexOverflowTrimming(summarize, settings, items);\n const summaryBody = summarized.summaryBody;\n const replacementHistory = buildCompactionReplacementHistory(canonicalItems, summaryBody);\n const estimatedTokensAfter = estimateTokens(await projectForWire(replacementHistory));\n const replacementFingerprint = compactionReplacementFingerprint(replacementHistory);\n const previousReplacementFingerprint = latestCompactionReplacementFingerprint(canonicalItems);\n const summaryItem = replacementHistory.at(-1);\n if (!summaryItem) {\n // Started already fanout; settle visibly so the landmark cannot stick on\n // \"Compacting…\". This is not an operator-request clear path.\n return await settleSkippedAfterStart(db, scope, options, \"summarization_failed\");\n }\n if (previousReplacementFingerprint === replacementFingerprint) {\n return await settleSkippedAfterStart(db, scope, options, \"replacement_unchanged\");\n }\n if (estimatedTokensAfter >= estimatedTokensBefore) {\n return await settleSkippedAfterStart(db, scope, options, \"replacement_not_smaller\");\n }\n const applied = await applyContextCompaction(db, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n sessionId: scope.sessionId,\n turnId: scope.turnId,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n replacementItems: replacementHistory.slice(0, -1),\n summaryItem: summaryItem as Record<string, unknown>,\n ...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),\n eventPayload: {\n trigger: options.trigger ?? \"auto\",\n estimatedTokensBefore,\n estimatedTokensAfter,\n compactionInputEstimatedTokens: summarized.preparation.estimatedInputTokens,\n compactionInputToolOutputsRewritten: summarized.preparation.rewrittenToolOutputs,\n compactionInputHistoryItemsDropped: summarized.preparation.droppedHistoryItems,\n compactionInputProviderCalls: summarized.providerCalls,\n },\n });\n if (!applied.applied) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced during context compaction: ${applied.reason}`,\n );\n }\n\n return {\n compacted: true,\n supersededFrom: applied.supersededFrom,\n summaryPosition: applied.summaryPosition,\n signalTokens: decision.signalTokens,\n thresholdTokens: decision.thresholdTokens,\n estimatedTokensBefore,\n estimatedTokensAfter,\n replacementFingerprint,\n events: applied.events,\n };\n}\n\nasync function summarizeWithCodexOverflowTrimming(\n summarize: CompactionSummarizer,\n settings: Settings,\n activeHistory: CompactionItem[],\n): Promise<{\n summaryBody: string;\n preparation: ReturnType<typeof prepareCompactionPromptInput>;\n providerCalls: number;\n}> {\n // Codex's estimator is intentionally coarse. Keep the explicit checkpoint\n // request below both the effective input window and the raw window minus the\n // requested summary, then leave 15% estimator headroom. This changes only the\n // temporary summarizer input; durable active history remains untouched until\n // applyContextCompaction succeeds under the attempt fence.\n const summaryAwareBudget = Math.max(0, settings.contextWindowTokens - SUMMARY_BUFFER_TOKENS);\n const configuredInputBudget = contextInputBudgetTokens(settings);\n const structuralBudget = Math.min(\n configuredInputBudget > 0 ? configuredInputBudget : summaryAwareBudget,\n summaryAwareBudget,\n );\n const initialBudget = Math.floor(structuralBudget * 0.85);\n let preparation = prepareCompactionPromptInput(activeHistory, initialBudget);\n try {\n return {\n summaryBody: await summarize(settings, preparation.input),\n preparation,\n providerCalls: 1,\n };\n } catch (error) {\n if (!isContextWindowExceeded(error)) throw error;\n // The provider is more authoritative than the byte/4 estimate. Refit once\n // to 70% of both the configured target and the actual prepared estimate;\n // then fail terminally with prior history intact. Never issue one failing\n // request per oldest item. The production incident proved that the\n // provider can count slightly more than twice the byte/4 estimate, so a\n // half-size retry is the smallest honest bound for that observed skew.\n const retryBudget = Math.floor(\n Math.min(initialBudget * 0.5, preparation.estimatedInputTokens * 0.5),\n );\n preparation = prepareCompactionPromptInput(activeHistory, retryBudget);\n return {\n summaryBody: await summarize(settings, preparation.input),\n preparation,\n providerCalls: 2,\n };\n }\n}\n\nexport function isContextWindowExceeded(error: unknown, seen = new WeakSet<object>()): boolean {\n if (!error || typeof error !== \"object\") return false;\n if (seen.has(error)) return false;\n seen.add(error);\n const record = error as Record<string, unknown>;\n const code = typeof record.code === \"string\" ? record.code.toLowerCase() : \"\";\n const message =\n typeof record.message === \"string\"\n ? record.message.toLowerCase()\n : error instanceof Error\n ? error.message.toLowerCase()\n : \"\";\n const direct =\n code === \"context_length_exceeded\" ||\n code === \"context_window_exceeded\" ||\n message.includes(\"context window\") ||\n message.includes(\"maximum context length\") ||\n message.includes(\"too many tokens\");\n return (\n direct ||\n isContextWindowExceeded(record.cause, seen) ||\n isContextWindowExceeded(record.error, seen) ||\n isContextWindowExceeded(record.diagnostics, seen)\n );\n}\n","import {\n MODEL_ATTACHMENT_REFS_FIELD,\n FileResourceRef,\n resourceMountPath,\n type FileAsset,\n type ResourceRef,\n} from \"@opengeni/contracts\";\nimport { createHash } from \"node:crypto\";\nimport {\n getActiveSessionHistoryItems,\n getFiles,\n getLatestRunState,\n getHumanInputResumeForEvent,\n getSandboxSessionEnvelope,\n getSessionEvent,\n listSessionSystemUpdatesForTurn,\n requireFile,\n type Database,\n} from \"@opengeni/db\";\nimport {\n projectHistoryForProvider,\n projectRejectedProviderArtifactsFromSerializedRunState,\n projectRejectedReasoningArtifact,\n hasOpaqueProviderArtifact,\n type HistoryProviderApi,\n type OpenGeniRuntime,\n} from \"@opengeni/runtime\";\n\n/** Project only artifacts explicitly rejected by the provider out of its next view. */\nexport function projectRejectedProviderArtifacts(\n rows: ReadonlyArray<{\n item: Record<string, unknown>;\n providerArtifactInvalidatedAt?: Date | null;\n }>,\n): Array<Record<string, unknown>> {\n const out: Array<Record<string, unknown>> = [];\n for (const row of rows) {\n if (!row.providerArtifactInvalidatedAt) {\n out.push(row.item);\n continue;\n }\n const type = typeof row.item.type === \"string\" ? row.item.type : undefined;\n if (type === \"reasoning\") {\n out.push(projectRejectedReasoningArtifact(row.item));\n continue;\n }\n if (type === \"compaction\") {\n continue;\n }\n out.push(row.item);\n }\n return out;\n}\n\n/** Build the attempt-local RunState view after an explicit provider rejection. */\nexport function resumeRunState(state: {\n serializedRunState: string;\n providerArtifactInvalidatedAt?: Date | null;\n}): string {\n if (!state.providerArtifactInvalidatedAt) {\n return state.serializedRunState;\n }\n return projectRejectedProviderArtifactsFromSerializedRunState(state.serializedRunState);\n}\n\n/** Prepared input and its exact durable-history prefix length for reconciliation. */\nexport type PreparedTurnInput = {\n input: Awaited<ReturnType<OpenGeniRuntime[\"prepareInput\"]>>;\n persistedHistoryCount: number;\n providerArtifactCandidates: {\n knownHistoryItemIds: string[];\n historyItemIds: string[];\n runStateId?: string;\n };\n};\n\nexport type TurnInputOptions = {\n turnId: string;\n recovering?: boolean;\n unavailableSandboxFilesNote?: string;\n runCredentialsNote?: string;\n providerApi: HistoryProviderApi;\n projectModelHistory?: ModelHistoryAttachmentProjector;\n};\n\nexport const MAX_INLINE_MODEL_ATTACHMENT_BYTES = 20 * 1024 * 1024;\n\nexport type ModelAttachmentContent = {\n kind: \"image\" | \"file\";\n fileId: string;\n filename: string;\n contentType: string;\n dataUrl: string;\n};\n\nexport type ModelHistoryAttachmentProjector = (\n items: Array<Record<string, unknown>>,\n) => Promise<Array<Record<string, unknown>>>;\n\nexport type ModelAttachmentInputPolicy = {\n supportsImageInput: boolean;\n inputFileMediaTypes: readonly string[];\n};\n\nconst MODEL_IMAGE_CONTENT_TYPES = new Set([\"image/gif\", \"image/jpeg\", \"image/png\", \"image/webp\"]);\n\nconst MODEL_FILE_CONTENT_TYPES = new Set([\n \"application/json\",\n \"application/pdf\",\n \"application/x-yaml\",\n \"application/yaml\",\n]);\n\n// Generic XML has equivalent application/* and text/* registrations. Keep both\n// aliases on the sandbox-path fallback until a provider parser boundary is\n// explicitly supported and verified; MIME spelling must not bypass the fence.\nconst BLOCKED_TEXT_CONTENT_TYPES = new Set([\n \"text/css\",\n \"text/html\",\n \"text/javascript\",\n \"text/xml\",\n]);\n\nfunction safeErrorType(error: unknown): string {\n if (!(error instanceof Error)) return typeof error;\n const name = error.name.trim();\n return /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(name) ? name : \"Error\";\n}\n\nfunction modelAttachmentDescriptor(\n contentType: string,\n): Pick<ModelAttachmentContent, \"kind\" | \"contentType\"> | null {\n const normalized = contentType.toLowerCase().split(\";\", 1)[0]?.trim() ?? \"\";\n if (MODEL_IMAGE_CONTENT_TYPES.has(normalized)) {\n return { kind: \"image\", contentType: normalized };\n }\n if (\n MODEL_FILE_CONTENT_TYPES.has(normalized) ||\n (normalized.startsWith(\"text/\") && !BLOCKED_TEXT_CONTENT_TYPES.has(normalized))\n ) {\n return { kind: \"file\", contentType: normalized };\n }\n return null;\n}\n\nexport async function modelAttachmentContentForFiles(\n files: FileAsset[],\n readFileBytes: (file: FileAsset) => Promise<Uint8Array>,\n): Promise<ModelAttachmentContent[]> {\n const selected: Array<{\n file: FileAsset;\n descriptor: Pick<ModelAttachmentContent, \"kind\" | \"contentType\">;\n checksum: string;\n }> = [];\n let remainingBytes = MAX_INLINE_MODEL_ATTACHMENT_BYTES;\n for (const file of files) {\n const descriptor = modelAttachmentDescriptor(file.contentType);\n const checksum = file.sha256?.trim().toLowerCase() ?? \"\";\n if (\n file.status !== \"ready\" ||\n !descriptor ||\n file.sizeBytes > remainingBytes ||\n !/^[a-f0-9]{64}$/.test(checksum)\n ) {\n continue;\n }\n selected.push({ file, descriptor, checksum });\n remainingBytes -= file.sizeBytes;\n }\n\n const attachments = new Array<ModelAttachmentContent | undefined>(selected.length);\n let cursor = 0;\n const worker = async () => {\n while (cursor < selected.length) {\n const index = cursor++;\n const { file, descriptor, checksum } = selected[index]!;\n try {\n const bytes = await readFileBytes(file);\n if (bytes.byteLength !== file.sizeBytes) {\n console.error(\"model attachment bytes did not match finalized metadata\", {\n fileId: file.id,\n expectedSizeBytes: file.sizeBytes,\n actualSizeBytes: bytes.byteLength,\n });\n continue;\n }\n if (createHash(\"sha256\").update(bytes).digest(\"hex\") !== checksum) {\n console.error(\"model attachment checksum did not match finalized metadata\", {\n fileId: file.id,\n });\n continue;\n }\n attachments[index] = {\n kind: descriptor.kind,\n fileId: file.id,\n filename: file.safeFilename,\n contentType: descriptor.contentType,\n dataUrl: `data:${descriptor.contentType};base64,${Buffer.from(bytes).toString(\"base64\")}`,\n };\n } catch (error) {\n // The sandbox-path projection remains available for every file. A direct\n // provider-content read is an additive fast path and must not turn a\n // transient storage read into loss of the accepted prompt.\n console.error(\"model attachment content read failed; retaining sandbox path fallback\", {\n fileId: file.id,\n errorType: safeErrorType(error),\n });\n }\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(8, selected.length) }, async () => await worker()),\n );\n return attachments.filter(\n (attachment): attachment is ModelAttachmentContent => attachment !== undefined,\n );\n}\n\nfunction modelAcceptsFileMediaType(\n policy: ModelAttachmentInputPolicy,\n contentType: string,\n): boolean {\n const normalized = contentType.toLowerCase().split(\";\", 1)[0]?.trim() ?? \"\";\n return policy.inputFileMediaTypes.some(\n (accepted) =>\n accepted === normalized ||\n (accepted.endsWith(\"/*\") && normalized.startsWith(accepted.slice(0, -1))),\n );\n}\n\nfunction attachmentRefsFromItem(item: Record<string, unknown>): FileResourceRef[] {\n const raw = item[MODEL_ATTACHMENT_REFS_FIELD];\n if (!Array.isArray(raw)) return [];\n const refs: FileResourceRef[] = [];\n for (const candidate of raw) {\n const parsed = FileResourceRef.safeParse(candidate);\n if (parsed.success) refs.push(parsed.data);\n }\n return refs;\n}\n\nfunction attachmentUnavailableText(ref: FileResourceRef, file: FileAsset | undefined): string {\n const filename = file?.safeFilename ?? ref.fileId;\n const mediaType = file?.contentType ?? \"unknown type\";\n const path = file ? sandboxFilePath(ref, file) : `/workspace/${resourceMountPath(ref)}`;\n return (\n `[Attachment not included directly because the selected model does not accept this input ` +\n `or it exceeded the safe inline limit: ${filename} (${mediaType}). ` +\n `It remains available to tools in the sandbox at ${path}.]`\n );\n}\n\n/**\n * Build one turn-scoped durable-attachment projector. Metadata is batch-loaded\n * and file bytes are memoized, so compaction/retry can reuse the same work and\n * the SDK's repeated tool loop never touches storage or rescans old history.\n */\nexport function createModelHistoryAttachmentProjector(\n db: Database,\n workspaceId: string,\n policy: ModelAttachmentInputPolicy,\n readFileBytes?: (file: FileAsset) => Promise<Uint8Array>,\n): ModelHistoryAttachmentProjector {\n const fileById = new Map<string, FileAsset>();\n const missingFileIds = new Set<string>();\n const contentById = new Map<string, ModelAttachmentContent>();\n const attemptedContentIds = new Set<string>();\n\n return async (items) => {\n const refsByIndex = new Map<number, FileResourceRef[]>();\n const orderedFileIds: string[] = [];\n const seenFileIds = new Set<string>();\n for (let index = 0; index < items.length; index += 1) {\n const refs = attachmentRefsFromItem(items[index]!);\n if (refs.length === 0) continue;\n refsByIndex.set(index, refs);\n for (const ref of refs) {\n if (seenFileIds.has(ref.fileId)) continue;\n seenFileIds.add(ref.fileId);\n orderedFileIds.push(ref.fileId);\n }\n }\n if (refsByIndex.size === 0) return items;\n\n const unknownIds = orderedFileIds.filter((id) => !fileById.has(id) && !missingFileIds.has(id));\n if (unknownIds.length > 0) {\n const files = await getFiles(db, workspaceId, unknownIds);\n for (const file of files) fileById.set(file.id, file);\n for (const id of unknownIds) {\n if (!fileById.has(id)) missingFileIds.add(id);\n }\n }\n\n if (readFileBytes) {\n // Prefer the newest attachments if the aggregate request safety limit is\n // reached; an old image becomes a marker instead of hiding the new prompt.\n const readable = [...orderedFileIds]\n .reverse()\n .map((id) => fileById.get(id))\n .filter((file): file is FileAsset => {\n if (!file || attemptedContentIds.has(file.id)) return false;\n const descriptor = modelAttachmentDescriptor(file.contentType);\n return Boolean(\n descriptor &&\n ((descriptor.kind === \"image\" && policy.supportsImageInput) ||\n (descriptor.kind === \"file\" && modelAcceptsFileMediaType(policy, file.contentType))),\n );\n });\n for (const file of readable) attemptedContentIds.add(file.id);\n const content = await modelAttachmentContentForFiles(readable, readFileBytes);\n for (const attachment of content) contentById.set(attachment.fileId, attachment);\n }\n\n const projected = [...items];\n for (const [index, refs] of refsByIndex) {\n const original = items[index]!;\n const existingContent = Array.isArray(original.content)\n ? [...original.content]\n : [{ type: \"input_text\", text: String(original.content ?? \"\") }];\n const attachmentParts = refs.map((ref) => {\n const attachment = contentById.get(ref.fileId);\n if (!attachment) {\n return {\n type: \"input_text\",\n text: attachmentUnavailableText(ref, fileById.get(ref.fileId)),\n };\n }\n return attachment.kind === \"image\"\n ? { type: \"input_image\", image: attachment.dataUrl }\n : {\n type: \"input_file\",\n file: attachment.dataUrl,\n filename: attachment.filename,\n };\n });\n const clone: Record<string, unknown> = {\n ...original,\n content: [...existingContent, ...attachmentParts],\n };\n delete clone[MODEL_ATTACHMENT_REFS_FIELD];\n projected[index] = clone;\n }\n return projected;\n };\n}\n\n/** Add current trigger refs only when older/local history predates durable stamping. */\nexport function withCurrentUserAttachmentRefs(\n historyItems: Array<Record<string, unknown>>,\n refs: FileResourceRef[],\n): Array<Record<string, unknown>> {\n if (refs.length === 0) return historyItems;\n for (let index = historyItems.length - 1; index >= 0; index -= 1) {\n const item = historyItems[index]!;\n if (item.type !== \"message\" || item.role !== \"user\") continue;\n const existing = attachmentRefsFromItem(item);\n const existingIds = new Set(existing.map((ref) => ref.fileId));\n const additions = refs.filter((ref) => !existingIds.has(ref.fileId));\n if (additions.length === 0) return historyItems;\n const projected = [...historyItems];\n projected[index] = { ...item, [MODEL_ATTACHMENT_REFS_FIELD]: [...existing, ...additions] };\n return projected;\n }\n return historyItems;\n}\n\nexport async function turnInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: Awaited<ReturnType<typeof getSessionEvent>>,\n options: TurnInputOptions,\n): Promise<PreparedTurnInput> {\n if (!trigger) {\n throw new Error(\"Missing trigger event\");\n }\n const updates = await listSessionSystemUpdatesForTurn(\n db,\n trigger.workspaceId,\n trigger.sessionId,\n options.turnId,\n );\n if (updates.length > 0) {\n const historyItemIds = new Set(\n updates.map((update) => update.deliveredHistoryItemId).filter(Boolean),\n );\n if (historyItemIds.size !== 1 || updates.some((update) => !update.deliveredHistoryItemId)) {\n throw new Error(\"Delivered internal updates have no single durable model-memory batch\");\n }\n }\n const internalContext = joinInternalContext(\n options.recovering\n ? [\n \"[OpenGeni inference recovery]\",\n \"Continue the same inference from durable conversation and sandbox state. A previous execution stopped before it could finish. Do not repeat completed side effects; inspect actual state when uncertain.\",\n ].join(\"\\n\")\n : undefined,\n options.unavailableSandboxFilesNote,\n options.runCredentialsNote,\n );\n if (trigger.type === \"user.message\") {\n const payload = trigger.payload as { text?: unknown; resources?: unknown };\n if (typeof payload.text !== \"string\" || payload.text.trim().length === 0) {\n throw new Error(\"user.message payload is missing text\");\n }\n const resources = Array.isArray(payload.resources) ? (payload.resources as ResourceRef[]) : [];\n const fileAttachments = await resolveUserMessageFileAttachments(\n db,\n trigger.workspaceId,\n resources,\n );\n const attachmentContext = userMessageAttachmentsContext(fileAttachments);\n return await messageInput(\n db,\n runtime,\n agent,\n trigger,\n undefined,\n joinInternalContext(internalContext, attachmentContext),\n fileAttachments.map((attachment) => attachment.resource),\n options.providerApi,\n options.projectModelHistory,\n );\n }\n if (trigger.type === \"system.update.delivered\") {\n if (updates.length === 0) {\n throw new Error(\"Internal update inference has no delivered updates\");\n }\n return await messageInput(\n db,\n runtime,\n agent,\n trigger,\n undefined,\n internalContext,\n [],\n options.providerApi,\n options.projectModelHistory,\n );\n }\n if (trigger.type === \"user.approvalDecision\") {\n const payload = trigger.payload as {\n approvalId?: unknown;\n decision?: unknown;\n message?: unknown;\n };\n // Approvals are the one path that legitimately requires the RunState blob:\n // a turn frozen mid-flight cannot be represented as plain history items.\n const state = await getLatestRunState(db, trigger.workspaceId, trigger.sessionId);\n if (!state) {\n throw new Error(\"No saved run state is available for approval decision\");\n }\n const prepared = await runtime.prepareInput(agent, {\n kind: \"approval\",\n serializedRunState: resumeRunState(state),\n approvalId: String(payload.approvalId ?? \"\"),\n decision: payload.decision === \"approve\" ? \"approve\" : \"reject\",\n ...(typeof payload.message === \"string\" ? { message: payload.message } : {}),\n });\n return {\n input: prepared,\n persistedHistoryCount: prepared.persistedHistoryCount,\n providerArtifactCandidates: {\n knownHistoryItemIds: [],\n historyItemIds: [],\n runStateId: state.id,\n },\n };\n }\n if (trigger.type === \"user.humanInputResponse\") {\n const [state, resume] = await Promise.all([\n getLatestRunState(db, trigger.workspaceId, trigger.sessionId),\n getHumanInputResumeForEvent(db, trigger.workspaceId, trigger.sessionId, trigger),\n ]);\n if (!state) {\n throw new Error(\"No saved run state is available for human-input response\");\n }\n if (!resume) {\n throw new Error(\"Human-input response does not resolve to a durable request\");\n }\n const prepared = await runtime.prepareInput(agent, {\n kind: \"human_input\",\n serializedRunState: resumeRunState(state),\n toolCallId: resume.toolCallId,\n });\n return {\n input: prepared,\n persistedHistoryCount: prepared.persistedHistoryCount,\n providerArtifactCandidates: {\n knownHistoryItemIds: [],\n historyItemIds: [],\n runStateId: state.id,\n },\n };\n }\n throw new Error(`Unsupported trigger event type: ${trigger.type}`);\n}\n\nfunction joinInternalContext(...parts: Array<string | undefined>): string | undefined {\n const content = parts.map((part) => part?.trim()).filter((part): part is string => Boolean(part));\n return content.length > 0 ? content.join(\"\\n\\n\") : undefined;\n}\n\n/** Build one inference from canonical history plus attempt-local operational context. */\nasync function messageInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: NonNullable<Awaited<ReturnType<typeof getSessionEvent>>>,\n text: string | undefined,\n internalContext: string | undefined,\n currentAttachmentRefs: FileResourceRef[] = [],\n providerApi: HistoryProviderApi = \"responses\",\n projectModelHistory?: ModelHistoryAttachmentProjector,\n): Promise<PreparedTurnInput> {\n const stored = await getActiveSessionHistoryItems(db, trigger.workspaceId, trigger.sessionId);\n const envelope = await getSandboxSessionEnvelope(db, trigger.workspaceId, trigger.sessionId);\n const canonicalView = projectRejectedProviderArtifacts(stored);\n const providerView = projectHistoryForProvider(canonicalView, providerApi);\n const referencedHistory = withCurrentUserAttachmentRefs(providerView, currentAttachmentRefs);\n const historyItems = projectModelHistory\n ? await projectModelHistory(referencedHistory)\n : referencedHistory;\n const prepared = await runtime.prepareInput(agent, {\n kind: \"message\",\n ...(text ? { text } : {}),\n ...(internalContext ? { internalContext } : {}),\n historyItems: historyItems as any,\n sandboxEnvelope: envelope,\n ...(projectModelHistory ? { modelInputAlreadyProjected: true } : {}),\n });\n const preparedItems = Array.isArray(prepared.input)\n ? new Set(prepared.input)\n : new Set<unknown>();\n return {\n input: prepared,\n persistedHistoryCount: prepared.persistedHistoryCount,\n providerArtifactCandidates: {\n knownHistoryItemIds: stored.map((row) => row.id),\n historyItemIds: stored\n .filter(\n (row) =>\n row.providerArtifactInvalidatedAt === null &&\n hasOpaqueProviderArtifact(row.item) &&\n preparedItems.has(row.item),\n )\n .map((row) => row.id),\n },\n };\n}\n\nexport async function userMessageTextWithAttachments(\n db: Database,\n workspaceId: string,\n text: string,\n resources: ResourceRef[],\n): Promise<string> {\n const fileAttachments = await resolveUserMessageFileAttachments(db, workspaceId, resources);\n const attachmentContext = userMessageAttachmentsContext(fileAttachments);\n return attachmentContext ? [text, \"\", attachmentContext].join(\"\\n\") : text;\n}\n\ntype UserMessageFileAttachment = {\n resource: Extract<ResourceRef, { kind: \"file\" }>;\n file: FileAsset;\n};\n\nasync function resolveUserMessageFileAttachments(\n db: Database,\n workspaceId: string,\n resources: ResourceRef[],\n): Promise<UserMessageFileAttachment[]> {\n const attachments: UserMessageFileAttachment[] = [];\n for (const resource of resources) {\n if (resource.kind !== \"file\") continue;\n const file = await requireFile(db, workspaceId, resource.fileId);\n attachments.push({ resource, file });\n }\n return attachments;\n}\n\nfunction userMessageAttachmentsContext(\n attachments: UserMessageFileAttachment[],\n): string | undefined {\n const attachedFiles = attachments.map(\n ({ resource, file }) =>\n `- ${file.filename} (${file.contentType}, ${file.sizeBytes} bytes): ${sandboxFilePath(resource, file)}`,\n );\n if (attachedFiles.length === 0) {\n return undefined;\n }\n return [\"Attached files are available in the sandbox:\", ...attachedFiles].join(\"\\n\");\n}\n\nfunction sandboxFilePath(\n resource: Extract<ResourceRef, { kind: \"file\" }>,\n file: FileAsset,\n): string {\n return `/workspace/${resourceMountPath(resource)}/${file.safeFilename}`;\n}\n","import {\n applyGitAuthPointerEnvironment,\n firstPartyMcpWorkspaceUrl,\n stableSandboxEnvironmentForRun,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n gitCredentialBindingIdForRepository,\n gitCredentialProviderForRepository,\n signDelegatedAccessToken,\n type ConnectionCredentialsPort,\n type GitCredentialProvider,\n type GitCredentialRepositoryRef,\n type GitCredentialTransport,\n type GitCredentials,\n type ResourceRef,\n type SandboxSecrets,\n type SessionTurn,\n type TurnInitiator,\n type TurnInitiatorContext,\n} from \"@opengeni/contracts\";\nimport {\n loadVariableSetForRun as loadWorkspaceEnvironmentForRunFromDb,\n type Database,\n type VariableSetForRun as WorkspaceEnvironmentForRun,\n} from \"@opengeni/db\";\nimport { createGitHubAppInstallationTokenWithExpiry, githubAppBotIdentity } from \"@opengeni/github\";\n\n// Re-exported from the shared @opengeni/db leaf (moved there so the API-direct\n// attach paths can load the SAME decrypted workspace environment the turn\n// declares — keeping the box-manifest env and agent-manifest env identical).\n// Existing worker import sites (agent-turn) continue importing from here.\nexport {\n loadWorkspaceEnvironmentForRunFromDb as loadWorkspaceEnvironmentForRun,\n type WorkspaceEnvironmentForRun,\n};\n\n// §7.6 connection-credential provider — the run's workspace identity, threaded so the connection-credential\n// provider can be called with the run's tenant context AND so the workspace-scope cross-check\n// cross-check has the run's workspace to assert the provider's echo against.\nexport type ConnectionScope = {\n accountId: string;\n workspaceId: string;\n};\n\nexport type GitTokenSeeds = Partial<Record<GitCredentialProvider, string>>;\nexport type GitTokenExpiries = Partial<Record<GitCredentialProvider, string>>;\nexport type GitCredentialBindingSeed = {\n credentialBindingId: string;\n provider: GitCredentialProvider;\n token: string;\n transport?: GitCredentialTransport;\n expiresAt?: string;\n providerBindingCount?: number;\n};\nexport type MintedRunGitCredentials = {\n bindings: GitCredentialBindingSeed[];\n // Compatibility views exist only when a provider has exactly one binding.\n // A multi-binding provider intentionally has no provider-level alias.\n gitTokens: GitTokenSeeds;\n expiresAt: GitTokenExpiries;\n};\n\nexport type GitHubTokenMintAuthorization = (selection: {\n installationId: number;\n repositoryIds: number[];\n}) => Promise<void>;\n\nexport const TOOLSPACE_TOKEN_TTL_SECONDS = 60 * 60;\n\nexport type MintedSandboxToolspaceToken = {\n token: string;\n expiresAt: Date;\n};\n\nexport type SandboxToolspaceAuthority = {\n sessionId: string;\n};\n\nexport async function mintSandboxToolspaceToken(\n settings: Settings,\n scope: ConnectionScope,\n authority: SandboxToolspaceAuthority,\n nowMs = Date.now(),\n): Promise<MintedSandboxToolspaceToken | undefined> {\n if (!settings.toolspaceEnabled || !settings.delegationSecret) {\n return undefined;\n }\n const expiresAtSeconds = Math.floor(nowMs / 1000) + TOOLSPACE_TOKEN_TTL_SECONDS;\n const token = await signDelegatedAccessToken(settings.delegationSecret, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n subjectId: `sandbox:${authority.sessionId}`,\n subjectLabel: \"sandbox toolspace\",\n permissions: [\"toolspace:call\"],\n sessionId: authority.sessionId,\n principalKind: \"service\",\n exp: expiresAtSeconds,\n });\n return { token, expiresAt: new Date(expiresAtSeconds * 1000) };\n}\n\nexport type GitCredentialAuthority = {\n sessionId: string;\n rootSessionId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n initiator: TurnInitiator;\n initiatorContext: TurnInitiatorContext;\n};\n\nexport function gitCredentialAuthorityForTurn(input: {\n sessionId: string;\n rootSessionId: string;\n attemptId: string;\n turn: Pick<SessionTurn, \"id\" | \"executionGeneration\" | \"initiator\" | \"initiatorContext\">;\n}): GitCredentialAuthority {\n return {\n sessionId: input.sessionId,\n rootSessionId: input.rootSessionId,\n turnId: input.turn.id,\n attemptId: input.attemptId,\n executionGeneration: input.turn.executionGeneration,\n initiator: input.turn.initiator,\n initiatorContext: input.turn.initiatorContext,\n };\n}\n\ntype RunGitCredentialOptions = {\n scope?: ConnectionScope;\n authority?: GitCredentialAuthority;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n authorizeGitHubTokenMint?: GitHubTokenMintAuthorization;\n};\n\n// §7.6 connection-credential provider — load the run's workspace environment, delegating the DECRYPT to a\n// host `sandboxSecrets` provider when one is bound (the host owns the secret\n// vault + encryption key in embedded/separate topologies) and otherwise running\n// today's local `environmentsEncryptionKeyBytes`-keyed decrypt byte-for-byte.\n//\n// Unattached runs (environmentId === null) short-circuit identically in BOTH\n// modes: zero DB/provider work, returns null. When a provider IS bound it owns\n// the decrypt end-to-end (it reads the host's own store), so the local DB read\n// is skipped — the provider is the sole source of truth for that leg.\nexport async function loadWorkspaceEnvironmentForRunWithCredentials(\n db: Database,\n settings: Settings,\n scope: ConnectionScope,\n environmentId: string | null,\n sandboxSecrets?: ConnectionCredentialsPort[\"sandboxSecrets\"],\n): Promise<WorkspaceEnvironmentForRun | null> {\n if (!sandboxSecrets) {\n // Standalone default: today's local decrypt, unchanged.\n return loadWorkspaceEnvironmentForRunFromDb(db, settings, scope.workspaceId, environmentId);\n }\n if (!environmentId) {\n return null;\n }\n const secrets: SandboxSecrets = await sandboxSecrets({\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n variableSetId: environmentId,\n });\n // workspace-scope cross-check: the provider must echo THIS run's workspace before we apply its\n // decrypted values into the sandbox.\n assertWorkspaceEcho(\"sandboxSecrets\", scope, secrets.workspaceId);\n return {\n id: secrets.id ?? environmentId,\n name: secrets.name ?? environmentId,\n description: secrets.description ?? null,\n values: secrets.values,\n };\n}\n\n// Workspace-scope cross-check. A credential provider echoes the workspace it scoped\n// the credential to; we ASSERT it equals the run's workspace BEFORE the caller\n// injects the credential. A host mapping bug returning tenant B's creds for a\n// tenant-A run hard-throws here instead of landing tenant B's token in tenant\n// A's sandbox. Account/workspace ids only in the message (never the credential).\nfunction assertWorkspaceEcho(\n kind: string,\n scope: ConnectionScope,\n echoedWorkspaceId: string,\n): void {\n if (echoedWorkspaceId !== scope.workspaceId) {\n throw new Error(\n `connection-credential provider (${kind}) scoped to workspace ${echoedWorkspaceId} but the run is workspace ${scope.workspaceId}`,\n );\n }\n}\n\nexport async function sandboxEnvironmentForRun(\n settings: Settings,\n resources: ResourceRef[],\n workspaceEnvironment: Record<string, string> = {},\n // §7.6 connection-credential provider - optional host git-credential provider + the run scope it needs\n // (unset, the standalone default → self-mint from `settings` byte-for-byte).\n // `skipGitHubToken` (Stage D): a connected-machine turn skips the inert platform\n // token mint entirely and returns the stable base env unchanged. `deferGitHubToken`\n // is the lazy CLOUD path: apply stable git-auth pointers now, mint only the token\n // value later. `= {}` default so the non-optional reads below are safe.\n options: RunGitCredentialOptions & {\n skipGitHubToken?: boolean;\n deferGitHubToken?: boolean;\n toolspaceAuthority?: SandboxToolspaceAuthority;\n } = {},\n): Promise<{\n environment: Record<string, string>;\n gitToken?: string;\n gitTokens?: GitTokenSeeds;\n gitTokenExpiresAt?: GitTokenExpiries;\n gitCredentialBindings?: GitCredentialBindingSeed[];\n toolspaceToken?: string;\n toolspaceTokenExpiresAt?: Date;\n}> {\n // Precedence: deployment allowlist < git identity < workspace environment\n // < backend-aware HOME (the STABLE base, shared with the API-direct attach\n // paths via stableSandboxEnvironmentForRun) < platform run-scoped git auth\n // (applied below, always last). Reserved name validation at write time prevents\n // workspace values from colliding with the platform-managed entries.\n //\n // TOKEN-BROKER (B1): run-scoped git provider tokens are NO LONGER layered into\n // the box/agent MANIFEST env (no GH_TOKEN/GITHUB_TOKEN/GITLAB_TOKEN/\n // AZURE_DEVOPS_EXT_PAT/GIT_CONFIG_* extraheader). They are minted once per turn\n // and returned separately as provider token seeds; the caller threads them\n // OFF-MANIFEST as clone-seed exec env vars so the clone hook writes stable token\n // files. The manifest carries only stable pointers (GIT_ASKPASS,\n // GIT_TERMINAL_PROMPT, identity, OPENGENI_GIT_CREDENTIALS_DIR, and\n // OPENGENI_GIT_TOKEN_FILE), so token VALUES never ride the manifest and the SDK's\n // per-turn provided-session env delta stays empty even though tokens rotate.\n // GitHub keeps the legacy `gitToken`/OPENGENI_GIT_TOKEN_FILE alias. The worker\n // proactively renews every selected provider behind these stable pointers.\n const stableOptions = options.scope ? { workspaceId: options.scope.workspaceId } : {};\n const environment = stableSandboxEnvironmentForRun(settings, workspaceEnvironment, stableOptions);\n // TOOLSPACE (selfhosted parity): the toolspace token is minted for EVERY\n // backend, including a connected machine. Unlike platform git provider tokens\n // (inert on selfhosted → skipped above), the toolspace token is the machine's\n // only path to programmatic tool calling, and it grants no more than the\n // machine owner's own authority (toolspace:call, own-session-bound,\n // short-lived and renewable, per-active-turn budgeted, approval-tools\n // excluded). Delivery mirrors the docker path: the caller threads it\n // OFF-MANIFEST as the seed the runtime writes to\n // $OPENGENI_TOOLSPACE_TOKEN_FILE over the box's exec channel.\n const toolspaceScope = options.scope;\n const toolspaceToken =\n toolspaceScope && options.toolspaceAuthority\n ? await mintSandboxToolspaceToken(settings, toolspaceScope, options.toolspaceAuthority)\n : undefined;\n if (toolspaceToken && toolspaceScope) {\n environment.OPENGENI_TOOLSPACE_URL ??= firstPartyMcpWorkspaceUrl(\n settings,\n toolspaceScope.workspaceId,\n );\n }\n const selections = gitCredentialSelections(resources);\n // NO-TOKEN SKIP (Stage D, change B): when the turn's EFFECTIVE compute backend is\n // a connected machine (selfhosted), platform git provider tokens are INERT: exec\n // routes over NATS to the user's machine, which uses ITS OWN git credentials, and\n // the box those tokens would auth is never created. So skip the token mint entirely\n // and return the STABLE base env (no gitToken/gitTokens). Env-\n // parity holds: the SAME base object still feeds buildManifest + the SelfhostedSession\n // manifest, so the SDK's per-turn provided-session env delta stays empty\n // (validateNoEnvironmentDelta). The API-direct viewer attach path already drops the\n // token under this exact contract — proof a box runs fine without it.\n if (selections.length === 0 || options.skipGitHubToken) {\n return {\n environment,\n ...(toolspaceToken\n ? {\n toolspaceToken: toolspaceToken.token,\n toolspaceTokenExpiresAt: toolspaceToken.expiresAt,\n }\n : {}),\n };\n }\n if (options.deferGitHubToken) {\n applyGitAuthPointerEnvironment(\n environment,\n await resolveRunGitIdentityWithSelections(settings, selections, options),\n );\n return {\n environment,\n ...(toolspaceToken\n ? {\n toolspaceToken: toolspaceToken.token,\n toolspaceTokenExpiresAt: toolspaceToken.expiresAt,\n }\n : {}),\n };\n }\n // Run-scoped sandbox preparation for repository resources. GitHub retains the\n // legacy request shape and standalone self-mint path. Non-GitHub providers are\n // host-brokered only: without a `gitCredentials` port there is no token value\n // to seed, and the runtime wrappers degrade to passthrough.\n const minted = await mintRunGitTokensWithIdentity(settings, selections, options);\n // TOKEN-BROKER (B2): the askpass helper is PROVISIONED AT SETUP (runtime) into a\n // per-box, user-writable path in the SAME dir as the token file, instead of a\n // baked image script at /usr/local/bin/opengeni-git-askpass. The clone-hook seed\n // block writes both the token file AND this askpass script before the fetch, so\n // git auth becomes correct on ANY box image (including pre-existing warm boxes on\n // their next turn's clone hook) — no product image needs to carry the askpass.\n // The pointer layer is the SHARED config helper so every API-direct attach\n // surface (viewer attach, channel-A) declares the IDENTICAL env when it\n // cold-creates the box for a repo-attached session — an attach-warmed box\n // missing these keys kills the next repo turn on the SDK's manifest-env guard.\n applyGitAuthPointerEnvironment(environment, minted.identity);\n return {\n environment,\n ...(minted.gitTokens.github ? { gitToken: minted.gitTokens.github } : {}),\n ...(Object.keys(minted.gitTokens).length > 0 ? { gitTokens: minted.gitTokens } : {}),\n ...(Object.keys(minted.expiresAt).length > 0 ? { gitTokenExpiresAt: minted.expiresAt } : {}),\n ...(minted.bindings.length > 0 ? { gitCredentialBindings: minted.bindings } : {}),\n ...(toolspaceToken\n ? {\n toolspaceToken: toolspaceToken.token,\n toolspaceTokenExpiresAt: toolspaceToken.expiresAt,\n }\n : {}),\n };\n}\n\nexport async function mintRunGitCredentials(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<MintedRunGitCredentials | undefined> {\n const selections = gitCredentialSelections(resources);\n if (selections.length === 0) {\n return undefined;\n }\n const minted = await mintRunGitTokensWithIdentity(settings, selections, options);\n return minted.bindings.length > 0\n ? { bindings: minted.bindings, gitTokens: minted.gitTokens, expiresAt: minted.expiresAt }\n : undefined;\n}\n\nexport async function mintRunGitCredentialBinding(\n settings: Settings,\n resources: ResourceRef[],\n provider: GitCredentialProvider,\n credentialBindingId: string,\n options: RunGitCredentialOptions = {},\n): Promise<GitCredentialBindingSeed | undefined> {\n const selections = gitCredentialSelections(resources);\n const selection = selections.find(\n (candidate) =>\n candidate.provider === provider && candidate.credentialBindingId === credentialBindingId,\n );\n if (!selection) {\n return undefined;\n }\n const minted = await mintRunGitTokensWithIdentity(settings, [selection], options);\n const binding = minted.bindings[0];\n if (binding) {\n binding.providerBindingCount = selections.filter(\n (candidate) => candidate.provider === selection.provider,\n ).length;\n }\n return binding;\n}\n\nexport async function mintRunGitTokens(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<GitTokenSeeds | undefined> {\n const tokens = (await mintRunGitCredentials(settings, resources, options))?.gitTokens;\n return tokens && Object.keys(tokens).length > 0 ? tokens : undefined;\n}\n\nexport async function mintRunGitToken(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<string | undefined> {\n return (await mintRunGitTokens(settings, resources, options))?.github;\n}\n\nexport async function resolveRunGitIdentity(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<{ name: string; email: string } | null> {\n const selections = gitCredentialSelections(resources);\n if (selections.length === 0) {\n return null;\n }\n return await resolveRunGitIdentityWithSelections(settings, selections, options);\n}\n\nasync function mintRunGitTokensWithIdentity(\n settings: Settings,\n selections: GitCredentialSelection[],\n options: RunGitCredentialOptions,\n): Promise<{\n bindings: GitCredentialBindingSeed[];\n gitTokens: GitTokenSeeds;\n expiresAt: GitTokenExpiries;\n identity: { name: string; email: string } | null;\n}> {\n const bindings: GitCredentialBindingSeed[] = [];\n let identity: { name: string; email: string } | null = null;\n for (const selection of selections) {\n let token: string | null = null;\n let transport: GitCredentialTransport | undefined;\n let tokenExpiresAt: string | undefined;\n if (\n selection.provider === \"github\" &&\n selection.installationId > 0 &&\n selection.repositoryIds.length > 0\n ) {\n // This callback belongs immediately next to the side effect. Turn startup\n // performs its own admission check, but lazy provisioning and proactive\n // renewal can happen much later in an intentionally unbounded run. Recheck\n // the current workspace binding before every host-brokered or built-in\n // GitHub installation-token mint.\n await options.authorizeGitHubTokenMint?.({\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n });\n }\n if (options?.gitCredentials && options.scope) {\n const request = gitCredentialsRequestForSelection(\n options.scope,\n requireGitCredentialAuthority(options),\n selection,\n \"token\",\n );\n const minted: GitCredentials = await options.gitCredentials(request);\n // workspace-scope cross-check: assert the provider scoped the token to THIS run's workspace\n // before accepting the token for clone seeding.\n assertWorkspaceEcho(\"gitCredentials\", options.scope, minted.workspaceId);\n assertGitCredentialBindingEcho(selection, request, minted);\n if (!minted.token) {\n throw new Error(\n \"connection-credential provider (gitCredentials) did not return a token for a token request\",\n );\n }\n token = minted.token;\n transport = validatedGitCredentialTransport(selection, minted);\n tokenExpiresAt = minted.expiresAt\n ? validatedGitCredentialExpiry(selection.provider, minted.expiresAt)\n : undefined;\n if (minted.identity) {\n identity = minted.identity;\n } else if (selection.provider === \"github\") {\n identity = githubAppBotIdentity(settings);\n }\n } else if (selection.provider === \"github\" && selection.installationId > 0) {\n const minted = await createGitHubAppInstallationTokenWithExpiry(settings, {\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n });\n token = minted.token;\n tokenExpiresAt = minted.expiresAt\n ? validatedGitCredentialExpiry(\"github\", minted.expiresAt)\n : undefined;\n identity = githubAppBotIdentity(settings);\n }\n if (token) {\n bindings.push({\n credentialBindingId: selection.credentialBindingId,\n provider: selection.provider,\n token,\n ...(transport ? { transport } : {}),\n ...(tokenExpiresAt ? { expiresAt: tokenExpiresAt } : {}),\n });\n }\n }\n const gitTokens: GitTokenSeeds = {};\n const expiresAt: GitTokenExpiries = {};\n const counts = new Map<GitCredentialProvider, number>();\n for (const binding of bindings) {\n counts.set(binding.provider, (counts.get(binding.provider) ?? 0) + 1);\n }\n for (const binding of bindings) {\n binding.providerBindingCount = counts.get(binding.provider) ?? 1;\n if (binding.transport?.kind === \"http_broker\") continue;\n if (counts.get(binding.provider) !== 1) continue;\n gitTokens[binding.provider] = binding.token;\n if (binding.expiresAt) expiresAt[binding.provider] = binding.expiresAt;\n }\n return { bindings, gitTokens, expiresAt, identity };\n}\n\nfunction validatedGitCredentialExpiry(provider: GitCredentialProvider, value: string): string {\n const timestamp = Date.parse(value);\n if (!Number.isFinite(timestamp)) {\n throw new Error(`connection-credential provider (${provider}) returned an invalid expiresAt`);\n }\n return new Date(timestamp).toISOString();\n}\n\nconst MAX_GIT_HTTP_BROKER_ROUTES = 256;\nconst MAX_GIT_HTTP_BROKER_URI_LENGTH = 4_096;\n\nfunction validatedGitCredentialTransport(\n selection: GitCredentialSelection,\n minted: GitCredentials,\n): GitCredentialTransport | undefined {\n const transport = minted.transport;\n if (!transport) return undefined;\n\n if (\n typeof transport !== \"object\" ||\n transport.kind !== \"http_broker\" ||\n !Array.isArray(transport.repositories)\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git credential transport`,\n );\n }\n const requestedUris = new Set(selection.repositoryRefs.map((repository) => repository.uri));\n if (\n requestedUris.size === 0 ||\n requestedUris.size > MAX_GIT_HTTP_BROKER_ROUTES ||\n transport.repositories.length !== requestedUris.size\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an incomplete Git HTTP broker route set`,\n );\n }\n\n const echoedUris = new Set<string>();\n const brokerUris = new Set<string>();\n const repositories = transport.repositories.map((route) => {\n if (\n !route ||\n typeof route !== \"object\" ||\n typeof route.repositoryUri !== \"string\" ||\n typeof route.brokerUri !== \"string\"\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker route`,\n );\n }\n if (!requestedUris.has(route.repositoryUri) || echoedUris.has(route.repositoryUri)) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an unexpected Git HTTP broker repository`,\n );\n }\n echoedUris.add(route.repositoryUri);\n if (\n route.brokerUri.length === 0 ||\n route.brokerUri.length > MAX_GIT_HTTP_BROKER_URI_LENGTH ||\n route.brokerUri.trim() !== route.brokerUri\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker URI`,\n );\n }\n let brokerUrl: URL;\n try {\n brokerUrl = new URL(route.brokerUri);\n } catch {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker URI`,\n );\n }\n if (\n brokerUrl.protocol !== \"https:\" ||\n brokerUrl.username ||\n brokerUrl.password ||\n brokerUrl.search ||\n brokerUrl.hash ||\n brokerUris.has(brokerUrl.href) ||\n brokerUrl.href === route.repositoryUri\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an unsafe Git HTTP broker URI`,\n );\n }\n brokerUris.add(brokerUrl.href);\n return {\n repositoryUri: route.repositoryUri,\n brokerUri: brokerUrl.href,\n };\n });\n\n if ([...requestedUris].some((uri) => !echoedUris.has(uri))) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an incomplete Git HTTP broker route set`,\n );\n }\n return { kind: \"http_broker\", repositories };\n}\n\nexport function assertGitCredentialRenewalTransportUnchanged(\n initial: GitCredentialBindingSeed,\n renewed: GitCredentialBindingSeed,\n): void {\n if (!initial.transport && !renewed.transport) return;\n if (\n !initial.transport ||\n !renewed.transport ||\n initial.transport.kind !== renewed.transport.kind\n ) {\n throw new Error(\n `renewed ${initial.provider} credential changed transport for binding ${initial.credentialBindingId}`,\n );\n }\n const routeKey = (route: { repositoryUri: string; brokerUri: string }) =>\n `${route.repositoryUri}\\u0000${route.brokerUri}`;\n const initialRoutes = initial.transport.repositories.map(routeKey).sort();\n const renewedRoutes = renewed.transport.repositories.map(routeKey).sort();\n if (\n initialRoutes.length !== renewedRoutes.length ||\n initialRoutes.some((route, index) => route !== renewedRoutes[index])\n ) {\n throw new Error(\n `renewed ${initial.provider} credential changed Git HTTP broker routes for binding ${initial.credentialBindingId}`,\n );\n }\n}\n\nasync function resolveRunGitIdentityWithSelections(\n settings: Settings,\n selections: GitCredentialSelection[],\n options: RunGitCredentialOptions,\n): Promise<{ name: string; email: string } | null> {\n let identity: { name: string; email: string } | null = null;\n for (const selection of selections) {\n if (options.gitCredentials && options.scope) {\n const request = gitCredentialsRequestForSelection(\n options.scope,\n requireGitCredentialAuthority(options),\n selection,\n \"identity\",\n );\n const resolved: GitCredentials = await options.gitCredentials(request);\n assertWorkspaceEcho(\"gitCredentials\", options.scope, resolved.workspaceId);\n assertGitCredentialBindingEcho(selection, request, resolved);\n if (resolved.identity) {\n identity = resolved.identity;\n } else if (selection.provider === \"github\") {\n identity = githubAppBotIdentity(settings);\n }\n } else if (selection.provider === \"github\" && selection.installationId > 0) {\n identity = githubAppBotIdentity(settings);\n }\n }\n return identity;\n}\n\ntype GitCredentialSelection = {\n provider: GitCredentialProvider;\n credentialBindingId: string;\n explicitCredentialBinding: boolean;\n requireBindingEcho: boolean;\n providerHost?: string;\n installationId: number;\n repositoryIds: number[];\n repositoryRefs: GitCredentialRepositoryRef[];\n};\n\nfunction gitCredentialsRequestForSelection(\n scope: ConnectionScope,\n authority: GitCredentialAuthority,\n selection: GitCredentialSelection,\n purpose?: \"token\" | \"identity\",\n): Parameters<NonNullable<ConnectionCredentialsPort[\"gitCredentials\"]>>[0] {\n const legacy = {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n ...authority,\n ...(purpose ? { purpose } : {}),\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n };\n const bindingEcho = selection.requireBindingEcho\n ? {\n credentialBindingId: selection.credentialBindingId,\n provider: selection.provider,\n ...(selection.providerHost ? { providerHost: selection.providerHost } : {}),\n }\n : {};\n if (selection.provider === \"github\") {\n return {\n ...legacy,\n ...bindingEcho,\n repositoryRefs: selection.repositoryRefs,\n };\n }\n return {\n ...legacy,\n ...bindingEcho,\n provider: selection.provider,\n repositoryRefs: selection.repositoryRefs,\n };\n}\n\nfunction requireGitCredentialAuthority(options: RunGitCredentialOptions): GitCredentialAuthority {\n if (!options.authority) {\n throw new Error(\"host git credential resolution requires immutable session turn authority\");\n }\n return options.authority;\n}\n\nfunction assertGitCredentialBindingEcho(\n selection: GitCredentialSelection,\n request: Parameters<NonNullable<ConnectionCredentialsPort[\"gitCredentials\"]>>[0],\n minted: GitCredentials,\n): void {\n if (!selection.requireBindingEcho) return;\n if (minted.credentialBindingId !== request.credentialBindingId) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned the wrong credential binding`,\n );\n }\n if (minted.provider !== selection.provider) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned the wrong provider echo`,\n );\n }\n if (request.providerHost && minted.providerHost !== request.providerHost) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned the wrong provider host echo`,\n );\n }\n}\n\n/**\n * The GitHub App installation + repository ids a run's git-credential mint\n * would use for these resources, or null when no GitHub token would be minted.\n * Derived from gitCredentialSelections so workspace-authorization rechecks\n * cover exactly the ids that reach createGitHubAppInstallationToken —\n * including legacy string-typed installationId/repositoryId refs, which the\n * mint path coerces via positiveInteger.\n */\nexport function gitHubTokenMintSelections(\n resources: ResourceRef[],\n): Array<{ installationId: number; repositoryIds: number[] }> {\n return gitCredentialSelections(resources)\n .filter(\n (candidate) =>\n candidate.provider === \"github\" &&\n candidate.installationId > 0 &&\n candidate.repositoryIds.length > 0,\n )\n .map(({ installationId, repositoryIds }) => ({ installationId, repositoryIds }));\n}\n\n/** @deprecated Use gitHubTokenMintSelections for multi-installation sessions. */\nexport function gitHubTokenMintSelection(\n resources: ResourceRef[],\n): { installationId: number; repositoryIds: number[] } | null {\n const selections = gitHubTokenMintSelections(resources);\n if (selections.length > 1) {\n throw new Error(\"GitHub resources span multiple credential bindings\");\n }\n return selections[0] ?? null;\n}\n\nfunction gitCredentialSelections(resources: ResourceRef[]): GitCredentialSelection[] {\n const byBinding = new Map<string, GitCredentialSelection>();\n const remoteBindings = new Map<string, string>();\n const bindingProviders = new Map<string, GitCredentialProvider>();\n for (const resource of resources) {\n if (resource.kind !== \"repository\") {\n continue;\n }\n const provider = repositoryCredentialProvider(resource);\n if (!provider) {\n continue;\n }\n const installationId =\n provider === \"github\"\n ? (positiveInteger(resource.githubInstallationId ?? resource.installationId) ?? 0)\n : 0;\n const credentialBindingId = gitCredentialBindingIdForRepository(resource, provider)!;\n const bindingKey = `${provider}\\u0000${credentialBindingId}`;\n const boundProvider = bindingProviders.get(credentialBindingId);\n if (boundProvider && boundProvider !== provider) {\n throw new Error(\n `credential binding ${credentialBindingId} is assigned to multiple Git providers`,\n );\n }\n bindingProviders.set(credentialBindingId, provider);\n const normalizedRemote = normalizedGitRemote(resource.uri);\n const claimedBinding = remoteBindings.get(normalizedRemote);\n if (claimedBinding && claimedBinding !== bindingKey) {\n throw new Error(\n `repository remote ${resource.uri} is claimed by multiple credential bindings`,\n );\n }\n remoteBindings.set(normalizedRemote, bindingKey);\n const entry = byBinding.get(bindingKey) ?? {\n provider,\n credentialBindingId,\n explicitCredentialBinding: Boolean(resource.credentialBindingId),\n requireBindingEcho: false,\n installationId: 0,\n repositoryIds: [],\n repositoryRefs: [],\n };\n entry.explicitCredentialBinding ||= Boolean(resource.credentialBindingId);\n const ref = gitCredentialRepositoryRef(resource, provider);\n entry.repositoryRefs.push(ref);\n if (provider === \"github\") {\n const repositoryId = positiveInteger(resource.githubRepositoryId ?? resource.repositoryId);\n if (installationId && repositoryId) {\n if (entry.installationId > 0 && entry.installationId !== installationId) {\n throw new Error(\n `GitHub credential binding ${credentialBindingId} spans multiple installations`,\n );\n }\n entry.installationId = installationId;\n entry.repositoryIds.push(repositoryId);\n }\n }\n byBinding.set(bindingKey, entry);\n }\n const selections = [...byBinding.values()];\n const providerCounts = new Map<GitCredentialProvider, number>();\n for (const selection of selections) {\n providerCounts.set(selection.provider, (providerCounts.get(selection.provider) ?? 0) + 1);\n const hosts = new Set(\n selection.repositoryRefs.map((ref) => normalizedGitHost(ref.uri)).filter(Boolean),\n );\n const [providerHost] = hosts;\n if (hosts.size === 1 && providerHost) selection.providerHost = providerHost;\n }\n for (const selection of selections) {\n selection.requireBindingEcho =\n selection.explicitCredentialBinding || (providerCounts.get(selection.provider) ?? 0) > 1;\n }\n return selections;\n}\n\nfunction normalizedGitHost(uri: string): string {\n try {\n return new URL(uri).host.toLowerCase();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizedGitRemote(uri: string): string {\n try {\n const url = new URL(uri);\n return `${url.protocol.toLowerCase()}//${url.host.toLowerCase()}${url.pathname.replace(/\\/+$/, \"\").replace(/\\.git$/, \"\")}`;\n } catch {\n return uri\n .trim()\n .replace(/\\/+$/, \"\")\n .replace(/\\.git$/, \"\")\n .toLowerCase();\n }\n}\n\nfunction repositoryCredentialProvider(\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n): GitCredentialProvider | null {\n return gitCredentialProviderForRepository(resource);\n}\n\nfunction gitCredentialRepositoryRef(\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n provider: GitCredentialProvider,\n): GitCredentialRepositoryRef {\n return {\n provider,\n ...(resource.credentialBindingId ? { credentialBindingId: resource.credentialBindingId } : {}),\n ...(resource.access ? { access: resource.access } : {}),\n uri: resource.uri,\n ref: resource.ref,\n ...(resource.repositoryId !== undefined\n ? { repositoryId: resource.repositoryId }\n : resource.githubRepositoryId !== undefined\n ? { repositoryId: resource.githubRepositoryId }\n : {}),\n ...(resource.installationId !== undefined\n ? { installationId: resource.installationId }\n : resource.githubInstallationId !== undefined\n ? { installationId: resource.githubInstallationId }\n : {}),\n ...(resource.projectId !== undefined ? { projectId: resource.projectId } : {}),\n ...(resource.connectionId ? { connectionId: resource.connectionId } : {}),\n };\n}\n\nfunction positiveInteger(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isInteger(value) && value > 0) {\n return value;\n }\n if (typeof value === \"string\" && /^\\d+$/.test(value) && Number(value) > 0) {\n return Number(value);\n }\n return null;\n}\n","import type { GitCredentialProvider } from \"@opengeni/contracts\";\nimport type { GitTokenExpiries, GitTokenSeeds, MintedRunGitCredentials } from \"./environment\";\n\nexport const GIT_CREDENTIAL_DEFAULT_REFRESH_MS = 30 * 60_000;\nexport const GIT_CREDENTIAL_EXPIRY_LEAD_MS = 5 * 60_000;\nexport const GIT_CREDENTIAL_MIN_REFRESH_MS = 5_000;\nexport const GIT_CREDENTIAL_MAX_RETRY_MS = 5 * 60_000;\n\ntype RenewalTimer = unknown;\n\nexport type GitCredentialRenewalResult = {\n providers: readonly GitCredentialProvider[];\n nextDelayMs: number;\n};\n\nexport type GitCredentialRenewalFailure = {\n providers: readonly GitCredentialProvider[];\n retryDelayMs: number;\n errorClass: string;\n};\n\nexport type GitCredentialRenewalController = {\n refreshNow(): Promise<void>;\n stop(): Promise<void>;\n};\n\nexport type GitCredentialRenewalOptions = {\n expectedProviders: readonly GitCredentialProvider[];\n initialExpiresAt?: GitTokenExpiries;\n mint: () => Promise<MintedRunGitCredentials | undefined>;\n write: (tokens: GitTokenSeeds) => Promise<void>;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => RenewalTimer;\n clearSchedule?: (timer: RenewalTimer) => void;\n onSuccess?: (result: GitCredentialRenewalResult) => void;\n onFailure?: (failure: GitCredentialRenewalFailure) => void;\n};\n\n/**\n * Return a conservative refresh delay for a provider set.\n *\n * The fixed cadence caps long/unknown provider TTLs; a known earlier expiry\n * pulls renewal forward. Invalid metadata is treated as unknown rather than\n * allowing a token to live indefinitely.\n */\nexport function nextGitCredentialRenewalDelay(\n expiresAt: GitTokenExpiries | undefined,\n providers: readonly GitCredentialProvider[],\n nowMs = Date.now(),\n): number {\n let delay = GIT_CREDENTIAL_DEFAULT_REFRESH_MS;\n for (const provider of providers) {\n const rawExpiry = expiresAt?.[provider];\n if (!rawExpiry) continue;\n const expiryMs = Date.parse(rawExpiry);\n if (!Number.isFinite(expiryMs)) continue;\n delay = Math.min(\n delay,\n Math.max(GIT_CREDENTIAL_MIN_REFRESH_MS, expiryMs - nowMs - GIT_CREDENTIAL_EXPIRY_LEAD_MS),\n );\n }\n return delay;\n}\n\nexport function startGitCredentialRenewalLoop(\n options: GitCredentialRenewalOptions,\n): GitCredentialRenewalController {\n const providers = [...new Set(options.expectedProviders)];\n const now = options.now ?? Date.now;\n const schedule =\n options.schedule ??\n ((callback: () => void, delayMs: number): ReturnType<typeof setTimeout> => {\n const timer = setTimeout(callback, delayMs);\n timer.unref?.();\n return timer;\n });\n const clearSchedule =\n options.clearSchedule ??\n ((timer: RenewalTimer): void => clearTimeout(timer as ReturnType<typeof setTimeout>));\n\n let stopped = false;\n let timer: RenewalTimer | null = null;\n let inFlight: Promise<void> | null = null;\n let writeInFlight: Promise<void> | null = null;\n let retryDelayMs = GIT_CREDENTIAL_MIN_REFRESH_MS;\n\n const clearTimer = (): void => {\n if (timer === null) return;\n clearSchedule(timer);\n timer = null;\n };\n\n const scheduleRefresh = (delayMs: number): void => {\n if (stopped || providers.length === 0) return;\n clearTimer();\n timer = schedule(() => {\n timer = null;\n void refreshNow();\n }, delayMs);\n };\n\n const validateMintedTokens = (\n minted: MintedRunGitCredentials | undefined,\n ): MintedRunGitCredentials => {\n if (!minted) {\n throw new GitCredentialRenewalError(\"credential provider returned no token bundle\");\n }\n for (const provider of providers) {\n if (!minted.gitTokens[provider]) {\n throw new GitCredentialRenewalError(`credential provider omitted ${provider}`);\n }\n }\n return minted;\n };\n\n const performRefresh = async (): Promise<void> => {\n try {\n const minted = validateMintedTokens(await options.mint());\n if (stopped) return;\n const write = options.write(minted.gitTokens);\n writeInFlight = write;\n try {\n await write;\n } finally {\n if (writeInFlight === write) writeInFlight = null;\n }\n if (stopped) return;\n retryDelayMs = GIT_CREDENTIAL_MIN_REFRESH_MS;\n const nextDelayMs = nextGitCredentialRenewalDelay(minted.expiresAt, providers, now());\n try {\n options.onSuccess?.({ providers, nextDelayMs });\n } catch {\n // Observability callbacks never own credential liveness.\n }\n scheduleRefresh(nextDelayMs);\n } catch (error) {\n if (stopped) return;\n const scheduledRetryMs = retryDelayMs;\n retryDelayMs = Math.min(retryDelayMs * 2, GIT_CREDENTIAL_MAX_RETRY_MS);\n try {\n options.onFailure?.({\n providers,\n retryDelayMs: scheduledRetryMs,\n errorClass: error instanceof Error ? error.name : \"UnknownError\",\n });\n } catch {\n // Observability callbacks never own credential liveness.\n }\n scheduleRefresh(scheduledRetryMs);\n }\n };\n\n const refreshNow = (): Promise<void> => {\n if (stopped || providers.length === 0) return Promise.resolve();\n if (inFlight) return inFlight;\n clearTimer();\n const operation = performRefresh();\n inFlight = operation;\n void operation.finally(() => {\n if (inFlight === operation) inFlight = null;\n });\n return operation;\n };\n\n scheduleRefresh(nextGitCredentialRenewalDelay(options.initialExpiresAt, providers, now()));\n\n return {\n refreshNow,\n stop: async () => {\n stopped = true;\n clearTimer();\n // A broker mint can be a remote host call with no cancellation seam. It\n // cannot mutate the sandbox, and the stopped check above rejects its late\n // result, so never hold turn settlement hostage to a hung mint. A write\n // does mutate the box and must drain before capture/teardown.\n await writeInFlight?.catch(() => undefined);\n },\n };\n}\n\nclass GitCredentialRenewalError extends Error {\n override readonly name = \"GitCredentialRenewalError\";\n}\n","export type ExpiringMaterialRenewalPolicy = {\n defaultRefreshMs: number;\n expiryLeadMs: number;\n minRefreshMs: number;\n maxRetryMs: number;\n};\n\ntype RenewalTimer = unknown;\n\nexport type ExpiringMaterialRenewalController = {\n refreshNow(): Promise<void>;\n stop(): Promise<void>;\n};\n\nexport type ExpiringMaterialRenewalOptions<T> = {\n initialExpiresAt: Date | null;\n resolve: () => Promise<T>;\n write: (material: T) => Promise<void>;\n expiresAt: (material: T) => Date | null;\n policy: ExpiringMaterialRenewalPolicy;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => RenewalTimer;\n clearSchedule?: (timer: RenewalTimer) => void;\n onSuccess?: (result: { material: T; nextDelayMs: number }) => void;\n onFailure?: (failure: { retryDelayMs: number; errorClass: string }) => void;\n};\n\nexport function nextExpiringMaterialRenewalDelay(\n expiresAt: Date | null,\n policy: ExpiringMaterialRenewalPolicy,\n nowMs = Date.now(),\n): number {\n if (!expiresAt || !Number.isFinite(expiresAt.getTime())) {\n return policy.defaultRefreshMs;\n }\n return Math.min(\n policy.defaultRefreshMs,\n Math.max(policy.minRefreshMs, expiresAt.getTime() - nowMs - policy.expiryLeadMs),\n );\n}\n\n/**\n * Attempt-owned single-flight renewal for expiring sandbox material.\n *\n * A late resolver cannot write after stop. A physical sandbox write that already\n * started is drained so turn settlement cannot race a stale mutation.\n */\nexport function startExpiringMaterialRenewalLoop<T>(\n options: ExpiringMaterialRenewalOptions<T>,\n): ExpiringMaterialRenewalController {\n const now = options.now ?? Date.now;\n const schedule =\n options.schedule ??\n ((callback: () => void, delayMs: number): ReturnType<typeof setTimeout> => {\n const timer = setTimeout(callback, delayMs);\n timer.unref?.();\n return timer;\n });\n const clearSchedule =\n options.clearSchedule ??\n ((timer: RenewalTimer): void => clearTimeout(timer as ReturnType<typeof setTimeout>));\n let stopped = false;\n let timer: RenewalTimer | null = null;\n let inFlight: Promise<void> | null = null;\n let writeInFlight: Promise<void> | null = null;\n let retryDelayMs = options.policy.minRefreshMs;\n\n const clearTimer = (): void => {\n if (timer === null) return;\n clearSchedule(timer);\n timer = null;\n };\n const scheduleRefresh = (delayMs: number): void => {\n if (stopped) return;\n clearTimer();\n timer = schedule(() => {\n timer = null;\n void refreshNow();\n }, delayMs);\n };\n const performRefresh = async (): Promise<void> => {\n try {\n const material = await options.resolve();\n if (stopped) return;\n const write = options.write(material);\n writeInFlight = write;\n try {\n await write;\n } finally {\n if (writeInFlight === write) writeInFlight = null;\n }\n if (stopped) return;\n retryDelayMs = options.policy.minRefreshMs;\n const nextDelayMs = nextExpiringMaterialRenewalDelay(\n options.expiresAt(material),\n options.policy,\n now(),\n );\n try {\n options.onSuccess?.({ material, nextDelayMs });\n } catch {\n // Observability never owns credential liveness.\n }\n scheduleRefresh(nextDelayMs);\n } catch (error) {\n if (stopped) return;\n const scheduledRetryMs = retryDelayMs;\n retryDelayMs = Math.min(retryDelayMs * 2, options.policy.maxRetryMs);\n try {\n options.onFailure?.({\n retryDelayMs: scheduledRetryMs,\n errorClass: error instanceof Error ? error.name : \"UnknownError\",\n });\n } catch {\n // Observability never owns credential liveness.\n }\n scheduleRefresh(scheduledRetryMs);\n }\n };\n const refreshNow = (): Promise<void> => {\n if (stopped) return Promise.resolve();\n if (inFlight) return inFlight;\n clearTimer();\n const operation = performRefresh();\n inFlight = operation;\n void operation.finally(() => {\n if (inFlight === operation) inFlight = null;\n });\n return operation;\n };\n\n scheduleRefresh(\n nextExpiringMaterialRenewalDelay(options.initialExpiresAt, options.policy, now()),\n );\n return {\n refreshNow,\n stop: async () => {\n stopped = true;\n clearTimer();\n await writeInFlight?.catch(() => undefined);\n },\n };\n}\n","import type { NormalizedRunCredentialMaterial } from \"@opengeni/runtime\";\nimport {\n nextExpiringMaterialRenewalDelay,\n startExpiringMaterialRenewalLoop,\n type ExpiringMaterialRenewalController,\n} from \"./expiring-material-renewal\";\n\nexport const RUN_CREDENTIAL_DEFAULT_REFRESH_MS = 30 * 60_000;\nexport const RUN_CREDENTIAL_EXPIRY_LEAD_MS = 5 * 60_000;\nexport const RUN_CREDENTIAL_MIN_REFRESH_MS = 5_000;\nexport const RUN_CREDENTIAL_MAX_RETRY_MS = 5 * 60_000;\n\nexport type RunCredentialRenewalController = ExpiringMaterialRenewalController;\n\ntype RenewalTimer = unknown;\n\nexport type RunCredentialRenewalOptions = {\n initialExpiresAt: Date | null;\n resolve: () => Promise<NormalizedRunCredentialMaterial | null>;\n write: (material: NormalizedRunCredentialMaterial | null) => Promise<void>;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => RenewalTimer;\n clearSchedule?: (timer: RenewalTimer) => void;\n onSuccess?: (result: { nextDelayMs: number; authNeeded: boolean }) => void;\n onFailure?: (failure: { retryDelayMs: number; errorClass: string }) => void;\n};\n\nexport function nextRunCredentialRenewalDelay(expiresAt: Date | null, nowMs = Date.now()): number {\n return nextExpiringMaterialRenewalDelay(\n expiresAt,\n {\n defaultRefreshMs: RUN_CREDENTIAL_DEFAULT_REFRESH_MS,\n expiryLeadMs: RUN_CREDENTIAL_EXPIRY_LEAD_MS,\n minRefreshMs: RUN_CREDENTIAL_MIN_REFRESH_MS,\n maxRetryMs: RUN_CREDENTIAL_MAX_RETRY_MS,\n },\n nowMs,\n );\n}\n\n/** Single-flight renewal; late resolves cannot mutate a stopped attempt. */\nexport function startRunCredentialRenewalLoop(\n options: RunCredentialRenewalOptions,\n): RunCredentialRenewalController {\n return startExpiringMaterialRenewalLoop<NormalizedRunCredentialMaterial | null>({\n initialExpiresAt: options.initialExpiresAt,\n resolve: options.resolve,\n write: options.write,\n expiresAt: (material) => material?.expiresAt ?? null,\n policy: {\n defaultRefreshMs: RUN_CREDENTIAL_DEFAULT_REFRESH_MS,\n expiryLeadMs: RUN_CREDENTIAL_EXPIRY_LEAD_MS,\n minRefreshMs: RUN_CREDENTIAL_MIN_REFRESH_MS,\n maxRetryMs: RUN_CREDENTIAL_MAX_RETRY_MS,\n },\n ...(options.now ? { now: options.now } : {}),\n ...(options.schedule ? { schedule: options.schedule } : {}),\n ...(options.clearSchedule ? { clearSchedule: options.clearSchedule } : {}),\n ...(options.onSuccess\n ? {\n onSuccess: ({ material, nextDelayMs }) =>\n options.onSuccess?.({\n nextDelayMs,\n authNeeded: (material?.authNeeded.length ?? 0) > 0,\n }),\n }\n : {}),\n ...(options.onFailure ? { onFailure: options.onFailure } : {}),\n });\n}\n","import {\n startExpiringMaterialRenewalLoop,\n type ExpiringMaterialRenewalController,\n} from \"./expiring-material-renewal\";\nimport type { MintedSandboxToolspaceToken } from \"./environment\";\n\nexport const TOOLSPACE_TOKEN_DEFAULT_REFRESH_MS = 30 * 60_000;\nexport const TOOLSPACE_TOKEN_EXPIRY_LEAD_MS = 5 * 60_000;\nexport const TOOLSPACE_TOKEN_MIN_REFRESH_MS = 5_000;\nexport const TOOLSPACE_TOKEN_MAX_RETRY_MS = 5 * 60_000;\n\nexport type ToolspaceTokenRenewalController = ExpiringMaterialRenewalController;\n\nexport type ToolspaceTokenRenewalOptions = {\n initialExpiresAt: Date;\n mint: () => Promise<MintedSandboxToolspaceToken | undefined>;\n write: (material: MintedSandboxToolspaceToken) => Promise<void>;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => unknown;\n clearSchedule?: (timer: unknown) => void;\n onSuccess?: (result: { nextDelayMs: number }) => void;\n onFailure?: (failure: { retryDelayMs: number; errorClass: string }) => void;\n};\n\nclass ToolspaceTokenRenewalError extends Error {\n override readonly name = \"ToolspaceTokenRenewalError\";\n}\n\nexport function startToolspaceTokenRenewalLoop(\n options: ToolspaceTokenRenewalOptions,\n): ToolspaceTokenRenewalController {\n return startExpiringMaterialRenewalLoop<MintedSandboxToolspaceToken>({\n initialExpiresAt: options.initialExpiresAt,\n resolve: async () => {\n const minted = await options.mint();\n if (!minted) {\n throw new ToolspaceTokenRenewalError(\"Toolspace token mint is no longer available\");\n }\n return minted;\n },\n write: options.write,\n expiresAt: (material) => material.expiresAt,\n policy: {\n defaultRefreshMs: TOOLSPACE_TOKEN_DEFAULT_REFRESH_MS,\n expiryLeadMs: TOOLSPACE_TOKEN_EXPIRY_LEAD_MS,\n minRefreshMs: TOOLSPACE_TOKEN_MIN_REFRESH_MS,\n maxRetryMs: TOOLSPACE_TOKEN_MAX_RETRY_MS,\n },\n ...(options.now ? { now: options.now } : {}),\n ...(options.schedule ? { schedule: options.schedule } : {}),\n ...(options.clearSchedule ? { clearSchedule: options.clearSchedule } : {}),\n ...(options.onSuccess\n ? { onSuccess: ({ nextDelayMs }) => options.onSuccess?.({ nextDelayMs }) }\n : {}),\n ...(options.onFailure ? { onFailure: options.onFailure } : {}),\n });\n}\n","import type {\n ConnectionCredentialsPort,\n CredentialAuthNeededPayload,\n SandboxBackend,\n RunCredentialsRequest,\n Session,\n SessionTurn,\n} from \"@opengeni/contracts\";\nimport { getSessionRootId, type Database } from \"@opengeni/db\";\nimport {\n normalizeRunCredentialsResolution,\n type NormalizedRunCredentialMaterial,\n} from \"@opengeni/runtime\";\n\nexport type RunCredentialResolutionContext = {\n db: Database;\n connectionCredentials?: ConnectionCredentialsPort | null;\n accountId: string;\n workspaceId: string;\n session: Session;\n turn: SessionTurn;\n attemptId: string;\n effectiveSandboxBackend: SandboxBackend;\n variableSet: { id: string; name: string } | null;\n};\n\nexport type BoundRunCredentialResolver = {\n resolve(input: {\n purpose: \"provision\" | \"renewal\";\n forceRefresh: boolean;\n }): Promise<NormalizedRunCredentialMaterial | null>;\n};\n\nexport function buildRunCredentialsRequest(\n input: Omit<RunCredentialResolutionContext, \"db\" | \"connectionCredentials\"> & {\n rootSessionId: string;\n purpose: \"provision\" | \"renewal\";\n forceRefresh: boolean;\n },\n): RunCredentialsRequest {\n return {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.session.id,\n parentSessionId: input.session.parentSessionId,\n rootSessionId: input.rootSessionId,\n sandboxGroupId: input.session.sandboxGroupId,\n turnId: input.turn.id,\n attemptId: input.attemptId,\n executionGeneration: input.turn.executionGeneration,\n initiator: input.turn.initiator,\n initiatorContext: input.turn.initiatorContext,\n effectiveSandboxBackend: input.effectiveSandboxBackend,\n sandboxOs: input.turn.sandboxOs ?? input.session.sandboxOs,\n purpose: input.purpose,\n forceRefresh: input.forceRefresh,\n variableSet: input.variableSet,\n };\n}\n\nexport function runCredentialAuthNeededPayloads(\n material: NormalizedRunCredentialMaterial,\n): CredentialAuthNeededPayload[] {\n return material.authNeeded.map((notice) => ({\n credentialClass: \"run\",\n reason: notice.reason,\n ...(notice.providerDomain ? { providerDomain: notice.providerDomain } : {}),\n ...(notice.connectionId ? { connectionId: notice.connectionId } : {}),\n ...(notice.scopes?.length ? { scopes: notice.scopes } : {}),\n ...(notice.resource ? { resource: notice.resource } : {}),\n ...(notice.authorizationUrl ? { authorizationUrl: notice.authorizationUrl } : {}),\n ...(notice.message ? { message: notice.message } : {}),\n }));\n}\n\nexport function runCredentialModelNote(\n material: NormalizedRunCredentialMaterial,\n): string | undefined {\n if (material.authNeeded.length === 0) return undefined;\n return [\n \"[OpenGeni connected-service status]\",\n \"One or more host-managed credentials need user attention. Continue with available capabilities, but do not claim the affected service is usable until it is reconnected.\",\n JSON.stringify({\n credentials: material.authNeeded.map((notice) => ({\n reason: notice.reason,\n ...(notice.providerDomain ? { providerDomain: notice.providerDomain } : {}),\n ...(notice.resource ? { resource: notice.resource } : {}),\n ...(notice.message ? { message: notice.message } : {}),\n })),\n }),\n ].join(\"\\n\");\n}\n\n/**\n * Freeze the provider-neutral host credential request to this exact admitted\n * turn. The host selects connections and material; the worker never infers a\n * provider from repositories, environment names, or an OpenGeni variable set.\n */\nexport async function bindRunCredentialResolver(\n input: RunCredentialResolutionContext,\n): Promise<BoundRunCredentialResolver | null> {\n const resolver = input.connectionCredentials?.runCredentials;\n if (!resolver) return null;\n const rootSessionId = await getSessionRootId(input.db, input.workspaceId, input.session.id);\n if (!rootSessionId) {\n throw new Error(`cannot resolve run credentials for missing session ${input.session.id}`);\n }\n const scope = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.session.id,\n };\n return {\n resolve: async ({ purpose, forceRefresh }) => {\n const resolution = await resolver(\n buildRunCredentialsRequest({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n session: input.session,\n turn: input.turn,\n attemptId: input.attemptId,\n effectiveSandboxBackend: input.effectiveSandboxBackend,\n variableSet: input.variableSet,\n rootSessionId,\n purpose,\n forceRefresh,\n }),\n );\n return normalizeRunCredentialsResolution(resolution, scope);\n },\n };\n}\n","import {\n configuredStaticUsageLimits,\n policyProviderIdForModel,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n evaluateWorkspaceModelPolicy,\n latencyModeForMetadata,\n mergeToolRefs,\n reasoningEffortForMetadata,\n type SessionGoal,\n type ToolRef,\n} from \"@opengeni/contracts\";\nimport { isCodexBilledModel } from \"@opengeni/codex\";\nimport {\n enqueueSessionWorkflowWakeIfRunnable,\n getBillingBalance,\n getLatestStartedSessionTurn,\n getWorkspaceModelPolicy,\n getSessionGoal,\n isCodexBilledTurn,\n materializeGoalContinuation,\n requireSession,\n sumUsageQuantity,\n type Database,\n} from \"@opengeni/db\";\nimport type { ActivityServices, MaybeContinueGoalInput, MaybeContinueGoalResult } from \"./types\";\n\nexport function createGoalActivities(services: () => Promise<ActivityServices>) {\n async function enqueueGoalRetryWake(input: MaybeContinueGoalInput): Promise<void> {\n const { db } = await services();\n await enqueueSessionWorkflowWakeIfRunnable(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n temporalWorkflowId: input.workflowId,\n reason: \"goal_retry\",\n // A permanently invalid goal must not become a tight workflow loop. One\n // durable retry after a short delay preserves liveness without scanning.\n notBefore: new Date(Date.now() + 30_000),\n });\n }\n\n async function maybeContinueGoal(\n input: MaybeContinueGoalInput,\n ): Promise<MaybeContinueGoalResult> {\n const { settings, db, bus } = await services();\n // Cheap pre-read: the common goal-less session skips the budget queries.\n const existingGoal = await getSessionGoal(db, input.workspaceId, input.sessionId);\n if (!existingGoal || existingGoal.status !== \"active\") {\n return { action: \"none\" };\n }\n // Loaded before the budget check so the codex-billed predicate and the\n // synthesized turn use the SAME effective policy. An explicit per-turn\n // model can differ from the persisted session default; follow-up goal work\n // must preserve the newest policy that actually emitted `turn.started`.\n // Admission-rejected turns have no such event and cannot poison it.\n // Kept below the goal-less fast path so a non-goal session still skips the\n // reads entirely.\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n const latestStartedTurn = await getLatestStartedSessionTurn(\n db,\n input.workspaceId,\n input.sessionId,\n );\n let continuationModel = latestStartedTurn?.model ?? session.model;\n const continuationReasoningEffort =\n latestStartedTurn?.reasoningEffort ??\n reasoningEffortForMetadata(session.metadata, settings.openaiReasoningEffort);\n const continuationLatencyMode =\n latestStartedTurn?.latencyMode ?? latencyModeForMetadata(session.metadata, \"standard\");\n // Workspace model policy: a continuation inherits the last STARTED turn's\n // model, so a single policy-violating turn would otherwise re-arm itself on\n // every continuation (exactly how one bare-model turn kept a goal loop on\n // the paid built-in provider all night). If the inherited model is blocked\n // but the session's own default is allowed, recover to the default; if\n // both are blocked, pause the goal visibly (the budget-pause channel, with\n // a truthful rationale) instead of synthesizing a turn the worker's hard\n // gate would fail over and over.\n let modelPolicyBlocked: string | null = null;\n const workspaceModelPolicy = await getWorkspaceModelPolicy(db, input.workspaceId);\n if (workspaceModelPolicy) {\n const policyBlocks = (modelId: string): boolean =>\n !evaluateWorkspaceModelPolicy(workspaceModelPolicy, {\n providerId: policyProviderIdForModel(settings, modelId),\n modelId,\n }).allowed;\n if (policyBlocks(continuationModel)) {\n if (continuationModel !== session.model && !policyBlocks(session.model)) {\n continuationModel = session.model;\n } else {\n modelPolicyBlocked = `workspace model policy blocks model \"${continuationModel}\"; pick an allowed model or change the workspace model policy`;\n }\n }\n }\n // remote_v2 sessions may only continue on Codex models — refuse synthesis\n // that would leave the portable/non-Codex path (and mixed history shapes).\n if (\n !modelPolicyBlocked &&\n session.codexCompactionMode === \"remote_v2\" &&\n !isCodexBilledModel(continuationModel)\n ) {\n modelPolicyBlocked = `session is locked to Codex remote compaction v2; model \"${continuationModel}\" is not a Codex subscription model`;\n }\n // A codex-model goal continuation is paid by the user's ChatGPT/Codex plan,\n // so it must not be budget-paused for zero OpenGeni credits. This file uses\n // BASE settings (no codex overlay); the predicate does its own credential read.\n const isCodexRun = await isCodexBilledTurn({\n db,\n settings,\n workspaceId: input.workspaceId,\n model: continuationModel,\n });\n // Budget exhaustion pauses the goal visibly instead of failing the\n // session. Computed up front and applied inside the locked decision so a\n // limits pause never consumes continuation budget.\n const budgetBlocked = await goalRunBudgetBlocked(\n settings,\n db,\n input.accountId,\n input.workspaceId,\n isCodexRun,\n );\n const decision = await materializeGoalContinuation(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n workflowId: input.workflowId,\n defaultMaxAutoContinuations: settings.goalMaxAutoContinuations ?? null,\n noProgressLimit: settings.goalNoProgressLimit,\n // A model-policy block takes precedence: it is deterministic (a budget\n // pause can clear on its own; a policy pause needs a model/policy change)\n // and rides the same visible-pause channel.\n budgetBlocked: modelPolicyBlocked ?? budgetBlocked,\n policy: {\n model: continuationModel,\n reasoningEffort: continuationReasoningEffort,\n latencyMode: continuationLatencyMode,\n tools: withFirstPartyTools(settings, session.tools),\n sandboxBackend: session.sandboxBackend,\n },\n prompt: goalContinuationPrompt,\n });\n if (decision.events.length > 0) {\n await bus.publish(input.workspaceId, input.sessionId, decision.events);\n }\n return { action: decision.action };\n }\n\n return {\n enqueueGoalRetryWake,\n maybeContinueGoal,\n };\n}\n\nexport function goalContinuationPrompt(\n goal: SessionGoal,\n autoContinuation: number,\n cap: number | null,\n): string {\n const counter = cap === null ? `${autoContinuation}` : `${autoContinuation}/${cap}`;\n return [\n `[GOAL CONTINUATION ${counter}] The session goal is not done. Goal: ${goal.text}.`,\n `Success criteria: ${goal.successCriteria ?? \"none specified\"}.`,\n \"Continue from the existing conversation state. Do not repeat completed session setup, persistent metadata settings, or context checks merely because this is a new continuation turn.\",\n \"Continue working toward the goal now. If it is actually complete, call opengeni__goal_complete with concrete evidence.\",\n \"If you are blocked or continuing is not productive, call opengeni__goal_pause with your rationale.\",\n \"You may revise the goal with opengeni__goal_update. Do not stop without one of these explicit actions.\",\n ].join(\"\\n\");\n}\n\n/**\n * Ensures a session/turn carries the first-party \"opengeni\" MCP server, which\n * hosts set_session_title, the goal tools, and the permission-gated\n * orchestration/environment/github tools. Attached to EVERY session/turn (not\n * just goal-bearing ones); built-in tool refs are not auto-added to empty tool\n * lists anywhere else in the pipeline. No-op when the server is not configured.\n */\nexport function withFirstPartyTools(settings: Settings, tools: ToolRef[]): ToolRef[] {\n if (!settings.mcpServers.some((server) => server.id === \"opengeni\")) {\n return tools;\n }\n return mergeToolRefs(tools, [{ kind: \"mcp\", id: \"opengeni\" }]);\n}\n\n/**\n * Non-throwing variant of the scheduled-run admission check: returns a human\n * readable reason when balance or monthly caps block another agent run.\n */\nasync function goalRunBudgetBlocked(\n settings: Settings,\n db: Database,\n accountId: string,\n workspaceId: string,\n isCodexRun: boolean,\n): Promise<string | null> {\n // Codex-billed continuations are paid by the user's ChatGPT/Codex plan: skip\n // the credit-balance gate and the monthly model-cost cap. The agent-run COUNT\n // cap below is a volume quota (not a credit/cost gate) and is intentionally kept.\n if (\n !isCodexRun &&\n (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")\n ) {\n const balance = await getBillingBalance(db, accountId);\n if (balance.balanceMicros <= 0) {\n return \"insufficient OpenGeni credits\";\n }\n }\n if (settings.usageLimitsMode === \"static\" || settings.usageLimitsMode === \"managed\") {\n const limits = configuredStaticUsageLimits(settings);\n if (!isCodexRun && limits.maxMonthlyCostMicrosPerAccount) {\n const used = await sumUsageQuantity(db, {\n accountId,\n eventType: \"model.cost\",\n since: startOfUtcMonth(),\n });\n if (used >= limits.maxMonthlyCostMicrosPerAccount) {\n return `monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`;\n }\n }\n if (limits.maxMonthlyAgentRunsPerWorkspace) {\n const used = await sumUsageQuantity(db, {\n workspaceId,\n eventType: \"agent_run.created\",\n since: startOfUtcMonth(),\n });\n if (used + 1 > limits.maxMonthlyAgentRunsPerWorkspace) {\n return `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`;\n }\n }\n }\n return null;\n}\n\nfunction startOfUtcMonth(): Date {\n const now = new Date();\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));\n}\n","import type { Settings } from \"@opengeni/config\";\nimport { CapabilityPack } from \"@opengeni/contracts\";\nimport {\n getWorkspace,\n getWorkspacePack,\n listCapabilityInstallations,\n listPackInstallations,\n type Database,\n} from \"@opengeni/db\";\nimport {\n isSkillLibraryEntryId,\n loadSkillLibrarySkill,\n type EffectiveSkillSelection,\n type PackSkill,\n} from \"@opengeni/runtime\";\n\n/**\n * The pack-scoped runtime for a workspace: the sandbox image its sessions run\n * in (when an enabled pack declares one) and the pack skills that join the\n * sandbox skill index.\n */\nexport type WorkspacePackRuntime = {\n sandboxImage: string | null;\n sandboxProviderImages: CapabilityPack[\"sandboxProviderImages\"] | null;\n skills: PackSkill[];\n};\n\nconst emptyPackRuntime: WorkspacePackRuntime = {\n sandboxImage: null,\n sandboxProviderImages: null,\n skills: [],\n};\n\nexport type WorkspaceSkillLibraryRuntime = {\n skillLibrarySkills: PackSkill[];\n skillLibrarySelections: EffectiveSkillSelection[];\n};\n\ntype SkillLibraryInstallationMetadata = {\n libraryId: string;\n libraryVersion: string;\n contentSha256: string;\n sourceCommit: string;\n provenance: string;\n};\n\n/**\n * Resolves the pack-scoped runtime from the workspace's active pack\n * installations. Only registered (manifest-backed) packs can contribute a\n * sandbox image or skills; built-in packs never declare either (enforced by a\n * test on the built-in catalog), so their installations are skipped here\n * without consulting the API's built-in pack list.\n */\nexport async function resolveWorkspacePackRuntime(\n db: Database,\n workspaceId: string,\n): Promise<WorkspacePackRuntime> {\n const installations = await listPackInstallations(db, workspaceId);\n const active = installations.filter((installation) => installation.status === \"active\");\n if (active.length === 0) {\n return emptyPackRuntime;\n }\n const packs: CapabilityPack[] = [];\n for (const installation of active) {\n const registration = await getWorkspacePack(db, workspaceId, installation.packId);\n if (!registration) {\n continue;\n }\n const parsed = CapabilityPack.safeParse(registration.pack);\n if (parsed.success) {\n packs.push(parsed.data);\n }\n }\n return workspacePackRuntimeFromPacks(packs);\n}\n\n/**\n * Resolves active immutable curated skills separately from pack skills. The\n * capability installation is the workspace selection boundary; it carries\n * only secret-free exact identity metadata, and the runtime loader verifies\n * the pinned artifact hash before any content is materialized.\n */\nexport async function resolveWorkspaceSkillLibraryRuntime(\n db: Database,\n workspaceId: string,\n): Promise<WorkspaceSkillLibraryRuntime> {\n const installations = await listCapabilityInstallations(db, workspaceId);\n const activeSkills = installations\n .filter(\n (installation) =>\n installation.status === \"active\" &&\n installation.kind === \"skill\" &&\n installation.capabilityId.startsWith(\"skill:\") &&\n isSkillLibraryEntryId(installation.capabilityId.slice(\"skill:\".length)),\n )\n .sort((a, b) => a.capabilityId.localeCompare(b.capabilityId));\n const skillLibrarySkills: PackSkill[] = [];\n const skillLibrarySelections: EffectiveSkillSelection[] = [];\n for (const installation of activeSkills) {\n const metadata = parseSkillLibraryInstallationMetadata(\n installation.metadata,\n installation.capabilityId,\n );\n if (installation.capabilityId !== `skill:${metadata.libraryId}`) {\n throw new Error(\n `Skill installation id does not match its library entry: ${installation.capabilityId} -> ${metadata.libraryId}`,\n );\n }\n const loaded = loadSkillLibrarySkill(metadata.libraryId, metadata.libraryVersion);\n if (installation.config.version !== metadata.libraryVersion) {\n throw new Error(\n `Skill installation version mismatch for ${metadata.libraryId}@${metadata.libraryVersion}: config has ${String(installation.config.version)}`,\n );\n }\n if (loaded.entry.contentSha256 !== metadata.contentSha256) {\n throw new Error(\n `Skill installation hash mismatch for ${metadata.libraryId}@${metadata.libraryVersion}: expected ${metadata.contentSha256}, catalog has ${loaded.entry.contentSha256}`,\n );\n }\n if (\n loaded.entry.sourceCommit !== metadata.sourceCommit ||\n loaded.entry.provenance !== metadata.provenance\n ) {\n throw new Error(\n `Skill installation provenance mismatch for ${metadata.libraryId}@${metadata.libraryVersion}; re-enable the skill from the current catalog`,\n );\n }\n skillLibrarySkills.push({\n name: loaded.skill.name,\n description: loaded.skill.description,\n files: loaded.skill.files.map((file) => ({ path: file.path, content: file.content })),\n });\n skillLibrarySelections.push({\n id: loaded.entry.id,\n name: loaded.entry.name,\n source: \"library\",\n version: loaded.entry.version,\n contentSha256: loaded.entry.contentSha256,\n reason: \"enabled workspace capability installation\",\n });\n }\n return { skillLibrarySkills, skillLibrarySelections };\n}\n\nfunction parseSkillLibraryInstallationMetadata(\n metadata: Record<string, unknown>,\n capabilityId: string,\n): SkillLibraryInstallationMetadata {\n const libraryId = stringMetadata(metadata.libraryId);\n const libraryVersion = stringMetadata(metadata.libraryVersion);\n const contentSha256 = stringMetadata(metadata.contentSha256);\n const sourceCommit = stringMetadata(metadata.sourceCommit);\n const provenance = stringMetadata(metadata.provenance);\n if (!libraryId || !libraryVersion || !contentSha256 || !sourceCommit || !provenance) {\n throw new Error(\n `Skill installation ${capabilityId} is missing immutable library metadata; re-enable the skill from the current catalog`,\n );\n }\n return { libraryId, libraryVersion, contentSha256, sourceCommit, provenance };\n}\n\nfunction stringMetadata(value: unknown): string | null {\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : null;\n}\n\n/**\n * Pure composition rule for enabled pack manifests. v1 keeps this small by\n * design: at most one enabled pack may declare a sandbox image (no image\n * layering or composition), and skill names must be unique across enabled\n * packs. Violations fail the turn with a plain error instead of guessing.\n */\nexport function workspacePackRuntimeFromPacks(packs: CapabilityPack[]): WorkspacePackRuntime {\n const imagePacks = packs.filter(\n (pack) => typeof pack.sandboxImage === \"string\" && pack.sandboxImage.trim().length > 0,\n );\n if (imagePacks.length > 1) {\n const ids = imagePacks\n .map((pack) => pack.id)\n .sort()\n .join(\", \");\n throw new Error(\n `Multiple enabled packs declare a sandbox image (${ids}). Only one enabled pack per workspace may declare sandboxImage; disable the others and retry.`,\n );\n }\n const skills: PackSkill[] = [];\n // Keyed case-insensitively to match the per-pack uniqueness rule in the\n // CapabilityPack contract (and case-insensitive filesystems).\n const skillOwners = new Map<string, string>();\n for (const pack of [...packs].sort((a, b) => a.id.localeCompare(b.id))) {\n for (const skill of pack.skills) {\n const key = skill.name.toLowerCase();\n const existingOwner = skillOwners.get(key);\n if (existingOwner !== undefined && existingOwner !== pack.id) {\n throw new Error(\n `Enabled packs ${existingOwner} and ${pack.id} both declare a skill named \"${skill.name}\". Pack skill names must be unique across enabled packs; disable one of the packs and retry.`,\n );\n }\n skillOwners.set(key, pack.id);\n skills.push({\n name: skill.name,\n description: skill.description ?? null,\n files: skill.files.map((file) => ({ path: file.path, content: file.content })),\n });\n }\n }\n return {\n sandboxImage: imagePacks[0]?.sandboxImage?.trim() ?? null,\n sandboxProviderImages: imagePacks[0]?.sandboxProviderImages ?? null,\n skills,\n };\n}\n\n/**\n * Resolves the per-workspace agent persona override (the white-label surface).\n * Returns the workspace's stored template when set, else null to mean \"use the\n * deployment default\" (settings.agentInstructionsTemplate). The runtime always\n * injects the non-bypassable CORE regardless, so a null here keeps the\n * byte-identical default and a non-null value only restyles the persona.\n *\n * This is the workspace tier of the session > workspace > deployment-default\n * resolution; per-session overrides do not exist in this slice, so the worker\n * resolves workspace > default and passes the result as instructionsTemplate.\n */\nexport async function resolveWorkspaceAgentInstructions(\n db: Database,\n workspaceId: string,\n): Promise<string | null> {\n const workspace = await getWorkspace(db, workspaceId);\n return workspace?.agentInstructions ?? null;\n}\n\n/**\n * Applies a pack-declared sandbox image to run settings. With no pack image\n * the settings pass through untouched, so deployments without packs keep the\n * global OPENGENI_DOCKER_IMAGE / OPENGENI_MODAL_IMAGE_REF behavior exactly.\n */\nexport function settingsWithPackSandboxImage(\n settings: Settings,\n sandboxImage: string | null,\n sandboxProviderImages: CapabilityPack[\"sandboxProviderImages\"] | null = null,\n): Settings {\n if (!sandboxImage) {\n return settings;\n }\n return {\n ...settings,\n dockerImage: sandboxImage,\n modalImageRef: sandboxImage,\n modalImageId: sandboxProviderImages?.modal?.imageId,\n };\n}\n\n/**\n * Applies the session's frozen rig-version image to run settings. Rig image is\n * the TOP of the image precedence chain (rig > pack > deployment default): when\n * the rig version pins an image it OVERRIDES both the deployment\n * dockerImage/modalImageRef AND any pack-declared sandboxImage. When the rig\n * pins no image (`null`), the settings pass through untouched so the pack /\n * deployment chain below still resolves exactly as today. Applied AFTER\n * settingsWithPackSandboxImage so it wins the collision; identical mechanics to\n * the pack equivalent (write both image fields so docker and modal agree).\n */\nexport function settingsWithRigImage(settings: Settings, rigImage: string | null): Settings {\n if (!rigImage) {\n return settings;\n }\n return {\n ...settings,\n dockerImage: rigImage,\n modalImageRef: rigImage,\n // A rig image has no provider-native identity in the current rig contract.\n // Clear a lower-precedence pack/deployment ID so the rig cannot silently\n // run the wrong Modal image.\n modalImageId: undefined,\n };\n}\n\n/**\n * Layers the rig version's default variable sets BELOW the session's own set:\n * the session's values WIN on any key collision (explicit precedence). Both maps\n * are already the decrypted-and-merged values (rig defaults merged in listed\n * order upstream). Pure and deterministic — given the same inputs it returns the\n * same env, which is what keeps a session's box-manifest env stable across turns\n * (the rig version is frozen per session, so its default-set list is fixed).\n */\nexport function mergeRigDefaultVariableSetEnvironment(\n rigDefaultValues: Record<string, string>,\n sessionValues: Record<string, string>,\n): Record<string, string> {\n return { ...rigDefaultValues, ...sessionValues };\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { Session, SessionGoal, SessionSystemUpdatePayload } from \"@opengeni/contracts\";\nimport {\n getSession,\n getSessionGoal,\n getSessionParentPersonalConnectionDelegations,\n addSessionSystemUpdateWithSourceMutation,\n claimPendingSessionSystemUpdateOutbox,\n claimPendingSessionWorkflowWakes,\n getSessionSystemUpdateOutboxByDedupeKey,\n getOrCreateSessionSystemUpdateOutbox,\n markSessionWorkflowWakeFailed,\n markSessionSystemUpdateOutboxDeliveredInTransaction,\n markSessionSystemUpdateOutboxFailed,\n type Database,\n type SessionSystemUpdateOutboxDelivery,\n} from \"@opengeni/db\";\nimport type { EventBus } from \"@opengeni/events\";\nimport type { ActivityServices, WakeSessionWorkflowSignal } from \"./types\";\n\nexport type NotifyServices = {\n db: Database;\n bus: EventBus;\n settings: Settings;\n observability: ActivityServices[\"observability\"];\n wakeSessionWorkflow: WakeSessionWorkflowSignal | null;\n};\n\nexport type ReconcileParentSystemUpdateOverrides = Partial<{\n claimPendingSessionSystemUpdateOutbox: typeof claimPendingSessionSystemUpdateOutbox;\n}>;\n\nexport type ReconcileSessionWorkflowWakeOverrides = Partial<{\n claimPendingSessionWorkflowWakes: typeof claimPendingSessionWorkflowWakes;\n}>;\n\n/**\n * Enrich and deliver the durable idle-boundary row committed by\n * settleSessionIdleWithParentOutbox. Idle has no single owning turn, so its\n * stable episode identity is the newest non-status event sequence.\n */\nexport async function notifyParentOfChildIdle(\n svc: NotifyServices,\n workspaceId: string,\n childSessionId: string,\n episodeKey: string,\n): Promise<void> {\n try {\n const child = await getSession(svc.db, workspaceId, childSessionId);\n if (!child || !child.parentSessionId) {\n return;\n }\n const goal = await getSessionGoal(svc.db, workspaceId, childSessionId);\n // Sacred user pause: if the MANAGER's own goal was paused by the user, the\n // wake must not tell it to \"resume it now\" — that instruction is exactly\n // what re-arms the loop the user just stopped. Suppress the resume nudge and\n // tell the agent to stay paused. Paired with the goal_set reactivation\n // guard so a nudge that slips through still cannot revive the goal.\n const clientEventId = `child-completion:${childSessionId}:${episodeKey}`;\n const payload = childCompletionPayload(child, goal);\n const personalConnectionDelegations = await getSessionParentPersonalConnectionDelegations(\n svc.db,\n workspaceId,\n childSessionId,\n );\n const outbox = await getOrCreateSessionSystemUpdateOutbox(svc.db, {\n accountId: child.accountId,\n workspaceId,\n sourceSessionId: child.id,\n targetSessionId: child.parentSessionId,\n kind: \"child_terminal_result\",\n classification: goal?.status === \"paused\" ? \"action_required\" : \"success\",\n sourceId: child.id,\n dedupeKey: clientEventId,\n summary: childCompletionSummary(child, goal, \"idle\"),\n payload,\n lineage: { childSessionId: child.id, parentSessionId: child.parentSessionId },\n personalConnectionDelegations,\n });\n if (outbox.status === \"delivered\") {\n return;\n }\n await deliverParentSystemUpdateOutbox(svc, outbox);\n } catch (error) {\n // A durable pending outbox row survives this boundary. The global worker\n // reaper retries it; child terminal settlement never depends on this turn.\n svc.observability.error(\"Failed to wake parent session on worker idle boundary\", {\n childSessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Deliver the exact failure row already committed by turn settlement. This\n * layer deliberately cannot create or rewrite the row: the settlement\n * transaction is the sole owner of the failed turn id, payload, and lineage.\n */\nexport async function deliverFailedChildTurnToParent(\n svc: NotifyServices,\n workspaceId: string,\n childSessionId: string,\n turnId: string,\n): Promise<void> {\n try {\n const child = await getSession(svc.db, workspaceId, childSessionId);\n if (!child || !child.parentSessionId) return;\n const dedupeKey = `child-completion:${childSessionId}:turn:${turnId}`;\n const outbox = await getSessionSystemUpdateOutboxByDedupeKey(svc.db, {\n accountId: child.accountId,\n workspaceId,\n dedupeKey,\n });\n if (!outbox) {\n throw new Error(`Committed failed-child outbox disappeared: ${dedupeKey}`);\n }\n if (outbox.status === \"delivered\") return;\n await deliverParentSystemUpdateOutbox(svc, outbox);\n } catch (error) {\n // Settlement already committed the retryable outbox row. The global\n // reconciler remains the recovery path if immediate delivery fails.\n svc.observability.error(\"Failed to deliver committed child-turn failure\", {\n childSessionId,\n turnId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nasync function deliverParentSystemUpdateOutbox(\n svc: NotifyServices,\n outbox: SessionSystemUpdateOutboxDelivery,\n): Promise<void> {\n try {\n const result = await addSessionSystemUpdateWithSourceMutation(\n svc.db,\n {\n accountId: outbox.accountId,\n workspaceId: outbox.workspaceId,\n sessionId: outbox.targetSessionId,\n kind: outbox.kind,\n classification: outbox.classification,\n sourceId: outbox.sourceId,\n dedupeKey: outbox.dedupeKey,\n summary: outbox.summary,\n payload: outbox.payload,\n lineage: outbox.lineage,\n personalConnectionDelegations: outbox.personalConnectionDelegations,\n },\n async (tx) => {\n await markSessionSystemUpdateOutboxDeliveredInTransaction(tx, outbox);\n },\n );\n if (result.reason === \"session_cancelled\") {\n return;\n }\n if (result.added && result.events.length > 0) {\n await svc.bus.publish(outbox.workspaceId, outbox.targetSessionId, result.events);\n }\n if (result.shouldWake && svc.wakeSessionWorkflow) {\n if (result.workflowWakeRevision === null) {\n throw new Error(\"Runnable system update has no workflow wake revision\");\n }\n await svc.wakeSessionWorkflow({\n accountId: outbox.accountId,\n workspaceId: outbox.workspaceId,\n sessionId: outbox.targetSessionId,\n workflowId: result.temporalWorkflowId ?? `session-${outbox.targetSessionId}`,\n wakeRevision: result.workflowWakeRevision,\n });\n }\n svc.observability.info(\"Woke parent session on worker completion\", {\n childSessionId: outbox.sourceSessionId,\n parentSessionId: outbox.targetSessionId,\n dedupeKey: outbox.dedupeKey,\n });\n } catch (error) {\n await markSessionSystemUpdateOutboxFailed(\n svc.db,\n outbox,\n error instanceof Error ? error.message : String(error),\n ).catch(() => undefined);\n throw error;\n }\n}\n\nexport async function reconcilePendingParentSystemUpdates(\n svc: NotifyServices,\n limit = 100,\n overrides: ReconcileParentSystemUpdateOverrides = {},\n): Promise<{ claimed: number; delivered: number; failed: number }> {\n const claimPendingSessionSystemUpdateOutboxFn =\n overrides.claimPendingSessionSystemUpdateOutbox ?? claimPendingSessionSystemUpdateOutbox;\n const rows = await claimPendingSessionSystemUpdateOutboxFn(svc.db, limit);\n let delivered = 0;\n let failed = 0;\n for (const row of rows) {\n try {\n await deliverParentSystemUpdateOutbox(svc, row);\n delivered += 1;\n } catch {\n failed += 1;\n }\n }\n return { claimed: rows.length, delivered, failed };\n}\n\nexport async function reconcilePendingSessionWorkflowWakes(\n svc: NotifyServices,\n limit = 1_000,\n overrides: ReconcileSessionWorkflowWakeOverrides = {},\n): Promise<{ claimed: number; delivered: number; failed: number }> {\n const claimPendingSessionWorkflowWakesFn =\n overrides.claimPendingSessionWorkflowWakes ?? claimPendingSessionWorkflowWakes;\n if (!svc.wakeSessionWorkflow) {\n return { claimed: 0, delivered: 0, failed: 0 };\n }\n const repairs = await claimPendingSessionWorkflowWakesFn(svc.db, limit);\n let delivered = 0;\n let failed = 0;\n const queue = [...repairs];\n const workers = Array.from({ length: Math.min(20, queue.length) }, async () => {\n for (;;) {\n const repair = queue.shift();\n if (!repair) return;\n try {\n await svc.wakeSessionWorkflow!({\n accountId: repair.accountId,\n workspaceId: repair.workspaceId,\n sessionId: repair.sessionId,\n workflowId: repair.temporalWorkflowId,\n wakeRevision: repair.wakeRevision,\n ...(repair.interruptionRequested ? { interruptionRequested: true } : {}),\n });\n delivered += 1;\n } catch (error) {\n failed += 1;\n await markSessionWorkflowWakeFailed(\n svc.db,\n repair,\n error instanceof Error ? error.message : String(error),\n ).catch(() => undefined);\n }\n }\n });\n await Promise.all(workers);\n return { claimed: repairs.length, delivered, failed };\n}\n\nfunction childCompletionPayload(\n child: Session,\n goal: SessionGoal | null,\n): Extract<SessionSystemUpdatePayload, { type: \"child_terminal_result\" }> {\n return {\n type: \"child_terminal_result\",\n childSessionId: child.id,\n status: \"idle\",\n ...(goal\n ? {\n goal: {\n status: goal.status,\n text: goal.text,\n ...(goal.evidence ? { evidence: goal.evidence } : {}),\n ...(goal.rationale ? { rationale: goal.rationale } : {}),\n ...(goal.pausedReason ? { pausedReason: goal.pausedReason } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * The worker-specific lines for one child (what happened + its goal), WITHOUT\n * the trailing \"what to do next\" instruction. Kept separate so N child\n * completions can be coalesced into one internal-update inference: the DB layer\n * stores each child's summary and rebuilds a single numbered digest with one\n * shared trailing instruction instead of running N model calls.\n */\nexport function childCompletionSummary(\n child: Session,\n goal: SessionGoal | null,\n terminalStatus: \"idle\" | \"failed\",\n): string {\n const lines: string[] = [];\n if (terminalStatus === \"failed\") {\n lines.push(`A worker session you spawned has FAILED. Worker session id: ${child.id}.`);\n } else if (goal?.status === \"completed\") {\n lines.push(\n `A worker session you spawned has COMPLETED its goal. Worker session id: ${child.id}.`,\n );\n } else if (goal?.status === \"paused\") {\n lines.push(\n `A worker session you spawned has PAUSED its goal and gone idle. Worker session id: ${child.id}.`,\n );\n } else {\n lines.push(\n `A worker session you spawned has finished its work and gone idle. Worker session id: ${child.id}.`,\n );\n }\n if (goal) {\n lines.push(`Worker goal: ${goal.text}`);\n if (goal.status === \"completed\" && goal.evidence) {\n lines.push(`Completion evidence: ${goal.evidence}`);\n }\n if (goal.status === \"paused\" && goal.rationale) {\n lines.push(`Pause rationale: ${goal.rationale}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * The single trailing instruction appended to a child-completion (or digest)\n * inference. Suppresses the \"resume it now\" nudge when the manager's own goal\n * was paused by the user (paired with the goal_set reactivation guard).\n */\nexport function childCompletionTrailing(parentGoalUserPaused: boolean): string {\n return parentGoalUserPaused\n ? \"Read each worker's session events/notebook output for its result. This session was paused by the user — do NOT resume or replace your goal; summarize the result for the user and remain paused.\"\n : \"Read each worker's session events/notebook output for its result, then continue. If your own goal was paused awaiting these workers, resume it now.\";\n}\n","export {\n createSecretRedactor,\n identityRedactor,\n isCredentialHeaderName,\n redactSensitiveData,\n redactSensitiveText,\n redactSerializedJson,\n type SecretForRedaction,\n} from \"@opengeni/contracts\";\n","import type { SessionEventType } from \"@opengeni/contracts\";\nimport type { AppendEventInput } from \"@opengeni/db\";\nimport { Context } from \"@temporalio/activity\";\n\n// Trailing-flush window. A burst of coalesced deltas followed by model silence\n// must not sit in `pending` unbounded — without a timer, flush fires only on\n// the NEXT push. Matched to the 33ms coalesce window so the client-visible\n// latency added by batching is bounded to ~one window (imperceptible, and far\n// cheaper than the per-delta DB round-trip it replaces).\nconst TRAILING_FLUSH_MS = 33;\nconst MAX_BATCH_EVENTS = 50;\n// Keep model ingestion independent from a slow durable append, but never let a\n// provider outrun storage without bound. At the high-water mark `push` waits for\n// the serialized drain before consuming more provider output.\nconst MAX_BUFFERED_EVENTS = 1_000;\n\n/** Optional metrics seam for the batcher. `onFlush` fires once per flush (on both\n * success and failure) with the coalesced event count and the flush duration, so\n * the worker can meter batch shape without the batcher knowing about Observability.\n * `now` is injectable for deterministic tests. Both are optional; absent ⇒ no-op. */\nexport type RuntimeBatcherOptions = {\n onFlush?: (info: { events: number; durationSeconds: number }) => void;\n now?: () => number;\n};\n\nexport function createRuntimeBatcher(\n flushEvents: (events: AppendEventInput[]) => Promise<void>,\n options: RuntimeBatcherOptions = {},\n) {\n const now = options.now ?? (() => performance.now());\n let pending: AppendEventInput[] = [];\n let lastFlush = Date.now();\n let trailingTimer: ReturnType<typeof setTimeout> | null = null;\n let activeBatchSize = 0;\n // One drain loop owns `flushEvents`, so DB-assigned sequence order always\n // matches push order. Ordinary deltas do not await this promise; structural\n // boundaries, explicit flushes, and the bounded high-water mark do.\n let drainPromise: Promise<void> | null = null;\n // A timer has no direct awaiter. Retain its failure so the next push or final\n // flush terminates the turn instead of silently losing streamed evidence.\n let flushFailed = false;\n let flushFailure: unknown;\n // The high-volume token deltas (agent.message.delta, agent.reasoning.delta,\n // sandbox.command.output.delta) are DELIBERATELY NOT here: they coalesce\n // under the 50-event / 33ms policy into one appendSessionEvents txn + one\n // publish per flush, instead of one DB round-trip per token. Only events that\n // must be delivered promptly stay structural (flush-immediately). PTY bytes\n // stay structural on purpose — an interactive terminal is useless batched\n // 33ms behind (P4.4).\n const structural = new Set<SessionEventType>([\n \"terminal.pty.output.delta\",\n \"agent.toolCall.created\",\n \"agent.toolCall.output\",\n \"agent.message.completed\",\n \"tool.auth_needed\",\n \"credential.auth_needed\",\n \"session.requiresAction\",\n \"turn.completed\",\n \"turn.failed\",\n \"turn.cancelled\",\n ]);\n return {\n push: async (event: { type: SessionEventType; payload: unknown }) => {\n throwIfFlushFailed();\n // Append BEFORE the structural check so a structural event's flush always\n // carries any pending deltas in order (same flush, order preserved).\n pending.push({ type: event.type, payload: event.payload });\n const elapsed = Date.now() - lastFlush;\n if (structural.has(event.type)) {\n await flush();\n return;\n }\n if (pending.length >= MAX_BATCH_EVENTS || elapsed >= TRAILING_FLUSH_MS) {\n // Start the serialized drain, but keep consuming provider deltas while\n // the append/publish round-trip is in flight. The active drain records\n // any failure for the next awaited boundary.\n void startDrain().catch(() => undefined);\n }\n if (activeBatchSize + pending.length >= MAX_BUFFERED_EVENTS) {\n await flush();\n return;\n }\n armTrailingTimer();\n },\n flush,\n };\n\n function armTrailingTimer() {\n if (trailingTimer !== null) {\n return;\n }\n trailingTimer = setTimeout(() => {\n trailingTimer = null;\n // A timer has no awaiter, so prevent an unhandled rejection. startDrain\n // retains the exact error and the next push/final flush rethrows it.\n void flush().catch(() => undefined);\n }, TRAILING_FLUSH_MS);\n if (\"unref\" in trailingTimer && typeof trailingTimer.unref === \"function\") {\n trailingTimer.unref();\n }\n }\n\n function clearTrailingTimer() {\n if (trailingTimer !== null) {\n clearTimeout(trailingTimer);\n trailingTimer = null;\n }\n }\n\n async function flush(): Promise<void> {\n throwIfFlushFailed();\n clearTrailingTimer();\n await startDrain();\n throwIfFlushFailed();\n }\n\n function startDrain(): Promise<void> {\n if (drainPromise) {\n return drainPromise;\n }\n if (flushFailed) {\n return Promise.reject(flushFailure);\n }\n if (pending.length === 0) {\n return Promise.resolve();\n }\n clearTrailingTimer();\n const running = (async () => {\n while (pending.length > 0) {\n const events = pending.splice(0, MAX_BATCH_EVENTS);\n activeBatchSize = events.length;\n lastFlush = Date.now();\n const startedAt = now();\n try {\n await flushEvents(events);\n } catch (error) {\n flushFailed = true;\n flushFailure = error;\n throw error;\n } finally {\n activeBatchSize = 0;\n if (options.onFlush) {\n try {\n options.onFlush({\n events: events.length,\n durationSeconds: Math.max(0, (now() - startedAt) / 1000),\n });\n } catch {\n // Metrics emission must never affect a flush.\n }\n }\n }\n }\n })();\n drainPromise = running.finally(() => {\n drainPromise = null;\n });\n return drainPromise;\n }\n\n function throwIfFlushFailed(): void {\n if (flushFailed) {\n throw flushFailure;\n }\n }\n}\n\nexport function currentActivityContext(): Context | null {\n try {\n return Context.current();\n } catch {\n return null;\n }\n}\n\nexport function startActivityHeartbeat(\n context: Context | null,\n details: Record<string, unknown>,\n): ReturnType<typeof setInterval> | null {\n if (!context) {\n return null;\n }\n const timer = setInterval(() => {\n context.heartbeat({ ...details, at: new Date().toISOString() });\n }, 10_000);\n if (\"unref\" in timer && typeof timer.unref === \"function\") {\n timer.unref();\n }\n return timer;\n}\n\nexport async function nextStreamEvent<T>(\n iterator: AsyncIterator<T>,\n context: Context | null,\n): Promise<IteratorResult<T>> {\n if (!context) {\n return await iterator.next();\n }\n return await Promise.race([iterator.next(), context.cancelled]);\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type {\n ConnectionCredentialsPort,\n DocumentAuthorityKind,\n EntitlementsPort,\n ScheduledTaskTriggerType,\n TurnInitiator,\n} from \"@opengeni/contracts\";\nimport type { Database } from \"@opengeni/db\";\nimport type { DocumentServices } from \"@opengeni/documents\";\nimport type { EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport type { OpenGeniRuntime } from \"@opengeni/runtime\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\n\n// Signal (start-if-needed) a session's Temporal workflow so a queued turn it\n// cannot otherwise observe gets claimed. Used to wake a PARENT session's\n// workflow when a spawned worker completes: the parent may have idled and let\n// its workflow run complete, so a plain signal would not start one — this must\n// signalWithStart. Injected (not built from the worker's NativeConnection)\n// because the worker package owns only the worker runtime, not a client; an\n// missing signaler leaves the committed outbox revision for the global repair\n// sweep; production workers always inject this dependency.\nexport type WakeSessionWorkflowSignal = (input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n wakeRevision: number;\n interruptionRequested?: boolean;\n}) => Promise<void>;\n\nexport type SignalCodexCapacityWorkflow = (input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n wakeRevision: number;\n}) => Promise<void>;\n\n/** Exact activity-owned proof that the hard sandbox/tool fence physically\n * drained. This is delivery evidence only: the workflow still validates the\n * persisted attempt dispatch and commits the authoritative Postgres receipt. */\nexport type SessionAttemptQuiescenceProof = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n workflowId: string;\n workflowRunId: string;\n activityId: string;\n};\n\nexport type SignalSessionAttemptQuiesced = (input: SessionAttemptQuiescenceProof) => Promise<void>;\n\nexport type InspectSessionAttemptActivity = (input: {\n workflowId: string;\n workflowRunId: string;\n activityId: string;\n}) => Promise<\"pending\" | \"settled\">;\n\nexport type ActivityServices = {\n settings: Settings;\n db: Database;\n bus: EventBus;\n runtime: OpenGeniRuntime;\n objectStorage: ObjectStorage | null;\n documentServices: DocumentServices;\n observability: Observability;\n wakeSessionWorkflow: WakeSessionWorkflowSignal | null;\n /** Durable signalWithStart fallback used only after the activity's direct\n * physical-quiescence receipt write exhausts its bounded DB retries. */\n signalSessionAttemptQuiesced: SignalSessionAttemptQuiesced | null;\n /** Server-authoritative Temporal activity lease inspection used only to\n * recover a missing quiescence receipt after the original activity vanished. */\n inspectSessionAttemptActivity: InspectSessionAttemptActivity | null;\n /** Revision-carrying capacity nudge; generic outbox repair is also sufficient. */\n signalCodexCapacityWorkflow?: SignalCodexCapacityWorkflow | null;\n // §7.5 P3 — host-entitlements port, the WORKER half of the same seam the API\n // edge exposes on `AppDependencies`. When set, `ensureRunAllowed` (turn-entry\n // AND the mid-stream budget valve) delegates the funding decision to\n // `admitRun` instead of reading `getBillingBalance` locally. null/undefined\n // (standalone default) → today's local-ledger read runs unchanged.\n //\n // IDEMPOTENCY: the worker calls `admitRun` ONLY as an admission READ (\"may\n // this run/continue?\"), never to RECORD consumption. Usage is recorded\n // exactly once, by `recordUsageEvent` keyed on a deterministic idempotency\n // key the API already wrote at create-time — so a host PULL meter that also\n // observes that same recorded event is consulted without double-charging:\n // admission and metering are separate operations, and only metering carries\n // the idempotency key.\n entitlements?: EntitlementsPort | null;\n // §7.6 connection-credential provider — host connection-credential provider, the WORKER half of the\n // federated-connection boundary. When set, the run's per-run credential mint\n // delegates to the host instead of self-minting from `settings`:\n // - `gitCredentials` REPLACES `createGitHubAppInstallationToken(settings,…)`\n // in `sandboxEnvironmentForRun` (the GH_TOKEN / git-extraheader source).\n // - `sandboxSecrets` REPLACES the `environmentsEncryptionKeyBytes(settings)`\n // decrypt in `loadWorkspaceEnvironmentForRun`.\n // Each leg is independently optional; an unset leg falls through to today's\n // self-mint for THAT leg. null/undefined (standalone default) → both legs\n // self-mint byte-for-byte as today.\n //\n // workspace-scope cross-check CROSS-CHECK: a provider echoes the `workspaceId` it scoped the\n // credential to; the consuming activity ASSERTS agreement with the run's\n // workspace BEFORE injecting `GH_TOKEN` (or applying decrypted values). A host\n // mapping bug returning tenant B's creds for a tenant-A run is caught here.\n connectionCredentials?: ConnectionCredentialsPort | null;\n};\n\nexport type CodexCapacityWaitRef = {\n waiterId: string;\n generation: number;\n nextCheckAt: string;\n wakeRevision: number;\n};\n\nexport type GetCodexCapacityWaitInput = {\n workspaceId: string;\n sessionId: string;\n};\n\nexport type ReconcileCodexCapacityWaitInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n waiterId: string;\n generation: number;\n cause: \"timer\" | \"signal\" | \"queue\" | \"recovery\";\n};\n\nexport type ReconcileCodexCapacityWaitResult =\n | ({ action: \"waiting\" } & CodexCapacityWaitRef)\n | { action: \"resumed\" | \"paused\" | \"superseded\" | \"stale\" };\n\nexport type ActivityDependencies = Partial<ActivityServices>;\n\nexport type RunAgentTurnInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n workflowRunId: string;\n attemptId: string;\n trigger: { kind: \"next\" } | { kind: \"approval\"; triggerEventId: string };\n};\n\nexport type SettleSessionInterruptionsInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n workflowId: string;\n /**\n * Replay-only compatibility for session workflow histories created before\n * the receipt-gated cancellation v2 patch. New histories never send this\n * phase; the exact activity writes the authoritative receipt itself.\n */\n phase?: \"logical\" | \"attempt_quiesced\";\n};\n\nexport type PersistSessionAttemptQuiescenceInput = SessionAttemptQuiescenceProof;\n\nexport type ReconcileSessionAttemptQuiescenceInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n workflowId: string;\n};\n\nexport type ReconcileSessionAttemptQuiescenceResult = {\n action: \"quiesced\" | \"pending\" | \"stale\";\n};\n\nexport type FailSessionAttemptInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n error?: string;\n};\n\nexport type RecoverDispatchInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n timeoutType: \"HEARTBEAT\" | \"SCHEDULE_TO_START\";\n};\n\nexport type RecoverDispatchResult =\n // The same current inference is now recoverable. It never enters the prompt\n // queue; the next claim creates a new attempt for this exact turn.\n | { action: \"unclaimed\" }\n | { action: \"recovering\"; turnId: string; redispatches: number }\n // The turn is no longer running/requires_action: the timed-out attempt was\n // a zombie that actually settled the turn after the server gave up on its\n // heartbeats. Nothing to redo; the workflow just continues its loop.\n | { action: \"stale\" }\n // The per-turn crash-loop guard tripped; the workflow must fail the\n // session for real. `redispatches` is the count already consumed (== the\n // ceiling), so the failed attempt was worker death number redispatches + 1.\n | { action: \"exceeded\"; turnId: string; redispatches: number };\n\nexport const ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_TYPE = \"EscapedMcpTimeoutRecoveryFailure\";\nexport const ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_MESSAGE =\n \"MCP request timeout recovery checkpoint failed before model request\";\n\nexport type EscapedMcpTimeoutRecoveryDetail = {\n turnId: string;\n triggerEventId: string;\n executionGeneration: number;\n};\n\nexport type RecoverEscapedMcpTimeoutInput = EscapedMcpTimeoutRecoveryDetail & {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n};\n\nexport type RecoverEscapedMcpTimeoutResult = {\n action: \"recovering\" | \"stale\" | \"ineligible\";\n};\n\nexport type PeekSessionWorkInput = {\n workspaceId: string;\n sessionId: string;\n};\n\nexport type ExpireSessionHumanInputInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n requestId: string;\n};\n\nexport type ExpireSessionHumanInputResult = {\n action: \"expired\" | \"stale\" | \"not_found\";\n};\n\nexport type MarkSessionIdleInput = {\n workspaceId: string;\n sessionId: string;\n};\n\nexport type MaybeContinueGoalInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n};\n\nexport type MaybeContinueGoalResult = {\n action: \"none\" | \"queue\" | \"continue\" | \"paused\";\n};\n\nexport type DispatchScheduledTaskRunInput = {\n workspaceId: string;\n taskId: string;\n /** Stable Temporal workflow identity; retries must reuse the same source row. */\n producerKey?: string;\n} & (\n | {\n triggerType: Extract<ScheduledTaskTriggerType, \"scheduled\">;\n agentRunUsageIdempotencyKey?: never;\n initiator?: never;\n }\n | {\n triggerType: Extract<ScheduledTaskTriggerType, \"manual\">;\n agentRunUsageIdempotencyKey: string;\n /** Exact identity used by the API-side charge for this same trigger. */\n initiator: TurnInitiator;\n }\n);\n\nexport type DispatchScheduledTaskRunResult =\n | { action: \"deleted\" }\n | {\n action: \"blocked\";\n reason:\n | \"insufficient_credits\"\n | \"monthly_model_cost_limit\"\n | \"monthly_agent_run_limit\"\n | \"malformed_manual_trigger\";\n }\n | {\n action: \"start\" | \"signal\";\n accountId: string;\n workspaceId: string;\n sessionId: string;\n triggerEventId: string;\n workflowId: string;\n workflowWakeRevision: number | null;\n };\n\ntype DocumentIndexIdentity = {\n accountId: string;\n workspaceId: string;\n documentId: string;\n};\n\ntype CurrentDocumentIndexAuthority = {\n authorityKind: DocumentAuthorityKind;\n authorityWorkspaceId: string | null;\n authoritySubjectId: string | null;\n};\n\ntype HistoricalDocumentIndexAuthority = {\n authorityKind?: never;\n authorityWorkspaceId?: never;\n authoritySubjectId?: never;\n};\n\nexport type IndexDocumentInput = DocumentIndexIdentity &\n (CurrentDocumentIndexAuthority | HistoricalDocumentIndexAuthority);\n\ntype ClaimedRunAgentTurnResult = {\n // \"recovering\": this attempt ended after durably preserving the same current\n // inference for a new attempt. Recovery is not prompt queue work.\n status: \"idle\" | \"requires_action\" | \"failed\" | \"cancelled\" | \"recovering\" | \"waiting_capacity\";\n turnId: string;\n attemptId: string;\n // Provider backpressure pacing: when set on an idle or recovering result, the\n // session workflow holds the loop this long before admitting the next attempt.\n continueDelayMs?: number;\n // Multi-account rotation all-capped idle: every connected Codex subscription is\n // rate-limited/cooling. This is a MANDATORY hold — session.ts must wait\n // continueDelayMs (floored to a minimum) and must NOT treat a 0/elapsed delay as\n // \"continue now\" (invariant 4: NO THRASH). Distinct from a normal continueDelayMs:0\n // which legitimately means \"a rotation candidate is ready, re-dispatch immediately\".\n idleUntilReset?: boolean;\n // Durable native zero-pool wait for this same nonterminal logical turn.\n // Unlike continueDelayMs, this reference is persisted in Postgres and\n // reconstructed after workflow/worker restart. The workflow must not call\n // maybeContinueGoal or manufacture queue/input work while it is active.\n capacityWait?: CodexCapacityWaitRef;\n // This execution reached a durable terminal-for-now boundary (for example,\n // maintenance could not run or same-turn context recovery failed). End this\n // workflow run without synthesizing another goal continuation from unchanged\n // state. A later prompt/control/new-update wake may retry through normal claim\n // ordering.\n deferredUntilWake?: boolean;\n};\n\nexport type RunAgentTurnResult =\n | ClaimedRunAgentTurnResult\n | {\n status: \"unclaimed\";\n reason: \"gate-closed\" | \"no-work\" | \"stale-approval\" | \"control-pending\";\n };\n","// apps/worker/src/sandbox-resume.ts — the stateless per-turn resume-by-id path.\n//\n// This is the turn-side half of the P1.2 ownership inversion. There is NO class,\n// NO timers, NO per-session owner, NO Map<id, owner> — every turn is a\n// self-contained critical section run by ANY pool worker:\n//\n// 1. acquireLease (group-keyed) under the DB FOR UPDATE + cold->warming CAS —\n// the SOLE double-spawn guard (P1.1).\n// 2. The cold->warming winner may create/restore. Every attached caller is\n// resume-only; a missing provider box retires the exact warm epoch and\n// re-enters admission instead of creating a rival.\n// 3. (spawner) commitWarmingToWarm (the lease_epoch++ fence + folds the resume\n// envelope onto the lease). Optional desktop work is deliberately absent:\n// the viewer and the first actual computer-use action initialize :0 lazily.\n// 4. the caller injects {client, session, sessionState} NON-OWNED into the run\n// (the SDK never reaps it — the keystone), runs, then in `finally` calls the\n// returned `release()` and drops the in-memory handle. NEVER provider-delete\n// — the box rides the provider idle-timeout; the reaper (P1.3) stop()s it at\n// refcount 0.\n//\n// Liveness between turns is the lease refcount; there is no keepalive loop.\n\nimport { sandboxArchiveCaptureTimeoutMs, type Settings } from \"@opengeni/config\";\nimport { redactSensitiveText } from \"@opengeni/contracts\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n acquireLease,\n adoptLegacyModalCheckpointArtifact,\n beginSandboxRematerialization,\n claimWorkspaceArchiveCapture,\n commitWarmingToWarm,\n failSandboxRematerialization,\n failWarmingToCold,\n getSandboxSessionEnvelope,\n markSandboxRestoreVerifying,\n markWarmLeaseInstanceLost,\n markSandboxCheckpointArtifactDeletePending,\n persistWarmSnapshot,\n readLease,\n registerSandboxCheckpointArtifact,\n recordWarmingSandboxCreated,\n releaseWorkspaceArchiveCapture,\n releaseLeaseHolder,\n touchLeaseHolder,\n SandboxLeaseRecoveryBlockedError,\n SandboxLeaseSupersededError,\n type Database,\n type LeaseHolderKind,\n} from \"@opengeni/db\";\nimport {\n captureVerifiedWorkspaceArchive,\n describeLegacyNativeSnapshotArchive,\n WorkspaceArchiveIntegrityError,\n establishSandboxSessionFromEnvelope,\n isProviderSandboxNotFoundError,\n parseWorkspaceArchiveDescriptor,\n requirePersistableReplacementSandboxEnvelope,\n modalSessionMatchesCheckpointProviderBinding,\n resolveModalCheckpointProviderBindingForSession,\n serializeReplacementSandboxEnvelope,\n tagModalSandbox,\n verifySandboxExecReadiness,\n type EstablishedSandboxSession,\n type RuntimeMetricsHooks,\n type WorkspaceArchiveDescriptor,\n} from \"@opengeni/runtime\";\n\n// Re-exported for callers that just want the ack-kind union.\nexport type ResumeHolderKind = LeaseHolderKind;\n\n/**\n * The durable identity of a turn holding a shared sandbox lease.\n *\n * Temporal activity ids cannot satisfy this type: they are workflow-local\n * sequence numbers and collide across sessions that share a sandbox group.\n */\nexport type TurnSandboxLeaseHolderId = `turn-attempt:${string}`;\n\nexport function sandboxLeaseHolderIdForAttempt(attemptId: string): TurnSandboxLeaseHolderId {\n const normalized = attemptId.trim();\n if (!normalized) {\n throw new Error(\"Sandbox lease holder requires a turn attempt id\");\n }\n return `turn-attempt:${normalized}`;\n}\n\nexport function isRetryableDegradedRestore(restore: {\n status: string;\n retryable?: boolean;\n}): boolean {\n return restore.status === \"degraded\" && restore.retryable === true;\n}\n\n/** The minimal services surface resumeBoxForTurn needs. A subset of\n * ActivityServices so a test (and the API later) can pass a lean bag. */\nexport type SandboxResumeServices = {\n db: Database;\n settings: Settings;\n sandboxMetrics?: RuntimeMetricsHooks;\n /**\n * The logical turn-attempt lifetime, not merely the provider request lifetime.\n * Some provider SDK calls cannot be interrupted. Aborting this signal still\n * releases the durable holder immediately and fences any late provider result.\n */\n cancellationSignal?: AbortSignal;\n /** Test seam for the attached/resumed path. Production uses the one runtime\n * resume primitive; callers must not use this to create a replacement box. */\n establishAttachedSandbox?: typeof establishSandboxSessionFromEnvelope;\n /** Test seam for the bounded command-readiness proof performed before an\n * attached provider box is handed to the agent. */\n verifyAttachedSandboxReadiness?: (established: EstablishedSandboxSession) => Promise<void>;\n /** Called only by the observer that wins the exact warm->cold loss CAS. */\n onSandboxLost?: (input: {\n sandboxGroupId: string;\n instanceId: string;\n leaseEpoch: number;\n }) => Promise<void>;\n};\n\nexport type ResumeBoxIds = {\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n /** The attributing session within the group (holders carry session_id for\n * disclosure/attribution). For a singleton group this == sandboxGroupId. */\n sessionId: string;\n /** The backend the box runs on (sessions.sandbox_backend). */\n backend: string;\n /** The OS axis (sessions.sandbox_os); default 'linux'. */\n os?: string;\n /**\n * The FULL environment the agent will declare for this run (the SAME object\n * passed to runtime.buildAgent's `sandboxEnvironment`). The box's manifest is\n * created with this environment so that when the SDK applies the agent's\n * manifest to this NON-OWNED provided session, the environments match exactly\n * and `validateNoEnvironmentDelta` finds an empty delta (otherwise it throws\n * \"Live sandbox sessions cannot change manifest environment variables\" and the\n * turn dies). Omitted → the leaf falls back to collectSandboxEnvironment(settings)\n * (the legacy default; only the resume/spawn-without-an-agent callers rely on it).\n */\n environment?: Record<string, string>;\n /**\n * IMAGE IS SHARED STATE (B3): the container image this run resolves (Modal image ref\n * / docker image). Threaded to acquireLease, which stamps it on the cold-create and\n * conflicts on a live box already running a DIFFERENT image (a solo holder requests\n * capture-and-drain rotation; N-holders throw SandboxImageConflictError). Omitted ->\n * image is not enforced (the selfhosted path never passes it; a legacy/null-image box\n * never conflicts).\n */\n image?: string;\n /**\n * RIG IS SHARED STATE (M3): the frozen rig version this run rides. Threaded to\n * acquireLease, which stamps it on the cold-create and conflicts on a live box\n * set up under a DIFFERENT rig version (a solo holder requests capture-and-drain\n * rotation; N-holders throw SandboxRigConflictError). Omitted for a rig-less\n * session -> rig is never stamped or enforced (shares exactly as today).\n */\n rigVersionId?: string;\n};\n\n/** What resumeBoxForTurn returns: the live NON-OWNED session to inject, the\n * fence token (lease_epoch) it was established under, and a release function\n * the caller invokes in `finally` (idempotent delete-my-holder-row). */\nexport type ResumedTurnSandbox = {\n /** The live, externally-owned session — inject {client, session, sessionState}\n * NON-OWNED into runStream's `ownedSandbox`; the SDK never reaps it. */\n established: EstablishedSandboxSession;\n /** The lease_epoch this turn holds; the heartbeat/fence token. */\n leaseEpoch: number;\n /** Idempotent release: deletes this holder row and (if refcount hits 0 with no\n * turn holders) CASes warm->draining. NEVER stops the box. Safe to call once. */\n release: () => Promise<void>;\n};\n\nexport class SandboxWarmingTimeoutError extends Error {\n readonly code = \"sandbox_warming_timeout\";\n\n constructor(\n public readonly backend: string,\n public readonly timeoutMs: number,\n ) {\n super(\n `Sandbox backend \"${backend}\" capacity or creation timed out after ${Math.ceil(timeoutMs / 1000)}s while warming the sandbox lease. Please try again; if this persists, sandbox capacity may be exhausted.`,\n );\n this.name = \"SandboxWarmingTimeoutError\";\n }\n}\n\n/** The exact attached caller that won warm->cold after proving the provider\n * instance gone. It is a lease supersession (the same logical turn recovers),\n * plus the lost id needed for one durable observability event. */\nexport class SandboxLeaseInstanceLostError extends SandboxLeaseSupersededError {\n constructor(\n sandboxGroupId: string,\n leaseEpoch: number,\n public readonly lostInstanceId: string,\n ) {\n super(sandboxGroupId, leaseEpoch);\n this.name = \"SandboxLeaseInstanceLostError\";\n }\n}\n\n// Bounded poll while a sibling spawner is mid cold-restore. The wait budget is\n// user-facing and separate from the lease TTL heartbeat/reaper horizon.\nconst WARMING_POLL_INTERVAL_MS = 250;\nconst MODAL_EXEC_READINESS_TIMEOUT_MS = 15_000;\n\nasync function sleep(ms: number): Promise<void> {\n await new Promise<void>((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Modal may return a sandbox handle before its command router accepts the first\n * exec. The upstream session's yieldTimeMs starts only after sandbox.exec()\n * returns, so it cannot bound that initial RPC. Probe it before publishing the\n * lease as warm and enforce our own wall-clock deadline.\n */\nexport async function waitForSandboxExecReadiness(\n established: EstablishedSandboxSession,\n timeoutMs = MODAL_EXEC_READINESS_TIMEOUT_MS,\n): Promise<void> {\n try {\n await verifySandboxExecReadiness(established, timeoutMs);\n } catch (error) {\n if (/sandbox creation timed out/i.test(error instanceof Error ? error.message : \"\")) {\n throw new SandboxWarmingTimeoutError(established.backendId, timeoutMs);\n }\n throw error;\n }\n}\n\nclass SnapshotTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`workspace snapshot timed out after ${timeoutMs}ms`);\n this.name = \"SnapshotTimeoutError\";\n }\n}\n\nfunction safeSnapshotError(error: unknown): { name: string; message: string } {\n const rawName = error instanceof Error ? error.name : \"Error\";\n return {\n name: /^[A-Za-z][A-Za-z0-9_.-]{0,79}$/.test(rawName) ? rawName : \"Error\",\n message: redactSensitiveText(error instanceof Error ? error.message : String(error)).slice(\n 0,\n 2_048,\n ),\n };\n}\n\nexport async function waitForWarmSnapshot(\n snapshot: Promise<unknown>,\n timeoutMs: number,\n signal?: AbortSignal,\n): Promise<boolean> {\n if (signal?.aborted) return false;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let cancelListener: (() => void) | undefined;\n try {\n await Promise.race([\n snapshot,\n ...(signal\n ? [\n new Promise<never>((_resolve, reject) => {\n cancelListener = () =>\n reject(signal.reason ?? new Error(\"workspace snapshot wait cancelled\"));\n signal.addEventListener(\"abort\", cancelListener, { once: true });\n if (signal.aborted) cancelListener();\n }),\n ]\n : []),\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new SnapshotTimeoutError(timeoutMs)), timeoutMs);\n if (timeout && \"unref\" in timeout && typeof timeout.unref === \"function\") {\n timeout.unref();\n }\n }),\n ]);\n return true;\n } catch (error) {\n if (signal?.aborted) return false;\n if (error instanceof SnapshotTimeoutError) {\n console.error(\n \"mid-session workspace snapshot wait timed out (turn unaffected)\",\n safeSnapshotError(error),\n );\n return false;\n }\n return true;\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n if (cancelListener) signal?.removeEventListener(\"abort\", cancelListener);\n }\n}\n\nasync function resolveModalCheckpointBindingBeforeCapture(\n settings: SandboxResumeServices[\"settings\"],\n session: unknown,\n signal?: AbortSignal,\n): Promise<Awaited<ReturnType<typeof resolveModalCheckpointProviderBindingForSession>>> {\n if (signal?.aborted) {\n throw signal.reason ?? new Error(\"workspace snapshot identity lookup cancelled\");\n }\n const pending = resolveModalCheckpointProviderBindingForSession(settings, session);\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let cancelListener: (() => void) | undefined;\n try {\n return await Promise.race([\n pending,\n ...(signal\n ? [\n new Promise<never>((_resolve, reject) => {\n cancelListener = () =>\n reject(signal.reason ?? new Error(\"workspace snapshot identity lookup cancelled\"));\n signal.addEventListener(\"abort\", cancelListener, { once: true });\n if (signal.aborted) cancelListener();\n }),\n ]\n : []),\n new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(\n () => reject(new SnapshotTimeoutError(settings.sandboxSnapshotTimeoutMs)),\n settings.sandboxSnapshotTimeoutMs,\n );\n timeout.unref?.();\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n if (cancelListener) signal?.removeEventListener(\"abort\", cancelListener);\n }\n}\n\nasync function terminateEstablishedSandbox(\n established: EstablishedSandboxSession | null,\n): Promise<boolean> {\n if (!established) {\n return true;\n }\n const client = established.client as {\n delete?: (state: unknown) => Promise<unknown>;\n };\n if (typeof client.delete === \"function\" && established.sessionState !== undefined) {\n try {\n await client.delete(established.sessionState);\n return true;\n } catch (error) {\n if (isProviderSandboxNotFoundError(established.backendId, error)) {\n return true;\n }\n return false;\n }\n }\n const session = established.session as {\n close?: () => Promise<unknown>;\n terminate?: () => Promise<unknown>;\n kill?: () => Promise<unknown>;\n closed?: boolean;\n };\n try {\n if (session.terminate) {\n await session.terminate();\n return true;\n } else if (session.kill) {\n await session.kill();\n return true;\n } else if (session.close) {\n if (!session.closed) {\n await session.close();\n }\n return true;\n }\n return false;\n } catch (error) {\n if (isProviderSandboxNotFoundError(established.backendId, error)) {\n return true;\n }\n // Best-effort cleanup. A provider-side orphan sweep is the backstop.\n return false;\n }\n}\n\nfunction asSandboxWarmingError(error: unknown, backend: string, timeoutMs: number): unknown {\n const message = error instanceof Error ? error.message : String(error);\n return /sandbox creation timed out|warming timed out|capacity.*timed out/i.test(message)\n ? new SandboxWarmingTimeoutError(backend, timeoutMs)\n : error;\n}\n\nfunction recordSandboxWarmingTimeout(\n metrics: RuntimeMetricsHooks | undefined,\n error: unknown,\n): void {\n if (!(error instanceof SandboxWarmingTimeoutError)) {\n return;\n }\n try {\n metrics?.onSandboxWarmingTimeout?.({ backend: error.backend });\n } catch {\n // Metrics emission must never affect sandbox recovery or error propagation.\n }\n}\n\nfunction workspaceArchiveFieldsFromEnvelope(\n envelope: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null {\n const sessionState =\n envelope && typeof envelope.sessionState === \"object\" && envelope.sessionState !== null\n ? (envelope.sessionState as Record<string, unknown>)\n : null;\n const archive = sessionState?.workspaceArchive;\n if (typeof archive !== \"string\" || archive.length === 0) {\n return null;\n }\n const previous = sessionState?.workspaceArchivePrev;\n const metadata = sessionState?.workspaceArchiveMeta;\n const previousMetadata = sessionState?.workspaceArchivePrevMeta;\n const capturedAt = sessionState?.workspaceArchiveAt;\n return {\n workspaceArchive: archive,\n ...(metadata !== undefined ? { workspaceArchiveMeta: metadata } : {}),\n ...(typeof previous === \"string\" && previous.length > 0\n ? { workspaceArchivePrev: previous }\n : {}),\n ...(previousMetadata !== undefined ? { workspaceArchivePrevMeta: previousMetadata } : {}),\n ...(typeof capturedAt === \"string\" && capturedAt.length > 0\n ? { workspaceArchiveAt: capturedAt }\n : {}),\n };\n}\n\nfunction legacyNativeArchiveFromEnvelope(envelope: Record<string, unknown> | null | undefined) {\n const sessionState =\n envelope && typeof envelope.sessionState === \"object\" && envelope.sessionState !== null\n ? (envelope.sessionState as Record<string, unknown>)\n : null;\n if (!sessionState) return null;\n const existing = parseWorkspaceArchiveDescriptor(sessionState.workspaceArchiveMeta);\n if (existing?.version === 2) return null;\n return describeLegacyNativeSnapshotArchive(\n sessionState.workspaceArchive,\n existing?.version === 1 ? Date.parse(existing.capturedAt) : Date.now(),\n );\n}\n\n/** A per-session fallback may still carry the dead provider identity that made\n * recovery necessary. It is useful only as durable archive/config input: never\n * let a cold rematerialization resume that stale provider before hydrating the\n * selected revision. */\nfunction withoutProviderIdentity(\n envelope: Record<string, unknown> | null,\n): Record<string, unknown> | null {\n if (!envelope) return null;\n const sessionState =\n envelope.sessionState && typeof envelope.sessionState === \"object\"\n ? (envelope.sessionState as Record<string, unknown>)\n : null;\n if (!sessionState) return envelope;\n const { providerState: _providerState, ...providerIndependentState } = sessionState;\n return { ...envelope, sessionState: providerIndependentState };\n}\n\n/**\n * MID-SESSION /workspace snapshot (sandbox-file-persistence). The reaper's\n * drain-persist only protects boxes the reaper itself kills; anything else —\n * Modal's hard creation-time timeout catching a session busy past it, provider\n * OOM/infra death — loses everything since the last clean drain (staging\n * session e644e8a8, 2026-07-06: mid-turn box termination cost an unpushed\n * branch + 2 commits). While a turn HOLDS the live box, this folds a fresh\n * snapshot onto the lease through persistWarmSnapshot (the warm sibling of the\n * drain seam: epoch-fenced CAS + atomic throttle re-check) and GCs the\n * superseded snapshot image, bounding worst-case loss of ANY unclean box death\n * to sandboxSnapshotIntervalMs.\n *\n * Never throws and never blocks turn progress semantics: every failure path\n * returns false (the snapshot is protection, not a turn dependency). No-ops\n * when the interval is 0, the backend has no persistWorkspace (selfhosted =\n * the user's machine IS the persistence), or a snapshot newer than the\n * interval already rides the lease.\n */\nexport async function maybePersistWarmWorkspaceSnapshot(\n services: SandboxResumeServices,\n ids: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n sandboxGroupId: string;\n },\n session: unknown,\n leaseEpoch: number,\n signal?: AbortSignal,\n force = false,\n): Promise<boolean> {\n const { db, settings } = services;\n const intervalMs = settings.sandboxSnapshotIntervalMs;\n if (intervalMs <= 0 && !force) {\n return false;\n }\n const persistable = session as {\n persistWorkspace?: () => Promise<Uint8Array | undefined>;\n state?: { workspacePersistence?: unknown };\n };\n if (typeof persistable.persistWorkspace !== \"function\") {\n return false;\n }\n if (signal?.aborted) {\n return false;\n }\n try {\n // Resolve the provider namespace before taking the durable capture gate.\n // This work cannot pause or mutate the box, so keeping it outside the claim\n // minimizes the time that command admission must wait.\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (\n !lease ||\n lease.leaseEpoch !== leaseEpoch ||\n lease.liveness !== \"warm\" ||\n lease.instanceId === null\n ) {\n return false;\n }\n const instanceId = lease.instanceId;\n const nativeModalPersistence =\n persistable.state?.workspacePersistence === \"snapshot_filesystem\" ||\n persistable.state?.workspacePersistence === \"snapshot_directory\";\n const checkpointBinding = nativeModalPersistence\n ? await resolveModalCheckpointBindingBeforeCapture(settings, persistable, signal)\n : null;\n if (signal?.aborted) return false;\n\n const captureId = randomUUID();\n const captureTimeoutMs = sandboxArchiveCaptureTimeoutMs(settings);\n const claimed = await claimWorkspaceArchiveCapture(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n captureId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: instanceId,\n liveness: \"warm\",\n captureTimeoutMs,\n minIntervalMs: force ? 0 : intervalMs,\n warmAttempt: {\n sessionId: ids.sessionId,\n turnId: ids.turnId,\n attemptId: ids.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(ids.attemptId),\n },\n });\n if (claimed.status !== \"claimed\") return false;\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n // Stamp WHEN this capture started: persistWarmSnapshot orders warm snapshots\n // by capture-initiation, not land time, so a slower heartbeat capture that\n // started earlier can never overwrite a fresher turn-end capture that landed\n // first (the bounded-wait race Bugbot flagged).\n const capturedAtMs = Date.now();\n const registerCandidate = async (\n archive: Awaited<ReturnType<typeof captureVerifiedWorkspaceArchive>>,\n ): Promise<{ id: string } | null> => {\n if (\n archive.descriptor.version !== 2 ||\n (archive.descriptor.provider !== \"modal_snapshot_filesystem\" &&\n archive.descriptor.provider !== \"modal_snapshot_directory\")\n ) {\n return null;\n }\n if (!checkpointBinding) {\n throw new Error(\"Modal native snapshot has no exact session provider identity\");\n }\n return await registerSandboxCheckpointArtifact(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n sourceLeaseId: claimed.claim.leaseId,\n sourceLeaseEpoch: leaseEpoch,\n sourceInstanceId: instanceId,\n sourceWorkspaceGeneration: claimed.claim.workspaceGeneration,\n providerBindingKey: checkpointBinding.key,\n providerBinding: checkpointBinding.binding,\n workspaceArchive: archive.base64,\n workspaceArchiveMeta: archive.descriptor,\n });\n };\n\n const abandonCandidate = async (artifactId: string, reason: string): Promise<void> => {\n await markSandboxCheckpointArtifactDeletePending(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n artifactId,\n reason,\n }).catch(() => undefined);\n };\n // The SDK capture itself is not cancellable. Keep one owned continuation\n // alive through provider settlement even if this caller's bounded wait or\n // turn signal resolves first. Its finally block is the only normal release\n // of the exact admission gate; a late callback cannot release a successor.\n const captureAndPublish = (async (): Promise<boolean> => {\n let candidate: { id: string } | null = null;\n try {\n const archive = await captureVerifiedWorkspaceArchive(session, capturedAtMs);\n candidate = await registerCandidate(archive);\n const { wrote } = await persistWarmSnapshot(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: ids.turnId,\n attemptId: ids.attemptId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: instanceId,\n expectedWorkspaceGeneration: claimed.claim.workspaceGeneration,\n captureId,\n workspaceArchive: archive.base64,\n workspaceArchiveMeta: archive.descriptor,\n checkpointArtifactId: candidate?.id ?? null,\n minIntervalMs: force ? 0 : intervalMs,\n capturedAtMs,\n });\n if (!wrote && candidate) {\n await abandonCandidate(candidate.id, \"snapshot_publication_fenced\");\n }\n return wrote;\n } catch (error) {\n if (candidate) await abandonCandidate(candidate.id, \"snapshot_capture_failed\");\n throw error;\n } finally {\n await releaseWorkspaceArchiveCapture(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n captureId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: instanceId,\n }).catch((error) => {\n console.error(\n \"mid-session workspace capture gate release failed\",\n safeSnapshotError(error),\n );\n });\n }\n })();\n const settled = captureAndPublish.then(\n (persisted) => ({ kind: \"settled\" as const, persisted }),\n (error) => {\n console.error(\n \"mid-session workspace snapshot failed (turn unaffected)\",\n safeSnapshotError(error),\n );\n return { kind: \"settled\" as const, persisted: false };\n },\n );\n let cancelListener: (() => void) | undefined;\n const outcome = await Promise.race([\n settled,\n ...(signal\n ? [\n new Promise<{ kind: \"cancelled\" }>((resolve) => {\n cancelListener = () => resolve({ kind: \"cancelled\" });\n signal.addEventListener(\"abort\", cancelListener, { once: true });\n if (signal.aborted) cancelListener();\n }),\n ]\n : []),\n new Promise<{ kind: \"timed_out\" }>((resolve) => {\n timeout = setTimeout(\n () => resolve({ kind: \"timed_out\" }),\n settings.sandboxSnapshotTimeoutMs,\n );\n }),\n ]).finally(() => {\n if (timeout) clearTimeout(timeout);\n if (cancelListener) signal?.removeEventListener(\"abort\", cancelListener);\n });\n // A timed-out/cancelled local waiter deliberately leaves the already-owned\n // provider continuation running; `settled` has both rejection handling and\n // exact claim cleanup, so it cannot leak an unhandled promise or artifact.\n return outcome.kind === \"settled\" ? outcome.persisted : false;\n } catch (error) {\n // Protection, not a dependency: a failed snapshot must never fail (or slow\n // down retrying) the turn. The next heartbeat/turn-end tick retries.\n console.error(\n \"mid-session workspace snapshot failed (turn unaffected)\",\n safeSnapshotError(error),\n );\n return false;\n }\n}\n\n/**\n * Resume the one box for a single turn (or any worker-side resume op). Returns\n * the live non-owned session + the fence epoch + a release fn. The CALLER owns\n * the lifecycle: inject non-owned, run, then `await release()` and drop the\n * handle in `finally`.\n *\n * holderId is the globally unique durable turn-attempt id. It must not be a\n * Temporal activity id, because activity ids are only workflow-local and\n * collide when sibling sessions share one sandbox group.\n */\nexport async function resumeBoxForTurn(\n services: SandboxResumeServices,\n ids: ResumeBoxIds,\n kind: \"turn\",\n holderId: TurnSandboxLeaseHolderId,\n): Promise<ResumedTurnSandbox> {\n const { db, settings } = services;\n const os = ids.os ?? \"linux\";\n const leaseTtlMs = settings.sandboxLeaseTtlMs;\n const cancellationSignal = services.cancellationSignal;\n\n // The release closure is created eagerly so the caller can always release in\n // finally, even if establish/commit throws after the holder was registered.\n // It is also bound directly to the logical attempt signal: an uninterruptible\n // provider promise must never keep its private warmup timer and holder alive\n // after Temporal has abandoned the activity.\n let released = false;\n let holderLivenessTimer: ReturnType<typeof setInterval> | undefined;\n let cancellationListener: (() => void) | undefined;\n const release = async (): Promise<void> => {\n if (released) {\n return;\n }\n released = true;\n if (cancellationListener) {\n cancellationSignal?.removeEventListener(\"abort\", cancellationListener);\n cancellationListener = undefined;\n }\n if (holderLivenessTimer) {\n clearInterval(holderLivenessTimer);\n holderLivenessTimer = undefined;\n }\n await releaseLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n idleGraceMs: settings.sandboxIdleGraceMs,\n });\n };\n const cancellationError = (): Error =>\n cancellationSignal?.reason instanceof Error\n ? cancellationSignal.reason\n : new Error(\"Sandbox resume was cancelled with its owning turn attempt\");\n const throwIfReleasedOrCancelled = (): void => {\n if (released || cancellationSignal?.aborted) {\n throw cancellationError();\n }\n };\n\n const acquired = await acquireLease(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n subjectId: ids.sessionId,\n backend: ids.backend,\n os,\n // IMAGE IS SHARED STATE (B3): thread the resolved image so the lease stamps it +\n // conflicts on a live box already running a different image. A\n // SandboxImageConflictError propagates while another holder is active; a\n // solo change requests a capture-and-drain rotation and this attempt retries\n // after the cold successor can safely stamp the new image.\n ...(ids.image ? { image: ids.image } : {}),\n // RIG IS SHARED STATE (M3): thread the frozen rig version so the lease stamps it\n // + conflicts on a live box under a different rig. A SandboxRigConflictError\n // propagates while another holder is active; a solo change uses the same\n // durable capture-and-drain rotation as an image change.\n ...(ids.rigVersionId ? { rigVersionId: ids.rigVersionId } : {}),\n leaseTtlMs,\n warmingLeaseTtlMs: settings.sandboxWarmingTimeoutMs,\n captureWaitMs: sandboxArchiveCaptureTimeoutMs(settings),\n });\n\n if (cancellationSignal) {\n cancellationListener = () => {\n // release() flips `released` and clears the timer synchronously before its\n // first await. The detached rejection handler is intentional: the outer\n // turn owns diagnostics, while this listener owns leak prevention.\n void release().catch(() => undefined);\n };\n cancellationSignal.addEventListener(\"abort\", cancellationListener, { once: true });\n }\n if (cancellationSignal?.aborted) {\n await release();\n throw cancellationError();\n }\n\n // HOLDER-LIVENESS loop: touch OUR holder row every 10s from the moment it is\n // registered until release. The dead-worker turn-holder reap judges liveness\n // by last_heartbeat_at, and the full turn heartbeat (heartbeatLeaseHolder in\n // agent-turn) only starts AFTER this function returns — while waitForWarm and\n // establish/cold-restore can legitimately run for many minutes in here,\n // COMPOUNDING past any fixed reap horizon. With this\n // loop no live holder is ever silent for more than one tick, so the reap\n // horizon is pure defense-in-depth, not a tuned guess about path lengths.\n // Epoch-free by design (touch only refreshes our own row's timestamp);\n // best-effort (a transient DB error must never fail the resume).\n holderLivenessTimer = setInterval(() => {\n void touchLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n })\n .then((touched) => {\n // A canonical turn holder is rejected once its exact attempt is no\n // longer the active writer. Stop this otherwise-unbounded provider\n // operation and idempotently drop any remaining holder state.\n if (!touched) {\n void release().catch(() => undefined);\n }\n })\n .catch(() => undefined);\n }, 10_000);\n if (\"unref\" in holderLivenessTimer && typeof holderLivenessTimer.unref === \"function\") {\n holderLivenessTimer.unref();\n }\n\n // FENCED: a newer epoch exists (a later turn re-established the box). Back off;\n // NEVER create(). Release our (just-registered) holder so we don't pin a stale\n // lease, then surface the supersession.\n if (acquired.role === \"blocked\") {\n await release();\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n acquired.lease.leaseEpoch,\n acquired.code,\n acquired.lease.recovery,\n );\n }\n if (acquired.role === \"fenced\") {\n await release();\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, acquired.lease.leaseEpoch);\n }\n\n // SPAWNER: we won the cold->warming CAS. Establish (cold-restore/create),\n // then commit warm (lease_epoch++). Optional desktop setup is lazy.\n if (acquired.role === \"spawner\") {\n const expectedEpoch = acquired.lease.leaseEpoch;\n let createdEstablished: EstablishedSandboxSession | null = null;\n let rematerialization: {\n id: string;\n selectedRevision: string;\n workspaceGeneration: number;\n providerBindingKey: string | null;\n legacyCheckpoint: NonNullable<ReturnType<typeof legacyNativeArchiveFromEnvelope>> | null;\n legacyProviderBinding: Awaited<\n ReturnType<typeof resolveModalCheckpointProviderBindingForSession>\n > | null;\n } | null = null;\n try {\n const envelope = await getSandboxSessionEnvelope(db, ids.workspaceId, ids.sessionId);\n // The lease is authoritative. A legacy per-session fallback archive may\n // only be used after beginSandboxRematerialization imports its archive\n // fields under the warming-row lock and records one selected revision.\n // Select the fallback only when the lease has no archive truth at all. A\n // lease-carried unverified/invalid archive must fail closed rather than\n // silently substituting another revision.\n const fallbackArchiveEnvelope =\n acquired.lease.recovery.archive.status === \"none\" &&\n workspaceArchiveFieldsFromEnvelope(envelope) !== null\n ? withoutProviderIdentity(envelope)\n : null;\n let spawnEnvelope = fallbackArchiveEnvelope ?? acquired.lease.resumeState ?? envelope;\n const archiveSource =\n acquired.lease.recovery.archive.status === \"none\"\n ? fallbackArchiveEnvelope\n : acquired.lease.resumeState;\n if (\n acquired.lease.recovery.archive.status === \"available\" ||\n workspaceArchiveFieldsFromEnvelope(archiveSource) !== null\n ) {\n const rematerializationId = crypto.randomUUID();\n const legacyNativeArchive = legacyNativeArchiveFromEnvelope(archiveSource);\n const begun = await beginSandboxRematerialization(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId,\n archiveSource,\n legacyNativeArchive,\n });\n if (begun.status !== \"started\") {\n if (begun.code === \"stale_epoch\" || begun.code === \"attempt_conflict\") {\n throw new SandboxLeaseSupersededError(\n ids.sandboxGroupId,\n begun.lease?.leaseEpoch ?? expectedEpoch,\n );\n }\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n begun.lease?.leaseEpoch ?? expectedEpoch,\n begun.code === \"archive_unverified\" ? \"restore_degraded\" : \"restore_unrecoverable\",\n begun.lease?.recovery ?? acquired.lease.recovery,\n );\n }\n spawnEnvelope = begun.lease.resumeState ?? spawnEnvelope;\n const selectedRevision = begun.lease.recovery.restore.selectedRevision;\n if (!selectedRevision) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_metadata_invalid\",\n \"sandbox rematerialization selected no durable archive revision\",\n );\n }\n rematerialization = {\n id: rematerializationId,\n selectedRevision,\n workspaceGeneration: begun.lease.workspaceGeneration,\n providerBindingKey: begun.checkpointArtifact?.providerBindingKey ?? null,\n legacyCheckpoint: begun.checkpointArtifact === null ? legacyNativeArchive : null,\n legacyProviderBinding: null,\n };\n } else if (acquired.lease.recovery.archive.status !== \"none\") {\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n expectedEpoch,\n \"restore_degraded\",\n acquired.lease.recovery,\n );\n }\n // Prefer the COLD lease's preserved resume_state when it carries a persisted\n // /workspace snapshot (confirmDrainCold keeps a minimal archive-only envelope\n // across draining->cold for exactly this re-warm). establishSandboxSessionFromEnvelope\n // cold-creates a fresh box and replays the archive via hydrateWorkspace, so\n // /workspace survives box churn (sandbox-file-persistence). No archive ->\n // the bare session envelope (a never-warmed cold start). Mirrors channel-a.ts's\n // spawner branch: the lease's resume_state is authoritative; the session\n // `_sandbox` envelope is the per-session fallback. Without this a turn-first\n // re-warm after a drain->cold would ignore the archive and start an EMPTY box.\n const providerCreateStartedAt = new Date();\n const established = await establishSandboxSessionFromEnvelope(settings, spawnEnvelope, {\n sessionId: ids.sessionId,\n recovery: \"create-or-restore\",\n backendOverride: ids.backend as never,\n ...(ids.environment ? { environment: ids.environment } : {}),\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n onSandboxCreated: async (created) => {\n createdEstablished = created;\n throwIfReleasedOrCancelled();\n if (\n rematerialization &&\n (rematerialization.providerBindingKey || rematerialization.legacyCheckpoint)\n ) {\n if (created.backendId !== \"modal\") {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Modal checkpoint restore resolved a non-Modal sandbox backend\",\n );\n }\n if (rematerialization.providerBindingKey) {\n if (\n !(await modalSessionMatchesCheckpointProviderBinding(\n settings,\n created.session,\n rematerialization.providerBindingKey,\n ))\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Modal checkpoint restore refused because the authenticated provider workspace changed\",\n );\n }\n } else {\n const resolved = await resolveModalCheckpointProviderBindingForSession(\n settings,\n created.session,\n );\n if (\n rematerialization.legacyProviderBinding &&\n rematerialization.legacyProviderBinding.key !== resolved.key\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Legacy Modal checkpoint restore crossed authenticated provider workspaces\",\n );\n }\n rematerialization.legacyProviderBinding = resolved;\n }\n }\n const resumeEnvelope = requirePersistableReplacementSandboxEnvelope(\n await serializeReplacementSandboxEnvelope(created, spawnEnvelope),\n created.backendId,\n );\n const recorded = await recordWarmingSandboxCreated(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization?.id ?? null,\n instanceId: created.instanceId,\n resumeBackendId: created.backendId,\n resumeState: resumeEnvelope,\n ...(created.backendId === \"modal\"\n ? {\n providerCreatedAt: providerCreateStartedAt,\n providerDeadlineAt: new Date(\n providerCreateStartedAt.getTime() + settings.modalTimeoutSeconds * 1000,\n ),\n }\n : {}),\n leaseTtlMs,\n // Keep the warming budget after create(): manifest setup and\n // commitWarmingToWarm still run, and can exceed the 90s turn TTL.\n warmingLeaseTtlMs: settings.sandboxWarmingTimeoutMs,\n });\n if (!recorded.recorded) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n if (created.backendId === \"modal\") {\n await tagModalSandbox(settings, created.instanceId, {\n leaseId: acquired.lease.id,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n }).catch(() => undefined);\n }\n throwIfReleasedOrCancelled();\n },\n onWorkspaceRestoreVerifying: async (descriptor: WorkspaceArchiveDescriptor) => {\n if (!rematerialization || descriptor.revision !== rematerialization.selectedRevision) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_metadata_invalid\",\n `hydrated archive revision ${descriptor.revision} does not match the selected rematerialization revision`,\n );\n }\n if (rematerialization.legacyCheckpoint) {\n const binding = rematerialization.legacyProviderBinding;\n if (!binding) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Legacy Modal checkpoint restore produced no authenticated provider identity\",\n );\n }\n const adopted = await adoptLegacyModalCheckpointArtifact(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n leaseId: acquired.lease.id,\n leaseEpoch: expectedEpoch,\n workspaceGeneration: rematerialization.workspaceGeneration,\n slot: \"current\",\n archiveBase64: rematerialization.legacyCheckpoint.archiveBase64,\n descriptor: rematerialization.legacyCheckpoint.descriptor,\n providerBindingKey: binding.key,\n providerBinding: binding.binding,\n rematerializationId: rematerialization.id,\n });\n if (!adopted) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n rematerialization.providerBindingKey = binding.key;\n }\n const verifying = await markSandboxRestoreVerifying(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization.id,\n });\n if (!verifying.wrote) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n },\n });\n createdEstablished = established;\n throwIfReleasedOrCancelled();\n // A sandbox handle is not sufficient evidence that Modal's command router\n // is live. Do not publish a warm lease until one bounded no-op exec works.\n // On timeout the catch below terminates the box and rolls warming -> cold,\n // so the next turn cold-creates instead of hanging forever on first use.\n await waitForSandboxExecReadiness(established);\n throwIfReleasedOrCancelled();\n // Fold the LIVE box into a re-resumable envelope and persist it as the\n // lease's resume_state — exactly like the API-direct paths (channel-a.ts /\n // viewer.ts). Without this the turn committed the ORIGINAL session manifest\n // as resume_state, so every LATER op off this lease (Channel-A fs/git/\n // terminal, the desktop viewer, the reaper) cold-restored a FRESH rival box\n // and never saw the turn's live box. Historical state may contribute only\n // durable archive pointers: if live serialization fails, publishing its\n // dead provider identity would pair the replacement instance with the box\n // that initiated recovery.\n // A successful cold hydrate has already proved this archive usable and the\n // replacement box now contains its files. Keep the current + fallback\n // archive pointers on the committed live envelope until a later warm\n // snapshot replaces them. Without this merge, serialization publishes only\n // the new provider id; a second provider loss before the snapshot cadence\n // fires would otherwise make truthful recovery impossible. Failed hydrate\n // attempts terminate the replacement and fail closed; they never publish a\n // clean or mixed workspace.\n const resumeEnvelope = requirePersistableReplacementSandboxEnvelope(\n await serializeReplacementSandboxEnvelope(established, spawnEnvelope),\n established.backendId,\n );\n throwIfReleasedOrCancelled();\n if (\n rematerialization &&\n established.restoredArchive?.revision !== rematerialization.selectedRevision\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_mismatch\",\n \"sandbox restore completed without the exact selected durable archive revision\",\n );\n }\n const committed = await commitWarmingToWarm(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n instanceId: established.instanceId,\n // Viewer attach resolves and records the tunnel URL lazily. A headless\n // turn must not touch the optional desktop data plane.\n dataPlaneUrl: null,\n resumeBackendId: established.backendId,\n resumeState: resumeEnvelope,\n ...(rematerialization\n ? {\n rematerialization: {\n id: rematerialization.id,\n verifiedRevision: rematerialization.selectedRevision,\n },\n }\n : {}),\n leaseTtlMs,\n });\n if (!committed.committed || !committed.lease) {\n // A reaper reset our warming row (we were too slow) or a sibling\n // re-established and bumped the epoch. Drop the handle; release our\n // holder; surface supersession. This spawner created the box, so stop it\n // before retrying to avoid an untracked running sandbox.\n const terminated = await terminateEstablishedSandbox(established);\n if (terminated && rematerialization) {\n await failSandboxRematerialization(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization.id,\n failureCode: committed.reason ?? \"warm_commit_rejected\",\n retryable: false,\n });\n }\n await release();\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n throwIfReleasedOrCancelled();\n return { established, leaseEpoch: committed.lease.leaseEpoch, release };\n } catch (error) {\n if (error instanceof SandboxLeaseSupersededError) {\n await terminateEstablishedSandbox(createdEstablished);\n await release();\n throw error;\n }\n const terminated = await terminateEstablishedSandbox(createdEstablished);\n // Caught spawn failure: if the just-created sandbox was actually stopped,\n // roll the warming row back to cold so a queued turn can re-acquire and\n // re-spawn. If termination itself failed, keep the recorded instance_id on\n // the warming row; the lease TTL/reaper and Modal orphan sweep are the\n // tracked backstops, and we must not erase the only provider pointer.\n if (terminated) {\n if (rematerialization) {\n await failSandboxRematerialization(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization.id,\n failureCode:\n error instanceof WorkspaceArchiveIntegrityError\n ? error.code\n : \"sandbox_rematerialization_failed\",\n retryable: error instanceof WorkspaceArchiveIntegrityError ? error.retryable : true,\n });\n } else {\n await failWarmingToCold(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n });\n }\n }\n await release();\n const warmingError = asSandboxWarmingError(\n error,\n ids.backend,\n settings.sandboxWarmingTimeoutMs,\n );\n recordSandboxWarmingTimeout(services.sandboxMetrics, warmingError);\n throw warmingError;\n }\n }\n\n // ATTACHED / REARMED: the box is live (or a sibling is warming it). Resume it\n // BY ID off the committed lease envelope. For an 'attached'-to-warming lease we\n // first wait for the spawner to commit warm, bounded by the explicit warming\n // budget. A cold reset means the spawner died; recover the same turn instead\n // of trying to enter the spawner create path from the attached branch.\n try {\n let leaseEpoch = acquired.lease.leaseEpoch;\n if (acquired.lease.liveness === \"warming\") {\n leaseEpoch = (await waitForWarm(services, ids)).leaseEpoch;\n }\n throwIfReleasedOrCancelled();\n\n // Prefer the lease's resume_state (the LIVE box the spawner committed) so we\n // re-attach to the SAME box by id, not cold-restore the original session\n // manifest into a rival. Fall back to the session envelope only when the\n // lease carries no resume_state (matches channel-a.ts's attached branch).\n const live = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (\n !live ||\n live.liveness !== \"warm\" ||\n live.leaseEpoch !== leaseEpoch ||\n live.instanceId === null\n ) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, live?.leaseEpoch ?? leaseEpoch);\n }\n let established: EstablishedSandboxSession;\n try {\n const establish = services.establishAttachedSandbox ?? establishSandboxSessionFromEnvelope;\n established = await establish(settings, live.resumeState, {\n sessionId: ids.sessionId,\n recovery: \"resume-only\",\n backendOverride: ids.backend as never,\n ...(ids.environment ? { environment: ids.environment } : {}),\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n });\n throwIfReleasedOrCancelled();\n // A durable `warm` row is an ownership assertion, not provider liveness.\n // Modal may have ended the exact box at its finite timeout while OpenGeni\n // was idle. Prove the command router before handing the session to the\n // agent so terminal evidence enters the atomic warm->cold recovery path\n // below instead of surfacing inside a model-visible tool call.\n await (services.verifyAttachedSandboxReadiness ?? waitForSandboxExecReadiness)(established);\n throwIfReleasedOrCancelled();\n } catch (error) {\n if (!isProviderSandboxNotFoundError(ids.backend, error)) {\n throw error;\n }\n const marked = await markWarmLeaseInstanceLost(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: live.instanceId,\n });\n if (marked.status === \"marked\") {\n await services.onSandboxLost?.({\n sandboxGroupId: ids.sandboxGroupId,\n instanceId: live.instanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n throw new SandboxLeaseInstanceLostError(\n ids.sandboxGroupId,\n marked.lease.leaseEpoch,\n live.instanceId,\n );\n }\n throw new SandboxLeaseSupersededError(\n ids.sandboxGroupId,\n marked.lease?.leaseEpoch ?? leaseEpoch,\n );\n }\n throwIfReleasedOrCancelled();\n return { established, leaseEpoch, release };\n } catch (error) {\n await release();\n const warmingError = asSandboxWarmingError(\n error,\n ids.backend,\n settings.sandboxWarmingTimeoutMs,\n );\n recordSandboxWarmingTimeout(services.sandboxMetrics, warmingError);\n throw warmingError;\n }\n}\n\n/**\n * Poll a warming lease until the spawner commits warm. If the warming row is\n * reset to cold (the spawner died and the reaper reset it), surface supersession\n * so the turn is re-dispatched and can enter the normal spawner branch from\n * acquireLease. Bounded by OPENGENI_SANDBOX_WARMING_TIMEOUT_MS, not the lease TTL.\n */\nasync function waitForWarm(\n services: SandboxResumeServices,\n ids: ResumeBoxIds,\n): Promise<{ leaseEpoch: number }> {\n const { db, settings } = services;\n const deadline = Date.now() + settings.sandboxWarmingTimeoutMs;\n while (Date.now() < deadline) {\n await sleep(WARMING_POLL_INTERVAL_MS);\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (!lease) {\n // Lease vanished (cold-reaped). Re-dispatch from scratch.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, 0);\n }\n if (lease.liveness === \"warm\") {\n return { leaseEpoch: lease.leaseEpoch };\n }\n if (lease.liveness === \"draining\") {\n // The warming attempt either failed into drain or committed+released before\n // this waiter observed it. Re-dispatch so acquireLease can re-arm or spawn\n // through the normal path.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, lease.leaseEpoch);\n }\n if (lease.liveness === \"cold\") {\n if (isRetryableDegradedRestore(lease.recovery.restore)) {\n // The elected spawner hit a transient archive verification failure.\n // Re-enter admission so one caller can become the next fenced spawner;\n // the archive remains authoritative and must not become terminal.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, lease.leaseEpoch);\n }\n if (\n lease.recovery.restore.status === \"degraded\" ||\n lease.recovery.restore.status === \"unrecoverable\"\n ) {\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n lease.leaseEpoch,\n lease.recovery.restore.status === \"degraded\"\n ? \"restore_degraded\"\n : \"restore_unrecoverable\",\n lease.recovery,\n );\n }\n // The spawner died; re-dispatch so the normal acquireLease path can win\n // cold->warming and run the full spawner branch.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, lease.leaseEpoch);\n }\n // still warming — keep polling.\n }\n throw new SandboxWarmingTimeoutError(ids.backend, settings.sandboxWarmingTimeoutMs);\n}\n","// apps/worker/src/sandbox-routing.ts — wire the agent-loop-free routing proxy\n// (`@opengeni/runtime` RoutingSandboxSession + makeActiveBackendResolver) to the\n// real DB pointer + the live NATS control plane for the WORKER TURN path (M7).\n//\n// The turn resumes its group box by id (resumeBoxForTurn) and injects it\n// NON-OWNED into the run. With hot-swap, the injected `session` must be the\n// STABLE routing proxy: the SDK binds to it ONCE and calls its\n// methods per tool call; the proxy re-reads `(active_sandbox_id, active_epoch)`\n// per op and dispatches to the currently-active backend (the group Modal box by\n// default, or a swap target — a sibling Modal box or a selfhosted machine).\n//\n// The glue here is the DB-coupled half the leaf cannot own (the leaf must stay\n// agent-loop-free + db-free): readActiveSandbox (the pointer), getSandbox (the\n// target lookup), and the selfhosted ControlRpc built over the events bus's NATS\n// request/reply connection.\n\nimport { sandboxArchiveCaptureTimeoutMs, type Settings } from \"@opengeni/config\";\nimport {\n advanceWorkspaceGenerationForRetainedProcess,\n advanceWorkspaceGeneration,\n getRetainedProcess,\n retainWorkspaceMutationProcess,\n retainedProcessSettlementIdentity,\n settleRetainedProcess,\n verifyRetainedProcessMutationSettlement,\n verifyWorkspaceMutationSettlement,\n getSandbox,\n markWarmLeaseInstanceLost,\n readLease,\n readActiveSandbox,\n SandboxRetainedProcessPromotionFencedError,\n type Database,\n type SandboxWorkspaceMutationAdmission,\n} from \"@opengeni/db\";\nimport type { EventBus } from \"@opengeni/events\";\nimport {\n buildSelfhostedBackendSession,\n establishSandboxSessionFromEnvelope,\n isProviderSandboxGoneDuringRoutedOperation,\n isProviderSandboxNotFoundError,\n makeActiveBackendResolver,\n NatsControlRpc,\n NatsOpStreamTransport,\n RoutingBackendRecoveryRequiredError,\n RoutingSandboxSession,\n resolveModalCheckpointProviderBindingForSession,\n sandboxBackendForSdkBackendId,\n verifySandboxExecReadiness,\n type ControlRpc,\n type EstablishedSandboxSession,\n type NatsRequestConnection,\n type RoutableBackendSession,\n type RoutableSandbox,\n type ResolvedActiveBackend,\n type RoutingMutationSettlementResult,\n type RoutingSandboxOperationObserver,\n type RoutingRetainedProcess,\n type RoutingRetainedProcessTerminalProof,\n type SelfhostedOpObserver,\n type SelfhostedRelayConfig,\n type OpStreamJournal,\n type SelfhostedOpStreamDeps,\n} from \"@opengeni/runtime\";\nimport { sandboxLeaseHolderIdForAttempt } from \"./sandbox-resume\";\n\ntype PersistableMutationAdmission = {\n admission: SandboxWorkspaceMutationAdmission;\n providerBinding: Awaited<\n ReturnType<typeof resolveModalCheckpointProviderBindingForSession>\n > | null;\n};\n\nexport type RoutingWiringServices = {\n db: Database;\n settings: Settings;\n /** The events bus, for the selfhosted control-plane request/reply connection.\n * Optional: when absent (or NATS unconfigured) a selfhosted swap target\n * surfaces agent_offline on its first op rather than failing to build. */\n bus?: EventBus;\n /** The per-op observer wired into every selfhosted session this turn builds\n * (out-of-band telemetry — op metrics + machine.* events). Absent ⇒ no-op. */\n onOp?: SelfhostedOpObserver;\n /** Every physical routed provider call, across cloud and selfhosted homes. */\n onSandboxOperation?: RoutingSandboxOperationObserver;\n /** The op-stream durable-resume journal (the Temporal adaptation from\n * op-journal.ts): attach generation + settled-frontier persistence. Absent ⇒\n * the runtime defaults (generation \"1\", no persistence) — tests / non-turn\n * callers. Only consulted when op-stream is actually enabled for the turn. */\n opJournal?: OpStreamJournal;\n /** Durable lifecycle notification emitted only by the observer that wins the\n * exact warm-instance loss CAS. */\n onHomeSandboxLost?: (input: {\n sandboxGroupId: string;\n instanceId: string;\n leaseEpoch: number;\n }) => Promise<void>;\n /** Called when a route repair replaces the worker's original home handle. */\n onHomeSandboxRebound?: (input: {\n established: EstablishedSandboxSession;\n leaseEpoch: number;\n }) => void;\n};\n\nexport type RoutingWiringIds = {\n workspaceId: string;\n sessionId: string;\n /** Canonical turn-attempt fence used to admit persistable-home mutations.\n * Omit outside a running worker attempt; mutation hooks then remain disabled. */\n workspaceMutationFence?: {\n accountId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n };\n homeLease?: {\n accountId: string;\n sandboxGroupId: string;\n leaseEpoch: number;\n instanceId: string;\n backend: string;\n };\n /**\n * The run's declared sandbox environment — the SAME object the turn passes to\n * `runtime.buildAgent`'s `sandboxEnvironment` and to `resumeBoxForTurn` (so the\n * group box's manifest carries it too). Threaded into a selfhosted swap target's\n * manifest so its `environment` EQUALS the turn's, making the SDK's per-turn\n * provided-session manifest-env delta empty (validateNoEnvironmentDelta).\n * WITHOUT this a pin-to-vm turn throws \"Live sandbox sessions cannot change\n * manifest environment variables.\" Optional → the resolver defaults to `{}`.\n */\n environment?: Record<string, string>;\n /**\n * Stage D machine-primary: PIN the already-established turn SelfhostedSession\n * (the `established` arg's session) for THIS machine pointer `(sandboxId, epoch)`\n * so the per-op resolver returns that SAME instance instead of building a fresh\n * one — the turn-start manifest write + per-op reads then hit ONE\n * SelfhostedSession/manifest. Set ONLY by the machine-primary establish branch\n * (where `established.session` is the SelfhostedSession bound to this pointer);\n * the group-box/swap path omits it (the default is the modal group box, and a\n * swap target is built fresh).\n */\n pinnedSelfhosted?: { sandboxId: string; epoch: number };\n /**\n * Whether the turn's `defaultBackend` IS the session's home (so the null pointer may\n * resolve to it). Defaults to TRUE (omitted). Set explicitly FALSE on a machine-primary\n * turn of a Modal-HOME session (pinned to a machine, no Modal group box established this\n * turn): the routing resolver's null branch then throws a typed `home_unavailable_this_turn`\n * error on a mid-turn clear-to-null instead of silently serving the pinned machine — the\n * detach's pointer commit stands and takes effect next turn. A genuine machine-HOME turn\n * (home IS the machine) passes true.\n */\n defaultIsHome?: boolean;\n};\n\n/** Map the deployment relay URL to the leaf's `SelfhostedRelayConfig` shape\n * (host/port/tls). M8 wires the real relay; until then a configured/placeholder\n * host yields a well-formed stream-URL shape behind `resolveExposedPort`. */\nexport function relayConfigFromSettings(settings: Settings): SelfhostedRelayConfig {\n const raw = settings.selfhostedRelayUrl?.trim();\n if (!raw) {\n return { host: \"relay.opengeni.local\", port: 443, tls: true };\n }\n try {\n const url = new URL(raw.includes(\"://\") ? raw : `wss://${raw}`);\n const tls = url.protocol === \"wss:\" || url.protocol === \"https:\";\n const port = url.port ? Number(url.port) : tls ? 443 : 80;\n return { host: url.hostname, port, tls };\n } catch {\n return { host: raw, port: 443, tls: true };\n }\n}\n\n/** The selfhosted CONTROL vs EXEC op deadlines for a turn, from settings. Control\n * ops (ping/fs/desktop/pty) stay on the short timeout so machine liveness is never\n * masked by a slow op; exec gets its own much larger budget so a real command is not\n * killed at the control wall. Threaded into every turn-path session build + resolver. */\nexport function selfhostedTimeoutsFromSettings(settings: Settings): {\n timeoutMs: number;\n execTimeoutMs: number;\n} {\n return {\n timeoutMs: settings.sandboxSelfhostedControlTimeoutMs,\n execTimeoutMs: settings.sandboxSelfhostedExecTimeoutMs,\n };\n}\n\n/** The same split deadlines shaped for `makeActiveBackendResolver`'s dep names\n * (`selfhostedTimeoutMs` / `selfhostedExecTimeoutMs`), for a swap/pin target. */\nfunction selfhostedResolverTimeouts(settings: Settings): {\n selfhostedTimeoutMs: number;\n selfhostedExecTimeoutMs: number;\n} {\n const { timeoutMs, execTimeoutMs } = selfhostedTimeoutsFromSettings(settings);\n return {\n selfhostedTimeoutMs: timeoutMs,\n selfhostedExecTimeoutMs: execTimeoutMs,\n };\n}\n\ntype HomeRouteLeaseIdentity = {\n accountId: string;\n sandboxGroupId: string;\n backend: string;\n};\n\ntype HomeRouteResolutionIds = HomeRouteLeaseIdentity & {\n workspaceId: string;\n sessionId: string;\n};\n\ntype HomeRouteRecovery = \"pending\" | \"degraded\" | \"unrecoverable\" | \"superseded\";\n\n/**\n * Translate the durable lease/recovery state into the typed disposition the\n * routing proxy exposes when the home cannot be safely resumed. A route repair\n * must never fall back to the old in-memory provider handle when the lease is\n * warming, restoring, unverifiable, or otherwise inconsistent.\n */\nfunction homeRouteRecoveryDisposition(\n lease: Awaited<ReturnType<typeof readLease>>,\n): HomeRouteRecovery {\n if (!lease) return \"unrecoverable\";\n if (lease.liveness === \"warming\") return \"pending\";\n if (lease.liveness === \"draining\") return \"superseded\";\n if (\n lease.recovery.restore.status === \"pending\" ||\n lease.recovery.restore.status === \"restoring\" ||\n lease.recovery.restore.status === \"verifying\"\n ) {\n return \"pending\";\n }\n if (\n lease.recovery.restore.status === \"degraded\" ||\n lease.recovery.workspace.status === \"degraded\" ||\n lease.recovery.archive.status === \"unverified\" ||\n lease.recovery.archive.status === \"invalid\"\n ) {\n return \"degraded\";\n }\n return \"unrecoverable\";\n}\n\nfunction homeRouteRecoveryError(\n lease: Awaited<ReturnType<typeof readLease>>,\n fallbackEpoch: number,\n): RoutingBackendRecoveryRequiredError {\n return new RoutingBackendRecoveryRequiredError(\n \"resolve_home_backend\",\n lease?.leaseEpoch ?? fallbackEpoch,\n homeRouteRecoveryDisposition(lease),\n );\n}\n\nexport function providerIdentityFromResumeState(\n resumeState: Record<string, unknown>,\n): string | null {\n const sessionState =\n resumeState.sessionState && typeof resumeState.sessionState === \"object\"\n ? (resumeState.sessionState as Record<string, unknown>)\n : null;\n const providerState =\n sessionState?.providerState && typeof sessionState.providerState === \"object\"\n ? (sessionState.providerState as Record<string, unknown>)\n : null;\n for (const field of [\n \"sandboxId\",\n \"instanceId\",\n \"id\",\n \"hostId\",\n \"containerId\",\n \"workspaceRootPath\",\n \"agentId\",\n ]) {\n const value = providerState?.[field];\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return null;\n}\n\n/**\n * Resolve the current durable home identity after the route epoch changes.\n *\n * Same-target attach/repair can replace the provider instance while a worker\n * turn still holds the stable routing proxy. The proxy must therefore resume\n * the lease's CURRENT identity, not reuse the object captured at turn start.\n * This seam is deliberately resume-only: lease election/rematerialization is\n * owned by the API/lease state machine, and a routed tool call must never create\n * a rival provider or replay an ambiguous mutation.\n */\nasync function resolveCurrentHomeBackend(\n services: RoutingWiringServices,\n ids: HomeRouteResolutionIds,\n established: EstablishedSandboxSession,\n): Promise<ResolvedActiveBackend> {\n const lease = await readLease(services.db, ids.workspaceId, ids.sandboxGroupId);\n const fallbackEpoch = lease?.leaseEpoch ?? 0;\n if (\n !lease ||\n lease.liveness !== \"warm\" ||\n lease.recovery.provider.status !== \"exists\" ||\n lease.instanceId === null ||\n lease.recovery.provider.instanceId !== lease.instanceId ||\n lease.recovery.workspace.status !== \"ready\" ||\n (lease.recovery.restore.status !== \"not_required\" && lease.recovery.restore.status !== \"ready\")\n ) {\n throw homeRouteRecoveryError(lease, fallbackEpoch);\n }\n\n // A route epoch can advance without a provider replacement. Reuse the exact\n // established handle only when its identity still equals the durable one.\n if (lease.instanceId === established.instanceId) {\n services.onHomeSandboxRebound?.({\n established,\n leaseEpoch: lease.leaseEpoch,\n });\n return {\n session: established.session as RoutableBackendSession,\n sandboxId: null,\n kind: established.backendId,\n leaseEpoch: lease.leaseEpoch,\n providerInstanceId: lease.instanceId,\n };\n }\n\n const resumeState = lease.resumeState;\n const durableResumeBackend = lease.resumeBackendId ?? lease.backend ?? ids.backend;\n const resumeBackend = sandboxBackendForSdkBackendId(durableResumeBackend) ?? durableResumeBackend;\n if (\n !resumeState ||\n resumeBackend !== ids.backend ||\n providerIdentityFromResumeState(resumeState) !== lease.instanceId\n ) {\n throw homeRouteRecoveryError(lease, lease.leaseEpoch);\n }\n\n let rebound: EstablishedSandboxSession;\n try {\n rebound = await establishSandboxSessionFromEnvelope(services.settings, resumeState, {\n sessionId: ids.sessionId,\n recovery: \"resume-only\",\n backendOverride: resumeBackend as never,\n });\n // A resumed handle is not enough evidence for the route to use it. Keep the\n // same bounded readiness gate used before publishing a Modal lease warm.\n await verifySandboxExecReadiness(rebound);\n } catch (error) {\n if (!isProviderSandboxNotFoundError(resumeBackend, error)) {\n // The durable identity is present, but a transient resume/provider error\n // did not prove the box gone. Keep the lease untouched and make the next\n // independent route operation retry the resume; never use the old handle.\n throw new RoutingBackendRecoveryRequiredError(\n \"resolve_home_backend\",\n lease.leaseEpoch,\n \"pending\",\n );\n }\n const marked = await markWarmLeaseInstanceLost(services.db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: lease.leaseEpoch,\n expectedInstanceId: lease.instanceId,\n diagnostic: \"provider_not_found_during_home_route_rebind\",\n });\n if (marked.status === \"marked\") {\n await services.onHomeSandboxLost?.({\n sandboxGroupId: ids.sandboxGroupId,\n instanceId: lease.instanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n }\n throw new RoutingBackendRecoveryRequiredError(\n \"resolve_home_backend\",\n marked.lease?.leaseEpoch ?? lease.leaseEpoch,\n marked.status === \"stale\" ? \"superseded\" : homeRouteRecoveryDisposition(marked.lease),\n );\n }\n\n // The provider identity must agree with the exact durable lease row before\n // any caller can publish or route through this rebound handle. A mismatch is\n // unverifiable local state, not permission to try the old handle.\n const reboundBackend = sandboxBackendForSdkBackendId(rebound.backendId) ?? rebound.backendId;\n if (rebound.instanceId !== lease.instanceId || reboundBackend !== resumeBackend) {\n throw homeRouteRecoveryError(lease, lease.leaseEpoch);\n }\n services.onHomeSandboxRebound?.({\n established: rebound,\n leaseEpoch: lease.leaseEpoch,\n });\n // Keep the resolver's mutable home reference on the latest verified handle so\n // a later route epoch does not resume the same replacement again. This is only\n // a worker-side handle update; the SDK-facing RoutingSandboxSession remains the\n // stable object returned below and is never replaced.\n Object.assign(established, rebound);\n return {\n session: rebound.session as RoutableBackendSession,\n sandboxId: null,\n kind: rebound.backendId,\n leaseEpoch: lease.leaseEpoch,\n providerInstanceId: lease.instanceId,\n };\n}\n\nfunction beforePersistableHomeMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n home: { accountId: string; sandboxGroupId: string; backend: string } | undefined,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n }) => Promise<PersistableMutationAdmission | null>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!home || !fence) return undefined;\n return async ({ op, backend }) => {\n // A connected-machine target is intentionally non-persistable: its writes\n // do not dirty the session home's archive. Exact home identity metadata is\n // present only on a verified durable home route.\n if (\n backend.sandboxId !== null ||\n backend.leaseEpoch === undefined ||\n backend.providerInstanceId === undefined\n ) {\n return null;\n }\n const providerBinding =\n home.backend === \"modal\"\n ? await resolveModalCheckpointProviderBindingForSession(services.settings, backend.session)\n : null;\n const admission = await advanceWorkspaceGeneration(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: fence.turnId,\n executionGeneration: fence.executionGeneration,\n attemptId: fence.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(fence.attemptId),\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n operation: op,\n captureWaitMs: sandboxArchiveCaptureTimeoutMs(services.settings),\n });\n return { admission, providerBinding };\n };\n}\n\nfunction afterPersistableHomeMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n home: { accountId: string; sandboxGroupId: string; backend: string } | undefined,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n admission: unknown;\n outcome: \"resolved\" | \"rejected\";\n result?: unknown;\n retainedProcess?: RoutingRetainedProcess;\n }) => Promise<void | RoutingMutationSettlementResult>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!home || !fence) return undefined;\n return async ({ op, backend, admission, outcome, retainedProcess }) => {\n if (\n backend.sandboxId !== null ||\n backend.leaseEpoch === undefined ||\n backend.providerInstanceId === undefined ||\n !admission ||\n typeof admission !== \"object\"\n ) {\n return;\n }\n const boundAdmission = admission as Partial<PersistableMutationAdmission>;\n const exactAdmission = boundAdmission.admission;\n if (\n !exactAdmission ||\n typeof exactAdmission.id !== \"string\" ||\n typeof exactAdmission.workspaceGeneration !== \"number\" ||\n !(\"providerBinding\" in boundAdmission)\n ) {\n throw new Error(\"Persistable home mutation settlement lacked its bound admission\");\n }\n if (outcome === \"resolved\" && retainedProcess) {\n try {\n await retainWorkspaceMutationProcess(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: retainedProcess.id,\n providerSessionId: retainedProcess.providerSessionId,\n admissionId: exactAdmission.id,\n admittedWorkspaceGeneration: exactAdmission.workspaceGeneration,\n operation: op,\n providerBinding: boundAdmission.providerBinding ?? null,\n owner: {\n kind: \"turn\",\n turnId: fence.turnId,\n executionGeneration: fence.executionGeneration,\n attemptId: fence.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(fence.attemptId),\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n routeKind: exactAdmission.routeKind,\n routeTargetId: exactAdmission.routeTargetId,\n routeEpoch: exactAdmission.routeEpoch,\n },\n });\n } catch (error) {\n if (!(error instanceof SandboxRetainedProcessPromotionFencedError)) throw error;\n const durable = error.process;\n if (\n durable.id !== retainedProcess.id ||\n durable.providerSessionId !== retainedProcess.providerSessionId ||\n durable.sessionId !== ids.sessionId ||\n durable.sandboxGroupId !== home.sandboxGroupId ||\n durable.parentAdmissionId !== exactAdmission.id ||\n durable.leaseEpoch !== backend.leaseEpoch ||\n durable.providerInstanceId !== backend.providerInstanceId ||\n durable.routeKind !== exactAdmission.routeKind ||\n durable.routeTargetId !== exactAdmission.routeTargetId ||\n durable.routeEpoch !== exactAdmission.routeEpoch ||\n durable.state !== \"active\"\n ) {\n throw new Error(\"Durable retained-process promotion returned a mismatched identity\", {\n cause: error,\n });\n }\n return {\n status: \"retained_process_durable_output_rejected\",\n retainedProcess: {\n id: durable.id,\n providerSessionId: durable.providerSessionId,\n },\n };\n }\n return;\n }\n await verifyWorkspaceMutationSettlement(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: fence.turnId,\n executionGeneration: fence.executionGeneration,\n attemptId: fence.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(fence.attemptId),\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n admission: exactAdmission,\n operation: op,\n outcome,\n });\n };\n}\n\nfunction beforeRetainedProcessMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n }) => Promise<SandboxWorkspaceMutationAdmission>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ op, process }) =>\n await advanceWorkspaceGenerationForRetainedProcess(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n operation: op,\n captureWaitMs: sandboxArchiveCaptureTimeoutMs(services.settings),\n });\n}\n\nfunction afterRetainedProcessMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n admission: unknown;\n outcome: \"resolved\" | \"rejected\";\n result?: unknown;\n }) => Promise<void>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ op, process, admission, outcome }) => {\n if (\n !admission ||\n typeof admission !== \"object\" ||\n typeof (admission as Partial<SandboxWorkspaceMutationAdmission>).id !== \"string\" ||\n typeof (admission as Partial<SandboxWorkspaceMutationAdmission>).workspaceGeneration !==\n \"number\"\n ) {\n throw new Error(\"Retained-process mutation settlement lacked its exact admission\");\n }\n await verifyRetainedProcessMutationSettlement(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n admission: admission as SandboxWorkspaceMutationAdmission,\n operation: op,\n outcome,\n });\n };\n}\n\nfunction settleRetainedProcessForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n proof: RoutingRetainedProcessTerminalProof;\n }) => Promise<void>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ backend, process, proof }) => {\n const durable = await getRetainedProcess(services.db, {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n });\n if (\n !durable ||\n durable.providerSessionId !== process.providerSessionId ||\n durable.providerBackend !== backend.kind ||\n durable.providerInstanceId !== backend.providerInstanceId ||\n durable.leaseEpoch !== backend.leaseEpoch ||\n durable.routeKind !== (backend.sandboxId === null ? \"home\" : \"active\") ||\n durable.routeTargetId !== backend.sandboxId ||\n durable.routeEpoch !== backend.activeEpoch\n ) {\n throw new Error(\"Retained-process settlement lost its exact durable backend identity\");\n }\n await settleRetainedProcess(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n expected: retainedProcessSettlementIdentity(durable),\n outcome: proof.outcome,\n exitCode: proof.exitCode,\n reason: proof.reason,\n idleGraceMs: services.settings.sandboxIdleGraceMs,\n });\n };\n}\n\n/** Build the selfhosted `ControlRpc` over the events bus's request/reply\n * connection. A null bus / unconfigured NATS yields a NatsControlRpc whose\n * connection factory returns null → agent_offline on every op (never a throw). */\nfunction controlRpcFactory(bus: EventBus | undefined): () => ControlRpc {\n return () =>\n new NatsControlRpc(async (): Promise<NatsRequestConnection | null> => {\n if (!bus) {\n return null;\n }\n return bus.getRequestConnection();\n });\n}\n\n/**\n * Wrap an established group-box session in a `RoutingSandboxSession` so a mid-turn\n * swap routes the NEXT tool call to the new active sandbox. Returns the SAME\n * established handle with its `session` replaced by the stable proxy; the\n * client/sessionState/instanceId/backendId are preserved (the lease still owns\n * the group box's lifecycle — the proxy is a routing veneer, not an owner).\n *\n * The DEFAULT pointer (active_sandbox_id == null) routes to the established group\n * session unchanged (backward-compat). A swap to a selfhosted machine routes to a\n * SelfhostedSession bound to the target's enrollment agentId, fenced under the\n * swap's active_epoch.\n */\nexport function wrapTurnBoxWithRouting(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n established: EstablishedSandboxSession,\n): EstablishedSandboxSession {\n const { db, settings, bus, onOp } = services;\n const beforeMutation = beforePersistableHomeMutation(services, ids, ids.homeLease);\n const afterMutation = afterPersistableHomeMutation(services, ids, ids.homeLease);\n const beforeProcessMutation = beforeRetainedProcessMutation(services, ids);\n const afterProcessMutation = afterRetainedProcessMutation(services, ids);\n const settleProcess = settleRetainedProcessForTurn(services, ids);\n const resolver = makeActiveBackendResolver({\n workspaceId: ids.workspaceId,\n defaultBackend: established.session as RoutableBackendSession,\n defaultKind: established.backendId,\n getSandbox: async (sandboxId): Promise<RoutableSandbox | null> => {\n const sandbox = await getSandbox(db, ids.workspaceId, sandboxId);\n return sandbox\n ? {\n id: sandbox.id,\n kind: sandbox.kind,\n name: sandbox.name,\n enrollmentId: sandbox.enrollmentId,\n }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n relay: relayConfigFromSettings(settings),\n // A selfhosted swap target runs real commands too, so give it the same split\n // deadlines the machine-primary establish path uses (short control, long exec).\n ...selfhostedResolverTimeouts(settings),\n ...(onOp !== undefined ? { selfhostedOnOp: onOp } : {}),\n // The turn's declared environment → a selfhosted swap target's manifest, so the\n // SDK's per-turn manifest-env delta is empty (no \"cannot change manifest\n // environment variables\" throw when the turn pins to a vm). Mirrors the group\n // box, which is created WITH this same environment (resumeBoxForTurn).\n ...(ids.environment !== undefined ? { environment: ids.environment } : {}),\n // Stage D machine-primary: pin THIS established SelfhostedSession for the machine\n // pointer so the resolver returns the SAME instance (no two-instance manifest\n // divergence). `established.session` is the SelfhostedSession the establish branch\n // bound to (sandboxId, epoch).\n ...(ids.pinnedSelfhosted\n ? {\n pinnedSelfhosted: {\n sandboxId: ids.pinnedSelfhosted.sandboxId,\n epoch: ids.pinnedSelfhosted.epoch,\n session: established.session as RoutableBackendSession,\n },\n }\n : {}),\n // A modal swap target in the turn path would need its own lease resume-by-id;\n // that is a future cross-group-box concern. Until then a modal swap target is\n // unresolvable (the swap tool validates liveness, so this only triggers if a\n // session points at a sibling modal box the turn cannot resume here) and the\n // op surfaces unresolvable — never a silent wrong-box landing.\n //\n // For a machine-primary turn of a Modal-HOME session (pinned to a machine, no\n // group box established this turn), a mid-turn clear-to-null must NOT fall back to\n // the pinned machine — passing defaultIsHome:false makes the null branch throw typed\n // `home_unavailable_this_turn` instead. Forward the explicit boolean (including false).\n ...(ids.defaultIsHome !== undefined ? { defaultIsHome: ids.defaultIsHome } : {}),\n ...(ids.homeLease\n ? {\n resolveDefaultBackend: () =>\n resolveCurrentHomeBackend(\n services,\n {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n accountId: ids.homeLease!.accountId,\n sandboxGroupId: ids.homeLease!.sandboxGroupId,\n backend: ids.homeLease!.backend,\n },\n established,\n ),\n }\n : {}),\n });\n\n const proxy = new RoutingSandboxSession({\n // Seed the DEFAULT backend (the established group box) at construction so\n // `session.state` is the real backend's state object BEFORE the first op. The\n // SDK reads `session.state.manifest` at turn START (and writes it back); an\n // empty `{}` there crashes serializeManifestEnvironment /\n // validateProvidedSessionManifestUpdate. This is byte-identical to what the\n // resolver returns for the default pointer (`activeSandboxId === null`).\n defaultResolved: {\n session: established.session as RoutableBackendSession,\n sandboxId: null,\n kind: established.backendId,\n ...(ids.homeLease\n ? {\n leaseEpoch: ids.homeLease.leaseEpoch,\n providerInstanceId: ids.homeLease.instanceId,\n }\n : {}),\n },\n readPointer: async () => {\n if (!routingEnabled(settings)) {\n return { activeSandboxId: null, activeEpoch: 0 };\n }\n const pointer = await readActiveSandbox(db, ids.workspaceId, ids.sessionId);\n return pointer ?? { activeSandboxId: null, activeEpoch: 0 };\n },\n resolveActiveBackend: resolver,\n ...(services.onSandboxOperation ? { onOperation: services.onSandboxOperation } : {}),\n ...(beforeMutation ? { beforeMutation } : {}),\n ...(afterMutation ? { afterMutation } : {}),\n ...(beforeProcessMutation ? { beforeProcessMutation } : {}),\n ...(afterProcessMutation ? { afterProcessMutation } : {}),\n ...(settleProcess ? { settleProcess } : {}),\n ...(ids.homeLease\n ? {\n onDefaultBackendError: async ({\n error,\n backend,\n }: {\n error: unknown;\n backend: ResolvedActiveBackend;\n }) => {\n const home = ids.homeLease!;\n if (!isProviderSandboxGoneDuringRoutedOperation(home.backend, error)) return null;\n const expectedEpoch = backend.leaseEpoch ?? home.leaseEpoch;\n const expectedInstanceId = backend.providerInstanceId ?? home.instanceId;\n const marked = await markWarmLeaseInstanceLost(db, {\n accountId: home.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch,\n expectedInstanceId,\n diagnostic: \"provider_not_found_during_routed_operation\",\n });\n if (marked.status === \"marked\") {\n await services.onHomeSandboxLost?.({\n sandboxGroupId: home.sandboxGroupId,\n instanceId: expectedInstanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n }\n const lease = marked.lease;\n const restore = lease?.recovery.restore.status;\n return {\n leaseEpoch: lease?.leaseEpoch ?? expectedEpoch,\n recovery:\n marked.status === \"stale\"\n ? (\"superseded\" as const)\n : restore === \"pending\"\n ? (\"pending\" as const)\n : restore === \"degraded\"\n ? (\"degraded\" as const)\n : (\"unrecoverable\" as const),\n };\n },\n }\n : {}),\n });\n\n return { ...established, session: proxy };\n}\n\nexport function wrapLazyTurnBoxWithRouting(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n args: {\n client: EstablishedSandboxSession[\"client\"];\n backendId: string;\n agentDefaultManifest: unknown;\n provisioner: {\n get(): Promise<{\n established: EstablishedSandboxSession;\n leaseEpoch?: number;\n }>;\n };\n homeLeaseIdentity?: {\n accountId: string;\n sandboxGroupId: string;\n backend: string;\n };\n },\n): EstablishedSandboxSession {\n const { db, settings, bus, onOp } = services;\n const beforeMutation = beforePersistableHomeMutation(services, ids, args.homeLeaseIdentity);\n const afterMutation = afterPersistableHomeMutation(services, ids, args.homeLeaseIdentity);\n const beforeProcessMutation = beforeRetainedProcessMutation(services, ids);\n const afterProcessMutation = afterRetainedProcessMutation(services, ids);\n const settleProcess = settleRetainedProcessForTurn(services, ids);\n const syntheticSession: RoutableBackendSession = {\n state: { manifest: args.agentDefaultManifest },\n };\n const routedResolver = makeActiveBackendResolver({\n workspaceId: ids.workspaceId,\n defaultBackend: syntheticSession,\n defaultKind: \"unprovisioned\",\n getSandbox: async (sandboxId): Promise<RoutableSandbox | null> => {\n const sandbox = await getSandbox(db, ids.workspaceId, sandboxId);\n return sandbox\n ? {\n id: sandbox.id,\n kind: sandbox.kind,\n name: sandbox.name,\n enrollmentId: sandbox.enrollmentId,\n }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n relay: relayConfigFromSettings(settings),\n ...selfhostedResolverTimeouts(settings),\n ...(onOp !== undefined ? { selfhostedOnOp: onOp } : {}),\n ...(ids.environment !== undefined ? { environment: ids.environment } : {}),\n });\n\n const proxy = new RoutingSandboxSession({\n // Before the first op the SDK reads `state.manifest`; the synthetic backend\n // points at agent.defaultManifest BY REFERENCE so the provided-session delta is\n // empty. The first default-pointer op resolves the real box through the\n // provisioner and `state` switches to that real backend by reference.\n defaultResolved: {\n session: syntheticSession,\n sandboxId: null,\n kind: \"unprovisioned\",\n },\n readPointer: async () => {\n const pointer = await readActiveSandbox(db, ids.workspaceId, ids.sessionId);\n return pointer ?? { activeSandboxId: null, activeEpoch: 0 };\n },\n resolveActiveBackend: async (pointer) => {\n if (pointer.activeSandboxId === null || !routingEnabled(settings)) {\n const provisioned = await args.provisioner.get();\n if (args.homeLeaseIdentity && provisioned.leaseEpoch !== undefined) {\n return resolveCurrentHomeBackend(\n services,\n {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n accountId: args.homeLeaseIdentity.accountId,\n sandboxGroupId: args.homeLeaseIdentity.sandboxGroupId,\n backend: args.homeLeaseIdentity.backend,\n },\n provisioned.established,\n );\n }\n return {\n session: provisioned.established.session as RoutableBackendSession,\n sandboxId: null,\n kind: provisioned.established.backendId,\n };\n }\n return routedResolver(pointer);\n },\n ...(services.onSandboxOperation ? { onOperation: services.onSandboxOperation } : {}),\n ...(beforeMutation ? { beforeMutation } : {}),\n ...(afterMutation ? { afterMutation } : {}),\n ...(beforeProcessMutation ? { beforeProcessMutation } : {}),\n ...(afterProcessMutation ? { afterProcessMutation } : {}),\n ...(settleProcess ? { settleProcess } : {}),\n ...(args.homeLeaseIdentity\n ? {\n onDefaultBackendError: async ({\n error,\n backend,\n }: {\n error: unknown;\n backend: ResolvedActiveBackend;\n }) => {\n const home = args.homeLeaseIdentity!;\n if (!isProviderSandboxGoneDuringRoutedOperation(home.backend, error)) return null;\n if (backend.leaseEpoch === undefined || backend.providerInstanceId === undefined) {\n return null;\n }\n const marked = await markWarmLeaseInstanceLost(db, {\n accountId: home.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n diagnostic: \"provider_not_found_during_routed_operation\",\n });\n if (marked.status === \"marked\") {\n await services.onHomeSandboxLost?.({\n sandboxGroupId: home.sandboxGroupId,\n instanceId: backend.providerInstanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n }\n const lease = marked.lease;\n const restore = lease?.recovery.restore.status;\n return {\n leaseEpoch: lease?.leaseEpoch ?? backend.leaseEpoch,\n recovery:\n marked.status === \"stale\"\n ? (\"superseded\" as const)\n : restore === \"pending\"\n ? (\"pending\" as const)\n : restore === \"degraded\"\n ? (\"degraded\" as const)\n : (\"unrecoverable\" as const),\n };\n },\n }\n : {}),\n });\n\n return {\n client: args.client,\n session: proxy,\n sessionState: undefined,\n instanceId: \"unprovisioned\",\n backendId: args.backendId,\n };\n}\n\nexport type SelfhostedTurnSessionArgs = {\n workspaceId: string;\n /** The target machine's enrollment id == the agent subject id. */\n agentId: string;\n /** Whether the target machine advertised Capabilities.op_stream in its latest\n * Hello. The runtime-side transport gate must still require the server flag. */\n opStream: boolean;\n /** The active pointer's epoch — the control-op fence echoed to the agent. */\n epoch: number;\n /** The run's declared sandbox environment (the SAME object fed to buildAgent +\n * the manifest), threaded so the SDK's per-turn provided-session env delta is\n * empty. */\n environment: Record<string, string>;\n /** The session working directory (per-session pointer). Null ⇒ workspace_root. */\n workingDir: string | null;\n};\n\ntype LegacySelfhostedTurnSessionArgs = Omit<SelfhostedTurnSessionArgs, \"opStream\">;\n\n/**\n * Stage D machine-primary establish: bind the live SelfhostedSession for a turn\n * whose ACTIVE sandbox is a connected machine — WITHOUT establishing or leasing a\n * phantom Modal home box. Reuses the SAME relay + ControlRpc wiring `wrapTurnBoxWithRouting`\n * builds (so the turn session and a later swap target dial the machine identically),\n * and the SAME `buildSelfhostedBackendSession` factory the routing resolver uses\n * (one build shape). Returns an `EstablishedSandboxSession` whose:\n * - `client` is the SelfhostedSandboxClient (the OWNED-sandbox client the turn\n * injects; its `serializeSessionState` round-trips `{agentId}`);\n * - `session` is the live SelfhostedSession (the routing default + pin instance);\n * - `backendId` is \"selfhosted\" (drives recording's desktopCapableBackend gate +\n * the warm-rate keying) and `instanceId` is the enrollment/agent id.\n * No NATS round-trip happens here — `resume()` just re-addresses the subject — so a\n * headless/offline machine binds fine; its ops surface agent_offline lazily.\n */\n/**\n * The op-stream injection for a machine-primary turn: present iff the machine\n * advertised `Capabilities.op_stream` in its latest Hello AND the server flag\n * is on AND a bus exists to carry frames. The transport rides the SAME managed\n * NATS connection as the control rpc (the bus's op-stream accessor); a bus\n * without the accessor (a test double) simply yields no connection and the\n * session falls back to the legacy exec on first use. Swap TARGETS resolved\n * mid-turn stay legacy for now — their capability row is not at hand in the\n * resolver, and legacy is always correct.\n */\nfunction opStreamDepsFor(\n services: RoutingWiringServices,\n machineAdvertisesOpStream: boolean,\n): SelfhostedOpStreamDeps | undefined {\n const { settings, bus, opJournal } = services;\n if (!machineAdvertisesOpStream || settings.agentOpStreamEnabled !== true || !bus) {\n return undefined;\n }\n return {\n transport: new NatsOpStreamTransport(async () => bus.getOpStreamConnection?.() ?? null),\n ...(opJournal !== undefined ? { journal: opJournal } : {}),\n };\n}\n\nexport async function establishSelfhostedTurnSession(\n services: RoutingWiringServices,\n args: SelfhostedTurnSessionArgs | LegacySelfhostedTurnSessionArgs,\n): Promise<EstablishedSandboxSession> {\n const { settings, bus, onOp } = services;\n const { timeoutMs, execTimeoutMs } = selfhostedTimeoutsFromSettings(settings);\n const opStream = opStreamDepsFor(services, \"opStream\" in args && args.opStream === true);\n const { client, session } = await buildSelfhostedBackendSession({\n workspaceId: args.workspaceId,\n agentId: args.agentId,\n relay: relayConfigFromSettings(settings),\n controlRpcFactory: controlRpcFactory(bus),\n epoch: args.epoch,\n environment: args.environment,\n workingDir: args.workingDir,\n // Give this turn's exec ops the long deadline (control ops stay short) so a real\n // command is not killed at the control wall.\n timeoutMs,\n execTimeoutMs,\n // Meter every control op (out-of-band telemetry) — no-op when unwired.\n ...(onOp !== undefined ? { onOp } : {}),\n // The streaming exec transport — present iff the machine advertised the\n // capability AND the server flag is on (latched per-op at OpStart; the\n // legacy exec stays the permanent fallback wire form).\n ...(opStream !== undefined ? { opStream } : {}),\n });\n return {\n client,\n session,\n sessionState: { agentId: args.agentId },\n instanceId: args.agentId,\n backendId: \"selfhosted\",\n };\n}\n\n/** Whether the routing proxy should wrap the turn box: the hot-swap feature is\n * gated by the selfhosted flag (the active pointer + swap tools are only\n * meaningful when selfhosted is enabled). With the flag off the established\n * group box is injected unchanged — byte-for-byte today. */\nexport function routingEnabled(settings: Settings): boolean {\n return settings.sandboxSelfhostedEnabled === true;\n}\n\n/** Whether the turn should defer sandbox provisioning to the first dispatched op\n * (the in-process single-flight provisioner behind the routing proxy's\n * resolveActiveBackend). Lazy is a property of the OWNED path only — the SDK never\n * creates/resumes an injected session, so we own establish timing — hence gated on\n * BOTH flags. With either off the turn provisions eagerly at turn start, exactly as\n * today. NB: under lazy the box is ALWAYS wrapped in the routing proxy (the proxy's\n * resolver IS the establish seam), independent of `routingEnabled`. */\nexport function lazyProvisionEnabled(settings: Settings): boolean {\n return settings.sandboxLazyProvisionEnabled === true && settings.sandboxOwnershipEnabled === true;\n}\n","// The Temporal adaptation of the op-stream durable-resume journal\n// (`OpStreamJournal`, @opengeni/runtime): the runtime leaf stays\n// Temporal-free; this is where its two seams bind to the activity.\n//\n// * `attachGeneration` — the consumer generation the runner fences zombie\n// consumers by. `Info.attempt` CANNOT serve here: `runAgentTurn` runs with\n// `maximumAttempts: 1`, so worker death is healed by the WORKFLOW\n// redispatching a NEW activity whose attempt is 1 again. The activity's\n// `currentAttemptScheduledTimestampMs` is Temporal-server-assigned and\n// strictly larger for a later dispatch (death detection is bounded below by\n// the 2-minute heartbeat timeout, far above ms resolution), so it is a\n// monotonic generation with zero workflow plumbing. Intra-activity\n// re-attaches (blip/gap heals) reuse it — the runner's equal-generation\n// replay path.\n//\n// * `persistSettled` — the durable-before-wire-ack ordering hook: fold the\n// settled op's frontier into the activity's shared heartbeat details and\n// flush a heartbeat BEFORE the client publishes the final ack. The shared\n// `details` object is the SAME one every other heartbeat site spreads, so a\n// later phase heartbeat re-carries the roster instead of clobbering it.\n\nimport type { Context } from \"@temporalio/activity\";\nimport type { OpStreamJournal } from \"@opengeni/runtime\";\n\n/** The activity's shared heartbeat-details object: every heartbeat call site\n * spreads THIS one object (plus its own phase), so fields like the op-ack\n * roster survive across sites instead of being lost to last-write-wins. */\nexport interface TurnHeartbeatDetails extends Record<string, unknown> {\n /** Settled-op roster: durable op id → its exit seq (the final-ack frontier). */\n opAcks: Record<string, string>;\n}\n\nexport function makeTurnOpJournal(\n context: Context | null,\n details: TurnHeartbeatDetails,\n): OpStreamJournal {\n return {\n attachGeneration: () => String(context?.info.currentAttemptScheduledTimestampMs ?? 1),\n persistSettled: (opId, exitSeq) => {\n details.opAcks[opId] = exitSeq;\n // Flush immediately (heartbeats are also sent on the 10s timer; this one\n // exists so the persist precedes the wire final ack, not just eventually).\n context?.heartbeat({ ...details, phase: \"op_settled\", at: new Date().toISOString() });\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { errorCodeToJSON } from \"@opengeni/agent-proto\";\nimport { SandboxBackend, type SessionEventType } from \"@opengeni/contracts\";\nimport type { EventLogger } from \"@opengeni/events\";\nimport type { Attributes, AttributeValue, Observability } from \"@opengeni/observability\";\nimport {\n SELFHOSTED_INFRASTRUCTURE_FAULT_CLASSES,\n modelUsageTokenCountOrNull,\n type RuntimeMetricsHooks,\n type SelfhostedOpObservation,\n type SelfhostedOpObserver,\n} from \"@opengeni/runtime\";\n\nexport type TurnOutcome = \"completed\" | \"failed\" | \"cancelled\" | \"recovering\";\nexport type CreditMicrosKind = \"usage\" | \"grant\" | \"topup\" | \"refund\";\nexport type SandboxLeaseLiveness = \"cold\" | \"warming\" | \"warm\" | \"draining\";\nexport type CreditBalanceGauge = { accountId: string; balanceMicros: number };\n\nconst turnTrackers = new WeakMap<Observability, TurnLifecycleMetrics>();\nconst creditBalanceGaugeAccounts = new WeakMap<Observability, Set<string>>();\nconst modelCacheCounterTotals = new WeakMap<Observability, Map<string, number>>();\n\n// A worker process reaching one trillion tokens in one provider/cache counter is\n// already far outside an ordinary scrape lifetime. Refuse further increments\n// before floating-point precision can degrade; a restart resets both the\n// process-local Prometheus registry and this guard together.\nconst MAX_MODEL_CACHE_COUNTER_TOTAL = 1_000_000_000_000;\n\nexport function observabilityEventLogger(observability: Observability): EventLogger {\n return {\n debug: (message, attributes) => observability.debug(message, eventAttributes(attributes)),\n warn: (message, attributes) => observability.warn(message, eventAttributes(attributes)),\n };\n}\n\nfunction eventAttributes(attributes: Record<string, unknown> | undefined): Attributes | undefined {\n if (!attributes) {\n return undefined;\n }\n const sanitized: Attributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n sanitized[key] = eventAttributeValue(value);\n }\n return sanitized;\n}\n\nfunction eventAttributeValue(value: unknown): AttributeValue {\n if (\n value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport function runtimeMetricsHooksForObservability(\n observability: Observability,\n): RuntimeMetricsHooks {\n return {\n onModelCall: ({ provider, outcome, durationSeconds }) => {\n observability.incrementCounter({\n name: \"opengeni_model_calls_total\",\n help: \"Total model calls by provider and outcome.\",\n labels: { provider, outcome },\n });\n observability.observeHistogram({\n name: \"opengeni_model_call_duration_seconds\",\n help: \"Model call duration in seconds by provider.\",\n labels: { provider },\n value: durationSeconds,\n });\n },\n onSandboxCreate: ({ backend, outcome, durationSeconds }) => {\n observability.incrementCounter({\n name: \"opengeni_sandbox_creates_total\",\n help: \"Total sandbox create attempts by backend and outcome.\",\n labels: { backend, outcome },\n });\n observability.observeHistogram({\n name: \"opengeni_sandbox_create_duration_seconds\",\n help: \"Sandbox create duration in seconds by backend.\",\n labels: { backend },\n value: durationSeconds,\n });\n },\n onSandboxWarmingTimeout: () => {\n observability.incrementCounter({\n name: \"opengeni_sandbox_warming_timeouts_total\",\n help: \"Total sandbox warming timeouts.\",\n });\n },\n onSandboxOp: ({ backend, op, outcome, code, healed, durationSeconds, replyBytes }) => {\n observability.incrementCounter({\n name: \"opengeni_machine_op_total\",\n help: \"Total Connected Machine control ops by op, outcome, and typed fault code.\",\n labels: { backend, op, outcome, code: code ?? \"\" },\n });\n observability.observeHistogram({\n name: \"opengeni_machine_op_duration_seconds\",\n help: \"Connected Machine control-op duration in seconds by op.\",\n labels: { backend, op },\n value: durationSeconds,\n });\n // The healed-fault leading indicator: an op that only succeeded after a retry\n // (a blip/backpressure the transport absorbed). The doctrine: healed faults are\n // the leading indicator of the next unhealed one, so they are always recorded.\n if (healed) {\n observability.incrementCounter({\n name: \"opengeni_machine_op_healed_total\",\n help: \"Connected Machine ops that succeeded only after ≥1 in-call retry.\",\n labels: { backend, op },\n });\n }\n // The payload-wall indicator (bytes known only on a PAYLOAD_TOO_LARGE fault today).\n if (replyBytes !== undefined) {\n observability.observeHistogram({\n name: \"opengeni_machine_op_reply_bytes\",\n help: \"Connected Machine control-op reply size in bytes (payload-wall indicator).\",\n labels: { backend, op },\n value: replyBytes,\n });\n }\n },\n };\n}\n\n/**\n * Adapt the runtime's transport-agnostic `SelfhostedOpObserver` to the metrics\n * hooks: map a completed-op observation onto `onSandboxOp`, converting the wire\n * `ErrorCode` to its stable enum-name string (a bounded metric label) and the\n * duration to seconds. Wired into the selfhosted session build so every Connected\n * Machine control op meters.\n */\nexport function selfhostedOpObserverForMetrics(hooks: RuntimeMetricsHooks): SelfhostedOpObserver {\n return (o) => {\n hooks.onSandboxOp?.({\n backend: \"selfhosted\",\n op: o.op,\n outcome: o.outcome,\n healed: o.healed,\n retries: o.retries,\n durationSeconds: o.durationMs / 1000,\n ...(o.code !== undefined ? { code: errorCodeToJSON(o.code) } : {}),\n ...(o.replyBytes !== undefined ? { replyBytes: o.replyBytes } : {}),\n });\n };\n}\n\n/** A session-scoped `machine.op.*` event mapped from a completed-op observation. */\nexport type MachineOpSessionEvent = {\n type: \"machine.op.failed\" | \"machine.op.recovered\";\n payload: { op: string; faultClass: string; attempts: number; machineId?: string };\n};\n\n/** Map an observation to a `machine.op.*` session event, or null if it is not\n * eventable. `machine.op.failed` fires ONLY for infrastructure fault classes (a\n * semantic miss the model asked about is an outcome, not an infra fault);\n * `machine.op.recovered` fires for a healed op (success after ≥1 retry). */\nexport function machineOpSessionEventFor(o: SelfhostedOpObservation): MachineOpSessionEvent | null {\n if (\n o.outcome === \"failed\" &&\n o.faultClass &&\n SELFHOSTED_INFRASTRUCTURE_FAULT_CLASSES.has(o.faultClass)\n ) {\n return {\n type: \"machine.op.failed\",\n payload: {\n op: o.op,\n faultClass: o.faultClass,\n attempts: o.retries,\n ...(o.machineId ? { machineId: o.machineId } : {}),\n },\n };\n }\n if (o.outcome === \"ok\" && o.healed) {\n return {\n type: \"machine.op.recovered\",\n payload: {\n op: o.op,\n faultClass: o.faultClass ?? \"unknown\",\n attempts: o.retries,\n ...(o.machineId ? { machineId: o.machineId } : {}),\n },\n };\n }\n return null;\n}\n\n/**\n * The Connected Machine op observer wired into a turn: it meters EVERY op (the\n * metrics sink) and BUFFERS the eventable ops (infra failures + healed recoveries)\n * as `machine.op.*` session events. The observer is SYNC (fire-and-forget), so the\n * turn drains the buffer to durable session events at a known checkpoint (turn end),\n * awaited — never an unawaited DB write inside the Temporal activity.\n */\nexport function makeMachineOpObserver(hooks: RuntimeMetricsHooks): {\n observer: SelfhostedOpObserver;\n drainEvents(): MachineOpSessionEvent[];\n} {\n const meter = selfhostedOpObserverForMetrics(hooks);\n const buffered: MachineOpSessionEvent[] = [];\n return {\n observer: (o) => {\n meter(o);\n const event = machineOpSessionEventFor(o);\n if (event) {\n buffered.push(event);\n }\n },\n drainEvents: () => buffered.splice(0, buffered.length),\n };\n}\n\nexport function turnLifecycleMetricsFor(observability: Observability): TurnLifecycleMetrics {\n const existing = turnTrackers.get(observability);\n if (existing) {\n return existing;\n }\n const tracker = new TurnLifecycleMetrics(observability);\n turnTrackers.set(observability, tracker);\n return tracker;\n}\n\nexport class TurnLifecycleMetrics {\n private readonly startedTurns = new Map<string, number>();\n private timer: ReturnType<typeof setInterval> | null = null;\n\n constructor(\n private readonly observability: Observability,\n private readonly options: { now?: () => number; refreshIntervalMs?: number } = {},\n ) {}\n\n start(turnId: string): void {\n this.startedTurns.set(turnId, this.now());\n this.ensureTimer();\n this.refreshGauges();\n }\n\n finish(turnId: string, outcome: TurnOutcome | null, durationSeconds?: number): void {\n const startedAt = this.startedTurns.get(turnId);\n if (startedAt !== undefined) {\n this.startedTurns.delete(turnId);\n }\n if (outcome) {\n const observedDuration =\n durationSeconds ??\n (startedAt === undefined ? 0 : Math.max(0, (this.now() - startedAt) / 1000));\n this.observability.incrementCounter({\n name: \"opengeni_turns_total\",\n help: \"Total agent turns by terminal outcome.\",\n labels: { outcome },\n });\n this.observability.observeHistogram({\n name: \"opengeni_turn_duration_seconds\",\n help: \"Agent turn duration in seconds by terminal outcome.\",\n labels: { outcome },\n value: observedDuration,\n });\n }\n this.refreshGauges();\n if (this.startedTurns.size === 0) {\n this.stopTimer();\n }\n }\n\n refreshGauges(): void {\n this.observability.setGauge({\n name: \"opengeni_turns_inflight\",\n help: \"Current number of in-flight agent turns in this worker process.\",\n value: this.startedTurns.size,\n });\n this.observability.setGauge({\n name: \"opengeni_turn_oldest_inflight_age_seconds\",\n help: \"Age in seconds of the oldest in-flight agent turn in this worker process.\",\n value: this.oldestInflightAgeSeconds(),\n });\n }\n\n stop(): void {\n this.startedTurns.clear();\n this.refreshGauges();\n this.stopTimer();\n }\n\n private oldestInflightAgeSeconds(): number {\n if (this.startedTurns.size === 0) {\n return 0;\n }\n let oldest = Number.POSITIVE_INFINITY;\n for (const startedAt of this.startedTurns.values()) {\n oldest = Math.min(oldest, startedAt);\n }\n return Math.max(0, (this.now() - oldest) / 1000);\n }\n\n private ensureTimer(): void {\n if (this.timer) {\n return;\n }\n this.timer = setInterval(() => this.refreshGauges(), this.options.refreshIntervalMs ?? 15_000);\n this.timer.unref?.();\n }\n\n private stopTimer(): void {\n if (!this.timer) {\n return;\n }\n clearInterval(this.timer);\n this.timer = null;\n }\n\n private now(): number {\n return this.options.now?.() ?? Date.now();\n }\n}\n\nexport function recordTurnsQueuedGauge(observability: Observability, value: number): void {\n observability.setGauge({\n name: \"opengeni_turns_queued\",\n help: \"Current number of queued session turns.\",\n value,\n });\n}\n\nexport function recordSandboxLeaseGauges(\n observability: Observability,\n counts: Partial<Record<SandboxLeaseLiveness, number>>,\n): void {\n for (const liveness of [\"cold\", \"warming\", \"warm\", \"draining\"] as const) {\n observability.setGauge({\n name: \"opengeni_sandbox_leases\",\n help: \"Current sandbox leases by liveness state.\",\n labels: { liveness },\n value: counts[liveness] ?? 0,\n });\n }\n}\n\nexport const SANDBOX_INVENTORY_PROJECTION_DOMAINS = [\n \"leases\",\n \"checkpoint_artifacts\",\n \"rotation_backlog\",\n \"retained_processes\",\n \"expired_drains\",\n] as const;\n\nexport type SandboxInventoryProjectionDomain =\n (typeof SANDBOX_INVENTORY_PROJECTION_DOMAINS)[number];\n\nexport function recordSandboxInventoryProjectionSuccess(\n observability: Observability,\n domain: SandboxInventoryProjectionDomain,\n timestampSeconds = Date.now() / 1_000,\n): void {\n observability.setGauge({\n name: \"opengeni_sandbox_inventory_refresh_timestamp_seconds\",\n help: \"Unix timestamp of the last complete successful sandbox inventory projection by domain.\",\n labels: { domain },\n value: timestampSeconds,\n });\n}\n\nexport function recordSandboxInventoryProjectionFailure(\n observability: Observability,\n domain: SandboxInventoryProjectionDomain,\n): void {\n observability.incrementCounter({\n name: \"opengeni_sandbox_inventory_refresh_failures_total\",\n help: \"Failed sandbox inventory projection refreshes by domain.\",\n labels: { domain },\n });\n}\n\nexport function recordCreditBalanceGauges(\n observability: Observability,\n balances: CreditBalanceGauge[],\n): void {\n const previous = creditBalanceGaugeAccounts.get(observability) ?? new Set<string>();\n const current = new Set<string>();\n for (const balance of balances) {\n current.add(balance.accountId);\n observability.setGauge({\n name: \"opengeni_credit_balance_micros\",\n help: \"Current credit balance in micros by account.\",\n labels: { account_id: balance.accountId },\n value: balance.balanceMicros,\n });\n }\n for (const accountId of previous) {\n if (!current.has(accountId)) {\n observability.setGauge({\n name: \"opengeni_credit_balance_micros\",\n help: \"Current credit balance in micros by account.\",\n labels: { account_id: accountId },\n value: 0,\n });\n }\n }\n creditBalanceGaugeAccounts.set(observability, current);\n}\n\nexport function recordSandboxOrphansTerminated(observability: Observability, count: number): void {\n if (count <= 0) {\n return;\n }\n observability.incrementCounter({\n name: \"opengeni_sandbox_orphans_terminated_total\",\n help: \"Total provider-side orphan sandboxes terminated by defensive sweeps.\",\n amount: count,\n });\n}\n\nexport type SandboxCheckpointArtifactMetricState =\n | \"candidate\"\n | \"current\"\n | \"previous\"\n | \"delete_pending\"\n | \"deleting\"\n | \"delete_failed\"\n | \"deleted\";\n\nexport function recordSandboxCheckpointArtifactGauges(\n observability: Observability,\n counts: Record<SandboxCheckpointArtifactMetricState, number>,\n): void {\n for (const state of [\n \"candidate\",\n \"current\",\n \"previous\",\n \"delete_pending\",\n \"deleting\",\n \"delete_failed\",\n \"deleted\",\n ] as const) {\n observability.setGauge({\n name: \"opengeni_sandbox_checkpoint_artifacts\",\n help: \"Current durable provider checkpoint artifacts by lifecycle state.\",\n labels: { state },\n value: counts[state],\n });\n }\n}\n\nexport type SandboxCheckpointArtifactOutcome =\n | \"legacy_adopted\"\n | \"claimed\"\n | \"deleted\"\n | \"delete_failed\"\n | \"tombstone_pruned\";\n\nexport function recordSandboxCheckpointArtifactOutcome(\n observability: Observability,\n outcome: SandboxCheckpointArtifactOutcome,\n count = 1,\n): void {\n if (count <= 0) return;\n observability.incrementCounter({\n name: \"opengeni_sandbox_checkpoint_artifact_operations_total\",\n help: \"Durable provider checkpoint artifact operations by fixed outcome.\",\n labels: { outcome },\n amount: count,\n });\n}\n\nexport function recordSandboxDeadlineRotationsRequested(\n observability: Observability,\n count: number,\n): void {\n if (count <= 0) return;\n observability.incrementCounter({\n name: \"opengeni_sandbox_deadline_rotations_requested_total\",\n help: \"Total finite-lifetime sandbox rotations requested before provider deadline.\",\n amount: count,\n });\n}\n\nexport function recordSandboxRotationBacklogGauges(\n observability: Observability,\n backlog: {\n requested: number;\n overdue: number;\n turnBlocked: number;\n directBlocked: number;\n processBlocked: number;\n },\n): void {\n const values = {\n requested: backlog.requested,\n overdue: backlog.overdue,\n turn_blocked: backlog.turnBlocked,\n direct_blocked: backlog.directBlocked,\n process_blocked: backlog.processBlocked,\n } as const;\n for (const [kind, value] of Object.entries(values)) {\n observability.setGauge({\n name: \"opengeni_sandbox_rotation_backlog\",\n help: \"Current finite-lifetime sandbox rotation backlog by fixed condition.\",\n labels: { kind },\n value,\n });\n }\n}\n\nconst RETAINED_PROCESS_OWNER_STATES = [\n \"direct\",\n \"queued\",\n \"running\",\n \"requires_action\",\n \"recovering\",\n \"waiting_capacity\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n \"superseded\",\n \"withdrawn_for_edit\",\n \"missing\",\n \"unknown\",\n] as const;\n\nconst RETAINED_PROCESS_OWNER_STATE_SET = new Set<string>(RETAINED_PROCESS_OWNER_STATES);\n\nexport function recordRetainedProcessInventoryGauges(\n observability: Observability,\n counts: Array<{ ownerState: string; activeCount: number; terminalOwnerCount: number }>,\n): void {\n const normalized = new Map<string, { active: number; terminal: number }>();\n for (const ownerState of RETAINED_PROCESS_OWNER_STATES) {\n normalized.set(ownerState, { active: 0, terminal: 0 });\n }\n for (const count of counts) {\n const ownerState = RETAINED_PROCESS_OWNER_STATE_SET.has(count.ownerState)\n ? count.ownerState\n : \"unknown\";\n const current = normalized.get(ownerState)!;\n current.active += Math.max(0, count.activeCount);\n current.terminal += Math.max(0, count.terminalOwnerCount);\n }\n\n for (const [ownerState, count] of normalized) {\n observability.setGauge({\n name: \"opengeni_retained_processes_active\",\n help: \"Current active retained provider processes by durable owner state.\",\n labels: { owner_state: ownerState },\n value: count.active,\n });\n observability.setGauge({\n name: \"opengeni_retained_processes_terminal_owner_backlog\",\n help: \"Current active retained processes whose exact owner attempt is terminal.\",\n labels: { owner_state: ownerState },\n value: count.terminal,\n });\n }\n}\n\nexport const EXPIRED_DRAINING_BACKENDS = [...SandboxBackend.options, \"unknown\"] as const;\nconst EXPIRED_DRAINING_BACKEND_SET = new Set<string>(EXPIRED_DRAINING_BACKENDS);\nexport const EXPIRED_DRAINING_AGE_BUCKETS = [\"lt_5m\", \"5m_1h\", \"1h_1d\", \"gte_1d\"] as const;\n\nexport function recordExpiredDrainingSandboxLeaseGauges(\n observability: Observability,\n counts: Array<{ backend: string; ageBucket: string; count: number }>,\n): void {\n const normalized = new Map<string, number>();\n for (const backend of EXPIRED_DRAINING_BACKENDS) {\n for (const ageBucket of EXPIRED_DRAINING_AGE_BUCKETS) {\n normalized.set(`${backend}:${ageBucket}`, 0);\n }\n }\n for (const count of counts) {\n const backend = EXPIRED_DRAINING_BACKEND_SET.has(count.backend) ? count.backend : \"unknown\";\n if (!EXPIRED_DRAINING_AGE_BUCKETS.includes(count.ageBucket as never)) continue;\n const key = `${backend}:${count.ageBucket}`;\n normalized.set(key, (normalized.get(key) ?? 0) + Math.max(0, count.count));\n }\n for (const [key, value] of normalized) {\n const [backend, ageBucket] = key.split(\":\") as [string, string];\n observability.setGauge({\n name: \"opengeni_sandbox_leases_expired_draining\",\n help: \"Current expired draining sandbox leases by backend and fixed age bucket.\",\n labels: { backend, age_bucket: ageBucket },\n value,\n });\n }\n}\n\nexport const RETAINED_PROCESS_RECONCILIATION_OUTCOMES = [\n \"claim_failed\",\n \"proof_exited\",\n \"proof_lost\",\n \"proof_checkpoint_failed\",\n \"settled_exited\",\n \"settled_lost\",\n \"settlement_failed\",\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 \"provider_binding_adopted\",\n \"defer_failed\",\n] as const;\n\nexport type RetainedProcessReconciliationOutcome =\n (typeof RETAINED_PROCESS_RECONCILIATION_OUTCOMES)[number];\n\nexport function recordRetainedProcessReconciliation(\n observability: Observability,\n outcome: RetainedProcessReconciliationOutcome,\n): void {\n observability.incrementCounter({\n name: \"opengeni_retained_process_reconciliation_total\",\n help: \"Bounded retained-process reconciliation observations by fixed app outcome.\",\n labels: { outcome },\n });\n}\n\nexport function recordCreditMicros(\n observability: Observability | undefined,\n kind: CreditMicrosKind,\n amountMicros: number,\n): void {\n if (!observability || amountMicros <= 0) {\n return;\n }\n observability.incrementCounter({\n name: \"opengeni_credit_micros_total\",\n help: \"Total credit micros recorded by kind.\",\n labels: { kind },\n amount: amountMicros,\n });\n}\n\n// ── Streaming SLIs ────────────────────────────────────────────────────────────\n// Instruments the token-streaming pipeline so \"streaming is sluggish\" is a number,\n// not a vibe. Split across the three attributable stages so an operator can tell\n// WHERE the latency lives: the model (TTFT + inter-delta gaps), our durable write\n// path (append latency), or delivery (publish latency + batcher flush shape). All\n// labels are bounded (provider from the model registry, a two-value delta class) —\n// never a session id or a raw user-supplied model string.\n\nexport type StreamDeltaClass = \"message\" | \"reasoning\";\n\n/** Content-delta classes only. A `null` return means \"not a content delta\" — the\n * event that re-arms the TTFT anchor and closes an inter-delta run. */\nfunction contentDeltaClass(type: SessionEventType): StreamDeltaClass | null {\n if (type === \"agent.message.delta\") {\n return \"message\";\n }\n if (type === \"agent.reasoning.delta\") {\n return \"reasoning\";\n }\n return null;\n}\n\n// TTFT and inter-delta live on a human-perceptible scale (tens of ms to a few\n// seconds), so they get their own SHORT buckets — the default duration buckets\n// (which run to 3600s) would collapse every real streaming value into one bucket.\nconst STREAM_TTFT_BUCKETS = [0.02, 0.05, 0.1, 0.2, 0.35, 0.5, 0.75, 1, 1.5, 2, 3, 5, 10];\nconst STREAM_INTER_DELTA_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.2, 0.35, 0.5, 1, 2, 5];\n\n/**\n * Per-turn stream-timing tracker fed every normalized runtime event in push order.\n * It emits two model-responsiveness SLIs from the worker's seat on the stream:\n *\n * - `opengeni_stream_ttft_seconds{provider}` — time from a model (re)start to its\n * first streamed content delta. The anchor starts at construction (≈ runStream\n * start, so the first observation is \"how long until text appears\") and re-arms\n * on every non-content event (a tool call, a completed message, a usage frame),\n * so a post-tool response measures the model's restart latency, NOT our own\n * tool-execution time.\n * - `opengeni_stream_inter_delta_gap_seconds{provider,class}` — gap between\n * consecutive content deltas of the SAME class. The run resets on any\n * non-content event so a gap never spans a tool call or a model boundary — it\n * measures only the choppiness of a live token stream.\n *\n * Purely observational and clock-injectable; it never touches the events it sees.\n */\nexport class StreamTimingMetrics {\n private readonly now: () => number;\n private ttftAnchor: number;\n private ttftArmed = true;\n private readonly lastDeltaAt = new Map<StreamDeltaClass, number>();\n\n constructor(\n private readonly observability: Observability,\n private readonly options: { provider: string; now?: () => number },\n ) {\n this.now = options.now ?? (() => performance.now());\n this.ttftAnchor = this.now();\n }\n\n onEvent(type: SessionEventType): void {\n const deltaClass = contentDeltaClass(type);\n if (deltaClass === null) {\n // A non-content event: the model paused emitting. Re-arm TTFT so the next\n // content delta measures (re)start latency, and close every inter-delta run\n // so no gap spans a tool call / model boundary.\n this.ttftAnchor = this.now();\n this.ttftArmed = true;\n this.lastDeltaAt.clear();\n return;\n }\n const at = this.now();\n if (this.ttftArmed) {\n this.observability.observeHistogram({\n name: \"opengeni_stream_ttft_seconds\",\n help: \"Seconds from a model (re)start to its first streamed content delta.\",\n buckets: STREAM_TTFT_BUCKETS,\n labels: { provider: this.options.provider },\n value: Math.max(0, (at - this.ttftAnchor) / 1000),\n });\n this.ttftArmed = false;\n }\n const last = this.lastDeltaAt.get(deltaClass);\n if (last !== undefined) {\n this.observability.observeHistogram({\n name: \"opengeni_stream_inter_delta_gap_seconds\",\n help: \"Seconds between consecutive streamed content deltas of the same class.\",\n buckets: STREAM_INTER_DELTA_BUCKETS,\n labels: { provider: this.options.provider, class: deltaClass },\n value: Math.max(0, (at - last) / 1000),\n });\n }\n this.lastDeltaAt.set(deltaClass, at);\n }\n}\n\n// Batch shapes: sizes are small integers; durations are the append+publish round\n// trip the flush performs (sub-ms to a couple seconds under contention).\nconst STREAM_BATCH_SIZE_BUCKETS = [1, 2, 5, 10, 20, 50, 100, 200, 500];\nconst STREAM_IO_BUCKETS = [0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5];\n\n/** Flush shape of the streaming batcher: how many events coalesced into one flush\n * (the coalescing win) and how long that flush took (append + publish). */\nexport function recordBatchFlush(\n observability: Observability,\n input: { events: number; durationSeconds: number },\n): void {\n observability.observeHistogram({\n name: \"opengeni_stream_batch_flush_events\",\n help: \"Session events coalesced into one streaming batcher flush.\",\n buckets: STREAM_BATCH_SIZE_BUCKETS,\n value: input.events,\n });\n observability.observeHistogram({\n name: \"opengeni_stream_batch_flush_duration_seconds\",\n help: \"Duration in seconds of one streaming batcher flush (append + publish).\",\n buckets: STREAM_IO_BUCKETS,\n value: input.durationSeconds,\n });\n}\n\n/** Latency of the durable `appendSessionEvents` DB write — the write path. A p99\n * climb here is our Postgres, not the model or NATS. */\nexport function recordSessionEventAppendLatency(\n observability: Observability,\n input: { durationSeconds: number },\n): void {\n observability.observeHistogram({\n name: \"opengeni_session_event_append_seconds\",\n help: \"Duration in seconds of an appendSessionEvents DB write (the durable write path).\",\n buckets: STREAM_IO_BUCKETS,\n value: input.durationSeconds,\n });\n}\n\n/** Latency of the best-effort NATS live fan-out — the delivery path. A p99 climb\n * here (with append healthy) is delivery, not the write path. */\nexport function recordSessionEventPublishLatency(\n observability: Observability,\n input: { durationSeconds: number },\n): void {\n observability.observeHistogram({\n name: \"opengeni_session_event_publish_seconds\",\n help: \"Duration in seconds of the best-effort NATS live fan-out publish (the delivery path).\",\n buckets: STREAM_IO_BUCKETS,\n value: input.durationSeconds,\n });\n}\n\n// Context tokens per response span a wide range; buckets track the pressure toward\n// a model's window so \"sessions are running hot but never compacting\" is queryable.\nconst MODEL_INPUT_TOKENS_BUCKETS = [\n 1_000, 5_000, 10_000, 25_000, 50_000, 100_000, 150_000, 200_000, 300_000, 500_000, 1_000_000,\n];\n\n/** Observed input (context) tokens per model response — the context-pressure\n * signal. Paired with `opengeni_context_compactions_total`, it makes the\n * \"compaction never firing while contexts run hot\" failure mode expressible. */\nexport function recordModelInputTokens(\n observability: Observability,\n provider: string,\n inputTokens: number,\n): void {\n const normalizedInputTokens = modelUsageTokenCountOrNull(inputTokens);\n if (normalizedInputTokens === null || normalizedInputTokens === 0) {\n return;\n }\n observability.observeHistogram({\n name: \"opengeni_model_input_tokens\",\n help: \"Observed input (context) tokens per model response, by provider.\",\n buckets: MODEL_INPUT_TOKENS_BUCKETS,\n labels: { provider },\n value: normalizedInputTokens,\n });\n}\n\n/** A context compaction actually fired, by trigger (operator | overflow | proactive\n * | auto). The rate of this — against the input-tokens histogram above — is how an\n * operator sees compaction working (or silently not). */\nexport function recordContextCompaction(observability: Observability, trigger: string): void {\n observability.incrementCounter({\n name: \"opengeni_context_compactions_total\",\n help: \"Total context compactions performed, by trigger.\",\n labels: { trigger },\n });\n}\n\n// ── Prompt-cache efficiency ─────────────────────────────────────────────────\n// Per model-call prompt-cache signal, provider-labelled only (bounded\n// cardinality — never a session id or account). `cached_tokens` is the slice of\n// the prompt the provider served from its prompt cache; the ratio cached/prompt\n// is the efficiency of that call. The account-switch hypothesis (a codex account\n// rotation cold-starts the provider's per-account prompt cache) is tested from\n// the per-call STRUCTURED LOG below — the account id is unbounded, so it is\n// hashed into a log field and NEVER a Prometheus label.\n\n// The hit ratio lives in [0, 1]; bucket tighter around the alerting threshold so\n// a p50 near 40% resolves. The default duration buckets (to 3600) would collapse\n// every ratio into the first bucket.\nconst MODEL_CACHE_HIT_RATIO_BUCKETS = [\n 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 1,\n];\n\n/**\n * Prompt-cache efficiency of one model response, by provider. Reads from the SAME\n * usage frame that feeds input-token accounting, so the two are always consistent:\n * - `opengeni_model_cached_tokens_total{provider}` — cumulative prompt tokens the\n * provider served from cache. Advanced only when >0, so a provider that never\n * reports cached tokens contributes nothing rather than phantom zero-increments.\n * - `opengeni_model_cache_write_tokens_total{provider}` — cumulative tokens a\n * reporting provider wrote into its prompt cache. Absent telemetry contributes\n * nothing; in particular, Codex subscription usage does not currently expose it.\n * - `opengeni_model_cache_hit_ratio{provider}` — cached/prompt for the call,\n * observed only when prompt tokens are known (>0) AND cached tokens are reported.\n * A reported cached-token zero records a real 0%; absent/null telemetry remains\n * unknown and must not fabricate a low-cache signal.\n * - `opengeni_model_cache_read_telemetry_total{provider,status}` — one bounded\n * availability observation per authoritative call (`reported` or `missing`).\n * Invalid, fractional, unsafe, or over-contract token telemetry is rejected. A call\n * with no prompt tokens has no ratio (skipped).\n */\nexport function recordModelCacheTokens(\n observability: Observability,\n provider: string,\n input: {\n cachedTokens: number | null | undefined;\n cacheWriteTokens?: number | null | undefined;\n promptTokens: number | null | undefined;\n },\n): void {\n const cached = modelUsageTokenCountOrNull(input.cachedTokens);\n const cacheWrite = modelUsageTokenCountOrNull(input.cacheWriteTokens);\n const prompt = modelUsageTokenCountOrNull(input.promptTokens);\n incrementBoundedModelCacheCounter(observability, {\n name: \"opengeni_model_cache_read_telemetry_total\",\n help: \"Authoritative model calls with reported or missing cache-read telemetry, by provider.\",\n provider,\n labels: { provider, status: cached === null ? \"missing\" : \"reported\" },\n amount: 1,\n });\n if (cached !== null && cached > 0) {\n incrementBoundedModelCacheCounter(observability, {\n name: \"opengeni_model_cached_tokens_total\",\n help: \"Total prompt tokens served from the provider's prompt cache, by provider.\",\n provider,\n labels: { provider },\n amount: cached,\n });\n }\n if (cacheWrite !== null && cacheWrite > 0) {\n incrementBoundedModelCacheCounter(observability, {\n name: \"opengeni_model_cache_write_tokens_total\",\n help: \"Total prompt tokens written to the provider's prompt cache, by provider.\",\n provider,\n labels: { provider },\n amount: cacheWrite,\n });\n }\n if (cached !== null && prompt !== null && prompt > 0) {\n observability.observeHistogram({\n name: \"opengeni_model_cache_hit_ratio\",\n help: \"Per-call prompt-cache hit ratio (cached/prompt tokens) by provider.\",\n buckets: MODEL_CACHE_HIT_RATIO_BUCKETS,\n labels: { provider },\n // Clamp to [0, 1]: a provider that (rarely) reports cached >= prompt must\n // not skew the histogram past 1.0.\n value: Math.min(1, cached / prompt),\n });\n }\n}\n\nfunction incrementBoundedModelCacheCounter(\n observability: Observability,\n input: {\n name: string;\n help: string;\n provider: string;\n labels: Record<string, string>;\n amount: number;\n },\n): void {\n const totals = modelCacheCounterTotals.get(observability) ?? new Map<string, number>();\n if (!modelCacheCounterTotals.has(observability)) {\n modelCacheCounterTotals.set(observability, totals);\n }\n const labelKey = Object.entries(input.labels)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, value]) => `${key}=${value}`)\n .join(\",\");\n const key = `${input.name}:${labelKey}`;\n const current = totals.get(key) ?? 0;\n if (input.amount > MAX_MODEL_CACHE_COUNTER_TOTAL - current) {\n observability.warn(\"model cache metric cumulative limit reached\", {\n provider: input.provider,\n metric: input.name,\n });\n return;\n }\n observability.incrementCounter({\n name: input.name,\n help: input.help,\n labels: input.labels,\n amount: input.amount,\n });\n totals.set(key, current + input.amount);\n}\n\n/**\n * An opaque, stable, non-reversible tag for a codex credential (account) — the\n * per-call log dimension the account-switch hypothesis correlates against. It is\n * a hash of the NON-SECRET credential ROW id (never a token/bearer), truncated so\n * it is short in logs while still distinguishing a handful of accounts without\n * collision. A null/absent credential (non-codex turn, no active account) tags as\n * \"none\" so the field is always present and never leaks an id verbatim.\n */\nexport function stableAccountHash(credentialId: string | null | undefined): string {\n if (!credentialId) {\n return \"none\";\n }\n return createHash(\"sha256\").update(credentialId).digest(\"hex\").slice(0, 12);\n}\n\n/**\n * The per-call account dimensions for the usage log: the opaque serving-account\n * tag and whether that account CHANGED versus the session's previous call. Within\n * one turn the serving credential is fixed, so a switch can only surface on the\n * turn's FIRST call (compared against the session's durably-recorded prior\n * credential); later calls in the same turn report `false`. A switch is reported\n * only when there was a KNOWN prior account that differs — a session's very first\n * call (no prior) is a cold start, not a switch.\n */\nexport function modelCallAccountContext(input: {\n servingCredentialId: string | null;\n priorSessionCredentialId: string | null;\n isFirstCallOfTurn: boolean;\n}): { servingAccountHash: string; accountChangedFromPrevCall: boolean } {\n const accountChangedFromPrevCall =\n input.isFirstCallOfTurn &&\n input.servingCredentialId !== null &&\n input.priorSessionCredentialId !== null &&\n input.priorSessionCredentialId !== input.servingCredentialId;\n return {\n servingAccountHash: stableAccountHash(input.servingCredentialId),\n accountChangedFromPrevCall,\n };\n}\n","// apps/worker/src/activities/recording.ts — the recording finalize helper (P4.3).\n//\n// The \"agent films itself proving the fix\" finalize loop, run IN the process that\n// already holds the resumed-by-id box (the agent turn's own activity). A scoped\n// upload URL sends bytes box → object storage; the worker never buffers the\n// recording and no bytes enter a Temporal payload.\n//\n// Ordering invariant (F9): the box file is deleted ONLY after the storage PUT\n// confirms and the `available` row commits — so a failed upload leaves the bytes\n// recoverable on the box.\n\nimport type { Settings } from \"@opengeni/config\";\nimport type { Database } from \"@opengeni/db\";\nimport { deleteRecording } from \"@opengeni/db\";\nimport type {\n RecordingCodec,\n RecordingFailedReason,\n RecordingStartedPayload,\n} from \"@opengeni/contracts\";\nimport {\n contentTypeForCodec,\n deleteRecordingArtifacts,\n RecordingError,\n recordingStorageKey,\n startRecording as startRecordingOnBox,\n stopRecording as stopRecordingOnBox,\n uploadRecordingArtifact,\n type RecordingProcess,\n} from \"@opengeni/runtime\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { DOWNLOAD_URL_TTL_SECONDS } from \"@opengeni/storage\";\n\nexport type RecordingMode = \"manual\" | \"on-turn\" | \"on-verify\";\n\nexport type ActiveRecording = {\n recordingId: string;\n turnId: string | null;\n mode: RecordingMode;\n proc: RecordingProcess;\n dimensions: [number, number];\n framerate: number;\n};\n\nexport const RECORDING_SETTLEMENT_PREP_TIMEOUT_MS = 100_000;\nconst RECORDING_SETTLEMENT_UPLOAD_MAX_SECONDS = 45;\n\nexport async function withRecordingPreparationTimeout(\n preparation: Promise<PreparedRecordingSettlement>,\n timeoutResult: PreparedRecordingSettlement,\n timeoutMs = RECORDING_SETTLEMENT_PREP_TIMEOUT_MS,\n): Promise<PreparedRecordingSettlement> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n preparation,\n new Promise<PreparedRecordingSettlement>((resolve) => {\n timer = setTimeout(() => resolve(timeoutResult), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/**\n * Insert the recording row, launch ffmpeg on the box, and return the live handle.\n * Emits the `recording.started` payload (the caller publishes it on the spine).\n */\nexport async function beginRecording(args: {\n settings: Settings;\n db: Database;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string | null;\n recordingId: string;\n mode: RecordingMode;\n session: unknown;\n runAs?: string | undefined;\n reason?: string | null;\n}): Promise<{ active: ActiveRecording; started: RecordingStartedPayload }> {\n const { settings, db } = args;\n const codec = settings.recordingDefaultCodec as RecordingCodec;\n const dimensions: [number, number] = [\n settings.streamResolutionWidth,\n settings.streamResolutionHeight,\n ];\n const framerate = settings.recordingFramerate;\n await import(\"@opengeni/db\").then(({ insertRecording }) =>\n insertRecording(db, {\n id: args.recordingId,\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n turnId: args.turnId,\n mode: args.mode,\n codec,\n width: dimensions[0],\n height: dimensions[1],\n reason: scrubFreeText(args.reason),\n }),\n );\n let proc: RecordingProcess;\n try {\n proc = await startRecordingOnBox(args.session, {\n recordingId: args.recordingId,\n codec,\n framerate,\n maxSeconds: settings.recordingMaxSeconds,\n dimensions,\n ...(args.runAs ? { runAs: args.runAs } : {}),\n });\n } catch (error) {\n await deleteRecording(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n recordingId: args.recordingId,\n }).catch(() => undefined);\n throw error;\n }\n const active: ActiveRecording = {\n recordingId: args.recordingId,\n turnId: args.turnId,\n mode: args.mode,\n proc,\n dimensions,\n framerate,\n };\n const started: RecordingStartedPayload = {\n recordingId: args.recordingId,\n turnId: args.turnId,\n mode: args.mode,\n codec,\n dimensions,\n framerate,\n startedAt: new Date().toISOString(),\n reason: scrubFreeText(args.reason),\n };\n return { active, started };\n}\n\nexport type PreparedRecordingSettlement =\n | {\n mutation: {\n action: \"available\";\n recordingId: string;\n storageKey: string;\n sizeBytes: number;\n durationSeconds: number;\n };\n deleteArtifactsAfterCommit: true;\n }\n | {\n mutation: {\n action: \"failed\";\n recordingId: string;\n reason: RecordingFailedReason;\n detail: string | null;\n };\n deleteArtifactsAfterCommit: false;\n }\n | {\n mutation: { action: \"discard\"; recordingId: string };\n deleteArtifactsAfterCommit: true;\n };\n\n/**\n * Prepare an on-turn recording for the attempt-closing settlement. This performs\n * only bounded box/storage work; it does not mutate canonical database state and\n * never deletes the box artifact. The caller folds the returned mutation into the\n * exact attempt-fenced turn settlement, then deletes artifacts only after commit.\n * NEVER throws and never prevents turn truth from settling.\n */\nexport async function prepareRecordingForSettlement(args: {\n settings: Settings;\n objectStorage: ObjectStorage | null;\n workspaceId: string;\n sessionId: string;\n active: ActiveRecording;\n session: unknown;\n didComputerUse: boolean;\n}): Promise<PreparedRecordingSettlement> {\n const { settings, objectStorage, active } = args;\n const codec = active.proc.codec;\n const fail = (\n reason: RecordingFailedReason,\n detail: string | null,\n ): PreparedRecordingSettlement => {\n return {\n mutation: {\n action: \"failed\",\n recordingId: active.recordingId,\n reason,\n detail: scrubFreeText(detail),\n },\n deleteArtifactsAfterCommit: false,\n };\n };\n\n const prepare = async (): Promise<PreparedRecordingSettlement> => {\n try {\n await stopRecordingOnBox(args.session, active.proc);\n if (!args.didComputerUse) {\n return {\n mutation: { action: \"discard\", recordingId: active.recordingId },\n deleteArtifactsAfterCommit: true,\n };\n }\n if (!objectStorage) {\n return fail(\"upload-failed\", \"object storage is not configured\");\n }\n const key = recordingStorageKey(args.workspaceId, args.sessionId, active.recordingId, codec);\n const upload = await objectStorage.createPutUrl({\n key,\n contentType: contentTypeForCodec(codec),\n });\n const finalized = await uploadRecordingArtifact(args.session, active.proc, {\n url: upload.url,\n requiredHeaders: upload.requiredHeaders,\n maxBytes: settings.recordingMaxBytes,\n maxSeconds: RECORDING_SETTLEMENT_UPLOAD_MAX_SECONDS,\n });\n return {\n mutation: {\n action: \"available\",\n recordingId: active.recordingId,\n storageKey: key,\n sizeBytes: finalized.sizeBytes,\n durationSeconds: finalized.durationSeconds,\n },\n deleteArtifactsAfterCommit: true,\n };\n } catch (error) {\n const reason: RecordingFailedReason =\n error instanceof RecordingError ? error.reason : \"upload-failed\";\n return fail(reason, error instanceof Error ? error.message : String(error));\n }\n };\n\n return await withRecordingPreparationTimeout(\n prepare(),\n fail(\"upload-failed\", \"recording settlement preparation timed out\"),\n );\n}\n\n/**\n * Compensate a start whose fenced `recording.started` event was rejected. Since\n * no canonical event was admitted, this exact recording id must leave no row,\n * process, or box artifact behind.\n */\nexport async function discardUnpublishedRecording(args: {\n db: Database;\n accountId: string;\n workspaceId: string;\n active: ActiveRecording;\n session: unknown;\n}): Promise<void> {\n const { db, active } = args;\n try {\n await stopRecordingOnBox(args.session, active.proc).catch(() => undefined);\n await deleteRecordingArtifacts(args.session, active.proc).catch(() => undefined);\n } finally {\n await deleteRecording(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n recordingId: active.recordingId,\n }).catch(() => undefined);\n }\n}\n\nexport { DOWNLOAD_URL_TTL_SECONDS };\n\n// Agent/ffmpeg-controlled free text rides redact() like every payload, but we\n// also cap it here (defense in depth — a path/URL with creds shouldn't ride a\n// reason/detail field unbounded; the redactor scrubs known secret shapes).\nfunction scrubFreeText(value: string | null | undefined): string | null {\n if (value === null || value === undefined) return null;\n const trimmed = String(value).slice(0, 2_000);\n return trimmed.length === 0 ? null : trimmed;\n}\n","// Workbench v2 — turn-end workspace capture.\n//\n// The universal spine that makes the session workspace paint instantly on cold /\n// offline reads: at TURN END, while the box is still guaranteed live and the\n// turn's lease pins the refcount (the reaper cannot drain), we probe the box's\n// CHANGED files directly off the un-proxied Channel-A session — per-repo git\n// status + diff, after-images of the touched files, and a pruned tree index —\n// serialize a manifest, PUT it + the after-image blobs to object storage, and\n// insert an epoch-fenced `workspace_captures` row. The read path (M2/M3) serves\n// this when the machine is cold/offline; a warm box always wins (capture is a\n// labelled cache, never a replacement).\n//\n// SAFETY INVARIANTS (non-negotiable — see):\n// • This module NEVER calls close()/terminate()/kill() on the session handle.\n// session.close() == terminate() on Modal and would kill the user's box.\n// Only the reaper terminates. We drop references, nothing more.\n// • The whole capture is time-capped (120s) and best-effort: ANY failure logs\n// \"workspace capture failed — turn outcome unaffected\" and returns; nothing\n// throws past captureWorkspaceRevision.\n// • The DB write is fenced on the exact attempt, accepted control requests,\n// and lease epoch — a cancelled attempt or superseded lease writes zero rows\n// (insertWorkspaceCapture).\n// • F9 storage ordering: blobs + manifest are PUT and the row is committed\n// BEFORE any GC delete runs.\n//\n// It is deliberately an EXTERNAL module with a SINGLE call-site line in\n// agent-turn.ts's finally (the accepted design tradeoff — do not grow the turn\n// activity). The emitted `workspace.revision.captured` event is ANNOUNCE-ONLY\n// (metadata, never content) and must never gain a rendered timeline item.\n\nimport { createHash } from \"node:crypto\";\nimport type { Settings } from \"@opengeni/config\";\nimport type { Database } from \"@opengeni/db\";\nimport {\n deleteWorkspaceCaptureRows,\n insertFailedWorkspaceCapture,\n insertWorkspaceCapture,\n latestWorkspaceCapture,\n planWorkspaceCaptureGc,\n} from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport type { Observability } from \"@opengeni/observability\";\n// The un-agent-loop leaf. Constructing the Channel-A service over the un-proxied\n// setupBoxSession here (NOT the routing veneer) guarantees a mid-turn\n// sandbox_swap can never re-route capture execs onto a user's machine — the same\n// reason the snapshot uses setupBoxSession.\nimport {\n SandboxChannelAService,\n type ChannelASession,\n type RepositoryDiscoveryDegradedReason,\n} from \"@opengeni/runtime/sandbox\";\nimport type {\n FsTreeNode,\n GitFileStatus,\n GitFileStatusCode,\n SessionEvent,\n WorkspaceCaptureFile,\n WorkspaceCaptureDegradedReason,\n WorkspaceCaptureManifest,\n WorkspaceCaptureRepo,\n WorkspaceCaptureStats,\n} from \"@opengeni/contracts\";\n\n// ─── Guards & constants for pathological cases; configurable ─────\n// Production Modal captures of the acceptance workspace normally take ~30s:\n// repository diff framing deliberately trades provider round-trips for bounded\n// output and symlink-safe reads. Sixty seconds gave that healthy path only a 2x\n// margin and repeatedly timed it out under ordinary provider variance. The turn\n// holder keeps the exact lease pinned for this whole window.\nexport const CAPTURE_TIMEOUT_MS = 120_000;\nexport const PER_FILE_CONTENT_GUARD_BYTES = 5 * 1024 * 1024; // after-image; over → tooLarge marker\nexport const PER_FILE_DIFF_GUARD_BYTES = 10 * 1024 * 1024; // per-file diff; over → truncated marker\nexport const WHOLE_CAPTURE_GUARD_BYTES = 200 * 1024 * 1024; // total → skip, fall back to live\nexport const KEEP_LATEST_REVISIONS = 10;\n// Directories listed as collapsed nodes in the tree index but NEVER descended\n// (their contents live on the machine — the Files tab wakes to expand them).\n//\n// Two classes:\n// • BUILD/DEP residue — huge, machine-resident, never review content.\n// • DESKTOP/SYSTEM residue (the Modal desktop-box fix): on a desktop image the\n// workspace root IS $HOME, and XFCE/dbus/etc. CONTINUOUSLY rewrite dotfiles\n// under ~/.config/xfce4, ~/.cache, ~/.dbus, … A tree walk that descends into\n// them (a) wastes the round-trip budget on churn no user is reviewing and\n// (b) races files that VANISH mid-walk. These are never workspace content, so\n// collapse them at the source. Legit hidden entries a user DOES author\n// (.gitignore, .env, .github, .vscode, .devcontainer) are deliberately NOT\n// here — they stay fully visible.\nexport const RESIDUE_DIRS: readonly string[] = [\n // build/dep residue\n \"node_modules\",\n \".git\",\n // Platform credential/helper state. The workspace root can be $HOME, so this\n // directory may sit inside a root repository; it must never enter a revision.\n \".opengeni\",\n \"dist\",\n \"build\",\n \"target\",\n \".venv\",\n \"__pycache__\",\n \".next\",\n // desktop/system residue (never workspace content; churned by the desktop stack)\n \".config\",\n \".cache\",\n \".local\",\n \".dbus\",\n \".gnupg\",\n \".ssh\",\n \".mozilla\",\n \".xfce4\",\n \".pki\",\n \".gvfs\",\n \".dbus-keyrings\",\n \".Xauthority\",\n \".ICEauthority\",\n];\nconst RESIDUE_DIR_SET: ReadonlySet<string> = new Set(RESIDUE_DIRS);\n\n/**\n * True when a workspace-relative FILE path lives INSIDE a residue dir — i.e. a\n * residue dir is one of its ANCESTOR segments (not the leaf), so the file is\n * churn/machine content never worth an after-image. `.config/xfce4/xfconf/…` and\n * `.config/mimeapps.list` → true; a root FILE literally named `.config` (a user\n * config the seed edits) → false (single segment, no residue ancestor); and\n * `.github/x.yml`, `.gitignore` → false (`.github`/`.gitignore` are not residue).\n * Matches the tree-BFS collapse (which collapses residue DIR nodes) so the\n * Changes tab and the tree agree on what is workspace content.\n */\nexport function isUnderResidueDir(wsPath: string): boolean {\n const segments = wsPath.split(\"/\");\n // Check ancestors only (every segment except the leaf): the leaf is the file\n // itself; a residue-named file at the root is still legitimate content.\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i];\n if (seg && RESIDUE_DIR_SET.has(seg)) return true;\n }\n return false;\n}\n\n/**\n * The box is being torn down under us (Modal reclaim / reaper drain / terminate)\n * — NOT a single file vanishing. Every subsequent op will fail too, so the\n * capture must ABORT (throw) rather than skip-and-continue, so it never commits a\n * bogus empty/partial revision for a dead box. Matched loosely so a provider\n * wording tweak still classifies. (The real fix for this is keeping the box\n * pinned through the capture window — sandbox-resume / agent-turn lease\n * heartbeat; this classifier only guarantees we fail HONESTLY if it still races.)\n */\nexport function isBoxExitingError(error: unknown): boolean {\n const msg = (error instanceof Error ? error.message : String(error ?? \"\")).toLowerCase();\n return (\n msg.includes(\"container exiting\") ||\n msg.includes(\"container is exiting\") ||\n msg.includes(\"container exited\") ||\n msg.includes(\"sandbox has been terminated\") ||\n msg.includes(\"sandbox is not running\") ||\n msg.includes(\"sandbox has terminated\") ||\n msg.includes(\"task has exited\")\n );\n}\n\n/** Marker thrown when the box died mid-capture — aborts cleanly (no partial row). */\nexport class BoxExitingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BoxExitingError\";\n }\n}\n\n/** Re-throw as a BoxExitingError when the box is gone; otherwise return null so\n * the caller SKIPS this single entry (a vanished/unreadable file) and continues.\n * One churning file must never kill the capture; a dead box must never yield a\n * bogus revision. */\nfunction classifyCaptureEntryError(error: unknown): BoxExitingError | null {\n if (isBoxExitingError(error)) {\n return new BoxExitingError(error instanceof Error ? error.message : String(error));\n }\n return null;\n}\nconst TREE_MAX_ENTRIES = 20_000; // whole-tree node cap (truncate beyond)\nconst TREE_MAX_DEPTH = 600; // pathological nesting cap; still one remote round-trip\n\n// The capture row and announcement are committed together by @opengeni/db. This\n// callback performs only best-effort live fanout of those already-durable events.\nexport type CaptureEventPublisher = (events: SessionEvent[]) => Promise<void>;\n\nexport type CaptureWorkspaceRevisionInput = {\n db: Database;\n objectStorage: ObjectStorage | null;\n settings: Settings;\n publish: CaptureEventPublisher | null;\n /** The un-proxied setupBoxSession (NOT the routing veneer). */\n session: ChannelASession;\n /**\n * Reopen the exact live provider instance as a fresh, non-owning read handle.\n * Modal sessions keep mutable exec-process bookkeeping; reusing the handle\n * that just drove model tools can strand a later capture command behind stale\n * provider state. The lease still owns the box. Capture drops this handle\n * without calling close(), which would terminate Modal's sandbox.\n */\n openReadSession?: () => Promise<ChannelASession>;\n leaseEpoch: number;\n sandboxGroupId: string;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n observability: Observability;\n /**\n * The owning turn activity's cancellation signal. Pause/Steer must preempt\n * review-cache housekeeping immediately; correctness still comes from the\n * activity plus the capture's transaction-level attempt/control/lease fences.\n */\n signal?: AbortSignal;\n /** Test-only: override keep-latest-N GC threshold (default 10). */\n keepLatest?: number;\n};\n\ntype CaptureRepositoryReadResult =\n | {\n complete: true;\n status: Awaited<ReturnType<SandboxChannelAService[\"gitStatus\"]>>;\n diff: Awaited<ReturnType<SandboxChannelAService[\"gitDiff\"]>>;\n }\n | { complete: false; degradedReason: \"repository_read_unavailable\" };\n\ntype ResumableCaptureClient = {\n resume?: (state: unknown) => Promise<unknown>;\n};\n\ntype StatefulCaptureSession = ChannelASession & {\n state?: unknown;\n};\n\nfunction captureSessionInstanceId(session: unknown): string | null {\n const state =\n session && typeof session === \"object\"\n ? (session as { state?: Record<string, unknown> }).state\n : undefined;\n if (!state || typeof state !== \"object\") return null;\n for (const value of [\n state.sandboxId,\n state.instanceId,\n state.id,\n state.hostId,\n state.containerId,\n state.workspaceRootPath,\n ]) {\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return null;\n}\n\n/**\n * Reattach a clean SDK handle to the exact already-live Modal sandbox. Modal's\n * resume contract is a pure from-id reattach. Other providers keep the original\n * session because their generic resume contract may restore or replace a dead\n * instance, which capture does not own.\n */\nexport async function openFreshWorkspaceCaptureSession(input: {\n backendId: string;\n client: unknown;\n session: ChannelASession;\n expectedInstanceId: string;\n}): Promise<ChannelASession> {\n if (input.backendId !== \"modal\") {\n return input.session;\n }\n const client = input.client as ResumableCaptureClient;\n const state = (input.session as StatefulCaptureSession).state;\n if (typeof client.resume !== \"function\" || state === undefined) {\n return input.session;\n }\n // The lease—not this temporary reader—owns provider teardown. Preserve the\n // exact state while explicitly removing close/terminate authority from\n // providers (Modal) that encode it in the resumed state.\n const readState =\n state !== null && typeof state === \"object\" ? { ...state, ownsSandbox: false } : state;\n const reopened = await client.resume(readState);\n const actualInstanceId = captureSessionInstanceId(reopened);\n if (input.expectedInstanceId.length > 0 && actualInstanceId !== input.expectedInstanceId) {\n throw new Error(\n `workspace capture reopened provider instance ${actualInstanceId ?? \"unknown\"}, expected ${input.expectedInstanceId}`,\n );\n }\n return reopened as ChannelASession;\n}\n\n/** One discovered repository is all-or-nothing capture authority. A provider\n * transport failure must never be represented as an authoritative empty diff. */\nexport async function readCaptureRepository(\n svc: Pick<SandboxChannelAService, \"gitStatus\" | \"gitDiff\">,\n root: string,\n): Promise<CaptureRepositoryReadResult> {\n let status: Awaited<ReturnType<SandboxChannelAService[\"gitStatus\"]>>;\n try {\n status = await svc.gitStatus({ path: root });\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n return { complete: false, degradedReason: \"repository_read_unavailable\" };\n }\n if (!status.isRepo) {\n return { complete: false, degradedReason: \"repository_read_unavailable\" };\n }\n try {\n const diff = await svc.gitDiff({\n path: root,\n staged: false,\n includeUntracked: true,\n fromRef: \"HEAD\",\n pathspec: [],\n contextLines: 3,\n maxBytesPerFile: PER_FILE_DIFF_GUARD_BYTES,\n });\n return { complete: true, status, diff };\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n return { complete: false, degradedReason: \"repository_read_unavailable\" };\n }\n}\n\nlet loggedStorageNullOnce = false;\n\n/**\n * Turn-end entrypoint. Gates on the flag + configured object storage, races the\n * whole capture against a 120s cap, and swallows every failure (\"turn outcome\n * unaffected\"). Returns void — the caller awaits it (it self-caps) and moves on\n * to release() regardless.\n */\nexport async function captureWorkspaceRevision(\n input: CaptureWorkspaceRevisionInput,\n): Promise<void> {\n const { observability } = input;\n const stage = { value: \"preflight\" };\n if (input.signal?.aborted) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"cancelled\" },\n });\n return;\n }\n if (!input.settings.workspaceCaptureEnabled) {\n return; // flag off → capture skipped; reads fall back to live/wake (status quo)\n }\n if (!input.objectStorage) {\n if (!loggedStorageNullOnce) {\n loggedStorageNullOnce = true;\n observability.info(\"workspace capture skipped — object storage not configured\");\n }\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"skipped_no_storage\" },\n });\n return;\n }\n\n const startedAt = Date.now();\n const controller = new AbortController();\n let rejectOwnerCancellation: ((reason?: unknown) => void) | undefined;\n const ownerCancelled = input.signal\n ? new Promise<never>((_resolve, reject) => {\n rejectOwnerCancellation = reject;\n })\n : new Promise<never>(() => undefined);\n const cancelFromOwner = (): void => {\n controller.abort(input.signal?.reason);\n rejectOwnerCancellation?.(\n input.signal?.reason ?? new Error(\"workspace capture cancelled by its owning activity\"),\n );\n };\n input.signal?.addEventListener(\"abort\", cancelFromOwner, { once: true });\n if (input.signal?.aborted) cancelFromOwner();\n observability.incrementGauge({\n name: \"opengeni_workspace_captures_inflight\",\n help: \"Current workspace-capture operations still resident in this worker process.\",\n });\n const capture = runCapture(\n input,\n { ...input, objectStorage: input.objectStorage },\n startedAt,\n controller.signal,\n stage,\n ).finally(() => {\n observability.incrementGauge({\n name: \"opengeni_workspace_captures_inflight\",\n help: \"Current workspace-capture operations still resident in this worker process.\",\n amount: -1,\n });\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n capture,\n ownerCancelled,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new Error(`workspace capture exceeded ${CAPTURE_TIMEOUT_MS}ms`));\n }, CAPTURE_TIMEOUT_MS);\n }),\n ]);\n } catch (error) {\n if (input.signal?.aborted) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"cancelled\" },\n });\n return;\n }\n // The one and only place a capture failure surfaces — as a log line, never\n // an exception past this boundary (the turn already completed).\n observability.warn(\"workspace capture failed — turn outcome unaffected\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": input.turnId ?? \"\",\n \"error.message\": error instanceof Error ? error.message : String(error),\n \"workspace_capture.duration_ms\": Date.now() - startedAt,\n \"workspace_capture.stage\": stage.value,\n });\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"failed\" },\n });\n } finally {\n if (timer) clearTimeout(timer);\n input.signal?.removeEventListener(\"abort\", cancelFromOwner);\n controller.abort();\n }\n}\n\n// The strongly-typed inner run (objectStorage proven non-null by the caller).\nasync function runCapture(\n input: CaptureWorkspaceRevisionInput,\n ctx: CaptureWorkspaceRevisionInput & { objectStorage: ObjectStorage },\n startedAt: number,\n signal: AbortSignal,\n stage: { value: string },\n): Promise<void> {\n const { observability } = input;\n const storage = ctx.objectStorage;\n const keepN = input.keepLatest ?? KEEP_LATEST_REVISIONS;\n stage.value = \"open_read_session\";\n const readSession = input.openReadSession ? await input.openReadSession() : input.session;\n throwIfCaptureAborted(signal);\n // Reads only — no emitter (we publish the announce ourselves after commit).\n const svc = new SandboxChannelAService({ session: readSession, leaseEpoch: input.leaseEpoch });\n\n // Resolve the previous revision before discovery so even a failed discovery\n // can commit a monotonic, explicit degraded marker. That marker becomes the\n // newest read result and prevents an older successful capture from being\n // mistaken for the current turn's authoritative workspace state.\n stage.value = \"load_previous_capture\";\n const prev = await latestWorkspaceCapture(input.db, input.workspaceId, input.sessionId);\n throwIfCaptureAborted(signal);\n const revision = (prev?.revision ?? -1) + 1;\n\n // ── 1. per-repo status + diff, union the touched set ──────────────────────\n stage.value = \"repository_discovery\";\n const discovery = await svc.detectReposDetailed();\n throwIfCaptureAborted(signal);\n if (process.env.OPENGENI_TEST_SCENARIO === \"sandbox\") {\n console.log(\n `[sandbox-e2e] capture discovery complete=${discovery.complete} repos=${JSON.stringify(discovery.repos)} degraded=${discovery.degradedReason ?? \"none\"}`,\n );\n }\n if (!discovery.complete) {\n const reason = captureDegradedReason(discovery.degradedReason);\n await persistDegradedCapture(\n input,\n startedAt,\n signal,\n revision,\n reason,\n discovery.repos.length,\n );\n return;\n }\n const repoRoots = discovery.repos;\n const repos: WorkspaceCaptureRepo[] = [];\n // workspace-relative path → touched-file descriptor\n const touched = new Map<string, { status: GitFileStatusCode; deleted: boolean }>();\n let additions = 0;\n let deletions = 0;\n\n for (const root of repoRoots) {\n stage.value = \"repository_read\";\n throwIfCaptureAborted(signal);\n // Repository discovery defines the authoritative set. Once a root is in\n // that set, status/diff failure must degrade the entire revision rather than\n // publish a partial or false-empty change surface. Box death still aborts\n // through the outer best-effort boundary.\n const repository = await readCaptureRepository(svc, root);\n throwIfCaptureAborted(signal);\n if (!repository.complete) {\n await persistDegradedCapture(\n input,\n startedAt,\n signal,\n revision,\n repository.degradedReason,\n repoRoots.length,\n );\n return;\n }\n const { status, diff } = repository;\n // Drop residue churn from the review diff too. On a desktop box the seed's\n // `git add -A` in $HOME commits ~/.config/xfce4/* into HEAD, so `git diff HEAD`\n // lists the continuously-rewritten desktop dotfiles as changed — noise the\n // Changes tab must not show. The status/after-image loop already excludes them\n // (isUnderResidueDir); exclude them here so the diff surface agrees.\n const diffFiles = diff.files.filter((f) => !isUnderResidueDir(joinRepoPath(root, f.path)));\n // Also drop residue-only status entries below; status.files is filtered in the\n // touched loop (isUnderResidueDir), so `status: status.files` would still carry\n // residue rows — filter for a consistent captured status surface.\n const statusFiles = status.files.filter((f) => !isUnderResidueDir(joinRepoPath(root, f.path)));\n repos.push({\n root,\n head: status.head,\n detached: status.detached,\n upstream: status.upstream,\n ahead: status.ahead,\n behind: status.behind,\n status: statusFiles,\n diff: diffFiles,\n });\n for (const f of diffFiles) {\n additions += f.additions;\n deletions += f.deletions;\n }\n for (const f of status.files) {\n const wsPath = joinRepoPath(root, f.path);\n // Skip desktop/system residue churn (~/.config/xfce4/…): on a desktop box\n // the workspace root is $HOME, so git reports the continuously-rewritten\n // XFCE/cache dotfiles as untracked. They are never review content — dropping\n // them here keeps the after-image loop off churn AND matches the tree BFS's\n // residue collapse (Changes tab and tree agree on what is workspace content).\n if (isUnderResidueDir(wsPath)) continue;\n touched.set(wsPath, {\n status: statusCodeOf(f),\n deleted: f.worktree === \"deleted\" || f.index === \"deleted\",\n });\n }\n }\n\n // Previous revision (for the empty-turn gate + revision assignment). The gate\n // itself fires AFTER the after-image loop, once the change fingerprint is known\n // (§10.1 / B3): uncommitted changes persist in the box across turns, so a\n // literal \"skip when git status is clean\" gate would re-capture an identical\n // dirty tree on every read-only turn. Instead we skip when the change surface\n // is byte-identical to the previous revision — \"no new revision when nothing\n // changed\" holds even with a persistently dirty tree, and content-addressed\n // blobs already dedupe storage. This preserves the intended empty-turn behavior\n // while correctly handling a persistently dirty tree.\n // ── 3. after-images of touched files (size-gated), content-addressed ───────\n const files: WorkspaceCaptureFile[] = [];\n const blobKeys = new Set<string>();\n let totalBytes = 0;\n let tooLargeCount = 0;\n let binaryCount = 0;\n\n for (const [wsPath, info] of touched) {\n stage.value = \"file_read\";\n throwIfCaptureAborted(signal);\n if (info.deleted) {\n files.push({\n path: wsPath,\n status: \"deleted\",\n hash: null,\n baseHash: null,\n contentRef: null,\n sizeBytes: 0,\n isBinary: false,\n tooLarge: false,\n deleted: true,\n });\n continue;\n }\n // Always request base64 so we get raw bytes uniformly (text or binary) for\n // content-addressing. maxBytes caps the read at the 5MB guard; `truncated`\n // means the file is ≥5MB → we record a tooLarge marker (no content blob).\n //\n // Per-file resilience: a file the box reported as changed can VANISH or turn\n // unreadable between git-status and this read (fs churn, a follow-up mutation,\n // a race). That must NEVER abort the whole capture — skip the one entry and\n // keep the rest. A box-death error is different: it aborts (BoxExitingError),\n // because every remaining read would fail too and we must not commit a partial\n // revision for a dead box.\n let read: Awaited<ReturnType<typeof svc.fsRead>>;\n try {\n read = await svc.fsRead({\n path: wsPath,\n encoding: \"base64\",\n maxBytes: PER_FILE_CONTENT_GUARD_BYTES,\n });\n throwIfCaptureAborted(signal);\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n continue; // vanished/unreadable single file — omit it, capture continues\n }\n if (read.truncated) {\n tooLargeCount += 1;\n files.push({\n path: wsPath,\n status: info.status,\n hash: null,\n baseHash: null,\n contentRef: null,\n sizeBytes: read.sizeBytes,\n isBinary: read.isBinary,\n tooLarge: true,\n deleted: false,\n });\n continue;\n }\n const bytes = Buffer.from(read.content, \"base64\");\n const hash = sha256(bytes);\n const contentRef = blobKey(input.workspaceId, input.sessionId, hash);\n if (read.isBinary) binaryCount += 1;\n if (!blobKeys.has(contentRef)) {\n totalBytes += bytes.byteLength;\n // Whole-capture guard: bail before writing anything (fall back to live).\n if (totalBytes > WHOLE_CAPTURE_GUARD_BYTES) {\n observability.warn(\"workspace capture skipped — whole-capture guard tripped\", {\n \"opengeni.session_id\": input.sessionId,\n \"workspace_capture.total_bytes\": totalBytes,\n });\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"guard_tripped\" },\n });\n return;\n }\n }\n blobKeys.add(contentRef);\n files.push({\n // baseHash (git HEAD blob sha) is intentionally null in M1: the wake-on-edit\n // flush guard (M3/C2) compares live content against the after-image `hash`,\n // not the HEAD blob, so baseHash is not load-bearing yet. Populating it would\n // cost an extra per-file round-trip at turn end (latency risk #1). Deferred.\n path: wsPath,\n status: info.status,\n hash,\n baseHash: null,\n contentRef,\n sizeBytes: bytes.byteLength,\n isBinary: read.isBinary,\n tooLarge: false,\n deleted: false,\n });\n }\n\n // ── 4. empty-turn gate (B3) ───────────────────────────────\n // Skip when the change surface is byte-identical to the previous revision.\n // Fires BEFORE the tree BFS + storage PUTs (the expensive parts) so a no-op\n // read-only turn on a persistently dirty tree costs only the (small) status/\n // diff/after-image probes.\n let fingerprint = changeFingerprint(repos, files);\n if (prev && prev.stats.fingerprint === fingerprint) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"skipped_empty\" },\n });\n return;\n }\n\n // ── 5. tree index (one bounded listing; residue dirs pruned at source) ─────\n stage.value = \"tree_index\";\n const tree = await buildTreeIndex(svc, startedAt, signal);\n throwIfCaptureAborted(signal);\n\n // ── 6. PUT blobs + tree + manifest (F9: all writes BEFORE any delete) ──────\n // Key manifest/tree by the turn (one capture per turn) so the key is known\n // before the revision is committed; content blobs are content-addressed.\n const turnKey = input.turnId;\n const treeKey = `workspace-captures/${input.workspaceId}/${input.sessionId}/trees/${turnKey}.json`;\n const manifestKey = `workspace-captures/${input.workspaceId}/${input.sessionId}/manifests/${turnKey}.json`;\n\n // Re-read and upload ONE after-image at a time. The first pass above computes\n // the stable capture fingerprint without retaining every changed file. This\n // second pass takes the actual after-image that will be uploaded, refreshing\n // metadata when a live process changed a file between passes. Peak worker\n // memory is bounded by PER_FILE_CONTENT_GUARD_BYTES instead of\n // WHOLE_CAPTURE_GUARD_BYTES per concurrent turn.\n const uploadedKeys = new Set<string>();\n blobKeys.clear();\n totalBytes = 0;\n let refreshedFiles = 0;\n const omittedFiles = new Set<string>();\n for (const file of files) {\n stage.value = \"content_upload\";\n throwIfCaptureAborted(signal);\n if (file.deleted || file.tooLarge || !file.contentRef || !file.hash) {\n continue;\n }\n let reread: Awaited<ReturnType<typeof svc.fsRead>>;\n try {\n reread = await svc.fsRead({\n path: file.path,\n encoding: \"base64\",\n maxBytes: PER_FILE_CONTENT_GUARD_BYTES,\n });\n throwIfCaptureAborted(signal);\n } catch (error) {\n if (signal.aborted) throw error;\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n // Match the first pass: a single vanished or unreadable file is omitted,\n // never misreported as deleted and never allowed to fail the full capture.\n omittedFiles.add(file.path);\n refreshedFiles += 1;\n continue;\n }\n if (reread.truncated) {\n file.hash = null;\n file.contentRef = null;\n file.sizeBytes = reread.sizeBytes;\n file.isBinary = reread.isBinary;\n file.tooLarge = true;\n refreshedFiles += 1;\n continue;\n }\n const bytes = Buffer.from(reread.content, \"base64\");\n const hash = sha256(bytes);\n const contentRef = blobKey(input.workspaceId, input.sessionId, hash);\n if (\n hash !== file.hash ||\n bytes.byteLength !== file.sizeBytes ||\n reread.isBinary !== file.isBinary\n ) {\n file.hash = hash;\n file.contentRef = contentRef;\n file.sizeBytes = bytes.byteLength;\n file.isBinary = reread.isBinary;\n refreshedFiles += 1;\n }\n if (!blobKeys.has(contentRef)) {\n totalBytes += bytes.byteLength;\n if (totalBytes > WHOLE_CAPTURE_GUARD_BYTES) {\n observability.warn(\"workspace capture skipped — whole-capture guard tripped\", {\n \"opengeni.session_id\": input.sessionId,\n \"workspace_capture.total_bytes\": totalBytes,\n });\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"guard_tripped\" },\n });\n return;\n }\n }\n blobKeys.add(contentRef);\n if (!uploadedKeys.has(contentRef)) {\n await storage.putObject({\n key: contentRef,\n contentType: \"application/octet-stream\",\n body: bytes,\n });\n throwIfCaptureAborted(signal);\n uploadedKeys.add(contentRef);\n }\n }\n if (omittedFiles.size > 0) {\n for (let index = files.length - 1; index >= 0; index -= 1) {\n const file = files[index];\n if (file && omittedFiles.has(file.path)) files.splice(index, 1);\n }\n }\n if (refreshedFiles > 0) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_files_refreshed_total\",\n amount: refreshedFiles,\n });\n }\n tooLargeCount = files.filter((file) => file.tooLarge).length;\n binaryCount = files.filter((file) => !file.deleted && file.isBinary).length;\n fingerprint = changeFingerprint(repos, files);\n if (prev && prev.stats.fingerprint === fingerprint) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"skipped_empty\" },\n });\n return;\n }\n\n // ── 7. serialize the exact uploaded after-images ──────────────────────────\n const capturedAt = new Date();\n const stats: WorkspaceCaptureStats = {\n repoCount: repos.length,\n fileCount: files.length,\n additions,\n deletions,\n totalBytes,\n tooLargeCount,\n binaryCount,\n treeEntryCount: tree.entryCount,\n treeTruncated: tree.truncated,\n durationMs: 0, // filled after tree/content writes, before manifest serialization\n fingerprint,\n };\n const manifest: WorkspaceCaptureManifest = {\n version: 1,\n revision,\n capturedAt: capturedAt.toISOString(),\n turnId: input.turnId,\n leaseEpoch: input.leaseEpoch,\n treeIndex: tree.root,\n treeTruncated: tree.truncated,\n repos,\n files,\n stats,\n };\n const treeBytes = utf8(\n JSON.stringify({\n version: 1,\n root: tree.root,\n truncated: tree.truncated,\n entryCount: tree.entryCount,\n }),\n );\n stage.value = \"tree_upload\";\n await storage.putObject({ key: treeKey, contentType: \"application/json\", body: treeBytes });\n throwIfCaptureAborted(signal);\n stats.durationMs = Date.now() - startedAt;\n const manifestBytes = utf8(JSON.stringify(manifest));\n stage.value = \"manifest_upload\";\n await storage.putObject({\n key: manifestKey,\n contentType: \"application/json\",\n body: manifestBytes,\n });\n throwIfCaptureAborted(signal);\n const sizeBytes = totalBytes + treeBytes.byteLength + manifestBytes.byteLength;\n\n // ── 8. epoch-fenced insert (superseded lease → zero rows) ─────────────────\n stage.value = \"database_commit\";\n const inserted = await insertWorkspaceCapture(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: input.leaseEpoch,\n revision,\n manifestKey,\n treeIndexKey: treeKey,\n blobKeys: [...blobKeys],\n sizeBytes,\n stats,\n capturedAt,\n });\n if (process.env.OPENGENI_TEST_SCENARIO === \"sandbox\") {\n console.log(\n `[sandbox-e2e] capture commit inserted=${Boolean(inserted)} revision=${revision} epoch=${input.leaseEpoch} group=${input.sandboxGroupId}`,\n );\n }\n throwIfCaptureAborted(signal);\n if (!inserted) {\n // Lease superseded/released between capture and commit. Best-effort clean up\n // the turn-keyed blobs we just PUT (content blobs may be shared with a\n // surviving revision — leave them for the next GC); never throw.\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"superseded\" },\n });\n await safeDelete(storage, [manifestKey, treeKey], observability, signal);\n return;\n }\n\n if (input.publish) {\n await input.publish(inserted.events).catch(() => undefined);\n }\n\n // ── 9. inline keep-latest-N GC (best-effort; F9 — after the commit) ────────\n let gcDeleted = 0;\n try {\n throwIfCaptureAborted(signal);\n const plan = await planWorkspaceCaptureGc(input.db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n keepN,\n });\n throwIfCaptureAborted(signal);\n if (plan.evictedRowIds.length > 0) {\n await safeDelete(\n storage,\n [...plan.deleteBlobKeys, ...plan.deletePerRevisionKeys],\n observability,\n signal,\n );\n throwIfCaptureAborted(signal);\n gcDeleted = await deleteWorkspaceCaptureRows(input.db, {\n workspaceId: input.workspaceId,\n rowIds: plan.evictedRowIds,\n });\n throwIfCaptureAborted(signal);\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_gc_deletions_total\",\n amount: gcDeleted,\n });\n }\n } catch (gcError) {\n if (signal.aborted) throw gcError;\n // GC is storage hygiene — a failure never affects the just-committed capture.\n observability.warn(\"workspace capture GC failed — capture unaffected\", {\n \"opengeni.session_id\": input.sessionId,\n \"error.message\": gcError instanceof Error ? gcError.message : String(gcError),\n });\n }\n\n // ── 10. observe completion ────────────────────────────────────────────────\n const durationMs = Date.now() - startedAt;\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"ok\" },\n });\n observability.observeHistogram({\n name: \"opengeni_workspace_capture_duration_seconds\",\n value: durationMs / 1000,\n });\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction captureDegradedReason(\n reason: RepositoryDiscoveryDegradedReason | null,\n): WorkspaceCaptureDegradedReason {\n switch (reason) {\n case \"command_timed_out\":\n return \"repository_discovery_timed_out\";\n case \"result_limit_exceeded\":\n return \"repository_discovery_result_limit_exceeded\";\n case \"command_failed\":\n default:\n return \"repository_discovery_command_failed\";\n }\n}\n\nasync function persistDegradedCapture(\n input: CaptureWorkspaceRevisionInput,\n startedAt: number,\n signal: AbortSignal,\n revision: number,\n reason: WorkspaceCaptureDegradedReason,\n discoveredRepoCount: number,\n): Promise<void> {\n const capturedAt = new Date();\n const stats = {\n degradedReason: reason,\n discoveredRepoCount,\n durationMs: Date.now() - startedAt,\n };\n const inserted = await insertFailedWorkspaceCapture(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: input.leaseEpoch,\n revision,\n stats,\n capturedAt,\n });\n throwIfCaptureAborted(signal);\n if (!inserted) {\n input.observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"superseded\" },\n });\n return;\n }\n const discoveryFailure = reason.startsWith(\"repository_discovery_\");\n input.observability.warn(\n discoveryFailure\n ? \"workspace capture degraded — repository discovery incomplete\"\n : \"workspace capture degraded — repository read incomplete\",\n {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": input.turnId ?? \"\",\n \"workspace_capture.degraded_reason\": reason,\n \"workspace_capture.discovered_repo_count\": discoveredRepoCount,\n },\n );\n input.observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: {\n result: discoveryFailure ? \"degraded_repository_discovery\" : \"degraded_repository_read\",\n },\n });\n if (input.publish) {\n await input.publish(inserted.events).catch(() => undefined);\n }\n}\n\nfunction throwIfCaptureAborted(signal: AbortSignal): void {\n if (signal.aborted) {\n throw new Error(\"workspace capture cancelled after its deadline\");\n }\n}\n\nfunction statusCodeOf(f: GitFileStatus): GitFileStatusCode {\n return f.worktree ?? f.index ?? \"modified\";\n}\n\n/**\n * sha256 over the CHANGE SURFACE only — per-file (path, status, hash, deleted,\n * tooLarge) and per-repo diff summary (path, status, additions, deletions).\n * Deliberately excludes the tree index and file mtimes (which drift without a\n * real change) so two turns that leave the workspace in the same state produce\n * the same fingerprint (the empty-turn gate). Order-independent (sorted).\n */\nfunction changeFingerprint(repos: WorkspaceCaptureRepo[], files: WorkspaceCaptureFile[]): string {\n const fileParts = files\n .map((f) => `${f.path}|${f.status}|${f.hash ?? \"\"}|${f.deleted ? 1 : 0}|${f.tooLarge ? 1 : 0}`)\n .sort();\n const repoParts = repos\n .map(\n (r) =>\n `${r.root}#${r.head ?? \"\"}#` +\n r.diff\n .map((d) => `${d.path}:${d.status}:${d.additions}:${d.deletions}:${d.truncated ? 1 : 0}`)\n .sort()\n .join(\",\"),\n )\n .sort();\n return sha256(utf8(JSON.stringify({ files: fileParts, repos: repoParts })));\n}\n\n/** Join a repo-root-relative path onto its workspace-relative repo root. */\nexport function joinRepoPath(repoRoot: string, repoRelPath: string): string {\n if (!repoRoot || repoRoot === \"\" || repoRoot === \".\") return repoRelPath;\n return `${repoRoot.replace(/\\/+$/, \"\")}/${repoRelPath}`;\n}\n\nfunction sha256(bytes: Uint8Array): string {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\nfunction utf8(s: string): Uint8Array {\n return new TextEncoder().encode(s);\n}\n\n/** Content-addressed after-image blob key (shared across revisions → GC input). */\nexport function blobKey(workspaceId: string, sessionId: string, sha256Hex: string): string {\n return `workspace-captures/${workspaceId}/${sessionId}/blobs/${sha256Hex}`;\n}\n\nasync function safeDelete(\n storage: ObjectStorage,\n keys: string[],\n observability: Observability,\n signal: AbortSignal,\n): Promise<void> {\n for (const key of keys) {\n throwIfCaptureAborted(signal);\n await storage.deleteObject(key).catch((error) => {\n observability.warn(\"workspace capture blob delete failed (orphan left; capture unaffected)\", {\n \"storage.key\": key,\n \"error.message\": error instanceof Error ? error.message : String(error),\n });\n });\n }\n}\n\n/**\n * Build the workspace tree index in ONE remote filesystem round-trip. Channel-A\n * prunes residue directories inside `find` while still emitting their collapsed\n * node, so node_modules cannot consume the authored-file budget. The former\n * serial per-directory BFS took 55.8 seconds for a 4,522-entry production tree\n * and blocked Steer cancellation. This path is bounded by entry count, nesting\n * depth, the outer capture deadline, and the owning activity's cancellation.\n */\nasync function buildTreeIndex(\n svc: SandboxChannelAService,\n startedAt: number,\n signal: AbortSignal,\n): Promise<{ root: FsTreeNode; entryCount: number; truncated: boolean }> {\n throwIfCaptureAborted(signal);\n if (Date.now() - startedAt > CAPTURE_TIMEOUT_MS - 5_000) {\n throw new Error(\"workspace capture tree index reached its deadline before listing\");\n }\n let listing: Awaited<ReturnType<typeof svc.fsListPruned>>;\n try {\n listing = await svc.fsListPruned(\n {\n path: \"\",\n depth: TREE_MAX_DEPTH,\n maxEntries: TREE_MAX_ENTRIES,\n includeHidden: true,\n },\n RESIDUE_DIRS,\n );\n throwIfCaptureAborted(signal);\n } catch (error) {\n if (isBoxExitingError(error)) {\n throw new BoxExitingError(error instanceof Error ? error.message : String(error));\n }\n throw error;\n }\n\n let entryCount = 0;\n let depthTruncated = false;\n const stack = [...(listing.root.children ?? [])];\n while (stack.length > 0) {\n const node = stack.pop()!;\n entryCount += 1;\n if (node.type !== \"dir\") continue;\n if (RESIDUE_DIR_SET.has(node.name)) {\n node.truncated = true;\n node.children = [];\n continue;\n }\n if (node.path.split(\"/\").length >= TREE_MAX_DEPTH) {\n node.truncated = true;\n depthTruncated = true;\n continue;\n }\n stack.push(...(node.children ?? []));\n }\n return {\n root: listing.root,\n entryCount,\n truncated: listing.truncated || depthTruncated,\n };\n}\n","import { getDocument, indexDocumentNow } from \"@opengeni/documents\";\nimport { configuredStaticUsageLimits } from \"@opengeni/config\";\nimport {\n getBillingBalance,\n recordUsageEvent,\n resolveDocumentIndexAuthority,\n rlsContextForWorkspace,\n sumUsageQuantity,\n withWorkspaceUsageLock,\n} from \"@opengeni/db\";\nimport type { ActivityServices, IndexDocumentInput } from \"./types\";\n\nexport function createDocumentActivities(services: () => Promise<ActivityServices>) {\n return {\n indexDocument: async (input: IndexDocumentInput) => {\n const { settings, db, objectStorage, documentServices } = await services();\n if (!objectStorage) {\n throw new Error(\"object storage is not configured\");\n }\n const context = await rlsContextForWorkspace(db, input.workspaceId);\n if (context.accountId !== input.accountId) {\n throw new Error(\"document account/workspace authority mismatch\");\n }\n return await withWorkspaceUsageLock(db, input.workspaceId, async (lockedDb) => {\n const storedAuthority = await resolveDocumentIndexAuthority(lockedDb, input);\n if (!storedAuthority) {\n throw new Error(\"document authority was not found before indexing\");\n }\n const suppliedAuthorityFields = [\n \"authorityKind\",\n \"authorityWorkspaceId\",\n \"authoritySubjectId\",\n ] as const;\n const suppliedCount = suppliedAuthorityFields.filter((field) =>\n Object.prototype.hasOwnProperty.call(input, field),\n ).length;\n const suppliedMismatch =\n (Object.prototype.hasOwnProperty.call(input, \"authorityKind\") &&\n input.authorityKind !== storedAuthority.authorityKind) ||\n (Object.prototype.hasOwnProperty.call(input, \"authorityWorkspaceId\") &&\n input.authorityWorkspaceId !== storedAuthority.authorityWorkspaceId) ||\n (Object.prototype.hasOwnProperty.call(input, \"authoritySubjectId\") &&\n input.authoritySubjectId !== storedAuthority.authoritySubjectId);\n if (suppliedMismatch) {\n throw new Error(\"document authority changed before indexing\");\n }\n if (suppliedCount !== 0 && suppliedCount !== suppliedAuthorityFields.length) {\n throw new Error(\"document authority tuple is partial\");\n }\n const claimedDocument = await getDocument(lockedDb, input.workspaceId, input.documentId, {\n viewerSubjectId: storedAuthority.authoritySubjectId,\n });\n if (\n !claimedDocument ||\n claimedDocument.authorityKind !== storedAuthority.authorityKind ||\n claimedDocument.authorityWorkspaceId !== storedAuthority.authorityWorkspaceId ||\n claimedDocument.authoritySubjectId !== storedAuthority.authoritySubjectId\n ) {\n throw new Error(\"document authority changed before indexing\");\n }\n const document = await indexDocumentNow(\n lockedDb,\n objectStorage,\n input.workspaceId,\n input.documentId,\n documentServices,\n {\n beforeEmbed: async ({ chunkCount }) => {\n if (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\") {\n const balance = await getBillingBalance(lockedDb, input.accountId);\n if (balance.balanceMicros <= 0) {\n throw new Error(\"insufficient OpenGeni credits\");\n }\n }\n if (settings.usageLimitsMode !== \"static\" && settings.usageLimitsMode !== \"managed\") {\n return;\n }\n const limit =\n configuredStaticUsageLimits(settings).maxDocumentIndexedChunksPerWorkspace;\n if (!limit) {\n return;\n }\n const used = await sumUsageQuantity(lockedDb, {\n workspaceId: input.workspaceId,\n eventType: \"document.indexed\",\n since: startOfUtcMonth(),\n });\n if (used + chunkCount > limit) {\n throw new Error(`monthly document indexing limit reached (${limit} chunks)`);\n }\n },\n },\n { viewerSubjectId: storedAuthority.authoritySubjectId },\n );\n if (\n document.authorityKind !== storedAuthority.authorityKind ||\n document.authorityWorkspaceId !== storedAuthority.authorityWorkspaceId ||\n document.authoritySubjectId !== storedAuthority.authoritySubjectId\n ) {\n throw new Error(\"document authority changed before indexing\");\n }\n if (document.status === \"ready\") {\n await recordUsageEvent(lockedDb, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"document.indexed\",\n quantity: document.chunkCount,\n unit: \"chunk\",\n sourceResourceType: \"document\",\n sourceResourceId: document.id,\n idempotencyKey: `document.indexed:${input.workspaceId}:${document.id}:${document.updatedAt}`,\n });\n }\n return document;\n });\n },\n };\n}\n\nfunction startOfUtcMonth(date = new Date()): Date {\n return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1));\n}\n","import {\n claimDueTranscriptionRecordingObjectCleanup,\n claimExpiredFileUploadCleanup,\n completeDueTranscriptionRecordingObjectCleanup,\n completeExpiredFileUploadCleanup,\n purgeExpiredTranscriptionRecordings,\n} from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport type { ActivityServices } from \"./types\";\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<ActivityServices>,\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 return { reapExpiredFileUploads };\n}\n","// apps/worker/src/activities/sandbox-lease.ts — the SOLE liveness/GC/cost-stop\n// driver (P1.3 / OD-3).\n//\n// There is exactly ONE reaper activity: `reapSandboxLeases`. It is fired by the\n// ONE global reaper Temporal Schedule (registered in apps/worker/src/index.ts).\n// There is NO ownerHeartbeat, NO per-session timer, NO per-RPC workflow, NO\n// *ForViewer activity, NO resolveOwnerTaskQueue. Turn-holder lifecycle is bound\n// to Temporal *activity* liveness (the turn activity acquires/releases the turn\n// holder); a crashed founder's leaked turn holder becomes reapable via the lease\n// TTL — TTL-exemption means a *live* turn is never idle-reaped, NOT that a dead\n// turn's holder is immortal.\n//\n// One pass per fire:\n// 1. reapStaleLeaseHoldersGlobal (the P1.1 SECURITY-DEFINER cross-workspace\n// sweep): TTL-reaps stale viewer holders, resets warming-death rows to cold,\n// recomputes refcounts + enters draining at refcount 0, and RETURNS the\n// drainable rows (workspace, group, instance, epoch) whose drain grace has\n// elapsed at refcount 0. DB-only — no provider call inside the sweep.\n// 2. For each drainable row: resume/attach the provider box BY ID (off the\n// lease's resume envelope, via createSandboxClientForBackend +\n// establishSandboxSessionFromEnvelope), call the provider terminate, then\n// confirmDrainCold (the CAS draining->cold under the epoch fence).\n//\n// IDEMPOTENT + safe to run concurrently with itself: the drain CAS is guarded on\n// (draining AND refcount=0 AND lease_epoch=expected). If another sweep already\n// drained the row, or a late re-arm flipped it warm, or a newer epoch snuck in,\n// confirmDrainCold returns wentCold:false and we skip — provider stop() fires\n// ONLY when the CAS proves the box is still the draining box we observed. We\n// confirm the CAS would still pass (re-read the lease) BEFORE the provider call\n// so a box that was re-armed mid-sweep is never terminated out from under a live\n// holder.\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n accrueWarmSeconds,\n adoptLegacyModalCheckpointArtifact,\n confirmDrainCold,\n appendSessionEventToSandboxGroup,\n bindRetainedProcessProviderIdentity,\n claimWorkspaceArchiveCapture,\n claimSandboxCheckpointArtifactsForGc,\n claimTerminalRetainedProcesses,\n countActiveRetainedProcessesByOwnerState,\n countSandboxCheckpointArtifactsByState,\n countExpiredDrainingSandboxLeases,\n countQueuedTurns,\n countSandboxLeasesByLiveness,\n deferRetainedProcessReconciliation,\n forceDrainOverLimitViewerOnlyBoxes,\n getBillingBalance,\n listCreditBalancesByAccount,\n listLegacyModalCheckpointSlots,\n listLiveModalSandboxLeaseAttributions,\n listMeterableWarmLeases,\n listSandboxViewerForceDrainWorkspaceIds,\n markSandboxCheckpointArtifactDeletePending,\n persistDrainSnapshot,\n pruneDeletedSandboxCheckpointArtifacts,\n registerSandboxCheckpointArtifact,\n recordRetainedProcessReconciliationProof,\n releaseWorkspaceArchiveCapture,\n replaceExpiredWorkspaceArchiveCapture,\n readLease,\n reapExpiredSessionListSnapshots,\n reapStaleLeaseHoldersGlobal,\n requestDueSandboxRotationsGlobal,\n readSandboxRotationBacklog,\n retainedProcessReconciliationProof,\n retainedProcessSettlementIdentity,\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 { sandboxArchiveCaptureTimeoutMs, sandboxWarmRateMicrosPerSecond } from \"@opengeni/config\";\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 captureVerifiedWorkspaceArchive,\n createSandboxClientForBackend,\n deleteModalCheckpointSnapshot,\n deserializeSandboxSessionStateEnvelope,\n establishSandboxSessionFromEnvelope,\n inspectModalSandboxLifecycle,\n isExecSessionLostBanner,\n isProviderSandboxNotFoundError,\n parseExecBannerExitCode,\n resolveModalCheckpointProviderBindingForLiveSandbox,\n resolveModalCheckpointProviderBinding,\n resolveModalCheckpointProviderBindingForSession,\n sandboxBackendForSdkBackendId,\n sandboxCommandExitCode,\n sandboxCommandStillRunning,\n sweepModalOrphanSandboxes,\n terminateModalSandboxById,\n verifySandboxExecReadiness,\n type ModalOrphanSweepTermination,\n type ModalCheckpointProviderBinding,\n type WorkspaceArchiveDescriptor,\n} from \"@opengeni/runtime\";\nimport type { ActivityServices } from \"./types\";\nimport { reconcilePendingParentSystemUpdates } from \"./parent-wake\";\nimport {\n recordCreditBalanceGauges,\n recordCreditMicros,\n recordExpiredDrainingSandboxLeaseGauges,\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 recordSandboxRotationBacklogGauges,\n recordTurnsQueuedGauge,\n} from \"../observability-metrics\";\nimport { providerIdentityFromResumeState } from \"../sandbox-routing\";\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 /** Viewer-only boxes force-drained because their workspace is over a limit\n * (0 balance / over the warm cap) — turn-held boxes are never drained (P2.1). */\n forceDrained: number;\n /** Provider-side Modal orphan sandboxes terminated by the defensive sweep. */\n modalOrphansTerminated: number;\n};\n\n// The structural slice of a provider SandboxClient we need to resume-by-id and\n// terminate a box. `delete(state)` is the provider's stop()/terminate (the\n// runtime SandboxClient maps it to the per-provider teardown). Narrowed so this\n// stays agent-loop-free.\ntype TerminableClient = {\n backendId: string;\n resume?: (state: unknown) => Promise<unknown>;\n deserializeSessionState?: (state: Record<string, unknown>) => Promise<unknown>;\n delete?: (state: unknown) => Promise<unknown>;\n};\n\n// A live session handle may expose a kill/terminate/close itself (some providers\n// tear the box down from the session, not the client). We try the client.delete\n// first (the canonical teardown), then fall back to a session-level terminator.\ntype TerminableSession = {\n kill?: () => Promise<unknown>;\n terminate?: () => Promise<unknown>;\n close?: () => Promise<unknown>;\n closed?: boolean;\n};\n\ntype CreateSandboxClientForBackendFn = typeof createSandboxClientForBackend;\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 | 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\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) => 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 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 /** 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 };\n\nexport type RetainedProcessProbeFn = (\n settings: ActivityServices[\"settings\"],\n lease: LeaseSnapshot,\n process: SandboxRetainedProcess,\n) => Promise<RetainedProcessProbeResult>;\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\nexport function createSandboxLeaseActivities(\n services: () => Promise<ActivityServices>,\n options: SandboxLeaseActivityOptions = {},\n) {\n const terminateBox: TerminateBoxFn = options.terminateBox ?? terminateProviderBox;\n const sweepModalOrphans: SweepModalOrphansFn =\n options.sweepModalOrphans ?? sweepModalOrphansForConfiguredBackend;\n const probeRetainedProcess = options.probeRetainedProcess ?? probeRetainedProcessAtProvider;\n const probeDrainableProvider = options.probeDrainableProvider ?? probeDrainableProviderReadiness;\n /**\n * The one global reaper sweep. Idempotent; concurrency-safe with itself.\n * The global Schedule always runs. A defensive mutation gate here ensures\n * that an ownership-off deployment still refreshes read-only metrics and\n * repairs the system-update outbox but can never terminate a box.\n */\n async function reapSandboxLeases(): Promise<ReapSandboxLeasesResult> {\n const service = await services();\n const { db, settings, observability } = service;\n const parentUpdates = await reconcilePendingParentSystemUpdates(service, 100).catch((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 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 // Inventory is useful even while provider ownership is disabled, and the\n // same globally scheduled activity remains its single projection owner.\n // Refresh before the mutation gate so dashboards show truthful zero/history\n // state and absence alerts do not misclassify an intentional rollout flag.\n await refreshQueueLeaseAndCreditGauges(db, observability);\n if (!settings.sandboxOwnershipEnabled) {\n if (parentUpdates.claimed > 0) {\n observability.info(\"system-update outbox reconciled\", parentUpdates);\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 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 // (0) Warm-meter tick (P2.1) — accrue warm-seconds for every WARM viewer-only\n // box (turn-held boxes meter on the turn heartbeat, so the list fn excludes\n // them). GROUP+epoch+tick idempotent → a shared box is one stream; an\n // overlapping/re-fired sweep cannot double-charge. Best-effort per row.\n const metered = await accrueWarmTick(db, settings, observability);\n\n // (0b) Per-workspace warm-cap + force-drain (P2.1) — under the usage lock, a\n // workspace at 0 balance / over its warm cap force-drains its VIEWER-ONLY\n // boxes (guarded turn_holders=0 — a paying turn is NEVER killed). The newly\n // draining rows are caught by the same sweep's terminate below.\n const forceDrainWorkspaceIds = new Set<string>();\n if (\n settings.billingMode === \"stripe\" ||\n settings.usageLimitsMode === \"managed\" ||\n settings.sandboxMaxWarmSecondsPerWorkspace > 0\n ) {\n for (const workspaceId of metered.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 const forceDrained = await forceDrainOverLimitWorkspaces(\n db,\n settings,\n forceDrainWorkspaceIds,\n observability,\n );\n\n // (0c) Terminal-owner retained-process reconciliation. Owner state selects\n // only a bounded inspection batch; exact provider exit/loss proof is\n // checkpointed before canonical settlement. Ambiguous, running, timed-out,\n // unsupported, and transient provider states preserve every durable row.\n await reconcileTerminalRetainedProcesses(\n db,\n settings,\n observability,\n probeRetainedProcess,\n options.inspectHistoricalModalSandbox ?? inspectModalSandboxLifecycle,\n );\n\n // (1) The DB-only cross-workspace sweep. Returns the drainable rows.\n const drainable: ReapDrainable[] = await reapStaleLeaseHoldersGlobal(db, {\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 horizon is deliberately generous defense-in-depth (not a\n // tuned guess about path lengths): a killed worker's frozen holder —\n // which would otherwise pin refcount >= 1 FOREVER, so the lease never\n // drains and the box dies at the provider hard-timeout UNPERSISTED —\n // clears within ~12 minutes.\n turnHolderTtlMs: settings.sandboxWarmingTimeoutMs + settings.sandboxLeaseTtlMs,\n idleGraceMs: settings.sandboxIdleGraceMs,\n });\n\n let terminated = 0;\n let skipped = 0;\n let modalOrphansTerminated = 0;\n\n // (2) Terminate each drainable box, then CAS draining->cold. Per-row failures\n // are isolated: one box's provider error must not abort the whole sweep (the\n // next sweep retries it; the provider idle-timeout is the backstop).\n for (const row of drainable) {\n try {\n const drainedCold = await terminateDrainableBox(\n db,\n settings,\n row,\n observability,\n terminateBox,\n probeDrainableProvider,\n );\n if (drainedCold) {\n terminated += 1;\n } else {\n skipped += 1;\n }\n } catch (error) {\n skipped += 1;\n observability.warn(\"sandbox reaper: terminate failed for drainable lease\", {\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n leaseEpoch: row.leaseEpoch,\n error: error instanceof Error ? error.message : String(error),\n });\n }\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(db, observability);\n\n if (\n drainable.length > 0 ||\n metered.accrued > 0 ||\n forceDrained > 0 ||\n modalOrphansTerminated > 0 ||\n rotationsRequested > 0 ||\n checkpointGc.claimed > 0\n ) {\n observability.info(\"sandbox reaper swept\", {\n drainable: drainable.length,\n terminated,\n skipped,\n metered: metered.accrued,\n forceDrained,\n modalOrphansTerminated,\n rotationsRequested,\n checkpointArtifactsClaimed: checkpointGc.claimed,\n checkpointArtifactsDeleted: checkpointGc.deleted,\n checkpointArtifactsFailed: checkpointGc.failed,\n });\n }\n\n return {\n examined: drainable.length,\n terminated,\n skipped,\n metered: metered.accrued,\n forceDrained,\n modalOrphansTerminated,\n };\n }\n\n return { reapSandboxLeases };\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;\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 for (const claim of claims) {\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 for (const slot of slots) {\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\nasync function reconcileTerminalRetainedProcesses(\n db: ActivityServices[\"db\"],\n settings: ActivityServices[\"settings\"],\n observability: ActivityServices[\"observability\"],\n probe: RetainedProcessProbeFn,\n inspectHistoricalModalSandbox: HistoricalModalSandboxLifecycleProbeFn,\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 for (const claim of claims) {\n let process = claim.process;\n const expected = retainedProcessSettlementIdentity(process);\n let proof = retainedProcessReconciliationProof(process);\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 = { status: \"deferred\", reason: \"provider_binding_missing\" };\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 (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 observation = await probe(settings, lease!, process);\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 );\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 observability.warn(\"sandbox reaper: retained-process proof checkpoint failed\", {\n processId: process.id,\n error: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n }\n\n try {\n 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 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: RetainedProcessReconciliationOutcome,\n): Promise<void> {\n const exponent = Math.min(4, Math.max(0, process.reconcileAttempts - 1));\n const retryAfterMs = Math.min(\n 5 * 60_000,\n Math.max(settings.sandboxLeaseReaperPeriodMs, 30_000) * 2 ** exponent,\n );\n try {\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,\n retryAfterMs,\n });\n recordRetainedProcessReconciliation(observability, outcome);\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 RetainedProcessProbeClient = {\n backendId: string;\n resume?: (state: unknown) => Promise<unknown>;\n deserializeSessionState?: (state: Record<string, unknown>) => Promise<unknown>;\n};\n\ntype RetainedProcessProbeSession = {\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\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\nexport async function probeRetainedProcessAtProvider(\n settings: ActivityServices[\"settings\"],\n lease: LeaseSnapshot,\n process: SandboxRetainedProcess,\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 !== 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 envelopeBackend = (lease.resumeState as { backendId?: unknown }).backendId;\n if (envelopeBackend !== undefined && envelopeBackend !== process.providerBackend) {\n return { status: \"deferred\", reason: \"identity_mismatch\" };\n }\n if (providerIdentityFromResumeState(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 (!client || client.backendId !== process.providerBackend || !client.resume) {\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 );\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 session = (await withRetainedProcessProbeTimeout(\n client.resume(resumedState),\n )) 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 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 }\n\n let result: unknown;\n try {\n result = await withRetainedProcessProbeTimeout(\n session.writeStdin({\n sessionId: process.providerSessionId,\n chars: \"\",\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 (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 const observation = classifyRetainedProcessPollResult(result, process.providerSessionId);\n if (\n observation.status === \"deferred\" &&\n observation.reason === \"provider_running\" &&\n lease.rotationRequestedAt !== null\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 return classifyRetainedProcessPollResult(interrupted, process.providerSessionId);\n } catch (error) {\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 {\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): RetainedProcessProbeResult {\n if (typeof result !== \"string\") {\n return { status: \"deferred\", reason: \"provider_unknown\" };\n }\n if (isExecSessionLostBanner(result, providerSessionId)) {\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 try {\n const rate = 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 subjectId: lease.sandboxGroupId,\n });\n if (result.accrued) {\n accrued += 1;\n }\n recordCreditMicros(observability, \"usage\", result.costMicros);\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 observability: ActivityServices[\"observability\"],\n): Promise<void> {\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 await refreshSandboxInventoryGauge(observability, \"leases\", \"sandbox-lease\", async () => {\n recordSandboxLeaseGauges(observability, await countSandboxLeasesByLiveness(db));\n });\n await refreshSandboxInventoryGauge(\n observability,\n \"checkpoint_artifacts\",\n \"checkpoint-artifact\",\n async () => {\n recordSandboxCheckpointArtifactGauges(\n observability,\n await countSandboxCheckpointArtifactsByState(db),\n );\n },\n );\n await refreshSandboxInventoryGauge(\n observability,\n \"rotation_backlog\",\n \"rotation-backlog\",\n async () => {\n recordSandboxRotationBacklogGauges(observability, await readSandboxRotationBacklog(db));\n },\n );\n await refreshSandboxInventoryGauge(\n observability,\n \"retained_processes\",\n \"retained-process\",\n async () => {\n recordRetainedProcessInventoryGauges(\n observability,\n await countActiveRetainedProcessesByOwnerState(db),\n );\n },\n );\n await refreshSandboxInventoryGauge(\n observability,\n \"expired_drains\",\n \"expired-draining\",\n async () => {\n recordExpiredDrainingSandboxLeaseGauges(\n observability,\n await countExpiredDrainingSandboxLeases(db),\n );\n },\n );\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\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 at 0 balance (when a billing /\n * managed mode is on) or over its warm cap, force-drain its VIEWER-ONLY boxes\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 =\n settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\";\n const cap = settings.sandboxMaxWarmSecondsPerWorkspace;\n let forceDrained = 0;\n for (const workspaceId of workspaceIds) {\n try {\n const { accountId } = await rlsContextForWorkspace(db, workspaceId);\n const balance = enforceBalance\n ? await getBillingBalance(db, accountId)\n : ({ balanceMicros: 1 } as { balanceMicros: number });\n const result = await forceDrainOverLimitViewerOnlyBoxes(db, {\n workspaceId,\n balanceMicros: balance.balanceMicros,\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 return forceDrained;\n}\n\nexport function modalOrphanTerminationStillEligible(\n latest: Awaited<ReturnType<typeof listLiveModalSandboxLeaseAttributions>>,\n candidate: ModalOrphanSweepTermination,\n): boolean {\n if (latest.some((lease) => lease.instanceId === candidate.sandboxId)) {\n return false;\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. A paused snapshot cannot pass that proof; a\n * missing provider is returned as typed loss; every ambiguous error preserves\n * the old claim for the next sweep.\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, { cmd: \"true\", yieldTimeMs: 1_000, maxOutputTokens: 1_000 }),\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\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 CAS-gated on BOTH ends:\n * - BEFORE provider terminate: re-read the lease and assert it is STILL\n * draining at refcount 0 at the SAME epoch we observed. A re-arm (a viewer\n * or turn arrived during the grace window) flips it back to warm and bumps\n * no epoch but changes liveness/refcount — we skip and never touch the box.\n * - AFTER provider terminate: confirmDrainCold's CAS (draining AND refcount=0\n * AND lease_epoch=expected) is the authoritative commit; if it returns false\n * a late re-arm raced us between our re-read and the stop — but the box is\n * already torn down, so we let the next acquire cold-restore it (NEVER a\n * double-spawn: the lease is the singleton, the box is just gone).\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): 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 ||\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 captureTimeoutMs = sandboxArchiveCaptureTimeoutMs(settings);\n let captureClaim:\n | NonNullable<\n Extract<Awaited<ReturnType<typeof claimWorkspaceArchiveCapture>>, { status: \"claimed\" }>\n >[\"claim\"]\n | null = null;\n let providerMissingBeforeCapture = false;\n if (lease.instanceId) {\n if (lease.archiveCapture) {\n if (lease.archiveCapture.deadlineAt.getTime() > Date.now()) {\n // A live owner still holds the provider pause gate. It will release the\n // exact claim on settlement; this sweep must not compete.\n return false;\n }\n // A deadline is never evidence that a non-cancellable provider capture\n // stopped. Without an exact resume envelope there is no safe way to prove\n // the attributed provider is command-ready, so preserve the gate.\n if (!lease.resumeState) return false;\n const providerState = await probeDrainableProvider(settings, lease);\n if (providerState === \"missing\") {\n providerMissingBeforeCapture = true;\n captureClaim = {\n ...lease.archiveCapture,\n leaseId: lease.id,\n leaseEpoch: lease.leaseEpoch,\n instanceId: lease.instanceId,\n archiveGeneration: lease.archiveGeneration,\n archiveComplete: lease.archiveComplete,\n };\n } else {\n const replacement = await replaceExpiredWorkspaceArchiveCapture(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n priorCaptureId: lease.archiveCapture.id,\n captureId: randomUUID(),\n expectedEpoch: row.leaseEpoch,\n expectedInstanceId: lease.instanceId,\n captureTimeoutMs,\n });\n if (!replacement) return false;\n captureClaim = replacement;\n }\n } else {\n const claimed = await claimWorkspaceArchiveCapture(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n captureId: randomUUID(),\n expectedEpoch: row.leaseEpoch,\n expectedInstanceId: lease.instanceId,\n liveness: \"draining\",\n captureTimeoutMs,\n minIntervalMs: 0,\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 {\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 guard as confirmDrainCold (draining AND refcount=0 AND lease_epoch=\n // expected): a re-arm or newer epoch that snuck in writes ZERO rows → wrote:false\n // → the seam leaves the box RUNNING and we skip 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 = false;\n let archiveRevision: string | null = null;\n const persistArchive: PersistArchiveFn = async (\n archiveBase64: string | 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 let checkpointArtifactId: string | null = null;\n if (\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 expectedEpoch: row.leaseEpoch,\n expectedInstanceId: lease.instanceId,\n expectedWorkspaceGeneration: captureClaim.workspaceGeneration,\n captureId: captureClaim.id,\n };\n let result: Awaited<ReturnType<typeof persistDrainSnapshot>>;\n if (archiveBase64 === null) {\n result = await persistDrainSnapshot(db, { ...baseInput, workspaceArchive: null });\n } else {\n if (!archiveMetadata) {\n throw new Error(\"Sandbox snapshot publication requires a verified archive descriptor\");\n }\n result = await persistDrainSnapshot(db, {\n ...baseInput,\n workspaceArchive: archiveBase64,\n workspaceArchiveMeta: archiveMetadata,\n ...(checkpointArtifactId ? { checkpointArtifactId } : {}),\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 try {\n const termination: ProviderTerminationOutcome | boolean = providerMissingBeforeCapture\n ? { terminated: true, providerMissingBeforeCapture: true }\n : await terminateBox(settings, lease, observability, persistArchive);\n const terminated = typeof termination === \"boolean\" ? termination : termination.terminated;\n if (!terminated) {\n return false;\n }\n\n const providerMissing =\n providerMissingBeforeCapture ||\n (typeof termination === \"boolean\" ? false : termination.providerMissingBeforeCapture);\n // The authoritative commit: CAS draining->cold under the epoch fence. If a\n // late re-arm or newer epoch raced in after our re-read, wentCold:false and we\n // report a skip (the box is down; a fresh acquire cold-restores it).\n const { wentCold } = await confirmDrainCold(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n expectedEpoch: row.leaseEpoch,\n providerMissingBeforeCapture: providerMissing,\n });\n if (wentCold) {\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 },\n });\n } catch (eventError) {\n observability.warn(\n \"sandbox reaper: box-terminated event write failed (drain outcome unaffected)\",\n {\n sandboxGroupId: row.sandboxGroupId,\n error: eventError instanceof Error ? eventError.message : String(eventError),\n },\n );\n }\n }\n return wentCold;\n } finally {\n if (captureClaim && lease.instanceId) {\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 }).catch((error) => {\n observability.warn(\"sandbox reaper: archive capture gate release failed\", {\n sandboxGroupId: row.sandboxGroupId,\n leaseEpoch: row.leaseEpoch,\n error: error instanceof Error ? error.message : String(error),\n });\n });\n }\n }\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 = TerminableSession & {\n persistWorkspace?: () => Promise<Uint8Array | undefined>;\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 (client.delete / session kill|terminate|close).\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 * For a draining lease with no envelope (a warming-death row that committed no\n * box, or a 'none'-backed group) there is no live box — a no-op (return true).\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): Promise<ProviderTerminationOutcome> {\n const durableBackendId = (lease.resumeBackendId ?? lease.backend) as string;\n const backend = sandboxBackendForSdkBackendId(durableBackendId) ?? durableBackendId;\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 sandboxGroupId: lease.sandboxGroupId,\n backend,\n },\n );\n return { terminated: true, providerMissingBeforeCapture: false };\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 if (backend === \"modal\" && !lease.resumeState && lease.instanceId) {\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 sandboxGroupId: lease.sandboxGroupId,\n backend,\n instanceId: lease.instanceId,\n },\n );\n return { terminated: false, providerMissingBeforeCapture: false };\n }\n try {\n await terminateModalSandboxById(settings, lease.instanceId);\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 sandboxGroupId: lease.sandboxGroupId,\n backend,\n instanceId: lease.instanceId,\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). No envelope -> no live box to stop.\n if (!lease.resumeState) {\n return { terminated: true, providerMissingBeforeCapture: false };\n }\n\n const client = createClientForBackend(backend as never, settings) as TerminableClient | 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: unknown;\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 );\n if (resumedState === undefined) {\n throw new Error(`sandbox backend ${backend} returned no resumable provider state`);\n }\n session = (await client.resume(resumedState)) as PersistableSession;\n sessionState = resumedState;\n } catch (error) {\n if (isProviderSandboxNotFoundError(client.backendId, error)) {\n observability.info(\"sandbox reaper: drainable box already gone before workspace capture\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n });\n return { terminated: true, providerMissingBeforeCapture: true };\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 // 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: Awaited<ReturnType<typeof captureVerifiedWorkspaceArchive>> | undefined;\n const sessionWorkspacePersistence = (\n session as { state?: { workspacePersistence?: unknown } } | undefined\n )?.state?.workspacePersistence;\n const checkpointBinding =\n backend === \"modal\" &&\n (sessionWorkspacePersistence === \"snapshot_filesystem\" ||\n sessionWorkspacePersistence === \"snapshot_directory\")\n ? await withRetainedProcessProbeTimeout(\n resolveModalCheckpointProviderBindingForSession(settings, session),\n )\n : null;\n try {\n verifiedArchive = session?.persistWorkspace\n ? await captureVerifiedWorkspaceArchive(session)\n : undefined;\n } catch (error) {\n if (isProviderSandboxNotFoundError(client.backendId, error)) {\n observability.info(\"sandbox reaper: box gone during workspace capture\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n });\n return { terminated: true, providerMissingBeforeCapture: true };\n }\n observability.warn(\n \"sandbox reaper: persistWorkspace failed — leaving box draining (files NOT lost)\",\n {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n error: error instanceof Error ? error.message : String(error),\n },\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 epoch fence, then GC the\n // superseded snapshot. A CAS miss (wrote:false) means the lease was re-armed\n // mid-drain: the box is wanted again — DO NOT terminate it (return false; the\n // caller skips confirmDrainCold).\n //\n // Re-arm guard for no-archive path: even when persistWorkspace returned no bytes\n // (a backend with no persistWorkspace, or an empty result), we MUST still CAS-\n // check before delete(). The snapshot window (resume → persistWorkspace) can be\n // long; a late acquireLease re-arm (draining→warm, same epoch) can land in it,\n // so without this check we would delete a box the lease now treats as live. The\n // null-archive path of persistArchive does exactly this: FOR UPDATE + liveness/\n // refcount/epoch guard, no write. wrote:false → abort the terminate.\n if (verifiedArchive) {\n const { wrote } = await persistArchive(\n verifiedArchive.base64,\n verifiedArchive.descriptor,\n session,\n checkpointBinding,\n );\n if (!wrote) {\n observability.info(\n \"sandbox reaper: lease re-armed during persist — leaving box RUNNING (no terminate)\",\n {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\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. Prefer the client.delete(state) teardown (the canonical\n // provider stop()); fall back to a session-level kill/terminate/close. A\n // terminate that fails because the box is already gone is success.\n try {\n if (client.delete && sessionState !== undefined) {\n await client.delete(sessionState);\n return { terminated: true, providerMissingBeforeCapture: false };\n }\n if (session?.kill) {\n await session.kill();\n return { terminated: true, providerMissingBeforeCapture: false };\n }\n if (session?.terminate) {\n await session.terminate();\n return { terminated: true, providerMissingBeforeCapture: false };\n }\n if (session?.close) {\n if (!session.closed) {\n await session.close();\n }\n return { terminated: true, providerMissingBeforeCapture: false };\n }\n } catch (error) {\n if (isProviderSandboxNotFoundError(client.backendId, error)) {\n observability.info(\"sandbox reaper: provider already gone during terminate\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\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 throw new Error(`sandbox backend ${backend} exposes no provider termination method`);\n}\n","import {\n OPENGENI_SLACK_BOT_CREDENTIAL_LABEL,\n OPENGENI_SLACK_BOT_CREDENTIAL_ROLE,\n OPENGENI_SLACK_BOT_SESSION_METADATA_KEY,\n} from \"@opengeni/contracts\";\nimport {\n openGeniSlackBotMetadata,\n requireOpenGeniSlackBotConnection,\n scheduledSlackBotConnectionId,\n} from \"@opengeni/core\";\nimport {\n appendSessionEventsWithLockedSessionUpdate,\n addSessionSystemUpdateWithSourceMutation,\n createScheduledTaskRun,\n createSession,\n createSessionGoal,\n enqueueSessionWorkflowWakeIfRunnable,\n getBillingBalance,\n getScheduledTask,\n getScheduledTaskPersonalConnectionDelegations,\n getRig,\n getVariableSet,\n isCodexBilledTurn,\n markScheduledTaskRunFailedIfQueued,\n recordUsageEvent,\n requireSession,\n setTemporalWorkflowId,\n settleScheduledTaskRunInTransaction,\n SessionSpawnDeniedDbError,\n sumUsageQuantity,\n updateScheduledTask,\n upsertSessionGoal,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents, publishDurableSessionEvents } from \"@opengeni/events\";\nimport { configuredStaticUsageLimits, type Settings } from \"@opengeni/config\";\nimport {\n assertReusableSessionRevivable,\n scheduledUserMessagePayload,\n workflowIdForSession,\n} from \"./common\";\nimport { withFirstPartyTools } from \"./goals\";\nimport type {\n ActivityServices,\n DispatchScheduledTaskRunInput,\n DispatchScheduledTaskRunResult,\n} from \"./types\";\n\nexport function createScheduledTaskActivities(services: () => Promise<ActivityServices>) {\n return {\n dispatchScheduledTaskRun: async (\n input: DispatchScheduledTaskRunInput,\n ): Promise<DispatchScheduledTaskRunResult> => {\n const { settings, db, bus, wakeSessionWorkflow } = 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 === \"manual\" && !input.initiator) {\n return { action: \"blocked\", reason: \"malformed_manual_trigger\" };\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 const taskPersonalConnectionDelegations = await getScheduledTaskPersonalConnectionDelegations(\n db,\n task.workspaceId,\n task.id,\n );\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 // The scheduled task's model can be codex/<slug>; resolve it here so the\n // admission gate can skip the credit/cost gates for a codex-billed run\n // (paid by the user's ChatGPT/Codex plan). This file uses BASE settings (no\n // codex overlay), so the predicate does its own active-credential read.\n const model = task.agentConfig.model ?? settings.openaiModel;\n const isCodexRun = await isCodexBilledTurn({\n db,\n settings,\n workspaceId: task.workspaceId,\n model,\n });\n const admissionDenial = await scheduledRunAdmissionDenial(\n settings,\n db,\n task.accountId,\n task.workspaceId,\n input.agentRunUsageIdempotencyKey ? 0 : 1,\n isCodexRun,\n );\n if (admissionDenial) {\n return { action: \"blocked\", reason: admissionDenial };\n }\n const run = await createScheduledTaskRun(db, {\n workspaceId: task.workspaceId,\n taskId: task.id,\n triggerType: input.triggerType,\n producerKey:\n input.producerKey ??\n input.agentRunUsageIdempotencyKey ??\n `scheduled:${crypto.randomUUID()}`,\n scheduledAt: null,\n });\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: input.initiator ?? { kind: \"service\", subjectId: \"scheduler\" },\n initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },\n origin: \"scheduled_task\",\n idempotencyKey: `usage:scheduled_task.fired:${run.id}`,\n });\n if (run.status === \"dispatched\" && run.sessionId && run.triggerEventId) {\n await recordUsageEvent(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: run.id,\n sessionId: run.sessionId,\n initiator: input.initiator ?? { kind: \"service\", subjectId: \"scheduler\" },\n initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },\n origin: \"scheduled_task\",\n idempotencyKey:\n input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`,\n });\n const workflowId = workflowIdForSession(run.sessionId);\n const workflowWakeRevision = await enqueueSessionWorkflowWakeIfRunnable(db, {\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 if (wakeSessionWorkflow && workflowWakeRevision !== null) {\n await 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 let result: DispatchScheduledTaskRunResult;\n try {\n const reasoningEffort = task.agentConfig.reasoningEffort ?? settings.openaiReasoningEffort;\n const sandboxBackend = task.agentConfig.sandboxBackend ?? settings.sandboxBackend;\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 taskTools = withFirstPartyTools(settings, task.agentConfig.tools);\n if (task.runMode === \"new_session_per_run\" || !task.reusableSessionId) {\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 = task.variableSetId\n ? await getVariableSet(db, task.workspaceId, task.variableSetId)\n : null;\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 = await getRig(db, task.workspaceId, task.rigId);\n if (!rig || !rig.activeVersion) {\n throw new Error(`rig has no active version to bind: ${task.rigId}`);\n }\n frozenRigId = rig.id;\n frozenRigVersionId = rig.activeVersion.id;\n }\n let session: Awaited<ReturnType<typeof createSession>>;\n const taskMetadata = { ...task.agentConfig.metadata };\n delete taskMetadata[OPENGENI_SLACK_BOT_SESSION_METADATA_KEY];\n try {\n session = await createSession(db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n initialMessage: task.agentConfig.prompt,\n resources: task.agentConfig.resources,\n tools: taskTools,\n metadata: {\n ...taskMetadata,\n model,\n reasoningEffort,\n scheduledTaskId: task.id,\n 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 scheduledTaskRunId: run.id,\n },\n model,\n sandboxBackend,\n variableSetId: task.variableSetId ?? null,\n rigId: frozenRigId,\n rigVersionId: frozenRigVersionId,\n personalConnectionDelegations: taskPersonalConnectionDelegations,\n maxNestedAgentDepthOverride: task.agentConfig.maxNestedAgentDepth ?? null,\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 });\n } catch (error) {\n if (error instanceof SessionSpawnDeniedDbError) {\n throw new Error(`${error.denial.code}: denial=${error.denial.id}`, { cause: error });\n }\n throw error;\n }\n const goal = goalSpec\n ? await createSessionGoal(db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n text: goalSpec.text,\n successCriteria: goalSpec.successCriteria ?? null,\n maxAutoContinuations: goalSpec.maxAutoContinuations ?? null,\n createdBy: \"scheduled_task\",\n })\n : null;\n const workflowId = workflowIdForSession(session.id);\n await setTemporalWorkflowId(db, task.workspaceId, session.id, workflowId);\n if (task.runMode === \"reusable_session\") {\n await updateScheduledTask(db, task.workspaceId, task.id, {\n reusableSessionId: session.id,\n });\n }\n await appendAndPublishEvents(db, bus, task.workspaceId, session.id, [\n {\n type: \"session.created\",\n payload: {\n status: session.status,\n createdBy: session.createdBy,\n scheduledTaskId: task.id,\n scheduledTaskRunId: 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 },\n ...(goal\n ? [\n {\n type: \"goal.set\" as const,\n payload: {\n goalId: goal.id,\n text: goal.text,\n ...(goal.successCriteria ? { successCriteria: goal.successCriteria } : {}),\n version: goal.version,\n actor: \"scheduled_task\",\n replaced: false,\n },\n },\n ]\n : []),\n { type: \"session.status.changed\", payload: { status: session.status } },\n ]);\n const scheduledUpdate = await addSessionSystemUpdateWithSourceMutation(\n db,\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-wake:${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: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },\n personalConnectionDelegations: taskPersonalConnectionDelegations,\n },\n async (tx, wakeEventId) => {\n if (!wakeEventId) throw new Error(\"Scheduled delivery has no wake event\");\n await settleScheduledTaskRunInTransaction(tx, {\n workspaceId: task.workspaceId,\n runId: run.id,\n sessionId: session.id,\n triggerEventId: wakeEventId,\n status: \"dispatched\",\n });\n },\n );\n if (scheduledUpdate.reason === \"session_cancelled\") {\n throw new Error(\"new scheduled session was cancelled during dispatch\");\n }\n if (scheduledUpdate.added && scheduledUpdate.events.length > 0) {\n await publishDurableSessionEvents(\n bus,\n task.workspaceId,\n session.id,\n scheduledUpdate.events,\n );\n }\n result = {\n action: \"start\",\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 const session = await requireSession(db, task.workspaceId, task.reusableSessionId);\n // A user-cancelled (terminal) reusable session must not be revived and\n // re-billed on the next fire. Early check avoids the pre-lock goal\n // upsert side-effect; the locked-callback check below is the\n // authoritative atomic guard. Mirrors 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 if ((session.variableSetId ?? null) !== (task.variableSetId ?? null)) {\n throw new Error(\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 Error(\n \"scheduled task OpenGeni Slack bot binding does not match its reusable session\",\n );\n }\n // A recurring \"maintain X\" task re-establishes its objective on every\n // fire: replace the goal text, reactivate it, and reset the counters.\n const reusableGoal =\n goalSpec && run.status === \"queued\"\n ? await upsertSessionGoal(db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n text: goalSpec.text,\n successCriteria: goalSpec.successCriteria ?? null,\n maxAutoContinuations: goalSpec.maxAutoContinuations ?? null,\n createdBy: \"scheduled_task\",\n })\n : null;\n if (reusableGoal) {\n const goalEvents = await appendSessionEventsWithLockedSessionUpdate(\n db,\n task.workspaceId,\n session.id,\n (locked) => {\n assertReusableSessionRevivable(locked.status);\n return {\n events: [\n {\n type: \"goal.set\" as const,\n payload: {\n goalId: reusableGoal.goal.id,\n text: reusableGoal.goal.text,\n ...(reusableGoal.goal.successCriteria\n ? { successCriteria: reusableGoal.goal.successCriteria }\n : {}),\n version: reusableGoal.goal.version,\n actor: \"scheduled_task\",\n replaced: reusableGoal.replaced,\n },\n },\n ],\n };\n },\n );\n await publishDurableSessionEvents(bus, task.workspaceId, session.id, goalEvents);\n }\n const bundled = await addSessionSystemUpdateWithSourceMutation(\n db,\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-wake:${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: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },\n personalConnectionDelegations: taskPersonalConnectionDelegations,\n },\n async (tx, wakeEventId) => {\n if (!wakeEventId) throw new Error(\"Scheduled delivery has no wake event\");\n await settleScheduledTaskRunInTransaction(tx, {\n workspaceId: task.workspaceId,\n runId: run.id,\n sessionId: session.id,\n triggerEventId: wakeEventId,\n status: \"dispatched\",\n });\n },\n );\n if (bundled.reason === \"session_cancelled\") {\n throw new Error(`scheduled wake was not added: ${bundled.reason}`);\n }\n if (bundled.added && bundled.events.length > 0) {\n await publishDurableSessionEvents(bus, task.workspaceId, session.id, bundled.events);\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 await markScheduledTaskRunFailedIfQueued(\n db,\n task.workspaceId,\n run.id,\n error instanceof Error ? error.message : String(error),\n ).catch(() => undefined);\n throw error;\n }\n await recordUsageEvent(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: run.id,\n sessionId: result.sessionId,\n initiator: input.initiator ?? { kind: \"service\", subjectId: \"scheduler\" },\n initiatorContext: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },\n origin: \"scheduled_task\",\n idempotencyKey:\n input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`,\n });\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\nasync function scheduledRunAdmissionDenial(\n settings: Settings,\n db: ActivityServices[\"db\"],\n accountId: string,\n workspaceId: string,\n requestedAgentRuns: number,\n isCodexRun: boolean,\n): Promise<\"insufficient_credits\" | \"monthly_model_cost_limit\" | \"monthly_agent_run_limit\" | null> {\n // Codex-billed runs are paid by the user's ChatGPT/Codex plan: skip the\n // credit-balance gate and the monthly model-cost cap. The agent-run COUNT cap\n // below is a volume quota (not a credit/cost gate) and is intentionally kept.\n if (\n !isCodexRun &&\n (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")\n ) {\n const balance = await getBillingBalance(db, accountId);\n if (balance.balanceMicros <= 0) {\n return \"insufficient_credits\";\n }\n }\n if (settings.usageLimitsMode === \"static\" || settings.usageLimitsMode === \"managed\") {\n const limits = configuredStaticUsageLimits(settings);\n if (!isCodexRun && limits.maxMonthlyCostMicrosPerAccount) {\n const used = await sumUsageQuantity(db, {\n accountId,\n eventType: \"model.cost\",\n since: startOfUtcMonth(),\n });\n if (used >= limits.maxMonthlyCostMicrosPerAccount) {\n return \"monthly_model_cost_limit\";\n }\n }\n if (limits.maxMonthlyAgentRunsPerWorkspace) {\n const used = await sumUsageQuantity(db, {\n workspaceId,\n eventType: \"agent_run.created\",\n since: startOfUtcMonth(),\n });\n if (used + requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {\n return \"monthly_agent_run_limit\";\n }\n }\n }\n return null;\n}\n\nfunction startOfUtcMonth(): Date {\n const now = new Date();\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));\n}\n","import {\n settleSessionAttemptInterruptions,\n applySessionTurnSettlement,\n requestSessionTurnRecovery,\n recoverSessionDispatch,\n reconcileSessionAttemptQuiescence,\n peekSessionWork as peekSessionWorkDb,\n countQueuedTurns,\n getSessionAttemptActivityRef,\n getSessionEvent,\n getSessionTurnForAttempt,\n expireSessionHumanInputRequest,\n markSessionAttemptQuiesced,\n requireSession,\n settleSessionIdleWithParentOutbox,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport { deliverFailedChildTurnToParent, notifyParentOfChildIdle } from \"./parent-wake\";\nimport { recordTurnsQueuedGauge } from \"../observability-metrics\";\nimport type {\n ActivityServices,\n ExpireSessionHumanInputInput,\n ExpireSessionHumanInputResult,\n PeekSessionWorkInput,\n FailSessionAttemptInput,\n SettleSessionInterruptionsInput,\n MarkSessionIdleInput,\n PersistSessionAttemptQuiescenceInput,\n ReconcileSessionAttemptQuiescenceInput,\n ReconcileSessionAttemptQuiescenceResult,\n RecoverDispatchInput,\n RecoverDispatchResult,\n RecoverEscapedMcpTimeoutInput,\n RecoverEscapedMcpTimeoutResult,\n} from \"./types\";\n\nexport type SessionStateActivityOverrides = Partial<{\n settleSessionAttemptInterruptions: typeof settleSessionAttemptInterruptions;\n applySessionTurnSettlement: typeof applySessionTurnSettlement;\n requestSessionTurnRecovery: typeof requestSessionTurnRecovery;\n recoverSessionDispatch: typeof recoverSessionDispatch;\n reconcileSessionAttemptQuiescence: typeof reconcileSessionAttemptQuiescence;\n peekSessionWork: typeof peekSessionWorkDb;\n countQueuedTurns: typeof countQueuedTurns;\n getSessionAttemptActivityRef: typeof getSessionAttemptActivityRef;\n getSessionEvent: typeof getSessionEvent;\n getSessionTurnForAttempt: typeof getSessionTurnForAttempt;\n expireSessionHumanInputRequest: typeof expireSessionHumanInputRequest;\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}>;\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<ActivityServices>,\n overrides: SessionStateActivityOverrides = {},\n) {\n const settleSessionAttemptInterruptionsFn =\n overrides.settleSessionAttemptInterruptions ?? settleSessionAttemptInterruptions;\n const applySessionTurnSettlementFn =\n overrides.applySessionTurnSettlement ?? applySessionTurnSettlement;\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 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 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\n async function failSessionAttempt(input: FailSessionAttemptInput): Promise<void> {\n const { db, bus, settings, observability, wakeSessionWorkflow } = await services();\n const session = await requireSessionFn(db, input.workspaceId, input.sessionId);\n if (session.status === \"failed\") {\n return;\n }\n const turn = await getSessionTurnForAttemptFn(\n db,\n input.workspaceId,\n input.sessionId,\n input.attemptId,\n );\n if (!turn) return;\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;\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 }\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 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 ) {\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 detail: {\n code: \"mcp_transport_timeout\",\n retryable: true,\n continueDelayMs: 60_000,\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 } = await services();\n const peek = await peekSessionWorkFn(db, input.workspaceId, input.sessionId);\n await refreshQueuedTurnsGauge(db, observability, countQueuedTurnsFn, recordTurnsQueuedGaugeFn);\n return peek;\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 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\") {\n return;\n }\n // The workflow reaches markSessionIdle exactly when it has decided to stop\n // for now (no queued turn, no goal continuation): the terminal-for-now\n // point for a spawned worker, whatever the cause (goal completed, agent or\n // system paused goal, goalless work finished, idle control settlement). Wake\n // the parent here, deduped per idle episode so the manager is nudged once.\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 expireSessionHumanInput,\n markSessionIdle,\n };\n}\n\nasync function refreshQueuedTurnsGauge(\n db: ActivityServices[\"db\"],\n observability: ActivityServices[\"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 type { ActivityServices } from \"./types\";\nimport { reconcilePendingSessionWorkflowWakes } from \"./parent-wake\";\n\nconst BATCH_SIZE = 1_000;\nconst MAX_DELIVERIES_PER_ACTIVITY = 10_000;\n\nexport type DispatchSessionWorkflowWakesResult = {\n claimed: number;\n delivered: number;\n failed: number;\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<ActivityServices>) {\n return {\n async dispatchSessionWorkflowWakes(): Promise<DispatchSessionWorkflowWakesResult> {\n const service = await services();\n let claimed = 0;\n let delivered = 0;\n let failed = 0;\n for (;;) {\n const remaining = MAX_DELIVERIES_PER_ACTIVITY - claimed;\n if (remaining <= 0) {\n return { claimed, delivered, failed, exhaustedBatchLimit: true };\n }\n const batch = await reconcilePendingSessionWorkflowWakes(\n service,\n Math.min(BATCH_SIZE, remaining),\n );\n claimed += batch.claimed;\n delivered += batch.delivered;\n failed += batch.failed;\n if (batch.claimed < Math.min(BATCH_SIZE, remaining)) {\n return { claimed, delivered, failed, exhaustedBatchLimit: false };\n }\n }\n },\n };\n}\n","import type { AccessGrant, Rig, RigChange, RigVersion } from \"@opengeni/contracts\";\nimport { sandboxArchiveCaptureTimeoutMs } from \"@opengeni/config\";\nimport {\n recordRigAuditEvent,\n classifyRigVerificationOutcome,\n promoteSetupAppendChange,\n} from \"@opengeni/core\";\nimport {\n acquireLease,\n beginRigChangeVerificationAttempt,\n commitWarmingToWarm,\n failWarmingToCold,\n getRig,\n getRigChange,\n getRigVersionById,\n markWarmLeaseInstanceLost,\n recordWarmingSandboxCreated,\n releaseLeaseHolder,\n sanitizeEventPayload,\n sanitizeEventString,\n sanitizeMemoryText,\n touchLeaseHolder,\n updateRigChangeStatus,\n type Database,\n} from \"@opengeni/db\";\nimport {\n createTurnToolCancellationController,\n establishSandboxSessionFromEnvelope,\n runRigSetupHook,\n sandboxCommandExitCode,\n sandboxCommandOutput,\n serializeEstablishedSandboxEnvelope,\n tagModalSandbox,\n type EstablishedSandboxSession,\n type SandboxLifecycleCommandRunner,\n type TurnSandboxCommandSession,\n} from \"@opengeni/runtime\";\nimport type { Context } from \"@temporalio/activity\";\nimport type { ActivityServices } from \"./types\";\nimport { settingsWithRigImage } from \"./packs\";\nimport { currentActivityContext } from \"./streaming\";\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\nconst OUTPUT_TAIL_LIMIT = 64 * 1024;\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 \"Rig 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 `Rig 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(temporalSignal?.reason ?? new Error(\"Rig verification cancelled\"));\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(\"Rig 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 tail(value: string, limit = OUTPUT_TAIL_LIMIT): string {\n return value.length > limit ? value.slice(-limit) : value;\n}\n\nfunction scrubVerificationOutput(value: string): string {\n return sanitizeMemoryText(sanitizeEventString(value)).text;\n}\n\nfunction scrubVerificationPayload<T>(value: T): T {\n return sanitizeEventPayload(value);\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) {\n return true;\n }\n const client = established.client as { delete?: (state: unknown) => Promise<unknown> };\n if (typeof client.delete === \"function\" && established.sessionState !== undefined) {\n try {\n await client.delete(established.sessionState);\n return true;\n } catch {\n return false;\n }\n }\n const session = established.session as {\n terminate?: () => Promise<unknown>;\n kill?: () => Promise<unknown>;\n close?: () => Promise<unknown>;\n closed?: boolean;\n };\n try {\n if (session.terminate) {\n await session.terminate();\n } else if (session.kill) {\n await session.kill();\n } else if (session.close && !session.closed) {\n await session.close();\n } else {\n return false;\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};\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(`Rig verification requires a new clean sandbox, but lease ${sandboxGroupId} was ${role}`);\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: ActivityServices[\"settings\"];\n db: Database;\n observability: ActivityServices[\"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(\"rig 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(\"rig 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: input.settings.modalImageRef ?? input.settings.dockerImage,\n rigVersionId: input.rigVersionId,\n leaseTtlMs: RIG_VERIFICATION_OWNER_TTL_MS,\n warmingLeaseTtlMs: RIG_VERIFICATION_OWNER_TTL_MS,\n captureWaitMs: sandboxArchiveCaptureTimeoutMs(input.settings),\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(\"rig verifier: Modal ownership tag failed\", {\n holderId,\n instanceId: created.instanceId,\n error: error instanceof Error ? error.message : String(error),\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 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, { signal, commandRunner });\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: scrubVerificationOutput(tail(sandboxCommandOutput(result))),\n };\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;\n }\n const payload = change.payload as {\n image?: unknown;\n setupScript?: unknown;\n checks?: unknown;\n credentialHooks?: unknown;\n defaultVariableSetIds?: unknown;\n changelog?: unknown;\n };\n return {\n ...baseVersion,\n image: payload.image === undefined ? baseVersion.image : (payload.image as string | 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 };\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(`Rig change not found: ${changeId}`);\n }\n const rig = await getRig(db, workspaceId, change.rigId);\n if (!rig) {\n throw new Error(`Rig not found for change: ${change.rigId}`);\n }\n if (!change.baseVersionId) {\n throw new Error(`Rig 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 rig 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(`Rig version not found: ${versionId}`);\n }\n const rig = await getRig(db, workspaceId, version.rigId);\n if (!rig) {\n throw new Error(`Rig 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<ActivityServices>) {\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 runSettings = settingsWithRigImage(settings, candidateVersion.image);\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 },\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: scrubVerificationPayload(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 checkResults = [];\n for (const check of candidateVersion.checks) {\n const result = await runCommand(\n established.session as TurnSandboxCommandSession,\n check.command,\n settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n );\n checkResults.push({\n name: check.name,\n command: scrubVerificationOutput(check.command),\n ...result,\n });\n }\n verification.checkResults = checkResults;\n const passed = checkResults.every((result) => result.exitCode === 0);\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: scrubVerificationPayload(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: scrubVerificationPayload(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 = scrubVerificationOutput(\n error instanceof Error ? error.message : String(error),\n );\n const updated = await updateRigChangeStatus(db, input.workspaceId, change.id, {\n status: \"failed\",\n verification: scrubVerificationPayload(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 = settingsWithRigImage(settings, version.image);\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 },\n });\n }\n const checkResults = [];\n for (const check of version.checks) {\n checkResults.push({\n name: check.name,\n command: scrubVerificationOutput(check.command),\n ...(await runCommand(\n established.session as TurnSandboxCommandSession,\n check.command,\n settings.rigSetupTimeoutMs,\n runContext.commandRunner,\n )),\n });\n }\n const passed = checkResults.every((result) => result.exitCode === 0);\n await recordRigAuditEvent(db, {\n grant,\n action: passed ? \"rig.verification.passed\" : \"rig.verification.failed\",\n rigId: rig.id,\n metadata: scrubVerificationPayload({\n versionId: version.id,\n startedAt,\n finishedAt: new Date().toISOString(),\n passed,\n checkResults,\n }),\n });\n return { versionId: version.id, passed, checkResults };\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 = tail(\n scrubVerificationOutput(error instanceof Error ? error.message : String(error)),\n 4096,\n );\n await recordRigAuditEvent(db, {\n grant,\n action: \"rig.verification.failed\",\n rigId: rig.id,\n metadata: scrubVerificationPayload({\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 { ActivityCancellationType, proxyActivities } from \"@temporalio/workflow\";\nimport type * as activities from \"../activities\";\n\ntype WorkflowControlActivities = Pick<\n typeof activities,\n | \"enqueueGoalRetryWake\"\n | \"expireSessionHumanInput\"\n | \"failSessionAttempt\"\n | \"getCodexCapacityWait\"\n | \"markSessionIdle\"\n | \"peekSessionWork\"\n | \"persistSessionAttemptQuiescence\"\n | \"reconcileSessionAttemptQuiescence\"\n | \"reconcileCodexCapacityWait\"\n | \"recoverDispatch\"\n | \"recoverEscapedMcpTimeout\"\n | \"settleSessionInterruptions\"\n>;\n\n/**\n * Session/schedule workflow control activities are bounded, idempotent database\n * and provider-metadata operations. They must not inherit the agent turn's\n * 30-day attempt: Temporal cannot otherwise detect that the pod which accepted\n * a non-heartbeating control activity disappeared, leaving the workflow pinned\n * to a dead worker for the full 30 days. A bounded attempt plus an unbounded\n * Temporal retry keeps the durable workflow alive across rollout, node loss, or\n * transient database/network failure; retries re-run on a healthy control pod.\n */\nexport const activity = proxyActivities<WorkflowControlActivities>({\n startToCloseTimeout: \"2 minutes\",\n retry: {\n initialInterval: \"1 second\",\n backoffCoefficient: 2,\n maximumInterval: \"30 seconds\",\n },\n});\n\n/** One schedule occurrence is bounded. Transient control-plane failures get a\n * short retry window, but a revoked binding or other permanent task error must\n * not leave a Temporal activity retrying forever; the next scheduled occurrence\n * is an independent workflow and will re-evaluate current state. */\nexport const scheduledTaskActivity = proxyActivities<\n Pick<typeof activities, \"dispatchScheduledTaskRun\">\n>({\n startToCloseTimeout: \"2 minutes\",\n retry: {\n initialInterval: \"1 second\",\n backoffCoefficient: 2,\n maximumInterval: \"30 seconds\",\n maximumAttempts: 5,\n },\n});\n\n/** Goal continuation evaluates a durable Postgres obligation at an idle\n * boundary. A transient failure gets a short retry window, then records an\n * explicit delayed outbox wake instead of relying on an unrelated mutation or\n * keeping workflow history alive with polling. */\nexport const goalActivity = proxyActivities<Pick<typeof activities, \"maybeContinueGoal\">>({\n startToCloseTimeout: \"30 seconds\",\n retry: {\n initialInterval: \"1 second\",\n backoffCoefficient: 2,\n maximumInterval: \"5 seconds\",\n maximumAttempts: 3,\n },\n});\n\nexport function turnTaskQueue(baseTaskQueue: string): string {\n return `${baseTaskQueue}-turns`;\n}\n\nexport function turnActivityForTaskQueue(baseTaskQueue: string, receiptGatedCancellation = true) {\n return proxyActivities<Pick<typeof activities, \"runAgentTurn\">>({\n taskQueue: turnTaskQueue(baseTaskQueue),\n // Agent segments legitimately run for days. A started turn heartbeats;\n // queued activities remain queued truthfully until a capped turn worker\n // accepts them and performs the atomic claim.\n startToCloseTimeout: \"30 days\",\n heartbeatTimeout: \"2 minutes\",\n // Pause/Steer first closes the exact attempt in Postgres, then asks\n // Temporal to deliver cancellation. The workflow must not wait for the\n // Temporal activity promise: a provider cleanup promise can outlive the\n // fenced activity body, and Temporal terminalization is not proof that\n // sandbox tools or processes are physically quiescent. The activity owns\n // that proof and writes an exact receipt after its hard tool fence; the\n // receipt transaction wakes the workflow to admit a replacement.\n cancellationType: receiptGatedCancellation\n ? ActivityCancellationType.TRY_CANCEL\n : ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,\n retry: { maximumAttempts: 1 },\n });\n}\n\nexport const documentActivity = proxyActivities<Pick<typeof activities, \"indexDocument\">>({\n startToCloseTimeout: \"30 minutes\",\n retry: { maximumAttempts: 1 },\n});\n\nexport function workflowFailureMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n","import type { Settings } from \"@opengeni/config\";\nimport {\n assertRuntimeDatabasePosture,\n dbSql,\n type Database,\n type RuntimeDatabasePostureOptions,\n} from \"@opengeni/db\";\nimport type { EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\n\nexport type ReadinessCheckName = \"db\" | \"nats\" | \"temporal\";\nexport type ReadinessChecks = Record<ReadinessCheckName, () => Promise<void> | void>;\n\nexport type ReadinessResult = {\n ok: boolean;\n state?: WorkerLifecycleState;\n checks: Record<ReadinessCheckName, { ok: boolean; error?: string }>;\n};\n\nexport type WorkerLifecycleState = \"starting\" | \"ready\" | \"draining\" | \"stopped\" | \"failed\";\n\nexport type WorkerHttpLifecycle = {\n role: \"control\" | \"turn\";\n state: () => WorkerLifecycleState;\n};\n\nexport type WorkerHttpServerInput = {\n settings: Settings;\n observability: Observability;\n checks: ReadinessChecks;\n timeoutMs?: number;\n lifecycle?: WorkerHttpLifecycle;\n};\n\nexport function createWorkerHttpHandler(\n input: WorkerHttpServerInput,\n): (request: Request) => Promise<Response> {\n const { settings, observability, checks, lifecycle } = input;\n const timeoutMs = input.timeoutMs ?? 2_000;\n return async (request) => {\n const url = new URL(request.url);\n if (request.method !== \"GET\") {\n return Response.json({ error: \"method_not_allowed\" }, { status: 405 });\n }\n if (url.pathname === \"/healthz\") {\n const state = lifecycle?.state();\n const ok = state !== \"failed\" && state !== \"stopped\";\n return Response.json(\n {\n service: settings.serviceName,\n environment: settings.environment,\n deploymentRevision: settings.deploymentRevision,\n ...(lifecycle ? { role: lifecycle.role, state } : {}),\n ok,\n },\n { status: ok ? 200 : 503 },\n );\n }\n if (url.pathname === \"/metrics\") {\n return new Response(await observability.prometheusMetrics(), {\n status: 200,\n headers: { \"content-type\": \"text/plain; version=0.0.4; charset=utf-8\" },\n });\n }\n if (url.pathname === \"/readyz\") {\n const state = lifecycle?.state();\n const result =\n state && state !== \"ready\"\n ? {\n ok: false,\n state,\n checks: Object.fromEntries(\n (Object.keys(checks) as ReadinessCheckName[]).map((name) => [\n name,\n { ok: false, error: `worker is ${state}` },\n ]),\n ) as ReadinessResult[\"checks\"],\n }\n : { ...(await runReadinessChecks(checks, timeoutMs)), ...(state ? { state } : {}) };\n return Response.json(result, { status: result.ok ? 200 : 503 });\n }\n return Response.json({ error: \"not_found\" }, { status: 404 });\n };\n}\n\nexport function startWorkerHttpServer(input: WorkerHttpServerInput): ReturnType<typeof Bun.serve> {\n return Bun.serve({\n hostname: \"0.0.0.0\",\n port: input.settings.workerHttpPort,\n fetch: createWorkerHttpHandler(input),\n });\n}\n\nexport async function runReadinessChecks(\n checks: ReadinessChecks,\n timeoutMs = 2_000,\n): Promise<ReadinessResult> {\n const entries = await Promise.all(\n (Object.entries(checks) as Array<[ReadinessCheckName, () => Promise<void> | void]>).map(\n async ([name, check]) => {\n try {\n await withTimeout(Promise.resolve().then(check), timeoutMs);\n return [name, { ok: true }] as const;\n } catch (error) {\n return [\n name,\n { ok: false, error: error instanceof Error ? error.message : String(error) },\n ] as const;\n }\n },\n ),\n );\n const result = Object.fromEntries(entries) as ReadinessResult[\"checks\"];\n return {\n ok: Object.values(result).every((check) => check.ok),\n checks: result,\n };\n}\n\nexport function dbReadyCheck(\n db: Database,\n posture?: RuntimeDatabasePostureOptions,\n): () => Promise<void> {\n return async () => {\n if (posture) {\n await assertRuntimeDatabasePosture(db, posture);\n return;\n }\n await db.execute(dbSql`select 1`);\n };\n}\n\nexport function natsReadyCheck(bus: EventBus): () => void {\n return () => {\n if (bus.isConnected && !bus.isConnected()) {\n throw new Error(\"NATS is not connected\");\n }\n };\n}\n\nexport function temporalReadyCheck(\n connection: Pick<\n import(\"@temporalio/worker\").NativeConnection,\n \"workflowService\" | \"withDeadline\"\n >,\n): () => Promise<void> {\n return async () => {\n await connection.withDeadline(Date.now() + 2_000, () =>\n connection.workflowService.getSystemInfo({}),\n );\n };\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`readiness check timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n }),\n ]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { WorkerOptions } from \"@temporalio/worker\";\n\nexport type TurnWorkerConcurrencySettings = Pick<\n Settings,\n | \"turnWorkerConcurrencyMode\"\n | \"turnWorkerMaxConcurrentTurns\"\n | \"turnWorkerTargetCpuUsage\"\n | \"turnWorkerTargetMemoryUsage\"\n>;\n\nexport type TurnWorkerConcurrencyOptions = Pick<\n WorkerOptions,\n \"maxConcurrentActivityTaskExecutions\" | \"tuner\"\n>;\n\n/**\n * Ordinary multi-worker deployments keep a fixed per-process ceiling so HPA or\n * an operator owns horizontal capacity. The single-machine profile selects the\n * resource tuner instead: Temporal admits activity slots while whole-system CPU\n * and memory remain below the configured targets, then stops polling more work.\n */\nexport function turnWorkerConcurrencyOptions(\n settings: TurnWorkerConcurrencySettings,\n): TurnWorkerConcurrencyOptions {\n if (settings.turnWorkerConcurrencyMode === \"fixed\") {\n return {\n maxConcurrentActivityTaskExecutions: settings.turnWorkerMaxConcurrentTurns,\n };\n }\n\n return {\n tuner: {\n tunerOptions: {\n targetCpuUsage: settings.turnWorkerTargetCpuUsage,\n targetMemoryUsage: settings.turnWorkerTargetMemoryUsage,\n },\n activityTaskSlotOptions: {\n minimumSlots: 1,\n maximumSlots: settings.turnWorkerMaxConcurrentTurns,\n rampThrottle: \"50ms\",\n },\n },\n };\n}\n\nexport function turnWorkerConcurrencyLogFields(settings: TurnWorkerConcurrencySettings): {\n concurrencyMode: \"fixed\" | \"resource-based\";\n maxConcurrentTurns: number;\n targetCpuUsage: number | null;\n targetMemoryUsage: number | null;\n} {\n const resourceBased = settings.turnWorkerConcurrencyMode === \"resource-based\";\n return {\n concurrencyMode: settings.turnWorkerConcurrencyMode,\n maxConcurrentTurns: settings.turnWorkerMaxConcurrentTurns,\n targetCpuUsage: resourceBased ? settings.turnWorkerTargetCpuUsage : null,\n targetMemoryUsage: resourceBased ? settings.turnWorkerTargetMemoryUsage : null,\n };\n}\n\nexport const CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES = 32;\nexport const CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS = 40;\n","import type { Observability } from \"@opengeni/observability\";\nimport type { WorkerLifecycleState } from \"./http\";\n\nexport async function constructWithOwnedConnection<Connection, Result>(\n connect: () => Promise<Connection>,\n construct: (connection: Connection) => Promise<Result>,\n close: (connection: Connection) => Promise<void>,\n): Promise<Result> {\n const connection = await connect();\n try {\n return await construct(connection);\n } catch (error) {\n await close(connection).catch(() => undefined);\n throw error;\n }\n}\n\nexport type WorkerRunTarget = {\n run(): Promise<void>;\n shutdown(): void;\n};\n\nexport type WorkerServiceLifecycle = {\n state(): WorkerLifecycleState;\n run(): Promise<void>;\n drain(reason?: string): void;\n close(): Promise<void>;\n};\n\nexport function createWorkerServiceLifecycle(input: {\n role: \"control\" | \"turn\";\n worker: WorkerRunTarget;\n observability: Observability;\n closeOwnedResources: () => Promise<void>;\n onReady?: () => void;\n}): WorkerServiceLifecycle {\n let state: WorkerLifecycleState = \"starting\";\n let runPromise: Promise<void> | undefined;\n let resourcesClosed: Promise<void> | undefined;\n const closeOwnedResources = () => {\n resourcesClosed ??= input.closeOwnedResources();\n return resourcesClosed;\n };\n\n const lifecycle: WorkerServiceLifecycle = {\n state: () => state,\n run: () => {\n if (!runPromise && state === \"draining\") {\n runPromise = (async () => {\n state = \"stopped\";\n await closeOwnedResources();\n })();\n return runPromise;\n }\n if (!runPromise && (state === \"stopped\" || state === \"failed\")) {\n return Promise.reject(new Error(`cannot run a worker service that is ${state}`));\n }\n runPromise ??= (async () => {\n if (state === \"starting\") {\n state = \"ready\";\n }\n input.onReady?.();\n try {\n await input.worker.run();\n state = \"stopped\";\n } catch (error) {\n state = \"failed\";\n throw error;\n } finally {\n await closeOwnedResources();\n }\n })();\n return runPromise;\n },\n drain: (reason = \"host request\") => {\n if (state === \"draining\" || state === \"stopped\" || state === \"failed\") {\n return;\n }\n state = \"draining\";\n input.observability.info(\"OpenGeni worker draining (graceful shutdown)\", {\n role: input.role,\n reason,\n });\n try {\n input.worker.shutdown();\n } catch (error) {\n input.observability.warn(\"worker shutdown request failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n },\n close: async () => {\n lifecycle.drain(\"service close\");\n if (runPromise) {\n await runPromise.catch(() => undefined);\n } else {\n state = \"stopped\";\n await closeOwnedResources();\n }\n },\n };\n\n return lifecycle;\n}\n"],"mappings":";;;;;AAAA;AAAA,EACE,gBAAAA;AAAA,EACA,eAAAC;AAAA,EACA,+BAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE,gCAAAC;AAAA,EACA,YAAAC;AAAA,EACA;AAAA,OAGK;AACP,SAAS,sBAAAC,2BAAyC;AAClD;AAAA,EACE,uBAAAC;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA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IAC7B;AACA,UAAM,MAAM;AAAA,MACV;AAAA,MACA,MACEC;AAAA,QACE,SAAS;AAAA,QACT,mBACI,EAAE,MAAM,iBAAiB,MAAM,MAAM,iBAAiB,SAAS,IAC/D;AAAA,QACJ,EAAE,QAAQ,yBAAyB,aAAa,EAAE;AAAA,MACpD;AAAA,MACF,EAAE,GAAG,cAAc,QAAQ;AAAA,IAC7B;AACA,UAAM,kBAAkB;AAAA,MACtB;AAAA,MACA;AAAA,MACA;AAAA,MACA,sBAAsB;AAAA,QACpB;AAAA,QACA,IAAI,SAAS;AAAA,QACb;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,UAAE;AACA,UAAM,QAAQ,WAAW,CAAC,KAAK,MAAM,GAAG,SAAS,MAAM,CAAC,CAAC;AAAA,EAC3D;AACF;AAEA,IAAI,YAAY,MAAM;AACpB,QAAM,YAAY;AACpB;","names":["dbSearchPath","getSettings","resolveNatsControlPlaneAuth","assertRuntimeDatabasePosture","createDb","createNatsEventBus","createObservability","ensureModalRegistryImage","createObjectStorage","advanceWorkspaceGeneration","verifyWorkspaceMutationSettlement","getBillingBalance","getSandbox","readActiveSandbox","requireFile","getSessionEvent","getSessionRootId","getSessionGoal","getHumanInputResumeForEvent","workspaceCodexSubscriptionActive","getWorkspaceModelPolicy","listCodexAccountStatuses","fetchCodexUsageForAccount","requireSession","getActiveSessionHistoryItems","sumUsageQuantity","readLease","SandboxLeaseRecoveryBlockedError","SandboxLeaseSupersededError","projectHistoryForProvider","sanitizeHistoryItemsForModel","summarizeForCompaction","REMOTE_COMPACTION_V2_IMPLEMENTATION","EmptyCompactionSummaryError","SUMMARY_BUFFER_TOKENS","WorkspaceArchiveIntegrityError","deleteRecordingArtifacts","stopRecordingOnBox","configuredStaticUsageLimits","sandboxArchiveCaptureTimeoutMs","CancelledFailure","chosen","getCodexCapacityWait","reconcileCodexCapacityWait","getActiveSessionHistoryItems","getActiveSessionHistoryItems","outcome","timer","timer","mergeToolRefs","reasoningEffortForMetadata","enqueueGoalRetryWake","maybeContinueGoal","getSessionGoal","redactSensitiveText","getSandboxSessionEnvelope","resumeEnvelope","sandboxArchiveCaptureTimeoutMs","markWarmLeaseInstanceLost","readLease","establishSandboxSessionFromEnvelope","isProviderSandboxNotFoundError","resolveModalCheckpointProviderBindingForSession","verifySandboxExecReadiness","readLease","establishSandboxSessionFromEnvelope","verifySandboxExecReadiness","isProviderSandboxNotFoundError","markWarmLeaseInstanceLost","resolveModalCheckpointProviderBindingForSession","sandboxArchiveCaptureTimeoutMs","process","createHash","key","createHash","createHash","evaluateWorkspaceModelPolicy","resourceMountPath","createHash","randomUUID","createHash","CancelledFailure","sleep","EmptyCompactionSummaryError","sanitizeHistoryItemsForModel","readActiveSandbox","CancelledFailure","sleep","SandboxLeaseRecoveryBlockedError","WorkspaceArchiveIntegrityError","SandboxLeaseSupersededError","fetchCodexUsageForAccount","listCodexAccountStatuses","runAgentTurn","randomUUID","sandboxArchiveCaptureTimeoutMs","advanceWorkspaceGeneration","verifyWorkspaceMutationSettlement","stopRecordingOnBox","readLease","snapshotSession","snapshotTurnId","workspaceCodexSubscriptionActive","requireSession","getSessionEvent","getHumanInputResumeForEvent","deleteRecordingArtifacts","getSessionGoal","projectHistoryForProvider","getWorkspaceModelPolicy","evaluateWorkspaceModelPolicy","REMOTE_COMPACTION_V2_IMPLEMENTATION","summarizeForCompaction","SUMMARY_BUFFER_TOKENS","EmptyCompactionSummaryError","getSandbox","getSessionRootId","getActiveSessionHistoryItems","getBillingBalance","configuredStaticUsageLimits","sumUsageQuantity","startOfUtcMonth","requireFile","resourceMountPath","configuredStaticUsageLimits","getBillingBalance","recordUsageEvent","sumUsageQuantity","startOfUtcMonth","reapExpiredFileUploads","randomUUID","accrueWarmSeconds","adoptLegacyModalCheckpointArtifact","claimWorkspaceArchiveCapture","getBillingBalance","markSandboxCheckpointArtifactDeletePending","registerSandboxCheckpointArtifact","releaseWorkspaceArchiveCapture","readLease","retainedProcessSettlementIdentity","rlsContextForWorkspace","settleRetainedProcess","sandboxArchiveCaptureTimeoutMs","sandboxWarmRateMicrosPerSecond","captureVerifiedWorkspaceArchive","establishSandboxSessionFromEnvelope","isProviderSandboxNotFoundError","resolveModalCheckpointProviderBindingForSession","sandboxBackendForSdkBackendId","verifySandboxExecReadiness","reapSandboxLeases","adoptLegacyModalCheckpointArtifact","process","retainedProcessSettlementIdentity","readLease","settleRetainedProcess","isProviderSandboxNotFoundError","resolveModalCheckpointProviderBindingForSession","sandboxWarmRateMicrosPerSecond","accrueWarmSeconds","rlsContextForWorkspace","getBillingBalance","sandboxBackendForSdkBackendId","establishSandboxSessionFromEnvelope","verifySandboxExecReadiness","sandboxArchiveCaptureTimeoutMs","randomUUID","claimWorkspaceArchiveCapture","registerSandboxCheckpointArtifact","markSandboxCheckpointArtifactDeletePending","releaseWorkspaceArchiveCapture","captureVerifiedWorkspaceArchive","addSessionSystemUpdateWithSourceMutation","enqueueSessionWorkflowWakeIfRunnable","getBillingBalance","isCodexBilledTurn","recordUsageEvent","requireSession","sumUsageQuantity","publishDurableSessionEvents","configuredStaticUsageLimits","isCodexBilledTurn","recordUsageEvent","enqueueSessionWorkflowWakeIfRunnable","result","addSessionSystemUpdateWithSourceMutation","publishDurableSessionEvents","requireSession","getBillingBalance","configuredStaticUsageLimits","sumUsageQuantity","startOfUtcMonth","applySessionTurnSettlement","requestSessionTurnRecovery","countQueuedTurns","getSessionEvent","markSessionAttemptQuiesced","requireSession","publishDurableSessionEvents","applySessionTurnSettlement","requestSessionTurnRecovery","countQueuedTurns","getSessionEvent","requireSession","markSessionAttemptQuiesced","publishDurableSessionEvents","failSessionAttempt","settleSessionInterruptions","persistSessionAttemptQuiescence","recoverDispatch","recoverEscapedMcpTimeout","peekSessionWork","expireSessionHumanInput","markSessionIdle","sandboxArchiveCaptureTimeoutMs","acquireLease","commitWarmingToWarm","failWarmingToCold","getRig","markWarmLeaseInstanceLost","recordWarmingSandboxCreated","releaseLeaseHolder","touchLeaseHolder","establishSandboxSessionFromEnvelope","sandboxCommandExitCode","tagModalSandbox","acquireLease","establishSandboxSessionFromEnvelope","recordWarmingSandboxCreated","commitWarmingToWarm","touchLeaseHolder","releaseLeaseHolder","failWarmingToCold","markWarmLeaseInstanceLost","tagModalSandbox","sandboxArchiveCaptureTimeoutMs","resumeState","sandboxCommandExitCode","getRig","updated","createObjectStorage","reconcileSessionAttemptQuiescence","getSettings","createObservability","ensureModalRegistryImage","activity","dbSearchPath","createDb","resolveNatsControlPlaneAuth","assertRuntimeDatabasePosture","createNatsEventBus"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/workflows/activities.ts","../src/http.ts","../src/worker-service-lifecycle.ts","../src/memory-pressure-guard.ts"],"sourcesContent":["import {\n dbSearchPath,\n getSettings,\n resolveNatsControlPlaneAuth,\n retryStartupDependency,\n startupRetryOptions,\n temporalConnectionOptions,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n assertRuntimeDatabasePosture,\n createDb,\n markSessionWorkflowWakeDelivered,\n type Database,\n type RuntimeDatabasePostureOptions,\n} from \"@opengeni/db\";\nimport { createNatsEventBus, type EventBus } from \"@opengeni/events\";\nimport {\n createObservability,\n logStartupDependencyRetry,\n type Observability,\n} from \"@opengeni/observability\";\nimport {\n Connection,\n isGrpcServiceError,\n ScheduleAlreadyRunning,\n ScheduleOverlapPolicy,\n Client as TemporalClient,\n WorkflowExecutionAlreadyStartedError,\n} from \"@temporalio/client\";\nimport { NativeConnection, Worker, type WorkflowBundleOption } from \"@temporalio/worker\";\nimport { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport type { createControlActivities } from \"./activities-control\";\nimport type { createTurnActivities } from \"./activities-turn\";\nimport type { ActivityDependencies } from \"./activities/types\";\nimport type {\n InspectSessionAttemptActivity,\n SignalCodexCapacityWorkflow,\n SignalSessionAttemptQuiesced,\n StartSandboxReaperWorkflow,\n StartVideoGenerationWorkflow,\n WakeSessionWorkflowSignal,\n} from \"./activities/types\";\nimport { turnTaskQueue } from \"./workflows/activities\";\nimport {\n dbReadyCheck,\n natsReadyCheck,\n startWorkerHttpServer,\n temporalReadyCheck,\n type WorkerLifecycleState,\n} from \"./http\";\nimport {\n normalizeTurnTaskQueueStats,\n observabilityEventLogger,\n startTurnCapacityMonitor,\n type TurnTaskQueueStats,\n} from \"./observability-metrics\";\nimport {\n SESSION_WORKFLOW_WAKE_DISPATCHER_PERIOD_MS,\n SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID,\n SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_TYPE,\n TURN_ACTIVITY_CANCELLATION_HEARTBEAT_INTERVAL_MS,\n} from \"@opengeni/core\";\nimport {\n CONTROL_WORKER_MAX_CACHED_WORKFLOWS,\n CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES,\n CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS,\n createTurnWorkerConcurrencyPlan,\n turnWorkerConcurrencyLogFields,\n} from \"./concurrency\";\nimport {\n combineWorkerRunTargets,\n constructWithOwnedConnection,\n createWorkerServiceLifecycle,\n type WorkerServiceLifecycle,\n type WorkerRunTarget,\n} from \"./worker-service-lifecycle\";\nimport {\n createTurnWorkerMemoryPressureGuard,\n turnWorkerMemoryPressureGuardEnabled,\n type TurnWorkerMemoryPressureGuard,\n} from \"./memory-pressure-guard\";\nimport { assertSandboxReaperActivityTimeout } from \"./sandbox-reaper-timeout\";\nimport {\n SANDBOX_REAPER_V2_WORKFLOW_ID,\n sandboxLifecycleTaskQueue,\n} from \"./sandbox-reaper-contract\";\n\nexport {\n createHostExportPump,\n type HostExportDrainResult,\n type HostExportPump,\n type HostExportPumpOptions,\n type HostEventExport,\n type HostEventExportBatch,\n type HostEventSink,\n type HostUsageExport,\n type HostUsageExportBatch,\n type HostUsageSink,\n} from \"./host-export\";\n\n// The deterministic id of the ONE global reaper Schedule. A single id means\n// create() is idempotent across every worker in the pool: the first worker to\n// boot creates it, all others collide on this id (ScheduleAlreadyRunning) and\n// no-op — so the Schedule is registered EXACTLY ONCE per deployment regardless\n// of replica count.\nconst SANDBOX_REAPER_SCHEDULE_ID = \"opengeni-sandbox-lease-reaper\";\nexport const FILE_UPLOAD_REAPER_SCHEDULE_ID = \"opengeni-file-upload-reaper\";\nexport const FILE_UPLOAD_REAPER_PERIOD_MS = 15 * 60 * 1_000;\nexport type OpenGeniWorkerRole = \"control\" | \"turn\";\n\nexport type WorkerOptions = {\n role: OpenGeniWorkerRole;\n settings?: Settings;\n activities?: ReturnType<typeof createControlActivities> | ReturnType<typeof createTurnActivities>;\n activityDependencies?: ActivityDependencies;\n /** Override the release-coherent workflow artifact. Most hosts should omit this. */\n workflowBundle?: WorkflowBundleOption;\n};\n\ntype TemporalActivityLease = {\n lastHeartbeatTime?: { seconds?: unknown; nanos?: number | null } | null;\n lastStartedTime?: { seconds?: unknown; nanos?: number | null } | null;\n activityOptions?: {\n heartbeatTimeout?: { seconds?: unknown; nanos?: number | null } | null;\n } | null;\n};\n\nfunction temporalTimeMs(\n value: { seconds?: unknown; nanos?: number | null } | null | undefined,\n): number | null {\n if (value?.seconds === undefined || value.seconds === null) return null;\n return Number(String(value.seconds)) * 1_000 + Math.floor((value.nanos ?? 0) / 1_000_000);\n}\n\nexport function temporalActivityLeaseSettled(\n pending: TemporalActivityLease | null | undefined,\n nowMs = Date.now(),\n): boolean {\n if (!pending) return true;\n const heartbeatAt =\n temporalTimeMs(pending.lastHeartbeatTime) ?? temporalTimeMs(pending.lastStartedTime);\n const heartbeatTimeoutMs = temporalTimeMs(pending.activityOptions?.heartbeatTimeout);\n return (\n heartbeatAt !== null && heartbeatTimeoutMs !== null && nowMs >= heartbeatAt + heartbeatTimeoutMs\n );\n}\n\n/** The exact Temporal workflow run is absent, so it cannot retain an activity. */\nexport function temporalWorkflowExecutionNotFound(error: unknown): boolean {\n // gRPC status code 5 is NOT_FOUND. The typed guard prevents unrelated\n // provider/HTTP errors carrying a numeric code from proving quiescence.\n return isGrpcServiceError(error) && error.code === 5;\n}\n\n/** Load exactly one role's activity graph. Exported for embedded hosts and the\n * process-RSS conformance benchmark; construction remains side-effect free\n * until an activity first resolves its injected services. */\nexport async function createDefaultWorkerActivities(\n role: OpenGeniWorkerRole,\n dependencies: ActivityDependencies = {},\n) {\n return role === \"control\"\n ? (await import(\"./activities-control\")).createControlActivities(dependencies)\n : (await import(\"./activities-turn\")).createTurnActivities(dependencies);\n}\n\ntype WorkerWorkflowDefinition =\n | { workflowBundle: WorkflowBundleOption }\n | { workflowsPath: string };\n\n/**\n * Resolve the deterministic workflow graph without asking installed hosts to\n * transpile or relocate package TypeScript. Monorepo source execution retains\n * the source path for the local development loop; published dist execution\n * fails closed unless the build-generated sibling artifact is present.\n */\nexport function resolveOpenGeniWorkflowDefinition(\n moduleUrl: string = import.meta.url,\n): WorkerWorkflowDefinition {\n const modulePath = fileURLToPath(moduleUrl).replaceAll(\"\\\\\", \"/\");\n if (modulePath.endsWith(\"/src/index.ts\")) {\n return { workflowsPath: fileURLToPath(new URL(\"./workflows.ts\", moduleUrl)) };\n }\n const codePath = fileURLToPath(new URL(\"./workflow-bundle.js\", moduleUrl));\n if (!existsSync(codePath)) {\n throw new Error(\n `OpenGeni workflow bundle is missing at ${codePath}; rebuild or reinstall @opengeni/worker-bundle`,\n );\n }\n return { workflowBundle: { codePath } };\n}\n\nexport function turnCancellationHeartbeatThrottleOptions() {\n return {\n maxHeartbeatThrottleInterval: TURN_ACTIVITY_CANCELLATION_HEARTBEAT_INTERVAL_MS,\n defaultHeartbeatThrottleInterval: TURN_ACTIVITY_CANCELLATION_HEARTBEAT_INTERVAL_MS,\n } as const;\n}\n\nexport async function createOpenGeniWorker(options: WorkerOptions): Promise<{\n worker: WorkerRunTarget;\n connection: NativeConnection;\n}> {\n const settings = options.settings ?? getSettings();\n if (options.role === \"control\") {\n // The exported lower-level factory is itself poll-capable. Validate here so\n // embedded hosts cannot bypass the reaper budget contract by omitting the\n // higher-level service and its Schedule-registration lifecycle.\n assertSandboxReaperActivityTimeout(settings);\n }\n const observability =\n options.activityDependencies?.observability ??\n createObservability(settings, { component: `worker-${options.role}` });\n if (options.role === \"turn\" && options.workflowBundle) {\n throw new Error(\"workflowBundle is valid only for the control worker role\");\n }\n // Pre-resolve a PRIVATE-registry sandbox image before any turn creates a box.\n // A provider-native OPENGENI_MODAL_IMAGE_ID intentionally bypasses this\n // registry path and is resolved by ModalImageSelector.fromId at create time.\n // Otherwise this is a no-op unless the registry secret + logical ref are both\n // set. Memoized in the provider, so it runs once per process.\n if (options.role === \"turn\") {\n const { ensureModalRegistryImage } = await import(\"@opengeni/runtime/sandbox\");\n await retryStartupDependency(\n \"Modal private-registry image\",\n () => ensureModalRegistryImage(settings),\n {\n ...startupRetryOptions(settings),\n onRetry: (event) => logStartupDependencyRetry(observability, event),\n },\n );\n }\n return constructWithOwnedConnection(\n () =>\n retryStartupDependency(\n \"Temporal\",\n () => NativeConnection.connect(temporalConnectionOptions(settings)),\n {\n ...startupRetryOptions(settings),\n onRetry: (event) => logStartupDependencyRetry(observability, event),\n },\n ),\n async (connection) => {\n const activityDependencies = {\n ...options.activityDependencies,\n settings,\n observability,\n };\n const activities =\n options.activities ??\n (await createDefaultWorkerActivities(options.role, activityDependencies));\n const turnConcurrency =\n options.role === \"turn\"\n ? createTurnWorkerConcurrencyPlan(settings, { observability })\n : null;\n const workflowDefinition =\n options.role === \"control\"\n ? options.workflowBundle\n ? { workflowBundle: options.workflowBundle }\n : resolveOpenGeniWorkflowDefinition()\n : {};\n const sharedWorkerOptions = {\n connection,\n namespace: settings.temporalNamespace,\n activities,\n // Cancellation is delivered through an activity heartbeat. Keep the SDK\n // throttle aligned with runAgentTurn's local heartbeat cadence so the\n // four-second control contract still has time for physical writer drain\n // and exact receipt-gated replacement admission.\n ...turnCancellationHeartbeatThrottleOptions(),\n // GRACEFUL DEPLOY SHUTDOWN (with the SIGTERM handler in startWorker):\n // after shutdown() stops polling, in-flight activities get this long to\n // finish naturally; the rest are then CANCELLED with WORKER_SHUTDOWN.\n shutdownGraceTime: \"5s\",\n // Hard ceiling inside the pod's termination grace period.\n shutdownForceTime: \"100s\",\n } as const;\n const worker = await Worker.create({\n ...sharedWorkerOptions,\n taskQueue:\n options.role === \"control\"\n ? settings.temporalTaskQueue\n : turnTaskQueue(settings.temporalTaskQueue),\n ...(options.role === \"control\"\n ? {\n ...workflowDefinition,\n reuseV8Context: true,\n workflowThreadPoolSize: 1,\n maxCachedWorkflows: CONTROL_WORKER_MAX_CACHED_WORKFLOWS,\n maxConcurrentWorkflowTaskExecutions: CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS,\n maxConcurrentActivityTaskExecutions: CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES,\n }\n : turnConcurrency!.options),\n });\n if (options.role !== \"control\") {\n turnConcurrency?.admission?.finalizeStartupBaseline();\n return { worker, connection };\n }\n\n try {\n const sandboxLifecycleWorker = await Worker.create({\n ...sharedWorkerOptions,\n ...workflowDefinition,\n taskQueue: sandboxLifecycleTaskQueue(settings.temporalTaskQueue),\n reuseV8Context: true,\n workflowThreadPoolSize: 1,\n maxCachedWorkflows: CONTROL_WORKER_MAX_CACHED_WORKFLOWS,\n maxConcurrentWorkflowTaskExecutions: CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS,\n maxConcurrentActivityTaskExecutions: CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES,\n });\n return {\n worker: combineWorkerRunTargets([worker, sandboxLifecycleWorker]),\n connection,\n };\n } catch (error) {\n try {\n worker.shutdown();\n } catch {\n // Preserve the lifecycle worker construction failure. The base poller\n // still received its shutdown request; a secondary synchronous\n // shutdown error must not replace the startup root cause.\n }\n throw error;\n }\n },\n (connection) => connection.close(),\n );\n}\n\n// A signalWithStart capability so a worker activity can wake a PARENT\n// session's workflow when a spawned worker completes (the parent may have\n// idled and let its run finish, so a plain signal would not start one).\n// Separate from the worker's NativeConnection: the @temporalio/client\n// Connection is what exposes workflow.signalWithStart.\nexport async function createWorkerWorkflowSignaler(\n settings: Settings,\n db: Database,\n): Promise<{\n wakeSessionWorkflow: WakeSessionWorkflowSignal;\n signalSessionAttemptQuiesced: SignalSessionAttemptQuiesced;\n inspectSessionAttemptActivity: InspectSessionAttemptActivity;\n signalCodexCapacityWorkflow: SignalCodexCapacityWorkflow;\n getTurnTaskQueueStats: () => Promise<TurnTaskQueueStats>;\n startSandboxReaperWorkflow: StartSandboxReaperWorkflow;\n startVideoGenerationWorkflow: StartVideoGenerationWorkflow;\n check: () => Promise<void>;\n close: () => Promise<void>;\n}> {\n const connection = await Connection.connect(temporalConnectionOptions(settings));\n const temporal = new TemporalClient({ connection, namespace: settings.temporalNamespace });\n return {\n wakeSessionWorkflow: async ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n interruptionRequested,\n }) => {\n if (interruptionRequested) {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"sessionControl\",\n signalArgs: [],\n });\n } else {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"queueChanged\",\n });\n }\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision,\n });\n },\n signalSessionAttemptQuiesced: async (proof) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId: proof.workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [\n {\n accountId: proof.accountId,\n workspaceId: proof.workspaceId,\n sessionId: proof.sessionId,\n },\n ],\n signal: \"sessionAttemptQuiesced\",\n signalArgs: [proof],\n });\n // No wake-outbox row exists yet: the direct receipt transaction failed.\n // The signalled workflow's DB-only control activity owns committing the\n // receipt and its exact wake revision atomically.\n },\n inspectSessionAttemptActivity: async ({ workflowId, workflowRunId, activityId }) => {\n let description;\n try {\n description = await connection.workflowService.describeWorkflowExecution({\n namespace: settings.temporalNamespace,\n execution: { workflowId, runId: workflowRunId },\n });\n } catch (error) {\n if (temporalWorkflowExecutionNotFound(error)) return \"settled\";\n throw error;\n }\n const pending = description.pendingActivities?.find(\n (activity) => activity.activityId === activityId,\n );\n return temporalActivityLeaseSettled(pending) ? \"settled\" : \"pending\";\n },\n signalCodexCapacityWorkflow: async ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"codexCapacityChanged\",\n signalArgs: [wakeRevision],\n });\n // A typed capacity signal cannot acknowledge the generic outbox row:\n // another producer may have advanced it with a Pause/Steer that requires\n // sessionControl. The global dispatcher owns that acknowledgement.\n },\n getTurnTaskQueueStats: async () => {\n const response = await connection.workflowService.describeTaskQueue({\n namespace: settings.temporalNamespace,\n taskQueue: { name: turnTaskQueue(settings.temporalTaskQueue) },\n // temporal.api.enums.v1.TASK_QUEUE_TYPE_ACTIVITY. Keep this request in\n // the supported DEFAULT mode; `stats.approximateBacklogCount` is the\n // server-documented scaling signal.\n taskQueueType: 2,\n reportStats: true,\n });\n return normalizeTurnTaskQueueStats(response.stats);\n },\n startSandboxReaperWorkflow: async () => {\n try {\n await temporal.workflow.start(\"sandboxReaperWorkflowV2\", {\n taskQueue: sandboxLifecycleTaskQueue(settings.temporalTaskQueue),\n workflowId: SANDBOX_REAPER_V2_WORKFLOW_ID,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [],\n });\n return \"started\";\n } catch (error) {\n if (error instanceof WorkflowExecutionAlreadyStartedError) {\n return \"already_running\";\n }\n throw error;\n }\n },\n startVideoGenerationWorkflow: async ({ accountId, workspaceId, operationId }) => {\n try {\n await temporal.workflow.start(\"videoGenerationWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId: `video-generation:${operationId}`,\n // Reject a concurrent or already-completed run, but allow the repair\n // sweep to restart this exact operation if the workflow itself failed.\n // Every provider/storage transition remains CAS/idempotency fenced in\n // Postgres, so recovery never creates a second logical operation.\n workflowIdReusePolicy: \"ALLOW_DUPLICATE_FAILED_ONLY\",\n args: [\n {\n accountId,\n workspaceId,\n operationId,\n baseTaskQueue: settings.temporalTaskQueue,\n },\n ],\n });\n return \"started\";\n } catch (error) {\n if (error instanceof WorkflowExecutionAlreadyStartedError) {\n return \"already_running\";\n }\n throw error;\n }\n },\n check: async () => {\n await connection.workflowService.getSystemInfo({});\n },\n close: async () => {\n await connection.close();\n },\n };\n}\n\n/**\n * Register the ONE global reaper Temporal Schedule (the sole liveness/GC/cost-stop\n * driver — P1.3 / OD-3) and durable system-update outbox repair cadence. With\n * sandbox ownership off the activity performs bounded DB outbox repair and\n * read-only observability projections; it never mutates or terminates sandbox leases.\n *\n * The Schedule permanently fires sandboxReaperWorkflow on the legacy/base queue\n * every settings.sandboxLeaseReaperPeriodMs (the SAME cadence the boot invariant\n * `reaperPeriod < viewerHolderTTL` and `reaperPeriod + idleGrace < providerLifetime`\n * validates in packages/config — wiring the schedule period to it). SKIP overlap means a slow\n * sweep never overlaps itself. Idempotent: a duplicate scheduleId across the\n * worker pool collides on ScheduleAlreadyRunning and reconciles the same\n * definition. New workers route onto the versioned lifecycle queue; old workers\n * can still run the legacy action during rollout or a full binary rollback.\n *\n * Returns a `close()` for the dedicated client connection (separate from the\n * worker's NativeConnection — the Schedule client is a @temporalio/client).\n */\nexport async function registerSandboxReaperSchedule(\n settings: Settings,\n observability: Observability,\n): Promise<{ registered: boolean; close: () => Promise<void> }> {\n assertSandboxReaperActivityTimeout(settings);\n const connection = await Connection.connect(temporalConnectionOptions(settings));\n const temporal = new TemporalClient({ connection, namespace: settings.temporalNamespace });\n const spec = { intervals: [{ every: settings.sandboxLeaseReaperPeriodMs }] };\n const action = {\n type: \"startWorkflow\" as const,\n workflowType: \"sandboxReaperWorkflow\",\n taskQueue: settings.temporalTaskQueue,\n args: [] as [],\n };\n const policies = {\n overlap: ScheduleOverlapPolicy.SKIP,\n catchupWindow: \"1m\",\n pauseOnFailure: false,\n } as const;\n try {\n await temporal.schedule.create({\n scheduleId: SANDBOX_REAPER_SCHEDULE_ID,\n // @every-style interval: fire once per reaper period. The boot invariant\n // guarantees reaperPeriod < viewerHolderTTL and\n // reaperPeriod + idleGrace < providerLifetime.\n spec,\n action,\n // The base workflow is a short router on new binaries; legacy binaries\n // still execute the pre-refactor composite under this same overlap fence.\n policies,\n });\n observability.info(\"Registered the global sandbox-lease reaper Schedule\", {\n scheduleId: SANDBOX_REAPER_SCHEDULE_ID,\n reaperPeriodMs: settings.sandboxLeaseReaperPeriodMs,\n });\n return {\n registered: true,\n close: async () => {\n await connection.close();\n },\n };\n } catch (error) {\n if (error instanceof ScheduleAlreadyRunning) {\n // Never move this action off the base queue: doing so would leave a full\n // rollback with no worker polling the only reaper Schedule. The workflow\n // implementation itself owns the forward-compatible queue handoff.\n await temporal.schedule.getHandle(SANDBOX_REAPER_SCHEDULE_ID).update((previous) => ({\n spec,\n action,\n policies,\n state: {\n paused: previous.state.paused,\n ...(previous.state.note ? { note: previous.state.note } : {}),\n ...(previous.state.remainingActions !== undefined\n ? { remainingActions: previous.state.remainingActions }\n : {}),\n },\n }));\n observability.info(\"Reconciled the global sandbox-lease reaper Schedule\", {\n scheduleId: SANDBOX_REAPER_SCHEDULE_ID,\n temporalTaskQueue: action.taskQueue,\n });\n return {\n registered: false,\n close: async () => {\n await connection.close();\n },\n };\n }\n await connection.close().catch(() => undefined);\n throw error;\n }\n}\n\n/**\n * Register the one provider-neutral expired direct-upload cleanup Schedule.\n * Unlike sandbox GC this is always registered: file uploads can be enabled in\n * deployments where sandbox ownership is disabled. The activity is a cheap\n * no-op when object storage is not configured.\n */\nexport async function registerFileUploadReaperSchedule(\n settings: Settings,\n observability: Observability,\n): Promise<{ registered: boolean; close: () => Promise<void> }> {\n const connection = await Connection.connect(temporalConnectionOptions(settings));\n const temporal = new TemporalClient({ connection, namespace: settings.temporalNamespace });\n try {\n await temporal.schedule.create({\n scheduleId: FILE_UPLOAD_REAPER_SCHEDULE_ID,\n spec: { intervals: [{ every: FILE_UPLOAD_REAPER_PERIOD_MS }] },\n action: {\n type: \"startWorkflow\",\n workflowType: \"fileUploadReaperWorkflow\",\n taskQueue: settings.temporalTaskQueue,\n args: [],\n },\n policies: {\n overlap: ScheduleOverlapPolicy.SKIP,\n catchupWindow: \"1m\",\n pauseOnFailure: false,\n },\n });\n observability.info(\"Registered the global file-upload reaper Schedule\", {\n scheduleId: FILE_UPLOAD_REAPER_SCHEDULE_ID,\n reaperPeriodMs: FILE_UPLOAD_REAPER_PERIOD_MS,\n });\n return { registered: true, close: async () => connection.close() };\n } catch (error) {\n if (error instanceof ScheduleAlreadyRunning) {\n observability.info(\"Global file-upload reaper Schedule already registered\", {\n scheduleId: FILE_UPLOAD_REAPER_SCHEDULE_ID,\n });\n return { registered: false, close: async () => connection.close() };\n }\n await connection.close().catch(() => undefined);\n throw error;\n }\n}\n\n/**\n * Register the one repair cadence for committed workflow-wake revisions. The\n * activity only reads the transactional outbox and sends revision-scoped\n * signals; it is independent of sandbox ownership and child-agent features.\n */\nexport async function registerSessionWorkflowWakeDispatcherSchedule(\n settings: Settings,\n observability: Observability,\n): Promise<{ registered: boolean; close: () => Promise<void> }> {\n const connection = await Connection.connect(temporalConnectionOptions(settings));\n const temporal = new TemporalClient({ connection, namespace: settings.temporalNamespace });\n try {\n await temporal.schedule.create({\n scheduleId: SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID,\n spec: { intervals: [{ every: SESSION_WORKFLOW_WAKE_DISPATCHER_PERIOD_MS }] },\n action: {\n type: \"startWorkflow\",\n workflowType: SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_TYPE,\n taskQueue: settings.temporalTaskQueue,\n args: [],\n },\n policies: {\n overlap: ScheduleOverlapPolicy.SKIP,\n catchupWindow: \"1m\",\n pauseOnFailure: false,\n },\n });\n observability.info(\"Registered the session-workflow wake dispatcher Schedule\", {\n scheduleId: SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID,\n periodMs: SESSION_WORKFLOW_WAKE_DISPATCHER_PERIOD_MS,\n });\n return { registered: true, close: async () => connection.close() };\n } catch (error) {\n if (error instanceof ScheduleAlreadyRunning) {\n observability.info(\"Session-workflow wake dispatcher Schedule already registered\", {\n scheduleId: SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID,\n });\n return { registered: false, close: async () => connection.close() };\n }\n await connection.close().catch(() => undefined);\n throw error;\n }\n}\n\nexport type OpenGeniWorkerServiceOptions = Omit<WorkerOptions, \"activityDependencies\"> & {\n activityDependencies: ActivityDependencies & { db: Database; bus: EventBus };\n /**\n * Exact catalog posture required by the standalone runtime. Embedded hosts\n * may omit this when they own an equivalent database isolation contract.\n */\n databasePosture?: RuntimeDatabasePostureOptions;\n /**\n * `role-default` registers OpenGeni's internal maintenance schedules on a\n * control worker only. These are engine maintenance schedules, not a host's\n * product-level scheduled-agent jobs. Use `none` when another control worker\n * in the same deployment owns them.\n */\n internalSchedules?: \"role-default\" | \"none\";\n /** Set false only when the host exposes equivalent lifecycle endpoints itself. */\n http?: false | { readinessTimeoutMs?: number };\n};\n\nexport type OpenGeniWorkerService = {\n readonly role: OpenGeniWorkerRole;\n readonly worker: WorkerRunTarget;\n readonly connection: NativeConnection;\n state(): WorkerLifecycleState;\n run(): Promise<void>;\n drain(reason?: string): void;\n close(): Promise<void>;\n};\n\nexport function workerOwnsInternalSchedules(\n role: OpenGeniWorkerRole,\n policy: OpenGeniWorkerServiceOptions[\"internalSchedules\"] = \"role-default\",\n): boolean {\n return role === \"control\" && policy !== \"none\";\n}\n\n/**\n * Construct one role-specific worker process around the lower-level Temporal\n * worker factory. The service owns every Temporal client and HTTP listener it\n * creates. The embedding host retains ownership of its injected DB and EventBus\n * handles and closes those only after this service has drained.\n */\nexport async function createOpenGeniWorkerService(\n options: OpenGeniWorkerServiceOptions,\n): Promise<OpenGeniWorkerService> {\n const settings = options.settings ?? getSettings();\n const observability =\n options.activityDependencies.observability ??\n createObservability(settings, { component: `worker-${options.role}` });\n const retryOptions = startupRetryOptions(settings);\n const onRetry = (event: Parameters<typeof logStartupDependencyRetry>[1]) =>\n logStartupDependencyRetry(observability, event);\n let lifecycle: WorkerServiceLifecycle | undefined;\n let signaler: Awaited<ReturnType<typeof createWorkerWorkflowSignaler>> | undefined;\n let workerBundle: Awaited<ReturnType<typeof createOpenGeniWorker>> | undefined;\n let turnCapacityMonitor: ReturnType<typeof startTurnCapacityMonitor> | undefined;\n const schedules: Array<{ close: () => Promise<void> }> = [];\n let httpServer: ReturnType<typeof startWorkerHttpServer> | undefined;\n let memoryPressureGuard: TurnWorkerMemoryPressureGuard | undefined;\n\n try {\n const needsSignaler =\n options.role === \"turn\" ||\n !options.activityDependencies.wakeSessionWorkflow ||\n !options.activityDependencies.signalSessionAttemptQuiesced ||\n !options.activityDependencies.inspectSessionAttemptActivity ||\n !options.activityDependencies.signalCodexCapacityWorkflow ||\n !options.activityDependencies.startSandboxReaperWorkflow ||\n !options.activityDependencies.startVideoGenerationWorkflow;\n if (needsSignaler) {\n signaler = await retryStartupDependency(\n \"Temporal client\",\n () => createWorkerWorkflowSignaler(settings, options.activityDependencies.db),\n { ...retryOptions, onRetry },\n );\n }\n const wakeSessionWorkflow =\n options.activityDependencies.wakeSessionWorkflow ?? signaler?.wakeSessionWorkflow;\n const signalSessionAttemptQuiesced =\n options.activityDependencies.signalSessionAttemptQuiesced ??\n signaler?.signalSessionAttemptQuiesced;\n const inspectSessionAttemptActivity =\n options.activityDependencies.inspectSessionAttemptActivity ??\n signaler?.inspectSessionAttemptActivity;\n const signalCodexCapacityWorkflow =\n options.activityDependencies.signalCodexCapacityWorkflow ??\n signaler?.signalCodexCapacityWorkflow;\n const startSandboxReaperWorkflow =\n options.activityDependencies.startSandboxReaperWorkflow ??\n signaler?.startSandboxReaperWorkflow;\n const startVideoGenerationWorkflow =\n options.activityDependencies.startVideoGenerationWorkflow ??\n signaler?.startVideoGenerationWorkflow;\n if (\n !wakeSessionWorkflow ||\n !signalSessionAttemptQuiesced ||\n !inspectSessionAttemptActivity ||\n !signalCodexCapacityWorkflow ||\n !startSandboxReaperWorkflow ||\n !startVideoGenerationWorkflow\n ) {\n throw new Error(\"OpenGeni worker lifecycle could not resolve its workflow signalers\");\n }\n workerBundle = await createOpenGeniWorker({\n role: options.role,\n settings,\n ...(options.activities ? { activities: options.activities } : {}),\n ...(options.workflowBundle ? { workflowBundle: options.workflowBundle } : {}),\n activityDependencies: {\n ...options.activityDependencies,\n settings,\n observability,\n wakeSessionWorkflow,\n signalSessionAttemptQuiesced,\n inspectSessionAttemptActivity,\n signalCodexCapacityWorkflow,\n startSandboxReaperWorkflow,\n startVideoGenerationWorkflow,\n },\n });\n\n if (options.role === \"turn\") {\n if (!signaler) {\n throw new Error(\"Turn worker capacity monitor could not resolve its Temporal stats client\");\n }\n turnCapacityMonitor = startTurnCapacityMonitor({\n observability,\n read: signaler.getTurnTaskQueueStats,\n });\n }\n\n if (workerOwnsInternalSchedules(options.role, options.internalSchedules)) {\n schedules.push(\n await retryStartupDependency(\n \"Temporal schedule (sandbox reaper)\",\n () => registerSandboxReaperSchedule(settings, observability),\n { ...retryOptions, onRetry },\n ),\n );\n schedules.push(\n await retryStartupDependency(\n \"Temporal schedule (file upload reaper)\",\n () => registerFileUploadReaperSchedule(settings, observability),\n { ...retryOptions, onRetry },\n ),\n );\n schedules.push(\n await retryStartupDependency(\n \"Temporal schedule (session-workflow wake dispatcher)\",\n () => registerSessionWorkflowWakeDispatcherSchedule(settings, observability),\n { ...retryOptions, onRetry },\n ),\n );\n }\n\n if (options.http !== false) {\n httpServer = startWorkerHttpServer({\n settings,\n observability,\n checks: {\n db: dbReadyCheck(options.activityDependencies.db, options.databasePosture),\n nats: natsReadyCheck(options.activityDependencies.bus),\n temporal: temporalReadyCheck(workerBundle.connection),\n },\n ...(options.http?.readinessTimeoutMs ? { timeoutMs: options.http.readinessTimeoutMs } : {}),\n lifecycle: { role: options.role, state: () => lifecycle?.state() ?? \"starting\" },\n });\n }\n } catch (error) {\n httpServer?.stop(true);\n await Promise.allSettled([\n turnCapacityMonitor?.close(),\n workerBundle?.connection.close(),\n signaler?.close(),\n ...schedules.map((schedule) => schedule.close()),\n ]);\n throw error;\n }\n\n const activeWorkerBundle = workerBundle;\n const activeSignaler = signaler;\n if (!activeWorkerBundle) {\n throw new Error(\"OpenGeni worker service initialization did not complete\");\n }\n\n lifecycle = createWorkerServiceLifecycle({\n role: options.role,\n worker: activeWorkerBundle.worker,\n observability,\n closeOwnedResources: async () => {\n memoryPressureGuard?.close();\n httpServer?.stop(true);\n await Promise.allSettled([\n turnCapacityMonitor?.close(),\n activeWorkerBundle.connection.close(),\n activeSignaler?.close(),\n ...schedules.map((schedule) => schedule.close()),\n ]);\n },\n onReady: () => {\n observability.info(\"OpenGeni worker listening\", {\n role: options.role,\n temporalTaskQueue:\n options.role === \"control\"\n ? settings.temporalTaskQueue\n : turnTaskQueue(settings.temporalTaskQueue),\n ...(options.role === \"turn\"\n ? turnWorkerConcurrencyLogFields(settings)\n : {\n concurrencyMode: \"fixed\",\n maxConcurrentTurns: CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES,\n targetCpuUsage: null,\n targetMemoryUsage: null,\n }),\n maxConcurrentWorkflowTaskExecutions:\n options.role === \"control\" ? CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS : 0,\n maxCachedWorkflows: options.role === \"control\" ? CONTROL_WORKER_MAX_CACHED_WORKFLOWS : 0,\n httpPort: options.http === false ? null : settings.workerHttpPort,\n });\n },\n });\n const activeLifecycle = lifecycle;\n\n if (turnWorkerMemoryPressureGuardEnabled(options.role, settings)) {\n try {\n memoryPressureGuard = createTurnWorkerMemoryPressureGuard({\n settings,\n observability,\n drain: () => {\n if (!activeLifecycle.drain(\"memory pressure guard\")) {\n throw new Error(\"worker shutdown request failed\");\n }\n },\n });\n } catch (error) {\n await activeLifecycle.close();\n throw error;\n }\n }\n\n return {\n role: options.role,\n worker: activeWorkerBundle.worker,\n connection: activeWorkerBundle.connection,\n state: activeLifecycle.state,\n run: activeLifecycle.run,\n drain: (reason) => {\n activeLifecycle.drain(reason);\n },\n close: activeLifecycle.close,\n };\n}\n\nexport type RunOpenGeniWorkerOptions = OpenGeniWorkerServiceOptions & {\n /** Defaults to SIGTERM and SIGINT. Pass false when the host owns process signals. */\n shutdownSignals?: false | ReadonlyArray<\"SIGTERM\" | \"SIGINT\">;\n};\n\n/** Start, drain, and close one embedded worker process. */\nexport async function runOpenGeniWorker(options: RunOpenGeniWorkerOptions): Promise<void> {\n const service = await createOpenGeniWorkerService(options);\n const signals =\n options.shutdownSignals === false ? [] : (options.shutdownSignals ?? [\"SIGTERM\", \"SIGINT\"]);\n const handlers = signals.map((signal) => {\n const handler = () => service.drain(signal);\n process.on(signal, handler);\n return { signal, handler };\n });\n try {\n await service.run();\n } finally {\n for (const { signal, handler } of handlers) {\n process.off(signal, handler);\n }\n await service.close();\n }\n}\n\nexport async function startWorker() {\n const role = process.env.OPENGENI_WORKER_ROLE;\n if (role !== \"control\" && role !== \"turn\") {\n throw new Error(\"OPENGENI_WORKER_ROLE must be explicitly set to 'control' or 'turn'\");\n }\n const settings = getSettings();\n const observability = createObservability(settings, { component: `worker-${role}` });\n const retryOptions = startupRetryOptions(settings);\n const onRetry = (event: Parameters<typeof logStartupDependencyRetry>[1]) =>\n logStartupDependencyRetry(observability, event);\n const searchPath = dbSearchPath(settings);\n const dbClient = createDb(settings.databaseUrl, {\n ...(searchPath ? { searchPath } : {}),\n rlsStrategy: settings.rlsStrategy,\n });\n const databasePosture = {\n rlsStrategy: settings.rlsStrategy,\n expectedRole: settings.runtimeDatabaseRole,\n targetSchema: settings.dbSchema.trim() || \"public\",\n } as const;\n const controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n let bus: Awaited<ReturnType<typeof createNatsEventBus>> | undefined;\n try {\n await retryStartupDependency(\n \"PostgreSQL runtime posture\",\n () => assertRuntimeDatabasePosture(dbClient.db, databasePosture),\n { ...retryOptions, onRetry },\n );\n bus = await retryStartupDependency(\n \"NATS\",\n () =>\n createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth\n ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password }\n : undefined,\n { logger: observabilityEventLogger(observability) },\n ),\n { ...retryOptions, onRetry },\n );\n await runOpenGeniWorker({\n role,\n settings,\n databasePosture,\n activityDependencies: {\n observability,\n db: dbClient.db,\n bus,\n },\n });\n } finally {\n await Promise.allSettled([bus?.close(), dbClient.close()]);\n }\n}\n\nif (import.meta.main) {\n await startWorker();\n}\n","import { ActivityCancellationType, proxyActivities } from \"@temporalio/workflow\";\nimport type * as activities from \"../activities\";\n\ntype WorkflowControlActivities = Pick<\n typeof activities,\n | \"enqueueGoalRetryWake\"\n | \"expireSessionHumanInput\"\n | \"failSessionAttempt\"\n | \"getCodexCapacityWait\"\n | \"markSessionIdle\"\n | \"peekSessionWork\"\n | \"persistSessionAttemptQuiescence\"\n | \"reconcileSessionAttemptQuiescence\"\n | \"reconcileCodexCapacityWait\"\n | \"recoverDispatch\"\n | \"recoverEscapedMcpTimeout\"\n | \"settleSessionInterruptions\"\n>;\n\n/**\n * Session/schedule workflow control activities are bounded, idempotent database\n * and provider-metadata operations. They must not inherit the agent turn's\n * 30-day attempt: Temporal cannot otherwise detect that the pod which accepted\n * a non-heartbeating control activity disappeared, leaving the workflow pinned\n * to a dead worker for the full 30 days. A bounded attempt plus an unbounded\n * Temporal retry keeps the durable workflow alive across rollout, node loss, or\n * transient database/network failure; retries re-run on a healthy control pod.\n */\nexport const activity = proxyActivities<WorkflowControlActivities>({\n startToCloseTimeout: \"2 minutes\",\n retry: {\n initialInterval: \"1 second\",\n backoffCoefficient: 2,\n maximumInterval: \"30 seconds\",\n },\n});\n\n/** One schedule occurrence is bounded. Transient control-plane failures get a\n * short retry window, but a revoked binding or other permanent task error must\n * not leave a Temporal activity retrying forever; the next scheduled occurrence\n * is an independent workflow and will re-evaluate current state. */\nexport const scheduledTaskActivity = proxyActivities<\n Pick<typeof activities, \"dispatchScheduledTaskRun\">\n>({\n startToCloseTimeout: \"2 minutes\",\n retry: {\n initialInterval: \"1 second\",\n backoffCoefficient: 2,\n maximumInterval: \"30 seconds\",\n maximumAttempts: 5,\n },\n});\n\n/** Goal continuation evaluates a durable Postgres obligation at an idle\n * boundary. A transient failure gets a short retry window, then records an\n * explicit delayed outbox wake instead of relying on an unrelated mutation or\n * keeping workflow history alive with polling. */\nexport const goalActivity = proxyActivities<Pick<typeof activities, \"maybeContinueGoal\">>({\n startToCloseTimeout: \"30 seconds\",\n retry: {\n initialInterval: \"1 second\",\n backoffCoefficient: 2,\n maximumInterval: \"5 seconds\",\n maximumAttempts: 3,\n },\n});\n\nexport function turnTaskQueue(baseTaskQueue: string): string {\n return `${baseTaskQueue}-turns`;\n}\n\nexport function turnActivityForTaskQueue(baseTaskQueue: string, receiptGatedCancellation = true) {\n return proxyActivities<Pick<typeof activities, \"runAgentTurn\">>({\n taskQueue: turnTaskQueue(baseTaskQueue),\n // Agent segments legitimately run for days. A started turn heartbeats;\n // queued activities remain queued truthfully until a capped turn worker\n // accepts them and performs the atomic claim.\n startToCloseTimeout: \"30 days\",\n heartbeatTimeout: \"2 minutes\",\n // Pause/Steer first closes the exact attempt in Postgres, then asks\n // Temporal to deliver cancellation. The workflow must not wait for the\n // Temporal activity promise: a provider cleanup promise can outlive the\n // fenced activity body, and Temporal terminalization is not proof that\n // sandbox tools or processes are physically quiescent. The activity owns\n // that proof and writes an exact receipt after its hard tool fence; the\n // receipt transaction wakes the workflow to admit a replacement.\n cancellationType: receiptGatedCancellation\n ? ActivityCancellationType.TRY_CANCEL\n : ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,\n retry: { maximumAttempts: 1 },\n });\n}\n\nexport function videoGenerationActivityForTaskQueue(baseTaskQueue: string) {\n return proxyActivities<Pick<typeof activities, \"reconcileVideoGenerationOperation\">>({\n taskQueue: turnTaskQueue(baseTaskQueue),\n startToCloseTimeout: \"20 minutes\",\n retry: {\n initialInterval: \"1 second\",\n backoffCoefficient: 2,\n maximumInterval: \"30 seconds\",\n maximumAttempts: 3,\n },\n });\n}\n\nexport const documentActivity = proxyActivities<Pick<typeof activities, \"indexDocument\">>({\n startToCloseTimeout: \"30 minutes\",\n retry: { maximumAttempts: 1 },\n});\n\n/** Connector inventory/download/index batches are provider-I/O activities. The\n * implementation heartbeats between bounded items and owns its resumable\n * checkpoint; Temporal retries therefore repeat only idempotent source/object\n * operations and never invoke the agent runtime. */\nexport const knowledgeSourceSyncActivity = proxyActivities<\n Pick<typeof activities, \"runKnowledgeSourceSyncBatch\">\n>({\n startToCloseTimeout: \"1 hour\",\n heartbeatTimeout: \"2 minutes\",\n retry: {\n initialInterval: \"2 seconds\",\n backoffCoefficient: 2,\n maximumInterval: \"1 minute\",\n maximumAttempts: 5,\n },\n});\n\nexport function workflowFailureMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n","import type { Settings } from \"@opengeni/config\";\nimport {\n assertRuntimeDatabasePosture,\n dbSql,\n type Database,\n type RuntimeDatabasePostureOptions,\n} from \"@opengeni/db\";\nimport type { EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\n\nexport type ReadinessCheckName = \"db\" | \"nats\" | \"temporal\";\nexport type ReadinessChecks = Record<ReadinessCheckName, () => Promise<void> | void>;\n\nexport type ReadinessResult = {\n ok: boolean;\n state?: WorkerLifecycleState;\n checks: Record<ReadinessCheckName, { ok: boolean; error?: string }>;\n};\n\nexport type WorkerLifecycleState = \"starting\" | \"ready\" | \"draining\" | \"stopped\" | \"failed\";\n\nexport type WorkerHttpLifecycle = {\n role: \"control\" | \"turn\";\n state: () => WorkerLifecycleState;\n};\n\nexport type WorkerHttpServerInput = {\n settings: Settings;\n observability: Observability;\n checks: ReadinessChecks;\n timeoutMs?: number;\n lifecycle?: WorkerHttpLifecycle;\n};\n\nexport function createWorkerHttpHandler(\n input: WorkerHttpServerInput,\n): (request: Request) => Promise<Response> {\n const { settings, observability, checks, lifecycle } = input;\n const timeoutMs = input.timeoutMs ?? 2_000;\n return async (request) => {\n const url = new URL(request.url);\n if (request.method !== \"GET\") {\n return Response.json({ error: \"method_not_allowed\" }, { status: 405 });\n }\n if (url.pathname === \"/healthz\") {\n const state = lifecycle?.state();\n const ok = state !== \"failed\" && state !== \"stopped\";\n return Response.json(\n {\n service: settings.serviceName,\n environment: settings.environment,\n deploymentRevision: settings.deploymentRevision,\n ...(lifecycle ? { role: lifecycle.role, state } : {}),\n ok,\n },\n { status: ok ? 200 : 503 },\n );\n }\n if (url.pathname === \"/metrics\") {\n return new Response(await observability.prometheusMetrics(), {\n status: 200,\n headers: { \"content-type\": \"text/plain; version=0.0.4; charset=utf-8\" },\n });\n }\n if (url.pathname === \"/readyz\") {\n const state = lifecycle?.state();\n const result =\n state && state !== \"ready\"\n ? {\n ok: false,\n state,\n checks: Object.fromEntries(\n (Object.keys(checks) as ReadinessCheckName[]).map((name) => [\n name,\n { ok: false, error: \"worker_not_ready\" },\n ]),\n ) as ReadinessResult[\"checks\"],\n }\n : { ...(await runReadinessChecks(checks, timeoutMs)), ...(state ? { state } : {}) };\n return Response.json(result, { status: result.ok ? 200 : 503 });\n }\n return Response.json({ error: \"not_found\" }, { status: 404 });\n };\n}\n\nexport function startWorkerHttpServer(input: WorkerHttpServerInput): ReturnType<typeof Bun.serve> {\n return Bun.serve({\n hostname: \"0.0.0.0\",\n port: input.settings.workerHttpPort,\n fetch: createWorkerHttpHandler(input),\n });\n}\n\nexport async function runReadinessChecks(\n checks: ReadinessChecks,\n timeoutMs = 2_000,\n): Promise<ReadinessResult> {\n const entries = await Promise.all(\n (Object.entries(checks) as Array<[ReadinessCheckName, () => Promise<void> | void]>).map(\n async ([name, check]) => {\n try {\n await withTimeout(Promise.resolve().then(check), timeoutMs);\n return [name, { ok: true }] as const;\n } catch {\n return [name, { ok: false, error: \"dependency_unavailable\" }] as const;\n }\n },\n ),\n );\n const result = Object.fromEntries(entries) as ReadinessResult[\"checks\"];\n return {\n ok: Object.values(result).every((check) => check.ok),\n checks: result,\n };\n}\n\nexport function dbReadyCheck(\n db: Database,\n posture?: RuntimeDatabasePostureOptions,\n): () => Promise<void> {\n return async () => {\n if (posture) {\n await assertRuntimeDatabasePosture(db, posture);\n return;\n }\n await db.execute(dbSql`select 1`);\n };\n}\n\nexport function natsReadyCheck(bus: EventBus): () => void {\n return () => {\n if (bus.isConnected && !bus.isConnected()) {\n throw new Error(\"NATS is not connected\");\n }\n };\n}\n\nexport function temporalReadyCheck(\n connection: Pick<\n import(\"@temporalio/worker\").NativeConnection,\n \"workflowService\" | \"withDeadline\"\n >,\n): () => Promise<void> {\n return async () => {\n await connection.withDeadline(Date.now() + 2_000, () =>\n connection.workflowService.getSystemInfo({}),\n );\n };\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`readiness check timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n }),\n ]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n","import type { Observability } from \"@opengeni/observability\";\nimport type { WorkerLifecycleState } from \"./http\";\n\nexport async function constructWithOwnedConnection<Connection, Result>(\n connect: () => Promise<Connection>,\n construct: (connection: Connection) => Promise<Result>,\n close: (connection: Connection) => Promise<void>,\n): Promise<Result> {\n const connection = await connect();\n try {\n return await construct(connection);\n } catch (error) {\n await close(connection).catch(() => undefined);\n throw error;\n }\n}\n\nexport type WorkerRunTarget = {\n run(): Promise<void>;\n shutdown(): void;\n};\n\n/** One process may poll several disjoint Temporal queues, but it still has one\n * host lifecycle. Start and stop every poller as a unit; a failed poller drains\n * its siblings and preserves the original failure. */\nexport function combineWorkerRunTargets(targets: readonly WorkerRunTarget[]): WorkerRunTarget {\n if (targets.length === 0) {\n throw new Error(\"a worker service requires at least one Temporal poller\");\n }\n let runPromise: Promise<void> | undefined;\n const shutdown = (): void => {\n let firstError: unknown;\n for (const target of targets) {\n try {\n target.shutdown();\n } catch (error) {\n firstError ??= error;\n }\n }\n if (firstError !== undefined) throw firstError;\n };\n return {\n run: () => {\n runPromise ??= (async () => {\n const runs = targets.map((target) => {\n try {\n return target.run();\n } catch (error) {\n return Promise.reject(error);\n }\n });\n try {\n await Promise.all(runs);\n } catch (error) {\n try {\n shutdown();\n } catch {\n // Preserve the poller failure. Every sibling still received its\n // shutdown request even when one request itself failed.\n }\n await Promise.allSettled(runs);\n throw error;\n }\n })();\n return runPromise;\n },\n shutdown,\n };\n}\n\nexport type WorkerServiceLifecycle = {\n state(): WorkerLifecycleState;\n run(): Promise<void>;\n drain(reason?: string): boolean;\n close(): Promise<void>;\n};\n\nexport function createWorkerServiceLifecycle(input: {\n role: \"control\" | \"turn\";\n worker: WorkerRunTarget;\n observability: Observability;\n closeOwnedResources: () => Promise<void>;\n onReady?: () => void;\n}): WorkerServiceLifecycle {\n let state: WorkerLifecycleState = \"starting\";\n let runPromise: Promise<void> | undefined;\n let resourcesClosed: Promise<void> | undefined;\n const closeOwnedResources = () => {\n resourcesClosed ??= input.closeOwnedResources();\n return resourcesClosed;\n };\n\n const lifecycle: WorkerServiceLifecycle = {\n state: () => state,\n run: () => {\n if (!runPromise && state === \"draining\") {\n runPromise = (async () => {\n state = \"stopped\";\n await closeOwnedResources();\n })();\n return runPromise;\n }\n if (!runPromise && (state === \"stopped\" || state === \"failed\")) {\n return Promise.reject(new Error(`cannot run a worker service that is ${state}`));\n }\n runPromise ??= (async () => {\n if (state === \"starting\") {\n state = \"ready\";\n }\n input.onReady?.();\n try {\n await input.worker.run();\n state = \"stopped\";\n } catch (error) {\n state = \"failed\";\n throw error;\n } finally {\n await closeOwnedResources();\n }\n })();\n return runPromise;\n },\n drain: (_reason = \"host request\") => {\n if (state === \"draining\" || state === \"stopped\" || state === \"failed\") {\n return true;\n }\n const previousState = state;\n safeLifecycleLog(() =>\n input.observability.info(\"OpenGeni worker draining (graceful shutdown)\", {\n role: input.role,\n errorClass: \"WorkerLifecycleOperation\",\n errorCode: \"worker_draining\",\n origin: \"worker-lifecycle\",\n }),\n );\n state = \"draining\";\n try {\n input.worker.shutdown();\n return true;\n } catch {\n state = previousState;\n safeLifecycleLog(() =>\n input.observability.warn(\"worker shutdown request failed\", {\n errorClass: \"WorkerLifecycleOperationError\",\n errorCode: \"worker_shutdown_request_failed\",\n origin: \"worker-lifecycle\",\n }),\n );\n return false;\n }\n },\n close: async () => {\n if (!lifecycle.drain(\"service close\")) {\n throw new Error(\"worker shutdown request failed\");\n }\n if (runPromise) {\n await runPromise.catch(() => undefined);\n } else {\n state = \"stopped\";\n await closeOwnedResources();\n }\n },\n };\n\n return lifecycle;\n}\n\nfunction safeLifecycleLog(log: () => void): void {\n try {\n log();\n } catch {\n // Telemetry cannot change worker lifecycle state or shutdown delivery.\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { freemem, totalmem } from \"node:os\";\nimport { posix } from \"node:path\";\nimport type { Settings } from \"@opengeni/config\";\nimport type { Observability } from \"@opengeni/observability\";\n\nexport type TurnWorkerMemoryScope = \"host\" | \"cgroup\";\n\nexport type TurnWorkerMemoryScopeSnapshot = {\n scope: TurnWorkerMemoryScope;\n usedBytes: number;\n limitBytes: number;\n};\n\nexport type TurnWorkerMemoryPressureSnapshot = {\n processRssBytes: number;\n processHeapUsedBytes: number;\n processExternalBytes: number;\n processArrayBuffersBytes: number;\n scopes: TurnWorkerMemoryScopeSnapshot[];\n};\n\nexport type TurnWorkerMemoryPressureGuard = {\n sampleNow(): void;\n close(): void;\n};\n\ntype GuardSettings = Pick<\n Settings,\n | \"turnWorkerConcurrencyMode\"\n | \"turnWorkerTargetMemoryUsage\"\n | \"turnWorkerEmergencyMemoryUsage\"\n | \"turnWorkerMemoryGuardIntervalMs\"\n | \"turnWorkerMemoryGuardSustainMs\"\n>;\n\ntype GuardDependencies = {\n now?: () => number;\n sample?: () => TurnWorkerMemoryPressureSnapshot;\n setInterval?: typeof setInterval;\n clearInterval?: typeof clearInterval;\n gc?: () => void;\n};\n\ntype SnapshotDependencies = {\n readText?: (path: string) => string | null;\n hostTotalBytes?: () => number;\n hostAvailableBytes?: () => number;\n processMemoryUsage?: () => Pick<\n NodeJS.MemoryUsage,\n \"rss\" | \"heapUsed\" | \"external\" | \"arrayBuffers\"\n >;\n};\n\nexport type ProcessCgroupMembership = {\n v2Path: string | null;\n v1MemoryPath: string | null;\n};\n\nexport type CgroupMemoryFilePair = {\n currentPath: string;\n maxPath: string;\n};\n\nconst CGROUP_V2_MOUNT = \"/sys/fs/cgroup\";\nconst CGROUP_V1_MEMORY_MOUNT = \"/sys/fs/cgroup/memory\";\n\nexport function parseLinuxMeminfo(\n value: string,\n): { totalBytes: number; availableBytes: number } | null {\n const fields = new Map<string, number>();\n for (const line of value.split(\"\\n\")) {\n const match = /^([A-Za-z_()]+):\\s+(\\d+)\\s+kB$/.exec(line.trim());\n if (!match) continue;\n fields.set(match[1] as string, Number(match[2]) * 1024);\n }\n const totalBytes = fields.get(\"MemTotal\");\n const availableBytes = fields.get(\"MemAvailable\");\n if (\n totalBytes === undefined ||\n availableBytes === undefined ||\n !Number.isFinite(totalBytes) ||\n !Number.isFinite(availableBytes) ||\n totalBytes <= 0 ||\n availableBytes < 0\n ) {\n return null;\n }\n return { totalBytes, availableBytes: Math.min(totalBytes, availableBytes) };\n}\n\nexport function parseFiniteCgroupMemoryLimit(value: string): number | null {\n const trimmed = value.trim();\n if (!trimmed || trimmed === \"max\") return null;\n const parsed = Number(trimmed);\n // cgroup v1 represents \"unlimited\" with a near-int64 sentinel. Treat only\n // realistic finite limits as authority; host headroom remains the fallback.\n if (!Number.isSafeInteger(parsed) || parsed <= 0 || parsed >= 2 ** 60) return null;\n return parsed;\n}\n\nexport function parseProcessCgroupMembership(value: string): ProcessCgroupMembership {\n let v2Path: string | null = null;\n let v1MemoryPath: string | null = null;\n for (const line of value.split(\"\\n\")) {\n const firstSeparator = line.indexOf(\":\");\n const secondSeparator = line.indexOf(\":\", firstSeparator + 1);\n if (firstSeparator <= 0 || secondSeparator < 0) continue;\n const hierarchyId = line.slice(0, firstSeparator);\n const controllers = line.slice(firstSeparator + 1, secondSeparator);\n const path = normalizeCgroupPath(line.slice(secondSeparator + 1));\n if (!path) continue;\n if (hierarchyId === \"0\" && controllers === \"\") {\n v2Path = path;\n }\n if (controllers.split(\",\").includes(\"memory\")) {\n v1MemoryPath = path;\n }\n }\n return { v2Path, v1MemoryPath };\n}\n\nexport function cgroupMemoryFilePairs(membership: ProcessCgroupMembership): CgroupMemoryFilePair[] {\n const pairs: CgroupMemoryFilePair[] = [];\n const seen = new Set<string>();\n const appendHierarchy = (\n mount: string,\n path: string | null,\n currentFilename: string,\n maxFilename: string,\n ) => {\n for (const candidate of cgroupAncestorPaths(path ?? \"/\")) {\n const relative = candidate === \"/\" ? \"\" : candidate.slice(1);\n const currentPath = posix.join(mount, relative, currentFilename);\n const maxPath = posix.join(mount, relative, maxFilename);\n const key = `${currentPath}\\0${maxPath}`;\n if (seen.has(key)) continue;\n seen.add(key);\n pairs.push({ currentPath, maxPath });\n }\n };\n\n appendHierarchy(CGROUP_V2_MOUNT, membership.v2Path, \"memory.current\", \"memory.max\");\n appendHierarchy(\n CGROUP_V1_MEMORY_MOUNT,\n membership.v1MemoryPath,\n \"memory.usage_in_bytes\",\n \"memory.limit_in_bytes\",\n );\n return pairs;\n}\n\nexport function readTurnWorkerMemoryPressureSnapshot(\n dependencies: SnapshotDependencies = {},\n): TurnWorkerMemoryPressureSnapshot {\n const readText = dependencies.readText ?? readTextOrNull;\n const linux = parseLinuxMeminfo(readText(\"/proc/meminfo\") ?? \"\");\n const hostTotalBytes = linux?.totalBytes ?? (dependencies.hostTotalBytes ?? totalmem)();\n const hostAvailableBytes =\n linux?.availableBytes ?? (dependencies.hostAvailableBytes ?? freemem)();\n const host = {\n scope: \"host\" as const,\n usedBytes: Math.max(0, hostTotalBytes - Math.min(hostTotalBytes, hostAvailableBytes)),\n limitBytes: hostTotalBytes,\n };\n const cgroup = readCgroupMemoryScope(readText);\n // A finite process cgroup is the pod's actual admission boundary. Host\n // pressure includes unrelated workloads and must not make every replica\n // drain simultaneously; use it only when no finite cgroup authority exists.\n const processMemory = (dependencies.processMemoryUsage ?? process.memoryUsage)();\n\n return {\n processRssBytes: processMemory.rss,\n processHeapUsedBytes: processMemory.heapUsed,\n processExternalBytes: processMemory.external,\n processArrayBuffersBytes: processMemory.arrayBuffers,\n scopes: [cgroup ?? host],\n };\n}\n\nexport function turnWorkerMemoryPressureGuardEnabled(\n role: \"control\" | \"turn\",\n settings: Pick<Settings, \"turnWorkerConcurrencyMode\">,\n): boolean {\n return role === \"turn\" && settings.turnWorkerConcurrencyMode === \"resource-based\";\n}\n\nexport function createTurnWorkerMemoryPressureGuard(input: {\n settings: GuardSettings;\n observability: Observability;\n drain: () => void;\n dependencies?: GuardDependencies;\n}): TurnWorkerMemoryPressureGuard {\n const now = input.dependencies?.now ?? Date.now;\n const sample = input.dependencies?.sample ?? readTurnWorkerMemoryPressureSnapshot;\n const schedule = input.dependencies?.setInterval ?? setInterval;\n const cancel = input.dependencies?.clearInterval ?? clearInterval;\n const collectGarbage = input.dependencies?.gc ?? (() => Bun.gc(false));\n const breachStartedAt = new Map<TurnWorkerMemoryScope, number>();\n let lastGcAt = Number.NEGATIVE_INFINITY;\n let drainRequested = false;\n let closed = false;\n\n const sampleNow = () => {\n if (closed) return;\n const observedAt = now();\n let snapshot: TurnWorkerMemoryPressureSnapshot;\n try {\n snapshot = sample();\n } catch {\n breachStartedAt.clear();\n safeIncrementCounter(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_sample_failures_total\",\n help: \"Turn-worker memory pressure guard samples that could not be read.\",\n });\n return;\n }\n\n const validScopes = snapshot.scopes.filter(\n ({ usedBytes, limitBytes }) =>\n Number.isFinite(usedBytes) &&\n Number.isFinite(limitBytes) &&\n usedBytes >= 0 &&\n limitBytes > 0,\n );\n if (validScopes.length === 0) {\n breachStartedAt.clear();\n safeIncrementCounter(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_sample_failures_total\",\n help: \"Turn-worker memory pressure guard samples that could not be read.\",\n });\n return;\n }\n\n const sustainedBreaches: Array<{\n scope: TurnWorkerMemoryScope;\n utilizationRatio: number;\n breachSeconds: number;\n }> = [];\n for (const [kind, value] of [\n [\"rss\", snapshot.processRssBytes],\n [\"heap_used\", snapshot.processHeapUsedBytes],\n [\"external\", snapshot.processExternalBytes],\n [\"array_buffers\", snapshot.processArrayBuffersBytes],\n ] as const) {\n safeSetGauge(input.observability, {\n name: \"opengeni_turn_worker_process_memory_bytes\",\n help: \"Turn-worker process memory by runtime-reported category.\",\n labels: { kind },\n value: Number.isFinite(value) && value >= 0 ? value : 0,\n });\n }\n let shouldCollectGarbage = false;\n for (const scope of validScopes) {\n const utilizationRatio = scope.usedBytes / scope.limitBytes;\n const processRssRatio = snapshot.processRssBytes / scope.limitBytes;\n safeSetGauge(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_utilization_ratio\",\n help: \"Observed memory utilization ratio used by the turn-worker pressure guard.\",\n labels: { scope: scope.scope },\n value: utilizationRatio,\n });\n safeSetGauge(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_target_ratio\",\n help: \"Memory admission target enforced by the Temporal resource tuner.\",\n labels: { scope: scope.scope },\n value: input.settings.turnWorkerTargetMemoryUsage,\n });\n safeSetGauge(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_emergency_ratio\",\n help: \"Emergency memory threshold enforced by the turn-worker pressure guard.\",\n labels: { scope: scope.scope },\n value: input.settings.turnWorkerEmergencyMemoryUsage,\n });\n safeSetGauge(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_available_bytes\",\n help: \"Memory headroom remaining in the turn-worker pressure guard scope.\",\n labels: { scope: scope.scope },\n value: Math.max(0, scope.limitBytes - scope.usedBytes),\n });\n safeSetGauge(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_process_rss_ratio\",\n help: \"Turn-worker RSS as a ratio of the observed host or finite cgroup memory scope.\",\n labels: { scope: scope.scope },\n value: processRssRatio,\n });\n shouldCollectGarbage ||= processRssRatio >= input.settings.turnWorkerTargetMemoryUsage;\n\n if (utilizationRatio < input.settings.turnWorkerEmergencyMemoryUsage) {\n breachStartedAt.delete(scope.scope);\n safeSetGauge(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_breach_seconds\",\n help: \"Seconds the turn-worker emergency threshold has remained continuously breached.\",\n labels: { scope: scope.scope },\n value: 0,\n });\n continue;\n }\n\n const startedAt = breachStartedAt.get(scope.scope) ?? observedAt;\n breachStartedAt.set(scope.scope, startedAt);\n const breachMs = Math.max(0, observedAt - startedAt);\n const breachSeconds = breachMs / 1_000;\n safeSetGauge(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_breach_seconds\",\n help: \"Seconds the turn-worker emergency threshold has remained continuously breached.\",\n labels: { scope: scope.scope },\n value: breachSeconds,\n });\n if (breachMs >= input.settings.turnWorkerMemoryGuardSustainMs) {\n sustainedBreaches.push({ scope: scope.scope, utilizationRatio, breachSeconds });\n }\n }\n\n // Large request buffers can become unreachable well before JSC's ordinary\n // heap trigger notices native/external pressure. Nudge an asynchronous GC\n // at most once per sustain window before escalating to a worker drain.\n const sustainedBreachesHadGcOpportunity =\n sustainedBreaches.length > 0 &&\n sustainedBreaches.every(({ scope }) => {\n const breachStarted = breachStartedAt.get(scope);\n return breachStarted !== undefined && lastGcAt >= breachStarted && lastGcAt < observedAt;\n });\n let collectedGarbageThisSample = false;\n if (\n shouldCollectGarbage &&\n observedAt - lastGcAt >= input.settings.turnWorkerMemoryGuardSustainMs &&\n (sustainedBreaches.length === 0 || !sustainedBreachesHadGcOpportunity)\n ) {\n lastGcAt = observedAt;\n try {\n collectGarbage();\n collectedGarbageThisSample = true;\n safeIncrementCounter(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_gc_total\",\n help: \"Proactive garbage-collection nudges under process memory pressure.\",\n });\n } catch {\n safeIncrementCounter(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_gc_failures_total\",\n help: \"Proactive memory-pressure garbage-collection nudges that failed.\",\n });\n }\n }\n\n // The nudge is asynchronous. Give it one sampling interval to make the\n // reclaimed RSS visible before deciding that process recycling is needed.\n if (\n (collectedGarbageThisSample && !sustainedBreachesHadGcOpportunity) ||\n drainRequested ||\n sustainedBreaches.length === 0\n ) {\n return;\n }\n\n const primaryBreach = sustainedBreaches.sort(\n (left, right) => right.utilizationRatio - left.utilizationRatio,\n )[0];\n if (!primaryBreach) return;\n\n drainRequested = true;\n safeIncrementCounter(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_drains_total\",\n help: \"Graceful turn-worker drains requested after sustained memory pressure.\",\n labels: { scope: primaryBreach.scope },\n });\n safeWarn(input.observability, \"turn worker memory guard requested graceful drain\", {\n errorClass: \"WorkerLifecycleOperation\",\n errorCode: \"worker_draining\",\n origin: \"worker-lifecycle\",\n reason: `memory pressure (${primaryBreach.scope}, ${boundedRatio(primaryBreach.utilizationRatio)} >= ${input.settings.turnWorkerEmergencyMemoryUsage}, ${primaryBreach.breachSeconds}s)`,\n });\n try {\n input.drain();\n } catch {\n drainRequested = false;\n safeIncrementCounter(input.observability, {\n name: \"opengeni_turn_worker_memory_guard_drain_failures_total\",\n help: \"Turn-worker memory pressure guard drain requests that failed synchronously.\",\n labels: { scope: primaryBreach.scope },\n });\n safeWarn(input.observability, \"turn worker memory guard drain request failed\", {\n errorClass: \"WorkerLifecycleOperationError\",\n errorCode: \"worker_shutdown_request_failed\",\n origin: \"worker-lifecycle\",\n });\n }\n };\n\n const timer = schedule(sampleNow, input.settings.turnWorkerMemoryGuardIntervalMs);\n timer.unref?.();\n sampleNow();\n\n return {\n sampleNow,\n close: () => {\n if (closed) return;\n closed = true;\n cancel(timer);\n },\n };\n}\n\nfunction readCgroupMemoryScope(\n readText: (path: string) => string | null,\n): TurnWorkerMemoryScopeSnapshot | null {\n const membership = parseProcessCgroupMembership(readText(\"/proc/self/cgroup\") ?? \"\");\n let mostPressured: TurnWorkerMemoryScopeSnapshot | null = null;\n for (const { currentPath, maxPath } of cgroupMemoryFilePairs(membership)) {\n const currentRaw = readText(currentPath);\n const maxRaw = readText(maxPath);\n if (currentRaw === null || maxRaw === null) continue;\n const current = Number(currentRaw.trim());\n const limit = parseFiniteCgroupMemoryLimit(maxRaw);\n if (!Number.isFinite(current) || current < 0 || limit === null) continue;\n const candidate = { scope: \"cgroup\" as const, usedBytes: current, limitBytes: limit };\n if (\n !mostPressured ||\n candidate.usedBytes / candidate.limitBytes >\n mostPressured.usedBytes / mostPressured.limitBytes\n ) {\n mostPressured = candidate;\n }\n }\n return mostPressured;\n}\n\nfunction readTextOrNull(path: string): string | null {\n try {\n return readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n}\n\nfunction boundedRatio(value: number): number {\n return Math.round(Math.max(0, Math.min(value, 10)) * 1_000_000) / 1_000_000;\n}\n\nfunction normalizeCgroupPath(value: string): string | null {\n const trimmed = value.trim();\n if (!trimmed.startsWith(\"/\") || trimmed.includes(\"\\0\")) return null;\n if (trimmed.split(\"/\").includes(\"..\")) return null;\n return posix.normalize(trimmed);\n}\n\nfunction cgroupAncestorPaths(path: string): string[] {\n const ancestors: string[] = [];\n let current = path;\n while (true) {\n ancestors.push(current);\n if (current === \"/\") return ancestors;\n current = posix.dirname(current);\n }\n}\n\nfunction safeSetGauge(\n observability: Observability,\n input: Parameters<Observability[\"setGauge\"]>[0],\n): void {\n try {\n observability.setGauge(input);\n } catch {\n // Telemetry cannot disable the memory-safety action.\n }\n}\n\nfunction safeIncrementCounter(\n observability: Observability,\n input: Parameters<Observability[\"incrementCounter\"]>[0],\n): void {\n try {\n observability.incrementCounter(input);\n } catch {\n // Telemetry cannot disable the memory-safety action.\n }\n}\n\nfunction safeWarn(\n observability: Observability,\n message: string,\n attributes: Parameters<Observability[\"warn\"]>[1],\n): void {\n try {\n observability.warn(message, attributes);\n } catch {\n // Telemetry cannot disable the memory-safety action.\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE,gCAAAA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,0BAAyC;AAClD;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV;AAAA,OACK;AACP,SAAS,kBAAkB,cAAyC;AACpE,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;;;AChC9B,SAAS,0BAA0B,uBAAuB;AA4BnD,IAAM,WAAW,gBAA2C;AAAA,EACjE,qBAAqB;AAAA,EACrB,OAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,IACpB,iBAAiB;AAAA,EACnB;AACF,CAAC;AAMM,IAAM,wBAAwB,gBAEnC;AAAA,EACA,qBAAqB;AAAA,EACrB,OAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,IACpB,iBAAiB;AAAA,IACjB,iBAAiB;AAAA,EACnB;AACF,CAAC;AAMM,IAAM,eAAe,gBAA8D;AAAA,EACxF,qBAAqB;AAAA,EACrB,OAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,oBAAoB;AAAA,IACpB,iBAAiB;AAAA,IACjB,i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