@opengeni/worker-bundle 3.1.2 → 3.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/activity-services.ts","../src/personal-github-git-credentials.ts","../src/pr-review-credentials.ts","../src/onepassword-vault-provider.ts","../src/activities/documents.ts","../src/activities/goals.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/subscription-core-wait-bindings.ts","../src/activities/subscription-core-codex-waits.ts","../src/activities/agent-turn/subscription-serving-catalog.ts","../src/activities/subscription-core-codex-quota.ts","../src/activities/subscription-core-usage-recheck.ts","../src/activities/common.ts","../src/activities/subscription-core-claude-waits.ts","../src/activities/subscription-core-xai-waits.ts","../src/activities/subscription-core-xai-quota.ts","../src/activities/sandbox-images.ts","../src/activities/streaming.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/session-usage-custody.ts","../src/activities/agent-turn/codex-credit-policy.ts","../src/activities/agent-turn/sandbox-provision.ts","../src/activities/agent-turn/quiescence.ts","../src/activities/agent-turn/provider-recovery-policy.ts","../src/activities/agent-turn/errors.ts","../../../node_modules/.bun/drizzle-orm@0.45.2+1d2c014f134ec9f4/node_modules/src/entity.ts","../../../node_modules/.bun/drizzle-orm@0.45.2+1d2c014f134ec9f4/node_modules/src/errors.ts","../src/activities/agent-turn/codex-usage-policy.ts","../src/activities/run-input.ts","../src/activities/requester-unavailable-receipt.ts","../src/activities/agent-turn/codex-plan-entitlement.ts","../src/activities/agent-turn/codex-core-errors.ts","../src/activities/types.ts","../src/activities/agent-turn/provider-recovery-copy.ts"],"sourcesContent":["import {\n codeSearchDeploymentPolicy,\n resolveWebSearchProvider,\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 { createRemoteExternalVaultFactories, 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\";\nimport { loadOnePasswordVaultProvider } from \"./onepassword-vault-provider\";\nimport { createNativeExternalVaultFactories } from \"./external-vault-providers\";\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 // A named but unusable web search provider withholds the tools; say why.\n const webSearchProvider = resolveWebSearchProvider(settings);\n if (webSearchProvider.status === \"invalid\") {\n observability.warn(\"web search provider is misconfigured; web_search stays off\", {\n reason: webSearchProvider.reason,\n });\n }\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 onePasswordVaultProvider:\n dependencies.onePasswordVaultProvider === undefined\n ? loadOnePasswordVaultProvider\n : dependencies.onePasswordVaultProvider,\n externalVaultProviders:\n dependencies.externalVaultProviders === undefined\n ? {\n ...createRemoteExternalVaultFactories(settings),\n ...createNativeExternalVaultFactories(settings),\n }\n : dependencies.externalVaultProviders,\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 type { OnePasswordVaultProviderFactory } from \"@opengeni/core\";\n\n/**\n * Loads the 1Password adapter (and its ~14 MB WASM SDK) only when a turn first\n * touches a 1Password vault. The only allowed import edge, besides apps/api,\n * is this dynamic one (OP-5, packages/vaults-onepassword/test/import-guard.test.ts).\n */\nexport const loadOnePasswordVaultProvider: OnePasswordVaultProviderFactory = async (input) => {\n const { vaultProviderForOnePasswordConnection } = await import(\"@opengeni/vaults-onepassword\");\n return vaultProviderForOnePasswordConnection(input);\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 resolveSessionFirstPartyMcpTools,\n resolveTurnExecutionPolicyV1,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n mergeToolRefs,\n readTurnExecutionPolicyV1,\n type SessionGoal,\n type ToolRef,\n} from \"@opengeni/contracts\";\nimport {\n enqueueSessionWorkflowWakeIfRunnable,\n getSessionGoal,\n getSessionTurn,\n materializeGoalContinuation,\n requireSession,\n requireWorkspace,\n} from \"@opengeni/db\";\nimport type {\n ControlActivityServices,\n MaybeContinueGoalInput,\n MaybeContinueGoalResult,\n} from \"./types\";\nimport {\n modelFundingForAdmission,\n goalRunBudgetBlocked,\n goalSessionUsageLimitBlocked,\n recordSessionUsageLimitEvent,\n resolveGoalModelAdmission,\n} from \"@opengeni/core\";\nexport { goalContinuationModelDecision, goalRunBudgetBlocked } from \"@opengeni/core\";\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 const workspace = await requireWorkspace(db, input.workspaceId);\n const modelDecision = await resolveGoalModelAdmission(db, catalogSourceSettings, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n model: session.model,\n codexCompactionMode: session.codexCompactionMode,\n latencyMode: session.latencyMode,\n });\n const settings = modelDecision.settings;\n const continuationModel = modelDecision.model;\n const continuationReasoningEffort = session.reasoningEffort;\n const continuationLatencyMode = session.latencyMode;\n const modelPolicyBlocked = modelDecision.blocked;\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 // a reached task usage limit pauses the goal with its own\n // reason before any funding gate; a read failure aborts materialization.\n const usageLimitBlocked = modelPolicyBlocked\n ? null\n : await goalSessionUsageLimitBlocked(tx, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n });\n if (usageLimitBlocked) {\n recordSessionUsageLimitEvent(service.observability, \"goal\", \"reached\");\n }\n const budgetBlocked = modelPolicyBlocked\n ? null\n : (usageLimitBlocked ??\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 const pausedReason = modelPolicyBlocked\n ? modelDecision.pausedReason\n : budgetBlocked?.pausedReason;\n return {\n budgetBlocked: modelPolicyBlocked ?? budgetBlocked?.message ?? null,\n ...(pausedReason ? { budgetPausedReason: pausedReason } : {}),\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 = resolveSessionFirstPartyMcpTools(\n settings,\n session,\n workspace.settings,\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 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","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 {\n ATLASSIAN_NATIVE_RETIRED_REASON,\n isRetiredNativeAtlassianSource,\n} from \"@opengeni/contracts/atlassian-native-retirement\";\nimport { 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 if (isRetiredNativeAtlassianSource(action))\n return {\n action: \"failed\",\n bufferedWake: false,\n errorCode: ATLASSIAN_NATIVE_RETIRED_REASON,\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","import { subscriptionCoreProviderIds } from \"@opengeni/db\";\nimport { CODEX_CORE_WAIT_BINDING, type CoreWaitBinding } from \"./subscription-core-codex-waits\";\nimport { CLAUDE_CORE_WAIT_BINDING } from \"./subscription-core-claude-waits\";\nimport { XAI_CORE_WAIT_BINDING } from \"./subscription-core-xai-waits\";\n\n/** Control-worker adapters only; never import the turn runtime to wake work. */\nexport function subscriptionCoreWaitBindings(): CoreWaitBinding[] {\n const registered = new Set(subscriptionCoreProviderIds());\n return [CODEX_CORE_WAIT_BINDING, CLAUDE_CORE_WAIT_BINDING, XAI_CORE_WAIT_BINDING].filter(\n (binding) => registered.has(binding.provider),\n );\n}\n","/**\n * Durable capacity waits and wakes for Codex chat turns on the shared\n * subscription core (M3 PR 2a, inventory EP-T09/T10). Reached only for an\n * account whose Codex cutover row is enabled; the legacy Codex waiter path is\n * untouched. Workflow activity names, signal names and argument shapes stay\n * those of the legacy Codex wait: the activities look a waiter id up in the\n * core table first and fall back to the legacy table.\n *\n * The wait, wake and reconcile steps are provider-neutral (SuperGrok track\n * X1b): a `CoreWaitBinding` supplies one provider's database entry points.\n * The Codex-named functions are Codex's bindings and are unchanged.\n */\nimport {\n abandonSubscriptionCapacityWakeDelivery,\n armSubscriptionCoreCodexCapacityWait,\n claimSubscriptionCapacityWakeDeliveries,\n evaluateSubscriptionCoreCodexPlacement,\n evaluateSubscriptionCorePlacementWithFailover,\n getSession,\n getSessionTurn,\n getSubscriptionCoreCodexCapacityWaitById,\n markSubscriptionCapacityWakeDelivered,\n readSubscriptionCoreCodexTurnModel,\n readSubscriptionCoreTurnIdentity,\n reconcileSubscriptionCoreCodexCapacityWait,\n recoverSubscriptionCoreCodexConnectionHealth,\n retrySubscriptionCapacityWakeDelivery,\n subscriptionCoreCodexCapacityWaitRef,\n subscriptionCoreProvider,\n wakeSubscriptionCoreCodexCapacityWaiters,\n withSubscriptionCapacityWakeOutboxScope,\n withSubscriptionCoreAcceptedTurn,\n type Database,\n type SubscriptionCoreCodexCapacityWait,\n type SubscriptionCoreCodexWaitEvaluation,\n type SubscriptionCoreCodexWakeScope,\n type SubscriptionCoreCodexPlacementEvaluation,\n type SubscriptionCoreTurnIdentity,\n type SubscriptionCoreWaiterProvider,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents, type EventBus } from \"@opengeni/events\";\nimport type { Settings } from \"@opengeni/config\";\nimport { readTurnExecutionPolicyV1 } from \"@opengeni/contracts\";\nimport { servingCatalogForBlockedTurn } from \"./agent-turn/subscription-serving-catalog\";\nimport { refreshExhaustedCodexCoreQuota } from \"./subscription-core-codex-quota\";\nimport { subscriptionCoreWaitBindings } from \"./subscription-core-wait-bindings\";\nimport type { CodexCapacityWaitRef, SignalCodexCapacityWorkflow } from \"./types\";\nimport { workflowIdForSession } from \"./common\";\n\n/** Typed wake signal attempts before the outbox gives the fast path up. */\nexport const CORE_CODEX_WAKE_DELIVERY_MAX_ATTEMPTS = 8;\nconst CORE_CODEX_WAKE_DELIVERY_BATCH = 100;\nconst CORE_CODEX_WAKE_CLAIM_TTL_MS = 60_000;\n\n/** Exponential retry for one typed wake signal: 1 s doubling to 5 minutes. */\nexport function coreCodexWakeRetryDelayMs(attemptCount: number): number {\n const exponent = Math.max(0, Math.min(attemptCount - 1, 16));\n return Math.min(1_000 * 2 ** exponent, 5 * 60_000);\n}\n\nexport type CoreCodexWakeServices = {\n db: Database;\n settings?: Settings;\n signalCodexCapacityWorkflow?: SignalCodexCapacityWorkflow | null | undefined;\n};\n\n/** One provider's database entry points for its core waiters. */\nexport type CoreWaitBinding = {\n provider: SubscriptionCoreWaiterProvider;\n arm: typeof armSubscriptionCoreCodexCapacityWait;\n getWaiterById: (\n db: Database,\n input: { workspaceId: string; sessionId: string; waiterId: string },\n ) => Promise<SubscriptionCoreCodexCapacityWait | null>;\n readTurnModel: typeof readSubscriptionCoreCodexTurnModel;\n recoverHealth: (db: Database, identity: SubscriptionCoreTurnIdentity) => Promise<number>;\n evaluatePlacement: (\n db: Database,\n request: {\n identity: SubscriptionCoreTurnIdentity;\n productModelId: string;\n reasoningLevel: string;\n },\n ) => Promise<SubscriptionCoreCodexPlacementEvaluation>;\n wakeWaiters: (\n db: Database,\n input: { accountId: string; reason: string; workspaceIds?: readonly string[] },\n ) => Promise<SubscriptionCoreCodexWakeScope[]>;\n reconcileWaiter: typeof reconcileSubscriptionCoreCodexCapacityWait;\n /**\n * Re-read the provider's usage before a timed or woken reconcile evaluates\n * placement, for a provider whose usage read can end an exhaustion before\n * its stored reset (its waiters then recheck on a bounded backoff), under\n * the parked turn's exact accepted identity (the same read placement\n * evaluation uses; never called without one). Best effort: a failure\n * leaves the stored state, and placement decides.\n */\n refreshBeforeReconcile?: (\n services: { db: Database; settings: Settings },\n turn: SubscriptionCoreTurnIdentity,\n ) => Promise<void>;\n};\n\n/** Codex's binding (each call resolves the Codex-named entry point at call time). */\nexport const CODEX_CORE_WAIT_BINDING: CoreWaitBinding = {\n provider: \"codex\",\n arm: (db, input) => armSubscriptionCoreCodexCapacityWait(db, input),\n getWaiterById: (db, input) => getSubscriptionCoreCodexCapacityWaitById(db, input),\n readTurnModel: (db, input) => readSubscriptionCoreCodexTurnModel(db, input),\n recoverHealth: (db, identity) => recoverSubscriptionCoreCodexConnectionHealth(db, identity),\n evaluatePlacement: (db, request) => evaluateSubscriptionCoreCodexPlacement(db, request),\n wakeWaiters: (db, input) => wakeSubscriptionCoreCodexCapacityWaiters(db, input),\n reconcileWaiter: (db, input) => reconcileSubscriptionCoreCodexCapacityWait(db, input),\n // OpenAI can reset a Codex limit before the reset it reported, so a parked\n // turn re-reads `/wham/usage` (rate-limited per connection) at each bounded\n // recheck instead of sleeping until a stale reset.\n refreshBeforeReconcile: ({ db, settings }, turn) =>\n refreshExhaustedCodexCoreQuota({\n db,\n settings,\n accountId: turn.accountId,\n workspaceId: turn.workspaceId,\n personalTurn: turn,\n }),\n};\n\nexport type CoreCodexWakeDeliveryResult = {\n claimed: number;\n delivered: number;\n retried: number;\n abandoned: number;\n};\n\n/**\n * Drain one workspace's due typed wake obligations: claim (fenced by claim\n * generation), signal `codexCapacityChanged` with the waiter's wake revision,\n * then mark delivered; a failed signal is retried with bounded backoff and\n * given up after a fixed number of attempts. Idempotent across a crash\n * between the database wake and the signal: an unacknowledged claim becomes\n * due again when its claim expires, and the generic session workflow wake\n * committed with the same database wake still reaches the workflow.\n */\nexport async function deliverSubscriptionCoreCodexWakes(\n services: CoreCodexWakeServices,\n scope: SubscriptionCoreCodexWakeScope,\n): Promise<CoreCodexWakeDeliveryResult> {\n const result: CoreCodexWakeDeliveryResult = {\n claimed: 0,\n delivered: 0,\n retried: 0,\n abandoned: 0,\n };\n const signal = services.signalCodexCapacityWorkflow;\n // A host without a typed signaler claims nothing: the rows stay pending for\n // a worker that can signal (the generic durable wake committed with each\n // row still reaches the workflow meanwhile).\n if (!signal) return result;\n const deliveries = await withSubscriptionCapacityWakeOutboxScope(services.db, scope, (tx) =>\n claimSubscriptionCapacityWakeDeliveries(tx, {\n limit: CORE_CODEX_WAKE_DELIVERY_BATCH,\n claimTtlMs: CORE_CODEX_WAKE_CLAIM_TTL_MS,\n }),\n );\n result.claimed = deliveries.length;\n for (const delivery of deliveries) {\n try {\n await signal({\n accountId: delivery.accountId,\n workspaceId: delivery.workspaceId,\n sessionId: delivery.sessionId,\n workflowId: workflowIdForSession(delivery.sessionId),\n wakeRevision: delivery.wakeRevision,\n });\n await withSubscriptionCapacityWakeOutboxScope(services.db, scope, (tx) =>\n markSubscriptionCapacityWakeDelivered(tx, delivery),\n );\n result.delivered += 1;\n } catch {\n const exhausted = delivery.attemptCount >= CORE_CODEX_WAKE_DELIVERY_MAX_ATTEMPTS;\n await withSubscriptionCapacityWakeOutboxScope(services.db, scope, (tx) =>\n exhausted\n ? abandonSubscriptionCapacityWakeDelivery(tx, {\n id: delivery.id,\n claimGeneration: delivery.claimGeneration,\n failureCode: \"signal_attempts_exhausted\",\n })\n : retrySubscriptionCapacityWakeDelivery(tx, {\n id: delivery.id,\n claimGeneration: delivery.claimGeneration,\n retryInMs: coreCodexWakeRetryDelayMs(delivery.attemptCount),\n failureCode: \"signal_failed\",\n }),\n ).catch(() => false);\n if (exhausted) result.abandoned += 1;\n else result.retried += 1;\n }\n }\n return result;\n}\n\n/**\n * A capacity change for the account's Codex pool: wake every waiting core\n * waiter (database first, outbox and generic wake in the same commit), then\n * deliver the typed signals. Best effort after the commit; never throws.\n */\nexport async function wakeSubscriptionCoreCodexWaitersAndDeliver(\n services: CoreCodexWakeServices,\n input: { accountId: string; reason: string; workspaceIds?: readonly string[] },\n): Promise<SubscriptionCoreCodexWakeScope[]> {\n return await wakeSubscriptionCoreWaitersAndDeliver(services, CODEX_CORE_WAIT_BINDING, input);\n}\n\n/** The same wake for any provider's core waiters. */\nexport async function wakeSubscriptionCoreWaitersAndDeliver(\n services: CoreCodexWakeServices,\n binding: Pick<CoreWaitBinding, \"wakeWaiters\">,\n input: { accountId: string; reason: string; workspaceIds?: readonly string[] },\n): Promise<SubscriptionCoreCodexWakeScope[]> {\n let scopes: SubscriptionCoreCodexWakeScope[] = [];\n try {\n scopes = await binding.wakeWaiters(services.db, input);\n } catch {\n return [];\n }\n await Promise.allSettled(\n scopes.map((scope) => deliverSubscriptionCoreCodexWakes(services, scope)),\n );\n return scopes;\n}\n\n/**\n * What core placement says about a blocked turn now: run, wait (with its\n * reason, earliest reset and quarantine end), revoked (the exact accepted\n * turn no longer authorizes core use) or paused (the cutover is switched off;\n * the work stays parked). Due quarantines are returned to service first, and\n * a recovery wakes the account's other waiters.\n */\nexport async function evaluateCoreCodexBlockedTurn(\n services: CoreCodexWakeServices,\n input: { accountId: string; workspaceId: string; sessionId: string; turnId: string },\n): Promise<SubscriptionCoreCodexWaitEvaluation> {\n return await evaluateCoreBlockedTurn(services, CODEX_CORE_WAIT_BINDING, input);\n}\n\n/** The same evaluation for any provider's blocked turn. */\nexport async function evaluateCoreBlockedTurn(\n services: CoreCodexWakeServices,\n binding: CoreWaitBinding,\n input: { accountId: string; workspaceId: string; sessionId: string; turnId: string },\n): Promise<SubscriptionCoreCodexWaitEvaluation> {\n const identity = await readSubscriptionCoreTurnIdentity(services.db, input);\n if (!identity) return { kind: \"revoked\" };\n const model = await binding.readTurnModel(services.db, input);\n if (!model) return { kind: \"revoked\" };\n await recoverCoreHealthAndWake(services, binding, identity);\n const failover = await evaluateFailoverBlockedTurn(services, binding, identity, model);\n if (failover) return failover;\n const evaluation = await binding.evaluatePlacement(services.db, {\n identity,\n productModelId: model.productModelId,\n reasoningLevel: model.reasoningLevel,\n });\n switch (evaluation.kind) {\n case \"not_visible\":\n return { kind: \"revoked\" };\n case \"cutover_not_enabled\":\n return { kind: \"paused\" };\n case \"run\":\n return { kind: \"run\" };\n case \"wait\":\n return {\n kind: \"wait\",\n waitReason: evaluation.reason,\n earliestResetAt: evaluation.earliestResetAt,\n healthRetryAt: evaluation.healthRetryAt,\n };\n }\n}\n\n/** Fresh accepted policy + current readiness/settings decide the whole pool.\n * Stored waiter candidates are deliberately not an input to this evaluator.\n * A wake grants no credentials: the resumed attempt still claims and leases.\n */\nasync function evaluateFailoverBlockedTurn(\n services: CoreCodexWakeServices,\n home: CoreWaitBinding,\n identity: SubscriptionCoreTurnIdentity,\n model: { productModelId: string; reasoningLevel: string },\n): Promise<SubscriptionCoreCodexWaitEvaluation | null> {\n const settings = services.settings;\n if (!settings?.subscriptionCrossProviderFailoverEnabled) return null;\n const context = await withSubscriptionCoreAcceptedTurn(services.db, identity, async (tx) => {\n const session = await getSession(tx, identity.workspaceId, identity.sessionId);\n const turn = await getSessionTurn(tx, identity.workspaceId, identity.turnId);\n if (!session || !turn || turn.sessionId !== identity.sessionId) return null;\n const accepted = readTurnExecutionPolicyV1(turn.metadata);\n return (\n session.codexCompactionMode === \"portable\" &&\n turn.source !== \"compaction\" &&\n accepted.kind === \"valid\" &&\n accepted.policy.credentialRestriction === undefined &&\n accepted.policy.productModelId === model.productModelId\n );\n });\n if (context.status !== \"completed\" || context.value === null) return { kind: \"revoked\" };\n if (!context.value) return null;\n const bindings = subscriptionCoreWaitBindings();\n const models = await servingCatalogForBlockedTurn(\n services.db,\n settings,\n identity,\n model.productModelId,\n bindings.map((binding) => binding.provider),\n );\n if (\n !models.some(\n (candidate) => candidate.id === model.productModelId && candidate.provider === home.provider,\n )\n )\n return null;\n const request = { identity, ...model, models, crossProviderFailoverEnabled: true };\n let evaluation = await evaluateSubscriptionCorePlacementWithFailover(\n services.db,\n subscriptionCoreProvider(home.provider),\n request,\n );\n // Only candidates derived by the live authority/policy evaluator can have\n // their health or usage refreshed. Personal billing keeps the same accepted\n // identity, including shared-session and frozen-background restrictions.\n const candidates = new Set(evaluation.candidateProviders ?? []);\n for (const binding of bindings) {\n if (binding.provider === home.provider || !candidates.has(binding.provider)) continue;\n await recoverCoreHealthAndWake(services, binding, identity);\n await binding\n .refreshBeforeReconcile?.({ db: services.db, settings }, identity)\n .catch(() => undefined);\n }\n if ([...candidates].some((provider) => provider !== home.provider)) {\n evaluation = await evaluateSubscriptionCorePlacementWithFailover(\n services.db,\n subscriptionCoreProvider(home.provider),\n request,\n );\n }\n switch (evaluation.kind) {\n case \"not_visible\":\n return { kind: \"revoked\" };\n case \"cutover_not_enabled\":\n return { kind: \"paused\" };\n case \"run\":\n return { kind: \"run\", candidateProviders: evaluation.candidateProviders ?? [] };\n case \"wait\":\n // Leave the capacity wait once to surface the actionable configuration\n // failure at claim. This is not a capacity/authority grant, and does not\n // fabricate a provider or strand work behind an unrelated quota reset.\n if (evaluation.reason === \"failover_no_model_mapping\")\n return { kind: \"run\", candidateProviders: [] };\n return {\n kind: \"wait\",\n waitReason: evaluation.reason,\n earliestResetAt: evaluation.earliestResetAt,\n healthRetryAt: evaluation.healthRetryAt,\n candidateProviders: evaluation.candidateProviders ?? [],\n };\n }\n}\n\n/** Return due quarantines to service under this accepted turn; wake others if any recovered. */\nexport async function recoverCoreCodexHealthAndWake(\n services: CoreCodexWakeServices,\n identity: SubscriptionCoreTurnIdentity,\n): Promise<number> {\n return await recoverCoreHealthAndWake(services, CODEX_CORE_WAIT_BINDING, identity);\n}\n\n/** The same recovery for any provider's connections. */\nexport async function recoverCoreHealthAndWake(\n services: CoreCodexWakeServices,\n binding: Pick<CoreWaitBinding, \"recoverHealth\" | \"wakeWaiters\">,\n identity: SubscriptionCoreTurnIdentity,\n): Promise<number> {\n const recovered = await binding.recoverHealth(services.db, identity).catch(() => 0);\n if (recovered > 0) {\n await wakeSubscriptionCoreWaitersAndDeliver(services, binding, {\n accountId: identity.accountId,\n reason: \"connection_health_recovered\",\n });\n }\n return recovered;\n}\n\nexport type CoreCodexReconcileResult =\n | ({ action: \"waiting\" } & CodexCapacityWaitRef)\n | { action: \"resumed\" | \"paused\" | \"superseded\" | \"stale\" };\n\n/**\n * Reconcile one core waiter for the workflow (timer, signal, queue wake or\n * recovery). Returns null when the waiter id is not a core waiter, so the\n * caller falls back to the legacy Codex waiter with the same reference.\n */\nexport async function reconcileCoreCodexCapacityWait(\n services: CoreCodexWakeServices & { bus: EventBus },\n input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n waiterId: string;\n generation: number;\n },\n): Promise<CoreCodexReconcileResult | null> {\n return await reconcileCoreCapacityWait(services, CODEX_CORE_WAIT_BINDING, input);\n}\n\n/**\n * The same reconcile for any provider: the waiter is looked up by the exact\n * id and generation the workflow recorded. Null when the id names no core\n * waiter of the binding's provider.\n */\nexport async function reconcileCoreCapacityWait(\n services: CoreCodexWakeServices & {\n bus: EventBus;\n /** Present on the workflow's reconcile; the in-turn arm has just placed. */\n settings?: Settings;\n },\n binding: CoreWaitBinding,\n input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n waiterId: string;\n generation: number;\n },\n): Promise<CoreCodexReconcileResult | null> {\n let waiter = await binding.getWaiterById(services.db, input);\n if (!waiter) return null;\n // Repair: drain this workspace's typed wakes that a crash left behind.\n await deliverSubscriptionCoreCodexWakes(services, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n }).catch(() => undefined);\n if (waiter.accountId !== input.accountId || waiter.generation !== input.generation) {\n return { action: \"stale\" };\n }\n if (binding.refreshBeforeReconcile && services.settings && waiter.blockedTurnLive !== false) {\n const turn = await readSubscriptionCoreTurnIdentity(services.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: waiter.blockedTurnId,\n });\n // Without the exact accepted identity the evaluation below revokes.\n if (turn) {\n await binding\n .refreshBeforeReconcile({ db: services.db, settings: services.settings }, turn)\n .catch(() => undefined);\n }\n // A recovery the re-read found woke this waiter: evaluate at that revision.\n waiter = await binding.getWaiterById(services.db, input);\n if (!waiter || waiter.accountId !== input.accountId || waiter.generation !== input.generation)\n return { action: \"stale\" };\n }\n // A row left behind by a Steer, Cancel or other transition is superseded by\n // the reconcile without placing (a non-run evaluation never resumes).\n const evaluation: SubscriptionCoreCodexWaitEvaluation =\n waiter.blockedTurnLive === false\n ? { kind: \"paused\" }\n : await evaluateCoreBlockedTurn(services, binding, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: waiter.blockedTurnId,\n });\n const result = await binding.reconcileWaiter(services.db, {\n ...input,\n evaluatedWakeRevision: waiter.wakeRevision,\n evaluation,\n });\n await publishDurableSessionEvents(\n services.bus,\n input.workspaceId,\n input.sessionId,\n result.events,\n );\n if (result.action === \"waiting\") {\n return { action: \"waiting\", ...subscriptionCoreCodexCapacityWaitRef(result.waiter) };\n }\n return { action: result.action };\n}\n","import {\n configuredModels,\n withCodexCatalogProvider,\n withXaiSubscriptionCatalogProvider,\n type Settings,\n} from \"@opengeni/config\";\nimport { resolveWorkspaceCatalogSettings } from \"@opengeni/core\";\nimport {\n subscriptionCoreProvider,\n type Database,\n type SubscriptionCoreFailoverModel,\n type SubscriptionCoreTurnIdentity,\n} from \"@opengeni/db\";\nimport { subscriptionCoreModelPolicyProviderIds } from \"@opengeni/subscriptions\";\n\n/** Shared by live placement and durable-wait evaluation, without importing\n * provider runtime hooks into the control worker. Catalog entries are not\n * authority: the core rechecks every candidate against accepted and live scope.\n */\nexport function servingCatalog(\n settings: Settings,\n providerIds: readonly string[],\n): SubscriptionCoreFailoverModel[] {\n return configuredModels(settings).flatMap((model) => {\n if (model.billing.metering !== \"external\" || model.credentialSource.kind === \"deployment\")\n return [];\n const matches = providerIds.filter((id) =>\n subscriptionCoreModelPolicyProviderIds(\n subscriptionCoreProvider(id).adapter,\n model.id,\n ).includes(model.providerId),\n );\n if (matches.length > 1) throw new Error(\"Ambiguous serving catalog provider\");\n const provider = matches[0];\n return provider\n ? [\n {\n id: model.id,\n provider,\n upstreamModelId: model.upstreamModelId,\n reasoningLevels: model.capabilities.reasoning.efforts.length\n ? [...model.capabilities.reasoning.efforts]\n : [\"none\"],\n },\n ]\n : [];\n });\n}\n\n/** The control worker has raw deployment settings, not claim's credential\n * overlays. Resolve the same current model definitions without loading keys\n * or filtering exhausted accounts out of the catalog. Core placement owns\n * authority/readiness, independently of catalog membership.\n */\nexport async function servingCatalogForBlockedTurn(\n db: Database,\n settings: Settings,\n identity: SubscriptionCoreTurnIdentity,\n productModelId: string,\n providerIds: readonly string[],\n): Promise<SubscriptionCoreFailoverModel[]> {\n const resolved = await resolveWorkspaceCatalogSettings(db, settings, {\n accountId: identity.accountId,\n workspaceId: identity.workspaceId,\n retainedProductModelId: productModelId,\n });\n let catalog = resolved.settings;\n if (catalog.codexSubscriptionEnabled) catalog = withCodexCatalogProvider(catalog);\n if (catalog.supergrokSubscriptionEnabled) catalog = withXaiSubscriptionCatalogProvider(catalog);\n return servingCatalog(catalog, providerIds);\n}\n","import {\n subscriptionCoreProvider,\n type Database,\n type SubscriptionCoreTurnIdentity,\n} from \"@opengeni/db\";\nimport type { Settings } from \"@opengeni/config\";\nimport {\n CORE_USAGE_PROBE_ATTEMPT_INTERVAL_MS,\n CORE_USAGE_RECHECK_MIN_INTERVAL_MS,\n refreshBlockedCoreQuotaBeforeReconcile,\n resetCoreUsageProbeAttempts,\n} from \"./subscription-core-usage-recheck\";\n\n/** Codex's per-connection re-read interval (the provider-neutral one). */\nexport const CODEX_CORE_USAGE_RECHECK_MIN_INTERVAL_MS = CORE_USAGE_RECHECK_MIN_INTERVAL_MS;\n\n/** Codex's per-scope probe attempt interval (the provider-neutral one). */\nexport const CODEX_CORE_USAGE_PROBE_ATTEMPT_INTERVAL_MS = CORE_USAGE_PROBE_ATTEMPT_INTERVAL_MS;\n\n/** Test seam: forget every recorded probe attempt. */\nexport function resetCodexCoreUsageProbeAttempts(): void {\n resetCoreUsageProbeAttempts();\n}\n\n/**\n * Before a parked Codex turn's reconcile: one `/wham/usage` read per\n * exhausted connection the work can use whose stored quota was not observed\n * within `CODEX_CORE_USAGE_RECHECK_MIN_INTERVAL_MS`, through the same core\n * probe the usage refresh route uses (`refreshBlockedCoreQuotaBeforeReconcile`\n * bound to Codex: shared connections as the core's service subject, and only\n * the personal connections the exact accepted turn admits).\n */\nexport async function refreshExhaustedCodexCoreQuota(input: {\n db: Database;\n settings: Settings;\n accountId: string;\n workspaceId: string;\n personalTurn?: SubscriptionCoreTurnIdentity | null;\n fetch?: typeof fetch;\n now?: number;\n}): Promise<void> {\n await refreshBlockedCoreQuotaBeforeReconcile({\n ...input,\n provider: subscriptionCoreProvider(\"codex\"),\n });\n}\n","import {\n deliverSubscriptionCoreProviderWake,\n subscriptionCoreOperationConnections,\n subscriptionCorePersonalConnections,\n type Database,\n type SubscriptionCoreProvider,\n type SubscriptionCoreTurnIdentity,\n} from \"@opengeni/db\";\nimport type { Settings } from \"@opengeni/config\";\nimport { subscriptionPersonalAuthorityForProviderV2 } from \"@opengeni/contracts\";\n\nconst CORE_SUBSCRIPTION_SERVICE_SUBJECT = \"service:subscription-core\";\n\n/** A provider with personal subscription authority (Codex, Claude, SuperGrok). */\ntype PersonalAuthorityProvider = Parameters<typeof subscriptionPersonalAuthorityForProviderV2>[1];\n\n/**\n * A stored exhaustion (or a model cooldown the adapter's usage read can end)\n * is re-read at most this often per connection, however many waiters\n * recheck: each waiter rechecks on the bounded backoff (at most every 15\n * minutes), so a parked turn sees an early provider reset within about 50\n * minutes instead of at a stale reset days away.\n */\nexport const CORE_USAGE_RECHECK_MIN_INTERVAL_MS = 30 * 60_000;\n\n/**\n * The per-connection interval above counts from the last stored reading, so\n * a probe that stores nothing (the endpoint fails, or answers without\n * windows) would otherwise be repeated by every waiter's recheck. This worker\n * attempts one probe scope (a provider's shared pool in a workspace, or one\n * owner's personal connections) at most this often, whatever the outcome.\n */\nexport const CORE_USAGE_PROBE_ATTEMPT_INTERVAL_MS = 5 * 60_000;\n\nconst probeAttempts = new Map<string, number>();\n\n/** Claims one probe attempt for `key` now, unless one ran within the interval. */\nfunction claimProbeAttempt(key: string, now: number): boolean {\n const last = probeAttempts.get(key);\n if (last !== undefined && now - last < CORE_USAGE_PROBE_ATTEMPT_INTERVAL_MS) return false;\n if (probeAttempts.size >= 10_000) {\n for (const [stale, at] of probeAttempts) {\n if (now - at >= CORE_USAGE_PROBE_ATTEMPT_INTERVAL_MS) probeAttempts.delete(stale);\n }\n }\n probeAttempts.set(key, now);\n return true;\n}\n\n/** Test seam: forget every recorded probe attempt (every provider). */\nexport function resetCoreUsageProbeAttempts(): void {\n probeAttempts.clear();\n}\n\n/**\n * Before a parked core turn's reconcile, for a provider whose usage read can\n * end an exhaustion before its stored reset (its adapter's\n * `usageReadEndsQuotaExhaustion`): one usage read per blocked connection the\n * work can use whose stored quota was not observed within\n * `CORE_USAGE_RECHECK_MIN_INTERVAL_MS`, through the same core probe the usage\n * refresh routes use.\n *\n * - Shared connections in this workspace's explicit context, as the core's\n * service subject.\n * - With `personalTurn` (the exact accepted turn that waits): only the\n * personal connections placement's personal authorization admits for that\n * turn, each read as the owner in their own Personal workspace.\n *\n * A recovery wakes the organization's core waiters of that provider. A failed\n * probe never blocks a waiter; the stored state stands. Each probe scope is\n * attempted at most once per `CORE_USAGE_PROBE_ATTEMPT_INTERVAL_MS` in this\n * worker.\n */\nexport async function refreshBlockedCoreQuotaBeforeReconcile(input: {\n provider: SubscriptionCoreProvider;\n db: Database;\n settings: Settings;\n accountId: string;\n workspaceId: string;\n personalTurn?: SubscriptionCoreTurnIdentity | null;\n fetch?: typeof fetch;\n now?: number;\n}): Promise<void> {\n const providerId = input.provider.adapter.provider;\n const now = input.now ?? Date.now();\n const deps = {\n minIntervalMs: CORE_USAGE_RECHECK_MIN_INTERVAL_MS,\n ...(input.fetch ? { fetchImpl: input.fetch } : {}),\n };\n const recovered: string[] = [];\n if (claimProbeAttempt(`${providerId}:${input.accountId}:${input.workspaceId}:shared`, now)) {\n try {\n recovered.push(\n ...(await subscriptionCoreOperationConnections(\n input.provider,\n ).refreshExhaustedSubscriptionCoreQuota(\n input.db,\n input.settings,\n {\n kind: \"workspace\",\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: CORE_SUBSCRIPTION_SERVICE_SUBJECT,\n },\n deps,\n )),\n );\n } catch {\n // The stored shared state stands.\n }\n }\n const personal = input.personalTurn;\n if (\n personal &&\n claimProbeAttempt(\n `${providerId}:${input.accountId}:${input.workspaceId}:personal:${personal.sessionOwnerMembershipId}:${\n subscriptionPersonalAuthorityForProviderV2(\n personal.acceptedAuthorityV2,\n providerId as PersonalAuthorityProvider,\n )?.authorityGeneration ?? \"none\"\n }`,\n now,\n )\n ) {\n try {\n recovered.push(\n ...(await subscriptionCorePersonalConnections(\n input.provider,\n ).refreshExhaustedSubscriptionCoreTurnPersonalQuota(\n input.db,\n input.settings,\n personal,\n deps,\n )),\n );\n } catch {\n // The stored personal state stands.\n }\n }\n if (recovered.length > 0) {\n await deliverSubscriptionCoreProviderWake(input.db, providerId, {\n accountId: input.accountId,\n reason: \"usage_recovered\",\n }).catch(() => undefined);\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 degradedAccounts: readonly { serverId: string }[] = [],\n): Extract<SessionSystemUpdatePayload, { type: \"scheduled_occurrence\" }> {\n // Connectors this occurrence runs without because every account a person\n // pinned for them is unusable. A connector that kept a working pin still has\n // its tools and is not named.\n const unavailableConnectors = [\n ...new Set(\n degradedAccounts\n .map((account) => account.serverId)\n .filter((serverId) => !tools.some((tool) => tool.kind === \"mcp\" && tool.id === serverId)),\n ),\n ].sort();\n return {\n type: \"scheduled_occurrence\",\n text: prompt,\n scheduledTaskId: taskId,\n scheduledTaskRunId: runId,\n ...(resources.length ? { resources } : {}),\n ...(tools.length ? { tools } : {}),\n ...(unavailableConnectors.length ? { unavailableConnectors } : {}),\n };\n}\n\nexport function workflowIdForSession(sessionId: string): string {\n return `session-${sessionId}`;\n}\n","/**\n * Claude's binding of the provider-neutral core waits (Claude track C1b).\n * The workflow reaches it only for a waiter the core holds.\n */\nimport {\n armSubscriptionCoreCapacityWait,\n getSubscriptionCoreCapacityWaitById,\n readSubscriptionCoreTurnModel,\n reconcileSubscriptionCoreCapacityWait,\n SUBSCRIPTION_CORE_CLAUDE,\n subscriptionCoreTurns,\n wakeSubscriptionCoreProviderCapacityWaiters,\n type SubscriptionCoreProvider,\n} from \"@opengeni/db\";\nimport type { CoreWaitBinding } from \"./subscription-core-codex-waits\";\nimport { refreshBlockedCoreQuotaBeforeReconcile } from \"./subscription-core-usage-recheck\";\n\nconst CLAUDE = SUBSCRIPTION_CORE_CLAUDE as SubscriptionCoreProvider;\n\nexport const CLAUDE_CORE_WAIT_BINDING: CoreWaitBinding = {\n provider: \"claude\",\n arm: (db, input) => armSubscriptionCoreCapacityWait(db, \"claude\", input),\n getWaiterById: async (db, input) => {\n const waiter = await getSubscriptionCoreCapacityWaitById(db, input);\n return waiter?.provider === \"claude\" ? waiter : null;\n },\n readTurnModel: (db, input) => readSubscriptionCoreTurnModel(db, input),\n recoverHealth: (db, identity) =>\n subscriptionCoreTurns(CLAUDE).recoverSubscriptionCoreConnectionHealth(db, identity),\n evaluatePlacement: (db, request) =>\n subscriptionCoreTurns(CLAUDE).evaluateSubscriptionCorePlacement(db, request),\n wakeWaiters: (db, input) => wakeSubscriptionCoreProviderCapacityWaiters(db, \"claude\", input),\n reconcileWaiter: (db, input) =>\n reconcileSubscriptionCoreCapacityWait(db, { ...input, provider: \"claude\" }),\n // Anthropic can reset a plan limit before the reset a refused request\n // reported, so a parked turn re-reads the Claude usage endpoint\n // (rate-limited per connection and per probe scope) at each bounded\n // recheck instead of sleeping until a stale reset: the shared pool, and the\n // personal connections its exact accepted identity authorizes.\n refreshBeforeReconcile: ({ db, settings }, turn) =>\n refreshBlockedCoreQuotaBeforeReconcile({\n provider: CLAUDE,\n db,\n settings,\n accountId: turn.accountId,\n workspaceId: turn.workspaceId,\n personalTurn: turn,\n }),\n};\n","/**\n * SuperGrok's binding of the provider-neutral core waits (SuperGrok track\n * X1b). The only SuperGrok waits: the drained cutover moved every legacy\n * waiter onto the core with its id and generation, and the workflow reaches\n * this binding only for a waiter the core holds.\n */\nimport {\n armSubscriptionCoreCapacityWait,\n getSubscriptionCoreCapacityWaitById,\n readSubscriptionCoreTurnModel,\n reconcileSubscriptionCoreCapacityWait,\n SUBSCRIPTION_CORE_XAI,\n subscriptionCoreTurns,\n wakeSubscriptionCoreProviderCapacityWaiters,\n type SubscriptionCoreProvider,\n} from \"@opengeni/db\";\nimport type { CoreWaitBinding } from \"./subscription-core-codex-waits\";\nimport { refreshExhaustedXaiCoreQuota } from \"./subscription-core-xai-quota\";\n\nconst XAI = SUBSCRIPTION_CORE_XAI as SubscriptionCoreProvider;\n\nexport const XAI_CORE_WAIT_BINDING: CoreWaitBinding = {\n provider: \"xai\",\n arm: (db, input) => armSubscriptionCoreCapacityWait(db, \"xai\", input),\n getWaiterById: async (db, input) => {\n const waiter = await getSubscriptionCoreCapacityWaitById(db, input);\n return waiter?.provider === \"xai\" ? waiter : null;\n },\n readTurnModel: (db, input) => readSubscriptionCoreTurnModel(db, input),\n recoverHealth: (db, identity) =>\n subscriptionCoreTurns(XAI).recoverSubscriptionCoreConnectionHealth(db, identity),\n evaluatePlacement: (db, request) =>\n subscriptionCoreTurns(XAI).evaluateSubscriptionCorePlacement(db, request),\n wakeWaiters: (db, input) => wakeSubscriptionCoreProviderCapacityWaiters(db, \"xai\", input),\n reconcileWaiter: (db, input) =>\n reconcileSubscriptionCoreCapacityWait(db, { ...input, provider: \"xai\" }),\n // A SuperGrok billing read can end an exhaustion before its stored reset, so\n // a parked turn re-reads shared billing and the personal connections its\n // exact accepted identity authorizes, at each bounded recheck.\n refreshBeforeReconcile: ({ db, settings }, turn) =>\n refreshExhaustedXaiCoreQuota({\n db,\n settings,\n accountId: turn.accountId,\n workspaceId: turn.workspaceId,\n personalTurn: turn,\n }),\n};\n","import {\n deliverSubscriptionCoreProviderWake,\n SUBSCRIPTION_CORE_XAI,\n SUBSCRIPTION_CORE_XAI_PROVIDER,\n subscriptionCoreOperationConnections,\n subscriptionCorePersonalConnections,\n type Database,\n type SubscriptionCoreTurnIdentity,\n} from \"@opengeni/db\";\nimport type { Settings } from \"@opengeni/config\";\n\nconst CORE_SUBSCRIPTION_SERVICE_SUBJECT = \"service:subscription-core\";\n\n/**\n * After the SuperGrok receipt: one billing probe per exhausted connection\n * the work can use (design 5.3, EP-N22), never legacy rows.\n *\n * - Shared connections in this workspace's explicit context, as the core's\n * service subject.\n * - With `personalTurn` (the exact accepted turn being placed or waiting):\n * only the personal connections placement's personal authorization admits\n * for that turn\n * (its initiating human is the session owner, a private session or the\n * owner's Personal workspace, the frozen v2 entry at the current\n * authority generation, personal connections allowed), each read as the\n * owner in their own Personal workspace (the administered\n * `personal_owner` read). Any other turn reads no personal connection.\n *\n * A recovery wakes the organization's SuperGrok core waiters: a shared\n * connection can serve every workspace it reaches, and an owner's parked\n * private work may wait in any workspace. A failed probe never blocks\n * placement or a waiter; the stored state stands.\n */\nexport async function refreshExhaustedXaiCoreQuota(input: {\n db: Database;\n settings: Settings;\n accountId: string;\n workspaceId: string;\n personalTurn?: SubscriptionCoreTurnIdentity | null;\n fetch?: typeof fetch;\n}): Promise<void> {\n const deps = input.fetch ? { fetchImpl: input.fetch } : {};\n const recovered: string[] = [];\n try {\n recovered.push(\n ...(await subscriptionCoreOperationConnections(\n SUBSCRIPTION_CORE_XAI,\n ).refreshExhaustedSubscriptionCoreQuota(\n input.db,\n input.settings,\n {\n kind: \"workspace\",\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: CORE_SUBSCRIPTION_SERVICE_SUBJECT,\n },\n deps,\n )),\n );\n } catch {\n // The stored shared state stands.\n }\n if (input.personalTurn) {\n try {\n recovered.push(\n ...(await subscriptionCorePersonalConnections(\n SUBSCRIPTION_CORE_XAI,\n ).refreshExhaustedSubscriptionCoreTurnPersonalQuota(\n input.db,\n input.settings,\n input.personalTurn,\n deps,\n )),\n );\n } catch {\n // The stored personal state stands.\n }\n }\n if (recovered.length > 0) {\n await deliverSubscriptionCoreProviderWake(input.db, SUBSCRIPTION_CORE_XAI_PROVIDER, {\n accountId: input.accountId,\n reason: \"usage_recovered\",\n }).catch(() => undefined);\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 {\n SESSION_EVENT_COALESCED_TEXT_TARGET_BYTES,\n reasoningDeltaSeparator,\n} from \"@opengeni/events\";\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. The first fragment of a turn, after a structural event (a\n// tool call, a completed message) or after a silence of one window is sent at\n// once, so time to first token is unchanged; later fragments wait at most one\n// window.\n// Each flush stores adjacent text fragments as one row, so the window sets how\n// many delta rows a stream writes: on staging traffic, 100ms stores about a\n// fifth of the provider fragments.\nexport const TRAILING_FLUSH_MS = 100;\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\nconst MERGEABLE_TEXT_DELTA_TYPES: ReadonlySet<string> = new Set([\n \"agent.message.delta\",\n \"agent.reasoning.delta\",\n]);\nconst textEncoder = new TextEncoder();\n\ntype PlainTextDelta = { text: string; messageId?: string; phase?: string };\n\n/** The plain fragment shape only: any other payload field would not survive a merge. */\nfunction plainTextDelta(event: AppendEventInput): PlainTextDelta | null {\n if (!MERGEABLE_TEXT_DELTA_TYPES.has(event.type)) return null;\n for (const key of Object.keys(event)) {\n if (key !== \"type\" && key !== \"payload\") return null;\n }\n const payload = event.payload;\n if (payload === null || typeof payload !== \"object\" || Array.isArray(payload)) return null;\n const record = payload as Record<string, unknown>;\n if (typeof record.text !== \"string\") return null;\n for (const key of Object.keys(record)) {\n if (key !== \"text\" && key !== \"messageId\" && key !== \"phase\") return null;\n }\n if (record.messageId !== undefined && typeof record.messageId !== \"string\") return null;\n if (record.phase !== undefined && typeof record.phase !== \"string\") return null;\n return record as PlainTextDelta;\n}\n\n/**\n * Stores adjacent text fragments of one stream as one delta: same type,\n * message and phase, at most the live stream's 48 KiB bound. The text and the\n * order of every other event are unchanged; only the provider's fragment\n * boundaries are dropped. Reasoning fragments are joined with the same\n * separator readers use ({@link reasoningDeltaSeparator}), so the rendered\n * reasoning is identical whether a reader sees the fragments or the merge.\n */\nexport function mergeAdjacentTextDeltas(events: AppendEventInput[]): AppendEventInput[] {\n const merged: AppendEventInput[] = [];\n let run: {\n first: AppendEventInput;\n head: PlainTextDelta;\n text: string;\n count: number;\n bytes: number;\n } | null = null;\n const flushRun = () => {\n if (!run) return;\n merged.push(\n run.count === 1\n ? run.first\n : {\n type: run.first.type,\n payload: {\n text: run.text,\n ...(run.head.messageId !== undefined ? { messageId: run.head.messageId } : {}),\n ...(run.head.phase !== undefined ? { phase: run.head.phase } : {}),\n },\n },\n );\n run = null;\n };\n for (const event of events) {\n const delta = plainTextDelta(event);\n if (!delta) {\n flushRun();\n merged.push(event);\n continue;\n }\n if (\n run &&\n run.first.type === event.type &&\n run.head.messageId === delta.messageId &&\n run.head.phase === delta.phase\n ) {\n const piece =\n (event.type === \"agent.reasoning.delta\"\n ? reasoningDeltaSeparator(run.text, delta.text)\n : \"\") + delta.text;\n const pieceBytes = textEncoder.encode(piece).byteLength;\n if (run.bytes + pieceBytes <= SESSION_EVENT_COALESCED_TEXT_TARGET_BYTES) {\n run.text += piece;\n run.count += 1;\n run.bytes += pieceBytes;\n continue;\n }\n }\n flushRun();\n run = {\n first: event,\n head: delta,\n text: delta.text,\n count: 1,\n bytes: textEncoder.encode(delta.text).byteLength,\n };\n }\n flushRun();\n return merged;\n}\n\n/** Optional metrics seam for the batcher. `onFlush` fires once per flush (on both\n * success and failure) with the stored event count (after adjacent text deltas\n * merge) and the flush duration, so the worker can meter batch shape without the\n * 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 = Number.NEGATIVE_INFINITY;\n // Leading edge: the first text fragment of a turn, and the first after a\n // structural event, goes out at once. Only text consumes it, so another\n // non-structural event (such as `agent.updated` on a handoff) cannot delay\n // the content that follows it.\n let awaitingFirstText = true;\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 / TRAILING_FLUSH_MS policy into one appendSessionEvents\n // txn + one publish per flush, instead of one DB round-trip per token, and\n // adjacent text fragments in a flush are stored as one row. 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 // behind a window (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 // A structural event closes the window: the next text fragment (the\n // start of the next message or reasoning item) is sent at once.\n awaitingFirstText = true;\n return;\n }\n const firstText = awaitingFirstText && MERGEABLE_TEXT_DELTA_TYPES.has(event.type);\n if (firstText) awaitingFirstText = false;\n if (firstText || 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 // Clear `drainPromise` in the same step that observes an empty queue, so a\n // push can never join a drain that has already finished its last batch\n // (that fragment would then wait for the trailing timer).\n let finished = false;\n const running = (async () => {\n try {\n while (pending.length > 0) {\n const events = mergeAdjacentTextDeltas(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 } finally {\n finished = true;\n drainPromise = null;\n }\n })();\n if (!finished) {\n drainPromise = running;\n }\n return running;\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 {\n IncidentTelemetryPreflight,\n secretNameKey,\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\n/** A vault the responder can reach, with its item names (never values). */\nexport type IncidentTelemetryVaultMetadata = {\n name: string;\n items: 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 /**\n * Vaults the responder reaches under the task's vault policy. The preflight\n * contract still says \"variable set\" (`requiredVariableSetNames`,\n * `requiredVariableNames`, route kind `variable_set`): those now name vaults\n * and items, matched case-insensitively.\n */\n vaults: readonly IncidentTelemetryVaultMetadata[];\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 vaultsByName = new Map(\n input.responder.vaults.map((vault) => [secretNameKey(vault.name), vault]),\n );\n if (preflight.requiredVariableSetNames.some((name) => !vaultsByName.has(secretNameKey(name)))) {\n return blocked(\"incident_responder_under_capable\");\n }\n const reachableItemNames = new Set(\n input.responder.vaults.flatMap((vault) => vault.items.map((item) => secretNameKey(item.name))),\n );\n if (\n preflight.requiredVariableNames.some((name) => !reachableItemNames.has(secretNameKey(name)))\n ) {\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 = vaultsByName.get(secretNameKey(route.variableSetName));\n const names = new Set(selected?.items.map((item) => secretNameKey(item.name)) ?? []);\n if (!selected || route.variableNames.some((name) => !names.has(secretNameKey(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 vaults: [...responder.vaults]\n .map((vault) => ({\n name: vault.name,\n items: vault.items.map((item) => item.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 listEnabledMcpCapabilityServerIds,\n listInstalledApiIntegrationServerIdsForDelegations,\n listVaultItems,\n listVaultsForSubject,\n markScheduledTaskRunAuthorityRejectedInTransaction,\n requireSession,\n requireWorkspace,\n type Database,\n} from \"@opengeni/db\";\nimport {\n resolveSessionFirstPartyMcpTools,\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 incidentTelemetryPreflightDeclaration,\n type IncidentTelemetryResponderMetadata,\n type IncidentTelemetryVaultMetadata,\n} from \"./incident-telemetry-preflight\";\n\n/**\n * Vaults (with item names) the responder reaches under the task's vault\n * policy, read only when the preflight names vaults or items. Metadata only:\n * connected vaults answer from their mirror, values are never read. Returns\n * null when the lookup failed, so the run blocks as metadata-incomplete.\n */\nasync function resolveIncidentTelemetryVaults(input: {\n db: Database;\n task: ScheduledTask;\n subjectId: string;\n}): Promise<IncidentTelemetryVaultMetadata[] | null> {\n const declaration = incidentTelemetryPreflightDeclaration(input.task.agentConfig, true);\n if (declaration.action !== \"required\") return [];\n const preflight = declaration.preflight;\n if (\n preflight.requiredVariableSetNames.length === 0 &&\n preflight.requiredVariableNames.length === 0 &&\n preflight.dataSource.route.kind !== \"variable_set\"\n ) {\n return [];\n }\n const context = {\n kind: \"subject\" as const,\n accountId: input.task.accountId,\n workspaceId: input.task.workspaceId,\n subjectId: input.subjectId,\n };\n const policy = input.task.vaultPolicy ?? { mode: \"all\" as const };\n try {\n const reachable = (\n await listVaultsForSubject(input.db, context, { workspaceId: input.task.workspaceId })\n ).filter((vault) => policy.mode === \"all\" || policy.vaultIds.includes(vault.id));\n const vaults: IncidentTelemetryVaultMetadata[] = [];\n for (const vault of reachable) {\n const items: { name: string }[] = [];\n let cursor: string | undefined;\n do {\n const page = await listVaultItems(input.db, context, {\n vaultId: vault.id,\n limit: 200,\n ...(cursor ? { cursor } : {}),\n });\n items.push(...page.items.map((item) => ({ name: item.name })));\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n vaults.push({ name: vault.name, items });\n }\n return vaults;\n } catch {\n return null;\n }\n}\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 /**\n * The tools a run that has no session yet will start with; a schedule that\n * follows the workspace defaults resolves them per run.\n */\n plannedTools?: Session[\"tools\"];\n executionPolicy?: {\n tools: ScheduledTaskRunAcceptedExecution[\"resolvedTools\"];\n firstPartyMcpTools: ScheduledTaskRunAcceptedExecution[\"resolvedFirstPartyMcpTools\"];\n firstPartyMcpPermissions:\n | ScheduledTaskRunAcceptedExecution[\"resolvedFirstPartyMcpPermissions\"]\n | 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 : (input.plannedTools ?? 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 if (input.executionPolicy ?? input.session) {\n const rigId = input.executionPolicy?.rigId ?? input.session?.rigId ?? null;\n const rigVersionId = input.executionPolicy?.rigVersionId ?? input.session?.rigVersionId ?? null;\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 }\n }\n } else {\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 }\n }\n }\n\n const vaults = await resolveIncidentTelemetryVaults({\n db: input.db,\n task: input.task,\n subjectId: input.personalResourceAuthoritySubjectId ?? input.task.createdBy.subjectId,\n });\n if (vaults === null) metadataComplete = false;\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 ? resolveSessionFirstPartyMcpTools(\n input.settings,\n input.session,\n (await requireWorkspace(input.db, input.task.workspaceId)).settings,\n )\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 vaults: vaults ?? [],\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:\n acceptedExecution.targetSessionExecution.effectiveFirstPartyMcpTools ??\n acceptedExecution.targetSessionExecution.firstPartyMcpTools,\n firstPartyMcpPermissions:\n acceptedExecution.targetSessionExecution.firstPartyMcpPermissions,\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 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 type { HeldSessionUsageReceipt } from \"@opengeni/core\";\nimport { settleSessionUsageReceipt, SessionUsageLimitUnavailableError } from \"@opengeni/db\";\nimport type { TurnActivityServices as ActivityServices } from \"../types\";\n\n/**\n * Attempt-scoped custody for per-task usage receipts whose write failed after\n * the provider response was received.\n *\n * The response is never lost or re-requested because of an accounting\n * failure: settlement hands the content-free receipt here (original source\n * identity, amount, pricing source) and the turn keeps the response. Before\n * the next model request (every admission check) and before the turn\n * completes, held receipts are written; if that still fails, the attempt\n * stops for the workflow's DB-only recovery lane and carries the held\n * receipts in its typed failure detail (durable in workflow history), which\n * the lane writes before any replacement attempt. Writes are idempotent per\n * source identity, so overlapping writers (the `agent.model.usage` event\n * meter, a later flush and the recovery lane) record the call once.\n */\n\ntype Scope = { accountId: string; workspaceId: string };\ntype Entry = Scope & { receipts: Map<string, HeldSessionUsageReceipt> };\n\n/** Bound on receipts carried through one recovery failure detail. */\nexport const MAX_RECOVERY_SESSION_USAGE_RECEIPTS = 64;\nconst MAX_HELD_SESSIONS = 4096;\nconst FLUSH_DELAYS_MS = [0, 250, 1_000];\n\nconst held = new Map<string, Entry>();\n\n/** Recovery reason and detail code for a task whose earlier single-call receipt is still owed. */\nexport const SESSION_USAGE_CUSTODY_PENDING = \"session_usage_custody_pending\";\n/**\n * How long a parked turn waits before its replacement attempt re-checks\n * admission (database reads only). An owner fills its receipt within\n * seconds; a dead owner's marker is disclosed by maintenance after 30\n * minutes, so a task waits at most about 60 rechecks.\n */\nexport const SESSION_USAGE_CUSTODY_RECHECK_MS = 30_000;\n\n/** A fenced or overdue custody marker (not a database outage) refused the next model request. */\nexport function sessionUsageCustodyPending(error: unknown): boolean {\n let current = error;\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n if (current instanceof SessionUsageLimitUnavailableError) {\n return current.reason === \"custody_pending\";\n }\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n}\n\nexport function holdSessionUsageReceipt(scope: Scope, receipt: HeldSessionUsageReceipt): void {\n let entry = held.get(receipt.sessionId);\n if (!entry) {\n if (held.size >= MAX_HELD_SESSIONS) {\n // Oldest sessions only: their receipts already travelled with a\n // recovery failure or will be re-imported from durable usage events.\n const oldest = held.keys().next().value;\n if (oldest !== undefined) held.delete(oldest);\n }\n entry = { accountId: scope.accountId, workspaceId: scope.workspaceId, receipts: new Map() };\n held.set(receipt.sessionId, entry);\n }\n entry.receipts.set(receipt.sourceId, receipt);\n}\n\n/** Held receipts for one turn, bounded, for a post-claim recovery failure detail. */\nexport function heldSessionUsageReceiptsForTurn(turnId: string): HeldSessionUsageReceipt[] {\n const receipts: HeldSessionUsageReceipt[] = [];\n for (const entry of held.values()) {\n for (const receipt of entry.receipts.values()) {\n if (receipt.turnId === turnId) receipts.push(receipt);\n if (receipts.length >= MAX_RECOVERY_SESSION_USAGE_RECEIPTS) return receipts;\n }\n }\n return receipts;\n}\n\nexport function heldSessionUsageReceiptCount(sessionId?: string): number {\n if (sessionId !== undefined) return held.get(sessionId)?.receipts.size ?? 0;\n let count = 0;\n for (const entry of held.values()) count += entry.receipts.size;\n return count;\n}\n\n/**\n * The `agent.model.usage` event for a held receipt committed. Its appending\n * transaction meters the same source identity through the database trigger\n * (or, for a root still preparing, leaves the event for the bounded import),\n * and a trigger failure would have rolled the event back. When the event\n * carries exactly the held amount, the receipt is therefore durable and the\n * hold is dropped, so completion does not stop for a write that is already\n * done. A different or unknown event amount keeps the hold: only the direct\n * write can record (or fill) that value.\n */\nexport function releaseHeldSessionUsageReceiptMeteredByEvent(input: {\n sessionId: string;\n sourceId: string;\n amountMicros: number | null;\n pricingSource: string | null;\n}): boolean {\n const entry = held.get(input.sessionId);\n const receipt = entry?.receipts.get(input.sourceId);\n if (!entry || !receipt) return false;\n if (receipt.amountMicros !== input.amountMicros) return false;\n if (receipt.amountMicros !== null && receipt.pricingSource !== input.pricingSource) return false;\n entry.receipts.delete(input.sourceId);\n if (entry.receipts.size === 0 && held.get(input.sessionId) === entry) {\n held.delete(input.sessionId);\n }\n return true;\n}\n\n/** Write receipts with their original identities; throws the last database error. */\nexport async function writeSessionUsageReceipts(\n db: ActivityServices[\"db\"],\n scope: Scope,\n receipts: readonly HeldSessionUsageReceipt[],\n): Promise<void> {\n for (const receipt of receipts) {\n await settleSessionUsageReceipt(db, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n sessionId: receipt.sessionId,\n sourceId: receipt.sourceId,\n turnId: receipt.turnId,\n amountMicros: receipt.amountMicros,\n pricingSource: receipt.amountMicros === null ? null : receipt.pricingSource,\n model: receipt.model,\n });\n }\n}\n\n/**\n * Write every receipt held for this session before another model request or\n * turn completion. Retries briefly; a persistent failure rethrows the\n * database error so the attempt enters post-claim DB recovery with the\n * receipts still held for its failure detail.\n */\nexport async function flushHeldSessionUsageReceipts(\n db: ActivityServices[\"db\"],\n sessionId: string,\n): Promise<void> {\n const entry = held.get(sessionId);\n if (!entry || entry.receipts.size === 0) return;\n let lastError: unknown;\n for (const delay of FLUSH_DELAYS_MS) {\n if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));\n try {\n // A parallel call (session title) may hold another receipt meanwhile.\n while (entry.receipts.size > 0) {\n for (const [sourceId, receipt] of [...entry.receipts]) {\n await writeSessionUsageReceipts(db, entry, [receipt]);\n entry.receipts.delete(sourceId);\n }\n }\n if (entry.receipts.size === 0 && held.get(sessionId) === entry) held.delete(sessionId);\n return;\n } catch (error) {\n lastError = error;\n }\n }\n throw lastError;\n}\n\n/** Test-only reset of process custody. */\nexport function resetSessionUsageReceiptCustodyForTests(): void {\n held.clear();\n}\n","import {\n CODEX_CLIENT_VERSION,\n fetchCodexUsage,\n normalizeCodexUsage,\n type CodexTokenSnapshot,\n type CodexUsageHeaderSnapshot,\n type CodexUsagePayload,\n} from \"@opengeni/codex\";\nimport { SubscriptionCoreCodexRequestOutcomeUnknownError } from \"@opengeni/db\";\n\n/** Local admission decision, never a synthetic provider/transport error. */\nexport class CodexIncludedUsageExhaustedError extends Error {\n readonly code = \"codex_included_usage_exhausted\";\n constructor(readonly resetsInSeconds: number | null) {\n super(\"This account's included Codex usage is exhausted. Extra credits are protected.\");\n this.name = \"CodexIncludedUsageExhaustedError\";\n }\n}\n\nexport class CodexIncludedUsageUnknownError extends Error {\n readonly code = \"codex_included_usage_unknown\";\n constructor() {\n super(\n \"Couldn't verify included Codex usage. This account is temporarily unavailable while extra credits are protected.\",\n );\n this.name = \"CodexIncludedUsageUnknownError\";\n }\n}\n\nexport function findCodexCreditPolicyError(\n error: unknown,\n): CodexIncludedUsageExhaustedError | CodexIncludedUsageUnknownError | null {\n const seen = new Set<object>();\n for (let depth = 0; depth < 8 && error && typeof error === \"object\"; depth++) {\n if (seen.has(error)) break;\n seen.add(error);\n if (\n error instanceof CodexIncludedUsageExhaustedError ||\n error instanceof CodexIncludedUsageUnknownError\n )\n return error;\n error = (error as { cause?: unknown }).cause;\n }\n return null;\n}\n\n/** A model call can cross the provider's limit; the next call must be admitted again. */\nexport function createCodexCreditGuard(input: {\n allowExtraCredits?: boolean;\n /** Live accepted-pool admission, rechecked immediately before dispatch. */\n canSpendCredits?: () => Promise<boolean>;\n readUsage?: (token: CodexTokenSnapshot) => Promise<CodexUsagePayload>;\n fetchUsage?: typeof fetchCodexUsage;\n refreshToken?: () => Promise<CodexTokenSnapshot>;\n now?: () => number;\n onUsage?: (snapshot: CodexUsageHeaderSnapshot) => void;\n}) {\n const now = input.now ?? Date.now;\n const readUsage =\n input.readUsage ??\n (async (token: CodexTokenSnapshot) => {\n const result = await (input.fetchUsage ?? fetchCodexUsage)({\n ...token,\n clientVersion: CODEX_CLIENT_VERSION,\n });\n if (result.status === 401) throw new CodexUsageUnauthorizedError();\n return normalizeCodexUsage(result.status, result.payload);\n });\n let token: CodexTokenSnapshot | null = null;\n type Observation = { windows: Array<{ used: number; reset: Date | null }>; checkedAt: Date };\n let snapshot: Observation | null = null;\n let spendingRefusal: CodexIncludedUsageExhaustedError | CodexIncludedUsageUnknownError | null =\n null;\n let observationRevision = 0;\n let admissionTail: Promise<void> = Promise.resolve();\n const observe = (next: CodexUsageHeaderSnapshot) => {\n if (snapshot && next.checkedAt.getTime() < snapshot.checkedAt.getTime()) return;\n observationRevision++;\n snapshot = {\n checkedAt: next.checkedAt,\n windows: [\n { used: next.primaryUsedPercent, reset: next.primaryResetAt },\n { used: next.secondaryUsedPercent, reset: next.secondaryResetAt },\n ],\n };\n };\n const check = (value: Observation, at: number): boolean => {\n const windows = value.windows;\n const exhausted = windows.filter((w) => w.used >= 100 && (!w.reset || w.reset.getTime() > at));\n if (exhausted.length) {\n const reset = exhausted.every((w) => w.reset)\n ? Math.max(...exhausted.map((w) => w.reset!.getTime()))\n : null;\n throw new CodexIncludedUsageExhaustedError(\n reset === null ? null : Math.ceil((reset - at) / 1000),\n );\n }\n // A passed reset is a reason to refresh, not proof of new allowance.\n return windows.every((w) => Number.isFinite(w.used) && (!w.reset || w.reset.getTime() > at));\n };\n const assertCanDispatch = async () => {\n if (input.allowExtraCredits) return;\n const at = now();\n // Headers can refuse dispatch immediately. A successful observation is\n // never a reusable spending permit: the preceding response or another\n // session may have consumed the remaining allowance.\n if (snapshot) check(snapshot, at);\n if (!token) throw new CodexIncludedUsageUnknownError();\n const revisionAtRead = observationRevision;\n let usage: CodexUsagePayload | null;\n try {\n usage = await readUsage(token);\n } catch (error) {\n if (error instanceof SubscriptionCoreCodexRequestOutcomeUnknownError) throw error;\n if (error instanceof CodexUsageUnauthorizedError && input.refreshToken) {\n // This runs during credential resolution, before the model's auth\n // headers are constructed. The caller tracks the refreshed version.\n token = await input.refreshToken();\n usage = await readUsage(token).catch((usageError: unknown) => {\n if (usageError instanceof SubscriptionCoreCodexRequestOutcomeUnknownError)\n throw usageError;\n return null;\n });\n } else {\n usage = null;\n }\n }\n if (!usage || usage.status === \"error\" || usage.status === \"no-data\")\n throw new CodexIncludedUsageUnknownError();\n const windows = [usage.fiveHour, usage.weekly].flatMap((window) =>\n window\n ? [\n {\n used: window.percent,\n reset: window.resetAt ? new Date(window.resetAt) : null,\n },\n ]\n : [],\n );\n if (!windows.length) {\n if (usage.limitReached || usage.status === \"limit_reached\")\n throw new CodexIncludedUsageExhaustedError(null);\n throw new CodexIncludedUsageUnknownError();\n }\n const next: Observation = { windows, checkedAt: new Date(now()) };\n // A response header received during this read is newer evidence than the\n // request's snapshot. Never let a delayed usage response erase it.\n if (observationRevision === revisionAtRead) snapshot = next;\n // The legacy cache contract only accepts a complete duration-labeled pair.\n if (usage.fiveHour && usage.weekly && observationRevision === revisionAtRead)\n input.onUsage?.({\n primaryUsedPercent: usage.fiveHour.percent,\n primaryResetAt: usage.fiveHour.resetAt ? new Date(usage.fiveHour.resetAt) : null,\n secondaryUsedPercent: usage.weekly.percent,\n secondaryResetAt: usage.weekly.resetAt ? new Date(usage.weekly.resetAt) : null,\n checkedAt: next.checkedAt,\n });\n if (snapshot) check(snapshot, now());\n if (!check(next, now())) throw new CodexIncludedUsageUnknownError();\n // Provider feature identifiers are not guaranteed to be model slugs.\n // Until an authoritative mapping exists, an exhausted extra allowance\n // cannot grant permission to continue spending on this account.\n for (const limit of usage.additionalLimits ?? []) {\n if (limit.unknownWindowExhausted) throw new CodexIncludedUsageExhaustedError(null);\n const featureWindows = [limit.fiveHour, limit.weekly].flatMap((window) =>\n window\n ? [\n {\n used: window.percent,\n reset: window.resetAt ? new Date(window.resetAt) : null,\n },\n ]\n : [],\n );\n if (\n featureWindows.length &&\n !check({ windows: featureWindows, checkedAt: next.checkedAt }, now())\n ) {\n throw new CodexIncludedUsageUnknownError();\n }\n }\n if (usage.limitReached || usage.status === \"limit_reached\")\n throw new CodexIncludedUsageExhaustedError(null);\n };\n return {\n setToken: (next: CodexTokenSnapshot) => {\n token = next;\n },\n observe,\n assertObservedUsageAllowsDispatch: async () => {\n if (input.allowExtraCredits) return;\n const refusal = spendingRefusal;\n if (refusal instanceof CodexIncludedUsageExhaustedError) {\n const allowed = await input.canSpendCredits?.();\n // A concurrent read can learn that usage is unverifiable while this\n // policy query is pending. Earlier consent cannot erase newer evidence.\n if (spendingRefusal !== refusal) {\n if (spendingRefusal) throw spendingRefusal;\n if (snapshot) check(snapshot, now());\n return;\n }\n if (allowed) return;\n }\n if (spendingRefusal) throw spendingRefusal;\n if (snapshot) check(snapshot, now());\n },\n assertCanDispatch: () => {\n // Main and title requests share this guard. Serialize their reads so a\n // late successful response cannot overwrite a newer exhaustion result.\n const admission = admissionTail.then(async () => {\n try {\n await assertCanDispatch();\n // Pending reads cannot erase an earlier feature-limit refusal. Only\n // a complete, successful usage observation restores included access.\n spendingRefusal = null;\n } catch (error) {\n if (\n error instanceof CodexIncludedUsageExhaustedError ||\n error instanceof CodexIncludedUsageUnknownError\n )\n spendingRefusal = error;\n if (\n error instanceof CodexIncludedUsageExhaustedError &&\n (await input.canSpendCredits?.()) &&\n spendingRefusal === error\n ) {\n return;\n }\n throw error;\n }\n });\n admissionTail = admission.catch(() => undefined);\n return admission;\n },\n };\n}\n\nclass CodexUsageUnauthorizedError extends Error {}\n\n/** No awaited policy work may run after the final physical lease fence. */\nexport async function assertCodexDispatchAdmission(\n assertCredits: () => Promise<void>,\n assertLease: () => Promise<void>,\n): Promise<void> {\n await assertCredits();\n await assertLease();\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\n/**\n * Upper bound for joining a cancelled attempt's in-flight provider establish.\n * Worker shutdown cancels activities 5s after SIGTERM and force-stops 100s\n * after it; this leaves room for the remaining finalization steps.\n */\nexport const PHYSICAL_SANDBOX_RESUME_DRAIN_TIMEOUT_MS = 60_000;\n\n/** Register the PHYSICAL lease acquire/provider establish promise, not the\n * cancellable wrapper awaiting it. */\nexport function trackPhysicalSandboxResume<T>(\n inFlight: Set<Promise<unknown>>,\n operation: Promise<T>,\n): Promise<T> {\n inFlight.add(operation);\n const settle = (): void => {\n inFlight.delete(operation);\n };\n operation.then(settle, settle);\n return operation;\n}\n\n/**\n * Join every lease acquire/provider establish this attempt started, even after\n * the turn-facing wrapper rejected on cancellation. An establish has no\n * portable abort: after cancellation it still finishes its own exact cleanup\n * (terminate an unpublished box and roll warming back to cold, or keep a\n * published box and drop its holder). If the activity returned first, a\n * shutting-down worker exited mid-cleanup and stranded a warming lease naming a\n * terminated box; the replacement attempt then waited out the warming TTL and\n * inherited a lost-workspace verdict. This wait is deliberately independent of\n * the finalizer cancellation signal (cancellation is what started it) and is\n * bounded so an uncooperative provider call cannot pin the activity.\n */\nexport async function drainPhysicalSandboxResumes(\n inFlight: Set<Promise<unknown>>,\n timeoutMs: number = PHYSICAL_SANDBOX_RESUME_DRAIN_TIMEOUT_MS,\n): Promise<\"none\" | \"settled\" | \"timed_out\"> {\n if (inFlight.size === 0) return \"none\";\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n Promise.allSettled([...inFlight]).then(() => \"settled\" as const),\n new Promise<\"timed_out\">((resolve) => {\n timer = setTimeout(() => resolve(\"timed_out\"), Math.max(1, timeoutMs));\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\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 physical cleanup is\n * stuck. The callback requests host-owned containment, which drains peer turns\n * before applying its final exit policy. A timeout is never quiescence proof. */\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(toolCallIds?: readonly string[]): Promise<void>;\n};\n\n/** Release only durably recorded tool results, or the complete durable turn. */\nexport async function finalizeDurableTurnOpStreams(\n sessions: readonly unknown[],\n fallback: OpStreamFinalizer | null,\n toolCallIds?: readonly string[],\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(toolCallIds);\n } catch {\n // The runner's retention TTL owns the fallback.\n }\n }\n}\n","/** Closed policy facts shared with the workflow's content-free recovery wire. */\nexport const PROVIDER_OVERLOAD_RECOVERY_CODE = \"provider_overloaded\";\nexport const MAX_AUTOMATIC_PROVIDER_OVERLOAD_RECOVERIES = 15;\nexport const PROVIDER_OVERLOAD_RECOVERY_WINDOW_MS = 15 * 60_000;\n\nexport function validProviderOverloadRecoveryDelay(code: unknown, delay: unknown): boolean {\n if (delay === undefined) return code !== PROVIDER_OVERLOAD_RECOVERY_CODE;\n return (\n code === PROVIDER_OVERLOAD_RECOVERY_CODE &&\n typeof delay === \"number\" &&\n Number.isSafeInteger(delay) &&\n delay > 0 &&\n delay < PROVIDER_OVERLOAD_RECOVERY_WINDOW_MS\n );\n}\n\nexport function readProviderRecoveryStartedAt(\n metadata: Record<string, unknown>,\n): number | undefined {\n const value =\n typeof metadata.providerRecoveryStartedAt === \"string\"\n ? Date.parse(metadata.providerRecoveryStartedAt)\n : NaN;\n return Number.isFinite(value) ? value : undefined;\n}\n","import { ClaudeSubscriptionReconnectRequired } from \"@opengeni/db\";\nimport { DrizzleQueryError } from \"drizzle-orm\";\nimport { SandboxCapabilitiesChangedError } from \"./provider-dispatch-barrier\";\nimport { heldSessionUsageReceiptsForTurn } from \"./session-usage-custody\";\nimport {\n ActiveSessionHistoryLimitExceededError,\n ApprovalRunStateLimitExceededError,\n nestedPostgresSqlState,\n databaseFailureCode,\n isRetryablePersistenceSqlState,\n safeDatabaseErrorFacts,\n isRetryableDatabaseTransportFailure,\n isSessionEventPersistenceError,\n DatabaseTransactionError,\n SandboxLeaseTransitionError,\n} from \"@opengeni/db\";\nimport {\n ActiveBackendUnresolvableError,\n AnthropicProviderRejection,\n CompactionProviderResponseError,\n EmptyCompactionSummaryError,\n compactionProviderRejection,\n describeCompactionProviderRejection,\n type CompactionProviderRejection,\n isMcpRequestTimeoutError,\n isMcpTransportConnectivityError,\n isModalTaskExecStartPreDispatchUnavailableError,\n isModalCommandStartOutcomeUnknownError,\n isProviderCommandObservationUnavailableError,\n ProviderCommandInputOutcomeUnknownError,\n ProviderCommandStartOutcomeUnknownError,\n isRoutingMutationOutcomeUnknownError,\n isRoutingMutationOutputRejectedError,\n RoutingWorkspaceRootChangedError,\n RoutingBackendRecoveryRequiredError,\n ResponsesStreamingTerminalError,\n classifyModelStreamIdleTimeoutError,\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 AnthropicRequestError,\n findAnthropicRequestSizeError,\n AnthropicSizeRecoveryExhaustedError,\n type AnthropicRequestSize,\n} from \"@opengeni/runtime\";\nimport {\n mcpTransportRequestFailureDiagnostic,\n type McpTransportRequestFailureDiagnostic,\n} from \"@opengeni/runtime/mcp-network\";\nimport { ApplicationFailure, CancelledFailure } from \"@temporalio/activity\";\nimport type { ProviderErrorOutcome } from \"@opengeni/subscriptions\";\nimport { CODEX_USAGE_EXHAUSTED_PCT } from \"./codex-usage-policy\";\nimport {\n RetainedAttachmentTransportLimitError,\n RetainedAttachmentUnavailableError,\n} 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 { SubscriptionCoreCodexTurnError } from \"./codex-core-errors\";\nimport {\n CodexIncludedUsageExhaustedError,\n CodexIncludedUsageUnknownError,\n findCodexCreditPolicyError,\n} from \"./codex-credit-policy\";\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\";\nimport {\n MODEL_PROVIDER_RECOVERY_CODES,\n providerRecoveryExhaustedMessage,\n providerRecoverySubject,\n type ProviderCondition,\n} from \"./provider-recovery-copy\";\nimport {\n PROVIDER_OVERLOAD_RECOVERY_CODE,\n MAX_AUTOMATIC_PROVIDER_OVERLOAD_RECOVERIES,\n PROVIDER_OVERLOAD_RECOVERY_WINDOW_MS,\n validProviderOverloadRecoveryDelay,\n} from \"./provider-recovery-policy\";\nexport {\n PROVIDER_OVERLOAD_RECOVERY_CODE,\n MAX_AUTOMATIC_PROVIDER_OVERLOAD_RECOVERIES,\n PROVIDER_OVERLOAD_RECOVERY_WINDOW_MS,\n} from \"./provider-recovery-policy\";\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;\nexport function providerRecoveryLimit(failureCode: unknown): number {\n return failureCode === PROVIDER_OVERLOAD_RECOVERY_CODE\n ? MAX_AUTOMATIC_PROVIDER_OVERLOAD_RECOVERIES\n : MAX_AUTOMATIC_PROVIDER_RECOVERIES;\n}\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;\n/** Positive-only spread: never shorten the provider's minimum delay. */\nexport function providerRecoveryJitterMs(delayMs: number, sample: number): number {\n const bounded = Number.isFinite(sample) ? Math.max(0, Math.min(sample, 1)) : 0;\n return Math.floor(Math.min(5_000, delayMs * 0.2) * bounded);\n}\nexport const POST_COMPACTION_CONTINUATION_EMPTY_CODE = \"post_compaction_continuation_empty\";\nexport const RETAINED_ATTACHMENT_UNAVAILABLE_CODE = \"retained_attachment_unavailable\";\n\nfunction findRetainedAttachmentUnavailableError(\n error: unknown,\n): RetainedAttachmentUnavailableError | null {\n let current = error;\n const seen = new Set<unknown>();\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n if (current instanceof RetainedAttachmentUnavailableError) return current;\n if (seen.has(current)) break;\n seen.add(current);\n current = (current as { cause?: unknown }).cause;\n }\n return null;\n}\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 maxProviderRecoveryCount?: number;\n }\n | {\n status: \"exhausted\";\n providerRecoveryCount: number;\n maxProviderRecoveryCount: number;\n providerRecoveryExhaustedReason?: \"deadline\" | \"retry_limit\" | \"invalid_clock\";\n };\n\nexport function providerRecoveryResult(input: {\n failureCode: string | undefined;\n attemptNumber: number;\n retryAfterMs?: number | null;\n jitterSample?: number;\n /** Durable first-failure clock, never a new clock on each replacement attempt. */\n recoveryStartedAt?: number | undefined;\n now?: number;\n}): ProviderRecoveryResult {\n const overload = input.failureCode === PROVIDER_OVERLOAD_RECOVERY_CODE;\n const limit = providerRecoveryLimit(input.failureCode);\n const exhausted = (\n reason: \"deadline\" | \"retry_limit\" | \"invalid_clock\",\n ): Extract<ProviderRecoveryResult, { status: \"exhausted\" }> => ({\n status: \"exhausted\",\n providerRecoveryCount: Math.min(Math.max(input.attemptNumber - 1, 0), limit),\n maxProviderRecoveryCount: limit,\n providerRecoveryExhaustedReason: reason,\n });\n if (input.attemptNumber > limit) {\n if (overload) return exhausted(\"retry_limit\");\n return {\n status: \"exhausted\",\n providerRecoveryCount: MAX_AUTOMATIC_PROVIDER_RECOVERIES,\n maxProviderRecoveryCount: MAX_AUTOMATIC_PROVIDER_RECOVERIES,\n };\n }\n const now = input.now ?? Date.now();\n const startedAt = input.recoveryStartedAt ?? (input.attemptNumber === 1 ? now : NaN);\n if (overload && (!Number.isFinite(startedAt) || !Number.isFinite(now) || startedAt > now)) {\n return exhausted(\"invalid_clock\");\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 : overload ||\n input.failureCode === \"provider_unavailable\" ||\n input.failureCode === \"upstream_connectivity_unavailable\" ||\n input.failureCode === \"sandbox_command_start_unavailable\" ||\n input.failureCode === RETAINED_ATTACHMENT_UNAVAILABLE_CODE ||\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 const delayMs =\n continueDelayMs +\n (overload ||\n input.failureCode === \"provider_rate_limited\" ||\n input.failureCode === \"provider_unavailable\" ||\n input.failureCode === \"upstream_connectivity_unavailable\"\n ? providerRecoveryJitterMs(continueDelayMs, input.jitterSample ?? 0)\n : 0);\n // Do not shorten Retry-After, or schedule a replacement outside the window.\n if (overload && now + delayMs >= startedAt + PROVIDER_OVERLOAD_RECOVERY_WINDOW_MS) {\n return exhausted(\"deadline\");\n }\n return {\n status: \"recovering\",\n continueDelayMs: delayMs,\n ...(overload ? { maxProviderRecoveryCount: limit } : {}),\n };\n}\n\n/** A timer/queue delay cannot authorize a provider call after the recovery window. */\nexport class ProviderOverloadRecoveryExpiredError extends Error {\n readonly failure;\n\n constructor(count: number, reason: \"deadline\" | \"retry_limit\" | \"invalid_clock\") {\n super(\"Confirmed provider overload recovery window expired before dispatch\");\n this.name = \"ProviderOverloadRecoveryExpiredError\";\n this.failure = providerRecoveryExhaustedFailure(\n {\n error: this.message,\n code: \"provider_unavailable\",\n providerCondition: \"overloaded\" as const,\n },\n {\n status: \"exhausted\",\n // The queued replacement has not dispatched; count only prior retries.\n providerRecoveryCount: Math.min(\n MAX_AUTOMATIC_PROVIDER_OVERLOAD_RECOVERIES,\n Math.max(0, count - 1),\n ),\n maxProviderRecoveryCount: MAX_AUTOMATIC_PROVIDER_OVERLOAD_RECOVERIES,\n providerRecoveryExhaustedReason: reason,\n },\n );\n }\n}\n\nexport function assertProviderOverloadRecoveryActive(input: {\n failureCode: unknown;\n providerRecoveryCount: number;\n recoveryStartedAt?: number | undefined;\n now?: number;\n}): void {\n if (input.failureCode !== PROVIDER_OVERLOAD_RECOVERY_CODE || input.providerRecoveryCount === 0) {\n return;\n }\n if (input.providerRecoveryCount > MAX_AUTOMATIC_PROVIDER_OVERLOAD_RECOVERIES) {\n throw new ProviderOverloadRecoveryExpiredError(input.providerRecoveryCount, \"retry_limit\");\n }\n const now = input.now ?? Date.now();\n const startedAt = input.recoveryStartedAt;\n if (\n startedAt === undefined ||\n !Number.isFinite(startedAt) ||\n !Number.isFinite(now) ||\n startedAt > now\n ) {\n throw new ProviderOverloadRecoveryExpiredError(input.providerRecoveryCount, \"invalid_clock\");\n }\n if (now >= startedAt + PROVIDER_OVERLOAD_RECOVERY_WINDOW_MS) {\n throw new ProviderOverloadRecoveryExpiredError(input.providerRecoveryCount, \"deadline\");\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 providerRecoveryExhaustedReason?: \"deadline\" | \"retry_limit\" | \"invalid_clock\";\n} {\n return {\n ...failure,\n error: providerRecoveryExhaustedMessage({\n code: typeof failure.code === \"string\" ? failure.code : null,\n providerCondition: isProviderCondition(failure.providerCondition)\n ? failure.providerCondition\n : null,\n modelLabel: typeof failure.modelLabel === \"string\" ? failure.modelLabel : null,\n providerLabel: typeof failure.providerLabel === \"string\" ? failure.providerLabel : null,\n providerRecoveryCount: recovery.providerRecoveryCount,\n }),\n retryable: false,\n recoveryExhausted: true,\n providerRecoveryCount: recovery.providerRecoveryCount,\n maxProviderRecoveryCount: recovery.maxProviderRecoveryCount,\n ...(recovery.providerRecoveryExhaustedReason\n ? { providerRecoveryExhaustedReason: recovery.providerRecoveryExhaustedReason }\n : {}),\n lastRetryableError: failure.error,\n };\n}\n\nfunction isProviderCondition(value: unknown): value is ProviderCondition {\n return (\n value === \"overloaded\" ||\n value === \"unavailable\" ||\n value === \"unresponsive\" ||\n value === \"rate_limited\"\n );\n}\n\n/**\n * A retryable failure whose automatic same-turn recovery was not authorized\n * (for example, request custody could not be checkpointed). The classifier's\n * \"will retry\" sentence would be false on a terminal record, so name the\n * condition and the person's options instead.\n */\nexport function automaticRecoveryUnavailableFailure<\n T extends Record<string, unknown> & { error: string },\n>(\n failure: T,\n): T & {\n retryable: false;\n automaticRecovery: \"unavailable\";\n lastRetryableError: string;\n} {\n const subject = providerRecoverySubject({\n code: typeof failure.code === \"string\" ? failure.code : null,\n providerCondition: isProviderCondition(failure.providerCondition)\n ? failure.providerCondition\n : null,\n modelLabel: typeof failure.modelLabel === \"string\" ? failure.modelLabel : null,\n providerLabel: typeof failure.providerLabel === \"string\" ? failure.providerLabel : null,\n });\n return {\n ...failure,\n error: `${subject}. Opengeni couldn't retry this turn automatically. Try again, or send a message to continue.`,\n retryable: false,\n automaticRecovery: \"unavailable\",\n lastRetryableError: failure.error,\n };\n}\n\n/**\n * Name the exact accepted model route on model-provider recovery evidence so a\n * person learns which model is affected. Display labels only: the route's\n * credentials, base URL and upstream ids never enter the event.\n */\nexport function withModelRoutePresentation<T extends { code?: string | undefined }>(\n failure: T,\n route: { model: string; modelLabel: string; providerLabel: string } | undefined,\n): T & { model?: string; modelLabel?: string; providerLabel?: string } {\n if (!route || !failure.code || !MODEL_PROVIDER_RECOVERY_CODES.has(failure.code)) return failure;\n return {\n ...failure,\n model: route.model,\n modelLabel: route.modelLabel,\n providerLabel: route.providerLabel,\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 milliseconds = Number(\n headerValue(value.headers, \"retry-after-ms\") ??\n headerValue(value.responseHeaders, \"retry-after-ms\") ??\n headerValue(body?.headers, \"retry-after-ms\") ??\n undefined,\n );\n if (Number.isFinite(milliseconds) && milliseconds > 0) return Math.ceil(milliseconds);\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\n/** Complete structured-cause graph or no recovery authority. Budget distinct\n * objects (including array containers), not queue positions/duplicate refs.\n * The separate link ceiling bounds huge duplicate arrays without truncating\n * them into permission. Cycles are harmless; overflow/unreadable edges hold. */\nfunction structuredRecoveryCauseGraph(error: unknown): Map<object, Set<object>> | null {\n const graph = new Map<object, Set<object>>();\n const queue: object[] = [];\n let links = 0;\n const add = (value: unknown): boolean => {\n if (!value || typeof value !== \"object\" || graph.has(value)) return true;\n if (graph.size >= 64) return false;\n graph.set(value, new Set());\n queue.push(value);\n return true;\n };\n if (!add(error)) return null;\n try {\n for (const current of queue) {\n const record = current as Record<string, unknown>;\n const children = Array.isArray(current)\n ? current\n : [\"cause\", \"original\", \"driverError\", \"error\", \"errors\"].map((key) => record[key]);\n for (const child of children) {\n if (++links > 4096 || !add(child)) return null;\n if (child && typeof child === \"object\") graph.get(current)!.add(child);\n }\n }\n } catch {\n return null;\n }\n return graph;\n}\n\nfunction retryableDatabaseFailureCode(\n error: unknown,\n requireDatabaseProvenance = false,\n): PostClaimDatabaseRecoveryDetail[\"code\"] | null {\n try {\n const graph = structuredRecoveryCauseGraph(error);\n if (!graph) return null;\n const transports = new Set<object>();\n const boundaries = new Set<object>();\n const ownDatabaseNodes = new Set<object>();\n const codes = new Set<PostClaimDatabaseRecoveryDetail[\"code\"]>();\n const ownChildren = (node: object): object[] =>\n node instanceof DatabaseTransactionError\n ? // Callback failures retained beside a failed rollback supply vetoes,\n // never driver provenance for a provider's connection-looking error.\n [...graph.get(node)!].filter((child) => child === node.cause)\n : [...graph.get(node)!];\n // Ask the canonical transport predicate about ONLY this node's facts. Its\n // recursive search must not pair a DB sibling with an unrelated provider.\n for (const node of graph.keys()) {\n if (isRoutingMutationOutcomeUnknownError(node) || isRoutingMutationOutputRejectedError(node))\n return null;\n const record = node as Record<string, unknown>;\n if (\n requireDatabaseProvenance\n ? isRunningTurnDatabaseTransportFailure(record)\n : isRetryableDatabaseTransportFailure({ code: record.code, errno: record.errno })\n )\n transports.add(node);\n const sqlState = isSessionEventPersistenceError(node)\n ? node.details.sqlState\n : record.name === \"PostgresError\" && typeof record.code === \"string\"\n ? record.code\n : null;\n if (\n requireDatabaseProvenance\n ? isRunningTurnDatabaseConnectionSqlState(sqlState)\n : isDatabaseConnectionSqlState(sqlState)\n )\n transports.add(node);\n if (\n node instanceof DrizzleQueryError ||\n node instanceof DatabaseTransactionError ||\n isSessionEventPersistenceError(node)\n ) {\n // Only actual errors raised at our ORM/typed persistence boundary own\n // their driver subtree. A PostgresError name, SDK wrapper or provider\n // socket by itself is never own-client provenance for a running turn.\n const queue: object[] = [node];\n for (const source of queue) {\n if (ownDatabaseNodes.has(source)) continue;\n ownDatabaseNodes.add(source);\n queue.push(...ownChildren(source));\n }\n }\n }\n const hasOwnTransport = (boundary: object): boolean => {\n const seen = new Set<object>();\n const queue = [boundary];\n for (const node of queue) {\n if (seen.has(node)) continue;\n seen.add(node);\n if (transports.has(node)) return true;\n queue.push(...ownChildren(node));\n }\n return false;\n };\n // Inspect ALL trusted DB evidence before returning a permit. A permanent,\n // auth or uncertain SQLSTATE vetoes every sibling regardless of traversal\n // order; a deeper transport/reset cannot override it either.\n for (const node of graph.keys()) {\n const record = node as Record<string, unknown>;\n if (node instanceof DrizzleQueryError || node instanceof DatabaseTransactionError) {\n boundaries.add(node);\n if (hasOwnTransport(node)) codes.add(\"db_failure\");\n }\n const typed = isSessionEventPersistenceError(node);\n if (!typed && record.name !== \"PostgresError\") continue;\n boundaries.add(node);\n const sqlState = typed\n ? node.details.sqlState\n : typeof record.code === \"string\"\n ? record.code\n : null;\n const connectionOutage = requireDatabaseProvenance\n ? isRunningTurnDatabaseConnectionSqlState(sqlState)\n : isDatabaseConnectionSqlState(sqlState);\n // PostgreSQL aborts a deadlock or serialization victim's whole\n // transaction: unlike a lost connection, that write certainly did not\n // commit, so it is at least as safe for exact-attempt recovery.\n const rolledBack = isRetryablePersistenceSqlState(sqlState);\n const code = typed\n ? retryablePersistenceFailureCode(sqlState)\n : connectionOutage || rolledBack\n ? databaseFailureCode(sqlState)\n : null;\n if (\n !code ||\n (requireDatabaseProvenance &&\n !connectionOutage &&\n !rolledBack &&\n !(sqlState === null && hasOwnTransport(node)))\n )\n return null;\n if (!requireDatabaseProvenance || ownDatabaseNodes.has(node)) codes.add(code);\n }\n // Preserve the legacy pre-execution transport-only allowance, but never\n // borrow it across an explicit DB boundary with no eligible own evidence.\n if (!requireDatabaseProvenance && boundaries.size === 0 && transports.size > 0)\n codes.add(\"db_failure\");\n // Stable classification for multiple positive DB siblings too.\n for (const code of [\"db_failure\", \"db_deadlock\", \"db_serialization_failure\"] as const)\n if (codes.has(code)) return code;\n return null;\n } catch {\n // Unreadable structured facts are no more authority than unreadable edges.\n return null;\n }\n}\n\nconst RUNNING_TURN_DATABASE_TRANSPORT_CODES = new Set([\n // postgres.js reports these for a physically lost connection, including\n // transaction cleanup after its socket has already closed. Own-client\n // provenance and the unknown-outcome veto remain mandatory above.\n \"CONNECTION_CLOSED\",\n \"CONNECTION_DESTROYED\",\n \"CONNECTION_ENDED\",\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"CONNECT_TIMEOUT\",\n]);\n\nfunction isRunningTurnDatabaseTransportFailure(record: Record<string, unknown>): boolean {\n return [record.code, record.errno].some(\n (code) => typeof code === \"string\" && RUNNING_TURN_DATABASE_TRANSPORT_CODES.has(code),\n );\n}\n\nfunction isRunningTurnDatabaseConnectionSqlState(sqlState: string | null): boolean {\n return (\n sqlState !== null &&\n (/^08[0-9A-Z]{3}$/.test(sqlState) || [\"57P01\", \"57P02\", \"57P03\"].includes(sqlState))\n );\n}\n\nfunction isDatabaseConnectionSqlState(sqlState: string | null): boolean {\n return (\n sqlState !== null &&\n (sqlState.startsWith(\"08\") || [\"57P01\", \"57P02\", \"57P03\"].includes(sqlState))\n );\n}\n\nfunction retryablePersistenceFailureCode(\n sqlState: string | null,\n): PostClaimDatabaseRecoveryDetail[\"code\"] | null {\n if (\n !(\n sqlState === null ||\n sqlState.startsWith(\"08\") ||\n isRetryablePersistenceSqlState(sqlState) ||\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 databaseFailureCode(sqlState);\n}\n\n/**\n * True when an error is a structured database failure that the exact-attempt\n * database recovery path owns. Callers that translate other failures into\n * user-visible states must rethrow these unchanged.\n */\nexport function isPostClaimDatabaseRecoveryCandidate(error: unknown): boolean {\n return retryableDatabaseFailureCode(error, true) !== null;\n}\n\n/**\n * Carry one exact claimed attempt into the workflow's DB-only\n * recovery lane. Permanent database/state failures remain terminal. The\n * running-turn lane additionally requires a closed own-client outage class;\n * existing pre-execution recovery classifications are unchanged.\n */\nexport function postClaimDatabaseRecoveryFailure(input: {\n error: unknown;\n turnId: string;\n triggerEventId: string;\n executionGeneration: number;\n /** Require an actual own-client boundary and the closed running-turn allowlist. */\n requireDatabaseProvenance?: boolean;\n sandboxSetupOutcomeUnknown?: true;\n sandboxSetupRecoveryExhausted?: true;\n providerRecovery?: {\n failureCode: string;\n providerRecoveryCount: number;\n continueDelayMs?: number;\n };\n}): ApplicationFailure | null {\n const code = retryableDatabaseFailureCode(input.error, input.requireDatabaseProvenance);\n if (!code || input.executionGeneration < 1) return null;\n if (\n (input.sandboxSetupOutcomeUnknown && input.sandboxSetupRecoveryExhausted) ||\n ((input.sandboxSetupOutcomeUnknown || input.sandboxSetupRecoveryExhausted) &&\n input.providerRecovery)\n ) {\n return null;\n }\n if (\n input.providerRecovery &&\n (!Number.isSafeInteger(input.providerRecovery.providerRecoveryCount) ||\n input.providerRecovery.providerRecoveryCount <= 0 ||\n input.providerRecovery.providerRecoveryCount >\n providerRecoveryLimit(input.providerRecovery.failureCode) ||\n !/^[a-z][a-z0-9_]{0,63}$/.test(input.providerRecovery.failureCode) ||\n !validProviderOverloadRecoveryDelay(\n input.providerRecovery.failureCode,\n input.providerRecovery.continueDelayMs,\n ))\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.sandboxSetupRecoveryExhausted ? { sandboxSetupRecoveryExhausted: true } : {}),\n ...(input.providerRecovery\n ? {\n providerFailureCode: input.providerRecovery.failureCode,\n providerRecoveryCount: input.providerRecovery.providerRecoveryCount,\n ...(input.providerRecovery.continueDelayMs !== undefined\n ? { providerRecoveryContinueDelayMs: input.providerRecovery.continueDelayMs }\n : {}),\n }\n : {}),\n };\n // Known usage whose receipt write failed travels with the exact attempt.\n const sessionUsageReceipts = heldSessionUsageReceiptsForTurn(input.turnId);\n if (sessionUsageReceipts.length > 0) detail.sessionUsageReceipts = sessionUsageReceipts;\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\nexport function modelPreparationFailureEventPayload(error: unknown, durationMs: number) {\n const transition = sandboxLifecycleTransitionDiagnostic(error);\n return {\n phase: \"model_preparation\",\n durationMs: Math.max(0, Math.round(durationMs)),\n expectedTransition: transition !== null,\n ...(transition\n ? {\n failureCategory: \"drain_capture_wait\",\n failureStage: \"lifecycle_wait\",\n failureCode: transition.reason,\n retryable: true,\n }\n : {}),\n };\n}\n\n/**\n * The turn's first model request could not be dispatched until the context\n * was compacted (proactive threshold or an operator-requested Compact). That\n * is an expected step of preparation, not a failure: the same activity\n * compacts and then reopens preparation for the retried request.\n */\nexport function compactionFirstPreparationEventPayload(durationMs: number) {\n return {\n phase: \"model_preparation\",\n durationMs: Math.max(0, Math.round(durationMs)),\n expectedTransition: true,\n failureCategory: \"context_compaction\",\n failureStage: \"context_compaction\",\n failureCode: \"compaction_required\",\n retryable: true,\n } as const;\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 */\n/**\n * Only the home resolver's positive pre-dispatch signal permits a fresh attempt.\n * The same error class can also escape AFTER a provider mutation, so neither its\n * retryable property nor message alone establishes replay safety. Inspect the\n * complete bounded SDK cause graph and let uncertain peer outcomes veto this\n * narrow recovery; unreadable or overflowing graphs fail closed.\n */\nfunction isPreDispatchHomeBackendRecoveryRequired(error: unknown): boolean {\n const graph = structuredRecoveryCauseGraph(error);\n if (!graph) return false;\n let found = false;\n try {\n for (const node of graph.keys()) {\n if (\n isRoutingMutationOutcomeUnknownError(node) ||\n isRoutingMutationOutputRejectedError(node) ||\n isRawProviderCommandOutcomeUnknown(node) ||\n isModalCommandStartOutcomeUnknownError(node) ||\n isProviderCommandObservationUnavailableError(node)\n )\n return false;\n if (node instanceof RoutingBackendRecoveryRequiredError) {\n if (\n node.op !== \"resolve_home_backend\" ||\n !Number.isSafeInteger(node.leaseEpoch) ||\n node.leaseEpoch < 0 ||\n !node.retryable ||\n (node.recovery !== \"pending\" && node.recovery !== \"superseded\")\n )\n return false;\n found = true;\n }\n }\n } catch {\n return false;\n }\n return found;\n}\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 | \"home_backend_recovery_pending\"\n | null {\n if (isPreDispatchHomeBackendRecoveryRequired(error)) {\n return \"home_backend_recovery_pending\";\n }\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 // The worker's own included-usage refusal (usage exhausted or unverifiable)\n // happens before dispatch, so the checkpoint request was never sent. It\n // settles exactly like the same refusal on an ordinary request: recorded\n // against the account, then the same turn re-places or waits for capacity.\n if (findCodexCreditPolicyError(error)) return true;\n if (isCodexTransportError(error) && classifyCodexUsageLimitError(error)) return true;\n // A Claude subscription refusal (rate limit or reconnect) on the checkpoint\n // request recovers exactly like one on an ordinary request: failure\n // settlement rotates to another account or waits for capacity on the same\n // logical turn. Its wording or retry hint never makes it a terminal quota.\n const claudeRefusal = isClaudeSubscriptionTransportError(error)\n ? classifyClaudeProviderError(error)\n : null;\n if (claudeRefusal?.kind === \"unauthorized\" || claudeRefusal?.kind === \"rate_limited\") 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/** Bun's exact fetch text when an upstream drops an open connection. */\nexport const STATUSLESS_UPSTREAM_SOCKET_CLOSED_MESSAGE =\n \"the socket connection was closed unexpectedly. for more information, pass `verbose: true` in the second argument to fetch()\";\nconst STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGES = new Set([\n STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGE,\n STATUSLESS_UPSTREAM_SOCKET_CLOSED_MESSAGE,\n]);\n\nexport function isExactStatuslessUpstreamConnectivityMessage(message: string): boolean {\n return STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGES.has(message.trim().toLowerCase());\n}\n\nconst TRANSIENT_TRANSPORT_CODE = /^(?:ECONNRESET|ETIMEDOUT|EAI_AGAIN|ECONNREFUSED|EPIPE)$/i;\n\n/**\n * A network fault code anywhere on the Error.cause chain. SDK and runner\n * wrappers often keep the transport error only as `cause`, so the outermost\n * error's own `code` is not enough.\n */\nfunction transientTransportCode(error: unknown): string | undefined {\n let current = error;\n const seen = new Set<unknown>();\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n if (seen.has(current)) break;\n seen.add(current);\n const value = current as { code?: unknown; cause?: unknown };\n if (typeof value.code === \"string\" && TRANSIENT_TRANSPORT_CODE.test(value.code)) {\n return value.code;\n }\n current = value.cause;\n }\n return undefined;\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|misalignment_policy_violation)$/.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\n/** Preserve the closest real HTTP status through SDK Error.cause wrappers. */\nfunction providerHttpStatus(error: unknown): number | undefined {\n let current = error;\n const seen = new Set<unknown>();\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n if (seen.has(current)) break;\n seen.add(current);\n const value = current as { status?: unknown; statusCode?: unknown; cause?: unknown };\n const status = Number(value.status ?? value.statusCode);\n if (Number.isInteger(status) && status >= 100 && status < 600) return status;\n current = value.cause;\n }\n return undefined;\n}\n\n/**\n * A fetch-layer timeout: the runtime's DOMException `TimeoutError` (message\n * \"The operation timed out.\"), possibly wrapped by SDK/runner `cause` chains.\n * Explicit cancellation (`AbortError`) is deliberately not matched.\n */\nexport function isTransportTimeoutError(error: unknown): boolean {\n let current: unknown = error;\n const seen = new Set<unknown>();\n for (let depth = 0; depth < 8 && current && typeof current === \"object\"; depth += 1) {\n if (seen.has(current)) break;\n seen.add(current);\n const value = current as { name?: unknown; message?: unknown; cause?: unknown };\n if (value.name === \"TimeoutError\" || value.message === \"The operation timed out.\") {\n return true;\n }\n current = value.cause;\n }\n return false;\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 = providerHttpStatus(error);\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 if (transientTransportCode(error)) return true;\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, SuperGrok or Claude subscription transport error never\n * classifies here.\n */\nexport function classifyProviderQuotaExhaustionError(\n error: unknown,\n): ProviderQuotaExhaustion | null {\n if (\n isCodexTransportError(error) ||\n isXaiSubscriptionTransportError(error) ||\n isClaudeSubscriptionTransportError(error)\n )\n return null;\n // The same reader the OpenAI SDK retry veto uses, so the two never disagree.\n return classifyProviderQuotaError(error);\n}\n\n/** A refusal raised by a Claude subscription (OAuth) transport, at any wrapper depth. */\nexport function isClaudeSubscriptionTransportError(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; depth < 6 && current instanceof Error; depth++) {\n if (current instanceof AnthropicRequestError && current.subscription) return true;\n current = current.cause;\n }\n return false;\n}\n\n/**\n * SuperGrok's classification of a failed model request as a shared provider\n * outcome (the adapter's `classifyError`, SuperGrok track X1b): a refresh\n * relogin or a marked 401 is `unauthorized`, a marked 403 `forbidden`, and a\n * marked 429 or HTTP 200 SSE capacity terminal `rate_limited` with the\n * provider's retry time (null when it gave none: the adapter's fallback\n * applies). Anything else, a provider safety refusal included, is null: not\n * a refusal of the account.\n */\nexport function classifyXaiProviderError(error: unknown): ProviderErrorOutcome | 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: \"unauthorized\" };\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: \"unauthorized\" };\n }\n if (status === 403) {\n return { kind: \"forbidden\" };\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 { kind: \"rate_limited\", retryAfterMs: providerRetryAfterMs(error) };\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\nfunction anthropicRequestDiagnostic(error: unknown): AnthropicRequestError | undefined {\n if (error instanceof AnthropicRequestError) return error;\n return error instanceof Error && error.cause instanceof AnthropicRequestError\n ? error.cause\n : undefined;\n}\n\nfunction isRawProviderCommandOutcomeUnknown(error: unknown): boolean {\n try {\n return (\n error instanceof ProviderCommandInputOutcomeUnknownError ||\n error instanceof ProviderCommandStartOutcomeUnknownError\n );\n } catch {\n return false;\n }\n}\n\nexport function agentRunFailurePayload(\n error: unknown,\n options: { isCodexTurn?: boolean } = {},\n): ReturnType<typeof baseAgentRunFailurePayload> {\n return withProviderCondition(error, classifyAgentRunFailurePayload(error, options));\n}\n\n/**\n * Record the closed provider condition on a retryable model-provider failure so\n * clients can say \"overloaded\" rather than a generic outage. Presentation\n * evidence only: retry authority and pacing are decided by `code`.\n */\nfunction withProviderCondition(\n error: unknown,\n failure: ReturnType<typeof baseAgentRunFailurePayload>,\n): ReturnType<typeof baseAgentRunFailurePayload> {\n if (failure.code === \"provider_rate_limited\") {\n return { ...failure, providerCondition: \"rate_limited\" };\n }\n if (failure.code !== \"provider_unavailable\") return failure;\n if (failure.timeoutClass) return { ...failure, providerCondition: \"unresponsive\" };\n return {\n ...failure,\n providerCondition: isProviderOverloadError(error, failure) ? \"overloaded\" : \"unavailable\",\n };\n}\n\n/** HTTP 529, Anthropic `overloaded_error`, or explicit provider \"overloaded\" wording. */\nexport function isProviderOverloadError(\n error: unknown,\n failure: { error?: string; detail?: string } = {},\n): boolean {\n if (providerHttpStatus(error) === 529) return true;\n const anthropic = anthropicRequestDiagnostic(error);\n return [...collectErrorStrings(error), anthropic?.detail, failure.error, failure.detail].some(\n (value) => typeof value === \"string\" && /\\boverload(?:ed)?(?:_error)?\\b/i.test(value),\n );\n}\n\n/** Retry authority must not depend on the looser presentation-only overload label. */\nexport function providerRecoveryCode(\n error: unknown,\n failure: { code?: string; retryable?: boolean },\n): string | undefined {\n if (failure.code !== \"provider_unavailable\" || !failure.retryable) return failure.code;\n const status = providerHttpStatus(error);\n let current = error;\n const seen = new Set<unknown>();\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n if (seen.has(current)) break;\n seen.add(current);\n if (\n current instanceof AnthropicRequestError &&\n status !== undefined &&\n status >= 500 &&\n status < 600 &&\n (status === 529 || current.errorType === \"overloaded_error\")\n ) {\n return PROVIDER_OVERLOAD_RECOVERY_CODE;\n }\n current = (current as { cause?: unknown }).cause;\n }\n return failure.code;\n}\n\nfunction classifyAgentRunFailurePayload(\n error: unknown,\n options: { isCodexTurn?: boolean } = {},\n): ReturnType<typeof baseAgentRunFailurePayload> {\n const sizeError = findAnthropicRequestSizeError(error);\n if (sizeError)\n return {\n error: sizeError.message,\n code: sizeError.code,\n retryable: false,\n requestSize: sizeError.requestSize,\n ...(sizeError.request_id ? { requestId: sizeError.request_id } : {}),\n };\n const graph = structuredRecoveryCauseGraph(error);\n const nodes = graph ? [...graph.keys()] : [];\n const outputRejected = nodes.find(isRoutingMutationOutputRejectedError);\n if (outputRejected) {\n // A known receipt applies only to its own mutation. Uncertain peers retain\n // their established terminal classification, regardless of SDK graph order.\n const unknown = nodes.find(\n (node) =>\n isRoutingMutationOutcomeUnknownError(node) ||\n isModalCommandStartOutcomeUnknownError(node) ||\n isProviderCommandObservationUnavailableError(node) ||\n isRawProviderCommandOutcomeUnknown(node),\n );\n if (unknown) return { ...baseAgentRunFailurePayload(unknown, options), retryable: false };\n return {\n error: outputRejected.message,\n code: outputRejected.code,\n retryable: false,\n };\n }\n const expired = nodes.find((node) => node instanceof ProviderOverloadRecoveryExpiredError);\n if (expired instanceof ProviderOverloadRecoveryExpiredError) return expired.failure;\n const failure = baseAgentRunFailurePayload(error, options);\n const diagnostic = materializationVerificationDiagnostic(error);\n const anthropic = anthropicRequestDiagnostic(error);\n if (anthropic) {\n const authenticationRejected =\n anthropic.status === 401 &&\n (error === anthropic ||\n (error instanceof Error && (error as Error & { status?: unknown }).status === 401));\n return {\n ...failure,\n code:\n failure.code ??\n (authenticationRejected ? \"anthropic_authentication_error\" : anthropic.code),\n retryable: failure.retryable ?? false,\n ...(anthropic.detail ? { detail: anthropic.detail } : {}),\n ...(anthropic.request_id ? { requestId: anthropic.request_id } : {}),\n };\n }\n return diagnostic ? { ...failure, materializationDiagnostic: diagnostic } : failure;\n}\n\n/** Keep Anthropic provider text on terminal failures, never recovery events. */\nexport function agentRunRecoveryFailurePayload(\n error: unknown,\n failure: ReturnType<typeof agentRunFailurePayload>,\n): ReturnType<typeof agentRunFailurePayload> {\n if (!anthropicRequestDiagnostic(error)) return failure;\n // Project a copy: retry exhaustion still needs the terminal diagnostic.\n const recovery = { ...failure };\n delete recovery.detail;\n return recovery;\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 requestSize?: AnthropicRequestSize;\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` or model-provider recovery failure refers to. */\n model?: string | null;\n /** Display label of the turn's model on model-provider recovery evidence. */\n modelLabel?: string;\n /** Display label of the serving provider on model-provider recovery evidence. */\n providerLabel?: string;\n /** Closed transient provider condition on `provider_unavailable` / `provider_rate_limited`. */\n providerCondition?: ProviderCondition;\n recoveryExhausted?: boolean;\n providerRecoveryCount?: number;\n maxProviderRecoveryCount?: number;\n providerRecoveryExhaustedReason?: \"deadline\" | \"retry_limit\" | \"invalid_clock\";\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 (findRetainedAttachmentUnavailableError(error)) {\n // Storage may lag after a replica outage. The same turn retries with the\n // connectivity backoff and never continues without the image's pixels.\n return {\n error:\n \"An image attached earlier in this conversation can't be read from storage right now. The same turn will retry after a short delay.\",\n code: RETAINED_ATTACHMENT_UNAVAILABLE_CODE,\n retryable: true,\n };\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 if (error instanceof AnthropicSizeRecoveryExhaustedError) {\n return { error: error.message, code: error.code, retryable: false };\n }\n if (error instanceof AnthropicProviderRejection) {\n return {\n error: error.message,\n code: error.code === \"content_policy_violation\" ? \"provider_safety_refusal\" : error.code,\n retryable: false,\n ...(error.request_id ? { requestId: error.request_id } : {}),\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 = providerHttpStatus(error);\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 (isProviderCommandObservationUnavailableError(error)) {\n return {\n error:\n \"A managed sandbox command cannot be observed. Its exact invocation and writer remain retained; setup is blocked without replay until the incomplete operation can be reconciled.\",\n code: \"sandbox_command_observation_unavailable\",\n retryable: false,\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 // Shared subscription core placement outcomes carry their own typed copy.\n if (error instanceof SubscriptionCoreCodexTurnError) {\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 creditPolicy = findCodexCreditPolicyError(error);\n if (creditPolicy) {\n return { error: creditPolicy.message, code: creditPolicy.code, retryable: false };\n }\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 // A generic model stream that went silent mid-response (typed idle bound) or\n // a transport timeout (\"The operation timed out.\" DOMException TimeoutError\n // from the fetch layer) is a dead upstream connection, not a request fault:\n // checkpoint durable truth and recover the same turn within the finite\n // provider recovery budget. Codex/SuperGrok typed timeouts are classified\n // above under their own transport policy.\n const streamIdle = classifyModelStreamIdleTimeoutError(error);\n if (streamIdle) {\n const seconds =\n streamIdle.idleTimeoutMs !== null ? Math.round(streamIdle.idleTimeoutMs / 1_000) : null;\n const window = seconds !== null ? ` for ${seconds}s` : \"\";\n return {\n error:\n streamIdle.kind === \"progress\"\n ? `The model provider stream stalled: only keepalive traffic and no response progress${window}. The same turn will retry after a short delay.`\n : `The model provider stopped sending response data${window}. The same turn will retry after a short delay.`,\n code: \"provider_unavailable\",\n retryable: true,\n timeoutClass: streamIdle.kind === \"progress\" ? \"progress_stream\" : \"idle_stream\",\n responseObserved: true,\n detail: streamIdle.message,\n };\n }\n if (status === undefined && isTransportTimeoutError(error)) {\n return {\n error:\n \"The model provider connection timed out. The same turn will retry after a short delay.\",\n code: \"provider_unavailable\",\n retryable: true,\n timeoutClass: \"transport\",\n detail: message,\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 if (status === 402 && code === \"anthropic_billing_error\") {\n return {\n error: \"Claude could not bill this request. Check the account's billing and payment details.\",\n code: \"provider_billing_error\",\n retryable: false,\n ...(message ? { detail: message } : {}),\n };\n }\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 ((status === undefined || !Number.isFinite(status)) &&\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 origin?: \"included_usage_policy\" | \"usage_verification_policy\";\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 const creditPolicy = findCodexCreditPolicyError(error);\n if (creditPolicy instanceof CodexIncludedUsageUnknownError) {\n // Verified pre-dispatch refusal. A short hard hold cannot authorize credit\n // fallback and does not claim that the provider exhausted its allowance.\n return { kind: \"rate_limit\", cooldownSeconds: 60, origin: \"usage_verification_policy\" };\n }\n if (creditPolicy instanceof CodexIncludedUsageExhaustedError) {\n return {\n kind: \"quota\",\n cooldownSeconds: creditPolicy.resetsInSeconds,\n origin: \"included_usage_policy\",\n };\n }\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\n/**\n * Claude's classification of a failed model request as a shared provider\n * outcome (the adapter's `classifyError`, Claude track C1b), for a request\n * of the Claude subscription transport only: a reconnect-required refresh or\n * HTTP 401 is `unauthorized` (the transport already ran the turn's one\n * forced refresh); 429 is `rate_limited` for the turn's model `modelId`, with\n * the provider's retry time (null: the adapter's fallback applies); 529 or\n * `overloaded_error` is `overloaded`, which never moves the turn to another\n * account; 403 is `fatal`, which never rotates or quarantines the account.\n * Anything else, a provider safety refusal included, is null: not a refusal\n * of the account.\n */\nexport function classifyClaudeProviderError(\n error: unknown,\n modelId?: string,\n): ProviderErrorOutcome | null {\n if (isProviderSafetyRefusal(error)) return null;\n let current: unknown = error;\n for (let depth = 0; depth < 6 && current instanceof Error; depth++) {\n if (current instanceof ClaudeSubscriptionReconnectRequired) return { kind: \"unauthorized\" };\n if (current instanceof AnthropicRequestError) {\n if (!current.subscription) return null;\n if (current.status === 401) return { kind: \"unauthorized\" };\n if (current.status === 429)\n return {\n kind: \"rate_limited\",\n retryAfterMs: providerRetryAfterMs(current),\n ...(modelId === undefined ? {} : { modelId }),\n };\n if (current.status === 529 || current.errorType === \"overloaded_error\")\n return { kind: \"overloaded\" };\n if (current.status === 403) return { kind: \"fatal\" };\n return null;\n }\n current = current.cause;\n }\n return null;\n}\n","export const entityKind = Symbol.for('drizzle:entityKind');\nexport const hasOwnEntityKind = Symbol.for('drizzle:hasOwnEntityKind');\n\nexport interface DrizzleEntity {\n\t[entityKind]: string;\n}\n\nexport type DrizzleEntityClass<T> =\n\t& ((abstract new(...args: any[]) => T) | (new(...args: any[]) => T))\n\t& DrizzleEntity;\n\nexport function is<T extends DrizzleEntityClass<any>>(value: any, type: T): value is InstanceType<T> {\n\tif (!value || typeof value !== 'object') {\n\t\treturn false;\n\t}\n\n\tif (value instanceof type) { // eslint-disable-line no-instanceof/no-instanceof\n\t\treturn true;\n\t}\n\n\tif (!Object.prototype.hasOwnProperty.call(type, entityKind)) {\n\t\tthrow new Error(\n\t\t\t`Class \"${\n\t\t\t\ttype.name ?? '<unknown>'\n\t\t\t}\" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`,\n\t\t);\n\t}\n\n\tlet cls = Object.getPrototypeOf(value).constructor;\n\tif (cls) {\n\t\t// Traverse the prototype chain to find the entityKind\n\t\twhile (cls) {\n\t\t\tif (entityKind in cls && cls[entityKind] === type[entityKind]) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tcls = Object.getPrototypeOf(cls);\n\t\t}\n\t}\n\n\treturn false;\n}\n","import { entityKind } from '~/entity.ts';\n\nexport class DrizzleError extends Error {\n\tstatic readonly [entityKind]: string = 'DrizzleError';\n\n\tconstructor({ message, cause }: { message?: string; cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = 'DrizzleError';\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class DrizzleQueryError extends Error {\n\tconstructor(\n\t\tpublic query: string,\n\t\tpublic params: any[],\n\t\tpublic override cause?: Error,\n\t) {\n\t\tsuper(`Failed query: ${query}\\nparams: ${params}`);\n\t\tError.captureStackTrace(this, DrizzleQueryError);\n\n\t\t// ES2022+: preserves original error on `.cause`\n\t\tif (cause) (this as any).cause = cause;\n\t}\n}\n\nexport class TransactionRollbackError extends DrizzleError {\n\tstatic override readonly [entityKind]: string = 'TransactionRollbackError';\n\n\tconstructor() {\n\t\tsuper({ message: 'Rollback' });\n\t}\n}\n","/** A provider-reported usage percentage at or above this value is exhausted. */\nexport const CODEX_USAGE_EXHAUSTED_PCT = 100;\n","import {\n MODEL_ATTACHMENT_REFS_FIELD,\n MODEL_ATTACHMENT_CATALOG_MARKER,\n MODEL_ATTACHMENT_CATALOG_RENDERED_FIELD,\n MODEL_ATTACHMENT_IMAGE_MAX_DIMENSION_FIELD,\n FileResourceRef,\n resourceMountPath,\n readTurnExecutionPolicyV1,\n readTurnServingPolicyV1,\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 readSubscriptionHistoryProvenance,\n type Database,\n} from \"@opengeni/db\";\nimport {\n createModelImageSizer,\n projectHistoryForProvider,\n projectRejectedProviderArtifactsFromSerializedRunState,\n projectRejectedReasoningArtifact,\n hasOpaqueProviderArtifact,\n type HistoryProviderApi,\n type OpenGeniRuntime,\n} from \"@opengeni/runtime\";\nimport { requesterUnavailableReceiptText } from \"./requester-unavailable-receipt\";\n\n/** D-37 request-copy projection. C1 is deliberately not wired into turnInput;\n * C2 must supply scoped turn metadata and the D-43 deployment gate. The API\n * alone cannot establish provenance: different providers may share a wire API.\n */\nexport function projectServingProviderArtifacts(\n rows: ReadonlyArray<{\n item: Record<string, unknown>;\n turnId?: string | null;\n position: number;\n providerArtifactInvalidatedAt?: Date | null;\n }>,\n options: {\n enabled?: boolean;\n servingProviderId: string;\n turnMetadata: ReadonlyMap<string, unknown>;\n },\n): Array<Record<string, unknown>> {\n if (options.enabled !== true) return projectRejectedProviderArtifacts(rows);\n const providers = new Map<string, ReturnType<typeof readTurnServingPolicyV1> | null>();\n const acceptedProviders = new Map<string, string | null>();\n return rows.flatMap((row) => {\n let provider: string | null = null;\n if (row.turnId) {\n if (!providers.has(row.turnId)) {\n try {\n const metadata = options.turnMetadata.get(row.turnId);\n const accepted = readTurnExecutionPolicyV1(metadata);\n providers.set(row.turnId, readTurnServingPolicyV1(metadata));\n acceptedProviders.set(\n row.turnId,\n accepted.kind === \"valid\" ? accepted.policy.providerId : null,\n );\n } catch {\n // Unattributable legacy/fork history keeps today's projection. This\n // does not authorize executing an unreadable serving policy.\n providers.set(row.turnId, null);\n acceptedProviders.set(row.turnId, null);\n }\n }\n provider = acceptedProviders.get(row.turnId) ?? null;\n const read = providers.get(row.turnId);\n if (read?.kind === \"valid\") {\n for (const revision of read.revisions) {\n if (revision.historyPosition >= row.position) break;\n provider = revision.policy.providerId;\n }\n }\n }\n if (\n provider !== null &&\n provider !== options.servingProviderId &&\n hasOpaqueProviderArtifact(row.item)\n ) {\n if (row.item.type === \"compaction\") return [];\n return [projectRejectedReasoningArtifact(row.item)];\n }\n return projectRejectedProviderArtifacts([row]);\n });\n}\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 codemodeContinuationNote?: string;\n programmaticApprovalAcknowledged?: boolean;\n knowledgeSourcePreparationNote?: string;\n providerApi: HistoryProviderApi;\n servingProviderId?: string;\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\n/**\n * A retained image the conversation already sent could not be read from\n * object storage, for example while a storage replica catches up after an\n * outage. Its pixels are part of the accepted prompt, so the turn waits and\n * retries rather than continuing without them. Integrity mismatches are not\n * this error: retrying cannot repair different bytes.\n */\nexport class RetainedAttachmentUnavailableError extends Error {\n readonly fileIds: readonly string[];\n\n constructor(fileIds: readonly string[]) {\n super(\"An image attached earlier in this conversation can't be read from storage right now.\");\n this.name = \"RetainedAttachmentUnavailableError\";\n this.fileIds = [...fileIds];\n }\n}\n\nexport type ModelAttachmentReadFailure = \"unavailable\" | \"integrity_mismatch\";\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: {\n retainAll?: boolean;\n /** Why a selected file produced no content; omitted files are not reported. */\n onReadFailure?: (fileId: string, failure: ModelAttachmentReadFailure) => void;\n } = {},\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 options.onReadFailure?.(file.id, \"integrity_mismatch\");\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 options.onReadFailure?.(file.id, \"integrity_mismatch\");\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 options.onReadFailure?.(file.id, \"unavailable\");\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 must not rewrite old\n // 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/** Receipt for an active reference that this turn's file-authority lookup did\n * not return: another participant's file, or one that is no longer available\n * (not ready, purged, or access revoked). The lookup cannot tell these apart,\n * so the text stays neutral. The authority boundary is unchanged: no bytes and\n * no fetch instruction, which would fail and lead the model to report the file\n * as deleted. */\nfunction unavailableAttachmentReceiptText(ref: FileResourceRef): string {\n return requesterUnavailableReceiptText(`Attachment: fileId=${ref.fileId}`, \"file\");\n}\n\n/** The image bound stamped on a message when it was accepted, if any. */\nfunction attachmentImageBound(item: Record<string, unknown>): number | undefined {\n const raw = item[MODEL_ATTACHMENT_IMAGE_MAX_DIMENSION_FIELD];\n return typeof raw === \"number\" && Number.isSafeInteger(raw) && raw >= 64 && raw <= 8192\n ? raw\n : undefined;\n}\n\n// Process-wide, so a long conversation does not re-encode the same photos on\n// every turn. The projection depends only on the image bytes and the bound.\nconst boundedImageSizers = new Map<number, ReturnType<typeof createModelImageSizer>>();\n\ntype BoundedAttachmentImage = { image: string; note: string };\n\n/**\n * The model-facing rendition of one image under the bound its message was\n * stamped with. Smaller images keep their original bytes. The file in the\n * sandbox and in storage stays at full resolution.\n */\nasync function boundedAttachmentImage(\n attachment: ModelAttachmentContent,\n bound: number,\n): Promise<BoundedAttachmentImage> {\n const original = { image: attachment.dataUrl, note: \"\" };\n const comma = attachment.dataUrl.indexOf(\",\");\n if (comma < 0) return original;\n const data = attachment.dataUrl.slice(comma + 1);\n let sizer = boundedImageSizers.get(bound);\n if (!sizer) {\n sizer = createModelImageSizer(bound, 10 * 1024 * 1024, { jpegQuality: 85 });\n boundedImageSizers.set(bound, sizer);\n }\n try {\n const sized = await sizer(data, attachment.contentType);\n if (sized.data === data && sized.mediaType === attachment.contentType) return original;\n return {\n image: `data:${sized.mediaType};base64,${sized.data}`,\n note:\n ` Shown to you downscaled to ${sized.width}x${sized.height} from ` +\n `${sized.originalWidth}x${sized.originalHeight}; the file itself is full resolution.`,\n };\n } catch (error) {\n // Decoding is deterministic: an image that cannot be resized here keeps\n // the original projection on every turn rather than being dropped.\n console.error(\"model attachment image could not be resized; sending original\", {\n fileId: attachment.fileId,\n errorType: safeErrorType(error),\n });\n return original;\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 * Images of a message stamped with an image bound are shown downscaled to fit\n * it; unstamped (older) messages keep their full-resolution projection.\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 const boundedById = new Map<string, BoundedAttachmentImage>();\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 readFailures = new Map<string, ModelAttachmentReadFailure>();\n const content = await modelAttachmentContentForFiles(readable, readFileBytes, {\n retainAll: true,\n onReadFailure: (fileId, failure) => readFailures.set(fileId, failure),\n });\n const loadedIds = new Set(content.map((entry) => entry.fileId));\n const missing = readable.filter(\n (file) =>\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 if (missing.length > 0) {\n // Do not let a retry silently proceed with pixels removed.\n for (const candidate of readable) attemptedContentIds.delete(candidate.id);\n const corrupt = missing.find((file) => readFailures.get(file.id) === \"integrity_mismatch\");\n if (corrupt) {\n throw new Error(`Retained attachment bytes unavailable or invalid: ${corrupt.id}`);\n }\n throw new RetainedAttachmentUnavailableError(missing.map((file) => file.id));\n }\n for (const attachment of content) contentById.set(attachment.fileId, attachment);\n }\n\n for (const [index, refs] of refsByIndex) {\n const item = items[index]!;\n if (item[MODEL_ATTACHMENT_CATALOG_MARKER] === true) continue;\n const bound = attachmentImageBound(item);\n if (bound === undefined) continue;\n for (const ref of refs) {\n const attachment = fileById.has(ref.fileId) ? contentById.get(ref.fileId) : undefined;\n const key = `${bound}:${ref.fileId}`;\n if (!attachment || attachment.kind !== \"image\" || boundedById.has(key)) continue;\n boundedById.set(key, await boundedAttachmentImage(attachment, bound));\n }\n }\n\n const projected = [...items];\n for (const [index, refs] of refsByIndex) {\n const original = items[index]!;\n if (original[MODEL_ATTACHMENT_CATALOG_RENDERED_FIELD] === true) {\n // Its complete, dated text was frozen when compaction created it.\n const clone: Record<string, unknown> = { ...original };\n delete clone[MODEL_ATTACHMENT_REFS_FIELD];\n projected[index] = clone;\n continue;\n }\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 catalog = original[MODEL_ATTACHMENT_CATALOG_MARKER] === true;\n const currentFile = catalog ? undefined : fileById.get(ref.fileId);\n // Only an authority lookup that actually ran can exclude a reference.\n // Legacy callers without a resolver and compacted catalogs, which never\n // look up authority, keep the reference-only receipt.\n const excluded =\n !catalog &&\n loadAuthorizedFiles !== undefined &&\n resolvedFileIds.has(ref.fileId) &&\n currentFile === undefined;\n const attachment = currentFile ? contentById.get(ref.fileId) : undefined;\n if (!attachment || attachment.kind !== \"image\") {\n return [\n {\n type: \"input_text\",\n text: excluded ? unavailableAttachmentReceiptText(ref) : attachmentReceiptText(ref),\n },\n ];\n }\n const bound = attachmentImageBound(original);\n const bounded = bound === undefined ? undefined : boundedById.get(`${bound}:${ref.fileId}`);\n return [\n { type: \"input_text\", text: attachmentReceiptText(ref) + (bounded?.note ?? \"\") },\n { type: \"input_image\", image: bounded?.image ?? attachment.dataUrl },\n ];\n });\n const clone: Record<string, unknown> = {\n ...original,\n content: [...existingContent, ...attachmentParts],\n };\n delete clone[MODEL_ATTACHMENT_REFS_FIELD];\n projected[index] = clone;\n }\n return projected;\n };\n}\n\n/** Add current trigger refs only when older/local history predates durable stamping. */\nexport function withCurrentUserAttachmentRefs(\n historyItems: Array<Record<string, unknown>>,\n refs: FileResourceRef[],\n): Array<Record<string, unknown>> {\n if (refs.length === 0) return historyItems;\n // 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.codemodeContinuationNote,\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 && !options.programmaticApprovalAcknowledged) {\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\" | \"servingProviderId\"> = {},\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 provenance = preparationOptions.servingProviderId\n ? await readSubscriptionHistoryProvenance(\n db,\n trigger.workspaceId,\n trigger.sessionId,\n stored.map((row) => row.id),\n )\n : null;\n const active =\n provenance && preparationOptions.servingProviderId\n ? projectServingProviderArtifacts(\n stored.map((row) => ({\n ...row,\n turnId: provenance.turnByHistoryId.get(row.id) ?? null,\n })),\n {\n enabled: true,\n servingProviderId: preparationOptions.servingProviderId,\n turnMetadata: provenance.turnMetadata,\n },\n )\n : 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","/**\n * Neutral model-facing text for history media the current requester's file\n * authority excludes, for example another participant's private file in a\n * shared session. Authority exclusion and real unavailability stay\n * indistinguishable, and there is no fetch instruction that would fail and\n * lead the model to report the file as deleted.\n */\nexport function requesterUnavailableReceiptText(subject: string, noun: \"file\" | \"image\"): string {\n return (\n `[${subject}. This ${noun} is not available to the current requester: ` +\n `it may belong to another participant, or it may no longer be available. ` +\n `Its contents are not included and it cannot be downloaded in this turn; do not guess which.]`\n );\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 { CODEX_CREDENTIAL_LEASE_TTL_MS } from \"@opengeni/db\";\nimport {\n subscriptionCapacityWaitReasonText,\n subscriptionCapacityWaitNeedsAction,\n type WaitReason,\n} from \"@opengeni/subscriptions\";\n\n/*\n * Failures of a chat turn on the shared subscription core, for any provider.\n * The codes are provider-neutral; the copy names the provider, and every\n * builder defaults to Codex, so Codex callers and texts are unchanged (M3\n * shipped these as Codex failures). Other providers pass their display name.\n */\n\n/** The provider name in failure copy when a caller passes none (M3's Codex texts). */\nconst DEFAULT_DISPLAY_NAME = \"Codex\";\n\n/** Typed, user-readable failure for a turn on the shared subscription core. */\nexport type SubscriptionCoreCodexFailurePayload = {\n error: string;\n code:\n | \"subscription_capacity_unavailable\"\n | \"subscription_lease_busy\"\n | \"subscription_core_unsupported\"\n | \"subscription_core_cutover_disabled\"\n | \"subscription_account_refused\"\n | \"subscription_failover_exhausted\";\n retryable: boolean;\n detail?: string;\n /** Placement wait reason when `code` is `subscription_capacity_unavailable`. */\n waitReason?: WaitReason;\n /** Refusal class when `code` is `subscription_account_refused`. */\n refusal?: SubscriptionCoreAccountRefusal;\n /** ISO time the earliest known capacity returns, when placement knows it. */\n resetsAt?: string;\n /**\n * Refusals this turn took, and the per-turn refusal bound, when `code` is\n * `subscription_failover_exhausted` (refusals, not switches: the turn\n * switched accounts `maxRefusals - 1` times before the last refusal).\n */\n refusals?: number;\n maxRefusals?: number;\n /** Combined model/provider changes and refusals, not a refusal count. */\n failoverSteps?: number;\n maxFailoverSteps?: number;\n};\n\n/** The provider-neutral name of the core turn failure payload. */\nexport type SubscriptionCoreFailurePayload = SubscriptionCoreCodexFailurePayload;\n\n/** A typed core turn failure (the class keeps its M3 name; it serves every provider). */\nexport class SubscriptionCoreCodexTurnError extends Error {\n readonly code: SubscriptionCoreCodexFailurePayload[\"code\"];\n /**\n * The provider name its copy used. In-process only, never part of the\n * payload, so a follow-up failure for the same turn (an exhausted lease-busy\n * chain) names the same provider without the settlement naming providers.\n */\n readonly displayName: string;\n constructor(\n readonly payload: SubscriptionCoreCodexFailurePayload,\n displayName: string = DEFAULT_DISPLAY_NAME,\n ) {\n super(payload.error);\n this.name = \"SubscriptionCoreCodexTurnError\";\n this.code = payload.code;\n this.displayName = displayName;\n }\n}\n\nconst WAIT_COPY = (name: string): Record<WaitReason, string> => ({\n pinned_account_disabled: `The ${name} account pinned to this chat is turned off. Turn it back on, choose another account, or switch the chat to automatic. Waiting alone will not fix this.`,\n pinned_account_unavailable: `The ${name} account chosen for this session is unavailable right now. Send a new message once it is available again, or switch the session back to automatic.`,\n pinned_account_ineligible: `The ${name} account chosen for this session can no longer serve this work. Choose another account or switch the session back to automatic.`,\n no_eligible_capacity: `No ${name} subscription has capacity for this turn right now. Send a new message once an account is available again.`,\n model_not_allowed: `This model is not allowed for the ${name} subscriptions available here.`,\n compaction_provider_locked:\n \"This session is tied to a provider that has no capacity right now. Send a new message once an account is available again.\",\n accepted_authority_unavailable:\n \"This work was accepted before the account move and its account access could not be carried. Send it again.\",\n});\n\n/**\n * The `codex.capacity.waiting` payload for a turn parked on a core waiter\n * (M3 PR 2a): the legacy event shape with the core wait reason and the\n * earliest known reset.\n */\nexport function subscriptionCoreCapacityWaitPayload(\n reason: WaitReason,\n earliestResetAt: Date | null,\n displayName: string = DEFAULT_DISPLAY_NAME,\n): Record<string, unknown> {\n return {\n error: subscriptionCapacityWaitReasonText(reason, displayName),\n code: \"subscription_capacity_unavailable\",\n waitReason: reason,\n ...(subscriptionCapacityWaitNeedsAction(reason) ? { actionRequired: true } : {}),\n ...(earliestResetAt ? { resetsAt: earliestResetAt.toISOString() } : {}),\n };\n}\n\n/** The per-turn failover bound was reached; the session stays usable. */\nexport function subscriptionCoreFailoverExhaustedFailure(\n refusals: number,\n maxRefusals: number,\n displayName: string = DEFAULT_DISPLAY_NAME,\n): SubscriptionCoreCodexTurnError {\n return new SubscriptionCoreCodexTurnError(\n {\n error: `${displayName} accounts refused this turn too many times in a row. Send a new message after checking the accounts' health or capacity.`,\n code: \"subscription_failover_exhausted\",\n retryable: false,\n refusals,\n maxRefusals,\n },\n displayName,\n );\n}\n\nexport function subscriptionCoreServingFailoverExhaustedFailure(\n steps: number,\n limit: number,\n): SubscriptionCoreCodexTurnError {\n return new SubscriptionCoreCodexTurnError(\n {\n error:\n \"Model accounts reached this turn's failover limit. Send a new message after checking the accounts' health or capacity.\",\n code: \"subscription_failover_exhausted\",\n retryable: false,\n failoverSteps: steps,\n maxFailoverSteps: limit,\n },\n \"Model account\",\n );\n}\n\n/**\n * The capacity wait the core decided, as a typed terminal failure. PR 2a\n * parks waits on a durable core waiter instead; this remains for callers that\n * cannot wait.\n */\nexport function subscriptionCoreCapacityFailure(\n reason: WaitReason,\n earliestResetAt: Date | null,\n displayName: string = DEFAULT_DISPLAY_NAME,\n): SubscriptionCoreCodexTurnError {\n return new SubscriptionCoreCodexTurnError(\n {\n error: WAIT_COPY(displayName)[reason],\n code: \"subscription_capacity_unavailable\",\n retryable: false,\n waitReason: reason,\n ...(earliestResetAt ? { resetsAt: earliestResetAt.toISOString() } : {}),\n },\n displayName,\n );\n}\n\n/**\n * An older attempt of this same turn still holds its lease until expiry, or\n * (`binding_conflict`) the session's account changed while this placement\n * was deciding. Both retry the same way; only the copy differs.\n */\nexport function subscriptionCoreLeaseBusyFailure(\n leasedUntil: Date | null,\n cause?: \"binding_conflict\",\n displayName: string = DEFAULT_DISPLAY_NAME,\n): SubscriptionCoreCodexTurnError {\n return new SubscriptionCoreCodexTurnError(\n {\n error:\n cause === \"binding_conflict\"\n ? `The session's ${displayName} account changed while this turn was starting. The turn will retry.`\n : `A previous attempt of this turn still holds its ${displayName} account. The turn will retry once that hold ends.`,\n code: \"subscription_lease_busy\",\n retryable: true,\n ...(leasedUntil ? { resetsAt: leasedUntil.toISOString() } : {}),\n },\n displayName,\n );\n}\n\n/** Most extra delay added after the older lease's expiry, so retries spread out. */\nexport const SUBSCRIPTION_CORE_LEASE_BUSY_JITTER_MS = 5_000;\n\n/**\n * When a redispatched attempt should retry after finding an older attempt's\n * live lease: just after that lease expires (plus jitter), never later than\n * one lease TTL, and never sooner than one second.\n */\nexport function subscriptionCoreLeaseBusyDelayMs(\n resetsAt: string | undefined,\n now: number,\n jitterSample: number,\n ttlMs: number = CODEX_CREDENTIAL_LEASE_TTL_MS,\n): number {\n const until = resetsAt ? Date.parse(resetsAt) : Number.NaN;\n const remaining = Number.isFinite(until) ? Math.min(Math.max(until - now, 0), ttlMs) : ttlMs;\n const jitter = Math.min(Math.max(jitterSample, 0), 1) * SUBSCRIPTION_CORE_LEASE_BUSY_JITTER_MS;\n return Math.max(1_000, Math.ceil(remaining + jitter));\n}\n\n/**\n * How long one turn may keep finding an older attempt's live lease: about\n * three lease TTLs of wall-clock time since the first such recovery. Lease\n * renewal is not fenced on the turn's current attempt, so a superseded attempt\n * that keeps heartbeating would otherwise hold the turn forever.\n */\nexport const SUBSCRIPTION_CORE_LEASE_BUSY_MAX_MS = 3 * CODEX_CREDENTIAL_LEASE_TTL_MS;\n\n/**\n * The consecutive lease-busy chain after this attempt: it continues only when\n * the immediately previous execution generation recorded it. A stored start\n * in the future (clock skew or a bad write) is clamped to now so it can never\n * disable the bound.\n */\nexport function subscriptionCoreLeaseBusyChain(\n stored: { startedAt: number; executionGeneration: number } | undefined,\n executionGeneration: number,\n now: number,\n): { startedAt: number; executionGeneration: number; exhausted: boolean } {\n const startedAt =\n stored && stored.executionGeneration === executionGeneration - 1\n ? Math.min(stored.startedAt, now)\n : now;\n return {\n startedAt,\n executionGeneration,\n exhausted: now - startedAt >= SUBSCRIPTION_CORE_LEASE_BUSY_MAX_MS,\n };\n}\n\n/** The lease-busy chain lasted too long: stop with readable copy. */\nexport function subscriptionCoreLeaseBusyExhaustedFailure(\n displayName: string = DEFAULT_DISPLAY_NAME,\n): SubscriptionCoreCodexTurnError {\n return new SubscriptionCoreCodexTurnError(\n {\n error: `A previous attempt of this turn kept holding its ${displayName} account, so the turn stopped. Send a new message to try again.`,\n code: \"subscription_lease_busy\",\n retryable: false,\n },\n displayName,\n );\n}\n\nexport type SubscriptionCoreAccountRefusal =\n | \"sign_in\"\n | \"forbidden\"\n | \"entitlement\"\n | \"access_lost\";\n\nconst REFUSAL_COPY = (name: string): Record<SubscriptionCoreAccountRefusal, string> => ({\n sign_in: `The ${name} account serving this session needs a new sign-in. Reconnect it or choose another account, then send a new message.`,\n forbidden: `The ${name} account serving this session refused this request. Check the account's access or choose another account, then send a new message.`,\n entitlement: `The ${name} account serving this session cannot use this model on its current plan. Choose another model or account, then send a new message.`,\n access_lost: `This session lost access to the ${name} account it was running on. Send a new message to continue on an account it can use.`,\n});\n\n/**\n * A definitive refusal from the leased account (revoked sign-in, 403, or a\n * plan that does not include the model). Health and quarantine of the\n * connection arrive with PR 2; until then the turn stops with readable copy\n * and the session stays usable.\n */\nexport function subscriptionCoreAccountRefusedFailure(\n refusal: SubscriptionCoreAccountRefusal,\n displayName: string = DEFAULT_DISPLAY_NAME,\n): SubscriptionCoreCodexTurnError {\n return new SubscriptionCoreCodexTurnError(\n {\n error: REFUSAL_COPY(displayName)[refusal],\n code: \"subscription_account_refused\",\n retryable: false,\n refusal,\n },\n displayName,\n );\n}\n\n/** A Codex consumer that has not moved to the core yet (PR 2) must not read legacy tables. */\nexport function subscriptionCoreUnsupportedFailure(\n consumer: string,\n displayName: string = DEFAULT_DISPLAY_NAME,\n): SubscriptionCoreCodexTurnError {\n return new SubscriptionCoreCodexTurnError(\n {\n error: `${consumer} is not available for ${displayName} subscriptions on this deployment yet.`,\n code: \"subscription_core_unsupported\",\n retryable: false,\n },\n displayName,\n );\n}\n\n/** The organization's cutover row for the provider exists but is switched off. */\nexport function subscriptionCoreCutoverDisabledFailure(\n displayName: string = DEFAULT_DISPLAY_NAME,\n): SubscriptionCoreCodexTurnError {\n return new SubscriptionCoreCodexTurnError(\n {\n error: `${displayName} subscriptions are paused for this organization during maintenance.`,\n code: \"subscription_core_cutover_disabled\",\n retryable: false,\n },\n displayName,\n );\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\";\nimport type { VaultConnectionCredentialsPort } from \"@opengeni/vaults\";\nimport type {\n ExternalVaultProviderFactories,\n OnePasswordVaultProviderFactory,\n} from \"@opengeni/core\";\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 // - `vaultProvider` links a host-owned secret store as a `source: \"host\"`\n // vault (see `@opengeni/vaults` `VaultConnectionCredentialsPort`).\n // Each leg is independently optional; an unset leg falls through to today's\n // self-mint for THAT leg. null/undefined (standalone default) → every leg\n // self-mints 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?: VaultConnectionCredentialsPort | null;\n /**\n * Builds 1Password providers for linked vaults (dynamic import of\n * `@opengeni/vaults-onepassword`); null leaves 1Password vaults unavailable.\n */\n onePasswordVaultProvider?: OnePasswordVaultProviderFactory | null;\n externalVaultProviders?: ExternalVaultProviderFactories | 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 /** Host-owned containment: stop polling and checkpoint peer turns before exit.\n * Bare activity embedders must provide their own worker lifecycle edge. */\n requestWorkerDrain: () => void;\n /** Deterministic test clock for the cleanup-only monitor. */\n turnFinalizationTimeoutMs?: number | undefined;\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\" | \"claude\";\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\" | \"claude\";\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 ReconcileSettledSessionAttemptInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n workflowId: string;\n workflowRunId: string;\n activityId: string;\n};\n\nexport type ReconcileSettledSessionAttemptResult = {\n action: \"recovering\" | \"exceeded\" | \"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\"; continueDelayMs?: number }\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 /** Preserve a confirmed-overload Retry-After through checkpoint DB outages. */\n providerRecoveryContinueDelayMs?: number;\n /** Persist the no-replay setup marker, not a new provider/setup attempt. */\n sandboxSetupOutcomeUnknown?: true;\n /** Preserve the exhausted budget for a command proven not dispatched. */\n sandboxSetupRecoveryExhausted?: true;\n /** Content-free task usage receipts whose write failed after their\n * provider responses were received. The DB-only control lane writes them\n * with their original identities before any replacement attempt, so known\n * usage is neither lost nor re-requested. Bounded; omitted when none. */\n sessionUsageReceipts?: PostClaimSessionUsageReceipt[];\n};\n\nexport type PostClaimSessionUsageReceipt = {\n sessionId: string;\n sourceId: string;\n turnId: string | null;\n amountMicros: number | null;\n pricingSource: \"configured_list_price\" | \"gateway_reported\" | null;\n model: string | null;\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 | \"session_usage_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 | \"scheduled_model_unavailable\"\n | \"knowledge_source_paused\"\n | \"legacy_source_schedule_requires_migration\"\n | \"atlassian_native_retired\"\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\" | \"dispatch-expired\";\n };\n","/**\n * Person-facing copy for finite same-turn provider recovery. Presentation only:\n * retry authority, pacing and the recovery budget stay in `errors.ts`.\n *\n * `@opengeni/react` (`lib/provider-recovery.ts`) composes the same sentences\n * from the structured event fields, so live retry status and historical\n * failures read identically in every surface. Keep the two in step.\n */\n\n/** Closed provider condition recorded on model-provider recovery payloads. */\nexport type ProviderCondition = \"overloaded\" | \"unavailable\" | \"unresponsive\" | \"rate_limited\";\n\n/** Failure codes whose transient condition belongs to the turn's model route. */\nexport const MODEL_PROVIDER_RECOVERY_CODES: ReadonlySet<string> = new Set([\n \"provider_unavailable\",\n \"provider_rate_limited\",\n \"provider_unknown_finish_reason\",\n \"post_compaction_continuation_empty\",\n]);\n\nexport type ProviderRecoveryCopyInput = {\n code?: string | null | undefined;\n providerCondition?: ProviderCondition | null | undefined;\n modelLabel?: string | null | undefined;\n providerLabel?: string | null | undefined;\n};\n\nfunction label(value: string | null | undefined): string | null {\n const trimmed = typeof value === \"string\" ? value.replace(/\\s+/g, \" \").trim() : \"\";\n return trimmed ? trimmed.slice(0, 120) : null;\n}\n\n/** One present-tense clause naming what is unavailable, without a trailing period. */\nexport function providerRecoverySubject(input: ProviderRecoveryCopyInput): string {\n const model = label(input.modelLabel) ?? \"The model\";\n const provider = label(input.providerLabel);\n const at = provider ? ` at the provider (${provider})` : \" at the provider\";\n switch (input.code) {\n case \"provider_rate_limited\":\n return `${model} is rate limited${at}`;\n case \"provider_unavailable\":\n return input.providerCondition === \"overloaded\"\n ? `${model} is overloaded${at}`\n : input.providerCondition === \"unresponsive\"\n ? `${model} stopped responding${at}`\n : `${model} is temporarily unavailable${at}`;\n case \"provider_unknown_finish_reason\":\n return `${model} ended its response unexpectedly`;\n case \"post_compaction_continuation_empty\":\n return `${model} stopped right after compacting the conversation`;\n case \"upstream_connectivity_unavailable\":\n return \"Opengeni can't reach an upstream service\";\n case \"mcp_transport_timeout\":\n return \"A required MCP server isn't responding\";\n case \"mcp_transport_unavailable\":\n return \"A required MCP server is unreachable\";\n case \"sandbox_command_start_unavailable\":\n return \"The sandbox isn't ready yet\";\n case \"retained_attachment_unavailable\":\n return \"An image from earlier in this conversation can't be read from storage\";\n case \"turn_execution_policy_definition_mismatch\":\n return \"Opengeni is applying a configuration update\";\n default:\n return \"A service this turn depends on is temporarily unavailable\";\n }\n}\n\n/** Terminal copy once the finite automatic recovery budget is spent. */\nexport function providerRecoveryExhaustedMessage(\n input: ProviderRecoveryCopyInput & { providerRecoveryCount: number },\n): string {\n const count = input.providerRecoveryCount;\n const retried = `Opengeni retried ${count} ${count === 1 ? \"time\" : \"times\"} without success.`;\n const remedy = MODEL_PROVIDER_RECOVERY_CODES.has(input.code ?? \"\")\n ? \"Try again in a few minutes, or switch to another model.\"\n : \"Try again in a few minutes.\";\n return `${providerRecoverySubject(input)}. ${retried} ${remedy}`;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;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,oCAAoC,8BAA8B;AAC3E,SAAS,2BAA2B;;;ACTpC;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;AAAA,EAC3E;AAEA,SAAO,OAAO,YAAY;AACxB,QAAI,QAAQ,YAAY,QAAQ,aAAa,UAAU;AACrD,YAAM,IAAI,MAAM,6DAA6D;AAAA,IAC/E;AACA,QAAI,CAAC,QAAQ,uBAAuB,CAAC,QAAQ,gBAAgB,QAAQ;AACnE,YAAM,IAAI,MAAM,kEAAkE;AAAA,IACpF;AACA,UAAM,OAAO,MAAM;AAAA,MACjB;AAAA,MACA,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ;A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L,MAAM;AAAA,UACN,cAAc,qBAAqB,OAAO;AAAA,UAC1C,GAAI,YAAY,SAAY,CAAC,IAAI,EAAE,QAAQ;AAAA,QAC7C;AACF,UAAI,QAAQ,WAAW,OAAO,QAAQ,cAAc;AAClD,eAAO,EAAE,MAAM,aAAa;AAC9B,UAAI,QAAQ,WAAW,IAAK,QAAO,EAAE,MAAM,QAAQ;AACnD,aAAO;AAAA,IACT;AACA,cAAU,QAAQ;AAAA,EACpB;AACA,SAAO;AACT;","names":["delegation","readTurnExecutionPolicyV1","goalRunBudgetBlocked","readTurnExecutionPolicyV1","isDeepStrictEqual","createHash","getConnectionMetadata","sleep","delayMs","parent","getConnectionMetadata","isDeepStrictEqual","settled","obligation","objectAcl","createHash","version","aclRevision","bytes","url","payload","label","getSessionTurn","subscriptionCoreProvider","readTurnExecutionPolicyV1","subscriptionCoreProvider","subscriptionCoreProvider","mergeToolRefs","getSessionTurn","readTurnExecutionPolicyV1","subscriptionCoreProvider","armSubscriptionCoreCapacityWait","getSubscriptionCoreCapacityWaitById","readSubscriptionCoreTurnModel","reconcileSubscriptionCoreCapacityWait","SUBSCRIPTION_CORE_XAI","subscriptionCoreTurns","wakeSubscriptionCoreProviderCapacityWaiters","deliverSubscriptionCoreProviderWake","subscriptionCoreOperationConnections","subscriptionCorePersonalConnections","CORE_SUBSCRIPTION_SERVICE_SUBJECT","SUBSCRIPTION_CORE_XAI","armSubscriptionCoreCapacityWait","getSubscriptionCoreCapacityWaitById","readSubscriptionCoreTurnModel","subscriptionCoreTurns","wakeSubscriptionCoreProviderCapacityWaiters","reconcileSubscriptionCoreCapacityWait","createHash","isDeepStrictEqual","label","getScheduledTaskRunAcceptedExecution","requireSession","requireWorkspace","resolveSessionFirstPartyMcpTools","resolveSessionFirstPartyMcpTools","requireWorkspace","requireSession","getScheduledTaskRunAcceptedExecution","token","randomUUID","retryDelayMs","SandboxLeaseTransitionError","CancelledFailure","readTurnExecutionPolicyV1","createHash","readTurnExecutionPolicyV1","createHash","clone","CancelledFailure","SandboxLeaseTransitionError","quota"]}