@opengeni/worker-bundle 0.27.3-canary.0 → 0.28.1-canary.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/activities-turn.ts","../src/activities/agent-turn/run.ts","../src/activities/codex-auth.ts","../src/activities/turn-attempt-fenced.ts","../src/model-context-contributions.ts","../src/activities/agent-turn/tool-result-spill.ts","../src/activities/agent-turn/file-resources.ts","../src/activities/environment.ts","../src/activities/agent-turn/credential-leases.ts","../src/activities/agent-turn/codex.ts","../src/activities/agent-turn/media-artifacts.ts","../src/activities/generated-images.ts","../src/activities/retained-screenshots.ts","../src/activities/agent-turn/history-sink.ts","../src/activities/agent-turn/history.ts","../src/activities/agent-turn/history-prefix.ts","../src/activities/agent-turn/provider-dispatch-barrier.ts","../src/model-checkpoint-memory-collector.ts","../src/activities/agent-turn/turn-context.ts","../src/activities/agent-turn/finalization.ts","../src/activities/workspace-capture.ts","../src/activities/agent-turn/failure-settlement.ts","../src/activities/agent-turn/admission.ts","../src/activities/agent-turn/model-usage.ts","../src/activities/agent-turn/stream-attempt.ts","../src/activities/context-compaction.ts","../src/activities/open-suffix-resume.ts","../src/activities/agent-turn/session-title.ts","../src/activities/agent-turn/sandbox-shared-preparation.ts","../src/activities/agent-turn/claim.ts","../src/activities/capabilities.ts","../src/op-journal.ts","../src/activities/agent-turn/codex-capacity.ts","../src/activities/codex-fleet-shadow.ts","../src/activities/agent-turn/governance-model.ts","../src/activities/agent-turn/tool-policy.ts","../src/activities/image-generation-operation.ts","../src/activities/agent-turn/compaction-prep.ts","../src/activities/agent-turn/sandbox-runtime.ts","../src/activities/agent-turn/sandbox-establish.ts","../src/activities/agent-turn/sandbox-route.ts","../src/activities/agent-turn/xai-capacity.ts","../src/activities/agent-turn/run-credentials.ts","../src/activities/git-credential-renewal.ts","../src/activities/expiring-material-renewal.ts","../src/activities/run-credential-renewal.ts","../src/activities/codemode-token-renewal.ts","../src/activities/run-credentials.ts","../src/activities/agent-turn/tool-environment.ts","../src/activities/google-drive-publication.ts","../src/activities/mcp-credentials.ts","../src/github-rest-mcp.ts","../src/activities/connector-attachments.ts","../src/activities/codemode-dispatcher.ts","../src/activities/agent-turn/turn-sandbox-access.ts","../src/activities/agent-turn/list-models.ts","../src/activities/agent-turn/skill-tools.ts","../src/activities/agent-turn/skill-read.ts","../src/activities/agent-turn/skill-search.ts","../src/activities/agent-turn/skill-save.ts","../src/activities/agent-turn/skill-install.ts","../src/activities/agent-turn/skill-transfer.ts","../src/activities/agent-turn/skill-checkout.ts","../src/activities/agent-turn/skill-selection.ts","../src/activities/agent-turn/github-repository-bindings.ts","../src/activities/agent-turn/agent-build.ts","../src/activities/xai-image-generation.ts","../src/activities/video-generation-admission.ts","../src/activities/video-reference-staging.ts","../src/activities/video-media-validation.ts","../src/activities/video-generation-credential.ts","../src/activities/gateway-image-generation.ts","../src/activities/codex-image-generation.ts","../src/activities/image-generation-references.ts","../src/activities/agent-turn/video-reference-sandbox.ts","../src/activities/video-generation-reconciliation.ts","../src/activities/gateway-video-generation.ts","../src/activities/video-output-retention.ts","../src/activities/xai-video-generation.ts"],"sourcesContent":["import { createProductionAgentRuntime, summarizeForCompaction } from \"@opengeni/runtime\";\nimport { createSharedActivityServices } from \"./activity-services\";\nimport { createRunAgentTurnActivity } from \"./activities/agent-turn\";\nimport { createVideoGenerationActivities } from \"./activities/video-generation-reconciliation\";\nimport type { ActivityDependencies, TurnActivityServices } from \"./activities/types\";\nimport { runtimeMetricsHooksForObservability } from \"./observability-metrics\";\n\nfunction createTurnActivityServices(\n dependencies: ActivityDependencies,\n): () => Promise<TurnActivityServices> {\n const shared = createSharedActivityServices(dependencies);\n let servicesPromise: Promise<TurnActivityServices> | null = null;\n return async () => {\n servicesPromise ??= (async () => {\n const services = await shared();\n return {\n ...services,\n runtime:\n dependencies.runtime ??\n createProductionAgentRuntime({\n metrics: runtimeMetricsHooksForObservability(services.observability),\n }),\n summarizeContextForCompaction:\n dependencies.summarizeContextForCompaction ?? summarizeForCompaction,\n };\n })();\n return await servicesPromise;\n };\n}\n\nexport function createTurnActivities(dependencies: ActivityDependencies = {}) {\n return createTurnActivitiesFromServices(createTurnActivityServices(dependencies));\n}\n\nexport function createTurnActivitiesFromServices(services: () => Promise<TurnActivityServices>) {\n return {\n runAgentTurn: createRunAgentTurnActivity(services),\n ...createVideoGenerationActivities(services),\n };\n}\n","import { assertModelConnectionAllowsTurn } from \"@opengeni/db\";\nimport {\n setSessionLastInputTokensForTurnAttempt,\n getMaterializedSandboxFileResources,\n markSandboxFileResourcesMaterialized,\n} from \"@opengeni/db\";\nimport { sandboxOperationMetricObserver } from \"@opengeni/observability\";\nimport {\n REMOTE_COMPACTION_V2_BETA_FEATURE,\n REMOTE_COMPACTION_V2_IMPLEMENTATION,\n materializeSandboxFileDownloads,\n sandboxFileDownloadFailureNote,\n type SandboxFileDownload,\n type SandboxFileDownloadFailure,\n type CodemodeTokenWriterSession,\n} from \"@opengeni/runtime\";\nimport { buildCodexTokenResolver } from \"../codex-auth\";\nimport {\n buildModelResolver,\n CODEX_CLIENT_VERSION,\n CODEX_FALLBACK_MODEL_SLUGS,\n codexRequestStorage,\n withCodexRequestOverrides,\n type CodexRequestContext,\n} from \"@opengeni/codex\";\nimport {\n xaiSubscriptionRequestStorage,\n type XaiSubscriptionRequestContext,\n} from \"@opengeni/xai-subscription\";\nimport { buildXaiTurnRequestAuthorization } from \"../xai-auth\";\nimport { TurnAttemptFencedError } from \"../turn-attempt-fenced\";\nimport { currentActivityContext } from \"../streaming\";\nimport type {\n TurnActivityServices as ActivityServices,\n RunAgentTurnInput,\n RunAgentTurnResult,\n} from \"../types\";\nimport {\n makeMachineOpObserver,\n modelRequestLifecycleMetricsFor,\n recordModelRequestPhase,\n recordCompanyBrainContributions,\n recordTurnStartupPhase,\n runtimeMetricsHooksForObservability,\n} from \"../../observability-metrics\";\nimport { summarizeCompanyBrainContributions } from \"../../model-context-contributions\";\nimport { ToolResultSpill } from \"./tool-result-spill\";\nimport { createTurnCredentialLeases } from \"./credential-leases\";\nimport { createTurnMediaArtifacts } from \"./media-artifacts\";\nimport { createTurnHistorySink } from \"./history-sink\";\nimport { checkpointHistoryBeforeProviderDispatch } from \"./provider-dispatch-barrier\";\nimport { providerRecoveryCountAfterModelRequestPhase } from \"./errors\";\nimport { sandboxRunAs } from \"@opengeni/runtime\";\nimport { randomUUID } from \"node:crypto\";\nimport { createModelCheckpointMemoryCollector } from \"../../model-checkpoint-memory-collector\";\n\nimport { codexWorkspaceMetricKey } from \"./codex\";\nimport {\n filterUnmaterializedSandboxFileDownloads,\n sandboxFileMaterializationOutcome,\n sandboxFileDownloadsForRun,\n objectStorageForSandboxDownloads,\n} from \"./file-resources\";\nimport { TurnEventPublisher } from \"./model-usage\";\nimport { waitForTurnOperation } from \"./sandbox-provision\";\nimport { createTurnContext, type EventingState } from \"./turn-context\";\nimport { finalizeTurnAttempt } from \"./finalization\";\nimport { settleTurnFailure } from \"./failure-settlement\";\nimport { runTurnStreamAttempt } from \"./stream-attempt\";\nimport { claimTurnAttempt } from \"./claim\";\nimport { selectCodexTurnCapacity, type CapacityPhaseDeps } from \"./codex-capacity\";\nimport { prepareGovernanceAndModel } from \"./governance-model\";\nimport { prepareCompaction, runPostAgentCompaction } from \"./compaction-prep\";\nimport { createSandboxTurnRuntime } from \"./sandbox-runtime\";\nimport {\n resolveSandboxRoute,\n establishTurnSandbox,\n bindLazySandboxProvisioner,\n} from \"./sandbox-establish\";\nimport { selectXaiTurnCapacity } from \"./xai-capacity\";\nimport { prepareRunCredentials } from \"./run-credentials\";\nimport { prepareTurnToolPolicy, prepareTurnToolRuntime } from \"./tool-environment\";\nimport { applyTurnGitHubRepositoryBindings } from \"./github-repository-bindings\";\nimport { buildTurnAgent } from \"./agent-build\";\n\n/**\n * Retain subscription credential/account authority for the title sidecar\n * without sharing main-stream recovery, startup, audit, or opaque-artifact\n * callbacks. Title usage is returned by the runtime and metered separately.\n */\nexport function sessionTitleCodexRequestContext(\n context: CodexRequestContext,\n nextRequestId: () => string,\n): CodexRequestContext {\n return {\n clientVersion: context.clientVersion,\n ...(context.sessionId !== undefined ? { sessionId: context.sessionId } : {}),\n getToken: context.getToken,\n refresh: context.refresh,\n resolveModel: context.resolveModel,\n ...(context.onUsageHeaders ? { onUsageHeaders: context.onUsageHeaders } : {}),\n ...(context.beforeProviderDispatch\n ? { beforeProviderDispatch: context.beforeProviderDispatch }\n : {}),\n ...(context.responseTimeoutPolicy\n ? { responseTimeoutPolicy: context.responseTimeoutPolicy }\n : {}),\n nextRequestId,\n turnMetadata: { request_kind: \"session_title\" },\n };\n}\n\nexport function sessionTitleXaiRequestContext(\n context: XaiSubscriptionRequestContext,\n nextRequestId: () => string,\n): XaiSubscriptionRequestContext {\n return {\n clientVersion: context.clientVersion,\n sessionId: context.sessionId,\n turnId: context.turnId,\n getToken: context.getToken,\n refresh: context.refresh,\n resolveModel: context.resolveModel,\n ...(context.streamIdleTimeoutMs !== undefined\n ? { streamIdleTimeoutMs: context.streamIdleTimeoutMs }\n : {}),\n ...(context.hostedToolContinuationTimeoutMs !== undefined\n ? { hostedToolContinuationTimeoutMs: context.hostedToolContinuationTimeoutMs }\n : {}),\n nextRequestId,\n };\n}\n\n/** Lifecycle orchestrator: claim → capacity → governance → sandbox → tools → stream. */\nexport function createRunAgentTurnActivity(services: () => Promise<ActivityServices>) {\n const modelCheckpointMemoryCollector = createModelCheckpointMemoryCollector();\n // Keep a distinct cooldown for terminal collection. A collection at the\n // final model checkpoint happens while the activity still owns its complete\n // turn graph and must not suppress collection after that graph is released.\n const turnCompletionMemoryCollector = createModelCheckpointMemoryCollector();\n return async function runAgentTurn(input: RunAgentTurnInput): Promise<RunAgentTurnResult> {\n const {\n settings,\n catalogSourceSettings = settings,\n db,\n bus,\n runtime,\n summarizeContextForCompaction,\n objectStorage,\n observability,\n wakeSessionWorkflow,\n signalSessionAttemptQuiesced,\n signalCodexCapacityWorkflow,\n entitlements,\n connectionCredentials,\n personalGitHubCredentials,\n startVideoGenerationWorkflow,\n } = await services();\n const activityContext = currentActivityContext();\n const cancellationSignal = activityContext?.cancellationSignal;\n // Temporal cancellation is not the only way an activity loses ownership:\n // a database attempt fence or workflow abandonment can finalize the logical\n // turn while the SDK cancellation signal remains open. Bind sandbox\n // provisioning to both lifetimes so an uninterruptible, late provider\n // promise cannot resurrect a holder after this activity has finalized.\n const sandboxResumeController = new AbortController();\n const sandboxResumeSignal = cancellationSignal\n ? AbortSignal.any([cancellationSignal, sandboxResumeController.signal])\n : sandboxResumeController.signal;\n const sandboxRotationController = new AbortController();\n const runtimeCancellationSignal = cancellationSignal\n ? AbortSignal.any([cancellationSignal, sandboxRotationController.signal])\n : sandboxRotationController.signal;\n\n const {\n control,\n attempt,\n billingState,\n sandboxState,\n renewals,\n eventing,\n workspaceRefs,\n providerTurn,\n } = createTurnContext({\n settings,\n cancellationRequestedAt: cancellationSignal?.aborted ? performance.now() : null,\n });\n const noteCancellationRequested = (): void => {\n control.cancellationRequestedAt ??= performance.now();\n };\n cancellationSignal?.addEventListener(\"abort\", noteCancellationRequested, {\n once: true,\n });\n const dispatchId = activityContext?.info.activityId ?? randomUUID();\n const activityStarted = performance.now();\n const activitySpan = observability.startSpan(\"worker.run_agent_segment\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.workflow_id\": input.workflowId,\n \"opengeni.trigger_kind\": input.trigger.kind,\n });\n const acknowledgeLostAttemptOwnership = (): void => {\n // A stale terminal/recovery settlement can lose either to a benign\n // successor or to Pause/Steer closing this exact attempt. Only the\n // receipt transaction can distinguish those cases after the hard tool\n // fence: allowUninterrupted makes the benign case an event-free no-op.\n control.acknowledgeQuiescence = true;\n noteCancellationRequested();\n };\n const acknowledgeRecoveryQuiescence = (): void => {\n // requestSessionTurnRecovery closed this exact attempt and durably\n // recorded the replacement cause. The activity still owns the physical\n // tool/credential boundary until finally drains it and publishes the\n // exact quiescence receipt; a workflow result alone is never that proof.\n control.acknowledgeQuiescence = true;\n noteCancellationRequested();\n };\n const claimedResult = (\n result: Omit<\n Extract<RunAgentTurnResult, { status: Exclude<RunAgentTurnResult[\"status\"], \"unclaimed\"> }>,\n \"turnId\" | \"attemptId\"\n >,\n ): RunAgentTurnResult => {\n if (!attempt.turnId)\n throw new Error(\"Claimed activity result produced before turn admission\");\n return {\n ...result,\n turnId: attempt.turnId,\n attemptId: input.attemptId,\n } as RunAgentTurnResult;\n };\n // The Connected Machine op observer for this turn: meters every op AND buffers\n // the eventable ones (infra failures + healed recoveries) as machine.op.* session\n // events, drained (awaited) at turn end in the finally below. ONE instance shared\n // by the machine-primary establish + both routing wraps.\n const machineOpObserver = makeMachineOpObserver(\n runtimeMetricsHooksForObservability(observability),\n );\n const sandboxOperationObserver = sandboxOperationMetricObserver(observability);\n // Still required by credential-loss/capacity settlements, whose own\n // recovery transactions fence against worker-death redispatches.\n const setLastInputTokensFenced = async (lastInputTokens: number | null): Promise<void> => {\n if (!attempt.turnId || attempt.executionGeneration <= 0) {\n throw new Error(\"Turn attempt was not initialized before token accounting\");\n }\n if (\n !(await setSessionLastInputTokensForTurnAttempt(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n expectedExecutionGeneration: attempt.executionGeneration,\n expectedAttemptId: input.attemptId,\n lastInputTokens,\n }))\n ) {\n throw new TurnAttemptFencedError(\"turn attempt was fenced while recording input tokens\");\n }\n };\n const codexWorkspaceKey = codexWorkspaceMetricKey(input.workspaceId);\n const leases = createTurnCredentialLeases({\n db,\n observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n codexWorkspaceKey,\n getTurnId: () => attempt.turnId,\n });\n\n const sandboxRuntime = createSandboxTurnRuntime({\n input,\n settings,\n db,\n objectStorage,\n observability,\n cancellationSignal,\n activityContext,\n sandboxRotationController,\n sandboxState,\n eventing,\n attempt,\n });\n const {\n requireResolvedSandboxForMutation,\n runWorkspaceMutationForSandbox,\n stopLeaseHeartbeat,\n flushRuntimeBatcher,\n finalizeTurnOpStreamOps,\n } = sandboxRuntime;\n\n const media = createTurnMediaArtifacts({\n db,\n objectStorage,\n observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n getTurnId: () => attempt.turnId,\n getModelRunSettings: () => eventing.modelRunSettings,\n getPublish: () => eventing.publish,\n toolCancellationFenceRef: eventing.toolCancellationFenceRef,\n getResolvedSandbox: () => sandboxState.resolvedSandbox,\n getSetupBoxSession: () => sandboxState.setupBoxSession,\n getSandboxGroupId: () => sandboxState.sandboxGroupId,\n runWorkspaceMutation: runWorkspaceMutationForSandbox,\n });\n const videoGenerationAcceptancesByCallId = new Map<\n string,\n { operationId: string; requestDigest: string }\n >();\n const requiredGeneratedVideoFiles: Array<{\n operationId: string;\n artifactId: string;\n fileId: string;\n objectKey: string;\n sizeBytes: number;\n sha256: string;\n filename: string;\n }> = [];\n const toolResultSpill = new ToolResultSpill({\n db,\n objectStorage,\n observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n attemptId: input.attemptId,\n getModelRunSettings: () => eventing.modelRunSettings,\n getSandboxFileDownloadBackend: () => media.sandboxFileDownloadBackend,\n getPublish: () => {\n const current = eventing.publish;\n if (!current) return null;\n return async (events, immediate) =>\n await current(events as Parameters<TurnEventPublisher>[0], immediate);\n },\n toolCancellationFenceRef: eventing.toolCancellationFenceRef,\n getResolvedSandbox: () => sandboxState.resolvedSandbox,\n getSetupBoxSession: () => sandboxState.setupBoxSession,\n getSdkOwnedSandboxSession: () => media.sdkOwnedSandboxSession,\n getSandboxGroupId: () => sandboxState.sandboxGroupId,\n runWorkspaceMutation: runWorkspaceMutationForSandbox,\n });\n const historySink = createTurnHistorySink({\n db,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n media,\n getTurnId: () => attempt.turnId,\n getStream: () => eventing.stream,\n getModelRunSettings: () => eventing.modelRunSettings,\n getExecutionGeneration: () => attempt.executionGeneration,\n });\n\n try {\n const claimed = await claimTurnAttempt({\n input,\n settings,\n catalogSourceSettings,\n db,\n bus,\n runtime,\n observability,\n entitlements,\n wakeSessionWorkflow,\n cancellationSignal,\n activityContext,\n dispatchId,\n activityStarted,\n control,\n attempt,\n billingState,\n sandboxState,\n eventing,\n leases,\n media,\n claimedResult,\n acknowledgeLostAttemptOwnership,\n });\n if (\"exit\" in claimed) return claimed.exit;\n if (!eventing.publish || !eventing.settle) {\n throw new Error(\"turn eventing was not wired during claim\");\n }\n // Same object, narrowed type: every post-claim phase mutates this exact\n // context, so this must stay an assertion and never become a copy.\n const wiredEventing = eventing as EventingState & {\n publish: NonNullable<EventingState[\"publish\"]>;\n settle: NonNullable<EventingState[\"settle\"]>;\n };\n const {\n turn,\n session,\n installedApiIntegrations,\n credentialSubjectId,\n fileAuthoritySubjectId,\n capabilitySettings,\n codexAppsCredentialId,\n turnExecutionPolicy,\n trigger,\n humanInputResume,\n interactionInterventionResume,\n attachPendingUpdatesAfterOpenSuffix,\n throwIfWorkerShuttingDown,\n throwIfTurnCancelled,\n opJournal,\n modelUsageDispatchId,\n claimedModelUsageSourceKeys,\n emittedModelUsageSourceKeys,\n } = claimed.ok;\n if (!attempt.turnId) {\n throw new Error(\"Turn id was not initialized\");\n }\n if (!leases.codex.holderId) {\n throw new Error(\"Codex lease holder was not initialized\");\n }\n const workerPreparationStartedAt = performance.now();\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 {\n const capacityDeps: CapacityPhaseDeps = {\n input,\n settings,\n db,\n bus,\n observability,\n wakeSessionWorkflow,\n signalCodexCapacityWorkflow,\n cancellationSignal,\n dispatchId,\n control,\n attempt,\n billingState,\n eventing: wiredEventing,\n providerTurn,\n leases,\n claimedResult,\n acknowledgeLostAttemptOwnership,\n acknowledgeRecoveryQuiescence,\n setLastInputTokensFenced,\n turn,\n session,\n turnExecutionPolicy,\n trigger,\n codexWorkspaceKey,\n };\n const codexCapacity = await selectCodexTurnCapacity(capacityDeps);\n if (\"exit\" in codexCapacity) return codexCapacity.exit;\n const xaiCapacity = await selectXaiTurnCapacity(capacityDeps);\n if (\"exit\" in xaiCapacity) return xaiCapacity.exit;\n }\n\n const governance = await prepareGovernanceAndModel({\n input,\n db,\n runtime,\n objectStorage,\n eventing,\n workspaceRefs,\n media,\n turn,\n session,\n capabilitySettings,\n fileAuthoritySubjectId,\n humanInputResume,\n turnExecutionPolicy,\n requiredGeneratedVideoFiles,\n });\n if (\"exit\" in governance) return governance.exit;\n await assertModelConnectionAllowsTurn(db, {\n workspaceId: input.workspaceId,\n subjectId: turn.initiatingHumanSubjectId ?? \"worker:model-access\",\n modelId: turnExecutionPolicy.productModelId,\n codexCredentialId: providerTurn.effectiveCodexCredentialId,\n xaiCredentialId: providerTurn.effectiveXaiCredentialId,\n });\n const {\n runtimePreparationStartedAt,\n packRuntime,\n rigVersion,\n rigName,\n agentHumanInputEnabled,\n workspaceAgentInstructions,\n workspaceGovernance,\n structuredWorkspacePolicyActive,\n workspaceMemory,\n buildCompanyBrainContributionReceiptFor,\n logicalSandboxSettings,\n verifiedRigProviderImageId,\n runSettings,\n resolvedModel,\n providerApi,\n nativeImageProviderBinding,\n lazyToolTransport,\n modelInputPolicy,\n supportsImageInput,\n modelHistoryProjector,\n generatedImageHistoryProjector,\n compactionModelHistoryProjector,\n } = governance.ok;\n\n // A codex-subscription turn resolves the bearer for THIS turn's effective\n // codex account (effectiveCodexCredentialId; pin > workspace-active) at\n // model-call time — multi-account P1 means a workspace can hold N accounts,\n // so the bearer is per-account, not per-workspace. codexSubscriptionFetch\n // (on the provider's OpenAI client) reads this AsyncLocalStorage context.\n // Build it once and wrap BOTH the compaction summarizer (a separate model\n // call on the same codex client) and the main run; otherwise the summarizer\n // would hit the codex backend unauthenticated.\n let codexModelRequestSequence = 0;\n let firstModelRequestAuditRecorded = false;\n const firstModelRequestCheckpoints = new Set<string>();\n const codexContext: CodexRequestContext | null =\n resolvedModel?.provider.kind === \"codex-subscription\"\n ? ((): CodexRequestContext => {\n // The empty-string fallback yields no row → null credential → the\n // existing CodexReloginRequired path (a codex turn with no usable\n // account fails closed, exactly as before multi-account).\n const resolver = buildCodexTokenResolver(\n db,\n runSettings,\n input.workspaceId,\n providerTurn.effectiveCodexCredentialId ?? \"\",\n );\n const resolveTrackedToken = async (\n resolve: () => ReturnType<typeof resolver.getToken>,\n ) => {\n const token = await resolve();\n providerTurn.effectiveCodexCredentialVersion = token.credentialVersion;\n return token;\n };\n return {\n clientVersion: CODEX_CLIENT_VERSION,\n // Backend sticky cache-routing key — the SAME id as the body's\n // prompt_cache_key (set from input.sessionId for codex turns),\n // so routing and cache key agree. Without this header on the\n // wire, byte-identical resends hit the prompt cache ~50%\n // (per-request shard lottery = prod's measured 48.6% on sol);\n // with it, resends pin to the warm shard (Codex CLI parity).\n sessionId: input.sessionId,\n getToken: () => resolveTrackedToken(resolver.getToken),\n refresh: () => resolveTrackedToken(resolver.refresh),\n resolveModel: buildModelResolver(\n CODEX_FALLBACK_MODEL_SLUGS,\n CODEX_FALLBACK_MODEL_SLUGS[0],\n ),\n onUsageHeaders: (snapshot) => {\n providerTurn.latestCodexUsage = snapshot;\n }, // latest wins; flushed once in finally\n beforeProviderDispatch: () => {\n leases.codex.assertUsable();\n },\n onRequestPreparationDiagnostic: (phase) => {\n if (\n eventing.firstModelRequestCheckpointAt === null ||\n firstModelRequestCheckpoints.has(phase)\n ) {\n return;\n }\n const now = performance.now();\n const metricPhase =\n phase === \"transport_entry\"\n ? \"model_sdk_serialization\"\n : phase === \"credential_ready\"\n ? \"model_credential_resolution\"\n : \"model_wire_normalization\";\n firstModelRequestCheckpoints.add(phase);\n recordTurnStartupPhase(observability, {\n phase: metricPhase,\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (now - eventing.firstModelRequestCheckpointAt) / 1_000,\n count: turnTools.length,\n });\n eventing.firstModelRequestCheckpointAt = now;\n },\n onRequestOpaqueArtifacts: ({ fingerprints }) => {\n providerTurn.lastCodexRequestOpaqueArtifacts = fingerprints;\n },\n onModelRequestDiagnostic: (event) => {\n if (event.phase === \"started\") sandboxState.firstProviderRequestStarted = true;\n if (\n event.phase === \"started\" &&\n eventing.firstModelRequestPreparationStartedAt !== null &&\n !eventing.firstModelRequestPreparationRecorded\n ) {\n eventing.firstModelRequestPreparationRecorded = true;\n recordTurnStartupPhase(observability, {\n phase: \"model_request_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds:\n (performance.now() - eventing.firstModelRequestPreparationStartedAt) /\n 1_000,\n count: turnTools.length,\n });\n }\n const phase =\n event.phase === \"headers\"\n ? \"headers\"\n : event.phase === \"first_byte\"\n ? \"first_byte\"\n : event.phase === \"completed\" ||\n event.phase === \"failed\" ||\n event.phase === \"timed_out\"\n ? \"terminal\"\n : null;\n if (!phase) return;\n recordModelRequestPhase(observability, {\n provider: \"codex-subscription\",\n phase,\n ...(event.phase === \"completed\"\n ? { outcome: \"completed\" as const }\n : event.phase === \"failed\"\n ? { outcome: \"failed\" as const }\n : event.phase === \"timed_out\"\n ? { outcome: \"timed_out\" as const }\n : {}),\n durationSeconds: event.durationMs / 1000,\n });\n },\n nextRequestId: () => `${dispatchId}:${++codexModelRequestSequence}`,\n onModelRequestEvent: async (event) => {\n if (!eventing.publish || !attempt.turnId) {\n throw new Error(\"Codex model request started before the turn event producer\");\n }\n if (event.phase === \"started\") {\n await checkpointHistoryBeforeProviderDispatch(historySink);\n }\n const shouldRecordStartedAudit =\n event.phase === \"started\" && !firstModelRequestAuditRecorded;\n if (shouldRecordStartedAudit) {\n firstModelRequestAuditRecorded = true;\n }\n const auditStartedAt = shouldRecordStartedAudit ? performance.now() : null;\n let auditOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n await eventing.publish([\n ...(shouldRecordStartedAudit &&\n eventing.firstModelRequestPreparationStartedAt !== null\n ? [\n {\n type: \"turn.startup.phase.completed\" as const,\n payload: {\n phase: \"model_preparation\",\n durationMs: Math.max(\n 0,\n Math.round(\n performance.now() -\n eventing.firstModelRequestPreparationStartedAt,\n ),\n ),\n },\n },\n ]\n : []),\n {\n type: \"agent.model.request\",\n payload: {\n ...event,\n provider: \"codex-subscription\",\n turnId: attempt.turnId,\n attemptId: input.attemptId,\n dispatchId,\n executionGeneration: attempt.executionGeneration,\n },\n },\n ]);\n attempt.providerRecoveryCount = providerRecoveryCountAfterModelRequestPhase(\n attempt.providerRecoveryCount,\n event.phase,\n );\n } catch (error) {\n auditOutcome = \"failed\";\n throw error;\n } finally {\n if (auditStartedAt !== null) {\n recordTurnStartupPhase(observability, {\n phase: \"model_request_audit\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: auditOutcome,\n durationSeconds: (performance.now() - auditStartedAt) / 1_000,\n count: turnTools.length,\n });\n }\n }\n },\n };\n })()\n : null;\n if (resolvedModel?.provider.kind === \"xai-subscription\") {\n if (!providerTurn.effectiveXaiCredentialId || !leases.xai.subjectId) {\n throw new Error(\"SuperGrok subscription execution has no leased credential\");\n }\n let xaiModelRequestSequence = 0;\n const authorization = await buildXaiTurnRequestAuthorization({\n db,\n settings: runSettings,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: leases.xai.subjectId,\n sessionId: input.sessionId,\n turnId: turn.id,\n credentialId: providerTurn.effectiveXaiCredentialId,\n authoritySnapshot: turn.xaiProviderAccountAuthoritySnapshot,\n hostedSearch: {\n webSearch: runSettings.webSearchEnabled,\n xSearch: runSettings.webSearchEnabled,\n },\n streamIdleTimeoutMs: runSettings.supergrokResponseStreamIdleTimeoutMs,\n nextRequestId: () => `${dispatchId}:xai:${++xaiModelRequestSequence}`,\n onModelRequestDiagnostic: (event) => {\n const requestKey = `${event.requestId}:${event.transportAttempt}`;\n if (event.phase === \"started\") {\n sandboxState.firstProviderRequestStarted = true;\n modelRequestLifecycleMetricsFor(observability).start(\n requestKey,\n \"supergrok-subscription\",\n );\n if (\n eventing.firstModelRequestPreparationStartedAt !== null &&\n !eventing.firstModelRequestPreparationRecorded\n ) {\n eventing.firstModelRequestPreparationRecorded = true;\n recordTurnStartupPhase(observability, {\n phase: \"model_request_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds:\n (performance.now() - eventing.firstModelRequestPreparationStartedAt) / 1_000,\n count: turnTools.length,\n });\n }\n }\n if (event.phase === \"first_event\" || event.phase === \"progress\") {\n modelRequestLifecycleMetricsFor(observability).event(\n requestKey,\n event.phase === \"progress\" ? event.interEventGapMs : undefined,\n );\n }\n const terminal =\n event.phase === \"completed\" ||\n event.phase === \"failed\" ||\n event.phase === \"timed_out\";\n if (terminal) {\n modelRequestLifecycleMetricsFor(observability).finish(requestKey);\n }\n const phase =\n event.phase === \"headers\"\n ? \"headers\"\n : event.phase === \"first_event\"\n ? \"first_byte\"\n : terminal\n ? \"terminal\"\n : null;\n if (!phase) return;\n recordModelRequestPhase(observability, {\n provider: \"supergrok-subscription\",\n phase,\n ...(terminal\n ? {\n outcome:\n event.phase === \"completed\"\n ? (\"completed\" as const)\n : event.phase === \"timed_out\"\n ? (\"timed_out\" as const)\n : (\"failed\" as const),\n }\n : {}),\n durationSeconds: event.durationMs / 1_000,\n });\n },\n onModelRequestEvent: async (event) => {\n if (!eventing.publish || !attempt.turnId) {\n throw new Error(\"SuperGrok model request started before the turn event producer\");\n }\n if (event.phase === \"started\") {\n await checkpointHistoryBeforeProviderDispatch(historySink);\n }\n const shouldRecordStartedAudit =\n event.phase === \"started\" && !firstModelRequestAuditRecorded;\n if (shouldRecordStartedAudit) firstModelRequestAuditRecorded = true;\n const auditStartedAt = shouldRecordStartedAudit ? performance.now() : null;\n let auditOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n await eventing.publish([\n ...(shouldRecordStartedAudit &&\n eventing.firstModelRequestPreparationStartedAt !== null\n ? [\n {\n type: \"turn.startup.phase.completed\" as const,\n payload: {\n phase: \"model_preparation\",\n durationMs: Math.max(\n 0,\n Math.round(\n performance.now() - eventing.firstModelRequestPreparationStartedAt,\n ),\n ),\n },\n },\n ]\n : []),\n {\n type: \"agent.model.request\",\n payload: {\n ...event,\n provider: \"supergrok-subscription\",\n turnId: attempt.turnId,\n attemptId: input.attemptId,\n dispatchId,\n executionGeneration: attempt.executionGeneration,\n },\n },\n ]);\n attempt.providerRecoveryCount = providerRecoveryCountAfterModelRequestPhase(\n attempt.providerRecoveryCount,\n event.phase,\n );\n } catch (error) {\n auditOutcome = \"failed\";\n throw error;\n } finally {\n if (auditStartedAt !== null) {\n recordTurnStartupPhase(observability, {\n phase: \"model_request_audit\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: auditOutcome,\n durationSeconds: (performance.now() - auditStartedAt) / 1_000,\n count: turnTools.length,\n });\n }\n }\n },\n });\n providerTurn.xaiRequestContext = authorization.context;\n }\n const withCodex = <T>(fn: () => Promise<T>): Promise<T> =>\n codexContext ? codexRequestStorage.run(codexContext, fn) : fn();\n const withProviderRequestContext = <T>(fn: () => Promise<T>): Promise<T> =>\n providerTurn.xaiRequestContext\n ? xaiSubscriptionRequestStorage.run(providerTurn.xaiRequestContext, fn)\n : withCodex(fn);\n let codexSessionTitleRequestSequence = 0;\n let xaiSessionTitleRequestSequence = 0;\n const codexSessionTitleContext = codexContext\n ? sessionTitleCodexRequestContext(\n codexContext,\n () => `${dispatchId}:title:${++codexSessionTitleRequestSequence}`,\n )\n : null;\n const xaiSessionTitleContext = providerTurn.xaiRequestContext\n ? sessionTitleXaiRequestContext(\n providerTurn.xaiRequestContext,\n () => `${dispatchId}:xai:title:${++xaiSessionTitleRequestSequence}`,\n )\n : null;\n const withSessionTitleProviderRequestContext = <T>(fn: () => Promise<T>): Promise<T> =>\n xaiSessionTitleContext\n ? xaiSubscriptionRequestStorage.run(xaiSessionTitleContext, fn)\n : codexSessionTitleContext\n ? codexRequestStorage.run(codexSessionTitleContext, fn)\n : fn();\n const withCodexRemoteCompaction = <T>(fn: () => Promise<T>): Promise<T> =>\n withCodex(() =>\n withCodexRequestOverrides(\n {\n betaFeatures: [REMOTE_COMPACTION_V2_BETA_FEATURE],\n turnMetadata: {\n request_kind: \"compaction\",\n compaction: {\n implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION,\n strategy: \"memento\",\n },\n },\n },\n fn,\n ),\n );\n const compactionPrep = await prepareCompaction({\n input,\n settings: capabilitySettings,\n db,\n bus,\n observability,\n cancellationSignal,\n control,\n attempt,\n billingState,\n eventing: wiredEventing,\n providerTurn,\n leases,\n media,\n claimedResult,\n claimedModelUsageSourceKeys,\n emittedModelUsageSourceKeys,\n modelUsageDispatchId,\n turn,\n session,\n turnExecutionPolicy,\n resolvedModel,\n workspaceAgentInstructions,\n workspaceGovernance,\n structuredWorkspacePolicyActive,\n workspaceMemory,\n rigVersion,\n rigName,\n compactionModelHistoryProjector,\n summarizeContextForCompaction,\n withProviderRequestContext,\n withCodexRemoteCompaction,\n });\n if (\"exit\" in compactionPrep) return compactionPrep.exit;\n const {\n promptCacheKey,\n remotePrefix,\n remoteCompactionRequester,\n publishCompactionLiveEvents,\n publishCompactionOutcomeEvents,\n compactionModeOptions,\n compactionOnlyTurn,\n compactionSummarizerFor,\n settleDeferredSteerAfterCompaction,\n } = compactionPrep.ok;\n\n const toolPolicy = await prepareTurnToolPolicy({\n input,\n db,\n cancellationSignal,\n connectionCredentials,\n turn,\n session,\n fileAuthoritySubjectId,\n capabilitySettings,\n runSettings,\n rigVersion,\n workspaceRefs,\n });\n const {\n turnResources: claimedTurnResources,\n runtimeResources: claimedRuntimeResources,\n mcpAvailabilityNote,\n turnTools,\n connectionScope,\n workspaceVariableSet,\n sandboxWorkspaceEnvironmentValues,\n } = toolPolicy;\n\n const sandboxRoute = await resolveSandboxRoute({\n input,\n settings,\n db,\n eventing,\n sandboxState,\n media,\n fileAuthoritySubjectId,\n runSettings,\n logicalSandboxSettings,\n });\n const {\n routingOn,\n activeSandboxBackend,\n machinePrimary,\n groupBoxBackend,\n sandboxCreationBackend,\n effectiveRunCredentialBackend,\n } = sandboxRoute;\n\n // A bare github.com repository URI (API caller, older session, or an\n // agent-spawned child inheriting its parent's resources) resolves to\n // the workspace's GitHub App binding here, before credential minting\n // and the runtime clone plan derive binding ids from the same resource\n // set. A Connected Machine receives no platform Git credential, so its\n // resources stay exactly as stored. Resolution never fails the turn;\n // an unusable bound repository stays bare and is reported visibly.\n const { turnResources, runtimeResources } = await waitForTurnOperation(\n applyTurnGitHubRepositoryBindings({\n db,\n settings: runSettings,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n activeSandboxBackend,\n claimedTurnResources,\n claimedRuntimeResources,\n publish: async (events) => {\n await eventing.publish!(events, true);\n },\n warn: (message, fields) => observability.warn(message, fields),\n }),\n cancellationSignal,\n undefined,\n );\n\n const runCredentials = await prepareRunCredentials({\n input,\n settings,\n db,\n observability,\n cancellationSignal,\n connectionCredentials,\n personalGitHubCredentials,\n eventing,\n attempt,\n renewals,\n sandboxState,\n sandboxRuntime,\n turn,\n session,\n fileAuthoritySubjectId,\n runSettings,\n workspaceVariableSet,\n turnResources,\n requiredGeneratedVideoFiles,\n machinePrimary,\n activeSandboxBackend,\n groupBoxBackend,\n sandboxCreationBackend,\n effectiveRunCredentialBackend,\n sandboxWorkspaceEnvironmentValues,\n connectionScope,\n runWorkspaceMutationForSandbox,\n });\n const {\n runCredentialResolver,\n establishPolicy,\n initialRunCredentialMaterial,\n runCredentialsNote,\n hostCredentialRootSessionId,\n codemodeAuthority,\n sandboxArtifactRuntime,\n sandboxEnvironment,\n sandboxGitToken,\n sandboxGitTokens,\n sandboxGitCredentialBindings,\n sandboxCodemodeToken,\n sandboxCodemodeTokenExpiresAt,\n transientCodemodeEnvironment,\n initialGitCredentials,\n startRunGitCredentialsMint,\n attachGitCredentialRenewal,\n attachCodemodeTokenRenewal,\n attachRunCredentialRenewal,\n } = runCredentials;\n\n await establishTurnSandbox({\n ...sandboxRoute,\n input,\n settings,\n db,\n bus,\n objectStorage,\n observability,\n cancellationSignal,\n runtimeCancellationSignal,\n sandboxResumeSignal,\n activityContext,\n opJournal,\n sandboxState,\n eventing,\n attempt,\n turn,\n session,\n fileAuthoritySubjectId,\n capabilitySettings,\n turnExecutionPolicy,\n runSettings,\n logicalSandboxSettings,\n verifiedRigProviderImageId,\n runtimePreparationStartedAt,\n establishPolicy,\n sandboxEnvironment,\n startRunGitCredentialsMint,\n machineOpObserver,\n sandboxOperationObserver,\n sandboxRuntime,\n transientCodemodeEnvironment,\n rigVersion,\n turnResources,\n });\n\n const ordinaryFileResourceDownloads = await (async () => {\n const fileResolutionStartedAt = performance.now();\n let fileResolutionOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n return await waitForTurnOperation(\n sandboxFileDownloadsForRun(\n runSettings,\n db,\n objectStorage,\n input.accountId,\n input.workspaceId,\n fileAuthoritySubjectId,\n turn.resources,\n activeSandboxBackend ?? groupBoxBackend,\n ),\n cancellationSignal,\n undefined,\n );\n } catch (error) {\n fileResolutionOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"file_resolution\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: fileResolutionOutcome,\n durationSeconds: (performance.now() - fileResolutionStartedAt) / 1_000,\n count: turn.resources.length,\n });\n }\n })();\n if (requiredGeneratedVideoFiles.length > 0 && !objectStorage) {\n throw new Error(\"Generated video materialization requires object storage\");\n }\n const generatedVideoDownloads: SandboxFileDownload[] = [];\n if (objectStorage && requiredGeneratedVideoFiles.length > 0) {\n const downloadStorage = objectStorageForSandboxDownloads(\n eventing.modelRunSettings,\n objectStorage,\n media.sandboxFileDownloadBackend,\n );\n for (const file of requiredGeneratedVideoFiles) {\n const signed = await downloadStorage.createGetUrl({\n key: file.objectKey,\n });\n generatedVideoDownloads.push({\n fileId: file.fileId,\n mountPath: \"generated-videos\",\n filename: file.filename,\n url: signed.url,\n expiresAt: signed.expiresAt,\n sizeBytes: file.sizeBytes,\n sha256: file.sha256,\n });\n }\n }\n const fileResourceDownloads = [\n ...new Map(\n [...ordinaryFileResourceDownloads, ...generatedVideoDownloads].map((download) => [\n download.fileId,\n download,\n ]),\n ).values(),\n ];\n const toolRuntime = await prepareTurnToolRuntime({\n selectedSkillActivations: packRuntime.skillActivations,\n input,\n catalogSourceSettings,\n db,\n bus,\n runtime,\n objectStorage,\n observability,\n cancellationSignal,\n connectionCredentials,\n eventing,\n attempt,\n sandboxState,\n media,\n toolResultSpill,\n turn,\n session,\n fileAuthoritySubjectId,\n capabilitySettings,\n installedApiIntegrations,\n codexAppsCredentialId,\n turnExecutionPolicy,\n trigger,\n runSettings,\n lazyToolTransport,\n turnTools,\n connectionScope,\n hostCredentialRootSessionId,\n sandboxArtifactRuntime,\n activeSandboxBackend,\n groupBoxBackend,\n routingOn,\n runtimeCancellationSignal,\n credentialSubjectId,\n interactionInterventionResume,\n runWorkspaceMutationForSandbox,\n throwIfWorkerShuttingDown,\n throwIfTurnCancelled,\n });\n const {\n attemptConnectorActionBindings,\n connectorActionPolicy,\n generateSessionTitleInParallel,\n postToolPreparationStartedAt,\n preparationIndependentToolNames,\n } = toolRuntime;\n\n const builtAgent = await buildTurnAgent({\n skillCatalog: toolRuntime.skillCatalog,\n input,\n db,\n runtime,\n objectStorage,\n observability,\n cancellationSignal,\n runtimeCancellationSignal,\n eventing,\n attempt,\n sandboxState,\n providerTurn,\n media,\n leases,\n turn,\n session,\n fileAuthoritySubjectId,\n capabilitySettings,\n humanInputResume,\n turnExecutionPolicy,\n runSettings,\n logicalSandboxSettings,\n verifiedRigProviderImageId,\n resolvedModel,\n nativeImageProviderBinding,\n lazyToolTransport,\n modelInputPolicy,\n supportsImageInput,\n agentHumanInputEnabled,\n workspaceAgentInstructions,\n workspaceGovernance,\n structuredWorkspacePolicyActive,\n workspaceMemory,\n rigVersion,\n rigName,\n buildCompanyBrainContributionReceiptFor,\n promptCacheKey,\n workspaceVariableSet,\n runtimeResources,\n sandboxEnvironment,\n sandboxArtifactRuntime,\n sandboxGitToken,\n sandboxGitTokens,\n sandboxGitCredentialBindings,\n sandboxCodemodeToken,\n fileResourceDownloads,\n attemptConnectorActionBindings,\n connectorActionPolicy,\n trigger,\n preparationIndependentToolNames,\n videoGenerationAcceptancesByCallId,\n activeSandboxBackend,\n groupBoxBackend,\n postToolPreparationStartedAt,\n codexContext,\n });\n const { agent, modelVisibleSkillCatalogText, postAgentPreparationStartedAt } = builtAgent;\n\n await bindLazySandboxProvisioner({\n ...sandboxRoute,\n input,\n settings,\n db,\n bus,\n objectStorage,\n observability,\n cancellationSignal,\n runtimeCancellationSignal,\n sandboxResumeSignal,\n activityContext,\n opJournal,\n sandboxState,\n eventing,\n attempt,\n turn,\n session,\n fileAuthoritySubjectId,\n capabilitySettings,\n turnExecutionPolicy,\n runSettings,\n logicalSandboxSettings,\n verifiedRigProviderImageId,\n runtimePreparationStartedAt,\n establishPolicy,\n sandboxEnvironment,\n startRunGitCredentialsMint,\n machineOpObserver,\n sandboxOperationObserver,\n sandboxRuntime,\n transientCodemodeEnvironment,\n agent,\n attachRunCredentialRenewal,\n attachGitCredentialRenewal,\n attachCodemodeTokenRenewal,\n throwIfWorkerShuttingDown,\n throwIfTurnCancelled,\n initialRunCredentialMaterial,\n sandboxCodemodeToken,\n media,\n toolResultSpill,\n connectionScope,\n codemodeAuthority,\n rigVersion,\n turnResources,\n });\n\n let companyBrainContributionReceiptRecorded = false;\n const recordCompanyBrainContributionReceiptOnce = (): void => {\n if (companyBrainContributionReceiptRecorded) return;\n companyBrainContributionReceiptRecorded = true;\n try {\n const companyBrainContributionReceipt = buildCompanyBrainContributionReceiptFor(\n modelVisibleSkillCatalogText,\n );\n eventing.companyBrainContextContributions = summarizeCompanyBrainContributions(\n companyBrainContributionReceipt,\n );\n recordCompanyBrainContributions(observability, companyBrainContributionReceipt);\n observability.info(\"model context contribution receipt\", {\n attemptId: companyBrainContributionReceipt.attemptId,\n turnId: companyBrainContributionReceipt.turnId,\n contextSelectionReceiptId: companyBrainContributionReceipt.contextSelectionReceiptId,\n sessionRole: companyBrainContributionReceipt.sessionRole,\n memoryPromptMode: companyBrainContributionReceipt.memoryPromptMode,\n instructionPolicySnapshotId:\n companyBrainContributionReceipt.instructionPolicySnapshotId,\n preferenceSnapshotId: companyBrainContributionReceipt.preferenceSnapshotId,\n companyProfileSnapshotId: companyBrainContributionReceipt.companyProfileSnapshotId,\n contributions: JSON.stringify(companyBrainContributionReceipt.contributions),\n });\n } catch {\n // Observability must never change model execution semantics.\n }\n };\n const postAgentCompaction = await runPostAgentCompaction({\n input,\n settings: capabilitySettings,\n db,\n bus,\n observability,\n cancellationSignal,\n control,\n attempt,\n billingState,\n eventing: wiredEventing,\n providerTurn,\n leases,\n media,\n claimedResult,\n claimedModelUsageSourceKeys,\n emittedModelUsageSourceKeys,\n modelUsageDispatchId,\n turn,\n session,\n turnExecutionPolicy,\n resolvedModel,\n workspaceAgentInstructions,\n workspaceGovernance,\n structuredWorkspacePolicyActive,\n workspaceMemory,\n rigVersion,\n rigName,\n compactionModelHistoryProjector,\n summarizeContextForCompaction,\n withProviderRequestContext,\n withCodexRemoteCompaction,\n remotePrefix,\n remoteCompactionRequester,\n publishCompactionLiveEvents,\n publishCompactionOutcomeEvents,\n compactionModeOptions,\n compactionOnlyTurn,\n compactionSummarizerFor,\n settleDeferredSteerAfterCompaction,\n agent,\n });\n if (\"exit\" in postAgentCompaction) return postAgentCompaction.exit;\n const { compactSummarizer } = postAgentCompaction.ok;\n\n recordTurnStartupPhase(observability, {\n phase: \"post_agent_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - postAgentPreparationStartedAt) / 1_000,\n });\n let fileMaterializationFailures: SandboxFileDownloadFailure[] = [];\n let fileDownloadsMaterializedForRun = false;\n if (\n sandboxState.resolvedSandbox &&\n sandboxState.setupBoxSession &&\n fileResourceDownloads.length > 0\n ) {\n const fileMaterializationStartedAt = performance.now();\n let fileMaterializationOutcome: \"completed\" | \"failed\" = \"completed\";\n let fileMaterializationCache: \"hit\" | \"miss\" = \"miss\";\n try {\n const boxInstanceId = sandboxState.resolvedSandbox.established.instanceId;\n // A successful transfer is durable for this exact filesystem instance.\n // Do not turn later model startup into an integrity scan. If an owner or\n // agent removes the file, it can be restored explicitly through the\n // existing Files MCP using the durable file id carried in model history.\n const alreadyMaterialized = await getMaterializedSandboxFileResources(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n expectedEpoch: sandboxState.resolvedSandbox.leaseEpoch,\n instanceId: boxInstanceId,\n });\n const downloadsToMaterialize = filterUnmaterializedSandboxFileDownloads(\n fileResourceDownloads,\n alreadyMaterialized,\n );\n if (downloadsToMaterialize.length === 0) {\n fileMaterializationCache = \"hit\";\n }\n const runAs = sandboxRunAs(runSettings);\n if (downloadsToMaterialize.length > 0) {\n const materialized = await runWorkspaceMutationForSandbox(\n sandboxState.resolvedSandbox,\n \"fileMaterialization\",\n async () =>\n await materializeSandboxFileDownloads(\n sandboxState.setupBoxSession as CodemodeTokenWriterSession,\n downloadsToMaterialize,\n {\n onRuntimeEvent: async (event) => {\n await eventing.publish!([{ type: event.type, payload: event.payload }], true);\n },\n ...(runAs ? { runAs } : {}),\n ...(eventing.toolCancellationFenceRef.current\n ? {\n commandRunner:\n eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(\n eventing.toolCancellationFenceRef.current,\n ),\n }\n : {}),\n },\n ),\n );\n fileMaterializationFailures = materialized.failures;\n fileMaterializationOutcome = sandboxFileMaterializationOutcome(materialized.failures);\n const failedFileIds = new Set(materialized.failures.map((failure) => failure.fileId));\n const succeededFileIds = downloadsToMaterialize\n .map((download) => download.fileId)\n .filter((fileId) => !failedFileIds.has(fileId));\n if (succeededFileIds.length > 0) {\n await markSandboxFileResourcesMaterialized(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n expectedEpoch: sandboxState.resolvedSandbox.leaseEpoch,\n instanceId: boxInstanceId,\n fileIds: succeededFileIds,\n });\n }\n }\n fileDownloadsMaterializedForRun = true;\n } catch (error) {\n fileMaterializationOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"file_materialization\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: fileMaterializationOutcome,\n durationSeconds: (performance.now() - fileMaterializationStartedAt) / 1_000,\n count: fileResourceDownloads.length,\n cache: fileMaterializationCache,\n });\n }\n } else {\n recordTurnStartupPhase(observability, {\n phase: \"file_materialization\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: 0,\n count: 0,\n });\n }\n const requiredVideoFileIds = new Set(requiredGeneratedVideoFiles.map((file) => file.fileId));\n const failedRequiredVideo = fileMaterializationFailures.find((failure) =>\n requiredVideoFileIds.has(failure.fileId),\n );\n if (failedRequiredVideo) {\n // Retention is already durable. A sandbox copy miss must not fail the\n // turn or replay generation; the File remains retrievable via Files MCP.\n observability.warn(\"Generated video sandbox materialization deferred\", {\n errorClass: \"SandboxFileDownloadFailure\",\n errorCode: \"generated_video_materialization_deferred\",\n origin: \"worker\",\n });\n }\n const unavailableSandboxFilesNote = sandboxFileDownloadFailureNote(\n fileMaterializationFailures,\n );\n return await runTurnStreamAttempt({\n input,\n settings: capabilitySettings,\n db,\n bus,\n runtime,\n objectStorage,\n observability,\n entitlements,\n startVideoGenerationWorkflow,\n cancellationSignal,\n runtimeCancellationSignal,\n activityContext,\n dispatchId,\n control,\n attempt,\n billingState,\n sandboxState,\n eventing: wiredEventing,\n providerTurn,\n leases,\n historySink,\n media,\n toolResultSpill,\n claimedResult,\n flushRuntimeBatcher,\n finalizeTurnOpStreamOps,\n runWorkspaceMutationForSandbox,\n throwIfWorkerShuttingDown,\n throwIfTurnCancelled,\n setLastInputTokensFenced,\n attachGitCredentialRenewal,\n attachCodemodeTokenRenewal,\n attachRunCredentialRenewal,\n withProviderRequestContext,\n withSessionTitleProviderRequestContext,\n publishCompactionLiveEvents,\n publishCompactionOutcomeEvents,\n recordCompanyBrainContributionReceiptOnce,\n modelCheckpointMemoryCollector,\n claimedModelUsageSourceKeys,\n emittedModelUsageSourceKeys,\n modelUsageDispatchId,\n workerPreparationStartedAt,\n fileDownloadsMaterializedForRun,\n unavailableSandboxFilesNote,\n runCredentialsNote,\n mcpAvailabilityNote,\n fileAuthoritySubjectId,\n activeSandboxBackend,\n groupBoxBackend,\n turnExecutionPolicy,\n turn,\n trigger,\n humanInputResume,\n attachPendingUpdatesAfterOpenSuffix,\n agent,\n resolvedModel,\n providerApi,\n runSettings,\n turnTools,\n generateSessionTitleInParallel,\n sessionTitlePrompt: session.initialMessage.trim() ? session.initialMessage : turn.prompt,\n compactSummarizer,\n settleDeferredSteerAfterCompaction,\n compactionModelHistoryProjector,\n generatedImageHistoryProjector,\n modelHistoryProjector,\n compactionModeOptions,\n initialRunCredentialMaterial,\n initialGitCredentials,\n sandboxEnvironment,\n sandboxCodemodeToken,\n sandboxCodemodeTokenExpiresAt,\n fileResourceDownloads,\n runCredentialResolver,\n videoGenerationAcceptancesByCallId,\n });\n } catch (error) {\n // Stop new external wait mutations before asynchronous failure\n // persistence. Do not drain here: the original failure/cancellation and\n // durable attempt fence retain authority over already-running calls.\n eventing.preparedTools?.inputWaitYield?.closeAdmission();\n return await settleTurnFailure({\n error,\n input,\n settings,\n db,\n bus,\n observability,\n wakeSessionWorkflow,\n cancellationSignal,\n sandboxRotationController,\n noteCancellationRequested,\n codexWorkspaceKey,\n control,\n attempt,\n billingState,\n eventing,\n providerTurn,\n leases,\n historySink,\n claimedResult,\n flushRuntimeBatcher,\n acknowledgeLostAttemptOwnership,\n acknowledgeRecoveryQuiescence,\n });\n } finally {\n await finalizeTurnAttempt({\n input,\n settings,\n db,\n bus,\n objectStorage,\n observability,\n wakeSessionWorkflow,\n signalSessionAttemptQuiesced,\n signalCodexCapacityWorkflow,\n cancellationSignal,\n sandboxResumeController,\n activityContext,\n activityStarted,\n activitySpan,\n dispatchId,\n noteCancellationRequested,\n machineOpObserver,\n leases,\n control,\n attempt,\n sandboxState,\n renewals,\n eventing,\n providerTurn,\n workspaceRefs,\n runWorkspaceMutationForSandbox,\n requireResolvedSandboxForMutation,\n stopLeaseHeartbeat,\n turnCompletionMemoryCollector,\n });\n }\n };\n}\n","// db-backed Codex token lifecycle for a turn: proactive refresh, single-flight\n// per credential instance, and permanent-failure status surfacing.\n//\n// The implementation now lives in @opengeni/db (packages/db/src/codex-token-resolver.ts)\n// so the API process can drive the SAME refreshing resolver for the P2 /wham/usage\n// quota-bar reads without duplicating the refresh-CAS / single-flight / RLS logic.\n// This module re-exports it for back-compat, keeping the agent-turn.ts call site\n// (buildCodexTokenResolver) unchanged.\nexport { buildCodexTokenResolver, type CodexAuthDeps } from \"@opengeni/db\";\n","/**\n * The activity lost ownership of its exact turn generation/attempt.\n *\n * This is an ordinary stale-writer outcome, not a Temporal cancellation. The\n * current owner or control transaction already holds authoritative state, so\n * the losing activity must stop locally without asking the workflow to settle\n * or fail the turn again.\n */\nexport class TurnAttemptFencedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TurnAttemptFencedError\";\n }\n}\n","import type {\n ModelContextContributionSource,\n ModelContextContributionSummary,\n PreferenceRegistrySnapshot,\n ResolvedCompanyProfileSnapshot,\n ResolvedWorkspaceInstructionPolicySnapshot,\n SandboxBackend,\n HistoricalMemoryPromptMode,\n} from \"@opengeni/contracts\";\nimport { composeRuntimeSkills, type RuntimeSkillActivation } from \"@opengeni/runtime\";\n\nexport type CompanyBrainContributionCategory =\n | \"mandatory_rule\"\n | \"skill_guide_descriptor\"\n | \"retrieved_knowledge\"\n | \"task_note\";\n\nexport type CompanyBrainContribution = Readonly<{\n category: CompanyBrainContributionCategory;\n source: ModelContextContributionSource;\n inclusionReason:\n | \"active_instruction_policy\"\n | \"legacy_instruction_fallback\"\n | \"active_preference_descriptor\"\n | \"active_company_profile_root\"\n | \"legacy_standing_working_set\"\n | \"authorized_skill_descriptor\";\n authorityScope: \"organization\" | \"workspace\" | \"user\" | \"session\";\n utf8Bytes: number;\n estimatedTokens: number;\n}>;\n\nexport function summarizeCompanyBrainContributions(\n receipt: CompanyBrainContributionReceipt,\n): readonly ModelContextContributionSummary[] {\n const bySource = new Map<ModelContextContributionSource, ModelContextContributionSummary>();\n for (const entry of receipt.contributions) {\n const current = bySource.get(entry.source);\n bySource.set(entry.source, {\n source: entry.source,\n items: (current?.items ?? 0) + 1,\n utf8Bytes: (current?.utf8Bytes ?? 0) + entry.utf8Bytes,\n estimatedTokens: (current?.estimatedTokens ?? 0) + entry.estimatedTokens,\n });\n }\n return Object.freeze([...bySource.values()].map((summary) => Object.freeze(summary)));\n}\n\nexport function modelVisibleCompanyBrainSkillActivations(\n sandboxBackend: SandboxBackend,\n skillActivations: readonly RuntimeSkillActivation[],\n): readonly RuntimeSkillActivation[] {\n return sandboxBackend === \"none\" ? [] : skillActivations;\n}\n\nexport type CompanyBrainContributionReceipt = Readonly<{\n contextSelectionReceiptId: string;\n attemptId: string;\n turnId: string;\n sessionRole: \"root\" | \"child\";\n memoryPromptMode: HistoricalMemoryPromptMode;\n instructionPolicySnapshotId: string;\n preferenceSnapshotId: string | null;\n companyProfileSnapshotId: string;\n contributions: readonly CompanyBrainContribution[];\n}>;\n\n/**\n * Build a content-free exact-attempt receipt for the Company Brain material\n * selected before inference. Token counts are deliberately estimates (UTF-8\n * bytes / 4); provider-accounted total input tokens remain the separate source\n * of truth for billing and context pressure.\n */\nexport function buildCompanyBrainContributionReceipt(input: {\n contextSelectionReceiptId: string;\n attemptId: string;\n turnId: string;\n nestedAgentDepth: number;\n memoryPromptMode: HistoricalMemoryPromptMode;\n instructionPolicy: ResolvedWorkspaceInstructionPolicySnapshot;\n workspaceAgentInstructions: string | null;\n preferences: PreferenceRegistrySnapshot | null;\n companyProfile: ResolvedCompanyProfileSnapshot;\n companyProfileIncluded: boolean;\n workspaceMemory: string | null;\n skillActivations: readonly RuntimeSkillActivation[];\n /** Exact already-bounded index text for server-backed reading, independent of compute. */\n skillCatalogText?: string;\n}): CompanyBrainContributionReceipt {\n const contributions: CompanyBrainContribution[] = [];\n for (const entry of input.instructionPolicy.entries) {\n contributions.push(\n contribution({\n category: \"mandatory_rule\",\n source: \"workspace_instruction_policy\",\n inclusionReason: \"active_instruction_policy\",\n authorityScope: \"workspace\",\n text: entry.content,\n }),\n );\n }\n if (input.instructionPolicy.entries.length === 0 && input.workspaceAgentInstructions) {\n contributions.push(\n contribution({\n category: \"mandatory_rule\",\n source: \"legacy_workspace_instructions\",\n inclusionReason: \"legacy_instruction_fallback\",\n authorityScope: \"workspace\",\n text: input.workspaceAgentInstructions,\n }),\n );\n }\n for (const descriptor of input.skillCatalogText !== undefined\n ? []\n : (input.preferences?.descriptors ?? [])) {\n contributions.push(\n contribution({\n category: \"skill_guide_descriptor\",\n source: \"preference_registry_descriptor\",\n inclusionReason: \"active_preference_descriptor\",\n authorityScope: descriptor.scope,\n text: JSON.stringify(descriptor),\n }),\n );\n }\n if (input.companyProfileIncluded && input.companyProfile.profile) {\n contributions.push(\n contribution({\n category: \"retrieved_knowledge\",\n source: \"company_profile\",\n inclusionReason: \"active_company_profile_root\",\n authorityScope: \"organization\",\n text: JSON.stringify(input.companyProfile.profile.profile),\n }),\n );\n }\n if (input.workspaceMemory?.trim()) {\n contributions.push(\n contribution({\n category: \"retrieved_knowledge\",\n source: \"legacy_memory_v1\",\n inclusionReason: \"legacy_standing_working_set\",\n authorityScope: \"workspace\",\n text: input.workspaceMemory,\n }),\n );\n }\n if (input.skillCatalogText)\n contributions.push(\n contribution({\n category: \"skill_guide_descriptor\",\n source: \"runtime_skill_catalog\",\n inclusionReason: \"authorized_skill_descriptor\",\n authorityScope: \"workspace\",\n text: input.skillCatalogText,\n }),\n );\n for (const descriptor of input.skillCatalogText !== undefined\n ? []\n : composeRuntimeSkills(input.skillActivations).configuredDescriptors) {\n contributions.push(\n contribution({\n category: \"skill_guide_descriptor\",\n source: \"runtime_skill_catalog\",\n inclusionReason: \"authorized_skill_descriptor\",\n authorityScope: descriptor.source === \"session\" ? \"session\" : \"workspace\",\n text: descriptor.description,\n }),\n );\n }\n return Object.freeze({\n contextSelectionReceiptId: input.contextSelectionReceiptId,\n attemptId: input.attemptId,\n turnId: input.turnId,\n sessionRole: input.nestedAgentDepth === 0 ? \"root\" : \"child\",\n memoryPromptMode: input.memoryPromptMode,\n instructionPolicySnapshotId: input.instructionPolicy.id,\n preferenceSnapshotId: input.preferences?.id ?? null,\n companyProfileSnapshotId: input.companyProfile.id,\n contributions: Object.freeze(contributions),\n });\n}\n\nfunction contribution(\n input: Omit<CompanyBrainContribution, \"utf8Bytes\" | \"estimatedTokens\"> & {\n text: string;\n },\n): CompanyBrainContribution {\n const utf8Bytes = Buffer.byteLength(input.text, \"utf8\");\n return Object.freeze({\n category: input.category,\n source: input.source,\n inclusionReason: input.inclusionReason,\n authorityScope: input.authorityScope,\n utf8Bytes,\n estimatedTokens: Math.ceil(utf8Bytes / 4),\n });\n}\n","import { createHash } from \"node:crypto\";\nimport {\n TOOL_RESULT_SPILL_MEDIA_TYPE,\n TOOL_RESULT_SPILL_MOUNT_PATH,\n toolResultSpillFilename,\n toolResultSpillSandboxPath,\n type AttemptToolResult as AttemptToolResultValue,\n type FileAsset,\n type ToolResultSpilledReceipt,\n} from \"@opengeni/contracts\";\nimport {\n completeFileUpload,\n getFile,\n getMaterializedSandboxFileResources,\n markSandboxFileResourcesMaterialized,\n prepareGeneratedWorkspaceFile,\n type Database,\n} from \"@opengeni/db\";\nimport type { Observability } from \"@opengeni/observability\";\nimport {\n materializeSandboxFileDownloads,\n sandboxRunAs,\n spilledModelToolResult,\n type CodemodeTokenWriterSession,\n type SandboxFileDownload,\n type TurnToolCancellationFence,\n} from \"@opengeni/runtime\";\nimport type { Settings } from \"@opengeni/config\";\nimport { type ObjectStorage } from \"@opengeni/storage\";\nimport { objectStorageForSandboxDownloads } from \"./file-resources\";\nimport type { ResumedTurnSandbox } from \"../../sandbox-resume\";\n\nconst UPLOAD_INTENT_TTL_MS = 60 * 60_000;\n\nexport type ToolResultSpillReceipt = ToolResultSpilledReceipt;\n\nexport type ToolResultSpillDeps = {\n db: Database;\n objectStorage: ObjectStorage | null;\n observability: Observability;\n accountId: string;\n workspaceId: string;\n attemptId: string;\n getModelRunSettings: () => Settings;\n getSandboxFileDownloadBackend: () => Settings[\"sandboxBackend\"];\n getPublish: () =>\n | ((events: Array<{ type: string; payload: unknown }>, immediate?: boolean) => Promise<unknown>)\n | null;\n toolCancellationFenceRef: { current: TurnToolCancellationFence | null };\n getResolvedSandbox: () => ResumedTurnSandbox | null;\n getSetupBoxSession: () => unknown;\n getSdkOwnedSandboxSession: () => unknown;\n getSandboxGroupId: () => string | null;\n runWorkspaceMutation: <T>(\n sandbox: ResumedTurnSandbox,\n operation: string,\n mutation: () => Promise<T>,\n ) => Promise<T>;\n};\n\nexport class ToolResultSpill {\n readonly receiptsCreatedThisTurn = new Map<string, ToolResultSpillReceipt>();\n private materializationCache: { instanceId: string; fileIds: Set<string> } | null = null;\n\n constructor(private readonly deps: ToolResultSpillDeps) {}\n\n spill = async (input: {\n operationId: string;\n result: AttemptToolResultValue;\n }): Promise<AttemptToolResultValue> => {\n const { objectStorage } = this.deps;\n if (!objectStorage) {\n throw new Error(\"Oversized tool-result spill requires configured object storage\");\n }\n const bytes = Buffer.from(JSON.stringify(input.result) ?? \"null\");\n const sha256 = createHash(\"sha256\").update(bytes).digest(\"hex\");\n const identity = toolResultSpillIdentity({\n workspaceId: this.deps.workspaceId,\n attemptId: this.deps.attemptId,\n operationId: input.operationId,\n });\n const filename = toolResultSpillFilename(input.operationId);\n const intendedSandboxPath = toolResultSpillSandboxPath(filename);\n const objectKey = `workspaces/${this.deps.workspaceId}/files/${identity.fileId}/tool-results/${filename}`;\n const prepared = await prepareGeneratedWorkspaceFile(this.deps.db, {\n accountId: this.deps.accountId,\n workspaceId: this.deps.workspaceId,\n fileId: identity.fileId,\n uploadId: identity.uploadId,\n filename,\n safeFilename: filename,\n contentType: TOOL_RESULT_SPILL_MEDIA_TYPE,\n sizeBytes: bytes.byteLength,\n sha256,\n bucket: objectStorage.bucket,\n objectKey,\n expiresAt: new Date(Date.now() + UPLOAD_INTENT_TTL_MS),\n });\n let file = prepared.file;\n if (file.status !== \"ready\") {\n if (!(await objectStorage.fileExists(file))) {\n await objectStorage.putObject({\n key: objectKey,\n contentType: TOOL_RESULT_SPILL_MEDIA_TYPE,\n body: bytes,\n sha256,\n });\n }\n file = await completeFileUpload(this.deps.db, this.deps.workspaceId, identity.uploadId);\n }\n const materialized = await this.materializeFile(file);\n const receipt: ToolResultSpillReceipt = {\n type: \"tool_result_spilled\",\n sandboxPath: materialized ? intendedSandboxPath : null,\n fileId: file.id,\n byteSize: file.sizeBytes,\n mediaType: TOOL_RESULT_SPILL_MEDIA_TYPE,\n };\n this.receiptsCreatedThisTurn.set(file.id, {\n ...receipt,\n sandboxPath: intendedSandboxPath,\n });\n return spilledModelToolResult(receipt);\n };\n\n materializeDeferred = async (): Promise<void> => {\n for (const receipt of this.receiptsCreatedThisTurn.values()) {\n const file = await getFile(this.deps.db, this.deps.workspaceId, receipt.fileId);\n if (file) await this.materializeFile(file);\n }\n };\n\n private async materializeFile(file: FileAsset): Promise<boolean> {\n if (this.deps.getSandboxFileDownloadBackend() === \"none\") return false;\n try {\n const sandbox = this.deps.getResolvedSandbox();\n const setupBoxSession = this.deps.getSetupBoxSession();\n if (sandbox && setupBoxSession) {\n return await this.materializeInSandbox(file, sandbox, setupBoxSession);\n }\n const sdkOwned = this.deps.getSdkOwnedSandboxSession();\n if (sdkOwned) {\n return await this.writeDownload(sdkOwned, await this.prepareDownload(file));\n }\n return false;\n } catch (error) {\n this.deps.observability.warn(\"Tool result spill sandbox materialization deferred\", {\n errorClass: error instanceof Error ? error.name : \"UnknownError\",\n errorCode: \"worker_operation_failed\",\n origin: \"worker\",\n });\n return false;\n }\n }\n\n private async materializeInSandbox(\n file: FileAsset,\n sandbox: ResumedTurnSandbox,\n session: unknown,\n ): Promise<boolean> {\n const download = await this.prepareDownload(file);\n if (this.materializationCache?.instanceId !== sandbox.established.instanceId) {\n const sandboxGroupId = this.deps.getSandboxGroupId();\n const fileIds = sandboxGroupId\n ? await getMaterializedSandboxFileResources(this.deps.db, {\n accountId: this.deps.accountId,\n workspaceId: this.deps.workspaceId,\n sandboxGroupId,\n expectedEpoch: sandbox.leaseEpoch,\n instanceId: sandbox.established.instanceId,\n })\n : new Set<string>();\n this.materializationCache = {\n instanceId: sandbox.established.instanceId,\n fileIds,\n };\n }\n if (this.materializationCache.fileIds.has(file.id)) return true;\n await this.deps.runWorkspaceMutation(sandbox, \"toolResultSpillMaterialization\", async () => {\n const ok = await this.writeDownload(session, download);\n if (!ok) throw new Error(\"Tool result spill sandbox copy failed\");\n });\n this.materializationCache.fileIds.add(file.id);\n const sandboxGroupId = this.deps.getSandboxGroupId();\n if (sandboxGroupId) {\n await markSandboxFileResourcesMaterialized(this.deps.db, {\n accountId: this.deps.accountId,\n workspaceId: this.deps.workspaceId,\n sandboxGroupId,\n expectedEpoch: sandbox.leaseEpoch,\n instanceId: sandbox.established.instanceId,\n fileIds: [file.id],\n });\n }\n return true;\n }\n\n private async prepareDownload(file: FileAsset): Promise<SandboxFileDownload> {\n const { objectStorage } = this.deps;\n if (!objectStorage) {\n throw new Error(\"Oversized tool-result spill requires configured object storage\");\n }\n const settings = this.deps.getModelRunSettings();\n const downloadStorage = objectStorageForSandboxDownloads(\n settings,\n objectStorage,\n this.deps.getSandboxFileDownloadBackend(),\n );\n const signed = await downloadStorage.createGetUrl({ key: file.objectKey });\n return {\n fileId: file.id,\n mountPath: TOOL_RESULT_SPILL_MOUNT_PATH,\n filename: file.safeFilename,\n url: signed.url,\n expiresAt: signed.expiresAt,\n sizeBytes: file.sizeBytes,\n ...(file.sha256 ? { sha256: file.sha256 } : {}),\n };\n }\n\n private async writeDownload(session: unknown, download: SandboxFileDownload): Promise<boolean> {\n const runAs = sandboxRunAs(this.deps.getModelRunSettings());\n const publish = this.deps.getPublish();\n const fence = this.deps.toolCancellationFenceRef.current;\n const materialized = await materializeSandboxFileDownloads(\n session as CodemodeTokenWriterSession,\n [download],\n {\n onRuntimeEvent: async (event) => {\n await publish?.([{ type: event.type, payload: event.payload }], true);\n },\n ...(runAs ? { runAs } : {}),\n ...(fence ? { commandRunner: fence.runSandboxCommand.bind(fence) } : {}),\n },\n );\n return materialized.failures.length === 0;\n }\n}\n\nexport function toolResultSpillIdentity(input: {\n workspaceId: string;\n attemptId: string;\n operationId: string;\n}): { fileId: string; uploadId: string } {\n const digest = createHash(\"sha256\")\n .update(\"opengeni-tool-result-spill-v1\\0\")\n .update(input.workspaceId)\n .update(\"\\0\")\n .update(input.attemptId)\n .update(\"\\0\")\n .update(input.operationId.toLowerCase())\n .digest(\"hex\");\n return {\n fileId: uuidFromDigest(digest, 0),\n uploadId: uuidFromDigest(digest, 16),\n };\n}\n\nfunction uuidFromDigest(digest: string, startByte: number): string {\n const bytes = Buffer.from(digest, \"hex\").subarray(startByte, startByte + 16);\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = bytes.toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","import {\n getFilesForSubject,\n requireFileForSubject,\n areGitHubRepositoriesAllowedForWorkspace,\n} from \"@opengeni/db\";\nimport { type SandboxFileDownload, type SandboxFileDownloadFailure } from \"@opengeni/runtime\";\nimport { type Settings } from \"@opengeni/config\";\nimport { mergeResourceRefs } from \"../common\";\nimport {\n gitHubTokenAuthorizationSelections,\n type GitHubTokenMintAuthorization,\n} from \"../environment\";\nimport type { TurnActivityServices as ActivityServices } from \"../types\";\nimport { createObjectStorage, type ObjectStorage } from \"@opengeni/storage\";\nimport { CAPABILITY_DESCRIPTORS, resourceMountPath, type ResourceRef } from \"@opengeni/contracts\";\n\nexport function filterUnmaterializedSandboxFileDownloads(\n downloads: SandboxFileDownload[],\n materializedFileIds: Set<string>,\n): SandboxFileDownload[] {\n if (downloads.length === 0 || materializedFileIds.size === 0) {\n return downloads;\n }\n return downloads.filter((download) => !materializedFileIds.has(download.fileId));\n}\n\nexport function runtimeResourcesForTurn(\n sessionResources: readonly ResourceRef[],\n currentTurnResources: readonly ResourceRef[],\n): ResourceRef[] {\n return mergeResourceRefs(\n sessionResources.filter((resource) => resource.kind !== \"file\"),\n [...currentTurnResources],\n );\n}\n\nexport function sandboxFileMaterializationOutcome(\n failures: readonly SandboxFileDownloadFailure[],\n): \"completed\" | \"failed\" {\n return failures.length === 0 ? \"completed\" : \"failed\";\n}\n\n/** Fixed-length one-way tenant correlation for metrics/alerts; never a raw id. */\nexport async function assertGitHubResourcesRemainAuthorized(\n db: Parameters<typeof areGitHubRepositoriesAllowedForWorkspace>[0],\n workspaceId: string,\n resources: ResourceRef[],\n authorize?: GitHubTokenMintAuthorization,\n): Promise<void> {\n // Must check exactly what sandboxEnvironmentForRun would mint a token for,\n // so the selection is derived from the same extraction as the mint path.\n for (const selection of gitHubTokenAuthorizationSelections(resources)) {\n if (authorize) {\n await authorize(selection);\n } else {\n await assertGitHubTokenMintSelectionAuthorized(\n db,\n workspaceId,\n selection.installationId,\n selection.repositoryIds,\n );\n }\n }\n}\n\nexport async function assertFileResourcesRemainAuthorized(\n db: ActivityServices[\"db\"],\n accountId: string,\n workspaceId: string,\n subjectId: string | null,\n resources: ResourceRef[],\n): Promise<void> {\n const fileIds = resources.flatMap((resource) =>\n resource.kind === \"file\" ? [resource.fileId] : [],\n );\n if (fileIds.length === 0) return;\n const authorized = await getFilesForSubject(db, {\n accountId,\n workspaceId,\n subjectId,\n fileIds,\n });\n if (authorized.length !== new Set(fileIds).size) {\n throw new Error(\"One or more file resources are unavailable or no longer authorized\");\n }\n}\n\nexport async function assertGitHubTokenMintSelectionAuthorized(\n db: Parameters<typeof areGitHubRepositoriesAllowedForWorkspace>[0],\n workspaceId: string,\n installationId: number,\n repositoryIds: number[],\n): Promise<void> {\n if (\n !(await areGitHubRepositoriesAllowedForWorkspace(\n db,\n workspaceId,\n installationId,\n repositoryIds,\n ))\n ) {\n throw new Error(\n \"This workspace no longer authorizes one or more GitHub repositories attached to the session\",\n );\n }\n}\n\n/**\n * True when the error is transient upstream backpressure — a model-provider 5xx,\n * a \"server had a bad minute\" body, or a dropped/again-able network connection —\n * rather than a request the session got wrong. These are safe to recover as a new\n * fenced attempt of the SAME turn after PROVIDER_BACKPRESSURE_DELAY_MS. Durable\n * tool results are preserved and ambiguous in-flight effects are closed before\n * the new attempt, independent of whether the session has an active goal.\n *\n * This is the classification gap that hard-failed a fleet of prod sessions during a\n * provider degradation window: their errors (\"Our servers are currently overloaded\",\n * the generic 500 \"An error occurred while processing your request\", \"Connection\n * error\") carried no retryable marker and fell through to a terminal session.failed.\n *\n * HTTP status is authoritative when present — EVERY 5xx is a server-side failure that\n * is safe to retry, while 4xx (validation, auth, 404) is a request fault that must\n * still hard-fail. The code/message matches are the fallback for network faults and\n * SDK-rethrown bare Errors that carry no status. A ChatGPT/Codex usage cap (a 429\n * that will NOT clear on retry) is classified and returned BEFORE this in\n * agentRunFailurePayload, so it never reaches here.\n */\nexport async function sandboxFileDownloadsForRun(\n settings: Settings,\n db: ActivityServices[\"db\"],\n objectStorage: ObjectStorage | null,\n accountId: string,\n workspaceId: string,\n subjectId: string | null,\n resources: ResourceRef[],\n activeSandboxBackend: Settings[\"sandboxBackend\"] = settings.sandboxBackend,\n): Promise<SandboxFileDownload[]> {\n if (!requiresSignedFileResourceDownloads(settings, activeSandboxBackend)) {\n return [];\n }\n const fileResources = resources.filter(\n (resource): resource is Extract<ResourceRef, { kind: \"file\" }> => resource.kind === \"file\",\n );\n if (fileResources.length === 0) {\n return [];\n }\n if (!objectStorage) {\n throw new Error(\n `${settings.objectStorageBackend} file resources require configured object storage`,\n );\n }\n const downloadStorage = objectStorageForSandboxDownloads(\n settings,\n objectStorage,\n activeSandboxBackend,\n );\n const downloads: SandboxFileDownload[] = [];\n for (const resource of fileResources) {\n const file = await requireFileForSubject(db, {\n accountId,\n workspaceId,\n subjectId,\n fileId: resource.fileId,\n });\n const url = await downloadStorage.createGetUrl({ key: file.objectKey });\n downloads.push({\n fileId: file.id,\n mountPath: resourceMountPath(resource),\n filename: file.safeFilename,\n url: url.url,\n expiresAt: url.expiresAt,\n sizeBytes: file.sizeBytes,\n ...(file.sha256 ? { sha256: file.sha256 } : {}),\n });\n }\n return downloads;\n}\n\nexport function requiresSignedFileResourceDownloads(\n settings: Settings,\n activeSandboxBackend: Settings[\"sandboxBackend\"] = settings.sandboxBackend,\n): boolean {\n if (activeSandboxBackend === \"none\") {\n return false;\n }\n // A selfhosted machine (bring-your-own-compute) can NEVER mount ANY object store\n // — it is a remote user machine reached only over NATS, so file resources are\n // ALWAYS delivered by exec-curling a pre-signed URL onto it. Without this a\n // machine-home turn (sandbox_backend \"selfhosted\") would silently drop file\n // resources on an azure-blob / s3-compatible store (nativeBucketMount=false),\n // a regression from the pre-honest-label path where the same turn ran home=modal\n // and modal's descriptor forced signed downloads.\n if (activeSandboxBackend === \"selfhosted\") {\n return true;\n }\n // A nativeBucketMount backend (modal) cannot mount Azure Blob entries, so it\n // needs pre-signed downloads for that store. Keying on the descriptor (not the\n // \"modal\" literal) keeps this correct as bucket-mount backends are added.\n const nativeBucketMount = CAPABILITY_DESCRIPTORS[activeSandboxBackend].nativeBucketMount;\n return (\n (activeSandboxBackend === \"docker\" && settings.objectStorageBackend === \"s3-compatible\") ||\n settings.objectStorageBackend === \"aws-s3\" ||\n settings.objectStorageBackend === \"gcs\" ||\n (nativeBucketMount && settings.objectStorageBackend === \"azure-blob\")\n );\n}\n\nexport function objectStorageForSandboxDownloads(\n settings: Settings,\n objectStorage: ObjectStorage,\n activeSandboxBackend: Settings[\"sandboxBackend\"] = settings.sandboxBackend,\n): ObjectStorage {\n // Connected Machines are not on the Docker compose network. Sign with the\n // ambient public endpoint; never rewrite to OPENGENI_OBJECT_STORAGE_SANDBOX_ENDPOINT.\n if (activeSandboxBackend === \"selfhosted\") {\n return objectStorage;\n }\n if (settings.objectStorageBackend !== \"s3-compatible\" || !settings.objectStorageSandboxEndpoint) {\n return objectStorage;\n }\n return (\n createObjectStorage({\n ...settings,\n objectStorageEndpoint: settings.objectStorageSandboxEndpoint,\n }) ?? objectStorage\n );\n}\n","import {\n applyGitAuthPointerEnvironment,\n codemodeWorkspaceUrl,\n stableSandboxEnvironmentForRun,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n gitCredentialBindingIdForRepository,\n gitCredentialProviderForRepository,\n gitRemoteIdentity,\n type ConnectionCredentialsPort,\n type GitCredentialProvider,\n type GitCredentialRepositoryRef,\n type GitCredentialTransport,\n type GitCredentials,\n type ResourceRef,\n type SandboxSecrets,\n type SessionTurn,\n type TurnInitiator,\n type TurnInitiatorContext,\n} from \"@opengeni/contracts\";\nimport { personalGitHubRepositoryResources } from \"@opengeni/core\";\nimport { mintSandboxCodemodeToken, type SandboxCodemodeAuthority } from \"@opengeni/runtime/sandbox\";\nimport {\n loadVariableSetForRun as loadWorkspaceEnvironmentForRunFromDb,\n type Database,\n type VariableSetForRun as WorkspaceEnvironmentForRun,\n} from \"@opengeni/db\";\nimport { createGitHubAppInstallationTokenWithExpiry, githubAppBotIdentity } from \"@opengeni/github\";\n\n// Re-exported from the shared @opengeni/db leaf (moved there so the API-direct\n// attach paths can load the SAME decrypted workspace environment the turn\n// declares — keeping the box-manifest env and agent-manifest env identical).\n// Existing worker import sites (agent-turn) continue importing from here.\nexport {\n loadWorkspaceEnvironmentForRunFromDb as loadWorkspaceEnvironmentForRun,\n type WorkspaceEnvironmentForRun,\n};\n\n// §7.6 connection-credential provider — the run's workspace identity, threaded so the connection-credential\n// provider can be called with the run's tenant context AND so the workspace-scope cross-check\n// cross-check has the run's workspace to assert the provider's echo against.\nexport type ConnectionScope = {\n accountId: string;\n workspaceId: string;\n};\n\nexport type VariableSetCredentialAuthority = {\n sessionId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n initiator: TurnInitiator;\n initiatingHumanSubjectId: string | null;\n};\n\nexport type GitTokenSeeds = Partial<Record<GitCredentialProvider, string>>;\nexport type GitTokenExpiries = Partial<Record<GitCredentialProvider, string>>;\nexport type GitCredentialBindingSeed = {\n credentialBindingId: string;\n provider: GitCredentialProvider;\n token: string;\n transport?: GitCredentialTransport;\n expiresAt?: string;\n providerBindingCount?: number;\n};\nexport type MintedRunGitCredentials = {\n bindings: GitCredentialBindingSeed[];\n // Compatibility views exist only when a provider has exactly one binding.\n // A multi-binding provider intentionally has no provider-level alias.\n gitTokens: GitTokenSeeds;\n expiresAt: GitTokenExpiries;\n};\n\nexport type GitHubTokenMintSelection = {\n credentialBindingId: string;\n installationId: number;\n repositoryIds: number[];\n repositoryRefs: GitCredentialRepositoryRef[];\n};\nexport type GitHubTokenMintAuthorization = (selection: GitHubTokenMintSelection) => Promise<void>;\n\nexport {\n CODEMODE_TOKEN_TTL_SECONDS,\n mintSandboxCodemodeToken,\n type MintedSandboxCodemodeToken,\n type SandboxCodemodeAuthority,\n} from \"@opengeni/runtime/sandbox\";\n\nexport type GitCredentialAuthority = {\n sessionId: string;\n rootSessionId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n initiator: TurnInitiator;\n initiatorContext: TurnInitiatorContext;\n};\n\nexport function gitCredentialAuthorityForTurn(input: {\n sessionId: string;\n rootSessionId: string;\n attemptId: string;\n turn: Pick<SessionTurn, \"id\" | \"executionGeneration\" | \"initiator\" | \"initiatorContext\">;\n}): GitCredentialAuthority {\n return {\n sessionId: input.sessionId,\n rootSessionId: input.rootSessionId,\n turnId: input.turn.id,\n attemptId: input.attemptId,\n executionGeneration: input.turn.executionGeneration,\n initiator: input.turn.initiator,\n initiatorContext: input.turn.initiatorContext,\n };\n}\n\ntype RunGitCredentialOptions = {\n scope?: ConnectionScope;\n authority?: GitCredentialAuthority;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n personalGitHubCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n authorizeGitHubTokenMint?: GitHubTokenMintAuthorization;\n};\n\n// §7.6 connection-credential provider — load the run's workspace environment, delegating the DECRYPT to a\n// host `sandboxSecrets` provider when one is bound (the host owns the secret\n// vault + encryption key in embedded/separate topologies) and otherwise running\n// today's local `environmentsEncryptionKeyBytes`-keyed decrypt byte-for-byte.\n//\n// Unattached runs (environmentId === null) short-circuit identically in BOTH\n// modes: zero DB/provider work, returns null. When a provider IS bound it owns\n// the decrypt end-to-end (it reads the host's own store), so the local DB read\n// is skipped — the provider is the sole source of truth for that leg.\nexport async function loadWorkspaceEnvironmentForRunWithCredentials(\n db: Database,\n settings: Settings,\n scope: ConnectionScope,\n environmentId: string | null,\n authority: VariableSetCredentialAuthority,\n sandboxSecrets?: ConnectionCredentialsPort[\"sandboxSecrets\"],\n options: {\n /**\n * Exact accepted scheduled-occurrence generation for this Variable Set,\n * resolved by the caller from the immutable run snapshot; null/omitted for\n * ordinary live turns.\n */\n expectedGeneration?: number | null;\n } = {},\n): Promise<WorkspaceEnvironmentForRun | null> {\n if (!sandboxSecrets) {\n return loadWorkspaceEnvironmentForRunFromDb(db, settings, {\n ...scope,\n variableSetId: environmentId,\n authority: {\n kind: \"agent_attempt\",\n subjectId: authority.initiatingHumanSubjectId ?? authority.initiator.subjectId,\n ...authority,\n },\n });\n }\n if (!environmentId) {\n return null;\n }\n const expectedGeneration = options.expectedGeneration ?? null;\n const secrets: SandboxSecrets = await sandboxSecrets({\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n ...authority,\n variableSetId: environmentId,\n ...(expectedGeneration === null ? {} : { expectedGeneration }),\n });\n // workspace-scope cross-check: the provider must echo THIS run's workspace before we apply its\n // decrypted values into the sandbox.\n assertWorkspaceEcho(\"sandboxSecrets\", scope, secrets.workspaceId);\n if (\n secrets.accountId !== scope.accountId ||\n secrets.sessionId !== authority.sessionId ||\n secrets.turnId !== authority.turnId ||\n secrets.attemptId !== authority.attemptId ||\n secrets.executionGeneration !== authority.executionGeneration ||\n secrets.variableSetId !== environmentId ||\n // A scheduled attempt materializes only the exact accepted generation:\n // the host must echo it and return that generation's values.\n (expectedGeneration !== null &&\n (secrets.expectedGeneration !== expectedGeneration ||\n secrets.generation !== expectedGeneration))\n ) {\n throw new Error(\"connection-credential provider (sandboxSecrets) returned stale authority\");\n }\n return {\n id: secrets.id ?? environmentId,\n name: secrets.name ?? environmentId,\n description: secrets.description ?? null,\n scope: secrets.scope,\n generation: secrets.generation,\n values: secrets.values,\n };\n}\n\n// Workspace-scope cross-check. A credential provider echoes the workspace it scoped\n// the credential to; we ASSERT it equals the run's workspace BEFORE the caller\n// injects the credential. A host mapping bug returning tenant B's creds for a\n// tenant-A run hard-throws here instead of landing tenant B's token in tenant\n// A's sandbox. Account/workspace ids only in the message (never the credential).\nfunction assertWorkspaceEcho(\n kind: string,\n scope: ConnectionScope,\n echoedWorkspaceId: string,\n): void {\n if (echoedWorkspaceId !== scope.workspaceId) {\n throw new Error(\n `connection-credential provider (${kind}) scoped to workspace ${echoedWorkspaceId} but the run is workspace ${scope.workspaceId}`,\n );\n }\n}\n\nexport async function sandboxEnvironmentForRun(\n settings: Settings,\n resources: ResourceRef[],\n workspaceEnvironment: Record<string, string> = {},\n // §7.6 connection-credential provider - optional host git-credential provider + the run scope it needs\n // (unset, the standalone default → self-mint from `settings` byte-for-byte).\n // `skipGitHubToken` (Stage D): a connected-machine turn skips the inert platform\n // token mint entirely and returns the stable base env unchanged. `deferGitHubToken`\n // is the lazy CLOUD path: apply stable git-auth pointers now, mint only the token\n // value later. `= {}` default so the non-optional reads below are safe.\n options: RunGitCredentialOptions & {\n skipGitHubToken?: boolean;\n /**\n * Codemode credential delivery for this attempt. Managed sandboxes receive\n * stable URL/file pointers in their manifest and the bearer through the\n * lifecycle file writer. Connected Machines receive no manifest pointers;\n * the worker injects the minted bearer only into exact exec requests.\n */\n codemodeDelivery?: \"managed_file\" | \"transient_exec\" | \"none\";\n deferGitHubToken?: boolean;\n codemodeAuthority?: SandboxCodemodeAuthority;\n } = {},\n): Promise<{\n environment: Record<string, string>;\n gitToken?: string;\n gitTokens?: GitTokenSeeds;\n gitTokenExpiresAt?: GitTokenExpiries;\n gitCredentialBindings?: GitCredentialBindingSeed[];\n codemodeToken?: string;\n codemodeTokenExpiresAt?: Date;\n}> {\n // Precedence: deployment allowlist < git identity < workspace environment\n // < backend-aware HOME (the STABLE base, shared with the API-direct attach\n // paths via stableSandboxEnvironmentForRun) < platform run-scoped git auth\n // (applied below, always last). Reserved name validation at write time prevents\n // workspace values from colliding with the platform-managed entries.\n //\n // TOKEN-BROKER (B1): run-scoped git provider tokens are NO LONGER layered into\n // the box/agent MANIFEST env (no GH_TOKEN/GITHUB_TOKEN/GITLAB_TOKEN/\n // AZURE_DEVOPS_EXT_PAT/GIT_CONFIG_* extraheader). They are minted once per turn\n // and returned separately as provider token seeds; the caller threads them\n // OFF-MANIFEST as clone-seed exec env vars so the clone hook writes stable token\n // files. The manifest carries only stable pointers (GIT_ASKPASS,\n // GIT_TERMINAL_PROMPT, identity, OPENGENI_GIT_CREDENTIALS_DIR, and\n // OPENGENI_GIT_TOKEN_FILE), so token VALUES never ride the manifest and the SDK's\n // per-turn provided-session env delta stays empty even though tokens rotate.\n // GitHub keeps the legacy `gitToken`/OPENGENI_GIT_TOKEN_FILE alias. The worker\n // proactively renews every selected provider behind these stable pointers.\n const stableOptions = options.scope ? { workspaceId: options.scope.workspaceId } : {};\n const environment = stableSandboxEnvironmentForRun(settings, workspaceEnvironment, stableOptions);\n const codemodeDelivery = options.codemodeDelivery ?? \"managed_file\";\n // Connected Machines keep their machine-wide environment untouched. Their\n // URL, package hint, and direct bearer are projected only onto an exact child\n // exec request by SelfhostedSession, never into the manifest or filesystem.\n if (codemodeDelivery !== \"managed_file\") {\n delete environment.OPENGENI_CODEMODE_URL;\n delete environment.OPENGENI_CODEMODE_TOKEN_FILE;\n delete environment.OPENGENI_OGTOOL_PACKAGE_SPEC;\n }\n const codemodeScope = options.scope;\n const codemodeToken =\n codemodeDelivery !== \"none\" && codemodeScope && options.codemodeAuthority\n ? await mintSandboxCodemodeToken(settings, codemodeScope, options.codemodeAuthority)\n : undefined;\n if (codemodeDelivery === \"managed_file\" && codemodeToken && codemodeScope) {\n environment.OPENGENI_CODEMODE_URL ??= codemodeWorkspaceUrl(settings, codemodeScope.workspaceId);\n }\n const selections = gitCredentialSelections(resources);\n // NO-TOKEN SKIP (Stage D, change B): when the turn's EFFECTIVE compute backend is\n // a connected machine (selfhosted), platform git provider tokens are INERT: exec\n // routes over NATS to the user's machine, which uses ITS OWN git credentials, and\n // the box those tokens would auth is never created. So skip the token mint entirely\n // and return the STABLE base env (no gitToken/gitTokens). Env-\n // parity holds: the SAME base object still feeds buildManifest + the SelfhostedSession\n // manifest, so the SDK's per-turn provided-session env delta stays empty\n // (validateNoEnvironmentDelta). The API-direct viewer attach path already drops the\n // token under this exact contract — proof a box runs fine without it.\n if (selections.length === 0 || options.skipGitHubToken) {\n return {\n environment,\n ...(codemodeToken\n ? {\n codemodeToken: codemodeToken.token,\n codemodeTokenExpiresAt: codemodeToken.expiresAt,\n }\n : {}),\n };\n }\n if (options.deferGitHubToken) {\n applyGitAuthPointerEnvironment(\n environment,\n await resolveRunGitIdentityWithSelections(settings, selections, options),\n );\n return {\n environment,\n ...(codemodeToken\n ? {\n codemodeToken: codemodeToken.token,\n codemodeTokenExpiresAt: codemodeToken.expiresAt,\n }\n : {}),\n };\n }\n // Run-scoped sandbox preparation for repository resources. GitHub retains the\n // legacy request shape and standalone self-mint path. Non-GitHub providers are\n // host-brokered only: without a `gitCredentials` port there is no token value\n // to seed, and the runtime wrappers degrade to passthrough.\n const minted = await mintRunGitTokensWithIdentity(settings, selections, options);\n // TOKEN-BROKER (B2): the askpass helper is PROVISIONED AT SETUP (runtime) into a\n // per-box, user-writable path in the SAME dir as the token file, instead of a\n // baked image script at /usr/local/bin/opengeni-git-askpass. The clone-hook seed\n // block writes both the token file AND this askpass script before the fetch, so\n // git auth becomes correct on ANY box image (including pre-existing warm boxes on\n // their next turn's clone hook) — no product image needs to carry the askpass.\n // The pointer layer is the SHARED config helper so every API-direct attach\n // surface (viewer attach, channel-A) declares the IDENTICAL env when it\n // cold-creates the box for a repo-attached session — an attach-warmed box\n // missing these keys kills the next repo turn on the SDK's manifest-env guard.\n applyGitAuthPointerEnvironment(environment, minted.identity);\n return {\n environment,\n ...(minted.gitTokens.github ? { gitToken: minted.gitTokens.github } : {}),\n ...(Object.keys(minted.gitTokens).length > 0 ? { gitTokens: minted.gitTokens } : {}),\n ...(Object.keys(minted.expiresAt).length > 0 ? { gitTokenExpiresAt: minted.expiresAt } : {}),\n ...(minted.bindings.length > 0 ? { gitCredentialBindings: minted.bindings } : {}),\n ...(codemodeToken\n ? {\n codemodeToken: codemodeToken.token,\n codemodeTokenExpiresAt: codemodeToken.expiresAt,\n }\n : {}),\n };\n}\n\nexport async function mintRunGitCredentials(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<MintedRunGitCredentials | undefined> {\n const selections = gitCredentialSelections(resources);\n if (selections.length === 0) {\n return undefined;\n }\n const minted = await mintRunGitTokensWithIdentity(settings, selections, options);\n return minted.bindings.length > 0\n ? {\n bindings: minted.bindings,\n gitTokens: minted.gitTokens,\n expiresAt: minted.expiresAt,\n }\n : undefined;\n}\n\nexport async function mintRunGitCredentialBinding(\n settings: Settings,\n resources: ResourceRef[],\n provider: GitCredentialProvider,\n credentialBindingId: string,\n options: RunGitCredentialOptions = {},\n): Promise<GitCredentialBindingSeed | undefined> {\n const selections = gitCredentialSelections(resources);\n const selection = selections.find(\n (candidate) =>\n candidate.provider === provider && candidate.credentialBindingId === credentialBindingId,\n );\n if (!selection) {\n return undefined;\n }\n const minted = await mintRunGitTokensWithIdentity(settings, [selection], options);\n const binding = minted.bindings[0];\n if (binding) {\n binding.providerBindingCount = selections.filter(\n (candidate) => candidate.provider === selection.provider,\n ).length;\n }\n return binding;\n}\n\nexport async function mintRunGitTokens(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<GitTokenSeeds | undefined> {\n const tokens = (await mintRunGitCredentials(settings, resources, options))?.gitTokens;\n return tokens && Object.keys(tokens).length > 0 ? tokens : undefined;\n}\n\nexport async function mintRunGitToken(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<string | undefined> {\n return (await mintRunGitTokens(settings, resources, options))?.github;\n}\n\nexport async function resolveRunGitIdentity(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<{ name: string; email: string } | null> {\n const selections = gitCredentialSelections(resources);\n if (selections.length === 0) {\n return null;\n }\n return await resolveRunGitIdentityWithSelections(settings, selections, options);\n}\n\nasync function mintRunGitTokensWithIdentity(\n settings: Settings,\n selections: GitCredentialSelection[],\n options: RunGitCredentialOptions,\n): Promise<{\n bindings: GitCredentialBindingSeed[];\n gitTokens: GitTokenSeeds;\n expiresAt: GitTokenExpiries;\n identity: { name: string; email: string } | null;\n}> {\n const bindings: GitCredentialBindingSeed[] = [];\n let identity: { name: string; email: string } | null = null;\n for (const selection of selections) {\n let token: string | null = null;\n let transport: GitCredentialTransport | undefined;\n let tokenExpiresAt: string | undefined;\n if (\n selection.provider === \"github\" &&\n selection.installationId > 0 &&\n selection.repositoryIds.length > 0\n ) {\n // This callback belongs immediately next to the side effect. Turn startup\n // performs its own admission check, but lazy provisioning and proactive\n // renewal can happen much later in an intentionally unbounded run. Recheck\n // the current workspace binding before every host-brokered or built-in\n // GitHub installation-token mint.\n await options.authorizeGitHubTokenMint?.({\n credentialBindingId: selection.credentialBindingId,\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n repositoryRefs: selection.repositoryRefs,\n });\n }\n const gitCredentials = credentialsForSelection(options, selection);\n assertPersonalGitHubConsumerAvailable(selection, gitCredentials, options.scope);\n if (gitCredentials && options.scope) {\n const request = gitCredentialsRequestForSelection(\n options.scope,\n requireGitCredentialAuthority(options),\n selection,\n \"token\",\n );\n const minted: GitCredentials = await gitCredentials(request);\n // workspace-scope cross-check: assert the provider scoped the token to THIS run's workspace\n // before accepting the token for clone seeding.\n assertWorkspaceEcho(\"gitCredentials\", options.scope, minted.workspaceId);\n assertGitCredentialBindingEcho(selection, request, minted);\n if (!minted.token) {\n throw new Error(\n \"connection-credential provider (gitCredentials) did not return a token for a token request\",\n );\n }\n token = minted.token;\n transport = validatedGitCredentialTransport(selection, minted);\n tokenExpiresAt = minted.expiresAt\n ? validatedGitCredentialExpiry(selection.provider, minted.expiresAt)\n : undefined;\n if (minted.identity) {\n identity = mergeGitIdentity(identity, minted.identity);\n } else if (selection.provider === \"github\") {\n identity = mergeGitIdentity(identity, githubAppBotIdentity(settings));\n }\n } else if (selection.provider === \"github\" && selection.installationId > 0) {\n const minted = await createGitHubAppInstallationTokenWithExpiry(settings, {\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n });\n token = minted.token;\n tokenExpiresAt = minted.expiresAt\n ? validatedGitCredentialExpiry(\"github\", minted.expiresAt)\n : undefined;\n identity = mergeGitIdentity(identity, githubAppBotIdentity(settings));\n }\n if (token) {\n bindings.push({\n credentialBindingId: selection.credentialBindingId,\n provider: selection.provider,\n token,\n ...(transport ? { transport } : {}),\n ...(tokenExpiresAt ? { expiresAt: tokenExpiresAt } : {}),\n });\n }\n }\n const gitTokens: GitTokenSeeds = {};\n const expiresAt: GitTokenExpiries = {};\n const counts = new Map<GitCredentialProvider, number>();\n for (const binding of bindings) {\n counts.set(binding.provider, (counts.get(binding.provider) ?? 0) + 1);\n }\n for (const binding of bindings) {\n binding.providerBindingCount = counts.get(binding.provider) ?? 1;\n if (binding.transport?.kind === \"http_broker\") continue;\n if (counts.get(binding.provider) !== 1) continue;\n gitTokens[binding.provider] = binding.token;\n if (binding.expiresAt) expiresAt[binding.provider] = binding.expiresAt;\n }\n return { bindings, gitTokens, expiresAt, identity };\n}\n\nfunction validatedGitCredentialExpiry(provider: GitCredentialProvider, value: string): string {\n const timestamp = Date.parse(value);\n if (!Number.isFinite(timestamp)) {\n throw new Error(`connection-credential provider (${provider}) returned an invalid expiresAt`);\n }\n return new Date(timestamp).toISOString();\n}\n\nconst MAX_GIT_HTTP_BROKER_ROUTES = 256;\nconst MAX_GIT_HTTP_BROKER_URI_LENGTH = 4_096;\n\nfunction validatedGitCredentialTransport(\n selection: GitCredentialSelection,\n minted: GitCredentials,\n): GitCredentialTransport | undefined {\n const transport = minted.transport;\n if (!transport) return undefined;\n\n if (\n typeof transport !== \"object\" ||\n transport.kind !== \"http_broker\" ||\n !Array.isArray(transport.repositories)\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git credential transport`,\n );\n }\n const requestedUris = new Set(selection.repositoryRefs.map((repository) => repository.uri));\n if (\n requestedUris.size === 0 ||\n requestedUris.size > MAX_GIT_HTTP_BROKER_ROUTES ||\n transport.repositories.length !== requestedUris.size\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an incomplete Git HTTP broker route set`,\n );\n }\n\n const echoedUris = new Set<string>();\n const brokerUris = new Set<string>();\n const repositories = transport.repositories.map((route) => {\n if (\n !route ||\n typeof route !== \"object\" ||\n typeof route.repositoryUri !== \"string\" ||\n typeof route.brokerUri !== \"string\"\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker route`,\n );\n }\n if (!requestedUris.has(route.repositoryUri) || echoedUris.has(route.repositoryUri)) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an unexpected Git HTTP broker repository`,\n );\n }\n echoedUris.add(route.repositoryUri);\n if (\n route.brokerUri.length === 0 ||\n route.brokerUri.length > MAX_GIT_HTTP_BROKER_URI_LENGTH ||\n route.brokerUri.trim() !== route.brokerUri\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker URI`,\n );\n }\n let brokerUrl: URL;\n try {\n brokerUrl = new URL(route.brokerUri);\n } catch {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker URI`,\n );\n }\n if (\n brokerUrl.protocol !== \"https:\" ||\n brokerUrl.username ||\n brokerUrl.password ||\n brokerUrl.search ||\n brokerUrl.hash ||\n brokerUris.has(brokerUrl.href) ||\n brokerUrl.href === route.repositoryUri\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an unsafe Git HTTP broker URI`,\n );\n }\n brokerUris.add(brokerUrl.href);\n return {\n repositoryUri: route.repositoryUri,\n brokerUri: brokerUrl.href,\n };\n });\n\n if ([...requestedUris].some((uri) => !echoedUris.has(uri))) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an incomplete Git HTTP broker route set`,\n );\n }\n return { kind: \"http_broker\", repositories };\n}\n\nexport function assertGitCredentialRenewalTransportUnchanged(\n initial: GitCredentialBindingSeed,\n renewed: GitCredentialBindingSeed,\n): void {\n if (!initial.transport && !renewed.transport) return;\n if (\n !initial.transport ||\n !renewed.transport ||\n initial.transport.kind !== renewed.transport.kind\n ) {\n throw new Error(\n `renewed ${initial.provider} credential changed transport for binding ${initial.credentialBindingId}`,\n );\n }\n const routeKey = (route: { repositoryUri: string; brokerUri: string }) =>\n `${route.repositoryUri}\\u0000${route.brokerUri}`;\n const initialRoutes = initial.transport.repositories.map(routeKey).sort();\n const renewedRoutes = renewed.transport.repositories.map(routeKey).sort();\n if (\n initialRoutes.length !== renewedRoutes.length ||\n initialRoutes.some((route, index) => route !== renewedRoutes[index])\n ) {\n throw new Error(\n `renewed ${initial.provider} credential changed Git HTTP broker routes for binding ${initial.credentialBindingId}`,\n );\n }\n}\n\nasync function resolveRunGitIdentityWithSelections(\n settings: Settings,\n selections: GitCredentialSelection[],\n options: RunGitCredentialOptions,\n): Promise<{ name: string; email: string } | null> {\n let identity: { name: string; email: string } | null = null;\n for (const selection of selections) {\n const gitCredentials = credentialsForSelection(options, selection);\n assertPersonalGitHubConsumerAvailable(selection, gitCredentials, options.scope);\n if (gitCredentials && options.scope) {\n const request = gitCredentialsRequestForSelection(\n options.scope,\n requireGitCredentialAuthority(options),\n selection,\n \"identity\",\n );\n const resolved: GitCredentials = await gitCredentials(request);\n assertWorkspaceEcho(\"gitCredentials\", options.scope, resolved.workspaceId);\n assertGitCredentialBindingEcho(selection, request, resolved);\n if (resolved.identity) {\n identity = mergeGitIdentity(identity, resolved.identity);\n } else if (selection.provider === \"github\") {\n identity = mergeGitIdentity(identity, githubAppBotIdentity(settings));\n }\n } else if (selection.provider === \"github\" && selection.installationId > 0) {\n identity = mergeGitIdentity(identity, githubAppBotIdentity(settings));\n }\n }\n return identity;\n}\n\ntype GitCredentialSelection = {\n provider: GitCredentialProvider;\n credentialBindingId: string;\n explicitCredentialBinding: boolean;\n requireBindingEcho: boolean;\n providerHost?: string;\n installationId: number;\n repositoryIds: number[];\n repositoryRefs: GitCredentialRepositoryRef[];\n personalGitHub: boolean;\n};\n\nfunction gitCredentialsRequestForSelection(\n scope: ConnectionScope,\n authority: GitCredentialAuthority,\n selection: GitCredentialSelection,\n purpose?: \"token\" | \"identity\",\n): Parameters<NonNullable<ConnectionCredentialsPort[\"gitCredentials\"]>>[0] {\n const legacy = {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n ...authority,\n ...(purpose ? { purpose } : {}),\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n };\n const bindingEcho = selection.requireBindingEcho\n ? {\n credentialBindingId: selection.credentialBindingId,\n provider: selection.provider,\n ...(selection.providerHost ? { providerHost: selection.providerHost } : {}),\n }\n : {};\n if (selection.provider === \"github\") {\n return {\n ...legacy,\n ...bindingEcho,\n repositoryRefs: selection.repositoryRefs,\n };\n }\n return {\n ...legacy,\n ...bindingEcho,\n provider: selection.provider,\n repositoryRefs: selection.repositoryRefs,\n };\n}\n\nfunction requireGitCredentialAuthority(options: RunGitCredentialOptions): GitCredentialAuthority {\n if (!options.authority) {\n throw new Error(\"host git credential resolution requires immutable session turn authority\");\n }\n return options.authority;\n}\n\nfunction assertGitCredentialBindingEcho(\n selection: GitCredentialSelection,\n request: Parameters<NonNullable<ConnectionCredentialsPort[\"gitCredentials\"]>>[0],\n minted: GitCredentials,\n): void {\n if (!selection.requireBindingEcho) return;\n if (minted.credentialBindingId !== request.credentialBindingId) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned the wrong credential binding`,\n );\n }\n if (minted.provider !== selection.provider) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned the wrong provider echo`,\n );\n }\n if (request.providerHost && minted.providerHost !== request.providerHost) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned the wrong provider host echo`,\n );\n }\n}\n\n/**\n * The GitHub App installation + repository ids a run's git-credential mint\n * would use for these resources, or null when no GitHub token would be minted.\n * Derived from gitCredentialSelections so workspace-authorization rechecks\n * cover exactly the ids that reach createGitHubAppInstallationToken —\n * including legacy string-typed installationId/repositoryId refs, which the\n * mint path coerces via positiveInteger.\n */\nexport function gitHubTokenMintSelections(\n resources: ResourceRef[],\n): Array<{ installationId: number; repositoryIds: number[] }> {\n return gitCredentialSelections(resources)\n .filter(\n (candidate) =>\n candidate.provider === \"github\" &&\n candidate.installationId > 0 &&\n candidate.repositoryIds.length > 0,\n )\n .map(({ installationId, repositoryIds }) => ({\n installationId,\n repositoryIds,\n }));\n}\n\n/** Exact binding-aware selections used by authorization immediately before mint. */\nexport function gitHubTokenAuthorizationSelections(\n resources: ResourceRef[],\n): GitHubTokenMintSelection[] {\n return gitCredentialSelections(resources)\n .filter(\n (candidate) =>\n candidate.provider === \"github\" &&\n candidate.installationId > 0 &&\n candidate.repositoryIds.length > 0,\n )\n .map(({ credentialBindingId, installationId, repositoryIds, repositoryRefs }) => ({\n credentialBindingId,\n installationId,\n repositoryIds,\n repositoryRefs,\n }));\n}\n\n/** @deprecated Use gitHubTokenMintSelections for multi-installation sessions. */\nexport function gitHubTokenMintSelection(\n resources: ResourceRef[],\n): { installationId: number; repositoryIds: number[] } | null {\n const selections = gitHubTokenMintSelections(resources);\n if (selections.length > 1) {\n throw new Error(\"GitHub resources span multiple credential bindings\");\n }\n return selections[0] ?? null;\n}\n\nfunction gitCredentialSelections(resources: ResourceRef[]): GitCredentialSelection[] {\n // The repository-authority phase admits and freezes this selection, while the\n // personal Git broker owns immediately-before-use revalidation. Until that\n // consumer is active, never let a generic host/App callback substitute a token.\n const personalGitHubResources = new Set<ResourceRef>(\n personalGitHubRepositoryResources(resources),\n );\n const byBinding = new Map<string, GitCredentialSelection>();\n const remoteBindings = new Map<string, string>();\n const bindingProviders = new Map<string, GitCredentialProvider>();\n for (const resource of resources) {\n if (resource.kind !== \"repository\") {\n continue;\n }\n const personalGitHub = personalGitHubResources.has(resource);\n const provider = repositoryCredentialProvider(resource);\n if (!provider) {\n continue;\n }\n const installationId =\n provider === \"github\"\n ? (positiveInteger(resource.githubInstallationId ?? resource.installationId) ?? 0)\n : 0;\n const credentialBindingId = gitCredentialBindingIdForRepository(resource, provider)!;\n const bindingKey = `${provider}\\u0000${credentialBindingId}`;\n const boundProvider = bindingProviders.get(credentialBindingId);\n if (boundProvider && boundProvider !== provider) {\n throw new Error(\n `credential binding ${credentialBindingId} is assigned to multiple Git providers`,\n );\n }\n bindingProviders.set(credentialBindingId, provider);\n const normalizedRemote = gitRemoteIdentity(resource.uri, provider);\n const claimedBinding = remoteBindings.get(normalizedRemote);\n if (claimedBinding && claimedBinding !== bindingKey) {\n throw new Error(\n `repository remote ${resource.uri} is claimed by multiple credential bindings`,\n );\n }\n remoteBindings.set(normalizedRemote, bindingKey);\n const entry = byBinding.get(bindingKey) ?? {\n provider,\n credentialBindingId,\n explicitCredentialBinding: Boolean(resource.credentialBindingId),\n requireBindingEcho: false,\n installationId: 0,\n repositoryIds: [],\n repositoryRefs: [],\n personalGitHub,\n };\n if (entry.personalGitHub !== personalGitHub) {\n throw new Error(\n `credential binding ${credentialBindingId} mixes personal and app GitHub repositories`,\n );\n }\n entry.explicitCredentialBinding ||= Boolean(resource.credentialBindingId);\n const ref = gitCredentialRepositoryRef(resource, provider);\n entry.repositoryRefs.push(ref);\n if (provider === \"github\") {\n const repositoryId = positiveInteger(resource.githubRepositoryId ?? resource.repositoryId);\n if (installationId && repositoryId) {\n if (entry.installationId > 0 && entry.installationId !== installationId) {\n throw new Error(\n `GitHub credential binding ${credentialBindingId} spans multiple installations`,\n );\n }\n entry.installationId = installationId;\n entry.repositoryIds.push(repositoryId);\n }\n }\n byBinding.set(bindingKey, entry);\n }\n const selections = [...byBinding.values()];\n const providerCounts = new Map<GitCredentialProvider, number>();\n for (const selection of selections) {\n providerCounts.set(selection.provider, (providerCounts.get(selection.provider) ?? 0) + 1);\n const hosts = new Set(\n selection.repositoryRefs.map((ref) => normalizedGitHost(ref.uri)).filter(Boolean),\n );\n const [providerHost] = hosts;\n if (hosts.size === 1 && providerHost) selection.providerHost = providerHost;\n }\n for (const selection of selections) {\n selection.requireBindingEcho =\n selection.explicitCredentialBinding || (providerCounts.get(selection.provider) ?? 0) > 1;\n }\n return selections;\n}\n\nfunction credentialsForSelection(\n options: RunGitCredentialOptions,\n selection: GitCredentialSelection,\n): ConnectionCredentialsPort[\"gitCredentials\"] | undefined {\n return selection.personalGitHub ? options.personalGitHubCredentials : options.gitCredentials;\n}\n\nfunction assertPersonalGitHubConsumerAvailable(\n selection: GitCredentialSelection,\n resolver: ConnectionCredentialsPort[\"gitCredentials\"] | undefined,\n scope: ConnectionScope | undefined,\n): void {\n if (selection.personalGitHub && (!resolver || !scope)) {\n throw new Error(\"personal GitHub Git broker is unavailable for this managed sandbox turn\");\n }\n}\n\nfunction mergeGitIdentity(\n current: { name: string; email: string } | null,\n candidate: { name: string; email: string } | null,\n): { name: string; email: string } | null {\n if (!candidate) return current;\n if (\n current &&\n (current.name !== candidate.name ||\n current.email.toLowerCase() !== candidate.email.toLowerCase())\n ) {\n throw new Error(\"repository resources require different Git commit identities\");\n }\n return current ?? candidate;\n}\n\nfunction normalizedGitHost(uri: string): string {\n try {\n return new URL(uri).host.toLowerCase();\n } catch {\n return \"\";\n }\n}\n\nfunction repositoryCredentialProvider(\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n): GitCredentialProvider | null {\n return gitCredentialProviderForRepository(resource);\n}\n\nfunction gitCredentialRepositoryRef(\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n provider: GitCredentialProvider,\n): GitCredentialRepositoryRef {\n return {\n provider,\n ...(resource.credentialBindingId ? { credentialBindingId: resource.credentialBindingId } : {}),\n ...(resource.access ? { access: resource.access } : {}),\n uri: resource.uri,\n ref: resource.ref,\n ...(resource.expectedCommitSha ? { expectedCommitSha: resource.expectedCommitSha } : {}),\n ...(resource.repositoryId !== undefined\n ? { repositoryId: resource.repositoryId }\n : resource.githubRepositoryId !== undefined\n ? { repositoryId: resource.githubRepositoryId }\n : {}),\n ...(resource.installationId !== undefined\n ? { installationId: resource.installationId }\n : resource.githubInstallationId !== undefined\n ? { installationId: resource.githubInstallationId }\n : {}),\n ...(resource.projectId !== undefined ? { projectId: resource.projectId } : {}),\n ...(resource.connectionId ? { connectionId: resource.connectionId } : {}),\n };\n}\n\nfunction positiveInteger(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isInteger(value) && value > 0) {\n return value;\n }\n if (typeof value === \"string\" && /^\\d+$/.test(value) && Number(value) > 0) {\n return Number(value);\n }\n return null;\n}\n","import {\n CODEX_CREDENTIAL_LEASE_TTL_MS,\n XAI_CREDENTIAL_LEASE_TTL_MS,\n heartbeatCodexCredentialLeaseUntil,\n heartbeatXaiCredentialLeaseUntil,\n} from \"@opengeni/db\";\nimport type { SharedActivityServices } from \"../types\";\nimport { codexCredentialLeaseDeadlineExpired } from \"./codex\";\nimport { safeErrorDiagnostic } from \"./errors\";\n\nexport type LeaseRenewReason = \"timer\" | \"runtime_event\" | \"model_usage\";\nexport type LeaseLossReason = \"deadline\" | \"not_found\";\n\nexport class CodexCredentialLeaseLostError extends Error {\n readonly code = \"codex_credential_lease_lost\";\n\n constructor(readonly reason: LeaseLossReason) {\n super(\"Codex credential lease is not usable for provider dispatch\");\n this.name = \"CodexCredentialLeaseLostError\";\n }\n}\n\nexport type TurnCredentialLeaseDeps = {\n db: SharedActivityServices[\"db\"];\n observability: SharedActivityServices[\"observability\"];\n accountId: string;\n workspaceId: string;\n codexWorkspaceKey: string;\n getTurnId: () => string | undefined;\n};\n\n/**\n * The Codex credential holder for one running turn. The DB row is the\n * cross-replica fairness primitive; the heartbeat here only extends its short\n * TTL. A killed worker stops heartbeating and the holder self-expires.\n */\nexport class CodexTurnLease {\n held = false;\n lost = false;\n lossReason: LeaseLossReason | null = null;\n holderId: string | null = null;\n generation: number | null = null;\n // Monotonic worker deadline, not a comparison between the Postgres and\n // worker wall clocks. It is advanced only after a database renewal confirms,\n // from the request START + TTL; slow queries therefore shorten (never extend)\n // the conservative ownership window.\n confirmedUntilMs: number | null = null;\n private heartbeatInFlight = false;\n private heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n\n constructor(private readonly deps: TurnCredentialLeaseDeps) {}\n\n markLost = (reason: LeaseLossReason): void => {\n if (this.lost) return;\n this.lost = true;\n this.lossReason = reason;\n this.deps.observability.incrementCounter({\n name: \"opengeni_codex_lease_renewals_total\",\n help: \"Codex lease renewal checkpoints by outcome and reason.\",\n labels: { workspace_key: this.deps.codexWorkspaceKey, outcome: \"lost\", reason },\n });\n this.deps.observability.warn(\"Codex credential lease was lost during an active turn\", {\n workspaceId: this.deps.workspaceId,\n turnId: this.deps.getTurnId(),\n reason,\n });\n };\n\n /** Fail closed at the last worker-confirmed lease deadline before dispatch. */\n assertUsable = (): void => {\n if (this.lost) {\n throw new CodexCredentialLeaseLostError(this.lossReason ?? \"not_found\");\n }\n if (\n !this.held ||\n this.holderId === null ||\n this.generation === null ||\n codexCredentialLeaseDeadlineExpired(this.confirmedUntilMs)\n ) {\n this.markLost(\"deadline\");\n throw new CodexCredentialLeaseLostError(\"deadline\");\n }\n };\n\n renew = async (reason: LeaseRenewReason): Promise<void> => {\n const turnId = this.deps.getTurnId();\n if (!turnId || !this.held || !this.holderId || this.generation === null || this.lost) {\n return;\n }\n if (codexCredentialLeaseDeadlineExpired(this.confirmedUntilMs)) {\n this.markLost(\"deadline\");\n return;\n }\n if (this.heartbeatInFlight) return;\n this.heartbeatInFlight = true;\n const priorConfirmedUntilMs = this.confirmedUntilMs;\n const renewalStartedAtMs = performance.now();\n try {\n const renewedUntil = await heartbeatCodexCredentialLeaseUntil(\n this.deps.db,\n this.deps.accountId,\n this.deps.workspaceId,\n turnId,\n this.holderId,\n this.generation,\n CODEX_CREDENTIAL_LEASE_TTL_MS,\n );\n if (!renewedUntil) {\n this.markLost(\"not_found\");\n } else if (\n codexCredentialLeaseDeadlineExpired(priorConfirmedUntilMs) ||\n codexCredentialLeaseDeadlineExpired(renewalStartedAtMs + CODEX_CREDENTIAL_LEASE_TTL_MS)\n ) {\n // The database call may have waited on a lock until the prior lease\n // expired. A late successful UPDATE is not proof that this worker\n // owned the credential continuously; do not accept or extend it.\n this.markLost(\"deadline\");\n } else {\n this.confirmedUntilMs = renewalStartedAtMs + CODEX_CREDENTIAL_LEASE_TTL_MS;\n this.deps.observability.incrementCounter({\n name: \"opengeni_codex_lease_renewals_total\",\n help: \"Codex lease renewal checkpoints by outcome and reason.\",\n labels: {\n workspace_key: this.deps.codexWorkspaceKey,\n outcome: \"completed\",\n reason,\n },\n });\n }\n } catch (error) {\n if (codexCredentialLeaseDeadlineExpired(this.confirmedUntilMs)) {\n this.markLost(\"deadline\");\n return;\n }\n this.deps.observability.warn(\"Codex credential lease heartbeat failed\", {\n workspaceId: this.deps.workspaceId,\n turnId,\n reason,\n ...safeErrorDiagnostic(error),\n });\n this.deps.observability.incrementCounter({\n name: \"opengeni_codex_lease_renewals_total\",\n help: \"Codex lease renewal checkpoints by outcome and reason.\",\n labels: {\n workspace_key: this.deps.codexWorkspaceKey,\n outcome: \"error\",\n reason,\n },\n });\n } finally {\n this.heartbeatInFlight = false;\n }\n };\n\n startHeartbeat = (): void => {\n if (!this.deps.getTurnId() || this.heartbeatTimer) return;\n this.heartbeatTimer = setInterval(() => {\n void this.renew(\"timer\");\n }, 60_000);\n this.heartbeatTimer.unref?.();\n };\n\n stopHeartbeat = (): void => {\n if (!this.heartbeatTimer) return;\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = undefined;\n };\n}\n\n/** The xAI/SuperGrok credential holder for one running turn; same shape. */\nexport class XaiTurnLease {\n held = false;\n lost = false;\n subjectId: string | null = null;\n holderId: string | null = null;\n generation: number | null = null;\n confirmedUntilMs: number | null = null;\n private heartbeatInFlight = false;\n private heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n\n constructor(private readonly deps: TurnCredentialLeaseDeps) {}\n\n markLost = (reason: LeaseLossReason): void => {\n if (this.lost) return;\n this.lost = true;\n this.deps.observability.warn(\"xAI credential lease was lost during an active turn\", {\n workspaceId: this.deps.workspaceId,\n turnId: this.deps.getTurnId(),\n reason,\n });\n };\n\n renew = async (): Promise<void> => {\n const turnId = this.deps.getTurnId();\n if (\n !turnId ||\n !this.held ||\n !this.subjectId ||\n !this.holderId ||\n this.generation === null ||\n this.lost\n ) {\n return;\n }\n if (codexCredentialLeaseDeadlineExpired(this.confirmedUntilMs)) {\n this.markLost(\"deadline\");\n return;\n }\n if (this.heartbeatInFlight) return;\n this.heartbeatInFlight = true;\n const renewalStartedAtMs = performance.now();\n try {\n const renewedUntil = await heartbeatXaiCredentialLeaseUntil(this.deps.db, {\n workspaceId: this.deps.workspaceId,\n subjectId: this.subjectId,\n turnId,\n holderId: this.holderId,\n generation: this.generation,\n leaseTtlMs: XAI_CREDENTIAL_LEASE_TTL_MS,\n });\n if (!renewedUntil) {\n this.markLost(\"not_found\");\n } else {\n this.confirmedUntilMs = renewalStartedAtMs + XAI_CREDENTIAL_LEASE_TTL_MS;\n }\n } catch (error) {\n if (codexCredentialLeaseDeadlineExpired(this.confirmedUntilMs)) {\n this.markLost(\"deadline\");\n return;\n }\n this.deps.observability.warn(\"xAI credential lease heartbeat failed\", {\n workspaceId: this.deps.workspaceId,\n turnId,\n ...safeErrorDiagnostic(error),\n });\n } finally {\n this.heartbeatInFlight = false;\n }\n };\n\n startHeartbeat = (): void => {\n if (!this.deps.getTurnId() || this.heartbeatTimer) return;\n this.heartbeatTimer = setInterval(() => {\n void this.renew();\n }, 60_000);\n this.heartbeatTimer.unref?.();\n };\n\n stopHeartbeat = (): void => {\n if (!this.heartbeatTimer) return;\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = undefined;\n };\n}\n\n/** Both serving-credential leases for one turn attempt plus their composite views. */\nexport type TurnCredentialLeases = {\n codex: CodexTurnLease;\n xai: XaiTurnLease;\n renewServing: (reason: LeaseRenewReason) => Promise<void>;\n servingLost: () => boolean;\n};\n\nexport function createTurnCredentialLeases(deps: TurnCredentialLeaseDeps): TurnCredentialLeases {\n const codex = new CodexTurnLease(deps);\n const xai = new XaiTurnLease(deps);\n return {\n codex,\n xai,\n renewServing: async (reason) => {\n await codex.renew(reason);\n await xai.renew();\n },\n servingLost: () => codex.lost || xai.lost,\n };\n}\n","import {\n listCodexAccountStatuses,\n fetchCodexUsageForAccount,\n type CodexAccountStatus,\n} from \"@opengeni/db\";\nimport { type ResolvedModelProvider, type Settings } from \"@opengeni/config\";\nimport { codexAccountNeedsLiveCapacityRefresh } from \"../codex-rotation\";\nimport {\n refreshCodexUsageAndRepairCapacityWaiters,\n signalPendingCodexCapacityWakeTargets,\n} from \"../codex-capacity\";\nimport type { TurnActivityServices as ActivityServices } from \"../types\";\nimport { createHash } from \"node:crypto\";\n\nexport function codexWorkspaceMetricKey(workspaceId: string): string {\n return createHash(\"sha256\").update(workspaceId).digest(\"hex\").slice(0, 12);\n}\n\n/** Stable public request identity across partial resumes and activity retries. */\nexport function acceptsPromptCacheKeyForTurn(\n resolvedModel: {\n provider: { kind: ResolvedModelProvider[\"kind\"]; builtin?: boolean };\n } | null,\n): boolean {\n if (!resolvedModel) {\n return true;\n }\n return (\n resolvedModel.provider.builtin === true || resolvedModel.provider.kind === \"codex-subscription\"\n );\n}\n\n/**\n * SELF-HEAL helper for the all-capped rotation idle (invariant 4: BOUNDED, no thrash).\n * The turn hot path never refreshes Codex usage — only the usage API route does — so a\n * window that has actually reset still reads OVER-threshold from the stale cache, which\n * would idle-loop forever. Before idling, refresh LIVE usage for every connected account\n * the cache marks exhausted (bounded to the account count), which re-writes the\n * cache columns, then return the re-read rows so the ranker can pick up a genuinely-reset\n * window THIS turn. Typed quota cooldowns are also refreshed because the provider may\n * replace an allowance cycle before its original reset; revision fencing makes that\n * repair safe. Generic backpressure and legacy-unknown cooldowns are never reconciled.\n * A refresh/read failure is swallowed (fall back to the pre-refresh rows + bounded idle).\n */\nexport async function refreshCappedCodexUsageRows(\n db: ActivityServices[\"db\"],\n settings: Settings,\n workspaceId: string,\n accounts: Array<\n Pick<\n CodexAccountStatus,\n | \"id\"\n | \"status\"\n | \"primaryUsedPercent\"\n | \"secondaryUsedPercent\"\n | \"exhaustedUntil\"\n | \"exhaustedKind\"\n >\n >,\n capacitySignals: {\n signalCodexCapacityWorkflow?: ActivityServices[\"signalCodexCapacityWorkflow\"] | undefined;\n wakeSessionWorkflow: ActivityServices[\"wakeSessionWorkflow\"];\n },\n): Promise<\n Array<\n Pick<\n CodexAccountStatus,\n | \"id\"\n | \"status\"\n | \"primaryUsedPercent\"\n | \"secondaryUsedPercent\"\n | \"exhaustedUntil\"\n | \"exhaustedKind\"\n >\n >\n> {\n const now = new Date();\n const stale = accounts.filter(\n (account) => account.status === \"active\" && codexAccountNeedsLiveCapacityRefresh(account, now),\n );\n if (stale.length === 0) {\n return accounts;\n }\n await refreshCodexUsageAndRepairCapacityWaiters(\n stale.map((account) => () => fetchCodexUsageForAccount(db, settings, workspaceId, account.id)),\n () => signalPendingCodexCapacityWakeTargets({ db, ...capacitySignals }, workspaceId),\n );\n return listCodexAccountStatuses(db, workspaceId).catch(() => accounts);\n}\n\n/**\n * True once the lifetime last confirmed by Postgres is no longer trustworthy.\n * A missing or malformed deadline fails closed for a holder that claims to be\n * leased; callers check this before accepting an in-flight heartbeat promise.\n */\nexport function codexCredentialLeaseDeadlineExpired(\n confirmedUntilMs: number | null,\n nowMs: number = performance.now(),\n): boolean {\n return (\n confirmedUntilMs === null || !Number.isFinite(confirmedUntilMs) || confirmedUntilMs <= nowMs\n );\n}\n","import {\n getMaterializedSandboxFileResources,\n markSandboxFileResourcesMaterialized,\n requireFile,\n} from \"@opengeni/db\";\nimport {\n materializeSandboxFileDownloads,\n sandboxRunAs,\n type CodemodeTokenWriterSession,\n type RetainableSessionImageOutputHook,\n type SandboxFileDownload,\n type TurnToolCancellationFence,\n} from \"@opengeni/runtime\";\nimport type { Settings } from \"@opengeni/config\";\nimport type { RetainedArtifactMetadata } from \"@opengeni/contracts\";\nimport type { ResumedTurnSandbox } from \"../../sandbox-resume\";\nimport type { SharedActivityServices } from \"../types\";\nimport {\n assertGeneratedImageHistoryRetained,\n collectGeneratedImageReceipts,\n compactGeneratedImageRunState,\n generatedImagesFromHistory,\n retainGeneratedImage,\n type GeneratedImageOutput,\n type GeneratedImageReceipt,\n} from \"../generated-images\";\nimport {\n collectRetainedScreenshotReceipts,\n compactRetainedScreenshotRunState,\n materializeRetainedScreenshotHistory,\n retainComputerScreenshot,\n toolOutputContainsInlineImage,\n typedScreenshotFromToolOutput,\n unavailableRetainedSessionImage,\n} from \"../retained-screenshots\";\nimport { objectStorageForSandboxDownloads } from \"./file-resources\";\nimport type { TurnEventPublisher } from \"./model-usage\";\n\nexport type NativeImageGenerationRetention = {\n providerId: string;\n providerBindingHash: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n};\n\nexport type TurnMediaArtifactDeps = {\n db: SharedActivityServices[\"db\"];\n objectStorage: SharedActivityServices[\"objectStorage\"];\n observability: SharedActivityServices[\"observability\"];\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n getTurnId: () => string | undefined;\n getModelRunSettings: () => Settings;\n getPublish: () => TurnEventPublisher | null;\n toolCancellationFenceRef: { current: TurnToolCancellationFence | null };\n getResolvedSandbox: () => ResumedTurnSandbox | null;\n getSetupBoxSession: () => unknown;\n getSandboxGroupId: () => string | null;\n runWorkspaceMutation: <T>(\n sandbox: ResumedTurnSandbox,\n operation: string,\n mutation: () => Promise<T>,\n ) => Promise<T>;\n};\n\nexport class TurnMediaArtifacts {\n readonly retainedScreenshotReceiptsByCallId = new Map<string, RetainedArtifactMetadata>();\n modelCanReceiveRetainedSessionImages = true;\n readonly generatedImageReceiptsByProviderItemId = new Map<string, GeneratedImageReceipt>();\n readonly generatedImageReceiptsCreatedThisTurn = new Map<string, GeneratedImageReceipt>();\n private generatedImageMaterializationCache: {\n instanceId: string;\n fileIds: Set<string>;\n } | null = null;\n sdkOwnedSandboxSession: CodemodeTokenWriterSession | null = null;\n sandboxFileDownloadBackend: Settings[\"sandboxBackend\"];\n nativeImageGenerationRetention: NativeImageGenerationRetention | null = null;\n readonly retainedSessionImageCallIds = new Set<string>();\n\n constructor(private readonly deps: TurnMediaArtifactDeps) {\n this.sandboxFileDownloadBackend = deps.getModelRunSettings().sandboxBackend;\n }\n\n rememberGeneratedImageCreatedThisTurn = (receipt: GeneratedImageReceipt): void => {\n this.generatedImageReceiptsCreatedThisTurn.set(receipt.artifact.artifactId, receipt);\n };\n\n private prepareGeneratedImageDownload = async (receipt: GeneratedImageReceipt) => {\n const { db, objectStorage } = this.deps;\n if (!objectStorage) {\n throw new Error(\"Generated image sandbox materialization requires object storage\");\n }\n const file = await requireFile(db, this.deps.workspaceId, receipt.artifact.artifactId);\n const downloadStorage = objectStorageForSandboxDownloads(\n this.deps.getModelRunSettings(),\n objectStorage,\n this.sandboxFileDownloadBackend,\n );\n const signed = await downloadStorage.createGetUrl({\n key: file.objectKey,\n });\n return {\n file,\n download: {\n fileId: file.id,\n mountPath: \"generated-images\",\n filename: file.safeFilename,\n url: signed.url,\n expiresAt: signed.expiresAt,\n sizeBytes: file.sizeBytes,\n ...(file.sha256 ? { sha256: file.sha256 } : {}),\n } satisfies SandboxFileDownload,\n };\n };\n\n private writeGeneratedImageDownload = async (\n sessionForDownload: CodemodeTokenWriterSession,\n download: SandboxFileDownload,\n ): Promise<void> => {\n const runAs = sandboxRunAs(this.deps.getModelRunSettings());\n const publish = this.deps.getPublish();\n const fence = this.deps.toolCancellationFenceRef.current;\n const materialized = await materializeSandboxFileDownloads(sessionForDownload, [download], {\n onRuntimeEvent: async (event) => {\n await publish?.([{ type: event.type, payload: event.payload }], true);\n },\n ...(runAs ? { runAs } : {}),\n ...(fence ? { commandRunner: fence.runSandboxCommand.bind(fence) } : {}),\n });\n if (materialized.failures.length > 0) {\n throw new Error(materialized.failures[0]!.reason);\n }\n };\n\n private warnGeneratedImageMaterializationDeferred = (error: unknown): void => {\n this.deps.observability.warn(\"Generated image sandbox materialization deferred\", {\n errorClass: error instanceof Error ? error.name : \"UnknownError\",\n errorCode: \"generated_image_materialization_deferred\",\n origin: \"worker\",\n });\n };\n\n materializeGeneratedImageInSandbox = async (\n receipt: GeneratedImageReceipt,\n sandbox: ResumedTurnSandbox,\n sessionForDownload: unknown,\n ): Promise<boolean> => {\n try {\n const { file, download } = await this.prepareGeneratedImageDownload(receipt);\n if (this.generatedImageMaterializationCache?.instanceId !== sandbox.established.instanceId) {\n const fileIds = this.deps.getSandboxGroupId()\n ? await getMaterializedSandboxFileResources(this.deps.db, {\n accountId: this.deps.accountId,\n workspaceId: this.deps.workspaceId,\n sandboxGroupId: this.deps.getSandboxGroupId()!,\n expectedEpoch: sandbox.leaseEpoch,\n instanceId: sandbox.established.instanceId,\n })\n : new Set<string>();\n this.generatedImageMaterializationCache = {\n instanceId: sandbox.established.instanceId,\n fileIds,\n };\n }\n if (this.generatedImageMaterializationCache.fileIds.has(file.id)) return true;\n await this.deps.runWorkspaceMutation(\n sandbox,\n \"generatedImageMaterialization\",\n async () =>\n await this.writeGeneratedImageDownload(\n sessionForDownload as CodemodeTokenWriterSession,\n download,\n ),\n );\n this.generatedImageMaterializationCache.fileIds.add(file.id);\n const sandboxGroupId = this.deps.getSandboxGroupId();\n if (sandboxGroupId) {\n await markSandboxFileResourcesMaterialized(this.deps.db, {\n accountId: this.deps.accountId,\n workspaceId: this.deps.workspaceId,\n sandboxGroupId,\n expectedEpoch: sandbox.leaseEpoch,\n instanceId: sandbox.established.instanceId,\n fileIds: [file.id],\n });\n }\n return true;\n } catch (error) {\n this.warnGeneratedImageMaterializationDeferred(error);\n return false;\n }\n };\n\n materializeGeneratedImageInOwnedSdkSession = async (\n receipt: GeneratedImageReceipt,\n sessionForDownload: unknown,\n ): Promise<boolean> => {\n try {\n const { download } = await this.prepareGeneratedImageDownload(receipt);\n await this.writeGeneratedImageDownload(\n sessionForDownload as CodemodeTokenWriterSession,\n download,\n );\n return true;\n } catch (error) {\n this.warnGeneratedImageMaterializationDeferred(error);\n return false;\n }\n };\n\n materializeGeneratedImage = async (receipt: GeneratedImageReceipt): Promise<boolean> => {\n if (this.sandboxFileDownloadBackend === \"none\") return false;\n const resolvedSandbox = this.deps.getResolvedSandbox();\n const setupBoxSession = this.deps.getSetupBoxSession();\n if (resolvedSandbox && setupBoxSession) {\n return await this.materializeGeneratedImageInSandbox(\n receipt,\n resolvedSandbox,\n setupBoxSession,\n );\n }\n if (this.sdkOwnedSandboxSession) {\n return await this.materializeGeneratedImageInOwnedSdkSession(\n receipt,\n this.sdkOwnedSandboxSession,\n );\n }\n return false;\n };\n\n retainNativeGeneratedImage = async (\n output: GeneratedImageOutput,\n ): Promise<GeneratedImageReceipt> => {\n if (output.providerItemId) {\n const existing = this.generatedImageReceiptsByProviderItemId.get(output.providerItemId);\n if (existing) return existing;\n }\n const context = this.nativeImageGenerationRetention;\n if (!context || !output.providerItemId) {\n throw new Error(\"Native generated image arrived without provider retention identity\");\n }\n const retained = await retainGeneratedImage({\n db: this.deps.db,\n objectStorage: this.deps.objectStorage,\n accountId: this.deps.accountId,\n workspaceId: this.deps.workspaceId,\n sessionId: context.sessionId,\n turnId: context.turnId,\n attemptId: context.attemptId,\n sourceStrategy: \"native_hosted\",\n providerId: context.providerId,\n providerBindingHash: context.providerBindingHash,\n output,\n });\n this.generatedImageReceiptsByProviderItemId.set(output.providerItemId, retained.receipt);\n this.rememberGeneratedImageCreatedThisTurn(retained.receipt);\n await this.materializeGeneratedImage(retained.receipt);\n return retained.receipt;\n };\n\n retainNativeGeneratedImagesFromHistory = async (\n history: Array<Record<string, unknown>>,\n ): Promise<void> => {\n collectGeneratedImageReceipts(history, this.generatedImageReceiptsByProviderItemId);\n for (const output of generatedImagesFromHistory(\n history,\n this.generatedImageReceiptsByProviderItemId,\n )) {\n if (\n !output.providerItemId ||\n this.generatedImageReceiptsByProviderItemId.has(output.providerItemId)\n ) {\n continue;\n }\n await this.retainNativeGeneratedImage(output);\n }\n assertGeneratedImageHistoryRetained(history, this.generatedImageReceiptsByProviderItemId);\n };\n\n compactMediaRunState = (serialized: string): string =>\n compactGeneratedImageRunState(\n compactRetainedScreenshotRunState(serialized, this.retainedScreenshotReceiptsByCallId),\n this.generatedImageReceiptsByProviderItemId,\n );\n\n retainSessionImageAtToolBoundary: RetainableSessionImageOutputHook = async ({\n toolCallId,\n output,\n }) => {\n const activeTurnId = this.deps.getTurnId();\n if (!activeTurnId) {\n throw new Error(\"Session image tool completed before turn initialization\");\n }\n const typedScreenshot = typedScreenshotFromToolOutput({\n callId: toolCallId,\n output,\n });\n this.retainedSessionImageCallIds.add(toolCallId);\n if (!typedScreenshot) {\n if (toolOutputContainsInlineImage(output)) {\n this.retainedScreenshotReceiptsByCallId.set(\n toolCallId,\n unavailableRetainedSessionImage({\n sessionId: this.deps.sessionId,\n turnId: activeTurnId,\n attemptId: this.deps.attemptId,\n toolCallId,\n toolOutputId: toolCallId,\n reason: \"unsupported\",\n }),\n );\n }\n return;\n }\n this.retainedScreenshotReceiptsByCallId.set(\n toolCallId,\n unavailableRetainedSessionImage({\n sessionId: this.deps.sessionId,\n turnId: activeTurnId,\n attemptId: this.deps.attemptId,\n toolCallId,\n toolOutputId: toolCallId,\n reason: \"pending\",\n }),\n );\n this.retainedScreenshotReceiptsByCallId.set(\n toolCallId,\n await retainComputerScreenshot({\n db: this.deps.db,\n objectStorage: this.deps.objectStorage,\n accountId: this.deps.accountId,\n workspaceId: this.deps.workspaceId,\n sessionId: this.deps.sessionId,\n turnId: activeTurnId,\n attemptId: this.deps.attemptId,\n output: typedScreenshot,\n }),\n );\n };\n\n materializeScreenshotHistory = async (history: Array<Record<string, unknown>>) => {\n collectRetainedScreenshotReceipts(history, this.retainedScreenshotReceiptsByCallId);\n if (!this.modelCanReceiveRetainedSessionImages) return history;\n return await materializeRetainedScreenshotHistory({\n db: this.deps.db,\n objectStorage: this.deps.objectStorage,\n workspaceId: this.deps.workspaceId,\n sessionId: this.deps.sessionId,\n history,\n });\n };\n}\n\nexport function createTurnMediaArtifacts(deps: TurnMediaArtifactDeps): TurnMediaArtifacts {\n return new TurnMediaArtifacts(deps);\n}\n","import {\n COMPUTER_SCREENSHOT_MAX_DIMENSION,\n COMPUTER_SCREENSHOT_MAX_PIXELS,\n GENERATED_IMAGE_MAX_BYTES,\n GeneratedImageReceiptSchema,\n retainedGeneratedImageReferenceFromFile,\n sandboxShellPath,\n type GeneratedImageReceipt,\n} from \"@opengeni/contracts\";\nimport {\n completeFileUpload,\n prepareGeneratedImageArtifact,\n recordGeneratedImageArtifactError,\n settleGeneratedImageArtifactReady,\n type Database,\n type GeneratedImageArtifact,\n type GeneratedImageSourceStrategy,\n} from \"@opengeni/db\";\nimport { retryWhileMissing, type ObjectHead, type ObjectStorage } from \"@opengeni/storage\";\nimport { createHash } from \"node:crypto\";\nimport { ScreenshotValidationError, validateRetainableSessionImage } from \"./retained-screenshots\";\n\nconst GENERATED_IMAGE_MARKER = \"generated_image\";\nconst UPLOAD_INTENT_TTL_MS = 60 * 60_000;\n\nexport type GeneratedImageMediaType = \"image/png\" | \"image/jpeg\" | \"image/webp\";\n\nexport type ValidatedGeneratedImage = {\n bytes: Uint8Array;\n mediaType: GeneratedImageMediaType;\n extension: \"png\" | \"jpg\" | \"webp\";\n sizeBytes: number;\n sha256: string;\n width: number;\n height: number;\n};\n\nexport type GeneratedImageOutput = {\n toolCallId: string;\n providerItemId: string | null;\n bytes: Uint8Array;\n declaredMediaType?: string;\n};\n\nexport type { GeneratedImageReceipt };\n\nexport type RetainedGeneratedImage = {\n receipt: GeneratedImageReceipt;\n artifact: GeneratedImageArtifact;\n};\n\nexport class GeneratedImageValidationError extends Error {\n constructor(\n message: string,\n readonly reason?: ScreenshotValidationError[\"reason\"],\n ) {\n super(message);\n this.name = \"GeneratedImageValidationError\";\n }\n}\n\n/** Extract the completed Responses hosted-tool payload before JSON serialization. */\nexport function generatedImageFromSdkEvent(event: unknown): GeneratedImageOutput | null {\n if (!event || typeof event !== \"object\") return null;\n const streamEvent = event as {\n type?: unknown;\n item?: { type?: unknown; rawItem?: unknown; id?: unknown };\n };\n if (streamEvent.type !== \"run_item_stream_event\") return null;\n const item = streamEvent.item;\n if (!item || item.type !== \"tool_call_item\") return null;\n if (!item.rawItem || typeof item.rawItem !== \"object\" || Array.isArray(item.rawItem)) return null;\n const raw = item.rawItem as Record<string, unknown>;\n if (\n raw.type !== \"hosted_tool_call\" ||\n raw.name !== \"image_generation_call\" ||\n raw.status !== \"completed\"\n ) {\n return null;\n }\n const providerData =\n raw.providerData && typeof raw.providerData === \"object\" && !Array.isArray(raw.providerData)\n ? (raw.providerData as Record<string, unknown>)\n : null;\n const encoded =\n typeof raw.output === \"string\"\n ? raw.output\n : typeof providerData?.result === \"string\"\n ? providerData.result\n : null;\n if (!encoded) return null;\n const providerItemId = raw.id ?? providerData?.id ?? item.id;\n const toolCallId = providerItemId;\n if (typeof toolCallId !== \"string\" || toolCallId.length === 0) return null;\n return {\n toolCallId,\n providerItemId: typeof providerItemId === \"string\" ? providerItemId : null,\n bytes: decodeGeneratedImageBase64(encoded),\n };\n}\n\n/** Classify the native terminal item independently from its current payload shape. */\nexport function isCompletedGeneratedImageSdkEvent(event: unknown): boolean {\n if (!isRecord(event) || event.type !== \"run_item_stream_event\") return false;\n const item = event.item;\n if (!isRecord(item) || item.type !== \"tool_call_item\" || !isRecord(item.rawItem)) return false;\n return (\n item.rawItem.type === \"hosted_tool_call\" &&\n item.rawItem.name === \"image_generation_call\" &&\n item.rawItem.status === \"completed\"\n );\n}\n\nexport function generatedImagesFromHistory(\n history: ReadonlyArray<Record<string, unknown>>,\n retainedProviderItems?: Pick<ReadonlyMap<string, unknown>, \"has\">,\n): GeneratedImageOutput[] {\n const outputs: GeneratedImageOutput[] = [];\n for (const item of history) {\n if (\n item.type !== \"hosted_tool_call\" ||\n item.name !== \"image_generation_call\" ||\n item.status !== \"completed\" ||\n typeof item.id !== \"string\" ||\n (typeof item.output !== \"string\" &&\n !(\n item.providerData &&\n typeof item.providerData === \"object\" &&\n !Array.isArray(item.providerData) &&\n typeof (item.providerData as Record<string, unknown>).result === \"string\"\n ))\n ) {\n continue;\n }\n if (retainedProviderItems?.has(item.id)) continue;\n if (generatedImageReceiptFromUnknown(item.output)) continue;\n outputs.push({\n toolCallId: item.id,\n providerItemId: item.id,\n bytes: decodeGeneratedImageBase64(\n typeof item.output === \"string\"\n ? item.output\n : ((item.providerData as Record<string, unknown>).result as string),\n ),\n });\n }\n return outputs;\n}\n\n/** Refuse to serialize a completed native item unless its bytes have a receipt. */\nexport function assertGeneratedImageHistoryRetained(\n history: ReadonlyArray<Record<string, unknown>>,\n receiptsByProviderItemId: Pick<ReadonlyMap<string, unknown>, \"has\">,\n): void {\n for (const item of history) {\n if (\n item.type !== \"hosted_tool_call\" ||\n item.name !== \"image_generation_call\" ||\n item.status !== \"completed\"\n ) {\n continue;\n }\n if (\n typeof item.id !== \"string\" ||\n (!receiptsByProviderItemId.has(item.id) && !generatedImageReceiptFromUnknown(item.output))\n ) {\n throw new Error(\"Completed native image history has no retained-artifact receipt\");\n }\n }\n}\n\nexport function decodeGeneratedImageBase64(value: string): Uint8Array {\n if (value.length === 0 || value.length % 4 !== 0) {\n throw new GeneratedImageValidationError(\"generated image base64 has invalid length\");\n }\n const padding = value.endsWith(\"==\") ? 2 : value.endsWith(\"=\") ? 1 : 0;\n const decodedBytes = (value.length / 4) * 3 - padding;\n if (decodedBytes <= 0 || decodedBytes > GENERATED_IMAGE_MAX_BYTES) {\n throw new GeneratedImageValidationError(\"generated image exceeds the byte limit\");\n }\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value)) {\n throw new GeneratedImageValidationError(\"generated image base64 is malformed\");\n }\n const lastSextet = base64Sextet(value.charCodeAt(value.length - padding - 1));\n if (\n (padding === 2 && (lastSextet & 0x0f) !== 0) ||\n (padding === 1 && (lastSextet & 0x03) !== 0)\n ) {\n throw new GeneratedImageValidationError(\"generated image base64 is non-canonical\");\n }\n const bytes = Buffer.from(value, \"base64\");\n if (bytes.byteLength !== decodedBytes) {\n throw new GeneratedImageValidationError(\"generated image base64 is non-canonical\");\n }\n return bytes;\n}\n\n/** Validate signatures and dimensions; never trust provider-declared MIME metadata. */\nexport function validateGeneratedImage(input: {\n bytes: Uint8Array;\n declaredMediaType?: string;\n}): ValidatedGeneratedImage {\n try {\n return validateRetainableSessionImage(\n {\n bytes: input.bytes,\n ...(input.declaredMediaType ? { declaredMediaType: input.declaredMediaType } : {}),\n },\n {\n maxBytes: GENERATED_IMAGE_MAX_BYTES,\n maxDimension: COMPUTER_SCREENSHOT_MAX_DIMENSION,\n maxPixels: COMPUTER_SCREENSHOT_MAX_PIXELS,\n },\n );\n } catch (error) {\n if (error instanceof ScreenshotValidationError) {\n throw new GeneratedImageValidationError(error.message, error.reason);\n }\n throw error;\n }\n}\n\ntype GeneratedImageIdentityInput = {\n workspaceId: string;\n sessionId: string;\n turnId: string;\n providerId: string;\n providerBindingHash: string;\n toolCallId: string;\n} & (\n | { sourceStrategy: \"native_hosted\"; providerItemId: string }\n | { sourceStrategy: \"provider_adapter\"; providerItemId: null }\n);\n\nexport function generatedImageIdentity(input: GeneratedImageIdentityInput): {\n artifactId: string;\n uploadId: string;\n settlementKey: string;\n} {\n const hash = createHash(\"sha256\")\n .update(\"opengeni:generated-image:v2\\0\")\n .update(input.workspaceId)\n .update(\"\\0\")\n .update(input.sourceStrategy)\n .update(\"\\0\")\n .update(input.providerId)\n .update(\"\\0\")\n .update(input.providerBindingHash)\n .update(\"\\0\");\n if (input.sourceStrategy === \"native_hosted\") {\n hash.update(input.providerItemId);\n } else {\n hash\n .update(input.sessionId)\n .update(\"\\0\")\n .update(input.turnId)\n .update(\"\\0\")\n .update(input.toolCallId);\n }\n const settlementKey = hash.digest(\"hex\");\n return {\n settlementKey,\n artifactId: uuidFromDigest(settlementKey, 0),\n uploadId: uuidFromDigest(settlementKey, 16),\n };\n}\n\nexport async function retainGeneratedImage(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n sourceStrategy: GeneratedImageSourceStrategy;\n providerId: string;\n providerBindingHash: string;\n output: GeneratedImageOutput;\n now?: Date;\n}): Promise<RetainedGeneratedImage> {\n if (!input.objectStorage) {\n throw new Error(\"Generated image retention requires configured object storage\");\n }\n const image = validateGeneratedImage(input.output);\n const identityInput = {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n toolCallId: input.output.toolCallId,\n };\n let identity: ReturnType<typeof generatedImageIdentity>;\n if (input.sourceStrategy === \"native_hosted\") {\n if (!input.output.providerItemId) {\n throw new Error(\"Native generated image has no provider item identity\");\n }\n identity = generatedImageIdentity({\n ...identityInput,\n sourceStrategy: \"native_hosted\",\n providerItemId: input.output.providerItemId,\n });\n } else {\n if (input.output.providerItemId !== null) {\n throw new Error(\"Adapter-generated image cannot carry a native provider item identity\");\n }\n identity = generatedImageIdentity({\n ...identityInput,\n sourceStrategy: \"provider_adapter\",\n providerItemId: null,\n });\n }\n const filename = `generated-image-${identity.artifactId}.${image.extension}`;\n const sandboxPath = `/workspace/generated-images/${filename}`;\n const objectKey = `workspaces/${input.workspaceId}/files/${identity.artifactId}/generated/${filename}`;\n const prepared = await prepareGeneratedImageArtifact(input.db, {\n artifactId: identity.artifactId,\n uploadId: identity.uploadId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n settlementKey: identity.settlementKey,\n toolCallId: input.output.toolCallId,\n sourceStrategy: input.sourceStrategy,\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n providerItemId: input.output.providerItemId,\n mediaType: image.mediaType,\n sizeBytes: image.sizeBytes,\n sha256: image.sha256,\n width: image.width,\n height: image.height,\n sandboxPath,\n filename,\n safeFilename: filename,\n bucket: input.objectStorage.bucket,\n objectKey,\n uploadExpiresAt: new Date((input.now ?? new Date()).getTime() + UPLOAD_INTENT_TTL_MS),\n });\n\n if (prepared.artifact.status === \"ready\") {\n return retainedGeneratedImageFromArtifact(prepared.artifact);\n }\n\n try {\n // A crash may leave the file complete while the correlation row is pending.\n // Verify and settle that state without rewriting the object.\n if (\n prepared.artifact.file.status !== \"ready\" ||\n prepared.artifact.uploadStatus !== \"completed\"\n ) {\n if (!(await input.objectStorage.fileExists(prepared.artifact.file))) {\n await input.objectStorage.putObject({\n key: objectKey,\n contentType: image.mediaType,\n body: image.bytes,\n sha256: image.sha256,\n });\n } else {\n await assertGeneratedImageObject(input.objectStorage, prepared.artifact.file, image);\n }\n await completeFileUpload(input.db, input.workspaceId, identity.uploadId);\n } else {\n await verifyReadyGeneratedImage(input.objectStorage, prepared.artifact, image);\n }\n const settled = await settleGeneratedImageArtifactReady(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: identity.artifactId,\n settlementKey: identity.settlementKey,\n });\n return retainedGeneratedImageFromArtifact(settled);\n } catch (error) {\n await recordGeneratedImageArtifactError(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: identity.artifactId,\n settlementKey: identity.settlementKey,\n error: error instanceof Error ? error.message : String(error),\n }).catch(() => undefined);\n throw error;\n }\n}\n\n/** Replace provider bytes before they can enter event/history serialization. */\nexport function compactGeneratedImageHistory(\n history: Array<Record<string, unknown>>,\n receiptsByProviderItemId: ReadonlyMap<string, GeneratedImageReceipt>,\n): Array<Record<string, unknown>> {\n if (receiptsByProviderItemId.size === 0) return history;\n return history.map((item) => {\n if (item.type !== \"hosted_tool_call\" || item.name !== \"image_generation_call\") return item;\n const id = typeof item.id === \"string\" ? item.id : null;\n const receipt = id ? receiptsByProviderItemId.get(id) : undefined;\n if (!receipt) return item;\n const existingReceipt = generatedImageReceiptFromUnknown(item.output);\n const providerDataContainsBytes =\n isRecord(item.providerData) && typeof item.providerData.result === \"string\";\n if (\n existingReceipt?.artifact.artifactId === receipt.artifact.artifactId &&\n !providerDataContainsBytes\n ) {\n return item;\n }\n return {\n ...item,\n output: receipt,\n ...(item.providerData ? { providerData: withoutNativeImageResult(item.providerData) } : {}),\n };\n });\n}\n\nexport function compactGeneratedImageSdkEvent(\n event: unknown,\n receipt: GeneratedImageReceipt,\n): unknown {\n if (!event || typeof event !== \"object\") return event;\n const streamEvent = event as Record<string, unknown>;\n const item = streamEvent.item;\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return event;\n const itemRecord = item as Record<string, unknown>;\n const raw = itemRecord.rawItem;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return event;\n const rawRecord = raw as Record<string, unknown>;\n if (rawRecord.type !== \"hosted_tool_call\" || rawRecord.name !== \"image_generation_call\") {\n return event;\n }\n return {\n ...streamEvent,\n item: {\n ...itemRecord,\n rawItem: {\n ...rawRecord,\n output: receipt,\n ...(rawRecord.providerData\n ? { providerData: withoutNativeImageResult(rawRecord.providerData) }\n : {}),\n },\n },\n };\n}\n\nexport function collectGeneratedImageReceipts(\n history: ReadonlyArray<Record<string, unknown>>,\n target: Map<string, GeneratedImageReceipt> = new Map(),\n): Map<string, GeneratedImageReceipt> {\n for (const item of history) {\n if (item.type !== \"hosted_tool_call\" || item.name !== \"image_generation_call\") continue;\n if (typeof item.id !== \"string\") continue;\n const receipt = generatedImageReceiptFromUnknown(item.output);\n if (receipt) target.set(item.id, receipt);\n }\n return target;\n}\n\nexport function collectGeneratedImageArtifactReceipts(\n history: ReadonlyArray<Record<string, unknown>>,\n target: Map<string, GeneratedImageReceipt> = new Map(),\n): Map<string, GeneratedImageReceipt> {\n for (const item of history) {\n const candidates = Array.isArray(item.output) ? item.output : [item.output];\n for (const candidate of candidates) {\n const receipt = generatedImageReceiptFromUnknown(candidate);\n if (receipt) target.set(receipt.artifact.artifactId, receipt);\n }\n }\n return target;\n}\n\n/**\n * Project native image calls to one provider-neutral, cache-stable model fact.\n * The canonical hosted-tool item remains available to the UI, but its provider\n * id and compact receipt are never replayed as a counterfeit native result.\n */\nexport function projectGeneratedImageHistoryForModel(\n history: Array<Record<string, unknown>>,\n): Array<Record<string, unknown>> {\n let changed = false;\n const projected: Array<Record<string, unknown>> = [];\n for (const item of history) {\n if (item.type !== \"hosted_tool_call\" || item.name !== \"image_generation_call\") {\n projected.push(item);\n continue;\n }\n const receipt = generatedImageReceiptFromUnknown(item.output);\n if (!receipt) {\n projected.push(item);\n continue;\n }\n changed = true;\n projected.push(generatedImageModelMessage(receipt, \"history\"));\n }\n return changed ? projected : history;\n}\n\n/**\n * Build the attempt-local RunState view consumed by the Agents SDK on resume.\n *\n * OpenAI serializes a hosted image call from `providerData.result`, not from\n * the SDK item's generic `output`. Our durable state deliberately replaces\n * those bytes with a compact receipt, so replaying the hosted item would send\n * a counterfeit `result: null`. Convert it to the same provider-neutral fact\n * used for ordinary history instead. Durable state is never modified.\n */\nexport function projectGeneratedImageRunStateForModel(serialized: string): string {\n const parsed = parseRunState(serialized);\n if (!parsed) return serialized;\n let changed = false;\n\n visitRunStateProtocolItems(parsed, (items) => {\n const projected = projectGeneratedImageRunStateItemsForModel(items);\n if (projected !== items) {\n items.splice(0, items.length, ...projected);\n changed = true;\n }\n });\n visitRunStateItemWrappers(parsed, (wrappers) => {\n for (let index = 0; index < wrappers.length; index += 1) {\n const projected = projectGeneratedImageRunItemWrapper(wrappers[index]!);\n if (projected !== wrappers[index]) {\n wrappers[index] = projected;\n changed = true;\n }\n }\n });\n\n return changed ? JSON.stringify(parsed) : serialized;\n}\n\nfunction projectGeneratedImageRunStateItemsForModel(\n items: Array<Record<string, unknown>>,\n): Array<Record<string, unknown>> {\n let changed = false;\n const projected = items.map((item) => {\n const receipt = generatedImageReceiptFromHostedItem(item);\n if (!receipt) return item;\n changed = true;\n return generatedImageModelMessage(receipt, \"run_state\");\n });\n return changed ? projected : items;\n}\n\nexport function compactGeneratedImageRunState(\n serialized: string,\n receiptsByProviderItemId: ReadonlyMap<string, GeneratedImageReceipt>,\n): string {\n if (receiptsByProviderItemId.size === 0) return serialized;\n let parsed: Record<string, unknown>;\n try {\n const value: unknown = JSON.parse(serialized);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return serialized;\n parsed = value as Record<string, unknown>;\n } catch {\n return serialized;\n }\n let changed = false;\n visitRunStateProtocolItems(parsed, (items) => {\n const compacted = compactGeneratedImageRunStateItems(items, receiptsByProviderItemId);\n if (compacted.some((item, index) => item !== items[index])) {\n items.splice(0, items.length, ...compacted);\n changed = true;\n }\n });\n visitRunStateItemWrappers(parsed, (wrappers) => {\n for (const wrapper of wrappers) {\n if (!isRecord(wrapper) || !isRecord(wrapper.rawItem)) continue;\n const compacted = compactGeneratedImageRunStateItems(\n [wrapper.rawItem],\n receiptsByProviderItemId,\n )[0];\n if (compacted && compacted !== wrapper.rawItem) {\n wrapper.rawItem = compacted;\n changed = true;\n }\n }\n });\n return changed ? JSON.stringify(parsed) : serialized;\n}\n\nfunction compactGeneratedImageRunStateItems(\n items: Array<Record<string, unknown>>,\n receiptsByProviderItemId: ReadonlyMap<string, GeneratedImageReceipt>,\n): Array<Record<string, unknown>> {\n const compacted = compactGeneratedImageHistory(items, receiptsByProviderItemId);\n let serializedReceipt = false;\n const serialized = compacted.map((item) => {\n const receipt = generatedImageReceiptFromUnknown(item.output);\n if (!receipt || typeof item.output === \"string\") return item;\n serializedReceipt = true;\n return { ...item, output: JSON.stringify(receipt) };\n });\n return serializedReceipt ? serialized : compacted;\n}\n\nexport function collectGeneratedImageRunStateArtifactReceipts(\n serialized: string,\n target: Map<string, GeneratedImageReceipt> = new Map(),\n): Map<string, GeneratedImageReceipt> {\n try {\n const value: unknown = JSON.parse(serialized);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return target;\n visitRunStateProtocolItems(value as Record<string, unknown>, (items) => {\n collectGeneratedImageArtifactReceipts(items, target);\n });\n visitRunStateItemWrappers(value as Record<string, unknown>, (wrappers) => {\n for (const wrapper of wrappers) {\n if (isRecord(wrapper) && isRecord(wrapper.rawItem)) {\n collectGeneratedImageArtifactReceipts([wrapper.rawItem], target);\n }\n }\n });\n } catch {\n // A provider-owned or legacy state format is opaque to this collector.\n }\n return target;\n}\n\nexport function generatedImageReceiptFromUnknown(value: unknown): GeneratedImageReceipt | null {\n if (typeof value === \"string\" && value.length <= 4_096) {\n try {\n return generatedImageReceiptFromUnknown(JSON.parse(value));\n } catch {\n return null;\n }\n }\n // Function-tool results are durably normalized to the Agents SDK's typed\n // text envelope. Unwrap that canonical transport shape before validating the\n // closed receipt; otherwise a later turn sees the path in model history but\n // cannot discover the artifact that must be copied into its sandbox.\n if (\n isRecord(value) &&\n value.type === \"text\" &&\n typeof value.text === \"string\" &&\n value.text.length <= 4_096\n ) {\n return generatedImageReceiptFromUnknown(value.text);\n }\n const parsed = GeneratedImageReceiptSchema.safeParse(value);\n return parsed.success ? parsed.data : null;\n}\n\nfunction visitRunStateProtocolItems(\n root: Record<string, unknown>,\n visitor: (items: Array<Record<string, unknown>>) => void,\n): void {\n if (Array.isArray(root.originalInput)) {\n visitor(root.originalInput as Array<Record<string, unknown>>);\n }\n if (Array.isArray(root.modelResponses)) {\n for (const response of root.modelResponses) {\n if (!response || typeof response !== \"object\" || Array.isArray(response)) continue;\n const output = (response as Record<string, unknown>).output;\n if (Array.isArray(output)) visitor(output as Array<Record<string, unknown>>);\n }\n }\n if (root.lastModelResponse && typeof root.lastModelResponse === \"object\") {\n const output = (root.lastModelResponse as Record<string, unknown>).output;\n if (Array.isArray(output)) visitor(output as Array<Record<string, unknown>>);\n }\n}\n\nfunction visitRunStateItemWrappers(\n root: Record<string, unknown>,\n visitor: (items: Array<Record<string, unknown>>) => void,\n): void {\n if (Array.isArray(root.generatedItems)) {\n visitor(root.generatedItems as Array<Record<string, unknown>>);\n }\n const processed = root.lastProcessedResponse;\n if (isRecord(processed) && Array.isArray(processed.newItems)) {\n visitor(processed.newItems as Array<Record<string, unknown>>);\n }\n}\n\nfunction projectGeneratedImageRunItemWrapper(\n value: Record<string, unknown>,\n): Record<string, unknown> {\n if (value.type !== \"tool_call_item\" || !isRecord(value.rawItem) || !isRecord(value.agent)) {\n return value;\n }\n const receipt = generatedImageReceiptFromHostedItem(value.rawItem);\n if (!receipt) return value;\n return {\n type: \"message_output_item\",\n rawItem: generatedImageModelMessage(receipt, \"run_state\"),\n agent: value.agent,\n };\n}\n\nfunction generatedImageReceiptFromHostedItem(\n item: Record<string, unknown>,\n): GeneratedImageReceipt | null {\n if (item.type !== \"hosted_tool_call\" || item.name !== \"image_generation_call\") {\n return null;\n }\n return generatedImageReceiptFromUnknown(item.output);\n}\n\nfunction generatedImageModelFact(receipt: GeneratedImageReceipt): string {\n return [\n \"Generated image artifact:\",\n `Artifact ID: ${receipt.artifact.artifactId}`,\n `Sandbox path: ${sandboxShellPath(receipt.sandboxPath)}`,\n `Format: ${receipt.artifact.contentType}`,\n `Dimensions: ${receipt.artifact.dimensions?.width ?? \"?\"}x${receipt.artifact.dimensions?.height ?? \"?\"}`,\n ].join(\"\\n\");\n}\n\nfunction generatedImageModelMessage(\n receipt: GeneratedImageReceipt,\n shape: \"history\" | \"run_state\",\n): Record<string, unknown> {\n const text = generatedImageModelFact(receipt);\n return shape === \"history\"\n ? { type: \"message\", role: \"assistant\", content: text }\n : {\n type: \"message\",\n role: \"assistant\",\n status: \"completed\",\n content: [{ type: \"output_text\", text }],\n };\n}\n\nfunction parseRunState(serialized: string): Record<string, unknown> | null {\n try {\n const parsed: unknown = JSON.parse(serialized);\n return isRecord(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nexport function retainedGeneratedImageFromArtifact(\n artifact: GeneratedImageArtifact,\n): RetainedGeneratedImage {\n const reference = retainedGeneratedImageReferenceFromFile({\n ...artifact.file,\n width: artifact.width,\n height: artifact.height,\n });\n if (!reference)\n throw new Error(`Ready generated image receipt is invalid: ${artifact.artifactId}`);\n return {\n artifact,\n receipt: {\n type: GENERATED_IMAGE_MARKER,\n artifact: reference,\n sandboxPath: artifact.sandboxPath,\n },\n };\n}\n\n/** Verify a recovered ready correlation against the immutable object metadata. */\nexport async function verifyReadyGeneratedImageArtifact(\n storage: ObjectStorage,\n artifact: GeneratedImageArtifact,\n): Promise<void> {\n if (artifact.status !== \"ready\" || artifact.file.status !== \"ready\") {\n throw new Error(\"Generated image artifact is not durably ready\");\n }\n await assertGeneratedImageObject(storage, artifact.file, {\n sizeBytes: artifact.sizeBytes,\n mediaType: artifact.mediaType as GeneratedImageMediaType,\n sha256: artifact.sha256,\n });\n}\n\n/**\n * Finish a crash-interrupted upload from immutable DB/object metadata without\n * provider replay. A missing object is not proof that generation failed: the\n * paid outcome remains unknown and the caller may check again later.\n */\nexport async function recoverGeneratedImageArtifact(input: {\n db: Database;\n storage: ObjectStorage;\n accountId: string;\n workspaceId: string;\n artifact: GeneratedImageArtifact;\n}): Promise<GeneratedImageArtifact | null> {\n const { artifact } = input;\n if (artifact.status === \"ready\") {\n await verifyReadyGeneratedImageArtifact(input.storage, artifact);\n return artifact;\n }\n if (artifact.status !== \"pending\") return null;\n const recovered = await retryWhileMissing(async () => {\n if (!(await input.storage.fileExists(artifact.file))) return null;\n return artifact.file;\n });\n if (!recovered) return null;\n await assertGeneratedImageObject(input.storage, artifact.file, {\n sizeBytes: artifact.sizeBytes,\n mediaType: artifact.mediaType as GeneratedImageMediaType,\n sha256: artifact.sha256,\n });\n if (artifact.file.status !== \"ready\" || artifact.uploadStatus !== \"completed\") {\n if (!artifact.uploadId) return null;\n await completeFileUpload(input.db, input.workspaceId, artifact.uploadId);\n }\n return await settleGeneratedImageArtifactReady(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: artifact.artifactId,\n settlementKey: artifact.settlementKey,\n });\n}\n\nasync function verifyReadyGeneratedImage(\n storage: ObjectStorage,\n artifact: GeneratedImageArtifact,\n expected: ValidatedGeneratedImage,\n): Promise<void> {\n await assertGeneratedImageObject(storage, artifact.file, expected);\n if (\n artifact.sizeBytes !== expected.sizeBytes ||\n artifact.sha256 !== expected.sha256 ||\n artifact.mediaType !== expected.mediaType ||\n artifact.width !== expected.width ||\n artifact.height !== expected.height\n ) {\n throw new Error(\"ready generated image metadata does not match provider bytes\");\n }\n}\n\nasync function assertGeneratedImageObject(\n storage: ObjectStorage,\n file: GeneratedImageArtifact[\"file\"],\n expected: Pick<ValidatedGeneratedImage, \"sizeBytes\" | \"mediaType\" | \"sha256\">,\n): Promise<void> {\n const head = await retryWhileMissing(async () => {\n if (!(await storage.fileExists(file))) return null;\n return await storage.headFile(file);\n });\n if (!head) throw new Error(\"generated image object is missing\");\n assertStoredGeneratedImageHead(head, expected);\n}\n\nfunction assertStoredGeneratedImageHead(\n head: ObjectHead,\n expected: Pick<ValidatedGeneratedImage, \"sizeBytes\" | \"mediaType\" | \"sha256\">,\n): void {\n if (head.ContentLength !== expected.sizeBytes)\n throw new Error(\"generated image object size mismatch\");\n if (head.ContentType !== expected.mediaType)\n throw new Error(\"generated image object MIME mismatch\");\n if (head.Metadata?.sha256 !== expected.sha256) {\n throw new Error(\"generated image object SHA-256 metadata mismatch\");\n }\n}\n\nfunction uuidFromDigest(digest: string, startByte: number): string {\n const source = Buffer.from(digest, \"hex\");\n const bytes = Uint8Array.from(source.subarray(startByte, startByte + 16));\n bytes[6] = (bytes[6]! & 0x0f) | 0x80;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Buffer.from(bytes).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction base64Sextet(code: number): number {\n if (code >= 0x41 && code <= 0x5a) return code - 0x41;\n if (code >= 0x61 && code <= 0x7a) return code - 0x61 + 26;\n if (code >= 0x30 && code <= 0x39) return code - 0x30 + 52;\n return code === 0x2b ? 62 : 63;\n}\n\nfunction withoutNativeImageResult(value: unknown): unknown {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return value;\n const { result: _result, ...rest } = value as Record<string, unknown>;\n return rest;\n}\n","import {\n COMPUTER_SCREENSHOT_MAX_BYTES,\n COMPUTER_SCREENSHOT_MAX_DIMENSION,\n COMPUTER_SCREENSHOT_MAX_PIXELS,\n COMPUTER_SCREENSHOT_RETENTION_MS,\n COMPUTER_SCREENSHOT_WORKSPACE_QUOTA_BYTES,\n RetainedArtifactMetadataSchema,\n retainedScreenshotReferenceFromFile,\n type RetainedArtifactMetadata,\n type RetainedArtifactReference,\n type RetainedOutputUnavailableReason,\n} from \"@opengeni/contracts\";\nimport {\n RetainedScreenshotQuotaExceededError,\n getRetainedScreenshotArtifact,\n isDatabasePersistenceFailure,\n isSessionEventPersistenceError,\n prepareRetainedScreenshotArtifact,\n recordRetainedScreenshotArtifactError,\n settleRetainedScreenshotArtifactReady,\n type Database,\n type RetainedScreenshotArtifact,\n} from \"@opengeni/db\";\nimport { retryWhileMissing, type ObjectStorage } from \"@opengeni/storage\";\nimport { createHash } from \"node:crypto\";\n\nconst PNG_SIGNATURE = Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a);\nconst PNG_ALLOWED_CRITICAL_CHUNKS = new Set([\"IHDR\", \"PLTE\", \"IDAT\", \"IEND\"]);\nconst PNG_MAX_CHUNKS = 16_384;\nconst RETAINED_IMAGE_MARKER = \"retained_artifact\";\n\nexport type TypedScreenshotToolOutput = {\n callId: string;\n toolOutputId: string;\n bytes: Uint8Array;\n mediaType: string;\n};\n\nexport type ValidatedScreenshot = {\n bytes: Uint8Array;\n mediaType: \"image/png\";\n sizeBytes: number;\n sha256: string;\n width: number;\n height: number;\n};\n\nexport type RetainableSessionImageMediaType = \"image/png\" | \"image/jpeg\" | \"image/webp\";\n\nexport type ValidatedSessionImage = {\n bytes: Uint8Array;\n mediaType: RetainableSessionImageMediaType;\n extension: \"png\" | \"jpg\" | \"webp\";\n sizeBytes: number;\n sha256: string;\n width: number;\n height: number;\n};\n\nexport class ScreenshotValidationError extends Error {\n constructor(\n readonly reason: \"invalid_content\" | \"oversized\" | \"unsupported\",\n message: string,\n ) {\n super(message);\n this.name = \"ScreenshotValidationError\";\n }\n}\n\nexport class RetainedScreenshotUnavailableError extends Error {\n constructor(\n readonly artifactId: string,\n readonly reason: RetainedOutputUnavailableReason,\n ) {\n super(`Retained screenshot ${artifactId} is unavailable: ${reason}`);\n this.name = \"RetainedScreenshotUnavailableError\";\n }\n}\n\n/** Read an intentional image directly at the tool execution boundary. */\nexport function typedScreenshotFromToolOutput(input: {\n callId: string;\n output: unknown;\n}): TypedScreenshotToolOutput | null {\n const image = imageBytesFromSdkToolOutput(input.output);\n if (!image) return null;\n return {\n callId: input.callId,\n toolOutputId: input.callId,\n bytes: image.bytes,\n mediaType: image.mediaType,\n };\n}\n\n/** Read the SDK's trusted typed image before event/history serialization. */\nexport function typedScreenshotFromSdkEvent(event: unknown): TypedScreenshotToolOutput | null {\n if (!event || typeof event !== \"object\") return null;\n const streamEvent = event as {\n type?: unknown;\n item?: {\n id?: unknown;\n type?: unknown;\n rawItem?: unknown;\n output?: unknown;\n };\n };\n if (streamEvent.type !== \"run_item_stream_event\") return null;\n const item = streamEvent.item;\n if (!item || item.type !== \"tool_call_output_item\") return null;\n const image = imageBytesFromSdkToolOutput(item.output);\n if (!image) return null;\n const raw =\n item.rawItem && typeof item.rawItem === \"object\" && !Array.isArray(item.rawItem)\n ? (item.rawItem as Record<string, unknown>)\n : {};\n // Live Agents SDK results can carry the call identity only on the run-item\n // wrapper; reconciled history later copies it into `rawItem`. Use the same\n // fallback as the canonical completed-call extractor so both paths agree.\n const callId = raw.callId ?? raw.call_id ?? item.id;\n if (typeof callId !== \"string\" || callId.length === 0) return null;\n const toolOutputId = raw.id ?? item.id ?? callId;\n if (typeof toolOutputId !== \"string\" || toolOutputId.length === 0) return null;\n return {\n callId,\n toolOutputId,\n bytes: image.bytes,\n mediaType: image.mediaType,\n };\n}\n\n/** Does this SDK result still contain inline bytes that persistence must replace? */\nexport function sdkEventContainsInlineImage(event: unknown): boolean {\n if (!event || typeof event !== \"object\") return false;\n const streamEvent = event as {\n type?: unknown;\n item?: { type?: unknown; output?: unknown };\n };\n return (\n streamEvent.type === \"run_item_stream_event\" &&\n streamEvent.item?.type === \"tool_call_output_item\" &&\n toolOutputContainsInlineImage(streamEvent.item.output)\n );\n}\n\nfunction imageBytesFromSdkToolOutput(\n output: unknown,\n): { bytes: Uint8Array; mediaType: string } | null {\n if (typeof output === \"string\") return decodeInlineImageDataUrl(output);\n if (Array.isArray(output)) {\n for (const entry of output) {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) continue;\n const record = entry as Record<string, unknown>;\n const decoded =\n record.type === \"input_image\"\n ? imageBytesFromSdkImageSource(record.image ?? record.image_url ?? record.imageUrl)\n : record.type === \"image\"\n ? decodeInlineMcpImage(record.data, record.mimeType)\n : null;\n if (decoded) return decoded;\n }\n return null;\n }\n if (!output || typeof output !== \"object\") return null;\n const outputRecord = output as Record<string, unknown>;\n if (Array.isArray(outputRecord.content)) {\n return imageBytesFromSdkToolOutput(outputRecord.content);\n }\n if (\n outputRecord.type !== \"image\" ||\n !outputRecord.image ||\n typeof outputRecord.image !== \"object\" ||\n Array.isArray(outputRecord.image)\n ) {\n return null;\n }\n return imageBytesFromSdkImageSource(outputRecord.image);\n}\n\nfunction imageBytesFromSdkImageSource(\n source: unknown,\n): { bytes: Uint8Array; mediaType: string } | null {\n const direct = decodeInlineImageDataUrl(source);\n if (direct) return direct;\n if (!source || typeof source !== \"object\" || Array.isArray(source)) return null;\n const image = source as Record<string, unknown>;\n const fromUrl = decodeInlineImageDataUrl(image.url);\n if (fromUrl) return fromUrl;\n return image.data instanceof Uint8Array && typeof image.mediaType === \"string\"\n ? { bytes: image.data, mediaType: image.mediaType }\n : null;\n}\n\nfunction sdkImageSourceContainsInlineImage(source: unknown): boolean {\n if (typeof source === \"string\") return source.startsWith(\"data:image/\");\n if (!source || typeof source !== \"object\" || Array.isArray(source)) return false;\n const image = source as Record<string, unknown>;\n return (\n (typeof image.url === \"string\" && image.url.startsWith(\"data:image/\")) ||\n (image.data instanceof Uint8Array && typeof image.mediaType === \"string\")\n );\n}\n\nexport function toolOutputContainsInlineImage(output: unknown): boolean {\n if (typeof output === \"string\") return output.startsWith(\"data:image/\");\n if (Array.isArray(output)) {\n return output.some((entry) => {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return false;\n const record = entry as Record<string, unknown>;\n return (\n (record.type === \"input_image\" &&\n sdkImageSourceContainsInlineImage(record.image ?? record.image_url ?? record.imageUrl)) ||\n (record.type === \"image\" && decodeInlineMcpImage(record.data, record.mimeType) !== null)\n );\n });\n }\n if (!output || typeof output !== \"object\") return false;\n const record = output as Record<string, unknown>;\n if (Array.isArray(record.content)) return toolOutputContainsInlineImage(record.content);\n return record.type === \"image\" && sdkImageSourceContainsInlineImage(record.image);\n}\n\nfunction decodeInlineMcpImage(\n data: unknown,\n mimeType: unknown,\n): { bytes: Uint8Array; mediaType: string } | null {\n if (\n typeof data !== \"string\" ||\n typeof mimeType !== \"string\" ||\n ![\"image/png\", \"image/jpeg\", \"image/webp\"].includes(mimeType)\n ) {\n return null;\n }\n const maxEncodedLength = Math.ceil(COMPUTER_SCREENSHOT_MAX_BYTES / 3) * 4;\n if (\n data.length === 0 ||\n data.length > maxEncodedLength ||\n data.length % 4 !== 0 ||\n !/^[A-Za-z0-9+/]+={0,2}$/u.test(data)\n ) {\n return null;\n }\n const bytes = Uint8Array.from(Buffer.from(data, \"base64\"));\n return bytes.byteLength > 0 && bytes.byteLength <= COMPUTER_SCREENSHOT_MAX_BYTES\n ? { bytes, mediaType: mimeType }\n : null;\n}\n\nfunction decodeInlineImageDataUrl(value: unknown): { bytes: Uint8Array; mediaType: string } | null {\n if (typeof value !== \"string\") return null;\n const match = /^data:(image\\/(?:png|jpeg|webp));base64,/u.exec(value);\n if (!match?.[1]) return null;\n const mediaType = match[1] as RetainableSessionImageMediaType;\n const encoded = value.slice(match[0].length);\n const maxEncodedLength = Math.ceil(COMPUTER_SCREENSHOT_MAX_BYTES / 3) * 4;\n if (\n encoded.length === 0 ||\n encoded.length > maxEncodedLength ||\n encoded.length % 4 !== 0 ||\n !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)\n ) {\n return null;\n }\n const padding = encoded.endsWith(\"==\") ? 2 : encoded.endsWith(\"=\") ? 1 : 0;\n const decodedLength = (encoded.length / 4) * 3 - padding;\n if (decodedLength <= 0 || decodedLength > COMPUTER_SCREENSHOT_MAX_BYTES) {\n return null;\n }\n const lastSextet = base64Sextet(encoded.charCodeAt(encoded.length - padding - 1));\n if (\n (padding === 2 && (lastSextet & 0x0f) !== 0) ||\n (padding === 1 && (lastSextet & 0x03) !== 0)\n ) {\n return null;\n }\n const decoded = Buffer.from(encoded, \"base64\");\n if (decoded.byteLength !== decodedLength) return null;\n const bytes = new Uint8Array(decoded.buffer, decoded.byteOffset, decoded.byteLength);\n return { bytes, mediaType };\n}\n\n/** Validate the complete canonical PNG and derive exact integrity metadata. */\nexport function validateComputerScreenshot(\n input: { bytes: Uint8Array; mediaType: string },\n limits: {\n maxBytes?: number;\n maxDimension?: number;\n maxPixels?: number;\n } = {},\n): ValidatedScreenshot {\n const maxBytes = limits.maxBytes ?? COMPUTER_SCREENSHOT_MAX_BYTES;\n const maxDimension = limits.maxDimension ?? COMPUTER_SCREENSHOT_MAX_DIMENSION;\n const maxPixels = limits.maxPixels ?? COMPUTER_SCREENSHOT_MAX_PIXELS;\n if (input.mediaType !== \"image/png\") {\n throw new ScreenshotValidationError(\n \"unsupported\",\n \"computer screenshot MIME must be image/png\",\n );\n }\n if (input.bytes.byteLength === 0) {\n throw new ScreenshotValidationError(\"invalid_content\", \"computer screenshot is empty\");\n }\n if (input.bytes.byteLength > maxBytes) {\n throw new ScreenshotValidationError(\n \"oversized\",\n `computer screenshot exceeds ${maxBytes} bytes`,\n );\n }\n if (input.bytes.byteLength < PNG_SIGNATURE.byteLength + 25) {\n throw new ScreenshotValidationError(\"invalid_content\", \"computer screenshot PNG is truncated\");\n }\n for (let index = 0; index < PNG_SIGNATURE.byteLength; index += 1) {\n if (input.bytes[index] !== PNG_SIGNATURE[index]) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG signature is invalid\",\n );\n }\n }\n\n let offset = PNG_SIGNATURE.byteLength;\n let chunks = 0;\n let width = 0;\n let height = 0;\n let sawIhdr = false;\n let sawIdat = false;\n let endedIdat = false;\n let sawIend = false;\n while (offset < input.bytes.byteLength) {\n chunks += 1;\n if (chunks > PNG_MAX_CHUNKS || offset + 12 > input.bytes.byteLength) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG chunk table is invalid\",\n );\n }\n const length = readUint32(input.bytes, offset);\n const typeOffset = offset + 4;\n const dataOffset = typeOffset + 4;\n const dataEnd = dataOffset + length;\n const crcOffset = dataEnd;\n const nextOffset = crcOffset + 4;\n if (!Number.isSafeInteger(nextOffset) || nextOffset > input.bytes.byteLength) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG chunk is truncated\",\n );\n }\n const type = asciiChunkType(input.bytes, typeOffset);\n const expectedCrc = readUint32(input.bytes, crcOffset);\n const actualCrc = crc32(input.bytes.subarray(typeOffset, dataEnd));\n if (expectedCrc !== actualCrc) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n `computer screenshot PNG ${type} CRC is invalid`,\n );\n }\n if (chunks === 1 && type !== \"IHDR\") {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG must begin with IHDR\",\n );\n }\n if (isCriticalChunk(type) && !PNG_ALLOWED_CRITICAL_CHUNKS.has(type)) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n `computer screenshot PNG has unsupported critical chunk ${type}`,\n );\n }\n\n if (type === \"IHDR\") {\n if (sawIhdr || length !== 13) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG IHDR is invalid\",\n );\n }\n sawIhdr = true;\n width = readUint32(input.bytes, dataOffset);\n height = readUint32(input.bytes, dataOffset + 4);\n const bitDepth = input.bytes[dataOffset + 8];\n const colorType = input.bytes[dataOffset + 9];\n const compression = input.bytes[dataOffset + 10];\n const filter = input.bytes[dataOffset + 11];\n const interlace = input.bytes[dataOffset + 12];\n if (\n !validPngColorMode(bitDepth, colorType) ||\n compression !== 0 ||\n filter !== 0 ||\n (interlace !== 0 && interlace !== 1)\n ) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG IHDR fields are invalid\",\n );\n }\n if (\n width <= 0 ||\n height <= 0 ||\n width > maxDimension ||\n height > maxDimension ||\n width * height > maxPixels\n ) {\n throw new ScreenshotValidationError(\n \"oversized\",\n \"computer screenshot dimensions exceed policy\",\n );\n }\n } else if (type === \"IDAT\") {\n if (!sawIhdr || sawIend || endedIdat || length === 0) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG IDAT ordering is invalid\",\n );\n }\n sawIdat = true;\n } else if (sawIdat && type !== \"IEND\") {\n endedIdat = true;\n }\n\n if (type === \"IEND\") {\n if (!sawIhdr || !sawIdat || sawIend || length !== 0) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG IEND is invalid\",\n );\n }\n sawIend = true;\n if (nextOffset !== input.bytes.byteLength) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG has trailing/polyglot bytes\",\n );\n }\n }\n offset = nextOffset;\n }\n if (!sawIhdr || !sawIdat || !sawIend || offset !== input.bytes.byteLength) {\n throw new ScreenshotValidationError(\"invalid_content\", \"computer screenshot PNG is incomplete\");\n }\n return {\n bytes: input.bytes,\n mediaType: \"image/png\",\n sizeBytes: input.bytes.byteLength,\n sha256: createHash(\"sha256\").update(input.bytes).digest(\"hex\"),\n width,\n height,\n };\n}\n\n/** Validate a durable view_image/computer image from bytes, never from its claimed MIME alone. */\nexport function validateRetainableSessionImage(\n input: { bytes: Uint8Array; declaredMediaType?: string },\n limits: {\n maxBytes?: number;\n maxDimension?: number;\n maxPixels?: number;\n } = {},\n): ValidatedSessionImage {\n const maxBytes = limits.maxBytes ?? COMPUTER_SCREENSHOT_MAX_BYTES;\n const maxDimension = limits.maxDimension ?? COMPUTER_SCREENSHOT_MAX_DIMENSION;\n const maxPixels = limits.maxPixels ?? COMPUTER_SCREENSHOT_MAX_PIXELS;\n if (input.bytes.byteLength === 0) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session image is empty\");\n }\n if (input.bytes.byteLength > maxBytes) {\n throw new ScreenshotValidationError(\"oversized\", `session image exceeds ${maxBytes} bytes`);\n }\n\n let identity: Pick<ValidatedSessionImage, \"mediaType\" | \"extension\" | \"width\" | \"height\">;\n if (isPng(input.bytes)) {\n const png = validateComputerScreenshot(\n { bytes: input.bytes, mediaType: \"image/png\" },\n { maxBytes, maxDimension, maxPixels },\n );\n identity = {\n mediaType: \"image/png\",\n extension: \"png\",\n width: png.width,\n height: png.height,\n };\n } else if (isJpeg(input.bytes)) {\n identity = {\n mediaType: \"image/jpeg\",\n extension: \"jpg\",\n ...jpegDimensions(input.bytes),\n };\n } else if (isWebp(input.bytes)) {\n identity = {\n mediaType: \"image/webp\",\n extension: \"webp\",\n ...webpDimensions(input.bytes),\n };\n } else {\n throw new ScreenshotValidationError(\"unsupported\", \"session image format is unsupported\");\n }\n assertImageDimensions(identity.width, identity.height, {\n maxDimension,\n maxPixels,\n });\n if (\n input.declaredMediaType &&\n canonicalMediaType(input.declaredMediaType) !== identity.mediaType\n ) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"session image MIME does not match its bytes\",\n );\n }\n return {\n bytes: input.bytes,\n ...identity,\n sizeBytes: input.bytes.byteLength,\n sha256: createHash(\"sha256\").update(input.bytes).digest(\"hex\"),\n };\n}\n\nexport function retainedScreenshotIdentity(input: {\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n toolOutputId: string;\n}): { artifactId: string; settlementKey: string } {\n const settlementKey = createHash(\"sha256\")\n .update(\"opengeni:computer-screenshot:v1\\0\")\n .update(input.sessionId)\n .update(\"\\0\")\n .update(input.turnId)\n .update(\"\\0\")\n .update(input.attemptId)\n .update(\"\\0\")\n .update(input.toolCallId)\n .update(\"\\0\")\n .update(input.toolOutputId)\n .digest(\"hex\");\n const uuidBytes = Uint8Array.from(Buffer.from(settlementKey.slice(0, 32), \"hex\"));\n uuidBytes[6] = (uuidBytes[6]! & 0x0f) | 0x80;\n uuidBytes[8] = (uuidBytes[8]! & 0x3f) | 0x80;\n const hex = Buffer.from(uuidBytes).toString(\"hex\");\n return {\n artifactId: `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`,\n settlementKey,\n };\n}\n\n/** Deterministic fail-closed receipt installed before retention can perform I/O. */\nexport function unavailableRetainedSessionImage(input: {\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n toolOutputId: string;\n reason: RetainedOutputUnavailableReason;\n}): RetainedArtifactMetadata {\n const identity = retainedScreenshotIdentity(input);\n return unavailable(identity.artifactId, input.reason);\n}\n\nexport async function retainComputerScreenshot(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n output: TypedScreenshotToolOutput;\n now?: Date;\n retentionMs?: number;\n workspaceQuotaBytes?: number;\n}): Promise<RetainedArtifactMetadata> {\n const identity = retainedScreenshotIdentity({\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n toolCallId: input.output.callId,\n toolOutputId: input.output.toolOutputId,\n });\n let screenshot: ValidatedSessionImage;\n try {\n screenshot = validateRetainableSessionImage({\n bytes: input.output.bytes,\n declaredMediaType: input.output.mediaType,\n });\n } catch (error) {\n if (error instanceof ScreenshotValidationError) {\n return unavailable(identity.artifactId, error.reason);\n }\n throw error;\n }\n if (!input.objectStorage) return unavailable(identity.artifactId, \"missing_storage\");\n\n const now = input.now ?? new Date();\n const retentionExpiresAt = new Date(\n now.getTime() + (input.retentionMs ?? COMPUTER_SCREENSHOT_RETENTION_MS),\n );\n const objectKey = `workspaces/${input.workspaceId}/files/${identity.artifactId}/retained/session-image.${screenshot.extension}`;\n let prepared: RetainedScreenshotArtifact;\n try {\n prepared = (\n await prepareRetainedScreenshotArtifact(input.db, {\n artifactId: identity.artifactId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n settlementKey: identity.settlementKey,\n toolCallId: input.output.callId,\n toolOutputId: input.output.toolOutputId,\n mediaType: screenshot.mediaType,\n sizeBytes: screenshot.sizeBytes,\n sha256: screenshot.sha256,\n width: screenshot.width,\n height: screenshot.height,\n retentionExpiresAt,\n bucket: input.objectStorage.bucket,\n objectKey,\n workspaceQuotaBytes: input.workspaceQuotaBytes ?? COMPUTER_SCREENSHOT_WORKSPACE_QUOTA_BYTES,\n })\n ).artifact;\n } catch (error) {\n if (error instanceof RetainedScreenshotQuotaExceededError) {\n return unavailable(identity.artifactId, \"quota_exceeded\");\n }\n if (isSessionEventPersistenceError(error) || isDatabasePersistenceFailure(error)) {\n return unavailable(identity.artifactId, \"pending\");\n }\n throw error;\n }\n\n if (prepared.status === \"ready\") {\n return reference(prepared);\n }\n if (prepared.status !== \"pending\" && prepared.status !== \"reconciling\") {\n return unavailable(identity.artifactId, unavailableReasonForStatus(prepared.status));\n }\n\n try {\n await input.objectStorage.putObject({\n key: objectKey,\n contentType: screenshot.mediaType,\n body: screenshot.bytes,\n sha256: screenshot.sha256,\n });\n } catch (error) {\n await recordRetainedScreenshotArtifactError(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: identity.artifactId,\n settlementKey: identity.settlementKey,\n error: error instanceof Error ? error.message : String(error),\n }).catch(() => undefined);\n return unavailable(identity.artifactId, \"storage_write_failed\");\n }\n\n try {\n const settled = await settleRetainedScreenshotArtifactReady(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: identity.artifactId,\n settlementKey: identity.settlementKey,\n });\n return reference(settled);\n } catch (error) {\n // PUT completed. If a concurrent cascade removed the deterministic intent,\n // compensate the now-unreferenced key. Otherwise leave the pending row for\n // exact retry/background reconciliation instead of deleting live truth.\n const stillReferenced = await getRetainedScreenshotArtifact(\n input.db,\n input.workspaceId,\n input.sessionId,\n identity.artifactId,\n ).catch(() => undefined);\n if (stillReferenced?.status === \"ready\") {\n return reference(stillReferenced);\n }\n if (\n stillReferenced === null ||\n stillReferenced?.status === \"cleanup_queued\" ||\n stillReferenced?.status === \"cleanup_pending\" ||\n stillReferenced?.status === \"failed\" ||\n stillReferenced?.status === \"expired\" ||\n stillReferenced?.status === \"deleted\"\n ) {\n await input.objectStorage.deleteObject(objectKey).catch(() => undefined);\n } else if (stillReferenced) {\n await recordRetainedScreenshotArtifactError(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: identity.artifactId,\n settlementKey: identity.settlementKey,\n error: error instanceof Error ? error.message : String(error),\n }).catch(() => undefined);\n }\n return unavailable(identity.artifactId, \"pending\");\n }\n}\n\n/** Replace only new screenshot bytes with a compact receipt before first persistence. */\nexport function compactRetainedScreenshotHistory(\n history: Array<Record<string, unknown>>,\n receiptsByCallId: ReadonlyMap<string, RetainedArtifactMetadata>,\n): Array<Record<string, unknown>> {\n if (receiptsByCallId.size === 0) return history;\n return history.map((item) => {\n const callId = historyCallId(item);\n const receipt = callId ? receiptsByCallId.get(callId) : undefined;\n if (!receipt) return item;\n if (typeof item.output === \"string\" && item.output.startsWith(\"data:image/\")) {\n return {\n ...item,\n output: { type: RETAINED_IMAGE_MARKER, artifact: receipt },\n };\n }\n if (\n item.output &&\n typeof item.output === \"object\" &&\n !Array.isArray(item.output) &&\n Array.isArray((item.output as Record<string, unknown>).content)\n ) {\n const result = item.output as Record<string, unknown>;\n const content = compactInlineImageContent(result.content as unknown[], receipt);\n return content.changed ? { ...item, output: { ...result, content: content.entries } } : item;\n }\n if (!Array.isArray(item.output)) return item;\n const output = compactInlineImageContent(item.output, receipt);\n return output.changed ? { ...item, output: output.entries } : item;\n });\n}\n\nfunction compactInlineImageContent(\n entries: unknown[],\n receipt: RetainedArtifactMetadata,\n): { entries: unknown[]; changed: boolean } {\n let changed = false;\n const compacted = entries.map((entry) => {\n if (!isInlineImageContent(entry)) return entry;\n changed = true;\n const record = entry as Record<string, unknown>;\n if (record.type === \"image\") {\n return {\n type: \"input_image\",\n image: { type: RETAINED_IMAGE_MARKER, artifact: receipt },\n };\n }\n return {\n ...record,\n image: { type: RETAINED_IMAGE_MARKER, artifact: receipt },\n };\n });\n return { entries: compacted, changed };\n}\n\n/** Collect durable screenshot receipts before their provider-only expansion. */\nexport function collectRetainedScreenshotReceipts(\n history: ReadonlyArray<Record<string, unknown>>,\n target: Map<string, RetainedArtifactMetadata> = new Map(),\n): Map<string, RetainedArtifactMetadata> {\n for (const item of history) {\n const callId = historyCallId(item);\n if (!callId) continue;\n const direct = retainedReceiptFromDirectOutput(item.output);\n if (direct) {\n target.set(callId, direct);\n continue;\n }\n const outputEntries = Array.isArray(item.output)\n ? item.output\n : item.output &&\n typeof item.output === \"object\" &&\n !Array.isArray(item.output) &&\n Array.isArray((item.output as Record<string, unknown>).content)\n ? ((item.output as Record<string, unknown>).content as unknown[])\n : null;\n if (!outputEntries) continue;\n for (const entry of outputEntries) {\n const receipt = retainedReceiptFromImageContent(entry);\n if (receipt) {\n target.set(callId, receipt);\n break;\n }\n }\n }\n return target;\n}\n\n/**\n * Compact every protocol-item copy inside an SDK RunState before persistence.\n * The traversal intentionally mirrors the repository's existing serialized\n * RunState sanitizers. A parse failure or no-op returns the original string.\n */\nexport function compactRetainedScreenshotRunState(\n serialized: string,\n receiptsByCallId: ReadonlyMap<string, RetainedArtifactMetadata>,\n): string {\n if (receiptsByCallId.size === 0) return serialized;\n const parsed = parseSerializedRunState(serialized);\n if (!parsed) return serialized;\n let changed = false;\n visitSerializedRunStateItemArrays(parsed, (items) => {\n const compacted = compactRetainedScreenshotHistory(items, receiptsByCallId);\n if (compacted !== items && compacted.some((item, index) => item !== items[index])) {\n items.splice(0, items.length, ...compacted);\n changed = true;\n }\n });\n return changed ? JSON.stringify(parsed) : serialized;\n}\n\nexport function collectRetainedScreenshotRunStateReceipts(\n serialized: string,\n target: Map<string, RetainedArtifactMetadata> = new Map(),\n): Map<string, RetainedArtifactMetadata> {\n const parsed = parseSerializedRunState(serialized);\n if (!parsed) return target;\n visitSerializedRunStateItemArrays(parsed, (items) => {\n collectRetainedScreenshotReceipts(items, target);\n });\n return target;\n}\n\n/**\n * Materialize canonical receipts to the exact SDK input_image data URL shape.\n * Missing/deleted/expired/corrupt bytes fail closed; no item is omitted,\n * reordered, rewritten in storage, or converted to text.\n */\nexport async function materializeRetainedScreenshotHistory(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n workspaceId: string;\n sessionId: string;\n history: Array<Record<string, unknown>>;\n now?: Date;\n}): Promise<Array<Record<string, unknown>>> {\n return await materializeRetainedScreenshotHistoryWithCache(input, new Map());\n}\n\n/** Expand durable markers in an SDK RunState immediately before resume. */\nexport async function materializeRetainedScreenshotRunState(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n workspaceId: string;\n sessionId: string;\n serialized: string;\n now?: Date;\n}): Promise<string> {\n const parsed = parseSerializedRunState(input.serialized);\n if (!parsed) return input.serialized;\n const cache = new Map<string, string>();\n let changed = false;\n await visitSerializedRunStateItemArraysAsync(parsed, async (items) => {\n const materialized = await materializeRetainedScreenshotHistoryWithCache(\n { ...input, history: items },\n cache,\n );\n if (materialized.some((item, index) => item !== items[index])) {\n items.splice(0, items.length, ...materialized);\n changed = true;\n }\n });\n return changed ? JSON.stringify(parsed) : input.serialized;\n}\n\nasync function materializeRetainedScreenshotHistoryWithCache(\n input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n workspaceId: string;\n sessionId: string;\n history: Array<Record<string, unknown>>;\n now?: Date;\n },\n cache: Map<string, string>,\n): Promise<Array<Record<string, unknown>>> {\n const now = input.now ?? new Date();\n const dataUrlForReceipt = async (receipt: RetainedArtifactMetadata): Promise<string> => {\n let dataUrl = cache.get(receipt.artifactId);\n if (!dataUrl) {\n if (!input.objectStorage) {\n throw new RetainedScreenshotUnavailableError(receipt.artifactId, \"missing_storage\");\n }\n const artifact = await getRetainedScreenshotArtifact(\n input.db,\n input.workspaceId,\n input.sessionId,\n receipt.artifactId,\n );\n if (!artifact) throw new RetainedScreenshotUnavailableError(receipt.artifactId, \"deleted\");\n if (artifact.status !== \"ready\") {\n throw new RetainedScreenshotUnavailableError(\n receipt.artifactId,\n unavailableReasonForStatus(artifact.status),\n );\n }\n if (artifact.retentionExpiresAt.getTime() <= now.getTime()) {\n throw new RetainedScreenshotUnavailableError(receipt.artifactId, \"expired\");\n }\n const object = await retryWhileMissing(async () =>\n input.objectStorage!.getObjectBytes(artifact.file.objectKey),\n );\n if (!object)\n throw new RetainedScreenshotUnavailableError(receipt.artifactId, \"missing_storage\");\n const bytes = object.bytes;\n const validated = validateRetainableSessionImage({\n bytes,\n declaredMediaType: artifact.mediaType,\n });\n if (\n validated.sizeBytes !== artifact.sizeBytes ||\n validated.sha256 !== artifact.sha256 ||\n validated.width !== artifact.width ||\n validated.height !== artifact.height ||\n (receipt.available &&\n (receipt.sha256 !== artifact.sha256 || receipt.originalBytes !== artifact.sizeBytes))\n ) {\n throw new RetainedScreenshotUnavailableError(receipt.artifactId, \"invalid_content\");\n }\n dataUrl = `data:${validated.mediaType};base64,${Buffer.from(validated.bytes).toString(\"base64\")}`;\n cache.set(receipt.artifactId, dataUrl);\n }\n return dataUrl;\n };\n const materializeEntry = async (entry: unknown): Promise<unknown> => {\n const receipt = retainedReceiptFromImageContent(entry);\n if (!receipt) return entry;\n const dataUrl = await dataUrlForReceipt(receipt);\n return { ...(entry as Record<string, unknown>), image: dataUrl };\n };\n\n const materialized: Array<Record<string, unknown>> = [];\n for (const item of input.history) {\n const directReceipt = retainedReceiptFromDirectOutput(item.output);\n if (directReceipt) {\n materialized.push({\n ...item,\n output: await dataUrlForReceipt(directReceipt),\n });\n continue;\n }\n const resultOutput =\n item.output && typeof item.output === \"object\" && !Array.isArray(item.output)\n ? (item.output as Record<string, unknown>)\n : null;\n const outputEntries = Array.isArray(item.output)\n ? item.output\n : resultOutput && Array.isArray(resultOutput.content)\n ? resultOutput.content\n : null;\n if (!outputEntries) {\n materialized.push(item);\n continue;\n }\n let changed = false;\n const output: unknown[] = [];\n for (const entry of outputEntries) {\n const next = await materializeEntry(entry);\n changed ||= next !== entry;\n output.push(next);\n }\n materialized.push(\n changed\n ? {\n ...item,\n output: resultOutput ? { ...resultOutput, content: output } : output,\n }\n : item,\n );\n }\n return materialized;\n}\n\nfunction parseSerializedRunState(serialized: string): Record<string, unknown> | null {\n try {\n const parsed: unknown = JSON.parse(serialized);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nfunction visitSerializedRunStateItemArrays(\n root: Record<string, unknown>,\n visitor: (items: Array<Record<string, unknown>>) => void,\n): void {\n const originalInput = root.originalInput;\n if (Array.isArray(originalInput)) {\n visitor(originalInput as Array<Record<string, unknown>>);\n }\n if (Array.isArray(root.generatedItems)) {\n for (const wrapper of root.generatedItems) {\n if (!wrapper || typeof wrapper !== \"object\" || Array.isArray(wrapper)) continue;\n const record = wrapper as Record<string, unknown>;\n const rawItem = record.rawItem;\n if (!rawItem || typeof rawItem !== \"object\" || Array.isArray(rawItem)) continue;\n const items = [rawItem as Record<string, unknown>];\n visitor(items);\n if (items[0] !== rawItem) record.rawItem = items[0];\n }\n }\n if (Array.isArray(root.modelResponses)) {\n for (const response of root.modelResponses) {\n if (!response || typeof response !== \"object\" || Array.isArray(response)) continue;\n const output = (response as Record<string, unknown>).output;\n if (Array.isArray(output)) visitor(output as Array<Record<string, unknown>>);\n }\n }\n const lastModelResponse = root.lastModelResponse;\n if (\n lastModelResponse &&\n typeof lastModelResponse === \"object\" &&\n !Array.isArray(lastModelResponse)\n ) {\n const output = (lastModelResponse as Record<string, unknown>).output;\n if (Array.isArray(output)) visitor(output as Array<Record<string, unknown>>);\n }\n}\n\nasync function visitSerializedRunStateItemArraysAsync(\n root: Record<string, unknown>,\n visitor: (items: Array<Record<string, unknown>>) => Promise<void>,\n): Promise<void> {\n const originalInput = root.originalInput;\n if (Array.isArray(originalInput)) {\n await visitor(originalInput as Array<Record<string, unknown>>);\n }\n if (Array.isArray(root.generatedItems)) {\n for (const wrapper of root.generatedItems) {\n if (!wrapper || typeof wrapper !== \"object\" || Array.isArray(wrapper)) continue;\n const record = wrapper as Record<string, unknown>;\n const rawItem = record.rawItem;\n if (!rawItem || typeof rawItem !== \"object\" || Array.isArray(rawItem)) continue;\n const items = [rawItem as Record<string, unknown>];\n await visitor(items);\n if (items[0] !== rawItem) record.rawItem = items[0];\n }\n }\n if (Array.isArray(root.modelResponses)) {\n for (const response of root.modelResponses) {\n if (!response || typeof response !== \"object\" || Array.isArray(response)) continue;\n const output = (response as Record<string, unknown>).output;\n if (Array.isArray(output)) await visitor(output as Array<Record<string, unknown>>);\n }\n }\n const lastModelResponse = root.lastModelResponse;\n if (\n lastModelResponse &&\n typeof lastModelResponse === \"object\" &&\n !Array.isArray(lastModelResponse)\n ) {\n const output = (lastModelResponse as Record<string, unknown>).output;\n if (Array.isArray(output)) await visitor(output as Array<Record<string, unknown>>);\n }\n}\n\nfunction reference(artifact: RetainedScreenshotArtifact): RetainedArtifactReference {\n if (!artifact.sessionId) {\n throw new Error(`Ready retained screenshot is detached: ${artifact.artifactId}`);\n }\n const value = retainedScreenshotReferenceFromFile({\n ...artifact.file,\n sessionId: artifact.sessionId,\n width: artifact.width,\n height: artifact.height,\n expiresAt: artifact.retentionExpiresAt.toISOString(),\n });\n if (!value)\n throw new Error(`Ready retained screenshot receipt is invalid: ${artifact.artifactId}`);\n return value;\n}\n\nfunction unavailable(\n artifactId: string,\n reason: RetainedOutputUnavailableReason,\n): RetainedArtifactMetadata {\n return RetainedArtifactMetadataSchema.parse({\n available: false,\n artifactId,\n reason,\n });\n}\n\nfunction unavailableReasonForStatus(\n status: RetainedScreenshotArtifact[\"status\"],\n): RetainedOutputUnavailableReason {\n switch (status) {\n case \"pending\":\n case \"reconciling\":\n return \"pending\";\n case \"cleanup_queued\":\n case \"cleanup_pending\":\n return \"failed\";\n case \"failed\":\n case \"expired\":\n case \"deleted\":\n return status;\n case \"ready\":\n return \"missing_storage\";\n }\n}\n\nfunction retainedReceiptFromImageContent(entry: unknown): RetainedArtifactMetadata | null {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return null;\n const image = (entry as Record<string, unknown>).image;\n if (!image || typeof image !== \"object\" || Array.isArray(image)) return null;\n const marker = image as Record<string, unknown>;\n if (marker.type !== RETAINED_IMAGE_MARKER) return null;\n return retainedReceipt(marker.artifact);\n}\n\nfunction retainedReceiptFromDirectOutput(output: unknown): RetainedArtifactMetadata | null {\n if (!output || typeof output !== \"object\" || Array.isArray(output)) return null;\n const marker = output as Record<string, unknown>;\n if (marker.type !== RETAINED_IMAGE_MARKER) return null;\n return retainedReceipt(marker.artifact);\n}\n\nfunction retainedReceipt(value: unknown): RetainedArtifactMetadata | null {\n const parsed = RetainedArtifactMetadataSchema.safeParse(value);\n if (!parsed.success) return null;\n return parsed.data.available && parsed.data.kind !== \"computer_screenshot\" ? null : parsed.data;\n}\n\nfunction isInlineImageContent(entry: unknown): boolean {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return false;\n const record = entry as Record<string, unknown>;\n return (\n (record.type === \"input_image\" &&\n typeof record.image === \"string\" &&\n record.image.startsWith(\"data:image/\")) ||\n (record.type === \"image\" && decodeInlineMcpImage(record.data, record.mimeType) !== null)\n );\n}\n\nfunction historyCallId(item: Record<string, unknown>): string | null {\n const value = item.callId ?? item.call_id;\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction canonicalMediaType(value: string): string {\n return value.split(\";\", 1)[0]!.trim().toLowerCase();\n}\n\nfunction isPng(bytes: Uint8Array): boolean {\n return (\n bytes.byteLength >= PNG_SIGNATURE.byteLength &&\n PNG_SIGNATURE.every((byte, index) => bytes[index] === byte)\n );\n}\n\nfunction isJpeg(bytes: Uint8Array): boolean {\n return bytes.byteLength >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8;\n}\n\nfunction jpegDimensions(bytes: Uint8Array): { width: number; height: number } {\n if (bytes[bytes.length - 2] !== 0xff || bytes[bytes.length - 1] !== 0xd9) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"session JPEG is truncated or has trailing bytes\",\n );\n }\n let offset = 2;\n while (offset + 4 <= bytes.length) {\n if (bytes[offset] !== 0xff) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"session JPEG marker table is invalid\",\n );\n }\n while (bytes[offset] === 0xff) offset += 1;\n const marker = bytes[offset++];\n if (marker === undefined || marker === 0xd9 || marker === 0xda) break;\n if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;\n if (offset + 2 > bytes.length) break;\n const length = readUint16Be(bytes, offset);\n if (length < 2 || offset + length > bytes.length) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session JPEG segment is invalid\");\n }\n if (JPEG_SOF_MARKERS.has(marker)) {\n if (length < 7) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session JPEG frame is invalid\");\n }\n return {\n height: readUint16Be(bytes, offset + 3),\n width: readUint16Be(bytes, offset + 5),\n };\n }\n offset += length;\n }\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"session JPEG has no supported frame header\",\n );\n}\n\nconst JPEG_SOF_MARKERS = new Set([\n 0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,\n]);\n\nfunction isWebp(bytes: Uint8Array): boolean {\n return bytes.byteLength >= 20 && ascii(bytes, 0, 4) === \"RIFF\" && ascii(bytes, 8, 4) === \"WEBP\";\n}\n\nfunction webpDimensions(bytes: Uint8Array): { width: number; height: number } {\n if (readUint32Le(bytes, 4) + 8 !== bytes.byteLength) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session WebP RIFF length is invalid\");\n }\n let offset = 12;\n while (offset + 8 <= bytes.length) {\n const type = ascii(bytes, offset, 4);\n const length = readUint32Le(bytes, offset + 4);\n const data = offset + 8;\n const next = data + length + (length & 1);\n if (next > bytes.length) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session WebP chunk is truncated\");\n }\n if (type === \"VP8X\") {\n if (length < 10) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session WebP VP8X is invalid\");\n }\n return {\n width: 1 + readUint24Le(bytes, data + 4),\n height: 1 + readUint24Le(bytes, data + 7),\n };\n }\n if (type === \"VP8 \") {\n if (\n length < 10 ||\n bytes[data + 3] !== 0x9d ||\n bytes[data + 4] !== 0x01 ||\n bytes[data + 5] !== 0x2a\n ) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session WebP VP8 frame is invalid\");\n }\n return {\n width: readUint16Le(bytes, data + 6) & 0x3fff,\n height: readUint16Le(bytes, data + 8) & 0x3fff,\n };\n }\n if (type === \"VP8L\") {\n if (length < 5 || bytes[data] !== 0x2f) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"session WebP VP8L frame is invalid\",\n );\n }\n const bits = readUint32Le(bytes, data + 1);\n return {\n width: 1 + (bits & 0x3fff),\n height: 1 + ((bits >>> 14) & 0x3fff),\n };\n }\n offset = next;\n }\n throw new ScreenshotValidationError(\"invalid_content\", \"session WebP has no image frame\");\n}\n\nfunction assertImageDimensions(\n width: number,\n height: number,\n limits: { maxDimension: number; maxPixels: number },\n): void {\n if (\n !Number.isSafeInteger(width) ||\n !Number.isSafeInteger(height) ||\n width <= 0 ||\n height <= 0 ||\n width > limits.maxDimension ||\n height > limits.maxDimension ||\n width * height > limits.maxPixels\n ) {\n throw new ScreenshotValidationError(\"oversized\", \"session image dimensions exceed policy\");\n }\n}\n\nfunction readUint16Be(bytes: Uint8Array, offset: number): number {\n return (bytes[offset]! << 8) | bytes[offset + 1]!;\n}\n\nfunction readUint16Le(bytes: Uint8Array, offset: number): number {\n return bytes[offset]! | (bytes[offset + 1]! << 8);\n}\n\nfunction readUint24Le(bytes: Uint8Array, offset: number): number {\n return bytes[offset]! | (bytes[offset + 1]! << 8) | (bytes[offset + 2]! << 16);\n}\n\nfunction readUint32Le(bytes: Uint8Array, offset: number): number {\n return (\n (bytes[offset]! |\n (bytes[offset + 1]! << 8) |\n (bytes[offset + 2]! << 16) |\n (bytes[offset + 3]! << 24)) >>>\n 0\n );\n}\n\nfunction ascii(bytes: Uint8Array, offset: number, length: number): string {\n return String.fromCharCode(...bytes.subarray(offset, offset + length));\n}\n\nfunction base64Sextet(code: number): number {\n if (code >= 0x41 && code <= 0x5a) return code - 0x41;\n if (code >= 0x61 && code <= 0x7a) return code - 0x61 + 26;\n if (code >= 0x30 && code <= 0x39) return code - 0x30 + 52;\n return code === 0x2b ? 62 : 63;\n}\n\nfunction readUint32(bytes: Uint8Array, offset: number): number {\n return (\n ((bytes[offset]! << 24) |\n (bytes[offset + 1]! << 16) |\n (bytes[offset + 2]! << 8) |\n bytes[offset + 3]!) >>>\n 0\n );\n}\n\nfunction asciiChunkType(bytes: Uint8Array, offset: number): string {\n const chars = [bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]];\n if (\n chars.some(\n (value) => value === undefined || value < 65 || (value > 90 && value < 97) || value > 122,\n )\n ) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG chunk type is invalid\",\n );\n }\n return String.fromCharCode(...(chars as number[]));\n}\n\nfunction isCriticalChunk(type: string): boolean {\n return type.charCodeAt(0) >= 65 && type.charCodeAt(0) <= 90;\n}\n\nfunction validPngColorMode(bitDepth: number | undefined, colorType: number | undefined): boolean {\n if (bitDepth === undefined || colorType === undefined) return false;\n switch (colorType) {\n case 0:\n return [1, 2, 4, 8, 16].includes(bitDepth);\n case 2:\n case 4:\n case 6:\n return bitDepth === 8 || bitDepth === 16;\n case 3:\n return [1, 2, 4, 8].includes(bitDepth);\n default:\n return false;\n }\n}\n\nconst CRC32_TABLE = Uint32Array.from({ length: 256 }, (_, value) => {\n let current = value;\n for (let bit = 0; bit < 8; bit += 1) {\n current = (current & 1) !== 0 ? 0xedb88320 ^ (current >>> 1) : current >>> 1;\n }\n return current >>> 0;\n});\n\nfunction crc32(bytes: Uint8Array): number {\n let crc = 0xffffffff;\n for (const byte of bytes) crc = CRC32_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n","import { appendSessionHistoryItems, upsertSandboxSessionEnvelope } from \"@opengeni/db\";\nimport { sandboxStateEntryFromRunState, type OpenGeniRuntime } from \"@opengeni/runtime\";\nimport type { Settings } from \"@opengeni/config\";\nimport { TurnAttemptFencedError } from \"../turn-attempt-fenced\";\nimport type { SharedActivityServices } from \"../types\";\nimport { compactGeneratedImageHistory } from \"../generated-images\";\nimport { compactRetainedScreenshotHistory } from \"../retained-screenshots\";\nimport type { turnInput } from \"../run-input\";\nimport { safeErrorDiagnostic } from \"./errors\";\nimport { historyRowsToAppend, isModelOrToolProgressHistoryItem } from \"./history\";\nimport { runMandatoryHistoryPersistenceStep } from \"./quiescence\";\nimport type { TurnMediaArtifacts } from \"./media-artifacts\";\nimport { HistoryPrefixGuard } from \"./history-prefix\";\n\nexport type TurnHistorySinkDeps = {\n db: SharedActivityServices[\"db\"];\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n media: TurnMediaArtifacts;\n getTurnId: () => string | undefined;\n getStream: () => Awaited<ReturnType<OpenGeniRuntime[\"runStream\"]>> | undefined;\n getModelRunSettings: () => Settings;\n getExecutionGeneration: () => number;\n};\n\n/**\n * Dual-write of conversation truth (issue #35): completed items are reconciled\n * into session_history_items after every model response and at every turn-end\n * path (idempotent on position), and the sandbox recovery envelope is upserted\n * alongside. Provider dispatch and settlement require durable persistence;\n * the prefix guard rejects SDK history removal/reordering before slicing.\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 settling\n * result yet is transiently ABSENT from history and a later reconcile sees a\n * DIFFERENT, shorter/reordered list. A blind length watermark with\n * onConflictDoNothing-on-position then freezes the first shape of a position\n * and can persist a `function_call_result` at a tail position while its\n * `function_call` was pruned away in an earlier slice and never written — the\n * orphan that bricks the session. We defend against it at the stream boundary\n * with the turn-scoped pending-tool ledger. A partial parallel batch records\n * raw results but does not call this reconciler. Once every registered call has\n * a result, the SDK history is stable and this scalar append watermark is valid\n * again. The sanitizer remains the final call/result pairing guard for every\n * other reconcile.\n */\nexport class TurnHistorySink {\n private readonly prefix = new HistoryPrefixGuard();\n\n seedHistory(input: string | readonly unknown[] | { readonly history: unknown[] }, count: number) {\n const items =\n typeof input === \"string\" && count === 0\n ? []\n : Array.isArray(input)\n ? input\n : (input as { history?: unknown[] })?.history;\n if (!Array.isArray(items)) throw new Error(\"Conversation history seed is unavailable\");\n this.prefix.seed(\n items as Array<Record<string, unknown>>,\n count,\n this.deps.getModelRunSettings().modelToolOutputTruncationTokens,\n );\n this.persistedHistoryCount = count;\n }\n persistedHistoryCount = 0;\n nextHistoryPosition = 0;\n providerArtifactCandidates: Awaited<ReturnType<typeof turnInput>>[\"providerArtifactCandidates\"] =\n {\n knownHistoryItemIds: [],\n historyItemIds: [],\n };\n\n constructor(private readonly deps: TurnHistorySinkDeps) {}\n\n reconcileConversationTruth = async (\n options: { skipInputOnlyRows?: boolean; requireDurable?: boolean } = {},\n ) => {\n const { media } = this.deps;\n const stream = this.deps.getStream();\n const turnId = this.deps.getTurnId();\n if (!stream || !turnId) {\n return;\n }\n const durableTurnId = turnId;\n try {\n const rawHistory = (stream.state as { history?: unknown[] }).history;\n if (Array.isArray(rawHistory)) {\n const typedHistory = rawHistory as Array<Record<string, unknown>>;\n const verifiedKeys = this.prefix.verify(\n typedHistory,\n this.deps.getModelRunSettings().modelToolOutputTruncationTokens,\n );\n await media.retainNativeGeneratedImagesFromHistory(typedHistory);\n const durableHistory = compactGeneratedImageHistory(\n compactRetainedScreenshotHistory(typedHistory, media.retainedScreenshotReceiptsByCallId),\n media.generatedImageReceiptsByProviderItemId,\n );\n const { rows, nextWatermark, nextPosition } = historyRowsToAppend(\n durableHistory,\n this.persistedHistoryCount,\n this.nextHistoryPosition,\n this.deps.getModelRunSettings().modelToolOutputTruncationTokens,\n );\n const hasModelOrToolProgress = rows.some((row) =>\n isModelOrToolProgressHistoryItem(row.item),\n );\n const shouldAppendRows =\n rows.length > 0 && (!options.skipInputOnlyRows || hasModelOrToolProgress);\n if (shouldAppendRows) {\n await runMandatoryHistoryPersistenceStep(\"history_append\", async () => {\n const appended = await appendSessionHistoryItems(this.deps.db, {\n accountId: this.deps.accountId,\n workspaceId: this.deps.workspaceId,\n sessionId: this.deps.sessionId,\n turnId: durableTurnId,\n expectedExecutionGeneration: this.deps.getExecutionGeneration(),\n expectedAttemptId: this.deps.attemptId,\n modelToolOutputTruncationTokens:\n this.deps.getModelRunSettings().modelToolOutputTruncationTokens,\n items: rows,\n });\n if (!appended) {\n throw new TurnAttemptFencedError(\n \"turn execution generation was fenced while saving conversation history\",\n );\n }\n });\n }\n if (shouldAppendRows || !options.skipInputOnlyRows) {\n this.prefix.acknowledge(verifiedKeys, nextWatermark);\n this.persistedHistoryCount = nextWatermark;\n this.nextHistoryPosition = nextPosition;\n }\n } else if (options.requireDurable) {\n throw new Error(\n \"SDK conversation history is unavailable at a mandatory persistence boundary\",\n );\n }\n const envelope = sandboxStateEntryFromRunState(stream.state);\n if (envelope) {\n await runMandatoryHistoryPersistenceStep(\"sandbox_envelope\", () =>\n upsertSandboxSessionEnvelope(this.deps.db, {\n accountId: this.deps.accountId,\n workspaceId: this.deps.workspaceId,\n sessionId: this.deps.sessionId,\n envelope,\n }),\n );\n }\n } catch (persistError) {\n console.error(\"session history persistence failed\", safeErrorDiagnostic(persistError));\n if (options.requireDurable) throw persistError;\n }\n };\n}\n\nexport function createTurnHistorySink(deps: TurnHistorySinkDeps): TurnHistorySink {\n return new TurnHistorySink(deps);\n}\n","import {\n normalizeProtocolJsonValue,\n sanitizeHistoryItemsForModel,\n toolCallIdFromSdkItem,\n} from \"@opengeni/runtime\";\nimport { opaqueProviderArtifactFingerprint } from \"@opengeni/codex\";\n\nexport function historyRowsToAppend(\n rawHistory: Array<Record<string, unknown>>,\n // How many items of the CURRENT in-memory history are already persisted (the\n // slice index into `sanitized`). This is the in-memory history length, NOT the\n // total persisted-row count: after a compaction the in-memory history is the\n // short [summary, ...tail, ...new] list, far shorter than the total rows in\n // the table (which still hold the superseded prefix).\n persistedHistoryCount: number,\n // Next free WHOLE-NUMBER absolute position to write at. Decoupled from the\n // slice index because compaction inserts a fractional summary position, so the\n // total-row count no longer equals max(position)+1. Defaults to\n // persistedHistoryCount to preserve the pre-compaction behaviour (contiguous\n // positions from 0) when callers do not pass an explicit next position.\n nextPosition: number = persistedHistoryCount,\n toolOutputTruncationTokens?: number,\n): {\n rows: Array<{ position: number; item: Record<string, unknown> }>;\n nextWatermark: number;\n nextPosition: number;\n} {\n const modelReady = sanitizeHistoryItemsForModel(rawHistory, toolOutputTruncationTokens);\n if (modelReady.length <= persistedHistoryCount) {\n return { rows: [], nextWatermark: persistedHistoryCount, nextPosition };\n }\n // Canonical model-facing inputs (including machine-input batches) are\n // persisted before inference and therefore live inside the prefix represented\n // by persistedHistoryCount. System messages synthesized only for this\n // attempt—recovery diagnostics, credential notices, attachment materialization\n // notes—must not accidentally become conversation memory during reconciliation.\n // Advance the in-memory watermark past them, but only allocate durable\n // positions to actual model/tool output.\n const rows: Array<{ position: number; item: Record<string, unknown> }> = [];\n for (const [offset, item] of modelReady.slice(persistedHistoryCount).entries()) {\n if (item.type === \"message\" && item.role === \"system\") {\n continue;\n }\n rows.push({\n position: nextPosition + rows.length,\n item: normalizeProtocolJsonValue(\n item as Record<string, unknown>,\n `$[${persistedHistoryCount + offset}]`,\n ),\n });\n }\n return {\n rows,\n nextWatermark: modelReady.length,\n nextPosition: nextPosition + rows.length,\n };\n}\n\n/** Select only opaque rows that participated in the provider's rejected wire request. */\nexport function selectRejectedProviderArtifactHistoryIds(\n activeHistory: ReadonlyArray<{\n id: string;\n item: Record<string, unknown>;\n providerArtifactInvalidatedAt: Date | null;\n }>,\n candidates: {\n knownHistoryItemIds: readonly string[];\n historyItemIds: readonly string[];\n },\n wireFingerprints: readonly string[],\n): string[] {\n const remainingWireArtifacts = new Map<string, number>();\n for (const fingerprint of wireFingerprints) {\n remainingWireArtifacts.set(fingerprint, (remainingWireArtifacts.get(fingerprint) ?? 0) + 1);\n }\n const knownHistoryItemIds = new Set(candidates.knownHistoryItemIds);\n const initialCandidateIds = new Set(candidates.historyItemIds);\n const selected: string[] = [];\n for (const row of activeHistory) {\n if (row.providerArtifactInvalidatedAt !== null) continue;\n // A row present before this attempt is eligible only when the exact\n // model-facing projection retained it. Rows appended during this run are\n // eligible after durable reconciliation.\n if (knownHistoryItemIds.has(row.id) && !initialCandidateIds.has(row.id)) continue;\n const fingerprint = opaqueProviderArtifactFingerprint(row.item);\n if (!fingerprint) continue;\n const remaining = remainingWireArtifacts.get(fingerprint) ?? 0;\n if (remaining === 0) continue;\n selected.push(row.id);\n remainingWireArtifacts.set(fingerprint, remaining - 1);\n }\n return selected;\n}\n\n/** Literal final per-call boundary for replayed and current-turn model input. */\nexport function isModelOrToolProgressHistoryItem(item: Record<string, unknown>): boolean {\n if (item.type === \"message\") {\n return item.role === \"assistant\";\n }\n if (item.type === \"reasoning\" || item.type === \"compaction\") {\n return true;\n }\n if (typeof item.type === \"string\") {\n return item.type !== \"message\";\n }\n return false;\n}\n\n/**\n * Resolve the EFFECTIVE/active compute backend a turn should gate\n * filesystem-touching agent lifecycle hooks on (today: the repository clone).\n *\n * WHY (Case B — clone-onto-real-disk hazard): a session keeps its CLOUD HOME\n * backend (`settings.sandboxBackend`, e.g. \"modal\") but its ACTIVE sandbox may\n * have been swapped to a connected machine (`active_sandbox_id` → a selfhosted\n * lease). `runtime.buildAgent`'s repository-clone hook keys off the backend it is\n * told; if the worker passes nothing it defaults to the HOME backend and the hook\n * would `git clone` a private GitHub-App repo onto the user's REAL disk — a\n * bring-your-own machine owns its own filesystem and must NEVER be cloned onto. So\n * we look at where the agent ACTUALLY runs, not where the session was created.\n *\n * Returns \"selfhosted\" ONLY when the selfhosted feature is on AND the session has\n * a non-null active pointer whose sandbox `kind` is \"selfhosted\". Otherwise\n * returns undefined so buildAgent falls back to the home backend — byte-for-byte\n * unchanged cloud behavior.\n *\n * Total + best-effort by contract: it NEVER throws (a lookup failure is logged and\n * falls back to the home default), so wiring it at turn start can't fail the turn.\n * The DB I/O is injected (the real call site passes readActiveSandbox + getSandbox,\n * the same helpers wrapTurnBoxWithRouting reuses) so the gate/decision/safety\n * contract is unit-testable without a live database.\n */\nexport function pendingToolCallFromSdkEvent(event: unknown): {\n callId: string;\n callType: string;\n callName: string | null;\n callItem: Record<string, unknown>;\n} | null {\n if (!event || typeof event !== \"object\") return null;\n if ((event as { type?: unknown }).type !== \"run_item_stream_event\") return null;\n const item = (event as { item?: { type?: unknown; rawItem?: unknown } }).item;\n if (\n !item ||\n (item.type !== \"tool_call_item\" && item.type !== \"tool_search_call_item\") ||\n !item.rawItem ||\n typeof item.rawItem !== \"object\" ||\n Array.isArray(item.rawItem)\n ) {\n return null;\n }\n const raw = item.rawItem as Record<string, unknown>;\n // The hosted image call is a complete provider fact carried by one item; it\n // never receives a separate function result and therefore must not enter the\n // pending function-call ledger.\n if (raw.type === \"hosted_tool_call\" && raw.name === \"image_generation_call\") return null;\n const callId = toolCallIdFromSdkItem(raw) ?? raw.id;\n const callType = raw.type;\n if (typeof callId !== \"string\" || callId.length === 0 || typeof callType !== \"string\") {\n return null;\n }\n const callItem = normalizeProtocolJsonValue(raw, '$[\"item\"][\"rawItem\"]');\n return {\n callId,\n callType,\n callName: typeof raw.name === \"string\" ? raw.name : null,\n callItem,\n };\n}\n\n/** Tools whose intentional visual result must survive inline-media sanitization. */\nexport function toolCallProducesRetainableSessionImage(name: string | null): boolean {\n return (\n name === \"computer_screenshot\" ||\n name === \"view_image\" ||\n name === \"interaction__computer_observe\"\n );\n}\n\nexport function completedToolCallFromSdkEvent(event: unknown): {\n callId: string;\n resultItem: Record<string, unknown>;\n} | null {\n if (!event || typeof event !== \"object\") return null;\n if ((event as { type?: unknown }).type !== \"run_item_stream_event\") return null;\n const item = (event as { item?: { type?: unknown; rawItem?: unknown; id?: unknown } }).item;\n if (!item || (item.type !== \"tool_call_output_item\" && item.type !== \"tool_search_output_item\")) {\n return null;\n }\n const raw =\n item.rawItem && typeof item.rawItem === \"object\" && !Array.isArray(item.rawItem)\n ? (item.rawItem as Record<string, unknown>)\n : {};\n const callId = toolCallIdFromSdkItem(raw) ?? item.id;\n if (typeof callId !== \"string\" || callId.length === 0) return null;\n return {\n callId,\n resultItem: normalizeProtocolJsonValue(raw, '$[\"item\"][\"rawItem\"]'),\n };\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 */\n","import { createHash } from \"node:crypto\";\nimport { normalizeProtocolJsonValue, sanitizeHistoryItemsForModel } from \"@opengeni/runtime\";\n\n/** A position is an append cursor only while the items before it stay identical. */\nexport class HistoryPrefixGuard {\n private persisted: string[] = [];\n\n seed(items: Array<Record<string, unknown>>, count: number, truncationTokens?: number) {\n const keys = this.keys(items, truncationTokens);\n if (keys.length < count)\n throw new Error(\"Conversation history seed is shorter than its durable prefix\");\n this.persisted = keys.slice(0, count);\n }\n\n verify(items: Array<Record<string, unknown>>, truncationTokens?: number): string[] {\n const keys = this.keys(items, truncationTokens);\n for (let i = 0; i < this.persisted.length; i++) {\n if (keys[i] !== this.persisted[i]) {\n // No content in diagnostics: this may include private user/tool data.\n throw new Error(\n `Conversation history durable prefix changed at item ${i}; refusing to skip unsaved work`,\n );\n }\n }\n return keys;\n }\n\n acknowledge(keys: string[], count: number) {\n this.persisted = keys.slice(0, count);\n }\n\n private keys(items: Array<Record<string, unknown>>, truncationTokens?: number): string[] {\n return sanitizeHistoryItemsForModel(items, truncationTokens).map((item) =>\n createHash(\"sha256\")\n .update(JSON.stringify(sorted(normalizeProtocolJsonValue(item))))\n .digest(\"hex\"),\n );\n }\n}\n\nfunction sorted(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sorted);\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, entry]) => [key, sorted(entry)]),\n );\n }\n return value;\n}\n","import type { TurnHistorySink } from \"./history-sink\";\n\n/**\n * Persist the SDK's complete prior model/tool history before another provider\n * request can start. The first request has no prior model/tool rows to append.\n * Follow-up requests run only after the preceding complete call/result batch is\n * replay-safe.\n */\nexport async function checkpointHistoryBeforeProviderDispatch(\n historySink: Pick<TurnHistorySink, \"reconcileConversationTruth\">,\n): Promise<void> {\n await historySink.reconcileConversationTruth({ requireDurable: true });\n}\n","import type { Observability } from \"@opengeni/observability\";\n\nexport const MODEL_CHECKPOINT_GC_PRESSURE_BYTES = 512 * 1024 * 1024;\nexport const MODEL_CHECKPOINT_GC_COOLDOWN_MS = 30_000;\n\ntype ProcessMemory = Pick<NodeJS.MemoryUsage, \"heapUsed\" | \"external\">;\n\ntype ModelCheckpointMemoryCollectorDependencies = {\n now?: () => number;\n memoryUsage?: () => ProcessMemory;\n gc?: () => void;\n setTimeout?: typeof setTimeout;\n};\n\nexport type ModelCheckpointMemoryCollector = {\n schedule(observability: Observability): void;\n};\n\nexport function modelCheckpointPressureBytes(memory: ProcessMemory): number {\n // `external` includes ArrayBuffer storage in Bun/Node's memoryUsage contract.\n // Heap and external allocations are independent, so max(heap, external)\n // undercounts the actual reclaimable pressure whenever both are large.\n return memory.heapUsed + memory.external;\n}\n\n/**\n * Reclaim request serialization and stream buffers only after one model\n * response has crossed the durable conversation checkpoint. The callback runs\n * on a later task so the completed response's stack can unwind first. Active\n * turns and their exact model context remain strongly reachable and are never\n * shortened, restarted, or rewritten by this process-local collection.\n */\nexport function createModelCheckpointMemoryCollector(\n dependencies: ModelCheckpointMemoryCollectorDependencies = {},\n): ModelCheckpointMemoryCollector {\n const now = dependencies.now ?? Date.now;\n const memoryUsage = dependencies.memoryUsage ?? process.memoryUsage;\n const collectGarbage = dependencies.gc ?? (() => Bun.gc(true));\n const scheduleTask = dependencies.setTimeout ?? setTimeout;\n let scheduled = false;\n let lastCollectionAt = Number.NEGATIVE_INFINITY;\n\n return {\n schedule(observability) {\n if (scheduled) return;\n scheduled = true;\n try {\n const timer = scheduleTask(() => {\n scheduled = false;\n let memory: ProcessMemory;\n try {\n memory = memoryUsage();\n } catch {\n safeIncrementCounter(observability, {\n name: \"opengeni_turn_worker_model_checkpoint_gc_failures_total\",\n help: \"Model-checkpoint garbage collections that could not sample or collect memory.\",\n });\n return;\n }\n\n const pressureBytes = modelCheckpointPressureBytes(memory);\n const observedAt = now();\n if (\n !Number.isFinite(pressureBytes) ||\n pressureBytes < MODEL_CHECKPOINT_GC_PRESSURE_BYTES ||\n observedAt - lastCollectionAt < MODEL_CHECKPOINT_GC_COOLDOWN_MS\n ) {\n return;\n }\n\n lastCollectionAt = observedAt;\n const startedAt = performance.now();\n try {\n collectGarbage();\n safeIncrementCounter(observability, {\n name: \"opengeni_turn_worker_model_checkpoint_gc_total\",\n help: \"Forced garbage collections after durable model-response checkpoints.\",\n });\n safeObserveHistogram(observability, {\n name: \"opengeni_turn_worker_model_checkpoint_gc_duration_seconds\",\n help: \"Forced garbage-collection duration after durable model-response checkpoints.\",\n value: Math.max(0, performance.now() - startedAt) / 1_000,\n });\n } catch {\n safeIncrementCounter(observability, {\n name: \"opengeni_turn_worker_model_checkpoint_gc_failures_total\",\n help: \"Model-checkpoint garbage collections that could not sample or collect memory.\",\n });\n }\n }, 0);\n try {\n timer.unref?.();\n } catch {\n // A timer implementation without a usable unref is still safe.\n }\n } catch {\n scheduled = false;\n }\n },\n };\n}\n\nfunction safeIncrementCounter(\n observability: Observability,\n input: Parameters<Observability[\"incrementCounter\"]>[0],\n): void {\n try {\n observability.incrementCounter(input);\n } catch {\n // Telemetry cannot disable collection at a durable model checkpoint.\n }\n}\n\nfunction safeObserveHistogram(\n observability: Observability,\n input: Parameters<Observability[\"observeHistogram\"]>[0],\n): void {\n try {\n observability.observeHistogram(input);\n } catch {\n // Telemetry cannot disable collection at a durable model checkpoint.\n }\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { CodexUsageHeaderSnapshot } from \"@opengeni/codex\";\nimport type { AppendEventInput, ApplySessionTurnSettlementInput } from \"@opengeni/db\";\nimport type {\n CodexCredentialPolicySnapshotV1,\n ModelContextContributionSummary,\n SessionStatus,\n XaiProviderAccountAuthoritySnapshotV1,\n} from \"@opengeni/contracts\";\nimport type {\n EstablishedSandboxSession,\n OpenGeniRuntime,\n RunCredentialCommandSession,\n SelfhostedSession,\n TurnToolCancellationFence,\n} from \"@opengeni/runtime\";\nimport type { XaiSubscriptionRequestContext } from \"@opengeni/xai-subscription\";\nimport type { CodemodeAttemptDispatcher } from \"../codemode-dispatcher\";\nimport type { CodemodeTokenRenewalController } from \"../codemode-token-renewal\";\nimport type { GitCredentialRenewalController } from \"../git-credential-renewal\";\nimport type { RunCredentialRenewalController } from \"../run-credential-renewal\";\nimport type { createRuntimeBatcher, startActivityHeartbeat } from \"../streaming\";\nimport type { RunAgentTurnResult } from \"../types\";\nimport type { TurnOutcome } from \"../../observability-metrics\";\nimport type { ResumedTurnSandbox, TurnSandboxLeaseHolderId } from \"../../sandbox-resume\";\nimport type { TurnEventPublisher } from \"./model-usage\";\nimport type { TurnSandboxProvisioner } from \"./sandbox-provision\";\n\n/** Stamps the claimed turn/attempt ids onto a phase's own outcome. */\nexport type ClaimedResult = (\n result: Omit<\n Extract<RunAgentTurnResult, { status: Exclude<RunAgentTurnResult[\"status\"], \"unclaimed\"> }>,\n \"turnId\" | \"attemptId\"\n >,\n) => RunAgentTurnResult;\n\nexport type TurnSettleFn = (input: {\n events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>;\n turnStatus:\n | \"queued\"\n | \"running\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n | \"superseded\"\n | \"requires_action\";\n sessionStatus: SessionStatus;\n activeTurnId: string | null;\n suppressGoalContinuation?: boolean;\n consumeRequestedCompactionFailure?: boolean;\n runState?: ApplySessionTurnSettlementInput[\"runState\"];\n}) => Promise<boolean>;\n\nexport type TurnControlState = {\n cancellationRequestedAt: number | null;\n activityStatus: RunAgentTurnResult[\"status\"] | \"unknown\";\n turnMetricOutcome: TurnOutcome | null;\n activityError: unknown;\n acknowledgeQuiescence: boolean;\n};\n\nexport type AttemptIdentityState = {\n turnId: string | undefined;\n dispatchId: string;\n triggerEventId: string | undefined;\n executionGeneration: number;\n providerRecoveryCount: number;\n modelRequestStarted: boolean;\n redispatchesAtDispatch: number;\n // Held for same-turn recovery: an approval-decision rerun must re-enter\n // through the suffix/history resume path, never through a swapped trigger.\n triggerType: string | null;\n};\n\nexport type BillingState = {\n isCodexTurn: boolean;\n isXaiTurn: boolean;\n isExternallyBilledTurn: boolean;\n chargesOpenGeniCredits: boolean;\n countsTowardTokenCap: boolean;\n};\n\nexport type SandboxRuntimeState = {\n resolvedSandbox: ResumedTurnSandbox | null;\n attemptWritersDrained: boolean;\n lateSandboxesAwaitingWriterDrain: Set<ResumedTurnSandbox>;\n machinePrimarySession: SelfhostedSession | null;\n lazyOwnedSandbox: EstablishedSandboxSession | null;\n firstModelPreparationNestedSandboxMs: number;\n firstModelPreparationNestedSandboxPhases: Array<{\n phase: \"admission\" | \"provider\" | \"settlement\" | \"snapshot_wait\";\n outcome: \"completed\" | \"failed\";\n durationSeconds: number;\n }>;\n turnSandboxProvisioner: TurnSandboxProvisioner<ResumedTurnSandbox> | null;\n resumeManagedGroupBox: (() => Promise<ResumedTurnSandbox>) | null;\n prefetchedManagedBox: Promise<ResumedTurnSandbox> | null;\n prefetchedManagedBoxResult: ResumedTurnSandbox | null;\n setupBoxSession: unknown;\n sandboxHolderId: TurnSandboxLeaseHolderId | null;\n sandboxGroupId: string | null;\n leaseHeartbeatTimer: ReturnType<typeof setInterval> | undefined;\n rotationPreemptionInFlight: Promise<void> | null;\n deadlineRotationRequested: boolean;\n snapshotInFlight: Promise<void> | null;\n firstProviderRequestStarted: boolean;\n turnEndCaptureInProgress: boolean;\n // Backend label for canonical startup milestones. Null until the route\n // resolves, so milestones recorded before then fall back to the turn's own\n // recorded backend and later ones report the effective route.\n startupMilestoneBackend: Settings[\"sandboxBackend\"] | null;\n};\n\nexport type RenewalState = {\n gitCredentialRenewals: GitCredentialRenewalController[];\n gitCredentialRenewalClosed: boolean;\n runCredentialRenewal: RunCredentialRenewalController | null;\n runCredentialRenewalClosed: boolean;\n runCredentialSession: RunCredentialCommandSession | null;\n codemodeTokenRenewal: CodemodeTokenRenewalController | null;\n codemodeTokenRenewalClosed: boolean;\n publishedRunCredentialNotices: Set<string>;\n};\n\nexport type EventingState = {\n heartbeatTimer: ReturnType<typeof startActivityHeartbeat> | undefined;\n batcher: ReturnType<typeof createRuntimeBatcher> | null;\n preparedTools: Awaited<ReturnType<OpenGeniRuntime[\"prepareTools\"]>> | null;\n toolPreparationReady: Promise<void> | null;\n toolPreparationClosing: boolean;\n codemodeDispatcher: CodemodeAttemptDispatcher | null;\n toolCancellationFenceRef: { current: TurnToolCancellationFence | null };\n publish: TurnEventPublisher | null;\n settle: TurnSettleFn | null;\n turnStartedPublished: boolean;\n stream: Awaited<ReturnType<OpenGeniRuntime[\"runStream\"]>> | undefined;\n modelRunSettings: Settings;\n firstModelRequestPreparationStartedAt: number | null;\n firstModelRequestPreparationRecorded: boolean;\n firstModelRequestCheckpointAt: number | null;\n companyBrainContextContributions: readonly ModelContextContributionSummary[] | null;\n};\n\n/** Rig telemetry (M3): set once the session loads; empty string for a rig-less\n * turn (mirrors variableSetId). Read by the activity span's finally block. */\nexport type WorkspaceRefState = {\n variableSetId: string;\n rigId: string;\n rigVersionId: string;\n};\n\nexport type ProviderTurnState = {\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.\n effectiveCodexCredentialId: string | null;\n /** Exact row version returned by the resolver for the latest provider request. */\n effectiveCodexCredentialVersion: number | null;\n /** Frozen alternate-account ceiling observed by the fenced allocator. */\n codexCredentialFailoverLimit: number;\n /** Accepted Codex allocator policy captured with the first durable lease. */\n codexPolicySnapshot: CodexCredentialPolicySnapshotV1 | null;\n effectiveXaiCredentialId: string | null;\n xaiRotationEnabled: boolean;\n xaiAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1 | null;\n xaiRequestContext: XaiSubscriptionRequestContext | null;\n xaiCredentialQuarantined: boolean;\n // The session's Codex credential BEFORE this turn resolved its own — captured\n // before recordSessionActiveCodexCredential overwrites the durable pointer, so\n // a per-call usage log can report whether the serving account CHANGED since the\n // session's previous call (the prompt-cache account-switch hypothesis).\n priorSessionCodexCredentialId: string | null;\n // The latest usage-header snapshot scraped for free off this turn's\n // `/codex/responses` responses (a turn issues many model calls; latest wins).\n // Flushed ONCE into the P2 usage cache for the serving account in the turn\n // finalizer — cheaper than a /wham/usage poll AND it self-heals P3 rotation\n // (the proactive + 429 rankers read these exact columns). null ⇒ nothing\n // scraped. Lives on the turn context so the finalizer sees it; the sink is\n // wired into codexContext.onUsageHeaders by the orchestrator.\n latestCodexUsage: CodexUsageHeaderSnapshot | null;\n lastCodexRequestOpaqueArtifacts: readonly string[];\n};\n\nexport type TurnContext = {\n control: TurnControlState;\n attempt: AttemptIdentityState;\n billingState: BillingState;\n sandboxState: SandboxRuntimeState;\n renewals: RenewalState;\n eventing: EventingState;\n workspaceRefs: WorkspaceRefState;\n providerTurn: ProviderTurnState;\n};\n\nexport function createTurnContext(input: {\n settings: Settings;\n cancellationRequestedAt: number | null;\n}): TurnContext {\n return {\n control: {\n cancellationRequestedAt: input.cancellationRequestedAt,\n activityStatus: \"unknown\",\n turnMetricOutcome: null,\n activityError: undefined,\n acknowledgeQuiescence: false,\n },\n attempt: {\n turnId: undefined,\n dispatchId: \"\",\n triggerEventId: undefined,\n executionGeneration: 0,\n providerRecoveryCount: 0,\n modelRequestStarted: false,\n redispatchesAtDispatch: 0,\n triggerType: null,\n },\n billingState: {\n isCodexTurn: false,\n isXaiTurn: false,\n isExternallyBilledTurn: false,\n chargesOpenGeniCredits: true,\n countsTowardTokenCap: true,\n },\n sandboxState: {\n resolvedSandbox: null,\n attemptWritersDrained: false,\n lateSandboxesAwaitingWriterDrain: new Set(),\n machinePrimarySession: null,\n lazyOwnedSandbox: null,\n firstModelPreparationNestedSandboxMs: 0,\n firstModelPreparationNestedSandboxPhases: [],\n turnSandboxProvisioner: null,\n resumeManagedGroupBox: null,\n prefetchedManagedBox: null,\n prefetchedManagedBoxResult: null,\n setupBoxSession: null,\n sandboxHolderId: null,\n sandboxGroupId: null,\n leaseHeartbeatTimer: undefined,\n rotationPreemptionInFlight: null,\n deadlineRotationRequested: false,\n snapshotInFlight: null,\n firstProviderRequestStarted: false,\n turnEndCaptureInProgress: false,\n startupMilestoneBackend: null,\n },\n renewals: {\n gitCredentialRenewals: [],\n gitCredentialRenewalClosed: false,\n runCredentialRenewal: null,\n runCredentialRenewalClosed: false,\n runCredentialSession: null,\n codemodeTokenRenewal: null,\n codemodeTokenRenewalClosed: false,\n publishedRunCredentialNotices: new Set(),\n },\n eventing: {\n heartbeatTimer: undefined,\n batcher: null,\n preparedTools: null,\n toolPreparationReady: null,\n toolPreparationClosing: false,\n codemodeDispatcher: null,\n toolCancellationFenceRef: { current: null },\n publish: null,\n settle: null,\n turnStartedPublished: false,\n stream: undefined,\n modelRunSettings: input.settings,\n firstModelRequestPreparationStartedAt: null,\n firstModelRequestPreparationRecorded: false,\n firstModelRequestCheckpointAt: null,\n companyBrainContextContributions: null,\n },\n workspaceRefs: {\n variableSetId: \"\",\n rigId: \"\",\n rigVersionId: \"\",\n },\n providerTurn: {\n effectiveCodexCredentialId: null,\n effectiveCodexCredentialVersion: null,\n codexCredentialFailoverLimit: 1,\n codexPolicySnapshot: null,\n effectiveXaiCredentialId: null,\n xaiRotationEnabled: false,\n xaiAuthoritySnapshot: null,\n xaiRequestContext: null,\n xaiCredentialQuarantined: false,\n priorSessionCodexCredentialId: null,\n latestCodexUsage: null,\n lastCodexRequestOpaqueArtifacts: [],\n },\n };\n}\n","import {\n commitSessionAttemptQuiescence,\n listPendingSessionTurns,\n recordCodexAccountUsageWithWakeTargets,\n releaseCodexCredentialLease,\n releaseXaiCredentialLease,\n updateXaiQuotaMetadata,\n type SessionAttemptQuiescenceCommit,\n} from \"@opengeni/db\";\nimport { appendAndPublishTurnEventsFenced, publishDurableSessionEvents } from \"@opengeni/events\";\nimport { sandboxLeaseTelemetryKey } from \"@opengeni/observability\";\nimport { clearRunCredentialsForAttempt } from \"@opengeni/runtime\";\nimport { fetchXaiSubscriptionQuota } from \"@opengeni/xai-subscription\";\nimport type { Settings } from \"@opengeni/config\";\nimport { signalCodexCapacityWakeTargets } from \"../codex-capacity\";\nimport type { currentActivityContext } from \"../streaming\";\nimport type { CodemodeTokenRenewalController } from \"../codemode-token-renewal\";\nimport type { RunCredentialRenewalController } from \"../run-credential-renewal\";\nimport type {\n RunAgentTurnInput,\n SessionAttemptQuiescenceProof,\n TurnActivityServices as ActivityServices,\n} from \"../types\";\nimport {\n captureWhileIdle,\n captureWorkspaceRevision,\n openFreshWorkspaceCaptureSession,\n} from \"../workspace-capture\";\nimport { type ChannelASession } from \"@opengeni/runtime/sandbox\";\nimport { createModelCheckpointMemoryCollector } from \"../../model-checkpoint-memory-collector\";\nimport {\n makeMachineOpObserver,\n recordSessionEventAppendPhase,\n turnLifecycleMetricsFor,\n} from \"../../observability-metrics\";\nimport {\n maybePersistWarmWorkspaceSnapshot,\n waitForWarmSnapshot,\n type ResumedTurnSandbox,\n} from \"../../sandbox-resume\";\nimport { createTurnCredentialLeases } from \"./credential-leases\";\nimport { safeErrorDiagnostic, safeErrorForTelemetry } from \"./errors\";\nimport {\n assertPhysicalToolQuiescenceForCancellation,\n assertSessionAttemptQuiescenceRecoveryDurable,\n armTurnQuiescenceWatchdog,\n clearAttemptCredentialsWithSettledFence,\n drainAttemptOwnedSandboxWriters,\n persistOrSignalSessionAttemptQuiescence,\n releaseTurnSandboxAfterWriterDrain,\n shouldRunTurnEndWorkspacePersistence,\n turnFinalizerCancellationSignal,\n waitForTurnFinalizerStep,\n} from \"./quiescence\";\nimport type {\n AttemptIdentityState,\n EventingState,\n ProviderTurnState,\n RenewalState,\n SandboxRuntimeState,\n TurnControlState,\n WorkspaceRefState,\n} from \"./turn-context\";\n\nexport type TurnFinalizationDeps = {\n input: RunAgentTurnInput;\n settings: Settings;\n db: ActivityServices[\"db\"];\n bus: ActivityServices[\"bus\"];\n objectStorage: ActivityServices[\"objectStorage\"];\n observability: ActivityServices[\"observability\"];\n wakeSessionWorkflow: ActivityServices[\"wakeSessionWorkflow\"];\n signalSessionAttemptQuiesced: ActivityServices[\"signalSessionAttemptQuiesced\"];\n signalCodexCapacityWorkflow: ActivityServices[\"signalCodexCapacityWorkflow\"];\n cancellationSignal: AbortSignal | undefined;\n sandboxResumeController: AbortController;\n activityContext: ReturnType<typeof currentActivityContext>;\n activityStarted: number;\n activitySpan: ReturnType<ActivityServices[\"observability\"][\"startSpan\"]>;\n dispatchId: string;\n noteCancellationRequested: () => void;\n machineOpObserver: ReturnType<typeof makeMachineOpObserver>;\n leases: ReturnType<typeof createTurnCredentialLeases>;\n control: TurnControlState;\n attempt: AttemptIdentityState;\n sandboxState: SandboxRuntimeState;\n renewals: RenewalState;\n eventing: EventingState;\n providerTurn: ProviderTurnState;\n workspaceRefs: WorkspaceRefState;\n runWorkspaceMutationForSandbox: <T>(\n sandbox: ResumedTurnSandbox,\n operation: string,\n mutation: () => Promise<T>,\n ) => Promise<T>;\n requireResolvedSandboxForMutation: (message: string) => ResumedTurnSandbox;\n stopLeaseHeartbeat: () => void;\n turnCompletionMemoryCollector: ReturnType<typeof createModelCheckpointMemoryCollector>;\n};\n\nexport async function finalizeTurnAttempt(deps: TurnFinalizationDeps): Promise<void> {\n const {\n input,\n settings,\n db,\n bus,\n objectStorage,\n observability,\n wakeSessionWorkflow,\n signalSessionAttemptQuiesced,\n signalCodexCapacityWorkflow,\n cancellationSignal,\n sandboxResumeController,\n activityContext,\n activityStarted,\n activitySpan,\n dispatchId,\n noteCancellationRequested,\n machineOpObserver,\n leases,\n control,\n attempt,\n sandboxState,\n renewals,\n eventing,\n providerTurn,\n workspaceRefs,\n runWorkspaceMutationForSandbox,\n requireResolvedSandboxForMutation,\n stopLeaseHeartbeat,\n turnCompletionMemoryCollector,\n } = deps;\n // This is the logical ownership boundary. Abort before any fallible\n // housekeeping so a still-pending provider establish releases its private\n // holder/timer even when Temporal itself never delivered cancellation.\n if (sandboxState.resolvedSandbox === null && !sandboxResumeController.signal.aborted) {\n sandboxResumeController.abort(\n cancellationSignal?.reason ?? new Error(\"TURN_ATTEMPT_FINALIZED\"),\n );\n }\n const finalizationStarted = performance.now();\n let finalizationError: unknown;\n let physicalToolQuiescenceConfirmed = !control.acknowledgeQuiescence;\n let quiescenceReceiptOrProofDurable = !control.acknowledgeQuiescence;\n const disarmQuiescenceWatchdog = armTurnQuiescenceWatchdog({\n enabled: control.acknowledgeQuiescence,\n onTimeout: () => {\n observability.error(\"turn quiescence drain exceeded hard containment deadline\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": attempt.turnId ?? \"\",\n \"opengeni.attempt_id\": input.attemptId,\n });\n },\n terminateWorker: () => process.exit(1),\n });\n const finalizerSignal = turnFinalizerCancellationSignal(\n cancellationSignal,\n control.activityStatus,\n );\n const drainInFlightWarmSnapshot = async (): Promise<void> => {\n const snapshot = sandboxState.snapshotInFlight;\n if (!snapshot) return;\n // This is physical quiescence, not optional turn-end persistence. The\n // provider capture SDK is not cancellable, so an aborted finalizer signal\n // must not detach this wait and release the holder while the continuation\n // is still reading or publishing the exact workspace generation.\n await snapshot.catch((error) => {\n console.error(\n \"in-flight workspace snapshot settlement failed (turn outcome unaffected)\",\n safeErrorDiagnostic(error),\n );\n });\n if (sandboxState.snapshotInFlight === snapshot) {\n sandboxState.snapshotInFlight = null;\n }\n };\n try {\n const toolCancellationFence = eventing.toolCancellationFenceRef.current;\n // Every renewal controller is an attempt-owned sandbox writer. Capture\n // and close all of them before the tool/run-writer drain and before the\n // quiescence receipt; none may start another admitted write afterward.\n renewals.gitCredentialRenewalClosed = true;\n const gitRenewalsToStop = renewals.gitCredentialRenewals;\n renewals.gitCredentialRenewals = [];\n renewals.codemodeTokenRenewalClosed = true;\n const codemodeRenewalToStop =\n renewals.codemodeTokenRenewal as CodemodeTokenRenewalController | null;\n renewals.codemodeTokenRenewal = null;\n renewals.runCredentialRenewalClosed = true;\n const runRenewalToStop = renewals.runCredentialRenewal as RunCredentialRenewalController | null;\n renewals.runCredentialRenewal = null;\n\n // Capture the attempt-qualified credential target before draining the\n // controllers that can still write a newer generation.\n const credentialSessionToClear = renewals.runCredentialSession;\n renewals.runCredentialSession = null;\n await drainAttemptOwnedSandboxWriters({\n // Normal turn completion owns the same process boundary as\n // Pause/Steer: yielded provider shells must be terminated, polled,\n // and durably settled before workspace capture. Only receipt\n // publication remains conditional on acknowledgeQuiescence.\n toolCancellationFence,\n cancellationReason: cancellationSignal?.reason ?? new Error(\"TURN_ATTEMPT_FINALIZED\"),\n gitCredentialRenewals: gitRenewalsToStop,\n codemodeTokenRenewal: codemodeRenewalToStop,\n runCredentialRenewal: runRenewalToStop,\n });\n // Attempt-qualified credential deletion is also a real workspace write,\n // but it must not be submitted behind the very command being cancelled.\n // Drain tool processes and credential renewals first, then delete only this\n // attempt's generation before publishing physical quiescence. A failure\n // deliberately keeps the receipt closed.\n if (credentialSessionToClear) {\n const clearAttemptCredentials = async (): Promise<void> =>\n await clearRunCredentialsForAttempt(credentialSessionToClear, {\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n });\n await clearAttemptCredentialsWithSettledFence({\n activityStatus: control.activityStatus,\n runWorkspaceFencedClear: async () =>\n await runWorkspaceMutationForSandbox(\n requireResolvedSandboxForMutation(\n \"Run credential cleanup has no exact sandbox lease target\",\n ),\n \"runCredentialAttemptClear\",\n clearAttemptCredentials,\n ),\n clearExactAttempt: clearAttemptCredentials,\n onSettledAttemptFence: () => {\n // Terminal settlement closes the active attempt before this finally\n // runs, so the ordinary workspace admission correctly rejects it.\n // The attempt-qualified delete is nevertheless successor-safe: it\n // removes only this attempt/generation and clears the pointer only\n // when it still names that exact generation. Finish that cleanup\n // directly so a successful turn can continue into workspace capture,\n // tool teardown, and lease release.\n observability.info(\"retrying exact run credential cleanup after turn settlement\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": attempt.turnId ?? \"\",\n \"opengeni.attempt_id\": input.attemptId,\n });\n },\n });\n }\n sandboxState.attemptWritersDrained = true;\n if (control.acknowledgeQuiescence) {\n // A cancellation before sandbox-backed capabilities exist still has\n // no tool controller to drain. Sandbox agent construction fails closed\n // when a backend exists but no controller was installed. Renewal\n // writers, when present, were drained above in either case.\n physicalToolQuiescenceConfirmed = true;\n }\n if (control.acknowledgeQuiescence && physicalToolQuiescenceConfirmed) {\n // This receipt is part of the hard cancellation boundary, not\n // housekeeping. Persist it immediately after the sandbox/tool fence\n // and before lease, cache, recording, or provider cleanup. Its\n // transaction also enqueues the exact workflow wake that will admit\n // the replacement; Temporal activity terminalization does neither.\n const proof: SessionAttemptQuiescenceProof = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n activityId: dispatchId,\n };\n const recoveryMode = await persistOrSignalSessionAttemptQuiescence({\n proof,\n persistReceipt: async () =>\n await commitSessionAttemptQuiescence(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n temporalWorkflowId: input.workflowId,\n temporalWorkflowRunId: input.workflowRunId,\n temporalActivityId: dispatchId,\n allowUninterrupted: true,\n }),\n ...(wakeSessionWorkflow\n ? {\n deliverWorkflowWake: async (\n wake: NonNullable<SessionAttemptQuiescenceCommit[\"workflowWake\"]>,\n ) =>\n await wakeSessionWorkflow({\n accountId: wake.accountId,\n workspaceId: wake.workspaceId,\n sessionId: wake.sessionId,\n workflowId: wake.temporalWorkflowId,\n wakeRevision: wake.wakeRevision,\n interruptionRequested: wake.interruptionRequested,\n }),\n }\n : {}),\n publishEvents: async (events) => {\n await waitForTurnFinalizerStep(\n publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, events),\n finalizerSignal,\n );\n },\n signalProof: signalSessionAttemptQuiesced,\n heartbeat: (deliveryAttempt, retryMs) => {\n activityContext?.heartbeat({\n phase: \"quiescence-proof-delivery\",\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n deliveryAttempt,\n retryMs,\n at: new Date().toISOString(),\n });\n },\n onReceiptFailure: (error) => {\n console.error(\n \"agent turn quiescence receipt exhausted; signalling proof\",\n safeErrorDiagnostic(error),\n );\n },\n onWakeFailure: (error) => {\n console.error(\n \"agent turn quiescence immediate workflow wake failed; outbox repair retained\",\n safeErrorDiagnostic(error),\n );\n },\n onPublishFailure: (error) => {\n console.error(\"agent turn quiescence event fanout failed\", safeErrorDiagnostic(error));\n },\n onSignalFailure: (error, deliveryAttempt, retryMs) => {\n console.error(\"agent turn quiescence proof signal failed; retrying\", {\n error: safeErrorDiagnostic(error),\n attempt: deliveryAttempt,\n retryMs,\n });\n },\n });\n quiescenceReceiptOrProofDurable = true;\n disarmQuiescenceWatchdog();\n if (recoveryMode === \"signal\") {\n observability.info(\"agent turn quiescence proof handed to workflow recovery\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.attempt_id\": input.attemptId,\n \"opengeni.workflow_run_id\": input.workflowRunId,\n \"opengeni.activity_id\": dispatchId,\n });\n }\n }\n // Drain the buffered Connected Machine op events (infra failures + healed\n // recoveries) to durable session events — awaited, best-effort, never blocking\n // the turn. Sync observer → buffer → single awaited append here (no unawaited\n // DB write inside the activity). Scoped to this turn; skipped if no turnId\n // (the op ran under a turn, so on the normal path turnId is set).\n const machineOpEvents = machineOpObserver.drainEvents();\n if (machineOpEvents.length > 0 && attempt.turnId && attempt.executionGeneration > 0) {\n await waitForTurnFinalizerStep(\n appendAndPublishTurnEventsFenced(\n db,\n bus,\n input.workspaceId,\n input.sessionId,\n attempt.turnId,\n attempt.executionGeneration,\n input.attemptId,\n machineOpEvents.map((event) => ({\n ...event,\n turnId: attempt.turnId ?? null,\n })),\n {\n onAppendPhase: (observation) =>\n recordSessionEventAppendPhase(observability, observation),\n },\n ).catch(() => undefined),\n finalizerSignal,\n );\n }\n // Multi-account P4: flush the serving account's free per-turn caches ONCE,\n // best-effort (same discipline as today's usage write). Both writers skip\n // version/updatedAt, so neither can race the token-refresh CAS.\n if (providerTurn.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 (providerTurn.latestCodexUsage) {\n const usageMutation = await waitForTurnFinalizerStep(\n recordCodexAccountUsageWithWakeTargets(\n db,\n input.workspaceId,\n providerTurn.effectiveCodexCredentialId,\n providerTurn.latestCodexUsage,\n ).catch(() => null),\n finalizerSignal,\n );\n if (usageMutation) {\n await waitForTurnFinalizerStep(\n signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n usageMutation.wakeTargets,\n ),\n finalizerSignal,\n );\n }\n }\n }\n leases.codex.stopHeartbeat();\n if (\n leases.codex.held &&\n attempt.turnId &&\n leases.codex.holderId &&\n leases.codex.generation !== null\n ) {\n await waitForTurnFinalizerStep(\n releaseCodexCredentialLease(\n db,\n input.accountId,\n input.workspaceId,\n attempt.turnId,\n leases.codex.holderId,\n leases.codex.generation,\n ).catch(() => undefined),\n finalizerSignal,\n );\n leases.codex.held = false;\n }\n if (\n providerTurn.effectiveXaiCredentialId &&\n leases.xai.subjectId &&\n providerTurn.xaiRequestContext &&\n !providerTurn.xaiCredentialQuarantined\n ) {\n const quota = await waitForTurnFinalizerStep(\n fetchXaiSubscriptionQuota({ context: providerTurn.xaiRequestContext }).catch(() => null),\n finalizerSignal,\n );\n if (quota) {\n await waitForTurnFinalizerStep(\n updateXaiQuotaMetadata(db, {\n workspaceId: input.workspaceId,\n subjectId: leases.xai.subjectId,\n credentialId: providerTurn.effectiveXaiCredentialId,\n quotaUsedPercent: quota.usedPercent,\n quotaResetAt: quota.period?.end ?? null,\n quotaCheckedAt: quota.checkedAt,\n exhaustedUntil:\n quota.usedPercent !== null && quota.usedPercent >= 100\n ? (quota.period?.end ?? null)\n : null,\n }).catch(() => undefined),\n finalizerSignal,\n );\n }\n }\n leases.xai.stopHeartbeat();\n if (\n leases.xai.held &&\n attempt.turnId &&\n leases.xai.subjectId &&\n leases.xai.holderId &&\n leases.xai.generation !== null\n ) {\n await waitForTurnFinalizerStep(\n releaseXaiCredentialLease(db, {\n workspaceId: input.workspaceId,\n subjectId: leases.xai.subjectId,\n turnId: attempt.turnId,\n holderId: leases.xai.holderId,\n generation: leases.xai.generation,\n }).catch(() => undefined),\n finalizerSignal,\n );\n leases.xai.held = false;\n }\n // Workbench v2 turn-end workspace capture — runs FIRST in\n // the turn-end finally, while the box is MAXIMALLY ALIVE. The agent's last\n // tool ran before this finally, so /workspace is already final; capture is\n // FS-equivalent to the warm snapshot (neither mutates workspace files).\n // Running it here — BEFORE preparedTools.close() tears down tools —\n // gives capture the full live-box margin instead of racing the teardown\n // tail, which was dropping 100% of captures on real Modal desktop boxes\n // (\"request cancelled due to container exiting\", 0 rows). External module:\n // self-capped at 120s, best-effort (never throws past its boundary),\n // epoch-fenced, and it NEVER closes the box. The emitted\n // workspace.revision.captured event is ANNOUNCE-ONLY (metadata, never\n // content).\n if (process.env.OPENGENI_TEST_SCENARIO === \"sandbox\") {\n console.log(\n `[sandbox-e2e] capture preflight ownership=${settings.sandboxOwnershipEnabled} enabled=${settings.workspaceCaptureEnabled} resolved=${Boolean(sandboxState.resolvedSandbox)} session=${Boolean(sandboxState.setupBoxSession)} group=${Boolean(sandboxState.sandboxGroupId)} storage=${Boolean(objectStorage)}`,\n );\n }\n const runTurnEndPersistence = shouldRunTurnEndWorkspacePersistence({\n activityStatus: control.activityStatus,\n cancellationRequested: finalizerSignal?.aborted === true,\n deadlineRotationRequested: sandboxState.deadlineRotationRequested,\n });\n if (\n settings.workspaceCaptureEnabled &&\n runTurnEndPersistence &&\n attempt.turnId &&\n sandboxState.resolvedSandbox &&\n sandboxState.setupBoxSession &&\n sandboxState.sandboxGroupId\n ) {\n // Review reads yield to queued work. Recovery snapshots have their own\n // physical-settlement requirement and are drained later in finalization.\n sandboxState.turnEndCaptureInProgress = true;\n const captureSandbox = sandboxState.resolvedSandbox;\n const captureSession = sandboxState.setupBoxSession as ChannelASession;\n const captureGroupId = sandboxState.sandboxGroupId;\n const captureTurnId = attempt.turnId;\n await captureWhileIdle({\n ...(finalizerSignal ? { signal: finalizerSignal } : {}),\n hasPendingWork: async () =>\n (await listPendingSessionTurns(db, input.workspaceId, input.sessionId)).some(\n (turn) => turn.id !== captureTurnId,\n ),\n capture: async (signal) => {\n if (sandboxState.snapshotInFlight) {\n await waitForWarmSnapshot(\n sandboxState.snapshotInFlight,\n settings.sandboxSnapshotTimeoutMs,\n signal,\n );\n }\n if (signal.aborted) return;\n await captureWorkspaceRevision({\n db,\n objectStorage,\n settings,\n publish: async (events) =>\n publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, events),\n session: captureSession,\n openReadSession: async () =>\n openFreshWorkspaceCaptureSession({\n backendId: captureSandbox.established.backendId,\n client: captureSandbox.established.client,\n session: captureSession,\n expectedInstanceId: captureSandbox.established.instanceId,\n }),\n leaseEpoch: captureSandbox.leaseEpoch,\n sandboxGroupId: captureGroupId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: captureTurnId,\n attemptId: input.attemptId,\n observability,\n signal,\n });\n },\n });\n }\n eventing.toolPreparationClosing = true;\n if (eventing.toolPreparationReady) {\n await waitForTurnFinalizerStep(\n eventing.toolPreparationReady.catch(() => undefined),\n finalizerSignal,\n );\n }\n if (eventing.codemodeDispatcher) {\n await waitForTurnFinalizerStep(\n eventing.codemodeDispatcher.close().catch(() => undefined),\n finalizerSignal,\n );\n eventing.codemodeDispatcher = null;\n }\n if (eventing.preparedTools) {\n await waitForTurnFinalizerStep(\n eventing.preparedTools.close().catch(() => undefined),\n finalizerSignal,\n );\n }\n if (eventing.heartbeatTimer) {\n clearInterval(eventing.heartbeatTimer);\n }\n if (sandboxState.turnSandboxProvisioner?.hasStarted()) {\n await waitForTurnFinalizerStep(\n sandboxState.turnSandboxProvisioner.waitForSettled(30_000),\n finalizerSignal,\n );\n } else if (sandboxState.prefetchedManagedBox) {\n // Create finished (or was aborted) before get()/setup. Join so a\n // successful prefetch cannot leak a holder after this attempt ends.\n await waitForTurnFinalizerStep(\n sandboxState.prefetchedManagedBox.then(\n (box) => {\n sandboxState.prefetchedManagedBoxResult = box;\n },\n () => undefined,\n ),\n finalizerSignal,\n );\n }\n // P1.2: stop the lease-TTL refresh, release the turn holder (idempotent\n // delete-my-row; refcount-- and warm->draining if it hit 0 with no turns),\n // and DROP the in-memory handle. Release NEVER stops the box — the reaper\n // (P1.3) issues the provider stop() past the drain grace at refcount 0; the\n // box rides the provider idle-timeout in the meantime. Best-effort: a\n // release failure must never mask the turn's real outcome.\n if (sandboxState.leaseHeartbeatTimer) {\n stopLeaseHeartbeat();\n }\n if (sandboxState.rotationPreemptionInFlight) {\n await sandboxState.rotationPreemptionInFlight.catch(() => undefined);\n }\n // No heartbeat can register another capture after this point. Join the\n // actual provider continuation before either starting a turn-end capture\n // or entering the proof-bearing holder release.\n await drainInFlightWarmSnapshot();\n if (sandboxState.resolvedSandbox) {\n // TURN-END mid-session snapshot (sandbox-file-persistence): fold the\n // turn's finished /workspace onto the lease before releasing the holder,\n // so the work this turn just produced survives any unclean box death in\n // the idle window ahead. Throttled by the same interval as the heartbeat\n // tick (a short turn right after a snapshot skips — bounded-loss contract\n // is the interval, not per-turn). Best-effort and time-capped by the\n // helper's own failure discipline; never delays release on failure.\n const settledTurnId = attempt.turnId;\n if (\n runTurnEndPersistence &&\n sandboxState.setupBoxSession &&\n sandboxState.sandboxGroupId &&\n settledTurnId\n ) {\n const snapshot = maybePersistWarmWorkspaceSnapshot(\n { db, settings, objectStorage },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: settledTurnId,\n attemptId: input.attemptId,\n sandboxGroupId: sandboxState.sandboxGroupId,\n },\n sandboxState.setupBoxSession,\n sandboxState.resolvedSandbox.leaseEpoch,\n finalizerSignal,\n );\n sandboxState.snapshotInFlight = snapshot.settled;\n const persisted = await snapshot;\n if (persisted && eventing.publish) {\n await eventing\n .publish([\n {\n type: \"sandbox.box.snapshot\",\n payload: { trigger: \"turn-end\" },\n },\n ])\n .catch(() => undefined);\n }\n // NB workspace capture no longer runs here — it moved to\n // the TOP of this finally (before preparedTools.close) so it completes\n // while the box is still solidly alive, instead of racing the turn-end\n // teardown that was killing 100% of captures on real Modal desktop boxes.\n }\n }\n } catch (error) {\n finalizationError ??= error;\n console.error(\n \"agent turn finalization failed (turn outcome unaffected)\",\n safeErrorDiagnostic(error),\n );\n } finally {\n // The writer drain is the only authority that licenses settling an\n // abandoned turn admission. Keep this second-stage release outside all\n // later housekeeping so an event/cache/capture/recording failure cannot\n // strand a null-outcome admission forever. Do not race it against\n // Temporal cancellation: the eager listener may already have dropped\n // the holder, and this idempotent proof-bearing pass still must run.\n stopLeaseHeartbeat();\n if (sandboxState.rotationPreemptionInFlight) {\n await sandboxState.rotationPreemptionInFlight.catch(() => undefined);\n }\n await drainInFlightWarmSnapshot();\n const sandboxReleaseTargets = new Set(sandboxState.lateSandboxesAwaitingWriterDrain);\n sandboxState.lateSandboxesAwaitingWriterDrain.clear();\n if (sandboxState.resolvedSandbox) {\n sandboxReleaseTargets.add(sandboxState.resolvedSandbox);\n sandboxState.resolvedSandbox = null;\n } else if (sandboxState.prefetchedManagedBoxResult) {\n sandboxReleaseTargets.add(sandboxState.prefetchedManagedBoxResult);\n }\n sandboxState.prefetchedManagedBoxResult = null;\n if (sandboxState.attemptWritersDrained) {\n for (const sandboxToRelease of sandboxReleaseTargets) {\n try {\n await releaseTurnSandboxAfterWriterDrain(sandboxToRelease);\n } catch (releaseError) {\n finalizationError ??= releaseError;\n console.error(\n \"sandbox lease quiesced release failed (turn outcome unaffected)\",\n safeErrorDiagnostic(releaseError),\n );\n }\n }\n } else {\n // No proof exists. Ensure every late result still receives the eager\n // leak-prevention release while preserving its admissions as a\n // fail-closed archive-capture fence.\n for (const sandboxToRelease of sandboxReleaseTargets) {\n await sandboxToRelease.release().catch(() => undefined);\n }\n }\n // Close provisioning after consuming the currently known targets. A\n // provider result that races in later is routed through releaseLateSandbox;\n // targets already released above synchronously removed their listener.\n if (!sandboxResumeController.signal.aborted) {\n sandboxResumeController.abort(\n cancellationSignal?.reason ?? new Error(\"TURN_ATTEMPT_FINALIZED\"),\n );\n }\n cancellationSignal?.removeEventListener(\"abort\", noteCancellationRequested);\n const completedAt = performance.now();\n const durationSeconds = (completedAt - activityStarted) / 1000;\n const finalizationDurationSeconds = (completedAt - finalizationStarted) / 1000;\n observability.observeHistogram({\n name: \"opengeni_turn_finalization_duration_seconds\",\n help: \"Agent turn finalization duration, including workspace housekeeping and lease release.\",\n labels: {\n cancellation_requested: String(control.cancellationRequestedAt !== null),\n },\n value: finalizationDurationSeconds,\n });\n if (control.cancellationRequestedAt !== null) {\n const physicalCancellationDurationSeconds =\n (completedAt - control.cancellationRequestedAt) / 1000;\n observability.observeHistogram({\n name: \"opengeni_turn_physical_cancellation_duration_seconds\",\n help: \"Time from Temporal cancellation delivery until the activity physically stops.\",\n value: physicalCancellationDurationSeconds,\n });\n observability.info(\"agent turn physical cancellation completed\", {\n durationMs: Math.round(physicalCancellationDurationSeconds * 1000),\n ...(sandboxState.sandboxGroupId\n ? {\n sandboxLeaseKey: sandboxLeaseTelemetryKey(\n input.workspaceId,\n sandboxState.sandboxGroupId,\n ),\n }\n : {}),\n });\n }\n observability.recordWorkerActivity({\n activity: \"runAgentTurn\",\n status: finalizationError ? \"cleanup_failed\" : control.activityStatus,\n durationSeconds,\n });\n if (attempt.turnId && control.activityStatus !== \"unknown\") {\n turnLifecycleMetricsFor(observability).finish(\n attempt.turnId,\n control.turnMetricOutcome,\n durationSeconds,\n );\n }\n activitySpan.end({\n attributes: {\n \"opengeni.turn_id\": attempt.turnId ?? \"\",\n \"opengeni.status\": control.activityStatus,\n \"opengeni.variable_set_id\": workspaceRefs.variableSetId,\n \"opengeni.rig_id\": workspaceRefs.rigId,\n \"opengeni.rig_version_id\": workspaceRefs.rigVersionId,\n \"opengeni.codex_credential_id\": providerTurn.effectiveCodexCredentialId ?? \"\",\n \"opengeni.duration_ms\": Math.round(durationSeconds * 1000),\n \"opengeni.finalization_duration_ms\": Math.round(finalizationDurationSeconds * 1000),\n },\n error:\n finalizationError || control.activityError\n ? safeErrorForTelemetry(finalizationError ?? control.activityError)\n : undefined,\n });\n // This timer runs only after the activity promise and its full turn\n // stack unwind. Checkpoint collection alone cannot reclaim objects that\n // remain strongly reachable until this terminal boundary.\n turnCompletionMemoryCollector.schedule(observability);\n assertPhysicalToolQuiescenceForCancellation({\n acknowledgeQuiescence: control.acknowledgeQuiescence,\n physicalToolQuiescenceConfirmed,\n failure: finalizationError,\n });\n assertSessionAttemptQuiescenceRecoveryDurable({\n acknowledgeQuiescence: control.acknowledgeQuiescence,\n physicalToolQuiescenceConfirmed,\n receiptOrProofDurable: quiescenceReceiptOrProofDurable,\n failure: finalizationError,\n });\n }\n}\n","// Workbench v2 — turn-end workspace capture.\n//\n// The universal spine that makes the session workspace paint instantly on cold /\n// offline reads: at TURN END, while the box is still guaranteed live and the\n// turn's lease pins the refcount (the reaper cannot drain), we probe the box's\n// CHANGED files directly off the un-proxied Channel-A session — per-repo git\n// status + diff, after-images of the touched files, and a pruned tree index —\n// serialize a manifest, PUT it + the after-image blobs to object storage, and\n// insert an epoch-fenced `workspace_captures` row. The read path (M2/M3) serves\n// this when the machine is cold/offline; a warm box always wins (capture is a\n// labelled cache, never a replacement).\n//\n// SAFETY INVARIANTS (non-negotiable — see):\n// • This module NEVER calls close()/terminate()/kill() on the session handle.\n// session.close() == terminate() on Modal and would kill the user's box.\n// Only the reaper terminates. We drop references, nothing more.\n// • The whole capture is time-capped (120s) and best-effort: ANY failure logs\n// \"workspace capture failed — turn outcome unaffected\" and returns; nothing\n// throws past captureWorkspaceRevision.\n// • The DB write is fenced on the exact attempt, accepted control requests,\n// and lease epoch — a cancelled attempt or superseded lease writes zero rows\n// (insertWorkspaceCapture).\n// • F9 storage ordering: blobs + manifest are PUT and the row is committed\n// BEFORE any GC delete runs.\n//\n// It is deliberately an EXTERNAL module with a SINGLE call-site line in\n// agent-turn.ts's finally (the accepted design tradeoff — do not grow the turn\n// activity). The emitted `workspace.revision.captured` event is ANNOUNCE-ONLY\n// (metadata, never content) and must never gain a rendered timeline item.\n\nimport { createHash } from \"node:crypto\";\nimport type { Settings } from \"@opengeni/config\";\nimport type { Database } from \"@opengeni/db\";\nimport {\n deleteWorkspaceCaptureRows,\n insertFailedWorkspaceCapture,\n insertWorkspaceCapture,\n latestWorkspaceCapture,\n planWorkspaceCaptureGc,\n} from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport type { Observability } from \"@opengeni/observability\";\n// The un-agent-loop leaf. Constructing the Channel-A service over the un-proxied\n// setupBoxSession here (NOT the routing veneer) guarantees a mid-turn\n// sandbox_swap can never re-route capture execs onto a user's machine — the same\n// reason the snapshot uses setupBoxSession.\nimport {\n SandboxChannelAService,\n type ChannelASession,\n type RepositoryDiscoveryDegradedReason,\n} from \"@opengeni/runtime/sandbox\";\nimport type {\n FsTreeNode,\n GitFileStatus,\n GitFileStatusCode,\n SessionEvent,\n WorkspaceCaptureFile,\n WorkspaceCaptureDegradedReason,\n WorkspaceCaptureManifest,\n WorkspaceCaptureRepo,\n WorkspaceCaptureStats,\n} from \"@opengeni/contracts\";\n\n// ─── Guards & constants for pathological cases; configurable ─────\n// Production Modal captures of the acceptance workspace normally take ~30s:\n// repository diff framing deliberately trades provider round-trips for bounded\n// output and symlink-safe reads. Sixty seconds gave that healthy path only a 2x\n// margin and repeatedly timed it out under ordinary provider variance. The turn\n// holder keeps the exact lease pinned for this whole window.\nexport const CAPTURE_TIMEOUT_MS = 120_000;\nexport const PER_FILE_CONTENT_GUARD_BYTES = 5 * 1024 * 1024; // after-image; over → tooLarge marker\nexport const PER_FILE_DIFF_GUARD_BYTES = 10 * 1024 * 1024; // per-file diff; over → truncated marker\nexport const WHOLE_CAPTURE_GUARD_BYTES = 200 * 1024 * 1024; // total → skip, fall back to live\nexport const KEEP_LATEST_REVISIONS = 10;\n// Directories listed as collapsed nodes in the tree index but NEVER descended\n// (their contents live on the machine — the Files tab wakes to expand them).\n//\n// Two classes:\n// • BUILD/DEP residue — huge, machine-resident, never review content.\n// • DESKTOP/SYSTEM residue (the Modal desktop-box fix): on a desktop image the\n// workspace root IS $HOME, and XFCE/dbus/etc. CONTINUOUSLY rewrite dotfiles\n// under ~/.config/xfce4, ~/.cache, ~/.dbus, … A tree walk that descends into\n// them (a) wastes the round-trip budget on churn no user is reviewing and\n// (b) races files that VANISH mid-walk. These are never workspace content, so\n// collapse them at the source. Legit hidden entries a user DOES author\n// (.gitignore, .env, .github, .vscode, .devcontainer) are deliberately NOT\n// here — they stay fully visible.\nexport const RESIDUE_DIRS: readonly string[] = [\n // build/dep residue\n \"node_modules\",\n \".git\",\n // Platform credential/helper state. The workspace root can be $HOME, so this\n // directory may sit inside a root repository; it must never enter a revision.\n \".opengeni\",\n \"dist\",\n \"build\",\n \"target\",\n \".venv\",\n \"__pycache__\",\n \".next\",\n // desktop/system residue (never workspace content; churned by the desktop stack)\n \".config\",\n \".cache\",\n \".local\",\n \".dbus\",\n \".gnupg\",\n \".ssh\",\n \".mozilla\",\n \".xfce4\",\n \".pki\",\n \".gvfs\",\n \".dbus-keyrings\",\n \".Xauthority\",\n \".ICEauthority\",\n];\nconst RESIDUE_DIR_SET: ReadonlySet<string> = new Set(RESIDUE_DIRS);\n\n/**\n * True when a workspace-relative FILE path lives INSIDE a residue dir — i.e. a\n * residue dir is one of its ANCESTOR segments (not the leaf), so the file is\n * churn/machine content never worth an after-image. `.config/xfce4/xfconf/…` and\n * `.config/mimeapps.list` → true; a root FILE literally named `.config` (a user\n * config the seed edits) → false (single segment, no residue ancestor); and\n * `.github/x.yml`, `.gitignore` → false (`.github`/`.gitignore` are not residue).\n * Matches the tree-BFS collapse (which collapses residue DIR nodes) so the\n * Changes tab and the tree agree on what is workspace content.\n */\nexport function isUnderResidueDir(wsPath: string): boolean {\n const segments = wsPath.split(\"/\");\n // Check ancestors only (every segment except the leaf): the leaf is the file\n // itself; a residue-named file at the root is still legitimate content.\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i];\n if (seg && RESIDUE_DIR_SET.has(seg)) return true;\n }\n return false;\n}\n\n/**\n * The box is being torn down under us (Modal reclaim / reaper drain / terminate)\n * — NOT a single file vanishing. Every subsequent op will fail too, so the\n * capture must ABORT (throw) rather than skip-and-continue, so it never commits a\n * bogus empty/partial revision for a dead box. Matched loosely so a provider\n * wording tweak still classifies. (The real fix for this is keeping the box\n * pinned through the capture window — sandbox-resume / agent-turn lease\n * heartbeat; this classifier only guarantees we fail HONESTLY if it still races.)\n */\nexport function isBoxExitingError(error: unknown): boolean {\n const msg = (error instanceof Error ? error.message : String(error ?? \"\")).toLowerCase();\n return (\n msg.includes(\"container exiting\") ||\n msg.includes(\"container is exiting\") ||\n msg.includes(\"container exited\") ||\n msg.includes(\"sandbox has been terminated\") ||\n msg.includes(\"sandbox is not running\") ||\n msg.includes(\"sandbox has terminated\") ||\n msg.includes(\"task has exited\")\n );\n}\n\n/** Marker thrown when the box died mid-capture — aborts cleanly (no partial row). */\nexport class BoxExitingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BoxExitingError\";\n }\n}\n\n/** Re-throw as a BoxExitingError when the box is gone; otherwise return null so\n * the caller SKIPS this single entry (a vanished/unreadable file) and continues.\n * One churning file must never kill the capture; a dead box must never yield a\n * bogus revision. */\nfunction classifyCaptureEntryError(error: unknown): BoxExitingError | null {\n if (isBoxExitingError(error)) {\n return new BoxExitingError(error instanceof Error ? error.message : String(error));\n }\n return null;\n}\nconst TREE_MAX_ENTRIES = 20_000; // whole-tree node cap (truncate beyond)\nconst TREE_MAX_DEPTH = 600; // pathological nesting cap; still one remote round-trip\n\n// The capture row and announcement are committed together by @opengeni/db. This\n// callback performs only best-effort live fanout of those already-durable events.\nexport type CaptureEventPublisher = (events: SessionEvent[]) => Promise<void>;\n\nexport type CaptureWorkspaceRevisionInput = {\n db: Database;\n objectStorage: ObjectStorage | null;\n settings: Settings;\n publish: CaptureEventPublisher | null;\n /** The un-proxied setupBoxSession (NOT the routing veneer). */\n session: ChannelASession;\n /**\n * Reopen the exact live provider instance as a fresh, non-owning read handle.\n * Modal sessions keep mutable exec-process bookkeeping; reusing the handle\n * that just drove model tools can strand a later capture command behind stale\n * provider state. The lease still owns the box. Capture drops this handle\n * without calling close(), which would terminate Modal's sandbox.\n */\n openReadSession?: () => Promise<ChannelASession>;\n leaseEpoch: number;\n sandboxGroupId: string;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n observability: Observability;\n /**\n * The owning turn activity's cancellation signal. Pause/Steer must preempt\n * review-cache housekeeping immediately; correctness still comes from the\n * activity plus the capture's transaction-level attempt/control/lease fences.\n */\n signal?: AbortSignal;\n /** Test-only: override keep-latest-N GC threshold (default 10). */\n keepLatest?: number;\n};\n\ntype CaptureRepositoryReadResult =\n | {\n complete: true;\n status: Awaited<ReturnType<SandboxChannelAService[\"gitStatus\"]>>;\n diff: Awaited<ReturnType<SandboxChannelAService[\"gitDiff\"]>>;\n branchDiff?: Awaited<ReturnType<SandboxChannelAService[\"gitDiff\"]>> | undefined;\n }\n | { complete: false; degradedReason: \"repository_read_unavailable\" };\n\ntype ResumableCaptureClient = {\n resume?: (state: unknown) => Promise<unknown>;\n};\n\ntype StatefulCaptureSession = ChannelASession & {\n state?: unknown;\n};\n\nfunction captureSessionInstanceId(session: unknown): string | null {\n const state =\n session && typeof session === \"object\"\n ? (session as { state?: Record<string, unknown> }).state\n : undefined;\n if (!state || typeof state !== \"object\") return null;\n for (const value of [\n state.sandboxId,\n state.instanceId,\n state.id,\n state.hostId,\n state.containerId,\n state.workspaceRootPath,\n ]) {\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return null;\n}\n\n/**\n * Reattach a clean SDK handle to the exact already-live Modal sandbox. Modal's\n * resume contract is a pure from-id reattach. Other providers keep the original\n * session because their generic resume contract may restore or replace a dead\n * instance, which capture does not own.\n */\nexport async function openFreshWorkspaceCaptureSession(input: {\n backendId: string;\n client: unknown;\n session: ChannelASession;\n expectedInstanceId: string;\n}): Promise<ChannelASession> {\n if (input.backendId !== \"modal\") {\n return input.session;\n }\n const client = input.client as ResumableCaptureClient;\n const state = (input.session as StatefulCaptureSession).state;\n if (typeof client.resume !== \"function\" || state === undefined) {\n return input.session;\n }\n // The lease—not this temporary reader—owns provider teardown. Preserve the\n // exact state while explicitly removing close/terminate authority from\n // providers (Modal) that encode it in the resumed state.\n const readState =\n state !== null && typeof state === \"object\" ? { ...state, ownsSandbox: false } : state;\n const reopened = await client.resume(readState);\n const actualInstanceId = captureSessionInstanceId(reopened);\n if (input.expectedInstanceId.length > 0 && actualInstanceId !== input.expectedInstanceId) {\n throw new Error(\n `workspace capture reopened provider instance ${actualInstanceId ?? \"unknown\"}, expected ${input.expectedInstanceId}`,\n );\n }\n return reopened as ChannelASession;\n}\n\n/** One discovered repository is all-or-nothing capture authority. A provider\n * transport failure must never be represented as an authoritative empty diff. */\nexport async function readCaptureRepository(\n svc: Pick<SandboxChannelAService, \"gitStatus\" | \"gitDiff\">,\n root: string,\n): Promise<CaptureRepositoryReadResult> {\n let status: Awaited<ReturnType<SandboxChannelAService[\"gitStatus\"]>>;\n try {\n status = await svc.gitStatus({ path: root });\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n return { complete: false, degradedReason: \"repository_read_unavailable\" };\n }\n if (!status.isRepo) {\n return { complete: false, degradedReason: \"repository_read_unavailable\" };\n }\n try {\n const workingRequest = svc.gitDiff({\n path: root,\n staged: false,\n includeUntracked: true,\n fromRef: \"HEAD\",\n pathspec: [],\n contextLines: 3,\n maxBytesPerFile: PER_FILE_DIFF_GUARD_BYTES,\n });\n // Branch capture is additive. A repository without origin/HEAD must not\n // degrade the authoritative working-tree capture.\n const branchRequest = Promise.resolve()\n .then(() =>\n svc.gitDiff({\n path: root,\n staged: false,\n includeUntracked: true,\n fromRef: \"origin/HEAD\",\n pathspec: [],\n contextLines: 3,\n maxBytesPerFile: PER_FILE_DIFF_GUARD_BYTES,\n }),\n )\n .then((value) => value)\n .catch(() => null);\n const [diff, branchDiff] = await Promise.all([workingRequest, branchRequest]);\n return {\n complete: true,\n status,\n diff,\n ...(branchDiff ? { branchDiff } : {}),\n };\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n return { complete: false, degradedReason: \"repository_read_unavailable\" };\n }\n}\n\nlet loggedStorageNullOnce = false;\n\n/** Review work may use idle time, but must yield to the next turn. Poll durable\n * queue state rather than relying on best-effort event delivery. The capture\n * already fences every continuation on this signal; no replacement writer is\n * admitted until its caller returns. */\nexport async function captureWhileIdle(input: {\n hasPendingWork: () => Promise<boolean>;\n capture: (signal: AbortSignal) => Promise<void>;\n signal?: AbortSignal;\n}): Promise<void> {\n if (input.signal?.aborted) return;\n const controller = new AbortController();\n const signal = input.signal\n ? AbortSignal.any([input.signal, controller.signal])\n : controller.signal;\n let checking = false;\n let stopped = false;\n const check = async (): Promise<void> => {\n if (checking || stopped || signal.aborted) return;\n checking = true;\n try {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let onAbort: (() => void) | undefined;\n try {\n const pending = await Promise.race([\n input.hasPendingWork(),\n new Promise<boolean>((resolve) => {\n onAbort = () => resolve(true);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n timer = setTimeout(() => resolve(true), 1_000);\n }),\n ]);\n if (pending) controller.abort();\n } finally {\n clearTimeout(timer);\n if (onAbort) signal.removeEventListener(\"abort\", onAbort);\n }\n } catch {\n // A failed queue read is not permission to delay accepted user work.\n controller.abort();\n } finally {\n checking = false;\n }\n };\n await check();\n if (signal.aborted) return;\n const timer = setInterval(() => void check(), 250);\n timer.unref?.();\n try {\n await input.capture(signal);\n } finally {\n stopped = true;\n clearInterval(timer);\n controller.abort();\n }\n}\n\n/**\n * Turn-end entrypoint. Gates on the flag + configured object storage, races the\n * whole capture against a 120s cap, and swallows every failure (\"turn outcome\n * unaffected\"). Returns void — the caller awaits it (it self-caps) and moves on\n * to release() regardless.\n */\nexport async function captureWorkspaceRevision(\n input: CaptureWorkspaceRevisionInput,\n): Promise<void> {\n const { observability } = input;\n const stage = { value: \"preflight\" };\n if (input.signal?.aborted) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"cancelled\" },\n });\n return;\n }\n if (!input.settings.workspaceCaptureEnabled) {\n return; // flag off → capture skipped; reads fall back to live/wake (status quo)\n }\n if (!input.objectStorage) {\n if (!loggedStorageNullOnce) {\n loggedStorageNullOnce = true;\n observability.info(\"workspace capture skipped — object storage not configured\");\n }\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"skipped_no_storage\" },\n });\n return;\n }\n\n const startedAt = Date.now();\n const controller = new AbortController();\n let rejectOwnerCancellation: ((reason?: unknown) => void) | undefined;\n const ownerCancelled = input.signal\n ? new Promise<never>((_resolve, reject) => {\n rejectOwnerCancellation = reject;\n })\n : new Promise<never>(() => undefined);\n const cancelFromOwner = (): void => {\n controller.abort(input.signal?.reason);\n rejectOwnerCancellation?.(\n input.signal?.reason ?? new Error(\"workspace capture cancelled by its owning activity\"),\n );\n };\n input.signal?.addEventListener(\"abort\", cancelFromOwner, { once: true });\n if (input.signal?.aborted) cancelFromOwner();\n observability.incrementGauge({\n name: \"opengeni_workspace_captures_inflight\",\n help: \"Current workspace-capture operations still resident in this worker process.\",\n });\n const ownership = { keys: new Set<string>(), retain: false };\n const capture = runCapture(\n input,\n { ...input, objectStorage: input.objectStorage },\n startedAt,\n controller.signal,\n stage,\n ownership,\n ).finally(async () => {\n // Cleanup follows physical write settlement, even after inference resumes.\n // Unique keys cannot belong to a successor capture.\n if (!ownership.retain && ownership.keys.size > 0) {\n await safeDelete(\n input.objectStorage!,\n [...ownership.keys],\n observability,\n new AbortController().signal,\n );\n }\n observability.incrementGauge({\n name: \"opengeni_workspace_captures_inflight\",\n help: \"Current workspace-capture operations still resident in this worker process.\",\n amount: -1,\n });\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n capture,\n ownerCancelled,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new Error(`workspace capture exceeded ${CAPTURE_TIMEOUT_MS}ms`));\n }, CAPTURE_TIMEOUT_MS);\n }),\n ]);\n } catch (error) {\n if (input.signal?.aborted) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"cancelled\" },\n });\n return;\n }\n // The one and only place a capture failure surfaces — as a log line, never\n // an exception past this boundary (the turn already completed).\n // Public telemetry intentionally strips arbitrary error text and unknown\n // attributes. Keep the bounded stage/reason in the message so operators can\n // distinguish a deadline from provider loss without logging file contents,\n // credentials, paths, or upstream exception messages.\n const reason = controller.signal.aborted\n ? \"deadline_exceeded\"\n : isBoxExitingError(error)\n ? \"sandbox_exited\"\n : \"operation_failed\";\n observability.warn(\n `workspace capture failed — stage=${stage.value} reason=${reason} durationMs=${Date.now() - startedAt}; review cache not updated`,\n {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": input.turnId ?? \"\",\n \"error.message\": error instanceof Error ? error.message : String(error),\n \"workspace_capture.duration_ms\": Date.now() - startedAt,\n \"workspace_capture.stage\": stage.value,\n },\n );\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"failed\" },\n });\n } finally {\n if (timer) clearTimeout(timer);\n input.signal?.removeEventListener(\"abort\", cancelFromOwner);\n controller.abort();\n }\n}\n\n// The strongly-typed inner run (objectStorage proven non-null by the caller).\nasync function runCapture(\n input: CaptureWorkspaceRevisionInput,\n ctx: CaptureWorkspaceRevisionInput & { objectStorage: ObjectStorage },\n startedAt: number,\n signal: AbortSignal,\n stage: { value: string },\n ownership: { keys: Set<string>; retain: boolean },\n): Promise<void> {\n const ownedKeys = ownership.keys;\n const { observability } = input;\n const storage = ctx.objectStorage;\n const keepN = input.keepLatest ?? KEEP_LATEST_REVISIONS;\n stage.value = \"open_read_session\";\n const readSession = input.openReadSession ? await input.openReadSession() : input.session;\n throwIfCaptureAborted(signal);\n // Reads only — no emitter (we publish the announce ourselves after commit).\n const svc = new SandboxChannelAService({ session: readSession, leaseEpoch: input.leaseEpoch });\n\n // Resolve the previous revision before discovery so even a failed discovery\n // can commit a monotonic, explicit degraded marker. That marker becomes the\n // newest read result and prevents an older successful capture from being\n // mistaken for the current turn's authoritative workspace state.\n stage.value = \"load_previous_capture\";\n const prev = await latestWorkspaceCapture(input.db, input.workspaceId, input.sessionId);\n throwIfCaptureAborted(signal);\n const revision = (prev?.revision ?? -1) + 1;\n\n // ── 1. per-repo status + diff, union the touched set ──────────────────────\n stage.value = \"repository_discovery\";\n const discovery = await svc.detectReposDetailed();\n throwIfCaptureAborted(signal);\n if (process.env.OPENGENI_TEST_SCENARIO === \"sandbox\") {\n console.log(\n `[sandbox-e2e] capture discovery complete=${discovery.complete} repos=${JSON.stringify(discovery.repos)} degraded=${discovery.degradedReason ?? \"none\"}`,\n );\n }\n if (!discovery.complete) {\n const reason = captureDegradedReason(discovery.degradedReason);\n await persistDegradedCapture(\n input,\n startedAt,\n signal,\n revision,\n reason,\n discovery.repos.length,\n );\n return;\n }\n const repoRoots = discovery.repos;\n const repos: WorkspaceCaptureRepo[] = [];\n // workspace-relative path → touched-file descriptor\n const touched = new Map<string, { status: GitFileStatusCode; deleted: boolean }>();\n let additions = 0;\n let deletions = 0;\n\n for (const root of repoRoots) {\n stage.value = \"repository_read\";\n throwIfCaptureAborted(signal);\n // Repository discovery defines the authoritative set. Once a root is in\n // that set, status/diff failure must degrade the entire revision rather than\n // publish a partial or false-empty change surface. Box death still aborts\n // through the outer best-effort boundary.\n const repository = await readCaptureRepository(svc, root);\n throwIfCaptureAborted(signal);\n if (!repository.complete) {\n await persistDegradedCapture(\n input,\n startedAt,\n signal,\n revision,\n repository.degradedReason,\n repoRoots.length,\n );\n return;\n }\n const { status, diff, branchDiff } = repository;\n // Drop residue churn from the review diff too. On a desktop box the seed's\n // `git add -A` in $HOME commits ~/.config/xfce4/* into HEAD, so `git diff HEAD`\n // lists the continuously-rewritten desktop dotfiles as changed — noise the\n // Changes tab must not show. The status/after-image loop already excludes them\n // (isUnderResidueDir); exclude them here so the diff surface agrees.\n const diffFiles = diff.files.filter((f) => !isUnderResidueDir(joinRepoPath(root, f.path)));\n // Also drop residue-only status entries below; status.files is filtered in the\n // touched loop (isUnderResidueDir), so `status: status.files` would still carry\n // residue rows — filter for a consistent captured status surface.\n const statusFiles = status.files.filter((f) => !isUnderResidueDir(joinRepoPath(root, f.path)));\n repos.push({\n root,\n head: status.head,\n headOid: status.headOid ?? null,\n detached: status.detached,\n upstream: status.upstream,\n ahead: status.ahead,\n behind: status.behind,\n status: statusFiles,\n diff: diffFiles,\n ...(branchDiff\n ? {\n branchDiff: branchDiff.files.filter(\n (f) => !isUnderResidueDir(joinRepoPath(root, f.path)),\n ),\n }\n : {}),\n });\n for (const f of diffFiles) {\n additions += f.additions;\n deletions += f.deletions;\n }\n for (const f of status.files) {\n const wsPath = joinRepoPath(root, f.path);\n // Skip desktop/system residue churn (~/.config/xfce4/…): on a desktop box\n // the workspace root is $HOME, so git reports the continuously-rewritten\n // XFCE/cache dotfiles as untracked. They are never review content — dropping\n // them here keeps the after-image loop off churn AND matches the tree BFS's\n // residue collapse (Changes tab and tree agree on what is workspace content).\n if (isUnderResidueDir(wsPath)) continue;\n touched.set(wsPath, {\n status: statusCodeOf(f),\n deleted: f.worktree === \"deleted\" || f.index === \"deleted\",\n });\n }\n }\n\n // Previous revision (for the empty-turn gate + revision assignment). The gate\n // itself fires AFTER the after-image loop, once the change fingerprint is known\n // (§10.1 / B3): uncommitted changes persist in the box across turns, so a\n // literal \"skip when git status is clean\" gate would re-capture an identical\n // dirty tree on every read-only turn. Instead we skip when the change surface\n // is byte-identical to the previous revision — \"no new revision when nothing\n // changed\" holds even with a persistently dirty tree, and content-addressed\n // blobs dedupe against the latest retained capture. This preserves empty-turn revision behavior\n // while correctly handling a persistently dirty tree.\n // ── 3. after-images of touched files (size-gated), content-addressed ───────\n const files: WorkspaceCaptureFile[] = [];\n const blobKeys = new Set<string>();\n const captureId = crypto.randomUUID();\n // A predecessor GC plan keeps the latest revision's refs. Never reuse refs\n // from older revisions: an already-issued delete may still target those.\n const retainedRefs = retainedCaptureBlobRefs(\n input.workspaceId,\n input.sessionId,\n prev?.blobKeys ?? [],\n );\n const storedKeys = new Set(retainedRefs.values());\n let totalBytes = 0;\n let tooLargeCount = 0;\n let binaryCount = 0;\n\n for (const [wsPath, info] of touched) {\n stage.value = \"file_read\";\n throwIfCaptureAborted(signal);\n if (info.deleted) {\n files.push({\n path: wsPath,\n status: \"deleted\",\n hash: null,\n baseHash: null,\n contentRef: null,\n sizeBytes: 0,\n isBinary: false,\n tooLarge: false,\n deleted: true,\n });\n continue;\n }\n // Always request base64 so we get raw bytes uniformly (text or binary) for\n // content-addressing. maxBytes caps the read at the 5MB guard; `truncated`\n // means the file is ≥5MB → we record a tooLarge marker (no content blob).\n //\n // Per-file resilience: a file the box reported as changed can VANISH or turn\n // unreadable between git-status and this read (fs churn, a follow-up mutation,\n // a race). That must NEVER abort the whole capture — skip the one entry and\n // keep the rest. A box-death error is different: it aborts (BoxExitingError),\n // because every remaining read would fail too and we must not commit a partial\n // revision for a dead box.\n let read: Awaited<ReturnType<typeof svc.fsRead>>;\n try {\n read = await svc.fsRead({\n path: wsPath,\n encoding: \"base64\",\n maxBytes: PER_FILE_CONTENT_GUARD_BYTES,\n });\n throwIfCaptureAborted(signal);\n } catch (error) {\n if (signal.aborted) throw error;\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n continue; // vanished/unreadable single file — omit it, capture continues\n }\n if (read.truncated) {\n tooLargeCount += 1;\n files.push({\n path: wsPath,\n status: info.status,\n hash: null,\n baseHash: null,\n contentRef: null,\n sizeBytes: read.sizeBytes,\n isBinary: read.isBinary,\n tooLarge: true,\n deleted: false,\n });\n continue;\n }\n const bytes = Buffer.from(read.content, \"base64\");\n const hash = sha256(bytes);\n const contentRef =\n retainedRefs.get(hash) ?? blobKey(input.workspaceId, input.sessionId, `${captureId}/${hash}`);\n if (read.isBinary) binaryCount += 1;\n if (!blobKeys.has(contentRef)) {\n totalBytes += bytes.byteLength;\n // Never publish a revision exceeding the whole-capture byte limit.\n if (totalBytes > WHOLE_CAPTURE_GUARD_BYTES) {\n observability.warn(\"workspace capture skipped — whole-capture guard tripped\", {\n \"opengeni.session_id\": input.sessionId,\n \"workspace_capture.total_bytes\": totalBytes,\n });\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"guard_tripped\" },\n });\n return;\n }\n }\n blobKeys.add(contentRef);\n if (!storedKeys.has(contentRef)) {\n stage.value = \"content_upload\";\n ownedKeys.add(contentRef);\n await storage.putObject({\n key: contentRef,\n contentType: \"application/octet-stream\",\n body: bytes,\n });\n throwIfCaptureAborted(signal);\n storedKeys.add(contentRef);\n }\n files.push({\n // baseHash (git HEAD blob sha) is intentionally null in M1: the wake-on-edit\n // flush guard (M3/C2) compares live content against the after-image `hash`,\n // not the HEAD blob, so baseHash is not load-bearing yet. Populating it would\n // cost an extra per-file round-trip at turn end (latency risk #1). Deferred.\n path: wsPath,\n status: info.status,\n hash,\n baseHash: null,\n contentRef,\n sizeBytes: bytes.byteLength,\n isBinary: read.isBinary,\n tooLarge: false,\n deleted: false,\n });\n }\n\n // ── 4. empty-turn gate (B3) ───────────────────────────────\n // Skip when the change surface is byte-identical to the previous revision.\n // New writes use unique keys; reused refs belong to the latest retained revision.\n // An unchanged dirty turn therefore performs no object-storage writes.\n // Each file is read once and its exact bytes are hashed and uploaded together;\n // peak memory remains one guarded file rather than the entire workspace.\n const fingerprint = changeFingerprint(repos, files);\n if (prev && prev.stats.fingerprint === fingerprint) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"skipped_empty\" },\n });\n return;\n }\n\n // ── 5. tree index (one bounded listing; residue dirs pruned at source) ─────\n stage.value = \"tree_index\";\n const tree = await buildTreeIndex(svc, startedAt, signal);\n throwIfCaptureAborted(signal);\n\n // ── 6. PUT blobs + tree + manifest (F9: all writes BEFORE any delete) ──────\n // Key manifest/tree by the turn (one capture per turn) so the key is known\n // before commit. Unique capture namespaces make late deletes safe across workers.\n const turnKey = `${input.turnId}/${captureId}`;\n const treeKey = `workspace-captures/${input.workspaceId}/${input.sessionId}/trees/${turnKey}.json`;\n const manifestKey = `workspace-captures/${input.workspaceId}/${input.sessionId}/manifests/${turnKey}.json`;\n\n // ── 7. serialize the exact uploaded after-images ──────────────────────────\n const capturedAt = new Date();\n const stats: WorkspaceCaptureStats = {\n repoCount: repos.length,\n fileCount: files.length,\n additions,\n deletions,\n totalBytes,\n tooLargeCount,\n binaryCount,\n treeEntryCount: tree.entryCount,\n treeTruncated: tree.truncated,\n durationMs: 0, // filled after tree/content writes, before manifest serialization\n fingerprint,\n };\n const manifest: WorkspaceCaptureManifest = {\n version: 1,\n revision,\n capturedAt: capturedAt.toISOString(),\n turnId: input.turnId,\n leaseEpoch: input.leaseEpoch,\n treeIndex: tree.root,\n treeTruncated: tree.truncated,\n repos,\n files,\n stats,\n };\n const treeBytes = utf8(\n JSON.stringify({\n version: 1,\n root: tree.root,\n truncated: tree.truncated,\n entryCount: tree.entryCount,\n }),\n );\n stage.value = \"tree_upload\";\n ownedKeys.add(treeKey);\n await storage.putObject({ key: treeKey, contentType: \"application/json\", body: treeBytes });\n throwIfCaptureAborted(signal);\n stats.durationMs = Date.now() - startedAt;\n const manifestBytes = utf8(JSON.stringify(manifest));\n stage.value = \"manifest_upload\";\n ownedKeys.add(manifestKey);\n await storage.putObject({\n key: manifestKey,\n contentType: \"application/json\",\n body: manifestBytes,\n });\n throwIfCaptureAborted(signal);\n const sizeBytes = totalBytes + treeBytes.byteLength + manifestBytes.byteLength;\n\n // ── 8. epoch-fenced insert (superseded lease → zero rows) ─────────────────\n stage.value = \"database_commit\";\n // A transport failure during commit has an unknown outcome: retain rather\n // than risk deleting a published review. A definite rejected commit is safe.\n ownership.retain = true;\n const inserted = await insertWorkspaceCapture(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: input.leaseEpoch,\n revision,\n manifestKey,\n treeIndexKey: treeKey,\n blobKeys: [...blobKeys],\n sizeBytes,\n stats,\n capturedAt,\n });\n ownership.retain = inserted !== null;\n if (process.env.OPENGENI_TEST_SCENARIO === \"sandbox\") {\n console.log(\n `[sandbox-e2e] capture commit inserted=${Boolean(inserted)} revision=${revision} epoch=${input.leaseEpoch} group=${input.sandboxGroupId}`,\n );\n }\n throwIfCaptureAborted(signal);\n if (!inserted) {\n // Lease superseded/released between capture and commit. Best-effort clean up\n // the turn-keyed blobs we just PUT. The finalizer also cleans newly owned\n // content blobs, leaving reused refs untouched; never throw.\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"superseded\" },\n });\n await safeDelete(storage, [manifestKey, treeKey], observability, signal);\n return;\n }\n\n if (input.publish) {\n await input.publish(inserted.events).catch(() => undefined);\n }\n\n // ── 9. inline keep-latest-N GC (best-effort; F9 — after the commit) ────────\n stage.value = \"garbage_collection\";\n let gcDeleted = 0;\n try {\n throwIfCaptureAborted(signal);\n const plan = await planWorkspaceCaptureGc(input.db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n keepN,\n });\n throwIfCaptureAborted(signal);\n if (plan.evictedRowIds.length > 0) {\n await safeDelete(\n storage,\n [...plan.deleteBlobKeys, ...plan.deletePerRevisionKeys],\n observability,\n signal,\n );\n throwIfCaptureAborted(signal);\n gcDeleted = await deleteWorkspaceCaptureRows(input.db, {\n workspaceId: input.workspaceId,\n rowIds: plan.evictedRowIds,\n });\n throwIfCaptureAborted(signal);\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_gc_deletions_total\",\n amount: gcDeleted,\n });\n }\n } catch (gcError) {\n if (signal.aborted) throw gcError;\n // GC is storage hygiene — a failure never affects the just-committed capture.\n observability.warn(\"workspace capture GC failed — capture unaffected\", {\n \"opengeni.session_id\": input.sessionId,\n \"error.message\": gcError instanceof Error ? gcError.message : String(gcError),\n });\n }\n\n // ── 10. observe completion ────────────────────────────────────────────────\n const durationMs = Date.now() - startedAt;\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"ok\" },\n });\n observability.observeHistogram({\n name: \"opengeni_workspace_capture_duration_seconds\",\n value: durationMs / 1000,\n });\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction captureDegradedReason(\n reason: RepositoryDiscoveryDegradedReason | null,\n): WorkspaceCaptureDegradedReason {\n switch (reason) {\n case \"command_timed_out\":\n return \"repository_discovery_timed_out\";\n case \"result_limit_exceeded\":\n return \"repository_discovery_result_limit_exceeded\";\n case \"command_failed\":\n default:\n return \"repository_discovery_command_failed\";\n }\n}\n\nasync function persistDegradedCapture(\n input: CaptureWorkspaceRevisionInput,\n startedAt: number,\n signal: AbortSignal,\n revision: number,\n reason: WorkspaceCaptureDegradedReason,\n discoveredRepoCount: number,\n): Promise<void> {\n const capturedAt = new Date();\n const stats = {\n degradedReason: reason,\n discoveredRepoCount,\n durationMs: Date.now() - startedAt,\n };\n const inserted = await insertFailedWorkspaceCapture(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: input.leaseEpoch,\n revision,\n stats,\n capturedAt,\n });\n throwIfCaptureAborted(signal);\n if (!inserted) {\n input.observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"superseded\" },\n });\n return;\n }\n const discoveryFailure = reason.startsWith(\"repository_discovery_\");\n input.observability.warn(\n discoveryFailure\n ? \"workspace capture degraded — repository discovery incomplete\"\n : \"workspace capture degraded — repository read incomplete\",\n {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": input.turnId ?? \"\",\n \"workspace_capture.degraded_reason\": reason,\n \"workspace_capture.discovered_repo_count\": discoveredRepoCount,\n },\n );\n input.observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: {\n result: discoveryFailure ? \"degraded_repository_discovery\" : \"degraded_repository_read\",\n },\n });\n if (input.publish) {\n await input.publish(inserted.events).catch(() => undefined);\n }\n}\n\nfunction throwIfCaptureAborted(signal: AbortSignal): void {\n if (signal.aborted) {\n throw new Error(\"workspace capture cancelled after its deadline\");\n }\n}\n\nfunction statusCodeOf(f: GitFileStatus): GitFileStatusCode {\n return f.worktree ?? f.index ?? \"modified\";\n}\n\n/**\n * sha256 over the CHANGE SURFACE only — per-file (path, status, hash, deleted,\n * tooLarge), exact HEAD identity, the working diff summary, and exact committed\n * branch changes.\n * Deliberately excludes the tree index and file mtimes (which drift without a\n * real change) so two turns that leave the workspace in the same state produce\n * the same fingerprint (the empty-turn gate). Order-independent (sorted).\n */\nexport function changeFingerprint(\n repos: WorkspaceCaptureRepo[],\n files: WorkspaceCaptureFile[],\n): string {\n const fileParts = files\n .map((f) => `${f.path}|${f.status}|${f.hash ?? \"\"}|${f.deleted ? 1 : 0}|${f.tooLarge ? 1 : 0}`)\n .sort();\n const branchDiffPart = (diff: WorkspaceCaptureRepo[\"diff\"][number]): string =>\n JSON.stringify([\n diff.path,\n diff.oldPath,\n diff.status,\n diff.isBinary,\n diff.isImage,\n diff.additions,\n diff.deletions,\n diff.truncated,\n diff.hunks.map((hunk) => [\n hunk.oldStart,\n hunk.oldLines,\n hunk.newStart,\n hunk.newLines,\n hunk.header,\n hunk.lines.map((line) => [line.type, line.oldNo, line.newNo, line.text]),\n ]),\n ]);\n const repoParts = repos\n .map((repo) => {\n const workingDiff = repo.diff\n .map(\n (diff) =>\n `${diff.path}:${diff.status}:${diff.additions}:${diff.deletions}:${diff.truncated ? 1 : 0}`,\n )\n .sort();\n const branchDiff =\n repo.branchDiff === undefined ? null : repo.branchDiff.map(branchDiffPart).sort();\n return JSON.stringify([\n repo.root,\n repo.head,\n repo.headOid ?? null,\n repo.ahead,\n workingDiff,\n branchDiff,\n ]);\n })\n .sort();\n return sha256(utf8(JSON.stringify({ files: fileParts, repos: repoParts })));\n}\n\n/** Join a repo-root-relative path onto its workspace-relative repo root. */\nexport function joinRepoPath(repoRoot: string, repoRelPath: string): string {\n if (!repoRoot || repoRoot === \"\" || repoRoot === \".\") return repoRelPath;\n return `${repoRoot.replace(/\\/+$/, \"\")}/${repoRelPath}`;\n}\n\nfunction sha256(bytes: Uint8Array): string {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\nfunction utf8(s: string): Uint8Array {\n return new TextEncoder().encode(s);\n}\n\n/** Content-addressed after-image blob key, optionally in a unique capture namespace. */\nexport function blobKey(workspaceId: string, sessionId: string, sha256Hex: string): string {\n return `workspace-captures/${workspaceId}/${sessionId}/blobs/${sha256Hex}`;\n}\n\n/** Only pass the latest retained revision's keys: older refs may be under deletion. */\nexport function retainedCaptureBlobRefs(\n workspaceId: string,\n sessionId: string,\n latestKeys: string[],\n): Map<string, string> {\n const prefix = blobKey(workspaceId, sessionId, \"\");\n const refs = new Map<string, string>();\n for (const key of latestKeys) {\n if (!key.startsWith(prefix)) continue;\n const match = /^(?:[0-9a-f-]{36}\\/)?([0-9a-f]{64})$/.exec(key.slice(prefix.length));\n if (match?.[1]) refs.set(match[1], key);\n }\n return refs;\n}\n\nasync function safeDelete(\n storage: ObjectStorage,\n keys: string[],\n observability: Observability,\n signal: AbortSignal,\n): Promise<void> {\n for (const key of keys) {\n throwIfCaptureAborted(signal);\n await storage.deleteObject(key).catch((error) => {\n observability.warn(\"workspace capture blob delete failed (orphan left; capture unaffected)\", {\n \"storage.key\": key,\n \"error.message\": error instanceof Error ? error.message : String(error),\n });\n });\n }\n}\n\n/**\n * Build the workspace tree index in ONE remote filesystem round-trip. Channel-A\n * prunes residue directories inside `find` while still emitting their collapsed\n * node, so node_modules cannot consume the authored-file budget. The former\n * serial per-directory BFS took 55.8 seconds for a 4,522-entry production tree\n * and blocked Steer cancellation. This path is bounded by entry count, nesting\n * depth, the outer capture deadline, and the owning activity's cancellation.\n */\nasync function buildTreeIndex(\n svc: SandboxChannelAService,\n startedAt: number,\n signal: AbortSignal,\n): Promise<{ root: FsTreeNode; entryCount: number; truncated: boolean }> {\n throwIfCaptureAborted(signal);\n if (Date.now() - startedAt > CAPTURE_TIMEOUT_MS - 5_000) {\n throw new Error(\"workspace capture tree index reached its deadline before listing\");\n }\n let listing: Awaited<ReturnType<typeof svc.fsListPruned>>;\n try {\n listing = await svc.fsListPruned(\n {\n path: \"\",\n depth: TREE_MAX_DEPTH,\n maxEntries: TREE_MAX_ENTRIES,\n includeHidden: true,\n },\n RESIDUE_DIRS,\n );\n throwIfCaptureAborted(signal);\n } catch (error) {\n if (isBoxExitingError(error)) {\n throw new BoxExitingError(error instanceof Error ? error.message : String(error));\n }\n throw error;\n }\n\n let entryCount = 0;\n let depthTruncated = false;\n const stack = [...(listing.root.children ?? [])];\n while (stack.length > 0) {\n const node = stack.pop()!;\n entryCount += 1;\n if (node.type !== \"dir\") continue;\n if (RESIDUE_DIR_SET.has(node.name)) {\n node.truncated = true;\n node.children = [];\n continue;\n }\n if (node.path.split(\"/\").length >= TREE_MAX_DEPTH) {\n node.truncated = true;\n depthTruncated = true;\n continue;\n }\n stack.push(...(node.children ?? []));\n }\n return {\n root: listing.root,\n entryCount,\n truncated: listing.truncated || depthTruncated,\n };\n}\n","import {\n requestSessionTurnRecovery,\n getSessionGoal,\n armXaiCapacityWait,\n reconcileXaiCapacityWait,\n listCodexAccountStatuses,\n quarantineCodexCredentialForLease,\n recordUsageEvent,\n getActiveSessionHistoryItemsPaged,\n settleCodexCredentialLeaseLoss,\n settleCodexCredentialFailover,\n readLease,\n SandboxLeaseSupersededError,\n isSessionEventPersistenceError,\n type CodexLeaseAccountStatus,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport { maxTurnsExceededRunState } from \"@opengeni/runtime\";\nimport { CancelledFailure } from \"@temporalio/activity\";\nimport {\n authoritativeCodexCapacityResetAt,\n classifyCodexPin,\n selectCodexCredentialLeaseForTurn,\n type CodexRotationStrategy,\n} from \"../codex-rotation\";\nimport type { Settings } from \"@opengeni/config\";\nimport {\n classifyCodexEncryptedArtifactRejection,\n classifyCodexUsageLimitError,\n isCodexTransportError,\n type CodexUsageHeaderSnapshot,\n} from \"@opengeni/codex\";\nimport { TurnAttemptFencedError } from \"../turn-attempt-fenced\";\nimport { deliverFailedChildTurnToParent } from \"../parent-wake\";\nimport type {\n TurnActivityServices as ActivityServices,\n RunAgentTurnInput,\n RunAgentTurnResult,\n} from \"../types\";\nimport { CodexCredentialLeaseLostError, createTurnCredentialLeases } from \"./credential-leases\";\nimport { createTurnHistorySink } from \"./history-sink\";\n\nimport { BudgetExhaustedError } from \"./admission\";\nimport {\n providerRecoveryExhaustedFailure,\n postClaimDatabaseRecoveryFailure,\n providerRecoveryResult,\n providerRetryAfterMs,\n escapedMcpTimeoutRecoveryFailure,\n preClaimAdmissionFailure,\n isWorkerShutdownCancellation,\n sandboxLifecycleTransitionDiagnostic,\n sandboxRouteTransitionCode,\n safeErrorDiagnostic,\n classifyXaiCredentialFailure,\n agentRunFailurePayload,\n codexCredentialCooldownUntil,\n classifyCodexCredentialFailure,\n codexUsageLimitFailurePayload,\n} from \"./errors\";\nimport { selectRejectedProviderArtifactHistoryIds } from \"./history\";\nimport { waitForTurnFinalizerStep, turnFinalizerCancellationSignal } from \"./quiescence\";\nimport {\n SandboxDeadlineRotationError,\n turnOperationCancellationFailure,\n sandboxDeadlineRotationRecoveryDelayMs,\n} from \"./sandbox-provision\";\nimport type {\n AttemptIdentityState,\n BillingState,\n EventingState,\n ProviderTurnState,\n TurnControlState,\n} from \"./turn-context\";\nimport type { CodexCredentialPolicySnapshotV1 } from \"@opengeni/contracts\";\nimport { armAndReconcileCodexCapacityWait } from \"../codex-capacity\";\n\nexport type TurnFailureDeps = {\n error: unknown;\n input: RunAgentTurnInput;\n settings: Settings;\n db: ActivityServices[\"db\"];\n bus: ActivityServices[\"bus\"];\n observability: ActivityServices[\"observability\"];\n wakeSessionWorkflow: ActivityServices[\"wakeSessionWorkflow\"];\n cancellationSignal: AbortSignal | undefined;\n sandboxRotationController: AbortController;\n noteCancellationRequested: () => void;\n codexWorkspaceKey: string;\n control: TurnControlState;\n attempt: AttemptIdentityState;\n billingState: BillingState;\n eventing: EventingState;\n providerTurn: ProviderTurnState;\n leases: ReturnType<typeof createTurnCredentialLeases>;\n historySink: ReturnType<typeof createTurnHistorySink>;\n claimedResult: (\n result: Omit<\n Extract<RunAgentTurnResult, { status: Exclude<RunAgentTurnResult[\"status\"], \"unclaimed\"> }>,\n \"turnId\" | \"attemptId\"\n >,\n ) => RunAgentTurnResult;\n flushRuntimeBatcher: () => Promise<void>;\n acknowledgeLostAttemptOwnership: () => void;\n acknowledgeRecoveryQuiescence: () => void;\n};\n\nexport type CodexDefinitiveFailureDisposition = \"failover\" | \"wait\" | \"terminal\";\n\ntype CodexCapacityWaitFailurePayload = {\n error: string;\n code: string;\n detail?: string;\n retryable: false;\n};\n\n/**\n * Pure policy for a definitive serving-credential refusal. A policy-constrained\n * account and an all-unavailable pool wait for the same selected capacity to\n * recover; only a truly empty/non-allocatable pool makes an auth/forbidden\n * failure terminal. A different eligible account under rotation-on policy may\n * recover the same durable turn immediately.\n */\nexport function codexDefinitiveFailureDisposition(input: {\n failureKind: \"auth\" | \"forbidden\" | \"rate_limit\" | \"quota\";\n rotationEnabled: boolean;\n pinDisposition: \"manual\" | \"sharded\" | \"clearStale\" | \"unpinned\";\n decisionKind: \"active\" | \"allCapped\" | \"none\";\n decisionCredentialId: string | null;\n servingCredentialId: string;\n}): CodexDefinitiveFailureDisposition {\n const alternateAvailable =\n input.rotationEnabled &&\n input.pinDisposition !== \"manual\" &&\n input.decisionKind === \"active\" &&\n input.decisionCredentialId !== null &&\n input.decisionCredentialId !== input.servingCredentialId;\n if (alternateAvailable) return \"failover\";\n if (\n input.failureKind === \"quota\" ||\n input.failureKind === \"rate_limit\" ||\n input.decisionKind === \"allCapped\" ||\n !input.rotationEnabled ||\n input.pinDisposition === \"manual\"\n ) {\n return \"wait\";\n }\n return \"terminal\";\n}\n\n/**\n * Bound one turn to the alternate credentials that policy actually permits.\n * The effective account list is already workspace/organization scoped;\n * allocator-disabled rows must not enlarge the retry budget. The database\n * requires a positive bound even though one-account paths never fail over.\n */\nexport function codexCredentialFailoverLimit(\n accounts: ReadonlyArray<{ id: string; allocatorEnabled: boolean }>,\n servingCredentialId: string,\n): number {\n const allocatableAccounts = accounts.filter((account) => account.allocatorEnabled).length;\n const servingIsAllocatable = accounts.some(\n (account) => account.id === servingCredentialId && account.allocatorEnabled,\n );\n return Math.max(1, allocatableAccounts - (servingIsAllocatable ? 1 : 0));\n}\n\n/** Build the durable waiter payload without collapsing quota refusals into 403. */\nexport function codexCapacityWaitFailurePayload(input: {\n failureKind: \"auth\" | \"forbidden\" | \"rate_limit\" | \"quota\";\n usageLimit: { resetsInSeconds: number | null } | null;\n cooldownSeconds: number | null;\n detail: string;\n allAccounts: boolean;\n}): CodexCapacityWaitFailurePayload {\n if (input.failureKind === \"quota\") {\n return codexUsageLimitFailurePayload(\n input.usageLimit ?? { resetsInSeconds: input.cooldownSeconds },\n input.detail,\n input.allAccounts ? { allAccounts: true } : undefined,\n );\n }\n if (input.failureKind === \"rate_limit\") {\n return {\n error: \"The serving Codex subscription is temporarily rate limited.\",\n code: \"codex_account_rate_limited\",\n detail: input.detail,\n retryable: false,\n };\n }\n if (input.failureKind === \"auth\") {\n return {\n error: \"The serving Codex account requires reconnection.\",\n code: \"codex_relogin_required\",\n detail: \"the same accepted turn is waiting for the selected account to recover\",\n retryable: false,\n };\n }\n return {\n error: \"The serving Codex account is not authorized for this request.\",\n code: \"codex_account_forbidden\",\n detail: \"the same accepted turn is waiting for the selected account to recover\",\n retryable: false,\n };\n}\n\nfunction codexLeaseAccountsForSelection(\n accounts: Awaited<ReturnType<typeof listCodexAccountStatuses>>,\n): CodexLeaseAccountStatus[] {\n return accounts.map((account) => ({\n ...account,\n activeLeaseCount: 0,\n selectionCount: 0,\n lastSelectedAt: null,\n }));\n}\n\nfunction acceptedCodexPolicySnapshot(\n providerTurn: ProviderTurnState,\n): CodexCredentialPolicySnapshotV1 {\n if (!providerTurn.codexPolicySnapshot) {\n throw new Error(\"Codex accepted policy snapshot is missing after durable lease acquisition\");\n }\n return providerTurn.codexPolicySnapshot;\n}\n\nexport async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgentTurnResult> {\n const {\n error,\n input,\n settings,\n db,\n bus,\n observability,\n wakeSessionWorkflow,\n cancellationSignal,\n sandboxRotationController,\n noteCancellationRequested,\n codexWorkspaceKey,\n control,\n attempt,\n billingState,\n eventing,\n providerTurn,\n leases,\n historySink,\n claimedResult,\n flushRuntimeBatcher,\n acknowledgeLostAttemptOwnership,\n acknowledgeRecoveryQuiescence,\n } = deps;\n // Graceful worker shutdown (deploy / rollout restart): checkpoint the\n // same current inference for a new fenced attempt instead of failing the\n // session. Conversation truth is already persisted per model response;\n // the final reconcile bounds loss to the one in-flight model step.\n //\n // The branch deliberately does NOT require turn.started to have been\n // published: a shutdown landing during setup (claim/billing, before the\n // turn visibly started) must also recover, not fail the session. In that\n // early case nothing ran, so the new attempt uses the original trigger.\n // The turn id falls\n // back to the workflow-claimed turn when the local lookup had not\n // finished yet.\n const recoveryTurnId = attempt.turnId;\n // A true epoch supersession and a provider lifecycle transition are both\n // recoverable control-plane states, never session failures. A rotation\n // persists an exact group/epoch wait marker so the workflow parks before\n // another turn-worker dispatch; shorter non-rotation transitions retain\n // their existing paced retry.\n const lifecycleTransition = sandboxLifecycleTransitionDiagnostic(error);\n const leaseControlError =\n error instanceof SandboxLeaseSupersededError ? error : lifecycleTransition;\n if (leaseControlError && recoveryTurnId) {\n try {\n const fencedLease = await readLease(\n db,\n input.workspaceId,\n leaseControlError.sandboxGroupId,\n ).catch(() => null);\n const rotationPending =\n fencedLease?.rotationRequestedAt != null ||\n lifecycleTransition?.reason === \"rotation_in_progress\";\n const transitionPending = lifecycleTransition !== null || rotationPending;\n const deadlineRotationPending =\n rotationPending && fencedLease?.rotationReason === \"provider_deadline\";\n const sandboxLifecycleWait = rotationPending\n ? {\n version: 1 as const,\n sandboxGroupId: leaseControlError.sandboxGroupId,\n leaseEpoch: fencedLease?.leaseEpoch ?? leaseControlError.leaseEpoch,\n reason: \"rotation_in_progress\" as const,\n }\n : undefined;\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: attempt.triggerEventId!,\n attemptId: input.attemptId,\n reason: deadlineRotationPending\n ? \"sandbox_deadline_rotation\"\n : lifecycleTransition !== null\n ? \"sandbox_lifecycle_transition\"\n : \"sandbox_lease_superseded\",\n ...(transitionPending\n ? {\n detail: {\n sandboxGroupId: leaseControlError.sandboxGroupId,\n leaseEpoch: leaseControlError.leaseEpoch,\n ...(rotationPending\n ? {\n rotationReason: fencedLease?.rotationReason ?? \"operator\",\n }\n : {}),\n ...(lifecycleTransition ? { transitionReason: lifecycleTransition.reason } : {}),\n },\n }\n : {}),\n ...(sandboxLifecycleWait ? { sandboxLifecycleWait } : {}),\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n return claimedResult({\n status: \"recovering\",\n ...(transitionPending && !sandboxLifecycleWait\n ? {\n continueDelayMs: sandboxDeadlineRotationRecoveryDelayMs(settings),\n }\n : {}),\n });\n } catch (recoveryError) {\n console.error(\"sandbox lifecycle recovery failed\", safeErrorDiagnostic(recoveryError));\n throw recoveryError;\n }\n }\n // A managed-home session can start directly on a Connected Machine without\n // creating or leasing its cloud home. If sandbox_attach/sandbox_swap then\n // clears the durable pointer to home, the commit is valid but this exact\n // attempt cannot serve a later home operation. Preserve the completed attach\n // and every preceding model/tool receipt, close only the unresolved suffix,\n // and continue the SAME logical turn in a fresh attempt. That next attempt\n // starts from the now-null pointer and establishes home normally.\n const routeTransitionCode = sandboxRouteTransitionCode(error);\n if (routeTransitionCode && recoveryTurnId && eventing.publish && eventing.turnStartedPublished) {\n try {\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth({ requireDurable: true });\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: attempt.triggerEventId!,\n attemptId: input.attemptId,\n reason: \"sandbox_route_transition\",\n detail: {\n code: routeTransitionCode,\n effectiveBoundary: \"next_attempt\",\n },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n if (recovery.action !== \"recovering\") {\n throw new Error(\"Home sandbox route transition could not recover the current turn\");\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n control.activityError = error;\n return claimedResult({ status: \"recovering\" });\n } catch (recoveryError) {\n console.error(\"sandbox route-transition recovery failed\", safeErrorDiagnostic(recoveryError));\n throw recoveryError;\n }\n }\n if (\n sandboxRotationController.signal.aborted &&\n sandboxRotationController.signal.reason instanceof SandboxDeadlineRotationError &&\n !cancellationSignal?.aborted &&\n recoveryTurnId\n ) {\n try {\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth({ requireDurable: true });\n const rotation = sandboxRotationController.signal.reason;\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: attempt.triggerEventId!,\n attemptId: input.attemptId,\n reason: \"sandbox_deadline_rotation\",\n detail: {\n sandboxGroupId: rotation.sandboxGroupId,\n leaseEpoch: rotation.leaseEpoch,\n },\n sandboxLifecycleWait: {\n version: 1,\n sandboxGroupId: rotation.sandboxGroupId,\n leaseEpoch: rotation.leaseEpoch,\n reason: \"rotation_in_progress\",\n },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n } catch (recoveryError) {\n console.error(\n \"sandbox deadline rotation recovery failed\",\n safeErrorDiagnostic(recoveryError),\n );\n throw recoveryError;\n }\n }\n const cancellationFailure = turnOperationCancellationFailure(error);\n if (cancellationFailure && isWorkerShutdownCancellation(cancellationFailure) && recoveryTurnId) {\n try {\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth();\n // An approval-decision rerun always replays its original trigger. The\n // decision is applied through the exact durable open-suffix receipt and\n // its paired history, so swapping the trigger for a resume notice could\n // drop the user's decision. Re-applying an already-consumed approval\n // re-enters at most the single approved step. Every approval-gated MCP\n // action crosses the durable execution-admission fence before provider\n // invocation, so a consumed step resumes as already-executed or\n // outcome-unknown rather than calling MCP again.\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: attempt.triggerEventId!,\n attemptId: input.attemptId,\n reason: \"worker_shutdown\",\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n } catch (recoveryError) {\n // The database transition is atomic. If it could not commit, surface\n // the failure so Temporal can retry on a healthy worker; never mutate\n // the turn through a second cancellation path.\n console.error(\n \"worker-shutdown recovery checkpoint failed\",\n safeErrorDiagnostic(recoveryError),\n );\n throw recoveryError;\n }\n }\n if (error instanceof TurnAttemptFencedError) {\n control.activityStatus = \"cancelled\";\n control.activityError = error;\n control.acknowledgeQuiescence = true;\n noteCancellationRequested();\n await waitForTurnFinalizerStep(\n flushRuntimeBatcher(),\n turnFinalizerCancellationSignal(cancellationSignal, control.activityStatus),\n );\n // Ownership already moved to a newer attempt or an authoritative\n // control transaction. Surface the exact transport cancellation rather\n // than a normal result. Temporal terminalization remains diagnostic\n // only; replacement admission waits for the activity-owned durable\n // quiescence receipt written from the hard tool fence below.\n control.turnMetricOutcome = \"cancelled\";\n throw new CancelledFailure(\"TURN_ATTEMPT_FENCED\", [], error);\n }\n if (cancellationFailure) {\n control.activityStatus = \"cancelled\";\n control.activityError = error;\n control.acknowledgeQuiescence = true;\n noteCancellationRequested();\n await waitForTurnFinalizerStep(\n flushRuntimeBatcher(),\n turnFinalizerCancellationSignal(cancellationSignal, control.activityStatus),\n );\n // The workflow owns cancellation settlement: Pause/Steer controls use\n // settleSessionControl, and heartbeat timeouts use worker-death\n // recovery. A dying activity must never append a\n // competing cancellation or mutate the turn/session on its own.\n control.turnMetricOutcome = \"cancelled\";\n throw cancellationFailure;\n }\n // The SDK's per-segment turn cap is a pacing valve, not a failure: end\n // the turn gracefully and idle the session so an active goal continues\n // via a synthesized continuation turn (or a user message resumes work).\n // The run state captured at the cap keeps full conversation context for\n // that resumption.\n const maxTurns = maxTurnsExceededRunState(error);\n if (maxTurns && eventing.publish && attempt.turnId && eventing.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 historySink.reconcileConversationTruth();\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: { output: \"\", segmentLimit: \"max_turns\" },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n control.turnMetricOutcome = \"completed\";\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"agent_run.completed\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"session_turn\",\n sourceResourceId: attempt.turnId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n turnAttemptId: input.attemptId,\n idempotencyKey: `usage:agent_run.completed:${attempt.turnId}`,\n });\n control.activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n const settleLostCodexAttempt = async (\n lostTurnId: string,\n holderId: string,\n generation: number,\n historyCheckpointDurable = false,\n ): Promise<RunAgentTurnResult> => {\n let checkpointDurable = historyCheckpointDurable;\n try {\n if (!historyCheckpointDurable) {\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth({ requireDurable: true });\n }\n checkpointDurable = true;\n } catch {\n observability.warn(\"Codex lease-loss checkpoint failed; refusing automatic turn replay\", {\n errorClass: \"CodexCheckpointOperationError\",\n errorCode: \"codex_lease_loss_checkpoint_failed\",\n origin: \"worker\",\n });\n }\n\n const settlement = await settleCodexCredentialLeaseLoss(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: lostTurnId,\n attemptId: input.attemptId,\n holderId,\n generation,\n expectedRedispatches: attempt.redispatchesAtDispatch,\n checkpointDurable,\n recoveryPayload: {\n triggerEventId: attempt.triggerEventId!,\n reason: \"codex_lease_lost\",\n credentialId: providerTurn.effectiveCodexCredentialId,\n },\n failedPayload: {\n error:\n \"The Codex credential lease was lost and the latest conversation checkpoint could not be persisted. Automatic replay was refused.\",\n code: \"codex_lease_checkpoint_failed\",\n retryable: false,\n },\n });\n leases.codex.held = false;\n observability.incrementCounter({\n name: \"opengeni_codex_lease_loss_settlements_total\",\n help: \"Fenced Codex lease-loss settlements by outcome.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n outcome: settlement.action,\n },\n });\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, settlement.events);\n control.activityError = error;\n if (settlement.action === \"failed\") {\n control.activityStatus = \"failed\";\n control.turnMetricOutcome = \"failed\";\n await deliverFailedChildTurnToParent(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n lostTurnId,\n );\n return claimedResult({ status: \"failed\" });\n }\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n };\n\n // A missing/expired/superseded lease is an execution-ownership failure,\n // not a provider failure. Settle it before credential quarantine or the\n // generic terminal path: the DB transaction marks a still-current turn\n // recoverable, but a successor attempt or worker recovery makes this activity\n // stale and unable to clobber the shared turn/session.\n if (\n (leases.codex.lost || error instanceof CodexCredentialLeaseLostError) &&\n billingState.isCodexTurn &&\n eventing.publish &&\n attempt.turnId &&\n eventing.turnStartedPublished &&\n leases.codex.holderId &&\n leases.codex.generation !== null\n ) {\n return await settleLostCodexAttempt(\n attempt.turnId,\n leases.codex.holderId,\n leases.codex.generation,\n );\n }\n if (\n leases.xai.lost &&\n billingState.isXaiTurn &&\n eventing.publish &&\n attempt.turnId &&\n eventing.turnStartedPublished\n ) {\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth({ requireDurable: true });\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n triggerEventId: attempt.triggerEventId!,\n attemptId: input.attemptId,\n reason: \"xai_lease_lost\",\n detail: { provider: \"supergrok-subscription\" },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n }\n // Definitive Codex credential/account refusals are the only provider\n // errors that may walk the pool. This is an explicit checkpoint + SAME\n // turn recovery, never an SDK/Temporal blind retry. A network break,\n // malformed/partial 200 stream, invalid content, prompt 4xx, or provider\n // 5xx does not classify here and therefore cannot consume another\n // subscription or duplicate a side effect.\n const usageLimit = isCodexTransportError(error) ? classifyCodexUsageLimitError(error) : null;\n const codexCredentialFailure =\n billingState.isCodexTurn && providerTurn.effectiveCodexCredentialId\n ? classifyCodexCredentialFailure(error)\n : null;\n if (\n codexCredentialFailure &&\n providerTurn.effectiveCodexCredentialId &&\n eventing.publish &&\n attempt.turnId &&\n eventing.turnStartedPublished\n ) {\n observability.incrementCounter({\n name: \"opengeni_codex_credential_failures_total\",\n help: \"Definitive Codex credential failures classified for safe failover.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n kind: codexCredentialFailure.kind,\n outcome: \"classified\",\n },\n });\n const failoverStartedAt = performance.now();\n let checkpointDurable = false;\n try {\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth({ requireDurable: true });\n checkpointDurable = true;\n } catch {\n observability.incrementCounter({\n name: \"opengeni_codex_failover_checkpoints_total\",\n help: \"Durable Codex failover checkpoint attempts by outcome.\",\n labels: { workspace_key: codexWorkspaceKey, outcome: \"failed\" },\n });\n observability.warn(\"Codex failover checkpoint failed; refusing automatic replay\", {\n errorClass: \"CodexCheckpointOperationError\",\n errorCode: \"codex_failover_checkpoint_failed\",\n origin: \"worker\",\n });\n }\n\n if (checkpointDurable) {\n observability.incrementCounter({\n name: \"opengeni_codex_failover_checkpoints_total\",\n help: \"Durable Codex failover checkpoint attempts by outcome.\",\n labels: { workspace_key: codexWorkspaceKey, outcome: \"completed\" },\n });\n const now = new Date();\n const before = await listCodexAccountStatuses(db, input.workspaceId).catch(() => []);\n const servingCached = before.find(\n (account) => account.id === providerTurn.effectiveCodexCredentialId,\n );\n const usageSnapshot = providerTurn.latestCodexUsage as CodexUsageHeaderSnapshot | null;\n const serving = servingCached\n ? {\n ...servingCached,\n ...(usageSnapshot\n ? {\n primaryUsedPercent: usageSnapshot.primaryUsedPercent,\n primaryResetAt: usageSnapshot.primaryResetAt,\n secondaryUsedPercent: usageSnapshot.secondaryUsedPercent,\n secondaryResetAt: usageSnapshot.secondaryResetAt,\n }\n : {}),\n }\n : null;\n const cooldownUntil = codexCredentialCooldownUntil(codexCredentialFailure, serving, now);\n const quarantineResult =\n leases.codex.holderId &&\n leases.codex.generation !== null &&\n providerTurn.effectiveCodexCredentialVersion !== null\n ? await quarantineCodexCredentialForLease(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n dispatchId: attempt.dispatchId,\n expectedRedispatches: attempt.redispatchesAtDispatch,\n credentialId: providerTurn.effectiveCodexCredentialId,\n credentialVersion: providerTurn.effectiveCodexCredentialVersion,\n holderId: leases.codex.holderId,\n generation: leases.codex.generation,\n maxFailovers: providerTurn.codexCredentialFailoverLimit,\n quarantine:\n codexCredentialFailure.kind === \"auth\"\n ? {\n kind: \"status\",\n status: \"needs_relogin\",\n lastError: \"model request remained unauthorized after refresh\",\n }\n : codexCredentialFailure.kind === \"forbidden\"\n ? {\n kind: \"status\",\n status: \"error\",\n lastError: \"model request was forbidden for this credential\",\n }\n : {\n kind: \"cooldown\",\n until: cooldownUntil!,\n cooldownKind: codexCredentialFailure.kind,\n },\n })\n : null;\n if (\n quarantineResult?.action === \"credential_changed\" &&\n leases.codex.holderId &&\n leases.codex.generation !== null\n ) {\n const recovery = await settleCodexCredentialLeaseLoss(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n attemptId: input.attemptId,\n holderId: leases.codex.holderId,\n generation: leases.codex.generation,\n expectedRedispatches: attempt.redispatchesAtDispatch,\n checkpointDurable: true,\n recoveryPayload: {\n triggerEventId: attempt.triggerEventId!,\n reason: \"codex_credential_version_changed\",\n },\n failedPayload: {},\n });\n if (recovery.action === \"recovering\") {\n leases.codex.held = false;\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n recovery.events,\n );\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n }\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n const statePersisted = quarantineResult?.action === \"recorded\";\n if (!statePersisted && leases.codex.holderId && leases.codex.generation !== null) {\n leases.codex.lost = true;\n return await settleLostCodexAttempt(\n attempt.turnId,\n leases.codex.holderId,\n leases.codex.generation,\n true,\n );\n }\n if (\n quarantineResult?.action === \"recorded\" &&\n quarantineResult.exhausted &&\n leases.codex.holderId &&\n leases.codex.generation !== null\n ) {\n const settlement = await settleCodexCredentialFailover(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n attemptId: input.attemptId,\n holderId: leases.codex.holderId,\n generation: leases.codex.generation,\n expectedRedispatches: attempt.redispatchesAtDispatch,\n maxFailovers: quarantineResult.maxFailovers,\n recoveryPayload: {\n triggerEventId: attempt.triggerEventId!,\n reason: \"codex_credential_failover\",\n credentialId: providerTurn.effectiveCodexCredentialId,\n failureKind: codexCredentialFailure.kind,\n },\n failedPayload: {\n error:\n \"Automatic Codex credential failover stopped after every bounded account attempt was consumed. Send a new message after checking account health or capacity.\",\n code: \"codex_credential_failover_exhausted\",\n retryable: false,\n recovery: \"user_message\",\n failoverCount: quarantineResult.failoverCount,\n maxFailovers: quarantineResult.maxFailovers,\n },\n });\n if (settlement.action === \"limit_exceeded\") {\n leases.codex.held = false;\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n settlement.events,\n );\n control.activityError = error;\n control.activityStatus = \"idle\";\n control.turnMetricOutcome = \"failed\";\n await deliverFailedChildTurnToParent(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n attempt.turnId,\n );\n return claimedResult({ status: \"idle\" });\n }\n if (settlement.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n throw new Error(\"Exhausted Codex failover receipt unexpectedly recovered\");\n }\n let accounts: Awaited<ReturnType<typeof listCodexAccountStatuses>>;\n try {\n accounts = await listCodexAccountStatuses(db, input.workspaceId);\n } catch (metadataError) {\n // Current account health/cooldown metadata is still required after\n // quarantine. Operational database failures re-enter the existing\n // exact-attempt recovery lane; no policy choice is made from partial\n // account state.\n const recoveryFailure = postClaimDatabaseRecoveryFailure({\n error: metadataError,\n turnId: attempt.turnId,\n triggerEventId: attempt.triggerEventId!,\n executionGeneration: attempt.executionGeneration,\n });\n if (recoveryFailure) {\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n control.activityError = metadataError;\n throw recoveryFailure;\n }\n throw metadataError;\n }\n const acceptedPolicy = acceptedCodexPolicySnapshot(providerTurn);\n const selected = selectCodexCredentialLeaseForTurn({\n context: {\n accounts: codexLeaseAccountsForSelection(accounts),\n activeCredentialId: acceptedPolicy.activeCredentialId,\n rotationEnabled: acceptedPolicy.rotationEnabled,\n rotationStrategy: acceptedPolicy.rotationStrategy,\n existingCredentialId: null,\n failedCredentialIds: [providerTurn.effectiveCodexCredentialId],\n policyScope: null,\n unavailableDiagnostics: [],\n },\n sessionId: input.sessionId,\n sessionPinnedCredentialId: acceptedPolicy.pinnedCredentialId,\n sessionPinSource: acceptedPolicy.pinSource,\n sessionLastCredentialId: acceptedPolicy.lastCredentialId,\n now,\n });\n const decisionKind =\n selected.decision.kind === \"allocatorDisabled\" ? \"allCapped\" : selected.decision.kind;\n const pinDisposition = classifyCodexPin({\n pinnedCredentialId: acceptedPolicy.pinnedCredentialId,\n pinSource: acceptedPolicy.pinSource,\n strategy: acceptedPolicy.rotationStrategy as CodexRotationStrategy,\n rotationEnabled: acceptedPolicy.rotationEnabled,\n });\n const failureDisposition = codexDefinitiveFailureDisposition({\n failureKind: codexCredentialFailure.kind,\n rotationEnabled: acceptedPolicy.rotationEnabled,\n pinDisposition,\n decisionKind,\n decisionCredentialId: selected.decision.kind === \"active\" ? selected.credentialId : null,\n servingCredentialId: providerTurn.effectiveCodexCredentialId,\n });\n const maxFailovers = providerTurn.codexCredentialFailoverLimit;\n\n if (\n statePersisted &&\n failureDisposition === \"failover\" &&\n leases.codex.holderId &&\n leases.codex.generation !== null\n ) {\n const settlement = await settleCodexCredentialFailover(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n attemptId: input.attemptId,\n holderId: leases.codex.holderId,\n generation: leases.codex.generation,\n expectedRedispatches: attempt.redispatchesAtDispatch,\n maxFailovers,\n recoveryPayload: {\n triggerEventId: attempt.triggerEventId!,\n reason: \"codex_credential_failover\",\n credentialId: providerTurn.effectiveCodexCredentialId,\n failureKind: codexCredentialFailure.kind,\n ...(cooldownUntil ? { cooldownUntil: cooldownUntil.toISOString() } : {}),\n },\n failedPayload: {\n error:\n \"Automatic Codex credential failover stopped after every bounded account attempt was consumed. Send a new message after checking account health or capacity.\",\n code: \"codex_credential_failover_exhausted\",\n retryable: false,\n recovery: \"user_message\",\n failoverCount: quarantineResult.failoverCount,\n maxFailovers: quarantineResult.maxFailovers,\n },\n });\n observability.incrementCounter({\n name: \"opengeni_codex_failover_settlements_total\",\n help: \"Atomic Codex failover settlements by outcome.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n outcome: settlement.action,\n },\n });\n if (settlement.action === \"recovering\") {\n leases.codex.held = false;\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n settlement.events,\n );\n observability.observeHistogram({\n name: \"opengeni_codex_failover_recovery_seconds\",\n help: \"Time from credential refusal to durable same-turn recovery.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n kind: codexCredentialFailure.kind,\n },\n value: Math.max(0, (performance.now() - failoverStartedAt) / 1000),\n });\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n }\n if (settlement.action === \"stale\") {\n // One transaction proves both exact-holder recovery (including a\n // just-expired or reaped lease row) and successor/control-gate\n // rejection. Cross the hard tool fence so a control-gate loss can\n // write its quiescence receipt; a successor-only loss is a no-op.\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n if (settlement.action === \"limit_exceeded\") {\n leases.codex.held = false;\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n settlement.events,\n );\n control.activityError = error;\n control.activityStatus = \"idle\";\n control.turnMetricOutcome = \"failed\";\n await deliverFailedChildTurnToParent(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n attempt.turnId,\n );\n return claimedResult({ status: \"idle\" });\n }\n }\n\n if (\n statePersisted &&\n failureDisposition === \"wait\" &&\n leases.codex.holderId &&\n leases.codex.generation !== null\n ) {\n let goal: Awaited<ReturnType<typeof getSessionGoal>>;\n try {\n goal = await getSessionGoal(db, input.workspaceId, input.sessionId);\n } catch (metadataError) {\n const recoveryFailure = postClaimDatabaseRecoveryFailure({\n error: metadataError,\n turnId: attempt.turnId,\n triggerEventId: attempt.triggerEventId!,\n executionGeneration: attempt.executionGeneration,\n });\n if (recoveryFailure) {\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n control.activityError = metadataError;\n throw recoveryFailure;\n }\n throw metadataError;\n }\n const activeGoal = goal?.status === \"active\" ? goal : null;\n const exactProviderReset =\n codexCredentialFailure.cooldownSeconds !== null &&\n Number.isFinite(codexCredentialFailure.cooldownSeconds) &&\n codexCredentialFailure.cooldownSeconds > 0;\n const policyCredentialId =\n pinDisposition === \"manual\" && acceptedPolicy.pinnedCredentialId\n ? acceptedPolicy.pinnedCredentialId\n : !acceptedPolicy.rotationEnabled\n ? acceptedPolicy.activeCredentialId\n : null;\n const capacityAccounts = policyCredentialId\n ? accounts.filter((account) => account.id === policyCredentialId)\n : accounts;\n const authoritativeResetAt = exactProviderReset\n ? (authoritativeCodexCapacityResetAt(capacityAccounts, now) ?? cooldownUntil)\n : null;\n const allAccounts =\n acceptedPolicy.rotationEnabled &&\n pinDisposition !== \"manual\" &&\n decisionKind === \"allCapped\";\n const failurePayload = codexCapacityWaitFailurePayload({\n failureKind: codexCredentialFailure.kind,\n usageLimit,\n cooldownSeconds: codexCredentialFailure.cooldownSeconds,\n detail:\n codexCredentialFailure.kind === \"quota\"\n ? error instanceof Error\n ? error.message\n : String(error)\n : \"the same accepted turn is waiting for eligible credential capacity\",\n allAccounts,\n });\n const evaluated = await armAndReconcileCodexCapacityWait(\n { db, bus },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n goalId: activeGoal?.id ?? null,\n goalVersion: activeGoal?.version ?? null,\n earliestResetAt: authoritativeResetAt,\n resetKind: authoritativeResetAt\n ? \"authoritative\"\n : codexCredentialFailure.kind === \"auth\" ||\n codexCredentialFailure.kind === \"forbidden\"\n ? \"mutation_only\"\n : \"bounded_refresh\",\n failurePayload,\n leaseFence: {\n holderId: leases.codex.holderId,\n generation: leases.codex.generation,\n },\n expectedRedispatches: attempt.redispatchesAtDispatch,\n },\n { onArmed: () => (leases.codex.held = false) },\n );\n control.activityError = error;\n if (evaluated.action === \"resumed\") {\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n }\n if (evaluated.action === \"waiting\") {\n control.activityError = error;\n control.activityStatus = \"waiting_capacity\";\n control.turnMetricOutcome = \"recovering\";\n return claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n waiterId: evaluated.waiter.id,\n generation: evaluated.waiter.generation,\n nextCheckAt: evaluated.waiter.nextCheckAt.toISOString(),\n wakeRevision: evaluated.waiter.wakeRevision,\n },\n });\n }\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n }\n }\n const xaiCredentialFailure =\n billingState.isXaiTurn && providerTurn.effectiveXaiCredentialId\n ? classifyXaiCredentialFailure(error)\n : null;\n if (\n xaiCredentialFailure &&\n providerTurn.effectiveXaiCredentialId &&\n providerTurn.xaiAuthoritySnapshot &&\n leases.xai.subjectId &&\n leases.xai.holderId &&\n leases.xai.generation !== null &&\n eventing.publish &&\n attempt.turnId &&\n eventing.turnStartedPublished\n ) {\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth({ requireDurable: true });\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId).catch(() => null);\n const activeGoal = goal?.status === \"active\" ? goal : null;\n const now = new Date();\n const cooldownUntil =\n xaiCredentialFailure.kind === \"rate_limit\"\n ? new Date(now.getTime() + Math.max(1, xaiCredentialFailure.cooldownMs ?? 60_000))\n : null;\n const failurePayload = {\n error:\n xaiCredentialFailure.kind === \"auth\"\n ? \"The serving SuperGrok account requires reconnection\"\n : xaiCredentialFailure.kind === \"forbidden\"\n ? \"The serving SuperGrok account is not authorized for this request\"\n : \"The serving SuperGrok account is temporarily rate limited\",\n code:\n xaiCredentialFailure.kind === \"auth\"\n ? \"xai_relogin_required\"\n : xaiCredentialFailure.kind === \"forbidden\"\n ? \"xai_account_forbidden\"\n : \"xai_account_rate_limited\",\n detail: \"the same accepted turn is waiting for another eligible account\",\n };\n const armed = await armXaiCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: leases.xai.subjectId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n authoritySnapshot: providerTurn.xaiAuthoritySnapshot,\n goalId: activeGoal?.id ?? null,\n goalVersion: activeGoal?.version ?? null,\n earliestResetAt: cooldownUntil,\n failurePayload,\n leaseFence: {\n holderId: leases.xai.holderId,\n generation: leases.xai.generation,\n },\n credentialQuarantine:\n xaiCredentialFailure.kind === \"auth\"\n ? {\n kind: \"status\",\n status: \"needs_relogin\",\n lastError: \"model request remained unauthorized after refresh\",\n }\n : xaiCredentialFailure.kind === \"forbidden\"\n ? {\n kind: \"status\",\n status: \"error\",\n lastError: \"model request was forbidden for this credential\",\n }\n : { kind: \"cooldown\", until: cooldownUntil! },\n now,\n });\n if (armed.action === \"waiting\") {\n leases.xai.held = false;\n providerTurn.xaiCredentialQuarantined = true;\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, armed.events);\n const evaluated = await reconcileXaiCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n waiterId: armed.waiter.id,\n generation: armed.waiter.generation,\n now,\n });\n if (evaluated.events.length > 0) {\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n evaluated.events,\n );\n }\n control.activityError = error;\n if (evaluated.action === \"resumed\") {\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n }\n if (evaluated.action === \"waiting\") {\n control.activityStatus = \"waiting_capacity\";\n control.turnMetricOutcome = \"recovering\";\n return claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n provider: \"xai\",\n waiterId: evaluated.waiter.id,\n generation: evaluated.waiter.generation,\n nextCheckAt: evaluated.waiter.nextCheckAt.toISOString(),\n wakeRevision: evaluated.waiter.wakeRevision,\n },\n });\n }\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n triggerEventId: attempt.triggerEventId!,\n attemptId: input.attemptId,\n reason: \"xai_credential_recheck\",\n detail: failurePayload,\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n control.activityError = error;\n return claimedResult({ status: \"recovering\" });\n }\n // The leased credential path above normally quarantines quota state and\n // either recovers the same turn or arms a durable capacity wait. This narrow\n // fallback covers failures before a credential lease existed, or a failed\n // durable checkpoint where replay would be unsafe. Keep the session usable,\n // but never synthesize another turn or walk an unfenced legacy pointer.\n if (usageLimit && eventing.publish && attempt.turnId && eventing.turnStartedPublished) {\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth();\n const failurePayload = codexUsageLimitFailurePayload(\n usageLimit,\n error instanceof Error ? error.message : String(error),\n );\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n ...failurePayload,\n recovery: \"user_message\",\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n control.turnMetricOutcome = \"failed\";\n control.activityStatus = \"idle\";\n control.activityError = error;\n return claimedResult({ status: \"idle\" });\n }\n // Budget/limit exhaustion between model calls is account state, not an\n // agent failure: idle the session for goal-bearing and goal-less runs\n // alike (a failed session would reject the user's next message after a\n // top-up). An active goal pauses visibly with reason \"limits\" at the\n // next continuation evaluation, without consuming continuation budget.\n if (\n error instanceof BudgetExhaustedError &&\n eventing.publish &&\n attempt.turnId &&\n eventing.turnStartedPublished\n ) {\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth();\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: {\n output: \"\",\n segmentLimit: \"budget_exhausted\",\n detail: error.message,\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n control.turnMetricOutcome = \"completed\";\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"agent_run.completed\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"session_turn\",\n sourceResourceId: attempt.turnId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n turnAttemptId: input.attemptId,\n idempotencyKey: `usage:agent_run.completed:${attempt.turnId}`,\n });\n control.activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n // The Codex backend can reject an opaque reasoning artifact that it\n // minted on the immediately preceding successful request, even when the\n // credential-row UUID is unchanged. HTTP 400 + the exact provider\n // semantic proves this request never entered inference. Atomically mark\n // the active opaque artifacts rejected and recover the SAME logical turn\n // from durable history; messages, tool calls/results, readable reasoning,\n // and the original audit rows remain intact. Opaque remote compaction has\n // no portable plaintext representation. If no artifact can be invalidated,\n // fall through to the terminal path rather than resend an equivalent\n // request forever.\n const encryptedArtifactRejection =\n billingState.isCodexTurn && providerTurn.effectiveCodexCredentialId\n ? classifyCodexEncryptedArtifactRejection(error)\n : null;\n if (\n encryptedArtifactRejection &&\n providerTurn.effectiveCodexCredentialId &&\n eventing.publish &&\n attempt.turnId &&\n eventing.turnStartedPublished\n ) {\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth({ requireDurable: true });\n const activeHistory = await getActiveSessionHistoryItemsPaged(\n db,\n input.workspaceId,\n input.sessionId,\n );\n const rejectedHistoryItemIds = selectRejectedProviderArtifactHistoryIds(\n activeHistory,\n historySink.providerArtifactCandidates,\n providerTurn.lastCodexRequestOpaqueArtifacts,\n );\n const rejectedRunStateId =\n historySink.providerArtifactCandidates.runStateId &&\n providerTurn.lastCodexRequestOpaqueArtifacts.length > 0\n ? historySink.providerArtifactCandidates.runStateId\n : undefined;\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n triggerEventId: attempt.triggerEventId!,\n attemptId: input.attemptId,\n reason: encryptedArtifactRejection.kind,\n detail: {\n code: encryptedArtifactRejection.kind,\n retryable: true,\n },\n providerArtifactInvalidation: {\n historyItemIds: rejectedHistoryItemIds,\n ...(rejectedRunStateId ? { runStateId: rejectedRunStateId } : {}),\n reason: encryptedArtifactRejection.kind,\n },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n if (recovery.action === \"recovering\") {\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n control.turnMetricOutcome = \"recovering\";\n control.activityStatus = \"recovering\";\n control.activityError = error;\n return claimedResult({ status: \"recovering\" });\n }\n }\n // A retryable provider/MCP failure is transient external backpressure,\n // not a session or goal failure. The in-client retry budget is already\n // exhausted by the time the error reaches here. Checkpoint conversation\n // truth, recover this SAME accepted turn, then let the workflow re-claim\n // it after a pacing delay. This is independent of goal state and never\n // relies on a synthetic continuation prompt.\n let failure = agentRunFailurePayload(error, {\n isCodexTurn: billingState.isCodexTurn,\n }) as ReturnType<typeof agentRunFailurePayload>;\n if (isSessionEventPersistenceError(error)) {\n // Preserve the exact source message in the internal runtime diagnostic;\n // SQLSTATE/catalog facts remain separate classification attributes.\n observability.error(\"session event persistence failed\", {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n attemptId: input.attemptId,\n code: error.details.code,\n sqlState: error.details.sqlState ?? \"unknown\",\n stage: error.details.stage,\n eventTypes: error.details.eventTypes.join(\",\"),\n correlationId: error.details.correlationId,\n attempts: error.details.attempts,\n retryOutcome: error.details.retryOutcome,\n dbSeverity: error.details.database.severity,\n dbSchema: error.details.database.schema,\n dbTable: error.details.database.table,\n dbColumn: error.details.database.column,\n dbDataType: error.details.database.dataType,\n dbConstraint: error.details.database.constraint,\n dbRoutine: error.details.database.routine,\n error: error.message,\n });\n }\n if (failure.retryable && eventing.publish && attempt.turnId && eventing.turnStartedPublished) {\n const nextProviderRecoveryCount = attempt.providerRecoveryCount + 1;\n const recoveryResult = providerRecoveryResult({\n failureCode: failure.code,\n attemptNumber: nextProviderRecoveryCount,\n retryAfterMs: providerRetryAfterMs(error),\n });\n try {\n if (recoveryResult.status === \"recovering\") {\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth({ requireDurable: true });\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n triggerEventId: attempt.triggerEventId!,\n attemptId: input.attemptId,\n reason: failure.code ?? \"provider_unavailable\",\n providerRecoveryCount: nextProviderRecoveryCount,\n detail: {\n ...failure,\n continueDelayMs: recoveryResult.continueDelayMs,\n providerRecoveryCount: nextProviderRecoveryCount,\n },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n control.turnMetricOutcome = \"recovering\";\n control.activityStatus = \"recovering\";\n control.activityError = error;\n return claimedResult(recoveryResult);\n }\n failure = providerRecoveryExhaustedFailure(failure, recoveryResult);\n } catch (recoveryError) {\n const escaped =\n recoveryResult.status === \"recovering\"\n ? escapedMcpTimeoutRecoveryFailure({\n failureCode: failure.code,\n modelRequestStarted: attempt.modelRequestStarted,\n detail: {\n turnId: attempt.turnId,\n triggerEventId: attempt.triggerEventId!,\n executionGeneration: attempt.executionGeneration,\n providerRecoveryCount: nextProviderRecoveryCount,\n continueDelayMs: recoveryResult.continueDelayMs,\n },\n })\n : null;\n if (escaped) {\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n control.activityError = error;\n throw escaped;\n }\n const postClaimRecovery =\n recoveryResult.status === \"recovering\"\n ? postClaimDatabaseRecoveryFailure({\n error: recoveryError,\n turnId: attempt.turnId,\n triggerEventId: attempt.triggerEventId!,\n executionGeneration: attempt.executionGeneration,\n providerRecovery: {\n failureCode: failure.code ?? \"provider_unavailable\",\n providerRecoveryCount: nextProviderRecoveryCount,\n },\n })\n : null;\n if (postClaimRecovery) {\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n control.activityError = error;\n throw postClaimRecovery;\n }\n throw recoveryError;\n }\n }\n if (\n attempt.turnId &&\n attempt.triggerEventId &&\n attempt.executionGeneration > 0 &&\n !eventing.turnStartedPublished &&\n !attempt.modelRequestStarted\n ) {\n const recoveryFailure = postClaimDatabaseRecoveryFailure({\n error,\n turnId: attempt.turnId,\n triggerEventId: attempt.triggerEventId,\n executionGeneration: attempt.executionGeneration,\n });\n if (recoveryFailure) {\n control.activityStatus = \"recovering\";\n control.turnMetricOutcome = \"recovering\";\n control.activityError = error;\n throw recoveryFailure;\n }\n }\n control.activityStatus = \"failed\";\n control.activityError = error;\n if (!attempt.turnId) {\n throw preClaimAdmissionFailure(error);\n }\n if (!eventing.publish || !eventing.turnStartedPublished) {\n throw error;\n }\n // A partial/malformed stream may have emitted assistant/tool items (and\n // external side effects) before its terminal error. Persist every item the\n // SDK state observed before marking the turn failed so a later user revive\n // never replays work from an incomplete history. This does not retry or\n // rotate the ambiguous request.\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth();\n if (\n !(await eventing.settle!({\n events: [\n { type: \"turn.failed\", payload: failure },\n { type: \"session.status.changed\", payload: { status: \"failed\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"failed\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n control.turnMetricOutcome = \"failed\";\n // The common failure path ends here: runAgentTurn marks the session\n // failed and returns \"failed\", and the session workflow then exits\n // WITHOUT calling failSession/markSessionIdle. Wake a spawned worker's\n // parent here too, so a manager learns of a worker that died inside its\n // turn (not just one failed by the workflow's failSession path). Turn\n // settlement already owns the durable outbox payload; this call only\n // delivers that exact turn-scoped row.\n await deliverFailedChildTurnToParent(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n attempt.turnId,\n );\n return claimedResult({ status: \"failed\" });\n}\n","import { getBillingBalance, sumUsageQuantity } from \"@opengeni/db\";\nimport {\n configuredStaticUsageLimits,\n resolveTurnExecutionPolicyV1,\n type Settings,\n} from \"@opengeni/config\";\nimport { selectCodexCredentialId } from \"@opengeni/codex\";\nimport { directPersonalConnectionSubjectId } from \"@opengeni/core\";\nimport type { TurnActivityServices as ActivityServices } from \"../types\";\nimport {\n type SessionEvent,\n type SessionTurn,\n type ToolAuthNeededPayload,\n type TurnExecutionPolicyV1,\n type XaiProviderAccountAuthoritySnapshotV1,\n} from \"@opengeni/contracts\";\nimport { createHash } from \"node:crypto\";\nimport { startOfUtcMonth } from \"./model-usage\";\n\nexport class WorkspaceHumanInputDisabledError extends Error {\n constructor(kind: \"resume\" | \"interruption\") {\n super(`Workspace policy rejects structured human-input ${kind}`);\n this.name = \"WorkspaceHumanInputDisabledError\";\n }\n}\n\nexport function assertWorkspaceHumanInputAllowed(\n enabled: boolean,\n kind: \"resume\" | \"interruption\",\n attempted: boolean,\n): void {\n if (!enabled && attempted) throw new WorkspaceHumanInputDisabledError(kind);\n}\n\n/** Broad personal lookup is allowed only for a direct human/API command. */\nexport function credentialSubjectIdForTurnInitiator(\n turn: Pick<SessionTurn, \"source\" | \"initiator\" | \"initiatorContext\">,\n): string | undefined {\n return directPersonalConnectionSubjectId(turn);\n}\n\nexport function xaiCatalogReadinessAuthority(\n turn: {\n initiatingHumanSubjectId: string | null;\n xaiProviderAccountAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;\n },\n directCredentialSubjectId: string | undefined,\n): {\n subjectId: string;\n authoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;\n} | null {\n const subjectId = turn.initiatingHumanSubjectId ?? directCredentialSubjectId;\n return subjectId\n ? { subjectId, authoritySnapshot: turn.xaiProviderAccountAuthoritySnapshot }\n : null;\n}\n\n/**\n * Direct authenticated-human work is the persisted human source with subject\n * authority and no inherited agent or legacy provenance. Use this complete\n * immutable turn authority instead of inferring causality from a\n * `user.message` event shape or the root initiator alone.\n */\nexport function isDirectHumanTurnInitiation(\n turn: Pick<SessionTurn, \"source\" | \"initiator\" | \"initiatorContext\">,\n): boolean {\n if ((turn.source !== \"user\" && turn.source !== \"api\") || turn.initiator.kind !== \"subject\") {\n return false;\n }\n return ![\"via\", \"viaTruncated\", \"provenanceError\", \"backfill\"].some((key) =>\n Object.prototype.hasOwnProperty.call(turn.initiatorContext, key),\n );\n}\n\n/**\n * A disconnected personal Slack server is prepared best-effort before the model\n * runs. Its initialize/tools-list credential miss is setup state, not evidence\n * that an unrelated turn wants Slack. Keep concrete tool-call failures\n * actionable, but gate setup-time Slack prompts to a human message that names\n * Slack explicitly. Other providers retain the existing generic behavior.\n */\nexport function shouldPublishToolAuthNeededForTurn(\n payload: Pick<ToolAuthNeededPayload, \"providerDomain\" | \"toolName\">,\n trigger: Pick<SessionEvent, \"type\" | \"payload\">,\n turn: Pick<SessionTurn, \"source\" | \"initiator\" | \"initiatorContext\">,\n): boolean {\n if (typeof payload.toolName === \"string\" && payload.toolName.trim().length > 0) {\n return true;\n }\n const providerDomain = payload.providerDomain.trim().toLowerCase();\n const isSlack = providerDomain === \"slack.com\" || providerDomain.endsWith(\".slack.com\");\n if (!isSlack) {\n return true;\n }\n if (!isDirectHumanTurnInitiation(turn) || trigger.type !== \"user.message\") {\n return false;\n }\n const text = (trigger.payload as { text?: unknown }).text;\n return typeof text === \"string\" && /\\bslack\\b/i.test(text);\n}\n\n/**\n * Keep host-owned auth events inert in browsers from before authoritySource\n * existed. Those bundles treat unsupported_auth as unavailable and therefore\n * do not invoke native OAuth; upgraded clients read hostReason and the\n * host-minted authorizationUrl.\n */\nexport function rollingSafeToolAuthNeededPayload(\n payload: ToolAuthNeededPayload,\n): ToolAuthNeededPayload {\n if (payload.authoritySource !== \"host\") {\n return payload;\n }\n return {\n ...payload,\n reason: \"unsupported_auth\",\n hostReason: payload.hostReason ?? payload.reason,\n };\n}\n\nexport function turnExecutionPolicyBillingIdentity(policy: TurnExecutionPolicyV1): {\n externallyBilled: boolean;\n countsTowardTokenCap: boolean;\n codexSubscription: boolean;\n xaiSubscription: boolean;\n} {\n return {\n externallyBilled: policy.billing.metering === \"external\",\n countsTowardTokenCap: policy.billing.upstreamPayer === \"deployment\",\n codexSubscription:\n policy.providerId === \"codex-subscription\" &&\n policy.credentialSource.kind === \"connected_subscription\" &&\n policy.credentialSource.provider === \"codex\",\n xaiSubscription:\n policy.providerId === \"supergrok-subscription\" &&\n policy.credentialSource.kind === \"connected_subscription\" &&\n policy.credentialSource.provider === \"xai\",\n };\n}\n\nexport function legacyTurnExecutionPolicyInput(\n turn: Pick<SessionTurn, \"source\" | \"model\" | \"reasoningEffort\" | \"latencyMode\">,\n): Parameters<typeof resolveTurnExecutionPolicyV1>[1] {\n const explicit = turn.source === \"user\" || turn.source === \"api\";\n return {\n modelId: turn.model,\n requestedModelId: explicit ? turn.model : null,\n modelSource: explicit ? \"explicit\" : \"continuation\",\n reasoningEffort: turn.reasoningEffort,\n reasoningSource: explicit ? \"explicit\" : \"continuation\",\n latencyMode: turn.latencyMode,\n latencyModeSource: explicit ? \"explicit\" : \"continuation\",\n };\n}\n\n/** A retryable provider fault recovers the accepted turn itself. Goal state is\n * irrelevant: autonomous continuation and infrastructure recovery are separate\n * concerns. */\nexport function selectCodexCredentialForTurn(args: {\n sessionPinnedCredentialId: string | null;\n activeCredentialId: string | null;\n connectedIds: Set<string>;\n}): string | null {\n return selectCodexCredentialId(args);\n}\n\nexport function stableHumanInputRequestId(\n sessionId: string,\n turnId: string,\n toolCallId: string,\n): string {\n const hex = createHash(\"sha256\")\n .update(\"opengeni-human-input-v1\\0\")\n .update(sessionId)\n .update(\"\\0\")\n .update(turnId)\n .update(\"\\0\")\n .update(toolCallId)\n .digest(\"hex\")\n .slice(0, 32)\n .split(\"\");\n hex[12] = \"5\";\n hex[16] = [\"8\", \"9\", \"a\", \"b\"][Number.parseInt(hex[16] ?? \"0\", 16) % 4] ?? \"8\";\n const value = hex.join(\"\");\n return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;\n}\n\nexport function stableInteractionInterventionId(\n sessionId: string,\n turnId: string,\n toolCallId: string,\n): string {\n return stableInteractionInterventionUuid(\n \"opengeni-interaction-intervention-v1\",\n sessionId,\n turnId,\n toolCallId,\n );\n}\n\nexport function stableInteractionInterventionOperationId(\n sessionId: string,\n turnId: string,\n toolCallId: string,\n): string {\n return stableInteractionInterventionUuid(\n \"opengeni-interaction-intervention-operation-v1\",\n sessionId,\n turnId,\n toolCallId,\n );\n}\n\nexport function stableInteractionInterventionUuid(\n namespace: string,\n sessionId: string,\n turnId: string,\n toolCallId: string,\n): string {\n const hex = createHash(\"sha256\")\n .update(namespace)\n .update(\"\\0\")\n .update(sessionId)\n .update(\"\\0\")\n .update(turnId)\n .update(\"\\0\")\n .update(toolCallId)\n .digest(\"hex\")\n .slice(0, 32)\n .split(\"\");\n hex[12] = \"5\";\n hex[16] = [\"8\", \"9\", \"a\", \"b\"][Number.parseInt(hex[16] ?? \"0\", 16) % 4] ?? \"8\";\n const value = hex.join(\"\");\n return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;\n}\n\n/**\n * True when this activity attempt was cancelled because its hosting worker is\n * shutting down gracefully (SIGTERM during a deploy), as opposed to a\n * workflow-requested Pause/Steer cancellation or a server-side timeout.\n */\nexport class BudgetExhaustedError extends Error {\n constructor(\n message: string,\n readonly serializedRunState: string | null,\n ) {\n super(message);\n this.name = \"BudgetExhaustedError\";\n }\n}\n\n// Exported for unit testing the external-billing bypass (codex-billing.test.ts); not\n// part of the activity surface. Takes the accepted policy's billing attribution and\n// the optional §7.5 P3 host `entitlements` port (when bound, its `admitRun` REPLACES\n// the local credit read for an OpenGeni-metered turn; unset → local ledger).\nexport async function ensureRunAllowed(\n settings: Settings,\n db: ActivityServices[\"db\"],\n accountId: string,\n workspaceId: string,\n isExternallyBilledTurn: boolean,\n entitlements?: ActivityServices[\"entitlements\"],\n chargesOpenGeniCredits = !isExternallyBilledTurn,\n countsTowardTokenCap = !isExternallyBilledTurn,\n): Promise<void> {\n // Upstream settlement and workspace-facing cost are independent. External\n // metering skips the token cap; free/subscription/workspace cost skips the\n // OpenGeni credit gate. The agent-run COUNT cap below is a volume/fairness\n // quota and is intentionally kept for every funding path.\n //\n // §7.5 P3 — host-entitlements DELEGATION (the worker half of the same seam the\n // API edge exposes). For a non-codex turn, when the host binds `entitlements`, its\n // `admitRun` decision REPLACES the local credit-balance read below: a host that owns\n // its ledger/meter is the funding authority. A deny throws the SAME Error the local\n // read throws, so the mid-stream budget-valve at :727 wraps it in a\n // `BudgetExhaustedError` and pauses identically — the valve never learns whether the\n // deny came from the local ledger or the host meter.\n //\n // This is an admission READ only; it records NO usage (metering stays the sole,\n // idempotency-keyed writer at recordModelUsageAndDebitCredits), so a PULL host meter\n // is consulted without ever double-charging.\n if (\n chargesOpenGeniCredits &&\n entitlements &&\n (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")\n ) {\n const decision = await entitlements.admitRun({\n accountId,\n workspaceId,\n action: \"agent_run:create\",\n quantity: 1,\n });\n if (!decision.allowed) {\n throw new Error(decision.reason || \"insufficient OpenGeni credits\");\n }\n } else if (\n chargesOpenGeniCredits &&\n (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")\n ) {\n const balance = await getBillingBalance(db, accountId);\n if (balance.balanceMicros <= 0) {\n throw new Error(\"insufficient OpenGeni credits\");\n }\n }\n if (settings.usageLimitsMode === \"static\" || settings.usageLimitsMode === \"managed\") {\n const limits = configuredStaticUsageLimits(settings);\n if (limits.maxMonthlyAgentRunsPerWorkspace) {\n const used = await sumUsageQuantity(db, {\n workspaceId,\n eventType: \"agent_run.created\",\n since: startOfUtcMonth(),\n });\n // Agent turns are admitted and recorded before this worker activity starts.\n // Equality means this accepted turn is exactly at the cap; greater-than is\n // the race/backstop case where another admission already exceeded the cap.\n if (used > limits.maxMonthlyAgentRunsPerWorkspace) {\n throw new Error(\n `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`,\n );\n }\n }\n if (countsTowardTokenCap && 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","import {\n applyCreditDebitUpToBalance,\n recordUsageEvent,\n recordModelCallFact,\n type AppendEventInput,\n type CanonicalTurnStartupMilestoneReceipt,\n} from \"@opengeni/db\";\nimport {\n modelResponseServiceTierFromSdkEvent,\n modelTerminalResponseFromSdkEvent,\n normalizeModelCallUsage,\n type ModelResponseUsage,\n type ModelCallUsageInput,\n type ModelCallUsageNormalization,\n} from \"@opengeni/runtime\";\nimport {\n calculateGatewayReportedCostBreakdown,\n calculateGatewayReportedProviderCostMicros,\n calculateModelUsageCostBreakdown,\n configuredModelPricingSchedules,\n resolveModelProvider,\n responseSatisfiesLatencyMode,\n OPENGENI_GATEWAY_PROVIDER_ID,\n WORKSPACE_GATEWAY_PROVIDER_ID,\n type ModelUsageInput,\n type ModelProviderApi,\n type Settings,\n} from \"@opengeni/config\";\nimport { CODEX_PROVIDER_ID } from \"@opengeni/codex\";\nimport type { TurnActivityServices as ActivityServices } from \"../types\";\nimport {\n modelCallAccountContext,\n recordCreditMicros,\n recordModelCacheTokens,\n recordModelInputTokens,\n} from \"../../observability-metrics\";\nimport {\n type LatencyMode,\n type ModelContextContributionSummary,\n type SessionEvent,\n} from \"@opengeni/contracts\";\nimport { safeErrorDiagnostic } from \"./errors\";\n\nexport function modelUsageSourceKey(input: {\n responseId?: string | null | undefined;\n dispatchId: string | null;\n positionalKey: string;\n}): string {\n if (input.responseId) {\n return input.responseId;\n }\n return input.dispatchId ? `${input.dispatchId}:${input.positionalKey}` : input.positionalKey;\n}\n\nexport function providerContextTokens(\n usage:\n | {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n }\n | null\n | undefined,\n): number | null {\n const total = normalizeModelCallUsage(usage).totalTokens;\n return total !== null && total > 0 ? total : null;\n}\n\n/**\n * A provider call has already consumed tokens by the time its usage frame is\n * available. Losing the Codex credential lease at the renewal checkpoint must\n * stop the result from becoming authoritative, but it must not erase accounting\n * truth for the call that already happened. Meter first, then surface the lost\n * lease, then write attempt-owned token/context signals. A replaced attempt can\n * reject those signals without erasing the provider usage already incurred.\n */\nexport async function recordCompletedModelCallBeforeOwnershipFences(input: {\n renewLease: () => Promise<void>;\n recordUsage: () => Promise<void>;\n leaseLost: () => boolean;\n leaseLostMessage: string;\n recordAttemptSignals?: () => Promise<void>;\n}): Promise<void> {\n await input.renewLease();\n await input.recordUsage();\n if (input.leaseLost()) {\n throw new Error(input.leaseLostMessage);\n }\n await input.recordAttemptSignals?.();\n}\n\nexport type TurnEventPublisher = (\n events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>,\n immediate?: boolean,\n) => Promise<{\n events: SessionEvent[];\n accepted: boolean;\n canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[];\n}>;\n\nexport type ModelResponseEventState = {\n responseCount: number;\n contextSignal: { revision: number; totalTokens: number } | null;\n claimedSourceKeys: Set<string>;\n};\n\nexport type CompactionModelUsageEventState = {\n usageCount: number;\n claimedSourceKeys: Set<string>;\n};\n\nexport function createModelResponseEventState(\n claimedSourceKeys: Set<string> = new Set<string>(),\n): ModelResponseEventState {\n return {\n responseCount: 0,\n contextSignal: null,\n claimedSourceKeys,\n };\n}\n\nexport function createCompactionModelUsageEventState(\n claimedSourceKeys: Set<string> = new Set<string>(),\n): CompactionModelUsageEventState {\n return { usageCount: 0, claimedSourceKeys };\n}\n\nexport const createSessionTitleModelUsageEventState = createCompactionModelUsageEventState;\n\nexport function modelResponseContextSignal(\n state: ModelResponseEventState,\n): { revision: number; totalTokens: number } | null {\n return state.contextSignal;\n}\n\nexport function assertModelResponseLatencyMode(input: {\n event: Parameters<typeof modelResponseServiceTierFromSdkEvent>[0];\n requested: LatencyMode;\n model: string;\n /** When set to Codex ChatGPT auth, response `service_tier` is not an honor signal. */\n providerId?: string;\n}): void {\n if (input.requested === \"standard\") {\n return;\n }\n // ChatGPT-auth Codex (subscription): Fast maps to request `service_tier=priority`\n // (see openai/codex ServiceTier::Fast.request_value). The backend may still return\n // `response.service_tier=default`; OpenAI maintainers document that this does not\n // mean Fast was ignored. Native CLI also does not fail closed on that field.\n if (input.providerId === CODEX_PROVIDER_ID) {\n return;\n }\n const serviceTierEvent = modelResponseServiceTierFromSdkEvent(input.event);\n if (\n !serviceTierEvent ||\n (serviceTierEvent.source === \"normalized\" && serviceTierEvent.serviceTier === null)\n ) {\n return;\n }\n if (!responseSatisfiesLatencyMode(input.requested, serviceTierEvent.serviceTier)) {\n throw new Error(\n `Provider did not honor ${input.requested} latency mode for ${input.model}: response service_tier=${serviceTierEvent.serviceTier ?? \"missing\"}`,\n );\n }\n}\n\n/**\n * Process one SDK terminal-response event through the production authority path.\n *\n * The pinned Responses SDK mirrors one provider terminal response as both a\n * normalized `response_done` and a raw `model/response.completed` event. Claim\n * the stable response/source key before lease renewal or any side effect, and\n * use that one positional ordinal for both response identity and same-run\n * context binding. A response without usage still clears attempt-owned token\n * state. When usage exists, the durable `agent.model.usage` source-key fence\n * remains the cross-restart authority: a replay may retry the idempotent billing\n * write, but it cannot advance metrics, context, or attempt-owned signals.\n */\nexport async function processModelResponseTerminalEvent(input: {\n event: Parameters<typeof modelTerminalResponseFromSdkEvent>[0];\n state: ModelResponseEventState;\n dispatchId: string | null;\n settings: Settings;\n db: ActivityServices[\"db\"];\n observability: ActivityServices[\"observability\"];\n publish: TurnEventPublisher | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n latencyMode?: LatencyMode;\n metricProvider: string;\n externallyBilled: boolean;\n chargesOpenGeniCredits?: boolean;\n countsTowardTokenCap?: boolean;\n servingCredentialId: string | null;\n priorSessionCredentialId: string | null;\n emittedSourceKeys: Set<string>;\n renewLease: () => Promise<void>;\n leaseLost: () => boolean;\n leaseLostMessage: string;\n setLastInputTokens: (tokens: number | null) => Promise<void>;\n contextContributions?: readonly ModelContextContributionSummary[] | null;\n}): Promise<\n | { status: \"not_response\" }\n | { status: \"duplicate\"; sourceKey: string }\n | {\n status: \"processed\";\n sourceKey: string;\n authoritative: boolean;\n usageReported: boolean;\n }\n> {\n const terminal = modelTerminalResponseFromSdkEvent(input.event);\n if (!terminal) {\n return { status: \"not_response\" };\n }\n\n const responseOrdinal = input.state.responseCount + 1;\n const sourceKey = modelUsageSourceKey({\n responseId: terminal.responseId,\n dispatchId: input.dispatchId,\n positionalKey: `response-${responseOrdinal}`,\n });\n if (input.state.claimedSourceKeys.has(sourceKey)) {\n return { status: \"duplicate\", sourceKey };\n }\n input.state.claimedSourceKeys.add(sourceKey);\n input.state.responseCount = responseOrdinal;\n\n const responseUsage = terminal.usage;\n\n const normalizedUsage = normalizeModelCallUsage(responseUsage?.usage);\n const accountContext = modelCallAccountContext({\n servingCredentialId: input.servingCredentialId,\n priorSessionCredentialId: input.priorSessionCredentialId,\n isFirstCallOfTurn: responseOrdinal === 1,\n });\n // A terminal response without usage still authoritatively replaces the\n // attempt-owned context signal. There is simply no billing event to claim.\n let authoritative = responseUsage === null;\n await recordCompletedModelCallBeforeOwnershipFences({\n renewLease: input.renewLease,\n leaseLost: input.leaseLost,\n leaseLostMessage: input.leaseLostMessage,\n recordUsage: async () => {\n if (!responseUsage) return;\n const billing = await recordModelUsageAndDebitCredits(input.settings, input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n model: input.model,\n externallyBilled: input.externallyBilled,\n ...(input.chargesOpenGeniCredits !== undefined\n ? { chargesOpenGeniCredits: input.chargesOpenGeniCredits }\n : {}),\n ...(input.countsTowardTokenCap !== undefined\n ? { countsTowardTokenCap: input.countsTowardTokenCap }\n : {}),\n usage: responseUsage.usage,\n normalizedUsage,\n gatewayBilling: responseUsage.gatewayBilling,\n sourceKey,\n ...(input.latencyMode ? { latencyMode: input.latencyMode } : {}),\n observability: input.observability,\n });\n authoritative = await emitModelCallUsage({\n observability: input.observability,\n publish: input.publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n sourceKey,\n usage: responseUsage,\n normalizedUsage,\n ...(billing ? { billingPath: billing.billingPath } : {}),\n ...(billing?.upstreamProvider ? { upstreamProvider: billing.upstreamProvider } : {}),\n servingAccountHash: accountContext.servingAccountHash,\n accountChangedFromPrevCall: accountContext.accountChangedFromPrevCall,\n emittedSourceKeys: input.emittedSourceKeys,\n });\n if (authoritative && billing) {\n await recordAuthoritativeModelCallFact({\n db: input.db,\n observability: input.observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n sourceKey,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n billing,\n ...(input.contextContributions !== undefined\n ? { contextContributions: input.contextContributions }\n : {}),\n });\n }\n const observedInput = normalizedUsage.telemetry.inputTokens;\n if (authoritative && observedInput !== null && observedInput > 0) {\n recordModelInputTokens(input.observability, input.metricProvider, observedInput);\n }\n },\n recordAttemptSignals: async () => {\n if (!authoritative) return;\n const observedTotal = normalizedUsage.totalTokens;\n input.state.contextSignal =\n observedTotal !== null && observedTotal > 0\n ? { revision: responseOrdinal, totalTokens: observedTotal }\n : null;\n const observedInput = normalizedUsage.telemetry.inputTokens;\n await input.setLastInputTokens(\n observedInput !== null && observedInput > 0 ? observedInput : null,\n );\n },\n });\n return {\n status: \"processed\",\n sourceKey,\n authoritative,\n usageReported: responseUsage !== null,\n };\n}\n\n/**\n * Apply the same source-key authority ordering to the compaction summarizer's\n * usage callback. The summarizer can retry or mirror a terminal response just\n * like the main stream, so claim before lease renewal, billing, durable usage,\n * logging, or cache metrics. Durable source-key idempotency remains the\n * cross-process authority after a worker restart.\n */\nexport async function processCompactionModelUsageEvent(input: {\n usage: ModelResponseUsage;\n state: CompactionModelUsageEventState;\n sourceKind?: \"compaction\" | \"session-title\";\n dispatchId: string | null;\n settings: Settings;\n db: ActivityServices[\"db\"];\n observability: ActivityServices[\"observability\"];\n publish: TurnEventPublisher | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n externallyBilled: boolean;\n chargesOpenGeniCredits?: boolean;\n countsTowardTokenCap?: boolean;\n servingCredentialId: string | null;\n priorSessionCredentialId: string | null;\n emittedSourceKeys: Set<string>;\n renewLease: () => Promise<void>;\n leaseLost: () => boolean;\n leaseLostMessage: string;\n contextContributions?: readonly ModelContextContributionSummary[] | null;\n}): Promise<\n | { status: \"duplicate\"; sourceKey: string }\n | { status: \"processed\"; sourceKey: string; authoritative: boolean }\n> {\n const usageOrdinal = input.state.usageCount + 1;\n const sourceKey = modelUsageSourceKey({\n responseId: input.usage.responseId,\n dispatchId: input.dispatchId,\n positionalKey: `${input.sourceKind ?? \"compaction\"}-${usageOrdinal}`,\n });\n if (input.state.claimedSourceKeys.has(sourceKey)) {\n return { status: \"duplicate\", sourceKey };\n }\n input.state.claimedSourceKeys.add(sourceKey);\n input.state.usageCount = usageOrdinal;\n\n const accountContext = modelCallAccountContext({\n servingCredentialId: input.servingCredentialId,\n priorSessionCredentialId: input.priorSessionCredentialId,\n isFirstCallOfTurn: usageOrdinal === 1,\n });\n const normalizedUsage = normalizeModelCallUsage(input.usage.usage);\n let authoritative = false;\n await recordCompletedModelCallBeforeOwnershipFences({\n renewLease: input.renewLease,\n leaseLost: input.leaseLost,\n leaseLostMessage: input.leaseLostMessage,\n recordUsage: async () => {\n const billing = await recordModelUsageAndDebitCredits(input.settings, input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n model: input.model,\n externallyBilled: input.externallyBilled,\n ...(input.chargesOpenGeniCredits !== undefined\n ? { chargesOpenGeniCredits: input.chargesOpenGeniCredits }\n : {}),\n ...(input.countsTowardTokenCap !== undefined\n ? { countsTowardTokenCap: input.countsTowardTokenCap }\n : {}),\n usage: input.usage.usage,\n normalizedUsage,\n gatewayBilling: input.usage.gatewayBilling,\n sourceKey,\n observability: input.observability,\n });\n authoritative = await emitModelCallUsage({\n observability: input.observability,\n publish: input.publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n sourceKey,\n usage: input.usage,\n normalizedUsage,\n ...(billing ? { billingPath: billing.billingPath } : {}),\n ...(billing?.upstreamProvider ? { upstreamProvider: billing.upstreamProvider } : {}),\n servingAccountHash: accountContext.servingAccountHash,\n accountChangedFromPrevCall: accountContext.accountChangedFromPrevCall,\n emittedSourceKeys: input.emittedSourceKeys,\n });\n if (authoritative && billing) {\n await recordAuthoritativeModelCallFact({\n db: input.db,\n observability: input.observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n sourceKey,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n billing,\n ...(input.contextContributions !== undefined\n ? { contextContributions: input.contextContributions }\n : {}),\n });\n }\n },\n });\n return { status: \"processed\", sourceKey, authoritative };\n}\n\nexport async function processSessionTitleModelUsageEvent(\n input: Omit<Parameters<typeof processCompactionModelUsageEvent>[0], \"sourceKind\">,\n): ReturnType<typeof processCompactionModelUsageEvent> {\n return await processCompactionModelUsageEvent({\n ...input,\n sourceKind: \"session-title\",\n });\n}\n\nexport async function emitModelCallUsage(input: {\n observability: ActivityServices[\"observability\"];\n publish: TurnEventPublisher | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n sourceKey: string;\n usage: ModelResponseUsage | { usage?: unknown | null } | null;\n normalizedUsage?: ModelCallUsageNormalization;\n /** Accepted billing authority persisted for Insights repair after a soft fact-write failure. */\n billingPath?: ModelUsageBillingRecord[\"billingPath\"];\n /** Validated Gateway endpoint provider persisted for exact Insights repair. */\n upstreamProvider?: string;\n // Prompt-cache research dimensions (log-only; NEVER on a metric label or a\n // durable event). The opaque serving-account tag and whether it changed since\n // the session's previous call — the account-switch hypothesis for cache misses.\n servingAccountHash?: string;\n accountChangedFromPrevCall?: boolean;\n emittedSourceKeys?: Set<string>;\n}): Promise<boolean> {\n const usage =\n input.usage && typeof input.usage === \"object\" && \"usage\" in input.usage\n ? (input.usage as { usage?: unknown }).usage\n : null;\n if (!usage || typeof usage !== \"object\") {\n return false;\n }\n if (input.emittedSourceKeys?.has(input.sourceKey)) return false;\n const normalizedUsage =\n input.normalizedUsage ?? normalizeModelCallUsage(usage as ModelCallUsageInput);\n const telemetry = normalizedUsage.telemetry;\n const appended = await input.publish?.(\n [\n {\n type: \"agent.model.usage\",\n payload: {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n sourceKey: input.sourceKey,\n ...(input.billingPath ? { billingPath: input.billingPath } : {}),\n ...(input.upstreamProvider ? { upstreamProvider: input.upstreamProvider } : {}),\n ...telemetry,\n },\n },\n ],\n true,\n );\n input.emittedSourceKeys?.add(input.sourceKey);\n const authoritative = appended?.events.some(\n (event) =>\n event.type === \"agent.model.usage\" &&\n event.turnAssociation === \"current\" &&\n event.payload !== null &&\n typeof event.payload === \"object\" &&\n (event.payload as Record<string, unknown>).sourceKey === input.sourceKey,\n );\n if (!authoritative) return false;\n try {\n input.observability.info(\"model call usage\", {\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n inputTokens: telemetry.inputTokens,\n outputTokens: telemetry.outputTokens,\n cachedTokens: telemetry.cachedTokens,\n cacheWriteTokens: telemetry.cacheWriteTokens,\n reasoningTokens: telemetry.reasoningTokens,\n ...(input.servingAccountHash !== undefined\n ? { servingAccountHash: input.servingAccountHash }\n : {}),\n ...(input.accountChangedFromPrevCall !== undefined\n ? { accountChangedFromPrevCall: input.accountChangedFromPrevCall }\n : {}),\n });\n if (normalizedUsage.rejectedFields.length > 0) {\n input.observability.warn(\"model call usage fields rejected\", {\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n rejectedFields: normalizedUsage.rejectedFields.join(\",\"),\n });\n }\n } catch {\n // Durable event + billing already committed; logging is best-effort only.\n }\n try {\n applyCodexCacheTelemetry(input.observability, input.provider, normalizedUsage);\n } catch {\n // Durable event + billing already committed; metrics are best-effort only.\n }\n return true;\n}\n\n/**\n * Apply one authoritative, normalized model-call usage frame to the shared\n * prompt-cache metrics. The durable source-key fence in `emitModelCallUsage`\n * owns idempotency; this helper must never receive raw provider values.\n */\nexport function applyCodexCacheTelemetry(\n observability: ActivityServices[\"observability\"],\n provider: string,\n normalizedUsage: ModelCallUsageNormalization,\n): void {\n recordModelCacheTokens(observability, provider, {\n cachedTokens: normalizedUsage.telemetry.cachedTokens,\n cacheWriteTokens: normalizedUsage.telemetry.cacheWriteTokens,\n promptTokens: normalizedUsage.telemetry.inputTokens,\n });\n}\n\nexport type ModelUsageBillingRecord = {\n billingPath: \"opengeni_credits\" | \"external\";\n /** Same quantity written to usage_events.model.cost when present; else 0. */\n pricedCostMicros: number;\n /** Hypothetical provider-rate USD micros; never an OpenGeni charge. */\n estimatedProviderCostMicros: number | null;\n /** Hypothetical OpenGeni credit price at the captured rate; never a debit. */\n equivalentCreditCostMicros: number | null;\n pricingSource: \"configured_list_price\" | \"gateway_reported\" | null;\n normalizedUsage: ModelCallUsageNormalization;\n upstreamProvider?: string;\n};\n\n// Exported for unit testing the external-billing bypass; not part of the activity surface.\nexport async function recordModelUsageAndDebitCredits(\n settings: Settings,\n db: ActivityServices[\"db\"],\n input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n model: string;\n externallyBilled: boolean;\n chargesOpenGeniCredits?: boolean;\n countsTowardTokenCap?: boolean;\n gatewayBilling?: ModelResponseUsage[\"gatewayBilling\"];\n usage?: ModelUsageInput | ModelCallUsageInput | null;\n normalizedUsage?: ModelCallUsageNormalization;\n sourceKey: string;\n latencyMode?: LatencyMode;\n observability?: ActivityServices[\"observability\"];\n },\n): Promise<ModelUsageBillingRecord | null> {\n if (!input.usage) {\n return null;\n }\n const normalizedUsage = input.normalizedUsage ?? normalizeModelCallUsage(input.usage);\n const sanitizedUsage = sanitizedModelUsageInput(normalizedUsage);\n const inputTokens = sanitizedUsage.inputTokens ?? 0;\n const outputTokens = sanitizedUsage.outputTokens ?? 0;\n const totalTokens = sanitizedUsage.totalTokens ?? 0;\n const chargesOpenGeniCredits = input.chargesOpenGeniCredits ?? !input.externallyBilled;\n const countsTowardTokenCap = input.countsTowardTokenCap ?? !input.externallyBilled;\n const resolvedGatewayModel = input.gatewayBilling\n ? resolveModelProvider(settings, input.model)\n : undefined;\n const gatewayProviderId = resolvedGatewayModel?.provider.id;\n const gatewayBilling =\n gatewayProviderId === OPENGENI_GATEWAY_PROVIDER_ID ||\n gatewayProviderId === WORKSPACE_GATEWAY_PROVIDER_ID\n ? input.gatewayBilling\n : undefined;\n const allowedProviders = resolvedGatewayModel?.model.requestPolicy?.gateway.only;\n const unpinnedWorkspaceGatewayModel =\n gatewayProviderId === WORKSPACE_GATEWAY_PROVIDER_ID && allowedProviders === undefined;\n if (gatewayBilling) {\n if (\n !unpinnedWorkspaceGatewayModel &&\n (!allowedProviders ||\n !(allowedProviders as readonly string[]).includes(gatewayBilling.finalProvider))\n ) {\n throw new Error(\n `AI Gateway reported unapproved provider ${gatewayBilling.finalProvider} for ${input.model}`,\n );\n }\n if (unpinnedWorkspaceGatewayModel && chargesOpenGeniCredits) {\n throw new Error(\n `Workspace Gateway custom model ${input.model} cannot charge OpenGeni credits without pinned pricing`,\n );\n }\n }\n const pricingSchedules = configuredModelPricingSchedules(settings);\n const configuredPricingModel = pricingSchedules[input.model]\n ? input.model\n : input.model.startsWith(\"codex/\") && pricingSchedules[input.model.slice(\"codex/\".length)]\n ? input.model.slice(\"codex/\".length)\n : null;\n const pricingBreakdown = gatewayBilling\n ? unpinnedWorkspaceGatewayModel\n ? {\n providerCostMicros: calculateGatewayReportedProviderCostMicros(\n gatewayBilling.inferenceCostUsd,\n ),\n creditCostMicros: 0,\n }\n : calculateGatewayReportedCostBreakdown(\n settings,\n configuredPricingModel ?? input.model,\n gatewayBilling.inferenceCostUsd,\n { inputTokens },\n )\n : configuredPricingModel\n ? calculateModelUsageCostBreakdown(settings, configuredPricingModel, sanitizedUsage, {\n latencyMode: input.latencyMode ?? \"standard\",\n })\n : null;\n const hasCompleteCoreTokenTelemetry =\n normalizedUsage.telemetry.inputTokens !== null &&\n normalizedUsage.telemetry.outputTokens !== null;\n const estimatedProviderCostMicros = gatewayBilling\n ? (pricingBreakdown?.providerCostMicros ?? null)\n : hasCompleteCoreTokenTelemetry\n ? (pricingBreakdown?.providerCostMicros ?? null)\n : null;\n const equivalentCreditCostMicros =\n pricingBreakdown && !unpinnedWorkspaceGatewayModel\n ? gatewayBilling || hasCompleteCoreTokenTelemetry\n ? pricingBreakdown.creditCostMicros\n : null\n : null;\n const pricingSource = gatewayBilling\n ? (\"gateway_reported\" as const)\n : estimatedProviderCostMicros !== null\n ? (\"configured_list_price\" as const)\n : null;\n // Provider settlement and workspace-facing cost are separate. Externally\n // metered subscription/workspace turns remain exempt from the OpenGeni token\n // cap, while a deployment-funded free model still records model.tokens. Every\n // non-credit path records a zero-cost marker and never consults pricing for a\n // debit.\n if (countsTowardTokenCap && totalTokens > 0) {\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"model.tokens\",\n quantity: totalTokens,\n unit: \"tokens\",\n sourceResourceType: \"model_response\",\n sourceResourceId: `${input.turnId}:${input.sourceKey}`,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n idempotencyKey: `usage:model.tokens:${input.turnId}:${input.sourceKey}`,\n });\n }\n if (!chargesOpenGeniCredits) {\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"model.cost\",\n quantity: 0,\n unit: \"usd_micros\",\n sourceResourceType: \"model_response\",\n sourceResourceId: `${input.turnId}:${input.sourceKey}`,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`,\n });\n return {\n billingPath: \"external\",\n pricedCostMicros: 0,\n estimatedProviderCostMicros,\n equivalentCreditCostMicros,\n pricingSource,\n normalizedUsage,\n ...(gatewayBilling ? { upstreamProvider: gatewayBilling.finalProvider } : {}),\n };\n }\n const shouldDebit = settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\";\n if (!shouldDebit || (totalTokens === 0 && !gatewayBilling)) {\n return {\n billingPath: \"opengeni_credits\",\n pricedCostMicros: 0,\n estimatedProviderCostMicros,\n equivalentCreditCostMicros,\n pricingSource,\n normalizedUsage,\n ...(gatewayBilling ? { upstreamProvider: gatewayBilling.finalProvider } : {}),\n };\n }\n if (!pricingBreakdown) {\n throw new Error(`Missing model pricing for ${input.model}`);\n }\n const costMicros = pricingBreakdown.creditCostMicros;\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"model.cost\",\n quantity: costMicros,\n unit: \"usd_micros\",\n sourceResourceType: \"model_response\",\n sourceResourceId: `${input.turnId}:${input.sourceKey}`,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`,\n });\n if (costMicros > 0) {\n const result = await applyCreditDebitUpToBalance(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n type: \"model_usage_debit\",\n requestedAmountMicros: costMicros,\n sourceType: \"model_response\",\n sourceId: `${input.turnId}:${input.sourceKey}`,\n idempotencyKey: `credit:model_usage_debit:${input.turnId}:${input.sourceKey}`,\n metadata: {\n model: input.model,\n sessionId: input.sessionId,\n turnId: input.turnId,\n sourceKey: input.sourceKey,\n latencyMode: input.latencyMode ?? \"standard\",\n inputTokens,\n outputTokens,\n totalTokens,\n // Additive: the prompt-cache slice of this call's input tokens, so the\n // per-call debit record carries cache efficiency alongside the token\n // counts. 0 when the provider did not report cached tokens.\n cachedTokens: normalizedUsage.telemetry.cachedTokens ?? 0,\n ...(gatewayBilling ? { gatewayProvider: gatewayBilling.finalProvider } : {}),\n },\n });\n recordCreditMicros(input.observability, \"usage\", result.debitedMicros);\n }\n return {\n billingPath: \"opengeni_credits\",\n pricedCostMicros: costMicros,\n estimatedProviderCostMicros,\n equivalentCreditCostMicros,\n pricingSource,\n normalizedUsage,\n ...(gatewayBilling ? { upstreamProvider: gatewayBilling.finalProvider } : {}),\n };\n}\n\n/** Soft-fail Insights fact write — never throws into the billing/emit path. */\nexport async function recordAuthoritativeModelCallFact(input: {\n db: ActivityServices[\"db\"];\n observability: ActivityServices[\"observability\"];\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n sourceKey: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n billing: ModelUsageBillingRecord;\n contextContributions?: readonly ModelContextContributionSummary[] | null;\n}): Promise<void> {\n try {\n const telemetry = input.billing.normalizedUsage.telemetry;\n await recordModelCallFact(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n sourceKey: input.sourceKey,\n provider: input.billing.upstreamProvider ?? input.provider,\n providerApi: input.providerApi,\n model: input.model,\n billingPath: input.billing.billingPath,\n pricedCostMicros: input.billing.pricedCostMicros,\n estimatedProviderCostMicros: input.billing.estimatedProviderCostMicros,\n equivalentCreditCostMicros: input.billing.equivalentCreditCostMicros,\n pricingSource: input.billing.pricingSource,\n inputTokens: telemetry.inputTokens,\n outputTokens: telemetry.outputTokens,\n cachedTokens: telemetry.cachedTokens,\n cacheWriteTokens: telemetry.cacheWriteTokens,\n reasoningTokens: telemetry.reasoningTokens,\n totalTokens: input.billing.normalizedUsage.totalTokens,\n ...(input.contextContributions !== undefined\n ? { contextContributions: input.contextContributions }\n : {}),\n });\n } catch (error) {\n input.observability.warn(\"model call fact persist failed\", {\n ...safeErrorDiagnostic(error),\n });\n }\n}\n\nexport function sanitizedModelUsageInput(normalized: ModelCallUsageNormalization): ModelUsageInput {\n return {\n ...(normalized.telemetry.inputTokens !== null\n ? { inputTokens: normalized.telemetry.inputTokens }\n : {}),\n ...(normalized.telemetry.outputTokens !== null\n ? { outputTokens: normalized.telemetry.outputTokens }\n : {}),\n ...(normalized.totalTokens !== null ? { totalTokens: normalized.totalTokens } : {}),\n ...(normalized.telemetry.cachedTokens !== null || normalized.telemetry.cacheWriteTokens !== null\n ? {\n inputTokensDetails: {\n ...(normalized.telemetry.cachedTokens === null\n ? {}\n : { cached_tokens: normalized.telemetry.cachedTokens }),\n ...(normalized.telemetry.cacheWriteTokens === null\n ? {}\n : { cache_write_tokens: normalized.telemetry.cacheWriteTokens }),\n },\n }\n : {}),\n ...(normalized.requestUsageEntries\n ? { requestUsageEntries: normalized.requestUsageEntries }\n : {}),\n };\n}\n\nexport function startOfUtcMonth(): Date {\n const now = new Date();\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));\n}\n","import {\n getSessionEvent,\n getHumanInputResumeForEvent,\n getSessionHumanInputRequest,\n getWorkspace,\n recordUsageEvent,\n registerPendingSessionToolCall,\n recordPendingSessionToolCallResult,\n attachOpenSuffixToPendingToolCalls,\n clearDurablePendingSessionToolCalls,\n isSessionCompactionRequested,\n nextSessionHistoryPosition,\n persistModelContextSnapshot,\n updateSessionTitleWithEvent,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport {\n normalizeModelCallUsage,\n normalizeSdkEvent,\n extractOpenSuffixFromRunState,\n assertOpenSuffixResumable,\n interruptionKindForCallItem,\n releaseMcpResultCustomDataFromSdkEvent,\n findCompactionNeededError,\n withRunCredentialsSession,\n runOwnedSandboxSetup,\n type SandboxFileDownload,\n type OpenGeniRuntime,\n type HistoryProviderApi,\n type GitCredentialTokenWriterSession,\n type NormalizedRunCredentialMaterial,\n type RunCredentialCommandSession,\n type CodemodeTokenWriterSession,\n} from \"@opengeni/runtime\";\nimport { serviceTierForLatencyMode, type Settings } from \"@opengeni/config\";\nimport { maybeCompactContext, settleFailedContextCompactionLandmark } from \"../context-compaction\";\nimport { TurnAttemptFencedError } from \"../turn-attempt-fenced\";\nimport { type MintedRunGitCredentials } from \"../environment\";\nimport { withFirstPartyTools } from \"../goals\";\nimport { turnInput } from \"../run-input\";\nimport { createRuntimeBatcher, currentActivityContext, nextStreamEvent } from \"../streaming\";\nimport type {\n TurnActivityServices as ActivityServices,\n RunAgentTurnInput,\n RunAgentTurnResult,\n} from \"../types\";\nimport { type ResumedTurnSandbox } from \"../../sandbox-resume\";\nimport {\n modelCallAccountContext,\n recordBatchFlush,\n recordContextCompaction,\n recordModelInputTokens,\n recordTurnStartupPhase,\n recordTurnWorkerPreparationTotal,\n recordSandboxSharedPreparation,\n StreamTimingMetrics,\n turnLifecycleMetricsFor,\n} from \"../../observability-metrics\";\nimport {\n compactRetainedScreenshotHistory,\n sdkEventContainsInlineImage,\n retainComputerScreenshot,\n typedScreenshotFromSdkEvent,\n unavailableRetainedSessionImage,\n} from \"../retained-screenshots\";\nimport {\n compactGeneratedImageSdkEvent,\n generatedImageFromSdkEvent,\n isCompletedGeneratedImageSdkEvent,\n} from \"../generated-images\";\nimport { ToolResultSpill } from \"./tool-result-spill\";\nimport { createTurnCredentialLeases } from \"./credential-leases\";\nimport { createTurnMediaArtifacts } from \"./media-artifacts\";\nimport { createTurnHistorySink } from \"./history-sink\";\nimport {\n interruptionCallIdsFromPause,\n settleOpenSuffixResumeIfNeeded,\n} from \"../open-suffix-resume\";\nimport {\n OPEN_SUFFIX_RUN_STATE_BLOB,\n resolveWorkspaceAgentHumanInputEnabled,\n type RetainedArtifactMetadata,\n type SessionEvent,\n} from \"@opengeni/contracts\";\nimport { createModelCheckpointMemoryCollector } from \"../../model-checkpoint-memory-collector\";\n\nimport {\n assertWorkspaceHumanInputAllowed,\n stableHumanInputRequestId,\n stableInteractionInterventionId,\n stableInteractionInterventionOperationId,\n BudgetExhaustedError,\n ensureRunAllowed,\n} from \"./admission\";\nimport {\n compactionFailureReason,\n safeErrorDiagnostic,\n compactionFailureReasonFromError,\n isCompactionSummaryFailure,\n PostCompactionContinuationEmptyError,\n shouldRecoverCompactionProviderFailure,\n classifyContextWindowOverflowError,\n} from \"./errors\";\nimport {\n pendingToolCallFromSdkEvent,\n toolCallProducesRetainableSessionImage,\n completedToolCallFromSdkEvent,\n} from \"./history\";\nimport { checkpointHistoryBeforeProviderDispatch } from \"./provider-dispatch-barrier\";\nimport {\n modelUsageSourceKey,\n recordCompletedModelCallBeforeOwnershipFences,\n TurnEventPublisher,\n createModelResponseEventState,\n createSessionTitleModelUsageEventState,\n modelResponseContextSignal,\n assertModelResponseLatencyMode,\n processModelResponseTerminalEvent,\n processSessionTitleModelUsageEvent,\n emitModelCallUsage,\n recordModelUsageAndDebitCredits,\n recordAuthoritativeModelCallFact,\n} from \"./model-usage\";\nimport { startParallelSessionTitleGeneration } from \"./session-title\";\nimport {\n assertAgentStreamNotCancelled,\n assertSuccessfulAgentStreamCompletion,\n requireAgentStreamFinalOutput,\n} from \"./quiescence\";\nimport { waitForTurnOperation } from \"./sandbox-provision\";\nimport { createSharedRigSetupCoordinator } from \"./sandbox-shared-preparation\";\n\nimport type { CompactionSummarizer } from \"../context-compaction\";\nimport type { TurnExecutionPolicyV1 } from \"@opengeni/contracts\";\nimport type { BoundRunCredentialResolver } from \"../run-credentials\";\nimport type { ModelHistoryAttachmentProjector } from \"../run-input\";\nimport type {\n AttemptIdentityState,\n BillingState,\n ClaimedResult,\n EventingState,\n ProviderTurnState,\n SandboxRuntimeState,\n TurnControlState,\n} from \"./turn-context\";\n\nexport type TurnStreamAttemptDeps = {\n input: RunAgentTurnInput;\n settings: Settings;\n db: ActivityServices[\"db\"];\n bus: ActivityServices[\"bus\"];\n runtime: ActivityServices[\"runtime\"];\n objectStorage: ActivityServices[\"objectStorage\"];\n observability: ActivityServices[\"observability\"];\n entitlements: ActivityServices[\"entitlements\"];\n startVideoGenerationWorkflow: ActivityServices[\"startVideoGenerationWorkflow\"];\n cancellationSignal: AbortSignal | undefined;\n runtimeCancellationSignal: AbortSignal;\n activityContext: ReturnType<typeof currentActivityContext>;\n dispatchId: string;\n control: TurnControlState;\n attempt: AttemptIdentityState;\n billingState: BillingState;\n sandboxState: SandboxRuntimeState;\n eventing: EventingState & {\n publish: TurnEventPublisher;\n settle: NonNullable<EventingState[\"settle\"]>;\n };\n providerTurn: ProviderTurnState;\n leases: ReturnType<typeof createTurnCredentialLeases>;\n historySink: ReturnType<typeof createTurnHistorySink>;\n media: ReturnType<typeof createTurnMediaArtifacts>;\n toolResultSpill: ToolResultSpill;\n claimedResult: ClaimedResult;\n flushRuntimeBatcher: () => Promise<void>;\n finalizeTurnOpStreamOps: () => Promise<void>;\n runWorkspaceMutationForSandbox: <T>(\n sandbox: ResumedTurnSandbox,\n operation: string,\n mutation: () => Promise<T>,\n observePhase?: (measurement: {\n phase: \"admission\" | \"provider\" | \"settlement\" | \"snapshot_wait\";\n outcome: \"completed\" | \"failed\";\n durationSeconds: number;\n }) => void,\n ) => Promise<T>;\n throwIfWorkerShuttingDown: () => void;\n throwIfTurnCancelled: () => void;\n setLastInputTokensFenced: (lastInputTokens: number | null) => Promise<void>;\n attachGitCredentialRenewal: (\n tokenSession: GitCredentialTokenWriterSession,\n initial: MintedRunGitCredentials | undefined,\n initialSandbox?: ResumedTurnSandbox,\n ) => Promise<void>;\n attachCodemodeTokenRenewal: (\n tokenSession?: CodemodeTokenWriterSession,\n initialExpiresAt?: Date,\n initialSandbox?: ResumedTurnSandbox,\n ) => Promise<void>;\n attachRunCredentialRenewal: (\n credentialSession: RunCredentialCommandSession,\n initialMaterial: NormalizedRunCredentialMaterial | null,\n initialSandbox?: ResumedTurnSandbox,\n ) => Promise<void>;\n withProviderRequestContext: <T>(fn: () => Promise<T>) => Promise<T>;\n withSessionTitleProviderRequestContext: <T>(fn: () => Promise<T>) => Promise<T>;\n publishCompactionLiveEvents: (events: SessionEvent[]) => Promise<void>;\n publishCompactionOutcomeEvents: (events: SessionEvent[]) => Promise<void>;\n recordCompanyBrainContributionReceiptOnce: () => void;\n modelCheckpointMemoryCollector: ReturnType<typeof createModelCheckpointMemoryCollector>;\n claimedModelUsageSourceKeys: Set<string>;\n emittedModelUsageSourceKeys: Set<string>;\n modelUsageDispatchId: string;\n workerPreparationStartedAt: number;\n fileDownloadsMaterializedForRun: boolean;\n unavailableSandboxFilesNote: string | undefined;\n runCredentialsNote: string | undefined;\n mcpAvailabilityNote: string | undefined;\n fileAuthoritySubjectId: string | null;\n activeSandboxBackend: Settings[\"sandboxBackend\"] | undefined;\n groupBoxBackend: Settings[\"sandboxBackend\"];\n turnExecutionPolicy: TurnExecutionPolicyV1;\n turn: { executionGeneration: number; model: string };\n trigger: NonNullable<Awaited<ReturnType<typeof getSessionEvent>>>;\n humanInputResume: Awaited<ReturnType<typeof getHumanInputResumeForEvent>>;\n attachPendingUpdatesAfterOpenSuffix: () => Promise<boolean>;\n agent: ReturnType<ActivityServices[\"runtime\"][\"buildAgent\"]>;\n resolvedModel: ReturnType<ActivityServices[\"runtime\"][\"resolveTurnModel\"]>;\n providerApi: HistoryProviderApi;\n runSettings: Settings;\n turnTools: ReturnType<typeof withFirstPartyTools>;\n generateSessionTitleInParallel: boolean;\n sessionTitlePrompt: string;\n compactSummarizer: CompactionSummarizer;\n settleDeferredSteerAfterCompaction: () => Promise<RunAgentTurnResult | null>;\n compactionModelHistoryProjector: (\n items: Array<Record<string, unknown>>,\n ) => Promise<Array<Record<string, unknown>>>;\n generatedImageHistoryProjector: (\n items: Array<Record<string, unknown>>,\n ) => Promise<Array<Record<string, unknown>>>;\n modelHistoryProjector: ModelHistoryAttachmentProjector;\n compactionModeOptions: NonNullable<Parameters<typeof maybeCompactContext>[5]>;\n initialRunCredentialMaterial: NormalizedRunCredentialMaterial | null;\n initialGitCredentials: MintedRunGitCredentials | undefined;\n sandboxEnvironment: Record<string, string>;\n sandboxCodemodeToken: string | undefined;\n sandboxCodemodeTokenExpiresAt: Date | string | number | null | undefined;\n fileResourceDownloads: SandboxFileDownload[];\n runCredentialResolver: BoundRunCredentialResolver | null;\n videoGenerationAcceptancesByCallId: Map<string, { operationId: string; requestDigest: string }>;\n};\n\nexport async function attachPendingUpdatesBeforePreparingModelInput(input: {\n shouldAttach: boolean;\n attachPendingUpdates: () => Promise<boolean>;\n prepareModelInput: () => Promise<void>;\n}): Promise<boolean> {\n if (input.shouldAttach && !(await input.attachPendingUpdates())) return false;\n await input.prepareModelInput();\n return true;\n}\n\nexport async function runTurnStreamAttempt(\n deps: TurnStreamAttemptDeps,\n): Promise<RunAgentTurnResult> {\n const {\n input,\n settings,\n db,\n bus,\n runtime,\n objectStorage,\n observability,\n entitlements,\n startVideoGenerationWorkflow,\n cancellationSignal,\n runtimeCancellationSignal,\n activityContext,\n dispatchId,\n control,\n attempt,\n billingState,\n sandboxState,\n eventing,\n providerTurn,\n leases,\n historySink,\n media,\n toolResultSpill,\n claimedResult,\n flushRuntimeBatcher,\n finalizeTurnOpStreamOps,\n runWorkspaceMutationForSandbox,\n throwIfWorkerShuttingDown,\n throwIfTurnCancelled,\n setLastInputTokensFenced,\n attachGitCredentialRenewal,\n attachCodemodeTokenRenewal,\n attachRunCredentialRenewal,\n withProviderRequestContext,\n withSessionTitleProviderRequestContext,\n publishCompactionLiveEvents,\n publishCompactionOutcomeEvents,\n recordCompanyBrainContributionReceiptOnce,\n modelCheckpointMemoryCollector,\n claimedModelUsageSourceKeys,\n emittedModelUsageSourceKeys,\n modelUsageDispatchId,\n workerPreparationStartedAt,\n fileDownloadsMaterializedForRun,\n unavailableSandboxFilesNote,\n runCredentialsNote,\n mcpAvailabilityNote,\n fileAuthoritySubjectId,\n activeSandboxBackend,\n groupBoxBackend,\n turnExecutionPolicy,\n turn,\n trigger,\n humanInputResume,\n attachPendingUpdatesAfterOpenSuffix,\n agent,\n resolvedModel,\n providerApi,\n runSettings,\n turnTools,\n generateSessionTitleInParallel,\n sessionTitlePrompt,\n compactSummarizer,\n settleDeferredSteerAfterCompaction,\n compactionModelHistoryProjector,\n generatedImageHistoryProjector,\n modelHistoryProjector,\n compactionModeOptions,\n initialRunCredentialMaterial,\n initialGitCredentials,\n sandboxEnvironment,\n sandboxCodemodeToken,\n sandboxCodemodeTokenExpiresAt,\n fileResourceDownloads,\n runCredentialResolver,\n videoGenerationAcceptancesByCallId,\n } = deps;\n\n // Build one attempt from canonical history. The provider adapter creates\n // only the temporary wire view required by this turn's selected API;\n // subscription identity never edits or filters durable history.\n const activeTurnId = attempt.turnId;\n if (!activeTurnId) {\n throw new Error(\"Turn id was not initialized\");\n }\n const sessionTitleUsageState = createSessionTitleModelUsageEventState(\n claimedModelUsageSourceKeys,\n );\n let parallelSessionTitle: ReturnType<typeof startParallelSessionTitleGeneration> | null = null;\n let parallelSessionTitleFinished = false;\n const finishParallelSessionTitle = async (): Promise<void> => {\n if (parallelSessionTitleFinished) return;\n parallelSessionTitleFinished = true;\n const generated = await parallelSessionTitle?.finish();\n if (!generated) return;\n\n if (generated.usage) {\n await processSessionTitleModelUsageEvent({\n usage: generated.usage,\n state: sessionTitleUsageState,\n dispatchId: modelUsageDispatchId,\n settings,\n db,\n observability,\n publish: eventing.publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n provider: resolvedModel?.provider.id ?? settings.openaiProvider,\n providerApi: resolvedModel?.provider.api ?? \"responses\",\n model: resolvedModel?.configured.id ?? turn.model,\n externallyBilled: billingState.isExternallyBilledTurn,\n chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,\n countsTowardTokenCap: billingState.countsTowardTokenCap,\n servingCredentialId: providerTurn.effectiveCodexCredentialId,\n priorSessionCredentialId: providerTurn.priorSessionCodexCredentialId,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n renewLease: () => leases.renewServing(\"model_usage\"),\n leaseLost: leases.servingLost,\n leaseLostMessage: \"Provider credential lease expired during session title generation\",\n });\n }\n if (!generated.title) return;\n\n try {\n const result = await updateSessionTitleWithEvent(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n title: generated.title,\n source: \"agent\",\n });\n if (result.events.length > 0) {\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, result.events);\n }\n } catch (error) {\n observability.warn(\"parallel session title persistence failed\", {\n ...safeErrorDiagnostic(error),\n errorClass: \"ParallelSessionTitlePersistenceError\",\n errorCode: \"parallel_session_title_persistence_failed\",\n origin: \"worker\",\n });\n }\n };\n const cancelParallelSessionTitle = async (): Promise<void> => {\n if (parallelSessionTitleFinished) return;\n parallelSessionTitleFinished = true;\n await parallelSessionTitle?.cancel();\n };\n let runInput: Awaited<ReturnType<typeof turnInput>>[\"input\"] | null = null;\n const prepareRunAttemptInput = async () => {\n const historyPreparationStartedAt = performance.now();\n let historyPreparationOutcome: \"completed\" | \"failed\" = \"completed\";\n let preparedHistoryCount: number | null = null;\n try {\n const prepared = await turnInput(db, runtime, agent, trigger, {\n turnId: activeTurnId,\n fileAuthority: {\n accountId: input.accountId,\n subjectId: fileAuthoritySubjectId,\n },\n recovering: turn.executionGeneration > 1,\n ...(unavailableSandboxFilesNote ? { unavailableSandboxFilesNote } : {}),\n ...(runCredentialsNote ? { runCredentialsNote } : {}),\n ...(mcpAvailabilityNote ? { mcpAvailabilityNote } : {}),\n providerApi,\n projectCanonicalHistory: generatedImageHistoryProjector,\n materializeModelHistory: media.materializeScreenshotHistory,\n projectModelHistory: modelHistoryProjector,\n onPreparationPhase: (measurement) => {\n recordTurnStartupPhase(observability, {\n phase: `history_${measurement.phase}`,\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: measurement.outcome,\n durationSeconds: measurement.durationSeconds,\n });\n },\n });\n runInput = prepared.input;\n historySink.providerArtifactCandidates = prepared.providerArtifactCandidates;\n // Slice index = the length of the model-facing (active) history this turn\n // is seeded from; new items beyond it (the trigger message + this turn's\n // generated items) are the ones to persist. After a compaction this is the\n // short [summary, ...tail] active set, NOT the total row count. The\n // absolute write position is tracked separately (next whole number past\n // the max existing position) because the fractional summary row means\n // total rows no longer equal max(position)+1. Pre-compaction both reduce to\n // the old total-count value, so the common path is unchanged.\n //\n // CRITICAL: seed from the structurally repaired 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 // repaired `state.history` off `historySink.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 repaired 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 // prepareInput already sanitized the exact durable prefix represented\n // by state.history. Carry its count forward instead of loading and\n // retaining the full active transcript a second time beside runInput.\n historySink.seedHistory(prepared.input.input, prepared.persistedHistoryCount);\n preparedHistoryCount = prepared.persistedHistoryCount;\n const historyPositionStartedAt = performance.now();\n let historyPositionOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n historySink.nextHistoryPosition = await nextSessionHistoryPosition(\n db,\n input.workspaceId,\n input.sessionId,\n );\n } catch (error) {\n historyPositionOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"history_position_load\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: historyPositionOutcome,\n durationSeconds: (performance.now() - historyPositionStartedAt) / 1_000,\n });\n }\n } catch (error) {\n historyPreparationOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"history_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: historyPreparationOutcome,\n durationSeconds: (performance.now() - historyPreparationStartedAt) / 1_000,\n count: preparedHistoryCount,\n });\n }\n };\n\n const forceContextCompaction = async (\n triggerLabel: \"overflow\" | \"proactive\" | \"operator\",\n recoverySignalTokens: number | null,\n ) => {\n const outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n eventing.modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n // Never reuse the persisted prior-turn signal for recovery. Proactive\n // guards provide their exact current provider-based signal; provider\n // overflows do not, so their diagnostic signal stays unknown/zero.\n // Forced recovery proves progress separately by comparing the\n // replacement with the current active-history estimate.\n recoverySignalTokens,\n compactSummarizer,\n {\n force: true,\n ...(triggerLabel === \"operator\" ? { clearRequestedCompaction: true } : {}),\n trigger: triggerLabel,\n materializeHistory: media.materializeScreenshotHistory,\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, triggerLabel);\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n return outcome;\n };\n\n // Keep response identity across every stream attempt in this\n // activity. Context compaction retries the same logical dispatch by\n // calling runStreamAttempt again; resetting this state there would reuse\n // the first no-response-ID fallback key and suppress a real model call.\n const modelResponseState = createModelResponseEventState(claimedModelUsageSourceKeys);\n let workerPreparationTotalRecorded = false;\n const runStreamAttempt = async (options: {\n requireTerminalModelResponse: boolean;\n }): Promise<RunAgentTurnResult> => {\n if (!runInput) {\n throw new Error(\"Run input was not prepared\");\n }\n const responseCountBeforeStream = modelResponseState.responseCount;\n eventing.stream = undefined;\n eventing.batcher = null;\n // The SDK emits every processed call item for one model response before\n // it emits any result for that response. Keep that response-local batch\n // in memory so an orphan from an older response cannot pin later stable\n // calls. Durable recovery remains call/result based and needs no batch\n // schema or compatibility state.\n let currentToolBatchCallIds = new Set<string>();\n let currentToolBatchCompletedCallIds = new Set<string>();\n let streamSawPerResponseUsage = false;\n // Actual input tokens of the most recent model response this turn; the\n // pre-read trigger for the NEXT turn. Persisted at every turn-end path.\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n const streamProvider = resolvedModel?.provider.id ?? settings.openaiProvider ?? \"openai\";\n const providerPublishesNativeRequestEvents =\n resolvedModel?.provider.kind === \"codex-subscription\" ||\n resolvedModel?.provider.kind === \"xai-subscription\";\n let fallbackProviderRequestStartedAt: number | null = null;\n let fallbackProviderRequestLifecycleStartedAt: number | null = null;\n const recordFallbackProviderDispatchAtWire = async (): Promise<void> => {\n await checkpointHistoryBeforeProviderDispatch(historySink);\n if (\n providerPublishesNativeRequestEvents ||\n eventing.firstModelRequestPreparationRecorded ||\n eventing.firstModelRequestPreparationStartedAt === null\n ) {\n return;\n }\n sandboxState.firstProviderRequestStarted = true;\n eventing.firstModelRequestPreparationRecorded = true;\n const preparationDurationMs = Math.max(\n 0,\n performance.now() - eventing.firstModelRequestPreparationStartedAt,\n );\n recordTurnStartupPhase(observability, {\n phase: \"model_request_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: preparationDurationMs / 1_000,\n count: turnTools.length,\n });\n const auditStartedAt = performance.now();\n let auditOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n await eventing.publish!([\n {\n type: \"turn.startup.phase.completed\",\n payload: {\n phase: \"model_preparation\",\n durationMs: Math.round(preparationDurationMs),\n },\n },\n {\n type: \"agent.model.request\",\n payload: {\n phase: \"started\",\n provider: streamProvider,\n turnId: activeTurnId,\n attemptId: input.attemptId,\n dispatchId,\n executionGeneration: attempt.executionGeneration,\n },\n },\n ]);\n fallbackProviderRequestStartedAt = performance.now();\n fallbackProviderRequestLifecycleStartedAt = fallbackProviderRequestStartedAt;\n } catch (error) {\n auditOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"model_request_audit\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: auditOutcome,\n durationSeconds: (performance.now() - auditStartedAt) / 1_000,\n count: turnTools.length,\n });\n }\n };\n const ownedEstablished =\n sandboxState.resolvedSandbox?.established ?? sandboxState.lazyOwnedSandbox;\n const runStreamOnce = async (): ReturnType<OpenGeniRuntime[\"runStream\"]> => {\n const eagerResolvedSandbox = sandboxState.resolvedSandbox;\n // Eager owned sessions must settle the exact platform-setup provider\n // promise before the long model stream starts; otherwise one admission\n // would remain in flight for the entire turn and suppress every\n // heartbeat capture. Lazy setup already runs under the same wrapper in\n // its first-operation provisioner above.\n if (eagerResolvedSandbox && !sandboxState.lazyOwnedSandbox && ownedEstablished) {\n const ownedSandboxSetupStartedAt = performance.now();\n let ownedSandboxSetupOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n const eagerSetupSession = sandboxState.setupBoxSession ?? ownedEstablished.session;\n // `deferredSetup: true` below tells the runtime that the worker owns\n // platform setup, so the runtime intentionally skips its credential\n // session callback. Materialize host-managed run credentials here\n // before any setup command (including provider login hooks), then\n // decorate setup commands so they source the active generation.\n await attachRunCredentialRenewal(\n eagerSetupSession as RunCredentialCommandSession,\n initialRunCredentialMaterial,\n eagerResolvedSandbox,\n );\n const eagerCredentialSetupSession = initialRunCredentialMaterial\n ? withRunCredentialsSession(eagerSetupSession as object, input.sessionId)\n : eagerSetupSession;\n await runWorkspaceMutationForSandbox(\n eagerResolvedSandbox,\n \"eagerOwnedSandboxSetup\",\n async () =>\n await runOwnedSandboxSetup(\n agent,\n ownedEstablished.session as never,\n eagerCredentialSetupSession as never,\n {\n settings: runSettings,\n environment: sandboxEnvironment,\n preparedInput: runInput!,\n ...(fileDownloadsMaterializedForRun ? { fileDownloadsMaterialized: true } : {}),\n onRuntimeEvent: async (event) => {\n await leases.renewServing(\"runtime_event\");\n if (leases.servingLost()) {\n throw new Error(\"Provider credential lease expired during sandbox setup\");\n }\n await eventing.publish!([{ type: event.type, payload: event.payload }], true);\n },\n ...(eventing.toolCancellationFenceRef.current\n ? {\n commandRunner:\n eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(\n eventing.toolCancellationFenceRef.current,\n ),\n }\n : {}),\n ...(sandboxState.sandboxGroupId && sandboxState.sandboxHolderId\n ? {\n coordinateSharedRigSetup: createSharedRigSetupCoordinator({\n db,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: sandboxState.sandboxGroupId,\n attemptId: input.attemptId,\n holderId: sandboxState.sandboxHolderId,\n sandbox: eagerResolvedSandbox,\n ...(runtimeCancellationSignal\n ? { signal: runtimeCancellationSignal }\n : {}),\n observe: (measurement) =>\n recordSandboxSharedPreparation(observability, measurement),\n }),\n }\n : {}),\n },\n ),\n );\n await attachGitCredentialRenewal(\n eagerSetupSession as GitCredentialTokenWriterSession,\n initialGitCredentials,\n );\n } catch (error) {\n ownedSandboxSetupOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"owned_sandbox_setup\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: ownedSandboxSetupOutcome,\n durationSeconds: (performance.now() - ownedSandboxSetupStartedAt) / 1_000,\n count: fileResourceDownloads.length,\n });\n }\n }\n // Conservative request boundary: once control enters runStream, the\n // provider may have accepted work even if no response/event follows.\n // Escaped MCP setup timeouts are automatically recoverable only\n // before this line.\n recordCompanyBrainContributionReceiptOnce();\n if (!eventing.firstModelRequestPreparationRecorded) {\n await eventing.publish!([\n {\n type: \"turn.startup.phase.started\",\n payload: { phase: \"model_preparation\" },\n },\n ]);\n eventing.firstModelRequestPreparationStartedAt = performance.now();\n eventing.firstModelRequestCheckpointAt = eventing.firstModelRequestPreparationStartedAt;\n }\n const providerDispatchStartedAt = performance.now();\n let providerDispatchOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n // This histogram describes worker preparation until the first entry\n // into the runtime. Lazy SDK request preparation and the durable\n // model-request audit happen after this boundary and have their own\n // phase metrics. Context-compaction recovery re-enters\n // runStreamAttempt; recording again would fold the prior request and\n // compaction into a bogus second startup sample.\n if (!workerPreparationTotalRecorded) {\n workerPreparationTotalRecorded = true;\n recordTurnWorkerPreparationTotal(observability, {\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - workerPreparationStartedAt) / 1_000,\n });\n }\n attempt.modelRequestStarted = true;\n return await runtime.runStream(agent, runInput!, eventing.modelRunSettings, {\n signal: runtimeCancellationSignal,\n sandboxEnvironment,\n onModelVisibleContext: async (snapshot) => {\n await persistModelContextSnapshot(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n snapshot,\n });\n },\n onRuntimeEvent: async (event) => {\n await leases.renewServing(\"runtime_event\");\n if (leases.servingLost()) {\n throw new Error(\"Provider credential lease expired during the active turn\");\n }\n await eventing.publish!([{ type: event.type, payload: event.payload }], true);\n },\n // P1.2: inject the resumed box NON-OWNED (the SDK never reaps it — the\n // keystone). Absent when the flag is off -> legacy build-and-discard.\n ...(ownedEstablished\n ? {\n ownedSandbox: {\n client: ownedEstablished.client,\n session: ownedEstablished.session,\n ...(sandboxState.resolvedSandbox?.established.sessionState\n ? {\n sessionState: sandboxState.resolvedSandbox.established.sessionState,\n }\n : {}),\n // Pin platform setup (hooks + file materialization) to the un-proxied\n // established box — never through the routing proxy, which would\n // re-route those execs onto a machine swapped in mid-turn.\n ...(sandboxState.setupBoxSession\n ? { setupSession: sandboxState.setupBoxSession }\n : {}),\n ...(fileDownloadsMaterializedForRun ? { fileDownloadsMaterialized: true } : {}),\n // Both owned paths execute setup outside runStream: eager just\n // above under its exact admission, lazy in the provisioner.\n deferredSetup: true,\n },\n }\n : {}),\n ...(activeSandboxBackend !== \"selfhosted\" &&\n sandboxCodemodeToken &&\n sandboxCodemodeTokenExpiresAt &&\n !sandboxState.lazyOwnedSandbox\n ? {\n onCodemodeTokenSessionReady: async (tokenSession: CodemodeTokenWriterSession) => {\n const renewalSession =\n (sandboxState.setupBoxSession as CodemodeTokenWriterSession | null) ??\n tokenSession;\n await attachCodemodeTokenRenewal(renewalSession);\n },\n }\n : {}),\n ...(runCredentialResolver\n ? {\n runCredentialSessionId: input.sessionId,\n ...(!sandboxState.lazyOwnedSandbox\n ? {\n onRunCredentialSessionReady: async (\n credentialSession: RunCredentialCommandSession,\n ) => {\n const pinnedCredentialSession = sandboxState.setupBoxSession\n ? (sandboxState.setupBoxSession as RunCredentialCommandSession)\n : credentialSession;\n await attachRunCredentialRenewal(\n pinnedCredentialSession,\n initialRunCredentialMaterial,\n );\n },\n }\n : {}),\n }\n : {}),\n ...(eventing.modelRunSettings.sandboxBackend !== \"none\"\n ? {\n onSandboxSessionReady: async (sandboxSession: CodemodeTokenWriterSession) => {\n media.sdkOwnedSandboxSession = sandboxSession;\n for (const receipt of media.generatedImageReceiptsCreatedThisTurn.values()) {\n await media.materializeGeneratedImageInOwnedSdkSession(receipt, sandboxSession);\n }\n await toolResultSpill.materializeDeferred();\n },\n }\n : {}),\n contextCompactionSignal: () => modelResponseContextSignal(modelResponseState),\n contextCompactionRequested: () =>\n isSessionCompactionRequested(db, input.workspaceId, input.sessionId),\n onModelPreparationPhase: (measurement) => {\n recordTurnStartupPhase(observability, {\n phase: `model_prepare_${measurement.phase}`,\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: measurement.outcome,\n durationSeconds: measurement.durationSeconds,\n ...(measurement.count === undefined ? {} : { count: measurement.count }),\n });\n },\n ...(!providerPublishesNativeRequestEvents\n ? {\n onModelTransportStarted: recordFallbackProviderDispatchAtWire,\n }\n : {}),\n ...(eventing.toolCancellationFenceRef.current\n ? {\n turnToolCancellationFence: eventing.toolCancellationFenceRef.current,\n }\n : {}),\n });\n } catch (error) {\n providerDispatchOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"provider_dispatch\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: providerDispatchOutcome,\n durationSeconds: (performance.now() - providerDispatchStartedAt) / 1_000,\n });\n }\n };\n if (billingState.isCodexTurn) {\n leases.codex.assertUsable();\n } else if (leases.codex.lost) {\n throw new Error(\"Codex credential lease expired before the model run\");\n }\n if (leases.xai.lost) {\n throw new Error(\"xAI credential lease expired before the model run\");\n }\n eventing.stream = await withProviderRequestContext(runStreamOnce);\n // Bounded provider label for the streaming SLIs — the resolved registry\n // provider id (or the built-in OpenAI/Azure provider), never a raw\n // user-supplied model string.\n const streamTiming = new StreamTimingMetrics(observability, {\n provider: streamProvider,\n });\n eventing.batcher = createRuntimeBatcher(\n async (events) => {\n await eventing.publish!(events);\n },\n {\n onFlush: ({ events, durationSeconds }) =>\n recordBatchFlush(observability, { events, durationSeconds }),\n },\n );\n\n const streamBootstrapStartedAt = performance.now();\n let streamBootstrapRecorded = false;\n const recordStreamBootstrap = (): void => {\n if (streamBootstrapRecorded) return;\n streamBootstrapRecorded = true;\n recordTurnStartupPhase(observability, {\n phase: \"stream_bootstrap\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - streamBootstrapStartedAt) / 1_000,\n count: turnTools.length,\n });\n };\n const settleFallbackProviderFirstByte = async (): Promise<void> => {\n if (fallbackProviderRequestStartedAt === null) return;\n const durationMs = Math.max(0, performance.now() - fallbackProviderRequestStartedAt);\n fallbackProviderRequestStartedAt = null;\n await eventing.publish!([\n {\n type: \"agent.model.request\",\n payload: {\n phase: \"first_byte\",\n provider: streamProvider,\n durationMs: Math.round(durationMs),\n turnId: activeTurnId,\n attemptId: input.attemptId,\n dispatchId,\n executionGeneration: attempt.executionGeneration,\n },\n },\n ]);\n };\n const iterator = eventing.stream.toStream()[Symbol.asyncIterator]();\n const closeStreamWaitAdmission = eventing.preparedTools?.inputWaitYield?.captureStreamClose();\n let streamDone = false;\n try {\n while (true) {\n const next = await nextStreamEvent(iterator, activityContext);\n recordStreamBootstrap();\n if (next.done) {\n streamDone = true;\n break;\n }\n await settleFallbackProviderFirstByte();\n let stableToolCallIdsToClear: string[] | null = null;\n let completedCurrentToolBatch = false;\n let retainedScreenshotMetadata: RetainedArtifactMetadata | null = null;\n let normalizedSdkEvents: ReturnType<typeof normalizeSdkEvent> | null = null;\n const generatedImage = generatedImageFromSdkEvent(next.value);\n if (isCompletedGeneratedImageSdkEvent(next.value) && !generatedImage) {\n throw new Error(\n \"Completed native image item could not cross the retained-artifact boundary\",\n );\n }\n const generatedImageReceipt = generatedImage\n ? await media.retainNativeGeneratedImage(generatedImage)\n : null;\n const responseResult = await processModelResponseTerminalEvent({\n event: next.value,\n state: modelResponseState,\n dispatchId: modelUsageDispatchId,\n settings,\n db,\n observability,\n publish: eventing.publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n provider: resolvedModel?.provider.id ?? settings.openaiProvider,\n providerApi: resolvedModel?.provider.api ?? \"responses\",\n model: turn.model,\n latencyMode: turnExecutionPolicy.latencyMode,\n metricProvider: streamProvider,\n externallyBilled: billingState.isExternallyBilledTurn,\n chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,\n countsTowardTokenCap: billingState.countsTowardTokenCap,\n servingCredentialId: providerTurn.effectiveCodexCredentialId,\n priorSessionCredentialId: providerTurn.priorSessionCodexCredentialId,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n renewLease: () => leases.renewServing(\"model_usage\"),\n leaseLost: leases.servingLost,\n leaseLostMessage: \"Provider credential lease expired during the active turn\",\n setLastInputTokens: setLastInputTokensFenced,\n contextContributions: eventing.companyBrainContextContributions,\n });\n assertModelResponseLatencyMode({\n event: next.value,\n requested: turnExecutionPolicy.latencyMode,\n model: turn.model,\n ...(resolvedModel?.provider.id ? { providerId: resolvedModel.provider.id } : {}),\n });\n if (responseResult.status === \"processed\") {\n if (\n !providerPublishesNativeRequestEvents &&\n fallbackProviderRequestLifecycleStartedAt !== null\n ) {\n const durationMs = Math.max(\n 0,\n performance.now() - fallbackProviderRequestLifecycleStartedAt,\n );\n fallbackProviderRequestLifecycleStartedAt = null;\n await eventing.publish!([\n {\n type: \"agent.model.request\",\n payload: {\n phase: \"completed\",\n provider: streamProvider,\n durationMs: Math.round(durationMs),\n turnId: activeTurnId,\n attemptId: input.attemptId,\n dispatchId,\n executionGeneration: attempt.executionGeneration,\n },\n },\n ]);\n attempt.providerRecoveryCount = 0;\n }\n const rawStreamHistory = (eventing.stream.state as { history?: unknown[] }).history;\n if (Array.isArray(rawStreamHistory)) {\n // The completed image item is normally retained from its own\n // run-item event above. Scan once at the terminal response as\n // a compatibility backstop before reconciliation can persist\n // provider bytes. Never rescan history for every token delta.\n await media.retainNativeGeneratedImagesFromHistory(\n rawStreamHistory as Array<Record<string, unknown>>,\n );\n }\n streamSawPerResponseUsage ||= responseResult.usageReported;\n currentToolBatchCallIds = new Set<string>();\n currentToolBatchCompletedCallIds = new Set<string>();\n await historySink.reconcileConversationTruth();\n turnLifecycleMetricsFor(observability).progress(attempt.turnId!);\n modelCheckpointMemoryCollector.schedule(observability);\n try {\n await ensureRunAllowed(\n settings,\n db,\n input.accountId,\n input.workspaceId,\n billingState.isExternallyBilledTurn,\n entitlements,\n billingState.chargesOpenGeniCredits,\n billingState.countsTowardTokenCap,\n );\n } catch (limitError) {\n // Capture the run state at the boundary so the budget valve in\n // the outer catch can end this segment gracefully with full\n // conversation context preserved for the post-top-up resume.\n let serializedRunState: string | null = null;\n try {\n serializedRunState = media.compactMediaRunState(\n String(eventing.stream.state.toString()),\n );\n } catch {\n serializedRunState = null;\n }\n throw new BudgetExhaustedError(\n limitError instanceof Error ? limitError.message : String(limitError),\n serializedRunState,\n );\n }\n }\n const durableSdkEvent = generatedImageReceipt\n ? compactGeneratedImageSdkEvent(next.value, generatedImageReceipt)\n : next.value;\n const pendingToolCall = pendingToolCallFromSdkEvent(durableSdkEvent);\n if (pendingToolCall) {\n const registered = await registerPendingSessionToolCall(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n modelToolOutputTruncationTokens:\n eventing.modelRunSettings.modelToolOutputTruncationTokens,\n callId: pendingToolCall.callId,\n callType: pendingToolCall.callType,\n callItem: pendingToolCall.callItem as Record<string, unknown>,\n });\n if (!registered.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while recording an in-flight tool call\",\n );\n }\n currentToolBatchCallIds.add(pendingToolCall.callId);\n if (toolCallProducesRetainableSessionImage(pendingToolCall.callName)) {\n media.retainedSessionImageCallIds.add(pendingToolCall.callId);\n }\n }\n const completedToolCall = completedToolCallFromSdkEvent(durableSdkEvent);\n if (completedToolCall) {\n retainedScreenshotMetadata =\n media.retainedScreenshotReceiptsByCallId.get(completedToolCall.callId) ?? null;\n const typedScreenshot = retainedScreenshotMetadata\n ? null\n : typedScreenshotFromSdkEvent(durableSdkEvent);\n if (\n !retainedScreenshotMetadata &&\n media.retainedSessionImageCallIds.has(completedToolCall.callId) &&\n sdkEventContainsInlineImage(durableSdkEvent) &&\n !typedScreenshot\n ) {\n retainedScreenshotMetadata = unavailableRetainedSessionImage({\n sessionId: input.sessionId,\n turnId: activeTurnId,\n attemptId: input.attemptId,\n toolCallId: completedToolCall.callId,\n toolOutputId: completedToolCall.callId,\n reason: \"unsupported\",\n });\n media.retainedScreenshotReceiptsByCallId.set(\n completedToolCall.callId,\n retainedScreenshotMetadata,\n );\n }\n if (\n !retainedScreenshotMetadata &&\n typedScreenshot &&\n typedScreenshot.callId === completedToolCall.callId &&\n media.retainedSessionImageCallIds.has(completedToolCall.callId)\n ) {\n // Install a compact deterministic fallback before database or\n // object-storage I/O. Unexpected retention failure can then\n // reconcile/serialize without leaking inline bytes.\n retainedScreenshotMetadata = unavailableRetainedSessionImage({\n sessionId: input.sessionId,\n turnId: activeTurnId,\n attemptId: input.attemptId,\n toolCallId: typedScreenshot.callId,\n toolOutputId: typedScreenshot.toolOutputId,\n reason: \"pending\",\n });\n media.retainedScreenshotReceiptsByCallId.set(\n completedToolCall.callId,\n retainedScreenshotMetadata,\n );\n retainedScreenshotMetadata = await retainComputerScreenshot({\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n attemptId: input.attemptId,\n output: typedScreenshot,\n });\n media.retainedScreenshotReceiptsByCallId.set(\n completedToolCall.callId,\n retainedScreenshotMetadata,\n );\n }\n normalizedSdkEvents = normalizeSdkEvent(\n durableSdkEvent as typeof next.value,\n retainedScreenshotMetadata\n ? {\n toolOutputOverride: retainedScreenshotMetadata,\n retainedOutputEvidence: retainedScreenshotMetadata.available\n ? retainedScreenshotMetadata\n : {\n available: false,\n reason: retainedScreenshotMetadata.reason,\n },\n }\n : {},\n );\n const normalizedToolOutput = normalizedSdkEvents.find(\n (event) =>\n event.type === \"agent.toolCall.output\" &&\n (event.payload as { id?: unknown }).id === completedToolCall.callId,\n )?.payload as { output?: unknown } | undefined;\n if (!normalizedToolOutput || !Object.hasOwn(normalizedToolOutput, \"output\")) {\n throw new Error(\n `Completed SDK tool call ${completedToolCall.callId} produced no durable output projection`,\n );\n }\n const durableResultItem = retainedScreenshotMetadata\n ? (compactRetainedScreenshotHistory(\n [completedToolCall.resultItem],\n media.retainedScreenshotReceiptsByCallId,\n )[0] ?? completedToolCall.resultItem)\n : completedToolCall.resultItem;\n // Keep every parallel result in the attempt ledger until the full\n // call batch has settled. The SDK's computed history is\n // non-monotonic while parallel calls complete (a later call may\n // appear before an earlier persisted pair), so reconciling a\n // partial batch through a scalar watermark can create an orphan.\n const recorded = await recordPendingSessionToolCallResult(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n callId: completedToolCall.callId,\n modelToolOutputTruncationTokens:\n eventing.modelRunSettings.modelToolOutputTruncationTokens,\n resultItem: durableResultItem as Record<string, unknown>,\n eventOutput: normalizedToolOutput.output,\n ...(videoGenerationAcceptancesByCallId.has(completedToolCall.callId)\n ? {\n videoGenerationAcceptance: videoGenerationAcceptancesByCallId.get(\n completedToolCall.callId,\n )!,\n }\n : {}),\n });\n if (!recorded.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while recording a tool-call result\",\n );\n }\n const videoAcceptance = videoGenerationAcceptancesByCallId.get(completedToolCall.callId);\n if (videoAcceptance && startVideoGenerationWorkflow) {\n try {\n await startVideoGenerationWorkflow({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: videoAcceptance.operationId,\n });\n } catch (error) {\n // The accepted operation is durable. The recovery sweep starts\n // the same deterministic workflow ID if this nudge fails.\n observability.warn(\"Video generation workflow start deferred\", {\n operationId: videoAcceptance.operationId,\n errorClass: error instanceof Error ? error.name : \"UnknownError\",\n });\n }\n }\n const belongsToCurrentBatch = currentToolBatchCallIds.has(completedToolCall.callId);\n if (belongsToCurrentBatch) {\n currentToolBatchCompletedCallIds.add(completedToolCall.callId);\n }\n const currentBatchIsStable =\n belongsToCurrentBatch &&\n currentToolBatchCallIds.size > 0 &&\n currentToolBatchCompletedCallIds.size === currentToolBatchCallIds.size;\n const standaloneStableResult =\n !belongsToCurrentBatch && currentToolBatchCallIds.size === 0;\n if (currentBatchIsStable || standaloneStableResult) {\n // Persist the SDK's now-stable complete call/result batch. Keep\n // the receipts until the normalized tool-output event below is\n // durably flushed: recovery then covers every crash boundary\n // without either losing or duplicating the UI projection.\n await historySink.reconcileConversationTruth({ requireDurable: true });\n stableToolCallIdsToClear = currentBatchIsStable\n ? [...currentToolBatchCallIds]\n : [completedToolCall.callId];\n completedCurrentToolBatch = currentBatchIsStable;\n }\n }\n const normalized =\n normalizedSdkEvents ??\n normalizeSdkEvent(\n durableSdkEvent as typeof next.value,\n retainedScreenshotMetadata\n ? {\n toolOutputOverride: retainedScreenshotMetadata,\n retainedOutputEvidence: retainedScreenshotMetadata.available\n ? retainedScreenshotMetadata\n : {\n available: false,\n reason: retainedScreenshotMetadata.reason,\n },\n }\n : {},\n );\n for (const event of normalized) {\n streamTiming.onEvent(event.type);\n await eventing.batcher.push(event);\n }\n // Structural tool-output events await their durable append before\n // push returns. The complete result is now retained in the event\n // row and pending-call recovery receipt, so release only our\n // duplicate live SDK marker before a long turn accumulates it.\n releaseMcpResultCustomDataFromSdkEvent(durableSdkEvent);\n if (stableToolCallIdsToClear) {\n const cleared = await clearDurablePendingSessionToolCalls(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n callIds: stableToolCallIdsToClear,\n });\n if (!cleared.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while finalizing tool-call results\",\n );\n }\n if (completedCurrentToolBatch) {\n currentToolBatchCallIds = new Set<string>();\n currentToolBatchCompletedCallIds = new Set<string>();\n }\n for (const callId of stableToolCallIdsToClear) {\n media.retainedSessionImageCallIds.delete(callId);\n }\n }\n }\n } catch (error) {\n // Event processing can fail while SDK completion is still pending.\n // Close this stream before any failure publication; a legitimate\n // compaction retry may start a new, independently fenced generation.\n closeStreamWaitAdmission?.();\n if (fallbackProviderRequestLifecycleStartedAt !== null) {\n const durationMs = Math.max(\n 0,\n performance.now() - fallbackProviderRequestLifecycleStartedAt,\n );\n fallbackProviderRequestStartedAt = null;\n fallbackProviderRequestLifecycleStartedAt = null;\n await eventing.publish!([\n {\n type: \"agent.model.request\",\n payload: {\n phase: \"failed\",\n provider: streamProvider,\n durationMs: Math.round(durationMs),\n turnId: activeTurnId,\n attemptId: input.attemptId,\n dispatchId,\n executionGeneration: attempt.executionGeneration,\n },\n },\n ]);\n }\n if (\n !eventing.firstModelRequestPreparationRecorded &&\n eventing.firstModelRequestPreparationStartedAt !== null\n ) {\n eventing.firstModelRequestPreparationRecorded = true;\n const durationMs = Math.max(\n 0,\n performance.now() - eventing.firstModelRequestPreparationStartedAt,\n );\n recordTurnStartupPhase(observability, {\n phase: \"model_request_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"failed\",\n durationSeconds: durationMs / 1_000,\n count: turnTools.length,\n });\n await eventing.publish!([\n {\n type: \"turn.startup.phase.failed\",\n payload: {\n phase: \"model_preparation\",\n durationMs: Math.round(durationMs),\n },\n },\n ]);\n }\n throw error;\n } finally {\n if (!streamDone) {\n // ReadableStream cancellation synchronously trips the Agents SDK's\n // abort controller, but its returned promise may wait for an\n // uncooperative provider producer. Once this attempt is fenced,\n // awaiting that provider-side cleanup pins the Temporal activity\n // (and therefore Pause) even though every late write is already\n // rejected. Start cancellation and detach only its cleanup wait;\n // the SDK abort signal stops the producer and the durable attempt\n // fence remains the authority for every callback that arrives late.\n void iterator.return?.().catch(() => undefined);\n }\n }\n await assertSuccessfulAgentStreamCompletion({\n batcherFlush: eventing.batcher.flush(),\n stream: eventing.stream,\n temporalCancellationSignal: cancellationSignal,\n runtimeCancellationSignal,\n });\n // External Codemode stays reachable until finalization. Close wait\n // admission before any terminal output/history decision, and drain an\n // already-admitted wait before consulting the actual runner-yield latch.\n await eventing.preparedTools?.inputWaitYield?.sealForSettlement(runtimeCancellationSignal);\n if (\n options.requireTerminalModelResponse &&\n !eventing.preparedTools?.inputWaitYield?.yielded &&\n eventing.stream.interruptions.length === 0 &&\n modelResponseState.responseCount === responseCountBeforeStream\n ) {\n // A fresh post-compaction stream may be returned already cancelled by\n // the SDK/runtime without yielding an event or terminal response. That\n // is not a completed logical turn: accepting finalOutput's undefined ->\n // empty-string fallback would release the queue and start newer user\n // work. Cancellation retains priority; otherwise checkpoint and recover\n // this exact turn from the durable compacted history. An actual runtime\n // wait yield deliberately needs no subsequent provider response.\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n throw new PostCompactionContinuationEmptyError();\n }\n assertAgentStreamNotCancelled(eventing.stream.cancelled);\n if (!streamSawPerResponseUsage) {\n const aggregateUsage = eventing.stream.state.usage;\n const normalizedAggregateUsage = normalizeModelCallUsage(aggregateUsage);\n const aggregateInput = normalizedAggregateUsage.telemetry.inputTokens;\n const aggregateSourceKey = modelUsageSourceKey({\n responseId: null,\n dispatchId: modelUsageDispatchId,\n positionalKey: \"aggregate\",\n });\n if (!claimedModelUsageSourceKeys.has(aggregateSourceKey)) {\n claimedModelUsageSourceKeys.add(aggregateSourceKey);\n // The aggregate frame is only a billing fallback when no terminal\n // response exposed usage. It is not final-request context authority.\n const aggregateAccountCtx = modelCallAccountContext({\n servingCredentialId: providerTurn.effectiveCodexCredentialId,\n priorSessionCredentialId: providerTurn.priorSessionCodexCredentialId,\n isFirstCallOfTurn: true,\n });\n let aggregateAuthoritative = false;\n await recordCompletedModelCallBeforeOwnershipFences({\n renewLease: () => leases.renewServing(\"model_usage\"),\n leaseLost: leases.servingLost,\n leaseLostMessage: \"Provider credential lease expired during the active turn\",\n recordUsage: async () => {\n const billing = await recordModelUsageAndDebitCredits(settings, db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n model: turn.model,\n externallyBilled: billingState.isExternallyBilledTurn,\n chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,\n countsTowardTokenCap: billingState.countsTowardTokenCap,\n usage: aggregateUsage,\n normalizedUsage: normalizedAggregateUsage,\n sourceKey: aggregateSourceKey,\n latencyMode: turnExecutionPolicy.latencyMode,\n observability,\n });\n const aggregateProvider = resolvedModel?.provider.id ?? settings.openaiProvider;\n const aggregateProviderApi = resolvedModel?.provider.api ?? \"responses\";\n aggregateAuthoritative = await emitModelCallUsage({\n observability,\n publish: eventing.publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n provider: aggregateProvider,\n providerApi: aggregateProviderApi,\n model: turn.model,\n sourceKey: aggregateSourceKey,\n usage: { usage: aggregateUsage },\n normalizedUsage: normalizedAggregateUsage,\n ...(billing ? { billingPath: billing.billingPath } : {}),\n ...(billing?.upstreamProvider ? { upstreamProvider: billing.upstreamProvider } : {}),\n servingAccountHash: aggregateAccountCtx.servingAccountHash,\n accountChangedFromPrevCall: aggregateAccountCtx.accountChangedFromPrevCall,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n });\n if (aggregateAuthoritative && billing) {\n await recordAuthoritativeModelCallFact({\n db,\n observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n sourceKey: aggregateSourceKey,\n provider: aggregateProvider,\n providerApi: aggregateProviderApi,\n model: turn.model,\n billing,\n contextContributions: eventing.companyBrainContextContributions,\n });\n }\n if (aggregateAuthoritative && aggregateInput !== null && aggregateInput > 0) {\n recordModelInputTokens(observability, streamProvider, aggregateInput);\n }\n },\n recordAttemptSignals: async () => {\n if (!aggregateAuthoritative) return;\n // Stream aggregates can cover multiple requests and therefore\n // cannot identify the final request that compaction must bind.\n // They remain billing/telemetry fallback data only.\n modelResponseState.contextSignal = null;\n await setLastInputTokensFenced(null);\n },\n });\n }\n }\n if (eventing.stream.interruptions.length > 0) {\n await historySink.reconcileConversationTruth({ requireDurable: true });\n const approvals = runtime.serializeApprovals(eventing.stream.interruptions);\n const humanInputInterruptions =\n runtime.serializeHumanInputRequests?.(eventing.stream.interruptions) ?? [];\n const interactionInterventionInterruptions =\n runtime.serializeInteractionInterventionRequests?.(eventing.stream.interruptions) ?? [];\n const latestWorkspace = await getWorkspace(db, input.workspaceId);\n if (!latestWorkspace) throw new Error(`Workspace not found: ${input.workspaceId}`);\n assertWorkspaceHumanInputAllowed(\n resolveWorkspaceAgentHumanInputEnabled(latestWorkspace.settings),\n \"interruption\",\n humanInputInterruptions.length > 0,\n );\n const humanInputRequests = await Promise.all(\n humanInputInterruptions.map(async (interruption) => {\n const id = stableHumanInputRequestId(\n input.sessionId,\n activeTurnId,\n interruption.toolCallId,\n );\n const existing = await getSessionHumanInputRequest(\n db,\n input.workspaceId,\n input.sessionId,\n id,\n );\n if (existing && existing.status !== \"pending\") {\n throw new Error(`Settled human-input request ${id} reappeared as an interruption`);\n }\n const expiresAt = existing?.expiresAt\n ? new Date(existing.expiresAt)\n : interruption.input.expiresInSeconds\n ? new Date(Date.now() + interruption.input.expiresInSeconds * 1000)\n : null;\n return {\n id,\n toolCallId: interruption.toolCallId,\n questions: interruption.input.questions,\n allowSkip: interruption.input.allowSkip,\n expiresAt,\n isNew: existing === null,\n };\n }),\n );\n const requestEvents = humanInputRequests\n .filter((request) => request.isNew)\n .map((request) => ({\n type: \"session.humanInput.requested\" as const,\n payload: {\n request: {\n id: request.id,\n questions: request.questions,\n allowSkip: request.allowSkip,\n expiresAt: request.expiresAt?.toISOString() ?? null,\n },\n },\n }));\n const interactionInterventionRequests = interactionInterventionInterruptions.map(\n (interruption) => ({\n id: stableInteractionInterventionId(\n input.sessionId,\n activeTurnId,\n interruption.toolCallId,\n ),\n operationId: stableInteractionInterventionOperationId(\n input.sessionId,\n activeTurnId,\n interruption.toolCallId,\n ),\n toolCallId: interruption.toolCallId,\n input: interruption.input,\n }),\n );\n const pendingApprovals = [\n ...approvals,\n ...interactionInterventionInterruptions.map((interruption) => interruption.approval),\n ];\n const suffixMembers = extractOpenSuffixFromRunState(eventing.stream.state);\n const interruptionCallIds = interruptionCallIdsFromPause({\n humanInputRequests,\n interactionInterventionRequests,\n pendingApprovals,\n });\n assertOpenSuffixResumable(suffixMembers, interruptionCallIds);\n const suffixByCallId = new Map(suffixMembers.map((member) => [member.callId, member]));\n const attached = await attachOpenSuffixToPendingToolCalls(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n members: interruptionCallIds.map((callId) => {\n const member = suffixByCallId.get(callId)!;\n return {\n callId,\n interruptionKind: interruptionKindForCallItem(\n member.callItem as Record<string, unknown>,\n ),\n reasoningItems: member.reasoningItems as Array<Record<string, unknown>>,\n };\n }),\n });\n if (!attached.accepted) {\n return claimedResult({ status: \"cancelled\" });\n }\n await finishParallelSessionTitle();\n if (\n !(await eventing.settle!({\n events: [\n ...requestEvents,\n ...(approvals.length > 0\n ? [\n {\n type: \"session.requiresAction\" as const,\n payload: { approvals },\n },\n ]\n : []),\n {\n type: \"session.status.changed\",\n payload: { status: \"requires_action\" },\n },\n ],\n turnStatus: \"requires_action\",\n sessionStatus: \"requires_action\",\n activeTurnId,\n runState: {\n serializedRunState: OPEN_SUFFIX_RUN_STATE_BLOB,\n pendingApprovals,\n humanInputRequests: humanInputRequests.map(({ isNew: _isNew, ...request }) => request),\n interactionInterventionRequests,\n },\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n // The interruption and its preceding tool results are now durable.\n await finalizeTurnOpStreamOps();\n control.activityStatus = \"requires_action\";\n return claimedResult({ status: \"requires_action\" });\n }\n\n const inputWaitYielded = eventing.preparedTools?.inputWaitYield?.yielded === true;\n const finalOutput = String(\n requireAgentStreamFinalOutput(eventing.stream.finalOutput, inputWaitYielded),\n );\n await historySink.reconcileConversationTruth({ requireDurable: true });\n // Op-stream durability fence: the tool outputs are now durably in the\n // history store (a redispatch would NOT re-execute them), so this\n // turn's settled ops may advance their acked frontier — journal persist\n // then wire final ack (licensing the runner to GC its retained\n // frames). Best-effort: a miss leaves the runner's retention TTL to\n // reap, never fails a completed turn.\n await finalizeTurnOpStreamOps();\n await finishParallelSessionTitle();\n if (\n !(await eventing.settle!({\n events: [\n ...(inputWaitYielded\n ? []\n : [{ type: \"agent.message.completed\" as const, payload: { text: finalOutput } }]),\n { type: \"turn.completed\", payload: { output: finalOutput } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n control.turnMetricOutcome = \"completed\";\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"agent_run.completed\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"session_turn\",\n sourceResourceId: activeTurnId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n idempotencyKey: `usage:agent_run.completed:${activeTurnId}`,\n });\n control.activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n };\n\n const openSuffixResume = await settleOpenSuffixResumeIfNeeded({\n db,\n agent,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n trigger,\n humanInputResume,\n modelToolOutputTruncationTokens: eventing.modelRunSettings.modelToolOutputTruncationTokens,\n settle: eventing.settle!,\n publish: eventing.publish,\n });\n if (openSuffixResume.action === \"cancelled\") {\n return claimedResult({ status: \"cancelled\" });\n }\n if (openSuffixResume.action === \"requires_action\") {\n control.activityStatus = \"requires_action\";\n return claimedResult({ status: \"requires_action\" });\n }\n if (\n !(await attachPendingUpdatesBeforePreparingModelInput({\n shouldAttach:\n trigger.type === \"user.approvalDecision\" || trigger.type === \"user.humanInputResponse\",\n attachPendingUpdates: attachPendingUpdatesAfterOpenSuffix,\n prepareModelInput: prepareRunAttemptInput,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n if (\n generateSessionTitleInParallel &&\n runtime.generateSessionTitle &&\n !runtimeCancellationSignal.aborted\n ) {\n const serviceTier = serviceTierForLatencyMode(\n turnExecutionPolicy.providerId,\n turnExecutionPolicy.latencyMode,\n );\n parallelSessionTitle = startParallelSessionTitleGeneration({\n signal: runtimeCancellationSignal,\n generate: async (signal) =>\n await withSessionTitleProviderRequestContext(() =>\n runtime.generateSessionTitle!(runSettings, sessionTitlePrompt, {\n ...(resolvedModel\n ? {\n client: resolvedModel.client,\n provider: resolvedModel.provider,\n model: resolvedModel.model,\n }\n : {}),\n modelName: turnExecutionPolicy.upstreamModelId,\n ...(serviceTier ? { serviceTier } : {}),\n signal,\n }),\n ),\n onError: (error) => {\n observability.warn(\"parallel session title generation failed\", {\n ...safeErrorDiagnostic(error),\n errorClass: \"ParallelSessionTitleGenerationError\",\n errorCode: \"parallel_session_title_generation_failed\",\n origin: \"worker\",\n });\n },\n });\n }\n try {\n let retriedAfterCompaction = false;\n while (true) {\n try {\n const result = await runStreamAttempt({\n requireTerminalModelResponse: retriedAfterCompaction,\n });\n if (retriedAfterCompaction) {\n observability.info(\"context compaction recovery succeeded after in-activity retry\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n });\n }\n return result;\n } catch (attemptError) {\n const overflow = classifyContextWindowOverflowError(attemptError);\n const compactionNeeded = findCompactionNeededError(attemptError);\n const recoveryKind = compactionNeeded\n ? compactionNeeded.trigger === \"operator\"\n ? \"operator\"\n : \"proactive\"\n : overflow\n ? \"overflow\"\n : null;\n if (!recoveryKind || !eventing.publish || !eventing.turnStartedPublished) {\n throw attemptError;\n }\n await flushRuntimeBatcher();\n await historySink.reconcileConversationTruth({ skipInputOnlyRows: true });\n observability.warn(\"context compaction recovery attempted\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n ...safeErrorDiagnostic(attemptError),\n signalTokens: compactionNeeded?.signalTokens,\n thresholdTokens: compactionNeeded?.thresholdTokens,\n });\n let compacted = false;\n let compactionHandled = false;\n let compactionFailureMessage: string | null = null;\n let compactionRequestCleared = false;\n try {\n const outcome = await forceContextCompaction(\n recoveryKind,\n compactionNeeded?.signalTokens ?? null,\n );\n compacted = outcome.compacted;\n if (outcome.compacted) {\n compactionHandled = true;\n } else {\n compactionHandled = recoveryKind === \"operator\" && outcome.requestConsumed;\n if (!compactionHandled) {\n compactionFailureMessage = compactionFailureReason(outcome.reason);\n }\n }\n } catch (compactError) {\n // Transient checkpoint-provider failures recover this same accepted\n // turn through the normal provider/capacity path. They are not an\n // empty summary and must not create a new goal continuation.\n if (shouldRecoverCompactionProviderFailure(compactError)) throw compactError;\n if (compactError instanceof TurnAttemptFencedError) throw compactError;\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId!,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: recoveryKind === \"operator\",\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n compactionRequestCleared = landmark.requestConsumed;\n if (!isCompactionSummaryFailure(compactError)) throw compactError;\n await finishParallelSessionTitle();\n const deferredSteer = await settleDeferredSteerAfterCompaction();\n if (deferredSteer) return deferredSteer;\n compactionFailureMessage = String(compactionFailureReasonFromError(compactError));\n observability.warn(\"context compaction recovery compaction failed\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n ...safeErrorDiagnostic(compactError),\n });\n }\n if (!compactionHandled) {\n const errorMessage =\n compactionFailureMessage ??\n \"compaction summarization failed: compaction produced no replacement history\";\n await finishParallelSessionTitle();\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(recoveryKind === \"operator\" && !compactionRequestCleared\n ? { consumeRequestedCompactionFailure: true }\n : {}),\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n control.turnMetricOutcome = \"failed\";\n control.activityStatus = \"idle\";\n control.activityError = attemptError;\n // The failed turn settlement already defers ordinary internal\n // updates and makes the delivered goal-continuation receipt\n // terminal. End this workflow run as well: returning plain idle\n // would immediately synthesize another goal continuation against\n // the unchanged active history and repeat the same failed\n // compaction. A new human/API prompt, Steer, or explicitly requested\n // Compact remains a durable explicit wake and may retry; ordinary\n // machine updates stay pending for that actionable wake.\n return claimedResult({ status: \"idle\", deferredUntilWake: true });\n }\n await finishParallelSessionTitle();\n const deferredSteer = await settleDeferredSteerAfterCompaction();\n if (deferredSteer) return deferredSteer;\n // Codex parity: compaction remains inside the same logical turn and\n // the same activity. Rebuild the model-visible history from the\n // durable replacement and continue the sampling loop; do not create\n // a recovery event, a queue row, a fake user message, or a sandbox.\n retriedAfterCompaction = true;\n observability.info(\"context compaction recovery retrying turn after compaction\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n compacted,\n });\n await prepareRunAttemptInput();\n }\n }\n } finally {\n await cancelParallelSessionTitle();\n }\n}\n","import {\n applyContextCompaction,\n getActiveSessionHistoryItemsPaged,\n recordSkippedContextCompaction,\n recordStartedContextCompaction,\n type Database,\n} from \"@opengeni/db\";\nimport {\n EmptyCompactionSummaryError,\n REMOTE_COMPACTION_V2_IMPLEMENTATION,\n SUMMARY_BUFFER_TOKENS,\n buildCompactionReplacementHistory,\n buildRemoteV2ReplacementHistory,\n compactionThresholdTokens,\n compactionReplacementFingerprint,\n decideCompaction,\n estimateTokens,\n latestCompactionReplacementFingerprint,\n prepareCompactionPromptInput,\n projectRemoteCompactionOverflowRetryInput,\n sanitizeHistoryItemsForModel,\n summarizeForCompaction,\n type CompactionItem,\n} from \"@opengeni/runtime\";\nimport { contextInputBudgetTokens, type Settings } from \"@opengeni/config\";\nimport type { SessionEvent } from \"@opengeni/contracts\";\nimport { projectRejectedProviderArtifacts } from \"./run-input\";\nimport { TurnAttemptFencedError } from \"./turn-attempt-fenced\";\n\nexport type MaybeCompactResult =\n | {\n compacted: false;\n reason: string;\n events: SessionEvent[];\n requestConsumed: boolean;\n }\n | {\n compacted: true;\n supersededFrom: number;\n summaryPosition: number;\n signalTokens: number;\n thresholdTokens: number;\n estimatedTokensBefore: number;\n estimatedTokensAfter: number;\n replacementFingerprint: string;\n events: SessionEvent[];\n };\n\n/**\n * Durable context compaction.\n *\n * Portable path: Codex CLI local plaintext checkpoint for every provider and\n * for Codex sessions frozen on `portable`.\n *\n * Remote v2 path: when the session is frozen on `remote_v2` and the turn is\n * Codex, call Codex `/codex/responses` with `compaction_trigger` and persist the\n * opaque compaction item. Fail closed — never silently fall back to portable.\n */\nexport type CompactionSummarizer = (settings: Settings, input: CompactionItem[]) => Promise<string>;\n\n/** Returns the opaque Codex remote compaction v2 item. */\nexport type RemoteCompactionV2Requester = (\n settings: Settings,\n input: CompactionItem[],\n) => Promise<CompactionItem>;\n\nexport async function maybeCompactContext(\n db: Database,\n settings: Settings,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n lastInputTokens: number | null,\n // Injectable for tests; defaults to the real provider-aware model call.\n summarize: CompactionSummarizer = (s, m) =>\n summarizeForCompaction(s, m, {\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n }),\n // Operator-forced (the /compact command): bypass the budget trigger and\n // compact now if there is anything to summarize. Structural guards still hold.\n options: {\n force?: boolean;\n clearRequestedCompaction?: boolean;\n trigger?: \"auto\" | \"operator\" | \"proactive\" | \"overflow\";\n /** Frozen session mode; remote_v2 selects the Codex opaque path. */\n codexCompactionMode?: \"remote_v2\" | \"portable\";\n /** True when this turn's resolved provider is codex-subscription. */\n isCodexSubscriptionTurn?: boolean;\n /** Injected remote requester; required for the remote_v2 branch. */\n requestRemoteCompactionV2?: RemoteCompactionV2Requester;\n /**\n * Live fanout for the attempt-fenced `compaction.started` event so the\n * timeline can show progress before the provider call returns. Must never\n * append again — the event is already durable.\n */\n publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;\n /** Observe the durable start immediately after its attempt-fenced commit. */\n onCompactionStarted?: (trigger: \"auto\" | \"operator\" | \"proactive\" | \"overflow\") => void;\n /** Materialize retained screenshot receipts only in the attempt-local model view. */\n materializeHistory?: (items: CompactionItem[]) => Promise<CompactionItem[]>;\n /** Turn-scoped attachment/modality view; canonical persisted rows stay untouched. */\n projectModelInput?: (items: CompactionItem[]) => Promise<CompactionItem[]>;\n } = {},\n): Promise<MaybeCompactResult> {\n if (options.codexCompactionMode === \"remote_v2\" && options.isCodexSubscriptionTurn !== true) {\n // Fail closed: a V2-locked session must never silently take the portable path\n // (mixed history shapes). Admission should have blocked this already.\n throw new Error(\n \"session is locked to Codex remote compaction v2 but this turn is not a Codex subscription turn\",\n );\n }\n const useRemoteV2 = options.codexCompactionMode === \"remote_v2\";\n\n // An automatic check below the provider-accounted threshold cannot compact.\n // Avoid loading and projecting the same complete history that the ordinary\n // model-input path will load immediately afterward. Operator requests still\n // load history so their durable requested/skipped semantics stay unchanged.\n if (!options.force && !options.clearRequestedCompaction) {\n const providerInputTokens =\n typeof lastInputTokens === \"number\" && lastInputTokens > 0 ? lastInputTokens : 0;\n if (providerInputTokens < compactionThresholdTokens(settings)) {\n return {\n compacted: false,\n reason: \"below_threshold\",\n events: [],\n requestConsumed: false,\n };\n }\n }\n\n // Preserve the complete ordered transcript while bounding each Postgres\n // driver result frame beside the decoded history already held by this turn.\n const active = await getActiveSessionHistoryItemsPaged(db, scope.workspaceId, scope.sessionId);\n if (active.length === 0) {\n let requestConsumed = false;\n if (options.clearRequestedCompaction) {\n const skipped = await recordSkippedContextCompaction(db, {\n ...scope,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n reason: \"no_history\",\n });\n if (!skipped.recorded) {\n throw new TurnAttemptFencedError(\n \"turn attempt was fenced while consuming an empty context compaction request\",\n );\n }\n requestConsumed = true;\n return {\n compacted: false,\n reason: \"no_history\",\n events: skipped.events,\n requestConsumed,\n };\n }\n return {\n compacted: false,\n reason: \"no_history\",\n events: [],\n requestConsumed,\n };\n }\n\n const canonicalItems = projectRejectedProviderArtifacts(active) as CompactionItem[];\n const projectForWire = async (input: CompactionItem[]): Promise<CompactionItem[]> => {\n const materialized = options.materializeHistory\n ? await options.materializeHistory(input)\n : input;\n return sanitizeHistoryItemsForModel(\n options.projectModelInput ? await options.projectModelInput(materialized) : materialized,\n settings.modelToolOutputTruncationTokens,\n ) as CompactionItem[];\n };\n const items = await projectForWire(canonicalItems);\n const decision = decideCompaction({\n items,\n lastInputTokens,\n contextWindowTokens: settings.contextWindowTokens,\n contextReservedOutputTokens: settings.contextReservedOutputTokens,\n contextAutoCompactThresholdTokens: settings.contextAutoCompactThresholdTokens,\n contextCompactionThresholdRatio: settings.contextCompactionThresholdRatio,\n ...(options.force ? { force: true } : {}),\n });\n if (!decision.shouldCompact) {\n return {\n compacted: false,\n reason: decision.reason,\n events: [],\n requestConsumed: false,\n };\n }\n\n const trigger = options.trigger ?? \"auto\";\n const estimatedTokensBefore = estimateTokens(items);\n const started = await recordStartedContextCompaction(db, {\n ...scope,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n trigger,\n estimatedTokensBefore,\n ...(useRemoteV2 ? { implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION } : {}),\n });\n if (!started.recorded) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced while recording context compaction start: ${started.reason}`,\n );\n }\n options.onCompactionStarted?.(trigger);\n await options.publishLiveEvents?.(started.events);\n\n if (useRemoteV2) {\n const outcome = await compactContextRemoteV2(\n db,\n settings,\n scope,\n canonicalItems,\n items,\n decision,\n options,\n projectForWire,\n );\n return prependCompactionEvents(started.events, outcome);\n }\n\n const outcome = await compactContextPortable(\n db,\n settings,\n scope,\n canonicalItems,\n items,\n decision,\n summarize,\n options,\n projectForWire,\n );\n return prependCompactionEvents(started.events, outcome);\n}\n\n/**\n * After `compaction.started`, record a visible skip so the timeline cannot\n * stick on \"Compacting…\". Used when the provider/summarizer throws a terminal\n * (non-retryable) failure — including auto/overflow paths that never set\n * `compactRequested`.\n */\nexport async function settleFailedContextCompactionLandmark(\n db: Database,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n options: {\n clearRequestedCompaction?: boolean;\n publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;\n } = {},\n): Promise<Extract<MaybeCompactResult, { compacted: false }>> {\n const settled = await settleSkippedAfterStart(db, scope, options, \"summarization_failed\");\n await options.publishLiveEvents?.(settled.events);\n return settled;\n}\n\nfunction prependCompactionEvents(\n prefix: SessionEvent[],\n outcome: MaybeCompactResult,\n): MaybeCompactResult {\n if (prefix.length === 0) return outcome;\n return { ...outcome, events: [...prefix, ...outcome.events] };\n}\n\nasync function settleSkippedAfterStart(\n db: Database,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n options: {\n clearRequestedCompaction?: boolean;\n },\n reason:\n | \"no_history\"\n | \"replacement_not_smaller\"\n | \"replacement_unchanged\"\n | \"summarization_failed\",\n): Promise<Extract<MaybeCompactResult, { compacted: false }>> {\n const clearRequestedCompaction = options.clearRequestedCompaction === true;\n const skipped = await recordSkippedContextCompaction(db, {\n ...scope,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n reason,\n // After `compaction.started`, always settle the landmark. Do not require\n // an operator `/compact` flag — auto/overflow never set one.\n requirePendingRequest: false,\n clearRequestedCompaction,\n });\n if (!skipped.recorded) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced while recording a context compaction skip (${reason}): ${skipped.reason}`,\n );\n }\n return {\n compacted: false,\n reason,\n events: skipped.events,\n requestConsumed: clearRequestedCompaction,\n };\n}\n\nasync function compactContextRemoteV2(\n db: Database,\n settings: Settings,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n canonicalItems: CompactionItem[],\n items: CompactionItem[],\n decision: { signalTokens: number; thresholdTokens: number },\n options: {\n clearRequestedCompaction?: boolean;\n trigger?: \"auto\" | \"operator\" | \"proactive\" | \"overflow\";\n requestRemoteCompactionV2?: RemoteCompactionV2Requester;\n },\n projectForWire: (items: CompactionItem[]) => Promise<CompactionItem[]>,\n): Promise<MaybeCompactResult> {\n if (!options.requestRemoteCompactionV2) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_requester\",\n reason: \"missing_requester\",\n });\n }\n const estimatedTokensBefore = estimateTokens(items);\n // Codex remote_v2: on a valid compaction item, install and recompute usage.\n // No local \"must shrink / must differ\" gate — that is portable-only.\n // Fail closed on provider/extract failure — no portable fallback.\n let providerCalls = 1;\n let rewrittenToolOutputs = 0;\n let compactionItem: CompactionItem;\n try {\n compactionItem = await options.requestRemoteCompactionV2(settings, items);\n } catch (error) {\n if (!isExactContextLengthExceeded(error)) throw error;\n const retry = projectRemoteCompactionOverflowRetryInput(items);\n if (retry.rewrittenToolOutputs === 0) throw error;\n providerCalls = 2;\n rewrittenToolOutputs = retry.rewrittenToolOutputs;\n compactionItem = await options.requestRemoteCompactionV2(settings, retry.input);\n }\n const retainedTokens = await retentionTokenCounts(canonicalItems, projectForWire);\n const replacementHistory = buildRemoteV2ReplacementHistory(\n canonicalItems,\n compactionItem,\n (item) => retainedTokens.get(item) ?? estimateTokens([item]),\n );\n const estimatedTokensAfter = estimateTokens(await projectForWire(replacementHistory));\n const replacementFingerprint = compactionReplacementFingerprint(replacementHistory);\n const tailItem = replacementHistory.at(-1);\n if (!tailItem) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_replacement\",\n reason: \"no_replacement_history\",\n });\n }\n const applied = await applyContextCompaction(db, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n sessionId: scope.sessionId,\n turnId: scope.turnId,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n replacementItems: replacementHistory.slice(0, -1),\n summaryItem: tailItem as Record<string, unknown>,\n ...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),\n eventPayload: {\n trigger: options.trigger ?? \"auto\",\n implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION,\n estimatedTokensBefore,\n estimatedTokensAfter,\n compactionInputToolOutputsRewritten: rewrittenToolOutputs,\n compactionInputProviderCalls: providerCalls,\n },\n });\n if (!applied.applied) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced during remote context compaction: ${applied.reason}`,\n );\n }\n return {\n compacted: true,\n supersededFrom: applied.supersededFrom,\n summaryPosition: applied.summaryPosition,\n signalTokens: decision.signalTokens,\n thresholdTokens: decision.thresholdTokens,\n estimatedTokensBefore,\n estimatedTokensAfter,\n replacementFingerprint,\n events: applied.events,\n };\n}\n\nasync function compactContextPortable(\n db: Database,\n settings: Settings,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n canonicalItems: CompactionItem[],\n items: CompactionItem[],\n decision: { signalTokens: number; thresholdTokens: number },\n summarize: CompactionSummarizer,\n options: {\n clearRequestedCompaction?: boolean;\n trigger?: \"auto\" | \"operator\" | \"proactive\" | \"overflow\";\n },\n projectForWire: (items: CompactionItem[]) => Promise<CompactionItem[]>,\n): Promise<MaybeCompactResult> {\n const estimatedTokensBefore = estimateTokens(items);\n const summarized = await summarizeWithCodexOverflowTrimming(summarize, settings, items);\n const summaryBody = summarized.summaryBody;\n const retainedTokens = await retentionTokenCounts(canonicalItems, projectForWire);\n const replacementHistory = buildCompactionReplacementHistory(\n canonicalItems,\n summaryBody,\n (item) => retainedTokens.get(item) ?? estimateTokens([item]),\n );\n const estimatedTokensAfter = estimateTokens(await projectForWire(replacementHistory));\n const replacementFingerprint = compactionReplacementFingerprint(replacementHistory);\n const previousReplacementFingerprint = latestCompactionReplacementFingerprint(canonicalItems);\n const summaryItem = replacementHistory.at(-1);\n if (!summaryItem) {\n // Started already fanout; settle visibly so the landmark cannot stick on\n // \"Compacting…\". This is not an operator-request clear path.\n return await settleSkippedAfterStart(db, scope, options, \"summarization_failed\");\n }\n if (previousReplacementFingerprint === replacementFingerprint) {\n return await settleSkippedAfterStart(db, scope, options, \"replacement_unchanged\");\n }\n if (estimatedTokensAfter >= estimatedTokensBefore) {\n return await settleSkippedAfterStart(db, scope, options, \"replacement_not_smaller\");\n }\n const applied = await applyContextCompaction(db, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n sessionId: scope.sessionId,\n turnId: scope.turnId,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n replacementItems: replacementHistory.slice(0, -1),\n summaryItem: summaryItem as Record<string, unknown>,\n ...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),\n eventPayload: {\n trigger: options.trigger ?? \"auto\",\n estimatedTokensBefore,\n estimatedTokensAfter,\n compactionInputEstimatedTokens: summarized.preparation.estimatedInputTokens,\n compactionInputToolOutputsRewritten: summarized.preparation.rewrittenToolOutputs,\n compactionInputHistoryItemsDropped: summarized.preparation.droppedHistoryItems,\n compactionInputProviderCalls: summarized.providerCalls,\n },\n });\n if (!applied.applied) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced during context compaction: ${applied.reason}`,\n );\n }\n\n return {\n compacted: true,\n supersededFrom: applied.supersededFrom,\n summaryPosition: applied.summaryPosition,\n signalTokens: decision.signalTokens,\n thresholdTokens: decision.thresholdTokens,\n estimatedTokensBefore,\n estimatedTokensAfter,\n replacementFingerprint,\n events: applied.events,\n };\n}\n\nasync function summarizeWithCodexOverflowTrimming(\n summarize: CompactionSummarizer,\n settings: Settings,\n activeHistory: CompactionItem[],\n): Promise<{\n summaryBody: string;\n preparation: ReturnType<typeof prepareCompactionPromptInput>;\n providerCalls: number;\n}> {\n // Codex's estimator is intentionally coarse. Keep the explicit checkpoint\n // request below both the effective input window and the raw window minus the\n // requested summary, then leave 15% estimator headroom. This changes only the\n // temporary summarizer input; durable active history remains untouched until\n // applyContextCompaction succeeds under the attempt fence.\n const summaryAwareBudget = Math.max(0, settings.contextWindowTokens - SUMMARY_BUFFER_TOKENS);\n const configuredInputBudget = contextInputBudgetTokens(settings);\n const structuralBudget = Math.min(\n configuredInputBudget > 0 ? configuredInputBudget : summaryAwareBudget,\n summaryAwareBudget,\n );\n const initialBudget = Math.floor(structuralBudget * 0.85);\n let preparation = prepareCompactionPromptInput(activeHistory, initialBudget);\n try {\n return {\n summaryBody: await summarize(settings, preparation.input),\n preparation,\n providerCalls: 1,\n };\n } catch (error) {\n if (!isContextWindowExceeded(error)) throw error;\n // The provider is more authoritative than the byte/4 estimate. Refit once\n // to 70% of both the configured target and the actual prepared estimate;\n // then fail terminally with prior history intact. Never issue one failing\n // request per oldest item. The production incident proved that the\n // provider can count slightly more than twice the byte/4 estimate, so a\n // half-size retry is the smallest honest bound for that observed skew.\n const retryBudget = Math.floor(\n Math.min(initialBudget * 0.5, preparation.estimatedInputTokens * 0.5),\n );\n preparation = prepareCompactionPromptInput(activeHistory, retryBudget);\n return {\n summaryBody: await summarize(settings, preparation.input),\n preparation,\n providerCalls: 2,\n };\n }\n}\n\nexport function isContextWindowExceeded(error: unknown, seen = new WeakSet<object>()): boolean {\n if (!error || typeof error !== \"object\") return false;\n if (seen.has(error)) return false;\n seen.add(error);\n const record = error as Record<string, unknown>;\n const code = typeof record.code === \"string\" ? record.code.toLowerCase() : \"\";\n const message =\n typeof record.message === \"string\"\n ? record.message.toLowerCase()\n : error instanceof Error\n ? error.message.toLowerCase()\n : \"\";\n const direct =\n code === \"context_length_exceeded\" ||\n code === \"context_window_exceeded\" ||\n message.includes(\"context window\") ||\n message.includes(\"maximum context length\") ||\n message.includes(\"too many tokens\");\n return (\n direct ||\n isContextWindowExceeded(record.cause, seen) ||\n isContextWindowExceeded(record.error, seen) ||\n isContextWindowExceeded(record.diagnostics, seen)\n );\n}\n\nexport function isExactContextLengthExceeded(\n error: unknown,\n seen = new WeakSet<object>(),\n): boolean {\n if (!error || typeof error !== \"object\") return false;\n if (seen.has(error)) return false;\n seen.add(error);\n const record = error as Record<string, unknown>;\n if (record.code === \"context_length_exceeded\") {\n return true;\n }\n return (\n isExactContextLengthExceeded(record.cause, seen) ||\n isExactContextLengthExceeded(record.error, seen) ||\n isExactContextLengthExceeded(record.diagnostics, seen)\n );\n}\n\n/** Charge retained uploads by their projected image context, not reference text. */\nasync function retentionTokenCounts(\n items: CompactionItem[],\n project: (items: CompactionItem[]) => Promise<CompactionItem[]>,\n): Promise<Map<CompactionItem, number>> {\n const counts = new Map<CompactionItem, number>();\n for (const item of items) {\n if (item.role === \"user\" || item.role === \"developer\") {\n counts.set(item, estimateTokens(await project([item])));\n }\n }\n return counts;\n}\n","import type { Agent } from \"@openai/agents\";\nimport {\n OPEN_SUFFIX_RUN_STATE_BLOB,\n approvalIdentifier,\n type HumanInputResponse,\n type SessionEvent,\n} from \"@opengeni/contracts\";\nimport {\n appendSessionHistoryItems,\n getActiveSessionHistoryItems,\n interruptedToolCallResult,\n listTurnOpenSuffixToolCalls,\n nextSessionHistoryPosition,\n recordPendingSessionToolCallResult,\n type Database,\n type OpenSuffixPendingToolCall,\n} from \"@opengeni/db\";\nimport {\n functionCallResultItem,\n invokePreparedAgentTool,\n sanitizeHistoryItemsForModel,\n} from \"@opengeni/runtime\";\n\nexport type OpenSuffixResumeOutcome =\n | { action: \"continue\" }\n | { action: \"requires_action\" }\n | { action: \"cancelled\" };\n\ntype OpenSuffixSettle = (input: {\n events: Array<\n | { type: \"session.requiresAction\"; payload: { approvals: unknown[] } }\n | { type: \"session.status.changed\"; payload: { status: \"requires_action\" } }\n >;\n turnStatus: \"requires_action\";\n sessionStatus: \"requires_action\";\n activeTurnId: string;\n runState: {\n serializedRunState: string;\n pendingApprovals: unknown[];\n };\n}) => Promise<boolean>;\n\nfunction argumentsJsonFromCallItem(callItem: Record<string, unknown>): string {\n const raw = callItem.arguments;\n if (typeof raw === \"string\") {\n return raw;\n }\n return JSON.stringify(raw ?? {});\n}\n\nfunction toolNameFromCallItem(callItem: Record<string, unknown>): string {\n return typeof callItem.name === \"string\" && callItem.name.length > 0 ? callItem.name : \"tool\";\n}\n\nfunction pendingApprovalProjection(row: OpenSuffixPendingToolCall): unknown {\n return {\n id: row.callId,\n name: toolNameFromCallItem(row.callItem),\n arguments: row.callItem.arguments ?? null,\n raw: row.callItem,\n };\n}\n\nfunction remainingSuffixApprovals(\n rows: readonly OpenSuffixPendingToolCall[],\n kinds: ReadonlySet<OpenSuffixPendingToolCall[\"interruptionKind\"]>,\n): unknown[] {\n return rows\n .filter((row) => row.resultItem == null && kinds.has(row.interruptionKind))\n .map(pendingApprovalProjection);\n}\n\n/** Matches the original pause `session.requiresAction` payload: ordinary approvals only. */\nexport function remainingPendingApprovalsFromSuffix(\n rows: readonly OpenSuffixPendingToolCall[],\n): unknown[] {\n return remainingSuffixApprovals(rows, new Set([\"approval\"]));\n}\n\n/** Leftover `pendingApprovals` snapshot includes interaction interventions. */\nexport function remainingRunStatePendingApprovalsFromSuffix(\n rows: readonly OpenSuffixPendingToolCall[],\n): unknown[] {\n return remainingSuffixApprovals(rows, new Set([\"approval\", \"interaction_intervention\"]));\n}\n\nexport function openSuffixHistoryItems(\n row: OpenSuffixPendingToolCall,\n resultItem: Record<string, unknown>,\n): Record<string, unknown>[] {\n return sanitizeHistoryItemsForModel([\n ...row.tiedReasoningItems,\n row.callItem,\n resultItem,\n ]) as Record<string, unknown>[];\n}\n\nexport function matchingOpenSuffixCallId(input: {\n trigger: Pick<SessionEvent, \"type\" | \"payload\">;\n humanInputToolCallId?: string | undefined;\n}): string | null {\n if (input.trigger.type === \"user.humanInputResponse\") {\n return input.humanInputToolCallId ?? null;\n }\n if (input.trigger.type === \"user.approvalDecision\") {\n const payload = input.trigger.payload as { approvalId?: unknown };\n return typeof payload.approvalId === \"string\" ? payload.approvalId : null;\n }\n return null;\n}\n\nfunction historyItemCallId(item: Record<string, unknown>): string | null {\n const value = item.callId ?? item.call_id ?? item.id;\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nexport function resolveOpenSuffixResumeTarget(\n rows: readonly OpenSuffixPendingToolCall[],\n callId: string | null,\n): OpenSuffixPendingToolCall | null {\n if (!callId) {\n return null;\n }\n return rows.find((row) => row.callId === callId) ?? null;\n}\n\n/** True when the paired call and result already exist in durable history. */\nexport function openSuffixPairPresentInHistory(\n items: readonly Record<string, unknown>[],\n callId: string,\n): boolean {\n let sawCall = false;\n for (const item of items) {\n if (historyItemCallId(item) !== callId) {\n continue;\n }\n const type = typeof item.type === \"string\" ? item.type : null;\n if (type === \"function_call\" || type === \"computer_call\") {\n sawCall = true;\n continue;\n }\n if (sawCall && (type === \"function_call_result\" || type === \"computer_call_result\")) {\n return true;\n }\n }\n return false;\n}\n\nfunction memberResult(input: {\n callId: string;\n name: string;\n output: unknown;\n resultItem?: Record<string, unknown>;\n}): { resultItem: Record<string, unknown>; eventOutput: unknown } {\n return {\n resultItem:\n input.resultItem ??\n functionCallResultItem({\n callId: input.callId,\n name: input.name,\n output: input.output,\n }),\n eventOutput: input.output,\n };\n}\n\nasync function resultItemForOpenSuffixMember(input: {\n agent: Agent<any, any>;\n row: OpenSuffixPendingToolCall;\n trigger: Pick<SessionEvent, \"type\" | \"payload\">;\n humanInputResume: {\n requestId: string;\n toolCallId: string;\n response: HumanInputResponse;\n } | null;\n}): Promise<{ resultItem: Record<string, unknown>; eventOutput: unknown }> {\n const name = toolNameFromCallItem(input.row.callItem);\n const rejected = (): { resultItem: Record<string, unknown>; eventOutput: unknown } => {\n const payload = input.trigger.payload as { message?: unknown; decision?: unknown };\n const message =\n typeof payload.message === \"string\" && payload.message.trim().length > 0\n ? payload.message\n : \"Tool approval was rejected.\";\n const interrupted = interruptedToolCallResult({\n callType: input.row.callType,\n callId: input.row.callId,\n callItem: input.row.callItem,\n reason: message,\n });\n return memberResult({\n callId: input.row.callId,\n name,\n output: message,\n ...(interrupted ? { resultItem: interrupted } : {}),\n });\n };\n if (input.row.interruptionKind === \"human_input\") {\n if (!input.humanInputResume || input.humanInputResume.toolCallId !== input.row.callId) {\n throw new Error(\"Human-input open suffix is missing its durable response\");\n }\n const output = JSON.stringify({\n requestId: input.humanInputResume.requestId,\n ...input.humanInputResume.response,\n });\n return memberResult({\n callId: input.row.callId,\n name,\n output,\n });\n }\n const payload = input.trigger.payload as { decision?: unknown };\n if (payload.decision !== \"approve\") {\n return rejected();\n }\n try {\n const output = await invokePreparedAgentTool({\n agent: input.agent,\n toolName: name,\n argumentsJson: argumentsJsonFromCallItem(input.row.callItem),\n callId: input.row.callId,\n });\n return memberResult({\n callId: input.row.callId,\n name,\n output,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return memberResult({\n callId: input.row.callId,\n name,\n output: message,\n });\n }\n}\n\nexport async function settleOpenSuffixResumeIfNeeded(input: {\n db: Database;\n agent: Agent<any, any>;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n trigger: Pick<SessionEvent, \"type\" | \"payload\">;\n humanInputResume: {\n requestId: string;\n toolCallId: string;\n response: HumanInputResponse;\n } | null;\n modelToolOutputTruncationTokens?: number;\n settle: OpenSuffixSettle;\n publish?: (\n events: Array<{ type: \"agent.toolCall.output\"; payload: { id: string; output: unknown } }>,\n ) => Promise<unknown>;\n}): Promise<OpenSuffixResumeOutcome> {\n if (\n input.trigger.type !== \"user.approvalDecision\" &&\n input.trigger.type !== \"user.humanInputResponse\"\n ) {\n return { action: \"continue\" };\n }\n const rows = await listTurnOpenSuffixToolCalls(\n input.db,\n input.workspaceId,\n input.sessionId,\n input.turnId,\n );\n if (rows.length === 0) {\n return { action: \"continue\" };\n }\n const callId = matchingOpenSuffixCallId({\n trigger: input.trigger,\n humanInputToolCallId: input.humanInputResume?.toolCallId,\n });\n const target = resolveOpenSuffixResumeTarget(rows, callId);\n if (!target || !callId) {\n throw new Error(\"Open suffix resume event does not match an interruption\");\n }\n const truncationTokens =\n input.modelToolOutputTruncationTokens ?? target.modelToolOutputTruncationTokens ?? undefined;\n let resultItem = target.resultItem;\n let eventOutput: unknown = resultItem?.output;\n if (!resultItem) {\n const member = await resultItemForOpenSuffixMember({\n agent: input.agent,\n row: target,\n trigger: input.trigger,\n humanInputResume: input.humanInputResume,\n });\n resultItem = member.resultItem;\n eventOutput = member.eventOutput;\n const recorded = await recordPendingSessionToolCallResult(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n executionGeneration: input.executionGeneration,\n attemptId: input.attemptId,\n callId: target.callId,\n ...(truncationTokens !== undefined\n ? { modelToolOutputTruncationTokens: truncationTokens }\n : {}),\n resultItem,\n eventOutput,\n });\n if (!recorded.accepted) {\n return { action: \"cancelled\" };\n }\n if (!recorded.recorded) {\n const latest = resolveOpenSuffixResumeTarget(\n await listTurnOpenSuffixToolCalls(\n input.db,\n input.workspaceId,\n input.sessionId,\n input.turnId,\n ),\n callId,\n );\n resultItem = latest?.resultItem ?? resultItem;\n } else if (input.publish) {\n await input.publish([\n {\n type: \"agent.toolCall.output\",\n payload: { id: target.callId, output: eventOutput },\n },\n ]);\n }\n }\n if (!resultItem) {\n throw new Error(`Open suffix resume for ${target.callId} has no result item`);\n }\n const history = await getActiveSessionHistoryItems(input.db, input.workspaceId, input.sessionId);\n if (\n !openSuffixPairPresentInHistory(\n history.map((row) => row.item),\n callId,\n )\n ) {\n const historyItems = openSuffixHistoryItems(target, resultItem);\n if (historyItems.length === 0) {\n throw new Error(`Open suffix resume for ${target.callId} produced no paired history`);\n }\n const nextPosition = await nextSessionHistoryPosition(\n input.db,\n input.workspaceId,\n input.sessionId,\n );\n const appended = await appendSessionHistoryItems(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n expectedExecutionGeneration: input.executionGeneration,\n expectedAttemptId: input.attemptId,\n ...(truncationTokens !== undefined\n ? { modelToolOutputTruncationTokens: truncationTokens }\n : {}),\n items: historyItems.map((item, offset) => ({\n position: nextPosition + offset,\n item,\n })),\n });\n if (!appended) {\n return { action: \"cancelled\" };\n }\n }\n const remaining = (\n await listTurnOpenSuffixToolCalls(input.db, input.workspaceId, input.sessionId, input.turnId)\n ).filter((row) => row.resultItem == null);\n if (remaining.length === 0) {\n return { action: \"continue\" };\n }\n const requiresActionApprovals = remainingPendingApprovalsFromSuffix(remaining);\n const pendingApprovals = remainingRunStatePendingApprovalsFromSuffix(remaining);\n const settled = await input.settle({\n events: [\n ...(requiresActionApprovals.length > 0\n ? [\n {\n type: \"session.requiresAction\" as const,\n payload: { approvals: requiresActionApprovals },\n },\n ]\n : []),\n {\n type: \"session.status.changed\" as const,\n payload: { status: \"requires_action\" as const },\n },\n ],\n turnStatus: \"requires_action\",\n sessionStatus: \"requires_action\",\n activeTurnId: input.turnId,\n runState: {\n serializedRunState: OPEN_SUFFIX_RUN_STATE_BLOB,\n pendingApprovals,\n },\n });\n return settled ? { action: \"requires_action\" } : { action: \"cancelled\" };\n}\n\nexport function interruptionCallIdsFromPause(input: {\n humanInputRequests: Array<{ toolCallId: string }>;\n interactionInterventionRequests: Array<{ toolCallId: string }>;\n pendingApprovals: unknown[];\n}): string[] {\n const ids = new Set<string>();\n for (const request of input.humanInputRequests) {\n ids.add(request.toolCallId);\n }\n for (const request of input.interactionInterventionRequests) {\n ids.add(request.toolCallId);\n }\n for (const approval of input.pendingApprovals) {\n const id = approvalIdentifier(approval);\n if (id) {\n ids.add(id);\n }\n }\n return [...ids];\n}\n","import { hasPermission } from \"@opengeni/core\";\nimport type { AttemptToolDefinition } from \"@opengeni/codemode\";\nimport type { GeneratedSessionTitle } from \"@opengeni/runtime\";\nimport {\n AUTOMATIC_SESSION_TITLE_FALLBACK,\n DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,\n type FirstPartyMcpToolName,\n type Permission,\n type ToolRef,\n} from \"@opengeni/contracts\";\n\nexport const SESSION_TITLE_MODEL_TOOL_NAME = \"opengeni__set_session_title\";\n\nconst SESSION_TITLE_DESCRIPTION =\n \"Set this session's display title to a concise 3-7 word topic label. Use a stable noun phrase about the actual task or subject, never a quote/prefix of a prompt, greeting, request boilerplate, URL, identifier, credential, token, or other sensitive value. Call once on a new session, then only when the topic materially changes. Never call it as routine setup after a continuation, resume, or interruption, or merely to reassert the same title. A human-set title cannot be replaced.\";\n\nexport function shouldRequestMissingSessionTitle(input: {\n title: string | null;\n titleSource: \"user\" | \"agent\" | null;\n firstPartyMcpTools: readonly FirstPartyMcpToolName[];\n firstPartyMcpPermissions: readonly Permission[] | null;\n}): boolean {\n const title = input.title?.trim() ?? \"\";\n const needsSemanticTitle =\n input.titleSource !== \"user\" && (!title || title === AUTOMATIC_SESSION_TITLE_FALLBACK);\n if (!needsSemanticTitle) return false;\n if (!input.firstPartyMcpTools.includes(\"set_session_title\")) return false;\n const permissions = input.firstPartyMcpPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS;\n return hasPermission([...permissions], \"sessions:control\");\n}\n\nexport function sessionTitleToolPlan(input: {\n tools: readonly ToolRef[];\n selectedFirstPartyMcpTools: readonly FirstPartyMcpToolName[];\n shouldRequestTitle: boolean;\n parallelGenerationAvailable: boolean;\n}): {\n promoteTitleTool: boolean;\n generateTitleInParallel: boolean;\n remoteFirstPartyMcpTools: FirstPartyMcpToolName[];\n preparationIndependentToolNames: string[];\n} {\n const titleToolAvailable =\n input.shouldRequestTitle &&\n input.tools.some((tool) => tool.kind === \"mcp\" && tool.id === \"opengeni\");\n const generateTitleInParallel = titleToolAvailable && input.parallelGenerationAvailable;\n const promoteTitleTool = titleToolAvailable && !generateTitleInParallel;\n return {\n promoteTitleTool,\n generateTitleInParallel,\n remoteFirstPartyMcpTools: titleToolAvailable\n ? input.selectedFirstPartyMcpTools.filter((tool) => tool !== \"set_session_title\")\n : [...input.selectedFirstPartyMcpTools],\n preparationIndependentToolNames: promoteTitleTool ? [SESSION_TITLE_MODEL_TOOL_NAME] : [],\n };\n}\n\nexport const PARALLEL_SESSION_TITLE_TIMEOUT_MS = 15_000;\n\nexport type ParallelSessionTitleGeneration = {\n finish: () => Promise<GeneratedSessionTitle | null>;\n cancel: () => Promise<void>;\n};\n\n/**\n * Start title inference immediately and keep it independent of the main agent\n * stream. finish() waits for the already-running bounded request, so a quick\n * main response does not discard a valid title merely because it completed\n * first. cancel() aborts and joins exceptional/cancelled exits so no provider\n * work escapes the owning runAgentTurn activity.\n */\nexport function startParallelSessionTitleGeneration(input: {\n generate: (signal: AbortSignal) => Promise<GeneratedSessionTitle>;\n signal?: AbortSignal;\n timeoutMs?: number;\n onError?: (error: unknown) => void;\n}): ParallelSessionTitleGeneration {\n const cancellationController = new AbortController();\n const timeoutSignal = AbortSignal.timeout(input.timeoutMs ?? PARALLEL_SESSION_TITLE_TIMEOUT_MS);\n const signals = [cancellationController.signal, timeoutSignal];\n if (input.signal) signals.push(input.signal);\n const signal = AbortSignal.any(signals);\n const generation = input\n .generate(signal)\n .then((result) => (signal.aborted ? null : result))\n .catch((error: unknown) => {\n if (!signal.aborted) input.onError?.(error);\n return null;\n });\n let finished: Promise<GeneratedSessionTitle | null> | null = null;\n\n return {\n finish: () => {\n if (finished) return finished;\n finished = generation;\n return finished;\n },\n cancel: async () => {\n cancellationController.abort();\n await generation;\n },\n };\n}\n\nexport function createSessionTitleAttemptToolDefinition(input: {\n updateTitle: (title: string) => Promise<{ updated: boolean; title: string | null }>;\n}): AttemptToolDefinition {\n return {\n identity: { serverId: \"opengeni\", toolName: \"set_session_title\" },\n modelName: SESSION_TITLE_MODEL_TOOL_NAME,\n codemodePath: [\"opengeni\", \"set_session_title\"],\n title: \"Set session title\",\n description: SESSION_TITLE_DESCRIPTION,\n inputSchema: {\n type: \"object\",\n properties: {\n title: { type: \"string\", minLength: 1, maxLength: 200 },\n },\n required: [\"title\"],\n additionalProperties: false,\n },\n outputSchema: {\n type: \"object\",\n properties: {\n ok: { type: \"boolean\", const: true },\n updated: { type: \"boolean\" },\n title: { type: \"string\" },\n },\n required: [\"ok\", \"updated\", \"title\"],\n additionalProperties: false,\n },\n annotations: {\n title: \"Set session title\",\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n source: \"opengeni\",\n approval: \"none\",\n execute: async (args) => {\n const title = args.title;\n if (typeof title !== \"string\") {\n throw new Error(\"set_session_title requires a title string\");\n }\n const result = await input.updateTitle(title);\n const output = {\n ok: true as const,\n updated: result.updated,\n title: result.title ?? title,\n };\n return {\n isError: false,\n content: [{ type: \"text\", text: JSON.stringify(output) }],\n structuredContent: output,\n };\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport {\n claimSandboxSharedPreparation,\n readSandboxSharedPreparation,\n SandboxLeaseSupersededError,\n settleSandboxSharedPreparation,\n type Database,\n} from \"@opengeni/db\";\n\nimport type { ResumedTurnSandbox } from \"../../sandbox-resume\";\n\ntype SharedRigSetupCoordinatorInput = {\n specHash: string;\n timeoutMs: number;\n execute: () => Promise<void>;\n};\n\ntype SharedRigSetupCoordinatorOptions = {\n db: Database;\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n attemptId: string;\n holderId: string;\n sandbox: ResumedTurnSandbox;\n signal?: AbortSignal;\n observe?: (measurement: {\n path: \"owner\" | \"joined\" | \"reused\";\n outcome: \"completed\" | \"failed\";\n durationSeconds: number;\n }) => void;\n};\n\nfunction observeSharedPreparation(\n options: SharedRigSetupCoordinatorOptions,\n measurement: Parameters<NonNullable<SharedRigSetupCoordinatorOptions[\"observe\"]>>[0],\n): void {\n try {\n options.observe?.(measurement);\n } catch {\n // Telemetry must never alter setup authority or settlement.\n }\n}\n\nfunction waitForPreparationTransition(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n let settled = false;\n const timer = setTimeout(finish, ms);\n function finish(): void {\n if (settled) return;\n settled = true;\n signal?.removeEventListener(\"abort\", cancel);\n resolve();\n }\n function cancel(): void {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", cancel);\n reject(signal?.reason ?? new Error(\"Sandbox shared preparation wait cancelled\"));\n }\n signal?.addEventListener(\"abort\", cancel, { once: true });\n if (signal?.aborted) cancel();\n });\n}\n\nasync function settleCompletedWithRetry(\n options: SharedRigSetupCoordinatorOptions,\n input: SharedRigSetupCoordinatorInput,\n claimId: string,\n): Promise<boolean> {\n let delayMs = 50;\n for (let attempt = 0; attempt < 4; attempt += 1) {\n try {\n if (\n await settleSandboxSharedPreparation(options.db, {\n accountId: options.accountId,\n workspaceId: options.workspaceId,\n sandboxGroupId: options.sandboxGroupId,\n expectedLeaseEpoch: options.sandbox.leaseEpoch,\n expectedInstanceId: options.sandbox.established.instanceId,\n specHash: input.specHash,\n holderId: options.holderId,\n claimId,\n outcome: \"completed\",\n })\n ) {\n return true;\n }\n } catch {\n // The exact claim remains durable. Retry settlement without replaying the\n // provider operation; a later owner can verify the box-local marker.\n }\n await waitForPreparationTransition(delayMs, options.signal);\n delayMs *= 2;\n }\n return false;\n}\n\n/**\n * Coordinate immutable rig setup across workers. Joiners use a revision-aware,\n * exponentially backed-off durable read instead of the old fixed 250 ms lease\n * polling pattern. PostgreSQL remains source of truth; a lost completion write\n * is recovered by the next deadline owner through the hook's box-local marker.\n */\nexport function createSharedRigSetupCoordinator(\n options: SharedRigSetupCoordinatorOptions,\n): (input: SharedRigSetupCoordinatorInput) => Promise<\"executed\" | \"reused\"> {\n return async (input) => {\n const startedAt = performance.now();\n const claimId = randomUUID();\n const identity = {\n accountId: options.accountId,\n workspaceId: options.workspaceId,\n sandboxGroupId: options.sandboxGroupId,\n expectedLeaseEpoch: options.sandbox.leaseEpoch,\n expectedInstanceId: options.sandbox.established.instanceId,\n specHash: input.specHash,\n holderId: options.holderId,\n };\n const claimTimeoutMs = Math.min(3_600_000, Math.max(30_000, input.timeoutMs + 30_000));\n let delayMs = 100;\n let observedRevision = -1;\n let path: \"owner\" | \"joined\" | \"reused\" = \"owner\";\n\n try {\n for (;;) {\n if (options.signal?.aborted) {\n throw options.signal.reason ?? new Error(\"Sandbox shared preparation cancelled\");\n }\n const claim = await claimSandboxSharedPreparation(options.db, {\n ...identity,\n claimId,\n ownerAttemptId: options.attemptId,\n timeoutMs: claimTimeoutMs,\n });\n if (claim.role === \"fenced\") {\n throw new SandboxLeaseSupersededError(options.sandboxGroupId, options.sandbox.leaseEpoch);\n }\n if (claim.role === \"reused\") {\n if (path !== \"joined\") path = \"reused\";\n observeSharedPreparation(options, {\n path,\n outcome: \"completed\",\n durationSeconds: (performance.now() - startedAt) / 1_000,\n });\n return \"reused\";\n }\n if (claim.role === \"owner\") {\n try {\n await input.execute();\n } catch (error) {\n await settleSandboxSharedPreparation(options.db, {\n ...identity,\n claimId,\n outcome: \"failed\",\n }).catch(() => undefined);\n throw error;\n }\n if (await settleCompletedWithRetry(options, input, claimId)) {\n observeSharedPreparation(options, {\n path,\n outcome: \"completed\",\n durationSeconds: (performance.now() - startedAt) / 1_000,\n });\n return \"executed\";\n }\n throw new Error(\n \"Sandbox shared preparation completed but its durable settlement remains unavailable\",\n );\n }\n\n path = \"joined\";\n observedRevision = claim.preparation.revision;\n const jitterMs = Math.floor(Math.random() * Math.max(1, Math.floor(delayMs / 4)));\n await waitForPreparationTransition(delayMs + jitterMs, options.signal);\n const observed = await readSandboxSharedPreparation(options.db, identity);\n if (observed.status === \"fenced\") {\n throw new SandboxLeaseSupersededError(options.sandboxGroupId, options.sandbox.leaseEpoch);\n }\n if (observed.preparation.status === \"completed\") {\n observeSharedPreparation(options, {\n path,\n outcome: \"completed\",\n durationSeconds: (performance.now() - startedAt) / 1_000,\n });\n return \"reused\";\n }\n if (observed.preparation.status === \"failed\") {\n delayMs = 100;\n continue;\n }\n delayMs =\n observed.preparation.revision === observedRevision ? Math.min(2_000, delayMs * 2) : 100;\n }\n } catch (error) {\n observeSharedPreparation(options, {\n path,\n outcome: \"failed\",\n durationSeconds: (performance.now() - startedAt) / 1_000,\n });\n throw error;\n }\n };\n}\n","import {\n applySessionTurnSettlement,\n claimSessionWorkForAttempt,\n getSessionEvent,\n getHumanInputResumeForEvent,\n getInteractionInterventionResumeForEvent,\n installOrReadTurnExecutionPolicyForAttempt,\n workspaceCodexSubscriptionActive,\n requireSession,\n type AppendEventInput,\n type ApiIntegrationRuntime,\n type CanonicalTurnStartupMilestoneReceipt,\n type ClaimSessionWorkForAttemptInput,\n type SessionTurnForExecution,\n} from \"@opengeni/db\";\nimport { appendAndPublishTurnEventsFenced, publishDurableSessionEvents } from \"@opengeni/events\";\nimport { deliverChildRequiresActionToParent } from \"../parent-wake\";\nimport {\n assertTurnExecutionPolicyMatchesConfigV1,\n resolveTurnExecutionPolicyV1,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n settingsWithCodexCredential,\n settingsWithEnabledCapabilityMcpServers,\n settingsWithWorkspaceGatewayCredential,\n settingsWithWorkspaceOpenRouterCredential,\n settingsWithOrganizationProviderCredentials,\n withXaiSubscriptionProvider,\n} from \"../capabilities\";\nimport { validateIncidentTelemetrySystemUpdateAuthority } from \"../incident-telemetry-authority\";\nimport {\n assertSessionAllowsProductModel,\n resolveCatalogSettings,\n resolveCodexAppsCredentialIdForRun,\n} from \"@opengeni/core\";\nimport { TurnAttemptFencedError } from \"../turn-attempt-fenced\";\nimport { currentActivityContext, startActivityHeartbeat } from \"../streaming\";\nimport type {\n TurnActivityServices as ActivityServices,\n RunAgentTurnInput,\n RunAgentTurnResult,\n} from \"../types\";\nimport { makeTurnOpJournal, type TurnHeartbeatDetails } from \"../../op-journal\";\nimport {\n recordSessionEventAppendLatency,\n recordSessionEventAppendPhase,\n recordSessionEventPublishLatency,\n recordTurnStartupPhase,\n recordTurnStartupMilestone,\n turnLifecycleMetricsFor,\n} from \"../../observability-metrics\";\nimport { createTurnCredentialLeases } from \"./credential-leases\";\nimport { createTurnMediaArtifacts } from \"./media-artifacts\";\nimport { readTurnExecutionPolicyV1 } from \"@opengeni/contracts\";\n\nimport {\n credentialSubjectIdForTurnInitiator,\n turnExecutionPolicyBillingIdentity,\n legacyTurnExecutionPolicyInput,\n ensureRunAllowed,\n} from \"./admission\";\nimport { providerRecoveryCountFromMetadata, isWorkerShutdownCancellation } from \"./errors\";\nimport { throwIfTurnOperationCancelled, waitForTurnOperation } from \"./sandbox-provision\";\nimport type { TurnExecutionPolicyV1 } from \"@opengeni/contracts\";\nimport type {\n AttemptIdentityState,\n BillingState,\n ClaimedResult,\n EventingState,\n SandboxRuntimeState,\n TurnControlState,\n} from \"./turn-context\";\n\nexport type ClaimTurnDeps = {\n input: RunAgentTurnInput;\n settings: Settings;\n catalogSourceSettings: Settings;\n db: ActivityServices[\"db\"];\n bus: ActivityServices[\"bus\"];\n runtime: ActivityServices[\"runtime\"];\n observability: ActivityServices[\"observability\"];\n entitlements: ActivityServices[\"entitlements\"];\n wakeSessionWorkflow: ActivityServices[\"wakeSessionWorkflow\"];\n cancellationSignal: AbortSignal | undefined;\n activityContext: ReturnType<typeof currentActivityContext>;\n dispatchId: string;\n activityStarted: number;\n control: TurnControlState;\n attempt: AttemptIdentityState;\n billingState: BillingState;\n sandboxState: SandboxRuntimeState;\n eventing: EventingState;\n leases: ReturnType<typeof createTurnCredentialLeases>;\n media: ReturnType<typeof createTurnMediaArtifacts>;\n claimedResult: ClaimedResult;\n acknowledgeLostAttemptOwnership: () => void;\n};\n\nexport type ClaimTurnOk = {\n turn: SessionTurnForExecution;\n session: Awaited<ReturnType<typeof requireSession>>;\n installedApiIntegrations: readonly ApiIntegrationRuntime[];\n credentialSubjectId: string | undefined;\n fileAuthoritySubjectId: string | null;\n capabilitySettings: Settings;\n codexAppsCredentialId: string | null;\n turnExecutionPolicy: TurnExecutionPolicyV1;\n trigger: NonNullable<Awaited<ReturnType<typeof getSessionEvent>>>;\n humanInputResume: Awaited<ReturnType<typeof getHumanInputResumeForEvent>>;\n interactionInterventionResume: Awaited<\n ReturnType<typeof getInteractionInterventionResumeForEvent>\n >;\n attachPendingUpdatesAfterOpenSuffix: () => Promise<boolean>;\n throwIfWorkerShuttingDown: () => void;\n throwIfTurnCancelled: () => void;\n opJournal: ReturnType<typeof makeTurnOpJournal>;\n modelUsageDispatchId: string;\n claimedModelUsageSourceKeys: Set<string>;\n emittedModelUsageSourceKeys: Set<string>;\n};\n\n/**\n * Stable for Temporal retries of one scheduled turn attempt, but unique across\n * workflow runs. Temporal activity ids restart at `1` after continue-as-new or\n * workflow restart, so they are not safe durable producer identities by\n * themselves.\n */\nexport function turnAttemptProducerId(\n input: Pick<RunAgentTurnInput, \"workflowId\" | \"attemptId\">,\n turnId: string,\n): string {\n return `${input.workflowId}:${turnId}:${input.attemptId}`;\n}\n\n/**\n * Durable Codex lease holder for one accepted turn attempt. Temporal activity\n * ids may repeat after workflow restart or continue-as-new, so they are not\n * owner identity. The attempt id is generated by the workflow for each\n * redispatch and remains stable when the same activity input is retried.\n */\nexport function codexCredentialLeaseHolderId(\n input: Pick<RunAgentTurnInput, \"workflowId\" | \"attemptId\">,\n turnId: string,\n): string {\n const parts = [input.workflowId, turnId, input.attemptId];\n if (parts.some((part) => part.trim().length === 0)) {\n throw new Error(\"Codex credential lease holder requires a complete turn attempt identity\");\n }\n return `codex-turn:${parts.map((part) => encodeURIComponent(part)).join(\":\")}`;\n}\n\nexport type ClaimTurnOutcome = { exit: RunAgentTurnResult } | { ok: ClaimTurnOk };\n\nexport async function claimTurnAttempt(deps: ClaimTurnDeps): Promise<ClaimTurnOutcome> {\n const {\n input,\n settings,\n catalogSourceSettings,\n db,\n bus,\n runtime,\n observability,\n entitlements,\n wakeSessionWorkflow,\n cancellationSignal,\n activityContext,\n dispatchId,\n activityStarted,\n control,\n attempt,\n billingState,\n sandboxState,\n eventing,\n leases,\n media,\n claimedResult,\n acknowledgeLostAttemptOwnership,\n } = deps;\n\n const deploymentCatalogSettings = (await resolveCatalogSettings(db, catalogSourceSettings))\n .settings;\n\n const validatePendingSystemUpdateAuthority: NonNullable<\n ClaimSessionWorkForAttemptInput[\"validatePendingSystemUpdateAuthority\"]\n > = async (tx, update) =>\n await validateIncidentTelemetrySystemUpdateAuthority({\n db: tx,\n settings: deploymentCatalogSettings,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n update,\n });\n const claim = await claimSessionWorkForAttempt(db, input.workspaceId, {\n sessionId: input.sessionId,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n attemptId: input.attemptId,\n dispatchId,\n trigger: input.trigger,\n validatePendingSystemUpdateAuthority,\n });\n if (claim.action === \"unclaimed\") {\n control.activityStatus = \"unclaimed\";\n return { exit: { status: \"unclaimed\", reason: claim.reason } };\n }\n const turn = claim.turn;\n attempt.turnId = turn.id;\n attempt.dispatchId = dispatchId;\n attempt.executionGeneration = turn.executionGeneration;\n attempt.providerRecoveryCount = providerRecoveryCountFromMetadata(turn.metadata);\n attempt.triggerEventId = turn.triggerEventId;\n // The durable attempt UUID is stable for a Temporal retry of this activity\n // input and freshly generated for worker-death redispatch/continue-as-new.\n // Keep dispatchId separate: it remains the Temporal activity identity used\n // by attempt fencing, audit, and observability.\n leases.codex.holderId = codexCredentialLeaseHolderId(input, turn.id);\n attempt.redispatchesAtDispatch = Number(\n (turn.metadata as { workerDeathRedispatches?: number } | null)?.workerDeathRedispatches ?? 0,\n );\n const claimedPolicy = readTurnExecutionPolicyV1(turn.metadata);\n // Establish durable attempt ownership before any later read can fail.\n // Therefore every failure with no turnId came from the one atomic claim\n // transaction and can be classified without conflating ordinary runtime\n // or transport failures with admission failures.\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n let installedApiIntegrations: readonly ApiIntegrationRuntime[] = [];\n const credentialSubjectId = credentialSubjectIdForTurnInitiator(turn);\n const fileAuthoritySubjectId = turn.initiatingHumanSubjectId ?? null;\n const mcpSettings = await settingsWithEnabledCapabilityMcpServers(\n db,\n input.workspaceId,\n deploymentCatalogSettings,\n {\n ...(credentialSubjectId\n ? { subjectId: credentialSubjectId }\n : {\n personalConnectionDelegations: turn.personalConnectionDelegations,\n }),\n onResolvedApiIntegrations: (integrations) => {\n installedApiIntegrations = integrations;\n },\n },\n );\n // Read the active-credential flag once for the runtime capability overlay.\n // Accepted billing/provider identity comes from the turn policy below,\n // never from this mutable health snapshot.\n const codexSubscriptionActive = await workspaceCodexSubscriptionActive(\n db,\n mcpSettings,\n input.workspaceId,\n );\n const codexSettings = await settingsWithCodexCredential(\n db,\n input.workspaceId,\n mcpSettings,\n codexSubscriptionActive,\n );\n const xaiSettings = codexSettings.supergrokSubscriptionEnabled\n ? withXaiSubscriptionProvider(codexSettings)\n : codexSettings;\n const gatewaySettings = await settingsWithWorkspaceGatewayCredential(\n db,\n input.accountId,\n input.workspaceId,\n xaiSettings,\n claimedPolicy.kind === \"valid\" ? claimedPolicy.policy.productModelId : turn.model,\n );\n const workspaceProviderSettings = await settingsWithWorkspaceOpenRouterCredential(\n db,\n input.accountId,\n input.workspaceId,\n gatewaySettings,\n claimedPolicy.kind === \"valid\" ? claimedPolicy.policy.productModelId : turn.model,\n );\n const capabilitySettings = await settingsWithOrganizationProviderCredentials(\n db,\n input.accountId,\n input.workspaceId,\n workspaceProviderSettings,\n claimedPolicy.kind === \"valid\" ? claimedPolicy.policy.productModelId : turn.model,\n );\n const codexAppsCredentialId = capabilitySettings.codexConnectedAppsEnabled\n ? await resolveCodexAppsCredentialIdForRun(db, input.workspaceId)\n : null;\n runtime.configure(capabilitySettings);\n const policyForAbsent =\n claimedPolicy.kind === \"valid\"\n ? claimedPolicy.policy\n : resolveTurnExecutionPolicyV1(capabilitySettings, legacyTurnExecutionPolicyInput(turn));\n const installedPolicy = await installOrReadTurnExecutionPolicyForAttempt(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n policyForAbsent,\n });\n if (!installedPolicy.accepted) {\n throw new TurnAttemptFencedError(`turn execution policy was fenced: ${installedPolicy.reason}`);\n }\n const verifiedExecutionPolicy = assertTurnExecutionPolicyMatchesConfigV1(\n capabilitySettings,\n installedPolicy.policy,\n {\n modelId: turn.model,\n reasoningEffort: turn.reasoningEffort,\n latencyMode: turn.latencyMode,\n },\n );\n const turnExecutionPolicy = verifiedExecutionPolicy.policy;\n assertSessionAllowsProductModel(session, turnExecutionPolicy.productModelId);\n const billingIdentity = turnExecutionPolicyBillingIdentity(turnExecutionPolicy);\n billingState.isExternallyBilledTurn = billingIdentity.externallyBilled;\n billingState.chargesOpenGeniCredits = verifiedExecutionPolicy.model.cost === \"credits\";\n billingState.countsTowardTokenCap = billingIdentity.countsTowardTokenCap;\n billingState.isCodexTurn = billingIdentity.codexSubscription;\n billingState.isXaiTurn = billingIdentity.xaiSubscription;\n const trigger = await getSessionEvent(db, input.workspaceId, attempt.triggerEventId);\n if (!trigger) {\n throw new Error(`Trigger event not found: ${attempt.triggerEventId}`);\n }\n const humanInputResume = await getHumanInputResumeForEvent(\n db,\n input.workspaceId,\n input.sessionId,\n trigger,\n );\n const interactionInterventionResume = await getInteractionInterventionResumeForEvent(\n db,\n input.workspaceId,\n input.sessionId,\n trigger,\n );\n attempt.triggerType = trigger.type;\n const attachPendingUpdatesAfterOpenSuffix = async (): Promise<boolean> => {\n const attached = await claimSessionWorkForAttempt(db, input.workspaceId, {\n sessionId: input.sessionId,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n attemptId: input.attemptId,\n dispatchId,\n trigger: input.trigger,\n validatePendingSystemUpdateAuthority,\n attachPendingUpdatesToRunningAttempt: true,\n });\n return attached.action === \"claimed\" && attached.turn.id === turn.id;\n };\n turnLifecycleMetricsFor(observability).start(attempt.turnId);\n // §7.5 P3 — pass the accepted billing attribution (externally funded turns\n // bypass OpenGeni credit/token gates)\n // AND the optional host `entitlements` port (when bound, its admitRun replaces\n // the local credit read). Unset port → today's local-ledger path.\n await waitForTurnOperation(\n ensureRunAllowed(\n capabilitySettings,\n db,\n input.accountId,\n input.workspaceId,\n billingState.isExternallyBilledTurn,\n entitlements,\n billingState.chargesOpenGeniCredits,\n billingState.countsTowardTokenCap,\n ),\n cancellationSignal,\n undefined,\n );\n // Setup (variableSet load, MCP connects, sandbox restore) does not\n // stream and so never observes cancellation on its own; these explicit\n // checks let a graceful shutdown checkpoint the turn before the worker is\n // force-killed instead of riding the setup to a heartbeat timeout.\n const throwIfWorkerShuttingDown = () => {\n const reason = activityContext?.cancellationSignal.reason;\n if (isWorkerShutdownCancellation(reason)) {\n throw reason;\n }\n };\n const throwIfTurnCancelled = () => throwIfTurnOperationCancelled(cancellationSignal);\n // ONE shared details object for every heartbeat this activity sends (each\n // site spreads it + its own phase), so cross-site fields — the op-stream\n // settled roster in particular — survive last-write-wins instead of being\n // clobbered by whichever site heartbeated most recently.\n const heartbeatDetails: TurnHeartbeatDetails = {\n phase: \"running\",\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n opAcks: {},\n };\n const opJournal = makeTurnOpJournal(activityContext, heartbeatDetails);\n eventing.heartbeatTimer = startActivityHeartbeat(activityContext, heartbeatDetails);\n let producerSeq = 0;\n // One producer per scheduled turn attempt, not per turn. A turn can run\n // again after Pause/Steer/recovery, and each attempt restarts producerSeq at\n // 1. `attemptId` is stable across a genuine Temporal activity retry and\n // unique across workflow runs; `activityId` is not, because Temporal resets\n // it after continue-as-new or a new workflow execution.\n const producerId = turnAttemptProducerId(input, attempt.turnId);\n // Fold the same durable attempt identity into positional usage source keys.\n // A retry dedupes; a re-dispatch cannot collide with the prior attempt.\n const modelUsageDispatchId = input.attemptId;\n const claimedModelUsageSourceKeys = new Set<string>();\n const emittedModelUsageSourceKeys = new Set<string>();\n const recordCanonicalStartupMilestones = (\n receipts: CanonicalTurnStartupMilestoneReceipt[],\n ): void => {\n for (const receipt of receipts) {\n recordTurnStartupMilestone(observability, {\n milestone: receipt.milestone,\n provider: turnExecutionPolicy.providerId,\n backend: sandboxState.startupMilestoneBackend ?? turn.sandboxBackend,\n outcome: receipt.outcome,\n durationSeconds: receipt.durationMs / 1_000,\n });\n }\n };\n eventing.publish = async (\n events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>,\n immediate = false,\n ) => {\n const inputs = events.map((event) => ({\n ...event,\n payload: event.payload,\n turnId: attempt.turnId!,\n producerId,\n producerSeq: ++producerSeq,\n }));\n const appended = await appendAndPublishTurnEventsFenced(\n db,\n bus,\n input.workspaceId,\n input.sessionId,\n attempt.turnId!,\n attempt.executionGeneration,\n input.attemptId,\n inputs,\n {\n onAppend: ({ durationSeconds }) =>\n recordSessionEventAppendLatency(observability, {\n durationSeconds,\n }),\n onAppendPhase: (observation) => recordSessionEventAppendPhase(observability, observation),\n onPublish: ({ durationSeconds }) =>\n recordSessionEventPublishLatency(observability, {\n durationSeconds,\n }),\n },\n );\n if (inputs.length > 0 && !appended.accepted) {\n throw new TurnAttemptFencedError(\"turn execution generation was fenced\");\n }\n recordCanonicalStartupMilestones(appended.canonicalStartupMilestones);\n if (inputs.length > 0) {\n turnLifecycleMetricsFor(observability).progress(attempt.turnId!);\n }\n activityContext?.heartbeat({\n ...heartbeatDetails,\n phase: \"events_published\",\n producerSeq,\n });\n if (immediate) {\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n }\n return appended;\n };\n eventing.settle = async (inputSettlement) => {\n const compactionRequestFailure = inputSettlement.consumeRequestedCompactionFailure\n ? {\n reason: \"summarization_failed\" as const,\n producerId,\n producerSeq: ++producerSeq,\n }\n : undefined;\n const inputs = inputSettlement.events.map((event) => ({\n ...event,\n payload: event.payload,\n turnId: attempt.turnId!,\n producerId,\n producerSeq: ++producerSeq,\n }));\n const runState = inputSettlement.runState\n ? {\n ...inputSettlement.runState,\n serializedRunState: media.compactMediaRunState(\n inputSettlement.runState.serializedRunState,\n ),\n }\n : undefined;\n const result = await applySessionTurnSettlement(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: attempt.turnId!,\n triggerEventId: attempt.triggerEventId!,\n attemptId: input.attemptId,\n turnStatus: inputSettlement.turnStatus,\n sessionStatus: inputSettlement.sessionStatus,\n activeTurnId: inputSettlement.activeTurnId,\n ...(inputSettlement.suppressGoalContinuation !== undefined\n ? { suppressGoalContinuation: inputSettlement.suppressGoalContinuation }\n : {}),\n events: inputs,\n ...(runState ? { runState } : {}),\n ...(compactionRequestFailure ? { compactionRequestFailure } : {}),\n });\n if (result.action === \"stale\") {\n // The terminal write can lose to a control transaction before the\n // workflow delivers Temporal cancellation. That control may settle\n // the already-closed attempt as rejected_stale, so returning without\n // this flag would strand its replacement behind quiesced_at forever.\n // Enter the same hard tool-fence/receipt path as an explicit\n // TurnAttemptFencedError. If ownership was lost for an unrelated\n // reason, allowUninterrupted makes the receipt transaction a no-op.\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return false;\n }\n recordCanonicalStartupMilestones(result.canonicalStartupMilestones);\n turnLifecycleMetricsFor(observability).progress(attempt.turnId!);\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, result.events);\n if (inputSettlement.turnStatus === \"requires_action\") {\n // The settlement transaction committed the parent's child_requires_action\n // outbox row (when this session has a parent and notices are enabled).\n // Deliver it right away; the reaper covers a crash between the two.\n await deliverChildRequiresActionToParent(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n { turnId: attempt.turnId!, turnGeneration: attempt.executionGeneration },\n );\n }\n activityContext?.heartbeat({\n ...heartbeatDetails,\n phase: \"events_published\",\n producerSeq,\n });\n return true;\n };\n activityContext?.heartbeat({\n ...heartbeatDetails,\n phase: \"turn_started\",\n });\n\n // A shutdown that landed during claim/billing setup stops before the turn\n // visibly starts: nothing ran yet, so the same inference starts cleanly\n // on a healthy worker.\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n recordTurnStartupPhase(observability, {\n phase: \"claim_and_policy\",\n provider: turnExecutionPolicy.providerId,\n backend: turn.sandboxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - activityStarted) / 1_000,\n });\n const turnStartSettlementStartedAt = performance.now();\n if (\n !(await eventing.settle({\n events: [\n { type: \"session.status.changed\", payload: { status: \"running\" } },\n {\n type: \"turn.started\",\n payload: { triggerEventId: attempt.triggerEventId },\n },\n ],\n turnStatus: \"running\",\n sessionStatus: \"running\",\n activeTurnId: attempt.turnId,\n }))\n ) {\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n recordTurnStartupPhase(observability, {\n phase: \"turn_start_settlement\",\n provider: turnExecutionPolicy.providerId,\n backend: turn.sandboxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - turnStartSettlementStartedAt) / 1_000,\n count: 2,\n });\n eventing.turnStartedPublished = true;\n\n return {\n ok: {\n turn,\n session,\n installedApiIntegrations,\n credentialSubjectId,\n fileAuthoritySubjectId,\n capabilitySettings,\n codexAppsCredentialId,\n turnExecutionPolicy,\n trigger,\n humanInputResume,\n interactionInterventionResume,\n attachPendingUpdatesAfterOpenSuffix,\n throwIfWorkerShuttingDown,\n throwIfTurnCancelled,\n opJournal,\n modelUsageDispatchId,\n claimedModelUsageSourceKeys,\n emittedModelUsageSourceKeys,\n },\n };\n}\n","import {\n environmentsEncryptionKeyBytes,\n type Settings,\n WORKSPACE_GATEWAY_MODEL_ID_PREFIX,\n WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,\n withCodexCatalogProvider,\n withWorkspaceGatewayCatalogProvider,\n withWorkspaceGatewayCredential,\n withWorkspaceOpenRouterCatalogProvider,\n withWorkspaceOpenRouterCredential,\n withOrganizationGatewayCatalogProvider,\n withOrganizationGatewayCredential,\n withOrganizationOpenRouterCatalogProvider,\n withOrganizationOpenRouterCredential,\n ORGANIZATION_GATEWAY_MODEL_ID_PREFIX,\n ORGANIZATION_OPENROUTER_MODEL_ID_PREFIX,\n withXaiSubscriptionCatalogProvider,\n} from \"@opengeni/config\";\nimport { settingsWithEnabledCapabilityMcpServers } from \"@opengeni/core\";\nimport {\n getWorkspaceGatewayCustomModelForExecution,\n getWorkspaceOpenRouterCustomModelForExecution,\n listSessionMcpServerMetadata,\n listSessionMcpServersForRun,\n listWorkspaceGatewayCustomModels,\n listWorkspaceOpenRouterCustomModels,\n workspaceCodexSubscriptionActive,\n loadWorkspaceVercelAiGatewayApiKey,\n loadWorkspaceOpenRouterApiKey,\n listOrganizationModelProviderCustomModelsForWorkspace,\n getOrganizationModelProviderCustomModelForExecution,\n loadOrganizationModelProviderApiKey,\n type Database,\n type SessionMcpServerForRun,\n} from \"@opengeni/db\";\n\nexport { settingsWithEnabledCapabilityMcpServers };\n\nexport async function settingsWithSessionMcpServersForRun(\n db: Database,\n workspaceId: string,\n sessionId: string,\n attemptId: string,\n settings: Settings,\n options?: {\n onResolvedServers?: (servers: readonly SessionMcpServerForRun[]) => void;\n },\n): Promise<Settings> {\n const encryptionKey = environmentsEncryptionKeyBytes(settings);\n if (!encryptionKey) {\n const metadata = await listSessionMcpServerMetadata(db, workspaceId, sessionId);\n if (metadata.length === 0) {\n return settings;\n }\n if (metadata.some((server) => server.headerNames.length > 0)) {\n throw new Error(\n \"session MCP server credentials require OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\",\n );\n }\n }\n const servers = await listSessionMcpServersForRun(\n db,\n workspaceId,\n sessionId,\n attemptId,\n encryptionKey ?? null,\n );\n // Keep credential provenance coupled to the exact decrypted rows that are\n // overlaid into settings. A session projection read earlier in the turn can\n // be stale after a concurrent mcpCredentialUpdates renewal.\n options?.onResolvedServers?.(servers);\n return settingsWithSessionMcpServers(settings, servers);\n}\n\nexport function settingsWithSessionMcpServers(\n settings: Settings,\n servers: SessionMcpServerForRun[],\n): Settings {\n if (servers.length === 0) {\n return settings;\n }\n const sessionIds = new Set(servers.map((server) => server.id));\n return {\n ...settings,\n mcpServers: [\n ...settings.mcpServers.filter((server) => !sessionIds.has(server.id)),\n ...servers.map((server) => ({\n id: server.id,\n ...(server.name ? { name: server.name } : {}),\n url: server.url,\n ...(server.allowedTools ? { allowedTools: server.allowedTools } : {}),\n ...(server.timeoutMs ? { timeoutMs: server.timeoutMs } : {}),\n cacheToolsList: server.cacheToolsList ?? false,\n ...(server.requireApproval !== undefined\n ? { requireApproval: server.requireApproval }\n : {}),\n ...(server.connectionRef ? { connectionRef: server.connectionRef } : {}),\n headers: server.headers,\n })),\n ],\n };\n}\n\n/**\n * When the workspace has an active Codex subscription connected and the feature\n * is enabled, inject a synthetic \"codex-subscription\" registry provider so a\n * `codex/<slug>` model id routes through the ChatGPT backend. No secrets touch\n * this overlay (metadata-only read); the per-request bearer is resolved later via\n * codexRequestStorage. Idempotent and a no-op when not applicable.\n */\nexport async function settingsWithCodexCredential(\n db: Database,\n workspaceId: string,\n settings: Settings,\n activeOverride?: boolean,\n): Promise<Settings> {\n // Same active-credential predicate the billing bypass uses, so provider\n // injection and billing can never disagree on what an \"active codex\" turn is.\n // The caller may pass `activeOverride` (a single, shared read; P2-b) so routing\n // and billing decide from the exact same observation, immune to a concurrent\n // disconnect/reconnect landing between two independent reads.\n const active =\n activeOverride ?? (await workspaceCodexSubscriptionActive(db, settings, workspaceId));\n if (!active) {\n return settings; // disabled / not connected / needs_relogin / error -> leave settings unchanged\n }\n const withProvider = withCodexProvider(settings);\n return withProvider;\n}\n\n/** Pure: append the synthetic codex-subscription provider, idempotently. */\nexport function withCodexProvider(settings: Settings): Settings {\n return withCodexCatalogProvider(settings);\n}\n\n/**\n * Pure: append the synthetic SuperGrok/xAI subscription provider,\n * idempotently. The overlay is catalogue metadata only; the exact account,\n * authority snapshot, and bearer remain frozen later at turn admission.\n */\nexport function withXaiSubscriptionProvider(settings: Settings): Settings {\n return withXaiSubscriptionCatalogProvider(settings);\n}\n\nexport async function settingsWithWorkspaceGatewayCredential(\n db: Database,\n accountId: string,\n workspaceId: string,\n settings: Settings,\n retainedProductModelId?: string | null,\n): Promise<Settings> {\n const activeCustomModels = await listWorkspaceGatewayCustomModels(db, {\n accountId,\n workspaceId,\n });\n const retainedUpstreamModelId = retainedProductModelId?.startsWith(\n WORKSPACE_GATEWAY_MODEL_ID_PREFIX,\n )\n ? retainedProductModelId.slice(WORKSPACE_GATEWAY_MODEL_ID_PREFIX.length)\n : null;\n const retainedCustomModel = retainedUpstreamModelId\n ? await getWorkspaceGatewayCustomModelForExecution(db, {\n accountId,\n workspaceId,\n upstreamModelId: retainedUpstreamModelId,\n })\n : null;\n const customModels =\n retainedCustomModel &&\n !activeCustomModels.some(\n (model) => model.upstreamModelId === retainedCustomModel.upstreamModelId,\n )\n ? [...activeCustomModels, retainedCustomModel]\n : activeCustomModels;\n const catalogSettings = withWorkspaceGatewayCatalogProvider(settings, customModels);\n const apiKey = await loadWorkspaceVercelAiGatewayApiKey(\n db,\n settings,\n workspaceId,\n retainedProductModelId,\n );\n return apiKey\n ? withWorkspaceGatewayCredential(catalogSettings, apiKey, customModels)\n : catalogSettings;\n}\n\nexport async function settingsWithWorkspaceOpenRouterCredential(\n db: Database,\n accountId: string,\n workspaceId: string,\n settings: Settings,\n retainedProductModelId?: string | null,\n): Promise<Settings> {\n const activeCustomModels = await listWorkspaceOpenRouterCustomModels(db, {\n accountId,\n workspaceId,\n });\n const retainedUpstreamModelId = retainedProductModelId?.startsWith(\n WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,\n )\n ? retainedProductModelId.slice(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX.length)\n : null;\n const retainedCustomModel = retainedUpstreamModelId\n ? await getWorkspaceOpenRouterCustomModelForExecution(db, {\n accountId,\n workspaceId,\n upstreamModelId: retainedUpstreamModelId,\n })\n : null;\n const customModels =\n retainedCustomModel &&\n !activeCustomModels.some(\n (model) => model.upstreamModelId === retainedCustomModel.upstreamModelId,\n )\n ? [...activeCustomModels, retainedCustomModel]\n : activeCustomModels;\n const catalogSettings = withWorkspaceOpenRouterCatalogProvider(settings, customModels);\n const apiKey = await loadWorkspaceOpenRouterApiKey(\n db,\n settings,\n workspaceId,\n retainedProductModelId,\n );\n return apiKey\n ? withWorkspaceOpenRouterCredential(catalogSettings, apiKey, customModels)\n : catalogSettings;\n}\n\nexport async function settingsWithOrganizationProviderCredentials(\n db: Database,\n accountId: string,\n workspaceId: string,\n settings: Settings,\n retainedProductModelId?: string | null,\n): Promise<Settings> {\n const buildModels = async (providerKind: \"vercel_gateway\" | \"openrouter\", prefix: string) => {\n const active = await listOrganizationModelProviderCustomModelsForWorkspace(db, {\n accountId,\n workspaceId,\n providerKind,\n });\n const upstreamModelId = retainedProductModelId?.startsWith(prefix)\n ? retainedProductModelId.slice(prefix.length)\n : null;\n const retained = upstreamModelId\n ? await getOrganizationModelProviderCustomModelForExecution(db, {\n accountId,\n workspaceId,\n providerKind,\n upstreamModelId,\n })\n : null;\n return retained && !active.some((model) => model.id === retained.id)\n ? [...active, retained]\n : active;\n };\n const gatewayModels = await buildModels(\"vercel_gateway\", ORGANIZATION_GATEWAY_MODEL_ID_PREFIX);\n const openRouterModels = await buildModels(\"openrouter\", ORGANIZATION_OPENROUTER_MODEL_ID_PREFIX);\n const gatewayKey = await loadOrganizationModelProviderApiKey(db, settings, {\n accountId,\n workspaceId,\n providerKind: \"vercel_gateway\",\n });\n const gatewaySettings = gatewayKey\n ? withOrganizationGatewayCredential(settings, gatewayKey, gatewayModels)\n : withOrganizationGatewayCatalogProvider(settings, gatewayModels);\n const openRouterKey = await loadOrganizationModelProviderApiKey(db, settings, {\n accountId,\n workspaceId,\n providerKind: \"openrouter\",\n });\n return openRouterKey\n ? withOrganizationOpenRouterCredential(gatewaySettings, openRouterKey, openRouterModels)\n : withOrganizationOpenRouterCatalogProvider(gatewaySettings, openRouterModels);\n}\n","// The Temporal adaptation of the op-stream durable-resume journal\n// (`OpStreamJournal`, @opengeni/runtime): the runtime leaf stays\n// Temporal-free; this is where its two seams bind to the activity.\n//\n// * `attachGeneration` — the consumer generation the runner fences zombie\n// consumers by. `Info.attempt` CANNOT serve here: `runAgentTurn` runs with\n// `maximumAttempts: 1`, so worker death is healed by the WORKFLOW\n// redispatching a NEW activity whose attempt is 1 again. The activity's\n// `currentAttemptScheduledTimestampMs` is Temporal-server-assigned and\n// strictly larger for a later dispatch (death detection is bounded below by\n// the 2-minute heartbeat timeout, far above ms resolution), so it is a\n// monotonic generation with zero workflow plumbing. Intra-activity\n// re-attaches (blip/gap heals) reuse it — the runner's equal-generation\n// replay path.\n//\n// * `persistSettled` — the durable-before-wire-ack ordering hook: fold the\n// settled op's frontier into the activity's shared heartbeat details and\n// flush a heartbeat BEFORE the client publishes the final ack. The shared\n// `details` object is the SAME one every other heartbeat site spreads, so a\n// later phase heartbeat re-carries the roster instead of clobbering it.\n\nimport type { Context } from \"@temporalio/activity\";\nimport type { OpStreamJournal } from \"@opengeni/runtime\";\n\n/** The activity's shared heartbeat-details object: every heartbeat call site\n * spreads THIS one object (plus its own phase), so fields like the op-ack\n * roster survive across sites instead of being lost to last-write-wins. */\nexport interface TurnHeartbeatDetails extends Record<string, unknown> {\n /** Settled-op roster: durable op id → its exit seq (the final-ack frontier). */\n opAcks: Record<string, string>;\n}\n\nexport function makeTurnOpJournal(\n context: Context | null,\n details: TurnHeartbeatDetails,\n): OpStreamJournal {\n return {\n attachGeneration: () => String(context?.info.currentAttemptScheduledTimestampMs ?? 1),\n persistSettled: (opId, exitSeq) => {\n details.opAcks[opId] = exitSeq;\n // Flush immediately (heartbeats are also sent on the 10s timer; this one\n // exists so the persist precedes the wire final ack, not just eventually).\n context?.heartbeat({ ...details, phase: \"op_settled\", at: new Date().toISOString() });\n },\n };\n}\n","import {\n connectionModelAllowed,\n getSessionGoal,\n acquireCodexCredentialLease,\n CodexCredentialLeaseAttemptFencedError,\n CodexCredentialFailoverExhaustedError,\n CODEX_CREDENTIAL_LEASE_TTL_MS,\n recordSessionActiveCodexCredential,\n setSessionCodexPinInTransaction,\n settleCodexCredentialFailover,\n withSessionCodexCapacityMutation,\n type CodexCredentialLeaseResult,\n type CodexCredentialLeaseSessionState,\n type CodexCredentialLeaseSelectionContext,\n} from \"@opengeni/db\";\nimport { type Settings } from \"@opengeni/config\";\nimport { CodexReloginRequired } from \"@opengeni/codex\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport {\n authoritativeCodexCapacityResetAt,\n classifyCodexPin,\n computeIdleDelayMs,\n isCodexCredentialEligible,\n selectCodexCredentialLeaseForTurn,\n type CodexRotationStrategy,\n type CodexTurnLeaseDecision,\n} from \"../codex-rotation\";\nimport {\n codexFleetShadowDecisionMetricLabelsV1,\n codexFleetShadowErrorMetricLabelsV1,\n publishCodexFleetShadowDecisionV1,\n} from \"../codex-fleet-shadow\";\nimport {\n armAndReconcileCodexCapacityWait,\n signalCodexCapacityWakeTargets,\n} from \"../codex-capacity\";\nimport type {\n TurnActivityServices as ActivityServices,\n RunAgentTurnInput,\n RunAgentTurnResult,\n} from \"../types\";\nimport { recordTurnStartupPhase } from \"../../observability-metrics\";\nimport { createTurnCredentialLeases } from \"./credential-leases\";\nimport { deliverFailedChildTurnToParent } from \"../parent-wake\";\nimport { randomUUID } from \"node:crypto\";\n\nimport { refreshCappedCodexUsageRows } from \"./codex\";\nimport { codexUsageLimitFailurePayload, CODEX_USAGE_LIMIT_MAX_RESUME_MS } from \"./errors\";\nimport type { ClaimTurnOk } from \"./claim\";\nimport type {\n AttemptIdentityState,\n BillingState,\n ClaimedResult,\n EventingState,\n ProviderTurnState,\n TurnControlState,\n} from \"./turn-context\";\n\nexport type CapacityPhaseDeps = {\n input: RunAgentTurnInput;\n settings: Settings;\n db: ActivityServices[\"db\"];\n bus: ActivityServices[\"bus\"];\n observability: ActivityServices[\"observability\"];\n wakeSessionWorkflow: ActivityServices[\"wakeSessionWorkflow\"];\n signalCodexCapacityWorkflow: ActivityServices[\"signalCodexCapacityWorkflow\"];\n cancellationSignal: AbortSignal | undefined;\n dispatchId: string;\n control: TurnControlState;\n attempt: AttemptIdentityState;\n billingState: BillingState;\n eventing: EventingState & {\n publish: NonNullable<EventingState[\"publish\"]>;\n settle: NonNullable<EventingState[\"settle\"]>;\n };\n providerTurn: ProviderTurnState;\n leases: ReturnType<typeof createTurnCredentialLeases>;\n claimedResult: ClaimedResult;\n acknowledgeLostAttemptOwnership: () => void;\n acknowledgeRecoveryQuiescence: () => void;\n setLastInputTokensFenced: (lastInputTokens: number | null) => Promise<void>;\n turn: ClaimTurnOk[\"turn\"];\n session: ClaimTurnOk[\"session\"];\n turnExecutionPolicy: ClaimTurnOk[\"turnExecutionPolicy\"];\n trigger: ClaimTurnOk[\"trigger\"];\n codexWorkspaceKey: string;\n};\n\nexport type CapacityPhaseOutcome = { exit: RunAgentTurnResult } | { ok: true };\n\nexport async function selectCodexTurnCapacity(\n deps: CapacityPhaseDeps,\n): Promise<CapacityPhaseOutcome> {\n const {\n input,\n settings,\n db,\n bus,\n observability,\n wakeSessionWorkflow,\n signalCodexCapacityWorkflow,\n dispatchId,\n control,\n attempt,\n billingState,\n eventing,\n providerTurn,\n leases,\n claimedResult,\n acknowledgeLostAttemptOwnership,\n turn,\n codexWorkspaceKey,\n } = deps;\n const turnId = attempt.turnId;\n const holderId = leases.codex.holderId;\n if (!turnId) {\n throw new Error(\"Turn id was not initialized\");\n }\n if (!holderId) {\n throw new Error(\"Codex lease holder was not initialized\");\n }\n\n if (billingState.isCodexTurn) {\n const credentialSelectionStartedAt = performance.now();\n let credentialSelectionOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n const selectForTurn = (\n context: CodexCredentialLeaseSelectionContext,\n lockedSessionCodexState: CodexCredentialLeaseSessionState,\n ) => {\n const allowed = context.accounts.filter((account) =>\n connectionModelAllowed(account.allowedModelIds, deps.turnExecutionPolicy.productModelId),\n );\n if (context.accounts.length > 0 && allowed.length === 0)\n throw new Error(\"This model is disabled for the connected Codex subscriptions\");\n const sessionPin = lockedSessionCodexState.pinnedCredentialId;\n if (\n sessionPin &&\n lockedSessionCodexState.pinSource !== \"policy\" &&\n context.accounts.some((account) => account.id === sessionPin) &&\n !allowed.some((account) => account.id === sessionPin)\n )\n throw new Error(\"This model is disabled for the pinned Codex subscription\");\n return selectCodexCredentialLeaseForTurn({\n context: { ...context, accounts: allowed },\n sessionId: input.sessionId,\n sessionPinnedCredentialId: lockedSessionCodexState.pinnedCredentialId,\n sessionPinSource: lockedSessionCodexState.pinSource,\n sessionLastCredentialId: lockedSessionCodexState.lastCredentialId,\n now: new Date(),\n });\n };\n\n let leaseAcquisitionStartedAtMs = performance.now();\n let leased: CodexCredentialLeaseResult<CodexTurnLeaseDecision> =\n await acquireCodexCredentialLease(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n dispatchId,\n expectedRedispatches: attempt.redispatchesAtDispatch,\n holderId,\n advanceActivePointer: true,\n },\n selectForTurn,\n );\n if (leased.decision.kind === \"allCapped\") {\n // Bounded self-heal of stale usage cache, then ONE new atomic selection.\n await refreshCappedCodexUsageRows(db, settings, input.workspaceId, leased.accounts, {\n signalCodexCapacityWorkflow,\n wakeSessionWorkflow,\n });\n leaseAcquisitionStartedAtMs = performance.now();\n leased = await acquireCodexCredentialLease(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n dispatchId,\n expectedRedispatches: attempt.redispatchesAtDispatch,\n holderId,\n advanceActivePointer: true,\n },\n selectForTurn,\n );\n }\n const lockedSessionCodexState = leased.sessionCodexState;\n providerTurn.codexPolicySnapshot = leased.codexPolicySnapshot;\n const sessionPin = lockedSessionCodexState.pinnedCredentialId;\n const sessionPinSource = lockedSessionCodexState.pinSource;\n const rotationDecision = leased.decision;\n const selectedPinDisposition = classifyCodexPin({\n pinnedCredentialId: sessionPin,\n pinSource: sessionPinSource,\n strategy: leased.rotationStrategy as CodexRotationStrategy,\n rotationEnabled: leased.rotationEnabled,\n });\n // pin policy pin persistence follows the atomic credential allocator selection. The selector\n // already ran exact-turn reuse before policy filtering and vetoed pointer\n // movement for manual/policy homes; this write only records the NEXT turn's\n // policy home (or clears a policy pin whose strategy is no longer active).\n if (\n !leased.codexPolicySnapshotReused &&\n selectedPinDisposition === \"sharded\" &&\n leased.credentialId !== null &&\n (sessionPinSource !== \"policy\" || sessionPin !== leased.credentialId)\n ) {\n const pinMutation = await withSessionCodexCapacityMutation(\n db,\n {\n workspaceId: input.workspaceId,\n reason: \"codex_policy_pin_changed\",\n },\n async (tx) => {\n const changed = await setSessionCodexPinInTransaction(\n tx,\n input.workspaceId,\n input.sessionId,\n leased.credentialId,\n \"policy\",\n {\n expected: {\n pinnedCredentialId: sessionPin,\n pinSource: sessionPinSource,\n },\n },\n );\n return { result: changed, changed };\n },\n );\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n pinMutation.wakeTargets,\n );\n } else if (selectedPinDisposition === \"clearStale\") {\n const pinMutation = await withSessionCodexCapacityMutation(\n db,\n {\n workspaceId: input.workspaceId,\n reason: \"codex_stale_policy_pin_cleared\",\n },\n async (tx) => {\n const changed = await setSessionCodexPinInTransaction(\n tx,\n input.workspaceId,\n input.sessionId,\n null,\n \"policy\",\n {\n expected: {\n pinnedCredentialId: sessionPin,\n pinSource: sessionPinSource,\n },\n },\n );\n return { result: changed, changed };\n },\n );\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n pinMutation.wakeTargets,\n );\n }\n providerTurn.effectiveCodexCredentialId = leased.credentialId;\n providerTurn.codexCredentialFailoverLimit = leased.failoverLimit;\n leases.codex.generation = leased.generation;\n leases.codex.confirmedUntilMs =\n leased.leasedUntil && leaseAcquisitionStartedAtMs !== null\n ? leaseAcquisitionStartedAtMs + CODEX_CREDENTIAL_LEASE_TTL_MS\n : null;\n leases.codex.held =\n providerTurn.effectiveCodexCredentialId !== null &&\n leased.holderId !== null &&\n leased.generation !== null &&\n leases.codex.confirmedUntilMs !== null;\n if (leases.codex.held) leases.codex.startHeartbeat();\n\n const actualOutcome = providerTurn.effectiveCodexCredentialId\n ? \"selected\"\n : rotationDecision.kind === \"allCapped\" || rotationDecision.kind === \"allocatorDisabled\"\n ? \"waiting\"\n : \"none\";\n const actualReason = providerTurn.effectiveCodexCredentialId\n ? leased.reused\n ? \"lease_reused\"\n : sessionPin === providerTurn.effectiveCodexCredentialId\n ? \"pin\"\n : rotationDecision.kind === \"active\" && rotationDecision.moved\n ? \"rotation\"\n : \"active\"\n : rotationDecision.kind === \"allCapped\"\n ? \"all_capped\"\n : rotationDecision.kind === \"allocatorDisabled\"\n ? \"allocator_disabled\"\n : \"none\";\n const fencedInFlight = leased.reused;\n const shadowResult = await publishCodexFleetShadowDecisionV1({\n enabled: settings.codexFleetPolicyShadowEnabled,\n decision: {\n accounts: leased.accounts,\n actualCredentialId: providerTurn.effectiveCodexCredentialId,\n actualOutcome,\n actualReason,\n affinityCredentialId: fencedInFlight\n ? providerTurn.effectiveCodexCredentialId\n : (sessionPin ?? lockedSessionCodexState.lastCredentialId ?? null),\n fencedInFlight,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\n now: new Date(),\n aliasSeed: randomUUID(),\n },\n publish: eventing.publish,\n });\n if (shadowResult.outcome === \"published\") {\n const shadowPayload = shadowResult.payload;\n observability.incrementCounter({\n name: \"opengeni_codex_fleet_shadow_decisions_total\",\n help: \"Shadow decisions by bounded actual/shadow outcome and comparison.\",\n labels: codexFleetShadowDecisionMetricLabelsV1(shadowPayload),\n });\n observability.info(\"Codex adaptive fleet shadow decision\", {\n workspaceId: input.workspaceId,\n policyVersion: shadowPayload.replay.policyVersion,\n inputFingerprint: shadowPayload.replay.inputFingerprint,\n decisionFingerprint: shadowPayload.replay.decisionFingerprint,\n actualOutcome: shadowPayload.actual.outcome,\n shadowOutcome: shadowPayload.replay.decision.outcome,\n comparison: shadowPayload.comparison,\n candidateCount: shadowPayload.replay.input.candidates.length,\n truncatedCandidateCount: shadowPayload.replay.truncatedCandidateCount,\n payloadBytes: shadowResult.payloadBytes,\n });\n } else if (shadowResult.outcome === \"failed\") {\n // Shadow observability is explicitly non-authoritative. A malformed\n // snapshot or event-write fault must never change the authoritative lease,\n // capacity wait, failover, or the account serving this fenced turn.\n observability.incrementCounter({\n name: \"opengeni_codex_fleet_shadow_errors_total\",\n help: \"Shadow decision build/publication failures.\",\n labels: codexFleetShadowErrorMetricLabelsV1(shadowResult),\n });\n observability.warn(\"Codex adaptive fleet shadow decision failed open\", {\n stage: shadowResult.stage,\n reason: shadowResult.reason,\n errorClass: \"CodexFleetShadowOperationError\",\n errorCode: \"codex_fleet_shadow_failed\",\n origin: \"worker\",\n payloadBytes: shadowResult.payloadBytes,\n });\n }\n\n const eligibleCount = leased.accounts.filter((account) =>\n isCodexCredentialEligible(account, new Date()),\n ).length;\n const poolDepth = eligibleCount === 0 ? \"zero\" : eligibleCount === 1 ? \"one\" : \"many\";\n observability.incrementCounter({\n name: \"opengeni_codex_pool_observations_total\",\n help: \"Observed eligible Codex pool depth buckets at turn selection.\",\n labels: { workspace_key: codexWorkspaceKey, depth: poolDepth },\n });\n if (eligibleCount <= 1) {\n observability.incrementCounter({\n name: \"opengeni_codex_pool_low_total\",\n help: \"Alert signal emitted when the eligible Codex pool is zero or one.\",\n labels: { workspace_key: codexWorkspaceKey, depth: poolDepth },\n });\n observability.warn(\"Codex eligible credential pool is low\", {\n workspaceId: input.workspaceId,\n eligibleCount,\n connectedCount: leased.accounts.length,\n depth: poolDepth,\n });\n }\n\n if (\n providerTurn.effectiveCodexCredentialId === null &&\n leased.accounts.length > 0 &&\n (rotationDecision.kind === \"allocatorDisabled\" ||\n leased.accounts.every((account) => !account.allocatorEnabled)) &&\n turnId\n ) {\n if (turn.source === \"compaction\") {\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.cancelled\",\n payload: {\n maintenance: \"context_compaction\",\n reason: \"codex_allocator_disabled\",\n requestPreserved: true,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"cancelled\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n control.turnMetricOutcome = \"cancelled\";\n control.activityStatus = \"idle\";\n return { exit: claimedResult({ status: \"idle\", deferredUntilWake: true }) };\n }\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId);\n const activeGoal = goal?.status === \"active\" ? goal : null;\n const evaluated = await armAndReconcileCodexCapacityWait(\n { db, bus },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n goalId: activeGoal?.id ?? null,\n goalVersion: activeGoal?.version ?? null,\n earliestResetAt: null,\n resetKind: \"mutation_only\",\n failurePayload: {\n error:\n rotationDecision.kind === \"allocatorDisabled\"\n ? \"The policy-selected Codex subscription is disabled for new allocations.\"\n : \"All connected Codex subscriptions are disabled for new allocations.\",\n code: \"codex_allocator_disabled\",\n detail:\n rotationDecision.kind === \"allocatorDisabled\"\n ? \"waiting for the selected credential to be re-enabled under the accepted source policy\"\n : \"waiting for a credential in the accepted source pool to be re-enabled, reconnected, or added\",\n },\n },\n );\n if (evaluated.action === \"resumed\") {\n control.turnMetricOutcome = \"recovering\";\n control.activityStatus = \"recovering\";\n return { exit: claimedResult({ status: \"recovering\" }) };\n }\n if (evaluated.action === \"waiting\") {\n control.turnMetricOutcome = \"recovering\";\n control.activityStatus = \"waiting_capacity\";\n return {\n exit: claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n waiterId: evaluated.waiter.id,\n generation: evaluated.waiter.generation,\n nextCheckAt: evaluated.waiter.nextCheckAt.toISOString(),\n wakeRevision: evaluated.waiter.wakeRevision,\n },\n }),\n };\n }\n acknowledgeLostAttemptOwnership();\n control.turnMetricOutcome = \"cancelled\";\n control.activityStatus = \"cancelled\";\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n\n if (rotationDecision.kind === \"none\") {\n if (\n leased.poolAccountCount === 0 &&\n !leased.codexPolicySnapshotReused &&\n leased.codexPolicySnapshot?.source !== \"disabled\"\n ) {\n // Preserve the established no-account behavior. The empty-string\n // token resolver used by the later model path raises this same typed\n // reconnect outcome, but capacity must not report success and defer\n // the failure to an unguarded provider setup.\n throw new CodexReloginRequired(\"No Codex subscription is connected for this workspace.\");\n }\n const noneReason =\n sessionPinSource === \"manual\" && sessionPin !== null\n ? {\n code: \"codex_manual_pin_unavailable\",\n error: \"The pinned Codex subscription is unavailable for this turn.\",\n detail:\n \"waiting for the pinned account to reconnect or become allocatable under the accepted source policy\",\n }\n : !leased.rotationEnabled && leased.activeCredentialId === null\n ? {\n code: \"codex_active_pointer_unavailable\",\n error: \"The Codex active subscription pointer is unavailable for this turn.\",\n detail:\n \"waiting for the accepted active account to be restored or become allocatable\",\n }\n : leased.poolAccountCount > leased.accounts.length\n ? {\n code: \"codex_policy_pool_unavailable\",\n error: \"No Codex subscription matches the accepted account-selection policy.\",\n detail:\n \"waiting for a matching credential to reconnect or become allocatable under the accepted source policy\",\n }\n : {\n code: \"codex_credential_unavailable\",\n error:\n \"No Codex subscription is currently available under the accepted policy.\",\n detail:\n \"waiting for a matching credential to reconnect or become allocatable under the accepted source policy\",\n };\n if (turn.source === \"compaction\") {\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.cancelled\",\n payload: {\n maintenance: \"context_compaction\",\n reason: noneReason.code,\n requestPreserved: true,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"cancelled\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n control.turnMetricOutcome = \"cancelled\";\n control.activityStatus = \"idle\";\n return { exit: claimedResult({ status: \"idle\", deferredUntilWake: true }) };\n }\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId);\n const activeGoal = goal?.status === \"active\" ? goal : null;\n const evaluated = await armAndReconcileCodexCapacityWait(\n { db, bus },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n goalId: activeGoal?.id ?? null,\n goalVersion: activeGoal?.version ?? null,\n earliestResetAt: null,\n resetKind: \"mutation_only\",\n failurePayload: {\n error: noneReason.error,\n code: noneReason.code,\n detail: noneReason.detail,\n },\n },\n );\n if (evaluated.action === \"resumed\") {\n control.turnMetricOutcome = \"recovering\";\n control.activityStatus = \"recovering\";\n return { exit: claimedResult({ status: \"recovering\" }) };\n }\n if (evaluated.action === \"waiting\") {\n control.turnMetricOutcome = \"recovering\";\n control.activityStatus = \"waiting_capacity\";\n return {\n exit: claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n waiterId: evaluated.waiter.id,\n generation: evaluated.waiter.generation,\n nextCheckAt: evaluated.waiter.nextCheckAt.toISOString(),\n wakeRevision: evaluated.waiter.wakeRevision,\n },\n }),\n };\n }\n acknowledgeLostAttemptOwnership();\n control.turnMetricOutcome = \"cancelled\";\n control.activityStatus = \"cancelled\";\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n\n if (rotationDecision.kind === \"allCapped\" && turnId) {\n if (turn.source === \"compaction\") {\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.cancelled\",\n payload: {\n maintenance: \"context_compaction\",\n reason: \"codex_capacity_unavailable\",\n requestPreserved: true,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"cancelled\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n control.turnMetricOutcome = \"cancelled\";\n control.activityStatus = \"idle\";\n return { exit: claimedResult({ status: \"idle\", deferredUntilWake: true }) };\n }\n // Every eligible account is capped/cooling (and a usage refresh did NOT\n // surface a reset): idle the turn AT THE BOUNDARY (no wasted model/sandbox\n // build) until the EARLIEST reset across all accounts — the multi-account\n // generalization of #143's single-account idle-until-reset. No saveRunState:\n // no model ran, nothing to freeze.\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId);\n const goalActive = Boolean(goal && goal.status === \"active\");\n // BOUNDED + POSITIVE: clamp to [MIN_IDLE_MS, max] so a null/elapsed/unknown\n // reset can never yield a 0 (which session.ts would treat as \"continue now\",\n // re-entering this path in a tight CPU/DB-hammering loop).\n const resumeMs = computeIdleDelayMs(\n rotationDecision.earliestResetAt,\n new Date(),\n CODEX_USAGE_LIMIT_MAX_RESUME_MS,\n );\n const allConnectedAccountsWereConsidered =\n leased.rotationEnabled && selectedPinDisposition !== \"manual\";\n const capacityDetail = allConnectedAccountsWereConsidered\n ? \"all connected Codex subscriptions are rate-limited\"\n : selectedPinDisposition === \"manual\"\n ? \"the pinned Codex subscription is rate-limited\"\n : \"the active Codex subscription is rate-limited\";\n const failurePayload = codexUsageLimitFailurePayload(\n { resetsInSeconds: Math.ceil(resumeMs / 1000) },\n capacityDetail,\n { allAccounts: allConnectedAccountsWereConsidered },\n );\n const authoritativeResetAt = authoritativeCodexCapacityResetAt(leased.accounts, new Date());\n const evaluated = await armAndReconcileCodexCapacityWait(\n { db, bus },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n goalId: goalActive && goal ? goal.id : null,\n goalVersion: goalActive && goal ? goal.version : null,\n earliestResetAt: authoritativeResetAt,\n resetKind: authoritativeResetAt ? \"authoritative\" : \"bounded_refresh\",\n failurePayload,\n },\n );\n if (evaluated.action === \"resumed\") {\n control.turnMetricOutcome = \"recovering\";\n control.activityStatus = \"recovering\";\n return { exit: claimedResult({ status: \"recovering\" }) };\n }\n if (evaluated.action === \"waiting\") {\n control.turnMetricOutcome = \"recovering\";\n control.activityStatus = \"waiting_capacity\";\n return {\n exit: claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n waiterId: evaluated.waiter.id,\n generation: evaluated.waiter.generation,\n nextCheckAt: evaluated.waiter.nextCheckAt.toISOString(),\n wakeRevision: evaluated.waiter.wakeRevision,\n },\n }),\n };\n }\n acknowledgeLostAttemptOwnership();\n control.turnMetricOutcome = \"cancelled\";\n control.activityStatus = \"cancelled\";\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n if (providerTurn.effectiveCodexCredentialId) {\n const priorAccountId = lockedSessionCodexState.lastCredentialId;\n if (priorAccountId !== providerTurn.effectiveCodexCredentialId) {\n await recordSessionActiveCodexCredential(\n db,\n input.workspaceId,\n input.sessionId,\n providerTurn.effectiveCodexCredentialId,\n );\n const rotated = rotationDecision.kind === \"active\" && rotationDecision.moved;\n await eventing.publish([\n {\n type: \"codex.account.switched\",\n payload: {\n fromAccountId: priorAccountId,\n toAccountId: providerTurn.effectiveCodexCredentialId,\n reason: rotated ? \"rotation\" : \"manual\",\n },\n },\n ]);\n }\n\n const selectionReason = leased.reused\n ? \"lease_reused\"\n : sessionPin === providerTurn.effectiveCodexCredentialId\n ? \"pin\"\n : rotationDecision.kind === \"active\" && rotationDecision.moved\n ? \"rotation\"\n : \"active\";\n observability.incrementCounter({\n name: \"opengeni_codex_credential_selections_total\",\n help: \"Codex credential selections by strategy and reason.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n strategy: leased.rotationStrategy,\n reason: selectionReason,\n },\n });\n await eventing.publish([\n {\n type: \"codex.credential.selected\",\n payload: {\n credentialId: providerTurn.effectiveCodexCredentialId,\n strategy: leased.rotationStrategy,\n reason: selectionReason,\n eligibleCount,\n connectedCount: leased.accounts.length,\n reused: leased.reused,\n },\n },\n ]);\n }\n } catch (error) {\n credentialSelectionOutcome = \"failed\";\n if (error instanceof CodexCredentialLeaseAttemptFencedError) {\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n if (error instanceof CodexCredentialFailoverExhaustedError) {\n const settlement = await settleCodexCredentialFailover(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n holderId: null,\n generation: null,\n expectedRedispatches: attempt.redispatchesAtDispatch,\n maxFailovers: error.maxFailovers,\n recoveryPayload: {\n triggerEventId: attempt.triggerEventId!,\n reason: \"codex_credential_failover_exhausted\",\n },\n failedPayload: {\n error:\n \"Automatic Codex credential failover stopped after every bounded account attempt was consumed. Send a new message after checking account health or capacity.\",\n code: \"codex_credential_failover_exhausted\",\n retryable: false,\n recovery: \"user_message\",\n failoverCount: error.failoverCount,\n maxFailovers: error.maxFailovers,\n },\n });\n if (settlement.action === \"limit_exceeded\") {\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n settlement.events,\n );\n control.activityStatus = \"idle\";\n control.turnMetricOutcome = \"failed\";\n await deliverFailedChildTurnToParent(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n turnId,\n );\n return { exit: claimedResult({ status: \"idle\" }) };\n }\n acknowledgeLostAttemptOwnership();\n control.activityStatus = \"cancelled\";\n control.turnMetricOutcome = \"cancelled\";\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"credential_selection\",\n provider: \"codex-subscription\",\n backend: turn.sandboxBackend,\n outcome: credentialSelectionOutcome,\n durationSeconds: (performance.now() - credentialSelectionStartedAt) / 1_000,\n });\n }\n }\n\n return { ok: true };\n}\n","import {\n DEFAULT_CODEX_FLEET_POLICY_V1,\n compareCodexFleetCanonicalStringsV1,\n createCodexFleetReplayRecordV1,\n type CodexFleetCandidateStatus,\n type CodexFleetDecisionInputV1,\n type CodexFleetReplayRecordV1,\n} from \"@opengeni/contracts\";\nimport type { CodexLeaseAccountStatus } from \"@opengeni/db\";\nimport { CancelledFailure } from \"@temporalio/activity\";\nimport { createHmac } from \"node:crypto\";\nimport { TurnAttemptFencedError } from \"./turn-attempt-fenced\";\n\nexport const CODEX_FLEET_SHADOW_MAX_PAYLOAD_BYTES = 34 * 1_024;\n\nexport type CodexFleetActualDecisionV1 = {\n outcome: \"selected\" | \"waiting\" | \"none\";\n candidateKey: string | null;\n reason:\n | \"lease_reused\"\n | \"pin\"\n | \"rotation\"\n | \"active\"\n | \"all_capped\"\n | \"allocator_disabled\"\n | \"none\";\n};\n\nexport type CodexFleetShadowComparisonV1 =\n | \"match\"\n | \"different_candidate\"\n | \"different_outcome\"\n | \"not_comparable_truncated\";\n\nexport type CodexFleetShadowPayloadV1 = {\n schemaVersion: 1;\n mode: \"shadow\";\n actual: CodexFleetActualDecisionV1;\n comparison: CodexFleetShadowComparisonV1;\n replay: CodexFleetReplayRecordV1;\n};\n\nexport type CodexFleetShadowBuildInputV1 = {\n accounts: readonly CodexLeaseAccountStatus[];\n actualCredentialId: string | null;\n actualOutcome: CodexFleetActualDecisionV1[\"outcome\"];\n actualReason: CodexFleetActualDecisionV1[\"reason\"];\n affinityCredentialId: string | null;\n fencedInFlight: boolean;\n nearExhaustionPct: number;\n now: Date;\n /** Per-event entropy used only to unlink account aliases; never persisted. */\n aliasSeed: string;\n};\n\nexport type CodexFleetShadowPublicationResultV1 =\n | { outcome: \"disabled\" }\n | {\n outcome: \"published\";\n payload: CodexFleetShadowPayloadV1;\n payloadBytes: number;\n }\n | {\n outcome: \"failed\";\n stage: \"build\" | \"serialize\" | \"publish\";\n reason: \"payload_too_large\" | \"unexpected\";\n errorName: string;\n payloadBytes: number | null;\n };\n\nexport const CODEX_FLEET_SHADOW_DECISION_MAX_METRIC_SERIES = 3 * 3 * 4 * 4 * 2;\nexport const CODEX_FLEET_SHADOW_ERROR_MAX_METRIC_SERIES = 3 * 2;\n\n/** Fixed low-cardinality labels; workspace/account/tenant identity is structurally absent. */\nexport function codexFleetShadowDecisionMetricLabelsV1(payload: CodexFleetShadowPayloadV1) {\n return {\n actual_outcome: payload.actual.outcome,\n shadow_outcome: payload.replay.decision.outcome,\n comparison: payload.comparison,\n confidence: payload.replay.decision.confidence,\n truncated: payload.replay.truncatedCandidateCount > 0 ? \"true\" : \"false\",\n } as const;\n}\n\nexport function codexFleetShadowErrorMetricLabelsV1(\n result: Extract<CodexFleetShadowPublicationResultV1, { outcome: \"failed\" }>,\n) {\n return { stage: result.stage, reason: result.reason } as const;\n}\n\n/**\n * Default-off, bounded, fail-open runtime seam for the shadow record.\n *\n * The typed result intentionally carries no error message: provider, database,\n * or transport errors can include private metadata. Callers may count/log only\n * the bounded stage, reason, name, and size fields returned here. A failure can\n * never replace or clear the credential already selected by the allocator.\n */\nexport async function publishCodexFleetShadowDecisionV1(input: {\n enabled: boolean;\n decision: CodexFleetShadowBuildInputV1;\n publish: (\n events: Array<{\n type: \"codex.fleet.decision\";\n payload: CodexFleetShadowPayloadV1;\n }>,\n ) => Promise<unknown>;\n}): Promise<CodexFleetShadowPublicationResultV1> {\n if (!input.enabled) return { outcome: \"disabled\" };\n\n let stage: \"build\" | \"serialize\" | \"publish\" = \"build\";\n let payloadBytes: number | null = null;\n try {\n const payload = buildCodexFleetShadowPayloadV1(input.decision);\n stage = \"serialize\";\n payloadBytes = new TextEncoder().encode(JSON.stringify(payload)).byteLength;\n if (payloadBytes > CODEX_FLEET_SHADOW_MAX_PAYLOAD_BYTES) {\n return {\n outcome: \"failed\",\n stage,\n reason: \"payload_too_large\",\n errorName: \"CodexFleetShadowPayloadTooLargeError\",\n payloadBytes,\n };\n }\n stage = \"publish\";\n await input.publish([{ type: \"codex.fleet.decision\", payload }]);\n return { outcome: \"published\", payload, payloadBytes };\n } catch (error) {\n // These are authoritative activity lifecycle signals, not shadow failures.\n // Swallowing either would allow a superseded attempt to continue mutating.\n if (error instanceof TurnAttemptFencedError || error instanceof CancelledFailure) throw error;\n return {\n outcome: \"failed\",\n stage,\n reason: \"unexpected\",\n errorName: safeErrorName(error),\n payloadBytes,\n };\n }\n}\n\nexport function buildCodexFleetShadowPayloadV1(\n input: CodexFleetShadowBuildInputV1,\n): CodexFleetShadowPayloadV1 {\n // Randomized keyed ordering makes c00/c01 unlinkable across events while the\n // supplied event seed keeps this one replay/payload build deterministic.\n const eventAccounts = [...input.accounts].sort(\n (left, right) =>\n compareCodexFleetCanonicalStringsV1(\n aliasSortKey(input.aliasSeed, left.id),\n aliasSortKey(input.aliasSeed, right.id),\n ) || compareCodexFleetCanonicalStringsV1(left.id, right.id),\n );\n const aliases = new Map(\n eventAccounts.map((account, index) => [account.id, candidateAlias(index)] as const),\n );\n const actualCandidateKey = input.actualCredentialId\n ? (aliases.get(input.actualCredentialId) ?? null)\n : null;\n const currentCandidateKey = input.affinityCredentialId\n ? (aliases.get(input.affinityCredentialId) ?? null)\n : null;\n const decisionInput: CodexFleetDecisionInputV1 = {\n observedAtMs: input.now.getTime(),\n request: {\n placement: input.fencedInFlight ? \"fenced_in_flight\" : \"new\",\n priority: \"standard\",\n currentCandidateKey: input.fencedInFlight ? actualCandidateKey : currentCandidateKey,\n waitAgeMs: 0,\n overlayKey: null,\n overlayMode: \"none\",\n },\n admission: {\n // The shadow policy does not invent hard capacity from account count. A later typed\n // admission snapshot supplies dynamic capacity; shadow v1 records unknown.\n dynamicCapacityUnits: null,\n inUseUnits: input.accounts.reduce((sum, account) => sum + account.activeLeaseCount, 0),\n queuedManagerCount: 0,\n emergencyFuseActive: false,\n },\n candidates: eventAccounts.map((account, index) => ({\n key: candidateAlias(index),\n status: normalizeStatus(account.status),\n allocatorEnabled: account.allocatorEnabled,\n cooldownRemainingMs: remainingMs(account.exhaustedUntil, input.now),\n activeLeaseCount: account.activeLeaseCount,\n quota: {\n primary: {\n usedPercent: account.primaryUsedPercent,\n resetRemainingMs: remainingMs(account.primaryResetAt, input.now),\n },\n secondary: {\n usedPercent: account.secondaryUsedPercent,\n resetRemainingMs: remainingMs(account.secondaryResetAt, input.now),\n },\n checkedAgeMs: ageMs(account.usageCheckedAt, input.now),\n confidence: quotaConfidence(account),\n },\n // Current production cache evidence is aggregate metric + opaque log data,\n // not allocator state. Preserve that gap as unknown instead of fabricating 0.\n cache: {\n hitRatio: null,\n sampledTokens: null,\n checkedAgeMs: null,\n confidence: \"unknown\",\n state: \"unknown\",\n thresholdObservedForMs: null,\n },\n // The shadow policy has no typed workspace-local burn feed at this boundary yet.\n observedBurn: {\n primaryPercentPerHour: null,\n secondaryPercentPerHour: null,\n confidence: \"unknown\",\n },\n // Provider accounting has not supplied a typed burn observation yet.\n // Unknown inference is explicit and contributes no fabricated tenant truth.\n inferredUnexplainedBurn: {\n primaryPercentPerHour: null,\n secondaryPercentPerHour: null,\n confidence: \"unknown\",\n },\n overlayKeys: [],\n })),\n };\n const replay = createCodexFleetReplayRecordV1(decisionInput, {\n ...DEFAULT_CODEX_FLEET_POLICY_V1,\n placementUsageCeilingPercent: input.nearExhaustionPct,\n });\n const actual: CodexFleetActualDecisionV1 = {\n outcome: input.actualOutcome,\n candidateKey: actualCandidateKey,\n reason: input.actualReason,\n };\n return {\n schemaVersion: 1,\n mode: \"shadow\",\n actual,\n comparison: compareDecision(actual, replay),\n replay,\n };\n}\n\nfunction compareDecision(\n actual: CodexFleetActualDecisionV1,\n replay: CodexFleetReplayRecordV1,\n): CodexFleetShadowComparisonV1 {\n if (\n replay.truncatedCandidateCount > 0 &&\n actual.candidateKey !== null &&\n !replay.input.candidates.some((candidate) => candidate.key === actual.candidateKey)\n ) {\n return \"not_comparable_truncated\";\n }\n const shadowOutcome = replay.decision.outcome === \"selected\" ? \"selected\" : \"none\";\n const actualComparableOutcome = actual.outcome === \"selected\" ? \"selected\" : \"none\";\n if (shadowOutcome !== actualComparableOutcome) return \"different_outcome\";\n if (shadowOutcome === \"selected\") {\n return replay.decision.selectedCandidateKey === actual.candidateKey\n ? \"match\"\n : \"different_candidate\";\n }\n return \"match\";\n}\n\nfunction normalizeStatus(status: string): CodexFleetCandidateStatus {\n if (status === \"active\" || status === \"needs_relogin\" || status === \"error\") return status;\n return \"unknown\";\n}\n\nfunction candidateAlias(index: number): string {\n return `c${index.toString(36).padStart(2, \"0\")}`;\n}\n\nfunction aliasSortKey(seed: string, credentialId: string): string {\n return createHmac(\"sha256\", seed).update(credentialId).digest(\"hex\");\n}\n\nfunction quotaConfidence(account: CodexLeaseAccountStatus): \"unknown\" | \"low\" | \"medium\" | \"high\" {\n if (!account.usageCheckedAt) return \"unknown\";\n const windows = [\n [account.primaryUsedPercent, account.primaryResetAt],\n [account.secondaryUsedPercent, account.secondaryResetAt],\n ] as const;\n const complete = windows.filter(([used, reset]) => used !== null && reset !== null).length;\n const partial = windows.some(([used, reset]) => (used === null) !== (reset === null));\n if (complete === 0) return \"unknown\";\n if (partial) return \"low\";\n return complete === windows.length ? \"high\" : \"medium\";\n}\n\nfunction remainingMs(value: Date | null, now: Date): number | null {\n return value ? Math.max(0, value.getTime() - now.getTime()) : null;\n}\n\nfunction ageMs(value: Date | null, now: Date): number | null {\n return value ? Math.max(0, now.getTime() - value.getTime()) : null;\n}\n\nfunction safeErrorName(error: unknown): string {\n if (!(error instanceof Error)) return \"UnknownError\";\n return /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(error.name) ? error.name : \"Error\";\n}\n","import {\n materializeRigVersionForAttempt,\n getWorkspaceModelPolicy,\n getFilesForSubject,\n getWorkspace,\n resolveCompanyBrainContextSelection,\n getGeneratedVideoArtifact,\n listSessionSystemUpdatesForTurn,\n getOrCreateCompanyProfileSnapshot,\n getOrCreatePreferenceRegistrySnapshot,\n getOrCreateWorkspaceInstructionPolicySnapshot,\n PreferenceRegistryInitiatorError,\n resolveSessionAttemptPersonalResources,\n} from \"@opengeni/db\";\nimport {\n projectHistoryForProvider,\n restoreGenericDispatchHistoryItems,\n projectModelInputForCapabilities,\n hasActiveWorkspaceInstructionPolicy,\n renderWorkspaceGovernanceContext,\n type OpenGeniRuntime,\n} from \"@opengeni/runtime\";\nimport { settingsWithResolvedModelContext, type Settings } from \"@opengeni/config\";\nimport { settingsWithSessionMcpServersForRun } from \"../capabilities\";\nimport { resolveRigProviderImageForRun } from \"@opengeni/core\";\nimport { resolveWorkspacePackRuntime, settingsWithPackSandboxImage } from \"../packs\";\nimport { createModelHistoryAttachmentProjector } from \"../run-input\";\nimport type {\n TurnActivityServices as ActivityServices,\n RunAgentTurnInput,\n RunAgentTurnResult,\n} from \"../types\";\nimport {\n buildCompanyBrainContributionReceipt,\n summarizeCompanyBrainContributions,\n} from \"../../model-context-contributions\";\nimport {\n collectGeneratedImageReceipts,\n projectGeneratedImageHistoryForModel,\n} from \"../generated-images\";\nimport { createTurnMediaArtifacts } from \"./media-artifacts\";\nimport { retryWhileMissing } from \"@opengeni/storage\";\nimport { WorkspaceModelPolicyBlockedError } from \"@opengeni/runtime\";\nimport {\n evaluateWorkspaceModelPolicy,\n resolveWorkspaceAgentHumanInputEnabled,\n type MediaGenerationResult,\n} from \"@opengeni/contracts\";\n\nimport { assertWorkspaceHumanInputAllowed } from \"./admission\";\nimport {\n lazyToolTransportForTurn,\n openAiHostedImageProviderBindingForTurn,\n modelAttachmentInputPolicyForTurn,\n} from \"./tool-policy\";\n\nimport type { ClaimTurnOk } from \"./claim\";\nimport type { EventingState, WorkspaceRefState } from \"./turn-context\";\n\nexport type GovernanceModelDeps = {\n input: RunAgentTurnInput;\n db: ActivityServices[\"db\"];\n runtime: ActivityServices[\"runtime\"];\n objectStorage: ActivityServices[\"objectStorage\"];\n eventing: EventingState;\n workspaceRefs: WorkspaceRefState;\n media: ReturnType<typeof createTurnMediaArtifacts>;\n turn: ClaimTurnOk[\"turn\"];\n session: ClaimTurnOk[\"session\"];\n capabilitySettings: ClaimTurnOk[\"capabilitySettings\"];\n fileAuthoritySubjectId: ClaimTurnOk[\"fileAuthoritySubjectId\"];\n humanInputResume: ClaimTurnOk[\"humanInputResume\"];\n turnExecutionPolicy: ClaimTurnOk[\"turnExecutionPolicy\"];\n requiredGeneratedVideoFiles: Array<{\n operationId: string;\n artifactId: string;\n fileId: string;\n objectKey: string;\n sizeBytes: number;\n sha256: string;\n filename: string;\n }>;\n};\n\nexport type GovernanceModelOk = {\n runtimePreparationStartedAt: number;\n packRuntime: Awaited<ReturnType<typeof resolveWorkspacePackRuntime>>;\n rigVersion:\n | NonNullable<Awaited<ReturnType<typeof materializeRigVersionForAttempt>>>[\"version\"]\n | null;\n rigName: string | null;\n agentHumanInputEnabled: boolean;\n workspaceAgentInstructions: string | null | undefined;\n workspaceGovernance: ReturnType<typeof renderWorkspaceGovernanceContext>;\n structuredWorkspacePolicyActive: boolean;\n workspaceMemory: string | null | undefined;\n buildCompanyBrainContributionReceiptFor: (\n skillCatalogText: string,\n ) => ReturnType<typeof buildCompanyBrainContributionReceipt>;\n logicalSandboxSettings: Settings;\n verifiedRigProviderImageId: string | undefined;\n runSettings: Settings;\n resolvedModel: ReturnType<OpenGeniRuntime[\"resolveTurnModel\"]>;\n providerApi:\n | NonNullable<ReturnType<OpenGeniRuntime[\"resolveTurnModel\"]>>[\"provider\"][\"api\"]\n | \"responses\";\n nativeImageProviderBinding: ReturnType<typeof openAiHostedImageProviderBindingForTurn>;\n lazyToolTransport: ReturnType<typeof lazyToolTransportForTurn>;\n modelInputPolicy: ReturnType<typeof modelAttachmentInputPolicyForTurn>;\n supportsImageInput: boolean;\n modelHistoryProjector: (\n items: Array<Record<string, unknown>>,\n projectionOptions?: Parameters<ReturnType<typeof createModelHistoryAttachmentProjector>>[1],\n ) => Promise<Array<Record<string, unknown>>>;\n generatedImageHistoryProjector: (\n items: Array<Record<string, unknown>>,\n ) => Promise<Array<Record<string, unknown>>>;\n compactionModelHistoryProjector: (\n items: Array<Record<string, unknown>>,\n ) => Promise<Array<Record<string, unknown>>>;\n};\n\nexport type GovernanceModelOutcome = { exit: RunAgentTurnResult } | { ok: GovernanceModelOk };\n\ntype PreferenceSnapshotTurn = Pick<ClaimTurnOk[\"turn\"], \"initiatingHumanSubjectId\" | \"initiator\">;\n\nexport function preferenceSnapshotHumanSubjectId(turn: PreferenceSnapshotTurn): string | null {\n return (\n turn.initiatingHumanSubjectId ??\n (turn.initiator.kind === \"subject\" ? turn.initiator.subjectId : null)\n );\n}\n\n/**\n * Preferences are scoped partly to the frozen initiating human. A service-only\n * turn has no such scope, so avoid calling the human-bound snapshot capability\n * merely to catch its expected authority rejection.\n */\nexport async function preferenceSnapshotForTurn<T>(\n turn: PreferenceSnapshotTurn,\n load: () => Promise<T>,\n): Promise<T | null> {\n if (!preferenceSnapshotHumanSubjectId(turn)) return null;\n try {\n return await load();\n } catch (error) {\n if (error instanceof PreferenceRegistryInitiatorError) return null;\n throw error;\n }\n}\n\nexport async function prepareGovernanceAndModel(\n deps: GovernanceModelDeps,\n): Promise<GovernanceModelOutcome> {\n const {\n input,\n db,\n runtime,\n objectStorage,\n eventing,\n workspaceRefs,\n media,\n turn,\n session,\n capabilitySettings,\n fileAuthoritySubjectId,\n humanInputResume,\n turnExecutionPolicy,\n requiredGeneratedVideoFiles,\n } = deps;\n\n const runtimePreparationStartedAt = performance.now();\n\n // Personal Rig/Variable Set authority is revalidated immediately before\n // any direct resource read. The database function is a zero-row no-op for\n // sessions with no personal resources, preserving the legacy workspace path.\n await resolveSessionAttemptPersonalResources(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: fileAuthoritySubjectId,\n attemptId: input.attemptId,\n });\n\n const governanceClaims = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: turn.executionGeneration,\n };\n // Independent workspace reads after the personal-resource fence. Pack,\n // installed skills, frozen rig, governance snapshots, and model policy do\n // not depend on each other. Company-brain selection still waits on the\n // snapshots below so its receipt stays exact.\n const [\n packRuntime,\n rigMaterialization,\n [workspace, companyProfileSnapshot, instructionPolicySnapshot, preferenceSnapshot],\n workspaceModelPolicy,\n ] = await Promise.all([\n resolveWorkspacePackRuntime(db, input.workspaceId),\n session.rigId && session.rigVersionId\n ? (async () =>\n await materializeRigVersionForAttempt(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: fileAuthoritySubjectId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: turn.executionGeneration,\n }))()\n : Promise.resolve(null),\n Promise.all([\n getWorkspace(db, input.workspaceId),\n getOrCreateCompanyProfileSnapshot(db, governanceClaims),\n getOrCreateWorkspaceInstructionPolicySnapshot(db, governanceClaims),\n preferenceSnapshotForTurn(\n turn,\n async () => await getOrCreatePreferenceRegistrySnapshot(db, governanceClaims),\n ),\n ]),\n getWorkspaceModelPolicy(db, input.workspaceId),\n ]);\n const rigVersion = rigMaterialization?.version ?? null;\n // Rig display name for the doctrine block + setup events/errors (only on a\n // rig-bound turn; null-safe fallback keeps the turn alive if the rig row is\n // gone). Loaded once here alongside the version.\n const rigName = rigVersion ? (rigMaterialization?.rigName ?? \"rig\") : null;\n // Telemetry: stamp the frozen rig binding (empty for a rig-less turn).\n workspaceRefs.rigId = session.rigId ?? \"\";\n workspaceRefs.rigVersionId = session.rigVersionId ?? \"\";\n if (!workspace) throw new Error(`Workspace not found: ${input.workspaceId}`);\n const agentHumanInputEnabled = resolveWorkspaceAgentHumanInputEnabled(workspace.settings);\n const contextSelection = await resolveCompanyBrainContextSelection(db, governanceClaims);\n const workspaceAgentInstructions = contextSelection.legacyWorkspaceInstructions;\n const memoryPromptMode = contextSelection.receipt.memoryPromptMode;\n assertWorkspaceHumanInputAllowed(agentHumanInputEnabled, \"resume\", humanInputResume !== null);\n const companyProfileIncluded = contextSelection.receipt.companyProfileIncluded;\n const workspaceGovernance = renderWorkspaceGovernanceContext(\n {\n companyProfile: companyProfileSnapshot,\n instructionPolicy: instructionPolicySnapshot,\n preferences: preferenceSnapshot,\n },\n {\n includeCompanyProfile: companyProfileIncluded,\n sharedSkillReader: true,\n },\n );\n const structuredWorkspacePolicyActive =\n hasActiveWorkspaceInstructionPolicy(instructionPolicySnapshot);\n const workspaceMemory = contextSelection.workspaceMemory;\n const buildCompanyBrainContributionReceiptFor = (skillCatalogText: string) =>\n buildCompanyBrainContributionReceipt({\n contextSelectionReceiptId: contextSelection.receipt.id,\n attemptId: input.attemptId,\n turnId: turn.id,\n nestedAgentDepth: session.nestedAgentDepth,\n memoryPromptMode,\n instructionPolicy: instructionPolicySnapshot,\n workspaceAgentInstructions,\n preferences: preferenceSnapshot,\n companyProfile: companyProfileSnapshot,\n companyProfileIncluded,\n workspaceMemory,\n skillActivations: [],\n skillCatalogText,\n });\n try {\n // Portable operator compaction runs before tool/skill preparation, so its\n // exact Company Brain prefix contains governance and standing memory but\n // no runtime skill catalog. Later compaction paths replace this summary\n // after the complete skill activation set is resolved.\n eventing.companyBrainContextContributions = summarizeCompanyBrainContributions(\n buildCompanyBrainContributionReceiptFor(\"\"),\n );\n } catch {\n // Contribution telemetry must never change model execution semantics.\n }\n // A Rig is always a setup/check layer over the deployment platform sandbox.\n // The pre-v2 Pack image path remains only for rig-less compatibility sessions.\n const logicalSandboxSettings = rigVersion\n ? capabilitySettings\n : settingsWithPackSandboxImage(\n capabilitySettings,\n packRuntime.sandboxImage,\n packRuntime.sandboxProviderImages,\n );\n const providerImageSelection = await resolveRigProviderImageForRun(\n logicalSandboxSettings,\n rigVersion,\n turn.sandboxBackend,\n );\n const providerImageSettings = providerImageSelection.settings;\n const verifiedRigProviderImageId =\n providerImageSelection.reason === \"selected\"\n ? (providerImageSelection.imageId ?? undefined)\n : undefined;\n const baseRunSettings = {\n // IMAGE PRECEDENCE: a Rig uses the deployment platform base; a rig-less\n // pre-v2 Pack may retain its compatibility image. A matching verified\n // provider-native ID is then applied only to fresh creation without\n // changing the logical lease image.\n ...providerImageSettings,\n openaiModel: turn.model,\n openaiReasoningEffort: turn.reasoningEffort,\n sandboxBackend: turn.sandboxBackend,\n };\n const runSettings = await settingsWithSessionMcpServersForRun(\n db,\n input.workspaceId,\n input.sessionId,\n input.attemptId,\n baseRunSettings,\n );\n\n // Multi-provider per-turn routing → the provider gating (compaction mode,\n // hosted web search, encrypted reasoning, context window) the agent and\n // compaction summarizer must use; null falls back to the legacy global\n // client. Resolve against `capabilitySettings` (whose openaiModel is the\n // deployment default), NOT `runSettings`: runSettings.openaiModel is the\n // turn's model, so for a turn ON a registry model the built-in provider\n // would otherwise claim that id (configuredModels builds the built-in's\n // models from openaiModel) and shadow the registry entry — resolving the\n // turn to the built-in (Azure) gating while the global model router routes\n // the name to its registry provider. That mismatch attaches web_search to\n // a chat-only Fireworks model. Resolving against the default-model settings\n // keeps gating consistent with the router. Cost accounting covers registry\n // models via configuredModelPricing.\n const resolvedModel = runtime.resolveTurnModel(\n capabilitySettings,\n turnExecutionPolicy.productModelId,\n );\n const providerApi = resolvedModel?.provider.api ?? \"responses\";\n const nativeImageProviderBinding =\n providerApi === \"responses\"\n ? openAiHostedImageProviderBindingForTurn(capabilitySettings, resolvedModel)\n : null;\n const lazyToolTransport = lazyToolTransportForTurn(resolvedModel);\n const modelInputPolicy = modelAttachmentInputPolicyForTurn(resolvedModel);\n // Use the proven wire capability, not the catalogue modality alone. Chat\n // providers may advertise vision, but OpenGeni intentionally has no typed\n // image transport for that wire yet; exposing view_image there would turn\n // pixels into a multi-megabyte text/base64 function result.\n const supportsImageInput = modelInputPolicy.supportsImageInput;\n media.modelCanReceiveRetainedSessionImages = supportsImageInput;\n const attachmentProjector = createModelHistoryAttachmentProjector(\n modelInputPolicy,\n objectStorage\n ? async (file) => {\n const object = await retryWhileMissing(async () =>\n objectStorage.getObjectBytes(file.objectKey),\n );\n if (!object) throw new Error(\"attachment object is missing\");\n return object.bytes;\n }\n : undefined,\n (fileIds) =>\n getFilesForSubject(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: fileAuthoritySubjectId,\n fileIds,\n }),\n );\n const modelHistoryProjector = async (\n items: Array<Record<string, unknown>>,\n projectionOptions?: Parameters<typeof attachmentProjector>[1],\n ) =>\n projectModelInputForCapabilities(\n await attachmentProjector(items, projectionOptions),\n modelInputPolicy,\n );\n const generatedImageHistoryProjector = async (\n items: Array<Record<string, unknown>>,\n ): Promise<Array<Record<string, unknown>>> => {\n collectGeneratedImageReceipts(items, media.generatedImageReceiptsByProviderItemId);\n return projectGeneratedImageHistoryForModel(items);\n };\n const compactionModelHistoryProjector = async (items: Array<Record<string, unknown>>) =>\n await modelHistoryProjector(\n projectHistoryForProvider(\n await generatedImageHistoryProjector(restoreGenericDispatchHistoryItems(items)),\n providerApi,\n ),\n );\n // Bind the provider/model catalog's context policy to every model-facing\n // path for this turn. In particular, Codex subscription turns must not\n // inherit the deployment's OpenAI/Azure mode or 1.05M context defaults:\n // raw window, effective ceiling, and auto-compact limit are distinct live\n // catalog values and must reach pre-turn compaction, history guards, and\n // every model call together.\n eventing.modelRunSettings = resolvedModel\n ? settingsWithResolvedModelContext(runSettings, resolvedModel.configured)\n : runSettings;\n // WORKSPACE MODEL POLICY — the authoritative hard gate. Runs immediately\n // after resolution and BEFORE any model call (the compaction summarizer\n // and the main run both come later in this scope), so a blocked\n // provider/model can never be reached through ANY stamp path: explicit\n // turn model, inherited session default, goal-continuation inheritance,\n // or the legacy null-resolution fallback. The frozen execution policy is\n // the attribution source even if an injected test runtime returns no\n // concrete resolved model. Fail-loud, never a silent remap.\n {\n if (workspaceModelPolicy) {\n const verdict = evaluateWorkspaceModelPolicy(workspaceModelPolicy, {\n providerId: turnExecutionPolicy.providerId,\n modelId: turnExecutionPolicy.productModelId,\n });\n if (!verdict.allowed) {\n throw new WorkspaceModelPolicyBlockedError(\n turnExecutionPolicy.productModelId,\n turnExecutionPolicy.providerId,\n verdict.reason,\n );\n }\n }\n }\n // A recovered asynchronous video completion is model-visible only after\n // its durable File is present at the exact sandbox path carried by the\n // receipt. Resolve and verify the claimed update before sandbox policy is\n // chosen so this turn cannot remain lazy and expose an absent path.\n for (const update of await listSessionSystemUpdatesForTurn(\n db,\n input.workspaceId,\n input.sessionId,\n turn.id,\n )) {\n const payload = update.payload as MediaGenerationResult;\n if (payload.type !== \"media_generation_result\" || payload.status !== \"ready\") continue;\n const retained = await getGeneratedVideoArtifact(\n db,\n input.workspaceId,\n payload.receipt.artifact.artifactId,\n );\n if (\n !retained ||\n retained.artifact.deletedAt ||\n retained.file.status !== \"ready\" ||\n retained.file.contentType !== \"video/mp4\" ||\n retained.file.sizeBytes !== payload.receipt.artifact.originalBytes ||\n retained.file.sha256 !== payload.receipt.artifact.sha256 ||\n retained.artifact.sandboxFilename !== `generated-video-${retained.artifact.id}.mp4`\n ) {\n throw new Error(\"Generated video completion does not match its retained File\");\n }\n requiredGeneratedVideoFiles.push({\n operationId: payload.operationId,\n artifactId: retained.artifact.id,\n fileId: retained.file.id,\n objectKey: retained.file.objectKey,\n sizeBytes: retained.file.sizeBytes,\n sha256: retained.file.sha256,\n filename: retained.artifact.sandboxFilename,\n });\n }\n\n return {\n ok: {\n runtimePreparationStartedAt,\n packRuntime,\n rigVersion,\n rigName,\n agentHumanInputEnabled,\n workspaceAgentInstructions,\n workspaceGovernance,\n structuredWorkspacePolicyActive,\n workspaceMemory,\n buildCompanyBrainContributionReceiptFor,\n logicalSandboxSettings,\n verifiedRigProviderImageId,\n runSettings,\n resolvedModel,\n providerApi,\n nativeImageProviderBinding,\n lazyToolTransport,\n modelInputPolicy,\n supportsImageInput,\n modelHistoryProjector,\n generatedImageHistoryProjector,\n compactionModelHistoryProjector,\n },\n };\n}\n","import {\n desktopCapableBackend,\n type ComputerToolMode,\n type LazyToolTransport,\n} from \"@opengeni/runtime\";\nimport {\n isDirectOpenAiApiBaseUrl,\n type ModelProviderApi,\n type ResolvedModelProvider,\n type Settings,\n} from \"@opengeni/config\";\nimport { type ModelAttachmentInputPolicy } from \"../run-input\";\nimport { imageProviderBindingHash } from \"../image-generation-operation\";\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 * Computer-use is ordinary `computer_*` function tools bound to the live\n * desktop. The worker picks the mode from the resolved provider so the runtime\n * never string-sniffs the model instance:\n * • catalogue `inputModalities` must include `image`, or computer-use is off\n * • Responses wires (Azure/OpenAI, Gateway, Codex, legacy client) →\n * \"function-image\": screenshot results are structured `{type:'image'}`\n * • Chat Completions → \"disabled\": tool results on that wire are text, so a\n * screenshot would become a base64 string rather than an image the model sees\n *\n * Pure + exported so the mapping is unit-testable without a live turn.\n */\nexport function computerToolModeForTurn(\n resolvedModel: {\n provider: { kind: ResolvedModelProvider[\"kind\"]; api: ModelProviderApi };\n configured: { capabilities: { inputModalities: string[] } };\n } | null,\n): ComputerToolMode {\n if (!resolvedModel) {\n return \"function-image\";\n }\n if (!modelSupportsImageInputForTurn(resolvedModel)) {\n return \"disabled\";\n }\n if (resolvedModel.provider.kind === \"codex-subscription\") {\n return \"function-image\";\n }\n if (resolvedModel.provider.api === \"chat\") {\n return \"disabled\";\n }\n return \"function-image\";\n}\n\n/** Chat wires and Gateway models do not advertise OpenAI's hosted sandbox tool types. */\nexport function structuredToolTransportForTurn(\n resolvedModel: {\n provider: {\n id: string;\n kind: ResolvedModelProvider[\"kind\"];\n api: ModelProviderApi;\n wireProfile: \"openai\" | \"azure-openai\";\n builtin: boolean;\n baseUrl?: string | undefined;\n };\n } | null,\n): boolean {\n if (!resolvedModel) return true;\n const provider = resolvedModel.provider;\n if (provider.api === \"chat\" || provider.kind === \"codex-subscription\") return false;\n return (\n provider.wireProfile === \"azure-openai\" ||\n (provider.builtin && provider.id === \"openai\" && provider.baseUrl === undefined)\n );\n}\n\n/**\n * Progressive tool disclosure is universal for supported OpenGeni turns; only\n * its contained transport differs. Codex keeps its native path, built-in direct\n * OpenAI/Azure Responses use native client tool search, and every other ordinary\n * function-calling provider uses OpenGeni's stable search/invoke dispatcher.\n */\nexport function lazyToolTransportForTurn(\n resolvedModel: {\n provider: {\n id: string;\n kind: ResolvedModelProvider[\"kind\"];\n api: ModelProviderApi;\n wireProfile: \"openai\" | \"azure-openai\";\n builtin: boolean;\n baseUrl?: string | undefined;\n };\n } | null,\n): LazyToolTransport {\n if (!resolvedModel) return \"openai_native\";\n const provider = resolvedModel.provider;\n if (provider.kind === \"codex-subscription\") return \"codex_native\";\n const isNativeResponsesProvider =\n provider.api === \"responses\" &&\n (provider.wireProfile === \"azure-openai\" ||\n (provider.builtin && provider.id === \"openai\" && provider.baseUrl === undefined));\n if (isNativeResponsesProvider) {\n return \"openai_native\";\n }\n return \"generic_dispatch\";\n}\n\n/** Only brand-new lazy-capable turns may overlap non-eager tool preparation. */\nexport function shouldDeferNonEagerToolPreparation(args: {\n lazyToolTransport: LazyToolTransport | null;\n progressiveDisclosureEnabled: boolean;\n /** Retained for call-site compatibility; the lazy runtime now gates artifact\n * and ordinary function calls on the same exact preparation promise. */\n artifactRuntimeAvailable: boolean;\n triggerKind: \"next\" | \"approval\";\n triggerType: string;\n}): boolean {\n return Boolean(\n args.lazyToolTransport &&\n args.progressiveDisclosureEnabled &&\n args.triggerKind === \"next\" &&\n (args.triggerType === \"user.message\" || args.triggerType === \"system.update.delivered\"),\n );\n}\n\n/**\n * Native web search is a runtime capability, not part of the session's MCP\n * allow-list. Attach it whenever the resolved provider advertises runnable\n * support. The null model is the legacy built-in Responses path, whose\n * deployment flag is its provider capability gate. There is deliberately no\n * cross-provider or sandbox/curl fallback.\n */\nexport function hostedWebSearchForTurn(\n resolvedModel: { configured: { hostedWebSearch: boolean } } | null,\n deploymentWebSearchEnabled: boolean,\n): boolean {\n return resolvedModel?.configured.hostedWebSearch ?? deploymentWebSearchEnabled;\n}\n\n/**\n * Image generation is an optional connected-account capability. A delegated\n * subscription may still authorize the text model without carrying the local\n * credential identity required for paid image operations; that must narrow the\n * tool catalog, not reject an otherwise valid turn.\n */\nexport function connectedSubscriptionImageGenerationAuthority<T>(\n credentialContext: T | null | undefined,\n credentialId: string | null | undefined,\n): { credentialContext: T; credentialId: string } | null {\n if (credentialContext == null || typeof credentialId !== \"string\" || credentialId.length === 0)\n return null;\n return { credentialContext, credentialId };\n}\n\n/** Direct OpenAI hosted image IDs are reusable only by the exact API credential. */\nexport function openAiHostedImageProviderBindingForTurn(\n settings: Pick<Settings, \"openaiProvider\" | \"openaiApiKey\" | \"openaiBaseUrl\">,\n resolvedModel: {\n provider: {\n id: string;\n kind: ResolvedModelProvider[\"kind\"];\n builtin: boolean;\n baseUrl?: string | undefined;\n };\n configured: {\n capabilities: {\n hostedTools: { imageGeneration: { runnable: boolean } };\n };\n };\n } | null,\n): { providerId: string; providerBindingHash: string } | null {\n if (!resolvedModel?.configured.capabilities.hostedTools.imageGeneration.runnable) return null;\n const providerId = resolvedModel.provider.id;\n const isDirectOpenAi =\n resolvedModel.provider.builtin &&\n resolvedModel.provider.id === \"openai\" &&\n isDirectOpenAiApiBaseUrl(resolvedModel.provider.baseUrl) &&\n settings.openaiProvider === \"openai\" &&\n isDirectOpenAiApiBaseUrl(settings.openaiBaseUrl);\n const bindingIdentity = isDirectOpenAi ? settings.openaiApiKey : null;\n if (!bindingIdentity) return null;\n return {\n providerId,\n providerBindingHash: imageProviderBindingHash(providerId, bindingIdentity),\n };\n}\n\n/** Exact model-catalog modality gate; null preserves the legacy built-in path. */\nexport function modelSupportsImageInputForTurn(\n resolvedModel: {\n configured: { capabilities?: { inputModalities: string[] } };\n } | null,\n): boolean {\n return (\n resolvedModel === null ||\n resolvedModel.configured.capabilities?.inputModalities.includes(\"image\") !== false\n );\n}\n\n/** Image support is catalogue-driven; document bytes are never `input_file`. */\nexport function modelAttachmentInputPolicyForTurn(\n resolvedModel: {\n provider: { api: ModelProviderApi };\n configured: {\n capabilities?: {\n inputModalities: string[];\n inputFileMediaTypes?: string[];\n };\n };\n } | null,\n): ModelAttachmentInputPolicy {\n const typedTransport = resolvedModel === null || resolvedModel.provider.api === \"responses\";\n return {\n supportsImageInput: typedTransport && modelSupportsImageInputForTurn(resolvedModel),\n inputFileMediaTypes: [],\n };\n}\n","import {\n beginImageGenerationOperation,\n completeImageGenerationOperation,\n getGeneratedImageArtifact,\n markImageGenerationOperationOutcomeUnknown,\n markImageGenerationOperationRetentionFailed,\n prepareImageGenerationOperation,\n resetImageGenerationOperationBeforeProviderDispatch,\n type Database,\n type ImageGenerationOperationStatus,\n} from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { createHash } from \"node:crypto\";\nimport {\n generatedImageIdentity,\n recoverGeneratedImageArtifact,\n retainGeneratedImage,\n retainedGeneratedImageFromArtifact,\n verifyReadyGeneratedImageArtifact,\n type GeneratedImageOutput,\n type GeneratedImageReceipt,\n} from \"./generated-images\";\n\nexport class ImageGenerationOutcomeUnknownError extends Error {\n constructor(readonly operationId: string) {\n super(\n \"The image provider request may have completed, but no durable result was recovered. It was not retried to avoid duplicate work or charges.\",\n );\n this.name = \"ImageGenerationOutcomeUnknownError\";\n }\n}\n\nexport class ImageGenerationRetentionFailedError extends Error {\n constructor(\n readonly operationId: string,\n cause?: unknown,\n ) {\n super(\n \"The image was generated, but OpenGeni could not save it. The paid provider request was not repeated.\",\n cause === undefined ? undefined : { cause },\n );\n this.name = \"ImageGenerationRetentionFailedError\";\n }\n}\n\nexport type ImageGenerationOperationPorts = {\n prepare: typeof prepareImageGenerationOperation;\n begin: typeof beginImageGenerationOperation;\n resetBeforeProviderDispatch: typeof resetImageGenerationOperationBeforeProviderDispatch;\n retain: typeof retainGeneratedImage;\n complete: typeof completeImageGenerationOperation;\n markOutcomeUnknown: typeof markImageGenerationOperationOutcomeUnknown;\n markRetentionFailed: typeof markImageGenerationOperationRetentionFailed;\n recover: typeof recoverCompletedImage;\n};\n\nconst imageGenerationOperationPorts: ImageGenerationOperationPorts = {\n prepare: prepareImageGenerationOperation,\n begin: beginImageGenerationOperation,\n resetBeforeProviderDispatch: resetImageGenerationOperationBeforeProviderDispatch,\n retain: retainGeneratedImage,\n complete: completeImageGenerationOperation,\n markOutcomeUnknown: markImageGenerationOperationOutcomeUnknown,\n markRetentionFailed: markImageGenerationOperationRetentionFailed,\n recover: recoverCompletedImage,\n};\n\n/**\n * Durable admission fence shared by every client-executed image provider.\n * Provider execution is permitted at most once after the prepared ->\n * provider_started transition. A verified pre-dispatch fence rejection returns\n * the row to `prepared`; a crash or any error after dispatch admission may\n * conservatively leave the outcome unknown. A retry may recover a ready\n * artifact, but never blindly replays an admitted paid operation.\n */\nexport type ExecuteImageGenerationOperationInput = {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n providerId: string;\n providerBindingHash: string;\n modelId: string;\n prompt: string;\n referenceDigests?: readonly Readonly<{ mediaType: string; sha256: string }>[];\n /**\n * Provider-specific proof that a thrown error occurred before the paid\n * provider boundary was crossed. Such a failure may return the operation to\n * `prepared`; every other generation error remains outcome-ambiguous after\n * `provider_started` and is never blindly replayed.\n */\n isProviderDispatchRejected?: (error: unknown) => boolean;\n generate: () => Promise<GeneratedImageOutput>;\n};\n\nexport async function executeImageGenerationOperation(\n input: ExecuteImageGenerationOperationInput,\n ports: ImageGenerationOperationPorts = imageGenerationOperationPorts,\n): Promise<GeneratedImageReceipt> {\n const identity = imageGenerationOperationIdentity({\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n modelId: input.modelId,\n prompt: input.prompt,\n ...(input.referenceDigests ? { referenceDigests: input.referenceDigests } : {}),\n toolCallId: input.toolCallId,\n });\n const prepared = await ports.prepare(input.db, {\n id: identity.operationId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n operationKey: identity.operationKey,\n toolCallId: input.toolCallId,\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n modelId: input.modelId,\n requestDigest: identity.requestDigest,\n expectedArtifactId: identity.artifactId,\n });\n\n if (prepared.operation.status !== \"prepared\") {\n const recovered = await ports.recover(input, {\n artifactId: identity.artifactId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n });\n if (recovered) return recovered;\n throw unrecoveredOperationError(prepared.operation.status, identity.operationId);\n }\n\n const begun = await ports.begin(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n providerBindingHash: input.providerBindingHash,\n expectedArtifactId: identity.artifactId,\n });\n if (!begun.started || begun.operation.status !== \"provider_started\") {\n const recovered = await ports.recover(input, {\n artifactId: identity.artifactId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n });\n if (recovered) return recovered;\n throw unrecoveredOperationError(begun.operation.status, identity.operationId);\n }\n\n let output: GeneratedImageOutput;\n try {\n output = await input.generate();\n } catch (error) {\n if (input.isProviderDispatchRejected?.(error) === true) {\n await ports\n .resetBeforeProviderDispatch(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n error: error instanceof Error ? error.message : String(error),\n })\n .catch(() => undefined);\n throw error;\n }\n await ports\n .markOutcomeUnknown(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n error: error instanceof Error ? error.message : String(error),\n })\n .catch(() => undefined);\n throw error;\n }\n\n try {\n if (output.toolCallId !== input.toolCallId || output.providerItemId !== null) {\n throw new Error(\"Client image provider returned a mismatched operation identity\");\n }\n const retained = await ports.retain({\n db: input.db,\n objectStorage: input.objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n sourceStrategy: \"provider_adapter\",\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n output,\n });\n await ports.complete(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n });\n return retained.receipt;\n } catch (error) {\n await ports\n .markRetentionFailed(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n error: error instanceof Error ? error.message : String(error),\n })\n .catch(() => undefined);\n throw new ImageGenerationRetentionFailedError(identity.operationId, error);\n }\n}\n\nfunction unrecoveredOperationError(\n status: ImageGenerationOperationStatus,\n operationId: string,\n): Error {\n return status === \"retention_failed\"\n ? new ImageGenerationRetentionFailedError(operationId)\n : new ImageGenerationOutcomeUnknownError(operationId);\n}\n\nexport function imageProviderBindingHash(providerId: string, credentialIdentity: string): string {\n if (!providerId.trim() || !credentialIdentity.trim()) {\n throw new Error(\"Image provider binding identity is empty\");\n }\n return digest(\"opengeni:image-provider-binding:v1\\0\", providerId, credentialIdentity);\n}\n\n/** Stable across worker/Temporal attempt retries; the attempt id is provenance, not identity. */\nexport function imageGenerationOperationIdentity(input: {\n workspaceId: string;\n sessionId: string;\n turnId: string;\n toolCallId: string;\n providerId: string;\n providerBindingHash: string;\n modelId: string;\n prompt: string;\n referenceDigests?: readonly Readonly<{ mediaType: string; sha256: string }>[];\n}): {\n operationId: string;\n operationKey: string;\n requestDigest: string;\n artifactId: string;\n} {\n const referenceDigests = input.referenceDigests ?? [];\n const requestDigest =\n referenceDigests.length === 0\n ? digest(\"opengeni:image-generation-request:v1\\0\", input.modelId, input.prompt)\n : digest(\n \"opengeni:image-generation-request:v2\\0\",\n input.modelId,\n input.prompt,\n ...referenceDigests.flatMap((reference) => [reference.mediaType, reference.sha256]),\n );\n const operationKey = digest(\n \"opengeni:image-generation-operation:v2\\0\",\n input.workspaceId,\n input.sessionId,\n input.turnId,\n input.toolCallId,\n );\n const artifact = generatedImageIdentity({\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n sourceStrategy: \"provider_adapter\",\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n providerItemId: null,\n toolCallId: input.toolCallId,\n });\n return {\n operationId: uuidFromDigest(operationKey),\n operationKey,\n requestDigest,\n artifactId: artifact.artifactId,\n };\n}\n\nasync function recoverCompletedImage(\n input: Pick<\n Parameters<typeof executeImageGenerationOperation>[0],\n | \"db\"\n | \"objectStorage\"\n | \"accountId\"\n | \"workspaceId\"\n | \"sessionId\"\n | \"turnId\"\n | \"toolCallId\"\n | \"providerId\"\n | \"providerBindingHash\"\n >,\n identity: { artifactId: string; operationId: string; operationKey: string },\n): Promise<GeneratedImageReceipt | null> {\n const artifact = await getGeneratedImageArtifact(\n input.db,\n input.workspaceId,\n identity.artifactId,\n );\n if (!artifact) return null;\n if (\n artifact.sourceStrategy !== \"provider_adapter\" ||\n artifact.sessionId !== input.sessionId ||\n artifact.turnId !== input.turnId ||\n artifact.toolCallId !== input.toolCallId ||\n artifact.providerId !== input.providerId ||\n artifact.providerBindingHash !== input.providerBindingHash ||\n artifact.providerItemId !== null\n ) {\n throw new Error(\"Recovered generated image does not match its provider operation\");\n }\n if (!input.objectStorage) {\n throw new Error(\"Recovered generated image requires configured object storage\");\n }\n const recovered = await recoverGeneratedImageArtifact({\n db: input.db,\n storage: input.objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifact,\n });\n if (!recovered) return null;\n await verifyReadyGeneratedImageArtifact(input.objectStorage, recovered);\n await completeImageGenerationOperation(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n });\n return retainedGeneratedImageFromArtifact(recovered).receipt;\n}\n\nfunction digest(prefix: string, ...values: string[]): string {\n const hash = createHash(\"sha256\").update(prefix);\n for (const value of values) hash.update(value).update(\"\\0\");\n return hash.digest(\"hex\");\n}\n\nfunction uuidFromDigest(digestValue: string): string {\n const bytes = Uint8Array.from(Buffer.from(digestValue.slice(0, 32), \"hex\"));\n bytes[6] = (bytes[6]! & 0x0f) | 0x80;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Buffer.from(bytes).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","import { hasPendingSteerAfterContextCompaction, isSessionCompactionRequested } from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport {\n appendSessionInstructions,\n appendWorkspaceGovernance,\n appendWorkspaceMemory,\n composeAgentInstructions,\n requestRemoteCompactionV2,\n serializedToolsForRemoteCompaction,\n EmptyCompactionSummaryError,\n SUMMARY_BUFFER_TOKENS,\n type ModelResponseUsage,\n} from \"@opengeni/runtime\";\nimport { type Settings } from \"@opengeni/config\";\nimport { maybeCompactContext, settleFailedContextCompactionLandmark } from \"../context-compaction\";\nimport type { CompactionSummarizer, RemoteCompactionV2Requester } from \"../context-compaction\";\nimport { TurnAttemptFencedError } from \"../turn-attempt-fenced\";\nimport type {\n TurnActivityServices as ActivityServices,\n RunAgentTurnInput,\n RunAgentTurnResult,\n} from \"../types\";\nimport {\n recordContextCompaction,\n recordContextCompactionStarted,\n} from \"../../observability-metrics\";\nimport { createTurnCredentialLeases } from \"./credential-leases\";\nimport { createTurnMediaArtifacts } from \"./media-artifacts\";\nimport { type SessionEvent } from \"@opengeni/contracts\";\n\nimport { acceptsPromptCacheKeyForTurn } from \"./codex\";\nimport {\n safeErrorDiagnostic,\n compactionFailureReasonFromError,\n isCompactionSummaryFailure,\n shouldRecoverCompactionProviderFailure,\n} from \"./errors\";\nimport {\n createCompactionModelUsageEventState,\n processCompactionModelUsageEvent,\n} from \"./model-usage\";\nimport { waitForTurnOperation } from \"./sandbox-provision\";\n\nimport type { ClaimTurnOk } from \"./claim\";\nimport type { GovernanceModelOk } from \"./governance-model\";\nimport type {\n AttemptIdentityState,\n BillingState,\n ClaimedResult,\n EventingState,\n ProviderTurnState,\n TurnControlState,\n} from \"./turn-context\";\n\nexport type RemoteCompactionPrefix = {\n tools: Awaited<ReturnType<typeof serializedToolsForRemoteCompaction>>;\n instructions: string;\n toolsReady: boolean;\n agent: Parameters<typeof serializedToolsForRemoteCompaction>[0] | null;\n};\n\nexport type CompactionPrepDeps = {\n input: RunAgentTurnInput;\n settings: Settings;\n db: ActivityServices[\"db\"];\n bus: ActivityServices[\"bus\"];\n observability: ActivityServices[\"observability\"];\n cancellationSignal: AbortSignal | undefined;\n control: TurnControlState;\n attempt: AttemptIdentityState;\n billingState: BillingState;\n eventing: EventingState & {\n publish: NonNullable<EventingState[\"publish\"]>;\n settle: NonNullable<EventingState[\"settle\"]>;\n };\n providerTurn: ProviderTurnState;\n leases: ReturnType<typeof createTurnCredentialLeases>;\n media: ReturnType<typeof createTurnMediaArtifacts>;\n claimedResult: ClaimedResult;\n claimedModelUsageSourceKeys: Set<string>;\n emittedModelUsageSourceKeys: Set<string>;\n modelUsageDispatchId: string;\n turn: ClaimTurnOk[\"turn\"];\n session: ClaimTurnOk[\"session\"];\n turnExecutionPolicy: ClaimTurnOk[\"turnExecutionPolicy\"];\n resolvedModel: GovernanceModelOk[\"resolvedModel\"];\n workspaceAgentInstructions: GovernanceModelOk[\"workspaceAgentInstructions\"];\n workspaceGovernance: GovernanceModelOk[\"workspaceGovernance\"];\n structuredWorkspacePolicyActive: GovernanceModelOk[\"structuredWorkspacePolicyActive\"];\n workspaceMemory: GovernanceModelOk[\"workspaceMemory\"];\n rigVersion: GovernanceModelOk[\"rigVersion\"];\n rigName: GovernanceModelOk[\"rigName\"];\n compactionModelHistoryProjector: GovernanceModelOk[\"compactionModelHistoryProjector\"];\n summarizeContextForCompaction: ActivityServices[\"summarizeContextForCompaction\"];\n withProviderRequestContext: <T>(fn: () => Promise<T>) => Promise<T>;\n withCodexRemoteCompaction: <T>(fn: () => Promise<T>) => Promise<T>;\n};\n\nexport type CompactionPrepOk = {\n promptCacheKey: string | undefined;\n remotePrefix: RemoteCompactionPrefix;\n remoteCompactionRequester: RemoteCompactionV2Requester | undefined;\n publishCompactionLiveEvents: (events: SessionEvent[]) => Promise<void>;\n publishCompactionOutcomeEvents: (events: SessionEvent[]) => Promise<void>;\n compactionModeOptions: NonNullable<Parameters<typeof maybeCompactContext>[5]>;\n compactionOnlyTurn: boolean;\n compactionSummarizerFor: (systemInstructions?: string) => CompactionSummarizer;\n settleDeferredSteerAfterCompaction: () => Promise<RunAgentTurnResult | null>;\n};\n\nexport type CompactionPrepOutcome = { exit: RunAgentTurnResult } | { ok: CompactionPrepOk };\n\nexport type PostAgentCompactionDeps = CompactionPrepDeps & {\n remotePrefix: RemoteCompactionPrefix;\n remoteCompactionRequester: CompactionPrepOk[\"remoteCompactionRequester\"];\n publishCompactionLiveEvents: CompactionPrepOk[\"publishCompactionLiveEvents\"];\n publishCompactionOutcomeEvents: CompactionPrepOk[\"publishCompactionOutcomeEvents\"];\n compactionModeOptions: CompactionPrepOk[\"compactionModeOptions\"];\n compactionOnlyTurn: boolean;\n compactionSummarizerFor: CompactionPrepOk[\"compactionSummarizerFor\"];\n settleDeferredSteerAfterCompaction: CompactionPrepOk[\"settleDeferredSteerAfterCompaction\"];\n agent: ReturnType<ActivityServices[\"runtime\"][\"buildAgent\"]>;\n};\n\nexport type PostAgentCompactionOk = {\n compactSummarizer: ReturnType<CompactionPrepOk[\"compactionSummarizerFor\"]>;\n};\n\nexport type PostAgentCompactionOutcome =\n | { exit: RunAgentTurnResult }\n | { ok: PostAgentCompactionOk };\n\nexport async function prepareCompaction(deps: CompactionPrepDeps): Promise<CompactionPrepOutcome> {\n const {\n input,\n settings,\n db,\n bus,\n observability,\n cancellationSignal,\n control,\n attempt,\n billingState,\n eventing,\n providerTurn,\n leases,\n media,\n claimedResult,\n claimedModelUsageSourceKeys,\n emittedModelUsageSourceKeys,\n modelUsageDispatchId,\n turn,\n session,\n turnExecutionPolicy,\n resolvedModel,\n workspaceAgentInstructions,\n workspaceGovernance,\n structuredWorkspacePolicyActive,\n workspaceMemory,\n rigVersion,\n rigName,\n compactionModelHistoryProjector,\n summarizeContextForCompaction,\n withProviderRequestContext,\n withCodexRemoteCompaction,\n } = deps;\n\n const remotePrefix: RemoteCompactionPrefix = {\n tools: [],\n instructions: \"\",\n toolsReady: false,\n agent: null,\n };\n\n const promptCacheKey = acceptsPromptCacheKeyForTurn(resolvedModel) ? input.sessionId : undefined;\n const compactionUsageState = createCompactionModelUsageEventState(claimedModelUsageSourceKeys);\n const recordCompactionUsage = async (usage: ModelResponseUsage) => {\n await processCompactionModelUsageEvent({\n usage,\n state: compactionUsageState,\n dispatchId: modelUsageDispatchId,\n settings,\n db,\n observability,\n publish: eventing.publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n provider: resolvedModel?.provider.id ?? settings.openaiProvider,\n providerApi: resolvedModel?.provider.api ?? \"responses\",\n model: resolvedModel?.configured.id ?? turn.model,\n externallyBilled: billingState.isExternallyBilledTurn,\n chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,\n countsTowardTokenCap: billingState.countsTowardTokenCap,\n turnAttemptId: input.attemptId,\n servingCredentialId: providerTurn.effectiveCodexCredentialId,\n priorSessionCredentialId: providerTurn.priorSessionCodexCredentialId,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n renewLease: () => leases.renewServing(\"model_usage\"),\n leaseLost: leases.servingLost,\n leaseLostMessage: \"Provider credential lease expired during context compaction\",\n contextContributions: eventing.companyBrainContextContributions,\n });\n };\n const compactionSummarizerFor = (systemInstructions?: string) =>\n resolvedModel\n ? (s: Settings, m: Array<Record<string, unknown>>) =>\n withProviderRequestContext(() =>\n summarizeContextForCompaction(s, m, {\n client: resolvedModel.client,\n provider: resolvedModel.provider,\n api: resolvedModel.provider.api,\n model: turnExecutionPolicy.upstreamModelId,\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n onUsage: recordCompactionUsage,\n ...(systemInstructions ? { systemInstructions } : {}),\n ...(promptCacheKey ? { promptCacheKey } : {}),\n }),\n )\n : (s: Settings, m: Array<Record<string, unknown>>) =>\n summarizeContextForCompaction(s, m, {\n model: turnExecutionPolicy.upstreamModelId,\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n onUsage: recordCompactionUsage,\n ...(systemInstructions ? { systemInstructions } : {}),\n ...(promptCacheKey ? { promptCacheKey } : {}),\n });\n // Prompt-cache prefix for remote_v2 MUST match ordinary turns:\n // tools → instructions → history. Filled after buildAgent for every\n // compact path (including operator /compact, which now builds the agent\n // first so it does not send empty tools/instructions).\n const remoteCompactionRequester =\n resolvedModel && billingState.isCodexTurn\n ? (s: Settings, m: Array<Record<string, unknown>>) =>\n withCodexRemoteCompaction(async () => {\n // Lazily serialize tools here so EmptyCompactionSummaryError is\n // thrown inside the compaction try/settlement handlers, not as a\n // raw activity failure before maybeCompactContext runs.\n if (!remotePrefix.instructions.trim()) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_instructions\",\n reason: \"agent_missing_system_instructions\",\n });\n }\n if (!remotePrefix.toolsReady) {\n if (!remotePrefix.agent) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_tools\",\n reason: \"agent_missing_for_tools\",\n });\n }\n try {\n remotePrefix.tools = await serializedToolsForRemoteCompaction(remotePrefix.agent);\n } catch (error) {\n // Tool schemas sit before instructions in the cache prefix.\n // Failing open to [] would reintroduce a massive pre-compact\n // cache bust — fail closed so we never send a tools mismatch\n // on purpose.\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_tools\",\n reason: \"serialize_tools_failed\",\n error: String(error),\n });\n }\n remotePrefix.toolsReady = true;\n }\n return requestRemoteCompactionV2(s, m, {\n client: resolvedModel.client,\n provider: resolvedModel.provider,\n model: turnExecutionPolicy.upstreamModelId,\n systemInstructions: remotePrefix.instructions,\n onUsage: recordCompactionUsage,\n tools: remotePrefix.tools,\n ...(promptCacheKey ? { promptCacheKey } : {}),\n });\n })\n : undefined;\n const publishCompactionLiveEvents = async (events: SessionEvent[]) => {\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, events);\n };\n const publishCompactionOutcomeEvents = async (events: SessionEvent[]) => {\n // `compaction.started` was already fanout via publishCompactionLiveEvents.\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n events.filter((event) => event.type !== \"session.context.compaction.started\"),\n );\n };\n const compactionModeOptions = {\n codexCompactionMode: session.codexCompactionMode,\n isCodexSubscriptionTurn: billingState.isCodexTurn,\n onCompactionStarted: (trigger: \"auto\" | \"operator\" | \"proactive\" | \"overflow\") =>\n recordContextCompactionStarted(observability, trigger),\n publishLiveEvents: publishCompactionLiveEvents,\n ...(remoteCompactionRequester ? { requestRemoteCompactionV2: remoteCompactionRequester } : {}),\n } as const;\n\n // Operator /compact:\n // - portable (incl. Codex portable): early maintenance path — no\n // prepareTools/sandbox; summarizer only needs composed instructions.\n // - remote_v2: fall through to prepareTools/buildAgent so the compact\n // request reuses the ordinary tools→instructions cache prefix, then\n // settle without inference. (Requester is also wired for Codex portable\n // turns but unused there — gate on the frozen session mode.)\n const compactionOnlyTurn = turn.source === \"compaction\";\n const remoteV2CompactionNeedsAgentPrefix =\n Boolean(remoteCompactionRequester) && session.codexCompactionMode === \"remote_v2\";\n const settleDeferredSteerAfterCompaction = async (): Promise<RunAgentTurnResult | null> => {\n if (compactionOnlyTurn) return null;\n const pending = await hasPendingSteerAfterContextCompaction(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n });\n if (!pending) return null;\n if (\n !(await eventing.settle({\n events: [\n {\n type: \"turn.superseded\",\n payload: { reason: \"steer\", deferredUntilCompaction: true },\n },\n { type: \"session.status.changed\", payload: { status: \"queued\" } },\n ],\n turnStatus: \"superseded\",\n sessionStatus: \"queued\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n // Metrics currently group user-directed supersession with cancellation;\n // the durable turn outcome remains the precise `superseded` truth.\n control.turnMetricOutcome = \"cancelled\";\n control.activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n };\n if (compactionOnlyTurn && !remoteV2CompactionNeedsAgentPrefix) {\n const compactionInstructions = appendWorkspaceMemory(\n appendSessionInstructions(\n appendWorkspaceGovernance(\n composeAgentInstructions(\n structuredWorkspacePolicyActive\n ? eventing.modelRunSettings.agentInstructionsTemplate\n : (workspaceAgentInstructions ?? eventing.modelRunSettings.agentInstructionsTemplate),\n undefined,\n rigVersion && rigName ? { name: rigName, version: rigVersion.version } : undefined,\n ),\n workspaceGovernance ?? undefined,\n ),\n session.instructions ?? undefined,\n ),\n workspaceMemory ?? undefined,\n );\n const requested = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);\n let outcome: Awaited<ReturnType<typeof maybeCompactContext>> | null = null;\n if (requested) {\n try {\n outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n eventing.modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n session.lastInputTokens,\n compactionSummarizerFor(compactionInstructions),\n {\n force: true,\n clearRequestedCompaction: true,\n trigger: \"operator\",\n materializeHistory: media.materializeScreenshotHistory,\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n } catch (error) {\n // Codex retries retryable checkpoint-provider failures rather than\n // treating them as a semantic compaction result. Keep the operator\n // request pending and let the ordinary same-turn provider/capacity\n // recovery path re-dispatch this exact maintenance execution.\n if (shouldRecoverCompactionProviderFailure(error)) throw error;\n if (error instanceof TurnAttemptFencedError) throw error;\n // `compaction.started` may already be live — settle skipped before\n // failing the turn so the timeline cannot stick on Compacting…\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: true,\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n if (!isCompactionSummaryFailure(error)) throw error;\n const errorMessage = String(compactionFailureReasonFromError(error));\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(landmark.requestConsumed ? {} : { consumeRequestedCompactionFailure: true }),\n }))\n ) {\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n control.turnMetricOutcome = \"failed\";\n control.activityStatus = \"idle\";\n control.activityError = error;\n return { exit: claimedResult({ status: \"idle\" }) };\n }\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, \"operator\");\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n }\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: {\n maintenance: \"context_compaction\",\n result: outcome?.compacted ? \"compacted\" : (outcome?.reason ?? \"already_applied\"),\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n control.turnMetricOutcome = \"completed\";\n control.activityStatus = \"idle\";\n return { exit: claimedResult({ status: \"idle\" }) };\n }\n\n return {\n ok: {\n promptCacheKey,\n remotePrefix,\n remoteCompactionRequester,\n publishCompactionLiveEvents,\n publishCompactionOutcomeEvents,\n compactionModeOptions,\n compactionOnlyTurn,\n compactionSummarizerFor,\n settleDeferredSteerAfterCompaction,\n },\n };\n}\n\nexport async function runPostAgentCompaction(\n deps: PostAgentCompactionDeps,\n): Promise<PostAgentCompactionOutcome> {\n const {\n input,\n db,\n observability,\n cancellationSignal,\n control,\n attempt,\n eventing,\n claimedResult,\n turn,\n session,\n remotePrefix,\n remoteCompactionRequester,\n publishCompactionLiveEvents,\n publishCompactionOutcomeEvents,\n compactionModeOptions,\n compactionOnlyTurn,\n compactionSummarizerFor,\n settleDeferredSteerAfterCompaction,\n compactionModelHistoryProjector,\n media,\n agent,\n } = deps;\n\n const agentInstructions = typeof agent.instructions === \"string\" ? agent.instructions : \"\";\n const compactSummarizer = compactionSummarizerFor(\n agentInstructions.trim() ? agentInstructions : undefined,\n );\n if (remoteCompactionRequester) {\n // Exact byte match with the ordinary turn prefix (CLI base_instructions).\n // Tools serialize lazily inside the requester so setup failures settle as\n // compaction failures rather than raw activity crashes.\n remotePrefix.instructions = agentInstructions;\n remotePrefix.agent = agent;\n }\n\n if (compactionOnlyTurn) {\n const requested = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);\n let outcome: Awaited<ReturnType<typeof maybeCompactContext>> | null = null;\n if (requested) {\n try {\n outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n eventing.modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n session.lastInputTokens,\n compactSummarizer,\n {\n force: true,\n clearRequestedCompaction: true,\n trigger: \"operator\",\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n } catch (error) {\n // Codex retries retryable checkpoint-provider failures rather than\n // treating them as a semantic compaction result. Keep the operator\n // request pending and let the ordinary same-turn provider/capacity\n // recovery path re-dispatch this exact maintenance execution.\n if (shouldRecoverCompactionProviderFailure(error)) throw error;\n if (error instanceof TurnAttemptFencedError) throw error;\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: true,\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n if (!isCompactionSummaryFailure(error)) throw error;\n const errorMessage = String(compactionFailureReasonFromError(error));\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(landmark.requestConsumed ? {} : { consumeRequestedCompactionFailure: true }),\n }))\n ) {\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n control.turnMetricOutcome = \"failed\";\n control.activityStatus = \"idle\";\n control.activityError = error;\n return { exit: claimedResult({ status: \"idle\" }) };\n }\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, \"operator\");\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n }\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: {\n maintenance: \"context_compaction\",\n result: outcome?.compacted ? \"compacted\" : (outcome?.reason ?? \"already_applied\"),\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n control.turnMetricOutcome = \"completed\";\n control.activityStatus = \"idle\";\n return { exit: claimedResult({ status: \"idle\" }) };\n }\n\n // Pre-turn durable context compaction. When the single Codex-parity\n // threshold is crossed, this summarizes active history and rebuilds active\n // history as [user messages..., summary] BEFORE the model input is read.\n // Summarizer context overflows drop one oldest summarizer-input item and\n // retry, exactly like Codex. Other failures end this turn honestly.\n // Run before every fresh inference. Approval resumes replay their frozen\n // RunState verbatim and recovering attempts already compacted, if needed,\n // before the first attempt's model boundary.\n if (attempt.triggerType === \"user.message\" || attempt.triggerType === \"system.update.delivered\") {\n let forced = false;\n try {\n // Operator /compact (the slash command) sets a durable request flag;\n // observe it without consuming it so a failed/stale attempt cannot\n // lose the request. The replacement transaction clears it on success.\n forced = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);\n const outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n eventing.modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId!,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n session.lastInputTokens,\n // Provider-aware summarizer: when the turn's model resolved to a\n // registry provider, summarize on THAT provider's client + wire API\n // (a chat provider can't summarize through OpenAI/Azure). Null\n // resolution uses the built-in Responses summarizer with the same\n // session prompt-cache key as the main model calls.\n compactSummarizer,\n forced\n ? {\n force: true,\n clearRequestedCompaction: true,\n trigger: \"operator\",\n materializeHistory: media.materializeScreenshotHistory,\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n }\n : {\n trigger: \"auto\",\n materializeHistory: media.materializeScreenshotHistory,\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n const compactionTrigger = forced ? \"operator\" : undefined;\n recordContextCompaction(observability, compactionTrigger ?? \"auto\");\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n if (\n outcome.events.some(\n (event) =>\n event.type === \"session.context.compacted\" ||\n event.type === \"session.context.compaction.skipped\",\n )\n ) {\n const deferredSteer = await settleDeferredSteerAfterCompaction();\n if (deferredSteer) return { exit: deferredSteer };\n }\n } catch (compactError) {\n if (shouldRecoverCompactionProviderFailure(compactError)) throw compactError;\n if (compactError instanceof TurnAttemptFencedError) throw compactError;\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId!,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: forced,\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n if (!isCompactionSummaryFailure(compactError)) throw compactError;\n const deferredSteer = await settleDeferredSteerAfterCompaction();\n if (deferredSteer) return { exit: deferredSteer };\n const errorMessage = String(compactionFailureReasonFromError(compactError));\n observability.error(\"context compaction failed\", {\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n ...safeErrorDiagnostic(compactError),\n });\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(forced && !landmark.requestConsumed\n ? { consumeRequestedCompactionFailure: true }\n : {}),\n }))\n ) {\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n control.turnMetricOutcome = \"failed\";\n control.activityStatus = \"idle\";\n control.activityError = compactError;\n return { exit: claimedResult({ status: \"idle\" }) };\n }\n }\n\n return { ok: { compactSummarizer } };\n}\n","import {\n advanceWorkspaceGeneration,\n verifyWorkspaceMutationSettlement,\n heartbeatLeaseHolder,\n readLease,\n accrueWarmSeconds,\n SandboxWorkspaceMutationFencedError,\n} from \"@opengeni/db\";\nimport {\n RoutingMutationOutcomeUnknownError,\n type EstablishedSandboxSession,\n} from \"@opengeni/runtime\";\nimport {\n sandboxLifecycleTransitionWaitMs,\n sandboxWarmRateMicrosPerSecond,\n type Settings,\n} from \"@opengeni/config\";\nimport { createRuntimeBatcher, currentActivityContext } from \"../streaming\";\nimport type { TurnActivityServices as ActivityServices, RunAgentTurnInput } from \"../types\";\nimport { maybePersistWarmWorkspaceSnapshot, type ResumedTurnSandbox } from \"../../sandbox-resume\";\nimport { recordCreditMicros } from \"../../observability-metrics\";\nimport { ChannelAPartialMutationError } from \"@opengeni/runtime/sandbox\";\n\nimport { safeErrorDiagnostic } from \"./errors\";\nimport {\n shouldStartPeriodicWorkspaceSnapshot,\n releaseTurnSandboxAfterWriterDrain,\n finalizeDurableTurnOpStreams,\n} from \"./quiescence\";\nimport { SandboxDeadlineRotationError } from \"./sandbox-provision\";\nimport type { AttemptIdentityState, EventingState, SandboxRuntimeState } from \"./turn-context\";\n\nexport type SandboxTurnRuntimeDeps = {\n input: RunAgentTurnInput;\n settings: Settings;\n db: ActivityServices[\"db\"];\n objectStorage: ActivityServices[\"objectStorage\"];\n observability: ActivityServices[\"observability\"];\n cancellationSignal: AbortSignal | undefined;\n activityContext: ReturnType<typeof currentActivityContext>;\n sandboxRotationController: AbortController;\n sandboxState: SandboxRuntimeState;\n eventing: EventingState;\n attempt: AttemptIdentityState;\n};\n\nexport type SandboxTurnRuntime = ReturnType<typeof createSandboxTurnRuntime>;\n\n/**\n * Provider-deadline rotation is a preemption boundary, not a cooperative\n * snapshot boundary. Snapshotting while this attempt still owns active tools\n * can deadlock on its own unsettled mutation admission or on an earlier native\n * capture. Abort first; the ordinary attempt finalizer then drains every writer\n * and releases the holder, after which the zero-holder reaper owns the exact\n * generation capture and same-request takeover protocol.\n */\nexport function preemptSandboxTurnForDeadlineRotation(input: {\n controller: AbortController;\n sandboxState: Pick<SandboxRuntimeState, \"deadlineRotationRequested\">;\n sandboxGroupId: string;\n leaseEpoch: number;\n cancellationSignal?: AbortSignal;\n}): boolean {\n if (input.controller.signal.aborted || input.cancellationSignal?.aborted) return false;\n input.sandboxState.deadlineRotationRequested = true;\n input.controller.abort(new SandboxDeadlineRotationError(input.sandboxGroupId, input.leaseEpoch));\n return true;\n}\n\nexport function createSandboxTurnRuntime(deps: SandboxTurnRuntimeDeps) {\n const {\n input,\n settings,\n db,\n objectStorage,\n observability,\n cancellationSignal,\n activityContext,\n sandboxRotationController,\n sandboxState,\n eventing,\n attempt,\n } = deps;\n\n // P1.2 ownership inversion: when sandboxOwnershipEnabled, the turn resolves\n // the one box by id from the group lease and injects it NON-OWNED into the\n // run. null when the flag is off (byte-for-byte the legacy build-and-discard\n // path) OR when the backend is \"none\". Released + dropped in `finally`.\n const releaseLateSandbox = async (sandbox: ResumedTurnSandbox): Promise<void> => {\n sandboxState.lateSandboxesAwaitingWriterDrain.add(sandbox);\n // Drop the holder/timer immediately, but keep its null-outcome admissions\n // fenced until the shared attempt writer drain completes. The staged\n // release serializes a later proof-bearing call behind this one.\n await sandbox.release().catch(() => undefined);\n if (!sandboxState.attemptWritersDrained) return;\n try {\n await releaseTurnSandboxAfterWriterDrain(sandbox);\n sandboxState.lateSandboxesAwaitingWriterDrain.delete(sandbox);\n } catch (error) {\n console.error(\n \"late sandbox quiesced release failed (turn outcome unaffected)\",\n safeErrorDiagnostic(error),\n );\n }\n };\n const requireResolvedSandboxForMutation = (message: string): ResumedTurnSandbox => {\n if (!sandboxState.resolvedSandbox) throw new Error(message);\n return sandboxState.resolvedSandbox;\n };\n // The machine-primary SelfhostedSession (the UNWRAPPED backend, not the\n // routing proxy). Kept as a fallback finalizer; the routing proxy normally\n // aggregates it together with every machine reached after a mid-turn swap.\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 const finalizeTurnOpStreamOps = async (): Promise<void> => {\n await finalizeDurableTurnOpStreams(\n [sandboxState.lazyOwnedSandbox?.session, sandboxState.resolvedSandbox?.established.session],\n sandboxState.machinePrimarySession,\n );\n };\n // A same-target API repair can replace the home provider while this turn is\n // alive. Keep setup/snapshot persistence on the rebound raw session while\n // preserving the SDK-owned routing proxy for eager turns. Lazy turns hold the\n // proxy separately, so their worker-side handle may replace its raw session.\n const onHomeSandboxRebound = (rebound: {\n established: EstablishedSandboxSession;\n leaseEpoch: number;\n }): void => {\n const current = sandboxState.resolvedSandbox;\n const previousSession = current?.established.session;\n const preserveRoutingProxy =\n current !== null && previousSession !== sandboxState.setupBoxSession;\n sandboxState.setupBoxSession = rebound.established.session;\n if (!current) return;\n current.leaseEpoch = rebound.leaseEpoch;\n current.established = preserveRoutingProxy\n ? {\n ...current.established,\n client: rebound.established.client,\n // Keep the stable SDK-facing proxy; only its resolver changes the\n // underlying backend. The worker's setupBoxSession above is raw.\n session: previousSession,\n sessionState: rebound.established.sessionState,\n instanceId: rebound.established.instanceId,\n backendId: rebound.established.backendId,\n ...(rebound.established.origin ? { origin: rebound.established.origin } : {}),\n ...(rebound.established.restoredArchive\n ? { restoredArchive: rebound.established.restoredArchive }\n : {}),\n }\n : rebound.established;\n };\n // The globally unique durable turn-attempt holder id + the group id,\n // captured so the lease heartbeat can refresh the lease TTL epoch-fenced\n // (a superseded owner self-evicts) and finally can release.\n const runWorkspaceMutationForSandbox = async <T>(\n sandbox: ResumedTurnSandbox,\n operation: string,\n mutation: () => Promise<T>,\n observePhase?: (measurement: {\n phase: \"admission\" | \"provider\" | \"settlement\" | \"snapshot_wait\";\n outcome: \"completed\" | \"failed\";\n durationSeconds: number;\n }) => void,\n ): Promise<T> => {\n const observeMutationPhase = (\n phase: \"admission\" | \"provider\" | \"settlement\" | \"snapshot_wait\",\n outcome: \"completed\" | \"failed\",\n durationMs: number,\n ): void => {\n try {\n observePhase?.({\n phase,\n outcome,\n durationSeconds: Math.max(0, durationMs) / 1_000,\n });\n } catch {\n // Diagnostics must never alter workspace mutation authority.\n }\n };\n // Connected machines are the user's own persistence and never dirty the\n // cloud home archive. Every persistable raw-session write batch is fenced\n // against the exact current lease/provider before the provider sees it.\n if (sandbox.established.backendId === \"selfhosted\") {\n const providerStartedAt = performance.now();\n let providerOutcome: \"completed\" | \"failed\" = \"failed\";\n try {\n const result = await mutation();\n providerOutcome = \"completed\";\n return result;\n } catch (error) {\n if (error instanceof ChannelAPartialMutationError) {\n throw new RoutingMutationOutcomeUnknownError(\n operation,\n `Connected Machine workspace mutation \"${operation}\" partially applied before a later batch item failed; the complete operation was not replayed`,\n { cause: error },\n );\n }\n throw error;\n } finally {\n observeMutationPhase(\"provider\", providerOutcome, performance.now() - providerStartedAt);\n }\n }\n if (\n !sandboxState.sandboxGroupId ||\n !sandboxState.sandboxHolderId ||\n !attempt.turnId ||\n attempt.executionGeneration <= 0\n ) {\n throw new Error(\"Workspace mutation attempted before exact turn sandbox admission\");\n }\n let admissionCaptureWaitMs = 0;\n const identity = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n holderId: sandboxState.sandboxHolderId,\n sandboxGroupId: sandboxState.sandboxGroupId,\n expectedEpoch: sandbox.leaseEpoch,\n expectedInstanceId: sandbox.established.instanceId,\n operation,\n captureWaitMs: sandboxLifecycleTransitionWaitMs(settings),\n ...(cancellationSignal ? { waitSignal: cancellationSignal } : {}),\n ...(observePhase\n ? {\n onCaptureWait: (observation: {\n durationMs: number;\n outcome: \"completed\" | \"failed\";\n }) => {\n admissionCaptureWaitMs += Math.max(0, observation.durationMs);\n observeMutationPhase(\"snapshot_wait\", observation.outcome, observation.durationMs);\n },\n }\n : {}),\n };\n const admissionStartedAt = performance.now();\n let admissionOutcome: \"completed\" | \"failed\" = \"failed\";\n let admission: Awaited<ReturnType<typeof advanceWorkspaceGeneration>>;\n try {\n admission = await advanceWorkspaceGeneration(db, identity);\n admissionOutcome = \"completed\";\n } catch (admissionError) {\n if (\n admissionError instanceof SandboxWorkspaceMutationFencedError &&\n admissionError.code === \"rotation_in_progress\" &&\n sandboxState.sandboxGroupId\n ) {\n // The lease still matches this turn's exact epoch/instance but a\n // rotation was requested. Start the same immediate preemption the\n // heartbeat would start on its next tick, so this attempt cannot keep\n // the provider generation pinned behind its own blocked mutation.\n // Best-effort and single-flight; the admission failure itself is still\n // surfaced to the caller.\n void beginRotationPreemption(\n sandbox,\n sandbox.leaseEpoch,\n sandboxState.sandboxGroupId,\n ).catch(() => undefined);\n }\n throw admissionError;\n } finally {\n observeMutationPhase(\n \"admission\",\n admissionOutcome,\n Math.max(0, performance.now() - admissionStartedAt - admissionCaptureWaitMs),\n );\n }\n const settleMutation = async (outcome: \"resolved\" | \"rejected\"): Promise<void> => {\n const settlementStartedAt = performance.now();\n let settlementOutcome: \"completed\" | \"failed\" = \"failed\";\n try {\n await verifyWorkspaceMutationSettlement(db, {\n ...identity,\n admission,\n outcome,\n });\n settlementOutcome = \"completed\";\n } finally {\n observeMutationPhase(\n \"settlement\",\n settlementOutcome,\n performance.now() - settlementStartedAt,\n );\n }\n };\n let result: T;\n const providerStartedAt = performance.now();\n let providerOutcome: \"completed\" | \"failed\" = \"failed\";\n try {\n result = await mutation();\n providerOutcome = \"completed\";\n } catch (providerError) {\n observeMutationPhase(\"provider\", providerOutcome, performance.now() - providerStartedAt);\n const partialMutation = providerError instanceof ChannelAPartialMutationError;\n try {\n await settleMutation(partialMutation ? \"resolved\" : \"rejected\");\n } catch (settlementError) {\n throw new RoutingMutationOutcomeUnknownError(\n operation,\n partialMutation\n ? `Platform workspace mutation \"${operation}\" partially applied at the provider but lost its durable physical settlement; its outcome is unknown and it was not replayed`\n : `Platform workspace mutation \"${operation}\" rejected at the provider but lost its durable physical settlement; its outcome is unknown and it was not replayed`,\n { cause: settlementError },\n );\n }\n if (partialMutation) {\n throw new RoutingMutationOutcomeUnknownError(\n operation,\n `Platform workspace mutation \"${operation}\" partially applied before a later batch item failed; the complete operation was not replayed`,\n { cause: providerError },\n );\n }\n throw providerError;\n }\n observeMutationPhase(\"provider\", providerOutcome, performance.now() - providerStartedAt);\n try {\n await settleMutation(\"resolved\");\n } catch (settlementError) {\n throw new RoutingMutationOutcomeUnknownError(\n operation,\n `Platform workspace mutation \"${operation}\" returned from the provider but lost its durable settlement fence; its outcome is unknown and it was not replayed`,\n { cause: settlementError },\n );\n }\n return result;\n };\n // Lease-TTL refresh timer (parallels the activity heartbeat): while the turn\n // runs it refreshes expires_at epoch-fenced so a legit multi-day turn is\n // never TTL-reaped. Cleared in finally. Only set when the flag resolved a box.\n const stopLeaseHeartbeat = (): void => {\n if (!sandboxState.leaseHeartbeatTimer) return;\n clearInterval(sandboxState.leaseHeartbeatTimer);\n sandboxState.leaseHeartbeatTimer = undefined;\n };\n // credential-renewal policy: the worker, not the model, owns renewal of run-scoped Git\n // credentials for a multi-day turn. The controller is attached only after\n // the initial seed reached a real cloud box and is drained before capture.\n // Generic host-owned run material has its own attempt-scoped renewal and\n // write handle. It is always drained and wiped before workspace capture.\n // The delegated Codemode bearer has a one-hour TTL. Renewal is attempt-\n // owned and attaches only after the initial token file reached a real\n // sandbox session; finalization drains an in-flight replacement.\n // MID-SESSION snapshot single-flight guard: the heartbeat tick fires every\n // 10s but a Modal filesystem snapshot can take longer — never overlap two\n // captures on one box. The in-flight capture's promise is held so the\n // turn-end persist can await it (its capture predates the turn's final\n // writes; landing after the fresher turn-end capture started would make\n // the atomic DB throttle discard the fresher one). Interval throttling\n // itself lives in maybePersistWarmWorkspaceSnapshot / persistWarmSnapshot.\n // The heartbeat snapshot is mid-session durability, not first-request\n // preparation. Keep it off the startup critical path until a provider\n // request has actually reached its transport boundary.\n // Turn-end capture needs the lease heartbeat to keep its holder alive, but\n // must prevent that same timer from starting another periodic snapshot\n // while it reads. This gate separates those two responsibilities.\n const flushRuntimeBatcher = async () => {\n const current = eventing.batcher as ReturnType<typeof createRuntimeBatcher> | null;\n await current?.flush().catch(() => undefined);\n };\n // Reconciliation is declared before provider routing so every turn-end path\n // can share one closure. It cannot run until `stream` exists, by which time\n // this value has been rebound to the turn's resolved model policy.\n const publishSandboxLifecycleEvents = async (sandbox: ResumedTurnSandbox): Promise<void> => {\n const established = sandbox.established;\n if (eventing.publish && established.origin && established.origin !== \"resumed\") {\n const lifecycleEvents: Array<{\n type: \"sandbox.box.lost\" | \"sandbox.box.created\";\n payload: unknown;\n }> = [];\n if (established.lostInstanceId) {\n lifecycleEvents.push({\n type: \"sandbox.box.lost\",\n payload: { sandboxId: established.lostInstanceId },\n });\n }\n lifecycleEvents.push({\n type: \"sandbox.box.created\",\n payload: {\n sandboxId: established.instanceId,\n hydrated: established.origin === \"restored\" ? \"archive\" : \"none\",\n },\n });\n await eventing.publish(lifecycleEvents).catch(() => undefined);\n }\n };\n const publishSandboxLost = async (lostSandbox: { instanceId: string }): Promise<void> => {\n if (!eventing.publish) return;\n await eventing\n .publish([\n {\n type: \"sandbox.box.lost\",\n payload: { sandboxId: lostSandbox.instanceId },\n },\n ])\n .catch((publishError) => {\n // The lease transition is already authoritative. A fenced/failed audit\n // append must not prevent the same logical turn from recovering.\n console.error(\"sandbox box lost event publish failed\", safeErrorDiagnostic(publishError));\n });\n };\n /**\n * Start (single-flight) provider-deadline preemption for the established box.\n * Entered from the lease heartbeat once the lease is rotation-fenced, and\n * from a workspace-mutation admission that observed `rotation_in_progress` at\n * the same epoch/instance. The active attempt is aborted immediately instead\n * of waiting behind a turn-side snapshot: finalization first drains every\n * writer and then releases the holder, licensing the zero-holder reaper's\n * authoritative capture/takeover/termination protocol.\n *\n * `not_rotating` means the exact epoch/instance no longer carries a requested\n * rotation (holder reaped, attempt closed, epoch superseded, or draining).\n */\n const beginRotationPreemption = async (\n sandbox: ResumedTurnSandbox,\n rotationEpoch: number,\n rotationGroupId: string,\n ): Promise<\"started\" | \"busy\" | \"not_rotating\"> => {\n // A cancelled attempt never starts another preemption check; its\n // cancellation settlement owns the holder from here.\n if (\n sandboxState.rotationPreemptionInFlight ||\n sandboxRotationController.signal.aborted ||\n cancellationSignal?.aborted\n ) {\n return \"busy\";\n }\n if (sandboxState.rotationPreemptionInFlight || sandboxRotationController.signal.aborted) {\n return \"busy\";\n }\n let disposition: \"started\" | \"not_rotating\" = \"started\";\n sandboxState.rotationPreemptionInFlight = (async () => {\n const rotatingLease = await readLease(db, input.workspaceId, rotationGroupId);\n if (\n rotatingLease?.leaseEpoch !== rotationEpoch ||\n rotatingLease.instanceId !== sandbox.established.instanceId ||\n rotatingLease.rotationRequestedAt === null\n ) {\n disposition = \"not_rotating\";\n return;\n }\n\n // Close the periodic producer before marking the turn for preemption.\n // A tick that already launched a capture is joined by finalization via\n // the capture promise's physical-settlement handle.\n stopLeaseHeartbeat();\n preemptSandboxTurnForDeadlineRotation({\n controller: sandboxRotationController,\n sandboxState,\n sandboxGroupId: rotationGroupId,\n leaseEpoch: rotationEpoch,\n ...(cancellationSignal ? { cancellationSignal } : {}),\n });\n })()\n .catch((error) => {\n observability.warn(\"sandbox deadline rotation preemption check failed; retrying\", {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n sandboxGroupId: rotationGroupId,\n leaseEpoch: rotationEpoch,\n ...safeErrorDiagnostic(error),\n });\n })\n .finally(() => {\n sandboxState.rotationPreemptionInFlight = null;\n });\n await sandboxState.rotationPreemptionInFlight;\n return disposition;\n };\n const startLeaseHeartbeat = (\n sandbox: ResumedTurnSandbox,\n warmBackend: Settings[\"sandboxBackend\"] | undefined,\n ): void => {\n if (sandboxState.leaseHeartbeatTimer) return;\n if (!sandboxState.sandboxHolderId || !sandboxState.sandboxGroupId) {\n return;\n }\n // Refresh the lease TTL on the activity-heartbeat cadence (10s, well\n // inside the 90s lease TTL). EPOCH-FENCED: a superseded owner's refresh\n // is rejected (returns false) and we stop refreshing — the box rides the\n // provider idle-timeout and the next dispatch re-establishes it. Best-\n // effort: a transient DB error must never fail the turn.\n const heartbeatEpoch = sandbox.leaseEpoch;\n const heartbeatHolderId = sandboxState.sandboxHolderId;\n const heartbeatGroupId = sandboxState.sandboxGroupId;\n // P2.1 warm-meter (tick A): while a turn runs, the heartbeat is also the\n // warm-seconds tick. GROUP+epoch+tick keyed (one box = one stream, shared\n // box metered once); epoch-fenced (a stale tick no-ops). Warm-cost is\n // metered when a per-backend rate is configured. Best-effort: a metering\n // failure must never fail the turn.\n //\n // Keyed off the EFFECTIVE backend (Stage D): a machine-primary turn has NO\n // Modal box, so it must accrue ZERO cloud warm-seconds — `selfhosted` has no\n // configured warm rate (0). Keying off turn.sandboxBackend (modal) would bill\n // cloud seconds for a box that does not exist (a real money bug). Non-machine\n // turns fall back to groupBoxBackend (the REAL box that ran): for a machine-\n // home turn that degraded to the cloud group box (swap-away / flag-off), that\n // is the deployment default (modal), so the fallback box is warm-metered at\n // the cloud rate instead of selfhosted's rate-0 (which would under-bill).\n const warmRate = sandboxWarmRateMicrosPerSecond(\n settings,\n warmBackend ?? (sandbox.established.backendId as Settings[\"sandboxBackend\"]),\n );\n sandboxState.leaseHeartbeatTimer = setInterval(() => {\n void heartbeatLeaseHolder(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: heartbeatGroupId,\n kind: \"turn\",\n holderId: heartbeatHolderId,\n leaseTtlMs: settings.sandboxLeaseTtlMs,\n expectedEpoch: heartbeatEpoch,\n })\n .then(async (alive) => {\n if (alive) return;\n const rotation = await beginRotationPreemption(sandbox, heartbeatEpoch, heartbeatGroupId);\n if (rotation === \"not_rotating\") {\n // The holder was reaped, the exact attempt closed, the epoch was\n // superseded, or the lease began draining. Do not leave a dead\n // interval issuing DB writes and snapshot probes forever.\n stopLeaseHeartbeat();\n }\n })\n .catch(() => undefined);\n void accrueWarmSeconds(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: heartbeatGroupId,\n expectedEpoch: heartbeatEpoch,\n warmRateMicrosPerSecond: warmRate,\n subjectId: input.sessionId,\n })\n .then((result) => recordCreditMicros(observability, \"usage\", result.costMicros))\n .catch(() => undefined);\n // MID-SESSION snapshot (sandbox-file-persistence): while the turn holds\n // the box, fold a fresh /workspace snapshot onto the lease every\n // sandboxSnapshotIntervalMs, so a box death the reaper never sees\n // (Modal hard timeout mid-busy, OOM, infra) costs at most one interval\n // of work — a legit multi-day turn is otherwise completely unprotected\n // (the reaper only drain-persists IDLE leases). Uses the UN-proxied box\n // session (setupBoxSession): the routing veneer could swap mid-op and a\n // selfhosted target has no persistWorkspace anyway. Best-effort +\n // single-flight; throttling lives in the helper.\n const snapshotSession = sandboxState.setupBoxSession;\n const snapshotTurnId = attempt.turnId;\n if (\n snapshotSession &&\n snapshotTurnId &&\n shouldStartPeriodicWorkspaceSnapshot({\n firstProviderRequestStarted: sandboxState.firstProviderRequestStarted,\n snapshotInFlight: Boolean(sandboxState.snapshotInFlight),\n turnEndCaptureInProgress: sandboxState.turnEndCaptureInProgress,\n deadlineRotationRequested: sandboxState.deadlineRotationRequested,\n })\n ) {\n const snapshot = maybePersistWarmWorkspaceSnapshot(\n { db, settings, objectStorage },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: snapshotTurnId,\n attemptId: input.attemptId,\n sandboxGroupId: heartbeatGroupId,\n },\n snapshotSession,\n heartbeatEpoch,\n activityContext?.cancellationSignal,\n );\n sandboxState.snapshotInFlight = snapshot.settled;\n void snapshot\n .then(async (persisted) => {\n if (persisted && eventing.publish) {\n await eventing.publish([\n {\n type: \"sandbox.box.snapshot\",\n payload: { trigger: \"heartbeat\" },\n },\n ]);\n }\n })\n .catch(() => undefined);\n void snapshot.settled.then(() => {\n if (sandboxState.snapshotInFlight === snapshot.settled) {\n sandboxState.snapshotInFlight = null;\n }\n });\n }\n }, 10_000);\n if (\n \"unref\" in sandboxState.leaseHeartbeatTimer &&\n typeof sandboxState.leaseHeartbeatTimer.unref === \"function\"\n ) {\n sandboxState.leaseHeartbeatTimer.unref();\n }\n };\n return {\n releaseLateSandbox,\n requireResolvedSandboxForMutation,\n finalizeTurnOpStreamOps,\n onHomeSandboxRebound,\n runWorkspaceMutationForSandbox,\n stopLeaseHeartbeat,\n flushRuntimeBatcher,\n publishSandboxLifecycleEvents,\n publishSandboxLost,\n startLeaseHeartbeat,\n };\n}\n","import {\n getEnrollment,\n getSandbox,\n readActiveSandbox,\n getLiveEnrollmentConnection,\n assertPersonalMachineForAttempt,\n type SandboxRecord,\n} from \"@opengeni/db\";\nimport { sandboxOperationMetricObserver } from \"@opengeni/observability\";\nimport {\n withRunCredentialsSession,\n runOwnedSandboxSetup,\n markModelPreparationFirstSandboxOperation,\n recordModelPreparationMeasurement,\n sdkBackendIdForSandboxBackend,\n type EstablishedSandboxSession,\n type GitCredentialTokenWriterSession,\n type NormalizedRunCredentialMaterial,\n type RunCredentialCommandSession,\n type CodemodeTokenWriterSession,\n type SelfhostedSession,\n resolveConnectedMachineWorkspaceRoot,\n} from \"@opengeni/runtime\";\nimport { type Settings } from \"@opengeni/config\";\nimport { managedSessionGroupBackend, managedSessionGroupOs } from \"@opengeni/core\";\nimport { mergeResourceRefs } from \"../common\";\nimport {\n mintSandboxCodemodeToken,\n type MintedRunGitCredentials,\n type SandboxCodemodeAuthority,\n} from \"../environment\";\nimport { rigProviderImageSourceImage } from \"../packs\";\nimport type { TurnActivityServices as ActivityServices, RunAgentTurnInput } from \"../types\";\nimport type { currentActivityContext } from \"../streaming\";\nimport { resumeBoxForTurn, type ResumedTurnSandbox } from \"../../sandbox-resume\";\nimport {\n wrapTurnBoxWithRouting,\n wrapLazyTurnBoxWithRouting,\n establishSelfhostedTurnSession,\n routingEnabled,\n} from \"../../sandbox-routing\";\nimport {\n makeMachineOpObserver,\n recordSandboxLogicalProvision,\n recordSandboxProvisionAttempt,\n recordSandboxSharedPreparation,\n recordTurnStartupPhase,\n runtimeMetricsHooksForObservability,\n} from \"../../observability-metrics\";\nimport { ToolResultSpill } from \"./tool-result-spill\";\nimport type { createTurnMediaArtifacts } from \"./media-artifacts\";\n\nimport {\n throwIfTurnOperationCancelled,\n waitForTurnOperation,\n classifySandboxLogicalProvisionFailure,\n isLazySandboxProvisionRetryable,\n createTurnSandboxProvisioner,\n} from \"./sandbox-provision\";\nimport {\n resolveActiveSandboxBackend,\n managedSandboxOwnershipForTurn,\n shouldEstablishSandboxForTurn,\n sandboxEstablishPolicyDecision,\n shouldPrefetchManagedSandbox,\n reconcileActiveSandboxPointer,\n sandboxSettingsForRoute,\n} from \"./sandbox-route\";\nimport type { ClaimTurnOk } from \"./claim\";\nimport type { GovernanceModelOk } from \"./governance-model\";\nimport type { SandboxTurnRuntime } from \"./sandbox-runtime\";\nimport type { AttemptIdentityState, EventingState, SandboxRuntimeState } from \"./turn-context\";\nimport { createSharedRigSetupCoordinator } from \"./sandbox-shared-preparation\";\n\nexport type SandboxRouteDeps = {\n input: RunAgentTurnInput;\n settings: Settings;\n db: ActivityServices[\"db\"];\n eventing: EventingState;\n sandboxState: SandboxRuntimeState;\n media: ReturnType<typeof createTurnMediaArtifacts>;\n fileAuthoritySubjectId: ClaimTurnOk[\"fileAuthoritySubjectId\"];\n runSettings: GovernanceModelOk[\"runSettings\"];\n logicalSandboxSettings: GovernanceModelOk[\"logicalSandboxSettings\"];\n};\n\nexport type SandboxRouteOk = {\n routingOn: boolean;\n activeSandboxPointer: Awaited<ReturnType<typeof readActiveSandbox>>;\n activeSandboxRecord: SandboxRecord | null;\n activeSandboxBackend: Settings[\"sandboxBackend\"] | undefined;\n machinePrimary: boolean;\n groupBoxBackend: Settings[\"sandboxBackend\"];\n groupBoxImage: ReturnType<typeof rigProviderImageSourceImage>;\n sandboxCreationBackend: Settings[\"sandboxBackend\"];\n effectiveRunCredentialBackend: Settings[\"sandboxBackend\"];\n};\n\nexport type EstablishTurnSandboxDeps = SandboxRouteOk & {\n input: RunAgentTurnInput;\n settings: Settings;\n db: ActivityServices[\"db\"];\n bus: ActivityServices[\"bus\"];\n objectStorage: ActivityServices[\"objectStorage\"];\n observability: ActivityServices[\"observability\"];\n cancellationSignal: AbortSignal | undefined;\n runtimeCancellationSignal: AbortSignal | undefined;\n sandboxResumeSignal: AbortSignal;\n activityContext: ReturnType<typeof currentActivityContext>;\n opJournal: ClaimTurnOk[\"opJournal\"];\n sandboxState: SandboxRuntimeState;\n eventing: EventingState;\n attempt: AttemptIdentityState;\n turn: ClaimTurnOk[\"turn\"];\n session: ClaimTurnOk[\"session\"];\n fileAuthoritySubjectId: ClaimTurnOk[\"fileAuthoritySubjectId\"];\n capabilitySettings: ClaimTurnOk[\"capabilitySettings\"];\n turnExecutionPolicy: ClaimTurnOk[\"turnExecutionPolicy\"];\n runSettings: GovernanceModelOk[\"runSettings\"];\n logicalSandboxSettings: GovernanceModelOk[\"logicalSandboxSettings\"];\n verifiedRigProviderImageId: GovernanceModelOk[\"verifiedRigProviderImageId\"];\n runtimePreparationStartedAt: number;\n establishPolicy: ReturnType<typeof sandboxEstablishPolicyDecision>[\"policy\"];\n sandboxEnvironment: Record<string, string>;\n startRunGitCredentialsMint: () => Promise<MintedRunGitCredentials | undefined>;\n machineOpObserver: ReturnType<typeof makeMachineOpObserver>;\n sandboxOperationObserver: ReturnType<typeof sandboxOperationMetricObserver>;\n sandboxRuntime: SandboxTurnRuntime;\n transientCodemodeEnvironment: (() => Readonly<Record<string, string>>) | undefined;\n rigVersion: GovernanceModelOk[\"rigVersion\"];\n turnResources: ReturnType<typeof mergeResourceRefs>;\n};\n\nexport type BindLazySandboxProvisionerDeps = EstablishTurnSandboxDeps & {\n agent: ReturnType<ActivityServices[\"runtime\"][\"buildAgent\"]>;\n attachRunCredentialRenewal: (\n credentialSession: RunCredentialCommandSession,\n initialMaterial: NormalizedRunCredentialMaterial | null,\n initialSandbox?: ResumedTurnSandbox,\n ) => Promise<void>;\n attachGitCredentialRenewal: (\n tokenSession: GitCredentialTokenWriterSession,\n initial: MintedRunGitCredentials | undefined,\n initialSandbox?: ResumedTurnSandbox,\n ) => Promise<void>;\n attachCodemodeTokenRenewal: (\n tokenSession?: CodemodeTokenWriterSession,\n initialExpiresAt?: Date,\n initialSandbox?: ResumedTurnSandbox,\n ) => Promise<void>;\n throwIfWorkerShuttingDown: () => void;\n throwIfTurnCancelled: () => void;\n initialRunCredentialMaterial: NormalizedRunCredentialMaterial | null;\n sandboxCodemodeToken: string | undefined;\n media: ReturnType<typeof createTurnMediaArtifacts>;\n toolResultSpill: ToolResultSpill;\n connectionScope: { accountId: string; workspaceId: string };\n codemodeAuthority: SandboxCodemodeAuthority;\n};\n\nexport async function resolveSandboxRoute(deps: SandboxRouteDeps): Promise<SandboxRouteOk> {\n const {\n input,\n settings,\n db,\n eventing,\n media,\n sandboxState,\n fileAuthoritySubjectId,\n runSettings,\n logicalSandboxSettings,\n } = deps;\n\n // EFFECTIVE compute backend, resolved ONCE at turn start (Case B + Stage D\n // D1-lite) and reused for EVERY downstream decision: the env mint (skip\n // inert platform git tokens for a machine turn), the establish path (no phantom Modal\n // home box for a machine-primary turn), buildAgent (skip the repository clone\n // hook so a private repo is never `git clone`d onto the user's real disk), and\n // the warm-rate (a machine accrues ZERO cloud warm-seconds). The active pointer\n // + its sandbox row are loaded ONCE here (best-effort, never throwing) and the\n // SAME values feed resolveActiveSandboxBackend (the tested gate) AND the\n // machine-primary establish branch (enrollmentId/epoch/workingDir) below — no\n // double read, no read-skew between the gate decision and the establish. With\n // routing OFF this is byte-for-byte the legacy path: no reads, undefined backend.\n const routingOn = routingEnabled(settings);\n let activeSandboxPointer = routingOn\n ? await readActiveSandbox(db, input.workspaceId, input.sessionId).catch(() => null)\n : null;\n // TURN-START RECONCILE (issue #341 invariant B / Shapes 1+2): a persisted\n // pointer whose target is STRUCTURALLY unestablishable at turn start would strand\n // EVERY op of this turn — reset it to the session HOME under the epoch fence +\n // emit a visible event, honoring a concurrent higher-epoch swap. The sandbox row\n // is loaded HERE, inside reconcile, via a NON-swallowing lookup: a null decision\n // then means the row is genuinely absent, never a suppressed transient DB error\n // (which would wrongly clear a healthy user-chosen pointer). On a lookup throw the\n // reconcile fails open — pointer untouched, record null (machinePrimary:false),\n // no event — and the establish branch below reads the returned values.\n let activeSandboxRecord: SandboxRecord | null = null;\n if (routingOn) {\n const reconciled = await reconcileActiveSandboxPointer(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n },\n activeSandboxPointer,\n (sandboxId) =>\n getSandbox(\n db,\n fileAuthoritySubjectId\n ? {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: fileAuthoritySubjectId,\n }\n : input.workspaceId,\n sandboxId,\n ),\n eventing.publish\n ? async (events) => {\n await eventing.publish!(events);\n }\n : undefined,\n );\n activeSandboxPointer = reconciled.pointer;\n activeSandboxRecord = reconciled.record;\n }\n const activeSandboxBackend = await resolveActiveSandboxBackend(\n routingOn,\n async () => activeSandboxPointer,\n async () => activeSandboxRecord?.kind ?? null,\n );\n // A machine-primary turn = the effective backend is selfhosted AND we have the\n // machine's enrollment (agent id) + a non-null pointer to bind it. Anything\n // missing (should not happen — the DB enforces selfhosted⇒enrollmentId) falls\n // back to the cloud establish path (a correct, if phantom, box) rather than\n // crashing the turn.\n const machinePrimary =\n activeSandboxBackend === \"selfhosted\" &&\n Boolean(activeSandboxPointer?.activeSandboxId) &&\n Boolean(activeSandboxRecord?.enrollmentId);\n // `none` describes the durable home, not an explicit per-turn route. Give\n // the runtime the effective backend so it builds a SandboxAgent for the\n // attached Connected Machine without mutating the session or turn record.\n if (machinePrimary && eventing.modelRunSettings.sandboxBackend === \"none\") {\n eventing.modelRunSettings = {\n ...eventing.modelRunSettings,\n sandboxBackend: \"selfhosted\",\n };\n }\n // The backend that can actually create a sandbox for this turn. In the\n // common path this is runSettings.sandboxBackend. A selfhosted home turn\n // that is NOT machine-primary falls back to the deployment cloud backend\n // so swap-away / flag-off degrade to a real group box.\n const groupBoxBackend: Settings[\"sandboxBackend\"] = !machinePrimary\n ? (managedSessionGroupBackend(settings.sandboxBackend, runSettings.sandboxBackend) ??\n runSettings.sandboxBackend)\n : runSettings.sandboxBackend;\n const groupRouteSettings = sandboxSettingsForRoute({\n runSettings,\n machinePrimary,\n groupBoxBackend,\n });\n if (groupRouteSettings !== runSettings) {\n // `modelRunSettings` drives SandboxAgent manifest construction and the\n // legacy SDK-owned client path. Keep its provider/model context overrides,\n // but replace the stale durable machine-home label with the route that will\n // actually execute.\n eventing.modelRunSettings = {\n ...eventing.modelRunSettings,\n sandboxBackend: groupRouteSettings.sandboxBackend,\n };\n }\n sandboxState.startupMilestoneBackend = activeSandboxBackend ?? groupBoxBackend;\n media.sandboxFileDownloadBackend = sandboxState.startupMilestoneBackend;\n // Durable lease identity is always the logical OCI/base image. A provider\n // image id in runSettings is only a physical cold-create optimization and\n // must never become cross-surface shared-state fencing.\n const groupBoxImage = rigProviderImageSourceImage(logicalSandboxSettings, groupBoxBackend);\n const sandboxCreationBackend: Settings[\"sandboxBackend\"] = groupRouteSettings.sandboxBackend;\n const effectiveRunCredentialBackend = activeSandboxBackend ?? groupBoxBackend;\n\n return {\n routingOn,\n activeSandboxPointer,\n activeSandboxRecord,\n activeSandboxBackend,\n machinePrimary,\n groupBoxBackend,\n groupBoxImage,\n sandboxCreationBackend,\n effectiveRunCredentialBackend,\n };\n}\n\nexport async function establishTurnSandbox(deps: EstablishTurnSandboxDeps): Promise<void> {\n const {\n input,\n settings,\n db,\n bus,\n objectStorage,\n observability,\n runtimeCancellationSignal,\n sandboxResumeSignal,\n opJournal,\n sandboxState,\n eventing,\n attempt,\n turn,\n session,\n fileAuthoritySubjectId,\n turnExecutionPolicy,\n runSettings,\n logicalSandboxSettings,\n runtimePreparationStartedAt,\n establishPolicy,\n sandboxEnvironment,\n startRunGitCredentialsMint,\n machineOpObserver,\n sandboxOperationObserver,\n sandboxRuntime,\n transientCodemodeEnvironment,\n activeSandboxPointer,\n activeSandboxRecord,\n activeSandboxBackend,\n machinePrimary,\n groupBoxBackend,\n groupBoxImage,\n rigVersion,\n turnResources,\n } = deps;\n const groupBoxOs = managedSessionGroupOs(runSettings.sandboxBackend, session.sandboxOs);\n const {\n releaseLateSandbox,\n onHomeSandboxRebound,\n publishSandboxLifecycleEvents,\n publishSandboxLost,\n startLeaseHeartbeat,\n } = sandboxRuntime;\n\n // P1.2 ownership inversion (gated, default OFF). With the flag off this\n // block is skipped entirely: resolvedSandbox stays null and runStream\n // takes the legacy per-run build-and-discard path — byte-for-byte today.\n // With it on, acquire the group lease (holder = the durable attempt id),\n // resume the one box by id, and inject it NON-OWNED into the run. The box\n // backend is \"none\" -> never resolve (no box to touch).\n //\n // Established AFTER sandboxEnvironment is computed (not before) so the box's\n // manifest is created with the SAME variableSet the agent declares — the SDK\n // applies the agent's manifest to this provided session and throws on ANY\n // variableSet delta (validateNoEnvironmentDelta). Passing sandboxEnvironment\n // here makes current==target so the delta is empty.\n recordTurnStartupPhase(observability, {\n phase: \"runtime_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - runtimePreparationStartedAt) / 1_000,\n });\n if (\n shouldEstablishSandboxForTurn(\n settings.sandboxOwnershipEnabled,\n turn.sandboxBackend,\n machinePrimary,\n )\n ) {\n const sandboxEstablishStartedAt = performance.now();\n let sandboxEstablishOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n const managedOwnership = managedSandboxOwnershipForTurn(\n machinePrimary,\n input.attemptId,\n session.sandboxGroupId,\n );\n sandboxState.sandboxHolderId = managedOwnership?.holderId ?? null;\n sandboxState.sandboxGroupId = managedOwnership?.sandboxGroupId ?? null;\n // STAGE D honest-label guard: a machine-home session carries\n // turn.sandboxBackend \"selfhosted\", but a turn is only machine-PRIMARY\n // when a live machine pointer resolves (activeSandboxBackend==='selfhosted'\n // + enrollmentId). When it is NOT primary — the agent swapped back to the\n // group box (sandbox_swap 'session'/'default'/groupId clears the pointer) or\n // selfhosted routing is flag-OFF (the pointer is ignored) — the else-branch\n // must resume a REAL cloud group box, not a \"selfhosted\" one: the registry\n // SelfhostedSandboxClient has no bound agentId and throws. Fall the group-box\n // backend back to the deployment default cloud backend so swap-away / flag-off\n // degrade to a genuine cloud box exactly like today (home=modal did).\n if (machinePrimary) {\n if (activeSandboxRecord!.scope === \"user\") {\n if (!fileAuthoritySubjectId) {\n throw new Error(\"personal machine use requires an initiating human subject\");\n }\n const authorized = await assertPersonalMachineForAttempt(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: fileAuthoritySubjectId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: turn.executionGeneration,\n enrollmentId: activeSandboxRecord!.enrollmentId!,\n });\n if (!authorized) {\n throw new Error(\"personal Connected Machine use was not admitted for this turn\");\n }\n }\n // STAGE D D1-lite: the active sandbox is a connected machine, so DO NOT\n // establish OR lease the managed home box. The active-sandbox pointer is\n // the machine route's own epoch fence; the managed-home lease separately\n // owns cloud recovery, snapshots, billing, and reaping. Mixing those two\n // ownership domains lets an unrelated degraded cloud archive block a\n // healthy explicitly selected machine.\n // Whether the machine's latest Hello advertised the op-stream engine\n // (refreshed on every connect). Read only when the server flag is on —\n // one indexed lookup, and the flag off keeps this path byte-identical.\n const liveMachineEnrollment = await getLiveEnrollmentConnection(\n db,\n activeSandboxRecord!.workspaceId,\n activeSandboxRecord!.enrollmentId!,\n );\n const machineEnrollment =\n liveMachineEnrollment ??\n (await getEnrollment(\n db,\n activeSandboxRecord!.workspaceId,\n activeSandboxRecord!.enrollmentId!,\n ));\n if (!machineEnrollment?.workspaceRoot) {\n throw new Error(\n \"Connected Machine has not reported an absolute workspace root; reconnect it with a current agent\",\n );\n }\n const machineWorkspaceRoot = resolveConnectedMachineWorkspaceRoot(\n machineEnrollment.workspaceRoot,\n activeSandboxPointer!.workingDir,\n );\n const machineOpStream =\n settings.agentOpStreamEnabled === true && liveMachineEnrollment?.opStream === true;\n const established = await establishSelfhostedTurnSession(\n {\n db,\n settings,\n bus,\n onOp: machineOpObserver.observer,\n onSandboxOperation: sandboxOperationObserver,\n opJournal,\n },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n controlWorkspaceId: activeSandboxRecord!.workspaceId,\n backgroundCommandAttempt: {\n turnId: turn.id,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n agentId: activeSandboxRecord!.enrollmentId!,\n // An offline machine must not fail turn admission. Bind an\n // intentionally unserved token so the model receives the normal\n // typed agent_offline tool result; a later turn resolves a fresh\n // claimed process instance.\n connectionInstanceId: liveMachineEnrollment?.connectionInstanceId ?? \"unavailable\",\n workspaceRoot: machineWorkspaceRoot,\n opStream: machineOpStream,\n operationResourcePolicy: liveMachineEnrollment?.operationPolicy ?? {\n memoryMaxBytes: null,\n memoryHighBytes: null,\n cpuMaxMillicores: null,\n revision: 0,\n updatedAt: null,\n },\n operationResourcePolicySupported:\n liveMachineEnrollment?.agentCapabilities.operationResourcePolicy === true,\n operationCpuQuotaSupported:\n liveMachineEnrollment?.agentCapabilities.operationCpuQuota === true,\n ...(activeSandboxRecord!.scope === \"user\" && fileAuthoritySubjectId\n ? {\n personalMachineAttempt: {\n accountId: input.accountId,\n subjectId: fileAuthoritySubjectId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n },\n }\n : {}),\n epoch: activeSandboxPointer!.activeEpoch,\n environment: sandboxEnvironment,\n ...(transientCodemodeEnvironment\n ? { transientExecEnvironment: transientCodemodeEnvironment }\n : {}),\n workingDir: activeSandboxPointer!.workingDir,\n },\n );\n // The machine-primary establish narrows `session` to SelfhostedSession\n // (buildSelfhostedBackendSession); EstablishedSandboxSession widens it.\n sandboxState.machinePrimarySession = established.session as SelfhostedSession;\n sandboxState.setupBoxSession = established.session;\n sandboxState.resolvedSandbox = {\n // Wrap in the SAME routing proxy so a mid-turn swap (to another machine\n // or back to the group box) still re-routes per op. PIN this established\n // SelfhostedSession for the machine pointer so the turn-start manifest\n // write (via the proxy's `state` getter) and the per-op reads hit ONE\n // instance — no two-instance manifest divergence.\n established: wrapTurnBoxWithRouting(\n {\n db,\n settings,\n bus,\n opJournal,\n onOp: machineOpObserver.observer,\n onSandboxOperation: sandboxOperationObserver,\n onHomeSandboxRebound,\n ...(runtimeCancellationSignal ? { waitSignal: runtimeCancellationSignal } : {}),\n },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n resourceAccountId: input.accountId,\n ...(fileAuthoritySubjectId ? { resourceSubjectId: fileAuthoritySubjectId } : {}),\n ...(fileAuthoritySubjectId\n ? {\n personalMachineAttempt: {\n accountId: input.accountId,\n subjectId: fileAuthoritySubjectId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n },\n }\n : {}),\n environment: sandboxEnvironment,\n ...(transientCodemodeEnvironment\n ? { transientExecEnvironment: transientCodemodeEnvironment }\n : {}),\n workspaceMutationFence: {\n accountId: input.accountId,\n turnId: turn.id,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n pinnedSelfhosted: {\n sandboxId: activeSandboxPointer!.activeSandboxId!,\n epoch: activeSandboxPointer!.activeEpoch,\n },\n // HOME semantics for a mid-turn clear-to-null: only a genuine\n // machine-HOME session (its home IS this machine, session.sandboxBackend\n // === \"selfhosted\") resolves null back to the pinned machine. A Modal-HOME\n // session merely PINNED to a machine this turn never established its group\n // box, so defaultIsHome:false makes a clear-to-null fail typed\n // (`home_unavailable_this_turn`) rather than silently serving the machine.\n // Failure settlement checkpoints the completed detach and continues the same\n // logical turn in a fresh home-primary attempt; it never serves this machine\n // after the pointer changed and never invents a cloud lease for machine-only work.\n defaultIsHome: session.sandboxBackend === \"selfhosted\",\n },\n established,\n ),\n // For a machine route this is the active-pointer epoch, not a cloud\n // lease epoch. Cloud-only heartbeat/snapshot/capture paths require\n // sandboxGroupId and remain disabled for this branch.\n leaseEpoch: activeSandboxPointer!.activeEpoch,\n release: async () => undefined,\n };\n } else if (establishPolicy === \"on-demand\") {\n // Lazy sandbox provisioning: holder/group ids are fixed at turn start,\n // but the lease acquire + box establish + setup move behind the routing\n // proxy's first default-pointer op. A chat-only turn never calls it, so\n // no lease row, no provider box, no warm-meter interval.\n //\n // A repository still forces that first default-pointer op before HTTP\n // (workspace-skill catalog in Agent.instructions). Start create now and\n // join it at get(); do not await here or we serialize Modal before tools.\n if (sandboxState.sandboxHolderId && sandboxState.sandboxGroupId) {\n const lazyHolderId = sandboxState.sandboxHolderId;\n const lazyGroupId = sandboxState.sandboxGroupId;\n sandboxState.resumeManagedGroupBox = () =>\n resumeBoxForTurn(\n {\n db,\n settings: runSettings,\n logicalFallbackSettings: logicalSandboxSettings,\n cancellationSignal: sandboxResumeSignal,\n sandboxMetrics: runtimeMetricsHooksForObservability(observability),\n onSandboxLost: publishSandboxLost,\n objectStorage,\n },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: lazyGroupId,\n sessionId: input.sessionId,\n backend: groupBoxBackend,\n os: groupBoxOs,\n environment: sandboxEnvironment,\n ...(groupBoxImage\n ? {\n image: groupBoxImage,\n }\n : {}),\n // The lazy acquire must enforce the same frozen rig authority\n // as the eager acquire; otherwise a warm box for another rig\n // can bypass the shared-state conflict/rotation fence.\n ...(rigVersion ? { rigVersionId: rigVersion.id } : {}),\n },\n \"turn\",\n lazyHolderId,\n );\n if (\n shouldPrefetchManagedSandbox({\n establishPolicy,\n machinePrimary,\n groupBoxBackend,\n hasRepositoryResources: turnResources.some(\n (resource) => resource.kind === \"repository\",\n ),\n })\n ) {\n startRunGitCredentialsMint();\n const started = waitForTurnOperation(\n sandboxState.resumeManagedGroupBox(),\n sandboxResumeSignal,\n releaseLateSandbox,\n );\n const joined = started.catch((error) => {\n if (isLazySandboxProvisionRetryable(error)) {\n sandboxState.prefetchedManagedBox = null;\n }\n throw error;\n });\n sandboxState.prefetchedManagedBox = joined;\n void joined.then(\n (box) => {\n if (sandboxResumeSignal.aborted) return;\n startLeaseHeartbeat(box, activeSandboxBackend ?? groupBoxBackend);\n },\n () => undefined,\n );\n }\n }\n } else {\n await eventing.publish!(\n [\n {\n type: \"sandbox.operation.started\",\n payload: { name: \"sandbox.provision\" },\n },\n ],\n true,\n );\n try {\n sandboxState.resolvedSandbox = await waitForTurnOperation(\n resumeBoxForTurn(\n {\n db,\n settings: runSettings,\n logicalFallbackSettings: logicalSandboxSettings,\n cancellationSignal: sandboxResumeSignal,\n sandboxMetrics: runtimeMetricsHooksForObservability(observability),\n onSandboxLost: publishSandboxLost,\n objectStorage,\n },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n sessionId: input.sessionId,\n // groupBoxBackend, not turn.sandboxBackend: a machine-home turn that\n // is not machine-primary resumes a real cloud group box (the\n // deployment default), never a \"selfhosted\" box (which would throw\n // for lack of a bound agentId).\n backend: groupBoxBackend,\n os: groupBoxOs,\n environment: sandboxEnvironment,\n // IMAGE IS SHARED STATE (B3): the container image\n // this run resolves. The lease stamps it + conflicts on a live shared box\n // running a DIFFERENT image (solo → durable rotation; N-holders →\n // SandboxImageConflictError surfaced as an actionable turn error). Select\n // the image for the actual group-box backend; a configured Modal image must\n // never override a Docker run. The selfhosted branch\n // (establishSelfhostedTurnSession) NEVER passes\n // an image — B3 lives only on this managed-box branch.\n ...(groupBoxImage\n ? {\n image: groupBoxImage,\n }\n : {}),\n // RIG IS SHARED STATE (M3): stamp the frozen rig version so the lease\n // conflicts on a live shared box set up under a different rig (solo\n // durable rotation / N-holders SandboxRigConflictError). Omitted for a\n // rig-less turn -> never stamped or enforced (shares exactly as today).\n ...(rigVersion ? { rigVersionId: rigVersion.id } : {}),\n },\n \"turn\",\n managedOwnership!.holderId,\n ),\n sandboxResumeSignal,\n releaseLateSandbox,\n );\n } catch (error) {\n await eventing.publish!(\n [\n {\n type: \"sandbox.operation.failed\",\n payload: {\n name: \"sandbox.provision\",\n error: error instanceof Error ? error.message : String(error),\n },\n },\n ],\n true,\n );\n throw error;\n }\n sandboxState.setupBoxSession = sandboxState.resolvedSandbox.established.session;\n // Durable box-lifecycle events (sandbox-file-persistence observability):\n // record every box transition in session_events so the NEXT box loss is\n // attributable from the DB alone — worker logs rotate within hours, which\n // left both 2026-07-06 incidents without a durable trace. Best-effort.\n await publishSandboxLifecycleEvents(sandboxState.resolvedSandbox);\n await eventing.publish!(\n [\n {\n type: \"sandbox.operation.completed\",\n payload: {\n name: \"sandbox.provision\",\n ...(sandboxState.resolvedSandbox.established.origin\n ? { origin: sandboxState.resolvedSandbox.established.origin }\n : {}),\n },\n },\n ],\n true,\n );\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 sandboxState.resolvedSandbox = {\n ...sandboxState.resolvedSandbox,\n established: wrapTurnBoxWithRouting(\n {\n db,\n settings,\n bus,\n opJournal,\n onSandboxOperation: sandboxOperationObserver,\n onHomeSandboxLost: publishSandboxLost,\n onHomeSandboxRebound,\n ...(runtimeCancellationSignal ? { waitSignal: runtimeCancellationSignal } : {}),\n },\n // Thread the SAME declared environment the group box was created with\n // (resumeBoxForTurn, above) so a selfhosted swap target's manifest\n // carries it too — the SDK's per-turn manifest-env delta stays empty\n // (no \"cannot change manifest environment variables\" throw).\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n resourceAccountId: input.accountId,\n ...(fileAuthoritySubjectId ? { resourceSubjectId: fileAuthoritySubjectId } : {}),\n ...(fileAuthoritySubjectId\n ? {\n personalMachineAttempt: {\n accountId: input.accountId,\n subjectId: fileAuthoritySubjectId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n },\n }\n : {}),\n environment: sandboxEnvironment,\n ...(transientCodemodeEnvironment\n ? { transientExecEnvironment: transientCodemodeEnvironment }\n : {}),\n workspaceMutationFence: {\n accountId: input.accountId,\n turnId: turn.id,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n homeLease: {\n accountId: input.accountId,\n sandboxGroupId: session.sandboxGroupId,\n leaseEpoch: sandboxState.resolvedSandbox.leaseEpoch,\n instanceId: sandboxState.resolvedSandbox.established.instanceId,\n backend: groupBoxBackend,\n },\n },\n sandboxState.resolvedSandbox.established,\n ),\n };\n }\n if (sandboxState.resolvedSandbox) {\n startLeaseHeartbeat(sandboxState.resolvedSandbox, activeSandboxBackend ?? groupBoxBackend);\n }\n } catch (error) {\n sandboxEstablishOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"sandbox_establish\",\n provider: turnExecutionPolicy.providerId,\n backend: machinePrimary ? \"selfhosted\" : groupBoxBackend,\n outcome: sandboxEstablishOutcome,\n durationSeconds: (performance.now() - sandboxEstablishStartedAt) / 1_000,\n });\n }\n }\n}\n\nexport async function bindLazySandboxProvisioner(\n deps: BindLazySandboxProvisionerDeps,\n): Promise<void> {\n const {\n input,\n settings,\n db,\n bus,\n observability,\n runtimeCancellationSignal,\n sandboxResumeSignal,\n opJournal,\n sandboxState,\n eventing,\n attempt,\n turn,\n session,\n fileAuthoritySubjectId,\n runSettings,\n sandboxEnvironment,\n groupBoxBackend,\n activeSandboxBackend,\n establishPolicy,\n startRunGitCredentialsMint,\n machineOpObserver,\n sandboxOperationObserver,\n sandboxRuntime,\n transientCodemodeEnvironment,\n agent,\n attachRunCredentialRenewal,\n attachGitCredentialRenewal,\n attachCodemodeTokenRenewal,\n throwIfWorkerShuttingDown,\n throwIfTurnCancelled,\n initialRunCredentialMaterial,\n sandboxCodemodeToken,\n media,\n toolResultSpill,\n connectionScope,\n codemodeAuthority,\n } = deps;\n const {\n releaseLateSandbox,\n onHomeSandboxRebound,\n publishSandboxLifecycleEvents,\n publishSandboxLost,\n startLeaseHeartbeat,\n runWorkspaceMutationForSandbox,\n } = sandboxRuntime;\n\n if (\n establishPolicy === \"on-demand\" &&\n sandboxState.sandboxHolderId &&\n sandboxState.sandboxGroupId\n ) {\n const agentDefaultManifest = (agent as { defaultManifest?: unknown }).defaultManifest;\n if (!agentDefaultManifest) {\n throw new Error(\"Lazy sandbox provisioning requires a SandboxAgent defaultManifest\");\n }\n const lazyClient = {\n backendId: sdkBackendIdForSandboxBackend(groupBoxBackend),\n } as EstablishedSandboxSession[\"client\"];\n let lazySandboxEstablishmentSettled = false;\n sandboxState.turnSandboxProvisioner = createTurnSandboxProvisioner<ResumedTurnSandbox>(\n async () => {\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n if (!sandboxState.resumeManagedGroupBox) {\n throw new Error(\"Lazy sandbox provisioning requires a managed group-box resume\");\n }\n startRunGitCredentialsMint();\n const provisioned = await (sandboxState.prefetchedManagedBox ??\n sandboxState.resumeManagedGroupBox());\n await publishSandboxLifecycleEvents(provisioned);\n // Return the REAL established box (NOT a copy whose session is the routing\n // proxy). resolveActiveBackend dispatches ops to `provisioned.established.session`;\n // if that were the proxy itself, proxy.exec -> dispatch -> resolve ->\n // provisioner.get() -> proxy.exec -> ... loops forever (an async infinite\n // recursion that HANGS the turn — caught live on staging 2026-07-08). The SDK\n // already holds the proxy directly (injected as lazyOwnedSandbox.session), so it\n // gets per-op routing; the worker-side handle (resolvedSandbox: release,\n // heartbeat, workspace capture) wants the real box, unproxied.\n return provisioned;\n },\n {\n signal: sandboxResumeSignal,\n onStarted: async ({ provisionId }) => {\n await eventing.publish?.(\n [\n {\n type: \"sandbox.operation.started\",\n payload: { name: \"sandbox.provision\", provisionId },\n },\n ],\n true,\n );\n },\n onAttemptSettled: ({ result, error, outcome, durationMs }) => {\n const successStage =\n result?.established.origin === \"created\"\n ? \"create\"\n : result?.established.origin === \"resumed\"\n ? \"resume\"\n : result?.established.origin === \"restored\"\n ? \"archive_recovery\"\n : \"unknown\";\n const failure = error\n ? classifySandboxLogicalProvisionFailure(groupBoxBackend, error)\n : null;\n recordSandboxProvisionAttempt(observability, {\n backend: groupBoxBackend,\n stage: failure?.stage ?? successStage,\n category: failure?.category ?? successStage,\n outcome,\n durationSeconds: durationMs / 1_000,\n });\n },\n beforeCompleted: async (provisioned, settlement) => {\n throwIfTurnOperationCancelled(sandboxResumeSignal);\n startLeaseHeartbeat(provisioned, activeSandboxBackend ?? groupBoxBackend);\n sandboxState.setupBoxSession = provisioned.established.session;\n sandboxState.resolvedSandbox = provisioned;\n // This durable completion and its logical metric close at actual box\n // establishment. Credential, rig, repository, and file preparation below\n // must never be attributed to \"Starting sandbox\" or provision latency.\n await eventing.publish?.(\n [\n {\n type: \"sandbox.operation.completed\",\n payload: {\n name: \"sandbox.provision\",\n ...(provisioned.established.origin\n ? { origin: provisioned.established.origin }\n : {}),\n provisionId: settlement.provisionId,\n internalAttempts: settlement.internalAttempts,\n },\n },\n ],\n true,\n );\n const successStage =\n provisioned.established.origin === \"created\"\n ? \"create\"\n : provisioned.established.origin === \"resumed\"\n ? \"resume\"\n : provisioned.established.origin === \"restored\"\n ? \"archive_recovery\"\n : \"unknown\";\n recordSandboxLogicalProvision(observability, {\n backend: groupBoxBackend,\n stage: successStage,\n category: \"none\",\n outcome: \"completed\",\n expected: false,\n internalAttempts: settlement.internalAttempts,\n durationSeconds: settlement.durationMs / 1_000,\n });\n lazySandboxEstablishmentSettled = true;\n\n const lazyGitCredentials =\n activeSandboxBackend === \"selfhosted\" ? undefined : await startRunGitCredentialsMint();\n const lazyGitTokens = lazyGitCredentials?.gitTokens;\n const lazyCodemodeToken = sandboxCodemodeToken\n ? await mintSandboxCodemodeToken(runSettings, connectionScope, codemodeAuthority)\n : undefined;\n await attachRunCredentialRenewal(\n provisioned.established.session as RunCredentialCommandSession,\n initialRunCredentialMaterial,\n provisioned,\n );\n const provisionedSetupSession = initialRunCredentialMaterial\n ? withRunCredentialsSession(provisioned.established.session as object, input.sessionId)\n : provisioned.established.session;\n await runWorkspaceMutationForSandbox(\n provisioned,\n \"lazyOwnedSandboxSetup\",\n async () =>\n await runOwnedSandboxSetup(\n agent,\n provisioned.established.session as never,\n provisionedSetupSession as never,\n {\n settings: runSettings,\n environment: sandboxEnvironment,\n onRuntimeEvent: async (event) => {\n await eventing.publish?.([{ type: event.type, payload: event.payload }], true);\n },\n ...(lazyGitTokens ? { gitTokenSeedsOverride: lazyGitTokens } : {}),\n ...(lazyGitCredentials?.bindings\n ? {\n gitCredentialBindingsOverride: lazyGitCredentials.bindings,\n }\n : {}),\n ...(lazyCodemodeToken\n ? {\n codemodeTokenSeedOverride: lazyCodemodeToken.token,\n }\n : {}),\n ...(eventing.toolCancellationFenceRef.current\n ? {\n commandRunner:\n eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(\n eventing.toolCancellationFenceRef.current,\n ),\n }\n : {}),\n ...(sandboxState.sandboxGroupId && sandboxState.sandboxHolderId\n ? {\n coordinateSharedRigSetup: createSharedRigSetupCoordinator({\n db,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: sandboxState.sandboxGroupId,\n attemptId: input.attemptId,\n holderId: sandboxState.sandboxHolderId,\n sandbox: provisioned,\n ...(runtimeCancellationSignal\n ? { signal: runtimeCancellationSignal }\n : {}),\n observe: (measurement) =>\n recordSandboxSharedPreparation(observability, measurement),\n }),\n }\n : {}),\n },\n ),\n (measurement) => {\n if (eventing.firstModelRequestPreparationRecorded) return;\n sandboxState.firstModelPreparationNestedSandboxMs +=\n measurement.durationSeconds * 1_000;\n sandboxState.firstModelPreparationNestedSandboxPhases.push(measurement);\n },\n );\n await attachCodemodeTokenRenewal(\n provisioned.established.session as CodemodeTokenWriterSession,\n lazyCodemodeToken?.expiresAt,\n provisioned,\n );\n await attachGitCredentialRenewal(\n provisioned.established.session as GitCredentialTokenWriterSession,\n lazyGitCredentials,\n provisioned,\n );\n // `get()` does not release the first routed sandbox operation\n // until this hook returns. Only images created during this exact\n // turn can require deferred delivery here; historical images stay\n // as durable receipts and are restored explicitly when requested.\n for (const receipt of media.generatedImageReceiptsCreatedThisTurn.values()) {\n await media.materializeGeneratedImageInSandbox(\n receipt,\n provisioned,\n provisioned.established.session,\n );\n }\n await toolResultSpill.materializeDeferred();\n throwIfTurnOperationCancelled(sandboxResumeSignal);\n },\n onFailed: async (error, settlement) => {\n if (lazySandboxEstablishmentSettled) return;\n const failure = classifySandboxLogicalProvisionFailure(groupBoxBackend, error);\n await eventing.publish?.(\n [\n {\n type: \"sandbox.operation.failed\",\n payload: {\n name: \"sandbox.provision\",\n error: error instanceof Error ? error.message : String(error),\n provisionId: settlement.provisionId,\n internalAttempts: settlement.internalAttempts,\n failureCategory: failure.category,\n failureStage: failure.stage,\n failureCode: failure.code,\n expectedTransition: failure.expected,\n retryable: failure.retryable,\n },\n },\n ],\n true,\n );\n recordSandboxLogicalProvision(observability, {\n backend: groupBoxBackend,\n stage: failure.stage,\n category: failure.category,\n outcome: failure.expected ? \"expected_transition\" : \"failed\",\n expected: failure.expected,\n internalAttempts: settlement.internalAttempts,\n durationSeconds: settlement.durationMs / 1_000,\n });\n },\n disposeResult: async (provisioned) => {\n await releaseLateSandbox(provisioned);\n },\n },\n );\n sandboxState.lazyOwnedSandbox = wrapLazyTurnBoxWithRouting(\n {\n db,\n settings,\n bus,\n opJournal,\n onOp: machineOpObserver.observer,\n onSandboxOperation: sandboxOperationObserver,\n onHomeSandboxLost: publishSandboxLost,\n onHomeSandboxRebound,\n ...(runtimeCancellationSignal ? { waitSignal: runtimeCancellationSignal } : {}),\n },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n resourceAccountId: input.accountId,\n ...(fileAuthoritySubjectId ? { resourceSubjectId: fileAuthoritySubjectId } : {}),\n ...(fileAuthoritySubjectId\n ? {\n personalMachineAttempt: {\n accountId: input.accountId,\n subjectId: fileAuthoritySubjectId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n },\n }\n : {}),\n environment: sandboxEnvironment,\n ...(transientCodemodeEnvironment\n ? { transientExecEnvironment: transientCodemodeEnvironment }\n : {}),\n workspaceMutationFence: {\n accountId: input.accountId,\n turnId: turn.id,\n executionGeneration: attempt.executionGeneration,\n attemptId: input.attemptId,\n },\n },\n {\n client: lazyClient,\n backendId: sdkBackendIdForSandboxBackend(groupBoxBackend),\n agentDefaultManifest,\n provisioner: sandboxState.turnSandboxProvisioner,\n homeLeaseIdentity: {\n accountId: input.accountId,\n sandboxGroupId: session.sandboxGroupId,\n backend: groupBoxBackend,\n },\n onFirstOperation: (measurement) => {\n if (eventing.firstModelRequestPreparationRecorded) return;\n markModelPreparationFirstSandboxOperation(measurement.durationMs / 1_000);\n\n for (const nested of sandboxState.firstModelPreparationNestedSandboxPhases) {\n if (nested.phase === \"snapshot_wait\") continue;\n recordModelPreparationMeasurement({\n phase:\n nested.phase === \"admission\"\n ? \"sandbox_workspace_mutation_admission\"\n : nested.phase === \"provider\"\n ? \"sandbox_workspace_mutation_provider\"\n : \"sandbox_workspace_mutation_settlement\",\n outcome: nested.outcome,\n durationSeconds: nested.durationSeconds,\n });\n }\n\n const resolution = measurement.phases.resolution;\n if (resolution) {\n recordModelPreparationMeasurement({\n phase: \"sandbox_first_routed_resolution_other\",\n outcome: resolution.outcome,\n durationSeconds:\n Math.max(\n 0,\n resolution.durationMs - sandboxState.firstModelPreparationNestedSandboxMs,\n ) / 1_000,\n });\n }\n\n const routedPhaseNames = [\n [\"mutationAdmission\", \"sandbox_first_routed_mutation_admission\"],\n [\"providerOperation\", \"sandbox_first_routed_provider_operation\"],\n [\"mutationSettlement\", \"sandbox_first_routed_mutation_settlement\"],\n ] as const;\n for (const [phaseName, metricPhase] of routedPhaseNames) {\n const phase = measurement.phases[phaseName];\n if (!phase) continue;\n recordModelPreparationMeasurement({\n phase: metricPhase,\n outcome: phase.outcome,\n durationSeconds: phase.durationMs / 1_000,\n });\n }\n\n const nestedSnapshotPhases = sandboxState.firstModelPreparationNestedSandboxPhases.filter(\n (phase) => phase.phase === \"snapshot_wait\",\n );\n const routedSnapshot = measurement.phases.snapshotWait;\n const snapshotWaitMs =\n nestedSnapshotPhases.reduce(\n (total, phase) => total + phase.durationSeconds * 1_000,\n 0,\n ) + (routedSnapshot?.durationMs ?? 0);\n if (snapshotWaitMs > 0) {\n recordModelPreparationMeasurement({\n phase: \"sandbox_snapshot_wait\",\n outcome:\n routedSnapshot?.outcome === \"failed\" ||\n nestedSnapshotPhases.some((phase) => phase.outcome === \"failed\")\n ? \"failed\"\n : \"completed\",\n durationSeconds: snapshotWaitMs / 1_000,\n });\n }\n\n const routedMeasuredMs = Object.values(measurement.phases).reduce(\n (total, phase) => total + (phase?.durationMs ?? 0),\n 0,\n );\n const routedOtherMs = Math.max(0, measurement.durationMs - routedMeasuredMs);\n if (routedOtherMs > 0) {\n recordModelPreparationMeasurement({\n phase: \"sandbox_first_routed_other\",\n outcome: measurement.outcome,\n durationSeconds: routedOtherMs / 1_000,\n });\n }\n },\n },\n );\n }\n}\n","import {\n readActiveSandbox,\n setActiveSandbox,\n type ActiveSandboxPointer,\n type SandboxRecord,\n} from \"@opengeni/db\";\nimport {\n ensureModalRegistryImage,\n swapTargetEstablishability,\n type BackendUnresolvableCode,\n} from \"@opengeni/runtime\";\nimport { type Settings } from \"@opengeni/config\";\nimport type { TurnActivityServices as ActivityServices } from \"../types\";\nimport {\n sandboxLeaseHolderIdForAttempt,\n type TurnSandboxLeaseHolderId,\n} from \"../../sandbox-resume\";\nimport { type TurnSandboxEstablishReason } from \"../../observability-metrics\";\nimport { type SessionEventType } from \"@opengeni/contracts\";\nimport { safeErrorDiagnostic } from \"./errors\";\n\nexport async function resolveActiveSandboxBackend(\n routingOn: boolean,\n loadPointer: () => Promise<{ activeSandboxId: string | null } | null>,\n loadSandboxKind: (sandboxId: string) => Promise<string | null>,\n): Promise<Settings[\"sandboxBackend\"] | undefined> {\n // The active pointer + swap tools only exist when selfhosted routing is on; with\n // the flag off there is nothing to resolve and we keep the home-backend default.\n if (!routingOn) {\n return undefined;\n }\n try {\n const pointer = await loadPointer();\n // A null pointer (no swap) means \"use the session's own cloud group box\" — the\n // home backend already governs that path, so leave the override unset.\n if (!pointer?.activeSandboxId) {\n return undefined;\n }\n const kind = await loadSandboxKind(pointer.activeSandboxId);\n return kind === \"selfhosted\" ? \"selfhosted\" : undefined;\n } catch (error) {\n console.error(\n \"active sandbox backend resolution failed (turn proceeds on home backend)\",\n safeErrorDiagnostic(error),\n );\n return undefined;\n }\n}\n\n/**\n * Managed-sandbox ownership exists only when this turn actually uses the\n * managed home. A Connected Machine is fenced by its active-route epoch and\n * must remain independent from cloud recovery state for the same session.\n */\nexport function managedSandboxOwnershipForTurn(\n machinePrimary: boolean,\n attemptId: string,\n sandboxGroupId: string,\n): { holderId: TurnSandboxLeaseHolderId; sandboxGroupId: string } | null {\n if (machinePrimary) return null;\n return {\n holderId: sandboxLeaseHolderIdForAttempt(attemptId),\n sandboxGroupId,\n };\n}\n\n/**\n * Bind backend-aware runtime settings to the route that will actually execute.\n *\n * A machine-home turn keeps `selfhosted` as its durable policy. After an\n * explicit clear-to-default, however, both the ownership-inverted path and the\n * legacy SDK-owned path must construct manifests and clients for the resolved\n * managed group backend. Machine-primary and ordinary session routes preserve\n * their existing settings object.\n */\nexport function sandboxSettingsForRoute(input: {\n runSettings: Settings;\n machinePrimary: boolean;\n groupBoxBackend: Settings[\"sandboxBackend\"];\n}): Settings {\n return input.runSettings.sandboxBackend === \"selfhosted\" &&\n !input.machinePrimary &&\n input.groupBoxBackend !== \"selfhosted\"\n ? { ...input.runSettings, sandboxBackend: input.groupBoxBackend }\n : input.runSettings;\n}\n\n/** A sandboxless home still establishes an explicitly attached Connected Machine. */\nexport function shouldEstablishSandboxForTurn(\n sandboxOwnershipEnabled: boolean,\n homeBackend: Settings[\"sandboxBackend\"],\n machinePrimary: boolean,\n): boolean {\n return sandboxOwnershipEnabled && (homeBackend !== \"none\" || machinePrimary);\n}\n\nexport function sandboxEstablishPolicyDecision(input: {\n lazyEnabled: boolean;\n machinePrimary: boolean;\n sandboxBackend: Settings[\"sandboxBackend\"];\n hasRunCredentialResolver: boolean;\n generatedVideoFileCount: number;\n hasSignedFileResources: boolean;\n}): { policy: \"eager\" | \"on-demand\"; reason: TurnSandboxEstablishReason } {\n if (!input.lazyEnabled) return { policy: \"eager\", reason: \"lazy_disabled\" };\n if (input.machinePrimary) return { policy: \"eager\", reason: \"machine_primary\" };\n if (input.sandboxBackend === \"none\") return { policy: \"eager\", reason: \"backend_none\" };\n if (input.generatedVideoFileCount > 0) {\n return { policy: \"eager\", reason: \"generated_video_files\" };\n }\n // Signed file downloads must finish before the first model boundary so any\n // integrity/download failure is present in the prepared input. Deferring the\n // box until the first tool call would make that first request advertise a\n // path whose materialization outcome is not known yet.\n if (input.hasSignedFileResources) {\n return { policy: \"eager\", reason: \"signed_file_resources\" };\n }\n // Merely having a host run-credential resolver is not proof that this turn\n // will use the sandbox. Resolve its attempt-bound material before model input\n // so auth-needed context remains deterministic, but defer every sandbox\n // write, lease, renewal, and cleanup action to the first-operation\n // provisioner. The eager file paths above remain unchanged.\n if (input.hasRunCredentialResolver) {\n return { policy: \"on-demand\", reason: \"initial_run_credentials_deferred\" };\n }\n return { policy: \"on-demand\", reason: \"eligible\" };\n}\n\n/**\n * Repo-backed workspace skills bind into the first-request prompt-cache prefix\n * (`WorkspaceSkillsCapability.instructions()` listDirs the live box). Starting\n * the managed-box establish as soon as its inputs exist lets Modal create overlap\n * tools/history/agent; `get()` still owns clone/setup after `buildAgent`.\n *\n * Do not flip those turns to eager: that serializes create BEFORE tools and\n * increases first-token latency. Chat-only turns without a repository still\n * never create a box. Portable `/compact` returns before this path. Connected\n * Machines and `backend: none` have no managed Modal/docker create to overlap.\n */\nexport function shouldPrefetchManagedSandbox(input: {\n establishPolicy: \"eager\" | \"on-demand\";\n machinePrimary: boolean;\n groupBoxBackend: Settings[\"sandboxBackend\"];\n hasRepositoryResources: boolean;\n}): boolean {\n if (input.establishPolicy !== \"on-demand\") return false;\n if (input.machinePrimary) return false;\n if (input.groupBoxBackend === \"none\" || input.groupBoxBackend === \"selfhosted\") {\n return false;\n }\n return input.hasRepositoryResources;\n}\n\n/**\n * Classify a persisted active-sandbox pointer for TURN-START RECONCILE (issue #341\n * invariant B). Returns the typed reason to RESET the pointer to the session HOME,\n * or null to leave it in place. STRUCTURAL unestablishability only:\n * - no record → the pointed-at sandbox row is gone (`stale_pointer`);\n * - an unestablishable kind (a non-group Modal sibling, or an unknown backend) per\n * the SHARED `swapTargetEstablishability` predicate (`unsupported_backend_context`);\n * - a selfhosted sandbox with no enrollment id to address (`offline_enrollment`).\n * A selfhosted sandbox WITH an enrollment is deliberately left in place even when it\n * is momentarily offline: the machine may recover mid-turn and its ops surface\n * agent_offline lazily, so the user's explicit machine target is never abandoned for\n * a transient control-plane blip (that is #339's concern, not this one).\n */\nexport function pointerReconcileReason(\n record: { kind: string; enrollmentId: string | null } | null,\n): BackendUnresolvableCode | null {\n if (!record) {\n return \"stale_pointer\";\n }\n const establishable = swapTargetEstablishability({\n kind: record.kind,\n isSessionGroup: false,\n });\n if (!establishable.ok) {\n return establishable.code;\n }\n if (record.kind === \"selfhosted\" && !record.enrollmentId) {\n return \"offline_enrollment\";\n }\n return null;\n}\n\n/** The active pointer + its sandbox row, loaded once at turn start and threaded\n * through the reconcile so the establish branch reads the SAME (possibly reset)\n * values with no second query. */\nexport type LoadedActivePointer = {\n pointer: ActiveSandboxPointer | null;\n record: SandboxRecord | null;\n};\n\n/**\n * TURN-START RECONCILE (issue #341 invariant B / Shapes 1+2). If the persisted pointer's\n * target is STRUCTURALLY unestablishable ({@link pointerReconcileReason}) reset the pointer\n * to the session HOME (null) under the epoch fence, emit a VISIBLE `session.route.reconciled`\n * event, and return the reconciled pointer/record so the rest of the turn runs on home. NEVER\n * a silent downgrade. Bounded to ONE attempt: a lost CAS means a concurrent user swap won a\n * higher epoch, so re-read + honor it rather than clobber a newer, user-directed pointer. The\n * event publish is best-effort — a publish failure never fails the turn.\n *\n * FAIL-OPEN on a lookup failure (issue #341 review): the sandbox row is fetched HERE via the\n * caller's NON-swallowing `loadRecord`, so a null decision means the row is genuinely absent,\n * never a suppressed transient DB error. If `loadRecord` THROWS, reconciliation is skipped\n * entirely this turn — the pointer is left UNTOUCHED (record null → the turn runs\n * machinePrimary:false on the group box exactly as before reconcile existed), no CAS, no\n * event — and the next turn retries. A TRANSIENT LOOKUP FAILURE MUST NEVER MUTATE THE POINTER.\n */\nexport async function reconcileActiveSandboxPointer(\n db: ActivityServices[\"db\"],\n ids: { accountId: string; workspaceId: string; sessionId: string },\n pointer: ActiveSandboxPointer | null,\n loadRecord: (sandboxId: string) => Promise<SandboxRecord | null>,\n publish?: (events: Array<{ type: SessionEventType; payload: unknown }>) => Promise<void> | void,\n): Promise<LoadedActivePointer> {\n if (!pointer?.activeSandboxId) {\n return { pointer, record: null };\n }\n // Re-fetch the row WITHOUT error swallowing. A throw here (a transient DB blip) is NOT\n // \"row absent\": fail open — skip reconciliation, leave the pointer untouched.\n let record: SandboxRecord | null;\n try {\n record = await loadRecord(pointer.activeSandboxId);\n } catch {\n return { pointer, record: null };\n }\n const reason = pointerReconcileReason(record);\n if (!reason) {\n return { pointer, record };\n }\n const fromEpoch = pointer.activeEpoch;\n const reset = await setActiveSandbox(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n targetSandboxId: null,\n expectedEpoch: fromEpoch,\n }).catch(\n () => ({ swapped: false, pointer: null }) as Awaited<ReturnType<typeof setActiveSandbox>>,\n );\n if (reset.swapped && reset.pointer) {\n await Promise.resolve(\n publish?.([\n {\n type: \"session.route.reconciled\",\n payload: { reason, fromEpoch, toEpoch: reset.pointer.activeEpoch },\n },\n ]),\n ).catch(() => undefined);\n return { pointer: reset.pointer, record: null };\n }\n // The fence was lost: a concurrent higher-epoch swap won. Honor the newer pointer; its\n // record is re-fetched fail-open too (a transient failure leaves record null, never a\n // mutation — we already did not win the CAS).\n const reread = await readActiveSandbox(db, ids.workspaceId, ids.sessionId).catch(() => null);\n if (!reread) {\n return { pointer, record: null };\n }\n let rereadRecord: SandboxRecord | null = null;\n if (reread.activeSandboxId) {\n try {\n rereadRecord = await loadRecord(reread.activeSandboxId);\n } catch {\n rereadRecord = null;\n }\n }\n return { pointer: reread, record: rereadRecord };\n}\n\n/**\n * Warm the Modal private-registry image for the image ref this turn actually\n * resolved, not only the deployment-global OPENGENI_MODAL_IMAGE_REF warmed at\n * worker boot. A provider-native modalImageId bypasses registry import and is\n * resolved by ModalImageSelector.fromId during create. Otherwise packs can\n * override `modalImageRef` per workspace/turn, so a private pack image must be\n * resolved before sandbox creation or Modal falls back to the unauthenticated\n * `fromTag` path.\n */\nexport async function ensureTurnModalRegistryImage(\n runSettings: Settings,\n sandboxCreationBackend: Settings[\"sandboxBackend\"] | undefined,\n ensureRegistryImage: (settings: Settings) => Promise<void> = ensureModalRegistryImage,\n): Promise<void> {\n if (sandboxCreationBackend !== \"modal\") {\n return;\n }\n if (runSettings.modalImageId) {\n return;\n }\n if (!runSettings.modalImageRegistrySecret || !runSettings.modalImageRef) {\n return;\n }\n await ensureRegistryImage(runSettings);\n}\n\nexport const SANDBOX_ARTIFACT_RUNTIME_MANIFEST = \"/opt/opengeni/artifact-runtime/installation.json\";\nexport const SANDBOX_ARTIFACT_TOOL_ENTRY = \"/opt/opengeni/artifact-runtime/skill-facade-entry.mjs\";\n\nexport type SandboxArtifactRuntimeAdmission = Readonly<{\n available: boolean;\n environment: Readonly<Record<string, string>>;\n}>;\n\n/**\n * Admit the optional native standalone-file runtime only for the deployment's\n * exact base sandbox image contract. A pack/rig image override is an\n * independent filesystem and therefore fails closed even when the deployment\n * base image is capable. Collaborative artifact skills are admitted separately\n * from the frozen canonical tool catalog.\n *\n * This keeps lazy provisioning intact: CI/release proves the image closure,\n * while a before-agent-start doctor verifies the actual box before any model\n * call. No speculative sandbox is created merely to populate the skill index.\n */\nexport function sandboxArtifactRuntimeAdmission(\n deploymentSettings: Settings,\n runSettings: Settings,\n backend: Settings[\"sandboxBackend\"] | undefined,\n options: Readonly<{ production?: boolean }> = {},\n): SandboxArtifactRuntimeAdmission {\n if (!deploymentSettings.sandboxArtifactRuntimeEnabled) {\n return { available: false, environment: {} };\n }\n const production = options.production ?? process.env.NODE_ENV === \"production\";\n if (backend === \"docker\") {\n const image = deploymentSettings.dockerImage;\n const localDevelopmentImage = /^opengeni-sandbox:local-[0-9a-f]{12}$/u.test(image);\n if (\n runSettings.dockerImage !== image ||\n (!/@sha256:[0-9a-f]{64}$/u.test(image) && (production || !localDevelopmentImage))\n ) {\n return { available: false, environment: {} };\n }\n } else if (backend === \"modal\") {\n if (\n !deploymentSettings.modalImageRef ||\n !/@sha256:[0-9a-f]{64}$/u.test(deploymentSettings.modalImageRef) ||\n runSettings.modalImageRef !== deploymentSettings.modalImageRef ||\n runSettings.modalImageId !== deploymentSettings.modalImageId\n ) {\n return { available: false, environment: {} };\n }\n } else {\n return { available: false, environment: {} };\n }\n return {\n available: true,\n environment: {\n OPENGENI_ARTIFACT_RUNTIME_MANIFEST: SANDBOX_ARTIFACT_RUNTIME_MANIFEST,\n OPENGENI_ARTIFACT_TOOL_ENTRY: SANDBOX_ARTIFACT_TOOL_ENTRY,\n },\n };\n}\n","import { connectionModelAllowed } from \"@opengeni/db\";\nimport {\n getSessionGoal,\n acquireXaiCredentialLease,\n getXaiSessionAccountPin,\n setXaiSessionAccountPin,\n recordXaiSessionLastAccount,\n XAI_CREDENTIAL_LEASE_TTL_MS,\n armXaiCapacityWait,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\n\nimport type { CapacityPhaseDeps, CapacityPhaseOutcome } from \"./codex-capacity\";\nimport { refreshExhaustedXaiQuota } from \"../xai-quota\";\n\nexport async function selectXaiTurnCapacity(\n deps: CapacityPhaseDeps,\n): Promise<CapacityPhaseOutcome> {\n const {\n input,\n db,\n bus,\n dispatchId,\n control,\n billingState,\n eventing,\n providerTurn,\n leases,\n claimedResult,\n turn,\n } = deps;\n\n if (billingState.isXaiTurn) {\n const authoritySnapshot = turn.xaiProviderAccountAuthoritySnapshot;\n providerTurn.xaiAuthoritySnapshot = authoritySnapshot;\n const subjectId =\n authoritySnapshot.scope === \"user\" ? turn.initiatingHumanSubjectId : \"worker:xai-workspace\";\n if (!subjectId) {\n throw new Error(\"User-scoped SuperGrok work has no frozen initiating human\");\n }\n const sessionPin = await getXaiSessionAccountPin(db, {\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n });\n const leaseStartedAtMs = performance.now();\n await refreshExhaustedXaiQuota({\n db,\n settings: deps.settings,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n turnId: turn.id,\n authoritySnapshot,\n });\n const leased = await acquireXaiCredentialLease(db, {\n modelId: deps.turnExecutionPolicy.productModelId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n turnId: turn.id,\n holderId: dispatchId,\n authoritySnapshot,\n pinnedCredentialId: sessionPin?.pinnedCredentialId ?? null,\n pinSource:\n sessionPin?.pinSource === \"manual\" || sessionPin?.pinSource === \"policy\"\n ? sessionPin.pinSource\n : null,\n });\n providerTurn.effectiveXaiCredentialId = leased.credentialId;\n providerTurn.xaiRotationEnabled = leased.rotationEnabled;\n leases.xai.subjectId = subjectId;\n leases.xai.holderId = leased.holderId;\n leases.xai.generation = leased.generation;\n leases.xai.confirmedUntilMs = leased.leasedUntil\n ? leaseStartedAtMs + XAI_CREDENTIAL_LEASE_TTL_MS\n : null;\n leases.xai.held =\n providerTurn.effectiveXaiCredentialId !== null &&\n leased.holderId !== null &&\n leased.generation !== null &&\n leases.xai.confirmedUntilMs !== null;\n if (!providerTurn.effectiveXaiCredentialId) {\n const relevant =\n sessionPin?.pinnedCredentialId && sessionPin.pinSource !== \"policy\"\n ? leased.accounts.filter((account) => account.id === sessionPin.pinnedCredentialId)\n : leased.accounts;\n if (\n relevant.length > 0 &&\n relevant.every(\n (account) =>\n !connectionModelAllowed(\n account.allowedModelIds,\n deps.turnExecutionPolicy.productModelId,\n ),\n )\n )\n throw new Error(\"This model is disabled for the selected SuperGrok subscription\");\n const connected = leased.accounts.length;\n const allocatorEnabled = leased.accounts.filter((account) => account.allocatorEnabled).length;\n if (connected === 0) {\n throw Object.assign(\n new Error(\"No SuperGrok subscription account is connected for this authority scope\"),\n { code: \"xai_not_connected\" },\n );\n }\n if (turn.source === \"compaction\") {\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.cancelled\",\n payload: {\n maintenance: \"context_compaction\",\n reason: \"xai_capacity_unavailable\",\n requestPreserved: true,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"cancelled\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n control.turnMetricOutcome = \"cancelled\";\n control.activityStatus = \"idle\";\n return { exit: claimedResult({ status: \"idle\", deferredUntilWake: true }) };\n }\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId).catch(() => null);\n const activeGoal = goal?.status === \"active\" ? goal : null;\n const now = new Date();\n const futureResets = leased.accounts\n .map((account) => account.exhaustedUntil)\n .filter((date): date is Date => date !== null && date > now);\n const earliestResetAt = futureResets.length\n ? new Date(Math.min(...futureResets.map((date) => date.getTime())))\n : null;\n const error =\n allocatorEnabled === 0\n ? \"All connected SuperGrok subscription accounts are disabled for allocation\"\n : \"All connected SuperGrok subscription accounts are temporarily unavailable\";\n const armed = await armXaiCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n authoritySnapshot,\n goalId: activeGoal?.id ?? null,\n goalVersion: activeGoal?.version ?? null,\n earliestResetAt,\n failurePayload: {\n error,\n code: allocatorEnabled === 0 ? \"xai_allocator_disabled\" : \"xai_capacity_unavailable\",\n detail: \"waiting for an eligible account, reconnect, pin change, or quota reset\",\n },\n });\n if (armed.action === \"waiting\") {\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, armed.events);\n control.turnMetricOutcome = \"recovering\";\n control.activityStatus = \"waiting_capacity\";\n return {\n exit: claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n provider: \"xai\",\n waiterId: armed.waiter.id,\n generation: armed.waiter.generation,\n nextCheckAt: armed.waiter.nextCheckAt.toISOString(),\n wakeRevision: armed.waiter.wakeRevision,\n },\n }),\n };\n }\n if (\n !(await eventing.settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error,\n code: \"xai_capacity_wait_stale\",\n retryable: false,\n recovery: \"user_message\",\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return { exit: claimedResult({ status: \"cancelled\" }) };\n }\n control.turnMetricOutcome = \"failed\";\n control.activityStatus = \"idle\";\n return { exit: claimedResult({ status: \"idle\" }) };\n }\n if (leases.xai.held) leases.xai.startHeartbeat();\n if (\n leased.rotationEnabled &&\n sessionPin?.pinSource !== \"manual\" &&\n (sessionPin?.pinnedCredentialId !== providerTurn.effectiveXaiCredentialId ||\n sessionPin?.pinSource !== \"policy\")\n ) {\n await setXaiSessionAccountPin(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n credentialId: providerTurn.effectiveXaiCredentialId,\n pinSource: \"policy\",\n expectedVersion: sessionPin?.version ?? null,\n }).catch((error: unknown) => {\n if (error instanceof Error && error.message === \"xAI session pin changed\") return;\n throw error;\n });\n } else if (!leased.rotationEnabled && sessionPin?.pinSource === \"policy\") {\n await setXaiSessionAccountPin(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n credentialId: null,\n pinSource: null,\n expectedVersion: sessionPin.version,\n }).catch((error: unknown) => {\n if (error instanceof Error && error.message === \"xAI session pin changed\") return;\n throw error;\n });\n }\n await recordXaiSessionLastAccount(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n credentialId: providerTurn.effectiveXaiCredentialId,\n });\n }\n\n return { ok: true };\n}\n","import { getSessionRootId, resolvePrReviewGitCredential } from \"@opengeni/db\";\nimport { prReviewRegistrationIdFromCredentialBinding } from \"@opengeni/core\";\nimport {\n materializeRunCredentials,\n clearRunCredentials,\n clearRunCredentialsForAttempt,\n refreshGitCredentialBindingTokenFiles,\n refreshCodemodeTokenFile,\n codemodeTokenFileFromEnvironment,\n type GitCredentialTokenWriterSession,\n type NormalizedRunCredentialMaterial,\n type RunCredentialCommandSession,\n type CodemodeTokenWriterSession,\n} from \"@opengeni/runtime\";\nimport { codemodeWorkspaceUrl, type Settings } from \"@opengeni/config\";\nimport {\n assertGitCredentialRenewalTransportUnchanged,\n gitCredentialAuthorityForTurn,\n mintSandboxCodemodeToken,\n mintRunGitCredentials,\n mintRunGitCredentialBinding,\n sandboxEnvironmentForRun,\n type GitHubTokenMintAuthorization,\n type MintedRunGitCredentials,\n type loadWorkspaceEnvironmentForRunWithCredentials,\n} from \"../environment\";\nimport type { mergeResourceRefs } from \"../common\";\nimport { startGitCredentialRenewalLoop } from \"../git-credential-renewal\";\nimport {\n RUN_CREDENTIAL_EXPIRY_LEAD_MS,\n startRunCredentialRenewalLoop,\n} from \"../run-credential-renewal\";\nimport {\n CODEMODE_TOKEN_EXPIRY_LEAD_MS,\n startCodemodeTokenRenewalLoop,\n} from \"../codemode-token-renewal\";\nimport {\n bindRunCredentialResolver,\n runCredentialAuthNeededPayloads,\n runCredentialModelNote,\n} from \"../run-credentials\";\nimport type { TurnActivityServices as ActivityServices, RunAgentTurnInput } from \"../types\";\nimport { type ResumedTurnSandbox } from \"../../sandbox-resume\";\nimport { lazyProvisionEnabled } from \"../../sandbox-routing\";\nimport { recordTurnSandboxEstablishPolicy } from \"../../observability-metrics\";\nimport { sandboxRunAs } from \"@opengeni/runtime\";\n\nimport {\n assertGitHubResourcesRemainAuthorized,\n assertFileResourcesRemainAuthorized,\n assertGitHubTokenMintSelectionAuthorized,\n requiresSignedFileResourceDownloads,\n} from \"./file-resources\";\nimport { throwIfTurnOperationCancelled, waitForTurnOperation } from \"./sandbox-provision\";\nimport {\n sandboxEstablishPolicyDecision,\n ensureTurnModalRegistryImage,\n sandboxArtifactRuntimeAdmission,\n sandboxSettingsForRoute,\n} from \"./sandbox-route\";\nimport type { ClaimTurnOk } from \"./claim\";\nimport type { GovernanceModelOk } from \"./governance-model\";\nimport type { SandboxTurnRuntime } from \"./sandbox-runtime\";\nimport type {\n AttemptIdentityState,\n EventingState,\n RenewalState,\n SandboxRuntimeState,\n} from \"./turn-context\";\n\nexport type PrepareRunCredentialsDeps = {\n input: RunAgentTurnInput;\n settings: Settings;\n db: ActivityServices[\"db\"];\n observability: ActivityServices[\"observability\"];\n cancellationSignal: AbortSignal | undefined;\n connectionCredentials: ActivityServices[\"connectionCredentials\"];\n personalGitHubCredentials: ActivityServices[\"personalGitHubCredentials\"];\n eventing: EventingState;\n attempt: AttemptIdentityState;\n renewals: RenewalState;\n sandboxState: SandboxRuntimeState;\n sandboxRuntime: SandboxTurnRuntime;\n turn: ClaimTurnOk[\"turn\"];\n session: ClaimTurnOk[\"session\"];\n fileAuthoritySubjectId: ClaimTurnOk[\"fileAuthoritySubjectId\"];\n runSettings: GovernanceModelOk[\"runSettings\"];\n workspaceVariableSet: Awaited<ReturnType<typeof loadWorkspaceEnvironmentForRunWithCredentials>>;\n turnResources: ReturnType<typeof mergeResourceRefs>;\n requiredGeneratedVideoFiles: Array<{\n operationId: string;\n artifactId: string;\n fileId: string;\n objectKey: string;\n sizeBytes: number;\n sha256: string;\n filename: string;\n }>;\n machinePrimary: boolean;\n activeSandboxBackend: Settings[\"sandboxBackend\"] | undefined;\n groupBoxBackend: Settings[\"sandboxBackend\"];\n sandboxCreationBackend: Settings[\"sandboxBackend\"];\n effectiveRunCredentialBackend: Settings[\"sandboxBackend\"];\n sandboxWorkspaceEnvironmentValues: Record<string, string>;\n connectionScope: { accountId: string; workspaceId: string };\n runWorkspaceMutationForSandbox: SandboxTurnRuntime[\"runWorkspaceMutationForSandbox\"];\n};\n\nexport async function prepareRunCredentials(deps: PrepareRunCredentialsDeps) {\n const {\n input,\n settings,\n db,\n observability,\n cancellationSignal,\n connectionCredentials,\n personalGitHubCredentials,\n eventing,\n attempt,\n renewals,\n sandboxState,\n turn,\n session,\n fileAuthoritySubjectId,\n runSettings,\n workspaceVariableSet,\n turnResources,\n requiredGeneratedVideoFiles,\n machinePrimary,\n activeSandboxBackend,\n groupBoxBackend,\n sandboxCreationBackend,\n effectiveRunCredentialBackend,\n sandboxWorkspaceEnvironmentValues,\n connectionScope,\n runWorkspaceMutationForSandbox,\n } = deps;\n // A machine-home row carries selfhosted path defaults, but clearing its\n // pointer explicitly selects the deployment-managed group. Build the stable\n // manifest environment with that effective provider just as Channel-A and\n // viewer readiness do; otherwise the verified managed box and the agent can\n // disagree on backend-aware HOME/token-file paths.\n const sandboxEnvironmentSettings = sandboxSettingsForRoute({\n runSettings,\n machinePrimary,\n groupBoxBackend,\n });\n\n const runCredentialResolver =\n effectiveRunCredentialBackend === \"none\"\n ? null\n : await waitForTurnOperation(\n bindRunCredentialResolver({\n db,\n connectionCredentials: connectionCredentials ?? null,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n session,\n turn,\n attemptId: input.attemptId,\n effectiveSandboxBackend: effectiveRunCredentialBackend,\n variableSet: workspaceVariableSet\n ? {\n id: workspaceVariableSet.id,\n name: workspaceVariableSet.name,\n }\n : null,\n }),\n cancellationSignal,\n undefined,\n );\n const establishDecision = sandboxEstablishPolicyDecision({\n lazyEnabled: lazyProvisionEnabled(settings),\n machinePrimary,\n sandboxBackend: runSettings.sandboxBackend,\n hasRunCredentialResolver: runCredentialResolver !== null,\n generatedVideoFileCount: requiredGeneratedVideoFiles.length,\n hasSignedFileResources:\n requiresSignedFileResourceDownloads(runSettings, activeSandboxBackend ?? groupBoxBackend) &&\n turn.resources.some((resource) => resource.kind === \"file\"),\n });\n const establishPolicy = establishDecision.policy;\n recordTurnSandboxEstablishPolicy(observability, {\n policy: establishDecision.policy,\n reason: establishDecision.reason,\n backend: machinePrimary ? \"selfhosted\" : groupBoxBackend,\n });\n // Resolve once before model preparation so partial/auth-needed host state\n // is available as bounded model context and reconnect UI even when an\n // on-demand turn never provisions a box. Resolution alone performs no\n // sandbox write or renewal; both paths reuse this exact material and the\n // lazy path materializes it only inside its first-operation single-flight.\n const initialRunCredentialMaterial = runCredentialResolver\n ? await waitForTurnOperation(\n runCredentialResolver.resolve({\n purpose: \"provision\",\n forceRefresh: false,\n }),\n cancellationSignal,\n undefined,\n )\n : null;\n if (initialRunCredentialMaterial) {\n for (const payload of runCredentialAuthNeededPayloads(initialRunCredentialMaterial)) {\n renewals.publishedRunCredentialNotices.add(JSON.stringify(payload));\n await eventing.publish!([{ type: \"credential.auth_needed\", payload }], true);\n }\n }\n const runCredentialsNote = initialRunCredentialMaterial\n ? runCredentialModelNote(initialRunCredentialMaterial)\n : undefined;\n throwIfTurnOperationCancelled(cancellationSignal);\n const authorizeGitHubTokenMint: GitHubTokenMintAuthorization = async (selection) => {\n const registrationId = prReviewRegistrationIdFromCredentialBinding(\n selection.credentialBindingId,\n );\n if (registrationId) {\n await resolvePrReviewGitCredential(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n registrationId,\n provider: \"github\",\n sessionId: input.sessionId,\n rootSessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: turn.executionGeneration,\n repositoryRefs: selection.repositoryRefs.map((reference) => ({\n uri: reference.uri,\n ...(reference.expectedCommitSha !== undefined\n ? { expectedCommitSha: reference.expectedCommitSha }\n : {}),\n ...(reference.repositoryId !== undefined ? { repositoryId: reference.repositoryId } : {}),\n ...(reference.installationId !== undefined\n ? { installationId: reference.installationId }\n : {}),\n ...(reference.projectId !== undefined ? { projectId: reference.projectId } : {}),\n })),\n });\n return;\n }\n await assertGitHubTokenMintSelectionAuthorized(\n db,\n input.workspaceId,\n selection.installationId,\n selection.repositoryIds,\n );\n };\n await Promise.all([\n waitForTurnOperation(\n ensureTurnModalRegistryImage(runSettings, sandboxCreationBackend),\n cancellationSignal,\n undefined,\n ),\n activeSandboxBackend !== \"selfhosted\"\n ? assertGitHubResourcesRemainAuthorized(\n db,\n input.workspaceId,\n turnResources,\n authorizeGitHubTokenMint,\n )\n : Promise.resolve(),\n assertFileResourcesRemainAuthorized(\n db,\n input.accountId,\n input.workspaceId,\n fileAuthoritySubjectId,\n turn.resources,\n ),\n ]);\n // Computed exactly ONCE per turn and reused for BOTH the box manifest\n // (resumeBoxForTurn -> establishSandboxSessionFromEnvelope, below) AND the\n // agent (runtime.buildAgent, below). sandboxEnvironmentForRun mints a FRESH\n // run-scoped git provider tokens on every call, so a second call would\n // yield DIFFERENT token values and re-introduce the manifest-env delta the\n // SDK's provided-session guard throws on — the box and the agent MUST share\n // this same object. A machine-primary turn skips the (inert) token mint entirely\n // (the machine uses its own git creds); the SAME base env still feeds the box +\n // the agent, so env-parity holds.\n // TOKEN-BROKER (B1): sandboxEnvironmentForRun now returns the STABLE manifest\n // env (no rotating GH_TOKEN/GITHUB_TOKEN/GIT_CONFIG_* extraheader) PLUS the\n // run-scoped git tokens minted ONCE per turn as provider seeds, with `gitToken`\n // retained as the GitHub alias. The env feeds BOTH the box manifest AND the\n // agent (env-parity, as before); tokens are threaded OFF-MANIFEST as\n // clone-seeds to buildAgent (below) so the box never carries rotating values\n // on its manifest. When a platform token IS minted, the host `gitCredentials`\n // provider may supply it; unset still self-mints GitHub from settings.\n // gitToken/gitTokens are undefined on the selfhosted skip path (the machine\n // uses its own git creds).\n // Git and MCP credentials share one lineage snapshot for this turn. A\n // host that supplies both ports must never see two independently resolved\n // roots for the same execution merely because the call sites are far apart.\n const needsHostCredentialRoot = Boolean(\n connectionCredentials?.gitCredentials ||\n personalGitHubCredentials ||\n connectionCredentials?.mcpCredentials,\n );\n const hostCredentialRootSessionId = needsHostCredentialRoot\n ? await getSessionRootId(db, input.workspaceId, input.sessionId)\n : null;\n if (needsHostCredentialRoot && !hostCredentialRootSessionId) {\n throw new Error(`cannot resolve host credentials for missing session ${input.sessionId}`);\n }\n const gitCredentialAuthority =\n (connectionCredentials?.gitCredentials || personalGitHubCredentials) &&\n hostCredentialRootSessionId\n ? gitCredentialAuthorityForTurn({\n sessionId: input.sessionId,\n rootSessionId: hostCredentialRootSessionId,\n attemptId: input.attemptId,\n turn,\n })\n : undefined;\n const codemodeAuthority = {\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: turn.executionGeneration,\n };\n const sandboxArtifactRuntime = sandboxArtifactRuntimeAdmission(\n settings,\n runSettings,\n activeSandboxBackend ?? groupBoxBackend,\n );\n const {\n environment: baseSandboxEnvironment,\n gitToken: sandboxGitToken,\n gitTokens: sandboxGitTokens,\n gitTokenExpiresAt: sandboxGitTokenExpiresAt,\n gitCredentialBindings: sandboxGitCredentialBindings,\n codemodeToken: sandboxCodemodeToken,\n codemodeTokenExpiresAt: sandboxCodemodeTokenExpiresAt,\n } = await waitForTurnOperation(\n sandboxEnvironmentForRun(\n sandboxEnvironmentSettings,\n turnResources,\n // Rig default sets merged BELOW the session set (session wins); rig-less\n // turns pass exactly workspaceVariableSet?.values (byte-for-byte today).\n sandboxWorkspaceEnvironmentValues,\n {\n skipGitHubToken: activeSandboxBackend === \"selfhosted\",\n codemodeDelivery: activeSandboxBackend === \"selfhosted\" ? \"transient_exec\" : \"managed_file\",\n deferGitHubToken: activeSandboxBackend !== \"selfhosted\" && establishPolicy === \"on-demand\",\n scope: connectionScope,\n ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),\n gitCredentials: connectionCredentials?.gitCredentials,\n personalGitHubCredentials: personalGitHubCredentials ?? undefined,\n authorizeGitHubTokenMint,\n codemodeAuthority,\n },\n ),\n cancellationSignal,\n undefined,\n );\n // Reserved, image-owned paths win over workspace/session variables. The\n // exact same merged object feeds both box manifest and agent declaration,\n // preserving the no-environment-delta invariant.\n const sandboxEnvironment = sandboxArtifactRuntime.available\n ? { ...baseSandboxEnvironment, ...sandboxArtifactRuntime.environment }\n : baseSandboxEnvironment;\n\n // One mutable in-memory bearer cell serves every Connected Machine route\n // in this attempt. SelfhostedSession snapshots it into each exact exec\n // request; it never enters the manifest, argv, filesystem, RunState, or\n // serialized session state. Managed renewal updates the same cell so a\n // later mid-turn swap sees the fresh bearer too.\n const codemodeTokenState = sandboxCodemodeToken ? { token: sandboxCodemodeToken } : undefined;\n const transientCodemodeEnvironment = codemodeTokenState\n ? (): Readonly<Record<string, string>> => ({\n OPENGENI_CODEMODE_URL: codemodeWorkspaceUrl(runSettings, input.workspaceId),\n OPENGENI_CODEMODE_TOKEN: codemodeTokenState.token,\n ...(runSettings.ogtoolPackageSpec\n ? { OPENGENI_OGTOOL_PACKAGE_SPEC: runSettings.ogtoolPackageSpec }\n : {}),\n })\n : undefined;\n\n const sandboxCodemodeTokenFile = sandboxCodemodeToken\n ? codemodeTokenFileFromEnvironment(sandboxEnvironment, input.sessionId)\n : undefined;\n\n const initialGitCredentials: MintedRunGitCredentials | undefined = sandboxGitCredentialBindings\n ? {\n bindings: sandboxGitCredentialBindings,\n gitTokens: sandboxGitTokens ?? {},\n expiresAt: sandboxGitTokenExpiresAt ?? {},\n }\n : undefined;\n // Lazy cloud provision mints the run-scoped git token while Modal create\n // runs. Chat-only turns never call get(), so this stays unstarted there.\n let runGitCredentialsMint: Promise<MintedRunGitCredentials | undefined> | undefined;\n const startRunGitCredentialsMint = (): Promise<MintedRunGitCredentials | undefined> => {\n if (activeSandboxBackend === \"selfhosted\") {\n return Promise.resolve(undefined);\n }\n runGitCredentialsMint ??= waitForTurnOperation(\n mintRunGitCredentials(runSettings, turnResources, {\n scope: connectionScope,\n ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),\n gitCredentials: connectionCredentials?.gitCredentials,\n personalGitHubCredentials: personalGitHubCredentials ?? undefined,\n authorizeGitHubTokenMint,\n }),\n cancellationSignal,\n undefined,\n );\n return runGitCredentialsMint;\n };\n const attachGitCredentialRenewal = async (\n tokenSession: GitCredentialTokenWriterSession,\n initial: MintedRunGitCredentials | undefined,\n initialSandbox?: ResumedTurnSandbox,\n ): Promise<void> => {\n if (!initial || initial.bindings.length === 0) return;\n const previous = renewals.gitCredentialRenewals;\n renewals.gitCredentialRenewals = [];\n await Promise.all(previous.map(async (controller) => await controller.stop()));\n if (renewals.gitCredentialRenewalClosed) return;\n\n const controllers = initial.bindings.map((initialBinding) => {\n let pendingBinding: typeof initialBinding | undefined;\n return startGitCredentialRenewalLoop({\n expectedProviders: [initialBinding.provider],\n ...(initialBinding.transport?.kind === \"http_broker\" ? { expiryLeadMs: 60_000 } : {}),\n initialExpiresAt: initialBinding.expiresAt\n ? { [initialBinding.provider]: initialBinding.expiresAt }\n : {},\n mint: async () => {\n const binding = await mintRunGitCredentialBinding(\n runSettings,\n turnResources,\n initialBinding.provider,\n initialBinding.credentialBindingId,\n {\n scope: connectionScope,\n ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),\n gitCredentials: connectionCredentials?.gitCredentials,\n personalGitHubCredentials: personalGitHubCredentials ?? undefined,\n authorizeGitHubTokenMint,\n },\n );\n if (binding) {\n assertGitCredentialRenewalTransportUnchanged(initialBinding, binding);\n }\n pendingBinding = binding;\n return binding\n ? {\n bindings: [binding],\n gitTokens: { [binding.provider]: binding.token },\n expiresAt: binding.expiresAt ? { [binding.provider]: binding.expiresAt } : {},\n }\n : undefined;\n },\n write: async () => {\n if (!pendingBinding) {\n throw new Error(\"credential renewal produced no binding token\");\n }\n const runAs = sandboxRunAs(runSettings);\n const targetSandbox = sandboxState.resolvedSandbox ?? initialSandbox;\n if (!targetSandbox) {\n throw new Error(\"Git credential renewal has no exact sandbox lease target\");\n }\n await runWorkspaceMutationForSandbox(\n targetSandbox,\n \"gitCredentialRenewal\",\n async () =>\n await refreshGitCredentialBindingTokenFiles(tokenSession, [pendingBinding!], {\n ...(runAs ? { runAs } : {}),\n ...(eventing.toolCancellationFenceRef.current\n ? {\n commandRunner:\n eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(\n eventing.toolCancellationFenceRef.current,\n ),\n }\n : {}),\n }),\n );\n },\n onSuccess: ({ providers: renewedProviders }) => {\n for (const provider of renewedProviders) {\n observability.incrementCounter({\n name: \"opengeni_git_credential_renewals_total\",\n help: \"Host-managed Git credential renewal attempts by provider and outcome.\",\n labels: { provider, outcome: \"completed\" },\n });\n }\n },\n onFailure: ({ providers: failedProviders, retryDelayMs, errorClass }) => {\n for (const provider of failedProviders) {\n observability.incrementCounter({\n name: \"opengeni_git_credential_renewals_total\",\n help: \"Host-managed Git credential renewal attempts by provider and outcome.\",\n labels: { provider, outcome: \"error\" },\n });\n }\n observability.warn(\"Sandbox Git credential renewal failed; retry scheduled\", {\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n providers: failedProviders.join(\",\"),\n errorClass,\n retryDelayMs,\n });\n },\n });\n });\n if (renewals.gitCredentialRenewalClosed) {\n await Promise.all(controllers.map(async (controller) => await controller.stop()));\n return;\n }\n renewals.gitCredentialRenewals = controllers;\n };\n\n const attachCodemodeTokenRenewal = async (\n tokenSession?: CodemodeTokenWriterSession,\n initialExpiresAt = sandboxCodemodeTokenExpiresAt,\n initialSandbox?: ResumedTurnSandbox,\n ): Promise<void> => {\n if (!codemodeTokenState || !initialExpiresAt) return;\n const previous = renewals.codemodeTokenRenewal;\n renewals.codemodeTokenRenewal = null;\n await previous?.stop();\n if (renewals.codemodeTokenRenewalClosed) return;\n\n const mint = async () => {\n const material = await mintSandboxCodemodeToken(\n runSettings,\n connectionScope,\n codemodeAuthority,\n );\n return material;\n };\n const write = async (material: NonNullable<Awaited<ReturnType<typeof mint>>>) => {\n if (tokenSession) {\n const runAs = sandboxRunAs(runSettings);\n const targetSandbox = sandboxState.resolvedSandbox ?? initialSandbox;\n if (!targetSandbox) {\n throw new Error(\"Codemode token renewal has no exact sandbox lease target\");\n }\n await runWorkspaceMutationForSandbox(\n targetSandbox,\n \"codemodeTokenRenewal\",\n async () =>\n await refreshCodemodeTokenFile(tokenSession, material.token, {\n ...(runAs ? { runAs } : {}),\n ...(sandboxCodemodeTokenFile\n ? {\n tokenFile: sandboxCodemodeTokenFile,\n legacyTokenFile: sandboxEnvironment.OPENGENI_CODEMODE_TOKEN_FILE!,\n }\n : {}),\n ...(eventing.toolCancellationFenceRef.current\n ? {\n commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(\n eventing.toolCancellationFenceRef.current,\n ),\n }\n : {}),\n }),\n );\n }\n codemodeTokenState.token = material.token;\n };\n let renewalExpiresAt = initialExpiresAt;\n if (renewalExpiresAt.getTime() <= Date.now() + CODEMODE_TOKEN_EXPIRY_LEAD_MS) {\n const fresh = await mint();\n if (!fresh) {\n throw new Error(\"Codemode token mint became unavailable during sandbox setup\");\n }\n await write(fresh);\n renewalExpiresAt = fresh.expiresAt;\n }\n const controller = startCodemodeTokenRenewalLoop({\n initialExpiresAt: renewalExpiresAt,\n mint,\n write,\n onSuccess: () => {\n observability.incrementCounter({\n name: \"opengeni_codemode_token_renewals_total\",\n help: \"Sandbox Codemode token renewal attempts by outcome.\",\n labels: { outcome: \"completed\" },\n });\n },\n onFailure: ({ retryDelayMs, errorClass }) => {\n observability.incrementCounter({\n name: \"opengeni_codemode_token_renewals_total\",\n help: \"Sandbox Codemode token renewal attempts by outcome.\",\n labels: { outcome: \"error\" },\n });\n observability.warn(\"Sandbox Codemode token renewal failed; retry scheduled\", {\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n errorClass,\n retryDelayMs,\n });\n },\n });\n if (renewals.codemodeTokenRenewalClosed) {\n await controller.stop();\n return;\n }\n renewals.codemodeTokenRenewal = controller;\n };\n\n // A Connected Machine needs renewal, but renewal is purely worker-local:\n // starting this loop performs no control-plane or machine operation.\n if (activeSandboxBackend === \"selfhosted\") {\n await attachCodemodeTokenRenewal();\n }\n\n const attachRunCredentialRenewal = async (\n credentialSession: RunCredentialCommandSession,\n initialMaterial: NormalizedRunCredentialMaterial | null,\n initialSandbox?: ResumedTurnSandbox,\n ): Promise<void> => {\n if (!runCredentialResolver) return;\n const previous = renewals.runCredentialRenewal;\n renewals.runCredentialRenewal = null;\n await previous?.stop();\n if (renewals.runCredentialRenewalClosed) return;\n renewals.runCredentialSession = credentialSession;\n\n const requireTargetSandbox = (): ResumedTurnSandbox => {\n const targetSandbox = sandboxState.resolvedSandbox ?? initialSandbox;\n if (!targetSandbox) {\n throw new Error(\"Run credential mutation has no exact sandbox lease target\");\n }\n return targetSandbox;\n };\n\n if (!initialMaterial) {\n await runWorkspaceMutationForSandbox(\n requireTargetSandbox(),\n \"runCredentialClear\",\n async () =>\n await clearRunCredentials(\n credentialSession,\n input.sessionId,\n eventing.toolCancellationFenceRef.current\n ? eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(\n eventing.toolCancellationFenceRef.current,\n )\n : undefined,\n ),\n );\n return;\n }\n\n const write = async (\n material: NormalizedRunCredentialMaterial | null,\n pruneOtherAttempts = false,\n ): Promise<void> => {\n if (!material) {\n await runWorkspaceMutationForSandbox(\n requireTargetSandbox(),\n \"runCredentialAttemptClear\",\n async () =>\n await clearRunCredentialsForAttempt(credentialSession, {\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n }),\n );\n return;\n }\n\n await runWorkspaceMutationForSandbox(\n requireTargetSandbox(),\n \"runCredentialMaterialization\",\n async () =>\n await materializeRunCredentials(credentialSession, material, {\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n ...(pruneOtherAttempts ? { pruneOtherAttempts: true } : {}),\n ...(!pruneOtherAttempts ? { pruneSupersededGenerations: true } : {}),\n ...(material.authNeeded.length > 0 &&\n Object.keys(material.environment).length === 0 &&\n material.files.length === 0\n ? { prunePreviousGenerations: true }\n : {}),\n ...(eventing.toolCancellationFenceRef.current\n ? {\n commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(\n eventing.toolCancellationFenceRef.current,\n ),\n }\n : {}),\n }),\n );\n for (const payload of runCredentialAuthNeededPayloads(material)) {\n const key = JSON.stringify(payload);\n if (renewals.publishedRunCredentialNotices.has(key)) continue;\n renewals.publishedRunCredentialNotices.add(key);\n await eventing.publish!([{ type: \"credential.auth_needed\", payload }], true);\n }\n };\n\n const initialExpiryMs = initialMaterial.expiresAt?.getTime() ?? null;\n const seed =\n initialExpiryMs !== null && initialExpiryMs <= Date.now() + RUN_CREDENTIAL_EXPIRY_LEAD_MS\n ? await runCredentialResolver.resolve({\n purpose: \"provision\",\n forceRefresh: true,\n })\n : initialMaterial;\n await write(seed, true);\n if (renewals.runCredentialRenewalClosed) return;\n const controller = startRunCredentialRenewalLoop({\n initialExpiresAt: seed?.expiresAt ?? null,\n resolve: async () =>\n await runCredentialResolver.resolve({\n purpose: \"renewal\",\n forceRefresh: true,\n }),\n write: async (material) => await write(material),\n onSuccess: ({ authNeeded }) => {\n observability.incrementCounter({\n name: \"opengeni_run_credential_renewals_total\",\n help: \"Host-managed run credential renewal attempts by outcome.\",\n labels: { outcome: authNeeded ? \"auth_needed\" : \"completed\" },\n });\n },\n onFailure: ({ retryDelayMs, errorClass }) => {\n observability.incrementCounter({\n name: \"opengeni_run_credential_renewals_total\",\n help: \"Host-managed run credential renewal attempts by outcome.\",\n labels: { outcome: \"error\" },\n });\n observability.warn(\"Host run credential renewal failed; retry scheduled\", {\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n errorClass,\n retryDelayMs,\n });\n },\n });\n if (renewals.runCredentialRenewalClosed) {\n await controller.stop();\n return;\n }\n renewals.runCredentialRenewal = controller;\n };\n\n return {\n runCredentialResolver,\n establishPolicy,\n initialRunCredentialMaterial,\n runCredentialsNote,\n authorizeGitHubTokenMint,\n hostCredentialRootSessionId,\n gitCredentialAuthority,\n codemodeAuthority,\n sandboxArtifactRuntime,\n sandboxEnvironment,\n sandboxGitToken,\n sandboxGitTokens,\n sandboxGitTokenExpiresAt,\n sandboxGitCredentialBindings,\n sandboxCodemodeToken,\n sandboxCodemodeTokenExpiresAt,\n sandboxCodemodeTokenFile,\n transientCodemodeEnvironment,\n initialGitCredentials,\n startRunGitCredentialsMint,\n attachGitCredentialRenewal,\n attachCodemodeTokenRenewal,\n attachRunCredentialRenewal,\n };\n}\n\nexport type PrepareRunCredentialsOk = Awaited<ReturnType<typeof prepareRunCredentials>>;\n","import type { GitCredentialProvider } from \"@opengeni/contracts\";\nimport type { GitTokenExpiries, GitTokenSeeds, MintedRunGitCredentials } from \"./environment\";\n\nexport const GIT_CREDENTIAL_DEFAULT_REFRESH_MS = 30 * 60_000;\nexport const GIT_CREDENTIAL_EXPIRY_LEAD_MS = 5 * 60_000;\nexport const GIT_CREDENTIAL_MIN_REFRESH_MS = 5_000;\nexport const GIT_CREDENTIAL_MAX_RETRY_MS = 5 * 60_000;\n\ntype RenewalTimer = unknown;\n\nexport type GitCredentialRenewalResult = {\n providers: readonly GitCredentialProvider[];\n nextDelayMs: number;\n};\n\nexport type GitCredentialRenewalFailure = {\n providers: readonly GitCredentialProvider[];\n retryDelayMs: number;\n errorClass: \"GitCredentialRenewalOperationError\";\n};\n\nexport type GitCredentialRenewalController = {\n refreshNow(): Promise<void>;\n stop(): Promise<void>;\n};\n\nexport type GitCredentialRenewalOptions = {\n expectedProviders: readonly GitCredentialProvider[];\n initialExpiresAt?: GitTokenExpiries;\n /** Override the default five-minute provider-token lead for shorter broker bearers. */\n expiryLeadMs?: number;\n mint: () => Promise<MintedRunGitCredentials | undefined>;\n write: (tokens: GitTokenSeeds) => Promise<void>;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => RenewalTimer;\n clearSchedule?: (timer: RenewalTimer) => void;\n onSuccess?: (result: GitCredentialRenewalResult) => void;\n onFailure?: (failure: GitCredentialRenewalFailure) => void;\n};\n\n/**\n * Return a conservative refresh delay for a provider set.\n *\n * The fixed cadence caps long/unknown provider TTLs; a known earlier expiry\n * pulls renewal forward. Invalid metadata is treated as unknown rather than\n * allowing a token to live indefinitely.\n */\nexport function nextGitCredentialRenewalDelay(\n expiresAt: GitTokenExpiries | undefined,\n providers: readonly GitCredentialProvider[],\n nowMs = Date.now(),\n expiryLeadMs = GIT_CREDENTIAL_EXPIRY_LEAD_MS,\n): number {\n let delay = GIT_CREDENTIAL_DEFAULT_REFRESH_MS;\n for (const provider of providers) {\n const rawExpiry = expiresAt?.[provider];\n if (!rawExpiry) continue;\n const expiryMs = Date.parse(rawExpiry);\n if (!Number.isFinite(expiryMs)) continue;\n delay = Math.min(\n delay,\n Math.max(GIT_CREDENTIAL_MIN_REFRESH_MS, expiryMs - nowMs - expiryLeadMs),\n );\n }\n return delay;\n}\n\nexport function startGitCredentialRenewalLoop(\n options: GitCredentialRenewalOptions,\n): GitCredentialRenewalController {\n const providers = [...new Set(options.expectedProviders)];\n const now = options.now ?? Date.now;\n const schedule =\n options.schedule ??\n ((callback: () => void, delayMs: number): ReturnType<typeof setTimeout> => {\n const timer = setTimeout(callback, delayMs);\n timer.unref?.();\n return timer;\n });\n const clearSchedule =\n options.clearSchedule ??\n ((timer: RenewalTimer): void => clearTimeout(timer as ReturnType<typeof setTimeout>));\n\n let stopped = false;\n let timer: RenewalTimer | null = null;\n let inFlight: Promise<void> | null = null;\n let writeInFlight: Promise<void> | null = null;\n let retryDelayMs = GIT_CREDENTIAL_MIN_REFRESH_MS;\n\n const clearTimer = (): void => {\n if (timer === null) return;\n clearSchedule(timer);\n timer = null;\n };\n\n const scheduleRefresh = (delayMs: number): void => {\n if (stopped || providers.length === 0) return;\n clearTimer();\n timer = schedule(() => {\n timer = null;\n void refreshNow();\n }, delayMs);\n };\n\n const validateMintedTokens = (\n minted: MintedRunGitCredentials | undefined,\n ): MintedRunGitCredentials => {\n if (!minted) {\n throw new GitCredentialRenewalError(\"credential provider returned no token bundle\");\n }\n for (const provider of providers) {\n if (!minted.gitTokens[provider]) {\n throw new GitCredentialRenewalError(`credential provider omitted ${provider}`);\n }\n }\n return minted;\n };\n\n const performRefresh = async (): Promise<void> => {\n try {\n const minted = validateMintedTokens(await options.mint());\n if (stopped) return;\n const write = options.write(minted.gitTokens);\n writeInFlight = write;\n try {\n await write;\n } finally {\n if (writeInFlight === write) writeInFlight = null;\n }\n if (stopped) return;\n retryDelayMs = GIT_CREDENTIAL_MIN_REFRESH_MS;\n const nextDelayMs = nextGitCredentialRenewalDelay(\n minted.expiresAt,\n providers,\n now(),\n options.expiryLeadMs,\n );\n try {\n options.onSuccess?.({ providers, nextDelayMs });\n } catch {\n // Observability callbacks never own credential liveness.\n }\n scheduleRefresh(nextDelayMs);\n } catch {\n if (stopped) return;\n const scheduledRetryMs = retryDelayMs;\n retryDelayMs = Math.min(retryDelayMs * 2, GIT_CREDENTIAL_MAX_RETRY_MS);\n try {\n options.onFailure?.({\n providers,\n retryDelayMs: scheduledRetryMs,\n errorClass: \"GitCredentialRenewalOperationError\",\n });\n } catch {\n // Observability callbacks never own credential liveness.\n }\n scheduleRefresh(scheduledRetryMs);\n }\n };\n\n const refreshNow = (): Promise<void> => {\n if (stopped || providers.length === 0) return Promise.resolve();\n if (inFlight) return inFlight;\n clearTimer();\n const operation = performRefresh();\n inFlight = operation;\n void operation.finally(() => {\n if (inFlight === operation) inFlight = null;\n });\n return operation;\n };\n\n scheduleRefresh(\n nextGitCredentialRenewalDelay(options.initialExpiresAt, providers, now(), options.expiryLeadMs),\n );\n\n return {\n refreshNow,\n stop: async () => {\n stopped = true;\n clearTimer();\n // A broker mint can be a remote host call with no cancellation seam. It\n // cannot mutate the sandbox, and the stopped check above rejects its late\n // result, so never hold turn settlement hostage to a hung mint. A write\n // does mutate the box and must drain before capture/teardown.\n await writeInFlight?.catch(() => undefined);\n },\n };\n}\n\nclass GitCredentialRenewalError extends Error {\n override readonly name = \"GitCredentialRenewalError\";\n}\n","export type ExpiringMaterialRenewalPolicy = {\n defaultRefreshMs: number;\n expiryLeadMs: number;\n minRefreshMs: number;\n maxRetryMs: number;\n};\n\ntype RenewalTimer = unknown;\n\nexport type ExpiringMaterialRenewalController = {\n refreshNow(): Promise<void>;\n stop(): Promise<void>;\n};\n\nexport type ExpiringMaterialRenewalPublicErrorClass =\n | \"RunCredentialRenewalOperationError\"\n | \"CodemodeTokenRenewalOperationError\";\n\nexport type ExpiringMaterialRenewalOptions<\n T,\n ErrorClass extends ExpiringMaterialRenewalPublicErrorClass,\n> = {\n initialExpiresAt: Date | null;\n resolve: () => Promise<T>;\n write: (material: T) => Promise<void>;\n expiresAt: (material: T) => Date | null;\n publicErrorClass: ErrorClass;\n policy: ExpiringMaterialRenewalPolicy;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => RenewalTimer;\n clearSchedule?: (timer: RenewalTimer) => void;\n onSuccess?: (result: { material: T; nextDelayMs: number }) => void;\n onFailure?: (failure: { retryDelayMs: number; errorClass: ErrorClass }) => void;\n};\n\nexport function nextExpiringMaterialRenewalDelay(\n expiresAt: Date | null,\n policy: ExpiringMaterialRenewalPolicy,\n nowMs = Date.now(),\n): number {\n if (!expiresAt || !Number.isFinite(expiresAt.getTime())) {\n return policy.defaultRefreshMs;\n }\n return Math.min(\n policy.defaultRefreshMs,\n Math.max(policy.minRefreshMs, expiresAt.getTime() - nowMs - policy.expiryLeadMs),\n );\n}\n\n/**\n * Attempt-owned single-flight renewal for expiring sandbox material.\n *\n * A late resolver cannot write after stop. A physical sandbox write that already\n * started is drained so turn settlement cannot race a stale mutation.\n */\nexport function startExpiringMaterialRenewalLoop<\n T,\n ErrorClass extends ExpiringMaterialRenewalPublicErrorClass,\n>(options: ExpiringMaterialRenewalOptions<T, ErrorClass>): ExpiringMaterialRenewalController {\n const now = options.now ?? Date.now;\n const schedule =\n options.schedule ??\n ((callback: () => void, delayMs: number): ReturnType<typeof setTimeout> => {\n const timer = setTimeout(callback, delayMs);\n timer.unref?.();\n return timer;\n });\n const clearSchedule =\n options.clearSchedule ??\n ((timer: RenewalTimer): void => clearTimeout(timer as ReturnType<typeof setTimeout>));\n let stopped = false;\n let timer: RenewalTimer | null = null;\n let inFlight: Promise<void> | null = null;\n let writeInFlight: Promise<void> | null = null;\n let retryDelayMs = options.policy.minRefreshMs;\n\n const clearTimer = (): void => {\n if (timer === null) return;\n clearSchedule(timer);\n timer = null;\n };\n const scheduleRefresh = (delayMs: number): void => {\n if (stopped) return;\n clearTimer();\n timer = schedule(() => {\n timer = null;\n void refreshNow();\n }, delayMs);\n };\n const performRefresh = async (): Promise<void> => {\n try {\n const material = await options.resolve();\n if (stopped) return;\n const write = options.write(material);\n writeInFlight = write;\n try {\n await write;\n } finally {\n if (writeInFlight === write) writeInFlight = null;\n }\n if (stopped) return;\n retryDelayMs = options.policy.minRefreshMs;\n const nextDelayMs = nextExpiringMaterialRenewalDelay(\n options.expiresAt(material),\n options.policy,\n now(),\n );\n try {\n options.onSuccess?.({ material, nextDelayMs });\n } catch {\n // Observability never owns credential liveness.\n }\n scheduleRefresh(nextDelayMs);\n } catch {\n if (stopped) return;\n const scheduledRetryMs = retryDelayMs;\n retryDelayMs = Math.min(retryDelayMs * 2, options.policy.maxRetryMs);\n try {\n options.onFailure?.({\n retryDelayMs: scheduledRetryMs,\n errorClass: options.publicErrorClass,\n });\n } catch {\n // Observability never owns credential liveness.\n }\n scheduleRefresh(scheduledRetryMs);\n }\n };\n const refreshNow = (): Promise<void> => {\n if (stopped) return Promise.resolve();\n if (inFlight) return inFlight;\n clearTimer();\n const operation = performRefresh();\n inFlight = operation;\n void operation.finally(() => {\n if (inFlight === operation) inFlight = null;\n });\n return operation;\n };\n\n scheduleRefresh(\n nextExpiringMaterialRenewalDelay(options.initialExpiresAt, options.policy, now()),\n );\n return {\n refreshNow,\n stop: async () => {\n stopped = true;\n clearTimer();\n await writeInFlight?.catch(() => undefined);\n },\n };\n}\n","import type { NormalizedRunCredentialMaterial } from \"@opengeni/runtime\";\nimport {\n nextExpiringMaterialRenewalDelay,\n startExpiringMaterialRenewalLoop,\n type ExpiringMaterialRenewalController,\n} from \"./expiring-material-renewal\";\n\nexport const RUN_CREDENTIAL_DEFAULT_REFRESH_MS = 30 * 60_000;\nexport const RUN_CREDENTIAL_EXPIRY_LEAD_MS = 5 * 60_000;\nexport const RUN_CREDENTIAL_MIN_REFRESH_MS = 5_000;\nexport const RUN_CREDENTIAL_MAX_RETRY_MS = 5 * 60_000;\n\nexport type RunCredentialRenewalController = ExpiringMaterialRenewalController;\n\ntype RenewalTimer = unknown;\n\nexport type RunCredentialRenewalOptions = {\n initialExpiresAt: Date | null;\n resolve: () => Promise<NormalizedRunCredentialMaterial | null>;\n write: (material: NormalizedRunCredentialMaterial | null) => Promise<void>;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => RenewalTimer;\n clearSchedule?: (timer: RenewalTimer) => void;\n onSuccess?: (result: { nextDelayMs: number; authNeeded: boolean }) => void;\n onFailure?: (failure: {\n retryDelayMs: number;\n errorClass: \"RunCredentialRenewalOperationError\";\n }) => void;\n};\n\nexport function nextRunCredentialRenewalDelay(expiresAt: Date | null, nowMs = Date.now()): number {\n return nextExpiringMaterialRenewalDelay(\n expiresAt,\n {\n defaultRefreshMs: RUN_CREDENTIAL_DEFAULT_REFRESH_MS,\n expiryLeadMs: RUN_CREDENTIAL_EXPIRY_LEAD_MS,\n minRefreshMs: RUN_CREDENTIAL_MIN_REFRESH_MS,\n maxRetryMs: RUN_CREDENTIAL_MAX_RETRY_MS,\n },\n nowMs,\n );\n}\n\n/** Single-flight renewal; late resolves cannot mutate a stopped attempt. */\nexport function startRunCredentialRenewalLoop(\n options: RunCredentialRenewalOptions,\n): RunCredentialRenewalController {\n return startExpiringMaterialRenewalLoop<\n NormalizedRunCredentialMaterial | null,\n \"RunCredentialRenewalOperationError\"\n >({\n initialExpiresAt: options.initialExpiresAt,\n resolve: options.resolve,\n write: options.write,\n expiresAt: (material) => material?.expiresAt ?? null,\n publicErrorClass: \"RunCredentialRenewalOperationError\",\n policy: {\n defaultRefreshMs: RUN_CREDENTIAL_DEFAULT_REFRESH_MS,\n expiryLeadMs: RUN_CREDENTIAL_EXPIRY_LEAD_MS,\n minRefreshMs: RUN_CREDENTIAL_MIN_REFRESH_MS,\n maxRetryMs: RUN_CREDENTIAL_MAX_RETRY_MS,\n },\n ...(options.now ? { now: options.now } : {}),\n ...(options.schedule ? { schedule: options.schedule } : {}),\n ...(options.clearSchedule ? { clearSchedule: options.clearSchedule } : {}),\n ...(options.onSuccess\n ? {\n onSuccess: ({ material, nextDelayMs }) =>\n options.onSuccess?.({\n nextDelayMs,\n authNeeded: (material?.authNeeded.length ?? 0) > 0,\n }),\n }\n : {}),\n ...(options.onFailure ? { onFailure: options.onFailure } : {}),\n });\n}\n","import {\n startExpiringMaterialRenewalLoop,\n type ExpiringMaterialRenewalController,\n} from \"./expiring-material-renewal\";\nimport type { MintedSandboxCodemodeToken } from \"./environment\";\n\nexport const CODEMODE_TOKEN_DEFAULT_REFRESH_MS = 30 * 60_000;\nexport const CODEMODE_TOKEN_EXPIRY_LEAD_MS = 5 * 60_000;\nexport const CODEMODE_TOKEN_MIN_REFRESH_MS = 5_000;\nexport const CODEMODE_TOKEN_MAX_RETRY_MS = 5 * 60_000;\n\nexport type CodemodeTokenRenewalController = ExpiringMaterialRenewalController;\n\nexport type CodemodeTokenRenewalOptions = {\n initialExpiresAt: Date;\n mint: () => Promise<MintedSandboxCodemodeToken | undefined>;\n write: (material: MintedSandboxCodemodeToken) => Promise<void>;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => unknown;\n clearSchedule?: (timer: unknown) => void;\n onSuccess?: (result: { nextDelayMs: number }) => void;\n onFailure?: (failure: {\n retryDelayMs: number;\n errorClass: \"CodemodeTokenRenewalOperationError\";\n }) => void;\n};\n\nclass CodemodeTokenRenewalError extends Error {\n override readonly name = \"CodemodeTokenRenewalError\";\n}\n\nexport function startCodemodeTokenRenewalLoop(\n options: CodemodeTokenRenewalOptions,\n): CodemodeTokenRenewalController {\n return startExpiringMaterialRenewalLoop<\n MintedSandboxCodemodeToken,\n \"CodemodeTokenRenewalOperationError\"\n >({\n initialExpiresAt: options.initialExpiresAt,\n resolve: async () => {\n const minted = await options.mint();\n if (!minted) {\n throw new CodemodeTokenRenewalError(\"Codemode token mint is no longer available\");\n }\n return minted;\n },\n write: options.write,\n expiresAt: (material) => material.expiresAt,\n publicErrorClass: \"CodemodeTokenRenewalOperationError\",\n policy: {\n defaultRefreshMs: CODEMODE_TOKEN_DEFAULT_REFRESH_MS,\n expiryLeadMs: CODEMODE_TOKEN_EXPIRY_LEAD_MS,\n minRefreshMs: CODEMODE_TOKEN_MIN_REFRESH_MS,\n maxRetryMs: CODEMODE_TOKEN_MAX_RETRY_MS,\n },\n ...(options.now ? { now: options.now } : {}),\n ...(options.schedule ? { schedule: options.schedule } : {}),\n ...(options.clearSchedule ? { clearSchedule: options.clearSchedule } : {}),\n ...(options.onSuccess\n ? { onSuccess: ({ nextDelayMs }) => options.onSuccess?.({ nextDelayMs }) }\n : {}),\n ...(options.onFailure ? { onFailure: options.onFailure } : {}),\n });\n}\n","import type {\n ConnectionCredentialsPort,\n CredentialAuthNeededPayload,\n SandboxBackend,\n RunCredentialsRequest,\n Session,\n SessionTurn,\n} from \"@opengeni/contracts\";\nimport { getSessionRootId, type Database } from \"@opengeni/db\";\nimport {\n normalizeRunCredentialsResolution,\n type NormalizedRunCredentialMaterial,\n} from \"@opengeni/runtime\";\n\nexport type RunCredentialResolutionContext = {\n db: Database;\n connectionCredentials?: ConnectionCredentialsPort | null;\n accountId: string;\n workspaceId: string;\n session: Session;\n turn: SessionTurn;\n attemptId: string;\n effectiveSandboxBackend: SandboxBackend;\n variableSet: { id: string; name: string } | null;\n};\n\nexport type BoundRunCredentialResolver = {\n resolve(input: {\n purpose: \"provision\" | \"renewal\";\n forceRefresh: boolean;\n }): Promise<NormalizedRunCredentialMaterial | null>;\n};\n\nexport function buildRunCredentialsRequest(\n input: Omit<RunCredentialResolutionContext, \"db\" | \"connectionCredentials\"> & {\n rootSessionId: string;\n purpose: \"provision\" | \"renewal\";\n forceRefresh: boolean;\n },\n): RunCredentialsRequest {\n return {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.session.id,\n parentSessionId: input.session.parentSessionId,\n rootSessionId: input.rootSessionId,\n sandboxGroupId: input.session.sandboxGroupId,\n turnId: input.turn.id,\n attemptId: input.attemptId,\n executionGeneration: input.turn.executionGeneration,\n initiator: input.turn.initiator,\n initiatorContext: input.turn.initiatorContext,\n effectiveSandboxBackend: input.effectiveSandboxBackend,\n sandboxOs: input.turn.sandboxOs ?? input.session.sandboxOs,\n purpose: input.purpose,\n forceRefresh: input.forceRefresh,\n variableSet: input.variableSet,\n };\n}\n\nexport function runCredentialAuthNeededPayloads(\n material: NormalizedRunCredentialMaterial,\n): CredentialAuthNeededPayload[] {\n return material.authNeeded.map((notice) => ({\n credentialClass: \"run\",\n reason: notice.reason,\n ...(notice.providerDomain ? { providerDomain: notice.providerDomain } : {}),\n ...(notice.connectionId ? { connectionId: notice.connectionId } : {}),\n ...(notice.scopes?.length ? { scopes: notice.scopes } : {}),\n ...(notice.resource ? { resource: notice.resource } : {}),\n ...(notice.authorizationUrl ? { authorizationUrl: notice.authorizationUrl } : {}),\n ...(notice.message ? { message: notice.message } : {}),\n }));\n}\n\nexport function runCredentialModelNote(\n material: NormalizedRunCredentialMaterial,\n): string | undefined {\n if (material.authNeeded.length === 0) return undefined;\n return [\n \"[OpenGeni connected-service status]\",\n \"One or more host-managed credentials need user attention. Continue with available capabilities, but do not claim the affected service is usable until it is reconnected.\",\n JSON.stringify({\n credentials: material.authNeeded.map((notice) => ({\n reason: notice.reason,\n ...(notice.providerDomain ? { providerDomain: notice.providerDomain } : {}),\n ...(notice.resource ? { resource: notice.resource } : {}),\n ...(notice.message ? { message: notice.message } : {}),\n })),\n }),\n ].join(\"\\n\");\n}\n\n/**\n * Freeze the provider-neutral host credential request to this exact admitted\n * turn. The host selects connections and material; the worker never infers a\n * provider from repositories, environment names, or an OpenGeni variable set.\n */\nexport async function bindRunCredentialResolver(\n input: RunCredentialResolutionContext,\n): Promise<BoundRunCredentialResolver | null> {\n const resolver = input.connectionCredentials?.runCredentials;\n if (!resolver) return null;\n const rootSessionId = await getSessionRootId(input.db, input.workspaceId, input.session.id);\n if (!rootSessionId) {\n throw new Error(`cannot resolve run credentials for missing session ${input.session.id}`);\n }\n const scope = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.session.id,\n };\n return {\n resolve: async ({ purpose, forceRefresh }) => {\n const resolution = await resolver(\n buildRunCredentialsRequest({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n session: input.session,\n turn: input.turn,\n attemptId: input.attemptId,\n effectiveSandboxBackend: input.effectiveSandboxBackend,\n variableSet: input.variableSet,\n rootSessionId,\n purpose,\n forceRefresh,\n }),\n );\n return normalizeRunCredentialsResolution(resolution, scope);\n },\n };\n}\n","import { getWorkspaceConnectionModelRestrictions } from \"@opengeni/db\";\nimport {\n beginConnectorActionExecution,\n getExternalLinkTurnAuthorization,\n getSessionTurnForAttempt,\n getWorkspaceVideoGenerationPolicy,\n listSkillDescriptors,\n completeConnectorActionExecution,\n getScheduledVariableSetExpectedGenerationForAttempt,\n getWorkspaceModelPolicy,\n listWorkspaceGatewayCustomModels,\n listWorkspaceOpenRouterCustomModels,\n listOrganizationModelProviderCustomModelsForWorkspace,\n organizationModelProviderConnectionActiveForWorkspace,\n persistAttemptToolCatalog,\n prepareConnectorActionApproval,\n previewConnectorActionApproval,\n namedSubjectHasLiveWorkspaceAuthority,\n updateSessionTitleWithEvent,\n withCodexAppsRequestAuthorization,\n workspaceCodexSubscriptionActive,\n workspaceVercelAiGatewayConnectionActive,\n workspaceOpenRouterConnectionActive,\n workspaceXaiSubscriptionActiveForAuthority,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport {\n type OpenGeniRuntime,\n type AttemptConnectorActionBinding,\n type ConnectorAttachmentMaterializationRequest,\n type ConnectorActionPolicyHooks,\n createFirstPartyInteractionAttemptToolDefinitions,\n} from \"@opengeni/runtime\";\nimport {\n createGoogleDrivePublicationAttemptTool,\n googleDrivePublicationConnectorCall,\n resolveGoogleDrivePublicationTarget,\n} from \"../google-drive-publication\";\nimport { connectionTokenResolverForTurn } from \"../mcp-credentials\";\nimport { buildGitHubRestMcpForTurn } from \"../../github-rest-mcp\";\nimport { materializeConnectorAttachmentsInChannel } from \"../connector-attachments\";\nimport { allowedFirstPartyMcpToolsForSession, type Settings } from \"@opengeni/config\";\nimport { CodemodeAttemptDispatcher } from \"../codemode-dispatcher\";\nimport { buildCodexTokenResolver } from \"../codex-auth\";\nimport { CODEX_CLIENT_VERSION } from \"@opengeni/codex\";\nimport { mergeResourceRefs } from \"../common\";\nimport {\n defaultSessionMcpServerIds,\n loadRigDefaultVariableSetEnvironment,\n mergeRigDefaultVariableSetEnvironment,\n buildApiIntegrationMcpServers,\n resolveCatalogSettings,\n resolveWorkspaceModelSelection,\n withFrozenPersonalConnectionDelegations,\n resolveSessionToolPolicy,\n hasPermission,\n} from \"@opengeni/core\";\nimport { loadWorkspaceEnvironmentForRunWithCredentials } from \"../environment\";\nimport { withFirstPartyTools } from \"../goals\";\nimport type { TurnActivityServices as ActivityServices, RunAgentTurnInput } from \"../types\";\nimport { recordTurnStartupPhase } from \"../../observability-metrics\";\nimport { ToolResultSpill } from \"./tool-result-spill\";\nimport { createTurnMediaArtifacts } from \"./media-artifacts\";\nimport { SandboxChannelAService } from \"@opengeni/runtime/sandbox\";\nimport { sandboxRunAs } from \"@opengeni/runtime\";\nimport {\n DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,\n type ToolAuthNeededPayload,\n} from \"@opengeni/contracts\";\n\nimport {\n rollingSafeToolAuthNeededPayload,\n shouldPublishToolAuthNeededForTurn,\n xaiCatalogReadinessAuthority,\n} from \"./admission\";\nimport { unavailableMcpOperationalContext } from \"./errors\";\nimport { runtimeResourcesForTurn } from \"./file-resources\";\nimport { waitForTurnOperation } from \"./sandbox-provision\";\nimport { shouldDeferNonEagerToolPreparation } from \"./tool-policy\";\nimport type { ClaimTurnOk } from \"./claim\";\nimport type { GovernanceModelOk } from \"./governance-model\";\nimport type { SandboxTurnRuntime } from \"./sandbox-runtime\";\nimport type { sandboxArtifactRuntimeAdmission } from \"./sandbox-route\";\nimport type {\n AttemptIdentityState,\n EventingState,\n SandboxRuntimeState,\n WorkspaceRefState,\n} from \"./turn-context\";\nimport {\n createSessionTitleAttemptToolDefinition,\n sessionTitleToolPlan,\n shouldRequestMissingSessionTitle,\n} from \"./session-title\";\nimport { resolveTurnSandboxAccess } from \"./turn-sandbox-access\";\nimport { createListModelsAttemptToolDefinition } from \"./list-models\";\nimport { createWorkspaceSkillTools } from \"./skill-tools\";\nimport { loadConfiguredBundledSkills } from \"./skill-selection\";\nimport { guardSkillFilesystem } from \"./skill-transfer\";\nimport type { RuntimeSkillActivation } from \"@opengeni/runtime\";\n\nexport type PrepareTurnToolPolicyDeps = {\n input: RunAgentTurnInput;\n db: ActivityServices[\"db\"];\n cancellationSignal: AbortSignal | undefined;\n connectionCredentials: ActivityServices[\"connectionCredentials\"];\n turn: ClaimTurnOk[\"turn\"];\n session: ClaimTurnOk[\"session\"];\n fileAuthoritySubjectId: ClaimTurnOk[\"fileAuthoritySubjectId\"];\n capabilitySettings: ClaimTurnOk[\"capabilitySettings\"];\n runSettings: GovernanceModelOk[\"runSettings\"];\n rigVersion: GovernanceModelOk[\"rigVersion\"];\n workspaceRefs: WorkspaceRefState;\n};\n\nexport type PrepareTurnToolRuntimeDeps = {\n selectedSkillActivations: readonly RuntimeSkillActivation[];\n input: RunAgentTurnInput;\n catalogSourceSettings: Settings;\n db: ActivityServices[\"db\"];\n bus: ActivityServices[\"bus\"];\n runtime: ActivityServices[\"runtime\"];\n objectStorage: ActivityServices[\"objectStorage\"];\n observability: ActivityServices[\"observability\"];\n cancellationSignal: AbortSignal | undefined;\n connectionCredentials: ActivityServices[\"connectionCredentials\"];\n eventing: EventingState;\n attempt: AttemptIdentityState;\n sandboxState: SandboxRuntimeState;\n media: ReturnType<typeof createTurnMediaArtifacts>;\n toolResultSpill: ToolResultSpill;\n turn: ClaimTurnOk[\"turn\"];\n session: ClaimTurnOk[\"session\"];\n fileAuthoritySubjectId: ClaimTurnOk[\"fileAuthoritySubjectId\"];\n capabilitySettings: ClaimTurnOk[\"capabilitySettings\"];\n installedApiIntegrations: ClaimTurnOk[\"installedApiIntegrations\"];\n codexAppsCredentialId: ClaimTurnOk[\"codexAppsCredentialId\"];\n turnExecutionPolicy: ClaimTurnOk[\"turnExecutionPolicy\"];\n trigger: ClaimTurnOk[\"trigger\"];\n runSettings: GovernanceModelOk[\"runSettings\"];\n lazyToolTransport: GovernanceModelOk[\"lazyToolTransport\"];\n turnTools: ReturnType<typeof withFirstPartyTools>;\n connectionScope: { accountId: string; workspaceId: string };\n hostCredentialRootSessionId: string | null;\n sandboxArtifactRuntime: ReturnType<typeof sandboxArtifactRuntimeAdmission>;\n activeSandboxBackend: Settings[\"sandboxBackend\"] | undefined;\n groupBoxBackend: Settings[\"sandboxBackend\"];\n routingOn: boolean;\n runtimeCancellationSignal: AbortSignal | undefined;\n credentialSubjectId: ClaimTurnOk[\"credentialSubjectId\"];\n interactionInterventionResume: ClaimTurnOk[\"interactionInterventionResume\"];\n runWorkspaceMutationForSandbox: SandboxTurnRuntime[\"runWorkspaceMutationForSandbox\"];\n throwIfWorkerShuttingDown: () => void;\n throwIfTurnCancelled: () => void;\n};\n\nexport async function prepareTurnToolPolicy(deps: PrepareTurnToolPolicyDeps) {\n const {\n input,\n db,\n cancellationSignal,\n connectionCredentials,\n turn,\n session,\n fileAuthoritySubjectId,\n capabilitySettings,\n runSettings,\n rigVersion,\n workspaceRefs,\n } = deps;\n\n const turnResources = mergeResourceRefs(session.resources, turn.resources);\n // Repositories remain durable workspace inputs. File attachments do not:\n // only files attached to this exact turn enter the sandbox manifest and\n // eager materialization path. Historical file ids remain in canonical\n // history/session metadata and are recoverable through the Files MCP.\n const runtimeResources = runtimeResourcesForTurn(session.resources, turn.resources);\n // Attach the first-party MCP server to EVERY turn, regardless of how/when\n // the session was created (API, scheduled task, or a pre-existing session\n // whose stored tools predate this). The server registration is then\n // narrowed by the session's exact firstPartyMcpTools selection and\n // authorization. Idempotent: mergeToolRefs dedupes if already present.\n // Resolve the durable policy at the turn boundary. Workspace-default\n // sessions follow the current configured MCP set,\n // while explicit, inherited-fixed, and legacy sessions remain narrowed\n // to their stored materialized allow-list.\n const scheduledEffectiveMcpServerIds = (() => {\n const value =\n turn.metadata && typeof turn.metadata === \"object\" && !Array.isArray(turn.metadata)\n ? (turn.metadata as Record<string, unknown>).scheduledEffectiveMcpServerIds\n : null;\n return Array.isArray(value) && value.every((id) => typeof id === \"string\")\n ? [...new Set(value)].sort()\n : null;\n })();\n const currentMcpServerIds = new Set(runSettings.mcpServers.map((server) => server.id));\n const resolvedToolPolicy = resolveSessionToolPolicy({\n toolPolicy: session.toolPolicy,\n sessionTools: scheduledEffectiveMcpServerIds ? turn.tools : session.tools,\n availableMcpServerIds: scheduledEffectiveMcpServerIds\n ? scheduledEffectiveMcpServerIds.filter((id) => currentMcpServerIds.has(id))\n : [...currentMcpServerIds],\n defaultMcpServerIds:\n scheduledEffectiveMcpServerIds ?? defaultSessionMcpServerIds(capabilitySettings.mcpServers),\n });\n const mcpAvailabilityNote = unavailableMcpOperationalContext({\n droppedIds: resolvedToolPolicy.effectivePolicy.droppedIds,\n droppedCount: resolvedToolPolicy.effectivePolicy.counts.dropped,\n });\n const effectivePolicyTools = resolvedToolPolicy.toolRefs;\n const turnTools = withFirstPartyTools(runSettings, effectivePolicyTools);\n // §7.6 connection-credential provider — load (and decrypt) selected Variable Sets via the\n // host `sandboxSecrets` provider when bound; unset → today's local decrypt. Preserve the\n // legacy null-attachment fast path: turns with neither a session set nor rig defaults perform\n // no Variable Set work. Organization/workspace sets use the exact turn actor; personal sets\n // additionally require the causal human frozen into the admitted turn.\n const connectionScope = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n };\n const rigDefaultVariableSetIds = rigVersion?.defaultVariableSetIds ?? [];\n const sessionVariableSetIds = session.variableSetIds;\n let workspaceVariableSet: Awaited<\n ReturnType<typeof loadWorkspaceEnvironmentForRunWithCredentials>\n > = null;\n const explicitEnvironmentValues: Record<string, string> = {};\n const rigDefaultEnvironmentValues: Record<string, string> = {};\n if (sessionVariableSetIds.length > 0 || rigDefaultVariableSetIds.length > 0) {\n const variableSetAuthority = {\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: turn.executionGeneration,\n initiator: turn.initiator,\n initiatingHumanSubjectId: fileAuthoritySubjectId,\n };\n // A scheduled attempt may materialize only the exact generation frozen\n // on its accepted occurrence; ordinary turns resolve to null.\n const expectedVariableSetGeneration = async (\n candidateVariableSetId: string,\n ): Promise<number | null> =>\n await getScheduledVariableSetExpectedGenerationForAttempt(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: fileAuthoritySubjectId ?? turn.initiator.subjectId,\n initiatingHumanSubjectId: fileAuthoritySubjectId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: turn.executionGeneration,\n variableSetId: candidateVariableSetId,\n });\n for (const variableSetId of sessionVariableSetIds) {\n const selected = await waitForTurnOperation(\n (async () =>\n loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n variableSetId,\n variableSetAuthority,\n connectionCredentials?.sandboxSecrets,\n connectionCredentials?.sandboxSecrets\n ? { expectedGeneration: await expectedVariableSetGeneration(variableSetId) }\n : {},\n ))(),\n cancellationSignal,\n undefined,\n );\n if (!selected) continue;\n Object.assign(explicitEnvironmentValues, selected.values);\n // Preserve the legacy single-set metadata view as the final,\n // highest-precedence explicit selection while its values represent the\n // complete ordered explicit layer.\n workspaceVariableSet = { ...selected, values: { ...explicitEnvironmentValues } };\n }\n // RIG DEFAULT VARIABLE SETS (M3): decrypt the frozen rig version's default\n // variable sets and layer them BELOW the session's own set — the session's\n // values WIN on any key collision. Loaded through the SAME host-secrets\n // provider path as the session set (embedded-topology parity). Precedence\n // WITHIN the rig defaults is listed order (a later set overrides an earlier\n // one), then the session set overrides all. STABLE-ENV INVARIANT: the rig\n // VERSION is frozen per session, so the SET of default variable sets is\n // fixed for the session's life — the merged manifest env is therefore stable\n // across the session's turns (the same guarantee the session's own variable\n // set already relies on), keeping validateNoEnvironmentDelta empty.\n Object.assign(\n rigDefaultEnvironmentValues,\n await loadRigDefaultVariableSetEnvironment(\n rigDefaultVariableSetIds,\n async (rigDefaultVariableSetId) =>\n await waitForTurnOperation(\n (async () =>\n loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n rigDefaultVariableSetId,\n variableSetAuthority,\n connectionCredentials?.sandboxSecrets,\n connectionCredentials?.sandboxSecrets\n ? {\n expectedGeneration:\n await expectedVariableSetGeneration(rigDefaultVariableSetId),\n }\n : {},\n ))(),\n cancellationSignal,\n undefined,\n ),\n ),\n );\n }\n workspaceRefs.variableSetId = workspaceVariableSet?.id ?? \"\";\n // Session set wins collisions with the rig defaults (explicit precedence).\n const sandboxWorkspaceEnvironmentValues = mergeRigDefaultVariableSetEnvironment(\n rigDefaultEnvironmentValues,\n explicitEnvironmentValues,\n );\n return {\n turnResources,\n runtimeResources,\n mcpAvailabilityNote,\n turnTools,\n connectionScope,\n workspaceVariableSet,\n sandboxWorkspaceEnvironmentValues,\n };\n}\n\nexport async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {\n const {\n input,\n catalogSourceSettings,\n db,\n bus,\n runtime,\n objectStorage,\n observability,\n cancellationSignal,\n connectionCredentials,\n eventing,\n attempt,\n sandboxState,\n media,\n toolResultSpill,\n turn,\n session,\n installedApiIntegrations,\n codexAppsCredentialId,\n turnExecutionPolicy,\n trigger,\n runSettings,\n lazyToolTransport,\n turnTools,\n hostCredentialRootSessionId,\n sandboxArtifactRuntime,\n activeSandboxBackend,\n groupBoxBackend,\n routingOn,\n runtimeCancellationSignal,\n credentialSubjectId,\n interactionInterventionResume,\n runWorkspaceMutationForSandbox,\n throwIfWorkerShuttingDown,\n throwIfTurnCancelled,\n } = deps;\n\n const toolContextPreparationStartedAt = performance.now();\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n const mcpCredentialRootSessionId =\n connectionCredentials?.mcpCredentials && hostCredentialRootSessionId\n ? hostCredentialRootSessionId\n : input.sessionId;\n // Connection credentials and the optional Apps credential are resolved\n // independently. Inference auth is never an Apps fallback.\n const rawResolveCredential = connectionTokenResolverForTurn({\n db,\n settings: runSettings,\n connectionCredentials: connectionCredentials ?? null,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n rootSessionId: mcpCredentialRootSessionId,\n attemptId: input.attemptId,\n turn,\n observability,\n });\n const personalConnectionDelegations = turn.personalConnectionDelegations;\n const delegatedMembershipChecks = new Map<string, Promise<boolean>>();\n // The canonical live-authority resolver, not a bare `workspace_memberships`\n // join: a managed human's personal workspace deliberately has no membership\n // row (migration 0219), so the bare join would revoke the owner's own frozen\n // personal connections for every turn that runs in their private workspace.\n const delegatedOwnerHasMembership = async (subjectId: string): Promise<boolean> => {\n const existing = delegatedMembershipChecks.get(subjectId);\n if (existing) return await existing;\n const check = namedSubjectHasLiveWorkspaceAuthority(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n });\n delegatedMembershipChecks.set(subjectId, check);\n return await check;\n };\n const resolveFrozenCredential = withFrozenPersonalConnectionDelegations({\n resolveCredential: rawResolveCredential,\n settings: runSettings,\n personalConnectionDelegations,\n ownerHasWorkspaceMembership: delegatedOwnerHasMembership,\n });\n const resolveCredential: typeof rawResolveCredential = async (request) => {\n const result = await resolveFrozenCredential(request);\n if (result.status === \"ok\") {\n }\n return result;\n };\n const connectorActionIdentity = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n initiator: {\n kind: turn.initiator.kind,\n subjectId: turn.initiator.subjectId,\n },\n } as const;\n const googleDrivePublicationTarget = objectStorage\n ? await resolveGoogleDrivePublicationTarget(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n personalConnectionDelegations,\n )\n : null;\n const googleDrivePublicationTool =\n objectStorage && googleDrivePublicationTarget\n ? createGoogleDrivePublicationAttemptTool({\n db,\n objectStorage,\n identity: connectorActionIdentity,\n subjectId: googleDrivePublicationTarget.ownerSubjectId,\n target: googleDrivePublicationTarget,\n resolveCredential,\n ...(runtimeCancellationSignal ? { signal: runtimeCancellationSignal } : {}),\n })\n : null;\n const publishToolAuthNeeded = async (payload: ToolAuthNeededPayload): Promise<void> => {\n if (!shouldPublishToolAuthNeededForTurn(payload, trigger, turn)) {\n return;\n }\n await eventing.publish!(\n [{ type: \"tool.auth_needed\", payload: rollingSafeToolAuthNeededPayload(payload) }],\n true,\n );\n };\n const selectedApiIntegrationServerIds = new Set(turnTools.map((tool) => tool.id));\n const apiIntegrationMcpServers = buildApiIntegrationMcpServers({\n settings: runSettings,\n integrations: installedApiIntegrations.filter((integration) =>\n selectedApiIntegrationServerIds.has(integration.serverId),\n ),\n authority: {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n rootSessionId: session.rootSessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n ...(credentialSubjectId ? { initiatingSubjectId: credentialSubjectId } : {}),\n },\n resolveCredential,\n onAuthNeeded: publishToolAuthNeeded,\n });\n const githubRestMcp = await buildGitHubRestMcpForTurn({\n db,\n settings: runSettings,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n turn,\n resources: mergeResourceRefs(session.resources, turn.resources),\n tools: turnTools,\n resolveCredential,\n });\n const localMcpServers = [...apiIntegrationMcpServers, ...githubRestMcp.localMcpServers];\n const codexAppsAuth = codexAppsCredentialId\n ? (() => {\n const resolver = buildCodexTokenResolver(\n db,\n runSettings,\n input.workspaceId,\n codexAppsCredentialId,\n );\n return {\n clientVersion: CODEX_CLIENT_VERSION,\n withAuthorization: async <T>(\n use: (token: { accessToken: string; chatgptAccountId: string | null }) => Promise<T>,\n ): Promise<T> => {\n const snapshot = await resolver.getToken();\n\n return await withCodexAppsRequestAuthorization(\n db,\n {\n workspaceId: input.workspaceId,\n credentialId: codexAppsCredentialId,\n },\n async () => await use(snapshot),\n );\n },\n };\n })()\n : undefined;\n const linkedAuthority = await getExternalLinkTurnAuthorization(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n },\n turn.id,\n );\n if (linkedAuthority && !linkedAuthority.authorized)\n throw new Error(\"Native identity link was revoked\");\n const effectiveFirstPartyPermissions = linkedAuthority\n ? (session.firstPartyMcpPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS).filter(\n (permission) => hasPermission(linkedAuthority.permissions, permission),\n )\n : session.firstPartyMcpPermissions;\n const selectedFirstPartyMcpTools = allowedFirstPartyMcpToolsForSession(\n runSettings,\n session.firstPartyMcpTools,\n );\n const titleToolPlan = sessionTitleToolPlan({\n tools: turnTools,\n selectedFirstPartyMcpTools,\n shouldRequestTitle: shouldRequestMissingSessionTitle({\n title: session.title,\n titleSource: session.titleSource,\n firstPartyMcpTools: selectedFirstPartyMcpTools,\n firstPartyMcpPermissions: effectiveFirstPartyPermissions,\n }),\n parallelGenerationAvailable: typeof runtime.generateSessionTitle === \"function\",\n });\n const googleDrivePublicationAllowed =\n selectedFirstPartyMcpTools.includes(\"editable_artifact_export\") &&\n selectedFirstPartyMcpTools.includes(\"editable_artifact_export_status\") &&\n hasPermission(\n [...(effectiveFirstPartyPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS)],\n \"artifacts:read\",\n ) &&\n hasPermission(\n [...(effectiveFirstPartyPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS)],\n \"artifacts:publish\",\n );\n const googleDriveConnectorBindings: readonly AttemptConnectorActionBinding[] =\n googleDrivePublicationTool && googleDrivePublicationTarget && googleDrivePublicationAllowed\n ? [\n {\n modelName: googleDrivePublicationTool.modelName,\n call: (approvalId, arguments_) =>\n googleDrivePublicationConnectorCall(\n googleDrivePublicationTarget,\n arguments_,\n approvalId,\n ),\n },\n ]\n : [];\n const attemptConnectorActionBindings = [\n ...googleDriveConnectorBindings,\n ...githubRestMcp.connectorBindings,\n ];\n const connectorActionPolicy: ConnectorActionPolicyHooks = {\n preview: async (call) =>\n await previewConnectorActionApproval(db, connectorActionIdentity, call),\n prepare: async (call) =>\n await prepareConnectorActionApproval(db, connectorActionIdentity, call),\n begin: async (call) => await beginConnectorActionExecution(db, connectorActionIdentity, call),\n complete: async ({ requestId, outcome }) =>\n await completeConnectorActionExecution(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n requestId,\n attemptId: input.attemptId,\n outcome,\n }),\n };\n const skillConfiguration = await getWorkspaceVideoGenerationPolicy(db, input.workspaceId);\n const bundledSkills = loadConfiguredBundledSkills({\n bundledSkillIds: session.bundledSkillIds,\n firstPartyTools: selectedFirstPartyMcpTools,\n videoGenerationEnabled:\n skillConfiguration.defaultModelId !== null && skillConfiguration.enabledModelIds.length > 0,\n });\n const selectedSkills = [\n ...bundledSkills,\n ...deps.selectedSkillActivations.map((entry) => ({ id: entry.id, artifact: entry.artifact })),\n ...session.skills.map((skill) => ({\n id: `session:${session.id}:${skill.name}`,\n artifact: skill,\n })),\n ];\n const sharedSkillDescriptors = await listSkillDescriptors(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n ...(deps.fileAuthoritySubjectId ? { subjectId: deps.fileAuthoritySubjectId } : {}),\n });\n const skillCatalog = [\n ...sharedSkillDescriptors\n .filter((entry) => entry.activationMode === \"workspace_managed\")\n .map((entry) => ({\n id: entry.id,\n name: entry.title,\n description: entry.description,\n })),\n ...selectedSkills.map((entry) => ({\n id: entry.id,\n name: entry.artifact.name,\n description: entry.artifact.description || entry.artifact.name,\n })),\n ];\n const skillTools = createWorkspaceSkillTools({\n db,\n settings: runSettings,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n ...(deps.fileAuthoritySubjectId ? { subjectId: deps.fileAuthoritySubjectId } : {}),\n actor: {\n kind: \"agent\",\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n },\n selected: selectedSkills,\n filesystem: async () => {\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n const access = await resolveTurnSandboxAccess(\n sandboxState,\n media.sdkOwnedSandboxSession,\n \"Skill checkout/publish requires a sandbox or Connected Machine.\",\n );\n const machineRoot = sandboxState.machinePrimarySession?.workspaceRoot;\n const runAs = sandboxRunAs(runSettings);\n const channel = new SandboxChannelAService({\n session: access.session,\n workspaceRoot: machineRoot ?? \"/workspace\",\n ...(machineRoot ? { providerPathMode: \"workspace-relative\" as const } : {}),\n leaseEpoch: access.leaseEpoch,\n emit: async (events) => {\n await eventing.publish?.(events, true);\n },\n ...(runAs ? { runAs } : {}),\n });\n return guardSkillFilesystem(channel, {\n assertActive: () => {\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n },\n runMutation: async (mutation) =>\n access.sandbox && !routingOn\n ? runWorkspaceMutationForSandbox(access.sandbox, \"skillCheckout\", mutation)\n : mutation(),\n });\n },\n });\n const attemptToolDefinitions = [\n ...skillTools,\n createListModelsAttemptToolDefinition({\n currentModelId: turnExecutionPolicy.productModelId,\n load: async () => {\n const currentCatalog = await resolveCatalogSettings(db, catalogSourceSettings);\n const currentSettings = currentCatalog.settings;\n const xaiReadinessAuthority = xaiCatalogReadinessAuthority(turn, credentialSubjectId);\n const [\n connectionModelRestrictions,\n policy,\n codexSubscriptionActive,\n xaiSubscriptionActive,\n workspaceGatewayConnectionActive,\n workspaceGatewayCustomModels,\n openRouterConnectionActive,\n workspaceOpenRouterCustomModels,\n organizationGatewayConnectionActive,\n organizationGatewayCustomModels,\n organizationOpenRouterConnectionActive,\n organizationOpenRouterCustomModels,\n ] = await Promise.all([\n getWorkspaceConnectionModelRestrictions(\n db,\n input.workspaceId,\n xaiReadinessAuthority?.subjectId ?? credentialSubjectId ?? \"worker:model-access\",\n xaiReadinessAuthority?.authoritySnapshot,\n ),\n getWorkspaceModelPolicy(db, input.workspaceId),\n workspaceCodexSubscriptionActive(db, currentSettings, input.workspaceId),\n xaiReadinessAuthority && currentSettings.supergrokSubscriptionEnabled\n ? workspaceXaiSubscriptionActiveForAuthority(db, currentSettings, {\n workspaceId: input.workspaceId,\n ...xaiReadinessAuthority,\n })\n : false,\n workspaceVercelAiGatewayConnectionActive(db, input.workspaceId),\n listWorkspaceGatewayCustomModels(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n }),\n workspaceOpenRouterConnectionActive(db, input.workspaceId),\n listWorkspaceOpenRouterCustomModels(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n }),\n organizationModelProviderConnectionActiveForWorkspace(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n providerKind: \"vercel_gateway\",\n }),\n listOrganizationModelProviderCustomModelsForWorkspace(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n providerKind: \"vercel_gateway\",\n }),\n organizationModelProviderConnectionActiveForWorkspace(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n providerKind: \"openrouter\",\n }),\n listOrganizationModelProviderCustomModelsForWorkspace(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n providerKind: \"openrouter\",\n }),\n ]);\n return {\n selections: resolveWorkspaceModelSelection({\n connectionModelRestrictions,\n settings: currentSettings,\n policy,\n codexSubscriptionActive,\n xaiSubscriptionActive,\n workspaceGatewayConnectionActive,\n workspaceGatewayCustomModels,\n workspaceOpenRouterConnectionActive: openRouterConnectionActive,\n workspaceOpenRouterCustomModels,\n organizationGatewayConnectionActive,\n organizationGatewayCustomModels,\n organizationOpenRouterConnectionActive,\n organizationOpenRouterCustomModels,\n }),\n modelNotes: currentCatalog.modelNotes,\n };\n },\n }),\n ...(titleToolPlan.promoteTitleTool\n ? [\n createSessionTitleAttemptToolDefinition({\n updateTitle: async (title) => {\n const result = await updateSessionTitleWithEvent(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n title,\n source: \"agent\",\n });\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n result.events,\n );\n return result;\n },\n }),\n ]\n : []),\n ...createFirstPartyInteractionAttemptToolDefinitions({\n settings: runSettings,\n scope: {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n },\n ...(effectiveFirstPartyPermissions ? { permissions: effectiveFirstPartyPermissions } : {}),\n selectedTools: selectedFirstPartyMcpTools,\n subjectId: \"worker:first-party-mcp\",\n subjectLabel: \"OpenGeni worker\",\n ...(interactionInterventionResume\n ? { interventionResume: interactionInterventionResume }\n : {}),\n }),\n ...(googleDrivePublicationTool && googleDrivePublicationAllowed\n ? [googleDrivePublicationTool]\n : []),\n ];\n recordTurnStartupPhase(observability, {\n phase: \"tool_context_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - toolContextPreparationStartedAt) / 1_000,\n count: githubRestMcp.tools.length,\n });\n await eventing.publish!([\n {\n type: \"turn.startup.phase.started\",\n payload: { phase: \"tools\" },\n },\n ]);\n const toolPreparationStartedAt = performance.now();\n let toolPreparationOutcome: \"completed\" | \"failed\" = \"completed\";\n const progressiveDisclosureEnabled =\n lazyToolTransport === \"codex_native\"\n ? runSettings.codexToolSearchEnabled\n : runSettings.lazyToolSearchEnabled;\n const deferNonEagerToolPreparation = shouldDeferNonEagerToolPreparation({\n lazyToolTransport,\n progressiveDisclosureEnabled,\n artifactRuntimeAvailable: sandboxArtifactRuntime.available,\n triggerKind: input.trigger.kind,\n triggerType: trigger.type,\n });\n const materializeConnectorAttachments = async (\n request: ConnectorAttachmentMaterializationRequest,\n ) => {\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n const sandboxAccess = await resolveTurnSandboxAccess(\n sandboxState,\n media.sdkOwnedSandboxSession,\n \"Connector attachment sandbox is unavailable\",\n );\n const sandbox = sandboxAccess.sandbox;\n const runAs = sandboxRunAs(runSettings);\n const channel = new SandboxChannelAService({\n session: sandboxAccess.session,\n workspaceRoot: \"/workspace\",\n leaseEpoch: sandboxAccess.leaseEpoch,\n emit: async (events) => {\n await eventing.publish?.(events, true);\n },\n ...(runAs ? { runAs } : {}),\n });\n return await materializeConnectorAttachmentsInChannel(channel, request, {\n runMutation: async (mutation) => {\n if (sandbox && !routingOn) {\n return await runWorkspaceMutationForSandbox(\n sandbox,\n \"connectorAttachmentMaterialization\",\n mutation,\n );\n }\n return await mutation();\n },\n });\n };\n try {\n eventing.preparedTools = await waitForTurnOperation(\n runtime.prepareTools(githubRestMcp.settings, githubRestMcp.tools, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n // Sign the calling turn into the first-party token so tools classify\n // the caller by its own identity (sacred-pause guard), not the racy\n // live active pointer.\n ...(attempt.turnId ? { turnId: attempt.turnId } : {}),\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n subjectId: \"worker:first-party-mcp\",\n subjectLabel: \"OpenGeni worker\",\n ...(credentialSubjectId ? { credentialSubjectId } : {}),\n ...(codexAppsAuth ? { codexAppsAuth } : {}),\n resolveCredential,\n ...(linkedAuthority\n ? {\n authorizeAttemptExecution: async () => {\n const current = await getSessionTurnForAttempt(\n db,\n input.workspaceId,\n input.sessionId,\n input.attemptId,\n );\n if (\n !current ||\n current.id !== turn.id ||\n current.executionGeneration !== attempt.executionGeneration\n )\n throw new Error(\"The linked agent attempt is no longer authorized\");\n },\n }\n : {}),\n onAuthNeeded: publishToolAuthNeeded,\n materializeConnectorAttachments,\n refreshOwnedCommand: async (commandId) => {\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n // Read only the existing attempt-owned object. A retained read must\n // not provision a sandbox or follow an active-pointer change.\n const owned = (sandboxState.lazyOwnedSandbox?.session ??\n sandboxState.resolvedSandbox?.established.session ??\n media.sdkOwnedSandboxSession) as {\n refreshOwnedCommand?: (id: string) => Promise<boolean>;\n } | null;\n return (await owned?.refreshOwnedCommand?.(commandId)) ?? false;\n },\n spillOversizedModelToolResult: async ({ operationId, result }) =>\n await toolResultSpill.spill({ operationId, result }),\n localMcpServers,\n ...(deferNonEagerToolPreparation ? { deferNonEagerUntilToolDemand: true } : {}),\n onPreparationPhase: (measurement) => {\n recordTurnStartupPhase(observability, {\n phase: `tool_${measurement.phase}`,\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: measurement.outcome,\n durationSeconds: measurement.durationSeconds,\n count: githubRestMcp.tools.length,\n });\n },\n onAttemptToolCatalog: async (catalog) => {\n await persistAttemptToolCatalog(db, catalog);\n },\n // Manager-style sessions carry a creation-validated permission set\n // for their first-party MCP token; null keeps the fixed default.\n ...(effectiveFirstPartyPermissions\n ? { firstPartyPermissions: effectiveFirstPartyPermissions }\n : {}),\n firstPartyTools: titleToolPlan.remoteFirstPartyMcpTools,\n nestedAgentDepth: session.nestedAgentDepth,\n effectiveMaxNestedAgentDepth: session.effectiveMaxNestedAgentDepth,\n attemptToolDefinitions,\n connectorActionPolicy,\n attemptConnectorActionBindings,\n }),\n cancellationSignal,\n async (latePreparedTools) => await latePreparedTools.close().catch(() => undefined),\n );\n } catch (error) {\n toolPreparationOutcome = \"failed\";\n throw error;\n } finally {\n const toolPreparationDurationMs = performance.now() - toolPreparationStartedAt;\n recordTurnStartupPhase(observability, {\n phase: \"tool_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: toolPreparationOutcome,\n durationSeconds: toolPreparationDurationMs / 1_000,\n count: githubRestMcp.tools.length,\n });\n await eventing.publish!([\n {\n type:\n toolPreparationOutcome === \"completed\"\n ? \"turn.startup.phase.completed\"\n : \"turn.startup.phase.failed\",\n payload: {\n phase: \"tools\",\n durationMs: Math.max(0, Math.round(toolPreparationDurationMs)),\n },\n },\n ]);\n }\n const postToolPreparationStartedAt = performance.now();\n const activatePreparedToolEnvironment = (\n tools: Awaited<ReturnType<OpenGeniRuntime[\"prepareTools\"]>>,\n ): void => {\n if (\n eventing.toolPreparationClosing ||\n !attempt.turnId ||\n !tools.attemptToolEnvironment ||\n eventing.codemodeDispatcher\n ) {\n return;\n }\n eventing.codemodeDispatcher = new CodemodeAttemptDispatcher(\n db,\n bus,\n tools.attemptToolEnvironment,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: attempt.turnId,\n attemptId: input.attemptId,\n executionGeneration: attempt.executionGeneration,\n },\n cancellationSignal,\n );\n eventing.codemodeDispatcher.start();\n };\n if (eventing.preparedTools.ready) {\n const toolPreparationReady = eventing.preparedTools.ready.then((tools) => {\n activatePreparedToolEnvironment(tools);\n });\n // The lazy runtime awaits and rethrows this exact failure when a model\n // attempts to use tools. Attach a handler immediately so an early MCP\n // rejection cannot become a process-level unhandled rejection first.\n void toolPreparationReady.catch(() => undefined);\n eventing.toolPreparationReady = toolPreparationReady;\n } else {\n activatePreparedToolEnvironment(eventing.preparedTools);\n }\n return {\n attemptConnectorActionBindings,\n connectorActionPolicy,\n generateSessionTitleInParallel: titleToolPlan.generateTitleInParallel,\n postToolPreparationStartedAt,\n preparationIndependentToolNames: [\n ...titleToolPlan.preparationIndependentToolNames,\n \"skill_read\",\n ],\n skillCatalog,\n };\n}\n\nexport type PrepareTurnToolPolicyOk = Awaited<ReturnType<typeof prepareTurnToolPolicy>>;\nexport type PrepareTurnToolRuntimeOk = Awaited<ReturnType<typeof prepareTurnToolRuntime>>;\n","import { createHash } from \"node:crypto\";\nimport type { AttemptToolDefinition } from \"@opengeni/codemode\";\nimport type { McpPersonalConnectionDelegation } from \"@opengeni/contracts\";\nimport {\n GOOGLE_DRIVE_FILE_SCOPE,\n GOOGLE_DRIVE_FULL_SCOPE,\n GOOGLE_DRIVE_PUBLICATION_CREATE_ACTION,\n GOOGLE_DRIVE_PUBLICATION_SERVER_ID,\n GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,\n GOOGLE_DRIVE_PROVIDER_DOMAIN,\n GoogleDriveConnectionMetadata,\n GoogleDrivePublicationReceipt,\n GoogleDrivePublicationToolInput,\n googleDriveScopesAllowCapability,\n type GoogleDriveOutputDestination,\n type GoogleDrivePublicationReceipt as GoogleDrivePublicationReceiptValue,\n type GoogleDrivePublicationToolInput as GoogleDrivePublicationToolInputValue,\n} from \"@opengeni/contracts/google-drive\";\nimport {\n getConnectionMetadata,\n requireFile,\n namedSubjectHasLiveWorkspaceAuthority,\n type ConnectorActionAttemptIdentity,\n type ConnectorActionInvocation,\n type Database,\n type ResolveConnectionCredentialInput,\n type ResolveConnectionCredentialResult,\n} from \"@opengeni/db\";\nimport {\n readAuthorizedEditableArtifactMaterialization,\n type PersistedEditableArtifactMaterializationJob,\n} from \"@opengeni/db/editable-artifact-durable-export\";\nimport { readResponseJsonBounded, undiciFetch, type FetchLike } from \"@opengeni/network\";\nimport { ConnectorActionExecutionError } from \"@opengeni/runtime\";\nimport { retryWhileMissing, type ObjectStorage } from \"@opengeni/storage\";\n\nconst DRIVE_API = \"https://www.googleapis.com/drive/v3\";\nconst DRIVE_UPLOAD_API = \"https://www.googleapis.com/upload/drive/v3\";\nconst DRIVE_FOLDER_MIME = \"application/vnd.google-apps.folder\";\nconst RESPONSE_MAX_BYTES = 256 * 1024;\nconst REQUEST_TIMEOUT_MS = 30_000;\nconst FIRST_PARTY_MCP_SUBJECT_ID = \"worker:first-party-mcp\";\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;\n\nclass GoogleDrivePublicationAuthorizationError extends Error {}\n\nexport type GoogleDrivePublicationTarget = Readonly<{\n ownerSubjectId: string;\n connectionId: string;\n originWorkspaceId: string;\n destination: GoogleDriveOutputDestination;\n credentialScope: typeof GOOGLE_DRIVE_FILE_SCOPE | typeof GOOGLE_DRIVE_FULL_SCOPE;\n}>;\n\nexport type GoogleDrivePublicationPorts = {\n getConnection: typeof getConnectionMetadata;\n /**\n * Live workspace authority for the frozen delegation owner. This must be the\n * canonical resolver, not a bare `workspace_memberships` join: a managed\n * human's personal workspace deliberately has no membership row (migration\n * 0219), so a bare join denies the owner publication inside their own\n * private workspace.\n */\n getMembership: typeof namedSubjectHasLiveWorkspaceAuthority;\n readMaterialization: typeof readAuthorizedEditableArtifactMaterialization;\n requireFile: typeof requireFile;\n fetch: FetchLike;\n};\n\nconst defaultPorts: GoogleDrivePublicationPorts = {\n getConnection: getConnectionMetadata,\n getMembership: namedSubjectHasLiveWorkspaceAuthority,\n readMaterialization: readAuthorizedEditableArtifactMaterialization,\n requireFile,\n fetch: undiciFetch,\n};\n\nexport async function resolveGoogleDrivePublicationTarget(\n db: Database,\n workspace: { accountId: string; workspaceId: string },\n delegations: readonly McpPersonalConnectionDelegation[],\n ports: Pick<GoogleDrivePublicationPorts, \"getConnection\" | \"getMembership\"> = defaultPorts,\n): Promise<GoogleDrivePublicationTarget | null> {\n const { workspaceId } = workspace;\n const frozen = delegations.filter(\n (delegation) =>\n delegation.serverId === GOOGLE_DRIVE_PUBLICATION_SERVER_ID &&\n delegation.providerDomain.toLowerCase() === GOOGLE_DRIVE_PROVIDER_DOMAIN &&\n delegation.kind === \"oauth2\",\n );\n if (frozen.length !== 1) return null;\n const delegation = frozen[0]!;\n const activated = delegation.userDelegation !== undefined;\n if (\n !activated &&\n !(await ports.getMembership(db, {\n accountId: workspace.accountId,\n workspaceId,\n subjectId: delegation.ownerSubjectId,\n }))\n ) {\n return null;\n }\n const originWorkspaceId = activated ? delegation.originWorkspaceId : workspaceId;\n if (!originWorkspaceId) return null;\n const connection = await ports.getConnection(\n db,\n originWorkspaceId,\n delegation.connectionId,\n delegation.ownerSubjectId,\n );\n if (\n !connection ||\n connection.id !== delegation.connectionId ||\n connection.workspaceId !== originWorkspaceId ||\n connection.subjectId !== delegation.ownerSubjectId ||\n connection.providerDomain.toLowerCase() !== GOOGLE_DRIVE_PROVIDER_DOMAIN ||\n connection.kind !== \"oauth2\" ||\n connection.status !== \"active\" ||\n !googleDriveScopesAllowCapability(connection.grantedScopes, \"publish_file\")\n ) {\n return null;\n }\n const metadata = GoogleDriveConnectionMetadata.safeParse(connection.metadata);\n if (\n !metadata.success ||\n !metadata.data.outputDestination ||\n metadata.data.lifecycle?.state === \"paused\" ||\n (metadata.data.lifecycle && metadata.data.lifecycle.state !== \"active\")\n ) {\n return null;\n }\n // The destination frozen on the accepted delegation is the authority. A\n // live connection-settings change since acceptance fails the target closed\n // (personal-authority warning path) instead of silently redirecting the\n // publication; a pre-freeze delegation keeps the bounded legacy\n // live-resolution behavior.\n const frozenDestination = delegation.outputDestination;\n if (frozenDestination && !sameDestination(metadata.data.outputDestination, frozenDestination)) {\n return null;\n }\n return Object.freeze({\n ownerSubjectId: delegation.ownerSubjectId,\n connectionId: connection.id,\n originWorkspaceId,\n destination: frozenDestination ?? metadata.data.outputDestination,\n credentialScope: connection.grantedScopes.includes(GOOGLE_DRIVE_FILE_SCOPE)\n ? GOOGLE_DRIVE_FILE_SCOPE\n : GOOGLE_DRIVE_FULL_SCOPE,\n });\n}\n\nexport function googleDrivePublicationConnectorCall(\n target: GoogleDrivePublicationTarget,\n rawRequest: unknown,\n approvalId: string,\n): ConnectorActionInvocation {\n const request = GoogleDrivePublicationToolInput.parse(rawRequest);\n return {\n approvalId,\n connectionId: target.connectionId,\n serverId: GOOGLE_DRIVE_PUBLICATION_SERVER_ID,\n toolName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,\n arguments: {\n action: GOOGLE_DRIVE_PUBLICATION_CREATE_ACTION,\n destination: target.destination,\n artifact: {\n id: request.file.artifactId,\n versionId: request.file.versionId,\n title: request.title,\n modality: request.modality,\n sourceSha256: request.file.sha256,\n },\n canonicalReceipt: { ...request.file },\n idempotencyKeyDigest: createHash(\"sha256\")\n .update(request.idempotencyKey, \"utf8\")\n .digest(\"hex\"),\n },\n };\n}\n\nexport function createGoogleDrivePublicationAttemptTool(input: {\n db: Database;\n objectStorage: ObjectStorage;\n identity: ConnectorActionAttemptIdentity;\n subjectId: string;\n target: GoogleDrivePublicationTarget;\n resolveCredential: (\n input: ResolveConnectionCredentialInput,\n ) => Promise<ResolveConnectionCredentialResult>;\n signal?: AbortSignal;\n ports?: GoogleDrivePublicationPorts;\n}): AttemptToolDefinition {\n const ports = input.ports ?? defaultPorts;\n return {\n identity: {\n serverId: GOOGLE_DRIVE_PUBLICATION_SERVER_ID,\n toolName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,\n },\n modelName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,\n codemodePath: [\"google_drive\", \"publish_file\"],\n title: \"Publish artifact to Google Drive\",\n description:\n \"Publish a completed editable-artifact Office export into the configured Google Drive output folder. First call editable_artifact_export and poll editable_artifact_export_status until it returns a file receipt, then pass that exact receipt here.\",\n inputSchema: {\n type: \"object\",\n properties: {\n title: { type: \"string\", minLength: 1, maxLength: 512 },\n modality: {\n type: \"string\",\n enum: [\"document\", \"spreadsheet\", \"presentation\"],\n },\n file: {\n type: \"object\",\n properties: {\n fileId: { type: \"string\", format: \"uuid\" },\n filename: { type: \"string\", minLength: 1, maxLength: 512 },\n contentType: { type: \"string\", minLength: 1, maxLength: 256 },\n sizeBytes: { type: \"integer\", minimum: 1 },\n sha256: { type: \"string\", pattern: \"^[0-9a-f]{64}$\" },\n artifactId: { type: \"string\", pattern: \"^[0-9a-f]{32}$\" },\n versionId: { type: \"string\", pattern: \"^[0-9a-f]{32}$\" },\n materializationJobId: { type: \"string\", pattern: \"^[0-9a-f]{32}$\" },\n sourceHeadSequence: { type: \"integer\", minimum: 0 },\n sourceStateHash: {\n type: \"string\",\n pattern: \"^sha256:[0-9a-f]{64}$\",\n },\n },\n required: [\n \"fileId\",\n \"filename\",\n \"contentType\",\n \"sizeBytes\",\n \"sha256\",\n \"artifactId\",\n \"versionId\",\n \"materializationJobId\",\n \"sourceHeadSequence\",\n \"sourceStateHash\",\n ],\n additionalProperties: false,\n },\n idempotencyKey: { type: \"string\", minLength: 1, maxLength: 200 },\n },\n required: [\"title\", \"modality\", \"file\", \"idempotencyKey\"],\n additionalProperties: false,\n },\n outputSchema: {\n type: \"object\",\n properties: {\n connectionId: { type: \"string\", format: \"uuid\" },\n providerFileId: { type: \"string\" },\n webViewLink: { type: \"string\", format: \"uri\" },\n mimeType: {\n type: \"string\",\n enum: [\n \"application/vnd.google-apps.document\",\n \"application/vnd.google-apps.spreadsheet\",\n \"application/vnd.google-apps.presentation\",\n ],\n },\n destination: {\n type: \"object\",\n properties: {\n folderId: { type: \"string\" },\n folderName: { type: \"string\" },\n driveId: { type: [\"string\", \"null\"] },\n location: { type: \"string\", enum: [\"my_drive\", \"shared_drive\"] },\n selectedAt: { type: \"string\" },\n },\n required: [\"folderId\", \"folderName\", \"driveId\", \"location\", \"selectedAt\"],\n additionalProperties: false,\n },\n replayed: { type: \"boolean\" },\n },\n required: [\n \"connectionId\",\n \"providerFileId\",\n \"webViewLink\",\n \"mimeType\",\n \"destination\",\n \"replayed\",\n ],\n additionalProperties: false,\n },\n annotations: {\n title: \"Publish artifact to Google Drive\",\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n source: \"mcp\",\n approval: \"policy\",\n execute: async (raw, context) => {\n const request = GoogleDrivePublicationToolInput.parse(raw);\n let providerRequestStarted = false;\n try {\n const receipt = await executeGoogleDrivePublication(\n {\n db: input.db,\n objectStorage: input.objectStorage,\n identity: input.identity,\n subjectId: input.subjectId,\n target: input.target,\n request,\n resolveCredential: input.resolveCredential,\n onProviderRequest: () => {\n providerRequestStarted = true;\n },\n ...((context.signal ?? input.signal) ? { signal: context.signal ?? input.signal } : {}),\n },\n ports,\n );\n return {\n content: [{ type: \"text\", text: JSON.stringify(receipt) }],\n structuredContent: receipt,\n };\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new ConnectorActionExecutionError(\n providerRequestStarted\n ? `Google Drive publication outcome is unknown: a provider request may have been sent before the failure. Verify in Drive before retrying. Cause: ${detail}`\n : `Google Drive publication was not executed: no request reached Google Drive. Cause: ${detail}`,\n providerRequestStarted ? \"uncertain\" : \"not_executed\",\n { cause: error },\n );\n }\n },\n };\n}\n\nexport async function executeGoogleDrivePublication(\n input: {\n db: Database;\n objectStorage: ObjectStorage;\n identity: ConnectorActionAttemptIdentity;\n subjectId: string;\n target: GoogleDrivePublicationTarget;\n request: GoogleDrivePublicationToolInputValue;\n resolveCredential: (\n input: ResolveConnectionCredentialInput,\n ) => Promise<ResolveConnectionCredentialResult>;\n signal?: AbortSignal;\n /** Invoked immediately before the first provider request is sent. */\n onProviderRequest?: () => void;\n },\n ports: Pick<\n GoogleDrivePublicationPorts,\n \"getConnection\" | \"readMaterialization\" | \"requireFile\" | \"fetch\"\n > = defaultPorts,\n): Promise<GoogleDrivePublicationReceiptValue> {\n const request = GoogleDrivePublicationToolInput.parse(input.request);\n const connection = await ports.getConnection(\n input.db,\n input.target.originWorkspaceId,\n input.target.connectionId,\n input.subjectId,\n );\n if (!connection || connection.subjectId !== input.subjectId) {\n throw new Error(\"Google Drive publication connection is unavailable\");\n }\n assertPublicationConnection(input, connection);\n const materialization = await ports.readMaterialization(input.db, {\n scope: {\n accountId: input.identity.accountId,\n workspaceId: input.identity.workspaceId,\n },\n artifactId: request.file.artifactId,\n jobId: request.file.materializationJobId,\n actor: {\n kind: \"agent\",\n subjectId: FIRST_PARTY_MCP_SUBJECT_ID,\n replicaId: publicationActorReplicaId(input.identity),\n sessionId: input.identity.sessionId,\n turnId: input.identity.turnId,\n attemptId: input.identity.attemptId,\n generation: input.identity.executionGeneration,\n },\n });\n assertCanonicalMaterialization(input.identity, request, materialization);\n const expected = expectedExportWorkspaceFile(input.identity.workspaceId, request);\n if (request.file.fileId !== expected.fileId) {\n throw new Error(\"Google Drive publication requires a canonical editable-artifact export file\");\n }\n const sourceFile = await ports.requireFile(\n input.db,\n input.identity.workspaceId,\n request.file.fileId,\n );\n if (\n sourceFile.status !== \"ready\" ||\n sourceFile.id !== expected.fileId ||\n sourceFile.safeFilename !== expected.safeFilename ||\n sourceFile.objectKey !== expected.objectKey ||\n sourceFile.filename !== request.file.filename ||\n sourceFile.contentType !== request.file.contentType ||\n sourceFile.sizeBytes !== request.file.sizeBytes ||\n sourceFile.sha256 !== request.file.sha256\n ) {\n throw new Error(\"Editable artifact export file differs from its canonical receipt\");\n }\n const object = await retryWhileMissing(async () =>\n input.objectStorage.getObjectBytes(sourceFile.objectKey),\n );\n if (!object) throw new Error(\"Editable artifact export object is missing\");\n const bytes = object.bytes;\n if (\n bytes.byteLength !== request.file.sizeBytes ||\n createHash(\"sha256\").update(bytes).digest(\"hex\") !== request.file.sha256\n ) {\n throw new Error(\"Editable artifact export bytes failed verification\");\n }\n const authorizedFetch: FetchLike = async (url, init) => {\n const destinationUrl = url instanceof Request ? url.url : url.toString();\n const credential = await input.resolveCredential({\n workspaceId: input.identity.workspaceId,\n subjectId: input.subjectId,\n serverId: GOOGLE_DRIVE_PUBLICATION_SERVER_ID,\n toolName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,\n connectionRef: {\n providerDomain: GOOGLE_DRIVE_PROVIDER_DOMAIN,\n connectionId: input.target.connectionId,\n kind: \"oauth2\",\n subjectScope: \"subject\",\n scopes: [input.target.credentialScope],\n },\n destinationUrl,\n forceRefresh: false,\n });\n if (credential.status !== \"ok\" || credential.connectionId !== input.target.connectionId) {\n throw new GoogleDrivePublicationAuthorizationError(\n \"Google Drive publication credential is unavailable\",\n );\n }\n const resolvedConnection = await ports.getConnection(\n input.db,\n input.target.originWorkspaceId,\n input.target.connectionId,\n input.subjectId,\n );\n if (!resolvedConnection) {\n throw new GoogleDrivePublicationAuthorizationError(\n \"Google Drive publication authority changed; retry on a new turn\",\n );\n }\n try {\n assertPublicationConnection(input, resolvedConnection);\n } catch (error) {\n throw new GoogleDrivePublicationAuthorizationError(\n error instanceof Error ? error.message : \"Google Drive publication authority changed\",\n );\n }\n if (credential.authorizeProviderRequest) {\n let authorized = false;\n try {\n authorized = await credential.authorizeProviderRequest();\n } catch {\n authorized = false;\n }\n if (!authorized) {\n throw new GoogleDrivePublicationAuthorizationError(\n \"Google Drive publication authority changed; retry on a new turn\",\n );\n }\n }\n const headers = new Headers(credential.headers);\n new Headers(init?.headers).forEach((value, name) => headers.set(name, value));\n // Only a mutating request can create the publication: read-only\n // verify/lookup GETs stay retry-safe, while any later failure after the\n // first mutation is an unknown outcome, never a safe retry.\n const method = (init?.method ?? (url instanceof Request ? url.method : \"GET\")).toUpperCase();\n if (method !== \"GET\" && method !== \"HEAD\") {\n input.onProviderRequest?.();\n }\n return await ports.fetch(url, { ...init, headers });\n };\n return await publishToGoogleDrive({\n workspaceId: input.identity.workspaceId,\n connectionId: input.target.connectionId,\n destination: input.target.destination,\n request,\n bytes,\n fetchImpl: authorizedFetch,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n}\n\nfunction assertPublicationConnection(\n input: { subjectId: string; target: GoogleDrivePublicationTarget },\n connection: NonNullable<Awaited<ReturnType<typeof getConnectionMetadata>>>,\n): void {\n const metadata = GoogleDriveConnectionMetadata.parse(connection.metadata);\n const credentialScope = connection.grantedScopes.includes(GOOGLE_DRIVE_FILE_SCOPE)\n ? GOOGLE_DRIVE_FILE_SCOPE\n : GOOGLE_DRIVE_FULL_SCOPE;\n if (\n input.subjectId !== input.target.ownerSubjectId ||\n connection.id !== input.target.connectionId ||\n connection.workspaceId !== input.target.originWorkspaceId ||\n connection.subjectId !== input.target.ownerSubjectId ||\n connection.providerDomain.toLowerCase() !== GOOGLE_DRIVE_PROVIDER_DOMAIN ||\n connection.kind !== \"oauth2\" ||\n connection.status !== \"active\" ||\n metadata.lifecycle?.state === \"paused\" ||\n (metadata.lifecycle && metadata.lifecycle.state !== \"active\") ||\n !googleDriveScopesAllowCapability(connection.grantedScopes, \"publish_file\") ||\n credentialScope !== input.target.credentialScope ||\n !metadata.outputDestination ||\n !sameDestination(metadata.outputDestination, input.target.destination)\n ) {\n throw new Error(\"Google Drive publication authority changed; retry on a new turn\");\n }\n}\n\nfunction publicationActorReplicaId(identity: ConnectorActionAttemptIdentity): string {\n const value = createHash(\"sha256\")\n .update(\n `google-drive-publication:${identity.sessionId}:${identity.turnId}:${identity.attemptId}:${identity.executionGeneration}`,\n \"utf8\",\n )\n .digest(\"hex\")\n .slice(0, 16);\n return /^0+$/u.test(value) ? `1${value.slice(1)}` : value;\n}\n\nfunction assertCanonicalMaterialization(\n identity: ConnectorActionAttemptIdentity,\n request: GoogleDrivePublicationToolInputValue,\n job: PersistedEditableArtifactMaterializationJob | null,\n): void {\n const format = officeFormat(request.modality, request.file.contentType);\n if (\n !job ||\n job.scope.accountId !== identity.accountId ||\n job.scope.workspaceId !== identity.workspaceId ||\n job.artifactId !== request.file.artifactId ||\n job.id !== request.file.materializationJobId ||\n job.versionId !== request.file.versionId ||\n job.targetHeadSequence !== request.file.sourceHeadSequence ||\n job.stateHash !== request.file.sourceStateHash ||\n job.format !== format ||\n job.state !== \"succeeded\" ||\n !job.result ||\n job.result.byteSize !== request.file.sizeBytes ||\n job.result.mimeType !== request.file.contentType ||\n job.result.contentHash !== `sha256:${request.file.sha256}`\n ) {\n throw new Error(\"Google Drive publication receipt differs from its canonical materialization\");\n }\n}\n\nfunction expectedExportWorkspaceFile(\n workspaceId: string,\n request: GoogleDrivePublicationToolInputValue,\n): { fileId: string; safeFilename: string; objectKey: string } {\n const format = officeFormat(request.modality, request.file.contentType);\n const fileId = deterministicUuid(\n `editable-artifact-export:file:${workspaceId}:${request.file.artifactId}:${request.file.versionId}:${request.file.materializationJobId}`,\n );\n const safeFilename = `artifact-${request.file.artifactId}-${request.file.materializationJobId}.${format}`;\n return {\n fileId,\n safeFilename,\n objectKey: `workspaces/${workspaceId}/files/${fileId}/artifact-exports/${safeFilename}`,\n };\n}\n\nfunction officeFormat(\n modality: GoogleDrivePublicationToolInputValue[\"modality\"],\n contentType: string,\n): \"docx\" | \"xlsx\" | \"pptx\" {\n const expected = {\n document: {\n format: \"docx\" as const,\n contentType: \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n },\n spreadsheet: {\n format: \"xlsx\" as const,\n contentType: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n },\n presentation: {\n format: \"pptx\" as const,\n contentType: \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n },\n }[modality];\n if (contentType !== expected.contentType) {\n throw new Error(\"Google Drive native publication requires the matching Office export format\");\n }\n return expected.format;\n}\n\nfunction deterministicUuid(seed: string): string {\n const bytes = createHash(\"sha256\").update(seed, \"utf8\").digest().subarray(0, 16);\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = bytes.toString(\"hex\");\n const value = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n if (!UUID_PATTERN.test(value)) throw new Error(\"Generated workspace file identity is invalid\");\n return value;\n}\n\nasync function publishToGoogleDrive(input: {\n workspaceId: string;\n connectionId: string;\n destination: GoogleDriveOutputDestination;\n request: GoogleDrivePublicationToolInputValue;\n bytes: Uint8Array;\n fetchImpl: FetchLike;\n signal?: AbortSignal;\n}): Promise<GoogleDrivePublicationReceiptValue> {\n await verifyDestinationAtWriteTime(input);\n const operationKey = publicationOperationKey(input);\n const existing = await findExistingPublication(input, operationKey);\n if (existing) return driveReceipt(input, existing, true);\n\n const mimeType = googleNativeMime(input.request.modality);\n const boundary = `opengeni_${operationKey.slice(0, 32)}`;\n const metadata = JSON.stringify({\n name: input.request.title,\n mimeType,\n parents: [input.destination.folderId],\n appProperties: {\n opengeniPublicationKey: operationKey,\n opengeniArtifactId: input.request.file.artifactId,\n opengeniArtifactVersionId: input.request.file.versionId,\n opengeniSourceSha256: input.request.file.sha256,\n },\n });\n const prefix = new TextEncoder().encode(\n `--${boundary}\\r\\nContent-Type: application/json; charset=UTF-8\\r\\n\\r\\n${metadata}\\r\\n--${boundary}\\r\\nContent-Type: ${input.request.file.contentType}\\r\\n\\r\\n`,\n );\n const suffix = new TextEncoder().encode(`\\r\\n--${boundary}--\\r\\n`);\n const body = new Uint8Array(prefix.byteLength + input.bytes.byteLength + suffix.byteLength);\n body.set(prefix, 0);\n body.set(input.bytes, prefix.byteLength);\n body.set(suffix, prefix.byteLength + input.bytes.byteLength);\n const url = new URL(`${DRIVE_UPLOAD_API}/files`);\n url.searchParams.set(\"uploadType\", \"multipart\");\n url.searchParams.set(\"supportsAllDrives\", \"true\");\n url.searchParams.set(\n \"fields\",\n \"id,name,mimeType,parents,driveId,webViewLink,appProperties,trashed\",\n );\n const created = parseDriveFile(\n await requestJson(input.fetchImpl, url, {\n method: \"POST\",\n headers: {\n accept: \"application/json\",\n \"content-type\": `multipart/related; boundary=${boundary}`,\n \"content-length\": String(body.byteLength),\n },\n body,\n ...(input.signal ? { signal: input.signal } : {}),\n }),\n );\n assertPublicationMatch(input, created, operationKey);\n return driveReceipt(input, created, false);\n}\n\nasync function verifyDestinationAtWriteTime(\n input: Parameters<typeof publishToGoogleDrive>[0],\n): Promise<void> {\n const url = new URL(`${DRIVE_API}/files/${encodeURIComponent(input.destination.folderId)}`);\n url.searchParams.set(\"supportsAllDrives\", \"true\");\n url.searchParams.set(\"fields\", \"id,name,mimeType,driveId,trashed,capabilities(canAddChildren)\");\n const folder = record(await requestJson(input.fetchImpl, url, {}));\n const capabilities = record(folder.capabilities);\n if (\n folder.id !== input.destination.folderId ||\n folder.name !== input.destination.folderName ||\n folder.mimeType !== DRIVE_FOLDER_MIME ||\n folder.trashed === true ||\n capabilities.canAddChildren !== true ||\n (folder.driveId ?? null) !== input.destination.driveId\n ) {\n throw new Error(\"Google Drive output destination changed or is no longer writable\");\n }\n}\n\nasync function findExistingPublication(\n input: Parameters<typeof publishToGoogleDrive>[0],\n operationKey: string,\n): Promise<DriveFile | null> {\n const url = new URL(`${DRIVE_API}/files`);\n url.searchParams.set(\n \"q\",\n `trashed = false and '${driveQuery(input.destination.folderId)}' in parents and appProperties has { key='opengeniPublicationKey' and value='${operationKey}' }`,\n );\n url.searchParams.set(\"spaces\", \"drive\");\n url.searchParams.set(\"supportsAllDrives\", \"true\");\n url.searchParams.set(\"includeItemsFromAllDrives\", \"true\");\n if (input.destination.driveId) {\n url.searchParams.set(\"corpora\", \"drive\");\n url.searchParams.set(\"driveId\", input.destination.driveId);\n } else {\n url.searchParams.set(\"corpora\", \"user\");\n }\n url.searchParams.set(\n \"fields\",\n \"files(id,name,mimeType,parents,driveId,webViewLink,appProperties,trashed)\",\n );\n const payload = record(await requestJson(input.fetchImpl, url, {}));\n const files = Array.isArray(payload.files) ? payload.files.map(parseDriveFile) : [];\n if (files.length > 1) throw new Error(\"Google Drive publication idempotency marker is ambiguous\");\n const existing = files[0] ?? null;\n if (existing) assertPublicationMatch(input, existing, operationKey);\n return existing;\n}\n\ntype DriveFile = {\n id: string;\n name: string;\n mimeType: string;\n parents: string[];\n driveId: string | null;\n webViewLink: string;\n appProperties: Record<string, string>;\n trashed: boolean;\n};\n\nfunction parseDriveFile(value: unknown): DriveFile {\n const item = record(value);\n const appProperties = record(item.appProperties);\n if (\n typeof item.id !== \"string\" ||\n typeof item.name !== \"string\" ||\n typeof item.mimeType !== \"string\" ||\n !Array.isArray(item.parents) ||\n !item.parents.every((entry) => typeof entry === \"string\") ||\n (item.driveId !== undefined && item.driveId !== null && typeof item.driveId !== \"string\") ||\n typeof item.webViewLink !== \"string\" ||\n typeof item.trashed !== \"boolean\"\n ) {\n throw new Error(\"Google Drive returned an invalid publication receipt\");\n }\n return {\n id: item.id,\n name: item.name,\n mimeType: item.mimeType,\n parents: item.parents,\n driveId: (item.driveId as string | null | undefined) ?? null,\n webViewLink: item.webViewLink,\n appProperties: Object.fromEntries(\n Object.entries(appProperties).filter(\n (entry): entry is [string, string] => typeof entry[1] === \"string\",\n ),\n ),\n trashed: item.trashed,\n };\n}\n\nfunction assertPublicationMatch(\n input: Parameters<typeof publishToGoogleDrive>[0],\n file: DriveFile,\n operationKey: string,\n): void {\n if (\n file.trashed ||\n file.name !== input.request.title ||\n file.mimeType !== googleNativeMime(input.request.modality) ||\n file.parents.length !== 1 ||\n file.parents[0] !== input.destination.folderId ||\n file.driveId !== input.destination.driveId ||\n file.appProperties.opengeniPublicationKey !== operationKey ||\n file.appProperties.opengeniArtifactId !== input.request.file.artifactId ||\n file.appProperties.opengeniArtifactVersionId !== input.request.file.versionId ||\n file.appProperties.opengeniSourceSha256 !== input.request.file.sha256\n ) {\n throw new Error(\"Google Drive publication idempotency key conflicts with another file\");\n }\n}\n\nfunction driveReceipt(\n input: Parameters<typeof publishToGoogleDrive>[0],\n file: DriveFile,\n replayed: boolean,\n): GoogleDrivePublicationReceiptValue {\n return GoogleDrivePublicationReceipt.parse({\n connectionId: input.connectionId,\n providerFileId: file.id,\n webViewLink: file.webViewLink,\n mimeType: googleNativeMime(input.request.modality),\n destination: input.destination,\n replayed,\n });\n}\n\nfunction publicationOperationKey(input: Parameters<typeof publishToGoogleDrive>[0]): string {\n return createHash(\"sha256\")\n .update(\n JSON.stringify({\n workspaceId: input.workspaceId,\n connectionId: input.connectionId,\n destination: input.destination,\n artifactId: input.request.file.artifactId,\n versionId: input.request.file.versionId,\n materializationJobId: input.request.file.materializationJobId,\n sourceSha256: input.request.file.sha256,\n idempotencyKey: input.request.idempotencyKey,\n }),\n \"utf8\",\n )\n .digest(\"hex\");\n}\n\nfunction googleNativeMime(\n modality: GoogleDrivePublicationToolInputValue[\"modality\"],\n): GoogleDrivePublicationReceiptValue[\"mimeType\"] {\n switch (modality) {\n case \"document\":\n return \"application/vnd.google-apps.document\";\n case \"spreadsheet\":\n return \"application/vnd.google-apps.spreadsheet\";\n case \"presentation\":\n return \"application/vnd.google-apps.presentation\";\n }\n}\n\nfunction sameDestination(\n left: GoogleDriveOutputDestination,\n right: GoogleDriveOutputDestination,\n): boolean {\n return (\n left.folderId === right.folderId &&\n left.folderName === right.folderName &&\n left.driveId === right.driveId &&\n left.location === right.location &&\n left.selectedAt === right.selectedAt\n );\n}\n\nasync function requestJson(fetchImpl: FetchLike, url: URL, init: RequestInit): Promise<unknown> {\n let response: Response;\n try {\n response = await fetchImpl(url, {\n ...init,\n redirect: \"error\",\n signal: init.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch (error) {\n if (error instanceof GoogleDrivePublicationAuthorizationError) throw error;\n throw new Error(\"Google Drive publication transport failed\", { cause: error });\n }\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n throw new Error(`Google Drive publication request failed with status ${response.status}`);\n }\n return await readResponseJsonBounded(response, RESPONSE_MAX_BYTES, \"Google Drive publication\");\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction driveQuery(value: string): string {\n return value.replace(/\\\\/gu, \"\\\\\\\\\").replace(/'/gu, \"\\\\'\");\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { ConnectionCredentialsPort } from \"@opengeni/contracts\";\nimport {\n buildConnectionTokenResolver,\n buildHostConnectionTokenResolver,\n getSessionTurnForAttempt,\n authorizeDirectHostMcpUse,\n resolveAcceptedConnectionUse,\n sessionTenancyProductActivated,\n type Database,\n type ResolveConnectionCredentialInput,\n type ResolveConnectionCredentialResult,\n type SessionTurnForExecution,\n} from \"@opengeni/db\";\nimport { recordTenancyCompatibilityLaneUse, type Observability } from \"@opengeni/observability\";\n\nconst OPENGENI_CONNECTION_ID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\nexport function connectionTokenResolverForTurn(input: {\n db: Database;\n settings: Settings;\n connectionCredentials?: ConnectionCredentialsPort | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n rootSessionId: string;\n attemptId: string;\n turn: SessionTurnForExecution;\n authorizeAcceptedUse?: typeof resolveAcceptedConnectionUse;\n /** Test seam; production always reads the canonical active-attempt projection. */\n getHostTurnForAttempt?: typeof getSessionTurnForAttempt;\n /** Test seam for the activation fence on pre-snapshot workspace refs. */\n isSessionTenancyProductActivated?: typeof sessionTenancyProductActivated;\n /** Optional; used only for content-free compatibility-lane counters. */\n observability?: Observability | null | undefined;\n}): (request: ResolveConnectionCredentialInput) => Promise<ResolveConnectionCredentialResult> {\n const hostResolver = input.connectionCredentials?.mcpCredentials;\n const readHostTurn = input.getHostTurnForAttempt ?? getSessionTurnForAttempt;\n const hostDb = input.db;\n const nativeResolver = buildConnectionTokenResolver(input.db, input.settings);\n const configuredResolver = hostResolver\n ? buildHostConnectionTokenResolver(hostResolver, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n rootSessionId: input.rootSessionId,\n turnId: input.turn.id,\n attemptId: input.attemptId,\n executionGeneration: input.turn.executionGeneration,\n initiator: input.turn.initiator,\n initiatorContext: input.turn.initiatorContext,\n surface: \"model\",\n // Only immutable captured direct-turn authority is currently supported.\n // Direct, scheduled and exact causal/child snapshots are validated;\n // no authority follows merely from a binding or creator identity.\n authorizeDurableBinding: (request) => authorizeDirectHostMcpUse(hostDb, request),\n authorizeExecution: async (request) => {\n // Native UUID references already pass the accepted-use boundary below.\n // Legacy opaque host IDs retain their compatibility path, but not a\n // right to execute after their accepted attempt has stopped.\n if (\n request.connectionRef.authoritySource !== \"host\" &&\n (!request.connectionRef.connectionId ||\n OPENGENI_CONNECTION_ID_PATTERN.test(request.connectionRef.connectionId))\n )\n return true;\n if (!request.attemptId) return false;\n const current = await readHostTurn(\n hostDb,\n request.workspaceId,\n request.sessionId,\n request.attemptId,\n );\n return (\n current !== null &&\n current.id === request.turnId &&\n current.executionGeneration === request.executionGeneration\n );\n },\n })\n : nativeResolver;\n const baseResolver = (request: ResolveConnectionCredentialInput) =>\n input.connectionCredentials?.mcpAuthoritySource === \"host\" &&\n request.connectionRef.authoritySource !== \"host\"\n ? nativeResolver(request)\n : configuredResolver(request);\n return async (request) => {\n // Host-owned refs carry explicit provenance because their opaque ids may\n // themselves be valid UUIDs. They never enter OpenGeni's native connection\n // authority or PostgreSQL UUID lookup; the bound host authorizes the exact\n // immutable turn context on every credential request.\n if (request.connectionRef.authoritySource === \"host\") {\n if (hostResolver) return await baseResolver(request);\n return {\n status: \"auth_needed\",\n reason: \"unsupported_auth\",\n providerDomain: request.connectionRef.providerDomain,\n authoritySource: \"host\",\n ...(request.connectionRef.provider ? { provider: request.connectionRef.provider } : {}),\n ...(request.connectionRef.connectionId\n ? { connectionId: request.connectionRef.connectionId }\n : {}),\n ...(request.connectionRef.scopes ? { scopes: request.connectionRef.scopes } : {}),\n ...(request.connectionRef.resource ? { resource: request.connectionRef.resource } : {}),\n ...(request.connectionRef.selectedResources\n ? { selectedResources: request.connectionRef.selectedResources }\n : {}),\n };\n }\n // Before explicit provenance existed, the public embedding contract let a\n // bound host use any non-UUID opaque id. Preserve those frozen/stored refs\n // during upgrades while keeping every UUID-shaped omission on OpenGeni's\n // native accepted-use authority. New host refs must carry authoritySource\n // so UUID-shaped host ids are unambiguous.\n if (\n hostResolver &&\n input.connectionCredentials?.mcpAuthoritySource !== \"host\" &&\n request.connectionRef.connectionId &&\n !OPENGENI_CONNECTION_ID_PATTERN.test(request.connectionRef.connectionId)\n ) {\n try {\n return await baseResolver(request);\n } catch {\n return {\n status: \"auth_needed\",\n reason: \"refresh_failed\",\n providerDomain: request.connectionRef.providerDomain,\n authoritySource: \"host\",\n ...(request.connectionRef.provider ? { provider: request.connectionRef.provider } : {}),\n connectionId: request.connectionRef.connectionId,\n ...(request.connectionRef.scopes ? { scopes: request.connectionRef.scopes } : {}),\n ...(request.connectionRef.resource ? { resource: request.connectionRef.resource } : {}),\n ...(request.connectionRef.selectedResources\n ? { selectedResources: request.connectionRef.selectedResources }\n : {}),\n };\n }\n }\n const acceptedDelegation = input.turn.personalConnectionDelegations.find(\n (delegation) =>\n (delegation.connectionType === undefined ||\n delegation.connectionType === \"mcp\" ||\n (delegation.connectionType === \"github_personal\" &&\n delegation.serverId === \"github:personal\" &&\n request.serverId === \"github:personal\" &&\n request.connectionRef.provider === \"github\" &&\n request.connectionRef.kind === \"oauth2\" &&\n request.connectionRef.providerDomain === \"github.com\" &&\n request.credentialTarget === \"http_api\" &&\n isGitHubApiDestination(request.destinationUrl))) &&\n delegation.serverId === request.serverId &&\n delegation.connectionId === request.connectionRef.connectionId,\n );\n const subjectScope: \"subject\" | \"workspace\" =\n request.connectionRef.subjectScope === \"subject\" ? \"subject\" : \"workspace\";\n // Every subject-scoped request must match an exact connection frozen on the\n // accepted turn. This also hard-fences pre-cutover common-user turns that\n // lack a userDelegation: the DB resolver denies those rows because only a\n // true legacy_user connection is eligible for bounded compatibility.\n if (\n subjectScope === \"subject\" &&\n (!acceptedDelegation || !request.connectionRef.connectionId)\n ) {\n return {\n status: \"auth_needed\",\n reason: \"personal_authority_unavailable\",\n providerDomain: request.connectionRef.providerDomain,\n ...(request.connectionRef.provider ? { provider: request.connectionRef.provider } : {}),\n };\n }\n // Workspace-scope requests now run through the same accepted-use authority\n // (migration 0279): the exact workspace-owned connection is revalidated\n // inside the canonical lifecycle fences and every use leaves an idempotent\n // audit fact. A ref with no connection id is the bounded pre-snapshot\n // legacy path - it cannot be authorized by exact identity, so it keeps the\n // unprivileged resolution the old short-circuit used.\n if (subjectScope === \"workspace\" && !request.connectionRef.connectionId) {\n if (\n await (input.isSessionTenancyProductActivated ?? sessionTenancyProductActivated)(\n input.db,\n input.workspaceId,\n )\n ) {\n return {\n status: \"auth_needed\",\n reason: \"missing_connection\",\n providerDomain: request.connectionRef.providerDomain,\n ...(request.connectionRef.provider ? { provider: request.connectionRef.provider } : {}),\n };\n }\n // This lane writes no `connection_use_audit_facts` row, so this counter is\n // the only evidence it was taken. Lane name only - never the server,\n // provider domain, connection, or subject.\n recordTenancyCompatibilityLaneUse(input.observability, \"connection_pre_snapshot_ref\");\n return await baseResolver(request);\n }\n const credentialUseContext = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turn.id,\n attemptId: input.attemptId,\n executionGeneration: input.turn.executionGeneration,\n physicalRequestId: crypto.randomUUID(),\n usePhase: \"credential_resolution\" as const,\n };\n const authorityBinding = {\n serverId: request.serverId,\n // Both lane guards above require an exact connection id at this point.\n ...(request.connectionRef.connectionId\n ? { connectionId: request.connectionRef.connectionId }\n : {}),\n providerDomain: request.connectionRef.providerDomain,\n ...(request.connectionRef.kind ? { connectionKind: request.connectionRef.kind } : {}),\n subjectScope,\n ...(subjectScope === \"subject\" && request.subjectId\n ? { ownerSubjectId: request.subjectId }\n : {}),\n };\n const authorize = async (\n context: Omit<typeof credentialUseContext, \"usePhase\"> & {\n usePhase: \"credential_resolution\" | \"provider_request\";\n },\n ) =>\n await (input.authorizeAcceptedUse ?? resolveAcceptedConnectionUse)(input.db, {\n ...context,\n ...authorityBinding,\n });\n const withProviderRequestAuthorization = (\n result: ResolveConnectionCredentialResult,\n ): ResolveConnectionCredentialResult => {\n if (result.status !== \"ok\") return result;\n return {\n ...result,\n authorizeProviderRequest: async () => {\n const authorization = await authorize({\n ...credentialUseContext,\n physicalRequestId: crypto.randomUUID(),\n usePhase: \"provider_request\",\n });\n return authorization.status === \"authorized\";\n },\n };\n };\n // One place records the `legacy_user` lane for both resolution paths: the\n // scope comes back on the resolver result when the DB resolver authorized\n // internally, and on the resolution itself when the host resolver did.\n const recordAuthorizedScope = (scope: \"workspace\" | \"user\" | \"legacy_user\" | undefined) => {\n if (scope === \"legacy_user\") {\n recordTenancyCompatibilityLaneUse(input.observability, \"connection_legacy_user\");\n }\n };\n if (!hostResolver) {\n const result = await baseResolver({\n ...request,\n connectionUseContext: credentialUseContext,\n });\n if (result.status === \"ok\") recordAuthorizedScope(result.connectionUseAttribution?.scope);\n return withProviderRequestAuthorization(result);\n }\n const authorization = await authorize(credentialUseContext);\n if (authorization.status === \"denied\") {\n return {\n status: \"auth_needed\",\n reason:\n request.connectionRef.subjectScope === \"subject\"\n ? \"personal_authority_unavailable\"\n : \"missing_connection\",\n providerDomain: request.connectionRef.providerDomain,\n ...(request.connectionRef.provider ? { provider: request.connectionRef.provider } : {}),\n };\n }\n recordAuthorizedScope(authorization.attribution.scope);\n const result = await baseResolver({\n ...request,\n connectionUseContext: credentialUseContext,\n connectionUseAuthority: authorization.attribution,\n connectionRef: {\n ...request.connectionRef,\n connectionId: authorization.attribution.connectionId,\n kind: authorization.connectionKind,\n subjectScope: authorization.attribution.scope === \"workspace\" ? \"workspace\" : \"subject\",\n },\n ...(authorization.attribution.ownerSubjectId\n ? { subjectId: authorization.attribution.ownerSubjectId }\n : {}),\n });\n return withProviderRequestAuthorization(result);\n };\n}\n\nfunction isGitHubApiDestination(value: string): boolean {\n try {\n const url = new URL(value);\n return (\n url.protocol === \"https:\" &&\n url.origin === \"https://api.github.com\" &&\n url.username === \"\" &&\n url.password === \"\" &&\n url.hash === \"\"\n );\n } catch {\n return false;\n }\n}\n","import type { Settings } from \"@opengeni/config\";\nimport {\n mergeToolRefs,\n type McpPersonalConnectionDelegation,\n type ResourceRef,\n type ToolRef,\n} from \"@opengeni/contracts\";\nimport {\n isPersonalGitHubConnection,\n PersonalGitHubConnectionMetadata,\n} from \"@opengeni/contracts/personal-github\";\nimport { personalGitHubRepositoryResources } from \"@opengeni/core\";\nimport {\n getConnectionMetadata,\n getPersonalGitHubRepositorySelectionState,\n hasAuditableGitHubInstallationAuthority,\n listGitHubInstallationAccessForWorkspace,\n resolveAcceptedConnectionUse,\n type Database,\n type ResolveConnectionCredentialInput,\n type ResolveConnectionCredentialResult,\n type SessionTurnForExecution,\n} from \"@opengeni/db\";\nimport { createGitHubAppInstallationTokenWithExpiry, githubAppBotIdentity } from \"@opengeni/github\";\nimport {\n type AttemptConnectorActionBinding,\n ConnectorActionBindingRejectedError,\n type LocalMcpServerRegistration,\n prefixedMcpToolName,\n} from \"@opengeni/runtime\";\nimport {\n GITHUB_REST_API_ORIGIN,\n GITHUB_REST_MCP_APP_SERVER_ID,\n GITHUB_REST_MCP_PERSONAL_SERVER_ID,\n GITHUB_REST_READ_TOOL_NAMES,\n GITHUB_REST_TOOL_NAMES,\n GitHubRestAuthorityError,\n githubRestConnectorActionOutcome,\n GitHubRestMcpServer,\n type GitHubRestRepository,\n} from \"@opengeni/runtime/github-rest-mcp\";\n\nconst PERSONAL_GITHUB_DELEGATION_SERVER_ID = \"github:personal\";\nconst INTERNAL_GITHUB_MCP_TIMEOUT_MS = 20_000;\n\ntype ResolveCredential = (\n request: ResolveConnectionCredentialInput,\n) => Promise<ResolveConnectionCredentialResult>;\n\nexport type GitHubRestMcpRuntime = {\n settings: Settings;\n tools: ToolRef[];\n localMcpServers: LocalMcpServerRegistration[];\n connectorBindings: AttemptConnectorActionBinding[];\n};\n\nexport async function buildGitHubRestMcpForTurn(input: {\n db: Database;\n settings: Settings;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n turn: SessionTurnForExecution;\n resources: ResourceRef[];\n tools: ToolRef[];\n resolveCredential: ResolveCredential;\n}): Promise<GitHubRestMcpRuntime> {\n if (!input.settings.githubRestMcpEnabled) {\n return {\n settings: input.settings,\n tools: input.tools,\n localMcpServers: [],\n connectorBindings: [],\n };\n }\n\n const appRepositories = appRepositoryAuthority(input.resources);\n const personalRepositories = personalRepositoryAuthority(\n input.resources,\n input.turn.personalConnectionDelegations,\n );\n if (appRepositories.length === 0 && personalRepositories.length === 0) {\n return {\n settings: input.settings,\n tools: input.tools,\n localMcpServers: [],\n connectorBindings: [],\n };\n }\n const configuredIds = new Set(input.settings.mcpServers.map((server) => server.id));\n for (const id of [GITHUB_REST_MCP_APP_SERVER_ID, GITHUB_REST_MCP_PERSONAL_SERVER_ID]) {\n if (configuredIds.has(id)) {\n throw new GitHubRestAuthorityError(\n `Reserved GitHub MCP server id is already configured: ${id}`,\n );\n }\n }\n\n const configs: Settings[\"mcpServers\"] = [];\n const localMcpServers: LocalMcpServerRegistration[] = [];\n const toolRefs: ToolRef[] = [];\n const connectorBindings: AttemptConnectorActionBinding[] = [];\n\n if (appRepositories.length > 0) {\n const appResolver = workspaceAppAuthorityResolver(input, appRepositories);\n localMcpServers.push({\n id: GITHUB_REST_MCP_APP_SERVER_ID,\n server: new GitHubRestMcpServer({\n serverId: GITHUB_REST_MCP_APP_SERVER_ID,\n authorityKind: \"workspace_app\",\n repositories: appRepositories,\n resolveAuthority: appResolver,\n }),\n });\n configs.push(internalMcpConfig(GITHUB_REST_MCP_APP_SERVER_ID, \"GitHub — OpenGeni bot\"));\n toolRefs.push({ kind: \"mcp\", id: GITHUB_REST_MCP_APP_SERVER_ID });\n connectorBindings.push(\n ...githubConnectorBindings(GITHUB_REST_MCP_APP_SERVER_ID, appRepositories),\n );\n }\n\n if (personalRepositories.length > 0) {\n localMcpServers.push({\n id: GITHUB_REST_MCP_PERSONAL_SERVER_ID,\n server: new GitHubRestMcpServer({\n serverId: GITHUB_REST_MCP_PERSONAL_SERVER_ID,\n authorityKind: \"personal_oauth\",\n repositories: personalRepositories,\n resolveAuthority: personalAuthorityResolver(input),\n }),\n });\n configs.push(internalMcpConfig(GITHUB_REST_MCP_PERSONAL_SERVER_ID, \"GitHub — My account\"));\n toolRefs.push({ kind: \"mcp\", id: GITHUB_REST_MCP_PERSONAL_SERVER_ID });\n connectorBindings.push(\n ...githubConnectorBindings(GITHUB_REST_MCP_PERSONAL_SERVER_ID, personalRepositories),\n );\n }\n\n return {\n settings: {\n ...input.settings,\n mcpServers: [...input.settings.mcpServers, ...configs],\n },\n tools: mergeToolRefs(input.tools, toolRefs),\n localMcpServers,\n connectorBindings,\n };\n}\n\nfunction internalMcpConfig(id: string, name: string): Settings[\"mcpServers\"][number] {\n return {\n id,\n name,\n url: `${GITHUB_REST_API_ORIGIN}/`,\n allowedTools: [...GITHUB_REST_TOOL_NAMES],\n timeoutMs: INTERNAL_GITHUB_MCP_TIMEOUT_MS,\n cacheToolsList: true,\n };\n}\n\nfunction appRepositoryAuthority(resources: ResourceRef[]): GitHubRestRepository[] {\n return resources.flatMap((resource) => {\n if (resource.kind !== \"repository\" || resource.connectionType === \"github_personal\") {\n return [];\n }\n const hasAppIdentity =\n resource.githubInstallationId !== undefined ||\n resource.installationId !== undefined ||\n resource.githubRepositoryId !== undefined;\n if (!hasAppIdentity) return [];\n if (resource.provider !== undefined && resource.provider !== \"github\") {\n throw new GitHubRestAuthorityError(\"GitHub App repository provider is invalid\");\n }\n const installationId = positiveSafeInteger(\n resource.githubInstallationId ?? resource.installationId,\n );\n const repositoryId = positiveSafeInteger(resource.githubRepositoryId ?? resource.repositoryId);\n const fullName = canonicalGitHubFullName(resource.uri);\n if (!installationId || !repositoryId) {\n throw new GitHubRestAuthorityError(\"GitHub App repository authority is incomplete\");\n }\n if (!fullName) {\n throw new GitHubRestAuthorityError(\"GitHub App repository URL is invalid\");\n }\n return [\n {\n repositoryId: String(repositoryId),\n fullName,\n canonicalUrl: `https://github.com/${fullName}`,\n defaultRef: resource.ref,\n access: resource.access === \"read\" ? \"read\" : \"write\",\n authorityKind: \"workspace_app\" as const,\n connectionId: `github-app:${installationId}`,\n },\n ];\n });\n}\n\nfunction personalRepositoryAuthority(\n resources: ResourceRef[],\n delegations: McpPersonalConnectionDelegation[],\n): GitHubRestRepository[] {\n const personalResources = personalGitHubRepositoryResources(resources);\n if (personalResources.length === 0) return [];\n const delegation = exactPersonalDelegation(delegations);\n const snapshot = delegation.personalGitHubRepositorySelection!;\n const acceptedById = new Map(\n snapshot.repositories.map((repository) => [repository.repositoryId, repository]),\n );\n return personalResources.map((resource) => {\n const accepted = acceptedById.get(resource.repositoryId);\n const fullName = canonicalGitHubFullName(resource.uri);\n if (\n !accepted ||\n !fullName ||\n accepted.fullName !== fullName ||\n accepted.canonicalUrl !== resource.uri ||\n accepted.ref !== resource.ref ||\n accepted.access !== resource.access\n ) {\n throw new GitHubRestAuthorityError(\n \"Personal GitHub repository does not match the accepted selection\",\n );\n }\n return {\n repositoryId: resource.repositoryId,\n fullName,\n canonicalUrl: resource.uri,\n defaultRef: resource.ref,\n access: resource.access,\n authorityKind: \"personal_oauth\" as const,\n connectionId: delegation.connectionId,\n };\n });\n}\n\nfunction workspaceAppAuthorityResolver(\n input: {\n db: Database;\n settings: Settings;\n accountId: string;\n workspaceId: string;\n },\n repositories: GitHubRestRepository[],\n): ConstructorParameters<typeof GitHubRestMcpServer>[0][\"resolveAuthority\"] {\n const installationByRepository = new Map(\n repositories.map((repository) => [\n repositoryKey(repository),\n Number(repository.connectionId.slice(\"github-app:\".length)),\n ]),\n );\n const tokenCache = new Map<string, { token: string; expiresAt: number }>();\n const validate = async (repository: GitHubRestRepository): Promise<number> => {\n const installationId = installationByRepository.get(repositoryKey(repository));\n const repositoryId = Number(repository.repositoryId);\n if (!installationId || !Number.isSafeInteger(repositoryId)) {\n throw new GitHubRestAuthorityError(\"GitHub App repository binding changed\");\n }\n const installations = await listGitHubInstallationAccessForWorkspace(\n input.db,\n input.workspaceId,\n );\n const installation = installations.find(\n (candidate) => candidate.installationId === installationId,\n );\n if (\n !installation ||\n installation.accountId !== input.accountId ||\n !hasAuditableGitHubInstallationAuthority(installation) ||\n !installation.repositoryIds.includes(repositoryId)\n ) {\n throw new GitHubRestAuthorityError(\"GitHub App repository authority is no longer current\");\n }\n return installationId;\n };\n return async ({ toolName, repository, forceRefresh }) => {\n const installationId = await validate(repository);\n const repositoryId = Number(repository.repositoryId);\n const identity = githubAppBotIdentity(input.settings);\n if (!identity) throw new GitHubRestAuthorityError(\"GitHub App identity is unavailable\");\n if (toolName === \"repositories_list\") {\n return {\n headers: {},\n connectionId: repository.connectionId,\n actor: { kind: \"workspace_app\", login: identity.name },\n authorizeProviderRequest: async () => {\n try {\n await validate(repository);\n return true;\n } catch {\n return false;\n }\n },\n };\n }\n const cacheKey = repositoryKey(repository);\n let cached = tokenCache.get(cacheKey);\n if (forceRefresh || !cached || cached.expiresAt <= Date.now() + 60_000) {\n const minted = await createGitHubAppInstallationTokenWithExpiry(input.settings, {\n installationId,\n repositoryIds: [repositoryId],\n });\n const parsedExpiry = minted.expiresAt ? Date.parse(minted.expiresAt) : Number.NaN;\n cached = {\n token: minted.token,\n // An absent or malformed expiry must shorten the cache lifetime rather\n // than turning NaN into an indefinitely reusable credential.\n expiresAt: Number.isFinite(parsedExpiry) ? parsedExpiry : Date.now() + 5 * 60_000,\n };\n tokenCache.set(cacheKey, cached);\n }\n return {\n headers: { authorization: `Bearer ${cached.token}` },\n connectionId: repository.connectionId,\n actor: { kind: \"workspace_app\", login: identity.name },\n authorizeProviderRequest: async () => {\n try {\n await validate(repository);\n return true;\n } catch {\n return false;\n }\n },\n };\n };\n}\n\nfunction personalAuthorityResolver(input: {\n db: Database;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n turn: SessionTurnForExecution;\n resolveCredential: ResolveCredential;\n}): ConstructorParameters<typeof GitHubRestMcpServer>[0][\"resolveAuthority\"] {\n return async ({ toolName, destinationUrl, repository, forceRefresh }) => {\n const current = await validatePersonalRepository(\n input,\n repository,\n toolName === \"repositories_list\",\n );\n if (toolName === \"repositories_list\") {\n return {\n headers: {},\n connectionId: repository.connectionId,\n actor: { kind: \"personal_oauth\", login: current.login },\n authorizeProviderRequest: async () => {\n try {\n await validatePersonalRepository(input, repository, true);\n return true;\n } catch {\n return false;\n }\n },\n };\n }\n const resolution = await input.resolveCredential({\n workspaceId: input.workspaceId,\n subjectId: current.delegation.ownerSubjectId,\n serverId: PERSONAL_GITHUB_DELEGATION_SERVER_ID,\n toolName,\n connectionRef: {\n connectionId: current.delegation.connectionId,\n provider: \"github\",\n providerDomain: \"github.com\",\n kind: \"oauth2\",\n scopes: [\"repo\"],\n subjectScope: \"subject\",\n },\n destinationUrl,\n credentialTarget: \"http_api\",\n forceRefresh,\n });\n if (resolution.status !== \"ok\" || resolution.connectionId !== repository.connectionId) {\n throw new GitHubRestAuthorityError(\"Personal GitHub credential is unavailable\");\n }\n return {\n headers: githubAuthorizationHeaders(resolution.headers),\n connectionId: resolution.connectionId,\n actor: { kind: \"personal_oauth\", login: current.login },\n authorizeProviderRequest: async () => {\n if (resolution.authorizeProviderRequest && !(await resolution.authorizeProviderRequest())) {\n return false;\n }\n try {\n await validatePersonalRepository(input, repository, false);\n return true;\n } catch {\n return false;\n }\n },\n };\n };\n}\n\nasync function validatePersonalRepository(\n input: {\n db: Database;\n accountId: string;\n workspaceId: string;\n turn: SessionTurnForExecution;\n sessionId: string;\n attemptId: string;\n },\n repository: GitHubRestRepository,\n validateAcceptedUse: boolean,\n) {\n const delegation = exactPersonalDelegation(input.turn.personalConnectionDelegations);\n if (delegation.connectionId !== repository.connectionId || !delegation.originWorkspaceId) {\n throw new GitHubRestAuthorityError(\"Personal GitHub delegation changed\");\n }\n const snapshot = delegation.personalGitHubRepositorySelection!;\n const accepted = snapshot.repositories.find(\n (candidate) => candidate.repositoryId === repository.repositoryId,\n );\n if (\n !accepted ||\n accepted.fullName !== repository.fullName ||\n accepted.canonicalUrl !== repository.canonicalUrl ||\n accepted.ref !== repository.defaultRef ||\n accepted.access !== repository.access\n ) {\n throw new GitHubRestAuthorityError(\"Personal GitHub repository exceeds accepted authority\");\n }\n const acceptedUse = validateAcceptedUse\n ? await resolveAcceptedConnectionUse(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turn.id,\n attemptId: input.attemptId,\n executionGeneration: input.turn.executionGeneration,\n physicalRequestId: crypto.randomUUID(),\n usePhase: \"credential_resolution\",\n serverId: PERSONAL_GITHUB_DELEGATION_SERVER_ID,\n connectionId: delegation.connectionId,\n providerDomain: \"github.com\",\n connectionKind: \"oauth2\",\n subjectScope: \"subject\",\n ownerSubjectId: delegation.ownerSubjectId,\n })\n : null;\n if (\n acceptedUse &&\n (acceptedUse.status !== \"authorized\" ||\n acceptedUse.originWorkspaceId !== delegation.originWorkspaceId ||\n acceptedUse.attribution.connectionId !== delegation.connectionId ||\n acceptedUse.attribution.connectionGeneration !== snapshot.connectionAuthorityGeneration ||\n acceptedUse.attribution.ownerSubjectId !== delegation.ownerSubjectId)\n ) {\n throw new GitHubRestAuthorityError(\"Personal GitHub connection authority changed\");\n }\n const connection = await getConnectionMetadata(\n input.db,\n delegation.originWorkspaceId,\n delegation.connectionId,\n delegation.ownerSubjectId,\n );\n if (\n !connection ||\n connection.accountId !== input.accountId ||\n connection.workspaceId !== delegation.originWorkspaceId ||\n connection.subjectId !== delegation.ownerSubjectId ||\n connection.status !== \"active\" ||\n connection.grantedScopes.length !== 1 ||\n connection.grantedScopes[0] !== \"repo\" ||\n !isPersonalGitHubConnection(connection)\n ) {\n throw new GitHubRestAuthorityError(\"Personal GitHub connection is unavailable\");\n }\n const metadata = PersonalGitHubConnectionMetadata.parse(connection.metadata);\n const current = await getPersonalGitHubRepositorySelectionState(input.db, {\n accountId: input.accountId,\n originWorkspaceId: delegation.originWorkspaceId,\n subjectId: delegation.ownerSubjectId,\n connectionId: delegation.connectionId,\n });\n const currentRepository = current?.repositories.find(\n (candidate) => candidate.repositoryId === repository.repositoryId,\n );\n if (\n !current ||\n !currentRepository ||\n current.connectionAuthorityGeneration !== snapshot.connectionAuthorityGeneration ||\n current.selectionGeneration !== snapshot.selectionGeneration ||\n current.credentialBindingId !== snapshot.credentialBindingId ||\n current.credentialBindingId !== metadata.credentialBindingId ||\n current.providerPrincipalId !== metadata.providerPrincipalId ||\n metadata.githubUserId !== metadata.providerPrincipalId ||\n currentRepository.fullName !== accepted.fullName ||\n currentRepository.canonicalUrl !== accepted.canonicalUrl ||\n currentRepository.selectionGeneration !== accepted.selectionGeneration ||\n currentRepository.disabled ||\n !canRead(currentRepository.permissions) ||\n (accepted.access === \"write\" &&\n (currentRepository.selectedAccess !== \"write\" ||\n currentRepository.archived ||\n !canWrite(currentRepository.permissions)))\n ) {\n throw new GitHubRestAuthorityError(\"Personal GitHub repository authority changed\");\n }\n return { delegation, login: metadata.githubLogin };\n}\n\nfunction exactPersonalDelegation(\n delegations: McpPersonalConnectionDelegation[],\n): McpPersonalConnectionDelegation {\n const matches = delegations.filter(\n (delegation) =>\n delegation.serverId === PERSONAL_GITHUB_DELEGATION_SERVER_ID &&\n delegation.connectionType === \"github_personal\",\n );\n const delegation = matches[0];\n if (\n matches.length !== 1 ||\n !delegation ||\n delegation.providerDomain !== \"github.com\" ||\n delegation.kind !== \"oauth2\" ||\n !delegation.originWorkspaceId ||\n !delegation.userDelegation ||\n !delegation.personalGitHubRepositorySelection\n ) {\n throw new GitHubRestAuthorityError(\"Personal GitHub delegation is unavailable\");\n }\n return delegation;\n}\n\nfunction githubConnectorBindings(\n serverId: string,\n repositories: GitHubRestRepository[],\n): AttemptConnectorActionBinding[] {\n const byName = new Map(\n repositories.map((repository) => [repository.fullName.toLowerCase(), repository]),\n );\n return GITHUB_REST_TOOL_NAMES.filter((toolName) => toolName !== \"repositories_list\").map(\n (toolName) => ({\n modelName: prefixedMcpToolName(serverId, toolName),\n resultOutcome: githubRestConnectorActionOutcome,\n call: (approvalId, arguments_) => {\n const args = objectRecord(arguments_);\n const repository =\n typeof args.repository === \"string\" ? byName.get(args.repository.toLowerCase()) : null;\n if (!repository) {\n throw new ConnectorActionBindingRejectedError(\n \"GitHub action repository does not match an accepted resource\",\n );\n }\n return {\n approvalId,\n connectionId: repository.connectionId,\n serverId,\n toolName,\n arguments: arguments_,\n ...(GITHUB_REST_READ_TOOL_NAMES.includes(\n toolName as (typeof GITHUB_REST_READ_TOOL_NAMES)[number],\n )\n ? {}\n : { approvalMode: \"connector_write\" as const }),\n };\n },\n }),\n );\n}\n\nfunction canonicalGitHubFullName(uri: string): string | null {\n try {\n const url = new URL(uri);\n const clonePath = url.pathname.replace(/^\\/+|\\/+$/gu, \"\");\n const path = clonePath.endsWith(\".git\") ? clonePath.slice(0, -4) : clonePath;\n if (\n url.protocol !== \"https:\" ||\n url.hostname !== \"github.com\" ||\n url.port ||\n url.username ||\n url.password ||\n url.search ||\n url.hash ||\n !/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u.test(path)\n ) {\n return null;\n }\n return path;\n } catch {\n return null;\n }\n}\n\nfunction positiveSafeInteger(value: unknown): number | null {\n const number = typeof value === \"string\" && /^\\d+$/u.test(value) ? Number(value) : value;\n return typeof number === \"number\" && Number.isSafeInteger(number) && number > 0 ? number : null;\n}\n\nfunction repositoryKey(repository: GitHubRestRepository): string {\n return `${repository.connectionId}\\0${repository.repositoryId}`;\n}\n\nfunction githubAuthorizationHeaders(headers: Record<string, string>): Record<string, string> {\n const authorization = new Headers(headers).get(\"authorization\");\n if (\n !authorization ||\n !/^Bearer [^\\u0000-\\u0020\\u007f]+$/u.test(authorization) ||\n authorization.length > 16_384\n ) {\n throw new GitHubRestAuthorityError(\"Personal GitHub authorization header is unavailable\");\n }\n return { authorization };\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction canRead(permissions: {\n pull: boolean;\n triage: boolean;\n push: boolean;\n maintain: boolean;\n admin: boolean;\n}): boolean {\n return (\n permissions.pull ||\n permissions.triage ||\n permissions.push ||\n permissions.maintain ||\n permissions.admin\n );\n}\n\nfunction canWrite(permissions: { push: boolean; maintain: boolean; admin: boolean }): boolean {\n return permissions.push || permissions.maintain || permissions.admin;\n}\n","import { createHash } from \"node:crypto\";\nimport {\n CONNECTOR_ATTACHMENT_RECEIPT_VERSION,\n ConnectorAttachmentReceiptEnvelope,\n type ConnectorAttachmentReceiptEnvelope as ConnectorAttachmentReceiptEnvelopeValue,\n type ConnectorAttachmentTransfer,\n} from \"@opengeni/contracts\";\nimport {\n connectorAttachmentSandboxPath,\n type ConnectorAttachmentMaterializationRequest,\n} from \"@opengeni/runtime\";\nimport {\n ChannelAPartialMutationError,\n RoutingMutationOutcomeUnknownError,\n SandboxChannelAService,\n} from \"@opengeni/runtime/sandbox\";\n\nexport class ConnectorAttachmentMaterializationError extends Error {\n constructor() {\n super(\"Connector attachment could not be materialized in the sandbox\");\n this.name = \"ConnectorAttachmentMaterializationError\";\n }\n}\n\ntype ConnectorAttachmentChannel = Pick<\n SandboxChannelAService,\n \"importWorkspaceFiles\" | \"inspectWorkspaceFiles\"\n>;\n\ntype ConnectorAttachmentMaterializationOptions = Readonly<{\n runMutation?: <T>(mutation: () => Promise<T>) => Promise<T>;\n}>;\n\nfunction digestParts(...parts: readonly string[]): Buffer {\n const hash = createHash(\"sha256\");\n for (const part of parts) {\n const bytes = Buffer.from(part, \"utf8\");\n hash.update(String(bytes.byteLength));\n hash.update(\":\");\n hash.update(bytes);\n hash.update(\";\");\n }\n return hash.digest();\n}\n\nfunction uuidFromDigest(digest: Buffer): string {\n const bytes = Uint8Array.from(digest.subarray(0, 16));\n bytes[6] = (bytes[6]! & 0x0f) | 0x50;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Buffer.from(bytes).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nexport { connectorAttachmentSandboxPath } from \"@opengeni/runtime\";\n\nexport function connectorAttachmentImportOperationId(\n request: Pick<\n ConnectorAttachmentMaterializationRequest,\n \"serverId\" | \"toolName\" | \"operationId\" | \"connectionId\"\n >,\n attachment: ConnectorAttachmentTransfer,\n index: number,\n): string {\n return uuidFromDigest(\n digestParts(\n \"opengeni-connector-attachment-import-v1\",\n request.serverId,\n request.toolName,\n request.operationId,\n request.connectionId,\n String(index),\n attachment.providerAttachmentId.provider,\n attachment.providerAttachmentId.value,\n attachment.contentSha256,\n ),\n );\n}\n\nexport async function materializeConnectorAttachmentsInChannel(\n channel: ConnectorAttachmentChannel,\n request: ConnectorAttachmentMaterializationRequest,\n options: ConnectorAttachmentMaterializationOptions = {},\n): Promise<ConnectorAttachmentReceiptEnvelopeValue> {\n try {\n const imports = request.attachments.map((attachment, index) => {\n const destinationPath = connectorAttachmentSandboxPath(request, attachment);\n return {\n operationId: connectorAttachmentImportOperationId(request, attachment, index),\n destinationPath,\n overwrite: false,\n mayReplaceExisting: false,\n createParents: true,\n sizeBytes: attachment.byteSize,\n sha256: attachment.contentSha256,\n source: attachment.source,\n };\n });\n const replayedFiles = await channel.inspectWorkspaceFiles(imports);\n const importExactBytes = async () => {\n const importedFiles = [];\n if (imports.length === 0) return await channel.importWorkspaceFiles([]);\n for (const item of imports) {\n try {\n if (request.authorizeProviderRequest) {\n let authorized = false;\n try {\n authorized = await request.authorizeProviderRequest();\n } catch {\n authorized = false;\n }\n if (!authorized) throw new ConnectorAttachmentMaterializationError();\n }\n const [imported] = await channel.importWorkspaceFiles([item]);\n if (!imported) throw new ConnectorAttachmentMaterializationError();\n importedFiles.push(imported);\n } catch (error) {\n if (importedFiles.length > 0 && !(error instanceof RoutingMutationOutcomeUnknownError)) {\n throw new ChannelAPartialMutationError(\n \"connector attachment materialization committed an earlier exact file\",\n { cause: error },\n );\n }\n throw error;\n }\n }\n return importedFiles;\n };\n const importedFiles =\n replayedFiles ??\n (options.runMutation\n ? await options.runMutation(importExactBytes)\n : await importExactBytes());\n const receipts = [];\n for (const [index, attachment] of request.attachments.entries()) {\n const sandboxPath = imports[index]?.destinationPath;\n const imported = importedFiles[index];\n if (\n !sandboxPath ||\n !imported ||\n imported.destinationPath !== sandboxPath ||\n imported.sizeBytes !== attachment.byteSize ||\n imported.sha256 !== attachment.contentSha256\n ) {\n throw new ConnectorAttachmentMaterializationError();\n }\n receipts.push({\n providerAttachmentId: attachment.providerAttachmentId,\n fileName: attachment.fileName,\n mediaType: attachment.mediaType,\n byteSize: attachment.byteSize,\n contentSha256: attachment.contentSha256,\n sandboxPath,\n });\n }\n return ConnectorAttachmentReceiptEnvelope.parse({\n version: CONNECTOR_ATTACHMENT_RECEIPT_VERSION,\n attachments: receipts,\n });\n } catch (error) {\n if (\n error instanceof ChannelAPartialMutationError ||\n error instanceof RoutingMutationOutcomeUnknownError\n ) {\n throw error;\n }\n throw new ConnectorAttachmentMaterializationError();\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport {\n AttemptToolApprovalRequiredError,\n AttemptToolCatalogStaleError,\n AttemptToolInputValidationError,\n AttemptToolNotFoundError,\n codemodeDispatchSubject,\n decodeCodemodeDispatchRequest,\n encodeCodemodeDispatchAck,\n type AttemptToolCatalogEntry,\n type AttemptToolEnvironment,\n} from \"@opengeni/codemode\";\nimport {\n CODEMODE_CLAIM_LEASE_MS,\n CODEMODE_CLAIM_HEARTBEAT_MS,\n CODEMODE_MAX_CONCURRENT_CALLS_PER_ATTEMPT,\n type CodemodeOperation,\n type SessionEvent,\n} from \"@opengeni/contracts\";\nimport {\n cancelQueuedCodemodeOperationsForAttempt,\n claimCodemodeOperation,\n failCodemodeOperation,\n getSessionEventByClientEventId,\n getSessionToolCallCreatedEventByOperationId,\n markCodemodeOperationExecutionStarted,\n renewCodemodeOperationClaim,\n settleCodemodeOperationWithOutput,\n type Database,\n} from \"@opengeni/db\";\nimport {\n appendAndPublishTurnEventsFenced,\n publishDurableSessionEvents,\n type EventBus,\n} from \"@opengeni/events\";\n\nexport type CodemodeDispatcherScope = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n};\n\nexport type CodemodeDispatcherTimings = {\n claimLeaseMs?: number;\n claimHeartbeatMs?: number;\n};\n\n/**\n * Owns the only Codemode execution edge for one exact attempt. NATS carries a\n * wake-up only; the durable row is claimed before any side effect and the call\n * is executed by the same AttemptToolEnvironment already bound to model MCP.\n */\nexport class CodemodeAttemptDispatcher {\n private readonly stopController = new AbortController();\n private readonly inFlight = new Map<string, Promise<void>>();\n private pendingClaims = 0;\n private unsubscribe: (() => void) | null = null;\n private closing = false;\n private readonly claimLeaseMs: number;\n private readonly claimHeartbeatMs: number;\n\n constructor(\n private readonly db: Database,\n private readonly bus: EventBus,\n private readonly environment: AttemptToolEnvironment,\n private readonly scope: CodemodeDispatcherScope,\n private readonly turnSignal?: AbortSignal,\n private readonly maxConcurrentCalls = CODEMODE_MAX_CONCURRENT_CALLS_PER_ATTEMPT,\n timings: CodemodeDispatcherTimings = {},\n ) {\n if (\n environment.catalog.accountId !== scope.accountId ||\n environment.catalog.workspaceId !== scope.workspaceId ||\n environment.catalog.sessionId !== scope.sessionId ||\n environment.catalog.turnId !== scope.turnId ||\n environment.catalog.attemptId !== scope.attemptId ||\n environment.catalog.executionGeneration !== scope.executionGeneration\n ) {\n throw new Error(\"Codemode dispatcher scope does not match its tool environment\");\n }\n if (!Number.isSafeInteger(maxConcurrentCalls) || maxConcurrentCalls < 1) {\n throw new Error(\"Codemode dispatcher concurrency must be a positive safe integer\");\n }\n this.claimLeaseMs = timings.claimLeaseMs ?? CODEMODE_CLAIM_LEASE_MS;\n this.claimHeartbeatMs = timings.claimHeartbeatMs ?? CODEMODE_CLAIM_HEARTBEAT_MS;\n if (\n !Number.isSafeInteger(this.claimLeaseMs) ||\n this.claimLeaseMs < 1_000 ||\n this.claimLeaseMs > 10 * 60_000\n ) {\n throw new Error(\"Codemode dispatcher claim lease must be between 1 second and 10 minutes\");\n }\n if (\n !Number.isSafeInteger(this.claimHeartbeatMs) ||\n this.claimHeartbeatMs < 1 ||\n this.claimHeartbeatMs >= this.claimLeaseMs\n ) {\n throw new Error(\"Codemode dispatcher heartbeat must be positive and shorter than its lease\");\n }\n }\n\n start(): void {\n if (this.unsubscribe || this.closing)\n throw new Error(\"Codemode dispatcher cannot be restarted\");\n this.unsubscribe = this.bus.subscribeRequests(\n codemodeDispatchSubject(this.scope.workspaceId, this.scope.attemptId),\n async (payload) => {\n const request = decodeCodemodeDispatchRequest(payload);\n if (request.catalogDigest !== this.environment.catalog.digest || this.closing) {\n return encodeCodemodeDispatchAck({\n version: 1,\n operationId: request.operationId,\n status: \"rejected\",\n });\n }\n if (\n !this.inFlight.has(request.operationId) &&\n this.inFlight.size + this.pendingClaims >= this.maxConcurrentCalls\n ) {\n return encodeCodemodeDispatchAck({\n version: 1,\n operationId: request.operationId,\n status: \"unavailable\",\n });\n }\n this.pendingClaims += 1;\n try {\n const claim = await claimCodemodeOperation(this.db, {\n ...this.scope,\n catalogDigest: request.catalogDigest,\n operationId: request.operationId,\n claimId: randomUUID(),\n claimLeaseMs: this.claimLeaseMs,\n });\n if (claim.status === \"claimed\") {\n const execution = this.execute(claim.operation, claim.claimId, claim.reclaimed).finally(\n () => {\n this.inFlight.delete(request.operationId);\n },\n );\n this.inFlight.set(request.operationId, execution);\n return encodeCodemodeDispatchAck({\n version: 1,\n operationId: request.operationId,\n status: \"accepted\",\n });\n }\n if (claim.status === \"execution_owner_lost\") {\n await this.settleWithOutput(claim.operation, claim.claimId, {\n state: \"outcome_unknown\",\n errorCode: \"worker_lost_during_execution\",\n errorMessage:\n \"The execution owner disappeared after the tool call began. Inspect actual state before retrying.\",\n });\n return encodeCodemodeDispatchAck({\n version: 1,\n operationId: request.operationId,\n status: \"terminal\",\n });\n }\n return encodeCodemodeDispatchAck({\n version: 1,\n operationId: request.operationId,\n status: claim.status,\n });\n } finally {\n this.pendingClaims -= 1;\n }\n },\n );\n }\n\n async close(reason = \"Execution attempt ended\"): Promise<void> {\n if (this.closing) {\n await Promise.allSettled([...this.inFlight.values()]);\n return;\n }\n this.closing = true;\n this.unsubscribe?.();\n this.unsubscribe = null;\n this.stopController.abort(reason);\n await cancelQueuedCodemodeOperationsForAttempt(this.db, {\n accountId: this.scope.accountId,\n workspaceId: this.scope.workspaceId,\n attemptId: this.scope.attemptId,\n reason,\n });\n await Promise.allSettled([...this.inFlight.values()]);\n }\n\n private async execute(\n operation: CodemodeOperation,\n claimId: string,\n reclaimed: boolean,\n ): Promise<void> {\n const claimAuthority = {\n accountId: this.scope.accountId,\n workspaceId: this.scope.workspaceId,\n attemptId: this.scope.attemptId,\n operationId: operation.operationId,\n claimId,\n claimLeaseMs: this.claimLeaseMs,\n };\n // Preparation may include provider preflight and policy resolution. Keep the\n // durable claim alive from the moment execution is accepted, not only after\n // the provider side-effect marker, so a slow preflight cannot be reclaimed.\n const heartbeat = setInterval(() => {\n void renewCodemodeOperationClaim(this.db, claimAuthority).catch(() => undefined);\n }, this.claimHeartbeatMs);\n heartbeat.unref?.();\n try {\n await this.executeClaimed(operation, claimId, reclaimed, claimAuthority);\n } finally {\n clearInterval(heartbeat);\n }\n }\n\n private async executeClaimed(\n operation: CodemodeOperation,\n claimId: string,\n reclaimed: boolean,\n claimAuthority: Parameters<typeof markCodemodeOperationExecutionStarted>[1],\n ): Promise<void> {\n const entry = this.environment.catalog.entries.find(\n (candidate) =>\n candidate.identity.serverId === operation.identity.serverId &&\n candidate.identity.toolName === operation.identity.toolName,\n );\n if (!entry) {\n await this.failBeforeExecution(\n operation.operationId,\n claimId,\n \"tool_not_found\",\n \"Tool left the active catalog\",\n );\n return;\n }\n const signal = combinedSignal(this.stopController.signal, this.turnSignal);\n if (signal.aborted) {\n await this.failBeforeExecution(\n operation.operationId,\n claimId,\n \"attempt_cancelled\",\n \"Execution attempt ended before the Codemode call started\",\n );\n return;\n }\n if (!(await this.ensureToolCallCreated(operation, entry, reclaimed))) {\n await this.failBeforeExecution(\n operation.operationId,\n claimId,\n \"attempt_fence_closed\",\n \"Execution attempt ended before the Codemode call started\",\n );\n return;\n }\n if (signal.aborted) {\n await this.settleWithOutput(operation, claimId, {\n state: \"failed\",\n errorCode: \"attempt_cancelled\",\n errorMessage: \"Execution attempt ended before the Codemode call started\",\n });\n return;\n }\n\n let preparedCall: Awaited<ReturnType<AttemptToolEnvironment[\"prepareCall\"]>>;\n try {\n preparedCall = await this.environment.prepareCall(\n {\n operationId: operation.operationId,\n catalogDigest: operation.catalogDigest,\n identity: operation.identity,\n arguments: operation.arguments,\n caller: operation.caller,\n },\n { signal },\n );\n } catch (error) {\n await this.settleWithOutput(operation, claimId, {\n state: \"failed\",\n errorCode: errorCode(error, signal, false),\n errorMessage: safeErrorMessage(error),\n });\n return;\n }\n if (signal.aborted) {\n await this.settleWithOutput(operation, claimId, {\n state: \"failed\",\n errorCode: \"attempt_cancelled\",\n errorMessage: \"Execution attempt ended before the Codemode call started\",\n });\n return;\n }\n\n const crossedExecutionBoundary = await markCodemodeOperationExecutionStarted(\n this.db,\n claimAuthority,\n );\n if (!crossedExecutionBoundary) return;\n try {\n const result = await preparedCall.execute();\n await this.settleWithOutput(operation, claimId, {\n state: \"completed\",\n result,\n });\n } catch (error) {\n const knownPreExecution =\n error instanceof AttemptToolApprovalRequiredError ||\n error instanceof AttemptToolCatalogStaleError ||\n error instanceof AttemptToolNotFoundError ||\n connectorActionWasNotExecuted(error);\n await this.settleWithOutput(operation, claimId, {\n state: knownPreExecution ? \"failed\" : \"outcome_unknown\",\n errorCode: errorCode(error, signal, true),\n errorMessage: !knownPreExecution\n ? \"Tool execution ended without a durable result. Its side-effect outcome is unknown; inspect actual state before retrying.\"\n : safeErrorMessage(error),\n });\n }\n }\n\n private async ensureToolCallCreated(\n operation: CodemodeOperation,\n entry: AttemptToolCatalogEntry,\n reclaimed: boolean,\n ): Promise<boolean> {\n const clientEventId = codemodeToolCallCreatedClientEventId(operation.operationId);\n if (reclaimed) {\n const existing = await getSessionEventByClientEventId(\n this.db,\n this.scope.workspaceId,\n this.scope.sessionId,\n clientEventId,\n ).catch(() => null);\n if (existing) {\n assertMatchingCodemodeToolCallCreated(existing, operation, entry, this.scope);\n return true;\n }\n const legacyCreated = await getSessionToolCallCreatedEventByOperationId(this.db, {\n workspaceId: this.scope.workspaceId,\n sessionId: this.scope.sessionId,\n turnId: this.scope.turnId,\n attemptId: this.scope.attemptId,\n operationId: operation.operationId,\n }).catch(() => null);\n if (legacyCreated) {\n assertMatchingCodemodeToolCallCreated(legacyCreated, operation, entry, this.scope);\n return true;\n }\n }\n try {\n const created = await appendAndPublishTurnEventsFenced(\n this.db,\n this.bus,\n this.scope.workspaceId,\n this.scope.sessionId,\n this.scope.turnId,\n this.scope.executionGeneration,\n this.scope.attemptId,\n [\n {\n type: \"agent.toolCall.created\",\n clientEventId,\n turnId: this.scope.turnId,\n turnGeneration: this.scope.executionGeneration,\n turnAttemptId: this.scope.attemptId,\n producerId: operation.caller.subjectId,\n payload: {\n id: operation.operationId,\n name: entry.modelName,\n arguments: operation.arguments,\n origin: \"codemode\",\n subjectId: operation.caller.subjectId,\n raw: {\n type: \"codemode_call\",\n serverId: operation.identity.serverId,\n toolName: operation.identity.toolName,\n catalogDigest: operation.catalogDigest,\n },\n },\n },\n ],\n );\n return created.accepted;\n } catch {\n // A concurrent reclaimed claimant can win the unique client-event insert,\n // or a committed append can lose its response. Reconcile durable truth\n // before treating the attempt fence as closed.\n const raced = await getSessionEventByClientEventId(\n this.db,\n this.scope.workspaceId,\n this.scope.sessionId,\n clientEventId,\n ).catch(() => null);\n if (!raced) return false;\n assertMatchingCodemodeToolCallCreated(raced, operation, entry, this.scope);\n return true;\n }\n }\n\n private async settleWithOutput(\n operation: CodemodeOperation,\n claimId: string,\n settlement:\n | { state: \"completed\"; result: NonNullable<CodemodeOperation[\"result\"]> }\n | {\n state: \"failed\" | \"outcome_unknown\";\n errorCode: string;\n errorMessage: string;\n },\n ): Promise<void> {\n const result = await settleCodemodeOperationWithOutput(this.db, {\n ...this.scope,\n operationId: operation.operationId,\n claimId,\n producerId: operation.caller.subjectId,\n settlement,\n });\n if (!result.committed || result.events.length === 0) return;\n await publishDurableSessionEvents(\n this.bus,\n this.scope.workspaceId,\n this.scope.sessionId,\n result.events,\n );\n }\n\n private async failBeforeExecution(\n operationId: string,\n claimId: string,\n failureCode: string,\n failureMessage: string,\n ): Promise<void> {\n await failCodemodeOperation(this.db, {\n accountId: this.scope.accountId,\n workspaceId: this.scope.workspaceId,\n attemptId: this.scope.attemptId,\n operationId,\n claimId,\n state: \"failed\",\n errorCode: failureCode,\n errorMessage: failureMessage,\n });\n }\n}\n\nexport function codemodeToolCallCreatedClientEventId(operationId: string): string {\n return `opengeni:codemode-tool-call-created:${operationId}`;\n}\n\nfunction assertMatchingCodemodeToolCallCreated(\n event: SessionEvent,\n operation: CodemodeOperation,\n entry: AttemptToolCatalogEntry,\n scope: CodemodeDispatcherScope,\n): void {\n const payload = recordValue(event.payload);\n const raw = recordValue(payload?.raw);\n if (\n event.type !== \"agent.toolCall.created\" ||\n event.turnId !== scope.turnId ||\n event.turnGeneration !== scope.executionGeneration ||\n event.turnAttemptId !== scope.attemptId ||\n event.turnAssociation !== \"current\" ||\n payload?.id !== operation.operationId ||\n payload?.name !== entry.modelName ||\n payload?.origin !== \"codemode\" ||\n payload?.subjectId !== operation.caller.subjectId ||\n raw?.type !== \"codemode_call\" ||\n raw?.serverId !== operation.identity.serverId ||\n raw?.toolName !== operation.identity.toolName ||\n raw?.catalogDigest !== operation.catalogDigest\n ) {\n throw new Error(\"Codemode tool-call creation id is bound to incompatible durable evidence\");\n }\n}\n\nfunction recordValue(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction connectorActionWasNotExecuted(error: unknown): boolean {\n return Boolean(\n error &&\n typeof error === \"object\" &&\n \"connectorActionOutcome\" in error &&\n (error as { connectorActionOutcome?: unknown }).connectorActionOutcome === \"not_executed\",\n );\n}\n\nfunction combinedSignal(primary: AbortSignal, secondary?: AbortSignal): AbortSignal {\n return secondary ? AbortSignal.any([primary, secondary]) : primary;\n}\n\nfunction errorCode(error: unknown, signal: AbortSignal, executionStarted: boolean): string {\n if (signal.aborted) {\n return executionStarted ? \"attempt_cancelled_during_execution\" : \"attempt_cancelled\";\n }\n if (connectorActionWasNotExecuted(error)) return \"connector_action_not_executed\";\n if (typeof error === \"object\" && error !== null && \"code\" in error) {\n const code = (error as { code?: unknown }).code;\n if (typeof code === \"string\" && /^[a-z0-9_]{1,128}$/u.test(code)) return code;\n }\n return \"tool_outcome_unknown\";\n}\n\nfunction safeErrorMessage(error: unknown): string {\n if (\n error instanceof AttemptToolApprovalRequiredError ||\n error instanceof AttemptToolCatalogStaleError ||\n error instanceof AttemptToolInputValidationError ||\n error instanceof AttemptToolNotFoundError\n ) {\n return error.message;\n }\n return \"Codemode call failed before tool execution\";\n}\n","import type { ChannelASession } from \"@opengeni/runtime/sandbox\";\nimport type { ResumedTurnSandbox } from \"../../sandbox-resume\";\nimport type { SandboxRuntimeState } from \"./turn-context\";\n\ntype TurnSandboxAccessState = Pick<\n SandboxRuntimeState,\n \"resolvedSandbox\" | \"lazyOwnedSandbox\" | \"turnSandboxProvisioner\"\n>;\n\nexport type ResolvedTurnSandboxAccess = Readonly<{\n sandbox: ResumedTurnSandbox | null;\n session: ChannelASession;\n leaseEpoch: number;\n}>;\n\n/** Join the turn's canonical sandbox boundary and return its active routed session. */\nexport async function resolveTurnSandboxAccess(\n sandboxState: TurnSandboxAccessState,\n sdkOwnedSandboxSession: unknown,\n unavailableMessage: string,\n): Promise<ResolvedTurnSandboxAccess> {\n let sandbox = sandboxState.resolvedSandbox;\n if (!sandbox && sandboxState.turnSandboxProvisioner) {\n sandbox = await sandboxState.turnSandboxProvisioner.get();\n }\n\n const session = (sandboxState.lazyOwnedSandbox?.session ??\n sandbox?.established.session ??\n sdkOwnedSandboxSession) as ChannelASession | null;\n if (!session) throw new Error(unavailableMessage);\n\n return {\n sandbox,\n session,\n leaseEpoch: sandbox?.leaseEpoch ?? 0,\n };\n}\n","import type { AttemptToolDefinition } from \"@opengeni/codemode\";\nimport {\n compareModelPickerOrder,\n modelPickerBillingClassFor,\n} from \"@opengeni/contracts/model-picker-order\";\nimport type { WorkspaceModelSelection } from \"@opengeni/core\";\n\nexport const LIST_MODELS_TOOL_NAME = \"list_models\";\n\nexport const LIST_MODELS_TOOL_DESCRIPTION =\n \"List the models this workspace can select right now, in picker order, with deployment-defined cost and optional guidance. This does not switch the current session model; use an ID with session_create or the human model picker.\";\n\nfunction safeLineField(value: string): string {\n return value\n .replace(/[\\r\\n|]/gu, \" \")\n .replace(/\\s+/gu, \" \")\n .trim();\n}\n\nexport function renderListModels(input: {\n currentModelId: string | null;\n selections: readonly WorkspaceModelSelection[];\n modelNotes: Readonly<Record<string, string>>;\n}): string {\n const lines: string[] = [];\n if (input.currentModelId) {\n lines.push(`Current: ${safeLineField(input.currentModelId)}`);\n }\n\n const selectable = input.selections\n .filter((entry) => entry.availability.selectable)\n .map((selection) => ({\n selection,\n billingClass: modelPickerBillingClassFor(selection.model),\n selectable: selection.availability.selectable,\n label: selection.model.label,\n }))\n .sort(compareModelPickerOrder);\n if (selectable.length === 0) {\n lines.push(\"No models are available in this workspace.\");\n return lines.join(\"\\n\");\n }\n\n for (const { selection } of selectable) {\n const { model } = selection;\n const fields = [safeLineField(model.id), safeLineField(model.label), model.cost];\n const note = input.modelNotes[model.id];\n if (note) fields.push(safeLineField(note));\n lines.push(`- ${fields.join(\" | \")}`);\n }\n return lines.join(\"\\n\");\n}\n\nexport function createListModelsAttemptToolDefinition(input: {\n currentModelId: string | null;\n load: () => Promise<{\n selections: readonly WorkspaceModelSelection[];\n modelNotes: Readonly<Record<string, string>>;\n }>;\n}): AttemptToolDefinition {\n return {\n identity: { serverId: \"opengeni\", toolName: LIST_MODELS_TOOL_NAME },\n modelName: LIST_MODELS_TOOL_NAME,\n codemodePath: [\"opengeni\", LIST_MODELS_TOOL_NAME],\n title: \"List selectable models\",\n description: LIST_MODELS_TOOL_DESCRIPTION,\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n annotations: {\n title: \"List selectable models\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n source: \"opengeni\",\n approval: \"none\",\n execute: async (args) => {\n if (Object.keys(args).length !== 0) {\n throw new Error(\"list_models accepts no arguments\");\n }\n const catalog = await input.load();\n return {\n isError: false,\n content: [\n {\n type: \"text\",\n text: renderListModels({\n currentModelId: input.currentModelId,\n selections: catalog.selections,\n modelNotes: catalog.modelNotes,\n }),\n },\n ],\n };\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport type { Settings } from \"@opengeni/config\";\nimport {\n skillReviewHumanInput,\n type SkillActor,\n type SkillWriteReceipt,\n} from \"@opengeni/contracts\";\nimport {\n assertSkillReadAttempt,\n skillReviewResolution,\n installPortableSkill,\n replayPortableSkillInstall,\n listSkillDescriptors,\n type Database,\n type InstallPortableSkillInput,\n} from \"@opengeni/db\";\nimport {\n createGitHubSkillSourceClient,\n createPublicSkillSearchClient,\n portableSkillCapabilityId,\n portableSkillPluginKey,\n readSkill,\n resolveSkillImport,\n saveSkill,\n} from \"@opengeni/core\";\nimport {\n buildPortableSkillArtifact,\n loadSkillLibrarySkill,\n skillLibraryRepositoryUrl,\n type SkillTextFile,\n} from \"@opengeni/runtime/skill-library\";\nimport type { RuntimeSkillArtifact } from \"@opengeni/runtime\";\nimport type { SandboxChannelAService } from \"@opengeni/runtime/sandbox\";\nimport { createSkillReadAttemptToolDefinition, type SkillReadContent } from \"./skill-read\";\nimport { createSkillSearchAttemptToolDefinition } from \"./skill-search\";\nimport { createSkillSaveAttemptToolDefinition, type SkillSaveRequest } from \"./skill-save\";\nimport { createSkillInstallAttemptToolDefinition } from \"./skill-install\";\nimport {\n createSkillCheckoutAttemptToolDefinition,\n createSkillPublishAttemptToolDefinition,\n} from \"./skill-checkout\";\n\nexport function createWorkspaceSkillTools(input: {\n db: Database;\n settings: Settings;\n accountId: string;\n workspaceId: string;\n subjectId?: string;\n actor: Extract<SkillActor, { kind: \"agent\" }>;\n selected: readonly { id: string; artifact: RuntimeSkillArtifact }[];\n filesystem: () => Promise<\n Pick<SandboxChannelAService, \"fsList\" | \"fsRead\" | \"fsWrite\" | \"fsMkdir\">\n >;\n}) {\n const context = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n ...(input.subjectId ? { subjectId: input.subjectId } : {}),\n };\n const authorize = () => assertSkillReadAttempt(input.db, { ...context, actor: input.actor });\n const selected = new Map(input.selected.map((entry) => [entry.id, entry.artifact]));\n const list = async () =>\n (await listSkillDescriptors(input.db, context)).filter(\n (entry) => entry.activationMode === \"workspace_managed\",\n );\n // Both text reads and inventory resolve through this same authorized source.\n // Selected artifacts have no ledger revision identity; never synthesize one.\n const load = async (identifier: string): Promise<readonly SkillTextFile[] | SkillReadContent> => {\n const exact = selected.get(identifier);\n if (exact) return exact.files;\n const descriptors = await list();\n const exactWorkspace = descriptors.find((entry) => entry.id === identifier);\n const matches = exactWorkspace\n ? [exactWorkspace]\n : descriptors.filter((entry) => entry.title === identifier || entry.stableKey === identifier);\n const selectedMatches = [...selected.entries()].filter(\n ([, artifact]) => artifact.name === identifier,\n );\n if (!exactWorkspace && matches.length + selectedMatches.length > 1)\n throw new Error(\n \"Multiple Skills match that name. Use the Skill id from the index or search.\",\n );\n if (!matches.length && selectedMatches.length === 1) return selectedMatches[0]![1].files;\n const match = matches[0];\n if (!match) throw new Error(\"Skill is not available in this session.\");\n const record = await readSkill(input.db, context, match.id);\n if (\n !record ||\n record.status !== \"active\" ||\n !record.activeRevisionId ||\n record.revisionId !== record.activeRevisionId\n )\n throw new Error(\"Skill is no longer active. Search again for current Skills.\");\n return {\n skillId: record.id,\n revisionId: record.activeRevisionId,\n scopeVersion: record.scopeVersion,\n ...(match.installationVersion !== null\n ? { installationVersion: match.installationVersion }\n : {}),\n files: record.files,\n };\n };\n const withConfirmation = async (receipt: SkillWriteReceipt) => {\n const reviewResolution = receipt.skillReview\n ? await skillReviewResolution(input.db, context, receipt.skillReview)\n : undefined;\n return {\n ...receipt,\n ...(reviewResolution ? { reviewResolution } : {}),\n ...(receipt.skillReview && reviewResolution === \"pending\"\n ? { humanInput: skillReviewHumanInput(receipt.skillReview) }\n : {}),\n };\n };\n const save = async (request: SkillSaveRequest) => {\n const artifact = buildPortableSkillArtifact(request.files);\n const base = request.expectedRevisionId\n ? await readSkill(input.db, context, request.skillId, request.expectedRevisionId)\n : null;\n return withConfirmation(\n await saveSkill(input.db, {\n ...context,\n ...request,\n actor: input.actor,\n files: [...artifact.files],\n stableKey: base?.stableKey ?? `authored-${request.skillId.replaceAll(\"-\", \"\")}`,\n }),\n );\n };\n return [\n createSkillReadAttemptToolDefinition({ authorize, load }),\n createSkillSearchAttemptToolDefinition({\n authorize,\n listWorkspace: async () => [\n ...(await list()).map((entry) => ({\n id: entry.id,\n name: entry.title,\n description: entry.description,\n revisionId: entry.revisionId,\n scopeVersion: entry.scopeVersion,\n ...(entry.installationVersion !== null\n ? { installationVersion: entry.installationVersion }\n : {}),\n })),\n ...input.selected.map((entry) => ({\n id: entry.id,\n name: entry.artifact.name,\n description: entry.artifact.description || entry.artifact.name,\n source: entry.id.startsWith(\"builtin:\")\n ? (\"builtin\" as const)\n : entry.id.startsWith(\"session:\")\n ? (\"session\" as const)\n : (\"pack\" as const),\n })),\n ],\n publicSearch: createPublicSkillSearchClient(input.settings),\n }),\n createSkillSaveAttemptToolDefinition({\n authorize,\n save,\n load: async (skillId, revisionId) => {\n const record = await readSkill(input.db, context, skillId, revisionId);\n if (!record?.revisionId) throw new Error(\"Skill edit base is unavailable.\");\n return { revisionId: record.revisionId, files: record.files };\n },\n }),\n createSkillInstallAttemptToolDefinition({\n authorize,\n install: async (request) => {\n const requestIdentity = {\n operation: \"skill_install\",\n source: request.source,\n expectedInstallationVersion: request.expectedInstallationVersion ?? null,\n reason: request.reason,\n owner: \"direct\",\n };\n const replay = await replayPortableSkillInstall(input.db, {\n ...context,\n actor: input.actor,\n operationId: request.operationId,\n requestIdentity,\n });\n if (replay) return withConfirmation(replay.skillReceipt);\n let source: Omit<InstallPortableSkillInput, \"accountId\" | \"workspaceId\" | \"subjectId\">;\n if (request.source.startsWith(\"library:\")) {\n const loaded = loadSkillLibrarySkill(request.source.slice(\"library:\".length));\n source = {\n capabilityId: `skill:${loaded.entry.id}`,\n pluginKey: `skill/library/${loaded.entry.id}`,\n source: \"library\",\n sourceUrl: loaded.entry.sourceUrl,\n repositoryUrl: skillLibraryRepositoryUrl(loaded.entry.sourceUrl),\n version: loaded.entry.version,\n sourceCommit: loaded.entry.sourceCommit,\n sourcePath: loaded.entry.relativePath,\n name: loaded.entry.name,\n description: loaded.entry.description,\n contentSha256: loaded.entry.contentSha256,\n totalBytes: loaded.skill.files.reduce(\n (total, file) => total + Buffer.byteLength(file.content),\n 0,\n ),\n files: fileMetadata(loaded.skill.files),\n provenance: \"platform\",\n sourceProvenance: loaded.entry.provenance,\n category: loaded.entry.category,\n tags: [...loaded.entry.tags],\n license: loaded.entry.license,\n };\n } else {\n const resolved = await resolveSkillImport(\n request.source,\n createGitHubSkillSourceClient(input.settings),\n );\n source = {\n capabilityId: portableSkillCapabilityId(resolved.preview),\n pluginKey: portableSkillPluginKey(resolved.preview),\n source: resolved.preview.source,\n sourceUrl: resolved.preview.sourceUrl,\n repositoryUrl: resolved.preview.repositoryUrl,\n version: resolved.preview.sourceCommit,\n sourceCommit: resolved.preview.sourceCommit,\n sourcePath: resolved.preview.sourcePath,\n name: resolved.preview.name,\n description: resolved.preview.description,\n contentSha256: resolved.preview.contentSha256,\n totalBytes: resolved.preview.totalBytes,\n files: fileMetadata(resolved.files),\n };\n }\n const installed = await installPortableSkill(input.db, {\n ...context,\n ...source,\n subjectId: `service:skill-attempt:${input.actor.attemptId}`,\n skillActor: input.actor,\n skillOperationId: request.operationId,\n skillRequestIdentity: requestIdentity,\n ...(request.expectedInstallationVersion !== undefined\n ? {\n expectedInstallationVersion: request.expectedInstallationVersion,\n }\n : {}),\n });\n return withConfirmation(installed.skillReceipt);\n },\n }),\n createSkillCheckoutAttemptToolDefinition({\n authorize,\n filesystem: input.filesystem,\n load: async (skill) => {\n const content = await load(skill);\n if (!(\"files\" in content))\n return { skillId: skill, revisionId: null, scopeVersion: null, files: content };\n return content;\n },\n }),\n createSkillPublishAttemptToolDefinition({ authorize, filesystem: input.filesystem, save }),\n ];\n}\n\nfunction fileMetadata(files: readonly SkillTextFile[]) {\n return files.map((file) => ({\n ...file,\n byteSize: Buffer.byteLength(file.content),\n contentSha256: createHash(\"sha256\").update(file.content, \"utf8\").digest(\"hex\"),\n }));\n}\n","import type { AttemptToolDefinition } from \"@opengeni/codemode\";\nimport {\n listSkillPaths,\n PORTABLE_SKILL_MAX_FILES,\n readSkillFiles,\n SKILL_READ_MAX_PATHS,\n type SkillTextFile,\n} from \"@opengeni/runtime/skill-library\";\n\nexport const SKILL_READ_TOOL_NAME = \"skill_read\";\n\nexport type SkillReadContent = Readonly<{\n files: readonly SkillTextFile[];\n skillId: string;\n revisionId: string;\n scopeVersion: number;\n installationVersion?: number;\n}>;\n\n/** A first-party gateway definition, not a sandbox capability or second backend. */\nexport function createSkillReadAttemptToolDefinition(input: {\n authorize: () => Promise<void>;\n load: (skill: string) => Promise<readonly SkillTextFile[] | SkillReadContent>;\n}): AttemptToolDefinition {\n return {\n identity: { serverId: \"opengeni\", toolName: SKILL_READ_TOOL_NAME },\n modelName: SKILL_READ_TOOL_NAME,\n codemodePath: [\"opengeni\", SKILL_READ_TOOL_NAME],\n title: \"Read Skill files\",\n description:\n \"Read Skill text without starting a sandbox. Omit paths to read SKILL.md; provide relative paths to read exactly those files, never implicitly adding SKILL.md. Set listFiles:true without paths to list relative paths and available revision identity only, with no file bodies. Use an id or name from the Skill index or skill_search. Management tools are lazy; when listed, opengeni-skills explains how to use them.\",\n inputSchema: {\n type: \"object\",\n properties: {\n skill: { type: \"string\", minLength: 1, maxLength: 512 },\n listFiles: { type: \"boolean\" },\n paths: {\n type: \"array\",\n minItems: 1,\n maxItems: SKILL_READ_MAX_PATHS,\n uniqueItems: true,\n items: { type: \"string\", minLength: 1, maxLength: 1024 },\n },\n },\n required: [\"skill\"],\n additionalProperties: false,\n },\n annotations: {\n title: \"Read Skill files\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n source: \"opengeni\",\n approval: \"none\",\n execute: async (args) => {\n if (\n typeof args.skill !== \"string\" ||\n !args.skill ||\n (args.listFiles !== undefined && typeof args.listFiles !== \"boolean\") ||\n (args.paths !== undefined &&\n (!Array.isArray(args.paths) || args.paths.some((path) => typeof path !== \"string\")))\n ) {\n throw new Error(\"skill_read requires a Skill identifier and optional relative paths.\");\n }\n if (args.listFiles === true && args.paths !== undefined) {\n throw new Error(\"skill_read listFiles:true cannot be combined with paths.\");\n }\n await input.authorize();\n const loaded = await input.load(args.skill);\n const metadata = \"files\" in loaded ? loaded : null;\n const files = metadata ? metadata.files : (loaded as readonly SkillTextFile[]);\n const selected =\n args.listFiles === true\n ? listSkillPaths(files, PORTABLE_SKILL_MAX_FILES)\n : readSkillFiles(files, args.paths as string[] | undefined);\n const output = {\n ...(metadata\n ? {\n skillId: metadata.skillId,\n revisionId: metadata.revisionId,\n scopeVersion: metadata.scopeVersion,\n ...(metadata.installationVersion !== undefined\n ? { installationVersion: metadata.installationVersion }\n : {}),\n }\n : {}),\n ...selected,\n };\n return {\n isError: false,\n content: [{ type: \"text\", text: JSON.stringify(output) }],\n structuredContent: output,\n };\n },\n };\n}\n","import type { AttemptToolDefinition } from \"@opengeni/codemode\";\nimport { PublicSkillSearchError, type PublicSkillSearchClient } from \"@opengeni/core\";\nimport { listSkillLibraryEntries } from \"@opengeni/runtime/skill-library\";\n\nexport type WorkspaceSkillSearchEntry = Readonly<{\n id: string;\n name: string;\n description: string;\n revisionId?: string;\n scopeVersion?: number;\n installationVersion?: number;\n source?: \"workspace\" | \"builtin\" | \"session\" | \"pack\";\n}>;\n\nexport function createSkillSearchAttemptToolDefinition(input: {\n authorize: () => Promise<void>;\n listWorkspace: () => Promise<readonly WorkspaceSkillSearchEntry[]>;\n publicSearch: PublicSkillSearchClient;\n}): AttemptToolDefinition {\n return {\n identity: { serverId: \"opengeni\", toolName: \"skill_search\" },\n modelName: \"skill_search\",\n codemodePath: [\"opengeni\", \"skill_search\"],\n title: \"Search Skills\",\n description:\n \"Find installed workspace Skills or available curated and public Skills. Returns identifiers and install sources, not file contents. Search never installs or starts a sandbox. Scope defaults to all; use installed to avoid external search.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", minLength: 2, maxLength: 200 },\n scope: { type: \"string\", enum: [\"installed\", \"catalog\", \"all\"] },\n limit: { type: \"integer\", minimum: 1, maximum: 20 },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n annotations: {\n title: \"Search Skills\",\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n source: \"opengeni\",\n approval: \"none\",\n execute: async (args) => {\n await input.authorize();\n const query = String(args.query).trim();\n const scope = args.scope ?? \"all\";\n const limit = typeof args.limit === \"number\" ? args.limit : 20;\n const searchText = query.toLowerCase();\n const matches = (entry: { name: string; description: string }) =>\n `${entry.name}\\n${entry.description}`.toLowerCase().includes(searchText);\n const installed = scope === \"catalog\" ? [] : await input.listWorkspace();\n const workspaceHits = installed\n .filter(matches)\n .slice(0, limit)\n .map((entry) => ({\n ...entry,\n source: entry.source ?? \"workspace\",\n installed: !entry.source || entry.source === \"workspace\",\n }));\n const libraryHits =\n scope === \"installed\"\n ? []\n : listSkillLibraryEntries()\n .filter(matches)\n .slice(0, limit)\n .map((entry) => ({\n id: `library:${entry.id}`,\n name: entry.name,\n description: entry.description,\n source: \"library\" as const,\n libraryId: entry.id,\n }));\n let publicResult: Awaited<ReturnType<PublicSkillSearchClient[\"search\"]>> | null = null;\n let publicError: {\n source: \"skills_sh\";\n code: string;\n retryAfterSeconds: number | null;\n } | null = null;\n if (scope !== \"installed\") {\n try {\n publicResult = await input.publicSearch.search({ query, limit });\n } catch (error) {\n if (!(error instanceof PublicSkillSearchError)) throw error;\n publicError = {\n source: \"skills_sh\",\n code: error.code,\n retryAfterSeconds: error.retryAfterSeconds,\n };\n }\n }\n const output = {\n workspace: workspaceHits,\n library: libraryHits,\n public: publicResult?.items.map((entry) => ({ ...entry })) ?? [],\n // A provider outage is not an empty search. Keep local results useful\n // and expose partial failure explicitly, without leaking network details.\n partial: publicError !== null,\n errors: publicError ? [publicError] : [],\n };\n return {\n isError: false,\n content: [{ type: \"text\", text: JSON.stringify(output) }],\n structuredContent: output,\n };\n },\n };\n}\n","import type { AttemptToolDefinition } from \"@opengeni/codemode\";\nimport {\n applySkillFileChanges,\n buildPortableSkillArtifact,\n PORTABLE_SKILL_MAX_FILES,\n type SkillTextFile,\n} from \"@opengeni/runtime/skill-library\";\n\nexport type SkillSaveRequest = {\n operationId: string;\n skillId: string;\n expectedRevisionId: string | null;\n expectedScopeVersion: number;\n files: readonly SkillTextFile[];\n reason: string;\n};\n\nexport type SkillSaveReceipt = {\n operationId: string;\n skillId: string;\n revisionId: string;\n outcome: \"applied\" | \"pending\" | \"preserved\";\n replayed: boolean;\n};\n\n/** Persistence owns mode enforcement, replay, and the final compare-and-swap. */\nexport function createSkillSaveAttemptToolDefinition(input: {\n authorize: () => Promise<void>;\n load: (\n skillId: string,\n revisionId: string,\n ) => Promise<{\n revisionId: string;\n files: readonly SkillTextFile[];\n }>;\n save: (request: SkillSaveRequest) => Promise<SkillSaveReceipt>;\n}): AttemptToolDefinition {\n return {\n identity: { serverId: \"opengeni\", toolName: \"skill_save\" },\n modelName: \"skill_save\",\n codemodePath: [\"opengeni\", \"skill_save\"],\n title: \"Save Skill text\",\n description:\n \"Create or edit a workspace Skill without a sandbox. Supply only changed UTF-8 text files and explicit deletions; omitted files are preserved. Use the revision and scope version returned by Skill discovery for stale-write protection. For creation choose a new UUID, set expectedRevisionId to null and expectedScopeVersion to 1. Learning mode determines whether the change is live, pending approval, or refused. If humanInput is returned, call request_human_input verbatim, Save activates the exact reviewed revision as the answer is accepted. Do not ask for a second review or call a separate activation tool.\",\n inputSchema: {\n type: \"object\",\n properties: {\n operationId: { type: \"string\", format: \"uuid\" },\n skillId: { type: \"string\", format: \"uuid\" },\n expectedRevisionId: { type: [\"string\", \"null\"], format: \"uuid\" },\n expectedScopeVersion: { type: \"integer\", minimum: 0 },\n files: {\n type: \"array\",\n maxItems: PORTABLE_SKILL_MAX_FILES,\n items: {\n type: \"object\",\n properties: {\n path: { type: \"string\", minLength: 1, maxLength: 1024 },\n content: { type: \"string\" },\n },\n required: [\"path\", \"content\"],\n additionalProperties: false,\n },\n },\n deletions: {\n type: \"array\",\n maxItems: PORTABLE_SKILL_MAX_FILES,\n uniqueItems: true,\n items: { type: \"string\", minLength: 1, maxLength: 1024 },\n },\n reason: { type: \"string\", minLength: 1, maxLength: 2000 },\n },\n required: [\n \"operationId\",\n \"skillId\",\n \"expectedRevisionId\",\n \"expectedScopeVersion\",\n \"files\",\n \"reason\",\n ],\n additionalProperties: false,\n },\n annotations: {\n title: \"Save Skill text\",\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n source: \"opengeni\",\n approval: \"none\",\n execute: async (args) => {\n await input.authorize();\n const skillId = args.skillId as string;\n const expectedRevisionId = args.expectedRevisionId as string | null;\n // Expand the edit against its immutable base, not today's head. The\n // lifecycle can then replay an already committed operation before CAS.\n const current =\n expectedRevisionId === null ? null : await input.load(skillId, expectedRevisionId);\n if (current && current.revisionId !== expectedRevisionId) {\n throw new Error(\"Skill edit base did not match the requested revision.\");\n }\n const files = applySkillFileChanges(\n current?.files ?? [],\n args.files as SkillTextFile[],\n (args.deletions ?? []) as string[],\n );\n const artifact = buildPortableSkillArtifact(files);\n const output = await input.save({\n operationId: args.operationId as string,\n skillId,\n expectedRevisionId,\n expectedScopeVersion: args.expectedScopeVersion as number,\n files: artifact.files,\n reason: args.reason as string,\n });\n return {\n isError: false,\n content: [{ type: \"text\", text: JSON.stringify(output) }],\n structuredContent: output,\n };\n },\n };\n}\n","import type { AttemptToolDefinition } from \"@opengeni/codemode\";\nimport type { SkillSaveReceipt } from \"./skill-save\";\n\n/** The installer resolves/pins bytes and persists them through the shared lifecycle. */\nexport function createSkillInstallAttemptToolDefinition(input: {\n authorize: () => Promise<void>;\n install: (request: {\n operationId: string;\n source: string;\n expectedInstallationVersion?: number;\n reason: string;\n }) => Promise<SkillSaveReceipt>;\n}): AttemptToolDefinition {\n return {\n identity: { serverId: \"opengeni\", toolName: \"skill_install\" },\n modelName: \"skill_install\",\n codemodePath: [\"opengeni\", \"skill_install\"],\n title: \"Install a Skill\",\n description:\n \"Install a Skill from a public skills.sh or GitHub URL, or library:<id> returned by skill_search. The server resolves and pins the source; no prior preview or invented hash is required. Learning mode controls activation. Replacing an existing installation requires its current installation version, and preserves workspace customizations.\",\n inputSchema: {\n type: \"object\",\n properties: {\n operationId: { type: \"string\", format: \"uuid\" },\n source: { type: \"string\", minLength: 1, maxLength: 2048 },\n expectedInstallationVersion: { type: \"integer\", minimum: 0 },\n reason: { type: \"string\", minLength: 1, maxLength: 2000 },\n },\n required: [\"operationId\", \"source\", \"reason\"],\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: true,\n },\n source: \"opengeni\",\n approval: \"none\",\n execute: async (args) => {\n await input.authorize();\n const output = await input.install({\n operationId: args.operationId as string,\n source: args.source as string,\n ...(args.expectedInstallationVersion !== undefined\n ? { expectedInstallationVersion: args.expectedInstallationVersion as number }\n : {}),\n reason: args.reason as string,\n });\n return {\n isError: false,\n content: [{ type: \"text\", text: JSON.stringify(output) }],\n structuredContent: output,\n };\n },\n };\n}\n","import { posix } from \"node:path\";\nimport type { SandboxChannelAService } from \"@opengeni/runtime/sandbox\";\nimport {\n assertSkillRelativePath,\n buildPortableSkillArtifact,\n PORTABLE_SKILL_MAX_FILES,\n PORTABLE_SKILL_MAX_FILE_BYTES,\n PORTABLE_SKILL_MAX_TOTAL_BYTES,\n type SkillTextFile,\n} from \"@opengeni/runtime/skill-library\";\n\ntype SkillFileSystem = Pick<SandboxChannelAService, \"fsList\" | \"fsRead\" | \"fsWrite\" | \"fsMkdir\">;\nconst maxTraversalEntries = 1024;\n\n/** Reuse the host's cancellation and workspace-mutation authority for each filesystem operation. */\nexport function guardSkillFilesystem(\n fs: SkillFileSystem,\n authority: {\n assertActive: () => void;\n runMutation: <T>(operation: () => Promise<T>) => Promise<T>;\n },\n): SkillFileSystem {\n const read = <T>(operation: () => Promise<T>): Promise<T> => {\n authority.assertActive();\n return operation();\n };\n const write = <T>(operation: () => Promise<T>): Promise<T> => {\n authority.assertActive();\n return authority.runMutation(() => read(operation));\n };\n return {\n fsList: (request) => read(() => fs.fsList(request)),\n fsRead: (request) => read(() => fs.fsRead(request)),\n fsWrite: (request) => write(() => fs.fsWrite(request)),\n fsMkdir: (request) => write(() => fs.fsMkdir(request)),\n };\n}\n\n/** Caller supplies an authorized live filesystem and a fresh workspace-relative target. */\nexport async function checkoutSkillDirectory(\n fs: SkillFileSystem,\n directory: string,\n files: readonly SkillTextFile[],\n): Promise<{ directory: string; fileCount: number }> {\n assertSkillRelativePath(directory);\n const artifact = buildPortableSkillArtifact(files);\n const parent = posix.dirname(directory);\n if (parent !== \".\") await fs.fsMkdir({ path: parent, recursive: true });\n // Never overwrite an earlier checkout (which may now contain the user's edits).\n await fs.fsMkdir({ path: directory, recursive: false });\n for (const file of artifact.files) {\n const result = await fs.fsWrite({\n path: `${directory}/${file.path}`,\n content: file.content,\n encoding: \"utf8\",\n overwrite: false,\n createParents: true,\n });\n if (result.sizeBytes !== new TextEncoder().encode(file.content).byteLength) {\n throw new Error(`Skill checkout wrote an unexpected byte count: ${file.path}`);\n }\n }\n return { directory, fileCount: artifact.files.length };\n}\n\n/**\n * Read a folder through existing structured filesystem services, never via model\n * arguments. The caller owns workspace confinement and the final governed save.\n * This operation does not execute scripts or activate the resulting artifact.\n */\nexport async function readSkillDirectory(fs: SkillFileSystem, directory: string) {\n assertSkillRelativePath(directory);\n const pending = [directory];\n const seen = new Set<string>(pending);\n const files: SkillTextFile[] = [];\n let entries = 0;\n let totalBytes = 0;\n while (pending.length) {\n const current = pending.shift()!;\n const listing = await fs.fsList({\n path: current,\n depth: 1,\n maxEntries: maxTraversalEntries + 1,\n includeHidden: true,\n });\n if (listing.root.type !== \"dir\" || listing.root.path !== current) {\n throw new Error(`Expected a real Skill directory: ${current}`);\n }\n if (listing.truncated || listing.root.truncated || !listing.root.children) {\n throw new Error(`Skill directory listing is incomplete: ${current}`);\n }\n for (const entry of listing.root.children) {\n assertSkillRelativePath(entry.path);\n if (posix.dirname(entry.path) !== current || posix.basename(entry.path) !== entry.name) {\n throw new Error(\"Skill directory listing returned a path outside the requested directory.\");\n }\n if (seen.has(entry.path)) throw new Error(`Duplicate Skill directory entry: ${entry.path}`);\n seen.add(entry.path);\n if (++entries > maxTraversalEntries) throw new Error(\"Skill directory has too many entries.\");\n if (entry.type === \"dir\") {\n pending.push(entry.path);\n continue;\n }\n if (entry.type !== \"file\") throw new Error(`Unsupported Skill file type: ${entry.path}`);\n if (files.length >= PORTABLE_SKILL_MAX_FILES) throw new Error(\"Skill has too many files.\");\n if (entry.sizeBytes !== null && entry.sizeBytes > PORTABLE_SKILL_MAX_FILE_BYTES) {\n throw new Error(`Skill file exceeds the size limit: ${entry.path}`);\n }\n const read = await fs.fsRead({\n path: entry.path,\n encoding: \"base64\",\n maxBytes: PORTABLE_SKILL_MAX_FILE_BYTES + 1,\n });\n if (read.truncated || read.sizeBytes > PORTABLE_SKILL_MAX_FILE_BYTES) {\n throw new Error(`Skill file exceeds the size limit: ${entry.path}`);\n }\n if (read.encoding !== \"base64\" || read.path !== entry.path) {\n throw new Error(`Invalid Skill file read response: ${entry.path}`);\n }\n const bytes = Buffer.from(read.content, \"base64\");\n if (bytes.byteLength !== read.sizeBytes) {\n throw new Error(`Invalid Skill file byte count: ${entry.path}`);\n }\n totalBytes += bytes.byteLength;\n if (totalBytes > PORTABLE_SKILL_MAX_TOTAL_BYTES)\n throw new Error(\"Skill exceeds the total size limit.\");\n let content: string;\n try {\n content = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(bytes);\n } catch {\n throw new Error(`Skill file is not valid UTF-8 text: ${entry.path}`);\n }\n files.push({ path: entry.path.slice(directory.length + 1), content });\n }\n }\n return buildPortableSkillArtifact(files);\n}\n","import type { AttemptToolDefinition } from \"@opengeni/codemode\";\nimport type { SandboxChannelAService } from \"@opengeni/runtime/sandbox\";\nimport type { SkillTextFile } from \"@opengeni/runtime/skill-library\";\nimport { checkoutSkillDirectory, readSkillDirectory } from \"./skill-transfer\";\nimport type { SkillSaveReceipt, SkillSaveRequest } from \"./skill-save\";\n\ntype SkillFileSystem = Pick<SandboxChannelAService, \"fsList\" | \"fsRead\" | \"fsWrite\" | \"fsMkdir\">;\n\nexport function createSkillCheckoutAttemptToolDefinition(input: {\n authorize: () => Promise<void>;\n load: (skill: string) => Promise<{\n skillId: string;\n revisionId: string | null;\n scopeVersion: number | null;\n files: readonly SkillTextFile[];\n }>;\n filesystem: () => Promise<SkillFileSystem>;\n}): AttemptToolDefinition {\n return {\n identity: { serverId: \"opengeni\", toolName: \"skill_checkout\" },\n modelName: \"skill_checkout\",\n codemodePath: [\"opengeni\", \"skill_checkout\"],\n title: \"Check out Skill files\",\n description:\n \"Copy a Skill to a fresh sandbox-relative directory for execution or larger edits. Starts the sandbox if needed. Never overwrites an existing directory and does not publish changes. Retain the returned revision and scope version for skill_publish. Use skill_read for ordinary reading without a sandbox.\",\n inputSchema: {\n type: \"object\",\n properties: {\n skill: { type: \"string\", minLength: 1, maxLength: 512 },\n directory: { type: \"string\", minLength: 1, maxLength: 1024 },\n },\n required: [\"skill\", \"directory\"],\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n source: \"opengeni\",\n approval: \"none\",\n execute: async (args) => {\n await input.authorize();\n const skill = await input.load(args.skill as string);\n const copied = await checkoutSkillDirectory(\n await input.filesystem(),\n args.directory as string,\n skill.files,\n );\n const output = {\n ...copied,\n skillId: skill.skillId,\n revisionId: skill.revisionId,\n scopeVersion: skill.scopeVersion,\n };\n return {\n isError: false,\n content: [{ type: \"text\", text: JSON.stringify(output) }],\n structuredContent: output,\n };\n },\n };\n}\n\nexport function createSkillPublishAttemptToolDefinition(input: {\n authorize: () => Promise<void>;\n filesystem: () => Promise<SkillFileSystem>;\n save: (request: SkillSaveRequest) => Promise<SkillSaveReceipt>;\n}): AttemptToolDefinition {\n return {\n identity: { serverId: \"opengeni\", toolName: \"skill_publish\" },\n modelName: \"skill_publish\",\n codemodePath: [\"opengeni\", \"skill_publish\"],\n title: \"Publish Skill directory\",\n description:\n \"Save a complete sandbox Skill directory through the same Learning-controlled service as skill_save. Reads UTF-8 text files directly; do not serialize the directory into arguments. Files missing from the directory are removed from the new revision. Supply the checkout revision and scope version; stale edits are refused. The result reports whether the change is live or pending approval.\",\n inputSchema: {\n type: \"object\",\n properties: {\n operationId: { type: \"string\", format: \"uuid\" },\n skillId: { type: \"string\", format: \"uuid\" },\n expectedRevisionId: { type: [\"string\", \"null\"], format: \"uuid\" },\n expectedScopeVersion: { type: \"integer\", minimum: 0 },\n directory: { type: \"string\", minLength: 1, maxLength: 1024 },\n reason: { type: \"string\", minLength: 1, maxLength: 2000 },\n },\n required: [\n \"operationId\",\n \"skillId\",\n \"expectedRevisionId\",\n \"expectedScopeVersion\",\n \"directory\",\n \"reason\",\n ],\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n source: \"opengeni\",\n approval: \"none\",\n execute: async (args) => {\n await input.authorize();\n const artifact = await readSkillDirectory(await input.filesystem(), args.directory as string);\n const output = await input.save({\n operationId: args.operationId as string,\n skillId: args.skillId as string,\n expectedRevisionId: args.expectedRevisionId as string | null,\n expectedScopeVersion: args.expectedScopeVersion as number,\n files: artifact.files,\n reason: args.reason as string,\n });\n return {\n isError: false,\n content: [{ type: \"text\", text: JSON.stringify(output) }],\n structuredContent: output,\n };\n },\n };\n}\n","import { loadNativeToolSkillArtifacts } from \"@opengeni/runtime\";\nimport { loadSkillManagementSkill } from \"@opengeni/runtime/skill-library\";\nimport type { BundledSkillId } from \"@opengeni/contracts\";\n\nexport type BundledSkillConfiguration = {\n /** Already resolved names, not discovered schemas or an attempt catalog. */\n firstPartyTools: readonly string[];\n videoGenerationEnabled: boolean;\n bundledSkillIds?: readonly BundledSkillId[] | undefined;\n};\n\n/** Individual ordinary-code defaults, evaluated without async tool preparation. */\nexport function configuredBundledSkillNames(context: BundledSkillConfiguration): string[] {\n const tools = new Set(context.firstPartyTools);\n const artifacts = () => tools.has(\"editable_artifact_list\") && tools.has(\"editable_artifact_get\");\n const definitions = [\n { name: \"opengeni-skills\", include: () => true },\n { name: \"opengeni-projects\", include: () => true },\n { name: \"opengeni-documents\", include: artifacts },\n { name: \"opengeni-spreadsheets\", include: artifacts },\n { name: \"opengeni-presentations\", include: artifacts },\n {\n name: \"opengeni-sites\",\n include: () => tools.has(\"artifacts_create\") && tools.has(\"artifacts_publish\"),\n },\n { name: \"opengeni-video-generation\", include: () => context.videoGenerationEnabled },\n ];\n return definitions\n .filter(\n (definition) =>\n definition.include() &&\n (context.bundledSkillIds === undefined ||\n context.bundledSkillIds.includes(`builtin:${definition.name}` as BundledSkillId)),\n )\n .map((definition) => definition.name);\n}\n\nexport function loadConfiguredBundledSkills(context: BundledSkillConfiguration) {\n const names = new Set(configuredBundledSkillNames(context));\n const artifacts = loadNativeToolSkillArtifacts({\n projects: names.has(\"opengeni-projects\"),\n editableArtifacts: [\n \"opengeni-documents\",\n \"opengeni-spreadsheets\",\n \"opengeni-presentations\",\n ].some((name) => names.has(name)),\n sites: names.has(\"opengeni-sites\"),\n videoGeneration: names.has(\"opengeni-video-generation\"),\n });\n return [...artifacts, ...(names.has(\"opengeni-skills\") ? [loadSkillManagementSkill()] : [])]\n .filter((artifact) => names.has(artifact.name))\n .map((artifact) => ({ id: `builtin:${artifact.name}`, artifact }));\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { CredentialAuthNeededPayload, ResourceRef } from \"@opengeni/contracts\";\nimport {\n applyGitHubRepositoryBindings,\n listGitHubRepositoryBindingCandidates,\n resolveGitHubRepositoryBindings,\n unboundGitHubRepositoryResources,\n type GitHubRepositoryBinding,\n type GitHubRepositoryBindingCandidate,\n type GitHubRepositoryBindingLookup,\n type GitHubRepositoryBindingResolution,\n} from \"@opengeni/core\";\nimport type { Database } from \"@opengeni/db\";\nimport {\n createGitHubAppInstallationRepositoryLookup,\n githubAppMissingSettings,\n} from \"@opengeni/github\";\n\n/**\n * Turn-time GitHub App binding resolution for bare repository URIs.\n *\n * The web composer and the MCP repository catalog stamp\n * `githubInstallationId`/`githubRepositoryId` on every bound repository, but an\n * API caller, an older session, or an agent-spawned child may still carry a\n * bare `https://github.com/<owner>/<repo>` resource. The workspace allowlist\n * stores repository ids only, so the worker (which already talks to GitHub to\n * mint the sandbox token) resolves the URI here: the owner selects the\n * workspace's auditable installation(s) from Postgres, one server-side\n * metadata-read supplies GitHub's repository id, and the allowlist decides.\n * Exactly one allowlisted match stamps the ids for this turn's in-memory\n * resources; every other case keeps the resource bare (anonymous clone, as\n * before) and reports a visible warning. Nothing here is durable and nothing\n * can fail the turn.\n */\n\n/** Process-local lookup memo: recovered turns and sibling children reuse it. */\nexport const GITHUB_REPOSITORY_LOOKUP_CACHE_TTL_MS = 10 * 60_000;\nconst GITHUB_REPOSITORY_LOOKUP_CACHE_MAX_ENTRIES = 4_096;\n\ntype LookupCacheEntry = { value: { id: number } | null; expiresAt: number };\n\nexport type GitHubRepositoryLookupCache = {\n get: (key: string, now: number) => LookupCacheEntry | undefined;\n set: (key: string, entry: LookupCacheEntry) => void;\n clear: () => void;\n};\n\nexport function createGitHubRepositoryLookupCache(\n maxEntries = GITHUB_REPOSITORY_LOOKUP_CACHE_MAX_ENTRIES,\n): GitHubRepositoryLookupCache {\n const entries = new Map<string, LookupCacheEntry>();\n return {\n get(key, now) {\n const entry = entries.get(key);\n if (!entry) return undefined;\n if (entry.expiresAt <= now) {\n entries.delete(key);\n return undefined;\n }\n return entry;\n },\n set(key, entry) {\n entries.delete(key);\n entries.set(key, entry);\n while (entries.size > maxEntries) {\n const oldest = entries.keys().next().value;\n if (oldest === undefined) break;\n entries.delete(oldest);\n }\n },\n clear() {\n entries.clear();\n },\n };\n}\n\nconst defaultLookupCache = createGitHubRepositoryLookupCache();\nconst defaultWarningCache = createGitHubRepositoryLookupCache();\n\nfunction lookupCacheKey(\n workspaceId: string,\n input: { installationId: number; owner: string; name: string },\n): string {\n return `${workspaceId}\\u0000${input.installationId}\\u0000${input.owner.toLowerCase()}/${input.name.toLowerCase()}`;\n}\n\n/**\n * Wrap a live lookup with the process-local TTL memo. Successful ids and\n * negative (not visible through this installation) answers are both cached;\n * failures are not, so a GitHub blip is retried on the next turn.\n */\nexport function cachedGitHubRepositoryBindingLookup(input: {\n workspaceId: string;\n lookup: GitHubRepositoryBindingLookup;\n cache?: GitHubRepositoryLookupCache;\n now?: () => number;\n ttlMs?: number;\n}): GitHubRepositoryBindingLookup {\n const cache = input.cache ?? defaultLookupCache;\n const now = input.now ?? Date.now;\n const ttlMs = input.ttlMs ?? GITHUB_REPOSITORY_LOOKUP_CACHE_TTL_MS;\n return async (request) => {\n const key = lookupCacheKey(input.workspaceId, request);\n const cached = cache.get(key, now());\n if (cached) return cached.value;\n const value = await input.lookup(request);\n cache.set(key, { value: value ? { id: value.id } : null, expiresAt: now() + ttlMs });\n return value;\n };\n}\n\nexport type TurnGitHubRepositoryBindings = {\n resources: ResourceRef[];\n bindings: Map<string, GitHubRepositoryBinding>;\n resolutions: GitHubRepositoryBindingResolution[];\n warnings: CredentialAuthNeededPayload[];\n /** Apply the same bindings to a sibling resource list (runtime resources). */\n apply: (resources: readonly ResourceRef[]) => ResourceRef[];\n};\n\nexport async function resolveTurnGitHubRepositoryBindings(input: {\n db: Database;\n settings: Settings;\n workspaceId: string;\n resources: readonly ResourceRef[];\n /** Test seam; defaults to the workspace's auditable bindings under RLS. */\n listCandidates?: (\n db: Database,\n workspaceId: string,\n ) => Promise<GitHubRepositoryBindingCandidate[]>;\n /** Test seam; defaults to one live GitHub App lookup client per call. */\n lookup?: GitHubRepositoryBindingLookup;\n /** Test seam; defaults to the process-local TTL memo. */\n lookupCache?: GitHubRepositoryLookupCache;\n}): Promise<TurnGitHubRepositoryBindings> {\n const passthrough = (): TurnGitHubRepositoryBindings => ({\n resources: [...input.resources],\n bindings: new Map(),\n resolutions: [],\n warnings: [],\n apply: (resources) => [...resources],\n });\n if (unboundGitHubRepositoryResources(input.resources).length === 0) {\n return passthrough();\n }\n let lookup = input.lookup;\n if (!lookup) {\n // Without App signing credentials no installation token could be minted\n // for a resolved id anyway, so a bare repository stays anonymous.\n if (githubAppMissingSettings(input.settings).length > 0) {\n return passthrough();\n }\n const live = createGitHubAppInstallationRepositoryLookup(input.settings);\n lookup = async (request) => {\n const repository = await live(request);\n return repository ? { id: repository.id } : null;\n };\n }\n const candidates = await (input.listCandidates ?? listGitHubRepositoryBindingCandidates)(\n input.db,\n input.workspaceId,\n );\n if (candidates.length === 0) {\n return passthrough();\n }\n const resolved = await resolveGitHubRepositoryBindings({\n resources: input.resources,\n candidates,\n lookup: cachedGitHubRepositoryBindingLookup({\n workspaceId: input.workspaceId,\n lookup,\n ...(input.lookupCache ? { cache: input.lookupCache } : {}),\n }),\n });\n return {\n resources: resolved.resources,\n bindings: resolved.bindings,\n resolutions: resolved.resolutions,\n warnings: resolved.resolutions.flatMap(\n (resolution) => gitHubRepositoryBindingWarning(resolution) ?? [],\n ),\n apply: (resources) => applyGitHubRepositoryBindings(resources, resolved.bindings),\n };\n}\n\n/**\n * The visible warning for a bound-but-unusable repository. An unbound owner\n * is the ordinary anonymous public clone and produces no warning; a resolved\n * repository needs none.\n */\nexport function gitHubRepositoryBindingWarning(\n resolution: GitHubRepositoryBindingResolution,\n): CredentialAuthNeededPayload | null {\n const repository = `${resolution.owner}/${resolution.name}`;\n switch (resolution.outcome.status) {\n case \"resolved\":\n case \"unbound\":\n return null;\n case \"not_allowlisted\":\n return {\n credentialClass: \"run\",\n providerDomain: \"github.com\",\n reason: \"insufficient_scope\",\n resource: resolution.uri,\n message: `GitHub repository ${repository} is not in the repository allowlist of the workspace's GitHub App installation for ${resolution.owner}. The sandbox clones it anonymously and cannot push or use gh until the repository is added to that installation.`,\n };\n case \"ambiguous\":\n return {\n credentialClass: \"run\",\n providerDomain: \"github.com\",\n reason: \"insufficient_scope\",\n resource: resolution.uri,\n message: `GitHub repository ${repository} is allowlisted by more than one GitHub App installation in this workspace (${resolution.outcome.installationIds.join(\", \")}). Select it with an explicit installation, or unlink the duplicate binding, to receive a scoped token.`,\n };\n case \"unavailable\":\n return {\n credentialClass: \"run\",\n providerDomain: \"github.com\",\n reason: \"refresh_failed\",\n resource: resolution.uri,\n message: `GitHub repository ${repository} could not be resolved against the workspace's GitHub App installation (${resolution.outcome.message}). The sandbox clones it anonymously for this turn.`,\n };\n }\n}\n\nexport type ApplyTurnGitHubRepositoryBindingsInput = {\n db: Database;\n settings: Settings;\n workspaceId: string;\n sessionId: string;\n activeSandboxBackend: Settings[\"sandboxBackend\"] | undefined;\n claimedTurnResources: readonly ResourceRef[];\n claimedRuntimeResources: readonly ResourceRef[];\n /** Publishes one attempt-fenced session event batch. */\n publish: (\n events: Array<{ type: \"credential.auth_needed\"; payload: CredentialAuthNeededPayload }>,\n ) => Promise<void>;\n /** Operational log for a resolution that threw; the turn proceeds bare. */\n warn: (message: string, fields: Record<string, string>) => void;\n /** Test seam for the resolver itself. */\n resolve?: typeof resolveTurnGitHubRepositoryBindings;\n /** Test seam for the per-session warning dedupe memo. */\n warningCache?: GitHubRepositoryLookupCache;\n now?: () => number;\n};\n\n/**\n * The run.ts wiring in one testable seam: skip for a Connected Machine,\n * proceed bare when resolution throws, stamp both the turn and runtime\n * resource lists from one resolution, and publish a bound-but-unusable\n * warning once per session and URI within the memo window (the resolution\n * itself already runs once per attempt).\n */\nexport async function applyTurnGitHubRepositoryBindings(\n input: ApplyTurnGitHubRepositoryBindingsInput,\n): Promise<{ turnResources: ResourceRef[]; runtimeResources: ResourceRef[] }> {\n const passthrough = {\n turnResources: [...input.claimedTurnResources],\n runtimeResources: [...input.claimedRuntimeResources],\n };\n if (input.activeSandboxBackend === \"selfhosted\") {\n return passthrough;\n }\n let resolved: TurnGitHubRepositoryBindings;\n try {\n resolved = await (input.resolve ?? resolveTurnGitHubRepositoryBindings)({\n db: input.db,\n settings: input.settings,\n workspaceId: input.workspaceId,\n resources: input.claimedTurnResources,\n });\n } catch (error) {\n input.warn(\"GitHub repository binding resolution skipped\", {\n errorClass: error instanceof Error ? error.name : \"Error\",\n errorCode: \"github_repository_binding_resolution_failed\",\n origin: \"worker\",\n });\n return passthrough;\n }\n const now = input.now ?? Date.now;\n const warningCache = input.warningCache ?? defaultWarningCache;\n const warnings = resolved.warnings.filter((payload) => {\n const key = `${input.sessionId}\\u0000${payload.resource ?? \"\"}\\u0000${payload.reason}`;\n if (warningCache.get(key, now())) return false;\n warningCache.set(key, {\n value: null,\n expiresAt: now() + GITHUB_REPOSITORY_LOOKUP_CACHE_TTL_MS,\n });\n return true;\n });\n if (warnings.length > 0) {\n await input.publish(\n warnings.map((payload) => ({ type: \"credential.auth_needed\" as const, payload })),\n );\n }\n return {\n turnResources: resolved.resources,\n runtimeResources: resolved.apply(input.claimedRuntimeResources),\n };\n}\n","import {\n selectXaiCredentialForUse,\n materializeXaiCredentialForRun,\n resolveXaiProviderAccountAuthoritySnapshotForAcceptance,\n getXaiSessionAccountPin,\n setXaiSessionAccountPin,\n getWorkspaceVideoGenerationPolicy,\n loadWorkspaceVercelAiGatewayCredentialLease,\n getExternalLinkTurnAuthorization,\n getSessionTurnForAttempt,\n} from \"@opengeni/db\";\nimport {\n formatSkillCatalog,\n type AttemptConnectorActionBinding,\n type BuildAgentOptions,\n type ConnectorActionPolicyHooks,\n type SandboxFileDownload,\n type TurnSandboxCommandSession,\n} from \"@opengeni/runtime\";\nimport {\n serviceTierForLatencyMode,\n environmentsEncryptionKeyBytes,\n WORKSPACE_GATEWAY_PROVIDER_ID,\n resolveModelProvider,\n type Settings,\n} from \"@opengeni/config\";\nimport { type CodexRequestContext } from \"@opengeni/codex\";\nimport { executeXaiSubscriptionImageGeneration } from \"../xai-image-generation\";\nimport { rigProviderImageContentHash, videoGenerationCapabilitiesForPolicy } from \"@opengeni/core\";\nimport {\n admitVideoGenerationRequest,\n managedVideoGenerationCredentialLease,\n xaiVideoGenerationCredentialLease,\n type VideoGenerationCredentialLease,\n} from \"../video-generation-admission\";\nimport { VideoReferenceInputError } from \"../video-reference-staging\";\nimport { rigProviderImageSourceImage } from \"../packs\";\nimport type { TurnActivityServices as ActivityServices, RunAgentTurnInput } from \"../types\";\nimport { recordTurnStartupPhase } from \"../../observability-metrics\";\nimport { summarizeCompanyBrainContributions } from \"../../model-context-contributions\";\nimport { createTurnCredentialLeases } from \"./credential-leases\";\nimport { createTurnMediaArtifacts } from \"./media-artifacts\";\nimport { executeGatewayImageGeneration } from \"../gateway-image-generation\";\nimport { executeCodexImageGeneration } from \"../codex-image-generation\";\nimport {\n ImageGenerationReferenceError,\n resolveImageGenerationReferencesForTool,\n} from \"../image-generation-references\";\nimport { SandboxChannelAService } from \"@opengeni/runtime/sandbox\";\nimport { sandboxRunAs } from \"@opengeni/runtime\";\nimport { VideoGenerationRejectedResult } from \"@opengeni/contracts\";\n\nimport {\n structuredToolTransportForTurn,\n hostedWebSearchForTurn,\n connectedSubscriptionImageGenerationAuthority,\n} from \"./tool-policy\";\nimport type { ClaimTurnOk } from \"./claim\";\nimport type { GovernanceModelOk } from \"./governance-model\";\nimport type { CompactionPrepOk } from \"./compaction-prep\";\nimport type { runtimeResourcesForTurn } from \"./file-resources\";\nimport type { sandboxArtifactRuntimeAdmission } from \"./sandbox-route\";\nimport type {\n loadWorkspaceEnvironmentForRunWithCredentials,\n sandboxEnvironmentForRun,\n} from \"../environment\";\nimport type {\n AttemptIdentityState,\n EventingState,\n ProviderTurnState,\n SandboxRuntimeState,\n} from \"./turn-context\";\nimport { SESSION_TITLE_MODEL_TOOL_NAME } from \"./session-title\";\nimport { resolveTurnSandboxAccess } from \"./turn-sandbox-access\";\nimport { resolveVideoReferenceSandboxAccess } from \"./video-reference-sandbox\";\n\nexport type BuildTurnAgentDeps = {\n skillCatalog: NonNullable<BuildAgentOptions[\"skillCatalog\"]>;\n input: RunAgentTurnInput;\n db: ActivityServices[\"db\"];\n runtime: ActivityServices[\"runtime\"];\n objectStorage: ActivityServices[\"objectStorage\"];\n observability: ActivityServices[\"observability\"];\n cancellationSignal: AbortSignal | undefined;\n runtimeCancellationSignal: AbortSignal | undefined;\n eventing: EventingState;\n attempt: AttemptIdentityState;\n sandboxState: SandboxRuntimeState;\n providerTurn: ProviderTurnState;\n media: ReturnType<typeof createTurnMediaArtifacts>;\n leases: ReturnType<typeof createTurnCredentialLeases>;\n turn: ClaimTurnOk[\"turn\"];\n session: ClaimTurnOk[\"session\"];\n fileAuthoritySubjectId: ClaimTurnOk[\"fileAuthoritySubjectId\"];\n capabilitySettings: ClaimTurnOk[\"capabilitySettings\"];\n humanInputResume: ClaimTurnOk[\"humanInputResume\"];\n turnExecutionPolicy: ClaimTurnOk[\"turnExecutionPolicy\"];\n runSettings: GovernanceModelOk[\"runSettings\"];\n logicalSandboxSettings: GovernanceModelOk[\"logicalSandboxSettings\"];\n verifiedRigProviderImageId: GovernanceModelOk[\"verifiedRigProviderImageId\"];\n resolvedModel: GovernanceModelOk[\"resolvedModel\"];\n nativeImageProviderBinding: GovernanceModelOk[\"nativeImageProviderBinding\"];\n lazyToolTransport: GovernanceModelOk[\"lazyToolTransport\"];\n modelInputPolicy: GovernanceModelOk[\"modelInputPolicy\"];\n supportsImageInput: GovernanceModelOk[\"supportsImageInput\"];\n agentHumanInputEnabled: GovernanceModelOk[\"agentHumanInputEnabled\"];\n workspaceAgentInstructions: GovernanceModelOk[\"workspaceAgentInstructions\"];\n workspaceGovernance: GovernanceModelOk[\"workspaceGovernance\"];\n structuredWorkspacePolicyActive: GovernanceModelOk[\"structuredWorkspacePolicyActive\"];\n workspaceMemory: GovernanceModelOk[\"workspaceMemory\"];\n rigVersion: GovernanceModelOk[\"rigVersion\"];\n rigName: GovernanceModelOk[\"rigName\"];\n buildCompanyBrainContributionReceiptFor: GovernanceModelOk[\"buildCompanyBrainContributionReceiptFor\"];\n promptCacheKey: CompactionPrepOk[\"promptCacheKey\"];\n workspaceVariableSet: Awaited<ReturnType<typeof loadWorkspaceEnvironmentForRunWithCredentials>>;\n runtimeResources: ReturnType<typeof runtimeResourcesForTurn>;\n sandboxEnvironment: Record<string, string>;\n sandboxArtifactRuntime: ReturnType<typeof sandboxArtifactRuntimeAdmission>;\n sandboxGitToken: string | undefined;\n sandboxGitTokens: Record<string, string> | undefined;\n sandboxGitCredentialBindings: Awaited<\n ReturnType<typeof sandboxEnvironmentForRun>\n >[\"gitCredentialBindings\"];\n sandboxCodemodeToken: string | undefined;\n fileResourceDownloads: SandboxFileDownload[];\n attemptConnectorActionBindings: readonly AttemptConnectorActionBinding[];\n connectorActionPolicy: ConnectorActionPolicyHooks;\n trigger: ClaimTurnOk[\"trigger\"];\n preparationIndependentToolNames: readonly string[];\n videoGenerationAcceptancesByCallId: Map<string, { operationId: string; requestDigest: string }>;\n activeSandboxBackend: Settings[\"sandboxBackend\"] | undefined;\n groupBoxBackend: Settings[\"sandboxBackend\"];\n postToolPreparationStartedAt: number;\n codexContext: CodexRequestContext | null;\n};\n\nexport async function buildTurnAgent(deps: BuildTurnAgentDeps) {\n const {\n input,\n db,\n runtime,\n objectStorage,\n observability,\n cancellationSignal,\n runtimeCancellationSignal,\n eventing,\n sandboxState,\n providerTurn,\n media,\n leases,\n turn,\n session,\n fileAuthoritySubjectId,\n capabilitySettings,\n humanInputResume,\n turnExecutionPolicy,\n runSettings,\n logicalSandboxSettings,\n verifiedRigProviderImageId,\n resolvedModel,\n nativeImageProviderBinding,\n lazyToolTransport,\n modelInputPolicy,\n supportsImageInput,\n agentHumanInputEnabled,\n workspaceAgentInstructions,\n workspaceGovernance,\n structuredWorkspacePolicyActive,\n workspaceMemory,\n rigVersion,\n rigName,\n buildCompanyBrainContributionReceiptFor,\n promptCacheKey,\n workspaceVariableSet,\n runtimeResources,\n sandboxEnvironment,\n sandboxArtifactRuntime,\n sandboxGitToken,\n sandboxGitTokens,\n sandboxGitCredentialBindings,\n sandboxCodemodeToken,\n fileResourceDownloads,\n attemptConnectorActionBindings,\n connectorActionPolicy,\n trigger,\n preparationIndependentToolNames,\n videoGenerationAcceptancesByCallId,\n activeSandboxBackend,\n groupBoxBackend,\n postToolPreparationStartedAt,\n codexContext,\n } = deps;\n const preparedTools = eventing.preparedTools!;\n\n const missingSessionTitleHint = preparationIndependentToolNames.includes(\n SESSION_TITLE_MODEL_TOOL_NAME,\n );\n // Clone-onto-real-disk hazard (Case B). A session keeps its CLOUD HOME\n // backend (runSettings.sandboxBackend, e.g. \"modal\") but its ACTIVE sandbox\n // may have been swapped to a connected machine (active_sandbox_id → a\n // selfhosted lease). buildAgent's repository-clone lifecycle hook keys off\n // the EFFECTIVE backend; if we let it default to the home backend it would\n // `git clone` a private GitHub-App repo onto the user's REAL disk. So pass\n // \"selfhosted\" through when the active sandbox is a connected machine;\n // otherwise leave it undefined so buildAgent defaults to the home backend\n // (byte-for-byte unchanged cloud behavior). `activeSandboxBackend` was\n // resolved ONCE at turn start (above) via resolveActiveSandboxBackend (the\n // tested gate) and is reused here — resolving once is correct because the\n // clone hook runs at beforeAgentStart, so a mid-turn swap can't affect it.\n // buildAgent's option key is `workspaceEnvironment` (internal runtime\n // symbol; the product concept is a variable set). Built as a TYPED const —\n // a direct literal assignment to Pick<BuildAgentOptions,...> IS excess-\n // property-checked, so a wrong key fails tsc. A bare conditional spread\n // inside the options literal is NOT checked, which is exactly how the M1\n // key regression (workspaceVariableSet vs workspaceEnvironment) slipped\n // through and silently dropped the variable-set instructions block.\n const workspaceEnvironmentOption: Pick<BuildAgentOptions, \"workspaceEnvironment\"> =\n workspaceVariableSet\n ? {\n workspaceEnvironment: {\n name: workspaceVariableSet.name,\n description: workspaceVariableSet.description,\n variableNames: Object.keys(workspaceVariableSet.values),\n },\n }\n : {};\n const hostedWebSearch = hostedWebSearchForTurn(resolvedModel, runSettings.webSearchEnabled);\n const resolveImageReferences = async (\n references: Parameters<typeof resolveImageGenerationReferencesForTool>[0][\"references\"],\n ) =>\n await resolveImageGenerationReferencesForTool({\n db,\n objectStorage: objectStorage!,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: fileAuthoritySubjectId,\n references,\n readSandboxFile: async (path, maxBytes) => {\n const imageReferenceSandbox = await resolveTurnSandboxAccess(\n sandboxState,\n media.sdkOwnedSandboxSession,\n \"Sandbox image reference is unavailable\",\n );\n const relativePath = path.slice(\"/workspace/\".length);\n const referenceRunAs = sandboxRunAs(eventing.modelRunSettings);\n const channel = new SandboxChannelAService({\n session: imageReferenceSandbox.session,\n workspaceRoot: \"/workspace\",\n leaseEpoch: imageReferenceSandbox.leaseEpoch,\n ...(referenceRunAs ? { runAs: referenceRunAs } : {}),\n });\n const read = await channel.fsRead({\n path: relativePath,\n encoding: \"base64\",\n maxBytes,\n });\n if (read.truncated) {\n throw new ImageGenerationReferenceError(\n \"reference_too_large\",\n \"The sandbox image reference exceeds the per-image byte limit.\",\n );\n }\n return Uint8Array.from(Buffer.from(read.content, \"base64\"));\n },\n });\n const imageGenerationOption: Pick<BuildAgentOptions, \"imageGeneration\"> = (() => {\n // Never expose a paid image operation unless its permanent artifact can\n // be committed. Failing after provider execution would leave an\n // unrecoverable outcome-unknown operation with no user-visible image.\n if (!objectStorage) return {};\n if (nativeImageProviderBinding) {\n media.nativeImageGenerationRetention = {\n ...nativeImageProviderBinding,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n };\n return { imageGeneration: { kind: \"native_hosted\" } };\n }\n\n if (resolvedModel?.provider.kind === \"codex-subscription\") {\n const imageAuthority = connectedSubscriptionImageGenerationAuthority(\n codexContext,\n providerTurn.effectiveCodexCredentialId,\n );\n if (!imageAuthority) return {};\n return {\n imageGeneration: {\n kind: \"provider_adapter\",\n execute: async ({ prompt, references }, { toolCallId }) => {\n const referenceResolution = await resolveImageReferences(references);\n if (referenceResolution.status === \"rejected\") return referenceResolution.result;\n const receipt = await executeCodexImageGeneration({\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n toolCallId,\n prompt,\n references: referenceResolution.references,\n credentialId: imageAuthority.credentialId,\n codexContext: imageAuthority.credentialContext,\n ...(runtimeCancellationSignal ? { abortSignal: runtimeCancellationSignal } : {}),\n });\n media.rememberGeneratedImageCreatedThisTurn(receipt);\n await media.materializeGeneratedImage(receipt);\n return receipt;\n },\n },\n };\n }\n\n if (resolvedModel?.provider.kind === \"xai-subscription\") {\n const imageAuthority = connectedSubscriptionImageGenerationAuthority(\n providerTurn.xaiRequestContext,\n providerTurn.effectiveXaiCredentialId,\n );\n if (!imageAuthority) return {};\n return {\n imageGeneration: {\n kind: \"provider_adapter\",\n execute: async ({ prompt, references }, { toolCallId }) => {\n const referenceResolution = await resolveImageReferences(references);\n if (referenceResolution.status === \"rejected\") return referenceResolution.result;\n const receipt = await executeXaiSubscriptionImageGeneration({\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n toolCallId,\n prompt,\n references: referenceResolution.references,\n credentialId: imageAuthority.credentialId,\n xaiContext: imageAuthority.credentialContext,\n ...(runtimeCancellationSignal ? { abortSignal: runtimeCancellationSignal } : {}),\n });\n media.rememberGeneratedImageCreatedThisTurn(receipt);\n await media.materializeGeneratedImage(receipt);\n return receipt;\n },\n },\n };\n }\n\n const gatewayResolution = resolveModelProvider(\n capabilitySettings,\n WORKSPACE_GATEWAY_PROVIDER_ID,\n );\n const gateway = gatewayResolution?.provider;\n if (gateway?.kind !== \"vercel-gateway-workspace\" || !gateway.apiKey) return {};\n const gatewayApiKey = gateway.apiKey;\n return {\n imageGeneration: {\n kind: \"provider_adapter\",\n execute: async ({ prompt, references }, { toolCallId }) => {\n const referenceResolution = await resolveImageReferences(references);\n if (referenceResolution.status === \"rejected\") return referenceResolution.result;\n const receipt = await executeGatewayImageGeneration({\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n apiKey: gatewayApiKey,\n modelId: capabilitySettings.imageGenerationModel,\n prompt,\n references: referenceResolution.references,\n toolCallId,\n ...(runtimeCancellationSignal ? { abortSignal: runtimeCancellationSignal } : {}),\n });\n media.rememberGeneratedImageCreatedThisTurn(receipt);\n await media.materializeGeneratedImage(receipt);\n return receipt;\n },\n },\n };\n })();\n const videoGenerationPolicy = await getWorkspaceVideoGenerationPolicy(db, input.workspaceId);\n const videoGenerationEnabled =\n videoGenerationPolicy.defaultModelId !== null &&\n videoGenerationPolicy.enabledModelIds.length > 0;\n let videoGenerationCredential: VideoGenerationCredentialLease | null = null;\n if (objectStorage && videoGenerationEnabled) {\n if (videoGenerationPolicy.fundingSource === \"opengeni_credits\") {\n videoGenerationCredential = managedVideoGenerationCredentialLease(eventing.modelRunSettings);\n } else if (videoGenerationPolicy.fundingSource === \"workspace_gateway\") {\n const workspaceCredential = await loadWorkspaceVercelAiGatewayCredentialLease(\n db,\n eventing.modelRunSettings,\n input.workspaceId,\n );\n if (workspaceCredential) {\n videoGenerationCredential = {\n fundingSource: \"workspace_gateway\",\n ...workspaceCredential,\n };\n }\n } else if (videoGenerationPolicy.fundingSource === \"supergrok_subscription\") {\n const encryptionKey = environmentsEncryptionKeyBytes(eventing.modelRunSettings);\n const subjectId = leases.xai.subjectId ?? turn.initiatingHumanSubjectId;\n if (encryptionKey && subjectId) {\n const authoritySnapshot =\n providerTurn.xaiAuthoritySnapshot ??\n (await resolveXaiProviderAccountAuthoritySnapshotForAcceptance(db, {\n workspaceId: input.workspaceId,\n subjectId,\n }));\n const pin = await getXaiSessionAccountPin(db, {\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n });\n const selected = providerTurn.effectiveXaiCredentialId\n ? {\n credentialId: providerTurn.effectiveXaiCredentialId,\n rotationEnabled: providerTurn.xaiRotationEnabled,\n }\n : await selectXaiCredentialForUse(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n authoritySnapshot,\n shardKey: input.sessionId,\n pinnedCredentialId: pin?.pinnedCredentialId ?? null,\n pinSource:\n pin?.pinSource === \"manual\" || pin?.pinSource === \"policy\" ? pin.pinSource : null,\n });\n if (selected.credentialId) {\n if (\n selected.rotationEnabled &&\n pin?.pinSource !== \"manual\" &&\n pin?.pinnedCredentialId !== selected.credentialId\n ) {\n await setXaiSessionAccountPin(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n credentialId: selected.credentialId,\n pinSource: \"policy\",\n expectedVersion: pin?.version ?? null,\n }).catch((error: unknown) => {\n if (error instanceof Error && error.message === \"xAI session pin changed\") return;\n throw error;\n });\n }\n const credential = await materializeXaiCredentialForRun(db, {\n workspaceId: input.workspaceId,\n subjectId,\n credentialId: selected.credentialId,\n authoritySnapshot,\n encryptionKey,\n });\n videoGenerationCredential = xaiVideoGenerationCredentialLease({\n settings: eventing.modelRunSettings,\n credential,\n subjectId,\n authoritySnapshot,\n });\n }\n }\n }\n }\n const videoGenerationOption: Pick<BuildAgentOptions, \"videoGeneration\"> = (() => {\n if (\n !objectStorage ||\n eventing.modelRunSettings.sandboxBackend === \"none\" ||\n !videoGenerationCredential ||\n !videoGenerationEnabled\n ) {\n return {};\n }\n // Parse the frozen capability snapshot before advertising either tool.\n // Invalid or unsupported workspace policy therefore fails closed before\n // it can perturb the model's tool list.\n const capabilities = videoGenerationCapabilitiesForPolicy({\n policy: videoGenerationPolicy,\n credentialVersion: videoGenerationCredential.version,\n });\n return {\n videoGeneration: {\n capabilities: async () => capabilities,\n execute: async (toolInput, { toolCallId }) => {\n const referenceSandbox = await resolveVideoReferenceSandboxAccess(\n toolInput,\n sandboxState,\n media.sdkOwnedSandboxSession,\n );\n const fence = eventing.toolCancellationFenceRef.current;\n if (referenceSandbox && !fence) {\n throw new Error(\"Video reference command fence is unavailable\");\n }\n const runAs = sandboxRunAs(eventing.modelRunSettings);\n let accepted: Awaited<ReturnType<typeof admitVideoGenerationRequest>>;\n try {\n accepted = await admitVideoGenerationRequest({\n db,\n storage: objectStorage,\n settings: eventing.modelRunSettings,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n toolCallId,\n toolInput,\n policy: videoGenerationPolicy,\n credential: videoGenerationCredential,\n ...(referenceSandbox && fence\n ? {\n runCommand: async (command) =>\n await fence.runSandboxCommandStructured(\n referenceSandbox.session as TurnSandboxCommandSession,\n {\n ...command,\n ...(runAs ? { runAs } : {}),\n },\n ),\n }\n : {}),\n ...(runtimeCancellationSignal ? { signal: runtimeCancellationSignal } : {}),\n });\n } catch (error) {\n if (error instanceof VideoReferenceInputError) {\n return VideoGenerationRejectedResult.parse({\n schemaVersion: 1,\n status: \"rejected\",\n code: error.code,\n message: error.message,\n operationCreated: false,\n });\n }\n throw error;\n }\n videoGenerationAcceptancesByCallId.set(toolCallId, {\n operationId: accepted.operationId,\n requestDigest: accepted.requestDigest,\n });\n return accepted.receipt;\n },\n },\n };\n })();\n const serviceTier = serviceTierForLatencyMode(\n turnExecutionPolicy.providerId,\n turnExecutionPolicy.latencyMode,\n );\n const approvedToolCallId = approvedConnectorActionCallId(trigger);\n const modelVisibleSkillCatalogText = formatSkillCatalog(deps.skillCatalog);\n try {\n eventing.companyBrainContextContributions = summarizeCompanyBrainContributions(\n buildCompanyBrainContributionReceiptFor(modelVisibleSkillCatalogText),\n );\n } catch {\n // Contribution telemetry must never change model execution semantics.\n }\n recordTurnStartupPhase(observability, {\n phase: \"post_tool_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - postToolPreparationStartedAt) / 1_000,\n });\n const linkedToolAuthority = await getExternalLinkTurnAuthorization(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n },\n turn.id,\n );\n if (linkedToolAuthority && !linkedToolAuthority.authorized)\n throw new Error(\"Native identity link was revoked\");\n const agent = (() => {\n const agentConstructionStartedAt = performance.now();\n let agentConstructionOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n return runtime.buildAgent(eventing.modelRunSettings, runtimeResources, {\n ...(linkedToolAuthority\n ? {\n authorizeAttemptExecution: async () => {\n const current = await getSessionTurnForAttempt(\n db,\n input.workspaceId,\n input.sessionId,\n input.attemptId,\n );\n if (\n !current ||\n current.id !== turn.id ||\n current.executionGeneration !== turn.executionGeneration\n )\n throw new Error(\"The linked agent attempt is no longer authorized\");\n },\n }\n : {}),\n ...(preparedTools.inputWaitYield ? { inputWaitYield: preparedTools.inputWaitYield } : {}),\n reasoningEffort: turn.reasoningEffort,\n latencyMode: turnExecutionPolicy.latencyMode,\n ...(serviceTier ? { serviceTier } : {}),\n ...(humanInputResume ? { humanInputResponse: humanInputResume } : {}),\n humanInputEnabled: agentHumanInputEnabled,\n missingSessionTitleHint,\n sandboxEnvironment,\n ...(preparedTools.attemptToolCatalog\n ? { attemptToolCatalog: preparedTools.attemptToolCatalog }\n : {}),\n ...(sandboxArtifactRuntime.available ? { artifactRuntimeAvailable: true } : {}),\n ...(cancellationSignal ? { turnCancellationSignal: cancellationSignal } : {}),\n onToolCancellationFence: (fence) => {\n eventing.toolCancellationFenceRef.current = fence;\n },\n // TOKEN-BROKER (B1): forward the per-turn git token OFF-MANIFEST as the clone\n // seed. ONLY when the effective backend is NOT selfhosted (the connected\n // machine uses its own git creds — mirrors the skipGitHubToken gate above)\n // AND the mint actually produced a token (repo resources present). The runtime\n // seeds it to the box's token file before the repository-clone runs; it never\n // touches the box/agent manifest env.\n ...(activeSandboxBackend !== \"selfhosted\" && sandboxGitTokens\n ? { gitTokenSeeds: sandboxGitTokens }\n : {}),\n ...(activeSandboxBackend !== \"selfhosted\" && sandboxGitCredentialBindings\n ? { gitCredentialBindings: sandboxGitCredentialBindings }\n : {}),\n ...(activeSandboxBackend !== \"selfhosted\" && !sandboxGitTokens && sandboxGitToken\n ? { gitTokenSeed: sandboxGitToken }\n : {}),\n ...(sandboxCodemodeToken ? { codemodeAvailable: true } : {}),\n // Managed boxes receive the bearer through their protected per-session\n // token file. Connected Machines use transient per-exec delivery above,\n // so they must not run the file-seeding lifecycle hook.\n ...(activeSandboxBackend !== \"selfhosted\" && sandboxCodemodeToken\n ? {\n codemodeTokenSeed: sandboxCodemodeToken,\n codemodeTokenSessionId: input.sessionId,\n }\n : {}),\n ...(activeSandboxBackend ? { activeSandboxBackend } : {}),\n ...(activeSandboxBackend === \"selfhosted\" && sandboxState.machinePrimarySession\n ? { sandboxWorkspaceRoot: sandboxState.machinePrimarySession.workspaceRoot }\n : {}),\n fileResourceDownloads,\n mcpServers: preparedTools.mcpServers,\n resolvedMcpConnectionIds: preparedTools.resolvedMcpConnectionIds,\n connectorActionPolicy,\n attemptConnectorActionBindings,\n ...(approvedToolCallId ? { approvedToolCallId } : {}),\n // LIVE by-reference connector namespaces (fills during this turn's\n // codex_apps tools/list): the codex tool_search description reads it per\n // model call so the model sees the account's real connected sources.\n codexConnectorNamespaces: preparedTools.codexConnectorNamespaces,\n // Resolved-model routing + gating (legacy defaults when null). The model\n // is passed as the model *string* (agent.model = runSettings.openaiModel),\n // NOT a Model instance: an instance only survives the in-process\n // (\"none\") run, whereas the SandboxAgent/Modal path drops it and\n // re-resolves the model *name* through the global MultiProviderModelProvider\n // configureOpenAI installed — so registry models (Fireworks GLM) route to\n // their own client instead of 404ing against the built-in Azure/OpenAI\n // client. The gating still comes from the resolved provider: server-side\n // store/compaction follow the provider's compaction mode (registry\n // providers resolve to \"client\"); encrypted reasoning is only\n // round-tripped on the Responses wire API; hosted web search is attached\n // whenever the provider declares it runnable and is independent of the\n // session's MCP allow-list; the effective context window drives the\n // compaction threshold.\n hostedWebSearch,\n ...imageGenerationOption,\n ...videoGenerationOption,\n lazyToolTransport,\n ...(eventing.toolPreparationReady\n ? { toolPreparationReady: eventing.toolPreparationReady }\n : {}),\n preparationIndependentToolNames,\n supportsImageInput,\n inputFileMediaTypes: modelInputPolicy.inputFileMediaTypes,\n ...(resolvedModel\n ? {\n encryptedReasoning:\n resolvedModel.provider.api === \"responses\" &&\n runSettings.openaiReasoningEncryptedContent,\n contextWindowTokens:\n resolvedModel.configured.contextWindowTokens ?? runSettings.contextWindowTokens,\n // The ChatGPT/Codex backend rejects the SDK's HOSTED apply_patch\n // tool. Gateway Responses routes likewise expose ordinary function\n // tools, not OpenAI-hosted sandbox tools. Tell buildAgent to use\n // function apply_patch and wrap successful view_image results as\n // typed input_image content. Chat wires have no proven typed image\n // result transport and therefore receive no view_image tool.\n structuredToolTransport: structuredToolTransportForTurn(resolvedModel),\n ...(promptCacheKey ? { promptCacheKey } : {}),\n }\n : // LEGACY global-client fallback (resolveTurnModel returned null → the model\n // is not in the registry, served by the built-in OpenAI/Azure Responses\n // client).\n {\n promptCacheKey: input.sessionId,\n }),\n onRetainableSessionImageOutput: media.retainSessionImageAtToolBoundary,\n skillCatalog: deps.skillCatalog,\n ...(!structuredWorkspacePolicyActive && workspaceAgentInstructions\n ? { instructionsTemplate: workspaceAgentInstructions }\n : {}),\n ...(workspaceGovernance ? { workspaceGovernance } : {}),\n ...(workspaceMemory ? { workspaceMemory } : {}),\n // Per-session persona tier (session > workspace > deployment default).\n // Composed system-level AFTER the workspace persona so it refines it for\n // this one session; absent ⇒ byte-identical to today's composition.\n ...(session.instructions ? { sessionInstructions: session.instructions } : {}),\n ...workspaceEnvironmentOption,\n // RIG RUNTIME (M3): the doctrine block, the setup-script hook (only when\n // the frozen version carries a non-empty script), and the rig credential\n // hooks. All absent for a rig-less turn (byte-for-byte today).\n ...(rigVersion && rigName\n ? {\n rig: { name: rigName, version: rigVersion.version },\n ...(rigVersion.setupScript && rigVersion.setupScript.trim().length > 0\n ? {\n rigSetup: {\n rigId: session.rigId!,\n versionId: rigVersion.id,\n rigName,\n script: rigVersion.setupScript,\n timeoutMs: runSettings.rigSetupTimeoutMs,\n contentHash: rigProviderImageContentHash({\n backend: turn.sandboxBackend,\n sourceImage: rigProviderImageSourceImage(\n logicalSandboxSettings,\n turn.sandboxBackend,\n ),\n definition: rigVersion,\n }),\n ...(verifiedRigProviderImageId\n ? { verifiedProviderImageId: verifiedRigProviderImageId }\n : {}),\n },\n }\n : {}),\n ...(rigVersion.credentialHooks.length > 0\n ? { rigCredentialHookIds: rigVersion.credentialHooks }\n : {}),\n }\n : {}),\n });\n } catch (error) {\n agentConstructionOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"agent_construction\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: agentConstructionOutcome,\n durationSeconds: (performance.now() - agentConstructionStartedAt) / 1_000,\n });\n }\n })();\n const postAgentPreparationStartedAt = performance.now();\n if (\n eventing.modelRunSettings.sandboxBackend !== \"none\" &&\n eventing.toolCancellationFenceRef.current === null\n ) {\n throw new Error(\n \"Sandbox agent construction did not install the mandatory turn tool cancellation fence\",\n );\n }\n return {\n agent,\n modelVisibleSkillCatalogText,\n postAgentPreparationStartedAt,\n };\n}\n\nfunction approvedConnectorActionCallId(trigger: ClaimTurnOk[\"trigger\"]): string | null {\n if (trigger.type !== \"user.approvalDecision\") {\n return null;\n }\n\n const payload = trigger.payload as {\n approvalId?: unknown;\n decision?: unknown;\n };\n return payload.decision === \"approve\" && typeof payload.approvalId === \"string\"\n ? payload.approvalId\n : null;\n}\n\nexport type BuildTurnAgentOk = Awaited<ReturnType<typeof buildTurnAgent>>;\n","import {\n generateXaiSubscriptionImage,\n XAI_IMAGE_MODEL,\n XAI_SUBSCRIPTION_PROVIDER_ID,\n type XaiSubscriptionRequestContext,\n} from \"@opengeni/xai-subscription\";\nimport type { Database } from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport type { GeneratedImageReceipt } from \"./generated-images\";\nimport {\n executeImageGenerationOperation,\n imageProviderBindingHash,\n} from \"./image-generation-operation\";\nimport type { ResolvedImageGenerationReference } from \"./image-generation-references\";\n\nexport type XaiImageGenerationPorts = {\n execute: typeof executeImageGenerationOperation;\n generate: typeof generateXaiSubscriptionImage;\n};\n\nconst xaiImageGenerationPorts: XaiImageGenerationPorts = {\n execute: executeImageGenerationOperation,\n generate: generateXaiSubscriptionImage,\n};\n\n/** Execute xAI's standalone subscription image path under the durable paid-operation fence. */\nexport async function executeXaiSubscriptionImageGeneration(\n input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n prompt: string;\n references?: readonly ResolvedImageGenerationReference[];\n credentialId: string;\n xaiContext: Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\">;\n abortSignal?: AbortSignal;\n },\n ports: XaiImageGenerationPorts = xaiImageGenerationPorts,\n): Promise<GeneratedImageReceipt> {\n const providerBindingHash = imageProviderBindingHash(\n XAI_SUBSCRIPTION_PROVIDER_ID,\n input.credentialId,\n );\n return await ports.execute({\n db: input.db,\n objectStorage: input.objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n toolCallId: input.toolCallId,\n prompt: input.prompt,\n providerId: XAI_SUBSCRIPTION_PROVIDER_ID,\n providerBindingHash,\n modelId: XAI_IMAGE_MODEL,\n generate: async () => {\n const generated = await ports.generate({\n prompt: input.prompt,\n sessionId: input.sessionId,\n ...(input.references?.length\n ? {\n references: input.references.map((reference) => ({\n mediaType: reference.mediaType,\n bytes: reference.bytes,\n })),\n }\n : {}),\n getToken: input.xaiContext.getToken,\n refresh: input.xaiContext.refresh,\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n });\n return {\n toolCallId: input.toolCallId,\n providerItemId: null,\n bytes: generated.bytes,\n declaredMediaType: generated.declaredMediaType,\n };\n },\n });\n}\n","import {\n VideoGenerationAcceptedReceipt,\n type GenerateVideoToolInput,\n type VideoGenerationCapabilities,\n type VideoGenerationPolicy,\n type XaiProviderAccountAuthoritySnapshotV1,\n} from \"@opengeni/contracts\";\nimport {\n normalizeVideoGenerationRequest,\n videoGenerationAdmissionKey,\n videoGenerationProviderIdempotencyKey,\n videoGenerationRequestDigest,\n} from \"@opengeni/core\";\nimport { videoGenerationCapabilitiesForPolicy } from \"@opengeni/core\";\nimport {\n admitVideoGenerationOperation,\n encryptEnvironmentValue,\n getVideoGenerationOperation,\n markVideoGenerationPrepared,\n type Database,\n type VideoGenerationReference,\n type XaiCredentialForRun,\n} from \"@opengeni/db\";\nimport {\n calculateVideoGenerationCreditCostMicros,\n environmentsEncryptionKeyBytes,\n type Settings,\n} from \"@opengeni/config\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n inspectSandboxVideoReferences,\n uploadAndVerifyVideoReferences,\n videoReferenceStagingKey,\n type SandboxCommandRunner,\n} from \"./video-reference-staging\";\nimport {\n encryptVideoGenerationApiKey,\n encryptVideoGenerationXaiCredential,\n} from \"./video-generation-credential\";\n\nexport type VideoGenerationCredentialLease = Readonly<{\n fundingSource: \"opengeni_credits\" | \"workspace_gateway\" | \"supergrok_subscription\";\n connectionId: string | null;\n version: number;\n credentialEncrypted: string;\n}>;\n\nexport type AcceptedVideoGeneration = Readonly<{\n receipt: ReturnType<typeof VideoGenerationAcceptedReceipt.parse>;\n operationId: string;\n requestDigest: string;\n}>;\n\nexport function videoCapabilitiesForTurn(input: {\n policy: VideoGenerationPolicy;\n credential: VideoGenerationCredentialLease;\n}): VideoGenerationCapabilities {\n if (input.policy.fundingSource !== input.credential.fundingSource) {\n throw new Error(\"Video generation funding changed before capability resolution\");\n }\n return videoGenerationCapabilitiesForPolicy({\n policy: input.policy,\n credentialVersion: input.credential.version,\n });\n}\n\nexport function managedVideoGenerationCredentialLease(\n settings: Settings,\n): VideoGenerationCredentialLease | null {\n if (!settings.vercelAiGatewayApiKey) return null;\n const encryptionKey = environmentsEncryptionKeyBytes(settings);\n if (!encryptionKey) {\n throw new Error(\"Managed video generation requires OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\");\n }\n return Object.freeze({\n fundingSource: \"opengeni_credits\",\n connectionId: null,\n version: 1,\n credentialEncrypted: encryptVideoGenerationApiKey(\n encryptionKey,\n settings.vercelAiGatewayApiKey,\n ),\n });\n}\n\nexport function xaiVideoGenerationCredentialLease(input: {\n settings: Settings;\n credential: XaiCredentialForRun;\n subjectId: string;\n authoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;\n}): VideoGenerationCredentialLease {\n const encryptionKey = environmentsEncryptionKeyBytes(input.settings);\n if (!encryptionKey) {\n throw new Error(\"SuperGrok video generation requires OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\");\n }\n const { accessToken, refreshToken } = input.credential.secret;\n const userId = input.credential.providerAccountId;\n if (!accessToken || !refreshToken || !userId) {\n throw new Error(\"The selected SuperGrok account cannot fund video generation\");\n }\n return Object.freeze({\n fundingSource: \"supergrok_subscription\",\n connectionId: null,\n version: input.credential.version,\n credentialEncrypted: encryptVideoGenerationXaiCredential(encryptionKey, {\n accessToken,\n refreshToken,\n userId,\n credentialId: input.credential.id,\n subjectId: input.subjectId,\n authoritySnapshot: input.authoritySnapshot,\n }),\n });\n}\n\nexport async function admitVideoGenerationRequest(input: {\n db: Database;\n storage: ObjectStorage;\n settings: Settings;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n toolInput: GenerateVideoToolInput;\n policy: VideoGenerationPolicy;\n credential: VideoGenerationCredentialLease;\n runCommand?: SandboxCommandRunner;\n signal?: AbortSignal;\n}): Promise<AcceptedVideoGeneration> {\n const capabilities = videoCapabilitiesForTurn({\n policy: input.policy,\n credential: input.credential,\n });\n const selectedModelId = input.toolInput.modelId ?? capabilities.defaultModelId;\n const model = capabilities.models.find((candidate) => candidate.modelId === selectedModelId);\n if (!model) throw new Error(\"The requested video model is not enabled for this workspace\");\n\n const sourceMode = input.toolInput.source?.mode ?? \"text\";\n if (sourceMode !== \"text\" && !input.runCommand) {\n throw new Error(\"Video references require an active sandbox\");\n }\n const inspected = input.runCommand\n ? await inspectSandboxVideoReferences({\n request: input.toolInput,\n runCommand: input.runCommand,\n })\n : [];\n const canonical = normalizeVideoGenerationRequest({\n toolInput: input.toolInput,\n model,\n sealedReferences: inspected.map((reference) => ({\n role: reference.role,\n contentSha256: reference.sha256,\n contentType: reference.contentType,\n byteSize: reference.sizeBytes,\n })),\n });\n const requestDigest = videoGenerationRequestDigest(canonical);\n const shouldDebitManagedCredits =\n input.credential.fundingSource === \"opengeni_credits\" &&\n (input.settings.billingMode === \"stripe\" || input.settings.usageLimitsMode === \"managed\");\n const pricedCostMicros = shouldDebitManagedCredits\n ? calculateVideoGenerationCreditCostMicros(input.settings, canonical)\n : 0;\n const admissionKey = videoGenerationAdmissionKey(input);\n const candidateOperationId = randomUUID();\n const expectedArtifactId = randomUUID();\n const expectedFileId = randomUUID();\n const providerIdempotencyKey = videoGenerationProviderIdempotencyKey({\n operationId: candidateOperationId,\n requestDigest,\n });\n const encryptionKey = environmentsEncryptionKeyBytes(input.settings);\n if (!encryptionKey) {\n throw new Error(\"Video generation requires OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\");\n }\n const now = Date.now();\n const recoveryDeadlineAt = new Date(now + input.settings.videoGenerationRecoveryDeadlineMs);\n const stagingKeys = inspected.map((reference) =>\n videoReferenceStagingKey({\n workspaceId: input.workspaceId,\n operationId: candidateOperationId,\n ordinal: reference.ordinal,\n sha256: reference.sha256,\n }),\n );\n const admitted = await admitVideoGenerationOperation(input.db, {\n id: candidateOperationId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n toolCallId: input.toolCallId,\n admissionKey,\n requestDigest,\n promptDigest: createHash(\"sha256\").update(canonical.prompt).digest(\"hex\"),\n requestEncrypted: encryptEnvironmentValue(encryptionKey, JSON.stringify(canonical)),\n modelId: canonical.modelId,\n sourceMode: canonical.sourceMode,\n capabilityRevision: capabilities.capabilityRevision,\n policyRevision: input.policy.revision,\n fundingSource: input.credential.fundingSource,\n pricedCostMicros,\n connectionId: input.credential.connectionId,\n credentialVersion: input.credential.version,\n credentialEncrypted: input.credential.credentialEncrypted,\n providerIdempotencyKey,\n expectedArtifactId,\n expectedFileId,\n workspaceQuotaBytes: input.settings.videoGenerationWorkspaceQuotaBytes,\n maxConcurrentPerWorkspace: input.settings.videoGenerationMaxConcurrentPerWorkspace,\n recoveryDeadlineAt,\n references: inspected.map((reference, index) => ({\n ordinal: reference.ordinal,\n role: reference.role,\n contentType: reference.contentType,\n sizeBytes: reference.sizeBytes,\n sha256: reference.sha256,\n stagingObjectKey: stagingKeys[index]!,\n grantExpiresAt: null,\n cleanupAfter: recoveryDeadlineAt,\n })),\n });\n const operation = await getVideoGenerationOperation(\n input.db,\n input.workspaceId,\n admitted.operation.id,\n );\n if (!operation) throw new Error(\"Admitted video generation operation disappeared\");\n if (operation.status === \"preparing\") {\n assertStoredReferencePlan(operation.references, inspected);\n if (inspected.length > 0) {\n if (!input.runCommand) throw new Error(\"Prepared video references lost their sandbox\");\n await uploadAndVerifyVideoReferences({\n storage: input.storage,\n references: inspected,\n stagingKeys: operation.references.map((reference) => {\n if (!reference.stagingObjectKey) {\n throw new Error(\"Video reference staging key is missing\");\n }\n return reference.stagingObjectKey;\n }),\n runCommand: input.runCommand,\n tempRoot: input.settings.videoGenerationTempDirectory,\n ffprobePath: input.settings.videoGenerationFfprobePath,\n uploadTtlSeconds: input.settings.videoGenerationReferenceUrlTtlSeconds,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n }\n await markVideoGenerationPrepared(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest,\n });\n } else if (\n ![\n \"prepared\",\n \"accepted\",\n \"submission_uncertain\",\n \"provider_started\",\n \"retaining\",\n \"completed\",\n ].includes(operation.status)\n ) {\n throw new Error(\"The existing video generation request cannot be resumed\");\n }\n return {\n receipt: VideoGenerationAcceptedReceipt.parse({\n schemaVersion: 1,\n status: \"accepted\",\n operationId: operation.id,\n }),\n operationId: operation.id,\n requestDigest,\n };\n}\n\nfunction assertStoredReferencePlan(\n stored: VideoGenerationReference[],\n inspected: Awaited<ReturnType<typeof inspectSandboxVideoReferences>>,\n): void {\n if (\n stored.length !== inspected.length ||\n stored.some((reference, index) => {\n const source = inspected[index];\n return (\n !source ||\n reference.ordinal !== source.ordinal ||\n reference.role !== source.role ||\n reference.contentType !== source.contentType ||\n reference.sizeBytes !== source.sizeBytes ||\n reference.sha256 !== source.sha256\n );\n })\n ) {\n throw new Error(\"Video reference bytes changed across tool-call recovery\");\n }\n}\n","import {\n GENERATED_VIDEO_MAX_BYTES,\n type GenerateVideoToolInput,\n type VideoGenerationRejectedCode,\n} from \"@opengeni/contracts\";\nimport type { SealedVideoReference, SealedVideoReferenceRole } from \"@opengeni/core\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport {\n copyVersionedObjectToVerifiedTemp,\n validateImageReference,\n validateVideoReference,\n} from \"./video-media-validation\";\n\nconst MAX_IMAGE_REFERENCE_BYTES = 30 * 1024 * 1024;\nconst MAX_VIDEO_REFERENCE_BYTES = 200 * 1024 * 1024;\nconst UPLOAD_TIMEOUT_SECONDS = 15 * 60;\n\nexport type SandboxCommandRunner = (input: {\n cmd: string;\n workdir: string;\n maxOutputTokens: number;\n}) => Promise<{ stdout: string; stderr: string; exitCode: number }>;\n\nexport type InspectedSandboxVideoReference = Readonly<{\n ordinal: number;\n role: SealedVideoReferenceRole;\n path: string;\n contentType: string;\n sizeBytes: number;\n sha256: string;\n}>;\n\nexport type VideoReferenceInputErrorCode = VideoGenerationRejectedCode;\n\n/** A deterministic, pre-admission tool-input error. No video operation exists yet. */\nexport class VideoReferenceInputError extends Error {\n readonly code: VideoReferenceInputErrorCode;\n\n constructor(code: VideoReferenceInputErrorCode, message: string) {\n super(message);\n this.name = \"VideoReferenceInputError\";\n this.code = code;\n }\n}\n\nexport function videoReferencePaths(\n request: GenerateVideoToolInput,\n): Array<{ role: SealedVideoReferenceRole; path: string }> {\n const source = request.source;\n if (!source || source.mode === \"text\") return [];\n if (source.mode === \"first_frame\") return [{ role: \"first_frame\", path: source.imagePath }];\n if (source.mode === \"first_and_last_frames\") {\n return [\n { role: \"first_frame\", path: source.firstFramePath },\n { role: \"last_frame\", path: source.lastFramePath },\n ];\n }\n if (source.mode === \"image_reference\") {\n return [{ role: \"image_reference\", path: source.imagePath }];\n }\n return [{ role: \"video_reference\", path: source.videoPath }];\n}\n\nexport async function inspectSandboxVideoReferences(input: {\n request: GenerateVideoToolInput;\n runCommand: SandboxCommandRunner;\n}): Promise<InspectedSandboxVideoReference[]> {\n const paths = videoReferencePaths(input.request);\n const inspected: InspectedSandboxVideoReference[] = [];\n for (const [ordinal, reference] of paths.entries()) {\n const result = await input.runCommand({\n cmd: inspectCommand(reference.path),\n workdir: \"/workspace\",\n maxOutputTokens: 4_096,\n });\n if (result.exitCode !== 0) {\n throw new VideoReferenceInputError(\n \"reference_not_stable\",\n \"The video reference must be an existing regular file at the exact /workspace path returned by the preceding tool.\",\n );\n }\n const [sizeText, sha256, prefixBase64] = result.stdout.trim().split(\"\\t\");\n const sizeBytes = Number(sizeText);\n if (\n !Number.isSafeInteger(sizeBytes) ||\n sizeBytes <= 0 ||\n !/^[0-9a-f]{64}$/u.test(sha256 ?? \"\")\n ) {\n throw new VideoReferenceInputError(\n \"reference_not_stable\",\n \"The video reference changed or could not be read safely. Use the exact current /workspace path and try again.\",\n );\n }\n const prefix = Buffer.from(prefixBase64 ?? \"\", \"base64\");\n const contentType = sniffContentType(prefix);\n const maxBytes =\n reference.role === \"video_reference\" ? MAX_VIDEO_REFERENCE_BYTES : MAX_IMAGE_REFERENCE_BYTES;\n if (sizeBytes > maxBytes) {\n throw new VideoReferenceInputError(\n \"reference_too_large\",\n \"The video reference exceeds the supported size for this source mode.\",\n );\n }\n if (\n (reference.role === \"video_reference\" && contentType !== \"video/mp4\") ||\n (reference.role !== \"video_reference\" && !contentType.startsWith(\"image/\"))\n ) {\n throw new VideoReferenceInputError(\n \"reference_media_type_mismatch\",\n \"The video reference media type does not match the selected source mode.\",\n );\n }\n inspected.push({\n ordinal,\n role: reference.role,\n path: reference.path,\n contentType,\n sizeBytes,\n sha256: sha256!,\n });\n }\n return inspected;\n}\n\nexport async function uploadAndVerifyVideoReferences(input: {\n storage: ObjectStorage;\n references: readonly InspectedSandboxVideoReference[];\n stagingKeys: readonly string[];\n runCommand: SandboxCommandRunner;\n tempRoot: string;\n ffprobePath: string;\n uploadTtlSeconds: number;\n signal?: AbortSignal;\n}): Promise<SealedVideoReference[]> {\n if (input.references.length !== input.stagingKeys.length) {\n throw new Error(\"Video reference staging identities do not match\");\n }\n const sealed: SealedVideoReference[] = [];\n for (const [index, reference] of input.references.entries()) {\n throwIfAborted(input.signal);\n const key = input.stagingKeys[index]!;\n const existing = input.storage.headObject ? await input.storage.headObject(key) : null;\n if (!existing) {\n const upload = await input.storage.createPutUrl({\n key,\n contentType: reference.contentType,\n sha256: reference.sha256,\n expiresInSeconds: Math.min(input.uploadTtlSeconds, UPLOAD_TIMEOUT_SECONDS),\n });\n const result = await input.runCommand({\n cmd: uploadCommand(reference, upload),\n workdir: \"/workspace\",\n maxOutputTokens: 4_096,\n });\n if (result.exitCode !== 0) throw new Error(\"Video reference staging upload failed\");\n }\n const verified = await copyVersionedObjectToVerifiedTemp({\n storage: input.storage,\n key,\n expectedSizeBytes: reference.sizeBytes,\n expectedSha256: reference.sha256,\n expectedContentType: reference.contentType,\n maxBytes:\n reference.role === \"video_reference\"\n ? MAX_VIDEO_REFERENCE_BYTES\n : MAX_IMAGE_REFERENCE_BYTES,\n tempRoot: input.tempRoot,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n try {\n if (reference.role === \"video_reference\") {\n await validateVideoReference({\n path: verified.path,\n ffprobePath: input.ffprobePath,\n });\n } else {\n const image = await validateImageReference(verified.path);\n if (image.contentType !== reference.contentType) {\n throw new Error(\"Video image reference MIME type changed during validation\");\n }\n }\n } finally {\n await verified.cleanup();\n }\n sealed.push({\n role: reference.role,\n contentSha256: reference.sha256,\n contentType: reference.contentType,\n byteSize: reference.sizeBytes,\n });\n }\n return sealed;\n}\n\nexport function videoReferenceStagingKey(input: {\n workspaceId: string;\n operationId: string;\n ordinal: number;\n sha256: string;\n}): string {\n if (!/^[0-9a-f]{64}$/u.test(input.sha256)) throw new Error(\"Video reference digest is invalid\");\n return `video-generation/staging/${input.workspaceId}/${input.operationId}/${input.ordinal}/${input.sha256}`;\n}\n\nfunction inspectCommand(path: string): string {\n return [\n \"set -euo pipefail\",\n ...stableWorkspaceFilePrelude(path, { nonCanonical: 43, invalidFile: 45 }),\n 'sha=$(video_reference_sha256 \"$fd\")',\n 'exec 3<&-; exec 3<\"$resolved\"',\n 'fd=/proc/$$/fd/3; [ -e \"$fd\" ] || fd=/dev/fd/3',\n 'reopened=$(video_reference_stat_identity \"$fd\")',\n '[ \"$before\" = \"$reopened\" ] || exit 46',\n '[ \"$(video_reference_stat_content_identity \"$resolved\")\" = \"$(video_reference_stat_content_identity \"$fd\")\" ] || exit 46',\n '[ \"$(realpath -- \"$requested\")\" = \"$expected\" ] || exit 46',\n 'prefix=$(dd if=\"$fd\" bs=32 count=1 2>/dev/null | base64 | tr -d \"\\\\r\\\\n\")',\n 'after=$(video_reference_stat_identity \"$fd\")',\n '[ \"$before\" = \"$after\" ] || exit 46',\n 'printf \"%s\\\\t%s\\\\t%s\\\\n\" \"$size\" \"$sha\" \"$prefix\"',\n ].join(\"\\n\");\n}\n\nfunction uploadCommand(\n reference: InspectedSandboxVideoReference,\n upload: Awaited<ReturnType<ObjectStorage[\"createPutUrl\"]>>,\n): string {\n const headers = Object.entries(upload.requiredHeaders)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([name, value]) => `--header ${shellQuote(`${name}: ${value}`)}`)\n .join(\" \");\n return [\n \"set -euo pipefail\",\n ...stableWorkspaceFilePrelude(reference.path, {\n nonCanonical: 51,\n invalidFile: 52,\n }),\n `[ \"$size\" = ${shellQuote(String(reference.sizeBytes))} ] || exit 53`,\n 'sha=$(video_reference_sha256 \"$fd\")',\n `[ \"$sha\" = ${shellQuote(reference.sha256)} ] || exit 54`,\n 'exec 3<&-; exec 3<\"$resolved\"',\n 'fd=/proc/$$/fd/3; [ -e \"$fd\" ] || fd=/dev/fd/3',\n 'reopened=$(video_reference_stat_identity \"$fd\")',\n '[ \"$before\" = \"$reopened\" ] || exit 55',\n '[ \"$(video_reference_stat_content_identity \"$resolved\")\" = \"$(video_reference_stat_content_identity \"$fd\")\" ] || exit 55',\n '[ \"$(realpath -- \"$requested\")\" = \"$expected\" ] || exit 55',\n `curl --silent --show-error --fail --connect-timeout 20 --max-time ${UPLOAD_TIMEOUT_SECONDS} --request PUT ${headers} --upload-file \"$fd\" --output /dev/null ${shellQuote(upload.url)}`,\n 'after=$(video_reference_stat_identity \"$fd\")',\n '[ \"$before\" = \"$after\" ] || exit 56',\n ].join(\"\\n\");\n}\n\nfunction stableWorkspaceFilePrelude(\n path: string,\n exitCodes: { nonCanonical: number; invalidFile: number },\n): string[] {\n const requested = workspaceRelativeReferencePath(path);\n return [\n `requested=${shellQuote(requested)}`,\n \"root=$(pwd -P)\",\n 'expected=\"$root/${requested#./}\"',\n 'resolved=$(realpath -- \"$requested\")',\n `[ \"$resolved\" = \"$expected\" ] || exit ${exitCodes.nonCanonical}`,\n `[ -f \"$resolved\" ] || exit ${exitCodes.invalidFile}`,\n 'exec 3<\"$resolved\"',\n 'fd=/proc/$$/fd/3; [ -e \"$fd\" ] || fd=/dev/fd/3',\n `[ -f \"$fd\" ] || exit ${exitCodes.invalidFile}`,\n \"video_reference_platform=$(uname -s)\",\n 'if [ \"$video_reference_platform\" = Darwin ]; then',\n ' video_reference_stat_identity() { stat -f \"%d:%i:%z:%m\" \"$1\"; }',\n ' video_reference_stat_content_identity() { stat -f \"%i:%z:%m\" \"$1\"; }',\n ' video_reference_stat_size() { stat -f \"%z\" \"$1\"; }',\n \"else\",\n ' video_reference_stat_identity() { stat -Lc \"%d:%i:%s:%Y\" -- \"$1\"; }',\n ' video_reference_stat_content_identity() { stat -Lc \"%d:%i:%s:%Y\" -- \"$1\"; }',\n ' video_reference_stat_size() { stat -Lc \"%s\" -- \"$1\"; }',\n \"fi\",\n \"video_reference_sha256() {\",\n \" if command -v sha256sum >/dev/null 2>&1; then\",\n \" sha256sum \\\"$1\\\" | awk '{print $1}'\",\n \" else\",\n \" shasum -a 256 \\\"$1\\\" | awk '{print $1}'\",\n \" fi\",\n \"}\",\n 'if [ \"$video_reference_platform\" != Darwin ]; then',\n ' fd_path=$(realpath -- \"$fd\")',\n ` [ \"$fd_path\" = \"$expected\" ] || exit ${exitCodes.invalidFile}`,\n \"fi\",\n `[ \"$(video_reference_stat_content_identity \"$resolved\")\" = \"$(video_reference_stat_content_identity \"$fd\")\" ] || exit ${exitCodes.invalidFile}`,\n `[ \"$(realpath -- \"$requested\")\" = \"$expected\" ] || exit ${exitCodes.invalidFile}`,\n 'before=$(video_reference_stat_identity \"$fd\")',\n 'size=$(video_reference_stat_size \"$fd\")',\n ];\n}\n\nfunction workspaceRelativeReferencePath(path: string): string {\n if (!path.startsWith(\"/workspace/\") || /[\\0\\r\\n]/u.test(path)) {\n throw new VideoReferenceInputError(\n \"invalid_reference_path\",\n \"Video references must use an exact file path under /workspace.\",\n );\n }\n const segments = path.slice(\"/workspace/\".length).split(\"/\");\n if (segments.some((segment) => segment.length === 0 || segment === \".\" || segment === \"..\")) {\n throw new VideoReferenceInputError(\n \"invalid_reference_path\",\n \"Video references must use a canonical file path under /workspace.\",\n );\n }\n return `./${segments.join(\"/\")}`;\n}\n\nfunction sniffContentType(prefix: Uint8Array): string {\n if (\n prefix.byteLength >= 8 &&\n Buffer.from(prefix.subarray(0, 8)).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))\n ) {\n return \"image/png\";\n }\n if (prefix.byteLength >= 3 && prefix[0] === 0xff && prefix[1] === 0xd8 && prefix[2] === 0xff) {\n return \"image/jpeg\";\n }\n if (\n prefix.byteLength >= 12 &&\n Buffer.from(prefix.subarray(0, 4)).toString(\"ascii\") === \"RIFF\" &&\n Buffer.from(prefix.subarray(8, 12)).toString(\"ascii\") === \"WEBP\"\n ) {\n return \"image/webp\";\n }\n if (prefix.byteLength >= 12 && Buffer.from(prefix.subarray(4, 8)).toString(\"ascii\") === \"ftyp\") {\n return \"video/mp4\";\n }\n throw new VideoReferenceInputError(\n \"unsupported_reference_media\",\n \"The video reference is not a supported PNG, JPEG, WebP, or MP4 file.\",\n );\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Video reference staging was cancelled\");\n}\n\nexport const VIDEO_REFERENCE_LIMITS = Object.freeze({\n imageBytes: MAX_IMAGE_REFERENCE_BYTES,\n videoBytes: MAX_VIDEO_REFERENCE_BYTES,\n outputBytes: GENERATED_VIDEO_MAX_BYTES,\n});\n","import type { GeneratedVideoFacts } from \"@opengeni/contracts\";\nimport { retryWhileMissing, type ObjectStorage } from \"@opengeni/storage\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { open, mkdir, rm, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport sharp from \"sharp\";\n\nconst RANGE_BYTES = 1024 * 1024;\nconst PROBE_STDOUT_MAX_BYTES = 64 * 1024;\nconst PROBE_STDERR_MAX_BYTES = 16 * 1024;\nconst PROBE_TIMEOUT_MS = 20_000;\n\nexport type VerifiedTempFile = Readonly<{\n directory: string;\n path: string;\n sizeBytes: number;\n sha256: string;\n contentType: string;\n cleanup: () => Promise<void>;\n}>;\n\nexport async function copyVersionedObjectToVerifiedTemp(input: {\n storage: ObjectStorage;\n key: string;\n expectedSizeBytes: number;\n expectedSha256: string;\n expectedContentType: string;\n maxBytes: number;\n tempRoot: string;\n signal?: AbortSignal;\n}): Promise<VerifiedTempFile> {\n if (!input.storage.headObject || !input.storage.getObjectRange) {\n throw new Error(\"Object storage lacks versioned range reads\");\n }\n assertSha256(input.expectedSha256);\n if (\n !Number.isSafeInteger(input.expectedSizeBytes) ||\n input.expectedSizeBytes <= 0 ||\n input.expectedSizeBytes > input.maxBytes\n ) {\n throw new Error(\"Media staging size is invalid\");\n }\n throwIfAborted(input.signal);\n const head = await retryWhileMissing(async () => await input.storage.headObject!(input.key));\n if (\n !head ||\n head.ContentLength !== input.expectedSizeBytes ||\n head.ContentType !== input.expectedContentType ||\n head.Metadata?.sha256 !== input.expectedSha256 ||\n !head.VersionToken\n ) {\n throw new Error(\"Media staging metadata does not match its sealed reference\");\n }\n const versionToken = head.VersionToken;\n await mkdir(input.tempRoot, { recursive: true, mode: 0o700 });\n const directory = join(input.tempRoot, `media-${randomUUID()}`);\n const path = join(directory, \"payload\");\n await mkdir(directory, { recursive: false, mode: 0o700 });\n const handle = await open(path, \"wx\", 0o600);\n const hash = createHash(\"sha256\");\n let offset = 0;\n try {\n while (offset < input.expectedSizeBytes) {\n throwIfAborted(input.signal);\n const endInclusive = Math.min(input.expectedSizeBytes - 1, offset + RANGE_BYTES - 1);\n const range = await input.storage.getObjectRange({\n key: input.key,\n start: offset,\n endInclusive,\n expectedVersionToken: versionToken,\n });\n if (\n !range ||\n range.versionToken !== versionToken ||\n range.bytes.byteLength !== endInclusive - offset + 1\n ) {\n throw new Error(\"Media staging object changed during range read\");\n }\n await writeAll(handle, range.bytes, offset);\n hash.update(range.bytes);\n offset += range.bytes.byteLength;\n }\n await handle.sync();\n } catch (error) {\n await handle.close().catch(() => undefined);\n await rm(directory, { recursive: true, force: true });\n throw error;\n }\n await handle.close();\n const digest = hash.digest(\"hex\");\n if (offset !== input.expectedSizeBytes || digest !== input.expectedSha256) {\n await rm(directory, { recursive: true, force: true });\n throw new Error(\"Media staging bytes do not match their sealed digest\");\n }\n const after = await retryWhileMissing(async () => await input.storage.headObject!(input.key));\n if (!after || after.VersionToken !== versionToken) {\n await rm(directory, { recursive: true, force: true });\n throw new Error(\"Media staging object changed after verification\");\n }\n return Object.freeze({\n directory,\n path,\n sizeBytes: offset,\n sha256: digest,\n contentType: input.expectedContentType,\n cleanup: async () => await rm(directory, { recursive: true, force: true }),\n });\n}\n\nexport async function validateImageReference(path: string): Promise<{\n contentType: \"image/jpeg\" | \"image/png\" | \"image/webp\";\n width: number;\n height: number;\n}> {\n const metadata = await sharp(path, { failOn: \"error\", limitInputPixels: 67_108_864 }).metadata();\n const contentType =\n metadata.format === \"jpeg\"\n ? \"image/jpeg\"\n : metadata.format === \"png\"\n ? \"image/png\"\n : metadata.format === \"webp\"\n ? \"image/webp\"\n : null;\n if (\n !contentType ||\n !metadata.width ||\n !metadata.height ||\n metadata.width > 8_192 ||\n metadata.height > 8_192\n ) {\n throw new Error(\"Video image reference is not a supported JPEG, PNG, or WebP image\");\n }\n return { contentType, width: metadata.width, height: metadata.height };\n}\n\nexport async function validateGeneratedVideo(input: {\n path: string;\n ffprobePath: string;\n expectedDurationSeconds?: number;\n}): Promise<GeneratedVideoFacts> {\n const facts = await probeBrowserCompatibleMp4(input.path, input.ffprobePath);\n if (\n input.expectedDurationSeconds !== undefined &&\n Math.abs(facts.durationSeconds - input.expectedDurationSeconds) > 3\n ) {\n throw new Error(\"Generated video duration differs from the requested duration\");\n }\n return facts;\n}\n\nexport async function validateVideoReference(input: {\n path: string;\n ffprobePath: string;\n}): Promise<GeneratedVideoFacts> {\n return await probeBrowserCompatibleMp4(input.path, input.ffprobePath);\n}\n\nasync function probeBrowserCompatibleMp4(\n path: string,\n ffprobePath: string,\n): Promise<GeneratedVideoFacts> {\n const file = await stat(path);\n if (!file.isFile() || file.size <= 0) throw new Error(\"Media probe input is not a regular file\");\n const result = await spawnBounded(ffprobePath, [\n \"-v\",\n \"error\",\n \"-protocol_whitelist\",\n \"file,pipe\",\n \"-probesize\",\n \"8388608\",\n \"-analyzeduration\",\n \"5000000\",\n \"-show_entries\",\n \"format=format_name,duration:stream=codec_type,codec_name,width,height,avg_frame_rate:stream_disposition=attached_pic\",\n \"-of\",\n \"json\",\n \"--\",\n path,\n ]);\n let decoded: unknown;\n try {\n decoded = JSON.parse(result.stdout);\n } catch {\n throw new Error(\"Media probe returned malformed metadata\");\n }\n const root = record(decoded);\n const format = record(root?.format);\n const streams = Array.isArray(root?.streams) ? root.streams.map(record).filter(Boolean) : [];\n const video = streams.filter(\n (stream) => stream?.codec_type === \"video\" && !isAttachedPicture(stream),\n );\n const audio = streams.filter((stream) => stream?.codec_type === \"audio\");\n const durationSeconds = finitePositive(format?.duration);\n const width = positiveInteger(video[0]?.width);\n const height = positiveInteger(video[0]?.height);\n const fps = parseFrameRate(video[0]?.avg_frame_rate);\n if (\n !stringValue(format?.format_name)\n ?.split(\",\")\n .some((value) => value === \"mp4\") ||\n video.length !== 1 ||\n audio.length > 1 ||\n video[0]?.codec_name !== \"h264\" ||\n (audio.length === 1 && audio[0]?.codec_name !== \"aac\") ||\n !durationSeconds ||\n durationSeconds > 120 ||\n !width ||\n !height ||\n width > 8_192 ||\n height > 8_192 ||\n !fps ||\n fps > 120\n ) {\n throw new Error(\"Video is not a supported browser-compatible H.264 MP4\");\n }\n return {\n durationSeconds,\n width,\n height,\n fps,\n hasAudio: audio.length === 1,\n videoCodec: \"h264\",\n audioCodec: audio.length === 1 ? \"aac\" : null,\n };\n}\n\nfunction isAttachedPicture(stream: Record<string, unknown>): boolean {\n return Number(record(stream.disposition)?.attached_pic) === 1;\n}\n\nasync function spawnBounded(\n command: string,\n args: string[],\n): Promise<{ stdout: string; stderr: string }> {\n return await new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { PATH: process.env.PATH ?? \"/usr/local/bin:/usr/bin:/bin\", LC_ALL: \"C\" },\n });\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n let stdoutBytes = 0;\n let stderrBytes = 0;\n let settled = false;\n const fail = (error: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n child.kill(\"SIGKILL\");\n reject(error);\n };\n const timer = setTimeout(() => fail(new Error(\"Media probe timed out\")), PROBE_TIMEOUT_MS);\n child.stdout.on(\"data\", (chunk: Buffer) => {\n stdoutBytes += chunk.byteLength;\n if (stdoutBytes > PROBE_STDOUT_MAX_BYTES) fail(new Error(\"Media probe output is too large\"));\n else stdout.push(Buffer.from(chunk));\n });\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderrBytes += chunk.byteLength;\n if (stderrBytes > PROBE_STDERR_MAX_BYTES) fail(new Error(\"Media probe error is too large\"));\n else stderr.push(Buffer.from(chunk));\n });\n child.once(\"error\", (error) => fail(error));\n child.once(\"close\", (code) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n const stderrText = Buffer.concat(stderr).toString(\"utf8\").trim();\n if (code !== 0) {\n reject(\n new Error(\n stderrText ? `Media probe failed: ${stderrText.slice(0, 1_000)}` : \"Media probe failed\",\n ),\n );\n } else {\n resolve({ stdout: Buffer.concat(stdout).toString(\"utf8\"), stderr: stderrText });\n }\n });\n });\n}\n\nasync function writeAll(\n handle: Awaited<ReturnType<typeof open>>,\n chunk: Uint8Array,\n offset: number,\n): Promise<void> {\n let written = 0;\n while (written < chunk.byteLength) {\n const result = await handle.write(chunk, written, chunk.byteLength - written, offset + written);\n if (result.bytesWritten <= 0) throw new Error(\"Media temporary file write stalled\");\n written += result.bytesWritten;\n }\n}\n\nfunction parseFrameRate(value: unknown): number | null {\n const text = stringValue(value);\n if (!text) return null;\n const [left, right] = text.split(\"/\");\n const numerator = Number(left);\n const denominator = right === undefined ? 1 : Number(right);\n const fps = numerator / denominator;\n return Number.isFinite(fps) && fps > 0 ? fps : null;\n}\n\nfunction positiveInteger(value: unknown): number | null {\n const parsed = typeof value === \"number\" ? value : Number(value);\n return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;\n}\n\nfunction finitePositive(value: unknown): number | null {\n const parsed = typeof value === \"number\" ? value : Number(value);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n}\n\nfunction stringValue(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value : null;\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction assertSha256(value: string): void {\n if (!/^[0-9a-f]{64}$/u.test(value)) throw new Error(\"Media SHA-256 is invalid\");\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Media operation was cancelled\");\n}\n","import { decryptEnvironmentValue, encryptEnvironmentValue } from \"@opengeni/db\";\nimport type { XaiProviderAccountAuthoritySnapshotV1 } from \"@opengeni/contracts\";\n\nexport type VideoGenerationProviderCredential =\n | Readonly<{ kind: \"api-key\"; apiKey: string }>\n | Readonly<{\n kind: \"xai-subscription\";\n accessToken: string;\n refreshToken: string;\n userId: string;\n credentialId: string;\n subjectId: string;\n authoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;\n }>;\n\n/** One frozen, provider-neutral credential envelope for every video funding route. */\nexport function encryptVideoGenerationApiKey(key: Uint8Array, apiKey: string): string {\n if (!apiKey.trim()) throw new Error(\"Video provider credential is empty\");\n return encryptEnvironmentValue(key, JSON.stringify({ kind: \"api-key\", apiKey }));\n}\n\nexport function encryptVideoGenerationXaiCredential(\n key: Uint8Array,\n credential: Omit<\n Extract<VideoGenerationProviderCredential, { kind: \"xai-subscription\" }>,\n \"kind\"\n >,\n): string {\n if (\n !credential.accessToken.trim() ||\n !credential.refreshToken.trim() ||\n !credential.userId.trim() ||\n !credential.credentialId.trim() ||\n !credential.subjectId.trim()\n ) {\n throw new Error(\"SuperGrok video credential is incomplete\");\n }\n return encryptEnvironmentValue(key, JSON.stringify({ kind: \"xai-subscription\", ...credential }));\n}\n\n/**\n * Decrypt without ever attaching parser/decryption errors: JSON parser errors\n * may quote plaintext and must not enter Temporal failure payloads or logs.\n */\nexport function decryptVideoGenerationCredential(\n key: Uint8Array,\n stored: string,\n): VideoGenerationProviderCredential {\n let plaintext: string;\n try {\n plaintext = decryptEnvironmentValue(key, stored);\n } catch {\n throw new Error(\"Video provider credential lease could not be decrypted\");\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(plaintext);\n } catch {\n throw new Error(\"Video provider credential lease is malformed\");\n }\n const row =\n decoded && typeof decoded === \"object\" && !Array.isArray(decoded)\n ? (decoded as Record<string, unknown>)\n : null;\n if (row?.kind === \"api-key\" || (row?.kind === undefined && typeof row?.apiKey === \"string\")) {\n if (typeof row.apiKey !== \"string\" || !row.apiKey.trim()) {\n throw new Error(\"Video provider credential lease is malformed\");\n }\n return Object.freeze({ kind: \"api-key\", apiKey: row.apiKey });\n }\n const authority =\n row?.authoritySnapshot &&\n typeof row.authoritySnapshot === \"object\" &&\n !Array.isArray(row.authoritySnapshot)\n ? (row.authoritySnapshot as Record<string, unknown>)\n : null;\n if (\n row?.kind !== \"xai-subscription\" ||\n typeof row.accessToken !== \"string\" ||\n !row.accessToken.trim() ||\n typeof row.refreshToken !== \"string\" ||\n !row.refreshToken.trim() ||\n typeof row.userId !== \"string\" ||\n !row.userId.trim() ||\n typeof row.credentialId !== \"string\" ||\n !row.credentialId.trim() ||\n typeof row.subjectId !== \"string\" ||\n !row.subjectId.trim() ||\n authority?.version !== 1 ||\n (authority.scope !== \"workspace\" && authority.scope !== \"user\") ||\n (authority.scope === \"user\" && !Number.isSafeInteger(authority.authorityGeneration))\n ) {\n throw new Error(\"Video provider credential lease is malformed\");\n }\n return Object.freeze({\n kind: \"xai-subscription\",\n accessToken: row.accessToken,\n refreshToken: row.refreshToken,\n userId: row.userId,\n credentialId: row.credentialId,\n subjectId: row.subjectId,\n authoritySnapshot: authority as XaiProviderAccountAuthoritySnapshotV1,\n });\n}\n\nexport function decryptVideoGenerationApiKey(key: Uint8Array, stored: string): string {\n const credential = decryptVideoGenerationCredential(key, stored);\n if (credential.kind !== \"api-key\") {\n throw new Error(\"Video provider credential is not an API key\");\n }\n return credential.apiKey;\n}\n","import type { Database } from \"@opengeni/db\";\nimport { readJsonBase64Field, readResponseTextBounded, type FetchLike } from \"@opengeni/network\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { type GeneratedImageOutput, type GeneratedImageReceipt } from \"./generated-images\";\nimport {\n executeImageGenerationOperation,\n imageProviderBindingHash,\n} from \"./image-generation-operation\";\nimport type { ResolvedImageGenerationReference } from \"./image-generation-references\";\n\nconst GATEWAY_IMAGE_PROVIDER_ID = \"vercel-ai-gateway\";\nconst GATEWAY_IMAGE_URL = \"https://ai-gateway.vercel.sh/v3/ai/image-model\";\nconst GATEWAY_PROTOCOL_VERSION = \"0.0.1\";\nconst GATEWAY_IMAGE_SPECIFICATION_VERSION = \"3\";\nconst GATEWAY_IMAGE_RESPONSE_MAX_BYTES = 90 * 1024 * 1024;\nconst GATEWAY_IMAGE_MAX_BYTES = 64 * 1024 * 1024;\nconst GATEWAY_IMAGE_ERROR_MAX_BYTES = 64 * 1024;\n\nexport class GatewayImageApiError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = \"GatewayImageApiError\";\n }\n}\n\nexport async function executeGatewayImageGeneration(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n apiKey: string;\n modelId: string;\n prompt: string;\n references?: readonly ResolvedImageGenerationReference[];\n toolCallId: string;\n abortSignal?: AbortSignal;\n}): Promise<GeneratedImageReceipt> {\n const providerBindingHash = imageProviderBindingHash(GATEWAY_IMAGE_PROVIDER_ID, input.apiKey);\n return await executeImageGenerationOperation({\n ...input,\n providerId: GATEWAY_IMAGE_PROVIDER_ID,\n providerBindingHash,\n ...(input.references ? { referenceDigests: input.references } : {}),\n generate: async () =>\n await generateGatewayImage({\n apiKey: input.apiKey,\n modelId: input.modelId,\n prompt: input.prompt,\n ...(input.references ? { references: input.references } : {}),\n toolCallId: input.toolCallId,\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n }),\n });\n}\n\n/**\n * One explicit Vercel AI Gateway image-protocol adapter. The caller owns durable\n * operation admission; this function never retries an outcome-ambiguous paid\n * request. The response is decoded directly from its JSON stream so neither\n * the complete envelope nor its multi-megabyte base64 string enters memory.\n */\nexport async function generateGatewayImage(input: {\n apiKey: string;\n modelId: string;\n prompt: string;\n references?: readonly ResolvedImageGenerationReference[];\n toolCallId: string;\n abortSignal?: AbortSignal;\n fetch?: FetchLike;\n}): Promise<GeneratedImageOutput> {\n if (!input.apiKey.trim()) throw new Error(\"AI Gateway image generation credential is empty\");\n if (!input.modelId.trim()) throw new Error(\"AI Gateway image generation model is empty\");\n const response = await (input.fetch ?? globalThis.fetch)(GATEWAY_IMAGE_URL, {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n Authorization: `Bearer ${input.apiKey}`,\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n \"ai-gateway-auth-method\": \"api-key\",\n \"ai-gateway-protocol-version\": GATEWAY_PROTOCOL_VERSION,\n \"ai-image-model-specification-version\": GATEWAY_IMAGE_SPECIFICATION_VERSION,\n \"ai-model-id\": input.modelId,\n \"user-agent\": \"opengeni/image-generation\",\n },\n body: JSON.stringify({\n prompt: input.prompt,\n n: 1,\n ...(input.references?.length\n ? {\n files: input.references.map((reference) => ({\n type: \"file\",\n mediaType: reference.mediaType,\n data: Buffer.from(reference.bytes).toString(\"base64\"),\n })),\n }\n : {}),\n }),\n ...(input.abortSignal ? { signal: input.abortSignal } : {}),\n });\n if (!response.ok) {\n const detail = await readResponseTextBounded(\n response,\n GATEWAY_IMAGE_ERROR_MAX_BYTES,\n \"AI Gateway image error\",\n input.abortSignal ? { signal: input.abortSignal } : {},\n ).catch(() => \"\");\n throw new GatewayImageApiError(\n response.status,\n detail\n ? `AI Gateway image generation failed (${response.status}): ${boundedErrorMessage(detail)}`\n : `AI Gateway image generation failed (${response.status})`,\n );\n }\n const bytes = await readJsonBase64Field(response, {\n fieldName: \"images\",\n shape: \"first_array_string\",\n maxResponseBytes: GATEWAY_IMAGE_RESPONSE_MAX_BYTES,\n maxDecodedBytes: GATEWAY_IMAGE_MAX_BYTES,\n label: \"AI Gateway image generation\",\n ...(input.abortSignal ? { signal: input.abortSignal } : {}),\n });\n return {\n toolCallId: input.toolCallId,\n providerItemId: null,\n bytes,\n };\n}\n\nfunction boundedErrorMessage(body: string): string {\n let message = body;\n try {\n const value = JSON.parse(body) as { error?: { message?: unknown }; message?: unknown };\n const candidate = value.error?.message ?? value.message;\n if (typeof candidate === \"string\") message = candidate;\n } catch {\n // Preserve a bounded non-JSON provider diagnostic.\n }\n return message.replace(/\\s+/g, \" \").trim().slice(0, 1_000);\n}\n","import {\n CODEX_PROVIDER_ID,\n generateCodexSubscriptionImage,\n type CodexRequestContext,\n} from \"@opengeni/codex\";\nimport type { Database } from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport type { GeneratedImageReceipt } from \"./generated-images\";\nimport { CodexCredentialLeaseLostError } from \"./agent-turn/credential-leases\";\nimport {\n executeImageGenerationOperation,\n imageProviderBindingHash,\n} from \"./image-generation-operation\";\nimport type { ResolvedImageGenerationReference } from \"./image-generation-references\";\n\nconst CODEX_IMAGE_MODEL = \"gpt-image-2\";\n\n/** Execute the same standalone subscription image path used by Codex clients. */\nexport async function executeCodexImageGeneration(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n prompt: string;\n references?: readonly ResolvedImageGenerationReference[];\n credentialId: string;\n codexContext: Pick<\n CodexRequestContext,\n \"clientVersion\" | \"getToken\" | \"refresh\" | \"beforeProviderDispatch\"\n >;\n abortSignal?: AbortSignal;\n}): Promise<GeneratedImageReceipt> {\n const providerBindingHash = imageProviderBindingHash(CODEX_PROVIDER_ID, input.credentialId);\n let providerDispatchAdmitted = false;\n const codexContext: Pick<\n CodexRequestContext,\n \"clientVersion\" | \"getToken\" | \"refresh\" | \"beforeProviderDispatch\"\n > = {\n ...input.codexContext,\n beforeProviderDispatch: async () => {\n await input.codexContext.beforeProviderDispatch?.();\n providerDispatchAdmitted = true;\n },\n };\n return await executeImageGenerationOperation({\n ...input,\n providerId: CODEX_PROVIDER_ID,\n providerBindingHash,\n modelId: CODEX_IMAGE_MODEL,\n ...(input.references ? { referenceDigests: input.references } : {}),\n isProviderDispatchRejected: (error) =>\n !providerDispatchAdmitted && error instanceof CodexCredentialLeaseLostError,\n generate: async () => {\n const generated = await generateCodexSubscriptionImage({\n prompt: input.prompt,\n ...(input.references ? { references: input.references } : {}),\n turnId: input.turnId,\n context: codexContext,\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n });\n return {\n toolCallId: input.toolCallId,\n providerItemId: null,\n bytes: generated.bytes,\n declaredMediaType: generated.declaredMediaType,\n };\n },\n });\n}\n","import { type ImageGenerationReference, type FileAsset } from \"@opengeni/contracts\";\nimport { getGeneratedImageArtifact, requireFileForSubject, type Database } from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport {\n GeneratedImageValidationError,\n validateGeneratedImage,\n type GeneratedImageMediaType,\n} from \"./generated-images\";\n\nexport const IMAGE_GENERATION_REFERENCE_MAX_BYTES = 30 * 1024 * 1024;\nexport const IMAGE_GENERATION_REFERENCES_MAX_TOTAL_BYTES = 64 * 1024 * 1024;\n\nexport type ResolvedImageGenerationReference = Readonly<{\n mediaType: GeneratedImageMediaType;\n bytes: Uint8Array;\n sizeBytes: number;\n sha256: string;\n}>;\n\nexport type SandboxImageReferenceReader = (path: string, maxBytes: number) => Promise<Uint8Array>;\n\nexport type ImageGenerationReferenceErrorCode =\n | \"invalid_reference\"\n | \"unsupported_reference_media\"\n | \"reference_too_large\"\n | \"reference_not_ready\"\n | \"reference_unavailable\"\n | \"reference_integrity_mismatch\";\n\n/** A deterministic input rejection that occurs before any image provider request. */\nexport class ImageGenerationReferenceError extends Error {\n constructor(\n readonly code: ImageGenerationReferenceErrorCode,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = \"ImageGenerationReferenceError\";\n }\n}\n\nexport type ImageGenerationReferenceRejectedResult = Readonly<{\n isError: true;\n status: \"rejected\";\n code: ImageGenerationReferenceErrorCode;\n message: string;\n operationCreated: false;\n content: readonly [{ readonly type: \"text\"; readonly text: string }];\n}>;\n\nexport type ResolveImageGenerationReferencesInput = Readonly<{\n db: Database;\n objectStorage: ObjectStorage;\n accountId: string;\n workspaceId: string;\n subjectId: string | null;\n references: readonly ImageGenerationReference[];\n readSandboxFile?: SandboxImageReferenceReader;\n}>;\n\nexport type ImageGenerationReferenceResolution =\n | Readonly<{\n status: \"resolved\";\n references: ResolvedImageGenerationReference[];\n }>\n | Readonly<{\n status: \"rejected\";\n result: ImageGenerationReferenceRejectedResult;\n }>;\n\n/**\n * Carry deterministic pre-provider input failures on the tool output. Unknown\n * database and object-storage failures still throw, and provider execution\n * remains outside this boundary so an outcome-unknown operation can never be\n * reported rejected.\n */\nexport async function resolveImageGenerationReferencesForTool(\n input: ResolveImageGenerationReferencesInput,\n): Promise<ImageGenerationReferenceResolution> {\n try {\n return {\n status: \"resolved\",\n references: await resolveImageGenerationReferences(input),\n };\n } catch (error) {\n if (!(error instanceof ImageGenerationReferenceError)) throw error;\n const text = `Image generation was not started: ${error.message}`;\n return {\n status: \"rejected\",\n result: {\n isError: true,\n status: \"rejected\",\n code: error.code,\n message: error.message,\n operationCreated: false,\n content: [{ type: \"text\", text }],\n },\n };\n }\n}\n\n/**\n * Resolve ordered model-facing references without accepting arbitrary URLs.\n * Stored files remain workspace-RLS scoped; sandbox reads stay rooted beneath\n * /workspace. Provider adapters receive only validated immutable bytes.\n */\nexport async function resolveImageGenerationReferences(\n input: ResolveImageGenerationReferencesInput,\n): Promise<ResolvedImageGenerationReference[]> {\n const resolved: ResolvedImageGenerationReference[] = [];\n let totalBytes = 0;\n\n for (const reference of input.references) {\n const source = await referenceBytes(input, reference);\n if (source.bytes.byteLength > IMAGE_GENERATION_REFERENCE_MAX_BYTES) {\n throw new ImageGenerationReferenceError(\n \"reference_too_large\",\n \"An image reference exceeds the per-image byte limit.\",\n );\n }\n totalBytes += source.bytes.byteLength;\n if (totalBytes > IMAGE_GENERATION_REFERENCES_MAX_TOTAL_BYTES) {\n throw new ImageGenerationReferenceError(\n \"reference_too_large\",\n \"The image references exceed the combined byte limit.\",\n );\n }\n\n const image = validateReferenceImage(source.bytes);\n if (source.file) assertStoredFileMatches(source.file, image);\n resolved.push({\n mediaType: image.mediaType,\n bytes: source.bytes,\n sizeBytes: image.sizeBytes,\n sha256: image.sha256,\n });\n }\n\n return resolved;\n}\n\nasync function referenceBytes(\n input: ResolveImageGenerationReferencesInput,\n reference: ImageGenerationReference,\n): Promise<{ bytes: Uint8Array; file?: FileAsset }> {\n if (reference.kind === \"sandbox_path\") {\n if (!input.readSandboxFile) {\n throw new ImageGenerationReferenceError(\n \"reference_unavailable\",\n \"Sandbox image references require an available workspace sandbox.\",\n );\n }\n try {\n return {\n bytes: await input.readSandboxFile(\n reference.path,\n IMAGE_GENERATION_REFERENCE_MAX_BYTES + 1,\n ),\n };\n } catch (error) {\n if (error instanceof ImageGenerationReferenceError) throw error;\n throw new ImageGenerationReferenceError(\n \"reference_unavailable\",\n \"The sandbox image reference could not be read. Verify that the file still exists in the current workspace.\",\n { cause: error },\n );\n }\n }\n\n let file: FileAsset;\n if (reference.kind === \"file\") {\n try {\n file = await requireFileForSubject(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: input.subjectId,\n fileId: reference.fileId,\n });\n } catch (error) {\n if (!(error instanceof Error) || !error.message.startsWith(\"File not found:\")) throw error;\n throw new ImageGenerationReferenceError(\n \"reference_unavailable\",\n \"The workspace File image reference is unavailable.\",\n { cause: error },\n );\n }\n } else {\n file = await artifactFile(input.db, input.workspaceId, reference.artifactId);\n }\n if (file.status !== \"ready\" || !file.sha256) {\n throw new ImageGenerationReferenceError(\n \"reference_not_ready\",\n \"The image reference is not durably ready yet.\",\n );\n }\n if (file.sizeBytes <= 0 || file.sizeBytes > IMAGE_GENERATION_REFERENCE_MAX_BYTES) {\n throw new ImageGenerationReferenceError(\n \"reference_too_large\",\n \"The image reference file exceeds the supported size.\",\n );\n }\n return {\n bytes: await readStoredImageReferenceFile(input.objectStorage, file),\n file,\n };\n}\n\nexport async function readStoredImageReferenceFile(\n objectStorage: Pick<ObjectStorage, \"getFileBytes\">,\n file: FileAsset,\n): Promise<Uint8Array> {\n const bytes = await objectStorage.getFileBytes(file);\n if (bytes.byteLength !== file.sizeBytes) {\n throw new ImageGenerationReferenceError(\n \"reference_integrity_mismatch\",\n \"The durable image reference bytes do not match their file metadata.\",\n );\n }\n return bytes;\n}\n\nasync function artifactFile(\n db: Database,\n workspaceId: string,\n artifactId: string,\n): Promise<FileAsset> {\n const artifact = await getGeneratedImageArtifact(db, workspaceId, artifactId);\n if (!artifact || artifact.status !== \"ready\") {\n throw new ImageGenerationReferenceError(\n \"reference_unavailable\",\n \"The generated-image artifact reference is unavailable.\",\n );\n }\n return artifact.file;\n}\n\nfunction assertStoredFileMatches(\n file: FileAsset,\n image: Pick<ResolvedImageGenerationReference, \"sizeBytes\" | \"sha256\">,\n): void {\n if (file.sizeBytes !== image.sizeBytes || file.sha256 !== image.sha256) {\n throw new ImageGenerationReferenceError(\n \"reference_integrity_mismatch\",\n \"The image reference bytes do not match their durable file metadata.\",\n );\n }\n}\n\nfunction validateReferenceImage(bytes: Uint8Array) {\n try {\n return validateGeneratedImage({ bytes });\n } catch (error) {\n if (!(error instanceof GeneratedImageValidationError)) throw error;\n if (error.reason === \"unsupported\") {\n throw new ImageGenerationReferenceError(\n \"unsupported_reference_media\",\n \"Image references must be PNG, JPEG, or WebP. Convert SVG or other formats before calling generate_image.\",\n { cause: error },\n );\n }\n if (error.reason === \"oversized\") {\n throw new ImageGenerationReferenceError(\n \"reference_too_large\",\n \"The image reference exceeds the supported dimensions or byte size.\",\n { cause: error },\n );\n }\n throw new ImageGenerationReferenceError(\n \"invalid_reference\",\n \"The image reference is not a valid PNG, JPEG, or WebP image.\",\n { cause: error },\n );\n }\n}\n","import type { GenerateVideoToolInput } from \"@opengeni/contracts\";\nimport { videoReferencePaths } from \"../video-reference-staging\";\nimport type { SandboxRuntimeState } from \"./turn-context\";\nimport { resolveTurnSandboxAccess, type ResolvedTurnSandboxAccess } from \"./turn-sandbox-access\";\n\ntype VideoReferenceSandboxState = Pick<\n SandboxRuntimeState,\n \"resolvedSandbox\" | \"lazyOwnedSandbox\" | \"turnSandboxProvisioner\"\n>;\n\n/** Text-to-video stays sandbox-free; source-bearing requests join the turn sandbox before I/O. */\nexport async function resolveVideoReferenceSandboxAccess(\n request: GenerateVideoToolInput,\n sandboxState: VideoReferenceSandboxState,\n sdkOwnedSandboxSession: unknown,\n): Promise<ResolvedTurnSandboxAccess | null> {\n if (videoReferencePaths(request).length === 0) return null;\n return await resolveTurnSandboxAccess(\n sandboxState,\n sdkOwnedSandboxSession,\n \"Video reference sandbox is unavailable\",\n );\n}\n","import { environmentsEncryptionKeyBytes } from \"@opengeni/config\";\nimport type { MediaGenerationResult } from \"@opengeni/contracts\";\nimport { type CanonicalVideoGenerationRequest, videoGenerationRequestDigest } from \"@opengeni/core\";\nimport {\n addSessionSystemUpdateWithSourceMutation,\n decryptEnvironmentValue,\n encryptEnvironmentValue,\n getVideoGenerationOperation,\n markVideoGenerationProviderStarted,\n markVideoGenerationReferenceCleaned,\n markVideoGenerationRetaining,\n markVideoGenerationSubmissionIntent,\n markVideoGenerationSubmissionUncertain,\n materializeXaiCredentialForRun,\n refreshXaiSubscriptionCredentialSerialized,\n rotateVideoGenerationCredential,\n markVideoGenerationTerminalUpdate,\n markVideoGenerationTerminalUpdateInTransaction,\n mediaGenerationResultForStoredOperation,\n rescheduleVideoGenerationOperation,\n settleVideoGenerationFailure,\n settleVideoGenerationReady,\n type XaiCredentialForRun,\n type VideoGenerationOperationWithReferences,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport {\n buildGatewayVideoStartBody,\n GatewayVideoApiError,\n getGatewayVideoGenerationStatus,\n startGatewayVideoGenerationWithBody,\n type GatewayVideoReferenceGrant,\n} from \"./gateway-video-generation\";\nimport {\n downloadGeneratedVideoToVerifiedTemp,\n retainVerifiedGeneratedVideo,\n} from \"./video-output-retention\";\nimport {\n decryptVideoGenerationCredential,\n encryptVideoGenerationXaiCredential,\n type VideoGenerationProviderCredential,\n} from \"./video-generation-credential\";\nimport {\n refreshXaiToken,\n XaiSubscriptionError,\n xaiAccessTokenExpiry,\n type XaiSubscriptionRequestContext,\n} from \"@opengeni/xai-subscription\";\nimport {\n buildXaiVideoStartBody,\n getXaiVideoGenerationStatus,\n startXaiVideoGeneration,\n} from \"./xai-video-generation\";\nimport type {\n TurnActivityServices,\n VideoGenerationReconcileResult,\n VideoGenerationTerminalStatus,\n} from \"./types\";\n\nconst RECONCILE_ERROR_MAX = 1_000;\n\nexport function createVideoGenerationActivities(services: () => Promise<TurnActivityServices>) {\n return {\n reconcileVideoGenerationOperation: async (input: {\n accountId: string;\n workspaceId: string;\n operationId: string;\n }): Promise<VideoGenerationReconcileResult> => {\n const service = await services();\n if (!service.objectStorage) {\n throw new Error(\"Video generation reconciliation requires object storage\");\n }\n return await reconcileVideoGenerationOperation(service, input);\n },\n };\n}\n\nexport async function reconcileVideoGenerationOperation(\n service: TurnActivityServices,\n input: { accountId: string; workspaceId: string; operationId: string },\n): Promise<VideoGenerationReconcileResult> {\n const storage = requireStorage(service.objectStorage);\n let operation = await requireOperation(service, input);\n if (isTerminal(operation.status)) {\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: operation.status };\n }\n const key = environmentsEncryptionKeyBytes(service.settings);\n if (!key) throw new Error(\"Video generation recovery encryption key is unavailable\");\n if (!operation.credentialEncrypted) {\n throw new Error(\"Video provider credential lease was erased too early\");\n }\n const providerCredential = decryptVideoGenerationCredential(key, operation.credentialEncrypted);\n const usesSuperGrok = operation.fundingSource === \"supergrok_subscription\";\n if (usesSuperGrok !== (providerCredential.kind === \"xai-subscription\")) {\n throw new Error(\"Video provider credential does not match its funding source\");\n }\n const apiKey = providerCredential.kind === \"api-key\" ? providerCredential.apiKey : null;\n const xaiAuth =\n providerCredential.kind === \"xai-subscription\"\n ? await durableXaiVideoAuth(service, operation, key, providerCredential)\n : null;\n let preparedSubmissionThisRun = false;\n\n if (operation.status === \"accepted\") {\n const canonical = decryptCanonicalRequest(operation, key);\n const grants: GatewayVideoReferenceGrant[] = [];\n const expirations: Date[] = [];\n for (const reference of operation.references) {\n if (!reference.stagingObjectKey) {\n throw new Error(\"Video generation reference staging object is missing\");\n }\n const signed = await storage.createGetUrl({\n key: reference.stagingObjectKey,\n expiresInSeconds: service.settings.videoGenerationReferenceUrlTtlSeconds,\n });\n grants.push({\n role: parseReferenceRole(reference.role),\n url: signed.url,\n mediaType: reference.contentType,\n });\n expirations.push(signed.expiresAt);\n }\n const providerRequestExpiresAt = expirations.length\n ? new Date(Math.min(...expirations.map((value) => value.getTime())))\n : operation.recoveryDeadlineAt;\n const body = usesSuperGrok\n ? buildXaiVideoStartBody(canonical, grants)\n : buildGatewayVideoStartBody(canonical, grants);\n operation = retainReferences(\n operation,\n await markVideoGenerationSubmissionIntent(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n encryptedProviderRequest: encryptEnvironmentValue(key, JSON.stringify(body)),\n providerRequestExpiresAt,\n nextReconcileAt: new Date(),\n }),\n );\n preparedSubmissionThisRun = true;\n }\n\n if (operation.status === \"submission_uncertain\") {\n if (usesSuperGrok && !preparedSubmissionThisRun) {\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: \"outcome_unknown\",\n publicReason:\n \"The video provider did not confirm whether generation started. It was not replayed because xAI provides no start idempotency key.\",\n }),\n );\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n }\n const deadline = Math.min(\n operation.recoveryDeadlineAt.getTime(),\n operation.providerRequestExpiresAt?.getTime() ?? 0,\n );\n if (Date.now() >= deadline) {\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: \"outcome_unknown\",\n publicReason:\n \"The video provider did not confirm whether generation started. It was not retried with a new request.\",\n }),\n );\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n }\n const body = decryptProviderBody(operation, key);\n try {\n const started = usesSuperGrok\n ? await startXaiVideoGeneration({\n body,\n sessionId: operation.sessionId,\n auth: requireXaiAuth(xaiAuth),\n })\n : await startGatewayVideoGenerationWithBody({\n apiKey: requireApiKey(apiKey),\n modelId: operation.modelId,\n body,\n idempotencyKey: operation.providerIdempotencyKey,\n });\n operation = retainReferences(\n operation,\n await markVideoGenerationProviderStarted(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n providerJobId: started.providerJobId,\n nextReconcileAt: nextPoll(service),\n }),\n );\n return waitResult(service);\n } catch (error) {\n if (isPermanentProviderFailure(error)) {\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: \"provider_failed\",\n publicReason: \"The video provider rejected the generation request.\",\n privateError: privateError(error),\n }),\n );\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n }\n await markVideoGenerationSubmissionUncertain(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n nextReconcileAt: nextPoll(service),\n error: privateError(error),\n });\n return waitResult(service);\n }\n }\n\n if (operation.status !== \"provider_started\" && operation.status !== \"retaining\") {\n throw new Error(`Video operation cannot be reconciled from ${operation.status}`);\n }\n if (!operation.providerJobId) throw new Error(\"Video provider job identity is missing\");\n let status;\n try {\n status = usesSuperGrok\n ? await getXaiVideoGenerationStatus({\n providerJobId: operation.providerJobId,\n sessionId: operation.sessionId,\n auth: requireXaiAuth(xaiAuth),\n })\n : await getGatewayVideoGenerationStatus({\n apiKey: requireApiKey(apiKey),\n modelId: operation.modelId,\n providerJobId: operation.providerJobId,\n });\n } catch (error) {\n if (Date.now() < operation.recoveryDeadlineAt.getTime() && !isPermanentProviderFailure(error)) {\n await rescheduleVideoGenerationOperation(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n nextReconcileAt: nextPoll(service),\n error: privateError(error),\n });\n return waitResult(service);\n }\n const failureStatus = operation.status === \"retaining\" ? \"retention_failed\" : \"outcome_unknown\";\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: failureStatus,\n publicReason:\n failureStatus === \"retention_failed\"\n ? \"The generated video could not be retained.\"\n : \"The video provider stopped reporting the accepted generation.\",\n privateError: privateError(error),\n }),\n );\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n }\n if (status.status === \"pending\") {\n await rescheduleVideoGenerationOperation(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n nextReconcileAt: nextPoll(service),\n });\n return waitResult(service);\n }\n if (status.status === \"error\") {\n const failureStatus = operation.status === \"retaining\" ? \"retention_failed\" : \"provider_failed\";\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: failureStatus,\n publicReason: status.publicReason,\n }),\n );\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n }\n\n if (operation.status === \"provider_started\") {\n operation = retainReferences(\n operation,\n await markVideoGenerationRetaining(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n }),\n );\n }\n try {\n const canonical = decryptCanonicalRequest(operation, key);\n const downloaded = await downloadGeneratedVideoToVerifiedTemp({\n url: status.outputUrl,\n mediaType: status.mediaType,\n settings: service.settings,\n expectedDurationSeconds: canonical.durationSeconds,\n });\n try {\n const retained = await retainVerifiedGeneratedVideo({\n storage,\n temp: downloaded.temp,\n facts: downloaded.facts,\n });\n const settled = await settleVideoGenerationReady(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n fileId: operation.expectedFileId,\n bucket: retained.bucket,\n objectKey: retained.objectKey,\n sizeBytes: retained.sizeBytes,\n sha256: retained.sha256,\n facts: retained.facts,\n });\n operation = { ...settled.operation, references: operation.references };\n } finally {\n await downloaded.temp.cleanup();\n }\n } catch (error) {\n if (Date.now() < operation.recoveryDeadlineAt.getTime()) {\n await rescheduleVideoGenerationOperation(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n nextReconcileAt: nextPoll(service),\n error: privateError(error),\n });\n return waitResult(service);\n }\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: \"retention_failed\",\n publicReason: \"The generated video could not be retained.\",\n privateError: privateError(error),\n }),\n );\n }\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n}\n\nasync function deliverTerminalResult(\n service: TurnActivityServices,\n operation: VideoGenerationOperationWithReferences,\n): Promise<void> {\n if (\n operation.terminalUpdateState === \"delivered\" ||\n operation.terminalUpdateState === \"suppressed\"\n ) {\n await cleanupTerminalReferences(service, operation);\n return;\n }\n if (!operation.sessionId) {\n await markVideoGenerationTerminalUpdate(service.db, {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n operationId: operation.id,\n state: \"suppressed\",\n });\n await cleanupTerminalReferences(service, operation);\n return;\n }\n const payload = await terminalPayload(service, operation);\n const result = await addSessionSystemUpdateWithSourceMutation(\n service.db,\n {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n sessionId: operation.sessionId,\n kind: \"media_generation_result\",\n classification: payload.status === \"ready\" ? \"success\" : \"failure\",\n sourceId: operation.id,\n dedupeKey: `video-generation-terminal:${operation.id}`,\n summary:\n payload.status === \"ready\"\n ? \"The requested video is ready and available in the workspace.\"\n : payload.boundedPublicReason,\n payload,\n lineage: { operationId: operation.id },\n },\n async (tx, _wakeEventId, updateId) => {\n const marked = await markVideoGenerationTerminalUpdateInTransaction(tx, {\n workspaceId: operation.workspaceId,\n operationId: operation.id,\n state: updateId ? \"leased\" : \"suppressed\",\n ...(updateId ? { updateId } : {}),\n });\n if (!marked && operation.terminalUpdateState !== \"leased\") {\n throw new Error(\"Video terminal result lost its disposition fence\");\n }\n },\n );\n if (result.reason === \"session_cancelled\") {\n await cleanupTerminalReferences(service, operation);\n return;\n }\n if (result.added && result.events.length > 0) {\n await publishDurableSessionEvents(\n service.bus,\n operation.workspaceId,\n operation.sessionId,\n result.events,\n );\n }\n if (result.shouldWake && service.wakeSessionWorkflow) {\n if (result.workflowWakeRevision === null) {\n throw new Error(\"Video terminal result wake has no revision\");\n }\n await service.wakeSessionWorkflow({\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n sessionId: operation.sessionId,\n workflowId: result.temporalWorkflowId ?? `session-${operation.sessionId}`,\n wakeRevision: result.workflowWakeRevision,\n });\n }\n await cleanupTerminalReferences(service, operation);\n}\n\nasync function cleanupTerminalReferences(\n service: TurnActivityServices,\n operation: VideoGenerationOperationWithReferences,\n): Promise<void> {\n const storage = requireStorage(service.objectStorage);\n for (const reference of operation.references) {\n if (!reference.stagingObjectKey || reference.cleanedAt) continue;\n // `outcome_unknown` is only terminal after the frozen provider grant and\n // recovery deadline have elapsed. Other terminal outcomes have observed a\n // provider terminal state, so their immutable staging inputs are no longer\n // needed. Delete first, then CAS the row; a crash repeats an idempotent delete.\n if (\n operation.status === \"outcome_unknown\" &&\n Date.now() <\n Math.max(\n operation.recoveryDeadlineAt.getTime(),\n reference.grantExpiresAt?.getTime() ?? 0,\n reference.cleanupAfter?.getTime() ?? 0,\n )\n ) {\n continue;\n }\n const stagingObjectKey = reference.stagingObjectKey;\n await storage.deleteObject(stagingObjectKey);\n const marked = await markVideoGenerationReferenceCleaned(service.db, {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n operationId: operation.id,\n ordinal: reference.ordinal,\n stagingObjectKey,\n });\n if (!marked) throw new Error(\"Video reference cleanup lost its durable identity\");\n }\n}\n\nasync function terminalPayload(\n service: TurnActivityServices,\n operation: VideoGenerationOperationWithReferences,\n): Promise<MediaGenerationResult> {\n return await mediaGenerationResultForStoredOperation(service.db, operation);\n}\n\nasync function requireOperation(\n service: TurnActivityServices,\n input: { workspaceId: string; operationId: string },\n): Promise<VideoGenerationOperationWithReferences> {\n const operation = await getVideoGenerationOperation(\n service.db,\n input.workspaceId,\n input.operationId,\n );\n if (!operation) throw new Error(\"Video generation operation was not found\");\n return operation;\n}\n\nfunction decryptCanonicalRequest(\n operation: VideoGenerationOperationWithReferences,\n key: Uint8Array,\n): CanonicalVideoGenerationRequest {\n if (!operation.requestEncrypted) throw new Error(\"Video generation request was erased too early\");\n const parsed = JSON.parse(decryptEnvironmentValue(key, operation.requestEncrypted)) as unknown;\n const request = validateCanonicalRequest(parsed);\n if (videoGenerationRequestDigest(request) !== operation.requestDigest) {\n throw new Error(\"Video generation request digest is inconsistent\");\n }\n return request;\n}\n\nfunction validateCanonicalRequest(value: unknown): CanonicalVideoGenerationRequest {\n const row = record(value);\n const references = Array.isArray(row?.references) ? row.references.map(record) : null;\n if (\n row?.schemaVersion !== 1 ||\n typeof row.modelId !== \"string\" ||\n typeof row.prompt !== \"string\" ||\n ![\n \"text\",\n \"first_frame\",\n \"first_and_last_frames\",\n \"image_reference\",\n \"video_reference\",\n ].includes(String(row.sourceMode)) ||\n !references ||\n !Number.isInteger(row.durationSeconds) ||\n ![\"16:9\", \"4:3\", \"1:1\", \"3:4\", \"9:16\", \"21:9\", \"adaptive\"].includes(String(row.aspectRatio)) ||\n ![\"480p\", \"720p\"].includes(String(row.resolution)) ||\n typeof row.generateAudio !== \"boolean\" ||\n references.some(\n (reference) =>\n !reference ||\n ![\"first_frame\", \"last_frame\", \"image_reference\", \"video_reference\"].includes(\n String(reference.role),\n ) ||\n typeof reference.contentSha256 !== \"string\" ||\n !/^[0-9a-f]{64}$/u.test(reference.contentSha256) ||\n typeof reference.contentType !== \"string\" ||\n !Number.isSafeInteger(reference.byteSize),\n )\n ) {\n throw new Error(\"Encrypted video generation request is malformed\");\n }\n return value as CanonicalVideoGenerationRequest;\n}\n\nfunction decryptProviderBody(\n operation: VideoGenerationOperationWithReferences,\n key: Uint8Array,\n): Record<string, unknown> {\n if (!operation.providerRequestEncrypted) throw new Error(\"Frozen provider request is missing\");\n const body = record(JSON.parse(decryptEnvironmentValue(key, operation.providerRequestEncrypted)));\n if (!body || Buffer.byteLength(JSON.stringify(body)) > 256 * 1024) {\n throw new Error(\"Frozen provider request is malformed\");\n }\n return body;\n}\n\nfunction parseReferenceRole(value: string): GatewayVideoReferenceGrant[\"role\"] {\n if (\n value !== \"first_frame\" &&\n value !== \"last_frame\" &&\n value !== \"image_reference\" &&\n value !== \"video_reference\"\n ) {\n throw new Error(\"Video reference role is invalid\");\n }\n return value;\n}\n\nfunction requireStorage(storage: ObjectStorage | null): ObjectStorage {\n if (!storage) throw new Error(\"Video generation requires object storage\");\n return storage;\n}\n\nfunction nextPoll(service: TurnActivityServices): Date {\n return new Date(Date.now() + service.settings.videoGenerationPollIntervalMs);\n}\n\nfunction waitResult(service: TurnActivityServices): VideoGenerationReconcileResult {\n return {\n action: \"waiting\",\n delayMs: service.settings.videoGenerationPollIntervalMs,\n };\n}\n\nfunction requireApiKey(value: string | null): string {\n if (!value) throw new Error(\"Video provider API key is unavailable\");\n return value;\n}\n\nfunction requireXaiAuth(\n value: Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\"> | null,\n): Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\"> {\n if (!value) throw new Error(\"SuperGrok video authorization is unavailable\");\n return value;\n}\n\n/**\n * A paid video job outlives the connected-account row. Keep its frozen OAuth\n * lease usable after disconnect, and durably replace rotated refresh tokens\n * before exposing them to another provider call. The shared account row is a\n * best-effort mirror only; it is never the operation's recovery authority.\n */\nasync function durableXaiVideoAuth(\n service: TurnActivityServices,\n operation: VideoGenerationOperationWithReferences,\n key: Uint8Array,\n credential: Extract<VideoGenerationProviderCredential, { kind: \"xai-subscription\" }>,\n): Promise<Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\">> {\n let current = credential;\n const frozenEncrypted = operation.credentialEncrypted;\n if (!frozenEncrypted) throw new Error(\"SuperGrok video credential lease is unavailable\");\n let currentEncrypted: string = frozenEncrypted;\n\n let connectedAccount: XaiCredentialForRun | null = null;\n try {\n connectedAccount = await materializeXaiCredentialForRun(service.db, {\n workspaceId: operation.workspaceId,\n subjectId: current.subjectId,\n credentialId: current.credentialId,\n authoritySnapshot: current.authoritySnapshot,\n encryptionKey: key,\n });\n } catch {\n // Disconnect/revocation must not cancel a previously accepted paid job.\n }\n\n return {\n getToken: async () => ({\n accessToken: current.accessToken,\n userId: current.userId,\n }),\n refresh: async () => {\n let next: typeof current | null = null;\n if (connectedAccount) {\n try {\n const result = await refreshXaiSubscriptionCredentialSerialized(service.db, {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n subjectId: current.subjectId,\n credentialId: current.credentialId,\n authoritySnapshot: current.authoritySnapshot,\n encryptionKey: key,\n observedAccessToken: current.accessToken,\n observedRefreshToken: current.refreshToken,\n refresh: async (shared) => {\n const refreshToken = shared.secret.refreshToken;\n if (!refreshToken) {\n throw new Error(\"The connected SuperGrok account cannot be refreshed\");\n }\n const tokens = await refreshXaiToken(refreshToken);\n return {\n secret: {\n version: 1,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n },\n expiresAt:\n xaiAccessTokenExpiry(tokens.accessToken) ??\n new Date(Date.now() + tokens.expiresInSeconds * 1_000),\n };\n },\n });\n connectedAccount = result.credential;\n if (\n connectedAccount.secret.accessToken &&\n connectedAccount.secret.refreshToken &&\n connectedAccount.providerAccountId\n ) {\n next = Object.freeze({\n ...current,\n accessToken: connectedAccount.secret.accessToken,\n refreshToken: connectedAccount.secret.refreshToken,\n userId: connectedAccount.providerAccountId,\n });\n }\n } catch {\n // Disconnect/revocation must not cancel a previously accepted paid job.\n connectedAccount = null;\n }\n }\n if (!next) {\n const tokens = await refreshXaiToken(current.refreshToken);\n next = Object.freeze({\n ...current,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n });\n }\n const nextEncrypted = encryptVideoGenerationXaiCredential(key, next);\n await rotateVideoGenerationCredential(service.db, {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n expectedCredentialEncrypted: currentEncrypted,\n credentialEncrypted: nextEncrypted,\n });\n current = next;\n currentEncrypted = nextEncrypted;\n return { accessToken: current.accessToken, userId: current.userId };\n },\n };\n}\n\nfunction isPermanentProviderFailure(error: unknown): boolean {\n if (error instanceof GatewayVideoApiError) return !error.retryable;\n if (!(error instanceof XaiSubscriptionError)) return false;\n if (error.kind === \"relogin_required\") return true;\n if (error.kind !== \"provider_rejected\") return false;\n return (\n typeof error.status === \"number\" &&\n error.status >= 400 &&\n error.status < 500 &&\n error.status !== 408 &&\n error.status !== 429\n );\n}\n\nfunction privateError(error: unknown): string {\n return (error instanceof Error ? `${error.name}: ${error.message}` : String(error))\n .replace(/https?:\\/\\/\\S+/gu, \"[url omitted]\")\n .slice(0, RECONCILE_ERROR_MAX);\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction isTerminal(status: string): status is VideoGenerationTerminalStatus {\n return [\n \"completed\",\n \"provider_failed\",\n \"cancelled_before_submit\",\n \"outcome_unknown\",\n \"retention_failed\",\n ].includes(status);\n}\n\nfunction terminalStatus(status: string): VideoGenerationTerminalStatus {\n if (!isTerminal(status)) throw new Error(`Video generation status ${status} is not terminal`);\n return status;\n}\n\nfunction retainReferences(\n current: VideoGenerationOperationWithReferences,\n next: Omit<VideoGenerationOperationWithReferences, \"references\">,\n): VideoGenerationOperationWithReferences {\n return { ...next, references: current.references };\n}\n","import type { CanonicalVideoGenerationRequest } from \"@opengeni/core\";\nimport { readResponseTextBounded, type FetchLike } from \"@opengeni/network\";\n\nexport const GATEWAY_VIDEO_PROVIDER_ID = \"vercel-ai-gateway\" as const;\nexport const GATEWAY_VIDEO_START_URL =\n \"https://ai-gateway.vercel.sh/v4/ai/video-model/start\" as const;\nexport const GATEWAY_VIDEO_STATUS_URL =\n \"https://ai-gateway.vercel.sh/v4/ai/video-model/status\" as const;\n\nconst PROTOCOL_VERSION = \"0.0.1\";\nconst VIDEO_SPECIFICATION_VERSION = \"4\";\nconst RESPONSE_MAX_BYTES = 1024 * 1024;\nconst ERROR_MAX_BYTES = 64 * 1024;\n\nexport type GatewayVideoReferenceGrant = Readonly<{\n role: \"first_frame\" | \"last_frame\" | \"image_reference\" | \"video_reference\";\n url: string;\n mediaType: string;\n}>;\n\nexport type GatewayVideoStartResult = Readonly<{ providerJobId: string }>;\nexport type GatewayVideoStatusResult =\n | Readonly<{ status: \"pending\" }>\n | Readonly<{ status: \"completed\"; outputUrl: string; mediaType: string }>\n | Readonly<{ status: \"error\"; publicReason: string }>;\n\nexport class GatewayVideoApiError extends Error {\n constructor(\n readonly status: number | null,\n readonly retryable: boolean,\n message: string,\n ) {\n super(message);\n this.name = \"GatewayVideoApiError\";\n }\n}\n\nexport async function startGatewayVideoGeneration(input: {\n apiKey: string;\n request: CanonicalVideoGenerationRequest;\n idempotencyKey: string;\n referenceGrants: readonly GatewayVideoReferenceGrant[];\n signal?: AbortSignal;\n fetch?: FetchLike;\n}): Promise<GatewayVideoStartResult> {\n return await startGatewayVideoGenerationWithBody({\n apiKey: input.apiKey,\n modelId: input.request.modelId,\n body: buildGatewayVideoStartBody(input.request, input.referenceGrants),\n idempotencyKey: input.idempotencyKey,\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n\n/** Replay entrypoint for the encrypted, byte-stable provider request. */\nexport async function startGatewayVideoGenerationWithBody(input: {\n apiKey: string;\n modelId: string;\n body: Record<string, unknown>;\n idempotencyKey: string;\n signal?: AbortSignal;\n fetch?: FetchLike;\n}): Promise<GatewayVideoStartResult> {\n requireSecret(input.apiKey);\n requireIdempotencyKey(input.idempotencyKey);\n const response = await gatewayFetch({\n url: GATEWAY_VIDEO_START_URL,\n apiKey: input.apiKey,\n modelId: input.modelId,\n body: input.body,\n idempotencyKey: input.idempotencyKey,\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n const parsed = await readGatewayJson(response, \"AI Gateway video start\", input.signal);\n const operation = record(parsed.operation);\n const providerJobId = stringValue(operation?.gatewayJobId);\n if (!providerJobId || providerJobId.length > 1_024) {\n throw new GatewayVideoApiError(null, true, \"AI Gateway video start response is malformed\");\n }\n return Object.freeze({ providerJobId });\n}\n\nexport async function getGatewayVideoGenerationStatus(input: {\n apiKey: string;\n modelId: string;\n providerJobId: string;\n signal?: AbortSignal;\n fetch?: FetchLike;\n}): Promise<GatewayVideoStatusResult> {\n requireSecret(input.apiKey);\n if (!input.providerJobId.trim() || input.providerJobId.length > 1_024) {\n throw new Error(\"AI Gateway video job identity is invalid\");\n }\n const response = await gatewayFetch({\n url: GATEWAY_VIDEO_STATUS_URL,\n apiKey: input.apiKey,\n modelId: input.modelId,\n body: { operation: { gatewayJobId: input.providerJobId } },\n retryNotFound: true,\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n const parsed = await readGatewayJson(response, \"AI Gateway video status\", input.signal);\n const status = stringValue(parsed.status);\n if (status === \"pending\" || status === \"queued\" || status === \"running\") {\n return Object.freeze({ status: \"pending\" });\n }\n if (status === \"error\" || status === \"cancelled\") {\n return Object.freeze({\n status: \"error\",\n publicReason: publicProviderReason(parsed.error, status === \"cancelled\"),\n });\n }\n if (status !== \"completed\" || !Array.isArray(parsed.videos) || parsed.videos.length !== 1) {\n throw new GatewayVideoApiError(null, true, \"AI Gateway video status response is malformed\");\n }\n const video = record(parsed.videos[0]);\n const outputUrl = video?.type === \"url\" ? stringValue(video.url) : null;\n const mediaType = stringValue(video?.mediaType);\n if (!outputUrl || !mediaType || outputUrl.length > 8_192 || mediaType.length > 128) {\n throw new GatewayVideoApiError(null, false, \"AI Gateway returned an unsupported video result\");\n }\n return Object.freeze({ status: \"completed\", outputUrl, mediaType });\n}\n\nexport function buildGatewayVideoStartBody(\n request: CanonicalVideoGenerationRequest,\n referenceGrants: readonly GatewayVideoReferenceGrant[],\n): Record<string, unknown> {\n const expectedRoles = request.references.map((reference) => reference.role);\n if (\n referenceGrants.length !== expectedRoles.length ||\n referenceGrants.some((grant, index) => grant.role !== expectedRoles[index])\n ) {\n throw new Error(\"Video reference grants do not match the sealed request\");\n }\n const files = referenceGrants.map((grant) => ({\n role: grant.role,\n file: {\n type: \"url\" as const,\n url: requireHttps(grant.url),\n mediaType: grant.mediaType,\n },\n }));\n return {\n prompt: request.prompt,\n n: 1,\n aspectRatio: request.aspectRatio,\n resolution: request.resolution,\n duration: request.durationSeconds,\n fps: 24,\n generateAudio: request.generateAudio,\n providerOptions: {},\n ...(request.sourceMode === \"first_frame\" || request.sourceMode === \"first_and_last_frames\"\n ? {\n frameImages: files.map(({ role, file }) => ({\n frameType: role,\n image: file,\n })),\n }\n : request.sourceMode === \"image_reference\" || request.sourceMode === \"video_reference\"\n ? { inputReferences: files.map(({ file }) => file) }\n : {}),\n };\n}\n\nasync function gatewayFetch(input: {\n url: string;\n apiKey: string;\n modelId: string;\n body: Record<string, unknown>;\n idempotencyKey?: string;\n retryNotFound?: boolean;\n signal?: AbortSignal;\n fetch?: FetchLike;\n}): Promise<Response> {\n const timeout = AbortSignal.timeout(60_000);\n const signal = input.signal ? AbortSignal.any([input.signal, timeout]) : timeout;\n let response: Response;\n try {\n response = await (input.fetch ?? globalThis.fetch)(input.url, {\n method: \"POST\",\n redirect: \"error\",\n signal,\n headers: {\n Authorization: `Bearer ${input.apiKey}`,\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n \"ai-gateway-auth-method\": \"api-key\",\n \"ai-gateway-protocol-version\": PROTOCOL_VERSION,\n \"ai-video-model-specification-version\": VIDEO_SPECIFICATION_VERSION,\n \"ai-model-id\": input.modelId,\n \"user-agent\": \"opengeni/video-generation\",\n ...(input.idempotencyKey ? { \"idempotency-key\": input.idempotencyKey } : {}),\n },\n body: JSON.stringify(input.body),\n });\n } catch (error) {\n if (input.signal?.aborted) throw input.signal.reason;\n throw new GatewayVideoApiError(\n null,\n true,\n error instanceof Error ? error.message : \"AI Gateway video request failed\",\n );\n }\n if (response.ok) return response;\n const detail = await readResponseTextBounded(\n response,\n ERROR_MAX_BYTES,\n \"AI Gateway video error\",\n {\n signal,\n },\n ).catch(() => \"\");\n const retryable =\n (input.retryNotFound === true && response.status === 404) ||\n response.status === 408 ||\n response.status === 429 ||\n response.status >= 500;\n throw new GatewayVideoApiError(\n response.status,\n retryable,\n detail\n ? `AI Gateway video request failed (${response.status}): ${boundedError(detail)}`\n : `AI Gateway video request failed (${response.status})`,\n );\n}\n\nasync function readGatewayJson(\n response: Response,\n label: string,\n signal?: AbortSignal,\n): Promise<Record<string, unknown>> {\n const text = await readResponseTextBounded(response, RESPONSE_MAX_BYTES, label, {\n ...(signal ? { signal } : {}),\n });\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new GatewayVideoApiError(null, true, `${label} response is not JSON`);\n }\n const value = record(parsed);\n if (!value) throw new GatewayVideoApiError(null, true, `${label} response is malformed`);\n return value;\n}\n\nfunction requireSecret(value: string): void {\n if (!value.trim()) throw new Error(\"AI Gateway video generation credential is empty\");\n}\n\nfunction requireIdempotencyKey(value: string): void {\n if (!/^ogvid_[0-9a-f]{48}$/u.test(value)) {\n throw new Error(\"AI Gateway video idempotency key is invalid\");\n }\n}\n\nfunction requireHttps(value: string): string {\n const url = new URL(value);\n if (url.protocol !== \"https:\" || url.username || url.password || url.hash) {\n throw new Error(\"Video reference grant must be an HTTPS bearer URL\");\n }\n return url.toString();\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction stringValue(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value : null;\n}\n\nfunction boundedError(value: string): string {\n let message = value;\n try {\n const parsed = record(JSON.parse(value));\n const error = record(parsed?.error);\n message = stringValue(error?.message) ?? stringValue(parsed?.message) ?? value;\n } catch {\n // Preserve the already-bounded non-JSON diagnostic.\n }\n return message.replace(/\\s+/gu, \" \").trim().slice(0, 1_000);\n}\n\nfunction publicProviderReason(error: unknown, cancelled: boolean): string {\n if (cancelled) return \"The video provider cancelled the generation.\";\n const message =\n typeof error === \"string\"\n ? error\n : (stringValue(record(error)?.message) ??\n \"The video provider could not complete the generation.\");\n return message.replace(/\\s+/gu, \" \").trim().slice(0, 1_000);\n}\n","import type { Settings } from \"@opengeni/config\";\nimport { GENERATED_VIDEO_MAX_BYTES, type GeneratedVideoFacts } from \"@opengeni/contracts\";\nimport { pinnedFetch, type FetchLike } from \"@opengeni/network\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport { mkdir, open, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { validateGeneratedVideo, type VerifiedTempFile } from \"./video-media-validation\";\n\nconst DOWNLOAD_TIMEOUT_MS = 15 * 60_000;\nconst READ_STALL_TIMEOUT_MS = 45_000;\nconst MAX_REDIRECTS = 3;\nconst STORAGE_RANGE_BYTES = 1024 * 1024;\ntype StreamReadResult = Awaited<ReturnType<ReadableStreamDefaultReader<Uint8Array>[\"read\"]>>;\n\nexport type RetainedGeneratedVideo = Readonly<{\n bucket: string;\n objectKey: string;\n sizeBytes: number;\n sha256: string;\n facts: GeneratedVideoFacts;\n}>;\n\n/**\n * Treat the provider's result URL and bytes as hostile. DNS is pinned, every\n * redirect is revalidated, and the body streams to a private temporary file\n * under hard time/size limits before ffprobe sees it.\n */\nexport async function downloadGeneratedVideoToVerifiedTemp(input: {\n url: string;\n mediaType: string;\n settings: Settings;\n expectedDurationSeconds: number;\n fetch?: FetchLike;\n signal?: AbortSignal;\n}): Promise<{ temp: VerifiedTempFile; facts: GeneratedVideoFacts }> {\n if (normalizedMediaType(input.mediaType) !== \"video/mp4\") {\n throw new Error(\"Video provider returned an unsupported media type\");\n }\n const timeoutSignal = AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS);\n const signal = input.signal ? AbortSignal.any([input.signal, timeoutSignal]) : timeoutSignal;\n const response = await fetchFollowingSafeRedirects(input.url, {\n settings: input.settings,\n signal,\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n if (!response.ok || !response.body) {\n await response.body?.cancel().catch(() => undefined);\n throw new Error(\"Video provider output could not be downloaded\");\n }\n if (normalizedMediaType(response.headers.get(\"content-type\")) !== \"video/mp4\") {\n await response.body.cancel().catch(() => undefined);\n throw new Error(\"Video provider output is not an MP4 response\");\n }\n const declaredBytes = parseContentLength(response.headers.get(\"content-length\"));\n if (declaredBytes !== null && declaredBytes > GENERATED_VIDEO_MAX_BYTES) {\n await response.body.cancel().catch(() => undefined);\n throw new Error(\"Generated video exceeds the retained output limit\");\n }\n\n await mkdir(input.settings.videoGenerationTempDirectory, { recursive: true, mode: 0o700 });\n const directory = join(input.settings.videoGenerationTempDirectory, `output-${randomUUID()}`);\n const path = join(directory, \"video.mp4\");\n await mkdir(directory, { recursive: false, mode: 0o700 });\n const handle = await open(path, \"wx\", 0o600);\n const reader = response.body.getReader();\n const digest = createHash(\"sha256\");\n let sizeBytes = 0;\n try {\n for (;;) {\n throwIfAborted(signal);\n const chunk = await readChunkWithStallLimit(reader, signal);\n if (chunk.done) break;\n if (chunk.value.byteLength === 0) continue;\n sizeBytes += chunk.value.byteLength;\n if (sizeBytes > GENERATED_VIDEO_MAX_BYTES) {\n throw new Error(\"Generated video exceeds the retained output limit\");\n }\n await writeAll(handle, chunk.value, sizeBytes - chunk.value.byteLength);\n digest.update(chunk.value);\n }\n await handle.sync();\n } catch (error) {\n await reader.cancel(error).catch(() => undefined);\n await handle.close().catch(() => undefined);\n await rm(directory, { recursive: true, force: true });\n throw error;\n } finally {\n try {\n reader.releaseLock();\n } catch {\n // The aborted transport may retain the lock until cancellation settles.\n }\n }\n await handle.close();\n if (sizeBytes <= 0 || (declaredBytes !== null && sizeBytes !== declaredBytes)) {\n await rm(directory, { recursive: true, force: true });\n throw new Error(\"Generated video response was truncated\");\n }\n const sha256 = digest.digest(\"hex\");\n const temp: VerifiedTempFile = Object.freeze({\n directory,\n path,\n sizeBytes,\n sha256,\n contentType: \"video/mp4\",\n cleanup: async () => await rm(directory, { recursive: true, force: true }),\n });\n try {\n const facts = await validateGeneratedVideo({\n path,\n ffprobePath: input.settings.videoGenerationFfprobePath,\n expectedDurationSeconds: input.expectedDurationSeconds,\n });\n return { temp, facts };\n } catch (error) {\n await temp.cleanup();\n throw error;\n }\n}\n\n/** Stream verified bytes into an immutable content-addressed object. */\nexport async function retainVerifiedGeneratedVideo(input: {\n storage: ObjectStorage;\n temp: VerifiedTempFile;\n facts: GeneratedVideoFacts;\n signal?: AbortSignal;\n}): Promise<RetainedGeneratedVideo> {\n if (!input.storage.putObjectStreamIfAbsent) {\n throw new Error(\"Object storage lacks bounded immutable video primitives\");\n }\n const objectKey = `video-generation/objects/sha256/${input.temp.sha256}.mp4`;\n const chunks = fileChunks(input.temp.path, input.signal);\n await input.storage.putObjectStreamIfAbsent({\n key: objectKey,\n contentType: \"video/mp4\",\n chunks,\n byteSize: input.temp.sizeBytes,\n sha256: input.temp.sha256,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n return Object.freeze({\n bucket: input.storage.bucket,\n objectKey,\n sizeBytes: input.temp.sizeBytes,\n sha256: input.temp.sha256,\n facts: input.facts,\n });\n}\n\nasync function fetchFollowingSafeRedirects(\n rawUrl: string,\n input: { settings: Settings; fetch?: FetchLike; signal: AbortSignal },\n): Promise<Response> {\n let url = requireSafeOutputUrl(rawUrl);\n for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) {\n const response = await pinnedFetch(\n url,\n {\n method: \"GET\",\n headers: { accept: \"video/mp4\", \"accept-encoding\": \"identity\" },\n redirect: \"manual\",\n signal: input.signal,\n },\n {\n environment: input.settings.environment,\n // Provider output must never inherit an integration-level private-net override.\n integrationsAllowPrivateNetworkTargets: false,\n },\n {\n label: \"video provider output\",\n requireHttpsOutsideLocalTest: true,\n ...(input.fetch ? { fetchImpl: input.fetch } : {}),\n },\n );\n if (![301, 302, 303, 307, 308].includes(response.status)) return response;\n const location = response.headers.get(\"location\");\n await response.body?.cancel().catch(() => undefined);\n if (!location || redirect === MAX_REDIRECTS) {\n throw new Error(\"Video provider output redirect is invalid\");\n }\n url = requireSafeOutputUrl(new URL(location, url).toString());\n }\n throw new Error(\"Video provider output has too many redirects\");\n}\n\nfunction requireSafeOutputUrl(rawUrl: string): string {\n const url = new URL(rawUrl);\n if (url.protocol !== \"https:\" || url.username || url.password || url.hash) {\n throw new Error(\"Video provider output URL is invalid\");\n }\n return url.toString();\n}\n\nasync function* fileChunks(path: string, signal?: AbortSignal): AsyncIterable<Uint8Array> {\n const stream = createReadStream(path, { highWaterMark: STORAGE_RANGE_BYTES });\n try {\n for await (const chunk of stream) {\n throwIfAborted(signal);\n yield chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);\n }\n } finally {\n stream.destroy();\n }\n}\n\nasync function readChunkWithStallLimit(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n signal: AbortSignal,\n): Promise<StreamReadResult> {\n if (signal.aborted) throw signal.reason;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n reader.read(),\n new Promise<never>((_, reject) => {\n timeout = setTimeout(\n () => reject(new Error(\"Generated video download stalled\")),\n READ_STALL_TIMEOUT_MS,\n );\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nasync function writeAll(\n handle: Awaited<ReturnType<typeof open>>,\n chunk: Uint8Array,\n offset: number,\n): Promise<void> {\n let written = 0;\n while (written < chunk.byteLength) {\n const result = await handle.write(chunk, written, chunk.byteLength - written, offset + written);\n if (result.bytesWritten <= 0) throw new Error(\"Generated video write stalled\");\n written += result.bytesWritten;\n }\n}\n\nfunction normalizedMediaType(value: string | null): string | null {\n const normalized = value?.split(\";\", 1)[0]?.trim().toLowerCase();\n return normalized || null;\n}\n\nfunction parseContentLength(value: string | null): number | null {\n if (value === null) return null;\n if (!/^\\d+$/u.test(value.trim())) throw new Error(\"Generated video length is invalid\");\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new Error(\"Generated video length is invalid\");\n }\n return parsed;\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Video retention was cancelled\");\n}\n","import { GROK_IMAGINE_VIDEO_1_5_MODEL_ID } from \"@opengeni/contracts\";\nimport type { CanonicalVideoGenerationRequest } from \"@opengeni/core\";\nimport {\n getXaiSubscriptionVideoStatus,\n startXaiSubscriptionVideoWithBody,\n XAI_VIDEO_MODEL,\n type XaiFetch,\n type XaiSubscriptionRequestContext,\n type XaiVideoStatus,\n} from \"@opengeni/xai-subscription\";\nimport type { GatewayVideoReferenceGrant } from \"./gateway-video-generation\";\n\nexport function buildXaiVideoStartBody(\n request: CanonicalVideoGenerationRequest,\n referenceGrants: readonly GatewayVideoReferenceGrant[],\n): Record<string, unknown> {\n if (request.modelId !== GROK_IMAGINE_VIDEO_1_5_MODEL_ID) {\n throw new Error(\"The selected video model is not a SuperGrok video model\");\n }\n if (request.sourceMode === \"first_and_last_frames\" || request.sourceMode === \"video_reference\") {\n throw new Error(`Grok Imagine Video does not support ${request.sourceMode}`);\n }\n if (referenceGrants.length !== request.references.length) {\n throw new Error(\"Video reference grants do not match the sealed request\");\n }\n const reference = referenceGrants[0];\n return {\n model: XAI_VIDEO_MODEL,\n prompt: request.prompt,\n duration: request.durationSeconds,\n aspect_ratio: request.aspectRatio,\n resolution: request.resolution,\n ...(request.sourceMode === \"first_frame\" && reference\n ? { image: { url: reference.url } }\n : request.sourceMode === \"image_reference\" && reference\n ? { reference_images: [{ url: reference.url }] }\n : {}),\n };\n}\n\nexport async function startXaiVideoGeneration(input: {\n body: Record<string, unknown>;\n sessionId: string | null;\n auth: Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\">;\n fetch?: XaiFetch;\n}): Promise<{ providerJobId: string }> {\n return await startXaiSubscriptionVideoWithBody({\n body: input.body,\n getToken: input.auth.getToken,\n refresh: input.auth.refresh,\n ...(input.sessionId ? { sessionId: input.sessionId } : {}),\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n\nexport async function getXaiVideoGenerationStatus(input: {\n providerJobId: string;\n sessionId: string | null;\n auth: Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\">;\n fetch?: XaiFetch;\n}): Promise<XaiVideoStatus> {\n return await getXaiSubscriptionVideoStatus({\n providerJobId: input.providerJobId,\n getToken: input.auth.getToken,\n refresh: input.auth.refresh,\n ...(input.sessionId ? { sessionId: input.sessionId } : {}),\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,8BAA8B,0BAAAA,+BAA8B;;;ACArE,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA,uCAAAC;AAAA,EACA,wCAAAC;AAAA,OACK;AACP,SAAS,sCAAsC;AAC/C;AAAA,EACE;AAAA,EACA,uCAAAC;AAAA,EACA,mCAAAC;AAAA,EACA;AAAA,OAIK;;;ACPP,SAAS,+BAAmD;;;ADS5D;AAAA,EACE;AAAA,EACA,wBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,OAEK;;;AEpBA,IAAM,yBAAN,cAAqC,MAAM;AAAA,EAChD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;;;ACJA,SAAS,4BAAyD;AAuB3D,SAAS,mCACd,SAC4C;AAC5C,QAAM,WAAW,oBAAI,IAAqE;AAC1F,aAAW,SAAS,QAAQ,eAAe;AACzC,UAAM,UAAU,SAAS,IAAI,MAAM,MAAM;AACzC,aAAS,IAAI,MAAM,QAAQ;AAAA,MACzB,QAAQ,MAAM;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andboxFileResourcesMaterialized","REMOTE_COMPACTION_V2_IMPLEMENTATION","materializeSandboxFileDownloads","CODEX_CLIENT_VERSION","mintSandboxCodemodeToken","sha256","sandboxGroupId","digest","createHash","getMaterializedSandboxFileResources","markSandboxFileResourcesMaterialized","materializeSandboxFileDownloads","sandboxRunAs","COMPUTER_SCREENSHOT_MAX_DIMENSION","COMPUTER_SCREENSHOT_MAX_PIXELS","completeFileUpload","retryWhileMissing","createHash","createHash","record","record","record","UPLOAD_INTENT_TTL_MS","base64Sextet","COMPUTER_SCREENSHOT_MAX_DIMENSION","COMPUTER_SCREENSHOT_MAX_PIXELS","createHash","uuidFromDigest","completeFileUpload","reference","retryWhileMissing","completeFileUpload","uuidFromDigest","digest","base64Sextet","sandboxRunAs","materializeSandboxFileDownloads","getMaterializedSandboxFileResources","markSandboxFileResourcesMaterialized","createHash","normalizeProtocolJsonValue","sanitizeHistoryItemsForModel","sandboxRunAs","randomUUID","createHash","timer","listCodexAccountStatuses","recordUsageEvent","isSessionEventPersistenceError","publishDurableSessionEvents","createHash","createHash","publishDurableSessionEvents","recordUsageEvent","listCodexAccountStatuses","isSessionEventPersistenceError","recordUsageEvent","recordPendingSessionToolCallResult","nextSessionHistoryPosition","publishDurableSessionEvents","normalizeModelCallUsage","getActiveSessionHistoryItemsPaged","sanitizeHistoryItemsForModel","getActiveSessionHistoryItemsPaged","sanitizeHistoryItemsForModel","outcome","record","appendSessionHistoryItems","sanitizeHistoryItemsForModel","payload","OPEN_SUFFIX_RUN_STATE_BLOB","SandboxLeaseSupersededError","publishDurableSessionEvents","nextSessionHistoryPosition","recordPendingSessionToolCallResult","normalizeModelCallUsage","OPEN_SUFFIX_RUN_STATE_BLOB","recordUsageEvent","deferredSteer","getSessionEvent","getHumanInputResumeForEvent","workspaceCodexSubscriptionActive","appendAndPublishTurnEventsFenced","publishDurableSessionEvents","resolveTurnExecutionPolicyV1","workspaceCodexSubscriptionActive","resolveTurnExecutionPolicyV1","getSessionEvent","getHumanInputResumeForEvent","appendAndPublishTurnEventsFenced","publishDurableSessionEvents","getSessionGoal","CODEX_CREDENTIAL_LEASE_TTL_MS","settleCodexCredentialFailover","publishDurableSessionEvents","CancelledFailure","CancelledFailure","randomUUID","lockedSessionCodexState","sessionPin","CODEX_CREDENTIAL_LEASE_TTL_MS","randomUUID","getSessionGoal","settleCodexCredentialFailover","publishDurableSessionEvents","getFilesForSubject","getWorkspace","retryWhileMissing","resolveWorkspaceAgentHumanInputEnabled","createHash","reference","uuidFromDigest","createHash","getWorkspace","resolveWorkspaceAgentHumanInputEnabled","retryWhileMissing","getFilesForSubject","isSessionCompactionRequested","publishDurableSessionEvents","EmptyCompactionSummaryError","SUMMARY_BUFFER_TOKENS","SUMMARY_BUFFER_TOKENS","EmptyCompactionSummaryError","publishDurableSessionEvents","isSessionCompactionRequested","readLease","providerStartedAt","providerOutcome","result","readLease","readActiveSandbox","withRunCredentialsSession","runOwnedSandboxSetup","record","readActiveSandbox","mintSandboxCodemodeToken","withRunCredentialsSession","runOwnedSandboxSetup","connectionModelAllowed","getSessionGoal","XAI_CREDENTIAL_LEASE_TTL_MS","armXaiCapacityWait","publishDurableSessionEvents","XAI_CREDENTIAL_LEASE_TTL_MS","connectionModelAllowed","getSessionGoal","armXaiCapacityWait","publishDurableSessionEvents","getSessionRootId","clearRunCredentialsForAttempt","codemodeWorkspaceUrl","timer","timer","sandboxRunAs","reference","getSessionRootId","codemodeWorkspaceUrl","sandboxRunAs","mintSandboxCodemodeToken","clearRunCredentialsForAttempt","getSessionTurnForAttempt","listSkillDescriptors","getWorkspaceModelPolicy","listWorkspaceGatewayCustomModels","listWorkspaceOpenRouterCustomModels","listOrganizationModelProviderCustomModelsForWorkspace","namedSubjectHasLiveWorkspaceAuthority","updateSessionTitleWithEvent","workspaceCodexSubscriptionActive","publishDurableSessionEvents","createHash","requireFile","retryWhileMissing","delegation","result","authorization","personalGitHubRepositoryResources","getConnectionMetadata","resolveAcceptedConnectionUse","createGitHubAppInstallationTokenWithExpiry","githubAppBotIdentity","delegation","createHash","ChannelAPartialMutationError","RoutingMutationOutcomeUnknownError","connectorAttachmentSandboxPath","uuidFromDigest","digest","importedFiles","randomUUID","appendAndPublishTurnEventsFenced","publishDurableSessionEvents","resolveCatalogSettings","hasPermission","SandboxChannelAService","sandboxRunAs","DEFAULT_FIRST_PARTY_MCP_PERMISSIONS","createHash","buildPortableSkillArtifact","PORTABLE_SKILL_MAX_FILES","buildPortableSkillArtifact","PORTABLE_SKILL_MAX_FILES","record","buildPortableSkillArtifact","createHash","namedSubjectHasLiveWorkspaceAuthority","DEFAULT_FIRST_PARTY_MCP_PERMISSIONS","hasPermission","listSkillDescriptors","sandboxRunAs","SandboxChannelAService","resolveCatalogSettings","getWorkspaceModelPolicy","workspaceCodexSubscriptionActive","listWorkspaceGatewayCustomModels","listWorkspaceOpenRouterCustomModels","listOrganizationModelProviderCustomModelsForWorkspace","updateSessionTitleWithEvent","publishDurableSessionEvents","getSessionTurnForAttempt","getXaiSessionAccountPin","setXaiSessionAccountPin","getWorkspaceVideoGenerationPolicy","getExternalLinkTurnAuthorization","getSessionTurnForAttempt","serviceTierForLatencyMode","environmentsEncryptionKeyBytes","WORKSPACE_GATEWAY_PROVIDER_ID","resolveModelProvider","reference","videoGenerationCapabilitiesForPolicy","encryptEnvironmentValue","environmentsEncryptionKeyBytes","createHash","randomUUID","retryWhileMissing","createHash","randomUUID","digest","record","positiveInteger","reference","sha256","throwIfAborted","environmentsEncryptionKeyBytes","reference","randomUUID","createHash","encryptEnvironmentValue","reference","CODEX_PROVIDER_ID","CODEX_PROVIDER_ID","getGeneratedImageArtifact","requireFileForSubject","reference","requireFileForSubject","getGeneratedImageArtifact","SandboxChannelAService","sandboxRunAs","sandboxRunAs","SandboxChannelAService","resolveModelProvider","WORKSPACE_GATEWAY_PROVIDER_ID","getWorkspaceVideoGenerationPolicy","environmentsEncryptionKeyBytes","getXaiSessionAccountPin","setXaiSessionAccountPin","videoGenerationCapabilitiesForPolicy","serviceTierForLatencyMode","getExternalLinkTurnAuthorization","getSessionTurnForAttempt","randomUUID","CODEX_CLIENT_VERSION","REMOTE_COMPACTION_V2_IMPLEMENTATION","getMaterializedSandboxFileResources","sandboxRunAs","materializeSandboxFileDownloads","markSandboxFileResourcesMaterialized","environmentsEncryptionKeyBytes","videoGenerationRequestDigest","decryptEnvironmentValue","encryptEnvironmentValue","getVideoGenerationOperation","materializeXaiCredentialForRun","publishDurableSessionEvents","readResponseTextBounded","RESPONSE_MAX_BYTES","record","stringValue","reference","readResponseTextBounded","RESPONSE_MAX_BYTES","GENERATED_VIDEO_MAX_BYTES","createHash","randomUUID","mkdir","open","rm","join","GENERATED_VIDEO_MAX_BYTES","mkdir","join","randomUUID","open","digest","createHash","throwIfAborted","writeAll","rm","sha256","reference","environmentsEncryptionKeyBytes","reference","encryptEnvironmentValue","publishDurableSessionEvents","getVideoGenerationOperation","decryptEnvironmentValue","videoGenerationRequestDigest","record","materializeXaiCredentialForRun","summarizeForCompaction"]}