@opengeni/worker-bundle 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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/common.ts","../src/activities/context-compaction.ts","../src/activities/environment.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/observability-metrics.ts","../src/activities/recording.ts","../src/activities/documents.ts","../src/activities/sandbox-lease.ts","../src/activities/scheduled-tasks.ts","../src/activities/session-state.ts","../src/http.ts"],"sourcesContent":["import { dbSearchPath, getSettings, resolveNatsControlPlaneAuth, retryStartupDependency, startupRetryOptions, type Settings } from \"@opengeni/config\";\nimport { createDb } from \"@opengeni/db\";\nimport { createNatsEventBus } from \"@opengeni/events\";\nimport { createObservability, logStartupDependencyRetry, type Observability } from \"@opengeni/observability\";\nimport { Connection, ScheduleAlreadyRunning, ScheduleOverlapPolicy, Client as TemporalClient } from \"@temporalio/client\";\nimport { NativeConnection, Worker } from \"@temporalio/worker\";\nimport { createActivities, type ActivityDependencies } from \"./activities\";\nimport type { WakeSessionWorkflowSignal } from \"./activities/types\";\nimport { dbReadyCheck, natsReadyCheck, startWorkerHttpServer } from \"./http\";\nimport { observabilityEventLogger } from \"./observability-metrics\";\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\";\n\nexport type WorkerOptions = {\n settings?: Settings;\n activities?: ReturnType<typeof createActivities>;\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 = options.activityDependencies?.observability ?? createObservability(settings, { component: \"worker\" });\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 = options.activities ?? createActivities({\n ...options.activityDependencies,\n settings,\n observability,\n });\n const worker = await Worker.create({\n connection,\n namespace: settings.temporalNamespace,\n taskQueue: settings.temporalTaskQueue,\n workflowsPath: options.workflowsPath ?? new URL(\"../src/workflows.ts\", import.meta.url).pathname,\n activities,\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(settings: Settings): Promise<{\n wakeSessionWorkflow: WakeSessionWorkflowSignal;\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 ({ accountId, workspaceId, sessionId, workflowId }) => {\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 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). Gated on sandboxOwnershipEnabled: with the flag off the\n * Schedule is never created, so the lease feature is fully dark (no sweeps, no\n * terminates).\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 if (!settings.sandboxOwnershipEnabled) {\n return { registered: false, close: async () => {} };\n }\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 { registered: true, close: async () => { await connection.close(); } };\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 { registered: false, close: async () => { await connection.close(); } };\n }\n await connection.close().catch(() => undefined);\n throw error;\n }\n}\n\nexport async function startWorker() {\n const settings = getSettings();\n const observability = createObservability(settings, { component: \"worker\" });\n const retryOptions = startupRetryOptions(settings);\n const onRetry = (event: Parameters<typeof logStartupDependencyRetry>[1]) => 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 httpServer: ReturnType<typeof startWorkerHttpServer> | undefined;\n try {\n bus = await retryStartupDependency(\n \"NATS\",\n () =>\n createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password } : undefined,\n { logger: observabilityEventLogger(observability) },\n ),\n { ...retryOptions, onRetry },\n );\n signaler = await retryStartupDependency(\n \"Temporal client\",\n () => createWorkerWorkflowSignaler(settings),\n { ...retryOptions, onRetry },\n );\n workerBundle = await createOpenGeniWorker({\n settings,\n activityDependencies: {\n observability,\n wakeSessionWorkflow: signaler.wakeSessionWorkflow,\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 // Register the ONE global reaper Schedule (no-op when sandboxOwnershipEnabled\n // is false). Idempotent across the pool: only the first worker creates it. The\n // static global-queue Worker.create above is UNCHANGED — there is no\n // per-session worker factory.\n reaperSchedule = await retryStartupDependency(\n \"Temporal schedule (sandbox reaper)\",\n () => registerSandboxReaperSchedule(settings, observability),\n { ...retryOptions, onRetry },\n );\n observability.info(\"OpenGeni worker listening\", {\n temporalTaskQueue: settings.temporalTaskQueue,\n httpPort: settings.workerHttpPort,\n });\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 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 { createDocumentActivities } from \"./activities/documents\";\nimport { createGoalActivities } from \"./activities/goals\";\nimport { createSandboxLeaseActivities } from \"./activities/sandbox-lease\";\nimport { createScheduledTaskActivities } from \"./activities/scheduled-tasks\";\nimport { createSessionStateActivities } from \"./activities/session-state\";\nimport type { ActivityDependencies, ActivityServices } from \"./activities/types\";\nimport { observabilityEventLogger, runtimeMetricsHooksForObservability } from \"./observability-metrics\";\n\nexport type {\n ActivityDependencies,\n DispatchScheduledTaskRunInput,\n DispatchScheduledTaskRunResult,\n IndexDocumentInput,\n MaybeContinueGoalInput,\n MaybeContinueGoalResult,\n PauseGoalForInterruptInput,\n RequeueTurnAfterWorkerDeathInput,\n RequeueTurnAfterWorkerDeathResult,\n RunAgentTurnInput,\n RunAgentTurnResult,\n} from \"./activities/types\";\n\nexport function createActivities(dependencies: ActivityDependencies = {}) {\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 = 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 ? null : 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 ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password } : undefined,\n { logger: observabilityEventLogger(observability) },\n )),\n runtime: dependencies.runtime ?? 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 // §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 const runAgentTurn = createRunAgentTurnActivity(services);\n return {\n runAgentTurn,\n // Legacy Temporal activity name. In-flight session workflows (which can\n // legitimately live for days) recorded ScheduleActivityTask events as\n // \"runAgentSegment\"; the name must keep resolving until those histories\n // drain. New workflow code must use runAgentTurn; migrate the session\n // workflow call site via patched() before removing this alias.\n runAgentSegment: runAgentTurn,\n ...createDocumentActivities(services),\n ...createSessionStateActivities(services),\n ...createScheduledTaskActivities(services),\n ...createGoalActivities(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\nconst defaultActivities = createActivities();\n\nexport const runAgentTurn = defaultActivities.runAgentTurn;\nexport const runAgentSegment = defaultActivities.runAgentSegment;\nexport const indexDocument = defaultActivities.indexDocument;\nexport const failSession = defaultActivities.failSession;\nexport const interruptActiveTurn = defaultActivities.interruptActiveTurn;\nexport const requeueTurnAfterWorkerDeath = defaultActivities.requeueTurnAfterWorkerDeath;\nexport const claimNextQueuedTurn = defaultActivities.claimNextQueuedTurn;\nexport const markSessionIdle = defaultActivities.markSessionIdle;\nexport const dispatchScheduledTaskRun = defaultActivities.dispatchScheduledTaskRun;\nexport const maybeContinueGoal = defaultActivities.maybeContinueGoal;\nexport const pauseGoalForInterrupt = defaultActivities.pauseGoalForInterrupt;\nexport const reapSandboxLeases = defaultActivities.reapSandboxLeases;\n","import {\n claimNextQueuedTurn as claimNextQueuedTurnDb,\n createTurn,\n applyCreditDebitUpToBalance,\n finishTurn,\n getBillingBalance,\n getSandbox,\n readActiveSandbox,\n requireFile,\n getSessionEvent,\n getSessionGoal,\n getSessionTurn,\n isCodexBilledTurn,\n workspaceCodexSubscriptionActive,\n getCodexRotationSettings,\n listCodexAccountStatuses,\n fetchCodexUsageForAccount,\n getSessionCodexState,\n recordSessionActiveCodexCredential,\n recordCodexAccountUsage,\n recordCodexAccountConnectors,\n setActiveCodexCredential,\n setCodexCredentialExhausted,\n countConsecutiveReactiveRotations,\n requireSession,\n recordUsageEvent,\n appendSessionHistoryItems,\n consumeSessionCompactionRequest,\n countSessionHistoryItems,\n getActiveSessionHistoryItems,\n nextSessionHistoryPosition,\n requeuePreemptedTurn,\n saveRunState,\n upsertSandboxSessionEnvelope,\n setSessionStatus,\n setSessionLastInputTokens,\n sumUsageQuantity,\n heartbeatLeaseHolder,\n accrueWarmSeconds,\n SandboxLeaseSupersededError,\n buildConnectionTokenResolver,\n type AppendEventInput,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents } from \"@opengeni/events\";\nimport {\n sandboxStateEntryFromRunState,\n agentsErrorRunState,\n maxTurnsExceededRunState,\n modelResponseUsageFromSdkEvent,\n normalizeSdkEvent,\n sanitizeHistoryItemsForModel,\n summarizeForCompaction,\n findCompactionNeededError,\n SUMMARY_BUFFER_TOKENS,\n type SandboxFileDownload,\n type OpenGeniRuntime,\n type ComputerToolMode,\n} from \"@opengeni/runtime\";\nimport { calculateModelUsageCostMicros, configuredModelPricing, configuredStaticUsageLimits, sandboxWarmRateMicrosPerSecond, type ModelUsageInput, type ModelProviderApi, type RegistryProviderKind, type Settings } from \"@opengeni/config\";\nimport { CancelledFailure } from \"@temporalio/activity\";\nimport { settingsWithCodexCredential, settingsWithEnabledCapabilityMcpServers, settingsWithSessionMcpServersForRun } from \"./capabilities\";\nimport { chooseRotationActive, computeIdleDelayMs, computeReactiveRotationResume, type CodexRotationStrategy, type RotationDecision } from \"./codex-rotation\";\nimport type { CodexAccountStatus } from \"@opengeni/db\";\nimport { buildCodexTokenResolver } from \"./codex-auth\";\nimport {\n buildModelResolver,\n CODEX_CLIENT_VERSION,\n CODEX_FALLBACK_MODEL_SLUGS,\n classifyCodexUsageLimitError,\n codexRequestStorage,\n type CodexRequestContext,\n type CodexUsageHeaderSnapshot,\n} from \"@opengeni/codex\";\nimport {\n mergeResourceRefs,\n mergeToolRefs,\n} from \"./common\";\nimport { maybeCompactContext } from \"./context-compaction\";\nimport { loadWorkspaceEnvironmentForRunWithCredentials, sandboxEnvironmentForRun } from \"./environment\";\nimport { withCodexAppsTool, withFirstPartyTools } from \"./goals\";\nimport { resolveWorkspaceAgentInstructions, resolveWorkspacePackRuntime, settingsWithPackSandboxImage } 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 {\n ActivityServices,\n RunAgentTurnInput,\n RunAgentTurnResult,\n} from \"./types\";\nimport { resumeBoxForTurn, acquireSelfhostedLeaseForTurn, type ResumedTurnSandbox } from \"../sandbox-resume\";\nimport { wrapTurnBoxWithRouting, establishSelfhostedTurnSession, routingEnabled } from \"../sandbox-routing\";\nimport { recordCreditMicros, runtimeMetricsHooksForObservability, turnLifecycleMetricsFor, type TurnOutcome } from \"../observability-metrics\";\nimport { beginRecording, discardRecording, finalizeRecording, type ActiveRecording } from \"./recording\";\nimport { createObjectStorage, type ObjectStorage } from \"@opengeni/storage\";\nimport { desktopCapableBackend, sandboxRunAs } from \"@opengeni/runtime\";\nimport { CAPABILITY_DESCRIPTORS, type ResourceRef } from \"@opengeni/contracts\";\nimport { 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/**\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\n// Resume notice fed to the model when a turn re-enters after a graceful\n// worker shutdown (deploy/rollout restart) checkpointed it mid-flight. The\n// agent must not blindly replay side effects it cannot see in its history:\n// at most the single in-flight model step was lost, and anything it started\n// there may or may not have completed.\n// Resume notice after an in-turn context-window overflow was recovered by\n// compaction: the turn's earlier work survives (albeit summarized), so the\n// agent continues instead of the session dying or stalling idle.\nexport const CONTEXT_OVERFLOW_RESUME_TEXT = [\n \"[TURN RESUMED AFTER CONTEXT COMPACTION] The conversation approached or exceeded the model's context window mid-turn; older history above was compacted into a summary.\",\n \"Continue the original task from where it left off. Before repeating any action with side effects, check whether it already happened.\",\n].join(\"\\n\");\n\nexport const WORKER_SHUTDOWN_RESUME_TEXT = [\n \"[TURN RESUMED AFTER WORKER RESTART] The platform worker running this turn restarted (deploy/rollout) before the turn finished.\",\n \"Your conversation history above, including this turn's earlier work, is preserved up to the last checkpoint; at most the single in-flight model step after it was lost.\",\n \"Continue the original task from where it left off. Before repeating any action with side effects, check whether it already happened.\",\n].join(\"\\n\");\n\n// Resume notice for the harder variant: the worker died WITHOUT running the\n// graceful checkpoint (SIGKILL, OOM, node loss — surfaced to the workflow as\n// a heartbeat-timeout activity failure). Conversation truth is still\n// dual-written after every model response, so the bound is the same order as\n// a graceful preempt, but nothing after the last reconcile was captured and\n// the agent must be even more suspicious about repeated side effects.\nexport const WORKER_DEATH_RESUME_TEXT = [\n \"[TURN RESUMED AFTER WORKER CRASH] The platform worker running this turn died before the turn finished.\",\n \"Your conversation history above, including this turn's earlier work, is preserved up to the last checkpoint; anything in flight after that checkpoint was lost.\",\n \"Continue the original task from where it left off. Before repeating any action with side effects, check whether it already happened.\",\n].join(\"\\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 cancellation (user interrupt) or a server-side timeout.\n */\nexport function isWorkerShutdownCancellation(error: unknown): boolean {\n return error instanceof CancelledFailure && error.message === \"WORKER_SHUTDOWN\";\n}\n\nexport const CONTEXT_WINDOW_OVERFLOW_RECOVERY_MESSAGE =\n \"The conversation reached the model context compaction threshold; it has been compacted. Send a message to continue.\";\nconst MAX_CONTEXT_COMPACTION_RECOVERY_ATTEMPTS = 3;\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(error: unknown): { message: string; code?: string; detail?: string } | null {\n const fields = collectErrorStrings(error);\n const matched = fields.find((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\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 re-dispatch of the SAME turn (preemption resume, 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 only fallback was 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 positional fallback with the\n * per-execution dispatch id (the Temporal activityId, unique per scheduled\n * execution) makes re-dispatched calls distinct while still deduping a\n * same-execution retry.\n */\nexport function modelUsageSourceKey(input: {\n responseId?: string | null | undefined;\n dispatchId: string | null;\n positionalKey: string;\n}): string {\n if (input.responseId) {\n return input.responseId;\n }\n return input.dispatchId ? `${input.dispatchId}:${input.positionalKey}` : input.positionalKey;\n}\n\nexport function 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): { rows: Array<{ position: number; item: Record<string, unknown> }>; nextWatermark: number; nextPosition: number } {\n const sanitized = sanitizeHistoryItemsForModel(rawHistory);\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 { rows, nextWatermark: sanitized.length, nextPosition: nextPosition + rows.length };\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 * - run-state BLOB path (`modelHistoryFromItems === false`: approval resume, the\n * items-mode run-state fallback, run_state mode) — `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<{ item: Record<string, unknown>; producerCodexCredentialId: string | null }>,\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(\"active sandbox backend resolution failed (turn proceeds on home backend)\", error);\n return undefined;\n }\n}\n\n/**\n * Decide whether to start on-turn desktop recording for THIS turn.\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 at turn start (the box is only filmed\n * for the duration of one turn). A swap AFTER the recording starts is deliberately\n * ignored — a partial-turn recording already has defined failure semantics, so we do\n * not add machinery to stop/restart it mid-turn.\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: { provider: { kind: RegistryProviderKind; api: ModelProviderApi } } | 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\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): Promise<CodexAccountStatus[]> {\n const nearPct = settings.codexRotationNearExhaustionPct;\n const stale = accounts.filter(\n (a) => a.status === \"active\" && ((a.primaryUsedPercent ?? 0) >= nearPct || (a.secondaryUsedPercent ?? 0) >= nearPct),\n );\n if (stale.length === 0) {\n return accounts;\n }\n await Promise.all(stale.map((a) => fetchCodexUsageForAccount(db, settings, workspaceId, a.id).catch(() => undefined)));\n return listCodexAccountStatuses(db, workspaceId).catch(() => accounts);\n}\n\nexport function createRunAgentTurnActivity(services: () => Promise<ActivityServices>) {\n return async function runAgentTurn(input: RunAgentTurnInput): Promise<RunAgentTurnResult> {\n const { settings, db, bus, runtime, objectStorage, observability, wakeSessionWorkflow, entitlements, connectionCredentials } = await services();\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_event_id\": input.triggerEventId,\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 heartbeatTimer: ReturnType<typeof startActivityHeartbeat> | undefined;\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 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 lease holder id (Temporal activityId, unique per scheduled execution)\n // + the group id, captured so the lease heartbeat can refresh the lease TTL\n // epoch-fenced (a superseded owner self-evicts) and finally can release.\n let sandboxHolderId: string | 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 // P4.3 on-turn recording: when the desktop tier + recording are enabled and\n // the box is desktop-capable, the turn films the SAME :0 the agent's\n // computer-use drives, finalized to storage in this activity's `finally`\n // (read+PUT in-process — never a Temporal payload, F10). null otherwise.\n let activeRecording: ActiveRecording | null = null;\n // P4.3 recording gate: flips true the first time a computer-use/desktop tool\n // ACTUALLY executes this turn (an SDK `computer_call` item streams through). A\n // plain text turn (\"hey\"/\"continue\") never flips it, so finalize discards the\n // recording with NO storage PUT and NO recording.failed — a clean no-op (a\n // static frame of an untouched desktop is not worth uploading).\n let didComputerUse = false;\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: ((events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>, immediate?: boolean) => Promise<void>) | null = null;\n let turnStartedPublished = false;\n let stream: Awaited<ReturnType<OpenGeniRuntime[\"runStream\"]>> | undefined;\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 by sanitizing the current history into an API-valid sequence (the same\n // pure function the read path uses) before persisting: a dangling call is\n // never persisted (it is deferred until its result exists, when the pair is\n // written together at consecutive positions), and a result is never\n // persisted without its preceding call. The watermark counts only items we\n // actually persisted, so a non-monotonic history can never desync it.\n let persistedHistoryCount = 0;\n let historyCountAtTurnStart = 0;\n let modelOrToolProgressPersisted = false;\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 (options: { skipInputOnlyRows?: boolean } = {}) => {\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) => isModelOrToolProgressHistoryItem(row.item));\n const shouldAppendRows = rows.length > 0 && (!options.skipInputOnlyRows || hasModelOrToolProgress);\n if (shouldAppendRows) {\n await appendSessionHistoryItems(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\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 }\n if (shouldAppendRows || !options.skipInputOnlyRows) {\n persistedHistoryCount = nextWatermark;\n nextHistoryPosition = nextPosition;\n }\n if (hasModelOrToolProgress) {\n modelOrToolProgressPersisted = true;\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 }\n };\n // Reassigned after the workspace environment loads; the publish closure is\n // created (and used for turn.started) before the environment is available.\n let redact: (payload: unknown) => unknown = identityRedactor;\n let environmentId = \"\";\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 // 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 the preemption path: 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(db, input.workspaceId, settings);\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(db, mcpSettings, input.workspaceId);\n const capabilitySettings = await settingsWithCodexCredential(db, input.workspaceId, mcpSettings, codexSubscriptionActive);\n runtime.configure(capabilitySettings);\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n const trigger = await getSessionEvent(db, input.workspaceId, input.triggerEventId);\n if (!trigger) {\n throw new Error(`Trigger event not found: ${input.triggerEventId}`);\n }\n triggerType = trigger.type;\n let turn = input.turnId ? await getSessionTurn(db, input.workspaceId, input.turnId) : await claimNextQueuedTurnDb(db, input.workspaceId, input.sessionId, input.workflowId);\n if (!turn && !input.turnId) {\n const createdTurnId = await createTurn(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n temporalWorkflowId: input.workflowId,\n triggerEventId: input.triggerEventId,\n });\n turn = await getSessionTurn(db, input.workspaceId, createdTurnId);\n }\n if (!turn) {\n throw new Error(`Session turn not found for trigger: ${input.triggerEventId}`);\n }\n turnId = turn.id;\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 const isCodexTurn = await isCodexBilledTurn({ db, settings, workspaceId: input.workspaceId, model: turn.model, active: codexSubscriptionActive });\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(settings, db, input.accountId, input.workspaceId, isCodexTurn, entitlements);\n const activityContext = currentActivityContext();\n // Setup (environment 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 preempt 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 heartbeatTimer = startActivityHeartbeat(activityContext, {\n phase: \"running\",\n sessionId: input.sessionId,\n turnId,\n });\n let producerSeq = 0;\n // One producer per activity execution, not per turn: a turn can run\n // again on the same workflow (preemption resume, 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 const dispatchId = activityContext?.info.activityId ?? null;\n publish = async (events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>, immediate = false) => {\n const inputs = events.map((event) => ({\n ...event,\n payload: redact(event.payload),\n turnId: turnId!,\n producerId,\n producerSeq: ++producerSeq,\n }));\n await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, inputs);\n activityContext?.heartbeat({ phase: \"events_published\", sessionId: input.sessionId, turnId, producerSeq });\n if (immediate) {\n await Bun.sleep(0);\n }\n };\n activityContext?.heartbeat({ phase: \"turn_started\", sessionId: input.sessionId, turnId });\n\n // A shutdown that landed during claim/billing setup preempts before the\n // turn visibly starts: nothing ran yet, so the requeued turn replays the\n // original trigger cleanly on a healthy worker.\n throwIfWorkerShuttingDown();\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"running\", turnId);\n await publish([\n { type: \"session.status.changed\", payload: { status: \"running\" } },\n { type: \"turn.started\", payload: { triggerEventId: input.triggerEventId } },\n ], true);\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 [rotation, accounts, sessionCodex] = await Promise.all([\n getCodexRotationSettings(db, input.workspaceId),\n listCodexAccountStatuses(db, input.workspaceId),\n getSessionCodexState(db, input.workspaceId, input.sessionId),\n ]);\n const connectedIds = new Set(accounts.map((account) => account.id));\n const sessionPin = sessionCodex?.pinnedCredentialId ?? null;\n // The off-path / P1 default: today's workspace active pointer. Untouched\n // when rotation is off or the session is pinned (byte-identical to P1).\n let chosenActive = rotation?.activeCredentialId ?? null;\n let rotationDecision: RotationDecision | null = null;\n\n // P3 auto-rotation: the ONLY new branch, gated on rotation_enabled and\n // pin-guarded (a pinned session NEVER rotates). When skipped, chosenActive\n // stays the active pointer and selectCodexCredentialForTurn is called with\n // byte-identical arguments to today — zero added cost on non-rotation turns.\n if (rotation?.rotationEnabled && sessionPin == null) {\n let rankAccounts = accounts;\n rotationDecision = chooseRotationActive({\n rotationStrategy: rotation.rotationStrategy as CodexRotationStrategy,\n activeCredentialId: rotation.activeCredentialId,\n priorCredentialId: sessionCodex?.lastCredentialId ?? null,\n accounts: rankAccounts,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\n now: new Date(),\n // P4: the leaving (active) account's cached connector set is the proxy\n // for \"what this session has access to\" — prefer a covering target.\n usedConnectors: rankAccounts.find((a) => a.id === rotation.activeCredentialId)?.connectorNamespaces ?? [],\n });\n if (rotationDecision.kind === \"allCapped\") {\n // SELF-HEAL (invariant 4): the turn hot path NEVER refreshes usage, so a\n // window that has actually reset still reads capped from the stale cache —\n // which would otherwise idle-loop forever (idle → continuation re-dispatch →\n // same stale all-capped → idle …). Before idling, refresh usage for the\n // over-threshold accounts (bounded to the account count) and re-rank ONCE,\n // so a genuinely-reset window is picked up immediately and the cache heals.\n rankAccounts = await refreshCappedCodexUsageRows(db, settings, input.workspaceId, rankAccounts);\n rotationDecision = chooseRotationActive({\n rotationStrategy: rotation.rotationStrategy as CodexRotationStrategy,\n activeCredentialId: rotation.activeCredentialId,\n priorCredentialId: sessionCodex?.lastCredentialId ?? null,\n accounts: rankAccounts,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\n now: new Date(),\n // P4: leaving (active) account's connector set (refreshCappedCodexUsageRows\n // only touches usage columns, so connectorNamespaces is preserved here).\n usedConnectors: rankAccounts.find((a) => a.id === rotation.activeCredentialId)?.connectorNamespaces ?? [],\n });\n }\n if (rotationDecision.kind === \"active\") {\n if (rotationDecision.moved) {\n // The single authoritative pointer-move site: persist the new active.\n await setActiveCodexCredential(db, input.workspaceId, rotationDecision.credentialId);\n }\n chosenActive = rotationDecision.credentialId;\n } else if (rotationDecision.kind === \"allCapped\" && publish && turnId) {\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(() => null);\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(rotationDecision.earliestResetAt, new Date(), CODEX_USAGE_LIMIT_MAX_RESUME_MS);\n const failurePayload = codexUsageLimitFailurePayload(\n { resetsInSeconds: Math.ceil(resumeMs / 1000) },\n \"all connected Codex subscriptions are rate-limited\",\n { allAccounts: true },\n );\n await publish([\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 { type: \"turn.failed\", payload: { ...failurePayload, recovery: goalActive ? \"goal_continuation\" : \"user_message\", runStateSaved: false, rotated: true } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\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 goalActive ? { status: \"idle\", continueDelayMs: resumeMs, idleUntilReset: true } : { status: \"idle\" };\n }\n // kind:\"none\" (no accounts) → chosenActive stays null → existing relogin path.\n }\n\n effectiveCodexCredentialId = selectCodexCredentialForTurn({\n sessionPinnedCredentialId: sessionPin, // pin still wins, structurally\n activeCredentialId: chosenActive, // rotation-choice OR today's active\n connectedIds,\n });\n if (effectiveCodexCredentialId) {\n const priorAccountId = sessionCodex?.lastCredentialId ?? null;\n await recordSessionActiveCodexCredential(db, input.workspaceId, input.sessionId, effectiveCodexCredentialId);\n if (priorAccountId !== effectiveCodexCredentialId) {\n // \"rotation\" only when the engine actually moved the pointer; otherwise the\n // unchanged P1 \"manual\" literal (a manual active flip between turns).\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 = rotationDecision?.kind === \"active\" ? rotationDecision.droppedConnectors : undefined;\n await publish([{\n type: \"codex.account.switched\",\n payload: {\n fromAccountId: priorAccountId,\n toAccountId: effectiveCodexCredentialId,\n reason: rotated ? \"rotation\" : \"manual\",\n ...(droppedConnectors && droppedConnectors.length > 0 ? { droppedConnectors } : {}),\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 // 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(db, input.workspaceId);\n const baseRunSettings = {\n ...settingsWithPackSandboxImage(capabilitySettings, packRuntime.sandboxImage),\n openaiModel: turn.model,\n openaiReasoningEffort: turn.reasoningEffort,\n sandboxBackend: turn.sandboxBackend,\n };\n const runSettings = await settingsWithSessionMcpServersForRun(db, input.workspaceId, input.sessionId, baseRunSettings);\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 // 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 = 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(db, runSettings, input.workspaceId, effectiveCodexCredentialId ?? \"\");\n return {\n clientVersion: CODEX_CLIENT_VERSION,\n getToken: resolver.getToken,\n refresh: resolver.refresh,\n resolveModel: buildModelResolver(CODEX_FALLBACK_MODEL_SLUGS, CODEX_FALLBACK_MODEL_SLUGS[0]),\n onUsageHeaders: (snapshot) => { latestCodexUsage = snapshot; }, // latest wins; flushed once in finally\n };\n })()\n : null;\n const withCodex = <T>(fn: () => Promise<T>): Promise<T> => (codexContext ? codexRequestStorage.run(codexContext, fn) : fn());\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(runSettings, withFirstPartyTools(runSettings, mergeToolRefs(session.tools, turn.tools)));\n // §7.6 P4a — load (and decrypt) the workspace environment via the host\n // `sandboxSecrets` provider when bound; unset → today's local decrypt.\n const connectionScope = { accountId: input.accountId, workspaceId: input.workspaceId };\n const workspaceEnvironment = await loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n session.environmentId,\n connectionCredentials?.sandboxSecrets,\n );\n environmentId = workspaceEnvironment?.id ?? \"\";\n redact = createSecretRedactor(\n Object.entries(workspaceEnvironment?.values ?? {}).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 the\n // inert GitHub token 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 const activeSandboxPointer = routingOn\n ? await readActiveSandbox(db, input.workspaceId, input.sessionId).catch(() => null)\n : null;\n const activeSandboxRecord = routingOn && activeSandboxPointer?.activeSandboxId\n ? await getSandbox(db, input.workspaceId, activeSandboxPointer.activeSandboxId).catch(() => null)\n : null;\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 // 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 GitHub installation token on every call, so a second call would\n // yield a DIFFERENT token value 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 GitHub token minted ONCE per turn as `gitToken`. The env feeds BOTH\n // the box manifest AND the agent (env-parity, as before); the token is threaded\n // OFF-MANIFEST as the clone-seed `gitTokenSeed` to buildAgent (below) so the box\n // never carries a rotating value on its manifest. When the platform token IS\n // minted, the host `gitCredentials` provider may supply it; unset → self-mint\n // from settings. gitToken is undefined on the selfhosted skip path (the machine\n // uses its own git creds).\n const {\n environment: sandboxEnvironment,\n gitToken: sandboxGitToken,\n toolspaceToken: sandboxToolspaceToken,\n } = await sandboxEnvironmentForRun(\n runSettings,\n turnResources,\n workspaceEnvironment?.values ?? {},\n {\n skipGitHubToken: activeSandboxBackend === \"selfhosted\",\n scope: connectionScope,\n gitCredentials: connectionCredentials?.gitCredentials,\n sessionId: input.sessionId,\n runId: turnId,\n },\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 ('turn' holder = the activityId),\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 environment the agent declares — the SDK\n // applies the agent's manifest to this provided session and throws on ANY\n // environment delta (validateNoEnvironmentDelta). Passing sandboxEnvironment\n // here makes current==target so the delta is empty.\n if (settings.sandboxOwnershipEnabled && turn.sandboxBackend !== \"none\") {\n sandboxHolderId = dispatchId ?? `turn:${turnId}`;\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 const groupBoxBackend: Settings[\"sandboxBackend\"] =\n turn.sandboxBackend === \"selfhosted\" && !machinePrimary\n ? settings.sandboxBackend\n : turn.sandboxBackend;\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 const established = await establishSelfhostedTurnSession(\n { db, settings, bus },\n {\n workspaceId: input.workspaceId,\n agentId: activeSandboxRecord!.enrollmentId!,\n epoch: activeSandboxPointer!.activeEpoch,\n environment: sandboxEnvironment,\n workingDir: activeSandboxPointer!.workingDir,\n },\n );\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 { db, settings, bus },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\n pinnedSelfhosted: {\n sandboxId: activeSandboxPointer!.activeSandboxId!,\n epoch: activeSandboxPointer!.activeEpoch,\n },\n },\n established,\n ),\n leaseEpoch: lease.leaseEpoch,\n release: lease.release,\n };\n } else {\n resolvedSandbox = await resumeBoxForTurn(\n { db, settings, sandboxMetrics: runtimeMetricsHooksForObservability(observability) },\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 ? { image: runSettings.modalImageRef ?? runSettings.dockerImage }\n : {}),\n },\n \"turn\",\n sandboxHolderId,\n );\n setupBoxSession = resolvedSandbox.established.session;\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 { workspaceId: input.workspaceId, sessionId: input.sessionId, environment: sandboxEnvironment },\n resolvedSandbox.established,\n ),\n };\n }\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 = resolvedSandbox.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(settings, activeSandboxBackend ?? groupBoxBackend);\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 }, 10_000);\n if (\"unref\" in leaseHeartbeatTimer && typeof leaseHeartbeatTimer.unref === \"function\") {\n leaseHeartbeatTimer.unref();\n }\n }\n\n // P4.3 on-turn recording. The box's :0 display stack was brought up by\n // resumeBoxForTurn (spawner path) / is up from a prior turn; film it for\n // the duration of this turn so the human can watch the agent work and the\n // agent's computer-use proofs are captured. Best-effort: a recording start\n // failure NEVER fails the turn (the desktop is a value-add). Finalized in\n // `finally` (read+PUT in this same activity — never a Temporal payload).\n if (\n resolvedSandbox\n && shouldStartOnTurnRecording({\n recordingEnabled: settings.recordingEnabled,\n desktopEnabled: settings.sandboxDesktopEnabled,\n establishedBackendId: resolvedSandbox.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: activeSandboxBackend,\n })\n ) {\n try {\n const 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: resolvedSandbox.established.session,\n runAs: sandboxRunAs(settings),\n reason: null,\n });\n activeRecording = begun.active;\n await publish([{ type: \"recording.started\", payload: begun.started }]);\n } catch (recordingError) {\n activeRecording = null;\n console.error(\"on-turn recording start failed (turn outcome unaffected)\", recordingError);\n }\n }\n\n const fileResourceDownloads = await sandboxFileDownloadsForRun(runSettings, db, objectStorage, input.workspaceId, turnResources);\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(() => runtime.prepareTools(runSettings, turnTools, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\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 ? { firstPartyPermissions: session.firstPartyMcpPermissions } : {}),\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; continuation/preemption turns never match (their\n // trigger is goal.continuation/turn.preempted).\n const isGenesisTurn = 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 const agent = runtime.buildAgent(runSettings, turnResources, {\n reasoningEffort: turn.reasoningEffort,\n genesisTitleHint: isGenesisTurn,\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\" && sandboxGitToken ? { gitTokenSeed: sandboxGitToken } : {}),\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 compactionMode: resolvedModel.provider.compactionMode,\n hostedWebSearch: resolvedModel.configured.hostedWebSearch,\n encryptedReasoning: resolvedModel.provider.api === \"responses\" && runSettings.openaiReasoningEncryptedContent,\n contextWindowTokens: 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 }\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 : { computerToolMode: computerToolModeForTurn(null) }),\n ...(packRuntime.skills.length > 0 ? { packSkills: packRuntime.skills } : {}),\n ...(workspaceAgentInstructions ? { instructionsTemplate: workspaceAgentInstructions } : {}),\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 ...(workspaceEnvironment\n ? {\n workspaceEnvironment: {\n name: workspaceEnvironment.name,\n description: workspaceEnvironment.description,\n variableNames: Object.keys(workspaceEnvironment.values),\n },\n }\n : {}),\n });\n const compactSummarizer = resolvedModel\n ? (s: Settings, m: Array<Record<string, unknown>>, o?: { maxTranscriptTokens?: number }) => withCodex(() => summarizeForCompaction(s, m, {\n client: resolvedModel.client,\n api: resolvedModel.provider.api,\n model: resolvedModel.configured.id,\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n ...(o?.maxTranscriptTokens ? { maxTranscriptTokens: o.maxTranscriptTokens } : {}),\n }))\n : undefined;\n // Pre-turn client-side context compaction (Azure path). When the\n // resolved mode is \"client\" and the single Codex-parity threshold is\n // crossed, this summarizes the current active history and rebuilds active\n // history as [user messages..., summary] BEFORE the model input is read.\n // Summarizer failures fall through to hard-trim retry and deterministic\n // fallback; only structural no-ops leave the history unchanged.\n // Skipped on approval/preempt resumes (no fresh user turn; the frozen\n // RunState or in-flight tail must replay verbatim).\n if (triggerType === \"user.message\" || triggerType === \"goal.continuation\") {\n try {\n // Operator /compact (the slash command) sets a durable request flag;\n // consume it atomically so a forced compaction runs now even when the\n // budget trigger would not fire. Only the turn that observes the flag\n // runs it, so concurrent turns can't double-compact.\n const forced = await consumeSessionCompactionRequest(db, input.workspaceId, input.sessionId);\n const outcome = await maybeCompactContext(\n db,\n runSettings,\n { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId },\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 keeps the default built-in Responses summarizer.\n compactSummarizer,\n forced ? { force: true } : {},\n );\n if (outcome.compacted) {\n const trigger = forced ? \"operator\" : undefined;\n await publish([{ type: \"session.context.compacted\", payload: { summaryPosition: outcome.summaryPosition, ...(trigger ? { trigger } : {}) } }]);\n }\n } catch (compactError) {\n console.error(\"context compaction failed (turn proceeds un-compacted)\", compactError);\n }\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 runSettings,\n { currentCodexCredentialId: effectiveCodexCredentialId },\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(db, input.workspaceId, input.sessionId);\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(\n activeSeedRows,\n prepared.modelHistoryFromItems,\n { currentCodexCredentialId: effectiveCodexCredentialId },\n );\n historyCountAtTurnStart = persistedHistoryCount;\n nextHistoryPosition = await nextSessionHistoryPosition(db, input.workspaceId, input.sessionId);\n };\n\n const forceContextCompaction = async (triggerLabel: \"overflow\" | \"proactive\") => {\n const clientCompactionSettings: Settings = { ...runSettings, contextCompactionMode: \"client\" };\n const outcome = await maybeCompactContext(\n db,\n clientCompactionSettings,\n { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: activeTurnId },\n session.lastInputTokens,\n compactSummarizer,\n { force: true, requireShrink: true },\n );\n if (outcome.compacted) {\n await publish!([{ type: \"session.context.compacted\", payload: { summaryPosition: outcome.summaryPosition, trigger: triggerLabel } }]);\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 runStreamOnce = (): ReturnType<OpenGeniRuntime[\"runStream\"]> => runtime.runStream(agent, runInput!, runSettings, {\n sandboxEnvironment,\n onRuntimeEvent: async (event) => {\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 ...(resolvedSandbox\n ? {\n ownedSandbox: {\n client: resolvedSandbox.established.client,\n session: resolvedSandbox.established.session,\n sessionState: resolvedSandbox.established.sessionState,\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 },\n }\n : {}),\n contextCompactionSignalTokens: () => lastInputTokensObserved,\n });\n stream = await withCodex(runStreamOnce);\n batcher = createRuntimeBatcher(async (events) => {\n await publish!(events);\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 responseUsageCount += 1;\n const observed = responseUsage.usage?.inputTokens;\n if (typeof observed === \"number\" && observed > 0) {\n lastInputTokensObserved = observed;\n await setSessionLastInputTokens(db, input.workspaceId, input.sessionId, observed)\n .catch((error) => console.error(\"persist last_input_tokens failed (non-fatal)\", error));\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: modelUsageSourceKey({\n responseId: responseUsage.responseId,\n dispatchId,\n positionalKey: `response-${responseUsageCount}`,\n }),\n observability,\n });\n await reconcileConversationTruth();\n try {\n await ensureRunAllowed(settings, db, input.accountId, input.workspaceId, isCodexTurn, entitlements);\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 // Recording gate: a computer-use tool actually ran when an SDK\n // `tool_call_item` whose rawItem.type is \"computer_call\" streams through\n // (screenshot/click/type/scroll/etc. — the first computer action proves\n // the desktop was driven). Match the raw SDK event (ground truth) BEFORE\n // normalization. Only meaningful when a recording is live.\n if (activeRecording && !didComputerUse && isComputerCallStreamEvent(next.value)) {\n didComputerUse = true;\n }\n const normalized = normalizeSdkEvent(next.value);\n for (const event of normalized) {\n await batcher.push(event);\n }\n }\n } finally {\n if (!streamDone) {\n await iterator.return?.();\n }\n }\n await batcher.flush();\n await stream.completed.catch(() => undefined);\n if (responseUsageCount === 0) {\n const aggregateInput = (stream.state.usage as { inputTokens?: unknown } | undefined)?.inputTokens;\n if (typeof aggregateInput === \"number\" && aggregateInput > 0) {\n lastInputTokensObserved = aggregateInput;\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: stream.state.usage,\n sourceKey: modelUsageSourceKey({ responseId: null, dispatchId, positionalKey: \"aggregate\" }),\n observability,\n });\n }\n if (lastInputTokensObserved !== null) {\n await setSessionLastInputTokens(db, input.workspaceId, input.sessionId, lastInputTokensObserved)\n .catch((error) => console.error(\"persist last_input_tokens failed (non-fatal)\", error));\n }\n\n if (stream.interruptions.length > 0) {\n await reconcileConversationTruth();\n const approvals = runtime.serializeApprovals(stream.interruptions);\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\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 await publish!([\n { type: \"session.requiresAction\", payload: { approvals } },\n { type: \"session.status.changed\", payload: { status: \"requires_action\" } },\n ], true);\n await finishTurn(db, input.workspaceId, activeTurnId, \"requires_action\");\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"requires_action\", activeTurnId);\n activityStatus = \"requires_action\";\n return { status: \"requires_action\" };\n }\n\n const finalOutput = String(stream.finalOutput ?? \"\");\n await reconcileConversationTruth();\n if (settings.sessionHistorySource !== \"items\") {\n // Legacy conversation memory; in items mode the blob is only written\n // for requires_action pauses (the one RunState-only resume path).\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n serializedRunState: stream.state.toString(),\n pendingApprovals: [],\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n }\n await publish!([\n { type: \"agent.message.completed\", payload: { text: finalOutput } },\n { type: \"turn.completed\", payload: { output: finalOutput } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, activeTurnId, \"idle\");\n turnMetricOutcome = \"completed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\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 { status: \"idle\" };\n };\n\n await prepareRunAttemptInput();\n let compactionRecoveryAttempts = 0;\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 ? \"proactive\" : overflow ? \"overflow\" : null;\n if (recoveryKind && compactionRecoveryAttempts >= MAX_CONTEXT_COMPACTION_RECOVERY_ATTEMPTS) {\n throw new Error(\n `compaction summarization failed: context compaction recovery attempt cap reached (${MAX_CONTEXT_COMPACTION_RECOVERY_ATTEMPTS})`,\n { cause: attemptError },\n );\n }\n if (!recoveryKind || !publish || !turnStartedPublished) {\n throw attemptError;\n }\n compactionRecoveryAttempts += 1;\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ skipInputOnlyRows: true });\n const progressPersisted = modelOrToolProgressPersisted;\n observability.warn(\"context compaction recovery attempted\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n progressPersisted,\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 compactionFailureMessage: string | null = null;\n try {\n const outcome = await forceContextCompaction(recoveryKind);\n compacted = outcome.compacted;\n if (!outcome.compacted) {\n compactionFailureMessage = compactionFailureReason(outcome.reason);\n }\n } catch (compactError) {\n compactionFailureMessage = compactionFailureReason(compactError instanceof Error ? compactError.message : String(compactError));\n observability.warn(\"context compaction recovery compaction failed\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n error: compactionFailureMessage,\n });\n }\n if (!compacted) {\n const errorMessage = compactionFailureMessage ?? \"compaction summarization failed: compaction produced no replacement history\";\n if (!progressPersisted) {\n throw new Error(errorMessage, { cause: attemptError });\n }\n await publish!([\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, activeTurnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\n activityStatus = \"idle\";\n activityError = attemptError;\n return { status: \"idle\" };\n }\n if (progressPersisted) {\n // The user's intent was live mid-turn — after a successful\n // compaction the turn AUTO-CONTINUES via the same synthesized\n // resume-notice requeue the worker-shutdown checkpoint uses (never\n // the original trigger, so side effects are not replayed). Idle is\n // the fallback, not the default; it remains for: legacy run-state\n // history (resuming the frozen pre-compaction RunState would\n // overflow again), a compaction that could not shrink anything,\n // and a turn that ALREADY resumed from an overflow (loop guard —\n // a second overflow in the same lineage stops churning).\n const triggerPayload =\n trigger.payload && typeof trigger.payload === \"object\" && !Array.isArray(trigger.payload)\n ? trigger.payload as Record<string, unknown>\n : {};\n const compactionResumedTurn = triggerType === \"turn.preempted\"\n && (triggerPayload.reason === \"context_compacted\" || triggerPayload.reason === \"context_overflow_compacted\");\n const canAutoContinue =\n compacted && !compactionResumedTurn && settings.sessionHistorySource === \"items\" && activeTurnId != null;\n if (canAutoContinue) {\n const [preemptedEvent] = await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n turnId: activeTurnId,\n type: \"turn.preempted\",\n payload: {\n triggerEventId: input.triggerEventId,\n reason: \"context_compacted\",\n resumeWithNotice: true,\n text: CONTEXT_OVERFLOW_RESUME_TEXT,\n },\n },\n { turnId: activeTurnId, type: \"session.status.changed\", payload: { status: \"queued\" } },\n ]);\n await requeuePreemptedTurn(db, input.workspaceId, activeTurnId, preemptedEvent ? preemptedEvent.id : input.triggerEventId);\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"queued\", null).catch(() => undefined);\n activityStatus = \"preempted\";\n turnMetricOutcome = \"preempted\";\n observability.info(\"context compaction recovery succeeded by compacting and auto-continuing\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n compacted,\n });\n return { status: \"preempted\" };\n }\n await publish!([\n {\n type: \"turn.failed\",\n payload: {\n error: CONTEXT_WINDOW_OVERFLOW_RECOVERY_MESSAGE,\n code: recoveryKind === \"overflow\" ? \"context_window_overflow_compacted\" : \"context_compacted\",\n retryable: false,\n recovery: \"user_message\",\n compacted,\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, activeTurnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\n activityStatus = \"idle\";\n activityError = attemptError;\n observability.info(\"context compaction recovery succeeded by compacting and idling\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n compacted,\n });\n return { status: \"idle\" };\n }\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 and\n // hand the turn back instead of failing the session. Conversation truth\n // is already dual-written per model response; the final reconcile below\n // bounds the loss to at most the single in-flight model step. The turn\n // is re-queued so the session workflow re-dispatches it on a healthy\n // worker — through a synthesized resume notice when this turn already\n // persisted progress (replaying the original trigger would duplicate\n // input the model has already seen and invite it to redo side effects),\n // or through the original trigger when nothing was persisted yet. This\n // is an explicit checkpoint/resume, not a blind activity retry: the\n // resumed attempt sees everything the first attempt did.\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 requeue, not fail the session. In\n // that early case nothing ran and nothing was checkpointed, so the\n // requeued turn replays the original trigger cleanly. The turn id falls\n // back to the workflow-claimed turn when the local lookup had not\n // finished yet.\n const preemptTurnId = turnId ?? input.turnId;\n // P1.2: a lease supersession during resume (a newer epoch re-established\n // the box concurrently) is NOT a session failure — re-dispatch the turn so\n // it re-resumes by id under the current epoch. Requeue + idle, mirroring\n // the worker-death re-dispatch (any worker re-resumes by id).\n if (error instanceof SandboxLeaseSupersededError && preemptTurnId) {\n try {\n await requeuePreemptedTurn(db, input.workspaceId, preemptTurnId, input.triggerEventId);\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"queued\", null).catch(() => undefined);\n activityStatus = \"preempted\";\n turnMetricOutcome = \"preempted\";\n return { status: \"preempted\" };\n } catch (requeueError) {\n console.error(\"sandbox lease supersession requeue failed; falling back\", requeueError);\n }\n }\n if (isWorkerShutdownCancellation(error) && preemptTurnId) {\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 preemption already accepts.\n const approvalRerun = triggerType === \"user.approvalDecision\";\n let resumeWithNotice = !approvalRerun && settings.sessionHistorySource === \"items\" && persistedHistoryCount > historyCountAtTurnStart;\n if (settings.sessionHistorySource !== \"items\" && stream) {\n // Legacy run-state mode: the resume reads the RunState blob, so\n // the checkpoint must be captured there — including any pending\n // approval interruptions, exactly like the requires_action path,\n // so a shutdown while approvals wait does not erase them. A\n // failed capture falls back to the previous snapshot and a clean\n // re-run of the original trigger.\n try {\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: preemptTurnId,\n serializedRunState: stream.state.toString(),\n pendingApprovals: runtime.serializeApprovals(stream.interruptions ?? []),\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n resumeWithNotice = true;\n } catch {\n resumeWithNotice = false;\n }\n }\n const [preemptedEvent] = await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n turnId: preemptTurnId,\n type: \"turn.preempted\",\n payload: {\n triggerEventId: input.triggerEventId,\n reason: \"worker_shutdown\",\n resumeWithNotice,\n ...(resumeWithNotice ? { text: WORKER_SHUTDOWN_RESUME_TEXT } : {}),\n },\n },\n {\n turnId: preemptTurnId,\n type: \"session.status.changed\",\n payload: { status: \"queued\" },\n },\n ]);\n await requeuePreemptedTurn(db, input.workspaceId, preemptTurnId, resumeWithNotice && preemptedEvent ? preemptedEvent.id : input.triggerEventId);\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"queued\", null).catch(() => undefined);\n activityStatus = \"preempted\";\n turnMetricOutcome = \"preempted\";\n return { status: \"preempted\" };\n } catch (preemptError) {\n // A failing checkpoint/requeue must not surface as an arbitrary\n // activity error around a half-applied preemption (the workflow\n // would fail the session while a requeued turn lingers). Fall\n // through to the cancellation path below: the turn is marked\n // cancelled — also resetting a turn this block already requeued —\n // and the session fails like an uncheckpointed death.\n console.error(\"worker-shutdown preemption failed; falling back to cancellation\", preemptError);\n }\n }\n if (error instanceof CancelledFailure) {\n activityStatus = \"cancelled\";\n activityError = error;\n await flushRuntimeBatcher();\n if (preemptTurnId) {\n await finishTurn(db, input.workspaceId, preemptTurnId, \"cancelled\").catch(() => undefined);\n turnMetricOutcome = \"cancelled\";\n }\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 const runStateSaved = Boolean(maxTurns.serializedRunState) && settings.sessionHistorySource !== \"items\";\n if (maxTurns.serializedRunState && settings.sessionHistorySource !== \"items\") {\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n serializedRunState: maxTurns.serializedRunState,\n pendingApprovals: [],\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n }\n await publish([\n { type: \"turn.completed\", payload: { output: \"\", segmentLimit: \"max_turns\", runStateSaved } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"idle\");\n turnMetricOutcome = \"completed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\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 { status: \"idle\" };\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 = classifyCodexUsageLimitError(error);\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 const serializedRunState = agentsErrorRunState(error);\n const runStateSaved = Boolean(serializedRunState) && settings.sessionHistorySource !== \"items\";\n if (serializedRunState && settings.sessionHistorySource !== \"items\") {\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n serializedRunState,\n pendingApprovals: [],\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n }\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 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 rotating = Boolean(rotation?.rotationEnabled) && (sessionCodex?.pinnedCredentialId == null);\n if (rotating && rotation) {\n const accounts = await listCodexAccountStatuses(db, input.workspaceId).catch(() => []);\n const serving = accounts.find((a) => a.id === effectiveCodexCredentialId) ?? null;\n // Cooldown end (invariant 5): authoritative resets_in_seconds from the 429; else\n // the serving account's soonest cached window reset; else the 1h cap.\n const cachedReset = [serving?.primaryResetAt, serving?.secondaryResetAt]\n .filter((d): d is Date => d instanceof Date && d.getTime() > Date.now())\n .sort((a, b) => a.getTime() - b.getTime())[0] ?? null;\n const until = usageLimit.resetsInSeconds !== null && Number.isFinite(usageLimit.resetsInSeconds) && usageLimit.resetsInSeconds > 0\n ? new Date(Date.now() + Math.ceil(usageLimit.resetsInSeconds) * 1000)\n : (cachedReset ?? new Date(Date.now() + CODEX_USAGE_LIMIT_MAX_RESUME_MS));\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 cooldownPersisted = await setCodexCredentialExhausted(db, input.workspaceId, effectiveCodexCredentialId, until).catch(() => false);\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) => (a.id === effectiveCodexCredentialId ? { ...a, exhaustedUntil: until } : a));\n const decision = chooseRotationActive({\n rotationStrategy: rotation.rotationStrategy as CodexRotationStrategy,\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(db, input.workspaceId, input.sessionId).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 }\n // kind:\"none\" → fall through to today's single-account idle.\n }\n }\n\n const failurePayload = allCappedResetAt\n ? codexUsageLimitFailurePayload(\n { resetsInSeconds: Math.ceil(Math.max(0, allCappedResetAt.getTime() - Date.now()) / 1000) },\n error instanceof Error ? error.message : String(error),\n { allAccounts: true },\n )\n : codexUsageLimitFailurePayload(usageLimit, error instanceof Error ? error.message : String(error));\n await publish([\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 { type: \"turn.failed\", payload: { ...failurePayload, recovery: goalActive ? \"goal_continuation\" : \"user_message\", runStateSaved, ...(rotated ? { rotated: true } : {}) } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\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 { status: \"idle\", continueDelayMs: rotationResumeMs, ...(rotationResumeIdleUntilReset ? { idleUntilReset: true } : {}) };\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 && Number.isFinite(usageLimit.resetsInSeconds) && usageLimit.resetsInSeconds > 0\n ? Math.min(Math.ceil(usageLimit.resetsInSeconds) * 1000, CODEX_USAGE_LIMIT_MAX_RESUME_MS)\n : CODEX_USAGE_LIMIT_MAX_RESUME_MS);\n return { status: \"idle\", continueDelayMs: resumeMs, ...(allCappedResetAt ? { idleUntilReset: true } : {}) };\n }\n return { 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 const runStateSaved = Boolean(error.serializedRunState) && settings.sessionHistorySource !== \"items\";\n if (error.serializedRunState && settings.sessionHistorySource !== \"items\") {\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n serializedRunState: error.serializedRunState,\n pendingApprovals: [],\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n }\n await publish([\n { type: \"turn.completed\", payload: { output: \"\", segmentLimit: \"budget_exhausted\", detail: error.message, runStateSaved } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"idle\");\n turnMetricOutcome = \"completed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\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 { status: \"idle\" };\n }\n // A retryable provider failure (rate limit) is transient backpressure,\n // not a session failure: the in-client retry budget is already\n // exhausted by the time the error reaches here, so fail the turn\n // truthfully but idle the session. With an active goal the continuation\n // loop resumes after a pacing delay; without one the session simply\n // waits for the next user message. Long-lived sessions (a per-customer\n // ops channel between goals) must never go terminal because the\n // provider had a bad minute -- a failed session would reject the very\n // retry message the failure asks for.\n const failure = agentRunFailurePayload(error);\n if (failure.retryable && 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 // Provider errors rarely carry SDK run state; a null falls back to\n // the previous snapshot, same degraded-context contract as the\n // max-turns path above.\n await reconcileConversationTruth();\n const serializedRunState = agentsErrorRunState(error);\n const runStateSaved = Boolean(serializedRunState) && settings.sessionHistorySource !== \"items\";\n if (serializedRunState && settings.sessionHistorySource !== \"items\") {\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n serializedRunState,\n pendingApprovals: [],\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n }\n await publish([\n { type: \"turn.failed\", payload: { ...failure, recovery: goalActive ? \"goal_continuation\" : \"user_message\", runStateSaved } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\n activityStatus = \"idle\";\n activityError = error;\n return goalActive ? { status: \"idle\", continueDelayMs: PROVIDER_BACKPRESSURE_DELAY_MS } : { status: \"idle\" };\n }\n activityStatus = \"failed\";\n activityError = error;\n if (!publish || !turnId || !turnStartedPublished) {\n throw error;\n }\n await publish([\n { type: \"turn.failed\", payload: failure },\n { type: \"session.status.changed\", payload: { status: \"failed\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"failed\", null);\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({ db, bus, settings, observability, wakeSessionWorkflow }, input.workspaceId, input.sessionId, \"failed\", `turn:${turnId}`);\n return { status: \"failed\" };\n } finally {\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.environment_id\": environmentId,\n \"opengeni.duration_ms\": Math.round(durationSeconds * 1000),\n },\n error: activityError,\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 await recordCodexAccountUsage(db, input.workspaceId, effectiveCodexCredentialId, latestCodexUsage)\n .catch(() => undefined);\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, [...connectorNamespaces])\n .catch(() => undefined);\n }\n }\n await preparedTools?.close().catch(() => undefined);\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\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 // P4.3: finalize the on-turn recording BEFORE releasing the box handle\n // (the read+PUT needs the live session). read bytes → storage PUT →\n // updateRecording(available) → publish recording.available; the box file is\n // deleted only after the PUT confirms (F9). Best-effort: a finalize failure\n // emits recording.failed and never masks the turn outcome (F10: the bytes\n // never become a Temporal payload — read+PUT happen here in-process).\n if (activeRecording && resolvedSandbox) {\n try {\n if (!didComputerUse) {\n // Recording gate (P4.3): the turn never drove the desktop (a plain text\n // turn), so the film is a static frame of an untouched screen. DISCARD\n // it — stop ffmpeg, delete the box artifact, drop the row — with NO\n // storage PUT and NO recording.failed (a clean no-op, not a failure).\n await discardRecording({\n db,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n active: activeRecording,\n session: resolvedSandbox.established.session,\n });\n } else {\n const outcome = await finalizeRecording({\n settings,\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n active: activeRecording,\n session: resolvedSandbox.established.session,\n runAs: sandboxRunAs(settings),\n });\n if (publish) {\n await publish(outcome.ok\n ? [{ type: \"recording.available\", payload: outcome.available }]\n : [{ type: \"recording.failed\", payload: { recordingId: activeRecording.recordingId, turnId: activeRecording.turnId, reason: outcome.reason, detail: outcome.detail } }]);\n }\n }\n } catch (finalizeError) {\n console.error(\"recording finalize failed (turn outcome unaffected)\", finalizeError);\n } finally {\n activeRecording = null;\n }\n }\n if (resolvedSandbox) {\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\nexport function agentRunFailurePayload(error: unknown): { error: string; code?: string; retryable?: boolean; detail?: string } {\n const message = error instanceof Error ? error.message : String(error);\n const status = typeof error === \"object\" && error !== null && \"status\" in error\n ? Number((error as { status?: unknown }).status)\n : undefined;\n const code = 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 const usageLimit = classifyCodexUsageLimitError(error);\n if (usageLimit) {\n return codexUsageLimitFailurePayload(usageLimit, message);\n }\n if (status === 429 || code === \"rate_limit_exceeded\" || /(?:too many requests|rate.?limit|\\b429\\b)/i.test(message)) {\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 return { error: message };\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\n/**\n * Recognize an SDK stream event that represents a COMPUTER-USE tool call actually\n * executing — a `run_item_stream_event` carrying a `tool_call_item` whose\n * underlying raw item is a `computer_call` (the @openai/agents computer tool's\n * action: screenshot/click/type/scroll/drag/keypress/move/wait/…). This is the\n * same shape `normalizeSdkEvent` reads (`event.item.rawItem`), matched here against\n * the raw SDK type rather than a tool NAME so it is robust to the computer tool's\n * configured name. Drives the on-turn recording gate (no computer-use → discard).\n */\nfunction isComputerCallStreamEvent(event: unknown): boolean {\n if (!event || typeof event !== \"object\") {\n return false;\n }\n if ((event as { type?: unknown }).type !== \"run_item_stream_event\") {\n return false;\n }\n const item = (event as { item?: { type?: unknown; rawItem?: { type?: unknown } } }).item;\n if (!item || item.type !== \"tool_call_item\") {\n return false;\n }\n return item.rawItem?.type === \"computer_call\";\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(message: string, readonly serializedRunState: string | null) {\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 (!isCodexTurn && entitlements && (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")) {\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 (!isCodexTurn && (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")) {\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(`monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`);\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(settings: Settings, db: ActivityServices[\"db\"], 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}): 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 },\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((resource): resource is Extract<ResourceRef, { kind: \"file\" }> => resource.kind === \"file\");\n if (fileResources.length === 0) {\n return [];\n }\n if (!objectStorage) {\n throw new Error(`${settings.objectStorageBackend} file resources require configured object storage`);\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 (settings.sandboxBackend === \"docker\" && settings.objectStorageBackend === \"s3-compatible\")\n || settings.objectStorageBackend === \"aws-s3\"\n || settings.objectStorageBackend === \"gcs\"\n || (nativeBucketMount && settings.objectStorageBackend === \"azure-blob\");\n}\n\nfunction objectStorageForSandboxDownloads(settings: Settings, objectStorage: ObjectStorage): ObjectStorage {\n if (settings.objectStorageBackend !== \"s3-compatible\" || !settings.objectStorageSandboxEndpoint) {\n return objectStorage;\n }\n return createObjectStorage({\n ...settings,\n objectStorageEndpoint: settings.objectStorageSandboxEndpoint,\n }) ?? objectStorage;\n}\n","import { environmentsEncryptionKeyBytes, parseModelProvidersJson, type RegistryProvider, type Settings } 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_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(db: Database, workspaceId: string, settings: Settings): 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(settings, await listSessionMcpServersForRun(db, workspaceId, sessionId, encryptionKey));\n}\n\nexport function settingsWithSessionMcpServers(settings: Settings, servers: SessionMcpServerForRun[]): 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 ? { requireApproval: server.requireApproval } : {}),\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(db: Database, workspaceId: string, settings: Settings, activeOverride?: boolean): 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 = 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) => ({ id: `${CODEX_MODEL_ID_PREFIX}${slug}`, label: slug, reasoningEffort: true })),\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 { CodexAccountStatus } from \"@opengeni/db\";\n\nexport type CodexRotationStrategy = \"most_remaining\" | \"round_robin\" | \"drain_then_next\";\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\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\n/** The worse-window used percent: weekly binds as hard as 5h, so take the max. null ⇒ 0. */\nfunction bindingUsedPct(acct: CodexAccountStatus): number {\n return Math.max(acct.primaryUsedPercent ?? 0, acct.secondaryUsedPercent ?? 0);\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: CodexAccountStatus): number {\n const primaryRemaining = 100 - (acct.primaryUsedPercent ?? 0);\n const secondaryRemaining = 100 - (acct.secondaryUsedPercent ?? 0);\n return Math.min(primaryRemaining, secondaryRemaining);\n}\n\nfunction cooling(acct: CodexAccountStatus, 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: CodexAccountStatus, 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: CodexAccountStatus, 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 * Eligible = connected/usable (status \"active\", excludes needs_relogin/error) AND\n * not cooling AND under the near-exhaustion threshold on BOTH windows.\n */\nfunction eligible(acct: CodexAccountStatus, nearExhaustionPct: number, now: Date): boolean {\n return acct.status === \"active\" && !cooling(acct, now) && bindingUsedPct(acct) < nearExhaustionPct;\n}\n\n/**\n * The soonest instant `acct` clears EVERY blocking condition: its cooldown end,\n * and each window's reset (only when that window is at/over the threshold). The\n * literal multi-account generalization of #143's single-account resetsInSeconds.\n *\n * GUARANTEE (invariant 4): the result is ALWAYS in the future. A blocking window\n * whose cached reset is null / unknown / already-elapsed does NOT contribute a past\n * instant (the old EPOCH0 seed bug that made earliestReset land in 1970 → a 0\n * continueDelayMs → a tight idle loop). Such a window is treated as clearing after a\n * default cooldown (now + DEFAULT_RESET_COOLDOWN_MS), so the caller always idles a\n * bounded positive time and re-checks (which refreshes usage and self-heals).\n */\nexport function availableAt(acct: CodexAccountStatus, nearExhaustionPct: number, now: Date): Date {\n const nowMs = now.getTime();\n // An unknown/elapsed block clears after a default cooldown, never in the past.\n const defaultClear = new Date(nowMs + DEFAULT_RESET_COOLDOWN_MS);\n const candidates: Date[] = [];\n // An active cooldown only blocks while it is still in the future; a past cooldown\n // self-clears (matches `cooling()`), so it must not pin availableAt to the past.\n if (acct.exhaustedUntil != null && acct.exhaustedUntil.getTime() > nowMs) {\n candidates.push(acct.exhaustedUntil);\n }\n const windowClear = (over: boolean, resetAt: Date | null | undefined) => {\n if (!over) return;\n // Over-threshold window: wait for its KNOWN future reset; a null/elapsed cached\n // reset is unknown → default cooldown (never a past instant).\n candidates.push(resetAt != null && resetAt.getTime() > nowMs ? resetAt : defaultClear);\n };\n windowClear((acct.primaryUsedPercent ?? 0) >= nearExhaustionPct, acct.primaryResetAt);\n windowClear((acct.secondaryUsedPercent ?? 0) >= nearExhaustionPct, acct.secondaryResetAt);\n // Ineligible for a non-quota reason (needs_relogin / error) with no known block, or\n // a cleared cooldown: still idle a bounded cooldown before re-check — never the past.\n if (candidates.length === 0) {\n return defaultClear;\n }\n // Clears EVERY blocking condition ⇒ the MAX of the per-condition clear instants.\n return candidates.reduce((a, b) => (b.getTime() > a.getTime() ? b : a));\n}\n\n/** earliestResetAt across ALL connected accounts (min of each account's availableAt). */\nfunction earliestReset(accounts: CodexAccountStatus[], nearExhaustionPct: number, now: Date): 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 * 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: CodexAccountStatus[];\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 { rotationStrategy, activeCredentialId, priorCredentialId, accounts, nearExhaustionPct, now } = args;\n const usedConnectors = args.usedConnectors ?? [];\n\n if (accounts.length === 0) {\n return { kind: \"none\" };\n }\n\n const eligibles = accounts.filter((acct) => eligible(acct, nearExhaustionPct, now));\n\n // Healthy-active fast path (minimal churn, all strategies): a rotation-enabled\n // session whose active account is still eligible does NOT rotate — no pointer\n // move, no switch event. Steady-state stays as cheap as a non-rotation turn\n // save the in-memory ranking. (Skipped for round_robin/drain which anchor on\n // the prior account, but most_remaining is the default + correctness path.)\n const activeRow = activeCredentialId ? accounts.find((acct) => acct.id === activeCredentialId) ?? null : null;\n\n const decide = (chosen: CodexAccountStatus | undefined): RotationDecision => {\n if (!chosen) {\n return { kind: \"allCapped\", earliestResetAt: earliestReset(accounts, nearExhaustionPct, now) };\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 { kind: \"allCapped\", earliestResetAt: earliestReset(accounts, nearExhaustionPct, now) };\n }\n const priorIdx = priorCredentialId ? accounts.findIndex((acct) => acct.id === priorCredentialId) : -1;\n const ordered = priorIdx >= 0\n ? [...accounts.slice(priorIdx + 1), ...accounts.slice(0, priorIdx + 1)]\n : accounts;\n const chosen = ordered.find((acct) => eligible(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 ? accounts.find((acct) => acct.id === priorCredentialId) : undefined;\n if (priorRow && eligible(priorRow, nearExhaustionPct, now)) {\n return decide(priorRow);\n }\n return decide(eligibles[0]);\n }\n\n // most_remaining (default + the correctness path).\n // Healthy-active fast path UNCHANGED (no-thrash): a session whose active account\n // is still eligible never switches — not even for connector coverage. Coverage\n // matters ONLY on the must-move branch below.\n if (activeRow && eligible(activeRow, nearExhaustionPct, now)) {\n return { kind: \"active\", credentialId: activeRow.id, moved: false };\n }\n // Active is capped/near-cap/cooling/missing → must move. Two-tier coverage pick\n // over 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, max bindingRemaining, ties broken by list (created_at)\n // order via a stable reduce — byte-identical to P3 when usedConnectors is empty\n // (Tier 1 == all eligibles).\n const covering = eligibles.filter((acct) => covers(acct, usedConnectors));\n const pool = covering.length > 0 ? covering : eligibles;\n const chosen = pool.reduce<CodexAccountStatus | undefined>((best, acct) => {\n if (!best) {\n return acct;\n }\n return bindingRemaining(acct) > bindingRemaining(best) ? acct : best;\n }, undefined);\n return decide(chosen);\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 type { ResourceRef, SessionStatus, ToolRef } 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(prompt: string, resources: ResourceRef[], tools: ToolRef[], taskId: string, runId: string): Record<string, unknown> {\n return {\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 nextSessionHistoryPosition,\n type Database,\n} from \"@opengeni/db\";\nimport {\n SUMMARY_BUFFER_TOKENS,\n buildCompactionPromptInput,\n buildDeterministicFallbackCompactionHistory,\n buildCompactionReplacementHistory,\n decideClientCompaction,\n estimateTokens,\n sanitizeHistoryItemsForModel,\n summarizeForCompaction,\n type CompactionItem,\n} from \"@opengeni/runtime\";\nimport { resolveContextCompactionMode, type Settings } from \"@opengeni/config\";\n\nexport type MaybeCompactResult =\n | { compacted: false; reason: string }\n | {\n compacted: true;\n supersededFrom: number;\n summaryPosition: number;\n signalTokens: number;\n thresholdTokens: number;\n method: \"summary\" | \"fallback\";\n estimatedTokensBefore: number;\n estimatedTokensAfter: number;\n };\n\n/**\n * Pre-turn client-side context compaction (the Azure path).\n *\n * Runs BEFORE the model call when the resolved compaction mode is \"client\".\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 * Required compactions are fail-closed on the summarizer: full rendered\n * transcript, hard-trim rendered retry, then deterministic non-LLM fallback.\n * DB errors still throw to the caller; \"compacted:false\" is reserved for\n * structural no-ops or impossible shrink, not summarizer failures.\n *\n * There is no kept assistant/tool tail in client mode now. Assistant messages,\n * tool calls/results, reasoning, and images stay only in inactive audit rows.\n */\nexport type CompactionSummarizerOptions = {\n maxTranscriptTokens?: number;\n attempt: \"full\" | \"hard_trim\";\n};\n\nexport type CompactionSummarizer = (\n settings: Settings,\n input: CompactionItem[],\n options?: CompactionSummarizerOptions,\n) => Promise<string | null>;\n\nexport async function maybeCompactContext(\n db: Database,\n settings: Settings,\n scope: { accountId: string; workspaceId: string; sessionId: string; turnId?: string | null },\n lastInputTokens: number | null,\n // Injectable for tests; defaults to the real provider-aware model call.\n summarize: CompactionSummarizer = (s, m, o) => summarizeForCompaction(s, m, {\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n ...(o?.maxTranscriptTokens ? { maxTranscriptTokens: o.maxTranscriptTokens } : {}),\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: { force?: boolean; requireShrink?: boolean } = {},\n): Promise<MaybeCompactResult> {\n if (resolveContextCompactionMode(settings) !== \"client\") {\n return { compacted: false, reason: \"mode_not_client\" };\n }\n\n const active = await getActiveSessionHistoryItems(db, scope.workspaceId, scope.sessionId);\n if (active.length === 0) {\n return { compacted: false, reason: \"no_history\" };\n }\n\n const items = sanitizeHistoryItemsForModel(active.map((row) => row.item) as CompactionItem[]);\n const decision = decideClientCompaction({\n items,\n lastInputTokens,\n contextWindowTokens: settings.contextWindowTokens,\n contextReservedOutputTokens: settings.contextReservedOutputTokens,\n contextCompactionThresholdRatio: settings.contextCompactionThresholdRatio,\n ...(options.force ? { force: true } : {}),\n });\n if (!decision.shouldCompact) {\n return { compacted: false, reason: decision.reason };\n }\n\n const promptInput = buildCompactionPromptInput(items);\n const estimatedTokensBefore = estimateTokens(items);\n const shrinkBaselineTokens = Math.max(estimatedTokensBefore, decision.signalTokens);\n const requireShrink = options.requireShrink || decision.reason === \"above_threshold\";\n let summarizerFailure = \"summarizer returned no summary\";\n let summaryBody: string | null = null;\n\n const fullAttempt = await runSummarizerAttempt(summarize, settings, promptInput, { attempt: \"full\" });\n if (fullAttempt.summary) {\n summaryBody = fullAttempt.summary;\n } else {\n summarizerFailure = fullAttempt.failure;\n const hardTrimBudget = Math.max(1, Math.floor(Math.max(1, decision.thresholdTokens) * 0.5));\n const retryAttempt = await runSummarizerAttempt(summarize, settings, promptInput, {\n attempt: \"hard_trim\",\n maxTranscriptTokens: hardTrimBudget,\n });\n if (retryAttempt.summary) {\n summaryBody = retryAttempt.summary;\n } else {\n summarizerFailure = retryAttempt.failure || summarizerFailure;\n }\n }\n\n let replacementHistory: CompactionItem[] | null = null;\n let method: \"summary\" | \"fallback\" = \"summary\";\n if (summaryBody) {\n const summaryReplacement = buildCompactionReplacementHistory(items, summaryBody);\n const summaryEstimate = estimateTokens(summaryReplacement);\n if (!requireShrink || summaryEstimate < shrinkBaselineTokens) {\n replacementHistory = summaryReplacement;\n } else {\n summarizerFailure = `summary replacement did not reduce context signal (${summaryEstimate} >= ${shrinkBaselineTokens})`;\n }\n }\n\n if (!replacementHistory) {\n method = \"fallback\";\n const fallbackTargetTokens = Math.max(\n 1,\n Math.min(\n Math.max(1, Math.floor(shrinkBaselineTokens * 0.5)),\n Math.max(1, Math.floor(Math.max(1, decision.thresholdTokens) * 0.5)),\n ),\n );\n replacementHistory = buildDeterministicFallbackCompactionHistory({\n items,\n cause: summarizerFailure,\n targetTokens: fallbackTargetTokens,\n });\n }\n\n const estimatedTokensAfter = estimateTokens(replacementHistory);\n if (requireShrink && estimatedTokensAfter >= shrinkBaselineTokens) {\n return { compacted: false, reason: `compaction summarization failed: fallback did not reduce context signal (${estimatedTokensAfter} >= ${shrinkBaselineTokens})` };\n }\n\n const summaryItem = replacementHistory.at(-1);\n if (!summaryItem) {\n return { compacted: false, reason: `compaction summarization failed: ${summarizerFailure}` };\n }\n const nextPosition = await nextSessionHistoryPosition(db, scope.workspaceId, scope.sessionId);\n const replacementItems = replacementHistory.slice(0, -1).map((item, index) => ({\n position: nextPosition + index,\n item,\n }));\n const summaryPosition = nextPosition + replacementItems.length;\n\n await applyContextCompaction(db, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n sessionId: scope.sessionId,\n turnId: scope.turnId ?? null,\n boundaryPosition: nextPosition,\n replacementItems,\n summaryPosition,\n summaryItem: summaryItem as Record<string, unknown>,\n });\n\n return {\n compacted: true,\n supersededFrom: nextPosition,\n summaryPosition,\n signalTokens: decision.signalTokens,\n thresholdTokens: decision.thresholdTokens,\n method,\n estimatedTokensBefore,\n estimatedTokensAfter,\n };\n}\n\nasync function runSummarizerAttempt(\n summarize: CompactionSummarizer,\n settings: Settings,\n promptInput: CompactionItem[],\n options: CompactionSummarizerOptions,\n): Promise<{ summary: string | null; failure: string }> {\n try {\n const summary = await summarize(settings, promptInput, options);\n if (summary && summary.trim().length > 0) {\n return { summary, failure: \"\" };\n }\n return { summary: null, failure: \"summarizer returned no summary\" };\n } catch (error) {\n return { summary: null, failure: error instanceof Error ? error.message : String(error) };\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 GitCredentials,\n type ResourceRef,\n type SandboxSecrets,\n} from \"@opengeni/contracts\";\nimport {\n loadWorkspaceEnvironmentForRun as loadWorkspaceEnvironmentForRunFromDb,\n type Database,\n type WorkspaceEnvironmentForRun,\n} from \"@opengeni/db\";\nimport {\n createGitHubAppInstallationToken,\n githubAppBotIdentity,\n} 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\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 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. `= {}` default so the non-optional reads below are safe.\n options: {\n skipGitHubToken?: boolean;\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n sessionId?: string;\n runId?: string;\n } = {},\n): Promise<{ environment: Record<string, string>; gitToken?: string; toolspaceToken?: string }> {\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 GitHub 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): the run-scoped GitHub App installation token is NO LONGER\n // layered into the box/agent MANIFEST env (no GH_TOKEN/GITHUB_TOKEN/GIT_CONFIG_*\n // extraheader). It is minted ONCE per turn and returned as `gitToken`; the caller\n // threads it OFF-MANIFEST as a clone-seed exec env (OPENGENI_GIT_TOKEN_SEED) so the\n // clone hook writes it to a stable FILE ($OPENGENI_GIT_TOKEN_FILE), and git auth\n // flows through GIT_ASKPASS -> that file. The manifest carries only the stable\n // pointers (GIT_ASKPASS, GIT_TERMINAL_PROMPT, identity, and — via the shared base —\n // OPENGENI_GIT_TOKEN_FILE), so the token VALUE never rides the manifest and the\n // SDK's per-turn provided-session env delta stays empty even though the token\n // rotates. The agent can refresh the token mid-turn via the `github_token` MCP tool.\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 the platform GitHub token\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(settings, options.scope.workspaceId);\n }\n const selection = githubRepositorySelection(resources);\n // NO-TOKEN SKIP (Stage D, change B): when the turn's EFFECTIVE compute backend is\n // a connected machine (selfhosted), the platform GitHub App installation token is\n // INERT — exec routes over NATS to the user's machine, which uses ITS OWN git\n // credentials, and the box that the token would auth is never created. So skip the\n // (network) token mint entirely and return the STABLE base env (no gitToken). 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 (!selection || options.skipGitHubToken) {\n return { environment, ...(toolspaceToken ? { toolspaceToken } : {}) };\n }\n // Run-scoped sandbox preparation for GitHub App repository resources. When a\n // host binds `gitCredentials`, the HOST mints the installation token (BYO\n // GitHub App); otherwise OpenGeni self-mints from `settings` (today's path). A\n // SINGLE token is minted per turn and returned as `gitToken` (seeded to the box's\n // token file by the caller's clone hook) — NOT layered into the manifest env.\n let token: string;\n let identity: { name: string; email: string } | null;\n if (options?.gitCredentials && options.scope) {\n const minted: GitCredentials = await options.gitCredentials({\n accountId: options.scope.accountId,\n workspaceId: options.scope.workspaceId,\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n });\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 token = minted.token;\n identity = minted.identity ?? githubAppBotIdentity(settings);\n } else {\n token = await createGitHubAppInstallationToken(settings, {\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n });\n identity = githubAppBotIdentity(settings);\n }\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, identity);\n return { environment, gitToken: token, ...(toolspaceToken ? { toolspaceToken } : {}) };\n}\n\nfunction githubRepositorySelection(resources: ResourceRef[]): { installationId: number; repositoryIds: number[] } | null {\n const selected = resources.flatMap((resource) => {\n if (resource.kind !== \"repository\") {\n return [];\n }\n const installationId = positiveInteger(resource.githubInstallationId);\n const repositoryId = positiveInteger(resource.githubRepositoryId);\n return installationId && repositoryId ? [{ installationId, repositoryId }] : [];\n });\n if (selected.length === 0) {\n return null;\n }\n const installationId = selected[0]!.installationId;\n if (selected.some((item) => item.installationId !== installationId)) {\n throw new Error(\"GitHub App repository resources must belong to one installation\");\n }\n return {\n installationId,\n repositoryIds: selected.map((item) => item.repositoryId),\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 { configuredStaticUsageLimits, type Settings } from \"@opengeni/config\";\nimport {\n mergeToolRefs,\n reasoningEffortForMetadata,\n type SessionGoal,\n type ToolRef,\n} from \"@opengeni/contracts\";\nimport {\n enqueueSessionTurn,\n evaluateGoalContinuation,\n getBillingBalance,\n getSessionEvent,\n getSessionGoal,\n isCodexBilledTurn,\n recordUsageEvent,\n requireSession,\n setSessionGoalLastContinuationTurn,\n setSessionGoalStatus,\n sumUsageQuantity,\n type Database,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents, type EventBus } from \"@opengeni/events\";\nimport type {\n ActivityServices,\n MaybeContinueGoalInput,\n MaybeContinueGoalResult,\n PauseGoalForInterruptInput,\n} from \"./types\";\n\nexport function createGoalActivities(services: () => Promise<ActivityServices>) {\n async function maybeContinueGoal(input: MaybeContinueGoalInput): 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 can read the\n // continuation turn's model (session.model). Kept below the goal-less fast\n // path above so a non-goal session still skips this read entirely.\n const session = await requireSession(db, input.workspaceId, input.sessionId);\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({ db, settings, workspaceId: input.workspaceId, model: session.model });\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(settings, db, input.accountId, input.workspaceId, isCodexRun);\n const decision = await evaluateGoalContinuation(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n defaultMaxAutoContinuations: settings.goalMaxAutoContinuations ?? null,\n noProgressLimit: settings.goalNoProgressLimit,\n 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 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 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 [continuationEvent] = await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [{\n type: \"goal.continuation\",\n payload: {\n goalId: decision.goal.id,\n text: prompt,\n autoContinuation: decision.autoContinuation,\n maxAutoContinuations: decision.cap,\n goalVersion: decision.goal.version,\n },\n }]);\n if (!continuationEvent) {\n throw new Error(\"failed to append goal continuation trigger event\");\n }\n const turn = await enqueueSessionTurn(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n triggerEventId: continuationEvent.id,\n temporalWorkflowId: input.workflowId,\n source: \"goal\",\n prompt,\n resources: [],\n // Continuations keep the session tool surface and force the first-party\n // server so the goal_complete/goal_pause escape hatches stay reachable.\n tools: withFirstPartyTools(settings, session.tools),\n model: session.model,\n reasoningEffort: reasoningEffortForMetadata(session.metadata, settings.openaiReasoningEffort),\n sandboxBackend: session.sandboxBackend,\n metadata: { goalId: decision.goal.id, autoContinuation: decision.autoContinuation },\n });\n await setSessionGoalLastContinuationTurn(db, input.workspaceId, input.sessionId, turn.id);\n await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [{\n type: \"turn.queued\",\n turnId: turn.id,\n payload: { turnId: turn.id, triggerEventId: continuationEvent.id, source: turn.source },\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_turn\",\n sourceResourceId: turn.id,\n idempotencyKey: `agent_run.created:goal:${input.workspaceId}:${turn.id}`,\n });\n return { action: \"continue\" };\n }\n\n async function pauseGoalForInterrupt(input: PauseGoalForInterruptInput): Promise<void> {\n const { db, bus } = await services();\n if (input.triggerEventId) {\n const trigger = await getSessionEvent(db, input.workspaceId, input.triggerEventId);\n if (isSteerInterrupt(trigger)) {\n return;\n }\n }\n await pauseActiveGoalOnInterrupt(db, bus, input.workspaceId, input.sessionId);\n }\n\n return {\n maybeContinueGoal,\n pauseGoalForInterrupt,\n };\n}\n\n/**\n * True when an interrupt's trigger event is a STEER: `user.interrupt` tagged\n * `reason: \"steer\"`, sent by `OpenGeniClient.steerMessage`. Steering cancels\n * the running turn only to deliver the steered message next — it redirects\n * the work rather than stopping it, so an active goal keeps going. Every\n * other user interrupt (the stop button, a plain `interrupt()` call) is the\n * explicit act of stopping and pauses the goal.\n */\nexport function isSteerInterrupt(trigger: { type: string; payload: unknown } | null | undefined): boolean {\n if (!trigger || trigger.type !== \"user.interrupt\") {\n return false;\n }\n const payload = trigger.payload;\n return typeof payload === \"object\" && payload !== null && (payload as { reason?: unknown }).reason === \"steer\";\n}\n\n/**\n * A user interrupt is the explicit act of stopping, so it pauses an active\n * goal. Shared by the idle-interrupt activity and `interruptActiveTurn` so the\n * loop never auto-continues a goal the user just stopped. Callers gate this\n * on `isSteerInterrupt` first: steer interrupts must NOT pause the goal.\n * No-op when the session has no goal or it is not active.\n */\nexport async function pauseActiveGoalOnInterrupt(db: Database, bus: EventBus, workspaceId: string, sessionId: string): Promise<void> {\n const goal = await getSessionGoal(db, workspaceId, sessionId);\n if (!goal || goal.status !== \"active\") {\n return;\n }\n const { goal: paused, changed } = await setSessionGoalStatus(db, workspaceId, sessionId, {\n status: \"paused\",\n pausedReason: \"user_interrupt\",\n });\n if (changed) {\n await appendAndPublishEvents(db, bus, workspaceId, sessionId, [{\n type: \"goal.paused\",\n payload: {\n goalId: paused.id,\n actor: \"user\",\n reason: \"user_interrupt\",\n autoContinuations: paused.autoContinuations,\n noProgressStreak: paused.noProgressStreak,\n },\n }]);\n }\n}\n\nexport function goalContinuationPrompt(goal: SessionGoal, autoContinuation: number, cap: number | null): 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 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(settings: Settings, db: Database, accountId: string, workspaceId: string, isCodexRun: boolean): 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 (!isCodexRun && (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")) {\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(db: Database, workspaceId: string): 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((pack) => typeof pack.sandboxImage === \"string\" && pack.sandboxImage.trim().length > 0);\n if (imagePacks.length > 1) {\n const ids = imagePacks.map((pack) => pack.id).sort().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(db: Database, workspaceId: string): 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(settings: Settings, sandboxImage: string | null): Settings {\n if (!sandboxImage) {\n return settings;\n }\n return {\n ...settings,\n dockerImage: sandboxImage,\n modalImageRef: sandboxImage,\n };\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { Session, SessionGoal } from \"@opengeni/contracts\";\nimport { getSession, getSessionGoal, wakeParentSessionForChildCompletion, type Database } 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\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's queued\n * turn is delivered by the DB wake; signalling the parent's workflow\n * (signalWithStart) ensures a parent whose workflow already completed gets a\n * fresh run to claim it. Failures here never fail the child: the wake is a\n * best-effort nudge layered on durable DB state.\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 const clientEventId = `child-completion:${childSessionId}:${episodeKey ?? child.lastSequence}`;\n const result = await wakeParentSessionForChildCompletion(svc.db, {\n workspaceId,\n parentSessionId: child.parentSessionId,\n clientEventId,\n text: childCompletionWakeText(child, goal, terminalStatus),\n childCompletion: childCompletionPayload(child, goal, terminalStatus),\n reasoningEffortFallback: svc.settings.openaiReasoningEffort,\n });\n if (!result.delivered) {\n return;\n }\n await svc.bus.publish(workspaceId, child.parentSessionId, result.events);\n if (svc.wakeSessionWorkflow) {\n await svc.wakeSessionWorkflow({\n accountId: child.accountId,\n workspaceId,\n sessionId: child.parentSessionId,\n workflowId: result.temporalWorkflowId,\n });\n }\n svc.observability.info(\"Woke parent session on worker completion\", {\n childSessionId,\n parentSessionId: child.parentSessionId,\n terminalStatus,\n });\n } catch (error) {\n // A parent-wake failure must never fail the child's terminal activity.\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\nfunction childCompletionPayload(child: Session, goal: SessionGoal | null, terminalStatus: \"idle\" | \"failed\"): Record<string, unknown> {\n return {\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\nfunction childCompletionWakeText(child: Session, goal: SessionGoal | null, terminalStatus: \"idle\" | \"failed\"): 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(`A worker session you spawned has COMPLETED its goal. Worker session id: ${child.id}.`);\n } else if (goal?.status === \"paused\") {\n lines.push(`A worker session you spawned has PAUSED its goal and gone idle. Worker session id: ${child.id}.`);\n } else {\n lines.push(`A worker session you spawned has finished its work and gone idle. Worker session id: ${child.id}.`);\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 lines.push(\"Read the worker's session events/notebook output for its result, then continue. If your own goal was paused awaiting this worker, resume it now.\");\n return lines.join(\"\\n\");\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(Object.entries(payload).map(([key, value]) => [key, redact(value)]));\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 { Settings } from \"@opengeni/config\";\nimport { contextInputBudgetTokens, resolveContextCompactionMode } from \"@opengeni/config\";\nimport type { FileAsset, ResourceRef } from \"@opengeni/contracts\";\nimport {\n getActiveSessionHistoryItems,\n getLatestRunState,\n getSandboxSessionEnvelope,\n getSessionEvent,\n requireFile,\n type Database,\n} from \"@opengeni/db\";\nimport { stripReasoningEncryptedContent, stripReasoningIdentityFromSerializedRunState, neutralizeToolSearchItemsInSerializedRunState, type OpenGeniRuntime } 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 to replay on a run-state path (approval resume\n * or the items-mode run-state fallback), applying the SAME cross-account rule the\n * history-items path uses. The blob 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(stripReasoningIdentityFromSerializedRunState(state.serializedRunState));\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 when `state.history` was seeded from the run-state BLOB\n * (approval resume, the items-mode run-state fallback, or run_state mode): 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 async function turnInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: Awaited<ReturnType<typeof getSessionEvent>>,\n settings?: Settings,\n current: TurnCodexAccount = NON_CODEX_TURN,\n): Promise<PreparedTurnInput> {\n if (!trigger) {\n throw new Error(\"Missing trigger event\");\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 text = await userMessageTextWithAttachments(\n db,\n trigger.workspaceId,\n payload.text,\n Array.isArray(payload.resources) ? payload.resources as ResourceRef[] : [],\n );\n return await messageInput(db, runtime, agent, trigger, text, settings, current);\n }\n if (trigger.type === \"goal.continuation\") {\n const payload = trigger.payload as { text?: unknown };\n if (typeof payload.text !== \"string\" || payload.text.trim().length === 0) {\n throw new Error(\"goal.continuation payload is missing text\");\n }\n // Threading the stored conversation keeps the agent's full context across\n // continuations — this is what makes \"keep working\" coherent.\n return await messageInput(db, runtime, agent, trigger, payload.text, settings, current);\n }\n if (trigger.type === \"turn.preempted\") {\n const payload = trigger.payload as { text?: unknown };\n if (typeof payload.text !== \"string\" || payload.text.trim().length === 0) {\n throw new Error(\"turn.preempted payload is missing text\");\n }\n // A turn re-entering after a graceful worker shutdown checkpointed it\n // mid-flight: thread the stored conversation (which includes the turn's\n // original input and its progress so far) behind a resume notice.\n return await messageInput(db, runtime, agent, trigger, payload.text, settings, 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\n/**\n * Build a message/continuation turn input from the configured history source.\n * Items mode reads conversation truth from session_history_items and the\n * sandbox envelope from its own store; a session with no stored items yet\n * (created before dual-write, or its first turn) falls back to the RunState\n * blob for this turn — the turn-end reconciliation then backfills its items,\n * so the fallback is self-eliminating (issue #35).\n */\nasync function messageInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: NonNullable<Awaited<ReturnType<typeof getSessionEvent>>>,\n text: string,\n settings?: Settings,\n current: TurnCodexAccount = NON_CODEX_TURN,\n): Promise<PreparedTurnInput> {\n // Read-path budget guard (the last-resort backstop behind best-effort pre-turn\n // compaction): supply B only when the client-side compaction path is active\n // (Azure). On the OpenAI server path the SDK manages the window, so we leave\n // the guard off and never crudely trim. Undefined = guard disabled.\n const inputBudgetTokens = readPathBudgetTokens(settings);\n if (settings?.sessionHistorySource === \"items\") {\n // Active rows only: after a client-side context compaction this is\n // [retained user messages..., active summary]; superseded rows stay in the\n // table as an audit trail but never reach the model.\n const stored = await getActiveSessionHistoryItems(db, trigger.workspaceId, trigger.sessionId);\n if (stored.length > 0) {\n const envelope = await getSandboxSessionEnvelope(db, trigger.workspaceId, trigger.sessionId);\n // Cross-account reasoning strip: drop any carried reasoning item NOT\n // produced by THIS turn's codex account (foreign reasoning is dropped\n // whole — id + blob; a foreign blob 400s the codex backend and a foreign\n // rs_ id is rejected by the Responses backend). No-op for single-account\n // workspaces, unchanged-account turns, and non-codex turns over a history\n // with no codex reasoning (every producer == current) — those replay\n // byte-for-byte. Message and tool content is never touched.\n const historyItems = applyCodexHistoryStrip(stored, current);\n return {\n input: await runtime.prepareInput(\n agent,\n {\n kind: \"message\",\n text,\n historyItems: historyItems as any,\n sandboxEnvelope: envelope,\n },\n inputBudgetTokens ? { inputBudgetTokens } : {},\n ),\n // state.history seeded from the cross-account-STRIPPED active items: the\n // reconcile watermark must apply the SAME strip (HOLE D).\n modelHistoryFromItems: true,\n };\n }\n }\n const latestState = await getLatestRunState(db, trigger.workspaceId, trigger.sessionId);\n return {\n input: await runtime.prepareInput(\n agent,\n {\n kind: \"message\",\n text,\n // Cross-account run-state strip (HOLE C): the items-mode fallback replays\n // the RunState blob when no history rows exist yet. If the resuming turn's\n // codex account differs from the one that froze the blob, neutralize its\n // account-bound reasoning before replay (else byte-for-byte).\n serializedRunState: latestState ? resumeRunStateForCodexAccount(latestState, current) : null,\n },\n inputBudgetTokens ? { inputBudgetTokens } : {},\n ),\n // state.history seeded from the run-state BLOB (or empty): NOT the stripped\n // items, so the reconcile watermark must NOT apply the cross-account strip\n // (HOLE E). On this fallback the active rows are empty anyway (the read above\n // took the items branch when stored.length > 0), so strip-or-not both yield 0.\n modelHistoryFromItems: false,\n };\n}\n\n/**\n * The usable input-token budget B to hand the read-path guard, or undefined\n * when the guard should stay off. Active only when the resolved compaction mode\n * is \"client\" (the Azure path that runs our own compaction); on the server path\n * the SDK enforces the window, and with no settings we can't compute B.\n */\nfunction readPathBudgetTokens(settings?: Settings): number | undefined {\n if (!settings || resolveContextCompactionMode(settings) !== \"client\") {\n return undefined;\n }\n const budget = contextInputBudgetTokens(settings);\n return budget > 0 ? budget : undefined;\n}\n\nexport async function userMessageTextWithAttachments(\n db: Database,\n workspaceId: string,\n text: string,\n resources: ResourceRef[],\n): Promise<string> {\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(`- ${file.filename} (${file.contentType}, ${file.sizeBytes} bytes): ${sandboxFilePath(resource, file)}`);\n }\n if (attachedFiles.length === 0) {\n return text;\n }\n return [\n text,\n \"\",\n \"Attached files are available in the sandbox:\",\n ...attachedFiles,\n ].join(\"\\n\");\n}\n\nfunction sandboxFilePath(resource: Extract<ResourceRef, { kind: \"file\" }>, file: FileAsset): 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\nexport function createRuntimeBatcher(flushEvents: (events: AppendEventInput[]) => Promise<void>) {\n let pending: AppendEventInput[] = [];\n let lastFlush = Date.now();\n const structural = new Set<SessionEventType>([\n \"agent.message.delta\",\n \"agent.reasoning.delta\",\n \"sandbox.command.output.delta\",\n // Channel-A PTY bytes flush promptly (P4.4) — a terminal stream is useless\n // batched 33ms behind; the structural set bypasses the batcher's coalesce.\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 pending.push({ type: event.type, payload: event.payload });\n const elapsed = Date.now() - lastFlush;\n if (pending.length >= 50 || elapsed >= 33 || structural.has(event.type)) {\n await flush();\n }\n },\n flush,\n };\n\n async function flush() {\n if (pending.length === 0) {\n return;\n }\n const events = pending;\n pending = [];\n lastFlush = Date.now();\n await flushEvents(events);\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(context: Context | null, details: Record<string, unknown>): 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>(iterator: AsyncIterator<T>, context: Context | null): Promise<IteratorResult<T>> {\n if (!context) {\n return await iterator.next();\n }\n return await Promise.race([\n iterator.next(),\n context.cancelled,\n ]);\n}\n","// apps/worker/src/sandbox-resume.ts — the stateless per-turn resume-by-id path.\n//\n// This is the turn-side half of the P1.2 ownership inversion. There is NO class,\n// NO timers, NO per-session owner, NO Map<id, owner> — every turn is a\n// self-contained critical section run by ANY pool worker:\n//\n// 1. acquireLease (group-keyed) under the DB FOR UPDATE + cold->warming CAS —\n// the SOLE double-spawn guard (P1.1).\n// 2. establishSandboxSessionFromEnvelope — resume the one box BY ID (warm\n// reattach, R4-safe) or cold-restore from snapshot on a provider NotFound.\n// 3. (spawner) ensureDisplayStack + exposeStreamPort, then commitWarmingToWarm\n// (the lease_epoch++ fence + folds the resume envelope onto the lease). The\n// ATTACHED/REARMED path RE-ensures the display stack too (idempotent) so a\n// computer-use turn always finds a live :0 even on a box first warmed by a\n// non-desktop op or after a snapshot rollover dropped the X stack.\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 readLease,\n recordWarmingSandboxCreated,\n releaseLeaseHolder,\n SandboxLeaseSupersededError,\n type Database,\n type LeaseHolderKind,\n} from \"@opengeni/db\";\nimport {\n establishSandboxSessionFromEnvelope,\n ensureDisplayStack as ensureDisplayStackOnBox,\n desktopCapableBackend,\n serializeEstablishedSandboxEnvelope,\n DisplayStackError,\n DisplayStackUnsupportedError,\n buildStreamUrl,\n StreamPortUnavailableError,\n modalSandboxAttributionEnvironment,\n tagModalSandbox,\n type EstablishedSandboxSession,\n type ExposedPortEndpoint,\n type RuntimeMetricsHooks,\n} from \"@opengeni/runtime\";\nimport { DESKTOP_STREAM_PORT } from \"@opengeni/contracts\";\n\nexport { DESKTOP_STREAM_PORT };\n\n// Re-exported for callers that just want the ack-kind union.\nexport type ResumeHolderKind = LeaseHolderKind;\n\n/** The minimal services surface resumeBoxForTurn needs. A subset of\n * ActivityServices so a test (and the API later) can pass a lean bag. */\nexport type SandboxResumeServices = {\n db: Database;\n settings: Settings;\n sandboxMetrics?: RuntimeMetricsHooks;\n};\n\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\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(public readonly backend: string, public readonly timeoutMs: number) {\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// Bounded poll while a sibling spawner is mid cold-restore. The wait budget is\n// user-facing and separate from the lease TTL heartbeat/reaper horizon.\nconst WARMING_POLL_INTERVAL_MS = 250;\n\nasync function sleep(ms: number): Promise<void> {\n await new Promise<void>((resolve) => setTimeout(resolve, ms));\n}\n\nasync function terminateEstablishedSandbox(established: EstablishedSandboxSession | null): Promise<boolean> {\n if (!established) {\n return true;\n }\n const client = established.client as { delete?: (state: unknown) => Promise<unknown> };\n if (typeof client.delete === \"function\" && established.sessionState !== undefined) {\n try {\n await client.delete(established.sessionState);\n return true;\n } catch {\n return false;\n }\n }\n const session = established.session as {\n 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(metrics: RuntimeMetricsHooks | undefined, error: unknown): 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 workspaceArchiveFromEnvelope(envelope: Record<string, unknown> | null | undefined): string | null {\n const sessionState = envelope && typeof envelope.sessionState === \"object\" && envelope.sessionState !== null\n ? envelope.sessionState as Record<string, unknown>\n : null;\n const archive = sessionState?.workspaceArchive;\n return typeof archive === \"string\" && archive.length > 0 ? archive : null;\n}\n\nfunction preserveWorkspaceArchiveOnInterimResumeState(\n resumeState: Record<string, unknown> | null,\n archiveSource: Record<string, unknown> | null,\n): Record<string, unknown> | null {\n const archive = workspaceArchiveFromEnvelope(archiveSource);\n if (!archive) {\n return resumeState;\n }\n const existingSessionState = 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 workspaceArchive: archive,\n },\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 unique-per-execution id (the Temporal activityId for a turn).\n */\nexport async function resumeBoxForTurn(\n services: SandboxResumeServices,\n ids: ResumeBoxIds,\n kind: LeaseHolderKind,\n holderId: string,\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 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: 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 leaseTtlMs,\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 // expose the stream port, then commit warm (lease_epoch++).\n if (acquired.role === \"spawner\") {\n const expectedEpoch = acquired.lease.leaseEpoch;\n let createdEstablished: EstablishedSandboxSession | null = null;\n if (ids.environment && ids.backend === \"modal\") {\n Object.assign(ids.environment, modalSandboxAttributionEnvironment({\n leaseId: acquired.lease.id,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n }));\n }\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 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 = preserveWorkspaceArchiveOnInterimResumeState(\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 });\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 await ensureDisplayStack(settings, established);\n const endpoint = await exposeStreamPort(settings, 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 resumeEnvelope = (await serializeEstablishedSandboxEnvelope(established)) ?? envelope ?? null;\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 dataPlaneUrl: endpoint?.url ?? 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(error, ids.backend, settings.sandboxWarmingTimeoutMs);\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; requeue the turn instead of\n // 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 const envelope =\n live?.resumeState ?? (await getSandboxSessionEnvelope(db, ids.workspaceId, ids.sessionId));\n const established = await establishSandboxSessionFromEnvelope(settings, envelope, {\n sessionId: ids.sessionId,\n backendOverride: ids.backend as never,\n ...(ids.environment ? { environment: ids.environment } : {}),\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n });\n // Re-ensure the desktop display stack on the ATTACHED/REARMED path too — NOT\n // just the spawner path. A turn attaching to a warm box whose :0 was never\n // brought up (the box was first warmed by a Channel-A op, or a snapshot\n // rollover dropped the X stack) would otherwise drive computer-use against a\n // dead display: scrot yields an empty PNG, the SDK builds `image_url: ''`,\n // and the model rejects the turn with \"400 Invalid input[N].output.image_url\".\n // ensureDisplayStack is idempotent + flock-guarded (cheap no-op when up) and\n // NO-OPs when the desktop tier is off or the backend is headless-only, so the\n // headless turn path stays byte-for-byte unchanged.\n await ensureDisplayStack(settings, established);\n return { established, leaseEpoch, release };\n } catch (error) {\n await release();\n const warmingError = asSandboxWarmingError(error, ids.backend, settings.sandboxWarmingTimeoutMs);\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 unique-per-execution id (the Temporal activityId for a turn).\n */\nexport async function acquireSelfhostedLeaseForTurn(\n services: SandboxResumeServices,\n ids: { accountId: string; workspaceId: string; sandboxGroupId: string; sessionId: string },\n kind: LeaseHolderKind,\n holderId: string,\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 });\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\n// ============================================================================\n// Channel-B display-stack launch (P4.1 — ensureDisplayStack is now real).\n//\n// Idempotent + callable by ANY worker on the resumed handle (and by the API on a\n// viewer op). When the desktop tier is OFF (sandboxDesktopEnabled=false) or the\n// backend is headless-only, this is a NO-OP — the HEADLESS ROLLOVER branch (I5),\n// so the headless turn path is byte-for-byte unchanged. When the tier is ON for\n// a desktop-capable backend, it execs the canonical opengeni-desktop-up under an\n// in-box flock (re-establishes after a rollover; safe to call N times).\n// `exposeStreamPort` real body remains a P4.2 concern.\n// ============================================================================\n\n/**\n * Ensure the desktop display stack (Xvfb -> XFCE -> x11vnc ->\n * websockify:6080 -> noVNC) is up on the live box. Idempotent: the lock-free\n * pre-check + the in-box flock + the up-script's per-stage PID guards make a\n * second call a cheap no-op. NO-OP when the desktop tier is disabled or the\n * backend cannot serve a desktop (degradation is a value: a headless-only session\n * simply skips the stack). Delegates to the agent-loop-free leaf\n * (@opengeni/runtime/sandbox display-stack).\n *\n * BEST-EFFORT — NEVER fails the turn. The display stack powers the OPTIONAL\n * Channel-B desktop / computer-use surface; it is NOT load-bearing for the\n * agent's work. A `DisplayStackError` (a real stage failure, OR — the regression\n * this guards — a timeout-derived exit -1 when a viewer attach already holds /\n * contends the up-script's flock and the turn's ensure waits ~45s and times out)\n * is CAUGHT + logged and swallowed, so a slow/contended/failed stack degrades to\n * Channel-A-only rather than killing the turn. The fast lock-free pre-check\n * upstream means the already-up case resolves in milliseconds and never reaches\n * this catch in the first place. `DisplayStackUnsupportedError` (a box that can't\n * run commands at all) is likewise swallowed.\n */\nexport async function ensureDisplayStack(\n settings: Settings,\n established: EstablishedSandboxSession,\n): Promise<void> {\n // Headless rollover branch (I5): the tier is off OR the backend is\n // headless-only -> no display stack. Behavior-preserving for the headless path.\n // This is ALSO the \"is the desktop relevant to this turn?\" gate: we only touch\n // the box when the desktop tier is enabled for a desktop-capable backend.\n if (!settings.sandboxDesktopEnabled) {\n return;\n }\n if (!desktopCapableBackend(established.backendId)) {\n return;\n }\n try {\n await ensureDisplayStackOnBox(established.session);\n } catch (error) {\n // The desktop is a value-add, not load-bearing for the agent's work, so NO\n // display-stack failure may fail the turn:\n // - DisplayStackUnsupportedError: the box genuinely can't run commands ->\n // Channel-A-only.\n // - DisplayStackError: a stage failure OR a contended-lock timeout (exit -1)\n // after a viewer attach already brought the stack up / is mid-launch. The\n // pre-check makes the already-up case fast; if we still time out or a stage\n // really failed, degrade — don't die.\n if (error instanceof DisplayStackUnsupportedError || error instanceof DisplayStackError) {\n console.warn(\n `[sandbox-resume] ensureDisplayStack degraded to Channel-A-only (turn continues): ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n return;\n }\n // An unexpected non-display error (e.g. the session blew up entirely) still\n // propagates — that is not a desktop-surface degradation.\n throw error;\n }\n}\n\n// The structural slice of a provider session we need to resolve the tunnel.\ntype PortResolvableSession = {\n resolveExposedPort?: (port: number) => Promise<ExposedPortEndpoint>;\n};\n\n/**\n * Resolve the desktop tunnel URL (resolveExposedPort(6080)) and assemble the\n * direct-to-provider WS URL, recorded on the lease as `data_plane_url` at\n * commit. The per-viewer scoped token is minted at viewer-attach time (the\n * handshake), NOT here — the spawner records only the box-scoped tunnel URL so\n * the lease carries a fresh value across a rollover. P4.2 productionizes the\n * P4.1 stub.\n *\n * Returns null (degradation is a value, NEVER a throw):\n * - the desktop tier is off (sandboxDesktopEnabled=false), or\n * - the backend is headless-only (no desktop), or\n * - the provider session cannot resolve the port (no resolveExposedPort), or\n * - the tunnel lookup transiently failed.\n * In every null case the lease's data_plane_url stays null and the next\n * API-direct viewer op re-mints it; the turn never fails on a desktop hiccup.\n */\nexport async function exposeStreamPort(\n settings: Settings,\n established: EstablishedSandboxSession,\n): Promise<{ url: string; expiresAt: Date } | null> {\n // Headless rollover branch (I5): tier !== desktop -> no stream port to expose.\n if (!settings.sandboxDesktopEnabled) {\n return null;\n }\n if (!desktopCapableBackend(established.backendId)) {\n return null;\n }\n const session = established.session as PortResolvableSession;\n if (typeof session?.resolveExposedPort !== \"function\") {\n return null;\n }\n try {\n const endpoint = await session.resolveExposedPort(DESKTOP_STREAM_PORT);\n const url = buildStreamUrl(endpoint);\n // The provider tunnel URL is box-lifetime-valid (Modal raw TLS) or\n // provider-TTL-signed (Daytona/Blaxel); the per-viewer token's TTL bounds the\n // viewer's freshness. We record only the URL on the lease; expiresAt here is a\n // soft hint (the box's idle horizon), not a hard token expiry.\n return { url, expiresAt: new Date(Date.now() + settings.sandboxLeaseTtlMs) };\n } catch (error) {\n // Degradation is a value: a transient resolve failure leaves data_plane_url\n // null and the next viewer op re-mints. Never fail the turn on a desktop op.\n if (error instanceof StreamPortUnavailableError) {\n return null;\n }\n return null;\n }\n}\n","// apps/worker/src/sandbox-routing.ts — wire the agent-loop-free routing proxy\n// (`@opengeni/runtime` RoutingSandboxSession + makeActiveBackendResolver) to the\n// real DB pointer + the live NATS control plane for the WORKER TURN path (M7).\n//\n// The turn resumes its group box by id (resumeBoxForTurn) and injects it\n// NON-OWNED into the run. With hot-swap, the injected `session` must be the\n// STABLE routing proxy (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 RoutingSandboxSession,\n type ControlRpc,\n type EstablishedSandboxSession,\n type NatsRequestConnection,\n type RoutableBackendSession,\n type RoutableSandbox,\n type SelfhostedRelayConfig,\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};\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\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/** 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 } = 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 ? { id: sandbox.id, kind: sandbox.kind, name: sandbox.name, enrollmentId: sandbox.enrollmentId }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n relay: relayConfigFromSettings(settings),\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\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\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 */\nexport async function establishSelfhostedTurnSession(\n services: RoutingWiringServices,\n args: {\n workspaceId: string;\n /** The target machine's enrollment id == the agent subject id. */\n agentId: string;\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): Promise<EstablishedSandboxSession> {\n const { settings, bus } = services;\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 });\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","import type { EventLogger } from \"@opengeni/events\";\nimport type { Attributes, AttributeValue, Observability } from \"@opengeni/observability\";\nimport type { RuntimeMetricsHooks } from \"@opengeni/runtime\";\n\nexport type TurnOutcome = \"completed\" | \"failed\" | \"cancelled\" | \"preempted\";\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 (value === null || value === undefined || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport function runtimeMetricsHooksForObservability(observability: Observability): 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 };\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 = durationSeconds ?? (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(observability: Observability, counts: Partial<Record<SandboxLeaseLiveness, number>>): 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(observability: Observability, balances: CreditBalanceGauge[]): 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(observability: Observability | undefined, kind: CreditMicrosKind, amountMicros: number): 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","// 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). The bytes\n// go box → process memory → object-storage PUT and are NEVER serialized as a\n// Temporal activity result (F10): read + PUT happen in ONE invocation here.\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, updateRecording } from \"@opengeni/db\";\nimport type {\n RecordingAvailablePayload,\n RecordingCodec,\n RecordingFailedReason,\n RecordingStartedPayload,\n} from \"@opengeni/contracts\";\nimport {\n contentTypeForCodec,\n deleteRecordingArtifacts,\n readRecordingBytes,\n RecordingError,\n recordingStorageKey,\n startRecording as startRecordingOnBox,\n stopRecording as stopRecordingOnBox,\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\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] = [settings.streamResolutionWidth, settings.streamResolutionHeight];\n const framerate = settings.recordingFramerate;\n await import(\"@opengeni/db\").then(({ insertRecording }) => 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 const 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 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 FinalizeOutcome =\n | { ok: true; available: RecordingAvailablePayload }\n | { ok: false; reason: RecordingFailedReason; detail: string | null };\n\n/**\n * Stop ffmpeg, read the bytes off the box, PUT them to storage, commit `available`,\n * and (only then) delete the box file (F9). Returns the available payload, or a\n * failure reason. NEVER throws — finalize runs in a turn `finally` and must not\n * mask the turn outcome.\n */\nexport async function finalizeRecording(args: {\n settings: Settings;\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n active: ActiveRecording;\n session: unknown;\n runAs?: string | undefined;\n}): Promise<FinalizeOutcome> {\n const { settings, db, objectStorage, active } = args;\n const codec = settings.recordingDefaultCodec as RecordingCodec;\n const fail = async (reason: RecordingFailedReason, detail: string | null): Promise<FinalizeOutcome> => {\n await updateRecording(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n recordingId: active.recordingId,\n state: \"failed\",\n reason: scrubFreeText(detail),\n }).catch(() => undefined);\n return { ok: false, reason, detail: scrubFreeText(detail) };\n };\n\n try {\n await updateRecording(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n recordingId: active.recordingId,\n state: \"finalizing\",\n }).catch(() => undefined);\n\n // 1. SIGINT ffmpeg and wait for the clean trailer.\n await stopRecordingOnBox(args.session, active.proc);\n\n // 2. Read bytes off the box (size-gated; no eager delete — F8/F9).\n const finalized = await readRecordingBytes(args.session, active.proc, settings.recordingMaxBytes);\n\n if (!objectStorage) {\n return await fail(\"upload-failed\", \"object storage is not configured\");\n }\n\n // 3. PUT to storage (the byte transfer stays IN this process — F10).\n //\n // SERVER-SIDE authenticated direct PUT, NOT presign+fetch. The worker holds the\n // storage creds, so a presigned URL buys nothing — and on a split public/\n // internal endpoint topology (a PUBLIC `objectStorageEndpoint` with no in-cluster\n // route, the preview case) the presigned URL points at the public host and the\n // fetch PUT 401s. `putObject` sends the bytes straight to the backend over the\n // configured (in-cluster) endpoint with the in-process SDK client. Browser\n // uploads keep using `createPutUrl`; this is the trusted-server twin.\n const key = recordingStorageKey(args.workspaceId, args.sessionId, active.recordingId, codec);\n try {\n // `.slice()` detaches a fresh ArrayBuffer from the box read.\n await objectStorage.putObject({ key, contentType: finalized.contentType, body: finalized.bytes.slice() });\n } catch (uploadError) {\n return await fail(\"upload-failed\", uploadError instanceof Error ? uploadError.message : String(uploadError));\n }\n\n // 4. Commit `available` with the artifact ref.\n await updateRecording(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n recordingId: active.recordingId,\n state: \"available\",\n storageKey: key,\n sizeBytes: finalized.sizeBytes,\n durationSeconds: finalized.durationSeconds,\n });\n\n // 5. ONLY NOW delete the box artifacts (F9 — never before a confirmed PUT).\n await deleteRecordingArtifacts(args.session, active.proc);\n\n const available: RecordingAvailablePayload = {\n recordingId: active.recordingId,\n turnId: active.turnId,\n codec,\n contentType: contentTypeForCodec(codec),\n storageKey: key,\n durationSeconds: finalized.durationSeconds,\n sizeBytes: finalized.sizeBytes,\n dimensions: active.dimensions,\n };\n return { ok: true, available };\n } catch (error) {\n const reason: RecordingFailedReason = error instanceof RecordingError ? error.reason : \"ffmpeg-error\";\n return await fail(reason, error instanceof Error ? error.message : String(error));\n }\n}\n\n/**\n * Discard an on-turn recording that captured NO computer-use activity (a plain\n * text turn): stop ffmpeg on the box, delete the box artifacts, and remove the\n * recording row entirely. NO storage PUT and NO `recording.failed` — a clean\n * no-op. NEVER throws (it runs in the turn `finally` and must not mask the turn\n * outcome). Returns nothing; the caller emits no recording event for a discard.\n */\nexport async function discardRecording(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 // Stop ffmpeg cleanly, then delete the partial artifact off the box. Both are\n // best-effort: a stuck box must not strand the discard (the box rides the\n // provider idle-timeout regardless).\n await stopRecordingOnBox(args.session, active.proc).catch(() => undefined);\n await deleteRecordingArtifacts(args.session, active.proc).catch(() => undefined);\n } finally {\n // Remove the phantom row inserted at beginRecording so a no-activity turn\n // leaves no recording trace at all.\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","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 {\n ActivityServices,\n IndexDocumentInput,\n} 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(lockedDb, objectStorage, input.workspaceId, input.documentId, documentServices, {\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 = 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 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","// 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 countQueuedTurns,\n countSandboxLeasesByLiveness,\n forceDrainOverLimitViewerOnlyBoxes,\n getBillingBalance,\n listCreditBalancesByAccount,\n listLiveModalSandboxLeaseAttributions,\n listMeterableWarmLeases,\n persistDrainSnapshot,\n readLease,\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 {\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 -> the superseded archive (if any) to GC the prior snapshot.\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 is always null in\n * this case.\n */\nexport type PersistArchiveFn = (\n archiveBase64: string | null,\n) => Promise<{ wrote: boolean; priorArchive: 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 = 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 { db, settings, observability } = await services();\n if (!settings.sandboxOwnershipEnabled) {\n return { examined: 0, terminated: 0, skipped: 0, metered: 0, forceDrained: 0, modalOrphansTerminated: 0 };\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(db, settings, metered.workspaceIds, observability);\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 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(db, settings, row, observability, terminateBox);\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 (drainable.length > 0 || metered.accrued > 0 || forceDrained > 0 || modalOrphansTerminated > 0) {\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 { examined: drainable.length, terminated, skipped, metered: metered.accrued, forceDrained, modalOrphansTerminated };\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 = 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 ? await getBillingBalance(db, accountId) : { 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 const persistArchive: PersistArchiveFn = async (archiveBase64: string | null) =>\n await persistDrainSnapshot(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n expectedEpoch: row.leaseEpoch,\n workspaceArchive: archiveBase64,\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 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 (backend === \"selfhosted\" || lease.backend === \"selfhosted\" || lease.resumeBackendId === \"selfhosted\") {\n observability.info(\"sandbox reaper: selfhosted lease drained to cold (NEVER provider-stopped — it is the user's machine)\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\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(\"sandbox reaper: Modal lease re-armed before direct terminate — leaving sandbox RUNNING\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n instanceId: lease.instanceId,\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(client as never, envelopeSessionState);\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(\"sandbox reaper: drainable box already gone (NotFound on resume) — proceeding to cold\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\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(\"sandbox reaper: box gone during persist (NotFound) — nothing to snapshot, proceeding to cold\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n });\n return true;\n }\n observability.warn(\"sandbox reaper: persistWorkspace failed — leaving box draining (files NOT lost)\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n error: error instanceof Error ? error.message : String(error),\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 } = await persistArchive(archiveBase64);\n if (!wrote) {\n observability.info(\"sandbox reaper: lease re-armed during persist — leaving box RUNNING (no terminate)\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\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 } 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(\"sandbox reaper: lease re-armed during snapshot window (no-archive path) — leaving box RUNNING (no terminate)\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\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 createScheduledTaskRun,\n createSession,\n createSessionGoal,\n enqueueSessionTurn,\n getBillingBalance,\n getWorkspaceEnvironment,\n isCodexBilledTurn,\n recordUsageEvent,\n requireScheduledTask,\n requireSession,\n setTemporalWorkflowId,\n sumUsageQuantity,\n updateScheduledTask,\n updateScheduledTaskRun,\n upsertSessionGoal,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents } from \"@opengeni/events\";\nimport { configuredStaticUsageLimits, type Settings } from \"@opengeni/config\";\nimport {\n assertReusableSessionRevivable,\n mergeResourceRefs,\n mergeToolRefs,\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 (input: DispatchScheduledTaskRunInput): Promise<DispatchScheduledTaskRunResult> => {\n const { settings, db, bus } = 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({ db, settings, workspaceId: task.workspaceId, model });\n await ensureScheduledRunAllowed(settings, db, task.accountId, task.workspaceId, input.agentRunUsageIdempotencyKey ? 0 : 1, isCodexRun);\n const run = await createScheduledTaskRun(db, {\n workspaceId: task.workspaceId,\n taskId: task.id,\n triggerType: input.triggerType,\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 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.environment_id is ON DELETE RESTRICT, so\n // an attached environment must still exist here; fail closed if not.\n const environment = task.environmentId\n ? await getWorkspaceEnvironment(db, task.workspaceId, task.environmentId)\n : null;\n if (task.environmentId && !environment) {\n throw new Error(`workspace environment not found: ${task.environmentId}`);\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 environmentId: task.environmentId ?? null,\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, { reusableSessionId: session.id });\n }\n const events = await appendAndPublishEvents(db, bus, task.workspaceId, session.id, [\n {\n type: \"session.created\",\n payload: {\n status: \"queued\",\n scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n // Names/ids only; never values.\n ...(environment ? { environmentId: environment.id, environmentName: environment.name } : {}),\n },\n },\n ...(goal ? [{\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 type: \"user.message\",\n payload: scheduledUserMessagePayload(task.agentConfig.prompt, task.agentConfig.resources, taskTools, task.id, run.id),\n },\n { type: \"session.status.changed\", payload: { status: \"queued\" } },\n ]);\n const trigger = events.find((event) => event.type === \"user.message\");\n if (!trigger) {\n throw new Error(\"failed to append scheduled task trigger event\");\n }\n const turn = await enqueueSessionTurn(db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n triggerEventId: trigger.id,\n temporalWorkflowId: workflowId,\n source: \"scheduled_task\",\n prompt: task.agentConfig.prompt,\n resources: task.agentConfig.resources,\n tools: taskTools,\n model,\n reasoningEffort,\n sandboxBackend,\n metadata: {\n scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n },\n });\n await appendAndPublishEvents(db, bus, task.workspaceId, session.id, [{\n type: \"turn.queued\",\n turnId: turn.id,\n payload: { turnId: turn.id, triggerEventId: trigger.id, source: turn.source },\n }]);\n await updateScheduledTaskRun(db, task.workspaceId, run.id, {\n status: \"dispatched\",\n sessionId: session.id,\n triggerEventId: trigger.id,\n });\n result = {\n action: \"start\",\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n triggerEventId: trigger.id,\n workflowId,\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.environmentId ?? null) !== (task.environmentId ?? null)) {\n throw new Error(\"scheduled task environment attachment does not match its reusable session\");\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 = goalSpec\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 const events = await appendSessionEventsWithLockedSessionUpdate(db, task.workspaceId, session.id, (locked) => {\n // Authoritative guard under the FOR UPDATE row lock: re-check the\n // current status to close the TOCTOU between the early read and the\n // lock (a cancel could land in between). Throwing aborts the whole\n // append+update transaction, so no user.message is persisted.\n assertReusableSessionRevivable(locked.status);\n return {\n events: [\n ...(reusableGoal ? [{\n type: \"goal.set\" as const,\n payload: {\n goalId: reusableGoal.goal.id,\n text: reusableGoal.goal.text,\n ...(reusableGoal.goal.successCriteria ? { successCriteria: reusableGoal.goal.successCriteria } : {}),\n version: reusableGoal.goal.version,\n actor: \"scheduled_task\",\n replaced: reusableGoal.replaced,\n },\n }] : []),\n {\n type: \"user.message\",\n payload: scheduledUserMessagePayload(task.agentConfig.prompt, task.agentConfig.resources, taskTools, task.id, run.id),\n },\n ],\n update: {\n resources: mergeResourceRefs(locked.resources, task.agentConfig.resources),\n tools: mergeToolRefs(locked.tools, taskTools),\n },\n };\n });\n await bus.publish(task.workspaceId, session.id, events);\n const trigger = events.find((event) => event.type === \"user.message\");\n if (!trigger) {\n throw new Error(\"failed to append scheduled task trigger event\");\n }\n const turn = await enqueueSessionTurn(db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n triggerEventId: trigger.id,\n temporalWorkflowId: workflowIdForSession(session.id),\n source: \"scheduled_task\",\n prompt: task.agentConfig.prompt,\n resources: task.agentConfig.resources,\n tools: taskTools,\n model,\n reasoningEffort,\n sandboxBackend,\n metadata: {\n scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n },\n });\n await appendAndPublishEvents(db, bus, task.workspaceId, session.id, [{\n type: \"turn.queued\",\n turnId: turn.id,\n payload: { turnId: turn.id, triggerEventId: trigger.id, source: turn.source },\n }]);\n await updateScheduledTaskRun(db, task.workspaceId, run.id, {\n status: \"dispatched\",\n sessionId: session.id,\n triggerEventId: trigger.id,\n });\n result = {\n action: \"signal\",\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n triggerEventId: trigger.id,\n workflowId: workflowIdForSession(session.id),\n };\n }\n } catch (error) {\n await updateScheduledTaskRun(db, task.workspaceId, run.id, {\n status: \"failed\",\n error: 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: input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`,\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 (!isCodexRun && (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")) {\n const balance = await getBillingBalance(db, accountId);\n if (balance.balanceMicros <= 0) {\n throw new Error(\"insufficient OpenGeni credits\");\n }\n }\n\t if (settings.usageLimitsMode === \"static\" || settings.usageLimitsMode === \"managed\") {\n\t const limits = configuredStaticUsageLimits(settings);\n\t if (!isCodexRun && limits.maxMonthlyCostMicrosPerAccount) {\n\t const used = await sumUsageQuantity(db, {\n\t accountId,\n\t eventType: \"model.cost\",\n\t since: startOfUtcMonth(),\n\t });\n\t if (used >= limits.maxMonthlyCostMicrosPerAccount) {\n\t throw new Error(`monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`);\n\t }\n\t }\n\t if (limits.maxMonthlyAgentRunsPerWorkspace) {\n\t const used = await sumUsageQuantity(db, {\n\t workspaceId,\n eventType: \"agent_run.created\",\n since: startOfUtcMonth(),\n });\n if (used + requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {\n throw new Error(`monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`);\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 claimNextQueuedTurn as claimNextQueuedTurnDb,\n countQueuedTurns,\n countTurnSessionHistoryItems,\n finishTurn,\n getSessionEvent,\n getSessionTurn,\n incrementTurnWorkerDeathRedispatches,\n requeuePreemptedTurn,\n requireSession,\n setSessionStatus,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents } from \"@opengeni/events\";\nimport { WORKER_DEATH_RESUME_TEXT } from \"./agent-turn\";\nimport { isSteerInterrupt, pauseActiveGoalOnInterrupt } from \"./goals\";\nimport { notifyParentOfChildTerminal } from \"./parent-wake\";\nimport { recordTurnsQueuedGauge } from \"../observability-metrics\";\nimport type {\n ActivityServices,\n ClaimNextQueuedTurnInput,\n MarkSessionIdleInput,\n RequeueTurnAfterWorkerDeathInput,\n RequeueTurnAfterWorkerDeathResult,\n RunAgentTurnInput,\n} from \"./types\";\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(services: () => Promise<ActivityServices>) {\n async function failSession(input: RunAgentTurnInput & { error?: string }): Promise<void> {\n const { db, bus, settings, observability, wakeSessionWorkflow } = await services();\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n // Already terminal: runAgentTurn settled this turn as failed (status failed,\n // activeTurnId cleared, turn finished) and already woke any parent, then the\n // workflow still routed here because the activity's finally threw after the\n // failed return. Re-failing would append a second turn.failed/status.changed\n // and a second parent wake (a different lastSequence dodges the idle dedupe).\n // The session is already where this activity would put it, so stop.\n if (session.status === \"failed\") {\n return;\n }\n const trigger = await getSessionEvent(db, input.workspaceId, input.triggerEventId);\n const turnId = session.activeTurnId ?? null;\n await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n type: \"turn.failed\",\n turnId,\n payload: {\n triggerEventId: input.triggerEventId,\n trigger: trigger?.payload ?? null,\n error: input.error ?? \"Agent activity failed before it could report a terminal state.\",\n },\n },\n {\n type: \"session.status.changed\",\n turnId,\n payload: { status: \"failed\" },\n },\n ]);\n if (turnId) {\n await finishTurn(db, input.workspaceId, turnId, \"failed\");\n }\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"failed\", null);\n await notifyParentOfChildTerminal({ db, bus, settings, observability, wakeSessionWorkflow }, input.workspaceId, input.sessionId, \"failed\");\n }\n\n async function interruptActiveTurn(input: RunAgentTurnInput): Promise<void> {\n const { db, bus, observability } = await services();\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n const trigger = await getSessionEvent(db, input.workspaceId, input.triggerEventId);\n // Pause an active goal before the early return below: an interrupt can\n // land after the turn already cleared activeTurnId, and skipping the pause\n // there would let the loop auto-continue the goal the user just stopped.\n // Steer interrupts are the exception: steering cancels the running turn\n // only to deliver the steered message next — redirection, not a stop —\n // so the goal loop stays active.\n if (!isSteerInterrupt(trigger)) {\n await pauseActiveGoalOnInterrupt(db, bus, input.workspaceId, input.sessionId);\n }\n if (!session.activeTurnId) {\n return;\n }\n await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n turnId: session.activeTurnId,\n type: \"turn.cancelled\",\n payload: { triggerEventId: input.triggerEventId, reason: trigger?.payload ?? null },\n },\n {\n turnId: session.activeTurnId,\n type: \"session.status.changed\",\n payload: { status: \"queued\" },\n },\n ]);\n await finishTurn(db, input.workspaceId, session.activeTurnId, \"cancelled\");\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"queued\", null);\n await refreshQueuedTurnsGauge(db, observability);\n }\n\n /**\n * Put a turn whose hosting worker died WITHOUT the graceful-preempt\n * checkpoint (heartbeat-timeout activity failure: SIGKILL, OOM, node loss)\n * back on the session queue, so the workflow re-dispatches it instead of\n * failing the session. The degraded-resume contract: conversation truth is\n * dual-written after every model response during the turn, so re-running\n * from the trigger event plus stored items loses at most the work since the\n * last reconcile. When the dead attempt persisted items for this turn, the\n * rerun enters through a synthesized `turn.preempted` resume notice (its\n * partial progress is already conversation truth; replaying the original\n * trigger would duplicate input the model has seen). When nothing was\n * persisted — checkpoint absent — the original trigger replays cleanly.\n * Approval reruns always replay their original trigger: the decision is\n * applied through the RunState resume path and a swapped trigger could\n * drop it. Re-dispatches are bounded per turn by\n * WORKER_DEATH_MAX_REDISPATCHES, persisted on the turn row.\n */\n async function requeueTurnAfterWorkerDeath(input: RequeueTurnAfterWorkerDeathInput): Promise<RequeueTurnAfterWorkerDeathResult> {\n const { settings, db, bus, observability } = await services();\n const turn = await getSessionTurn(db, input.workspaceId, input.turnId);\n if (!turn || (turn.status !== \"running\" && turn.status !== \"requires_action\")) {\n // The timed-out attempt was a zombie that actually settled the turn\n // (completed/failed/cancelled it) after the server gave up on its\n // heartbeats. Whatever it recorded is the truth; nothing to redo.\n return { action: \"stale\" };\n }\n const redispatches = await incrementTurnWorkerDeathRedispatches(db, input.workspaceId, input.turnId);\n if (redispatches > WORKER_DEATH_MAX_REDISPATCHES) {\n return { action: \"exceeded\", redispatches: redispatches - 1 };\n }\n const trigger = await getSessionEvent(db, input.workspaceId, input.triggerEventId);\n const approvalRerun = trigger?.type === \"user.approvalDecision\";\n // Legacy run-state mode has no crash checkpoint (the dying worker never\n // captured the blob), so it always replays the original trigger against\n // the previous RunState snapshot — the documented degraded resume.\n const resumeWithNotice = !approvalRerun\n && settings.sessionHistorySource === \"items\"\n && await countTurnSessionHistoryItems(db, input.workspaceId, input.turnId) > 0;\n const [preemptedEvent] = await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n turnId: turn.id,\n type: \"turn.preempted\",\n payload: {\n triggerEventId: input.triggerEventId,\n reason: \"worker_death\",\n redispatches,\n resumeWithNotice,\n ...(resumeWithNotice ? { text: WORKER_DEATH_RESUME_TEXT } : {}),\n },\n },\n {\n turnId: turn.id,\n type: \"session.status.changed\",\n payload: { status: \"queued\" },\n },\n ]);\n try {\n await requeuePreemptedTurn(db, input.workspaceId, turn.id, resumeWithNotice && preemptedEvent ? preemptedEvent.id : input.triggerEventId);\n } catch (requeueError) {\n // The zombie attempt can settle the turn between the status check above\n // and this requeue (it keeps executing until it notices the timeout).\n // A settled turn means its recorded outcome is the truth: report stale\n // so the workflow continues instead of failing the session over a lost\n // race. Anything else is a real persistence failure — rethrow.\n const current = await getSessionTurn(db, input.workspaceId, input.turnId);\n if (current && current.status !== \"running\" && current.status !== \"requires_action\") {\n return { action: \"stale\" };\n }\n throw requeueError;\n }\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"queued\", null);\n await refreshQueuedTurnsGauge(db, observability);\n return { action: \"requeued\", redispatches };\n }\n\n async function claimNextQueuedTurn(input: ClaimNextQueuedTurnInput) {\n const { db, observability } = await services();\n const turn = await claimNextQueuedTurnDb(db, input.workspaceId, input.sessionId, input.workflowId);\n await refreshQueuedTurnsGauge(db, observability);\n return turn;\n }\n\n async function markSessionIdle(input: MarkSessionIdleInput): Promise<void> {\n const { db, bus, settings, observability, wakeSessionWorkflow } = await services();\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n if (session.status === \"queued\" || session.status === \"running\") {\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\n }\n await refreshQueuedTurnsGauge(db, observability);\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-interrupt stop). Wake\n // the parent here, deduped per idle episode so the manager is nudged once.\n await notifyParentOfChildTerminal({ db, bus, settings, observability, wakeSessionWorkflow }, input.workspaceId, input.sessionId, \"idle\");\n }\n\n return {\n failSession,\n interruptActiveTurn,\n requeueTurnAfterWorkerDeath,\n claimNextQueuedTurn,\n markSessionIdle,\n };\n}\n\nasync function refreshQueuedTurnsGauge(\n db: ActivityServices[\"db\"],\n observability: ActivityServices[\"observability\"],\n): Promise<void> {\n try {\n recordTurnsQueuedGauge(observability, await countQueuedTurns(db));\n } catch {\n // Best-effort telemetry; session state transitions remain authoritative.\n }\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(checks: ReadinessChecks, timeoutMs = 2_000): Promise<ReadinessResult> {\n const entries = await Promise.all(\n (Object.entries(checks) as Array<[ReadinessCheckName, () => Promise<void> | void]>)\n .map(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 [name, { ok: false, error: error instanceof Error ? error.message : String(error) }] as const;\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(() => reject(new Error(`readiness check timed out after ${timeoutMs}ms`)), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n"],"mappings":";AAAA,SAAS,gBAAAA,eAAc,eAAAC,cAAa,+BAAAC,8BAA6B,wBAAwB,2BAA0C;AACnI,SAAS,YAAAC,iBAAgB;AACzB,SAAS,sBAAAC,2BAA0B;AACnC,SAAS,uBAAAC,sBAAqB,iCAAqD;AACnF,SAAS,YAAY,wBAAwB,uBAAuB,UAAU,sBAAsB;AACpG,SAAS,kBAAkB,cAAc;;;ACLzC,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,uBAAuB;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA,cAAAC;AAAA,EACA,qBAAAC;AAAA,EACA,eAAAC;AAAA,EACA,mBAAAC;AAAA,EACA,kBAAAC;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA,oCAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,gCAAAC;AAAA,EACA,8BAAAC;AAAA,EACA;AAA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C9B,IAAI,SAAS;AAAA,QACb;AAAA,MACF;AAAA,IACF,CAAC;AACD,iBAAa,sBAAsB;AAAA,MACjC;AAAA,MACA;AAAA,MACA,QAAQ;AAAA,QACN,IAAI,aAAa,SAAS,EAAE;AAAA,QAC5B,MAAM,eAAe,GAAG;AAAA,QACxB,UAAU,SAAS;AAAA,MACrB;AAAA,IACF,CAAC;AAKD,qBAAiB,MAAM;AAAA,MACrB;AAAA,MACA,MAAM,8BAA8B,UAAU,aAAa;AAAA,MAC3D,EAAE,GAAG,cAAc,QAAQ;AAAA,IAC7B;AACA,kBAAc,KAAK,6BAA6B;AAAA,MAC9C,mBAAmB,SAAS;AAAA,MAC5B,UAAU,SAAS;AAAA,IACrB,CAAC;AACD,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,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","createObjectStorage","getBillingBalance","getSandbox","readActiveSandbox","requireFile","getSessionEvent","getSessionGoal","isCodexBilledTurn","workspaceCodexSubscriptionActive","requireSession","recordUsageEvent","getActiveSessionHistoryItems","nextSessionHistoryPosition","sumUsageQuantity","SandboxLeaseSupersededError","appendAndPublishEvents","sanitizeHistoryItemsForModel","summarizeForCompaction","SUMMARY_BUFFER_TOKENS","configuredStaticUsageLimits","chosen","CODEX_FALLBACK_MODEL_SLUGS","installationId","mergeToolRefs","reasoningEffortForMetadata","maybeContinueGoal","pauseGoalForInterrupt","getSessionGoal","resolveContextCompactionMode","getActiveSessionHistoryItems","getSandboxSessionEnvelope","getSandboxSessionEnvelope","resumeEnvelope","desktopCapableBackend","sanitizeHistoryItemsForModel","runAgentTurn","workspaceCodexSubscriptionActive","requireSession","getSessionEvent","isCodexBilledTurn","appendAndPublishEvents","getSessionGoal","CODEX_FALLBACK_MODEL_SLUGS","readActiveSandbox","getSandbox","summarizeForCompaction","SUMMARY_BUFFER_TOKENS","trigger","getActiveSessionHistoryItems","nextSessionHistoryPosition","recordUsageEvent","SandboxLeaseSupersededError","getBillingBalance","configuredStaticUsageLimits","sumUsageQuantity","startOfUtcMonth","requireFile","configuredStaticUsageLimits","getBillingBalance","recordUsageEvent","sumUsageQuantity","startOfUtcMonth","accrueWarmSeconds","getBillingBalance","readLease","sandboxWarmRateMicrosPerSecond","reapSandboxLeases","sandboxWarmRateMicrosPerSecond","accrueWarmSeconds","getBillingBalance","readLease","enqueueSessionTurn","getBillingBalance","isCodexBilledTurn","recordUsageEvent","requireSession","sumUsageQuantity","appendAndPublishEvents","configuredStaticUsageLimits","isCodexBilledTurn","recordUsageEvent","appendAndPublishEvents","enqueueSessionTurn","requireSession","getBillingBalance","configuredStaticUsageLimits","sumUsageQuantity","startOfUtcMonth","claimNextQueuedTurnDb","countQueuedTurns","finishTurn","getSessionEvent","getSessionTurn","requeuePreemptedTurn","requireSession","setSessionStatus","appendAndPublishEvents","failSession","requireSession","getSessionEvent","appendAndPublishEvents","finishTurn","setSessionStatus","interruptActiveTurn","requeueTurnAfterWorkerDeath","getSessionTurn","requeuePreemptedTurn","claimNextQueuedTurn","claimNextQueuedTurnDb","markSessionIdle","countQueuedTurns","createObjectStorage","runAgentTurn","getSettings","createObservability","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/common.ts","../src/activities/context-compaction.ts","../src/activities/environment.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/observability-metrics.ts","../src/activities/recording.ts","../src/activities/documents.ts","../src/activities/sandbox-lease.ts","../src/activities/scheduled-tasks.ts","../src/activities/session-state.ts","../src/http.ts"],"sourcesContent":["import { dbSearchPath, getSettings, resolveNatsControlPlaneAuth, retryStartupDependency, startupRetryOptions, type Settings } from \"@opengeni/config\";\nimport { createDb } from \"@opengeni/db\";\nimport { createNatsEventBus } from \"@opengeni/events\";\nimport { createObservability, logStartupDependencyRetry, type Observability } from \"@opengeni/observability\";\nimport { Connection, ScheduleAlreadyRunning, ScheduleOverlapPolicy, Client as TemporalClient } from \"@temporalio/client\";\nimport { NativeConnection, Worker } from \"@temporalio/worker\";\nimport { ensureModalRegistryImage } from \"@opengeni/runtime\";\nimport { createActivities, type ActivityDependencies } from \"./activities\";\nimport type { WakeSessionWorkflowSignal } from \"./activities/types\";\nimport { dbReadyCheck, natsReadyCheck, startWorkerHttpServer } from \"./http\";\nimport { observabilityEventLogger } from \"./observability-metrics\";\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\";\n\nexport type WorkerOptions = {\n settings?: Settings;\n activities?: ReturnType<typeof createActivities>;\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 = options.activityDependencies?.observability ?? createObservability(settings, { component: \"worker\" });\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 await retryStartupDependency(\n \"Modal private-registry image\",\n () => ensureModalRegistryImage(settings),\n {\n ...startupRetryOptions(settings),\n onRetry: (event) => logStartupDependencyRetry(observability, event),\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 = options.activities ?? createActivities({\n ...options.activityDependencies,\n settings,\n observability,\n });\n const worker = await Worker.create({\n connection,\n namespace: settings.temporalNamespace,\n taskQueue: settings.temporalTaskQueue,\n workflowsPath: options.workflowsPath ?? new URL(\"../src/workflows.ts\", import.meta.url).pathname,\n activities,\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(settings: Settings): Promise<{\n wakeSessionWorkflow: WakeSessionWorkflowSignal;\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 ({ accountId, workspaceId, sessionId, workflowId }) => {\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 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). Gated on sandboxOwnershipEnabled: with the flag off the\n * Schedule is never created, so the lease feature is fully dark (no sweeps, no\n * terminates).\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 if (!settings.sandboxOwnershipEnabled) {\n return { registered: false, close: async () => {} };\n }\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 { registered: true, close: async () => { await connection.close(); } };\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 { registered: false, close: async () => { await connection.close(); } };\n }\n await connection.close().catch(() => undefined);\n throw error;\n }\n}\n\nexport async function startWorker() {\n const settings = getSettings();\n const observability = createObservability(settings, { component: \"worker\" });\n const retryOptions = startupRetryOptions(settings);\n const onRetry = (event: Parameters<typeof logStartupDependencyRetry>[1]) => 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 httpServer: ReturnType<typeof startWorkerHttpServer> | undefined;\n try {\n bus = await retryStartupDependency(\n \"NATS\",\n () =>\n createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password } : undefined,\n { logger: observabilityEventLogger(observability) },\n ),\n { ...retryOptions, onRetry },\n );\n signaler = await retryStartupDependency(\n \"Temporal client\",\n () => createWorkerWorkflowSignaler(settings),\n { ...retryOptions, onRetry },\n );\n workerBundle = await createOpenGeniWorker({\n settings,\n activityDependencies: {\n observability,\n wakeSessionWorkflow: signaler.wakeSessionWorkflow,\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 // Register the ONE global reaper Schedule (no-op when sandboxOwnershipEnabled\n // is false). Idempotent across the pool: only the first worker creates it. The\n // static global-queue Worker.create above is UNCHANGED — there is no\n // per-session worker factory.\n reaperSchedule = await retryStartupDependency(\n \"Temporal schedule (sandbox reaper)\",\n () => registerSandboxReaperSchedule(settings, observability),\n { ...retryOptions, onRetry },\n );\n observability.info(\"OpenGeni worker listening\", {\n temporalTaskQueue: settings.temporalTaskQueue,\n httpPort: settings.workerHttpPort,\n });\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 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 { createDocumentActivities } from \"./activities/documents\";\nimport { createGoalActivities } from \"./activities/goals\";\nimport { createSandboxLeaseActivities } from \"./activities/sandbox-lease\";\nimport { createScheduledTaskActivities } from \"./activities/scheduled-tasks\";\nimport { createSessionStateActivities } from \"./activities/session-state\";\nimport type { ActivityDependencies, ActivityServices } from \"./activities/types\";\nimport { observabilityEventLogger, runtimeMetricsHooksForObservability } from \"./observability-metrics\";\n\nexport type {\n ActivityDependencies,\n DispatchScheduledTaskRunInput,\n DispatchScheduledTaskRunResult,\n IndexDocumentInput,\n MaybeContinueGoalInput,\n MaybeContinueGoalResult,\n PauseGoalForInterruptInput,\n RequeueTurnAfterWorkerDeathInput,\n RequeueTurnAfterWorkerDeathResult,\n RunAgentTurnInput,\n RunAgentTurnResult,\n} from \"./activities/types\";\n\nexport function createActivities(dependencies: ActivityDependencies = {}) {\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 = 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 ? null : 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 ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password } : undefined,\n { logger: observabilityEventLogger(observability) },\n )),\n runtime: dependencies.runtime ?? 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 // §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 const runAgentTurn = createRunAgentTurnActivity(services);\n return {\n runAgentTurn,\n // Legacy Temporal activity name. In-flight session workflows (which can\n // legitimately live for days) recorded ScheduleActivityTask events as\n // \"runAgentSegment\"; the name must keep resolving until those histories\n // drain. New workflow code must use runAgentTurn; migrate the session\n // workflow call site via patched() before removing this alias.\n runAgentSegment: runAgentTurn,\n ...createDocumentActivities(services),\n ...createSessionStateActivities(services),\n ...createScheduledTaskActivities(services),\n ...createGoalActivities(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\nconst defaultActivities = createActivities();\n\nexport const runAgentTurn = defaultActivities.runAgentTurn;\nexport const runAgentSegment = defaultActivities.runAgentSegment;\nexport const indexDocument = defaultActivities.indexDocument;\nexport const failSession = defaultActivities.failSession;\nexport const interruptActiveTurn = defaultActivities.interruptActiveTurn;\nexport const requeueTurnAfterWorkerDeath = defaultActivities.requeueTurnAfterWorkerDeath;\nexport const claimNextQueuedTurn = defaultActivities.claimNextQueuedTurn;\nexport const markSessionIdle = defaultActivities.markSessionIdle;\nexport const dispatchScheduledTaskRun = defaultActivities.dispatchScheduledTaskRun;\nexport const maybeContinueGoal = defaultActivities.maybeContinueGoal;\nexport const pauseGoalForInterrupt = defaultActivities.pauseGoalForInterrupt;\nexport const reapSandboxLeases = defaultActivities.reapSandboxLeases;\n","import {\n claimNextQueuedTurn as claimNextQueuedTurnDb,\n createTurn,\n applyCreditDebitUpToBalance,\n finishTurn,\n getBillingBalance,\n getSandbox,\n readActiveSandbox,\n requireFile,\n getSessionEvent,\n getSessionGoal,\n getSessionTurn,\n isCodexBilledTurn,\n workspaceCodexSubscriptionActive,\n getCodexRotationSettings,\n listCodexAccountStatuses,\n fetchCodexUsageForAccount,\n getSessionCodexState,\n recordSessionActiveCodexCredential,\n recordCodexAccountUsage,\n recordCodexAccountConnectors,\n setActiveCodexCredential,\n setCodexCredentialExhausted,\n countConsecutiveReactiveRotations,\n requireSession,\n recordUsageEvent,\n appendSessionHistoryItems,\n consumeSessionCompactionRequest,\n countSessionHistoryItems,\n getActiveSessionHistoryItems,\n nextSessionHistoryPosition,\n requeuePreemptedTurn,\n saveRunState,\n upsertSandboxSessionEnvelope,\n setSessionStatus,\n setSessionLastInputTokens,\n sumUsageQuantity,\n heartbeatLeaseHolder,\n accrueWarmSeconds,\n SandboxLeaseSupersededError,\n buildConnectionTokenResolver,\n type AppendEventInput,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents } from \"@opengeni/events\";\nimport {\n sandboxStateEntryFromRunState,\n agentsErrorRunState,\n maxTurnsExceededRunState,\n modelResponseUsageFromSdkEvent,\n normalizeSdkEvent,\n sanitizeHistoryItemsForModel,\n summarizeForCompaction,\n findCompactionNeededError,\n SUMMARY_BUFFER_TOKENS,\n type SandboxFileDownload,\n type OpenGeniRuntime,\n type ComputerToolMode,\n} from \"@opengeni/runtime\";\nimport { calculateModelUsageCostMicros, configuredModelPricing, configuredStaticUsageLimits, sandboxWarmRateMicrosPerSecond, type ModelUsageInput, type ModelProviderApi, type RegistryProviderKind, type Settings } from \"@opengeni/config\";\nimport { CancelledFailure } from \"@temporalio/activity\";\nimport { settingsWithCodexCredential, settingsWithEnabledCapabilityMcpServers, settingsWithSessionMcpServersForRun } from \"./capabilities\";\nimport { chooseRotationActive, computeIdleDelayMs, computeReactiveRotationResume, type CodexRotationStrategy, type RotationDecision } from \"./codex-rotation\";\nimport type { CodexAccountStatus } from \"@opengeni/db\";\nimport { buildCodexTokenResolver } from \"./codex-auth\";\nimport {\n buildModelResolver,\n CODEX_CLIENT_VERSION,\n CODEX_FALLBACK_MODEL_SLUGS,\n classifyCodexUsageLimitError,\n codexRequestStorage,\n type CodexRequestContext,\n type CodexUsageHeaderSnapshot,\n} from \"@opengeni/codex\";\nimport {\n mergeResourceRefs,\n mergeToolRefs,\n} from \"./common\";\nimport { maybeCompactContext } from \"./context-compaction\";\nimport { loadWorkspaceEnvironmentForRunWithCredentials, sandboxEnvironmentForRun } from \"./environment\";\nimport { withCodexAppsTool, withFirstPartyTools } from \"./goals\";\nimport { resolveWorkspaceAgentInstructions, resolveWorkspacePackRuntime, settingsWithPackSandboxImage } 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 {\n ActivityServices,\n RunAgentTurnInput,\n RunAgentTurnResult,\n} from \"./types\";\nimport { resumeBoxForTurn, acquireSelfhostedLeaseForTurn, type ResumedTurnSandbox } from \"../sandbox-resume\";\nimport { wrapTurnBoxWithRouting, establishSelfhostedTurnSession, routingEnabled } from \"../sandbox-routing\";\nimport { recordCreditMicros, runtimeMetricsHooksForObservability, turnLifecycleMetricsFor, type TurnOutcome } from \"../observability-metrics\";\nimport { beginRecording, discardRecording, finalizeRecording, type ActiveRecording } from \"./recording\";\nimport { createObjectStorage, type ObjectStorage } from \"@opengeni/storage\";\nimport { desktopCapableBackend, sandboxRunAs } from \"@opengeni/runtime\";\nimport { CAPABILITY_DESCRIPTORS, type ResourceRef } from \"@opengeni/contracts\";\nimport { 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/**\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\n// Resume notice fed to the model when a turn re-enters after a graceful\n// worker shutdown (deploy/rollout restart) checkpointed it mid-flight. The\n// agent must not blindly replay side effects it cannot see in its history:\n// at most the single in-flight model step was lost, and anything it started\n// there may or may not have completed.\n// Resume notice after an in-turn context-window overflow was recovered by\n// compaction: the turn's earlier work survives (albeit summarized), so the\n// agent continues instead of the session dying or stalling idle.\nexport const CONTEXT_OVERFLOW_RESUME_TEXT = [\n \"[TURN RESUMED AFTER CONTEXT COMPACTION] The conversation approached or exceeded the model's context window mid-turn; older history above was compacted into a summary.\",\n \"Continue the original task from where it left off. Before repeating any action with side effects, check whether it already happened.\",\n].join(\"\\n\");\n\nexport const WORKER_SHUTDOWN_RESUME_TEXT = [\n \"[TURN RESUMED AFTER WORKER RESTART] The platform worker running this turn restarted (deploy/rollout) before the turn finished.\",\n \"Your conversation history above, including this turn's earlier work, is preserved up to the last checkpoint; at most the single in-flight model step after it was lost.\",\n \"Continue the original task from where it left off. Before repeating any action with side effects, check whether it already happened.\",\n].join(\"\\n\");\n\n// Resume notice for the harder variant: the worker died WITHOUT running the\n// graceful checkpoint (SIGKILL, OOM, node loss — surfaced to the workflow as\n// a heartbeat-timeout activity failure). Conversation truth is still\n// dual-written after every model response, so the bound is the same order as\n// a graceful preempt, but nothing after the last reconcile was captured and\n// the agent must be even more suspicious about repeated side effects.\nexport const WORKER_DEATH_RESUME_TEXT = [\n \"[TURN RESUMED AFTER WORKER CRASH] The platform worker running this turn died before the turn finished.\",\n \"Your conversation history above, including this turn's earlier work, is preserved up to the last checkpoint; anything in flight after that checkpoint was lost.\",\n \"Continue the original task from where it left off. Before repeating any action with side effects, check whether it already happened.\",\n].join(\"\\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 cancellation (user interrupt) or a server-side timeout.\n */\nexport function isWorkerShutdownCancellation(error: unknown): boolean {\n return error instanceof CancelledFailure && error.message === \"WORKER_SHUTDOWN\";\n}\n\nexport const CONTEXT_WINDOW_OVERFLOW_RECOVERY_MESSAGE =\n \"The conversation reached the model context compaction threshold; it has been compacted. Send a message to continue.\";\nconst MAX_CONTEXT_COMPACTION_RECOVERY_ATTEMPTS = 3;\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(error: unknown): { message: string; code?: string; detail?: string } | null {\n const fields = collectErrorStrings(error);\n const matched = fields.find((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\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 re-dispatch of the SAME turn (preemption resume, 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 only fallback was 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 positional fallback with the\n * per-execution dispatch id (the Temporal activityId, unique per scheduled\n * execution) makes re-dispatched calls distinct while still deduping a\n * same-execution retry.\n */\nexport function modelUsageSourceKey(input: {\n responseId?: string | null | undefined;\n dispatchId: string | null;\n positionalKey: string;\n}): string {\n if (input.responseId) {\n return input.responseId;\n }\n return input.dispatchId ? `${input.dispatchId}:${input.positionalKey}` : input.positionalKey;\n}\n\nexport function 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): { rows: Array<{ position: number; item: Record<string, unknown> }>; nextWatermark: number; nextPosition: number } {\n const sanitized = sanitizeHistoryItemsForModel(rawHistory);\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 { rows, nextWatermark: sanitized.length, nextPosition: nextPosition + rows.length };\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 * - run-state BLOB path (`modelHistoryFromItems === false`: approval resume, the\n * items-mode run-state fallback, run_state mode) — `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<{ item: Record<string, unknown>; producerCodexCredentialId: string | null }>,\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(\"active sandbox backend resolution failed (turn proceeds on home backend)\", error);\n return undefined;\n }\n}\n\n/**\n * Decide whether to start on-turn desktop recording for THIS turn.\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 at turn start (the box is only filmed\n * for the duration of one turn). A swap AFTER the recording starts is deliberately\n * ignored — a partial-turn recording already has defined failure semantics, so we do\n * not add machinery to stop/restart it mid-turn.\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: { provider: { kind: RegistryProviderKind; api: ModelProviderApi } } | 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\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): Promise<CodexAccountStatus[]> {\n const nearPct = settings.codexRotationNearExhaustionPct;\n const stale = accounts.filter(\n (a) => a.status === \"active\" && ((a.primaryUsedPercent ?? 0) >= nearPct || (a.secondaryUsedPercent ?? 0) >= nearPct),\n );\n if (stale.length === 0) {\n return accounts;\n }\n await Promise.all(stale.map((a) => fetchCodexUsageForAccount(db, settings, workspaceId, a.id).catch(() => undefined)));\n return listCodexAccountStatuses(db, workspaceId).catch(() => accounts);\n}\n\nexport function createRunAgentTurnActivity(services: () => Promise<ActivityServices>) {\n return async function runAgentTurn(input: RunAgentTurnInput): Promise<RunAgentTurnResult> {\n const { settings, db, bus, runtime, objectStorage, observability, wakeSessionWorkflow, entitlements, connectionCredentials } = await services();\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_event_id\": input.triggerEventId,\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 heartbeatTimer: ReturnType<typeof startActivityHeartbeat> | undefined;\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 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 lease holder id (Temporal activityId, unique per scheduled execution)\n // + the group id, captured so the lease heartbeat can refresh the lease TTL\n // epoch-fenced (a superseded owner self-evicts) and finally can release.\n let sandboxHolderId: string | 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 // P4.3 on-turn recording: when the desktop tier + recording are enabled and\n // the box is desktop-capable, the turn films the SAME :0 the agent's\n // computer-use drives, finalized to storage in this activity's `finally`\n // (read+PUT in-process — never a Temporal payload, F10). null otherwise.\n let activeRecording: ActiveRecording | null = null;\n // P4.3 recording gate: flips true the first time a computer-use/desktop tool\n // ACTUALLY executes this turn (an SDK `computer_call` item streams through). A\n // plain text turn (\"hey\"/\"continue\") never flips it, so finalize discards the\n // recording with NO storage PUT and NO recording.failed — a clean no-op (a\n // static frame of an untouched desktop is not worth uploading).\n let didComputerUse = false;\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: ((events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>, immediate?: boolean) => Promise<void>) | null = null;\n let turnStartedPublished = false;\n let stream: Awaited<ReturnType<OpenGeniRuntime[\"runStream\"]>> | undefined;\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 by sanitizing the current history into an API-valid sequence (the same\n // pure function the read path uses) before persisting: a dangling call is\n // never persisted (it is deferred until its result exists, when the pair is\n // written together at consecutive positions), and a result is never\n // persisted without its preceding call. The watermark counts only items we\n // actually persisted, so a non-monotonic history can never desync it.\n let persistedHistoryCount = 0;\n let historyCountAtTurnStart = 0;\n let modelOrToolProgressPersisted = false;\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 (options: { skipInputOnlyRows?: boolean } = {}) => {\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) => isModelOrToolProgressHistoryItem(row.item));\n const shouldAppendRows = rows.length > 0 && (!options.skipInputOnlyRows || hasModelOrToolProgress);\n if (shouldAppendRows) {\n await appendSessionHistoryItems(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\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 }\n if (shouldAppendRows || !options.skipInputOnlyRows) {\n persistedHistoryCount = nextWatermark;\n nextHistoryPosition = nextPosition;\n }\n if (hasModelOrToolProgress) {\n modelOrToolProgressPersisted = true;\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 }\n };\n // Reassigned after the workspace environment loads; the publish closure is\n // created (and used for turn.started) before the environment is available.\n let redact: (payload: unknown) => unknown = identityRedactor;\n let environmentId = \"\";\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 // 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 the preemption path: 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(db, input.workspaceId, settings);\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(db, mcpSettings, input.workspaceId);\n const capabilitySettings = await settingsWithCodexCredential(db, input.workspaceId, mcpSettings, codexSubscriptionActive);\n runtime.configure(capabilitySettings);\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n const trigger = await getSessionEvent(db, input.workspaceId, input.triggerEventId);\n if (!trigger) {\n throw new Error(`Trigger event not found: ${input.triggerEventId}`);\n }\n triggerType = trigger.type;\n let turn = input.turnId ? await getSessionTurn(db, input.workspaceId, input.turnId) : await claimNextQueuedTurnDb(db, input.workspaceId, input.sessionId, input.workflowId);\n if (!turn && !input.turnId) {\n const createdTurnId = await createTurn(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n temporalWorkflowId: input.workflowId,\n triggerEventId: input.triggerEventId,\n });\n turn = await getSessionTurn(db, input.workspaceId, createdTurnId);\n }\n if (!turn) {\n throw new Error(`Session turn not found for trigger: ${input.triggerEventId}`);\n }\n turnId = turn.id;\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 const isCodexTurn = await isCodexBilledTurn({ db, settings, workspaceId: input.workspaceId, model: turn.model, active: codexSubscriptionActive });\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(settings, db, input.accountId, input.workspaceId, isCodexTurn, entitlements);\n const activityContext = currentActivityContext();\n // Setup (environment 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 preempt 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 heartbeatTimer = startActivityHeartbeat(activityContext, {\n phase: \"running\",\n sessionId: input.sessionId,\n turnId,\n });\n let producerSeq = 0;\n // One producer per activity execution, not per turn: a turn can run\n // again on the same workflow (preemption resume, 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 const dispatchId = activityContext?.info.activityId ?? null;\n publish = async (events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>, immediate = false) => {\n const inputs = events.map((event) => ({\n ...event,\n payload: redact(event.payload),\n turnId: turnId!,\n producerId,\n producerSeq: ++producerSeq,\n }));\n await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, inputs);\n activityContext?.heartbeat({ phase: \"events_published\", sessionId: input.sessionId, turnId, producerSeq });\n if (immediate) {\n await Bun.sleep(0);\n }\n };\n activityContext?.heartbeat({ phase: \"turn_started\", sessionId: input.sessionId, turnId });\n\n // A shutdown that landed during claim/billing setup preempts before the\n // turn visibly starts: nothing ran yet, so the requeued turn replays the\n // original trigger cleanly on a healthy worker.\n throwIfWorkerShuttingDown();\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"running\", turnId);\n await publish([\n { type: \"session.status.changed\", payload: { status: \"running\" } },\n { type: \"turn.started\", payload: { triggerEventId: input.triggerEventId } },\n ], true);\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 [rotation, accounts, sessionCodex] = await Promise.all([\n getCodexRotationSettings(db, input.workspaceId),\n listCodexAccountStatuses(db, input.workspaceId),\n getSessionCodexState(db, input.workspaceId, input.sessionId),\n ]);\n const connectedIds = new Set(accounts.map((account) => account.id));\n const sessionPin = sessionCodex?.pinnedCredentialId ?? null;\n // The off-path / P1 default: today's workspace active pointer. Untouched\n // when rotation is off or the session is pinned (byte-identical to P1).\n let chosenActive = rotation?.activeCredentialId ?? null;\n let rotationDecision: RotationDecision | null = null;\n\n // P3 auto-rotation: the ONLY new branch, gated on rotation_enabled and\n // pin-guarded (a pinned session NEVER rotates). When skipped, chosenActive\n // stays the active pointer and selectCodexCredentialForTurn is called with\n // byte-identical arguments to today — zero added cost on non-rotation turns.\n if (rotation?.rotationEnabled && sessionPin == null) {\n let rankAccounts = accounts;\n rotationDecision = chooseRotationActive({\n rotationStrategy: rotation.rotationStrategy as CodexRotationStrategy,\n activeCredentialId: rotation.activeCredentialId,\n priorCredentialId: sessionCodex?.lastCredentialId ?? null,\n accounts: rankAccounts,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\n now: new Date(),\n // P4: the leaving (active) account's cached connector set is the proxy\n // for \"what this session has access to\" — prefer a covering target.\n usedConnectors: rankAccounts.find((a) => a.id === rotation.activeCredentialId)?.connectorNamespaces ?? [],\n });\n if (rotationDecision.kind === \"allCapped\") {\n // SELF-HEAL (invariant 4): the turn hot path NEVER refreshes usage, so a\n // window that has actually reset still reads capped from the stale cache —\n // which would otherwise idle-loop forever (idle → continuation re-dispatch →\n // same stale all-capped → idle …). Before idling, refresh usage for the\n // over-threshold accounts (bounded to the account count) and re-rank ONCE,\n // so a genuinely-reset window is picked up immediately and the cache heals.\n rankAccounts = await refreshCappedCodexUsageRows(db, settings, input.workspaceId, rankAccounts);\n rotationDecision = chooseRotationActive({\n rotationStrategy: rotation.rotationStrategy as CodexRotationStrategy,\n activeCredentialId: rotation.activeCredentialId,\n priorCredentialId: sessionCodex?.lastCredentialId ?? null,\n accounts: rankAccounts,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\n now: new Date(),\n // P4: leaving (active) account's connector set (refreshCappedCodexUsageRows\n // only touches usage columns, so connectorNamespaces is preserved here).\n usedConnectors: rankAccounts.find((a) => a.id === rotation.activeCredentialId)?.connectorNamespaces ?? [],\n });\n }\n if (rotationDecision.kind === \"active\") {\n if (rotationDecision.moved) {\n // The single authoritative pointer-move site: persist the new active.\n await setActiveCodexCredential(db, input.workspaceId, rotationDecision.credentialId);\n }\n chosenActive = rotationDecision.credentialId;\n } else if (rotationDecision.kind === \"allCapped\" && publish && turnId) {\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(() => null);\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(rotationDecision.earliestResetAt, new Date(), CODEX_USAGE_LIMIT_MAX_RESUME_MS);\n const failurePayload = codexUsageLimitFailurePayload(\n { resetsInSeconds: Math.ceil(resumeMs / 1000) },\n \"all connected Codex subscriptions are rate-limited\",\n { allAccounts: true },\n );\n await publish([\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 { type: \"turn.failed\", payload: { ...failurePayload, recovery: goalActive ? \"goal_continuation\" : \"user_message\", runStateSaved: false, rotated: true } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\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 goalActive ? { status: \"idle\", continueDelayMs: resumeMs, idleUntilReset: true } : { status: \"idle\" };\n }\n // kind:\"none\" (no accounts) → chosenActive stays null → existing relogin path.\n }\n\n effectiveCodexCredentialId = selectCodexCredentialForTurn({\n sessionPinnedCredentialId: sessionPin, // pin still wins, structurally\n activeCredentialId: chosenActive, // rotation-choice OR today's active\n connectedIds,\n });\n if (effectiveCodexCredentialId) {\n const priorAccountId = sessionCodex?.lastCredentialId ?? null;\n await recordSessionActiveCodexCredential(db, input.workspaceId, input.sessionId, effectiveCodexCredentialId);\n if (priorAccountId !== effectiveCodexCredentialId) {\n // \"rotation\" only when the engine actually moved the pointer; otherwise the\n // unchanged P1 \"manual\" literal (a manual active flip between turns).\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 = rotationDecision?.kind === \"active\" ? rotationDecision.droppedConnectors : undefined;\n await publish([{\n type: \"codex.account.switched\",\n payload: {\n fromAccountId: priorAccountId,\n toAccountId: effectiveCodexCredentialId,\n reason: rotated ? \"rotation\" : \"manual\",\n ...(droppedConnectors && droppedConnectors.length > 0 ? { droppedConnectors } : {}),\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 // 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(db, input.workspaceId);\n const baseRunSettings = {\n ...settingsWithPackSandboxImage(capabilitySettings, packRuntime.sandboxImage),\n openaiModel: turn.model,\n openaiReasoningEffort: turn.reasoningEffort,\n sandboxBackend: turn.sandboxBackend,\n };\n const runSettings = await settingsWithSessionMcpServersForRun(db, input.workspaceId, input.sessionId, baseRunSettings);\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 // 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 = 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(db, runSettings, input.workspaceId, effectiveCodexCredentialId ?? \"\");\n return {\n clientVersion: CODEX_CLIENT_VERSION,\n getToken: resolver.getToken,\n refresh: resolver.refresh,\n resolveModel: buildModelResolver(CODEX_FALLBACK_MODEL_SLUGS, CODEX_FALLBACK_MODEL_SLUGS[0]),\n onUsageHeaders: (snapshot) => { latestCodexUsage = snapshot; }, // latest wins; flushed once in finally\n };\n })()\n : null;\n const withCodex = <T>(fn: () => Promise<T>): Promise<T> => (codexContext ? codexRequestStorage.run(codexContext, fn) : fn());\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(runSettings, withFirstPartyTools(runSettings, mergeToolRefs(session.tools, turn.tools)));\n // §7.6 P4a — load (and decrypt) the workspace environment via the host\n // `sandboxSecrets` provider when bound; unset → today's local decrypt.\n const connectionScope = { accountId: input.accountId, workspaceId: input.workspaceId };\n const workspaceEnvironment = await loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n session.environmentId,\n connectionCredentials?.sandboxSecrets,\n );\n environmentId = workspaceEnvironment?.id ?? \"\";\n redact = createSecretRedactor(\n Object.entries(workspaceEnvironment?.values ?? {}).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 the\n // inert GitHub token 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 const activeSandboxPointer = routingOn\n ? await readActiveSandbox(db, input.workspaceId, input.sessionId).catch(() => null)\n : null;\n const activeSandboxRecord = routingOn && activeSandboxPointer?.activeSandboxId\n ? await getSandbox(db, input.workspaceId, activeSandboxPointer.activeSandboxId).catch(() => null)\n : null;\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 // 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 GitHub installation token on every call, so a second call would\n // yield a DIFFERENT token value 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 GitHub token minted ONCE per turn as `gitToken`. The env feeds BOTH\n // the box manifest AND the agent (env-parity, as before); the token is threaded\n // OFF-MANIFEST as the clone-seed `gitTokenSeed` to buildAgent (below) so the box\n // never carries a rotating value on its manifest. When the platform token IS\n // minted, the host `gitCredentials` provider may supply it; unset → self-mint\n // from settings. gitToken is undefined on the selfhosted skip path (the machine\n // uses its own git creds).\n const {\n environment: sandboxEnvironment,\n gitToken: sandboxGitToken,\n toolspaceToken: sandboxToolspaceToken,\n } = await sandboxEnvironmentForRun(\n runSettings,\n turnResources,\n workspaceEnvironment?.values ?? {},\n {\n skipGitHubToken: activeSandboxBackend === \"selfhosted\",\n scope: connectionScope,\n gitCredentials: connectionCredentials?.gitCredentials,\n sessionId: input.sessionId,\n runId: turnId,\n },\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 ('turn' holder = the activityId),\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 environment the agent declares — the SDK\n // applies the agent's manifest to this provided session and throws on ANY\n // environment delta (validateNoEnvironmentDelta). Passing sandboxEnvironment\n // here makes current==target so the delta is empty.\n if (settings.sandboxOwnershipEnabled && turn.sandboxBackend !== \"none\") {\n sandboxHolderId = dispatchId ?? `turn:${turnId}`;\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 const groupBoxBackend: Settings[\"sandboxBackend\"] =\n turn.sandboxBackend === \"selfhosted\" && !machinePrimary\n ? settings.sandboxBackend\n : turn.sandboxBackend;\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 const established = await establishSelfhostedTurnSession(\n { db, settings, bus },\n {\n workspaceId: input.workspaceId,\n agentId: activeSandboxRecord!.enrollmentId!,\n epoch: activeSandboxPointer!.activeEpoch,\n environment: sandboxEnvironment,\n workingDir: activeSandboxPointer!.workingDir,\n },\n );\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 { db, settings, bus },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\n pinnedSelfhosted: {\n sandboxId: activeSandboxPointer!.activeSandboxId!,\n epoch: activeSandboxPointer!.activeEpoch,\n },\n },\n established,\n ),\n leaseEpoch: lease.leaseEpoch,\n release: lease.release,\n };\n } else {\n resolvedSandbox = await resumeBoxForTurn(\n { db, settings, sandboxMetrics: runtimeMetricsHooksForObservability(observability) },\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 ? { image: runSettings.modalImageRef ?? runSettings.dockerImage }\n : {}),\n },\n \"turn\",\n sandboxHolderId,\n );\n setupBoxSession = resolvedSandbox.established.session;\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 { workspaceId: input.workspaceId, sessionId: input.sessionId, environment: sandboxEnvironment },\n resolvedSandbox.established,\n ),\n };\n }\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 = resolvedSandbox.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(settings, activeSandboxBackend ?? groupBoxBackend);\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 }, 10_000);\n if (\"unref\" in leaseHeartbeatTimer && typeof leaseHeartbeatTimer.unref === \"function\") {\n leaseHeartbeatTimer.unref();\n }\n }\n\n // P4.3 on-turn recording. The box's :0 display stack was brought up by\n // resumeBoxForTurn (spawner path) / is up from a prior turn; film it for\n // the duration of this turn so the human can watch the agent work and the\n // agent's computer-use proofs are captured. Best-effort: a recording start\n // failure NEVER fails the turn (the desktop is a value-add). Finalized in\n // `finally` (read+PUT in this same activity — never a Temporal payload).\n if (\n resolvedSandbox\n && shouldStartOnTurnRecording({\n recordingEnabled: settings.recordingEnabled,\n desktopEnabled: settings.sandboxDesktopEnabled,\n establishedBackendId: resolvedSandbox.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: activeSandboxBackend,\n })\n ) {\n try {\n const 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: resolvedSandbox.established.session,\n runAs: sandboxRunAs(settings),\n reason: null,\n });\n activeRecording = begun.active;\n await publish([{ type: \"recording.started\", payload: begun.started }]);\n } catch (recordingError) {\n activeRecording = null;\n console.error(\"on-turn recording start failed (turn outcome unaffected)\", recordingError);\n }\n }\n\n const fileResourceDownloads = await sandboxFileDownloadsForRun(runSettings, db, objectStorage, input.workspaceId, turnResources);\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(() => runtime.prepareTools(runSettings, turnTools, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\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 ? { firstPartyPermissions: session.firstPartyMcpPermissions } : {}),\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; continuation/preemption turns never match (their\n // trigger is goal.continuation/turn.preempted).\n const isGenesisTurn = 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 const agent = runtime.buildAgent(runSettings, turnResources, {\n reasoningEffort: turn.reasoningEffort,\n genesisTitleHint: isGenesisTurn,\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\" && sandboxGitToken ? { gitTokenSeed: sandboxGitToken } : {}),\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 compactionMode: resolvedModel.provider.compactionMode,\n hostedWebSearch: resolvedModel.configured.hostedWebSearch,\n encryptedReasoning: resolvedModel.provider.api === \"responses\" && runSettings.openaiReasoningEncryptedContent,\n contextWindowTokens: 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 }\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 : { computerToolMode: computerToolModeForTurn(null) }),\n ...(packRuntime.skills.length > 0 ? { packSkills: packRuntime.skills } : {}),\n ...(workspaceAgentInstructions ? { instructionsTemplate: workspaceAgentInstructions } : {}),\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 ...(workspaceEnvironment\n ? {\n workspaceEnvironment: {\n name: workspaceEnvironment.name,\n description: workspaceEnvironment.description,\n variableNames: Object.keys(workspaceEnvironment.values),\n },\n }\n : {}),\n });\n const compactSummarizer = resolvedModel\n ? (s: Settings, m: Array<Record<string, unknown>>, o?: { maxTranscriptTokens?: number }) => withCodex(() => summarizeForCompaction(s, m, {\n client: resolvedModel.client,\n api: resolvedModel.provider.api,\n model: resolvedModel.configured.id,\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n ...(o?.maxTranscriptTokens ? { maxTranscriptTokens: o.maxTranscriptTokens } : {}),\n }))\n : undefined;\n // Pre-turn client-side context compaction (Azure path). When the\n // resolved mode is \"client\" and the single Codex-parity threshold is\n // crossed, this summarizes the current active history and rebuilds active\n // history as [user messages..., summary] BEFORE the model input is read.\n // Summarizer failures fall through to hard-trim retry and deterministic\n // fallback; only structural no-ops leave the history unchanged.\n // Skipped on approval/preempt resumes (no fresh user turn; the frozen\n // RunState or in-flight tail must replay verbatim).\n if (triggerType === \"user.message\" || triggerType === \"goal.continuation\") {\n try {\n // Operator /compact (the slash command) sets a durable request flag;\n // consume it atomically so a forced compaction runs now even when the\n // budget trigger would not fire. Only the turn that observes the flag\n // runs it, so concurrent turns can't double-compact.\n const forced = await consumeSessionCompactionRequest(db, input.workspaceId, input.sessionId);\n const outcome = await maybeCompactContext(\n db,\n runSettings,\n { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId },\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 keeps the default built-in Responses summarizer.\n compactSummarizer,\n forced ? { force: true } : {},\n );\n if (outcome.compacted) {\n const trigger = forced ? \"operator\" : undefined;\n await publish([{ type: \"session.context.compacted\", payload: { summaryPosition: outcome.summaryPosition, ...(trigger ? { trigger } : {}) } }]);\n }\n } catch (compactError) {\n console.error(\"context compaction failed (turn proceeds un-compacted)\", compactError);\n }\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 runSettings,\n { currentCodexCredentialId: effectiveCodexCredentialId },\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(db, input.workspaceId, input.sessionId);\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(\n activeSeedRows,\n prepared.modelHistoryFromItems,\n { currentCodexCredentialId: effectiveCodexCredentialId },\n );\n historyCountAtTurnStart = persistedHistoryCount;\n nextHistoryPosition = await nextSessionHistoryPosition(db, input.workspaceId, input.sessionId);\n };\n\n const forceContextCompaction = async (triggerLabel: \"overflow\" | \"proactive\") => {\n const clientCompactionSettings: Settings = { ...runSettings, contextCompactionMode: \"client\" };\n const outcome = await maybeCompactContext(\n db,\n clientCompactionSettings,\n { accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: activeTurnId },\n session.lastInputTokens,\n compactSummarizer,\n { force: true, requireShrink: true },\n );\n if (outcome.compacted) {\n await publish!([{ type: \"session.context.compacted\", payload: { summaryPosition: outcome.summaryPosition, trigger: triggerLabel } }]);\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 runStreamOnce = (): ReturnType<OpenGeniRuntime[\"runStream\"]> => runtime.runStream(agent, runInput!, runSettings, {\n sandboxEnvironment,\n onRuntimeEvent: async (event) => {\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 ...(resolvedSandbox\n ? {\n ownedSandbox: {\n client: resolvedSandbox.established.client,\n session: resolvedSandbox.established.session,\n sessionState: resolvedSandbox.established.sessionState,\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 },\n }\n : {}),\n contextCompactionSignalTokens: () => lastInputTokensObserved,\n });\n stream = await withCodex(runStreamOnce);\n batcher = createRuntimeBatcher(async (events) => {\n await publish!(events);\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 responseUsageCount += 1;\n const observed = responseUsage.usage?.inputTokens;\n if (typeof observed === \"number\" && observed > 0) {\n lastInputTokensObserved = observed;\n await setSessionLastInputTokens(db, input.workspaceId, input.sessionId, observed)\n .catch((error) => console.error(\"persist last_input_tokens failed (non-fatal)\", error));\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: modelUsageSourceKey({\n responseId: responseUsage.responseId,\n dispatchId,\n positionalKey: `response-${responseUsageCount}`,\n }),\n observability,\n });\n await reconcileConversationTruth();\n try {\n await ensureRunAllowed(settings, db, input.accountId, input.workspaceId, isCodexTurn, entitlements);\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 // Recording gate: a computer-use tool actually ran when an SDK\n // `tool_call_item` whose rawItem.type is \"computer_call\" streams through\n // (screenshot/click/type/scroll/etc. — the first computer action proves\n // the desktop was driven). Match the raw SDK event (ground truth) BEFORE\n // normalization. Only meaningful when a recording is live.\n if (activeRecording && !didComputerUse && isComputerCallStreamEvent(next.value)) {\n didComputerUse = true;\n }\n const normalized = normalizeSdkEvent(next.value);\n for (const event of normalized) {\n await batcher.push(event);\n }\n }\n } finally {\n if (!streamDone) {\n await iterator.return?.();\n }\n }\n await batcher.flush();\n await stream.completed.catch(() => undefined);\n if (responseUsageCount === 0) {\n const aggregateInput = (stream.state.usage as { inputTokens?: unknown } | undefined)?.inputTokens;\n if (typeof aggregateInput === \"number\" && aggregateInput > 0) {\n lastInputTokensObserved = aggregateInput;\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: stream.state.usage,\n sourceKey: modelUsageSourceKey({ responseId: null, dispatchId, positionalKey: \"aggregate\" }),\n observability,\n });\n }\n if (lastInputTokensObserved !== null) {\n await setSessionLastInputTokens(db, input.workspaceId, input.sessionId, lastInputTokensObserved)\n .catch((error) => console.error(\"persist last_input_tokens failed (non-fatal)\", error));\n }\n\n if (stream.interruptions.length > 0) {\n await reconcileConversationTruth();\n const approvals = runtime.serializeApprovals(stream.interruptions);\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\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 await publish!([\n { type: \"session.requiresAction\", payload: { approvals } },\n { type: \"session.status.changed\", payload: { status: \"requires_action\" } },\n ], true);\n await finishTurn(db, input.workspaceId, activeTurnId, \"requires_action\");\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"requires_action\", activeTurnId);\n activityStatus = \"requires_action\";\n return { status: \"requires_action\" };\n }\n\n const finalOutput = String(stream.finalOutput ?? \"\");\n await reconcileConversationTruth();\n if (settings.sessionHistorySource !== \"items\") {\n // Legacy conversation memory; in items mode the blob is only written\n // for requires_action pauses (the one RunState-only resume path).\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n serializedRunState: stream.state.toString(),\n pendingApprovals: [],\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n }\n await publish!([\n { type: \"agent.message.completed\", payload: { text: finalOutput } },\n { type: \"turn.completed\", payload: { output: finalOutput } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, activeTurnId, \"idle\");\n turnMetricOutcome = \"completed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\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 { status: \"idle\" };\n };\n\n await prepareRunAttemptInput();\n let compactionRecoveryAttempts = 0;\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 ? \"proactive\" : overflow ? \"overflow\" : null;\n if (recoveryKind && compactionRecoveryAttempts >= MAX_CONTEXT_COMPACTION_RECOVERY_ATTEMPTS) {\n throw new Error(\n `compaction summarization failed: context compaction recovery attempt cap reached (${MAX_CONTEXT_COMPACTION_RECOVERY_ATTEMPTS})`,\n { cause: attemptError },\n );\n }\n if (!recoveryKind || !publish || !turnStartedPublished) {\n throw attemptError;\n }\n compactionRecoveryAttempts += 1;\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ skipInputOnlyRows: true });\n const progressPersisted = modelOrToolProgressPersisted;\n observability.warn(\"context compaction recovery attempted\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n progressPersisted,\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 compactionFailureMessage: string | null = null;\n try {\n const outcome = await forceContextCompaction(recoveryKind);\n compacted = outcome.compacted;\n if (!outcome.compacted) {\n compactionFailureMessage = compactionFailureReason(outcome.reason);\n }\n } catch (compactError) {\n compactionFailureMessage = compactionFailureReason(compactError instanceof Error ? compactError.message : String(compactError));\n observability.warn(\"context compaction recovery compaction failed\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n error: compactionFailureMessage,\n });\n }\n if (!compacted) {\n const errorMessage = compactionFailureMessage ?? \"compaction summarization failed: compaction produced no replacement history\";\n if (!progressPersisted) {\n throw new Error(errorMessage, { cause: attemptError });\n }\n await publish!([\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, activeTurnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\n activityStatus = \"idle\";\n activityError = attemptError;\n return { status: \"idle\" };\n }\n if (progressPersisted) {\n // The user's intent was live mid-turn — after a successful\n // compaction the turn AUTO-CONTINUES via the same synthesized\n // resume-notice requeue the worker-shutdown checkpoint uses (never\n // the original trigger, so side effects are not replayed). Idle is\n // the fallback, not the default; it remains for: legacy run-state\n // history (resuming the frozen pre-compaction RunState would\n // overflow again), a compaction that could not shrink anything,\n // and a turn that ALREADY resumed from an overflow (loop guard —\n // a second overflow in the same lineage stops churning).\n const triggerPayload =\n trigger.payload && typeof trigger.payload === \"object\" && !Array.isArray(trigger.payload)\n ? trigger.payload as Record<string, unknown>\n : {};\n const compactionResumedTurn = triggerType === \"turn.preempted\"\n && (triggerPayload.reason === \"context_compacted\" || triggerPayload.reason === \"context_overflow_compacted\");\n const canAutoContinue =\n compacted && !compactionResumedTurn && settings.sessionHistorySource === \"items\" && activeTurnId != null;\n if (canAutoContinue) {\n const [preemptedEvent] = await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n turnId: activeTurnId,\n type: \"turn.preempted\",\n payload: {\n triggerEventId: input.triggerEventId,\n reason: \"context_compacted\",\n resumeWithNotice: true,\n text: CONTEXT_OVERFLOW_RESUME_TEXT,\n },\n },\n { turnId: activeTurnId, type: \"session.status.changed\", payload: { status: \"queued\" } },\n ]);\n await requeuePreemptedTurn(db, input.workspaceId, activeTurnId, preemptedEvent ? preemptedEvent.id : input.triggerEventId);\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"queued\", null).catch(() => undefined);\n activityStatus = \"preempted\";\n turnMetricOutcome = \"preempted\";\n observability.info(\"context compaction recovery succeeded by compacting and auto-continuing\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n compacted,\n });\n return { status: \"preempted\" };\n }\n await publish!([\n {\n type: \"turn.failed\",\n payload: {\n error: CONTEXT_WINDOW_OVERFLOW_RECOVERY_MESSAGE,\n code: recoveryKind === \"overflow\" ? \"context_window_overflow_compacted\" : \"context_compacted\",\n retryable: false,\n recovery: \"user_message\",\n compacted,\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, activeTurnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\n activityStatus = \"idle\";\n activityError = attemptError;\n observability.info(\"context compaction recovery succeeded by compacting and idling\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n compacted,\n });\n return { status: \"idle\" };\n }\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 and\n // hand the turn back instead of failing the session. Conversation truth\n // is already dual-written per model response; the final reconcile below\n // bounds the loss to at most the single in-flight model step. The turn\n // is re-queued so the session workflow re-dispatches it on a healthy\n // worker — through a synthesized resume notice when this turn already\n // persisted progress (replaying the original trigger would duplicate\n // input the model has already seen and invite it to redo side effects),\n // or through the original trigger when nothing was persisted yet. This\n // is an explicit checkpoint/resume, not a blind activity retry: the\n // resumed attempt sees everything the first attempt did.\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 requeue, not fail the session. In\n // that early case nothing ran and nothing was checkpointed, so the\n // requeued turn replays the original trigger cleanly. The turn id falls\n // back to the workflow-claimed turn when the local lookup had not\n // finished yet.\n const preemptTurnId = turnId ?? input.turnId;\n // P1.2: a lease supersession during resume (a newer epoch re-established\n // the box concurrently) is NOT a session failure — re-dispatch the turn so\n // it re-resumes by id under the current epoch. Requeue + idle, mirroring\n // the worker-death re-dispatch (any worker re-resumes by id).\n if (error instanceof SandboxLeaseSupersededError && preemptTurnId) {\n try {\n await requeuePreemptedTurn(db, input.workspaceId, preemptTurnId, input.triggerEventId);\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"queued\", null).catch(() => undefined);\n activityStatus = \"preempted\";\n turnMetricOutcome = \"preempted\";\n return { status: \"preempted\" };\n } catch (requeueError) {\n console.error(\"sandbox lease supersession requeue failed; falling back\", requeueError);\n }\n }\n if (isWorkerShutdownCancellation(error) && preemptTurnId) {\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 preemption already accepts.\n const approvalRerun = triggerType === \"user.approvalDecision\";\n let resumeWithNotice = !approvalRerun && settings.sessionHistorySource === \"items\" && persistedHistoryCount > historyCountAtTurnStart;\n if (settings.sessionHistorySource !== \"items\" && stream) {\n // Legacy run-state mode: the resume reads the RunState blob, so\n // the checkpoint must be captured there — including any pending\n // approval interruptions, exactly like the requires_action path,\n // so a shutdown while approvals wait does not erase them. A\n // failed capture falls back to the previous snapshot and a clean\n // re-run of the original trigger.\n try {\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: preemptTurnId,\n serializedRunState: stream.state.toString(),\n pendingApprovals: runtime.serializeApprovals(stream.interruptions ?? []),\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n resumeWithNotice = true;\n } catch {\n resumeWithNotice = false;\n }\n }\n const [preemptedEvent] = await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n turnId: preemptTurnId,\n type: \"turn.preempted\",\n payload: {\n triggerEventId: input.triggerEventId,\n reason: \"worker_shutdown\",\n resumeWithNotice,\n ...(resumeWithNotice ? { text: WORKER_SHUTDOWN_RESUME_TEXT } : {}),\n },\n },\n {\n turnId: preemptTurnId,\n type: \"session.status.changed\",\n payload: { status: \"queued\" },\n },\n ]);\n await requeuePreemptedTurn(db, input.workspaceId, preemptTurnId, resumeWithNotice && preemptedEvent ? preemptedEvent.id : input.triggerEventId);\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"queued\", null).catch(() => undefined);\n activityStatus = \"preempted\";\n turnMetricOutcome = \"preempted\";\n return { status: \"preempted\" };\n } catch (preemptError) {\n // A failing checkpoint/requeue must not surface as an arbitrary\n // activity error around a half-applied preemption (the workflow\n // would fail the session while a requeued turn lingers). Fall\n // through to the cancellation path below: the turn is marked\n // cancelled — also resetting a turn this block already requeued —\n // and the session fails like an uncheckpointed death.\n console.error(\"worker-shutdown preemption failed; falling back to cancellation\", preemptError);\n }\n }\n if (error instanceof CancelledFailure) {\n activityStatus = \"cancelled\";\n activityError = error;\n await flushRuntimeBatcher();\n if (preemptTurnId) {\n await finishTurn(db, input.workspaceId, preemptTurnId, \"cancelled\").catch(() => undefined);\n turnMetricOutcome = \"cancelled\";\n }\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 const runStateSaved = Boolean(maxTurns.serializedRunState) && settings.sessionHistorySource !== \"items\";\n if (maxTurns.serializedRunState && settings.sessionHistorySource !== \"items\") {\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n serializedRunState: maxTurns.serializedRunState,\n pendingApprovals: [],\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n }\n await publish([\n { type: \"turn.completed\", payload: { output: \"\", segmentLimit: \"max_turns\", runStateSaved } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"idle\");\n turnMetricOutcome = \"completed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\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 { status: \"idle\" };\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 = classifyCodexUsageLimitError(error);\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 const serializedRunState = agentsErrorRunState(error);\n const runStateSaved = Boolean(serializedRunState) && settings.sessionHistorySource !== \"items\";\n if (serializedRunState && settings.sessionHistorySource !== \"items\") {\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n serializedRunState,\n pendingApprovals: [],\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n }\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 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 rotating = Boolean(rotation?.rotationEnabled) && (sessionCodex?.pinnedCredentialId == null);\n if (rotating && rotation) {\n const accounts = await listCodexAccountStatuses(db, input.workspaceId).catch(() => []);\n const serving = accounts.find((a) => a.id === effectiveCodexCredentialId) ?? null;\n // Cooldown end (invariant 5): authoritative resets_in_seconds from the 429; else\n // the serving account's soonest cached window reset; else the 1h cap.\n const cachedReset = [serving?.primaryResetAt, serving?.secondaryResetAt]\n .filter((d): d is Date => d instanceof Date && d.getTime() > Date.now())\n .sort((a, b) => a.getTime() - b.getTime())[0] ?? null;\n const until = usageLimit.resetsInSeconds !== null && Number.isFinite(usageLimit.resetsInSeconds) && usageLimit.resetsInSeconds > 0\n ? new Date(Date.now() + Math.ceil(usageLimit.resetsInSeconds) * 1000)\n : (cachedReset ?? new Date(Date.now() + CODEX_USAGE_LIMIT_MAX_RESUME_MS));\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 cooldownPersisted = await setCodexCredentialExhausted(db, input.workspaceId, effectiveCodexCredentialId, until).catch(() => false);\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) => (a.id === effectiveCodexCredentialId ? { ...a, exhaustedUntil: until } : a));\n const decision = chooseRotationActive({\n rotationStrategy: rotation.rotationStrategy as CodexRotationStrategy,\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(db, input.workspaceId, input.sessionId).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 }\n // kind:\"none\" → fall through to today's single-account idle.\n }\n }\n\n const failurePayload = allCappedResetAt\n ? codexUsageLimitFailurePayload(\n { resetsInSeconds: Math.ceil(Math.max(0, allCappedResetAt.getTime() - Date.now()) / 1000) },\n error instanceof Error ? error.message : String(error),\n { allAccounts: true },\n )\n : codexUsageLimitFailurePayload(usageLimit, error instanceof Error ? error.message : String(error));\n await publish([\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 { type: \"turn.failed\", payload: { ...failurePayload, recovery: goalActive ? \"goal_continuation\" : \"user_message\", runStateSaved, ...(rotated ? { rotated: true } : {}) } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\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 { status: \"idle\", continueDelayMs: rotationResumeMs, ...(rotationResumeIdleUntilReset ? { idleUntilReset: true } : {}) };\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 && Number.isFinite(usageLimit.resetsInSeconds) && usageLimit.resetsInSeconds > 0\n ? Math.min(Math.ceil(usageLimit.resetsInSeconds) * 1000, CODEX_USAGE_LIMIT_MAX_RESUME_MS)\n : CODEX_USAGE_LIMIT_MAX_RESUME_MS);\n return { status: \"idle\", continueDelayMs: resumeMs, ...(allCappedResetAt ? { idleUntilReset: true } : {}) };\n }\n return { 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 const runStateSaved = Boolean(error.serializedRunState) && settings.sessionHistorySource !== \"items\";\n if (error.serializedRunState && settings.sessionHistorySource !== \"items\") {\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n serializedRunState: error.serializedRunState,\n pendingApprovals: [],\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n }\n await publish([\n { type: \"turn.completed\", payload: { output: \"\", segmentLimit: \"budget_exhausted\", detail: error.message, runStateSaved } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"idle\");\n turnMetricOutcome = \"completed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\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 { status: \"idle\" };\n }\n // A retryable provider failure (rate limit) is transient backpressure,\n // not a session failure: the in-client retry budget is already\n // exhausted by the time the error reaches here, so fail the turn\n // truthfully but idle the session. With an active goal the continuation\n // loop resumes after a pacing delay; without one the session simply\n // waits for the next user message. Long-lived sessions (a per-customer\n // ops channel between goals) must never go terminal because the\n // provider had a bad minute -- a failed session would reject the very\n // retry message the failure asks for.\n const failure = agentRunFailurePayload(error);\n if (failure.retryable && 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 // Provider errors rarely carry SDK run state; a null falls back to\n // the previous snapshot, same degraded-context contract as the\n // max-turns path above.\n await reconcileConversationTruth();\n const serializedRunState = agentsErrorRunState(error);\n const runStateSaved = Boolean(serializedRunState) && settings.sessionHistorySource !== \"items\";\n if (serializedRunState && settings.sessionHistorySource !== \"items\") {\n await saveRunState(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n serializedRunState,\n pendingApprovals: [],\n frozenCodexCredentialId: effectiveCodexCredentialId,\n });\n }\n await publish([\n { type: \"turn.failed\", payload: { ...failure, recovery: goalActive ? \"goal_continuation\" : \"user_message\", runStateSaved } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\n activityStatus = \"idle\";\n activityError = error;\n return goalActive ? { status: \"idle\", continueDelayMs: PROVIDER_BACKPRESSURE_DELAY_MS } : { status: \"idle\" };\n }\n activityStatus = \"failed\";\n activityError = error;\n if (!publish || !turnId || !turnStartedPublished) {\n throw error;\n }\n await publish([\n { type: \"turn.failed\", payload: failure },\n { type: \"session.status.changed\", payload: { status: \"failed\" } },\n ], true);\n await finishTurn(db, input.workspaceId, turnId, \"failed\");\n turnMetricOutcome = \"failed\";\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"failed\", null);\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({ db, bus, settings, observability, wakeSessionWorkflow }, input.workspaceId, input.sessionId, \"failed\", `turn:${turnId}`);\n return { status: \"failed\" };\n } finally {\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.environment_id\": environmentId,\n \"opengeni.duration_ms\": Math.round(durationSeconds * 1000),\n },\n error: activityError,\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 await recordCodexAccountUsage(db, input.workspaceId, effectiveCodexCredentialId, latestCodexUsage)\n .catch(() => undefined);\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, [...connectorNamespaces])\n .catch(() => undefined);\n }\n }\n await preparedTools?.close().catch(() => undefined);\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\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 // P4.3: finalize the on-turn recording BEFORE releasing the box handle\n // (the read+PUT needs the live session). read bytes → storage PUT →\n // updateRecording(available) → publish recording.available; the box file is\n // deleted only after the PUT confirms (F9). Best-effort: a finalize failure\n // emits recording.failed and never masks the turn outcome (F10: the bytes\n // never become a Temporal payload — read+PUT happen here in-process).\n if (activeRecording && resolvedSandbox) {\n try {\n if (!didComputerUse) {\n // Recording gate (P4.3): the turn never drove the desktop (a plain text\n // turn), so the film is a static frame of an untouched screen. DISCARD\n // it — stop ffmpeg, delete the box artifact, drop the row — with NO\n // storage PUT and NO recording.failed (a clean no-op, not a failure).\n await discardRecording({\n db,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n active: activeRecording,\n session: resolvedSandbox.established.session,\n });\n } else {\n const outcome = await finalizeRecording({\n settings,\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n active: activeRecording,\n session: resolvedSandbox.established.session,\n runAs: sandboxRunAs(settings),\n });\n if (publish) {\n await publish(outcome.ok\n ? [{ type: \"recording.available\", payload: outcome.available }]\n : [{ type: \"recording.failed\", payload: { recordingId: activeRecording.recordingId, turnId: activeRecording.turnId, reason: outcome.reason, detail: outcome.detail } }]);\n }\n }\n } catch (finalizeError) {\n console.error(\"recording finalize failed (turn outcome unaffected)\", finalizeError);\n } finally {\n activeRecording = null;\n }\n }\n if (resolvedSandbox) {\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\nexport function agentRunFailurePayload(error: unknown): { error: string; code?: string; retryable?: boolean; detail?: string } {\n const message = error instanceof Error ? error.message : String(error);\n const status = typeof error === \"object\" && error !== null && \"status\" in error\n ? Number((error as { status?: unknown }).status)\n : undefined;\n const code = 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 const usageLimit = classifyCodexUsageLimitError(error);\n if (usageLimit) {\n return codexUsageLimitFailurePayload(usageLimit, message);\n }\n if (status === 429 || code === \"rate_limit_exceeded\" || /(?:too many requests|rate.?limit|\\b429\\b)/i.test(message)) {\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 return { error: message };\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\n/**\n * Recognize an SDK stream event that represents a COMPUTER-USE tool call actually\n * executing — a `run_item_stream_event` carrying a `tool_call_item` whose\n * underlying raw item is a `computer_call` (the @openai/agents computer tool's\n * action: screenshot/click/type/scroll/drag/keypress/move/wait/…). This is the\n * same shape `normalizeSdkEvent` reads (`event.item.rawItem`), matched here against\n * the raw SDK type rather than a tool NAME so it is robust to the computer tool's\n * configured name. Drives the on-turn recording gate (no computer-use → discard).\n */\nfunction isComputerCallStreamEvent(event: unknown): boolean {\n if (!event || typeof event !== \"object\") {\n return false;\n }\n if ((event as { type?: unknown }).type !== \"run_item_stream_event\") {\n return false;\n }\n const item = (event as { item?: { type?: unknown; rawItem?: { type?: unknown } } }).item;\n if (!item || item.type !== \"tool_call_item\") {\n return false;\n }\n return item.rawItem?.type === \"computer_call\";\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(message: string, readonly serializedRunState: string | null) {\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 (!isCodexTurn && entitlements && (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")) {\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 (!isCodexTurn && (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")) {\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(`monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`);\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(settings: Settings, db: ActivityServices[\"db\"], 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}): 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 },\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((resource): resource is Extract<ResourceRef, { kind: \"file\" }> => resource.kind === \"file\");\n if (fileResources.length === 0) {\n return [];\n }\n if (!objectStorage) {\n throw new Error(`${settings.objectStorageBackend} file resources require configured object storage`);\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 (settings.sandboxBackend === \"docker\" && settings.objectStorageBackend === \"s3-compatible\")\n || settings.objectStorageBackend === \"aws-s3\"\n || settings.objectStorageBackend === \"gcs\"\n || (nativeBucketMount && settings.objectStorageBackend === \"azure-blob\");\n}\n\nfunction objectStorageForSandboxDownloads(settings: Settings, objectStorage: ObjectStorage): ObjectStorage {\n if (settings.objectStorageBackend !== \"s3-compatible\" || !settings.objectStorageSandboxEndpoint) {\n return objectStorage;\n }\n return createObjectStorage({\n ...settings,\n objectStorageEndpoint: settings.objectStorageSandboxEndpoint,\n }) ?? objectStorage;\n}\n","import { environmentsEncryptionKeyBytes, parseModelProvidersJson, type RegistryProvider, type Settings } 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_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(db: Database, workspaceId: string, settings: Settings): 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(settings, await listSessionMcpServersForRun(db, workspaceId, sessionId, encryptionKey));\n}\n\nexport function settingsWithSessionMcpServers(settings: Settings, servers: SessionMcpServerForRun[]): 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 ? { requireApproval: server.requireApproval } : {}),\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(db: Database, workspaceId: string, settings: Settings, activeOverride?: boolean): 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 = 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) => ({ id: `${CODEX_MODEL_ID_PREFIX}${slug}`, label: slug, reasoningEffort: true })),\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 { CodexAccountStatus } from \"@opengeni/db\";\n\nexport type CodexRotationStrategy = \"most_remaining\" | \"round_robin\" | \"drain_then_next\";\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\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\n/** The worse-window used percent: weekly binds as hard as 5h, so take the max. null ⇒ 0. */\nfunction bindingUsedPct(acct: CodexAccountStatus): number {\n return Math.max(acct.primaryUsedPercent ?? 0, acct.secondaryUsedPercent ?? 0);\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: CodexAccountStatus): number {\n const primaryRemaining = 100 - (acct.primaryUsedPercent ?? 0);\n const secondaryRemaining = 100 - (acct.secondaryUsedPercent ?? 0);\n return Math.min(primaryRemaining, secondaryRemaining);\n}\n\nfunction cooling(acct: CodexAccountStatus, 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: CodexAccountStatus, 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: CodexAccountStatus, 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 * Eligible = connected/usable (status \"active\", excludes needs_relogin/error) AND\n * not cooling AND under the near-exhaustion threshold on BOTH windows.\n */\nfunction eligible(acct: CodexAccountStatus, nearExhaustionPct: number, now: Date): boolean {\n return acct.status === \"active\" && !cooling(acct, now) && bindingUsedPct(acct) < nearExhaustionPct;\n}\n\n/**\n * The soonest instant `acct` clears EVERY blocking condition: its cooldown end,\n * and each window's reset (only when that window is at/over the threshold). The\n * literal multi-account generalization of #143's single-account resetsInSeconds.\n *\n * GUARANTEE (invariant 4): the result is ALWAYS in the future. A blocking window\n * whose cached reset is null / unknown / already-elapsed does NOT contribute a past\n * instant (the old EPOCH0 seed bug that made earliestReset land in 1970 → a 0\n * continueDelayMs → a tight idle loop). Such a window is treated as clearing after a\n * default cooldown (now + DEFAULT_RESET_COOLDOWN_MS), so the caller always idles a\n * bounded positive time and re-checks (which refreshes usage and self-heals).\n */\nexport function availableAt(acct: CodexAccountStatus, nearExhaustionPct: number, now: Date): Date {\n const nowMs = now.getTime();\n // An unknown/elapsed block clears after a default cooldown, never in the past.\n const defaultClear = new Date(nowMs + DEFAULT_RESET_COOLDOWN_MS);\n const candidates: Date[] = [];\n // An active cooldown only blocks while it is still in the future; a past cooldown\n // self-clears (matches `cooling()`), so it must not pin availableAt to the past.\n if (acct.exhaustedUntil != null && acct.exhaustedUntil.getTime() > nowMs) {\n candidates.push(acct.exhaustedUntil);\n }\n const windowClear = (over: boolean, resetAt: Date | null | undefined) => {\n if (!over) return;\n // Over-threshold window: wait for its KNOWN future reset; a null/elapsed cached\n // reset is unknown → default cooldown (never a past instant).\n candidates.push(resetAt != null && resetAt.getTime() > nowMs ? resetAt : defaultClear);\n };\n windowClear((acct.primaryUsedPercent ?? 0) >= nearExhaustionPct, acct.primaryResetAt);\n windowClear((acct.secondaryUsedPercent ?? 0) >= nearExhaustionPct, acct.secondaryResetAt);\n // Ineligible for a non-quota reason (needs_relogin / error) with no known block, or\n // a cleared cooldown: still idle a bounded cooldown before re-check — never the past.\n if (candidates.length === 0) {\n return defaultClear;\n }\n // Clears EVERY blocking condition ⇒ the MAX of the per-condition clear instants.\n return candidates.reduce((a, b) => (b.getTime() > a.getTime() ? b : a));\n}\n\n/** earliestResetAt across ALL connected accounts (min of each account's availableAt). */\nfunction earliestReset(accounts: CodexAccountStatus[], nearExhaustionPct: number, now: Date): 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 * 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: CodexAccountStatus[];\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 { rotationStrategy, activeCredentialId, priorCredentialId, accounts, nearExhaustionPct, now } = args;\n const usedConnectors = args.usedConnectors ?? [];\n\n if (accounts.length === 0) {\n return { kind: \"none\" };\n }\n\n const eligibles = accounts.filter((acct) => eligible(acct, nearExhaustionPct, now));\n\n // Healthy-active fast path (minimal churn, all strategies): a rotation-enabled\n // session whose active account is still eligible does NOT rotate — no pointer\n // move, no switch event. Steady-state stays as cheap as a non-rotation turn\n // save the in-memory ranking. (Skipped for round_robin/drain which anchor on\n // the prior account, but most_remaining is the default + correctness path.)\n const activeRow = activeCredentialId ? accounts.find((acct) => acct.id === activeCredentialId) ?? null : null;\n\n const decide = (chosen: CodexAccountStatus | undefined): RotationDecision => {\n if (!chosen) {\n return { kind: \"allCapped\", earliestResetAt: earliestReset(accounts, nearExhaustionPct, now) };\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 { kind: \"allCapped\", earliestResetAt: earliestReset(accounts, nearExhaustionPct, now) };\n }\n const priorIdx = priorCredentialId ? accounts.findIndex((acct) => acct.id === priorCredentialId) : -1;\n const ordered = priorIdx >= 0\n ? [...accounts.slice(priorIdx + 1), ...accounts.slice(0, priorIdx + 1)]\n : accounts;\n const chosen = ordered.find((acct) => eligible(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 ? accounts.find((acct) => acct.id === priorCredentialId) : undefined;\n if (priorRow && eligible(priorRow, nearExhaustionPct, now)) {\n return decide(priorRow);\n }\n return decide(eligibles[0]);\n }\n\n // most_remaining (default + the correctness path).\n // Healthy-active fast path UNCHANGED (no-thrash): a session whose active account\n // is still eligible never switches — not even for connector coverage. Coverage\n // matters ONLY on the must-move branch below.\n if (activeRow && eligible(activeRow, nearExhaustionPct, now)) {\n return { kind: \"active\", credentialId: activeRow.id, moved: false };\n }\n // Active is capped/near-cap/cooling/missing → must move. Two-tier coverage pick\n // over 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, max bindingRemaining, ties broken by list (created_at)\n // order via a stable reduce — byte-identical to P3 when usedConnectors is empty\n // (Tier 1 == all eligibles).\n const covering = eligibles.filter((acct) => covers(acct, usedConnectors));\n const pool = covering.length > 0 ? covering : eligibles;\n const chosen = pool.reduce<CodexAccountStatus | undefined>((best, acct) => {\n if (!best) {\n return acct;\n }\n return bindingRemaining(acct) > bindingRemaining(best) ? acct : best;\n }, undefined);\n return decide(chosen);\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 type { ResourceRef, SessionStatus, ToolRef } 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(prompt: string, resources: ResourceRef[], tools: ToolRef[], taskId: string, runId: string): Record<string, unknown> {\n return {\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 nextSessionHistoryPosition,\n type Database,\n} from \"@opengeni/db\";\nimport {\n SUMMARY_BUFFER_TOKENS,\n buildCompactionPromptInput,\n buildDeterministicFallbackCompactionHistory,\n buildCompactionReplacementHistory,\n decideClientCompaction,\n estimateTokens,\n sanitizeHistoryItemsForModel,\n summarizeForCompaction,\n type CompactionItem,\n} from \"@opengeni/runtime\";\nimport { resolveContextCompactionMode, type Settings } from \"@opengeni/config\";\n\nexport type MaybeCompactResult =\n | { compacted: false; reason: string }\n | {\n compacted: true;\n supersededFrom: number;\n summaryPosition: number;\n signalTokens: number;\n thresholdTokens: number;\n method: \"summary\" | \"fallback\";\n estimatedTokensBefore: number;\n estimatedTokensAfter: number;\n };\n\n/**\n * Pre-turn client-side context compaction (the Azure path).\n *\n * Runs BEFORE the model call when the resolved compaction mode is \"client\".\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 * Required compactions are fail-closed on the summarizer: full rendered\n * transcript, hard-trim rendered retry, then deterministic non-LLM fallback.\n * DB errors still throw to the caller; \"compacted:false\" is reserved for\n * structural no-ops or impossible shrink, not summarizer failures.\n *\n * There is no kept assistant/tool tail in client mode now. Assistant messages,\n * tool calls/results, reasoning, and images stay only in inactive audit rows.\n */\nexport type CompactionSummarizerOptions = {\n maxTranscriptTokens?: number;\n attempt: \"full\" | \"hard_trim\";\n};\n\nexport type CompactionSummarizer = (\n settings: Settings,\n input: CompactionItem[],\n options?: CompactionSummarizerOptions,\n) => Promise<string | null>;\n\nexport async function maybeCompactContext(\n db: Database,\n settings: Settings,\n scope: { accountId: string; workspaceId: string; sessionId: string; turnId?: string | null },\n lastInputTokens: number | null,\n // Injectable for tests; defaults to the real provider-aware model call.\n summarize: CompactionSummarizer = (s, m, o) => summarizeForCompaction(s, m, {\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n ...(o?.maxTranscriptTokens ? { maxTranscriptTokens: o.maxTranscriptTokens } : {}),\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: { force?: boolean; requireShrink?: boolean } = {},\n): Promise<MaybeCompactResult> {\n if (resolveContextCompactionMode(settings) !== \"client\") {\n return { compacted: false, reason: \"mode_not_client\" };\n }\n\n const active = await getActiveSessionHistoryItems(db, scope.workspaceId, scope.sessionId);\n if (active.length === 0) {\n return { compacted: false, reason: \"no_history\" };\n }\n\n const items = sanitizeHistoryItemsForModel(active.map((row) => row.item) as CompactionItem[]);\n const decision = decideClientCompaction({\n items,\n lastInputTokens,\n contextWindowTokens: settings.contextWindowTokens,\n contextReservedOutputTokens: settings.contextReservedOutputTokens,\n contextCompactionThresholdRatio: settings.contextCompactionThresholdRatio,\n ...(options.force ? { force: true } : {}),\n });\n if (!decision.shouldCompact) {\n return { compacted: false, reason: decision.reason };\n }\n\n const promptInput = buildCompactionPromptInput(items);\n const estimatedTokensBefore = estimateTokens(items);\n const shrinkBaselineTokens = Math.max(estimatedTokensBefore, decision.signalTokens);\n const requireShrink = options.requireShrink || decision.reason === \"above_threshold\";\n let summarizerFailure = \"summarizer returned no summary\";\n let summaryBody: string | null = null;\n\n const fullAttempt = await runSummarizerAttempt(summarize, settings, promptInput, { attempt: \"full\" });\n if (fullAttempt.summary) {\n summaryBody = fullAttempt.summary;\n } else {\n summarizerFailure = fullAttempt.failure;\n const hardTrimBudget = Math.max(1, Math.floor(Math.max(1, decision.thresholdTokens) * 0.5));\n const retryAttempt = await runSummarizerAttempt(summarize, settings, promptInput, {\n attempt: \"hard_trim\",\n maxTranscriptTokens: hardTrimBudget,\n });\n if (retryAttempt.summary) {\n summaryBody = retryAttempt.summary;\n } else {\n summarizerFailure = retryAttempt.failure || summarizerFailure;\n }\n }\n\n let replacementHistory: CompactionItem[] | null = null;\n let method: \"summary\" | \"fallback\" = \"summary\";\n if (summaryBody) {\n const summaryReplacement = buildCompactionReplacementHistory(items, summaryBody);\n const summaryEstimate = estimateTokens(summaryReplacement);\n if (!requireShrink || summaryEstimate < shrinkBaselineTokens) {\n replacementHistory = summaryReplacement;\n } else {\n summarizerFailure = `summary replacement did not reduce context signal (${summaryEstimate} >= ${shrinkBaselineTokens})`;\n }\n }\n\n if (!replacementHistory) {\n method = \"fallback\";\n const fallbackTargetTokens = Math.max(\n 1,\n Math.min(\n Math.max(1, Math.floor(shrinkBaselineTokens * 0.5)),\n Math.max(1, Math.floor(Math.max(1, decision.thresholdTokens) * 0.5)),\n ),\n );\n replacementHistory = buildDeterministicFallbackCompactionHistory({\n items,\n cause: summarizerFailure,\n targetTokens: fallbackTargetTokens,\n });\n }\n\n const estimatedTokensAfter = estimateTokens(replacementHistory);\n if (requireShrink && estimatedTokensAfter >= shrinkBaselineTokens) {\n return { compacted: false, reason: `compaction summarization failed: fallback did not reduce context signal (${estimatedTokensAfter} >= ${shrinkBaselineTokens})` };\n }\n\n const summaryItem = replacementHistory.at(-1);\n if (!summaryItem) {\n return { compacted: false, reason: `compaction summarization failed: ${summarizerFailure}` };\n }\n const nextPosition = await nextSessionHistoryPosition(db, scope.workspaceId, scope.sessionId);\n const replacementItems = replacementHistory.slice(0, -1).map((item, index) => ({\n position: nextPosition + index,\n item,\n }));\n const summaryPosition = nextPosition + replacementItems.length;\n\n await applyContextCompaction(db, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n sessionId: scope.sessionId,\n turnId: scope.turnId ?? null,\n boundaryPosition: nextPosition,\n replacementItems,\n summaryPosition,\n summaryItem: summaryItem as Record<string, unknown>,\n });\n\n return {\n compacted: true,\n supersededFrom: nextPosition,\n summaryPosition,\n signalTokens: decision.signalTokens,\n thresholdTokens: decision.thresholdTokens,\n method,\n estimatedTokensBefore,\n estimatedTokensAfter,\n };\n}\n\nasync function runSummarizerAttempt(\n summarize: CompactionSummarizer,\n settings: Settings,\n promptInput: CompactionItem[],\n options: CompactionSummarizerOptions,\n): Promise<{ summary: string | null; failure: string }> {\n try {\n const summary = await summarize(settings, promptInput, options);\n if (summary && summary.trim().length > 0) {\n return { summary, failure: \"\" };\n }\n return { summary: null, failure: \"summarizer returned no summary\" };\n } catch (error) {\n return { summary: null, failure: error instanceof Error ? error.message : String(error) };\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 GitCredentials,\n type ResourceRef,\n type SandboxSecrets,\n} from \"@opengeni/contracts\";\nimport {\n loadWorkspaceEnvironmentForRun as loadWorkspaceEnvironmentForRunFromDb,\n type Database,\n type WorkspaceEnvironmentForRun,\n} from \"@opengeni/db\";\nimport {\n createGitHubAppInstallationToken,\n githubAppBotIdentity,\n} 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\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 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. `= {}` default so the non-optional reads below are safe.\n options: {\n skipGitHubToken?: boolean;\n scope?: ConnectionScope;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n sessionId?: string;\n runId?: string;\n } = {},\n): Promise<{ environment: Record<string, string>; gitToken?: string; toolspaceToken?: string }> {\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 GitHub 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): the run-scoped GitHub App installation token is NO LONGER\n // layered into the box/agent MANIFEST env (no GH_TOKEN/GITHUB_TOKEN/GIT_CONFIG_*\n // extraheader). It is minted ONCE per turn and returned as `gitToken`; the caller\n // threads it OFF-MANIFEST as a clone-seed exec env (OPENGENI_GIT_TOKEN_SEED) so the\n // clone hook writes it to a stable FILE ($OPENGENI_GIT_TOKEN_FILE), and git auth\n // flows through GIT_ASKPASS -> that file. The manifest carries only the stable\n // pointers (GIT_ASKPASS, GIT_TERMINAL_PROMPT, identity, and — via the shared base —\n // OPENGENI_GIT_TOKEN_FILE), so the token VALUE never rides the manifest and the\n // SDK's per-turn provided-session env delta stays empty even though the token\n // rotates. The agent can refresh the token mid-turn via the `github_token` MCP tool.\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 the platform GitHub token\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(settings, options.scope.workspaceId);\n }\n const selection = githubRepositorySelection(resources);\n // NO-TOKEN SKIP (Stage D, change B): when the turn's EFFECTIVE compute backend is\n // a connected machine (selfhosted), the platform GitHub App installation token is\n // INERT — exec routes over NATS to the user's machine, which uses ITS OWN git\n // credentials, and the box that the token would auth is never created. So skip the\n // (network) token mint entirely and return the STABLE base env (no gitToken). 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 (!selection || options.skipGitHubToken) {\n return { environment, ...(toolspaceToken ? { toolspaceToken } : {}) };\n }\n // Run-scoped sandbox preparation for GitHub App repository resources. When a\n // host binds `gitCredentials`, the HOST mints the installation token (BYO\n // GitHub App); otherwise OpenGeni self-mints from `settings` (today's path). A\n // SINGLE token is minted per turn and returned as `gitToken` (seeded to the box's\n // token file by the caller's clone hook) — NOT layered into the manifest env.\n let token: string;\n let identity: { name: string; email: string } | null;\n if (options?.gitCredentials && options.scope) {\n const minted: GitCredentials = await options.gitCredentials({\n accountId: options.scope.accountId,\n workspaceId: options.scope.workspaceId,\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n });\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 token = minted.token;\n identity = minted.identity ?? githubAppBotIdentity(settings);\n } else {\n token = await createGitHubAppInstallationToken(settings, {\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n });\n identity = githubAppBotIdentity(settings);\n }\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, identity);\n return { environment, gitToken: token, ...(toolspaceToken ? { toolspaceToken } : {}) };\n}\n\nfunction githubRepositorySelection(resources: ResourceRef[]): { installationId: number; repositoryIds: number[] } | null {\n const selected = resources.flatMap((resource) => {\n if (resource.kind !== \"repository\") {\n return [];\n }\n const installationId = positiveInteger(resource.githubInstallationId);\n const repositoryId = positiveInteger(resource.githubRepositoryId);\n return installationId && repositoryId ? [{ installationId, repositoryId }] : [];\n });\n if (selected.length === 0) {\n return null;\n }\n const installationId = selected[0]!.installationId;\n if (selected.some((item) => item.installationId !== installationId)) {\n throw new Error(\"GitHub App repository resources must belong to one installation\");\n }\n return {\n installationId,\n repositoryIds: selected.map((item) => item.repositoryId),\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 { configuredStaticUsageLimits, type Settings } from \"@opengeni/config\";\nimport {\n mergeToolRefs,\n reasoningEffortForMetadata,\n type SessionGoal,\n type ToolRef,\n} from \"@opengeni/contracts\";\nimport {\n enqueueSessionTurn,\n evaluateGoalContinuation,\n getBillingBalance,\n getSessionEvent,\n getSessionGoal,\n isCodexBilledTurn,\n recordUsageEvent,\n requireSession,\n setSessionGoalLastContinuationTurn,\n setSessionGoalStatus,\n sumUsageQuantity,\n type Database,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents, type EventBus } from \"@opengeni/events\";\nimport type {\n ActivityServices,\n MaybeContinueGoalInput,\n MaybeContinueGoalResult,\n PauseGoalForInterruptInput,\n} from \"./types\";\n\nexport function createGoalActivities(services: () => Promise<ActivityServices>) {\n async function maybeContinueGoal(input: MaybeContinueGoalInput): 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 can read the\n // continuation turn's model (session.model). Kept below the goal-less fast\n // path above so a non-goal session still skips this read entirely.\n const session = await requireSession(db, input.workspaceId, input.sessionId);\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({ db, settings, workspaceId: input.workspaceId, model: session.model });\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(settings, db, input.accountId, input.workspaceId, isCodexRun);\n const decision = await evaluateGoalContinuation(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n defaultMaxAutoContinuations: settings.goalMaxAutoContinuations ?? null,\n noProgressLimit: settings.goalNoProgressLimit,\n 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 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 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 [continuationEvent] = await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [{\n type: \"goal.continuation\",\n payload: {\n goalId: decision.goal.id,\n text: prompt,\n autoContinuation: decision.autoContinuation,\n maxAutoContinuations: decision.cap,\n goalVersion: decision.goal.version,\n },\n }]);\n if (!continuationEvent) {\n throw new Error(\"failed to append goal continuation trigger event\");\n }\n const turn = await enqueueSessionTurn(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n triggerEventId: continuationEvent.id,\n temporalWorkflowId: input.workflowId,\n source: \"goal\",\n prompt,\n resources: [],\n // Continuations keep the session tool surface and force the first-party\n // server so the goal_complete/goal_pause escape hatches stay reachable.\n tools: withFirstPartyTools(settings, session.tools),\n model: session.model,\n reasoningEffort: reasoningEffortForMetadata(session.metadata, settings.openaiReasoningEffort),\n sandboxBackend: session.sandboxBackend,\n metadata: { goalId: decision.goal.id, autoContinuation: decision.autoContinuation },\n });\n await setSessionGoalLastContinuationTurn(db, input.workspaceId, input.sessionId, turn.id);\n await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [{\n type: \"turn.queued\",\n turnId: turn.id,\n payload: { turnId: turn.id, triggerEventId: continuationEvent.id, source: turn.source },\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_turn\",\n sourceResourceId: turn.id,\n idempotencyKey: `agent_run.created:goal:${input.workspaceId}:${turn.id}`,\n });\n return { action: \"continue\" };\n }\n\n async function pauseGoalForInterrupt(input: PauseGoalForInterruptInput): Promise<void> {\n const { db, bus } = await services();\n if (input.triggerEventId) {\n const trigger = await getSessionEvent(db, input.workspaceId, input.triggerEventId);\n if (isSteerInterrupt(trigger)) {\n return;\n }\n }\n await pauseActiveGoalOnInterrupt(db, bus, input.workspaceId, input.sessionId);\n }\n\n return {\n maybeContinueGoal,\n pauseGoalForInterrupt,\n };\n}\n\n/**\n * True when an interrupt's trigger event is a STEER: `user.interrupt` tagged\n * `reason: \"steer\"`, sent by `OpenGeniClient.steerMessage`. Steering cancels\n * the running turn only to deliver the steered message next — it redirects\n * the work rather than stopping it, so an active goal keeps going. Every\n * other user interrupt (the stop button, a plain `interrupt()` call) is the\n * explicit act of stopping and pauses the goal.\n */\nexport function isSteerInterrupt(trigger: { type: string; payload: unknown } | null | undefined): boolean {\n if (!trigger || trigger.type !== \"user.interrupt\") {\n return false;\n }\n const payload = trigger.payload;\n return typeof payload === \"object\" && payload !== null && (payload as { reason?: unknown }).reason === \"steer\";\n}\n\n/**\n * A user interrupt is the explicit act of stopping, so it pauses an active\n * goal. Shared by the idle-interrupt activity and `interruptActiveTurn` so the\n * loop never auto-continues a goal the user just stopped. Callers gate this\n * on `isSteerInterrupt` first: steer interrupts must NOT pause the goal.\n * No-op when the session has no goal or it is not active.\n */\nexport async function pauseActiveGoalOnInterrupt(db: Database, bus: EventBus, workspaceId: string, sessionId: string): Promise<void> {\n const goal = await getSessionGoal(db, workspaceId, sessionId);\n if (!goal || goal.status !== \"active\") {\n return;\n }\n const { goal: paused, changed } = await setSessionGoalStatus(db, workspaceId, sessionId, {\n status: \"paused\",\n pausedReason: \"user_interrupt\",\n });\n if (changed) {\n await appendAndPublishEvents(db, bus, workspaceId, sessionId, [{\n type: \"goal.paused\",\n payload: {\n goalId: paused.id,\n actor: \"user\",\n reason: \"user_interrupt\",\n autoContinuations: paused.autoContinuations,\n noProgressStreak: paused.noProgressStreak,\n },\n }]);\n }\n}\n\nexport function goalContinuationPrompt(goal: SessionGoal, autoContinuation: number, cap: number | null): 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 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(settings: Settings, db: Database, accountId: string, workspaceId: string, isCodexRun: boolean): 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 (!isCodexRun && (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")) {\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(db: Database, workspaceId: string): 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((pack) => typeof pack.sandboxImage === \"string\" && pack.sandboxImage.trim().length > 0);\n if (imagePacks.length > 1) {\n const ids = imagePacks.map((pack) => pack.id).sort().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(db: Database, workspaceId: string): 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(settings: Settings, sandboxImage: string | null): Settings {\n if (!sandboxImage) {\n return settings;\n }\n return {\n ...settings,\n dockerImage: sandboxImage,\n modalImageRef: sandboxImage,\n };\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { Session, SessionGoal } from \"@opengeni/contracts\";\nimport { getSession, getSessionGoal, wakeParentSessionForChildCompletion, type Database } 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\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's queued\n * turn is delivered by the DB wake; signalling the parent's workflow\n * (signalWithStart) ensures a parent whose workflow already completed gets a\n * fresh run to claim it. Failures here never fail the child: the wake is a\n * best-effort nudge layered on durable DB state.\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 const clientEventId = `child-completion:${childSessionId}:${episodeKey ?? child.lastSequence}`;\n const result = await wakeParentSessionForChildCompletion(svc.db, {\n workspaceId,\n parentSessionId: child.parentSessionId,\n clientEventId,\n text: childCompletionWakeText(child, goal, terminalStatus),\n childCompletion: childCompletionPayload(child, goal, terminalStatus),\n reasoningEffortFallback: svc.settings.openaiReasoningEffort,\n });\n if (!result.delivered) {\n return;\n }\n await svc.bus.publish(workspaceId, child.parentSessionId, result.events);\n if (svc.wakeSessionWorkflow) {\n await svc.wakeSessionWorkflow({\n accountId: child.accountId,\n workspaceId,\n sessionId: child.parentSessionId,\n workflowId: result.temporalWorkflowId,\n });\n }\n svc.observability.info(\"Woke parent session on worker completion\", {\n childSessionId,\n parentSessionId: child.parentSessionId,\n terminalStatus,\n });\n } catch (error) {\n // A parent-wake failure must never fail the child's terminal activity.\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\nfunction childCompletionPayload(child: Session, goal: SessionGoal | null, terminalStatus: \"idle\" | \"failed\"): Record<string, unknown> {\n return {\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\nfunction childCompletionWakeText(child: Session, goal: SessionGoal | null, terminalStatus: \"idle\" | \"failed\"): 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(`A worker session you spawned has COMPLETED its goal. Worker session id: ${child.id}.`);\n } else if (goal?.status === \"paused\") {\n lines.push(`A worker session you spawned has PAUSED its goal and gone idle. Worker session id: ${child.id}.`);\n } else {\n lines.push(`A worker session you spawned has finished its work and gone idle. Worker session id: ${child.id}.`);\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 lines.push(\"Read the worker's session events/notebook output for its result, then continue. If your own goal was paused awaiting this worker, resume it now.\");\n return lines.join(\"\\n\");\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(Object.entries(payload).map(([key, value]) => [key, redact(value)]));\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 { Settings } from \"@opengeni/config\";\nimport { contextInputBudgetTokens, resolveContextCompactionMode } from \"@opengeni/config\";\nimport type { FileAsset, ResourceRef } from \"@opengeni/contracts\";\nimport {\n getActiveSessionHistoryItems,\n getLatestRunState,\n getSandboxSessionEnvelope,\n getSessionEvent,\n requireFile,\n type Database,\n} from \"@opengeni/db\";\nimport { stripReasoningEncryptedContent, stripReasoningIdentityFromSerializedRunState, neutralizeToolSearchItemsInSerializedRunState, type OpenGeniRuntime } 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 to replay on a run-state path (approval resume\n * or the items-mode run-state fallback), applying the SAME cross-account rule the\n * history-items path uses. The blob 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(stripReasoningIdentityFromSerializedRunState(state.serializedRunState));\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 when `state.history` was seeded from the run-state BLOB\n * (approval resume, the items-mode run-state fallback, or run_state mode): 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 async function turnInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: Awaited<ReturnType<typeof getSessionEvent>>,\n settings?: Settings,\n current: TurnCodexAccount = NON_CODEX_TURN,\n): Promise<PreparedTurnInput> {\n if (!trigger) {\n throw new Error(\"Missing trigger event\");\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 text = await userMessageTextWithAttachments(\n db,\n trigger.workspaceId,\n payload.text,\n Array.isArray(payload.resources) ? payload.resources as ResourceRef[] : [],\n );\n return await messageInput(db, runtime, agent, trigger, text, settings, current);\n }\n if (trigger.type === \"goal.continuation\") {\n const payload = trigger.payload as { text?: unknown };\n if (typeof payload.text !== \"string\" || payload.text.trim().length === 0) {\n throw new Error(\"goal.continuation payload is missing text\");\n }\n // Threading the stored conversation keeps the agent's full context across\n // continuations — this is what makes \"keep working\" coherent.\n return await messageInput(db, runtime, agent, trigger, payload.text, settings, current);\n }\n if (trigger.type === \"turn.preempted\") {\n const payload = trigger.payload as { text?: unknown };\n if (typeof payload.text !== \"string\" || payload.text.trim().length === 0) {\n throw new Error(\"turn.preempted payload is missing text\");\n }\n // A turn re-entering after a graceful worker shutdown checkpointed it\n // mid-flight: thread the stored conversation (which includes the turn's\n // original input and its progress so far) behind a resume notice.\n return await messageInput(db, runtime, agent, trigger, payload.text, settings, 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\n/**\n * Build a message/continuation turn input from the configured history source.\n * Items mode reads conversation truth from session_history_items and the\n * sandbox envelope from its own store; a session with no stored items yet\n * (created before dual-write, or its first turn) falls back to the RunState\n * blob for this turn — the turn-end reconciliation then backfills its items,\n * so the fallback is self-eliminating (issue #35).\n */\nasync function messageInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: NonNullable<Awaited<ReturnType<typeof getSessionEvent>>>,\n text: string,\n settings?: Settings,\n current: TurnCodexAccount = NON_CODEX_TURN,\n): Promise<PreparedTurnInput> {\n // Read-path budget guard (the last-resort backstop behind best-effort pre-turn\n // compaction): supply B only when the client-side compaction path is active\n // (Azure). On the OpenAI server path the SDK manages the window, so we leave\n // the guard off and never crudely trim. Undefined = guard disabled.\n const inputBudgetTokens = readPathBudgetTokens(settings);\n if (settings?.sessionHistorySource === \"items\") {\n // Active rows only: after a client-side context compaction this is\n // [retained user messages..., active summary]; superseded rows stay in the\n // table as an audit trail but never reach the model.\n const stored = await getActiveSessionHistoryItems(db, trigger.workspaceId, trigger.sessionId);\n if (stored.length > 0) {\n const envelope = await getSandboxSessionEnvelope(db, trigger.workspaceId, trigger.sessionId);\n // Cross-account reasoning strip: drop any carried reasoning item NOT\n // produced by THIS turn's codex account (foreign reasoning is dropped\n // whole — id + blob; a foreign blob 400s the codex backend and a foreign\n // rs_ id is rejected by the Responses backend). No-op for single-account\n // workspaces, unchanged-account turns, and non-codex turns over a history\n // with no codex reasoning (every producer == current) — those replay\n // byte-for-byte. Message and tool content is never touched.\n const historyItems = applyCodexHistoryStrip(stored, current);\n return {\n input: await runtime.prepareInput(\n agent,\n {\n kind: \"message\",\n text,\n historyItems: historyItems as any,\n sandboxEnvelope: envelope,\n },\n inputBudgetTokens ? { inputBudgetTokens } : {},\n ),\n // state.history seeded from the cross-account-STRIPPED active items: the\n // reconcile watermark must apply the SAME strip (HOLE D).\n modelHistoryFromItems: true,\n };\n }\n }\n const latestState = await getLatestRunState(db, trigger.workspaceId, trigger.sessionId);\n return {\n input: await runtime.prepareInput(\n agent,\n {\n kind: \"message\",\n text,\n // Cross-account run-state strip (HOLE C): the items-mode fallback replays\n // the RunState blob when no history rows exist yet. If the resuming turn's\n // codex account differs from the one that froze the blob, neutralize its\n // account-bound reasoning before replay (else byte-for-byte).\n serializedRunState: latestState ? resumeRunStateForCodexAccount(latestState, current) : null,\n },\n inputBudgetTokens ? { inputBudgetTokens } : {},\n ),\n // state.history seeded from the run-state BLOB (or empty): NOT the stripped\n // items, so the reconcile watermark must NOT apply the cross-account strip\n // (HOLE E). On this fallback the active rows are empty anyway (the read above\n // took the items branch when stored.length > 0), so strip-or-not both yield 0.\n modelHistoryFromItems: false,\n };\n}\n\n/**\n * The usable input-token budget B to hand the read-path guard, or undefined\n * when the guard should stay off. Active only when the resolved compaction mode\n * is \"client\" (the Azure path that runs our own compaction); on the server path\n * the SDK enforces the window, and with no settings we can't compute B.\n */\nfunction readPathBudgetTokens(settings?: Settings): number | undefined {\n if (!settings || resolveContextCompactionMode(settings) !== \"client\") {\n return undefined;\n }\n const budget = contextInputBudgetTokens(settings);\n return budget > 0 ? budget : undefined;\n}\n\nexport async function userMessageTextWithAttachments(\n db: Database,\n workspaceId: string,\n text: string,\n resources: ResourceRef[],\n): Promise<string> {\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(`- ${file.filename} (${file.contentType}, ${file.sizeBytes} bytes): ${sandboxFilePath(resource, file)}`);\n }\n if (attachedFiles.length === 0) {\n return text;\n }\n return [\n text,\n \"\",\n \"Attached files are available in the sandbox:\",\n ...attachedFiles,\n ].join(\"\\n\");\n}\n\nfunction sandboxFilePath(resource: Extract<ResourceRef, { kind: \"file\" }>, file: FileAsset): 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\nexport function createRuntimeBatcher(flushEvents: (events: AppendEventInput[]) => Promise<void>) {\n let pending: AppendEventInput[] = [];\n let lastFlush = Date.now();\n const structural = new Set<SessionEventType>([\n \"agent.message.delta\",\n \"agent.reasoning.delta\",\n \"sandbox.command.output.delta\",\n // Channel-A PTY bytes flush promptly (P4.4) — a terminal stream is useless\n // batched 33ms behind; the structural set bypasses the batcher's coalesce.\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 pending.push({ type: event.type, payload: event.payload });\n const elapsed = Date.now() - lastFlush;\n if (pending.length >= 50 || elapsed >= 33 || structural.has(event.type)) {\n await flush();\n }\n },\n flush,\n };\n\n async function flush() {\n if (pending.length === 0) {\n return;\n }\n const events = pending;\n pending = [];\n lastFlush = Date.now();\n await flushEvents(events);\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(context: Context | null, details: Record<string, unknown>): 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>(iterator: AsyncIterator<T>, context: Context | null): Promise<IteratorResult<T>> {\n if (!context) {\n return await iterator.next();\n }\n return await Promise.race([\n iterator.next(),\n context.cancelled,\n ]);\n}\n","// apps/worker/src/sandbox-resume.ts — the stateless per-turn resume-by-id path.\n//\n// This is the turn-side half of the P1.2 ownership inversion. There is NO class,\n// NO timers, NO per-session owner, NO Map<id, owner> — every turn is a\n// self-contained critical section run by ANY pool worker:\n//\n// 1. acquireLease (group-keyed) under the DB FOR UPDATE + cold->warming CAS —\n// the SOLE double-spawn guard (P1.1).\n// 2. establishSandboxSessionFromEnvelope — resume the one box BY ID (warm\n// reattach, R4-safe) or cold-restore from snapshot on a provider NotFound.\n// 3. (spawner) ensureDisplayStack + exposeStreamPort, then commitWarmingToWarm\n// (the lease_epoch++ fence + folds the resume envelope onto the lease). The\n// ATTACHED/REARMED path RE-ensures the display stack too (idempotent) so a\n// computer-use turn always finds a live :0 even on a box first warmed by a\n// non-desktop op or after a snapshot rollover dropped the X stack.\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 readLease,\n recordWarmingSandboxCreated,\n releaseLeaseHolder,\n SandboxLeaseSupersededError,\n type Database,\n type LeaseHolderKind,\n} from \"@opengeni/db\";\nimport {\n establishSandboxSessionFromEnvelope,\n ensureDisplayStack as ensureDisplayStackOnBox,\n desktopCapableBackend,\n serializeEstablishedSandboxEnvelope,\n DisplayStackError,\n DisplayStackUnsupportedError,\n buildStreamUrl,\n StreamPortUnavailableError,\n modalSandboxAttributionEnvironment,\n tagModalSandbox,\n type EstablishedSandboxSession,\n type ExposedPortEndpoint,\n type RuntimeMetricsHooks,\n} from \"@opengeni/runtime\";\nimport { DESKTOP_STREAM_PORT } from \"@opengeni/contracts\";\n\nexport { DESKTOP_STREAM_PORT };\n\n// Re-exported for callers that just want the ack-kind union.\nexport type ResumeHolderKind = LeaseHolderKind;\n\n/** The minimal services surface resumeBoxForTurn needs. A subset of\n * ActivityServices so a test (and the API later) can pass a lean bag. */\nexport type SandboxResumeServices = {\n db: Database;\n settings: Settings;\n sandboxMetrics?: RuntimeMetricsHooks;\n};\n\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\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(public readonly backend: string, public readonly timeoutMs: number) {\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// Bounded poll while a sibling spawner is mid cold-restore. The wait budget is\n// user-facing and separate from the lease TTL heartbeat/reaper horizon.\nconst WARMING_POLL_INTERVAL_MS = 250;\n\nasync function sleep(ms: number): Promise<void> {\n await new Promise<void>((resolve) => setTimeout(resolve, ms));\n}\n\nasync function terminateEstablishedSandbox(established: EstablishedSandboxSession | null): Promise<boolean> {\n if (!established) {\n return true;\n }\n const client = established.client as { delete?: (state: unknown) => Promise<unknown> };\n if (typeof client.delete === \"function\" && established.sessionState !== undefined) {\n try {\n await client.delete(established.sessionState);\n return true;\n } catch {\n return false;\n }\n }\n const session = established.session as {\n 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(metrics: RuntimeMetricsHooks | undefined, error: unknown): 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 workspaceArchiveFromEnvelope(envelope: Record<string, unknown> | null | undefined): string | null {\n const sessionState = envelope && typeof envelope.sessionState === \"object\" && envelope.sessionState !== null\n ? envelope.sessionState as Record<string, unknown>\n : null;\n const archive = sessionState?.workspaceArchive;\n return typeof archive === \"string\" && archive.length > 0 ? archive : null;\n}\n\nfunction preserveWorkspaceArchiveOnInterimResumeState(\n resumeState: Record<string, unknown> | null,\n archiveSource: Record<string, unknown> | null,\n): Record<string, unknown> | null {\n const archive = workspaceArchiveFromEnvelope(archiveSource);\n if (!archive) {\n return resumeState;\n }\n const existingSessionState = 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 workspaceArchive: archive,\n },\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 unique-per-execution id (the Temporal activityId for a turn).\n */\nexport async function resumeBoxForTurn(\n services: SandboxResumeServices,\n ids: ResumeBoxIds,\n kind: LeaseHolderKind,\n holderId: string,\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 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: 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 leaseTtlMs,\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 // expose the stream port, then commit warm (lease_epoch++).\n if (acquired.role === \"spawner\") {\n const expectedEpoch = acquired.lease.leaseEpoch;\n let createdEstablished: EstablishedSandboxSession | null = null;\n if (ids.environment && ids.backend === \"modal\") {\n Object.assign(ids.environment, modalSandboxAttributionEnvironment({\n leaseId: acquired.lease.id,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n }));\n }\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 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 = preserveWorkspaceArchiveOnInterimResumeState(\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 });\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 await ensureDisplayStack(settings, established);\n const endpoint = await exposeStreamPort(settings, 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 resumeEnvelope = (await serializeEstablishedSandboxEnvelope(established)) ?? envelope ?? null;\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 dataPlaneUrl: endpoint?.url ?? 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(error, ids.backend, settings.sandboxWarmingTimeoutMs);\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; requeue the turn instead of\n // 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 const envelope =\n live?.resumeState ?? (await getSandboxSessionEnvelope(db, ids.workspaceId, ids.sessionId));\n const established = await establishSandboxSessionFromEnvelope(settings, envelope, {\n sessionId: ids.sessionId,\n backendOverride: ids.backend as never,\n ...(ids.environment ? { environment: ids.environment } : {}),\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n });\n // Re-ensure the desktop display stack on the ATTACHED/REARMED path too — NOT\n // just the spawner path. A turn attaching to a warm box whose :0 was never\n // brought up (the box was first warmed by a Channel-A op, or a snapshot\n // rollover dropped the X stack) would otherwise drive computer-use against a\n // dead display: scrot yields an empty PNG, the SDK builds `image_url: ''`,\n // and the model rejects the turn with \"400 Invalid input[N].output.image_url\".\n // ensureDisplayStack is idempotent + flock-guarded (cheap no-op when up) and\n // NO-OPs when the desktop tier is off or the backend is headless-only, so the\n // headless turn path stays byte-for-byte unchanged.\n await ensureDisplayStack(settings, established);\n return { established, leaseEpoch, release };\n } catch (error) {\n await release();\n const warmingError = asSandboxWarmingError(error, ids.backend, settings.sandboxWarmingTimeoutMs);\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 unique-per-execution id (the Temporal activityId for a turn).\n */\nexport async function acquireSelfhostedLeaseForTurn(\n services: SandboxResumeServices,\n ids: { accountId: string; workspaceId: string; sandboxGroupId: string; sessionId: string },\n kind: LeaseHolderKind,\n holderId: string,\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 });\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\n// ============================================================================\n// Channel-B display-stack launch (P4.1 — ensureDisplayStack is now real).\n//\n// Idempotent + callable by ANY worker on the resumed handle (and by the API on a\n// viewer op). When the desktop tier is OFF (sandboxDesktopEnabled=false) or the\n// backend is headless-only, this is a NO-OP — the HEADLESS ROLLOVER branch (I5),\n// so the headless turn path is byte-for-byte unchanged. When the tier is ON for\n// a desktop-capable backend, it execs the canonical opengeni-desktop-up under an\n// in-box flock (re-establishes after a rollover; safe to call N times).\n// `exposeStreamPort` real body remains a P4.2 concern.\n// ============================================================================\n\n/**\n * Ensure the desktop display stack (Xvfb -> XFCE -> x11vnc ->\n * websockify:6080 -> noVNC) is up on the live box. Idempotent: the lock-free\n * pre-check + the in-box flock + the up-script's per-stage PID guards make a\n * second call a cheap no-op. NO-OP when the desktop tier is disabled or the\n * backend cannot serve a desktop (degradation is a value: a headless-only session\n * simply skips the stack). Delegates to the agent-loop-free leaf\n * (@opengeni/runtime/sandbox display-stack).\n *\n * BEST-EFFORT — NEVER fails the turn. The display stack powers the OPTIONAL\n * Channel-B desktop / computer-use surface; it is NOT load-bearing for the\n * agent's work. A `DisplayStackError` (a real stage failure, OR — the regression\n * this guards — a timeout-derived exit -1 when a viewer attach already holds /\n * contends the up-script's flock and the turn's ensure waits ~45s and times out)\n * is CAUGHT + logged and swallowed, so a slow/contended/failed stack degrades to\n * Channel-A-only rather than killing the turn. The fast lock-free pre-check\n * upstream means the already-up case resolves in milliseconds and never reaches\n * this catch in the first place. `DisplayStackUnsupportedError` (a box that can't\n * run commands at all) is likewise swallowed.\n */\nexport async function ensureDisplayStack(\n settings: Settings,\n established: EstablishedSandboxSession,\n): Promise<void> {\n // Headless rollover branch (I5): the tier is off OR the backend is\n // headless-only -> no display stack. Behavior-preserving for the headless path.\n // This is ALSO the \"is the desktop relevant to this turn?\" gate: we only touch\n // the box when the desktop tier is enabled for a desktop-capable backend.\n if (!settings.sandboxDesktopEnabled) {\n return;\n }\n if (!desktopCapableBackend(established.backendId)) {\n return;\n }\n try {\n await ensureDisplayStackOnBox(established.session);\n } catch (error) {\n // The desktop is a value-add, not load-bearing for the agent's work, so NO\n // display-stack failure may fail the turn:\n // - DisplayStackUnsupportedError: the box genuinely can't run commands ->\n // Channel-A-only.\n // - DisplayStackError: a stage failure OR a contended-lock timeout (exit -1)\n // after a viewer attach already brought the stack up / is mid-launch. The\n // pre-check makes the already-up case fast; if we still time out or a stage\n // really failed, degrade — don't die.\n if (error instanceof DisplayStackUnsupportedError || error instanceof DisplayStackError) {\n console.warn(\n `[sandbox-resume] ensureDisplayStack degraded to Channel-A-only (turn continues): ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n return;\n }\n // An unexpected non-display error (e.g. the session blew up entirely) still\n // propagates — that is not a desktop-surface degradation.\n throw error;\n }\n}\n\n// The structural slice of a provider session we need to resolve the tunnel.\ntype PortResolvableSession = {\n resolveExposedPort?: (port: number) => Promise<ExposedPortEndpoint>;\n};\n\n/**\n * Resolve the desktop tunnel URL (resolveExposedPort(6080)) and assemble the\n * direct-to-provider WS URL, recorded on the lease as `data_plane_url` at\n * commit. The per-viewer scoped token is minted at viewer-attach time (the\n * handshake), NOT here — the spawner records only the box-scoped tunnel URL so\n * the lease carries a fresh value across a rollover. P4.2 productionizes the\n * P4.1 stub.\n *\n * Returns null (degradation is a value, NEVER a throw):\n * - the desktop tier is off (sandboxDesktopEnabled=false), or\n * - the backend is headless-only (no desktop), or\n * - the provider session cannot resolve the port (no resolveExposedPort), or\n * - the tunnel lookup transiently failed.\n * In every null case the lease's data_plane_url stays null and the next\n * API-direct viewer op re-mints it; the turn never fails on a desktop hiccup.\n */\nexport async function exposeStreamPort(\n settings: Settings,\n established: EstablishedSandboxSession,\n): Promise<{ url: string; expiresAt: Date } | null> {\n // Headless rollover branch (I5): tier !== desktop -> no stream port to expose.\n if (!settings.sandboxDesktopEnabled) {\n return null;\n }\n if (!desktopCapableBackend(established.backendId)) {\n return null;\n }\n const session = established.session as PortResolvableSession;\n if (typeof session?.resolveExposedPort !== \"function\") {\n return null;\n }\n try {\n const endpoint = await session.resolveExposedPort(DESKTOP_STREAM_PORT);\n const url = buildStreamUrl(endpoint);\n // The provider tunnel URL is box-lifetime-valid (Modal raw TLS) or\n // provider-TTL-signed (Daytona/Blaxel); the per-viewer token's TTL bounds the\n // viewer's freshness. We record only the URL on the lease; expiresAt here is a\n // soft hint (the box's idle horizon), not a hard token expiry.\n return { url, expiresAt: new Date(Date.now() + settings.sandboxLeaseTtlMs) };\n } catch (error) {\n // Degradation is a value: a transient resolve failure leaves data_plane_url\n // null and the next viewer op re-mints. Never fail the turn on a desktop op.\n if (error instanceof StreamPortUnavailableError) {\n return null;\n }\n return null;\n }\n}\n","// apps/worker/src/sandbox-routing.ts — wire the agent-loop-free routing proxy\n// (`@opengeni/runtime` RoutingSandboxSession + makeActiveBackendResolver) to the\n// real DB pointer + the live NATS control plane for the WORKER TURN path (M7).\n//\n// The turn resumes its group box by id (resumeBoxForTurn) and injects it\n// NON-OWNED into the run. With hot-swap, the injected `session` must be the\n// STABLE routing proxy (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 RoutingSandboxSession,\n type ControlRpc,\n type EstablishedSandboxSession,\n type NatsRequestConnection,\n type RoutableBackendSession,\n type RoutableSandbox,\n type SelfhostedRelayConfig,\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};\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\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/** 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 } = 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 ? { id: sandbox.id, kind: sandbox.kind, name: sandbox.name, enrollmentId: sandbox.enrollmentId }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n relay: relayConfigFromSettings(settings),\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\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\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 */\nexport async function establishSelfhostedTurnSession(\n services: RoutingWiringServices,\n args: {\n workspaceId: string;\n /** The target machine's enrollment id == the agent subject id. */\n agentId: string;\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): Promise<EstablishedSandboxSession> {\n const { settings, bus } = services;\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 });\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","import type { EventLogger } from \"@opengeni/events\";\nimport type { Attributes, AttributeValue, Observability } from \"@opengeni/observability\";\nimport type { RuntimeMetricsHooks } from \"@opengeni/runtime\";\n\nexport type TurnOutcome = \"completed\" | \"failed\" | \"cancelled\" | \"preempted\";\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 (value === null || value === undefined || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport function runtimeMetricsHooksForObservability(observability: Observability): 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 };\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 = durationSeconds ?? (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(observability: Observability, counts: Partial<Record<SandboxLeaseLiveness, number>>): 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(observability: Observability, balances: CreditBalanceGauge[]): 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(observability: Observability | undefined, kind: CreditMicrosKind, amountMicros: number): 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","// 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). The bytes\n// go box → process memory → object-storage PUT and are NEVER serialized as a\n// Temporal activity result (F10): read + PUT happen in ONE invocation here.\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, updateRecording } from \"@opengeni/db\";\nimport type {\n RecordingAvailablePayload,\n RecordingCodec,\n RecordingFailedReason,\n RecordingStartedPayload,\n} from \"@opengeni/contracts\";\nimport {\n contentTypeForCodec,\n deleteRecordingArtifacts,\n readRecordingBytes,\n RecordingError,\n recordingStorageKey,\n startRecording as startRecordingOnBox,\n stopRecording as stopRecordingOnBox,\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\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] = [settings.streamResolutionWidth, settings.streamResolutionHeight];\n const framerate = settings.recordingFramerate;\n await import(\"@opengeni/db\").then(({ insertRecording }) => 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 const 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 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 FinalizeOutcome =\n | { ok: true; available: RecordingAvailablePayload }\n | { ok: false; reason: RecordingFailedReason; detail: string | null };\n\n/**\n * Stop ffmpeg, read the bytes off the box, PUT them to storage, commit `available`,\n * and (only then) delete the box file (F9). Returns the available payload, or a\n * failure reason. NEVER throws — finalize runs in a turn `finally` and must not\n * mask the turn outcome.\n */\nexport async function finalizeRecording(args: {\n settings: Settings;\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n active: ActiveRecording;\n session: unknown;\n runAs?: string | undefined;\n}): Promise<FinalizeOutcome> {\n const { settings, db, objectStorage, active } = args;\n const codec = settings.recordingDefaultCodec as RecordingCodec;\n const fail = async (reason: RecordingFailedReason, detail: string | null): Promise<FinalizeOutcome> => {\n await updateRecording(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n recordingId: active.recordingId,\n state: \"failed\",\n reason: scrubFreeText(detail),\n }).catch(() => undefined);\n return { ok: false, reason, detail: scrubFreeText(detail) };\n };\n\n try {\n await updateRecording(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n recordingId: active.recordingId,\n state: \"finalizing\",\n }).catch(() => undefined);\n\n // 1. SIGINT ffmpeg and wait for the clean trailer.\n await stopRecordingOnBox(args.session, active.proc);\n\n // 2. Read bytes off the box (size-gated; no eager delete — F8/F9).\n const finalized = await readRecordingBytes(args.session, active.proc, settings.recordingMaxBytes);\n\n if (!objectStorage) {\n return await fail(\"upload-failed\", \"object storage is not configured\");\n }\n\n // 3. PUT to storage (the byte transfer stays IN this process — F10).\n //\n // SERVER-SIDE authenticated direct PUT, NOT presign+fetch. The worker holds the\n // storage creds, so a presigned URL buys nothing — and on a split public/\n // internal endpoint topology (a PUBLIC `objectStorageEndpoint` with no in-cluster\n // route, the preview case) the presigned URL points at the public host and the\n // fetch PUT 401s. `putObject` sends the bytes straight to the backend over the\n // configured (in-cluster) endpoint with the in-process SDK client. Browser\n // uploads keep using `createPutUrl`; this is the trusted-server twin.\n const key = recordingStorageKey(args.workspaceId, args.sessionId, active.recordingId, codec);\n try {\n // `.slice()` detaches a fresh ArrayBuffer from the box read.\n await objectStorage.putObject({ key, contentType: finalized.contentType, body: finalized.bytes.slice() });\n } catch (uploadError) {\n return await fail(\"upload-failed\", uploadError instanceof Error ? uploadError.message : String(uploadError));\n }\n\n // 4. Commit `available` with the artifact ref.\n await updateRecording(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n recordingId: active.recordingId,\n state: \"available\",\n storageKey: key,\n sizeBytes: finalized.sizeBytes,\n durationSeconds: finalized.durationSeconds,\n });\n\n // 5. ONLY NOW delete the box artifacts (F9 — never before a confirmed PUT).\n await deleteRecordingArtifacts(args.session, active.proc);\n\n const available: RecordingAvailablePayload = {\n recordingId: active.recordingId,\n turnId: active.turnId,\n codec,\n contentType: contentTypeForCodec(codec),\n storageKey: key,\n durationSeconds: finalized.durationSeconds,\n sizeBytes: finalized.sizeBytes,\n dimensions: active.dimensions,\n };\n return { ok: true, available };\n } catch (error) {\n const reason: RecordingFailedReason = error instanceof RecordingError ? error.reason : \"ffmpeg-error\";\n return await fail(reason, error instanceof Error ? error.message : String(error));\n }\n}\n\n/**\n * Discard an on-turn recording that captured NO computer-use activity (a plain\n * text turn): stop ffmpeg on the box, delete the box artifacts, and remove the\n * recording row entirely. NO storage PUT and NO `recording.failed` — a clean\n * no-op. NEVER throws (it runs in the turn `finally` and must not mask the turn\n * outcome). Returns nothing; the caller emits no recording event for a discard.\n */\nexport async function discardRecording(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 // Stop ffmpeg cleanly, then delete the partial artifact off the box. Both are\n // best-effort: a stuck box must not strand the discard (the box rides the\n // provider idle-timeout regardless).\n await stopRecordingOnBox(args.session, active.proc).catch(() => undefined);\n await deleteRecordingArtifacts(args.session, active.proc).catch(() => undefined);\n } finally {\n // Remove the phantom row inserted at beginRecording so a no-activity turn\n // leaves no recording trace at all.\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","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 {\n ActivityServices,\n IndexDocumentInput,\n} 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(lockedDb, objectStorage, input.workspaceId, input.documentId, documentServices, {\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 = 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 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","// 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 countQueuedTurns,\n countSandboxLeasesByLiveness,\n forceDrainOverLimitViewerOnlyBoxes,\n getBillingBalance,\n listCreditBalancesByAccount,\n listLiveModalSandboxLeaseAttributions,\n listMeterableWarmLeases,\n persistDrainSnapshot,\n readLease,\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 {\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 -> the superseded archive (if any) to GC the prior snapshot.\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 is always null in\n * this case.\n */\nexport type PersistArchiveFn = (\n archiveBase64: string | null,\n) => Promise<{ wrote: boolean; priorArchive: 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 = 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 { db, settings, observability } = await services();\n if (!settings.sandboxOwnershipEnabled) {\n return { examined: 0, terminated: 0, skipped: 0, metered: 0, forceDrained: 0, modalOrphansTerminated: 0 };\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(db, settings, metered.workspaceIds, observability);\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 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(db, settings, row, observability, terminateBox);\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 (drainable.length > 0 || metered.accrued > 0 || forceDrained > 0 || modalOrphansTerminated > 0) {\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 { examined: drainable.length, terminated, skipped, metered: metered.accrued, forceDrained, modalOrphansTerminated };\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 = 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 ? await getBillingBalance(db, accountId) : { 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 const persistArchive: PersistArchiveFn = async (archiveBase64: string | null) =>\n await persistDrainSnapshot(db, {\n accountId,\n workspaceId: row.workspaceId,\n sandboxGroupId: row.sandboxGroupId,\n expectedEpoch: row.leaseEpoch,\n workspaceArchive: archiveBase64,\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 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 (backend === \"selfhosted\" || lease.backend === \"selfhosted\" || lease.resumeBackendId === \"selfhosted\") {\n observability.info(\"sandbox reaper: selfhosted lease drained to cold (NEVER provider-stopped — it is the user's machine)\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\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(\"sandbox reaper: Modal lease re-armed before direct terminate — leaving sandbox RUNNING\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n instanceId: lease.instanceId,\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(client as never, envelopeSessionState);\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(\"sandbox reaper: drainable box already gone (NotFound on resume) — proceeding to cold\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\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(\"sandbox reaper: box gone during persist (NotFound) — nothing to snapshot, proceeding to cold\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n });\n return true;\n }\n observability.warn(\"sandbox reaper: persistWorkspace failed — leaving box draining (files NOT lost)\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\n error: error instanceof Error ? error.message : String(error),\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 } = await persistArchive(archiveBase64);\n if (!wrote) {\n observability.info(\"sandbox reaper: lease re-armed during persist — leaving box RUNNING (no terminate)\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\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 } 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(\"sandbox reaper: lease re-armed during snapshot window (no-archive path) — leaving box RUNNING (no terminate)\", {\n sandboxGroupId: lease.sandboxGroupId,\n backend,\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 createScheduledTaskRun,\n createSession,\n createSessionGoal,\n enqueueSessionTurn,\n getBillingBalance,\n getWorkspaceEnvironment,\n isCodexBilledTurn,\n recordUsageEvent,\n requireScheduledTask,\n requireSession,\n setTemporalWorkflowId,\n sumUsageQuantity,\n updateScheduledTask,\n updateScheduledTaskRun,\n upsertSessionGoal,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents } from \"@opengeni/events\";\nimport { configuredStaticUsageLimits, type Settings } from \"@opengeni/config\";\nimport {\n assertReusableSessionRevivable,\n mergeResourceRefs,\n mergeToolRefs,\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 (input: DispatchScheduledTaskRunInput): Promise<DispatchScheduledTaskRunResult> => {\n const { settings, db, bus } = 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({ db, settings, workspaceId: task.workspaceId, model });\n await ensureScheduledRunAllowed(settings, db, task.accountId, task.workspaceId, input.agentRunUsageIdempotencyKey ? 0 : 1, isCodexRun);\n const run = await createScheduledTaskRun(db, {\n workspaceId: task.workspaceId,\n taskId: task.id,\n triggerType: input.triggerType,\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 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.environment_id is ON DELETE RESTRICT, so\n // an attached environment must still exist here; fail closed if not.\n const environment = task.environmentId\n ? await getWorkspaceEnvironment(db, task.workspaceId, task.environmentId)\n : null;\n if (task.environmentId && !environment) {\n throw new Error(`workspace environment not found: ${task.environmentId}`);\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 environmentId: task.environmentId ?? null,\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, { reusableSessionId: session.id });\n }\n const events = await appendAndPublishEvents(db, bus, task.workspaceId, session.id, [\n {\n type: \"session.created\",\n payload: {\n status: \"queued\",\n scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n // Names/ids only; never values.\n ...(environment ? { environmentId: environment.id, environmentName: environment.name } : {}),\n },\n },\n ...(goal ? [{\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 type: \"user.message\",\n payload: scheduledUserMessagePayload(task.agentConfig.prompt, task.agentConfig.resources, taskTools, task.id, run.id),\n },\n { type: \"session.status.changed\", payload: { status: \"queued\" } },\n ]);\n const trigger = events.find((event) => event.type === \"user.message\");\n if (!trigger) {\n throw new Error(\"failed to append scheduled task trigger event\");\n }\n const turn = await enqueueSessionTurn(db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n triggerEventId: trigger.id,\n temporalWorkflowId: workflowId,\n source: \"scheduled_task\",\n prompt: task.agentConfig.prompt,\n resources: task.agentConfig.resources,\n tools: taskTools,\n model,\n reasoningEffort,\n sandboxBackend,\n metadata: {\n scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n },\n });\n await appendAndPublishEvents(db, bus, task.workspaceId, session.id, [{\n type: \"turn.queued\",\n turnId: turn.id,\n payload: { turnId: turn.id, triggerEventId: trigger.id, source: turn.source },\n }]);\n await updateScheduledTaskRun(db, task.workspaceId, run.id, {\n status: \"dispatched\",\n sessionId: session.id,\n triggerEventId: trigger.id,\n });\n result = {\n action: \"start\",\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n triggerEventId: trigger.id,\n workflowId,\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.environmentId ?? null) !== (task.environmentId ?? null)) {\n throw new Error(\"scheduled task environment attachment does not match its reusable session\");\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 = goalSpec\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 const events = await appendSessionEventsWithLockedSessionUpdate(db, task.workspaceId, session.id, (locked) => {\n // Authoritative guard under the FOR UPDATE row lock: re-check the\n // current status to close the TOCTOU between the early read and the\n // lock (a cancel could land in between). Throwing aborts the whole\n // append+update transaction, so no user.message is persisted.\n assertReusableSessionRevivable(locked.status);\n return {\n events: [\n ...(reusableGoal ? [{\n type: \"goal.set\" as const,\n payload: {\n goalId: reusableGoal.goal.id,\n text: reusableGoal.goal.text,\n ...(reusableGoal.goal.successCriteria ? { successCriteria: reusableGoal.goal.successCriteria } : {}),\n version: reusableGoal.goal.version,\n actor: \"scheduled_task\",\n replaced: reusableGoal.replaced,\n },\n }] : []),\n {\n type: \"user.message\",\n payload: scheduledUserMessagePayload(task.agentConfig.prompt, task.agentConfig.resources, taskTools, task.id, run.id),\n },\n ],\n update: {\n resources: mergeResourceRefs(locked.resources, task.agentConfig.resources),\n tools: mergeToolRefs(locked.tools, taskTools),\n },\n };\n });\n await bus.publish(task.workspaceId, session.id, events);\n const trigger = events.find((event) => event.type === \"user.message\");\n if (!trigger) {\n throw new Error(\"failed to append scheduled task trigger event\");\n }\n const turn = await enqueueSessionTurn(db, {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n triggerEventId: trigger.id,\n temporalWorkflowId: workflowIdForSession(session.id),\n source: \"scheduled_task\",\n prompt: task.agentConfig.prompt,\n resources: task.agentConfig.resources,\n tools: taskTools,\n model,\n reasoningEffort,\n sandboxBackend,\n metadata: {\n scheduledTaskId: task.id,\n scheduledTaskRunId: run.id,\n },\n });\n await appendAndPublishEvents(db, bus, task.workspaceId, session.id, [{\n type: \"turn.queued\",\n turnId: turn.id,\n payload: { turnId: turn.id, triggerEventId: trigger.id, source: turn.source },\n }]);\n await updateScheduledTaskRun(db, task.workspaceId, run.id, {\n status: \"dispatched\",\n sessionId: session.id,\n triggerEventId: trigger.id,\n });\n result = {\n action: \"signal\",\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n sessionId: session.id,\n triggerEventId: trigger.id,\n workflowId: workflowIdForSession(session.id),\n };\n }\n } catch (error) {\n await updateScheduledTaskRun(db, task.workspaceId, run.id, {\n status: \"failed\",\n error: 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: input.agentRunUsageIdempotencyKey ?? `usage:agent_run.created:scheduled:${run.id}`,\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 (!isCodexRun && (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")) {\n const balance = await getBillingBalance(db, accountId);\n if (balance.balanceMicros <= 0) {\n throw new Error(\"insufficient OpenGeni credits\");\n }\n }\n\t if (settings.usageLimitsMode === \"static\" || settings.usageLimitsMode === \"managed\") {\n\t const limits = configuredStaticUsageLimits(settings);\n\t if (!isCodexRun && limits.maxMonthlyCostMicrosPerAccount) {\n\t const used = await sumUsageQuantity(db, {\n\t accountId,\n\t eventType: \"model.cost\",\n\t since: startOfUtcMonth(),\n\t });\n\t if (used >= limits.maxMonthlyCostMicrosPerAccount) {\n\t throw new Error(`monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`);\n\t }\n\t }\n\t if (limits.maxMonthlyAgentRunsPerWorkspace) {\n\t const used = await sumUsageQuantity(db, {\n\t workspaceId,\n eventType: \"agent_run.created\",\n since: startOfUtcMonth(),\n });\n if (used + requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {\n throw new Error(`monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`);\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 claimNextQueuedTurn as claimNextQueuedTurnDb,\n countQueuedTurns,\n countTurnSessionHistoryItems,\n finishTurn,\n getSessionEvent,\n getSessionTurn,\n incrementTurnWorkerDeathRedispatches,\n requeuePreemptedTurn,\n requireSession,\n setSessionStatus,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents } from \"@opengeni/events\";\nimport { WORKER_DEATH_RESUME_TEXT } from \"./agent-turn\";\nimport { isSteerInterrupt, pauseActiveGoalOnInterrupt } from \"./goals\";\nimport { notifyParentOfChildTerminal } from \"./parent-wake\";\nimport { recordTurnsQueuedGauge } from \"../observability-metrics\";\nimport type {\n ActivityServices,\n ClaimNextQueuedTurnInput,\n MarkSessionIdleInput,\n RequeueTurnAfterWorkerDeathInput,\n RequeueTurnAfterWorkerDeathResult,\n RunAgentTurnInput,\n} from \"./types\";\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(services: () => Promise<ActivityServices>) {\n async function failSession(input: RunAgentTurnInput & { error?: string }): Promise<void> {\n const { db, bus, settings, observability, wakeSessionWorkflow } = await services();\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n // Already terminal: runAgentTurn settled this turn as failed (status failed,\n // activeTurnId cleared, turn finished) and already woke any parent, then the\n // workflow still routed here because the activity's finally threw after the\n // failed return. Re-failing would append a second turn.failed/status.changed\n // and a second parent wake (a different lastSequence dodges the idle dedupe).\n // The session is already where this activity would put it, so stop.\n if (session.status === \"failed\") {\n return;\n }\n const trigger = await getSessionEvent(db, input.workspaceId, input.triggerEventId);\n const turnId = session.activeTurnId ?? null;\n await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n type: \"turn.failed\",\n turnId,\n payload: {\n triggerEventId: input.triggerEventId,\n trigger: trigger?.payload ?? null,\n error: input.error ?? \"Agent activity failed before it could report a terminal state.\",\n },\n },\n {\n type: \"session.status.changed\",\n turnId,\n payload: { status: \"failed\" },\n },\n ]);\n if (turnId) {\n await finishTurn(db, input.workspaceId, turnId, \"failed\");\n }\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"failed\", null);\n await notifyParentOfChildTerminal({ db, bus, settings, observability, wakeSessionWorkflow }, input.workspaceId, input.sessionId, \"failed\");\n }\n\n async function interruptActiveTurn(input: RunAgentTurnInput): Promise<void> {\n const { db, bus, observability } = await services();\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n const trigger = await getSessionEvent(db, input.workspaceId, input.triggerEventId);\n // Pause an active goal before the early return below: an interrupt can\n // land after the turn already cleared activeTurnId, and skipping the pause\n // there would let the loop auto-continue the goal the user just stopped.\n // Steer interrupts are the exception: steering cancels the running turn\n // only to deliver the steered message next — redirection, not a stop —\n // so the goal loop stays active.\n if (!isSteerInterrupt(trigger)) {\n await pauseActiveGoalOnInterrupt(db, bus, input.workspaceId, input.sessionId);\n }\n if (!session.activeTurnId) {\n return;\n }\n await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n turnId: session.activeTurnId,\n type: \"turn.cancelled\",\n payload: { triggerEventId: input.triggerEventId, reason: trigger?.payload ?? null },\n },\n {\n turnId: session.activeTurnId,\n type: \"session.status.changed\",\n payload: { status: \"queued\" },\n },\n ]);\n await finishTurn(db, input.workspaceId, session.activeTurnId, \"cancelled\");\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"queued\", null);\n await refreshQueuedTurnsGauge(db, observability);\n }\n\n /**\n * Put a turn whose hosting worker died WITHOUT the graceful-preempt\n * checkpoint (heartbeat-timeout activity failure: SIGKILL, OOM, node loss)\n * back on the session queue, so the workflow re-dispatches it instead of\n * failing the session. The degraded-resume contract: conversation truth is\n * dual-written after every model response during the turn, so re-running\n * from the trigger event plus stored items loses at most the work since the\n * last reconcile. When the dead attempt persisted items for this turn, the\n * rerun enters through a synthesized `turn.preempted` resume notice (its\n * partial progress is already conversation truth; replaying the original\n * trigger would duplicate input the model has seen). When nothing was\n * persisted — checkpoint absent — the original trigger replays cleanly.\n * Approval reruns always replay their original trigger: the decision is\n * applied through the RunState resume path and a swapped trigger could\n * drop it. Re-dispatches are bounded per turn by\n * WORKER_DEATH_MAX_REDISPATCHES, persisted on the turn row.\n */\n async function requeueTurnAfterWorkerDeath(input: RequeueTurnAfterWorkerDeathInput): Promise<RequeueTurnAfterWorkerDeathResult> {\n const { settings, db, bus, observability } = await services();\n const turn = await getSessionTurn(db, input.workspaceId, input.turnId);\n if (!turn || (turn.status !== \"running\" && turn.status !== \"requires_action\")) {\n // The timed-out attempt was a zombie that actually settled the turn\n // (completed/failed/cancelled it) after the server gave up on its\n // heartbeats. Whatever it recorded is the truth; nothing to redo.\n return { action: \"stale\" };\n }\n const redispatches = await incrementTurnWorkerDeathRedispatches(db, input.workspaceId, input.turnId);\n if (redispatches > WORKER_DEATH_MAX_REDISPATCHES) {\n return { action: \"exceeded\", redispatches: redispatches - 1 };\n }\n const trigger = await getSessionEvent(db, input.workspaceId, input.triggerEventId);\n const approvalRerun = trigger?.type === \"user.approvalDecision\";\n // Legacy run-state mode has no crash checkpoint (the dying worker never\n // captured the blob), so it always replays the original trigger against\n // the previous RunState snapshot — the documented degraded resume.\n const resumeWithNotice = !approvalRerun\n && settings.sessionHistorySource === \"items\"\n && await countTurnSessionHistoryItems(db, input.workspaceId, input.turnId) > 0;\n const [preemptedEvent] = await appendAndPublishEvents(db, bus, input.workspaceId, input.sessionId, [\n {\n turnId: turn.id,\n type: \"turn.preempted\",\n payload: {\n triggerEventId: input.triggerEventId,\n reason: \"worker_death\",\n redispatches,\n resumeWithNotice,\n ...(resumeWithNotice ? { text: WORKER_DEATH_RESUME_TEXT } : {}),\n },\n },\n {\n turnId: turn.id,\n type: \"session.status.changed\",\n payload: { status: \"queued\" },\n },\n ]);\n try {\n await requeuePreemptedTurn(db, input.workspaceId, turn.id, resumeWithNotice && preemptedEvent ? preemptedEvent.id : input.triggerEventId);\n } catch (requeueError) {\n // The zombie attempt can settle the turn between the status check above\n // and this requeue (it keeps executing until it notices the timeout).\n // A settled turn means its recorded outcome is the truth: report stale\n // so the workflow continues instead of failing the session over a lost\n // race. Anything else is a real persistence failure — rethrow.\n const current = await getSessionTurn(db, input.workspaceId, input.turnId);\n if (current && current.status !== \"running\" && current.status !== \"requires_action\") {\n return { action: \"stale\" };\n }\n throw requeueError;\n }\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"queued\", null);\n await refreshQueuedTurnsGauge(db, observability);\n return { action: \"requeued\", redispatches };\n }\n\n async function claimNextQueuedTurn(input: ClaimNextQueuedTurnInput) {\n const { db, observability } = await services();\n const turn = await claimNextQueuedTurnDb(db, input.workspaceId, input.sessionId, input.workflowId);\n await refreshQueuedTurnsGauge(db, observability);\n return turn;\n }\n\n async function markSessionIdle(input: MarkSessionIdleInput): Promise<void> {\n const { db, bus, settings, observability, wakeSessionWorkflow } = await services();\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n if (session.status === \"queued\" || session.status === \"running\") {\n await setSessionStatus(db, input.workspaceId, input.sessionId, \"idle\", null);\n }\n await refreshQueuedTurnsGauge(db, observability);\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-interrupt stop). Wake\n // the parent here, deduped per idle episode so the manager is nudged once.\n await notifyParentOfChildTerminal({ db, bus, settings, observability, wakeSessionWorkflow }, input.workspaceId, input.sessionId, \"idle\");\n }\n\n return {\n failSession,\n interruptActiveTurn,\n requeueTurnAfterWorkerDeath,\n claimNextQueuedTurn,\n markSessionIdle,\n };\n}\n\nasync function refreshQueuedTurnsGauge(\n db: ActivityServices[\"db\"],\n observability: ActivityServices[\"observability\"],\n): Promise<void> {\n try {\n recordTurnsQueuedGauge(observability, await countQueuedTurns(db));\n } catch {\n // Best-effort telemetry; session state transitions remain authoritative.\n }\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(checks: ReadinessChecks, timeoutMs = 2_000): Promise<ReadinessResult> {\n const entries = await Promise.all(\n (Object.entries(checks) as Array<[ReadinessCheckName, () => Promise<void> | void]>)\n .map(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 [name, { ok: false, error: error instanceof Error ? error.message : String(error) }] as const;\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(() => reject(new Error(`readiness check timed out after ${timeoutMs}ms`)), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n"],"mappings":";AAAA,SAAS,gBAAAA,eAAc,eAAAC,cAAa,+BAAAC,8BAA6B,wBAAwB,2BAA0C;AACnI,SAAS,YAAAC,iBAAgB;AACzB,SAAS,sBAAAC,2BAA0B;AACnC,SAAS,uBAAAC,sBAAqB,iCAAqD;AACnF,SAAS,YAAY,wBAAwB,uBAAuB,UAAU,sBAAsB;AACpG,SAAS,kBAAkB,cAAc;AACzC,SAAS,gCAAgC;;;ACNzC,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,uBAAuB;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA,cAAAC;AAAA,EACA,qBAAAC;AAAA,EACA,eAAAC;AAAA,EACA,mBAAAC;AAAA,EACA,kBAAAC;AAAA,EACA;AAAA,EACA,qBAAAC;AAAA,EACA,oCAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,gCAAAC;AAAA,EACA,8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AA,MACf;AAAA,MACA,MAAM,6BAA6B,QAAQ;AAAA,MAC3C,EAAE,GAAG,cAAc,QAAQ;AAAA,IAC7B;AACA,mBAAe,MAAM,qBAAqB;AAAA,MACxC;AAAA,MACA,sBAAsB;AAAA,QACpB;AAAA,QACA,qBAAqB,SAAS;AAAA,QAC9B,IAAI,SAAS;AAAA,QACb;AAAA,MACF;AAAA,IACF,CAAC;AACD,iBAAa,sBAAsB;AAAA,MACjC;AAAA,MACA;AAAA,MACA,QAAQ;AAAA,QACN,IAAI,aAAa,SAAS,EAAE;AAAA,QAC5B,MAAM,eAAe,GAAG;AAAA,QACxB,UAAU,SAAS;AAAA,MACrB;AAAA,IACF,CAAC;AAKD,qBAAiB,MAAM;AAAA,MACrB;AAAA,MACA,MAAM,8BAA8B,UAAU,aAAa;AAAA,MAC3D,EAAE,GAAG,cAAc,QAAQ;AAAA,IAC7B;AACA,kBAAc,KAAK,6BAA6B;AAAA,MAC9C,mBAAmB,SAAS;AAAA,MAC5B,UAAU,SAAS;AAAA,IACrB,CAAC;AACD,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,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","createObjectStorage","getBillingBalance","getSandbox","readActiveSandbox","requireFile","getSessionEvent","getSessionGoal","isCodexBilledTurn","workspaceCodexSubscriptionActive","requireSession","recordUsageEvent","getActiveSessionHistoryItems","nextSessionHistoryPosition","sumUsageQuantity","SandboxLeaseSupersededError","appendAndPublishEvents","sanitizeHistoryItemsForModel","summarizeForCompaction","SUMMARY_BUFFER_TOKENS","configuredStaticUsageLimits","chosen","CODEX_FALLBACK_MODEL_SLUGS","installationId","mergeToolRefs","reasoningEffortForMetadata","maybeContinueGoal","pauseGoalForInterrupt","getSessionGoal","resolveContextCompactionMode","getActiveSessionHistoryItems","getSandboxSessionEnvelope","getSandboxSessionEnvelope","resumeEnvelope","desktopCapableBackend","sanitizeHistoryItemsForModel","runAgentTurn","workspaceCodexSubscriptionActive","requireSession","getSessionEvent","isCodexBilledTurn","appendAndPublishEvents","getSessionGoal","CODEX_FALLBACK_MODEL_SLUGS","readActiveSandbox","getSandbox","summarizeForCompaction","SUMMARY_BUFFER_TOKENS","trigger","getActiveSessionHistoryItems","nextSessionHistoryPosition","recordUsageEvent","SandboxLeaseSupersededError","getBillingBalance","configuredStaticUsageLimits","sumUsageQuantity","startOfUtcMonth","requireFile","configuredStaticUsageLimits","getBillingBalance","recordUsageEvent","sumUsageQuantity","startOfUtcMonth","accrueWarmSeconds","getBillingBalance","readLease","sandboxWarmRateMicrosPerSecond","reapSandboxLeases","sandboxWarmRateMicrosPerSecond","accrueWarmSeconds","getBillingBalance","readLease","enqueueSessionTurn","getBillingBalance","isCodexBilledTurn","recordUsageEvent","requireSession","sumUsageQuantity","appendAndPublishEvents","configuredStaticUsageLimits","isCodexBilledTurn","recordUsageEvent","appendAndPublishEvents","enqueueSessionTurn","requireSession","getBillingBalance","configuredStaticUsageLimits","sumUsageQuantity","startOfUtcMonth","claimNextQueuedTurnDb","countQueuedTurns","finishTurn","getSessionEvent","getSessionTurn","requeuePreemptedTurn","requireSession","setSessionStatus","appendAndPublishEvents","failSession","requireSession","getSessionEvent","appendAndPublishEvents","finishTurn","setSessionStatus","interruptActiveTurn","requeueTurnAfterWorkerDeath","getSessionTurn","requeuePreemptedTurn","claimNextQueuedTurn","claimNextQueuedTurnDb","markSessionIdle","countQueuedTurns","createObjectStorage","runAgentTurn","getSettings","createObservability","dbSearchPath","createDb","resolveNatsControlPlaneAuth","createNatsEventBus"]}