@opengeni/worker-bundle 0.7.3 → 0.7.4
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.
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/package.json +9 -9
- package/src/activities/session-state.ts +1 -0
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/capabilities.ts","../src/activities/codex-rotation.ts","../src/activities/codex-auth.ts","../src/activities/codex-capacity.ts","../src/activities/common.ts","../src/activities/context-compaction.ts","../src/activities/turn-attempt-fenced.ts","../src/activities/environment.ts","../src/activities/git-credential-renewal.ts","../src/activities/goals.ts","../src/activities/packs.ts","../src/activities/parent-wake.ts","../src/activities/redaction.ts","../src/activities/run-input.ts","../src/activities/streaming.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"],"sourcesContent":["import {\n dbSearchPath,\n getSettings,\n resolveNatsControlPlaneAuth,\n retryStartupDependency,\n startupRetryOptions,\n type Settings,\n} from \"@opengeni/config\";\nimport { createDb, markSessionWorkflowWakeDelivered, type Database } from \"@opengeni/db\";\nimport { createNatsEventBus } from \"@opengeni/events\";\nimport {\n createObservability,\n logStartupDependencyRetry,\n type Observability,\n} from \"@opengeni/observability\";\nimport {\n Connection,\n ScheduleAlreadyRunning,\n ScheduleOverlapPolicy,\n Client as TemporalClient,\n} from \"@temporalio/client\";\nimport { NativeConnection, Worker } from \"@temporalio/worker\";\nimport { ensureModalRegistryImage } from \"@opengeni/runtime\";\nimport {\n createControlActivities,\n createTurnActivities,\n type ActivityDependencies,\n} from \"./activities\";\nimport type { SignalCodexCapacityWorkflow, WakeSessionWorkflowSignal } from \"./activities/types\";\nimport { turnTaskQueue } from \"./workflows/activities\";\nimport { dbReadyCheck, natsReadyCheck, startWorkerHttpServer } 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 TURN_WORKER_MAX_CONCURRENT_TURNS,\n} from \"./concurrency\";\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 // Embedded hosts install @opengeni/worker-bundle under node_modules, where\n // Temporal's workflow webpack refuses to transpile TS. They relocate\n // src/workflows.ts to a host-owned path and point the worker at it here.\n // Unset (standalone) keeps today's in-package path byte-for-byte.\n workflowsPath?: string;\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 // Pre-resolve a PRIVATE-registry sandbox image before any turn creates a box.\n // No-op unless OPENGENI_MODAL_IMAGE_REGISTRY_SECRET + OPENGENI_MODAL_IMAGE_REF are\n // both set (so non-modal / public-image deployments are byte-unchanged and never\n // load the modal SDK here). Memoized in the provider, so this 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 const connection = await retryStartupDependency(\n \"Temporal\",\n () => NativeConnection.connect({ address: settings.temporalHost }),\n {\n ...startupRetryOptions(settings),\n onRetry: (event) => logStartupDependencyRetry(observability, event),\n },\n );\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 workflowsPath:\n options.workflowsPath ?? new URL(\"../src/workflows.ts\", import.meta.url).pathname,\n maxConcurrentWorkflowTaskExecutions: CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS,\n }\n : {}),\n activities,\n maxConcurrentActivityTaskExecutions:\n options.role === \"turn\"\n ? TURN_WORKER_MAX_CONCURRENT_TURNS\n : CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES,\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\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 signalCodexCapacityWorkflow: SignalCodexCapacityWorkflow;\n check: () => Promise<void>;\n close: () => Promise<void>;\n}> {\n const connection = await Connection.connect({ address: settings.temporalHost });\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 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 only bounded DB outbox repair;\n * it never reads/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({ address: settings.temporalHost });\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({ address: settings.temporalHost });\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({ address: settings.temporalHost });\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 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 controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n let bus: Awaited<ReturnType<typeof createNatsEventBus>> | undefined;\n let signaler: Awaited<ReturnType<typeof createWorkerWorkflowSignaler>> | undefined;\n let workerBundle: Awaited<ReturnType<typeof createOpenGeniWorker>> | undefined;\n let reaperSchedule: Awaited<ReturnType<typeof registerSandboxReaperSchedule>> | undefined;\n let fileUploadReaperSchedule:\n | Awaited<ReturnType<typeof registerFileUploadReaperSchedule>>\n | undefined;\n let workflowWakeDispatcherSchedule:\n | Awaited<ReturnType<typeof registerSessionWorkflowWakeDispatcherSchedule>>\n | undefined;\n let httpServer: ReturnType<typeof startWorkerHttpServer> | undefined;\n try {\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 signaler = await retryStartupDependency(\n \"Temporal client\",\n () => createWorkerWorkflowSignaler(settings, dbClient.db),\n { ...retryOptions, onRetry },\n );\n workerBundle = await createOpenGeniWorker({\n role,\n settings,\n activityDependencies: {\n observability,\n wakeSessionWorkflow: signaler.wakeSessionWorkflow,\n signalCodexCapacityWorkflow: signaler.signalCodexCapacityWorkflow,\n db: dbClient.db,\n bus,\n },\n });\n httpServer = startWorkerHttpServer({\n settings,\n observability,\n checks: {\n db: dbReadyCheck(dbClient.db),\n nats: natsReadyCheck(bus),\n temporal: signaler.check,\n },\n });\n // Control workers alone own global schedules. Turn workers poll only the\n // bounded inference activity queue and can never duplicate schedule setup.\n if (role === \"control\") {\n reaperSchedule = await retryStartupDependency(\n \"Temporal schedule (sandbox reaper)\",\n () => registerSandboxReaperSchedule(settings, observability),\n { ...retryOptions, onRetry },\n );\n fileUploadReaperSchedule = await retryStartupDependency(\n \"Temporal schedule (file upload reaper)\",\n () => registerFileUploadReaperSchedule(settings, observability),\n { ...retryOptions, onRetry },\n );\n workflowWakeDispatcherSchedule = await retryStartupDependency(\n \"Temporal schedule (session-workflow wake dispatcher)\",\n () => registerSessionWorkflowWakeDispatcherSchedule(settings, observability),\n { ...retryOptions, onRetry },\n );\n }\n observability.info(\"OpenGeni worker listening\", {\n role,\n temporalTaskQueue:\n role === \"control\" ? settings.temporalTaskQueue : turnTaskQueue(settings.temporalTaskQueue),\n maxConcurrentActivityTaskExecutions:\n role === \"turn\"\n ? TURN_WORKER_MAX_CONCURRENT_TURNS\n : CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES,\n maxConcurrentWorkflowTaskExecutions:\n role === \"control\" ? CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS : 0,\n httpPort: settings.workerHttpPort,\n });\n // GRACEFUL DEPLOY SHUTDOWN — the missing link that made every deploy a\n // worker_death. The worker is the container's MAIN process (PID 1), and a\n // PID-1 process with no explicit handler IGNORES SIGTERM: the pod sat\n // through the entire terminationGracePeriodSeconds doing nothing, then the\n // kubelet SIGKILLed it — so agent-turn's worker-shutdown checkpoint path\n // (same-turn recovery + run-state save) never once ran in production\n // (forensics 2026-07-06: every observed recovery was\n // reason=worker_death). This handler starts the drain the moment k8s asks:\n // shutdown() stops polling, then (per shutdownGraceTime/ForceTime above)\n // cancels in-flight activities with WORKER_SHUTDOWN so long turns\n // checkpoint INSIDE the grace window. run() resolves once\n // drained and the finally below closes connections cleanly.\n let shutdownRequested = false;\n const requestShutdown = (signal: string) => {\n if (shutdownRequested) {\n return;\n }\n shutdownRequested = true;\n observability.info(\"OpenGeni worker draining (graceful shutdown)\", { signal });\n try {\n workerBundle!.worker.shutdown();\n } catch (error) {\n observability.warn(\"worker shutdown request failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n process.on(\"SIGTERM\", () => requestShutdown(\"SIGTERM\"));\n process.on(\"SIGINT\", () => requestShutdown(\"SIGINT\"));\n await workerBundle.worker.run();\n } finally {\n httpServer?.stop(true);\n await Promise.allSettled([\n workerBundle?.connection.close(),\n signaler?.close(),\n reaperSchedule?.close(),\n fileUploadReaperSchedule?.close(),\n workflowWakeDispatcherSchedule?.close(),\n bus?.close(),\n dbClient.close(),\n ]);\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 IndexDocumentInput,\n MaybeContinueGoalInput,\n MaybeContinueGoalResult,\n CodexCapacityWaitRef,\n GetCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitResult,\n RecoverDispatchInput,\n RecoverDispatchResult,\n RunAgentTurnInput,\n RunAgentTurnResult,\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 (SPIKE-1 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 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 P4a — 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 recoverDispatch = defaultControlActivities.recoverDispatch;\nexport const peekSessionWork = defaultControlActivities.peekSessionWork;\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 applySessionTurnSettlement,\n requestSessionTurnRecovery,\n claimSessionWorkForAttempt,\n applyCreditDebitUpToBalance,\n getBillingBalance,\n getRigName,\n getRigVersion,\n getSandbox,\n readActiveSandbox,\n setActiveSandbox,\n requireFile,\n getSessionEvent,\n getSessionGoal,\n getLatestRunState,\n isCodexBilledTurn,\n workspaceCodexSubscriptionActive,\n acquireCodexCredentialLease,\n armCodexCapacityWait,\n heartbeatCodexCredentialLeaseUntil,\n releaseCodexCredentialLease,\n CODEX_CREDENTIAL_LEASE_TTL_MS,\n getCodexRotationSettings,\n getWorkspaceModelPolicy,\n listCodexAccountStatuses,\n fetchCodexUsageForAccount,\n getSessionCodexState,\n recordSessionActiveCodexCredential,\n setSessionCodexPin,\n recordCodexAccountUsageWithWakeTargets,\n recordCodexAccountConnectors,\n quarantineCodexCredentialForLease,\n setActiveCodexCredential,\n resolveWorkspaceMemoryBlock,\n setCodexCredentialExhaustedWithWakeTargets,\n withCodexCapacityMutation,\n countConsecutiveReactiveRotations,\n requireSession,\n recordUsageEvent,\n registerPendingSessionToolCall,\n recordPendingSessionToolCallResult,\n clearDurablePendingSessionToolCalls,\n appendSessionHistoryItems,\n isSessionCompactionRequested,\n countSessionHistoryItems,\n getActiveSessionHistoryItems,\n nextSessionHistoryPosition,\n settleCodexCredentialLeaseLoss,\n settleCodexCredentialFailover,\n saveRunState,\n upsertSandboxSessionEnvelope,\n setSessionLastInputTokensForTurnAttempt,\n sumUsageQuantity,\n heartbeatLeaseHolder,\n accrueWarmSeconds,\n getMaterializedSandboxFileResources,\n markSandboxFileResourcesMaterialized,\n SandboxLeaseSupersededError,\n SandboxImageConflictError,\n buildConnectionTokenResolver,\n getEnrollment,\n abandonRecordingForTurnAttempt,\n type AppendEventInput,\n type ActiveSandboxPointer,\n type SandboxRecord,\n type CodexCredentialLeaseResult,\n type CodexCredentialLeaseSelectionContext,\n type SessionTurnRecordingSettlement,\n} from \"@opengeni/db\";\nimport { appendAndPublishTurnEventsFenced, publishDurableSessionEvents } from \"@opengeni/events\";\nimport {\n sandboxStateEntryFromRunState,\n maxTurnsExceededRunState,\n modelCallUsageTelemetry,\n modelResponseUsageFromSdkEvent,\n normalizeSdkEvent,\n sanitizeHistoryItemsForModel,\n isEphemeralInternalContext,\n appendPersistentSessionSettings,\n appendSessionInstructions,\n appendWorkspaceMemory,\n composeAgentInstructions,\n summarizeForCompaction,\n ensureModalRegistryImage,\n findCompactionNeededError,\n materializeSandboxFileDownloads,\n refreshGitProviderTokenFiles,\n sandboxFileDownloadFailureNote,\n SUMMARY_BUFFER_TOKENS,\n runOwnedSandboxSetup,\n swapTargetEstablishability,\n type SandboxFileDownload,\n type SandboxFileDownloadFailure,\n type OpenGeniRuntime,\n type ComputerToolMode,\n type ModelResponseUsage,\n type BuildAgentOptions,\n type BackendUnresolvableCode,\n type EstablishedSandboxSession,\n type GitCredentialTokenWriterSession,\n deleteRecordingArtifacts,\n stopRecording as stopRecordingOnBox,\n} from \"@opengeni/runtime\";\nimport {\n builtinProviderId,\n calculateModelUsageCostMicros,\n configuredModelPricing,\n configuredStaticUsageLimits,\n sandboxWarmRateMicrosPerSecond,\n settingsWithResolvedModelContext,\n type ModelUsageInput,\n type ModelProviderApi,\n type RegistryProviderKind,\n type Settings,\n} from \"@opengeni/config\";\nimport { CancelledFailure } from \"@temporalio/activity\";\nimport {\n settingsWithCodexCredential,\n settingsWithEnabledCapabilityMcpServers,\n settingsWithSessionMcpServersForRun,\n} from \"./capabilities\";\nimport {\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 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 CodexReloginRequired,\n classifyCodexUsageLimitError,\n codexRequestStorage,\n isCodexTransportError,\n type CodexRequestContext,\n type CodexUsageHeaderSnapshot,\n} from \"@opengeni/codex\";\nimport { mergeResourceRefs, mergeToolRefs } from \"./common\";\nimport { maybeCompactContext } from \"./context-compaction\";\nimport { TurnAttemptFencedError } from \"./turn-attempt-fenced\";\nimport {\n loadWorkspaceEnvironmentForRunWithCredentials,\n mintRunGitCredentials,\n sandboxEnvironmentForRun,\n type MintedRunGitCredentials,\n} from \"./environment\";\nimport {\n startGitCredentialRenewalLoop,\n type GitCredentialRenewalController,\n} from \"./git-credential-renewal\";\nimport { withCodexAppsTool, withFirstPartyTools } from \"./goals\";\nimport {\n mergeRigDefaultVariableSetEnvironment,\n resolveWorkspaceAgentInstructions,\n resolveWorkspacePackRuntime,\n settingsWithPackSandboxImage,\n settingsWithRigImage,\n} from \"./packs\";\nimport { notifyParentOfChildTerminal } from \"./parent-wake\";\nimport { createSecretRedactor, identityRedactor } from \"./redaction\";\nimport { applyCodexHistoryStrip, turnInput, type TurnCodexAccount } from \"./run-input\";\nimport {\n createRuntimeBatcher,\n currentActivityContext,\n nextStreamEvent,\n startActivityHeartbeat,\n} from \"./streaming\";\nimport type { ActivityServices, RunAgentTurnInput, RunAgentTurnResult } from \"./types\";\nimport {\n resumeBoxForTurn,\n acquireSelfhostedLeaseForTurn,\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 } 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 evaluateWorkspaceModelPolicy,\n type GitCredentialProvider,\n type ResourceRef,\n type SessionEvent,\n type SessionEventType,\n type SessionStatus,\n} from \"@opengeni/contracts\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\n// How long the session workflow holds the loop after a retryable provider\n// failure before the goal continuation re-enters the model. Azure/OpenAI TPM\n// throttling is minute-granular; anything shorter mostly burns continuation\n// budget against the same window.\nexport const PROVIDER_BACKPRESSURE_DELAY_MS = 60_000;\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(): {\n status: \"recovering\";\n continueDelayMs: number;\n} {\n return {\n status: \"recovering\",\n continueDelayMs: PROVIDER_BACKPRESSURE_DELAY_MS,\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 const { sessionPinnedCredentialId: pin, activeCredentialId: active, connectedIds } = args;\n if (pin && connectedIds.has(pin)) {\n return pin;\n }\n if (active && connectedIds.has(active)) {\n return active;\n }\n return null;\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/**\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\nfunction compactionFailureReason(reason: string): string {\n return reason.startsWith(\"compaction summarization failed:\")\n ? reason\n : `compaction summarization failed: ${reason}`;\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 `-32001 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 matched = 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 if (!matched) {\n return null;\n }\n const message = error instanceof Error ? error.message : String(error);\n return {\n message,\n ...(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\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 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 // 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<void> {\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;\n }\n if (input.emittedSourceKeys?.has(input.sourceKey)) return;\n const telemetry = modelCallUsageTelemetry(usage as Parameters<typeof modelCallUsageTelemetry>[0]);\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;\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 reasoningTokens: telemetry.reasoningTokens,\n ...(input.servingAccountHash !== undefined\n ? { servingAccountHash: input.servingAccountHash }\n : {}),\n ...(input.accountChangedFromPrevCall !== undefined\n ? { accountChangedFromPrevCall: input.accountChangedFromPrevCall }\n : {}),\n });\n } catch {\n // Durable event + billing already committed; logging is best-effort only.\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): {\n rows: Array<{ position: number; item: Record<string, unknown> }>;\n nextWatermark: number;\n nextPosition: number;\n} {\n const sanitized = sanitizeHistoryItemsForModel(rawHistory).filter(\n (item) => !isEphemeralInternalContext(item),\n );\n if (sanitized.length <= persistedHistoryCount) {\n return { rows: [], nextWatermark: persistedHistoryCount, nextPosition };\n }\n const rows = sanitized.slice(persistedHistoryCount).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\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 * Seed the turn-end reconcile watermark (`persistedHistoryCount`) from EXACTLY the\n * view `state.history` was seeded from, so the model-input length and the watermark\n * can NEVER disagree. The watermark is the slice index the reconcile cuts the\n * (re-sanitized) `state.history` at to find this turn's genuinely-new items, so it\n * must equal the length of `state.history`'s already-persisted leading prefix.\n *\n * The cross-account reasoning strip drops foreign reasoning items, so the prefix\n * length is PATH-DEPENDENT, captured by `modelHistoryFromItems`:\n *\n * - items read path (`modelHistoryFromItems === true`) — `state.history` was seeded\n * from the cross-account-STRIPPED active items (foreign reasoning DROPPED), so it\n * starts K shorter than the raw active-row count. Seed from the SAME strip\n * (HOLE D); seeding from the un-stripped count would slice K genuinely-new items\n * off the reconcile and silently lose them (incl. the user's switch-turn message).\n *\n * - approval RunState path (`modelHistoryFromItems === false`) — `state.history` was seeded\n * from the blob, where foreign reasoning is NEUTRALIZED-IN-PLACE (the item is\n * KEPT, only its id/encrypted_content go — see resumeRunStateForCodexAccount), so\n * the blob's history length still COUNTS those items. Applying the strip here\n * under-counts by K and the reconcile re-appends K already-persisted items at\n * fresh positions — HOLE E. So the blob path must NOT strip: count the raw\n * sanitized active length, which mirrors the blob's completed prefix.\n *\n * On a same-account / non-codex turn the strip is a no-op, so both branches reduce\n * to the same raw sanitized count (byte-identical to the pre-strip behaviour).\n * Pure; exported for unit testing the D/E seed invariant.\n */\nexport function reconcileSeedCount(\n activeSeedRows: ReadonlyArray<{\n item: Record<string, unknown>;\n producerCodexCredentialId: string | null;\n }>,\n modelHistoryFromItems: boolean,\n current: TurnCodexAccount,\n): number {\n return sanitizeHistoryItemsForModel(\n modelHistoryFromItems\n ? applyCodexHistoryStrip(activeSeedRows, current)\n : activeSeedRows.map((row) => row.item),\n ).length;\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 error,\n );\n return undefined;\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. Packs can override `modalImageRef` per workspace/turn, so a\n * private pack image must be resolved before sandbox creation or Modal falls\n * back to the unauthenticated `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.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 → \"function-text\": it takes\n * function tools but can't read structured image results, so screenshots render\n * as a text data-URL.\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 } | null,\n): ComputerToolMode {\n if (!resolvedModel) {\n return \"hosted\"; // legacy built-in Responses client — real hosted support\n }\n if (resolvedModel.provider.kind === \"codex-subscription\") {\n return \"function-image\";\n }\n if (resolvedModel.provider.api === \"chat\") {\n return \"function-text\";\n }\n return \"hosted\";\n}\n\nexport type TurnSandboxProvisioner<T> = {\n get(): Promise<T>;\n hasStarted(): boolean;\n waitForSettled(timeoutMs: number): Promise<T | null>;\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 (error instanceof SandboxImageConflictError) {\n return false;\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\nexport function createTurnSandboxProvisioner<T>(\n establish: () => Promise<T>,\n options: {\n maxRetries?: number;\n backoffMs?: number;\n onStarted?: () => Promise<void> | void;\n onCompleted?: () => Promise<void> | void;\n onFailed?: (error: unknown) => 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 return await establish();\n } catch (error) {\n if (attempt >= maxRetries || !isLazySandboxProvisionRetryable(error)) {\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 await options.onStarted?.();\n try {\n const result = await run();\n await options.onCompleted?.();\n return result;\n } catch (error) {\n await options.onFailed?.(error);\n throw error;\n }\n })().catch((error) => {\n memo = null;\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\nfunction sdkBackendIdForSandboxBackend(backend: Settings[\"sandboxBackend\"]): string {\n return backend === \"local\" ? \"unix_local\" : backend;\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 over-threshold (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: CodexAccountStatus[],\n capacitySignals: {\n signalCodexCapacityWorkflow?: ActivityServices[\"signalCodexCapacityWorkflow\"] | undefined;\n wakeSessionWorkflow: ActivityServices[\"wakeSessionWorkflow\"];\n },\n): Promise<CodexAccountStatus[]> {\n const nearPct = settings.codexRotationNearExhaustionPct;\n const stale = accounts.filter(\n (a) =>\n a.status === \"active\" &&\n ((a.primaryUsedPercent ?? 0) >= nearPct || (a.secondaryUsedPercent ?? 0) >= nearPct),\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 signalCodexCapacityWorkflow,\n entitlements,\n connectionCredentials,\n } = await services();\n const activityContext = currentActivityContext();\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 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 let isCodexTurn = false;\n let executionGeneration = 0;\n // Still required by credential-loss/capacity settlements, whose own\n // recovery transactions fence against worker-death redispatches.\n let redispatchesAtDispatch = 0;\n const saveRunStateFenced = async (state: Parameters<typeof saveRunState>[1]): Promise<void> => {\n if (!(await saveRunState(db, state))) {\n throw new TurnAttemptFencedError(\n \"turn execution generation was fenced while saving run state\",\n );\n }\n };\n const setLastInputTokensFenced = async (lastInputTokens: number): 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 // OPE-21: 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 // 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 // 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 // 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 // OPE-41: 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 gitCredentialRenewal: GitCredentialRenewalController | null = null;\n let gitCredentialRenewalClosed = 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 // 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 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 }) => Promise<boolean>)\n | null = null;\n let turnStartedPublished = false;\n let stream: Awaited<ReturnType<OpenGeniRuntime[\"runStream\"]>> | undefined;\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\", 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 }).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 if (snapshotSession && !snapshotInFlight) {\n snapshotInFlight = maybePersistWarmWorkspaceSnapshot(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: heartbeatGroupId,\n },\n snapshotSession,\n heartbeatEpoch,\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 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 // 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 );\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 // Tag each row with the codex account that produced it (null on the\n // non-codex path). Resolved at line ~504 before any reconcile pass\n // runs, so this is the turn's effective account. The read path uses\n // it to strip cross-account reasoning.encrypted_content next turn.\n producerCodexCredentialId: effectiveCodexCredentialId,\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(\"session history dual-write failed (run unaffected)\", persistError);\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 let redact: (payload: unknown) => unknown = identityRedactor;\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 // Multi-account P4 (Part A): 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 // 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 (P2-b) and thread it through both the\n // routing overlay (settingsWithCodexCredential) and the billed-turn predicate\n // (isCodexBilledTurn below), so a concurrent disconnect/reconnect cannot make\n // provider-injection and billing disagree about whether this is a codex turn.\n const codexSubscriptionActive = await workspaceCodexSubscriptionActive(\n db,\n mcpSettings,\n input.workspaceId,\n );\n const capabilitySettings = await settingsWithCodexCredential(\n db,\n input.workspaceId,\n mcpSettings,\n codexSubscriptionActive,\n );\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 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 triggerType = trigger.type;\n executionGeneration = turn.executionGeneration;\n const latestTurnState = await getLatestRunState(db, input.workspaceId, input.sessionId);\n const continuationCodexCredentialId =\n latestTurnState?.turnId === turnId ? latestTurnState.frozenCodexCredentialId : null;\n redispatchesAtDispatch = Number(\n (turn.metadata as { workerDeathRedispatches?: number } | null)?.workerDeathRedispatches ??\n 0,\n );\n turnLifecycleMetricsFor(observability).start(turnId);\n // Canonical codex-billed predicate (codex/<slug> + feature enabled + active\n // workspace credential). Computed once and threaded through every billing\n // gate + the usage recorder so a turn paid by the user's ChatGPT/Codex plan\n // consumes ZERO OpenGeni credits and never feeds an OpenGeni cap. Resolved\n // here (before resolvedModel at the routing step) because the pre-turn gate\n // below needs it; mirrors the same active-credential read the codex provider\n // overlay uses, so billing and routing agree on what \"codex\" is.\n isCodexTurn = await isCodexBilledTurn({\n db,\n settings,\n workspaceId: input.workspaceId,\n model: turn.model,\n active: codexSubscriptionActive,\n });\n // §7.5 P3 — pass BOTH the codex predicate (codex-plan turns bypass the gate)\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 ensureRunAllowed(\n settings,\n db,\n input.accountId,\n input.workspaceId,\n isCodexTurn,\n entitlements,\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 // 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 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 Bun.sleep(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 inputs = inputSettlement.events.map((event) => ({\n ...event,\n payload: redact(event.payload),\n turnId: turnId!,\n producerId,\n producerSeq: ++producerSeq,\n }));\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 ...(recordingMutation ? { recording: recordingMutation } : {}),\n });\n if (result.action === \"stale\") {\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 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 continuationCredentialId: continuationCodexCredentialId,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\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 continuationCredentialId: continuationCodexCredentialId,\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 continuationCredentialId: continuationCodexCredentialId,\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 // OPE-31 pin persistence follows the atomic OPE-21 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 eligibleCount = leased.accounts.filter((account) =>\n isCodexCredentialEligible(account, settings.codexRotationNearExhaustionPct, 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 if (goal?.status === \"active\") {\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: goal.id,\n goalVersion: goal.version,\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 = \"failed\";\n activityStatus = \"idle\";\n return claimedResult({\n status: \"idle\",\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 {\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 if (goalActive && goal) {\n const authoritativeResetAt = authoritativeCodexCapacityResetAt(\n leased.accounts,\n settings.codexRotationNearExhaustionPct,\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: goal.id,\n goalVersion: goal.version,\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 = \"failed\";\n activityStatus = \"idle\";\n return claimedResult({\n status: \"idle\",\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` (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 // P4: surface the dropped-connector note when this rotation pick couldn't\n // cover the session's used connectors (a Tier-2/unknown failover); the pill\n // renders the badge. Omitted when the switch covered everything (the norm).\n const droppedConnectors =\n rotationDecision.kind === \"active\" ? rotationDecision.droppedConnectors : undefined;\n await publish([\n {\n type: \"codex.account.switched\",\n payload: {\n fromAccountId: priorAccountId,\n toAccountId: effectiveCodexCredentialId,\n reason: rotated ? \"rotation\" : \"manual\",\n ...(droppedConnectors && droppedConnectors.length > 0\n ? { droppedConnectors }\n : {}),\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 = await resolveWorkspacePackRuntime(db, input.workspaceId);\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 workspaceAgentInstructions = await resolveWorkspaceAgentInstructions(\n db,\n input.workspaceId,\n );\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(capabilitySettings, packRuntime.sandboxImage),\n rigVersion?.image ?? null,\n ),\n openaiModel: turn.model,\n openaiReasoningEffort: turn.reasoningEffort,\n sandboxBackend: turn.sandboxBackend,\n };\n const runSettings = await settingsWithSessionMcpServersForRun(\n db,\n input.workspaceId,\n input.sessionId,\n baseRunSettings,\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(capabilitySettings, turn.model);\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 const 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 (null → the built-in\n // OpenAI/Azure client, attributed here via builtinProviderId so a policy\n // blocking the built-in also blocks that fallback — this exact path is\n // how bare-model turns silently spent real Azure money in a\n // codex-intended workspace). Fail-loud, never a silent remap.\n {\n const workspaceModelPolicy = await getWorkspaceModelPolicy(db, input.workspaceId);\n if (workspaceModelPolicy) {\n const effectiveProviderId = resolvedModel\n ? resolvedModel.provider.id\n : builtinProviderId(capabilitySettings);\n const verdict = evaluateWorkspaceModelPolicy(workspaceModelPolicy, {\n providerId: effectiveProviderId,\n modelId: turn.model,\n });\n if (!verdict.allowed) {\n throw new WorkspaceModelPolicyBlockedError(\n turn.model,\n effectiveProviderId,\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 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 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: resolver.getToken,\n refresh: 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 };\n })()\n : null;\n const withCodex = <T>(fn: () => Promise<T>): Promise<T> =>\n codexContext ? codexRequestStorage.run(codexContext, fn) : fn();\n const promptCacheKey = acceptsPromptCacheKeyForTurn(resolvedModel)\n ? input.sessionId\n : undefined;\n let compactionUsageCount = 0;\n const recordCompactionUsage = async (usage: ModelResponseUsage) => {\n await recordCompletedModelCallBeforeOwnershipFences({\n renewLease: () => renewCodexLease(\"model_usage\"),\n leaseLost: () => codexLeaseLost,\n leaseLostMessage: \"Codex credential lease expired during context compaction\",\n recordUsage: async () => {\n compactionUsageCount += 1;\n const sourceKey = modelUsageSourceKey({\n responseId: usage.responseId,\n dispatchId: modelUsageDispatchId,\n positionalKey: `compaction-${compactionUsageCount}`,\n });\n const responseAccountCtx = modelCallAccountContext({\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n isFirstCallOfTurn: compactionUsageCount === 1,\n });\n await recordModelUsageAndDebitCredits(settings, db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n model: resolvedModel?.configured.id ?? turn.model,\n isCodexTurn,\n usage: usage.usage,\n sourceKey,\n observability,\n });\n await emitModelCallUsage({\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 sourceKey,\n usage,\n servingAccountHash: responseAccountCtx.servingAccountHash,\n accountChangedFromPrevCall: responseAccountCtx.accountChangedFromPrevCall,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n });\n },\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: resolvedModel.configured.id,\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 maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n onUsage: recordCompactionUsage,\n ...(systemInstructions ? { systemInstructions } : {}),\n ...(promptCacheKey ? { promptCacheKey } : {}),\n });\n\n if (turn.source === \"compaction\") {\n const persistentSessionSettings = {\n titleIsSet: Boolean(session.title?.trim()),\n };\n const compactionInstructions = appendPersistentSessionSettings(\n appendSessionInstructions(\n appendWorkspaceMemory(\n composeAgentInstructions(\n workspaceAgentInstructions ?? modelRunSettings.agentInstructionsTemplate,\n undefined,\n rigVersion && rigName ? { name: rigName, version: rigVersion.version } : undefined,\n ),\n workspaceMemory ?? undefined,\n ),\n session.instructions ?? undefined,\n ),\n persistentSessionSettings,\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 outcome = await 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 },\n );\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, \"operator\");\n }\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n outcome.events,\n );\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) — so set_session_title and the rest are\n // always reachable. Idempotent: mergeToolRefs dedupes if already present.\n // Attach codex_apps (the ChatGPT/Codex connectors MCP) when the codex\n // overlay injected it into runSettings.mcpServers (active subscription +\n // connector scopes); no-op for every other turn. Its refreshing bearer is\n // resolved at connect time from the codex ALS (see the withCodex-wrapped\n // prepareTools call below).\n const turnTools = withCodexAppsTool(\n runSettings,\n withFirstPartyTools(runSettings, mergeToolRefs(session.tools, turn.tools)),\n );\n // §7.6 P4a — 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 loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n session.variableSetId,\n connectionCredentials?.sandboxSecrets,\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 loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n rigDefaultVariableSetId,\n connectionCredentials?.sandboxSecrets,\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 redact = createSecretRedactor(\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 await ensureTurnModalRegistryImage(runSettings, sandboxCreationBackend);\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 const {\n environment: sandboxEnvironment,\n gitToken: sandboxGitToken,\n gitTokens: sandboxGitTokens,\n gitTokenExpiresAt: sandboxGitTokenExpiresAt,\n toolspaceToken: sandboxToolspaceToken,\n } = await 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 gitCredentials: connectionCredentials?.gitCredentials,\n sessionId: input.sessionId,\n runId: turnId,\n },\n );\n\n const initialGitCredentials: MintedRunGitCredentials | undefined = sandboxGitTokens\n ? {\n gitTokens: sandboxGitTokens,\n expiresAt: sandboxGitTokenExpiresAt ?? {},\n }\n : undefined;\n const attachGitCredentialRenewal = async (\n tokenSession: GitCredentialTokenWriterSession,\n initial: MintedRunGitCredentials | undefined,\n ): Promise<void> => {\n if (!initial || Object.keys(initial.gitTokens).length === 0) return;\n const previous = gitCredentialRenewal;\n gitCredentialRenewal = null;\n await previous?.stop();\n if (gitCredentialRenewalClosed) return;\n\n const providers = Object.keys(initial.gitTokens) as GitCredentialProvider[];\n const controller = startGitCredentialRenewalLoop({\n expectedProviders: providers,\n initialExpiresAt: initial.expiresAt,\n mint: async () =>\n await mintRunGitCredentials(runSettings, turnResources, {\n scope: connectionScope,\n gitCredentials: connectionCredentials?.gitCredentials,\n }),\n write: async (tokens) => {\n const runAs = sandboxRunAs(runSettings);\n await refreshGitProviderTokenFiles(tokenSession, tokens, {\n ...(runAs ? { runAs } : {}),\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 if (gitCredentialRenewalClosed) {\n await controller.stop();\n return;\n }\n gitCredentialRenewal = 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 sandboxHolderId = sandboxLeaseHolderIdForAttempt(input.attemptId);\n sandboxGroupId = session.sandboxGroupId;\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 a phantom Modal home box (today's path leased + BILLED\n // a cloud box the turn never touched). Build the SelfhostedSession DIRECTLY\n // (no Modal box created) and take the group lease with backend \"selfhosted\"\n // (refcount/idle bookkeeping; the reaper drains it cold with NO provider\n // stop, and bills ZERO warm-seconds). The session is a harmless in-memory\n // bind (no NATS round-trip), so build it FIRST; if the lease then fences,\n // there is nothing to clean up.\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 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 const lease = await acquireSelfhostedLeaseForTurn(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n sessionId: input.sessionId,\n },\n \"turn\",\n sandboxHolderId,\n );\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 },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\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 leaseEpoch: lease.leaseEpoch,\n release: lease.release,\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 resumeBoxForTurn(\n {\n db,\n settings,\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 → recreate on the new image; N-holders →\n // SandboxImageConflictError surfaced as an actionable turn error). Prefer the\n // explicit Modal image ref, else the docker image. The selfhosted branch\n // (establishSelfhostedTurnSession/acquireSelfhostedLeaseForTurn) 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 // recreate / N-holders SandboxRigConflictError). Omitted for a rig-less\n // turn -> never stamped or enforced (shares exactly as today).\n ...(rigVersion ? { rigVersionId: rigVersion.id } : {}),\n },\n \"turn\",\n sandboxHolderId,\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 if (routingEnabled(settings)) {\n resolvedSandbox = {\n ...resolvedSandbox,\n established: wrapTurnBoxWithRouting(\n { db, settings, bus },\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 },\n resolvedSandbox.established,\n ),\n };\n }\n }\n if (resolvedSandbox) {\n startLeaseHeartbeat(resolvedSandbox, activeSandboxBackend ?? groupBoxBackend);\n }\n }\n\n const fileResourceDownloads = await sandboxFileDownloadsForRun(\n runSettings,\n db,\n objectStorage,\n input.workspaceId,\n turnResources,\n );\n throwIfWorkerShuttingDown();\n // Wrap MCP prep in the codex ALS so the codex_apps connect handshake\n // (initialize + tools/list) can resolve the per-workspace bearer from\n // codexRequestStorage (runtime/codexAppsMcpRequestInit). withCodex is the\n // identity on every non-codex turn, so this is a no-op for existing paths.\n const resolveCredential = buildConnectionTokenResolver(db, runSettings);\n preparedTools = await withCodex(() =>\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 resolveCredential,\n onAuthNeeded: async (payload) => {\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 }),\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 agent = runtime.buildAgent(modelRunSettings, turnResources, {\n reasoningEffort: turn.reasoningEffort,\n genesisTitleHint: isGenesisTurn,\n persistentSessionSettings: {\n titleIsSet: Boolean(session.title?.trim()),\n },\n sandboxEnvironment,\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\" && !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, turn TTL,\n // budgeted, approval-tools excluded). The runtime seeds it to the box's\n // token file over the same exec channel, off-manifest, on every backend.\n ...(sandboxToolspaceToken ? { toolspaceTokenSeed: sandboxToolspaceToken } : {}),\n ...(activeSandboxBackend ? { activeSandboxBackend } : {}),\n fileResourceDownloads,\n mcpServers: preparedTools.mcpServers,\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 // only when the model opts in; the effective context window drives the\n // compaction threshold.\n ...(resolvedModel\n ? {\n hostedWebSearch: resolvedModel.configured.hostedWebSearch,\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: resolvedModel.provider.kind !== \"codex-subscription\",\n // EXPLICIT computer-use tool transport, derived from the resolved provider's\n // authoritative wire identity (codex → function-image, chat → function-text,\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 ...(workspaceAgentInstructions ? { instructionsTemplate: workspaceAgentInstructions } : {}),\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 ...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 (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 let lazyEstablishmentOrigin: EstablishedSandboxSession[\"origin\"] | null = null;\n turnSandboxProvisioner = createTurnSandboxProvisioner<ResumedTurnSandbox>(\n async () => {\n throwIfWorkerShuttingDown();\n const lazyGitCredentials =\n activeSandboxBackend === \"selfhosted\"\n ? undefined\n : await mintRunGitCredentials(runSettings, turnResources, {\n scope: connectionScope,\n gitCredentials: connectionCredentials?.gitCredentials,\n });\n const lazyGitTokens = lazyGitCredentials?.gitTokens;\n const provisioned = await resumeBoxForTurn(\n {\n db,\n settings,\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 lazyEstablishmentOrigin = provisioned.established.origin ?? null;\n setupBoxSession = provisioned.established.session;\n await publishSandboxLifecycleEvents(provisioned);\n await runOwnedSandboxSetup(\n agent,\n provisioned.established.session as never,\n provisioned.established.session 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 },\n );\n await attachGitCredentialRenewal(\n provisioned.established.session as GitCredentialTokenWriterSession,\n lazyGitCredentials,\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 resolvedSandbox = provisioned;\n startLeaseHeartbeat(provisioned, activeSandboxBackend ?? groupBoxBackend);\n return provisioned;\n },\n {\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 () => {\n await publish?.(\n [\n {\n type: \"sandbox.operation.completed\",\n payload: {\n name: \"sandbox.provision\",\n ...(lazyEstablishmentOrigin ? { origin: lazyEstablishmentOrigin } : {}),\n },\n },\n ],\n true,\n );\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 },\n );\n lazyOwnedSandbox = wrapLazyTurnBoxWithRouting(\n {\n db,\n settings,\n bus,\n onOp: machineOpObserver.observer,\n },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\n },\n {\n client: lazyClient,\n backendId: sdkBackendIdForSandboxBackend(groupBoxBackend),\n agentDefaultManifest,\n provisioner: turnSandboxProvisioner,\n },\n );\n }\n const compactSummarizer = compactionSummarizerFor(\n typeof agent.instructions === \"string\" ? agent.instructions : undefined,\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 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 const forced = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);\n const outcome = await 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 }\n : { trigger: \"auto\" },\n );\n if (outcome.compacted) {\n const compactionTrigger = forced ? \"operator\" : undefined;\n recordContextCompaction(observability, compactionTrigger ?? \"auto\");\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n outcome.events,\n );\n }\n } catch (compactError) {\n observability.error(\"context compaction failed\", {\n sessionId: input.sessionId,\n turnId,\n error: compactError instanceof Error ? compactError.message : String(compactError),\n });\n throw compactError;\n }\n }\n let fileMaterializationFailures: SandboxFileDownloadFailure[] = [];\n let fileDownloadsMaterializedForRun = false;\n if (\n resolvedSandbox &&\n setupBoxSession &&\n activeSandboxBackend !== \"selfhosted\" &&\n fileResourceDownloads.length > 0\n ) {\n const boxInstanceId = resolvedSandbox.established.instanceId;\n const alreadyMaterialized = await getMaterializedSandboxFileResources(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n expectedEpoch: resolvedSandbox.leaseEpoch,\n instanceId: boxInstanceId,\n });\n const downloadsToMaterialize = filterUnmaterializedSandboxFileDownloads(\n fileResourceDownloads,\n alreadyMaterialized,\n );\n const runAs = sandboxRunAs(runSettings);\n if (downloadsToMaterialize.length > 0) {\n const materialized = 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 },\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 (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 // Cross-account reasoning strip: pass THIS turn's codex account so every\n // history read path (items + run-state replay) drops reasoning produced by\n // a DIFFERENT codex account. effectiveCodexCredentialId is the resolved\n // codex credential on a codex turn (pin > workspace-active) and null on a\n // non-codex turn OR a codex turn with no usable account — exactly the\n // \"current account\" the single strip rule compares against (null is the\n // built-in/Azure account, so a non-codex turn still drops codex-produced\n // reasoning, and a no-codex-history session is a byte-for-byte no-op).\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(\n db,\n runtime,\n agent,\n trigger,\n { currentCodexCredentialId: effectiveCodexCredentialId },\n {\n turnId: activeTurnId,\n recovering: turn.executionGeneration > 1,\n ...(unavailableSandboxFilesNote ? { unavailableSandboxFilesNote } : {}),\n },\n );\n runInput = prepared.input;\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 const activeSeedRows = await getActiveSessionHistoryItems(\n db,\n input.workspaceId,\n input.sessionId,\n );\n // Seed the reconcile watermark from EXACTLY the view the model's\n // `state.history` was seeded from (items strip on the items path = HOLE D; NO\n // strip on the run-state blob path, where foreign reasoning is neutralized but\n // KEPT = HOLE E), so the model-input length and the watermark never disagree.\n persistedHistoryCount = reconcileSeedCount(activeSeedRows, prepared.modelHistoryFromItems, {\n currentCodexCredentialId: effectiveCodexCredentialId,\n });\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 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 signal; provider overflows do not,\n // so null derives decision metadata from active history. Forced\n // recovery proves progress separately by comparing the replacement\n // with the current active-history estimate in maybeCompactContext.\n recoverySignalTokens,\n compactSummarizer,\n {\n force: true,\n ...(triggerLabel === \"operator\" ? { clearRequestedCompaction: true } : {}),\n trigger: triggerLabel,\n },\n );\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, triggerLabel);\n }\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n outcome.events,\n );\n }\n return outcome;\n };\n\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 let responseUsageCount = 0;\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 let lastInputTokensObserved: number | null = null;\n throwIfWorkerShuttingDown();\n const ownedEstablished = resolvedSandbox?.established ?? lazyOwnedSandbox;\n const runStreamOnce = (): ReturnType<OpenGeniRuntime[\"runStream\"]> =>\n runtime.runStream(agent, runInput!, modelRunSettings, {\n ...(activityContext ? { signal: activityContext.cancellationSignal } : {}),\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 ...(lazyOwnedSandbox ? { deferredSetup: true } : {}),\n },\n }\n : {}),\n ...(initialGitCredentials\n ? {\n onGitCredentialSessionReady: async (\n tokenSession: GitCredentialTokenWriterSession,\n ) => {\n await attachGitCredentialRenewal(tokenSession, initialGitCredentials);\n },\n }\n : {}),\n contextCompactionSignalTokens: () => lastInputTokensObserved,\n contextCompactionRequested: () =>\n isSessionCompactionRequested(db, input.workspaceId, input.sessionId),\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 const responseUsage = modelResponseUsageFromSdkEvent(next.value);\n if (responseUsage) {\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 responseUsageCount += 1;\n const responseSourceKey = modelUsageSourceKey({\n responseId: responseUsage.responseId,\n dispatchId: modelUsageDispatchId,\n positionalKey: `response-${responseUsageCount}`,\n });\n // Within a turn the serving credential is fixed, so a switch can only\n // surface on the turn's FIRST model call (vs the session's prior).\n const responseAccountCtx = modelCallAccountContext({\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n isFirstCallOfTurn: responseUsageCount === 1,\n });\n await recordModelUsageAndDebitCredits(settings, db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n model: turn.model,\n isCodexTurn,\n usage: responseUsage.usage,\n sourceKey: responseSourceKey,\n observability,\n });\n await emitModelCallUsage({\n observability,\n publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n provider: resolvedModel?.provider.id ?? settings.openaiProvider,\n providerApi: resolvedModel?.provider.api ?? \"responses\",\n model: turn.model,\n sourceKey: responseSourceKey,\n usage: responseUsage,\n servingAccountHash: responseAccountCtx.servingAccountHash,\n accountChangedFromPrevCall: responseAccountCtx.accountChangedFromPrevCall,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n });\n const observed = responseUsage.usage?.inputTokens;\n if (typeof observed === \"number\" && observed > 0) {\n recordModelInputTokens(observability, streamProvider, observed);\n lastInputTokensObserved = observed;\n }\n // Prompt-cache efficiency for this response — same usage frame as the\n // input-token accounting above, so the two are always consistent.\n recordModelCacheTokens(observability, streamProvider, {\n cachedTokens: modelCallUsageTelemetry(responseUsage.usage).cachedTokens,\n promptTokens: responseUsage.usage?.inputTokens,\n });\n },\n recordAttemptSignals: async () => {\n const observed = responseUsage.usage?.inputTokens;\n if (typeof observed === \"number\" && observed > 0) {\n await setLastInputTokensFenced(observed);\n }\n },\n });\n await reconcileConversationTruth();\n try {\n await ensureRunAllowed(\n settings,\n db,\n input.accountId,\n input.workspaceId,\n isCodexTurn,\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 = 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 ...pendingToolCall,\n });\n if (!registered.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while recording an in-flight tool call\",\n );\n }\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 resultItem: completedToolCall.resultItem,\n });\n if (!recorded.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while recording a tool-call result\",\n );\n }\n if (recorded.allResultsRecorded) {\n // Persist the SDK's now-stable complete call/result batch before\n // clearing its receipts. A crash between these transactions is\n // harmless: settlement finds both raw results and merely\n // consumes them without fabricating an interruption.\n await reconcileConversationTruth({ requireDurable: true });\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 });\n if (!cleared.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while finalizing tool-call results\",\n );\n }\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 }\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 batcher.flush();\n await stream.completed.catch(() => undefined);\n if (responseUsageCount === 0) {\n const aggregateUsage = stream.state.usage;\n const aggregateInput = (aggregateUsage as { inputTokens?: unknown } | undefined)\n ?.inputTokens;\n if (typeof aggregateInput === \"number\" && aggregateInput > 0) {\n lastInputTokensObserved = aggregateInput;\n }\n const aggregateSourceKey = modelUsageSourceKey({\n responseId: null,\n dispatchId: modelUsageDispatchId,\n positionalKey: \"aggregate\",\n });\n // The single aggregate frame is this turn's only model-usage record, so\n // it is the first (account-switch surfaces here just like a first response).\n const aggregateAccountCtx = modelCallAccountContext({\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n isFirstCallOfTurn: true,\n });\n recordModelCacheTokens(observability, streamProvider, {\n cachedTokens: modelCallUsageTelemetry(\n aggregateUsage as Parameters<typeof modelCallUsageTelemetry>[0],\n ).cachedTokens,\n promptTokens: (aggregateUsage as { inputTokens?: unknown } | undefined)?.inputTokens as\n | number\n | undefined,\n });\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 await recordModelUsageAndDebitCredits(settings, db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n model: turn.model,\n isCodexTurn,\n usage: aggregateUsage,\n sourceKey: aggregateSourceKey,\n observability,\n });\n await emitModelCallUsage({\n observability,\n publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n provider: resolvedModel?.provider.id ?? settings.openaiProvider,\n providerApi: resolvedModel?.provider.api ?? \"responses\",\n model: turn.model,\n sourceKey: aggregateSourceKey,\n usage: { usage: aggregateUsage },\n servingAccountHash: aggregateAccountCtx.servingAccountHash,\n accountChangedFromPrevCall: aggregateAccountCtx.accountChangedFromPrevCall,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n });\n },\n recordAttemptSignals: async () => {\n if (typeof aggregateInput === \"number\" && aggregateInput > 0) {\n await setLastInputTokensFenced(aggregateInput);\n }\n },\n });\n }\n if (stream.interruptions.length > 0) {\n await reconcileConversationTruth();\n const approvals = runtime.serializeApprovals(stream.interruptions);\n await saveRunStateFenced({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n expectedExecutionGeneration: executionGeneration,\n expectedAttemptId: input.attemptId,\n serializedRunState: stream.state.toString(),\n pendingApprovals: approvals,\n // Record the account freezing this state so a resume on a DIFFERENT\n // codex account strips its account-bound reasoning before replay (HOLE C).\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n if (\n !(await settle!({\n events: [\n { type: \"session.requiresAction\", payload: { approvals } },\n {\n type: \"session.status.changed\",\n payload: { status: \"requires_action\" },\n },\n ],\n turnStatus: \"requires_action\",\n sessionStatus: \"requires_action\",\n activeTurnId,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n activityStatus = \"requires_action\";\n return claimedResult({ status: \"requires_action\" });\n }\n\n const finalOutput = 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 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,\n error: 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 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 compactionFailureMessage = compactionFailureReason(\n compactError instanceof Error ? compactError.message : String(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 }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = attemptError;\n return claimedResult({ status: \"idle\" });\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 recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: \"sandbox_lease_superseded\",\n });\n if (recovery.action === \"stale\") {\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 console.error(\"sandbox lease supersession recovery failed\", recoveryError);\n throw recoveryError;\n }\n }\n if (isWorkerShutdownCancellation(error) && recoveryTurnId) {\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 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(\"worker-shutdown recovery checkpoint failed\", recoveryError);\n throw recoveryError;\n }\n }\n if (error instanceof TurnAttemptFencedError) {\n activityStatus = \"cancelled\";\n activityError = error;\n await flushRuntimeBatcher();\n // Ownership already moved to a newer attempt or an authoritative\n // control transaction. Surface a transport cancellation instead of a\n // normal activity result: with WAIT_CANCELLATION_COMPLETED, Temporal\n // must observe a terminal cancellation before the session workflow may\n // close. Returning normally after a cancel request is rejected by the\n // server and leaves the worker task detached indefinitely.\n turnMetricOutcome = \"cancelled\";\n throw new CancelledFailure(\"TURN_ATTEMPT_FENCED\", [], error);\n }\n if (error instanceof CancelledFailure) {\n activityStatus = \"cancelled\";\n activityError = error;\n await flushRuntimeBatcher();\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 error;\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 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 notifyParentOfChildTerminal(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n \"failed\",\n `turn:${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(\n codexCredentialFailure,\n serving,\n settings.codexRotationNearExhaustionPct,\n now,\n );\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 nearExhaustionPct: settings.codexRotationNearExhaustionPct,\n now: new Date(),\n usedConnectors: serving?.connectorNamespaces ?? [],\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. A stale activity performs no second settlement.\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\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 settings.codexRotationNearExhaustionPct,\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 nearExhaustionPct: settings.codexRotationNearExhaustionPct,\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(\n fresh,\n settings.codexRotationNearExhaustionPct,\n new Date(),\n );\n capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(\n fresh,\n settings.codexRotationNearExhaustionPct,\n new Date(),\n );\n }\n } else {\n const decision = chooseRotationActive({\n rotationStrategy: reactiveStrategy,\n activeCredentialId: rotation.activeCredentialId,\n priorCredentialId: effectiveCodexCredentialId,\n accounts: fresh,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\n now: new Date(),\n // P4: the just-capped serving account's connector set is the proxy for\n // \"what this session has access to\" — prefer a covering failover target.\n usedConnectors: serving?.connectorNamespaces ?? [],\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(\n fresh,\n settings.codexRotationNearExhaustionPct,\n new Date(),\n );\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 (goalActive && goal && 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: goal.id,\n goalVersion: goal.version,\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 = \"failed\";\n activityStatus = \"idle\";\n activityError = error;\n return claimedResult({\n status: \"idle\",\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 idempotencyKey: `usage:agent_run.completed:${turnId}`,\n });\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\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 = agentRunFailurePayload(error);\n if (failure.retryable && publish && turnId && turnStartedPublished) {\n const recoveryResult = providerRecoveryResult();\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 detail: {\n ...failure,\n continueDelayMs: recoveryResult.continueDelayMs,\n },\n });\n if (recovery.action === \"stale\") {\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n turnMetricOutcome = \"recovering\";\n activityStatus = \"recovering\";\n activityError = error;\n return claimedResult(recoveryResult);\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). Deduped\n // per terminal episode by the child's lastSequence, so it never\n // double-fires with the workflow-level wake.\n await notifyParentOfChildTerminal(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n \"failed\",\n `turn:${turnId}`,\n );\n return claimedResult({ status: \"failed\" });\n } finally {\n gitCredentialRenewalClosed = true;\n const renewalToStop = gitCredentialRenewal as GitCredentialRenewalController | null;\n gitCredentialRenewal = null;\n await renewalToStop?.stop();\n const durationSeconds = (performance.now() - activityStarted) / 1000;\n observability.recordWorkerActivity({\n activity: \"runAgentTurn\",\n status: 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 },\n error: activityError,\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 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 }\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 recordCodexAccountUsageWithWakeTargets(\n db,\n input.workspaceId,\n effectiveCodexCredentialId,\n latestCodexUsage,\n ).catch(() => null);\n if (usageMutation) {\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n usageMutation.wakeTargets,\n );\n }\n }\n // Part B.1: the connector namespaces codex_apps listed this turn → the\n // connector-set cache. NON-EMPTY-only: a flaky/empty tools/list must never\n // overwrite a known set with [] (false coverage drop). Read by reference\n // AFTER the run, so every tools/list this turn has accumulated.\n const connectorNamespaces = preparedTools?.codexConnectorNamespaces;\n if (connectorNamespaces && connectorNamespaces.size > 0) {\n await recordCodexAccountConnectors(db, input.workspaceId, effectiveCodexCredentialId, [\n ...connectorNamespaces,\n ]).catch(() => undefined);\n }\n }\n if (codexLeaseHeartbeatTimer) {\n clearInterval(codexLeaseHeartbeatTimer);\n codexLeaseHeartbeatTimer = undefined;\n }\n if (codexLeaseHeld && turnId && codexLeaseHolderId && codexLeaseGeneration !== null) {\n await releaseCodexCredentialLease(\n db,\n input.accountId,\n input.workspaceId,\n turnId,\n codexLeaseHolderId,\n codexLeaseGeneration,\n ).catch(() => undefined);\n codexLeaseHeld = false;\n }\n // Workbench v2 turn-end workspace capture (dossier §10.1) — 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 60s, 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 (resolvedSandbox && setupBoxSession && sandboxGroupId) {\n // Stop new heartbeat snapshot/meter ticks so a mid-turn snapshot cannot\n // start concurrently with capture, then drain any in-flight snapshot\n // (bounded) — capture and the warm snapshot both exec on the box, so\n // sequence them, exactly as the turn-end snapshot placement did.\n if (leaseHeartbeatTimer) {\n clearInterval(leaseHeartbeatTimer);\n leaseHeartbeatTimer = undefined;\n }\n if (snapshotInFlight) {\n await waitForWarmSnapshot(snapshotInFlight, settings.sandboxSnapshotTimeoutMs);\n }\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 leaseEpoch: resolvedSandbox.leaseEpoch,\n sandboxGroupId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turnId ?? null,\n observability,\n });\n }\n await preparedTools?.close().catch(() => undefined);\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\n }\n if (turnSandboxProvisioner?.hasStarted()) {\n await turnSandboxProvisioner.waitForSettled(30_000);\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 clearInterval(leaseHeartbeatTimer);\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 abandonActiveRecording(\n \"activity ended without recording settlement\",\n didComputerUse ? \"failed\" : \"discard\",\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 if (setupBoxSession && sandboxGroupId) {\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(snapshotInFlight, settings.sandboxSnapshotTimeoutMs);\n }\n const persisted = await maybePersistWarmWorkspaceSnapshot(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId,\n },\n setupBoxSession,\n resolvedSandbox.leaseEpoch,\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 (dossier §10.1) 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 await resolvedSandbox.release().catch((releaseError) => {\n console.error(\"sandbox lease release failed (turn outcome unaffected)\", releaseError);\n });\n resolvedSandbox = null; // drop the handle; the box survives the turn\n }\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 */\nexport function isTransientProviderError(error: unknown): boolean {\n const status =\n typeof error === \"object\" && error !== null && \"status\" in error\n ? Number((error as { status?: unknown }).status)\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 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(error: unknown): {\n error: string;\n code?: string;\n retryable?: boolean;\n detail?: string;\n} {\n const message = error instanceof Error ? error.message : String(error);\n const status =\n typeof error === \"object\" && error !== null && \"status\" in error\n ? Number((error as { status?: unknown }).status)\n : undefined;\n const code =\n typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\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 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 (\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 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 nearExhaustionPct: number,\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) >= nearExhaustionPct &&\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 ?? body?.status);\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 headers = value.headers as { get?: (name: string) => string | null } | undefined;\n const retryAfterHeader = headers?.get?.(\"retry-after\") ?? null;\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 codex-billed bypass (codex-billing.test.ts); not part\n// of the activity surface. Takes BOTH `isCodexTurn` (codex-plan turns bypass the credit\n// and token gates) and the optional §7.5 P3 host `entitlements` port (when bound, its\n// `admitRun` REPLACES the local credit read for a non-codex turn; unset → local ledger).\nexport async function ensureRunAllowed(\n settings: Settings,\n db: ActivityServices[\"db\"],\n accountId: string,\n workspaceId: string,\n isCodexTurn: boolean,\n entitlements?: ActivityServices[\"entitlements\"],\n): Promise<void> {\n // Codex-billed turns are paid by the user's ChatGPT/Codex plan: skip the\n // credit-balance gate and the monthly token cap. The agent-run COUNT cap below\n // is a 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 !isCodexTurn &&\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 !isCodexTurn &&\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 (!isCodexTurn && 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\n// Exported for unit testing the codex-billed 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 model: string;\n isCodexTurn: boolean;\n usage?: ModelUsageInput | null;\n sourceKey: string;\n observability?: ActivityServices[\"observability\"];\n },\n): Promise<void> {\n if (!input.usage) {\n return;\n }\n const inputTokens = positiveInt(input.usage.inputTokens);\n const outputTokens = positiveInt(input.usage.outputTokens);\n const totalTokens = positiveInt(input.usage.totalTokens) || inputTokens + outputTokens;\n // A codex-subscription turn is paid by the user's ChatGPT/Codex plan, 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.isCodexTurn) {\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 idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`,\n });\n return;\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 idempotencyKey: `usage:model.tokens:${input.turnId}:${input.sourceKey}`,\n });\n }\n const shouldDebit = settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\";\n if (!shouldDebit || totalTokens === 0) {\n return;\n }\n if (!configuredModelPricing(settings)[input.model]) {\n throw new Error(`Missing model pricing for ${input.model}`);\n }\n const costMicros = calculateModelUsageCostMicros(settings, input.model, input.usage);\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 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 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: positiveInt(\n modelCallUsageTelemetry(input.usage as Parameters<typeof modelCallUsageTelemetry>[0])\n .cachedTokens,\n ),\n },\n });\n recordCreditMicros(input.observability, \"usage\", result.debitedMicros);\n }\n}\n\nfunction positiveInt(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;\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): Promise<SandboxFileDownload[]> {\n if (settings.sandboxBackend === \"none\" || !requiresSignedFileResourceDownloads(settings)) {\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: resource.mountPath ?? `files/${file.id}`,\n filename: file.safeFilename,\n url: url.url,\n expiresAt: url.expiresAt,\n sizeBytes: file.sizeBytes,\n });\n }\n return downloads;\n}\n\nfunction requiresSignedFileResourceDownloads(settings: Settings): boolean {\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 (settings.sandboxBackend === \"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[settings.sandboxBackend].nativeBucketMount;\n return (\n (settings.sandboxBackend === \"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 {\n environmentsEncryptionKeyBytes,\n parseModelProvidersJson,\n type RegistryProvider,\n type Settings,\n} from \"@opengeni/config\";\nimport { settingsWithMcpCapabilityServers } from \"@opengeni/core\";\nimport {\n CODEX_APPS_MCP_SERVER_ID,\n CODEX_APPS_MCP_SERVER_NAME,\n CODEX_APPS_MCP_URL,\n CODEX_APPS_STARTUP_TIMEOUT_MS,\n CODEX_FALLBACK_MODEL_SLUGS,\n CODEX_MODEL_CONTEXT_WINDOW_TOKENS,\n CODEX_MODEL_EFFECTIVE_CONTEXT_WINDOW_TOKENS,\n CODEX_MODEL_AUTO_COMPACT_TOKEN_LIMIT,\n CODEX_MODEL_ID_PREFIX,\n CODEX_PROVIDER_BASE_URL,\n CODEX_PROVIDER_ID,\n} from \"@opengeni/codex\";\nimport {\n listEnabledMcpCapabilityServers,\n listSessionMcpServerMetadata,\n listSessionMcpServersForRun,\n workspaceCodexSubscriptionActive,\n type Database,\n type SessionMcpServerForRun,\n} from \"@opengeni/db\";\n\nexport async function settingsWithEnabledCapabilityMcpServers(\n db: Database,\n workspaceId: string,\n settings: Settings,\n): Promise<Settings> {\n const enabled = await listEnabledMcpCapabilityServers(db, workspaceId);\n return settingsWithMcpCapabilityServers(settings, enabled);\n}\n\nexport async function settingsWithSessionMcpServersForRun(\n db: Database,\n workspaceId: string,\n sessionId: string,\n settings: Settings,\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 throw new Error(\"session MCP server credentials require OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\");\n }\n return settingsWithSessionMcpServers(\n settings,\n await listSessionMcpServersForRun(db, workspaceId, sessionId, encryptionKey),\n );\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 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 // Additive: append the synthetic codex_apps connectors MCP server for ANY\n // active credential. Connector access is gated SERVER-SIDE per ChatGPT account\n // (via chatgpt-account-id), NOT by token scopes — confirmed live: a `pro` token\n // whose only scopes are openid/profile/email/offline_access still lists all 217\n // connector tools at .../ps/mcp. So we inject unconditionally and let\n // runtime-discovery decide: an account with no connectors yields an empty\n // tools/list, and a connect failure best-effort-drops the server without\n // failing the turn. The bearer is injected dynamically at connect time\n // (runtime/codexAppsMcpRequestInit).\n return withCodexAppsMcpServer(withProvider);\n}\n\n/**\n * Pure: append the synthetic codex_apps MCP server, idempotently. Connector\n * access is gated SERVER-SIDE per ChatGPT account (chatgpt-account-id), not by\n * token scopes, so we inject for any active credential and let runtime-discovery\n * resolve the actual tool set (empty list / dropped server when unavailable).\n * No secrets here — the refreshing bearer is injected at connect time from\n * codexRequestStorage (runtime/codexAppsMcpRequestInit). The connectors backend\n * tolerates serial and parallel tool invocation, so no per-server serialization\n * is enforced (the SDK exposes no per-server parallel-tool-calls flag in\n * @openai/agents 0.11.6).\n */\nexport function withCodexAppsMcpServer(settings: Settings): Settings {\n if (settings.mcpServers.some((server) => server.id === CODEX_APPS_MCP_SERVER_ID)) {\n return settings; // already injected\n }\n return {\n ...settings,\n mcpServers: [\n ...settings.mcpServers,\n {\n id: CODEX_APPS_MCP_SERVER_ID,\n name: CODEX_APPS_MCP_SERVER_NAME,\n url: CODEX_APPS_MCP_URL,\n timeoutMs: CODEX_APPS_STARTUP_TIMEOUT_MS,\n // Connector availability is per-credential and must re-discover each\n // run; never poison a process-global tools-list cache.\n cacheToolsList: false,\n // deliberately NO `headers` — the refreshing bearer is dynamic\n },\n ],\n };\n}\n\n/** Pure: append the synthetic codex-subscription provider, idempotently. */\nexport function withCodexProvider(settings: Settings): Settings {\n const providers = parseModelProvidersJson(settings.modelProvidersJson);\n if (providers.some((provider) => provider.id === CODEX_PROVIDER_ID)) {\n return settings; // already injected\n }\n const codexProvider: RegistryProvider = {\n kind: \"codex-subscription\",\n id: CODEX_PROVIDER_ID,\n label: \"Codex (ChatGPT subscription)\",\n api: \"responses\",\n baseUrl: CODEX_PROVIDER_BASE_URL,\n models: CODEX_FALLBACK_MODEL_SLUGS.map((slug) => ({\n id: `${CODEX_MODEL_ID_PREFIX}${slug}`,\n label: slug,\n reasoningEffort: true,\n // These three values are the live Codex CLI catalog policy, kept distinct\n // so proactive compaction and the effective input guard match Codex core.\n contextWindowTokens: CODEX_MODEL_CONTEXT_WINDOW_TOKENS,\n effectiveContextWindowTokens: CODEX_MODEL_EFFECTIVE_CONTEXT_WINDOW_TOKENS,\n autoCompactTokenLimit: CODEX_MODEL_AUTO_COMPACT_TOKEN_LIMIT,\n })),\n };\n return { ...settings, modelProvidersJson: JSON.stringify([...providers, codexProvider]) };\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 * 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 && 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 // `droppedConnectors` (P4 Part B): the leaving session's used connectors that the\n // chosen account does NOT cover — populated ONLY on a Tier-2/unknown pick that\n // can't cover (prefer-not-require: failover still happens, but the pill warns).\n | { kind: \"active\"; credentialId: string; moved: boolean; droppedConnectors?: string[] }\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 over-threshold 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\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 * P4 connector coverage (prefer-not-require). `acct` COVERS `usedConnectors` iff its\n * cached connector set is a SUPERSET of the session's used set. An empty used set is\n * trivially covered by everyone (→ Tier 1 == all eligibles == byte-identical to P3).\n * A null (never-probed) set is UNKNOWN: never credited as covering (Tier 2 only),\n * but — critically — never excluded, so failover is fully preserved.\n */\nfunction covers(acct: CodexRotationAccount, usedConnectors: string[]): boolean {\n if (usedConnectors.length === 0) {\n return true;\n }\n const owned = acct.connectorNamespaces;\n if (owned === null) {\n return false; // unprobed ⇒ unknown ⇒ never Tier 1 (but still a Tier-2 candidate)\n }\n const ownedSet = new Set(owned);\n return usedConnectors.every((connector) => ownedSet.has(connector));\n}\n\n/**\n * The used connectors the chosen account does NOT cover (the \"switch dropped a\n * connector\" note). Empty when the account covers (superset) or nothing was used.\n * A null (unknown) set surfaces ALL used connectors — we can't prove it covers them.\n */\nfunction droppedConnectorsFor(acct: CodexRotationAccount, usedConnectors: string[]): string[] {\n if (usedConnectors.length === 0) {\n return [];\n }\n const owned = acct.connectorNamespaces;\n if (owned === null) {\n return [...usedConnectors];\n }\n const ownedSet = new Set(owned);\n return usedConnectors.filter((connector) => !ownedSet.has(connector));\n}\n\n/**\n * Healthy for an already-frozen/in-flight turn = connected/usable (status\n * \"active\", excludes needs_relogin/error), not cooling, and under the\n * near-exhaustion threshold on BOTH windows. Allocator eligibility is\n * deliberately separate so disabling NEW work cannot break refresh/resume.\n */\nexport function isCodexCredentialHealthy(\n acct: CodexRotationAccount,\n nearExhaustionPct: number,\n now: Date,\n): boolean {\n return (\n acct.status === \"active\" && !cooling(acct, now) && bindingUsedPct(acct, now) < nearExhaustionPct\n );\n}\n\n/** New automatic allocation requires both health and explicit allocator eligibility. */\nexport function isCodexCredentialEligible(\n acct: CodexRotationAccount,\n nearExhaustionPct: number,\n now: Date,\n): boolean {\n return acct.allocatorEnabled && isCodexCredentialHealthy(acct, nearExhaustionPct, 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 under\n * the near-exhaustion threshold 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(\n acct: CodexRotationAccount,\n nearExhaustionPct: number,\n now: Date,\n): boolean {\n return isCodexCredentialEligible(acct, nearExhaustionPct, 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, under-threshold) 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 nearExhaustionPct: number;\n now: Date;\n}): string | null {\n const { sessionId, accounts, nearExhaustionPct, now } = args;\n const eligibles = accounts.filter((acct) =>\n isCodexCredentialEligible(acct, nearExhaustionPct, now),\n );\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(\n accounts: CodexRotationAccount[],\n nearExhaustionPct: number,\n now: Date,\n): Date {\n return earliestReset(accounts, nearExhaustionPct, 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 nearExhaustionPct: number;\n now: Date;\n}):\n | { kind: \"home\"; credentialId: string; rewritePin: boolean }\n | { kind: \"allCapped\"; earliestResetAt: Date } {\n const { sessionId, currentPolicyPin, accounts, nearExhaustionPct, now } = args;\n const pinRow = currentPolicyPin\n ? (accounts.find((acct) => acct.id === currentPolicyPin) ?? null)\n : null;\n if (pinRow && isCodexCredentialEligible(pinRow, nearExhaustionPct, now)) {\n return { kind: \"home\", credentialId: currentPolicyPin!, rewritePin: false };\n }\n const home = shardCredentialForSession({ sessionId, accounts, nearExhaustionPct, now });\n if (home == null) {\n return { kind: \"allCapped\", earliestResetAt: earliestReset(accounts, nearExhaustionPct, 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(\n acct: CodexRotationAccount,\n nearExhaustionPct: number,\n now: Date,\n): 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) >= nearExhaustionPct,\n acct.primaryResetAt,\n );\n windowClear(\n effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now) >= nearExhaustionPct,\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(\n accounts: CodexRotationAccount[],\n nearExhaustionPct: number,\n now: Date,\n): Date {\n return accounts\n .map((acct) => availableAt(acct, nearExhaustionPct, 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 nearExhaustionPct: number,\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) >= nearExhaustionPct &&\n account.primaryResetAt &&\n account.primaryResetAt.getTime() > now.getTime()\n ) {\n future.push(account.primaryResetAt);\n }\n if (\n (account.secondaryUsedPercent ?? 0) >= nearExhaustionPct &&\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 re-ranks (a connector-covering\n * pick order) without 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 nearExhaustionPct: number;\n now: Date;\n // P4 (Part B): the connectors the leaving session has access to (the leaving\n // account's cached connector set, used as the \"session needs these\" proxy).\n // Optional + defaults to [] ⇒ when absent/empty the ranker is BYTE-IDENTICAL to\n // P3 (every account trivially covers → Tier 1 == all eligibles). Self-gating.\n usedConnectors?: string[];\n}): RotationDecision {\n const {\n rotationStrategy,\n activeCredentialId,\n priorCredentialId,\n accounts,\n nearExhaustionPct,\n now,\n } = args;\n const allocatableAccounts = accounts.filter((account) => account.allocatorEnabled);\n const usedConnectors = args.usedConnectors ?? [];\n\n if (allocatableAccounts.length === 0) {\n return { kind: \"none\" };\n }\n\n const eligibles = allocatableAccounts.filter((acct) =>\n isCodexCredentialEligible(acct, nearExhaustionPct, now),\n );\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 until 90% was the production monopolization\n // defect fixed by OPE-21. 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, nearExhaustionPct, now),\n };\n }\n // P4: surface the dropped-connector note when the chosen account doesn't cover\n // the session's used connectors (a Tier-2/unknown failover pick). Empty ⇒ omit.\n const dropped = droppedConnectorsFor(chosen, usedConnectors);\n return {\n kind: \"active\",\n credentialId: chosen.id,\n moved: chosen.id !== activeCredentialId,\n ...(dropped.length > 0 ? { droppedConnectors: dropped } : {}),\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, nearExhaustionPct, 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, nearExhaustionPct, 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, nearExhaustionPct, now)) {\n return decide(priorRow);\n }\n return decide(eligibles[0]);\n }\n\n // most_remaining (default + the correctness path). Two-tier coverage pick over\n // the SAME eligible set (prefer-not-require):\n // Tier 1 — eligibles whose connector set COVERS the session's used set.\n // Tier 2 — ALL eligibles, only if Tier 1 is empty (failover fully preserved).\n // Within the chosen tier:\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 covering = eligibles.filter((acct) => covers(acct, usedConnectors));\n const pool = covering.length > 0 ? covering : eligibles;\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 = pool.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/connector 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.nearExhaustionPct, 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 /** Same-turn checkpoint/frozen account; temporary disable cannot move it. */\n continuationCredentialId?: string | null;\n nearExhaustionPct: number;\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 const strategy = rotationStrategy as CodexRotationStrategy;\n const existing = existingCredentialId\n ? accounts.find((account) => account.id === existingCredentialId)\n : undefined;\n if (existing && isCodexCredentialHealthy(existing, args.nearExhaustionPct, 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 continuation = args.continuationCredentialId\n ? accounts.find((account) => account.id === args.continuationCredentialId)\n : undefined;\n if (continuation && isCodexCredentialHealthy(continuation, args.nearExhaustionPct, args.now)) {\n return {\n credentialId: continuation.id,\n advanceActivePointer: false,\n decision: {\n kind: \"active\",\n credentialId: continuation.id,\n moved: continuation.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; healthy live/frozen\n // same-turn continuity 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.nearExhaustionPct, 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.nearExhaustionPct, args.now),\n },\n advanceActivePointer: false,\n };\n }\n\n // OPE-31 policy homes compose with OPE-21 by sharding only the candidate list\n // handed to this selector. A future OPE-32 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 nearExhaustionPct: args.nearExhaustionPct,\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 nearExhaustionPct: args.nearExhaustionPct,\n now: args.now,\n usedConnectors: accounts.find((account) => account.id === priorId)?.connectorNamespaces ?? [],\n });\n return {\n credentialId: decision.kind === \"active\" ? decision.credentialId : null,\n decision,\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 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 continuationCredentialId: null,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\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) =>\n isCodexCredentialEligible(account, settings.codexRotationNearExhaustionPct, now),\n ).length,\n },\n };\n }\n const authoritativeReset = authoritativeCodexCapacityResetAt(\n context.accounts,\n settings.codexRotationNearExhaustionPct,\n now,\n );\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) >= services.settings.codexRotationNearExhaustionPct ||\n (account.secondaryUsedPercent ?? 0) >= services.settings.codexRotationNearExhaustionPct ||\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\", updateId: result.update.id };\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 type Database,\n} from \"@opengeni/db\";\nimport {\n SUMMARY_BUFFER_TOKENS,\n buildCompactionPromptInput,\n buildCompactionReplacementHistory,\n decideCompaction,\n estimateTokens,\n sanitizeHistoryItemsForModel,\n summarizeForCompaction,\n type CompactionItem,\n} from \"@opengeni/runtime\";\nimport type { Settings } from \"@opengeni/config\";\nimport type { SessionEvent } from \"@opengeni/contracts\";\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 events: SessionEvent[];\n };\n\n/**\n * Durable portable context compaction, following Codex CLI's local path.\n *\n * Runs before a fresh model call and on a same-turn compaction recovery.\n * Reads the active history rows + the most recent provider-reported input\n * tokens, applies the single Codex-parity threshold, and - when it should -\n * summarizes the active history with the Codex checkpoint prompt. The write\n * supersedes the old active rows and inserts replacement active rows:\n * all real user messages plus one summary.\n *\n * If the summarizer itself exceeds the context window, the oldest prompt item\n * is removed and the same compaction call is retried, exactly like Codex local\n * compaction. Other provider failures propagate. There is no non-model\n * fallback and no silent request-local history trimming.\n *\n * There is no kept assistant/tool tail. Assistant messages,\n * tool calls/results, reasoning, and images stay only in inactive audit rows.\n */\nexport type CompactionSummarizer = (settings: Settings, input: CompactionItem[]) => Promise<string>;\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 } = {},\n): Promise<MaybeCompactResult> {\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 { compacted: false, reason: \"no_history\", events: [], requestConsumed };\n }\n\n const items = sanitizeHistoryItemsForModel(active.map((row) => row.item) as CompactionItem[]);\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 estimatedTokensBefore = estimateTokens(items);\n const summaryBody = await summarizeWithCodexOverflowTrimming(summarize, settings, items);\n const replacementHistory = buildCompactionReplacementHistory(items, summaryBody);\n const estimatedTokensAfter = estimateTokens(replacementHistory);\n const summaryItem = replacementHistory.at(-1);\n if (!summaryItem) {\n return {\n compacted: false,\n reason: \"compaction produced no replacement history\",\n events: [],\n requestConsumed: false,\n };\n }\n if (estimatedTokensAfter >= estimatedTokensBefore) {\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: \"replacement_not_smaller\",\n });\n if (!skipped.recorded) {\n throw new TurnAttemptFencedError(\n \"turn attempt was fenced while consuming a non-shrinking context compaction request\",\n );\n }\n requestConsumed = true;\n return {\n compacted: false,\n reason: \"replacement_not_smaller\",\n events: skipped.events,\n requestConsumed,\n };\n }\n return {\n compacted: false,\n reason: \"replacement_not_smaller\",\n events: [],\n requestConsumed,\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: summaryItem as Record<string, unknown>,\n replacementInputTokens: estimatedTokensAfter,\n ...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),\n eventPayload: {\n trigger: options.trigger ?? \"auto\",\n estimatedTokensBefore,\n estimatedTokensAfter,\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 events: applied.events,\n };\n}\n\nasync function summarizeWithCodexOverflowTrimming(\n summarize: CompactionSummarizer,\n settings: Settings,\n activeHistory: CompactionItem[],\n): Promise<string> {\n const compactionHistory = activeHistory.slice();\n while (true) {\n try {\n return await summarize(settings, buildCompactionPromptInput(compactionHistory));\n } catch (error) {\n if (!isContextWindowExceeded(error) || compactionHistory.length === 0) {\n throw error;\n }\n // Codex removes one oldest history item, keeps the synthesized checkpoint\n // prompt, resets its stream retry count, and samples the summary again.\n compactionHistory.shift();\n }\n }\n}\n\nfunction isContextWindowExceeded(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const record = error as Record<string, unknown>;\n const code = typeof record.code === \"string\" ? record.code.toLowerCase() : \"\";\n const message = error instanceof Error ? error.message.toLowerCase() : \"\";\n return (\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 );\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","import {\n applyGitAuthPointerEnvironment,\n firstPartyMcpWorkspaceUrl,\n stableSandboxEnvironmentForRun,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n signDelegatedAccessToken,\n type ConnectionCredentialsPort,\n type GitCredentialProvider,\n type GitCredentialRepositoryRef,\n type GitCredentials,\n type ResourceRef,\n type SandboxSecrets,\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 P4a — the run's workspace identity, threaded so the connection-credential\n// provider can be called with the run's tenant context AND so the FORK-7\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 MintedRunGitCredentials = {\n gitTokens: GitTokenSeeds;\n expiresAt: GitTokenExpiries;\n};\n\n// §7.6 P4a — 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 // FORK-7: 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// §7.6 FORK-7 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 P4a - 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: {\n skipGitHubToken?: boolean;\n deferGitHubToken?: boolean;\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n sessionId?: string;\n runId?: string;\n } = {},\n): Promise<{\n environment: Record<string, string>;\n gitToken?: string;\n gitTokens?: GitTokenSeeds;\n gitTokenExpiresAt?: GitTokenExpiries;\n toolspaceToken?: string;\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, turn TTL,\n // budgeted, approval-tools excluded). Delivery mirrors the docker path: the\n // caller threads it OFF-MANIFEST as the seed the runtime writes to\n // $OPENGENI_TOOLSPACE_TOKEN_FILE over the box's exec channel.\n let toolspaceToken: string | undefined;\n if (\n settings.toolspaceEnabled &&\n settings.delegationSecret &&\n options.scope &&\n options.sessionId &&\n options.runId\n ) {\n toolspaceToken = await signDelegatedAccessToken(settings.delegationSecret, {\n accountId: options.scope.accountId,\n workspaceId: options.scope.workspaceId,\n subjectId: `sandbox:${options.runId}`,\n subjectLabel: \"sandbox toolspace\",\n permissions: [\"toolspace:call\"],\n sessionId: options.sessionId,\n exp: Math.floor(Date.now() / 1000) + 60 * 60,\n });\n environment.OPENGENI_TOOLSPACE_URL ??= firstPartyMcpWorkspaceUrl(\n settings,\n options.scope.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 { environment, ...(toolspaceToken ? { toolspaceToken } : {}) };\n }\n if (options.deferGitHubToken) {\n applyGitAuthPointerEnvironment(\n environment,\n await resolveRunGitIdentityWithSelections(settings, selections, options),\n );\n return { environment, ...(toolspaceToken ? { toolspaceToken } : {}) };\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 ...(toolspaceToken ? { toolspaceToken } : {}),\n };\n}\n\nexport async function mintRunGitCredentials(\n settings: Settings,\n resources: ResourceRef[],\n options: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n } = {},\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 Object.keys(minted.gitTokens).length > 0\n ? { gitTokens: minted.gitTokens, expiresAt: minted.expiresAt }\n : undefined;\n}\n\nexport async function mintRunGitTokens(\n settings: Settings,\n resources: ResourceRef[],\n options: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n } = {},\n): Promise<GitTokenSeeds | undefined> {\n return (await mintRunGitCredentials(settings, resources, options))?.gitTokens;\n}\n\nexport async function mintRunGitToken(\n settings: Settings,\n resources: ResourceRef[],\n options: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n } = {},\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: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n } = {},\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: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n },\n): Promise<{\n gitTokens: GitTokenSeeds;\n expiresAt: GitTokenExpiries;\n identity: { name: string; email: string } | null;\n}> {\n const gitTokens: GitTokenSeeds = {};\n const expiresAt: GitTokenExpiries = {};\n let identity: { name: string; email: string } | null = null;\n for (const selection of selections) {\n let token: string | null = null;\n if (options?.gitCredentials && options.scope) {\n const request = gitCredentialsRequestForSelection(options.scope, selection, \"token\");\n const minted: GitCredentials = await options.gitCredentials(request);\n // FORK-7: 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 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 if (minted.expiresAt) {\n expiresAt[selection.provider] = validatedGitCredentialExpiry(\n selection.provider,\n minted.expiresAt,\n );\n }\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 if (minted.expiresAt) {\n expiresAt.github = validatedGitCredentialExpiry(\"github\", minted.expiresAt);\n }\n identity = githubAppBotIdentity(settings);\n }\n if (token) {\n gitTokens[selection.provider] = token;\n }\n }\n return { 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\nasync function resolveRunGitIdentityWithSelections(\n settings: Settings,\n selections: GitCredentialSelection[],\n options: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n },\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 resolved: GitCredentials = await options.gitCredentials(\n gitCredentialsRequestForSelection(options.scope, selection, \"identity\"),\n );\n assertWorkspaceEcho(\"gitCredentials\", options.scope, resolved.workspaceId);\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 installationId: number;\n repositoryIds: number[];\n repositoryRefs: GitCredentialRepositoryRef[];\n};\n\nfunction gitCredentialsRequestForSelection(\n scope: ConnectionScope,\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 ...(purpose ? { purpose } : {}),\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n };\n if (selection.provider === \"github\") {\n return {\n ...legacy,\n repositoryRefs: selection.repositoryRefs,\n };\n }\n return {\n ...legacy,\n provider: selection.provider,\n repositoryRefs: selection.repositoryRefs,\n };\n}\n\nfunction gitCredentialSelections(resources: ResourceRef[]): GitCredentialSelection[] {\n const byProvider = new Map<GitCredentialProvider, GitCredentialSelection>();\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 entry = byProvider.get(provider) ?? {\n provider,\n installationId: 0,\n repositoryIds: [],\n repositoryRefs: [],\n };\n const ref = gitCredentialRepositoryRef(resource, provider);\n entry.repositoryRefs.push(ref);\n if (provider === \"github\") {\n const installationId = positiveInteger(\n resource.githubInstallationId ?? resource.installationId,\n );\n const repositoryId = positiveInteger(resource.githubRepositoryId ?? resource.repositoryId);\n if (installationId && repositoryId) {\n if (entry.installationId > 0 && entry.installationId !== installationId) {\n throw new Error(\"GitHub App repository resources must belong to one installation\");\n }\n entry.installationId = installationId;\n entry.repositoryIds.push(repositoryId);\n }\n }\n byProvider.set(provider, entry);\n }\n return [...byProvider.values()];\n}\n\nfunction repositoryCredentialProvider(\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n): GitCredentialProvider | null {\n if (resource.provider) {\n return resource.provider;\n }\n if (\n positiveInteger(resource.githubInstallationId) &&\n positiveInteger(resource.githubRepositoryId)\n ) {\n return \"github\";\n }\n return null;\n}\n\nfunction gitCredentialRepositoryRef(\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n provider: GitCredentialProvider,\n): GitCredentialRepositoryRef {\n return {\n provider,\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","import {\n configuredStaticUsageLimits,\n policyProviderIdForModel,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n evaluateWorkspaceModelPolicy,\n mergeToolRefs,\n reasoningEffortForMetadata,\n type SessionGoal,\n type ToolRef,\n} from \"@opengeni/contracts\";\nimport {\n addSessionSystemUpdate,\n enqueueSessionWorkflowWakeIfRunnable,\n evaluateGoalContinuation,\n getBillingBalance,\n getLatestStartedSessionTurn,\n getWorkspaceModelPolicy,\n getSessionGoal,\n isCodexBilledTurn,\n recordUsageEvent,\n requireSession,\n sumUsageQuantity,\n type Database,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents } from \"@opengeni/events\";\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 // 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 // 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 evaluateGoalContinuation(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\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 });\n if (decision.decision === \"none\" || decision.decision === \"queue\") {\n return { action: decision.decision };\n }\n if (decision.decision === \"paused\") {\n await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n type: \"goal.paused\",\n payload: {\n goalId: decision.goal.id,\n actor: \"system\",\n reason: decision.reason,\n ...(decision.goal.rationale ? { rationale: decision.goal.rationale } : {}),\n autoContinuations: decision.goal.autoContinuations,\n noProgressStreak: decision.goal.noProgressStreak,\n },\n },\n ]);\n return { action: \"paused\" };\n }\n // Stop/continue race guard: a concurrent goal_complete/goal_pause/operator\n // PATCH between the locked decision and this synthesis must win. The\n // version check also catches a replace. A pause landing after this point\n // results in at most one already-admitted continuation turn; the next\n // pass sees the non-active goal and stops, and interrupt-driven pauses\n // additionally cancel the claimed turn via the workflow interrupt path.\n const recheck = await getSessionGoal(db, input.workspaceId, input.sessionId);\n if (!recheck || recheck.status !== \"active\" || recheck.version !== decision.goal.version) {\n return { action: \"none\" };\n }\n const prompt = goalContinuationPrompt(decision.goal, decision.autoContinuation, decision.cap);\n const update = await addSessionSystemUpdate(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n kind: \"goal_continuation\",\n classification: \"info\",\n sourceId: decision.goal.id,\n dedupeKey: `goal-continuation:${decision.goal.id}:${decision.goal.version}:${decision.autoContinuation}`,\n summary: prompt,\n payload: {\n type: \"goal_continuation\",\n goalId: decision.goal.id,\n goalVersion: decision.goal.version,\n autoContinuation: decision.autoContinuation,\n maxAutoContinuations: decision.cap,\n prompt,\n policy: {\n model: continuationModel,\n reasoningEffort: continuationReasoningEffort,\n tools: withFirstPartyTools(settings, session.tools),\n sandboxBackend: session.sandboxBackend,\n },\n },\n lineage: { goalId: decision.goal.id },\n });\n if (update.reason === \"session_cancelled\") return { action: \"none\" };\n if (update.added && update.events.length > 0) {\n await bus.publish(input.workspaceId, input.sessionId, update.events);\n }\n // Continuations count as agent runs for limits/metering parity with\n // user-initiated and scheduled turns.\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"agent_run.created\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"session_system_update\",\n sourceResourceId: update.update.id,\n idempotencyKey: `agent_run.created:goal:${input.workspaceId}:${update.update.id}`,\n });\n return { action: \"continue\" };\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 * Ensures a turn references the synthetic codex_apps connectors MCP server when\n * the codex overlay injected it (active subscription + connector scopes). A\n * registry entry is inert until a ToolRef references its id, so this wires the\n * server into the run. No-op when the server is not configured (every non-codex\n * turn), and idempotent via mergeToolRefs.\n */\nexport function withCodexAppsTool(settings: Settings, tools: ToolRef[]): ToolRef[] {\n if (!settings.mcpServers.some((server) => server.id === \"codex_apps\")) {\n return tools;\n }\n return mergeToolRefs(tools, [{ kind: \"mcp\", id: \"codex_apps\" }]);\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 { getWorkspace, getWorkspacePack, listPackInstallations, type Database } from \"@opengeni/db\";\nimport type { PackSkill } 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 skills: PackSkill[];\n};\n\nconst emptyPackRuntime: WorkspacePackRuntime = { sandboxImage: null, skills: [] };\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 * 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 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): Settings {\n if (!sandboxImage) {\n return settings;\n }\n return {\n ...settings,\n dockerImage: sandboxImage,\n modalImageRef: sandboxImage,\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 };\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 addSessionSystemUpdateWithSourceMutation,\n claimPendingSessionSystemUpdateOutbox,\n claimPendingSessionWorkflowWakes,\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 * Deliver exactly one completion wake to a spawned worker's parent (manager)\n * session when the worker reaches a terminal-for-now state. No-op for a\n * parentless session (direct API create / scheduled run). Idempotent per\n * terminal episode: the idempotency key is the child's current lastSequence,\n * which advances every time the child does work, so a retry of the same\n * terminal transition (activity retry, the workflow's idle re-check, the\n * runAgentTurn-failed path overlapping a workflow-level wake) is deduped while\n * a genuinely new idle-after-work episode notifies again. The parent receives\n * one typed internal update; signalling its workflow ensures an idle parent can\n * coalesce and process all pending updates in one inference. Failures here never\n * fail the child because the durable outbox remains retryable.\n *\n * Lives in its own module so both the session-state terminal activities\n * (markSessionIdle / failSession) and runAgentTurn's in-turn failure path can\n * call it without a circular import between those two activity modules.\n */\nexport async function notifyParentOfChildTerminal(\n svc: NotifyServices,\n workspaceId: string,\n childSessionId: string,\n terminalStatus: \"idle\" | \"failed\",\n // Stable identifier for the terminal episode, used as the idempotency key so\n // the same completion never wakes the parent twice. A FAILURE passes the\n // failed turn's id: both the in-turn wake (runAgentTurn) and the\n // workflow-level wake (failSession, after it appends more events that would\n // shift lastSequence) key on the same turn, so a finally-throw that turns one\n // failure into both paths still dedupes. An idle episode has no single\n // owning turn, so it falls back to the child's lastSequence — which advances\n // per work batch and is stable across retries of that same idle transition.\n episodeKey?: string | null,\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 ?? child.lastSequence}`;\n const payload = childCompletionPayload(child, goal, terminalStatus);\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:\n terminalStatus === \"failed\"\n ? \"failure\"\n : goal?.status === \"paused\"\n ? \"action_required\"\n : \"success\",\n sourceId: child.id,\n dedupeKey: clientEventId,\n summary: childCompletionSummary(child, goal, terminalStatus),\n payload,\n lineage: { childSessionId: child.id, parentSessionId: child.parentSessionId },\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 completion\", {\n childSessionId,\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 },\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 terminalStatus: \"idle\" | \"failed\",\n): Extract<SessionSystemUpdatePayload, { type: \"child_terminal_result\" }> {\n return {\n type: \"child_terminal_result\",\n childSessionId: child.id,\n status: terminalStatus,\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","const MIN_REDACTABLE_VALUE_LENGTH = 6;\n\nexport type SecretForRedaction = {\n name: string;\n value: string;\n};\n\n/**\n * Defense-in-depth against an agent echoing injected workspace environment\n * values (for example via `env`) into session events. Deep-walks payloads and\n * replaces every exact occurrence of each secret value with\n * `[redacted:<NAME>]`. Values shorter than six characters are skipped to avoid\n * a false-positive flood; secrets are applied longest-value-first so\n * overlapping values redact deterministically.\n */\nexport function createSecretRedactor(secrets: SecretForRedaction[]): (payload: unknown) => unknown {\n const usable = secrets\n .filter((secret) => secret.value.length >= MIN_REDACTABLE_VALUE_LENGTH)\n .sort((a, b) => b.value.length - a.value.length);\n if (usable.length === 0) {\n return identityRedactor;\n }\n const redact = (payload: unknown): unknown => {\n if (typeof payload === \"string\") {\n let out = payload;\n for (const secret of usable) {\n if (out.includes(secret.value)) {\n out = out.split(secret.value).join(`[redacted:${secret.name}]`);\n }\n }\n return out;\n }\n if (Array.isArray(payload)) {\n return payload.map(redact);\n }\n if (isPlainObject(payload)) {\n return Object.fromEntries(\n Object.entries(payload).map(([key, value]) => [key, redact(value)]),\n );\n }\n return payload;\n };\n return redact;\n}\n\nexport function identityRedactor(payload: unknown): unknown {\n return payload;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n","import type { FileAsset, ResourceRef, SessionSystemUpdate } from \"@opengeni/contracts\";\nimport {\n getActiveSessionHistoryItems,\n getLatestRunState,\n getSandboxSessionEnvelope,\n getSessionEvent,\n listSessionSystemUpdatesForTurn,\n requireFile,\n type Database,\n} from \"@opengeni/db\";\nimport {\n stripReasoningEncryptedContent,\n stripReasoningIdentityFromSerializedRunState,\n neutralizeToolSearchItemsInSerializedRunState,\n type OpenGeniRuntime,\n} from \"@opengeni/runtime\";\n\n/**\n * The codex account THIS turn runs on, threaded into every history read path so a\n * cross-account turn never replays another account's encrypted reasoning. The\n * single rule across all paths: DROP any reasoning item whose producing codex\n * account differs from `currentCodexCredentialId`.\n *\n * `currentCodexCredentialId` is the resolved codex credential id on a codex turn,\n * or NULL on a non-codex turn (the \"account\" of the built-in Azure/OpenAI path).\n * NULL is a real value in the comparison, not a \"skip\" sentinel: a non-codex turn\n * (current = null) still drops codex-produced reasoning (producer != null) so a\n * foreign encrypted blob never reaches the Azure/built-in Responses call. A\n * session with no codex history (every producer == null == current) is a no-op.\n */\nexport type TurnCodexAccount = { currentCodexCredentialId: string | null };\n\n/** A non-codex turn's account (current = null): no codex credential resolved. */\nconst NON_CODEX_TURN: TurnCodexAccount = { currentCodexCredentialId: null };\n\n/**\n * Apply the cross-account reasoning strip to a set of stored history rows. Pure +\n * non-mutating. The single rule: a row whose producing codex account EQUALS the\n * turn's current account replays verbatim (by reference); a row produced by a\n * DIFFERENT account is treated by item type —\n *\n * - `reasoning` → DROPPED WHOLE (id + blob filtered out of the history). The\n * foreign `rs_…` id is validated by the Responses backend, which rejects a\n * reasoning item that has a foreign id and no encrypted_content (store:false),\n * so blanking only the blob is not enough — the whole item must go.\n * - `compaction` → kept, with only its account-bound `encrypted_content` blob\n * stripped (its summary is real conversation content that must survive).\n * - everything else (messages, tool calls, tool outputs) → kept verbatim by\n * reference; message and tool content are never account-bound, never touched.\n *\n * Mismatch covers a foreign codex account, the non-codex/Azure producer (null on\n * a codex turn), and legacy untagged rows (null): all are stripped, which is\n * defensive and harmless (at most one turn of lost chain-of-thought continuity,\n * never any content). No-op (rows by reference) when every producer equals the\n * current account — a single-account workspace, an unchanged-account turn, or a\n * non-codex turn over a history with no codex-produced reasoning.\n */\nexport function applyCodexHistoryStrip(\n rows: ReadonlyArray<{ item: Record<string, unknown>; producerCodexCredentialId: string | null }>,\n current: TurnCodexAccount,\n): Array<Record<string, unknown>> {\n const out: Array<Record<string, unknown>> = [];\n for (const row of rows) {\n if (row.producerCodexCredentialId === current.currentCodexCredentialId) {\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 // Foreign reasoning: drop the WHOLE item (id + blob) — see rule above.\n continue;\n }\n if (type === \"tool_search_call\" || type === \"tool_search_output\") {\n // Foreign tool_search items (progressive connector disclosure): drop WHOLE,\n // like reasoning. The `tsc_…` id is minted by the producing account's\n // backend, and the output's disclosure set reflects THAT account's\n // connectors — replaying either into a different account risks a 400 /\n // wrong-connector disclosure. Dropping both sides keeps the pair invariant\n // (the history sanitizer would drop a stranded half anyway); the model\n // simply re-searches on the new account, re-disclosing from the NEW\n // account's own connector pool. Never any content loss — search items\n // carry tool metadata, not conversation content.\n continue;\n }\n if (type === \"compaction\") {\n out.push(stripReasoningEncryptedContent(row.item));\n continue;\n }\n out.push(row.item);\n }\n return out;\n}\n\n/**\n * Resolve the serialized RunState used only for an approval resume, applying\n * the same cross-account rule as the canonical history-items path. The blob\n * carries no per-item producer tag, so we\n * compare the codex account that FROZE the state to the resuming turn's account:\n * when they differ, neutralize every reasoning item's account-bound identity\n * (encrypted_content + provider id) in the blob; when they match (including\n * null == null for non-codex / single-account) the blob replays byte-for-byte\n * (same string reference). This closes the gap where a frozen A-minted RunState\n * was replayed verbatim into a turn that switched to account B (or to a non-codex\n * turn), 400ing the resume.\n */\nexport function resumeRunStateForCodexAccount(\n state: { serializedRunState: string; frozenCodexCredentialId: string | null },\n current: TurnCodexAccount,\n): string {\n if (state.frozenCodexCredentialId === current.currentCodexCredentialId) {\n return state.serializedRunState;\n }\n // Cross-account: neutralize reasoning identity in place AND flip frozen\n // tool_search pairs to execution:\"server\" in place (count-preserving — HOLE E\n // forbids removing blob items). The server flip makes the SDK skip its\n // client-executor rehydration (which would THROW when the resuming account's\n // connector pool differs from the freezing account's); the flipped shape is\n // live-verified wire-safe. The model can still re-search on this account.\n return neutralizeToolSearchItemsInSerializedRunState(\n stripReasoningIdentityFromSerializedRunState(state.serializedRunState),\n );\n}\n\n/**\n * A prepared turn input plus the watermark-seed discriminator the reconcile pass\n * needs (HOLE E). `modelHistoryFromItems` is TRUE iff `state.history` was seeded\n * from the cross-account-STRIPPED active history items (the items read path) — so\n * the turn-end reconcile must seed `persistedHistoryCount` from the SAME strip\n * (HOLE D). It is FALSE only when `state.history` was seeded from the approval\n * RunState: there\n * foreign reasoning is NEUTRALIZED-IN-PLACE by {@link resumeRunStateForCodexAccount}\n * (the item is KEPT, only its id/encrypted_content go), so the blob's history\n * length still COUNTS those items. Seeding the watermark with the strip on that\n * path under-counts by K and the reconcile re-appends K already-persisted items at\n * fresh positions — that is HOLE E. The watermark must therefore NOT strip on the\n * blob path (count the raw sanitized active length, matching the blob).\n */\nexport type PreparedTurnInput = {\n input: Awaited<ReturnType<OpenGeniRuntime[\"prepareInput\"]>>;\n modelHistoryFromItems: boolean;\n};\n\nexport type TurnInputOptions = {\n turnId: string;\n recovering?: boolean;\n unavailableSandboxFilesNote?: string;\n};\n\nexport async function turnInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: Awaited<ReturnType<typeof getSessionEvent>>,\n current: TurnCodexAccount = NON_CODEX_TURN,\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 const updateContext = systemUpdateContext(updates);\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 updateContext,\n options.unavailableSandboxFilesNote,\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 attachmentContext = await userMessageAttachmentsContext(\n db,\n trigger.workspaceId,\n Array.isArray(payload.resources) ? (payload.resources as ResourceRef[]) : [],\n );\n return await messageInput(\n db,\n runtime,\n agent,\n trigger,\n undefined,\n joinInternalContext(internalContext, attachmentContext),\n current,\n );\n }\n if (trigger.type === \"system.update.delivered\") {\n if (!internalContext) throw new Error(\"Internal update inference has no delivered updates\");\n return await messageInput(db, runtime, agent, trigger, undefined, internalContext, current);\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 return {\n input: await runtime.prepareInput(agent, {\n kind: \"approval\",\n // Cross-account run-state strip (HOLE C): if the account resuming this\n // frozen approval differs from the one that froze it, neutralize the\n // blob's account-bound reasoning before replay (else byte-for-byte).\n serializedRunState: resumeRunStateForCodexAccount(state, current),\n approvalId: String(payload.approvalId ?? \"\"),\n decision: payload.decision === \"approve\" ? \"approve\" : \"reject\",\n ...(typeof payload.message === \"string\" ? { message: payload.message } : {}),\n }),\n // Model seeded from the run-state BLOB (neutralize-in-place), NOT stripped\n // items: the reconcile watermark must NOT apply the cross-account strip\n // (HOLE E) — else a cross-account approval resume re-appends K\n // already-persisted items at fresh positions.\n modelHistoryFromItems: false,\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\nfunction systemUpdateContext(updates: SessionSystemUpdate[]): string | undefined {\n if (updates.length === 0) return undefined;\n return [\n \"[OpenGeni internal updates]\",\n \"These platform updates were delivered together for this inference. They are not human prompts.\",\n JSON.stringify({\n updates: updates.map((update) => ({\n id: update.id,\n kind: update.kind,\n classification: update.classification,\n sourceId: update.sourceId,\n summary: update.summary,\n payload: update.payload,\n lineage: update.lineage,\n })),\n }),\n ].join(\"\\n\");\n}\n\n/** Build one inference from canonical history plus optional ephemeral system 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 current: TurnCodexAccount = NON_CODEX_TURN,\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 historyItems = applyCodexHistoryStrip(stored, current);\n return {\n input: await runtime.prepareInput(agent, {\n kind: \"message\",\n ...(text ? { text } : {}),\n ...(internalContext ? { internalContext } : {}),\n historyItems: historyItems as any,\n sandboxEnvelope: envelope,\n }),\n modelHistoryFromItems: true,\n };\n}\n\nexport async function userMessageTextWithAttachments(\n db: Database,\n workspaceId: string,\n text: string,\n resources: ResourceRef[],\n): Promise<string> {\n const attachmentContext = await userMessageAttachmentsContext(db, workspaceId, resources);\n return attachmentContext ? [text, \"\", attachmentContext].join(\"\\n\") : text;\n}\n\nasync function userMessageAttachmentsContext(\n db: Database,\n workspaceId: string,\n resources: ResourceRef[],\n): Promise<string | undefined> {\n const attachedFiles: string[] = [];\n for (const resource of resources) {\n if (resource.kind !== \"file\") {\n continue;\n }\n const file = await requireFile(db, workspaceId, resource.fileId);\n attachedFiles.push(\n `- ${file.filename} (${file.contentType}, ${file.sizeBytes} bytes): ${sandboxFilePath(resource, file)}`,\n );\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/${resource.mountPath ?? `files/${file.id}`}/${file.safeFilename}`;\n}\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 \"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","// 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 type { Settings } from \"@opengeni/config\";\nimport {\n acquireLease,\n commitWarmingToWarm,\n failWarmingToCold,\n getSandboxSessionEnvelope,\n markWarmLeaseInstanceLost,\n persistWarmSnapshot,\n readLease,\n recordWarmingSandboxCreated,\n releaseLeaseHolder,\n touchLeaseHolder,\n SandboxLeaseSupersededError,\n type Database,\n type LeaseHolderKind,\n} from \"@opengeni/db\";\nimport {\n establishSandboxSessionFromEnvelope,\n isProviderSandboxNotFoundError,\n SandboxResumeStateUnavailableError,\n serializeEstablishedSandboxEnvelope,\n deletePriorPersistedSnapshot,\n tagModalSandbox,\n type EstablishedSandboxSession,\n type RuntimeMetricsHooks,\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\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 /** 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 (solo holder recreates;\n * N-holders throw SandboxImageConflictError). Omitted -> image is not enforced (the\n * selfhosted path never passes it; a legacy/null-image box 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 (solo holder recreates cold on the new\n * rig; N-holders throw SandboxRigConflictError). Omitted for a rig-less session\n * -> 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 if (established.backendId !== \"modal\") return;\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) {\n throw new Error(\"Modal sandbox session does not expose exec\");\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n run.call(session, {\n cmd: \"true\",\n yieldTimeMs: 1_000,\n maxOutputTokens: 1_000,\n }),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new SandboxWarmingTimeoutError(established.backendId, timeoutMs)),\n timeoutMs,\n );\n if (timer && \"unref\" in timer && typeof timer.unref === \"function\") timer.unref();\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nclass SnapshotTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`workspace snapshot timed out after ${timeoutMs}ms`);\n this.name = \"SnapshotTimeoutError\";\n }\n}\n\nexport async function waitForWarmSnapshot(\n snapshot: Promise<unknown>,\n timeoutMs: number,\n): Promise<boolean> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n snapshot,\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 (error instanceof SnapshotTimeoutError) {\n console.error(\"mid-session workspace snapshot wait timed out (turn unaffected)\", error);\n return false;\n }\n return true;\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\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 {\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 {\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, string> | 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 capturedAt = sessionState?.workspaceArchiveAt;\n return {\n workspaceArchive: archive,\n ...(typeof previous === \"string\" && previous.length > 0\n ? { workspaceArchivePrev: previous }\n : {}),\n ...(typeof capturedAt === \"string\" && capturedAt.length > 0\n ? { workspaceArchiveAt: capturedAt }\n : {}),\n };\n}\n\nfunction preserveWorkspaceArchivesOnResumeState(\n resumeState: Record<string, unknown> | null,\n archiveSource: Record<string, unknown> | null,\n): Record<string, unknown> | null {\n const archiveFields = workspaceArchiveFieldsFromEnvelope(archiveSource);\n if (!archiveFields) {\n return resumeState;\n }\n const existingSessionState =\n resumeState && typeof resumeState.sessionState === \"object\" && resumeState.sessionState !== null\n ? (resumeState.sessionState as Record<string, unknown>)\n : {};\n return {\n ...(resumeState ?? {}),\n ...(resumeState?.backendId === undefined && archiveSource?.backendId !== undefined\n ? { backendId: archiveSource.backendId }\n : {}),\n sessionState: {\n ...existingSessionState,\n ...archiveFields,\n },\n };\n}\n\n/**\n * MID-SESSION /workspace snapshot (sandbox-file-persistence). The reaper's\n * drain-persist only protects boxes the reaper itself kills; anything else —\n * Modal's hard creation-time timeout catching a session busy past it, provider\n * OOM/infra death — loses everything since the last clean drain (staging\n * session e644e8a8, 2026-07-06: mid-turn box termination cost an unpushed\n * branch + 2 commits). While a turn HOLDS the live box, this folds a fresh\n * snapshot onto the lease through persistWarmSnapshot (the warm sibling of the\n * drain seam: epoch-fenced CAS + atomic throttle re-check) and GCs the\n * superseded snapshot image, bounding worst-case loss of ANY unclean box death\n * to sandboxSnapshotIntervalMs.\n *\n * Never throws and never blocks turn progress semantics: every failure path\n * returns false (the snapshot is protection, not a turn dependency). No-ops\n * when the interval is 0, the backend has no persistWorkspace (selfhosted =\n * the user's machine IS the persistence), or a snapshot newer than the\n * interval already rides the lease.\n */\nexport async function maybePersistWarmWorkspaceSnapshot(\n services: SandboxResumeServices,\n ids: { accountId: string; workspaceId: string; sandboxGroupId: string },\n session: unknown,\n leaseEpoch: number,\n): Promise<boolean> {\n const { db, settings } = services;\n const intervalMs = settings.sandboxSnapshotIntervalMs;\n if (intervalMs <= 0) {\n return false;\n }\n const persistable = session as {\n persistWorkspace?: () => Promise<Uint8Array | undefined>;\n };\n if (typeof persistable.persistWorkspace !== \"function\") {\n return false;\n }\n try {\n // Cheap throttle pre-check before the (potentially slow) capture;\n // persistWarmSnapshot re-checks atomically under the row lock, so this is\n // purely a cost optimization, not the correctness guard.\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (!lease || lease.leaseEpoch !== leaseEpoch || lease.liveness !== \"warm\") {\n return false;\n }\n const sessionState =\n lease.resumeState && typeof lease.resumeState === \"object\"\n ? (lease.resumeState as { sessionState?: Record<string, unknown> }).sessionState\n : undefined;\n const priorAtRaw =\n sessionState && typeof sessionState === \"object\"\n ? sessionState.workspaceArchiveAt\n : undefined;\n const priorAtMs = typeof priorAtRaw === \"string\" ? Date.parse(priorAtRaw) : Number.NaN;\n if (Number.isFinite(priorAtMs) && Date.now() - priorAtMs < intervalMs) {\n 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 // On timeout the race settles on `undefined` while persistWorkspace() keeps\n // running orphaned. Swallow its LATE settlement: an un-awaited rejection\n // after the race resolved would surface as an unhandledRejection and can\n // take down the whole worker process — which would defeat the very hang-\n // guard this timeout exists to provide.\n const capture = persistable.persistWorkspace();\n capture.catch(() => undefined);\n const bytes = await Promise.race([\n capture,\n new Promise<undefined>((resolve) => {\n timeout = setTimeout(() => resolve(undefined), settings.sandboxSnapshotTimeoutMs);\n if (timeout && \"unref\" in timeout && typeof timeout.unref === \"function\") {\n timeout.unref();\n }\n }),\n ]).finally(() => {\n if (timeout) {\n clearTimeout(timeout);\n }\n });\n if (!bytes || bytes.length === 0) {\n return false;\n }\n const { wrote, priorArchiveForGc } = await persistWarmSnapshot(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n workspaceArchive: Buffer.from(bytes).toString(\"base64\"),\n minIntervalMs: intervalMs,\n capturedAtMs,\n });\n if (!wrote) {\n return false;\n }\n // Warm snapshots retain a 2-deep restore window. Only the two-ago archive\n // returned by persistWarmSnapshot is GC-eligible.\n await deletePriorPersistedSnapshot(persistable, priorArchiveForGc);\n return true;\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(\"mid-session workspace snapshot failed (turn unaffected)\", error);\n return false;\n }\n}\n\n/**\n * Resume the one box for a single turn (or any worker-side resume op). Returns\n * the live non-owned session + the fence epoch + a release fn. The CALLER owns\n * the lifecycle: inject non-owned, run, then `await release()` and drop the\n * handle in `finally`.\n *\n * holderId is the globally unique durable turn-attempt id. It must not be a\n * Temporal activity id, because activity ids are only workflow-local and\n * collide when sibling sessions share one sandbox group.\n */\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\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 let released = false;\n let holderLivenessTimer: ReturnType<typeof setInterval> | undefined;\n const release = async (): Promise<void> => {\n if (released) {\n return;\n }\n released = true;\n if (holderLivenessTimer) {\n clearInterval(holderLivenessTimer);\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\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 SandboxImageConflictError\n // propagates to the turn activity (an actionable error); a solo image change is handled\n // by acquireLease recreating the box cold on 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 to the turn activity (actionable); a solo rig change recreates cold.\n ...(ids.rigVersionId ? { rigVersionId: ids.rigVersionId } : {}),\n leaseTtlMs,\n warmingLeaseTtlMs: settings.sandboxWarmingTimeoutMs,\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 }).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 === \"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 try {\n const envelope = await getSandboxSessionEnvelope(db, ids.workspaceId, ids.sessionId);\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 spawnEnvelope = acquired.lease.resumeState ?? envelope;\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 const resumeEnvelope = preserveWorkspaceArchivesOnResumeState(\n (await serializeEstablishedSandboxEnvelope(created)) ?? null,\n spawnEnvelope,\n );\n const recorded = await recordWarmingSandboxCreated(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n instanceId: created.instanceId,\n resumeBackendId: created.backendId,\n resumeState: resumeEnvelope,\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 },\n });\n createdEstablished = established;\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 // 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. Fall back to the session envelope only\n // when the client cannot serialize live state.\n const serializedResumeEnvelope =\n (await serializeEstablishedSandboxEnvelope(established)) ?? envelope;\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 retire the lease with no archive and recreate an empty box.\n // A failed hydrate falls back to a clean box with origin=\"created\", so its\n // unusable archive is deliberately cleared by the unmerged serialized state.\n const resumeEnvelope =\n established.origin === \"restored\"\n ? preserveWorkspaceArchivesOnResumeState(serializedResumeEnvelope, spawnEnvelope)\n : serializedResumeEnvelope;\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 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 await terminateEstablishedSandbox(established);\n await release();\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\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 await failWarmingToCold(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\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\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 established = await establishSandboxSessionFromEnvelope(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 } catch (error) {\n if (\n !(error instanceof SandboxResumeStateUnavailableError) &&\n !isProviderSandboxNotFoundError(ids.backend, error)\n ) {\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 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 * Stage D machine-primary: acquire the group lease for a turn whose ACTIVE sandbox\n * is a connected machine (selfhosted) WITHOUT establishing a provider box. The\n * \"box\" is the user's physical machine reached over NATS; there is NOTHING to\n * spawn, snapshot, expose, or serialize — so we take the lease (the SAME group-keyed\n * refcount/idle/epoch bookkeeping resumeBoxForTurn uses) but skip every box step.\n *\n * The lease is keyed backend \"selfhosted\": the reaper's terminateProviderBox\n * short-circuits a selfhosted lease (it is the user's machine — NEVER provider-stop),\n * draining it to cold with no stop; and the reaper's warm-meter rate for \"selfhosted\"\n * is 0 (no cloud seconds billed for a box that does not exist). Returns the lease\n * epoch + an idempotent release so the turn's lease-heartbeat + `finally` release are\n * identical to the cloud path.\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 acquireSelfhostedLeaseForTurn(\n services: SandboxResumeServices,\n ids: {\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n sessionId: string;\n },\n kind: \"turn\",\n holderId: TurnSandboxLeaseHolderId,\n): Promise<{ leaseEpoch: number; release: () => Promise<void> }> {\n const { db, settings } = services;\n const leaseTtlMs = settings.sandboxLeaseTtlMs;\n\n let released = false;\n const release = async (): Promise<void> => {\n if (released) {\n return;\n }\n released = true;\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\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: \"selfhosted\",\n os: \"linux\",\n leaseTtlMs,\n warmingLeaseTtlMs: settings.sandboxWarmingTimeoutMs,\n });\n\n // FENCED: a newer epoch re-established the group concurrently. Release our\n // just-registered holder + surface the supersession (the outer turn catch\n // requeues, mirroring resumeBoxForTurn).\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. There is NO box to establish — commit\n // warm immediately so the lease does not linger in 'warming' (no box id, no\n // resume_state; selfhosted is re-addressed by enrollment via the active pointer,\n // never resumed from an envelope). resume_backend_id \"selfhosted\" keeps the\n // reaper's never-provider-stop short-circuit correct.\n if (acquired.role === \"spawner\") {\n const expectedEpoch = acquired.lease.leaseEpoch;\n const committed = await commitWarmingToWarm(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n // No provider box id; stamp a clearly non-box marker for diagnostics.\n instanceId: `selfhosted:${ids.sessionId}`,\n resumeBackendId: \"selfhosted\",\n resumeState: null,\n leaseTtlMs,\n });\n if (!committed.committed || !committed.lease) {\n // A reaper reset our warming row, or a sibling re-established + bumped the\n // epoch. Release our holder; surface supersession (NEVER touch any box).\n await release();\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n return { leaseEpoch: committed.lease.leaseEpoch, release };\n }\n\n // ATTACHED / REARMED: the lease is live. There is no box to resume — just carry\n // the lease epoch (same-session turns are serialized, so a concurrent 'warming'\n // spawner on this group is not expected; the machine session is independent of the\n // lease state regardless).\n return { leaseEpoch: acquired.lease.leaseEpoch, release };\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 // 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 (dossier §10.3): 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 type { Settings } from \"@opengeni/config\";\nimport { getSandbox, readActiveSandbox, type Database } from \"@opengeni/db\";\nimport type { EventBus } from \"@opengeni/events\";\nimport {\n buildSelfhostedBackendSession,\n makeActiveBackendResolver,\n NatsControlRpc,\n NatsOpStreamTransport,\n RoutingSandboxSession,\n type ControlRpc,\n type EstablishedSandboxSession,\n type NatsRequestConnection,\n type RoutableBackendSession,\n type RoutableSandbox,\n type SelfhostedOpObserver,\n type SelfhostedRelayConfig,\n type OpStreamJournal,\n type SelfhostedOpStreamDeps,\n} from \"@opengeni/runtime\";\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 /** 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};\n\nexport type RoutingWiringIds = {\n workspaceId: string;\n sessionId: string;\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 { selfhostedTimeoutMs: timeoutMs, selfhostedExecTimeoutMs: execTimeoutMs };\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 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 });\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 },\n readPointer: async () => {\n const pointer = await readActiveSandbox(db, ids.workspaceId, ids.sessionId);\n return pointer ?? { activeSandboxId: null, activeEpoch: 0 };\n },\n resolveActiveBackend: resolver,\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: { get(): Promise<{ established: EstablishedSandboxSession }> };\n },\n): EstablishedSandboxSession {\n const { db, settings, bus, onOp } = services;\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 return {\n session: provisioned.established.session as RoutableBackendSession,\n sandboxId: null,\n kind: provisioned.established.backendId,\n };\n }\n return routedResolver(pointer);\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 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 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>>();\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 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 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 if (!(inputTokens > 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: inputTokens,\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_hit_ratio{provider}` — cached/prompt for the call,\n * observed whenever prompt tokens are known (>0). A call whose provider does NOT\n * report cached_tokens records a real 0 here — \"we saw a call and the cache did\n * nothing\" is exactly the signal the alert watches, so it must not be swallowed.\n * Absent/zero/non-finite `cachedTokens` (providers that don't report it) is safe: no\n * counter increment, ratio 0. A call with no prompt tokens has no ratio (skipped).\n */\nexport function recordModelCacheTokens(\n observability: Observability,\n provider: string,\n input: { cachedTokens: number | null | undefined; promptTokens: number | null | undefined },\n): void {\n const cached = nonNegativeTokenCount(input.cachedTokens);\n const prompt = nonNegativeTokenCount(input.promptTokens);\n if (cached > 0) {\n observability.incrementCounter({\n name: \"opengeni_model_cached_tokens_total\",\n help: \"Total prompt tokens served from the provider's prompt cache, by provider.\",\n labels: { provider },\n amount: cached,\n });\n }\n if (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 nonNegativeTokenCount(value: number | null | undefined): number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : 0;\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 (dossier §10.1).\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 dossier §7.3 / §19):\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 (60s) 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 lease epoch — a superseded lease writes zero\n// rows (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 (dossier \"Accepted warts\" #2 — 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, randomUUID } 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 (dossier §7.3).\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 (dossier §10.1 — pathological-only; configurable) ─────\nexport const CAPTURE_TIMEOUT_MS = 60_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_DIRS = 600; // BFS round-trip cap (bounds turn-end latency)\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 leaseEpoch: number;\n sandboxGroupId: string;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string | null;\n observability: Observability;\n /** Test-only: override keep-latest-N GC threshold (default 10). */\n keepLatest?: number;\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 60s 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 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 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 ).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 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 // 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 });\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"failed\" },\n });\n } finally {\n if (timer) clearTimeout(timer);\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): Promise<void> {\n const { observability } = input;\n const storage = ctx.objectStorage;\n const keepN = input.keepLatest ?? KEEP_LATEST_REVISIONS;\n // Reads only — no emitter (we publish the announce ourselves after commit).\n const svc = new SandboxChannelAService({ session: input.session, 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 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 const discovery = await svc.detectReposDetailed();\n throwIfCaptureAborted(signal);\n if (!discovery.complete) {\n const capturedAt = new Date();\n const reason = captureDegradedReason(discovery.degradedReason);\n const stats = {\n degradedReason: reason,\n discoveredRepoCount: discovery.repos.length,\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 sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: input.leaseEpoch,\n revision,\n stats,\n capturedAt,\n });\n throwIfCaptureAborted(signal);\n if (!inserted) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"superseded\" },\n });\n return;\n }\n observability.warn(\"workspace capture degraded — repository discovery incomplete\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": input.turnId ?? \"\",\n \"workspace_capture.degraded_reason\": reason,\n \"workspace_capture.discovered_repo_count\": discovery.repos.length,\n });\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"degraded_repository_discovery\" },\n });\n if (input.publish) {\n await input.publish(inserted.events).catch(() => undefined);\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 throwIfCaptureAborted(signal);\n // Per-repo resilience: a box death aborts the whole capture (BoxExitingError\n // propagates); any other single-repo failure (a repo that vanished, a\n // transient git error) SKIPS that repo and the capture continues with the\n // rest. One flaky repo must never kill the capture.\n let status: Awaited<ReturnType<typeof svc.gitStatus>>;\n try {\n status = await svc.gitStatus({ path: root });\n throwIfCaptureAborted(signal);\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n continue;\n }\n if (!status.isRepo) continue;\n // `git diff HEAD`: combined staged+unstaged tracked changes vs HEAD (the\n // review diff). Untracked files are absent here but present in status.files\n // and captured as after-images. A repo with no commits yields an empty diff\n // (git diff HEAD errors → empty numstat) and everything reads as untracked.\n let diff: Awaited<ReturnType<typeof svc.gitDiff>>;\n try {\n diff = await svc.gitDiff({\n path: root,\n staged: false,\n fromRef: \"HEAD\",\n pathspec: [],\n contextLines: 3,\n maxBytesPerFile: PER_FILE_DIFF_GUARD_BYTES,\n });\n throwIfCaptureAborted(signal);\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n diff = { files: [], revision: 0 };\n }\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. (Deviation from the dossier's literal \"clean\"\n // wording — same intent, strictly better; recorded in PROGRESS.)\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 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 (dossier §10.1 / 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 (bounded BFS; residue dirs collapsed, not descended) ─────\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 ?? randomUUID();\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 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 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 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 const inserted = await insertWorkspaceCapture(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\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 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\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 via bounded BFS over the PUBLIC fsList (depth 1\n * per directory). Residue dirs are emitted as collapsed nodes but never queued\n * for descent — a single deep fsList would let node_modules exhaust the entry\n * budget and truncate real files, so we prune at the source. Bounded by\n * TREE_MAX_ENTRIES, TREE_MAX_DIRS round-trips, and the outer capture deadline.\n */\nasync function buildTreeIndex(\n svc: SandboxChannelAService,\n startedAt: number,\n signal: AbortSignal,\n): Promise<{ root: FsTreeNode; entryCount: number; truncated: boolean }> {\n const root: FsTreeNode = {\n name: \"\",\n path: \"\",\n type: \"dir\",\n sizeBytes: null,\n mtimeMs: null,\n mode: null,\n children: [],\n truncated: false,\n };\n const byPath = new Map<string, FsTreeNode>([[\"\", root]]);\n const queue: string[] = [\"\"];\n let entryCount = 0;\n let dirCalls = 0;\n let truncated = false;\n\n while (queue.length > 0) {\n throwIfCaptureAborted(signal);\n if (dirCalls >= TREE_MAX_DIRS || entryCount >= TREE_MAX_ENTRIES) {\n truncated = true;\n break;\n }\n if (Date.now() - startedAt > CAPTURE_TIMEOUT_MS - 5_000) {\n truncated = true;\n break;\n } // leave headroom for PUTs\n const dir = queue.shift()!;\n dirCalls += 1;\n // Per-dir resilience: a directory can vanish or fail to list mid-walk (fs\n // churn on a desktop box, a permission edge). Skip the one directory and keep\n // walking the rest — a single unreadable dir must never abort the tree index.\n // A box death still aborts the whole capture (BoxExitingError).\n let listing: Awaited<ReturnType<typeof svc.fsList>>;\n try {\n listing = await svc.fsList({ path: dir, depth: 1, maxEntries: 2_000, includeHidden: true });\n throwIfCaptureAborted(signal);\n } catch (error) {\n if (isBoxExitingError(error)) {\n throw new BoxExitingError(error instanceof Error ? error.message : String(error));\n }\n truncated = true; // this subtree is incomplete; continue with the rest\n continue;\n }\n if (listing.truncated) truncated = true;\n const parent = byPath.get(dir) ?? root;\n const children = collectImmediateChildren(listing.root);\n for (const child of children) {\n if (entryCount >= TREE_MAX_ENTRIES) {\n truncated = true;\n break;\n }\n const node: FsTreeNode = {\n name: child.name,\n path: child.path,\n type: child.type,\n sizeBytes: child.sizeBytes,\n mtimeMs: child.mtimeMs,\n mode: child.mode,\n truncated: false,\n ...(child.type === \"dir\" ? { children: [] as FsTreeNode[] } : {}),\n };\n (parent.children ??= []).push(node);\n byPath.set(node.path, node);\n entryCount += 1;\n if (node.type === \"dir\") {\n if (RESIDUE_DIR_SET.has(node.name)) {\n node.truncated = true; // collapsed residue dir — contents on the machine\n } else {\n queue.push(node.path);\n }\n }\n }\n }\n return { root, entryCount, truncated };\n}\n\n/** fsList returns a subtree; at depth 1 the immediate children hang off root. */\nfunction collectImmediateChildren(node: FsTreeNode): FsTreeNode[] {\n return node.children ?? [];\n}\n","import { indexDocumentNow } from \"@opengeni/documents\";\nimport { configuredStaticUsageLimits } from \"@opengeni/config\";\nimport {\n getBillingBalance,\n recordUsageEvent,\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 return await withWorkspaceUsageLock(db, input.workspaceId, async (lockedDb) => {\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 );\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 { claimExpiredFileUploadCleanup, completeExpiredFileUploadCleanup } 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;\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};\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\n async function reapExpiredFileUploads(): Promise<ReapExpiredFileUploadsResult> {\n const { db, objectStorage, observability } = await services();\n if (!objectStorage) {\n return { claimed: 0, deleted: 0, failed: 0 };\n }\n\n const claims = await claimExpiredFileUploadCleanup(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 completeExpiredFileUploadCleanup(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 error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (claims.length > 0) {\n observability.info(\"expired file upload cleanup swept\", {\n claimed: claims.length,\n deleted,\n failed,\n });\n }\n return { claimed: claims.length, 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 {\n accrueWarmSeconds,\n confirmDrainCold,\n appendSessionEventToSandboxGroup,\n countQueuedTurns,\n countSandboxLeasesByLiveness,\n forceDrainOverLimitViewerOnlyBoxes,\n getBillingBalance,\n listCreditBalancesByAccount,\n listLiveModalSandboxLeaseAttributions,\n listMeterableWarmLeases,\n persistDrainSnapshot,\n readLease,\n reapExpiredSessionListSnapshots,\n reapStaleLeaseHoldersGlobal,\n rlsContextForWorkspace,\n type MeterableWarmLease,\n type ReapDrainable,\n} from \"@opengeni/db\";\nimport { sandboxWarmRateMicrosPerSecond } from \"@opengeni/config\";\nimport {\n // The reaper attaches to the box by id to terminate it. It does NOT use\n // establishSandboxSessionFromEnvelope (which cold-RESTORES via create() on a\n // NotFound) — restoring a box just to immediately kill it is wrong. Instead it\n // builds the client + resumes the envelope DIRECTLY: a live box resumes, gets\n // its /workspace PERSISTED (snapshot/tar), then is terminated; a gone box\n // (NotFound on resume) is already down, a clean no-op.\n createSandboxClientForBackend,\n deletePriorPersistedSnapshot,\n deserializeSandboxSessionStateEnvelope,\n isProviderSandboxNotFoundError,\n sweepModalOrphanSandboxes,\n terminateModalSandboxById,\n} from \"@opengeni/runtime\";\nimport type { ActivityServices } from \"./types\";\nimport { reconcilePendingParentSystemUpdates } from \"./parent-wake\";\nimport {\n recordCreditBalanceGauges,\n recordCreditMicros,\n recordSandboxLeaseGauges,\n recordSandboxOrphansTerminated,\n recordTurnsQueuedGauge,\n} from \"../observability-metrics\";\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 -> the CAS missed (re-armed / newer epoch / vanished). The box\n * is wanted again; the seam MUST NOT terminate it.\n * - priorArchive / priorArchivePrev -> superseded archives to GC at drain.\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()). priorArchive values are always\n * null in this case.\n */\nexport type PersistArchiveFn = (\n archiveBase64: string | null,\n) => Promise<{ wrote: boolean; priorArchive: string | null; priorArchivePrev: string | null }>;\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 * Returns true when the box was terminated (or already gone), false when persist\n * found the lease re-armed and the box was deliberately LEFT RUNNING. */\nexport type TerminateBoxFn = (\n settings: ActivityServices[\"settings\"],\n lease: NonNullable<Awaited<ReturnType<typeof readLease>>>,\n observability: ActivityServices[\"observability\"],\n persistArchive: PersistArchiveFn,\n) => Promise<boolean>;\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};\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 /**\n * The one global reaper sweep. Idempotent; concurrency-safe with itself.\n * Gated by the caller (the Schedule is only registered when\n * sandboxOwnershipEnabled); a defensive no-op here too so a manual trigger\n * with the flag off 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 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 await refreshQueueLeaseAndCreditGauges(db, observability);\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 forceDrained = await forceDrainOverLimitWorkspaces(\n db,\n settings,\n metered.workspaceIds,\n observability,\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 );\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 await refreshQueueLeaseAndCreditGauges(db, observability);\n\n if (\n drainable.length > 0 ||\n metered.accrued > 0 ||\n forceDrained > 0 ||\n modalOrphansTerminated > 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 });\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\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 try {\n recordSandboxLeaseGauges(observability, await countSandboxLeasesByLiveness(db));\n } catch (error) {\n observability.warn(\"sandbox reaper: sandbox-lease gauge refresh failed\", {\n error: error instanceof Error ? error.message : String(error),\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\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 // Nothing to enforce → skip the whole pass (no lock churn).\n if (!enforceBalance && cap <= 0) {\n return 0;\n }\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\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 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 * 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): 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 // 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 const persistArchive: PersistArchiveFn = async (archiveBase64: string | null) => {\n const result = await persistDrainSnapshot(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n expectedEpoch: row.leaseEpoch,\n workspaceArchive: archiveBase64,\n });\n if (result.wrote && archiveBase64 !== null) {\n persisted = true;\n }\n return result;\n };\n\n // Resume-by-id -> persistWorkspace -> persist-onto-lease -> GC prior snapshot ->\n // provider terminate. A box that is already gone (NotFound) is success (the goal\n // is \"box is not running\"). A genuine PERSIST failure (could not snapshot) or a\n // resume failure on a box that IS alive re-throws -> the lease stays draining for\n // the next sweep (NEVER terminate a box whose files we could not capture). A\n // persist CAS-miss (re-armed) returns false -> the box was left running; skip the\n // cold-commit so the re-armed box is not cold-leaked.\n const terminated = await terminateBox(settings, lease, observability, persistArchive);\n if (!terminated) {\n return false;\n }\n\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 });\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: { actor: \"reaper\", persisted, instanceId: lease.instanceId },\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}\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. modal carries the Modal SDK client used\n// for snapshot-image GC (deletePriorPersistedSnapshot reads session.modal).\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, GC the superseded snapshot, THEN terminate. Resumes\n * DIRECTLY (no cold-restore fallback) so a gone box is a clean no-op, never a\n * 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 (epoch-fenced);\n * - GC the PRIOR snapshot (keep-latest-per-lease);\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<boolean> {\n const backend = (lease.resumeBackendId ?? lease.backend) as string;\n // 'none' / no backend -> nothing to terminate.\n if (!backend || backend === \"none\") {\n return true;\n }\n\n // CRITICAL SAFETY (bring-your-own-compute, dossier §19/§21): 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 true;\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 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 return true;\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 true;\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 true;\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 backend that cannot resume cannot be attached-to for terminate; the\n // provider idle-timeout is the backstop. No-op.\n return true;\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 return true;\n }\n session = (await client.resume(resumedState)) as PersistableSession;\n sessionState = resumedState;\n } catch (error) {\n if (isProviderSandboxNotFoundError(client.backendId, error)) {\n observability.info(\n \"sandbox reaper: drainable box already gone (NotFound on resume) — proceeding to cold\",\n {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n },\n );\n return 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 archiveBytes: Uint8Array | undefined;\n try {\n archiveBytes = session?.persistWorkspace ? await session.persistWorkspace() : undefined;\n } catch (error) {\n if (isProviderSandboxNotFoundError(client.backendId, error)) {\n observability.info(\n \"sandbox reaper: box gone during persist (NotFound) — nothing to snapshot, proceeding to cold\",\n {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n },\n );\n return 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 (archiveBytes && archiveBytes.length > 0) {\n const archiveBase64 = Buffer.from(archiveBytes).toString(\"base64\");\n const { wrote, priorArchive, priorArchivePrev } = await persistArchive(archiveBase64);\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 false;\n }\n // Keep-latest-per-lease GC: best-effort delete the prior snapshot image now,\n // while the session (and its Modal client) is still live. Never throws.\n const deleted = await deletePriorPersistedSnapshot(session, priorArchive);\n if (deleted) {\n observability.info(\"sandbox reaper: GC'd superseded workspace snapshot\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n snapshotId: deleted,\n });\n }\n const deletedPrev = await deletePriorPersistedSnapshot(session, priorArchivePrev);\n if (deletedPrev) {\n observability.info(\"sandbox reaper: GC'd superseded previous workspace snapshot\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n snapshotId: deletedPrev,\n });\n }\n } else {\n // No archive produced (backend has no persistWorkspace or returned empty).\n // CAS-check via persistArchive(null): if the lease was re-armed during the\n // snapshot window, wrote:false → leave the box RUNNING (abort terminate).\n const { wrote } = await persistArchive(null);\n if (!wrote) {\n observability.info(\n \"sandbox reaper: lease re-armed during snapshot window (no-archive path) — leaving box RUNNING (no terminate)\",\n {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n },\n );\n return false;\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 true;\n }\n if (session?.kill) {\n await session.kill();\n return true;\n }\n if (session?.terminate) {\n await session.terminate();\n return true;\n }\n if (session?.close && !session.closed) {\n await session.close();\n }\n } catch (error) {\n observability.warn(\"sandbox reaper: provider terminate raised (box may already be gone)\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return true;\n}\n","import {\n appendSessionEventsWithLockedSessionUpdate,\n addSessionSystemUpdateWithSourceMutation,\n createScheduledTaskRun,\n createSession,\n createSessionGoal,\n enqueueSessionWorkflowWakeIfRunnable,\n getBillingBalance,\n getRig,\n getVariableSet,\n isCodexBilledTurn,\n markScheduledTaskRunFailedIfQueued,\n recordUsageEvent,\n requireScheduledTask,\n requireSession,\n setTemporalWorkflowId,\n settleScheduledTaskRunInTransaction,\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 const task = await requireScheduledTask(db, input.workspaceId, input.taskId);\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 await ensureScheduledRunAllowed(\n settings,\n db,\n task.accountId,\n task.workspaceId,\n input.agentRunUsageIdempotencyKey ? 0 : 1,\n isCodexRun,\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 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 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 (set_session_title,\n // goal tools, and the permission-gated tools), matching the API path.\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 const 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 ...task.agentConfig.metadata,\n model,\n reasoningEffort,\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 });\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 scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n // Names/ids only; never values.\n ...(variableSet\n ? { variableSetId: variableSet.id, variableSetName: variableSet.name }\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 },\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 // 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 },\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 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 ensureScheduledRunAllowed(\n settings: Settings,\n db: ActivityServices[\"db\"],\n accountId: string,\n workspaceId: string,\n requestedAgentRuns: number,\n isCodexRun: boolean,\n): Promise<void> {\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 throw new Error(\"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 throw new Error(\n `monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`,\n );\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 throw new Error(\n `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`,\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","import {\n settleSessionAttemptInterruptions,\n applySessionTurnSettlement,\n recoverSessionDispatch,\n peekSessionWork as peekSessionWorkDb,\n countQueuedTurns,\n getSessionEvent,\n getSessionTurnForAttempt,\n requireSession,\n settleSessionIdleWithParentOutbox,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport { notifyParentOfChildTerminal } from \"./parent-wake\";\nimport { recordTurnsQueuedGauge } from \"../observability-metrics\";\nimport type {\n ActivityServices,\n PeekSessionWorkInput,\n FailSessionAttemptInput,\n SettleSessionInterruptionsInput,\n MarkSessionIdleInput,\n RecoverDispatchInput,\n RecoverDispatchResult,\n} from \"./types\";\n\nexport type SessionStateActivityOverrides = Partial<{\n settleSessionAttemptInterruptions: typeof settleSessionAttemptInterruptions;\n applySessionTurnSettlement: typeof applySessionTurnSettlement;\n recoverSessionDispatch: typeof recoverSessionDispatch;\n peekSessionWork: typeof peekSessionWorkDb;\n countQueuedTurns: typeof countQueuedTurns;\n getSessionEvent: typeof getSessionEvent;\n getSessionTurnForAttempt: typeof getSessionTurnForAttempt;\n requireSession: typeof requireSession;\n settleSessionIdleWithParentOutbox: typeof settleSessionIdleWithParentOutbox;\n publishDurableSessionEvents: typeof publishDurableSessionEvents;\n notifyParentOfChildTerminal: typeof notifyParentOfChildTerminal;\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 recoverSessionDispatchFn = overrides.recoverSessionDispatch ?? recoverSessionDispatch;\n const peekSessionWorkFn = overrides.peekSessionWork ?? peekSessionWorkDb;\n const countQueuedTurnsFn = overrides.countQueuedTurns ?? countQueuedTurns;\n const getSessionEventFn = overrides.getSessionEvent ?? getSessionEvent;\n const getSessionTurnForAttemptFn = overrides.getSessionTurnForAttempt ?? getSessionTurnForAttempt;\n const requireSessionFn = overrides.requireSession ?? requireSession;\n const settleSessionIdleWithParentOutboxFn =\n overrides.settleSessionIdleWithParentOutbox ?? settleSessionIdleWithParentOutbox;\n const publishDurableSessionEventsFn =\n overrides.publishDurableSessionEvents ?? publishDurableSessionEvents;\n const notifyParentOfChildTerminalFn =\n overrides.notifyParentOfChildTerminal ?? notifyParentOfChildTerminal;\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 notifyParentOfChildTerminalFn(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n \"failed\",\n );\n }\n\n async function settleSessionInterruptions(\n input: SettleSessionInterruptionsInput,\n ): Promise<{ action: \"paused\" | \"continue\" | \"stale\" }> {\n const { db, bus, observability } = await services();\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 /**\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 notifyParentOfChildTerminalFn(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n \"failed\",\n `turn:${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 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 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 notifyParentOfChildTerminalFn(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n \"idle\",\n settled.episodeKey,\n );\n }\n\n return {\n failSessionAttempt,\n settleSessionInterruptions,\n recoverDispatch,\n peekSessionWork,\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 {\n recordRigAuditEvent,\n classifyRigVerificationOutcome,\n promoteSetupAppendChange,\n} from \"@opengeni/core\";\nimport {\n beginRigChangeVerificationAttempt,\n getRig,\n getRigChange,\n getRigVersionById,\n sanitizeEventPayload,\n sanitizeEventString,\n sanitizeMemoryText,\n updateRigChangeStatus,\n type Database,\n} from \"@opengeni/db\";\nimport {\n establishSandboxSessionFromEnvelope,\n runRigSetupHook,\n sandboxCommandExitCode,\n sandboxCommandOutput,\n type EstablishedSandboxSession,\n} from \"@opengeni/runtime\";\nimport type { ActivityServices } from \"./types\";\nimport { settingsWithRigImage } from \"./packs\";\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\ntype CommandSession = {\n exec?: (args: Record<string, unknown>) => Promise<unknown>;\n execCommand?: (args: Record<string, unknown>) => Promise<unknown>;\n};\n\nconst OUTPUT_TAIL_LIMIT = 64 * 1024;\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<void> {\n if (!established) {\n return;\n }\n const client = established.client as { delete?: (state: unknown) => Promise<unknown> };\n if (typeof client.delete === \"function\" && established.sessionState !== undefined) {\n await client.delete(established.sessionState).catch(() => undefined);\n return;\n }\n const session = established.session as {\n terminate?: () => Promise<unknown>;\n kill?: () => Promise<unknown>;\n close?: () => Promise<unknown>;\n closed?: boolean;\n };\n if (session.terminate) {\n await session.terminate().catch(() => undefined);\n } else if (session.kill) {\n await session.kill().catch(() => undefined);\n } else if (session.close && !session.closed) {\n await session.close().catch(() => undefined);\n }\n}\n\nasync function runCommand(\n session: CommandSession,\n command: string,\n timeoutMs: number,\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 = session.exec\n ? await session.exec(args)\n : session.execCommand\n ? await session.execCommand(args)\n : (() => {\n throw new Error(\"Sandbox session does not support command execution\");\n })();\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\nexport function createRigVerificationActivities(services: () => Promise<ActivityServices>) {\n return {\n verifyRigChange: async (input: { workspaceId: string; changeId: string }) => {\n const { settings, db } = await services();\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 let established: EstablishedSandboxSession | null = null;\n const verification: Record<string, unknown> = { startedAt, checkResults: [] };\n try {\n const candidateVersion = candidateVersionForChange(baseVersion, change);\n const runSettings = settingsWithRigImage(settings, candidateVersion.image);\n established = await establishSandboxSessionFromEnvelope(runSettings, null, {\n sessionId: `rig-verification-${change.id}`,\n recovery: \"create-or-restore\",\n environment: {},\n });\n if ((candidateVersion.setupScript ?? \"\").trim()) {\n await runRigSetupHook(established.session as never, {\n environment: {},\n runAs: \"root\",\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 CommandSession,\n command,\n settings.rigSetupTimeoutMs,\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 CommandSession,\n check.command,\n settings.rigSetupTimeoutMs,\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 } 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 return updated;\n } finally {\n await terminateThrowaway(established);\n }\n },\n\n verifyRigVersion: async (input: { workspaceId: string; versionId: string }) => {\n const { settings, db } = await services();\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 let established: EstablishedSandboxSession | null = null;\n try {\n const runSettings = settingsWithRigImage(settings, version.image);\n established = await establishSandboxSessionFromEnvelope(runSettings, null, {\n sessionId: `rig-version-verification-${version.id}`,\n recovery: \"create-or-restore\",\n environment: {},\n });\n if ((version.setupScript ?? \"\").trim()) {\n await runRigSetupHook(established.session as never, {\n environment: {},\n runAs: \"root\",\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 CommandSession,\n check.command,\n settings.rigSetupTimeoutMs,\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 } 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 } finally {\n await terminateThrowaway(established);\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 | \"dispatchScheduledTaskRun\"\n | \"enqueueGoalRetryWake\"\n | \"failSessionAttempt\"\n | \"getCodexCapacityWait\"\n | \"markSessionIdle\"\n | \"peekSessionWork\"\n | \"reconcileCodexCapacityWait\"\n | \"recoverDispatch\"\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/** Goal continuation is advisory at an idle boundary. A transient failure gets\n * a short retry window, then records an explicit delayed outbox wake instead\n * of relying on an unrelated future mutation. */\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) {\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 may complete the durable control transition immediately,\n // but the session workflow must remain open until the old turn activity is\n // physically gone. Leaving this implicit uses Temporal's try-cancel wire\n // default: the activity promise rejects as soon as cancellation is\n // requested and the workflow can close while the worker keeps streaming.\n cancellationType: 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 { dbSql, type Database } 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 checks: Record<ReadinessCheckName, { ok: boolean; error?: string }>;\n};\n\nexport function startWorkerHttpServer(input: {\n settings: Settings;\n observability: Observability;\n checks: ReadinessChecks;\n timeoutMs?: number;\n}): ReturnType<typeof Bun.serve> {\n const { settings, observability, checks } = input;\n const timeoutMs = input.timeoutMs ?? 2_000;\n return Bun.serve({\n hostname: \"0.0.0.0\",\n port: settings.workerHttpPort,\n async fetch(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 return Response.json({\n service: settings.serviceName,\n environment: settings.environment,\n deploymentRevision: settings.deploymentRevision,\n ok: true,\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 result = await runReadinessChecks(checks, timeoutMs);\n return Response.json(result, { status: result.ok ? 200 : 503 });\n }\n return Response.json({ error: \"not_found\" }, { status: 404 });\n },\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(db: Database): () => Promise<void> {\n return async () => {\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\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","/**\n * Process-local Temporal execution ceilings.\n *\n * Turn workers host only runAgentTurn, so this is the exact number of agent\n * turns one worker process may own concurrently. Keep the value centralized so\n * production and the real Temporal integration harness exercise one topology.\n */\nexport const TURN_WORKER_MAX_CONCURRENT_TURNS = 16;\n\nexport const CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES = 32;\nexport const CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS = 40;\n"],"mappings":";AAAA;AAAA,EACE,gBAAAA;AAAA,EACA,eAAAC;AAAA,EACA,+BAAAC;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,YAAAC,WAAU,wCAAuD;AAC1E,SAAS,sBAAAC,2BAA0B;AACnC;AAAA,EACE,uBAAAC;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,OACL;AACP,SAAS,kBAAkB,cAAc;AACzC,SAAS,4BAAAC,iCAAgC;;;ACtBzC,SAAS,cAAc,aAAa,mCAAmC;AACvE,SAAS,gBAAgB;AACzB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,oCAAoC;AAC7C,SAAS,uBAAAC,4BAA2B;;;ACNpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAAC;AAAA,EACA,qBAAAC;AAAA,EACA;AAAA,EACA,eAAAC;AAAA,EACA,mBAAAC;AAAA,EACA,kBAAAC;AAAA,EACA,qBAAAC;AAAA,EACA,qBAAAC;AAAA,EACA,oCAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;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AG,cAAc,QAAQ;AAAA,MAC7B;AAAA,IACF;AACA,kBAAc,KAAK,6BAA6B;AAAA,MAC9C;AAAA,MACA,mBACE,SAAS,YAAY,SAAS,oBAAoB,cAAc,SAAS,iBAAiB;AAAA,MAC5F,qCACE,SAAS,SACL,mCACA;AAAA,MACN,qCACE,SAAS,YAAY,+CAA+C;AAAA,MACtE,UAAU,SAAS;AAAA,IACrB,CAAC;AAaD,QAAI,oBAAoB;AACxB,UAAM,kBAAkB,CAAC,WAAmB;AAC1C,UAAI,mBAAmB;AACrB;AAAA,MACF;AACA,0BAAoB;AACpB,oBAAc,KAAK,gDAAgD,EAAE,OAAO,CAAC;AAC7E,UAAI;AACF,qBAAc,OAAO,SAAS;AAAA,MAChC,SAAS,OAAO;AACd,sBAAc,KAAK,kCAAkC;AAAA,UACnD,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,QAC9D,CAAC;AAAA,MACH;AAAA,IACF;AACA,YAAQ,GAAG,WAAW,MAAM,gBAAgB,SAAS,CAAC;AACtD,YAAQ,GAAG,UAAU,MAAM,gBAAgB,QAAQ,CAAC;AACpD,UAAM,aAAa,OAAO,IAAI;AAAA,EAChC,UAAE;AACA,gBAAY,KAAK,IAAI;AACrB,UAAM,QAAQ,WAAW;AAAA,MACvB,cAAc,WAAW,MAAM;AAAA,MAC/B,UAAU,MAAM;AAAA,MAChB,gBAAgB,MAAM;AAAA,MACtB,0BAA0B,MAAM;AAAA,MAChC,gCAAgC,MAAM;AAAA,MACtC,KAAK,MAAM;AAAA,MACX,SAAS,MAAM;AAAA,IACjB,CAAC;AAAA,EACH;AACF;AAEA,IAAI,YAAY,MAAM;AACpB,QAAM,YAAY;AACpB;","names":["dbSearchPath","getSettings","resolveNatsControlPlaneAuth","createDb","createNatsEventBus","createObservability","ensureModalRegistryImage","createObjectStorage","getBillingBalance","getSandbox","readActiveSandbox","requireFile","getSessionEvent","getSessionGoal","getLatestRunState","isCodexBilledTurn","workspaceCodexSubscriptionActive","getWorkspaceModelPolicy","listCodexAccountStatuses","fetchCodexUsageForAccount","requireSession","recordUsageEvent","getActiveSessionHistoryItems","sumUsageQuantity","SandboxLeaseSupersededError","sanitizeHistoryItemsForModel","summarizeForCompaction","SUMMARY_BUFFER_TOKENS","deleteRecordingArtifacts","stopRecordingOnBox","configuredStaticUsageLimits","chosen","getCodexCapacityWait","reconcileCodexCapacityWait","CODEX_FALLBACK_MODEL_SLUGS","timer","mergeToolRefs","reasoningEffortForMetadata","enqueueGoalRetryWake","maybeContinueGoal","getSessionGoal","getActiveSessionHistoryItems","getSandboxSessionEnvelope","resumeEnvelope","createHash","capturedAt","stats","inserted","evaluateWorkspaceModelPolicy","createHash","randomUUID","createHash","sanitizeHistoryItemsForModel","readActiveSandbox","sleep","SandboxLeaseSupersededError","fetchCodexUsageForAccount","listCodexAccountStatuses","runAgentTurn","randomUUID","stopRecordingOnBox","workspaceCodexSubscriptionActive","requireSession","getSessionEvent","getLatestRunState","isCodexBilledTurn","deleteRecordingArtifacts","getSessionGoal","getWorkspaceModelPolicy","evaluateWorkspaceModelPolicy","CODEX_FALLBACK_MODEL_SLUGS","summarizeForCompaction","SUMMARY_BUFFER_TOKENS","getSandbox","getActiveSessionHistoryItems","recordUsageEvent","getBillingBalance","configuredStaticUsageLimits","sumUsageQuantity","startOfUtcMonth","requireFile","configuredStaticUsageLimits","getBillingBalance","recordUsageEvent","sumUsageQuantity","startOfUtcMonth","reapExpiredFileUploads","accrueWarmSeconds","getBillingBalance","readLease","sandboxWarmRateMicrosPerSecond","deletePriorPersistedSnapshot","isProviderSandboxNotFoundError","reapSandboxLeases","sandboxWarmRateMicrosPerSecond","accrueWarmSeconds","getBillingBalance","readLease","isProviderSandboxNotFoundError","deletePriorPersistedSnapshot","addSessionSystemUpdateWithSourceMutation","enqueueSessionWorkflowWakeIfRunnable","getBillingBalance","isCodexBilledTurn","recordUsageEvent","requireSession","sumUsageQuantity","appendAndPublishEvents","publishDurableSessionEvents","configuredStaticUsageLimits","isCodexBilledTurn","recordUsageEvent","enqueueSessionWorkflowWakeIfRunnable","result","appendAndPublishEvents","addSessionSystemUpdateWithSourceMutation","publishDurableSessionEvents","requireSession","getBillingBalance","configuredStaticUsageLimits","sumUsageQuantity","startOfUtcMonth","applySessionTurnSettlement","countQueuedTurns","getSessionEvent","requireSession","publishDurableSessionEvents","applySessionTurnSettlement","countQueuedTurns","getSessionEvent","requireSession","publishDurableSessionEvents","failSessionAttempt","settleSessionInterruptions","recoverDispatch","peekSessionWork","markSessionIdle","getRig","establishSandboxSessionFromEnvelope","getRig","establishSandboxSessionFromEnvelope","updated","createObjectStorage","getSettings","createObservability","ensureModalRegistryImage","dbSearchPath","createDb","resolveNatsControlPlaneAuth","createNatsEventBus"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/activities.ts","../src/activities/agent-turn.ts","../src/activities/capabilities.ts","../src/activities/codex-rotation.ts","../src/activities/codex-auth.ts","../src/activities/codex-capacity.ts","../src/activities/common.ts","../src/activities/context-compaction.ts","../src/activities/turn-attempt-fenced.ts","../src/activities/environment.ts","../src/activities/git-credential-renewal.ts","../src/activities/goals.ts","../src/activities/packs.ts","../src/activities/parent-wake.ts","../src/activities/redaction.ts","../src/activities/run-input.ts","../src/activities/streaming.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"],"sourcesContent":["import {\n dbSearchPath,\n getSettings,\n resolveNatsControlPlaneAuth,\n retryStartupDependency,\n startupRetryOptions,\n type Settings,\n} from \"@opengeni/config\";\nimport { createDb, markSessionWorkflowWakeDelivered, type Database } from \"@opengeni/db\";\nimport { createNatsEventBus } from \"@opengeni/events\";\nimport {\n createObservability,\n logStartupDependencyRetry,\n type Observability,\n} from \"@opengeni/observability\";\nimport {\n Connection,\n ScheduleAlreadyRunning,\n ScheduleOverlapPolicy,\n Client as TemporalClient,\n} from \"@temporalio/client\";\nimport { NativeConnection, Worker } from \"@temporalio/worker\";\nimport { ensureModalRegistryImage } from \"@opengeni/runtime\";\nimport {\n createControlActivities,\n createTurnActivities,\n type ActivityDependencies,\n} from \"./activities\";\nimport type { SignalCodexCapacityWorkflow, WakeSessionWorkflowSignal } from \"./activities/types\";\nimport { turnTaskQueue } from \"./workflows/activities\";\nimport { dbReadyCheck, natsReadyCheck, startWorkerHttpServer } 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 TURN_WORKER_MAX_CONCURRENT_TURNS,\n} from \"./concurrency\";\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 // Embedded hosts install @opengeni/worker-bundle under node_modules, where\n // Temporal's workflow webpack refuses to transpile TS. They relocate\n // src/workflows.ts to a host-owned path and point the worker at it here.\n // Unset (standalone) keeps today's in-package path byte-for-byte.\n workflowsPath?: string;\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 // Pre-resolve a PRIVATE-registry sandbox image before any turn creates a box.\n // No-op unless OPENGENI_MODAL_IMAGE_REGISTRY_SECRET + OPENGENI_MODAL_IMAGE_REF are\n // both set (so non-modal / public-image deployments are byte-unchanged and never\n // load the modal SDK here). Memoized in the provider, so this 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 const connection = await retryStartupDependency(\n \"Temporal\",\n () => NativeConnection.connect({ address: settings.temporalHost }),\n {\n ...startupRetryOptions(settings),\n onRetry: (event) => logStartupDependencyRetry(observability, event),\n },\n );\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 workflowsPath:\n options.workflowsPath ?? new URL(\"../src/workflows.ts\", import.meta.url).pathname,\n maxConcurrentWorkflowTaskExecutions: CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS,\n }\n : {}),\n activities,\n maxConcurrentActivityTaskExecutions:\n options.role === \"turn\"\n ? TURN_WORKER_MAX_CONCURRENT_TURNS\n : CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES,\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\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 signalCodexCapacityWorkflow: SignalCodexCapacityWorkflow;\n check: () => Promise<void>;\n close: () => Promise<void>;\n}> {\n const connection = await Connection.connect({ address: settings.temporalHost });\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 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 only bounded DB outbox repair;\n * it never reads/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({ address: settings.temporalHost });\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({ address: settings.temporalHost });\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({ address: settings.temporalHost });\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 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 controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n let bus: Awaited<ReturnType<typeof createNatsEventBus>> | undefined;\n let signaler: Awaited<ReturnType<typeof createWorkerWorkflowSignaler>> | undefined;\n let workerBundle: Awaited<ReturnType<typeof createOpenGeniWorker>> | undefined;\n let reaperSchedule: Awaited<ReturnType<typeof registerSandboxReaperSchedule>> | undefined;\n let fileUploadReaperSchedule:\n | Awaited<ReturnType<typeof registerFileUploadReaperSchedule>>\n | undefined;\n let workflowWakeDispatcherSchedule:\n | Awaited<ReturnType<typeof registerSessionWorkflowWakeDispatcherSchedule>>\n | undefined;\n let httpServer: ReturnType<typeof startWorkerHttpServer> | undefined;\n try {\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 signaler = await retryStartupDependency(\n \"Temporal client\",\n () => createWorkerWorkflowSignaler(settings, dbClient.db),\n { ...retryOptions, onRetry },\n );\n workerBundle = await createOpenGeniWorker({\n role,\n settings,\n activityDependencies: {\n observability,\n wakeSessionWorkflow: signaler.wakeSessionWorkflow,\n signalCodexCapacityWorkflow: signaler.signalCodexCapacityWorkflow,\n db: dbClient.db,\n bus,\n },\n });\n httpServer = startWorkerHttpServer({\n settings,\n observability,\n checks: {\n db: dbReadyCheck(dbClient.db),\n nats: natsReadyCheck(bus),\n temporal: signaler.check,\n },\n });\n // Control workers alone own global schedules. Turn workers poll only the\n // bounded inference activity queue and can never duplicate schedule setup.\n if (role === \"control\") {\n reaperSchedule = await retryStartupDependency(\n \"Temporal schedule (sandbox reaper)\",\n () => registerSandboxReaperSchedule(settings, observability),\n { ...retryOptions, onRetry },\n );\n fileUploadReaperSchedule = await retryStartupDependency(\n \"Temporal schedule (file upload reaper)\",\n () => registerFileUploadReaperSchedule(settings, observability),\n { ...retryOptions, onRetry },\n );\n workflowWakeDispatcherSchedule = await retryStartupDependency(\n \"Temporal schedule (session-workflow wake dispatcher)\",\n () => registerSessionWorkflowWakeDispatcherSchedule(settings, observability),\n { ...retryOptions, onRetry },\n );\n }\n observability.info(\"OpenGeni worker listening\", {\n role,\n temporalTaskQueue:\n role === \"control\" ? settings.temporalTaskQueue : turnTaskQueue(settings.temporalTaskQueue),\n maxConcurrentActivityTaskExecutions:\n role === \"turn\"\n ? TURN_WORKER_MAX_CONCURRENT_TURNS\n : CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES,\n maxConcurrentWorkflowTaskExecutions:\n role === \"control\" ? CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS : 0,\n httpPort: settings.workerHttpPort,\n });\n // GRACEFUL DEPLOY SHUTDOWN — the missing link that made every deploy a\n // worker_death. The worker is the container's MAIN process (PID 1), and a\n // PID-1 process with no explicit handler IGNORES SIGTERM: the pod sat\n // through the entire terminationGracePeriodSeconds doing nothing, then the\n // kubelet SIGKILLed it — so agent-turn's worker-shutdown checkpoint path\n // (same-turn recovery + run-state save) never once ran in production\n // (forensics 2026-07-06: every observed recovery was\n // reason=worker_death). This handler starts the drain the moment k8s asks:\n // shutdown() stops polling, then (per shutdownGraceTime/ForceTime above)\n // cancels in-flight activities with WORKER_SHUTDOWN so long turns\n // checkpoint INSIDE the grace window. run() resolves once\n // drained and the finally below closes connections cleanly.\n let shutdownRequested = false;\n const requestShutdown = (signal: string) => {\n if (shutdownRequested) {\n return;\n }\n shutdownRequested = true;\n observability.info(\"OpenGeni worker draining (graceful shutdown)\", { signal });\n try {\n workerBundle!.worker.shutdown();\n } catch (error) {\n observability.warn(\"worker shutdown request failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n process.on(\"SIGTERM\", () => requestShutdown(\"SIGTERM\"));\n process.on(\"SIGINT\", () => requestShutdown(\"SIGINT\"));\n await workerBundle.worker.run();\n } finally {\n httpServer?.stop(true);\n await Promise.allSettled([\n workerBundle?.connection.close(),\n signaler?.close(),\n reaperSchedule?.close(),\n fileUploadReaperSchedule?.close(),\n workflowWakeDispatcherSchedule?.close(),\n bus?.close(),\n dbClient.close(),\n ]);\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 IndexDocumentInput,\n MaybeContinueGoalInput,\n MaybeContinueGoalResult,\n CodexCapacityWaitRef,\n GetCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitResult,\n RecoverDispatchInput,\n RecoverDispatchResult,\n RunAgentTurnInput,\n RunAgentTurnResult,\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 (SPIKE-1 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 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 P4a — 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 recoverDispatch = defaultControlActivities.recoverDispatch;\nexport const peekSessionWork = defaultControlActivities.peekSessionWork;\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 applySessionTurnSettlement,\n requestSessionTurnRecovery,\n claimSessionWorkForAttempt,\n applyCreditDebitUpToBalance,\n getBillingBalance,\n getRigName,\n getRigVersion,\n getSandbox,\n readActiveSandbox,\n setActiveSandbox,\n requireFile,\n getSessionEvent,\n getSessionGoal,\n getLatestRunState,\n isCodexBilledTurn,\n workspaceCodexSubscriptionActive,\n acquireCodexCredentialLease,\n armCodexCapacityWait,\n heartbeatCodexCredentialLeaseUntil,\n releaseCodexCredentialLease,\n CODEX_CREDENTIAL_LEASE_TTL_MS,\n getCodexRotationSettings,\n getWorkspaceModelPolicy,\n listCodexAccountStatuses,\n fetchCodexUsageForAccount,\n getSessionCodexState,\n recordSessionActiveCodexCredential,\n setSessionCodexPin,\n recordCodexAccountUsageWithWakeTargets,\n recordCodexAccountConnectors,\n quarantineCodexCredentialForLease,\n setActiveCodexCredential,\n resolveWorkspaceMemoryBlock,\n setCodexCredentialExhaustedWithWakeTargets,\n withCodexCapacityMutation,\n countConsecutiveReactiveRotations,\n requireSession,\n recordUsageEvent,\n registerPendingSessionToolCall,\n recordPendingSessionToolCallResult,\n clearDurablePendingSessionToolCalls,\n appendSessionHistoryItems,\n isSessionCompactionRequested,\n countSessionHistoryItems,\n getActiveSessionHistoryItems,\n nextSessionHistoryPosition,\n settleCodexCredentialLeaseLoss,\n settleCodexCredentialFailover,\n saveRunState,\n upsertSandboxSessionEnvelope,\n setSessionLastInputTokensForTurnAttempt,\n sumUsageQuantity,\n heartbeatLeaseHolder,\n accrueWarmSeconds,\n getMaterializedSandboxFileResources,\n markSandboxFileResourcesMaterialized,\n SandboxLeaseSupersededError,\n SandboxImageConflictError,\n buildConnectionTokenResolver,\n getEnrollment,\n abandonRecordingForTurnAttempt,\n type AppendEventInput,\n type ActiveSandboxPointer,\n type SandboxRecord,\n type CodexCredentialLeaseResult,\n type CodexCredentialLeaseSelectionContext,\n type SessionTurnRecordingSettlement,\n} from \"@opengeni/db\";\nimport { appendAndPublishTurnEventsFenced, publishDurableSessionEvents } from \"@opengeni/events\";\nimport {\n sandboxStateEntryFromRunState,\n maxTurnsExceededRunState,\n modelCallUsageTelemetry,\n modelResponseUsageFromSdkEvent,\n normalizeSdkEvent,\n sanitizeHistoryItemsForModel,\n isEphemeralInternalContext,\n appendPersistentSessionSettings,\n appendSessionInstructions,\n appendWorkspaceMemory,\n composeAgentInstructions,\n summarizeForCompaction,\n ensureModalRegistryImage,\n findCompactionNeededError,\n materializeSandboxFileDownloads,\n refreshGitProviderTokenFiles,\n sandboxFileDownloadFailureNote,\n SUMMARY_BUFFER_TOKENS,\n runOwnedSandboxSetup,\n swapTargetEstablishability,\n type SandboxFileDownload,\n type SandboxFileDownloadFailure,\n type OpenGeniRuntime,\n type ComputerToolMode,\n type ModelResponseUsage,\n type BuildAgentOptions,\n type BackendUnresolvableCode,\n type EstablishedSandboxSession,\n type GitCredentialTokenWriterSession,\n deleteRecordingArtifacts,\n stopRecording as stopRecordingOnBox,\n} from \"@opengeni/runtime\";\nimport {\n builtinProviderId,\n calculateModelUsageCostMicros,\n configuredModelPricing,\n configuredStaticUsageLimits,\n sandboxWarmRateMicrosPerSecond,\n settingsWithResolvedModelContext,\n type ModelUsageInput,\n type ModelProviderApi,\n type RegistryProviderKind,\n type Settings,\n} from \"@opengeni/config\";\nimport { CancelledFailure } from \"@temporalio/activity\";\nimport {\n settingsWithCodexCredential,\n settingsWithEnabledCapabilityMcpServers,\n settingsWithSessionMcpServersForRun,\n} from \"./capabilities\";\nimport {\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 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 CodexReloginRequired,\n classifyCodexUsageLimitError,\n codexRequestStorage,\n isCodexTransportError,\n type CodexRequestContext,\n type CodexUsageHeaderSnapshot,\n} from \"@opengeni/codex\";\nimport { mergeResourceRefs, mergeToolRefs } from \"./common\";\nimport { maybeCompactContext } from \"./context-compaction\";\nimport { TurnAttemptFencedError } from \"./turn-attempt-fenced\";\nimport {\n loadWorkspaceEnvironmentForRunWithCredentials,\n mintRunGitCredentials,\n sandboxEnvironmentForRun,\n type MintedRunGitCredentials,\n} from \"./environment\";\nimport {\n startGitCredentialRenewalLoop,\n type GitCredentialRenewalController,\n} from \"./git-credential-renewal\";\nimport { withCodexAppsTool, withFirstPartyTools } from \"./goals\";\nimport {\n mergeRigDefaultVariableSetEnvironment,\n resolveWorkspaceAgentInstructions,\n resolveWorkspacePackRuntime,\n settingsWithPackSandboxImage,\n settingsWithRigImage,\n} from \"./packs\";\nimport { notifyParentOfChildTerminal } from \"./parent-wake\";\nimport { createSecretRedactor, identityRedactor } from \"./redaction\";\nimport { applyCodexHistoryStrip, turnInput, type TurnCodexAccount } from \"./run-input\";\nimport {\n createRuntimeBatcher,\n currentActivityContext,\n nextStreamEvent,\n startActivityHeartbeat,\n} from \"./streaming\";\nimport type { ActivityServices, RunAgentTurnInput, RunAgentTurnResult } from \"./types\";\nimport {\n resumeBoxForTurn,\n acquireSelfhostedLeaseForTurn,\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 } 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 evaluateWorkspaceModelPolicy,\n type GitCredentialProvider,\n type ResourceRef,\n type SessionEvent,\n type SessionEventType,\n type SessionStatus,\n} from \"@opengeni/contracts\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\n// How long the session workflow holds the loop after a retryable provider\n// failure before the goal continuation re-enters the model. Azure/OpenAI TPM\n// throttling is minute-granular; anything shorter mostly burns continuation\n// budget against the same window.\nexport const PROVIDER_BACKPRESSURE_DELAY_MS = 60_000;\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(): {\n status: \"recovering\";\n continueDelayMs: number;\n} {\n return {\n status: \"recovering\",\n continueDelayMs: PROVIDER_BACKPRESSURE_DELAY_MS,\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 const { sessionPinnedCredentialId: pin, activeCredentialId: active, connectedIds } = args;\n if (pin && connectedIds.has(pin)) {\n return pin;\n }\n if (active && connectedIds.has(active)) {\n return active;\n }\n return null;\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/**\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\nfunction compactionFailureReason(reason: string): string {\n return reason.startsWith(\"compaction summarization failed:\")\n ? reason\n : `compaction summarization failed: ${reason}`;\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 `-32001 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 matched = 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 if (!matched) {\n return null;\n }\n const message = error instanceof Error ? error.message : String(error);\n return {\n message,\n ...(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\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 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 // 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<void> {\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;\n }\n if (input.emittedSourceKeys?.has(input.sourceKey)) return;\n const telemetry = modelCallUsageTelemetry(usage as Parameters<typeof modelCallUsageTelemetry>[0]);\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;\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 reasoningTokens: telemetry.reasoningTokens,\n ...(input.servingAccountHash !== undefined\n ? { servingAccountHash: input.servingAccountHash }\n : {}),\n ...(input.accountChangedFromPrevCall !== undefined\n ? { accountChangedFromPrevCall: input.accountChangedFromPrevCall }\n : {}),\n });\n } catch {\n // Durable event + billing already committed; logging is best-effort only.\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): {\n rows: Array<{ position: number; item: Record<string, unknown> }>;\n nextWatermark: number;\n nextPosition: number;\n} {\n const sanitized = sanitizeHistoryItemsForModel(rawHistory).filter(\n (item) => !isEphemeralInternalContext(item),\n );\n if (sanitized.length <= persistedHistoryCount) {\n return { rows: [], nextWatermark: persistedHistoryCount, nextPosition };\n }\n const rows = sanitized.slice(persistedHistoryCount).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\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 * Seed the turn-end reconcile watermark (`persistedHistoryCount`) from EXACTLY the\n * view `state.history` was seeded from, so the model-input length and the watermark\n * can NEVER disagree. The watermark is the slice index the reconcile cuts the\n * (re-sanitized) `state.history` at to find this turn's genuinely-new items, so it\n * must equal the length of `state.history`'s already-persisted leading prefix.\n *\n * The cross-account reasoning strip drops foreign reasoning items, so the prefix\n * length is PATH-DEPENDENT, captured by `modelHistoryFromItems`:\n *\n * - items read path (`modelHistoryFromItems === true`) — `state.history` was seeded\n * from the cross-account-STRIPPED active items (foreign reasoning DROPPED), so it\n * starts K shorter than the raw active-row count. Seed from the SAME strip\n * (HOLE D); seeding from the un-stripped count would slice K genuinely-new items\n * off the reconcile and silently lose them (incl. the user's switch-turn message).\n *\n * - approval RunState path (`modelHistoryFromItems === false`) — `state.history` was seeded\n * from the blob, where foreign reasoning is NEUTRALIZED-IN-PLACE (the item is\n * KEPT, only its id/encrypted_content go — see resumeRunStateForCodexAccount), so\n * the blob's history length still COUNTS those items. Applying the strip here\n * under-counts by K and the reconcile re-appends K already-persisted items at\n * fresh positions — HOLE E. So the blob path must NOT strip: count the raw\n * sanitized active length, which mirrors the blob's completed prefix.\n *\n * On a same-account / non-codex turn the strip is a no-op, so both branches reduce\n * to the same raw sanitized count (byte-identical to the pre-strip behaviour).\n * Pure; exported for unit testing the D/E seed invariant.\n */\nexport function reconcileSeedCount(\n activeSeedRows: ReadonlyArray<{\n item: Record<string, unknown>;\n producerCodexCredentialId: string | null;\n }>,\n modelHistoryFromItems: boolean,\n current: TurnCodexAccount,\n): number {\n return sanitizeHistoryItemsForModel(\n modelHistoryFromItems\n ? applyCodexHistoryStrip(activeSeedRows, current)\n : activeSeedRows.map((row) => row.item),\n ).length;\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 error,\n );\n return undefined;\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. Packs can override `modalImageRef` per workspace/turn, so a\n * private pack image must be resolved before sandbox creation or Modal falls\n * back to the unauthenticated `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.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 → \"function-text\": it takes\n * function tools but can't read structured image results, so screenshots render\n * as a text data-URL.\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 } | null,\n): ComputerToolMode {\n if (!resolvedModel) {\n return \"hosted\"; // legacy built-in Responses client — real hosted support\n }\n if (resolvedModel.provider.kind === \"codex-subscription\") {\n return \"function-image\";\n }\n if (resolvedModel.provider.api === \"chat\") {\n return \"function-text\";\n }\n return \"hosted\";\n}\n\nexport type TurnSandboxProvisioner<T> = {\n get(): Promise<T>;\n hasStarted(): boolean;\n waitForSettled(timeoutMs: number): Promise<T | null>;\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 (error instanceof SandboxImageConflictError) {\n return false;\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\nexport function createTurnSandboxProvisioner<T>(\n establish: () => Promise<T>,\n options: {\n maxRetries?: number;\n backoffMs?: number;\n onStarted?: () => Promise<void> | void;\n onCompleted?: () => Promise<void> | void;\n onFailed?: (error: unknown) => 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 return await establish();\n } catch (error) {\n if (attempt >= maxRetries || !isLazySandboxProvisionRetryable(error)) {\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 await options.onStarted?.();\n try {\n const result = await run();\n await options.onCompleted?.();\n return result;\n } catch (error) {\n await options.onFailed?.(error);\n throw error;\n }\n })().catch((error) => {\n memo = null;\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\nfunction sdkBackendIdForSandboxBackend(backend: Settings[\"sandboxBackend\"]): string {\n return backend === \"local\" ? \"unix_local\" : backend;\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 over-threshold (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: CodexAccountStatus[],\n capacitySignals: {\n signalCodexCapacityWorkflow?: ActivityServices[\"signalCodexCapacityWorkflow\"] | undefined;\n wakeSessionWorkflow: ActivityServices[\"wakeSessionWorkflow\"];\n },\n): Promise<CodexAccountStatus[]> {\n const nearPct = settings.codexRotationNearExhaustionPct;\n const stale = accounts.filter(\n (a) =>\n a.status === \"active\" &&\n ((a.primaryUsedPercent ?? 0) >= nearPct || (a.secondaryUsedPercent ?? 0) >= nearPct),\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 signalCodexCapacityWorkflow,\n entitlements,\n connectionCredentials,\n } = await services();\n const activityContext = currentActivityContext();\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 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 let isCodexTurn = false;\n let executionGeneration = 0;\n // Still required by credential-loss/capacity settlements, whose own\n // recovery transactions fence against worker-death redispatches.\n let redispatchesAtDispatch = 0;\n const saveRunStateFenced = async (state: Parameters<typeof saveRunState>[1]): Promise<void> => {\n if (!(await saveRunState(db, state))) {\n throw new TurnAttemptFencedError(\n \"turn execution generation was fenced while saving run state\",\n );\n }\n };\n const setLastInputTokensFenced = async (lastInputTokens: number): 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 // OPE-21: 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 // 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 // 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 // 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 // OPE-41: 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 gitCredentialRenewal: GitCredentialRenewalController | null = null;\n let gitCredentialRenewalClosed = 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 // 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 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 }) => Promise<boolean>)\n | null = null;\n let turnStartedPublished = false;\n let stream: Awaited<ReturnType<OpenGeniRuntime[\"runStream\"]>> | undefined;\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\", 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 }).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 if (snapshotSession && !snapshotInFlight) {\n snapshotInFlight = maybePersistWarmWorkspaceSnapshot(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: heartbeatGroupId,\n },\n snapshotSession,\n heartbeatEpoch,\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 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 // 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 );\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 // Tag each row with the codex account that produced it (null on the\n // non-codex path). Resolved at line ~504 before any reconcile pass\n // runs, so this is the turn's effective account. The read path uses\n // it to strip cross-account reasoning.encrypted_content next turn.\n producerCodexCredentialId: effectiveCodexCredentialId,\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(\"session history dual-write failed (run unaffected)\", persistError);\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 let redact: (payload: unknown) => unknown = identityRedactor;\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 // Multi-account P4 (Part A): 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 // 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 (P2-b) and thread it through both the\n // routing overlay (settingsWithCodexCredential) and the billed-turn predicate\n // (isCodexBilledTurn below), so a concurrent disconnect/reconnect cannot make\n // provider-injection and billing disagree about whether this is a codex turn.\n const codexSubscriptionActive = await workspaceCodexSubscriptionActive(\n db,\n mcpSettings,\n input.workspaceId,\n );\n const capabilitySettings = await settingsWithCodexCredential(\n db,\n input.workspaceId,\n mcpSettings,\n codexSubscriptionActive,\n );\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 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 triggerType = trigger.type;\n executionGeneration = turn.executionGeneration;\n const latestTurnState = await getLatestRunState(db, input.workspaceId, input.sessionId);\n const continuationCodexCredentialId =\n latestTurnState?.turnId === turnId ? latestTurnState.frozenCodexCredentialId : null;\n redispatchesAtDispatch = Number(\n (turn.metadata as { workerDeathRedispatches?: number } | null)?.workerDeathRedispatches ??\n 0,\n );\n turnLifecycleMetricsFor(observability).start(turnId);\n // Canonical codex-billed predicate (codex/<slug> + feature enabled + active\n // workspace credential). Computed once and threaded through every billing\n // gate + the usage recorder so a turn paid by the user's ChatGPT/Codex plan\n // consumes ZERO OpenGeni credits and never feeds an OpenGeni cap. Resolved\n // here (before resolvedModel at the routing step) because the pre-turn gate\n // below needs it; mirrors the same active-credential read the codex provider\n // overlay uses, so billing and routing agree on what \"codex\" is.\n isCodexTurn = await isCodexBilledTurn({\n db,\n settings,\n workspaceId: input.workspaceId,\n model: turn.model,\n active: codexSubscriptionActive,\n });\n // §7.5 P3 — pass BOTH the codex predicate (codex-plan turns bypass the gate)\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 ensureRunAllowed(\n settings,\n db,\n input.accountId,\n input.workspaceId,\n isCodexTurn,\n entitlements,\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 // 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 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 Bun.sleep(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 inputs = inputSettlement.events.map((event) => ({\n ...event,\n payload: redact(event.payload),\n turnId: turnId!,\n producerId,\n producerSeq: ++producerSeq,\n }));\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 ...(recordingMutation ? { recording: recordingMutation } : {}),\n });\n if (result.action === \"stale\") {\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 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 continuationCredentialId: continuationCodexCredentialId,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\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 continuationCredentialId: continuationCodexCredentialId,\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 continuationCredentialId: continuationCodexCredentialId,\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 // OPE-31 pin persistence follows the atomic OPE-21 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 eligibleCount = leased.accounts.filter((account) =>\n isCodexCredentialEligible(account, settings.codexRotationNearExhaustionPct, 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 if (goal?.status === \"active\") {\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: goal.id,\n goalVersion: goal.version,\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 = \"failed\";\n activityStatus = \"idle\";\n return claimedResult({\n status: \"idle\",\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 {\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 if (goalActive && goal) {\n const authoritativeResetAt = authoritativeCodexCapacityResetAt(\n leased.accounts,\n settings.codexRotationNearExhaustionPct,\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: goal.id,\n goalVersion: goal.version,\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 = \"failed\";\n activityStatus = \"idle\";\n return claimedResult({\n status: \"idle\",\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` (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 // P4: surface the dropped-connector note when this rotation pick couldn't\n // cover the session's used connectors (a Tier-2/unknown failover); the pill\n // renders the badge. Omitted when the switch covered everything (the norm).\n const droppedConnectors =\n rotationDecision.kind === \"active\" ? rotationDecision.droppedConnectors : undefined;\n await publish([\n {\n type: \"codex.account.switched\",\n payload: {\n fromAccountId: priorAccountId,\n toAccountId: effectiveCodexCredentialId,\n reason: rotated ? \"rotation\" : \"manual\",\n ...(droppedConnectors && droppedConnectors.length > 0\n ? { droppedConnectors }\n : {}),\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 = await resolveWorkspacePackRuntime(db, input.workspaceId);\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 workspaceAgentInstructions = await resolveWorkspaceAgentInstructions(\n db,\n input.workspaceId,\n );\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(capabilitySettings, packRuntime.sandboxImage),\n rigVersion?.image ?? null,\n ),\n openaiModel: turn.model,\n openaiReasoningEffort: turn.reasoningEffort,\n sandboxBackend: turn.sandboxBackend,\n };\n const runSettings = await settingsWithSessionMcpServersForRun(\n db,\n input.workspaceId,\n input.sessionId,\n baseRunSettings,\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(capabilitySettings, turn.model);\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 const 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 (null → the built-in\n // OpenAI/Azure client, attributed here via builtinProviderId so a policy\n // blocking the built-in also blocks that fallback — this exact path is\n // how bare-model turns silently spent real Azure money in a\n // codex-intended workspace). Fail-loud, never a silent remap.\n {\n const workspaceModelPolicy = await getWorkspaceModelPolicy(db, input.workspaceId);\n if (workspaceModelPolicy) {\n const effectiveProviderId = resolvedModel\n ? resolvedModel.provider.id\n : builtinProviderId(capabilitySettings);\n const verdict = evaluateWorkspaceModelPolicy(workspaceModelPolicy, {\n providerId: effectiveProviderId,\n modelId: turn.model,\n });\n if (!verdict.allowed) {\n throw new WorkspaceModelPolicyBlockedError(\n turn.model,\n effectiveProviderId,\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 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 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: resolver.getToken,\n refresh: 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 };\n })()\n : null;\n const withCodex = <T>(fn: () => Promise<T>): Promise<T> =>\n codexContext ? codexRequestStorage.run(codexContext, fn) : fn();\n const promptCacheKey = acceptsPromptCacheKeyForTurn(resolvedModel)\n ? input.sessionId\n : undefined;\n let compactionUsageCount = 0;\n const recordCompactionUsage = async (usage: ModelResponseUsage) => {\n await recordCompletedModelCallBeforeOwnershipFences({\n renewLease: () => renewCodexLease(\"model_usage\"),\n leaseLost: () => codexLeaseLost,\n leaseLostMessage: \"Codex credential lease expired during context compaction\",\n recordUsage: async () => {\n compactionUsageCount += 1;\n const sourceKey = modelUsageSourceKey({\n responseId: usage.responseId,\n dispatchId: modelUsageDispatchId,\n positionalKey: `compaction-${compactionUsageCount}`,\n });\n const responseAccountCtx = modelCallAccountContext({\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n isFirstCallOfTurn: compactionUsageCount === 1,\n });\n await recordModelUsageAndDebitCredits(settings, db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n model: resolvedModel?.configured.id ?? turn.model,\n isCodexTurn,\n usage: usage.usage,\n sourceKey,\n observability,\n });\n await emitModelCallUsage({\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 sourceKey,\n usage,\n servingAccountHash: responseAccountCtx.servingAccountHash,\n accountChangedFromPrevCall: responseAccountCtx.accountChangedFromPrevCall,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n });\n },\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: resolvedModel.configured.id,\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 maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n onUsage: recordCompactionUsage,\n ...(systemInstructions ? { systemInstructions } : {}),\n ...(promptCacheKey ? { promptCacheKey } : {}),\n });\n\n if (turn.source === \"compaction\") {\n const persistentSessionSettings = {\n titleIsSet: Boolean(session.title?.trim()),\n };\n const compactionInstructions = appendPersistentSessionSettings(\n appendSessionInstructions(\n appendWorkspaceMemory(\n composeAgentInstructions(\n workspaceAgentInstructions ?? modelRunSettings.agentInstructionsTemplate,\n undefined,\n rigVersion && rigName ? { name: rigName, version: rigVersion.version } : undefined,\n ),\n workspaceMemory ?? undefined,\n ),\n session.instructions ?? undefined,\n ),\n persistentSessionSettings,\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 outcome = await 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 },\n );\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, \"operator\");\n }\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n outcome.events,\n );\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) — so set_session_title and the rest are\n // always reachable. Idempotent: mergeToolRefs dedupes if already present.\n // Attach codex_apps (the ChatGPT/Codex connectors MCP) when the codex\n // overlay injected it into runSettings.mcpServers (active subscription +\n // connector scopes); no-op for every other turn. Its refreshing bearer is\n // resolved at connect time from the codex ALS (see the withCodex-wrapped\n // prepareTools call below).\n const turnTools = withCodexAppsTool(\n runSettings,\n withFirstPartyTools(runSettings, mergeToolRefs(session.tools, turn.tools)),\n );\n // §7.6 P4a — 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 loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n session.variableSetId,\n connectionCredentials?.sandboxSecrets,\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 loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n rigDefaultVariableSetId,\n connectionCredentials?.sandboxSecrets,\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 redact = createSecretRedactor(\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 await ensureTurnModalRegistryImage(runSettings, sandboxCreationBackend);\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 const {\n environment: sandboxEnvironment,\n gitToken: sandboxGitToken,\n gitTokens: sandboxGitTokens,\n gitTokenExpiresAt: sandboxGitTokenExpiresAt,\n toolspaceToken: sandboxToolspaceToken,\n } = await 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 gitCredentials: connectionCredentials?.gitCredentials,\n sessionId: input.sessionId,\n runId: turnId,\n },\n );\n\n const initialGitCredentials: MintedRunGitCredentials | undefined = sandboxGitTokens\n ? {\n gitTokens: sandboxGitTokens,\n expiresAt: sandboxGitTokenExpiresAt ?? {},\n }\n : undefined;\n const attachGitCredentialRenewal = async (\n tokenSession: GitCredentialTokenWriterSession,\n initial: MintedRunGitCredentials | undefined,\n ): Promise<void> => {\n if (!initial || Object.keys(initial.gitTokens).length === 0) return;\n const previous = gitCredentialRenewal;\n gitCredentialRenewal = null;\n await previous?.stop();\n if (gitCredentialRenewalClosed) return;\n\n const providers = Object.keys(initial.gitTokens) as GitCredentialProvider[];\n const controller = startGitCredentialRenewalLoop({\n expectedProviders: providers,\n initialExpiresAt: initial.expiresAt,\n mint: async () =>\n await mintRunGitCredentials(runSettings, turnResources, {\n scope: connectionScope,\n gitCredentials: connectionCredentials?.gitCredentials,\n }),\n write: async (tokens) => {\n const runAs = sandboxRunAs(runSettings);\n await refreshGitProviderTokenFiles(tokenSession, tokens, {\n ...(runAs ? { runAs } : {}),\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 if (gitCredentialRenewalClosed) {\n await controller.stop();\n return;\n }\n gitCredentialRenewal = 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 sandboxHolderId = sandboxLeaseHolderIdForAttempt(input.attemptId);\n sandboxGroupId = session.sandboxGroupId;\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 a phantom Modal home box (today's path leased + BILLED\n // a cloud box the turn never touched). Build the SelfhostedSession DIRECTLY\n // (no Modal box created) and take the group lease with backend \"selfhosted\"\n // (refcount/idle bookkeeping; the reaper drains it cold with NO provider\n // stop, and bills ZERO warm-seconds). The session is a harmless in-memory\n // bind (no NATS round-trip), so build it FIRST; if the lease then fences,\n // there is nothing to clean up.\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 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 const lease = await acquireSelfhostedLeaseForTurn(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n sessionId: input.sessionId,\n },\n \"turn\",\n sandboxHolderId,\n );\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 },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\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 leaseEpoch: lease.leaseEpoch,\n release: lease.release,\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 resumeBoxForTurn(\n {\n db,\n settings,\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 → recreate on the new image; N-holders →\n // SandboxImageConflictError surfaced as an actionable turn error). Prefer the\n // explicit Modal image ref, else the docker image. The selfhosted branch\n // (establishSelfhostedTurnSession/acquireSelfhostedLeaseForTurn) 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 // recreate / N-holders SandboxRigConflictError). Omitted for a rig-less\n // turn -> never stamped or enforced (shares exactly as today).\n ...(rigVersion ? { rigVersionId: rigVersion.id } : {}),\n },\n \"turn\",\n sandboxHolderId,\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 if (routingEnabled(settings)) {\n resolvedSandbox = {\n ...resolvedSandbox,\n established: wrapTurnBoxWithRouting(\n { db, settings, bus },\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 },\n resolvedSandbox.established,\n ),\n };\n }\n }\n if (resolvedSandbox) {\n startLeaseHeartbeat(resolvedSandbox, activeSandboxBackend ?? groupBoxBackend);\n }\n }\n\n const fileResourceDownloads = await sandboxFileDownloadsForRun(\n runSettings,\n db,\n objectStorage,\n input.workspaceId,\n turnResources,\n );\n throwIfWorkerShuttingDown();\n // Wrap MCP prep in the codex ALS so the codex_apps connect handshake\n // (initialize + tools/list) can resolve the per-workspace bearer from\n // codexRequestStorage (runtime/codexAppsMcpRequestInit). withCodex is the\n // identity on every non-codex turn, so this is a no-op for existing paths.\n const resolveCredential = buildConnectionTokenResolver(db, runSettings);\n preparedTools = await withCodex(() =>\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 resolveCredential,\n onAuthNeeded: async (payload) => {\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 }),\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 agent = runtime.buildAgent(modelRunSettings, turnResources, {\n reasoningEffort: turn.reasoningEffort,\n genesisTitleHint: isGenesisTurn,\n persistentSessionSettings: {\n titleIsSet: Boolean(session.title?.trim()),\n },\n sandboxEnvironment,\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\" && !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, turn TTL,\n // budgeted, approval-tools excluded). The runtime seeds it to the box's\n // token file over the same exec channel, off-manifest, on every backend.\n ...(sandboxToolspaceToken ? { toolspaceTokenSeed: sandboxToolspaceToken } : {}),\n ...(activeSandboxBackend ? { activeSandboxBackend } : {}),\n fileResourceDownloads,\n mcpServers: preparedTools.mcpServers,\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 // only when the model opts in; the effective context window drives the\n // compaction threshold.\n ...(resolvedModel\n ? {\n hostedWebSearch: resolvedModel.configured.hostedWebSearch,\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: resolvedModel.provider.kind !== \"codex-subscription\",\n // EXPLICIT computer-use tool transport, derived from the resolved provider's\n // authoritative wire identity (codex → function-image, chat → function-text,\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 ...(workspaceAgentInstructions ? { instructionsTemplate: workspaceAgentInstructions } : {}),\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 ...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 (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 let lazyEstablishmentOrigin: EstablishedSandboxSession[\"origin\"] | null = null;\n turnSandboxProvisioner = createTurnSandboxProvisioner<ResumedTurnSandbox>(\n async () => {\n throwIfWorkerShuttingDown();\n const lazyGitCredentials =\n activeSandboxBackend === \"selfhosted\"\n ? undefined\n : await mintRunGitCredentials(runSettings, turnResources, {\n scope: connectionScope,\n gitCredentials: connectionCredentials?.gitCredentials,\n });\n const lazyGitTokens = lazyGitCredentials?.gitTokens;\n const provisioned = await resumeBoxForTurn(\n {\n db,\n settings,\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 lazyEstablishmentOrigin = provisioned.established.origin ?? null;\n setupBoxSession = provisioned.established.session;\n await publishSandboxLifecycleEvents(provisioned);\n await runOwnedSandboxSetup(\n agent,\n provisioned.established.session as never,\n provisioned.established.session 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 },\n );\n await attachGitCredentialRenewal(\n provisioned.established.session as GitCredentialTokenWriterSession,\n lazyGitCredentials,\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 resolvedSandbox = provisioned;\n startLeaseHeartbeat(provisioned, activeSandboxBackend ?? groupBoxBackend);\n return provisioned;\n },\n {\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 () => {\n await publish?.(\n [\n {\n type: \"sandbox.operation.completed\",\n payload: {\n name: \"sandbox.provision\",\n ...(lazyEstablishmentOrigin ? { origin: lazyEstablishmentOrigin } : {}),\n },\n },\n ],\n true,\n );\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 },\n );\n lazyOwnedSandbox = wrapLazyTurnBoxWithRouting(\n {\n db,\n settings,\n bus,\n onOp: machineOpObserver.observer,\n },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\n },\n {\n client: lazyClient,\n backendId: sdkBackendIdForSandboxBackend(groupBoxBackend),\n agentDefaultManifest,\n provisioner: turnSandboxProvisioner,\n },\n );\n }\n const compactSummarizer = compactionSummarizerFor(\n typeof agent.instructions === \"string\" ? agent.instructions : undefined,\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 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 const forced = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);\n const outcome = await 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 }\n : { trigger: \"auto\" },\n );\n if (outcome.compacted) {\n const compactionTrigger = forced ? \"operator\" : undefined;\n recordContextCompaction(observability, compactionTrigger ?? \"auto\");\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n outcome.events,\n );\n }\n } catch (compactError) {\n observability.error(\"context compaction failed\", {\n sessionId: input.sessionId,\n turnId,\n error: compactError instanceof Error ? compactError.message : String(compactError),\n });\n throw compactError;\n }\n }\n let fileMaterializationFailures: SandboxFileDownloadFailure[] = [];\n let fileDownloadsMaterializedForRun = false;\n if (\n resolvedSandbox &&\n setupBoxSession &&\n activeSandboxBackend !== \"selfhosted\" &&\n fileResourceDownloads.length > 0\n ) {\n const boxInstanceId = resolvedSandbox.established.instanceId;\n const alreadyMaterialized = await getMaterializedSandboxFileResources(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n expectedEpoch: resolvedSandbox.leaseEpoch,\n instanceId: boxInstanceId,\n });\n const downloadsToMaterialize = filterUnmaterializedSandboxFileDownloads(\n fileResourceDownloads,\n alreadyMaterialized,\n );\n const runAs = sandboxRunAs(runSettings);\n if (downloadsToMaterialize.length > 0) {\n const materialized = 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 },\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 (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 // Cross-account reasoning strip: pass THIS turn's codex account so every\n // history read path (items + run-state replay) drops reasoning produced by\n // a DIFFERENT codex account. effectiveCodexCredentialId is the resolved\n // codex credential on a codex turn (pin > workspace-active) and null on a\n // non-codex turn OR a codex turn with no usable account — exactly the\n // \"current account\" the single strip rule compares against (null is the\n // built-in/Azure account, so a non-codex turn still drops codex-produced\n // reasoning, and a no-codex-history session is a byte-for-byte no-op).\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(\n db,\n runtime,\n agent,\n trigger,\n { currentCodexCredentialId: effectiveCodexCredentialId },\n {\n turnId: activeTurnId,\n recovering: turn.executionGeneration > 1,\n ...(unavailableSandboxFilesNote ? { unavailableSandboxFilesNote } : {}),\n },\n );\n runInput = prepared.input;\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 const activeSeedRows = await getActiveSessionHistoryItems(\n db,\n input.workspaceId,\n input.sessionId,\n );\n // Seed the reconcile watermark from EXACTLY the view the model's\n // `state.history` was seeded from (items strip on the items path = HOLE D; NO\n // strip on the run-state blob path, where foreign reasoning is neutralized but\n // KEPT = HOLE E), so the model-input length and the watermark never disagree.\n persistedHistoryCount = reconcileSeedCount(activeSeedRows, prepared.modelHistoryFromItems, {\n currentCodexCredentialId: effectiveCodexCredentialId,\n });\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 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 signal; provider overflows do not,\n // so null derives decision metadata from active history. Forced\n // recovery proves progress separately by comparing the replacement\n // with the current active-history estimate in maybeCompactContext.\n recoverySignalTokens,\n compactSummarizer,\n {\n force: true,\n ...(triggerLabel === \"operator\" ? { clearRequestedCompaction: true } : {}),\n trigger: triggerLabel,\n },\n );\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, triggerLabel);\n }\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n outcome.events,\n );\n }\n return outcome;\n };\n\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 let responseUsageCount = 0;\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 let lastInputTokensObserved: number | null = null;\n throwIfWorkerShuttingDown();\n const ownedEstablished = resolvedSandbox?.established ?? lazyOwnedSandbox;\n const runStreamOnce = (): ReturnType<OpenGeniRuntime[\"runStream\"]> =>\n runtime.runStream(agent, runInput!, modelRunSettings, {\n ...(activityContext ? { signal: activityContext.cancellationSignal } : {}),\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 ...(lazyOwnedSandbox ? { deferredSetup: true } : {}),\n },\n }\n : {}),\n ...(initialGitCredentials\n ? {\n onGitCredentialSessionReady: async (\n tokenSession: GitCredentialTokenWriterSession,\n ) => {\n await attachGitCredentialRenewal(tokenSession, initialGitCredentials);\n },\n }\n : {}),\n contextCompactionSignalTokens: () => lastInputTokensObserved,\n contextCompactionRequested: () =>\n isSessionCompactionRequested(db, input.workspaceId, input.sessionId),\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 const responseUsage = modelResponseUsageFromSdkEvent(next.value);\n if (responseUsage) {\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 responseUsageCount += 1;\n const responseSourceKey = modelUsageSourceKey({\n responseId: responseUsage.responseId,\n dispatchId: modelUsageDispatchId,\n positionalKey: `response-${responseUsageCount}`,\n });\n // Within a turn the serving credential is fixed, so a switch can only\n // surface on the turn's FIRST model call (vs the session's prior).\n const responseAccountCtx = modelCallAccountContext({\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n isFirstCallOfTurn: responseUsageCount === 1,\n });\n await recordModelUsageAndDebitCredits(settings, db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n model: turn.model,\n isCodexTurn,\n usage: responseUsage.usage,\n sourceKey: responseSourceKey,\n observability,\n });\n await emitModelCallUsage({\n observability,\n publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n provider: resolvedModel?.provider.id ?? settings.openaiProvider,\n providerApi: resolvedModel?.provider.api ?? \"responses\",\n model: turn.model,\n sourceKey: responseSourceKey,\n usage: responseUsage,\n servingAccountHash: responseAccountCtx.servingAccountHash,\n accountChangedFromPrevCall: responseAccountCtx.accountChangedFromPrevCall,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n });\n const observed = responseUsage.usage?.inputTokens;\n if (typeof observed === \"number\" && observed > 0) {\n recordModelInputTokens(observability, streamProvider, observed);\n lastInputTokensObserved = observed;\n }\n // Prompt-cache efficiency for this response — same usage frame as the\n // input-token accounting above, so the two are always consistent.\n recordModelCacheTokens(observability, streamProvider, {\n cachedTokens: modelCallUsageTelemetry(responseUsage.usage).cachedTokens,\n promptTokens: responseUsage.usage?.inputTokens,\n });\n },\n recordAttemptSignals: async () => {\n const observed = responseUsage.usage?.inputTokens;\n if (typeof observed === \"number\" && observed > 0) {\n await setLastInputTokensFenced(observed);\n }\n },\n });\n await reconcileConversationTruth();\n try {\n await ensureRunAllowed(\n settings,\n db,\n input.accountId,\n input.workspaceId,\n isCodexTurn,\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 = 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 ...pendingToolCall,\n });\n if (!registered.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while recording an in-flight tool call\",\n );\n }\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 resultItem: completedToolCall.resultItem,\n });\n if (!recorded.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while recording a tool-call result\",\n );\n }\n if (recorded.allResultsRecorded) {\n // Persist the SDK's now-stable complete call/result batch before\n // clearing its receipts. A crash between these transactions is\n // harmless: settlement finds both raw results and merely\n // consumes them without fabricating an interruption.\n await reconcileConversationTruth({ requireDurable: true });\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 });\n if (!cleared.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while finalizing tool-call results\",\n );\n }\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 }\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 batcher.flush();\n await stream.completed.catch(() => undefined);\n if (responseUsageCount === 0) {\n const aggregateUsage = stream.state.usage;\n const aggregateInput = (aggregateUsage as { inputTokens?: unknown } | undefined)\n ?.inputTokens;\n if (typeof aggregateInput === \"number\" && aggregateInput > 0) {\n lastInputTokensObserved = aggregateInput;\n }\n const aggregateSourceKey = modelUsageSourceKey({\n responseId: null,\n dispatchId: modelUsageDispatchId,\n positionalKey: \"aggregate\",\n });\n // The single aggregate frame is this turn's only model-usage record, so\n // it is the first (account-switch surfaces here just like a first response).\n const aggregateAccountCtx = modelCallAccountContext({\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n isFirstCallOfTurn: true,\n });\n recordModelCacheTokens(observability, streamProvider, {\n cachedTokens: modelCallUsageTelemetry(\n aggregateUsage as Parameters<typeof modelCallUsageTelemetry>[0],\n ).cachedTokens,\n promptTokens: (aggregateUsage as { inputTokens?: unknown } | undefined)?.inputTokens as\n | number\n | undefined,\n });\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 await recordModelUsageAndDebitCredits(settings, db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n model: turn.model,\n isCodexTurn,\n usage: aggregateUsage,\n sourceKey: aggregateSourceKey,\n observability,\n });\n await emitModelCallUsage({\n observability,\n publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n provider: resolvedModel?.provider.id ?? settings.openaiProvider,\n providerApi: resolvedModel?.provider.api ?? \"responses\",\n model: turn.model,\n sourceKey: aggregateSourceKey,\n usage: { usage: aggregateUsage },\n servingAccountHash: aggregateAccountCtx.servingAccountHash,\n accountChangedFromPrevCall: aggregateAccountCtx.accountChangedFromPrevCall,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n });\n },\n recordAttemptSignals: async () => {\n if (typeof aggregateInput === \"number\" && aggregateInput > 0) {\n await setLastInputTokensFenced(aggregateInput);\n }\n },\n });\n }\n if (stream.interruptions.length > 0) {\n await reconcileConversationTruth();\n const approvals = runtime.serializeApprovals(stream.interruptions);\n await saveRunStateFenced({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n expectedExecutionGeneration: executionGeneration,\n expectedAttemptId: input.attemptId,\n serializedRunState: stream.state.toString(),\n pendingApprovals: approvals,\n // Record the account freezing this state so a resume on a DIFFERENT\n // codex account strips its account-bound reasoning before replay (HOLE C).\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n if (\n !(await settle!({\n events: [\n { type: \"session.requiresAction\", payload: { approvals } },\n {\n type: \"session.status.changed\",\n payload: { status: \"requires_action\" },\n },\n ],\n turnStatus: \"requires_action\",\n sessionStatus: \"requires_action\",\n activeTurnId,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n activityStatus = \"requires_action\";\n return claimedResult({ status: \"requires_action\" });\n }\n\n const finalOutput = 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 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,\n error: 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 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 compactionFailureMessage = compactionFailureReason(\n compactError instanceof Error ? compactError.message : String(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 }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = attemptError;\n return claimedResult({ status: \"idle\" });\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 recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: \"sandbox_lease_superseded\",\n });\n if (recovery.action === \"stale\") {\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 console.error(\"sandbox lease supersession recovery failed\", recoveryError);\n throw recoveryError;\n }\n }\n if (isWorkerShutdownCancellation(error) && recoveryTurnId) {\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 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(\"worker-shutdown recovery checkpoint failed\", recoveryError);\n throw recoveryError;\n }\n }\n if (error instanceof TurnAttemptFencedError) {\n activityStatus = \"cancelled\";\n activityError = error;\n await flushRuntimeBatcher();\n // Ownership already moved to a newer attempt or an authoritative\n // control transaction. Surface a transport cancellation instead of a\n // normal activity result: with WAIT_CANCELLATION_COMPLETED, Temporal\n // must observe a terminal cancellation before the session workflow may\n // close. Returning normally after a cancel request is rejected by the\n // server and leaves the worker task detached indefinitely.\n turnMetricOutcome = \"cancelled\";\n throw new CancelledFailure(\"TURN_ATTEMPT_FENCED\", [], error);\n }\n if (error instanceof CancelledFailure) {\n activityStatus = \"cancelled\";\n activityError = error;\n await flushRuntimeBatcher();\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 error;\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 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 notifyParentOfChildTerminal(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n \"failed\",\n `turn:${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(\n codexCredentialFailure,\n serving,\n settings.codexRotationNearExhaustionPct,\n now,\n );\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 nearExhaustionPct: settings.codexRotationNearExhaustionPct,\n now: new Date(),\n usedConnectors: serving?.connectorNamespaces ?? [],\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. A stale activity performs no second settlement.\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\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 settings.codexRotationNearExhaustionPct,\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 nearExhaustionPct: settings.codexRotationNearExhaustionPct,\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(\n fresh,\n settings.codexRotationNearExhaustionPct,\n new Date(),\n );\n capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(\n fresh,\n settings.codexRotationNearExhaustionPct,\n new Date(),\n );\n }\n } else {\n const decision = chooseRotationActive({\n rotationStrategy: reactiveStrategy,\n activeCredentialId: rotation.activeCredentialId,\n priorCredentialId: effectiveCodexCredentialId,\n accounts: fresh,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\n now: new Date(),\n // P4: the just-capped serving account's connector set is the proxy for\n // \"what this session has access to\" — prefer a covering failover target.\n usedConnectors: serving?.connectorNamespaces ?? [],\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(\n fresh,\n settings.codexRotationNearExhaustionPct,\n new Date(),\n );\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 (goalActive && goal && 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: goal.id,\n goalVersion: goal.version,\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 = \"failed\";\n activityStatus = \"idle\";\n activityError = error;\n return claimedResult({\n status: \"idle\",\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 idempotencyKey: `usage:agent_run.completed:${turnId}`,\n });\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\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 = agentRunFailurePayload(error);\n if (failure.retryable && publish && turnId && turnStartedPublished) {\n const recoveryResult = providerRecoveryResult();\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 detail: {\n ...failure,\n continueDelayMs: recoveryResult.continueDelayMs,\n },\n });\n if (recovery.action === \"stale\") {\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n turnMetricOutcome = \"recovering\";\n activityStatus = \"recovering\";\n activityError = error;\n return claimedResult(recoveryResult);\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). Deduped\n // per terminal episode by the child's lastSequence, so it never\n // double-fires with the workflow-level wake.\n await notifyParentOfChildTerminal(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n \"failed\",\n `turn:${turnId}`,\n );\n return claimedResult({ status: \"failed\" });\n } finally {\n gitCredentialRenewalClosed = true;\n const renewalToStop = gitCredentialRenewal as GitCredentialRenewalController | null;\n gitCredentialRenewal = null;\n await renewalToStop?.stop();\n const durationSeconds = (performance.now() - activityStarted) / 1000;\n observability.recordWorkerActivity({\n activity: \"runAgentTurn\",\n status: 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 },\n error: activityError,\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 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 }\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 recordCodexAccountUsageWithWakeTargets(\n db,\n input.workspaceId,\n effectiveCodexCredentialId,\n latestCodexUsage,\n ).catch(() => null);\n if (usageMutation) {\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n usageMutation.wakeTargets,\n );\n }\n }\n // Part B.1: the connector namespaces codex_apps listed this turn → the\n // connector-set cache. NON-EMPTY-only: a flaky/empty tools/list must never\n // overwrite a known set with [] (false coverage drop). Read by reference\n // AFTER the run, so every tools/list this turn has accumulated.\n const connectorNamespaces = preparedTools?.codexConnectorNamespaces;\n if (connectorNamespaces && connectorNamespaces.size > 0) {\n await recordCodexAccountConnectors(db, input.workspaceId, effectiveCodexCredentialId, [\n ...connectorNamespaces,\n ]).catch(() => undefined);\n }\n }\n if (codexLeaseHeartbeatTimer) {\n clearInterval(codexLeaseHeartbeatTimer);\n codexLeaseHeartbeatTimer = undefined;\n }\n if (codexLeaseHeld && turnId && codexLeaseHolderId && codexLeaseGeneration !== null) {\n await releaseCodexCredentialLease(\n db,\n input.accountId,\n input.workspaceId,\n turnId,\n codexLeaseHolderId,\n codexLeaseGeneration,\n ).catch(() => undefined);\n codexLeaseHeld = false;\n }\n // Workbench v2 turn-end workspace capture (dossier §10.1) — 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 60s, 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 (resolvedSandbox && setupBoxSession && sandboxGroupId) {\n // Stop new heartbeat snapshot/meter ticks so a mid-turn snapshot cannot\n // start concurrently with capture, then drain any in-flight snapshot\n // (bounded) — capture and the warm snapshot both exec on the box, so\n // sequence them, exactly as the turn-end snapshot placement did.\n if (leaseHeartbeatTimer) {\n clearInterval(leaseHeartbeatTimer);\n leaseHeartbeatTimer = undefined;\n }\n if (snapshotInFlight) {\n await waitForWarmSnapshot(snapshotInFlight, settings.sandboxSnapshotTimeoutMs);\n }\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 leaseEpoch: resolvedSandbox.leaseEpoch,\n sandboxGroupId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turnId ?? null,\n observability,\n });\n }\n await preparedTools?.close().catch(() => undefined);\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\n }\n if (turnSandboxProvisioner?.hasStarted()) {\n await turnSandboxProvisioner.waitForSettled(30_000);\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 clearInterval(leaseHeartbeatTimer);\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 abandonActiveRecording(\n \"activity ended without recording settlement\",\n didComputerUse ? \"failed\" : \"discard\",\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 if (setupBoxSession && sandboxGroupId) {\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(snapshotInFlight, settings.sandboxSnapshotTimeoutMs);\n }\n const persisted = await maybePersistWarmWorkspaceSnapshot(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId,\n },\n setupBoxSession,\n resolvedSandbox.leaseEpoch,\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 (dossier §10.1) 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 await resolvedSandbox.release().catch((releaseError) => {\n console.error(\"sandbox lease release failed (turn outcome unaffected)\", releaseError);\n });\n resolvedSandbox = null; // drop the handle; the box survives the turn\n }\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 */\nexport function isTransientProviderError(error: unknown): boolean {\n const status =\n typeof error === \"object\" && error !== null && \"status\" in error\n ? Number((error as { status?: unknown }).status)\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 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(error: unknown): {\n error: string;\n code?: string;\n retryable?: boolean;\n detail?: string;\n} {\n const message = error instanceof Error ? error.message : String(error);\n const status =\n typeof error === \"object\" && error !== null && \"status\" in error\n ? Number((error as { status?: unknown }).status)\n : undefined;\n const code =\n typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\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 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 (\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 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 nearExhaustionPct: number,\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) >= nearExhaustionPct &&\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 ?? body?.status);\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 headers = value.headers as { get?: (name: string) => string | null } | undefined;\n const retryAfterHeader = headers?.get?.(\"retry-after\") ?? null;\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 codex-billed bypass (codex-billing.test.ts); not part\n// of the activity surface. Takes BOTH `isCodexTurn` (codex-plan turns bypass the credit\n// and token gates) and the optional §7.5 P3 host `entitlements` port (when bound, its\n// `admitRun` REPLACES the local credit read for a non-codex turn; unset → local ledger).\nexport async function ensureRunAllowed(\n settings: Settings,\n db: ActivityServices[\"db\"],\n accountId: string,\n workspaceId: string,\n isCodexTurn: boolean,\n entitlements?: ActivityServices[\"entitlements\"],\n): Promise<void> {\n // Codex-billed turns are paid by the user's ChatGPT/Codex plan: skip the\n // credit-balance gate and the monthly token cap. The agent-run COUNT cap below\n // is a 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 !isCodexTurn &&\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 !isCodexTurn &&\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 (!isCodexTurn && 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\n// Exported for unit testing the codex-billed 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 model: string;\n isCodexTurn: boolean;\n usage?: ModelUsageInput | null;\n sourceKey: string;\n observability?: ActivityServices[\"observability\"];\n },\n): Promise<void> {\n if (!input.usage) {\n return;\n }\n const inputTokens = positiveInt(input.usage.inputTokens);\n const outputTokens = positiveInt(input.usage.outputTokens);\n const totalTokens = positiveInt(input.usage.totalTokens) || inputTokens + outputTokens;\n // A codex-subscription turn is paid by the user's ChatGPT/Codex plan, 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.isCodexTurn) {\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 idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`,\n });\n return;\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 idempotencyKey: `usage:model.tokens:${input.turnId}:${input.sourceKey}`,\n });\n }\n const shouldDebit = settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\";\n if (!shouldDebit || totalTokens === 0) {\n return;\n }\n if (!configuredModelPricing(settings)[input.model]) {\n throw new Error(`Missing model pricing for ${input.model}`);\n }\n const costMicros = calculateModelUsageCostMicros(settings, input.model, input.usage);\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 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 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: positiveInt(\n modelCallUsageTelemetry(input.usage as Parameters<typeof modelCallUsageTelemetry>[0])\n .cachedTokens,\n ),\n },\n });\n recordCreditMicros(input.observability, \"usage\", result.debitedMicros);\n }\n}\n\nfunction positiveInt(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;\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): Promise<SandboxFileDownload[]> {\n if (settings.sandboxBackend === \"none\" || !requiresSignedFileResourceDownloads(settings)) {\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: resource.mountPath ?? `files/${file.id}`,\n filename: file.safeFilename,\n url: url.url,\n expiresAt: url.expiresAt,\n sizeBytes: file.sizeBytes,\n });\n }\n return downloads;\n}\n\nfunction requiresSignedFileResourceDownloads(settings: Settings): boolean {\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 (settings.sandboxBackend === \"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[settings.sandboxBackend].nativeBucketMount;\n return (\n (settings.sandboxBackend === \"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 {\n environmentsEncryptionKeyBytes,\n parseModelProvidersJson,\n type RegistryProvider,\n type Settings,\n} from \"@opengeni/config\";\nimport { settingsWithMcpCapabilityServers } from \"@opengeni/core\";\nimport {\n CODEX_APPS_MCP_SERVER_ID,\n CODEX_APPS_MCP_SERVER_NAME,\n CODEX_APPS_MCP_URL,\n CODEX_APPS_STARTUP_TIMEOUT_MS,\n CODEX_FALLBACK_MODEL_SLUGS,\n CODEX_MODEL_CONTEXT_WINDOW_TOKENS,\n CODEX_MODEL_EFFECTIVE_CONTEXT_WINDOW_TOKENS,\n CODEX_MODEL_AUTO_COMPACT_TOKEN_LIMIT,\n CODEX_MODEL_ID_PREFIX,\n CODEX_PROVIDER_BASE_URL,\n CODEX_PROVIDER_ID,\n} from \"@opengeni/codex\";\nimport {\n listEnabledMcpCapabilityServers,\n listSessionMcpServerMetadata,\n listSessionMcpServersForRun,\n workspaceCodexSubscriptionActive,\n type Database,\n type SessionMcpServerForRun,\n} from \"@opengeni/db\";\n\nexport async function settingsWithEnabledCapabilityMcpServers(\n db: Database,\n workspaceId: string,\n settings: Settings,\n): Promise<Settings> {\n const enabled = await listEnabledMcpCapabilityServers(db, workspaceId);\n return settingsWithMcpCapabilityServers(settings, enabled);\n}\n\nexport async function settingsWithSessionMcpServersForRun(\n db: Database,\n workspaceId: string,\n sessionId: string,\n settings: Settings,\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 throw new Error(\"session MCP server credentials require OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\");\n }\n return settingsWithSessionMcpServers(\n settings,\n await listSessionMcpServersForRun(db, workspaceId, sessionId, encryptionKey),\n );\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 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 // Additive: append the synthetic codex_apps connectors MCP server for ANY\n // active credential. Connector access is gated SERVER-SIDE per ChatGPT account\n // (via chatgpt-account-id), NOT by token scopes — confirmed live: a `pro` token\n // whose only scopes are openid/profile/email/offline_access still lists all 217\n // connector tools at .../ps/mcp. So we inject unconditionally and let\n // runtime-discovery decide: an account with no connectors yields an empty\n // tools/list, and a connect failure best-effort-drops the server without\n // failing the turn. The bearer is injected dynamically at connect time\n // (runtime/codexAppsMcpRequestInit).\n return withCodexAppsMcpServer(withProvider);\n}\n\n/**\n * Pure: append the synthetic codex_apps MCP server, idempotently. Connector\n * access is gated SERVER-SIDE per ChatGPT account (chatgpt-account-id), not by\n * token scopes, so we inject for any active credential and let runtime-discovery\n * resolve the actual tool set (empty list / dropped server when unavailable).\n * No secrets here — the refreshing bearer is injected at connect time from\n * codexRequestStorage (runtime/codexAppsMcpRequestInit). The connectors backend\n * tolerates serial and parallel tool invocation, so no per-server serialization\n * is enforced (the SDK exposes no per-server parallel-tool-calls flag in\n * @openai/agents 0.11.6).\n */\nexport function withCodexAppsMcpServer(settings: Settings): Settings {\n if (settings.mcpServers.some((server) => server.id === CODEX_APPS_MCP_SERVER_ID)) {\n return settings; // already injected\n }\n return {\n ...settings,\n mcpServers: [\n ...settings.mcpServers,\n {\n id: CODEX_APPS_MCP_SERVER_ID,\n name: CODEX_APPS_MCP_SERVER_NAME,\n url: CODEX_APPS_MCP_URL,\n timeoutMs: CODEX_APPS_STARTUP_TIMEOUT_MS,\n // Connector availability is per-credential and must re-discover each\n // run; never poison a process-global tools-list cache.\n cacheToolsList: false,\n // deliberately NO `headers` — the refreshing bearer is dynamic\n },\n ],\n };\n}\n\n/** Pure: append the synthetic codex-subscription provider, idempotently. */\nexport function withCodexProvider(settings: Settings): Settings {\n const providers = parseModelProvidersJson(settings.modelProvidersJson);\n if (providers.some((provider) => provider.id === CODEX_PROVIDER_ID)) {\n return settings; // already injected\n }\n const codexProvider: RegistryProvider = {\n kind: \"codex-subscription\",\n id: CODEX_PROVIDER_ID,\n label: \"Codex (ChatGPT subscription)\",\n api: \"responses\",\n baseUrl: CODEX_PROVIDER_BASE_URL,\n models: CODEX_FALLBACK_MODEL_SLUGS.map((slug) => ({\n id: `${CODEX_MODEL_ID_PREFIX}${slug}`,\n label: slug,\n reasoningEffort: true,\n // These three values are the live Codex CLI catalog policy, kept distinct\n // so proactive compaction and the effective input guard match Codex core.\n contextWindowTokens: CODEX_MODEL_CONTEXT_WINDOW_TOKENS,\n effectiveContextWindowTokens: CODEX_MODEL_EFFECTIVE_CONTEXT_WINDOW_TOKENS,\n autoCompactTokenLimit: CODEX_MODEL_AUTO_COMPACT_TOKEN_LIMIT,\n })),\n };\n return { ...settings, modelProvidersJson: JSON.stringify([...providers, codexProvider]) };\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 * 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 && 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 // `droppedConnectors` (P4 Part B): the leaving session's used connectors that the\n // chosen account does NOT cover — populated ONLY on a Tier-2/unknown pick that\n // can't cover (prefer-not-require: failover still happens, but the pill warns).\n | { kind: \"active\"; credentialId: string; moved: boolean; droppedConnectors?: string[] }\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 over-threshold 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\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 * P4 connector coverage (prefer-not-require). `acct` COVERS `usedConnectors` iff its\n * cached connector set is a SUPERSET of the session's used set. An empty used set is\n * trivially covered by everyone (→ Tier 1 == all eligibles == byte-identical to P3).\n * A null (never-probed) set is UNKNOWN: never credited as covering (Tier 2 only),\n * but — critically — never excluded, so failover is fully preserved.\n */\nfunction covers(acct: CodexRotationAccount, usedConnectors: string[]): boolean {\n if (usedConnectors.length === 0) {\n return true;\n }\n const owned = acct.connectorNamespaces;\n if (owned === null) {\n return false; // unprobed ⇒ unknown ⇒ never Tier 1 (but still a Tier-2 candidate)\n }\n const ownedSet = new Set(owned);\n return usedConnectors.every((connector) => ownedSet.has(connector));\n}\n\n/**\n * The used connectors the chosen account does NOT cover (the \"switch dropped a\n * connector\" note). Empty when the account covers (superset) or nothing was used.\n * A null (unknown) set surfaces ALL used connectors — we can't prove it covers them.\n */\nfunction droppedConnectorsFor(acct: CodexRotationAccount, usedConnectors: string[]): string[] {\n if (usedConnectors.length === 0) {\n return [];\n }\n const owned = acct.connectorNamespaces;\n if (owned === null) {\n return [...usedConnectors];\n }\n const ownedSet = new Set(owned);\n return usedConnectors.filter((connector) => !ownedSet.has(connector));\n}\n\n/**\n * Healthy for an already-frozen/in-flight turn = connected/usable (status\n * \"active\", excludes needs_relogin/error), not cooling, and under the\n * near-exhaustion threshold on BOTH windows. Allocator eligibility is\n * deliberately separate so disabling NEW work cannot break refresh/resume.\n */\nexport function isCodexCredentialHealthy(\n acct: CodexRotationAccount,\n nearExhaustionPct: number,\n now: Date,\n): boolean {\n return (\n acct.status === \"active\" && !cooling(acct, now) && bindingUsedPct(acct, now) < nearExhaustionPct\n );\n}\n\n/** New automatic allocation requires both health and explicit allocator eligibility. */\nexport function isCodexCredentialEligible(\n acct: CodexRotationAccount,\n nearExhaustionPct: number,\n now: Date,\n): boolean {\n return acct.allocatorEnabled && isCodexCredentialHealthy(acct, nearExhaustionPct, 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 under\n * the near-exhaustion threshold 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(\n acct: CodexRotationAccount,\n nearExhaustionPct: number,\n now: Date,\n): boolean {\n return isCodexCredentialEligible(acct, nearExhaustionPct, 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, under-threshold) 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 nearExhaustionPct: number;\n now: Date;\n}): string | null {\n const { sessionId, accounts, nearExhaustionPct, now } = args;\n const eligibles = accounts.filter((acct) =>\n isCodexCredentialEligible(acct, nearExhaustionPct, now),\n );\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(\n accounts: CodexRotationAccount[],\n nearExhaustionPct: number,\n now: Date,\n): Date {\n return earliestReset(accounts, nearExhaustionPct, 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 nearExhaustionPct: number;\n now: Date;\n}):\n | { kind: \"home\"; credentialId: string; rewritePin: boolean }\n | { kind: \"allCapped\"; earliestResetAt: Date } {\n const { sessionId, currentPolicyPin, accounts, nearExhaustionPct, now } = args;\n const pinRow = currentPolicyPin\n ? (accounts.find((acct) => acct.id === currentPolicyPin) ?? null)\n : null;\n if (pinRow && isCodexCredentialEligible(pinRow, nearExhaustionPct, now)) {\n return { kind: \"home\", credentialId: currentPolicyPin!, rewritePin: false };\n }\n const home = shardCredentialForSession({ sessionId, accounts, nearExhaustionPct, now });\n if (home == null) {\n return { kind: \"allCapped\", earliestResetAt: earliestReset(accounts, nearExhaustionPct, 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(\n acct: CodexRotationAccount,\n nearExhaustionPct: number,\n now: Date,\n): 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) >= nearExhaustionPct,\n acct.primaryResetAt,\n );\n windowClear(\n effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now) >= nearExhaustionPct,\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(\n accounts: CodexRotationAccount[],\n nearExhaustionPct: number,\n now: Date,\n): Date {\n return accounts\n .map((acct) => availableAt(acct, nearExhaustionPct, 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 nearExhaustionPct: number,\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) >= nearExhaustionPct &&\n account.primaryResetAt &&\n account.primaryResetAt.getTime() > now.getTime()\n ) {\n future.push(account.primaryResetAt);\n }\n if (\n (account.secondaryUsedPercent ?? 0) >= nearExhaustionPct &&\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 re-ranks (a connector-covering\n * pick order) without 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 nearExhaustionPct: number;\n now: Date;\n // P4 (Part B): the connectors the leaving session has access to (the leaving\n // account's cached connector set, used as the \"session needs these\" proxy).\n // Optional + defaults to [] ⇒ when absent/empty the ranker is BYTE-IDENTICAL to\n // P3 (every account trivially covers → Tier 1 == all eligibles). Self-gating.\n usedConnectors?: string[];\n}): RotationDecision {\n const {\n rotationStrategy,\n activeCredentialId,\n priorCredentialId,\n accounts,\n nearExhaustionPct,\n now,\n } = args;\n const allocatableAccounts = accounts.filter((account) => account.allocatorEnabled);\n const usedConnectors = args.usedConnectors ?? [];\n\n if (allocatableAccounts.length === 0) {\n return { kind: \"none\" };\n }\n\n const eligibles = allocatableAccounts.filter((acct) =>\n isCodexCredentialEligible(acct, nearExhaustionPct, now),\n );\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 until 90% was the production monopolization\n // defect fixed by OPE-21. 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, nearExhaustionPct, now),\n };\n }\n // P4: surface the dropped-connector note when the chosen account doesn't cover\n // the session's used connectors (a Tier-2/unknown failover pick). Empty ⇒ omit.\n const dropped = droppedConnectorsFor(chosen, usedConnectors);\n return {\n kind: \"active\",\n credentialId: chosen.id,\n moved: chosen.id !== activeCredentialId,\n ...(dropped.length > 0 ? { droppedConnectors: dropped } : {}),\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, nearExhaustionPct, 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, nearExhaustionPct, 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, nearExhaustionPct, now)) {\n return decide(priorRow);\n }\n return decide(eligibles[0]);\n }\n\n // most_remaining (default + the correctness path). Two-tier coverage pick over\n // the SAME eligible set (prefer-not-require):\n // Tier 1 — eligibles whose connector set COVERS the session's used set.\n // Tier 2 — ALL eligibles, only if Tier 1 is empty (failover fully preserved).\n // Within the chosen tier:\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 covering = eligibles.filter((acct) => covers(acct, usedConnectors));\n const pool = covering.length > 0 ? covering : eligibles;\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 = pool.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/connector 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.nearExhaustionPct, 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 /** Same-turn checkpoint/frozen account; temporary disable cannot move it. */\n continuationCredentialId?: string | null;\n nearExhaustionPct: number;\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 const strategy = rotationStrategy as CodexRotationStrategy;\n const existing = existingCredentialId\n ? accounts.find((account) => account.id === existingCredentialId)\n : undefined;\n if (existing && isCodexCredentialHealthy(existing, args.nearExhaustionPct, 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 continuation = args.continuationCredentialId\n ? accounts.find((account) => account.id === args.continuationCredentialId)\n : undefined;\n if (continuation && isCodexCredentialHealthy(continuation, args.nearExhaustionPct, args.now)) {\n return {\n credentialId: continuation.id,\n advanceActivePointer: false,\n decision: {\n kind: \"active\",\n credentialId: continuation.id,\n moved: continuation.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; healthy live/frozen\n // same-turn continuity 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.nearExhaustionPct, 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.nearExhaustionPct, args.now),\n },\n advanceActivePointer: false,\n };\n }\n\n // OPE-31 policy homes compose with OPE-21 by sharding only the candidate list\n // handed to this selector. A future OPE-32 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 nearExhaustionPct: args.nearExhaustionPct,\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 nearExhaustionPct: args.nearExhaustionPct,\n now: args.now,\n usedConnectors: accounts.find((account) => account.id === priorId)?.connectorNamespaces ?? [],\n });\n return {\n credentialId: decision.kind === \"active\" ? decision.credentialId : null,\n decision,\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 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 continuationCredentialId: null,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\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) =>\n isCodexCredentialEligible(account, settings.codexRotationNearExhaustionPct, now),\n ).length,\n },\n };\n }\n const authoritativeReset = authoritativeCodexCapacityResetAt(\n context.accounts,\n settings.codexRotationNearExhaustionPct,\n now,\n );\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) >= services.settings.codexRotationNearExhaustionPct ||\n (account.secondaryUsedPercent ?? 0) >= services.settings.codexRotationNearExhaustionPct ||\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\", updateId: result.update.id };\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 type Database,\n} from \"@opengeni/db\";\nimport {\n SUMMARY_BUFFER_TOKENS,\n buildCompactionPromptInput,\n buildCompactionReplacementHistory,\n decideCompaction,\n estimateTokens,\n sanitizeHistoryItemsForModel,\n summarizeForCompaction,\n type CompactionItem,\n} from \"@opengeni/runtime\";\nimport type { Settings } from \"@opengeni/config\";\nimport type { SessionEvent } from \"@opengeni/contracts\";\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 events: SessionEvent[];\n };\n\n/**\n * Durable portable context compaction, following Codex CLI's local path.\n *\n * Runs before a fresh model call and on a same-turn compaction recovery.\n * Reads the active history rows + the most recent provider-reported input\n * tokens, applies the single Codex-parity threshold, and - when it should -\n * summarizes the active history with the Codex checkpoint prompt. The write\n * supersedes the old active rows and inserts replacement active rows:\n * all real user messages plus one summary.\n *\n * If the summarizer itself exceeds the context window, the oldest prompt item\n * is removed and the same compaction call is retried, exactly like Codex local\n * compaction. Other provider failures propagate. There is no non-model\n * fallback and no silent request-local history trimming.\n *\n * There is no kept assistant/tool tail. Assistant messages,\n * tool calls/results, reasoning, and images stay only in inactive audit rows.\n */\nexport type CompactionSummarizer = (settings: Settings, input: CompactionItem[]) => Promise<string>;\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 } = {},\n): Promise<MaybeCompactResult> {\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 { compacted: false, reason: \"no_history\", events: [], requestConsumed };\n }\n\n const items = sanitizeHistoryItemsForModel(active.map((row) => row.item) as CompactionItem[]);\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 estimatedTokensBefore = estimateTokens(items);\n const summaryBody = await summarizeWithCodexOverflowTrimming(summarize, settings, items);\n const replacementHistory = buildCompactionReplacementHistory(items, summaryBody);\n const estimatedTokensAfter = estimateTokens(replacementHistory);\n const summaryItem = replacementHistory.at(-1);\n if (!summaryItem) {\n return {\n compacted: false,\n reason: \"compaction produced no replacement history\",\n events: [],\n requestConsumed: false,\n };\n }\n if (estimatedTokensAfter >= estimatedTokensBefore) {\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: \"replacement_not_smaller\",\n });\n if (!skipped.recorded) {\n throw new TurnAttemptFencedError(\n \"turn attempt was fenced while consuming a non-shrinking context compaction request\",\n );\n }\n requestConsumed = true;\n return {\n compacted: false,\n reason: \"replacement_not_smaller\",\n events: skipped.events,\n requestConsumed,\n };\n }\n return {\n compacted: false,\n reason: \"replacement_not_smaller\",\n events: [],\n requestConsumed,\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: summaryItem as Record<string, unknown>,\n replacementInputTokens: estimatedTokensAfter,\n ...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),\n eventPayload: {\n trigger: options.trigger ?? \"auto\",\n estimatedTokensBefore,\n estimatedTokensAfter,\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 events: applied.events,\n };\n}\n\nasync function summarizeWithCodexOverflowTrimming(\n summarize: CompactionSummarizer,\n settings: Settings,\n activeHistory: CompactionItem[],\n): Promise<string> {\n const compactionHistory = activeHistory.slice();\n while (true) {\n try {\n return await summarize(settings, buildCompactionPromptInput(compactionHistory));\n } catch (error) {\n if (!isContextWindowExceeded(error) || compactionHistory.length === 0) {\n throw error;\n }\n // Codex removes one oldest history item, keeps the synthesized checkpoint\n // prompt, resets its stream retry count, and samples the summary again.\n compactionHistory.shift();\n }\n }\n}\n\nfunction isContextWindowExceeded(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const record = error as Record<string, unknown>;\n const code = typeof record.code === \"string\" ? record.code.toLowerCase() : \"\";\n const message = error instanceof Error ? error.message.toLowerCase() : \"\";\n return (\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 );\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","import {\n applyGitAuthPointerEnvironment,\n firstPartyMcpWorkspaceUrl,\n stableSandboxEnvironmentForRun,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n signDelegatedAccessToken,\n type ConnectionCredentialsPort,\n type GitCredentialProvider,\n type GitCredentialRepositoryRef,\n type GitCredentials,\n type ResourceRef,\n type SandboxSecrets,\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 P4a — the run's workspace identity, threaded so the connection-credential\n// provider can be called with the run's tenant context AND so the FORK-7\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 MintedRunGitCredentials = {\n gitTokens: GitTokenSeeds;\n expiresAt: GitTokenExpiries;\n};\n\n// §7.6 P4a — 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 // FORK-7: 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// §7.6 FORK-7 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 P4a - 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: {\n skipGitHubToken?: boolean;\n deferGitHubToken?: boolean;\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n sessionId?: string;\n runId?: string;\n } = {},\n): Promise<{\n environment: Record<string, string>;\n gitToken?: string;\n gitTokens?: GitTokenSeeds;\n gitTokenExpiresAt?: GitTokenExpiries;\n toolspaceToken?: string;\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, turn TTL,\n // budgeted, approval-tools excluded). Delivery mirrors the docker path: the\n // caller threads it OFF-MANIFEST as the seed the runtime writes to\n // $OPENGENI_TOOLSPACE_TOKEN_FILE over the box's exec channel.\n let toolspaceToken: string | undefined;\n if (\n settings.toolspaceEnabled &&\n settings.delegationSecret &&\n options.scope &&\n options.sessionId &&\n options.runId\n ) {\n toolspaceToken = await signDelegatedAccessToken(settings.delegationSecret, {\n accountId: options.scope.accountId,\n workspaceId: options.scope.workspaceId,\n subjectId: `sandbox:${options.runId}`,\n subjectLabel: \"sandbox toolspace\",\n permissions: [\"toolspace:call\"],\n sessionId: options.sessionId,\n exp: Math.floor(Date.now() / 1000) + 60 * 60,\n });\n environment.OPENGENI_TOOLSPACE_URL ??= firstPartyMcpWorkspaceUrl(\n settings,\n options.scope.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 { environment, ...(toolspaceToken ? { toolspaceToken } : {}) };\n }\n if (options.deferGitHubToken) {\n applyGitAuthPointerEnvironment(\n environment,\n await resolveRunGitIdentityWithSelections(settings, selections, options),\n );\n return { environment, ...(toolspaceToken ? { toolspaceToken } : {}) };\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 ...(toolspaceToken ? { toolspaceToken } : {}),\n };\n}\n\nexport async function mintRunGitCredentials(\n settings: Settings,\n resources: ResourceRef[],\n options: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n } = {},\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 Object.keys(minted.gitTokens).length > 0\n ? { gitTokens: minted.gitTokens, expiresAt: minted.expiresAt }\n : undefined;\n}\n\nexport async function mintRunGitTokens(\n settings: Settings,\n resources: ResourceRef[],\n options: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n } = {},\n): Promise<GitTokenSeeds | undefined> {\n return (await mintRunGitCredentials(settings, resources, options))?.gitTokens;\n}\n\nexport async function mintRunGitToken(\n settings: Settings,\n resources: ResourceRef[],\n options: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n } = {},\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: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n } = {},\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: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n },\n): Promise<{\n gitTokens: GitTokenSeeds;\n expiresAt: GitTokenExpiries;\n identity: { name: string; email: string } | null;\n}> {\n const gitTokens: GitTokenSeeds = {};\n const expiresAt: GitTokenExpiries = {};\n let identity: { name: string; email: string } | null = null;\n for (const selection of selections) {\n let token: string | null = null;\n if (options?.gitCredentials && options.scope) {\n const request = gitCredentialsRequestForSelection(options.scope, selection, \"token\");\n const minted: GitCredentials = await options.gitCredentials(request);\n // FORK-7: 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 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 if (minted.expiresAt) {\n expiresAt[selection.provider] = validatedGitCredentialExpiry(\n selection.provider,\n minted.expiresAt,\n );\n }\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 if (minted.expiresAt) {\n expiresAt.github = validatedGitCredentialExpiry(\"github\", minted.expiresAt);\n }\n identity = githubAppBotIdentity(settings);\n }\n if (token) {\n gitTokens[selection.provider] = token;\n }\n }\n return { 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\nasync function resolveRunGitIdentityWithSelections(\n settings: Settings,\n selections: GitCredentialSelection[],\n options: {\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n },\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 resolved: GitCredentials = await options.gitCredentials(\n gitCredentialsRequestForSelection(options.scope, selection, \"identity\"),\n );\n assertWorkspaceEcho(\"gitCredentials\", options.scope, resolved.workspaceId);\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 installationId: number;\n repositoryIds: number[];\n repositoryRefs: GitCredentialRepositoryRef[];\n};\n\nfunction gitCredentialsRequestForSelection(\n scope: ConnectionScope,\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 ...(purpose ? { purpose } : {}),\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n };\n if (selection.provider === \"github\") {\n return {\n ...legacy,\n repositoryRefs: selection.repositoryRefs,\n };\n }\n return {\n ...legacy,\n provider: selection.provider,\n repositoryRefs: selection.repositoryRefs,\n };\n}\n\nfunction gitCredentialSelections(resources: ResourceRef[]): GitCredentialSelection[] {\n const byProvider = new Map<GitCredentialProvider, GitCredentialSelection>();\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 entry = byProvider.get(provider) ?? {\n provider,\n installationId: 0,\n repositoryIds: [],\n repositoryRefs: [],\n };\n const ref = gitCredentialRepositoryRef(resource, provider);\n entry.repositoryRefs.push(ref);\n if (provider === \"github\") {\n const installationId = positiveInteger(\n resource.githubInstallationId ?? resource.installationId,\n );\n const repositoryId = positiveInteger(resource.githubRepositoryId ?? resource.repositoryId);\n if (installationId && repositoryId) {\n if (entry.installationId > 0 && entry.installationId !== installationId) {\n throw new Error(\"GitHub App repository resources must belong to one installation\");\n }\n entry.installationId = installationId;\n entry.repositoryIds.push(repositoryId);\n }\n }\n byProvider.set(provider, entry);\n }\n return [...byProvider.values()];\n}\n\nfunction repositoryCredentialProvider(\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n): GitCredentialProvider | null {\n if (resource.provider) {\n return resource.provider;\n }\n if (\n positiveInteger(resource.githubInstallationId) &&\n positiveInteger(resource.githubRepositoryId)\n ) {\n return \"github\";\n }\n return null;\n}\n\nfunction gitCredentialRepositoryRef(\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n provider: GitCredentialProvider,\n): GitCredentialRepositoryRef {\n return {\n provider,\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","import {\n configuredStaticUsageLimits,\n policyProviderIdForModel,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n evaluateWorkspaceModelPolicy,\n mergeToolRefs,\n reasoningEffortForMetadata,\n type SessionGoal,\n type ToolRef,\n} from \"@opengeni/contracts\";\nimport {\n addSessionSystemUpdate,\n enqueueSessionWorkflowWakeIfRunnable,\n evaluateGoalContinuation,\n getBillingBalance,\n getLatestStartedSessionTurn,\n getWorkspaceModelPolicy,\n getSessionGoal,\n isCodexBilledTurn,\n recordUsageEvent,\n requireSession,\n sumUsageQuantity,\n type Database,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents } from \"@opengeni/events\";\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 // 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 // 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 evaluateGoalContinuation(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\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 });\n if (decision.decision === \"none\" || decision.decision === \"queue\") {\n return { action: decision.decision };\n }\n if (decision.decision === \"paused\") {\n await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n type: \"goal.paused\",\n payload: {\n goalId: decision.goal.id,\n actor: \"system\",\n reason: decision.reason,\n ...(decision.goal.rationale ? { rationale: decision.goal.rationale } : {}),\n autoContinuations: decision.goal.autoContinuations,\n noProgressStreak: decision.goal.noProgressStreak,\n },\n },\n ]);\n return { action: \"paused\" };\n }\n // Stop/continue race guard: a concurrent goal_complete/goal_pause/operator\n // PATCH between the locked decision and this synthesis must win. The\n // version check also catches a replace. A pause landing after this point\n // results in at most one already-admitted continuation turn; the next\n // pass sees the non-active goal and stops, and interrupt-driven pauses\n // additionally cancel the claimed turn via the workflow interrupt path.\n const recheck = await getSessionGoal(db, input.workspaceId, input.sessionId);\n if (!recheck || recheck.status !== \"active\" || recheck.version !== decision.goal.version) {\n return { action: \"none\" };\n }\n const prompt = goalContinuationPrompt(decision.goal, decision.autoContinuation, decision.cap);\n const update = await addSessionSystemUpdate(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n kind: \"goal_continuation\",\n classification: \"info\",\n sourceId: decision.goal.id,\n dedupeKey: `goal-continuation:${decision.goal.id}:${decision.goal.version}:${decision.autoContinuation}`,\n summary: prompt,\n payload: {\n type: \"goal_continuation\",\n goalId: decision.goal.id,\n goalVersion: decision.goal.version,\n autoContinuation: decision.autoContinuation,\n maxAutoContinuations: decision.cap,\n prompt,\n policy: {\n model: continuationModel,\n reasoningEffort: continuationReasoningEffort,\n tools: withFirstPartyTools(settings, session.tools),\n sandboxBackend: session.sandboxBackend,\n },\n },\n lineage: { goalId: decision.goal.id },\n });\n if (update.reason === \"session_cancelled\") return { action: \"none\" };\n if (update.added && update.events.length > 0) {\n await bus.publish(input.workspaceId, input.sessionId, update.events);\n }\n // Continuations count as agent runs for limits/metering parity with\n // user-initiated and scheduled turns.\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"agent_run.created\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"session_system_update\",\n sourceResourceId: update.update.id,\n idempotencyKey: `agent_run.created:goal:${input.workspaceId}:${update.update.id}`,\n });\n return { action: \"continue\" };\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 * Ensures a turn references the synthetic codex_apps connectors MCP server when\n * the codex overlay injected it (active subscription + connector scopes). A\n * registry entry is inert until a ToolRef references its id, so this wires the\n * server into the run. No-op when the server is not configured (every non-codex\n * turn), and idempotent via mergeToolRefs.\n */\nexport function withCodexAppsTool(settings: Settings, tools: ToolRef[]): ToolRef[] {\n if (!settings.mcpServers.some((server) => server.id === \"codex_apps\")) {\n return tools;\n }\n return mergeToolRefs(tools, [{ kind: \"mcp\", id: \"codex_apps\" }]);\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 { getWorkspace, getWorkspacePack, listPackInstallations, type Database } from \"@opengeni/db\";\nimport type { PackSkill } 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 skills: PackSkill[];\n};\n\nconst emptyPackRuntime: WorkspacePackRuntime = { sandboxImage: null, skills: [] };\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 * 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 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): Settings {\n if (!sandboxImage) {\n return settings;\n }\n return {\n ...settings,\n dockerImage: sandboxImage,\n modalImageRef: sandboxImage,\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 };\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 addSessionSystemUpdateWithSourceMutation,\n claimPendingSessionSystemUpdateOutbox,\n claimPendingSessionWorkflowWakes,\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 * Deliver exactly one completion wake to a spawned worker's parent (manager)\n * session when the worker reaches a terminal-for-now state. No-op for a\n * parentless session (direct API create / scheduled run). Idempotent per\n * terminal episode: the idempotency key is the child's current lastSequence,\n * which advances every time the child does work, so a retry of the same\n * terminal transition (activity retry, the workflow's idle re-check, the\n * runAgentTurn-failed path overlapping a workflow-level wake) is deduped while\n * a genuinely new idle-after-work episode notifies again. The parent receives\n * one typed internal update; signalling its workflow ensures an idle parent can\n * coalesce and process all pending updates in one inference. Failures here never\n * fail the child because the durable outbox remains retryable.\n *\n * Lives in its own module so both the session-state terminal activities\n * (markSessionIdle / failSession) and runAgentTurn's in-turn failure path can\n * call it without a circular import between those two activity modules.\n */\nexport async function notifyParentOfChildTerminal(\n svc: NotifyServices,\n workspaceId: string,\n childSessionId: string,\n terminalStatus: \"idle\" | \"failed\",\n // Stable identifier for the terminal episode, used as the idempotency key so\n // the same completion never wakes the parent twice. A FAILURE passes the\n // failed turn's id: both the in-turn wake (runAgentTurn) and the\n // workflow-level wake (failSession, after it appends more events that would\n // shift lastSequence) key on the same turn, so a finally-throw that turns one\n // failure into both paths still dedupes. An idle episode has no single\n // owning turn, so it falls back to the child's lastSequence — which advances\n // per work batch and is stable across retries of that same idle transition.\n episodeKey?: string | null,\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 ?? child.lastSequence}`;\n const payload = childCompletionPayload(child, goal, terminalStatus);\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:\n terminalStatus === \"failed\"\n ? \"failure\"\n : goal?.status === \"paused\"\n ? \"action_required\"\n : \"success\",\n sourceId: child.id,\n dedupeKey: clientEventId,\n summary: childCompletionSummary(child, goal, terminalStatus),\n payload,\n lineage: { childSessionId: child.id, parentSessionId: child.parentSessionId },\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 completion\", {\n childSessionId,\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 },\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 terminalStatus: \"idle\" | \"failed\",\n): Extract<SessionSystemUpdatePayload, { type: \"child_terminal_result\" }> {\n return {\n type: \"child_terminal_result\",\n childSessionId: child.id,\n status: terminalStatus,\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","const MIN_REDACTABLE_VALUE_LENGTH = 6;\n\nexport type SecretForRedaction = {\n name: string;\n value: string;\n};\n\n/**\n * Defense-in-depth against an agent echoing injected workspace environment\n * values (for example via `env`) into session events. Deep-walks payloads and\n * replaces every exact occurrence of each secret value with\n * `[redacted:<NAME>]`. Values shorter than six characters are skipped to avoid\n * a false-positive flood; secrets are applied longest-value-first so\n * overlapping values redact deterministically.\n */\nexport function createSecretRedactor(secrets: SecretForRedaction[]): (payload: unknown) => unknown {\n const usable = secrets\n .filter((secret) => secret.value.length >= MIN_REDACTABLE_VALUE_LENGTH)\n .sort((a, b) => b.value.length - a.value.length);\n if (usable.length === 0) {\n return identityRedactor;\n }\n const redact = (payload: unknown): unknown => {\n if (typeof payload === \"string\") {\n let out = payload;\n for (const secret of usable) {\n if (out.includes(secret.value)) {\n out = out.split(secret.value).join(`[redacted:${secret.name}]`);\n }\n }\n return out;\n }\n if (Array.isArray(payload)) {\n return payload.map(redact);\n }\n if (isPlainObject(payload)) {\n return Object.fromEntries(\n Object.entries(payload).map(([key, value]) => [key, redact(value)]),\n );\n }\n return payload;\n };\n return redact;\n}\n\nexport function identityRedactor(payload: unknown): unknown {\n return payload;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n","import type { FileAsset, ResourceRef, SessionSystemUpdate } from \"@opengeni/contracts\";\nimport {\n getActiveSessionHistoryItems,\n getLatestRunState,\n getSandboxSessionEnvelope,\n getSessionEvent,\n listSessionSystemUpdatesForTurn,\n requireFile,\n type Database,\n} from \"@opengeni/db\";\nimport {\n stripReasoningEncryptedContent,\n stripReasoningIdentityFromSerializedRunState,\n neutralizeToolSearchItemsInSerializedRunState,\n type OpenGeniRuntime,\n} from \"@opengeni/runtime\";\n\n/**\n * The codex account THIS turn runs on, threaded into every history read path so a\n * cross-account turn never replays another account's encrypted reasoning. The\n * single rule across all paths: DROP any reasoning item whose producing codex\n * account differs from `currentCodexCredentialId`.\n *\n * `currentCodexCredentialId` is the resolved codex credential id on a codex turn,\n * or NULL on a non-codex turn (the \"account\" of the built-in Azure/OpenAI path).\n * NULL is a real value in the comparison, not a \"skip\" sentinel: a non-codex turn\n * (current = null) still drops codex-produced reasoning (producer != null) so a\n * foreign encrypted blob never reaches the Azure/built-in Responses call. A\n * session with no codex history (every producer == null == current) is a no-op.\n */\nexport type TurnCodexAccount = { currentCodexCredentialId: string | null };\n\n/** A non-codex turn's account (current = null): no codex credential resolved. */\nconst NON_CODEX_TURN: TurnCodexAccount = { currentCodexCredentialId: null };\n\n/**\n * Apply the cross-account reasoning strip to a set of stored history rows. Pure +\n * non-mutating. The single rule: a row whose producing codex account EQUALS the\n * turn's current account replays verbatim (by reference); a row produced by a\n * DIFFERENT account is treated by item type —\n *\n * - `reasoning` → DROPPED WHOLE (id + blob filtered out of the history). The\n * foreign `rs_…` id is validated by the Responses backend, which rejects a\n * reasoning item that has a foreign id and no encrypted_content (store:false),\n * so blanking only the blob is not enough — the whole item must go.\n * - `compaction` → kept, with only its account-bound `encrypted_content` blob\n * stripped (its summary is real conversation content that must survive).\n * - everything else (messages, tool calls, tool outputs) → kept verbatim by\n * reference; message and tool content are never account-bound, never touched.\n *\n * Mismatch covers a foreign codex account, the non-codex/Azure producer (null on\n * a codex turn), and legacy untagged rows (null): all are stripped, which is\n * defensive and harmless (at most one turn of lost chain-of-thought continuity,\n * never any content). No-op (rows by reference) when every producer equals the\n * current account — a single-account workspace, an unchanged-account turn, or a\n * non-codex turn over a history with no codex-produced reasoning.\n */\nexport function applyCodexHistoryStrip(\n rows: ReadonlyArray<{ item: Record<string, unknown>; producerCodexCredentialId: string | null }>,\n current: TurnCodexAccount,\n): Array<Record<string, unknown>> {\n const out: Array<Record<string, unknown>> = [];\n for (const row of rows) {\n if (row.producerCodexCredentialId === current.currentCodexCredentialId) {\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 // Foreign reasoning: drop the WHOLE item (id + blob) — see rule above.\n continue;\n }\n if (type === \"tool_search_call\" || type === \"tool_search_output\") {\n // Foreign tool_search items (progressive connector disclosure): drop WHOLE,\n // like reasoning. The `tsc_…` id is minted by the producing account's\n // backend, and the output's disclosure set reflects THAT account's\n // connectors — replaying either into a different account risks a 400 /\n // wrong-connector disclosure. Dropping both sides keeps the pair invariant\n // (the history sanitizer would drop a stranded half anyway); the model\n // simply re-searches on the new account, re-disclosing from the NEW\n // account's own connector pool. Never any content loss — search items\n // carry tool metadata, not conversation content.\n continue;\n }\n if (type === \"compaction\") {\n out.push(stripReasoningEncryptedContent(row.item));\n continue;\n }\n out.push(row.item);\n }\n return out;\n}\n\n/**\n * Resolve the serialized RunState used only for an approval resume, applying\n * the same cross-account rule as the canonical history-items path. The blob\n * carries no per-item producer tag, so we\n * compare the codex account that FROZE the state to the resuming turn's account:\n * when they differ, neutralize every reasoning item's account-bound identity\n * (encrypted_content + provider id) in the blob; when they match (including\n * null == null for non-codex / single-account) the blob replays byte-for-byte\n * (same string reference). This closes the gap where a frozen A-minted RunState\n * was replayed verbatim into a turn that switched to account B (or to a non-codex\n * turn), 400ing the resume.\n */\nexport function resumeRunStateForCodexAccount(\n state: { serializedRunState: string; frozenCodexCredentialId: string | null },\n current: TurnCodexAccount,\n): string {\n if (state.frozenCodexCredentialId === current.currentCodexCredentialId) {\n return state.serializedRunState;\n }\n // Cross-account: neutralize reasoning identity in place AND flip frozen\n // tool_search pairs to execution:\"server\" in place (count-preserving — HOLE E\n // forbids removing blob items). The server flip makes the SDK skip its\n // client-executor rehydration (which would THROW when the resuming account's\n // connector pool differs from the freezing account's); the flipped shape is\n // live-verified wire-safe. The model can still re-search on this account.\n return neutralizeToolSearchItemsInSerializedRunState(\n stripReasoningIdentityFromSerializedRunState(state.serializedRunState),\n );\n}\n\n/**\n * A prepared turn input plus the watermark-seed discriminator the reconcile pass\n * needs (HOLE E). `modelHistoryFromItems` is TRUE iff `state.history` was seeded\n * from the cross-account-STRIPPED active history items (the items read path) — so\n * the turn-end reconcile must seed `persistedHistoryCount` from the SAME strip\n * (HOLE D). It is FALSE only when `state.history` was seeded from the approval\n * RunState: there\n * foreign reasoning is NEUTRALIZED-IN-PLACE by {@link resumeRunStateForCodexAccount}\n * (the item is KEPT, only its id/encrypted_content go), so the blob's history\n * length still COUNTS those items. Seeding the watermark with the strip on that\n * path under-counts by K and the reconcile re-appends K already-persisted items at\n * fresh positions — that is HOLE E. The watermark must therefore NOT strip on the\n * blob path (count the raw sanitized active length, matching the blob).\n */\nexport type PreparedTurnInput = {\n input: Awaited<ReturnType<OpenGeniRuntime[\"prepareInput\"]>>;\n modelHistoryFromItems: boolean;\n};\n\nexport type TurnInputOptions = {\n turnId: string;\n recovering?: boolean;\n unavailableSandboxFilesNote?: string;\n};\n\nexport async function turnInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: Awaited<ReturnType<typeof getSessionEvent>>,\n current: TurnCodexAccount = NON_CODEX_TURN,\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 const updateContext = systemUpdateContext(updates);\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 updateContext,\n options.unavailableSandboxFilesNote,\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 attachmentContext = await userMessageAttachmentsContext(\n db,\n trigger.workspaceId,\n Array.isArray(payload.resources) ? (payload.resources as ResourceRef[]) : [],\n );\n return await messageInput(\n db,\n runtime,\n agent,\n trigger,\n undefined,\n joinInternalContext(internalContext, attachmentContext),\n current,\n );\n }\n if (trigger.type === \"system.update.delivered\") {\n if (!internalContext) throw new Error(\"Internal update inference has no delivered updates\");\n return await messageInput(db, runtime, agent, trigger, undefined, internalContext, current);\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 return {\n input: await runtime.prepareInput(agent, {\n kind: \"approval\",\n // Cross-account run-state strip (HOLE C): if the account resuming this\n // frozen approval differs from the one that froze it, neutralize the\n // blob's account-bound reasoning before replay (else byte-for-byte).\n serializedRunState: resumeRunStateForCodexAccount(state, current),\n approvalId: String(payload.approvalId ?? \"\"),\n decision: payload.decision === \"approve\" ? \"approve\" : \"reject\",\n ...(typeof payload.message === \"string\" ? { message: payload.message } : {}),\n }),\n // Model seeded from the run-state BLOB (neutralize-in-place), NOT stripped\n // items: the reconcile watermark must NOT apply the cross-account strip\n // (HOLE E) — else a cross-account approval resume re-appends K\n // already-persisted items at fresh positions.\n modelHistoryFromItems: false,\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\nfunction systemUpdateContext(updates: SessionSystemUpdate[]): string | undefined {\n if (updates.length === 0) return undefined;\n return [\n \"[OpenGeni internal updates]\",\n \"These platform updates were delivered together for this inference. They are not human prompts.\",\n JSON.stringify({\n updates: updates.map((update) => ({\n id: update.id,\n kind: update.kind,\n classification: update.classification,\n sourceId: update.sourceId,\n summary: update.summary,\n payload: update.payload,\n lineage: update.lineage,\n })),\n }),\n ].join(\"\\n\");\n}\n\n/** Build one inference from canonical history plus optional ephemeral system 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 current: TurnCodexAccount = NON_CODEX_TURN,\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 historyItems = applyCodexHistoryStrip(stored, current);\n return {\n input: await runtime.prepareInput(agent, {\n kind: \"message\",\n ...(text ? { text } : {}),\n ...(internalContext ? { internalContext } : {}),\n historyItems: historyItems as any,\n sandboxEnvelope: envelope,\n }),\n modelHistoryFromItems: true,\n };\n}\n\nexport async function userMessageTextWithAttachments(\n db: Database,\n workspaceId: string,\n text: string,\n resources: ResourceRef[],\n): Promise<string> {\n const attachmentContext = await userMessageAttachmentsContext(db, workspaceId, resources);\n return attachmentContext ? [text, \"\", attachmentContext].join(\"\\n\") : text;\n}\n\nasync function userMessageAttachmentsContext(\n db: Database,\n workspaceId: string,\n resources: ResourceRef[],\n): Promise<string | undefined> {\n const attachedFiles: string[] = [];\n for (const resource of resources) {\n if (resource.kind !== \"file\") {\n continue;\n }\n const file = await requireFile(db, workspaceId, resource.fileId);\n attachedFiles.push(\n `- ${file.filename} (${file.contentType}, ${file.sizeBytes} bytes): ${sandboxFilePath(resource, file)}`,\n );\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/${resource.mountPath ?? `files/${file.id}`}/${file.safeFilename}`;\n}\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 \"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","// 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 type { Settings } from \"@opengeni/config\";\nimport {\n acquireLease,\n commitWarmingToWarm,\n failWarmingToCold,\n getSandboxSessionEnvelope,\n markWarmLeaseInstanceLost,\n persistWarmSnapshot,\n readLease,\n recordWarmingSandboxCreated,\n releaseLeaseHolder,\n touchLeaseHolder,\n SandboxLeaseSupersededError,\n type Database,\n type LeaseHolderKind,\n} from \"@opengeni/db\";\nimport {\n establishSandboxSessionFromEnvelope,\n isProviderSandboxNotFoundError,\n SandboxResumeStateUnavailableError,\n serializeEstablishedSandboxEnvelope,\n deletePriorPersistedSnapshot,\n tagModalSandbox,\n type EstablishedSandboxSession,\n type RuntimeMetricsHooks,\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\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 /** 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 (solo holder recreates;\n * N-holders throw SandboxImageConflictError). Omitted -> image is not enforced (the\n * selfhosted path never passes it; a legacy/null-image box 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 (solo holder recreates cold on the new\n * rig; N-holders throw SandboxRigConflictError). Omitted for a rig-less session\n * -> 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 if (established.backendId !== \"modal\") return;\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) {\n throw new Error(\"Modal sandbox session does not expose exec\");\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n run.call(session, {\n cmd: \"true\",\n yieldTimeMs: 1_000,\n maxOutputTokens: 1_000,\n }),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new SandboxWarmingTimeoutError(established.backendId, timeoutMs)),\n timeoutMs,\n );\n if (timer && \"unref\" in timer && typeof timer.unref === \"function\") timer.unref();\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nclass SnapshotTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`workspace snapshot timed out after ${timeoutMs}ms`);\n this.name = \"SnapshotTimeoutError\";\n }\n}\n\nexport async function waitForWarmSnapshot(\n snapshot: Promise<unknown>,\n timeoutMs: number,\n): Promise<boolean> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n snapshot,\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 (error instanceof SnapshotTimeoutError) {\n console.error(\"mid-session workspace snapshot wait timed out (turn unaffected)\", error);\n return false;\n }\n return true;\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\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 {\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 {\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, string> | 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 capturedAt = sessionState?.workspaceArchiveAt;\n return {\n workspaceArchive: archive,\n ...(typeof previous === \"string\" && previous.length > 0\n ? { workspaceArchivePrev: previous }\n : {}),\n ...(typeof capturedAt === \"string\" && capturedAt.length > 0\n ? { workspaceArchiveAt: capturedAt }\n : {}),\n };\n}\n\nfunction preserveWorkspaceArchivesOnResumeState(\n resumeState: Record<string, unknown> | null,\n archiveSource: Record<string, unknown> | null,\n): Record<string, unknown> | null {\n const archiveFields = workspaceArchiveFieldsFromEnvelope(archiveSource);\n if (!archiveFields) {\n return resumeState;\n }\n const existingSessionState =\n resumeState && typeof resumeState.sessionState === \"object\" && resumeState.sessionState !== null\n ? (resumeState.sessionState as Record<string, unknown>)\n : {};\n return {\n ...(resumeState ?? {}),\n ...(resumeState?.backendId === undefined && archiveSource?.backendId !== undefined\n ? { backendId: archiveSource.backendId }\n : {}),\n sessionState: {\n ...existingSessionState,\n ...archiveFields,\n },\n };\n}\n\n/**\n * MID-SESSION /workspace snapshot (sandbox-file-persistence). The reaper's\n * drain-persist only protects boxes the reaper itself kills; anything else —\n * Modal's hard creation-time timeout catching a session busy past it, provider\n * OOM/infra death — loses everything since the last clean drain (staging\n * session e644e8a8, 2026-07-06: mid-turn box termination cost an unpushed\n * branch + 2 commits). While a turn HOLDS the live box, this folds a fresh\n * snapshot onto the lease through persistWarmSnapshot (the warm sibling of the\n * drain seam: epoch-fenced CAS + atomic throttle re-check) and GCs the\n * superseded snapshot image, bounding worst-case loss of ANY unclean box death\n * to sandboxSnapshotIntervalMs.\n *\n * Never throws and never blocks turn progress semantics: every failure path\n * returns false (the snapshot is protection, not a turn dependency). No-ops\n * when the interval is 0, the backend has no persistWorkspace (selfhosted =\n * the user's machine IS the persistence), or a snapshot newer than the\n * interval already rides the lease.\n */\nexport async function maybePersistWarmWorkspaceSnapshot(\n services: SandboxResumeServices,\n ids: { accountId: string; workspaceId: string; sandboxGroupId: string },\n session: unknown,\n leaseEpoch: number,\n): Promise<boolean> {\n const { db, settings } = services;\n const intervalMs = settings.sandboxSnapshotIntervalMs;\n if (intervalMs <= 0) {\n return false;\n }\n const persistable = session as {\n persistWorkspace?: () => Promise<Uint8Array | undefined>;\n };\n if (typeof persistable.persistWorkspace !== \"function\") {\n return false;\n }\n try {\n // Cheap throttle pre-check before the (potentially slow) capture;\n // persistWarmSnapshot re-checks atomically under the row lock, so this is\n // purely a cost optimization, not the correctness guard.\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (!lease || lease.leaseEpoch !== leaseEpoch || lease.liveness !== \"warm\") {\n return false;\n }\n const sessionState =\n lease.resumeState && typeof lease.resumeState === \"object\"\n ? (lease.resumeState as { sessionState?: Record<string, unknown> }).sessionState\n : undefined;\n const priorAtRaw =\n sessionState && typeof sessionState === \"object\"\n ? sessionState.workspaceArchiveAt\n : undefined;\n const priorAtMs = typeof priorAtRaw === \"string\" ? Date.parse(priorAtRaw) : Number.NaN;\n if (Number.isFinite(priorAtMs) && Date.now() - priorAtMs < intervalMs) {\n 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 // On timeout the race settles on `undefined` while persistWorkspace() keeps\n // running orphaned. Swallow its LATE settlement: an un-awaited rejection\n // after the race resolved would surface as an unhandledRejection and can\n // take down the whole worker process — which would defeat the very hang-\n // guard this timeout exists to provide.\n const capture = persistable.persistWorkspace();\n capture.catch(() => undefined);\n const bytes = await Promise.race([\n capture,\n new Promise<undefined>((resolve) => {\n timeout = setTimeout(() => resolve(undefined), settings.sandboxSnapshotTimeoutMs);\n if (timeout && \"unref\" in timeout && typeof timeout.unref === \"function\") {\n timeout.unref();\n }\n }),\n ]).finally(() => {\n if (timeout) {\n clearTimeout(timeout);\n }\n });\n if (!bytes || bytes.length === 0) {\n return false;\n }\n const { wrote, priorArchiveForGc } = await persistWarmSnapshot(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n workspaceArchive: Buffer.from(bytes).toString(\"base64\"),\n minIntervalMs: intervalMs,\n capturedAtMs,\n });\n if (!wrote) {\n return false;\n }\n // Warm snapshots retain a 2-deep restore window. Only the two-ago archive\n // returned by persistWarmSnapshot is GC-eligible.\n await deletePriorPersistedSnapshot(persistable, priorArchiveForGc);\n return true;\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(\"mid-session workspace snapshot failed (turn unaffected)\", error);\n return false;\n }\n}\n\n/**\n * Resume the one box for a single turn (or any worker-side resume op). Returns\n * the live non-owned session + the fence epoch + a release fn. The CALLER owns\n * the lifecycle: inject non-owned, run, then `await release()` and drop the\n * handle in `finally`.\n *\n * holderId is the globally unique durable turn-attempt id. It must not be a\n * Temporal activity id, because activity ids are only workflow-local and\n * collide when sibling sessions share one sandbox group.\n */\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\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 let released = false;\n let holderLivenessTimer: ReturnType<typeof setInterval> | undefined;\n const release = async (): Promise<void> => {\n if (released) {\n return;\n }\n released = true;\n if (holderLivenessTimer) {\n clearInterval(holderLivenessTimer);\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\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 SandboxImageConflictError\n // propagates to the turn activity (an actionable error); a solo image change is handled\n // by acquireLease recreating the box cold on 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 to the turn activity (actionable); a solo rig change recreates cold.\n ...(ids.rigVersionId ? { rigVersionId: ids.rigVersionId } : {}),\n leaseTtlMs,\n warmingLeaseTtlMs: settings.sandboxWarmingTimeoutMs,\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 }).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 === \"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 try {\n const envelope = await getSandboxSessionEnvelope(db, ids.workspaceId, ids.sessionId);\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 spawnEnvelope = acquired.lease.resumeState ?? envelope;\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 const resumeEnvelope = preserveWorkspaceArchivesOnResumeState(\n (await serializeEstablishedSandboxEnvelope(created)) ?? null,\n spawnEnvelope,\n );\n const recorded = await recordWarmingSandboxCreated(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n instanceId: created.instanceId,\n resumeBackendId: created.backendId,\n resumeState: resumeEnvelope,\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 },\n });\n createdEstablished = established;\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 // 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. Fall back to the session envelope only\n // when the client cannot serialize live state.\n const serializedResumeEnvelope =\n (await serializeEstablishedSandboxEnvelope(established)) ?? envelope;\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 retire the lease with no archive and recreate an empty box.\n // A failed hydrate falls back to a clean box with origin=\"created\", so its\n // unusable archive is deliberately cleared by the unmerged serialized state.\n const resumeEnvelope =\n established.origin === \"restored\"\n ? preserveWorkspaceArchivesOnResumeState(serializedResumeEnvelope, spawnEnvelope)\n : serializedResumeEnvelope;\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 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 await terminateEstablishedSandbox(established);\n await release();\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\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 await failWarmingToCold(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\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\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 established = await establishSandboxSessionFromEnvelope(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 } catch (error) {\n if (\n !(error instanceof SandboxResumeStateUnavailableError) &&\n !isProviderSandboxNotFoundError(ids.backend, error)\n ) {\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 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 * Stage D machine-primary: acquire the group lease for a turn whose ACTIVE sandbox\n * is a connected machine (selfhosted) WITHOUT establishing a provider box. The\n * \"box\" is the user's physical machine reached over NATS; there is NOTHING to\n * spawn, snapshot, expose, or serialize — so we take the lease (the SAME group-keyed\n * refcount/idle/epoch bookkeeping resumeBoxForTurn uses) but skip every box step.\n *\n * The lease is keyed backend \"selfhosted\": the reaper's terminateProviderBox\n * short-circuits a selfhosted lease (it is the user's machine — NEVER provider-stop),\n * draining it to cold with no stop; and the reaper's warm-meter rate for \"selfhosted\"\n * is 0 (no cloud seconds billed for a box that does not exist). Returns the lease\n * epoch + an idempotent release so the turn's lease-heartbeat + `finally` release are\n * identical to the cloud path.\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 acquireSelfhostedLeaseForTurn(\n services: SandboxResumeServices,\n ids: {\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n sessionId: string;\n },\n kind: \"turn\",\n holderId: TurnSandboxLeaseHolderId,\n): Promise<{ leaseEpoch: number; release: () => Promise<void> }> {\n const { db, settings } = services;\n const leaseTtlMs = settings.sandboxLeaseTtlMs;\n\n let released = false;\n const release = async (): Promise<void> => {\n if (released) {\n return;\n }\n released = true;\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\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: \"selfhosted\",\n os: \"linux\",\n leaseTtlMs,\n warmingLeaseTtlMs: settings.sandboxWarmingTimeoutMs,\n });\n\n // FENCED: a newer epoch re-established the group concurrently. Release our\n // just-registered holder + surface the supersession (the outer turn catch\n // requeues, mirroring resumeBoxForTurn).\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. There is NO box to establish — commit\n // warm immediately so the lease does not linger in 'warming' (no box id, no\n // resume_state; selfhosted is re-addressed by enrollment via the active pointer,\n // never resumed from an envelope). resume_backend_id \"selfhosted\" keeps the\n // reaper's never-provider-stop short-circuit correct.\n if (acquired.role === \"spawner\") {\n const expectedEpoch = acquired.lease.leaseEpoch;\n const committed = await commitWarmingToWarm(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n // No provider box id; stamp a clearly non-box marker for diagnostics.\n instanceId: `selfhosted:${ids.sessionId}`,\n resumeBackendId: \"selfhosted\",\n resumeState: null,\n leaseTtlMs,\n });\n if (!committed.committed || !committed.lease) {\n // A reaper reset our warming row, or a sibling re-established + bumped the\n // epoch. Release our holder; surface supersession (NEVER touch any box).\n await release();\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n return { leaseEpoch: committed.lease.leaseEpoch, release };\n }\n\n // ATTACHED / REARMED: the lease is live. There is no box to resume — just carry\n // the lease epoch (same-session turns are serialized, so a concurrent 'warming'\n // spawner on this group is not expected; the machine session is independent of the\n // lease state regardless).\n return { leaseEpoch: acquired.lease.leaseEpoch, release };\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 // 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 (dossier §10.3): 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 type { Settings } from \"@opengeni/config\";\nimport { getSandbox, readActiveSandbox, type Database } from \"@opengeni/db\";\nimport type { EventBus } from \"@opengeni/events\";\nimport {\n buildSelfhostedBackendSession,\n makeActiveBackendResolver,\n NatsControlRpc,\n NatsOpStreamTransport,\n RoutingSandboxSession,\n type ControlRpc,\n type EstablishedSandboxSession,\n type NatsRequestConnection,\n type RoutableBackendSession,\n type RoutableSandbox,\n type SelfhostedOpObserver,\n type SelfhostedRelayConfig,\n type OpStreamJournal,\n type SelfhostedOpStreamDeps,\n} from \"@opengeni/runtime\";\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 /** 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};\n\nexport type RoutingWiringIds = {\n workspaceId: string;\n sessionId: string;\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 { selfhostedTimeoutMs: timeoutMs, selfhostedExecTimeoutMs: execTimeoutMs };\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 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 });\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 },\n readPointer: async () => {\n const pointer = await readActiveSandbox(db, ids.workspaceId, ids.sessionId);\n return pointer ?? { activeSandboxId: null, activeEpoch: 0 };\n },\n resolveActiveBackend: resolver,\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: { get(): Promise<{ established: EstablishedSandboxSession }> };\n },\n): EstablishedSandboxSession {\n const { db, settings, bus, onOp } = services;\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 return {\n session: provisioned.established.session as RoutableBackendSession,\n sandboxId: null,\n kind: provisioned.established.backendId,\n };\n }\n return routedResolver(pointer);\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 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 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>>();\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 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 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 if (!(inputTokens > 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: inputTokens,\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_hit_ratio{provider}` — cached/prompt for the call,\n * observed whenever prompt tokens are known (>0). A call whose provider does NOT\n * report cached_tokens records a real 0 here — \"we saw a call and the cache did\n * nothing\" is exactly the signal the alert watches, so it must not be swallowed.\n * Absent/zero/non-finite `cachedTokens` (providers that don't report it) is safe: no\n * counter increment, ratio 0. A call with no prompt tokens has no ratio (skipped).\n */\nexport function recordModelCacheTokens(\n observability: Observability,\n provider: string,\n input: { cachedTokens: number | null | undefined; promptTokens: number | null | undefined },\n): void {\n const cached = nonNegativeTokenCount(input.cachedTokens);\n const prompt = nonNegativeTokenCount(input.promptTokens);\n if (cached > 0) {\n observability.incrementCounter({\n name: \"opengeni_model_cached_tokens_total\",\n help: \"Total prompt tokens served from the provider's prompt cache, by provider.\",\n labels: { provider },\n amount: cached,\n });\n }\n if (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 nonNegativeTokenCount(value: number | null | undefined): number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : 0;\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 (dossier §10.1).\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 dossier §7.3 / §19):\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 (60s) 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 lease epoch — a superseded lease writes zero\n// rows (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 (dossier \"Accepted warts\" #2 — 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, randomUUID } 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 (dossier §7.3).\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 (dossier §10.1 — pathological-only; configurable) ─────\nexport const CAPTURE_TIMEOUT_MS = 60_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_DIRS = 600; // BFS round-trip cap (bounds turn-end latency)\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 leaseEpoch: number;\n sandboxGroupId: string;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string | null;\n observability: Observability;\n /** Test-only: override keep-latest-N GC threshold (default 10). */\n keepLatest?: number;\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 60s 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 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 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 ).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 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 // 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 });\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"failed\" },\n });\n } finally {\n if (timer) clearTimeout(timer);\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): Promise<void> {\n const { observability } = input;\n const storage = ctx.objectStorage;\n const keepN = input.keepLatest ?? KEEP_LATEST_REVISIONS;\n // Reads only — no emitter (we publish the announce ourselves after commit).\n const svc = new SandboxChannelAService({ session: input.session, 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 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 const discovery = await svc.detectReposDetailed();\n throwIfCaptureAborted(signal);\n if (!discovery.complete) {\n const capturedAt = new Date();\n const reason = captureDegradedReason(discovery.degradedReason);\n const stats = {\n degradedReason: reason,\n discoveredRepoCount: discovery.repos.length,\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 sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: input.leaseEpoch,\n revision,\n stats,\n capturedAt,\n });\n throwIfCaptureAborted(signal);\n if (!inserted) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"superseded\" },\n });\n return;\n }\n observability.warn(\"workspace capture degraded — repository discovery incomplete\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": input.turnId ?? \"\",\n \"workspace_capture.degraded_reason\": reason,\n \"workspace_capture.discovered_repo_count\": discovery.repos.length,\n });\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"degraded_repository_discovery\" },\n });\n if (input.publish) {\n await input.publish(inserted.events).catch(() => undefined);\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 throwIfCaptureAborted(signal);\n // Per-repo resilience: a box death aborts the whole capture (BoxExitingError\n // propagates); any other single-repo failure (a repo that vanished, a\n // transient git error) SKIPS that repo and the capture continues with the\n // rest. One flaky repo must never kill the capture.\n let status: Awaited<ReturnType<typeof svc.gitStatus>>;\n try {\n status = await svc.gitStatus({ path: root });\n throwIfCaptureAborted(signal);\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n continue;\n }\n if (!status.isRepo) continue;\n // `git diff HEAD`: combined staged+unstaged tracked changes vs HEAD (the\n // review diff). Untracked files are absent here but present in status.files\n // and captured as after-images. A repo with no commits yields an empty diff\n // (git diff HEAD errors → empty numstat) and everything reads as untracked.\n let diff: Awaited<ReturnType<typeof svc.gitDiff>>;\n try {\n diff = await svc.gitDiff({\n path: root,\n staged: false,\n fromRef: \"HEAD\",\n pathspec: [],\n contextLines: 3,\n maxBytesPerFile: PER_FILE_DIFF_GUARD_BYTES,\n });\n throwIfCaptureAborted(signal);\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n diff = { files: [], revision: 0 };\n }\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. (Deviation from the dossier's literal \"clean\"\n // wording — same intent, strictly better; recorded in PROGRESS.)\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 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 (dossier §10.1 / 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 (bounded BFS; residue dirs collapsed, not descended) ─────\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 ?? randomUUID();\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 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 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 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 const inserted = await insertWorkspaceCapture(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\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 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\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 via bounded BFS over the PUBLIC fsList (depth 1\n * per directory). Residue dirs are emitted as collapsed nodes but never queued\n * for descent — a single deep fsList would let node_modules exhaust the entry\n * budget and truncate real files, so we prune at the source. Bounded by\n * TREE_MAX_ENTRIES, TREE_MAX_DIRS round-trips, and the outer capture deadline.\n */\nasync function buildTreeIndex(\n svc: SandboxChannelAService,\n startedAt: number,\n signal: AbortSignal,\n): Promise<{ root: FsTreeNode; entryCount: number; truncated: boolean }> {\n const root: FsTreeNode = {\n name: \"\",\n path: \"\",\n type: \"dir\",\n sizeBytes: null,\n mtimeMs: null,\n mode: null,\n children: [],\n truncated: false,\n };\n const byPath = new Map<string, FsTreeNode>([[\"\", root]]);\n const queue: string[] = [\"\"];\n let entryCount = 0;\n let dirCalls = 0;\n let truncated = false;\n\n while (queue.length > 0) {\n throwIfCaptureAborted(signal);\n if (dirCalls >= TREE_MAX_DIRS || entryCount >= TREE_MAX_ENTRIES) {\n truncated = true;\n break;\n }\n if (Date.now() - startedAt > CAPTURE_TIMEOUT_MS - 5_000) {\n truncated = true;\n break;\n } // leave headroom for PUTs\n const dir = queue.shift()!;\n dirCalls += 1;\n // Per-dir resilience: a directory can vanish or fail to list mid-walk (fs\n // churn on a desktop box, a permission edge). Skip the one directory and keep\n // walking the rest — a single unreadable dir must never abort the tree index.\n // A box death still aborts the whole capture (BoxExitingError).\n let listing: Awaited<ReturnType<typeof svc.fsList>>;\n try {\n listing = await svc.fsList({ path: dir, depth: 1, maxEntries: 2_000, includeHidden: true });\n throwIfCaptureAborted(signal);\n } catch (error) {\n if (isBoxExitingError(error)) {\n throw new BoxExitingError(error instanceof Error ? error.message : String(error));\n }\n truncated = true; // this subtree is incomplete; continue with the rest\n continue;\n }\n if (listing.truncated) truncated = true;\n const parent = byPath.get(dir) ?? root;\n const children = collectImmediateChildren(listing.root);\n for (const child of children) {\n if (entryCount >= TREE_MAX_ENTRIES) {\n truncated = true;\n break;\n }\n const node: FsTreeNode = {\n name: child.name,\n path: child.path,\n type: child.type,\n sizeBytes: child.sizeBytes,\n mtimeMs: child.mtimeMs,\n mode: child.mode,\n truncated: false,\n ...(child.type === \"dir\" ? { children: [] as FsTreeNode[] } : {}),\n };\n (parent.children ??= []).push(node);\n byPath.set(node.path, node);\n entryCount += 1;\n if (node.type === \"dir\") {\n if (RESIDUE_DIR_SET.has(node.name)) {\n node.truncated = true; // collapsed residue dir — contents on the machine\n } else {\n queue.push(node.path);\n }\n }\n }\n }\n return { root, entryCount, truncated };\n}\n\n/** fsList returns a subtree; at depth 1 the immediate children hang off root. */\nfunction collectImmediateChildren(node: FsTreeNode): FsTreeNode[] {\n return node.children ?? [];\n}\n","import { indexDocumentNow } from \"@opengeni/documents\";\nimport { configuredStaticUsageLimits } from \"@opengeni/config\";\nimport {\n getBillingBalance,\n recordUsageEvent,\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 return await withWorkspaceUsageLock(db, input.workspaceId, async (lockedDb) => {\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 );\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 { claimExpiredFileUploadCleanup, completeExpiredFileUploadCleanup } 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;\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};\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\n async function reapExpiredFileUploads(): Promise<ReapExpiredFileUploadsResult> {\n const { db, objectStorage, observability } = await services();\n if (!objectStorage) {\n return { claimed: 0, deleted: 0, failed: 0 };\n }\n\n const claims = await claimExpiredFileUploadCleanup(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 completeExpiredFileUploadCleanup(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 error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (claims.length > 0) {\n observability.info(\"expired file upload cleanup swept\", {\n claimed: claims.length,\n deleted,\n failed,\n });\n }\n return { claimed: claims.length, 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 {\n accrueWarmSeconds,\n confirmDrainCold,\n appendSessionEventToSandboxGroup,\n countQueuedTurns,\n countSandboxLeasesByLiveness,\n forceDrainOverLimitViewerOnlyBoxes,\n getBillingBalance,\n listCreditBalancesByAccount,\n listLiveModalSandboxLeaseAttributions,\n listMeterableWarmLeases,\n persistDrainSnapshot,\n readLease,\n reapExpiredSessionListSnapshots,\n reapStaleLeaseHoldersGlobal,\n rlsContextForWorkspace,\n type MeterableWarmLease,\n type ReapDrainable,\n} from \"@opengeni/db\";\nimport { sandboxWarmRateMicrosPerSecond } from \"@opengeni/config\";\nimport {\n // The reaper attaches to the box by id to terminate it. It does NOT use\n // establishSandboxSessionFromEnvelope (which cold-RESTORES via create() on a\n // NotFound) — restoring a box just to immediately kill it is wrong. Instead it\n // builds the client + resumes the envelope DIRECTLY: a live box resumes, gets\n // its /workspace PERSISTED (snapshot/tar), then is terminated; a gone box\n // (NotFound on resume) is already down, a clean no-op.\n createSandboxClientForBackend,\n deletePriorPersistedSnapshot,\n deserializeSandboxSessionStateEnvelope,\n isProviderSandboxNotFoundError,\n sweepModalOrphanSandboxes,\n terminateModalSandboxById,\n} from \"@opengeni/runtime\";\nimport type { ActivityServices } from \"./types\";\nimport { reconcilePendingParentSystemUpdates } from \"./parent-wake\";\nimport {\n recordCreditBalanceGauges,\n recordCreditMicros,\n recordSandboxLeaseGauges,\n recordSandboxOrphansTerminated,\n recordTurnsQueuedGauge,\n} from \"../observability-metrics\";\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 -> the CAS missed (re-armed / newer epoch / vanished). The box\n * is wanted again; the seam MUST NOT terminate it.\n * - priorArchive / priorArchivePrev -> superseded archives to GC at drain.\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()). priorArchive values are always\n * null in this case.\n */\nexport type PersistArchiveFn = (\n archiveBase64: string | null,\n) => Promise<{ wrote: boolean; priorArchive: string | null; priorArchivePrev: string | null }>;\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 * Returns true when the box was terminated (or already gone), false when persist\n * found the lease re-armed and the box was deliberately LEFT RUNNING. */\nexport type TerminateBoxFn = (\n settings: ActivityServices[\"settings\"],\n lease: NonNullable<Awaited<ReturnType<typeof readLease>>>,\n observability: ActivityServices[\"observability\"],\n persistArchive: PersistArchiveFn,\n) => Promise<boolean>;\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};\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 /**\n * The one global reaper sweep. Idempotent; concurrency-safe with itself.\n * Gated by the caller (the Schedule is only registered when\n * sandboxOwnershipEnabled); a defensive no-op here too so a manual trigger\n * with the flag off 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 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 await refreshQueueLeaseAndCreditGauges(db, observability);\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 forceDrained = await forceDrainOverLimitWorkspaces(\n db,\n settings,\n metered.workspaceIds,\n observability,\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 );\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 await refreshQueueLeaseAndCreditGauges(db, observability);\n\n if (\n drainable.length > 0 ||\n metered.accrued > 0 ||\n forceDrained > 0 ||\n modalOrphansTerminated > 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 });\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\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 try {\n recordSandboxLeaseGauges(observability, await countSandboxLeasesByLiveness(db));\n } catch (error) {\n observability.warn(\"sandbox reaper: sandbox-lease gauge refresh failed\", {\n error: error instanceof Error ? error.message : String(error),\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\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 // Nothing to enforce → skip the whole pass (no lock churn).\n if (!enforceBalance && cap <= 0) {\n return 0;\n }\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\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 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 * 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): 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 // 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 const persistArchive: PersistArchiveFn = async (archiveBase64: string | null) => {\n const result = await persistDrainSnapshot(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n expectedEpoch: row.leaseEpoch,\n workspaceArchive: archiveBase64,\n });\n if (result.wrote && archiveBase64 !== null) {\n persisted = true;\n }\n return result;\n };\n\n // Resume-by-id -> persistWorkspace -> persist-onto-lease -> GC prior snapshot ->\n // provider terminate. A box that is already gone (NotFound) is success (the goal\n // is \"box is not running\"). A genuine PERSIST failure (could not snapshot) or a\n // resume failure on a box that IS alive re-throws -> the lease stays draining for\n // the next sweep (NEVER terminate a box whose files we could not capture). A\n // persist CAS-miss (re-armed) returns false -> the box was left running; skip the\n // cold-commit so the re-armed box is not cold-leaked.\n const terminated = await terminateBox(settings, lease, observability, persistArchive);\n if (!terminated) {\n return false;\n }\n\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 });\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: { actor: \"reaper\", persisted, instanceId: lease.instanceId },\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}\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. modal carries the Modal SDK client used\n// for snapshot-image GC (deletePriorPersistedSnapshot reads session.modal).\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, GC the superseded snapshot, THEN terminate. Resumes\n * DIRECTLY (no cold-restore fallback) so a gone box is a clean no-op, never a\n * 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 (epoch-fenced);\n * - GC the PRIOR snapshot (keep-latest-per-lease);\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<boolean> {\n const backend = (lease.resumeBackendId ?? lease.backend) as string;\n // 'none' / no backend -> nothing to terminate.\n if (!backend || backend === \"none\") {\n return true;\n }\n\n // CRITICAL SAFETY (bring-your-own-compute, dossier §19/§21): 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 true;\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 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 return true;\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 true;\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 true;\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 backend that cannot resume cannot be attached-to for terminate; the\n // provider idle-timeout is the backstop. No-op.\n return true;\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 return true;\n }\n session = (await client.resume(resumedState)) as PersistableSession;\n sessionState = resumedState;\n } catch (error) {\n if (isProviderSandboxNotFoundError(client.backendId, error)) {\n observability.info(\n \"sandbox reaper: drainable box already gone (NotFound on resume) — proceeding to cold\",\n {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n },\n );\n return 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 archiveBytes: Uint8Array | undefined;\n try {\n archiveBytes = session?.persistWorkspace ? await session.persistWorkspace() : undefined;\n } catch (error) {\n if (isProviderSandboxNotFoundError(client.backendId, error)) {\n observability.info(\n \"sandbox reaper: box gone during persist (NotFound) — nothing to snapshot, proceeding to cold\",\n {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n },\n );\n return 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 (archiveBytes && archiveBytes.length > 0) {\n const archiveBase64 = Buffer.from(archiveBytes).toString(\"base64\");\n const { wrote, priorArchive, priorArchivePrev } = await persistArchive(archiveBase64);\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 false;\n }\n // Keep-latest-per-lease GC: best-effort delete the prior snapshot image now,\n // while the session (and its Modal client) is still live. Never throws.\n const deleted = await deletePriorPersistedSnapshot(session, priorArchive);\n if (deleted) {\n observability.info(\"sandbox reaper: GC'd superseded workspace snapshot\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n snapshotId: deleted,\n });\n }\n const deletedPrev = await deletePriorPersistedSnapshot(session, priorArchivePrev);\n if (deletedPrev) {\n observability.info(\"sandbox reaper: GC'd superseded previous workspace snapshot\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n snapshotId: deletedPrev,\n });\n }\n } else {\n // No archive produced (backend has no persistWorkspace or returned empty).\n // CAS-check via persistArchive(null): if the lease was re-armed during the\n // snapshot window, wrote:false → leave the box RUNNING (abort terminate).\n const { wrote } = await persistArchive(null);\n if (!wrote) {\n observability.info(\n \"sandbox reaper: lease re-armed during snapshot window (no-archive path) — leaving box RUNNING (no terminate)\",\n {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n },\n );\n return false;\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 true;\n }\n if (session?.kill) {\n await session.kill();\n return true;\n }\n if (session?.terminate) {\n await session.terminate();\n return true;\n }\n if (session?.close && !session.closed) {\n await session.close();\n }\n } catch (error) {\n observability.warn(\"sandbox reaper: provider terminate raised (box may already be gone)\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return true;\n}\n","import {\n appendSessionEventsWithLockedSessionUpdate,\n addSessionSystemUpdateWithSourceMutation,\n createScheduledTaskRun,\n createSession,\n createSessionGoal,\n enqueueSessionWorkflowWakeIfRunnable,\n getBillingBalance,\n getRig,\n getVariableSet,\n isCodexBilledTurn,\n markScheduledTaskRunFailedIfQueued,\n recordUsageEvent,\n requireScheduledTask,\n requireSession,\n setTemporalWorkflowId,\n settleScheduledTaskRunInTransaction,\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 const task = await requireScheduledTask(db, input.workspaceId, input.taskId);\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 await ensureScheduledRunAllowed(\n settings,\n db,\n task.accountId,\n task.workspaceId,\n input.agentRunUsageIdempotencyKey ? 0 : 1,\n isCodexRun,\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 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 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 (set_session_title,\n // goal tools, and the permission-gated tools), matching the API path.\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 const 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 ...task.agentConfig.metadata,\n model,\n reasoningEffort,\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 });\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 scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n // Names/ids only; never values.\n ...(variableSet\n ? { variableSetId: variableSet.id, variableSetName: variableSet.name }\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 },\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 // 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 },\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 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 ensureScheduledRunAllowed(\n settings: Settings,\n db: ActivityServices[\"db\"],\n accountId: string,\n workspaceId: string,\n requestedAgentRuns: number,\n isCodexRun: boolean,\n): Promise<void> {\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 throw new Error(\"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 throw new Error(\n `monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`,\n );\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 throw new Error(\n `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`,\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","import {\n settleSessionAttemptInterruptions,\n applySessionTurnSettlement,\n recoverSessionDispatch,\n peekSessionWork as peekSessionWorkDb,\n countQueuedTurns,\n getSessionEvent,\n getSessionTurnForAttempt,\n requireSession,\n settleSessionIdleWithParentOutbox,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport { notifyParentOfChildTerminal } from \"./parent-wake\";\nimport { recordTurnsQueuedGauge } from \"../observability-metrics\";\nimport type {\n ActivityServices,\n PeekSessionWorkInput,\n FailSessionAttemptInput,\n SettleSessionInterruptionsInput,\n MarkSessionIdleInput,\n RecoverDispatchInput,\n RecoverDispatchResult,\n} from \"./types\";\n\nexport type SessionStateActivityOverrides = Partial<{\n settleSessionAttemptInterruptions: typeof settleSessionAttemptInterruptions;\n applySessionTurnSettlement: typeof applySessionTurnSettlement;\n recoverSessionDispatch: typeof recoverSessionDispatch;\n peekSessionWork: typeof peekSessionWorkDb;\n countQueuedTurns: typeof countQueuedTurns;\n getSessionEvent: typeof getSessionEvent;\n getSessionTurnForAttempt: typeof getSessionTurnForAttempt;\n requireSession: typeof requireSession;\n settleSessionIdleWithParentOutbox: typeof settleSessionIdleWithParentOutbox;\n publishDurableSessionEvents: typeof publishDurableSessionEvents;\n notifyParentOfChildTerminal: typeof notifyParentOfChildTerminal;\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 recoverSessionDispatchFn = overrides.recoverSessionDispatch ?? recoverSessionDispatch;\n const peekSessionWorkFn = overrides.peekSessionWork ?? peekSessionWorkDb;\n const countQueuedTurnsFn = overrides.countQueuedTurns ?? countQueuedTurns;\n const getSessionEventFn = overrides.getSessionEvent ?? getSessionEvent;\n const getSessionTurnForAttemptFn = overrides.getSessionTurnForAttempt ?? getSessionTurnForAttempt;\n const requireSessionFn = overrides.requireSession ?? requireSession;\n const settleSessionIdleWithParentOutboxFn =\n overrides.settleSessionIdleWithParentOutbox ?? settleSessionIdleWithParentOutbox;\n const publishDurableSessionEventsFn =\n overrides.publishDurableSessionEvents ?? publishDurableSessionEvents;\n const notifyParentOfChildTerminalFn =\n overrides.notifyParentOfChildTerminal ?? notifyParentOfChildTerminal;\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 notifyParentOfChildTerminalFn(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n \"failed\",\n `turn:${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 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 /**\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 notifyParentOfChildTerminalFn(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n \"failed\",\n `turn:${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 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 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 notifyParentOfChildTerminalFn(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n \"idle\",\n settled.episodeKey,\n );\n }\n\n return {\n failSessionAttempt,\n settleSessionInterruptions,\n recoverDispatch,\n peekSessionWork,\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 {\n recordRigAuditEvent,\n classifyRigVerificationOutcome,\n promoteSetupAppendChange,\n} from \"@opengeni/core\";\nimport {\n beginRigChangeVerificationAttempt,\n getRig,\n getRigChange,\n getRigVersionById,\n sanitizeEventPayload,\n sanitizeEventString,\n sanitizeMemoryText,\n updateRigChangeStatus,\n type Database,\n} from \"@opengeni/db\";\nimport {\n establishSandboxSessionFromEnvelope,\n runRigSetupHook,\n sandboxCommandExitCode,\n sandboxCommandOutput,\n type EstablishedSandboxSession,\n} from \"@opengeni/runtime\";\nimport type { ActivityServices } from \"./types\";\nimport { settingsWithRigImage } from \"./packs\";\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\ntype CommandSession = {\n exec?: (args: Record<string, unknown>) => Promise<unknown>;\n execCommand?: (args: Record<string, unknown>) => Promise<unknown>;\n};\n\nconst OUTPUT_TAIL_LIMIT = 64 * 1024;\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<void> {\n if (!established) {\n return;\n }\n const client = established.client as { delete?: (state: unknown) => Promise<unknown> };\n if (typeof client.delete === \"function\" && established.sessionState !== undefined) {\n await client.delete(established.sessionState).catch(() => undefined);\n return;\n }\n const session = established.session as {\n terminate?: () => Promise<unknown>;\n kill?: () => Promise<unknown>;\n close?: () => Promise<unknown>;\n closed?: boolean;\n };\n if (session.terminate) {\n await session.terminate().catch(() => undefined);\n } else if (session.kill) {\n await session.kill().catch(() => undefined);\n } else if (session.close && !session.closed) {\n await session.close().catch(() => undefined);\n }\n}\n\nasync function runCommand(\n session: CommandSession,\n command: string,\n timeoutMs: number,\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 = session.exec\n ? await session.exec(args)\n : session.execCommand\n ? await session.execCommand(args)\n : (() => {\n throw new Error(\"Sandbox session does not support command execution\");\n })();\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\nexport function createRigVerificationActivities(services: () => Promise<ActivityServices>) {\n return {\n verifyRigChange: async (input: { workspaceId: string; changeId: string }) => {\n const { settings, db } = await services();\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 let established: EstablishedSandboxSession | null = null;\n const verification: Record<string, unknown> = { startedAt, checkResults: [] };\n try {\n const candidateVersion = candidateVersionForChange(baseVersion, change);\n const runSettings = settingsWithRigImage(settings, candidateVersion.image);\n established = await establishSandboxSessionFromEnvelope(runSettings, null, {\n sessionId: `rig-verification-${change.id}`,\n recovery: \"create-or-restore\",\n environment: {},\n });\n if ((candidateVersion.setupScript ?? \"\").trim()) {\n await runRigSetupHook(established.session as never, {\n environment: {},\n runAs: \"root\",\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 CommandSession,\n command,\n settings.rigSetupTimeoutMs,\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 CommandSession,\n check.command,\n settings.rigSetupTimeoutMs,\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 } 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 return updated;\n } finally {\n await terminateThrowaway(established);\n }\n },\n\n verifyRigVersion: async (input: { workspaceId: string; versionId: string }) => {\n const { settings, db } = await services();\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 let established: EstablishedSandboxSession | null = null;\n try {\n const runSettings = settingsWithRigImage(settings, version.image);\n established = await establishSandboxSessionFromEnvelope(runSettings, null, {\n sessionId: `rig-version-verification-${version.id}`,\n recovery: \"create-or-restore\",\n environment: {},\n });\n if ((version.setupScript ?? \"\").trim()) {\n await runRigSetupHook(established.session as never, {\n environment: {},\n runAs: \"root\",\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 CommandSession,\n check.command,\n settings.rigSetupTimeoutMs,\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 } 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 } finally {\n await terminateThrowaway(established);\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 | \"dispatchScheduledTaskRun\"\n | \"enqueueGoalRetryWake\"\n | \"failSessionAttempt\"\n | \"getCodexCapacityWait\"\n | \"markSessionIdle\"\n | \"peekSessionWork\"\n | \"reconcileCodexCapacityWait\"\n | \"recoverDispatch\"\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/** Goal continuation is advisory at an idle boundary. A transient failure gets\n * a short retry window, then records an explicit delayed outbox wake instead\n * of relying on an unrelated future mutation. */\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) {\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 may complete the durable control transition immediately,\n // but the session workflow must remain open until the old turn activity is\n // physically gone. Leaving this implicit uses Temporal's try-cancel wire\n // default: the activity promise rejects as soon as cancellation is\n // requested and the workflow can close while the worker keeps streaming.\n cancellationType: 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 { dbSql, type Database } 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 checks: Record<ReadinessCheckName, { ok: boolean; error?: string }>;\n};\n\nexport function startWorkerHttpServer(input: {\n settings: Settings;\n observability: Observability;\n checks: ReadinessChecks;\n timeoutMs?: number;\n}): ReturnType<typeof Bun.serve> {\n const { settings, observability, checks } = input;\n const timeoutMs = input.timeoutMs ?? 2_000;\n return Bun.serve({\n hostname: \"0.0.0.0\",\n port: settings.workerHttpPort,\n async fetch(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 return Response.json({\n service: settings.serviceName,\n environment: settings.environment,\n deploymentRevision: settings.deploymentRevision,\n ok: true,\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 result = await runReadinessChecks(checks, timeoutMs);\n return Response.json(result, { status: result.ok ? 200 : 503 });\n }\n return Response.json({ error: \"not_found\" }, { status: 404 });\n },\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(db: Database): () => Promise<void> {\n return async () => {\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\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","/**\n * Process-local Temporal execution ceilings.\n *\n * Turn workers host only runAgentTurn, so this is the exact number of agent\n * turns one worker process may own concurrently. Keep the value centralized so\n * production and the real Temporal integration harness exercise one topology.\n */\nexport const TURN_WORKER_MAX_CONCURRENT_TURNS = 16;\n\nexport const CONTROL_WORKER_MAX_CONCURRENT_ACTIVITIES = 32;\nexport const CONTROL_WORKER_MAX_CONCURRENT_WORKFLOW_TASKS = 40;\n"],"mappings":";AAAA;AAAA,EACE,gBAAAA;AAAA,EACA,eAAAC;AAAA,EACA,+BAAAC;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,YAAAC,WAAU,wCAAuD;AAC1E,SAAS,sBAAAC,2BAA0B;AACnC;AAAA,EACE,uBAAAC;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,UAAU;AAAA,OACL;AACP,SAAS,kBAAkB,cAAc;AACzC,SAAS,4BAAAC,iCAAgC;;;ACtBzC,SAAS,cAAc,aAAa,mCAAmC;AACvE,SAAS,gBAAgB;AACzB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,oCAAoC;AAC7C,SAAS,uBAAAC,4BAA2B;;;ACNpC;AAAA,EACE;AAAA,EACA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C,KAAK,MAAM;AAAA,MACX,SAAS,MAAM;AAAA,IACjB,CAAC;AAAA,EACH;AACF;AAEA,IAAI,YAAY,MAAM;AACpB,QAAM,YAAY;AACpB;","names":["dbSearchPath","getSettings","resolveNatsControlPlaneAuth","createDb","createNatsEventBus","createObservability","ensureModalRegistryImage","createObjectStorage","getBillingBalance","getSandbox","readActiveSandbox","requireFile","getSessionEvent","getSessionGoal","getLatestRunState","isCodexBilledTurn","workspaceCodexSubscriptionActive","getWorkspaceModelPolicy","listCodexAccountStatuses","fetchCodexUsageForAccount","requireSession","recordUsageEvent","getActiveSessionHistoryItems","sumUsageQuantity","SandboxLeaseSupersededError","sanitizeHistoryItemsForModel","summarizeForCompaction","SUMMARY_BUFFER_TOKENS","deleteRecordingArtifacts","stopRecordingOnBox","configuredStaticUsageLimits","chosen","getCodexCapacityWait","reconcileCodexCapacityWait","CODEX_FALLBACK_MODEL_SLUGS","timer","mergeToolRefs","reasoningEffortForMetadata","enqueueGoalRetryWake","maybeContinueGoal","getSessionGoal","getActiveSessionHistoryItems","getSandboxSessionEnvelope","resumeEnvelope","createHash","capturedAt","stats","inserted","evaluateWorkspaceModelPolicy","createHash","randomUUID","createHash","sanitizeHistoryItemsForModel","readActiveSandbox","sleep","SandboxLeaseSupersededError","fetchCodexUsageForAccount","listCodexAccountStatuses","runAgentTurn","randomUUID","stopRecordingOnBox","workspaceCodexSubscriptionActive","requireSession","getSessionEvent","getLatestRunState","isCodexBilledTurn","deleteRecordingArtifacts","getSessionGoal","getWorkspaceModelPolicy","evaluateWorkspaceModelPolicy","CODEX_FALLBACK_MODEL_SLUGS","summarizeForCompaction","SUMMARY_BUFFER_TOKENS","getSandbox","getActiveSessionHistoryItems","recordUsageEvent","getBillingBalance","configuredStaticUsageLimits","sumUsageQuantity","startOfUtcMonth","requireFile","configuredStaticUsageLimits","getBillingBalance","recordUsageEvent","sumUsageQuantity","startOfUtcMonth","reapExpiredFileUploads","accrueWarmSeconds","getBillingBalance","readLease","sandboxWarmRateMicrosPerSecond","deletePriorPersistedSnapshot","isProviderSandboxNotFoundError","reapSandboxLeases","sandboxWarmRateMicrosPerSecond","accrueWarmSeconds","getBillingBalance","readLease","isProviderSandboxNotFoundError","deletePriorPersistedSnapshot","addSessionSystemUpdateWithSourceMutation","enqueueSessionWorkflowWakeIfRunnable","getBillingBalance","isCodexBilledTurn","recordUsageEvent","requireSession","sumUsageQuantity","appendAndPublishEvents","publishDurableSessionEvents","configuredStaticUsageLimits","isCodexBilledTurn","recordUsageEvent","enqueueSessionWorkflowWakeIfRunnable","result","appendAndPublishEvents","addSessionSystemUpdateWithSourceMutation","publishDurableSessionEvents","requireSession","getBillingBalance","configuredStaticUsageLimits","sumUsageQuantity","startOfUtcMonth","applySessionTurnSettlement","countQueuedTurns","getSessionEvent","requireSession","publishDurableSessionEvents","applySessionTurnSettlement","countQueuedTurns","getSessionEvent","requireSession","publishDurableSessionEvents","failSessionAttempt","settleSessionInterruptions","recoverDispatch","peekSessionWork","markSessionIdle","getRig","establishSandboxSessionFromEnvelope","getRig","establishSandboxSessionFromEnvelope","updated","createObjectStorage","getSettings","createObservability","ensureModalRegistryImage","dbSearchPath","createDb","resolveNatsControlPlaneAuth","createNatsEventBus"]}
|