@opengeni/worker-bundle 2.3.1 → 2.3.2-canary.37090756480001
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/activities/agent-turn/claude-usage-observer.d.ts +30 -6
- package/dist/activities/agent-turn/credential-leases.d.ts +5 -32
- package/dist/activities/agent-turn/errors.d.ts +3 -0
- package/dist/activities/agent-turn/finalization-monitor.d.ts +1 -1
- package/dist/activities/agent-turn/finalization.d.ts +2 -0
- package/dist/activities/agent-turn/quiescence.d.ts +3 -4
- package/dist/activities/agent-turn/subscription-lease.d.ts +38 -0
- package/dist/activities/agent-turn/turn-context.d.ts +1 -1
- package/dist/activities/model-call-fact-reconciler.d.ts +34 -0
- package/dist/activities/session-state.d.ts +2 -2
- package/dist/activities/types.d.ts +7 -0
- package/dist/{activities-control-3HAH4FMG.js → activities-control-3BY4IJKL.js} +166 -35
- package/dist/activities-control-3BY4IJKL.js.map +1 -0
- package/dist/activities-control.d.ts +6 -4
- package/dist/{activities-turn-KU25J3VQ.js → activities-turn-TTNAVGKN.js} +263 -308
- package/dist/activities-turn-TTNAVGKN.js.map +1 -0
- package/dist/activities.d.ts +6 -4
- package/dist/{chunk-3K3ULWEE.js → chunk-PA7Z55P4.js} +242 -17
- package/dist/chunk-PA7Z55P4.js.map +1 -0
- package/dist/{chunk-YG27NEMX.js → chunk-YOI3Z3GF.js} +9 -1
- package/dist/chunk-YOI3Z3GF.js.map +1 -0
- package/dist/http.d.ts +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +82 -16
- package/dist/index.js.map +1 -1
- package/dist/observability-metrics.d.ts +6 -1
- package/dist/sandbox-resume.d.ts +3 -0
- package/dist/session-event-fanout.d.ts +6 -0
- package/dist/worker-service-lifecycle.d.ts +12 -0
- package/dist/workflow-bundle.js +3 -2
- package/package.json +21 -21
- package/src/activities/agent-turn/claim.ts +13 -0
- package/src/activities/agent-turn/claude-usage-observer.ts +99 -8
- package/src/activities/agent-turn/credential-leases.ts +86 -213
- package/src/activities/agent-turn/errors.ts +61 -1
- package/src/activities/agent-turn/failure-settlement.ts +59 -5
- package/src/activities/agent-turn/finalization-monitor.ts +3 -4
- package/src/activities/agent-turn/finalization.ts +8 -3
- package/src/activities/agent-turn/quiescence.ts +3 -4
- package/src/activities/agent-turn/run.ts +24 -20
- package/src/activities/agent-turn/sandbox-establish.ts +2 -0
- package/src/activities/agent-turn/sandbox-runtime.ts +5 -1
- package/src/activities/agent-turn/skill-selection.ts +2 -0
- package/src/activities/agent-turn/subscription-lease.ts +115 -0
- package/src/activities/agent-turn/turn-context.ts +1 -4
- package/src/activities/codex-rotation.ts +2 -12
- package/src/activities/model-call-fact-reconciler.ts +112 -0
- package/src/activities/sandbox-lease.ts +59 -8
- package/src/activities/session-state.ts +29 -4
- package/src/activities/types.ts +7 -0
- package/src/activities-control.ts +2 -0
- package/src/activities-turn.ts +5 -0
- package/src/activities.ts +7 -0
- package/src/http.ts +4 -2
- package/src/index.ts +39 -9
- package/src/observability-metrics.ts +27 -0
- package/src/sandbox-resume.ts +9 -0
- package/src/sandbox-routing.ts +77 -0
- package/src/session-event-fanout.ts +23 -0
- package/src/worker-service-lifecycle.ts +53 -0
- package/src/workflows/file-upload-reaper.ts +2 -0
- package/src/workflows/session.ts +6 -1
- package/dist/activities-control-3HAH4FMG.js.map +0 -1
- package/dist/activities-turn-KU25J3VQ.js.map +0 -1
- package/dist/chunk-3K3ULWEE.js.map +0 -1
- package/dist/chunk-YG27NEMX.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/activity-services.ts","../src/personal-github-git-credentials.ts","../src/pr-review-credentials.ts","../src/activities/codex-capacity.ts","../src/activities/xai-quota.ts","../src/activities/xai-auth.ts","../src/activities/codex-rotation.ts","../src/activities/documents.ts","../src/activities/goals.ts","../src/activities/agent-run-admission.ts","../src/activities/agent-turn/credential-restriction.ts","../src/activities/knowledge-source-sync.ts","../src/activities/google-drive-provider.ts","../src/activities/google-drive-changes.ts","../src/activities/sandbox-images.ts","../src/activities/streaming.ts","../src/sandbox-snapshot-diagnostics.ts","../src/sandbox-archive-storage.ts","../src/sandbox-routing.ts","../src/sandbox-resume.ts","../src/warm-capture-holder.ts","../src/activities/parent-wake.ts","../src/activities/common.ts","../src/activities/incident-telemetry-preflight.ts","../src/activities/incident-telemetry-authority.ts","../src/activities/agent-turn/provider-dispatch-barrier.ts","../src/activities/agent-turn/sandbox-provision.ts","../src/activities/agent-turn/quiescence.ts","../src/activities/agent-turn/errors.ts","../src/activities/run-input.ts","../src/activities/agent-turn/codex-plan-entitlement.ts","../src/activities/types.ts"],"sourcesContent":["import {\n codeSearchDeploymentPolicy,\n dbSearchPath,\n getSettings,\n resolveNatsControlPlaneAuth,\n} from \"@opengeni/config\";\nimport {\n configureChildLifecycleNotices,\n configureCodeSearchDeploymentPolicy,\n createDb,\n} from \"@opengeni/db\";\nimport { createNatsEventBus } from \"@opengeni/events\";\nimport { createObservability } from \"@opengeni/observability\";\nimport { resolveCatalogSettings } from \"@opengeni/core\";\nimport { createObjectStorage } from \"@opengeni/storage\";\nimport type { ActivityDependencies, SharedActivityServices } from \"./activities/types\";\nimport { observabilityEventBusOptions } from \"./observability-metrics\";\nimport { buildPersonalGitHubGitCredentials } from \"./personal-github-git-credentials\";\nimport { createStandaloneConnectionCredentialsPort } from \"./pr-review-credentials\";\n\n/**\n * Build the dependency graph common to both worker roles exactly once.\n *\n * This module deliberately has no import edge to @opengeni/runtime or\n * @opengeni/documents. Those graphs are added by the role-specific factories,\n * preventing an idle process from retaining an unused model SDK or parser\n * stack for its entire lifetime.\n */\nexport function createSharedActivityServices(\n dependencies: ActivityDependencies,\n): () => Promise<SharedActivityServices> {\n let servicesPromise: Promise<SharedActivityServices> | null = null;\n\n return async function services(): Promise<SharedActivityServices> {\n servicesPromise ??= (async () => {\n const settings = dependencies.settings ?? getSettings();\n const observability =\n dependencies.observability ?? createObservability(settings, { component: \"worker\" });\n const searchPath = dbSearchPath(settings);\n const dbClient = dependencies.db\n ? null\n : createDb(settings.databaseUrl, {\n ...(searchPath ? { searchPath } : {}),\n rlsStrategy: settings.rlsStrategy,\n });\n const controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n const db = dependencies.db ?? dbClient!.db;\n const resolvedSettings = (await resolveCatalogSettings(db, settings)).settings;\n // Child lifecycle notice producers are process-global in @opengeni/db;\n // install the boot-validated rollout flag once for this worker.\n configureChildLifecycleNotices({ enabled: settings.childLifecycleNoticesEnabled });\n // Child, scheduled and automation sessions created here freeze their\n // code_search decision from the same deployment policy as the API.\n configureCodeSearchDeploymentPolicy(codeSearchDeploymentPolicy(settings));\n return {\n settings: resolvedSettings,\n catalogSourceSettings: settings,\n db,\n bus:\n dependencies.bus ??\n (await createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth\n ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password }\n : undefined,\n observabilityEventBusOptions(observability),\n )),\n objectStorage: dependencies.objectStorage ?? createObjectStorage(settings),\n observability,\n wakeSessionWorkflow: dependencies.wakeSessionWorkflow ?? null,\n signalSessionAttemptQuiesced: dependencies.signalSessionAttemptQuiesced ?? null,\n inspectSessionAttemptActivity: dependencies.inspectSessionAttemptActivity ?? null,\n signalCodexCapacityWorkflow: dependencies.signalCodexCapacityWorkflow ?? null,\n startSandboxReaperWorkflow: dependencies.startSandboxReaperWorkflow ?? null,\n startVideoGenerationWorkflow: dependencies.startVideoGenerationWorkflow ?? null,\n entitlements: dependencies.entitlements ?? null,\n connectionCredentials:\n dependencies.connectionCredentials ??\n createStandaloneConnectionCredentialsPort(settings, db),\n personalGitHubCredentials:\n dependencies.personalGitHubCredentials ?? buildPersonalGitHubGitCredentials(db, settings),\n };\n })();\n return await servicesPromise;\n };\n}\n","import type { Settings } from \"@opengeni/config\";\nimport {\n type ConnectionCredentialsPort,\n type GitCredentialRepositoryRef,\n type McpPersonalConnectionDelegation,\n} from \"@opengeni/contracts\";\nimport {\n isPersonalGitHubConnection,\n PersonalGitHubConnectionMetadata,\n} from \"@opengeni/contracts/personal-github\";\nimport {\n getConnectionMetadata,\n getPersonalGitHubRepositorySelectionState,\n getSessionAuthorityProjection,\n getSessionTurnForAttempt,\n resolveAcceptedConnectionUse,\n type Database,\n} from \"@opengeni/db\";\nimport {\n PERSONAL_GITHUB_GIT_BROKER_TOKEN_TTL_SECONDS,\n personalGitHubGitBrokerRouteId,\n sealPersonalGitHubGitBrokerClaims,\n type PersonalGitHubGitBrokerClaims,\n type PersonalGitHubGitBrokerRepositoryClaim,\n} from \"@opengeni/github\";\nimport { randomBytes, randomUUID } from \"node:crypto\";\nimport { execFileSync } from \"node:child_process\";\nimport { isIP } from \"node:net\";\nimport { isDeepStrictEqual } from \"node:util\";\n\nconst PERSONAL_GITHUB_SERVER_ID = \"github:personal\";\n\n/**\n * Build the standalone personal-GitHub credential consumer. It returns only an\n * OpenGeni broker bearer: the broad provider OAuth token remains encrypted in\n * the API/database process and never crosses into a sandbox or worker result.\n */\nexport function buildPersonalGitHubGitCredentials(\n db: Database,\n settings: Settings,\n): NonNullable<ConnectionCredentialsPort[\"gitCredentials\"]> | null {\n if (!settings.githubPersonalOauthEnabled) return null;\n const secret = settings.integrationsStateSecret?.trim();\n const publicOrigin = personalGitBrokerOrigin(settings);\n if (!secret || !publicOrigin) {\n throw new Error(\"personal GitHub Git broker configuration is unavailable\");\n }\n\n return async (request) => {\n if (request.provider && request.provider !== \"github\") {\n throw new Error(\"personal GitHub Git broker accepts only GitHub repositories\");\n }\n if (!request.credentialBindingId || !request.repositoryRefs?.length) {\n throw new Error(\"personal GitHub Git broker requires one exact credential binding\");\n }\n const turn = await getSessionTurnForAttempt(\n db,\n request.workspaceId,\n request.sessionId,\n request.attemptId,\n );\n const session = await getSessionAuthorityProjection(db, request.workspaceId, request.sessionId);\n if (\n !turn ||\n !session ||\n turn.id !== request.turnId ||\n turn.executionGeneration !== request.executionGeneration ||\n !isDeepStrictEqual(turn.initiator, request.initiator) ||\n !isDeepStrictEqual(turn.initiatorContext, request.initiatorContext) ||\n session.rootSessionId !== request.rootSessionId\n ) {\n throw new Error(\"personal GitHub Git credential authority is no longer current\");\n }\n const delegation = exactPersonalGitHubDelegation(\n turn.personalConnectionDelegations,\n request.credentialBindingId,\n );\n const snapshot = delegation.personalGitHubRepositorySelection!;\n const repositories = exactRequestedRepositories(\n request.repositoryRefs,\n snapshot.credentialBindingId,\n snapshot.repositories,\n );\n\n const resolution = await resolveAcceptedConnectionUse(db, {\n accountId: request.accountId,\n workspaceId: request.workspaceId,\n sessionId: request.sessionId,\n turnId: request.turnId,\n attemptId: request.attemptId,\n executionGeneration: request.executionGeneration,\n physicalRequestId: randomUUID(),\n usePhase: \"credential_resolution\",\n serverId: PERSONAL_GITHUB_SERVER_ID,\n connectionId: delegation.connectionId,\n providerDomain: \"github.com\",\n connectionKind: \"oauth2\",\n subjectScope: \"subject\",\n ownerSubjectId: delegation.ownerSubjectId,\n });\n if (\n resolution.status !== \"authorized\" ||\n resolution.originWorkspaceId !== delegation.originWorkspaceId ||\n resolution.attribution.connectionId !== delegation.connectionId ||\n resolution.attribution.connectionGeneration !== snapshot.connectionAuthorityGeneration ||\n resolution.attribution.ownerSubjectId !== delegation.ownerSubjectId\n ) {\n throw new Error(\"personal GitHub Git connection authority is no longer current\");\n }\n\n const connection = await getConnectionMetadata(\n db,\n delegation.originWorkspaceId!,\n delegation.connectionId,\n delegation.ownerSubjectId,\n );\n if (\n !connection ||\n connection.accountId !== request.accountId ||\n connection.workspaceId !== delegation.originWorkspaceId ||\n connection.subjectId !== delegation.ownerSubjectId ||\n connection.status !== \"active\" ||\n // connections.version is credential-refresh CAS, not use authority.\n // resolveAcceptedConnectionUse above fences the independent common\n // connection-authority generation carried by the accepted snapshot.\n connection.grantedScopes.length !== 1 ||\n connection.grantedScopes[0] !== \"repo\" ||\n !isPersonalGitHubConnection(connection)\n ) {\n throw new Error(\"personal GitHub Git connection is unavailable\");\n }\n const metadata = PersonalGitHubConnectionMetadata.parse(connection.metadata);\n const currentSelection = await getPersonalGitHubRepositorySelectionState(db, {\n accountId: request.accountId,\n originWorkspaceId: delegation.originWorkspaceId!,\n subjectId: delegation.ownerSubjectId,\n connectionId: delegation.connectionId,\n });\n if (\n !currentSelection ||\n currentSelection.connectionAuthorityGeneration !== snapshot.connectionAuthorityGeneration ||\n currentSelection.selectionGeneration !== snapshot.selectionGeneration ||\n currentSelection.credentialBindingId !== snapshot.credentialBindingId ||\n currentSelection.credentialBindingId !== metadata.credentialBindingId ||\n currentSelection.providerPrincipalId !== metadata.providerPrincipalId ||\n metadata.githubUserId !== metadata.providerPrincipalId\n ) {\n throw new Error(\"personal GitHub repository authority changed\");\n }\n const currentById = new Map(\n currentSelection.repositories.map((repository) => [repository.repositoryId, repository]),\n );\n for (const repository of repositories) {\n const current = currentById.get(repository.repositoryId);\n if (\n !current ||\n current.fullName !== repository.fullName ||\n current.canonicalUrl !== repository.canonicalUrl ||\n current.selectionGeneration !== repository.selectionGeneration ||\n current.disabled ||\n (repository.access === \"write\" &&\n (current.selectedAccess !== \"write\" ||\n current.archived ||\n !personalGitHubCanWrite(current.permissions))) ||\n !personalGitHubCanRead(current.permissions)\n ) {\n throw new Error(\"personal GitHub repository authority changed\");\n }\n }\n\n const identity = {\n name: metadata.githubLogin,\n email: `${metadata.githubUserId}+${metadata.githubLogin}@users.noreply.github.com`,\n };\n if (request.purpose === \"identity\") {\n return {\n workspaceId: request.workspaceId,\n credentialBindingId: request.credentialBindingId,\n provider: \"github\",\n providerHost: \"github.com\",\n identity,\n };\n }\n\n const now = Math.floor(Date.now() / 1_000);\n const baseClaims = {\n version: 1 as const,\n accountId: request.accountId,\n workspaceId: request.workspaceId,\n sessionId: request.sessionId,\n rootSessionId: request.rootSessionId,\n turnId: request.turnId,\n attemptId: request.attemptId,\n executionGeneration: request.executionGeneration,\n originWorkspaceId: delegation.originWorkspaceId!,\n connectionId: delegation.connectionId,\n connectionAuthorityGeneration: snapshot.connectionAuthorityGeneration,\n ownerSubjectId: delegation.ownerSubjectId,\n credentialBindingId: snapshot.credentialBindingId,\n selectionGeneration: snapshot.selectionGeneration,\n };\n const repositoryClaims: PersonalGitHubGitBrokerRepositoryClaim[] = repositories.map(\n (repository) => ({\n ...repository,\n routeId: personalGitHubGitBrokerRouteId(secret, {\n ...baseClaims,\n repository,\n }),\n }),\n );\n const claims: PersonalGitHubGitBrokerClaims = {\n ...baseClaims,\n nonce: randomBytes(24).toString(\"base64url\"),\n issuedAt: now,\n expiresAt: now + PERSONAL_GITHUB_GIT_BROKER_TOKEN_TTL_SECONDS,\n };\n return {\n token: sealPersonalGitHubGitBrokerClaims(secret, claims),\n expiresAt: new Date(claims.expiresAt * 1_000).toISOString(),\n workspaceId: request.workspaceId,\n credentialBindingId: request.credentialBindingId,\n provider: \"github\",\n providerHost: \"github.com\",\n identity,\n transport: {\n kind: \"http_broker\",\n repositories: repositoryClaims.map((repository) => ({\n repositoryUri: repository.canonicalUrl,\n brokerUri: `${publicOrigin}/v1/git/personal/${repository.routeId}`,\n })),\n },\n };\n };\n}\n\nfunction personalGitHubCanRead(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 personalGitHubCanWrite(permissions: {\n push: boolean;\n maintain: boolean;\n admin: boolean;\n}): boolean {\n return permissions.push || permissions.maintain || permissions.admin;\n}\n\nlet cachedDockerBridgeGateway: string | null | undefined;\n\nfunction dockerBridgeGateway(): string | null {\n if (cachedDockerBridgeGateway !== undefined) return cachedDockerBridgeGateway;\n try {\n const value = execFileSync(\n \"docker\",\n [\"network\", \"inspect\", \"bridge\", \"--format\", \"{{(index .IPAM.Config 0).Gateway}}\"],\n { encoding: \"utf8\", timeout: 2_000, maxBuffer: 16 * 1024 },\n ).trim();\n cachedDockerBridgeGateway = isIP(value) ? value : null;\n } catch {\n cachedDockerBridgeGateway = null;\n }\n return cachedDockerBridgeGateway;\n}\n\nexport function personalGitBrokerOrigin(settings: Settings): string | null {\n const value =\n settings.opengeniMcpUrl ??\n (settings.sandboxBackend === \"docker\"\n ? `http://host.docker.internal:${settings.apiPort}`\n : settings.sandboxBackend === \"local\" || settings.sandboxBackend === \"none\"\n ? `http://127.0.0.1:${settings.apiPort}`\n : settings.publicBaseUrl);\n if (!value) return null;\n const url = new URL(value);\n if (\n settings.sandboxBackend === \"docker\" &&\n (url.hostname === \"127.0.0.1\" || url.hostname === \"localhost\")\n ) {\n url.hostname = dockerBridgeGateway() ?? \"host.docker.internal\";\n }\n const dockerPrivateOrigin =\n settings.sandboxBackend === \"docker\" &&\n (url.hostname === \"host.docker.internal\" ||\n url.hostname === cachedDockerBridgeGateway ||\n /^[a-z][a-z0-9-]{0,62}$/iu.test(url.hostname));\n // The `local` and `test` environments accept any origin, which covers the\n // local launcher's Linux Docker sandbox route on the Compose network gateway.\n const privateExecutionOrigin =\n (url.protocol === \"http:\" &&\n (url.hostname === \"127.0.0.1\" || url.hostname === \"localhost\" || dockerPrivateOrigin)) ||\n [\"local\", \"test\"].includes(settings.environment);\n if (\n (url.protocol !== \"https:\" && !privateExecutionOrigin) ||\n url.username ||\n url.password ||\n url.search ||\n url.hash\n ) {\n return null;\n }\n url.pathname = \"/\";\n return url.origin;\n}\n\nfunction exactPersonalGitHubDelegation(\n delegations: McpPersonalConnectionDelegation[],\n credentialBindingId: string,\n): McpPersonalConnectionDelegation {\n const matches = delegations.filter(\n (delegation) =>\n delegation.serverId === PERSONAL_GITHUB_SERVER_ID &&\n delegation.connectionType === \"github_personal\" &&\n delegation.personalGitHubRepositorySelection?.credentialBindingId === credentialBindingId,\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.personalGitHubRepositorySelection\n ) {\n throw new Error(\"personal GitHub Git delegation is unavailable\");\n }\n return delegation;\n}\n\nfunction exactRequestedRepositories(\n refs: GitCredentialRepositoryRef[],\n credentialBindingId: string,\n snapshots: NonNullable<\n McpPersonalConnectionDelegation[\"personalGitHubRepositorySelection\"]\n >[\"repositories\"],\n): Array<Omit<PersonalGitHubGitBrokerRepositoryClaim, \"routeId\">> {\n if (refs.length !== snapshots.length) {\n throw new Error(\"personal GitHub Git request does not match the accepted repository set\");\n }\n const byCanonicalUrl = new Map(\n snapshots.map((repository) => [repository.canonicalUrl, repository]),\n );\n const seen = new Set<string>();\n return refs.map((ref) => {\n const snapshot = byCanonicalUrl.get(ref.uri);\n if (\n !snapshot ||\n seen.has(ref.uri) ||\n ref.provider !== \"github\" ||\n ref.credentialBindingId !== credentialBindingId ||\n ref.connectionId !== undefined ||\n ref.installationId !== undefined ||\n String(ref.repositoryId) !== snapshot.repositoryId ||\n ref.ref !== snapshot.ref ||\n ref.access !== snapshot.access\n ) {\n throw new Error(\"personal GitHub Git request exceeds the accepted repository authority\");\n }\n seen.add(ref.uri);\n return snapshot;\n });\n}\n","import { environmentsEncryptionKeyBytes, type Settings } from \"@opengeni/config\";\nimport type {\n ConnectionCredentialsPort,\n GitCredentials,\n GitCredentialsRequest,\n} from \"@opengeni/contracts\";\nimport { prReviewRegistrationIdFromCredentialBinding } from \"@opengeni/core\";\nimport { decryptVariableSetValue, resolvePrReviewGitCredential, type Database } from \"@opengeni/db\";\nimport {\n createGitHubAppInstallationTokenWithExpiry,\n createGitHubAppInstallationTokenWithSigningSettings,\n} from \"@opengeni/github\";\n\n/** Standalone credential broker for PR Review plus the existing GitHub App path.\n * Embedded hosts keep precedence by supplying their own connectionCredentials. */\nexport function createStandaloneConnectionCredentialsPort(\n settings: Settings,\n db: Database,\n): ConnectionCredentialsPort {\n return {\n gitCredentials: async (request) => await resolveStandaloneGitCredentials(settings, db, request),\n };\n}\n\nasync function resolveStandaloneGitCredentials(\n settings: Settings,\n db: Database,\n request: GitCredentialsRequest,\n): Promise<GitCredentials> {\n const provider = request.provider ?? \"github\";\n const registrationId = request.credentialBindingId\n ? prReviewRegistrationIdFromCredentialBinding(request.credentialBindingId)\n : null;\n if (!registrationId) {\n if (provider !== \"github\") {\n throw new Error(`${provider} Git credentials require an explicit PR Review or host binding`);\n }\n if (request.purpose === \"identity\") {\n return { workspaceId: request.workspaceId };\n }\n const minted = await createGitHubAppInstallationTokenWithExpiry(settings, {\n installationId: request.installationId,\n repositoryIds: request.repositoryIds,\n });\n return {\n token: minted.token,\n workspaceId: request.workspaceId,\n ...(minted.expiresAt ? { expiresAt: minted.expiresAt } : {}),\n };\n }\n\n const authority = await resolvePrReviewGitCredential(db, {\n accountId: request.accountId,\n workspaceId: request.workspaceId,\n registrationId,\n provider,\n sessionId: request.sessionId,\n rootSessionId: request.rootSessionId,\n turnId: request.turnId,\n attemptId: request.attemptId,\n executionGeneration: request.executionGeneration,\n repositoryRefs: (request.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 const echoes = {\n workspaceId: request.workspaceId,\n ...(request.credentialBindingId ? { credentialBindingId: request.credentialBindingId } : {}),\n provider,\n ...(request.providerHost ? { providerHost: request.providerHost } : {}),\n };\n if (request.purpose === \"identity\") {\n return authority.credentialKind === \"github_app\" ||\n authority.credentialKind === \"managed_github_app\"\n ? {\n ...echoes,\n identity: {\n name: \"pr-review[bot]\",\n email: `${authority.appId ?? \"pr-review\"}+pr-review[bot]@users.noreply.github.com`,\n },\n }\n : echoes;\n }\n if (\n authority.credentialKind === \"github_app\" ||\n authority.credentialKind === \"managed_github_app\"\n ) {\n assertGitHubMintMatchesRepositoryRefs(request);\n if (!authority.appId) {\n throw new Error(\"PR Review GitHub App credential is unavailable\");\n }\n const signingSettings =\n authority.credentialKind === \"managed_github_app\"\n ? {\n githubAppId: settings.prReviewGithubAppId,\n githubAppPrivateKey: settings.prReviewGithubAppPrivateKey,\n }\n : manualPrReviewGitHubSigningSettings(settings, {\n appId: authority.appId,\n credentialEncrypted: authority.credentialEncrypted,\n });\n if (\n authority.credentialKind === \"managed_github_app\" &&\n settings.prReviewGithubAppId !== authority.appId\n ) {\n throw new Error(\"OpenGeni Lens App identity no longer matches this registration\");\n }\n const minted = await createGitHubAppInstallationTokenWithSigningSettings(signingSettings, {\n installationId: request.installationId,\n repositoryIds: request.repositoryIds,\n permissions: { contents: \"read\", pull_requests: \"write\" },\n });\n return {\n ...echoes,\n token: minted.token,\n ...(minted.expiresAt ? { expiresAt: minted.expiresAt } : {}),\n };\n }\n if (authority.expiresAt && Date.parse(authority.expiresAt) <= Date.now()) {\n throw new Error(`PR Review ${provider} provider credential has expired`);\n }\n const encryptionKey = environmentsEncryptionKeyBytes(settings);\n if (!encryptionKey || !authority.credentialEncrypted) {\n throw new Error(`PR Review ${provider} provider credential is unavailable`);\n }\n return {\n ...echoes,\n token: decryptVariableSetValue(encryptionKey, authority.credentialEncrypted),\n ...(authority.expiresAt ? { expiresAt: authority.expiresAt } : {}),\n };\n}\n\nfunction manualPrReviewGitHubSigningSettings(\n settings: Settings,\n authority: { appId: string; credentialEncrypted: string | null },\n) {\n const encryptionKey = environmentsEncryptionKeyBytes(settings);\n if (!encryptionKey || !authority.credentialEncrypted) {\n throw new Error(\"PR Review GitHub App credential is unavailable\");\n }\n return {\n githubAppId: authority.appId,\n githubAppPrivateKey: decryptVariableSetValue(encryptionKey, authority.credentialEncrypted),\n };\n}\n\nfunction assertGitHubMintMatchesRepositoryRefs(request: GitCredentialsRequest): void {\n const refs = request.repositoryRefs ?? [];\n const repositoryIds = refs.map((reference) => positiveInteger(reference.repositoryId));\n const installationIds = refs.map((reference) => positiveInteger(reference.installationId));\n if (\n repositoryIds.some((value) => value === null) ||\n installationIds.some((value) => value === null)\n ) {\n throw new Error(\"PR Review GitHub credential request lacks exact repository authority\");\n }\n const exactRepositoryIds = [...new Set(repositoryIds as number[])].sort(\n (left, right) => left - right,\n );\n const requestedRepositoryIds = [...new Set(request.repositoryIds)].sort(\n (left, right) => left - right,\n );\n const exactInstallationIds = [...new Set(installationIds as number[])];\n if (\n exactInstallationIds.length !== 1 ||\n exactInstallationIds[0] !== request.installationId ||\n exactRepositoryIds.length !== request.repositoryIds.length ||\n exactRepositoryIds.some((value, index) => value !== requestedRepositoryIds[index])\n ) {\n throw new Error(\n \"PR Review GitHub token mint authority does not match its repository resources\",\n );\n }\n}\n\nfunction positiveInteger(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isSafeInteger(value) && value > 0) return value;\n if (typeof value === \"string\" && /^\\d+$/.test(value)) {\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;\n }\n return null;\n}\n","import {\n armCodexCapacityWait,\n fetchCodexUsageForAccount,\n getCodexCapacityWaitForSession,\n getXaiCapacityWaitForSession,\n resolveXaiWaiterSubject,\n listCodexAccountStatuses,\n listPendingCodexCapacityWakeTargets,\n reconcileCodexCapacityWait as reconcileCodexCapacityWaitDb,\n reconcileXaiCapacityWait as reconcileXaiCapacityWaitDb,\n type CodexCapacityWakeTarget,\n type CodexCapacitySelectionContext,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport { refreshExhaustedXaiQuota } from \"./xai-quota\";\nimport {\n authoritativeCodexCapacityResetAt,\n codexAccountNeedsLiveCapacityRefresh,\n codexAccountServesModel,\n isCodexCredentialEligible,\n isCodexCredentialHealthy,\n selectCodexCredentialLeaseForTurn,\n} from \"./codex-rotation\";\nimport type {\n ControlActivityServices,\n GetCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitInput,\n ReconcileCodexCapacityWaitResult,\n} from \"./types\";\n\ntype CodexCapacitySignalServices = {\n signalCodexCapacityWorkflow?:\n | NonNullable<ControlActivityServices[\"signalCodexCapacityWorkflow\"]>\n | null\n | undefined;\n wakeSessionWorkflow: ControlActivityServices[\"wakeSessionWorkflow\"];\n};\n\n/**\n * Run a bounded set of usage refreshes, then repair every committed waiter\n * revision even when an individual provider refresh failed. The database\n * outbox remains authoritative; this helper only guarantees that every worker\n * refresh path reaches the same post-commit delivery seam.\n */\nexport async function refreshCodexUsageAndRepairCapacityWaiters(\n refreshes: readonly (() => Promise<unknown>)[],\n repairPendingWakes: () => Promise<void>,\n): Promise<void> {\n await Promise.all(refreshes.map((refresh) => refresh().catch(() => undefined)));\n await repairPendingWakes();\n}\n\n/** Deliver committed waiter revisions; Postgres remains the repairable outbox. */\nexport async function signalCodexCapacityWakeTargets(\n services: CodexCapacitySignalServices,\n targets: readonly CodexCapacityWakeTarget[],\n): Promise<void> {\n await Promise.allSettled(\n targets.map((target) =>\n services.signalCodexCapacityWorkflow\n ? services.signalCodexCapacityWorkflow({\n accountId: target.accountId,\n workspaceId: target.workspaceId,\n sessionId: target.sessionId,\n workflowId: target.workflowId,\n wakeRevision: target.wakeRevision,\n })\n : services.wakeSessionWorkflow\n ? services.wakeSessionWorkflow({\n accountId: target.accountId,\n workspaceId: target.workspaceId,\n sessionId: target.sessionId,\n workflowId: target.workflowId,\n wakeRevision: target.workflowWakeRevision,\n })\n : Promise.resolve(),\n ),\n );\n}\n\n/** Repair a commit/signal crash edge by redelivering every pending revision. */\nexport async function signalPendingCodexCapacityWakeTargets(\n services: CodexCapacitySignalServices & { db: ControlActivityServices[\"db\"] },\n workspaceId: string,\n): Promise<void> {\n const targets = await listPendingCodexCapacityWakeTargets(services.db, workspaceId).catch(\n () => [],\n );\n await signalCodexCapacityWakeTargets(services, targets);\n}\n\nexport function codexCapacityDecision<TPolicyScope = never, TUnavailableDiagnostic = never>(\n context: CodexCapacitySelectionContext<TPolicyScope, TUnavailableDiagnostic>,\n now = new Date(),\n): ReturnType<Parameters<typeof reconcileCodexCapacityWaitDb>[2]> {\n context = {\n ...context,\n accounts: context.accounts.filter(\n (account) => !context.modelId || codexAccountServesModel(account, context.modelId, now),\n ),\n };\n const selected = selectCodexCredentialLeaseForTurn({\n context,\n sessionId: context.sessionId,\n sessionPinnedCredentialId: context.sessionPinnedCredentialId,\n sessionPinSource: context.sessionPinSource,\n sessionLastCredentialId: context.sessionLastCredentialId,\n now,\n });\n const selectedAccount = selected.credentialId\n ? context.accounts.find((account) => account.id === selected.credentialId)\n : undefined;\n const selectedIsAvailable =\n selectedAccount !== undefined &&\n (selectedAccount.id === context.existingCredentialId\n ? isCodexCredentialHealthy(selectedAccount, now)\n : isCodexCredentialEligible(selectedAccount, now));\n if (selected.credentialId && selectedIsAvailable) {\n return {\n kind: \"available\",\n credentialId: selected.credentialId,\n diagnostic: {\n connectedCount: context.accounts.length,\n eligibleCount: context.accounts.filter(\n (account) =>\n (account.id === selected.credentialId ||\n !context.failedCredentialIds?.includes(account.id)) &&\n isCodexCredentialEligible(account, now),\n ).length,\n },\n };\n }\n const policyCredentialId =\n context.sessionPinSource === \"manual\" && context.sessionPinnedCredentialId\n ? context.sessionPinnedCredentialId\n : !context.rotationEnabled\n ? context.activeCredentialId\n : null;\n const capacityAccounts = policyCredentialId\n ? context.accounts.filter((account) => account.id === policyCredentialId)\n : context.accounts;\n const authoritativeReset = authoritativeCodexCapacityResetAt(capacityAccounts, now);\n const hasReconcilableQuotaCooldown = capacityAccounts.some(\n (account) =>\n account.status === \"active\" &&\n account.allocatorEnabled &&\n account.exhaustedKind === \"quota\" &&\n account.exhaustedUntil !== null,\n );\n const policyAccount = capacityAccounts[0] ?? null;\n const mutationOnlyStatusBlock =\n (policyAccount != null &&\n (!policyAccount.allocatorEnabled || policyAccount.status !== \"active\")) ||\n (authoritativeReset === null &&\n capacityAccounts.length > 0 &&\n capacityAccounts.every(\n (account) => !account.allocatorEnabled || account.status !== \"active\",\n ));\n const noneReason =\n selected.decision.kind === \"none\"\n ? context.sessionPinSource === \"manual\" && context.sessionPinnedCredentialId !== null\n ? \"manual_pin_missing\"\n : !context.rotationEnabled && context.activeCredentialId === null\n ? \"rotation_off_active_pointer_missing\"\n : context.policyScope !== null && context.accounts.length === 0\n ? \"policy_filtered_pool_empty\"\n : context.accounts.length === 0\n ? \"no_connected_credentials\"\n : \"no_eligible_credential\"\n : null;\n return {\n kind: \"unavailable\",\n earliestResetAt: authoritativeReset,\n resetKind:\n (selected.decision.kind === \"none\" && !hasReconcilableQuotaCooldown && !authoritativeReset) ||\n selected.decision.kind === \"allocatorDisabled\" ||\n mutationOnlyStatusBlock\n ? \"mutation_only\"\n : authoritativeReset && !hasReconcilableQuotaCooldown\n ? \"authoritative\"\n : \"bounded_refresh\",\n diagnostic: {\n connectedCount: context.accounts.length,\n allocatorEnabledCount: context.accounts.filter((account) => account.allocatorEnabled).length,\n policyHash: context.policyHash,\n ...(noneReason ? { reason: noneReason } : {}),\n },\n };\n}\n\n/**\n * Arm a durable Codex waiter and immediately re-evaluate it under the\n * allocator lock. A capacity mutation that commits just before the waiter is\n * inserted cannot signal a row that does not exist yet, so every arm site must\n * close that edge before returning an hours-away reset timer to the workflow.\n * Mutations after the arm commit still advance the waiter's wake revision.\n */\nexport async function armAndReconcileCodexCapacityWait(\n services: Pick<ControlActivityServices, \"db\" | \"bus\">,\n input: Parameters<typeof armCodexCapacityWait>[1],\n options: { onArmed?: () => void } = {},\n) {\n const armed = await armCodexCapacityWait(services.db, input);\n if (armed.action === \"stopped\") {\n options.onArmed?.();\n await publishDurableSessionEvents(\n services.bus,\n input.workspaceId,\n input.sessionId,\n armed.events,\n );\n return armed;\n }\n if (armed.action !== \"waiting\") return armed;\n\n options.onArmed?.();\n await publishDurableSessionEvents(services.bus, input.workspaceId, input.sessionId, armed.events);\n const evaluated = await reconcileCodexCapacityWaitDb(\n services.db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n waiterId: armed.waiter.id,\n generation: armed.waiter.generation,\n ...(input.now ? { now: input.now } : {}),\n },\n (context) => codexCapacityDecision(context),\n );\n await publishDurableSessionEvents(\n services.bus,\n input.workspaceId,\n input.sessionId,\n evaluated.events,\n );\n return evaluated;\n}\n\nasync function refreshCapacityMetadata(\n services: ControlActivityServices,\n workspaceId: string,\n turnId: string,\n): Promise<void> {\n const accounts = await listCodexAccountStatuses(services.db, workspaceId, turnId).catch(() => []);\n const now = new Date();\n const stale = accounts.filter(\n (account) =>\n account.allocatorEnabled &&\n account.status === \"active\" &&\n (codexAccountNeedsLiveCapacityRefresh(account, now) || account.usageCheckedAt === null),\n );\n await refreshCodexUsageAndRepairCapacityWaiters(\n stale.map(\n (account) => () =>\n fetchCodexUsageForAccount(\n services.db,\n services.settings,\n workspaceId,\n account.id,\n undefined,\n turnId,\n ),\n ),\n () => signalPendingCodexCapacityWakeTargets(services, workspaceId),\n );\n}\n\nexport function createCodexCapacityActivities(services: () => Promise<ControlActivityServices>) {\n async function getCodexCapacityWait(input: GetCodexCapacityWaitInput) {\n const { db } = await services();\n const codexWaiter = await getCodexCapacityWaitForSession(\n db,\n input.workspaceId,\n input.sessionId,\n );\n const xaiWaiter = codexWaiter\n ? null\n : await getXaiCapacityWaitForSession(db, input.workspaceId, input.sessionId);\n const waiter = codexWaiter ?? xaiWaiter;\n return waiter\n ? {\n ...(xaiWaiter ? { provider: \"xai\" as const } : {}),\n waiterId: waiter.id,\n generation: waiter.generation,\n // A capacity mutation may have committed while its Temporal signal\n // was lost or while the workflow continued-as-new. Reconstruct that\n // outbox edge as an immediate re-evaluation rather than waiting for\n // the older timer.\n nextCheckAt:\n waiter.wakeRevision > waiter.observedWakeRevision\n ? new Date(0).toISOString()\n : waiter.nextCheckAt.toISOString(),\n wakeRevision: waiter.wakeRevision,\n }\n : null;\n }\n\n async function reconcileCodexCapacityWait(\n input: ReconcileCodexCapacityWaitInput,\n ): Promise<ReconcileCodexCapacityWaitResult> {\n const resolved = await services();\n if (input.provider === \"xai\") {\n const current = await getXaiCapacityWaitForSession(\n resolved.db,\n input.workspaceId,\n input.sessionId,\n );\n if (!current || current.id !== input.waiterId || current.generation !== input.generation) {\n return { action: \"stale\" };\n }\n const authority = await resolveXaiWaiterSubject(\n resolved.db,\n input.workspaceId,\n input.sessionId,\n );\n if (authority)\n await refreshExhaustedXaiQuota({\n db: resolved.db,\n settings: resolved.settings,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: authority.turnId,\n subjectId: authority.subjectId,\n authoritySnapshot: authority.snapshot,\n });\n const result = await reconcileXaiCapacityWaitDb(resolved.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n waiterId: input.waiterId,\n generation: input.generation,\n });\n if (result.events.length > 0) {\n try {\n await resolved.bus.publish(input.workspaceId, input.sessionId, result.events);\n } catch {\n // Postgres is authoritative; SSE replay/gap fill repairs missed fanout.\n }\n }\n if (result.action === \"resumed\") return { action: \"resumed\" };\n if (result.action === \"waiting\") {\n return {\n action: \"waiting\",\n provider: \"xai\",\n waiterId: result.waiter.id,\n generation: result.waiter.generation,\n nextCheckAt: result.waiter.nextCheckAt.toISOString(),\n wakeRevision: result.waiter.wakeRevision,\n };\n }\n return { action: result.action };\n }\n const current = await getCodexCapacityWaitForSession(\n resolved.db,\n input.workspaceId,\n input.sessionId,\n );\n if (!current || current.id !== input.waiterId || current.generation !== input.generation) {\n return { action: \"stale\" };\n }\n const boundedRefreshAttempted =\n current.resetKind === \"bounded_refresh\" &&\n input.cause === \"timer\" &&\n current.nextCheckAt.getTime() <= Date.now();\n if (boundedRefreshAttempted) {\n // This is a bounded secret-safe control-plane quota refresh. It creates no\n // turn, model call, user message, schedule, or entitlement action.\n await refreshCapacityMetadata(resolved, input.workspaceId, current.blockedTurnId);\n }\n const result = await reconcileCodexCapacityWaitDb(\n resolved.db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n waiterId: input.waiterId,\n generation: input.generation,\n boundedRefreshAttempted,\n },\n (context) => codexCapacityDecision(context),\n );\n if (result.events.length > 0) {\n try {\n await resolved.bus.publish(input.workspaceId, input.sessionId, result.events);\n } catch {\n // Postgres is authoritative; SSE replay/gap fill repairs missed fanout.\n }\n }\n if (result.action === \"resumed\") {\n return { action: \"resumed\" };\n }\n if (result.action === \"waiting\") {\n return {\n action: \"waiting\",\n waiterId: result.waiter.id,\n generation: result.waiter.generation,\n nextCheckAt: result.waiter.nextCheckAt.toISOString(),\n wakeRevision: result.waiter.wakeRevision,\n };\n }\n return { action: result.action };\n }\n\n return { getCodexCapacityWait, reconcileCodexCapacityWait };\n}\n","import { listXaiSubscriptionAccountsMetadata, updateXaiQuotaMetadata } from \"@opengeni/db\";\nimport { fetchXaiSubscriptionQuota } from \"@opengeni/xai-subscription\";\nimport { buildXaiTurnRequestAuthorization } from \"./xai-auth\";\n\n/** Refresh billing, never inference, before treating cached exhaustion as current. */\nexport async function refreshExhaustedXaiQuota(\n input: Omit<Parameters<typeof buildXaiTurnRequestAuthorization>[0], \"credentialId\">,\n) {\n const accounts = await listXaiSubscriptionAccountsMetadata(input.db, input);\n for (const account of accounts) {\n if (account.status !== \"active\" || !account.allocatorEnabled || !account.exhaustedUntil)\n continue;\n if (account.quotaCheckedAt && Date.now() - account.quotaCheckedAt.getTime() < 30_000) continue;\n try {\n const auth = await buildXaiTurnRequestAuthorization({ ...input, credentialId: account.id });\n const quota = await fetchXaiSubscriptionQuota({ context: auth.context });\n // Unknown billing is not evidence that a refusal has cleared.\n if (quota.usedPercent === null) continue;\n await updateXaiQuotaMetadata(input.db, {\n workspaceId: input.workspaceId,\n subjectId: input.subjectId,\n credentialId: account.id,\n quotaUsedPercent: quota.usedPercent,\n quotaResetAt: quota.period?.end ?? null,\n quotaCheckedAt: quota.checkedAt,\n expectedExhaustedUntil: account.exhaustedUntil,\n expectedQuotaCheckedAt: account.quotaCheckedAt,\n exhaustedUntil:\n quota.usedPercent < 100 ? null : (quota.period?.end ?? account.exhaustedUntil),\n });\n } catch {\n // Preserve provider refusal on refresh failure; the durable timer retries.\n }\n }\n}\n","import { environmentsEncryptionKeyBytes, type Settings } from \"@opengeni/config\";\nimport {\n materializeXaiCredentialForRun,\n refreshXaiSubscriptionCredentialSerialized,\n type Database,\n} from \"@opengeni/db\";\nimport type { XaiProviderAccountAuthoritySnapshotV1 } from \"@opengeni/contracts\";\nimport {\n refreshXaiToken,\n XAI_CLIENT_VERSION,\n XAI_SUBSCRIPTION_MODEL_ID_PREFIX,\n XaiSubscriptionReloginRequired,\n xaiAccessTokenExpiry,\n type XaiFetch,\n type XaiSubscriptionRequestContext,\n type XaiSubscriptionTokenSnapshot,\n} from \"@opengeni/xai-subscription\";\n\nexport type XaiTurnRequestAuthorization = {\n context: XaiSubscriptionRequestContext;\n credentialId: string;\n};\n\nexport async function buildXaiTurnRequestAuthorization(input: {\n db: Database;\n settings: Settings;\n accountId: string;\n workspaceId: string;\n subjectId: string;\n sessionId: string;\n turnId: string;\n credentialId: string;\n authoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;\n fetch?: XaiFetch;\n hostedSearch?: XaiSubscriptionRequestContext[\"hostedSearch\"];\n onFinalContextUsage?: XaiSubscriptionRequestContext[\"onFinalContextUsage\"];\n nextRequestId?: XaiSubscriptionRequestContext[\"nextRequestId\"];\n streamIdleTimeoutMs?: XaiSubscriptionRequestContext[\"streamIdleTimeoutMs\"];\n onModelRequestDiagnostic?: XaiSubscriptionRequestContext[\"onModelRequestDiagnostic\"];\n onModelRequestEvent?: XaiSubscriptionRequestContext[\"onModelRequestEvent\"];\n}): Promise<XaiTurnRequestAuthorization> {\n const encryptionKey = environmentsEncryptionKeyBytes(input.settings);\n if (!encryptionKey) {\n throw new Error(\"SuperGrok subscriptions require OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\");\n }\n let credential = await materializeXaiCredentialForRun(input.db, {\n workspaceId: input.workspaceId,\n subjectId: input.subjectId,\n credentialId: input.credentialId,\n authoritySnapshot: input.authoritySnapshot,\n encryptionKey,\n });\n\n const tokenSnapshot = (): XaiSubscriptionTokenSnapshot => {\n const accessToken = credential.secret.accessToken;\n const userId = credential.providerAccountId;\n if (!accessToken || !userId) {\n throw new XaiSubscriptionReloginRequired(\n \"The SuperGrok connection is missing a verified token identity. Reconnect the account.\",\n );\n }\n return { accessToken, userId };\n };\n\n const refresh = async (): Promise<XaiSubscriptionTokenSnapshot> => {\n const observedAccessToken = credential.secret.accessToken;\n const observedRefreshToken = credential.secret.refreshToken;\n if (!observedRefreshToken) {\n throw new XaiSubscriptionReloginRequired(\n \"The SuperGrok connection cannot be refreshed. Reconnect the account.\",\n );\n }\n const result = await refreshXaiSubscriptionCredentialSerialized(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: input.subjectId,\n credentialId: input.credentialId,\n authoritySnapshot: input.authoritySnapshot,\n encryptionKey,\n observedAccessToken,\n observedRefreshToken,\n refresh: async (current) => {\n const refreshToken = current.secret.refreshToken;\n if (!refreshToken) {\n throw new XaiSubscriptionReloginRequired(\n \"The SuperGrok connection cannot be refreshed. Reconnect the account.\",\n );\n }\n const tokens = await refreshXaiToken(refreshToken, {\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\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 credential = result.credential;\n return tokenSnapshot();\n };\n\n return {\n credentialId: input.credentialId,\n context: {\n clientVersion: XAI_CLIENT_VERSION,\n sessionId: input.sessionId,\n turnId: input.turnId,\n getToken: async () => tokenSnapshot(),\n refresh,\n resolveModel: (model) =>\n model.startsWith(XAI_SUBSCRIPTION_MODEL_ID_PREFIX)\n ? model.slice(XAI_SUBSCRIPTION_MODEL_ID_PREFIX.length)\n : model,\n ...(input.hostedSearch ? { hostedSearch: input.hostedSearch } : {}),\n ...(input.onFinalContextUsage ? { onFinalContextUsage: input.onFinalContextUsage } : {}),\n ...(input.nextRequestId ? { nextRequestId: input.nextRequestId } : {}),\n ...(input.streamIdleTimeoutMs ? { streamIdleTimeoutMs: input.streamIdleTimeoutMs } : {}),\n ...(input.onModelRequestDiagnostic\n ? { onModelRequestDiagnostic: input.onModelRequestDiagnostic }\n : {}),\n ...(input.onModelRequestEvent ? { onModelRequestEvent: input.onModelRequestEvent } : {}),\n },\n };\n}\n","// Multi-account P3 — the PURE rotation ranker. Zero I/O: no provider calls, no\n// decrypts, no db. It consumes the already-loaded, metadata-only account list\n// (cached usage columns + the exhausted_until cooldown column) and returns the\n// account a turn should run on. The two call sites (turn-start pre-emption and\n// the reactive 429 catch in agent-turn.ts) feed its result into the unchanged\n// `selectCodexCredentialForTurn` precedence gate (pin > active). Keeping the\n// decision pure makes the whole rotation correctness story unit-testable in\n// isolation (see codex-rotation.test.ts).\nimport type {\n CodexAccountStatus,\n CodexCredentialLeaseSelectionContext,\n CodexLeaseAccountStatus,\n CodexPinSource,\n} from \"@opengeni/db\";\nimport { codexPlanExcludesModel, connectionModelAllowed } from \"@opengeni/db\";\n\nexport type CodexRotationAccount = CodexAccountStatus | CodexLeaseAccountStatus;\n\n/**\n * Model-scoped allocation filter: user connection policy plus proven plan\n * entitlement. A plan exclusion applies only until it expires (one request\n * then re-probes the account) or a different plan is observed.\n */\nexport function codexAccountServesModel(\n account: Pick<CodexRotationAccount, \"allowedModelIds\" | \"planType\" | \"planEntitlementExclusion\">,\n modelId: string,\n now: Date,\n): boolean {\n return (\n connectionModelAllowed(account.allowedModelIds, modelId) &&\n !codexPlanExcludesModel(account, modelId, now)\n );\n}\n\n/** Capacity metadata worth an authoritative live read before/all through an idle. */\nexport function codexAccountNeedsLiveCapacityRefresh(\n account: Pick<\n CodexAccountStatus,\n \"primaryUsedPercent\" | \"secondaryUsedPercent\" | \"exhaustedUntil\" | \"exhaustedKind\"\n >,\n _now: Date,\n): boolean {\n return (\n (account.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||\n (account.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||\n (account.exhaustedKind === \"quota\" && account.exhaustedUntil !== null)\n );\n}\n\nexport type CodexRotationStrategy =\n | \"most_remaining\"\n | \"round_robin\"\n | \"drain_then_next\"\n | \"sharded\";\n\n/**\n * The ONE strategy rotation-enabled workspaces run: sticky-sharded. The legacy\n * strategies are all strictly dominated post-cache-affinity — session\n * stickiness is worth ~half the prompt-cache hit rate, and round_robin /\n * most_remaining churn accounts per turn while drain_then_next concentrates\n * every concurrent session on ONE account (the measured concurrency-eviction\n * failure sharding replaced). Stored `rotation_strategy` values are therefore\n * NORMALIZED here at every read site: legacy values (and any future unknown\n * string) behave as \"sharded\". The column and the legacy branch code are kept\n * intact for old-binary rollback safety — they are simply unreachable through\n * this normalization. The API accepts-but-ignores strategy writes for the same\n * reason (no SDK caller breaks). User-facing choice is intentionally gone: the\n * remaining real intents are rotation on/off, per-account allocator\n * include/exclude, and manual pins — not algorithm selection.\n */\nexport function effectiveRotationStrategy(_stored: string): CodexRotationStrategy {\n return \"sharded\";\n}\n\n/**\n * How a session's codex pin governs THIS turn's account selection (pure). Encodes the\n * policy-pin LIFECYCLE rule: a 'policy' pin is meaningful ONLY while the sharded policy\n * is active.\n * • \"manual\" — a manual pin: honored under EVERY strategy; never moved or cleared.\n * • \"sharded\" — the sharded policy is active and the pin is non-manual: assign / keep\n * / re-shard the deterministic home (covers an unpinned first turn AND\n * an existing policy pin).\n * • \"clearStale\" — a 'policy' pin while the sharded policy is NOT active: IGNORE it\n * (never honor it as a sticky pin — that is the no-escape trap) and\n * clear it lazily so the session converges to the active strategy.\n * • \"unpinned\" — no pin (or none that applies): follow the active strategy / workspace\n * active pointer, unchanged.\n */\nexport type CodexPinDisposition = \"manual\" | \"sharded\" | \"clearStale\" | \"unpinned\";\n\n/** Classify a session's codex pin against the active rotation regime (see {@link CodexPinDisposition}). */\nexport function classifyCodexPin(args: {\n pinnedCredentialId: string | null;\n pinSource: CodexPinSource | null;\n strategy: CodexRotationStrategy;\n rotationEnabled: boolean;\n}): CodexPinDisposition {\n const { pinnedCredentialId, pinSource, strategy, rotationEnabled } = args;\n const pinned = pinnedCredentialId != null;\n // A manual pin is sacrosanct under every strategy — checked FIRST so sharded never\n // touches it. DEFENSE-IN-DEPTH (fail-safe toward sacredness): a pin whose source is\n // anything OTHER than the explicit 'policy' — including a NULL source (a pre-backfill\n // row, or any pin an unforeseen path wrote without labeling it) — is treated as\n // MANUAL. An unlabeled pin must NEVER be policy-moved; only an explicitly-'policy' pin\n // is re-shardable.\n if (pinned && pinSource !== \"policy\") {\n return \"manual\";\n }\n const shardedActive = rotationEnabled && effectiveRotationStrategy(strategy) === \"sharded\";\n if (shardedActive) {\n return \"sharded\";\n }\n // A policy pin outside the sharded regime is stale → clear it.\n if (pinned && pinSource === \"policy\") {\n return \"clearStale\";\n }\n return \"unpinned\";\n}\n\nexport type RotationDecision =\n // The chosen account. `moved` ⇒ it differs from the current active pointer, so\n // the caller must persist the pointer move (and the switch is a \"rotation\").\n | { kind: \"active\"; credentialId: string; moved: boolean }\n // Every eligible account is capped/cooling: idle until the soonest instant ANY\n // account clears every blocking condition (the multi-account generalization of\n // the single-account idle-until-reset).\n | { kind: \"allCapped\"; earliestResetAt: Date }\n // No connected accounts at all (preserves today's relogin-fail path).\n | { kind: \"none\" };\n\nexport type CodexTurnLeaseDecision =\n | RotationDecision\n // The user's manual pin or rotation-off active pointer names a connected row\n // that is disabled for NEW allocations. This is policy-constrained capacity,\n // not a disconnected-account relogin failure: the accepted turn must wait\n // until the row is re-enabled or the governing policy changes.\n | { kind: \"allocatorDisabled\"; credentialId: string };\n\nexport type CodexTurnLeaseSelection = {\n credentialId: string | null;\n decision: CodexTurnLeaseDecision;\n /** Policy/manual homes never move the workspace-global legacy pointer. */\n advanceActivePointer?: boolean;\n};\n\n// Invariant 4 (NO THRASH / BOUNDED) safety floors. An all-capped idle MUST be a\n// positive, bounded wait — a null / elapsed / unknown reset can NEVER collapse it\n// into a 0 or a past instant (which the caller would turn into a 0 continueDelayMs\n// and a tight re-dispatch loop that hammers CPU/DB and never runs the model, so the\n// stale usage cache never self-heals).\n/** The minimum all-capped idle: continueDelayMs is clamped to at least this (never 0). */\nexport const MIN_IDLE_MS = 60_000; // 60s\n/**\n * Cooldown applied to an exhausted account whose cached reset is null / unknown\n * / already-elapsed (the turn hot path never refreshes usage, so a capped window's\n * reset reads stale). Treating it as \"available after a default cooldown\" keeps\n * availableAt — and therefore earliestReset — ALWAYS in the future.\n */\nexport const DEFAULT_RESET_COOLDOWN_MS = 60_000; // 60s\n/** Cached provider usage becomes unavailable only at actual exhaustion. */\nexport const CODEX_USAGE_EXHAUSTED_PCT = 100;\n\nfunction effectiveWindowUsed(usedPercent: number | null, resetAt: Date | null, now: Date): number {\n // A completed provider window is eligible immediately even if its last cache\n // sample still says 100%. This is the five-hour reset boundary—not a TTL\n // heuristic—and avoids stranding a reset subscription while another remains\n // healthy. A future/unknown reset keeps the cached percentage authoritative.\n return resetAt && resetAt.getTime() <= now.getTime() ? 0 : (usedPercent ?? 0);\n}\n\n/** The worse live window: weekly binds as hard as 5h. */\nfunction bindingUsedPct(acct: CodexRotationAccount, now: Date): number {\n return Math.max(\n effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now),\n effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now),\n );\n}\n\n/**\n * Remaining quota across the binding window — the P3 rotation key. Mirrors\n * buildCodexUsageWindowFromCache's `remaining = 100 - percent`, taking the MIN\n * across both windows (the scarcer of 5h/weekly). null percent ⇒ 100 remaining.\n */\nfunction bindingRemaining(acct: CodexRotationAccount, now: Date): number {\n const primaryRemaining =\n 100 - effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now);\n const secondaryRemaining =\n 100 - effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now);\n return Math.min(primaryRemaining, secondaryRemaining);\n}\n\nfunction cooling(acct: CodexRotationAccount, now: Date): boolean {\n return acct.exhaustedUntil != null && acct.exhaustedUntil.getTime() > now.getTime();\n}\n\n/**\n * Healthy for an already-leased/in-flight turn = connected/usable (status\n * \"active\", excludes needs_relogin/error), not cooling, and not exhausted in\n * either provider window. Allocator eligibility is\n * deliberately separate so disabling NEW work cannot break an existing live lease.\n */\nexport function isCodexCredentialHealthy(acct: CodexRotationAccount, now: Date): boolean {\n return (\n acct.status === \"active\" &&\n !cooling(acct, now) &&\n bindingUsedPct(acct, now) < CODEX_USAGE_EXHAUSTED_PCT\n );\n}\n\n/** New automatic allocation requires both health and explicit allocator eligibility. */\nexport function isCodexCredentialEligible(acct: CodexRotationAccount, now: Date): boolean {\n return acct.allocatorEnabled && isCodexCredentialHealthy(acct, now);\n}\n\n/**\n * Public eligibility predicate (same definition as the private `eligible`): an\n * account is usable this turn iff it is connected/active, not cooling, and below\n * actual exhaustion on both windows. The worker's sharded home\n * health-check uses this to decide whether a session's existing policy pin is still\n * a valid home or must be re-sharded.\n */\nexport function isCodexAccountEligible(acct: CodexRotationAccount, now: Date): boolean {\n return isCodexCredentialEligible(acct, now);\n}\n\n/** Deterministic 32-bit FNV-1a over a UTF-16 code-unit stream. Pure, allocation-free. */\nfunction fnv1a32(input: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n // 32-bit FNV prime multiply via Math.imul; `>>> 0` keeps it unsigned.\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\n\n/**\n * Session-sharded HOME account (AM-6): the deterministic account a session runs on\n * under the \"sharded\" strategy — `stableAccountList[ hash(sessionId) % N ]` over the\n * ELIGIBLE (connected, not cooling, not exhausted) accounts in stable created_at\n * order (`listCodexAccountStatuses`).\n *\n * Why deterministic hash over \"least-loaded by session count\" (AM-6): it needs ZERO\n * coordination — every worker computes the same home for a given (sessionId,\n * eligible-set), so a burst of concurrent first-turns can't all read the same\n * \"least-loaded\" account and stampede it (read-then-write skew), and there is no\n * shared round-robin cursor to contend on. It is balanced in expectation.\n *\n * Re-shard (AM-5): pass the just-capped account as already-cooling (or simply let it\n * fall over its threshold) and this reshuffles the SURVIVORS deterministically — the\n * sessions that shared a capped account spread across the remaining pool by their own\n * hashes instead of all re-concentrating on one first-eligible failover.\n *\n * Returns null when NO account is eligible (the caller idles until reset).\n */\nexport function shardCredentialForSession(args: {\n sessionId: string;\n accounts: CodexRotationAccount[];\n now: Date;\n}): string | null {\n const { sessionId, accounts, now } = args;\n const eligibles = accounts.filter((acct) => isCodexCredentialEligible(acct, now));\n if (eligibles.length === 0) {\n return null;\n }\n const index = fnv1a32(sessionId) % eligibles.length;\n return eligibles[index]!.id;\n}\n\n/** earliestResetAt across ALL connected accounts — exported for the sharded all-capped idle. */\nexport function earliestCodexReset(accounts: CodexRotationAccount[], now: Date): Date {\n return earliestReset(accounts, now);\n}\n\n/**\n * The proactive SHARDED home decision (pure — zero I/O, like {@link chooseRotationActive}).\n * Decides the account a session should run on THIS turn under the \"sharded\" strategy,\n * given its current POLICY pin (null on the first turn) and the accounts snapshot:\n *\n * - keepPin: the current policy pin is still ELIGIBLE → run there, no rewrite. This\n * is the steady-state cache-warm path (a session stays on its one home account).\n * - reshard: no policy pin yet (first-turn lazy assignment, AM-7) OR the policy pin\n * is capped/ineligible (proactive re-shard, AM-4) → deterministically shard over the\n * ELIGIBLE set (AM-6) and durably (re)write the pin (`rewritePin:true`, AM-3/AM-5).\n * - allCapped: no account is eligible → the caller idles until the earliest reset.\n *\n * A MANUAL pin is handled by the CALLER (it never reaches here); this function only\n * governs policy homes. Pure so the assignment/re-shard/keep logic is unit-testable\n * without a worker/db env; the caller wraps it with a self-heal usage refresh between\n * two evaluations exactly like chooseRotationActive's allCapped path.\n */\nexport function chooseShardedHome(args: {\n sessionId: string;\n currentPolicyPin: string | null;\n accounts: CodexRotationAccount[];\n now: Date;\n}):\n | { kind: \"home\"; credentialId: string; rewritePin: boolean }\n | { kind: \"allCapped\"; earliestResetAt: Date } {\n const { sessionId, currentPolicyPin, accounts, now } = args;\n const pinRow = currentPolicyPin\n ? (accounts.find((acct) => acct.id === currentPolicyPin) ?? null)\n : null;\n if (pinRow && isCodexCredentialEligible(pinRow, now)) {\n return { kind: \"home\", credentialId: currentPolicyPin!, rewritePin: false };\n }\n const home = shardCredentialForSession({ sessionId, accounts, now });\n if (home == null) {\n return { kind: \"allCapped\", earliestResetAt: earliestReset(accounts, now) };\n }\n return { kind: \"home\", credentialId: home, rewritePin: true };\n}\n\n/**\n * The soonest instant `acct` clears EVERY blocking condition: its cooldown end,\n * and each window's reset (only when that window is at/over the threshold). The\n * literal multi-account generalization of #143's single-account resetsInSeconds.\n *\n * GUARANTEE (invariant 4): the result is ALWAYS in the future. A blocking window\n * whose cached reset is null / unknown / already-elapsed does NOT contribute a past\n * instant (the old EPOCH0 seed bug that made earliestReset land in 1970 → a 0\n * continueDelayMs → a tight idle loop). Such a window is treated as clearing after a\n * default cooldown (now + DEFAULT_RESET_COOLDOWN_MS), so the caller always idles a\n * bounded positive time and re-checks (which refreshes usage and self-heals).\n */\nexport function availableAt(acct: CodexRotationAccount, now: Date): Date {\n const nowMs = now.getTime();\n // An unknown/elapsed block clears after a default cooldown, never in the past.\n const defaultClear = new Date(nowMs + DEFAULT_RESET_COOLDOWN_MS);\n const candidates: Date[] = [];\n // An active cooldown only blocks while it is still in the future; a past cooldown\n // self-clears (matches `cooling()`), so it must not pin availableAt to the past.\n if (acct.exhaustedUntil != null && acct.exhaustedUntil.getTime() > nowMs) {\n candidates.push(acct.exhaustedUntil);\n }\n const windowClear = (over: boolean, resetAt: Date | null | undefined) => {\n if (!over) return;\n // Over-threshold window: wait for its KNOWN future reset; a null/elapsed cached\n // reset is unknown → default cooldown (never a past instant).\n candidates.push(resetAt != null && resetAt.getTime() > nowMs ? resetAt : defaultClear);\n };\n windowClear(\n effectiveWindowUsed(acct.primaryUsedPercent, acct.primaryResetAt, now) >=\n CODEX_USAGE_EXHAUSTED_PCT,\n acct.primaryResetAt,\n );\n windowClear(\n effectiveWindowUsed(acct.secondaryUsedPercent, acct.secondaryResetAt, now) >=\n CODEX_USAGE_EXHAUSTED_PCT,\n acct.secondaryResetAt,\n );\n // Ineligible for a non-quota reason (needs_relogin / error) with no known block, or\n // a cleared cooldown: still idle a bounded cooldown before re-check — never the past.\n if (candidates.length === 0) {\n return defaultClear;\n }\n // Clears EVERY blocking condition ⇒ the MAX of the per-condition clear instants.\n return candidates.reduce((a, b) => (b.getTime() > a.getTime() ? b : a));\n}\n\n/** earliestResetAt across ALL connected accounts (min of each account's availableAt). */\nfunction earliestReset(accounts: CodexRotationAccount[], now: Date): Date {\n return accounts\n .map((acct) => availableAt(acct, now))\n .reduce((a, b) => (b.getTime() < a.getTime() ? b : a));\n}\n\n/**\n * Earliest provider/cooldown timestamp that is actually authoritative. The\n * ranker's `availableAt` deliberately synthesizes a positive default for\n * unknown/stale state; durable capacity waits must distinguish that bounded\n * refresh backoff from a real provider reset timer.\n */\nexport function authoritativeCodexCapacityResetAt(\n accounts: CodexRotationAccount[],\n now: Date,\n): Date | null {\n const future: Date[] = [];\n for (const account of accounts) {\n if (!account.allocatorEnabled || account.status !== \"active\") continue;\n if (account.exhaustedUntil && account.exhaustedUntil.getTime() > now.getTime()) {\n future.push(account.exhaustedUntil);\n }\n if (\n (account.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT &&\n account.primaryResetAt &&\n account.primaryResetAt.getTime() > now.getTime()\n ) {\n future.push(account.primaryResetAt);\n }\n if (\n (account.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT &&\n account.secondaryResetAt &&\n account.secondaryResetAt.getTime() > now.getTime()\n ) {\n future.push(account.secondaryResetAt);\n }\n }\n if (future.length === 0) return null;\n return future.reduce((earliest, candidate) =>\n candidate.getTime() < earliest.getTime() ? candidate : earliest,\n );\n}\n\n/**\n * The bounded all-capped idle delay: clamp(earliestResetAt − now) into\n * [MIN_IDLE_MS, maxMs]. NEVER 0 and NEVER negative, so a null / elapsed / unknown\n * reset cannot collapse the hold into a tight re-dispatch loop (invariant 4). The two\n * agent-turn call sites (proactive turn-start + reactive 429) feed allCapped's\n * earliestResetAt through this before returning continueDelayMs.\n */\nexport function computeIdleDelayMs(earliestResetAt: Date, now: Date, maxMs: number): number {\n const delta = earliestResetAt.getTime() - now.getTime();\n return Math.min(Math.max(delta, MIN_IDLE_MS), maxMs);\n}\n\n/**\n * THE pure rotation ranker. `accounts` arrives in stable created_at order\n * (listCodexAccountStatuses), which deterministically breaks ranking ties.\n */\nexport function chooseRotationActive(args: {\n rotationStrategy: CodexRotationStrategy;\n activeCredentialId: string | null;\n priorCredentialId: string | null;\n accounts: CodexRotationAccount[];\n now: Date;\n}): RotationDecision {\n const { activeCredentialId, priorCredentialId, accounts, now } = args;\n // Normalize at the entry point: rotation-enabled ALWAYS behaves as sharded\n // (see effectiveRotationStrategy). args keeps the field so call sites and\n // tests can still express stored legacy values.\n const rotationStrategy = effectiveRotationStrategy(args.rotationStrategy);\n const allocatableAccounts = accounts.filter((account) => account.allocatorEnabled);\n\n if (allocatableAccounts.length === 0) {\n return { kind: \"none\" };\n }\n\n const eligibles = allocatableAccounts.filter((acct) => isCodexCredentialEligible(acct, now));\n\n // The active pointer is a cursor/manual preference, NOT a sticky lease. In\n // particular, most_remaining must rank the whole eligible pool every turn;\n // keeping a healthy active account sticky was the production monopolization\n // defect fixed by credential allocator. drain_then_next remains the one explicitly sticky\n // strategy, and a manual pin is handled by the caller as explicit policy.\n const decide = (chosen: CodexRotationAccount | undefined): RotationDecision => {\n if (!chosen) {\n return {\n kind: \"allCapped\",\n earliestResetAt: earliestReset(allocatableAccounts, now),\n };\n }\n return {\n kind: \"active\",\n credentialId: chosen.id,\n moved: chosen.id !== activeCredentialId,\n };\n };\n\n if (rotationStrategy === \"round_robin\") {\n // Next eligible AFTER the prior account in list order (wrap around). When the\n // prior account isn't found, start from the head.\n if (eligibles.length === 0) {\n return {\n kind: \"allCapped\",\n earliestResetAt: earliestReset(allocatableAccounts, now),\n };\n }\n const priorIdx = priorCredentialId\n ? allocatableAccounts.findIndex((acct) => acct.id === priorCredentialId)\n : -1;\n const ordered =\n priorIdx >= 0\n ? [\n ...allocatableAccounts.slice(priorIdx + 1),\n ...allocatableAccounts.slice(0, priorIdx + 1),\n ]\n : allocatableAccounts;\n const chosen = ordered.find((acct) => isCodexCredentialEligible(acct, now));\n return decide(chosen);\n }\n\n if (rotationStrategy === \"drain_then_next\") {\n // Stay on the prior account while it is eligible (drain it), else first eligible.\n const priorRow = priorCredentialId\n ? accounts.find((acct) => acct.id === priorCredentialId)\n : undefined;\n if (priorRow && isCodexCredentialEligible(priorRow, now)) {\n return decide(priorRow);\n }\n return decide(eligibles[0]);\n }\n\n // most_remaining (default + the correctness path). Across the eligible set:\n // 1. least active leases (concurrent turns spread before quota metadata moves),\n // 2. most remaining binding quota,\n // 3. fewest historical selections,\n // 4. least-recently selected, then stable created_at/id input order.\n // Base CodexAccountStatus values (pure legacy tests/reactive rank) default the\n // lease/cursor metadata to zero/null, preserving deterministic stable ties.\n const activeLeases = (acct: CodexRotationAccount): number =>\n \"activeLeaseCount\" in acct ? acct.activeLeaseCount : 0;\n const selections = (acct: CodexRotationAccount): number =>\n \"selectionCount\" in acct ? acct.selectionCount : 0;\n const lastSelected = (acct: CodexRotationAccount): number =>\n \"lastSelectedAt\" in acct && acct.lastSelectedAt ? acct.lastSelectedAt.getTime() : 0;\n const chosen = eligibles.reduce<CodexRotationAccount | undefined>((best, acct) => {\n if (!best) {\n return acct;\n }\n if (activeLeases(acct) !== activeLeases(best)) {\n return activeLeases(acct) < activeLeases(best) ? acct : best;\n }\n if (bindingRemaining(acct, now) !== bindingRemaining(best, now)) {\n return bindingRemaining(acct, now) > bindingRemaining(best, now) ? acct : best;\n }\n if (selections(acct) !== selections(best)) {\n return selections(acct) < selections(best) ? acct : best;\n }\n return lastSelected(acct) < lastSelected(best) ? acct : best;\n }, undefined);\n return decide(chosen);\n}\n\n/**\n * Full pure policy at the transaction boundary. A live same-turn lease is\n * idempotent; manual and rotation-off policy preserve pin>pointer behavior; a\n * healthy pin wins only while eligible, so quota/auth quarantine cannot trap a\n * session on one subscription.\n */\nexport function selectCodexCredentialLeaseForTurn<\n TPolicyScope = never,\n TUnavailableDiagnostic = never,\n>(args: {\n context: CodexCredentialLeaseSelectionContext<TPolicyScope, TUnavailableDiagnostic>;\n sessionId: string;\n sessionPinnedCredentialId: string | null;\n sessionPinSource: CodexPinSource | null;\n sessionLastCredentialId: string | null;\n now: Date;\n}): CodexTurnLeaseSelection {\n const { activeCredentialId, rotationEnabled, rotationStrategy, existingCredentialId } =\n args.context;\n if (args.context.failoverExhausted) {\n return { credentialId: null, decision: { kind: \"none\" }, advanceActivePointer: false };\n }\n // User model policy and proven plan entitlement both remove an account for\n // this model only. A plan exclusion is provider truth, never user policy; it\n // becomes inert when a different plan is observed or its TTL elapses.\n const accounts = args.context.modelId\n ? args.context.accounts.filter((account) =>\n codexAccountServesModel(account, args.context.modelId!, args.now),\n )\n : args.context.accounts;\n const failedCredentialIds = new Set(args.context.failedCredentialIds ?? []);\n // Normalized: rotation-enabled always behaves as sharded (see\n // effectiveRotationStrategy); the stored value is only ever legacy residue.\n const strategy = effectiveRotationStrategy(rotationStrategy);\n const existing = existingCredentialId\n ? accounts.find((account) => account.id === existingCredentialId)\n : undefined;\n if (\n existing &&\n !failedCredentialIds.has(existing.id) &&\n isCodexCredentialHealthy(existing, args.now)\n ) {\n return {\n credentialId: existing.id,\n advanceActivePointer: false,\n decision: {\n kind: \"active\",\n credentialId: existing.id,\n moved: existing.id !== activeCredentialId,\n },\n };\n }\n\n const pinDisposition = classifyCodexPin({\n pinnedCredentialId: args.sessionPinnedCredentialId,\n pinSource: args.sessionPinSource,\n strategy,\n rotationEnabled,\n });\n\n // A manual pin is user intent, not a policy hint. Never silently fail it over.\n // We still reject allocator-disabled rows for a NEW turn; a healthy live\n // same-turn lease already returned above before this admission filter.\n if (pinDisposition === \"manual\" && args.sessionPinnedCredentialId) {\n const pinned = accounts.find((account) => account.id === args.sessionPinnedCredentialId);\n if (!pinned) {\n return { credentialId: null, decision: { kind: \"none\" }, advanceActivePointer: false };\n }\n if (failedCredentialIds.has(pinned.id)) {\n return { credentialId: null, decision: { kind: \"none\" }, advanceActivePointer: false };\n }\n if (!pinned.allocatorEnabled) {\n return {\n credentialId: null,\n decision: { kind: \"allocatorDisabled\", credentialId: pinned.id },\n advanceActivePointer: false,\n };\n }\n if (isCodexCredentialHealthy(pinned, args.now)) {\n return {\n credentialId: pinned.id,\n decision: { kind: \"active\", credentialId: pinned.id, moved: false },\n advanceActivePointer: false,\n };\n }\n return {\n credentialId: null,\n decision: {\n kind: \"allCapped\",\n earliestResetAt: availableAt(pinned, args.now),\n },\n advanceActivePointer: false,\n };\n }\n\n // Pin-policy homes compose with the credential allocator by sharding only the candidate list\n // handed to this selector. A future policy filter may therefore choose one\n // primary/fallback pool before this ranker runs; accounts from different pools\n // are never union-ranked here.\n if (pinDisposition === \"sharded\") {\n const unattemptedAccounts = accounts.filter((account) => !failedCredentialIds.has(account.id));\n if (unattemptedAccounts.length === 0) {\n return { credentialId: null, decision: { kind: \"none\" }, advanceActivePointer: false };\n }\n const shard = chooseShardedHome({\n sessionId: args.sessionId,\n currentPolicyPin: args.sessionPinSource === \"policy\" ? args.sessionPinnedCredentialId : null,\n accounts: unattemptedAccounts,\n now: args.now,\n });\n if (shard.kind === \"allCapped\") {\n return {\n credentialId: null,\n decision: shard,\n advanceActivePointer: false,\n };\n }\n return {\n credentialId: shard.credentialId,\n decision: {\n kind: \"active\",\n credentialId: shard.credentialId,\n moved: shard.credentialId !== activeCredentialId,\n },\n advanceActivePointer: false,\n };\n }\n\n // A stale policy pin is intentionally ignored here and cleared by the caller\n // after the atomic selection. Rotation-off/unpinned behavior otherwise keeps\n // the pre-lease pin > active-pointer contract. The pointer is preference, not\n // proof of capacity: rotation-off must wait on a capped pointer rather than\n // falsely admitting it or silently failing over to another subscription.\n if (!rotationEnabled) {\n const active = activeCredentialId\n ? accounts.find((account) => account.id === activeCredentialId)\n : undefined;\n if (!active) {\n return { credentialId: null, decision: { kind: \"none\" }, advanceActivePointer: false };\n }\n if (failedCredentialIds.has(active.id)) {\n return { credentialId: null, decision: { kind: \"none\" }, advanceActivePointer: false };\n }\n if (!active.allocatorEnabled) {\n return {\n credentialId: null,\n decision: { kind: \"allocatorDisabled\", credentialId: active.id },\n advanceActivePointer: false,\n };\n }\n if (!isCodexCredentialHealthy(active, args.now)) {\n return {\n credentialId: null,\n decision: { kind: \"allCapped\", earliestResetAt: availableAt(active, args.now) },\n advanceActivePointer: false,\n };\n }\n return {\n credentialId: active.id,\n decision: { kind: \"active\", credentialId: active.id, moved: false },\n advanceActivePointer: false,\n };\n }\n\n const priorId = args.sessionLastCredentialId ?? activeCredentialId;\n const unattemptedAccounts = accounts.filter((account) => !failedCredentialIds.has(account.id));\n const decision = chooseRotationActive({\n rotationStrategy: strategy,\n activeCredentialId,\n // Per-session continuity is the round-robin/drain cursor. Falling back to\n // the workspace pointer is only correct when this session has never run.\n priorCredentialId: priorId,\n accounts: unattemptedAccounts,\n now: args.now,\n });\n return {\n credentialId: decision.kind === \"active\" ? decision.credentialId : null,\n decision,\n };\n}\n","import type { DocumentServices } from \"@opengeni/documents\";\nimport {\n resolveDocumentIndexAuthority,\n rlsContextForWorkspace,\n withSessionRlsActorContext,\n withWorkspaceUsageLock,\n} from \"@opengeni/db\";\nimport type { ControlActivityServices, IndexDocumentInput } from \"./types\";\n\nexport function createDocumentActivities(\n services: () => Promise<ControlActivityServices>,\n resolveDocumentServices?: () => Promise<DocumentServices>,\n) {\n return {\n indexDocument: async (input: IndexDocumentInput) => {\n const { db, objectStorage } = await services();\n if (!objectStorage) {\n throw new Error(\"object storage is not configured\");\n }\n if (!resolveDocumentServices) {\n throw new Error(\"document services are not configured\");\n }\n const [{ getDocumentForIndexing, indexDocumentNow }, documentServices] = await Promise.all([\n import(\"@opengeni/documents\"),\n resolveDocumentServices(),\n ]);\n const context = await rlsContextForWorkspace(db, input.workspaceId);\n if (context.accountId !== input.accountId) {\n throw new Error(\"document account/workspace authority mismatch\");\n }\n return await withWorkspaceUsageLock(db, input.workspaceId, async (lockedDb) => {\n const storedAuthority = await resolveDocumentIndexAuthority(lockedDb, input);\n if (!storedAuthority) {\n throw new Error(\"document authority was not found before indexing\");\n }\n const suppliedAuthorityFields = [\n \"authorityKind\",\n \"authorityWorkspaceId\",\n \"authoritySubjectId\",\n ] as const;\n const suppliedCount = suppliedAuthorityFields.filter((field) =>\n Object.prototype.hasOwnProperty.call(input, field),\n ).length;\n const suppliedMismatch =\n (Object.prototype.hasOwnProperty.call(input, \"authorityKind\") &&\n input.authorityKind !== storedAuthority.authorityKind) ||\n (Object.prototype.hasOwnProperty.call(input, \"authorityWorkspaceId\") &&\n input.authorityWorkspaceId !== storedAuthority.authorityWorkspaceId) ||\n (Object.prototype.hasOwnProperty.call(input, \"authoritySubjectId\") &&\n input.authoritySubjectId !== storedAuthority.authoritySubjectId);\n if (suppliedMismatch) {\n throw new Error(\"document authority changed before indexing\");\n }\n if (suppliedCount !== 0 && suppliedCount !== suppliedAuthorityFields.length) {\n throw new Error(\"document authority tuple is partial\");\n }\n const claimedDocument = await getDocumentForIndexing(\n lockedDb,\n input.workspaceId,\n input.documentId,\n );\n if (\n !claimedDocument ||\n claimedDocument.authorityKind !== storedAuthority.authorityKind ||\n claimedDocument.authorityWorkspaceId !== storedAuthority.authorityWorkspaceId ||\n claimedDocument.authoritySubjectId !== storedAuthority.authoritySubjectId\n ) {\n throw new Error(\"document authority changed before indexing\");\n }\n const document = await withSessionRlsActorContext(\n {\n subjectId: \"service:document-preparation\",\n privateFileOwnerSubjectId:\n storedAuthority.authorityKind === \"personal\"\n ? storedAuthority.authoritySubjectId\n : null,\n },\n () =>\n indexDocumentNow(\n lockedDb,\n objectStorage,\n input.workspaceId,\n input.documentId,\n documentServices,\n { viewerSubjectId: storedAuthority.authoritySubjectId },\n ),\n );\n if (\n document.authorityKind !== storedAuthority.authorityKind ||\n document.authorityWorkspaceId !== storedAuthority.authorityWorkspaceId ||\n document.authoritySubjectId !== storedAuthority.authoritySubjectId\n ) {\n throw new Error(\"document authority changed before indexing\");\n }\n return document;\n });\n },\n };\n}\n","import {\n allowedFirstPartyMcpToolsForSession,\n configuredStaticUsageLimits,\n isModelAvailableForNewSelection,\n policyProviderIdForModel,\n resolveModelProvider,\n resolveTurnExecutionPolicyV1,\n withCodexCatalogProvider,\n withXaiSubscriptionCatalogProvider,\n WORKSPACE_GATEWAY_MODEL_ID_PREFIX,\n WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n evaluateWorkspaceModelPolicy,\n mergeToolRefs,\n readTurnExecutionPolicyV1,\n type SessionGoal,\n type ToolRef,\n} from \"@opengeni/contracts\";\nimport { isCodexBilledModel } from \"@opengeni/codex\";\nimport {\n enqueueSessionWorkflowWakeIfRunnable,\n getWorkspaceModelPolicy,\n getSessionGoal,\n getSessionTurn,\n materializeGoalContinuation,\n requireSession,\n} from \"@opengeni/db\";\nimport type {\n ControlActivityServices,\n MaybeContinueGoalInput,\n MaybeContinueGoalResult,\n} from \"./types\";\nimport {\n modelFundingForAdmission,\n resolveCatalogSettings,\n resolveWorkspaceCatalogSettings,\n} from \"@opengeni/core\";\nimport { agentRunAdmissionDenial } from \"./agent-run-admission\";\nimport { turnCredentialRestriction } from \"./agent-turn/credential-restriction\";\n\nexport function createGoalActivities(services: () => Promise<ControlActivityServices>) {\n async function enqueueGoalRetryWake(input: MaybeContinueGoalInput): Promise<void> {\n const { db } = await services();\n await enqueueSessionWorkflowWakeIfRunnable(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n temporalWorkflowId: input.workflowId,\n reason: \"goal_retry\",\n // A permanently invalid goal must not become a tight workflow loop. One\n // durable retry after a short delay preserves liveness without scanning.\n notBefore: new Date(Date.now() + 30_000),\n });\n }\n\n async function maybeContinueGoal(\n input: MaybeContinueGoalInput,\n ): Promise<MaybeContinueGoalResult> {\n const service = await services();\n const { db, bus } = service;\n const catalogSourceSettings = service.catalogSourceSettings ?? service.settings;\n // Cheap pre-read: the common goal-less session skips the budget queries.\n const existingGoal = await getSessionGoal(db, input.workspaceId, input.sessionId);\n if (!existingGoal || existingGoal.status !== \"active\") {\n return { action: \"none\" };\n }\n // Loaded before the budget check so the codex-billed predicate and the\n // synthesized turn use the SAME effective policy. An explicit per-turn\n // model can differ from the persisted session default; follow-up goal work\n // follows effective defaults: a started turn or a newer explicit settings\n // boundary. Admission-rejected turns cannot poison that projection.\n // Kept below the goal-less fast path so a non-goal session still skips the\n // reads entirely.\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n // Terminal sessions retain their goal for human recovery, but cannot\n // continue. Do not validate an obsolete model before the locked guard gets\n // the chance to reject that work; otherwise a deterministic error retries.\n if (session.status === \"failed\" || session.status === \"cancelled\") {\n return { action: \"none\" };\n }\n let settings = (await resolveCatalogSettings(db, catalogSourceSettings)).settings;\n const inheritedContinuationModel = session.model;\n let continuationModel = inheritedContinuationModel;\n const continuationReasoningEffort = session.reasoningEffort;\n const continuationLatencyMode = session.latencyMode;\n const workspaceModelPolicy = await getWorkspaceModelPolicy(db, input.workspaceId);\n if (\n inheritedContinuationModel.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||\n inheritedContinuationModel.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX) ||\n session.model.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||\n session.model.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX)\n ) {\n settings = (\n await resolveWorkspaceCatalogSettings(db, catalogSourceSettings, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n retainedProductModelIds: [inheritedContinuationModel, session.model],\n })\n ).settings;\n }\n const modelDecision = goalContinuationModelDecision({\n settings,\n workspaceModelPolicy,\n inheritedModel: inheritedContinuationModel,\n });\n continuationModel = modelDecision.model;\n let modelPolicyBlocked = modelDecision.blocked;\n // remote_v2 sessions may only continue on Codex models — refuse synthesis\n // that would leave the portable/non-Codex path (and mixed history shapes).\n if (\n !modelPolicyBlocked &&\n session.codexCompactionMode === \"remote_v2\" &&\n !isCodexBilledModel(continuationModel)\n ) {\n modelPolicyBlocked = `session is locked to Codex remote compaction v2; model \"${continuationModel}\" is not a Codex subscription model`;\n }\n const turnExecutionPolicy = modelPolicyBlocked\n ? undefined\n : resolveTurnExecutionPolicyV1(settings, {\n modelId: continuationModel,\n requestedModelId: null,\n modelSource: \"continuation\",\n reasoningEffort: continuationReasoningEffort,\n reasoningSource: \"continuation\",\n latencyMode: continuationLatencyMode,\n latencyModeSource: \"continuation\",\n });\n const continuationPolicy: NonNullable<\n Parameters<typeof materializeGoalContinuation>[1][\"policy\"]\n > = {\n model: continuationModel,\n reasoningEffort: continuationReasoningEffort,\n latencyMode: continuationLatencyMode,\n ...(turnExecutionPolicy ? { turnExecutionPolicy } : {}),\n tools: withFirstPartyTools(settings, session.tools),\n sandboxBackend: session.sandboxBackend,\n };\n const decision = await materializeGoalContinuation(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n workflowId: input.workflowId,\n defaultMaxAutoContinuations: settings.goalMaxAutoContinuations ?? null,\n // Pacing between consecutive no-input continuations (never a cap). The\n // materializer re-arms a delayed outbox wake and returns `deferred`.\n idleBackoff: {\n scheduleMs: settings.goalIdleBackoffMs,\n maxMs: settings.goalIdleBackoffMaxMs,\n },\n // A model-policy block takes precedence: it is deterministic (a budget\n // pause can clear on its own; a policy pause needs a model/policy change)\n // and rides the same visible-pause channel.\n admission: async (tx, causalTurn) => {\n // The materializer selects this exact causal row under its session/goal\n // locks and freezes policy only after admission returns. Never infer\n // credential authority from the generated continuation's payload.\n const sourceTurn = causalTurn\n ? await getSessionTurn(tx, input.workspaceId, causalTurn.id)\n : null;\n if (causalTurn && (!sourceTurn || sourceTurn.sessionId !== input.sessionId)) {\n throw new Error(\"Goal continuation source turn is unavailable\");\n }\n const sourcePolicy = readTurnExecutionPolicyV1(sourceTurn?.metadata);\n if (turnExecutionPolicy) {\n const credentialRestriction = turnCredentialRestriction(\n sourcePolicy.kind === \"valid\" ? sourcePolicy.policy : turnExecutionPolicy,\n session.metadata,\n );\n continuationPolicy.turnExecutionPolicy = credentialRestriction\n ? { ...turnExecutionPolicy, credentialRestriction }\n : turnExecutionPolicy;\n }\n const budgetBlocked = modelPolicyBlocked\n ? null\n : await goalRunBudgetBlocked(\n { ...service, settings, db: tx },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n model: continuationModel,\n initiatingHumanSubjectId: causalTurn?.initiatingHumanSubjectId ?? null,\n },\n );\n return {\n budgetBlocked: modelPolicyBlocked ?? budgetBlocked?.message ?? null,\n budgetPausedReason: modelPolicyBlocked\n ? \"limits\"\n : (budgetBlocked?.pausedReason ?? \"limits\"),\n };\n },\n policy: continuationPolicy,\n // Long-wait guidance is only given when `wait_for_input` is actually in this\n // session's effective first-party selection (the same source the worker\n // signs into the delegated token and the API uses to register tools), so\n // a pre-existing narrowed selection is never told to call a missing tool.\n prompt: (goal, autoContinuation, cap) => {\n const effectiveFirstPartyTools = allowedFirstPartyMcpToolsForSession(\n settings,\n session.firstPartyMcpTools,\n );\n return goalContinuationPrompt(goal, autoContinuation, cap, {\n inputWaitAvailable: effectiveFirstPartyTools.includes(\"wait_for_input\"),\n humanInputRespondAvailable: effectiveFirstPartyTools.includes(\n \"session_human_input_respond\",\n ),\n });\n },\n });\n if (decision.events.length > 0) {\n await bus.publish(input.workspaceId, input.sessionId, decision.events);\n }\n return { action: decision.action };\n }\n\n return {\n enqueueGoalRetryWake,\n maybeContinueGoal,\n };\n}\n\nexport function goalContinuationModelDecision(input: {\n settings: Settings;\n workspaceModelPolicy: Awaited<ReturnType<typeof getWorkspaceModelPolicy>>;\n inheritedModel: string;\n}): { model: string; blocked: string | null } {\n const catalogSettings = input.settings.supergrokSubscriptionEnabled\n ? withXaiSubscriptionCatalogProvider(\n input.settings.codexSubscriptionEnabled\n ? withCodexCatalogProvider(input.settings)\n : input.settings,\n )\n : input.settings.codexSubscriptionEnabled\n ? withCodexCatalogProvider(input.settings)\n : input.settings;\n const policyBlocks = (modelId: string): boolean =>\n input.workspaceModelPolicy !== null &&\n !evaluateWorkspaceModelPolicy(input.workspaceModelPolicy, {\n providerId: policyProviderIdForModel(catalogSettings, modelId),\n modelId,\n }).allowed;\n if (!resolveModelProvider(catalogSettings, input.inheritedModel)) {\n return {\n model: input.inheritedModel,\n blocked: `model \"${input.inheritedModel}\" is no longer in the deployment or workspace catalog; choose an available model before resuming the goal`,\n };\n }\n if (!isModelAvailableForNewSelection(catalogSettings, input.inheritedModel)) {\n return {\n model: input.inheritedModel,\n blocked: `model \"${input.inheritedModel}\" is retired from new selection; choose an available model before resuming the goal`,\n };\n }\n if (!policyBlocks(input.inheritedModel)) {\n return { model: input.inheritedModel, blocked: null };\n }\n return {\n model: input.inheritedModel,\n blocked: `workspace model policy blocks model \"${input.inheritedModel}\"; pick an allowed model or change the workspace model policy`,\n };\n}\n\nexport function goalContinuationFundedWithoutCredits(\n settings: Settings,\n model: string,\n codexBilled: boolean,\n): boolean {\n return modelFundingForAdmission(settings, model, codexBilled).fundedWithoutCredits;\n}\n\nexport function goalContinuationPrompt(\n _goal: SessionGoal,\n _autoContinuation: number,\n _cap: number | null,\n options: { inputWaitAvailable?: boolean; humanInputRespondAvailable?: boolean } = {},\n): string {\n const waitingGuidance = options.inputWaitAvailable\n ? [\n \"Waiting on child sessions, background commands, or external events:\",\n \"- When further progress depends on work already in flight, do not sleep, loop, or poll session or command state repeatedly.\",\n \"- If progress depends on work already in flight and the wait is long or uncertain, call opengeni__wait_for_input with a concrete reason and timeoutSeconds, then end your turn immediately. A preliminary status check is not required. Relevant session input or the safety deadline will start a new turn, and this goal stays active.\",\n \"- No short execution wait is required first. Choose the safety deadline for the dependency or a meaningful monitoring cadence; an out-of-turn wait may span hours or days within the tool's limits. Do not schedule model wakeups merely to repeat reassurance. Honor explicit user/task/Skill check or update cadences within existing authority.\",\n \"- If the immediately preceding user-facing update already reported this same unchanged wait, do not restate it or produce another equivalent final answer. Call opengeni__wait_for_input and end the turn. Report only material new state or a newly discovered blocker, unless an explicit user/task/Skill update cadence calls for an update.\",\n \"- If you are blocked on a human decision, use opengeni__goal_pause under the blocked audit below instead.\",\n \"\",\n ]\n : [];\n const childNoticeGuidance = [\n \"Child lifecycle notices:\",\n \"- A `child_requires_action` update means a worker you spawned is blocked on a question or a tool approval and will not progress until it is answered. \" +\n (options.humanInputRespondAvailable\n ? \"If you know the answer to its question, answer it with opengeni__session_human_input_respond (pass the worker's sessionId, the requestId from the notice, and a response). \"\n : \"\") +\n \"Tool approvals can only be decided by a human. If you cannot resolve the blocker yourself, report the exact blocker (worker session id, the question); if it prevents further goal progress, pause under the blocked audit instead of retrying the worker or treating a human decision as an in-flight wait.\",\n \"- `child_requires_action_resolved`, `child_paused`, `child_waiting_capacity`, and `child_progress` updates are informational: a resolved notice means the worker is moving again; a paused worker needs a human or you to resume it; a capacity wait resumes by itself; a progress note needs no action.\",\n \"\",\n ];\n return [\n \"Automatic goal continuation (generated input, not a new user request or grant of authority). Resume established work toward the full applied objective and verify its requested end state.\",\n \"\",\n \"Goal recovery:\",\n \"- Use the current applied goal frozen for this turn, including its success criteria, root constraints, and report requirements, as the authoritative objective. Pending proposals and older goal revisions do not replace it; change it only through the authorized goal-mutation controls, without widening authority.\",\n \"- Treat this continuation as re-entry into the full objective, not as a request to perform one step and stop.\",\n \"- Resume from established work and relevant evidence rather than restarting discovery or a full reconciliation on every turn. Perform full reconciliation or a comprehensive audit when the goal, user, or applicable Skill calls for it, when uncertainty or recovery warrants it, or when required by risk or a gate.\",\n \"- Do not rely on previous assistant claims of progress or completion; use them only to locate authoritative evidence.\",\n \"- If authoritative evidence already proves the full objective, call opengeni__goal_complete instead of manufacturing more work.\",\n \"- Before repeating a state-setting action, verify whether its desired state already holds, using relevant evidence that remains valid or a fresh check when needed. If it does, do not repeat it; continue the overall goal.\",\n \"\",\n \"Continuation behavior:\",\n \"- This goal persists across turns. A runtime boundary can end one turn without shrinking the objective; the next continuation resumes the same full objective.\",\n \"- Keep working until the requested end state is true and verified. Do not end the turn merely because one useful action completed, and do not redefine success around a smaller or easier task.\",\n \"- An incomplete-status report is not a substitute for continuing the work. If the remaining problem can be investigated or addressed within your current authority, continue that work in this turn rather than returning another equivalent status-only final.\",\n \"- Distinguish unfinished work from a blocker that actually requires human input or external change; use the existing waiting and blocked audits only when their conditions hold.\",\n \"- Temporary rough edges are acceptable while the work is moving in the right direction. Completion still requires the requested end state to be true and verified.\",\n \"\",\n \"Work from evidence:\",\n \"Use authoritative workspace and external evidence, including prior tool results that remain relevant and valid. Reuse evidence only for the requirement, scope, version, and state it actually establishes; recheck changed, stale, uncertain, or insufficient evidence. Conversation summaries and assistant claims are pointers, not proof. Do not infer progress or evidence validity merely from this continuation. Improve, replace, or remove existing work as needed within authority to satisfy the actual objective.\",\n \"\",\n \"Progress visibility:\",\n \"If a planning tool is available and the next work is meaningfully multi-step, use it to show a concise plan tied to the real objective. Keep the plan current as steps complete or the next best action changes. Skip planning overhead for trivial one-step progress, and do not treat a plan update as a substitute for doing the work.\",\n \"\",\n \"Fidelity:\",\n \"- Optimize each turn for movement toward the requested end state, not for the smallest stable-looking subset or easiest passing change.\",\n \"- Do not substitute a narrower, safer, smaller, merely compatible, or easier-to-test solution because it is more likely to pass current tests.\",\n \"- Treat alignment as movement toward the requested end state. An edit is aligned only if it makes the requested final state more true; useful-looking behavior that preserves a different end state is misaligned.\",\n \"\",\n \"Completion audit:\",\n \"Before deciding that the goal is achieved, treat completion as unproven and verify it against the actual current state. This full completion audit is required even when ordinary continuation did not need full reconciliation; reuse still-valid authoritative evidence, but refresh it when the requirement or gate requires a fresh check:\",\n \"- Derive concrete requirements from the objective and any referenced files, plans, specifications, issues, or user instructions.\",\n \"- Preserve the applied objective's scope; do not redefine success around the work that already exists.\",\n \"- For every explicit requirement, named artifact, command, test, gate, invariant, and deliverable, identify and inspect the authoritative evidence that would prove it.\",\n \"- Match verification scope to requirement scope. Treat uncertain, indirect, incomplete, or missing evidence as not achieved and continue working.\",\n \"- The audit must prove completion, not merely fail to find obvious remaining work.\",\n \"- For document report deliverables (a document the user asked for, or a large report meant to be kept or shared), follow the Documents Skill: create the durable native document first, inspect its relevant final head after the last edit, and provide the returned artifact reference. Declare report requirements through the available goal tools before authoring and satisfy every persisted report requirement with verified artifact delivery evidence before completion. Sandbox paths and raw file IDs do not prove report delivery. If artifact tooling or access is unavailable, keep that deliverable incomplete and state the blocker; never invent proof or silently substitute a local report. Ordinary chat answers, short progress updates, source-code links, and explicitly requested local-file work remain outside this report contract.\",\n \"\",\n \"Do not rely on intent, partial progress, memory of earlier work, or a plausible final answer as proof of completion. Call opengeni__goal_complete with concrete evidence only when the full objective is actually achieved and no required work remains.\",\n \"Goal evidence is a short proof for the ledger, not the deliverable. After goal_complete succeeds, finish this same turn with the requested user-facing answer, or a concise summary and retained artifact link. Goal completion stops future automatic continuations; it does not send the answer or end this turn. Never compress a report into evidence or omit the final reply.\",\n \"Goal progress notes are short human-readable milestone statuses, not raw transcripts or continuation instructions. Keep normal spaces and summarize detail instead of squeezing words into a ledger field. The text and successCriteria fields each allow 8192 UTF-8 bytes, progressNote allows 8192 UTF-8 bytes, rationale allows 2048 UTF-8 bytes, and evidence allows 8192 characters.\",\n \"\",\n ...waitingGuidance,\n ...childNoticeGuidance,\n \"Blocked audit:\",\n \"- Base persistence on evidence, not a fixed number of turns or retries. Investigate recoverable failures and try plausible safe alternatives within current authority when they could materially advance the goal; do not exhaust every imaginable alternative or repeat an unchanged failure without a reason to expect progress.\",\n \"- A definitive missing permission, required human decision, or external prerequisite with no actionable authorized path can justify pausing immediately. State the concrete blocker, relevant evidence or attempted alternatives, and what must change to resume. Tool approvals remain human-only.\",\n \"- If progress depends on work already in flight or a meaningful timed recheck, use the available waiting mechanism rather than pausing the goal; continue any independent authorized work first.\",\n \"- Do not pause merely because the work is hard, slow, uncertain, incomplete, or would benefit from clarification.\",\n \"- When no meaningful authorized progress remains and the blocker requires human input or an external change that cannot be handled by an available wait or monitoring mechanism, call opengeni__goal_pause with the concrete blocker instead of repeatedly reporting it while leaving the goal active.\",\n \"\",\n \"Do not call opengeni__goal_complete or opengeni__goal_pause unless the corresponding audit above is satisfied.\",\n ].join(\"\\n\");\n}\n\n/**\n * Ensures a session/turn carries the first-party \"opengeni\" MCP server, which\n * hosts set_session_title, the goal tools, and the permission-gated\n * orchestration/environment/github tools. Attached to EVERY session/turn (not\n * just goal-bearing ones); built-in tool refs are not auto-added to empty tool\n * lists anywhere else in the pipeline. No-op when the server is not configured.\n */\nexport function withFirstPartyTools(settings: Settings, tools: ToolRef[]): ToolRef[] {\n if (!settings.mcpServers.some((server) => server.id === \"opengeni\")) {\n return tools;\n }\n return mergeToolRefs(tools, [{ kind: \"mcp\", id: \"opengeni\" }]);\n}\n\n/**\n * Goals share scheduled admission and pause visibly without synthesizing work.\n */\nexport async function goalRunBudgetBlocked(\n services: Parameters<typeof agentRunAdmissionDenial>[0],\n input: Omit<Parameters<typeof agentRunAdmissionDenial>[1], \"requestedAgentRuns\">,\n): Promise<{ pausedReason: \"limits\" | \"allowance\"; message: string } | null> {\n const denial = await agentRunAdmissionDenial(services, { ...input, requestedAgentRuns: 1 });\n if (denial === null) return null;\n if (denial === \"allowance_exhausted\") {\n return { pausedReason: \"allowance\", message: \"OpenGeni usage allowance exhausted\" };\n }\n const limits = configuredStaticUsageLimits(services.settings);\n const messages = {\n insufficient_credits: \"insufficient OpenGeni credits\",\n monthly_model_cost_limit: `monthly model cost limit reached (${limits.maxMonthlyCostMicrosPerAccount} micros)`,\n monthly_agent_run_limit: `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`,\n };\n return { pausedReason: \"limits\", message: messages[denial] };\n}\n","import { configuredStaticUsageLimits, type Settings } from \"@opengeni/config\";\nimport { modelFundingForAdmission } from \"@opengeni/core\";\nimport {\n checkWorkspaceAllowance,\n getBillingBalance,\n isCodexBilledTurn,\n sumUsageQuantity,\n} from \"@opengeni/db\";\nimport type { ControlActivityServices } from \"./types\";\n\nexport type AgentRunAdmissionDenial =\n | \"insufficient_credits\"\n | \"allowance_exhausted\"\n | \"monthly_model_cost_limit\"\n | \"monthly_agent_run_limit\";\n\n/** One worker-side admission boundary for service-authored agent runs. */\nexport async function agentRunAdmissionDenial(\n services: Pick<ControlActivityServices, \"db\" | \"entitlements\"> & { settings: Settings },\n input: {\n accountId: string;\n workspaceId: string;\n model: string;\n requestedAgentRuns: number;\n /** The accepted work's causal human, not the scheduler/service caller. */\n initiatingHumanSubjectId?: string | null;\n },\n): Promise<AgentRunAdmissionDenial | null> {\n const codexBilled = await isCodexBilledTurn({\n db: services.db,\n settings: services.settings,\n workspaceId: input.workspaceId,\n model: input.model,\n });\n const externallyBilled = modelFundingForAdmission(\n services.settings,\n input.model,\n codexBilled,\n ).fundedWithoutCredits;\n if (\n !externallyBilled &&\n (services.settings.billingMode === \"stripe\" || services.settings.usageLimitsMode === \"managed\")\n ) {\n if (services.entitlements) {\n const decision = await services.entitlements.admitRun({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n action: \"agent_run:create\",\n quantity: input.requestedAgentRuns,\n });\n if (!decision.allowed) return \"insufficient_credits\";\n } else {\n const balance = await getBillingBalance(services.db, input.accountId);\n if (balance.balanceMicros <= 0) return \"insufficient_credits\";\n }\n }\n if (!externallyBilled) {\n const refusal = await checkWorkspaceAllowance(services.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: input.initiatingHumanSubjectId ?? null,\n });\n if (refusal) return refusal.code;\n }\n if (\n services.settings.usageLimitsMode !== \"static\" &&\n services.settings.usageLimitsMode !== \"managed\"\n ) {\n return null;\n }\n const limits = configuredStaticUsageLimits(services.settings);\n if (!externallyBilled && limits.maxMonthlyCostMicrosPerAccount) {\n const used = await sumUsageQuantity(services.db, {\n accountId: input.accountId,\n eventType: \"model.cost\",\n since: startOfUtcMonth(),\n });\n if (used >= limits.maxMonthlyCostMicrosPerAccount) {\n return \"monthly_model_cost_limit\";\n }\n }\n if (limits.maxMonthlyAgentRunsPerWorkspace) {\n const used = await sumUsageQuantity(services.db, {\n workspaceId: input.workspaceId,\n eventType: \"agent_run.created\",\n since: startOfUtcMonth(),\n });\n if (used + input.requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {\n return \"monthly_agent_run_limit\";\n }\n }\n return null;\n}\n\nfunction startOfUtcMonth(): Date {\n const now = new Date();\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));\n}\n","import { readTurnExecutionPolicyV1, type TurnExecutionPolicyV1 } from \"@opengeni/contracts\";\n\n/** Only accepted policies establish the ceiling; ordinary metadata is not authority. */\nexport function turnCredentialRestriction(\n acceptedPolicy: TurnExecutionPolicyV1,\n initialSessionMetadata: unknown,\n): \"developer_setup\" | undefined {\n const initialPolicy = readTurnExecutionPolicyV1(initialSessionMetadata);\n return acceptedPolicy.credentialRestriction === \"developer_setup\" ||\n (initialPolicy.kind === \"valid\" &&\n initialPolicy.policy.credentialRestriction === \"developer_setup\")\n ? \"developer_setup\"\n : undefined;\n}\n","import { isDeepStrictEqual } from \"node:util\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { scheduledTaskKnowledgeSource } from \"@opengeni/contracts\";\nimport {\n freezeAgentLearningPolicy,\n getScheduledTaskRunAcceptedExecution,\n ensureKnowledgeSourceSyncState,\n recordKnowledgeSourceSyncWake,\n} from \"@opengeni/db\";\nimport { createHash } from \"node:crypto\";\nimport { heartbeat } from \"@temporalio/activity\";\nimport {\n googleDriveProviderRetryOptions,\n type GoogleDriveProviderRetryOptions,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n KnowledgeSourceSyncRunSummary,\n type ScheduledTask,\n type ScopedKnowledgeScope,\n} from \"@opengeni/contracts\";\nimport {\n ATLASSIAN_PROVIDER_DOMAIN,\n AtlassianConnectionMetadata,\n atlassianScopesAllowRead,\n type AtlassianSelectedSource,\n} from \"@opengeni/contracts/atlassian\";\nimport {\n GoogleDriveConnectionMetadata,\n GOOGLE_DRIVE_PROVIDER_DOMAIN,\n googleDriveScopesAllowCapability,\n type GoogleDriveSelectedSource,\n} from \"@opengeni/contracts/google-drive\";\nimport {\n googleDriveKnowledgeScope,\n inventoryGoogleDriveSource,\n type GoogleDriveInventoryEntry,\n type GoogleDriveInventoryCheckpoint,\n type GoogleDriveInventoryPage,\n type GoogleDriveInventoryProviderItem,\n type GoogleDriveInventoryStopReason,\n} from \"@opengeni/documents/google-drive\";\nimport {\n atlassianKnowledgeScope,\n inventoryAtlassianSource,\n type AtlassianInventoryEntry,\n type AtlassianInventoryPage,\n type AtlassianInventoryStopReason,\n} from \"@opengeni/documents/atlassian\";\nimport { addDocumentToBase, ensureDefaultBase, getDocumentBase } from \"@opengeni/documents\";\nimport {\n appendKnowledgeDocumentVersion,\n appendKnowledgeSourceAclVersion,\n beginKnowledgeSyncRun,\n beginGoogleDriveObjectAclRefresh,\n buildConnectionTokenResolver,\n checkpointKnowledgeSourceSync,\n claimKnowledgeSourceSyncLease,\n compareCanonicalDecimalProviderRevisions,\n completeKnowledgeSyncRun,\n completeKnowledgeSourceSyncWakeWithoutLease,\n deauthorizeKnowledgeSourceRetrieval,\n enqueueKnowledgeSourceSyncIndexObligation,\n ensureKnowledgeSourceBlobFile,\n getConnectionMetadata,\n getKnowledgeDocumentVersionObservationForSyncAuthority,\n getKnowledgeSyncRunForSyncAuthority,\n getKnowledgeSourceAclForSyncAuthority,\n getKnowledgeSourceForSyncAuthority,\n getKnowledgeSourceObjectForSyncAuthority,\n getKnowledgeSourceSyncIndexObligationForVersion,\n getScheduledTask,\n listObservedKnowledgeSourceSyncExternalObjectIds,\n KnowledgeSourceSyncObservationFenceError,\n reconcileKnowledgeSourceSyncCompleteScan,\n reconcileKnowledgeSourceSyncLiveGeneration,\n recordGoogleDriveObjectAclEvidence,\n recordKnowledgeSourceSyncItemOutcomes,\n recordKnowledgeSourceSyncObjectObservations,\n recordUsageEvent,\n releaseKnowledgeSourceSyncLeaseForRetry,\n restoreKnowledgeSourceObject,\n retryKnowledgeSourceSyncIndexObligation,\n scopedKnowledgeScopeKey,\n settleKnowledgeSourceSyncLease,\n settleKnowledgeSourceSyncIndexObligation,\n updateKnowledgeSourceDocumentObservationMetadata,\n updateScheduledTaskRun,\n upsertKnowledgeSourceObject,\n type Database,\n type KnowledgeSourceSyncObjectObservationResult,\n type KnowledgeSourceSyncObservationFloor,\n} from \"@opengeni/db\";\nimport { readResponseJsonBounded } from \"@opengeni/network\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { createDocumentActivities } from \"./documents\";\nimport {\n fetchGoogleDriveProvider,\n GoogleDriveProviderTransportError,\n type GoogleDriveProviderOperation,\n} from \"./google-drive-provider\";\nimport type {\n ControlActivityServices,\n RunKnowledgeSourceSyncBatchInput,\n RunKnowledgeSourceSyncBatchResult,\n} from \"./types\";\nimport type {\n KnowledgeSourceSyncAclEvidence,\n KnowledgeSourceSyncDriver,\n} from \"./knowledge-source-sync-driver\";\nimport {\n advanceGoogleDriveChangesCursor,\n buildGoogleDriveChangesCursor,\n drainGoogleDriveChanges,\n GoogleDriveChangesProtocolError,\n GoogleDriveCursorInvalidError,\n googleDriveFullReconciliationDue,\n parseGoogleDriveChangesCheckpoint,\n parseGoogleDriveChangesCursor,\n resolveGoogleDriveChangesBoundaryId,\n type GoogleDriveChangesCheckpoint,\n type GoogleDriveChangesPage,\n type GoogleDriveSyncBudget,\n} from \"./google-drive-changes\";\n\n// Carries exact-attempt liveness into every physical request, including provider retries.\nconst sourceRequestAuthority = new AsyncLocalStorage<() => Promise<unknown>>();\nconst sourceFetch: typeof fetch = Object.assign(\n async (...args: Parameters<typeof fetch>) => {\n await sourceRequestAuthority.getStore()?.();\n return fetch(...args);\n },\n { preconnect: fetch.preconnect },\n);\n\nconst DRIVE_API_BASE = \"https://www.googleapis.com/drive/v3\";\nconst DRIVE_JSON_MAX_BYTES = 2 * 1024 * 1024;\nconst GOOGLE_DRIVE_FULL_RECONCILIATION_INTERVAL_MS = 24 * 60 * 60 * 1_000;\nconst GOOGLE_DRIVE_SYNC_INVOCATION_SLICE_MS = 30_000;\nconst GOOGLE_DRIVE_EXECUTION_CHECKPOINT_MAX_BYTES = 2 * 1024 * 1024;\nconst GOOGLE_DRIVE_ACL_FRESHNESS_MS = 26 * 60 * 60 * 1_000;\nconst GOOGLE_DRIVE_ACL_MAX_PRINCIPALS = 1_000;\nconst ATLASSIAN_API_BASE = \"https://api.atlassian.com\";\nconst ATLASSIAN_JSON_MAX_BYTES = 4 * 1024 * 1024;\n\ntype KnowledgeSyncEntry = GoogleDriveInventoryEntry | AtlassianInventoryEntry;\ntype KnowledgeSyncStopReason = GoogleDriveInventoryStopReason | AtlassianInventoryStopReason;\n\ntype GoogleDrivePermission = {\n id: string;\n type: \"user\" | \"group\" | \"domain\" | \"anyone\";\n role: \"owner\" | \"organizer\" | \"fileOrganizer\" | \"writer\" | \"commenter\" | \"reader\";\n emailAddress: string | null;\n domain: string | null;\n allowFileDiscovery: boolean | null;\n expirationTime: string | null;\n inherited: boolean;\n};\n\ntype GoogleDrivePermissionsPage = {\n permissions: GoogleDrivePermission[];\n nextPageToken: string | null;\n denied: boolean;\n};\n\nexport function knowledgeSyncObservationPolicy(kind: \"google_drive\" | \"atlassian\") {\n return kind === \"google_drive\"\n ? { revisionOrdering: \"canonical_decimal\" as const, filterWithDriveDurability: true }\n : { revisionOrdering: \"first_observation\" as const, filterWithDriveDurability: false };\n}\n\nexport function createKnowledgeSourceSyncActivities(\n services: () => Promise<ControlActivityServices>,\n resolveDocumentServices?: () => Promise<import(\"@opengeni/documents\").DocumentServices>,\n) {\n const documentActivities = createDocumentActivities(services, resolveDocumentServices);\n return {\n runKnowledgeSourceSyncBatch: async (\n input: RunKnowledgeSourceSyncBatchInput,\n ): Promise<RunKnowledgeSourceSyncBatchResult> => {\n const { settings, db, objectStorage, observability } = await services();\n if (!objectStorage) throw new Error(\"object storage is not configured\");\n // A control workflow cannot fetch sources. Only the exact ordinary\n // agent run carrying the immutable source binding can use this adapter.\n if (!input.agent)\n return { action: \"failed\", bufferedWake: false, errorCode: \"accepted_agent_required\" };\n const context = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n actor: input.agent,\n };\n let boundSource: ReturnType<typeof scheduledTaskKnowledgeSource> = null;\n const authorize = async () => {\n const policy = await freezeAgentLearningPolicy(db, context);\n if (policy.scheduledTaskRunId !== input.scheduledTaskRunId)\n throw new Error(\"Source fetch does not belong to this accepted agent run\");\n if (boundSource) {\n const [currentTask, connection] = await Promise.all([\n getScheduledTask(db, input.workspaceId, input.taskId),\n getConnectionMetadata(\n db,\n input.workspaceId,\n boundSource.connection.connectionId,\n boundSource.initiatingSubjectId,\n ),\n ]);\n const control = currentTask?.metadata.knowledgeSourceSync as\n | Record<string, unknown>\n | undefined;\n if (\n !currentTask ||\n currentTask.status !== \"active\" ||\n control?.sourceEnabled === false ||\n control?.connectionPaused === true ||\n !isDeepStrictEqual(scheduledTaskKnowledgeSource(currentTask), boundSource) ||\n !connection ||\n connection.status !== \"active\" ||\n connection.version !== boundSource.connection.connectionVersion ||\n connection.subjectId !== boundSource.connection.ownerSubjectId\n )\n throw new SyncFailure(\"authority_changed\", false);\n }\n return policy;\n };\n await authorize();\n const accepted = await getScheduledTaskRunAcceptedExecution(db, {\n workspaceId: input.workspaceId,\n runId: input.scheduledTaskRunId,\n });\n const task = accepted?.task;\n const action = task ? scheduledTaskKnowledgeSource(task) : null;\n const liveTask = await getScheduledTask(db, input.workspaceId, input.taskId);\n if (\n !task ||\n !action ||\n !liveTask ||\n liveTask.status !== \"active\" ||\n task.id !== input.taskId ||\n task.accountId !== input.accountId ||\n task.action.kind !== \"agent_turn\" ||\n action.sourceId !== input.sourceId ||\n accepted.causalHumanSubjectId !== action.initiatingSubjectId\n ) {\n return { action: \"failed\", bufferedWake: false };\n }\n boundSource = action;\n await authorize();\n await ensureKnowledgeSourceSyncState(db, task);\n await recordKnowledgeSourceSyncWake(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n scheduledTaskId: task.id,\n scheduledTaskRunId: input.scheduledTaskRunId,\n cause: \"scheduled\",\n producerKey: `agent-source:${input.scheduledTaskRunId}`,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n });\n const providerLabel =\n action.connection.providerDomain === ATLASSIAN_PROVIDER_DOMAIN\n ? \"atlassian\"\n : \"google_drive\";\n if (\n action.controlWorkspaceId !== input.workspaceId ||\n action.sourceConfigGeneration <= 0 ||\n !action.providerCoordinationKey\n ) {\n return await failWithoutProvider(\"authority_changed\");\n }\n const lease = await claimKnowledgeSourceSyncLease(db, {\n ...input,\n overlapPolicy: input.overlapPolicy,\n });\n if (lease.action !== \"claimed\") {\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_runs_total\",\n labels: { provider: providerLabel, outcome: lease.action },\n });\n return { action: lease.action };\n }\n\n let knowledgeRunId: string | null = null;\n let activeSourceSyncGeneration: number | null = null;\n const startedAt = Date.now();\n const summary: KnowledgeSourceSyncRunSummary = {\n phase: \"queued\",\n scanned: 0,\n imported: 0,\n unchanged: 0,\n skipped: 0,\n failed: 0,\n bytes: 0,\n providerRequests: 0,\n elapsedMs: 0,\n indexed: 0,\n aclPending: 0,\n retryable: false,\n limitReached: null as\n | \"items\"\n | \"bytes\"\n | \"file_bytes\"\n | \"provider_requests\"\n | \"elapsed_time\"\n | null,\n checkpointed: false,\n reconnectRequired: false,\n failures: [],\n };\n observability.info(\"Knowledge source sync started\", {\n provider: providerLabel,\n outcome: \"started\",\n });\n try {\n summary.phase = \"inventory\";\n const resolved = await getKnowledgeSourceForSyncAuthority(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n initiatingSubjectId: action.initiatingSubjectId,\n });\n if (!resolved || resolved.source.lifecycleState !== \"active\") {\n throw new SyncFailure(\"authority_changed\", false);\n }\n if (\n scopedKnowledgeScopeKey(resolved.source.scope) !==\n scopedKnowledgeScopeKey(action.destination)\n ) {\n throw new SyncFailure(\"authority_changed\", false);\n }\n const liveState = await reconcileKnowledgeSourceSyncLiveGeneration(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n initiatingSubjectId: action.initiatingSubjectId,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n liveSourceSyncGeneration: resolved.source.syncGeneration,\n });\n activeSourceSyncGeneration = resolved.source.syncGeneration;\n const syncOperationId = `scheduled-task-run:${input.scheduledTaskRunId}`;\n const replayedRun = await getKnowledgeSyncRunForSyncAuthority(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n operationId: syncOperationId,\n initiatingSubjectId: action.initiatingSubjectId,\n });\n if (replayedRun && replayedRun.state !== \"started\") {\n const replayedSummary = KnowledgeSourceSyncRunSummary.parse(replayedRun.metadata);\n const settlementInput: Parameters<typeof settleKnowledgeSourceSyncLease>[1] = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n knowledgeSyncRunId: replayedRun.id,\n status: replayedRun.state === \"succeeded\" ? \"succeeded\" : \"failed\",\n summary: replayedSummary,\n error: replayedRun.errorCode,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n sourceSyncGeneration: replayedRun.inputSyncGeneration,\n completedSourceSyncGeneration:\n replayedRun.state === \"succeeded\" ? replayedRun.inputSyncGeneration + 1 : null,\n ...(replayedRun.state === \"succeeded\" &&\n replayedRun.metadata.providerCursor &&\n typeof replayedRun.metadata.providerCursor === \"object\"\n ? {\n providerCursor: replayedRun.metadata.providerCursor as Record<string, unknown>,\n }\n : {}),\n };\n const settled =\n replayedRun.state === \"failed\" && replayedSummary.reconnectRequired\n ? await deauthorizeAndSettleKnowledgeSourceSyncFailure(db, {\n deauthorization: {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n audience: action.destination,\n operationId: `knowledge-sync-deauthorize:${input.sourceId}:${action.connection.connectionVersion}:${replayedRun.errorCode ?? \"connection_reconnect_required\"}`,\n reasonCode: \"connection_reconnect_required\",\n actor: {\n kind: \"service\",\n subjectId: \"knowledge-source-sync\",\n initiatingHumanSubjectId: action.initiatingSubjectId,\n },\n },\n settlement: settlementInput,\n })\n : await settleKnowledgeSourceSyncLease(db, settlementInput);\n await recordConnectorUsage(\"completed\", replayedSummary.scanned, \"item\");\n await recordConnectorUsage(\"items\", replayedSummary.imported, \"item\");\n await recordConnectorUsage(\"bytes\", replayedSummary.bytes, \"byte\");\n return {\n action: replayedRun.state === \"succeeded\" ? \"complete\" : \"failed\",\n summary: replayedSummary,\n ...(replayedRun.errorCode ? { errorCode: replayedRun.errorCode } : {}),\n bufferedWake: settled.bufferedWake,\n bufferedScheduledTaskRunId: settled.bufferedScheduledTaskRunId,\n };\n }\n const provider = await resolveKnowledgeSyncProvider({\n db,\n settings,\n observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n action,\n sourceId: input.sourceId,\n externalSourceId: resolved.source.externalSourceId,\n });\n const selectedDestination = provider.selectedDestination;\n const observationPolicy = knowledgeSyncObservationPolicy(provider.kind);\n\n let aclGeneration = resolved.source.currentAclGeneration;\n let acl = aclGeneration\n ? await getKnowledgeSourceAclForSyncAuthority(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n generation: aclGeneration,\n initiatingSubjectId: action.initiatingSubjectId,\n })\n : null;\n const actor = {\n kind: \"service\" as const,\n subjectId: \"knowledge-source-sync\",\n initiatingHumanSubjectId: action.initiatingSubjectId,\n };\n if (!acl) {\n acl = await appendKnowledgeSourceAclVersion(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n audience: action.destination,\n expectedSourceLifecycleGeneration: resolved.source.lifecycleGeneration,\n expectedAclGeneration: 0,\n aclVersion: \"opengeni-destination-v1\",\n agentAccess: false,\n operationId: `source-initial-acl:${input.sourceId}`,\n reasonCode: \"initial_destination_acl\",\n actor,\n });\n aclGeneration = acl.generation;\n }\n\n const knowledgeRun =\n replayedRun ??\n (await beginKnowledgeSyncRun(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n expectedSourceLifecycleGeneration: resolved.source.lifecycleGeneration,\n expectedSyncGeneration: resolved.source.syncGeneration,\n inputCursor: null,\n operationId: syncOperationId,\n actor,\n }));\n knowledgeRunId = knowledgeRun.id;\n\n const originalDriver = provider.driver;\n const readAcl = originalDriver.readAcl;\n const driver = {\n ...originalDriver,\n inventory: (...args: Parameters<typeof originalDriver.inventory>) =>\n sourceRequestAuthority.run(authorize, () => originalDriver.inventory(...args)),\n fetchContent: (...args: Parameters<typeof originalDriver.fetchContent>) =>\n sourceRequestAuthority.run(authorize, () => originalDriver.fetchContent(...args)),\n ...(readAcl\n ? {\n readAcl: (...args: Parameters<typeof readAcl>) =>\n sourceRequestAuthority.run(authorize, () => readAcl(...args)),\n }\n : {}),\n };\n await authorize();\n const inventory = await driver.inventory(\n lease.state.executionCheckpoint,\n lease.state.providerCursor,\n );\n summary.providerRequests = inventory.providerRequests;\n summary.elapsedMs = inventory.elapsedMs;\n\n const base = selectedDestination.collectionId\n ? await getDocumentBase(db, input.workspaceId, selectedDestination.collectionId)\n : await ensureDefaultBase(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n });\n if (!base) throw new SyncFailure(\"authority_changed\", false);\n\n const durableObservations = await recordKnowledgeSourceSyncObjectObservations(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n initiatingSubjectId: action.initiatingSubjectId,\n scanGeneration: liveState.activeScanGeneration,\n executionCheckpointGeneration: lease.state.executionCheckpointGeneration,\n revisionOrdering: observationPolicy.revisionOrdering,\n observations: inventory.entries.map((entry) => ({\n externalObjectId: entry.externalObjectId,\n providerRevision: entry.externalVersionId,\n metadataHash: entryMetadataHash(entry),\n })),\n });\n const entriesToProcess = observationPolicy.filterWithDriveDurability\n ? inventory.entries.filter((entry, index) =>\n shouldProcessGoogleDriveDurableObservation({\n entry,\n observation: durableObservations[index]!,\n sourceLifecycleGeneration: resolved.source.lifecycleGeneration,\n aclGeneration: aclGeneration!,\n }),\n )\n : inventory.entries;\n const observationFloorsById = new Map<string, KnowledgeSourceSyncObservationFloor>();\n for (const observation of durableObservations) {\n observationFloorsById.set(observation.externalObjectId, {\n externalObjectId: observation.externalObjectId,\n providerRevision: observation.providerRevision,\n metadataHash: observation.metadataHash,\n });\n }\n const observationFloors = [...observationFloorsById.values()];\n const executionCheckpoint = mergeGoogleDriveDurableObservationFloors(\n inventory.checkpoint,\n observationFloors,\n action.limits.maxItems,\n );\n\n const ensureVersionIndexed = async (details: {\n entry: KnowledgeSyncEntry;\n object: {\n id: string;\n lifecycleGeneration: number;\n };\n version: {\n id: string;\n versionGeneration: number;\n documentId: string | null;\n };\n indexRequired: boolean;\n obligation?: Awaited<ReturnType<typeof getKnowledgeSourceSyncIndexObligationForVersion>>;\n }) => {\n if (!details.version.documentId) {\n throw new SyncFailure(\"authority_changed\", false);\n }\n let obligation =\n details.obligation ??\n (await getKnowledgeSourceSyncIndexObligationForVersion(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n knowledgeDocumentVersionId: details.version.id,\n initiatingSubjectId: action.initiatingSubjectId,\n }));\n if (!obligation) {\n obligation = await enqueueKnowledgeSourceSyncIndexObligation(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n sourceId: input.sourceId,\n sourceSyncGeneration: knowledgeRun.inputSyncGeneration,\n initiatingSubjectId: action.initiatingSubjectId,\n externalObjectId: details.entry.externalObjectId,\n knowledgeSourceObjectId: details.object.id,\n knowledgeDocumentVersionId: details.version.id,\n documentId: details.version.documentId,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n objectLifecycleGeneration: details.object.lifecycleGeneration,\n objectVersionGeneration: details.version.versionGeneration,\n citationLocator: driver.citationLocator(details.entry),\n });\n }\n if (obligation.documentId !== details.version.documentId) {\n throw new SyncFailure(\"authority_changed\", false);\n }\n if (obligation.status === \"indexed\" && !details.indexRequired) return obligation;\n if (obligation.status === \"indexed\" && details.indexRequired) {\n summary.phase = \"index\";\n try {\n const indexedDocument = await documentActivities.indexDocument({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n documentId: details.version.documentId,\n authorityKind: action.destination.kind,\n authorityWorkspaceId: action.destination.workspaceId,\n authoritySubjectId: action.destination.subjectId,\n });\n if (indexedDocument.status !== \"ready\") {\n throw new Error(\"document indexing did not complete\");\n }\n } catch {\n throw new SyncFailure(\"indexing_failed\", true);\n }\n return obligation;\n }\n if (obligation.status === \"failed\") {\n const retried = await retryKnowledgeSourceSyncIndexObligation(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n obligationId: obligation.id,\n scheduledTaskRunId: input.scheduledTaskRunId,\n });\n if (retried === \"invalidated\") {\n throw new SyncFailure(\"authority_changed\", false);\n }\n obligation = { ...obligation, status: retried };\n if (retried === \"indexed\") return obligation;\n }\n if (obligation.status !== \"pending\") {\n throw new SyncFailure(\"authority_changed\", false);\n }\n if (details.indexRequired) {\n summary.phase = \"index\";\n try {\n const indexedDocument = await documentActivities.indexDocument({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n documentId: details.version.documentId,\n authorityKind: action.destination.kind,\n authorityWorkspaceId: action.destination.workspaceId,\n authoritySubjectId: action.destination.subjectId,\n });\n if (indexedDocument.status !== \"ready\") {\n throw new Error(\"document indexing did not complete\");\n }\n } catch {\n await settleKnowledgeSourceSyncIndexObligation(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n obligationId: obligation.id,\n status: \"failed\",\n failureCode: \"indexing_failed\",\n }).catch(() => undefined);\n throw new SyncFailure(\"indexing_failed\", true);\n }\n }\n const settlement = await settleKnowledgeSourceSyncIndexObligation(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n obligationId: obligation.id,\n status: \"indexed\",\n });\n if (settlement === \"invalidated\") {\n throw new SyncFailure(\"authority_changed\", false);\n }\n return { ...obligation, status: \"indexed\" };\n };\n\n const recordEntryAcl = async (details: {\n entry: KnowledgeSyncEntry;\n object: { id: string; lifecycleGeneration: number };\n version: { id: string; versionGeneration: number };\n obligation: { id: string; sourceSyncGeneration: number };\n }): Promise<{\n aclEligibility: \"pending\" | \"eligible\" | \"denied\";\n aclEvidence: Record<string, unknown> | null;\n }> => {\n if (!driver.readAcl || !provider.aclAuthority) {\n return { aclEligibility: \"pending\", aclEvidence: null };\n }\n await beginGoogleDriveObjectAclRefresh(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n obligationId: details.obligation.id,\n sourceSyncGeneration: details.obligation.sourceSyncGeneration,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n objectLifecycleGeneration: details.object.lifecycleGeneration,\n objectVersionGeneration: details.version.versionGeneration,\n });\n const remainingProviderRequests =\n action.limits.maxProviderRequests - summary.providerRequests;\n if (remainingProviderRequests < 1) {\n throw new SyncFailure(\"resource_limit\", false);\n }\n await authorize();\n const evidence = await driver.readAcl(details.entry, remainingProviderRequests);\n summary.providerRequests += evidence.providerRequests;\n if (summary.providerRequests > action.limits.maxProviderRequests) {\n throw new SyncFailure(\"resource_limit\", false);\n }\n const recorded = await recordGoogleDriveObjectAclEvidence(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n obligationId: details.obligation.id,\n connectionId: provider.aclAuthority.connectionId,\n connectionVersion: provider.aclAuthority.connectionVersion,\n sourceGooglePermissionId: provider.aclAuthority.sourceGooglePermissionId,\n sourceSyncGeneration: details.obligation.sourceSyncGeneration,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n objectLifecycleGeneration: details.object.lifecycleGeneration,\n objectVersionGeneration: details.version.versionGeneration,\n providerRevision: evidence.providerRevision,\n driveId: evidence.driveId,\n aclRevision: evidence.aclRevision,\n eligibility: evidence.eligibility,\n observedAt: evidence.observedAt,\n expiresAt: evidence.expiresAt,\n citationLocator: driver.citationLocator(details.entry),\n operationId: `drive-acl:${details.obligation.id}:${evidence.aclRevision}`,\n principals: evidence.principals,\n });\n return {\n aclEligibility: evidence.eligibility,\n aclEvidence: {\n version: 1,\n provider: \"google_drive\",\n evidenceId: recorded.evidenceId,\n aclRevision: evidence.aclRevision,\n aclHash: recorded.aclHash,\n observedAt: evidence.observedAt,\n expiresAt: evidence.expiresAt,\n },\n };\n };\n\n const outcomes = [];\n for (const entry of entriesToProcess) {\n await authorize();\n heartbeat({ sourceId: input.sourceId, externalObjectId: entry.externalObjectId });\n const observationFloor = observationFloorsById.get(entry.externalObjectId);\n if (!observationFloor) throw new SyncFailure(\"provider_payload_invalid\", false);\n const syncObservation = {\n scheduledTaskRunId: input.scheduledTaskRunId,\n scanGeneration: liveState.activeScanGeneration,\n providerRevision: observationFloor.providerRevision,\n metadataHash: observationFloor.metadataHash,\n };\n summary.scanned += 1;\n if (entry.transfer.action === \"skip\") {\n summary.skipped += 1;\n outcomes.push({\n externalObjectId: entry.externalObjectId,\n outcome: \"skipped\" as const,\n reasonCode: entry.transfer.reason,\n });\n continue;\n }\n if (entry.transfer.action === \"traverse\") continue;\n try {\n const existingObject = await getKnowledgeSourceObjectForSyncAuthority(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n externalObjectId: entry.externalObjectId,\n initiatingSubjectId: action.initiatingSubjectId,\n });\n let object =\n existingObject ??\n (await upsertKnowledgeSourceObject(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n externalObjectId: entry.externalObjectId,\n operationId: `source-object:${input.sourceId}:${entry.externalObjectId}`,\n actor,\n }));\n if (object.lifecycleState !== \"active\") {\n const restored = await restoreKnowledgeSourceObject(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n targetId: object.id,\n expectedGeneration: object.lifecycleGeneration,\n operationId: `knowledge-sync-object-restore:${object.id}:${liveState.activeScanGeneration}`,\n reasonCode: \"authoritative_scan_observed\",\n actor,\n });\n object = {\n ...object,\n lifecycleState: \"active\",\n lifecycleGeneration: restored.lifecycleGeneration,\n };\n }\n const currentObservation = object.currentVersionId\n ? await getKnowledgeDocumentVersionObservationForSyncAuthority(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n versionId: object.currentVersionId,\n initiatingSubjectId: action.initiatingSubjectId,\n })\n : null;\n const currentVersion = currentObservation?.version ?? null;\n const metadataHash = entryMetadataHash(entry);\n const observedProviderRevision =\n typeof currentObservation?.sourceMetadata.providerRevision === \"string\"\n ? currentObservation.sourceMetadata.providerRevision\n : null;\n const observedMetadataHash =\n typeof currentObservation?.sourceMetadata.metadataHash === \"string\"\n ? currentObservation.sourceMetadata.metadataHash\n : null;\n const observedSourceLifecycleGeneration = Number(\n currentObservation?.sourceMetadata.sourceLifecycleGeneration ?? 0,\n );\n const observedObjectLifecycleGeneration = Number(\n currentObservation?.sourceMetadata.objectLifecycleGeneration ?? 0,\n );\n const currentObligation = currentVersion\n ? await getKnowledgeSourceSyncIndexObligationForVersion(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n knowledgeDocumentVersionId: currentVersion.id,\n initiatingSubjectId: action.initiatingSubjectId,\n })\n : null;\n if (\n currentVersion &&\n currentVersion.documentId &&\n observedProviderRevision === entry.externalVersionId &&\n observedMetadataHash === metadataHash &&\n currentVersion.aclGeneration === aclGeneration &&\n observedSourceLifecycleGeneration === resolved.source.lifecycleGeneration &&\n observedObjectLifecycleGeneration === object.lifecycleGeneration &&\n currentObligation?.status !== \"invalidated\"\n ) {\n await updateKnowledgeSourceDocumentObservationMetadata(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n initiatingSubjectId: action.initiatingSubjectId,\n sourceId: input.sourceId,\n expectedSourceLifecycleGeneration: resolved.source.lifecycleGeneration,\n objectId: object.id,\n expectedObjectLifecycleGeneration: object.lifecycleGeneration,\n versionId: currentVersion.id,\n documentId: currentVersion.documentId,\n title: entry.title,\n sourceUri: entry.sourceUri,\n sourceVersion: entry.externalVersionId ?? currentVersion.contentSha256,\n sourceUpdatedAt: entry.modifiedTime,\n syncObservation,\n });\n const obligation = await ensureVersionIndexed({\n entry,\n object,\n version: currentVersion,\n indexRequired: (currentObservation?.documentChunkCount ?? 0) === 0,\n obligation: currentObligation,\n });\n const objectAcl = await recordEntryAcl({\n entry,\n object,\n version: currentVersion,\n obligation,\n });\n summary.unchanged += 1;\n outcomes.push({\n externalObjectId: entry.externalObjectId,\n outcome: \"unchanged\" as const,\n contentSha256: currentVersion.contentSha256,\n providerRevision: entry.externalVersionId,\n metadataHash,\n aclEligibility: objectAcl.aclEligibility,\n aclEvidence: objectAcl.aclEvidence,\n indexObligationId: obligation.id,\n });\n continue;\n }\n summary.phase = \"transfer\";\n await authorize();\n const bytes = await driver.fetchContent(entry, action.limits.maxFileBytes);\n const contentSha256 = createHash(\"sha256\").update(bytes).digest(\"hex\");\n const observationKey = createHash(\"sha256\")\n .update(\n JSON.stringify({\n externalObjectId: entry.externalObjectId,\n providerRevision: entry.externalVersionId,\n metadataHash,\n contentSha256,\n aclGeneration,\n sourceLifecycleGeneration: resolved.source.lifecycleGeneration,\n objectLifecycleGeneration: object.lifecycleGeneration,\n }),\n )\n .digest(\"hex\");\n if (\n currentVersion?.contentSha256 === contentSha256 &&\n currentVersion.documentId &&\n currentVersion.fileId\n ) {\n const version = await appendKnowledgeDocumentVersion(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n objectId: object.id,\n expectedSourceLifecycleGeneration: resolved.source.lifecycleGeneration,\n expectedObjectLifecycleGeneration: object.lifecycleGeneration,\n expectedVersionGeneration: object.versionGeneration,\n externalVersionId: entry.externalVersionId ?? contentSha256,\n contentSha256,\n ingestionKey: `${entry.externalObjectId}:${observationKey}`,\n sourceCursor: null,\n sourceMetadata: {\n title: entry.title,\n mimeType: entry.mimeType,\n driveId: entry.driveId,\n providerRevision: entry.externalVersionId,\n metadataHash,\n aclEligibility: \"pending\",\n sourceLifecycleGeneration: resolved.source.lifecycleGeneration,\n objectLifecycleGeneration: object.lifecycleGeneration,\n },\n sourceCreatedAt: entry.createdTime,\n sourceUpdatedAt: entry.modifiedTime,\n aclVersionId: acl.id,\n aclGeneration: aclGeneration!,\n documentId: currentVersion.documentId,\n fileId: currentVersion.fileId,\n locationMetadata: { sourceUri: entry.sourceUri },\n documentObservationMetadata: {\n title: entry.title,\n sourceUri: entry.sourceUri,\n sourceVersion: entry.externalVersionId ?? contentSha256,\n sourceUpdatedAt: entry.modifiedTime,\n },\n syncObservation,\n operationId: `document-observation:${object.id}:${observationKey}`,\n reasonCode: \"source_metadata_observed\",\n actor,\n });\n await updateKnowledgeSourceDocumentObservationMetadata(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n initiatingSubjectId: action.initiatingSubjectId,\n sourceId: input.sourceId,\n expectedSourceLifecycleGeneration: resolved.source.lifecycleGeneration,\n objectId: object.id,\n expectedObjectLifecycleGeneration: object.lifecycleGeneration,\n versionId: version.id,\n documentId: currentVersion.documentId,\n title: entry.title,\n sourceUri: entry.sourceUri,\n sourceVersion: entry.externalVersionId ?? contentSha256,\n sourceUpdatedAt: entry.modifiedTime,\n syncObservation,\n });\n const obligation = await ensureVersionIndexed({\n entry,\n object,\n version,\n indexRequired: (currentObservation?.documentChunkCount ?? 0) === 0,\n });\n const objectAcl = await recordEntryAcl({ entry, object, version, obligation });\n summary.unchanged += 1;\n summary.indexed += 1;\n if (objectAcl.aclEligibility === \"pending\") summary.aclPending += 1;\n outcomes.push({\n externalObjectId: entry.externalObjectId,\n outcome: \"unchanged\" as const,\n contentSha256,\n sizeBytes: bytes.byteLength,\n providerRevision: entry.externalVersionId,\n metadataHash,\n aclEligibility: objectAcl.aclEligibility,\n aclEvidence: objectAcl.aclEvidence,\n indexObligationId: obligation.id,\n });\n continue;\n }\n const fileId = deterministicUuid(\n `knowledge-blob:${input.accountId}:${input.workspaceId}:${contentSha256}`,\n );\n const objectKey = `workspaces/${input.workspaceId}/knowledge/blobs/${contentSha256}`;\n await objectStorage.putObject({\n key: objectKey,\n contentType: entry.transfer.contentType,\n body: bytes,\n sha256: contentSha256,\n });\n const file = await ensureKnowledgeSourceBlobFile(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n fileId,\n filename: entry.transfer.filename,\n safeFilename: safeFilename(entry.transfer.filename),\n contentType: entry.transfer.contentType,\n sizeBytes: bytes.byteLength,\n sha256: contentSha256,\n bucket: objectStorage.bucket,\n objectKey,\n });\n const document = await addDocumentToBase(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n baseId: base.id,\n fileId: file.id,\n title: entry.title,\n sourceKind: \"document\",\n sourceUri: entry.sourceUri,\n sourceExternalId: entry.externalObjectId,\n sourceTitle: entry.title,\n sourceCreatedAt: entry.createdTime ?? undefined,\n sourceUpdatedAt: entry.modifiedTime ?? undefined,\n sourceVersion: entry.externalVersionId ?? contentSha256,\n knowledgeSourceIdentity: deterministicUuid(\n `knowledge-source-version:${object.id}:${observationKey}`,\n ),\n authorityKind: action.destination.kind,\n createdBy: action.initiatingSubjectId,\n initiatingSubjectId: action.initiatingSubjectId,\n organizationAuthorityGranted: action.destination.kind === \"organization\",\n agentAccess: false,\n curationStatus: \"none\",\n access: { viewerSubjectId: action.initiatingSubjectId },\n });\n const version = await appendKnowledgeDocumentVersion(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n objectId: object.id,\n expectedSourceLifecycleGeneration: resolved.source.lifecycleGeneration,\n expectedObjectLifecycleGeneration: object.lifecycleGeneration,\n expectedVersionGeneration: object.versionGeneration,\n externalVersionId: entry.externalVersionId ?? contentSha256,\n contentSha256,\n ingestionKey: `${entry.externalObjectId}:${observationKey}`,\n sourceCursor: null,\n sourceMetadata: {\n title: entry.title,\n mimeType: entry.mimeType,\n driveId: entry.driveId,\n providerRevision: entry.externalVersionId,\n metadataHash,\n aclEligibility: \"pending\",\n sourceLifecycleGeneration: resolved.source.lifecycleGeneration,\n objectLifecycleGeneration: object.lifecycleGeneration,\n },\n sourceCreatedAt: entry.createdTime,\n sourceUpdatedAt: entry.modifiedTime,\n aclVersionId: acl.id,\n aclGeneration: aclGeneration!,\n documentId: document.id,\n fileId: file.id,\n locationMetadata: { sourceUri: entry.sourceUri },\n syncObservation,\n operationId: `document-version:${object.id}:${observationKey}`,\n reasonCode: \"source_content_observed\",\n actor,\n });\n const obligation = await ensureVersionIndexed({\n entry,\n object,\n version,\n indexRequired: true,\n });\n const objectAcl = await recordEntryAcl({ entry, object, version, obligation });\n summary.indexed += 1;\n summary.imported += 1;\n if (objectAcl.aclEligibility === \"pending\") summary.aclPending += 1;\n summary.bytes += bytes.byteLength;\n outcomes.push({\n externalObjectId: entry.externalObjectId,\n outcome: \"imported\" as const,\n contentSha256,\n sizeBytes: bytes.byteLength,\n providerRevision: entry.externalVersionId,\n metadataHash,\n aclEligibility: objectAcl.aclEligibility,\n aclEvidence: objectAcl.aclEvidence,\n indexObligationId: obligation.id,\n });\n } catch (error) {\n if (error instanceof KnowledgeSourceSyncObservationFenceError) {\n throw new SyncFailure(\"provider_payload_invalid\", false);\n }\n const message = boundedError(error);\n const itemFailure =\n error instanceof SyncFailure\n ? error\n : new SyncFailure(\"item_processing_failed\", false);\n summary.failed += 1;\n summary.retryable ||= itemFailure.retryable;\n if (summary.failures.length < action.limits.maxFailureDetails) {\n summary.failures.push({\n externalObjectId: entry.externalObjectId,\n code: itemFailure.code,\n retryable: itemFailure.retryable,\n message,\n });\n }\n outcomes.push({\n externalObjectId: entry.externalObjectId,\n outcome: \"failed\" as const,\n reasonCode: itemFailure.code,\n detail: message,\n providerRevision: entry.externalVersionId,\n metadataHash: entryMetadataHash(entry),\n aclEligibility: \"pending\" as const,\n });\n }\n }\n await recordKnowledgeSourceSyncItemOutcomes(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n knowledgeSyncRunId: knowledgeRun.id,\n sourceId: input.sourceId,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n outcomes,\n });\n\n if (inventory.status === \"paused\" && inventory.checkpoint) {\n if (\n inventory.stopReason === \"provider_error\" ||\n inventory.stopReason === \"incomplete_search\"\n ) {\n throw new SyncFailure(\n inventory.stopReason === \"provider_error\"\n ? \"provider_unavailable\"\n : \"provider_payload_invalid\",\n inventory.stopReason === \"provider_error\",\n );\n }\n if (inventory.hardLimitReached) {\n summary.limitReached = inventoryLimit(inventory.stopReason);\n throw new SyncFailure(\"resource_limit\", false);\n }\n if (inventory.stopReason !== \"elapsed_time_limit\") {\n summary.limitReached = inventoryLimit(inventory.stopReason);\n throw new SyncFailure(\"resource_limit\", false);\n }\n summary.checkpointed = true;\n summary.phase = \"checkpoint\";\n await checkpointKnowledgeSourceSync(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n executionCheckpoint: executionCheckpoint as Record<string, unknown>,\n observationFence: {\n initiatingSubjectId: action.initiatingSubjectId,\n scanGeneration: liveState.activeScanGeneration,\n executionCheckpointGeneration: lease.state.executionCheckpointGeneration,\n observations: observationFloors,\n },\n });\n return { action: \"continue\", summary };\n }\n\n const tombstonedExternalObjectIds = inventory.authoritativeFullScan\n ? await reconcileKnowledgeSourceSyncCompleteScan(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n initiatingSubjectId: action.initiatingSubjectId,\n sourceSyncGeneration: knowledgeRun.inputSyncGeneration,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n scanGeneration: liveState.activeScanGeneration,\n })\n : [];\n if (tombstonedExternalObjectIds.length > 0) {\n summary.skipped += tombstonedExternalObjectIds.length;\n await recordKnowledgeSourceSyncItemOutcomes(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n knowledgeSyncRunId: knowledgeRun.id,\n sourceId: input.sourceId,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n outcomes: tombstonedExternalObjectIds.map((externalObjectId) => ({\n externalObjectId,\n outcome: \"tombstoned\" as const,\n reasonCode: \"authoritative_scan_absent\",\n aclEligibility: \"denied\" as const,\n })),\n });\n }\n\n await completeKnowledgeSyncRun(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n initiatingSubjectId: action.initiatingSubjectId,\n runId: knowledgeRun.id,\n state: \"succeeded\",\n outputCursor: null,\n watermark: new Date().toISOString(),\n metadata: { ...summary, providerCursor: inventory.providerCursor },\n reasonCode: \"scheduled_source_sync\",\n });\n summary.phase = \"completed\";\n summary.elapsedMs = Date.now() - startedAt;\n const settled = await settleKnowledgeSourceSyncLease(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n knowledgeSyncRunId: knowledgeRun.id,\n status: \"succeeded\",\n summary,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n sourceSyncGeneration: knowledgeRun.inputSyncGeneration,\n completedSourceSyncGeneration: knowledgeRun.inputSyncGeneration + 1,\n providerCursor: inventory.providerCursor,\n observationFence: {\n initiatingSubjectId: action.initiatingSubjectId,\n scanGeneration: liveState.activeScanGeneration,\n executionCheckpointGeneration: lease.state.executionCheckpointGeneration,\n observations: observationFloors,\n },\n });\n await recordConnectorUsage(\"completed\", summary.scanned, \"item\");\n await recordConnectorUsage(\"items\", summary.imported, \"item\");\n await recordConnectorUsage(\"bytes\", summary.bytes, \"byte\");\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_runs_total\",\n labels: { provider: providerLabel, outcome: \"succeeded\" },\n });\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_items_total\",\n labels: { provider: providerLabel, outcome: \"imported\" },\n amount: summary.imported,\n });\n for (const outcome of [\"unchanged\", \"skipped\", \"failed\"] as const) {\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_items_total\",\n labels: { provider: providerLabel, outcome },\n amount: summary[outcome],\n });\n }\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_bytes_total\",\n labels: { provider: providerLabel },\n amount: summary.bytes,\n });\n recordSyncHealthTelemetry(observability, providerLabel, summary, \"succeeded\");\n return {\n action: \"complete\",\n summary,\n bufferedWake: settled.bufferedWake,\n bufferedScheduledTaskRunId: settled.bufferedScheduledTaskRunId,\n };\n } catch (error) {\n const failure =\n error instanceof SyncFailure ? error : new SyncFailure(\"internal_failure\", false);\n summary.phase = \"failed\";\n summary.retryable ||= failure.retryable;\n summary.elapsedMs = Date.now() - startedAt;\n summary.reconnectRequired = failure.reconnectRequired;\n summary.failed = Math.max(summary.failed, 1);\n if (summary.failures.length === 0) {\n summary.failures.push({\n externalObjectId: input.sourceId,\n code: failure.code,\n retryable: failure.retryable,\n message: boundedError(error),\n });\n }\n if (knowledgeRunId) {\n await completeKnowledgeSyncRun(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n initiatingSubjectId: action.initiatingSubjectId,\n runId: knowledgeRunId,\n state: \"failed\",\n metadata: summary,\n errorCode: failure.code,\n reasonCode: \"scheduled_source_sync_failed\",\n }).catch(() => undefined);\n }\n const settlementInput: Parameters<typeof settleKnowledgeSourceSyncLease>[1] = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n knowledgeSyncRunId: knowledgeRunId,\n status: \"failed\",\n summary,\n error: failure.code,\n sourceConfigGeneration: action.sourceConfigGeneration,\n sourceLifecycleGeneration: action.sourceLifecycleGeneration,\n sourceSyncGeneration: activeSourceSyncGeneration ?? lease.state.sourceSyncGeneration,\n // Failed or incomplete provider walks are not authoritative scans.\n // A later scheduled run must restart from the root under a fresh\n // observation generation before it can infer object absence.\n executionCheckpoint: null,\n };\n const settled = failure.reconnectRequired\n ? await deauthorizeAndSettleKnowledgeSourceSyncFailure(db, {\n deauthorization: {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n audience: action.destination,\n operationId: `knowledge-sync-deauthorize:${input.sourceId}:${action.connection.connectionVersion}:${failure.code}`,\n reasonCode: \"connection_reconnect_required\",\n actor: {\n kind: \"service\",\n subjectId: \"knowledge-source-sync\",\n initiatingHumanSubjectId: action.initiatingSubjectId,\n },\n },\n settlement: settlementInput,\n })\n : await settleKnowledgeSourceSyncLease(db, settlementInput);\n await recordConnectorUsage(\"completed\", summary.scanned, \"item\");\n await recordConnectorUsage(\"items\", summary.imported, \"item\");\n await recordConnectorUsage(\"bytes\", summary.bytes, \"byte\");\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_runs_total\",\n labels: { provider: providerLabel, outcome: \"failed\" },\n });\n for (const outcome of [\"imported\", \"unchanged\", \"skipped\", \"failed\"] as const) {\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_items_total\",\n labels: { provider: providerLabel, outcome },\n amount: summary[outcome],\n });\n }\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_bytes_total\",\n labels: { provider: providerLabel },\n amount: summary.bytes,\n });\n recordSyncHealthTelemetry(observability, providerLabel, summary, \"failed\", failure);\n return {\n action: \"failed\",\n summary,\n errorCode: failure.code,\n bufferedWake: settled.bufferedWake,\n bufferedScheduledTaskRunId: settled.bufferedScheduledTaskRunId,\n };\n }\n\n async function failWithoutProvider(code: string): Promise<RunKnowledgeSourceSyncBatchResult> {\n const terminalSummary = {\n phase: \"failed\" as const,\n scanned: 0,\n imported: 0,\n unchanged: 0,\n skipped: 0,\n failed: 1,\n bytes: 0,\n providerRequests: 0,\n elapsedMs: 0,\n indexed: 0,\n aclPending: 0,\n retryable: false,\n limitReached: null,\n checkpointed: false,\n reconnectRequired: false,\n failures: [\n {\n externalObjectId: input.sourceId,\n code: \"authority_changed\" as const,\n retryable: false,\n message: code,\n },\n ],\n };\n await updateScheduledTaskRun(db, input.workspaceId, input.scheduledTaskRunId, {\n knowledgeSummary: terminalSummary,\n }).catch(() => undefined);\n await completeKnowledgeSourceSyncWakeWithoutLease(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n }).catch(() => undefined);\n await recordConnectorUsage(\"completed\", 0, \"item\").catch(() => undefined);\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_runs_total\",\n labels: { provider: \"unknown\", outcome: \"failed_preflight\" },\n });\n return { action: \"failed\", bufferedWake: false, summary: terminalSummary, errorCode: code };\n }\n\n async function recordConnectorUsage(\n kind: \"completed\" | \"items\" | \"bytes\",\n quantity: number,\n unit: string,\n ) {\n if (quantity === 0 && kind !== \"completed\") return;\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: `knowledge_source_sync.${kind}`,\n quantity: kind === \"completed\" ? 1 : quantity,\n unit,\n sourceResourceType: \"scheduled_task_run\",\n sourceResourceId: input.scheduledTaskRunId,\n initiator: { kind: \"service\", subjectId: \"knowledge-source-sync\" },\n initiatorContext: {\n scheduledTaskId: input.taskId,\n scheduledTaskRunId: input.scheduledTaskRunId,\n },\n origin: \"scheduled_task\",\n idempotencyKey: `usage:knowledge_source_sync.${kind}:${input.scheduledTaskRunId}`,\n });\n }\n },\n };\n}\n\n/**\n * Permission loss must fail closed, while the exact source lease must never be\n * stranded by a deauthorization error. If deauthorization fails, release the\n * lease without settling the wake/run and surface the error so Temporal retries\n * this DB-only safety obligation. Terminal settlement is allowed only after\n * deauthorization succeeds.\n */\nexport async function deauthorizeAndSettleKnowledgeSourceSyncFailure(\n db: Database,\n input: {\n deauthorization: Parameters<typeof deauthorizeKnowledgeSourceRetrieval>[1];\n settlement: Parameters<typeof settleKnowledgeSourceSyncLease>[1];\n },\n): Promise<Awaited<ReturnType<typeof settleKnowledgeSourceSyncLease>>> {\n try {\n await deauthorizeKnowledgeSourceRetrieval(db, input.deauthorization);\n } catch (error) {\n await releaseKnowledgeSourceSyncLeaseForRetry(db, {\n accountId: input.settlement.accountId,\n workspaceId: input.settlement.workspaceId,\n sourceId: input.settlement.sourceId,\n scheduledTaskRunId: input.settlement.scheduledTaskRunId,\n });\n throw error;\n }\n return await settleKnowledgeSourceSyncLease(db, input.settlement);\n}\n\nexport type GoogleDriveSyncProviderPort = {\n now?: () => number;\n getStartPageToken: (driveId: string | null) => Promise<string>;\n listChanges: (\n pageToken: string,\n driveId: string | null,\n pageSize: number,\n ) => Promise<GoogleDriveChangesPage>;\n getFile: (fileId: string) => Promise<GoogleDriveInventoryProviderItem | null>;\n listChildren: (input: {\n folderId: string;\n driveId: string | null;\n pageToken: string | null;\n pageSize: number;\n }) => Promise<GoogleDriveInventoryPage>;\n listPermissions?: (input: {\n fileId: string;\n pageToken: string | null;\n pageSize: number;\n }) => Promise<GoogleDrivePermissionsPage>;\n};\n\nasync function resolveKnowledgeSyncProvider(input: {\n db: Database;\n settings: Settings;\n observability: Observability;\n accountId: string;\n workspaceId: string;\n action: Extract<ScheduledTask[\"action\"], { kind: \"knowledge_source_sync\" }>;\n sourceId: string;\n externalSourceId: string;\n}): Promise<{\n kind: \"google_drive\" | \"atlassian\";\n selectedDestination: NonNullable<\n GoogleDriveSelectedSource[\"destination\"] | AtlassianSelectedSource[\"destination\"]\n >;\n driver: KnowledgeSourceSyncDriver<KnowledgeSyncEntry, KnowledgeSyncStopReason>;\n aclAuthority: {\n connectionId: string;\n connectionVersion: number;\n sourceGooglePermissionId: string;\n } | null;\n}> {\n const { action } = input;\n const connection = await getConnectionMetadata(\n input.db,\n input.workspaceId,\n action.connection.connectionId,\n action.initiatingSubjectId,\n );\n if (\n !connection ||\n connection.accountId !== input.accountId ||\n connection.subjectId !== action.connection.ownerSubjectId ||\n connection.providerDomain.toLowerCase() !== action.connection.providerDomain.toLowerCase() ||\n connection.kind !== action.connection.kind ||\n connection.version < action.connection.connectionVersion ||\n connection.status !== \"active\"\n ) {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n\n const googleInitial =\n connection.providerDomain === GOOGLE_DRIVE_PROVIDER_DOMAIN\n ? GoogleDriveConnectionMetadata.safeParse(connection.metadata)\n : null;\n const atlassianInitial =\n connection.providerDomain === ATLASSIAN_PROVIDER_DOMAIN\n ? AtlassianConnectionMetadata.safeParse(connection.metadata)\n : null;\n const initialAtlassianMetadata = atlassianInitial?.success ? atlassianInitial.data : null;\n if (!googleInitial?.success && !initialAtlassianMetadata) {\n throw new SyncFailure(\"provider_rejected\", false);\n }\n if (\n googleInitial?.success &&\n !googleDriveScopesAllowCapability(connection.grantedScopes, \"recursive_source_sync\")\n ) {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n if (atlassianInitial?.success && !atlassianScopesAllowRead(connection.grantedScopes)) {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n const initialLifecycle = googleInitial?.success\n ? googleInitial.data.lifecycle\n : initialAtlassianMetadata!.lifecycle;\n if (initialLifecycle?.state && initialLifecycle.state !== \"active\") {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n const initialSource = googleInitial?.success\n ? selectedDriveSource(googleInitial.data, input.externalSourceId)\n : selectedAtlassianSource(initialAtlassianMetadata!, input.externalSourceId);\n if (\n !initialSource ||\n !initialSource.syncEnabled ||\n initialSource.configGeneration !== action.sourceConfigGeneration ||\n !initialSource.destination ||\n scopedKnowledgeScopeKey(\n googleInitial?.success\n ? googleDriveKnowledgeScope(initialSource.destination)\n : atlassianKnowledgeScope(initialSource.destination),\n ) !== scopedKnowledgeScopeKey(action.destination)\n ) {\n throw new SyncFailure(\"authority_changed\", false);\n }\n\n const token = await buildConnectionTokenResolver(\n input.db,\n input.settings,\n )({\n workspaceId: input.workspaceId,\n subjectId: action.initiatingSubjectId,\n serverId: \"knowledge-source-sync\",\n connectionRef: {\n connectionId: connection.id,\n providerDomain: connection.providerDomain,\n kind: connection.kind,\n subjectScope: \"subject\",\n },\n destinationUrl:\n connection.providerDomain === ATLASSIAN_PROVIDER_DOMAIN\n ? ATLASSIAN_API_BASE\n : \"https://www.googleapis.com\",\n });\n if (token.status !== \"ok\") {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n const resolvedConnection = await getConnectionMetadata(\n input.db,\n input.workspaceId,\n action.connection.connectionId,\n action.initiatingSubjectId,\n );\n if (\n !resolvedConnection ||\n resolvedConnection.accountId !== input.accountId ||\n resolvedConnection.subjectId !== action.connection.ownerSubjectId ||\n resolvedConnection.providerDomain.toLowerCase() !==\n action.connection.providerDomain.toLowerCase() ||\n resolvedConnection.kind !== action.connection.kind ||\n resolvedConnection.version !== token.connectionVersion ||\n resolvedConnection.status !== \"active\"\n ) {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n const authorization = token.headers.Authorization ?? token.headers.authorization;\n if (resolvedConnection.providerDomain === GOOGLE_DRIVE_PROVIDER_DOMAIN) {\n const metadata = GoogleDriveConnectionMetadata.parse(resolvedConnection.metadata);\n if (\n !googleDriveSyncProviderAccessAllowed({\n connectionVersion: resolvedConnection.version,\n resolvedConnectionVersion: token.connectionVersion,\n connectionStatus: resolvedConnection.status,\n lifecycleState: metadata.lifecycle?.state,\n grantedScopes: resolvedConnection.grantedScopes,\n })\n ) {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n const source = selectedDriveSource(metadata, input.externalSourceId);\n if (!validSelectedSource(source, action, googleDriveKnowledgeScope)) {\n throw new SyncFailure(\"authority_changed\", false);\n }\n return {\n kind: \"google_drive\",\n selectedDestination: source.destination!,\n aclAuthority: {\n connectionId: resolvedConnection.id,\n connectionVersion: resolvedConnection.version,\n sourceGooglePermissionId: metadata.googlePermissionId,\n },\n driver: googleDriveSyncDriver({\n actionProviderCoordinationKey: action.providerCoordinationKey,\n metadata,\n selectedSource: source,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n initiatingSubjectId: action.initiatingSubjectId,\n authorization,\n retry: googleDriveProviderRetryOptions(input.settings),\n observability: input.observability,\n limits: action.limits,\n connectionId: resolvedConnection.id,\n fullReconciliationIntervalMs: GOOGLE_DRIVE_FULL_RECONCILIATION_INTERVAL_MS,\n observedExternalObjectIds: async (externalObjectIds) =>\n await listObservedKnowledgeSourceSyncExternalObjectIds(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sourceId: input.sourceId,\n externalObjectIds,\n }),\n }) as unknown as KnowledgeSourceSyncDriver<KnowledgeSyncEntry, KnowledgeSyncStopReason>,\n };\n }\n if (resolvedConnection.providerDomain === ATLASSIAN_PROVIDER_DOMAIN) {\n const metadata = AtlassianConnectionMetadata.parse(resolvedConnection.metadata);\n if (\n metadata.lifecycle?.state !== \"active\" ||\n !atlassianScopesAllowRead(resolvedConnection.grantedScopes)\n ) {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n const source = selectedAtlassianSource(metadata, input.externalSourceId);\n if (!validSelectedSource(source, action, atlassianKnowledgeScope)) {\n throw new SyncFailure(\"authority_changed\", false);\n }\n return {\n kind: \"atlassian\",\n selectedDestination: source.destination!,\n aclAuthority: null,\n driver: atlassianSyncDriver({\n actionProviderCoordinationKey: action.providerCoordinationKey,\n metadata,\n selectedSource: source,\n authorization,\n limits: action.limits,\n }) as unknown as KnowledgeSourceSyncDriver<KnowledgeSyncEntry, KnowledgeSyncStopReason>,\n };\n }\n throw new SyncFailure(\"provider_rejected\", false);\n}\n\nfunction validSelectedSource<Source extends GoogleDriveSelectedSource | AtlassianSelectedSource>(\n source: Source | null,\n action: Extract<ScheduledTask[\"action\"], { kind: \"knowledge_source_sync\" }>,\n scope: (destination: NonNullable<Source[\"destination\"]>) => ScopedKnowledgeScope,\n): source is Source & { destination: NonNullable<Source[\"destination\"]> } {\n return Boolean(\n source &&\n source.syncEnabled &&\n source.configGeneration === action.sourceConfigGeneration &&\n source.destination &&\n scopedKnowledgeScopeKey(scope(source.destination)) ===\n scopedKnowledgeScopeKey(action.destination),\n );\n}\n\nfunction selectedAtlassianSource(\n metadata: ReturnType<typeof AtlassianConnectionMetadata.parse>,\n externalSourceId: string,\n): AtlassianSelectedSource | null {\n return metadata.selectedSources.find((source) => source.id === externalSourceId) ?? null;\n}\n\nfunction atlassianSyncDriver(input: {\n actionProviderCoordinationKey: string;\n metadata: ReturnType<typeof AtlassianConnectionMetadata.parse>;\n selectedSource: AtlassianSelectedSource;\n authorization: string | undefined;\n limits: {\n maxItems: number;\n maxBytes: number;\n maxFileBytes: number;\n maxProviderRequests: number;\n maxElapsedSeconds: number;\n };\n}): KnowledgeSourceSyncDriver<AtlassianInventoryEntry, AtlassianInventoryStopReason> {\n return {\n providerKey: \"atlassian\",\n providerDomain: ATLASSIAN_PROVIDER_DOMAIN,\n providerCoordinationKey: input.actionProviderCoordinationKey,\n inventory: async (checkpoint) => {\n const inventory = await inventoryAtlassianSource({\n cloudId: input.selectedSource.cloudId,\n source: input.selectedSource,\n limits: {\n maxItems: input.limits.maxItems,\n maxApiRequests: input.limits.maxProviderRequests,\n maxElapsedMs: input.limits.maxElapsedSeconds * 1_000,\n pageSize: Math.min(input.limits.maxItems, 100),\n },\n checkpoint,\n listPage: async (cursor, pageSize) =>\n await listAtlassianItems(input.selectedSource, cursor, pageSize, input.authorization),\n });\n return {\n ...inventory,\n providerCursor: null,\n authoritativeFullScan: inventory.status === \"complete\",\n cursorInvalidated: false,\n hardLimitReached:\n inventory.status === \"paused\" &&\n inventory.stopReason !== \"elapsed_time_limit\" &&\n inventory.stopReason !== \"provider_error\",\n };\n },\n fetchContent: async (entry, maxBytes) =>\n await fetchAtlassianContent(input.selectedSource, entry, input.authorization, maxBytes),\n citationLocator: (entry) => ({\n version: 1,\n providerKey: \"atlassian\",\n providerCoordinationKey: input.actionProviderCoordinationKey,\n cloudId: input.selectedSource.cloudId,\n sourceKind: input.selectedSource.kind,\n externalObjectId: entry.externalObjectId,\n sourceUri: entry.sourceUri,\n }),\n };\n}\n\nexport function googleDriveSyncDriver(input: {\n actionProviderCoordinationKey: string;\n metadata: ReturnType<typeof GoogleDriveConnectionMetadata.parse>;\n selectedSource: GoogleDriveSelectedSource;\n connectionId: string;\n accountId: string;\n workspaceId: string;\n initiatingSubjectId: string;\n authorization: string | undefined;\n retry: GoogleDriveProviderRetryOptions;\n observability: Observability;\n fullReconciliationIntervalMs: number;\n observedExternalObjectIds: (ids: string[]) => Promise<Set<string>>;\n provider?: GoogleDriveSyncProviderPort;\n limits: {\n maxItems: number;\n maxBytes: number;\n maxFileBytes: number;\n maxProviderRequests: number;\n maxElapsedSeconds: number;\n };\n}): KnowledgeSourceSyncDriver<GoogleDriveInventoryEntry, GoogleDriveInventoryStopReason> {\n const maxElapsedMs = input.limits.maxElapsedSeconds * 1_000;\n const provider: GoogleDriveSyncProviderPort = input.provider ?? {\n getStartPageToken: async (driveId) =>\n await getDriveStartPageToken(driveId, input.authorization, input.retry, input.observability),\n listChanges: async (pageToken, driveId, pageSize) =>\n await listDriveChanges(\n pageToken,\n driveId,\n pageSize,\n input.authorization,\n input.retry,\n input.observability,\n ),\n getFile: async (fileId) =>\n await getDriveFile(fileId, input.authorization, input.retry, input.observability),\n listChildren: async (request) =>\n await listDriveChildren(request, input.authorization, input.retry, input.observability),\n listPermissions: async (request) =>\n await listDrivePermissions(request, input.authorization, input.retry, input.observability),\n };\n const clock = provider.now ?? Date.now;\n const budgetLimits = {\n maxItems: input.limits.maxItems,\n maxProviderRequests: input.limits.maxProviderRequests,\n maxElapsedMs,\n };\n return {\n providerKey: \"google_drive\",\n providerDomain: GOOGLE_DRIVE_PROVIDER_DOMAIN,\n providerCoordinationKey: input.actionProviderCoordinationKey,\n inventory: async (executionCheckpoint, providerCursor) => {\n const expectedCursor = {\n connectionId: input.connectionId,\n googlePermissionId: input.metadata.googlePermissionId,\n sourceId: input.selectedSource.id,\n driveId: input.selectedSource.driveId,\n };\n const legacyFullCheckpoint = isLegacyGoogleDriveFullReconciliationCheckpoint(\n executionCheckpoint,\n expectedCursor,\n );\n const cursor = parseGoogleDriveChangesCursor(providerCursor, expectedCursor);\n const checkpoint = parseGoogleDriveExecutionCheckpoint(\n executionCheckpoint,\n expectedCursor,\n budgetLimits,\n );\n const now = new Date(clock());\n\n const runFullReconciliation = async (full: {\n boundaryId: string;\n startPageToken: string;\n cursorInvalidated: boolean;\n budgetBeforeInventory: GoogleDriveSyncBudget;\n inventoryElapsedMs: number;\n inventoryCheckpoint: GoogleDriveInventoryCheckpoint | null;\n revisionFloors: GoogleDriveRevisionFloor[];\n }) => {\n const inventoryItems = full.inventoryCheckpoint?.totals.itemCount ?? 0;\n const inventoryProviderRequests = full.inventoryCheckpoint?.totals.apiRequestCount ?? 0;\n const budgetBeforeInvocation = {\n examinedItems: full.budgetBeforeInventory.examinedItems + inventoryItems,\n providerRequests: full.budgetBeforeInventory.providerRequests + inventoryProviderRequests,\n elapsedMs: full.budgetBeforeInventory.elapsedMs + full.inventoryElapsedMs,\n } satisfies GoogleDriveSyncBudget;\n const hardStopReason = googleDriveHardLimitReason(budgetBeforeInvocation, budgetLimits);\n const fullCheckpoint = buildGoogleDriveFullReconciliationCheckpoint({\n ...expectedCursor,\n ...full,\n });\n if (hardStopReason) {\n return {\n status: \"paused\" as const,\n stopReason: hardStopReason,\n entries: [],\n checkpoint: fullCheckpoint,\n providerCursor,\n authoritativeFullScan: false,\n cursorInvalidated: full.cursorInvalidated,\n providerRequests: budgetBeforeInvocation.providerRequests,\n elapsedMs: budgetBeforeInvocation.elapsedMs,\n hardLimitReached: true,\n };\n }\n\n const phaseMaxItems = input.limits.maxItems - full.budgetBeforeInventory.examinedItems;\n const phaseMaxProviderRequests =\n input.limits.maxProviderRequests - full.budgetBeforeInventory.providerRequests;\n const remainingElapsedMs = maxElapsedMs - budgetBeforeInvocation.elapsedMs;\n const inventory = await inventoryGoogleDriveSource({\n googlePermissionId: input.metadata.googlePermissionId,\n googleEmail: input.metadata.googleEmail,\n source: input.selectedSource,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n connectionSubjectId: input.initiatingSubjectId,\n limits: {\n maxItems: phaseMaxItems,\n maxKnownBytes: input.limits.maxBytes,\n maxApiRequests: phaseMaxProviderRequests,\n maxElapsedMs: Math.min(GOOGLE_DRIVE_SYNC_INVOCATION_SLICE_MS, remainingElapsedMs),\n maxFileBytes: input.limits.maxFileBytes,\n maxFolders: Math.min(phaseMaxItems * 2, 2_000),\n pageSize: Math.min(phaseMaxItems, 100),\n },\n checkpoint: full.inventoryCheckpoint,\n listChildren: provider.listChildren,\n now: clock,\n });\n const inventoryElapsedMs = full.inventoryElapsedMs + inventory.run.elapsedMs;\n const budget = {\n examinedItems: full.budgetBeforeInventory.examinedItems + inventory.totals.itemCount,\n providerRequests:\n full.budgetBeforeInventory.providerRequests + inventory.totals.apiRequestCount,\n elapsedMs: full.budgetBeforeInventory.elapsedMs + inventoryElapsedMs,\n } satisfies GoogleDriveSyncBudget;\n const reconciled = reconcileGoogleDriveRevisionFloors(\n inventory.entries,\n full.revisionFloors,\n input.limits.maxItems,\n );\n if (reconciled.conflict) {\n return {\n status: \"paused\" as const,\n stopReason: \"incomplete_search\" as const,\n entries: [],\n checkpoint: fullCheckpoint,\n providerCursor,\n authoritativeFullScan: false,\n cursorInvalidated: full.cursorInvalidated,\n providerRequests: budget.providerRequests,\n elapsedMs: budget.elapsedMs,\n hardLimitReached: false,\n };\n }\n const nextCursor =\n inventory.status === \"complete\"\n ? buildGoogleDriveChangesCursor({\n ...expectedCursor,\n boundaryId: full.boundaryId,\n pageToken: full.startPageToken,\n previousGeneration: cursor?.cursorGeneration ?? 0,\n reconciledAt: now,\n fullReconciliationIntervalMs: input.fullReconciliationIntervalMs,\n })\n : providerCursor;\n return {\n status: inventory.status,\n stopReason: inventory.stopReason,\n entries: reconciled.entries,\n checkpoint:\n inventory.status === \"paused\" && inventory.checkpoint\n ? buildGoogleDriveFullReconciliationCheckpoint({\n ...expectedCursor,\n boundaryId: full.boundaryId,\n startPageToken: full.startPageToken,\n cursorInvalidated: full.cursorInvalidated,\n budgetBeforeInventory: full.budgetBeforeInventory,\n inventoryElapsedMs,\n inventoryCheckpoint: inventory.checkpoint,\n revisionFloors: reconciled.revisionFloors,\n })\n : null,\n providerCursor: nextCursor,\n authoritativeFullScan: inventory.status === \"complete\",\n cursorInvalidated: full.cursorInvalidated,\n providerRequests: budget.providerRequests,\n elapsedMs: budget.elapsedMs,\n hardLimitReached:\n inventory.status === \"paused\" &&\n googleDriveInventoryStopIsHard(inventory.stopReason, budget, budgetLimits),\n };\n };\n\n const acquireFullReconciliation = async (details: {\n budget: GoogleDriveSyncBudget;\n boundaryId: string | null;\n cursorInvalidated: boolean;\n }) => {\n const acquisitionStartedAt = clock();\n const initialElapsedMs = details.budget.elapsedMs;\n const budget = { ...details.budget };\n const refreshElapsed = () => {\n budget.elapsedMs = initialElapsedMs + Math.max(0, clock() - acquisitionStartedAt);\n };\n const requireProviderCapacity = () => {\n refreshElapsed();\n if (googleDriveHardLimitReason(budget, budgetLimits)) {\n throw new SyncFailure(\"resource_limit\", false);\n }\n budget.providerRequests += 1;\n };\n\n requireProviderCapacity();\n const startPageToken = await provider.getStartPageToken(input.selectedSource.driveId);\n refreshElapsed();\n\n let boundaryId = details.boundaryId;\n if (!boundaryId) {\n if (input.selectedSource.id === \"root\" && input.selectedSource.driveId === null) {\n requireProviderCapacity();\n try {\n boundaryId = await resolveGoogleDriveChangesBoundaryId({\n source: input.selectedSource,\n getFile: provider.getFile,\n });\n } catch (error) {\n if (error instanceof GoogleDriveChangesProtocolError) {\n throw new SyncFailure(\"provider_payload_invalid\", false);\n }\n throw error;\n }\n refreshElapsed();\n } else {\n boundaryId = input.selectedSource.id;\n }\n }\n\n return {\n boundaryId,\n startPageToken,\n cursorInvalidated: details.cursorInvalidated,\n budgetBeforeInventory: budget,\n inventoryElapsedMs: 0,\n inventoryCheckpoint: null,\n revisionFloors: [],\n };\n };\n\n if (checkpoint?.kind === \"google_drive_full_reconciliation\") {\n return await runFullReconciliation(checkpoint);\n }\n if (!cursor) {\n const budget =\n checkpoint?.kind === \"google_drive_changes\"\n ? checkpoint.changesCheckpoint.budget\n : emptyGoogleDriveSyncBudget();\n return await runFullReconciliation(\n await acquireFullReconciliation({\n budget,\n boundaryId: null,\n cursorInvalidated: providerCursor !== null,\n }),\n );\n }\n if (!checkpoint && !legacyFullCheckpoint && googleDriveFullReconciliationDue(cursor, now)) {\n return await runFullReconciliation(\n await acquireFullReconciliation({\n budget: emptyGoogleDriveSyncBudget(),\n boundaryId: cursor.boundaryId,\n cursorInvalidated: false,\n }),\n );\n }\n\n try {\n const forceFullReconciliation =\n legacyFullCheckpoint || googleDriveFullReconciliationDue(cursor, now);\n const changesCheckpoint =\n checkpoint?.kind === \"google_drive_changes\"\n ? {\n ...checkpoint.changesCheckpoint,\n requiresFullReconciliation:\n checkpoint.changesCheckpoint.requiresFullReconciliation ||\n forceFullReconciliation,\n }\n : null;\n const changes = await drainGoogleDriveChanges({\n source: input.selectedSource,\n cursor,\n checkpoint: changesCheckpoint,\n maxItems: input.limits.maxItems,\n maxProviderRequests: input.limits.maxProviderRequests,\n maxElapsedMs,\n maxInvocationElapsedMs: Math.min(GOOGLE_DRIVE_SYNC_INVOCATION_SLICE_MS, maxElapsedMs),\n maxFileBytes: input.limits.maxFileBytes,\n listChanges: async (pageToken, pageSize) =>\n await provider.listChanges(pageToken, input.selectedSource.driveId, pageSize),\n getFile: provider.getFile,\n observedExternalObjectIds: input.observedExternalObjectIds,\n now: clock,\n });\n if (changes.status === \"paused\" && changes.checkpoint) {\n return {\n status: \"paused\" as const,\n stopReason: changes.stopReason,\n entries: changes.entries,\n checkpoint: {\n version: 2,\n kind: \"google_drive_changes\",\n ...expectedCursor,\n changesCheckpoint: {\n ...changes.checkpoint,\n requiresFullReconciliation:\n changes.checkpoint.requiresFullReconciliation || forceFullReconciliation,\n },\n } satisfies GoogleDriveExecutionCheckpoint,\n providerCursor,\n authoritativeFullScan: false,\n cursorInvalidated: false,\n providerRequests: changes.providerRequests,\n elapsedMs: changes.elapsedMs,\n hardLimitReached: changes.hardLimitReached,\n };\n }\n if (!changes.newStartPageToken) throw new Error(\"google_drive_changes_cursor_missing\");\n if (changes.requiresFullReconciliation || forceFullReconciliation) {\n const hardStopReason = googleDriveHardLimitReason(changes.budget, budgetLimits);\n return {\n status: \"paused\" as const,\n stopReason: hardStopReason ?? (\"elapsed_time_limit\" as const),\n entries: changes.entries,\n checkpoint: buildGoogleDriveFullReconciliationCheckpoint({\n ...expectedCursor,\n boundaryId: cursor.boundaryId,\n startPageToken: changes.newStartPageToken,\n cursorInvalidated: false,\n budgetBeforeInventory: changes.budget,\n inventoryElapsedMs: 0,\n inventoryCheckpoint: null,\n revisionFloors: revisionFloorsForEntries(changes.entries, input.limits.maxItems),\n }),\n providerCursor,\n authoritativeFullScan: false,\n cursorInvalidated: false,\n providerRequests: changes.providerRequests,\n elapsedMs: changes.elapsedMs,\n hardLimitReached: hardStopReason !== null,\n };\n }\n return {\n status: \"complete\" as const,\n stopReason: null,\n entries: changes.entries,\n checkpoint: null,\n providerCursor: advanceGoogleDriveChangesCursor(cursor, changes.newStartPageToken),\n authoritativeFullScan: false,\n cursorInvalidated: false,\n providerRequests: changes.providerRequests,\n elapsedMs: changes.elapsedMs,\n hardLimitReached: false,\n };\n } catch (error) {\n if (error instanceof GoogleDriveChangesProtocolError) {\n throw new SyncFailure(\"provider_payload_invalid\", false);\n }\n if (!(error instanceof GoogleDriveCursorInvalidError)) throw error;\n const full = await acquireFullReconciliation({\n budget: error.budget ?? emptyGoogleDriveSyncBudget(),\n boundaryId: cursor.boundaryId,\n cursorInvalidated: true,\n });\n const hardStopReason = googleDriveHardLimitReason(full.budgetBeforeInventory, budgetLimits);\n return {\n status: \"paused\" as const,\n stopReason: hardStopReason ?? (\"elapsed_time_limit\" as const),\n entries: [],\n checkpoint: buildGoogleDriveFullReconciliationCheckpoint({\n ...expectedCursor,\n ...full,\n }),\n providerCursor,\n authoritativeFullScan: false,\n cursorInvalidated: true,\n providerRequests: full.budgetBeforeInventory.providerRequests,\n elapsedMs: full.budgetBeforeInventory.elapsedMs,\n hardLimitReached: hardStopReason !== null,\n };\n }\n },\n fetchContent: async (entry, maxBytes) =>\n await fetchDriveBytes(entry, input.authorization, maxBytes, input.retry, input.observability),\n readAcl: async (entry, maxProviderRequests) => {\n if (!provider.listPermissions) {\n throw new SyncFailure(\"provider_rejected\", false);\n }\n return await collectGoogleDriveAclEvidence({\n entry,\n maxProviderRequests,\n listPermissions: provider.listPermissions,\n getFile: provider.getFile,\n now: clock,\n });\n },\n citationLocator: (entry) => ({\n version: 2,\n providerKey: \"google-drive\",\n providerCoordinationKey: input.actionProviderCoordinationKey,\n externalObjectId: entry.externalObjectId,\n providerRevision: entry.externalVersionId,\n driveId: entry.driveId,\n sourceUri: entry.sourceUri,\n }),\n };\n}\n\ntype GoogleDriveCheckpointIdentity = {\n connectionId: string;\n googlePermissionId: string;\n sourceId: string;\n driveId: string | null;\n};\n\ntype GoogleDriveRevisionFloor = [externalObjectId: string, providerRevision: string | null];\n\ntype GoogleDriveFullReconciliationCheckpoint = GoogleDriveCheckpointIdentity & {\n version: 3;\n kind: \"google_drive_full_reconciliation\";\n boundaryId: string;\n startPageToken: string;\n cursorInvalidated: boolean;\n budgetBeforeInventory: GoogleDriveSyncBudget;\n inventoryElapsedMs: number;\n inventoryCheckpoint: GoogleDriveInventoryCheckpoint | null;\n revisionFloors: GoogleDriveRevisionFloor[];\n};\n\ntype GoogleDriveExecutionCheckpoint = GoogleDriveCheckpointIdentity &\n (\n | {\n version: 2;\n kind: \"google_drive_changes\";\n changesCheckpoint: GoogleDriveChangesCheckpoint;\n }\n | GoogleDriveFullReconciliationCheckpoint\n );\n\nfunction isLegacyGoogleDriveFullReconciliationCheckpoint(\n value: Record<string, unknown> | null,\n expected: GoogleDriveCheckpointIdentity,\n): boolean {\n return (\n value?.version === 2 &&\n value.kind === \"google_drive_full_reconciliation\" &&\n value.connectionId === expected.connectionId &&\n value.googlePermissionId === expected.googlePermissionId &&\n value.sourceId === expected.sourceId &&\n value.driveId === expected.driveId &&\n encodedJsonBytes(value) <= GOOGLE_DRIVE_EXECUTION_CHECKPOINT_MAX_BYTES\n );\n}\n\nfunction parseGoogleDriveExecutionCheckpoint(\n value: Record<string, unknown> | null,\n expected: GoogleDriveCheckpointIdentity,\n limits: { maxItems: number; maxProviderRequests: number; maxElapsedMs: number },\n): GoogleDriveExecutionCheckpoint | null {\n if (\n !value ||\n value.connectionId !== expected.connectionId ||\n value.googlePermissionId !== expected.googlePermissionId ||\n value.sourceId !== expected.sourceId ||\n value.driveId !== expected.driveId ||\n encodedJsonBytes(value) > GOOGLE_DRIVE_EXECUTION_CHECKPOINT_MAX_BYTES\n ) {\n return null;\n }\n if (value.version === 2 && value.kind === \"google_drive_changes\") {\n const changesCheckpoint = parseGoogleDriveChangesCheckpoint(value.changesCheckpoint, limits);\n return changesCheckpoint\n ? ({ ...value, changesCheckpoint } as GoogleDriveExecutionCheckpoint)\n : null;\n }\n if (value.version === 3 && value.kind === \"google_drive_full_reconciliation\") {\n const budgetBeforeInventory = parseGoogleDriveSyncBudget(value.budgetBeforeInventory, limits);\n const revisionFloors = parseGoogleDriveRevisionFloors(value.revisionFloors, limits.maxItems);\n if (\n typeof value.boundaryId !== \"string\" ||\n value.boundaryId.length < 1 ||\n value.boundaryId.length > 1024 ||\n typeof value.startPageToken !== \"string\" ||\n value.startPageToken.length < 1 ||\n value.startPageToken.length > 4096 ||\n typeof value.cursorInvalidated !== \"boolean\" ||\n !budgetBeforeInventory ||\n !revisionFloors ||\n !Number.isSafeInteger(value.inventoryElapsedMs) ||\n Number(value.inventoryElapsedMs) < 0 ||\n Number(value.inventoryElapsedMs) > limits.maxElapsedMs ||\n budgetBeforeInventory.elapsedMs + Number(value.inventoryElapsedMs) > limits.maxElapsedMs ||\n (value.inventoryCheckpoint !== null &&\n (!value.inventoryCheckpoint ||\n typeof value.inventoryCheckpoint !== \"object\" ||\n Array.isArray(value.inventoryCheckpoint)))\n ) {\n return null;\n }\n return {\n ...value,\n budgetBeforeInventory,\n inventoryElapsedMs: Number(value.inventoryElapsedMs),\n revisionFloors,\n } as GoogleDriveExecutionCheckpoint;\n }\n return null;\n}\n\nfunction buildGoogleDriveFullReconciliationCheckpoint(\n input: Omit<GoogleDriveFullReconciliationCheckpoint, \"version\" | \"kind\">,\n): GoogleDriveFullReconciliationCheckpoint {\n const checkpoint = {\n version: 3,\n kind: \"google_drive_full_reconciliation\",\n ...input,\n revisionFloors: input.revisionFloors.map((floor) => [...floor]),\n } satisfies GoogleDriveFullReconciliationCheckpoint;\n if (encodedJsonBytes(checkpoint) > GOOGLE_DRIVE_EXECUTION_CHECKPOINT_MAX_BYTES) {\n throw new SyncFailure(\"resource_limit\", false);\n }\n return checkpoint;\n}\n\nfunction parseGoogleDriveRevisionFloors(\n value: unknown,\n maxItems: number,\n): GoogleDriveRevisionFloor[] | null {\n if (!Array.isArray(value) || value.length > maxItems) return null;\n const floors: GoogleDriveRevisionFloor[] = [];\n const seen = new Set<string>();\n for (const floor of value) {\n if (\n !Array.isArray(floor) ||\n floor.length !== 2 ||\n typeof floor[0] !== \"string\" ||\n floor[0].trim().length < 1 ||\n floor[0].length > 1024 ||\n (floor[1] !== null &&\n (typeof floor[1] !== \"string\" || floor[1].length < 1 || floor[1].length > 256)) ||\n seen.has(floor[0])\n ) {\n return null;\n }\n seen.add(floor[0]);\n floors.push([floor[0], floor[1]]);\n }\n return floors;\n}\n\nfunction revisionFloorsForEntries(\n entries: GoogleDriveInventoryEntry[],\n maxItems: number,\n): GoogleDriveRevisionFloor[] {\n const reconciled = reconcileGoogleDriveRevisionFloors(entries, [], maxItems);\n if (reconciled.conflict) throw new SyncFailure(\"provider_payload_invalid\", false);\n return reconciled.revisionFloors;\n}\n\nexport function shouldProcessGoogleDriveDurableObservation(input: {\n entry: Pick<GoogleDriveInventoryEntry, \"externalObjectId\">;\n observation: KnowledgeSourceSyncObjectObservationResult;\n sourceLifecycleGeneration: number;\n aclGeneration: number;\n}): boolean {\n if (input.observation.externalObjectId !== input.entry.externalObjectId) {\n throw new SyncFailure(\"provider_payload_invalid\", false);\n }\n if (\n input.observation.disposition === \"accepted\" ||\n input.observation.disposition === \"replayed\"\n ) {\n return true;\n }\n if (input.observation.disposition === \"conflict\") {\n throw new SyncFailure(\"provider_payload_invalid\", false);\n }\n const current = input.observation.currentVersion;\n const comparison = current\n ? compareCanonicalDecimalProviderRevisions(\n current.providerRevision,\n input.observation.providerRevision,\n )\n : null;\n const fullyProcessed =\n current !== null &&\n current.objectLifecycleState === \"active\" &&\n current.sourceLifecycleGeneration === input.sourceLifecycleGeneration &&\n current.objectLifecycleGeneration === current.currentObjectLifecycleGeneration &&\n current.aclGeneration === input.aclGeneration &&\n current.indexObligationStatus === \"indexed\" &&\n comparison !== null &&\n comparison >= 0 &&\n (comparison > 0 || current.metadataHash === input.observation.metadataHash);\n if (!fullyProcessed) throw new SyncFailure(\"provider_payload_invalid\", false);\n return false;\n}\n\nexport function mergeGoogleDriveDurableObservationFloors(\n checkpoint: Record<string, unknown> | null,\n observations: KnowledgeSourceSyncObservationFloor[],\n maxItems: number,\n): Record<string, unknown> | null {\n if (\n !checkpoint ||\n checkpoint.version !== 3 ||\n checkpoint.kind !== \"google_drive_full_reconciliation\"\n ) {\n return checkpoint;\n }\n const parsedFloors = parseGoogleDriveRevisionFloors(checkpoint.revisionFloors, maxItems);\n if (!parsedFloors) throw new SyncFailure(\"provider_payload_invalid\", false);\n const floors = new Map<string, string | null>(parsedFloors);\n for (const observation of observations) {\n floors.set(observation.externalObjectId, observation.providerRevision);\n }\n if (floors.size > maxItems) throw new SyncFailure(\"resource_limit\", false);\n const merged = {\n ...checkpoint,\n revisionFloors: [...floors],\n };\n if (encodedJsonBytes(merged) > GOOGLE_DRIVE_EXECUTION_CHECKPOINT_MAX_BYTES) {\n throw new SyncFailure(\"resource_limit\", false);\n }\n return merged;\n}\n\nfunction reconcileGoogleDriveRevisionFloors(\n entries: GoogleDriveInventoryEntry[],\n existingFloors: GoogleDriveRevisionFloor[],\n maxItems: number,\n): {\n entries: GoogleDriveInventoryEntry[];\n revisionFloors: GoogleDriveRevisionFloor[];\n conflict: boolean;\n} {\n const floors = new Map<string, string | null>(existingFloors);\n const accepted: GoogleDriveInventoryEntry[] = [];\n for (const entry of entries) {\n if (!floors.has(entry.externalObjectId)) {\n floors.set(entry.externalObjectId, entry.externalVersionId);\n accepted.push(entry);\n } else {\n const comparison = compareCanonicalDecimalProviderRevisions(\n entry.externalVersionId,\n floors.get(entry.externalObjectId) ?? null,\n );\n if (comparison === null) {\n return {\n entries: [],\n revisionFloors: [...floors],\n conflict: true,\n };\n }\n if (comparison > 0) {\n floors.set(entry.externalObjectId, entry.externalVersionId);\n accepted.push(entry);\n }\n }\n if (floors.size > maxItems) throw new SyncFailure(\"resource_limit\", false);\n }\n return {\n entries: accepted,\n revisionFloors: [...floors],\n conflict: false,\n };\n}\n\nfunction encodedJsonBytes(value: unknown): number {\n try {\n return new TextEncoder().encode(JSON.stringify(value)).byteLength;\n } catch {\n return Number.POSITIVE_INFINITY;\n }\n}\n\nfunction parseGoogleDriveSyncBudget(\n value: unknown,\n limits: { maxItems: number; maxProviderRequests: number; maxElapsedMs: number },\n): GoogleDriveSyncBudget | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const row = value as Record<string, unknown>;\n for (const [key, maximum] of [\n [\"examinedItems\", limits.maxItems],\n [\"providerRequests\", limits.maxProviderRequests],\n [\"elapsedMs\", limits.maxElapsedMs],\n ] as const) {\n const budgetValue = row[key];\n if (\n !Number.isSafeInteger(budgetValue) ||\n Number(budgetValue) < 0 ||\n Number(budgetValue) > maximum\n ) {\n return null;\n }\n }\n return value as GoogleDriveSyncBudget;\n}\n\nfunction emptyGoogleDriveSyncBudget(): GoogleDriveSyncBudget {\n return { examinedItems: 0, providerRequests: 0, elapsedMs: 0 };\n}\n\nfunction googleDriveHardLimitReason(\n budget: GoogleDriveSyncBudget,\n limits: { maxItems: number; maxProviderRequests: number; maxElapsedMs: number },\n): Extract<\n GoogleDriveInventoryStopReason,\n \"api_request_limit\" | \"elapsed_time_limit\" | \"item_limit\"\n> | null {\n if (budget.examinedItems >= limits.maxItems) return \"item_limit\";\n if (budget.providerRequests >= limits.maxProviderRequests) return \"api_request_limit\";\n if (budget.elapsedMs >= limits.maxElapsedMs) return \"elapsed_time_limit\";\n return null;\n}\n\nfunction googleDriveInventoryStopIsHard(\n reason: GoogleDriveInventoryStopReason | null,\n budget: GoogleDriveSyncBudget,\n limits: { maxItems: number; maxProviderRequests: number; maxElapsedMs: number },\n): boolean {\n if (reason === \"api_request_limit\" || reason === \"item_limit\" || reason === \"known_byte_limit\") {\n return true;\n }\n return reason === \"elapsed_time_limit\" && budget.elapsedMs >= limits.maxElapsedMs;\n}\n\nasync function getDriveStartPageToken(\n driveId: string | null,\n authorization: string | undefined,\n retry: GoogleDriveProviderRetryOptions,\n observability: Observability,\n): Promise<string> {\n if (!authorization) throw new SyncFailure(\"connection_reconnect_required\", true, true);\n const url = new URL(`${DRIVE_API_BASE}/changes/startPageToken`);\n url.searchParams.set(\"supportsAllDrives\", \"true\");\n if (driveId) url.searchParams.set(\"driveId\", driveId);\n const response = await requestGoogleDrive(\n url,\n { headers: { authorization, accept: \"application/json\" } },\n \"start_page_token\",\n retry,\n observability,\n );\n if (!response.ok) throwGoogleDriveResponse(response);\n const payload = (await readResponseJsonBounded(\n response,\n DRIVE_JSON_MAX_BYTES,\n \"Google Drive start page token\",\n )) as Record<string, unknown>;\n return requiredString(payload.startPageToken, \"start_page_token\");\n}\n\nasync function listDriveChanges(\n pageToken: string,\n driveId: string | null,\n pageSize: number,\n authorization: string | undefined,\n retry: GoogleDriveProviderRetryOptions,\n observability: Observability,\n): Promise<GoogleDriveChangesPage> {\n if (!authorization) throw new SyncFailure(\"connection_reconnect_required\", true, true);\n const url = new URL(`${DRIVE_API_BASE}/changes`);\n url.searchParams.set(\"pageToken\", pageToken);\n url.searchParams.set(\"pageSize\", String(pageSize));\n url.searchParams.set(\"supportsAllDrives\", \"true\");\n url.searchParams.set(\"includeItemsFromAllDrives\", \"true\");\n url.searchParams.set(\"spaces\", \"drive\");\n url.searchParams.set(\n \"fields\",\n \"nextPageToken,newStartPageToken,changes(fileId,removed,time,driveId,file(id,name,mimeType,driveId,parents,modifiedTime,createdTime,version,md5Checksum,size,webViewLink,trashed))\",\n );\n if (driveId) url.searchParams.set(\"driveId\", driveId);\n const response = await requestGoogleDrive(\n url,\n { headers: { authorization, accept: \"application/json\" } },\n \"list_changes\",\n retry,\n observability,\n );\n if (response.status === 410) throw new GoogleDriveCursorInvalidError();\n if (!response.ok) throwGoogleDriveResponse(response);\n const payload = (await readResponseJsonBounded(\n response,\n DRIVE_JSON_MAX_BYTES,\n \"Google Drive changes list\",\n )) as Record<string, unknown>;\n const changes = Array.isArray(payload.changes) ? payload.changes : [];\n return {\n changes: changes.map((value) => {\n const row = value && typeof value === \"object\" ? (value as Record<string, unknown>) : {};\n const fileId = requiredString(row.fileId, \"change_file_id\");\n return {\n fileId,\n removed: row.removed === true,\n file: row.file && typeof row.file === \"object\" ? parseDriveProviderItem(row.file) : null,\n };\n }),\n nextPageToken: optionalString(payload.nextPageToken),\n newStartPageToken: optionalString(payload.newStartPageToken),\n };\n}\n\nasync function getDriveFile(\n fileId: string,\n authorization: string | undefined,\n retry: GoogleDriveProviderRetryOptions,\n observability: Observability,\n): Promise<GoogleDriveInventoryProviderItem | null> {\n if (!authorization) throw new SyncFailure(\"connection_reconnect_required\", true, true);\n const url = new URL(`${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}`);\n url.searchParams.set(\"supportsAllDrives\", \"true\");\n url.searchParams.set(\n \"fields\",\n \"id,name,mimeType,driveId,parents,modifiedTime,createdTime,version,md5Checksum,size,webViewLink,trashed\",\n );\n const response = await requestGoogleDrive(\n url,\n { headers: { authorization, accept: \"application/json\" } },\n \"get_file\",\n retry,\n observability,\n );\n if (response.status === 404) return null;\n if (!response.ok) throwGoogleDriveResponse(response);\n return parseDriveProviderItem(\n await readResponseJsonBounded(response, DRIVE_JSON_MAX_BYTES, \"Google Drive file metadata\"),\n );\n}\n\nasync function listDrivePermissions(\n input: { fileId: string; pageToken: string | null; pageSize: number },\n authorization: string | undefined,\n retry: GoogleDriveProviderRetryOptions,\n observability: Observability,\n): Promise<GoogleDrivePermissionsPage> {\n if (!authorization) throw new SyncFailure(\"connection_reconnect_required\", true, true);\n const url = new URL(`${DRIVE_API_BASE}/files/${encodeURIComponent(input.fileId)}/permissions`);\n url.searchParams.set(\"supportsAllDrives\", \"true\");\n url.searchParams.set(\"pageSize\", String(input.pageSize));\n url.searchParams.set(\n \"fields\",\n \"nextPageToken,permissions(id,type,emailAddress,domain,role,allowFileDiscovery,expirationTime,deleted,permissionDetails(inherited))\",\n );\n if (input.pageToken) url.searchParams.set(\"pageToken\", input.pageToken);\n const response = await requestGoogleDrive(\n url,\n { headers: { authorization, accept: \"application/json\" } },\n \"list_permissions\",\n retry,\n observability,\n );\n if (response.status === 403 || response.status === 404) {\n return { permissions: [], nextPageToken: null, denied: true };\n }\n if (!response.ok) throwGoogleDriveResponse(response);\n const payload = (await readResponseJsonBounded(\n response,\n DRIVE_JSON_MAX_BYTES,\n \"Google Drive permission list\",\n )) as Record<string, unknown>;\n const rawPermissions = Array.isArray(payload.permissions) ? payload.permissions : null;\n if (!rawPermissions) throw new SyncFailure(\"provider_payload_invalid\", false);\n return {\n permissions: rawPermissions.map(parseDrivePermission),\n nextPageToken: optionalString(payload.nextPageToken),\n denied: false,\n };\n}\n\nexport async function collectGoogleDriveAclEvidence(input: {\n entry: Pick<GoogleDriveInventoryEntry, \"externalObjectId\" | \"externalVersionId\" | \"driveId\">;\n maxProviderRequests: number;\n listPermissions: NonNullable<GoogleDriveSyncProviderPort[\"listPermissions\"]>;\n getFile?: GoogleDriveSyncProviderPort[\"getFile\"];\n now?: () => number;\n}): Promise<KnowledgeSourceSyncAclEvidence> {\n if (!Number.isSafeInteger(input.maxProviderRequests) || input.maxProviderRequests < 1) {\n throw new SyncFailure(\"resource_limit\", false);\n }\n const now = input.now ?? Date.now;\n const observedAt = new Date(now());\n if (!Number.isFinite(observedAt.getTime())) {\n throw new SyncFailure(\"provider_payload_invalid\", false);\n }\n const permissions: GoogleDrivePermission[] = [];\n const seenTokens = new Set<string>();\n let pageToken: string | null = null;\n let providerRequests = 0;\n let permissionListDenied = false;\n do {\n if (providerRequests >= input.maxProviderRequests) {\n throw new SyncFailure(\"resource_limit\", false);\n }\n providerRequests += 1;\n const page = await input.listPermissions({\n fileId: input.entry.externalObjectId,\n pageToken,\n pageSize: Math.min(100, GOOGLE_DRIVE_ACL_MAX_PRINCIPALS - permissions.length),\n });\n if (page.denied) {\n permissionListDenied = true;\n break;\n }\n permissions.push(...page.permissions);\n if (permissions.length > GOOGLE_DRIVE_ACL_MAX_PRINCIPALS) {\n throw new SyncFailure(\"resource_limit\", false);\n }\n pageToken = page.nextPageToken;\n if (pageToken) {\n if (pageToken.length > 4096 || seenTokens.has(pageToken)) {\n throw new SyncFailure(\"provider_payload_invalid\", false);\n }\n seenTokens.add(pageToken);\n }\n } while (pageToken);\n\n if (permissionListDenied) {\n if (!input.getFile || providerRequests >= input.maxProviderRequests) {\n return googleDriveDeniedAclEvidence(input.entry, observedAt, providerRequests);\n }\n providerRequests += 1;\n const current = await input.getFile(input.entry.externalObjectId);\n if (!current || current.trashed) {\n return googleDriveDeniedAclEvidence(input.entry, observedAt, providerRequests);\n }\n const aclRevision = createHash(\"sha256\")\n .update(\n JSON.stringify({\n version: 1,\n mode: \"source_owner_only\",\n externalObjectId: input.entry.externalObjectId,\n providerRevision: input.entry.externalVersionId,\n }),\n )\n .digest(\"hex\");\n return {\n eligibility: \"eligible\",\n providerRevision: input.entry.externalVersionId,\n driveId: input.entry.driveId,\n aclRevision,\n observedAt: observedAt.toISOString(),\n expiresAt: new Date(observedAt.getTime() + GOOGLE_DRIVE_ACL_FRESHNESS_MS).toISOString(),\n providerRequests,\n principals: [],\n };\n }\n\n const canonicalPermissions = permissions\n .map((permission) => ({\n id: permission.id,\n type: permission.type,\n role: permission.role,\n emailAddress: permission.emailAddress,\n domain: permission.domain,\n allowFileDiscovery: permission.allowFileDiscovery,\n expirationTime: permission.expirationTime,\n inherited: permission.inherited,\n }))\n .sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right)));\n const aclRevision = createHash(\"sha256\")\n .update(\n JSON.stringify({\n version: 1,\n externalObjectId: input.entry.externalObjectId,\n providerRevision: input.entry.externalVersionId,\n permissions: canonicalPermissions,\n }),\n )\n .digest(\"hex\");\n return {\n eligibility: \"eligible\",\n providerRevision: input.entry.externalVersionId,\n driveId: input.entry.driveId,\n aclRevision,\n observedAt: observedAt.toISOString(),\n expiresAt: new Date(observedAt.getTime() + GOOGLE_DRIVE_ACL_FRESHNESS_MS).toISOString(),\n providerRequests,\n principals: canonicalPermissions.map((permission) => ({\n type: permission.type,\n permissionId: permission.id,\n emailAddress: permission.emailAddress,\n domain: permission.domain,\n role: permission.role,\n inherited: permission.inherited,\n allowFileDiscovery: permission.allowFileDiscovery,\n expirationTime: permission.expirationTime,\n })),\n };\n}\n\nfunction googleDriveDeniedAclEvidence(\n entry: Pick<GoogleDriveInventoryEntry, \"externalObjectId\" | \"externalVersionId\" | \"driveId\">,\n observedAt: Date,\n providerRequests: number,\n) {\n return {\n eligibility: \"denied\" as const,\n providerRevision: entry.externalVersionId,\n driveId: entry.driveId,\n aclRevision: createHash(\"sha256\")\n .update(\n JSON.stringify({\n version: 1,\n mode: \"provider_denied\",\n externalObjectId: entry.externalObjectId,\n providerRevision: entry.externalVersionId,\n }),\n )\n .digest(\"hex\"),\n observedAt: observedAt.toISOString(),\n expiresAt: new Date(observedAt.getTime() + GOOGLE_DRIVE_ACL_FRESHNESS_MS).toISOString(),\n providerRequests,\n principals: [],\n };\n}\n\nfunction parseDrivePermission(value: unknown): GoogleDrivePermission {\n const row = objectRecord(value);\n if (row.deleted === true) throw new SyncFailure(\"provider_payload_invalid\", false);\n const type = requiredString(row.type, \"permission.type\");\n if (type !== \"user\" && type !== \"group\" && type !== \"domain\" && type !== \"anyone\") {\n throw new SyncFailure(\"provider_payload_invalid\", false);\n }\n const role = requiredString(row.role, \"permission.role\");\n if (\n role !== \"owner\" &&\n role !== \"organizer\" &&\n role !== \"fileOrganizer\" &&\n role !== \"writer\" &&\n role !== \"commenter\" &&\n role !== \"reader\"\n ) {\n throw new SyncFailure(\"provider_payload_invalid\", false);\n }\n const permissionDetails = Array.isArray(row.permissionDetails) ? row.permissionDetails : [];\n return {\n id: requiredString(row.id, \"permission.id\"),\n type,\n role,\n emailAddress: optionalString(row.emailAddress),\n domain: optionalString(row.domain),\n allowFileDiscovery: typeof row.allowFileDiscovery === \"boolean\" ? row.allowFileDiscovery : null,\n expirationTime: optionalExactProviderTimestamp(row.expirationTime),\n inherited: permissionDetails.some((detail) => objectRecord(detail).inherited === true),\n };\n}\n\nfunction optionalExactProviderTimestamp(value: unknown): string | null {\n const timestamp = optionalString(value);\n if (!timestamp) return null;\n const parsed = new Date(timestamp);\n if (!Number.isFinite(parsed.getTime())) throw new SyncFailure(\"provider_payload_invalid\", false);\n return parsed.toISOString();\n}\n\nfunction throwGoogleDriveResponse(response: Response): never {\n if (response.status === 401 || response.status === 403) {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n throw new SyncFailure(\n response.status >= 500 || response.status === 429\n ? \"provider_unavailable\"\n : \"provider_rejected\",\n response.status >= 500 || response.status === 429,\n );\n}\n\nasync function requestGoogleDrive(\n url: URL,\n init: RequestInit,\n operation: GoogleDriveProviderOperation,\n retry: GoogleDriveProviderRetryOptions,\n observability: Observability,\n): Promise<Response> {\n try {\n return await fetchGoogleDriveProvider({\n fetchImpl: sourceFetch,\n url,\n init,\n operation,\n policy: retry,\n observability,\n heartbeat: (details) => heartbeat({ provider: \"google_drive\", ...details }),\n });\n } catch (error) {\n if (error instanceof GoogleDriveProviderTransportError) {\n throw new SyncFailure(\"provider_unavailable\", true);\n }\n throw error;\n }\n}\n\nfunction selectedDriveSource(\n metadata: ReturnType<typeof GoogleDriveConnectionMetadata.parse>,\n externalSourceId: string,\n): GoogleDriveSelectedSource | null {\n const sources =\n metadata.selectedSources ?? (metadata.selectedSource ? [metadata.selectedSource] : []);\n return sources.find((source) => source.id === externalSourceId) ?? null;\n}\n\nexport function googleDriveSyncProviderAccessAllowed(input: {\n connectionVersion: number;\n resolvedConnectionVersion: number | undefined;\n connectionStatus: string;\n lifecycleState: string | undefined;\n grantedScopes: string[];\n}): boolean {\n return (\n input.resolvedConnectionVersion !== undefined &&\n input.connectionVersion === input.resolvedConnectionVersion &&\n input.connectionStatus === \"active\" &&\n (input.lifecycleState === undefined || input.lifecycleState === \"active\") &&\n googleDriveScopesAllowCapability(input.grantedScopes, \"recursive_source_sync\")\n );\n}\n\nasync function listDriveChildren(\n input: { folderId: string; driveId: string | null; pageToken: string | null; pageSize: number },\n authorization: string | undefined,\n retry: GoogleDriveProviderRetryOptions,\n observability: Observability,\n): Promise<GoogleDriveInventoryPage> {\n if (!authorization) throw new SyncFailure(\"connection_reconnect_required\", true, true);\n const url = new URL(`${DRIVE_API_BASE}/files`);\n url.searchParams.set(\n \"q\",\n `'${input.folderId.replaceAll(\"'\", \"\\\\'\")}' in parents and trashed = false`,\n );\n url.searchParams.set(\"pageSize\", String(input.pageSize));\n url.searchParams.set(\"supportsAllDrives\", \"true\");\n url.searchParams.set(\"includeItemsFromAllDrives\", \"true\");\n url.searchParams.set(\n \"fields\",\n \"nextPageToken,incompleteSearch,files(id,name,mimeType,driveId,parents,modifiedTime,createdTime,version,md5Checksum,size,webViewLink,trashed)\",\n );\n if (input.pageToken) url.searchParams.set(\"pageToken\", input.pageToken);\n if (input.driveId) {\n url.searchParams.set(\"corpora\", \"drive\");\n url.searchParams.set(\"driveId\", input.driveId);\n }\n const response = await requestGoogleDrive(\n url,\n { headers: { authorization, accept: \"application/json\" } },\n \"list_children\",\n retry,\n observability,\n );\n if (!response.ok) {\n if (response.status === 401 || response.status === 403) {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n throw new SyncFailure(\n \"provider_unavailable\",\n response.status >= 500 || response.status === 429,\n );\n }\n const payload = (await readResponseJsonBounded(\n response,\n DRIVE_JSON_MAX_BYTES,\n \"Google Drive file list\",\n )) as Record<string, unknown>;\n const rawFiles = Array.isArray(payload.files) ? payload.files : [];\n return {\n items: rawFiles.map(parseDriveProviderItem),\n nextPageToken: typeof payload.nextPageToken === \"string\" ? payload.nextPageToken : null,\n incompleteSearch: payload.incompleteSearch === true,\n };\n}\n\nfunction parseDriveProviderItem(value: unknown): GoogleDriveInventoryProviderItem {\n const row = value && typeof value === \"object\" ? (value as Record<string, unknown>) : {};\n return {\n id: requiredString(row.id, \"id\"),\n name: requiredString(row.name, \"name\"),\n mimeType: requiredString(row.mimeType, \"mimeType\"),\n driveId: optionalString(row.driveId),\n parents: Array.isArray(row.parents)\n ? row.parents.filter((item): item is string => typeof item === \"string\")\n : [],\n modifiedTime: optionalString(row.modifiedTime),\n createdTime: optionalString(row.createdTime),\n version: optionalString(row.version),\n md5Checksum: optionalString(row.md5Checksum),\n size: optionalString(row.size),\n webViewLink: optionalString(row.webViewLink),\n trashed: row.trashed === true,\n };\n}\n\nasync function fetchDriveBytes(\n entry: GoogleDriveInventoryEntry,\n authorization: string | undefined,\n maxBytes: number,\n retry: GoogleDriveProviderRetryOptions,\n observability: Observability,\n): Promise<Uint8Array> {\n if (!authorization) throw new SyncFailure(\"connection_reconnect_required\", true, true);\n const url =\n entry.transfer.action === \"export\"\n ? new URL(`${DRIVE_API_BASE}/files/${encodeURIComponent(entry.externalObjectId)}/export`)\n : new URL(`${DRIVE_API_BASE}/files/${encodeURIComponent(entry.externalObjectId)}`);\n if (entry.transfer.action === \"export\") {\n url.searchParams.set(\"mimeType\", entry.transfer.contentType);\n } else {\n url.searchParams.set(\"alt\", \"media\");\n url.searchParams.set(\"supportsAllDrives\", \"true\");\n }\n const response = await requestGoogleDrive(\n url,\n { headers: { authorization } },\n entry.transfer.action === \"export\" ? \"export\" : \"download\",\n retry,\n observability,\n );\n if (!response.ok) {\n if (response.status === 401 || response.status === 403) {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n throw new SyncFailure(\n \"provider_unavailable\",\n response.status >= 500 || response.status === 429,\n );\n }\n const declared = Number(response.headers.get(\"content-length\") ?? \"0\");\n if (Number.isFinite(declared) && declared > maxBytes) {\n throw new SyncFailure(\"content_too_large\", false);\n }\n if (!response.body) {\n const bytes = new Uint8Array(await response.arrayBuffer());\n if (bytes.byteLength > maxBytes) throw new SyncFailure(\"content_too_large\", false);\n return bytes;\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw new SyncFailure(\"content_too_large\", false);\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\nasync function listAtlassianItems(\n source: AtlassianSelectedSource,\n cursor: string | null,\n pageSize: number,\n authorization: string | undefined,\n): Promise<AtlassianInventoryPage> {\n if (!authorization) throw new SyncFailure(\"connection_reconnect_required\", true, true);\n if (source.kind === \"jira_project\") {\n const url = new URL(\n `${ATLASSIAN_API_BASE}/ex/jira/${encodeURIComponent(source.cloudId)}/rest/api/3/search/jql`,\n );\n url.searchParams.set(\n \"jql\",\n `project = \"${source.key.replaceAll('\"', '\\\\\"')}\" ORDER BY key ASC`,\n );\n url.searchParams.set(\"maxResults\", String(pageSize));\n url.searchParams.set(\"fields\", \"summary,created,updated\");\n if (cursor) url.searchParams.set(\"nextPageToken\", cursor);\n const payload = objectRecord(await atlassianJsonRequest(url, authorization, \"Jira issue list\"));\n const issues = Array.isArray(payload.issues) ? payload.issues : [];\n return {\n items: issues.map((raw) => {\n const row = objectRecord(raw);\n const fields = objectRecord(row.fields);\n const id = requiredAtlassianString(row.id, \"issue.id\");\n const key = requiredAtlassianString(row.key, \"issue.key\");\n const updatedAt = optionalString(fields.updated);\n return {\n id,\n key,\n title: requiredAtlassianString(fields.summary, \"issue.summary\"),\n version: updatedAt,\n createdAt: optionalString(fields.created),\n updatedAt,\n webUrl: new URL(`/browse/${encodeURIComponent(key)}`, source.siteUrl).toString(),\n };\n }),\n nextCursor: optionalString(payload.nextPageToken),\n };\n }\n\n const url = new URL(\n `${ATLASSIAN_API_BASE}/ex/confluence/${encodeURIComponent(source.cloudId)}/wiki/api/v2/spaces/${encodeURIComponent(source.resourceId)}/pages`,\n );\n url.searchParams.set(\"limit\", String(pageSize));\n url.searchParams.set(\"sort\", \"id\");\n if (cursor) url.searchParams.set(\"cursor\", cursor);\n const payload = objectRecord(\n await atlassianJsonRequest(url, authorization, \"Confluence page list\"),\n );\n const pages = Array.isArray(payload.results) ? payload.results : [];\n return {\n items: pages.map((raw) => {\n const row = objectRecord(raw);\n const version = objectRecord(row.version);\n const id = requiredAtlassianString(row.id, \"page.id\");\n const webUi = optionalString(objectRecord(row._links).webui);\n const versionNumber = numberValue(version.number);\n return {\n id,\n key: id,\n title: requiredAtlassianString(row.title, \"page.title\"),\n version: versionNumber === undefined ? null : String(versionNumber),\n createdAt: optionalString(row.createdAt),\n updatedAt: optionalString(version.createdAt),\n webUrl: webUi\n ? new URL(webUi.startsWith(\"/wiki/\") ? webUi : `/wiki${webUi}`, source.siteUrl).toString()\n : new URL(\n `/wiki/spaces/${encodeURIComponent(source.key)}/pages/${encodeURIComponent(id)}`,\n source.siteUrl,\n ).toString(),\n };\n }),\n nextCursor: confluenceCursor(objectRecord(payload._links).next),\n };\n}\n\nasync function fetchAtlassianContent(\n source: AtlassianSelectedSource,\n entry: AtlassianInventoryEntry,\n authorization: string | undefined,\n maxBytes: number,\n): Promise<Uint8Array> {\n if (!authorization) throw new SyncFailure(\"connection_reconnect_required\", true, true);\n const objectId = entry.externalObjectId.slice(entry.externalObjectId.indexOf(\":\") + 1);\n const markdown =\n source.kind === \"jira_project\"\n ? await jiraIssueMarkdown(source, objectId, entry, authorization)\n : await confluencePageMarkdown(source, objectId, entry, authorization);\n const bytes = new TextEncoder().encode(markdown);\n if (bytes.byteLength > maxBytes) throw new SyncFailure(\"content_too_large\", false);\n return bytes;\n}\n\nasync function jiraIssueMarkdown(\n source: AtlassianSelectedSource,\n issueId: string,\n entry: AtlassianInventoryEntry,\n authorization: string,\n): Promise<string> {\n const issueUrl = new URL(\n `${ATLASSIAN_API_BASE}/ex/jira/${encodeURIComponent(source.cloudId)}/rest/api/3/issue/${encodeURIComponent(issueId)}`,\n );\n issueUrl.searchParams.set(\n \"fields\",\n \"summary,description,status,issuetype,priority,assignee,reporter,labels,created,updated\",\n );\n const issue = objectRecord(await atlassianJsonRequest(issueUrl, authorization, \"Jira issue\"));\n const fields = objectRecord(issue.fields);\n const lines = [\n `# ${entry.title}`,\n \"\",\n `- Key: ${optionalString(issue.key) ?? entry.title}`,\n `- Type: ${optionalString(objectRecord(fields.issuetype).name) ?? \"Unknown\"}`,\n `- Status: ${optionalString(objectRecord(fields.status).name) ?? \"Unknown\"}`,\n `- Priority: ${optionalString(objectRecord(fields.priority).name) ?? \"None\"}`,\n `- Assignee: ${optionalString(objectRecord(fields.assignee).displayName) ?? \"Unassigned\"}`,\n `- Reporter: ${optionalString(objectRecord(fields.reporter).displayName) ?? \"Unknown\"}`,\n `- Updated: ${optionalString(fields.updated) ?? \"Unknown\"}`,\n `- Source: ${entry.sourceUri}`,\n \"\",\n \"## Description\",\n \"\",\n adfToMarkdown(fields.description) || \"No description.\",\n ];\n const labels = Array.isArray(fields.labels)\n ? fields.labels.filter((value): value is string => typeof value === \"string\")\n : [];\n if (labels.length > 0) lines.splice(9, 0, `- Labels: ${labels.join(\", \")}`);\n const comments = await jiraComments(source, issueId, authorization);\n if (comments.length > 0) {\n lines.push(\"\", \"## Comments\", \"\");\n for (const comment of comments) {\n const row = objectRecord(comment);\n const author = optionalString(objectRecord(row.author).displayName) ?? \"Unknown author\";\n const created = optionalString(row.created) ?? \"Unknown date\";\n lines.push(`### ${author} · ${created}`, \"\", adfToMarkdown(row.body), \"\");\n }\n }\n return lines.join(\"\\n\");\n}\n\nasync function jiraComments(\n source: AtlassianSelectedSource,\n issueId: string,\n authorization: string,\n): Promise<unknown[]> {\n const comments: unknown[] = [];\n let startAt = 0;\n for (let page = 0; page < 20; page += 1) {\n const url = new URL(\n `${ATLASSIAN_API_BASE}/ex/jira/${encodeURIComponent(source.cloudId)}/rest/api/3/issue/${encodeURIComponent(issueId)}/comment`,\n );\n url.searchParams.set(\"startAt\", String(startAt));\n url.searchParams.set(\"maxResults\", \"100\");\n url.searchParams.set(\"orderBy\", \"created\");\n const payload = objectRecord(await atlassianJsonRequest(url, authorization, \"Jira comments\"));\n const pageComments = Array.isArray(payload.comments) ? payload.comments : [];\n comments.push(...pageComments);\n const total = numberValue(payload.total) ?? comments.length;\n if (comments.length >= total || pageComments.length === 0) break;\n startAt += pageComments.length;\n }\n return comments;\n}\n\nasync function confluencePageMarkdown(\n source: AtlassianSelectedSource,\n pageId: string,\n entry: AtlassianInventoryEntry,\n authorization: string,\n): Promise<string> {\n const pageUrl = new URL(\n `${ATLASSIAN_API_BASE}/ex/confluence/${encodeURIComponent(source.cloudId)}/wiki/api/v2/pages/${encodeURIComponent(pageId)}`,\n );\n pageUrl.searchParams.set(\"body-format\", \"storage\");\n const page = objectRecord(await atlassianJsonRequest(pageUrl, authorization, \"Confluence page\"));\n const storage = objectRecord(objectRecord(page.body).storage);\n const lines = [\n `# ${entry.title}`,\n \"\",\n `- Space: ${source.name} (${source.key})`,\n `- Updated: ${entry.modifiedTime ?? \"Unknown\"}`,\n `- Source: ${entry.sourceUri}`,\n \"\",\n \"## Content\",\n \"\",\n optionalString(storage.value) ?? \"No content.\",\n ];\n const comments = await confluenceFooterComments(source, pageId, authorization);\n if (comments.length > 0) {\n lines.push(\"\", \"## Comments\", \"\");\n for (const comment of comments) {\n const row = objectRecord(comment);\n const body = objectRecord(objectRecord(row.body).storage);\n const version = objectRecord(row.version);\n lines.push(\n `### Comment · ${optionalString(version.createdAt) ?? \"Unknown date\"}`,\n \"\",\n optionalString(body.value) ?? \"\",\n \"\",\n );\n }\n }\n return lines.join(\"\\n\");\n}\n\nasync function confluenceFooterComments(\n source: AtlassianSelectedSource,\n pageId: string,\n authorization: string,\n): Promise<unknown[]> {\n const comments: unknown[] = [];\n let cursor: string | null = null;\n for (let page = 0; page < 20; page += 1) {\n const url = new URL(\n `${ATLASSIAN_API_BASE}/ex/confluence/${encodeURIComponent(source.cloudId)}/wiki/api/v2/pages/${encodeURIComponent(pageId)}/footer-comments`,\n );\n url.searchParams.set(\"body-format\", \"storage\");\n url.searchParams.set(\"limit\", \"100\");\n if (cursor) url.searchParams.set(\"cursor\", cursor);\n const payload = objectRecord(\n await atlassianJsonRequest(url, authorization, \"Confluence page comments\"),\n );\n const results = Array.isArray(payload.results) ? payload.results : [];\n comments.push(...results);\n cursor = confluenceCursor(objectRecord(payload._links).next);\n if (!cursor) break;\n }\n return comments;\n}\n\nasync function atlassianJsonRequest(\n url: URL,\n authorization: string,\n label: string,\n): Promise<unknown> {\n const response = await sourceFetch(url, {\n headers: { authorization, accept: \"application/json\" },\n redirect: \"error\",\n signal: AbortSignal.timeout(20_000),\n });\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n if (response.status === 401 || response.status === 403) {\n throw new SyncFailure(\"connection_reconnect_required\", true, true);\n }\n throw new SyncFailure(\n \"provider_unavailable\",\n response.status >= 500 || response.status === 429,\n );\n }\n return await readResponseJsonBounded(response, ATLASSIAN_JSON_MAX_BYTES, label);\n}\n\nexport function confluenceCursor(value: unknown): string | null {\n const next = optionalString(value);\n if (!next) return null;\n const url = new URL(next, ATLASSIAN_API_BASE);\n const cursor = url.searchParams.get(\"cursor\");\n if (!cursor || cursor.length > 4_096 || /[\\u0000-\\u001f]/.test(cursor)) {\n throw new Error(\"invalid Confluence cursor\");\n }\n return cursor;\n}\n\nexport function adfToMarkdown(value: unknown): string {\n const node = objectRecord(value);\n const type = optionalString(node.type);\n const children = Array.isArray(node.content) ? node.content.map(adfToMarkdown).join(\"\") : \"\";\n if (type === \"text\") {\n let text = typeof node.text === \"string\" ? node.text : \"\";\n const marks = Array.isArray(node.marks) ? node.marks : [];\n for (const rawMark of marks) {\n const mark = objectRecord(rawMark);\n const markType = optionalString(mark.type);\n if (markType === \"code\") text = `\\`${text}\\``;\n if (markType === \"strong\") text = `**${text}**`;\n if (markType === \"em\") text = `*${text}*`;\n if (markType === \"strike\") text = `~~${text}~~`;\n if (markType === \"link\") {\n const href = optionalString(objectRecord(mark.attrs).href);\n if (href) text = `[${text}](${href})`;\n }\n }\n return text;\n }\n if (type === \"paragraph\") return `${children}\\n\\n`;\n if (type === \"heading\") {\n const level = Math.min(Math.max(numberValue(objectRecord(node.attrs).level) ?? 2, 1), 6);\n return `${\"#\".repeat(level)} ${children.trim()}\\n\\n`;\n }\n if (type === \"hardBreak\") return \" \\n\";\n if (type === \"rule\") return \"---\\n\\n\";\n if (type === \"blockquote\") {\n return `${children\n .trim()\n .split(\"\\n\")\n .map((line) => `> ${line}`)\n .join(\"\\n\")}\\n\\n`;\n }\n if (type === \"bulletList\") {\n return `${children.trimEnd()}\\n`;\n }\n if (type === \"orderedList\") {\n return `${children.trimEnd()}\\n`;\n }\n if (type === \"listItem\") {\n return `- ${children.trim().replaceAll(\"\\n\", \"\\n \")}\\n`;\n }\n if (type === \"codeBlock\") return `\\`\\`\\`\\n${children.trimEnd()}\\n\\`\\`\\`\\n\\n`;\n if (type === \"mention\") return `@${optionalString(objectRecord(node.attrs).text) ?? \"user\"}`;\n if (type === \"emoji\") return optionalString(objectRecord(node.attrs).text) ?? \"\";\n if (type === \"inlineCard\") {\n const url = optionalString(objectRecord(node.attrs).url);\n return url ? `[${url}](${url})` : \"\";\n }\n return children;\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 requiredAtlassianString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !value.trim()) throw new Error(`invalid_atlassian_${label}`);\n return value;\n}\n\nfunction deterministicUuid(value: string): string {\n const bytes = createHash(\"sha256\").update(value).digest().subarray(0, 16);\n bytes[6] = (bytes[6]! & 0x0f) | 0x50;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = bytes.toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction safeFilename(value: string): string {\n const normalized = value\n .normalize(\"NFKC\")\n .replace(/[\\\\/:*?\"<>|\\0-\\x1f]/g, \"_\")\n .trim();\n return (normalized || \"document\").slice(0, 240);\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !value.trim()) throw new Error(`invalid_google_drive_${label}`);\n return value;\n}\n\nfunction optionalString(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction boundedError(error: unknown): string {\n return (error instanceof Error ? error.message : String(error)).slice(0, 1000);\n}\n\nfunction entryMetadataHash(entry: KnowledgeSyncEntry): string {\n return createHash(\"sha256\")\n .update(\n JSON.stringify({\n externalObjectId: entry.externalObjectId,\n externalVersionId: entry.externalVersionId,\n title: entry.title,\n mimeType: entry.mimeType,\n driveId: entry.driveId,\n modifiedTime: entry.modifiedTime,\n createdTime: entry.createdTime,\n sourceUri: entry.sourceUri,\n }),\n )\n .digest(\"hex\");\n}\n\nfunction inventoryLimit(\n reason: GoogleDriveInventoryStopReason | null,\n): KnowledgeSourceSyncRunSummary[\"limitReached\"] {\n if (reason === \"api_request_limit\") return \"provider_requests\";\n if (reason === \"elapsed_time_limit\") return \"elapsed_time\";\n if (reason === \"item_limit\") return \"items\";\n if (reason === \"known_byte_limit\") return \"bytes\";\n return null;\n}\n\nfunction recordSyncHealthTelemetry(\n observability: Observability,\n provider: \"google_drive\" | \"atlassian\",\n summary: KnowledgeSourceSyncRunSummary,\n outcome: \"succeeded\" | \"failed\",\n failure?: SyncFailure,\n): void {\n observability.observeHistogram({\n name: \"opengeni_knowledge_source_sync_terminal_batch_duration_seconds\",\n help: \"Terminal knowledge-source activity batch duration by provider and outcome.\",\n labels: { provider, outcome },\n value: Math.max(0, summary.elapsedMs) / 1_000,\n });\n if (summary.providerRequests > 0) {\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_provider_requests_total\",\n help: \"Logical provider requests consumed by knowledge-source synchronization.\",\n labels: { provider, outcome },\n amount: summary.providerRequests,\n });\n }\n if (summary.limitReached) {\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_limit_hits_total\",\n help: \"Knowledge-source synchronization runs stopped by an explicit resource budget.\",\n labels: { provider, limit: summary.limitReached },\n });\n }\n if (summary.reconnectRequired) {\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_reconnect_required_total\",\n help: \"Knowledge-source synchronization failures requiring connector reconnection.\",\n labels: { provider },\n });\n }\n if (failure) {\n observability.incrementCounter({\n name: \"opengeni_knowledge_source_sync_failures_total\",\n help: \"Knowledge-source synchronization terminal failures by bounded reason.\",\n labels: {\n provider,\n reason: failure.code,\n retryable: failure.retryable ? \"true\" : \"false\",\n },\n });\n observability.warn(\"Knowledge source sync failed\", {\n provider,\n outcome: failure.retryable ? \"retryable_failed\" : \"failed\",\n reason: failure.code,\n durationMs: summary.elapsedMs,\n });\n return;\n }\n observability.info(\"Knowledge source sync completed\", {\n provider,\n outcome: \"succeeded\",\n durationMs: summary.elapsedMs,\n });\n}\n\ntype SyncFailureCode = KnowledgeSourceSyncRunSummary[\"failures\"][number][\"code\"];\n\nclass SyncFailure extends Error {\n constructor(\n readonly code: SyncFailureCode,\n readonly retryable: boolean,\n readonly reconnectRequired = false,\n ) {\n super(code);\n this.name = \"KnowledgeSourceSyncFailure\";\n }\n}\n","import type { GoogleDriveProviderRetryOptions } from \"@opengeni/config\";\nimport type { FetchLike } from \"@opengeni/network\";\nimport type { Observability } from \"@opengeni/observability\";\n\nexport type GoogleDriveProviderOperation =\n | \"start_page_token\"\n | \"list_changes\"\n | \"get_file\"\n | \"list_children\"\n | \"list_permissions\"\n | \"download\"\n | \"export\";\n\nexport type GoogleDriveProviderHeartbeat = (details: {\n operation: GoogleDriveProviderOperation;\n attempt: number;\n phase: \"request_start\" | \"request_end\" | \"retry_delay_start\" | \"retry_delay_end\";\n}) => void;\n\nexport class GoogleDriveProviderTransportError extends Error {\n constructor() {\n super(\"google_drive_provider_transport_failed\");\n this.name = \"GoogleDriveProviderTransportError\";\n }\n}\n\n/**\n * Absorb only short, explicitly retryable Drive failures inside one bounded\n * activity. Provider bodies, URLs, headers, and credentials never enter logs\n * or metric labels. The caller's logical sync-request accounting remains\n * unchanged; this helper exposes physical attempts separately as telemetry.\n */\nexport async function fetchGoogleDriveProvider(input: {\n fetchImpl: FetchLike;\n url: string | URL;\n init: RequestInit;\n operation: GoogleDriveProviderOperation;\n policy: GoogleDriveProviderRetryOptions;\n observability: Observability;\n heartbeat?: GoogleDriveProviderHeartbeat;\n now?: () => number;\n sleep?: (delayMs: number) => Promise<void>;\n}): Promise<Response> {\n const now = input.now ?? Date.now;\n const sleep = input.sleep ?? Bun.sleep;\n let retryDelaySpentMs = 0;\n\n for (let attempt = 1; attempt <= input.policy.attempts; attempt += 1) {\n let response: Response;\n input.heartbeat?.({ operation: input.operation, attempt, phase: \"request_start\" });\n try {\n response = await input.fetchImpl(input.url, {\n ...input.init,\n redirect: \"error\",\n signal: AbortSignal.timeout(input.policy.requestTimeoutMs),\n });\n } catch {\n input.heartbeat?.({ operation: input.operation, attempt, phase: \"request_end\" });\n recordRequest(input.observability, input.operation, \"retryable_error\");\n const delayMs = retryDelayMs(input.policy, attempt, null);\n if (!canRetry(input.policy, attempt, retryDelaySpentMs, delayMs)) {\n throw new GoogleDriveProviderTransportError();\n }\n recordRetry(input.observability, input.operation, \"transport\", attempt, delayMs);\n retryDelaySpentMs += delayMs;\n input.heartbeat?.({ operation: input.operation, attempt, phase: \"retry_delay_start\" });\n await sleep(delayMs);\n input.heartbeat?.({ operation: input.operation, attempt, phase: \"retry_delay_end\" });\n continue;\n }\n input.heartbeat?.({ operation: input.operation, attempt, phase: \"request_end\" });\n\n if (!isRetryableStatus(response.status)) {\n recordRequest(\n input.observability,\n input.operation,\n response.ok ? \"succeeded\" : \"terminal_error\",\n );\n return response;\n }\n\n recordRequest(input.observability, input.operation, \"retryable_error\");\n const delayMs = retryDelayMs(\n input.policy,\n attempt,\n retryAfterDelayMs(response.headers.get(\"retry-after\"), now()),\n );\n if (!canRetry(input.policy, attempt, retryDelaySpentMs, delayMs)) return response;\n await response.body?.cancel().catch(() => undefined);\n recordRetry(\n input.observability,\n input.operation,\n response.status === 429 ? \"rate_limited\" : \"provider_unavailable\",\n attempt,\n delayMs,\n );\n retryDelaySpentMs += delayMs;\n input.heartbeat?.({ operation: input.operation, attempt, phase: \"retry_delay_start\" });\n await sleep(delayMs);\n input.heartbeat?.({ operation: input.operation, attempt, phase: \"retry_delay_end\" });\n }\n\n throw new GoogleDriveProviderTransportError();\n}\n\nfunction canRetry(\n policy: GoogleDriveProviderRetryOptions,\n attempt: number,\n retryDelaySpentMs: number,\n delayMs: number,\n): boolean {\n return attempt < policy.attempts && retryDelaySpentMs + delayMs <= policy.budgetMs;\n}\n\nfunction retryDelayMs(\n policy: GoogleDriveProviderRetryOptions,\n attempt: number,\n retryAfterMs: number | null,\n): number {\n const exponential = Math.min(\n policy.maxDelayMs,\n policy.initialDelayMs * 2 ** Math.max(0, attempt - 1),\n );\n return Math.min(policy.maxDelayMs, Math.max(exponential, retryAfterMs ?? 0));\n}\n\nfunction retryAfterDelayMs(value: string | null, nowMs: number): number | null {\n if (!value) return null;\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1_000);\n const timestamp = Date.parse(value);\n return Number.isFinite(timestamp) ? Math.max(0, timestamp - nowMs) : null;\n}\n\nfunction isRetryableStatus(status: number): boolean {\n return status === 429 || status >= 500;\n}\n\nfunction recordRequest(\n observability: Observability,\n operation: GoogleDriveProviderOperation,\n outcome: \"succeeded\" | \"retryable_error\" | \"terminal_error\",\n): void {\n observability.incrementCounter({\n name: \"opengeni_google_drive_provider_requests_total\",\n help: \"Google Drive provider request attempts by operation and bounded outcome.\",\n labels: { operation, outcome },\n });\n}\n\nfunction recordRetry(\n observability: Observability,\n operation: GoogleDriveProviderOperation,\n reason: \"transport\" | \"rate_limited\" | \"provider_unavailable\",\n attempt: number,\n delayMs: number,\n): void {\n observability.incrementCounter({\n name: \"opengeni_google_drive_provider_retries_total\",\n help: \"Bounded Google Drive provider retries by operation and reason.\",\n labels: { operation, reason },\n });\n observability.observeHistogram({\n name: \"opengeni_google_drive_provider_retry_delay_seconds\",\n help: \"Delay applied before a bounded Google Drive provider retry.\",\n labels: { operation, reason },\n value: delayMs / 1_000,\n buckets: [0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60],\n });\n observability.warn(\"Google Drive provider request retry scheduled\", {\n provider: \"google_drive\",\n operation,\n outcome: \"retry_scheduled\",\n reason,\n attempt,\n delayMs,\n });\n}\n","import { createHash } from \"node:crypto\";\nimport type { GoogleDriveSelectedSource } from \"@opengeni/contracts/google-drive\";\nimport {\n GOOGLE_DRIVE_FOLDER_MIME_TYPE,\n planGoogleDriveTransfer,\n type GoogleDriveInventoryEntry,\n type GoogleDriveInventoryProviderItem,\n} from \"@opengeni/documents/google-drive\";\n\nconst MAX_TOKEN_CHARS = 4096;\nconst MAX_BOUNDARY_ID_CHARS = 1024;\nconst MAX_ANCESTOR_DEPTH = 100;\n\nexport type GoogleDriveSyncBudget = {\n examinedItems: number;\n providerRequests: number;\n elapsedMs: number;\n};\n\nexport type GoogleDriveChangesCursor = {\n version: 1;\n kind: \"google_drive_changes\";\n connectionId: string;\n googlePermissionId: string;\n sourceId: string;\n driveId: string | null;\n boundaryId: string;\n pageToken: string;\n cursorGeneration: number;\n lastFullReconciliationAt: string;\n nextFullReconciliationAt: string;\n};\n\nexport type GoogleDriveChangesCheckpoint = {\n version: 2;\n pageToken: string;\n requiresFullReconciliation: boolean;\n seenPageTokenHashes: string[];\n budget: GoogleDriveSyncBudget;\n};\n\nexport type GoogleDriveChange = {\n fileId: string;\n removed: boolean;\n file: GoogleDriveInventoryProviderItem | null;\n};\n\nexport type GoogleDriveChangesPage = {\n changes: GoogleDriveChange[];\n nextPageToken: string | null;\n newStartPageToken: string | null;\n};\n\nexport type GoogleDriveChangesStopReason =\n | \"item_limit\"\n | \"api_request_limit\"\n | \"elapsed_time_limit\";\n\nexport type GoogleDriveChangesDrainResult = {\n status: \"complete\" | \"paused\";\n stopReason: GoogleDriveChangesStopReason | null;\n entries: GoogleDriveInventoryEntry[];\n checkpoint: GoogleDriveChangesCheckpoint | null;\n newStartPageToken: string | null;\n requiresFullReconciliation: boolean;\n providerRequests: number;\n elapsedMs: number;\n budget: GoogleDriveSyncBudget;\n hardLimitReached: boolean;\n};\n\nexport function parseGoogleDriveChangesCursor(\n value: Record<string, unknown> | null,\n expected: {\n connectionId: string;\n googlePermissionId: string;\n sourceId: string;\n driveId: string | null;\n },\n): GoogleDriveChangesCursor | null {\n if (!value || value.version !== 1 || value.kind !== \"google_drive_changes\") return null;\n if (\n value.connectionId !== expected.connectionId ||\n value.googlePermissionId !== expected.googlePermissionId ||\n value.sourceId !== expected.sourceId ||\n value.driveId !== expected.driveId ||\n typeof value.boundaryId !== \"string\" ||\n value.boundaryId.length < 1 ||\n value.boundaryId.length > MAX_BOUNDARY_ID_CHARS ||\n typeof value.pageToken !== \"string\" ||\n value.pageToken.length < 1 ||\n value.pageToken.length > MAX_TOKEN_CHARS ||\n typeof value.cursorGeneration !== \"number\" ||\n !Number.isSafeInteger(value.cursorGeneration) ||\n value.cursorGeneration < 1 ||\n typeof value.lastFullReconciliationAt !== \"string\" ||\n !Number.isFinite(Date.parse(value.lastFullReconciliationAt)) ||\n typeof value.nextFullReconciliationAt !== \"string\" ||\n !Number.isFinite(Date.parse(value.nextFullReconciliationAt))\n ) {\n return null;\n }\n return value as GoogleDriveChangesCursor;\n}\n\nexport function buildGoogleDriveChangesCursor(input: {\n connectionId: string;\n googlePermissionId: string;\n sourceId: string;\n driveId: string | null;\n boundaryId: string;\n pageToken: string;\n previousGeneration: number;\n reconciledAt: Date;\n fullReconciliationIntervalMs: number;\n}): GoogleDriveChangesCursor {\n return {\n version: 1,\n kind: \"google_drive_changes\",\n connectionId: input.connectionId,\n googlePermissionId: input.googlePermissionId,\n sourceId: input.sourceId,\n driveId: input.driveId,\n boundaryId: boundedBoundaryId(input.boundaryId),\n pageToken: boundedToken(input.pageToken),\n cursorGeneration: input.previousGeneration + 1,\n lastFullReconciliationAt: input.reconciledAt.toISOString(),\n nextFullReconciliationAt: new Date(\n input.reconciledAt.getTime() + input.fullReconciliationIntervalMs,\n ).toISOString(),\n };\n}\n\nexport function advanceGoogleDriveChangesCursor(\n cursor: GoogleDriveChangesCursor,\n pageToken: string,\n): GoogleDriveChangesCursor {\n return {\n ...cursor,\n pageToken: boundedToken(pageToken),\n cursorGeneration: cursor.cursorGeneration + 1,\n };\n}\n\nexport function googleDriveFullReconciliationDue(cursor: GoogleDriveChangesCursor, now: Date) {\n return Date.parse(cursor.nextFullReconciliationAt) <= now.getTime();\n}\n\nexport async function resolveGoogleDriveChangesBoundaryId(input: {\n source: GoogleDriveSelectedSource;\n getFile: (fileId: string) => Promise<GoogleDriveInventoryProviderItem | null>;\n}): Promise<string> {\n if (input.source.id !== \"root\" || input.source.driveId !== null) {\n return boundedBoundaryId(input.source.id);\n }\n const root = await input.getFile(\"root\");\n if (!root || root.mimeType !== GOOGLE_DRIVE_FOLDER_MIME_TYPE || root.trashed) {\n throw new GoogleDriveChangesProtocolError(\"google_drive_root_boundary_invalid\");\n }\n return boundedBoundaryId(root.id);\n}\n\nexport function parseGoogleDriveChangesCheckpoint(\n value: unknown,\n limits: { maxItems: number; maxProviderRequests: number; maxElapsedMs: number },\n): GoogleDriveChangesCheckpoint | null {\n try {\n return validatedCheckpoint(value, limits);\n } catch {\n return null;\n }\n}\n\nexport async function drainGoogleDriveChanges(input: {\n source: GoogleDriveSelectedSource;\n cursor: GoogleDriveChangesCursor;\n checkpoint: GoogleDriveChangesCheckpoint | null;\n maxItems: number;\n maxProviderRequests: number;\n maxElapsedMs: number;\n maxInvocationElapsedMs: number;\n maxFileBytes: number;\n listChanges: (pageToken: string, pageSize: number) => Promise<GoogleDriveChangesPage>;\n getFile: (fileId: string) => Promise<GoogleDriveInventoryProviderItem | null>;\n observedExternalObjectIds: (ids: string[]) => Promise<Set<string>>;\n now?: () => number;\n}): Promise<GoogleDriveChangesDrainResult> {\n const now = input.now ?? Date.now;\n const startedAt = now();\n const checkpoint = input.checkpoint ? validatedCheckpoint(input.checkpoint, input) : null;\n let pageToken = boundedToken(checkpoint?.pageToken ?? input.cursor.pageToken);\n let requiresFullReconciliation = checkpoint?.requiresFullReconciliation ?? false;\n const seenPageTokenHashes = new Set(checkpoint?.seenPageTokenHashes ?? []);\n const initialBudget = checkpoint?.budget ?? emptyBudget();\n const budget = { ...initialBudget };\n const entries = new Map<string, GoogleDriveInventoryEntry>();\n\n while (true) {\n const invocationElapsedMs = Math.max(0, now() - startedAt);\n budget.elapsedMs = initialBudget.elapsedMs + invocationElapsedMs;\n const stopReason = limitReason(budget, input, invocationElapsedMs);\n if (stopReason) {\n return {\n status: \"paused\",\n stopReason,\n entries: [...entries.values()],\n checkpoint: {\n version: 2,\n pageToken,\n requiresFullReconciliation,\n seenPageTokenHashes: [...seenPageTokenHashes],\n budget: { ...budget },\n },\n newStartPageToken: null,\n requiresFullReconciliation,\n providerRequests: budget.providerRequests,\n elapsedMs: budget.elapsedMs,\n budget: { ...budget },\n hardLimitReached:\n stopReason !== \"elapsed_time_limit\" || budget.elapsedMs >= input.maxElapsedMs,\n };\n }\n\n const pageTokenHash = createHash(\"sha256\").update(pageToken).digest(\"hex\");\n if (seenPageTokenHashes.has(pageTokenHash)) {\n throw new GoogleDriveChangesProtocolError(\"google_drive_changes_page_token_cycle\");\n }\n seenPageTokenHashes.add(pageTokenHash);\n budget.providerRequests += 1;\n const pageSize = Math.min(100, input.maxItems - budget.examinedItems);\n let page: GoogleDriveChangesPage;\n try {\n page = await input.listChanges(pageToken, pageSize);\n } catch (error) {\n budget.elapsedMs = initialBudget.elapsedMs + Math.max(0, now() - startedAt);\n if (error instanceof GoogleDriveCursorInvalidError) error.budget = { ...budget };\n throw error;\n }\n if (page.changes.length > pageSize) {\n throw new GoogleDriveChangesProtocolError(\"google_drive_changes_page_exceeds_item_budget\");\n }\n budget.examinedItems += page.changes.length;\n\n const repairCandidates = new Set<string>();\n for (const change of page.changes) {\n if (change.removed || !change.file || change.file.trashed) {\n repairCandidates.add(change.fileId);\n continue;\n }\n const membership = await isInsideSource({\n file: change.file,\n boundaryId: input.cursor.boundaryId,\n getFile: async (fileId) => {\n const ancestryElapsedMs = Math.max(0, now() - startedAt);\n budget.elapsedMs = initialBudget.elapsedMs + ancestryElapsedMs;\n if (\n budget.providerRequests >= input.maxProviderRequests ||\n budget.elapsedMs >= input.maxElapsedMs ||\n ancestryElapsedMs >= input.maxInvocationElapsedMs\n ) {\n return null;\n }\n budget.providerRequests += 1;\n const parent = await input.getFile(fileId);\n budget.elapsedMs = initialBudget.elapsedMs + Math.max(0, now() - startedAt);\n return parent;\n },\n });\n if (change.file.mimeType === GOOGLE_DRIVE_FOLDER_MIME_TYPE) {\n entries.delete(change.fileId);\n if (membership !== \"outside\") requiresFullReconciliation = true;\n else repairCandidates.add(change.fileId);\n continue;\n }\n if (membership === \"inside\") {\n entries.set(change.fileId, toInventoryEntry(change.file, input.source, input.maxFileBytes));\n } else if (membership === \"unknown\") {\n entries.delete(change.fileId);\n requiresFullReconciliation = true;\n } else {\n repairCandidates.add(change.fileId);\n }\n }\n if (repairCandidates.size > 0) {\n for (const fileId of repairCandidates) {\n if (entries.delete(fileId)) requiresFullReconciliation = true;\n }\n const observed = await input.observedExternalObjectIds([...repairCandidates]);\n if (observed.size > 0) requiresFullReconciliation = true;\n }\n if (page.nextPageToken) {\n pageToken = boundedToken(page.nextPageToken);\n continue;\n }\n if (!page.newStartPageToken) {\n throw new GoogleDriveChangesProtocolError(\"google_drive_changes_terminal_token_missing\");\n }\n budget.elapsedMs = initialBudget.elapsedMs + Math.max(0, now() - startedAt);\n return {\n status: \"complete\",\n stopReason: null,\n entries: [...entries.values()],\n checkpoint: null,\n newStartPageToken: boundedToken(page.newStartPageToken),\n requiresFullReconciliation,\n providerRequests: budget.providerRequests,\n elapsedMs: budget.elapsedMs,\n budget: { ...budget },\n hardLimitReached: false,\n };\n }\n}\n\nasync function isInsideSource(input: {\n file: GoogleDriveInventoryProviderItem;\n boundaryId: string;\n getFile: (fileId: string) => Promise<GoogleDriveInventoryProviderItem | null>;\n}): Promise<\"inside\" | \"outside\" | \"unknown\"> {\n if (input.file.id === input.boundaryId) return \"inside\";\n let parents = input.file.parents;\n const seen = new Set<string>([input.file.id]);\n for (let depth = 0; depth < MAX_ANCESTOR_DEPTH; depth += 1) {\n if (parents.includes(input.boundaryId)) return \"inside\";\n const next = parents.find((parent) => !seen.has(parent));\n if (!next) return \"outside\";\n seen.add(next);\n const parent = await input.getFile(next);\n if (!parent) return \"unknown\";\n parents = parent.parents;\n }\n return \"unknown\";\n}\n\nfunction toInventoryEntry(\n file: GoogleDriveInventoryProviderItem,\n source: GoogleDriveSelectedSource,\n maxFileBytes: number,\n): GoogleDriveInventoryEntry {\n return {\n externalObjectId: file.id,\n externalVersionId: file.version ?? file.modifiedTime ?? file.md5Checksum,\n sourceId: source.id,\n parentFolderId: file.parents[0] ?? source.id,\n driveId: file.driveId ?? source.driveId,\n title: file.name,\n mimeType: file.mimeType,\n modifiedTime: file.modifiedTime,\n createdTime: file.createdTime,\n sourceUri:\n file.webViewLink ?? `https://drive.google.com/open?id=${encodeURIComponent(file.id)}`,\n transfer: planGoogleDriveTransfer(file, maxFileBytes),\n };\n}\n\nfunction validatedCheckpoint(\n value: unknown,\n limits: { maxItems: number; maxProviderRequests: number; maxElapsedMs: number },\n): GoogleDriveChangesCheckpoint {\n if (!value || typeof value !== \"object\") {\n throw new Error(\"google_drive_changes_checkpoint_invalid\");\n }\n const checkpoint = value as Record<string, unknown>;\n const budget = checkpoint.budget;\n if (\n checkpoint.version !== 2 ||\n typeof checkpoint.requiresFullReconciliation !== \"boolean\" ||\n !Array.isArray(checkpoint.seenPageTokenHashes) ||\n checkpoint.seenPageTokenHashes.some((hash) => !/^[a-f0-9]{64}$/.test(hash)) ||\n new Set(checkpoint.seenPageTokenHashes).size !== checkpoint.seenPageTokenHashes.length ||\n checkpoint.seenPageTokenHashes.length > limits.maxProviderRequests ||\n !budget ||\n typeof budget !== \"object\"\n ) {\n throw new Error(\"google_drive_changes_checkpoint_invalid\");\n }\n if (typeof checkpoint.pageToken !== \"string\") {\n throw new Error(\"google_drive_changes_checkpoint_invalid\");\n }\n boundedToken(checkpoint.pageToken);\n const budgetRow = budget as Record<string, unknown>;\n for (const [key, maximum] of [\n [\"examinedItems\", limits.maxItems],\n [\"providerRequests\", limits.maxProviderRequests],\n [\"elapsedMs\", limits.maxElapsedMs],\n ] as const) {\n const budgetValue = budgetRow[key];\n if (\n !Number.isSafeInteger(budgetValue) ||\n Number(budgetValue) < 0 ||\n Number(budgetValue) > maximum\n ) {\n throw new Error(\"google_drive_changes_checkpoint_budget_invalid\");\n }\n }\n if (checkpoint.seenPageTokenHashes.length > Number(budgetRow.providerRequests)) {\n throw new Error(\"google_drive_changes_checkpoint_request_history_invalid\");\n }\n return value as GoogleDriveChangesCheckpoint;\n}\n\nfunction limitReason(\n budget: GoogleDriveSyncBudget,\n input: {\n maxItems: number;\n maxProviderRequests: number;\n maxElapsedMs: number;\n maxInvocationElapsedMs: number;\n },\n invocationElapsedMs: number,\n): GoogleDriveChangesStopReason | null {\n if (budget.examinedItems >= input.maxItems) return \"item_limit\";\n if (budget.providerRequests >= input.maxProviderRequests) return \"api_request_limit\";\n if (\n budget.elapsedMs >= input.maxElapsedMs ||\n invocationElapsedMs >= input.maxInvocationElapsedMs\n ) {\n return \"elapsed_time_limit\";\n }\n return null;\n}\n\nfunction emptyBudget(): GoogleDriveSyncBudget {\n return { examinedItems: 0, providerRequests: 0, elapsedMs: 0 };\n}\n\nfunction boundedToken(value: string): string {\n if (value.length < 1 || value.length > MAX_TOKEN_CHARS) {\n throw new Error(\"google_drive_changes_token_invalid\");\n }\n return value;\n}\n\nfunction boundedBoundaryId(value: string): string {\n if (value.length < 1 || value.length > MAX_BOUNDARY_ID_CHARS) {\n throw new Error(\"google_drive_changes_boundary_invalid\");\n }\n return value;\n}\n\nexport class GoogleDriveCursorInvalidError extends Error {\n budget: GoogleDriveSyncBudget | null = null;\n\n constructor() {\n super(\"google_drive_changes_cursor_invalid\");\n this.name = \"GoogleDriveCursorInvalidError\";\n }\n}\n\nexport class GoogleDriveChangesProtocolError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GoogleDriveChangesProtocolError\";\n }\n}\n","export {\n resolveRigProviderImageSelection,\n rigProviderImageSourceImage,\n settingsWithRigImage,\n settingsWithRigProviderImage,\n type RigProviderImageSelectionReason,\n} from \"@opengeni/core\";\n","import type { SessionEventType } from \"@opengeni/contracts\";\nimport { TURN_ACTIVITY_CANCELLATION_HEARTBEAT_INTERVAL_MS } from \"@opengeni/core\";\nimport type { AppendEventInput } from \"@opengeni/db\";\nimport { Context } from \"@temporalio/activity\";\n\n// Trailing-flush window. A burst of coalesced deltas followed by model silence\n// must not sit in `pending` unbounded — without a timer, flush fires only on\n// the NEXT push. Matched to the 33ms coalesce window so the client-visible\n// latency added by batching is bounded to ~one window (imperceptible, and far\n// cheaper than the per-delta DB round-trip it replaces).\nconst TRAILING_FLUSH_MS = 33;\nconst MAX_BATCH_EVENTS = 50;\n// Keep model ingestion independent from a slow durable append, but never let a\n// provider outrun storage without bound. At the high-water mark `push` waits for\n// the serialized drain before consuming more provider output.\nconst MAX_BUFFERED_EVENTS = 1_000;\n\n/** Optional metrics seam for the batcher. `onFlush` fires once per flush (on both\n * success and failure) with the coalesced event count and the flush duration, so\n * the worker can meter batch shape without the batcher knowing about Observability.\n * `now` is injectable for deterministic tests. Both are optional; absent ⇒ no-op. */\nexport type RuntimeBatcherOptions = {\n onFlush?: (info: { events: number; durationSeconds: number }) => void;\n now?: () => number;\n};\n\nexport function createRuntimeBatcher(\n flushEvents: (events: AppendEventInput[]) => Promise<void>,\n options: RuntimeBatcherOptions = {},\n) {\n const now = options.now ?? (() => performance.now());\n let pending: AppendEventInput[] = [];\n let lastFlush = Date.now();\n let trailingTimer: ReturnType<typeof setTimeout> | null = null;\n let activeBatchSize = 0;\n // One drain loop owns `flushEvents`, so DB-assigned sequence order always\n // matches push order. Ordinary deltas do not await this promise; structural\n // boundaries, explicit flushes, and the bounded high-water mark do.\n let drainPromise: Promise<void> | null = null;\n // A timer has no direct awaiter. Retain its failure so the next push or final\n // flush terminates the turn instead of silently losing streamed evidence.\n let flushFailed = false;\n let flushFailure: unknown;\n // The high-volume token deltas (agent.message.delta, agent.reasoning.delta,\n // sandbox.command.output.delta) are DELIBERATELY NOT here: they coalesce\n // under the 50-event / 33ms policy into one appendSessionEvents txn + one\n // publish per flush, instead of one DB round-trip per token. Only events that\n // must be delivered promptly stay structural (flush-immediately). PTY bytes\n // stay structural on purpose — an interactive terminal is useless batched\n // 33ms behind (P4.4).\n const structural = new Set<SessionEventType>([\n \"terminal.pty.output.delta\",\n \"agent.toolCall.created\",\n \"agent.toolCall.output\",\n \"agent.message.completed\",\n \"tool.auth_needed\",\n \"credential.auth_needed\",\n \"session.requiresAction\",\n \"turn.completed\",\n \"turn.failed\",\n \"turn.cancelled\",\n ]);\n return {\n push: async (event: { type: SessionEventType; payload: unknown }) => {\n throwIfFlushFailed();\n // Append BEFORE the structural check so a structural event's flush always\n // carries any pending deltas in order (same flush, order preserved).\n pending.push({ type: event.type, payload: event.payload });\n const elapsed = Date.now() - lastFlush;\n if (structural.has(event.type)) {\n await flush();\n return;\n }\n if (pending.length >= MAX_BATCH_EVENTS || elapsed >= TRAILING_FLUSH_MS) {\n // Start the serialized drain, but keep consuming provider deltas while\n // the append/publish round-trip is in flight. The active drain records\n // any failure for the next awaited boundary.\n void startDrain().catch(() => undefined);\n }\n if (activeBatchSize + pending.length >= MAX_BUFFERED_EVENTS) {\n await flush();\n return;\n }\n armTrailingTimer();\n },\n flush,\n };\n\n function armTrailingTimer() {\n if (trailingTimer !== null) {\n return;\n }\n trailingTimer = setTimeout(() => {\n trailingTimer = null;\n // A timer has no awaiter, so prevent an unhandled rejection. startDrain\n // retains the exact error and the next push/final flush rethrows it.\n void flush().catch(() => undefined);\n }, TRAILING_FLUSH_MS);\n if (\"unref\" in trailingTimer && typeof trailingTimer.unref === \"function\") {\n trailingTimer.unref();\n }\n }\n\n function clearTrailingTimer() {\n if (trailingTimer !== null) {\n clearTimeout(trailingTimer);\n trailingTimer = null;\n }\n }\n\n async function flush(): Promise<void> {\n throwIfFlushFailed();\n clearTrailingTimer();\n await startDrain();\n throwIfFlushFailed();\n }\n\n function startDrain(): Promise<void> {\n if (drainPromise) {\n return drainPromise;\n }\n if (flushFailed) {\n return Promise.reject(flushFailure);\n }\n if (pending.length === 0) {\n return Promise.resolve();\n }\n clearTrailingTimer();\n const running = (async () => {\n while (pending.length > 0) {\n const events = pending.splice(0, MAX_BATCH_EVENTS);\n activeBatchSize = events.length;\n lastFlush = Date.now();\n const startedAt = now();\n try {\n await flushEvents(events);\n } catch (error) {\n flushFailed = true;\n flushFailure = error;\n throw error;\n } finally {\n activeBatchSize = 0;\n if (options.onFlush) {\n try {\n options.onFlush({\n events: events.length,\n durationSeconds: Math.max(0, (now() - startedAt) / 1000),\n });\n } catch {\n // Metrics emission must never affect a flush.\n }\n }\n }\n }\n })();\n drainPromise = running.finally(() => {\n drainPromise = null;\n });\n return drainPromise;\n }\n\n function throwIfFlushFailed(): void {\n if (flushFailed) {\n throw flushFailure;\n }\n }\n}\n\nexport function currentActivityContext(): Context | null {\n try {\n return Context.current();\n } catch {\n return null;\n }\n}\n\nexport function startActivityHeartbeat(\n context: Context | null,\n details: Record<string, unknown>,\n schedule: typeof setInterval = setInterval,\n): ReturnType<typeof setInterval> | null {\n if (!context) {\n return null;\n }\n const timer = schedule(() => {\n context.heartbeat({ ...details, at: new Date().toISOString() });\n }, TURN_ACTIVITY_CANCELLATION_HEARTBEAT_INTERVAL_MS);\n if (\"unref\" in timer && typeof timer.unref === \"function\") {\n timer.unref();\n }\n return timer;\n}\n\nexport async function nextStreamEvent<T>(\n iterator: AsyncIterator<T>,\n context: Context | null,\n): Promise<IteratorResult<T>> {\n if (!context) {\n return await iterator.next();\n }\n const signal = context.cancellationSignal;\n if (signal.aborted) {\n throw signal.reason;\n }\n\n // Context.cancelled never settles for a normally completed activity. Racing\n // every token/event read against that lifetime promise leaves one losing\n // Promise reaction attached for every event until the Context itself dies.\n // Use the equivalent Temporal AbortSignal and remove each listener as soon as\n // the iterator wins, so a long stream retains at most its one pending read.\n return await new Promise<IteratorResult<T>>((resolve, reject) => {\n let settled = false;\n const settle = (complete: () => void) => {\n if (settled) return;\n settled = true;\n signal.removeEventListener(\"abort\", onAbort);\n complete();\n };\n const onAbort = () => settle(() => reject(signal.reason));\n\n signal.addEventListener(\"abort\", onAbort, { once: true });\n if (signal.aborted) {\n onAbort();\n return;\n }\n\n let next: PromiseLike<IteratorResult<T>>;\n try {\n next = iterator.next();\n } catch (error) {\n settle(() => reject(error));\n return;\n }\n void Promise.resolve(next).then(\n (result) => settle(() => resolve(result)),\n (error) => settle(() => reject(error)),\n );\n });\n}\n","import { sandboxLeaseTelemetryKey, type Observability } from \"@opengeni/observability\";\n\ntype SafeSnapshotError = {\n errorClass: \"SnapshotOperationError\";\n errorCode: \"snapshot_operation_failed\";\n status?: number;\n origin: \"sandbox-resume\" | \"worker-lifecycle\";\n causeName?: string;\n integrityCode?: string;\n providerErrorName?: string;\n providerGrpcCode?: number;\n providerHttpStatus?: number;\n providerRetryable?: boolean;\n};\n\nexport function safeSnapshotError(\n error: unknown,\n origin: SafeSnapshotError[\"origin\"] = \"sandbox-resume\",\n): SafeSnapshotError {\n const fields: SafeSnapshotError = {\n errorClass: \"SnapshotOperationError\",\n errorCode: \"snapshot_operation_failed\",\n origin,\n };\n try {\n if (error && typeof error === \"object\") {\n const candidate = error as {\n name?: unknown;\n code?: unknown;\n status?: unknown;\n statusCode?: unknown;\n };\n if (\n typeof candidate.name === \"string\" &&\n /^[A-Z][A-Za-z0-9]{2,62}Error$/u.test(candidate.name)\n ) {\n fields.causeName = candidate.name;\n }\n if (typeof candidate.code === \"string\" && /^[a-z0-9_]{1,64}$/u.test(candidate.code)) {\n fields.integrityCode = candidate.code;\n }\n const status = Number(candidate.status ?? candidate.statusCode);\n if (Number.isInteger(status) && status >= 100 && status <= 599) fields.status = status;\n }\n } catch {\n // Diagnostics must never replace the exact internal snapshot failure.\n }\n // The SDK wraps provider classification in details, not Error.cause. Never\n // project free-form messages, causes, request IDs or payloads. Read fields\n // independently so a hostile getter cannot hide other safe classifications.\n const read = (value: unknown, key: string): unknown => {\n try {\n return value && typeof value === \"object\" ? Reflect.get(value, key) : undefined;\n } catch {\n return undefined;\n }\n };\n const details = read(error, \"details\");\n const providerName = read(details, \"errorName\");\n if (\n typeof providerName === \"string\" &&\n [\n \"ClientError\",\n \"TimeoutError\",\n \"ConnectionError\",\n \"AuthError\",\n \"NotFoundError\",\n \"InvalidError\",\n \"RemoteError\",\n \"AbortError\",\n ].includes(providerName)\n )\n fields.providerErrorName = providerName;\n const grpcCode = read(details, \"errorCode\");\n if (\n providerName === \"ClientError\" &&\n typeof grpcCode === \"number\" &&\n Number.isInteger(grpcCode) &&\n grpcCode >= 0 &&\n grpcCode <= 16\n )\n fields.providerGrpcCode = grpcCode;\n for (const key of [\"status\", \"httpStatus\", \"responseStatus\"]) {\n const status = read(details, key);\n if (typeof status === \"number\" && Number.isInteger(status) && status >= 100 && status <= 599) {\n fields.providerHttpStatus = status;\n break;\n }\n }\n const retryable = read(error, \"retryable\");\n if (typeof retryable === \"boolean\") fields.providerRetryable = retryable;\n return fields;\n}\n\nexport function warnDrainSnapshotFailure(\n observability: Pick<Observability, \"warn\">,\n message: string,\n error: unknown,\n lease: { workspaceId?: string; sandboxGroupId: string; leaseEpoch: number },\n): void {\n try {\n observability.warn(message, {\n ...safeSnapshotError(error, \"worker-lifecycle\"),\n ...(lease.workspaceId\n ? { sandboxLeaseKey: sandboxLeaseTelemetryKey(lease.workspaceId, lease.sandboxGroupId) }\n : {}),\n leaseEpoch: lease.leaseEpoch,\n });\n } catch {\n // Logging cannot replace the provider failure or prevent claim release.\n }\n}\n","import { uploadWorkspaceArchiveSpool, type ObjectStorage } from \"@opengeni/storage\";\nimport { randomUUID } from \"node:crypto\";\nimport type { VerifiedHostWorkspaceArchive } from \"@opengeni/runtime/sandbox\";\nimport {\n parseWorkspaceArchiveObjectRef,\n workspaceArchiveObjectKey,\n type WorkspaceArchiveDescriptor,\n type WorkspaceArchiveObjectRef,\n} from \"@opengeni/contracts\";\n\nexport class WorkspaceArchiveObjectStorageRequiredError extends Error {\n readonly code = \"workspace_archive_object_storage_required\" as const;\n\n constructor(backend: string) {\n super(`${backend} workspace archives require object storage`);\n this.name = \"WorkspaceArchiveObjectStorageRequiredError\";\n }\n}\n\nexport function collectWorkspaceArchiveObjectKeys(\n resumeState: Record<string, unknown> | null | undefined,\n): Set<string> {\n const sessionState =\n resumeState?.sessionState && typeof resumeState.sessionState === \"object\"\n ? (resumeState.sessionState as Record<string, unknown>)\n : null;\n const keys = new Set<string>();\n for (const value of [sessionState?.workspaceArchiveRef, sessionState?.workspaceArchivePrevRef]) {\n const ref = parseWorkspaceArchiveObjectRef(value);\n if (ref) keys.add(ref.key);\n }\n return keys;\n}\n\nexport async function putTarWorkspaceArchiveObject(input: {\n objectStorage: ObjectStorage;\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n archive:\n | { bytes: Uint8Array; descriptor: WorkspaceArchiveDescriptor }\n | VerifiedHostWorkspaceArchive;\n}): Promise<WorkspaceArchiveObjectRef> {\n // Snapshot caller-owned metadata before any provider callback can mutate it.\n const descriptor = structuredClone(input.archive.descriptor);\n if (descriptor.version !== 1) {\n throw new Error(\"Object-storage workspace archives are portable tar only\");\n }\n const key = workspaceArchiveObjectKey({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n revision: descriptor.revision,\n uploadId: randomUUID(),\n });\n const archive = input.archive;\n if (\"spool\" in archive) {\n if (\n archive.spool.byteSize !== descriptor.archiveBytes ||\n archive.spool.sha256 !== descriptor.archiveSha256\n ) {\n throw new Error(\"Workspace archive spool does not match its verified descriptor\");\n }\n }\n const source =\n \"spool\" in archive\n ? archive.spool\n : {\n path: \"\",\n byteSize: archive.bytes.byteLength,\n sha256: descriptor.archiveSha256,\n async *open() {\n for (let offset = 0; offset < archive.bytes.length; offset += 1024 * 1024)\n yield archive.bytes.subarray(offset, offset + 1024 * 1024);\n },\n async dispose() {},\n };\n try {\n await uploadWorkspaceArchiveSpool(input.objectStorage, key, {\n ...source,\n byteSize: descriptor.archiveBytes,\n sha256: descriptor.archiveSha256,\n open: source.open.bind(source),\n });\n } catch (error) {\n // This fresh locator has never been offered to database publication. An\n // ambiguous provider upload can leave an orphan, never overwrite a retained\n // archive or justify deleting another attempt's object.\n await input.objectStorage.deleteObject(key).catch(() => undefined);\n throw error;\n }\n return {\n schema: \"sandbox_archive_object_v1\",\n key,\n sha256: descriptor.archiveSha256,\n bytes: descriptor.archiveBytes,\n backend: input.objectStorage.backend,\n };\n}\n\n/** The caller owns a fresh candidate returned by this module. A thrown or lost\n * database response is UNKNOWN: it may have committed, so never delete on catch.\n * Only the transaction's exact candidate disposition can authorize cleanup. */\nexport async function persistWorkspaceArchiveCandidate<\n T extends {\n wrote: boolean;\n candidateDisposition?: \"adopted\" | \"already_referenced\" | \"unused\";\n },\n>(input: {\n objectStorage?: ObjectStorage | null;\n ref?: WorkspaceArchiveObjectRef;\n persist: () => Promise<T>;\n}): Promise<T> {\n const objectStorage = input.objectStorage;\n const ref = input.ref ? { ...input.ref } : undefined;\n const result = await input.persist();\n if (objectStorage && ref && result.candidateDisposition === \"unused\") {\n await deleteUnpublishedWorkspaceArchiveObject(objectStorage, ref);\n }\n return result;\n}\n\nexport async function putVersion1TarArchiveOrInline(input: {\n backend: string;\n objectStorage?: ObjectStorage | null | undefined;\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n archive:\n | VerifiedHostWorkspaceArchive\n | {\n bytes: Uint8Array;\n descriptor: WorkspaceArchiveDescriptor;\n base64: string;\n };\n metrics?: {\n onWorkspaceArchiveObject?: (input: {\n outcome: \"put\" | \"put_failed\" | \"deleted_unpublished\";\n backend: string;\n }) => void;\n };\n}): Promise<{\n workspaceArchive?: string;\n workspaceArchiveRef?: WorkspaceArchiveObjectRef;\n}> {\n if (input.archive.descriptor.version !== 1) {\n if (\"spool\" in input.archive) throw new Error(\"Native snapshots cannot use a portable spool\");\n return { workspaceArchive: input.archive.base64 };\n }\n if (input.backend === \"opensandbox\" && !input.objectStorage) {\n throw new WorkspaceArchiveObjectStorageRequiredError(\"opensandbox\");\n }\n if (!input.objectStorage) {\n if (\"spool\" in input.archive)\n throw new WorkspaceArchiveObjectStorageRequiredError(input.backend);\n return { workspaceArchive: input.archive.base64 };\n }\n try {\n const workspaceArchiveRef = await putTarWorkspaceArchiveObject({\n objectStorage: input.objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: input.sandboxGroupId,\n archive: input.archive,\n });\n try {\n input.metrics?.onWorkspaceArchiveObject?.({\n outcome: \"put\",\n backend: input.objectStorage.backend,\n });\n } catch {\n /* metrics must not affect persist */\n }\n console.info(\"workspace archive object put\", {\n key: workspaceArchiveRef.key,\n bytes: workspaceArchiveRef.bytes,\n sha256: workspaceArchiveRef.sha256,\n });\n return { workspaceArchiveRef };\n } catch (error) {\n try {\n input.metrics?.onWorkspaceArchiveObject?.({\n outcome: \"put_failed\",\n backend: input.objectStorage.backend,\n });\n } catch {\n /* metrics must not affect persist */\n }\n throw error;\n }\n}\n\nexport async function deleteUnpublishedWorkspaceArchiveObject(\n objectStorage: ObjectStorage | null | undefined,\n ref: WorkspaceArchiveObjectRef | undefined,\n metrics?: {\n onWorkspaceArchiveObject?: (input: { outcome: \"deleted_unpublished\"; backend: string }) => void;\n },\n): Promise<void> {\n if (!objectStorage || !ref) return;\n try {\n await objectStorage.deleteObject(ref.key);\n try {\n metrics?.onWorkspaceArchiveObject?.({\n outcome: \"deleted_unpublished\",\n backend: objectStorage.backend,\n });\n } catch {\n /* metrics must not affect persist */\n }\n } catch {\n console.error(\"unpublished workspace archive object delete failed\", { key: ref.key });\n }\n}\n\nexport async function deleteWorkspaceArchiveObjectKeys(\n objectStorage: ObjectStorage,\n keys: Iterable<string>,\n): Promise<void> {\n for (const key of keys) {\n await objectStorage.deleteObject(key);\n }\n}\n","// apps/worker/src/sandbox-routing.ts — wire the agent-loop-free routing proxy\n// (`@opengeni/runtime` RoutingSandboxSession + makeActiveBackendResolver) to the\n// real DB pointer + the live NATS control plane for the WORKER TURN path (M7).\n//\n// The turn resumes its group box by id (resumeBoxForTurn) and injects it\n// NON-OWNED into the run. With hot-swap, the injected `session` must be the\n// STABLE routing proxy: the SDK binds to it ONCE and calls its\n// methods per tool call; the proxy re-reads `(active_sandbox_id, active_epoch)`\n// per op and dispatches to the currently-active backend (the group Modal box by\n// default, or a swap target — a sibling Modal box or a selfhosted machine).\n//\n// The glue here is the DB-coupled half the leaf cannot own (the leaf must stay\n// agent-loop-free + db-free): readActiveSandbox (the pointer), getSandbox (the\n// target lookup), and the selfhosted ControlRpc built over the events bus's NATS\n// request/reply connection.\n\nimport { sandboxLifecycleTransitionWaitMs, type Settings } from \"@opengeni/config\";\nimport {\n createProviderCommandRetainer,\n supervisedCommandProtocolReady,\n} from \"@opengeni/db/retained-provider-commands\";\nimport {\n adoptConnectedMachineSessionBackgroundCommand,\n adoptManagedSessionBackgroundCommand,\n advanceWorkspaceGenerationForRetainedProcess,\n retainedProviderCommandPersistence,\n advanceWorkspaceGeneration,\n getRetainedProcess,\n retainWorkspaceMutationProcess,\n retainedProcessSettlementIdentity,\n settleConnectedMachineSessionBackgroundCommand,\n settleRetainedProcess,\n verifyRetainedProcessMutationSettlement,\n verifyWorkspaceMutationSettlement,\n getSandbox,\n getLiveEnrollmentConnection,\n markWarmLeaseInstanceLost,\n readLease,\n readActiveSandbox,\n resolvePersonalMachineConnectionForAttempt,\n SandboxRetainedProcessPromotionFencedError,\n type Database,\n type EnrollmentRecord,\n type SandboxWorkspaceMutationAdmission,\n} from \"@opengeni/db\";\nimport { observeSessionBackgroundCommandCompletion } from \"@opengeni/db/session-background-commands\";\nimport { appendSessionCommandOutput } from \"@opengeni/db/session-command-output\";\nimport type { OpStreamOutputFrame } from \"@opengeni/runtime/sandbox\";\nimport type { EventBus } from \"@opengeni/events\";\nimport {\n buildSelfhostedBackendSession,\n ActiveBackendUnresolvableError,\n establishSandboxSessionFromEnvelope,\n isProviderSandboxGoneDuringRoutedOperation,\n isProviderSandboxNotFoundError,\n makeActiveBackendResolver,\n NatsControlRpc,\n NatsOpStreamTransport,\n RoutingBackendRecoveryRequiredError,\n RoutingSandboxSession,\n resolveModalCheckpointProviderBindingForSession,\n resolveConnectedMachineWorkspaceRoot,\n sandboxProviderInstanceIdFromEnvelope,\n sandboxBackendForSdkBackendId,\n selectBackend,\n verifySandboxExecReadiness,\n type ControlRpc,\n type EstablishedSandboxSession,\n type NatsRequestConnection,\n type RoutableBackendSession,\n type RoutableSandbox,\n type ResolvedActiveBackend,\n type RoutingMutationSettlementResult,\n type RoutingSandboxFirstOperationObserver,\n type RoutingSandboxOperationObserver,\n type RoutingSandboxCaptureWaitObserver,\n type RoutingSandboxWaitObservation,\n type RoutingRetainedProcess,\n type RoutingRetainedProcessTerminalProof,\n type SelfhostedOpObserver,\n type SelfhostedConnectionBinding,\n type SelfhostedRelayConfig,\n type OpStreamJournal,\n type SelfhostedOpStreamDeps,\n} from \"@opengeni/runtime\";\nimport { sandboxLeaseHolderIdForAttempt } from \"./sandbox-resume\";\n\nconst retainWorkspaceProviderCommand = createProviderCommandRetainer(\n retainWorkspaceMutationProcess,\n (error) => (error instanceof SandboxRetainedProcessPromotionFencedError ? error.process : null),\n);\n\ntype PersistableMutationAdmission = {\n admission: SandboxWorkspaceMutationAdmission;\n providerBinding: Awaited<\n ReturnType<typeof resolveModalCheckpointProviderBindingForSession>\n > | null;\n};\n\nfunction admittedCommandHandle(value: unknown): number | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n return (value as PersistableMutationAdmission).admission?.workspaceGeneration;\n}\n\nexport type RoutingWiringServices = {\n db: Database;\n settings: Settings;\n /** The events bus, for the selfhosted control-plane request/reply connection.\n * Optional: when absent (or NATS unconfigured) a selfhosted swap target\n * surfaces agent_offline on its first op rather than failing to build. */\n bus?: EventBus;\n /** The per-op observer wired into every selfhosted session this turn builds\n * (out-of-band telemetry — op metrics + machine.* events). Absent ⇒ no-op. */\n onOp?: SelfhostedOpObserver;\n /** Every physical routed provider call, across cloud and selfhosted homes. */\n onSandboxOperation?: RoutingSandboxOperationObserver;\n onSandboxCaptureWait?: RoutingSandboxCaptureWaitObserver;\n /** The op-stream durable-resume journal (the Temporal adaptation from\n * op-journal.ts): attach generation + settled-frontier persistence. Absent ⇒\n * the runtime defaults (generation \"1\", no persistence) — tests / non-turn\n * callers. Only consulted when op-stream is actually enabled for the turn. */\n opJournal?: OpStreamJournal;\n /** Durable lifecycle notification emitted only by the observer that wins the\n * exact warm-instance loss CAS. */\n onHomeSandboxLost?: (input: {\n sandboxGroupId: string;\n instanceId: string;\n leaseEpoch: number;\n }) => Promise<void>;\n /** Prepare and publish the worker's home handle. Rejection leaves the route\n * unpublished; replacement preparation must settle before the first tool op. */\n onHomeSandboxRebound?: (input: {\n established: EstablishedSandboxSession;\n leaseEpoch: number;\n }) => void | Promise<void>;\n /** Cancel bounded capture waits with the owning turn activity. */\n waitSignal?: AbortSignal;\n};\n\n/** Worker-turn routing may final-ack streamed command output, so it must always\n * carry the turn's durable frontier journal. Non-turn helpers may still omit it\n * through the broader service shape above. */\ntype TurnRoutingWiringServices = RoutingWiringServices & {\n opJournal: OpStreamJournal;\n};\n\nexport type RoutingWiringIds = {\n workspaceId: string;\n sessionId: string;\n resourceAccountId?: string;\n resourceSubjectId?: string;\n /** Frozen initiating-human authority for personal Connected Machine use.\n * Every routed operation reasserts this exact accepted attempt before the\n * control-plane connection is resolved. */\n personalMachineAttempt?: {\n accountId: string;\n subjectId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n };\n /** Canonical turn-attempt fence used to admit persistable-home mutations.\n * Omit outside a running worker attempt; mutation hooks then remain disabled. */\n workspaceMutationFence?: {\n accountId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n };\n homeLease?: {\n accountId: string;\n sandboxGroupId: string;\n leaseEpoch: number;\n instanceId: string;\n backend: string;\n };\n /**\n * The run's declared sandbox environment — the SAME object the turn passes to\n * `runtime.buildAgent`'s `sandboxEnvironment` and to `resumeBoxForTurn` (so the\n * group box's manifest carries it too). Threaded into a selfhosted swap target's\n * manifest so its `environment` EQUALS the turn's, making the SDK's per-turn\n * provided-session manifest-env delta empty (validateNoEnvironmentDelta).\n * WITHOUT this a pin-to-vm turn throws \"Live sandbox sessions cannot change\n * manifest environment variables.\" Optional → the resolver defaults to `{}`.\n */\n environment?: Record<string, string>;\n /** Attempt-local values projected only onto Connected Machine child execs. */\n transientExecEnvironment?: () => Readonly<Record<string, string>>;\n /**\n * Stage D machine-primary: PIN the already-established turn SelfhostedSession\n * (the `established` arg's session) for THIS machine pointer `(sandboxId, epoch)`\n * so the per-op resolver returns that SAME instance instead of building a fresh\n * one — the turn-start manifest write + per-op reads then hit ONE\n * SelfhostedSession/manifest. Set ONLY by the machine-primary establish branch\n * (where `established.session` is the SelfhostedSession bound to this pointer);\n * the group-box/swap path omits it (the default is the modal group box, and a\n * swap target is built fresh).\n */\n pinnedSelfhosted?: { sandboxId: string; epoch: number };\n /**\n * Whether the turn's `defaultBackend` IS the session's home (so the null pointer may\n * resolve to it). Defaults to TRUE (omitted). Set explicitly FALSE on a machine-primary\n * turn of a Modal-HOME session (pinned to a machine, no Modal group box established this\n * turn): the routing resolver's null branch then throws a typed `home_unavailable_this_turn`\n * error on a mid-turn clear-to-null instead of silently serving the pinned machine — the\n * detach's pointer commit stands and takes effect next turn. A genuine machine-HOME turn\n * (home IS the machine) passes true.\n */\n defaultIsHome?: boolean;\n};\n\n/** Map the deployment relay URL to the leaf's `SelfhostedRelayConfig` shape\n * (host/port/tls). M8 wires the real relay; until then a configured/placeholder\n * host yields a well-formed stream-URL shape behind `resolveExposedPort`. */\nexport function relayConfigFromSettings(settings: Settings): SelfhostedRelayConfig {\n const raw = settings.selfhostedRelayUrl?.trim();\n if (!raw) {\n return { host: \"relay.opengeni.local\", port: 443, tls: true };\n }\n try {\n const url = new URL(raw.includes(\"://\") ? raw : `wss://${raw}`);\n const tls = url.protocol === \"wss:\" || url.protocol === \"https:\";\n const port = url.port ? Number(url.port) : tls ? 443 : 80;\n return { host: url.hostname, port, tls };\n } catch {\n return { host: raw, port: 443, tls: true };\n }\n}\n\n/** The selfhosted CONTROL vs EXEC op deadlines for a turn, from settings. Control\n * ops (ping/fs/desktop/pty) stay on the short timeout so machine liveness is never\n * masked by a slow op; exec has its own setting and defaults to no duration wall.\n * Threaded into every turn-path session build + resolver. */\nexport function selfhostedTimeoutsFromSettings(settings: Settings): {\n timeoutMs: number;\n execTimeoutMs: number;\n} {\n return {\n timeoutMs: settings.sandboxSelfhostedControlTimeoutMs,\n execTimeoutMs: settings.sandboxSelfhostedExecTimeoutMs,\n };\n}\n\n/** The same split deadlines shaped for `makeActiveBackendResolver`'s dep names\n * (`selfhostedTimeoutMs` / `selfhostedExecTimeoutMs`), for a swap/pin target. */\nfunction selfhostedResolverTimeouts(settings: Settings): {\n selfhostedTimeoutMs: number;\n selfhostedExecTimeoutMs: number;\n} {\n const { timeoutMs, execTimeoutMs } = selfhostedTimeoutsFromSettings(settings);\n return {\n selfhostedTimeoutMs: timeoutMs,\n selfhostedExecTimeoutMs: execTimeoutMs,\n };\n}\n\ntype HomeRouteLeaseIdentity = {\n accountId: string;\n sandboxGroupId: string;\n backend: string;\n};\n\ntype HomeRouteResolutionIds = HomeRouteLeaseIdentity & {\n workspaceId: string;\n sessionId: string;\n};\n\ntype HomeRouteRecovery = \"pending\" | \"degraded\" | \"unrecoverable\" | \"superseded\";\n\n/**\n * Translate the durable lease/recovery state into the typed disposition the\n * routing proxy exposes when the home cannot be safely resumed. A route repair\n * must never fall back to the old in-memory provider handle when the lease is\n * warming, restoring, unverifiable, or otherwise inconsistent.\n */\nfunction homeRouteRecoveryDisposition(\n lease: Awaited<ReturnType<typeof readLease>>,\n): HomeRouteRecovery {\n if (!lease) return \"unrecoverable\";\n if (lease.liveness === \"warming\") return \"pending\";\n if (lease.liveness === \"draining\") return \"superseded\";\n if (\n lease.recovery.restore.status === \"pending\" ||\n lease.recovery.restore.status === \"restoring\" ||\n lease.recovery.restore.status === \"verifying\"\n ) {\n return \"pending\";\n }\n if (\n lease.recovery.restore.status === \"degraded\" ||\n lease.recovery.workspace.status === \"degraded\" ||\n lease.recovery.archive.status === \"unverified\" ||\n lease.recovery.archive.status === \"invalid\"\n ) {\n return \"degraded\";\n }\n return \"unrecoverable\";\n}\n\nfunction homeRouteRecoveryError(\n lease: Awaited<ReturnType<typeof readLease>>,\n fallbackEpoch: number,\n): RoutingBackendRecoveryRequiredError {\n return new RoutingBackendRecoveryRequiredError(\n \"resolve_home_backend\",\n lease?.leaseEpoch ?? fallbackEpoch,\n homeRouteRecoveryDisposition(lease),\n );\n}\n\nexport function providerIdentityFromResumeState(\n resumeState: Record<string, unknown>,\n): string | null {\n return sandboxProviderInstanceIdFromEnvelope(resumeState);\n}\n\n/**\n * Resolve the current durable home identity after the route epoch changes.\n *\n * Same-target attach/repair can replace the provider instance while a worker\n * turn still holds the stable routing proxy. The proxy must therefore resume\n * the lease's CURRENT identity, not reuse the object captured at turn start.\n * This seam is deliberately resume-only: lease election/rematerialization is\n * owned by the API/lease state machine, and a routed tool call must never create\n * a rival provider or replay an ambiguous mutation.\n */\nasync function resolveCurrentHomeBackend(\n services: RoutingWiringServices,\n ids: HomeRouteResolutionIds,\n established: EstablishedSandboxSession,\n): Promise<ResolvedActiveBackend> {\n const lease = await readLease(services.db, ids.workspaceId, ids.sandboxGroupId);\n const fallbackEpoch = lease?.leaseEpoch ?? 0;\n if (\n !lease ||\n lease.liveness !== \"warm\" ||\n lease.recovery.provider.status !== \"exists\" ||\n lease.instanceId === null ||\n lease.recovery.provider.instanceId !== lease.instanceId ||\n lease.recovery.workspace.status !== \"ready\" ||\n (lease.recovery.restore.status !== \"not_required\" && lease.recovery.restore.status !== \"ready\")\n ) {\n throw homeRouteRecoveryError(lease, fallbackEpoch);\n }\n\n // A route epoch can advance without a provider replacement. Reuse the exact\n // established handle only when its identity still equals the durable one.\n if (lease.instanceId === established.instanceId) {\n await services.onHomeSandboxRebound?.({\n established,\n leaseEpoch: lease.leaseEpoch,\n });\n return {\n session: established.session as RoutableBackendSession,\n sandboxId: null,\n kind: established.backendId,\n leaseEpoch: lease.leaseEpoch,\n providerInstanceId: lease.instanceId,\n };\n }\n\n const resumeState = lease.resumeState;\n const durableResumeBackend = lease.resumeBackendId ?? lease.backend ?? ids.backend;\n const resumeBackend = sandboxBackendForSdkBackendId(durableResumeBackend) ?? durableResumeBackend;\n if (\n !resumeState ||\n resumeBackend !== ids.backend ||\n providerIdentityFromResumeState(resumeState) !== lease.instanceId\n ) {\n throw homeRouteRecoveryError(lease, lease.leaseEpoch);\n }\n\n let rebound: EstablishedSandboxSession;\n try {\n rebound = await establishSandboxSessionFromEnvelope(services.settings, resumeState, {\n sessionId: ids.sessionId,\n recovery: \"resume-only\",\n backendOverride: resumeBackend as never,\n });\n // A resumed handle is not enough evidence for the route to use it. Keep the\n // same bounded readiness gate used before publishing a Modal lease warm.\n await verifySandboxExecReadiness(rebound);\n } catch (error) {\n if (!isProviderSandboxNotFoundError(resumeBackend, error)) {\n // The durable identity is present, but a transient resume/provider error\n // did not prove the box gone. Keep the lease untouched and make the next\n // independent route operation retry the resume; never use the old handle.\n throw new RoutingBackendRecoveryRequiredError(\n \"resolve_home_backend\",\n lease.leaseEpoch,\n \"pending\",\n );\n }\n const marked = await markWarmLeaseInstanceLost(services.db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: lease.leaseEpoch,\n expectedInstanceId: lease.instanceId,\n expectedBackend: lease.backend,\n diagnostic: \"provider_not_found_during_home_route_rebind\",\n });\n if (marked.status === \"marked\") {\n await services.onHomeSandboxLost?.({\n sandboxGroupId: ids.sandboxGroupId,\n instanceId: lease.instanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n }\n throw new RoutingBackendRecoveryRequiredError(\n \"resolve_home_backend\",\n marked.lease?.leaseEpoch ?? lease.leaseEpoch,\n marked.status === \"stale\" ? \"superseded\" : homeRouteRecoveryDisposition(marked.lease),\n );\n }\n\n // The provider identity must agree with the exact durable lease row before\n // any caller can publish or route through this rebound handle. A mismatch is\n // unverifiable local state, not permission to try the old handle.\n const reboundBackend = sandboxBackendForSdkBackendId(rebound.backendId) ?? rebound.backendId;\n if (rebound.instanceId !== lease.instanceId || reboundBackend !== resumeBackend) {\n throw homeRouteRecoveryError(lease, lease.leaseEpoch);\n }\n await services.onHomeSandboxRebound?.({\n established: rebound,\n leaseEpoch: lease.leaseEpoch,\n });\n // Keep the resolver's mutable home reference on the latest verified handle so\n // a later route epoch does not resume the same replacement again. This is only\n // a worker-side handle update; the SDK-facing RoutingSandboxSession remains the\n // stable object returned below and is never replaced.\n Object.assign(established, rebound);\n return {\n session: rebound.session as RoutableBackendSession,\n sandboxId: null,\n kind: rebound.backendId,\n leaseEpoch: lease.leaseEpoch,\n providerInstanceId: lease.instanceId,\n };\n}\n\nfunction beforePersistableHomeMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n home: { accountId: string; sandboxGroupId: string; backend: string } | undefined,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n onCaptureWait?: (observation: RoutingSandboxWaitObservation) => void;\n }) => Promise<PersistableMutationAdmission | null>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!home || !fence) return undefined;\n return async ({ op, backend, onCaptureWait }) => {\n // A connected-machine target is intentionally non-persistable: its writes\n // do not dirty the session home's archive. Exact home identity metadata is\n // present only on a verified durable home route.\n if (\n backend.sandboxId !== null ||\n backend.leaseEpoch === undefined ||\n backend.providerInstanceId === undefined\n ) {\n return null;\n }\n const providerBinding =\n home.backend === \"modal\"\n ? await resolveModalCheckpointProviderBindingForSession(services.settings, backend.session)\n : null;\n const admission = await advanceWorkspaceGeneration(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: fence.turnId,\n executionGeneration: fence.executionGeneration,\n attemptId: fence.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(fence.attemptId),\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n operation: op,\n captureWaitMs: sandboxLifecycleTransitionWaitMs(services.settings),\n ...(services.waitSignal ? { waitSignal: services.waitSignal } : {}),\n ...(onCaptureWait ? { onCaptureWait } : {}),\n });\n return { admission, providerBinding };\n };\n}\n\nfunction afterPersistableHomeMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n home: { accountId: string; sandboxGroupId: string; backend: string } | undefined,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n admission: unknown;\n outcome: \"resolved\" | \"rejected\" | \"outcome_unknown\";\n result?: unknown;\n retainedProcess?: RoutingRetainedProcess;\n }) => Promise<void | RoutingMutationSettlementResult>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!home || !fence) return undefined;\n return async ({ op, backend, admission, outcome, retainedProcess }) => {\n if (\n backend.sandboxId !== null ||\n backend.leaseEpoch === undefined ||\n backend.providerInstanceId === undefined ||\n !admission ||\n typeof admission !== \"object\"\n ) {\n return;\n }\n const boundAdmission = admission as Partial<PersistableMutationAdmission>;\n const exactAdmission = boundAdmission.admission;\n if (\n !exactAdmission ||\n typeof exactAdmission.id !== \"string\" ||\n typeof exactAdmission.workspaceGeneration !== \"number\" ||\n !(\"providerBinding\" in boundAdmission)\n ) {\n throw new Error(\"Persistable home mutation settlement lacked its bound admission\");\n }\n if ((outcome === \"resolved\" || outcome === \"outcome_unknown\") && retainedProcess) {\n try {\n await retainWorkspaceProviderCommand(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: retainedProcess.id,\n providerSessionId: retainedProcess.providerSessionId,\n ...(retainedProcess.providerCommand\n ? { providerCommand: retainedProcess.providerCommand }\n : {}),\n admissionId: exactAdmission.id,\n admittedWorkspaceGeneration: exactAdmission.workspaceGeneration,\n operation: op,\n providerBinding: boundAdmission.providerBinding ?? null,\n owner: {\n kind: \"turn\",\n turnId: fence.turnId,\n executionGeneration: fence.executionGeneration,\n attemptId: fence.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(fence.attemptId),\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n routeKind: exactAdmission.routeKind,\n routeTargetId: exactAdmission.routeTargetId,\n routeEpoch: exactAdmission.routeEpoch,\n },\n });\n } catch (error) {\n if (!(error instanceof SandboxRetainedProcessPromotionFencedError)) throw error;\n const durable = error.process;\n if (\n durable.id !== retainedProcess.id ||\n durable.providerSessionId !== retainedProcess.providerSessionId ||\n durable.sessionId !== ids.sessionId ||\n durable.sandboxGroupId !== home.sandboxGroupId ||\n durable.parentAdmissionId !== exactAdmission.id ||\n durable.leaseEpoch !== backend.leaseEpoch ||\n durable.providerInstanceId !== backend.providerInstanceId ||\n durable.routeKind !== exactAdmission.routeKind ||\n durable.routeTargetId !== exactAdmission.routeTargetId ||\n durable.routeEpoch !== exactAdmission.routeEpoch ||\n durable.state !== \"active\"\n ) {\n throw new Error(\"Durable retained-process promotion returned a mismatched identity\", {\n cause: error,\n });\n }\n return {\n status: \"retained_process_durable_output_rejected\",\n retainedProcess: {\n id: durable.id,\n providerSessionId: durable.providerSessionId,\n },\n };\n }\n return;\n }\n if (outcome === \"outcome_unknown\")\n throw new Error(\"Outcome-unknown command settlement requires its exact retained invocation\");\n await verifyWorkspaceMutationSettlement(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: fence.turnId,\n executionGeneration: fence.executionGeneration,\n attemptId: fence.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(fence.attemptId),\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n admission: exactAdmission,\n operation: op,\n outcome,\n });\n };\n}\n\nfunction beforeRetainedProcessMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n }) => Promise<SandboxWorkspaceMutationAdmission>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ op, process }) =>\n await advanceWorkspaceGenerationForRetainedProcess(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n operation: op,\n captureWaitMs: sandboxLifecycleTransitionWaitMs(services.settings),\n ...(services.waitSignal ? { waitSignal: services.waitSignal } : {}),\n });\n}\n\nfunction afterRetainedProcessMutation(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n op: string;\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n admission: unknown;\n outcome: \"resolved\" | \"rejected\";\n result?: unknown;\n }) => Promise<void>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ op, process, admission, outcome }) => {\n if (\n !admission ||\n typeof admission !== \"object\" ||\n typeof (admission as Partial<SandboxWorkspaceMutationAdmission>).id !== \"string\" ||\n typeof (admission as Partial<SandboxWorkspaceMutationAdmission>).workspaceGeneration !==\n \"number\"\n ) {\n throw new Error(\"Retained-process mutation settlement lacked its exact admission\");\n }\n await verifyRetainedProcessMutationSettlement(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n admission: admission as SandboxWorkspaceMutationAdmission,\n operation: op,\n outcome,\n });\n };\n}\n\nexport function captureConnectedCommandOutput(\n db: Database,\n ids: { accountId: string; workspaceId: string; sessionId: string },\n bus?: EventBus,\n) {\n return async (commandId: string, frames: OpStreamOutputFrame[]) => {\n for (const frame of frames) {\n const events = await appendSessionCommandOutput(db, {\n ...ids,\n commandId,\n chunkId: `op-frame:${frame.sequence}`,\n stream: frame.stream,\n chunk: frame.chunk,\n });\n if (events.length && bus)\n await bus.publish(ids.workspaceId, ids.sessionId, events).catch(() => undefined);\n }\n };\n}\n\nfunction captureRetainedProcessOutputForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n) {\n const accountId = ids.workspaceMutationFence?.accountId;\n if (!accountId) return undefined;\n return async ({\n process,\n chunkId,\n chunk,\n stream,\n streamFidelity,\n }: {\n process: RoutingRetainedProcess;\n chunkId: string;\n chunk: string;\n stream: \"stdout\" | \"stderr\";\n streamFidelity: \"separate\" | \"merged\";\n }) => {\n const events = await appendSessionCommandOutput(services.db, {\n accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: process.id,\n chunkId,\n chunk,\n stream,\n streamFidelity,\n });\n if (events.length && services.bus)\n await services.bus.publish(ids.workspaceId, ids.sessionId, events).catch(() => undefined);\n };\n}\n\nfunction observeRetainedProcessTerminalForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n) {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ process }: { process: RoutingRetainedProcess }) => {\n await observeSessionBackgroundCommandCompletion(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: process.id,\n });\n };\n}\n\nfunction settleRetainedProcessForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n proof: RoutingRetainedProcessTerminalProof;\n }) => Promise<void>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ backend, process, proof }) => {\n const durable = await getRetainedProcess(services.db, {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n });\n if (\n !durable ||\n durable.providerSessionId !== process.providerSessionId ||\n durable.providerBackend !== (sandboxBackendForSdkBackendId(backend.kind) ?? backend.kind) ||\n durable.providerInstanceId !== backend.providerInstanceId ||\n durable.leaseEpoch !== backend.leaseEpoch ||\n durable.routeKind !== (backend.sandboxId === null ? \"home\" : \"active\") ||\n durable.routeTargetId !== backend.sandboxId ||\n durable.routeEpoch !== backend.activeEpoch\n ) {\n throw new Error(\"Retained-process settlement lost its exact durable backend identity\");\n }\n const settlement = await settleRetainedProcess(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n expected: retainedProcessSettlementIdentity(durable),\n outcome: proof.outcome,\n exitCode: proof.exitCode,\n reason: proof.reason,\n idleGraceMs: services.settings.sandboxIdleGraceMs,\n });\n if (settlement.process.state === \"active\") {\n throw new Error(\"Retained-process settlement returned an active durable process\");\n }\n if (settlement.backgroundCommandEvents.length > 0 && services.bus) {\n await services.bus\n .publish(ids.workspaceId, ids.sessionId, settlement.backgroundCommandEvents)\n .catch(() => undefined);\n }\n };\n}\n\nfunction adoptRetainedProcessAsBackgroundCommandForTurn(\n services: RoutingWiringServices,\n ids: RoutingWiringIds,\n):\n | ((input: {\n backend: ResolvedActiveBackend;\n process: RoutingRetainedProcess;\n command?: string | undefined;\n }) => Promise<void>)\n | undefined {\n const fence = ids.workspaceMutationFence;\n if (!fence) return undefined;\n return async ({ backend, process, command }) => {\n const durable = await getRetainedProcess(services.db, {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n });\n if (\n !durable ||\n durable.providerSessionId !== process.providerSessionId ||\n durable.providerBackend !== (sandboxBackendForSdkBackendId(backend.kind) ?? backend.kind) ||\n durable.providerInstanceId !== backend.providerInstanceId ||\n durable.leaseEpoch !== backend.leaseEpoch ||\n durable.routeKind !== (backend.sandboxId === null ? \"home\" : \"active\") ||\n durable.routeTargetId !== backend.sandboxId ||\n durable.routeEpoch !== backend.activeEpoch\n ) {\n throw new Error(\"Background command adoption lost its exact retained-process identity\");\n }\n await adoptManagedSessionBackgroundCommand(services.db, {\n accountId: fence.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: fence.turnId,\n executionGeneration: fence.executionGeneration,\n attemptId: fence.attemptId,\n processId: process.id,\n expected: retainedProcessSettlementIdentity(durable),\n command: command ?? \"Background command\",\n });\n };\n}\n\n/** Build the selfhosted `ControlRpc` over the events bus's request/reply\n * connection. A null bus / unconfigured NATS yields a NatsControlRpc whose\n * connection factory returns null → agent_offline on every op (never a throw). */\nfunction controlRpcFactory(bus: EventBus | undefined): () => ControlRpc {\n return () =>\n new NatsControlRpc(async (): Promise<NatsRequestConnection | null> => {\n if (!bus) {\n return null;\n }\n return bus.getRequestConnection();\n });\n}\n\n/**\n * Wrap an established group-box session in a `RoutingSandboxSession` so a mid-turn\n * swap routes the NEXT tool call to the new active sandbox. Returns the SAME\n * established handle with its `session` replaced by the stable proxy; the\n * client/sessionState/instanceId/backendId are preserved (the lease still owns\n * the group box's lifecycle — the proxy is a routing veneer, not an owner).\n *\n * The DEFAULT pointer (active_sandbox_id == null) routes to the established group\n * session unchanged (backward-compat). A swap to a selfhosted machine routes to a\n * SelfhostedSession bound to the target's enrollment agentId, fenced under the\n * swap's active_epoch.\n */\nexport function wrapTurnBoxWithRouting(\n services: TurnRoutingWiringServices,\n ids: RoutingWiringIds,\n established: EstablishedSandboxSession,\n): EstablishedSandboxSession {\n const { db, settings, bus, onOp } = services;\n const backgroundCommandAccountId = ids.workspaceMutationFence?.accountId;\n const backgroundCommandAttempt = ids.workspaceMutationFence;\n const beforeMutation = beforePersistableHomeMutation(services, ids, ids.homeLease);\n const afterMutation = afterPersistableHomeMutation(services, ids, ids.homeLease);\n const beforeProcessMutation = beforeRetainedProcessMutation(services, ids);\n const afterProcessMutation = afterRetainedProcessMutation(services, ids);\n const settleProcess = settleRetainedProcessForTurn(services, ids);\n const adoptProcessAsBackgroundCommand = adoptRetainedProcessAsBackgroundCommandForTurn(\n services,\n ids,\n );\n const resolver = makeActiveBackendResolver({\n workspaceId: ids.workspaceId,\n defaultBackend: established.session as RoutableBackendSession,\n defaultKind: established.backendId,\n getSandbox: async (sandboxId): Promise<RoutableSandbox | null> => {\n const sandbox = await getSandbox(\n db,\n ids.resourceAccountId && ids.resourceSubjectId\n ? {\n accountId: ids.resourceAccountId,\n workspaceId: ids.workspaceId,\n subjectId: ids.resourceSubjectId,\n }\n : ids.workspaceId,\n sandboxId,\n );\n return sandbox\n ? {\n id: sandbox.id,\n workspaceId: sandbox.workspaceId,\n kind: sandbox.kind,\n name: sandbox.name,\n ...(sandbox.scope ? { scope: sandbox.scope } : {}),\n enrollmentId: sandbox.enrollmentId,\n }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n resolveSelfhostedConnection: async (sandbox) => {\n if (!sandbox.enrollmentId) return null;\n const enrollment = await resolveRoutedMachineConnection(db, ids, sandbox);\n return connectionBindingFor(services, enrollment);\n },\n relay: relayConfigFromSettings(settings),\n // A selfhosted swap target runs real commands too, so give it the same split\n // deadlines the machine-primary establish path uses (short control, long exec).\n ...selfhostedResolverTimeouts(settings),\n ...(onOp !== undefined ? { selfhostedOnOp: onOp } : {}),\n ...(backgroundCommandAccountId && backgroundCommandAttempt\n ? {\n selfhostedAdoptBackgroundCommand: async (command) => {\n const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: backgroundCommandAttempt.turnId,\n executionGeneration: backgroundCommandAttempt.executionGeneration,\n attemptId: backgroundCommandAttempt.attemptId,\n commandId: crypto.randomUUID(),\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n command: command.command,\n });\n return { commandId: adopted.id };\n },\n selfhostedSettleBackgroundCommand: async (command) => {\n const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: command.commandId,\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n outcome: command.outcome,\n exitCode: command.exitCode,\n reason: command.reason,\n ...(command.failure ? { failure: command.failure } : {}),\n });\n if (settlement && bus) {\n await bus\n .publish(ids.workspaceId, ids.sessionId, settlement.events)\n .catch(() => undefined);\n }\n },\n selfhostedCaptureBackgroundCommandOutput: captureConnectedCommandOutput(\n db,\n {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n },\n bus,\n ),\n }\n : {}),\n // The turn's declared environment → a selfhosted swap target's manifest, so the\n // SDK's per-turn manifest-env delta is empty (no \"cannot change manifest\n // environment variables\" throw when the turn pins to a vm). Mirrors the group\n // box, which is created WITH this same environment (resumeBoxForTurn).\n ...(ids.environment !== undefined ? { environment: ids.environment } : {}),\n ...(ids.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: ids.transientExecEnvironment }\n : {}),\n // Stage D machine-primary: pin THIS established SelfhostedSession for the machine\n // pointer so the resolver returns the SAME instance (no two-instance manifest\n // divergence). `established.session` is the SelfhostedSession the establish branch\n // bound to (sandboxId, epoch).\n ...(ids.pinnedSelfhosted\n ? {\n pinnedSelfhosted: {\n sandboxId: ids.pinnedSelfhosted.sandboxId,\n epoch: ids.pinnedSelfhosted.epoch,\n session: established.session as RoutableBackendSession,\n },\n }\n : {}),\n // A modal swap target in the turn path would need its own lease resume-by-id;\n // that is a future cross-group-box concern. Until then a modal swap target is\n // unresolvable (the swap tool validates liveness, so this only triggers if a\n // session points at a sibling modal box the turn cannot resume here) and the\n // op surfaces unresolvable — never a silent wrong-box landing.\n //\n // For a machine-primary turn of a Modal-HOME session (pinned to a machine, no\n // group box established this turn), a mid-turn clear-to-null must NOT fall back to\n // the pinned machine — passing defaultIsHome:false makes the null branch throw typed\n // `home_unavailable_this_turn` instead. Forward the explicit boolean (including false).\n ...(ids.defaultIsHome !== undefined ? { defaultIsHome: ids.defaultIsHome } : {}),\n ...(ids.homeLease\n ? {\n resolveDefaultBackend: () =>\n resolveCurrentHomeBackend(\n services,\n {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n accountId: ids.homeLease!.accountId,\n sandboxGroupId: ids.homeLease!.sandboxGroupId,\n backend: ids.homeLease!.backend,\n },\n established,\n ),\n }\n : {}),\n });\n\n const proxy = new RoutingSandboxSession({\n // Seed the DEFAULT backend (the established group box) at construction so\n // `session.state` is the real backend's state object BEFORE the first op. The\n // SDK reads `session.state.manifest` at turn START (and writes it back); an\n // empty `{}` there crashes serializeManifestEnvironment /\n // validateProvidedSessionManifestUpdate. This is byte-identical to what the\n // resolver returns for the default pointer (`activeSandboxId === null`).\n defaultResolved: {\n session: established.session as RoutableBackendSession,\n sandboxId: null,\n kind: established.backendId,\n ...(ids.homeLease\n ? {\n leaseEpoch: ids.homeLease.leaseEpoch,\n providerInstanceId: ids.homeLease.instanceId,\n }\n : {}),\n },\n readPointer: async () => {\n if (!routingEnabled(settings)) {\n return { activeSandboxId: null, activeEpoch: 0 };\n }\n const pointer = await readActiveSandbox(db, ids.workspaceId, ids.sessionId);\n return pointer ?? { activeSandboxId: null, activeEpoch: 0 };\n },\n resolveActiveBackend: resolver,\n ...(services.onSandboxOperation ? { onOperation: services.onSandboxOperation } : {}),\n ...(services.onSandboxCaptureWait ? { onCaptureWait: services.onSandboxCaptureWait } : {}),\n providerCommandHandle: admittedCommandHandle,\n providerSupervisionReady: async () =>\n settings.modalCommandSupervisionEnabled && (await supervisedCommandProtocolReady(db)),\n ...(ids.workspaceMutationFence\n ? {\n providerCommandPersistence: (process: RoutingRetainedProcess) =>\n retainedProviderCommandPersistence(\n db,\n {\n accountId: ids.workspaceMutationFence!.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n },\n services.bus\n ? (events) => services.bus!.publish(ids.workspaceId, ids.sessionId, events)\n : undefined,\n ),\n }\n : {}),\n ...(beforeMutation ? { beforeMutation } : {}),\n ...(afterMutation ? { afterMutation } : {}),\n ...(beforeProcessMutation ? { beforeProcessMutation } : {}),\n ...(afterProcessMutation ? { afterProcessMutation } : {}),\n ...(settleProcess ? { settleProcess } : {}),\n ...(ids.workspaceMutationFence\n ? { observeProcessTerminal: observeRetainedProcessTerminalForTurn(services, ids)! }\n : {}),\n ...(ids.workspaceMutationFence\n ? { captureProcessOutput: captureRetainedProcessOutputForTurn(services, ids)! }\n : {}),\n ...(adoptProcessAsBackgroundCommand ? { adoptProcessAsBackgroundCommand } : {}),\n ...(ids.homeLease\n ? {\n onDefaultBackendError: async ({\n error,\n backend,\n }: {\n error: unknown;\n backend: ResolvedActiveBackend;\n }) => {\n const home = ids.homeLease!;\n if (!isProviderSandboxGoneDuringRoutedOperation(home.backend, error)) return null;\n const expectedEpoch = backend.leaseEpoch ?? home.leaseEpoch;\n const expectedInstanceId = backend.providerInstanceId ?? home.instanceId;\n const marked = await markWarmLeaseInstanceLost(db, {\n accountId: home.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch,\n expectedInstanceId,\n expectedBackend: home.backend,\n diagnostic: \"provider_not_found_during_routed_operation\",\n });\n if (marked.status === \"marked\") {\n await services.onHomeSandboxLost?.({\n sandboxGroupId: home.sandboxGroupId,\n instanceId: expectedInstanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n }\n const lease = marked.lease;\n const restore = lease?.recovery.restore.status;\n return {\n leaseEpoch: lease?.leaseEpoch ?? expectedEpoch,\n recovery:\n marked.status === \"stale\"\n ? (\"superseded\" as const)\n : restore === \"pending\"\n ? (\"pending\" as const)\n : restore === \"degraded\"\n ? (\"degraded\" as const)\n : (\"unrecoverable\" as const),\n };\n },\n }\n : {}),\n });\n\n return { ...established, session: proxy };\n}\n\nexport function wrapLazyTurnBoxWithRouting(\n services: TurnRoutingWiringServices,\n ids: RoutingWiringIds,\n args: {\n client: EstablishedSandboxSession[\"client\"];\n backendId: string;\n agentDefaultManifest: unknown;\n provisioner: {\n get(): Promise<{\n established: EstablishedSandboxSession;\n leaseEpoch?: number;\n }>;\n };\n homeLeaseIdentity?: {\n accountId: string;\n sandboxGroupId: string;\n backend: string;\n };\n onFirstOperation?: RoutingSandboxFirstOperationObserver;\n },\n): EstablishedSandboxSession {\n const { db, settings, bus, onOp } = services;\n const backgroundCommandAccountId = ids.workspaceMutationFence?.accountId;\n const backgroundCommandAttempt = ids.workspaceMutationFence;\n const beforeMutation = beforePersistableHomeMutation(services, ids, args.homeLeaseIdentity);\n const afterMutation = afterPersistableHomeMutation(services, ids, args.homeLeaseIdentity);\n const beforeProcessMutation = beforeRetainedProcessMutation(services, ids);\n const afterProcessMutation = afterRetainedProcessMutation(services, ids);\n const settleProcess = settleRetainedProcessForTurn(services, ids);\n const adoptProcessAsBackgroundCommand = adoptRetainedProcessAsBackgroundCommandForTurn(\n services,\n ids,\n );\n const defaultBackend = sandboxBackendForSdkBackendId(args.backendId);\n const defaultSupportsPty = defaultBackend\n ? selectBackend(defaultBackend).capabilities.Terminal.pty\n : false;\n const syntheticSession: RoutableBackendSession = {\n state: { manifest: args.agentDefaultManifest },\n // The SDK binds shell tools synchronously before lazy provisioning. Preserve\n // the authoritative descriptor's PTY shape so a Modal home exposes\n // write_stdin on its first turn operation; the async cancellation transport\n // below still resolves the exact live route before executing a command.\n supportsPty: () => defaultSupportsPty,\n };\n const routedResolver = makeActiveBackendResolver({\n workspaceId: ids.workspaceId,\n defaultBackend: syntheticSession,\n defaultKind: \"unprovisioned\",\n getSandbox: async (sandboxId): Promise<RoutableSandbox | null> => {\n const sandbox = await getSandbox(\n db,\n ids.resourceAccountId && ids.resourceSubjectId\n ? {\n accountId: ids.resourceAccountId,\n workspaceId: ids.workspaceId,\n subjectId: ids.resourceSubjectId,\n }\n : ids.workspaceId,\n sandboxId,\n );\n return sandbox\n ? {\n id: sandbox.id,\n workspaceId: sandbox.workspaceId,\n kind: sandbox.kind,\n name: sandbox.name,\n ...(sandbox.scope ? { scope: sandbox.scope } : {}),\n enrollmentId: sandbox.enrollmentId,\n }\n : null;\n },\n controlRpcFactory: controlRpcFactory(bus),\n resolveSelfhostedConnection: async (sandbox) => {\n if (!sandbox.enrollmentId) return null;\n const enrollment = await resolveRoutedMachineConnection(db, ids, sandbox);\n return connectionBindingFor(services, enrollment);\n },\n relay: relayConfigFromSettings(settings),\n ...selfhostedResolverTimeouts(settings),\n ...(onOp !== undefined ? { selfhostedOnOp: onOp } : {}),\n ...(backgroundCommandAccountId && backgroundCommandAttempt\n ? {\n selfhostedAdoptBackgroundCommand: async (command) => {\n const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: backgroundCommandAttempt.turnId,\n executionGeneration: backgroundCommandAttempt.executionGeneration,\n attemptId: backgroundCommandAttempt.attemptId,\n commandId: crypto.randomUUID(),\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n command: command.command,\n });\n return { commandId: adopted.id };\n },\n selfhostedSettleBackgroundCommand: async (command) => {\n const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n commandId: command.commandId,\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n outcome: command.outcome,\n exitCode: command.exitCode,\n reason: command.reason,\n ...(command.failure ? { failure: command.failure } : {}),\n });\n if (settlement && bus) {\n await bus\n .publish(ids.workspaceId, ids.sessionId, settlement.events)\n .catch(() => undefined);\n }\n },\n selfhostedCaptureBackgroundCommandOutput: captureConnectedCommandOutput(\n db,\n {\n accountId: backgroundCommandAccountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n },\n bus,\n ),\n }\n : {}),\n ...(ids.environment !== undefined ? { environment: ids.environment } : {}),\n ...(ids.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: ids.transientExecEnvironment }\n : {}),\n });\n\n const proxy = new RoutingSandboxSession({\n // Before the first op the SDK reads `state.manifest`; the synthetic backend\n // points at agent.defaultManifest BY REFERENCE so the provided-session delta is\n // empty. The first default-pointer op resolves the real box through the\n // provisioner and `state` switches to that real backend by reference.\n defaultResolved: {\n session: syntheticSession,\n sandboxId: null,\n kind: \"unprovisioned\",\n },\n readPointer: async () => {\n const pointer = await readActiveSandbox(db, ids.workspaceId, ids.sessionId);\n return pointer ?? { activeSandboxId: null, activeEpoch: 0 };\n },\n resolveActiveBackend: async (pointer) => {\n if (pointer.activeSandboxId === null || !routingEnabled(settings)) {\n const provisioned = await args.provisioner.get();\n if (args.homeLeaseIdentity && provisioned.leaseEpoch !== undefined) {\n return resolveCurrentHomeBackend(\n services,\n {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n accountId: args.homeLeaseIdentity.accountId,\n sandboxGroupId: args.homeLeaseIdentity.sandboxGroupId,\n backend: args.homeLeaseIdentity.backend,\n },\n provisioned.established,\n );\n }\n return {\n session: provisioned.established.session as RoutableBackendSession,\n sandboxId: null,\n kind: provisioned.established.backendId,\n };\n }\n return routedResolver(pointer);\n },\n ...(services.onSandboxOperation ? { onOperation: services.onSandboxOperation } : {}),\n ...(services.onSandboxCaptureWait ? { onCaptureWait: services.onSandboxCaptureWait } : {}),\n ...(args.onFirstOperation ? { onFirstOperation: args.onFirstOperation } : {}),\n providerCommandHandle: admittedCommandHandle,\n providerSupervisionReady: async () =>\n settings.modalCommandSupervisionEnabled && (await supervisedCommandProtocolReady(db)),\n ...(ids.workspaceMutationFence\n ? {\n providerCommandPersistence: (process: RoutingRetainedProcess) =>\n retainedProviderCommandPersistence(\n db,\n {\n accountId: ids.workspaceMutationFence!.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n processId: process.id,\n },\n services.bus\n ? (events) => services.bus!.publish(ids.workspaceId, ids.sessionId, events)\n : undefined,\n ),\n }\n : {}),\n ...(beforeMutation ? { beforeMutation } : {}),\n ...(afterMutation ? { afterMutation } : {}),\n ...(beforeProcessMutation ? { beforeProcessMutation } : {}),\n ...(afterProcessMutation ? { afterProcessMutation } : {}),\n ...(settleProcess ? { settleProcess } : {}),\n ...(ids.workspaceMutationFence\n ? { observeProcessTerminal: observeRetainedProcessTerminalForTurn(services, ids)! }\n : {}),\n ...(ids.workspaceMutationFence\n ? { captureProcessOutput: captureRetainedProcessOutputForTurn(services, ids)! }\n : {}),\n ...(adoptProcessAsBackgroundCommand ? { adoptProcessAsBackgroundCommand } : {}),\n ...(args.homeLeaseIdentity\n ? {\n onDefaultBackendError: async ({\n error,\n backend,\n }: {\n error: unknown;\n backend: ResolvedActiveBackend;\n }) => {\n const home = args.homeLeaseIdentity!;\n if (!isProviderSandboxGoneDuringRoutedOperation(home.backend, error)) return null;\n if (backend.leaseEpoch === undefined || backend.providerInstanceId === undefined) {\n return null;\n }\n const marked = await markWarmLeaseInstanceLost(db, {\n accountId: home.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: home.sandboxGroupId,\n expectedEpoch: backend.leaseEpoch,\n expectedInstanceId: backend.providerInstanceId,\n expectedBackend: home.backend,\n diagnostic: \"provider_not_found_during_routed_operation\",\n });\n if (marked.status === \"marked\") {\n await services.onHomeSandboxLost?.({\n sandboxGroupId: home.sandboxGroupId,\n instanceId: backend.providerInstanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n }\n const lease = marked.lease;\n const restore = lease?.recovery.restore.status;\n return {\n leaseEpoch: lease?.leaseEpoch ?? backend.leaseEpoch,\n recovery:\n marked.status === \"stale\"\n ? (\"superseded\" as const)\n : restore === \"pending\"\n ? (\"pending\" as const)\n : restore === \"degraded\"\n ? (\"degraded\" as const)\n : (\"unrecoverable\" as const),\n };\n },\n }\n : {}),\n });\n\n return {\n client: args.client,\n session: proxy,\n sessionState: undefined,\n instanceId: \"unprovisioned\",\n backendId: args.backendId,\n };\n}\n\nexport type SelfhostedTurnSessionArgs = {\n accountId: string;\n /** Authorization/session workspace. */\n workspaceId: string;\n sessionId: string;\n /** Physical machine-origin workspace used in control-plane routing. */\n controlWorkspaceId?: string;\n /** Exact launching attempt required before a live Connected Machine command\n * can transfer into session ownership. Omitted by non-turn/test callers,\n * which therefore cannot yield a durable background command. */\n backgroundCommandAttempt?: Pick<\n NonNullable<RoutingWiringIds[\"workspaceMutationFence\"]>,\n \"turnId\" | \"executionGeneration\" | \"attemptId\"\n >;\n /** The target machine's enrollment id == the agent subject id. */\n agentId: string;\n /** Exact daemon process currently leased for the enrollment. */\n connectionInstanceId: string;\n /** Whether the target machine advertised Capabilities.op_stream in its latest\n * Hello. The runtime-side transport gate must still require the server flag. */\n opStream: boolean;\n /** Desired per-enrollment command policy and capability from the same live\n * enrollment snapshot as the process identity. */\n operationResourcePolicy: EnrollmentRecord[\"operationPolicy\"];\n operationResourcePolicySupported: boolean;\n operationCpuQuotaSupported: boolean;\n /** Feature advertisement only; refreshed by exact live admission for each operation. */\n transactionalFsWriteSupported?: boolean;\n /** The active pointer's epoch — the control-op fence echoed to the agent. */\n epoch: number;\n /** The run's declared sandbox environment (the SAME object fed to buildAgent +\n * the manifest), threaded so the SDK's per-turn provided-session env delta is\n * empty. */\n environment: Record<string, string>;\n /** Attempt-local values projected only onto this machine's child execs. */\n transientExecEnvironment?: () => Readonly<Record<string, string>>;\n /** The session working directory (per-session pointer). Null ⇒ workspace_root. */\n workingDir: string | null;\n /** Effective absolute host-native root frozen for this attempt. */\n workspaceRoot: string;\n /** Present only for a user-owned machine. Every provider operation rechecks\n * this frozen accepted-attempt authority immediately before dispatch. */\n personalMachineAttempt?: NonNullable<RoutingWiringIds[\"personalMachineAttempt\"]> & {\n sessionId: string;\n };\n};\n\n/**\n * Stage D machine-primary establish: bind the live SelfhostedSession for a turn\n * whose ACTIVE sandbox is a connected machine — WITHOUT establishing or leasing a\n * phantom Modal home box. Reuses the SAME relay + ControlRpc wiring `wrapTurnBoxWithRouting`\n * builds (so the turn session and a later swap target dial the machine identically),\n * and the SAME `buildSelfhostedBackendSession` factory the routing resolver uses\n * (one build shape). Returns an `EstablishedSandboxSession` whose:\n * - `client` is the SelfhostedSandboxClient (the OWNED-sandbox client the turn\n * injects; its `serializeSessionState` round-trips `{agentId}`);\n * - `session` is the live SelfhostedSession (the routing default + pin instance);\n * - `backendId` is \"selfhosted\" (drives recording's desktopCapableBackend gate +\n * the warm-rate keying) and `instanceId` is the enrollment/agent id.\n * No NATS round-trip happens here — `resume()` just re-addresses the subject — so a\n * headless/offline machine binds fine; its ops surface agent_offline lazily.\n */\n/**\n * The op-stream injection for a machine-primary turn: present iff the machine\n * advertised `Capabilities.op_stream` in its latest Hello AND the server flag\n * is on AND a bus exists to carry frames. The transport rides the SAME managed\n * NATS connection as the control rpc (the bus's op-stream accessor). A bus\n * without the accessor yields no stream; an unbounded exec then fails before\n * starting instead of silently degrading to request/reply. Swap targets resolve\n * the same enrollment capability through the injected backend-resolver seam.\n */\nfunction opStreamDepsFor(\n services: RoutingWiringServices,\n machineAdvertisesOpStream: boolean,\n): SelfhostedOpStreamDeps | undefined {\n const { settings, bus, opJournal } = services;\n if (!machineAdvertisesOpStream || settings.agentOpStreamEnabled !== true || !bus) {\n return undefined;\n }\n return {\n transport: new NatsOpStreamTransport(async () => bus.getOpStreamConnection?.() ?? null),\n ...(opJournal !== undefined ? { journal: opJournal } : {}),\n };\n}\n\n/** Project one enrollment read into one exact runtime route. Capability and\n * process identity must be taken from the same snapshot. */\nexport function connectionBindingFor(\n services: RoutingWiringServices,\n enrollment: EnrollmentRecord | null,\n): SelfhostedConnectionBinding | null {\n if (!enrollment?.connectionInstanceId) return null;\n const opStream = opStreamDepsFor(services, enrollment.opStream === true);\n return {\n workspaceId: enrollment.workspaceId,\n connectionInstanceId: enrollment.connectionInstanceId,\n workspaceRoot: enrollment.workspaceRoot,\n ...(opStream !== undefined ? { opStream } : {}),\n operationResourcePolicy: enrollment.operationPolicy,\n operationResourcePolicySupported: enrollment.agentCapabilities.operationResourcePolicy === true,\n operationCpuQuotaSupported: enrollment.agentCapabilities.operationCpuQuota === true,\n transactionalFsWriteSupported: enrollment.agentCapabilities.transactionalFsWrite === true,\n };\n}\n\n/** Personal-machine discovery is not execution authority. Recheck the frozen\n * initiating human, exact current attempt, immutable authorization snapshot,\n * and current visibility-keyed grant immediately before each routed operation\n * resolves a live control-plane connection. */\nasync function resolveRoutedMachineConnection(\n db: Database,\n ids: RoutingWiringIds,\n sandbox: RoutableSandbox,\n): Promise<EnrollmentRecord | null> {\n if (!sandbox.enrollmentId) return null;\n if (sandbox.scope !== \"user\") {\n return await getLiveEnrollmentConnection(\n db,\n ids.resourceAccountId && ids.resourceSubjectId\n ? {\n accountId: ids.resourceAccountId,\n workspaceId: ids.workspaceId,\n subjectId: ids.resourceSubjectId,\n }\n : sandbox.workspaceId,\n sandbox.enrollmentId,\n );\n }\n const authority = ids.personalMachineAttempt;\n if (!authority) return null;\n return await resolvePersonalMachineConnectionForAttempt(db, {\n accountId: authority.accountId,\n workspaceId: ids.workspaceId,\n subjectId: authority.subjectId,\n sessionId: ids.sessionId,\n turnId: authority.turnId,\n attemptId: authority.attemptId,\n executionGeneration: authority.executionGeneration,\n enrollmentId: sandbox.enrollmentId,\n requireActiveSandbox: true,\n });\n}\n\nexport async function establishSelfhostedTurnSession(\n services: RoutingWiringServices,\n args: SelfhostedTurnSessionArgs,\n): Promise<EstablishedSandboxSession> {\n const { db, settings, bus, onOp } = services;\n const { timeoutMs, execTimeoutMs } = selfhostedTimeoutsFromSettings(settings);\n const opStream = opStreamDepsFor(services, args.opStream);\n const { client, session } = await buildSelfhostedBackendSession({\n workspaceId: args.workspaceId,\n ...(args.controlWorkspaceId !== undefined\n ? { controlWorkspaceId: args.controlWorkspaceId }\n : {}),\n agentId: args.agentId,\n connectionInstanceId: args.connectionInstanceId,\n workspaceRoot: args.workspaceRoot,\n relay: relayConfigFromSettings(settings),\n controlRpcFactory: controlRpcFactory(bus),\n epoch: args.epoch,\n environment: args.environment,\n ...(args.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: args.transientExecEnvironment }\n : {}),\n // Give this turn's exec ops the long deadline (control ops stay short) so a real\n // command is not killed at the control wall.\n timeoutMs,\n execTimeoutMs,\n operationResourcePolicy: args.operationResourcePolicy,\n operationResourcePolicySupported: args.operationResourcePolicySupported,\n operationCpuQuotaSupported: args.operationCpuQuotaSupported,\n transactionalFsWriteSupported: args.transactionalFsWriteSupported === true,\n resolveOperationAdmission: async () => {\n const enrollment = args.personalMachineAttempt\n ? await resolvePersonalMachineConnectionForAttempt(db, {\n accountId: args.personalMachineAttempt.accountId,\n workspaceId: args.workspaceId,\n subjectId: args.personalMachineAttempt.subjectId,\n sessionId: args.personalMachineAttempt.sessionId,\n turnId: args.personalMachineAttempt.turnId,\n attemptId: args.personalMachineAttempt.attemptId,\n executionGeneration: args.personalMachineAttempt.executionGeneration,\n enrollmentId: args.agentId,\n requireActiveSandbox: true,\n })\n : await getLiveEnrollmentConnection(\n db,\n args.controlWorkspaceId ?? args.workspaceId,\n args.agentId,\n );\n const binding = connectionBindingFor(services, enrollment);\n if (!binding) return null;\n if (!binding.workspaceRoot) {\n throw new ActiveBackendUnresolvableError(\n \"workspace_root_unavailable\",\n \"Connected Machine no longer has a reported workspace root\",\n );\n }\n return {\n ...binding,\n workspaceRoot: resolveConnectedMachineWorkspaceRoot(binding.workspaceRoot, args.workingDir),\n };\n },\n ...(args.backgroundCommandAttempt\n ? {\n adoptBackgroundCommand: async (command) => {\n const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n turnId: args.backgroundCommandAttempt!.turnId,\n executionGeneration: args.backgroundCommandAttempt!.executionGeneration,\n attemptId: args.backgroundCommandAttempt!.attemptId,\n commandId: crypto.randomUUID(),\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n command: command.command,\n });\n return { commandId: adopted.id };\n },\n }\n : {}),\n captureBackgroundCommandOutput: captureConnectedCommandOutput(\n db,\n {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n },\n bus,\n ),\n settleBackgroundCommand: async (command) => {\n const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n commandId: command.commandId,\n controlWorkspaceId: command.controlWorkspaceId,\n enrollmentId: command.enrollmentId,\n connectionInstanceId: command.connectionInstanceId,\n opId: command.opId,\n outcome: command.outcome,\n exitCode: command.exitCode,\n reason: command.reason,\n ...(command.failure ? { failure: command.failure } : {}),\n });\n if (settlement && bus) {\n await bus\n .publish(args.workspaceId, args.sessionId, settlement.events)\n .catch(() => undefined);\n }\n },\n // Meter every control op (out-of-band telemetry) — no-op when unwired.\n ...(onOp !== undefined ? { onOp } : {}),\n // The streaming exec transport — present iff the machine advertised the\n // capability AND the server flag is on. Connected Machine exec fails closed\n // when it is absent; there is no request/reply downgrade.\n ...(opStream !== undefined ? { opStream } : {}),\n });\n return {\n client,\n session,\n sessionState: { agentId: args.agentId },\n instanceId: args.agentId,\n backendId: \"selfhosted\",\n };\n}\n\n/** Whether the routing proxy should wrap the turn box: the hot-swap feature is\n * gated by the selfhosted flag (the active pointer + swap tools are only\n * meaningful when selfhosted is enabled). With the flag off the established\n * group box is injected unchanged — byte-for-byte today. */\nexport function routingEnabled(settings: Settings): boolean {\n return settings.sandboxSelfhostedEnabled === true;\n}\n\n/** Whether the turn should defer sandbox provisioning to the first dispatched op\n * (the in-process single-flight provisioner behind the routing proxy's\n * resolveActiveBackend). Lazy is a property of the OWNED path only — the SDK never\n * creates/resumes an injected session, so we own establish timing — hence gated on\n * BOTH flags. With either off the turn provisions eagerly at turn start, exactly as\n * today. NB: under lazy the box is ALWAYS wrapped in the routing proxy (the proxy's\n * resolver IS the establish seam), independent of `routingEnabled`. */\nexport function lazyProvisionEnabled(settings: Settings): boolean {\n return settings.sandboxLazyProvisionEnabled === true && settings.sandboxOwnershipEnabled === true;\n}\n","// apps/worker/src/sandbox-resume.ts — the stateless per-turn resume-by-id path.\n//\n// This is the turn-side half of the P1.2 ownership inversion. There is NO class,\n// NO timers, NO per-session owner, NO Map<id, owner> — every turn is a\n// self-contained critical section run by ANY pool worker:\n//\n// 1. acquireLease (group-keyed) under the DB FOR UPDATE + cold->warming CAS —\n// the SOLE double-spawn guard (P1.1).\n// 2. The cold->warming winner may create/restore. Every attached caller is\n// resume-only; a missing provider box retires the exact warm epoch and\n// re-enters admission instead of creating a rival.\n// 3. (spawner) commitWarmingToWarm (the lease_epoch++ fence + folds the resume\n// envelope onto the lease). Optional desktop work is deliberately absent:\n// viewers and managed ComputerSession operations initialize it lazily.\n// 4. the caller injects {client, session, sessionState} NON-OWNED into the run\n// (the SDK never reaps it — the keystone), runs, then in `finally` calls the\n// returned `release()` and drops the in-memory handle. NEVER provider-delete\n// — the box rides the provider idle-timeout; the reaper (P1.3) stop()s it at\n// refcount 0.\n//\n// Liveness between turns is the lease refcount; there is no keepalive loop.\n\nimport {\n effectiveSandboxLifecycle,\n sandboxArchiveCaptureTimeoutMs,\n sandboxLifecycleTransitionWaitMs,\n sandboxWarmRateMicrosPerSecond,\n type Settings,\n} from \"@opengeni/config\";\nimport { randomUUID } from \"node:crypto\";\nimport { retainsHolderForWarmCapture } from \"./warm-capture-holder\";\nimport {\n acquireLease,\n adoptLegacyModalCheckpointArtifact,\n beginSandboxRematerialization,\n sessionHoldsFreshWorkspaceRecovery,\n claimWorkspaceArchiveCapture,\n commitWarmingToWarm,\n failSandboxRematerialization,\n failWarmingToCold,\n beginModalProviderCreate,\n getSandboxSessionEnvelope,\n heartbeatLeaseHolderStatus,\n markSandboxRestoreVerifying,\n markWarmLeaseInstanceLost,\n markSandboxCheckpointArtifactDeletePending,\n persistWarmSnapshot,\n readLease,\n registerSandboxCheckpointArtifact,\n recordWarmingSandboxCreated,\n reinstateTurnLeaseHolder,\n releaseWorkspaceArchiveCapture,\n releaseLeaseHolder,\n touchLeaseHolder,\n SandboxLeaseRecoveryBlockedError,\n SandboxLeaseSupersededError,\n SandboxLeaseTransitionError,\n type Database,\n type LeaseHolderKind,\n} from \"@opengeni/db\";\nimport {\n captureWorkspaceArchiveForStorage,\n disposeWorkspaceArchive,\n type VerifiedWorkspaceArchivePayload,\n describeLegacyNativeSnapshotArchive,\n inlineWorkspaceArchiveForRestore,\n MODAL_EXEC_READINESS_TIMEOUT_MS,\n SandboxExecReadinessError,\n WorkspaceArchiveIntegrityError,\n establishSandboxSessionFromEnvelope,\n isProviderSandboxNotFoundError,\n parseWorkspaceArchiveDescriptor,\n providerWorkspaceCapturePolicy,\n SandboxProviderContinuityUnavailableError,\n requirePersistableReplacementSandboxEnvelope,\n renewSandboxProviderExpiration,\n modalSessionMatchesCheckpointProviderBinding,\n resolveModalCheckpointProviderBindingForSession,\n serializeReplacementSandboxEnvelope,\n tagModalSandbox,\n terminateUnpublishedSandboxSession,\n verifySandboxExecReadiness,\n withoutSandboxProviderIdentity,\n type EstablishedSandboxSession,\n type RuntimeMetricsHooks,\n type SandboxReadinessReplacementOutcome,\n type WorkspaceArchiveDescriptor,\n} from \"@opengeni/runtime\";\nimport {\n downloadWorkspaceArchiveSpool,\n WorkspaceArchiveStorageError,\n type ObjectStorage,\n} from \"@opengeni/storage\";\nimport { sandboxLeaseTelemetryKey, type Observability } from \"@opengeni/observability\";\nimport { safeSnapshotError } from \"./sandbox-snapshot-diagnostics\";\nexport { safeSnapshotError } from \"./sandbox-snapshot-diagnostics\";\nimport { parseWorkspaceArchiveObjectRef } from \"@opengeni/contracts\";\nimport {\n persistWorkspaceArchiveCandidate,\n putVersion1TarArchiveOrInline,\n} from \"./sandbox-archive-storage\";\n\n// Re-exported for callers that just want the ack-kind union.\nexport type ResumeHolderKind = LeaseHolderKind;\n\n/**\n * The durable identity of a turn holding a shared sandbox lease.\n *\n * Temporal activity ids cannot satisfy this type: they are workflow-local\n * sequence numbers and collide across sessions that share a sandbox group.\n */\nexport type TurnSandboxLeaseHolderId = `turn-attempt:${string}`;\n\nexport function sandboxLeaseHolderIdForAttempt(attemptId: string): TurnSandboxLeaseHolderId {\n const normalized = attemptId.trim();\n if (!normalized) {\n throw new Error(\"Sandbox lease holder requires a turn attempt id\");\n }\n return `turn-attempt:${normalized}`;\n}\n\nexport function isRetryableDegradedRestore(restore: {\n status: string;\n retryable?: boolean;\n}): boolean {\n return restore.status === \"degraded\" && restore.retryable === true;\n}\n\n/** The minimal services surface resumeBoxForTurn needs. A subset of\n * ActivityServices so a test (and the API later) can pass a lean bag. */\nexport type SandboxResumeServices = {\n db: Database;\n settings: Settings;\n objectStorage?: ObjectStorage | null;\n\n logicalFallbackSettings?: Settings;\n sandboxMetrics?: RuntimeMetricsHooks;\n /** Structured logger for lifecycle decisions (holder release reasons). Falls\n * back to the console when a lean caller passes none. */\n observability?: Pick<Observability, \"info\" | \"warn\">;\n /** Test seam only: cadence of the private holder-liveness loop (default 10 s).\n * Production keeps the default; the dead-worker reap horizon assumes it. */\n holderLivenessIntervalMs?: number;\n /**\n * The logical turn-attempt lifetime, not merely the provider request lifetime.\n * Some provider SDK calls cannot be interrupted. Aborting this signal still\n * releases the durable holder immediately and fences any late provider result.\n */\n cancellationSignal?: AbortSignal;\n /** Test seam for the attached/resumed path. Production uses the one runtime\n * resume primitive; callers must not use this to create a replacement box. */\n establishAttachedSandbox?: typeof establishSandboxSessionFromEnvelope;\n /** Test seam for the bounded command-readiness proof performed before an\n * attached provider box is handed to the agent. */\n verifyAttachedSandboxReadiness?: (established: EstablishedSandboxSession) => Promise<void>;\n /** Test seam for the bounded command-readiness proof the elected spawner runs\n * on its freshly created box before publishing the lease warm. Production\n * uses {@link waitForSandboxExecReadiness} with the shared 60 s budget. */\n verifySpawnedSandboxReadiness?: (\n established: EstablishedSandboxSession,\n identity: { sandboxGroupId: string },\n ) => Promise<void>;\n /** Test seam for the jittered pause before the single fresh-box readiness\n * replacement. Production uses {@link freshSandboxReadinessReplacementDelayMs}.\n * It may be async so a test can observe the rolled-back lease in between. */\n freshSandboxReadinessReplacementDelayMs?: () => number | Promise<number>;\n /**\n * The turn attempt's fresh-box readiness replacement budget. The lazy\n * provisioner may call resumeBoxForTurn again after a typed lease\n * supersession, so the turn creates the budget once and shares it with every\n * call. Absent, the call gets its own single replacement.\n */\n freshSandboxReadinessReplacementBudget?: FreshSandboxReadinessReplacementBudget;\n /** Called only by the observer that wins the exact warm->cold loss CAS. */\n onSandboxLost?: (input: {\n sandboxGroupId: string;\n instanceId: string;\n leaseEpoch: number;\n }) => Promise<void>;\n};\n\nexport type ResumeBoxIds = {\n accountId: string;\n workspaceId: string;\n sandboxGroupId: string;\n /** The attributing session within the group (holders carry session_id for\n * disclosure/attribution). For a singleton group this == sandboxGroupId. */\n sessionId: string;\n /** The backend the box runs on (sessions.sandbox_backend). */\n backend: Settings[\"sandboxBackend\"];\n /** The OS axis (sessions.sandbox_os); default 'linux'. */\n os?: string;\n /**\n * The FULL environment the agent will declare for this run (the SAME object\n * passed to runtime.buildAgent's `sandboxEnvironment`). The box's manifest is\n * created with this environment so that when the SDK applies the agent's\n * manifest to this NON-OWNED provided session, the environments match exactly\n * and `validateNoEnvironmentDelta` finds an empty delta (otherwise it throws\n * \"Live sandbox sessions cannot change manifest environment variables\" and the\n * turn dies). Omitted → the leaf falls back to collectSandboxEnvironment(settings)\n * (the legacy default; only the resume/spawn-without-an-agent callers rely on it).\n */\n environment?: Record<string, string>;\n /**\n * IMAGE IS SHARED STATE (B3): the container image this run resolves (Modal image ref\n * / docker image). Threaded to acquireLease, which stamps it on the cold-create and\n * conflicts on a live box already running a DIFFERENT image (a solo holder requests\n * capture-and-drain rotation; N-holders throw SandboxImageConflictError). Omitted ->\n * image is not enforced (the selfhosted path never passes it; a legacy/null-image box\n * never conflicts).\n */\n image?: string;\n /** Deployment/workspace image pins apply only to new creates; an existing\n * group keeps its image. Omission preserves explicit image matching (B3). */\n imagePolicy?: \"require_match\" | \"new_creates_only\";\n /**\n * RIG IS SHARED STATE (M3): the frozen rig version this run rides. Threaded to\n * acquireLease, which stamps it on the cold-create and conflicts on a live box\n * set up under a DIFFERENT rig version (a solo holder requests capture-and-drain\n * rotation; N-holders throw SandboxRigConflictError). Omitted for a rig-less\n * session -> rig is never stamped or enforced (shares exactly as today).\n */\n rigVersionId?: string;\n};\n\n/** What resumeBoxForTurn returns: the live NON-OWNED session to inject, the\n * fence token (lease_epoch) it was established under, and a release function\n * the caller invokes in `finally` (idempotent delete-my-holder-row). */\nexport type ResumedTurnSandbox = {\n /** The live, externally-owned session — inject {client, session, sessionState}\n * NON-OWNED into runStream's `ownedSandbox`; the SDK never reaps it. */\n established: EstablishedSandboxSession;\n /** The lease_epoch this turn holds; the heartbeat/fence token. */\n leaseEpoch: number;\n /** Staged idempotent release. The ordinary form immediately prevents a\n * holder/timer leak. The quiesced form may be called later—even after the\n * ordinary form—to repair null-outcome admissions only after every exact\n * attempt-owned workspace writer has physically drained. NEVER stops the box. */\n release: (options?: { workspaceWritersQuiesced?: boolean }) => Promise<void>;\n};\n\n/**\n * Structural ownership of the provider boundary that failed while establishing\n * a logical sandbox provision. Object errors retain their identity and receive\n * an out-of-band stage; primitive thrown values use a typed wrapper. In both\n * cases the source diagnostic is unchanged and the stage is never guessed from\n * prose.\n */\nexport type SandboxProvisionFailureStage = \"create\" | \"resume\" | \"archive_recovery\";\n\nexport class SandboxProvisionStageError extends Error {\n readonly name = \"SandboxProvisionStageError\";\n\n constructor(\n public readonly stage: SandboxProvisionFailureStage,\n public readonly source: unknown,\n ) {\n super(source instanceof Error ? source.message : String(source), { cause: source });\n }\n}\n\nconst sandboxProvisionFailureStages = new WeakMap<object, SandboxProvisionFailureStage>();\n\nexport function sandboxProvisionFailureStage(error: unknown): SandboxProvisionFailureStage | null {\n if (!error || typeof error !== \"object\") return null;\n return (\n sandboxProvisionFailureStages.get(error) ??\n (error instanceof SandboxProvisionStageError ? error.stage : null)\n );\n}\n\nfunction sandboxProvisionStageError(stage: SandboxProvisionFailureStage, error: unknown): unknown {\n if (error && typeof error === \"object\") {\n sandboxProvisionFailureStages.set(error, stage);\n return error;\n }\n return new SandboxProvisionStageError(stage, error);\n}\n\nexport abstract class SandboxWarmingTimeoutError extends Error {\n abstract readonly code: \"sandbox_exec_readiness_timeout\" | \"sandbox_sibling_warming_timeout\";\n\n protected constructor(\n public readonly backend: string,\n public readonly timeoutMs: number,\n public readonly stage: \"exec_readiness\" | \"sibling_warming\",\n public readonly sandboxGroupId: string | null,\n public readonly instanceId: string | null,\n ) {\n const timeoutSeconds = Math.ceil(timeoutMs / 1000);\n const identity = [\n sandboxGroupId ? `group ${sandboxGroupId}` : null,\n instanceId ? `sandbox ${instanceId}` : null,\n ]\n .filter((part): part is string => part !== null)\n .join(\", \");\n const target = identity ? ` (${identity})` : \"\";\n super(\n stage === \"exec_readiness\"\n ? `Sandbox backend \"${backend}\"${target} did not become command-ready within ${timeoutSeconds}s after creation or restore.`\n : `Sandbox backend \"${backend}\"${target} did not finish warming within ${timeoutSeconds}s while waiting for the elected sandbox creator.`,\n );\n this.name = \"SandboxWarmingTimeoutError\";\n }\n}\n\nexport class SandboxExecReadinessTimeoutError extends SandboxWarmingTimeoutError {\n readonly code = \"sandbox_exec_readiness_timeout\" as const;\n\n constructor(\n backend: string,\n timeoutMs: number,\n identity: { sandboxGroupId?: string | null; instanceId?: string | null } = {},\n ) {\n super(\n backend,\n timeoutMs,\n \"exec_readiness\",\n identity.sandboxGroupId ?? null,\n identity.instanceId ?? null,\n );\n this.name = \"SandboxExecReadinessTimeoutError\";\n }\n}\n\nexport class SandboxSiblingWarmingTimeoutError extends SandboxWarmingTimeoutError {\n readonly code = \"sandbox_sibling_warming_timeout\" as const;\n\n constructor(\n backend: string,\n timeoutMs: number,\n identity: { sandboxGroupId: string; instanceId?: string | null },\n ) {\n super(\n backend,\n timeoutMs,\n \"sibling_warming\",\n identity.sandboxGroupId,\n identity.instanceId ?? null,\n );\n this.name = \"SandboxSiblingWarmingTimeoutError\";\n }\n}\n\n/**\n * Out-of-band proof attached to one exact {@link SandboxExecReadinessTimeoutError}\n * thrown by the elected spawner: the box that missed its readiness budget was\n * freshly created by this caller (not an attached, resumed, or provider-continuity\n * box), it was never published warm, the provider terminated it, and the holder\n * was released. Only such an error may be replaced by re-entering admission.\n */\nconst disposedUnreadyFreshSandboxErrors = new WeakSet<object>();\n\n/** True only for a spawner readiness timeout whose unready fresh box is proven gone. */\nexport function isReplaceableFreshSandboxReadinessTimeout(error: unknown): boolean {\n return (\n error instanceof SandboxExecReadinessTimeoutError &&\n disposedUnreadyFreshSandboxErrors.has(error)\n );\n}\n\n/**\n * A burst of simultaneous turn starts can leave many freshly created provider\n * boxes command-unready at once. The single replacement re-enters admission\n * after a jittered pause so the replacement creates do not re-synchronize into\n * the same burst. Bounded to [2 s, 10 s).\n */\nexport const FRESH_SANDBOX_READINESS_REPLACEMENT_BASE_DELAY_MS = 2_000;\nexport const FRESH_SANDBOX_READINESS_REPLACEMENT_JITTER_MS = 8_000;\n\nexport function freshSandboxReadinessReplacementDelayMs(\n random: () => number = Math.random,\n): number {\n const sample = random();\n const unit = Number.isFinite(sample) ? Math.min(Math.max(sample, 0), 1 - Number.EPSILON) : 0;\n return (\n FRESH_SANDBOX_READINESS_REPLACEMENT_BASE_DELAY_MS +\n Math.floor(unit * FRESH_SANDBOX_READINESS_REPLACEMENT_JITTER_MS)\n );\n}\n\n/** Replacements allowed per turn attempt, across every resumeBoxForTurn call. */\nexport const FRESH_SANDBOX_READINESS_REPLACEMENTS_PER_TURN_ATTEMPT = 1;\n\nexport type FreshSandboxReadinessReplacementBudget = { remaining: number };\n\nexport function createFreshSandboxReadinessReplacementBudget(): FreshSandboxReadinessReplacementBudget {\n return { remaining: FRESH_SANDBOX_READINESS_REPLACEMENTS_PER_TURN_ATTEMPT };\n}\n\nfunction recordFreshSandboxReadinessReplacement(\n metrics: RuntimeMetricsHooks | undefined,\n backend: string,\n outcome: SandboxReadinessReplacementOutcome,\n): void {\n try {\n metrics?.onSandboxReadinessReplacement?.({ backend, outcome });\n } catch {\n // Metrics emission must never affect sandbox recovery or error propagation.\n }\n}\n\nasync function sleepUnlessCancelled(ms: number, signal: AbortSignal | undefined): Promise<boolean> {\n if (signal?.aborted) return false;\n if (ms <= 0) return true;\n return await new Promise<boolean>((resolve) => {\n const onAbort = () => {\n clearTimeout(timer);\n resolve(false);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(true);\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\n/** The exact attached caller that won warm->cold after proving the provider\n * instance gone. It is a lease supersession (the same logical turn recovers),\n * plus the lost id needed for one durable observability event. */\nexport class SandboxLeaseInstanceLostError extends SandboxLeaseSupersededError {\n constructor(\n sandboxGroupId: string,\n leaseEpoch: number,\n public readonly lostInstanceId: string,\n ) {\n super(sandboxGroupId, leaseEpoch);\n this.name = \"SandboxLeaseInstanceLostError\";\n }\n}\n\n// Bounded poll while a sibling spawner is mid cold-restore. The wait budget is\n// user-facing and separate from the lease TTL heartbeat/reaper horizon.\nconst WARMING_POLL_INTERVAL_MS = 250;\n\nasync function sleep(ms: number): Promise<void> {\n await new Promise<void>((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * A remote provider may return a sandbox handle before its command router\n * accepts the first exec. The upstream session's yieldTimeMs starts only after\n * sandbox.exec() returns, so it cannot bound that initial RPC. Probe it before\n * publishing the lease as warm and enforce our own wall-clock deadline.\n */\nexport async function waitForSandboxExecReadiness(\n established: EstablishedSandboxSession,\n timeoutMs = MODAL_EXEC_READINESS_TIMEOUT_MS,\n identity: { sandboxGroupId?: string | null } = {},\n signal?: AbortSignal,\n): Promise<void> {\n try {\n await verifySandboxExecReadiness(established, timeoutMs, signal);\n } catch (error) {\n if (error instanceof SandboxExecReadinessError && error.code === \"exec_probe_timeout\") {\n throw new SandboxExecReadinessTimeoutError(established.backendId, timeoutMs, {\n sandboxGroupId: identity.sandboxGroupId ?? null,\n instanceId: established.instanceId,\n });\n }\n throw error;\n }\n}\n\nclass SnapshotTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`workspace snapshot timed out after ${timeoutMs}ms`);\n this.name = \"SnapshotTimeoutError\";\n }\n}\n\nexport async function waitForWarmSnapshot(\n snapshot: Promise<unknown>,\n timeoutMs: number,\n signal?: AbortSignal,\n): Promise<boolean> {\n if (signal?.aborted) return false;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let cancelListener: (() => void) | undefined;\n try {\n await Promise.race([\n snapshot,\n ...(signal\n ? [\n new Promise<never>((_resolve, reject) => {\n cancelListener = () =>\n reject(signal.reason ?? new Error(\"workspace snapshot wait cancelled\"));\n signal.addEventListener(\"abort\", cancelListener, { once: true });\n if (signal.aborted) cancelListener();\n }),\n ]\n : []),\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new SnapshotTimeoutError(timeoutMs)), timeoutMs);\n if (timeout && \"unref\" in timeout && typeof timeout.unref === \"function\") {\n timeout.unref();\n }\n }),\n ]);\n return true;\n } catch (error) {\n if (signal?.aborted) return false;\n if (error instanceof SnapshotTimeoutError) {\n console.error(\n \"mid-session workspace snapshot wait timed out (turn unaffected)\",\n safeSnapshotError(error),\n );\n return false;\n }\n return true;\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n if (cancelListener) signal?.removeEventListener(\"abort\", cancelListener);\n }\n}\n\nasync function resolveModalCheckpointBindingBeforeCapture(\n settings: SandboxResumeServices[\"settings\"],\n session: unknown,\n signal?: AbortSignal,\n): Promise<Awaited<ReturnType<typeof resolveModalCheckpointProviderBindingForSession>>> {\n if (signal?.aborted) {\n throw signal.reason ?? new Error(\"workspace snapshot identity lookup cancelled\");\n }\n const pending = resolveModalCheckpointProviderBindingForSession(settings, session);\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let cancelListener: (() => void) | undefined;\n try {\n return await Promise.race([\n pending,\n ...(signal\n ? [\n new Promise<never>((_resolve, reject) => {\n cancelListener = () =>\n reject(signal.reason ?? new Error(\"workspace snapshot identity lookup cancelled\"));\n signal.addEventListener(\"abort\", cancelListener, { once: true });\n if (signal.aborted) cancelListener();\n }),\n ]\n : []),\n new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(\n () => reject(new SnapshotTimeoutError(settings.sandboxSnapshotTimeoutMs)),\n settings.sandboxSnapshotTimeoutMs,\n );\n timeout.unref?.();\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n if (cancelListener) signal?.removeEventListener(\"abort\", cancelListener);\n }\n}\n\nasync function terminateEstablishedSandbox(\n established: EstablishedSandboxSession | null,\n): Promise<boolean> {\n if (!established) return true;\n try {\n await terminateUnpublishedSandboxSession(established);\n return true;\n } catch (error) {\n if (isProviderSandboxNotFoundError(established.backendId, error)) {\n return true;\n }\n // Best-effort cleanup. A provider-side orphan sweep is the backstop.\n return false;\n }\n}\n\nfunction recordSandboxWarmingTimeout(\n metrics: RuntimeMetricsHooks | undefined,\n error: unknown,\n): void {\n if (!(error instanceof SandboxWarmingTimeoutError)) {\n return;\n }\n try {\n metrics?.onSandboxWarmingTimeout?.({ backend: error.backend, stage: error.stage });\n } catch {\n // Metrics emission must never affect sandbox recovery or error propagation.\n }\n}\n\nfunction workspaceArchiveFieldsFromEnvelope(\n envelope: Record<string, unknown> | null | undefined,\n): Record<string, unknown> | null {\n const sessionState =\n envelope && typeof envelope.sessionState === \"object\" && envelope.sessionState !== null\n ? (envelope.sessionState as Record<string, unknown>)\n : null;\n const archive = sessionState?.workspaceArchive;\n const archiveRef = parseWorkspaceArchiveObjectRef(sessionState?.workspaceArchiveRef);\n const hasInline = typeof archive === \"string\" && archive.length > 0;\n if (!hasInline && !archiveRef) {\n return null;\n }\n const previous = sessionState?.workspaceArchivePrev;\n const previousRef = parseWorkspaceArchiveObjectRef(sessionState?.workspaceArchivePrevRef);\n const metadata = sessionState?.workspaceArchiveMeta;\n const previousMetadata = sessionState?.workspaceArchivePrevMeta;\n const capturedAt = sessionState?.workspaceArchiveAt;\n return {\n ...(hasInline && !archiveRef ? { workspaceArchive: archive } : {}),\n ...(archiveRef ? { workspaceArchiveRef: archiveRef } : {}),\n ...(metadata !== undefined ? { workspaceArchiveMeta: metadata } : {}),\n ...(typeof previous === \"string\" && previous.length > 0 && !previousRef\n ? { workspaceArchivePrev: previous }\n : {}),\n ...(previousRef ? { workspaceArchivePrevRef: previousRef } : {}),\n ...(previousMetadata !== undefined ? { workspaceArchivePrevMeta: previousMetadata } : {}),\n ...(typeof capturedAt === \"string\" && capturedAt.length > 0\n ? { workspaceArchiveAt: capturedAt }\n : {}),\n };\n}\n\nasync function materializeSpawnEnvelopeArchive(\n envelope: unknown,\n objectStorage: ObjectStorage | null | undefined,\n): Promise<unknown> {\n if (!envelope || typeof envelope !== \"object\") return envelope;\n const record = envelope as Record<string, unknown>;\n const sessionState =\n record.sessionState &&\n typeof record.sessionState === \"object\" &&\n !Array.isArray(record.sessionState)\n ? (record.sessionState as Record<string, unknown>)\n : null;\n if (!sessionState || !parseWorkspaceArchiveObjectRef(sessionState.workspaceArchiveRef)) {\n return envelope;\n }\n if (!objectStorage) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_storage_unavailable\",\n \"workspace archive object storage is not configured\",\n { retryable: true },\n );\n }\n const descriptor = parseWorkspaceArchiveDescriptor(sessionState.workspaceArchiveMeta);\n if (\n process.platform === \"linux\" &&\n descriptor?.version === 1 &&\n descriptor.workspace.projection === \"sdk_local_archive_v1\"\n ) {\n return envelope;\n }\n return {\n ...record,\n sessionState: await inlineWorkspaceArchiveForRestore(sessionState, (key) =>\n objectStorage.getObjectBytes(key),\n ),\n };\n}\n\nfunction legacyNativeArchiveFromEnvelope(envelope: Record<string, unknown> | null | undefined) {\n const sessionState =\n envelope && typeof envelope.sessionState === \"object\" && envelope.sessionState !== null\n ? (envelope.sessionState as Record<string, unknown>)\n : null;\n if (!sessionState) return null;\n const existing = parseWorkspaceArchiveDescriptor(sessionState.workspaceArchiveMeta);\n if (existing?.version === 2) return null;\n return describeLegacyNativeSnapshotArchive(\n sessionState.workspaceArchive,\n existing?.version === 1 ? Date.parse(existing.capturedAt) : Date.now(),\n );\n}\n\nexport type SandboxDeadlineRotationCheckpointResult = {\n /** The exact established epoch still carries a requested rotation and a\n * complete current-generation archive: the turn may abort orderly. */\n checkpointed: boolean;\n /** What the defense-in-depth holder step observed before the capture. */\n holder: Awaited<ReturnType<typeof reinstateTurnLeaseHolder>>[\"status\"];\n lease: Awaited<ReturnType<typeof readLease>>;\n};\n\n/**\n * The orderly provider-deadline rotation checkpoint for one running turn. The\n * turn-side lease heartbeat calls this once it observes a rotation-fenced lease\n * at its established epoch/instance; `checkpointed: true` licenses the\n * SandboxDeadlineRotationError abort that hands the same logical turn to the\n * cold successor.\n *\n * Defense in depth: the warm capture claim requires exactly this turn's holder.\n * If that holder was lost while the attempt is still the active writer (a stale\n * release, a reap race), `reinstateTurnLeaseHolder` puts it back under the\n * exact epoch/instance fence before the capture, so a lost holder cannot\n * silently disable the orderly abort and leave the reaper to terminate the box\n * under the running turn. Never captures when the epoch/instance changed.\n */\nexport async function persistSandboxDeadlineRotationCheckpoint(\n services: SandboxResumeServices,\n ids: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n sandboxGroupId: string;\n },\n session: unknown,\n expected: { leaseEpoch: number; instanceId: string },\n signal?: AbortSignal,\n): Promise<SandboxDeadlineRotationCheckpointResult> {\n const { db, settings } = services;\n // A cancelled attempt must never briefly regain its holder: its eager\n // cancellation listener may already have released it, and reinstating here\n // would pin the lease behind an attempt that is being torn down.\n if (signal?.aborted) {\n return { checkpointed: false, holder: \"attempt_fenced\", lease: null };\n }\n const reinstated = await reinstateTurnLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n sessionId: ids.sessionId,\n attemptId: ids.attemptId,\n expectedEpoch: expected.leaseEpoch,\n expectedInstanceId: expected.instanceId,\n leaseTtlMs: settings.sandboxLeaseTtlMs,\n });\n if (reinstated.status === \"reinstated\") {\n const message = \"sandbox rotation checkpoint reinstated the live turn holder\";\n const fields = {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n sandboxGroupId: ids.sandboxGroupId,\n leaseEpoch: expected.leaseEpoch,\n liveness: reinstated.lease.liveness,\n };\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n }\n if (reinstated.status !== \"present\" && reinstated.status !== \"reinstated\") {\n return { checkpointed: false, holder: reinstated.status, lease: null };\n }\n await maybePersistWarmWorkspaceSnapshot(\n services,\n ids,\n session,\n expected.leaseEpoch,\n signal,\n true,\n );\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n const checkpointed =\n lease?.leaseEpoch === expected.leaseEpoch &&\n lease.instanceId === expected.instanceId &&\n lease.rotationRequestedAt !== null &&\n lease.archiveComplete &&\n signal?.aborted !== true;\n return { checkpointed, holder: reinstated.status, lease };\n}\n\n/**\n * MID-SESSION /workspace snapshot (sandbox-file-persistence). The reaper's\n * drain-persist only protects boxes the reaper itself kills; anything else —\n * Modal's hard creation-time timeout catching a session busy past it, provider\n * OOM/infra death — loses everything since the last clean drain (staging\n * session e644e8a8, 2026-07-06: mid-turn box termination cost an unpushed\n * branch + 2 commits). While a turn HOLDS the live box, this folds a fresh\n * snapshot onto the lease through persistWarmSnapshot (the warm sibling of the\n * drain seam: epoch-fenced CAS + atomic throttle re-check) and GCs the\n * superseded snapshot image, bounding worst-case loss of ANY unclean box death\n * to sandboxSnapshotIntervalMs.\n *\n * Never throws and never blocks turn progress semantics: every failure path\n * returns false (the snapshot is protection, not a turn dependency). No-ops\n * when the interval is 0, the backend has no persistWorkspace (selfhosted =\n * the user's machine IS the persistence), or a snapshot newer than the\n * interval already rides the lease.\n */\nexport type WarmWorkspaceSnapshotPromise = Promise<boolean> & {\n /** Settles only after any provider capture continuation has published or\n * failed and released its exact workspace-capture admission. */\n readonly settled: Promise<void>;\n};\n\nexport function maybePersistWarmWorkspaceSnapshot(\n services: SandboxResumeServices,\n ids: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n sandboxGroupId: string;\n },\n session: unknown,\n leaseEpoch: number,\n signal?: AbortSignal,\n force = false,\n): WarmWorkspaceSnapshotPromise {\n let continuationRegistered = false;\n let resolvePhysicalSettlement: () => void = () => undefined;\n const physicalSettlement = new Promise<void>((resolve) => {\n resolvePhysicalSettlement = resolve;\n });\n const result = persistWarmWorkspaceSnapshot(\n services,\n ids,\n session,\n leaseEpoch,\n signal,\n force,\n (continuation) => {\n continuationRegistered = true;\n void continuation.then(resolvePhysicalSettlement, resolvePhysicalSettlement);\n },\n );\n void result.then(\n () => {\n if (!continuationRegistered) resolvePhysicalSettlement();\n },\n () => {\n if (!continuationRegistered) resolvePhysicalSettlement();\n },\n );\n return Object.assign(result, { settled: physicalSettlement });\n}\n\nasync function persistWarmWorkspaceSnapshot(\n services: SandboxResumeServices,\n ids: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n sandboxGroupId: string;\n },\n session: unknown,\n leaseEpoch: number,\n signal: AbortSignal | undefined,\n force: boolean,\n registerOwnedContinuation: (continuation: Promise<void>) => void,\n): Promise<boolean> {\n const { db, settings } = services;\n const warnSnapshotFailure = (message: string, error: unknown): void => {\n const fields = {\n ...safeSnapshotError(error),\n sandboxLeaseKey: sandboxLeaseTelemetryKey(ids.workspaceId, ids.sandboxGroupId),\n leaseEpoch,\n };\n try {\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n } catch {\n // Diagnostics cannot change provider settlement or capture-gate cleanup.\n }\n };\n const intervalMs = settings.sandboxSnapshotIntervalMs;\n if (intervalMs <= 0 && !force) {\n return false;\n }\n const persistable = session as {\n persistWorkspace?: () => Promise<Uint8Array | undefined>;\n persistWorkspaceTar?: () => Promise<Uint8Array | undefined>;\n backendId?: unknown;\n state?: {\n workspacePersistence?: unknown;\n providerState?: { workspacePersistence?: unknown };\n };\n };\n if (\n typeof persistable.persistWorkspace !== \"function\" &&\n typeof persistable.persistWorkspaceTar !== \"function\"\n ) {\n console.error(\"mid-session workspace snapshot skipped (no persist primitive)\", {\n backendId: typeof persistable.backendId === \"string\" ? persistable.backendId : null,\n });\n return false;\n }\n // Filesystem and directory snapshots create retained Images without\n // terminating the source Sandbox. (Modal's termination warning applies to\n // memory snapshots.) They are therefore the preferred warm-checkpoint path:\n // the durable capture gate pauses OpenGeni commands while the provider reads\n // the filesystem, then the same live instance continues serving the turn.\n const workspacePersistence =\n persistable.state?.workspacePersistence ??\n persistable.state?.providerState?.workspacePersistence;\n if (signal?.aborted) {\n return false;\n }\n try {\n // Resolve the provider namespace before taking the durable capture gate.\n // This work cannot pause or mutate the box, so keeping it outside the claim\n // minimizes the time that command admission must wait.\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n const canWarmCapture =\n lease?.liveness === \"warm\" && lease.instanceId !== null && lease.leaseEpoch === leaseEpoch;\n const canForceDrainingCapture =\n force === true &&\n lease?.liveness === \"draining\" &&\n lease.instanceId !== null &&\n lease.leaseEpoch === leaseEpoch;\n if (!lease || (!canWarmCapture && !canForceDrainingCapture)) {\n console.error(\"mid-session workspace snapshot skipped (lease not warm)\", {\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n liveness: lease?.liveness ?? null,\n leaseEpoch: lease?.leaseEpoch ?? null,\n hasInstance: lease?.instanceId !== null && lease?.instanceId !== undefined,\n });\n return false;\n }\n // A checkpoint of this exact mutation generation already protects every\n // settled operation admitted so far. Capturing it again cannot improve the\n // recovery point, even when the wall-clock interval has elapsed.\n if (lease.archiveComplete) {\n return false;\n }\n if (lease.instanceId === null) {\n return false;\n }\n const instanceId = lease.instanceId;\n const captureLiveness: \"warm\" | \"draining\" = canWarmCapture ? \"warm\" : \"draining\";\n const capturePolicy = providerWorkspaceCapturePolicy(lease.backend, session);\n if (!capturePolicy || capturePolicy.liveInstance !== \"preserved\") {\n console.error(\"mid-session workspace snapshot skipped (capture policy)\", {\n sandboxGroupId: ids.sandboxGroupId,\n backend: lease.backend,\n liveInstance: capturePolicy?.liveInstance ?? null,\n });\n return false;\n }\n const nativeModalPersistence =\n workspacePersistence === \"snapshot_filesystem\" ||\n workspacePersistence === \"snapshot_directory\";\n const checkpointBinding = nativeModalPersistence\n ? await resolveModalCheckpointBindingBeforeCapture(settings, persistable, signal)\n : null;\n if (signal?.aborted) return false;\n\n const captureId = randomUUID();\n const captureTimeoutMs = sandboxArchiveCaptureTimeoutMs(settings);\n const claimed = await claimWorkspaceArchiveCapture(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n captureId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: instanceId,\n liveness: captureLiveness,\n captureTimeoutMs,\n minIntervalMs: force ? 0 : intervalMs,\n providerReplaySafe: capturePolicy.takeover === \"same_request\",\n takeoverSafe: capturePolicy.takeover !== \"exclusive\",\n ...(captureLiveness === \"warm\"\n ? {\n warmAttempt: {\n sessionId: ids.sessionId,\n turnId: ids.turnId,\n attemptId: ids.attemptId,\n holderId: sandboxLeaseHolderIdForAttempt(ids.attemptId),\n },\n }\n : {}),\n });\n if (claimed.status !== \"claimed\") {\n // A scheduled interval not being due is normal, including after a failed\n // attempt. Do not turn every ten-second heartbeat into an error log.\n if (claimed.status === \"throttled\") return false;\n console.error(\"mid-session workspace snapshot skipped (capture claim)\", {\n sandboxGroupId: ids.sandboxGroupId,\n status: claimed.status,\n });\n return false;\n }\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n // Stamp WHEN this capture started: persistWarmSnapshot orders warm snapshots\n // by capture-initiation, not land time, so a slower heartbeat capture that\n // started earlier can never overwrite a fresher turn-end capture that landed\n // first (the bounded-wait race Bugbot flagged).\n const capturedAtMs = Date.now();\n const registerCandidate = async (\n archive: VerifiedWorkspaceArchivePayload,\n ): Promise<{ id: string } | null> => {\n if (\n archive.kind === \"host_spool\" ||\n archive.descriptor.version !== 2 ||\n (archive.descriptor.provider !== \"modal_snapshot_filesystem\" &&\n archive.descriptor.provider !== \"modal_snapshot_directory\")\n ) {\n return null;\n }\n if (!checkpointBinding) {\n throw new Error(\"Modal native snapshot has no exact session provider identity\");\n }\n return await registerSandboxCheckpointArtifact(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n sourceLeaseId: claimed.claim.leaseId,\n sourceLeaseEpoch: leaseEpoch,\n sourceInstanceId: instanceId,\n sourceWorkspaceGeneration: claimed.claim.workspaceGeneration,\n providerBindingKey: checkpointBinding.key,\n providerBinding: checkpointBinding.binding,\n workspaceArchive: archive.base64,\n workspaceArchiveMeta: archive.descriptor,\n });\n };\n\n const abandonCandidate = async (artifactId: string, reason: string): Promise<void> => {\n await markSandboxCheckpointArtifactDeletePending(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n artifactId,\n reason,\n }).catch(() => undefined);\n };\n // The SDK capture itself is not cancellable. Keep one owned continuation\n // alive through provider settlement even if this caller's bounded wait or\n // turn signal resolves first. Its finally block is the only normal release\n // of the exact admission gate; a late callback cannot release a successor.\n const captureAndPublish = (async (): Promise<boolean> => {\n const captureStarted = performance.now();\n let captureOutcome: \"completed\" | \"failed\" = \"failed\";\n let archive: VerifiedWorkspaceArchivePayload | undefined;\n let candidate: { id: string } | null = null;\n let publicationAttempted = false;\n try {\n archive = await captureWorkspaceArchiveForStorage(\n session,\n capturedAtMs,\n {\n requestId: claimed.claim.providerRequestId,\n strategy: capturePolicy.strategy,\n },\n Boolean(services.objectStorage),\n );\n candidate = await registerCandidate(archive);\n const archiveDescriptor = archive.descriptor;\n const published = await putVersion1TarArchiveOrInline({\n backend: lease.backend,\n objectStorage: services.objectStorage,\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n archive,\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n });\n publicationAttempted = true;\n const { wrote } = await persistWorkspaceArchiveCandidate({\n ...(services.objectStorage ? { objectStorage: services.objectStorage } : {}),\n ...(published.workspaceArchiveRef ? { ref: published.workspaceArchiveRef } : {}),\n persist: () =>\n persistWarmSnapshot(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n turnId: ids.turnId,\n attemptId: ids.attemptId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: instanceId,\n expectedWorkspaceGeneration: claimed.claim.workspaceGeneration,\n captureId,\n workspaceArchiveMeta: archiveDescriptor,\n ...published,\n checkpointArtifactId: candidate?.id ?? null,\n minIntervalMs: force ? 0 : intervalMs,\n capturedAtMs,\n }),\n });\n if (!wrote && candidate) {\n await abandonCandidate(candidate.id, \"snapshot_publication_fenced\");\n }\n if (wrote) captureOutcome = \"completed\";\n return wrote;\n } catch (error) {\n if (candidate && !publicationAttempted)\n await abandonCandidate(candidate.id, \"snapshot_capture_failed\");\n throw error;\n } finally {\n await disposeWorkspaceArchive(archive).catch(() => {\n console.warn(\"workspace archive spool cleanup failed\");\n });\n await releaseWorkspaceArchiveCapture(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n captureId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: instanceId,\n }).catch((error) => {\n captureOutcome = \"failed\";\n warnSnapshotFailure(\"mid-session workspace capture gate release failed\", error);\n });\n try {\n services.sandboxMetrics?.onWorkspaceCapture?.({\n backend: lease.backend,\n outcome: captureOutcome,\n durationSeconds: Math.max(0, performance.now() - captureStarted) / 1_000,\n });\n } catch {\n // A completed capture and released gate cannot depend on telemetry.\n }\n }\n })();\n const settled = captureAndPublish.then(\n (persisted) => ({ kind: \"settled\" as const, persisted }),\n (error) => {\n warnSnapshotFailure(\"mid-session workspace snapshot failed (turn unaffected)\", error);\n return { kind: \"settled\" as const, persisted: false };\n },\n );\n registerOwnedContinuation(settled.then(() => undefined));\n let cancelListener: (() => void) | undefined;\n const outcome = await Promise.race([\n settled,\n ...(signal\n ? [\n new Promise<{ kind: \"cancelled\" }>((resolve) => {\n cancelListener = () => resolve({ kind: \"cancelled\" });\n signal.addEventListener(\"abort\", cancelListener, { once: true });\n if (signal.aborted) cancelListener();\n }),\n ]\n : []),\n new Promise<{ kind: \"timed_out\" }>((resolve) => {\n timeout = setTimeout(\n () => resolve({ kind: \"timed_out\" }),\n settings.sandboxSnapshotTimeoutMs,\n );\n }),\n ]).finally(() => {\n if (timeout) clearTimeout(timeout);\n if (cancelListener) signal?.removeEventListener(\"abort\", cancelListener);\n });\n // A timed-out/cancelled local waiter deliberately leaves the already-owned\n // provider continuation running; `settled` has both rejection handling and\n // exact claim cleanup, so it cannot leak an unhandled promise or artifact.\n return outcome.kind === \"settled\" ? outcome.persisted : false;\n } catch (error) {\n // A failed snapshot does not fail the turn. Physical captures can still\n // fence commands until their exact gate settles; the caller timeout is not\n // permission to release that gate. The next eligible tick can retry.\n warnSnapshotFailure(\"mid-session workspace snapshot failed (turn unaffected)\", error);\n return false;\n }\n}\n\n/**\n * Resume the one box for a single turn (or any worker-side resume op). Returns\n * the live non-owned session + the fence epoch + a release fn. The CALLER owns\n * the lifecycle: inject non-owned, run, then `await release()` and drop the\n * handle in `finally`.\n *\n * holderId is the globally unique durable turn-attempt id. It must not be a\n * Temporal activity id, because activity ids are only workflow-local and\n * collide when sibling sessions share one sandbox group.\n *\n * A freshly created box that misses its bounded command-readiness budget is\n * replaced at most once per turn attempt (the budget is shared by every call\n * the turn's provisioner makes). The first establish has already terminated that exact\n * unpublished box, rolled its exact warming epoch back to cold (advancing the\n * epoch), and released its holder, so the replacement is an ordinary new\n * admission: it re-runs the cold->warming CAS, persists its own provider\n * instance before readiness, and may instead attach to a sibling that won the\n * CAS first. Nothing model- or tool-visible ran on the discarded box, so no\n * side effect is replayed. A second readiness timeout fails the turn exactly\n * as before; attached/resumed boxes and unconfirmed terminations never\n * replace.\n */\nexport async function resumeBoxForTurn(\n services: SandboxResumeServices,\n ids: ResumeBoxIds,\n kind: \"turn\",\n holderId: TurnSandboxLeaseHolderId,\n): Promise<ResumedTurnSandbox> {\n try {\n return await resumeBoxForTurnOnce(services, ids, kind, holderId);\n } catch (error) {\n if (!isReplaceableFreshSandboxReadinessTimeout(error)) throw error;\n const readiness = error as SandboxExecReadinessTimeoutError;\n const warn = (message: string, fields: Parameters<Observability[\"warn\"]>[1]) => {\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n };\n const identity = {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n sandboxGroupId: ids.sandboxGroupId,\n backend: readiness.backend,\n instanceId: readiness.instanceId,\n readinessTimeoutMs: readiness.timeoutMs,\n };\n const budget =\n services.freshSandboxReadinessReplacementBudget ??\n createFreshSandboxReadinessReplacementBudget();\n if (budget.remaining <= 0) {\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n \"budget_spent\",\n );\n warn(\n \"sandbox command-readiness timed out on a fresh box; this turn attempt already used its replacement\",\n identity,\n );\n throw error;\n }\n budget.remaining -= 1;\n const delayMs = await (\n services.freshSandboxReadinessReplacementDelayMs ?? freshSandboxReadinessReplacementDelayMs\n )();\n warn(\"sandbox command-readiness timed out on a fresh box; replacing it once after jitter\", {\n ...identity,\n replacementDelayMs: delayMs,\n });\n if (!(await sleepUnlessCancelled(delayMs, services.cancellationSignal))) {\n // Cancellation owns the turn boundary; surface the original typed\n // readiness failure rather than starting a replacement.\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n \"cancelled\",\n );\n throw error;\n }\n try {\n const replaced = await resumeBoxForTurnOnce(services, ids, kind, holderId);\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n \"replaced\",\n );\n return replaced;\n } catch (replacementError) {\n recordFreshSandboxReadinessReplacement(\n services.sandboxMetrics,\n readiness.backend,\n services.cancellationSignal?.aborted\n ? \"cancelled\"\n : replacementError instanceof SandboxExecReadinessTimeoutError\n ? \"failed_again\"\n : \"replacement_failed\",\n );\n throw replacementError;\n }\n }\n}\n\nasync function resumeBoxForTurnOnce(\n services: SandboxResumeServices,\n ids: ResumeBoxIds,\n kind: \"turn\",\n holderId: TurnSandboxLeaseHolderId,\n): Promise<ResumedTurnSandbox> {\n const { db, settings } = services;\n const os = ids.os ?? \"linux\";\n const leaseTtlMs = settings.sandboxLeaseTtlMs;\n const cancellationSignal = services.cancellationSignal;\n\n // The release closure is created eagerly so the caller can always release in\n // finally, even if establish/commit throws after the holder was registered.\n // It is also bound directly to the logical attempt signal: an uninterruptible\n // provider promise must never keep its private warmup timer and holder alive\n // after Temporal has abandoned the activity.\n let releaseStarted = false;\n let holderRelease: Promise<void> | null = null;\n let quiescedRelease: Promise<void> | null = null;\n let holderLivenessTimer: ReturnType<typeof setInterval> | undefined;\n let cancellationListener: (() => void) | undefined;\n const release = (options?: { workspaceWritersQuiesced?: boolean }): Promise<void> => {\n const writersQuiesced = options?.workspaceWritersQuiesced === true;\n // First invocation synchronously closes every in-memory liveness source.\n // A later quiesced invocation is still allowed to enter the DB: cancellation\n // commonly wins this race and drops the holder before the physical writer\n // drain can prove that abandoned turn admissions are safe to settle.\n if (!releaseStarted) {\n releaseStarted = true;\n if (cancellationListener) {\n cancellationSignal?.removeEventListener(\"abort\", cancellationListener);\n cancellationListener = undefined;\n }\n if (holderLivenessTimer) {\n clearInterval(holderLivenessTimer);\n holderLivenessTimer = undefined;\n }\n }\n const persistRelease = async (workspaceWritersQuiesced: boolean): Promise<void> => {\n await releaseLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n idleGraceMs: settings.sandboxIdleGraceMs,\n ...(workspaceWritersQuiesced ? { workspaceWritersQuiesced: true } : {}),\n });\n };\n if (writersQuiesced) {\n if (!quiescedRelease) {\n // Serialize behind an eager cancellation release when one exists. Its\n // failure is intentionally swallowed only as a predecessor: this exact\n // idempotent proof-bearing call retries both holder deletion and\n // admission settlement in one transaction.\n const predecessor = holderRelease;\n const attempt = (predecessor ? predecessor.catch(() => undefined) : Promise.resolve()).then(\n async () => await persistRelease(true),\n );\n const tracked = attempt.catch((error) => {\n if (quiescedRelease === tracked) quiescedRelease = null;\n throw error;\n });\n quiescedRelease = tracked;\n holderRelease = tracked;\n }\n return quiescedRelease;\n }\n if (!holderRelease) {\n const attempt = persistRelease(false);\n const tracked = attempt.catch((error) => {\n if (holderRelease === tracked) holderRelease = null;\n throw error;\n });\n holderRelease = tracked;\n }\n return holderRelease;\n };\n const cancellationError = (): Error =>\n cancellationSignal?.reason instanceof Error\n ? cancellationSignal.reason\n : new Error(\"Sandbox resume was cancelled with its owning turn attempt\");\n const throwIfReleasedOrCancelled = (): void => {\n if (releaseStarted || cancellationSignal?.aborted) {\n throw cancellationError();\n }\n };\n\n const acquired = await acquireLease(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n subjectId: ids.sessionId,\n backend: ids.backend,\n warmBilling: {\n mode: settings.sandboxWarmBillingMode,\n rateMicrosPerSecond: sandboxWarmRateMicrosPerSecond(settings, ids.backend),\n },\n os,\n // IMAGE IS SHARED STATE (B3): thread the resolved image so the lease stamps it +\n // conflicts on a live box already running a different required image. A\n // SandboxImageConflictError propagates while another holder is active; a\n // solo change requests a capture-and-drain rotation and this attempt retries\n // after the cold successor can safely stamp the new image.\n ...(ids.image ? { image: ids.image } : {}),\n ...(ids.imagePolicy ? { imagePolicy: ids.imagePolicy } : {}),\n // RIG IS SHARED STATE (M3): thread the frozen rig version so the lease stamps it\n // + conflicts on a live box under a different rig. A SandboxRigConflictError\n // propagates while another holder is active; a solo change uses the same\n // durable capture-and-drain rotation as an image change.\n ...(ids.rigVersionId ? { rigVersionId: ids.rigVersionId } : {}),\n leaseTtlMs,\n warmingLeaseTtlMs: settings.sandboxLeaseWarmingTtlMs,\n captureWaitMs: sandboxLifecycleTransitionWaitMs(settings),\n ...(cancellationSignal ? { waitSignal: cancellationSignal } : {}),\n });\n\n if (cancellationSignal) {\n cancellationListener = () => {\n // release() flips `releaseStarted` and clears the timer synchronously\n // before its first await. This eager form deliberately carries no writer-\n // quiescence proof; the outer turn supplies that second stage after its\n // physical drain. The detached rejection handler is intentional: the\n // outer turn owns diagnostics, while this listener owns leak prevention.\n void release().catch(() => undefined);\n };\n cancellationSignal.addEventListener(\"abort\", cancellationListener, { once: true });\n }\n if (cancellationSignal?.aborted) {\n await release();\n throw cancellationError();\n }\n\n // HOLDER-LIVENESS loop: refresh OUR holder every 10s from registration.\n // registered until release. The dead-worker turn-holder reap judges liveness\n // by last_heartbeat_at, and the full turn heartbeat (heartbeatLeaseHolder in\n // agent-turn) only starts AFTER this function returns — while waitForWarm and\n // establish/cold-restore can legitimately run for many minutes in here,\n // COMPOUNDING past any fixed reap horizon. With this\n // loop no live holder is ever silent for more than one tick, so the reap\n // horizon is pure defense-in-depth, not a tuned guess about path lengths.\n // The elected spawner also heartbeats the short rolling warming lease; this\n // makes warming expiry a crash detector rather than a fixed upper bound on a\n // legitimate provider create/restore. A warming waiter only touches its own\n // holder so it cannot keep a dead spawner's lease alive. Once the box is warm,\n // every owner uses the normal epoch-fenced lease heartbeat.\n let holderLeaseHeartbeat: { expectedEpoch: number; leaseTtlMs: number } | null =\n acquired.role === \"spawner\"\n ? {\n expectedEpoch: acquired.lease.leaseEpoch,\n leaseTtlMs: settings.sandboxLeaseWarmingTtlMs,\n }\n : (acquired.role === \"attached\" || acquired.role === \"rearmed\") &&\n acquired.lease.liveness === \"warm\"\n ? { expectedEpoch: acquired.lease.leaseEpoch, leaseTtlMs }\n : null;\n let providerRenewalTarget: { backend: Settings[\"sandboxBackend\"]; instanceId: string } | null =\n acquired.lease.liveness === \"warm\" && acquired.lease.instanceId\n ? {\n backend: ids.backend,\n instanceId: acquired.lease.instanceId,\n }\n : null;\n let providerRenewedAtMs = Date.now();\n let providerRenewalInFlight: Promise<void> | null = null;\n const maybeRenewProviderExpiration = async (force = false): Promise<void> => {\n const target = providerRenewalTarget;\n if (!target || providerRenewalInFlight) return;\n const ttlSeconds = effectiveSandboxLifecycle(settings, target.backend).renewableTtlSeconds;\n if (ttlSeconds === null) return;\n const intervalMs = Math.max(10_000, Math.floor((ttlSeconds * 1000) / 3));\n if (!force && Date.now() - providerRenewedAtMs < intervalMs) return;\n providerRenewalInFlight = renewSandboxProviderExpiration({\n backend: target.backend,\n settings,\n instanceId: target.instanceId,\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n })\n .then(() => {\n providerRenewedAtMs = Date.now();\n })\n .finally(() => {\n providerRenewalInFlight = null;\n });\n await providerRenewalInFlight;\n };\n // Release ONLY on holder death. `heartbeatLeaseHolderStatus` separates \"this\n // holder is gone / its attempt is no longer the active writer\" from \"the lease\n // could not be extended\" (rotation requested, draining, another epoch). The\n // second is NOT a reason to release: once a provider-deadline rotation is\n // requested the turn-side heartbeat immediately preempts the attempt, whose\n // finalizer retains this holder until every attempt-owned writer is physically\n // drained. Dropping it here would let the reaper capture or terminate while a\n // provider operation may still be mutating /workspace. Both loops therefore\n // converge on \"holder alive -> never release\"; finalization performs the\n // proof-bearing release.\n const releaseDeadHolder = async (reason: string): Promise<void> => {\n // Logical closure deliberately fences heartbeat authority. It is not proof\n // that the already-admitted capture has physically settled: the finalizer\n // owns that wait and the original deadline bounds dead-worker recovery.\n // Match the reaper's retention rule without touching holder/lease TTLs.\n if (reason === \"holder_gone\" && kind === \"turn\" && holderLeaseHeartbeat) {\n const expectedEpoch = holderLeaseHeartbeat.expectedEpoch;\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (retainsHolderForWarmCapture(lease, expectedEpoch)) return;\n }\n const message = \"sandbox resume holder released: holder no longer live\";\n const fields = {\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n sandboxGroupId: ids.sandboxGroupId,\n holderKind: kind,\n reason,\n };\n if (services.observability) services.observability.warn(message, fields);\n else console.warn(message, fields);\n void release().catch(() => undefined);\n };\n holderLivenessTimer = setInterval(() => {\n const heartbeat = holderLeaseHeartbeat;\n if (heartbeat) {\n void heartbeatLeaseHolderStatus(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n expectedEpoch: heartbeat.expectedEpoch,\n leaseTtlMs: heartbeat.leaseTtlMs,\n billingMode: services.settings.sandboxWarmBillingMode,\n })\n .then(async (status) => {\n if (heartbeat !== holderLeaseHeartbeat) return;\n if (!status.holderAlive) {\n // Reaped, released, or its exact attempt is no longer the active\n // writer. Stop this otherwise-unbounded provider operation and\n // idempotently drop any remaining holder state.\n await releaseDeadHolder(status.fence);\n return;\n }\n if (status.fence === \"epoch\") {\n // The lease epoch never regresses: a newer epoch means the box this\n // holder was registered against is definitively superseded (lost\n // instance replaced, re-established by a later turn). The holder\n // row is stale authority for an instance that no longer exists;\n // drop it promptly instead of pinning a successor's lease.\n await releaseDeadHolder(status.fence);\n return;\n }\n // The box is still serving this live holder: keep the provider TTL\n // renewed while the lease is ours (extended, or only rotation-fenced at\n // the same epoch). A liveness fence (draining at our epoch) means the\n // reaper now governs the instance; keep the holder but leave its\n // expiry alone.\n if (status.leaseExtended || status.fence === \"rotation_requested\") {\n void maybeRenewProviderExpiration().catch(() => undefined);\n }\n })\n .catch(() => undefined);\n return;\n }\n void touchLeaseHolder(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n kind,\n holderId,\n })\n .then(async (touched) => {\n if (heartbeat !== holderLeaseHeartbeat) return;\n // A canonical turn holder is rejected once its exact attempt is no\n // longer the active writer (touch is attempt-fenced only; it never\n // consults lease authority, so false here always means holder death).\n if (!touched) {\n await releaseDeadHolder(\"holder_gone\");\n return;\n }\n void maybeRenewProviderExpiration().catch(() => undefined);\n })\n .catch(() => undefined);\n }, services.holderLivenessIntervalMs ?? 10_000);\n if (\"unref\" in holderLivenessTimer && typeof holderLivenessTimer.unref === \"function\") {\n holderLivenessTimer.unref();\n }\n\n // FENCED: a newer epoch exists (a later turn re-established the box). Back off;\n // NEVER create(). Release our (just-registered) holder so we don't pin a stale\n // lease, then surface the supersession.\n if (acquired.role === \"blocked\") {\n await release();\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n acquired.lease.leaseEpoch,\n acquired.code,\n acquired.lease.recovery,\n );\n }\n if (acquired.role === \"fenced\") {\n await release();\n if (acquired.reason !== \"superseded\") {\n throw new SandboxLeaseTransitionError(\n ids.sandboxGroupId,\n acquired.lease.leaseEpoch,\n acquired.reason,\n acquired.lease.backend,\n acquired.lease.instanceId,\n acquired.lease.liveness,\n );\n }\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, acquired.lease.leaseEpoch, {\n backend: acquired.lease.backend,\n instanceId: acquired.lease.instanceId,\n liveness: acquired.lease.liveness,\n });\n }\n\n // SPAWNER: we won the cold->warming CAS. Establish (cold-restore/create),\n // then commit warm (lease_epoch++). Optional desktop setup is lazy.\n if (acquired.role === \"spawner\") {\n const expectedEpoch = acquired.lease.leaseEpoch;\n let createdEstablished: EstablishedSandboxSession | null = null;\n let providerCreateOperationId: string | undefined;\n let providerCreateBindingKey: string | undefined;\n let rematerialization: {\n id: string;\n selectedRevision: string;\n workspaceGeneration: number;\n providerBindingKey: string | null;\n legacyCheckpoint: NonNullable<ReturnType<typeof legacyNativeArchiveFromEnvelope>> | null;\n legacyProviderBinding: Awaited<\n ReturnType<typeof resolveModalCheckpointProviderBindingForSession>\n > | null;\n } | null = null;\n try {\n // An audited decision to continue a definitively lost workspace on a new\n // EMPTY box: hydrate nothing (not even a per-session legacy archive) and\n // resume no prior provider identity. Every group member was already told\n // the workspace is empty; the DB accepts only this exact publication.\n const freshWorkspaceRecoveryId = acquired.lease.freshWorkspaceRecoveryId ?? null;\n const envelope = freshWorkspaceRecoveryId\n ? null\n : await getSandboxSessionEnvelope(db, ids.workspaceId, ids.sessionId);\n // The lease is authoritative. A legacy per-session fallback archive may\n // only be used after beginSandboxRematerialization imports its archive\n // fields under the warming-row lock and records one selected revision.\n // Select the fallback only when the lease has no archive truth at all. A\n // lease-carried unverified/invalid archive must fail closed rather than\n // silently substituting another revision.\n // Backstop: a session already told its workspace is empty never gets a\n // legacy per-session archive back, even if the lease marker was lost.\n const legacyFallbackRefused =\n !freshWorkspaceRecoveryId &&\n acquired.lease.recovery.archive.status === \"none\" &&\n workspaceArchiveFieldsFromEnvelope(envelope) !== null &&\n (await sessionHoldsFreshWorkspaceRecovery(db, ids.workspaceId, ids.sessionId));\n const fallbackArchiveEnvelope =\n !freshWorkspaceRecoveryId &&\n !legacyFallbackRefused &&\n acquired.lease.recovery.archive.status === \"none\" &&\n workspaceArchiveFieldsFromEnvelope(envelope) !== null\n ? withoutSandboxProviderIdentity(envelope)\n : null;\n let spawnEnvelope = freshWorkspaceRecoveryId\n ? null\n : legacyFallbackRefused\n ? (acquired.lease.resumeState ?? null)\n : (fallbackArchiveEnvelope ?? acquired.lease.resumeState ?? envelope);\n const archiveSource =\n acquired.lease.recovery.archive.status === \"none\"\n ? fallbackArchiveEnvelope\n : acquired.lease.resumeState;\n const continuityRecovery = acquired.lease.recovery.continuity;\n // A fresh-workspace spawn is deliberately archive-free; commitWarmingToWarm\n // verifies the exact decision before publication.\n if (\n !freshWorkspaceRecoveryId &&\n ((acquired.lease.recovery.archive.status === \"available\" &&\n (acquired.lease.archiveComplete ||\n acquired.lease.historicalRecoveryAuthorized === true)) ||\n (acquired.lease.recovery.archive.status === \"none\" &&\n workspaceArchiveFieldsFromEnvelope(archiveSource) !== null))\n ) {\n const rematerializationId = crypto.randomUUID();\n const legacyNativeArchive = legacyNativeArchiveFromEnvelope(archiveSource);\n const begun = await beginSandboxRematerialization(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId,\n archiveSource,\n legacyNativeArchive,\n });\n if (begun.status !== \"started\") {\n if (begun.code === \"stale_epoch\" || begun.code === \"attempt_conflict\") {\n throw new SandboxLeaseSupersededError(\n ids.sandboxGroupId,\n begun.lease?.leaseEpoch ?? expectedEpoch,\n );\n }\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n begun.lease?.leaseEpoch ?? expectedEpoch,\n begun.code === \"archive_unverified\" ? \"restore_degraded\" : \"restore_unrecoverable\",\n begun.lease?.recovery ?? acquired.lease.recovery,\n );\n }\n spawnEnvelope = begun.lease.resumeState ?? spawnEnvelope;\n const selectedRevision = begun.lease.recovery.restore.selectedRevision;\n if (!selectedRevision) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_metadata_invalid\",\n \"sandbox rematerialization selected no durable archive revision\",\n );\n }\n rematerialization = {\n id: rematerializationId,\n selectedRevision,\n workspaceGeneration: begun.lease.workspaceGeneration,\n providerBindingKey: begun.checkpointArtifact?.providerBindingKey ?? null,\n legacyCheckpoint: begun.checkpointArtifact === null ? legacyNativeArchive : null,\n legacyProviderBinding: null,\n };\n } else if (\n !freshWorkspaceRecoveryId &&\n acquired.lease.recovery.archive.status !== \"none\" &&\n !continuityRecovery\n ) {\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n expectedEpoch,\n \"restore_degraded\",\n acquired.lease.recovery,\n );\n }\n // Prefer the COLD lease's preserved resume_state when it carries a persisted\n // /workspace snapshot (confirmDrainCold keeps a minimal archive-only envelope\n // across draining->cold for exactly this re-warm). establishSandboxSessionFromEnvelope\n // cold-creates a fresh box and replays the archive via hydrateWorkspace, so\n // /workspace survives box churn (sandbox-file-persistence). No archive ->\n // the bare session envelope (a never-warmed cold start). Mirrors channel-a.ts's\n // spawner branch: the lease's resume_state is authoritative; the session\n // `_sandbox` envelope is the per-session fallback. Without this a turn-first\n // re-warm after a drain->cold would ignore the archive and start an EMPTY box.\n const providerCreateStartedAt = new Date();\n const persistArchiveSource =\n spawnEnvelope && typeof spawnEnvelope === \"object\"\n ? (spawnEnvelope as Record<string, unknown>)\n : null;\n const hydrateEnvelopeRaw = await materializeSpawnEnvelopeArchive(\n persistArchiveSource,\n services.objectStorage,\n );\n const hydrateEnvelope =\n hydrateEnvelopeRaw && typeof hydrateEnvelopeRaw === \"object\"\n ? (hydrateEnvelopeRaw as Record<string, unknown>)\n : null;\n const established = await establishSandboxSessionFromEnvelope(settings, hydrateEnvelope, {\n sessionId: ids.sessionId,\n recovery: \"create-or-restore\",\n ...(services.objectStorage\n ? {\n loadHostWorkspaceArchive: async (ref) => {\n try {\n return await downloadWorkspaceArchiveSpool(services.objectStorage!, ref.key, {\n bytes: ref.bytes,\n sha256: ref.sha256,\n });\n } catch (error) {\n if (error instanceof WorkspaceArchiveStorageError) {\n throw new WorkspaceArchiveIntegrityError(error.code, error.message, {\n retryable: error.retryable,\n cause: error,\n });\n }\n throw error;\n }\n },\n }\n : {}),\n backendOverride: ids.backend as never,\n ...(ids.environment ? { environment: ids.environment } : {}),\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n ...(services.logicalFallbackSettings\n ? { logicalFallbackSettings: services.logicalFallbackSettings }\n : {}),\n onBeforeSandboxCreate: async (createSettings, intent, providerContext) => {\n if (ids.backend !== \"modal\") return;\n if (!intent || !providerContext)\n throw new Error(\"Modal create requires the provider dispatch boundary\");\n throwIfReleasedOrCancelled();\n const binding = await resolveModalCheckpointProviderBindingForSession(\n createSettings,\n providerContext,\n );\n const operationId = intent.operationId;\n await beginModalProviderCreate(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n operationId,\n providerBindingKey: binding.key,\n rematerializationId: rematerialization?.id ?? null,\n selectedRevision: rematerialization?.selectedRevision ?? null,\n imageId: intent.imageId,\n imageRef: createSettings.modalImageRef ?? null,\n appId: intent.appId,\n providerName: intent.name,\n requestSha256: intent.requestSha256,\n });\n providerCreateOperationId = operationId;\n providerCreateBindingKey = binding.key;\n },\n onSandboxCreated: async (created) => {\n createdEstablished = created;\n providerRenewalTarget = {\n backend: ids.backend,\n instanceId: created.instanceId,\n };\n providerRenewedAtMs = Date.now();\n if (\n providerCreateBindingKey &&\n !(await modalSessionMatchesCheckpointProviderBinding(\n settings,\n created.session,\n providerCreateBindingKey,\n ))\n ) {\n throw new Error(\"Modal creation receipt crossed the fenced provider namespace\");\n }\n if (\n rematerialization &&\n (rematerialization.providerBindingKey || rematerialization.legacyCheckpoint)\n ) {\n if (created.backendId !== \"modal\") {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Modal checkpoint restore resolved a non-Modal sandbox backend\",\n );\n }\n if (rematerialization.providerBindingKey) {\n if (\n !(await modalSessionMatchesCheckpointProviderBinding(\n settings,\n created.session,\n rematerialization.providerBindingKey,\n ))\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Modal checkpoint restore refused because the authenticated provider workspace changed\",\n );\n }\n } else {\n const resolved = await resolveModalCheckpointProviderBindingForSession(\n settings,\n created.session,\n );\n if (\n rematerialization.legacyProviderBinding &&\n rematerialization.legacyProviderBinding.key !== resolved.key\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Legacy Modal checkpoint restore crossed authenticated provider workspaces\",\n );\n }\n rematerialization.legacyProviderBinding = resolved;\n }\n }\n const resumeEnvelope = requirePersistableReplacementSandboxEnvelope(\n await serializeReplacementSandboxEnvelope(created, persistArchiveSource),\n created.backendId,\n );\n const recorded = await recordWarmingSandboxCreated(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization?.id ?? null,\n ...(providerCreateOperationId ? { providerCreateOperationId } : {}),\n ...(created.providerContinuity\n ? { continuityRecovery: created.providerContinuity }\n : {}),\n instanceId: created.instanceId,\n resumeBackendId: created.backendId,\n resumeState: resumeEnvelope,\n ...(created.backendId === \"modal\"\n ? {\n providerCreatedAt: providerCreateStartedAt,\n providerDeadlineAt: new Date(\n providerCreateStartedAt.getTime() + settings.modalTimeoutSeconds * 1000,\n ),\n }\n : {}),\n leaseTtlMs,\n // Keep the warming budget after create(): manifest setup and\n // commitWarmingToWarm still run, and can exceed the 90s turn TTL.\n warmingLeaseTtlMs: settings.sandboxLeaseWarmingTtlMs,\n });\n if (!recorded.recorded) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n if (created.backendId === \"modal\") {\n await tagModalSandbox(settings, created.instanceId, {\n leaseId: acquired.lease.id,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n }).catch(() => undefined);\n }\n throwIfReleasedOrCancelled();\n },\n onWorkspaceRestoreVerifying: async (descriptor: WorkspaceArchiveDescriptor) => {\n if (!rematerialization || descriptor.revision !== rematerialization.selectedRevision) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_metadata_invalid\",\n `hydrated archive revision ${descriptor.revision} does not match the selected rematerialization revision`,\n );\n }\n if (rematerialization.legacyCheckpoint) {\n const binding = rematerialization.legacyProviderBinding;\n if (!binding) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n \"Legacy Modal checkpoint restore produced no authenticated provider identity\",\n );\n }\n const adopted = await adoptLegacyModalCheckpointArtifact(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n leaseId: acquired.lease.id,\n leaseEpoch: expectedEpoch,\n workspaceGeneration: rematerialization.workspaceGeneration,\n slot: \"current\",\n archiveBase64: rematerialization.legacyCheckpoint.archiveBase64,\n descriptor: rematerialization.legacyCheckpoint.descriptor,\n providerBindingKey: binding.key,\n providerBinding: binding.binding,\n rematerializationId: rematerialization.id,\n });\n if (!adopted) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n rematerialization.providerBindingKey = binding.key;\n }\n const verifying = await markSandboxRestoreVerifying(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization.id,\n });\n if (!verifying.wrote) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n },\n });\n createdEstablished = established;\n throwIfReleasedOrCancelled();\n // A sandbox handle is not sufficient evidence that an asynchronous\n // provider's command router is live. Do not publish a warm lease until\n // one bounded no-op exec works.\n // On timeout the catch below terminates the box and rolls warming -> cold;\n // resumeBoxForTurn may then replace a proven-terminated fresh box once.\n if (services.verifySpawnedSandboxReadiness) {\n await services.verifySpawnedSandboxReadiness(established, {\n sandboxGroupId: ids.sandboxGroupId,\n });\n } else {\n await waitForSandboxExecReadiness(\n established,\n MODAL_EXEC_READINESS_TIMEOUT_MS,\n {\n sandboxGroupId: ids.sandboxGroupId,\n },\n cancellationSignal,\n );\n }\n await maybeRenewProviderExpiration(true);\n throwIfReleasedOrCancelled();\n // Fold the LIVE box into a re-resumable envelope and persist it as the\n // lease's resume_state — exactly like the API-direct paths (channel-a.ts /\n // viewer.ts). Without this the turn committed the ORIGINAL session manifest\n // as resume_state, so every LATER op off this lease (Channel-A fs/git/\n // terminal, the desktop viewer, the reaper) cold-restored a FRESH rival box\n // and never saw the turn's live box. Historical state may contribute only\n // durable archive pointers: if live serialization fails, publishing its\n // dead provider identity would pair the replacement instance with the box\n // that initiated recovery.\n // A successful cold hydrate has already proved this archive usable and the\n // replacement box now contains its files. Keep the current + fallback\n // archive pointers on the committed live envelope until a later warm\n // snapshot replaces them. Without this merge, serialization publishes only\n // the new provider id; a second provider loss before the snapshot cadence\n // fires would otherwise make truthful recovery impossible. Failed hydrate\n // attempts terminate the replacement and fail closed; they never publish a\n // clean or mixed workspace.\n const resumeEnvelope = requirePersistableReplacementSandboxEnvelope(\n await serializeReplacementSandboxEnvelope(established, persistArchiveSource),\n established.backendId,\n );\n throwIfReleasedOrCancelled();\n if (\n rematerialization &&\n !established.providerContinuity &&\n established.restoredArchive?.revision !== rematerialization.selectedRevision\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_mismatch\",\n \"sandbox restore completed without the exact selected durable archive revision\",\n );\n }\n const committed = await commitWarmingToWarm(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n instanceId: established.instanceId,\n // Viewer attach resolves and records the tunnel URL lazily. A headless\n // turn must not touch the optional desktop data plane.\n dataPlaneUrl: null,\n resumeBackendId: established.backendId,\n resumeState: resumeEnvelope,\n ...(freshWorkspaceRecoveryId\n ? { freshWorkspace: { operationId: freshWorkspaceRecoveryId } }\n : established.providerContinuity\n ? { continuityRecovery: established.providerContinuity }\n : rematerialization\n ? {\n rematerialization: {\n id: rematerialization.id,\n verifiedRevision: rematerialization.selectedRevision,\n },\n }\n : {}),\n leaseTtlMs,\n });\n if (!committed.committed || !committed.lease) {\n // A reaper reset our warming row (we were too slow) or a sibling\n // re-established and bumped the epoch. Drop the handle; release our\n // holder; surface supersession. This spawner created the box, so stop it\n // before retrying to avoid an untracked running sandbox.\n const terminated = await terminateEstablishedSandbox(established);\n if (terminated && rematerialization && !established.providerContinuity) {\n await failSandboxRematerialization(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization.id,\n failureCode: committed.reason ?? \"warm_commit_rejected\",\n retryable: false,\n });\n } else if (terminated) {\n await failWarmingToCold(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n });\n }\n await release();\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, expectedEpoch);\n }\n holderLeaseHeartbeat = {\n expectedEpoch: committed.lease.leaseEpoch,\n leaseTtlMs,\n };\n throwIfReleasedOrCancelled();\n return { established, leaseEpoch: committed.lease.leaseEpoch, release };\n } catch (error) {\n if (error instanceof SandboxLeaseSupersededError) {\n await terminateEstablishedSandbox(createdEstablished);\n await release();\n throw error;\n }\n const terminated = await terminateEstablishedSandbox(createdEstablished);\n // Caught spawn failure: if the just-created sandbox was actually stopped,\n // roll the warming row back to cold so a queued turn can re-acquire and\n // re-spawn. If termination itself failed, keep the recorded instance_id on\n // the warming row; the lease TTL/reaper and Modal orphan sweep are the\n // tracked backstops, and we must not erase the only provider pointer.\n if (terminated) {\n const continuityUnavailable = error instanceof SandboxProviderContinuityUnavailableError;\n if (rematerialization && !createdEstablished?.providerContinuity) {\n await failSandboxRematerialization(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n rematerializationId: rematerialization.id,\n failureCode: continuityUnavailable\n ? \"provider_continuity_unavailable\"\n : error instanceof WorkspaceArchiveIntegrityError\n ? error.code\n : \"sandbox_rematerialization_failed\",\n retryable: continuityUnavailable\n ? error.retryable\n : error instanceof WorkspaceArchiveIntegrityError\n ? error.retryable\n : true,\n ...(continuityUnavailable ? { discardContinuity: true } : {}),\n });\n } else {\n await failWarmingToCold(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch,\n ...(continuityUnavailable ? { discardContinuity: true } : {}),\n });\n }\n }\n await release();\n recordSandboxWarmingTimeout(services.sandboxMetrics, error);\n if (\n terminated &&\n createdEstablished &&\n error instanceof SandboxExecReadinessTimeoutError &&\n error.instanceId === createdEstablished.instanceId &&\n (createdEstablished.origin === \"created\" || createdEstablished.origin === \"restored\") &&\n !createdEstablished.providerContinuity\n ) {\n disposedUnreadyFreshSandboxErrors.add(error);\n }\n throw sandboxProvisionStageError(rematerialization ? \"archive_recovery\" : \"create\", error);\n }\n }\n\n // ATTACHED / REARMED: the box is live (or a sibling is warming it). Resume it\n // BY ID off the committed lease envelope. For an 'attached'-to-warming lease we\n // first wait for the spawner to commit warm, bounded by the explicit warming\n // budget. A cold reset means the spawner died; recover the same turn instead\n // of trying to enter the spawner create path from the attached branch.\n try {\n let leaseEpoch = acquired.lease.leaseEpoch;\n if (acquired.lease.liveness === \"warming\") {\n leaseEpoch = (await waitForWarm(services, ids)).leaseEpoch;\n holderLeaseHeartbeat = { expectedEpoch: leaseEpoch, leaseTtlMs };\n }\n throwIfReleasedOrCancelled();\n\n // Prefer the lease's resume_state (the LIVE box the spawner committed) so we\n // re-attach to the SAME box by id, not cold-restore the original session\n // manifest into a rival. Fall back to the session envelope only when the\n // lease carries no resume_state (matches channel-a.ts's attached branch).\n const live = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (\n !live ||\n live.liveness !== \"warm\" ||\n live.leaseEpoch !== leaseEpoch ||\n live.instanceId === null\n ) {\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, live?.leaseEpoch ?? leaseEpoch);\n }\n let established: EstablishedSandboxSession;\n try {\n const establish = services.establishAttachedSandbox ?? establishSandboxSessionFromEnvelope;\n established = await establish(settings, live.resumeState, {\n sessionId: ids.sessionId,\n recovery: \"resume-only\",\n backendOverride: ids.backend as never,\n ...(ids.environment ? { environment: ids.environment } : {}),\n ...(services.sandboxMetrics ? { metrics: services.sandboxMetrics } : {}),\n });\n throwIfReleasedOrCancelled();\n // A durable `warm` row is an ownership assertion, not provider liveness.\n // A provider may have ended the exact box while OpenGeni was idle. Prove\n // the command router before handing the session to the\n // agent so terminal evidence enters the atomic warm->cold recovery path\n // below instead of surfacing inside a model-visible tool call.\n if (services.verifyAttachedSandboxReadiness) {\n await services.verifyAttachedSandboxReadiness(established);\n } else {\n await waitForSandboxExecReadiness(\n established,\n MODAL_EXEC_READINESS_TIMEOUT_MS,\n {\n sandboxGroupId: ids.sandboxGroupId,\n },\n cancellationSignal,\n );\n }\n providerRenewalTarget = {\n backend: ids.backend,\n instanceId: established.instanceId,\n };\n await maybeRenewProviderExpiration(true);\n throwIfReleasedOrCancelled();\n } catch (error) {\n if (!isProviderSandboxNotFoundError(ids.backend, error)) {\n throw sandboxProvisionStageError(\"resume\", error);\n }\n const marked = await markWarmLeaseInstanceLost(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sandboxGroupId: ids.sandboxGroupId,\n expectedEpoch: leaseEpoch,\n expectedInstanceId: live.instanceId,\n expectedBackend: ids.backend,\n });\n if (marked.status === \"marked\") {\n await services.onSandboxLost?.({\n sandboxGroupId: ids.sandboxGroupId,\n instanceId: live.instanceId,\n leaseEpoch: marked.lease.leaseEpoch,\n });\n throw new SandboxLeaseInstanceLostError(\n ids.sandboxGroupId,\n marked.lease.leaseEpoch,\n live.instanceId,\n );\n }\n throw new SandboxLeaseSupersededError(\n ids.sandboxGroupId,\n marked.lease?.leaseEpoch ?? leaseEpoch,\n );\n }\n throwIfReleasedOrCancelled();\n return { established, leaseEpoch, release };\n } catch (error) {\n await release();\n recordSandboxWarmingTimeout(services.sandboxMetrics, error);\n throw error;\n }\n}\n\n/**\n * Poll a warming lease until the spawner commits warm. If the warming row is\n * reset to cold (the spawner died and the reaper reset it), surface supersession\n * so the turn is re-dispatched and can enter the normal spawner branch from\n * acquireLease. Bounded by OPENGENI_SANDBOX_WARMING_TIMEOUT_MS, not the lease TTL.\n */\nasync function waitForWarm(\n services: SandboxResumeServices,\n ids: ResumeBoxIds,\n): Promise<{ leaseEpoch: number }> {\n const { db, settings } = services;\n const deadline = Date.now() + settings.sandboxWarmingTimeoutMs;\n let instanceId: string | null = null;\n while (Date.now() < deadline) {\n await sleep(WARMING_POLL_INTERVAL_MS);\n const lease = await readLease(db, ids.workspaceId, ids.sandboxGroupId);\n if (!lease) {\n // Lease vanished (cold-reaped). Re-dispatch from scratch.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, 0);\n }\n instanceId = lease.instanceId;\n if (lease.liveness === \"warm\") {\n return { leaseEpoch: lease.leaseEpoch };\n }\n if (lease.liveness === \"draining\") {\n // The warming attempt either failed into drain or committed+released before\n // this waiter observed it. Re-dispatch so acquireLease can re-arm or spawn\n // through the normal path.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, lease.leaseEpoch);\n }\n if (lease.liveness === \"cold\") {\n if (isRetryableDegradedRestore(lease.recovery.restore)) {\n // The elected spawner hit a transient archive verification failure.\n // Re-enter admission so one caller can become the next fenced spawner;\n // the archive remains authoritative and must not become terminal.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, lease.leaseEpoch);\n }\n if (\n lease.recovery.restore.status === \"degraded\" ||\n lease.recovery.restore.status === \"unrecoverable\"\n ) {\n throw new SandboxLeaseRecoveryBlockedError(\n ids.sandboxGroupId,\n lease.leaseEpoch,\n lease.recovery.restore.status === \"degraded\"\n ? \"restore_degraded\"\n : \"restore_unrecoverable\",\n lease.recovery,\n );\n }\n // The spawner died; re-dispatch so the normal acquireLease path can win\n // cold->warming and run the full spawner branch.\n throw new SandboxLeaseSupersededError(ids.sandboxGroupId, lease.leaseEpoch);\n }\n // still warming — keep polling.\n }\n throw new SandboxSiblingWarmingTimeoutError(ids.backend, settings.sandboxWarmingTimeoutMs, {\n sandboxGroupId: ids.sandboxGroupId,\n instanceId,\n });\n}\n","import type { LeaseSnapshot } from \"@opengeni/db\";\n\n/** Physical capture retention is not permission to heartbeat or execute a closed turn. */\nexport function retainsHolderForWarmCapture(\n lease: Pick<LeaseSnapshot, \"liveness\" | \"leaseEpoch\" | \"archiveCapture\"> | null,\n expectedEpoch: number,\n now = Date.now(),\n): boolean {\n return Boolean(\n lease?.liveness === \"warm\" &&\n lease.leaseEpoch === expectedEpoch &&\n lease.archiveCapture &&\n lease.archiveCapture.deadlineAt.getTime() > now,\n );\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { Session, SessionGoal, SessionSystemUpdatePayload } from \"@opengeni/contracts\";\nimport {\n getSession,\n getSessionGoal,\n getSessionParentPersonalConnectionDelegations,\n getSessionParentMcpAccountBindings,\n getSessionParentXaiProviderAccountAuthority,\n addSessionSystemUpdateWithSourceMutation,\n claimPendingSessionSystemUpdateOutbox,\n claimPendingSessionWorkflowWakes,\n childRequiresActionDedupeKey,\n getSessionSystemUpdateOutboxByDedupeKey,\n getOrCreateSessionSystemUpdateOutbox,\n claimAutomaticSessionTitleFanout,\n markSessionWorkflowWakeFailed,\n markSessionSystemUpdateOutboxDeliveredInTransaction,\n markSessionSystemUpdateOutboxFailed,\n markAutomaticSessionTitleFanoutDelivered,\n markAutomaticSessionTitleFanoutFailed,\n sessionSystemUpdateOutboxKindPayload,\n type Database,\n type SessionSystemUpdateOutboxDelivery,\n} from \"@opengeni/db\";\nimport { requireSessionEventDurableFanoutCapability, type EventBus } from \"@opengeni/events\";\nimport type { ActivityServices, WakeSessionWorkflowSignal } from \"./types\";\n\nexport type NotifyServices = {\n db: Database;\n bus: EventBus;\n settings: Settings;\n observability: ActivityServices[\"observability\"];\n wakeSessionWorkflow: WakeSessionWorkflowSignal | null;\n};\n\nexport type ReconcileParentSystemUpdateOverrides = Partial<{\n claimPendingSessionSystemUpdateOutbox: typeof claimPendingSessionSystemUpdateOutbox;\n}>;\n\nexport type ReconcileSessionWorkflowWakeOverrides = Partial<{\n claimPendingSessionWorkflowWakes: typeof claimPendingSessionWorkflowWakes;\n}>;\n\nexport type ReconcileAutomaticSessionTitleFanoutOverrides = Partial<{\n claimAutomaticSessionTitleFanout: typeof claimAutomaticSessionTitleFanout;\n markAutomaticSessionTitleFanoutDelivered: typeof markAutomaticSessionTitleFanoutDelivered;\n markAutomaticSessionTitleFanoutFailed: typeof markAutomaticSessionTitleFanoutFailed;\n}>;\n\n/**\n * Enrich and deliver the durable idle-boundary row committed by\n * settleSessionIdleWithParentOutbox. Idle has no single owning turn, so its\n * stable episode identity is the newest non-status event sequence.\n */\nexport async function notifyParentOfChildIdle(\n svc: NotifyServices,\n workspaceId: string,\n childSessionId: string,\n episodeKey: string,\n): Promise<void> {\n try {\n const child = await getSession(svc.db, workspaceId, childSessionId);\n if (!child || !child.parentSessionId) {\n return;\n }\n const goal = await getSessionGoal(svc.db, workspaceId, childSessionId);\n const clientEventId = `child-completion:${childSessionId}:${episodeKey}`;\n // The idle settlement committed this row with the child's frozen final\n // answer. This adds the goal facts; the upsert keeps the frozen content.\n const payload = childCompletionPayload(child, goal);\n const personalConnectionDelegations = await getSessionParentPersonalConnectionDelegations(\n svc.db,\n workspaceId,\n childSessionId,\n );\n const mcpAccountBindings = await getSessionParentMcpAccountBindings(\n svc.db,\n workspaceId,\n childSessionId,\n );\n const xaiAuthority = await getSessionParentXaiProviderAccountAuthority(\n svc.db,\n workspaceId,\n childSessionId,\n );\n const outbox = await getOrCreateSessionSystemUpdateOutbox(svc.db, {\n accountId: child.accountId,\n workspaceId,\n sourceSessionId: child.id,\n targetSessionId: child.parentSessionId,\n kind: \"child_terminal_result\",\n classification: goal?.status === \"paused\" ? \"action_required\" : \"success\",\n sourceId: child.id,\n dedupeKey: clientEventId,\n summary: childCompletionSummary(child, goal, \"idle\"),\n payload,\n lineage: {\n childSessionId: child.id,\n parentSessionId: child.parentSessionId,\n ...(xaiAuthority.subjectId ? { xaiAuthoritySubjectId: xaiAuthority.subjectId } : {}),\n },\n personalConnectionDelegations,\n mcpAccountBindings,\n xaiProviderAccountAuthoritySnapshot: xaiAuthority.snapshot,\n });\n if (outbox.status === \"delivered\") {\n return;\n }\n await deliverParentSystemUpdateOutbox(svc, outbox);\n } catch (error) {\n // A durable pending outbox row survives this boundary. The global worker\n // reaper retries it; child terminal settlement never depends on this turn.\n svc.observability.error(\"Failed to wake parent session on worker idle boundary\", {\n childSessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Deliver one exact child-lifecycle outbox row already committed by the\n * child's own lifecycle transaction (turn failure, requires_action freeze,\n * ...). This layer deliberately cannot create or rewrite the row: the\n * producing transaction is the sole owner of its payload and lineage, and the\n * global reconciler remains the recovery path if immediate delivery fails.\n */\nexport async function deliverChildLifecycleOutboxToParent(\n svc: NotifyServices,\n workspaceId: string,\n childSessionId: string,\n dedupeKey: string,\n options: { requireRow?: boolean } = {},\n): Promise<void> {\n try {\n const child = await getSession(svc.db, workspaceId, childSessionId);\n if (!child || !child.parentSessionId) return;\n const outbox = await getSessionSystemUpdateOutboxByDedupeKey(svc.db, {\n accountId: child.accountId,\n workspaceId,\n dedupeKey,\n });\n if (!outbox) {\n if (options.requireRow === false) return;\n throw new Error(`Committed child-lifecycle outbox disappeared: ${dedupeKey}`);\n }\n if (outbox.status === \"delivered\") return;\n await deliverParentSystemUpdateOutbox(svc, outbox);\n } catch (error) {\n svc.observability.error(\"Failed to deliver committed child-lifecycle notice\", {\n childSessionId,\n dedupeKey,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Deliver the exact failure row already committed by turn settlement. This\n * layer deliberately cannot create or rewrite the row: the settlement\n * transaction is the sole owner of the failed turn id, payload, and lineage.\n */\nexport async function deliverFailedChildTurnToParent(\n svc: NotifyServices,\n workspaceId: string,\n childSessionId: string,\n turnId: string,\n): Promise<void> {\n await deliverChildLifecycleOutboxToParent(\n svc,\n workspaceId,\n childSessionId,\n `child-completion:${childSessionId}:turn:${turnId}`,\n );\n}\n\n/**\n * Deliver the child_requires_action notice a requires_action settlement\n * committed for this exact (child, turn, generation). When the rollout flag is\n * off no row exists and this is a no-op; the reaper covers crashes after commit.\n */\nexport async function deliverChildRequiresActionToParent(\n svc: NotifyServices,\n workspaceId: string,\n childSessionId: string,\n input: { turnId: string; turnGeneration: number },\n): Promise<void> {\n if (!svc.settings.childLifecycleNoticesEnabled) return;\n await deliverChildLifecycleOutboxToParent(\n svc,\n workspaceId,\n childSessionId,\n childRequiresActionDedupeKey({\n childSessionId,\n turnId: input.turnId,\n turnGeneration: input.turnGeneration,\n }),\n // A requires_action freeze without any human-input/approval request (or a\n // child without a parent) commits no row; that is not an error.\n { requireRow: false },\n );\n}\n\nasync function deliverParentSystemUpdateOutbox(\n svc: NotifyServices,\n outbox: SessionSystemUpdateOutboxDelivery,\n): Promise<void> {\n try {\n const result = await addSessionSystemUpdateWithSourceMutation(\n svc.db,\n {\n accountId: outbox.accountId,\n workspaceId: outbox.workspaceId,\n sessionId: outbox.targetSessionId,\n ...sessionSystemUpdateOutboxKindPayload(outbox),\n classification: outbox.classification,\n sourceId: outbox.sourceId,\n dedupeKey: outbox.dedupeKey,\n summary: outbox.summary,\n lineage: outbox.lineage,\n personalConnectionDelegations: outbox.personalConnectionDelegations,\n mcpAccountBindings: outbox.mcpAccountBindings,\n xaiProviderAccountAuthoritySnapshot: outbox.xaiProviderAccountAuthoritySnapshot,\n },\n async (tx) => {\n await markSessionSystemUpdateOutboxDeliveredInTransaction(tx, outbox);\n },\n );\n if (result.reason === \"session_cancelled\") {\n return;\n }\n if (result.added && result.events.length > 0) {\n await svc.bus.publish(outbox.workspaceId, outbox.targetSessionId, result.events);\n }\n if (result.shouldWake && svc.wakeSessionWorkflow) {\n if (result.workflowWakeRevision === null) {\n throw new Error(\"Runnable system update has no workflow wake revision\");\n }\n await svc.wakeSessionWorkflow({\n accountId: outbox.accountId,\n workspaceId: outbox.workspaceId,\n sessionId: outbox.targetSessionId,\n workflowId: result.temporalWorkflowId ?? `session-${outbox.targetSessionId}`,\n wakeRevision: result.workflowWakeRevision,\n });\n }\n svc.observability.info(\"Delivered child lifecycle notice to parent session\", {\n childSessionId: outbox.sourceSessionId,\n parentSessionId: outbox.targetSessionId,\n kind: outbox.kind,\n dedupeKey: outbox.dedupeKey,\n woke: result.shouldWake,\n });\n } catch (error) {\n await markSessionSystemUpdateOutboxFailed(\n svc.db,\n outbox,\n error instanceof Error ? error.message : String(error),\n ).catch(() => undefined);\n throw error;\n }\n}\n\nexport async function reconcilePendingParentSystemUpdates(\n svc: NotifyServices,\n limit = 100,\n overrides: ReconcileParentSystemUpdateOverrides = {},\n): Promise<{ claimed: number; delivered: number; failed: number }> {\n const claimPendingSessionSystemUpdateOutboxFn =\n overrides.claimPendingSessionSystemUpdateOutbox ?? claimPendingSessionSystemUpdateOutbox;\n const rows = await claimPendingSessionSystemUpdateOutboxFn(svc.db, limit);\n let delivered = 0;\n let failed = 0;\n for (const row of rows) {\n try {\n await deliverParentSystemUpdateOutbox(svc, row);\n delivered += 1;\n } catch {\n failed += 1;\n }\n }\n return { claimed: rows.length, delivered, failed };\n}\n\n/**\n * Publish migration-created safe title events through the configured session\n * event bus. The outbox is durable and deployment-global; a crash after publish\n * but before acknowledgement can duplicate a notification, which is safe\n * because SSE consumers sequence-fence and gap-fill from the durable log.\n *\n * Managed NATS exposes the stronger bounded flush acknowledgement through\n * publishConfirmed. Embedding buses predate that optional capability, so their\n * required publish promise remains the delivery acknowledgement: resolve only\n * after accepting the batch, and reject a real transport failure so the durable\n * row stays retryable. Every supported bus also provides the mandatory paired\n * recovery capability used by API SSE streams after subscriber reconnect.\n */\nexport async function reconcileAutomaticSessionTitleFanout(\n svc: NotifyServices,\n limit = 100,\n overrides: ReconcileAutomaticSessionTitleFanoutOverrides = {},\n): Promise<{ claimed: number; delivered: number; failed: number }> {\n requireSessionEventDurableFanoutCapability(svc.bus);\n const claim = overrides.claimAutomaticSessionTitleFanout ?? claimAutomaticSessionTitleFanout;\n const markDelivered =\n overrides.markAutomaticSessionTitleFanoutDelivered ?? markAutomaticSessionTitleFanoutDelivered;\n const markFailed =\n overrides.markAutomaticSessionTitleFanoutFailed ?? markAutomaticSessionTitleFanoutFailed;\n const rows = await claim(svc.db, limit);\n let delivered = 0;\n let failed = 0;\n const queue = [...rows];\n const workers = Array.from({ length: Math.min(20, queue.length) }, async () => {\n for (;;) {\n const row = queue.shift();\n if (!row) return;\n try {\n if (svc.bus.isConnected?.() === false) {\n throw new Error(\"session event bus is disconnected\");\n }\n if (svc.bus.publishConfirmed) {\n await svc.bus.publishConfirmed(row.event.workspaceId, row.event.sessionId, [row.event]);\n } else {\n await svc.bus.publish(row.event.workspaceId, row.event.sessionId, [row.event]);\n }\n await markDelivered(svc.db, row);\n delivered += 1;\n } catch (error) {\n failed += 1;\n await markFailed(svc.db, row, error instanceof Error ? error.message : String(error)).catch(\n () => undefined,\n );\n }\n }\n });\n await Promise.all(workers);\n return { claimed: rows.length, delivered, failed };\n}\n\nexport type WorkflowWakeReconciliationResult = {\n claimed: number;\n /** Transport acceptance is not durable admission. */\n signaled: number;\n /** Revisions acknowledged by the durable admission guard. */\n delivered: number;\n pendingAdmission: number;\n /** Legacy/embedding signalers may not return an acknowledgment receipt. */\n unconfirmed: number;\n failed: number;\n pendingAdmissionBlockers: Partial<\n Record<\n Extract<\n import(\"@opengeni/db\").SessionWorkflowWakeDeliveryResult,\n { action: \"pending_admission\" }\n >[\"blocker\"],\n number\n >\n >;\n};\n\nexport async function reconcilePendingSessionWorkflowWakes(\n svc: NotifyServices,\n limit = 1_000,\n overrides: ReconcileSessionWorkflowWakeOverrides = {},\n): Promise<WorkflowWakeReconciliationResult> {\n const claimPendingSessionWorkflowWakesFn =\n overrides.claimPendingSessionWorkflowWakes ?? claimPendingSessionWorkflowWakes;\n if (!svc.wakeSessionWorkflow) {\n return {\n claimed: 0,\n signaled: 0,\n delivered: 0,\n pendingAdmission: 0,\n unconfirmed: 0,\n failed: 0,\n pendingAdmissionBlockers: {},\n };\n }\n const repairs = await claimPendingSessionWorkflowWakesFn(svc.db, limit);\n let signaled = 0;\n let pendingAdmission = 0;\n let unconfirmed = 0;\n const pendingAdmissionBlockers: WorkflowWakeReconciliationResult[\"pendingAdmissionBlockers\"] = {};\n let delivered = 0;\n let failed = 0;\n const queue = [...repairs];\n const workers = Array.from({ length: Math.min(20, queue.length) }, async () => {\n for (;;) {\n const repair = queue.shift();\n if (!repair) return;\n let signalAccepted = false;\n const onSignalAccepted = () => {\n if (signalAccepted) return;\n signalAccepted = true;\n signaled += 1;\n };\n try {\n const receipt = await svc.wakeSessionWorkflow!({\n accountId: repair.accountId,\n workspaceId: repair.workspaceId,\n sessionId: repair.sessionId,\n workflowId: repair.temporalWorkflowId,\n wakeRevision: repair.wakeRevision,\n ...(repair.interruptionRequested ? { interruptionRequested: true } : {}),\n onSignalAccepted,\n });\n // Older embeddings do not invoke the optional transport observer.\n // Their successful return still proves a signal call, never an ACK.\n onSignalAccepted();\n if (receipt?.action === \"acknowledged\") {\n delivered += 1;\n } else if (receipt?.action === \"pending_admission\") {\n pendingAdmission += 1;\n pendingAdmissionBlockers[receipt.blocker] =\n (pendingAdmissionBlockers[receipt.blocker] ?? 0) + 1;\n } else {\n // A successful legacy signal is not proof of acknowledgment. The\n // committed outbox obligation remains owned by the existing guard.\n unconfirmed += 1;\n }\n } catch (error) {\n failed += 1;\n await markSessionWorkflowWakeFailed(\n svc.db,\n repair,\n error instanceof Error ? error.message : String(error),\n ).catch(() => undefined);\n }\n }\n });\n await Promise.all(workers);\n return {\n claimed: repairs.length,\n signaled,\n delivered,\n pendingAdmission,\n unconfirmed,\n failed,\n pendingAdmissionBlockers,\n };\n}\n\nfunction childCompletionPayload(\n child: Session,\n goal: SessionGoal | null,\n): Extract<SessionSystemUpdatePayload, { type: \"child_terminal_result\" }> {\n return {\n type: \"child_terminal_result\",\n childSessionId: child.id,\n status: \"idle\",\n ...(goal\n ? {\n goal: {\n status: goal.status,\n text: goal.text,\n ...(goal.evidence ? { evidence: goal.evidence } : {}),\n ...(goal.rationale ? { rationale: goal.rationale } : {}),\n ...(goal.pausedReason ? { pausedReason: goal.pausedReason } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * The short status line for one child (what happened + its goal). It is also\n * the timeline preview, so it carries no instructions: the parent reads the\n * child's answer from the typed payload, and the operational contract says how\n * to use it. N completions coalesce into one internal-update inference.\n */\nexport function childCompletionSummary(\n child: Session,\n goal: SessionGoal | null,\n terminalStatus: \"idle\" | \"failed\",\n): string {\n const lines: string[] = [];\n if (terminalStatus === \"failed\") {\n lines.push(`A worker session you spawned has FAILED. Worker session id: ${child.id}.`);\n } else if (goal?.status === \"completed\") {\n lines.push(\n `A worker session you spawned has COMPLETED its goal. Worker session id: ${child.id}.`,\n );\n } else if (goal?.status === \"paused\") {\n lines.push(\n `A worker session you spawned has PAUSED its goal and gone idle. Worker session id: ${child.id}.`,\n );\n } else {\n lines.push(\n `A worker session you spawned has finished its work and gone idle. Worker session id: ${child.id}.`,\n );\n }\n if (goal) {\n lines.push(`Worker goal: ${goal.text}`);\n if (goal.status === \"completed\" && goal.evidence) {\n lines.push(`Completion evidence: ${goal.evidence}`);\n }\n if (goal.status === \"paused\" && goal.rationale) {\n lines.push(`Pause rationale: ${goal.rationale}`);\n }\n }\n return lines.join(\"\\n\");\n}\n","import type {\n ResourceRef,\n SessionStatus,\n SessionSystemUpdatePayload,\n ToolRef,\n} from \"@opengeni/contracts\";\n\nexport { mergeResourceRefs, mergeToolRefs } from \"@opengeni/contracts\";\n\n/**\n * Refuse to revive a terminal reusable session on a scheduled fire. Mirrors the\n * API-level guard in apps/api/src/domain/sessions.ts (post a user message ->\n * 409 when cancelled): \"cancelled\" is the one terminal state, an explicit user\n * act, so a recurring task must NOT silently resurrect and re-bill it. Failed\n * and idle sessions stay revivable (talking to a session is how it resumes), so\n * only \"cancelled\" is rejected. Throwing inside the FOR UPDATE locked-update\n * callback aborts the whole append+enqueue transaction atomically, and the\n * dispatch catch marks the scheduled_task_run \"failed\" rather than dispatched.\n */\nexport function assertReusableSessionRevivable(status: SessionStatus): void {\n if (status === \"cancelled\") {\n throw new Error(\"reusable session is cancelled; refusing to revive on scheduled fire\");\n }\n}\n\nexport function scheduledUserMessagePayload(\n prompt: string,\n resources: ResourceRef[],\n tools: ToolRef[],\n taskId: string,\n runId: string,\n): Extract<SessionSystemUpdatePayload, { type: \"scheduled_occurrence\" }> {\n return {\n type: \"scheduled_occurrence\",\n text: prompt,\n scheduledTaskId: taskId,\n scheduledTaskRunId: runId,\n ...(resources.length ? { resources } : {}),\n ...(tools.length ? { tools } : {}),\n };\n}\n\nexport function workflowIdForSession(sessionId: string): string {\n return `session-${sessionId}`;\n}\n","import {\n IncidentTelemetryPreflight,\n stableJson,\n type FirstPartyMcpToolName,\n type Permission,\n type ResourceRef,\n type ScheduledTask,\n type ScheduledTaskAgentConfig,\n} from \"@opengeni/contracts\";\nimport { createHash } from \"node:crypto\";\nimport { isDeepStrictEqual } from \"node:util\";\n\nexport type IncidentTelemetryPreflightBlockReason =\n | \"incident_preflight_metadata_missing\"\n | \"incident_responder_under_capable\"\n | \"incident_data_source_unsuitable\";\n\nexport type IncidentTelemetryPreflightResult =\n | { action: \"not_required\" }\n | { action: \"ready\" }\n | { action: \"blocked\"; reason: IncidentTelemetryPreflightBlockReason };\n\nexport type IncidentTelemetryRigMetadata = {\n name: string;\n credentialHooks: readonly string[];\n checkHealth: \"passing\" | \"failing\" | \"unknown\";\n};\n\nexport type IncidentTelemetryVariableSetMetadata = {\n name: string;\n variables: readonly { name: string }[];\n};\n\nexport type IncidentTelemetryResponderMetadata = {\n /** False when an exact selected attachment could not be projected safely. */\n metadataComplete: boolean;\n resources: readonly ResourceRef[];\n mcpServerIds: readonly string[];\n firstPartyMcpTools: readonly FirstPartyMcpToolName[];\n firstPartyMcpPermissions: readonly Permission[];\n rig: IncidentTelemetryRigMetadata | null;\n variableSets: readonly IncidentTelemetryVariableSetMetadata[];\n /** Exact durable session policy version, or null for a not-yet-created session. */\n toolPolicyVersion: number | null;\n};\n\nexport type IncidentTelemetryPreflightInput = {\n agentConfig: ScheduledTaskAgentConfig;\n /** A valid structured alert occurrence also makes a legacy task incident-triggered. */\n incidentTriggered: boolean;\n /** Exact bounded labels from that validated occurrence; values are never rendered in blockers. */\n alertOccurrenceLabels: Readonly<Record<string, string>> | null;\n responder: IncidentTelemetryResponderMetadata;\n};\n\nexport const INCIDENT_TELEMETRY_AUTHORITY_FENCE_LINEAGE_KEY = \"incidentTelemetryAuthorityFence\";\n\nexport type IncidentTelemetryAuthorityFence = {\n version: 2;\n toolPolicyVersion: number;\n responderDigest: string;\n taskDigest: string;\n alertSelectorDigest: string;\n};\n\nexport type IncidentTelemetryPreflightDeclaration =\n | { action: \"not_required\" }\n | {\n action: \"blocked\";\n reason: \"incident_preflight_metadata_missing\" | \"incident_data_source_unsuitable\";\n }\n | { action: \"required\"; preflight: IncidentTelemetryPreflight };\n\nexport function incidentTelemetryPreflightDeclaration(\n agentConfig: ScheduledTaskAgentConfig,\n incidentTriggered: boolean,\n): IncidentTelemetryPreflightDeclaration {\n const rawConfig = agentConfig as ScheduledTaskAgentConfig & Record<string, unknown>;\n const executionClass = rawConfig.executionClass;\n const rawPreflight = rawConfig.incidentTelemetryPreflight;\n if (executionClass === undefined && rawPreflight === undefined && !incidentTriggered) {\n return { action: \"not_required\" };\n }\n if (executionClass !== \"incident_telemetry\" || rawPreflight === undefined) {\n return { action: \"blocked\", reason: \"incident_preflight_metadata_missing\" };\n }\n\n const parsed = IncidentTelemetryPreflight.safeParse(rawPreflight);\n if (!parsed.success) {\n const dataSourceInvalid = parsed.error.issues.some((issue) => issue.path[0] === \"dataSource\");\n return {\n action: \"blocked\",\n reason: dataSourceInvalid\n ? \"incident_data_source_unsuitable\"\n : \"incident_preflight_metadata_missing\",\n };\n }\n return { action: \"required\", preflight: parsed.data };\n}\n\n/**\n * Pure, metadata-only incident admission. No provider request, public endpoint\n * fetch, secret read/decrypt, session creation, or ambient credential lookup is\n * reachable from this evaluator.\n */\nexport function evaluateIncidentTelemetryPreflight(\n input: IncidentTelemetryPreflightInput,\n): IncidentTelemetryPreflightResult {\n const declaration = incidentTelemetryPreflightDeclaration(\n input.agentConfig,\n input.incidentTriggered,\n );\n if (declaration.action !== \"required\") return declaration;\n const preflight = declaration.preflight;\n\n if (!input.responder.metadataComplete) {\n return blocked(\"incident_preflight_metadata_missing\");\n }\n\n if (\n preflight.requiredResources.some(\n (required) =>\n !input.responder.resources.some((selected) => isDeepStrictEqual(selected, required)),\n )\n ) {\n return blocked(\"incident_responder_under_capable\");\n }\n\n const selectedMcpServerIds = new Set(input.responder.mcpServerIds);\n if (preflight.requiredMcpServerIds.some((id) => !selectedMcpServerIds.has(id))) {\n return blocked(\"incident_responder_under_capable\");\n }\n\n const selectedFirstPartyTools = new Set(input.responder.firstPartyMcpTools);\n if (preflight.requiredFirstPartyMcpTools.some((tool) => !selectedFirstPartyTools.has(tool))) {\n return blocked(\"incident_responder_under_capable\");\n }\n\n const selectedFirstPartyPermissions = new Set(input.responder.firstPartyMcpPermissions);\n if (\n preflight.requiredFirstPartyMcpPermissions.some(\n (permission) => !selectedFirstPartyPermissions.has(permission),\n )\n ) {\n return blocked(\"incident_responder_under_capable\");\n }\n\n if (preflight.requiredRig && !rigSatisfies(input.responder.rig, preflight.requiredRig)) {\n return blocked(\"incident_responder_under_capable\");\n }\n\n const variableSetsByName = new Map(input.responder.variableSets.map((set) => [set.name, set]));\n if (preflight.requiredVariableSetNames.some((name) => !variableSetsByName.has(name))) {\n return blocked(\"incident_responder_under_capable\");\n }\n const attachedVariableNames = new Set(\n input.responder.variableSets.flatMap((set) => set.variables.map((variable) => variable.name)),\n );\n if (preflight.requiredVariableNames.some((name) => !attachedVariableNames.has(name))) {\n return blocked(\"incident_responder_under_capable\");\n }\n\n const route = preflight.dataSource.route;\n if (route.kind === \"mcp\" && !selectedMcpServerIds.has(route.serverId)) {\n return blocked(\"incident_responder_under_capable\");\n }\n if (route.kind === \"first_party\" && !selectedFirstPartyTools.has(route.tool)) {\n return blocked(\"incident_responder_under_capable\");\n }\n if (route.kind === \"variable_set\") {\n const selected = variableSetsByName.get(route.variableSetName);\n const names = new Set(selected?.variables.map((variable) => variable.name) ?? []);\n if (!selected || route.variableNames.some((name) => !names.has(name))) {\n return blocked(\"incident_responder_under_capable\");\n }\n }\n if (\n route.kind === \"rig_credential_hook\" &&\n !rigSatisfies(input.responder.rig, {\n name: preflight.requiredRig?.name ?? \"\",\n credentialHookIds: [route.credentialHookId],\n })\n ) {\n return blocked(\"incident_responder_under_capable\");\n }\n\n if (!seriesMetadataSatisfies(preflight.dataSource)) {\n return blocked(\"incident_data_source_unsuitable\");\n }\n if (!alertSelectorsSatisfy(preflight.dataSource, input.alertOccurrenceLabels)) {\n return blocked(\"incident_data_source_unsuitable\");\n }\n return { action: \"ready\" };\n}\n\nexport function incidentTelemetryAuthorityFence(input: {\n task: ScheduledTask;\n responder: IncidentTelemetryResponderMetadata;\n alertOccurrenceLabels: Readonly<Record<string, string>> | null;\n}): IncidentTelemetryAuthorityFence | null {\n const { task, responder } = input;\n if (responder.toolPolicyVersion === null) return null;\n const declaration = incidentTelemetryPreflightDeclaration(\n task.agentConfig,\n input.alertOccurrenceLabels !== null,\n );\n if (declaration.action !== \"required\" || !input.alertOccurrenceLabels) return null;\n const selectorEntries = declaration.preflight.dataSource.alertSelectorLabels\n .map((label) => [label, input.alertOccurrenceLabels?.[label]] as const)\n .sort(([left], [right]) => left.localeCompare(right));\n if (selectorEntries.some(([, value]) => typeof value !== \"string\" || value.length === 0)) {\n return null;\n }\n const normalized = {\n metadataComplete: responder.metadataComplete,\n resources: [...responder.resources].map((resource) => stableJson(resource)).sort(),\n mcpServerIds: [...responder.mcpServerIds].sort(),\n firstPartyMcpTools: [...responder.firstPartyMcpTools].sort(),\n firstPartyMcpPermissions: [...responder.firstPartyMcpPermissions].sort(),\n rig: responder.rig\n ? {\n name: responder.rig.name,\n credentialHooks: [...responder.rig.credentialHooks].sort(),\n checkHealth: responder.rig.checkHealth,\n }\n : null,\n variableSets: [...responder.variableSets]\n .map((set) => ({\n name: set.name,\n variables: set.variables.map((variable) => variable.name).sort(),\n }))\n .sort((left, right) => left.name.localeCompare(right.name)),\n };\n return {\n version: 2,\n toolPolicyVersion: responder.toolPolicyVersion,\n responderDigest: createHash(\"sha256\").update(stableJson(normalized)).digest(\"hex\"),\n taskDigest: createHash(\"sha256\").update(stableJson(task)).digest(\"hex\"),\n alertSelectorDigest: createHash(\"sha256\").update(stableJson(selectorEntries)).digest(\"hex\"),\n };\n}\n\nexport function parseIncidentTelemetryAuthorityFence(\n lineage: Record<string, unknown>,\n): IncidentTelemetryAuthorityFence | null {\n const raw = lineage[INCIDENT_TELEMETRY_AUTHORITY_FENCE_LINEAGE_KEY];\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const value = raw as Record<string, unknown>;\n return value.version === 2 &&\n typeof value.toolPolicyVersion === \"number\" &&\n Number.isInteger(value.toolPolicyVersion) &&\n value.toolPolicyVersion > 0 &&\n typeof value.responderDigest === \"string\" &&\n /^[0-9a-f]{64}$/.test(value.responderDigest) &&\n typeof value.taskDigest === \"string\" &&\n /^[0-9a-f]{64}$/.test(value.taskDigest) &&\n typeof value.alertSelectorDigest === \"string\" &&\n /^[0-9a-f]{64}$/.test(value.alertSelectorDigest)\n ? {\n version: 2,\n toolPolicyVersion: value.toolPolicyVersion,\n responderDigest: value.responderDigest,\n taskDigest: value.taskDigest,\n alertSelectorDigest: value.alertSelectorDigest,\n }\n : null;\n}\n\nfunction blocked(reason: IncidentTelemetryPreflightBlockReason): IncidentTelemetryPreflightResult {\n return { action: \"blocked\", reason };\n}\n\nfunction rigSatisfies(\n rig: IncidentTelemetryRigMetadata | null,\n required: { name: string; credentialHookIds: readonly string[] },\n): boolean {\n if (!rig || rig.name !== required.name || rig.checkHealth !== \"passing\") {\n return false;\n }\n const hookIds = new Set(rig.credentialHooks);\n return required.credentialHookIds.every((hookId) => hookIds.has(hookId));\n}\n\nfunction seriesMetadataSatisfies(dataSource: IncidentTelemetryPreflight[\"dataSource\"]): boolean {\n if (dataSource.queryPath !== \"/api/v1/query\" && dataSource.queryPath !== \"/api/v1/query_range\") {\n return false;\n }\n return dataSource.requiredSeries.every((required) =>\n dataSource.availableSeries.some((available) => {\n if (available.metric !== required.metric) return false;\n const labels = new Set(available.labels);\n return (\n labels.has(dataSource.workspaceLabel) && required.labels.every((label) => labels.has(label))\n );\n }),\n );\n}\n\nfunction alertSelectorsSatisfy(\n dataSource: IncidentTelemetryPreflight[\"dataSource\"],\n occurrenceLabels: Readonly<Record<string, string>> | null,\n): boolean {\n if (!occurrenceLabels) return false;\n return dataSource.alertSelectorLabels.every(\n (label) =>\n label !== dataSource.workspaceLabel &&\n typeof occurrenceLabels[label] === \"string\" &&\n occurrenceLabels[label]!.length > 0 &&\n dataSource.requiredSeries.every((series) => series.labels.includes(label)) &&\n dataSource.availableSeries.some(\n (series) =>\n dataSource.requiredSeries.some((required) => required.metric === series.metric) &&\n series.labels.includes(dataSource.workspaceLabel) &&\n series.labels.includes(label),\n ),\n );\n}\n","import {\n DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,\n type McpPersonalConnectionDelegation,\n type ScheduledTask,\n type ScheduledTaskRunAcceptedExecution,\n type Session,\n type SessionSystemUpdate,\n} from \"@opengeni/contracts\";\nimport { defaultSessionMcpServerIds, resolveSessionToolPolicy } from \"@opengeni/core\";\nimport {\n getRig,\n getScheduledScopedRigVersionMetadata,\n getScheduledTaskRunAcceptedExecution,\n getVariableSet,\n listEnabledMcpCapabilityServerIds,\n listInstalledApiIntegrationServerIdsForDelegations,\n markScheduledTaskRunAuthorityRejectedInTransaction,\n requireSession,\n type Database,\n} from \"@opengeni/db\";\nimport {\n allowedFirstPartyMcpToolsForSession,\n resolveFirstPartyMcpToolPolicy,\n type Settings,\n} from \"@opengeni/config\";\nimport { withFirstPartyTools } from \"./goals\";\nimport {\n INCIDENT_TELEMETRY_AUTHORITY_FENCE_LINEAGE_KEY,\n incidentTelemetryAuthorityFence,\n parseIncidentTelemetryAuthorityFence,\n evaluateIncidentTelemetryPreflight,\n type IncidentTelemetryResponderMetadata,\n} from \"./incident-telemetry-preflight\";\n\n/** Resolve only exact selected responder metadata; never read/decrypt values or call providers. */\nexport async function resolveIncidentTelemetryResponderMetadata(input: {\n db: Database;\n settings: Settings;\n task: ScheduledTask;\n session: Session | null;\n personalConnectionDelegations: readonly McpPersonalConnectionDelegation[];\n personalResourceAuthoritySubjectId?: string | null;\n executionPolicy?: {\n tools: ScheduledTaskRunAcceptedExecution[\"resolvedTools\"];\n firstPartyMcpTools: ScheduledTaskRunAcceptedExecution[\"resolvedFirstPartyMcpTools\"];\n firstPartyMcpPermissions:\n | ScheduledTaskRunAcceptedExecution[\"resolvedFirstPartyMcpPermissions\"]\n | null;\n variableSetIds?: readonly string[];\n variableSetId: string | null;\n rigId: string | null;\n rigVersionId: string | null;\n toolPolicy: Session[\"toolPolicy\"];\n mcpServerIds: readonly string[];\n toolPolicyVersion: number | null;\n };\n}): Promise<IncidentTelemetryResponderMetadata> {\n const [capabilityServerIds, apiIntegrationServerIds] = await Promise.all([\n listEnabledMcpCapabilityServerIds(input.db, input.task.workspaceId),\n listInstalledApiIntegrationServerIdsForDelegations(\n input.db,\n input.task.workspaceId,\n input.personalConnectionDelegations,\n ),\n ]);\n const sessionTools = input.executionPolicy\n ? input.executionPolicy.tools\n : input.session\n ? input.session.tools\n : withFirstPartyTools(input.settings, input.task.agentConfig.tools);\n const resolvedToolPolicy = resolveIncidentTelemetryResponderToolPolicy({\n settingsMcpServerIds: input.settings.mcpServers.map((server) => server.id),\n capabilityServerIds,\n apiIntegrationServerIds,\n ...(input.executionPolicy\n ? { acceptedSessionMcpServerIds: input.executionPolicy.mcpServerIds }\n : {}),\n session: input.executionPolicy\n ? {\n mcpServers: input.executionPolicy.mcpServerIds.map((id) => ({ id })),\n tools: input.executionPolicy.tools,\n toolPolicy: input.executionPolicy.toolPolicy,\n }\n : input.session,\n plannedTools: sessionTools,\n });\n\n let metadataComplete = true;\n let rig: IncidentTelemetryResponderMetadata[\"rig\"] = null;\n const variableSetIds = new Set<string>();\n if (input.executionPolicy ?? input.session) {\n for (const id of input.executionPolicy?.variableSetIds ?? input.session?.variableSetIds ?? []) {\n variableSetIds.add(id);\n }\n const variableSetId = input.executionPolicy?.variableSetId ?? input.session?.variableSetId;\n const rigId = input.executionPolicy?.rigId ?? input.session?.rigId ?? null;\n const rigVersionId = input.executionPolicy?.rigVersionId ?? input.session?.rigVersionId ?? null;\n if (variableSetId) variableSetIds.add(variableSetId);\n if ((rigId === null) !== (rigVersionId === null)) {\n metadataComplete = false;\n } else if (rigId && rigVersionId) {\n const selected = await getScheduledScopedRigVersionMetadata(\n input.db,\n {\n accountId: input.task.accountId,\n workspaceId: input.task.workspaceId,\n subjectId: input.personalResourceAuthoritySubjectId ?? input.task.createdBy.subjectId,\n },\n rigId,\n rigVersionId,\n );\n if (!selected) {\n metadataComplete = false;\n } else {\n rig = {\n name: selected.name,\n credentialHooks: selected.version.credentialHooks,\n checkHealth: selected.health.checkHealth,\n };\n for (const id of selected.version.defaultVariableSetIds) variableSetIds.add(id);\n }\n }\n } else {\n if (input.task.variableSetId) variableSetIds.add(input.task.variableSetId);\n if (input.task.rigId) {\n const selectedRig = await getRig(\n input.db,\n {\n accountId: input.task.accountId,\n workspaceId: input.task.workspaceId,\n subjectId: input.personalResourceAuthoritySubjectId ?? input.task.createdBy.subjectId,\n },\n input.task.rigId,\n );\n if (!selectedRig?.activeVersion || !selectedRig.activeVersionHealth) {\n metadataComplete = false;\n } else {\n rig = {\n name: selectedRig.name,\n credentialHooks: selectedRig.activeVersion.credentialHooks,\n checkHealth: selectedRig.activeVersionHealth.checkHealth,\n };\n for (const id of selectedRig.activeVersion.defaultVariableSetIds) variableSetIds.add(id);\n }\n }\n }\n\n const variableSets = await Promise.all(\n [...variableSetIds].map(\n async (id) =>\n await getVariableSet(\n input.db,\n {\n accountId: input.task.accountId,\n workspaceId: input.task.workspaceId,\n subjectId: input.personalResourceAuthoritySubjectId ?? input.task.createdBy.subjectId,\n },\n id,\n ),\n ),\n );\n if (variableSets.some((variableSet) => variableSet === null)) {\n metadataComplete = false;\n }\n\n return {\n metadataComplete,\n resources: input.executionPolicy\n ? input.task.agentConfig.resources\n : (input.session?.resources ?? input.task.agentConfig.resources),\n mcpServerIds: resolvedToolPolicy.toolRefs.map((tool) => tool.id),\n firstPartyMcpTools: input.executionPolicy\n ? input.executionPolicy.firstPartyMcpTools\n : input.session\n ? allowedFirstPartyMcpToolsForSession(input.settings, input.session.firstPartyMcpTools)\n : resolveFirstPartyMcpToolPolicy(input.settings).default,\n firstPartyMcpPermissions: input.executionPolicy\n ? (input.executionPolicy.firstPartyMcpPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS)\n : (input.session?.firstPartyMcpPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS),\n rig,\n variableSets: variableSets.flatMap((variableSet) =>\n variableSet\n ? [\n {\n name: variableSet.name,\n variables: variableSet.variables.map((variable) => ({\n name: variable.name,\n })),\n },\n ]\n : [],\n ),\n toolPolicyVersion:\n input.executionPolicy?.toolPolicyVersion ?? input.session?.toolPolicyVersion ?? null,\n };\n}\n\n/** Resolve the responder's current ID-only MCP policy without materializing runtime secrets. */\nexport function resolveIncidentTelemetryResponderToolPolicy(input: {\n settingsMcpServerIds: readonly string[];\n capabilityServerIds: readonly string[];\n apiIntegrationServerIds: readonly string[];\n acceptedSessionMcpServerIds?: readonly string[];\n session: {\n mcpServers: readonly { id: string }[];\n tools: Session[\"tools\"];\n toolPolicy: Session[\"toolPolicy\"];\n } | null;\n plannedTools: Session[\"tools\"];\n}) {\n const workspaceDefaultMcpServerIds = new Set(input.settingsMcpServerIds);\n for (const id of input.capabilityServerIds) workspaceDefaultMcpServerIds.add(id);\n for (const id of input.apiIntegrationServerIds) workspaceDefaultMcpServerIds.add(id);\n for (const id of input.acceptedSessionMcpServerIds ?? []) {\n workspaceDefaultMcpServerIds.add(id);\n }\n\n const availableMcpServerIds = new Set(workspaceDefaultMcpServerIds);\n for (const server of input.session?.mcpServers ?? []) {\n availableMcpServerIds.add(server.id);\n }\n\n return resolveSessionToolPolicy({\n toolPolicy: input.session?.toolPolicy ?? {\n mode: \"explicit\",\n inheritedFromSessionId: null,\n },\n sessionTools: input.plannedTools,\n availableMcpServerIds,\n defaultMcpServerIds: defaultSessionMcpServerIds(\n [...workspaceDefaultMcpServerIds].map((id) => ({ id })),\n ),\n });\n}\n\n/** Revalidate a source-frozen incident responder fence before a turn can claim it. */\nexport async function validateIncidentTelemetrySystemUpdateAuthority(input: {\n db: Database;\n settings: Settings;\n workspaceId: string;\n sessionId: string;\n update: SessionSystemUpdate;\n}): Promise<{ action: \"accept\" } | { action: \"reject\"; reason: string }> {\n if (!(INCIDENT_TELEMETRY_AUTHORITY_FENCE_LINEAGE_KEY in input.update.lineage)) {\n return { action: \"accept\" };\n }\n const fence = parseIncidentTelemetryAuthorityFence(input.update.lineage);\n const payload = input.update.payload;\n const taskId = input.update.lineage.scheduledTaskId;\n const runId = payload.type === \"scheduled_occurrence\" ? payload.scheduledTaskRunId : null;\n const reject = async () => {\n if (runId) {\n await markScheduledTaskRunAuthorityRejectedInTransaction(input.db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n runId,\n });\n }\n return {\n action: \"reject\",\n reason: \"incident_responder_under_capable\",\n } as const;\n };\n if (!fence || typeof taskId !== \"string\" || !runId) return await reject();\n\n const session = await requireSession(input.db, input.workspaceId, input.sessionId);\n const acceptedExecution = await getScheduledTaskRunAcceptedExecution(input.db, {\n workspaceId: input.workspaceId,\n runId,\n });\n if (\n !acceptedExecution ||\n acceptedExecution.task.id !== taskId ||\n !acceptedExecution.incidentPreflightRequired\n ) {\n return await reject();\n }\n const task = acceptedExecution.task;\n const personalConnectionDelegations = acceptedExecution.personalConnectionDelegations;\n const responder = await resolveIncidentTelemetryResponderMetadata({\n db: input.db,\n settings: input.settings,\n task,\n session,\n personalConnectionDelegations,\n personalResourceAuthoritySubjectId: acceptedExecution.personalResourceAuthoritySubjectId,\n executionPolicy: acceptedExecution.targetSessionExecution\n ? {\n tools: acceptedExecution.targetSessionExecution.tools,\n firstPartyMcpTools: acceptedExecution.targetSessionExecution.firstPartyMcpTools,\n firstPartyMcpPermissions:\n acceptedExecution.targetSessionExecution.firstPartyMcpPermissions,\n variableSetIds: acceptedExecution.targetSessionExecution.variableSets.map(\n (variableSet) => variableSet.id,\n ),\n variableSetId: acceptedExecution.targetSessionExecution.variableSetId,\n rigId: acceptedExecution.targetSessionExecution.rigId,\n rigVersionId: acceptedExecution.targetSessionExecution.rigVersionId,\n toolPolicy: acceptedExecution.targetSessionExecution.toolPolicy,\n mcpServerIds: acceptedExecution.targetSessionExecution.mcpServerIds,\n toolPolicyVersion: acceptedExecution.targetSessionExecution.toolPolicyVersion,\n }\n : {\n tools: acceptedExecution.resolvedTools,\n firstPartyMcpTools: acceptedExecution.resolvedFirstPartyMcpTools,\n firstPartyMcpPermissions: acceptedExecution.resolvedFirstPartyMcpPermissions,\n variableSetId: acceptedExecution.resolvedVariableSet?.id ?? null,\n rigId: acceptedExecution.resolvedRig?.id ?? null,\n rigVersionId: acceptedExecution.resolvedRig?.versionId ?? null,\n toolPolicy: session.toolPolicy,\n mcpServerIds: [],\n toolPolicyVersion: session.toolPolicyVersion,\n },\n });\n const preflight = evaluateIncidentTelemetryPreflight({\n agentConfig: task.agentConfig,\n incidentTriggered: acceptedExecution.alertOccurrenceLabels !== null,\n alertOccurrenceLabels: acceptedExecution.alertOccurrenceLabels,\n responder,\n });\n if (preflight.action !== \"ready\") return await reject();\n const current = incidentTelemetryAuthorityFence({\n task,\n responder,\n alertOccurrenceLabels: acceptedExecution.alertOccurrenceLabels,\n });\n return current &&\n current.toolPolicyVersion === fence.toolPolicyVersion &&\n current.responderDigest === fence.responderDigest &&\n current.taskDigest === fence.taskDigest &&\n current.alertSelectorDigest === fence.alertSelectorDigest\n ? { action: \"accept\" }\n : await reject();\n}\n","import type { TurnHistorySink } from \"./history-sink\";\nimport type { Settings } from \"@opengeni/config\";\n\nexport class SandboxCapabilitiesChangedError extends Error {\n readonly code = \"native_capabilities_changed_this_attempt\";\n\n constructor() {\n super(\"The attached sandbox requires rebuilding this attempt's native capabilities.\");\n this.name = \"SandboxCapabilitiesChangedError\";\n }\n}\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 route?: {\n effectiveSandboxBackend: Settings[\"sandboxBackend\"];\n routingEnabled: boolean;\n readActiveSandbox: () => Promise<{ activeSandboxId: string | null } | null>;\n },\n): Promise<void> {\n await historySink.reconcileConversationTruth({ requireDurable: true });\n // A plain Agent cannot acquire SandboxAgent capabilities in place. Preserve\n // its completed tool batch before recovering the same logical turn; the next\n // attempt resolves and authorizes the route normally.\n if (route?.effectiveSandboxBackend === \"none\" && route.routingEnabled) {\n const active = await route.readActiveSandbox();\n if (active?.activeSandboxId) throw new SandboxCapabilitiesChangedError();\n }\n}\n","import {\n SandboxLeaseRecoveryBlockedError,\n SandboxLeaseSupersededError,\n SandboxLeaseTransitionError,\n SandboxImageConflictError,\n SandboxRigConflictError,\n} from \"@opengeni/db\";\nimport {\n SandboxConfigError,\n SandboxExactResumeInstanceUnavailableError,\n SandboxExactResumeReplacedError,\n SandboxExecReadinessError,\n SandboxProviderContinuityUnavailableError,\n SandboxProviderUnavailableError,\n SandboxResumeIdentityMismatchError,\n SandboxResumeIdentityUnavailableError,\n SandboxResumeStateUnavailableError,\n WorkspaceArchiveIntegrityError,\n classifyProviderSandboxFailure,\n} from \"@opengeni/runtime\";\nimport { type Settings } from \"@opengeni/config\";\nimport { CancelledFailure } from \"@temporalio/activity\";\nimport {\n sandboxProvisionFailureStage,\n SandboxProvisionStageError,\n SandboxWarmingTimeoutError,\n} from \"../../sandbox-resume\";\nimport {\n type SandboxLogicalProvisionCategory,\n type SandboxLogicalProvisionStage,\n} from \"../../observability-metrics\";\nimport { randomUUID } from \"node:crypto\";\n\nexport type TurnSandboxProvisioner<T> = {\n get(): Promise<T>;\n hasStarted(): boolean;\n waitForSettled(timeoutMs: number): Promise<T | null>;\n};\n\nexport type SandboxLogicalProvisionFailure = {\n category: SandboxLogicalProvisionCategory;\n stage: SandboxLogicalProvisionStage;\n code: string;\n expected: boolean;\n retryable: boolean;\n};\n\nexport type TurnSandboxProvisionAttempt<T = unknown> = {\n provisionId: string;\n attempt: number;\n outcome: \"completed\" | \"retrying\" | \"failed\";\n durationMs: number;\n result?: T;\n error?: unknown;\n};\n\nexport type TurnSandboxProvisionSettlement = {\n provisionId: string;\n internalAttempts: number;\n durationMs: number;\n};\n\nexport class TurnOperationCancelledError extends Error {\n readonly name = \"TurnOperationCancelledError\";\n\n constructor(readonly reason: unknown) {\n super(\"Turn operation was cancelled with its owning turn\", {\n ...(reason instanceof Error ? { cause: reason } : {}),\n });\n }\n}\n\nexport class SandboxDeadlineRotationError extends Error {\n readonly name = \"SandboxDeadlineRotationError\";\n\n constructor(\n readonly sandboxGroupId: string,\n readonly leaseEpoch: number,\n ) {\n super(\n `Sandbox ${sandboxGroupId} reached its provider rotation boundary at lease epoch ${leaseEpoch}`,\n );\n }\n}\n\n/**\n * Normalize a preparation/provisioning cancellation race back to the Temporal\n * cancellation that owns the activity. Several provider APIs expose no portable\n * abort primitive, so the worker stops awaiting them and disposes any late\n * resource. The wrapper error must never fall through as an ordinary turn\n * failure: doing so would omit the quiescence receipt and strand a committed\n * Steer/Pause behind `control-pending`.\n */\nexport function turnOperationCancellationFailure(error: unknown): CancelledFailure | null {\n if (error instanceof CancelledFailure) return error;\n if (!(error instanceof TurnOperationCancelledError)) return null;\n return error.reason instanceof CancelledFailure\n ? error.reason\n : new CancelledFailure(\"TURN_SANDBOX_PROVISION_CANCELLED\", [], error);\n}\n\nexport function throwIfTurnOperationCancelled(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw new TurnOperationCancelledError(signal.reason);\n }\n}\n\nexport async function waitForTurnOperation<T>(\n operation: Promise<T>,\n signal: AbortSignal | undefined,\n disposeLateResult: ((result: T) => Promise<void> | void) | undefined,\n): Promise<T> {\n if (!signal) return await operation;\n\n let rejectCancellation: ((error: TurnOperationCancelledError) => void) | undefined;\n const cancelled = new Promise<never>((_resolve, reject) => {\n rejectCancellation = reject;\n });\n const cancel = (): void => {\n rejectCancellation?.(new TurnOperationCancelledError(signal.reason));\n };\n signal.addEventListener(\"abort\", cancel, { once: true });\n if (signal.aborted) cancel();\n\n try {\n const result = await Promise.race([operation, cancelled]);\n // Cancellation owns an exact turn boundary even when the provider result\n // and AbortSignal settle in the same microtask checkpoint. Never let a\n // just-resolved lease escape after the control was already committed.\n if (signal.aborted) {\n throw new TurnOperationCancelledError(signal.reason);\n }\n return result;\n } catch (error) {\n if (signal.aborted) {\n // The provider establish call has no universal cancellation seam. It may\n // finish after the Temporal activity has correctly stopped; dispose its\n // late lease instead of letting a cancelled turn resurrect a holder/box.\n void operation\n .then(async (result) => await disposeLateResult?.(result))\n .catch(() => undefined);\n // A provider failure may settle in the same checkpoint as the committed\n // control. The control is authoritative; retain its cancellation shape\n // so the activity publishes quiescence instead of looking like an\n // unrelated turn failure.\n if (!(error instanceof TurnOperationCancelledError)) {\n throw new TurnOperationCancelledError(signal.reason);\n }\n }\n throw error;\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n }\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function sandboxProvisionErrorChain(error: unknown): unknown[] {\n const chain: unknown[] = [];\n const seen = new Set<object>();\n let current = error;\n for (let depth = 0; depth < 6; depth += 1) {\n chain.push(current);\n if (!current || typeof current !== \"object\" || seen.has(current)) break;\n seen.add(current);\n if (current instanceof SandboxProvisionStageError) {\n current = current.source;\n continue;\n }\n const cause = Reflect.get(current, \"cause\");\n if (cause === undefined || cause === current) break;\n current = cause;\n }\n return chain;\n}\n\nexport function firstProvisionError<T>(\n chain: readonly unknown[],\n constructor: abstract new (...args: never[]) => T,\n): T | null {\n return chain.find((value): value is T => value instanceof constructor) ?? null;\n}\n\n/**\n * Closed, structural taxonomy for one logical provision failure. The classifier\n * follows only typed wrapper/cause links and provider status/code fields; it\n * never infers lifecycle truth from an arbitrary error message.\n */\nexport function classifySandboxLogicalProvisionFailure(\n backend: string,\n error: unknown,\n): SandboxLogicalProvisionFailure {\n const chain = sandboxProvisionErrorChain(error);\n const wrappedStage =\n chain.map((value) => sandboxProvisionFailureStage(value)).find((stage) => stage !== null) ??\n null;\n const warming =\n chain.find(\n (value): value is SandboxWarmingTimeoutError => value instanceof SandboxWarmingTimeoutError,\n ) ?? null;\n if (warming) {\n const execReadiness = warming.stage === \"exec_readiness\";\n return {\n category: execReadiness ? \"exec_readiness\" : \"sibling_warming\",\n stage: execReadiness ? \"exec_readiness\" : \"sibling_warming\",\n code: warming.code,\n expected: false,\n retryable: false,\n };\n }\n const readiness = firstProvisionError(chain, SandboxExecReadinessError);\n if (readiness) {\n return {\n category: \"exec_readiness\",\n stage: \"exec_readiness\",\n code: readiness.code,\n expected: false,\n retryable: false,\n };\n }\n const superseded = firstProvisionError(chain, SandboxLeaseSupersededError);\n if (superseded) {\n return {\n category: \"lease_superseded\",\n stage: \"lease_admission\",\n code: \"lease_superseded\",\n expected: true,\n retryable: true,\n };\n }\n const transition = firstProvisionError(chain, SandboxLeaseTransitionError);\n if (transition) {\n return {\n category: \"drain_capture_wait\",\n stage: \"lifecycle_wait\",\n code: transition.reason,\n expected: true,\n retryable: true,\n };\n }\n const deadlineRotation = firstProvisionError(chain, SandboxDeadlineRotationError);\n if (deadlineRotation) {\n return {\n category: \"drain_capture_wait\",\n stage: \"lifecycle_wait\",\n code: \"provider_deadline_rotation\",\n expected: true,\n retryable: false,\n };\n }\n const recoveryBlocked = firstProvisionError(chain, SandboxLeaseRecoveryBlockedError);\n if (recoveryBlocked) {\n return {\n category: \"archive_recovery\",\n stage: \"archive_recovery\",\n code: recoveryBlocked.code,\n expected: false,\n retryable: false,\n };\n }\n const archive = firstProvisionError(chain, WorkspaceArchiveIntegrityError);\n if (archive) {\n return {\n category: \"archive_recovery\",\n stage: \"archive_recovery\",\n code: archive.code,\n expected: false,\n retryable: archive.retryable,\n };\n }\n const continuity = firstProvisionError(chain, SandboxProviderContinuityUnavailableError);\n if (continuity) {\n return {\n category: \"archive_recovery\",\n stage: \"archive_recovery\",\n code: \"provider_continuity_unavailable\",\n expected: false,\n retryable: continuity.retryable,\n };\n }\n const configuration = chain.find(\n (value) =>\n value instanceof SandboxConfigError ||\n value instanceof SandboxProviderUnavailableError ||\n value instanceof SandboxImageConflictError ||\n value instanceof SandboxRigConflictError,\n );\n if (configuration) {\n return {\n category: \"configuration\",\n stage: wrappedStage ?? \"configuration\",\n code:\n configuration instanceof SandboxImageConflictError\n ? \"image_conflict\"\n : configuration instanceof SandboxRigConflictError\n ? \"rig_conflict\"\n : configuration instanceof SandboxProviderUnavailableError\n ? \"provider_unavailable\"\n : \"sandbox_config\",\n expected: false,\n retryable: false,\n };\n }\n const resumeFailure = chain.find(\n (value) =>\n value instanceof SandboxResumeStateUnavailableError ||\n value instanceof SandboxResumeIdentityMismatchError ||\n value instanceof SandboxResumeIdentityUnavailableError ||\n value instanceof SandboxExactResumeReplacedError ||\n value instanceof SandboxExactResumeInstanceUnavailableError,\n );\n if (resumeFailure) {\n return {\n category: \"resume\",\n stage: \"resume\",\n code:\n resumeFailure instanceof SandboxResumeStateUnavailableError\n ? \"resume_state_unavailable\"\n : resumeFailure instanceof SandboxResumeIdentityMismatchError\n ? \"resume_identity_mismatch\"\n : resumeFailure instanceof SandboxResumeIdentityUnavailableError\n ? \"resume_identity_unavailable\"\n : resumeFailure instanceof SandboxExactResumeReplacedError\n ? \"exact_resume_replaced\"\n : \"exact_resume_instance_unavailable\",\n expected: false,\n retryable: false,\n };\n }\n const providerFailure = classifyProviderSandboxFailure(backend, error);\n if (providerFailure.kind === \"transient_transport\") {\n return {\n category: \"provider_transport\",\n stage: wrappedStage ?? \"provider_transport\",\n code: providerFailure.diagnostic,\n expected: false,\n // A typed transport fault is attributable, but a create outcome may be\n // ambiguous. Classification never licenses replay on its own.\n retryable: false,\n };\n }\n if (wrappedStage) {\n return {\n category: wrappedStage,\n stage: wrappedStage,\n code: `${wrappedStage}_failed`,\n expected: false,\n retryable: false,\n };\n }\n return {\n category: \"unknown\",\n stage: \"unknown\",\n code: \"unknown\",\n expected: false,\n retryable: false,\n };\n}\n\nexport function isLazySandboxProvisionRetryable(error: unknown): boolean {\n const chain = sandboxProvisionErrorChain(error);\n // Rotation resumes through the durable lifecycle wake. Retrying here holds\n // a turn worker and can repeat the entire lease wait for every skill root.\n if (\n chain.some(\n (value) =>\n value instanceof SandboxLeaseTransitionError && value.reason === \"rotation_in_progress\",\n )\n )\n return false;\n if (\n chain.some(\n (value) =>\n value instanceof SandboxImageConflictError ||\n value instanceof SandboxRigConflictError ||\n value instanceof SandboxLeaseRecoveryBlockedError,\n )\n ) {\n return false;\n }\n const archive = firstProvisionError(chain, WorkspaceArchiveIntegrityError);\n if (archive) {\n return archive.retryable;\n }\n if (\n chain.some(\n (value) =>\n value instanceof SandboxLeaseSupersededError ||\n value instanceof SandboxLeaseTransitionError,\n )\n ) {\n return true;\n }\n if (chain.some((value) => value instanceof SandboxWarmingTimeoutError)) {\n return false;\n }\n // Provider/transport text is not durable evidence that creation never\n // happened. Retrying an ambiguous unknown here can create a second box; only\n // typed, ownership-fenced lifecycle outcomes above are safe to replay.\n return false;\n}\n\n/** Short workflow-visible anti-churn pacing after a lifecycle transition. The\n * next acquire waits on the exact durable claim itself, so this is deliberately\n * not a guessed snapshot-plus-schedules completion time. */\nexport function sandboxDeadlineRotationRecoveryDelayMs(\n settings: Pick<Settings, \"sandboxLeaseReaperPeriodMs\">,\n): number {\n // The next attempt waits on the durable lifecycle claim itself. This delay is\n // only anti-churn pacing, not an estimate of snapshot + future schedules.\n return Math.min(5_000, settings.sandboxLeaseReaperPeriodMs);\n}\n\nexport function createTurnSandboxProvisioner<T>(\n establish: () => Promise<T>,\n options: {\n maxRetries?: number;\n backoffMs?: number;\n signal?: AbortSignal;\n provisionIdFactory?: () => string;\n onStarted?: (\n settlement: Pick<TurnSandboxProvisionSettlement, \"provisionId\">,\n ) => Promise<void> | void;\n onAttemptSettled?: (attempt: TurnSandboxProvisionAttempt<T>) => Promise<void> | void;\n beforeCompleted?: (\n result: T,\n settlement: TurnSandboxProvisionSettlement,\n ) => Promise<void> | void;\n onCompleted?: (result: T, settlement: TurnSandboxProvisionSettlement) => Promise<void> | void;\n onFailed?: (error: unknown, settlement: TurnSandboxProvisionSettlement) => Promise<void> | void;\n disposeResult?: (result: T) => Promise<void> | void;\n } = {},\n): TurnSandboxProvisioner<T> {\n const maxRetries = options.maxRetries ?? 2;\n const backoffMs = options.backoffMs ?? 250;\n let memo: Promise<T> | null = null;\n\n const run = async (\n provisionId: string,\n onAttempt: (attempt: number) => void,\n ): Promise<{ result: T; internalAttempts: number }> => {\n let internalAttempts = 0;\n while (true) {\n internalAttempts += 1;\n onAttempt(internalAttempts);\n const startedAt = performance.now();\n try {\n throwIfTurnOperationCancelled(options.signal);\n const operation = establish();\n const result = await waitForTurnOperation(operation, options.signal, options.disposeResult);\n await options.onAttemptSettled?.({\n provisionId,\n attempt: internalAttempts,\n outcome: \"completed\",\n durationMs: performance.now() - startedAt,\n result,\n });\n return { result, internalAttempts };\n } catch (error) {\n const retrying = !(\n error instanceof TurnOperationCancelledError ||\n internalAttempts > maxRetries ||\n !isLazySandboxProvisionRetryable(error)\n );\n await options.onAttemptSettled?.({\n provisionId,\n attempt: internalAttempts,\n outcome: retrying ? \"retrying\" : \"failed\",\n durationMs: performance.now() - startedAt,\n error,\n });\n if (!retrying) {\n throw error;\n }\n await sleep(backoffMs * internalAttempts);\n }\n }\n };\n\n return {\n get(): Promise<T> {\n if (!memo) {\n const provisionId = options.provisionIdFactory?.() ?? randomUUID();\n memo = (async () => {\n const startedAt = performance.now();\n throwIfTurnOperationCancelled(options.signal);\n await options.onStarted?.({ provisionId });\n throwIfTurnOperationCancelled(options.signal);\n let result: T | undefined;\n let internalAttempts = 0;\n let hasResult = false;\n try {\n const runResult = await run(provisionId, (attempt) => {\n internalAttempts = attempt;\n });\n result = runResult.result;\n internalAttempts = runResult.internalAttempts;\n hasResult = true;\n throwIfTurnOperationCancelled(options.signal);\n await options.beforeCompleted?.(result, {\n provisionId,\n internalAttempts,\n durationMs: performance.now() - startedAt,\n });\n throwIfTurnOperationCancelled(options.signal);\n await options.onCompleted?.(result, {\n provisionId,\n internalAttempts,\n durationMs: performance.now() - startedAt,\n });\n return result;\n } catch (error) {\n if (hasResult) {\n await options.disposeResult?.(result as T);\n }\n if (!(error instanceof TurnOperationCancelledError)) {\n await options.onFailed?.(error, {\n provisionId,\n internalAttempts: Math.max(1, internalAttempts),\n durationMs: performance.now() - startedAt,\n });\n }\n throw error;\n }\n })().catch((error) => {\n // A terminal lease/archive/configuration result cannot change within\n // this frozen turn. Keep its rejected promise memoized so later model\n // tool calls observe the same typed result without re-entering\n // provisioning, emitting another failure event, or creating another\n // provider attempt. Only a retryable failure releases the single-flight\n // for a later operation to re-read the lease/provider state.\n if (isLazySandboxProvisionRetryable(error)) {\n memo = null;\n }\n throw error;\n });\n }\n return memo;\n },\n hasStarted(): boolean {\n return memo !== null;\n },\n async waitForSettled(timeoutMs: number): Promise<T | null> {\n if (!memo) {\n return null;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n memo.catch(() => null),\n new Promise<null>((resolve) => {\n timer = setTimeout(() => resolve(null), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n },\n };\n}\n\n/**\n * Decide whether THIS turn may send OpenAI's `prompt_cache_key` request field.\n *\n * Accepted transports:\n * - legacy/built-in OpenAI or Azure Responses fallback (resolvedModel null);\n * - resolved built-in OpenAI/Azure providers;\n * - ChatGPT/Codex subscription backend (its strict allowlist permits the field).\n * - native Anthropic Messages (maps the internal key to Claude session identity;\n * the OpenAI field is never sent on that wire).\n *\n * Other registry API-key providers are intentionally excluded. Fireworks' prompt-cache\n * docs prescribe `user` or `x-session-affinity`, not `prompt_cache_key`; Z.AI/GLM\n * documents automatic context caching plus `user_id`. Sending OpenAI-only fields\n * to unknown OpenAI-compatible providers risks unsupported-parameter 400s.\n */\n","import { type SessionAttemptQuiescenceCommit } from \"@opengeni/db\";\nimport { type TurnToolCancellationFence } from \"@opengeni/runtime\";\nimport { type GitCredentialRenewalController } from \"../git-credential-renewal\";\nimport { type RunCredentialRenewalController } from \"../run-credential-renewal\";\nimport { type CodemodeTokenRenewalController } from \"../codemode-token-renewal\";\nimport type {\n TurnActivityServices as ActivityServices,\n RunAgentTurnResult,\n SessionAttemptQuiescenceProof,\n} from \"../types\";\nimport { type ResumedTurnSandbox } from \"../../sandbox-resume\";\nimport { type SessionEvent } from \"@opengeni/contracts\";\nimport { sleep } from \"./sandbox-provision\";\n\nexport function shouldRunTurnEndWorkspacePersistence(input: {\n activityStatus: RunAgentTurnResult[\"status\"] | \"unknown\";\n cancellationRequested: boolean;\n deadlineRotationRequested?: boolean;\n}): boolean {\n return (\n input.activityStatus !== \"cancelled\" &&\n !input.cancellationRequested &&\n input.deadlineRotationRequested !== true\n );\n}\n\n/**\n * Periodic workspace snapshots protect work performed during a long-running\n * turn. Before the first provider request reaches the wire there is no\n * mid-turn agent work to protect; snapshotting platform setup at that point can\n * instead make the request wait behind the snapshot's workspace-write fence.\n */\nexport function shouldStartPeriodicWorkspaceSnapshot(input: {\n firstProviderRequestStarted: boolean;\n snapshotInFlight: boolean;\n turnEndCaptureInProgress: boolean;\n deadlineRotationRequested: boolean;\n}): boolean {\n return (\n input.firstProviderRequestStarted &&\n !input.snapshotInFlight &&\n !input.turnEndCaptureInProgress &&\n !input.deadlineRotationRequested\n );\n}\n\n/**\n * Temporal cancellation is delivery/transport state, never proof that the\n * dying activity crossed its mandatory sandbox-tool fence. If that fence\n * fails, surface the fence failure instead of retaining a misleading typed\n * cancellation; replacement admission remains closed because no durable\n * quiescence receipt was written.\n */\nexport function assertPhysicalToolQuiescenceForCancellation(input: {\n acknowledgeQuiescence: boolean;\n physicalToolQuiescenceConfirmed: boolean;\n failure: unknown;\n}): void {\n if (!input.acknowledgeQuiescence || input.physicalToolQuiescenceConfirmed) return;\n if (input.failure instanceof Error) throw input.failure;\n throw new Error(\"Physical sandbox-tool quiescence could not be confirmed\", {\n cause: input.failure,\n });\n}\n\n/** A physically drained attempt must leave one durable recovery producer. The\n * direct Postgres receipt is preferred; after its bounded retries exhaust, an\n * exact Temporal proof signal is sufficient because the workflow persists it\n * through an independently retrying DB-only control activity. */\nexport function assertSessionAttemptQuiescenceRecoveryDurable(input: {\n acknowledgeQuiescence: boolean;\n physicalToolQuiescenceConfirmed: boolean;\n receiptOrProofDurable: boolean;\n failure: unknown;\n}): void {\n if (\n !input.acknowledgeQuiescence ||\n !input.physicalToolQuiescenceConfirmed ||\n input.receiptOrProofDurable\n ) {\n return;\n }\n if (input.failure instanceof Error) throw input.failure;\n throw new Error(\"Physical quiescence had no durable receipt or recovery proof\", {\n cause: input.failure,\n });\n}\n\nexport const QUIESCENCE_PROOF_SIGNAL_INITIAL_RETRY_MS = 250;\nexport const QUIESCENCE_PROOF_SIGNAL_MAX_RETRY_MS = 5_000;\nexport const TURN_QUIESCENCE_WATCHDOG_MS = 5 * 60_000;\nexport const TURN_FINALIZER_STEP_TIMEOUT_MS = 30_000;\n\n/** A fenced activity must never heartbeat forever while its physical writer\n * drain is stuck. The last-resort worker exit stops every in-process writer;\n * Kubernetes replaces the pod and the workflow's heartbeat-lease reconciler\n * then commits the exact quiescence receipt. */\nexport function armTurnQuiescenceWatchdog(input: {\n enabled: boolean;\n timeoutMs?: number;\n onTimeout?: () => void;\n terminateWorker: () => void;\n}): () => void {\n if (!input.enabled) return () => undefined;\n let armed = true;\n const timer = setTimeout(() => {\n if (!armed) return;\n input.onTimeout?.();\n input.terminateWorker();\n }, input.timeoutMs ?? TURN_QUIESCENCE_WATCHDOG_MS);\n timer.unref?.();\n return () => {\n if (!armed) return;\n armed = false;\n clearTimeout(timer);\n };\n}\n\n/** Persist the authoritative receipt or durably hand the exact physical proof\n * to Temporal. This retries signal delivery, not DB eligibility or workflow\n * state. The proof object never changes between attempts. */\nexport async function persistOrSignalSessionAttemptQuiescence(input: {\n proof: SessionAttemptQuiescenceProof;\n persistReceipt: () => Promise<SessionAttemptQuiescenceCommit>;\n deliverWorkflowWake?: (\n wake: NonNullable<SessionAttemptQuiescenceCommit[\"workflowWake\"]>,\n ) => Promise<unknown>;\n publishEvents: (events: SessionEvent[]) => Promise<unknown>;\n signalProof: ActivityServices[\"signalSessionAttemptQuiesced\"];\n sleep?: (ms: number) => Promise<void>;\n heartbeat?: (attempt: number, delayMs: number) => void;\n onReceiptFailure?: (error: unknown) => void;\n onWakeFailure?: (error: unknown) => void;\n onPublishFailure?: (error: unknown) => void;\n onSignalFailure?: (error: unknown, attempt: number, delayMs: number) => void;\n}): Promise<\"receipt\" | \"signal\"> {\n let receipt: SessionAttemptQuiescenceCommit;\n try {\n receipt = await input.persistReceipt();\n } catch (receiptError) {\n input.onReceiptFailure?.(receiptError);\n if (!input.signalProof) {\n throw new Error(\"Session-attempt quiescence proof signaler is unavailable\", {\n cause: receiptError,\n });\n }\n const delay = input.sleep ?? sleep;\n let retryMs = QUIESCENCE_PROOF_SIGNAL_INITIAL_RETRY_MS;\n let attempt = 1;\n for (;;) {\n try {\n await input.signalProof(input.proof);\n return \"signal\";\n } catch (signalError) {\n input.onSignalFailure?.(signalError, attempt, retryMs);\n try {\n input.heartbeat?.(attempt, retryMs);\n } catch {\n // Heartbeat telemetry is not proof delivery and cannot replace or\n // interrupt the exact signal retry loop.\n }\n await delay(retryMs);\n retryMs = Math.min(retryMs * 2, QUIESCENCE_PROOF_SIGNAL_MAX_RETRY_MS);\n attempt += 1;\n }\n }\n }\n\n if (receipt.workflowWake && input.deliverWorkflowWake) {\n try {\n await input.deliverWorkflowWake(receipt.workflowWake);\n } catch (wakeError) {\n // The exact revision is already durable. Immediate delivery is latency\n // optimization only; the outbox dispatcher remains the repair path.\n input.onWakeFailure?.(wakeError);\n }\n }\n try {\n await input.publishEvents(receipt.events);\n } catch (publishError) {\n // Postgres already committed quiesced_at, the queue event, and the wake.\n // NATS is live fanout only; never misclassify its failure as receipt loss.\n input.onPublishFailure?.(publishError);\n }\n return \"receipt\";\n}\n\n/**\n * Cross the non-detachable physical boundary for one dying attempt. Temporal's\n * cancellation signal is intentionally absent: cancellation is transport, not\n * proof that sandbox tools and attempt-owned credential writers have drained.\n * A replacement may be admitted only after this function resolves and the\n * caller durably persists or signals the exact quiescence receipt.\n */\nexport async function drainAttemptOwnedSandboxWriters(input: {\n toolCancellationFence: Pick<TurnToolCancellationFence, \"cancel\" | \"waitForQuiescence\"> | null;\n cancellationReason?: unknown;\n gitCredentialRenewals: readonly Pick<GitCredentialRenewalController, \"stop\">[];\n codemodeTokenRenewal: Pick<CodemodeTokenRenewalController, \"stop\"> | null;\n runCredentialRenewal: Pick<RunCredentialRenewalController, \"stop\"> | null;\n onStage?: (stage: \"tool_writers\" | \"credential_renewals\") => void;\n}): Promise<void> {\n input.onStage?.(\"tool_writers\");\n if (input.toolCancellationFence) {\n input.toolCancellationFence.cancel(\n input.cancellationReason ?? new Error(\"TURN_ATTEMPT_FENCED\"),\n );\n await input.toolCancellationFence.waitForQuiescence();\n }\n input.onStage?.(\"credential_renewals\");\n await Promise.all(input.gitCredentialRenewals.map(async (renewal) => await renewal.stop()));\n await input.codemodeTokenRenewal?.stop();\n await input.runCredentialRenewal?.stop();\n}\n\n/** Persist the exact turn's second-stage release only after the caller has\n * crossed the physical writer boundary. This wait is intentionally independent\n * of Temporal cancellation: it is a short idempotent DB transaction that closes\n * the durable archive-capture fence. Bounded retries cover a rollout connection\n * reset without turning ordinary finalizer housekeeping into lifecycle state. */\nexport async function releaseTurnSandboxAfterWriterDrain(\n sandbox: Pick<ResumedTurnSandbox, \"release\">,\n options: {\n maxAttempts?: number;\n retryDelayMs?: number;\n wait?: (delayMs: number) => Promise<void>;\n } = {},\n): Promise<void> {\n const maxAttempts = Math.max(1, options.maxAttempts ?? 3);\n const retryDelayMs = Math.max(0, options.retryDelayMs ?? 50);\n const wait = options.wait ?? sleep;\n let lastError: unknown;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n try {\n await sandbox.release({ workspaceWritersQuiesced: true });\n return;\n } catch (error) {\n lastError = error;\n if (attempt < maxAttempts) {\n await wait(retryDelayMs * attempt);\n }\n }\n }\n throw lastError;\n}\n\n/**\n * Await bounded, idempotent finalizer housekeeping only while this Temporal\n * activity still owns its execution window. A completed turn must never keep\n * heartbeating forever because a provider/tool close promise did not settle:\n * that strands every later durable prompt behind an already-terminal attempt.\n * Cancellation or the hard timeout detaches the operation with a rejection\n * handler; the operation may still finish its attempt-scoped cleanup, but it\n * cannot pin activity terminalization.\n */\nexport async function waitForTurnFinalizerStep<T>(\n operation: Promise<T>,\n signal: AbortSignal | undefined,\n timeoutMs = TURN_FINALIZER_STEP_TIMEOUT_MS,\n): Promise<T | undefined> {\n if (signal?.aborted) {\n void operation.catch(() => undefined);\n return undefined;\n }\n\n let resolveDetached: (() => void) | undefined;\n const detached = new Promise<undefined>((resolve) => {\n resolveDetached = () => resolve(undefined);\n });\n const detach = (): void => {\n void operation.catch(() => undefined);\n resolveDetached?.();\n };\n signal?.addEventListener(\"abort\", detach, { once: true });\n const timeout = setTimeout(detach, Math.max(1, timeoutMs));\n timeout.unref?.();\n try {\n return await Promise.race([operation, detached]);\n } finally {\n clearTimeout(timeout);\n signal?.removeEventListener(\"abort\", detach);\n }\n}\n\n/**\n * Flush provider-facing stream state while the attempt still owns its activity\n * window. On Pause/Steer, both promises are detached with rejection handlers:\n * neither a runtime batcher nor an uncooperative provider completion promise\n * may pin the activity behind cancellation after durable writes are fenced.\n */\nexport async function waitForTurnStreamCleanup(\n batcherFlush: Promise<unknown>,\n providerCompleted: Promise<unknown>,\n signal: AbortSignal | undefined,\n): Promise<void> {\n await waitForTurnFinalizerStep(batcherFlush, signal);\n await waitForTurnFinalizerStep(providerCompleted, signal);\n}\n\nexport class IncompleteAgentStreamError extends Error {\n readonly name = \"IncompleteAgentStreamError\";\n\n constructor(message = \"Agent stream ended without a successful terminal output\") {\n super(message);\n }\n}\n\n/**\n * Prove that SDK completion authority did not report a failure or runtime\n * cancellation. The Agents SDK closes its ReadableStream immediately when its\n * run signal aborts, so iterator EOF is not completion authority: the separate\n * `completed` promise carries the eventual run failure.\n *\n * Only Temporal cancellation detaches cleanup. Internal runtime cancellation\n * such as a provider-deadline sandbox rotation must escape to the turn failure\n * settlement path, which checkpoints and redispatches the same logical turn.\n */\nexport async function assertSuccessfulAgentStreamCompletion(input: {\n batcherFlush: Promise<unknown>;\n stream: {\n completed: Promise<void>;\n error: unknown;\n };\n temporalCancellationSignal: AbortSignal | undefined;\n runtimeCancellationSignal: AbortSignal;\n}): Promise<void> {\n await waitForTurnStreamCleanup(\n input.batcherFlush,\n input.stream.completed,\n input.temporalCancellationSignal,\n );\n\n if (input.runtimeCancellationSignal.aborted) {\n throw (\n input.runtimeCancellationSignal.reason ??\n new IncompleteAgentStreamError(\"Agent stream was cancelled without a terminal reason\")\n );\n }\n if (input.stream.error !== null && input.stream.error !== undefined) {\n throw input.stream.error;\n }\n}\n\n/** Call after any more-specific empty-stream recovery has had priority. */\nexport function assertAgentStreamNotCancelled(cancelled: boolean): void {\n if (cancelled) {\n throw new IncompleteAgentStreamError(\"Agent stream was cancelled without a terminal result\");\n }\n}\n\n/** Interruption streams do not produce a normal final output. Call this only\n * after the interruption branch has settled any required action. A successful\n * runtime-owned input wait is a normal terminal result without assistant text;\n * its authority comes from prepared tools, never the provider's output. */\nexport function requireAgentStreamFinalOutput(\n finalOutput: unknown | undefined,\n inputWaitYielded = false,\n): unknown {\n if (inputWaitYielded) return \"\";\n if (finalOutput === undefined) {\n throw new IncompleteAgentStreamError();\n }\n return finalOutput;\n}\n\n/**\n * Terminal settlement closes the active attempt before turn finalization. The\n * ordinary workspace admission therefore correctly returns `attempt_fenced`\n * for the final attempt-qualified credential deletion. Retry only that exact\n * settled-attempt case directly; every other fence/status and the direct\n * deletion itself remain fail-closed.\n */\nexport async function clearAttemptCredentialsWithSettledFence(input: {\n activityStatus: RunAgentTurnResult[\"status\"] | \"unknown\";\n runWorkspaceFencedClear: () => Promise<void>;\n clearExactAttempt: () => Promise<void>;\n onSettledAttemptFence: () => void;\n}): Promise<void> {\n try {\n await input.runWorkspaceFencedClear();\n } catch (error) {\n const settledAttemptFence =\n error instanceof Error &&\n error.name === \"SandboxWorkspaceMutationFencedError\" &&\n (error as Error & { code?: unknown }).code === \"attempt_fenced\" &&\n (input.activityStatus === \"idle\" ||\n input.activityStatus === \"failed\" ||\n input.activityStatus === \"cancelled\");\n if (!settledAttemptFence) throw error;\n input.onSettledAttemptFence();\n await input.clearExactAttempt();\n }\n}\n\nexport function turnFinalizerCancellationSignal(\n temporalSignal: AbortSignal | undefined,\n activityStatus: RunAgentTurnResult[\"status\"] | \"unknown\",\n): AbortSignal | undefined {\n if (activityStatus !== \"cancelled\" || temporalSignal?.aborted) return temporalSignal;\n const fenced = new AbortController();\n fenced.abort(new Error(\"TURN_ATTEMPT_FENCED\"));\n return fenced.signal;\n}\n\nexport type MandatoryHistoryPersistenceStage = \"history_append\" | \"sandbox_envelope\";\n\n/**\n * Preserve the exact storage failure for the permission-controlled turn event\n * while attaching only a stable, non-secret operation token to public worker\n * diagnostics. Mandatory history failures remain terminal and never inherit a\n * provider-retry classification from coincidental source text or status.\n */\nexport class MandatoryHistoryPersistenceError extends Error {\n readonly name = \"MandatoryHistoryPersistenceError\";\n readonly cause: unknown;\n\n constructor(\n readonly stage: MandatoryHistoryPersistenceStage,\n cause: unknown,\n ) {\n super(cause instanceof Error ? cause.message : String(cause));\n this.cause = cause;\n }\n}\n\nexport async function runMandatoryHistoryPersistenceStep<T>(\n stage: MandatoryHistoryPersistenceStage,\n operation: () => Promise<T>,\n): Promise<T> {\n try {\n return await operation();\n } catch (cause) {\n throw new MandatoryHistoryPersistenceError(stage, cause);\n }\n}\n\nexport type OpStreamFinalizer = {\n finalizeOpStreamOps(): Promise<void>;\n};\n\n/** Release retained Connected Machine output only after the turn is durable. */\nexport async function finalizeDurableTurnOpStreams(\n sessions: readonly unknown[],\n fallback: OpStreamFinalizer | null,\n): Promise<void> {\n const candidates = new Set<OpStreamFinalizer>();\n for (const session of sessions) {\n const candidate = session as Partial<OpStreamFinalizer> | null;\n if (typeof candidate?.finalizeOpStreamOps === \"function\") {\n candidates.add(candidate as OpStreamFinalizer);\n }\n }\n if (candidates.size === 0 && fallback) {\n candidates.add(fallback);\n }\n for (const candidate of candidates) {\n try {\n await candidate.finalizeOpStreamOps();\n } catch {\n // The runner's retention TTL owns the fallback.\n }\n }\n}\n","import { SandboxCapabilitiesChangedError } from \"./provider-dispatch-barrier\";\nimport {\n ActiveSessionHistoryLimitExceededError,\n ApprovalRunStateLimitExceededError,\n nestedPostgresSqlState,\n databaseFailureCode,\n isRetryablePersistenceSqlState,\n safeDatabaseErrorFacts,\n isRetryableDatabaseTransportFailure,\n isSessionEventPersistenceError,\n SandboxLeaseTransitionError,\n} from \"@opengeni/db\";\nimport {\n ActiveBackendUnresolvableError,\n CompactionProviderResponseError,\n EmptyCompactionSummaryError,\n compactionProviderRejection,\n describeCompactionProviderRejection,\n type CompactionProviderRejection,\n isMcpRequestTimeoutError,\n isMcpTransportConnectivityError,\n isModalTaskExecStartPreDispatchUnavailableError,\n isModalCommandStartOutcomeUnknownError,\n isRoutingMutationOutcomeUnknownError,\n RoutingWorkspaceRootChangedError,\n ResponsesStreamingTerminalError,\n SandboxMaterializationVerificationError,\n materializationVerificationDiagnostic,\n type MaterializationVerificationDiagnostic,\n PROVIDER_QUOTA_EXHAUSTED_CODE,\n type ProviderQuotaExhaustion,\n type ProviderQuotaScope,\n classifyProviderQuotaError,\n providerQuotaExhaustedMessage,\n SelfhostedWorkspaceRootChangedError,\n UNKNOWN_MODEL_FINISH_REASON_CODE,\n} from \"@opengeni/runtime\";\nimport {\n mcpTransportRequestFailureDiagnostic,\n type McpTransportRequestFailureDiagnostic,\n} from \"@opengeni/runtime/mcp-network\";\nimport { ApplicationFailure, CancelledFailure } from \"@temporalio/activity\";\nimport { CODEX_USAGE_EXHAUSTED_PCT } from \"../codex-rotation\";\nimport { RetainedAttachmentTransportLimitError } from \"../run-input\";\nimport type { CodexAccountStatus } from \"@opengeni/db\";\nimport {\n CODEX_USAGE_LIMIT_ERROR_TYPE,\n CodexReloginRequired,\n classifyCodexEncryptedArtifactRejection,\n classifyCodexEntitlementRejection,\n classifyCodexResponseTimeoutError,\n classifyCodexUsageLimitError,\n isCodexTransportError,\n} from \"@opengeni/codex\";\nimport {\n CodexPlanEntitlementError,\n codexPlanEntitlementFailurePayload,\n codexRequestRejectedFailurePayload,\n} from \"./codex-plan-entitlement\";\nimport {\n classifyXaiSubscriptionStreamingTerminalError,\n classifyXaiSubscriptionStreamIdleTimeoutError,\n isXaiSubscriptionHostedToolContinuationError,\n isXaiSubscriptionRateLimitDiagnostic,\n isXaiSubscriptionTransportError,\n XaiSubscriptionReloginRequired,\n} from \"@opengeni/xai-subscription\";\nimport type {\n EscapedMcpTimeoutRecoveryDetail,\n PostClaimDatabaseRecoveryDetail,\n PreClaimFailureDetail,\n} from \"../types\";\nimport {\n ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_MESSAGE,\n ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_TYPE,\n POST_CLAIM_DATABASE_RECOVERY_FAILURE_MESSAGE,\n POST_CLAIM_DATABASE_RECOVERY_FAILURE_TYPE,\n PRE_CLAIM_FAILURE_MESSAGE,\n PRE_CLAIM_FAILURE_TYPE,\n} from \"../types\";\nimport {\n MandatoryHistoryPersistenceError,\n type MandatoryHistoryPersistenceStage,\n} from \"./quiescence\";\n\n// Retryable provider connectivity/5xx failures start quickly and back off to\n// this ceiling. Explicit rate limits retain the minute-granular fallback.\nexport const PROVIDER_BACKPRESSURE_DELAY_MS = 60_000;\nexport const PROVIDER_CONNECTIVITY_BACKOFF_MS = [2_000, 5_000, 15_000, 30_000, 60_000] as const;\nexport const MAX_AUTOMATIC_PROVIDER_RECOVERIES = PROVIDER_CONNECTIVITY_BACKOFF_MS.length;\n/**\n * Minimum wait per rate-limited recovery. Providers such as Azure OpenAI often\n * answer a per-minute token limit with a `retry-after` of about a second, which\n * alone would spend every automatic recovery before the window resets.\n */\nexport const PROVIDER_RATE_LIMIT_BACKOFF_MS = [10_000, 20_000, 40_000, 60_000, 120_000] as const;\nexport const POST_COMPACTION_CONTINUATION_EMPTY_CODE = \"post_compaction_continuation_empty\";\n\nexport class PostCompactionContinuationEmptyError extends Error {\n readonly code = POST_COMPACTION_CONTINUATION_EMPTY_CODE;\n\n constructor() {\n super(\"Post-compaction continuation stream ended before a terminal model response\");\n this.name = \"PostCompactionContinuationEmptyError\";\n }\n}\n\nexport type ProviderRecoveryResult =\n | {\n status: \"recovering\";\n continueDelayMs: number;\n }\n | {\n status: \"exhausted\";\n providerRecoveryCount: number;\n maxProviderRecoveryCount: number;\n };\n\nexport function providerRecoveryResult(input: {\n failureCode: string | undefined;\n attemptNumber: number;\n retryAfterMs?: number | null;\n}): ProviderRecoveryResult {\n if (input.attemptNumber > MAX_AUTOMATIC_PROVIDER_RECOVERIES) {\n return {\n status: \"exhausted\",\n providerRecoveryCount: MAX_AUTOMATIC_PROVIDER_RECOVERIES,\n maxProviderRecoveryCount: MAX_AUTOMATIC_PROVIDER_RECOVERIES,\n };\n }\n const providerDelay =\n input.retryAfterMs !== null &&\n input.retryAfterMs !== undefined &&\n Number.isFinite(input.retryAfterMs) &&\n input.retryAfterMs > 0\n ? Math.ceil(input.retryAfterMs)\n : null;\n const continueDelayMs =\n input.failureCode === \"provider_rate_limited\"\n ? Math.max(\n providerDelay ?? PROVIDER_BACKPRESSURE_DELAY_MS,\n PROVIDER_RATE_LIMIT_BACKOFF_MS[\n Math.min(\n Math.max(Math.trunc(input.attemptNumber) - 1, 0),\n PROVIDER_RATE_LIMIT_BACKOFF_MS.length - 1,\n )\n ]!,\n )\n : input.failureCode === \"provider_unavailable\" ||\n input.failureCode === \"upstream_connectivity_unavailable\" ||\n input.failureCode === \"sandbox_command_start_unavailable\" ||\n input.failureCode === \"mcp_transport_timeout\" ||\n input.failureCode === \"mcp_transport_unavailable\" ||\n input.failureCode === \"turn_execution_policy_definition_mismatch\" ||\n input.failureCode === POST_COMPACTION_CONTINUATION_EMPTY_CODE\n ? Math.max(\n providerDelay ?? 0,\n PROVIDER_CONNECTIVITY_BACKOFF_MS[\n Math.min(\n Math.max(Math.trunc(input.attemptNumber) - 1, 0),\n PROVIDER_CONNECTIVITY_BACKOFF_MS.length - 1,\n )\n ]!,\n )\n : PROVIDER_BACKPRESSURE_DELAY_MS;\n return {\n status: \"recovering\",\n continueDelayMs,\n };\n}\n\nexport function providerRecoveryExhaustedFailure<\n T extends Record<string, unknown> & { error: string },\n>(\n failure: T,\n recovery: Extract<ProviderRecoveryResult, { status: \"exhausted\" }>,\n): T & {\n retryable: false;\n recoveryExhausted: true;\n providerRecoveryCount: number;\n maxProviderRecoveryCount: number;\n lastRetryableError: string;\n} {\n return {\n ...failure,\n error: `Automatic same-turn recovery stopped after ${recovery.providerRecoveryCount} retries because the upstream dependency remained unavailable. Send a new message to retry after the dependency recovers.`,\n retryable: false,\n recoveryExhausted: true,\n providerRecoveryCount: recovery.providerRecoveryCount,\n maxProviderRecoveryCount: recovery.maxProviderRecoveryCount,\n lastRetryableError: failure.error,\n };\n}\n\nexport function providerRecoveryCountFromMetadata(metadata: Record<string, unknown>): number {\n const value = metadata.providerRecoveryCount;\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 ? value : 0;\n}\n\nexport function providerRecoveryCountAfterModelRequestPhase(\n currentCount: number,\n phase: string,\n): number {\n return phase === \"completed\" ? 0 : currentCount;\n}\n\nexport function headerValue(headers: unknown, name: string): string | null {\n if (!headers || typeof headers !== \"object\") return null;\n const getter = (headers as { get?: unknown }).get;\n if (typeof getter === \"function\") {\n const value = getter.call(headers, name);\n return typeof value === \"string\" ? value : null;\n }\n const target = name.toLowerCase();\n const entry = Object.entries(headers as Record<string, unknown>).find(\n ([key, value]) => key.toLowerCase() === target && typeof value === \"string\",\n );\n return typeof entry?.[1] === \"string\" ? entry[1] : null;\n}\n\n/** Read a provider Retry-After hint without retaining response headers/body. */\nexport function providerRetryAfterMs(error: unknown, nowMs = Date.now()): number | null {\n let current: unknown = error;\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n const value = current as Record<string, unknown>;\n const body =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : null;\n const directSeconds = Number(\n value.retry_after_seconds ?? body?.retry_after_seconds ?? value.retryAfterSeconds,\n );\n const header =\n headerValue(value.headers, \"retry-after\") ??\n headerValue(value.responseHeaders, \"retry-after\") ??\n headerValue(body?.headers, \"retry-after\");\n const headerSeconds = header === null ? Number.NaN : Number(header);\n const headerDate =\n header !== null && !Number.isFinite(headerSeconds) ? Date.parse(header) : Number.NaN;\n const seconds = Number.isFinite(directSeconds)\n ? directSeconds\n : Number.isFinite(headerSeconds)\n ? headerSeconds\n : Number.isFinite(headerDate)\n ? Math.max(0, (headerDate - nowMs) / 1_000)\n : Number.NaN;\n if (Number.isFinite(seconds) && seconds > 0) return Math.ceil(seconds * 1_000);\n current = value.cause;\n }\n return null;\n}\n\n/**\n * Tell the model when durable MCP policy references are unavailable for this\n * exact turn. The policy projection already bounds and validates these ids;\n * this notice prevents a graceful runtime drop from becoming a silent source-\n * of-truth substitution or a false claim that the disconnected system was read.\n */\nexport function unavailableMcpOperationalContext(input: {\n droppedIds: readonly string[];\n droppedCount: number;\n}): string | undefined {\n if (input.droppedCount <= 0) {\n return undefined;\n }\n const omittedCount = Math.max(0, input.droppedCount - input.droppedIds.length);\n const listed = input.droppedIds.map((id) => `\"${id}\"`).join(\", \");\n const inventory = listed\n ? `${listed}${omittedCount > 0 ? `, plus ${omittedCount} additional unavailable server(s)` : \"\"}`\n : `${input.droppedCount} unavailable server(s)`;\n return `MCP capability availability for this turn: the following session-selected server(s) are disconnected or no longer registered and were skipped: ${inventory}. Do not claim to have read or updated those systems. If the task depends on one as a source of truth, explain the limitation and ask the user to reconnect it or select another authoritative source; continue with unaffected work only when safe.`;\n}\n\n/**\n * Preserve one precise recovery obligation across Temporal's activity boundary.\n * This is intentionally narrower than the ordinary retryable-provider path:\n * only a recovered turn (generation > 1) whose MCP timeout happened before a\n * model request may ask the workflow's DB-only control activity to finish the\n * same-turn checkpoint. The original transport/recovery errors are excluded\n * from details so raw MCP response data can never enter workflow history.\n */\nexport function escapedMcpTimeoutRecoveryFailure(input: {\n failureCode: string | undefined;\n modelRequestStarted: boolean;\n detail: EscapedMcpTimeoutRecoveryDetail;\n}): ApplicationFailure | null {\n if (\n input.failureCode !== \"mcp_transport_timeout\" ||\n input.modelRequestStarted ||\n !Number.isSafeInteger(input.detail.executionGeneration) ||\n input.detail.executionGeneration <= 1 ||\n !Number.isSafeInteger(input.detail.providerRecoveryCount) ||\n input.detail.providerRecoveryCount <= 0 ||\n input.detail.providerRecoveryCount > MAX_AUTOMATIC_PROVIDER_RECOVERIES ||\n !Number.isSafeInteger(input.detail.continueDelayMs) ||\n input.detail.continueDelayMs <= 0\n ) {\n return null;\n }\n return ApplicationFailure.create({\n message: ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_MESSAGE,\n type: ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_TYPE,\n nonRetryable: true,\n details: [input.detail],\n });\n}\n\n/**\n * Convert the atomic claim transaction's failure into a small, stable\n * Temporal wire contract. The original error remains in activity diagnostics,\n * but SQL text, parameters, and arbitrary invariant messages never enter\n * workflow history. Operational failures retry; other persistence rejections\n * retain accepted work behind a durable explicit-recheck fence. Repeating the\n * same rejected transaction without changed conditions is not recovery.\n */\nexport function preClaimAdmissionFailure(error: unknown): ApplicationFailure {\n const persistenceFailure = isSessionEventPersistenceError(error) ? error : null;\n const retryableCode = retryableDatabaseFailureCode(error);\n const rejectedClaim =\n persistenceFailure?.details.stage === \"session_attempts.claim\" &&\n persistenceFailure.details.retryOutcome === \"not_retryable\" &&\n !retryableCode;\n const detail: PreClaimFailureDetail = {\n disposition: rejectedClaim\n ? \"blocked\"\n : persistenceFailure || retryableCode\n ? \"retryable\"\n : \"permanent\",\n code: retryableCode ?? persistenceFailure?.details.code ?? \"claim_invariant\",\n ...(persistenceFailure && rejectedClaim\n ? {\n sqlState: persistenceFailure.details.sqlState,\n reason:\n persistenceFailure.details.stage === \"session_attempts.claim\" &&\n persistenceFailure.details.sqlState === \"OG001\"\n ? (\"initiator_membership_required\" as const)\n : persistenceFailure.details.stage === \"session_attempts.claim\" &&\n persistenceFailure.details.sqlState === \"OG002\"\n ? (\"personal_resource_grant_required\" as const)\n : (\"database_claim_rejected\" as const),\n retryPolicy: \"explicit_recheck\" as const,\n }\n : {}),\n };\n return ApplicationFailure.create({\n message: PRE_CLAIM_FAILURE_MESSAGE,\n type: PRE_CLAIM_FAILURE_TYPE,\n nonRetryable: true,\n details: [detail],\n });\n}\n\nfunction retryableDatabaseFailureCode(\n error: unknown,\n): PostClaimDatabaseRecoveryDetail[\"code\"] | null {\n const persistenceFailure = isSessionEventPersistenceError(error) ? error : null;\n if (!persistenceFailure) {\n const driver = findPostgresDriverError(error);\n const driverSqlState = typeof driver?.code === \"string\" ? driver.code : null;\n if (isRetryablePersistenceSqlState(driverSqlState)) {\n return databaseFailureCode(driverSqlState);\n }\n }\n const sqlState = persistenceFailure?.details.sqlState ?? null;\n if (sqlState === null && isRetryableDatabaseTransportFailure(error)) {\n return \"db_failure\";\n }\n if (\n !persistenceFailure ||\n !(\n sqlState === null ||\n sqlState.startsWith(\"08\") ||\n sqlState.startsWith(\"40\") ||\n sqlState.startsWith(\"53\") ||\n sqlState === \"55P03\" ||\n sqlState === \"57014\" ||\n sqlState === \"57P01\" ||\n sqlState === \"57P02\" ||\n sqlState === \"57P03\" ||\n sqlState.startsWith(\"58\")\n )\n ) {\n return null;\n }\n return persistenceFailure.details.code;\n}\n\n/**\n * Carry one exact claimed-but-not-started attempt into the workflow's DB-only\n * recovery lane. Permanent database/state failures remain terminal; only the\n * same operational outage classes that are safe before claim are admitted.\n */\nexport function postClaimDatabaseRecoveryFailure(input: {\n error: unknown;\n turnId: string;\n triggerEventId: string;\n executionGeneration: number;\n sandboxSetupOutcomeUnknown?: true;\n providerRecovery?: {\n failureCode: string;\n providerRecoveryCount: number;\n };\n}): ApplicationFailure | null {\n const code = retryableDatabaseFailureCode(input.error);\n if (!code || input.executionGeneration < 1) return null;\n if (input.sandboxSetupOutcomeUnknown && input.providerRecovery) return null;\n if (\n input.providerRecovery &&\n (!Number.isSafeInteger(input.providerRecovery.providerRecoveryCount) ||\n input.providerRecovery.providerRecoveryCount <= 0 ||\n input.providerRecovery.providerRecoveryCount > MAX_AUTOMATIC_PROVIDER_RECOVERIES ||\n !/^[a-z][a-z0-9_]{0,63}$/.test(input.providerRecovery.failureCode))\n ) {\n return null;\n }\n const detail: PostClaimDatabaseRecoveryDetail = {\n turnId: input.turnId,\n triggerEventId: input.triggerEventId,\n executionGeneration: input.executionGeneration,\n code,\n ...(input.sandboxSetupOutcomeUnknown ? { sandboxSetupOutcomeUnknown: true } : {}),\n ...(input.providerRecovery\n ? {\n providerFailureCode: input.providerRecovery.failureCode,\n providerRecoveryCount: input.providerRecovery.providerRecoveryCount,\n }\n : {}),\n };\n return ApplicationFailure.create({\n message: POST_CLAIM_DATABASE_RECOVERY_FAILURE_MESSAGE,\n type: POST_CLAIM_DATABASE_RECOVERY_FAILURE_TYPE,\n nonRetryable: true,\n details: [detail],\n });\n}\n\n/**\n * Resolve which Codex account a turn runs on (multi-account P1): session-pin >\n * workspace-active. No rotation in P1. The selected id must still be in the\n * connected set — a disconnected pin was FK-nulled, so a stale id can't appear,\n * but we guard anyway. Returns null when there is no usable account (the turn\n * then fails with the existing relogin error path).\n */\nexport function isWorkerShutdownCancellation(error: unknown): boolean {\n return error instanceof CancelledFailure && error.message === \"WORKER_SHUTDOWN\";\n}\n\nexport type SandboxLifecycleTransitionDiagnostic = {\n sandboxGroupId: string;\n leaseEpoch: number;\n reason: \"capture_in_progress\" | \"rotation_in_progress\" | \"provider_recovery_in_progress\";\n};\n\n/**\n * Recover a typed sandbox lifecycle transition through the structural wrappers\n * used by parallel Agents SDK function-tool execution. Never infer transition\n * truth from message text: only the original class or an exact, fully-shaped\n * cross-package error object is accepted.\n */\nexport function sandboxLifecycleTransitionDiagnostic(\n error: unknown,\n): SandboxLifecycleTransitionDiagnostic | null {\n const pending: unknown[] = [error];\n const seen = new WeakSet<object>();\n let inspected = 0;\n\n while (pending.length > 0 && inspected < 64) {\n const current = pending.shift();\n inspected += 1;\n if (!current || typeof current !== \"object\" || seen.has(current)) continue;\n seen.add(current);\n\n try {\n const record = current as Record<string, unknown>;\n const reason = record.reason;\n if (\n (current instanceof SandboxLeaseTransitionError ||\n record.name === \"SandboxLeaseTransitionError\") &&\n typeof record.sandboxGroupId === \"string\" &&\n record.sandboxGroupId.length > 0 &&\n typeof record.leaseEpoch === \"number\" &&\n Number.isSafeInteger(record.leaseEpoch) &&\n record.leaseEpoch >= 0 &&\n (reason === \"capture_in_progress\" ||\n reason === \"rotation_in_progress\" ||\n reason === \"provider_recovery_in_progress\")\n ) {\n return {\n sandboxGroupId: record.sandboxGroupId,\n leaseEpoch: record.leaseEpoch,\n reason,\n };\n }\n\n for (const key of [\"cause\", \"error\"] as const) {\n const nested = record[key];\n if (nested && typeof nested === \"object\") pending.push(nested);\n }\n if (Array.isArray(record.errors)) pending.push(...record.errors.slice(0, 32));\n } catch {\n // A hostile proxy or getter is not durable lifecycle evidence.\n }\n }\n\n return null;\n}\n\n/**\n * Recognize active-route transitions that cannot finish inside their\n * originating attempt. A Modal-home session may start on a Connected Machine\n * without creating or leasing its managed home box. When an explicit attach\n * clears the active pointer back to home, the pointer commit is authoritative,\n * but this attempt has no home session to serve the next sandbox operation.\n *\n * The Agents SDK may retain the typed routing error directly, through `cause`,\n * or inside an AggregateError from a parallel function-tool batch. Traverse\n * only those structural error links with a strict bound; never classify from\n * message text, which could originate in model or tool content.\n */\nexport function sandboxRouteTransitionCode(\n error: unknown,\n):\n | \"home_unavailable_this_turn\"\n | \"workspace_root_changed_this_turn\"\n | \"native_capabilities_changed_this_attempt\"\n | null {\n const pending: unknown[] = [error];\n const seen = new WeakSet<object>();\n let inspected = 0;\n\n while (pending.length > 0 && inspected < 64) {\n const current = pending.shift();\n inspected += 1;\n if (!current || typeof current !== \"object\" || seen.has(current)) continue;\n seen.add(current);\n\n try {\n const record = current as Record<string, unknown>;\n if (\n (current instanceof SandboxCapabilitiesChangedError ||\n record.name === \"SandboxCapabilitiesChangedError\") &&\n record.code === \"native_capabilities_changed_this_attempt\"\n ) {\n return \"native_capabilities_changed_this_attempt\";\n }\n if (\n (current instanceof ActiveBackendUnresolvableError ||\n record.name === \"ActiveBackendUnresolvableError\") &&\n record.code === \"home_unavailable_this_turn\"\n ) {\n return \"home_unavailable_this_turn\";\n }\n if (\n current instanceof RoutingWorkspaceRootChangedError ||\n current instanceof SelfhostedWorkspaceRootChangedError ||\n record.name === \"RoutingWorkspaceRootChangedError\" ||\n record.name === \"SelfhostedWorkspaceRootChangedError\"\n ) {\n return \"workspace_root_changed_this_turn\";\n }\n\n for (const key of [\"cause\", \"error\"] as const) {\n const nested = record[key];\n if (nested && typeof nested === \"object\") pending.push(nested);\n }\n if (Array.isArray(record.errors)) {\n pending.push(...record.errors.slice(0, 32));\n }\n } catch {\n // A hostile proxy or getter is not a route-transition proof.\n }\n }\n\n return null;\n}\n\nexport function isSandboxRouteTransitionError(error: unknown): boolean {\n return sandboxRouteTransitionCode(error) !== null;\n}\n\n/** Backward-compatible name for callers/tests that only exercised the original\n * machine-to-home transition. */\nexport function isHomeSandboxTurnTransitionError(error: unknown): boolean {\n return sandboxRouteTransitionCode(error) === \"home_unavailable_this_turn\";\n}\n\n/**\n * Review captures and protective snapshots are cache/persistence housekeeping,\n * never part of cancellation correctness. A control-fenced or Temporal-cancelled\n * attempt must release its physical activity promptly so Steer/Pause can advance.\n */\nexport function compactionFailureReason(reason: string): string {\n return reason.startsWith(\"compaction summarization failed:\")\n ? reason\n : `compaction summarization failed: ${reason}`;\n}\n\nexport type SafeErrorDiagnostic = {\n errorClass: \"WorkerOperationError\";\n errorCode: \"worker_operation_failed\";\n status?: number;\n origin: \"worker\";\n historyPersistenceStage?: MandatoryHistoryPersistenceStage;\n};\n\n/**\n * Produce the only exception shape allowed in worker logs. It deliberately\n * excludes the arbitrary source message, stack, cause, response/request\n * bodies, and enumerable properties. Exact failure content belongs in the\n * permission-controlled session event, not stdout or telemetry.\n */\nexport function safeErrorDiagnostic(error: unknown): SafeErrorDiagnostic {\n const diagnostic: SafeErrorDiagnostic = {\n errorClass: \"WorkerOperationError\",\n errorCode: \"worker_operation_failed\",\n origin: \"worker\",\n };\n try {\n let statusSource = error;\n if (error instanceof MandatoryHistoryPersistenceError) {\n diagnostic.historyPersistenceStage = error.stage;\n statusSource = error.cause;\n }\n if (statusSource && typeof statusSource === \"object\") {\n const status = Number(\n (statusSource as { status?: unknown; statusCode?: unknown }).status ??\n (statusSource as { statusCode?: unknown }).statusCode,\n );\n if (Number.isInteger(status) && status >= 100 && status <= 599) {\n diagnostic.status = status;\n }\n }\n } catch {\n // Public diagnostics are best-effort and must never replace the exact\n // internal worker failure.\n }\n return diagnostic;\n}\n\nexport function safeErrorForTelemetry(error: unknown): Error {\n const diagnostic = safeErrorDiagnostic(error);\n const safe = new Error(\"worker operation failed\") as Error & {\n code?: string;\n status?: number;\n origin?: string;\n };\n safe.name = \"WorkerOperationError\";\n safe.code = diagnostic.errorCode;\n if (diagnostic.status !== undefined) safe.status = diagnostic.status;\n safe.origin = diagnostic.origin;\n return safe;\n}\n\n/**\n * Guidance appended to a definitive provider rejection. Repeating the exact\n * request cannot succeed, so the generic \"send another message to retry\"\n * advice is wrong here: a new prompt re-sends the same rejected history.\n */\nexport const COMPACTION_PROVIDER_REJECTION_GUIDANCE =\n \"The provider refused this exact request, so repeating it fails the same way until the conversation changes. If a new message fails again, start a new session.\";\n\nexport function compactionFailureReasonFromError(error: unknown): string {\n const rejection = compactionProviderRejection(error);\n if (rejection) {\n return compactionFailureReason(\n `the model provider rejected the compaction request (${describeCompactionProviderRejection(rejection)}). Active history was preserved. ${COMPACTION_PROVIDER_REJECTION_GUIDANCE}`,\n );\n }\n // An exhausted provider quota is not retried (see agentRunFailurePayload),\n // so name the refusal plainly instead of the raw diagnostic envelope.\n const quota = classifyProviderQuotaExhaustionError(error);\n if (quota) {\n return compactionFailureReason(\n `${providerQuotaExhaustedMessage(quota.scope)} Active history was preserved.`,\n );\n }\n if (\n error instanceof CompactionProviderResponseError ||\n error instanceof EmptyCompactionSummaryError\n ) {\n return compactionFailureReason(error.message);\n }\n const errorName = error instanceof Error && error.name ? error.name : \"unknown error\";\n return compactionFailureReason(`unexpected ${errorName}`);\n}\n\n/**\n * Exact `turn.failed` payload for a terminal compaction failure. A definitive\n * provider rejection additionally carries its closed identifier record so the\n * timeline, API consumers, and operators can name the rejected field without\n * parsing the message.\n */\nexport function compactionFailureTurnEventPayload(\n error: unknown,\n overrides: { error?: string } = {},\n): {\n error: string;\n code: \"context_compaction_failed\";\n retryable: false;\n recovery: \"user_message\";\n compacted: false;\n providerRejection?: CompactionProviderRejection;\n quotaScope?: ProviderQuotaScope;\n} {\n const rejection = compactionProviderRejection(error);\n // The same closed marker as a `provider_quota_exhausted` turn failure, so\n // clients can name the exhausted limit and offer another model here too.\n const quota = rejection ? null : classifyProviderQuotaExhaustionError(error);\n return {\n error: overrides.error ?? compactionFailureReasonFromError(error),\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n ...(rejection ? { providerRejection: rejection } : {}),\n ...(quota ? { quotaScope: quota.scope } : {}),\n };\n}\n\nexport function isCompactionSummaryFailure(error: unknown): boolean {\n return (\n error instanceof CompactionProviderResponseError || error instanceof EmptyCompactionSummaryError\n );\n}\n\nexport function shouldRecoverCompactionProviderFailure(error: unknown): boolean {\n if (!(error instanceof CompactionProviderResponseError)) return false;\n if (isCodexTransportError(error) && classifyCodexUsageLimitError(error)) return true;\n // Codex may reject an opaque artifact it minted itself on the compaction\n // request exactly as it can on an ordinary request. Failure settlement\n // invalidates only the exact participating artifacts and recovers the same\n // logical turn; when nothing can be invalidated it fails closed there.\n if (classifyCodexEncryptedArtifactRejection(error)) return true;\n // A ChatGPT plan that no longer includes the model refuses the compaction\n // request exactly as it refuses an ordinary one (often with an empty 400).\n // Failure settlement re-checks the plan and, when it proves the loss,\n // excludes that account for the model and fails the same turn over; an\n // unexplained rejection still fails there with typed copy.\n if (classifyCodexEntitlementRejection(error)) return true;\n return agentRunFailurePayload(error).retryable === true;\n}\n\nexport function classifyContextWindowOverflowError(\n error: unknown,\n): { message: string; code?: string; detail?: string } | null {\n if (isProviderSafetyRefusal(error)) return null;\n const fields = collectErrorStrings(error);\n const matched = fields.find(\n (value) =>\n /context[_\\s-]*length[_\\s-]*exceeded/i.test(value) ||\n /exceeds?\\s+(?:the\\s+)?context\\s+window/i.test(value) ||\n /maximum\\s+context\\s+length/i.test(value) ||\n /context\\s+window[^.]*exceed/i.test(value),\n );\n if (!matched) {\n return null;\n }\n const message = error instanceof Error ? error.message : String(error);\n const code = fields.find((value) => /context[_\\s-]*length[_\\s-]*exceeded/i.test(value));\n return {\n message,\n ...(code ? { code } : {}),\n ...(matched && matched !== message ? { detail: matched } : {}),\n };\n}\n\n/**\n * Recognize an MCP transport/request timeout that escaped the SDK's per-tool\n * `mcpConfig.errorFunction` boundary. A thrown tool invocation is normally\n * converted to an `{isError:true}` tool output; however, connect/tools-list or\n * next-loop transport work can reject the stream iterator after a prior tool\n * output was already published. That is transient external backpressure, not a\n * terminal session error. Match MCP-qualified timeout text only: an unrelated\n * sandbox/model timeout and MCP's application-defined Authentication required signal must\n * retain their existing semantics.\n */\nexport function classifyMcpTransportTimeoutError(\n error: unknown,\n): { message: string; detail?: string } | null {\n const fields = collectErrorStrings(error);\n const matchedText = fields.find(\n (value) =>\n /\\bmcp\\b/i.test(value) &&\n /(?:request\\s+timed\\s+out|request\\s+timeout|\\btimed\\s+out\\b|\\btimeout\\b|ETIMEDOUT)/i.test(\n value,\n ) &&\n !/authentication\\s+required/i.test(value),\n );\n const sanitizedSdkTimeout = isMcpRequestTimeoutError(error);\n if (!matchedText && !sanitizedSdkTimeout) {\n return null;\n }\n const message = error instanceof Error ? error.message : String(error);\n const matched = matchedText ?? fields.find((value) => /\\bmcp\\b/i.test(value));\n return {\n message,\n ...(matched && matched !== message ? { detail: matched } : {}),\n };\n}\n\nexport function collectErrorStrings(value: unknown, seen = new WeakSet<object>()): string[] {\n if (typeof value === \"string\") {\n return [value];\n }\n if (!value || typeof value !== \"object\") {\n return [];\n }\n if (seen.has(value)) {\n return [];\n }\n seen.add(value);\n const out: string[] = [];\n // This diagnostic is already provider-owned and byte-bounded. Do not widen\n // generic detail traversal to arbitrary application payloads.\n if (value instanceof ResponsesStreamingTerminalError) out.push(value.detail);\n const record = value as Record<string, unknown>;\n for (const key of [\"message\", \"code\", \"type\", \"name\", \"param\"]) {\n const field = record[key];\n if (typeof field === \"string\" && field.length > 0) {\n out.push(field);\n }\n }\n for (const key of [\"error\", \"cause\", \"response\", \"data\"]) {\n out.push(...collectErrorStrings(record[key], seen));\n }\n return out;\n}\n\n/**\n * Compute the conversation-truth rows a reconcile pass should append, given the\n * SDK's current `state.history` and the count already persisted.\n *\n * `state.history` is a computed getter that runs the SDK's orphan-tool-call\n * pruning on every access, so it is non-monotonic: a `function_call` with no\n * settling result yet is transiently absent and a later access yields a\n * different, possibly shorter/reordered list. The old code sliced this list by\n * a blind length watermark and appended at fixed positions with\n * onConflictDoNothing, which could freeze a position with one shape and later\n * persist a `function_call_result` whose `function_call` had been pruned away in\n * an earlier slice — the orphaned tool output that 400s the Responses API and\n * bricks the session on every replay.\n *\n * Defending: structurally repair the full current history into an API-valid sequence (the\n * same pure rules the read path uses), then append only the new tail beyond the\n * watermark. A trailing dangling call is dropped here and re-evaluated next\n * pass once its result lands, so a call and its result are written together at\n * consecutive positions and a result is never persisted without its call. The\n * watermark advances to the repaired length — never past anything unwritten —\n * so a non-monotonic history can never desync it. When previously-persisted\n * rows already exceed the repaired length (e.g. legacy orphans written before\n * this fix), nothing new is appended and the watermark holds steady.\n */\n/**\n * Stable+unique usage source key for one model call, used to build the per-call\n * idempotency key (`usage:model.tokens:${turnId}:${sourceKey}`). The turnId is\n * shared across a new attempt of the SAME turn (recovery, approval\n * rerun, activity retry), so the sourceKey alone must distinguish calls.\n *\n * - A provider responseId is globally stable+unique, so reuse it verbatim: a\n * true activity retry that re-emits the same responseId correctly DEDUPES\n * (one charge), while two distinct calls get distinct ids.\n * - Without a responseId the old synthesized key was only POSITIONAL (\"response-1\",\n * \"aggregate\"), which collides across a re-dispatch — dispatch B's first\n * call reuses dispatch A's \"response-1\" key and its charge is silently\n * dropped (undercharge). Qualifying the synthesized key with the\n * per-execution dispatch id (the Temporal activityId, unique per scheduled\n * execution) makes re-dispatched calls distinct while still deduping a\n * same-execution retry.\n */\nexport const STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGE =\n \"unable to connect. is the computer able to access the url?\";\n\nexport function isExactStatuslessUpstreamConnectivityMessage(message: string): boolean {\n return message.trim().toLowerCase() === STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGE;\n}\n\nfunction providerSafetyRefusalDiagnostic(error: unknown): string | undefined {\n if (error instanceof ResponsesStreamingTerminalError) {\n return error.category === \"safety\" ? error.detail : undefined;\n }\n return collectErrorStrings(error).find(\n (value) =>\n /^(?:content_policy_violation|content_filter|safety_violation|bio_policy|cyber_policy)$/.test(\n value,\n ) || /\\bthis request was blocked by our safety systems\\b/i.test(value),\n );\n}\n\nfunction isProviderSafetyRefusal(error: unknown): boolean {\n return providerSafetyRefusalDiagnostic(error) !== undefined;\n}\n\nexport function isTransientProviderError(error: unknown): boolean {\n if (error instanceof ResponsesStreamingTerminalError) {\n return error.category === \"unavailable\";\n }\n // A semantic refusal can arrive inside a 5xx transport envelope.\n if (isProviderSafetyRefusal(error)) return false;\n const status =\n typeof error === \"object\" && error !== null\n ? Number(\n (error as { status?: unknown; statusCode?: unknown }).status ??\n (error as { statusCode?: unknown }).statusCode,\n )\n : undefined;\n // A real HTTP status is AUTHORITATIVE: a 5xx is transient, and ANY other status\n // (4xx validation/auth/404, plus the 429 the earlier branches already handled) is\n // a request fault that must NOT auto-retry — even if its body happens to read like\n // \"connection error\" or \"overloaded\". The code/message heuristics below apply ONLY\n // when no status survived: a network fault or an SDK-rethrown bare Error.\n if (status !== undefined && Number.isFinite(status)) {\n return status >= 500 && status < 600;\n }\n const code =\n typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n if (code && /^(?:ECONNRESET|ETIMEDOUT|EAI_AGAIN|ECONNREFUSED|EPIPE)$/i.test(code)) {\n return true;\n }\n const message = error instanceof Error ? error.message : String(error);\n if (isExactStatuslessUpstreamConnectivityMessage(message)) {\n return true;\n }\n return /overloaded|an error occurred while processing your request|connection error|service unavailable|bad gateway|gateway timeout/i.test(\n message,\n );\n}\n\n/** An explicit `usage_limit_reached` type or code string anywhere on the error chain. */\nfunction hasCodexUsageLimitType(error: unknown): boolean {\n return collectErrorStrings(error).some((value) => value.includes(CODEX_USAGE_LIMIT_ERROR_TYPE));\n}\n\n/**\n * Recognize an exhausted API-key provider quota (a daily or monthly allowance,\n * a free-tier day cap, or an account out of credits) as distinct from an\n * ordinary per-minute rate limit. Retrying within the bounded same-turn budget\n * cannot succeed, so the turn fails promptly instead. Subscription transports\n * own their quota semantics through credential rotation and durable capacity\n * waits, so a Codex or SuperGrok transport error never classifies here.\n */\nexport function classifyProviderQuotaExhaustionError(\n error: unknown,\n): ProviderQuotaExhaustion | null {\n if (isCodexTransportError(error) || isXaiSubscriptionTransportError(error)) return null;\n // The same reader the OpenAI SDK retry veto uses, so the two never disagree.\n return classifyProviderQuotaError(error);\n}\n\nexport type XaiCredentialFailure = {\n kind: \"auth\" | \"forbidden\" | \"rate_limit\";\n cooldownMs: number | null;\n};\n\n/**\n * Only definitive SuperGrok account refusals may move the same logical turn to\n * another credential. A marked HTTP 401/403/429, or an HTTP 200 SSE terminal\n * that is a rate-limit/capacity diagnostic, proves inference was refused\n * without an accepted model response; refresh relogin is equally definitive.\n */\nexport function classifyXaiCredentialFailure(error: unknown): XaiCredentialFailure | null {\n if (isProviderSafetyRefusal(error)) return null;\n let relogin: unknown = error;\n for (let depth = 0; depth < 6 && relogin && typeof relogin === \"object\"; depth += 1) {\n if (relogin instanceof XaiSubscriptionReloginRequired) {\n return { kind: \"auth\", cooldownMs: null };\n }\n relogin = (relogin as Record<string, unknown>).cause;\n }\n if (!isXaiSubscriptionTransportError(error)) return null;\n let current: unknown = error;\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n const value = current as Record<string, unknown>;\n const body =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : null;\n const status = Number(value.status ?? value.statusCode ?? body?.status ?? body?.statusCode);\n const code = String(value.code ?? body?.code ?? \"\").toLowerCase();\n if (status === 401 || code === \"unauthorized\" || code === \"invalid_token\") {\n return { kind: \"auth\", cooldownMs: null };\n }\n if (status === 403) {\n return { kind: \"forbidden\", cooldownMs: null };\n }\n const message = String(value.message ?? body?.message ?? \"\");\n if (\n isXaiSubscriptionRateLimitDiagnostic({\n code,\n message,\n status: Number.isInteger(status) ? status : null,\n })\n ) {\n return {\n kind: \"rate_limit\",\n cooldownMs: providerRetryAfterMs(error) ?? PROVIDER_BACKPRESSURE_DELAY_MS,\n };\n }\n current = value.cause;\n }\n return null;\n}\n\n// The generic turn-failure boundary also receives application/provider errors.\n// A five-character code or generic severity alone does not establish a driver error.\nfunction findPostgresDriverError(error: unknown): Record<string, unknown> | null {\n const queue: unknown[] = [error];\n const seen = new Set<unknown>();\n for (let index = 0; index < queue.length && index < 64; index += 1) {\n const current = queue[index];\n if (!current || typeof current !== \"object\" || seen.has(current)) continue;\n seen.add(current);\n const record = current as Record<string, unknown>;\n if (record.name === \"PostgresError\") return record;\n for (const key of [\"cause\", \"original\", \"driverError\", \"error\", \"errors\"]) {\n const nested = record[key];\n if (Array.isArray(nested)) queue.push(...nested.slice(0, 64));\n else if (nested !== undefined) queue.push(nested);\n }\n }\n return null;\n}\n\nfunction isRawDatabaseQueryError(error: unknown): boolean {\n return (\n error instanceof Error &&\n \"query\" in error &&\n typeof error.query === \"string\" &&\n \"params\" in error &&\n Array.isArray(error.params)\n );\n}\n\nexport function agentRunFailurePayload(\n error: unknown,\n options: { isCodexTurn?: boolean } = {},\n): ReturnType<typeof baseAgentRunFailurePayload> {\n const failure = baseAgentRunFailurePayload(error, options);\n const diagnostic = materializationVerificationDiagnostic(error);\n return diagnostic ? { ...failure, materializationDiagnostic: diagnostic } : failure;\n}\n\nfunction baseAgentRunFailurePayload(\n error: unknown,\n options: { isCodexTurn?: boolean } = {},\n): {\n error: string;\n code?: string;\n retryable?: boolean;\n detail?: string;\n timeoutClass?: string;\n responseObserved?: boolean;\n requestId?: string;\n eventCount?: number;\n lastEventType?: string;\n silenceDurationMs?: number;\n correlationId?: string;\n stage?: string;\n sqlState?: string | null;\n attempts?: number;\n retryOutcome?: string;\n database?: Record<string, string>;\n historyPersistenceStage?: MandatoryHistoryPersistenceStage;\n mcpTransportDiagnostic?: McpTransportRequestFailureDiagnostic;\n materializationDiagnostic?: MaterializationVerificationDiagnostic;\n quotaScope?: ProviderQuotaScope;\n /** Closed Codex plan key on `codex_plan_entitlement` / `codex_request_rejected`. */\n planType?: string | null;\n /** Product model id a `codex_plan_entitlement` failure refers to. */\n model?: string | null;\n} {\n if (error instanceof SandboxMaterializationVerificationError) {\n return {\n error: error.message,\n code: error.code,\n retryable: false,\n materializationDiagnostic: error.diagnostic,\n };\n }\n if (error instanceof RetainedAttachmentTransportLimitError) {\n return { error: error.message, code: \"retained_attachment_transport_limit\", retryable: false };\n }\n if (error instanceof MandatoryHistoryPersistenceError) {\n const databaseFailure =\n isSessionEventPersistenceError(error.cause) ||\n findPostgresDriverError(error.cause) !== null ||\n isRawDatabaseQueryError(error.cause);\n const underlying = databaseFailure\n ? agentRunFailurePayload(error.cause, options)\n : {\n error: error.cause instanceof Error ? error.cause.message : String(error.cause),\n };\n return {\n ...underlying,\n historyPersistenceStage: error.stage,\n };\n }\n // Raw ORM wrappers can contain the full SQL and its parameters. Classify a\n // real driver before provider message heuristics; the original cause stays\n // available to internal diagnostics. This payload grants no replay authority.\n const postgresDriverError = findPostgresDriverError(error);\n const rawOrmFailure = isRawDatabaseQueryError(error);\n if ((postgresDriverError || rawOrmFailure) && !isSessionEventPersistenceError(error)) {\n const database = safeDatabaseErrorFacts(postgresDriverError ?? error);\n const sqlState = postgresDriverError ? nestedPostgresSqlState(postgresDriverError) : null;\n return {\n error: \"OpenGeni encountered a database error.\",\n code: databaseFailureCode(sqlState),\n sqlState,\n ...(Object.keys(database).length > 0 ? { database } : {}),\n };\n }\n const safetyRefusalDiagnostic = providerSafetyRefusalDiagnostic(error);\n if (safetyRefusalDiagnostic !== undefined) {\n return {\n error:\n \"The model provider blocked this request through its safety systems. Automatic retries stopped.\",\n code: \"provider_safety_refusal\",\n retryable: false,\n detail: safetyRefusalDiagnostic,\n };\n }\n if (error instanceof ResponsesStreamingTerminalError) {\n const quota =\n error.category === \"unknown\" || error.category === \"rate_limit\"\n ? classifyProviderQuotaExhaustionError({\n code: error.code,\n error: { code: error.code, type: error.type, message: error.detail },\n retryAfterSeconds: error.retryAfterSeconds,\n })\n : null;\n if (quota) {\n return {\n error: providerQuotaExhaustedMessage(quota.scope),\n code: PROVIDER_QUOTA_EXHAUSTED_CODE,\n retryable: false,\n quotaScope: quota.scope,\n detail: error.detail,\n };\n }\n return {\n error:\n error.category === \"rate_limit\"\n ? \"Model provider rate limit hit. Try again in a minute or lower the reasoning effort.\"\n : error.category === \"unavailable\"\n ? \"The model provider is temporarily unavailable. The same turn will retry after a short delay.\"\n : \"The model provider rejected the response. Automatic retries stopped.\",\n code:\n error.category === \"rate_limit\"\n ? \"provider_rate_limited\"\n : error.category === \"unavailable\"\n ? \"provider_unavailable\"\n : \"provider_request_rejected\",\n retryable: error.category === \"rate_limit\" || error.category === \"unavailable\",\n detail: error.detail,\n };\n }\n const message = error instanceof Error ? error.message : String(error);\n const status =\n typeof error === \"object\" && error !== null\n ? Number(\n (error as { status?: unknown; statusCode?: unknown }).status ??\n (error as { statusCode?: unknown }).statusCode,\n )\n : undefined;\n const code =\n typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n if (error instanceof ActiveSessionHistoryLimitExceededError) {\n return {\n error:\n \"The session's active conversation history exceeds the worker's safe materialization envelope. Clear the session context before retrying; an oversized history cannot be compacted safely in a serving worker.\",\n code: error.code,\n retryable: false,\n detail: error.message,\n };\n }\n if (error instanceof ApprovalRunStateLimitExceededError) {\n return {\n error:\n \"The saved approval state exceeds the worker's safe materialization envelope. Clear the pending approval context before retrying.\",\n code: error.code,\n retryable: false,\n detail: error.message,\n };\n }\n if (error instanceof PostCompactionContinuationEmptyError) {\n return {\n error:\n \"Context compaction completed, but the continuation ended before a new model response. The same turn will retry from the compacted checkpoint.\",\n code: POST_COMPACTION_CONTINUATION_EMPTY_CODE,\n retryable: true,\n };\n }\n if (isModalCommandStartOutcomeUnknownError(error)) {\n return {\n error:\n \"A managed sandbox command has an unknown outcome. Its original invocation remains fenced; setup is blocked without replay until the incomplete operation can be reconciled.\",\n code: \"sandbox_command_start_outcome_unknown\",\n retryable: false,\n };\n }\n if (\n !isRoutingMutationOutcomeUnknownError(error) &&\n isModalTaskExecStartPreDispatchUnavailableError(error)\n ) {\n return {\n error:\n \"The managed sandbox command router was not ready before the command was sent. The same turn will retry after a short delay.\",\n code: \"sandbox_command_start_unavailable\",\n retryable: true,\n };\n }\n // An accepted Codex stream with no terminal response is malformed/partial,\n // not provider backpressure. Replaying the same accepted turn could repeat\n // model or tool effects, so this marked transport failure must outrank the\n // generic 5xx retry classifier (CodexStreamingTerminalError uses status 502).\n if (isCodexTransportError(error) && code === \"invalid_sse_terminal\") {\n return {\n error: \"The Codex response stream ended without a terminal response\",\n code: \"invalid_sse_terminal\",\n retryable: false,\n };\n }\n if (isXaiSubscriptionHostedToolContinuationError(error)) {\n return {\n error:\n \"SuperGrok stopped responding after its hosted search completed. Partial output was preserved; automatic replay is disabled because the accepted response may still have provider-side effects.\",\n code: \"xai_hosted_tool_continuation_stalled\",\n retryable: false,\n };\n }\n const xaiStreamTerminal = classifyXaiSubscriptionStreamingTerminalError(error);\n if (xaiStreamTerminal) {\n return {\n error: xaiStreamTerminal.message,\n code: xaiStreamTerminal.code,\n retryable: xaiStreamTerminal.status === 429,\n lastEventType: xaiStreamTerminal.eventType,\n ...(xaiStreamTerminal.requestId ? { requestId: xaiStreamTerminal.requestId } : {}),\n };\n }\n const xaiStreamTimeout = classifyXaiSubscriptionStreamIdleTimeoutError(error);\n if (xaiStreamTimeout) {\n return {\n error:\n \"SuperGrok stopped sending valid response events. Partial output was preserved; automatic replay is disabled because the accepted response may still have provider-side effects.\",\n code: \"xai_response_stream_idle_timeout\",\n retryable: false,\n responseObserved: xaiStreamTimeout.responseObserved,\n eventCount: xaiStreamTimeout.eventCount,\n silenceDurationMs: xaiStreamTimeout.silenceDurationMs,\n ...(xaiStreamTimeout.requestId ? { requestId: xaiStreamTimeout.requestId } : {}),\n ...(xaiStreamTimeout.lastEventType ? { lastEventType: xaiStreamTimeout.lastEventType } : {}),\n };\n }\n if (isSessionEventPersistenceError(error)) {\n const { details } = error;\n return {\n error: error.message,\n code: details.code,\n detail:\n details.retryOutcome === \"exhausted\"\n ? `The idempotent persistence transaction failed after ${details.attempts} attempts.`\n : \"The database rejected the idempotent persistence transaction.\",\n correlationId: details.correlationId,\n stage: details.stage,\n sqlState: details.sqlState,\n attempts: details.attempts,\n retryOutcome: details.retryOutcome,\n ...(Object.keys(details.database).length > 0 ? { database: details.database } : {}),\n };\n }\n // Codex plan entitlement: the settlement path normally re-checks the plan\n // and records a precise payload. These branches keep any other path from\n // surfacing the SDK's raw \"400 status code (no body)\" text.\n if (error instanceof CodexPlanEntitlementError) {\n return error.payload;\n }\n const entitlementRejection = classifyCodexEntitlementRejection(error);\n if (entitlementRejection) {\n return entitlementRejection.evidence === \"plan_entitlement\"\n ? codexPlanEntitlementFailurePayload({\n accountLabel: null,\n planType: null,\n planChanged: false,\n modelId: null,\n rejection: entitlementRejection,\n })\n : codexRequestRejectedFailurePayload({\n accountLabel: null,\n planType: null,\n rejection: entitlementRejection,\n planChecked: false,\n });\n }\n // A ChatGPT/Codex usage cap is a HARD limit, not transient backpressure: it\n // must NOT be reported as a generic, retryable rate-limit (which would loop a\n // goal against a capped backend). Surface a precise, actionable message with\n // the humanized reset window and code, non-retryable. Checked BEFORE the\n // generic 429 branch below (a usage cap is also a 429).\n // This terminal payload classifier may receive a plain SDK-shaped error in\n // tests or after wrapper metadata was stripped. An explicit\n // `usage_limit_reached` shape must still outrank generic 429 retryability.\n // Credential quarantine/failover remains separately provenance-gated by\n // `isCodexTransportError`; this branch only chooses the truthful user payload.\n // The looser \"429 ... usage limit\" wording counts only on a Codex transport\n // error: an API-key provider's 429 that says \"usage limit\" is provider quota\n // evidence, not a ChatGPT/Codex subscription cap.\n const usageLimit = classifyCodexUsageLimitError(error);\n if (usageLimit && (isCodexTransportError(error) || hasCodexUsageLimitType(error))) {\n return codexUsageLimitFailurePayload(usageLimit, message);\n }\n const codexTimeout = classifyCodexResponseTimeoutError(error, {\n allowLegacyRequestTimeout: options.isCodexTurn === true,\n });\n if (codexTimeout) {\n return {\n error: codexTimeout.responseObserved\n ? \"The Codex response timed out after streaming began. Observed output was checkpointed; automatic replay is disabled because the upstream operation may still be active.\"\n : \"The Codex response timed out before any response was observed. Upstream acceptance is unknown, so automatic replay is disabled.\",\n code: \"codex_response_timeout\",\n retryable: false,\n timeoutClass: codexTimeout.timeoutClass,\n responseObserved: codexTimeout.responseObserved,\n ...(codexTimeout.requestId ? { requestId: codexTimeout.requestId } : {}),\n ...(codexTimeout.message ? { detail: codexTimeout.message } : {}),\n };\n }\n const mcpTimeout = classifyMcpTransportTimeoutError(error);\n if (mcpTimeout) {\n const mcpTransportDiagnostic = mcpTransportRequestFailureDiagnostic(error);\n return {\n error:\n \"An MCP server request timed out. Any completed tool output was checkpointed; the session can continue safely.\",\n code: \"mcp_transport_timeout\",\n retryable: true,\n ...(mcpTimeout.detail || mcpTimeout.message\n ? { detail: mcpTimeout.detail ?? mcpTimeout.message }\n : {}),\n ...(mcpTransportDiagnostic ? { mcpTransportDiagnostic } : {}),\n };\n }\n if (isMcpTransportConnectivityError(error)) {\n const mcpTransportDiagnostic = mcpTransportRequestFailureDiagnostic(error);\n return {\n error:\n \"A required MCP server was temporarily unreachable. The same turn will retry after a short delay.\",\n code: \"mcp_transport_unavailable\",\n retryable: true,\n detail: message,\n ...(mcpTransportDiagnostic ? { mcpTransportDiagnostic } : {}),\n };\n }\n if (code === UNKNOWN_MODEL_FINISH_REASON_CODE) {\n return {\n error:\n \"The model provider ended its response ambiguously. Partial output was not accepted as complete; the same turn will retry from durable history.\",\n code: UNKNOWN_MODEL_FINISH_REASON_CODE,\n retryable: true,\n };\n }\n // An exhausted quota also arrives as HTTP 429 (or 402), but no retry within\n // the finite same-turn budget can succeed. Fail the turn promptly with a\n // distinct code so the client can offer another model; ordinary short rate\n // limits fall through to the retryable branch below.\n const quota = classifyProviderQuotaExhaustionError(error);\n if (quota) {\n return {\n error: providerQuotaExhaustedMessage(quota.scope),\n code: PROVIDER_QUOTA_EXHAUSTED_CODE,\n retryable: false,\n quotaScope: quota.scope,\n ...(message ? { detail: message } : {}),\n };\n }\n if (\n status === 429 ||\n code === \"rate_limit_exceeded\" ||\n /(?:too many requests|rate.?limit|\\b429\\b)/i.test(message)\n ) {\n return {\n error: \"Model provider rate limit hit. Try again in a minute or lower the reasoning effort.\",\n code: \"provider_rate_limited\",\n retryable: true,\n ...(message && message !== \"Too Many Requests\" ? { detail: message } : {}),\n };\n }\n // Transient upstream backpressure (5xx / overloaded / dropped connection): keep\n // the provider's own message (it is already user-meaningful) but mark it\n // retryable so a goal-bearing session idles and auto-continues instead of going\n // terminal on a provider's bad minute. See isTransientProviderError.\n if (isTransientProviderError(error)) {\n if (isExactStatuslessUpstreamConnectivityMessage(message)) {\n return {\n error:\n \"OpenGeni could not reach an upstream service. The same turn will retry after a short delay.\",\n code: \"upstream_connectivity_unavailable\",\n retryable: true,\n };\n }\n return { error: message, code: \"provider_unavailable\", retryable: true };\n }\n return { error: message };\n}\n\nexport type CodexCredentialFailure = {\n /**\n * `plan_entitlement` is produced only after a plan re-check proves the\n * serving account's current plan does not include the requested model.\n */\n kind: \"auth\" | \"forbidden\" | \"rate_limit\" | \"quota\" | \"plan_entitlement\";\n cooldownSeconds: number | null;\n};\n\nexport const CODEX_ALLOWANCE_FALLBACK_MS = 5 * 60 * 60_000;\n\n/**\n * Resolve a deterministic quarantine end. Generic request throttling honors\n * provider retry-after (or one minute); allowance/quota refusal waits for the\n * LAST of provider reset and every still-binding cached window (five-hour and\n * weekly both bind), falling back to one complete five-hour window when no reset\n * metadata exists.\n */\nexport function codexCredentialCooldownUntil(\n failure: CodexCredentialFailure,\n account: Pick<\n CodexAccountStatus,\n \"primaryUsedPercent\" | \"primaryResetAt\" | \"secondaryUsedPercent\" | \"secondaryResetAt\"\n > | null,\n now: Date,\n): Date | null {\n if (\n failure.kind === \"auth\" ||\n failure.kind === \"forbidden\" ||\n failure.kind === \"plan_entitlement\"\n ) {\n return null;\n }\n const providerReset =\n failure.cooldownSeconds !== null &&\n Number.isFinite(failure.cooldownSeconds) &&\n failure.cooldownSeconds > 0\n ? new Date(now.getTime() + Math.ceil(failure.cooldownSeconds) * 1000)\n : null;\n if (failure.kind === \"rate_limit\") {\n return providerReset ?? new Date(now.getTime() + PROVIDER_BACKPRESSURE_DELAY_MS);\n }\n const blockingResets = account\n ? [\n { used: account.primaryUsedPercent, reset: account.primaryResetAt },\n { used: account.secondaryUsedPercent, reset: account.secondaryResetAt },\n ]\n .filter(\n (window): window is { used: number; reset: Date } =>\n (window.used ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT &&\n window.reset instanceof Date &&\n window.reset.getTime() > now.getTime(),\n )\n .map((window) => window.reset)\n : [];\n const quotaResets = providerReset ? [...blockingResets, providerReset] : blockingResets;\n if (quotaResets.length === 0) {\n return new Date(now.getTime() + CODEX_ALLOWANCE_FALLBACK_MS);\n }\n return quotaResets.reduce((latest, reset) =>\n reset.getTime() > latest.getTime() ? reset : latest,\n );\n}\n\n/**\n * Only definitive credential/account refusals are safe rotation signals.\n * Ambiguous network failures, malformed/partial streams, invalid model content,\n * prompt 4xx, and provider 5xx may already have consumed tokens or persisted\n * progress and therefore MUST NOT walk the credential pool automatically.\n */\nexport function classifyCodexCredentialFailure(error: unknown): CodexCredentialFailure | null {\n // A request safety refusal is not evidence that another account should run it.\n if (isProviderSafetyRefusal(error)) return null;\n // A permanent OAuth refresh failure is definitive and the shared resolver has\n // already fenced/stamped the exact credential version. The OpenAI client can\n // wrap a rejection from its custom fetch in APIConnectionError, so recognize\n // the typed exception through the same bounded cause chain used below.\n let refreshError: unknown = error;\n for (let depth = 0; depth < 6 && refreshError && typeof refreshError === \"object\"; depth += 1) {\n if (refreshError instanceof CodexReloginRequired) {\n return { kind: \"auth\", cooldownSeconds: null };\n }\n refreshError = (refreshError as Record<string, unknown>).cause;\n }\n // The activity catch also receives sandbox, MCP, storage, and tool failures.\n // Their HTTP status codes are not Codex account state and must never walk the\n // subscription pool or replay a tool on another credential.\n if (!isCodexTransportError(error)) {\n return null;\n }\n // Plan/model entitlement evidence (an explicit plan refusal, or an empty\n // HTTP 400) is not account health or quota. The worker re-checks the plan\n // first; only a proven entitlement loss walks the pool, as `plan_entitlement`.\n if (classifyCodexEntitlementRejection(error)) {\n return null;\n }\n const usageLimit = classifyCodexUsageLimitError(error);\n if (usageLimit) {\n return { kind: \"quota\", cooldownSeconds: usageLimit.resetsInSeconds };\n }\n let cur: unknown = error;\n for (let depth = 0; depth < 6 && cur && typeof cur === \"object\"; depth++) {\n const value = cur as Record<string, unknown>;\n const body =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : null;\n const status = Number(value.status ?? value.statusCode ?? body?.status ?? body?.statusCode);\n const code = String(value.code ?? body?.code ?? \"\").toLowerCase();\n const directRetryAfter = Number(\n value.retry_after_seconds ?? body?.retry_after_seconds ?? value.retryAfterSeconds,\n );\n const retryAfterHeader =\n headerValue(value.headers, \"retry-after\") ??\n headerValue(value.responseHeaders, \"retry-after\") ??\n headerValue(body?.headers, \"retry-after\");\n const retryAfterNumber = retryAfterHeader === null ? Number.NaN : Number(retryAfterHeader);\n const retryAfterDate =\n retryAfterHeader !== null && !Number.isFinite(retryAfterNumber)\n ? Date.parse(retryAfterHeader)\n : Number.NaN;\n const retryAfter = Number.isFinite(directRetryAfter)\n ? directRetryAfter\n : Number.isFinite(retryAfterNumber)\n ? retryAfterNumber\n : Number.isFinite(retryAfterDate)\n ? Math.max(0, (retryAfterDate - Date.now()) / 1000)\n : Number.NaN;\n const cooldownSeconds =\n Number.isFinite(retryAfter) && retryAfter > 0 ? Math.ceil(retryAfter) : null;\n // Provider quota codes are more specific than their HTTP transport status.\n // A permanent allowance refusal commonly arrives as HTTP 429; classify it\n // before generic backpressure so it receives the binding-window cooldown.\n if (\n code === \"insufficient_quota\" ||\n code === \"quota_exceeded\" ||\n code === \"billing_hard_limit_reached\"\n ) {\n return { kind: \"quota\", cooldownSeconds };\n }\n if (status === 401 || code === \"unauthorized\" || code === \"invalid_api_key\") {\n return { kind: \"auth\", cooldownSeconds };\n }\n if (status === 403) {\n return { kind: \"forbidden\", cooldownSeconds };\n }\n if (status === 429 || code === \"rate_limit_exceeded\" || code === \"too_many_requests\") {\n return { kind: \"rate_limit\", cooldownSeconds };\n }\n cur = value.cause;\n }\n return null;\n}\n\n/** Humanize a seconds duration into a short \"2h 5m\" / \"9m\" / \"in under a minute\" string. */\nexport function humanizeResetWindow(resetsInSeconds: number | null): string {\n if (resetsInSeconds === null || !Number.isFinite(resetsInSeconds) || resetsInSeconds <= 0) {\n return \"shortly\";\n }\n const total = Math.ceil(resetsInSeconds);\n if (total < 60) {\n return \"in under a minute\";\n }\n const hours = Math.floor(total / 3600);\n const minutes = Math.round((total % 3600) / 60);\n if (hours > 0) {\n return minutes > 0 ? `in about ${hours}h ${minutes}m` : `in about ${hours}h`;\n }\n return `in about ${minutes}m`;\n}\n\n/**\n * Build the turn.failed payload for a ChatGPT/Codex usage cap: a precise,\n * actionable message naming the reset window, the stable `codex_usage_limit_reached`\n * code, and retryable:false (an auto-retry would just re-hit the cap).\n */\nexport function codexUsageLimitFailurePayload(\n info: { resetsInSeconds: number | null },\n detail: string,\n opts?: { allAccounts?: boolean },\n): { error: string; code: string; retryable: false; detail?: string } {\n // P3: when EVERY connected subscription is rate-limited the message names the\n // earliest reset across accounts; the single-account message is unchanged.\n const error = opts?.allAccounts\n ? `All connected ChatGPT/Codex subscriptions are rate-limited. Access returns ${humanizeResetWindow(info.resetsInSeconds)}. ` +\n `You can switch this session to a different model in the meantime, or wait for a subscription to reset.`\n : `Your ChatGPT/Codex subscription usage limit has been reached. Access resets ${humanizeResetWindow(info.resetsInSeconds)}. ` +\n `You can switch this session to a different model in the meantime, or wait for the limit to reset.`;\n return {\n error,\n code: \"codex_usage_limit_reached\",\n retryable: false,\n ...(detail ? { detail } : {}),\n };\n}\n\n// A usage cap that won't reset for a long time should not pin a Temporal timer\n// open indefinitely for a goal-bearing session; cap the continuation hold so the\n// goal re-evaluates at most this far out (it will re-pause if still capped).\nexport const CODEX_USAGE_LIMIT_MAX_RESUME_MS = 60 * 60_000; // 1h\n","import {\n MODEL_ATTACHMENT_REFS_FIELD,\n MODEL_ATTACHMENT_CATALOG_MARKER,\n FileResourceRef,\n resourceMountPath,\n type FileAsset,\n type ResourceRef,\n} from \"@opengeni/contracts\";\nimport { createHash } from \"node:crypto\";\nimport {\n getActiveSessionHistoryItemsPaged,\n getFilesForSubject,\n getSandboxSessionEnvelope,\n getSessionEvent,\n listSessionSystemUpdatesForTurn,\n listTurnOpenSuffixToolCalls,\n type Database,\n} from \"@opengeni/db\";\nimport {\n projectHistoryForProvider,\n projectRejectedProviderArtifactsFromSerializedRunState,\n projectRejectedReasoningArtifact,\n hasOpaqueProviderArtifact,\n type HistoryProviderApi,\n type OpenGeniRuntime,\n} from \"@opengeni/runtime\";\n\n/** Project only artifacts explicitly rejected by the provider out of its next view. */\nexport function projectRejectedProviderArtifacts(\n rows: ReadonlyArray<{\n item: Record<string, unknown>;\n providerArtifactInvalidatedAt?: Date | null;\n }>,\n): Array<Record<string, unknown>> {\n const out: Array<Record<string, unknown>> = [];\n for (const row of rows) {\n if (!row.providerArtifactInvalidatedAt) {\n out.push(row.item);\n continue;\n }\n const type = typeof row.item.type === \"string\" ? row.item.type : undefined;\n if (type === \"reasoning\") {\n out.push(projectRejectedReasoningArtifact(row.item));\n continue;\n }\n if (type === \"compaction\") {\n continue;\n }\n out.push(row.item);\n }\n return out;\n}\n\n/** Build the attempt-local RunState view after an explicit provider rejection. */\nexport function resumeRunState(state: {\n serializedRunState: string;\n providerArtifactInvalidatedAt?: Date | null;\n}): string {\n if (!state.providerArtifactInvalidatedAt) {\n return state.serializedRunState;\n }\n return projectRejectedProviderArtifactsFromSerializedRunState(state.serializedRunState);\n}\n\n/** Prepared input and its exact durable-history prefix length for reconciliation. */\nexport type PreparedTurnInput = {\n input: Awaited<ReturnType<OpenGeniRuntime[\"prepareInput\"]>>;\n persistedHistoryCount: number;\n providerArtifactCandidates: {\n knownHistoryItemIds: string[];\n historyItemIds: string[];\n runStateId?: string;\n };\n};\n\nexport type TurnInputOptions = {\n turnId: string;\n /** Frozen initiating-human authority for every model-visible file read. */\n fileAuthority: { accountId: string; subjectId: string | null };\n recovering?: boolean;\n unavailableSandboxFilesNote?: string;\n runCredentialsNote?: string;\n mcpAvailabilityNote?: string;\n knowledgeSourcePreparationNote?: string;\n providerApi: HistoryProviderApi;\n projectCanonicalHistory?: ModelHistoryAttachmentProjector;\n materializeModelHistory?: ModelHistoryAttachmentProjector;\n projectModelHistory?: ModelHistoryAttachmentProjector;\n loadActiveHistory?: typeof getActiveSessionHistoryItemsPaged;\n /** Bounded critical-path timings; telemetry failures never affect preparation. */\n onPreparationPhase?: (measurement: HistoryPreparationPhaseMeasurement) => void;\n};\n\nexport type HistoryPreparationPhase =\n | \"system_update_load\"\n | \"current_attachment_resolution\"\n | \"durable_history_load\"\n | \"sandbox_envelope_load\"\n | \"canonical_projection\"\n | \"provider_projection\"\n | \"attachment_ref_projection\"\n | \"screenshot_materialization\"\n | \"model_attachment_projection\"\n | \"runtime_input_assembly\"\n | \"artifact_candidate_scan\";\n\nexport type HistoryPreparationPhaseMeasurement = {\n phase: HistoryPreparationPhase;\n outcome: \"completed\" | \"failed\";\n durationSeconds: number;\n};\n\nasync function measureHistoryPreparationPhase<T>(\n options: Pick<TurnInputOptions, \"onPreparationPhase\">,\n phase: HistoryPreparationPhase,\n operation: () => T | Promise<T>,\n): Promise<T> {\n const startedAt = performance.now();\n let outcome: HistoryPreparationPhaseMeasurement[\"outcome\"] = \"completed\";\n try {\n return await operation();\n } catch (error) {\n outcome = \"failed\";\n throw error;\n } finally {\n try {\n options.onPreparationPhase?.({\n phase,\n outcome,\n durationSeconds: (performance.now() - startedAt) / 1_000,\n });\n } catch {\n // Diagnostics must not change durable history or provider input.\n }\n }\n}\n\nexport const MAX_INLINE_MODEL_ATTACHMENT_BYTES = 20 * 1024 * 1024;\n// Raw-byte allowance; base64 and request serialization add memory overhead.\n// This is transport admission, never an instruction to rewrite old messages.\nexport const MAX_RETAINED_MODEL_ATTACHMENT_BYTES = 64 * 1024 * 1024;\n\nexport class RetainedAttachmentTransportLimitError extends Error {\n constructor() {\n super(\n \"Active uploaded images exceed the 64 MiB inline transport limit. \" +\n \"History was preserved and no new image bytes were downloaded. \" +\n \"Start a smaller conversation or fork before the image-heavy messages.\",\n );\n this.name = \"RetainedAttachmentTransportLimitError\";\n }\n}\n\nexport type ModelAttachmentContent = {\n kind: \"image\" | \"file\";\n fileId: string;\n filename: string;\n contentType: string;\n dataUrl: string;\n};\n\nexport type ModelHistoryAttachmentProjector = (\n items: Array<Record<string, unknown>>,\n options?: ModelHistoryAttachmentProjectionOptions,\n) => Promise<Array<Record<string, unknown>>>;\n\nexport type ModelHistoryAttachmentProjectionOptions = {\n /** Exact, already-authorized files attached to the triggering message. */\n inlineFiles?: readonly FileAsset[];\n};\n\nexport type ModelAttachmentInputPolicy = {\n supportsImageInput: boolean;\n inputFileMediaTypes: readonly string[];\n};\n\nconst MODEL_IMAGE_CONTENT_TYPES = new Set([\"image/gif\", \"image/jpeg\", \"image/png\", \"image/webp\"]);\n\nconst MODEL_FILE_CONTENT_TYPES = new Set([\n \"application/json\",\n \"application/pdf\",\n \"application/x-yaml\",\n \"application/yaml\",\n]);\n\n// Generic XML has equivalent application/* and text/* registrations. Keep both\n// aliases on the sandbox-path fallback until a provider parser boundary is\n// explicitly supported and verified; MIME spelling must not bypass the fence.\nconst BLOCKED_TEXT_CONTENT_TYPES = new Set([\n \"text/css\",\n \"text/html\",\n \"text/javascript\",\n \"text/xml\",\n]);\n\nfunction safeErrorType(error: unknown): string {\n if (!(error instanceof Error)) return typeof error;\n const name = error.name.trim();\n return /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(name) ? name : \"Error\";\n}\n\nfunction modelAttachmentDescriptor(\n contentType: string,\n): Pick<ModelAttachmentContent, \"kind\" | \"contentType\"> | null {\n const normalized = contentType.toLowerCase().split(\";\", 1)[0]?.trim() ?? \"\";\n if (MODEL_IMAGE_CONTENT_TYPES.has(normalized)) {\n return { kind: \"image\", contentType: normalized };\n }\n if (\n MODEL_FILE_CONTENT_TYPES.has(normalized) ||\n (normalized.startsWith(\"text/\") && !BLOCKED_TEXT_CONTENT_TYPES.has(normalized))\n ) {\n return { kind: \"file\", contentType: normalized };\n }\n return null;\n}\n\nexport async function modelAttachmentContentForFiles(\n files: FileAsset[],\n readFileBytes: (file: FileAsset) => Promise<Uint8Array>,\n options: { retainAll?: boolean } = {},\n): Promise<ModelAttachmentContent[]> {\n const selected: Array<{\n file: FileAsset;\n descriptor: Pick<ModelAttachmentContent, \"kind\" | \"contentType\">;\n checksum: string;\n }> = [];\n let remainingBytes = options.retainAll\n ? Number.POSITIVE_INFINITY\n : MAX_INLINE_MODEL_ATTACHMENT_BYTES;\n for (const file of files) {\n const descriptor = modelAttachmentDescriptor(file.contentType);\n const checksum = file.sha256?.trim().toLowerCase() ?? \"\";\n if (\n file.status !== \"ready\" ||\n !descriptor ||\n descriptor.kind !== \"image\" ||\n file.sizeBytes > MAX_INLINE_MODEL_ATTACHMENT_BYTES ||\n file.sizeBytes > remainingBytes ||\n !/^[a-f0-9]{64}$/.test(checksum)\n ) {\n continue;\n }\n selected.push({ file, descriptor, checksum });\n remainingBytes -= file.sizeBytes;\n }\n\n const attachments = new Array<ModelAttachmentContent | undefined>(selected.length);\n let cursor = 0;\n const worker = async () => {\n while (cursor < selected.length) {\n const index = cursor++;\n const { file, descriptor, checksum } = selected[index]!;\n try {\n const bytes = await readFileBytes(file);\n if (bytes.byteLength !== file.sizeBytes) {\n console.error(\"model attachment bytes did not match finalized metadata\", {\n fileId: file.id,\n expectedSizeBytes: file.sizeBytes,\n actualSizeBytes: bytes.byteLength,\n });\n continue;\n }\n if (createHash(\"sha256\").update(bytes).digest(\"hex\") !== checksum) {\n console.error(\"model attachment checksum did not match finalized metadata\", {\n fileId: file.id,\n });\n continue;\n }\n attachments[index] = {\n kind: descriptor.kind,\n fileId: file.id,\n filename: file.safeFilename,\n contentType: descriptor.contentType,\n dataUrl: `data:${descriptor.contentType};base64,${Buffer.from(bytes).toString(\"base64\")}`,\n };\n } catch (error) {\n // The sandbox-path projection remains available for every file. A direct\n // provider-content read is an additive fast path and must not turn a\n // transient storage read into loss of the accepted prompt.\n console.error(\"model attachment content read failed; retaining sandbox path fallback\", {\n fileId: file.id,\n errorType: safeErrorType(error),\n });\n }\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(8, selected.length) }, async () => await worker()),\n );\n return attachments.filter(\n (attachment): attachment is ModelAttachmentContent => attachment !== undefined,\n );\n}\n\nfunction attachmentRefsFromItem(item: Record<string, unknown>): FileResourceRef[] {\n const raw = item[MODEL_ATTACHMENT_REFS_FIELD];\n if (!Array.isArray(raw)) return [];\n const refs: FileResourceRef[] = [];\n for (const candidate of raw) {\n const parsed = FileResourceRef.safeParse(candidate);\n if (parsed.success) refs.push(parsed.data);\n }\n return refs;\n}\n\nfunction attachmentReceiptText(ref: FileResourceRef): string {\n // The durable reference is immutable; live metadata/authority must not rewrite\n // old receipt text. Pixel delivery remains subject to current file authority.\n return (\n `[Attachment: fileId=${ref.fileId}; mountDirectory=${resourceMountPath(ref)}. ` +\n `Use the existing file there, or call files__files_get_download_url with this fileId and ` +\n `download it with the shell.]`\n );\n}\n\n/**\n * Build one turn-scoped durable-attachment projector. Resolve active refs under\n * current file authority and memoize metadata/bytes for retries and compaction.\n * A turn boundary never changes an authorized attachment's representation.\n */\nexport function createModelHistoryAttachmentProjector(\n policy: ModelAttachmentInputPolicy,\n readFileBytes?: (file: FileAsset) => Promise<Uint8Array>,\n loadAuthorizedFiles?: (fileIds: readonly string[]) => Promise<readonly FileAsset[]>,\n): ModelHistoryAttachmentProjector {\n const contentById = new Map<string, ModelAttachmentContent>();\n const attemptedContentIds = new Set<string>();\n const fileById = new Map<string, FileAsset>();\n const resolvedFileIds = new Set<string>();\n const retainedByteSizes = new Map<string, number>();\n\n return async (items, options = {}) => {\n for (const file of options.inlineFiles ?? []) {\n fileById.set(file.id, file);\n resolvedFileIds.add(file.id);\n }\n const refsByIndex = new Map<number, FileResourceRef[]>();\n const orderedFileIds: string[] = [];\n const seenFileIds = new Set<string>();\n for (let index = 0; index < items.length; index += 1) {\n const refs = attachmentRefsFromItem(items[index]!);\n if (refs.length === 0) continue;\n refsByIndex.set(index, refs);\n for (const ref of refs) {\n if (items[index]![MODEL_ATTACHMENT_CATALOG_MARKER] === true || seenFileIds.has(ref.fileId))\n continue;\n seenFileIds.add(ref.fileId);\n orderedFileIds.push(ref.fileId);\n }\n }\n if (refsByIndex.size === 0) return items;\n const unresolved = orderedFileIds.filter((id) => !resolvedFileIds.has(id));\n if (loadAuthorizedFiles && unresolved.length > 0) {\n const files = await loadAuthorizedFiles(unresolved);\n for (const file of files) fileById.set(file.id, file);\n for (const id of unresolved) resolvedFileIds.add(id);\n }\n\n if (readFileBytes) {\n const admitted = new Map(retainedByteSizes);\n let requestImageBytes = 0;\n for (const [index, refs] of refsByIndex) {\n if (items[index]![MODEL_ATTACHMENT_CATALOG_MARKER] === true) continue;\n for (const ref of refs) {\n const file = fileById.get(ref.fileId);\n if (\n !file ||\n !policy.supportsImageInput ||\n file.status !== \"ready\" ||\n file.sizeBytes > MAX_INLINE_MODEL_ATTACHMENT_BYTES ||\n modelAttachmentDescriptor(file.contentType)?.kind !== \"image\" ||\n !/^[a-f0-9]{64}$/i.test(file.sha256?.trim() ?? \"\")\n )\n continue;\n // Repeated references share cached bytes but repeat in the wire body.\n requestImageBytes += file.sizeBytes;\n admitted.set(file.id, file.sizeBytes);\n }\n }\n const turnImageBytes = [...admitted.values()].reduce((sum, bytes) => sum + bytes, 0);\n if (\n requestImageBytes > MAX_RETAINED_MODEL_ATTACHMENT_BYTES ||\n turnImageBytes > MAX_RETAINED_MODEL_ATTACHMENT_BYTES\n ) {\n throw new RetainedAttachmentTransportLimitError();\n }\n for (const [id, bytes] of admitted) retainedByteSizes.set(id, bytes);\n // Every active attachment uses the same authorized projection. Metadata\n // and bytes are resolved once per turn, including compaction and retries.\n const readable = [...orderedFileIds]\n .reverse()\n .map((id) => fileById.get(id))\n .filter((file): file is FileAsset => {\n if (!file || attemptedContentIds.has(file.id)) return false;\n const descriptor = modelAttachmentDescriptor(file.contentType);\n return Boolean(descriptor && descriptor.kind === \"image\" && policy.supportsImageInput);\n });\n for (const file of readable) attemptedContentIds.add(file.id);\n const content = await modelAttachmentContentForFiles(readable, readFileBytes, {\n retainAll: true,\n });\n const loadedIds = new Set(content.map((entry) => entry.fileId));\n for (const file of readable) {\n if (\n file.status === \"ready\" &&\n file.sizeBytes <= MAX_INLINE_MODEL_ATTACHMENT_BYTES &&\n /^[a-f0-9]{64}$/i.test(file.sha256 ?? \"\") &&\n !loadedIds.has(file.id)\n ) {\n // Do not let a retry silently proceed with pixels removed.\n for (const candidate of readable) attemptedContentIds.delete(candidate.id);\n throw new Error(`Retained attachment bytes unavailable or invalid: ${file.id}`);\n }\n }\n for (const attachment of content) contentById.set(attachment.fileId, attachment);\n }\n\n const projected = [...items];\n for (const [index, refs] of refsByIndex) {\n const original = items[index]!;\n const existingContent = Array.isArray(original.content)\n ? [...original.content]\n : [{ type: \"input_text\", text: String(original.content ?? \"\") }];\n const attachmentParts = refs.flatMap((ref) => {\n const currentFile =\n original[MODEL_ATTACHMENT_CATALOG_MARKER] === true ? undefined : fileById.get(ref.fileId);\n const attachment = currentFile ? contentById.get(ref.fileId) : undefined;\n const receipt = {\n type: \"input_text\",\n text: attachmentReceiptText(ref),\n };\n if (!attachment || attachment.kind !== \"image\") {\n return [receipt];\n }\n return [receipt, { type: \"input_image\", image: attachment.dataUrl }];\n });\n const clone: Record<string, unknown> = {\n ...original,\n content: [...existingContent, ...attachmentParts],\n };\n delete clone[MODEL_ATTACHMENT_REFS_FIELD];\n projected[index] = clone;\n }\n return projected;\n };\n}\n\n/** Add current trigger refs only when older/local history predates durable stamping. */\nexport function withCurrentUserAttachmentRefs(\n historyItems: Array<Record<string, unknown>>,\n refs: FileResourceRef[],\n): Array<Record<string, unknown>> {\n if (refs.length === 0) return historyItems;\n // Compaction can put a catalog after the triggering user message. A ref\n // already retained anywhere in canonical history must not be copied onto\n // that older catalog (and then disappear when the next turn replays it).\n const retainedIds = new Set(\n historyItems.flatMap((item) => attachmentRefsFromItem(item).map((ref) => ref.fileId)),\n );\n const missing = refs.filter((ref) => !retainedIds.has(ref.fileId));\n if (missing.length === 0) return historyItems;\n for (let index = historyItems.length - 1; index >= 0; index -= 1) {\n const item = historyItems[index]!;\n if (item[MODEL_ATTACHMENT_CATALOG_MARKER] === true) continue;\n if (item.type !== \"message\" || item.role !== \"user\") continue;\n const existing = attachmentRefsFromItem(item);\n const existingIds = new Set(existing.map((ref) => ref.fileId));\n const additions = missing.filter((ref) => !existingIds.has(ref.fileId));\n if (additions.length === 0) return historyItems;\n const projected = [...historyItems];\n projected[index] = { ...item, [MODEL_ATTACHMENT_REFS_FIELD]: [...existing, ...additions] };\n return projected;\n }\n return historyItems;\n}\n\nexport async function turnInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: Awaited<ReturnType<typeof getSessionEvent>>,\n options: TurnInputOptions,\n): Promise<PreparedTurnInput> {\n if (!trigger) {\n throw new Error(\"Missing trigger event\");\n }\n const updates = await measureHistoryPreparationPhase(\n options,\n \"system_update_load\",\n async () =>\n await listSessionSystemUpdatesForTurn(\n db,\n trigger.workspaceId,\n trigger.sessionId,\n options.turnId,\n ),\n );\n // A logical turn can receive another atomic batch when an interrupted\n // attempt resumes. Every update must retain its durable receipt, but the\n // turn-wide query legitimately spans multiple history items. Canonical\n // history owns their ordering and exactly-once inclusion below.\n if (updates.some((update) => !update.deliveredHistoryItemId)) {\n throw new Error(\"Delivered internal update has no durable model-memory batch\");\n }\n const internalContext = joinInternalContext(\n options.recovering\n ? [\n \"[OpenGeni inference recovery]\",\n \"Continue the same inference from durable conversation and sandbox state. A previous execution stopped before it could finish. Do not repeat completed side effects; inspect actual state when uncertain.\",\n ].join(\"\\n\")\n : undefined,\n options.unavailableSandboxFilesNote,\n options.runCredentialsNote,\n options.mcpAvailabilityNote,\n options.knowledgeSourcePreparationNote,\n );\n if (trigger.type === \"user.message\") {\n const payload = trigger.payload as {\n text?: unknown;\n annotations?: unknown;\n resources?: unknown;\n };\n const hasAnnotations = Array.isArray(payload.annotations) && payload.annotations.length > 0;\n if (typeof payload.text !== \"string\" || (payload.text.trim().length === 0 && !hasAnnotations)) {\n throw new Error(\"user.message payload is missing text and annotations\");\n }\n const resources = Array.isArray(payload.resources) ? (payload.resources as ResourceRef[]) : [];\n const fileAttachments = await measureHistoryPreparationPhase(\n options,\n \"current_attachment_resolution\",\n async () =>\n await resolveUserMessageFileAttachments(\n db,\n options.fileAuthority.accountId,\n trigger.workspaceId,\n options.fileAuthority.subjectId,\n resources,\n ),\n );\n const attachmentContext = userMessageAttachmentsContext(fileAttachments);\n return await messageInput(\n db,\n runtime,\n agent,\n trigger,\n undefined,\n joinInternalContext(internalContext, attachmentContext),\n fileAttachments,\n options.providerApi,\n options.projectCanonicalHistory,\n options.materializeModelHistory,\n options.projectModelHistory,\n options.loadActiveHistory,\n options,\n );\n }\n // Maintenance has no user message or delivered-update batch. It still needs\n // the ordinary history/projection path so SDK preparation can capture the\n // same model request prefix before the queued compaction stops inference.\n if (\n trigger.type === \"system.update.delivered\" ||\n trigger.type === \"session.context.compaction.requested\"\n ) {\n if (trigger.type === \"system.update.delivered\" && updates.length === 0) {\n throw new Error(\"Internal update inference has no delivered updates\");\n }\n return await messageInput(\n db,\n runtime,\n agent,\n trigger,\n undefined,\n internalContext,\n [],\n options.providerApi,\n options.projectCanonicalHistory,\n options.materializeModelHistory,\n options.projectModelHistory,\n options.loadActiveHistory,\n options,\n );\n }\n if (trigger.type === \"user.approvalDecision\" || trigger.type === \"user.humanInputResponse\") {\n return await openSuffixMessageInput(db, runtime, agent, trigger, internalContext, options);\n }\n throw new Error(`Unsupported trigger event type: ${trigger.type}`);\n}\n\nfunction joinInternalContext(...parts: Array<string | undefined>): string | undefined {\n const content = parts.map((part) => part?.trim()).filter((part): part is string => Boolean(part));\n return content.length > 0 ? content.join(\"\\n\\n\") : undefined;\n}\n\nasync function openSuffixMessageInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: NonNullable<Awaited<ReturnType<typeof getSessionEvent>>>,\n internalContext: string | undefined,\n options: TurnInputOptions,\n): Promise<PreparedTurnInput> {\n const suffixRows = await listTurnOpenSuffixToolCalls(\n db,\n trigger.workspaceId,\n trigger.sessionId,\n options.turnId,\n );\n if (suffixRows.length === 0) {\n throw new Error(\"Open suffix resume has no interruption rows\");\n }\n if (suffixRows.some((row) => row.resultItem == null)) {\n throw new Error(\"Open suffix resume still has unresolved members\");\n }\n return await messageInput(\n db,\n runtime,\n agent,\n trigger,\n undefined,\n internalContext,\n [],\n options.providerApi,\n options.projectCanonicalHistory,\n options.materializeModelHistory,\n options.projectModelHistory,\n options.loadActiveHistory,\n options,\n );\n}\n\n/** Build one inference from canonical history plus attempt-local operational context. */\nasync function messageInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: NonNullable<Awaited<ReturnType<typeof getSessionEvent>>>,\n text: string | undefined,\n internalContext: string | undefined,\n currentAttachments: UserMessageFileAttachment[] = [],\n providerApi: HistoryProviderApi = \"responses\",\n projectCanonicalHistory?: ModelHistoryAttachmentProjector,\n materializeModelHistory?: ModelHistoryAttachmentProjector,\n projectModelHistory?: ModelHistoryAttachmentProjector,\n loadActiveHistory: typeof getActiveSessionHistoryItemsPaged = getActiveSessionHistoryItemsPaged,\n preparationOptions: Pick<TurnInputOptions, \"onPreparationPhase\"> = {},\n): Promise<PreparedTurnInput> {\n const currentAttachmentRefs = currentAttachments.map((attachment) => attachment.resource);\n const [stored, envelope] = await Promise.all([\n measureHistoryPreparationPhase(preparationOptions, \"durable_history_load\", async () =>\n loadActiveHistory(db, trigger.workspaceId, trigger.sessionId),\n ),\n measureHistoryPreparationPhase(preparationOptions, \"sandbox_envelope_load\", async () =>\n getSandboxSessionEnvelope(db, trigger.workspaceId, trigger.sessionId),\n ),\n ]);\n const canonicalView = await measureHistoryPreparationPhase(\n preparationOptions,\n \"canonical_projection\",\n async () => {\n const active = projectRejectedProviderArtifacts(stored);\n return projectCanonicalHistory ? await projectCanonicalHistory(active) : active;\n },\n );\n const providerView = await measureHistoryPreparationPhase(\n preparationOptions,\n \"provider_projection\",\n () => projectHistoryForProvider(canonicalView, providerApi),\n );\n const referencedHistory = await measureHistoryPreparationPhase(\n preparationOptions,\n \"attachment_ref_projection\",\n () => withCurrentUserAttachmentRefs(providerView, currentAttachmentRefs),\n );\n const materializedHistory = await measureHistoryPreparationPhase(\n preparationOptions,\n \"screenshot_materialization\",\n async () =>\n materializeModelHistory\n ? await materializeModelHistory(referencedHistory)\n : referencedHistory,\n );\n const historyItems = await measureHistoryPreparationPhase(\n preparationOptions,\n \"model_attachment_projection\",\n async () =>\n projectModelHistory\n ? await projectModelHistory(materializedHistory, {\n inlineFiles: currentAttachments.map((attachment) => attachment.file),\n })\n : materializedHistory,\n );\n const prepared = await measureHistoryPreparationPhase(\n preparationOptions,\n \"runtime_input_assembly\",\n async () =>\n await runtime.prepareInput(agent, {\n kind: \"message\",\n ...(text ? { text } : {}),\n ...(internalContext ? { internalContext } : {}),\n historyItems: historyItems as any,\n sandboxEnvelope: envelope,\n ...(projectModelHistory ? { modelInputAlreadyProjected: true } : {}),\n }),\n );\n const providerArtifactCandidates = await measureHistoryPreparationPhase(\n preparationOptions,\n \"artifact_candidate_scan\",\n () => {\n const preparedItems = Array.isArray(prepared.input)\n ? new Set(prepared.input)\n : new Set<unknown>();\n return {\n knownHistoryItemIds: stored.map((row) => row.id),\n historyItemIds: stored\n .filter(\n (row) =>\n row.providerArtifactInvalidatedAt === null &&\n hasOpaqueProviderArtifact(row.item) &&\n preparedItems.has(row.item),\n )\n .map((row) => row.id),\n };\n },\n );\n return {\n input: prepared,\n persistedHistoryCount: prepared.persistedHistoryCount,\n providerArtifactCandidates,\n };\n}\n\nexport async function userMessageTextWithAttachments(\n db: Database,\n accountId: string,\n workspaceId: string,\n subjectId: string | null,\n text: string,\n resources: ResourceRef[],\n): Promise<string> {\n const fileAttachments = await resolveUserMessageFileAttachments(\n db,\n accountId,\n workspaceId,\n subjectId,\n resources,\n );\n const attachmentContext = userMessageAttachmentsContext(fileAttachments);\n return attachmentContext ? [text, \"\", attachmentContext].join(\"\\n\") : text;\n}\n\ntype UserMessageFileAttachment = {\n resource: Extract<ResourceRef, { kind: \"file\" }>;\n file: FileAsset;\n};\n\nasync function resolveUserMessageFileAttachments(\n db: Database,\n accountId: string,\n workspaceId: string,\n subjectId: string | null,\n resources: ResourceRef[],\n): Promise<UserMessageFileAttachment[]> {\n const fileResources = resources.filter(\n (resource): resource is FileResourceRef => resource.kind === \"file\",\n );\n if (fileResources.length === 0) return [];\n const files = await getFilesForSubject(db, {\n accountId,\n workspaceId,\n subjectId,\n fileIds: fileResources.map((resource) => resource.fileId),\n });\n const fileById = new Map(files.map((file) => [file.id, file]));\n return fileResources.map((resource) => {\n const file = fileById.get(resource.fileId);\n if (!file) throw new Error(`File not found: ${resource.fileId}`);\n return { resource, file };\n });\n}\n\nfunction userMessageAttachmentsContext(\n attachments: UserMessageFileAttachment[],\n): string | undefined {\n const attachedFiles = attachments.map(\n ({ resource, file }) =>\n `- ${file.filename} (${file.contentType}, ${file.sizeBytes} bytes): ${sandboxFilePath(resource, file)}`,\n );\n if (attachedFiles.length === 0) {\n return undefined;\n }\n return [\"Attached files are available in the sandbox:\", ...attachedFiles].join(\"\\n\");\n}\n\nfunction sandboxFilePath(\n resource: Extract<ResourceRef, { kind: \"file\" }>,\n file: FileAsset,\n): string {\n return `${resourceMountPath(resource)}/${file.safeFilename}`;\n}\n","// ChatGPT plan entitlement for Codex-billed turns.\n//\n// A connected ChatGPT account can move to a plan that no longer includes the\n// requested model (production: Pro to Free, then every request answered with\n// an empty HTTP 400). This module turns that evidence into a typed decision:\n// re-check the account's current plan, and either exclude that credential for\n// this model and let the normal failover protocol move the SAME turn, or fail\n// with a typed, plain-language payload. It never retries the request itself.\n\nimport { productLabelForModelId } from \"@opengeni/config\";\nimport {\n codexPlanDisplayName,\n codexPlanEntitlementLost,\n codexPlanIsUpgrade,\n codexPlanKey,\n type CodexEntitlementRejection,\n} from \"@opengeni/codex\";\nimport {\n codexPlanExcludesModel,\n codexPlanPreviouslyExcludedModel,\n connectionModelAllowed,\n type CodexCredentialPlanRecheck,\n type CodexPlanEntitlementExclusion,\n} from \"@opengeni/db\";\n\nexport const CODEX_PLAN_ENTITLEMENT_CODE = \"codex_plan_entitlement\";\nexport const CODEX_REQUEST_REJECTED_CODE = \"codex_request_rejected\";\n\nexport type CodexPlanEntitlementFailurePayload = {\n error: string;\n code: typeof CODEX_PLAN_ENTITLEMENT_CODE;\n retryable: false;\n planType: string | null;\n model: string | null;\n detail?: string;\n};\n\nexport type CodexRequestRejectedFailurePayload = {\n error: string;\n code: typeof CODEX_REQUEST_REJECTED_CODE;\n retryable: false;\n planType: string | null;\n detail?: string;\n};\n\n/**\n * The user-set label of one connected ChatGPT account. The account email is\n * deliberately never used: this text lands in the durable `turn.failed` event\n * that every session reader (including embedding-host end users) can see, and\n * an inherited organization credential's email may be a member's personal\n * address. Without a label the copy says \"The connected ChatGPT account\".\n */\nexport function codexAccountDisplayLabel(\n account: { label: string | null } | null | undefined,\n): string | null {\n const label = account?.label?.trim() || null;\n return label ? label.slice(0, 120) : null;\n}\n\nfunction accountPhrase(accountLabel: string | null): string {\n return accountLabel ? `The ChatGPT account \"${accountLabel}\"` : \"The connected ChatGPT account\";\n}\n\nfunction rejectionDetail(rejection: CodexEntitlementRejection | null): string | undefined {\n if (!rejection) return undefined;\n return rejection.evidence === \"empty_body\"\n ? `The Codex backend answered HTTP ${rejection.status} with no error body.`\n : `The Codex backend refused the model for this plan (HTTP ${rejection.status}).`;\n}\n\n/** Terminal copy when the serving account's plan does not include the model. */\nexport function codexPlanEntitlementFailurePayload(input: {\n accountLabel: string | null;\n planType: string | null;\n planChanged: boolean;\n modelId: string | null;\n rejection?: CodexEntitlementRejection | null;\n /** The same turn waits for another connected account instead of failing. */\n waiting?: boolean;\n}): CodexPlanEntitlementFailurePayload {\n const plan = codexPlanDisplayName(input.planType);\n const model = input.modelId ? productLabelForModelId(input.modelId) : \"this model\";\n const lead = accountPhrase(input.accountLabel);\n const next = input.waiting\n ? \"OpenGeni is waiting for another connected account to become available.\"\n : \"Upgrade it, use another connected account, or choose another model.\";\n const error = plan\n ? `${lead} ${input.planChanged ? \"is now\" : \"is\"} on the ${plan} plan, which doesn't include ${model}. ${next}`\n : `${lead} no longer has access to ${model} on its current plan. ${next}`;\n const detail = rejectionDetail(input.rejection ?? null);\n return {\n error,\n code: CODEX_PLAN_ENTITLEMENT_CODE,\n retryable: false,\n planType: plan ? codexPlanKey(input.planType) : null,\n model: input.modelId,\n ...(detail ? { detail } : {}),\n };\n}\n\n/**\n * Terminal copy for an empty Codex rejection. With `planChecked`, the account's\n * plan was re-read and did not explain it, so OpenGeni kept the account.\n */\nexport function codexRequestRejectedFailurePayload(input: {\n accountLabel: string | null;\n planType: string | null;\n rejection: CodexEntitlementRejection;\n planChecked?: boolean;\n}): CodexRequestRejectedFailurePayload {\n const plan = codexPlanDisplayName(input.planType);\n const lead = accountPhrase(input.accountLabel);\n const planClause =\n input.planChecked === false\n ? \"\"\n : plan\n ? `${lead} still reports the ${plan} plan, so OpenGeni did not switch accounts. `\n : `OpenGeni could not confirm the current plan of ${lead.charAt(0).toLowerCase()}${lead.slice(1)}, so it did not switch accounts. `;\n return {\n error:\n `The Codex backend rejected this request (HTTP ${input.rejection.status}) without an error message. ` +\n `${planClause}Try again, or choose another model if it keeps failing.`,\n code: CODEX_REQUEST_REJECTED_CODE,\n retryable: false,\n planType: plan ? codexPlanKey(input.planType) : null,\n ...(rejectionDetail(input.rejection) ? { detail: rejectionDetail(input.rejection)! } : {}),\n };\n}\n\n/**\n * Admission-time refusal: the only accounts that could serve this turn were\n * already proven not to include its model on their current plan.\n */\nexport class CodexPlanEntitlementError extends Error {\n readonly code = CODEX_PLAN_ENTITLEMENT_CODE;\n constructor(readonly payload: CodexPlanEntitlementFailurePayload) {\n super(payload.error);\n this.name = \"CodexPlanEntitlementError\";\n }\n}\n\nexport type CodexPlanEntitlementAssessment =\n | {\n kind: \"entitlement_lost\";\n /**\n * Plan the exclusion binds to: the freshly observed plan, or the\n * recorded plan when the provider reported none.\n */\n planType: string | null;\n /** The provider reported the current plan during this re-check. */\n planObserved: boolean;\n /** The observed plan was reached by a recorded (non-upgrade) plan change. */\n planChanged: boolean;\n credentialVersion: number | null;\n }\n | { kind: \"unexplained\"; planType: string | null };\n\n/** Pure decision over one plan re-check (see `codexPlanEntitlementLost`). */\nexport function assessCodexPlanEntitlement(\n rejection: CodexEntitlementRejection,\n recheck: CodexCredentialPlanRecheck,\n modelId: string | null,\n): CodexPlanEntitlementAssessment {\n const planObserved = recheck.planType !== null;\n // The persisted change record, or (if that write did not land) the plan\n // recorded just before this re-check when the fresh observation differs.\n const planChangedFrom =\n planObserved &&\n recheck.previousPlanType !== null &&\n codexPlanKey(recheck.previousPlanType) !== codexPlanKey(recheck.planType)\n ? recheck.previousPlanType\n : recheck.planChangedFrom;\n const planChanged =\n planObserved &&\n planChangedFrom !== null &&\n codexPlanKey(planChangedFrom) !== codexPlanKey(recheck.planType) &&\n !codexPlanIsUpgrade(planChangedFrom, recheck.planType);\n if (\n codexPlanEntitlementLost({\n evidence: rejection.evidence,\n currentPlanType: recheck.planType,\n planChangedFrom,\n previouslyExcluded:\n planObserved &&\n codexPlanPreviouslyExcludedModel(\n { planType: recheck.planType, planEntitlementExclusion: recheck.exclusion },\n modelId,\n ),\n })\n ) {\n return {\n kind: \"entitlement_lost\",\n planType: planObserved ? recheck.planType : recheck.previousPlanType,\n planObserved,\n planChanged,\n credentialVersion: recheck.credentialVersion,\n };\n }\n return { kind: \"unexplained\", planType: recheck.planType };\n}\n\ntype AdmissionAccount = {\n id: string;\n label: string | null;\n planType: string | null;\n allocatorEnabled: boolean;\n allowedModelIds?: string[] | null;\n planEntitlementExclusion?: CodexPlanEntitlementExclusion | null;\n};\n\n/**\n * Pure admission check after credential selection found no account. Returns\n * the plan-excluded accounts that alone explain it, or null when capacity,\n * health, or policy (not plan entitlement) is the reason:\n *\n * - a manual pin (user intent) whose account's plan excludes the model;\n * - with rotation off, the active account's plan excludes the model;\n * - with rotation on, every allocatable account permitted for the model is\n * plan-excluded.\n */\nexport function codexPlanEntitlementAdmissionBlock<T extends AdmissionAccount>(input: {\n accounts: readonly T[];\n modelId: string;\n credentialId: string | null;\n rotationEnabled: boolean;\n activeCredentialId: string | null;\n pinnedCredentialId: string | null;\n pinSource: \"manual\" | \"policy\" | null;\n now: Date;\n}): T[] | null {\n if (input.credentialId !== null) return null;\n const permitted = input.accounts.filter((account) =>\n connectionModelAllowed(account.allowedModelIds, input.modelId),\n );\n const excluded = permitted.filter((account) =>\n codexPlanExcludesModel(account, input.modelId, input.now),\n );\n if (excluded.length === 0) return null;\n if (input.pinnedCredentialId && input.pinSource !== \"policy\") {\n const pinned = excluded.find((account) => account.id === input.pinnedCredentialId);\n return pinned ? [pinned] : null;\n }\n if (!input.rotationEnabled) {\n const active = excluded.find((account) => account.id === input.activeCredentialId);\n return active ? [active] : null;\n }\n const allocatable = permitted.filter((account) => account.allocatorEnabled);\n const allocatableExcluded = allocatable.filter((account) =>\n codexPlanExcludesModel(account, input.modelId, input.now),\n );\n return allocatable.length > 0 && allocatableExcluded.length === allocatable.length\n ? allocatableExcluded\n : null;\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type {\n ConnectionCredentialsPort,\n DocumentAuthorityKind,\n EntitlementsPort,\n KnowledgeSourceSyncRunSummary,\n ScheduledTaskTriggerType,\n TurnInitiator,\n} from \"@opengeni/contracts\";\nimport type {\n Database,\n SessionWorkflowWakeDeliveryResult,\n SessionAdmissionFence,\n} from \"@opengeni/db\";\nimport type { DocumentServices } from \"@opengeni/documents\";\nimport type { EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport type { OpenGeniRuntime } from \"@opengeni/runtime\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\n\n// Signal (start-if-needed) a session's Temporal workflow so a queued turn it\n// cannot otherwise observe gets claimed. Used to wake a PARENT session's\n// workflow when a spawned worker completes: the parent may have idled and let\n// its workflow run complete, so a plain signal would not start one — this must\n// signalWithStart. Injected (not built from the worker's NativeConnection)\n// because the worker package owns only the worker runtime, not a client; an\n// missing signaler leaves the committed outbox revision for the global repair\n// sweep; production workers always inject this dependency.\nexport type WakeSessionWorkflowSignal = (input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n wakeRevision: number;\n interruptionRequested?: boolean;\n /** Called after transport acceptance, before the fallible durable ACK. */\n onSignalAccepted?: () => void;\n}) => Promise<SessionWorkflowWakeDeliveryResult | void>;\n\nexport type SignalCodexCapacityWorkflow = (input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n wakeRevision: number;\n}) => Promise<void>;\n\n/** Start the versioned, per-box sandbox reaper from the history-stable legacy\n * activity. The legacy Schedule workflow must keep its exact historical\n * ScheduleActivity command across mixed-version worker pools. */\nexport type StartSandboxReaperWorkflow = () => Promise<\"started\" | \"already_running\">;\n\n/** Start-or-observe the one durable reconciler for a paid video operation. */\nexport type StartVideoGenerationWorkflow = (input: {\n accountId: string;\n workspaceId: string;\n operationId: string;\n}) => Promise<\"started\" | \"already_running\">;\n\n/** Exact activity-owned proof that the hard sandbox/tool fence physically\n * drained. This is delivery evidence only: the workflow still validates the\n * persisted attempt dispatch and commits the authoritative Postgres receipt. */\nexport type SessionAttemptQuiescenceProof = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n workflowId: string;\n workflowRunId: string;\n activityId: string;\n};\n\nexport type SignalSessionAttemptQuiesced = (input: SessionAttemptQuiescenceProof) => Promise<void>;\n\nexport type InspectSessionAttemptActivity = (input: {\n workflowId: string;\n workflowRunId: string;\n activityId: string;\n}) => Promise<\"pending\" | \"settled\">;\n\n/** Services shared by both Temporal worker roles. Keep this graph free of the\n * agent runtime and document parser so each process can load only its role. */\nexport type SharedActivityServices = {\n settings: Settings;\n /**\n * Original environment/host settings retained across live database-catalog\n * refreshes. Older embedded test hosts may omit it and fall back to settings.\n */\n catalogSourceSettings?: Settings;\n db: Database;\n bus: EventBus;\n objectStorage: ObjectStorage | null;\n observability: Observability;\n wakeSessionWorkflow: WakeSessionWorkflowSignal | null;\n /** Durable signalWithStart fallback used only after the activity's direct\n * physical-quiescence receipt write exhausts its bounded DB retries. */\n signalSessionAttemptQuiesced: SignalSessionAttemptQuiesced | null;\n /** Server-authoritative Temporal activity lease inspection used only to\n * recover a missing quiescence receipt after the original activity vanished. */\n inspectSessionAttemptActivity: InspectSessionAttemptActivity | null;\n /** Revision-carrying capacity nudge; generic outbox repair is also sufficient. */\n signalCodexCapacityWorkflow?: SignalCodexCapacityWorkflow | null;\n /** Production control workers inject this Temporal client edge. A null edge\n * deliberately retains the composite implementation for embedded/test hosts. */\n startSandboxReaperWorkflow?: StartSandboxReaperWorkflow | null;\n startVideoGenerationWorkflow?: StartVideoGenerationWorkflow | null;\n // §7.5 P3 — host-entitlements port, the WORKER half of the same seam the API\n // edge exposes on `AppDependencies`. When set, `ensureRunAllowed` (turn-entry\n // AND the mid-stream budget valve) delegates the funding decision to\n // `admitRun` instead of reading `getBillingBalance` locally. null/undefined\n // (standalone default) → today's local-ledger read runs unchanged.\n //\n // IDEMPOTENCY: the worker calls `admitRun` ONLY as an admission READ (\"may\n // this run/continue?\"), never to RECORD consumption. Usage is recorded\n // exactly once, by `recordUsageEvent` keyed on a deterministic idempotency\n // key the API already wrote at create-time — so a host PULL meter that also\n // observes that same recorded event is consulted without double-charging:\n // admission and metering are separate operations, and only metering carries\n // the idempotency key.\n entitlements?: EntitlementsPort | null;\n // §7.6 connection-credential provider — host connection-credential provider, the WORKER half of the\n // federated-connection boundary. When set, the run's per-run credential mint\n // delegates to the host instead of self-minting from `settings`:\n // - `gitCredentials` REPLACES `createGitHubAppInstallationToken(settings,…)`\n // in `sandboxEnvironmentForRun` (the GH_TOKEN / git-extraheader source).\n // - `sandboxSecrets` REPLACES the `environmentsEncryptionKeyBytes(settings)`\n // decrypt in `loadWorkspaceEnvironmentForRun`.\n // Each leg is independently optional; an unset leg falls through to today's\n // self-mint for THAT leg. null/undefined (standalone default) → both legs\n // self-mint byte-for-byte as today.\n //\n // workspace-scope cross-check CROSS-CHECK: a provider echoes the `workspaceId` it scoped the\n // credential to; the consuming activity ASSERTS agreement with the run's\n // workspace BEFORE injecting `GH_TOKEN` (or applying decrypted values). A host\n // mapping bug returning tenant B's creds for a tenant-A run is caught here.\n connectionCredentials?: ConnectionCredentialsPort | null;\n /** Standalone, default-off personal GitHub smart-HTTP broker consumer. */\n personalGitHubCredentials?: ConnectionCredentialsPort[\"gitCredentials\"] | null;\n};\n\n/** Control workers own short database and maintenance activities. Document\n * parsing is resolved lazily by the indexing activity itself. */\nexport type ControlActivityServices = SharedActivityServices;\n\n/** Turn workers own the model loop and never construct document parsers. */\nexport type TurnActivityServices = SharedActivityServices & {\n runtime: OpenGeniRuntime;\n /** Provider-free test/profiling seam; production injects the real runtime summarizer. */\n summarizeContextForCompaction: typeof import(\"@opengeni/runtime\").summarizeForCompaction;\n};\n\n/** Full test/embedded harness retained as a source-compatible superset. */\nexport type ActivityServices = ControlActivityServices &\n TurnActivityServices & {\n documentServices: DocumentServices;\n };\n\nexport type CodexCapacityWaitRef = {\n /** Absent only for Temporal histories written before provider-tagged waits. */\n provider?: \"codex\" | \"xai\";\n waiterId: string;\n generation: number;\n nextCheckAt: string;\n wakeRevision: number;\n};\n\nexport type XaiCapacityWaitRef = CodexCapacityWaitRef & { provider: \"xai\" };\n\nexport type GetCodexCapacityWaitInput = {\n workspaceId: string;\n sessionId: string;\n};\n\nexport type ReconcileCodexCapacityWaitInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n waiterId: string;\n generation: number;\n cause: \"timer\" | \"signal\" | \"queue\" | \"recovery\";\n /** Absent only for Codex waits and pre-provider-tagged workflow histories. */\n provider?: \"codex\" | \"xai\";\n};\n\nexport type ReconcileCodexCapacityWaitResult =\n | ({ action: \"waiting\" } & CodexCapacityWaitRef)\n | { action: \"resumed\" | \"paused\" | \"superseded\" | \"stale\" };\n\nexport type ActivityDependencies = Partial<ActivityServices>;\nexport type ControlActivityDependencies = Partial<ControlActivityServices>;\nexport type TurnActivityDependencies = Partial<TurnActivityServices>;\n\nexport type RunAgentTurnInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n workflowRunId: string;\n attemptId: string;\n trigger: { kind: \"next\" } | { kind: \"approval\"; triggerEventId: string };\n};\n\nexport type VideoGenerationTerminalStatus =\n | \"completed\"\n | \"provider_failed\"\n | \"cancelled_before_submit\"\n | \"outcome_unknown\"\n | \"retention_failed\";\n\nexport type VideoGenerationReconcileResult =\n | { action: \"waiting\"; delayMs: number }\n | { action: \"terminal\"; status: VideoGenerationTerminalStatus };\n\nexport type SettleSessionInterruptionsInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n workflowId: string;\n /**\n * Replay-only compatibility for session workflow histories created before\n * the receipt-gated cancellation v2 patch. New histories never send this\n * phase; the exact activity writes the authoritative receipt itself.\n */\n phase?: \"logical\" | \"attempt_quiesced\";\n};\n\nexport type PersistSessionAttemptQuiescenceInput = SessionAttemptQuiescenceProof;\n\nexport type ReconcileSessionAttemptQuiescenceInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n workflowId: string;\n};\n\nexport type ReconcileSessionAttemptQuiescenceResult = {\n action: \"quiesced\" | \"pending\" | \"stale\";\n};\n\nexport type FailSessionAttemptInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n /** Added in v2; old Temporal histories derive the session's canonical id. */\n workflowId?: string;\n /** Added in v2; old Temporal histories use the bounded 60-second floor. */\n retryDelayMs?: number;\n /** Added in v3. Upgraded turn workers classify failures from the atomic\n * admission transaction; omission is a rolling-deploy/legacy unknown and\n * deliberately keeps the recoverable wake behavior. */\n preClaimFailureDisposition?: PreClaimFailureDisposition;\n /** Added in v4. Retains the safe classified DB code so an ambiguously\n * committed claim discovered by the control lane can recover the exact\n * attempt instead of terminally failing it. */\n preClaimFailure?: PreClaimFailureDetail;\n admissionFence?: SessionAdmissionFence;\n /** Added in v4. A claimed attempt that lost operational database access\n * before turn-start completion carries its exact immutable turn identity so\n * the DB-only control lane can recover it instead of terminally failing it. */\n postClaimDatabaseRecovery?: PostClaimDatabaseRecoveryDetail;\n /** The workflow admission trigger is required to re-evaluate the same\n * durable admission branch before terminally settling a permanent failure. */\n trigger?: RunAgentTurnInput[\"trigger\"];\n error?: string;\n};\n\nexport type FailSessionAttemptResult =\n | { action: \"blocked\" }\n | { action: \"failed\" }\n | { action: \"recovering\" }\n | { action: \"unclaimed\" }\n | { action: \"terminal\" }\n | { action: \"stale\" };\n\nexport type PreClaimFailureDisposition = \"retryable\" | \"permanent\" | \"blocked\";\n\nexport type PreClaimFailureDetail = {\n disposition: PreClaimFailureDisposition;\n code: \"db_deadlock\" | \"db_serialization_failure\" | \"db_failure\" | \"claim_invariant\";\n sqlState?: string | null;\n reason?:\n | \"database_claim_rejected\"\n | \"initiator_membership_required\"\n | \"personal_resource_grant_required\";\n retryPolicy?: \"explicit_recheck\";\n};\n\nexport const PRE_CLAIM_FAILURE_TYPE = \"OpenGeniPreClaimFailure\";\nexport const PRE_CLAIM_FAILURE_MESSAGE = \"Agent turn admission failed before attempt claim.\";\n\nexport type PostClaimDatabaseRecoveryDetail = {\n turnId: string;\n triggerEventId: string;\n executionGeneration: number;\n code: \"db_deadlock\" | \"db_serialization_failure\" | \"db_failure\";\n /** Present when the database outage interrupted a retryable provider\n * recovery checkpoint. The control lane must advance this exact durable\n * count instead of reopening the same recovery generation. */\n providerRecoveryCount?: number;\n /** Safe classified provider cause paired with providerRecoveryCount. */\n providerFailureCode?: string;\n /** Persist the no-replay setup marker, not a new provider/setup attempt. */\n sandboxSetupOutcomeUnknown?: true;\n};\n\nexport const POST_CLAIM_DATABASE_RECOVERY_FAILURE_TYPE = \"OpenGeniPostClaimDatabaseRecovery\";\nexport const POST_CLAIM_DATABASE_RECOVERY_FAILURE_MESSAGE =\n \"Agent turn database recovery required after attempt claim.\";\n\nexport type RecoverDispatchInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n timeoutType: \"HEARTBEAT\" | \"SCHEDULE_TO_START\";\n};\n\nexport type RecoverDispatchResult =\n // The same current inference is now recoverable. It never enters the prompt\n // queue; the next claim creates a new attempt for this exact turn.\n | { action: \"unclaimed\" }\n | { action: \"recovering\"; turnId: string; redispatches: number }\n // The turn is no longer running/requires_action: the timed-out attempt was\n // a zombie that actually settled the turn after the server gave up on its\n // heartbeats. Nothing to redo; the workflow just continues its loop.\n | { action: \"stale\" }\n // The per-turn crash-loop guard tripped; the workflow must fail the\n // session for real. `redispatches` is the count already consumed (== the\n // ceiling), so the failed attempt was worker death number redispatches + 1.\n | { action: \"exceeded\"; turnId: string; redispatches: number };\n\nexport const ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_TYPE = \"EscapedMcpTimeoutRecoveryFailure\";\nexport const ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_MESSAGE =\n \"MCP request timeout recovery checkpoint failed before model request\";\n\nexport type EscapedMcpTimeoutRecoveryDetail = {\n turnId: string;\n triggerEventId: string;\n executionGeneration: number;\n providerRecoveryCount: number;\n continueDelayMs: number;\n};\n\nexport type RecoverEscapedMcpTimeoutInput = EscapedMcpTimeoutRecoveryDetail & {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n};\n\nexport type RecoverEscapedMcpTimeoutResult = {\n action: \"recovering\" | \"stale\" | \"ineligible\";\n};\n\nexport type PeekSessionWorkInput = {\n workspaceId: string;\n sessionId: string;\n includeAdmissionFence?: boolean;\n /** Versioned workflow observer opt-in, never a caller authorization grant. */\n observerAccountId?: string;\n};\n\nexport type SettleSessionInputWaitInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n waitTurnId: string;\n disposition: \"held\" | \"timeout\" | \"superseded\";\n};\n\nexport type SettleSessionInputWaitResult = {\n action: \"held\" | \"timeout\" | \"superseded\" | \"stale\";\n};\n\nexport type ExpireSessionHumanInputInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n requestId: string;\n};\n\nexport type ExpireSessionHumanInputResult = {\n action: \"expired\" | \"stale\" | \"not_found\";\n};\n\nexport type ExpireSessionInteractionInterventionInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n interventionId: string;\n};\n\nexport type ExpireSessionInteractionInterventionResult = {\n action: \"expired\" | \"stale\" | \"not_found\";\n};\n\nexport type ExpireScheduledRunHumanWaitInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n runId: string;\n};\n\nexport type ExpireScheduledRunHumanWaitResult = {\n action: \"expired\" | \"stale\" | \"not_found\";\n};\n\nexport type MarkSessionIdleInput = {\n workspaceId: string;\n sessionId: string;\n};\n\nexport type MaybeContinueGoalInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n};\n\nexport type MaybeContinueGoalResult = {\n // `deferred`: idle backoff between consecutive no-input continuations.\n // Nothing was materialized; the obligation remains armed and a delayed\n // outbox wake at the pacing deadline restarts it.\n action: \"none\" | \"queue\" | \"continue\" | \"paused\" | \"deferred\";\n};\n\nexport type DispatchScheduledTaskRunInput = {\n workspaceId: string;\n taskId: string;\n /** Stable Temporal workflow identity; retries must reuse the same source row. */\n producerKey?: string;\n} & (\n | {\n triggerType: Extract<ScheduledTaskTriggerType, \"scheduled\">;\n agentRunUsageIdempotencyKey?: never;\n initiator?: never;\n credentialRestriction?: never;\n }\n | {\n triggerType: Extract<\n ScheduledTaskTriggerType,\n \"manual\" | \"initial\" | \"provider_event\" | \"retry\" | \"repair\"\n >;\n agentRunUsageIdempotencyKey: string;\n /** Exact identity used by the API-side charge for this same trigger. */\n initiator: TurnInitiator;\n /** Trusted API-side caller ceiling for this occurrence, not the schedule. */\n credentialRestriction?: \"developer_setup\";\n }\n);\n\nexport type DispatchScheduledTaskRunResult =\n | { action: \"deleted\" }\n | {\n action: \"blocked\";\n runId?: string;\n diagnostic?: import(\"@opengeni/contracts\").ConnectionAccountSelectionDiagnostic;\n /** Present when the occurrence was refused as a visible run receipt. */\n refusal?: import(\"@opengeni/contracts\").ScheduledTaskAdmissionRefusal;\n reason:\n | \"insufficient_credits\"\n | \"allowance_exhausted\"\n | \"monthly_model_cost_limit\"\n | \"monthly_agent_run_limit\"\n | \"malformed_manual_trigger\"\n | \"scheduled_task_paused\"\n | \"scheduled_authority_exhausted\"\n | \"scheduled_run_terminal\"\n | \"scheduled_execution_unrepresentable\"\n | \"connection_account_unavailable\"\n | \"scheduled_authority_unavailable\"\n | \"machine_target_unavailable\"\n | \"machine_enrollment_inactive\"\n | \"variable_set_unavailable\"\n | \"rig_version_unavailable\"\n | \"knowledge_source_paused\"\n | \"legacy_source_schedule_requires_migration\"\n | \"incident_preflight_metadata_missing\"\n | \"incident_responder_under_capable\"\n | \"incident_data_source_unsuitable\";\n }\n | {\n action: \"start\" | \"signal\";\n accountId: string;\n workspaceId: string;\n sessionId: string;\n triggerEventId: string;\n workflowId: string;\n workflowWakeRevision: number | null;\n }\n | {\n action: \"knowledge_source_sync\";\n accountId: string;\n workspaceId: string;\n taskId: string;\n scheduledTaskRunId: string;\n sourceId: string;\n overlapPolicy: \"skip\" | \"buffer_one\";\n };\n\nexport type RunKnowledgeSourceSyncBatchInput = {\n /** Host-bound attempt only. Legacy control workflow inputs have none and cannot fetch. */\n agent?: Extract<import(\"@opengeni/db\").KnowledgeActor, { kind: \"agent\" }>;\n\n accountId: string;\n workspaceId: string;\n taskId: string;\n scheduledTaskRunId: string;\n sourceId: string;\n overlapPolicy: \"skip\" | \"buffer_one\";\n};\n\nexport type DispatchAutomationRunInput = {\n accountId: string;\n workspaceId: string;\n runId: string;\n};\n\nexport type DispatchAutomationRunResult =\n | { action: \"started\"; sessionId: string }\n | { action: \"already_dispatched\"; sessionId: string }\n | { action: \"skipped\"; reason: string }\n | { action: \"failed\"; reason: string }\n | { action: \"not_found\" };\n\nexport type RunKnowledgeSourceSyncBatchResult = (\n | { action: \"continue\" }\n | {\n action: \"complete\";\n bufferedWake: boolean;\n bufferedScheduledTaskRunId?: string | null;\n }\n | { action: \"skipped\" | \"buffered\" }\n | {\n action: \"failed\";\n bufferedWake: boolean;\n bufferedScheduledTaskRunId?: string | null;\n }\n) & { summary?: KnowledgeSourceSyncRunSummary; errorCode?: string };\n\ntype DocumentIndexIdentity = {\n accountId: string;\n workspaceId: string;\n documentId: string;\n};\n\ntype CurrentDocumentIndexAuthority = {\n authorityKind: DocumentAuthorityKind;\n authorityWorkspaceId: string | null;\n authoritySubjectId: string | null;\n};\n\ntype HistoricalDocumentIndexAuthority = {\n authorityKind?: never;\n authorityWorkspaceId?: never;\n authoritySubjectId?: never;\n};\n\nexport type IndexDocumentInput = DocumentIndexIdentity &\n (CurrentDocumentIndexAuthority | HistoricalDocumentIndexAuthority);\n\ntype ClaimedRunAgentTurnResult = {\n // \"recovering\": this attempt ended after durably preserving the same current\n // inference for a new attempt. Recovery is not prompt queue work.\n status: \"idle\" | \"requires_action\" | \"failed\" | \"cancelled\" | \"recovering\" | \"waiting_capacity\";\n turnId: string;\n attemptId: string;\n // Provider backpressure pacing: when set on an idle or recovering result, the\n // session workflow holds the loop this long before admitting the next attempt.\n continueDelayMs?: number;\n // Multi-account rotation all-capped idle: every connected Codex subscription is\n // rate-limited/cooling. This is a MANDATORY hold — session.ts must wait\n // continueDelayMs (floored to a minimum) and must NOT treat a 0/elapsed delay as\n // \"continue now\" (invariant 4: NO THRASH). Distinct from a normal continueDelayMs:0\n // which legitimately means \"a rotation candidate is ready, re-dispatch immediately\".\n idleUntilReset?: boolean;\n // Durable native zero-pool wait for this same nonterminal logical turn.\n // Unlike continueDelayMs, this reference is persisted in Postgres and\n // reconstructed after workflow/worker restart. The workflow must not call\n // maybeContinueGoal or manufacture queue/input work while it is active.\n capacityWait?: CodexCapacityWaitRef;\n // This execution reached a durable terminal-for-now boundary (for example,\n // maintenance could not run or same-turn context recovery failed). End this\n // workflow run without synthesizing another goal continuation from unchanged\n // state. A later prompt/control/new-update wake may retry through normal claim\n // ordering.\n deferredUntilWake?: boolean;\n};\n\nexport type RunAgentTurnResult =\n | ClaimedRunAgentTurnResult\n | {\n status: \"unclaimed\";\n reason: \"gate-closed\" | \"no-work\" | \"stale-approval\" | \"control-pending\";\n };\n"],"mappings":";;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,8BAA8B;AACvC,SAAS,2BAA2B;;;ACRpC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,aAAa,kBAAkB;AACxC,SAAS,oBAAoB;AAC7B,SAAS,YAAY;AACrB,SAAS,yBAAyB;AAElC,IAAM,4BAA4B;AAO3B,SAAS,kCACd,IACA,UACiE;AACjE,MAAI,CAAC,SAAS,2BAA4B,QAAO;AACjD,QAAM,SAAS,SAAS,yBAAyB,KAAK;AACtD,QAAM,eAAe,wBAAwB,QAAQ;AACrD,MAAI,CAAC,UAAU,CAAC,cAAc;AAC5B,UAAM,IAAI,MAAM,yDAAyD;AA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,UAAU,IAAI,YAAY,KAAK,KAAK,OAAO,MAAM,YAAY,KAAK;AAAA,EAC3E;AACA,SAAO,YAAY,OAAO;AAC5B;AAOO,SAAS,8BACd,MACA,QACA,MACoE;AAGpE,QAAM,QAAQ,MAAM,cAChB,8EAA8E,oBAAoB,KAAK,eAAe,CAAC,6GAEvH,+EAA+E,oBAAoB,KAAK,eAAe,CAAC;AAE5H,SAAO;AAAA,IACL;AAAA,IACA,MAAM;AAAA,IACN,WAAW;AAAA,IACX,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,EAC7B;AACF;AAKO,IAAM,kCAAkC,KAAK;","names":["delegation","environmentsEncryptionKeyBytes","chosen","unattemptedAccounts","current","result","configuredStaticUsageLimits","readTurnExecutionPolicyV1","modelFundingForAdmission","resolveCatalogSettings","resolveCatalogSettings","readTurnExecutionPolicyV1","configuredStaticUsageLimits","isDeepStrictEqual","createHash","getConnectionMetadata","sleep","delayMs","parent","getConnectionMetadata","isDeepStrictEqual","settled","obligation","objectAcl","createHash","version","aclRevision","bytes","url","payload","randomUUID","randomUUID","sandboxLifecycleTransitionWaitMs","markWarmLeaseInstanceLost","readLease","establishSandboxSessionFromEnvelope","isProviderSandboxNotFoundError","resolveModalCheckpointProviderBindingForSession","verifySandboxExecReadiness","randomUUID","sandboxLeaseTelemetryKey","parseWorkspaceArchiveObjectRef","parseWorkspaceArchiveObjectRef","sandboxLeaseTelemetryKey","randomUUID","heartbeat","resumeEnvelope","readLease","establishSandboxSessionFromEnvelope","verifySandboxExecReadiness","isProviderSandboxNotFoundError","markWarmLeaseInstanceLost","resolveModalCheckpointProviderBindingForSession","sandboxLifecycleTransitionWaitMs","process","getSessionGoal","mergeToolRefs","createHash","isDeepStrictEqual","getScheduledTaskRunAcceptedExecution","requireSession","allowedFirstPartyMcpToolsForSession","allowedFirstPartyMcpToolsForSession","requireSession","getScheduledTaskRunAcceptedExecution","SandboxLeaseRecoveryBlockedError","SandboxLeaseSupersededError","SandboxLeaseTransitionError","SandboxExecReadinessError","SandboxProviderContinuityUnavailableError","WorkspaceArchiveIntegrityError","randomUUID","sleep","SandboxExecReadinessError","SandboxLeaseSupersededError","SandboxLeaseTransitionError","SandboxLeaseRecoveryBlockedError","WorkspaceArchiveIntegrityError","SandboxProviderContinuityUnavailableError","sleep","retryDelayMs","SandboxLeaseTransitionError","ActiveBackendUnresolvableError","CancelledFailure","createHash","getSandboxSessionEnvelope","createHash","getSandboxSessionEnvelope","codexPlanExcludesModel","connectionModelAllowed","XaiSubscriptionReloginRequired","CancelledFailure","SandboxLeaseTransitionError","ActiveBackendUnresolvableError","XaiSubscriptionReloginRequired","quota"]}
|