@opengeni/runtime 0.14.1 → 0.14.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-4YJ5Z52Z.js → chunk-7E2ZSCZK.js} +6 -6
- package/dist/{chunk-4YJ5Z52Z.js.map → chunk-7E2ZSCZK.js.map} +1 -1
- package/dist/{chunk-HHWIZHQM.js → chunk-GNEGANUF.js} +942 -300
- package/dist/chunk-GNEGANUF.js.map +1 -0
- package/dist/codex-tool-search.d.ts +100 -0
- package/dist/context-compaction.d.ts +236 -0
- package/dist/history-sanitizer.d.ts +320 -0
- package/dist/index.d.ts +186 -718
- package/dist/index.js +612 -126
- package/dist/index.js.map +1 -1
- package/dist/{localSources-T3HZ6KY4.js → localSources-BXHBKGF4.js} +2 -2
- package/dist/mcp-network.d.ts +32 -35
- package/dist/metrics.d.ts +33 -0
- package/dist/sandbox/capabilities.d.ts +11 -0
- package/dist/sandbox/channel-a.d.ts +226 -0
- package/dist/sandbox/display-stack.d.ts +99 -0
- package/dist/sandbox/errors.d.ts +16 -0
- package/dist/sandbox/exec-banner.d.ts +19 -0
- package/dist/sandbox/index.d.ts +190 -6
- package/dist/sandbox/index.js +20 -4
- package/dist/sandbox/op-correlation.d.ts +24 -0
- package/dist/sandbox/provider-errors.d.ts +32 -0
- package/dist/sandbox/provider-operation-gate.d.ts +12 -0
- package/dist/sandbox/providers/blaxel.d.ts +2 -0
- package/dist/sandbox/providers/cloudflare.d.ts +2 -0
- package/dist/sandbox/providers/daytona.d.ts +2 -0
- package/dist/sandbox/providers/docker.d.ts +2 -0
- package/dist/sandbox/providers/e2b.d.ts +2 -0
- package/dist/sandbox/providers/index.d.ts +11 -0
- package/dist/sandbox/providers/local.d.ts +2 -0
- package/dist/sandbox/providers/modal.d.ts +132 -0
- package/dist/sandbox/providers/none.d.ts +2 -0
- package/dist/sandbox/providers/runloop.d.ts +2 -0
- package/dist/sandbox/providers/selfhosted.d.ts +2 -0
- package/dist/sandbox/providers/types.d.ts +30 -0
- package/dist/sandbox/providers/vercel.d.ts +2 -0
- package/dist/sandbox/recording.d.ts +80 -0
- package/dist/sandbox/routing/backend-resolver.d.ts +173 -0
- package/dist/sandbox/routing/routing-session.d.ts +401 -0
- package/dist/sandbox/run-credentials.d.ts +65 -0
- package/dist/sandbox/select.d.ts +120 -0
- package/dist/sandbox/selfhosted/capabilities.d.ts +91 -0
- package/dist/sandbox/selfhosted/control-rpc.d.ts +175 -0
- package/dist/sandbox/selfhosted/fault-rendering.d.ts +40 -0
- package/dist/sandbox/selfhosted/op-observer.d.ts +40 -0
- package/dist/sandbox/selfhosted/op-stream.d.ts +104 -0
- package/dist/sandbox/selfhosted/op-testing.d.ts +108 -0
- package/dist/sandbox/selfhosted/op-transport.d.ts +60 -0
- package/dist/sandbox/selfhosted/retry-policy.d.ts +106 -0
- package/dist/sandbox/selfhosted/session.d.ts +552 -0
- package/dist/sandbox/selfhosted/testing.d.ts +48 -0
- package/dist/sandbox/stream-port.d.ts +80 -0
- package/dist/sandbox/stream-token.d.ts +44 -0
- package/dist/sandbox/terminal-server.d.ts +67 -0
- package/dist/sandbox/toolspace-token.d.ts +23 -0
- package/dist/sandbox/turn-tool-cancellation.d.ts +72 -0
- package/dist/sandbox/workspace-archive.d.ts +39 -0
- package/dist/sandbox-computer.d.ts +227 -0
- package/dist/screenshot-error-card.d.ts +1 -0
- package/dist/skill-library.d.ts +10 -12
- package/dist/usage-telemetry.d.ts +45 -0
- package/dist/workspace-skills.d.ts +31 -0
- package/package.json +7 -7
- package/src/context-compaction.ts +600 -6
- package/src/history-sanitizer.ts +10 -92
- package/src/index.ts +301 -62
- package/src/sandbox/channel-a.ts +267 -81
- package/src/sandbox/index.ts +56 -94
- package/src/sandbox/provider-operation-gate.ts +110 -0
- package/src/sandbox/providers/docker.ts +13 -1
- package/src/sandbox/providers/modal.ts +433 -3
- package/src/sandbox/routing/routing-session.ts +84 -8
- package/src/sandbox/selfhosted/session.ts +7 -6
- package/src/sandbox/turn-tool-cancellation.ts +47 -7
- package/src/sandbox/workspace-archive.ts +176 -73
- package/src/sandbox-computer.ts +25 -75
- package/dist/chunk-HHWIZHQM.js.map +0 -1
- package/dist/index-BraazrAO.d.ts +0 -2931
- /package/dist/{localSources-T3HZ6KY4.js.map → localSources-BXHBKGF4.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiProvider.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/metadata.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/defaults.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiResponsesModel.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/logger.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/rawModelEvents.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/retryAdvice.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/responsesWebSocketConnection.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/responsesTransportUtils.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/tools.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/utils/providerData.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/utils/modelSettings.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/responsesUtils.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiChatCompletionsStreaming.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiChatCompletionsConverter.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiChatCompletionsModel.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiTracingExporter.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/memory/openaiConversationsSession.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/memory/openaiSessionApi.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/memory/openaiResponsesCompactionSession.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/metadata.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/utils.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/items.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/logger.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/openaiRealtimeEvents.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/shims/shims-node.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/tool.ts","../../../node_modules/.bun/@openai+agents@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents/src/index.ts","../src/screenshot-error-card.ts","../src/history-sanitizer.ts","../src/codex-tool-search.ts","../src/context-compaction.ts","../src/sandbox-computer.ts","../src/workspace-skills.ts","../src/usage-telemetry.ts"],"sourcesContent":["import type {\n ConfiguredModel,\n ModelProviderApi,\n ResolvedModelProvider,\n Settings,\n} from \"@opengeni/config\";\nimport {\n AGENT_INSTRUCTIONS_CORE_PLACEHOLDER,\n collectSandboxEnvironment,\n firstPartyMcpBaseUrl,\n resolveModelProvider,\n sandboxLifecycleHookIds,\n} from \"@opengeni/config\";\nimport {\n approvalIdentifier,\n CAPABILITY_DESCRIPTORS,\n DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,\n DEFAULT_FIRST_PARTY_MCP_TOOLS,\n assertUniqueResourceMountPaths,\n gitCredentialBindingIdForRepository,\n gitCredentialProviderForRepository,\n isClearedRunStateBlob,\n normalizeRepositorySubpath,\n normalizeResourceMountPath,\n prefixedMcpToolName as sharedPrefixedMcpToolName,\n resourceMountPath,\n redactSensitiveText,\n sessionEventMediaPreview,\n sessionEventMediaPreviewFromDataUrl,\n signDelegatedAccessToken,\n RequestHumanInputToolInput,\n type GitCredentialProvider,\n type GitCredentialTransport,\n type HumanInputResponse,\n type McpServerConnectionRef,\n type Permission,\n type FirstPartyMcpToolName,\n type ReasoningEffort,\n type ResourceRef,\n type SessionEventType,\n type SessionEventMediaPreview,\n type ToolAuthNeededPayload,\n type ToolRef,\n} from \"@opengeni/contracts\";\nimport {\n MCP_MAX_CONCURRENT_SERVER_OPERATIONS,\n MCP_MAX_TOOL_RESULT_BYTES,\n McpAggregateToolListBudget,\n assertMcpPayloadWithinBytes,\n assertMcpServerSelectionWithinBounds,\n assertMcpToolListWithinBounds,\n boundedParallelMap,\n cancelMcpResponseBody,\n guardedMcpFetch,\n mcpOuterConnectTimeoutMs,\n undiciFetch,\n} from \"./mcp-network\";\nimport {\n Agent,\n AgentsError,\n connectMcpServers,\n OpenAIProvider,\n setDefaultModelProvider,\n MaxTurnsExceededError,\n MCPServerStreamableHttp,\n // Provider-bound Model instances. Both are re-exported from\n // @openai/agents-openai via `export * from '@openai/agents-openai'` in\n // @openai/agents' index (0.11.6), so the multi-provider routing imports them\n // from the same entrypoint as the rest of the SDK rather than reaching into\n // the openai subpackage. OpenAIChatCompletionsModel speaks /v1/chat/completions\n // (the registry \"chat\" wire API, e.g. Fireworks); OpenAIResponsesModel speaks\n // /v1/responses (the built-in OpenAI/Azure \"responses\" wire API). Both bind a\n // model id to a specific OpenAI client, which is what routes a turn to its\n // provider without touching the global default client.\n OpenAIChatCompletionsModel,\n OpenAIResponsesModel,\n RunState,\n isOpenAIResponsesRawModelStreamEvent,\n run,\n Runner,\n setDefaultOpenAIClient,\n setDefaultOpenAIKey,\n setOpenAIResponsesTransport,\n setTracingDisabled,\n tool as agentTool,\n // Hosted web_search tool factory. Re-exported from @openai/agents-openai via\n // `export * from '@openai/agents-openai'` in @openai/agents' index (0.11.6);\n // it returns a { type: 'hosted_tool', providerData: { type: 'web_search' } }\n // descriptor the OpenAI Responses model serializes into request.tools[].\n webSearchTool,\n // The SDK's V4A-diff applier — the apply_patch host the filesystem capability's\n // editor uses. The agent-loop-free sandbox leaf cannot import it (it lives behind\n // the `@openai/agents` root the leaf forbids), so the barrel imports it here and\n // injects it into the selfhosted session's `createEditor` via setSelfhostedApplyDiff\n // (below, right after the leaf re-export). This lets a selfhosted active backend\n // apply file edits over its NATS fs ops using the SDK's exact diff semantics.\n applyDiff,\n type AgentInputItem,\n type CallModelInputFilter,\n type MCPServer,\n type MCPToolErrorFunction,\n type Model,\n type ModelRequest,\n type ModelProvider,\n type RunStreamEvent,\n type Tool,\n} from \"@openai/agents\";\nimport { localDirLazySkillSource } from \"@openai/agents/sandbox/local\";\nimport {\n Capabilities,\n Manifest,\n SandboxAgent,\n azureBlobMount,\n dir,\n file,\n filesystem,\n gitRepo,\n inContainerMountStrategy,\n localDir,\n s3Mount,\n shell,\n skills,\n type Dir,\n type Entry,\n type LocalDirLazySkillSource,\n type SandboxClient,\n type SandboxSessionLike,\n type SandboxSessionState,\n type SandboxRunConfig,\n type SkillIndexEntry,\n} from \"@openai/agents/sandbox\";\nimport { ModalCloudBucketMountStrategy } from \"@openai/agents-extensions/sandbox/modal\";\nimport OpenAI from \"openai\";\nimport {\n CODEX_APPS_MCP_SERVER_ID,\n CODEX_MODEL_ID_PREFIX,\n CODEX_ORIGINATOR,\n CODEX_RESPONSE_SDK_OUTER_TIMEOUT_MS,\n boundModelToolOutputItems,\n codexAppsSanitizingFetch,\n codexRequestStorage,\n codexSubscriptionFetch,\n} from \"@opengeni/codex\";\nimport { cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { dirname, isAbsolute, join, posix as posixPath, relative } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n computerCallNormalizingFetch,\n elideSupersededViewImagePairs,\n normalizeComputerCallActions,\n sanitizeHistoryItemsForModel,\n} from \"./history-sanitizer\";\nimport { installCodexToolSearch } from \"./codex-tool-search\";\nimport {\n CompactionNeededError,\n CompactionProviderResponseError,\n EmptyCompactionSummaryError,\n SUMMARY_BUFFER_TOKENS,\n compactionThresholdTokens,\n estimateCompleteModelInput,\n estimateSerializedValueTokens,\n hasModelGeneratedItem,\n renderCompactionPromptInputForChat,\n type CompleteModelInputFootprint,\n type ProviderContextTokenSignal,\n} from \"./context-compaction\";\nimport {\n createSandboxClient,\n desktopCapableBackend,\n restoredSandboxSessionStateFromEntry,\n setSelfhostedApplyDiff,\n toolspaceTokenFileFromEnvironment,\n withToolspaceTokenClient,\n withToolspaceTokenSession,\n withRunCredentialsClient,\n withRunCredentialsSession,\n type RunCredentialSessionReady,\n} from \"./sandbox\";\nimport { runWithToolCallCorrelation } from \"./sandbox/op-correlation\";\nimport { shellToolspacePath } from \"./sandbox/toolspace-token\";\nimport {\n createTurnToolCancellationController,\n TurnSandboxCommandCancelledError,\n wrapCapabilityToolsForTurnCancellation,\n type TurnSandboxCommandArgs,\n type TurnSandboxCommandSession,\n type TurnToolCancellationFence,\n} from \"./sandbox/turn-tool-cancellation\";\nimport { computerUse, type ComputerToolMode } from \"./sandbox-computer\";\nimport type { RuntimeMetricsHooks } from \"./metrics\";\nimport { workspaceSkills, type WorkspaceSkillSearchPath } from \"./workspace-skills\";\n\n// The Agents SDK's debug namespaces can otherwise serialize complete model\n// inputs/outputs and tool arguments/results. These getters read process.env on\n// every log call, so keep the process-global guard permanently enabled rather\n// than toggling it around concurrent turns.\nprocess.env.OPENAI_AGENTS_DONT_LOG_MODEL_DATA = \"1\";\nprocess.env.OPENAI_AGENTS_DONT_LOG_TOOL_DATA = \"1\";\n\nexport {\n getSkillLibraryEntry,\n isSkillLibraryEntryId,\n listSkillLibraryEntries,\n loadSkillLibrarySkill,\n type SkillLibraryEntry,\n type SkillLibraryFile,\n type SkillLibrarySkill,\n} from \"./skill-library\";\n\nexport type { RuntimeMetricsHooks } from \"./metrics\";\nexport {\n createTurnToolCancellationController,\n TurnSandboxCommandCancelledError,\n} from \"./sandbox/turn-tool-cancellation\";\nexport type {\n TurnSandboxCommandArgs,\n TurnSandboxCommandSession,\n TurnToolCancellationController,\n TurnToolCancellationFence,\n} from \"./sandbox/turn-tool-cancellation\";\n\n// P4.3 computer-use surface (the agent's :0 driver). Re-exported from the barrel\n// so callers (the worker, live proofs) reach SandboxComputer/ComputerUseCapability\n// alongside the rest of the runtime. NOT part of the agent-loop-free leaf (it\n// imports computerTool from the @openai/agents root).\nexport {\n SandboxComputer,\n ComputerUseCapability,\n computerUse,\n ComputerUnavailableError,\n ComputerReadOnlyError,\n ComputerActionError,\n type SandboxComputerOptions,\n type ComputerUseArgs,\n type ComputerToolMode,\n} from \"./sandbox-computer\";\n\n// The agent-loop-free sandbox leaf (createSandboxClient + resume/recovery\n// helpers + the config-owned env/port re-exports). Re-exported verbatim so the\n// barrel surface is unchanged for apps/worker while @opengeni/runtime/sandbox\n// stays importable by the API without the agent loop.\nexport * from \"./sandbox\";\n\n// Inject the SDK's V4A `applyDiff` into the selfhosted session's apply_patch editor\n// at module load. The leaf can't import `applyDiff` (agent-loop root), so the\n// barrel — which already imports `@openai/agents` — wires it once. A selfhosted\n// active backend can now apply file edits over its NATS fs ops with the SDK's exact\n// diff semantics; without this, `createEditor()` throws a clear \"not injected\" error\n// rather than mis-editing. Runs at import time, before any turn binds a capability.\nsetSelfhostedApplyDiff(\n applyDiff as unknown as (input: string, diff: string, mode?: \"default\" | \"create\") => string,\n);\n\nexport {\n elideSupersededViewImagePairs,\n sanitizeHistoryItemsForModel,\n stripReasoningEncryptedContent,\n stripReasoningIdentityFromSerializedRunState,\n neutralizeToolSearchItemsInSerializedRunState,\n} from \"./history-sanitizer\";\nexport type { HistoryItem } from \"./history-sanitizer\";\n\n// The provider-bound Model classes used by buildModelInstance/resolveTurnModel.\n// Re-exported so callers (and routing tests) can assert which wire API a\n// resolved turn was bound to — OpenAIChatCompletionsModel for registry \"chat\"\n// providers (Fireworks), OpenAIResponsesModel for the built-in \"responses\" path\n// — without reaching into @openai/agents directly.\nexport { OpenAIChatCompletionsModel, OpenAIResponsesModel } from \"@openai/agents\";\n\nexport {\n CompactionNeededError,\n CompactionProviderResponseError,\n EmptyCompactionSummaryError,\n buildCompactionPromptInput,\n buildCompactionReplacementHistory,\n compactionReplacementFingerprint,\n compactionThresholdTokens,\n clampCompactionThresholdRatio,\n decideCompaction,\n buildSummaryItem,\n findCompactionNeededError,\n isCompactionSummary,\n latestCompactionReplacementFingerprint,\n prepareCompactionPromptInput,\n isUserMessage,\n estimateTokens,\n estimateItemTokens,\n estimateCompleteModelInput,\n estimateSerializedValueTokens,\n hasModelGeneratedItem,\n renderCompactionPromptInputForChat,\n COMPACTION_SUMMARY_MARKER,\n COMPACTION_PROMPT,\n COMPACT_USER_MESSAGE_MAX_TOKENS,\n DEFAULT_COMPACTION_THRESHOLD_RATIO,\n MIN_COMPACTION_THRESHOLD_RATIO,\n MAX_COMPACTION_THRESHOLD_RATIO,\n SUMMARY_BUFFER_TOKENS,\n SUMMARY_PREFIX,\n USER_MESSAGE_TRUNCATION_MARKER,\n} from \"./context-compaction\";\nexport type {\n CompactionDecision,\n CompactionItem,\n PreparedCompactionPromptInput,\n} from \"./context-compaction\";\nexport {\n MAX_MODEL_USAGE_TOKEN_COUNT,\n modelCallUsageTelemetry,\n modelUsageTokenCountOrNull,\n normalizeModelCallUsage,\n} from \"./usage-telemetry\";\nexport type {\n ModelCallUsageInput,\n ModelCallUsageNormalization,\n ModelCallUsageTelemetry,\n} from \"./usage-telemetry\";\n\nensureReadableStreamFrom();\n\nconst SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS = 120_000;\n\nexport type NormalizedRuntimeEvent = {\n type: SessionEventType;\n payload: unknown;\n};\n\nexport type ModelResponseUsage = {\n responseId?: string;\n usage: {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n inputTokensDetails?: Record<string, number> | Array<Record<string, number>>;\n outputTokensDetails?: Record<string, number> | Array<Record<string, number>>;\n requestUsageEntries?: Array<{\n inputTokens?: number;\n input_tokens?: number;\n outputTokens?: number;\n output_tokens?: number;\n totalTokens?: number;\n total_tokens?: number;\n inputTokensDetails?: Record<string, number>;\n input_tokens_details?: Record<string, number>;\n outputTokensDetails?: Record<string, number>;\n output_tokens_details?: Record<string, number>;\n }>;\n };\n};\n\ntype RuntimeMcpTool = Awaited<ReturnType<MCPServer[\"listTools\"]>>[number];\n\ntype FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n\nexport type ResolveConnectionCredentialInput = {\n workspaceId: string;\n subjectId?: string;\n serverId: string;\n toolName?: string;\n connectionRef: McpServerConnectionRef;\n /** Exact MCP destination whose request would receive the resolved headers. */\n destinationUrl: string;\n forceRefresh?: boolean;\n};\n\nexport type ResolveConnectionCredentialResult =\n | {\n status: \"ok\";\n headers: Record<string, string>;\n connectionId: string;\n expiresAt?: Date | null;\n }\n | {\n status: \"auth_needed\";\n reason: ToolAuthNeededPayload[\"reason\"];\n providerDomain: string;\n provider?: string;\n connectionId?: string;\n scopes?: string[];\n resource?: string;\n selectedResources?: McpServerConnectionRef[\"selectedResources\"];\n authorizationUrl?: string;\n };\n\nexport function ensureReadableStreamFrom(): void {\n const ctor = globalThis.ReadableStream as\n | (typeof ReadableStream & {\n from?: <T>(source: Iterable<T> | AsyncIterable<T>) => ReadableStream<T>;\n })\n | undefined;\n if (!ctor || typeof ctor.from === \"function\") {\n return;\n }\n Object.defineProperty(ctor, \"from\", {\n configurable: true,\n writable: true,\n value<T>(source: Iterable<T> | AsyncIterable<T>): ReadableStream<T> {\n const iterator = isAsyncIterable(source)\n ? source[Symbol.asyncIterator]()\n : source[Symbol.iterator]();\n return new ReadableStream<T>({\n async pull(controller) {\n const next = await iterator.next();\n if (next.done) {\n controller.close();\n } else {\n controller.enqueue(next.value);\n }\n },\n async cancel() {\n await iterator.return?.();\n },\n });\n },\n });\n}\n\nexport type AgentSegmentInput =\n | {\n kind: \"message\";\n /** A real human/API prompt. Omitted when resuming the same inference. */\n text?: string;\n /** Ephemeral platform context: system role, never conversation history. */\n internalContext?: string;\n // Canonical conversation truth. When omitted, this is a fresh first\n // message; ordinary messages never deserialize an SDK RunState.\n historyItems?: AgentInputItem[] | null;\n sandboxEnvelope?: Record<string, unknown> | null;\n }\n | {\n kind: \"approval\";\n serializedRunState: string;\n approvalId: string;\n decision: \"approve\" | \"reject\";\n message?: string;\n }\n | {\n kind: \"human_input\";\n serializedRunState: string;\n toolCallId: string;\n };\n\nexport type PreparedAgentInput = {\n input: string | AgentInputItem[] | RunState<any, any>;\n sandboxSessionState?: SandboxSessionState;\n};\n\nexport const HUMAN_INPUT_TOOL_NAME = \"request_human_input\";\n\nexport type SerializedHumanInputInterruption = {\n toolCallId: string;\n input: ReturnType<typeof RequestHumanInputToolInput.parse>;\n};\n\nexport type SandboxFileDownload = {\n fileId: string;\n mountPath: string;\n filename: string;\n url?: string;\n content?: Uint8Array;\n expiresAt?: Date | string;\n sizeBytes?: number;\n};\n\nexport type SandboxFileDownloadFailure = {\n fileId: string;\n filename: string;\n path: string;\n reason: string;\n exitCode?: number;\n output?: string;\n};\n\nexport type SandboxFileDownloadMaterializationResult = {\n failures: SandboxFileDownloadFailure[];\n};\n\nlet runtimeMetricsHooks: RuntimeMetricsHooks | null = null;\n\nexport function configureRuntimeMetricsHooks(hooks: RuntimeMetricsHooks | null | undefined): void {\n runtimeMetricsHooks = hooks ?? null;\n}\n\nexport type OpenGeniRuntime = {\n configure: (settings: Settings) => void;\n // Multi-provider per-turn model routing. Returns the resolved provider, its\n // (cached) client, the provider-bound Model instance, and the configured-model\n // shape; null when the turn's model is not in the registry, so the caller\n // falls back to the legacy global-client path (settings.openaiModel).\n resolveTurnModel: (settings: Settings, modelId: string) => ReturnType<typeof resolveTurnModel>;\n buildAgent: (\n settings: Settings,\n resources: ResourceRef[],\n options?: BuildAgentOptions,\n ) => Agent<any, any>;\n prepareTools: (\n settings: Settings,\n tools: ToolRef[],\n options?: PrepareToolsOptions,\n ) => Promise<PreparedAgentTools>;\n prepareInput: (\n agent: Agent<any, any>,\n input: AgentSegmentInput,\n options?: PrepareInputOptions,\n ) => Promise<PreparedAgentInput>;\n runStream: (\n agent: Agent<any, any>,\n input: PreparedAgentInput,\n settings: Settings,\n options?: RunAgentStreamOptions,\n ) => Promise<Awaited<ReturnType<typeof runAgentStream>>>;\n serializeApprovals: (interruptions: unknown[]) => unknown[];\n serializeHumanInputRequests?: (interruptions: unknown[]) => SerializedHumanInputInterruption[];\n};\n\nexport type ProductionRuntimeOverrides = {\n model?: Model;\n sandboxClient?: unknown;\n metrics?: RuntimeMetricsHooks;\n};\n\nexport function createProductionAgentRuntime(\n overrides: ProductionRuntimeOverrides = {},\n): OpenGeniRuntime {\n return {\n configure: (settings) => {\n configureRuntimeMetricsHooks(overrides.metrics);\n configureOpenAI(settings);\n },\n // A test/override model shadows the registry routing entirely (the scripted\n // model used in worker tests is not in any provider's allow-list), so when\n // one is supplied resolveTurnModel reports \"no resolution\" and the caller\n // keeps the legacy global-client path with the override model.\n resolveTurnModel: (settings, modelId) =>\n overrides.model ? null : resolveTurnModel(settings, modelId),\n buildAgent: (settings, resources, options) =>\n buildOpenGeniAgent(settings, resources, {\n ...options,\n ...(overrides.model ? { model: overrides.model } : {}),\n }),\n prepareTools: prepareAgentTools,\n prepareInput: prepareRunInput,\n runStream: async (agent, input, settings, options) =>\n await runAgentStream(agent, input, settings, {\n ...options,\n sandboxClient: overrides.sandboxClient,\n }),\n serializeApprovals,\n serializeHumanInputRequests,\n };\n}\n\n/**\n * Build an OpenAI client from settings for the configured provider. Mirrors the\n * client construction in configureOpenAI so a direct API call (the compaction\n * summarizer) uses the same Azure/OpenAI auth and base URL. Returns null when\n * the OpenAI-platform path has only a key (the SDK default client is used via\n * setDefaultOpenAIKey there); the caller then constructs a key-only client.\n */\nexport function buildOpenAIClientFromSettings(\n settings: Settings,\n providerId: string = settings.openaiProvider,\n): OpenAI {\n if (settings.openaiProvider === \"azure\") {\n const baseURL = settings.azureOpenaiBaseUrl ?? azureDeploymentBaseUrl(settings);\n const apiKey = settings.azureOpenaiApiKey ?? settings.azureOpenaiAdToken ?? \"azure-ad-token\";\n return new OpenAI({\n apiKey,\n baseURL,\n maxRetries: settings.openaiMaxRetries,\n defaultQuery: azureOpenAIDefaultQuery(settings, baseURL),\n defaultHeaders:\n settings.azureOpenaiAdToken && !settings.azureOpenaiApiKey\n ? { Authorization: `Bearer ${settings.azureOpenaiAdToken}` }\n : undefined,\n // Rewrite every outbound /responses computer_call to the ACTIONS-ONLY shape\n // the GA Azure computer tool accepts. This is the lowest reachable\n // seam — below the SDK responses converter, which always re-synthesizes BOTH\n // `action` and `actions` (rejected 400 \"exactly one of action or actions\").\n // See computerCallNormalizingFetch / rewriteComputerCallsToActionsOnly.\n fetch: computerCallNormalizingFetch(instrumentedModelFetch(providerId, globalThis.fetch)),\n });\n }\n return new OpenAI({\n apiKey: settings.openaiApiKey ?? process.env.OPENAI_API_KEY,\n ...(settings.openaiBaseUrl ? { baseURL: settings.openaiBaseUrl } : {}),\n maxRetries: settings.openaiMaxRetries,\n fetch: instrumentedModelFetch(providerId, globalThis.fetch),\n });\n}\n\n/**\n * One OpenAI client per resolved provider id, built lazily and cached for the\n * process. The built-in openai/azure provider reuses\n * buildOpenAIClientFromSettings verbatim (so its Azure AD/api-version/base-URL\n * construction stays byte-for-byte identical to configureOpenAI); a registry\n * provider gets a plain client pointed at its base URL with its resolved key,\n * the shared maxRetries budget, and its declared defaultQuery/defaultHeaders.\n * Caching by provider.id keeps concurrent multi-provider turns sharing one\n * connection pool per provider rather than reconstructing a client per turn.\n */\nconst providerClientCache = new Map<string, OpenAI>();\n\nexport function buildProviderClient(provider: ResolvedModelProvider, settings: Settings): OpenAI {\n const cached = providerClientCache.get(provider.id);\n if (cached) {\n return cached;\n }\n const client = provider.builtin\n ? buildOpenAIClientFromSettings(settings, provider.id)\n : provider.kind === \"codex-subscription\"\n ? // Codex subscription: the static apiKey is a placeholder — the real per-request\n // bearer + ChatGPT-Account-ID, the /responses->/codex/responses rewrite, and the\n // body normalization are all injected by codexSubscriptionFetch, which reads the\n // per-workspace token from codexRequestStorage (AsyncLocalStorage) at call time.\n // The provider id is constant (\"codex-subscription\"), so one cached client serves\n // every workspace without baking a token into it.\n new OpenAI({\n apiKey: provider.apiKey ?? \"codex-subscription\",\n ...(provider.baseUrl ? { baseURL: provider.baseUrl } : {}),\n // Codex transport owns exactly one explicit 401 refresh/retry. Blind\n // SDK retries on network/5xx/partial streams can replay provider work\n // or external tool side effects without a durable checkpoint.\n maxRetries: 0,\n // The Codex transport owns finer headers/idle/whole deadlines and\n // emits typed durable evidence. Keep the SDK's opaque envelope beyond\n // that whole-response budget so `Request timed out.` cannot win first.\n timeout: CODEX_RESPONSE_SDK_OUTER_TIMEOUT_MS,\n fetch: codexSubscriptionFetch(instrumentedModelFetch(provider.id, globalThis.fetch)),\n })\n : // ResolvedModelProvider.apiKey is already the resolved key (configuredProviders\n // ran resolveProviderApiKey at config time, collapsing apiKey/apiKeyEnv), so it\n // is passed straight through here rather than re-resolved.\n new OpenAI({\n ...(provider.apiKey ? { apiKey: provider.apiKey } : {}),\n ...(provider.baseUrl ? { baseURL: provider.baseUrl } : {}),\n maxRetries: settings.openaiMaxRetries,\n ...(provider.defaultQuery ? { defaultQuery: provider.defaultQuery } : {}),\n ...(provider.defaultHeaders ? { defaultHeaders: provider.defaultHeaders } : {}),\n fetch: instrumentedModelFetch(provider.id, globalThis.fetch),\n });\n providerClientCache.set(provider.id, client);\n return client;\n}\n\n/**\n * Bind a model id to a provider's OpenAI client as an @openai/agents `Model`\n * instance, choosing the wire API by the provider's declared `api`: the \"chat\"\n * providers (e.g. Fireworks) get an OpenAIChatCompletionsModel that speaks\n * /v1/chat/completions, the \"responses\" providers (built-in OpenAI/Azure) get\n * an OpenAIResponsesModel that speaks /v1/responses. Passing this Model into\n * the agent is what routes a turn to its provider without mutating the global\n * default client.\n */\nexport function buildModelInstance(\n provider: ResolvedModelProvider,\n client: OpenAI,\n modelId: string,\n): Model {\n return provider.api === \"chat\"\n ? new OpenAIChatCompletionsModel(client, modelId)\n : new OpenAIResponsesModel(client, modelId);\n}\n\n/**\n * Resolved per-turn model routing: the provider that serves `modelId`, its\n * (cached) OpenAI client, the provider-bound `Model` instance, and the\n * configured-model shape (label/api/contextWindow/reasoningEffort/hostedWebSearch).\n * Returns null when the model is not in the registry — the caller then falls\n * back to the legacy global-client path (settings.openaiModel + the default\n * client configured by configureOpenAI), preserved byte-for-byte.\n */\nexport function resolveTurnModel(\n settings: Settings,\n modelId: string,\n): {\n provider: ResolvedModelProvider;\n client: OpenAI;\n model: Model;\n configured: ConfiguredModel;\n} | null {\n const resolved = resolveModelProvider(settings, modelId);\n if (!resolved) {\n return null;\n }\n const client = buildProviderClient(resolved.provider, settings);\n return {\n provider: resolved.provider,\n client,\n model: buildModelInstance(resolved.provider, client, resolved.model.upstreamModelId),\n configured: resolved.model,\n };\n}\n\n/**\n * Routes a model *name* to its provider-bound Model (Fireworks chat model for a\n * registry model id, the built-in OpenAI/Azure responses model otherwise) via\n * `resolveTurnModel`. This is the load-bearing piece for the sandbox path:\n * passing a Model *instance* as `agent.model` only survives the in-process\n * (`sandboxBackend: \"none\"`) run — on the SandboxAgent/Modal path the instance\n * is dropped and the model *name* is re-resolved through the run's\n * `modelProvider` (or the global default). Without this router that re-resolution\n * hits the default client (e.g. Azure) and a registry model 404s\n * (\"deployment does not exist\"); with it the name resolves back to the right\n * provider. Installed both as the run-scoped `Runner.config.modelProvider` (every\n * run in runAgentStream goes through `runScopedRunner(settings)`, built from the\n * per-turn settings) and as the process default (see configureOpenAI). The\n * run-scoped instance is the load-bearing one: a `Runner` resolves string model\n * names against ITS OWN modelProvider, not the lazy global default, so each\n * concurrent turn routes codex/registry names against its own settings and a\n * foreign turn's setDefaultModelProvider can never clobber this turn's routing.\n * The process default remains only as a boot-time fallback. Falls back to the\n * SDK default provider for a model that is in no provider's allow-list.\n */\nexport class MultiProviderModelProvider implements ModelProvider {\n private fallback: OpenAIProvider | undefined;\n\n constructor(private readonly settings: Settings) {}\n\n async getModel(modelName?: string): Promise<Model> {\n if (modelName) {\n const resolved = resolveTurnModel(\n settingsForRunScopedModelResolution(this.settings, modelName),\n modelName,\n );\n if (resolved) {\n // Fail-loud floor (defense in depth): a `codex/<slug>` id must only ever\n // resolve through the synthetic codex-subscription provider (which installs\n // fetch: codexSubscriptionFetch + the per-workspace bearer). If a future\n // settings path re-introduces a built-in/registry shadow that binds a\n // `codex/` id to any other provider kind, that would silently ship the id\n // to Azure/OpenAI as a deployment name (DeploymentNotFound 404). Refuse it\n // here so codex can never reach a non-codex client on ANY backend; the\n // primary fix (config configuredModels) keeps this a no-op in practice.\n if (\n modelName.startsWith(CODEX_MODEL_ID_PREFIX) &&\n resolved.provider.kind !== \"codex-subscription\"\n ) {\n throw new CodexSubscriptionUnavailableError(modelName);\n }\n return resolved.model;\n }\n // A `codex/<slug>` id only resolves when the per-workspace worker overlay\n // (settingsWithCodexCredential) has injected the synthetic codex-subscription\n // provider — which it does ONLY for a workspace with an *active* connected\n // Codex subscription. If it did not resolve, the subscription is not\n // connected for this workspace, so the codex provider is absent. Falling\n // through to the built-in OpenAIProvider below would ship `codex/<slug>` to\n // the global default (Azure) client as a deployment name and surface a\n // misleading \"DeploymentNotFound\" 404. Throw a clear, user-actionable error\n // instead; it propagates through the worker's agentRunFailurePayload as the\n // turn.failed message the session UI shows. Mirrors the codex-prefix\n // awareness of assertConfiguredModel at apps/api/src/domain/sessions.ts.\n if (modelName.startsWith(CODEX_MODEL_ID_PREFIX)) {\n throw new CodexSubscriptionUnavailableError(modelName);\n }\n }\n // A non-codex model in no provider's allow-list falls back to the SDK's\n // default OpenAIProvider, which uses the global default client/key\n // configureOpenAI set up (the built-in OpenAI/Azure provider).\n this.fallback ??= new OpenAIProvider();\n return this.fallback.getModel(modelName);\n }\n}\n\nfunction settingsForRunScopedModelResolution(settings: Settings, modelName: string): Settings {\n if (modelName !== settings.openaiModel) {\n return settings;\n }\n const builtinAllowed = splitOpenaiAllowedModels(settings.openaiAllowedModels);\n const fallbackBuiltin = builtinAllowed.find((id) => id !== modelName);\n if (!fallbackBuiltin) {\n return settings;\n }\n // The worker sets runSettings.openaiModel to the turn's model. For namespaced\n // registry ids configuredModels filters the built-in entry out, but a unique\n // bare registry id would otherwise be claimed by the built-in only because of\n // that per-turn override. Resolve the run-scoped router against the deployment\n // allow-list head instead; real built-in models stay in the allow-list.\n return builtinAllowed.includes(modelName)\n ? settings\n : { ...settings, openaiModel: fallbackBuiltin };\n}\n\nfunction splitOpenaiAllowedModels(value: string): string[] {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\n/**\n * A `codex/<slug>` turn reached the model router but the workspace has no active\n * Codex subscription connected (the worker overlay never injected the synthetic\n * provider, so resolveTurnModel returned nothing). Thrown instead of silently\n * routing the id to the built-in Azure/OpenAI client — that produced an opaque\n * \"DeploymentNotFound\" 404. The message is user-actionable (connect/reconnect)\n * and carries no status/code, so agentRunFailurePayload surfaces it verbatim as\n * a non-retryable turn.failed the session UI shows.\n */\nexport class CodexSubscriptionUnavailableError extends Error {\n constructor(modelName: string) {\n super(\n `Codex subscription model \"${modelName}\" is unavailable: no active Codex subscription is connected for this workspace. ` +\n `Connect (or reconnect) your ChatGPT/Codex subscription in Settings, then retry.`,\n );\n this.name = \"CodexSubscriptionUnavailableError\";\n }\n}\n\n/**\n * The workspace's model policy blocks the provider/model this turn resolved\n * to. Thrown at the worker's post-resolution gate INSTEAD of running the turn\n * on the blocked provider — a policy-restricted workspace (e.g. fail-closed to\n * the Codex subscription) must never silently remap to, or fall through to,\n * the paid built-in client. Like CodexSubscriptionUnavailableError the message\n * is user-actionable and surfaces verbatim as a non-retryable turn.failed.\n */\nexport class WorkspaceModelPolicyBlockedError extends Error {\n constructor(modelName: string, providerId: string, reason: \"provider\" | \"model\") {\n super(\n reason === \"provider\"\n ? `Model \"${modelName}\" is not available in this workspace: its provider (\"${providerId}\") is not in the workspace's allowed providers. ` +\n `Pick an allowed model, or ask a workspace admin to change the workspace model policy.`\n : `Model \"${modelName}\" is not in this workspace's allowed models. ` +\n `Pick an allowed model, or ask a workspace admin to change the workspace model policy.`,\n );\n this.name = \"WorkspaceModelPolicyBlockedError\";\n }\n}\n\nexport function configureOpenAI(settings: Settings): void {\n setOpenAIResponsesTransport(settings.openaiResponsesTransport);\n setTracingDisabled(settings.disableOpenaiTracing || !settings.observabilityOtlpEndpoint);\n // Install the registry-aware router as the process default model provider so a\n // model name re-resolved on the SandboxAgent/Modal path (where a Model instance\n // does not survive) routes to its provider instead of the built-in client.\n // Built before the default-client calls below so it captures the same settings.\n const router = new MultiProviderModelProvider(settings);\n if (settings.openaiProvider === \"azure\") {\n setDefaultOpenAIClient(buildOpenAIClientFromSettings(settings));\n setDefaultModelProvider(router);\n return;\n }\n if (settings.openaiApiKey) {\n setDefaultOpenAIKey(settings.openaiApiKey);\n }\n if (settings.openaiBaseUrl) {\n setDefaultOpenAIClient(buildOpenAIClientFromSettings(settings));\n }\n setDefaultModelProvider(router);\n}\n\nfunction instrumentedModelFetch(provider: string, inner: typeof fetch): typeof fetch {\n return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n if (!isModelCallFetch(input)) {\n return await inner(input, init);\n }\n const started = performance.now();\n try {\n const response = await inner(input, init);\n recordModelCallMetric(provider, response.ok ? \"completed\" : \"failed\", started);\n return response;\n } catch (error) {\n recordModelCallMetric(provider, \"failed\", started);\n throw error;\n }\n }) as typeof fetch;\n}\n\nfunction isModelCallFetch(input: Parameters<typeof fetch>[0]): boolean {\n const rawUrl =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.toString()\n : (input as { url?: unknown }).url;\n if (typeof rawUrl !== \"string\" || rawUrl.length === 0) {\n return false;\n }\n try {\n const pathname = new URL(rawUrl, \"http://opengeni.local\").pathname;\n return (\n pathname.endsWith(\"/responses\") ||\n pathname.endsWith(\"/chat/completions\") ||\n pathname.endsWith(\"/codex/responses\")\n );\n } catch {\n return /\\/(?:codex\\/)?responses(?:\\?|$)|\\/chat\\/completions(?:\\?|$)/.test(rawUrl);\n }\n}\n\nfunction recordModelCallMetric(\n provider: string,\n outcome: \"completed\" | \"failed\",\n started: number,\n): void {\n const durationSeconds = Math.max(0, (performance.now() - started) / 1000);\n try {\n runtimeMetricsHooks?.onModelCall?.({ provider, outcome, durationSeconds });\n } catch {\n // Metrics emission must never affect a model call.\n }\n}\n\n/**\n * Run the compaction summarizer as one plain, tool-less, non-streaming model\n * call against the resolved provider. `input` is the active history plus\n * Codex's checkpoint prompt. Provider failures propagate to the compaction\n * lifecycle; there is no non-model fallback that silently discards history.\n * The call deliberately does NOT\n * request reasoning encryption, tools, or inline provider compaction; it is a\n * self-contained summarize.\n *\n * Provider-aware: the summary always runs on the SAME provider that serves the\n * turn (registry providers can't summarize through OpenAI/Azure, and vice\n * versa). `api: \"chat\"` providers (Fireworks) speak /v1/chat/completions, where\n * the summary is choices[0].message.content; `api: \"responses\"` (the default,\n * built-in OpenAI/Azure) speaks /v1/responses as before. When no client/api is\n * supplied it uses the built-in OpenAI/Azure Responses path. store:false is set\n * only on the OpenAI-platform Responses path (Azure rejects it; chat ignores it).\n */\nexport async function summarizeForCompaction(\n settings: Settings,\n input: Array<Record<string, unknown>>,\n options: {\n client?: OpenAI;\n api?: ModelProviderApi;\n maxOutputTokens?: number;\n model?: string;\n promptCacheKey?: string;\n systemInstructions?: string;\n onUsage?: (usage: ModelResponseUsage) => void | Promise<void>;\n } = {},\n): Promise<string> {\n const client = options.client ?? buildOpenAIClientFromSettings(settings);\n const api = options.api ?? \"responses\";\n const model = options.model ?? settings.openaiModel;\n const maxTokens = options.maxOutputTokens ?? SUMMARY_BUFFER_TOKENS;\n if (api === \"chat\") {\n const transcript = renderCompactionPromptInputForChat(input);\n let completion: unknown;\n try {\n completion = await client.chat.completions.create({\n model,\n max_tokens: maxTokens,\n messages: [{ role: \"user\", content: transcript }],\n ...(options.promptCacheKey ? { prompt_cache_key: options.promptCacheKey } : {}),\n } as any);\n } catch (error) {\n throw new CompactionProviderResponseError(compactionProviderFailureDiagnostics(error), error);\n }\n const usage = modelResponseUsageFromResponse(completion);\n if (usage) {\n await options.onUsage?.(usage);\n }\n const text = (completion as { choices?: Array<{ message?: { content?: unknown } }> })\n .choices?.[0]?.message?.content;\n const summary = typeof text === \"string\" ? text.trim() : \"\";\n if (!summary) {\n throw new EmptyCompactionSummaryError(compactionResponseDiagnostics(completion, summary));\n }\n return summary;\n }\n // Use the same SDK Responses adapter as the real agent call. It converts the\n // structured AgentInputItems (callId/providerData/etc.) to provider wire\n // items without flattening tool history into a fake user transcript.\n const request: ModelRequest = {\n systemInstructions: options.systemInstructions ?? \"\",\n input: input as AgentInputItem[],\n modelSettings: {\n maxTokens,\n // Azure rejects store:false; the Codex subscription transport enforces\n // it independently. The OpenAI platform path remains explicitly storeless.\n ...(settings.openaiProvider === \"azure\" ? {} : { store: false }),\n ...(options.promptCacheKey\n ? { providerData: { prompt_cache_key: options.promptCacheKey } }\n : {}),\n },\n tools: [],\n toolsExplicitlyProvided: true,\n outputType: \"text\",\n handoffs: [],\n tracing: false,\n };\n let response: unknown;\n try {\n response = await new CompactionResponsesModel(client, model).fetchResponse(request);\n } catch (error) {\n throw new CompactionProviderResponseError(compactionProviderFailureDiagnostics(error), error);\n }\n const usage = modelResponseUsageFromResponse(response);\n if (usage) {\n await options.onUsage?.(usage);\n }\n if (isFailedCompactionProviderResponse(response)) {\n throw new CompactionProviderResponseError(compactionProviderFailureDiagnostics(response));\n }\n const summary = extractResponseOutputText(response).trim();\n if (!summary) {\n throw new EmptyCompactionSummaryError(compactionResponseDiagnostics(response, summary));\n }\n return summary;\n}\n\nfunction isFailedCompactionProviderResponse(response: unknown): boolean {\n if (!response || typeof response !== \"object\") return false;\n const record = response as Record<string, unknown>;\n return (\n record.status === \"failed\" ||\n record.status === \"incomplete\" ||\n (record.error !== null && record.error !== undefined)\n );\n}\n\n/** Bounded provider diagnostics: identifiers and classifications, never messages or model data. */\nexport function compactionProviderFailureDiagnostics(error: unknown): Record<string, unknown> {\n let current = error;\n let errorName: string | null = null;\n let httpStatus: number | null = null;\n let responseStatus: string | null = null;\n let responseId: string | null = null;\n let code: string | null = null;\n let type: string | null = null;\n let requestId: string | null = null;\n let eventType: string | null = null;\n const seen = new Set<object>();\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 record = current as Record<string, unknown>;\n if (!errorName && current instanceof Error) {\n errorName = boundCompactionDiagnosticField(current.name);\n }\n if (\n httpStatus === null &&\n typeof record.status === \"number\" &&\n Number.isFinite(record.status)\n ) {\n httpStatus = record.status;\n }\n if (responseStatus === null && typeof record.status === \"string\") {\n responseStatus = boundCompactionDiagnosticField(record.status);\n }\n const directResponseStatus = record.response_status ?? record.responseStatus;\n if (responseStatus === null && typeof directResponseStatus === \"string\") {\n responseStatus = boundCompactionDiagnosticField(directResponseStatus);\n }\n const directResponseId = record.response_id ?? record.responseId ?? record.id;\n if (responseId === null && typeof directResponseId === \"string\") {\n responseId = boundCompactionDiagnosticField(directResponseId);\n }\n if (code === null && typeof record.code === \"string\") {\n code = boundCompactionDiagnosticField(record.code);\n }\n if (type === null && typeof record.type === \"string\") {\n type = boundCompactionDiagnosticField(record.type);\n }\n const directEventType = record.event_type ?? record.eventType;\n if (eventType === null && typeof directEventType === \"string\") {\n eventType = boundCompactionDiagnosticField(directEventType);\n }\n if (requestId === null) {\n const directRequestId = record.request_id ?? record.requestId ?? record._request_id;\n if (typeof directRequestId === \"string\") {\n requestId = boundCompactionDiagnosticField(directRequestId);\n }\n const headers = record.headers;\n if (!requestId && headers && typeof headers === \"object\") {\n const get = (headers as { get?: unknown }).get;\n if (typeof get === \"function\") {\n const headerId = get.call(headers, \"x-request-id\");\n if (typeof headerId === \"string\") {\n requestId = boundCompactionDiagnosticField(headerId);\n }\n }\n }\n }\n const nestedError = record.error;\n if (nestedError && typeof nestedError === \"object\" && !seen.has(nestedError)) {\n const nested = nestedError as Record<string, unknown>;\n if (code === null && typeof nested.code === \"string\") {\n code = boundCompactionDiagnosticField(nested.code);\n }\n if (type === null && typeof nested.type === \"string\") {\n type = boundCompactionDiagnosticField(nested.type);\n }\n const nestedResponseStatus = nested.response_status ?? nested.responseStatus;\n if (responseStatus === null && typeof nestedResponseStatus === \"string\") {\n responseStatus = boundCompactionDiagnosticField(nestedResponseStatus);\n }\n const nestedResponseId = nested.response_id ?? nested.responseId ?? nested.id;\n if (responseId === null && typeof nestedResponseId === \"string\") {\n responseId = boundCompactionDiagnosticField(nestedResponseId);\n }\n const nestedEventType = nested.event_type ?? nested.eventType;\n if (eventType === null && typeof nestedEventType === \"string\") {\n eventType = boundCompactionDiagnosticField(nestedEventType);\n }\n }\n current = record.cause;\n }\n return {\n errorName,\n httpStatus,\n responseStatus,\n responseId,\n code,\n type,\n requestId,\n ...(eventType ? { eventType } : {}),\n };\n}\n\nconst COMPACTION_DIAGNOSTIC_FIELD_MAX_BYTES = 256;\nconst COMPACTION_DIAGNOSTIC_TRUNCATION_MARKER = \"…[truncated]\";\n\nfunction boundCompactionDiagnosticField(value: string): string {\n const bytes = Buffer.from(value, \"utf8\");\n if (bytes.length <= COMPACTION_DIAGNOSTIC_FIELD_MAX_BYTES) return value;\n const markerBytes = Buffer.byteLength(COMPACTION_DIAGNOSTIC_TRUNCATION_MARKER, \"utf8\");\n let end = COMPACTION_DIAGNOSTIC_FIELD_MAX_BYTES - markerBytes;\n while (end > 0 && isUtf8ContinuationByte(bytes[end]!)) end -= 1;\n return `${bytes.subarray(0, end).toString(\"utf8\")}${COMPACTION_DIAGNOSTIC_TRUNCATION_MARKER}`;\n}\n\nfunction isUtf8ContinuationByte(value: number): boolean {\n return (value & 0xc0) === 0x80;\n}\n\n/** Bounded, content-free diagnostics for a semantically empty checkpoint. */\nexport function compactionResponseDiagnostics(\n response: unknown,\n extractedText = extractResponseOutputText(response).trim(),\n): Record<string, unknown> {\n if (!response || typeof response !== \"object\") {\n return { responseShape: typeof response, extractedTextLength: extractedText.length };\n }\n const record = response as Record<string, unknown>;\n const output = Array.isArray(record.output) ? record.output : [];\n const outputItems = output.slice(0, 50).map((item) => {\n if (!item || typeof item !== \"object\") return { type: typeof item };\n const value = item as Record<string, unknown>;\n const content = Array.isArray(value.content) ? value.content : [];\n return {\n type: typeof value.type === \"string\" ? value.type : null,\n role: typeof value.role === \"string\" ? value.role : null,\n status: typeof value.status === \"string\" ? value.status : null,\n contentPartTypes: content\n .slice(0, 50)\n .map((part) =>\n part && typeof part === \"object\" && typeof (part as { type?: unknown }).type === \"string\"\n ? (part as { type: string }).type\n : typeof part,\n ),\n contentPartCount: content.length,\n };\n });\n const choices = Array.isArray(record.choices) ? record.choices : [];\n const usage = modelResponseUsageFromResponse(response)?.usage;\n const incomplete =\n record.incomplete_details && typeof record.incomplete_details === \"object\"\n ? (record.incomplete_details as Record<string, unknown>)\n : null;\n return {\n responseId: typeof record.id === \"string\" ? record.id : null,\n status: typeof record.status === \"string\" ? record.status : null,\n outputItemCount: output.length,\n outputItems,\n choiceCount: choices.length,\n finishReasons: choices\n .slice(0, 20)\n .map((choice) =>\n choice && typeof choice === \"object\"\n ? ((choice as Record<string, unknown>).finish_reason ?? null)\n : null,\n ),\n incompleteReason:\n incomplete && typeof incomplete.reason === \"string\" ? incomplete.reason : null,\n inputTokens: usage?.inputTokens ?? null,\n outputTokens: usage?.outputTokens ?? null,\n totalTokens: usage?.totalTokens ?? null,\n extractedTextLength: extractedText.length,\n };\n}\n\n/**\n * Pull the assistant text out of a Responses API result, shape-tolerant. Only\n * `role === \"assistant\"` message items contribute: a provider whose Responses\n * endpoint echoes the user input back as an output `message` item (Fireworks'\n * beta /v1/responses does exactly this — see docs/model-providers.md) would\n * otherwise corrupt the summary with the prompt it was given. The OpenAI/Azure\n * Responses API only emits assistant messages, so this guard is a no-op there.\n */\nexport function extractResponseOutputText(response: unknown): string {\n if (!response || typeof response !== \"object\") {\n return \"\";\n }\n const direct = (response as { output_text?: unknown }).output_text;\n if (typeof direct === \"string\") {\n return direct;\n }\n const output = (response as { output?: unknown }).output;\n if (!Array.isArray(output)) {\n return \"\";\n }\n const parts: string[] = [];\n for (const item of output) {\n if (!item || typeof item !== \"object\") {\n continue;\n }\n if ((item as { type?: unknown }).type !== \"message\") {\n continue;\n }\n // Read assistant messages only; skip any input-echo (role \"user\"/\"system\").\n if ((item as { role?: unknown }).role !== \"assistant\") {\n continue;\n }\n const content = (item as { content?: unknown }).content;\n if (!Array.isArray(content)) {\n continue;\n }\n for (const part of content) {\n if (\n part &&\n typeof part === \"object\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n parts.push((part as { text: string }).text);\n }\n }\n }\n return parts.join(\"\");\n}\n\n/**\n * The public SDK getResponse() method is runner-facing and always opens a\n * tracing span. Compaction is a standalone model call, so use the same SDK\n * request conversion and Responses transport without manufacturing a runner\n * trace solely to satisfy that wrapper.\n */\nclass CompactionResponsesModel extends OpenAIResponsesModel {\n fetchResponse(request: ModelRequest) {\n return this._fetchResponse(request, false);\n }\n}\n\nexport type GitTokenSeeds = Partial<Record<GitCredentialProvider, string>>;\nexport type GitCredentialBindingSeed = {\n credentialBindingId: string;\n provider: GitCredentialProvider;\n token: string;\n transport?: GitCredentialTransport;\n expiresAt?: string;\n /** Total active bindings for this provider, used to suppress unsafe aliases. */\n providerBindingCount?: number;\n};\nexport type GitCredentialTokenWriterSession = SandboxSessionLike;\nexport type ToolspaceTokenWriterSession = SandboxSessionLike;\n\nexport type EffectiveSkillSelection = Readonly<{\n id: string;\n name: string;\n source: \"bundled\" | \"library\" | \"pack\" | \"session\";\n version: string | null;\n contentSha256: string | null;\n reason: string;\n}>;\n\nconst agentSkillSelections = new WeakMap<object, readonly EffectiveSkillSelection[]>();\nconst emptySkillSelections: readonly EffectiveSkillSelection[] = Object.freeze([]);\n\n/**\n * Read-only, secret-free skill provenance for an already-built agent. This is\n * intentionally separate from the model instructions and sandbox manifest so\n * effective configuration inspection cannot accidentally expose credentials or\n * turn skill activation into an authorization change.\n */\nexport function effectiveSkillSelectionsForAgent(\n agent: object,\n): readonly EffectiveSkillSelection[] {\n return agentSkillSelections.get(agent) ?? emptySkillSelections;\n}\n\nexport type BuildAgentOptions = {\n model?: Model;\n /** Settled response for the one internal human-input interruption resumed by this run. */\n humanInputResponse?: {\n requestId: string;\n toolCallId: string;\n response: HumanInputResponse;\n };\n reasoningEffort?: ReasoningEffort;\n // Per-turn gating overrides for the multi-provider path. Each defaults to\n // today's settings-derived behaviour when omitted, so the legacy\n // global-client callers (no model resolution) are byte-for-byte unchanged.\n //\n // - hostedWebSearch: attach the hosted web_search tool. Only the providers\n // that actually execute it (built-in OpenAI/Azure; a registry model that\n // opts in) should get it — Fireworks accepts the param but no-ops it, which\n // would hand the agent a dead tool. Default: settings.webSearchEnabled.\n // - encryptedReasoning: round-trip reasoning.encrypted_content via\n // providerData.include. Only the Responses API carries it; the chat wire\n // API has no such field, so registry \"chat\" providers turn it off.\n // Default: settings.openaiReasoningEncryptedContent.\n // - structuredToolTransport: whether the backend supports the Responses\n // STRUCTURED/HOSTED sandbox-tool transport — the hosted `apply_patch` tool\n // type and structured `view_image` output. The SDK's sandbox capabilities\n // pick hosted-vs-function purely from the bound model instance's constructor\n // name (supportsApplyPatchTransport / supportsStructuredToolOutputTransport).\n // Our codex turns run the OpenAIResponsesModel — which the SDK reads as\n // hosted-capable — but route it to the ChatGPT/Codex backend, which REJECTS\n // the hosted `apply_patch` type (\"Unsupported tool type: apply_patch\",\n // verified live). Set false for that backend so filesystem emits the\n // function `apply_patch` + text `view_image` variants it accepts. Default\n // true (let the SDK decide from the model instance) — non-codex paths are\n // byte-for-byte unchanged.\n hostedWebSearch?: boolean;\n encryptedReasoning?: boolean;\n structuredToolTransport?: boolean;\n // EXPLICIT computer-use tool transport, decided where provider identity is\n // authoritative (the worker's model resolution — agent-turn.ts). Threaded into\n // buildAgentCapabilities → computerUse({toolMode}) so tool selection never rests\n // on the SDK's constructor-name sniff. When omitted, the legacy sniff +\n // `structuredToolTransport` neutralize path is preserved byte-for-byte.\n computerToolMode?: ComputerToolMode;\n /**\n * Invoked once, immediately before the first real computer action and after\n * the display is ready. Merely advertising computer-use does not call it.\n * The worker uses this seam for computer-use-only recording; ordinary\n * shell/filesystem turns never pay that cost.\n */\n onComputerUseReady?: (session: SandboxSessionLike) => Promise<void>;\n // The LIVE, by-reference connector-namespace Set from prepareAgentTools\n // (codexConnectorNamespaces): fills during each turn's codex_apps tools/list,\n // read per model call by the codex tool_search description so the model sees\n // the account's ACTUALLY-connected sources (codex-rs parity). Only meaningful\n // on the codex tool-search path.\n codexConnectorNamespaces?: ReadonlySet<string>;\n // Stable per-session routing key for provider-side prompt prefix caches. The\n // worker passes this only for transports whose docs/API surface accept\n // prompt_cache_key; registry providers that use a different affinity field stay\n // unset to avoid unknown-parameter 400s.\n promptCacheKey?: string;\n sandboxEnvironment?: Record<string, string>;\n // The EFFECTIVE/active compute backend for this turn. `settings.sandboxBackend`\n // is the session's HOME backend (the default cloud group box it was created\n // with); when a session has swapped its active sandbox to a connected machine\n // (active_sandbox_id → a selfhosted lease, while the home backend stays the\n // cloud default), the worker passes that machine's backend here so\n // filesystem-touching lifecycle hooks key off where the agent ACTUALLY runs,\n // not where it was created. The one such hook today is the repository clone\n // (sandboxRepositoryCloneHooks): a bring-your-own machine owns its real disk,\n // so the platform must NEVER `git clone` onto it. Defaults to\n // settings.sandboxBackend, so the legacy cloud paths are byte-for-byte\n // unchanged and a session whose HOME backend is \"selfhosted\" is gated with no\n // caller change.\n activeSandboxBackend?: Settings[\"sandboxBackend\"];\n fileResourceDownloads?: SandboxFileDownload[];\n mcpServers?: MCPServer[];\n // Workspace Memory V1 working-set block, resolved by the worker per turn.\n // Composed after the workspace persona/CORE/toolspace substrate and before\n // per-session instructions. Omitted/blank ⇒ byte-identical instructions.\n workspaceMemory?: string;\n workspaceEnvironment?: WorkspaceEnvironmentContext;\n // M3 rig runtime binding (all absent ⇒ a rig-less turn, byte-for-byte today).\n // - `rig`: renders the non-bypassable rig doctrine block in the CORE.\n // - `rigSetup`: the rig version's setup script, run ONCE per box (marker-\n // guarded) as the FIRST beforeAgentStart hook so later hooks see its tooling.\n // - `rigCredentialHookIds`: the rig version's credential_hooks, unioned with\n // the deployment preparation-profile hooks. Resolved (and VALIDATED — an\n // unknown name throws here, at build = per-turn resolution time) so a typo'd\n // hook fails the turn instead of being silently ignored.\n rig?: RigInstructionsContext;\n rigSetup?: RigSetupDescriptor;\n rigCredentialHookIds?: string[];\n // TOKEN-BROKER (B1): the run-scoped GitHub App installation token alias,\n // minted ONCE per turn by the worker (sandboxEnvironmentForRun's `gitToken`).\n // Kept for back-compat; internally it maps to gitTokenSeeds.github.\n gitTokenSeed?: string;\n // Provider-token map for GitHub/GitLab/Azure DevOps. Threaded here OFF-\n // MANIFEST — it is NOT part of sandboxEnvironment (the manifest env), so token\n // VALUES never trigger the SDK's provided-session env-delta guard even though\n // they rotate every turn. buildAgent stashes them alongside the agent's\n // repository-clone hooks; runStream forwards them into the hook context, which\n // seeds provider token FILES before the clone/setup runs.\n gitTokenSeeds?: GitTokenSeeds;\n // Provider-neutral, independently mintable credentials. Binding ids remain\n // off-manifest and are hashed before they influence sandbox paths.\n gitCredentialBindings?: GitCredentialBindingSeed[];\n // TOOLSPACE: the run-scoped delegated token to seed into\n // $OPENGENI_TOOLSPACE_TOKEN_FILE. Like gitTokenSeed, this stays off the\n // manifest/env delta and is written into the sandbox filesystem by a lifecycle\n // hook before the agent starts.\n toolspaceTokenSeed?: string;\n // Durable OpenGeni session identity used only to derive the off-manifest,\n // per-session token file. Required together with toolspaceTokenSeed so two\n // sessions sharing one box never overwrite the same pointer.\n toolspaceTokenSessionId?: string;\n // Genesis turn only: inject a one-shot instruction into the FIRST model\n // call telling it to title the session via opengeni__set_session_title.\n // Keeping this out of the persistent Agent.instructions prevents every\n // tool-follow-up model call in a long first turn from re-running setup.\n genesisTitleHint?: boolean;\n // Persistent session settings, resolved by the worker from the durable\n // session row at turn start. Tool schemas are rebuilt on every turn, so\n // without this factual state the model can mistake persistent metadata tools\n // for per-turn initialization and re-apply the same title/notification mode.\n // Values only — never the user-controlled title text — enter instructions.\n persistentSessionSettings?: PersistentSessionSettings;\n // Per-call agent persona override (the white-label surface). Resolved by the\n // caller as session > workspace > deployment default; when omitted the\n // runtime falls back to settings.agentInstructionsTemplate. The runtime\n // substitutes the non-bypassable CORE at AGENT_INSTRUCTIONS_CORE_PLACEHOLDER\n // (or appends it when the template omits the marker), so an override can\n // restyle the persona but never drop the goal-loop contract or environment\n // block.\n instructionsTemplate?: string;\n // Per-SESSION persona/system instructions (the per-agent-type prompt lever an\n // embedding host supplies at session create). Composed AFTER the workspace\n // instructionsTemplate + the non-bypassable CORE, so it refines the workspace\n // persona for this one session without dropping the goal-loop/environment\n // contract. Rides the SAME instructions channel (system-level) — NEVER a user/\n // timeline message. Omitted ⇒ the composed instructions are byte-identical to\n // a workspace-only persona.\n sessionInstructions?: string;\n // Host context for this exact accepted turn. Composed system-level after the\n // durable session persona and omitted from all later turns.\n turnInstructions?: string;\n // Skills delivered by enabled capability packs. They join the bundled\n // skills in the sandbox skill index (mounted under .agents/) so\n // skills/<name> references resolve like any other indexed skill.\n packSkills?: PackSkill[];\n // Inline skills fixed onto this session at creation. They use the SDK's lazy\n // skill source and are materialized only when the model loads one.\n sessionSkills?: PackSkill[];\n // Explicitly selected, immutable curated-library skill content. These are\n // separate from packSkills so repository-local/pack compatibility does not\n // turn a curated entry into a mutable override.\n skillLibrarySkills?: PackSkill[];\n // Secret-free provenance for effective-configuration inspection. The worker\n // resolves exact ids/versions/hashes before constructing the agent.\n skillLibrarySelections?: EffectiveSkillSelection[];\n /**\n * Internal per-attempt cancellation boundary. The worker supplies Temporal's\n * signal so an in-flight shell process is interrupted immediately instead of\n * holding Steer/Pause behind its requested yield or natural exit.\n */\n turnCancellationSignal?: AbortSignal;\n /**\n * Receives the physical sandbox-tool fence at agent construction time. A\n * cancelled/fenced worker attempt must await it before publishing its durable\n * attempt-quiesced receipt.\n */\n onToolCancellationFence?: (fence: TurnToolCancellationFence) => void;\n};\n\nexport type PackSkillFile = {\n // Relative POSIX path inside the skill directory, e.g. \"SKILL.md\" or\n // \"references/runbook.md\".\n path: string;\n content: string;\n};\n\nexport type PackSkill = {\n name: string;\n description?: string | null | undefined;\n files: PackSkillFile[];\n};\n\n/**\n * Operator-facing metadata for the workspace environment attached to a run.\n * Surfaced verbatim in the agent instructions: the description is where\n * operators document how the exported credentials are meant to be used\n * (e.g. which variable holds a deploy key and how to clone with it), so an\n * agent must not have to rediscover that by enumerating `env` and guessing.\n * Only metadata belongs here — never variable values.\n */\nexport type WorkspaceEnvironmentContext = {\n name: string;\n description?: string | null;\n variableNames?: string[];\n};\n\nexport type PersistentSessionSettings = {\n titleIsSet: boolean;\n};\n\n/**\n * The rig a session rides (M3): its name + the active version pinned onto the\n * session. Surfaced verbatim in the non-bypassable CORE instructions so the\n * agent understands its sandbox is a disposable fork of a shared, versioned\n * machine definition and how to promote a durable change. Absent for rig-less\n * sessions (the block never renders).\n */\nexport type RigInstructionsContext = {\n name: string;\n version: number;\n};\n\nexport function rigInstructions(rig: RigInstructionsContext): string[] {\n return [\n `This session runs on rig \"${rig.name}\" (active version v${rig.version}) — a shared, versioned sandbox machine definition for your workspace.`,\n \"Your sandbox is an EPHEMERAL FORK of that rig: you have root and may install anything freely, but everything you change here is junk that dies with the box and never reaches the rig or other sessions.\",\n \"For a DURABLE, team-wide change (tooling every future session on this rig should have), propose it with rig_propose_change, passing the EXACT command that already worked in this box — never assume an unverified change propagates.\",\n \"If tooling you expect is missing, consult rig_get to see the rig's current setup and checks before reinstalling.\",\n ];\n}\n\nexport function workspaceEnvironmentInstructions(\n environment: WorkspaceEnvironmentContext,\n): string[] {\n const lines = [\n `A workspace environment named \"${environment.name}\" is attached to this session; its variables are exported in the sandbox shell environment.`,\n ];\n const variableNames = (environment.variableNames ?? []).filter((name) => name.length > 0);\n if (variableNames.length > 0) {\n lines.push(`Exported environment variables: ${[...variableNames].sort().join(\", \")}.`);\n }\n const description = environment.description?.trim();\n if (description) {\n lines.push(`Environment notes from the operator: ${description}`);\n }\n return lines;\n}\n\n/**\n * The non-bypassable CORE of the agent instructions: the goal-loop ownership\n * line (which names the opengeni__goal_* tools and is what keeps a long-running\n * session driving itself) followed by the dynamic workspace-environment block.\n * Returned as ordered lines so the caller joins them with the rest of the\n * instructions by \" \", exactly as the historical preamble did.\n *\n * This is the slice a white-labelled persona template must never be able to\n * drop: composeAgentInstructions() substitutes it at the persona template's\n * {{core}} marker, and appends it when the marker is absent.\n */\nexport function coreInstructions(\n workspaceEnvironment?: WorkspaceEnvironmentContext,\n rig?: RigInstructionsContext,\n): string[] {\n return [\n \"If the session has a goal, you own it: keep working until you call opengeni__goal_complete with concrete evidence or opengeni__goal_pause with a rationale; revise it with opengeni__goal_update; create one with opengeni__goal_set when given a long-running objective.\",\n ...(workspaceEnvironment ? workspaceEnvironmentInstructions(workspaceEnvironment) : []),\n // Rig doctrine (M3): data-conditional, inside the non-bypassable CORE so a\n // white-label persona template can never drop it. Absent for rig-less sessions.\n ...(rig ? rigInstructions(rig) : []),\n ];\n}\n\n/**\n * Composes the final agent instructions from a (possibly white-labelled)\n * persona template and the non-bypassable CORE. The CORE is substituted at the\n * template's {{core}} marker; if the template omits the marker, the CORE is\n * appended after it instead (the non-bypassable fail-safe). The substitution\n * and the append both join by \" \", so the DEFAULT_AGENT_INSTRUCTIONS template\n * with an empty environment reproduces the historical preamble byte-for-byte.\n */\nexport function composeAgentInstructions(\n template: string,\n workspaceEnvironment?: WorkspaceEnvironmentContext,\n rig?: RigInstructionsContext,\n): string {\n const core = coreInstructions(workspaceEnvironment, rig).join(\" \");\n if (template.includes(AGENT_INSTRUCTIONS_CORE_PLACEHOLDER)) {\n return template.split(AGENT_INSTRUCTIONS_CORE_PLACEHOLDER).join(core);\n }\n return core ? `${template} ${core}` : template;\n}\n\n/**\n * Appends the per-session persona instructions to the already-composed\n * (workspace + CORE) instructions, joined by \" \" — exactly the join used\n * throughout the persona composition. The session slice is intentionally LAST\n * (session-specific refinement of the workspace persona). An absent/blank value\n * is a no-op that returns the composed string byte-for-byte.\n */\nexport function appendSessionInstructions(composed: string, sessionInstructions?: string): string {\n const trimmed = sessionInstructions?.trim();\n return trimmed ? `${composed} ${trimmed}` : composed;\n}\n\n/** Append system instructions that apply to this exact turn only. */\nexport function appendTurnInstructions(composed: string, turnInstructions?: string): string {\n const trimmed = turnInstructions?.trim();\n return trimmed ? `${composed} ${trimmed}` : composed;\n}\n\n/**\n * Append the durable session metadata the model otherwise cannot observe.\n * This is deliberately declarative and excludes the title text: the title is\n * user-controlled display metadata, while the agent only needs to know whether\n * initialization has already happened. The block is present on every turn when\n * supplied so compaction cannot erase knowledge that these settings persist.\n */\nexport function appendPersistentSessionSettings(\n composed: string,\n settings?: PersistentSessionSettings,\n): string {\n if (!settings) {\n return composed;\n }\n return `${composed} Persistent session settings already in effect: the display title is ${settings.titleIsSet ? \"set\" : \"not set\"}. This setting persists across turns, continuations, and interruptions. Do not call opengeni__set_session_title merely to reassert an unchanged value; call it only when the current value actually needs to change.`;\n}\n\n/**\n * Appends the workspace memory working-set block to the already-composed\n * (workspace + CORE + generic substrate) instructions, joined by \" \". The\n * memory slice is workspace-ground and intentionally lands before\n * per-session instructions. An absent/blank value is a no-op that returns the\n * composed string byte-for-byte.\n */\nexport function appendWorkspaceMemory(composed: string, workspaceMemory?: string): string {\n const trimmed = workspaceMemory?.trim();\n return trimmed ? `${composed} ${trimmed}` : composed;\n}\n\n/**\n * Appends the generic programmatic-tool-calling (toolspace) directive to the\n * composed workspace + CORE instructions, joined by \" \". This is GENERIC\n * substrate prompting — the same text for every host, never per-host copy.\n *\n * Included ONLY when `toolspaceAvailable` is true, which the caller sets from the\n * exact condition that gates the sandbox token mint: the toolspace feature is\n * enabled AND a toolspace token was minted for THIS turn. That mint now happens\n * on every backend including selfhosted (connected machines get the token too),\n * so the block appears there as well; a turn with no minted token (feature off)\n * has no toolspace URL/token in its sandbox and must not advertise a capability\n * that is not there — the gate is false and this is a no-op. Placed BEFORE the\n * per-session instructions so host/session specificity still wins over this\n * substrate note.\n */\nexport function appendToolspaceInstructions(composed: string, toolspaceAvailable: boolean): string {\n return toolspaceAvailable ? `${composed} ${TOOLSPACE_PROGRAMMATIC_DIRECTIVE}` : composed;\n}\n\nconst GIT_BINDING_DISCOVERY_DIRECTIVE =\n \"This managed sandbox has multiple credential bindings for at least one Git provider. Native Git selects credentials from the repository remote. For gh, glab, or az, run inside the intended attached repository so its origin selects the binding; when running elsewhere, inspect $HOME/.opengeni/git-bindings.json and set OPENGENI_GIT_BINDING to the listed credentialBindingId. The inventory contains identifiers and repository routes, never credential values. A binding marked git_http_broker is Git-only, so use the configured provider MCP tools for provider API operations on it.\";\n\n/**\n * Make multi-account provider-CLI selection discoverable to the model.\n *\n * Binding ids are opaque routing identifiers, not credentials. The detailed,\n * secret-free repository mapping is materialized in the sandbox by the Git\n * setup hook so prompts stay compact.\n */\nexport function appendGitCredentialBindingInstructions(\n composed: string,\n bindings: GitCredentialBindingSeed[] | undefined,\n activeSandboxBackend?: Settings[\"sandboxBackend\"],\n): string {\n if (activeSandboxBackend === \"selfhosted\" || !bindings?.length) {\n return composed;\n }\n const bindingsByProvider = new Map<GitCredentialProvider, Set<string>>();\n for (const binding of bindings) {\n const ids = bindingsByProvider.get(binding.provider) ?? new Set<string>();\n ids.add(binding.credentialBindingId);\n bindingsByProvider.set(binding.provider, ids);\n }\n return [...bindingsByProvider.values()].some((ids) => ids.size > 1)\n ? `${composed} ${GIT_BINDING_DISCOVERY_DIRECTIVE}`\n : composed;\n}\n\n/**\n * Appends the one-shot genesis title directive (genesis turn only), joined by\n * \" \" and always LAST so a white-label persona template or a per-session\n * instruction can't drop it. A no-op when the hint is absent.\n */\nexport function appendGenesisTitleDirective(\n instructions: string,\n genesisTitleHint?: boolean,\n): string {\n return genesisTitleHint ? `${instructions} ${GENESIS_TITLE_DIRECTIVE}` : instructions;\n}\n\nconst agentFileDownloads = new WeakMap<object, SandboxFileDownload[]>();\nconst agentRepositoryCloneHooks = new WeakMap<object, SandboxLifecycleHook[]>();\n// TOKEN-BROKER (B1): the per-turn provider git token seeds, stashed alongside\n// the agent's repository-clone hooks (a parallel map keyed by the agent). Kept\n// OFF the manifest/defaultManifest so rotating values never ride the SDK's\n// provided-session env; runStream reads them to build the clone hook context.\n// Absent when no brokered repo is attached / on the selfhosted path.\nconst agentGitTokenSeeds = new WeakMap<object, GitTokenSeeds>();\nconst agentGitCredentialBindings = new WeakMap<object, GitCredentialBindingSeed[]>();\nconst agentToolspaceTokenSeed = new WeakMap<object, string>();\nconst agentToolspaceTokenSessionId = new WeakMap<object, string>();\n// A genesis directive is consumed by runAgentStream exactly once for the\n// freshly-built agent. It must not remain in Agent.instructions: those\n// instructions are presented again on every internal model/tool loop.\nconst agentsNeedingGenesisTitleDirective = new WeakSet<object>();\n// The EFFECTIVE backend the turn resolved for this agent (undefined -> the home\n// backend). Read by runStream's owned branch to keep platform box-setup hooks off\n// connected machines (a user's real computer).\nconst agentActiveSandboxBackend = new WeakMap<object, Settings[\"sandboxBackend\"]>();\n// M3: the rig-setup descriptor + resolved rig credential hooks for this agent's\n// turn (kept off the manifest like the clone hooks). Read by runStream to build\n// the rig-setup hook and to union the rig credential hooks with the deployment\n// preparation-profile hooks. Absent for a rig-less turn.\nconst agentRigSetup = new WeakMap<object, RigSetupDescriptor>();\nconst agentRigCredentialHooks = new WeakMap<object, SandboxLifecycleHook[]>();\n\n/**\n * The tool output emitted for an MCP tool call that FAILED with a THROWN error\n * — a JSON-RPC protocol error (e.g. -32602 invalid params), an auth 401/403, a\n * transport failure, a timeout, or tool-not-found. Shaped as an MCP\n * `{ isError: true, content }` result so the failure is CARRIED on the tool\n * output rather than erased.\n *\n * The SDK's `defaultToolErrorFunction` would instead turn a thrown tool error\n * into a plain STRING (\"An error occurred while running the tool…\") returned as\n * a NORMAL, successful-looking result — so `agent.toolCall.output` carried no\n * error signal and the timeline rendered the failure as success. `normalizeSdkEvent`\n * captures `RunToolCallOutputItem.output` (the raw function return) verbatim, so\n * returning this object makes the emitted payload's `output.isError === true`,\n * which the timeline projection's `isErrorOutput` (packages/react/src/timeline/\n * projection.ts) settles to \"failed\" and downstream client normalizers read the same field.\n *\n * SCOPE: this only covers THROWN MCP failures (the ones that reach an\n * errorFunction). An MCP tool result carrying `isError: true` INLINE alongside\n * content is stripped to its `content` by @openai/agents-core's streamable-http\n * shim (dist/shims/mcp-server/node.js `callTool` returns `parsed.content`,\n * dropping `parsed.isError`) BEFORE the runtime ever sees it. Covering that mode\n * requires an SDK-level change (preserve `isError`) or reading the raw\n * CallToolResult — tracked separately.\n */\nexport function mcpToolErrorOutput(error: unknown): {\n isError: true;\n content: [{ type: \"text\"; text: string }];\n} {\n const details = redactSensitiveText(error instanceof Error ? error.message : String(error));\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `An error occurred while running the tool. Please try again. Error: ${details}`,\n },\n ],\n };\n}\n\n// Applied to EVERY MCP server via the agent's `mcpConfig.errorFunction`\n// (server-level errorFunctions would win, but PrefixedMcpServer sets none). The\n// SDK types the return as `string`; the runtime actually stores the raw return\n// as the tool output, so we return the MCP-shaped error object and cast — this\n// is the only way to attach an `isError` flag to a failed MCP tool call's output.\nconst mcpToolErrorFunction: MCPToolErrorFunction = ({ error }) =>\n mcpToolErrorOutput(error) as unknown as string;\n\nexport function buildOpenGeniAgent(\n settings: Settings,\n resources: ResourceRef[],\n options: BuildAgentOptions = {},\n): Agent<any, any> {\n if (Boolean(options.toolspaceTokenSeed) !== Boolean(options.toolspaceTokenSessionId)) {\n throw new Error(\"toolspaceTokenSeed and toolspaceTokenSessionId must be supplied together\");\n }\n // Resolved per-turn gating. Each override defaults to today's settings-derived\n // behaviour, so the legacy global-client callers (no resolved model) build the\n // exact same agent as before; the multi-provider worker path passes the\n // resolved provider's api/window/web-search instead.\n const hostedWebSearch = options.hostedWebSearch ?? settings.webSearchEnabled;\n const encryptedReasoning = options.encryptedReasoning ?? settings.openaiReasoningEncryptedContent;\n const providerData = {\n ...(encryptedReasoning ? { include: [\"reasoning.encrypted_content\"] } : {}),\n ...(options.promptCacheKey ? { prompt_cache_key: options.promptCacheKey } : {}),\n };\n // Native hosted tools attached to every constructed agent. webSearchEnabled\n // is ON by default and provider-unconditional on the built-in path (the live\n // Azure Responses path executes the hosted web_search tool); a registry model\n // only gets it when it opts in (resolved via options.hostedWebSearch), since\n // a provider that no-ops the param would hand the agent a dead tool. The SDK\n // merges this explicit `tools` array with the MCP-server tools\n // (Agent.getAllTools = [...mcpTools, ...tools]) and, on the SandboxAgent path,\n // with the sandbox capability tools (prepareSandboxAgent: tools =\n // [...agent.tools, ...capability.tools()]), so hosted web_search coexists with\n // both rather than overriding them.\n const hostedTools = hostedWebSearch ? [webSearchTool()] : [];\n const humanInputTool = agentTool({\n name: HUMAN_INPUT_TOOL_NAME,\n description:\n \"Pause this turn and request structured human input. Use for decisions or missing information that only a person can provide. Supports free text, single-select, multi-select, an optional Other value, multiple questions, explicit skip policy, and an optional expiry.\",\n parameters: RequestHumanInputToolInput,\n needsApproval: true,\n // A missing/mismatched durable response is a protocol integrity failure,\n // not model-visible tool output the agent may reason past.\n errorFunction: null,\n execute: (_input, _context, details) => {\n const settled = options.humanInputResponse;\n if (!settled) {\n throw new Error(\"Human-input tool resumed without a durable response\");\n }\n const resumedCallId = details?.toolCall?.callId;\n if (resumedCallId && resumedCallId !== settled.toolCallId) {\n throw new Error(\"Human-input response does not belong to the resumed tool call\");\n }\n return JSON.stringify({ requestId: settled.requestId, ...settled.response });\n },\n });\n const agentTools = [...hostedTools, humanInputTool];\n const baseConfig = {\n name: \"OpenGeni Agent\",\n model: options.model ?? settings.openaiModel,\n // White-label persona composition. The effective template is the per-call\n // override (options.instructionsTemplate, resolved by the caller as\n // session > workspace) falling back to the deployment default\n // (settings.agentInstructionsTemplate, default DEFAULT_AGENT_INSTRUCTIONS).\n // composeAgentInstructions substitutes the non-bypassable CORE (goal-loop\n // ownership + workspace-environment block) at the {{core}} marker, or\n // appends it when the template omits the marker. With the default template\n // and no environment this is byte-identical to the historical preamble.\n // Persona composition order (all one system-level instructions string):\n // 1. workspace instructionsTemplate (or deployment default) with the\n // non-bypassable CORE substituted at {{core}} — composeAgentInstructions,\n // 2. + the generic programmatic-tool-calling (toolspace) directive, ONLY\n // when a toolspace token was minted for this turn (feature enabled + a\n // per-turn seed — the mint gate, which includes selfhosted turns since\n // they now receive the token too) — appendToolspaceInstructions,\n // 3. + managed-sandbox Git binding discovery, ONLY when one provider has\n // multiple credential bindings,\n // 4. + workspace memory working set, ONLY when the workspace setting is on\n // and the worker resolved a nonblank block — appendWorkspaceMemory,\n // 5. + the per-session persona instructions (session-specific, so it\n // refines both the workspace persona and the substrate note),\n // 6. + host context for this exact turn, when supplied,\n // 7. + durable session-setting state (title present + child notification\n // mode), when supplied by the worker,\n // The genesis title directive is deliberately NOT part of this persistent\n // string. runAgentStream injects it into the first model call only.\n instructions: appendPersistentSessionSettings(\n appendTurnInstructions(\n appendSessionInstructions(\n appendWorkspaceMemory(\n appendGitCredentialBindingInstructions(\n appendToolspaceInstructions(\n composeAgentInstructions(\n options.instructionsTemplate ?? settings.agentInstructionsTemplate,\n options.workspaceEnvironment,\n options.rig,\n ),\n settings.toolspaceEnabled && Boolean(options.toolspaceTokenSeed),\n ),\n options.gitCredentialBindings,\n options.activeSandboxBackend,\n ),\n options.workspaceMemory,\n ),\n options.sessionInstructions,\n ),\n options.turnInstructions,\n ),\n options.persistentSessionSettings,\n ),\n modelSettings: {\n reasoning: {\n effort: options.reasoningEffort ?? settings.openaiReasoningEffort,\n summary: \"detailed\",\n },\n // Round-trip the encrypted reasoning payload with every call so chains\n // of thought survive without provider-side response storage (which is\n // what stripped provider item ids opt us out of — see\n // stripProviderItemIds). providerData.include replaces any\n // tool-derived include entries; OpenGeni's tools are MCP/sandbox\n // function tools, which contribute none. Gated on the resolved\n // encryptedReasoning flag: the chat wire API has no encrypted_content\n // field, so registry \"chat\" providers turn it off.\n ...(Object.keys(providerData).length > 0 ? { providerData } : {}),\n },\n // Explicit hosted tools (web_search when enabled). Threaded into BOTH the\n // `new Agent(baseConfig)` path (sandboxBackend === \"none\") and the\n // `new SandboxAgent({ ...baseConfig, ... })` path via the shared baseConfig\n // spread; the SDK concatenates these with MCP and sandbox capability tools.\n tools: agentTools,\n ...(options.mcpServers?.length ? { mcpServers: options.mcpServers } : {}),\n // Surface FAILED MCP tool calls as `{ isError: true }` tool output (see\n // mcpToolErrorFunction / mcpToolErrorOutput) instead of the SDK's default\n // flat error string, so a thrown MCP failure (protocol error, auth, timeout,\n // tool-not-found) settles the timeline tool to \"failed\" rather than rendering\n // as success. Applies to every MCP server on this agent (session, first-party,\n // capability, codex_apps) since none set a server-level errorFunction.\n mcpConfig: { errorFunction: mcpToolErrorFunction },\n } as const;\n\n if (settings.sandboxBackend === \"none\") {\n const agent = new Agent(baseConfig);\n if (options.genesisTitleHint) {\n agentsNeedingGenesisTitleDirective.add(agent);\n }\n maybeInstallCodexToolSearch(agent, settings, options);\n applyMcpApprovalPolicy(agent, settings);\n return agent;\n }\n\n const runAs = sandboxRunAs(settings);\n const agent = new SandboxAgent({\n ...baseConfig,\n defaultManifest: buildManifest(\n settings,\n resources,\n options.sandboxEnvironment,\n options.fileResourceDownloads,\n ),\n ...(runAs ? { runAs } : {}),\n capabilities: buildAgentCapabilities(settings, options.packSkills ?? [], {\n ...(options.skillLibrarySkills?.length\n ? { skillLibrarySkills: options.skillLibrarySkills }\n : {}),\n ...(options.sessionSkills?.length ? { sessionSkills: options.sessionSkills } : {}),\n ...repositoryWorkspaceSkillPathsOption(resources),\n ...(options.structuredToolTransport !== undefined\n ? { structuredToolTransport: options.structuredToolTransport }\n : {}),\n ...(options.computerToolMode !== undefined\n ? { computerToolMode: options.computerToolMode }\n : {}),\n ...(options.onComputerUseReady ? { onComputerUseReady: options.onComputerUseReady } : {}),\n ...(options.turnCancellationSignal\n ? { turnCancellationSignal: options.turnCancellationSignal }\n : {}),\n ...(options.onToolCancellationFence\n ? { onToolCancellationFence: options.onToolCancellationFence }\n : {}),\n }),\n });\n agentSkillSelections.set(\n agent,\n Object.freeze(\n effectiveSkillSelections(\n options.skillLibrarySelections ?? [],\n options.skillLibrarySkills ?? [],\n options.packSkills ?? [],\n options.sessionSkills ?? [],\n ).map((selection) => Object.freeze(selection)),\n ),\n );\n if (options.genesisTitleHint) {\n agentsNeedingGenesisTitleDirective.add(agent);\n }\n agentFileDownloads.set(\n agent,\n normalizeSandboxFileDownloads(options.fileResourceDownloads ?? []).filter(\n (download) => !download.content,\n ),\n );\n agentRepositoryCloneHooks.set(\n agent,\n sandboxRepositoryCloneHooks(settings, resources, options.activeSandboxBackend),\n );\n // Stash the EFFECTIVE backend so runStream's owned branch can skip the direct\n // beforeAgentStart hook run on a connected machine: the box there is the user's\n // REAL computer — the platform must not run setup (az login) against it. The\n // clone hooks are already excluded for selfhosted at construction (above); this\n // keeps the built-in hooks equally out.\n if (options.activeSandboxBackend) {\n agentActiveSandboxBackend.set(agent, options.activeSandboxBackend);\n }\n // TOKEN-BROKER (B1): stash per-turn provider seeds off-manifest so runStream\n // can seed the setup hook without tokens ever touching defaultManifest /\n // sandboxEnvironment. `gitTokenSeed` remains the GitHub alias.\n const gitTokenSeeds = {\n ...(options.gitTokenSeeds ?? {}),\n ...(options.gitTokenSeed ? { github: options.gitTokenSeed } : {}),\n } satisfies GitTokenSeeds;\n if (Object.keys(gitTokenSeeds).length > 0) {\n agentGitTokenSeeds.set(agent, gitTokenSeeds);\n }\n if (options.gitCredentialBindings && options.gitCredentialBindings.length > 0) {\n agentGitCredentialBindings.set(agent, options.gitCredentialBindings);\n }\n if (options.toolspaceTokenSeed) {\n agentToolspaceTokenSeed.set(agent, options.toolspaceTokenSeed);\n agentToolspaceTokenSessionId.set(agent, options.toolspaceTokenSessionId!);\n }\n // M3: stash the rig setup descriptor + RESOLVE the rig credential hooks now.\n // sandboxLifecycleHooksForIds throws on an unknown hook name, so a typo'd rig\n // credential_hook fails the turn HERE (per-turn resolution) rather than being\n // silently dropped — the fail-visible contract the brief requires.\n if (options.rigSetup) {\n agentRigSetup.set(agent, options.rigSetup);\n }\n if (options.rigCredentialHookIds && options.rigCredentialHookIds.length > 0) {\n agentRigCredentialHooks.set(agent, sandboxLifecycleHooksForIds(options.rigCredentialHookIds));\n }\n maybeInstallCodexToolSearch(agent, settings, options);\n applyMcpApprovalPolicy(agent, settings);\n return agent;\n}\n\n/**\n * Enable Codex-CLI-style progressive MCP disclosure on a Codex turn when the\n * flag is on. Gated on `structuredToolTransport === false` — the same signal that\n * identifies a Codex-subscription turn (the ChatGPT backend that rejects hosted\n * tools) — so no non-Codex turn is ever touched. On qualifying turns it wraps\n * `getAllTools` (clone-survivingly — see {@link installCodexToolSearch}) to defer\n * selected non-mandatory MCP schemas and add the client tool_search tool. The\n * description combines live connector namespaces with selected server identities.\n */\nfunction maybeInstallCodexToolSearch(\n agent: Agent<any, any>,\n settings: Settings,\n options: BuildAgentOptions,\n): void {\n if (settings.codexToolSearchEnabled && options.structuredToolTransport === false) {\n const mcpServers = options.mcpServers ?? [];\n // `defer_loading:true` removes these MCP schemas from provider context until\n // tool_search discloses a bounded match. Keep the compaction estimator on\n // that same wire truth; otherwise a large deferred catalog can falsely trip\n // compaction before the first real model request. OpenGeni remains eager.\n for (const server of mcpServers) {\n if (server.name === \"opengeni\") continue;\n (\n server as MCPServer & {\n deferModelToolSchemaAccounting?: () => void;\n }\n ).deferModelToolSchemaAccounting?.();\n }\n installCodexToolSearch(\n agent as unknown as Parameters<typeof installCodexToolSearch>[0],\n options.codexConnectorNamespaces ?? new Set<string>(),\n new Set(mcpServers.map((server) => server.name)),\n );\n }\n}\n\n/** True when the unprefixed tool `name` requires approval under `policy`. */\nfunction mcpToolRequiresApproval(\n policy: boolean | ReadonlySet<string>,\n unprefixedName: string,\n): boolean {\n return policy === true || (policy !== false && policy.has(unprefixedName));\n}\n\n/** A per-server approval policy keyed by the server's `<id>__` tool prefix. */\ntype McpApprovalPolicy = {\n prefix: string;\n requireApproval: boolean | ReadonlySet<string>;\n};\n\n/** The subset of the agent surface the approval wrap needs — including `clone`. */\ntype ApprovalCapableAgent = {\n getMcpTools: (runContext: unknown) => Promise<Tool<any>[]>;\n clone?: (config: unknown) => ApprovalCapableAgent;\n};\n\n/**\n * Install the approval wrap on a single agent instance: replace `getMcpTools`\n * with one that stamps `needsApproval: () => true` on every MCP tool whose\n * server policy demands it. Tools are matched by the server's `<id>__` prefix\n * (LONGEST prefix first — see {@link applyMcpApprovalPolicy}), then the\n * unprefixed tool name.\n *\n * CLONE SURVIVAL (mirrors {@link installCodexToolSearch}): the sandbox runtime\n * resolves tools not on the agent we build here but on a FRESH clone —\n * `prepareSandboxAgent` calls `agent.clone(...)`, and `SandboxAgent.clone`\n * reconstructs from a FIXED field list (name/tools/mcpServers/…), so an\n * instance-own `getMcpTools` override is dropped and approval would silently\n * bypass on every sandbox turn. We therefore also wrap `clone` to RE-INSTALL the\n * policy onto every clone, recursively — covering clone-of-clone and the resume\n * paths. The base (non-sandbox) `Agent.clone` spreads `...this` and would carry\n * the override, but re-installing is idempotent there and keeps one code path.\n */\nfunction installMcpApprovalPolicy(\n agent: ApprovalCapableAgent,\n policies: McpApprovalPolicy[],\n): void {\n const listMcpTools = agent.getMcpTools.bind(agent);\n agent.getMcpTools = async (runContext: unknown) => {\n const tools = await listMcpTools(runContext);\n return tools.map((tool) => {\n if (tool.type !== \"function\") {\n return tool;\n }\n const policy = policies.find((entry) => tool.name.startsWith(entry.prefix));\n if (!policy) {\n return tool;\n }\n const unprefixed = tool.name.slice(policy.prefix.length);\n return mcpToolRequiresApproval(policy.requireApproval, unprefixed)\n ? { ...tool, needsApproval: async () => true }\n : tool;\n });\n };\n const originalClone = agent.clone?.bind(agent);\n if (originalClone) {\n agent.clone = (config: unknown) => {\n const cloned = originalClone(config);\n installMcpApprovalPolicy(cloned, policies);\n return cloned;\n };\n }\n}\n\n/**\n * Enforce per-MCP-server human approval. `settings.mcpServers[].requireApproval`\n * is `true` (every tool of that server requires approval) or a string[] of\n * UNPREFIXED tool names (only those do); absent = auto-run. The SDK converts MCP\n * tools to function tools with `needsApproval` unset (defaults false) and exposes\n * no per-server/agent approval knob, so we wrap the agent's `getMcpTools` to\n * attach a `needsApproval: () => true` predicate to the matching tools — matched\n * by the server's `<id>__` prefix, then the unprefixed tool name. A tool that\n * needs approval raises a run INTERRUPTION, which the worker turns into\n * `session.requiresAction` and resolves via `user.approvalDecision`\n * (resumeApproval) — the same generic path shell/computer-use approvals use, so\n * no extra plumbing. No-op when no server requests approval, so the default\n * (auto-run everything) is byte-for-byte unchanged.\n *\n * Two robustness properties the wrap must hold:\n * - LONGEST-PREFIX-FIRST. Server ids can be prefixes of one another (`my` vs\n * `my_`), so their tool prefixes collide (`my__` vs `my___`): a tool like\n * `my___run` (from server `my_`) also `startsWith` `my__` (server `my`). A\n * first-match `find` over unsorted policies could bind it to the WRONG\n * server's policy and bypass gating. Sorting policies by DESCENDING prefix\n * length makes the most-specific (longest) prefix win, so each tool resolves\n * to its own server.\n * - CLONE SURVIVAL. The wrap is re-installed onto every clone; see\n * {@link installMcpApprovalPolicy}.\n */\nfunction applyMcpApprovalPolicy(agent: Agent<any, any>, settings: Settings): void {\n const policies: McpApprovalPolicy[] = settings.mcpServers\n .filter(\n (server) =>\n server.requireApproval === true ||\n (Array.isArray(server.requireApproval) && server.requireApproval.length > 0),\n )\n .map((server) => ({\n prefix: prefixedMcpToolName(server.id, \"\"),\n requireApproval:\n server.requireApproval === true ? true : new Set(server.requireApproval as string[]),\n }))\n .sort((a, b) => b.prefix.length - a.prefix.length);\n if (policies.length === 0) {\n return;\n }\n installMcpApprovalPolicy(agent as unknown as ApprovalCapableAgent, policies);\n}\n\n/**\n * Force a sandbox capability to emit its FUNCTION-transport tool variants instead\n * of the hosted ones, by dropping the model instance the SDK's transport\n * detection keys off. See {@link buildAgentCapabilities} for why (codex routes the\n * OpenAIResponsesModel to the ChatGPT backend, which rejects the hosted\n * `apply_patch` AND `computer_use_preview` tool types). The SDK reads\n * hosted-vs-function ONLY from `_modelInstance` (set via `bindModel`); overriding\n * `bindModel` to discard the instance leaves `_modelInstance` undefined, so\n * `supportsApplyPatchTransport` / `supportsStructuredToolOutputTransport` return\n * false and `tools()` emits the function variants — `apply_patch` + text\n * `view_image` for filesystem, and the `computer_*` function tools + text\n * `computer_screenshot` for computer-use. `bindModel` still returns the capability\n * so the SDK's bind chain (`.bind().bindRunAs().bindModel()`) is preserved.\n */\nfunction neutralizeStructuredToolTransport(\n capability: ReturnType<typeof filesystem> | ReturnType<typeof computerUse>,\n): void {\n // Use `this` (NOT a captured reference to `capability`): the SandboxAgent binds\n // via `cap.clone().bind(session).bindRunAs(runAs).bindModel(model, instance)` and\n // runs tools() on the object the CHAIN returns. Capability.clone() copies this\n // override onto the fresh per-run instance, so bindModel must operate on and\n // RETURN `this` (the clone) — a version that mutated/returned the ORIGINAL\n // capability leaves the clone (which .bind() set `_session` on) out of the chain,\n // so tools() runs on the unbound original and throws \"Filesystem capability is\n // not bound to a SandboxSession\". Dropping the model instance is all we need:\n // supportsApplyPatchTransport(undefined) is false → the function apply_patch.\n const forceFunctionTransport = function (this: Record<string, unknown>): unknown {\n this._modelInstance = undefined;\n return this;\n };\n (capability as unknown as { bindModel: typeof forceFunctionTransport }).bindModel =\n forceFunctionTransport;\n}\n\n/**\n * Build the SandboxAgent capability set explicitly. The SDK default includes\n * its inline provider compaction capability; OpenGeni deliberately omits it\n * because durable portable compaction owns the full history transition.\n */\n/**\n * Wrap the shell capability's `exec_command` so its execution runs inside a\n * tool-call correlation context (op-correlation.ts): the SDK's tool machinery\n * passes `details.toolCall` (the model's function_call, with its durable\n * `callId`) into every function-tool `invoke`, and binding an\n * AsyncLocalStorage around the invocation makes that id visible to the sandbox\n * transport underneath — which mints the DURABLE op id `{callId}:{ordinal}`\n * (op-stream ruling B1). A re-dispatched turn re-executes the same\n * function_call with the same callId, so the transport's idempotent OpStart\n * ATTACHES to the already-running/completed op instead of re-running it.\n * Without a callId (no details on the invocation) the tool runs unwrapped and\n * the transport falls back to a random unique id — today's semantics.\n */\nfunction withExecOpCorrelation(tools: Tool<unknown>[]): Tool<unknown>[] {\n return tools.map((capabilityTool) => {\n if (capabilityTool.type !== \"function\" || capabilityTool.name !== \"exec_command\") {\n return capabilityTool;\n }\n const invoke = capabilityTool.invoke;\n return {\n ...capabilityTool,\n invoke: (runContext, input, details) => {\n const callId = details?.toolCall?.callId;\n if (!callId) {\n return invoke(runContext, input, details);\n }\n return runWithToolCallCorrelation(callId, () => invoke(runContext, input, details));\n },\n };\n });\n}\n\n/**\n * Codex accepts ordinary FUNCTION tools but also accepts `input_image` content\n * inside a function_call_output (the same transport used by codex-rs\n * view_image). The SDK filesystem capability unnecessarily couples this choice\n * to hosted apply_patch support; when hosted tools are disabled it degrades\n * view_image to a giant text data URL, charging roughly one token per four\n * base64 characters. Re-wrap only successful data-URL results as a structured\n * image. Text errors remain text, and the tool itself remains a normal function.\n */\nexport function withStructuredViewImageFunctionResults(tools: Tool<unknown>[]): Tool<unknown>[] {\n return tools.map((capabilityTool) => {\n if (capabilityTool.type !== \"function\" || capabilityTool.name !== \"view_image\") {\n return capabilityTool;\n }\n const invoke = capabilityTool.invoke;\n return {\n ...capabilityTool,\n invoke: async (runContext, input, details) => {\n const output = await invoke(runContext, input, details);\n const dataUrl =\n typeof output === \"string\"\n ? output\n : output &&\n typeof output === \"object\" &&\n typeof (output as { text?: unknown }).text === \"string\"\n ? (output as { text: string }).text\n : null;\n return dataUrl?.startsWith(\"data:image/\")\n ? { type: \"image\" as const, image: { url: dataUrl } }\n : output;\n },\n };\n });\n}\n\nexport function buildAgentCapabilities(\n settings: Settings,\n packSkills: PackSkill[],\n options: {\n skillLibrarySkills?: PackSkill[];\n sessionSkills?: PackSkill[];\n workspaceSkillPaths?: readonly WorkspaceSkillSearchPath[];\n structuredToolTransport?: boolean;\n // EXPLICIT computer-use transport (see BuildAgentOptions.computerToolMode). When\n // present, computerUse() is handed the mode directly and its tools() obeys it\n // without the constructor-name sniff. When absent, the legacy neutralize +\n // imageFunctionResults path (driven by structuredToolTransport) is unchanged.\n computerToolMode?: ComputerToolMode;\n onComputerUseReady?: (session: SandboxSessionLike) => Promise<void>;\n turnCancellationSignal?: AbortSignal;\n onToolCancellationFence?: (fence: TurnToolCancellationFence) => void;\n } = {},\n): ReturnType<typeof Capabilities.default> {\n const toolCancellation =\n options.turnCancellationSignal || options.onToolCancellationFence\n ? createTurnToolCancellationController(options.turnCancellationSignal)\n : null;\n if (toolCancellation) options.onToolCancellationFence?.(toolCancellation);\n // The `filesystem()` capability picks hosted-vs-function tool variants from the\n // bound model instance (supportsApplyPatchTransport / structured tool output).\n // When the caller declares the backend does NOT support that structured/hosted\n // transport (codex → the ChatGPT backend rejects the hosted `apply_patch` type),\n // neutralize this capability's model binding so tools() falls to the function\n // `apply_patch` + text `view_image` variants the backend accepts — the SDK\n // handles their function_call round-trip natively, so no reimplementation.\n // Scoped to filesystem: shell() is always a function-tool transport.\n const filesystemCapability = filesystem({\n ...(options.structuredToolTransport === false\n ? { configureTools: withStructuredViewImageFunctionResults }\n : {}),\n });\n if (options.structuredToolTransport === false) {\n neutralizeStructuredToolTransport(filesystemCapability);\n }\n const caps: ReturnType<typeof Capabilities.default> = [\n filesystemCapability,\n shell({ ...(toolCancellation ? {} : { configureTools: withExecOpCorrelation }) }),\n ];\n const sessionSkills = sessionSkillsForMaterialization(\n packSkills,\n options.skillLibrarySkills ?? [],\n options.sessionSkills ?? [],\n );\n caps.push(\n skills({\n lazyFrom: lazySkillSourceWithPackSkills(\n [...packSkills, ...sessionSkills],\n options.skillLibrarySkills ?? [],\n ),\n }),\n );\n if (options.workspaceSkillPaths?.length) {\n caps.push(\n workspaceSkills(options.workspaceSkillPaths, [\n ...bundledSkillDirNames(bundledSkillsDir()),\n ...(options.skillLibrarySkills ?? []).map((skill) => skill.name),\n ...packSkills.map((skill) => skill.name),\n ...sessionSkills.map((skill) => skill.name),\n ]),\n );\n }\n // P4.3 computer-use: the agent drives the SAME :0 humans watch (xdotool/XTEST +\n // scrot), but only when the desktop tier is ON, computer-use is enabled, and the\n // backend is one whose image carries the X stack (descriptorgate — honest about\n // which backends are desktop-capable today; headless/dev backends never get the\n // tool, so a misconfigured non-desktop box can't register a tool that always\n // fails). The capability's tools() bind to the live externally-owned session at\n // run time (the SandboxAgent merge); xdotool drives :0 regardless of whether any\n // viewer is attached, so no pixel-tunnel dependency.\n if (\n settings.computerUseEnabled &&\n settings.sandboxDesktopEnabled &&\n desktopCapableBackend(settings.sandboxBackend)\n ) {\n // computer-use is transport-aware, exactly like filesystem: `tools()` emits the\n // HOSTED `computer_use_preview` tool on the structured transport and a set of\n // FUNCTION `computer_*` tools on the text transport. The ChatGPT/Codex backend\n // rejects hosted tool types (only function/custom/web_search accepted).\n //\n // HARDENING: when the caller declares an EXPLICIT `computerToolMode` (the worker\n // does, from its authoritative model resolution), thread it straight through —\n // tool selection then never depends on the SDK's model-instance constructor-name\n // sniff (which a wrapped/proxied model would defeat, silently 400ing a\n // chat-completions provider handed the hosted tool). When ABSENT, the legacy path\n // is preserved byte-for-byte: on the codex path (structuredToolTransport === false)\n // we set imageFunctionResults and neutralize the capability's model binding — the\n // SAME trick used for filesystem above — so `tools()` sees no model instance and\n // emits the function tools the backend can call, instead of suppressing the tier.\n const explicitMode = options.computerToolMode;\n const computerCapability = computerUse({\n dimensions: [settings.streamResolutionWidth, settings.streamResolutionHeight],\n readOnly: settings.computerUseReadOnly,\n ...(options.onComputerUseReady ? { onReady: options.onComputerUseReady } : {}),\n ...(explicitMode\n ? { toolMode: explicitMode }\n : // Legacy (no explicit mode): on the codex path the function tools deliver\n // screenshots as a real image the model can see. The ChatGPT/Codex backend\n // rejects HOSTED tool types but DOES accept `input_image` content items inside a\n // `function_call_output` (proven by openai/codex codex-rs, whose view_image tool\n // ships exactly that shape) — so a structured image tool result is seen, where a\n // text data-URL would be unreadable.\n options.structuredToolTransport === false\n ? { imageFunctionResults: true }\n : {}),\n });\n // Neutralize ONLY on the legacy sniff path. With an explicit toolMode the mode\n // already forces the function tools, so the constructor-name override is moot.\n if (!explicitMode && options.structuredToolTransport === false) {\n neutralizeStructuredToolTransport(computerCapability);\n }\n caps.push(computerCapability as unknown as ReturnType<typeof Capabilities.default>[number]);\n }\n if (toolCancellation) {\n for (const capability of caps) {\n wrapCapabilityToolsForTurnCancellation(\n capability as unknown as { tools(): Tool<unknown>[] },\n toolCancellation,\n );\n }\n }\n return caps;\n}\n\nexport function sandboxRunAs(_settings: Settings): string | undefined {\n return undefined;\n}\n\nexport type PreparedAgentTools = {\n mcpServers: MCPServer[];\n close: () => Promise<void>;\n // P4 (Part B.1): the live, by-reference Set of ORIGINAL-dotted connector\n // namespaces the codex_apps transport saw across this turn's tools/list calls.\n // Accumulates as the agent lists tools during the run, so the worker reads it\n // AFTER the turn (in its finally) to cache the serving account's connector set.\n // Empty when this turn has no codex_apps server (or it never listed any\n // namespaced tool) — the worker only persists a non-empty set.\n codexConnectorNamespaces: Set<string>;\n};\n\nexport type PrepareToolsOptions = {\n accountId?: string;\n workspaceId?: string;\n // Worker-asserted session scope for first-party MCP calls; enables\n // session-scoped tools such as goal management on the API side.\n sessionId?: string;\n // The calling turn's id, signed into the token so tools can classify the\n // caller from its own identity instead of the session's live active pointer.\n turnId?: string;\n // The exact executing attempt that owns the MCP call.\n attemptId?: string;\n executionGeneration?: number;\n subjectId?: string;\n subjectLabel?: string;\n // Immutable human authority used only for subject-owned connection lookup.\n // This is intentionally separate from the worker's first-party MCP identity.\n credentialSubjectId?: string;\n // Overrides the fixed first-party MCP permission set for this session's\n // delegated token (manager-style sessions). The caller is responsible for\n // having validated the set against the session creator's grant.\n firstPartyPermissions?: Permission[];\n // Exact model-visible catalog selection for the broad first-party server.\n // Permissions are signed separately and remain the authorization boundary.\n firstPartyTools?: FirstPartyMcpToolName[];\n resolveCredential?: (\n input: ResolveConnectionCredentialInput,\n ) => Promise<ResolveConnectionCredentialResult>;\n onAuthNeeded?: (payload: ToolAuthNeededPayload) => Promise<void> | void;\n /** Injectable final MCP transport for tests and embedded hosts. */\n mcpFetchImpl?: FetchLike;\n};\n\ntype ConnectedMcpServerBatch = Awaited<ReturnType<typeof connectMcpServers>>;\n\nexport type ConnectedMcpServerBatches = {\n active: MCPServer[];\n failed: MCPServer[];\n errors: ReadonlyMap<MCPServer, Error>;\n close: () => Promise<void>;\n};\n\n/**\n * Connect SDK-managed MCP servers in stable, bounded batches. The SDK cleans a\n * failing strict batch; this wrapper additionally closes every earlier batch\n * before rethrowing, so a later-batch failure cannot leak live connections.\n */\nexport async function connectMcpServersInBatches(\n servers: MCPServer[],\n options: { strict: boolean; connectTimeoutMs?: number },\n): Promise<ConnectedMcpServerBatches> {\n assertMcpServerSelectionWithinBounds(servers);\n const batches: ConnectedMcpServerBatch[] = [];\n try {\n for (let offset = 0; offset < servers.length; offset += MCP_MAX_CONCURRENT_SERVER_OPERATIONS) {\n batches.push(\n await connectMcpServers(\n servers.slice(offset, offset + MCP_MAX_CONCURRENT_SERVER_OPERATIONS),\n {\n ...(options.connectTimeoutMs === undefined\n ? {}\n : { connectTimeoutMs: options.connectTimeoutMs }),\n connectInParallel: true,\n strict: options.strict,\n },\n ),\n );\n }\n } catch (error) {\n await closeMcpServerBatches(batches).catch(() => undefined);\n throw error;\n }\n\n const errors = new Map<MCPServer, Error>();\n for (const batch of batches) {\n for (const [server, error] of batch.errors) errors.set(server, error);\n }\n return {\n active: batches.flatMap((batch) => batch.active),\n failed: batches.flatMap((batch) => batch.failed),\n errors,\n close: async () => {\n await closeMcpServerBatches(batches);\n },\n };\n}\n\nasync function closeMcpServerBatches(batches: ConnectedMcpServerBatch[]): Promise<void> {\n let firstError: unknown;\n for (const batch of [...batches].reverse()) {\n try {\n await batch.close();\n } catch (error) {\n firstError ??= error;\n }\n }\n if (firstError !== undefined) throw firstError;\n}\n\nexport async function prepareAgentTools(\n settings: Settings,\n tools: ToolRef[],\n options: PrepareToolsOptions = {},\n): Promise<PreparedAgentTools> {\n // P4 (Part B.1): one Set per prepareTools call, shared by reference into the\n // codex_apps sanitizing fetch so every tools/list this turn accumulates the\n // account's connector namespaces. Surfaced on PreparedAgentTools for the worker.\n const codexConnectorNamespaces = new Set<string>();\n assertMcpServerSelectionWithinBounds(tools);\n if (tools.length === 0) {\n return { mcpServers: [], close: async () => {}, codexConnectorNamespaces };\n }\n const registry = new Map(settings.mcpServers.map((server) => [server.id, server]));\n const subjectOwnedTool = tools.find(\n (tool) => registry.get(tool.id)?.connectionRef?.subjectScope === \"subject\",\n );\n if (subjectOwnedTool && !options.credentialSubjectId) {\n throw new Error(\n `subject-owned connection for MCP server ${subjectOwnedTool.id} requires a human turn initiator`,\n );\n }\n const aggregateToolBudget = new McpAggregateToolListBudget();\n // npm Undici's dispatcher transport can hang indefinitely under Bun even\n // after an AbortSignal fires. Bun's native fetch is the supported runtime\n // transport there; destination policy validation still runs before every\n // credential-bearing MCP request.\n const useBunNativeFetch = options.mcpFetchImpl === undefined && !!process.versions.bun;\n const mcpFetchImpl =\n options.mcpFetchImpl ?? (useBunNativeFetch ? globalThis.fetch.bind(globalThis) : undiciFetch);\n const servers = await boundedParallelMap(\n tools,\n MCP_MAX_CONCURRENT_SERVER_OPERATIONS,\n async (tool, index) => {\n const config = registry.get(tool.id);\n if (!config) {\n throw new Error(`Unknown MCP server id: ${tool.id}`);\n }\n const url = firstPartyMcpServerUrlForRun(settings, config, options.workspaceId) ?? config.url;\n const firstParty = isFirstPartyMcpServer(settings, config);\n const baseFetch = isCodexAppsMcpServer(config)\n ? codexAppsSanitizingFetch(mcpFetchImpl, codexConnectorNamespaces)\n : mcpFetchImpl;\n const guardedFetch = guardedMcpFetch(\n firstParty ? { ...settings, integrationsAllowPrivateNetworkTargets: true } : settings,\n baseFetch,\n {\n ...(firstParty ? { requireHttpsOutsideLocalTest: false } : {}),\n ...(useBunNativeFetch ? { pinResolvedDestination: false } : {}),\n },\n );\n const fetchImpl = config.connectionRef\n ? connectionBrokerFetch(guardedFetch, config, options)\n : firstParty\n ? firstPartyAuthFetch(guardedFetch, settings, options)\n : guardedFetch;\n // A server is connected BEST-EFFORT (a connect OR tools-list failure drops\n // it — its tools go unavailable for the turn — instead of failing the turn)\n // in two cases:\n // - codex_apps: connector availability is RUNTIME-DISCOVERED — the\n // device-code login may lack the connector scopes, and the backend can\n // reject the bearer at the initialize/tools-list handshake, so a 401/403\n // (or a missing/failed token) drops the server.\n // - an optional ToolRef: either an auto-attached workspace-default\n // capability MCP or a client/pack-selected portable ref. A\n // broken/expired credential or unavailable endpoint skips the server\n // with a warning, never killing the turn before the model runs. Bare\n // refs stay strict (below), preserving the fail-loud default.\n // The connect-time drop is handled by connectMcpServers({ strict: false });\n // the tools-list-time drop is enforced inside PrefixedMcpServer.listTools —\n // a best-effort server whose tools/list throws (e.g. an expired connection\n // credential surfacing as a StreamableHTTP \"authentication required\" 401)\n // degrades to zero tools rather than throwing out of the SDK's run-time\n // getAllMcpTools and failing an unrelated turn. The actionable\n // tool.auth_needed signal is preserved: the connection-broker fetch\n // publishes it before returning the 401 that provokes the throw.\n const optional = tool.optional === true;\n const bestEffort = isCodexAppsMcpServer(config) || optional || !!config.connectionRef;\n const server = new PrefixedMcpServer(\n new MCPServerStreamableHttp({\n url,\n name: config.name ?? config.id,\n cacheToolsList: config.cacheToolsList,\n // The upstream transport logger receives raw thrown errors, whose\n // messages may contain response bodies, URLs, headers, or echoed\n // credentials. Keep its diagnostic surface structural only.\n logger: safeMcpTransportLogger(config.id),\n // codex_apps returns connector tools with empty `outputSchema: {}` that the\n // MCP SDK's strict Tool schema rejects (fails the turn during tools/list);\n // sanitize the response on the wire before validation. The namespace Set\n // also captures each tool's original connector namespace (P4 Part B.1).\n fetch: fetchImpl,\n ...(await mcpServerRequestInit(settings, config)),\n ...(config.timeoutMs\n ? {\n timeout: config.timeoutMs,\n clientSessionTimeoutSeconds: Math.ceil(config.timeoutMs / 1000),\n }\n : {}),\n }),\n config.id,\n config.allowedTools,\n bestEffort,\n aggregateToolBudget,\n `${config.id}:${index}`,\n );\n return {\n server,\n bestEffort,\n optional,\n timeoutMs: config.timeoutMs,\n };\n },\n );\n const requiredEntries = servers.filter((entry) => !entry.bestEffort);\n const bestEffortEntries = servers.filter((entry) => entry.bestEffort);\n const requiredServers = requiredEntries.map((entry) => entry.server);\n const bestEffortServers = bestEffortEntries.map((entry) => entry.server);\n // Names of the OPTIONAL servers (not codex_apps) so a drop is surfaced as a\n // warning; codex_apps keeps its historically-quiet drop (a not-logged-in\n // ChatGPT plan is a normal, non-noteworthy state).\n const optionalServerNames = new Set(\n servers.filter((entry) => entry.optional).map((entry) => entry.server.name),\n );\n const connectedRequired = await connectMcpServersInBatches(requiredServers, {\n strict: true,\n connectTimeoutMs: mcpOuterConnectTimeoutMs(requiredEntries.map((entry) => entry.timeoutMs)),\n });\n let connectedBestEffort: ConnectedMcpServerBatches | null = null;\n try {\n connectedBestEffort = bestEffortServers.length\n ? await connectMcpServersInBatches(bestEffortServers, {\n strict: false,\n connectTimeoutMs: mcpOuterConnectTimeoutMs(\n bestEffortEntries.map((entry) => entry.timeoutMs),\n ),\n })\n : null;\n } catch (error) {\n await connectedRequired.close().catch(() => undefined);\n throw error;\n }\n if (connectedBestEffort) {\n for (const failed of connectedBestEffort.failed) {\n if (failed instanceof PrefixedMcpServer) {\n failed.releaseAggregateBudget();\n }\n if (!optionalServerNames.has(failed.name)) {\n continue;\n }\n const error = connectedBestEffort.errors.get(failed);\n console.warn(\n `[mcp] optional server \"${failed.name}\" failed to connect/list tools; skipping it for this turn`,\n safeMcpErrorFields(error),\n );\n }\n }\n return {\n mcpServers: [...connectedRequired.active, ...(connectedBestEffort?.active ?? [])],\n close: async () => {\n let firstError: unknown;\n if (connectedBestEffort) {\n try {\n await connectedBestEffort.close();\n } catch (error) {\n firstError ??= error;\n }\n }\n try {\n await connectedRequired.close();\n } catch (error) {\n firstError ??= error;\n }\n if (firstError !== undefined) throw firstError;\n },\n codexConnectorNamespaces,\n };\n}\n\nfunction connectionBrokerFetch(\n baseFetch: FetchLike,\n config: Settings[\"mcpServers\"][number],\n options: PrepareToolsOptions,\n): FetchLike {\n const connectionRef = config.connectionRef;\n if (!connectionRef) {\n return baseFetch;\n }\n return async (input, init) => {\n const request = await mcpRequestInfo(input, init);\n const destinationUrl = mcpRequestDestinationUrl(input);\n const first = await resolveConnectionForRequest(\n options,\n config.id,\n connectionRef,\n destinationUrl,\n request.toolName,\n false,\n );\n if (first.status === \"auth_needed\") {\n return await authNeededFetchResponse(options, config.id, request, first, connectionRef);\n }\n const response = await baseFetch(\n fetchInputForAttempt(input),\n withConnectionHeaders(input, init, first.headers),\n );\n if (response.status === 401) {\n await cancelMcpResponseBody(response);\n const refreshed = await resolveConnectionForRequest(\n options,\n config.id,\n connectionRef,\n destinationUrl,\n request.toolName,\n true,\n );\n if (refreshed.status === \"auth_needed\") {\n return await authNeededFetchResponse(options, config.id, request, refreshed, connectionRef);\n }\n const retry = await baseFetch(\n fetchInputForAttempt(input),\n withConnectionHeaders(input, init, refreshed.headers),\n );\n if (retry.status === 403) {\n const auth = insufficientScopeAuth(retry.headers, connectionRef, refreshed.connectionId);\n if (auth) {\n await cancelMcpResponseBody(retry);\n return await authNeededFetchResponse(options, config.id, request, auth, connectionRef);\n }\n return retry;\n }\n if (retry.status === 401) {\n await cancelMcpResponseBody(retry);\n return await authNeededFetchResponse(\n options,\n config.id,\n request,\n {\n status: \"auth_needed\",\n reason: \"expired\",\n providerDomain: connectionRef.providerDomain,\n ...(connectionRef.provider ? { provider: connectionRef.provider } : {}),\n connectionId: refreshed.connectionId,\n ...(connectionRef.scopes ? { scopes: connectionRef.scopes } : {}),\n ...(connectionRef.resource ? { resource: connectionRef.resource } : {}),\n ...(connectionRef.selectedResources\n ? { selectedResources: connectionRef.selectedResources }\n : {}),\n },\n connectionRef,\n );\n }\n return retry;\n }\n if (response.status === 403) {\n const auth = insufficientScopeAuth(response.headers, connectionRef, first.connectionId);\n if (auth) {\n await cancelMcpResponseBody(response);\n return await authNeededFetchResponse(options, config.id, request, auth, connectionRef);\n }\n return response;\n }\n return response;\n };\n}\n\nasync function resolveConnectionForRequest(\n options: PrepareToolsOptions,\n serverId: string,\n connectionRef: McpServerConnectionRef,\n destinationUrl: string,\n toolName: string | undefined,\n forceRefresh: boolean,\n): Promise<ResolveConnectionCredentialResult> {\n if (!options.workspaceId || !options.resolveCredential) {\n return {\n status: \"auth_needed\",\n reason: \"missing_connection\",\n providerDomain: connectionRef.providerDomain,\n ...(connectionRef.provider ? { provider: connectionRef.provider } : {}),\n ...(connectionRef.connectionId ? { connectionId: connectionRef.connectionId } : {}),\n ...(connectionRef.scopes ? { scopes: connectionRef.scopes } : {}),\n ...(connectionRef.resource ? { resource: connectionRef.resource } : {}),\n ...(connectionRef.selectedResources\n ? { selectedResources: connectionRef.selectedResources }\n : {}),\n };\n }\n const request: ResolveConnectionCredentialInput = {\n workspaceId: options.workspaceId,\n serverId,\n connectionRef,\n destinationUrl,\n forceRefresh,\n ...(toolName ? { toolName } : {}),\n ...(options.credentialSubjectId ? { subjectId: options.credentialSubjectId } : {}),\n };\n try {\n return await options.resolveCredential(request);\n } catch {\n return {\n status: \"auth_needed\",\n reason: \"refresh_failed\",\n providerDomain: connectionRef.providerDomain,\n ...(connectionRef.provider ? { provider: connectionRef.provider } : {}),\n ...(connectionRef.connectionId ? { connectionId: connectionRef.connectionId } : {}),\n ...(connectionRef.scopes ? { scopes: connectionRef.scopes } : {}),\n ...(connectionRef.resource ? { resource: connectionRef.resource } : {}),\n ...(connectionRef.selectedResources\n ? { selectedResources: connectionRef.selectedResources }\n : {}),\n };\n }\n}\n\nfunction insufficientScopeAuth(\n headers: Headers,\n connectionRef: McpServerConnectionRef,\n connectionId: string,\n): Extract<ResolveConnectionCredentialResult, { status: \"auth_needed\" }> | null {\n const challenge = parseWwwAuthenticate(headers.get(\"www-authenticate\"));\n if (challenge.error !== \"insufficient_scope\") {\n return null;\n }\n return {\n status: \"auth_needed\",\n reason: \"insufficient_scope\",\n providerDomain: connectionRef.providerDomain,\n ...(connectionRef.provider ? { provider: connectionRef.provider } : {}),\n connectionId,\n ...(challenge.scope?.length\n ? { scopes: challenge.scope }\n : connectionRef.scopes\n ? { scopes: connectionRef.scopes }\n : {}),\n ...(challenge.resource\n ? { resource: challenge.resource }\n : connectionRef.resource\n ? { resource: connectionRef.resource }\n : {}),\n ...(connectionRef.selectedResources\n ? { selectedResources: connectionRef.selectedResources }\n : {}),\n };\n}\n\nasync function authNeededFetchResponse(\n options: PrepareToolsOptions,\n serverId: string,\n request: McpRequestInfo,\n auth: Extract<ResolveConnectionCredentialResult, { status: \"auth_needed\" }>,\n connectionRef: McpServerConnectionRef,\n): Promise<Response> {\n const connectionId = auth.connectionId ?? connectionRef.connectionId;\n await publishAuthNeeded(options, {\n serverId,\n toolName: request.toolName ?? null,\n providerDomain: auth.providerDomain,\n ...(auth.provider\n ? { provider: auth.provider }\n : connectionRef.provider\n ? { provider: connectionRef.provider }\n : {}),\n reason: auth.reason,\n ...(connectionId ? { connectionId } : {}),\n ...(auth.scopes\n ? { scopes: auth.scopes }\n : connectionRef.scopes\n ? { scopes: connectionRef.scopes }\n : {}),\n ...(auth.resource\n ? { resource: auth.resource }\n : connectionRef.resource\n ? { resource: connectionRef.resource }\n : {}),\n ...(auth.selectedResources\n ? { selectedResources: auth.selectedResources }\n : connectionRef.selectedResources\n ? { selectedResources: connectionRef.selectedResources }\n : {}),\n ...(auth.authorizationUrl ? { authorizationUrl: auth.authorizationUrl } : {}),\n ...(options.subjectId ? { subjectId: options.subjectId } : {}),\n });\n if (request.method === \"tools/call\") {\n return mcpToolAuthNeededResponse(request.id);\n }\n return new Response(\"Authentication required for MCP server connection\", {\n status: 401,\n });\n}\n\nasync function publishAuthNeeded(\n options: PrepareToolsOptions,\n payload: ToolAuthNeededPayload,\n): Promise<void> {\n try {\n await options.onAuthNeeded?.(payload);\n } catch {\n // Auth-needed events are advisory UI/audit signals; a publisher failure must\n // not turn an auth-recoverable tool condition into a failed agent turn.\n }\n}\n\ntype McpRequestInfo = {\n method?: string;\n id?: string | number | null;\n toolName?: string;\n};\n\nfunction mcpRequestDestinationUrl(input: string | URL | Request): string {\n return new URL(input instanceof Request ? input.url : input.toString()).toString();\n}\n\nasync function mcpRequestInfo(\n input: string | URL | Request,\n init?: RequestInit,\n): Promise<McpRequestInfo> {\n const body =\n typeof init?.body === \"string\"\n ? init.body\n : input instanceof Request && (init?.method ?? input.method).toUpperCase() === \"POST\"\n ? await input\n .clone()\n .text()\n .catch(() => \"\")\n : \"\";\n if (!body) {\n return {};\n }\n try {\n const parsed = JSON.parse(body) as {\n id?: unknown;\n method?: unknown;\n params?: { name?: unknown };\n };\n const method = typeof parsed.method === \"string\" ? parsed.method : undefined;\n const id =\n typeof parsed.id === \"string\" || typeof parsed.id === \"number\" || parsed.id === null\n ? parsed.id\n : undefined;\n const toolName =\n method === \"tools/call\" && typeof parsed.params?.name === \"string\"\n ? parsed.params.name\n : undefined;\n return {\n ...(method ? { method } : {}),\n ...(id !== undefined ? { id } : {}),\n ...(toolName ? { toolName } : {}),\n };\n } catch {\n return {};\n }\n}\n\nfunction withConnectionHeaders(\n input: string | URL | Request,\n init: RequestInit | undefined,\n authHeaders: Record<string, string>,\n): RequestInit {\n const headers = new Headers(\n init?.headers ?? (input instanceof Request ? input.headers : undefined),\n );\n for (const [name, value] of Object.entries(authHeaders)) {\n headers.set(name, value);\n }\n return { ...init, headers };\n}\n\nfunction fetchInputForAttempt(input: string | URL | Request): string | URL | Request {\n return input instanceof Request ? input.clone() : input;\n}\n\nfunction parseWwwAuthenticate(header: string | null): {\n error?: string;\n scope?: string[];\n resource?: string;\n} {\n if (!header) {\n return {};\n }\n const bearerIndex = header.toLowerCase().indexOf(\"bearer\");\n if (bearerIndex < 0) {\n return {};\n }\n const paramsText = header.slice(bearerIndex + \"bearer\".length);\n const params: Record<string, string> = {};\n const re = /([a-zA-Z_][a-zA-Z0-9_-]*)\\s*=\\s*(\"(?:[^\"\\\\]|\\\\.)*\"|[^,\\s]+)/g;\n let match: RegExpExecArray | null;\n while ((match = re.exec(paramsText)) !== null) {\n const raw = match[2]!;\n params[match[1]!.toLowerCase()] = raw.startsWith('\"')\n ? raw.slice(1, -1).replace(/\\\\\"/g, '\"')\n : raw;\n }\n return {\n ...(params.error ? { error: params.error } : {}),\n ...(params.scope ? { scope: params.scope.split(/\\s+/).filter(Boolean) } : {}),\n ...(params.resource ? { resource: params.resource } : {}),\n };\n}\n\n// Application-defined JSON-RPC error code marking \"this tool call needs a\n// connection\". A RESULT carrying inline `isError: true` cannot be used here:\n// the agents SDK's streamable-http shim strips `isError` and returns only the\n// content, erasing the failure. A JSON-RPC error survives the shim as a thrown\n// McpError, which PrefixedMcpServer.callTool converts back into an MCP-shaped\n// `{ isError: true }` output for the model.\nconst MCP_AUTH_NEEDED_ERROR_CODE = -32001;\nconst MCP_AUTH_NEEDED_MESSAGE =\n \"Authentication required - a connection link was posted to the session.\";\n\nfunction mcpToolAuthNeededResponse(id: string | number | null | undefined): Response {\n return new Response(\n JSON.stringify({\n jsonrpc: \"2.0\",\n id: id ?? null,\n error: {\n code: MCP_AUTH_NEEDED_ERROR_CODE,\n message: MCP_AUTH_NEEDED_MESSAGE,\n },\n }),\n {\n status: 200,\n headers: { \"content-type\": \"application/json\" },\n },\n );\n}\n\nfunction isAuthNeededMcpError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = (error as { code?: unknown }).code;\n return code === MCP_AUTH_NEEDED_ERROR_CODE || error.message.includes(MCP_AUTH_NEEDED_MESSAGE);\n}\n\n// Model-facing text for a best-effort server whose tool call failed for a\n// non-auth reason (transport 401/403 that never became the broker's JSON-RPC\n// short-circuit, a provider 5xx, a network blip). The copy is LOOP-SAFE: it\n// tells the model the tool is dead for the REST OF THIS TURN and to NOT retry\n// it, so a model that would otherwise burn the turn re-calling the same broken\n// optional tool moves on instead. Only the safe error surface (JS error class +\n// numeric HTTP status) is interpolated — NEVER the raw error message/response\n// body, which for a broker 401/403 can echo request URLs/headers/credentials.\nfunction mcpToolUnavailableMessage(reason: string): string {\n return `This tool is unavailable for the rest of this turn (${reason}). Do not retry it — continue without it or use another approach.`;\n}\n\n// The only error detail safe to surface to the model or the logs: the JS error\n// constructor name and, when present, a numeric HTTP status. A StreamableHTTP\n// transport error carries the raw response BODY in its `.message` (a broker\n// 401/403 body can echo request detail), so `.message` is never included; the\n// numeric `.code`/`.status` (e.g. 401) is safe and useful.\nfunction safeMcpErrorFields(error: unknown): {\n errorClass: string;\n status?: number;\n} {\n const errorClass = error instanceof Error ? error.constructor.name : typeof error;\n const raw = (error as { code?: unknown; status?: unknown } | null)?.code;\n const status = typeof raw === \"number\" ? raw : undefined;\n if (status === undefined) {\n const altRaw = (error as { status?: unknown } | null)?.status;\n return typeof altRaw === \"number\" ? { errorClass, status: altRaw } : { errorClass };\n }\n return { errorClass, status };\n}\n\nfunction safeMcpTransportError(error: unknown): Error & { status?: number; code?: number } {\n const fields = safeMcpErrorFields(error);\n const safeError = new Error(\n `MCP transport operation failed (${mcpErrorReason(fields)})`,\n ) as Error & {\n status?: number;\n code?: number;\n };\n safeError.name = \"McpTransportError\";\n if (fields.status !== undefined) {\n safeError.status = fields.status;\n safeError.code = fields.status;\n }\n return safeError;\n}\n\nfunction safeMcpTransportLogger(serverId: string) {\n const logFailure = (_message: string, ...args: unknown[]) => {\n let error: unknown;\n for (let index = args.length - 1; index >= 0; index -= 1) {\n if (args[index] instanceof Error) {\n error = args[index];\n break;\n }\n }\n console.warn(\"[mcp] transport operation failed\", {\n serverId,\n ...safeMcpErrorFields(error),\n });\n };\n return {\n namespace: \"opengeni:mcp-transport\",\n debug: () => undefined,\n error: logFailure,\n warn: logFailure,\n dontLogModelData: true,\n dontLogToolData: true,\n };\n}\n\n// Compose the safe model/log reason string (\"StreamableHTTPError 401\", or just\n// the class when no numeric status is available). Never carries the raw body.\nfunction mcpErrorReason(fields: { errorClass: string; status?: number }): string {\n return fields.status === undefined ? fields.errorClass : `${fields.errorClass} ${fields.status}`;\n}\n\nasync function mcpServerRequestInit(\n settings: Settings,\n config: Settings[\"mcpServers\"][number],\n): Promise<{ requestInit: { headers: Record<string, string> } } | {}> {\n // codex_apps is checked FIRST so the static-headers path can never apply to\n // it: its refreshing ChatGPT/Codex bearer is resolved per-connect from the\n // codex ALS, never from a baked `config.headers` value.\n if (isCodexAppsMcpServer(config)) {\n return await codexAppsMcpRequestInit(settings);\n }\n if (isFirstPartyMcpServer(settings, config)) {\n return await firstPartyMcpRequestInit(settings, config);\n }\n // Third-party MCP servers get their configured credential headers (for\n // example workspace-enabled capability MCP credentials) and nothing else —\n // never OpenGeni's own access key or delegated tokens.\n if (config.headers && Object.keys(config.headers).length > 0) {\n return { requestInit: { headers: { ...config.headers } } };\n }\n return {};\n}\n\nasync function firstPartyMcpRequestInit(\n settings: Settings,\n config: Settings[\"mcpServers\"][number],\n): Promise<{ requestInit: { headers: Record<string, string> } } | {}> {\n if (!isFirstPartyMcpServer(settings, config)) {\n return {};\n }\n const headers: Record<string, string> = {};\n if (settings.authRequired && settings.accessKey) {\n headers[\"x-opengeni-access-key\"] = settings.accessKey;\n }\n // The delegated bearer is deliberately NOT baked here. It is re-signed PER\n // REQUEST by firstPartyAuthFetch (wired in prepareAgentTools) so a turn or\n // persistent MCP connection that outlives the token's 1h TTL never sends a\n // stale bearer — an expired first-party bearer 401s (\"authentication\n // required\"), and because the first-party server is REQUIRED that killed the\n // turn on any run past ~1h. This function keeps only NON-expiring static\n // headers (the access key); the per-request fetch wrapper is the single source\n // of truth for the ever-refreshed Authorization header.\n if (Object.keys(headers).length === 0) {\n return {};\n }\n return {\n requestInit: {\n headers,\n },\n };\n}\n\n// Sign a FRESH first-party delegated bearer for a single request. Returns null\n// when the run lacks the inputs to mint one (no delegation secret / account /\n// workspace), in which case the request proceeds with whatever static headers\n// requestInit already set. The 1h TTL is safe precisely because this runs per\n// request: the token on the wire is always seconds old, never near expiry.\nasync function signFirstPartyDelegatedBearer(\n settings: Settings,\n options: PrepareToolsOptions,\n): Promise<string | null> {\n if (!settings.delegationSecret || !options.accountId || !options.workspaceId) {\n return null;\n }\n return await signDelegatedAccessToken(settings.delegationSecret, {\n accountId: options.accountId,\n workspaceId: options.workspaceId,\n subjectId: options.subjectId ?? \"worker:first-party-mcp\",\n ...(options.subjectLabel ? { subjectLabel: options.subjectLabel } : {}),\n permissions: options.firstPartyPermissions ?? [...DEFAULT_FIRST_PARTY_MCP_PERMISSIONS],\n firstPartyMcpTools: options.firstPartyTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS],\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options.turnId ? { turnId: options.turnId } : {}),\n ...(options.attemptId ? { attemptId: options.attemptId } : {}),\n ...(options.executionGeneration ? { executionGeneration: options.executionGeneration } : {}),\n exp: Math.floor(Date.now() / 1000) + 60 * 60,\n });\n}\n\n// Per-request auth for the FIRST-PARTY MCP server: re-sign the delegated bearer\n// on EVERY request (connect/initialize, every tools/list re-list, every\n// tools/call) and set it as the Authorization header, so a turn or connection\n// outliving the 1h token TTL never sends an expired bearer. This is the fix for\n// the prod grind where a >1h turn's next re-list/tool-call 401'd on the stale\n// first-party bearer and — the first-party server being required — failed the\n// whole turn. Scoped STRICTLY to the token WE mint; external OAuth (connectionRef\n// servers) go through connectionBrokerFetch and are untouched.\nfunction firstPartyAuthFetch(\n baseFetch: FetchLike,\n settings: Settings,\n options: PrepareToolsOptions,\n): FetchLike {\n return async (input, init) => {\n const bearer = await signFirstPartyDelegatedBearer(settings, options);\n if (!bearer) {\n return await baseFetch(input, init);\n }\n return await baseFetch(\n fetchInputForAttempt(input),\n withConnectionHeaders(input, init, { authorization: `Bearer ${bearer}` }),\n );\n };\n}\n\n/**\n * Builds the connect-time auth headers for the codex_apps connectors MCP. The\n * bearer is resolved from codexRequestStorage — the SAME refreshing token source\n * the model fetch uses (proactive refresh + single-flight + db persist) — so the\n * token is valid at connect. A missing store (non-codex turn, or prepareTools\n * ran outside the ALS) or a token failure (needs_relogin) returns {} so the\n * best-effort connect drops the server rather than crashing the turn.\n */\nasync function codexAppsMcpRequestInit(\n settings: Settings,\n): Promise<{ requestInit: { headers: Record<string, string> } } | {}> {\n const ctx = codexRequestStorage.getStore();\n if (!ctx) {\n return {};\n }\n let token;\n try {\n token = await ctx.getToken();\n } catch {\n return {};\n }\n const headers: Record<string, string> = {\n authorization: `Bearer ${token.accessToken}`,\n // The ChatGPT backend sits behind Cloudflare, which 403s requests bearing a\n // default runtime User-Agent (confirmed live: an HTML bot-block page, NOT an\n // auth failure). Send the codex client identity — the same originator/version/\n // User-Agent the model fetch uses — so the MCP connect handshake passes the edge.\n originator: CODEX_ORIGINATOR,\n \"user-agent\": `${CODEX_ORIGINATOR}/${ctx.clientVersion}`,\n version: ctx.clientVersion,\n };\n if (token.chatgptAccountId) {\n headers[\"chatgpt-account-id\"] = token.chatgptAccountId;\n }\n if (settings.codexProductSku) {\n headers[\"X-OpenAI-Product-Sku\"] = settings.codexProductSku;\n }\n return { requestInit: { headers } };\n}\n\n// The first-party MCP permission set signed into a worker's delegated token\n// when the session does not specify its own. POWERFUL BY DEFAULT: it carries\n// every permission that unlocks a first-party tool — session orchestration\n// (sessions:*), workspace variable sets (variable-sets:*), rigs:use\n// (list/get/propose/verify only), and GitHub (github:use) — so agents are fully capable out of the box. A user DEMOTES a\n// specific session by setting a narrower session.firstPartyMcpPermissions (the\n// create-session permission picker), which the worker uses instead. Account-\n// level scopes (billing/account/members/api_keys/workspace:admin) are\n// intentionally excluded: they gate no first-party tool and are not agent\n// capabilities. (A finer-grained capability model comes later.)\n// codex_apps is third-party-by-trust (the external ChatGPT connectors backend)\n// but needs DYNAMIC auth, so it is its own category — deliberately NOT folded\n// into the first-party allowlist, which would wrongly sign an OpenGeni delegated\n// token to chatgpt.com.\nfunction isCodexAppsMcpServer(config: Settings[\"mcpServers\"][number]): boolean {\n return config.id === CODEX_APPS_MCP_SERVER_ID;\n}\n\nfunction isFirstPartyMcpServer(\n settings: Settings,\n config: Settings[\"mcpServers\"][number],\n): boolean {\n if (![\"opengeni\", \"files\", \"docs\"].includes(config.id)) {\n return false;\n }\n if (config.url.includes(\"{workspaceId}\")) {\n return true;\n }\n const url = normalizeUrl(config.url);\n if (!url) {\n return false;\n }\n return firstPartyMcpUrls(settings).some((candidate) => candidate === url);\n}\n\nfunction firstPartyMcpServerUrlForRun(\n settings: Settings,\n config: Settings[\"mcpServers\"][number],\n workspaceId: string | undefined,\n): string | null {\n if (!workspaceId || ![\"opengeni\", \"files\", \"docs\"].includes(config.id)) {\n return null;\n }\n if (config.url.includes(\"{workspaceId}\")) {\n return config.url.replaceAll(\"{workspaceId}\", workspaceId);\n }\n if (!isFirstPartyMcpServer(settings, config)) {\n return null;\n }\n const rawBase = settings.opengeniMcpUrl?.includes(\"{workspaceId}\")\n ? settings.opengeniMcpUrl.replaceAll(\"{workspaceId}\", workspaceId)\n : settings.opengeniMcpUrl\n ? scopedMcpUrlFromConfiguredBase(settings.opengeniMcpUrl, workspaceId)\n : // unset → the shared loopback default (a `{workspaceId}` template owned by\n // @opengeni/config's firstPartyMcpBaseUrl), scoped to this run's workspace.\n firstPartyMcpBaseUrl(settings).replaceAll(\"{workspaceId}\", workspaceId);\n const url = new URL(rawBase);\n if (config.id === \"docs\") {\n url.pathname = `${url.pathname.replace(/\\/+$/, \"\")}/docs`;\n }\n return url.toString();\n}\n\nfunction scopedMcpUrlFromConfiguredBase(raw: string, workspaceId: string): string {\n const url = new URL(raw);\n url.pathname = `/v1/workspaces/${workspaceId}/mcp`;\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n}\n\nfunction firstPartyMcpUrls(settings: Settings): string[] {\n // Route the unset case through the shared loopback default so the literal\n // lives in exactly one place (@opengeni/config's firstPartyMcpBaseUrl).\n const base = normalizeUrl(settings.opengeniMcpUrl ?? firstPartyMcpBaseUrl(settings));\n if (!base) {\n return [];\n }\n const docs = new URL(base);\n docs.pathname = `${docs.pathname.replace(/\\/+$/, \"\")}/docs`;\n return [base, normalizeUrl(docs.toString())].filter((value): value is string => Boolean(value));\n}\n\nfunction normalizeUrl(raw: string): string | null {\n try {\n const url = new URL(raw);\n url.hash = \"\";\n url.pathname = url.pathname.replace(/\\/+$/, \"\");\n return url.toString();\n } catch {\n return null;\n }\n}\n\nexport function prefixedMcpToolName(registryId: string, toolName: string): string {\n return sharedPrefixedMcpToolName(registryId, toolName);\n}\n\nclass PrefixedMcpServer implements MCPServer {\n readonly cacheToolsList: boolean;\n readonly name: string;\n readonly prefix: string;\n private readonly allowedTools: Set<string> | undefined;\n // Best-effort servers (optional refs, connectionRef-backed capability MCPs,\n // codex_apps) must never fail a turn: a tools/list throw degrades to zero\n // tools instead of propagating. Deduplicate the warn so one degraded server\n // doesn't spam the log when the SDK re-lists across model turns.\n private readonly bestEffort: boolean;\n private loggedListToolsFailure = false;\n private listedToolSchemaTokens = 0;\n private modelToolSchemaAccountingDeferred = false;\n\n constructor(\n private readonly inner: MCPServer,\n registryId: string,\n allowedTools?: string[],\n bestEffort = false,\n private readonly aggregateToolBudget?: McpAggregateToolListBudget,\n private readonly aggregateSourceId = registryId,\n ) {\n this.name = registryId;\n this.prefix = prefixedMcpToolName(registryId, \"\");\n this.cacheToolsList = inner.cacheToolsList;\n this.allowedTools = allowedTools ? new Set(allowedTools) : undefined;\n this.bestEffort = bestEffort;\n }\n\n connect(): Promise<void> {\n return this.inner.connect().catch((error: unknown) => {\n // connectMcpServers has its own global logger and logs the thrown Error.\n // Never let a raw transport response body cross that logging boundary.\n throw safeMcpTransportError(error);\n });\n }\n\n close(): Promise<void> {\n this.releaseAggregateBudget();\n return this.inner.close();\n }\n\n releaseAggregateBudget(): void {\n this.aggregateToolBudget?.remove(this.aggregateSourceId);\n }\n\n async listTools(): Promise<RuntimeMcpTool[]> {\n try {\n const tools = assertMcpToolListWithinBounds(await this.inner.listTools()) as RuntimeMcpTool[];\n const exposed = tools\n .filter((tool) => this.isAllowed(tool.name))\n .map((tool) => ({\n ...tool,\n name: prefixedMcpToolName(this.name, tool.name),\n }));\n const bounded = (this.aggregateToolBudget?.replace(this.aggregateSourceId, exposed) ??\n assertMcpToolListWithinBounds(exposed)) as RuntimeMcpTool[];\n this.listedToolSchemaTokens = estimateSerializedValueTokens(bounded);\n return bounded;\n } catch (error) {\n // A REQUIRED server's tools/list failure is fatal (fail-loud default): the\n // caller explicitly requested it, so its absence must fail the turn.\n if (!this.bestEffort) {\n throw error;\n }\n // Best-effort isolation. The SDK's run-time getAllMcpTools calls listTools\n // OUTSIDE the connect-time connectMcpServers({ strict: false }) guard, so a\n // best-effort server whose tools/list throws here — for ANY reason (an\n // expired/failed connection credential surfacing as a StreamableHTTP\n // \"authentication required\" 401, a provider 5xx, a network blip) — would\n // otherwise take down an unrelated turn. Drop this server's tools for the\n // turn instead. An auth failure additionally published tool.auth_needed via\n // the connection-broker fetch before the throw (so that actionable signal\n // is preserved), but a non-auth failure has NO such signal — the structured\n // warn below is its only visibility, so a chronically-dead optional\n // integration surfaces in logs/metrics rather than being silently swallowed.\n // Warn once per degraded server per turn (instances are per-turn), so a\n // re-list across model turns does not spam the log.\n if (!this.loggedListToolsFailure) {\n this.loggedListToolsFailure = true;\n console.warn(\n \"[mcp] best-effort server tools/list failed; its tools are unavailable this turn\",\n // Safe surface only (class + numeric status), never the raw error\n // message/response body — a broker 401/403 body can echo request detail.\n { serverId: this.name, ...safeMcpErrorFields(error) },\n );\n }\n this.releaseAggregateBudget();\n return [];\n }\n }\n\n /** Latest exact tools/list projection used to build the model request. */\n modelToolSchemaTokens(): number {\n return this.modelToolSchemaAccountingDeferred ? 0 : this.listedToolSchemaTokens;\n }\n\n /**\n * Keep model-input accounting aligned with Codex `defer_loading`: the full\n * schema is not provider context until a tool_search_output discloses it.\n * Instances are turn-local, so this cannot leak into a non-Codex turn.\n */\n deferModelToolSchemaAccounting(): void {\n this.modelToolSchemaAccountingDeferred = true;\n }\n\n async callTool(\n toolName: string,\n args: Record<string, unknown> | null,\n meta?: Record<string, unknown> | null,\n ): Promise<any> {\n const unprefixed = this.unprefixToolName(toolName);\n if (!this.isAllowed(unprefixed)) {\n throw new Error(`MCP tool ${unprefixed} is not allowed for server ${this.name}`);\n }\n try {\n const output = await this.inner.callTool(unprefixed, args, meta);\n assertMcpPayloadWithinBytes(output, MCP_MAX_TOOL_RESULT_BYTES, \"MCP tool result\");\n return output;\n } catch (error) {\n // The connection broker's auth-needed short-circuit arrives as a thrown\n // JSON-RPC error (an inline isError result would be stripped by the SDK\n // shim). Surface it to the model as a failed-but-recoverable tool result\n // instead of failing the turn; the timeline chip was already published.\n // This applies to ANY server — an auth-needed is recoverable once the user\n // re-links, so even a required tool degrades gracefully here.\n if (isAuthNeededMcpError(error)) {\n return {\n isError: true,\n content: [{ type: \"text\", text: MCP_AUTH_NEEDED_MESSAGE }],\n };\n }\n // Best-effort INVOCATION isolation (sibling to the listTools guard). When\n // the model calls a best-effort server's tool and the call throws for ANY\n // other reason — a raw transport 401/403 that never became the broker's\n // JSON-RPC short-circuit (e.g. a codex_apps bearer that expired mid-turn,\n // or a 403 with no insufficient_scope challenge), a provider 5xx, or a\n // network blip — the whole turn would otherwise die. Return a tool-error\n // RESULT the model sees instead, so it adapts (tries another approach,\n // tells the user) and the turn survives. Required servers keep the\n // fail-loud default: the caller depends on them, so their tool failure\n // still fails the turn. For auth cases the actionable tool.auth_needed was\n // already published upstream by the connection-broker fetch before the\n // throw, so degrading here never silences it.\n if (this.bestEffort) {\n const fields = safeMcpErrorFields(error);\n console.warn(\n \"[mcp] best-effort server tool call failed; returning an unavailable result for this turn\",\n { serverId: this.name, toolName: unprefixed, ...fields },\n );\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: mcpToolUnavailableMessage(mcpErrorReason(fields)),\n },\n ],\n };\n }\n throw error;\n }\n }\n\n invalidateToolsCache(): Promise<void> {\n return this.inner.invalidateToolsCache();\n }\n\n async listResources(params?: Record<string, unknown>): Promise<any> {\n const resourcesServer = this.inner as MCPServer & {\n listResources?: (params?: Record<string, unknown>) => Promise<any>;\n };\n if (!resourcesServer.listResources) {\n throw new Error(`MCP server ${this.name} does not support resources`);\n }\n return await resourcesServer.listResources(params);\n }\n\n async listResourceTemplates(params?: Record<string, unknown>): Promise<any> {\n const resourcesServer = this.inner as MCPServer & {\n listResourceTemplates?: (params?: Record<string, unknown>) => Promise<any>;\n };\n if (!resourcesServer.listResourceTemplates) {\n throw new Error(`MCP server ${this.name} does not support resource templates`);\n }\n return await resourcesServer.listResourceTemplates(params);\n }\n\n async readResource(uri: string): Promise<any> {\n const resourcesServer = this.inner as MCPServer & {\n readResource?: (uri: string) => Promise<any>;\n };\n if (!resourcesServer.readResource) {\n throw new Error(`MCP server ${this.name} does not support resource reads`);\n }\n return await resourcesServer.readResource(uri);\n }\n\n private isAllowed(toolName: string): boolean {\n return !this.allowedTools || this.allowedTools.has(toolName);\n }\n\n private unprefixToolName(toolName: string): string {\n if (!toolName.startsWith(this.prefix)) {\n throw new Error(`MCP tool ${toolName} is missing expected ${this.name} prefix`);\n }\n return toolName.slice(this.prefix.length);\n }\n}\n\n// createSandboxClient (+ withDockerNetwork / connectDockerNetwork) moved to the\n// agent-loop-free leaf ./sandbox; re-exported via `export * from \"./sandbox\"`.\n\nexport type PrepareInputOptions = {\n sandboxClient?: unknown;\n};\n\nexport async function prepareRunInput(\n agent: Agent<any, any>,\n input: AgentSegmentInput,\n options: PrepareInputOptions = {},\n): Promise<PreparedAgentInput> {\n if (input.kind === \"message\") {\n const trailingMessages: AgentInputItem[] = [];\n if (input.internalContext?.trim()) {\n trailingMessages.push({\n type: \"message\",\n role: \"system\",\n content: input.internalContext,\n } as AgentInputItem);\n }\n if (input.text?.trim()) {\n trailingMessages.push({\n type: \"message\",\n role: \"user\",\n content: input.text,\n } as AgentInputItem);\n }\n if (\n trailingMessages.length === 0 &&\n (input.historyItems === undefined ||\n input.historyItems === null ||\n input.historyItems.length === 0)\n ) {\n throw new Error(\"Message input requires a user prompt or internal context\");\n }\n // Conversation truth comes only from durable history items. Sanitize the\n // in-memory copy before it reaches the model so a corrupt tool-call pair is\n // non-fatal; stored audit rows remain untouched.\n const sanitizedHistory = sanitizeHistoryItemsForModel(\n (input.historyItems ?? []) as unknown as Array<Record<string, unknown>>,\n ) as unknown as AgentInputItem[];\n const sandboxSessionState = input.sandboxEnvelope\n ? await restoredSandboxSessionStateFromEntry(input.sandboxEnvelope, options.sandboxClient)\n : undefined;\n const assembled = [...sanitizedHistory, ...trailingMessages];\n if (assembled.length === 0) {\n throw new Error(\"Message input requires durable history or internal context\");\n }\n return {\n // Preserve the SDK's simple first-message form without creating a second\n // history path: this is merely the zero-history representation.\n input:\n sanitizedHistory.length === 0 && !input.internalContext?.trim() && input.text?.trim()\n ? input.text\n : assembled,\n ...(sandboxSessionState ? { sandboxSessionState } : {}),\n };\n }\n // An interrupted tool can only be resumed against a real saved run state. If the\n // latest blob is the cleared sentinel the awaiting turn was wiped (the API\n // refuses clear in requires_action, so this is a defensive guard) — fail with\n // an honest message instead of the cryptic SDK \"missing schema version\".\n if (isClearedRunStateBlob(input.serializedRunState)) {\n throw new Error(\n \"Cannot resume an interrupted tool: the session context was cleared, so the awaiting run state no longer exists.\",\n );\n }\n const state = await RunState.fromString(agent, input.serializedRunState);\n const interruptions = state.getInterruptions();\n const interruptionId = input.kind === \"human_input\" ? input.toolCallId : input.approvalId;\n const target = interruptions.find((item: any) => approvalIdentifier(item) === interruptionId);\n if (!target) {\n throw new Error(`Interrupted tool not found in saved run state: ${interruptionId}`);\n }\n if (input.kind === \"human_input\") {\n state.approve(target as any);\n } else if (input.decision === \"approve\") {\n state.approve(target as any);\n } else {\n state.reject(target as any, input.message ? { message: input.message } : undefined);\n }\n return { input: state };\n}\n\nexport type RunAgentStreamOptions = {\n /** Abort the provider/tool loop when the owning activity is cancelled. */\n signal?: AbortSignal;\n sandboxClient?: unknown;\n sandboxEnvironment?: Record<string, string>;\n onRuntimeEvent?: (event: NormalizedRuntimeEvent) => Promise<void> | void;\n contextCompactionSignal?: () => ProviderContextTokenSignal | null | undefined;\n contextCompactionRequested?: () => boolean | Promise<boolean>;\n // Host-managed git credential renewal registration. Called only after the\n // initial token-file seed completed on a real provisioned box. The worker\n // owns the multi-day timer and uses this pinned, un-proxied session to\n // atomically replace token files; runtime never mints credentials itself.\n onGitCredentialSessionReady?: (session: GitCredentialTokenWriterSession) => Promise<void> | void;\n // OpenGeni-minted Toolspace token renewal registration. Called only after the\n // initial token file reached the real sandbox session.\n onToolspaceTokenSessionReady?: (session: ToolspaceTokenWriterSession) => Promise<void> | void;\n // Host-owned run material is seeded off-manifest before setup and every\n // agent-created process sources the active immutable generation. The worker\n // owns resolution/renewal/fencing; runtime owns sandbox transport.\n runCredentialSessionId?: string;\n onRunCredentialSessionReady?: RunCredentialSessionReady;\n // OWNERSHIP INVERSION (P1.2): an externally-owned, already-live sandbox\n // session resolved by the per-turn resume-by-id path. When present,\n // runAgentStream does NOT build (or resume, or discard) a client — it threads\n // these straight into runOptions.sandbox as a NON-OWNED session. The SDK\n // registers a provided session non-owned (manager.js) and NEVER reaps it on a\n // normal finish (proven by spikes/sdk-keystone) — that is the keystone: the\n // one box survives across turns. Mutually exclusive with the per-run\n // createSandboxClient path (the owned branch takes precedence when both set).\n // Agent-dependent decorators (file-downloads, lifecycle/repo-clone hooks) are\n // re-applied around the resumed client here; the live `session`/`sessionState`\n // carry the box, so no create()/resume() is re-invoked inside run().\n ownedSandbox?: {\n client: unknown; // built by the per-turn resume path (the raw provider client)\n session: unknown; // SandboxSessionLike — the live, NON-OWNED handle (never reaped)\n sessionState?: unknown; // SandboxSessionState the box was resumed from\n // The UN-PROXIED established box for platform setup (lifecycle hooks + file\n // resource materialization). `session` may be the mid-turn routing proxy whose\n // every exec re-reads the active pointer — platform-initiated setup must NOT\n // follow a swap onto a connected machine (the user's real computer), so it\n // runs against this pinned handle instead. Absent -> falls back to `session`.\n setupSession?: unknown;\n // True when the caller already ran file-resource materialization for this\n // provided session and threaded any failures into the model input.\n fileDownloadsMaterialized?: boolean;\n // Lazy sandbox provisioning injects a synthetic provided session at run start;\n // the real box does not exist until the first sandbox op. In that path the\n // worker provisioner runs runOwnedSandboxSetup against the un-proxied real box\n // after establish, so runAgentStream must not run it eagerly here.\n deferredSetup?: boolean;\n };\n /**\n * The attempt's authoritative physical sandbox-operation fence. Platform\n * lifecycle commands use its command runner too, so Steer/Pause can interrupt\n * repository clone, rig setup, file materialization, and credential seeding\n * before the attempt-quiesced receipt opens queue admission.\n */\n turnToolCancellationFence?: TurnToolCancellationFence;\n // A per-turn model-input filter chained AFTER the provider-item-id strip.\n // Used by the genesis-title injection to prepend a hidden, NON-PERSISTED\n // directive: a callModelInputFilter mutates only `modelData.input` for each\n // model call and never touches `state.history`/`originalInput`, so the\n // reconcile dual-write never sees it.\n callModelInputFilter?: CallModelInputFilter;\n};\n\nexport type ContextRobustnessFilterOptions = {\n contextCompactionSignal?: () => ProviderContextTokenSignal | null | undefined;\n contextCompactionRequested?: () => boolean | Promise<boolean>;\n throwOnCompactionNeeded?: boolean;\n};\n\n// One-shot directive injected into the FIRST model call on the genesis turn\n// (see buildOpenGeniAgent's genesisTitleHint). Delivered through the\n// authoritative instructions channel so the model reliably obeys; references\n// the prefixed tool name the agent actually sees (opengeni__set_session_title).\nexport const GENESIS_TITLE_DIRECTIVE =\n \"This is the first turn of a new session. Before responding to the user, call the opengeni__set_session_title tool with a concise 3-7 word title that summarizes what this session is about, then address the user's request normally.\";\n\n/**\n * Inject the genesis-title directive into exactly one model request. Agent\n * instructions are reused for every model call in a tool loop, so placing this\n * directive there turned a nominally one-shot setup action into repeated title\n * calls. The closure is intentionally consumed even when the first request\n * fails: a retry/recovery must continue the task, not restart setup.\n */\nexport function oneShotGenesisTitleInputFilter(): CallModelInputFilter {\n let pending = true;\n return ({ modelData }) => {\n if (!pending) {\n return modelData;\n }\n pending = false;\n return {\n ...modelData,\n instructions: modelData.instructions\n ? `${modelData.instructions} ${GENESIS_TITLE_DIRECTIVE}`\n : GENESIS_TITLE_DIRECTIVE,\n };\n };\n}\n\nfunction takeGenesisTitleInputFilter(agent: Agent<any, any>): CallModelInputFilter | undefined {\n if (!agentsNeedingGenesisTitleDirective.has(agent)) {\n return undefined;\n }\n agentsNeedingGenesisTitleDirective.delete(agent);\n return oneShotGenesisTitleInputFilter();\n}\n\n// Generic substrate prompting for programmatic tool calling (toolspace). Same\n// text for every host; gated per-turn by appendToolspaceInstructions on the\n// presence of a minted toolspace token, so it only appears when the sandbox\n// exposes $OPENGENI_TOOLSPACE_URL/_TOKEN_FILE. Stock images carry ogtool;\n// custom environments get only an exact deployment-pinned bootstrap hint.\nexport const TOOLSPACE_PROGRAMMATIC_DIRECTIVE =\n \"Every tool on your MCP surface is also callable programmatically from the sandbox shell, so scripts can invoke tools without a model round trip per call. If `ogtool` is installed, run `ogtool list` to see the available tools and their input schemas (from tools/list), then `ogtool call <tool-name> '<json-args>'`. If it is absent and both npm and $OPENGENI_OGTOOL_PACKAGE_SPEC are available, run the exact deployment-pinned package with `npm exec --yes --package=\\\"$OPENGENI_OGTOOL_PACKAGE_SPEC\\\" -- ogtool ...`; never guess a version or install `latest`. Otherwise POST MCP JSON-RPC directly to $OPENGENI_TOOLSPACE_URL with the bearer token read from $OPENGENI_TOOLSPACE_TOKEN_FILE. Prefer programmatic calls for loops, polling, and bulk filtering: their results stay in the sandbox and do not consume your context window. Tools that require human approval must still be invoked normally — called programmatically they return a typed error.\";\n\n/**\n * callModelInputFilter that removes provider-assigned item ids (rs_/msg_/fc_…)\n * from every input item immediately before each model call. Responses-API\n * requests that carry item ids are resolved against the provider's stored\n * responses, and that store is not durable enough to anchor long runs on: a\n * response that streamed successfully can be missing from the store on the\n * very next call, which then fails with 400 \"Item with id ... not found\"\n * (observed live on Azure OpenAI mid-turn). All item content — including the\n * encrypted reasoning payload carried in providerData when\n * `openaiReasoningEncryptedContent` is on — is sent inline, so the ids add\n * fragility without adding information. Pairing fields (`call_id`/`callId`)\n * are separate properties and stay untouched; items are cloned, never mutated.\n */\nexport const stripProviderItemIdsFilter: CallModelInputFilter = ({ modelData }) => ({\n ...modelData,\n input: modelData.input.map((item) => {\n if (item && typeof item === \"object\" && \"id\" in item) {\n const { id: _id, ...rest } = item as Record<string, unknown>;\n return rest as AgentInputItem;\n }\n return item;\n }),\n});\n\n/**\n * callModelInputFilter that normalizes every `computer_call` carrying BOTH\n * `action` and `actions` down to EXACTLY ONE (keeps `actions`, drops `action`).\n * The Azure computer-use endpoint rejects a request whose computer_call has\n * both with `400 Computer call input must include exactly one of `action` or\n * `actions``; and (live-proven against gpt-5.6-sol's GA computer tool) it also\n * rejects the `action`-only form, accepting ONLY the batched plural `actions`.\n * The SDK 0.11.6 schema allows both, so a freshly-emitted\n * screenshot call carries the redundant pair. This filter runs before EVERY\n * model call — the turn-start history replay AND every mid-turn follow-up — so\n * it covers the just-emitted (non-replayed) computer_call on the same turn,\n * which the turn-start `prepareRunInput` sanitizer never sees. Items are cloned,\n * never mutated.\n */\nexport const normalizeComputerCallsFilter: CallModelInputFilter = ({ modelData }) => ({\n ...modelData,\n input: normalizeComputerCallActions(\n modelData.input as unknown as Array<Record<string, unknown>>,\n ) as unknown as AgentInputItem[],\n});\n\n/**\n * Per-call state compaction for local image inspection. Re-opening the same\n * path supersedes its prior base64 result; carrying both provides no newer\n * information and can otherwise balloon every following model request.\n */\nexport const elideSupersededViewImagesFilter: CallModelInputFilter = ({ modelData }) => ({\n ...modelData,\n input: elideSupersededViewImagePairs(\n modelData.input as unknown as Array<Record<string, unknown>>,\n ) as unknown as AgentInputItem[],\n});\n\n/**\n * Canonical Codex-style tool-result bound at the final model-input seam. The\n * identical pure normalizer also runs before conversation rows are persisted,\n * so this is a live-turn defense rather than a request-only alternate history.\n */\nexport function boundModelToolOutputsFilterForSettings(settings: Settings): CallModelInputFilter {\n return ({ modelData }) => ({\n ...modelData,\n input: boundModelToolOutputItems(\n modelData.input as unknown as Array<Record<string, unknown>>,\n settings.modelToolOutputTruncationTokens,\n ) as unknown as AgentInputItem[],\n });\n}\n\nfunction estimateAgentToolSchemaTokens(agent: Agent<any, any>): number {\n const localTools = Array.isArray((agent as { tools?: unknown }).tools)\n ? ((agent as { tools: unknown[] }).tools ?? [])\n : [];\n const localDescriptors = localTools.map((candidate) => {\n if (!candidate || typeof candidate !== \"object\") return candidate;\n const tool = candidate as Record<string, unknown>;\n return {\n type: tool.type,\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n inputSchema: tool.inputSchema,\n strict: tool.strict,\n providerData: tool.providerData,\n };\n });\n const mcpServers = Array.isArray((agent as { mcpServers?: unknown }).mcpServers)\n ? ((agent as { mcpServers: unknown[] }).mcpServers ?? [])\n : [];\n const mcpTokens = mcpServers.reduce<number>((total, server) => {\n const getter = (server as { modelToolSchemaTokens?: () => number } | null)\n ?.modelToolSchemaTokens;\n return total + (typeof getter === \"function\" ? getter.call(server) : 0);\n }, 0);\n return estimateSerializedValueTokens(localDescriptors) + mcpTokens;\n}\n\nexport function contextRobustnessFilterForSettings(\n settings: Settings,\n options: ContextRobustnessFilterOptions = {},\n): CallModelInputFilter {\n const thresholdTokens = compactionThresholdTokens(settings);\n let previousRequest: { revision: number; footprint: CompleteModelInputFootprint } | null = null;\n let requestRevision = 0;\n return async ({ modelData, agent }) => {\n const input = modelData.input;\n if (options.throwOnCompactionNeeded) {\n const reported = options.contextCompactionSignal?.();\n const current: CompleteModelInputFootprint = {\n input: input as unknown as Array<Record<string, unknown>>,\n instructionsTokens: estimateSerializedValueTokens(modelData.instructions ?? \"\"),\n toolSchemaTokens: estimateAgentToolSchemaTokens(agent),\n };\n // Stream consumption can lag the SDK's background model loop. A provider\n // usage signal is safe only when its response revision belongs to the\n // immediately preceding request. Never attach a delayed response count to\n // a newer footprint: doing so can hide all model output produced between\n // them and recreate an under-counting compaction loop.\n const boundProvider =\n reported &&\n previousRequest &&\n reported.revision === previousRequest.revision &&\n hasModelGeneratedItem(current.input)\n ? reported\n : null;\n const estimate = estimateCompleteModelInput({\n current,\n provider: boundProvider,\n providerRequestFootprint: boundProvider ? (previousRequest?.footprint ?? null) : null,\n });\n const signalTokens = estimate.tokens;\n previousRequest = { revision: ++requestRevision, footprint: current };\n if (await options.contextCompactionRequested?.()) {\n throw new CompactionNeededError({\n signalTokens,\n thresholdTokens,\n signalSource: boundProvider ? \"provider\" : \"estimate\",\n trigger: \"operator\",\n });\n }\n if (signalTokens >= thresholdTokens) {\n throw new CompactionNeededError({\n signalTokens,\n thresholdTokens,\n signalSource: boundProvider ? \"provider\" : \"estimate\",\n });\n }\n }\n return { ...modelData, input };\n };\n}\n\n/**\n * Compose a list of callModelInputFilters into one, applied left-to-right so\n * each sees the prior filter's output.\n */\nfunction composeCallModelInputFilters(filters: CallModelInputFilter[]): CallModelInputFilter {\n return async (args) => {\n let modelData = args.modelData;\n for (const filter of filters) {\n modelData = await filter({ ...args, modelData });\n }\n return modelData;\n };\n}\n\n/**\n * The model-input filter applied before every model call. The computer_call\n * action/actions normalizer is ALWAYS on (the Azure endpoint 400s without it);\n * the provider-item-id strip is layered on top when the configured policy\n * selects it; the context-robustness guard then raises the proactive durable\n * compaction signal on the client-compaction path. It never trims history from\n * an individual request.\n */\nexport function callModelInputFilterForSettings(\n settings: Settings,\n options: ContextRobustnessFilterOptions = {},\n): CallModelInputFilter | undefined {\n const filters: CallModelInputFilter[] = [\n normalizeComputerCallsFilter,\n elideSupersededViewImagesFilter,\n boundModelToolOutputsFilterForSettings(settings),\n ];\n if (settings.openaiProviderItemIds === \"strip\") {\n filters.push(stripProviderItemIdsFilter);\n }\n filters.push(contextRobustnessFilterForSettings(settings, options));\n return composeCallModelInputFilters(filters);\n}\n\nexport async function runAgentStream(\n agent: Agent<any, any>,\n input: PreparedAgentInput | string | RunState<any, any>,\n settings: Settings,\n overrides: RunAgentStreamOptions = {},\n) {\n const prepared: PreparedAgentInput =\n typeof input === \"string\" || input instanceof RunState ? { input } : input;\n const environment = overrides.sandboxEnvironment ?? collectSandboxEnvironment(settings);\n const toolspaceTokenFile = toolspaceTokenFileForAgent(agent, environment);\n const genesisTitleInputFilter = takeGenesisTitleInputFilter(agent);\n if (overrides.onRunCredentialSessionReady && !overrides.runCredentialSessionId) {\n throw new Error(\"runCredentialSessionId is required when run credential setup is enabled\");\n }\n\n // OWNED PATH (P1.2 ownership inversion): the per-turn resume path injected a\n // live, externally-owned box. We thread the live `session` straight into\n // runOptions.sandbox so the SDK registers it NON-OWNED and never reaps it on\n // a normal finish (the keystone). We re-apply ONLY the agent-dependent\n // decorators (file-downloads + lifecycle/repo-clone hooks) around the resumed\n // client — the manifest-refresh-on-resume wrap is a no-op when a live\n // `session` is supplied (resume is not re-invoked). This branch is reached\n // ONLY when sandboxOwnershipEnabled gated the activity into resolving a box;\n // with the flag off the activity never sets `ownedSandbox` and this whole\n // block is skipped (byte-for-byte the legacy path).\n if (overrides.ownedSandbox) {\n const { client: ownedClient, session, sessionState } = overrides.ownedSandbox;\n // Platform setup (hooks + file materialization) execs against the UN-PROXIED\n // established box when the caller pinned one — never through the routing proxy,\n // whose per-op pointer re-read could land these execs on a machine swapped in\n // mid-turn.\n const setupSession = (overrides.ownedSandbox.setupSession ?? session) as SandboxSessionLike;\n const credentialAgentSession = overrides.runCredentialSessionId\n ? withRunCredentialsSession(session as SandboxSessionLike, overrides.runCredentialSessionId)\n : (session as SandboxSessionLike);\n const agentSession = toolspaceTokenFile\n ? withToolspaceTokenSession(credentialAgentSession, toolspaceTokenFile)\n : credentialAgentSession;\n const credentialSetupSession = overrides.runCredentialSessionId\n ? withRunCredentialsSession(setupSession, overrides.runCredentialSessionId)\n : setupSession;\n const decoratedSetupSession = toolspaceTokenFile\n ? withToolspaceTokenSession(credentialSetupSession, toolspaceTokenFile)\n : credentialSetupSession;\n // Platform setup (manifest-env pin + beforeAgentStart hooks + file downloads)\n // against the UN-proxied established box — the ONE-TRUTH helper shared with the\n // lazy provisioner. Eager path: runs here, before the run starts (unchanged).\n if (!overrides.ownedSandbox.deferredSetup) {\n await overrides.onRunCredentialSessionReady?.(session as SandboxSessionLike);\n await runOwnedSandboxSetup(agent, session as SandboxSessionLike, decoratedSetupSession, {\n settings,\n environment,\n preparedInput: prepared,\n ...(overrides.ownedSandbox.fileDownloadsMaterialized\n ? { fileDownloadsMaterialized: true }\n : {}),\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n ...(overrides.turnToolCancellationFence\n ? {\n commandRunner: overrides.turnToolCancellationFence.runSandboxCommand.bind(\n overrides.turnToolCancellationFence,\n ),\n }\n : {}),\n });\n if (toolspaceTokenSeedForAgent(agent)) {\n await overrides.onToolspaceTokenSessionReady?.(agentSession);\n }\n await overrides.onGitCredentialSessionReady?.(setupSession);\n }\n const runAs = sandboxRunAs(settings);\n const fileDownloads = sandboxFileDownloadsForAgent(agent);\n const resourceClient =\n fileDownloads.length > 0\n ? withSandboxFileDownloads(ownedClient as SandboxClient, fileDownloads, {\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n ...(overrides.turnToolCancellationFence\n ? {\n commandRunner: overrides.turnToolCancellationFence.runSandboxCommand.bind(\n overrides.turnToolCancellationFence,\n ),\n }\n : {}),\n })\n : (ownedClient as SandboxClient);\n // TOKEN-BROKER (B1): the per-turn git token seed, forwarded OFF-MANIFEST so the\n // repository-clone hook seeds it to the box's token file before the clone.\n const ownedGitTokenSeeds = gitTokenSeedsForAgent(agent);\n const ownedGitCredentialBindings = gitCredentialBindingsForAgent(agent);\n const ownedToolspaceTokenSeed = toolspaceTokenSeedForAgent(agent);\n const ownedRigSetup = rigSetupDescriptorForAgent(agent);\n const ownedHooks = [\n // M3: rig setup runs FIRST so any tooling it installs is present for the\n // credential / repository-clone hooks below. The rig's credential hooks are\n // unioned into the deployment preparation-profile hooks (deduped by id).\n ...sandboxRigSetupHooksForAgent(agent),\n ...unionCredentialHooks(\n sandboxLifecycleHooksForIds(sandboxLifecycleHookIds(settings)),\n rigCredentialHooksForAgent(agent),\n ),\n ...sandboxToolspaceTokenHooksForAgent(agent),\n ...toolspaceTokenSessionRegistrationHooks(\n ownedToolspaceTokenSeed ? overrides.onToolspaceTokenSessionReady : undefined,\n ),\n ...sandboxRepositoryCloneHooksForAgent(agent),\n ...gitCredentialSessionRegistrationHooks(overrides.onGitCredentialSessionReady),\n ];\n const ownedHookContext: SandboxLifecycleHookContext = {\n environment,\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n ...(ownedGitTokenSeeds ? { gitTokenSeeds: ownedGitTokenSeeds } : {}),\n ...(ownedGitCredentialBindings ? { gitCredentialBindings: ownedGitCredentialBindings } : {}),\n ...(ownedToolspaceTokenSeed ? { toolspaceTokenSeed: ownedToolspaceTokenSeed } : {}),\n ...(toolspaceTokenFile ? { toolspaceTokenFile } : {}),\n ...(ownedRigSetup ? { rigSetup: ownedRigSetup } : {}),\n };\n // Keep both credential seeding and lifecycle decoration as a safety net for\n // any session the SDK does create/resume during this run. They are inert for\n // the provided session, which remains the normal ownership-inverted path.\n const credentialResourceClient = overrides.runCredentialSessionId\n ? withRunCredentialsClient(\n resourceClient,\n overrides.runCredentialSessionId,\n overrides.onRunCredentialSessionReady,\n )\n : resourceClient;\n const toolspaceResourceClient = toolspaceTokenFile\n ? withToolspaceTokenClient(credentialResourceClient, toolspaceTokenFile)\n : credentialResourceClient;\n const decoratedClient = withSandboxLifecycleHooks(\n toolspaceResourceClient,\n ownedHooks,\n ownedHookContext,\n );\n const ownedFilter = composeCallModelInputFilters(\n [\n callModelInputFilterForSettings(settings),\n genesisTitleInputFilter,\n overrides.callModelInputFilter,\n // A caller filter may synthesize model input. Re-apply the idempotent\n // canonical bound at the literal final seam before accounting/provider\n // serialization so no extension can bypass the policy.\n boundModelToolOutputsFilterForSettings(settings),\n contextRobustnessFilterForSettings(settings, {\n throwOnCompactionNeeded: Boolean(\n overrides.contextCompactionSignal || overrides.contextCompactionRequested,\n ),\n ...(overrides.contextCompactionSignal\n ? { contextCompactionSignal: overrides.contextCompactionSignal }\n : {}),\n ...(overrides.contextCompactionRequested\n ? { contextCompactionRequested: overrides.contextCompactionRequested }\n : {}),\n }),\n ].filter((f): f is CallModelInputFilter => Boolean(f)),\n );\n const ownedRunOptions: Parameters<typeof run>[2] = {\n stream: true,\n maxTurns: settings.agentMaxModelCallsPerTurn,\n callModelInputFilter: ownedFilter,\n ...(overrides.signal ? { signal: overrides.signal } : {}),\n };\n ownedRunOptions.sandbox = {\n client: decoratedClient,\n session: agentSession,\n ...(sessionState ? { sessionState } : {}),\n } as SandboxRunConfig;\n return await runScopedRunner(settings).run(agent, prepared.input, ownedRunOptions);\n }\n\n const rawClient = overrides.sandboxClient ?? createSandboxClient(settings, environment);\n const refreshedClient = rawClient\n ? withManifestRefreshOnResume(\n rawClient as SandboxClient,\n (agent as { defaultManifest?: Manifest }).defaultManifest,\n {\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n },\n )\n : undefined;\n const runAs = sandboxRunAs(settings);\n const fileDownloads = sandboxFileDownloadsForAgent(agent);\n const resourceClient =\n refreshedClient && fileDownloads.length > 0\n ? withSandboxFileDownloads(refreshedClient, fileDownloads, {\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n })\n : refreshedClient;\n const credentialClient =\n resourceClient && overrides.runCredentialSessionId\n ? withRunCredentialsClient(\n resourceClient,\n overrides.runCredentialSessionId,\n overrides.onRunCredentialSessionReady,\n )\n : resourceClient;\n const toolspaceClient =\n credentialClient && toolspaceTokenFile\n ? withToolspaceTokenClient(credentialClient, toolspaceTokenFile)\n : credentialClient;\n // TOKEN-BROKER (B1): the per-turn git token seed, forwarded OFF-MANIFEST so the\n // repository-clone hook seeds it to the box's token file before the clone.\n const gitTokenSeeds = gitTokenSeedsForAgent(agent);\n const gitCredentialBindings = gitCredentialBindingsForAgent(agent);\n const toolspaceTokenSeed = toolspaceTokenSeedForAgent(agent);\n const legacyRigSetup = rigSetupDescriptorForAgent(agent);\n const client = toolspaceClient\n ? withSandboxLifecycleHooks(\n toolspaceClient,\n [\n // M3: same rig-setup-first ordering + credential-hook union as the owned\n // path (this legacy create/resume decoration path is byte-for-byte today\n // for a rig-less turn — the rig hooks are empty then).\n ...sandboxRigSetupHooksForAgent(agent),\n ...unionCredentialHooks(\n sandboxLifecycleHooksForIds(sandboxLifecycleHookIds(settings)),\n rigCredentialHooksForAgent(agent),\n ),\n ...sandboxToolspaceTokenHooksForAgent(agent),\n ...toolspaceTokenSessionRegistrationHooks(\n toolspaceTokenSeed ? overrides.onToolspaceTokenSessionReady : undefined,\n ),\n ...sandboxRepositoryCloneHooksForAgent(agent),\n ...gitCredentialSessionRegistrationHooks(overrides.onGitCredentialSessionReady),\n ],\n {\n environment,\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n ...(gitTokenSeeds ? { gitTokenSeeds } : {}),\n ...(gitCredentialBindings ? { gitCredentialBindings } : {}),\n ...(toolspaceTokenSeed ? { toolspaceTokenSeed } : {}),\n ...(toolspaceTokenFile ? { toolspaceTokenFile } : {}),\n ...(legacyRigSetup ? { rigSetup: legacyRigSetup } : {}),\n },\n )\n : undefined;\n const sandboxSessionState = prepared.sandboxSessionState;\n // Apply the built-in per-call filters (computer-call normalization, optional\n // provider-id stripping, image/budget guard), then any per-turn filter\n // (genesis title directive). A callModelInputFilter only shapes the per-call\n // model input; the SDK persists filtered clones into its session view, while\n // OpenGeni's durable conversation truth is still reconciled explicitly below.\n const callModelInputFilter = composeCallModelInputFilters(\n [\n callModelInputFilterForSettings(settings),\n genesisTitleInputFilter,\n overrides.callModelInputFilter,\n boundModelToolOutputsFilterForSettings(settings),\n contextRobustnessFilterForSettings(settings, {\n throwOnCompactionNeeded: Boolean(\n overrides.contextCompactionSignal || overrides.contextCompactionRequested,\n ),\n ...(overrides.contextCompactionSignal\n ? { contextCompactionSignal: overrides.contextCompactionSignal }\n : {}),\n ...(overrides.contextCompactionRequested\n ? { contextCompactionRequested: overrides.contextCompactionRequested }\n : {}),\n }),\n ].filter((f): f is CallModelInputFilter => Boolean(f)),\n );\n const runOptions: Parameters<typeof run>[2] = {\n stream: true,\n maxTurns: settings.agentMaxModelCallsPerTurn,\n // Built-in per-call guard chain: normalize computer calls, optionally strip\n // provider ids, trim to the input budget on the client-compaction path, and\n // raise the proactive compaction signal. This runs for turn-start replay AND\n // every mid-turn follow-up.\n callModelInputFilter,\n ...(overrides.signal ? { signal: overrides.signal } : {}),\n };\n if (client) {\n runOptions.sandbox = {\n client,\n ...(sandboxSessionState ? { sessionState: sandboxSessionState } : {}),\n } as SandboxRunConfig;\n }\n return await runScopedRunner(settings).run(agent, prepared.input, runOptions);\n}\n\nfunction appendSandboxFileDownloadFailureNote(\n input: PreparedAgentInput,\n failures: SandboxFileDownloadFailure[],\n): void {\n const note = sandboxFileDownloadFailureNote(failures);\n if (!note) {\n return;\n }\n if (typeof input.input === \"string\") {\n input.input = [input.input, \"\", note].join(\"\\n\");\n return;\n }\n if (Array.isArray(input.input)) {\n input.input = [\n ...input.input,\n { type: \"message\", role: \"user\", content: note } as AgentInputItem,\n ];\n }\n}\n\n/**\n * A per-run `Runner` whose `modelProvider` is built from THIS turn's settings.\n *\n * The standalone `run()` uses a process-global default Runner whose modelProvider\n * is the lazy global default (whatever the last `configureOpenAI` /\n * `setDefaultModelProvider` installed). The worker runs ~100 activities\n * concurrently in one process, so a concurrently-starting turn for a DIFFERENT\n * workspace can overwrite that global between this turn's `configure` and a\n * per-call `getModel()` during the stream — leaving the global router with no\n * codex provider and throwing CodexSubscriptionUnavailableError on a\n * `codex/<slug>` name re-resolution (the SandboxAgent/Modal path drops the Model\n * instance and re-resolves by NAME). Pinning a run-scoped Runner makes the\n * mutable global irrelevant to correctness: each concurrent turn resolves names\n * against its OWN settings (which carry the codex-subscription provider via\n * withCodexProvider for an active workspace, and the registry providers). The\n * Runner inherits the SDK's default config for everything else, identical to the\n * default runner. setDefaultModelProvider remains only as a boot-time fallback.\n */\nfunction runScopedRunner(settings: Settings): Runner {\n return new Runner({\n modelProvider: new MultiProviderModelProvider(settings),\n });\n}\n\nexport { MaxTurnsExceededError } from \"@openai/agents\";\n\n/**\n * Detects the agents SDK per-segment turn cap. The cap is a pacing valve, not\n * a session failure: callers should end the segment gracefully (idle) so an\n * active goal's continuation loop -- or a follow-up user message -- resumes\n * the work. When the SDK attached the run state at the moment the cap hit,\n * the serialized form is returned so the resumed turn keeps full context.\n */\nexport function maxTurnsExceededRunState(\n error: unknown,\n): { serializedRunState: string | null } | null {\n if (!(error instanceof MaxTurnsExceededError)) {\n return null;\n }\n try {\n return { serializedRunState: error.state ? error.state.toString() : null };\n } catch {\n return { serializedRunState: null };\n }\n}\n\n/**\n * Serialized run state attached to any agents SDK error, when present.\n * Provider failures usually surface as raw API errors without state; callers\n * must treat a null here as \"resume from the previous snapshot\" rather than\n * an error.\n */\nexport function agentsErrorRunState(error: unknown): string | null {\n if (!(error instanceof AgentsError) || !error.state) {\n return null;\n }\n try {\n return error.state.toString();\n } catch {\n return null;\n }\n}\n\nexport function withManifestRefreshOnResume(\n client: SandboxClient,\n targetManifest: Manifest | undefined,\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\"> = {},\n): SandboxClient {\n if (!targetManifest || !client.resume) {\n return client;\n }\n return {\n backendId: client.backendId,\n ...(client.supportsDefaultOptions !== undefined\n ? { supportsDefaultOptions: client.supportsDefaultOptions }\n : {}),\n ...(client.create\n ? {\n create: async (...args: any[]) => await (client.create as any)(...args),\n }\n : {}),\n resume: async (state: SandboxSessionState) => {\n const session = await client.resume!(state);\n await applyMissingManifestEntries(session, targetManifest, context);\n return session;\n },\n ...(client.delete\n ? {\n delete: async (state: SandboxSessionState) => await client.delete!(state),\n }\n : {}),\n ...(client.serializeSessionState\n ? {\n serializeSessionState: async (state: SandboxSessionState, options) =>\n await client.serializeSessionState!(state, options),\n }\n : {}),\n ...(client.canPersistOwnedSessionState\n ? {\n canPersistOwnedSessionState: async (state: SandboxSessionState) =>\n await client.canPersistOwnedSessionState!(state),\n }\n : {}),\n ...(client.canReusePreservedOwnedSession\n ? {\n canReusePreservedOwnedSession: async (state: SandboxSessionState) =>\n await client.canReusePreservedOwnedSession!(state),\n }\n : {}),\n ...(client.deserializeSessionState\n ? {\n deserializeSessionState: async (state: Record<string, unknown>) =>\n await client.deserializeSessionState!(state),\n }\n : {}),\n };\n}\n\n// OWNED-RESUME manifest refresh. This path runs ONLY for SDK-owned sessions\n// (withManifestRefreshOnResume wraps client.resume, which the SDK never calls\n// when handed a live provided session — the ownedSandbox branch bypasses this\n// entirely). Owned applyManifest MERGES env safely with no guard, and this\n// refresh is a FEATURE: it is how a workspace-env edit reaches a long-lived\n// owned local/docker box that rarely recycles. The provided-session env pin\n// (pinProvidedSessionManifestEnvironment below) — NOT this function — is the\n// fix for the SDK's validateNoEnvironmentDelta session-fatal guard. Drift is\n// additionally REPORTED here (key names only, never values) so any env\n// recompute change stays attributable from the DB alone.\nexport async function applyMissingManifestEntries(\n session: SandboxSessionLike,\n targetManifest: Manifest,\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\"> = {},\n): Promise<void> {\n const currentManifestValue = (\n session as {\n state?: {\n manifest?:\n | Manifest\n | {\n root?: string;\n entries?: Record<string, any>;\n environment?: Record<string, any>;\n };\n };\n }\n ).state?.manifest;\n const currentManifest = currentManifestValue ? ensureManifest(currentManifestValue) : undefined;\n const target = ensureManifest(targetManifest);\n if (!currentManifest) {\n if (Object.keys(target.entries).length === 0) {\n return;\n }\n throw new Error(\n \"Resumed sandbox session cannot apply new manifest entries because current manifest state is unavailable\",\n );\n }\n // Drift detection runs on EVERY resume (even no-op ones): the durable trace\n // that makes an env-recompute regression attributable from the DB instead of\n // from rotated worker logs.\n await reportManifestEnvironmentDrift(currentManifest, target, context);\n if (!session.applyManifest && !session.materializeEntry) {\n if (Object.keys(target.entries).length === 0) {\n return;\n }\n throw new Error(\n \"Resumed sandbox session cannot apply new manifest entries because it does not support applyManifest() or materializeEntry()\",\n );\n }\n if (Object.keys(target.entries).length === 0) {\n return;\n }\n if (currentManifest.root !== target.root) {\n throw new Error(\"Cannot apply per-turn resources to a sandbox with a different manifest root\");\n }\n const entries: Record<string, any> = {};\n for (const [path, entry] of Object.entries(target.entries)) {\n const existing = (currentManifest.entries as Record<string, unknown>)[path];\n if (existing === undefined) {\n entries[path] = entry;\n continue;\n }\n if (stableJson(existing) !== stableJson(entry)) {\n throw new Error(`Cannot replace existing sandbox manifest entry: ${path}`);\n }\n }\n const environmentChanged =\n stableJson(currentManifest.environment) !== stableJson(target.environment);\n if (environmentChanged && !session.applyManifest) {\n throw new Error(\n \"Resumed sandbox session cannot refresh manifest environment because it does not support applyManifest()\",\n );\n }\n if (Object.keys(entries).length === 0 && !environmentChanged) {\n return;\n }\n // Carry path grants through manifest rebuilds: since @openai/agents 0.11.0\n // they gate local source materialization, and run states saved before the\n // upgrade have manifests without grants.\n const extraPathGrants = mergePathGrants(currentManifest.extraPathGrants, target.extraPathGrants);\n const delta = new Manifest({\n root: currentManifest.root,\n entries,\n environment: target.environment,\n ...(extraPathGrants.length ? { extraPathGrants } : {}),\n });\n if (session.applyManifest) {\n await session.applyManifest(delta);\n } else {\n for (const [path, entry] of Object.entries(entries)) {\n await session.materializeEntry!({ path, entry });\n }\n }\n (session as { state?: { manifest?: Manifest } }).state!.manifest = new Manifest({\n root: currentManifest.root,\n environment: environmentChanged ? target.environment : currentManifest.environment,\n entries: {\n ...currentManifest.entries,\n ...entries,\n },\n ...(extraPathGrants.length ? { extraPathGrants } : {}),\n });\n}\n\n/**\n * Key-level diff of the live box's baked manifest env vs the freshly recomputed\n * target env. Returns null when identical. Key NAMES only — values are secrets\n * and must never leave this function's comparison.\n */\nexport function manifestEnvironmentDrift(\n current: Manifest,\n target: Manifest,\n): { added: string[]; removed: string[]; changed: string[] } | null {\n const currentEnv = (current.environment ?? {}) as Record<string, unknown>;\n const targetEnv = (target.environment ?? {}) as Record<string, unknown>;\n const added: string[] = [];\n const removed: string[] = [];\n const changed: string[] = [];\n for (const key of Object.keys(targetEnv)) {\n if (!(key in currentEnv)) {\n added.push(key);\n } else if (stableJson(currentEnv[key]) !== stableJson(targetEnv[key])) {\n changed.push(key);\n }\n }\n for (const key of Object.keys(currentEnv)) {\n if (!(key in targetEnv)) {\n removed.push(key);\n }\n }\n if (added.length === 0 && removed.length === 0 && changed.length === 0) {\n return null;\n }\n return {\n added: added.sort(),\n removed: removed.sort(),\n changed: changed.sort(),\n };\n}\n\nasync function reportManifestEnvironmentDrift(\n current: Manifest,\n target: Manifest,\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\">,\n): Promise<ReturnType<typeof manifestEnvironmentDrift>> {\n const drift = manifestEnvironmentDrift(current, target);\n if (!drift) {\n return null;\n }\n // Reporting must never break a resume: the drift itself is benign under the\n // env pin (the box keeps running on its baked env); only the SIGNAL matters.\n try {\n await context.onRuntimeEvent?.({\n type: \"sandbox.env.drift\",\n payload: drift,\n });\n } catch {\n // Swallow: a failed emit must not fail the turn.\n }\n return drift;\n}\n\n/**\n * ENV PIN for provided sessions (the ownership-inversion turn path). The SDK\n * validates the FULL target manifest environment against a live provided\n * session's baked env BEFORE reducing to its entry-only delta\n * (validateNoEnvironmentDelta -> session-fatal UserError on ANY difference).\n * So a turn resuming an existing box must declare the box's OWN env,\n * byte-identical — never the fresh recompute. This replaces the agent's\n * defaultManifest environment with the baked one and reports the drift (key\n * names only) instead of letting it kill the session. Fresh env lands at the\n * next cold-create; rotating values ride OFF-manifest (TOKEN-BROKER B1/B2).\n */\nexport async function pinProvidedSessionManifestEnvironment(\n agent: Agent<any, any>,\n session: SandboxSessionLike,\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\"> = {},\n): Promise<void> {\n const holder = agent as { defaultManifest?: Manifest };\n const currentManifestValue = (\n session as {\n state?: {\n manifest?:\n | Manifest\n | {\n root?: string;\n entries?: Record<string, any>;\n environment?: Record<string, any>;\n };\n };\n }\n ).state?.manifest;\n if (!holder.defaultManifest || !currentManifestValue) {\n return;\n }\n const current = ensureManifest(currentManifestValue);\n const target = ensureManifest(holder.defaultManifest);\n const drift = await reportManifestEnvironmentDrift(current, target, context);\n if (!drift) {\n return;\n }\n holder.defaultManifest = new Manifest({\n ...(target.root ? { root: target.root } : {}),\n entries: target.entries,\n environment: current.environment,\n ...(target.extraPathGrants?.length ? { extraPathGrants: target.extraPathGrants } : {}),\n });\n}\n\n/**\n * The one-truth owned-path platform setup: the manifest-env pin (align the turn's\n * manifest to the live box's baked env + report drift, NEVER die on it) plus the\n * beforeAgentStart hooks (repository clone with B1 token/askpass seed, toolspace\n * token seed, azure-cli-login) and signed-URL file materialization — all executed\n * DIRECTLY against the pinned, UN-proxied established box (the SDK never calls\n * client.create/resume for a provided session, so these decorations would never\n * fire on their own).\n *\n * Extracted verbatim from `runStream`'s owned branch so both the EAGER path\n * (runStream, before the run starts) and the LAZY path (the worker's first-op\n * provisioner, after the box is established) run the IDENTICAL setup. A pure\n * refactor for the eager path: same order, same gates, same idempotency\n * (clone skips a materialized tree, token seed overwrites — the desired per-turn\n * refresh, az login is idempotent). The connected-machine (selfhosted) branch\n * keeps platform setup OFF the user's real box and seeds ONLY the toolspace token.\n *\n * `gitTokenSeedsOverride` lets the lazy provisioner pass its own freshly-minted\n * run-scoped provider tokens (minted at establish time, not turn start);\n * unset ⇒ read the seeds off the agent exactly as the eager path does.\n */\nexport async function runOwnedSandboxSetup(\n agent: Agent<any, any>,\n session: SandboxSessionLike,\n setupSession: SandboxSessionLike,\n opts: {\n settings: Settings;\n environment: Record<string, string>;\n preparedInput?: PreparedAgentInput;\n fileDownloadsMaterialized?: boolean;\n onRuntimeEvent?: SandboxLifecycleHookContext[\"onRuntimeEvent\"];\n gitTokenSeedsOverride?: GitTokenSeeds;\n gitTokenSeedOverride?: string;\n gitCredentialBindingsOverride?: GitCredentialBindingSeed[];\n toolspaceTokenSeedOverride?: string;\n commandRunner?: SandboxLifecycleCommandRunner;\n },\n): Promise<void> {\n const { settings, environment } = opts;\n // ENV PIN (provided sessions): the SDK validates the FULL recomputed manifest\n // env against the live box's baked env before applying its entry-only delta\n // (validateNoEnvironmentDelta — session-fatal on ANY drift; killed a 4-day\n // prod manager session 2026-07-06). Align the turn's manifest to the box's\n // own env and REPORT the drift instead of dying on it.\n await pinProvidedSessionManifestEnvironment(agent, session, {\n ...(opts.onRuntimeEvent ? { onRuntimeEvent: opts.onRuntimeEvent } : {}),\n });\n const runAs = sandboxRunAs(settings);\n const fileDownloads = sandboxFileDownloadsForAgent(agent);\n // TOKEN-BROKER (B1): per-turn provider token seeds, forwarded OFF-MANIFEST so\n // the repository-clone hook writes provider token files before the clone. The\n // lazy provisioner overrides them with its own establish-time mint.\n const ownedGitTokenSeeds = {\n ...(gitTokenSeedsForAgent(agent) ?? {}),\n ...(opts.gitTokenSeedOverride ? { github: opts.gitTokenSeedOverride } : {}),\n ...(opts.gitTokenSeedsOverride ?? {}),\n } satisfies GitTokenSeeds;\n const ownedGitCredentialBindings =\n opts.gitCredentialBindingsOverride ?? gitCredentialBindingsForAgent(agent);\n const ownedToolspaceTokenSeed =\n opts.toolspaceTokenSeedOverride ?? toolspaceTokenSeedForAgent(agent);\n const ownedToolspaceTokenFile = toolspaceTokenFileForAgent(agent, environment);\n const ownedRigSetup = rigSetupDescriptorForAgent(agent);\n const ownedHooks = [\n // M3: rig setup runs FIRST so any tooling it installs is present for the\n // credential / repository-clone hooks below; the rig's credential hooks are\n // unioned into the deployment preparation-profile hooks (deduped by id).\n // This is the LIVE owned-path execution (the provided session skips the\n // client create/resume decoration), so the rig hooks MUST be here or a\n // rig-bound turn would start without ever running the frozen setup script.\n ...sandboxRigSetupHooksForAgent(agent),\n ...unionCredentialHooks(\n sandboxLifecycleHooksForIds(sandboxLifecycleHookIds(settings)),\n rigCredentialHooksForAgent(agent),\n ),\n ...sandboxToolspaceTokenHooksForAgent(agent),\n ...sandboxRepositoryCloneHooksForAgent(agent),\n ];\n const ownedHookContext: SandboxLifecycleHookContext = {\n environment,\n ...(opts.onRuntimeEvent ? { onRuntimeEvent: opts.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n ...(Object.keys(ownedGitTokenSeeds).length > 0 ? { gitTokenSeeds: ownedGitTokenSeeds } : {}),\n ...(ownedGitCredentialBindings ? { gitCredentialBindings: ownedGitCredentialBindings } : {}),\n ...(ownedToolspaceTokenSeed ? { toolspaceTokenSeed: ownedToolspaceTokenSeed } : {}),\n ...(ownedToolspaceTokenFile ? { toolspaceTokenFile: ownedToolspaceTokenFile } : {}),\n ...(ownedRigSetup ? { rigSetup: ownedRigSetup } : {}),\n ...(opts.commandRunner ? { commandRunner: opts.commandRunner } : {}),\n };\n // OWNED-PATH HOOKS: run the beforeAgentStart hooks directly against the provided\n // box, once per turn, BEFORE the run starts (repository-clone hook seeds the B1\n // askpass + token file; azure-cli-login on lease-owned boxes). Re-running on a\n // warm box is safe by construction (clone skips a materialized tree, token seed\n // overwrites the file, az login is idempotent). EXCEPT on a connected machine\n // (effective backend \"selfhosted\"): the box is the user's REAL computer — the\n // platform must not run setup against it (clone hooks are already empty there;\n // this keeps az login off it too).\n if (agentActiveSandboxBackend.get(agent) !== \"selfhosted\") {\n await runBeforeAgentStartHooks(setupSession, ownedHooks, ownedHookContext);\n // FILE RESOURCES: withSandboxFileDownloads has the IDENTICAL provided-session\n // blind spot (it too wraps only create/resume), so signed-URL file\n // materialization must also run directly against the pinned box. The download\n // command is idempotent (skips an existing file) and atomic (tmp + rename).\n if (fileDownloads.length > 0 && !opts.fileDownloadsMaterialized) {\n const materialized = await materializeSandboxFileDownloads(setupSession, fileDownloads, {\n ...(opts.onRuntimeEvent ? { onRuntimeEvent: opts.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n ...(opts.commandRunner ? { commandRunner: opts.commandRunner } : {}),\n });\n if (opts.preparedInput) {\n appendSandboxFileDownloadFailureNote(opts.preparedInput, materialized.failures);\n }\n }\n } else {\n // SELFHOSTED TOOLSPACE (parity): the platform setup hooks and file\n // materialization stay OFF the user's real machine — but the toolspace token\n // seed is the ONE piece of per-turn material that must reach it (a scoped,\n // own-session-bound token written to $OPENGENI_TOOLSPACE_TOKEN_FILE over the\n // same off-manifest exec channel the clone-seed uses; the machine's only path\n // to programmatic tool calling). Seed it (only) here.\n const toolspaceHooks = sandboxToolspaceTokenHooksForAgent(agent);\n if (toolspaceHooks.length > 0) {\n await runBeforeAgentStartHooks(setupSession, toolspaceHooks, ownedHookContext);\n }\n }\n}\n\nfunction mergePathGrants(\n current: Manifest[\"extraPathGrants\"] | undefined,\n target: Manifest[\"extraPathGrants\"] | undefined,\n): Manifest[\"extraPathGrants\"] {\n const merged = new Map<string, Manifest[\"extraPathGrants\"][number]>();\n for (const grant of [...(current ?? []), ...(target ?? [])]) {\n merged.set(grant.path, grant);\n }\n return [...merged.values()];\n}\n\nexport function withSandboxFileDownloads(\n client: SandboxClient,\n downloads: SandboxFileDownload[],\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\" | \"runAs\" | \"commandRunner\"> = {},\n): SandboxClient {\n const normalizedDownloads = normalizeSandboxFileDownloads(downloads);\n if (normalizedDownloads.length === 0) {\n return client;\n }\n const completed = new WeakSet<object>();\n const wrapSession = async <T extends SandboxSessionLike>(session: T): Promise<T> => {\n if (typeof session === \"object\" && session !== null && !completed.has(session)) {\n await materializeSandboxFileDownloads(session, normalizedDownloads, context);\n completed.add(session);\n }\n return session;\n };\n return {\n backendId: client.backendId,\n ...(client.supportsDefaultOptions !== undefined\n ? { supportsDefaultOptions: client.supportsDefaultOptions }\n : {}),\n ...(client.create\n ? {\n create: async (...args: any[]) =>\n await wrapSession(await (client.create as any)(...args)),\n }\n : {}),\n ...(client.resume\n ? {\n resume: async (state: SandboxSessionState) =>\n await wrapSession(await client.resume!(state)),\n }\n : {}),\n ...(client.delete\n ? {\n delete: async (state: SandboxSessionState) => await client.delete!(state),\n }\n : {}),\n ...(client.serializeSessionState\n ? {\n serializeSessionState: async (state: SandboxSessionState, options) =>\n await client.serializeSessionState!(state, options),\n }\n : {}),\n ...(client.canPersistOwnedSessionState\n ? {\n canPersistOwnedSessionState: async (state: SandboxSessionState) =>\n await client.canPersistOwnedSessionState!(state),\n }\n : {}),\n ...(client.canReusePreservedOwnedSession\n ? {\n canReusePreservedOwnedSession: async (state: SandboxSessionState) =>\n await client.canReusePreservedOwnedSession!(state),\n }\n : {}),\n ...(client.deserializeSessionState\n ? {\n deserializeSessionState: async (state: Record<string, unknown>) =>\n await client.deserializeSessionState!(state),\n }\n : {}),\n };\n}\n\nexport async function materializeSandboxFileDownloads(\n session: SandboxSessionLike,\n downloads: SandboxFileDownload[],\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\" | \"runAs\" | \"commandRunner\"> = {},\n): Promise<SandboxFileDownloadMaterializationResult> {\n const normalizedDownloads = normalizeSandboxFileDownloads(downloads);\n if (normalizedDownloads.length === 0) {\n return { failures: [] };\n }\n const failures: SandboxFileDownloadFailure[] = [];\n for (const download of normalizedDownloads) {\n const targetPath = sandboxDownloadTargetPath(download);\n const payload = {\n fileId: download.fileId,\n path: targetPath,\n sizeBytes: download.sizeBytes ?? null,\n expiresAt: download.expiresAt ? new Date(download.expiresAt).toISOString() : null,\n };\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.started\",\n payload: { name: \"file-resource-download\", ...payload },\n });\n if (!session.exec && !session.execCommand) {\n const failure = sandboxFileDownloadFailure(\n download,\n targetPath,\n \"Sandbox file download materialization requires command execution support\",\n );\n failures.push(failure);\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.failed\",\n payload: {\n name: \"file-resource-download\",\n ...payload,\n error: failure.reason,\n },\n });\n continue;\n }\n let result: unknown;\n try {\n result = await runSandboxLifecycleCommand(\n session,\n {\n cmd: sandboxFileDownloadCommand(download, targetPath),\n workdir: \"/workspace\",\n ...(context.runAs ? { runAs: context.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 20_000,\n },\n context.commandRunner,\n );\n assertSandboxCommandSucceeded(result, `Sandbox file resource download ${download.fileId}`);\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.completed\",\n payload: { name: \"file-resource-download\", ...payload },\n });\n } catch (error) {\n if (error instanceof TurnSandboxCommandCancelledError) throw error;\n const failure = sandboxFileDownloadFailure(download, targetPath, error, result);\n failures.push(failure);\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.failed\",\n payload: {\n name: \"file-resource-download\",\n ...payload,\n error: failure.reason,\n ...(failure.exitCode !== undefined ? { exitCode: failure.exitCode } : {}),\n ...(failure.output ? { output: failure.output } : {}),\n },\n });\n }\n }\n return { failures };\n}\n\nfunction sandboxFileDownloadFailure(\n download: SandboxFileDownload,\n targetPath: string,\n error: unknown,\n result?: unknown,\n): SandboxFileDownloadFailure {\n const exitCode = sandboxCommandExitCode(result);\n const output = sandboxCommandOutput(result);\n return {\n fileId: download.fileId,\n filename: download.filename,\n path: targetPath,\n reason: error instanceof Error ? error.message : String(error),\n ...(exitCode !== null ? { exitCode } : {}),\n ...(output ? { output } : {}),\n };\n}\n\nexport function sandboxFileDownloadFailureNote(failures: SandboxFileDownloadFailure[]): string {\n if (failures.length === 0) {\n return \"\";\n }\n return [\n \"The following attached files could not be loaded into the sandbox and are unavailable this turn:\",\n ...failures.map((failure) => `- ${failure.filename} (${failure.reason})`),\n \"Continue without them or tell the user.\",\n ].join(\"\\n\");\n}\n\nexport function sandboxFileDownloadsForAgent(agent: unknown): SandboxFileDownload[] {\n return typeof agent === \"object\" && agent !== null\n ? [...(agentFileDownloads.get(agent) ?? [])]\n : [];\n}\n\nfunction ensureManifest(\n manifest:\n | Manifest\n | {\n root?: string;\n entries?: Record<string, any>;\n environment?: Record<string, any>;\n extraPathGrants?: any[];\n },\n): Manifest {\n if (\n manifest instanceof Manifest &&\n typeof manifest.mountTargetsForMaterialization === \"function\"\n ) {\n return manifest;\n }\n return new Manifest({\n ...(manifest.root ? { root: manifest.root } : {}),\n entries: manifest.entries ?? {},\n environment: manifest.environment ?? {},\n ...(manifest.extraPathGrants?.length ? { extraPathGrants: manifest.extraPathGrants } : {}),\n });\n}\n\nfunction base64DecodedByteLength(value: string): number {\n const padding = value.endsWith(\"==\") ? 2 : value.endsWith(\"=\") ? 1 : 0;\n return Math.max(0, Math.floor((value.length * 3) / 4) - padding);\n}\n\n/** Determine image byte length without allocating another binary/base64 copy. */\nfunction imageDataByteLength(data: unknown): number | null {\n if (ArrayBuffer.isView(data)) return data.byteLength;\n if (data instanceof ArrayBuffer) return data.byteLength;\n if (Array.isArray(data)) {\n return data.every((value) => typeof value === \"number\") ? data.length : null;\n }\n if (!data || typeof data !== \"object\") return null;\n const record = data as Record<string, unknown>;\n if (record.type === \"Buffer\" && Array.isArray(record.data)) {\n return record.data.every((value) => typeof value === \"number\") ? record.data.length : null;\n }\n const keys = Object.keys(record);\n return keys.length > 0 &&\n keys.every((key) => /^\\d+$/.test(key) && typeof record[key] === \"number\")\n ? keys.length\n : null;\n}\n\n/**\n * Convert one image-shaped tool result into a content-free audit fact. This is\n * intentionally different from model history: the model keeps its structured\n * image item, while `session_events` never becomes an implicit image blob store.\n */\nfunction toolOutputMediaPreview(value: unknown): SessionEventMediaPreview | null {\n if (typeof value === \"string\") {\n return sessionEventMediaPreviewFromDataUrl(value);\n }\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const record = value as Record<string, unknown>;\n if (record.type === \"input_image\") {\n const source = record.image ?? record.image_url ?? record.imageUrl;\n const url =\n typeof source === \"string\"\n ? source\n : source && typeof source === \"object\"\n ? (source as Record<string, unknown>).url\n : null;\n if (typeof url !== \"string\" || url.length === 0) return null;\n return sessionEventMediaPreviewFromDataUrl(url) ?? sessionEventMediaPreview(\"image/*\", null);\n }\n if (record.type !== \"image\" || !record.image || typeof record.image !== \"object\") return null;\n const image = record.image as Record<string, unknown>;\n const mediaType =\n typeof image.mediaType === \"string\" && image.mediaType.length > 0\n ? image.mediaType\n : \"image/png\";\n if (typeof image.url === \"string\" && image.url.length > 0) {\n return (\n sessionEventMediaPreviewFromDataUrl(image.url) ?? sessionEventMediaPreview(mediaType, null)\n );\n }\n if (typeof image.data === \"string\") {\n return (\n sessionEventMediaPreviewFromDataUrl(image.data) ??\n sessionEventMediaPreview(mediaType, base64DecodedByteLength(image.data))\n );\n }\n const byteLength = imageDataByteLength(image.data);\n return byteLength === null ? null : sessionEventMediaPreview(mediaType, byteLength);\n}\n\n/**\n * Normalize a tool-call output for the lossy `agent.toolCall.output` audit event.\n * Inline image bytes/data URLs become a compact `media_preview` with exact byte\n * length where knowable and `fullOutputAvailable:false`. The model-facing output\n * is not changed here, and mixed arrays retain their non-image text/error facts.\n */\nexport function normalizeToolOutputForEvent(output: unknown): unknown {\n const single = toolOutputMediaPreview(output);\n if (single !== null) {\n return single;\n }\n if (Array.isArray(output)) {\n const normalized = output.map((el) => toolOutputMediaPreview(el) ?? el);\n if (normalized.length === 1 && normalized[0]?.type === \"media_preview\") {\n return normalized[0];\n }\n return normalized;\n }\n return output;\n}\n\nexport function normalizeSdkEvent(event: RunStreamEvent): NormalizedRuntimeEvent[] {\n const out: NormalizedRuntimeEvent[] = [];\n if (event.type === \"raw_model_stream_event\") {\n const data = (event as any).data;\n if (data?.type === \"output_text_delta\" && typeof data.delta === \"string\") {\n out.push({ type: \"agent.message.delta\", payload: { text: data.delta } });\n return out;\n }\n if (data?.type === \"response_done\") {\n return out;\n }\n }\n if (isOpenAIResponsesRawModelStreamEvent(event)) {\n const raw = (event as any).data?.event;\n if (raw?.type === \"response.reasoning_summary_text.delta\" && typeof raw.delta === \"string\") {\n out.push({ type: \"agent.reasoning.delta\", payload: { text: raw.delta } });\n }\n return out;\n }\n if (event.type === \"agent_updated_stream_event\") {\n out.push({\n type: \"agent.updated\",\n payload: { agent: (event as any).agent?.name ?? null },\n });\n return out;\n }\n if (event.type !== \"run_item_stream_event\") {\n return out;\n }\n const item = (event as any).item;\n if (!item) {\n return out;\n }\n if (item.type === \"tool_call_item\") {\n const raw = item.rawItem ?? {};\n out.push({\n type: \"agent.toolCall.created\",\n payload: {\n id: raw.callId ?? raw.id ?? item.id ?? null,\n name: raw.name ?? raw.type ?? \"tool\",\n arguments: raw.arguments ?? raw.input ?? null,\n raw,\n },\n });\n } else if (item.type === \"tool_call_output_item\") {\n out.push({\n type: \"agent.toolCall.output\",\n payload: {\n id: item.rawItem?.callId ?? item.id ?? null,\n // Inline media becomes a content-free audit fact. Model history keeps\n // the provider's real structured image output on its separate path.\n output: normalizeToolOutputForEvent(item.output),\n },\n });\n } else if (item.type === \"tool_search_call_item\") {\n // Progressive connector disclosure: surface the model's tool search as a\n // regular tool-call event so the session stream shows the step (parity with\n // the Codex CLI, which renders its searches). Arguments may be an object\n // (the live wire shape) or a string.\n const raw = item.rawItem ?? {};\n out.push({\n type: \"agent.toolCall.created\",\n payload: {\n id: raw.call_id ?? raw.callId ?? raw.id ?? item.id ?? null,\n name: \"tool_search\",\n arguments: raw.arguments ?? null,\n raw,\n },\n });\n } else if (item.type === \"tool_search_output_item\") {\n const raw = item.rawItem ?? {};\n const disclosed = Array.isArray(raw.tools)\n ? raw.tools\n .map((tool: { name?: unknown }) => (typeof tool?.name === \"string\" ? tool.name : \"\"))\n .filter(Boolean)\n : [];\n out.push({\n type: \"agent.toolCall.output\",\n payload: {\n id: raw.call_id ?? raw.callId ?? item.id ?? null,\n output: {\n type: \"text\",\n text:\n disclosed.length > 0\n ? `Disclosed tools: ${disclosed.join(\", \")}`\n : \"No matching tools found.\",\n },\n },\n });\n } else if (item.type === \"message_output_item\") {\n const text = typeof item.text === \"string\" ? item.text : undefined;\n if (text) {\n out.push({ type: \"agent.message.completed\", payload: { text } });\n }\n }\n return out;\n}\n\nexport function modelResponseUsageFromSdkEvent(event: RunStreamEvent): ModelResponseUsage | null {\n const response = modelResponseFromSdkEvent(event);\n return modelResponseUsageFromResponse(response);\n}\n\n/** Normalize usage from either a Responses or Chat Completions result. */\nexport function modelResponseUsageFromResponse(response: unknown): ModelResponseUsage | null {\n const usage = usageFromResponse(response);\n if (!usage) {\n return null;\n }\n const responseId =\n typeof (response as { id?: unknown } | null)?.id === \"string\"\n ? (response as { id: string }).id\n : typeof (response as { responseId?: unknown } | null)?.responseId === \"string\"\n ? (response as { responseId: string }).responseId\n : undefined;\n return {\n ...(responseId ? { responseId } : {}),\n usage,\n };\n}\n\nfunction modelResponseFromSdkEvent(event: RunStreamEvent): any {\n if (event.type === \"raw_model_stream_event\") {\n const data = (event as any).data;\n if (data?.type === \"response_done\") {\n return data.response;\n }\n }\n if (isOpenAIResponsesRawModelStreamEvent(event)) {\n const raw = (event as any).data?.event;\n if (raw?.type === \"response.completed\") {\n return raw.response;\n }\n }\n return null;\n}\n\nfunction usageFromResponse(response: unknown): ModelResponseUsage[\"usage\"] | null {\n const raw = (response as { usage?: unknown } | null)?.usage;\n if (!raw || typeof raw !== \"object\") {\n return null;\n }\n const record = raw as Record<string, unknown>;\n const usage = {\n ...numberProp(\n record,\n \"inputTokens\",\n \"inputTokens\",\n \"input_tokens\",\n \"promptTokens\",\n \"prompt_tokens\",\n ),\n ...numberProp(\n record,\n \"outputTokens\",\n \"outputTokens\",\n \"output_tokens\",\n \"completionTokens\",\n \"completion_tokens\",\n ),\n ...numberProp(record, \"totalTokens\", \"totalTokens\", \"total_tokens\"),\n ...inputTokenDetailsProp(record),\n ...outputTokenDetailsProp(record),\n ...requestUsageEntriesProp(record),\n };\n return Object.keys(usage).length > 0 ? usage : null;\n}\n\nfunction numberProp(\n raw: Record<string, unknown>,\n outputKey: \"inputTokens\" | \"outputTokens\" | \"totalTokens\",\n ...keys: string[]\n): Partial<ModelResponseUsage[\"usage\"]> {\n const value = keys.map((key) => raw[key]).find((candidate) => candidate !== undefined);\n // Preserve numeric provider values verbatim here, including malformed ones.\n // The shared usage normalizer is the single bounded validation boundary and\n // needs to see NaN/infinite/fractional/oversized values so it can emit safe\n // field-path diagnostics rather than silently erasing the evidence.\n return typeof value === \"number\" ? { [outputKey]: value } : {};\n}\n\nfunction inputTokenDetailsProp(raw: Record<string, unknown>): Partial<ModelResponseUsage[\"usage\"]> {\n const details =\n raw.inputTokensDetails ??\n raw.input_tokens_details ??\n raw.promptTokensDetails ??\n raw.prompt_tokens_details;\n if (details === undefined || details === null) {\n return {};\n }\n return {\n inputTokensDetails: details as Record<string, number> | Array<Record<string, number>>,\n };\n}\n\nfunction outputTokenDetailsProp(\n raw: Record<string, unknown>,\n): Partial<ModelResponseUsage[\"usage\"]> {\n const details = raw.outputTokensDetails ?? raw.output_tokens_details;\n const normalized = details ?? raw.completionTokensDetails ?? raw.completion_tokens_details;\n if (normalized === undefined || normalized === null) {\n return {};\n }\n return {\n outputTokensDetails: normalized as Record<string, number> | Array<Record<string, number>>,\n };\n}\n\nfunction requestUsageEntriesProp(\n raw: Record<string, unknown>,\n): Partial<ModelResponseUsage[\"usage\"]> {\n const entries = raw.requestUsageEntries ?? raw.request_usage_entries;\n if (entries === undefined || entries === null) {\n return {};\n }\n return {\n // The normalizer validates every entry and all supported field aliases.\n // Preserve the SDK objects rather than rebuilding them and accidentally\n // dropping provider detail fields such as cache_write_tokens.\n requestUsageEntries: entries as NonNullable<ModelResponseUsage[\"usage\"][\"requestUsageEntries\"]>,\n };\n}\n\nexport function serializeApprovals(interruptions: unknown[]): unknown[] {\n return interruptions\n .filter((item) => interruptionToolName(item) !== HUMAN_INPUT_TOOL_NAME)\n .map((item: any) => {\n if (typeof item?.toJSON === \"function\") {\n return item.toJSON();\n }\n return {\n id: approvalIdentifier(item) ?? \"approval\",\n name: item?.name ?? item?.rawItem?.name ?? \"tool\",\n arguments: item?.arguments ?? item?.rawItem?.arguments ?? null,\n raw: item,\n };\n });\n}\n\nexport function serializeHumanInputRequests(\n interruptions: unknown[],\n): SerializedHumanInputInterruption[] {\n return interruptions\n .filter((item) => interruptionToolName(item) === HUMAN_INPUT_TOOL_NAME)\n .map((item: any) => {\n const rawArguments = item?.arguments ?? item?.rawItem?.arguments;\n let parsedArguments: unknown = rawArguments;\n if (typeof rawArguments === \"string\") {\n try {\n parsedArguments = JSON.parse(rawArguments);\n } catch {\n throw new Error(\"Human-input interruption contains invalid JSON arguments\");\n }\n }\n const toolCallId = approvalIdentifier(item);\n if (!toolCallId) {\n throw new Error(\"Human-input interruption is missing a stable tool-call identity\");\n }\n return {\n toolCallId,\n input: RequestHumanInputToolInput.parse(parsedArguments),\n };\n });\n}\n\nexport function buildManifest(\n settings: Settings,\n resources: ResourceRef[],\n environment = collectSandboxEnvironment(settings),\n fileResourceDownloads: SandboxFileDownload[] = [],\n): Manifest {\n assertUniqueResourceMountPaths(resources);\n const entries: Record<string, any> = {};\n const downloadsByFileId = new Map(\n normalizeSandboxFileDownloads(fileResourceDownloads).map((download) => [\n download.fileId,\n download,\n ]),\n );\n for (const resource of resources) {\n if (resource.kind === \"repository\") {\n const url = new URL(resource.uri);\n const host = url.host.toLowerCase();\n const repo = url.pathname.replace(/^\\/+|\\/+$/g, \"\").replace(/\\.git$/, \"\");\n const mountPath = resourceMountPath(resource);\n if (repositoryUsesSandboxClone(settings, resource)) {\n entries[mountPath] = dir();\n continue;\n }\n entries[mountPath] = gitRepo({\n host,\n repo,\n ref: resource.ref,\n ...(resource.subpath ? { subpath: normalizeRepositorySubpath(resource.subpath) } : {}),\n });\n continue;\n }\n if (resource.kind === \"file\") {\n const mountPath = resourceMountPath(resource);\n const download = downloadsByFileId.get(resource.fileId);\n entries[mountPath] = download\n ? sandboxDownloadDirectory(download, mountPath)\n : objectStorageFileMount(settings, `files/${resource.fileId}/original`);\n }\n }\n // No extraPathGrants here: remote sandbox clients (Modal) reject manifests\n // that carry them at create/apply time, which broke every Modal session.\n // The lazy bundled-skills source no longer needs a grant because\n // bundledSkillsDir() stages the skills inside the process working directory\n // whenever the packaged copy lives outside it.\n return new Manifest({\n root: \"/workspace\",\n entries,\n environment,\n });\n}\n\nexport function repositoryWorkspaceSkillPathsOption(resources: readonly ResourceRef[]): {\n workspaceSkillPaths?: readonly WorkspaceSkillSearchPath[];\n} {\n const repositories = resources.filter(\n (resource): resource is Extract<ResourceRef, { kind: \"repository\" }> =>\n resource.kind === \"repository\",\n );\n if (repositories.length === 0) return {};\n\n const paths = new Map<string, WorkspaceSkillSearchPath>();\n const add = (path: string, source: string): void => {\n if (!paths.has(path)) paths.set(path, { path, source });\n };\n // A Connected Machine maps /workspace to its configured working directory,\n // which may itself be the selected repository. Managed sandboxes normally use\n // the repository mount paths below. Checking both keeps the rule portable.\n add(\".agents/skills\", \"workspace .agents/skills\");\n add(\".claude/skills\", \"workspace .claude/skills\");\n for (const repository of repositories) {\n const mountPath = resourceMountPath(repository);\n add(`${mountPath}/.agents/skills`, `${mountPath}/.agents/skills`);\n add(`${mountPath}/.claude/skills`, `${mountPath}/.claude/skills`);\n }\n return { workspaceSkillPaths: [...paths.values()] };\n}\n\nfunction sandboxDownloadDirectory(download: SandboxFileDownload, mountPath: string): any {\n if (download.mountPath !== mountPath) {\n throw new Error(\n `File download materialization path mismatch for ${download.fileId}: expected ${mountPath}, got ${download.mountPath}`,\n );\n }\n assertSafeSandboxFilename(download.filename, download.fileId);\n if (download.content) {\n return dir({\n children: {\n [download.filename]: file({ content: download.content }),\n },\n });\n }\n return dir();\n}\n\nfunction objectStorageFileMount(settings: Settings, prefix: string): any {\n // Descriptor-driven: a nativeBucketMount backend (modal) mounts via the\n // provider's own bucket-mount strategy and cannot mount Azure Blob entries —\n // it needs pre-signed downloads instead. Reading the descriptor (not a\n // hard-coded backend name) keeps this honest as providers are added.\n const nativeBucketMount = CAPABILITY_DESCRIPTORS[settings.sandboxBackend].nativeBucketMount;\n if (settings.objectStorageBackend === \"azure-blob\") {\n if (nativeBucketMount) {\n throw new Error(\n \"Modal sandbox Azure Blob file resources require pre-signed download materialization because the current OpenAI Agents SDK Modal client does not support Azure Blob mount entries.\",\n );\n }\n const config = azureBlobMountConfig(settings);\n return azureBlobMount({\n container: config.container,\n prefix,\n accountName: config.accountName,\n accountKey: config.accountKey,\n endpointUrl: config.endpointUrl,\n readOnly: true,\n mountStrategy: inContainerMountStrategy({\n pattern: { type: \"rclone\", mode: \"fuse\" },\n }),\n });\n }\n if (settings.objectStorageBackend === \"aws-s3\" || settings.objectStorageBackend === \"gcs\") {\n throw new Error(\n `${settings.objectStorageBackend} file resources require pre-signed download materialization`,\n );\n }\n const config = s3CompatibleMountConfig(settings);\n return s3Mount({\n bucket: config.bucket,\n prefix,\n endpointUrl: config.endpointUrl,\n region: config.region,\n s3Provider: config.s3Provider,\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n readOnly: true,\n mountStrategy: nativeBucketMount\n ? new ModalCloudBucketMountStrategy()\n : inContainerMountStrategy({ pattern: { type: \"rclone\", mode: \"fuse\" } }),\n });\n}\n\nfunction s3CompatibleMountConfig(settings: Settings): {\n bucket: string;\n endpointUrl: string;\n region: string;\n s3Provider: string;\n accessKeyId: string;\n secretAccessKey: string;\n} {\n const endpointUrl = settings.objectStorageSandboxEndpoint ?? settings.objectStorageEndpoint;\n if (\n !endpointUrl ||\n !settings.objectStorageAccessKeyId ||\n !settings.objectStorageSecretAccessKey\n ) {\n throw new Error(\"File resources require configured S3-compatible object storage\");\n }\n return {\n bucket: settings.objectStorageBucket,\n endpointUrl,\n region: settings.objectStorageRegion,\n s3Provider: settings.objectStorageS3Provider,\n accessKeyId: settings.objectStorageAccessKeyId,\n secretAccessKey: settings.objectStorageSecretAccessKey,\n };\n}\n\nfunction azureBlobMountConfig(settings: Settings): {\n container: string;\n accountName: string;\n accountKey: string;\n endpointUrl?: string;\n} {\n const parsed = settings.objectStorageAzureConnectionString\n ? parseAzureConnectionString(settings.objectStorageAzureConnectionString)\n : {};\n const accountName = settings.objectStorageAzureAccountName ?? parsed.AccountName;\n const accountKey = settings.objectStorageAzureAccountKey ?? parsed.AccountKey;\n if (!accountName || !accountKey) {\n throw new Error(\"File resources require Azure Blob account name and account key\");\n }\n const endpointUrl = azureBlobManifestEndpoint(\n settings.objectStorageAzureEndpoint ?? parsed.BlobEndpoint,\n accountName,\n );\n return {\n container: settings.objectStorageBucket,\n accountName,\n accountKey,\n ...(endpointUrl ? { endpointUrl } : {}),\n };\n}\n\nfunction azureBlobManifestEndpoint(\n endpoint: string | undefined,\n accountName: string,\n): string | undefined {\n if (!endpoint) {\n return undefined;\n }\n const normalized = endpoint.replace(/\\/+$/, \"\");\n const standardAccountEndpoint = `https://${accountName}.blob.core.windows.net`;\n return normalized === standardAccountEndpoint ? undefined : normalized;\n}\n\nfunction parseAzureConnectionString(value: string): Record<string, string> {\n return Object.fromEntries(\n value\n .split(\";\")\n .map((part) => part.trim())\n .filter(Boolean)\n .map((part) => {\n const index = part.indexOf(\"=\");\n return index === -1 ? [part, \"\"] : [part.slice(0, index), part.slice(index + 1)];\n }),\n );\n}\n\nfunction normalizeManifestPath(path: string): string {\n return normalizeResourceMountPath(path);\n}\n\nfunction normalizeSandboxFileDownloads(downloads: SandboxFileDownload[]): SandboxFileDownload[] {\n return downloads.map((download) => {\n const mountPath = normalizeManifestPath(download.mountPath);\n assertSafeSandboxFilename(download.filename, download.fileId);\n if (!download.content && !download.url?.trim()) {\n throw new Error(\n `File download materialization requires content or a URL for ${download.fileId}`,\n );\n }\n return {\n ...download,\n mountPath,\n };\n });\n}\n\nfunction assertSafeSandboxFilename(filename: string, fileId: string): void {\n if (\n !filename ||\n filename.includes(\"/\") ||\n filename.includes(\"\\\\\") ||\n filename === \".\" ||\n filename === \"..\" ||\n filename.includes(\"..\")\n ) {\n throw new Error(`Invalid sandbox file name for ${fileId}: ${filename}`);\n }\n}\n\nfunction sandboxDownloadTargetPath(download: SandboxFileDownload): string {\n return posixPath.join(\"/workspace\", download.mountPath, download.filename);\n}\n\nfunction sandboxFileDownloadCommand(download: SandboxFileDownload, targetPath: string): string {\n if (!download.url) {\n throw new Error(`File download materialization URL is empty for ${download.fileId}`);\n }\n const targetDir = posixPath.dirname(targetPath);\n const tmpPath = `${targetPath}.opengeni-download-$$`;\n return [\n \"set +x\",\n \"set -eu\",\n `mkdir -p -- ${shellQuote(targetDir)}`,\n `if [ ! -f ${shellQuote(targetPath)} ]; then`,\n ` tmp=${shellQuote(tmpPath)}`,\n ' cleanup() { rm -f -- \"$tmp\"; }',\n \" trap cleanup EXIT\",\n ` curl --fail --location --silent --show-error --retry 3 --retry-delay 1 --output \"$tmp\" ${shellQuote(download.url)}`,\n ` mv -- \"$tmp\" ${shellQuote(targetPath)}`,\n \" trap - EXIT\",\n \"fi\",\n `chmod a-w -- ${shellQuote(targetPath)} 2>/dev/null || true`,\n ].join(\"\\n\");\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nexport type SandboxLifecycleHookPhase = \"beforeAgentStart\";\n\nexport type SandboxLifecycleCommandRunner = (\n session: TurnSandboxCommandSession,\n args: TurnSandboxCommandArgs,\n) => Promise<unknown>;\n\nexport type SandboxLifecycleHookContext = {\n environment: Record<string, string>;\n onRuntimeEvent?: (event: NormalizedRuntimeEvent) => Promise<void> | void;\n runAs?: string;\n // TOKEN-BROKER (B1): back-compat GitHub alias for gitTokenSeeds.github.\n gitTokenSeed?: string;\n // Provider tokens to seed into box token FILES before repository clone/setup\n // runs. Threaded OFF-MANIFEST — they ride ONLY the setup exec command prefix,\n // NEVER the box/agent manifest env (validateNoEnvironmentDelta must never see\n // rotating values).\n gitTokenSeeds?: GitTokenSeeds;\n gitCredentialBindings?: GitCredentialBindingSeed[];\n toolspaceTokenSeed?: string;\n toolspaceTokenFile?: string;\n // M3: the rig setup descriptor for the rig-setup hook (the script + marker\n // version id + the rig's own timeout). Present only on a rig-bound turn.\n rigSetup?: RigSetupDescriptor;\n commandRunner?: SandboxLifecycleCommandRunner;\n};\n\nasync function runSandboxLifecycleCommand(\n session: SandboxSessionLike,\n args: TurnSandboxCommandArgs,\n commandRunner?: SandboxLifecycleCommandRunner,\n): Promise<unknown> {\n if (commandRunner) {\n return await commandRunner(session as TurnSandboxCommandSession, args);\n }\n if (session.exec) return await session.exec(args);\n if (session.execCommand) return await session.execCommand(args);\n throw new Error(\"Sandbox session does not support command execution\");\n}\n\n// M3: everything the rig-setup hook needs to run the frozen rig version's setup\n// script exactly once per box. `versionId` keys the idempotence marker\n// (/var/opengeni/rig-setup-<versionId>.done); `timeoutMs` is the rig-specific\n// budget (settings.rigSetupTimeoutMs), NOT the 120s lifecycle default; `rigName`\n// is for human-readable events/errors only.\nexport type RigSetupDescriptor = {\n rigId: string;\n versionId: string;\n rigName: string;\n script: string;\n timeoutMs: number;\n};\n\nexport type SandboxLifecycleHook = {\n id: string;\n phase: SandboxLifecycleHookPhase;\n shouldRun?: (context: SandboxLifecycleHookContext) => boolean;\n run: (session: SandboxSessionLike, context: SandboxLifecycleHookContext) => Promise<void>;\n};\n\nconst builtInSandboxLifecycleHooks: Record<string, SandboxLifecycleHook> = {\n \"azure-cli-login\": {\n id: \"azure-cli-login\",\n phase: \"beforeAgentStart\",\n shouldRun: ({ environment }) => hasAzureServicePrincipal(environment),\n run: runAzureCliLoginHook,\n },\n};\n\nexport function sandboxLifecycleHooksForIds(ids: string[]): SandboxLifecycleHook[] {\n return ids.map((id) => {\n const hook = builtInSandboxLifecycleHooks[id];\n if (!hook) {\n throw new Error(`Unknown sandbox lifecycle hook ${id}`);\n }\n return hook;\n });\n}\n\nfunction applicableBeforeAgentStartHooks(\n hooks: SandboxLifecycleHook[],\n context: SandboxLifecycleHookContext,\n): SandboxLifecycleHook[] {\n return hooks.filter(\n (hook) => hook.phase === \"beforeAgentStart\" && (hook.shouldRun?.(context) ?? true),\n );\n}\n\n/**\n * Run the beforeAgentStart lifecycle hooks directly against an already-live box.\n *\n * The create/resume decoration (withSandboxLifecycleHooks) is structurally blind to\n * the PROVIDED-session path: when runStream hands the SDK a live `session`\n * (runOptions.sandbox.session — the lease-owned box resolved by the turn activity),\n * SandboxRuntimeManager uses it as-is and never calls client.create/resume, so a\n * wrapper around those methods never fires. Callers on that path invoke this\n * before starting the run so the box still gets its beforeAgentStart preparation\n * (repository clone + B1 askpass/token-file seed, azure-cli-login).\n */\nexport async function runBeforeAgentStartHooks(\n session: SandboxSessionLike,\n hooks: SandboxLifecycleHook[],\n context: SandboxLifecycleHookContext,\n): Promise<void> {\n for (const hook of applicableBeforeAgentStartHooks(hooks, context)) {\n await hook.run(session, context);\n }\n}\n\nexport function withSandboxLifecycleHooks(\n client: SandboxClient,\n hooks: SandboxLifecycleHook[],\n context: SandboxLifecycleHookContext,\n): SandboxClient {\n const beforeAgentStartHooks = applicableBeforeAgentStartHooks(hooks, context);\n if (beforeAgentStartHooks.length === 0) {\n return client;\n }\n const seen = new WeakSet<object>();\n const wrapSession = async <T extends SandboxSessionLike>(session: T): Promise<T> => {\n if (typeof session === \"object\" && session !== null && !seen.has(session)) {\n for (const hook of beforeAgentStartHooks) {\n await hook.run(session, context);\n }\n seen.add(session);\n }\n return session;\n };\n const wrapped: SandboxClient = {\n backendId: client.backendId,\n ...(client.supportsDefaultOptions !== undefined\n ? { supportsDefaultOptions: client.supportsDefaultOptions }\n : {}),\n ...(client.create\n ? {\n create: async (...args: any[]) =>\n await wrapSession(await (client.create as any)(...args)),\n }\n : {}),\n ...(client.resume\n ? {\n resume: async (state: SandboxSessionState) =>\n await wrapSession(await client.resume!(state)),\n }\n : {}),\n ...(client.delete\n ? {\n delete: async (state: SandboxSessionState) => await client.delete!(state),\n }\n : {}),\n ...(client.serializeSessionState\n ? {\n serializeSessionState: async (state: SandboxSessionState, options) =>\n await client.serializeSessionState!(state, options),\n }\n : {}),\n ...(client.canPersistOwnedSessionState\n ? {\n canPersistOwnedSessionState: async (state: SandboxSessionState) =>\n await client.canPersistOwnedSessionState!(state),\n }\n : {}),\n ...(client.canReusePreservedOwnedSession\n ? {\n canReusePreservedOwnedSession: async (state: SandboxSessionState) =>\n await client.canReusePreservedOwnedSession!(state),\n }\n : {}),\n ...(client.deserializeSessionState\n ? {\n deserializeSessionState: async (state: Record<string, unknown>) =>\n await client.deserializeSessionState!(state),\n }\n : {}),\n };\n return wrapped;\n}\n\nfunction sandboxRepositoryCloneHooksForAgent(agent: Agent<any, any>): SandboxLifecycleHook[] {\n return agentRepositoryCloneHooks.get(agent) ?? [];\n}\n\n// TOKEN-BROKER (B1): the per-turn git token seed stashed for this agent (undefined\n// when no repo is attached / on the selfhosted path). Read into the clone hook\n// context at runStream so the token is seeded off-manifest.\nfunction gitTokenSeedsForAgent(agent: Agent<any, any>): GitTokenSeeds | undefined {\n return agentGitTokenSeeds.get(agent);\n}\n\nfunction gitCredentialBindingsForAgent(\n agent: Agent<any, any>,\n): GitCredentialBindingSeed[] | undefined {\n return agentGitCredentialBindings.get(agent);\n}\n\nfunction toolspaceTokenSeedForAgent(agent: Agent<any, any>): string | undefined {\n return agentToolspaceTokenSeed.get(agent);\n}\n\nfunction toolspaceTokenSessionIdForAgent(agent: Agent<any, any>): string | undefined {\n return agentToolspaceTokenSessionId.get(agent);\n}\n\nfunction toolspaceTokenFileForAgent(\n agent: Agent<any, any>,\n environment: Readonly<Record<string, string>>,\n): string | undefined {\n if (!toolspaceTokenSeedForAgent(agent)) return undefined;\n const sessionId = toolspaceTokenSessionIdForAgent(agent);\n if (!sessionId) {\n throw new Error(\"Toolspace token seed is missing its session identity\");\n }\n return toolspaceTokenFileFromEnvironment(environment, sessionId);\n}\n\nfunction sandboxToolspaceTokenHooksForAgent(agent: Agent<any, any>): SandboxLifecycleHook[] {\n return toolspaceTokenSeedForAgent(agent)\n ? [\n {\n id: \"toolspace-token\",\n phase: \"beforeAgentStart\",\n run: runToolspaceTokenSeedHook,\n },\n ]\n : [];\n}\n\n// M3: the rig-setup hook for this agent (present only on a rig-bound turn whose\n// frozen version carries a non-empty setup script). It runs FIRST among the\n// owned beforeAgentStart hooks so any tooling it installs is available to the\n// repository-clone / credential hooks that follow. The descriptor is threaded\n// through the hook context (rigSetupHookContext) so runRigSetupHook reads it.\nfunction sandboxRigSetupHooksForAgent(agent: Agent<any, any>): SandboxLifecycleHook[] {\n return agentRigSetup.get(agent)\n ? [\n {\n id: \"rig-setup\",\n phase: \"beforeAgentStart\",\n run: runRigSetupHook,\n },\n ]\n : [];\n}\n\nfunction rigSetupDescriptorForAgent(agent: Agent<any, any>): RigSetupDescriptor | undefined {\n return agentRigSetup.get(agent);\n}\n\n// M3: the rig version's credential hooks (already resolved + validated at build\n// time). Unioned with the deployment preparation-profile hooks by the caller.\nfunction rigCredentialHooksForAgent(agent: Agent<any, any>): SandboxLifecycleHook[] {\n return agentRigCredentialHooks.get(agent) ?? [];\n}\n\n// M3: union the deployment preparation-profile hooks with the rig version's\n// credential hooks, deduped by id (a hook named by BOTH the deployment profile\n// and the rig runs once). Deployment hooks keep their leading position.\nfunction unionCredentialHooks(\n deploymentHooks: SandboxLifecycleHook[],\n rigHooks: SandboxLifecycleHook[],\n): SandboxLifecycleHook[] {\n if (rigHooks.length === 0) {\n return deploymentHooks;\n }\n const seen = new Set(deploymentHooks.map((hook) => hook.id));\n return [...deploymentHooks, ...rigHooks.filter((hook) => !seen.has(hook.id))];\n}\n\nfunction gitCredentialSessionRegistrationHooks(\n callback: RunAgentStreamOptions[\"onGitCredentialSessionReady\"],\n): SandboxLifecycleHook[] {\n return callback\n ? [\n {\n id: \"git-credential-renewal-registration\",\n phase: \"beforeAgentStart\",\n run: async (session) => {\n await callback(session);\n },\n },\n ]\n : [];\n}\n\nfunction toolspaceTokenSessionRegistrationHooks(\n callback: RunAgentStreamOptions[\"onToolspaceTokenSessionReady\"],\n): SandboxLifecycleHook[] {\n return callback\n ? [\n {\n id: \"toolspace-token-renewal-registration\",\n phase: \"beforeAgentStart\",\n run: async (session) => {\n await callback(session);\n },\n },\n ]\n : [];\n}\n\nfunction sandboxRepositoryCloneHooks(\n settings: Settings,\n resources: ResourceRef[],\n activeSandboxBackend: Settings[\"sandboxBackend\"] = settings.sandboxBackend,\n): SandboxLifecycleHook[] {\n const repositories = resources.filter(\n (resource): resource is Extract<ResourceRef, { kind: \"repository\" }> =>\n resource.kind === \"repository\" &&\n repositoryUsesSandboxClone(settings, resource, activeSandboxBackend),\n );\n if (repositories.length === 0) {\n return [];\n }\n return [\n {\n id: \"repository-clone\",\n phase: \"beforeAgentStart\",\n run: async (session, context) => {\n await runRepositoryCloneHook(session, repositories, context);\n },\n },\n ];\n}\n\n/**\n * Whether the platform should seed a repository resource by `git clone` inside\n * the sandbox before the agent starts.\n *\n * SAFETY GATE (selfhosted/bring-your-own machine): the clone hook writes into\n * `posixPath.join(\"/workspace\", mountPath)`, which a selfhosted agent rewrites\n * to a path under its REAL launch directory — so a platform-initiated clone\n * lands on the user's actual disk. A connected machine already owns its\n * filesystem; the platform must NEVER clone onto it. We therefore key the\n * decision off the EFFECTIVE/active backend, not just the session's HOME backend\n * (`settings.sandboxBackend`): a session can run on the cloud default while its\n * active sandbox has been swapped to a connected machine (active_sandbox_id → a\n * selfhosted lease), in which case the agent actually executes on the user's\n * machine even though the home backend is e.g. \"modal\". `activeSandboxBackend`\n * defaults to the home backend, so a session whose HOME backend is \"selfhosted\"\n * is gated with no caller change, and every cloud path is byte-for-byte\n * unchanged.\n */\nexport function repositoryUsesSandboxClone(\n settings: Settings,\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n activeSandboxBackend: Settings[\"sandboxBackend\"] = settings.sandboxBackend,\n): boolean {\n if (activeSandboxBackend === \"selfhosted\") {\n return false;\n }\n return (\n settings.sandboxBackend === \"modal\" ||\n Boolean(resource.githubInstallationId && resource.githubRepositoryId) ||\n Boolean(resource.provider)\n );\n}\n\nconst GIT_CREDENTIAL_PROVIDERS = [\n \"github\",\n \"gitlab\",\n \"azure_devops\",\n] as const satisfies readonly GitCredentialProvider[];\n\nfunction gitProviderSeedEnv(provider: GitCredentialProvider): string {\n return `OPENGENI_GIT_${provider.toUpperCase()}_TOKEN_SEED`;\n}\n\nexport function gitCredentialBindingHash(credentialBindingId: string): string {\n return createHash(\"sha256\").update(credentialBindingId, \"utf8\").digest(\"hex\").slice(0, 32);\n}\n\nfunction gitBindingSeedEnv(binding: GitCredentialBindingSeed): string {\n return `OPENGENI_GIT_BINDING_${gitCredentialBindingHash(binding.credentialBindingId).toUpperCase()}_TOKEN_SEED`;\n}\n\nfunction gitCredentialBindingSeedExportPrefix(bindings: GitCredentialBindingSeed[]): string {\n return bindings\n .map((binding) => `export ${gitBindingSeedEnv(binding)}=${shellQuote(binding.token)}`)\n .join(\"\\n\");\n}\n\nfunction gitTokenSeedExportPrefix(seeds: GitTokenSeeds): string {\n const lines: string[] = [];\n for (const provider of GIT_CREDENTIAL_PROVIDERS) {\n const token = seeds[provider];\n if (!token) {\n continue;\n }\n lines.push(`export ${gitProviderSeedEnv(provider)}=${shellQuote(token)}`);\n if (provider === \"github\") {\n lines.push(`export OPENGENI_GIT_TOKEN_SEED=${shellQuote(token)}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\ntype RuntimeGitBindingDescriptor = {\n provider: GitCredentialProvider;\n credentialBindingId: string;\n bindingHash: string;\n protocol: string;\n host: string;\n path: string;\n uri: string;\n mountPath: string;\n};\n\ntype RuntimeGitHttpBrokerRouteDescriptor = {\n provider: GitCredentialProvider;\n credentialBindingId: string;\n bindingHash: string;\n repositoryUri: string;\n brokerUri: string;\n protocol: \"https\";\n host: string;\n path: string;\n};\n\nfunction runtimeGitBindingDescriptors(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n): RuntimeGitBindingDescriptor[] {\n const remoteBindings = new Map<string, string>();\n const bindingProviders = new Map<string, GitCredentialProvider>();\n return resources.map((resource) => {\n const url = new URL(resource.uri);\n const credentialProvider = gitCredentialProviderForRepository(resource);\n // Provider-less public/legacy resources retain the historical GitHub\n // askpass fallback, but credential-bound resources derive through the\n // shared contracts helper used by the worker and core.\n const provider = credentialProvider ?? \"github\";\n const credentialBindingId =\n gitCredentialBindingIdForRepository(resource, credentialProvider) ?? provider;\n const path = url.pathname.replace(/^\\/+|\\/+$/g, \"\");\n const remote = `${url.protocol.toLowerCase()}//${url.host.toLowerCase()}/${path.replace(/\\.git$/, \"\")}`;\n const bindingKey = `${provider}\\u0000${credentialBindingId}`;\n const boundProvider = bindingProviders.get(credentialBindingId);\n if (boundProvider && boundProvider !== provider) {\n throw new Error(\n `credential binding ${credentialBindingId} is assigned to multiple Git providers`,\n );\n }\n bindingProviders.set(credentialBindingId, provider);\n const claimed = remoteBindings.get(remote);\n if (claimed && claimed !== bindingKey) {\n throw new Error(\n `repository remote ${resource.uri} is claimed by multiple credential bindings`,\n );\n }\n remoteBindings.set(remote, bindingKey);\n return {\n provider,\n credentialBindingId,\n bindingHash: gitCredentialBindingHash(credentialBindingId),\n protocol: url.protocol.replace(/:$/, \"\").toLowerCase(),\n host: url.host.toLowerCase(),\n path,\n uri: resource.uri,\n mountPath: `/workspace/${resourceMountPath(resource)}`,\n };\n });\n}\n\nfunction gitCredentialBindingInventoryCommandLines(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n bindings: GitCredentialBindingSeed[],\n): string[] {\n type GitBindingInventoryTransport = \"direct_token\" | \"git_http_broker\";\n type GitBindingInventoryEntry = {\n credentialBindingId: string;\n provider: GitCredentialProvider;\n transport: GitBindingInventoryTransport;\n repositories: Array<{ uri: string; mountPath: string }>;\n };\n const bindingTransports = new Map<string, GitBindingInventoryTransport>(\n bindings.map((binding) => [\n gitCredentialBindingKey(binding.provider, binding.credentialBindingId),\n binding.transport?.kind === \"http_broker\" ? \"git_http_broker\" : \"direct_token\",\n ]),\n );\n const entries = new Map<string, GitBindingInventoryEntry>();\n for (const descriptor of runtimeGitBindingDescriptors(resources)) {\n const key = gitCredentialBindingKey(descriptor.provider, descriptor.credentialBindingId);\n const transport = bindingTransports.get(key);\n if (!transport) continue;\n const entry: GitBindingInventoryEntry = entries.get(key) ?? {\n credentialBindingId: descriptor.credentialBindingId,\n provider: descriptor.provider,\n transport,\n repositories: [],\n };\n entry.repositories.push({ uri: descriptor.uri, mountPath: descriptor.mountPath });\n entries.set(key, entry);\n }\n const inventory = `${JSON.stringify(\n {\n version: 1,\n bindings: [...entries.values()],\n },\n null,\n 2,\n )}\\n`;\n return [\n 'git_binding_inventory=\"${OPENGENI_GIT_BINDINGS_FILE:-$HOME/.opengeni/git-bindings.json}\"',\n 'mkdir -p \"$(dirname \"$git_binding_inventory\")\"',\n 'inventory_umask=\"$(umask)\"',\n \"umask 077\",\n `printf '%s' ${shellQuote(inventory)} > \"$git_binding_inventory.tmp.$$\"`,\n 'mv -f \"$git_binding_inventory.tmp.$$\" \"$git_binding_inventory\"',\n 'umask \"$inventory_umask\"',\n ];\n}\n\nfunction gitCredentialBindingKey(\n provider: GitCredentialProvider,\n credentialBindingId: string,\n): string {\n return `${provider}\\u0000${credentialBindingId}`;\n}\n\nfunction brokeredGitCredentialBindingKeys(\n bindings: GitCredentialBindingSeed[],\n): ReadonlySet<string> {\n return new Set(\n bindings\n .filter((binding) => binding.transport?.kind === \"http_broker\")\n .map((binding) => gitCredentialBindingKey(binding.provider, binding.credentialBindingId)),\n );\n}\n\nfunction runtimeGitHttpBrokerRouteDescriptors(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n bindings: GitCredentialBindingSeed[],\n): RuntimeGitHttpBrokerRouteDescriptor[] {\n const resourceDescriptors = runtimeGitBindingDescriptors(resources);\n const byBindingAndUri = new Map<string, RuntimeGitBindingDescriptor>();\n for (const descriptor of resourceDescriptors) {\n byBindingAndUri.set(\n `${gitCredentialBindingKey(descriptor.provider, descriptor.credentialBindingId)}\\u0000${descriptor.uri}`,\n descriptor,\n );\n }\n\n const routes: RuntimeGitHttpBrokerRouteDescriptor[] = [];\n const claimedRepositoryUris = new Set<string>();\n const claimedBrokerUris = new Set<string>();\n for (const binding of bindings) {\n if (!binding.transport) continue;\n if (\n typeof binding.transport !== \"object\" ||\n binding.transport.kind !== \"http_broker\" ||\n !Array.isArray(binding.transport.repositories)\n ) {\n throw new Error(\n `Git credential binding ${binding.credentialBindingId} uses an unsupported transport`,\n );\n }\n const bindingKey = gitCredentialBindingKey(binding.provider, binding.credentialBindingId);\n const expected = resourceDescriptors.filter(\n (descriptor) =>\n gitCredentialBindingKey(descriptor.provider, descriptor.credentialBindingId) === bindingKey,\n );\n if (expected.length === 0 || binding.transport.repositories.length !== expected.length) {\n throw new Error(\n `Git HTTP broker binding ${binding.credentialBindingId} does not cover its exact repository set`,\n );\n }\n for (const route of binding.transport.repositories) {\n if (\n !route ||\n typeof route !== \"object\" ||\n typeof route.repositoryUri !== \"string\" ||\n typeof route.brokerUri !== \"string\"\n ) {\n throw new Error(\n `Git HTTP broker binding ${binding.credentialBindingId} contains an invalid repository route`,\n );\n }\n const descriptor = byBindingAndUri.get(`${bindingKey}\\u0000${route.repositoryUri}`);\n if (!descriptor || claimedRepositoryUris.has(route.repositoryUri)) {\n throw new Error(\n `Git HTTP broker binding ${binding.credentialBindingId} contains an unexpected repository route`,\n );\n }\n let brokerUrl: URL;\n try {\n brokerUrl = new URL(route.brokerUri);\n } catch {\n throw new Error(\n `Git HTTP broker binding ${binding.credentialBindingId} contains an invalid broker URI`,\n );\n }\n if (\n brokerUrl.protocol !== \"https:\" ||\n brokerUrl.username ||\n brokerUrl.password ||\n brokerUrl.search ||\n brokerUrl.hash ||\n brokerUrl.href !== route.brokerUri ||\n claimedBrokerUris.has(brokerUrl.href)\n ) {\n throw new Error(\n `Git HTTP broker binding ${binding.credentialBindingId} contains an unsafe broker URI`,\n );\n }\n claimedRepositoryUris.add(route.repositoryUri);\n claimedBrokerUris.add(brokerUrl.href);\n routes.push({\n provider: binding.provider,\n credentialBindingId: binding.credentialBindingId,\n bindingHash: gitCredentialBindingHash(binding.credentialBindingId),\n repositoryUri: route.repositoryUri,\n brokerUri: route.brokerUri,\n protocol: \"https\",\n host: brokerUrl.host.toLowerCase(),\n path: brokerUrl.pathname.replace(/^\\/+|\\/+$/g, \"\"),\n });\n }\n }\n return routes;\n}\n\nfunction gitUsernameForProvider(provider: GitCredentialProvider): string {\n if (provider === \"github\") return \"x-access-token\";\n if (provider === \"gitlab\") return \"oauth2\";\n return \"opengeni\";\n}\n\nfunction gitCredentialHelperBindingCaseLines(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n bindings: GitCredentialBindingSeed[],\n): string[] {\n const brokeredBindings = brokeredGitCredentialBindingKeys(bindings);\n return runtimeGitBindingDescriptors(resources)\n .filter(\n (descriptor) =>\n !brokeredBindings.has(\n gitCredentialBindingKey(descriptor.provider, descriptor.credentialBindingId),\n ),\n )\n .flatMap((descriptor) => {\n const paths = new Set([\n descriptor.path,\n descriptor.path.replace(/\\.git$/, \"\"),\n `${descriptor.path.replace(/\\.git$/, \"\")}.git`,\n ]);\n return [...paths].map(\n (path) =>\n ` ${shellQuote(`${descriptor.protocol}|${descriptor.host}|${path}`)}) username=${shellQuote(gitUsernameForProvider(descriptor.provider))}; token_file=\"$credential_dir/${descriptor.bindingHash}-token\" ;;`,\n );\n });\n}\n\nfunction gitCredentialHelperBrokerCaseLines(\n routes: RuntimeGitHttpBrokerRouteDescriptor[],\n): string[] {\n return routes.flatMap((route) => {\n const paths = new Set([\n route.path,\n route.path.replace(/\\.git$/, \"\"),\n `${route.path.replace(/\\.git$/, \"\")}.git`,\n ]);\n return [...paths].map(\n (path) =>\n ` ${shellQuote(`${route.protocol}|${route.host}|${path}`)}) username=opengeni; token_file=\"$credential_dir/${route.bindingHash}-token\" ;;`,\n );\n });\n}\n\nfunction gitAskpassHostProviderCaseLines(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n brokerRoutes: RuntimeGitHttpBrokerRouteDescriptor[],\n): string[] {\n const hosts = new Map<string, { provider: GitCredentialProvider; bindings: Set<string> }>();\n for (const descriptor of runtimeGitBindingDescriptors(resources)) {\n const entry = hosts.get(descriptor.host) ?? {\n provider: descriptor.provider,\n bindings: new Set<string>(),\n };\n entry.bindings.add(`${descriptor.provider}\\u0000${descriptor.credentialBindingId}`);\n hosts.set(descriptor.host, entry);\n }\n const brokerHosts = [...new Set(brokerRoutes.map((route) => route.host))]\n .sort((a, b) => a.localeCompare(b))\n .map((hostname) => ` ${shellQuote(hostname)}) printf '\\\\n'; return 0 ;;`);\n return [\n ...brokerHosts,\n ...[...hosts.entries()]\n .filter(([, entry]) => entry.bindings.size === 1)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(\n ([hostname, entry]) =>\n ` ${shellQuote(hostname)}) printf '%s\\\\n' ${entry.provider}; return 0 ;;`,\n ),\n ];\n}\n\nfunction gitCredentialTokenWriterCommandLines(bindings: GitCredentialBindingSeed[] = []): string[] {\n const bindingWrites = bindings.flatMap((binding) => {\n const hash = gitCredentialBindingHash(binding.credentialBindingId);\n const seedEnv = gitBindingSeedEnv(binding);\n const count = Math.max(1, binding.providerBindingCount ?? 1);\n const provider = binding.provider;\n const lines = [`write_git_binding_token ${shellQuote(hash)} \"\\${${seedEnv}:-}\"`];\n if (count === 1 && binding.transport?.kind !== \"http_broker\") {\n lines.push(`write_git_provider_token ${shellQuote(provider)} \"\\${${seedEnv}:-}\"`);\n } else {\n lines.push(`remove_git_provider_token ${shellQuote(provider)}`);\n }\n return lines;\n });\n return [\n // TOKEN-BROKER (B1/B2): seed run-scoped provider tokens into stable files and\n // atomically replace each provider file. Token VALUES are supplied only by\n // the per-exec command prefix\n // (OPENGENI_GIT_*_TOKEN_SEED), never by the box/agent manifest. Helper paths\n // are stable manifest values from @opengeni/config.\n \"git_provider_token_file() {\",\n ' provider=\"$1\"',\n ' case \"$provider\" in',\n \" github) printf '%s\\\\n' \\\"${OPENGENI_GIT_TOKEN_FILE:-$HOME/.opengeni/git-token}\\\" ;;\",\n \" *) printf '%s\\\\n' \\\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/$provider-token\\\" ;;\",\n \" esac\",\n \"}\",\n \"write_git_binding_token() {\",\n ' binding_hash=\"$1\"',\n ' token=\"$2\"',\n ' [ -n \"$token\" ] || return 0',\n ' credential_dir=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}\"',\n ' mkdir -p \"$credential_dir\"',\n ' token_file=\"$credential_dir/$binding_hash-token\"',\n ' printf \\'%s\\' \"$token\" > \"$token_file.tmp.$$\"',\n ' mv -f \"$token_file.tmp.$$\" \"$token_file\"',\n \"}\",\n \"remove_git_provider_token() {\",\n ' provider=\"$1\"',\n ' rm -f \"$(git_provider_token_file \"$provider\")\"',\n ' if [ \"$provider\" = github ]; then',\n ' rm -f \"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/github-token\"',\n \" fi\",\n \"}\",\n \"write_git_provider_token() {\",\n ' provider=\"$1\"',\n ' token=\"$2\"',\n ' [ -n \"$token\" ] || return 0',\n ' token_file=\"$(git_provider_token_file \"$provider\")\"',\n ' mkdir -p \"$(dirname \"$token_file\")\"',\n ' printf \\'%s\\' \"$token\" > \"$token_file.tmp.$$\"',\n ' mv -f \"$token_file.tmp.$$\" \"$token_file\"',\n ' if [ \"$provider\" = github ]; then',\n ' credential_dir=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}\"',\n ' mkdir -p \"$credential_dir\"',\n ' printf \\'%s\\' \"$token\" > \"$credential_dir/github-token.tmp.$$\"',\n ' mv -f \"$credential_dir/github-token.tmp.$$\" \"$credential_dir/github-token\"',\n \" fi\",\n \"}\",\n 'seed_umask=\"$(umask)\"',\n \"umask 077\",\n 'write_git_provider_token github \"${OPENGENI_GIT_GITHUB_TOKEN_SEED:-${OPENGENI_GIT_TOKEN_SEED:-}}\"',\n 'write_git_provider_token gitlab \"${OPENGENI_GIT_GITLAB_TOKEN_SEED:-}\"',\n 'write_git_provider_token azure_devops \"${OPENGENI_GIT_AZURE_DEVOPS_TOKEN_SEED:-}\"',\n ...bindingWrites,\n 'umask \"$seed_umask\"',\n ];\n}\n\nfunction gitHttpBrokerConfigCommandLines(routes: RuntimeGitHttpBrokerRouteDescriptor[]): string[] {\n return [\n 'git_http_broker_config=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/http-broker.gitconfig\"',\n 'mkdir -p \"$(dirname \"$git_http_broker_config\")\"',\n 'broker_umask=\"$(umask)\"',\n \"umask 077\",\n ': > \"$git_http_broker_config.tmp.$$\"',\n ...routes.map(\n (route) =>\n `git config --file \"$git_http_broker_config.tmp.$$\" --add ${shellQuote(`url.${route.brokerUri}.insteadOf`)} ${shellQuote(route.repositoryUri)}`,\n ),\n 'mv -f \"$git_http_broker_config.tmp.$$\" \"$git_http_broker_config\"',\n 'umask \"$broker_umask\"',\n 'git config --global --unset-all include.path \"$git_http_broker_config\" >/dev/null 2>&1 || true',\n 'git config --global --add include.path \"$git_http_broker_config\"',\n ];\n}\n\nfunction gitCredentialHelperCommandLines(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[] = [],\n bindings: GitCredentialBindingSeed[] = [],\n): string[] {\n const brokerRoutes = runtimeGitHttpBrokerRouteDescriptors(resources, bindings);\n const hostProviderCases = gitAskpassHostProviderCaseLines(resources, brokerRoutes);\n const bindingCases = [\n ...gitCredentialHelperBindingCaseLines(resources, bindings),\n ...gitCredentialHelperBrokerCaseLines(brokerRoutes),\n ];\n const descriptors = runtimeGitBindingDescriptors(resources);\n const brokeredBindings = brokeredGitCredentialBindingKeys(bindings);\n const wrapperDescriptors =\n bindings.length > 0\n ? descriptors.filter(\n (descriptor) =>\n !brokeredBindings.has(\n gitCredentialBindingKey(descriptor.provider, descriptor.credentialBindingId),\n ),\n )\n : [];\n const bindingProviders = new Map<GitCredentialProvider, Set<string>>();\n for (const descriptor of runtimeGitBindingDescriptors(resources)) {\n const ids = bindingProviders.get(descriptor.provider) ?? new Set<string>();\n ids.add(descriptor.credentialBindingId);\n bindingProviders.set(descriptor.provider, ids);\n }\n const strictAskpass = [...bindingProviders.values()].some((ids) => ids.size > 1);\n const allowedWrapperHashes = [\n ...new Set(wrapperDescriptors.map((item) => `${item.provider}|${item.bindingHash}`)),\n ].map((key) => ` ${shellQuote(key)}) return 0 ;;`);\n const originWrapperHashes = wrapperDescriptors.flatMap((item) => {\n const base = item.uri.replace(/\\.git$/, \"\");\n return [...new Set([item.uri, base, `${base}.git`])].map(\n (uri) =>\n ` ${shellQuote(`${item.provider}|${uri}`)}) printf '%s\\\\n' ${shellQuote(item.bindingHash)}; return 0 ;;`,\n );\n });\n const soleWrapperHashes = [...bindingProviders.entries()].flatMap(([provider, ids]) => {\n if (ids.size !== 1) return [];\n const descriptor = wrapperDescriptors.find((item) => item.provider === provider);\n return descriptor\n ? [\n ` ${shellQuote(provider)}) printf '%s\\\\n' ${shellQuote(descriptor.bindingHash)}; return 0 ;;`,\n ]\n : [];\n });\n const multiWrapperProviders =\n bindings.length > 0\n ? [...bindingProviders.entries()]\n .filter(([, ids]) => ids.size > 1)\n .map(([provider]) => provider)\n : [];\n const brokeredOriginCases = brokerRoutes.flatMap((route) => {\n const base = route.repositoryUri.replace(/\\.git$/, \"\");\n return [...new Set([route.repositoryUri, base, `${base}.git`])].map(\n (uri) => ` ${shellQuote(`${route.provider}|${uri}`)}) return 0 ;;`,\n );\n });\n const brokeredBindingHashCases = bindings\n .filter((binding) => binding.transport?.kind === \"http_broker\")\n .map(\n (binding) =>\n ` ${shellQuote(`${binding.provider}|${gitCredentialBindingHash(binding.credentialBindingId)}`)}) return 0 ;;`,\n );\n const providerBindingKinds = new Map<\n GitCredentialProvider,\n { direct: number; brokered: number }\n >();\n for (const binding of bindings) {\n const counts = providerBindingKinds.get(binding.provider) ?? { direct: 0, brokered: 0 };\n if (binding.transport?.kind === \"http_broker\") counts.brokered += 1;\n else counts.direct += 1;\n providerBindingKinds.set(binding.provider, counts);\n }\n const brokerOnlyProviders = [...providerBindingKinds.entries()]\n .filter(([, counts]) => counts.brokered > 0 && counts.direct === 0)\n .map(([provider]) => provider);\n return [\n ...gitCredentialTokenWriterCommandLines(bindings),\n ...gitCredentialBindingInventoryCommandLines(resources, bindings),\n // Provision git/provider-CLI helpers at SETUP (runtime) before any clone\n // runs. Renewal updates only token files and deliberately leaves these\n // repository-specific host mappings intact.\n 'git_askpass=\"${GIT_ASKPASS:-$HOME/.opengeni/askpass}\"',\n 'mkdir -p \"$(dirname \"$git_askpass\")\"',\n \"cat > \\\"$git_askpass.tmp.$$\\\" <<'ASKPASS_EOF'\",\n \"#!/usr/bin/env sh\",\n \"prompt_host() {\",\n \" prompt_lower=\\\"$(printf '%s\\\\n' \\\"$1\\\" | tr '[:upper:]' '[:lower:]')\\\"\",\n ' case \"$prompt_lower\" in',\n \" *://*) ;;\",\n \" *) printf '\\\\n'; return 0 ;;\",\n \" esac\",\n ' rest=\"${prompt_lower#*://}\"',\n ' rest=\"${rest#*@}\"',\n ' host=\"${rest%%/*}\"',\n ' host=\"$(printf \\'%s\\\\n\\' \"$host\" | tr -d \"\\'\")\"',\n ' host=\"${host%:}\"',\n \" printf '%s\\\\n' \\\"$host\\\"\",\n \"}\",\n \"provider_for_prompt() {\",\n ' host=\"$(prompt_host \"$1\")\"',\n ' case \"$host\" in',\n ...(hostProviderCases.length > 0 ? hostProviderCases : [' \"\") : ;;']),\n \" esac\",\n \" case \\\"$(printf '%s\\\\n' \\\"$1\\\" | tr '[:upper:]' '[:lower:]')\\\" in\",\n \" *github.com*|*githubusercontent.com*) printf '%s\\\\n' github ;;\",\n \" *gitlab*) printf '%s\\\\n' gitlab ;;\",\n \" *dev.azure.com*|*.visualstudio.com*) printf '%s\\\\n' azure_devops ;;\",\n strictAskpass ? \" *) printf '\\\\n' ;;\" : \" *) printf '%s\\\\n' github ;;\",\n \" esac\",\n \"}\",\n \"token_file_for_provider() {\",\n ' case \"$1\" in',\n \" github) printf '%s\\\\n' \\\"${OPENGENI_GIT_TOKEN_FILE:-$HOME/.opengeni/git-token}\\\" ;;\",\n \" *) printf '%s\\\\n' \\\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/$1-token\\\" ;;\",\n \" esac\",\n \"}\",\n \"username_for_provider() {\",\n ' case \"$1\" in',\n \" github) printf '%s\\\\n' \\\"x-access-token\\\" ;;\",\n \" gitlab) printf '%s\\\\n' \\\"oauth2\\\" ;;\",\n \" azure_devops) printf '%s\\\\n' \\\"opengeni\\\" ;;\",\n \" *) printf '\\\\n' ;;\",\n \" esac\",\n \"}\",\n 'provider=\"$(provider_for_prompt \"$1\")\"',\n 'case \"$1\" in',\n ' *Username*) username_for_provider \"$provider\" ;;',\n ' *Password*) cat \"$(token_file_for_provider \"$provider\")\" 2>/dev/null || printf \\'\\\\n\\' ;;',\n \" *) printf '\\\\n' ;;\",\n \"esac\",\n \"ASKPASS_EOF\",\n 'chmod 0755 \"$git_askpass.tmp.$$\"',\n 'mv -f \"$git_askpass.tmp.$$\" \"$git_askpass\"',\n 'git_credential_helper=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/helper\"',\n 'mkdir -p \"$(dirname \"$git_credential_helper\")\"',\n \"cat > \\\"$git_credential_helper.tmp.$$\\\" <<'GIT_CREDENTIAL_HELPER_EOF'\",\n \"#!/usr/bin/env sh\",\n \"set -eu\",\n '[ \"${1:-get}\" = get ] || exit 0',\n \"protocol= host= path=\",\n \"while IFS='=' read -r key value; do\",\n ' case \"$key\" in',\n \" protocol) protocol=\\\"$(printf '%s' \\\"$value\\\" | tr '[:upper:]' '[:lower:]')\\\" ;;\",\n \" host) host=\\\"$(printf '%s' \\\"$value\\\" | tr '[:upper:]' '[:lower:]')\\\" ;;\",\n ' path) path=\"${value#/}\" ;;',\n \" esac\",\n \"done\",\n 'credential_dir=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}\"',\n \"username= token_file=\",\n 'case \"$protocol|$host|$path\" in',\n ...bindingCases,\n \" *) exit 0 ;;\",\n \"esac\",\n '[ -r \"$token_file\" ] || exit 0',\n 'password=\"$(cat \"$token_file\" 2>/dev/null || true)\"',\n '[ -n \"$password\" ] || exit 0',\n 'printf \\'username=%s\\\\npassword=%s\\\\n\\' \"$username\" \"$password\"',\n \"GIT_CREDENTIAL_HELPER_EOF\",\n 'chmod 0755 \"$git_credential_helper.tmp.$$\"',\n 'mv -f \"$git_credential_helper.tmp.$$\" \"$git_credential_helper\"',\n // Empty helper resets lower-priority/system helpers; our exact path-aware\n // helper returns no credential for an unbound remote, so multi-binding\n // sessions fail closed instead of falling through to ambient credentials.\n \"git config --global --unset-all credential.helper >/dev/null 2>&1 || true\",\n \"git config --global --add credential.helper ''\",\n 'git config --global --add credential.helper \"$git_credential_helper\"',\n \"git config --global credential.useHttpPath true\",\n ...gitHttpBrokerConfigCommandLines(brokerRoutes),\n 'wrapper_dir=\"${OPENGENI_GIT_CLI_WRAPPER_DIR:-$HOME/.opengeni/bin}\"',\n 'mkdir -p \"$wrapper_dir\"',\n \"for opengeni_git_cli_tool in gh glab az; do\",\n ' wrapper=\"$wrapper_dir/$opengeni_git_cli_tool\"',\n \" cat > \\\"$wrapper.tmp.$$\\\" <<'CLI_WRAPPER_EOF'\",\n \"#!/usr/bin/env sh\",\n \"set -eu\",\n 'tool=\"${0##*/}\"',\n 'case \"$tool\" in',\n \" gh) provider=github; token_env=GH_TOKEN ;;\",\n \" glab) provider=gitlab; token_env=GITLAB_TOKEN ;;\",\n \" az) provider=azure_devops; token_env=AZURE_DEVOPS_EXT_PAT ;;\",\n \" *) provider=; token_env= ;;\",\n \"esac\",\n \"hash_binding_id() {\",\n \" if command -v sha256sum >/dev/null 2>&1; then printf '%s' \\\"$1\\\" | sha256sum | cut -c1-32; return; fi\",\n \" if command -v shasum >/dev/null 2>&1; then printf '%s' \\\"$1\\\" | shasum -a 256 | cut -c1-32; return; fi\",\n \" if command -v openssl >/dev/null 2>&1; then printf '%s' \\\"$1\\\" | openssl dgst -sha256 | sed 's/^.*= //' | cut -c1-32; return; fi\",\n \" printf '%s\\\\n' 'No SHA-256 utility is available to select OPENGENI_GIT_BINDING' >&2\",\n \" return 127\",\n \"}\",\n \"binding_hash_allowed() {\",\n ' case \"$provider|$1\" in',\n ...allowedWrapperHashes,\n \" *) return 1 ;;\",\n \" esac\",\n \"}\",\n \"binding_hash_is_brokered() {\",\n ' case \"$provider|$1\" in',\n ...brokeredBindingHashCases,\n \" *) return 1 ;;\",\n \" esac\",\n \"}\",\n \"binding_hash_for_origin() {\",\n ' case \"$provider|$1\" in',\n ...originWrapperHashes,\n \" *) return 1 ;;\",\n \" esac\",\n \"}\",\n \"origin_is_brokered() {\",\n ' case \"$provider|$1\" in',\n ...brokeredOriginCases,\n \" *) return 1 ;;\",\n \" esac\",\n \"}\",\n \"sole_binding_hash() {\",\n ' case \"$provider\" in',\n ...soleWrapperHashes,\n \" *) return 1 ;;\",\n \" esac\",\n \"}\",\n `multi_binding_providers=${shellQuote(multiWrapperProviders.join(\" \"))}`,\n `broker_only_providers=${shellQuote(brokerOnlyProviders.join(\" \"))}`,\n 'if [ -n \"$provider\" ]; then',\n \" binding_hash=\",\n ' if [ -n \"${OPENGENI_GIT_BINDING:-}\" ]; then',\n ' binding_hash=\"$(hash_binding_id \"$OPENGENI_GIT_BINDING\")\"',\n ' binding_hash_is_brokered \"$binding_hash\" && { printf \\'%s\\\\n\\' \"$tool provider API authentication is host-brokered for OPENGENI_GIT_BINDING; use the configured provider MCP tools\" >&2; exit 2; }',\n ' binding_hash_allowed \"$binding_hash\" || { printf \\'%s\\\\n\\' \"OPENGENI_GIT_BINDING does not select a $provider credential attached to this session\" >&2; exit 2; }',\n \" elif command -v git >/dev/null 2>&1; then\",\n ' origin=\"$(git config --get remote.origin.url 2>/dev/null || true)\"',\n ' [ -z \"$origin\" ] || ! origin_is_brokered \"$origin\" || { printf \\'%s\\\\n\\' \"$tool provider API authentication is host-brokered for this repository; use the configured provider MCP tools\" >&2; exit 2; }',\n ' [ -z \"$origin\" ] || binding_hash=\"$(binding_hash_for_origin \"$origin\" 2>/dev/null || true)\"',\n \" fi\",\n ' [ -n \"$binding_hash\" ] || binding_hash=\"$(sole_binding_hash 2>/dev/null || true)\"',\n ' if [ -n \"$binding_hash\" ]; then',\n ' token_file=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/$binding_hash-token\"',\n \" else\",\n ' case \" $broker_only_providers \" in',\n ' *\" $provider \"*) printf \\'%s\\\\n\\' \"$tool provider API authentication is host-brokered for this session; use the configured provider MCP tools\" >&2; exit 2 ;;',\n \" esac\",\n ' case \" $multi_binding_providers \" in',\n ' *\" $provider \"*) printf \\'%s\\\\n\\' \"Unable to select one of multiple $provider credentials; run inside an attached repository, or inspect ${OPENGENI_GIT_BINDINGS_FILE:-$HOME/.opengeni/git-bindings.json} and set OPENGENI_GIT_BINDING\" >&2; exit 2 ;;',\n \" esac\",\n ' case \"$provider\" in',\n ' github) token_file=\"${OPENGENI_GIT_TOKEN_FILE:-$HOME/.opengeni/git-token}\" ;;',\n ' *) token_file=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/$provider-token\" ;;',\n \" esac\",\n \" fi\",\n ' if [ -f \"$token_file\" ]; then',\n ' token=\"$(cat \"$token_file\" 2>/dev/null || true)\"',\n ' if [ -n \"$token\" ]; then',\n ' case \"$token_env\" in',\n ' GH_TOKEN) export GH_TOKEN=\"$token\" ;;',\n ' GITLAB_TOKEN) export GITLAB_TOKEN=\"$token\" ;;',\n ' AZURE_DEVOPS_EXT_PAT) export AZURE_DEVOPS_EXT_PAT=\"$token\" ;;',\n \" esac\",\n \" fi\",\n \" fi\",\n \"fi\",\n 'self_real=\"$(readlink -f \"$0\" 2>/dev/null || printf \\'%s\\\\n\\' \"$0\")\"',\n 'old_ifs=\"$IFS\"',\n \"IFS=:\",\n \"for dir in $PATH; do\",\n ' [ -n \"$dir\" ] || dir=.',\n ' candidate=\"$dir/$tool\"',\n ' [ -x \"$candidate\" ] || continue',\n ' candidate_real=\"$(readlink -f \"$candidate\" 2>/dev/null || printf \\'%s\\\\n\\' \"$candidate\")\"',\n ' [ \"$candidate_real\" = \"$self_real\" ] && continue',\n ' IFS=\"$old_ifs\"',\n ' exec \"$candidate\" \"$@\"',\n \"done\",\n 'IFS=\"$old_ifs\"',\n \"printf '%s\\\\n' \\\"$tool: real command not found on PATH\\\" >&2\",\n \"exit 127\",\n \"CLI_WRAPPER_EOF\",\n ' chmod 0755 \"$wrapper.tmp.$$\"',\n ' mv -f \"$wrapper.tmp.$$\" \"$wrapper\"',\n \"done\",\n ];\n}\n\n/**\n * Build the off-manifest command used to atomically replace provider token files.\n *\n * Token values exist only in this one sandbox exec command. The stable askpass\n * and provider-CLI wrappers always read the files at invocation time, so an\n * in-flight multi-day turn observes the replacement without changing its\n * manifest environment or rebuilding the sandbox.\n */\nexport function gitProviderTokenRefreshCommand(seeds: GitTokenSeeds): string {\n const seedPrefix = gitTokenSeedExportPrefix(seeds);\n if (!seedPrefix) {\n return \"\";\n }\n return [\n \"set +x\",\n seedPrefix,\n \"set -eu\",\n 'export HOME=\"${HOME:-/workspace}\"',\n ...gitCredentialTokenWriterCommandLines(),\n ].join(\"\\n\");\n}\n\nexport function gitCredentialBindingTokenRefreshCommand(\n bindings: GitCredentialBindingSeed[],\n): string {\n const seedPrefix = gitCredentialBindingSeedExportPrefix(bindings);\n if (!seedPrefix) return \"\";\n return [\n \"set +x\",\n seedPrefix,\n \"set -eu\",\n 'export HOME=\"${HOME:-/workspace}\"',\n ...gitCredentialTokenWriterCommandLines(bindings),\n ].join(\"\\n\");\n}\n\nexport async function refreshGitProviderTokenFiles(\n session: GitCredentialTokenWriterSession,\n seeds: GitTokenSeeds,\n options: { runAs?: string; commandRunner?: SandboxLifecycleCommandRunner } = {},\n): Promise<void> {\n const command = gitProviderTokenRefreshCommand(seeds);\n if (!command) {\n return;\n }\n const args = {\n cmd: command,\n workdir: \"/workspace\",\n ...(options.runAs ? { runAs: options.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 4_000,\n };\n assertSandboxCommandSucceeded(\n await runSandboxLifecycleCommand(session, args, options.commandRunner),\n \"Git credential refresh\",\n );\n}\n\nexport async function refreshGitCredentialBindingTokenFiles(\n session: GitCredentialTokenWriterSession,\n bindings: GitCredentialBindingSeed[],\n options: { runAs?: string; commandRunner?: SandboxLifecycleCommandRunner } = {},\n): Promise<void> {\n const command = gitCredentialBindingTokenRefreshCommand(bindings);\n if (!command) return;\n const args = {\n cmd: command,\n workdir: \"/workspace\",\n ...(options.runAs ? { runAs: options.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 4_000,\n };\n assertSandboxCommandSucceeded(\n await runSandboxLifecycleCommand(session, args, options.commandRunner),\n \"Git credential binding refresh\",\n );\n}\n\nexport function repositoryCloneCommand(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n bindings: GitCredentialBindingSeed[] = [],\n): string {\n assertUniqueResourceMountPaths(resources);\n const commands = [\n \"set +x\",\n \"set -eu\",\n 'export HOME=\"${HOME:-/workspace}\"',\n 'export GIT_TERMINAL_PROMPT=\"${GIT_TERMINAL_PROMPT:-0}\"',\n \"ensure_git() {\",\n \" if command -v git >/dev/null 2>&1; then\",\n \" return 0\",\n \" fi\",\n \" if command -v apt-get >/dev/null 2>&1; then\",\n \" export DEBIAN_FRONTEND=noninteractive\",\n \" apt-get update >/dev/null\",\n \" apt-get install -y --no-install-recommends ca-certificates git >/dev/null\",\n \" rm -rf /var/lib/apt/lists/*\",\n \" command -v git >/dev/null 2>&1 && return 0\",\n \" fi\",\n ' echo \"git is not installed in the sandbox and could not be bootstrapped\" >&2',\n \" exit 127\",\n \"}\",\n \"ensure_git\",\n ...gitCredentialHelperCommandLines(resources, bindings),\n \"clone_repository() {\",\n ' target=\"$1\"',\n ' uri=\"$2\"',\n ' ref=\"$3\"',\n ' subpath=\"$4\"',\n ' if [ -e \"$target\" ] && { [ -f \"$target\" ] || [ -n \"$(find \"$target\" -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null)\" ]; }; then',\n // This hook re-runs every turn on a long-lived box, so \\\"non-empty\\\" alone is not\n // proof of a completed materialization: an interrupted clone (worker crash /\n // lifecycle timeout mid-mv/cp) leaves a partial tree that would otherwise pass\n // this check forever. A full-repo target must actually BE a work tree to be\n // skipped; a partial one is wiped and rebuilt (nothing legitimate writes under\n // the mount path before the repo exists). Subpath extracts are not git repos —\n // for those the plain non-empty check stands (no stronger signal available).\n ' if [ -n \"$subpath\" ] || git -C \"$target\" rev-parse --is-inside-work-tree >/dev/null 2>&1; then',\n ' echo \"Repository resource already present at $target\"',\n \" return 0\",\n \" fi\",\n ' echo \"Re-materializing partial repository resource at $target\" >&2',\n ' find \"$target\" -mindepth 1 -maxdepth 1 -exec rm -rf {} +',\n \" fi\",\n ' mkdir -p \"$(dirname \"$target\")\"',\n ' tmp=\"${target}.tmp.$$\"',\n ' rm -rf \"$tmp\"',\n // Fetch failures must not leak the pid-suffixed tmp clone beside the mount\n // (set -eu would exit before any cleanup).\n ' if ! { git init \"$tmp\" >/dev/null && git -C \"$tmp\" remote add origin \"$uri\" && git -C \"$tmp\" fetch --depth 1 --no-tags --filter=blob:none origin \"$ref\" && git -C \"$tmp\" checkout --detach FETCH_HEAD >/dev/null; }; then',\n ' rm -rf \"$tmp\"',\n ' echo \"Repository resource fetch failed for $target\" >&2',\n \" exit 1\",\n \" fi\",\n ' if [ -n \"$subpath\" ]; then',\n ' if [ ! -e \"$tmp/$subpath\" ]; then',\n ' echo \"Repository subpath not found: $subpath\" >&2',\n ' rm -rf \"$tmp\"',\n \" exit 1\",\n \" fi\",\n ' if [ -d \"$tmp/$subpath\" ]; then',\n ' mkdir -p \"$target\"',\n ' cp -a \"$tmp/$subpath/.\" \"$target/\"',\n \" else\",\n ' rmdir \"$target\" 2>/dev/null || true',\n ' cp -a \"$tmp/$subpath\" \"$target\"',\n \" fi\",\n ' rm -rf \"$tmp\"',\n \" else\",\n ' rmdir \"$target\" 2>/dev/null || true',\n // Two concurrent turn holders can race this install: without the existence\n // re-check the loser's un-flagged `mv` would nest its tmp clone INSIDE the\n // winner's tree as <name>.tmp.<pid>. If the winner produced a valid work tree,\n // accept it; a non-empty non-repo survivor here is a mount point the manifest\n // re-filled — install into it by content copy instead of rename.\n ' if [ -e \"$target\" ]; then',\n ' if git -C \"$target\" rev-parse --is-inside-work-tree >/dev/null 2>&1; then',\n ' rm -rf \"$tmp\"',\n ' echo \"Repository resource already present at $target\"',\n \" return 0\",\n \" fi\",\n ' cp -a \"$tmp/.\" \"$target/\"',\n ' rm -rf \"$tmp\"',\n \" else\",\n ' mv \"$tmp\" \"$target\"',\n \" fi\",\n ' git -C \"$target\" rev-parse --is-inside-work-tree >/dev/null',\n \" fi\",\n ' if [ ! -e \"$target\" ]; then',\n ' echo \"Repository resource was not materialized at $target\" >&2',\n \" exit 1\",\n \" fi\",\n ' echo \"Repository resource ready at $target\"',\n \"}\",\n ];\n for (const resource of resources) {\n const mountPath = resourceMountPath(resource);\n commands.push(\n [\n \"clone_repository\",\n shellQuote(posixPath.join(\"/workspace\", mountPath)),\n shellQuote(resource.uri),\n shellQuote(resource.ref),\n shellQuote(resource.subpath ? normalizeRepositorySubpath(resource.subpath) : \"\"),\n ].join(\" \"),\n );\n }\n return commands.join(\"\\n\");\n}\n\nexport function toolspaceTokenSeedCommand(\n options: { tokenFile?: string; legacyTokenFile?: string } = {},\n): string {\n return [\n \"set +x\",\n \"set -eu\",\n 'export HOME=\"${HOME:-/workspace}\"',\n 'if [ -n \"${OPENGENI_TOOLSPACE_TOKEN_SEED:-}\" ]; then',\n ' seed_umask=\"$(umask)\"',\n \" umask 077\",\n options.tokenFile\n ? ` token_file=${shellToolspacePath(options.tokenFile)}`\n : ' token_file=\"${OPENGENI_TOOLSPACE_TOKEN_FILE:-$HOME/.opengeni/toolspace-token}\"',\n options.legacyTokenFile\n ? ` legacy_token_file=${shellToolspacePath(options.legacyTokenFile)}`\n : ' legacy_token_file=\"\"',\n ' mkdir -p \"$(dirname \"$token_file\")\"',\n ' printf \\'%s\\' \"$OPENGENI_TOOLSPACE_TOKEN_SEED\" > \"$token_file.tmp.$$\"',\n ' mv -f \"$token_file.tmp.$$\" \"$token_file\"',\n ' if [ -n \"$legacy_token_file\" ] && [ \"$legacy_token_file\" != \"$token_file\" ]; then',\n ' rm -f -- \"$legacy_token_file\"',\n \" fi\",\n ' umask \"$seed_umask\"',\n \"fi\",\n ].join(\"\\n\");\n}\n\nexport async function runToolspaceTokenSeedHook(\n session: SandboxSessionLike,\n context: SandboxLifecycleHookContext,\n): Promise<void> {\n if (!context.toolspaceTokenSeed) {\n return;\n }\n const command = `set +x\\nexport OPENGENI_TOOLSPACE_TOKEN_SEED=${shellQuote(context.toolspaceTokenSeed)}\\n${toolspaceTokenSeedCommand(\n {\n ...(context.toolspaceTokenFile ? { tokenFile: context.toolspaceTokenFile } : {}),\n ...(context.toolspaceTokenFile && context.environment.OPENGENI_TOOLSPACE_TOKEN_FILE\n ? { legacyTokenFile: context.environment.OPENGENI_TOOLSPACE_TOKEN_FILE }\n : {}),\n },\n )}`;\n const result = await runSandboxLifecycleCommand(\n session,\n {\n cmd: command,\n workdir: \"/workspace\",\n ...(context.runAs ? { runAs: context.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 4_000,\n },\n context.commandRunner,\n );\n assertSandboxCommandSucceeded(result, \"Toolspace token seed hook\");\n}\n\nexport async function refreshToolspaceTokenFile(\n session: ToolspaceTokenWriterSession,\n token: string,\n options: {\n runAs?: string;\n commandRunner?: SandboxLifecycleCommandRunner;\n tokenFile?: string;\n legacyTokenFile?: string;\n } = {},\n): Promise<void> {\n const command = `set +x\\nexport OPENGENI_TOOLSPACE_TOKEN_SEED=${shellQuote(token)}\\n${toolspaceTokenSeedCommand(\n {\n ...(options.tokenFile ? { tokenFile: options.tokenFile } : {}),\n ...(options.legacyTokenFile ? { legacyTokenFile: options.legacyTokenFile } : {}),\n },\n )}`;\n const result = await runSandboxLifecycleCommand(\n session,\n {\n cmd: command,\n workdir: \"/workspace\",\n ...(options.runAs ? { runAs: options.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 4_000,\n },\n options.commandRunner,\n );\n assertSandboxCommandSucceeded(result, \"Toolspace token refresh\");\n}\n\n// Bounds the setup output tail carried on a rig.setup failure event/error so a\n// runaway script can't bloat the session's event stream or the turn error.\nconst RIG_SETUP_OUTPUT_TAIL_LIMIT = 4_000;\n\n// A distinctive sentinel the guard prints when the idempotence marker already\n// exists, so the runtime can tell a SKIP from an actual run without a second\n// exec round-trip.\nconst RIG_SETUP_SKIPPED_SENTINEL = \"__OPENGENI_RIG_SETUP_SKIPPED__\";\n\n/**\n * The rig-setup command (M3). One idempotent bash program:\n * 1. `mkdir -p /var/opengeni` and, if the per-version marker already exists,\n * print the SKIP sentinel and exit 0 (a warm box re-running the hook).\n * 2. otherwise atomically claim a per-version lock directory. A loser waits\n * for the winner's marker, then skips; if the winner fails and releases the\n * lock, the loser retries the claim.\n * 3. the winner writes the rig's setup script to a temp file and runs it under\n * coreutils `timeout` (NOT `bash -e` — the script opts into `set -e`\n * itself if it wants), then captures the exit code and `touch`es the marker\n * ONLY on success (exit 0) so a failed/timed-out setup re-runs next turn.\n * The heredoc delimiter is quoted, so the script content is executed verbatim\n * with no host-side expansion.\n */\nexport function rigSetupScriptCommand(\n script: string,\n versionId: string,\n timeoutMs = 600_000,\n markerRoot = \"/var/opengeni\",\n): string {\n const timeoutSecs = Math.max(1, Math.ceil(timeoutMs / 1000));\n const lockWaitSecs = timeoutSecs + 6;\n const marker = `${markerRoot.replace(/\\/+$/, \"\")}/rig-setup-${versionId}.done`;\n return [\n \"set -u\",\n `mkdir -p ${shellQuote(markerRoot)}`,\n `__OG_RIG_MARKER=${shellQuote(marker)}`,\n '__OG_RIG_LOCK=\"$__OG_RIG_MARKER.lock\"',\n `__OG_RIG_TIMEOUT_SECS=${timeoutSecs}`,\n `__OG_RIG_LOCK_WAIT_SECS=${lockWaitSecs}`,\n `if [ -f \"$__OG_RIG_MARKER\" ]; then printf '%s\\\\n' ${shellQuote(RIG_SETUP_SKIPPED_SENTINEL)}; exit 0; fi`,\n \"while :; do\",\n ' if mkdir \"$__OG_RIG_LOCK\" 2>/dev/null; then',\n \" trap 'rm -rf \\\"$__OG_RIG_LOCK\\\"' EXIT\",\n ` if [ -f \"$__OG_RIG_MARKER\" ]; then printf '%s\\\\n' ${shellQuote(RIG_SETUP_SKIPPED_SENTINEL)}; exit 0; fi`,\n '__OG_RIG_SCRIPT=\"$(mktemp)\"',\n \"cat > \\\"$__OG_RIG_SCRIPT\\\" <<'__OPENGENI_RIG_SETUP_SCRIPT_EOF__'\",\n script,\n \"__OPENGENI_RIG_SETUP_SCRIPT_EOF__\",\n ' timeout -k 5s \"${__OG_RIG_TIMEOUT_SECS}s\" bash \"$__OG_RIG_SCRIPT\"',\n \"__OG_RIG_RC=$?\",\n ' rm -f \"$__OG_RIG_SCRIPT\"',\n ' if [ \"$__OG_RIG_RC\" -eq 0 ]; then touch \"$__OG_RIG_MARKER\"; fi',\n ' exit \"$__OG_RIG_RC\"',\n \" fi\",\n \" __OG_RIG_WAITED=0\",\n ' while [ \"$__OG_RIG_WAITED\" -lt \"$__OG_RIG_LOCK_WAIT_SECS\" ]; do',\n ` if [ -f \"$__OG_RIG_MARKER\" ]; then printf '%s\\\\n' ${shellQuote(RIG_SETUP_SKIPPED_SENTINEL)}; exit 0; fi`,\n ' if [ ! -d \"$__OG_RIG_LOCK\" ]; then break; fi',\n \" sleep 1\",\n \" __OG_RIG_WAITED=$((__OG_RIG_WAITED + 1))\",\n \" done\",\n ` if [ -f \"$__OG_RIG_MARKER\" ]; then printf '%s\\\\n' ${shellQuote(RIG_SETUP_SKIPPED_SENTINEL)}; exit 0; fi`,\n ' if [ ! -d \"$__OG_RIG_LOCK\" ]; then continue; fi',\n ' rmdir \"$__OG_RIG_LOCK\" 2>/dev/null || true',\n \"done\",\n ].join(\"\\n\");\n}\n\n/**\n * The rig-setup beforeAgentStart hook (M3). Runs the frozen rig version's setup\n * script exactly once per box (marker-guarded), under the RIG's own timeout\n * (context.rigSetup.timeoutMs, NOT the 120s lifecycle default). Emits\n * rig.setup.started, then one terminal event:\n * - rig.setup.skipped — marker already present,\n * - rig.setup.completed — script ran and exited 0,\n * - rig.setup.failed — nonzero exit / timeout,\n * and on failure THROWS (fail the turn closed) with a message naming the\n * rig/version and a bounded tail of the setup output.\n */\nexport async function runRigSetupHook(\n session: SandboxSessionLike,\n context: SandboxLifecycleHookContext = { environment: {} },\n): Promise<void> {\n const rigSetup = context.rigSetup;\n if (!rigSetup) {\n return;\n }\n const payload = {\n rigId: rigSetup.rigId,\n versionId: rigSetup.versionId,\n rigName: rigSetup.rigName,\n };\n await context.onRuntimeEvent?.({ type: \"rig.setup.started\", payload });\n const command = rigSetupScriptCommand(rigSetup.script, rigSetup.versionId, rigSetup.timeoutMs);\n const execArgs = {\n cmd: command,\n workdir: \"/workspace\",\n ...(context.runAs ? { runAs: context.runAs } : {}),\n // The in-box coreutils timeout is the hard deadline; the SDK yield waits a\n // little longer so it observes timeout's non-zero exit instead of a live\n // still-running process.\n yieldTimeMs: rigSetup.timeoutMs + 7_000,\n maxOutputTokens: 20_000,\n };\n let result: unknown;\n try {\n result = await runSandboxLifecycleCommand(session, execArgs, context.commandRunner);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n await context.onRuntimeEvent?.({\n type: \"rig.setup.failed\",\n payload: {\n ...payload,\n error: message.slice(-RIG_SETUP_OUTPUT_TAIL_LIMIT),\n },\n });\n throw new Error(\n `Rig setup failed for rig \"${rigSetup.rigName}\" (version ${rigSetup.versionId}): ${message}`,\n { cause: error },\n );\n }\n const output = sandboxCommandOutput(result);\n // Marker present → the guard skipped the script. Distinct terminal signal.\n if (output.includes(RIG_SETUP_SKIPPED_SENTINEL)) {\n await context.onRuntimeEvent?.({ type: \"rig.setup.skipped\", payload });\n return;\n }\n // Ran → classify. A \"still running\" result means the script outlived the rig\n // timeout; any nonzero/absent exit code is a setup failure. Both fail closed.\n const stillRunning = sandboxCommandStillRunning(result);\n const exitCode = sandboxCommandExitCode(result);\n if (stillRunning || exitCode === null || exitCode !== 0) {\n const tail =\n output.length > RIG_SETUP_OUTPUT_TAIL_LIMIT\n ? output.slice(-RIG_SETUP_OUTPUT_TAIL_LIMIT)\n : output;\n const reason = stillRunning\n ? `did not finish within the rig setup timeout (${rigSetup.timeoutMs}ms)`\n : exitCode === null\n ? \"did not report an exit code\"\n : `exited with code ${exitCode}`;\n const failure = new Error(\n `Rig setup failed for rig \"${rigSetup.rigName}\" (version ${rigSetup.versionId}): the setup script ${reason}${tail ? `:\\n${tail}` : \"\"}`,\n );\n await context.onRuntimeEvent?.({\n type: \"rig.setup.failed\",\n payload: {\n ...payload,\n error: failure.message.slice(-RIG_SETUP_OUTPUT_TAIL_LIMIT),\n },\n });\n throw failure;\n }\n await context.onRuntimeEvent?.({\n type: \"rig.setup.completed\",\n payload: { ...payload, skipped: false },\n });\n}\n\nexport async function runRepositoryCloneHook(\n session: SandboxSessionLike,\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n context: SandboxLifecycleHookContext = { environment: {} },\n): Promise<void> {\n const payload = {\n name: \"repository-clone\",\n repositoryCount: resources.length,\n };\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.started\",\n payload,\n });\n try {\n // TOKEN-BROKER (B1): thread run-scoped provider tokens PER-EXEC, never on\n // the manifest. The SDK's ExecCommandArgs has no `environment` field (exec\n // inherits the box's manifest env), so we can't hand seeds through an exec\n // option — and we MUST NOT put them on the manifest (validateNoEnvironmentDelta\n // would see rotating values). We inline ephemeral `export` prefixes on THIS\n // exec's command text only. The clone command writes them to provider token\n // FILES before fetch/CLI use. Absent seeds -> no prefix; helper wrappers still\n // install and passthrough cleanly.\n const gitTokenSeeds = {\n ...(context.gitTokenSeeds ?? {}),\n ...(context.gitTokenSeed ? { github: context.gitTokenSeed } : {}),\n } satisfies GitTokenSeeds;\n const gitCredentialBindings = context.gitCredentialBindings ?? [];\n const seedPrefix = [\n gitTokenSeedExportPrefix(gitTokenSeeds),\n gitCredentialBindingSeedExportPrefix(gitCredentialBindings),\n ]\n .filter(Boolean)\n .join(\"\\n\");\n const cloneCommand = repositoryCloneCommand(resources, gitCredentialBindings);\n const command = seedPrefix ? `set +x\\n${seedPrefix}\\n${cloneCommand}` : cloneCommand;\n const result = await runSandboxLifecycleCommand(\n session,\n {\n cmd: command,\n workdir: \"/workspace\",\n ...(context.runAs ? { runAs: context.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 20_000,\n },\n context.commandRunner,\n );\n assertSandboxCommandSucceeded(result, \"Repository clone hook\");\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.completed\",\n payload,\n });\n } catch (error) {\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.failed\",\n payload: {\n ...payload,\n error: error instanceof Error ? error.message : String(error),\n },\n });\n throw error;\n }\n}\n\nexport function azureCliLoginCommand(): string {\n return [\n \"set +x\",\n 'export HOME=\"${HOME:-/workspace}\"',\n 'mkdir -p \"$HOME/.azure\"',\n 'CLIENT_ID=\"${AZURE_CLIENT_ID:-${ARM_CLIENT_ID:-}}\"',\n 'CLIENT_SECRET=\"${AZURE_CLIENT_SECRET:-${ARM_CLIENT_SECRET:-}}\"',\n 'TENANT_ID=\"${AZURE_TENANT_ID:-${ARM_TENANT_ID:-}}\"',\n 'SUBSCRIPTION_ID=\"${AZURE_SUBSCRIPTION_ID:-${ARM_SUBSCRIPTION_ID:-}}\"',\n 'if [ -n \"$CLIENT_ID\" ] && [ -n \"$CLIENT_SECRET\" ] && [ -n \"$TENANT_ID\" ]; then',\n ' command -v az >/dev/null 2>&1 || { echo \"Azure CLI is not installed in the sandbox\" >&2; exit 127; }',\n ' az account show --only-show-errors >/dev/null 2>&1 || az login --service-principal --username \"$CLIENT_ID\" --password \"$CLIENT_SECRET\" --tenant \"$TENANT_ID\" --allow-no-subscriptions --only-show-errors --output none',\n // if/fi, NOT `[ -n ] && az`: this line ends the credentialed if-body, so with a\n // no-subscription SP (an explicitly supported config — the login above passes\n // --allow-no-subscriptions) the bare `[ -n ]` would exit the whole script 1 and\n // fail the turn.\n ' if [ -n \"$SUBSCRIPTION_ID\" ]; then az account set --subscription \"$SUBSCRIPTION_ID\" --only-show-errors; fi',\n \"fi\",\n ].join(\"\\n\");\n}\n\nexport function sandboxCommandExitCode(result: unknown): number | null {\n if (typeof result === \"string\") {\n const match = result.match(/Process exited with code (-?\\d+)/);\n return match ? Number(match[1]) : null;\n }\n if (!result || typeof result !== \"object\") {\n return null;\n }\n const candidate = result as {\n exitCode?: unknown;\n exit_code?: unknown;\n code?: unknown;\n status?: unknown;\n };\n for (const value of [candidate.exitCode, candidate.exit_code, candidate.code, candidate.status]) {\n if (typeof value === \"number\") {\n return value;\n }\n }\n return null;\n}\n\nexport function sandboxCommandOutput(result: unknown): string {\n if (typeof result === \"string\") {\n const outputIndex = result.indexOf(\"Output:\");\n return outputIndex >= 0 ? result.slice(outputIndex + \"Output:\".length).trim() : result.trim();\n }\n if (!result || typeof result !== \"object\") {\n return \"\";\n }\n const candidate = result as {\n output?: unknown;\n stdout?: unknown;\n stderr?: unknown;\n };\n return [candidate.output, candidate.stderr, candidate.stdout]\n .filter((value): value is string => typeof value === \"string\" && value.length > 0)\n .join(\"\\n\");\n}\n\nfunction assertSandboxCommandSucceeded(result: unknown, operation: string): void {\n const output = sandboxCommandOutput(result);\n if (sandboxCommandStillRunning(result)) {\n throw new Error(\n `${operation} did not finish before the lifecycle command timeout${output ? `:\\n${output}` : \"\"}`,\n );\n }\n const exitCode = sandboxCommandExitCode(result);\n if (exitCode !== null && exitCode !== 0) {\n throw new Error(\n `${operation} failed with exit code ${exitCode}${output ? `:\\n${output}` : \"\"}`,\n );\n }\n if (exitCode === null) {\n throw new Error(output || `${operation} did not return a command exit code`);\n }\n}\n\nexport function sandboxCommandStillRunning(result: unknown): boolean {\n if (typeof result === \"string\") {\n return /Process running with session ID \\d+/u.test(result);\n }\n if (!result || typeof result !== \"object\") {\n return false;\n }\n const candidate = result as { sessionId?: unknown; session_id?: unknown };\n return typeof candidate.sessionId === \"number\" || typeof candidate.session_id === \"number\";\n}\n\nfunction hasAzureServicePrincipal(environment: Record<string, string>): boolean {\n const clientId = environment.AZURE_CLIENT_ID || environment.ARM_CLIENT_ID;\n const clientSecret = environment.AZURE_CLIENT_SECRET || environment.ARM_CLIENT_SECRET;\n const tenantId = environment.AZURE_TENANT_ID || environment.ARM_TENANT_ID;\n return Boolean(clientId && clientSecret && tenantId);\n}\n\nexport async function runAzureCliLoginHook(\n session: SandboxSessionLike,\n context: SandboxLifecycleHookContext = { environment: {} },\n): Promise<void> {\n const payload = {\n name: \"azure-cli-login\",\n command: \"az login --service-principal\",\n };\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.started\",\n payload,\n });\n try {\n const result = await runSandboxLifecycleCommand(\n session,\n {\n cmd: azureCliLoginCommand(),\n workdir: \"/workspace\",\n ...(context.runAs ? { runAs: context.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 20_000,\n },\n context.commandRunner,\n );\n assertSandboxCommandSucceeded(result, \"Azure CLI login hook\");\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.completed\",\n payload,\n });\n } catch (error) {\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.failed\",\n payload: {\n ...payload,\n error: error instanceof Error ? error.message : String(error),\n },\n });\n throw error;\n }\n}\n\nfunction azureDeploymentBaseUrl(settings: Settings): string {\n const endpoint = settings.azureOpenaiEndpoint?.replace(/\\/+$/, \"\");\n if (!endpoint || !settings.azureOpenaiDeployment) {\n throw new Error(\"Azure OpenAI endpoint/deployment settings are incomplete\");\n }\n return `${endpoint}/openai/deployments/${settings.azureOpenaiDeployment}`;\n}\n\nexport function azureOpenAIDefaultQuery(\n settings: Pick<Settings, \"azureOpenaiApiVersion\">,\n baseURL: string,\n): Record<string, string> | undefined {\n if (!settings.azureOpenaiApiVersion) return undefined;\n const normalized = baseURL.replace(/\\/+$/, \"\").toLowerCase();\n if (normalized.endsWith(\"/openai/v1\")) {\n return undefined;\n }\n return { \"api-version\": settings.azureOpenaiApiVersion };\n}\n\n// Since @openai/agents 0.11.0 local sandbox sources (including the lazy\n// bundled-skills source) must stay within the SDK process working directory:\n// reads outside it require manifest.extraPathGrants, and remote sandbox\n// clients such as Modal reject manifests that carry extra path grants. The\n// packaged skills live inside the runtime package — outside the worker's cwd\n// in production — so stage a copy under the working directory once per\n// process instead of granting the packaged path.\nlet stagedBundledSkillsDir: string | null = null;\n\nfunction bundledSkillsDir(): string {\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const packaged =\n [\n join(moduleDir, \"bundled_hashicorp_terraform_skills\"),\n join(moduleDir, \"..\", \"src\", \"bundled_hashicorp_terraform_skills\"),\n ].find((candidate) => existsSync(candidate)) ??\n join(moduleDir, \"bundled_hashicorp_terraform_skills\");\n if (isPathWithin(process.cwd(), packaged)) {\n return packaged;\n }\n if (!stagedBundledSkillsDir) {\n stagedBundledSkillsDir = stageBundledSkills(\n packaged,\n join(process.cwd(), \".opengeni\", \"bundled_hashicorp_terraform_skills\"),\n );\n }\n return stagedBundledSkillsDir;\n}\n\nfunction stageBundledSkills(packaged: string, target: string): string {\n const tmp = `${target}.tmp-${process.pid}`;\n rmSync(tmp, { recursive: true, force: true });\n mkdirSync(dirname(tmp), { recursive: true });\n cpSync(packaged, tmp, { recursive: true });\n rmSync(target, { recursive: true, force: true });\n try {\n renameSync(tmp, target);\n } catch (error) {\n // Another process staged the same content between our rm and rename.\n rmSync(tmp, { recursive: true, force: true });\n if (!existsSync(target)) {\n throw error;\n }\n }\n return target;\n}\n\nfunction isPathWithin(root: string, candidate: string): boolean {\n const relativePath = relative(root, candidate);\n return relativePath === \"\" || (!relativePath.startsWith(\"..\") && !isAbsolute(relativePath));\n}\n\n/**\n * The skill source fed to the SDK Skills capability. Without pack or curated\n * skills this is the plain bundled local-dir source, byte-for-byte the\n * pre-pack behavior. With either selected source it becomes a single\n * in-memory dir source combining bundled skill directories (as local_dir\n * entries the SDK materializes lazily) with selected in-memory skill\n * directories — one skill index, one `## Skills` instruction section, lazy\n * `load_skill` for all of them. A pack skill shadows a bundled or curated\n * skill with the same directory name, case-insensitively.\n */\nexport function lazySkillSourceWithPackSkills(\n packSkills: PackSkill[],\n skillLibrarySkills: PackSkill[] = [],\n): LocalDirLazySkillSource {\n const bundledDir = bundledSkillsDir();\n const bundled = localDirLazySkillSource({ src: bundledDir });\n if (packSkills.length === 0 && skillLibrarySkills.length === 0) {\n return bundled;\n }\n const children: Record<string, Entry> = {};\n for (const name of bundledSkillDirNames(bundledDir)) {\n children[name] = localDir({ src: join(bundledDir, name) });\n }\n const libraryIndex: SkillIndexEntry[] = [];\n const libraryNameKeys = new Set<string>();\n for (const skill of skillLibrarySkills) {\n assertSafePackSkillName(skill.name);\n const key = skill.name.toLowerCase();\n if (libraryNameKeys.has(key)) {\n throw new Error(`Duplicate curated skill name: ${skill.name}`);\n }\n libraryNameKeys.add(key);\n removeSkillChildByNameKey(children, key);\n children[skill.name] = packSkillDirEntry(skill);\n libraryIndex.push({\n name: skill.name,\n description: packSkillDescription(skill),\n path: skill.name,\n });\n }\n const packIndex: SkillIndexEntry[] = [];\n const packNameKeys = new Set<string>();\n for (const skill of packSkills) {\n assertSafePackSkillName(skill.name);\n if (packNameKeys.has(skill.name.toLowerCase())) {\n throw new Error(`Duplicate pack skill name: ${skill.name}`);\n }\n packNameKeys.add(skill.name.toLowerCase());\n removeSkillChildByNameKey(children, skill.name.toLowerCase());\n children[skill.name] = packSkillDirEntry(skill);\n packIndex.push({\n name: skill.name,\n description: packSkillDescription(skill),\n path: skill.name,\n });\n }\n return {\n source: dir({ children }),\n getIndex: (manifest, skillsPath) => [\n ...(bundled.getIndex?.(manifest, skillsPath) ?? []).filter(\n (entry) =>\n !packNameKeys.has((entry.path ?? entry.name).toLowerCase()) &&\n !libraryNameKeys.has((entry.path ?? entry.name).toLowerCase()),\n ),\n ...libraryIndex.filter(\n (entry) => !packNameKeys.has((entry.path ?? entry.name).toLowerCase()),\n ),\n ...packIndex,\n ],\n };\n}\n\nfunction effectiveSkillSelections(\n librarySelections: readonly EffectiveSkillSelection[],\n librarySkills: readonly PackSkill[],\n packSkills: readonly PackSkill[],\n sessionSkills: readonly PackSkill[],\n): readonly EffectiveSkillSelection[] {\n const defaultSelections = bundledSkillDirNames(bundledSkillsDir()).map((name) => ({\n id: `bundled:${name}`,\n name,\n source: \"bundled\" as const,\n version: null,\n contentSha256: null,\n reason: \"deployment default skill bundle\",\n }));\n const libraryNameKeys = new Set(librarySkills.map((skill) => skill.name.toLowerCase()));\n const packNameKeys = new Set(packSkills.map((skill) => skill.name.toLowerCase()));\n const effectiveSessionSkills = sessionSkillsForMaterialization(\n packSkills,\n librarySkills,\n sessionSkills,\n );\n const sessionNameKeys = new Set(effectiveSessionSkills.map((skill) => skill.name.toLowerCase()));\n const selected = librarySelections.filter((selection) =>\n libraryNameKeys.has(selection.name.toLowerCase()),\n );\n return [\n ...defaultSelections.filter(\n (selection) =>\n !libraryNameKeys.has(selection.name.toLowerCase()) &&\n !packNameKeys.has(selection.name.toLowerCase()) &&\n !sessionNameKeys.has(selection.name.toLowerCase()),\n ),\n ...selected.filter(\n (selection) =>\n !packNameKeys.has(selection.name.toLowerCase()) &&\n !sessionNameKeys.has(selection.name.toLowerCase()),\n ),\n ...packSkills.map((skill) => ({\n id: `pack:${skill.name}`,\n name: skill.name,\n source: \"pack\" as const,\n version: null,\n contentSha256: null,\n reason: \"enabled capability pack\",\n })),\n ...effectiveSessionSkills.map((skill) => ({\n id: `session:${skill.name}`,\n name: skill.name,\n source: \"session\" as const,\n version: null,\n contentSha256: null,\n reason: \"attached to session\",\n })),\n ];\n}\n\nfunction sessionSkillsForMaterialization(\n packSkills: readonly PackSkill[],\n librarySkills: readonly PackSkill[],\n sessionSkills: readonly PackSkill[],\n): PackSkill[] {\n const configured = new Map<string, PackSkill>();\n for (const skill of [...librarySkills, ...packSkills]) {\n configured.set(skill.name.toLowerCase(), skill);\n }\n const bundledNames = new Set(\n bundledSkillDirNames(bundledSkillsDir()).map((name) => name.toLowerCase()),\n );\n const selected = new Map<string, PackSkill>();\n for (const skill of sessionSkills) {\n assertSafePackSkillName(skill.name);\n const key = skill.name.toLowerCase();\n if (bundledNames.has(key)) {\n throw new Error(`Session skill \"${skill.name}\" conflicts with a bundled skill`);\n }\n const existing = selected.get(key) ?? configured.get(key);\n if (existing) {\n if (skillFingerprint(existing) !== skillFingerprint(skill)) {\n throw new Error(`Conflicting skill definitions for \"${skill.name}\"`);\n }\n continue;\n }\n selected.set(key, skill);\n }\n return [...selected.values()];\n}\n\nfunction skillFingerprint(skill: PackSkill): string {\n return JSON.stringify(\n [...skill.files]\n .sort((left, right) => left.path.localeCompare(right.path))\n .map(({ path, content }) => ({ path, content })),\n );\n}\n\nfunction removeSkillChildByNameKey(children: Record<string, Entry>, nameKey: string): void {\n for (const name of Object.keys(children)) {\n if (name.toLowerCase() === nameKey) {\n delete children[name];\n }\n }\n}\n\nfunction bundledSkillDirNames(root: string): string[] {\n return readdirSync(root, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && existsSync(join(root, entry.name, \"SKILL.md\")))\n .map((entry) => entry.name)\n .sort();\n}\n\ntype PackSkillDirNode = {\n dirs: Map<string, PackSkillDirNode>;\n files: Map<string, string>;\n};\n\nfunction packSkillDirEntry(skill: PackSkill): Dir {\n const root: PackSkillDirNode = { dirs: new Map(), files: new Map() };\n for (const skillFile of skill.files) {\n const segments = packSkillPathSegments(skill.name, skillFile.path);\n let node = root;\n for (const segment of segments.slice(0, -1)) {\n if (node.files.has(segment)) {\n throw new Error(`Pack skill ${skill.name} uses ${segment} as both a file and a directory`);\n }\n let next = node.dirs.get(segment);\n if (!next) {\n next = { dirs: new Map(), files: new Map() };\n node.dirs.set(segment, next);\n }\n node = next;\n }\n const filename = segments[segments.length - 1]!;\n if (node.dirs.has(filename) || node.files.has(filename)) {\n throw new Error(`Duplicate pack skill file path in ${skill.name}: ${skillFile.path}`);\n }\n node.files.set(filename, skillFile.content);\n }\n if (!root.files.has(\"SKILL.md\")) {\n throw new Error(`Pack skill ${skill.name} is missing a top-level SKILL.md file`);\n }\n return packSkillDirFromNode(root);\n}\n\nfunction packSkillDirFromNode(node: PackSkillDirNode): Dir {\n const children: Record<string, Entry> = {};\n for (const [name, child] of node.dirs) {\n children[name] = packSkillDirFromNode(child);\n }\n for (const [name, content] of node.files) {\n children[name] = file({ content });\n }\n return dir({ children });\n}\n\nfunction assertSafePackSkillName(name: string): void {\n if (packSkillPathSegments(name, name).length !== 1) {\n throw new Error(`Invalid pack skill name: ${name}`);\n }\n}\n\nfunction packSkillPathSegments(skillName: string, path: string): string[] {\n const segments = path.split(\"/\");\n if (\n path.startsWith(\"/\") ||\n path.includes(\"\\\\\") ||\n segments.some((segment) => segment.length === 0 || segment === \".\" || segment === \"..\")\n ) {\n throw new Error(`Invalid pack skill file path for ${skillName}: ${path}`);\n }\n return segments;\n}\n\nfunction packSkillDescription(skill: PackSkill): string {\n const explicit = skill.description?.trim();\n if (explicit) {\n return explicit;\n }\n const markdown = skill.files.find((skillFile) => skillFile.path === \"SKILL.md\")?.content ?? \"\";\n return skillFrontmatterDescription(markdown) ?? \"No description provided.\";\n}\n\nfunction skillFrontmatterDescription(markdown: string): string | null {\n const lines = markdown.split(/\\r?\\n/);\n if (lines[0]?.trim() !== \"---\") {\n return null;\n }\n const end = lines.findIndex((line, index) => index > 0 && line.trim() === \"---\");\n if (end === -1) {\n return null;\n }\n const collected: string[] = [];\n let inDescription = false;\n for (const line of lines.slice(1, end)) {\n const match = line.match(/^description:\\s*(.*)$/);\n if (match) {\n const inline = match[1]!.trim();\n if (inline && inline !== \">-\" && inline !== \">\" && inline !== \"|\" && inline !== \"|-\") {\n return unquoteFrontmatterValue(inline);\n }\n inDescription = true;\n continue;\n }\n if (inDescription) {\n if (/^\\s+\\S/.test(line)) {\n collected.push(line.trim());\n continue;\n }\n break;\n }\n }\n const blockValue = collected.join(\" \").trim();\n return blockValue ? blockValue : null;\n}\n\nfunction unquoteFrontmatterValue(value: string): string {\n if (\n value.length >= 2 &&\n value[0] === value[value.length - 1] &&\n (value[0] === '\"' || value[0] === \"'\")\n ) {\n return value.slice(1, -1);\n }\n return value;\n}\n\nfunction isAsyncIterable<T>(source: Iterable<T> | AsyncIterable<T>): source is AsyncIterable<T> {\n return typeof (source as AsyncIterable<T>)[Symbol.asyncIterator] === \"function\";\n}\n\nfunction stableJson(value: unknown): string {\n return JSON.stringify(sortJson(value));\n}\n\nfunction sortJson(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortJson);\n }\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, nested]) => [key, sortJson(nested)]),\n );\n }\n return value;\n}\nfunction interruptionToolName(item: unknown): string {\n const candidate = item as {\n toolName?: unknown;\n name?: unknown;\n rawItem?: { name?: unknown };\n };\n const name = candidate?.toolName ?? candidate?.name ?? candidate?.rawItem?.name;\n return typeof name === \"string\" ? name : \"\";\n}\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"// The legible \"screen capture failed\" error card the history-sanitizer wire seam\n// substitutes for an EMPTY `computer_call_output` image_url (see\n// `rewriteEmptyComputerCallOutputImageUrls`). The hosted `computer_use_preview`\n// protocol has only an IMAGE channel back to the model, so a capture failure has to\n// be a legible IMAGE — otherwise the SDK's empty-output placeholder (a 1×1\n// transparent PNG) reaches the model as a plausible-but-wrong BLANK DESKTOP it then\n// confidently reports (the exact failure mode of the 0.1.3 TCC-denied incident).\n//\n// This is a valid 8-bit RGBA PNG (verified: signature + per-chunk CRC + IDAT inflates\n// to the exact scanline size) rendered from a fixed message, so the provider's image\n// decoder accepts it (an invalid/empty image_url is what 400s the turn). The specific\n// failure REASON (permission denied / null image / timeout / display down) is not in\n// the card — it is logged worker-side by `NativeDesktopComputer.screenshot()`; the\n// card's job is only to stop the model from hallucinating a real blank desktop.\n//\n// Regenerate with: `bun run scripts/gen-screenshot-error-card.mjs`\n// Rendered text:\n// SCREEN CAPTURE FAILED\n// THE DESKTOP COULD NOT BE CAPTURED.\n// THIS IS A PLACEHOLDER, NOT THE REAL SCREEN.\n// DO NOT SAY THE SCREEN IS BLANK.\n// TELL THE USER TO CHECK THE DISPLAY AND GRANT\n// SCREEN RECORDING PERMISSION.\nexport const SCREENSHOT_FAILURE_CARD_IMAGE_URL =\n \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABVMAAAGYCAYAAABPvXKBAAAh90lEQVR42u3dMXLkxhJF0VnEGDQQXLY2CaedtkcLkEJBBaqrXmYe43j6bDZQKGTd+RH89df39x8AAAAAAP7bLxcBAAAAAEBMBQAAAAAQUwEAAAAAxFQAAAAAADEVAAAAAEBMBQAAAAAQUwEAAAAAxFQAAAAAAMRUAAAAAAAxFQAAAABATAUAAAAAEFMBAAAAAMRUAAAAAAAxFQAAAABATAUAAAAAQEwFAAAAABBTAQAAAADEVAAAAAAAMRUAAAAAQEwFAAAAABBTAQAAAADEVAAAAAAAMRUAAAAAgMCY+n7dSyV9bpfvdur7Pvnc1Wsy/eGtuNam7RHp63nade7yrE57fk89R9Pev4ZiAAAQU8VUMVVMFWPEVPuVmCqmiqliKgAAiKliqpgqpooxIpCYKqaKqWKqmAoAAGKqmCqmiqliqpgqpoqpnl8xVUwFAAAxVUwVU8VUMVVMFVPFVM+vmCqmAgCAmBp9uKn4uRUPkUmH1y4x1Xq+S34P1/lu848Xnt95P8/9FVgBAEBMFZ/EVDFV5PPzxFTPr5/n/oqpAAAgpopPYqqYaj2LQGKqmGrdmzfEVAAAEFMdbsRUMdV6FoHEVDHVujdviKkAACCm+lwxVUy1nkUgMVVMFVNdZzEVAADEVIcbMfXg53aJO9azCCSmiqnWvXlDTAUAADHV54qpYqr1LAKJqWKqmCqmiqkAACCmOtyIqWKq9Symus5iqtgmpoqpAAAgpjrciBNiqhgjpoqpYqrnV0x1fwEAQEx1yBBTxVQxRkwVU8VU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Tu5uGIZdgAAAABJRU5ErkJggg==\";\n","/**\n * Read-path sanitizer for replayed conversation history (issue: orphaned\n * tool outputs brick a session).\n *\n * Conversation truth is persisted as a flat list of SDK history items in\n * `session_history_items` and replayed verbatim into the model on every turn.\n * The OpenAI Responses API rejects the whole request (HTTP 400) when that list\n * violates its tool-call pairing rules — most destructively:\n *\n * `400 No tool call found for function call output with call_id <X>`\n *\n * when a `function_call_result` (a.k.a. function_call_output) has no matching\n * `function_call` earlier in the list. Because the corrupt item is replayed on\n * every subsequent turn, one orphaned output permanently bricks the session\n * across revival — it stays dead until the row is hand-deleted.\n *\n * This module is the reliability net: before history items are sent to the\n * model they pass through `sanitizeHistoryItemsForModel`, which removes any\n * item that would make the request invalid. It mirrors the SDK's own\n * `dropOrphanToolCalls` continuation logic (which only runs over the SDK's\n * in-memory `state.history`, not over rows we reload from the database) so a\n * reloaded history is shaped exactly like a freshly-generated one.\n *\n * It is a pure function over plain JSON item shapes (no SDK import, no I/O) so\n * it is cheap to unit-test exhaustively. It NEVER mutates its input items and\n * NEVER touches the stored rows — only the in-memory copy sent to the model is\n * filtered, keeping the persisted audit trail intact.\n */\n\nimport { SCREENSHOT_FAILURE_CARD_IMAGE_URL } from \"./screenshot-error-card\";\nimport {\n boundModelToolOutputItems,\n DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n} from \"@opengeni/codex\";\n\n/** A history item is any JSON object; we only inspect a few discriminator fields. */\nexport type HistoryItem = Record<string, unknown>;\n\n/**\n * Tool-call item types and the result-item type that settles them. Kept in\n * sync with the SDK's `TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE`; `function_call` is\n * the one observed live, the rest are included so the same pairing logic holds\n * for every tool-call kind the SDK can emit.\n */\nexport const TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE: Record<string, string> = {\n function_call: \"function_call_result\",\n computer_call: \"computer_call_result\",\n shell_call: \"shell_call_output\",\n apply_patch_call: \"apply_patch_call_output\",\n // Progressive connector disclosure (codex tool_search): a replayed\n // `tool_search_call` must be settled by its `tool_search_output` exactly like a\n // function call — an unpaired one 400s the store:false replay. The SDK pairs\n // these OUTSIDE its own TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE (sessionPersistence's\n // hasToolSearchCallId), so we mirror the semantics here; the correlation id can\n // additionally ride providerData (see callIdOf).\n tool_search_call: \"tool_search_output\",\n};\n\nconst RESULT_TYPE_BY_CALL_TYPE = TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE;\nconst RESULT_TYPES = new Set(Object.values(RESULT_TYPE_BY_CALL_TYPE));\n\nfunction itemType(item: unknown): string | undefined {\n if (!item || typeof item !== \"object\") {\n return undefined;\n }\n const type = (item as { type?: unknown }).type;\n return typeof type === \"string\" ? type : undefined;\n}\n\n/**\n * Correlation id for a tool call / result. The SDK's canonical history shape\n * uses camelCase `callId`; the raw Responses wire shape uses snake_case\n * `call_id`. Persisted rows are the SDK shape, but we accept either so a row\n * written by any code path (or hand-repaired) still correlates.\n */\nfunction callIdOf(item: unknown): string | undefined {\n if (!item || typeof item !== \"object\") {\n return undefined;\n }\n const record = item as { callId?: unknown; call_id?: unknown; providerData?: unknown };\n if (typeof record.callId === \"string\" && record.callId.length > 0) {\n return record.callId;\n }\n if (typeof record.call_id === \"string\" && record.call_id.length > 0) {\n return record.call_id;\n }\n // tool_search items may carry their correlation id ONLY in providerData\n // (mirrors the SDK's getToolSearchProviderCallId: providerData.call_id ??\n // providerData.callId ?? call_id ?? callId). Harmless for other item kinds —\n // their ids never live there.\n const provider = record.providerData as\n | { call_id?: unknown; callId?: unknown }\n | null\n | undefined;\n if (provider && typeof provider === \"object\") {\n if (typeof provider.call_id === \"string\" && provider.call_id.length > 0) {\n return provider.call_id;\n }\n if (typeof provider.callId === \"string\" && provider.callId.length > 0) {\n return provider.callId;\n }\n }\n return undefined;\n}\n\n/**\n * Return the normalized local path from a sandbox `view_image` function call.\n * Invalid/partial calls are deliberately ignored: the filter below only\n * removes fully-paired calls whose replacement is known to be valid.\n */\nfunction viewImagePathOf(item: unknown): string | undefined {\n if (!item || typeof item !== \"object\") {\n return undefined;\n }\n const record = item as { type?: unknown; name?: unknown; arguments?: unknown };\n if (\n record.type !== \"function_call\" ||\n record.name !== \"view_image\" ||\n typeof record.arguments !== \"string\"\n ) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(record.arguments) as { path?: unknown };\n return typeof parsed.path === \"string\" && parsed.path.length > 0 ? parsed.path : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Remove superseded `view_image` call/result pairs for the SAME local path,\n * retaining the newest fully-paired observation. A `view_image` result can be\n * hundreds of kilobytes of base64. When a model re-opens the same attachment,\n * replaying every older copy on each subsequent model call grows input\n * quadratically and can trap a turn in context-compaction/requeue recovery.\n *\n * This is state-based rather than count-based: every distinct path is kept,\n * and an older observation is removed only after a newer successful pair for\n * that exact path exists. The reasoning items immediately attached to a\n * removed call are removed with it, preserving Responses API item validity.\n */\nexport function elideSupersededViewImagePairs<T extends HistoryItem>(items: readonly T[]): T[] {\n if (items.length === 0) {\n return [];\n }\n\n const callIndexById = new Map<string, number>();\n const resultIndexById = new Map<string, number>();\n items.forEach((item, index) => {\n const callId = callIdOf(item);\n if (!callId) {\n return;\n }\n if (itemType(item) === \"function_call\") {\n callIndexById.set(callId, index);\n } else if (\n itemType(item) === \"function_call_result\" ||\n itemType(item) === \"function_call_output\"\n ) {\n resultIndexById.set(callId, index);\n }\n });\n\n const pairedByPath = new Map<string, Array<{ callIndex: number; resultIndex: number }>>();\n for (const [callId, callIndex] of callIndexById) {\n const path = viewImagePathOf(items[callIndex]);\n const resultIndex = resultIndexById.get(callId);\n if (!path || resultIndex === undefined || resultIndex <= callIndex) {\n continue;\n }\n const pairs = pairedByPath.get(path) ?? [];\n pairs.push({ callIndex, resultIndex });\n pairedByPath.set(path, pairs);\n }\n\n const dropped = new Set<number>();\n for (const pairs of pairedByPath.values()) {\n if (pairs.length < 2) {\n continue;\n }\n pairs.sort((left, right) => left.callIndex - right.callIndex);\n for (const pair of pairs.slice(0, -1)) {\n dropped.add(pair.callIndex);\n dropped.add(pair.resultIndex);\n for (let index = pair.callIndex - 1; index >= 0; index -= 1) {\n if (itemType(items[index]) !== \"reasoning\") {\n break;\n }\n dropped.add(index);\n }\n }\n }\n\n return dropped.size === 0 ? items.slice() : items.filter((_item, index) => !dropped.has(index));\n}\n\n/**\n * Sanitize a replayed history item list into a sequence the Responses API\n * accepts. Pure: returns a new array of the same item references in order,\n * with invalid items omitted. Valid histories come back byte-identical\n * (same references, same order).\n *\n * Rules, each motivated by a concrete 400 the API raises:\n *\n * 1. Drop every tool-call RESULT whose matching tool CALL does not appear\n * earlier in the list. This is the session-bricking orphan: a\n * `function_call_result` with no preceding `function_call` of the same\n * `call_id`. (\"No tool call found for function call output…\")\n *\n * 2. Drop every tool CALL that has no matching RESULT anywhere after it.\n * The Responses API requires each tool call to be settled by its output\n * before the conversation can continue; a dangling call left in replayed\n * history 400s with \"No tool output found for function call…\". Dropping\n * the dangling call (rather than synthesizing a fake output) is what the\n * SDK itself does for in-memory continuation, so a reloaded history is\n * shaped identically. The matching result, if it later exists, is kept;\n * only genuinely unpaired calls are removed.\n *\n * 3. Drop any `reasoning` item that immediately precedes (across a run of\n * reasoning items) a dropped tool call. The Responses API ties an\n * encrypted reasoning item to the tool call it produced; a reasoning item\n * orphaned by rule 2 trips \"Item 'rs_…' of type 'reasoning' was provided\n * without its required following item\". Mirrors the SDK's\n * `dropReasoningItemsPrecedingDroppedCalls`.\n *\n * A `call_id` is paired only when BOTH a call and a result of the matching\n * types exist with that id, the call appearing before the result. Calls and\n * results that satisfy that survive untouched.\n */\nexport function sanitizeHistoryItemsForModel<T extends HistoryItem>(\n items: readonly T[],\n toolOutputTruncationTokens = DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n): T[] {\n if (items.length === 0) {\n return [];\n }\n\n // Pre-scan: for every (call-type, call_id) record the index of a RESULT that\n // appears strictly after the call. A call is valid only when such a result\n // exists; a result is valid only when its call appears strictly before it.\n // We resolve pairs in order so ordering is enforced both ways (a result that\n // precedes its call is an orphan, and a call whose only result precedes it is\n // dangling).\n const dropped = new Set<number>();\n\n // For each result-type, the call_ids of CALLs we have seen so far that are\n // still waiting to be settled by a following result.\n const openCallIdsByResultType = new Map<string, Set<string>>();\n\n items.forEach((item, index) => {\n const type = itemType(item);\n const callId = callIdOf(item);\n if (!type || !callId) {\n return;\n }\n const callResultType = RESULT_TYPE_BY_CALL_TYPE[type];\n if (callResultType) {\n const open = openCallIdsByResultType.get(callResultType) ?? new Set<string>();\n open.add(callId);\n openCallIdsByResultType.set(callResultType, open);\n return;\n }\n if (RESULT_TYPES.has(type)) {\n const open = openCallIdsByResultType.get(type);\n if (open && open.has(callId)) {\n // Settles a call we have already seen — keep both, close the call.\n open.delete(callId);\n } else {\n // Rule 1: result whose call is absent or appears later — the orphan.\n dropped.add(index);\n }\n }\n });\n\n // Rule 2: any call still open after the full scan has no result after it —\n // a dangling call the API rejects. Drop those calls. We re-walk to find the\n // indices of the still-open call_ids (the last unmatched call per id).\n const stillOpen = new Map<string, Set<string>>();\n for (const [resultType, open] of openCallIdsByResultType) {\n if (open.size > 0) {\n stillOpen.set(resultType, new Set(open));\n }\n }\n if (stillOpen.size > 0) {\n for (let index = items.length - 1; index >= 0; index -= 1) {\n const item = items[index];\n const type = itemType(item);\n const callId = callIdOf(item);\n if (!type || !callId) {\n continue;\n }\n const resultType = RESULT_TYPE_BY_CALL_TYPE[type];\n if (!resultType) {\n continue;\n }\n const open = stillOpen.get(resultType);\n if (open && open.has(callId)) {\n dropped.add(index);\n open.delete(callId);\n }\n }\n }\n\n if (dropped.size > 0) {\n // Rule 3: drop reasoning items stranded by a dropped tool call. A reasoning\n // item is stranded when the next non-reasoning item after it is dropped.\n for (let index = 0; index < items.length; index += 1) {\n if (dropped.has(index) || itemType(items[index]) !== \"reasoning\") {\n continue;\n }\n for (let next = index + 1; next < items.length; next += 1) {\n if (itemType(items[next]) === \"reasoning\") {\n continue;\n }\n if (dropped.has(next)) {\n dropped.add(index);\n }\n break;\n }\n }\n }\n\n const paired =\n dropped.size === 0 ? items.slice() : items.filter((_item, index) => !dropped.has(index));\n return boundModelToolOutputItems(\n paired.map(stripInternalResumeMarker),\n toolOutputTruncationTokens,\n );\n}\n\n/**\n * Internal marker stamping machine-generated resume/continuation messages\n * (turn-resumed notices, goal continuations) so compaction housekeeping can\n * recognize them in STORED history. Lives here (not context-compaction, which\n * imports from this module) so the wire sanitizer below can strip it without\n * an import cycle; context-compaction re-exports it.\n */\nexport const INTERNAL_RESUME_MESSAGE_MARKER = \"opengeni_internal_resume\";\n\n/**\n * Remove the {@link INTERNAL_RESUME_MESSAGE_MARKER} providerData key from a\n * single item before it reaches ANY model wire. Pure + non-mutating; returns\n * the SAME reference when there is nothing to strip (keeping the common path\n * byte-identical, mirroring {@link stripReasoningEncryptedContent}).\n *\n * WHY. The @openai/agents SDK serializes providerData keys verbatim into the\n * request item, and strict Responses backends reject unknown per-item fields —\n * observed in production as `400 Unknown parameter:\n * 'input[N].opengeni_internal_resume'`, which deterministically failed every\n * turn whose replayed history contained a marked resume message (the marker is\n * durable in conversation truth, so retries could never succeed). Detection\n * (isInternalResumeMessage) reads STORED items and also keeps a text-prefix\n * fallback, so stripping at the wire degrades housekeeping gracefully and\n * never the turn.\n */\nexport function stripInternalResumeMarker<T extends HistoryItem>(item: T): T {\n const providerData = (item as Record<string, unknown>).providerData;\n if (\n !providerData ||\n typeof providerData !== \"object\" ||\n !(INTERNAL_RESUME_MESSAGE_MARKER in (providerData as Record<string, unknown>))\n ) {\n return item;\n }\n const { [INTERNAL_RESUME_MESSAGE_MARKER]: _dropped, ...rest } = providerData as Record<\n string,\n unknown\n >;\n const next: Record<string, unknown> = { ...(item as Record<string, unknown>) };\n if (Object.keys(rest).length > 0) {\n next.providerData = rest;\n } else {\n delete next.providerData;\n }\n return next as T;\n}\n\n/**\n * Drop the account/org-bound `reasoning.encrypted_content` blob from a single\n * history item, preserving everything else (the visible chain-of-thought text in\n * `summary`/`content`, and every non-reasoning field). Pure + non-mutating: when\n * there is nothing to strip the SAME reference is returned (so the common,\n * same-account path stays byte-identical); otherwise a shallow clone is returned.\n *\n * WHY. A codex-subscription turn round-trips `reasoning.encrypted_content` — an\n * opaque blob minted by the ChatGPT/Codex backend that is bound to the account\n * (org) that produced it. After a manual switch from codex account A to B, the\n * carried history items still hold A-minted blobs; replaying them into a turn\n * running on B is rejected (400). The blob is purely a chain-of-thought\n * continuity optimization — dropping it costs at most one turn of lost CoT\n * continuity and never any message content.\n *\n * USED FOR `compaction` items only on the history-items read path: a foreign\n * `compaction` summary carries account-bound `encrypted_content` but its summary\n * is real conversation content that must be preserved, so we strip only the blob\n * (we do NOT drop the whole item). Foreign `reasoning` items are instead dropped\n * WHOLESALE by the caller (id + blob), because the Responses backend validates\n * the foreign `rs_…` id and rejects a reasoning item that has a foreign id and no\n * encrypted_content (so blanking the blob alone is not enough — see\n * {@link applyCodexHistoryStrip}).\n *\n * The SDK's Responses converter reads the blob via `providerData.encryptedContent`\n * (camel) or `providerData.encrypted_content` (snake); persisted rows use the\n * snake form, but we delete both casings defensively. We also clear a top-level\n * `encrypted_content` (the `compaction`-item shape) belt-and-braces — that blob\n * is likewise source-bound. Only `reasoning` and `compaction` items are touched;\n * messages, tool calls, and tool outputs pass through untouched by reference.\n */\nexport function stripReasoningEncryptedContent<T extends HistoryItem>(item: T): T {\n const type = itemType(item);\n if (type !== \"reasoning\" && type !== \"compaction\") {\n return item;\n }\n const record = item as Record<string, unknown>;\n const providerData = record.providerData;\n const providerHasBlob =\n !!providerData &&\n typeof providerData === \"object\" &&\n (\"encryptedContent\" in (providerData as Record<string, unknown>) ||\n \"encrypted_content\" in (providerData as Record<string, unknown>));\n const topLevelHasBlob = \"encrypted_content\" in record;\n if (!providerHasBlob && !topLevelHasBlob) {\n // Nothing encrypted to strip — return the same reference (byte-identical).\n return item;\n }\n const clone: Record<string, unknown> = { ...record };\n if (providerHasBlob) {\n const providerClone = { ...(providerData as Record<string, unknown>) };\n delete providerClone.encryptedContent;\n delete providerClone.encrypted_content;\n clone.providerData = providerClone;\n }\n if (topLevelHasBlob) {\n delete clone.encrypted_content;\n }\n return clone as unknown as T;\n}\n\n/**\n * Neutralize the account/org-bound identity of EVERY `reasoning` item embedded\n * in a serialized RunState JSON string, returning the re-serialized string. Pure:\n * a parse failure or a no-op returns the SAME string reference (so an unchanged\n * or non-codex run-state replays byte-for-byte).\n *\n * WHY (HOLE C — approval replay). An approval decision resumes the serialized\n * RunState blob. That blob round-trips `reasoning.encrypted_content` minted by the ChatGPT/Codex\n * backend (bound to the freezing account/org — a foreign account 400s it) AND the\n * foreign `rs_…` reasoning ids the Responses backend validates (rejected once the\n * blob is gone). Unlike `session_history_items`, the blob carries NO per-item\n * producer tag, so foreign-ness cannot be decided per item; the worker instead\n * records the FREEZING codex account on the run-state row and calls this only when\n * the resuming turn's codex account DIFFERS from it. When the accounts differ we\n * conservatively neutralize every reasoning item: delete its provider id and its\n * `encrypted_content` (both casings, in `providerData`). The visible reasoning\n * `content`/`summary` and every message / tool-call / tool-output item are left\n * intact (message and tool content are never account-bound).\n *\n * A reasoning item with no id and no encrypted_content is exactly the shape the\n * production Azure path already sends (see `stripProviderItemIdsFilter`), so it\n * deserializes and replays cleanly. Reasoning items live in several places in the\n * blob — `originalInput` (when an array), each `modelResponses[].output`,\n * `lastModelResponse.output`, and the `generatedItems` wrappers (`reasoning_item`\n * → `rawItem`) — and we scrub all of them. `compaction` items are deliberately\n * left untouched: their `encrypted_content` is a protocol-REQUIRED field whose\n * removal would fail the SDK's run-state schema validation on deserialize.\n */\nexport function stripReasoningIdentityFromSerializedRunState(serialized: string): string {\n let parsed: unknown;\n try {\n parsed = JSON.parse(serialized);\n } catch {\n // Not JSON (e.g. a cleared-state sentinel handled elsewhere): forward as-is.\n return serialized;\n }\n if (!parsed || typeof parsed !== \"object\") {\n return serialized;\n }\n let changed = false;\n const scrubReasoning = (candidate: unknown): void => {\n if (!candidate || typeof candidate !== \"object\") {\n return;\n }\n const record = candidate as Record<string, unknown>;\n if (record.type !== \"reasoning\") {\n return;\n }\n if (\"id\" in record) {\n delete record.id;\n changed = true;\n }\n const providerData = record.providerData;\n if (providerData && typeof providerData === \"object\") {\n const provider = providerData as Record<string, unknown>;\n if (\"encryptedContent\" in provider) {\n delete provider.encryptedContent;\n changed = true;\n }\n if (\"encrypted_content\" in provider) {\n delete provider.encrypted_content;\n changed = true;\n }\n }\n if (\"encrypted_content\" in record) {\n delete record.encrypted_content;\n changed = true;\n }\n };\n const scrubItemArray = (arr: unknown): void => {\n if (Array.isArray(arr)) {\n for (const item of arr) {\n scrubReasoning(item);\n }\n }\n };\n const root = parsed as Record<string, unknown>;\n // 1. originalInput is either a string (no items) or an array of protocol items.\n scrubItemArray(root.originalInput);\n // 2. generatedItems are SDK run-item wrappers; a `reasoning_item` carries the\n // protocol reasoning shape under `rawItem`.\n if (Array.isArray(root.generatedItems)) {\n for (const wrapper of root.generatedItems) {\n if (\n wrapper &&\n typeof wrapper === \"object\" &&\n \"rawItem\" in (wrapper as Record<string, unknown>)\n ) {\n scrubReasoning((wrapper as Record<string, unknown>).rawItem);\n }\n }\n }\n // 3. modelResponses[].output and lastModelResponse.output hold protocol items.\n const scrubResponseOutput = (response: unknown): void => {\n if (response && typeof response === \"object\") {\n scrubItemArray((response as Record<string, unknown>).output);\n }\n };\n if (Array.isArray(root.modelResponses)) {\n for (const response of root.modelResponses) {\n scrubResponseOutput(response);\n }\n }\n scrubResponseOutput(root.lastModelResponse);\n if (!changed) {\n return serialized;\n }\n return JSON.stringify(parsed);\n}\n\n/**\n * Neutralize tool_search items IN PLACE in a serialized RunState blob for a\n * cross-account codex resume — the run-state sibling of\n * `applyCodexHistoryStrip`'s tool_search rule, but COUNT-PRESERVING (HOLE E: the\n * blob path's reconcile watermark counts the blob's history length, so items\n * must never be removed — only mutated, exactly like the reasoning\n * neutralization above).\n *\n * The hazard: on deserialize, the SDK re-runs the registered CLIENT tool_search\n * execute callback per frozen pair (`rehydrateToolSearchRuntimeTools`) and\n * THROWS a UserError when the re-run's runtime-tool keys mismatch the serialized\n * expectation — which is exactly what happens when the RESUMING account's\n * connector pool differs from the FREEZING account's. The SDK skips that\n * rehydration entirely for `execution === 'server'` calls, so flipping the\n * frozen pairs' `execution` to `\"server\"` in place defuses the throw without\n * touching counts, ids, pairing, or content. The flipped shape is wire-safe:\n * LIVE-VERIFIED against /codex/responses — a replayed server-execution pair is\n * accepted (200) and its disclosure still holds. The account-bound `tsc_…` id is\n * separately stripped by the codex transport normalizer (all input item ids).\n *\n * Walks the same blob locations as {@link stripReasoningIdentityFromSerializedRunState}:\n * `originalInput` (array form), `generatedItems` (SDK run-item wrappers — the\n * raw shape under `rawItem`), every `modelResponses[].output`, and\n * `lastModelResponse.output`. Returns the input string unchanged when nothing\n * matched.\n */\nexport function neutralizeToolSearchItemsInSerializedRunState(serialized: string): string {\n let parsed: unknown;\n try {\n parsed = JSON.parse(serialized);\n } catch {\n return serialized;\n }\n if (!parsed || typeof parsed !== \"object\") {\n return serialized;\n }\n let changed = false;\n const neutralize = (candidate: unknown): void => {\n if (!candidate || typeof candidate !== \"object\") {\n return;\n }\n const record = candidate as Record<string, unknown>;\n if (record.type !== \"tool_search_call\" && record.type !== \"tool_search_output\") {\n return;\n }\n if (record.execution !== \"server\") {\n record.execution = \"server\";\n changed = true;\n }\n };\n const neutralizeArray = (arr: unknown): void => {\n if (Array.isArray(arr)) {\n for (const item of arr) {\n neutralize(item);\n }\n }\n };\n const root = parsed as Record<string, unknown>;\n neutralizeArray(root.originalInput);\n if (Array.isArray(root.generatedItems)) {\n for (const wrapper of root.generatedItems) {\n if (\n wrapper &&\n typeof wrapper === \"object\" &&\n \"rawItem\" in (wrapper as Record<string, unknown>)\n ) {\n neutralize((wrapper as Record<string, unknown>).rawItem);\n }\n }\n }\n const neutralizeResponseOutput = (response: unknown): void => {\n if (response && typeof response === \"object\") {\n neutralizeArray((response as Record<string, unknown>).output);\n }\n };\n if (Array.isArray(root.modelResponses)) {\n for (const response of root.modelResponses) {\n neutralizeResponseOutput(response);\n }\n }\n neutralizeResponseOutput(root.lastModelResponse);\n if (!changed) {\n return serialized;\n }\n return JSON.stringify(parsed);\n}\n\n/**\n * Normalize `computer_call` items so each carries EXACTLY ONE of the two\n * mutually-exclusive action fields the provider accepts.\n *\n * The OpenAI Agents SDK 0.11.6 `computer_call` schema (protocol.mjs) carries\n * BOTH the legacy singular `action` and the GA batched `actions`, each\n * `.optional()`, and only requires \"at least one\" (its superRefine errors only\n * when both are absent). The Azure computer-use endpoint is stricter: it\n * requires EXACTLY one and rejects the whole request with\n *\n * `400 Computer call input must include exactly one of `action` or `actions`.`\n *\n * when an emitted `computer_call` carries both (observed live: a screenshot\n * call carrying `action:{type:\"screenshot\"}` AND `actions:[{type:\"screenshot\"}]`).\n *\n * Which singular do we keep? LIVE-PROVEN against the deployed Azure deployment\n * (gpt-5.6-sol-2026-04-24): for gpt-5.6-sol the SDK serializes the GA computer tool as\n * `{type:\"computer\"}` (not the legacy `computer_use_preview`), and that GA tool\n * accepts ONLY the batched plural `actions`. Probing all three shapes:\n * - `action`-only -> 400 \"exactly one of action or actions\" (STILL rejected)\n * - `actions`-only -> passes the action/actions structural validation\n * - both -> 400 \"exactly one …\"\n * The \"exactly one\" wording is misleading: only the `actions`-only form is\n * accepted by the GA tool. So when both are present we KEEP `actions` (the GA\n * batched plural) and DROP `action`. Calls that already carry exactly one field\n * — or the legacy `action`-only form — pass through untouched (this transform's\n * sole job is to resolve the both-present conflict, not to rewrite singulars).\n *\n * Pure and non-mutating: only the conflicting item(s) are cloned; every other\n * item passes through by reference (byte-identical). Unlike\n * {@link sanitizeHistoryItemsForModel} (which only *filters* items), this is a\n * read-path *transform* of a single item's shape.\n */\nexport function normalizeComputerCallActions<T extends HistoryItem>(items: readonly T[]): T[] {\n let changed = false;\n const out = items.map((item) => {\n if (itemType(item) !== \"computer_call\") {\n return item;\n }\n const record = item as Record<string, unknown>;\n const hasAction = record.action !== undefined && record.action !== null;\n const hasActions = Array.isArray(record.actions) && (record.actions as unknown[]).length > 0;\n if (hasAction && hasActions) {\n changed = true;\n const { action: _droppedAction, ...rest } = record;\n return rest as unknown as T;\n }\n return item;\n });\n return changed ? out : items.slice();\n}\n\n/**\n * Rewrite EVERY `computer_call` item in a serialized Responses request body to\n * the ACTIONS-ONLY shape the GA Azure computer tool accepts, mutating the parsed\n * JSON object in place and returning whether anything changed.\n *\n * WHY THIS LIVES AT THE WIRE LEVEL (not the input-item filter). The input-item\n * normalizer above ({@link normalizeComputerCallActions}, wired as a\n * callModelInputFilter) runs BEFORE the SDK's responses converter\n * (`convertAgentItemToResponsesInput`). That converter then re-derives the wire\n * payload from the item: when `actions` is present it emits BOTH\n * `{action: ..., actions: [...]}`, and when only `action` is present it emits\n * `action`-only. It can NEVER emit actions-only. Probed live against the\n * deployed Azure gpt-5.6-sol-2026-04-24 GA computer tool (`{type:\"computer\"}`):\n * - `action`-only -> 400 \"Computer call input must include exactly one of\n * `action` or `actions`.\" (rejected)\n * - both -> 400 same message (rejected)\n * - `actions`-only -> passes the action/actions structural validation\n * So neither the input-filter nor the converter can produce an accepted body.\n * The ONLY seam that sees — and can rewrite — the final serialized JSON is a\n * custom `fetch` on the OpenAI client (it runs after the converter and after\n * `responses.create` serialization). This function is that rewriter's core.\n *\n * It collapses each computer_call to actions-only: it prefers an existing\n * non-empty `actions` array, else wraps the singular `action` into\n * `actions:[action]`, then deletes `action`. A computer_call with neither field\n * is left untouched (nothing to derive; let the provider report it).\n *\n * Mutates `body` in place (the caller has already JSON.parsed a private copy of\n * the request body). Returns `true` iff at least one computer_call was changed.\n */\nexport function rewriteComputerCallsToActionsOnly(body: unknown): boolean {\n if (!body || typeof body !== \"object\") {\n return false;\n }\n const input = (body as Record<string, unknown>).input;\n if (!Array.isArray(input)) {\n return false;\n }\n let changed = false;\n for (const item of input) {\n if (!item || typeof item !== \"object\") {\n continue;\n }\n const record = item as Record<string, unknown>;\n if (record.type !== \"computer_call\") {\n continue;\n }\n const existingActions =\n Array.isArray(record.actions) && (record.actions as unknown[]).length > 0\n ? (record.actions as unknown[])\n : undefined;\n const actions =\n existingActions ??\n (record.action !== undefined && record.action !== null ? [record.action] : undefined);\n if (actions === undefined) {\n // Neither action nor actions present: nothing to normalize.\n continue;\n }\n const hadAction = \"action\" in record;\n const actionsAlreadyExact = existingActions !== undefined && !hadAction;\n if (actionsAlreadyExact) {\n // Already actions-only with a non-empty array — leave byte-identical.\n continue;\n }\n delete record.action;\n record.actions = actions;\n changed = true;\n }\n return changed;\n}\n\n/**\n * Backstop for the empty `computer_call_output` image_url: walk the `input` array of\n * a serialized Responses request body and replace any `computer_call_output` item\n * whose `output.image_url` is empty/missing with a LEGIBLE \"screen capture failed\"\n * error card ({@link SCREENSHOT_FAILURE_CARD_IMAGE_URL}).\n *\n * WHY A CARD, NOT A BLANK. An empty `image_url` reaches this seam ONLY when the\n * computer op genuinely FAILED to produce a screen: agents-core's `toolExecution.mjs`\n * catch sets `output = ''` when the action OR the follow-up `computer.screenshot()`\n * throws, building `{type:\"computer_call_output\",output:{type:\"computer_screenshot\",\n * image_url:\"\"}}`. Azure then rejects the whole request with\n * `400 Invalid 'input[N].output.image_url'`. The previous fix substituted a 1×1\n * TRANSPARENT placeholder to dodge the 400 — but that reaches the model as a\n * plausible BLANK DESKTOP it confidently reports (\"the screen appears blank/empty\"),\n * turning a hard capture FAILURE into a silent, wrong observation. That is the worst\n * failure mode for computer use, and it is exactly what the 0.1.3 TCC-denied incident\n * produced. Substituting a legible error card instead makes the failure REACH THE\n * MODEL as an error (the only channel the hosted `computer_use_preview` protocol has\n * is the image), so the model stops and tells the user rather than hallucinating.\n *\n * WHY THIS IS SAFE (empty = failure, never an intentional blank). Post-af289e3 the\n * intentional-blank cases carry a NON-empty data URI already: agents-core's\n * tool-approval-rejection screenshot is its own non-empty 1×1 placeholder, and the\n * SandboxComputer action-timeout now warn+returns to a REAL screenshot rather than an\n * empty output. So an EMPTY image_url at this seam is unambiguously a capture/interact\n * FAILURE — the error card is the correct substitution for every empty case, and this\n * function never touches a non-empty (real screenshot OR intentional blank) output.\n *\n * The failure REASON (permission denied / null image / timeout / display down) is not\n * on the card; it is logged worker-side by `NativeDesktopComputer.screenshot()`.\n *\n * Mutates `body` in place (the caller has already JSON.parsed a private copy).\n * Returns `true` iff at least one image_url was replaced.\n */\nexport function rewriteEmptyComputerCallOutputImageUrls(body: unknown): boolean {\n if (!body || typeof body !== \"object\") {\n return false;\n }\n const input = (body as Record<string, unknown>).input;\n if (!Array.isArray(input)) {\n return false;\n }\n let changed = false;\n for (const item of input) {\n if (!item || typeof item !== \"object\") {\n continue;\n }\n const record = item as Record<string, unknown>;\n if (record.type !== \"computer_call_output\") {\n continue;\n }\n const output = record.output;\n if (!output || typeof output !== \"object\") {\n continue;\n }\n const out = output as Record<string, unknown>;\n const imageUrl = out.image_url;\n // Replace the image_url when it is not a non-empty string (covers: \"\", null,\n // undefined, missing) — an empty output is always a genuine capture failure, so\n // it becomes the legible error card, never a silent blank.\n if (typeof imageUrl !== \"string\" || imageUrl.length === 0) {\n out.image_url = SCREENSHOT_FAILURE_CARD_IMAGE_URL;\n changed = true;\n }\n }\n return changed;\n}\n\n/**\n * Wrap a `fetch` so every outbound OpenAI Responses request body that contains a\n * `computer_call` is rewritten to the ACTIONS-ONLY shape (see\n * {@link rewriteComputerCallsToActionsOnly}) before it reaches the network, AND\n * any `computer_call_output` item with an empty/missing `output.image_url` is\n * patched with the 1×1 transparent PNG placeholder (see\n * {@link rewriteEmptyComputerCallOutputImageUrls}).\n *\n * Installed as the `fetch:` option on the Azure OpenAI client, this is the\n * lowest reachable seam — below the agents-core input filter and below the SDK's\n * responses converter — so it neutralizes the converter's both-fields synthesis\n * regardless of what the input item carried, and backstops the action-timeout\n * empty image_url regardless of how it was produced.\n *\n * Surgical and cheap: it only parses the body when it is a string that contains\n * the prefix `\"computer_call` (matching both `\"computer_call\"` action items and\n * `\"computer_call_output\"` result items). Every other request — non-computer-use\n * turns, streaming SSE responses, non-string bodies — forwards untouched, the\n * SAME `init` reference, so streaming and other providers are unaffected. A JSON\n * parse failure or a no-op rewrite also forwards the original `init` unchanged.\n *\n * Typed structurally (the `(input, init) => Promise<Response>` call signature)\n * rather than as the DOM `typeof fetch` so it omits the `preconnect` static the\n * global type carries; this matches the OpenAI SDK's `Fetch` option, which only\n * needs the call signature. The wiring site passes it as the client `fetch:`.\n */\ntype FetchLike = (\n input: Parameters<typeof fetch>[0],\n init?: Parameters<typeof fetch>[1],\n) => Promise<Response>;\n\nexport function computerCallNormalizingFetch(base: FetchLike): FetchLike {\n return (input, init) => {\n // Match any request that mentions either `computer_call` (the action call) or\n // `computer_call_output` (the output/result item). Both strings begin with\n // `\"computer_call` so a single prefix-substring check covers both.\n if (init && typeof init.body === \"string\" && init.body.includes('\"computer_call')) {\n try {\n const parsed = JSON.parse(init.body) as unknown;\n const changed1 = rewriteComputerCallsToActionsOnly(parsed);\n const changed2 = rewriteEmptyComputerCallOutputImageUrls(parsed);\n if (changed1 || changed2) {\n return base(input, { ...init, body: JSON.stringify(parsed) });\n }\n } catch {\n // Non-JSON or parse failure: forward the request unchanged.\n }\n }\n return base(input, init);\n };\n}\n","// Progressive MCP disclosure for the ChatGPT/Codex backend — parity with how the\n// Codex CLI surfaces its ~217 `codex_apps` connector tools WITHOUT paying their\n// schemas in every turn's context, while applying the same bounded search seam to\n// other selected MCP servers.\n//\n// WHY. OpenGeni connects MCP servers as CLIENTs and the SDK materializes every\n// selected MCP tool as a `function` tool in request.tools[] on a Codex turn. The\n// Codex CLI instead uses the backend's NATIVE tool-search: the model gets one\n// compact search tool + deferred MCP tools (schemas dropped from model context),\n// searches by capability, and only matched tools are disclosed back and become\n// callable.\n//\n// PROVEN LIVE (Phase 0 probe against /codex/responses on gpt-5.6-sol): the backend\n// HONORS `defer_loading:true` on function tools — 50 fat tools dropped input_tokens\n// 6766 → 108 — AND makes a tool callable purely because a prior `tool_search_output`\n// disclosed it (V3). The model emits `tool_search_call` on our slug.\n//\n// HOW. We wrap the agent's `getAllTools` (codex turns only, flag-gated): tag every\n// non-mandatory MCP function tool `deferLoading = true` (converTool then serializes\n// `defer_loading:true`, dropping the schema from context) and append one\n// client-executed `toolSearchTool`. The SDK routes a `tool_search_call` to our\n// executor (ClientToolSearchExecutor), which BM25-ranks the deferred pool and\n// returns matched tools BY REFERENCE — the SDK emits the `tool_search_output` that\n// discloses them; the subsequent `function_call` resolves through the normal\n// `PrefixedMcpServer.callTool` path (auth + name-sanitize + structuredContent\n// inline all unchanged). Invocation is untouched; only the wire tool-set shrinks.\n\nimport { toolSearchTool, type Tool } from \"@openai/agents\";\nimport {\n MCP_MAX_TOOL_DEFINITION_BYTES,\n MCP_MAX_TOOL_SEARCH_DESCRIPTION_BYTES,\n MCP_MAX_TOOL_SEARCH_DISCLOSURE_BYTES,\n MCP_MAX_TOOL_SEARCH_SOURCE_LABEL_LENGTH,\n MCP_MAX_TOOL_SEARCH_SOURCES,\n mcpSerializedSizeBytes,\n} from \"./mcp-network\";\n\n/** The prefix OpenGeni's PrefixedMcpServer stamps on codex_apps connector tools. */\nexport const CODEX_APPS_TOOL_PREFIX = \"codex_apps__\";\nconst DEFAULT_SEARCH_LIMIT = 8;\nconst MAX_SEARCH_LIMIT = 20;\n\n/** True for a materialized codex_apps connector function tool. */\nexport function isCodexAppsFunctionTool(\n tool: unknown,\n): tool is Tool & { name: string; deferLoading?: boolean } {\n return (\n !!tool &&\n typeof tool === \"object\" &&\n (tool as { type?: unknown }).type === \"function\" &&\n typeof (tool as { name?: unknown }).name === \"string\" &&\n (tool as { name: string }).name.startsWith(CODEX_APPS_TOOL_PREFIX)\n );\n}\n\nconst MCP_TOOL_NAME_SEPARATOR = \"__\";\nconst MANDATORY_FIRST_PARTY_MCP_SERVER_ID = \"opengeni\";\nconst NO_MCP_SERVER_IDS: ReadonlySet<string> = new Set();\n\n/** Return the authorized server id for a runtime MCP function tool name. */\nfunction mcpServerIdForTool(tool: unknown, mcpServerIds: ReadonlySet<string>): string | null {\n if (!tool || typeof tool !== \"object\") return null;\n if ((tool as { type?: unknown }).type !== \"function\") return null;\n const name = (tool as { name?: unknown }).name;\n if (typeof name !== \"string\") return null;\n let match: string | null = null;\n for (const serverId of mcpServerIds) {\n if (\n typeof serverId !== \"string\" ||\n serverId.length === 0 ||\n !name.startsWith(`${serverId}${MCP_TOOL_NAME_SEPARATOR}`)\n ) {\n continue;\n }\n if (match === null || serverId.length > match.length) {\n match = serverId;\n }\n }\n return match;\n}\n\n/**\n * True for non-mandatory MCP function tools on the effective agent surface.\n * The prefix is the same runtime namespace used by PrefixedMcpServer; this\n * intentionally does not inspect the global registry, connection metadata, or\n * credentials, so search cannot widen the already-authorized tool set.\n */\nexport function isSearchableMcpFunctionTool(\n tool: unknown,\n mcpServerIds: ReadonlySet<string> = NO_MCP_SERVER_IDS,\n): tool is Tool & { name: string; deferLoading?: boolean } {\n const serverId = mcpServerIdForTool(tool, mcpServerIds);\n return serverId !== null && serverId !== MANDATORY_FIRST_PARTY_MCP_SERVER_ID;\n}\n\nfunction truncateUtf8(value: string, maxBytes: number): string {\n if (Buffer.byteLength(value) <= maxBytes) return value;\n let output = \"\";\n for (const character of value) {\n const candidate = output + character;\n if (Buffer.byteLength(candidate) > maxBytes) break;\n output = candidate;\n }\n return output;\n}\n\nfunction searchSourceForTool(tool: Tool, mcpServerIds: ReadonlySet<string>): string | null {\n const serverId = mcpServerIdForTool(tool, mcpServerIds);\n return serverId && serverId !== MANDATORY_FIRST_PARTY_MCP_SERVER_ID\n ? truncateUtf8(serverId, MCP_MAX_TOOL_SEARCH_SOURCE_LABEL_LENGTH)\n : null;\n}\n\nfunction searchSourcesForTools(\n connectorNamespaces: ReadonlySet<string>,\n tools: readonly Tool[],\n mcpServerIds: ReadonlySet<string>,\n): Set<string> {\n const sources = new Set<string>();\n for (const source of connectorNamespaces) {\n if (typeof source !== \"string\" || source.length === 0) continue;\n if (sources.size >= MCP_MAX_TOOL_SEARCH_SOURCES) break;\n sources.add(truncateUtf8(source, MCP_MAX_TOOL_SEARCH_SOURCE_LABEL_LENGTH));\n }\n for (const tool of tools) {\n // Codex connector labels come from the transport's original namespace set\n // (for example, `gmail`), not from the synthetic `codex_apps__` prefix.\n // Keep that authoritative path intact; derive fallback labels only for\n // directly materialized non-Codex MCP tools such as selected Slack tools.\n const source =\n isSearchableMcpFunctionTool(tool, mcpServerIds) && !isCodexAppsFunctionTool(tool)\n ? searchSourceForTool(tool, mcpServerIds)\n : null;\n if (!source || sources.has(source)) continue;\n if (sources.size >= MCP_MAX_TOOL_SEARCH_SOURCES) break;\n sources.add(source);\n }\n return sources;\n}\n\n// Minimal English stopword set: query phrasings like \"send an email to someone\"\n// should match on capability words, not drown in glue words (parity with\n// codex-rs, whose search normalizes tokens server-side).\nconst STOPWORDS = new Set([\n \"a\",\n \"an\",\n \"the\",\n \"and\",\n \"or\",\n \"of\",\n \"to\",\n \"in\",\n \"on\",\n \"for\",\n \"with\",\n \"by\",\n \"at\",\n \"is\",\n \"are\",\n \"be\",\n \"do\",\n \"does\",\n \"my\",\n \"me\",\n \"your\",\n \"you\",\n \"it\",\n \"its\",\n \"this\",\n \"that\",\n \"from\",\n \"as\",\n \"up\",\n \"out\",\n \"all\",\n \"some\",\n \"any\",\n \"can\",\n \"will\",\n \"would\",\n \"should\",\n \"want\",\n \"need\",\n \"please\",\n \"user\",\n \"users\",\n]);\n\n/** Light suffix stemmer so \"emails\"/\"email\", \"creating\"/\"create\" co-match (min-stem guards, no over-stripping). */\nfunction stem(token: string): string {\n if (token.length > 5 && token.endsWith(\"ing\")) return token.slice(0, -3);\n if (token.length > 4 && token.endsWith(\"ed\")) return token.slice(0, -2);\n if (token.length > 4 && token.endsWith(\"es\")) return token.slice(0, -2);\n if (token.length > 3 && token.endsWith(\"s\") && !token.endsWith(\"ss\")) return token.slice(0, -1);\n return token;\n}\n\n/** Split snake_case/camelCase/dotted text into stemmed lowercase word tokens (len ≥ 2, stopwords removed). */\nfunction tokenize(text: string): string[] {\n return text\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 1 && !STOPWORDS.has(t))\n .map(stem);\n}\n\n/** The searchable text of a connector tool: name (weighted ×2) + description + param names. */\nfunction toolSearchText(tool: Tool): string {\n const raw = (tool as { name?: string }).name ?? \"\";\n const name = raw.startsWith(CODEX_APPS_TOOL_PREFIX)\n ? raw.slice(CODEX_APPS_TOOL_PREFIX.length)\n : raw;\n const description =\n typeof (tool as { description?: unknown }).description === \"string\"\n ? (tool as { description: string }).description\n : \"\";\n const params = (tool as { parameters?: { properties?: Record<string, unknown> } }).parameters\n ?.properties;\n const paramNames = params && typeof params === \"object\" ? Object.keys(params).join(\" \") : \"\";\n return `${name} ${name} ${description} ${paramNames}`;\n}\n\n/**\n * Rank connector tools against a plain-language query with BM25 (Okapi, k1=1.5,\n * b=0.75) over tokenized name+description+params. Returns the top `limit` tools\n * with a positive score, most-relevant first. An empty or no-match query returns\n * [] — matching codex-rs, whose search returns empty rather than arbitrary tools;\n * disclosing unrelated (and thereby CALLABLE) tools on a miss feeds the model\n * noise. The SDK normalizes an empty executor result into an empty\n * tool_search_output, which the model reads as \"nothing matched — rephrase\".\n */\nexport function bm25RankTools(tools: Tool[], query: string, limit: number): Tool[] {\n const qTokens = Array.from(new Set(tokenize(query)));\n if (tools.length === 0 || qTokens.length === 0) return [];\n\n const docs = tools.map((tool) => {\n const tokens = tokenize(toolSearchText(tool));\n const tf = new Map<string, number>();\n for (const t of tokens) tf.set(t, (tf.get(t) ?? 0) + 1);\n return { tool, len: tokens.length, tf };\n });\n const N = docs.length;\n const avgdl = Math.max(1, docs.reduce((s, d) => s + d.len, 0) / N);\n const df = new Map<string, number>();\n for (const d of docs) for (const t of d.tf.keys()) df.set(t, (df.get(t) ?? 0) + 1);\n\n const k1 = 1.5;\n const b = 0.75;\n const scored = docs.map((d) => {\n let score = 0;\n for (const qt of qTokens) {\n const n = df.get(qt);\n const f = d.tf.get(qt);\n if (!n || !f) continue;\n const idf = Math.log(1 + (N - n + 0.5) / (n + 0.5));\n score += idf * ((f * (k1 + 1)) / (f + k1 * (1 - b + (b * d.len) / avgdl)));\n }\n return { tool: d.tool, score };\n });\n const hits = scored.filter((s) => s.score > 0).sort((a, b2) => b2.score - a.score);\n return hits.slice(0, limit).map((s) => s.tool); // no hits ⇒ [] (codex-rs parity; see doc)\n}\n\n/** Parse `{query, limit}` from a tool_search_call's arguments (string or object). */\nfunction parseSearchArgs(raw: unknown): { query: string; limit: number } {\n let obj: Record<string, unknown> = {};\n try {\n obj =\n typeof raw === \"string\"\n ? raw.length\n ? JSON.parse(raw)\n : {}\n : raw && typeof raw === \"object\"\n ? (raw as Record<string, unknown>)\n : {};\n } catch {\n obj = {};\n }\n const query = typeof obj.query === \"string\" ? obj.query : \"\";\n const limitRaw =\n typeof obj.limit === \"number\" && Number.isFinite(obj.limit) ? obj.limit : DEFAULT_SEARCH_LIMIT;\n return { query, limit: Math.max(1, Math.min(MAX_SEARCH_LIMIT, Math.round(limitRaw))) };\n}\n\n/**\n * Render the search tool's description from the account's ACTUALLY-connected\n * sources — codex-rs parity (its create_tool_search_tool builds \"You have access\n * to tools from the following sources:\\n- <name>\" from the live enabled-source\n * list). With defer_loading stripping every connector schema (and name) from\n * model context, this description is the model's ONLY signal of which apps\n * exist, so a hardcoded list would both advertise absent connectors and hide\n * present ones.\n */\nexport function renderSearchToolDescription(connectorNamespaces: ReadonlySet<string>): string {\n const base =\n \"Search the user's connected app tools by capability. \" +\n 'Describe in plain language WHAT you need to do (for example: \"send an email\", \"create a calendar event\") ' +\n \"rather than guessing exact tool names. Returns the matching connector tools, which then become callable.\";\n const sources = Array.from(connectorNamespaces)\n .filter((n) => typeof n === \"string\" && n.length > 0)\n .slice(0, MCP_MAX_TOOL_SEARCH_SOURCES)\n .map((source) => truncateUtf8(source, MCP_MAX_TOOL_SEARCH_SOURCE_LABEL_LENGTH))\n .filter(Boolean)\n .sort();\n if (sources.length === 0) {\n return `${base}\\nConnected sources: none currently available.`;\n }\n const header = `${base}\\nYou have access to tools from the following sources:`;\n const lines: string[] = [];\n for (const source of sources) {\n const candidate = `${header}${[...lines, `- ${source}`].map((line) => `\\n${line}`).join(\"\")}`;\n if (Buffer.byteLength(candidate) > MCP_MAX_TOOL_SEARCH_DESCRIPTION_BYTES) break;\n lines.push(`- ${source}`);\n }\n return lines.length > 0\n ? `${header}\\n${lines.join(\"\\n\")}`\n : `${base}\\nConnected sources: none currently available.`;\n}\n\nconst SEARCH_TOOL_PARAMETERS = {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"Plain-language description of the capability you need.\",\n },\n limit: { type: \"number\", description: \"Maximum number of tools to return (default 8).\" },\n },\n required: [\"query\"],\n additionalProperties: false,\n} as const;\n\n/**\n * The client tool-search executor: BM25 over the deferred MCP pool from the\n * turn's live `availableTools`, returning matched tools BY REFERENCE (the only legal\n * return — the SDK emits the disclosing `tool_search_output` and flips the loaded\n * gate; returning copies would throw). Stateless — reads the pool per call.\n */\nfunction codexToolSearchExecutor(\n args: {\n availableTools?: Tool[];\n toolCall?: { arguments?: unknown };\n },\n mcpServerIds: ReadonlySet<string>,\n): Tool[] {\n const deferred = (args.availableTools ?? []).filter((tool) =>\n isSearchableMcpFunctionTool(tool, mcpServerIds),\n );\n if (deferred.length === 0) return [];\n const { query, limit } = parseSearchArgs(args.toolCall?.arguments);\n const ranked = bm25RankTools(deferred, query, limit);\n const bounded: Tool[] = [];\n let disclosedBytes = 0;\n for (const tool of ranked) {\n const toolBytes = mcpSerializedSizeBytes(tool);\n if (toolBytes > MCP_MAX_TOOL_DEFINITION_BYTES) {\n continue;\n }\n if (disclosedBytes + toolBytes > MCP_MAX_TOOL_SEARCH_DISCLOSURE_BYTES) {\n break;\n }\n disclosedBytes += toolBytes;\n bounded.push(tool);\n }\n return bounded;\n}\n\nconst NO_NAMESPACES: ReadonlySet<string> = new Set();\n\n/** True when the namespace set contains at least one usable (non-empty string) source — mirrors {@link renderSearchToolDescription}'s filter, so it is TRUE exactly when the render produces the \"following sources\" list and FALSE when it produces \"none currently available\". */\nfunction hasConnectorSources(connectorNamespaces: ReadonlySet<string>): boolean {\n for (const namespace of connectorNamespaces) {\n if (typeof namespace === \"string\" && namespace.length > 0) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * A per-TURN freeze cell for the tool_search description (AM-8). The connector Set\n * `installCodexToolSearch` reads is LIVE and by-reference — it fills as the turn's\n * codex_apps tools/list resolves and can change between a turn's model calls.\n * Re-rendering the description per call from a changed Set flips the tools block,\n * and because tools precede the history in the request prefix, ANY change misses the\n * ENTIRE conversation prefix from that point on — a proven prompt-cache breaker.\n *\n * We therefore freeze the description ONCE, at the first model call whose Set has\n * been populated (connectors discovered), and reuse that frozen string for the rest\n * of the turn — trading a slightly staler connector list for a byte-stable prefix.\n * The freeze is created per {@link installCodexToolSearch} (once per turn) and shared\n * by reference into every clone re-install, so all of a turn's clones agree.\n */\nexport type CodexToolSearchDescriptionFreeze = { value: string | null };\n\n/**\n * Resolve the tool_search description for this model call, honoring the per-turn\n * freeze (AM-8):\n * - Already frozen ⇒ return the frozen string (byte-stable for the rest of the turn).\n * - Not yet frozen + connectors DISCOVERED (non-empty Set) ⇒ render and FREEZE it,\n * locking the discovered list against a later same-turn Set mutation.\n * - Not yet frozen + Set still EMPTY ⇒ render live (\"none currently available\") but\n * do NOT freeze. This is the load-bearing safety of AM-8: the Set fills lazily and\n * best-effort, so an empty Set means \"not discovered yet\", not \"no connectors\".\n * Freezing \"none\" here would silently disable the turn's connectors (capability\n * loss). Leaving it unfrozen is still byte-stable while the Set stays empty (the\n * empty render is a constant), and lets a later call freeze the real list once it\n * resolves — at most ONE prefix transition, versus today's per-call churn.\n * With no freeze cell (the default / direct callers + tests) this is a live render,\n * byte-for-byte the pre-AM-8 behavior.\n */\nfunction resolveSearchToolDescription(\n connectorNamespaces: ReadonlySet<string>,\n freeze?: CodexToolSearchDescriptionFreeze,\n): string {\n if (freeze?.value != null) {\n return freeze.value;\n }\n const rendered = renderSearchToolDescription(connectorNamespaces);\n if (freeze && hasConnectorSources(connectorNamespaces)) {\n freeze.value = rendered;\n }\n return rendered;\n}\n\n/** Build the client-executed tool_search tool from an already-rendered description. */\nfunction buildCodexToolSearchToolFromDescription(\n description: string,\n mcpServerIds: ReadonlySet<string>,\n): Tool {\n return toolSearchTool({\n execution: \"client\",\n description,\n parameters: SEARCH_TOOL_PARAMETERS as unknown as Record<string, unknown>,\n execute: ((args: Parameters<typeof codexToolSearchExecutor>[0]) =>\n codexToolSearchExecutor(args, mcpServerIds)) as never,\n }) as unknown as Tool;\n}\n\n/** Build the client-executed tool_search tool that discloses deferred MCP tools on demand. */\nexport function buildCodexToolSearchTool(\n connectorNamespaces: ReadonlySet<string> = NO_NAMESPACES,\n mcpServerIds: ReadonlySet<string> = NO_MCP_SERVER_IDS,\n): Tool {\n return buildCodexToolSearchToolFromDescription(\n renderSearchToolDescription(connectorNamespaces),\n mcpServerIds,\n );\n}\n\n/** True for the built-in tool_search tool (so we never add a second one). */\nfunction isToolSearchTool(tool: unknown): boolean {\n const t = tool as { name?: unknown; providerData?: { type?: unknown } } | null;\n return !!t && (t.name === \"tool_search\" || t.providerData?.type === \"tool_search\");\n}\n\n/**\n * The transform applied to a turn's resolved tool list: tag every searchable\n * non-mandatory MCP function tool `deferLoading = true`, and — unless one is already\n * present — append the client tool_search tool. Pure (mutates the passed tools +\n * returns the possibly-extended array); the SDK's `getTools` gate requires a\n * tool_search whenever a deferred tool is present, which appending here satisfies\n * in the same request.\n *\n * The search tool is appended UNCONDITIONALLY (even when the turn has no\n * searchable MCP tools, e.g. a best-effort connector was dropped this\n * turn): a prior turn's history may carry tool_search_call/output items, and\n * replaying those without a tool_search tool in the request risks a backend\n * reject; a search over an empty pool simply discloses nothing. The description\n * reflects the LIVE connector namespaces, so an empty turn reads\n * \"none currently available\".\n */\nexport function applyCodexToolSearch(\n tools: Tool[],\n connectorNamespaces: ReadonlySet<string> = NO_NAMESPACES,\n descriptionFreeze?: CodexToolSearchDescriptionFreeze,\n mcpServerIds: ReadonlySet<string> = NO_MCP_SERVER_IDS,\n): Tool[] {\n for (const tool of tools) {\n if (\n isSearchableMcpFunctionTool(tool, mcpServerIds) &&\n (tool as { deferLoading?: boolean }).deferLoading !== true\n ) {\n (tool as { deferLoading?: boolean }).deferLoading = true;\n }\n }\n if (tools.some(isToolSearchTool)) {\n return tools;\n }\n // AM-8: render through the per-turn freeze so the tools-block prefix stays\n // byte-stable across a turn's model calls once connectors are discovered.\n const description = resolveSearchToolDescription(\n searchSourcesForTools(connectorNamespaces, tools, mcpServerIds),\n descriptionFreeze,\n );\n return [...tools, buildCodexToolSearchToolFromDescription(description, mcpServerIds)];\n}\n\ntype CloneCapableAgent = {\n getAllTools: (runContext: unknown) => Promise<Tool[]>;\n clone?: (config: unknown) => CloneCapableAgent;\n};\n\n/**\n * Install progressive MCP disclosure on a Codex-path agent by wrapping\n * `getAllTools` so every per-model-call tool resolution runs\n * {@link applyCodexToolSearch}. Idempotent-per-call (re-tags each\n * freshly-materialized MCP tool under cacheToolsList:false). Gated by the caller\n * (flag + Codex path).\n *\n * CLONE SURVIVAL (the part that makes this work on the REAL sandbox path): the\n * SDK's sandbox runtime routes EVERY model call through\n * `prepareSandboxAgent → agent.clone(...)` (agentPreparation.js), and\n * `SandboxAgent.clone` constructs a FRESH agent from a fixed field list — an\n * instance-own `getAllTools` override is NOT copied, so patching only this\n * instance would silently no-op the whole feature on sandbox turns (the run\n * loop resolves tools on the CLONE). We therefore also wrap `clone` to\n * RE-INSTALL onto every clone, recursively — covering clone-of-clone and the\n * RunState resume paths. `connectorNamespaces` is the LIVE, by-reference Set the\n * codex_apps sanitizing transport fills during each turn's tools/list\n * (prepareAgentTools), so by the time the wrapper post-processes getAllTools the\n * current turn's connector sources are known.\n */\nexport function installCodexToolSearch(\n agent: CloneCapableAgent,\n connectorNamespaces: ReadonlySet<string> = NO_NAMESPACES,\n mcpServerIds: ReadonlySet<string> = NO_MCP_SERVER_IDS,\n): void {\n // ONE freeze cell per install (i.e. per turn), shared BY REFERENCE into every\n // clone re-install below so the whole turn — the built agent and every clone the\n // sandbox runtime resolves tools on — agrees on the same frozen description\n // (AM-8). Created here, at the top-level install, never per clone.\n installCodexToolSearchWithFreeze(agent, connectorNamespaces, mcpServerIds, { value: null });\n}\n\nfunction installCodexToolSearchWithFreeze(\n agent: CloneCapableAgent,\n connectorNamespaces: ReadonlySet<string>,\n mcpServerIds: ReadonlySet<string>,\n descriptionFreeze: CodexToolSearchDescriptionFreeze,\n): void {\n const originalGetAllTools = agent.getAllTools.bind(agent);\n agent.getAllTools = (async (runContext: unknown) =>\n applyCodexToolSearch(\n await originalGetAllTools(runContext),\n connectorNamespaces,\n descriptionFreeze,\n mcpServerIds,\n )) as typeof agent.getAllTools;\n const originalClone = agent.clone?.bind(agent);\n if (originalClone) {\n const cloneWithToolSearch: NonNullable<CloneCapableAgent[\"clone\"]> = (config: unknown) => {\n const cloned = originalClone(config);\n installCodexToolSearchWithFreeze(\n cloned,\n connectorNamespaces,\n mcpServerIds,\n descriptionFreeze,\n );\n return cloned;\n };\n agent.clone = cloneWithToolSearch;\n }\n}\n","/**\n * Portable conversation context compaction, following Codex CLI's local path.\n *\n * The checkpoint model sees the current active history plus one fixed\n * checkpoint prompt, then the active history is rebuilt from the newest real\n * user messages within one cumulative 20k-token budget plus one summary.\n * Assistant messages, tool calls/results, reasoning, and images are removed\n * from the active model-facing history; the database audit rows remain.\n */\n\nimport {\n TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE,\n sanitizeHistoryItemsForModel,\n} from \"./history-sanitizer\";\nimport { boundModelToolOutputItem } from \"@opengeni/codex\";\nimport { createHash } from \"node:crypto\";\n\nexport type CompactionItem = Record<string, unknown>;\n\n/**\n * Marker stored on the synthetic summary item so the UI can render it and the\n * next rebuild can exclude old summaries from the retained user-message set.\n */\nexport const COMPACTION_SUMMARY_MARKER = \"opengeni_context_summary\";\n\nexport const SUMMARY_BUFFER_TOKENS = 20_000;\n// A single cumulative budget for all retained real user messages, matching\n// Codex core's build_compacted_history_with_limit (not a per-message allowance).\nexport const COMPACT_USER_MESSAGE_MAX_TOKENS = 20_000;\n// 0.9: compact as LATE as possible — retained context is worth more than early\n// headroom now that declared per-model windows are honest. Model-catalog\n// explicit limits take precedence; the ratio is used for models without one.\nexport const DEFAULT_COMPACTION_THRESHOLD_RATIO = 0.9;\nexport const MIN_COMPACTION_THRESHOLD_RATIO = 0.3;\nexport const MAX_COMPACTION_THRESHOLD_RATIO = 0.9;\n\n// Verbatim from Codex CLI:\n// codex-rs/prompts/templates/compact/prompt.md\nexport const COMPACTION_PROMPT = [\n \"You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.\",\n \"\",\n \"Include:\",\n \"- Current progress and key decisions made\",\n \"- Important context, constraints, or user preferences\",\n \"- What remains to be done (clear next steps)\",\n \"- Any critical data, examples, or references needed to continue\",\n \"\",\n \"Be concise, structured, and focused on helping the next LLM seamlessly continue the work.\",\n].join(\"\\n\");\n\n// Verbatim from Codex CLI:\n// codex-rs/prompts/templates/compact/summary_prefix.md\nexport const SUMMARY_PREFIX =\n \"Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:\";\n\nexport const USER_MESSAGE_TRUNCATION_MARKER =\n \"\\n[... middle truncated for context compaction ...]\\n\";\n\nconst RESULT_TYPE_BY_CALL_TYPE = TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE;\nconst RESULT_TYPES = new Set(Object.values(RESULT_TYPE_BY_CALL_TYPE));\nconst MODEL_GENERATED_ITEM_TYPES = new Set([\n \"reasoning\",\n \"function_call\",\n \"custom_tool_call\",\n \"tool_search_call\",\n \"web_search_call\",\n \"image_generation_call\",\n \"computer_call\",\n \"shell_call\",\n \"apply_patch_call\",\n \"compaction\",\n \"context_compaction\",\n]);\n\nfunction itemType(item: unknown): string | undefined {\n if (!item || typeof item !== \"object\") {\n return undefined;\n }\n const type = (item as { type?: unknown }).type;\n return typeof type === \"string\" ? type : undefined;\n}\n\nfunction itemRole(item: unknown): string | undefined {\n if (!item || typeof item !== \"object\") {\n return undefined;\n }\n const role = (item as { role?: unknown }).role;\n return typeof role === \"string\" ? role : undefined;\n}\n\n/** A user-authored `message` item is the only legal turn boundary. */\nexport function isUserMessage(item: unknown): boolean {\n return itemType(item) === \"message\" && itemRole(item) === \"user\";\n}\n\n/** True for our synthetic compaction summary item. */\nexport function isCompactionSummary(item: unknown): boolean {\n return (\n isUserMessage(item) && (item as Record<string, unknown>)[COMPACTION_SUMMARY_MARKER] === true\n );\n}\n\n/**\n * Conservative tokenizer-independent text estimate used for every local input\n * budget. Preserve the stable ASCII `chars / 4` heuristic, but never discount\n * Unicode as UTF-16 length/4: each non-ASCII code unit costs at least one token\n * (CJK ≈ 1/code point; an astral emoji's surrogate pair ≈ 2). This intentionally\n * errs toward compaction rather than letting multilingual current input exceed\n * a provider context window before an authoritative usage anchor exists.\n */\nexport function estimateTextTokens(text: string): number {\n let asciiCodeUnits = 0;\n let nonAsciiCodeUnits = 0;\n for (let index = 0; index < text.length; index += 1) {\n if (text.charCodeAt(index) <= 0x7f) asciiCodeUnits += 1;\n else nonAsciiCodeUnits += 1;\n }\n return nonAsciiCodeUnits + Math.ceil(asciiCodeUnits / 4);\n}\n\n/** Serialized-item estimate for pre-call accounting and retained user budgets. */\nexport function estimateItemTokens(item: CompactionItem): number {\n let text: string;\n try {\n text = JSON.stringify(item);\n } catch {\n text = String(item);\n }\n return estimateTextTokens(text);\n}\n\nexport function estimateTokens(items: readonly CompactionItem[]): number {\n let total = 0;\n for (const item of items) {\n total += estimateItemTokens(item);\n }\n return total;\n}\n\nexport function estimateSerializedValueTokens(value: unknown): number {\n let serialized: string;\n try {\n serialized = typeof value === \"string\" ? value : JSON.stringify(value);\n } catch {\n serialized = String(value);\n }\n return estimateTextTokens(serialized ?? \"\");\n}\n\nexport type CompleteModelInputFootprint = {\n input: readonly CompactionItem[];\n instructionsTokens: number;\n toolSchemaTokens: number;\n};\n\nexport type ProviderContextTokenSignal = {\n /** Monotonic within one sampled run; advances after every model response. */\n revision: number;\n /** Provider total tokens after that response (input + generated output). */\n totalTokens: number;\n};\n\nexport type CompleteModelInputEstimate = {\n tokens: number;\n source: \"complete_estimate\" | \"provider_plus_local\";\n inputTokens: number;\n instructionsTokens: number;\n toolSchemaTokens: number;\n appendedAfterModelTokens: number;\n};\n\n/**\n * Match Codex history accounting: after one provider response, start from its\n * authoritative TOTAL token count and add only local items placed after the\n * newest model-generated item. System instructions and tool schemas are\n * compared with the exact request footprint that produced the provider count;\n * positive growth is added. Without a bound anchor, estimate the entire\n * outgoing request rather than trusting stale usage from an earlier turn.\n */\nexport function estimateCompleteModelInput(input: {\n current: CompleteModelInputFootprint;\n provider?: ProviderContextTokenSignal | null;\n providerRequestFootprint?: CompleteModelInputFootprint | null;\n}): CompleteModelInputEstimate {\n const inputTokens = estimateTokens(input.current.input);\n const instructionsTokens = input.current.instructionsTokens;\n const toolSchemaTokens = input.current.toolSchemaTokens;\n if (!input.provider || !input.providerRequestFootprint || input.provider.totalTokens <= 0) {\n return {\n tokens: inputTokens + instructionsTokens + toolSchemaTokens,\n source: \"complete_estimate\",\n inputTokens,\n instructionsTokens,\n toolSchemaTokens,\n appendedAfterModelTokens: 0,\n };\n }\n\n const appended = itemsAfterLastModelGeneratedItem(input.current.input);\n const appendedAfterModelTokens = estimateTokens(appended);\n const instructionGrowth = Math.max(\n 0,\n instructionsTokens - input.providerRequestFootprint.instructionsTokens,\n );\n const toolSchemaGrowth = Math.max(\n 0,\n toolSchemaTokens - input.providerRequestFootprint.toolSchemaTokens,\n );\n return {\n tokens:\n input.provider.totalTokens + appendedAfterModelTokens + instructionGrowth + toolSchemaGrowth,\n source: \"provider_plus_local\",\n inputTokens,\n instructionsTokens,\n toolSchemaTokens,\n appendedAfterModelTokens,\n };\n}\n\nexport function itemsAfterLastModelGeneratedItem(\n items: readonly CompactionItem[],\n): CompactionItem[] {\n for (let index = items.length - 1; index >= 0; index -= 1) {\n if (isModelGeneratedItem(items[index])) {\n return items.slice(index + 1);\n }\n }\n // Codex treats a provider token anchor without any model-generated item as\n // unbound. Callers therefore fall back to a complete estimate in that case.\n return items.slice();\n}\n\nexport function hasModelGeneratedItem(items: readonly CompactionItem[]): boolean {\n return items.some(isModelGeneratedItem);\n}\n\nfunction isModelGeneratedItem(item: unknown): boolean {\n const type = itemType(item);\n if (type === \"message\") return itemRole(item) === \"assistant\";\n return MODEL_GENERATED_ITEM_TYPES.has(type ?? \"\");\n}\n\nexport function clampCompactionThresholdRatio(value: number | undefined | null): number {\n const numeric =\n typeof value === \"number\" && Number.isFinite(value)\n ? value\n : DEFAULT_COMPACTION_THRESHOLD_RATIO;\n return Math.min(\n MAX_COMPACTION_THRESHOLD_RATIO,\n Math.max(MIN_COMPACTION_THRESHOLD_RATIO, numeric),\n );\n}\n\nexport function compactionThresholdTokens(input: {\n contextWindowTokens: number;\n contextReservedOutputTokens: number;\n contextAutoCompactThresholdTokens?: number | null | undefined;\n contextCompactionThresholdRatio?: number | null | undefined;\n}): number {\n const window = Math.max(0, input.contextWindowTokens);\n const codexMaximum = Math.floor(window * MAX_COMPACTION_THRESHOLD_RATIO);\n if (\n typeof input.contextAutoCompactThresholdTokens === \"number\" &&\n Number.isFinite(input.contextAutoCompactThresholdTokens) &&\n input.contextAutoCompactThresholdTokens > 0\n ) {\n return Math.min(Math.floor(input.contextAutoCompactThresholdTokens), codexMaximum);\n }\n return Math.floor(window * clampCompactionThresholdRatio(input.contextCompactionThresholdRatio));\n}\n\nexport type CompactionDecision = {\n shouldCompact: boolean;\n reason: \"force\" | \"above_threshold\" | \"below_threshold\" | \"no_history\";\n signalTokens: number;\n thresholdTokens: number;\n};\n\nexport function decideCompaction(input: {\n items: readonly CompactionItem[];\n lastInputTokens?: number | null;\n contextWindowTokens: number;\n contextReservedOutputTokens: number;\n contextAutoCompactThresholdTokens?: number | null | undefined;\n contextCompactionThresholdRatio?: number | null | undefined;\n force?: boolean;\n}): CompactionDecision {\n const thresholdTokens = compactionThresholdTokens(input);\n const recorded =\n typeof input.lastInputTokens === \"number\" && input.lastInputTokens > 0\n ? input.lastInputTokens\n : 0;\n const activeHistoryEstimate = estimateTokens(input.items);\n // A durable provider count belongs to an earlier request. The full active\n // estimate is a conservative cross-turn floor until an exact same-run anchor\n // is available in the per-call guard.\n const signalTokens = Math.max(recorded, activeHistoryEstimate);\n if (input.items.length === 0) {\n return {\n shouldCompact: false,\n reason: \"no_history\",\n signalTokens,\n thresholdTokens,\n };\n }\n if (input.force) {\n return {\n shouldCompact: true,\n reason: \"force\",\n signalTokens,\n thresholdTokens,\n };\n }\n if (signalTokens >= thresholdTokens) {\n return {\n shouldCompact: true,\n reason: \"above_threshold\",\n signalTokens,\n thresholdTokens,\n };\n }\n return {\n shouldCompact: false,\n reason: \"below_threshold\",\n signalTokens,\n thresholdTokens,\n };\n}\n\nexport class CompactionNeededError extends Error {\n readonly signalTokens: number;\n readonly thresholdTokens: number;\n readonly signalSource: \"provider\" | \"estimate\";\n readonly trigger: \"threshold\" | \"operator\";\n\n constructor(input: {\n signalTokens: number;\n thresholdTokens: number;\n signalSource: \"provider\" | \"estimate\";\n trigger?: \"threshold\" | \"operator\";\n }) {\n const trigger = input.trigger ?? \"threshold\";\n super(\n trigger === \"operator\"\n ? \"Context compaction requested by the operator\"\n : `Context compaction needed: signal ${input.signalTokens} tokens exceeded threshold ${input.thresholdTokens}`,\n );\n this.name = \"CompactionNeededError\";\n this.signalTokens = input.signalTokens;\n this.thresholdTokens = input.thresholdTokens;\n this.signalSource = input.signalSource;\n this.trigger = trigger;\n }\n}\n\nexport class EmptyCompactionSummaryError extends Error {\n readonly diagnostics: Record<string, unknown>;\n\n constructor(diagnostics: Record<string, unknown> = {}) {\n const compact = JSON.stringify(diagnostics).slice(0, 2_000);\n super(\n `Compaction summarizer returned no assistant text; active history was preserved${compact ? ` (${compact})` : \"\"}`,\n );\n this.name = \"EmptyCompactionSummaryError\";\n this.diagnostics = diagnostics;\n }\n}\n\n/**\n * The checkpoint model request ended in a provider/transport failure rather\n * than a successful response with an empty assistant message. Diagnostics are\n * deliberately bounded and content-free so this error can be persisted on a\n * turn without copying provider messages or conversation input into events.\n */\nexport class CompactionProviderResponseError extends Error {\n readonly diagnostics: Record<string, unknown>;\n readonly status?: number;\n readonly code?: string;\n readonly type?: string;\n override readonly cause?: unknown;\n\n constructor(diagnostics: Record<string, unknown> = {}, cause?: unknown) {\n const compact = JSON.stringify(diagnostics).slice(0, 2_000);\n super(\n `Compaction provider request failed; active history was preserved${compact ? ` (${compact})` : \"\"}`,\n );\n this.name = \"CompactionProviderResponseError\";\n this.diagnostics = diagnostics;\n if (typeof diagnostics.httpStatus === \"number\") this.status = diagnostics.httpStatus;\n if (typeof diagnostics.code === \"string\") this.code = diagnostics.code;\n if (typeof diagnostics.type === \"string\") this.type = diagnostics.type;\n if (cause !== undefined) {\n Object.defineProperty(this, \"cause\", { value: cause, enumerable: false });\n }\n }\n}\n\nexport function findCompactionNeededError(\n error: unknown,\n seen = new WeakSet<object>(),\n): CompactionNeededError | null {\n if (error instanceof CompactionNeededError) {\n return error;\n }\n if (!error || typeof error !== \"object\") {\n return null;\n }\n if (seen.has(error)) {\n return null;\n }\n seen.add(error);\n const record = error as Record<string, unknown>;\n return (\n findCompactionNeededError(record.cause, seen) ?? findCompactionNeededError(record.error, seen)\n );\n}\n\n/**\n * The exact checkpoint input shape: current active history followed by Codex's\n * checkpoint prompt as a synthesized user message.\n */\nexport function buildCompactionPromptInput(items: readonly CompactionItem[]): CompactionItem[] {\n return [\n ...items,\n {\n type: \"message\",\n role: \"user\",\n content: COMPACTION_PROMPT,\n },\n ];\n}\n\nexport type PreparedCompactionPromptInput = {\n input: CompactionItem[];\n estimatedInputTokens: number;\n rewrittenToolOutputs: number;\n droppedHistoryItems: number;\n};\n\n/**\n * Fit the explicit checkpoint request without mutating canonical history.\n *\n * Codex first replaces oversized tool outputs in its temporary remote-\n * compaction input. OpenGeni does the same oldest-first, preserving the most\n * recent tool detail for the plaintext summary. If that is still insufficient,\n * whole oldest user-delimited work units are removed and the remaining suffix\n * is protocol-sanitized so no call/result/reasoning fragment is orphaned.\n * The raw active history is still the source for the eventual replacement and\n * remains unchanged if the provider call fails.\n */\nexport function prepareCompactionPromptInput(\n items: readonly CompactionItem[],\n maxInputTokens: number,\n): PreparedCompactionPromptInput {\n const budget = Math.max(0, Math.floor(maxInputTokens));\n let history = items.slice();\n let estimatedInputTokens = estimateTokens(buildCompactionPromptInput(history));\n let rewrittenToolOutputs = 0;\n\n for (let index = 0; index < history.length && estimatedInputTokens > budget; index += 1) {\n const current = history[index]!;\n const replacement = minimalToolResultForCompaction(current);\n if (replacement === current) continue;\n const before = estimateItemTokens(current);\n const after = estimateItemTokens(replacement);\n if (after >= before) continue;\n history[index] = replacement;\n estimatedInputTokens -= before - after;\n rewrittenToolOutputs += 1;\n }\n\n const beforeDropLength = history.length;\n if (estimatedInputTokens > budget && history.length > 0) {\n const prefixTokens = new Array<number>(history.length + 1).fill(0);\n for (let index = 0; index < history.length; index += 1) {\n prefixTokens[index + 1] = prefixTokens[index]! + estimateItemTokens(history[index]!);\n }\n const cuts = oldestLogicalUnitCuts(history);\n const cut =\n cuts.find((candidate) => estimatedInputTokens - prefixTokens[candidate]! <= budget) ??\n history.length;\n history = sanitizeHistoryItemsForModel(history.slice(cut));\n estimatedInputTokens = estimateTokens(buildCompactionPromptInput(history));\n // The synthesized checkpoint instruction is the irreducible floor. The\n // real model budgets are far above it, but keep the helper total for tests\n // and malformed configuration instead of constructing invalid fragments.\n if (estimatedInputTokens > budget) {\n history = [];\n estimatedInputTokens = estimateTokens(buildCompactionPromptInput(history));\n }\n }\n\n return {\n input: buildCompactionPromptInput(history),\n estimatedInputTokens,\n rewrittenToolOutputs,\n droppedHistoryItems: beforeDropLength - history.length,\n };\n}\n\nfunction minimalToolResultForCompaction(item: CompactionItem): CompactionItem {\n const type = itemType(item);\n if (!type || !RESULT_TYPES.has(type)) return item;\n if (type === \"tool_search_output\" && Array.isArray(item.tools) && item.tools.length > 0) {\n return { ...item, tools: [] };\n }\n return boundModelToolOutputItem(item, 0);\n}\n\nfunction oldestLogicalUnitCuts(items: readonly CompactionItem[]): number[] {\n const userMessageIndexes: number[] = [];\n for (let index = 0; index < items.length; index += 1) {\n if (isUserMessage(items[index])) userMessageIndexes.push(index);\n }\n const cuts: number[] = [];\n if (userMessageIndexes.length === 0) {\n return [items.length];\n }\n if (userMessageIndexes[0]! > 0) cuts.push(userMessageIndexes[0]!);\n for (const index of userMessageIndexes.slice(1)) cuts.push(index);\n cuts.push(items.length);\n return cuts;\n}\n\n/**\n * Build the active history after compaction:\n * the newest real user messages that fit one cumulative 20k-token budget\n * (prior summaries excluded, images removed) plus one marked summary item.\n */\nexport function buildCompactionReplacementHistory(\n items: readonly CompactionItem[],\n summaryBody: string,\n): CompactionItem[] {\n const retainedReversed: CompactionItem[] = [];\n let remaining = COMPACT_USER_MESSAGE_MAX_TOKENS;\n for (let index = items.length - 1; index >= 0 && remaining > 0; index -= 1) {\n const item = items[index]!;\n if (!isUserMessage(item) || isCompactionSummary(item)) {\n continue;\n }\n const textTokens = estimateTextTokens(messageText(item));\n retainedReversed.push(compactMessageToTokenBudget(item, remaining));\n if (textTokens > remaining) {\n remaining = 0;\n break;\n }\n remaining -= textTokens;\n }\n const history = retainedReversed.reverse();\n history.push(buildSummaryItem(summaryBody));\n return history;\n}\n\nexport function compactionReplacementFingerprint(items: readonly CompactionItem[]): string {\n // PostgreSQL JSONB does not preserve JavaScript object-key insertion order.\n // Canonicalize recursively so a replacement has the same identity before\n // and after its durable round trip.\n const serialized = JSON.stringify(canonicalJsonValue(items));\n return createHash(\"sha256\").update(serialized, \"utf8\").digest(\"hex\");\n}\n\nfunction canonicalJsonValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalJsonValue);\n if (!value || typeof value !== \"object\") return value;\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => [key, canonicalJsonValue(entry)]),\n );\n}\n\n/** Fingerprint the latest durable replacement prefix in active history. */\nexport function latestCompactionReplacementFingerprint(\n items: readonly CompactionItem[],\n): string | null {\n for (let index = items.length - 1; index >= 0; index -= 1) {\n if (isCompactionSummary(items[index])) {\n return compactionReplacementFingerprint(items.slice(0, index + 1));\n }\n }\n return null;\n}\n\n/**\n * Build the synthetic summary item (a plain user message) appended to the\n * rebuilt active history.\n */\nexport function buildSummaryItem(summaryBody: string): CompactionItem {\n const trimmed = summaryBody.trim();\n if (!trimmed) {\n throw new EmptyCompactionSummaryError({ stage: \"build_summary_item\" });\n }\n return {\n type: \"message\",\n role: \"user\",\n content: `${SUMMARY_PREFIX}\\n${trimmed}`,\n [COMPACTION_SUMMARY_MARKER]: true,\n };\n}\n\nfunction compactMessageToTokenBudget(item: CompactionItem, maxTokens: number): CompactionItem {\n const text = messageText(item);\n const next = { ...item };\n if (estimateTextTokens(text) > maxTokens) {\n next.content = truncateMiddleByEstimatedTokens(text, maxTokens);\n return next;\n }\n next.content = contentWithoutImages(item);\n return next;\n}\n\nfunction truncateMiddleByEstimatedTokens(text: string, maxTokens: number): string {\n const budget = Math.max(0, Math.floor(maxTokens));\n if (estimateTextTokens(text) <= budget) {\n return text;\n }\n if (estimateTextTokens(USER_MESSAGE_TRUNCATION_MARKER) > budget) {\n return tokenBoundedPrefix(USER_MESSAGE_TRUNCATION_MARKER, budget);\n }\n\n let low = 0;\n let high = text.length;\n let best = USER_MESSAGE_TRUNCATION_MARKER;\n while (low <= high) {\n const keepCodeUnits = Math.floor((low + high) / 2);\n const candidate = middleTruncationCandidate(text, keepCodeUnits);\n if (estimateTextTokens(candidate) <= budget) {\n best = candidate;\n low = keepCodeUnits + 1;\n } else {\n high = keepCodeUnits - 1;\n }\n }\n return best;\n}\n\nfunction middleTruncationCandidate(text: string, keepCodeUnits: number): string {\n const headTarget = Math.ceil(keepCodeUnits / 2);\n const tailTarget = Math.floor(keepCodeUnits / 2);\n const headEnd = validPrefixBoundary(text, headTarget);\n const tailStart = validSuffixBoundary(text, text.length - tailTarget);\n return `${text.slice(0, headEnd)}${USER_MESSAGE_TRUNCATION_MARKER}${text.slice(tailStart)}`;\n}\n\nfunction tokenBoundedPrefix(text: string, maxTokens: number): string {\n let low = 0;\n let high = text.length;\n let best = \"\";\n while (low <= high) {\n const target = Math.floor((low + high) / 2);\n const end = validPrefixBoundary(text, target);\n const candidate = text.slice(0, end);\n if (estimateTextTokens(candidate) <= maxTokens) {\n best = candidate;\n low = target + 1;\n } else {\n high = target - 1;\n }\n }\n return best;\n}\n\n/** Largest boundary at or below target that does not split a surrogate pair. */\nfunction validPrefixBoundary(text: string, target: number): number {\n let boundary = Math.max(0, Math.min(text.length, target));\n if (\n boundary > 0 &&\n boundary < text.length &&\n isHighSurrogate(text.charCodeAt(boundary - 1)) &&\n isLowSurrogate(text.charCodeAt(boundary))\n ) {\n boundary -= 1;\n }\n return boundary;\n}\n\n/** Smallest boundary at or above target that does not split a surrogate pair. */\nfunction validSuffixBoundary(text: string, target: number): number {\n let boundary = Math.max(0, Math.min(text.length, target));\n if (\n boundary > 0 &&\n boundary < text.length &&\n isHighSurrogate(text.charCodeAt(boundary - 1)) &&\n isLowSurrogate(text.charCodeAt(boundary))\n ) {\n boundary += 1;\n }\n return boundary;\n}\n\nfunction isHighSurrogate(codeUnit: number): boolean {\n return codeUnit >= 0xd800 && codeUnit <= 0xdbff;\n}\n\nfunction isLowSurrogate(codeUnit: number): boolean {\n return codeUnit >= 0xdc00 && codeUnit <= 0xdfff;\n}\n\nfunction contentWithoutImages(item: CompactionItem): unknown {\n const content = (item as { content?: unknown }).content;\n if (!Array.isArray(content)) {\n return content;\n }\n return content.filter((part) => {\n if (!part || typeof part !== \"object\") {\n return true;\n }\n const type = (part as { type?: unknown }).type;\n return type !== \"input_image\" && type !== \"image_url\";\n });\n}\n\nfunction messageText(item: CompactionItem): string {\n const content = (item as { content?: unknown }).content;\n if (typeof content === \"string\") {\n return content;\n }\n if (Array.isArray(content)) {\n return content\n .map((part) => {\n if (part && typeof part === \"object\") {\n const record = part as { text?: unknown; content?: unknown };\n if (typeof record.text === \"string\") {\n return record.text;\n }\n if (typeof record.content === \"string\") {\n return record.content;\n }\n }\n return \"\";\n })\n .join(\"\");\n }\n return \"\";\n}\n\nexport function renderCompactionPromptInputForChat(input: readonly CompactionItem[]): string {\n return input.map(renderItem).join(\"\\n\");\n}\n\nfunction renderItem(item: CompactionItem): string {\n const type = itemType(item) ?? \"unknown\";\n if (type === \"message\") {\n const role = itemRole(item) ?? \"assistant\";\n return `[${role}] ${messageText(item)}`;\n }\n if (type === \"reasoning\") {\n return \"[reasoning] (omitted)\";\n }\n if (RESULT_TYPES.has(type)) {\n return `[tool_result] ${resultText(item)}`;\n }\n if (RESULT_TYPE_BY_CALL_TYPE[type]) {\n return `[tool_call ${type}] ${callText(item)}`;\n }\n return `[${type}] ${safeStringify(item)}`;\n}\n\nfunction resultText(item: CompactionItem): string {\n const output = (item as { output?: unknown }).output;\n if (typeof output === \"string\") {\n return output;\n }\n return safeStringify(output ?? item);\n}\n\nfunction callText(item: CompactionItem): string {\n const name = (item as { name?: unknown }).name;\n const args = (item as { arguments?: unknown }).arguments;\n const namePart = typeof name === \"string\" ? name : \"\";\n const argPart = typeof args === \"string\" ? args : safeStringify(args ?? {});\n return `${namePart} ${argPart}`.trim();\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n","// packages/runtime/src/sandbox-computer.ts — the agent computer-use surface (P4.3).\n//\n// A `Computer` impl backed by xdotool (mouse/keyboard/move/click/type/key) +\n// scrot (screenshots), issued through the SAME externally-owned `session` the\n// human watches over Channel B. The agent and the human share ONE :0 display —\n// zero projection: ffmpeg reads exactly the pixels xdotool draws. Exposed to the\n// Agents SDK as a `computerTool` carried by `ComputerUseCapability`, pushed into\n// `buildAgentCapabilities` when `computerUseEnabled && desktopCapableBackend`.\n//\n// This file lives OUTSIDE the @opengeni/runtime/sandbox agent-loop-free leaf\n// (it imports `computerTool` from the @openai/agents root, which the leaf forbids)\n// and is wired into the agent-loop barrel (packages/runtime/src/index.ts).\n//\n// ── Adversarial-review fixes folded in (module 05 §Adversarial) ──────────────\n// F1 exec is OPTIONAL on every provider (Modal has only execCommand) — the\n// primitive dual-paths `session.exec ?? session.execCommand`.\n// F2 execCommand returns a FORMATTED STRING with a metadata preamble, not raw\n// stdout — screenshots read the PNG by running `base64 <path>` over the SAME\n// command primitive and stripping the banner (NOT `session.readFile`: Modal's\n// readFile path-validates against the /workspace root and THROWS\n// \"Sandbox path /tmp/…png escapes the workspace root\", so the /tmp scrot can\n// never be read → empty frame → `image_url: ''` → model 400). This mirrors\n// recording.ts/channel-a fsReadViaExec. Exit codes come from the established\n// `sandboxCommandExitCode` parser, not a `.exitCode` field.\n// F3 exec/execCommand YIELDS (does not wait) — `sandboxCommandStillRunning` is\n// treated as a retriable failure, and the input commands complete well under\n// the yield window.\n// F4 import paths: `computerTool`/`Computer` from `@openai/agents` (root, via\n// the agents-core star re-export); `Capability`/`requireBoundSession` from\n// `@openai/agents/sandbox`. `Button` is NOT exported — the union is inlined.\n// F5 scroll deltas are model PIXELS (often hundreds) — divided by a notch step\n// and clamped, NOT used as literal wheel-click `--repeat` counts.\n\nimport { computerTool, tool, type Computer, type Tool } from \"@openai/agents\";\nimport { Capability, type SandboxSessionLike } from \"@openai/agents/sandbox\";\nimport {\n KeyAction,\n PointerAction,\n PointerButton,\n type DesktopInputRequest,\n} from \"@opengeni/agent-proto\";\nimport { redactSensitiveText } from \"@opengeni/contracts\";\n\nimport { sandboxCommandExitCode, sandboxCommandOutput, sandboxCommandStillRunning } from \"./index\";\n// `stripExecBanner` is the SAME pure helper recording.ts uses to recover the raw\n// command body from Modal's execCommand banner (\"…Output:\\n<body>\"). Imported from\n// the agent-loop-free leaf (importing a pure parser FROM the leaf is allowed — the\n// leaf boundary only forbids the leaf importing the agent loop, not the reverse).\nimport { ensureDisplayStack, stripExecBanner } from \"./sandbox\";\n\n// `requireBoundSession` lives in @openai/agents-core/sandbox/capabilities/base\n// but is NOT re-exported from the public @openai/agents/sandbox barrel, so we\n// inline the trivial bound-session guard (parity with the SDK's own helper).\nfunction requireBoundSession(\n capabilityType: string,\n session?: SandboxSessionLike,\n): SandboxSessionLike {\n if (!session) {\n throw new ComputerUnavailableError(`capability \"${capabilityType}\" used before bind(session)`);\n }\n return session;\n}\n\n// `Button` is intentionally NOT imported (it is not a public export, F4) — the\n// union is inlined and kept in lockstep with @openai/agents-core/computer.d.ts.\ntype ComputerButton = \"left\" | \"right\" | \"wheel\" | \"back\" | \"forward\";\n\nconst DEFAULT_DISPLAY = \":0\";\nconst DEFAULT_DIMENSIONS: [number, number] = [1280, 800];\n// Commands must complete well under this (F3): xdotool/scrot of a 1280x800 PNG is\n// sub-second; the wait gives headroom on a cold gVisor box without masking a wedge.\nconst ACTION_YIELD_MS = 15_000;\n// Model scroll deltas are pixels (F5); one wheel \"notch\" ≈ this many pixels. e2b\n// uses a similar divisor. Clamp keeps a runaway delta from spamming the wheel.\nconst SCROLL_NOTCH_PIXELS = 100;\nconst SCROLL_MAX_CLICKS = 15;\n// screenshot() never hands the model an empty image_url (the SDK turns \"\" into\n// `image_url: ''`, which the model API 400s). A cold/not-yet-painting :0 can yield\n// zero-byte frames for the WHOLE warm-up window of a freshly cold-booted box — Xvfb\n// + XFCE + dbus + font-cache under gVisor routinely take 20s+, and the recovery path\n// after a machine→sandbox swap ALWAYS hits a stone-cold Modal box on its first turn.\n// So we retry across a bounded WALL-CLOCK budget (not a tiny fixed attempt count) with\n// a short pause between tries, so that first post-cold / post-swap screenshot self-heals\n// as the display warms — then FAIL LOUD once the budget is genuinely spent (a display\n// that is dead, not merely warming). ~800ms of retries (the prior 3×400ms) was far too\n// short to ride out a cold gVisor XFCE boot, so the turn failed loud on a transient.\nconst SCREENSHOT_WARMUP_BUDGET_MS = 30_000;\nconst SCREENSHOT_RETRY_DELAY_MS = 750;\n// The screenshot PNG is read back off the box by base64-ing it over the provider's exec\n// channel. Modal's exec collects stdout into a BOUNDED buffer that silently EMPTIES a\n// single oversized read: a fully-painted 1280x800 desktop PNG (~222 KB) base64s to\n// ~296 KB, which trips the cap and returns \"\" — the blank-frame incident. A partly-\n// painted frame (~200 KB base64) slipped under it, which is why this only surfaced once\n// the paint gate began delivering FULLY-painted frames. (Channel-A's file read already\n// caps its own base64-over-exec output for the same reason; the screenshot read was the\n// one large read that didn't bound itself.) We therefore read the file in 3-byte-aligned\n// CHUNKS whose per-read base64 (~131 KB) stays well under the cap, then VALIDATE the\n// reconstructed byte count against the on-box file size. 98304 = 96 KiB, divisible by 3\n// so each chunk's base64 is self-contained (no cross-chunk padding) and concatenating the\n// decoded chunks reconstructs the PNG byte-exactly.\nconst SCREENSHOT_READ_CHUNK_BYTES = 98_304;\n\nexport type SandboxComputerOptions = {\n display?: string; // \":0\"\n dimensions?: [number, number]; // must match the Xvfb geometry\n runAs?: string; // provider runAs (modal/docker: \"sandbox\"); undefined otherwise\n typeDelayMs?: number; // xdotool type --delay (default 12ms)\n readOnly?: boolean; // when true, every WRITE action throws ComputerReadOnlyError\n screenshotTmpDir?: string; // \"/tmp\"\n // How long screenshot() keeps retrying an empty (still-warming) frame before it\n // FAILS LOUD, and the pause between tries. Defaults to the cold-boot warm-up budget;\n // exposed mainly so tests can shrink it (a real caller wants the full budget).\n screenshotWarmupBudgetMs?: number;\n screenshotRetryDelayMs?: number;\n /**\n * One turn-scoped preparation hook, invoked by the first real computer action.\n * The agent may advertise computer-use on every turn, but merely advertising the\n * tool must not boot Xvfb/XFCE or start a recording. The runtime capability owns\n * this hook and uses it to bring up :0 (and optionally notify the worker) only\n * after the model actually chooses a computer tool.\n */\n prepare?: (session: SandboxSessionLike) => Promise<void>;\n};\n\n// X keysym map for keypress(): model key names → xdotool keysyms.\nconst KEYSYM: Record<string, string> = {\n ctrl: \"ctrl\",\n control: \"ctrl\",\n alt: \"alt\",\n option: \"alt\",\n shift: \"shift\",\n cmd: \"super\",\n meta: \"super\",\n win: \"super\",\n super: \"super\",\n enter: \"Return\",\n return: \"Return\",\n tab: \"Tab\",\n esc: \"Escape\",\n escape: \"Escape\",\n backspace: \"BackSpace\",\n delete: \"Delete\",\n space: \"space\",\n up: \"Up\",\n down: \"Down\",\n left: \"Left\",\n right: \"Right\",\n pageup: \"Prior\",\n pagedown: \"Next\",\n home: \"Home\",\n end: \"End\",\n};\nfunction toKeysym(k: string): string {\n const low = k.toLowerCase();\n if (KEYSYM[low]) return KEYSYM[low];\n if (/^f([1-9]|1[0-2])$/.test(low)) return low.toUpperCase();\n return low.length === 1 ? low : k;\n}\nconst BUTTON_NUM: Record<ComputerButton, number> = {\n left: 1,\n wheel: 2,\n right: 3,\n back: 8,\n forward: 9,\n};\n\n// The structural slice of a provider session computer-use drives. exec and\n// execCommand are optional because the SDK's SandboxSessionLike leaves them\n// optional (Modal implements execCommand, not exec — F1). readFile is intentionally\n// NOT in this type: screenshots read the /tmp PNG via `base64 <path>` over\n// exec/execCommand (readFile path-validates against /workspace and rejects /tmp).\ntype ExecResultLike = {\n output?: string;\n stdout?: string;\n stderr?: string;\n exitCode?: number | null;\n sessionId?: number;\n};\ntype ComputerSession = {\n // A native provider exec returns a structured `ExecResultLike`; the routing proxy\n // fronting a Modal box returns the execCommand banner STRING. Both are handled.\n exec?: (args: {\n cmd: string;\n runAs?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<ExecResultLike | string>;\n execCommand?: (args: {\n cmd: string;\n runAs?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<string>;\n};\n\n/** No exec/execCommand on the session, or the display is not up. */\nexport class ComputerUnavailableError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ComputerUnavailableError\";\n }\n}\n/** The screenshot file read back SHORT of its on-box byte size — a chunk was truncated\n * by the provider's exec-output cap. This is deterministic, NOT a warm-up transient, so\n * it fails LOUD immediately with the byte counts (never a silent blank the model would\n * read as a real empty screen) and is not retried. */\nexport class ScreenshotReadError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ScreenshotReadError\";\n }\n}\n/** A write action attempted while readOnly. */\nexport class ComputerReadOnlyError extends Error {\n constructor() {\n super(\"computer-use is read-only — write actions are disabled\");\n this.name = \"ComputerReadOnlyError\";\n }\n}\n/** A nonzero xdotool/scrot exit, OR a command that did not finish before the\n * yield window (F3 — \"still running\" is a failure, not a silent success). */\nexport class ComputerActionError extends Error {\n constructor(\n public cmd: string,\n public exitCode: number,\n public stderr: string,\n ) {\n super(`computer action failed (${exitCode}): ${cmd}${stderr ? `\\n${stderr}` : \"\"}`);\n this.name = \"ComputerActionError\";\n }\n}\n\n/**\n * The Computer the agent drives. Every action issues ONE shell line through the\n * externally-owned session (exec ?? execCommand, F1), prefixed with the display.\n * screenshot() scrots to a /tmp file and reads the RAW bytes by running\n * `base64 <path>` over the SAME command primitive and stripping the banner — NOT\n * `session.readFile` (Modal's readFile path-validates against /workspace and rejects\n * /tmp with \"escapes the workspace root\", which would yield an empty frame and 400\n * the model). The base64-over-exec path is /tmp-readable and binary-safe.\n */\nexport class SandboxComputer implements Computer {\n readonly environment = \"ubuntu\" as const;\n readonly dimensions: [number, number];\n private session: ComputerSession & SandboxSessionLike;\n private readonly display: string;\n private readonly runAs?: string;\n private readonly typeDelayMs: number;\n private readonly readOnly: boolean;\n private readonly tmp: string;\n private readonly screenshotWarmupBudgetMs: number;\n private readonly screenshotRetryDelayMs: number;\n private readonly prepare: ((session: SandboxSessionLike) => Promise<void>) | undefined;\n private prepared = false;\n private preparation: Promise<void> | null = null;\n\n constructor(session: SandboxSessionLike, opts: SandboxComputerOptions = {}) {\n this.session = session as ComputerSession & SandboxSessionLike;\n this.display = opts.display ?? DEFAULT_DISPLAY;\n this.dimensions = opts.dimensions ?? DEFAULT_DIMENSIONS;\n if (opts.runAs !== undefined) {\n this.runAs = opts.runAs;\n }\n this.typeDelayMs = opts.typeDelayMs ?? 12;\n this.readOnly = opts.readOnly ?? false;\n this.tmp = opts.screenshotTmpDir ?? \"/tmp\";\n this.screenshotWarmupBudgetMs = opts.screenshotWarmupBudgetMs ?? SCREENSHOT_WARMUP_BUDGET_MS;\n this.screenshotRetryDelayMs = opts.screenshotRetryDelayMs ?? SCREENSHOT_RETRY_DELAY_MS;\n this.prepare = opts.prepare;\n }\n\n /** Rebind to a freshly resumed-by-id session after a box rollover / re-establish. */\n rebind(session: SandboxSessionLike) {\n this.session = session as ComputerSession & SandboxSessionLike;\n this.prepared = false;\n this.preparation = null;\n }\n\n private async prepareOnce(): Promise<void> {\n if (this.prepared) return;\n if (!this.prepare) {\n // No lazy hook means the caller handed us an already-ready display, which\n // is the historical direct-construction behavior used by embedders/tests.\n this.prepared = true;\n return;\n }\n this.preparation ??= this.prepare(this.session);\n try {\n await this.preparation;\n this.prepared = true;\n } catch (error) {\n // A viewer may have contended the display flock or a provider operation may\n // have failed transiently. Let a later computer call retry; never cache a\n // rejected preparation as the permanent state of the turn.\n this.preparation = null;\n throw error;\n }\n }\n\n // The single command primitive. Dual-paths exec/execCommand (F1), then uses the\n // established string-aware parsers (F2/F3): exitCode from the preamble, and\n // \"still running\" → a retriable failure. Returns the command OUTPUT body.\n private async x(cmd: string): Promise<string> {\n await this.prepareOnce();\n const args = {\n cmd: `DISPLAY=${this.display} ${cmd}`,\n ...(this.runAs ? { runAs: this.runAs } : {}),\n yieldTimeMs: ACTION_YIELD_MS,\n maxOutputTokens: 4_000,\n };\n let result: ExecResultLike | string;\n if (typeof this.session.exec === \"function\") {\n result = await this.session.exec(args);\n } else if (typeof this.session.execCommand === \"function\") {\n result = await this.session.execCommand(args);\n } else {\n throw new ComputerUnavailableError(\"session cannot run commands (no exec/execCommand)\");\n }\n const output = sandboxCommandOutput(result);\n if (sandboxCommandStillRunning(result)) {\n // F3: the command exceeded the yield window. WARN AND RETURN rather than\n // throw. Throwing here causes the SDK's catch in `_runComputerActionAndScreenshot`\n // to set output='' and build `{image_url:\"\"}` → Azure 400. By returning\n // instead, the SDK proceeds past the action loop and calls computer.screenshot()\n // so the model gets the REAL current frame for its next step.\n //\n // screenshot()'s FAIL-LOUD + retry contract is preserved: if scrot itself\n // times out (very unlikely at 15 s), x() returns here, readScreenshotBytes\n // produces empty bytes, and the retry loop eventually throws. The wire-level\n // backstop in computerCallNormalizingFetch is also in place as a second net.\n console.warn(\n `[SandboxComputer] action command did not finish before the ${ACTION_YIELD_MS}ms yield window — proceeding to screenshot: ${redactSensitiveText(cmd)}`,\n );\n return output;\n }\n const exitCode = sandboxCommandExitCode(result);\n if (exitCode !== null && exitCode !== 0) {\n throw new ComputerActionError(cmd, exitCode, output);\n }\n return output;\n }\n\n private guardWrite() {\n if (this.readOnly) throw new ComputerReadOnlyError();\n }\n private shq(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n }\n\n async screenshot(): Promise<string> {\n // F2: scrot to a /tmp file, then read the RAW PNG bytes by running `base64\n // <path>` over the SAME command primitive (exec ?? execCommand) and stripping\n // the banner — NOT `session.readFile`. On Modal, readFile path-validates the\n // path against the /workspace root and THROWS for /tmp (\"Sandbox path\n // /tmp/og-shot-*.png escapes the workspace root\"), so the scrot could never be\n // read → empty frame → `image_url: ''` → the model 400s. The base64-over-exec\n // mechanism (mirroring Channel A's bounded file reads\n // fsReadViaExec) is /tmp-readable and binary-safe. We do NOT use execCommand's\n // body via the `this.x()` parser — that drops the execCommand string body; the\n // banner is stripped explicitly here so the base64 payload survives intact.\n //\n // CRITICAL CONTRACT: this NEVER returns an empty string. The Agents SDK builds\n // the model-facing image as `data:image/png;base64,${output}` — so an empty\n // `output` becomes `image_url: ''`, which the model API rejects with\n // \"400 Invalid input[N].output.image_url, expected a valid URL\" and kills the\n // turn. An empty/failed frame is therefore a THROW (a clear action failure the\n // SDK surfaces), never a silent \"\". We also self-heal a transient cold-display\n // frame: bounded retries with a short wait between attempts, so a :0 that is up\n // but momentarily not painting (XFCE/dbus still warming) recovers without\n // failing the turn.\n let lastError: unknown;\n const deadline = Date.now() + this.screenshotWarmupBudgetMs;\n let attempt = 0;\n // Retry across a WALL-CLOCK budget (not a fixed count): a stone-cold box on the\n // first post-swap / post-cold turn can take 20s+ to paint, and a zero-byte frame\n // is a KNOWN transient during that warm-up — not a reason to fail the turn.\n while (true) {\n if (attempt > 0) {\n await new Promise((r) => setTimeout(r, this.screenshotRetryDelayMs));\n }\n attempt++;\n const f = `${this.tmp}/og-shot-${Date.now()}-${Math.random().toString(36).slice(2)}.png`;\n try {\n await this.x(`scrot --pointer --overwrite ${f}`);\n const bytes = await this.readScreenshotBytes(f);\n if (bytes.length === 0) {\n // A cold/not-yet-painting :0 yields a zero-byte frame. Retry rather than\n // hand the model an empty image_url; throw once the budget is spent.\n throw new ComputerUnavailableError(\n \"scrot produced an empty screenshot (display not up?)\",\n );\n }\n return Buffer.from(bytes).toString(\"base64\");\n } catch (error) {\n lastError = error;\n // A short/truncated read is deterministic (the exec-output cap), not a warm-up\n // transient — retrying only burns the budget and delays a legible failure. Fail\n // loud NOW (the `finally` still cleans up the temp file).\n if (error instanceof ScreenshotReadError) {\n throw error;\n }\n } finally {\n // Best-effort cleanup on every attempt (success OR failure); never mask the\n // screenshot result.\n // If preparation itself failed, scrot never ran and no file exists. Do\n // not route cleanup through x(), because that would retry the expensive\n // display preparation merely to delete a nonexistent path.\n if (this.prepared) {\n await this.x(`rm -f ${f}`).catch(() => undefined);\n }\n }\n // Stop once the warm-up budget is spent — the NEXT sleep would push us past it.\n if (Date.now() + this.screenshotRetryDelayMs >= deadline) {\n break;\n }\n }\n // Exhausted the warm-up budget: FAIL LOUD. A clear throw is the only acceptable\n // outcome — returning \"\" here would surface to the model as an invalid empty\n // image_url. Reaching here means the display was still dead after ~30s, not merely\n // warming, so a hard action failure is correct.\n if (lastError instanceof Error) {\n throw lastError;\n }\n throw new ComputerUnavailableError(\"scrot produced an empty screenshot (display not up?)\");\n }\n\n // Run a read-only command over the SAME command primitive computer actions use\n // (exec ?? execCommand) and return its RAW stdout body — NOT `session.readFile` (Modal\n // path-validates against /workspace and rejects /tmp) and NOT `this.x()` (its\n // `sandboxCommandOutput` parser drops the execCommand STRING body). exec exposes a\n // structured stdout; execCommand returns the formatted STRING, so we strip its banner\n // (\"…Output:\\n<body>\") to recover the body.\n //\n // ROUTING-PROXY SEAM: when the selfhosted feature is on, the turn's box is wrapped in a\n // `RoutingSandboxSession`, which ALWAYS exposes an `exec` method — but for a Modal-backed\n // box (no native `exec`) that method internally falls back to `execCommand` and returns\n // the formatted STRING, not a `{output}` object. `sandboxCommandOutput` returns \"\" for a\n // string, so a naive `sandboxCommandOutput(await session.exec())` silently dropped the\n // whole screenshot body → empty read → \"display not up\" error card on EVERY Modal\n // computer-use turn once routing was enabled. So a STRING exec result is banner-stripped\n // exactly like the direct execCommand path; only a structured object goes to\n // sandboxCommandOutput.\n private async readCmdRaw(cmd: string): Promise<string> {\n const args = {\n cmd,\n ...(this.runAs ? { runAs: this.runAs } : {}),\n yieldTimeMs: ACTION_YIELD_MS,\n // null disables the provider's TOKEN truncation; the byte cap this method chunks\n // around is a separate, lower-level exec-stdout buffer limit.\n maxOutputTokens: null as unknown as number,\n };\n if (typeof this.session.exec === \"function\") {\n const result = await this.session.exec(args);\n // A routing proxy fronting a Modal box returns the execCommand banner STRING;\n // a native structured exec returns an object. Handle both so neither silently\n // yields an empty body.\n return typeof result === \"string\" ? stripExecBanner(result) : sandboxCommandOutput(result);\n }\n if (typeof this.session.execCommand === \"function\") {\n return stripExecBanner(await this.session.execCommand(args));\n }\n throw new ComputerUnavailableError(\n \"session cannot run commands (no exec/execCommand) — screenshots unavailable\",\n );\n }\n\n // Read the screenshot PNG bytes off the box. A SINGLE `base64 <file>` over Modal's\n // exec silently returns \"\" once the base64 exceeds the exec-stdout buffer cap (a full\n // desktop ~296 KB base64 trips it — the blank-frame incident). So we size the file\n // first, then base64 it in SCREENSHOT_READ_CHUNK_BYTES-sized, 3-byte-aligned chunks\n // (each read's base64 stays well under the cap) and reconstruct — validating the total\n // against the on-box size and failing LOUD on any short read rather than handing back a\n // truncated/blank frame. Binary-safe: base64 is plain ASCII over stdout.\n private async readScreenshotBytes(path: string): Promise<Uint8Array> {\n // On-box byte size (tiny output — always safe). A still-warming :0 can yield a\n // zero-byte scrot file; report empty so the caller retries within its warm-up budget.\n const sizeRaw = (await this.readCmdRaw(`wc -c < ${path} 2>/dev/null`)).replace(/[^0-9]/g, \"\");\n const fileSize = Number.parseInt(sizeRaw, 10);\n if (!Number.isFinite(fileSize) || fileSize <= 0) return new Uint8Array();\n\n const chunks: Buffer[] = [];\n const nChunks = Math.ceil(fileSize / SCREENSHOT_READ_CHUNK_BYTES);\n for (let i = 0; i < nChunks; i++) {\n // `dd bs=CHUNK skip=i count=1` reads bytes [i*CHUNK, (i+1)*CHUNK); CHUNK % 3 == 0\n // so each chunk's base64 is self-contained and decoded chunks concatenate exactly.\n const raw = await this.readCmdRaw(\n `dd if=${path} bs=${SCREENSHOT_READ_CHUNK_BYTES} skip=${i} count=1 2>/dev/null | base64`,\n );\n chunks.push(Buffer.from(raw.replace(/\\s+/g, \"\"), \"base64\"));\n }\n const bytes = Buffer.concat(chunks);\n if (bytes.length !== fileSize) {\n throw new ScreenshotReadError(\n `screenshot read reconstructed ${bytes.length}B of ${fileSize}B (${nChunks} chunk(s), path=${path}) — a chunk was truncated by the exec-output cap; frame incomplete`,\n );\n }\n return new Uint8Array(bytes);\n }\n\n async click(xp: number, yp: number, button: ComputerButton) {\n this.guardWrite();\n await this.x(`xdotool mousemove --sync ${xp} ${yp} click ${BUTTON_NUM[button] ?? 1}`);\n }\n async doubleClick(xp: number, yp: number) {\n this.guardWrite();\n await this.x(`xdotool mousemove --sync ${xp} ${yp} click --repeat 2 --delay 60 1`);\n }\n async move(xp: number, yp: number) {\n this.guardWrite();\n await this.x(`xdotool mousemove --sync ${xp} ${yp}`);\n }\n async scroll(xp: number, yp: number, sx: number, sy: number) {\n this.guardWrite();\n // F5: model deltas are PIXELS — convert to wheel notches, clamp.\n const notches = (px: number): number =>\n Math.min(SCROLL_MAX_CLICKS, Math.max(0, Math.round(Math.abs(px) / SCROLL_NOTCH_PIXELS)));\n const vBtn = sy < 0 ? 4 : 5;\n const hBtn = sx < 0 ? 6 : 7;\n const vN = notches(sy);\n const hN = notches(sx);\n let cmd = `xdotool mousemove --sync ${xp} ${yp}`;\n if (vN) cmd += ` click --repeat ${vN} ${vBtn}`;\n if (hN) cmd += ` click --repeat ${hN} ${hBtn}`;\n await this.x(cmd);\n }\n async type(text: string) {\n this.guardWrite();\n await this.x(`xdotool type --delay ${this.typeDelayMs} -- ${this.shq(text)}`);\n }\n async keypress(keys: string[]) {\n this.guardWrite();\n const combo = keys.map(toKeysym).join(\"+\");\n await this.x(`xdotool key -- ${this.shq(combo)}`);\n }\n async drag(path: [number, number][]) {\n this.guardWrite();\n if (path.length === 0) return;\n const [sx0, sy0] = path[0]!;\n let cmd = `xdotool mousemove --sync ${sx0} ${sy0} mousedown 1`;\n for (const [px, py] of path.slice(1)) cmd += ` mousemove --sync ${px} ${py}`;\n cmd += ` mouseup 1`;\n await this.x(cmd);\n }\n async wait() {\n await new Promise((r) => setTimeout(r, 1000));\n }\n}\n\n// ── The native-desktop computer (self-hosted / macOS) ────────────────────────\n//\n// `SandboxComputer` drives the desktop by shelling out to xdotool/scrot over the\n// session's `exec` — which needs those X utilities installed in the box image and\n// only works under X11. A SELF-HOSTED machine (macOS OR bring-your-own Linux) has\n// neither guarantee, so it drives the desktop NATIVELY over the control plane: the\n// Rust agent injects input via CGEvent (macOS) / XTEST (Linux) and captures via\n// ScreenCaptureKit / x11, exposed as the two `SelfhostedSession` ops below. No\n// xdotool/scrot dependency; works on macOS.\n\n/** The structural slice of a self-hosted session the native computer drives — the\n * two control-plane ops added in session.ts. Kept structural (NOT an import of\n * `SelfhostedSession`) so this agent-loop file never hard-couples to the sandbox\n * leaf; the duck-typed `isNativeDesktopSession` probe (below) selects on it. */\nexport type NativeDesktopSession = {\n desktopInput(event: DesktopInputRequest[\"event\"]): Promise<void>;\n // `nativeWidth`/`nativeHeight` are the PRE-DOWNSCALE capture geometry (equal to\n // width/height when the agent did not have to shrink the PNG to fit the transport\n // budget). NativeDesktopComputer scales model clicks from the ENCODED pixel space\n // back to native pixels using their ratio before injecting.\n screenshot(): Promise<{\n png: Uint8Array;\n width: number;\n height: number;\n nativeWidth: number;\n nativeHeight: number;\n }>;\n};\n\n/** Model `Button` → wire `PointerButton`. The proto has no back/forward button, so\n * those degrade to UNSPECIFIED (the agent ignores an unmapped button rather than\n * mis-clicking). A total record so indexing is exhaustive. */\nconst POINTER_BUTTON: Record<ComputerButton, PointerButton> = {\n left: PointerButton.POINTER_BUTTON_LEFT,\n right: PointerButton.POINTER_BUTTON_RIGHT,\n wheel: PointerButton.POINTER_BUTTON_MIDDLE,\n back: PointerButton.POINTER_BUTTON_UNSPECIFIED,\n forward: PointerButton.POINTER_BUTTON_UNSPECIFIED,\n};\n\n// Native capture (ScreenCaptureKit / x11) can hand back a null/empty FIRST frame in\n// the moments right after the agent connects — the capture stream still warming — the\n// same class of transient the scrot path retries around for a cold :0. Native capture\n// is normally sub-second, so the warm-up budget is much shorter than the scrot path's\n// 30 s cold-Modal-box budget; enough to ride a first-frame miss, not enough to hang a\n// turn on a genuinely dead capture. A TERMINAL failure (permission denied) short-\n// circuits the budget and fails immediately.\nconst NATIVE_SCREENSHOT_WARMUP_BUDGET_MS = 6_000;\nconst NATIVE_SCREENSHOT_RETRY_DELAY_MS = 400;\n\nexport type NativeDesktopComputerOptions = {\n dimensions?: [number, number]; // the display geometry (must match the capture size)\n environment?: NonNullable<Computer[\"environment\"]>; // \"ubuntu\" (default) | \"mac\" | ...; model uses it for OS key conventions\n readOnly?: boolean; // when true, every WRITE action throws ComputerReadOnlyError\n screenshotWarmupBudgetMs?: number; // wall-clock budget to retry a warming/empty first frame\n screenshotRetryDelayMs?: number; // delay between warm-up retries\n};\n\n/** A capture failure that RETRYING cannot cure — Screen Recording (TCC) has not been\n * granted to the agent, so every capture will deny until the user grants it. We fail\n * FAST on this rather than burn the warm-up budget, and surface the reason verbatim so\n * the operator sees \"grant Screen Recording\", not a blank screen. Matches the agent's\n * `capture_rgba` denial strings (\"Screen Recording permission is not granted\",\n * \"no shareable content (Screen Recording denied?)\"). */\nfunction isTerminalCaptureDenial(error: unknown): boolean {\n const msg = (error instanceof Error ? error.message : String(error ?? \"\")).toLowerCase();\n return (\n msg.includes(\"screen recording\") ||\n msg.includes(\"permission is not granted\") ||\n msg.includes(\"consent\")\n );\n}\n\n/**\n * A `Computer` that drives a SELF-HOSTED machine's OWN desktop NATIVELY over the\n * control plane (`desktopInput` inject + `screenshot` capture on the bound\n * `SelfhostedSession`) instead of xdotool/scrot over `exec`. Consent + epoch are\n * enforced AGENT-side, so an unconsented inject surfaces the session's mapped\n * control error.\n *\n * screenshot() returns raw base64 with NO data-URL prefix — the EXACT contract of\n * `SandboxComputer.screenshot`: the Agents SDK wraps it as\n * `data:image/png;base64,${output}`, so an empty string would become\n * `image_url: ''` and 400 the model turn. An empty PNG therefore THROWS\n * `ComputerUnavailableError` (mirroring SandboxComputer's empty-guard) — the model\n * never receives an empty image_url.\n */\nexport class NativeDesktopComputer implements Computer {\n readonly environment: NonNullable<Computer[\"environment\"]>;\n readonly dimensions: [number, number];\n private session: NativeDesktopSession;\n private readonly readOnly: boolean;\n private readonly screenshotWarmupBudgetMs: number;\n private readonly screenshotRetryDelayMs: number;\n // The ENCODED vs NATIVE geometry of the MOST RECENT screenshot the model saw. The\n // model computes click coordinates in the encoded-pixel space of that screenshot;\n // when the agent downscaled the PNG to fit the transport budget, encoded < native,\n // so we scale coordinates back up to native pixels before injecting (the agent's\n // native inject — macOS CGEvent / Linux XTEST — expects native-pixel coordinates,\n // exactly as it received them pre-downscale). Null until the first screenshot;\n // equal encoded==native (or absent) ⇒ scale factor 1.0 ⇒ byte-identical behavior.\n private lastEncoded: [number, number] | null = null;\n private lastNative: [number, number] | null = null;\n\n constructor(session: NativeDesktopSession, opts: NativeDesktopComputerOptions = {}) {\n this.session = session;\n this.dimensions = opts.dimensions ?? DEFAULT_DIMENSIONS;\n // Default \"ubuntu\" (self-hosted Linux is the near-term target); a macOS session\n // should pass \"mac\" so the model uses ⌘-based shortcuts — see the coordinate TODO.\n this.environment = opts.environment ?? \"ubuntu\";\n this.readOnly = opts.readOnly ?? false;\n this.screenshotWarmupBudgetMs =\n opts.screenshotWarmupBudgetMs ?? NATIVE_SCREENSHOT_WARMUP_BUDGET_MS;\n this.screenshotRetryDelayMs = opts.screenshotRetryDelayMs ?? NATIVE_SCREENSHOT_RETRY_DELAY_MS;\n }\n\n /** Rebind to a freshly resumed-by-id session after a box rollover / re-establish. */\n rebind(session: NativeDesktopSession) {\n this.session = session;\n }\n\n private guardWrite() {\n if (this.readOnly) throw new ComputerReadOnlyError();\n }\n\n /** Scale a coordinate the model expressed in the MOST RECENT screenshot's\n * ENCODED pixel space back to NATIVE pixels. When the last frame was not\n * downscaled (encoded == native), or no screenshot has been taken yet, this is a\n * 1:1 identity — the byte-identical current behavior. The agent then applies its\n * own platform mapping (macOS divides native pixels by the backing scale to reach\n * CGEvent points; Linux XTEST is 1:1) exactly as it did pre-downscale. */\n private toNative(x: number, y: number): { x: number; y: number } {\n const enc = this.lastEncoded;\n const nat = this.lastNative;\n if (!enc || !nat || enc[0] <= 0 || enc[1] <= 0) return { x, y };\n if (enc[0] === nat[0] && enc[1] === nat[1]) return { x, y };\n return {\n x: Math.round((x * nat[0]) / enc[0]),\n y: Math.round((y * nat[1]) / enc[1]),\n };\n }\n\n private async pointer(\n x: number,\n y: number,\n action: PointerAction,\n button: PointerButton,\n ): Promise<void> {\n // COORDINATE SEAM: the model computes x/y against the pixels of the screenshot it\n // just saw — which the agent may have DOWNSCALED to fit the transport's max\n // payload (a full-res Retina/busy screen exceeds NATS's 1 MiB default). We scale\n // those encoded-pixel coordinates back to native pixels here, using the native\n // geometry the last screenshot reported, so the agent's native inject lands the\n // click where the model intended. When no downscale occurred the factor is 1.0\n // and the coordinates pass through unchanged. Self-hosted Linux (XTEST/x11) and\n // any non-downscaled frame are 1:1 and unaffected.\n const n = this.toNative(x, y);\n await this.session.desktopInput({\n $case: \"pointer\",\n pointer: { x: n.x, y: n.y, action, button },\n });\n }\n\n async screenshot(): Promise<string> {\n // CRITICAL CONTRACT (mirrors SandboxComputer.screenshot): NEVER return \"\". The\n // Agents SDK builds the model image as `data:image/png;base64,${output}`; an\n // empty output → `image_url: ''`. On the hosted computer_use_preview path the SDK\n // catches a throw here, sets output='', and the wire-seam sanitizer rewrites the\n // empty image_url to a BLANK 1×1 placeholder to dodge a 400 — so a capture MISS\n // silently reaches the model as a \"blank desktop\" it then confidently reports.\n //\n // Native capture (ScreenCaptureKit / x11) can hand back a null/empty FIRST frame\n // in the moments right after the agent connects (the capture stream warming) — the\n // same transient the scrot path retries around for a cold :0. This path previously\n // did a SINGLE capture, so one warm-up miss became a blank. We now RETRY across a\n // bounded budget and, on a terminal failure, FAIL LOUD with the agent's actual\n // reason (logged) — never a silent blank. A permission (TCC) denial is terminal:\n // retrying cannot grant Screen Recording, so we break immediately.\n let lastError: unknown;\n const deadline = Date.now() + this.screenshotWarmupBudgetMs;\n let attempt = 0;\n while (true) {\n if (attempt > 0) {\n await new Promise((r) => setTimeout(r, this.screenshotRetryDelayMs));\n }\n attempt++;\n try {\n const { png, width, height, nativeWidth, nativeHeight } = await this.session.screenshot();\n if (png.length === 0) {\n // A warming capture yields an empty frame — retry rather than hand the model\n // a blank; throw once the budget is spent.\n throw new ComputerUnavailableError(\n \"native desktop screenshot returned an empty frame (display not up?)\",\n );\n }\n // Record the encoded (what the model sees) vs native geometry of THIS frame so\n // the next click/move/scroll/drag scales its coordinates back to native pixels.\n this.lastEncoded = [width, height];\n this.lastNative = [nativeWidth || width, nativeHeight || height];\n return Buffer.from(png).toString(\"base64\");\n } catch (error) {\n lastError = error;\n // A permission denial will deny on every retry — fail fast with the reason.\n if (isTerminalCaptureDenial(error)) break;\n }\n // Stop once the warm-up budget is spent — the NEXT sleep would push us past it.\n if (Date.now() + this.screenshotRetryDelayMs >= deadline) {\n break;\n }\n }\n // Exhausted the budget (or hit a terminal denial): FAIL LOUD. Log the specific\n // reason so the failure is DIAGNOSABLE (not a silent blank the model misreads),\n // then rethrow — never return \"\".\n const reason = redactSensitiveText(\n lastError instanceof Error ? lastError.message : String(lastError),\n );\n console.warn(\n `[NativeDesktopComputer] screenshot failed after ${attempt} attempt(s): ${reason}`,\n );\n if (lastError instanceof Error) {\n throw lastError;\n }\n throw new ComputerUnavailableError(\n \"native desktop screenshot returned an empty frame (display not up?)\",\n );\n }\n\n async click(x: number, y: number, button: ComputerButton) {\n this.guardWrite();\n await this.pointer(\n x,\n y,\n PointerAction.POINTER_ACTION_CLICK,\n POINTER_BUTTON[button] ?? PointerButton.POINTER_BUTTON_LEFT,\n );\n }\n async doubleClick(x: number, y: number) {\n this.guardWrite();\n await this.pointer(\n x,\n y,\n PointerAction.POINTER_ACTION_DOUBLE_CLICK,\n PointerButton.POINTER_BUTTON_LEFT,\n );\n }\n async move(x: number, y: number) {\n this.guardWrite();\n await this.pointer(\n x,\n y,\n PointerAction.POINTER_ACTION_MOVE,\n PointerButton.POINTER_BUTTON_UNSPECIFIED,\n );\n }\n async scroll(x: number, y: number, sx: number, sy: number) {\n this.guardWrite();\n // The scroll ANCHOR (x,y) is a screenshot-pixel position → scale to native like a\n // click. The deltas (sx,sy) are relative scroll AMOUNTS, not positions; the agent\n // owns the platform-appropriate wheel translation, so they pass through unscaled\n // (no xdotool \"notch\" quantization here — that is an xdotool-specific artifact).\n const n = this.toNative(x, y);\n await this.session.desktopInput({\n $case: \"scroll\",\n scroll: { x: n.x, y: n.y, deltaX: sx, deltaY: sy },\n });\n }\n async type(text: string) {\n this.guardWrite();\n // A literal text burst: isText:true tells the agent to type the string verbatim\n // (Unicode-aware) rather than interpret it as a key name.\n await this.session.desktopInput({\n $case: \"key\",\n key: { key: text, isText: true, action: KeyAction.KEY_ACTION_PRESS },\n });\n }\n async keypress(keys: string[]) {\n this.guardWrite();\n // A chord (\"ctrl+c\") as ONE non-text KeyEvent (isText:false ⇒ interpret as key\n // names). We send the model's PLATFORM-INDEPENDENT key names joined with \"+\" —\n // NOT xdotool X keysyms (SandboxComputer's toKeysym maps to \"Return\"/\"super\"/\n // \"Prior\", which are X-specific and wrong for the macOS CGEvent path). The agent\n // owns the per-platform key-name → keycode mapping (the KeyEvent.key contract).\n await this.session.desktopInput({\n $case: \"key\",\n key: { key: keys.join(\"+\"), isText: false, action: KeyAction.KEY_ACTION_PRESS },\n });\n }\n async drag(path: [number, number][]) {\n this.guardWrite();\n if (path.length === 0) return;\n // Press at the start, move through each waypoint with the button held, release at\n // the last point. The agent tracks button state across the DOWN → MOVE… → UP.\n const [sx, sy] = path[0]!;\n await this.pointer(\n sx,\n sy,\n PointerAction.POINTER_ACTION_DOWN,\n PointerButton.POINTER_BUTTON_LEFT,\n );\n for (const [px, py] of path.slice(1)) {\n await this.pointer(\n px,\n py,\n PointerAction.POINTER_ACTION_MOVE,\n PointerButton.POINTER_BUTTON_LEFT,\n );\n }\n const [ex, ey] = path[path.length - 1]!;\n await this.pointer(ex, ey, PointerAction.POINTER_ACTION_UP, PointerButton.POINTER_BUTTON_LEFT);\n }\n async wait() {\n await new Promise((r) => setTimeout(r, 1000));\n }\n}\n\n/**\n * Backend-aware SELECTION discriminator: a SELF-HOSTED session exposes the two\n * native control-plane ops (`desktopInput` + `screenshot`); a MODAL session does\n * not (it drives the desktop via xdotool/scrot over `exec`). Duck-typing on those\n * two methods keeps this file from hard-importing `SelfhostedSession` (avoiding an\n * agent-loop ↔ sandbox-leaf import coupling) and is future-proof: any backend that\n * grows native inject/capture is picked up automatically.\n */\nexport function isNativeDesktopSession(\n session: SandboxSessionLike,\n): session is SandboxSessionLike & NativeDesktopSession {\n const s = session as Partial<NativeDesktopSession>;\n return typeof s.desktopInput === \"function\" && typeof s.screenshot === \"function\";\n}\n\n// ── Function-transport (codex / text backend) computer tools ─────────────────\n//\n// The SDK emits computer-use ONLY as the HOSTED `computer_use_preview` tool, which\n// the codex / ChatGPT backend rejects (it accepts only function/custom/web_search\n// tool types) — so on codex the hosted tool is unusable and the agent has nothing\n// to drive the desktop with. We mirror EXACTLY how the SDK's filesystem capability\n// degrades `view_image` for the text transport: when the bound model does NOT\n// support the structured tool-output transport, emit a set of FUNCTION tools that\n// route to the SAME bound `Computer`, and hand the model the screen by rendering\n// the screenshot image-output as a text-transport data URL — the identical two-step\n// `imageOutputFromBytes` → `renderImageForTextTransport` the SDK's text `view_image`\n// uses. Those three helpers are NOT public exports of `@openai/agents` /\n// `@openai/agents/sandbox` (they live in the SDK's private capabilities/transport +\n// shared/media modules, unreachable via the package `exports` map), so — mirroring\n// selfhosted/session.ts's local `sniffImageMediaType` — the three tiny pure helpers\n// are reimplemented here in lockstep with the SDK.\n\n/** The SDK's tool-output image shape (@openai/agents-core shared/media `ToolOutputImage`). */\ntype ToolOutputImage = { type: \"image\"; image: { data: Uint8Array; mediaType: string } };\n\n/** Magic-byte image sniff, in lockstep with the SDK's `sniffImageMediaType`\n * (shared/media). Screenshots are always PNG (scrot / ScreenCaptureKit / x11), so\n * an unrecognized header defaults to image/png rather than failing the frame. */\nfunction sniffScreenshotMediaType(bytes: Uint8Array): string {\n if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47)\n return \"image/png\";\n if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return \"image/jpeg\";\n if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38)\n return \"image/gif\";\n if (\n bytes[0] === 0x52 &&\n bytes[1] === 0x49 &&\n bytes[2] === 0x46 &&\n bytes[3] === 0x46 &&\n bytes[8] === 0x57 &&\n bytes[9] === 0x45 &&\n bytes[10] === 0x42 &&\n bytes[11] === 0x50\n )\n return \"image/webp\";\n return \"image/png\";\n}\n\n/** Build the SDK `ToolOutputImage` from raw screenshot bytes — the structured shape\n * the SDK's `imageOutputFromBytes` produces (`{type:'image', image:{data,mediaType}}`). */\nfunction imageOutputFromScreenshotBytes(bytes: Uint8Array): ToolOutputImage {\n return {\n type: \"image\",\n image: { data: Uint8Array.from(bytes), mediaType: sniffScreenshotMediaType(bytes) },\n };\n}\n\n/** Render an image tool-output as a text-transport string, in lockstep with the\n * SDK's private `renderImageForTextTransport` (capabilities/filesystem). Our image\n * output always carries `data` as bytes, so it becomes a `data:<mediaType>;base64,…`\n * URL — the exact form the text-backend `view_image` hands the model. */\nfunction renderImageForTextTransport(output: ToolOutputImage | string): string {\n if (typeof output === \"string\") return output;\n const { image } = output;\n const mediaType =\n typeof image.mediaType === \"string\" ? image.mediaType : \"application/octet-stream\";\n return `data:${mediaType};base64,${Buffer.from(image.data).toString(\"base64\")}`;\n}\n\n/** Whether the bound model supports the structured tool-output transport, in\n * lockstep with the SDK's private `supportsStructuredToolOutputTransport`\n * (capabilities/transport): a ChatCompletions-family model — and an UNBOUND model\n * (undefined) — does NOT, so it gets the function tools; every other model keeps\n * the hosted `computer_use_preview` tool. The codex neutralize trick in index.ts\n * drops `_modelInstance`, so this returns false there and the function tools win. */\nfunction supportsStructuredToolOutputTransport(modelInstance: unknown): boolean {\n if (!modelInstance) return false;\n const constructorName =\n typeof modelInstance === \"object\" &&\n modelInstance &&\n typeof (modelInstance as { constructor?: unknown }).constructor === \"function\"\n ? ((modelInstance as { constructor: { name?: string } }).constructor.name ?? \"\")\n : \"\";\n return !constructorName.includes(\"ChatCompletions\");\n}\n\nconst COMPUTER_READ_ONLY_MESSAGE =\n \"computer-use is read-only for this session — click, double_click, move, scroll, type, keypress, and drag are disabled. Call computer_screenshot to observe the desktop.\";\n\n// The two coordinate properties every pointer tool shares. Raw JSON schema (NOT\n// zod: zod is not a @opengeni/runtime dependency) with `strict:false`, mirroring the\n// SDK's own `apply_patch` function-tool schema style.\nconst COORD_PROPS = {\n x: {\n type: \"integer\",\n description: \"X coordinate in the pixels of the most recent computer_screenshot\",\n },\n y: {\n type: \"integer\",\n description: \"Y coordinate in the pixels of the most recent computer_screenshot\",\n },\n} as const;\n\nfunction objectSchema(\n properties: Record<string, unknown>,\n required: string[],\n): Record<string, unknown> {\n return { type: \"object\", properties, required, additionalProperties: false };\n}\n\n/**\n * The FUNCTION-transport computer tools for the codex / text backend, each routing\n * to the SAME bound `Computer` the hosted `computer_use_preview` tool would drive.\n * `computer_screenshot` hands the model the desktop two ways, selected by\n * `imageFunctionResults`:\n * • false (chat-completions providers, the default) → the text-transport\n * `data:image/png;base64,…` URL (imageOutputFromBytes → renderImageForTextTransport,\n * the SDK's text `view_image` path) — those backends can't read structured image\n * tool results.\n * • true (the codex/ChatGPT backend) → the structured `{type:'image'}` tool output,\n * which agents-core normalizes into an `input_image` content item inside the\n * function_call_output — the codex /responses backend accepts and SEES it (a text\n * data-URL there is just unreadable text). See index.ts for why it's on there.\n * Write tools return a concise confirmation; when read-only they return\n * {@link COMPUTER_READ_ONLY_MESSAGE} instead of throwing, and any action error is\n * returned as a string so a failed action never kills the turn. Exported so it can be\n * unit-tested against a fake `Computer`.\n */\nexport function computerFunctionTools(\n computer: Computer,\n readOnly: boolean,\n needsApproval?: ComputerUseArgs[\"needsApproval\"],\n imageFunctionResults = false,\n): Tool<unknown>[] {\n const approval = needsApproval !== undefined ? { needsApproval: needsApproval as never } : {};\n // Perform a WRITE action, surfacing read-only / failures as a model-readable\n // string rather than an uncaught throw (an uncaught throw becomes a tool error\n // the backend may 400 on, or kills the step).\n const write = async (\n confirmation: string,\n action: () => void | Promise<void>,\n ): Promise<string> => {\n if (readOnly) return COMPUTER_READ_ONLY_MESSAGE;\n try {\n await action();\n return confirmation;\n } catch (error) {\n if (error instanceof ComputerReadOnlyError) return COMPUTER_READ_ONLY_MESSAGE;\n return `computer action failed: ${error instanceof Error ? error.message : String(error)}`;\n }\n };\n\n return [\n tool({\n name: \"computer_screenshot\",\n description:\n \"Capture the current desktop and return it as an image. Call this FIRST and again after each action — all coordinates for click/move/scroll/drag are pixels of the most recent screenshot.\",\n parameters: objectSchema({}, []) as never,\n strict: false,\n execute: async () => {\n // screenshot() returns raw base64 PNG and NEVER an empty string (it throws\n // instead), so the model can't receive an empty image_url.\n const b64 = await computer.screenshot();\n const bytes = Uint8Array.from(Buffer.from(b64, \"base64\"));\n const image = imageOutputFromScreenshotBytes(bytes);\n // On the codex backend return the structured image output so the model SEES\n // the desktop (agents-core normalizes {type:'image'} → an input_image data-URL\n // content item in the function_call_output); chat-completions providers get\n // the text data-URL string they expect.\n return imageFunctionResults ? image : renderImageForTextTransport(image);\n },\n }),\n tool({\n name: \"computer_click\",\n description:\n \"Click the mouse at (x, y). `button` is one of left|right|wheel|back|forward (default left). Take a computer_screenshot first to find coordinates.\",\n parameters: objectSchema(\n {\n ...COORD_PROPS,\n button: {\n type: \"string\",\n enum: [\"left\", \"right\", \"wheel\", \"back\", \"forward\"],\n description: \"Mouse button; defaults to left\",\n },\n },\n [\"x\", \"y\"],\n ) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { x, y, button } = input as { x: number; y: number; button?: ComputerButton };\n return write(`clicked ${button ?? \"left\"} at (${x}, ${y})`, () =>\n computer.click(x, y, button ?? \"left\"),\n );\n },\n }),\n tool({\n name: \"computer_double_click\",\n description:\n \"Double-click the left mouse button at (x, y). Take a computer_screenshot first to find coordinates.\",\n parameters: objectSchema({ ...COORD_PROPS }, [\"x\", \"y\"]) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { x, y } = input as { x: number; y: number };\n return write(`double-clicked at (${x}, ${y})`, () => computer.doubleClick(x, y));\n },\n }),\n tool({\n name: \"computer_move\",\n description: \"Move the mouse cursor to (x, y) without clicking.\",\n parameters: objectSchema({ ...COORD_PROPS }, [\"x\", \"y\"]) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { x, y } = input as { x: number; y: number };\n return write(`moved to (${x}, ${y})`, () => computer.move(x, y));\n },\n }),\n tool({\n name: \"computer_scroll\",\n description:\n \"Scroll at (x, y) by scroll_x / scroll_y pixels (positive scroll_y scrolls down, negative up; positive scroll_x scrolls right).\",\n parameters: objectSchema(\n {\n ...COORD_PROPS,\n scroll_x: {\n type: \"integer\",\n description: \"Horizontal scroll amount in pixels (positive = right)\",\n },\n scroll_y: {\n type: \"integer\",\n description: \"Vertical scroll amount in pixels (positive = down)\",\n },\n },\n [\"x\", \"y\", \"scroll_x\", \"scroll_y\"],\n ) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { x, y, scroll_x, scroll_y } = input as {\n x: number;\n y: number;\n scroll_x: number;\n scroll_y: number;\n };\n return write(`scrolled (${scroll_x}, ${scroll_y}) at (${x}, ${y})`, () =>\n computer.scroll(x, y, scroll_x, scroll_y),\n );\n },\n }),\n tool({\n name: \"computer_type\",\n description:\n \"Type a literal text string at the current keyboard focus. Click the target field first.\",\n parameters: objectSchema(\n { text: { type: \"string\", description: \"The literal text to type\" } },\n [\"text\"],\n ) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { text } = input as { text: string };\n return write(`typed ${text.length} character(s)`, () => computer.type(text));\n },\n }),\n tool({\n name: \"computer_keypress\",\n description:\n 'Press a key or chord. `keys` is an ordered list pressed together, e.g. [\"ctrl\",\"c\"] or [\"Enter\"]. Use key names (ctrl, alt, shift, cmd, enter, tab, esc, arrows…), not characters.',\n parameters: objectSchema(\n {\n keys: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Keys pressed together as a chord\",\n },\n },\n [\"keys\"],\n ) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { keys } = input as { keys: string[] };\n return write(`pressed ${keys.join(\"+\")}`, () => computer.keypress(keys));\n },\n }),\n tool({\n name: \"computer_drag\",\n description:\n \"Drag the left mouse button along a path of points. `path` is an ordered list of {x, y} pixels; the button is pressed at the first point, moved through each, and released at the last.\",\n parameters: objectSchema(\n {\n path: {\n type: \"array\",\n description: \"Ordered list of points to drag through\",\n items: {\n type: \"object\",\n properties: { x: { type: \"integer\" }, y: { type: \"integer\" } },\n required: [\"x\", \"y\"],\n additionalProperties: false,\n },\n },\n },\n [\"path\"],\n ) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { path } = input as { path: Array<{ x: number; y: number }> };\n const points = path.map((p) => [p.x, p.y] as [number, number]);\n return write(`dragged through ${points.length} point(s)`, () => computer.drag(points));\n },\n }),\n ] as unknown as Tool<unknown>[];\n}\n\n// ── The capability (the SDK seam) ────────────────────────────────────────────\n\n/**\n * EXPLICIT tool-transport selection, decided by the caller that knows the\n * provider's true wire identity (the worker's model resolution — see agent-turn.ts),\n * NOT inferred from the bound model instance's constructor name. This is the\n * HARDENING seam: `supportsStructuredToolOutputTransport` string-sniffs the\n * constructor for \"ChatCompletions\", which a wrapped / proxied / minified model\n * instance would defeat — silently handing a chat-completions provider the HOSTED\n * `computer_use_preview` tool it 400s on every turn. When `toolMode` is set, tools()\n * OBEYS it and never consults the sniff:\n * • \"hosted\" → the single hosted `computer_use_preview` tool (Responses backends).\n * • \"function-image\" → the FUNCTION `computer_*` tools with screenshots delivered as a\n * structured `{type:'image'}` output (the codex/ChatGPT backend,\n * which rejects hosted tool types but SEES structured image results).\n * • \"function-text\" → the FUNCTION tools with screenshots rendered as a text\n * `data:…;base64` URL (chat-completions providers, which can't read\n * structured image tool results).\n */\nexport type ComputerToolMode = \"hosted\" | \"function-image\" | \"function-text\";\n\nexport type ComputerUseArgs = {\n dimensions?: [number, number];\n readOnly?: boolean;\n display?: string;\n needsApproval?: boolean | ((ctx: unknown, action: unknown) => boolean | Promise<boolean>);\n // Deliver screenshots from the FUNCTION tools as a REAL image the model can see\n // (a structured `{type:'image'}` tool output → agents-core normalizes it to an\n // `input_image` content item inside the function_call_output) instead of the text\n // data-URL string. Only the codex/ChatGPT backend can read structured image tool\n // results; chat-completions providers cannot, so this stays OFF (text rendering)\n // by default and is turned on only on the codex path (see index.ts). Ignored when\n // `toolMode` is set (the mode carries its own image-delivery choice).\n imageFunctionResults?: boolean;\n // EXPLICIT transport selection (see {@link ComputerToolMode}). When present, tools()\n // obeys it directly — the constructor-name sniff is NOT consulted. When ABSENT, the\n // legacy sniff behaviour is preserved byte-for-byte (back-compat for any embedder\n // that constructs the capability without threading a mode).\n toolMode?: ComputerToolMode;\n /** Called after the display is ready on the first actual computer action. */\n onReady?: (session: SandboxSessionLike) => Promise<void>;\n};\n\nexport function computerUse(args: ComputerUseArgs = {}): ComputerUseCapability {\n return new ComputerUseCapability(args);\n}\n\n/**\n * A `Capability` subclass merged into the agent's tool set by SandboxAgent\n * (`tools = [...agent.tools, ...capability.tools()]`). `bind(session)` hands it\n * the LIVE externally-owned session, so the agent's actions and the viewers'\n * pixels are one display.\n *\n * `tools()` is TRANSPORT-AWARE, mirroring the SDK's `filesystem()` capability\n * (which branches its `view_image` / `apply_patch` on\n * `supportsStructuredToolOutputTransport(this._modelInstance)`):\n * • structured transport (the Responses/OpenAI backend) → the single HOSTED\n * `computer_use_preview` tool over a Computer bound to the session (unchanged).\n * • text transport (codex / ChatGPT backend — or an unbound model) → a set of\n * FUNCTION tools ({@link computerFunctionTools}) that route to the SAME Computer,\n * because the codex backend rejects the hosted computer tool type.\n * The bound model instance is captured by the SDK's `bind().bindRunAs().bindModel()`\n * chain (base `Capability._modelInstance`); the codex path in index.ts neutralizes\n * `bindModel` so `_modelInstance` stays undefined here → the function tools win.\n */\nexport class ComputerUseCapability extends Capability {\n readonly type = \"computer-use\";\n constructor(private args: ComputerUseArgs = {}) {\n super();\n }\n\n override tools(): Tool<unknown>[] {\n const session = requireBoundSession(\"computer-use\", this._session);\n // Backend-aware: a SELF-HOSTED session (macOS OR bring-your-own Linux) drives the\n // desktop NATIVELY (CGEvent/XTEST inject + ScreenCaptureKit/x11 capture over the\n // control plane) — no xdotool/scrot on the user's machine required. Everything\n // else (Modal) keeps the xdotool/scrot-over-exec SandboxComputer. See\n // `isNativeDesktopSession` for the duck-typed discriminator.\n const computer: Computer = isNativeDesktopSession(session)\n ? new NativeDesktopComputer(session, {\n ...(this.args.dimensions ? { dimensions: this.args.dimensions } : {}),\n ...(this.args.readOnly !== undefined ? { readOnly: this.args.readOnly } : {}),\n })\n : new SandboxComputer(session, {\n ...(this.args.dimensions ? { dimensions: this.args.dimensions } : {}),\n ...(this.args.readOnly !== undefined ? { readOnly: this.args.readOnly } : {}),\n ...(this.args.display ? { display: this.args.display } : {}),\n // The SDK base exposes the bound runAs as a protected field.\n ...(typeof this._runAs === \"string\" ? { runAs: this._runAs } : {}),\n // Crucially lazy: tool registration does no provider work. The first\n // click/type/screenshot boots the display, then lets the worker start\n // any computer-use-only recording. One SandboxComputer instance caches\n // this for the rest of the turn.\n prepare: async (preparedSession) => {\n await ensureDisplayStack(preparedSession, {\n telemetryContext: { callerKind: \"computer\" },\n });\n await this.args.onReady?.(preparedSession);\n },\n });\n // HARDENING: when the caller declares an EXPLICIT toolMode, obey it and NEVER\n // consult `supportsStructuredToolOutputTransport` — tool selection must not\n // depend on the model instance's constructor name (a wrapped/proxied/minified\n // instance would defeat the \"ChatCompletions\" string-sniff and silently hand a\n // chat-completions provider the hosted tool it 400s on). The mode is decided by\n // the worker, where provider identity is authoritative (see agent-turn.ts).\n switch (this.args.toolMode) {\n case \"hosted\":\n return [this.hostedComputerTool(computer)];\n case \"function-image\":\n return computerFunctionTools(\n computer,\n this.args.readOnly ?? false,\n this.args.needsApproval,\n true,\n );\n case \"function-text\":\n return computerFunctionTools(\n computer,\n this.args.readOnly ?? false,\n this.args.needsApproval,\n false,\n );\n case undefined:\n break; // fall through to the legacy sniff (back-compat), preserved byte-for-byte\n }\n // Legacy (no toolMode): structured transport keeps the HOSTED computer tool\n // (unchanged); the codex / text backend gets the FUNCTION tools it can call.\n if (supportsStructuredToolOutputTransport(this._modelInstance)) {\n return [this.hostedComputerTool(computer)];\n }\n return computerFunctionTools(\n computer,\n this.args.readOnly ?? false,\n this.args.needsApproval,\n this.args.imageFunctionResults ?? false,\n );\n }\n\n /** The single HOSTED `computer_use_preview` tool bound to `computer` — identical\n * construction for the explicit \"hosted\" mode and the legacy structured-sniff path. */\n private hostedComputerTool(computer: Computer): Tool<unknown> {\n return computerTool({\n computer,\n ...(this.args.needsApproval !== undefined\n ? { needsApproval: this.args.needsApproval as never }\n : {}),\n }) as unknown as Tool<unknown>;\n }\n}\n","import { createHash } from \"node:crypto\";\n\nimport { Capability, type SandboxSessionLike } from \"@openai/agents/sandbox\";\n\nconst SKILL_FILE = \"SKILL.md\";\nconst MAX_DISCOVERED_SKILLS = 256;\nconst MAX_SKILL_ENTRIES = 1_024;\nconst MAX_SKILL_BYTES = 32 * 1024 * 1024;\nconst SAFE_SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\nexport type WorkspaceSkillSearchPath = Readonly<{\n path: string;\n source: string;\n}>;\n\ntype WorkspaceSkill = Readonly<{\n name: string;\n description: string;\n path: string;\n fingerprint: string;\n source: string;\n}>;\n\n/**\n * Index skills that already exist in the live workspace.\n *\n * Unlike the SDK's `skills({ from })` and `skills({ lazyFrom })` sources, this\n * capability deliberately contributes no manifest entries and materializes\n * nothing. Repository resources and Connected Machines already own these\n * files; the bound sandbox session is the one portable way to inspect them.\n */\nexport class WorkspaceSkillsCapability extends Capability {\n readonly type = \"workspace-skills\";\n private discovery?: Promise<readonly WorkspaceSkill[]>;\n\n constructor(\n private readonly searchPaths: readonly WorkspaceSkillSearchPath[],\n private readonly reservedNames: ReadonlySet<string> = new Set(),\n ) {\n super();\n }\n\n override async instructions(): Promise<string | null> {\n const session = requireWorkspaceSkillSession(this._session);\n this.discovery ??= discoverWorkspaceSkills(\n session,\n this.searchPaths,\n this.reservedNames,\n this._runAs,\n );\n const skills = await this.discovery;\n if (skills.length === 0) return null;\n\n const available = skills\n .map((skill) => `- ${skill.name}: ${skill.description} (file: ${skill.path})`)\n .join(\"\\n\");\n return `## Repository skills\n\nRepository skills are instructions already present in the live workspace. They do not need to be loaded or copied.\n\n### Available repository skills\n${available}\n\n### How to use repository skills\n- If the user names a skill, or the task clearly matches a skill description, read its complete SKILL.md before acting.\n- Resolve referenced scripts, references, assets, and templates relative to that skill directory.\n- Use only the minimum relevant skills for the turn, and say briefly which ones you are using.\n- Do not assume a skill remains applicable on later turns; evaluate the current request again.`;\n }\n}\n\nexport function workspaceSkills(\n searchPaths: readonly WorkspaceSkillSearchPath[],\n reservedNames: Iterable<string> = [],\n): WorkspaceSkillsCapability {\n return new WorkspaceSkillsCapability(\n searchPaths,\n new Set([...reservedNames].map((name) => name.toLowerCase())),\n );\n}\n\nexport async function discoverWorkspaceSkills(\n session: SandboxSessionLike,\n searchPaths: readonly WorkspaceSkillSearchPath[],\n reservedNames: ReadonlySet<string> = new Set(),\n runAs?: string,\n): Promise<readonly WorkspaceSkill[]> {\n if (!session.listDir || !session.readFile) {\n throw new Error(\"Workspace skill discovery requires sandbox listDir() and readFile() support\");\n }\n const discovered = new Map<string, WorkspaceSkill>();\n let candidates = 0;\n for (const searchPath of searchPaths) {\n let entries;\n try {\n entries = await session.listDir({ path: searchPath.path, ...(runAs ? { runAs } : {}) });\n } catch {\n continue;\n }\n for (const entry of [...entries].sort((left, right) => left.name.localeCompare(right.name))) {\n if (entry.type !== \"dir\") continue;\n candidates += 1;\n if (candidates > MAX_DISCOVERED_SKILLS) {\n throw new Error(`Repository skill discovery exceeds ${MAX_DISCOVERED_SKILLS} directories`);\n }\n const skillMarkdownPath = joinWorkspacePath(entry.path, SKILL_FILE);\n let markdown: string;\n try {\n const content = await session.readFile({\n path: skillMarkdownPath,\n ...(runAs ? { runAs } : {}),\n });\n markdown = typeof content === \"string\" ? content : new TextDecoder().decode(content);\n } catch {\n continue;\n }\n const frontmatter = parseSkillFrontmatter(markdown);\n const name = frontmatter.name?.trim() || entry.name;\n if (name.length > 64 || !SAFE_SKILL_NAME.test(name)) {\n throw new Error(`Repository skill has an invalid name: ${name.slice(0, 64)}`);\n }\n const description = frontmatter.description?.trim() || \"No description provided.\";\n if (description.length > 2_048 || /[\\r\\n]/.test(description)) {\n throw new Error(`Repository skill \"${name}\" has an invalid description`);\n }\n const key = name.toLowerCase();\n if (reservedNames.has(key)) {\n throw new Error(`Workspace skill \"${name}\" conflicts with a configured OpenGeni skill`);\n }\n const candidate: WorkspaceSkill = {\n name,\n description,\n path: skillMarkdownPath,\n fingerprint: await fingerprintWorkspaceDirectory(session, entry.path, runAs),\n source: searchPath.source,\n };\n const existing = discovered.get(key);\n if (!existing) {\n discovered.set(key, candidate);\n continue;\n }\n if (existing.fingerprint !== candidate.fingerprint) {\n throw new Error(\n `Workspace skill \"${name}\" has conflicting definitions in ${existing.source} and ${candidate.source}`,\n );\n }\n }\n }\n return [...discovered.values()].sort((left, right) => left.name.localeCompare(right.name));\n}\n\nasync function fingerprintWorkspaceDirectory(\n session: SandboxSessionLike,\n root: string,\n runAs?: string,\n): Promise<string> {\n const hash = createHash(\"sha256\");\n let entryCount = 0;\n let byteCount = 0;\n\n async function visit(path: string, relativePath: string): Promise<void> {\n const entries = await session.listDir!({ path, ...(runAs ? { runAs } : {}) });\n for (const entry of [...entries].sort((left, right) => left.name.localeCompare(right.name))) {\n entryCount += 1;\n if (entryCount > MAX_SKILL_ENTRIES) {\n throw new Error(`Workspace skill exceeds ${MAX_SKILL_ENTRIES} filesystem entries`);\n }\n const childRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;\n hash.update(entry.type);\n hash.update(\"\\0\");\n hash.update(childRelativePath);\n hash.update(\"\\0\");\n if (entry.type === \"dir\") {\n await visit(entry.path, childRelativePath);\n continue;\n }\n if (entry.type !== \"file\") continue;\n const content = await session.readFile!({\n path: entry.path,\n ...(runAs ? { runAs } : {}),\n });\n const bytes = typeof content === \"string\" ? new TextEncoder().encode(content) : content;\n byteCount += bytes.byteLength;\n if (byteCount > MAX_SKILL_BYTES) {\n throw new Error(`Workspace skill exceeds ${MAX_SKILL_BYTES} bytes`);\n }\n hash.update(bytes);\n hash.update(\"\\0\");\n }\n }\n\n await visit(root, \"\");\n return hash.digest(\"hex\");\n}\n\nfunction parseSkillFrontmatter(markdown: string): {\n name?: string;\n description?: string;\n} {\n const lines = markdown.split(/\\r?\\n/);\n if (lines[0]?.trim() !== \"---\") return {};\n const end = lines.findIndex((line, index) => index > 0 && line.trim() === \"---\");\n if (end === -1) return {};\n const values: Record<string, string> = {};\n for (const line of lines.slice(1, end)) {\n const separator = line.indexOf(\":\");\n if (separator === -1) continue;\n const key = line.slice(0, separator).trim();\n if (key !== \"name\" && key !== \"description\") continue;\n values[key] = unquote(line.slice(separator + 1).trim());\n }\n return values;\n}\n\nfunction unquote(value: string): string {\n if (\n value.length >= 2 &&\n value[0] === value[value.length - 1] &&\n (value[0] === '\"' || value[0] === \"'\")\n ) {\n return value.slice(1, -1);\n }\n return value;\n}\n\nfunction joinWorkspacePath(parent: string, child: string): string {\n return `${parent.replace(/\\/+$/, \"\")}/${child}`;\n}\n\nfunction requireWorkspaceSkillSession(session: SandboxSessionLike | undefined): SandboxSessionLike {\n if (!session) {\n throw new Error('capability \"workspace-skills\" used before bind(session)');\n }\n return session;\n}\n","type UsageDetails = Record<string, unknown> | Array<Record<string, unknown>>;\n\ntype RequestUsageEntry = {\n inputTokens?: unknown;\n input_tokens?: unknown;\n outputTokens?: unknown;\n output_tokens?: unknown;\n totalTokens?: unknown;\n total_tokens?: unknown;\n inputTokensDetails?: UsageDetails | undefined;\n input_tokens_details?: UsageDetails | undefined;\n outputTokensDetails?: UsageDetails | undefined;\n output_tokens_details?: UsageDetails | undefined;\n};\n\nexport type ModelCallUsageInput = {\n inputTokens?: unknown;\n outputTokens?: unknown;\n totalTokens?: unknown;\n inputTokensDetails?: UsageDetails | undefined;\n outputTokensDetails?: UsageDetails | undefined;\n requestUsageEntries?: RequestUsageEntry[] | undefined;\n};\n\n/**\n * A single provider usage frame above one billion tokens is outside every\n * supported OpenGeni model contract. Keeping the ceiling explicit also prevents\n * malformed-but-finite provider values from corrupting durable accounting or a\n * process-lifetime Prometheus counter.\n */\nexport const MAX_MODEL_USAGE_TOKEN_COUNT = 1_000_000_000;\n\nexport type ModelCallUsageTelemetry = {\n inputTokens: number | null;\n outputTokens: number | null;\n cachedTokens: number | null;\n cacheWriteTokens: number | null;\n reasoningTokens: number | null;\n};\n\nexport type ModelCallUsageNormalization = {\n telemetry: ModelCallUsageTelemetry;\n totalTokens: number | null;\n /** Bounded field paths only; raw provider values are never retained. */\n rejectedFields: string[];\n};\n\nexport function modelUsageTokenCountOrNull(value: unknown): number | null {\n return typeof value === \"number\" &&\n Number.isSafeInteger(value) &&\n value >= 0 &&\n value <= MAX_MODEL_USAGE_TOKEN_COUNT\n ? value\n : null;\n}\n\nexport function normalizeModelCallUsage(\n usage: ModelCallUsageInput | null | undefined,\n): ModelCallUsageNormalization {\n const rejectedFields = new Set<string>();\n if (!usage) {\n return {\n telemetry: {\n inputTokens: null,\n outputTokens: null,\n cachedTokens: null,\n cacheWriteTokens: null,\n reasoningTokens: null,\n },\n totalTokens: null,\n rejectedFields: [],\n };\n }\n\n const requestEntries = requestUsageEntries(usage.requestUsageEntries, rejectedFields);\n const topLevelInputTokens = reportedTokenCount(usage.inputTokens, \"inputTokens\", rejectedFields);\n const topLevelOutputTokens = reportedTokenCount(\n usage.outputTokens,\n \"outputTokens\",\n rejectedFields,\n );\n const topLevelTotalTokens = reportedTokenCount(usage.totalTokens, \"totalTokens\", rejectedFields);\n const requestInputTokens = completeRequestTokenAggregate(\n requestEntries,\n [\"inputTokens\", \"input_tokens\"],\n \"inputTokens.requestUsageEntries\",\n rejectedFields,\n );\n const requestOutputTokens = completeRequestTokenAggregate(\n requestEntries,\n [\"outputTokens\", \"output_tokens\"],\n \"outputTokens.requestUsageEntries\",\n rejectedFields,\n );\n let requestTotalTokens = completeRequestTokenAggregate(\n requestEntries,\n [\"totalTokens\", \"total_tokens\"],\n \"totalTokens.requestUsageEntries\",\n rejectedFields,\n );\n if (rejectInconsistentRequestTotals(requestEntries, rejectedFields)) {\n requestTotalTokens = { ...requestTotalTokens, status: \"invalid\", value: null };\n }\n\n // Complete per-request aggregates are the installed SDK's request-level\n // truth. A conflicting top-level field is diagnostic only; it must never\n // override the request sum with a smaller billable/context value. Invalid\n // complete request aggregates fail closed rather than falling back to a\n // potentially undercounting top-level number.\n const inputTokens = canonicalTokenDimension({\n topLevel: topLevelInputTokens,\n topLevelReported: isReported(usage.inputTokens),\n topLevelPath: \"inputTokens\",\n requestAggregate: requestInputTokens,\n rejectedFields,\n });\n const outputTokens = canonicalTokenDimension({\n topLevel: topLevelOutputTokens,\n topLevelReported: isReported(usage.outputTokens),\n topLevelPath: \"outputTokens\",\n requestAggregate: requestOutputTokens,\n rejectedFields,\n });\n const totalTokens = canonicalTotalTokens({\n inputTokens,\n outputTokens,\n topLevel: topLevelTotalTokens,\n topLevelReported: isReported(usage.totalTokens),\n requestAggregate: requestTotalTokens,\n rejectedFields,\n });\n\n const inputDetailSource = preferredDetailSource(\n usage.inputTokensDetails,\n \"inputTokensDetails\",\n requestEntries,\n [\"inputTokensDetails\", \"input_tokens_details\"],\n );\n const outputDetailSource = preferredDetailSource(\n usage.outputTokensDetails,\n \"outputTokensDetails\",\n requestEntries,\n [\"outputTokensDetails\", \"output_tokens_details\"],\n );\n\n return {\n telemetry: {\n inputTokens,\n outputTokens,\n cachedTokens: aggregateDetailTokenCount(\n inputDetailSource,\n [\"cached_tokens\", \"cachedInputTokens\", \"cached_input_tokens\"],\n \"cachedTokens\",\n rejectedFields,\n ),\n cacheWriteTokens: aggregateDetailTokenCount(\n inputDetailSource,\n [\"cache_write_tokens\", \"cacheWriteTokens\"],\n \"cacheWriteTokens\",\n rejectedFields,\n ),\n reasoningTokens: aggregateDetailTokenCount(\n outputDetailSource,\n [\"reasoning_tokens\", \"reasoningTokens\", \"reasoning_output_tokens\"],\n \"reasoningTokens\",\n rejectedFields,\n ),\n },\n totalTokens,\n rejectedFields: [...rejectedFields].slice(0, 32),\n };\n}\n\nexport function modelCallUsageTelemetry(\n usage: ModelCallUsageInput | null | undefined,\n): ModelCallUsageTelemetry {\n return normalizeModelCallUsage(usage).telemetry;\n}\n\nfunction requestUsageEntries(\n value: RequestUsageEntry[] | undefined,\n rejectedFields: Set<string>,\n): RequestUsageEntry[] {\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n rejectField(rejectedFields, \"requestUsageEntries\");\n return [];\n }\n const entries: RequestUsageEntry[] = [];\n for (const [index, entry] of value.entries()) {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n rejectField(rejectedFields, `requestUsageEntries[${index}]`);\n // Preserve the request slot as unknown. Dropping it would let fallback\n // aggregation silently undercount only the well-formed requests.\n entries.push({});\n continue;\n }\n entries.push(entry);\n }\n return entries;\n}\n\ntype RequestTokenAggregate = {\n status: \"absent\" | \"incomplete\" | \"invalid\" | \"complete\";\n value: number | null;\n};\n\nfunction completeRequestTokenAggregate(\n requestEntries: RequestUsageEntry[],\n requestKeys: string[],\n aggregatePath: string,\n rejectedFields: Set<string>,\n): RequestTokenAggregate {\n if (requestEntries.length === 0) {\n return { status: \"absent\", value: null };\n }\n const values: Array<number | null> = [];\n let incomplete = false;\n let invalid = false;\n for (const [index, entry] of requestEntries.entries()) {\n const selected = firstPresentEntry(entry as Record<string, unknown>, requestKeys);\n if (!selected || selected.value === null) {\n incomplete = true;\n continue;\n }\n const parsed = reportedTokenCount(\n selected.value,\n `requestUsageEntries[${index}].${selected.key}`,\n rejectedFields,\n );\n if (parsed === null) invalid = true;\n values.push(parsed);\n }\n if (invalid) {\n return { status: \"invalid\", value: null };\n }\n if (incomplete) {\n return { status: \"incomplete\", value: null };\n }\n const value = boundedTokenSum(values, aggregatePath, rejectedFields);\n return value === null ? { status: \"invalid\", value: null } : { status: \"complete\", value };\n}\n\nfunction canonicalTokenDimension(input: {\n topLevel: number | null;\n topLevelReported: boolean;\n topLevelPath: string;\n requestAggregate: RequestTokenAggregate;\n rejectedFields: Set<string>;\n}): number | null {\n if (input.requestAggregate.status === \"complete\") {\n if (\n input.topLevelReported &&\n input.topLevel !== null &&\n input.topLevel !== input.requestAggregate.value\n ) {\n rejectField(input.rejectedFields, input.topLevelPath);\n }\n return input.requestAggregate.value;\n }\n if (input.requestAggregate.status === \"invalid\") {\n if (input.topLevelReported) {\n rejectField(input.rejectedFields, input.topLevelPath);\n }\n return null;\n }\n return input.topLevel;\n}\n\nfunction canonicalTotalTokens(input: {\n inputTokens: number | null;\n outputTokens: number | null;\n topLevel: number | null;\n topLevelReported: boolean;\n requestAggregate: RequestTokenAggregate;\n rejectedFields: Set<string>;\n}): number | null {\n if (input.inputTokens !== null && input.outputTokens !== null) {\n const derived = boundedTokenSum(\n [input.inputTokens, input.outputTokens],\n \"totalTokens.aggregate\",\n input.rejectedFields,\n );\n if (derived === null) {\n // Both canonical components are known and exceed the supported aggregate\n // ceiling. Any bounded reported total necessarily undercounts them.\n if (input.topLevelReported) rejectField(input.rejectedFields, \"totalTokens\");\n if (input.requestAggregate.status === \"complete\") {\n rejectField(input.rejectedFields, \"totalTokens.requestUsageEntries\");\n }\n return null;\n }\n if (input.topLevelReported && input.topLevel !== null && input.topLevel !== derived) {\n rejectField(input.rejectedFields, \"totalTokens\");\n }\n if (input.requestAggregate.status === \"complete\" && input.requestAggregate.value !== derived) {\n rejectField(input.rejectedFields, \"totalTokens.requestUsageEntries\");\n }\n return derived;\n }\n\n if (input.requestAggregate.status === \"complete\") {\n const requestTotal = input.requestAggregate.value;\n if (\n requestTotal === null ||\n !totalCoversKnownComponents(requestTotal, input.inputTokens, input.outputTokens)\n ) {\n rejectField(input.rejectedFields, \"totalTokens.requestUsageEntries\");\n if (input.topLevelReported) rejectField(input.rejectedFields, \"totalTokens\");\n return null;\n }\n if (input.topLevelReported && input.topLevel !== null && input.topLevel !== requestTotal) {\n rejectField(input.rejectedFields, \"totalTokens\");\n }\n return requestTotal;\n }\n if (input.requestAggregate.status === \"invalid\") {\n if (input.topLevelReported) rejectField(input.rejectedFields, \"totalTokens\");\n return null;\n }\n if (\n input.topLevel !== null &&\n !totalCoversKnownComponents(input.topLevel, input.inputTokens, input.outputTokens)\n ) {\n rejectField(input.rejectedFields, \"totalTokens\");\n return null;\n }\n return input.topLevel;\n}\n\nfunction totalCoversKnownComponents(\n total: number,\n inputTokens: number | null,\n outputTokens: number | null,\n): boolean {\n return (\n (inputTokens === null || total >= inputTokens) &&\n (outputTokens === null || total >= outputTokens)\n );\n}\n\nfunction rejectInconsistentRequestTotals(\n requestEntries: RequestUsageEntry[],\n rejectedFields: Set<string>,\n): boolean {\n let inconsistent = false;\n for (const [index, entry] of requestEntries.entries()) {\n const record = entry as Record<string, unknown>;\n const selectedInput = firstPresentEntry(record, [\"inputTokens\", \"input_tokens\"]);\n const selectedOutput = firstPresentEntry(record, [\"outputTokens\", \"output_tokens\"]);\n const selectedTotal = firstPresentEntry(record, [\"totalTokens\", \"total_tokens\"]);\n if (!selectedInput || !selectedOutput || !selectedTotal) continue;\n const inputTokens = modelUsageTokenCountOrNull(selectedInput.value);\n const outputTokens = modelUsageTokenCountOrNull(selectedOutput.value);\n const totalTokens = modelUsageTokenCountOrNull(selectedTotal.value);\n if (inputTokens === null || outputTokens === null || totalTokens === null) continue;\n const derived =\n inputTokens <= MAX_MODEL_USAGE_TOKEN_COUNT - outputTokens ? inputTokens + outputTokens : null;\n if (derived === null || totalTokens !== derived) {\n rejectField(rejectedFields, `requestUsageEntries[${index}].${selectedTotal.key}`);\n inconsistent = true;\n }\n }\n return inconsistent;\n}\n\nfunction isReported(value: unknown): boolean {\n return value !== undefined && value !== null;\n}\n\nfunction preferredDetailSource(\n aggregateDetails: UsageDetails | undefined,\n aggregatePath: string,\n requestEntries: RequestUsageEntry[],\n requestKeys: string[],\n): Array<{ details: unknown; path: string; missing?: boolean }> {\n const requestDetails: Array<{ details: unknown; path: string; missing?: boolean }> = [];\n let sawRequestDetails = false;\n for (const [index, entry] of requestEntries.entries()) {\n const selected = firstPresentEntry(entry as Record<string, unknown>, requestKeys);\n if (!selected) {\n requestDetails.push({\n details: undefined,\n path: `requestUsageEntries[${index}].${requestKeys[0]}`,\n missing: true,\n });\n continue;\n }\n sawRequestDetails = true;\n requestDetails.push({\n details: selected.value,\n path: `requestUsageEntries[${index}].${selected.key}`,\n });\n }\n // The installed Agents SDK explicitly carries per-request entries. Prefer\n // them when they include detail records; otherwise fall back to the aggregate\n // detail arrays that Usage.add() appends in request order.\n return sawRequestDetails\n ? requestDetails\n : aggregateDetails === undefined\n ? []\n : [{ details: aggregateDetails, path: aggregatePath }];\n}\n\nfunction aggregateDetailTokenCount(\n sources: Array<{ details: unknown; path: string; missing?: boolean }>,\n keys: string[],\n field: string,\n rejectedFields: Set<string>,\n): number | null {\n const values: Array<number | null> = [];\n let sawReportedValue = false;\n let sawMissingValue = false;\n for (const source of sources) {\n if (source.missing) {\n sawMissingValue = true;\n continue;\n }\n const details = detailRecords(source.details, source.path, rejectedFields);\n if (!details.complete) {\n sawMissingValue = true;\n }\n for (const detail of details.records) {\n const selected = firstPresentEntry(detail.record, keys);\n if (!selected) {\n sawMissingValue = true;\n continue;\n }\n sawReportedValue = true;\n values.push(\n reportedTokenCount(selected.value, `${detail.path}.${selected.key}`, rejectedFields),\n );\n }\n }\n return sawReportedValue && !sawMissingValue\n ? boundedTokenSum(values, `${field}.aggregate`, rejectedFields)\n : null;\n}\n\nfunction detailRecords(\n details: unknown,\n path: string,\n rejectedFields: Set<string>,\n): {\n records: Array<{ record: Record<string, unknown>; path: string }>;\n complete: boolean;\n} {\n const entries = Array.isArray(details) ? details : [details];\n const records: Array<{ record: Record<string, unknown>; path: string }> = [];\n let complete = true;\n for (const [index, entry] of entries.entries()) {\n const entryPath = Array.isArray(details) ? `${path}[${index}]` : path;\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n rejectField(rejectedFields, entryPath);\n complete = false;\n continue;\n }\n records.push({ record: entry as Record<string, unknown>, path: entryPath });\n }\n return { records, complete };\n}\n\nfunction firstPresentEntry(\n record: Record<string, unknown>,\n keys: string[],\n): { key: string; value: unknown } | null {\n for (const key of keys) {\n if (Object.prototype.hasOwnProperty.call(record, key) && record[key] !== undefined) {\n // One request can expose the same value under provider and SDK aliases.\n // Pick the first canonical alias instead of adding aliases together.\n return { key, value: record[key] };\n }\n }\n return null;\n}\n\nfunction reportedTokenCount(\n value: unknown,\n field: string,\n rejectedFields: Set<string>,\n): number | null {\n if (value === undefined || value === null) {\n return null;\n }\n const normalized = modelUsageTokenCountOrNull(value);\n if (normalized === null) {\n rejectField(rejectedFields, field);\n }\n return normalized;\n}\n\nfunction boundedTokenSum(\n values: Array<number | null>,\n field: string,\n rejectedFields: Set<string>,\n): number | null {\n if (values.length === 0 || values.some((value) => value === null)) {\n return null;\n }\n let total = 0;\n for (const value of values as number[]) {\n if (value > MAX_MODEL_USAGE_TOKEN_COUNT - total) {\n rejectField(rejectedFields, field);\n return null;\n }\n total += value;\n }\n return total;\n}\n\nfunction rejectField(rejectedFields: Set<string>, field: string): void {\n if (rejectedFields.size < 32) {\n rejectedFields.add(field);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;AAAA,EACE;AAAA,EACA,6BAAAA;AAA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AAG;AACxB,WAAO,MAAM,IAAI,QAAQ;AAAA,EAC3B;AACA,MAAI,SAAS,OAAO,UAAU,UAAU;AACtC,WAAO,OAAO;AAAA,MACZ,OAAO,QAAQ,KAAK,EACjB,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,EACrC,IAAI,CAAC,CAAC,KAAK,MAAM,MAAM,CAAC,KAAK,SAAS,MAAM,CAAC,CAAC;AAAA,IACnD;AAAA,EACF;AACA,SAAO;AACT;AACA,SAAS,qBAAqB,MAAuB;AACnD,QAAM,YAAY;AAKlB,QAAM,OAAO,WAAW,YAAY,WAAW,QAAQ,WAAW,SAAS;AAC3E,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;","names":["collectSandboxEnvironment","CAPABILITY_DESCRIPTORS","redactSensitiveText","OpenAI","OpenAI","isRecord","isRecord","tool","isRecord","skills","openaiTool","openaiIncludes","webSearchTool","entry","response","isRecord","OpenAI","getCompatibleToolChoice","tool","file","isMessageItem","isRecord","response","tool","getResponseFormat","getCompatibleToolChoice","OpenAI","isRecord","child","isRecord","OpenAI","iterator","OpenAI","OpenAI","logger","resolveClient","OpenAI","METADATA","metadata_default","HEADERS","metadata_default","logger","OpenAI","boundModelToolOutputItems","createHash","tool","tool","RESULT_TYPE_BY_CALL_TYPE","RESULT_TYPES","itemType","window","createHash","skills","createHash","OpenAI","usage","summary","redactSensitiveText","agent","tool","boundModelToolOutputItems","collectSandboxEnvironment","runAs","fileDownloads","resourceClient","CAPABILITY_DESCRIPTORS","config","createHash"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiProvider.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/metadata.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/defaults.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiResponsesModel.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/logger.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/rawModelEvents.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/retryAdvice.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/responsesWebSocketConnection.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/responsesTransportUtils.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/tools.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/utils/providerData.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/utils/modelSettings.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/responsesUtils.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiChatCompletionsStreaming.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiChatCompletionsConverter.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiChatCompletionsModel.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/openaiTracingExporter.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/memory/openaiConversationsSession.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/memory/openaiSessionApi.ts","../../../node_modules/.bun/@openai+agents-openai@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents-openai/src/memory/openaiResponsesCompactionSession.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/metadata.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/utils.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/items.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/logger.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/openaiRealtimeEvents.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/shims/shims-node.ts","../../../node_modules/.bun/@openai+agents-realtime@0.13.3+6faab70c3ac8f376/node_modules/@openai/agents-realtime/src/tool.ts","../../../node_modules/.bun/@openai+agents@0.13.3+bd37e07cd49ea605/node_modules/@openai/agents/src/index.ts","../src/screenshot-error-card.ts","../src/history-sanitizer.ts","../src/codex-tool-search.ts","../src/context-compaction.ts","../src/sandbox-computer.ts","../src/workspace-skills.ts","../src/usage-telemetry.ts"],"sourcesContent":["import type {\n ConfiguredModel,\n ModelProviderApi,\n ResolvedModelProvider,\n Settings,\n} from \"@opengeni/config\";\nimport {\n AGENT_INSTRUCTIONS_CORE_PLACEHOLDER,\n collectSandboxEnvironment,\n firstPartyMcpBaseUrl,\n resolveModelProvider,\n sandboxLifecycleHookIds,\n} from \"@opengeni/config\";\nimport {\n approvalIdentifier,\n CAPABILITY_DESCRIPTORS,\n DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,\n DEFAULT_FIRST_PARTY_MCP_TOOLS,\n assertUniqueResourceMountPaths,\n gitCredentialBindingIdForRepository,\n gitCredentialProviderForRepository,\n isClearedRunStateBlob,\n normalizeRepositorySubpath,\n normalizeResourceMountPath,\n prefixedMcpToolName as sharedPrefixedMcpToolName,\n resourceMountPath,\n redactSensitiveText,\n sessionEventMediaPreview,\n sessionEventMediaPreviewFromDataUrl,\n signDelegatedAccessToken,\n RequestHumanInputToolInput,\n type GitCredentialProvider,\n type GitCredentialTransport,\n type HumanInputResponse,\n type McpServerConnectionRef,\n type Permission,\n type FirstPartyMcpToolName,\n type LatencyMode,\n type ReasoningEffort,\n type ResourceRef,\n type SessionEventType,\n type SessionEventMediaPreview,\n type ToolAuthNeededPayload,\n type ToolRef,\n} from \"@opengeni/contracts\";\nimport {\n MCP_MAX_CONCURRENT_SERVER_OPERATIONS,\n MCP_MAX_TOOL_RESULT_BYTES,\n McpAggregateToolListBudget,\n assertMcpPayloadWithinBytes,\n assertMcpServerSelectionWithinBounds,\n assertMcpToolListWithinBounds,\n boundedParallelMap,\n cancelMcpResponseBody,\n guardedMcpFetch,\n mcpOuterConnectTimeoutMs,\n undiciFetch,\n} from \"./mcp-network\";\nimport {\n Agent,\n AgentsError,\n connectMcpServers,\n OpenAIProvider,\n setDefaultModelProvider,\n MaxTurnsExceededError,\n MCPServerStreamableHttp,\n // Provider-bound Model instances. Both are re-exported from\n // @openai/agents-openai via `export * from '@openai/agents-openai'` in\n // @openai/agents' index (0.11.6), so the multi-provider routing imports them\n // from the same entrypoint as the rest of the SDK rather than reaching into\n // the openai subpackage. OpenAIChatCompletionsModel speaks /v1/chat/completions\n // (the registry \"chat\" wire API, e.g. Fireworks); OpenAIResponsesModel speaks\n // /v1/responses (the built-in OpenAI/Azure \"responses\" wire API). Both bind a\n // model id to a specific OpenAI client, which is what routes a turn to its\n // provider without touching the global default client.\n OpenAIChatCompletionsModel,\n OpenAIResponsesModel,\n RunState,\n isOpenAIResponsesRawModelStreamEvent,\n run,\n Runner,\n setDefaultOpenAIClient,\n setDefaultOpenAIKey,\n setOpenAIResponsesTransport,\n setTracingDisabled,\n tool as agentTool,\n // Hosted web_search tool factory. Re-exported from @openai/agents-openai via\n // `export * from '@openai/agents-openai'` in @openai/agents' index (0.11.6);\n // it returns a { type: 'hosted_tool', providerData: { type: 'web_search' } }\n // descriptor the OpenAI Responses model serializes into request.tools[].\n webSearchTool,\n // The SDK's V4A-diff applier — the apply_patch host the filesystem capability's\n // editor uses. The agent-loop-free sandbox leaf cannot import it (it lives behind\n // the `@openai/agents` root the leaf forbids), so the barrel imports it here and\n // injects it into the selfhosted session's `createEditor` via setSelfhostedApplyDiff\n // (below, right after the leaf re-export). This lets a selfhosted active backend\n // apply file edits over its NATS fs ops using the SDK's exact diff semantics.\n applyDiff,\n type AgentInputItem,\n type CallModelInputFilter,\n type MCPServer,\n type MCPToolErrorFunction,\n type Model,\n type ModelRequest,\n type ModelProvider,\n type RunStreamEvent,\n type Tool,\n} from \"@openai/agents\";\nimport { localDirLazySkillSource } from \"@openai/agents/sandbox/local\";\nimport {\n Capabilities,\n Manifest,\n SandboxAgent,\n azureBlobMount,\n dir,\n file,\n filesystem,\n gitRepo,\n inContainerMountStrategy,\n localDir,\n s3Mount,\n shell,\n skills,\n type Dir,\n type Entry,\n type LocalDirLazySkillSource,\n type SandboxClient,\n type SandboxSessionLike,\n type SandboxSessionState,\n type SandboxRunConfig,\n type SkillIndexEntry,\n} from \"@openai/agents/sandbox\";\nimport { ModalCloudBucketMountStrategy } from \"@openai/agents-extensions/sandbox/modal\";\nimport OpenAI from \"openai\";\nimport {\n CODEX_APPS_MCP_SERVER_ID,\n CODEX_MODEL_ID_PREFIX,\n CODEX_ORIGINATOR,\n CODEX_RESPONSE_SDK_OUTER_TIMEOUT_MS,\n boundModelToolOutputItems,\n codexAppsSanitizingFetch,\n codexRequestStorage,\n codexSubscriptionFetch,\n} from \"@opengeni/codex\";\nimport { cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { dirname, isAbsolute, join, posix as posixPath, relative } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n computerCallNormalizingFetch,\n normalizeComputerCallActions,\n sanitizeHistoryItemsForModel,\n} from \"./history-sanitizer\";\nimport { installCodexToolSearch } from \"./codex-tool-search\";\nimport {\n CompactionNeededError,\n CompactionProviderResponseError,\n EmptyCompactionSummaryError,\n SUMMARY_BUFFER_TOKENS,\n buildRemoteCompactionV2PromptInput,\n extractRemoteCompactionV2OutputItem,\n compactionThresholdTokens,\n estimateCompleteModelInput,\n estimateSerializedValueTokens,\n hasModelGeneratedItem,\n renderCompactionPromptInputForChat,\n type CompleteModelInputFootprint,\n type ProviderContextTokenSignal,\n} from \"./context-compaction\";\nimport {\n createSandboxClient,\n desktopCapableBackend,\n restoredSandboxSessionStateFromEntry,\n setSelfhostedApplyDiff,\n toolspaceTokenFileFromEnvironment,\n withToolspaceTokenClient,\n withToolspaceTokenSession,\n withRunCredentialsClient,\n withRunCredentialsSession,\n type RunCredentialSessionReady,\n} from \"./sandbox\";\nimport { runWithToolCallCorrelation } from \"./sandbox/op-correlation\";\nimport { shellToolspacePath } from \"./sandbox/toolspace-token\";\nimport {\n createTurnToolCancellationController,\n TurnSandboxCommandCancelledError,\n wrapCapabilityToolsForTurnCancellation,\n type TurnSandboxCommandArgs,\n type TurnSandboxCommandSession,\n type TurnToolCancellationFence,\n} from \"./sandbox/turn-tool-cancellation\";\nimport { computerUse, type ComputerToolMode } from \"./sandbox-computer\";\nimport type { RuntimeMetricsHooks } from \"./metrics\";\nimport { workspaceSkills, type WorkspaceSkillSearchPath } from \"./workspace-skills\";\n\n// The Agents SDK's debug namespaces can otherwise serialize complete model\n// inputs/outputs and tool arguments/results. These getters read process.env on\n// every log call, so keep the process-global guard permanently enabled rather\n// than toggling it around concurrent turns.\nprocess.env.OPENAI_AGENTS_DONT_LOG_MODEL_DATA = \"1\";\nprocess.env.OPENAI_AGENTS_DONT_LOG_TOOL_DATA = \"1\";\n\nexport {\n getSkillLibraryEntry,\n isSkillLibraryEntryId,\n listSkillLibraryEntries,\n loadSkillLibrarySkill,\n type SkillLibraryEntry,\n type SkillLibraryFile,\n type SkillLibrarySkill,\n} from \"./skill-library\";\n\nexport type { RuntimeMetricsHooks } from \"./metrics\";\nexport {\n createTurnToolCancellationController,\n TurnSandboxCommandCancelledError,\n} from \"./sandbox/turn-tool-cancellation\";\nexport type {\n TurnSandboxCommandArgs,\n TurnSandboxCommandSession,\n TurnToolCancellationController,\n TurnToolCancellationFence,\n} from \"./sandbox/turn-tool-cancellation\";\n\n// P4.3 computer-use surface (the agent's :0 driver). Re-exported from the barrel\n// so callers (the worker, live proofs) reach SandboxComputer/ComputerUseCapability\n// alongside the rest of the runtime. NOT part of the agent-loop-free leaf (it\n// imports computerTool from the @openai/agents root).\nexport {\n SandboxComputer,\n ComputerUseCapability,\n computerUse,\n ComputerUnavailableError,\n ComputerReadOnlyError,\n ComputerActionError,\n type SandboxComputerOptions,\n type ComputerUseArgs,\n type ComputerToolMode,\n} from \"./sandbox-computer\";\n\n// The agent-loop-free sandbox leaf (createSandboxClient + resume/recovery\n// helpers + the config-owned env/port re-exports). Re-exported verbatim so the\n// barrel surface is unchanged for apps/worker while @opengeni/runtime/sandbox\n// stays importable by the API without the agent loop.\nexport * from \"./sandbox\";\n\n// Inject the SDK's V4A `applyDiff` into the selfhosted session's apply_patch editor\n// at module load. The leaf can't import `applyDiff` (agent-loop root), so the\n// barrel — which already imports `@openai/agents` — wires it once. A selfhosted\n// active backend can now apply file edits over its NATS fs ops with the SDK's exact\n// diff semantics; without this, `createEditor()` throws a clear \"not injected\" error\n// rather than mis-editing. Runs at import time, before any turn binds a capability.\nsetSelfhostedApplyDiff(\n applyDiff as unknown as (input: string, diff: string, mode?: \"default\" | \"create\") => string,\n);\n\nexport {\n elideSupersededViewImagePairs,\n sanitizeHistoryItemsForModel,\n stripReasoningEncryptedContent,\n stripReasoningIdentityFromSerializedRunState,\n neutralizeToolSearchItemsInSerializedRunState,\n} from \"./history-sanitizer\";\nexport type { HistoryItem } from \"./history-sanitizer\";\n\n// The provider-bound Model classes used by buildModelInstance/resolveTurnModel.\n// Re-exported so callers (and routing tests) can assert which wire API a\n// resolved turn was bound to — OpenAIChatCompletionsModel for registry \"chat\"\n// providers (Fireworks), OpenAIResponsesModel for the built-in \"responses\" path\n// — without reaching into @openai/agents directly.\nexport { OpenAIChatCompletionsModel, OpenAIResponsesModel } from \"@openai/agents\";\n\nexport {\n CompactionNeededError,\n CompactionProviderResponseError,\n EmptyCompactionSummaryError,\n buildCompactionPromptInput,\n buildCompactionReplacementHistory,\n compactionReplacementFingerprint,\n compactionThresholdTokens,\n clampCompactionThresholdRatio,\n decideCompaction,\n buildSummaryItem,\n buildRemoteCompactionV2PromptInput,\n buildRemoteV2ReplacementHistory,\n extractRemoteCompactionV2OutputItem,\n findCompactionNeededError,\n isCompactionSummary,\n isRemoteCompactionItem,\n isRetainedRemoteV2Message,\n latestCompactionReplacementFingerprint,\n prepareCompactionPromptInput,\n isUserMessage,\n estimateTokens,\n estimateTokensBreakdown,\n estimateItemTokens,\n estimateItemTokenBreakdown,\n estimateOpaqueEncryptedModelVisibleBytes,\n estimateOpaqueEncryptedTokens,\n opaqueEncryptedContentLength,\n estimateNativeImageTokens,\n estimateCompleteModelInput,\n estimateSerializedValueTokens,\n hasModelGeneratedItem,\n renderCompactionPromptInputForChat,\n COMPACTION_SUMMARY_MARKER,\n COMPACTION_PROMPT,\n COMPACT_USER_MESSAGE_MAX_TOKENS,\n REMOTE_V2_RETAINED_MESSAGE_TOKEN_BUDGET,\n REMOTE_COMPACTION_V2_IMPLEMENTATION,\n REMOTE_COMPACTION_V2_BETA_FEATURE,\n DEFAULT_COMPACTION_THRESHOLD_RATIO,\n MIN_COMPACTION_THRESHOLD_RATIO,\n MAX_COMPACTION_THRESHOLD_RATIO,\n SUMMARY_BUFFER_TOKENS,\n SUMMARY_PREFIX,\n USER_MESSAGE_TRUNCATION_MARKER,\n UNKNOWN_IMAGE_TOKENS,\n MAX_NATIVE_IMAGE_TOKENS,\n} from \"./context-compaction\";\nexport type {\n CompactionDecision,\n ModelInputTokenBreakdown,\n NativeImageEstimateReason,\n NativeImageTokenEstimate,\n CompactionItem,\n PreparedCompactionPromptInput,\n} from \"./context-compaction\";\nexport {\n MAX_MODEL_USAGE_TOKEN_COUNT,\n modelCallUsageTelemetry,\n modelUsageTokenCountOrNull,\n normalizeModelCallUsage,\n} from \"./usage-telemetry\";\nexport type {\n ModelCallUsageInput,\n ModelCallUsageNormalization,\n ModelCallUsageTelemetry,\n} from \"./usage-telemetry\";\n\nensureReadableStreamFrom();\n\nconst SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS = 120_000;\n\nexport type NormalizedRuntimeEvent = {\n type: SessionEventType;\n payload: unknown;\n};\n\nexport type ModelResponseUsage = {\n responseId?: string;\n serviceTier?: string;\n usage: {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n inputTokensDetails?: Record<string, number> | Array<Record<string, number>>;\n outputTokensDetails?: Record<string, number> | Array<Record<string, number>>;\n requestUsageEntries?: Array<{\n inputTokens?: number;\n input_tokens?: number;\n outputTokens?: number;\n output_tokens?: number;\n totalTokens?: number;\n total_tokens?: number;\n inputTokensDetails?: Record<string, number>;\n input_tokens_details?: Record<string, number>;\n outputTokensDetails?: Record<string, number>;\n output_tokens_details?: Record<string, number>;\n }>;\n };\n};\n\ntype RuntimeMcpTool = Awaited<ReturnType<MCPServer[\"listTools\"]>>[number];\n\ntype FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n\nexport type ResolveConnectionCredentialInput = {\n workspaceId: string;\n subjectId?: string;\n serverId: string;\n toolName?: string;\n connectionRef: McpServerConnectionRef;\n /** Exact MCP destination whose request would receive the resolved headers. */\n destinationUrl: string;\n forceRefresh?: boolean;\n};\n\nexport type ResolveConnectionCredentialResult =\n | {\n status: \"ok\";\n headers: Record<string, string>;\n connectionId: string;\n expiresAt?: Date | null;\n }\n | {\n status: \"auth_needed\";\n reason: ToolAuthNeededPayload[\"reason\"];\n providerDomain: string;\n provider?: string;\n connectionId?: string;\n scopes?: string[];\n resource?: string;\n selectedResources?: McpServerConnectionRef[\"selectedResources\"];\n authorizationUrl?: string;\n };\n\nexport function ensureReadableStreamFrom(): void {\n const ctor = globalThis.ReadableStream as\n | (typeof ReadableStream & {\n from?: <T>(source: Iterable<T> | AsyncIterable<T>) => ReadableStream<T>;\n })\n | undefined;\n if (!ctor || typeof ctor.from === \"function\") {\n return;\n }\n Object.defineProperty(ctor, \"from\", {\n configurable: true,\n writable: true,\n value<T>(source: Iterable<T> | AsyncIterable<T>): ReadableStream<T> {\n const iterator = isAsyncIterable(source)\n ? source[Symbol.asyncIterator]()\n : source[Symbol.iterator]();\n return new ReadableStream<T>({\n async pull(controller) {\n const next = await iterator.next();\n if (next.done) {\n controller.close();\n } else {\n controller.enqueue(next.value);\n }\n },\n async cancel() {\n await iterator.return?.();\n },\n });\n },\n });\n}\n\nexport type AgentSegmentInput =\n | {\n kind: \"message\";\n /** A real human/API prompt. Omitted when resuming the same inference. */\n text?: string;\n /** Ephemeral platform context: system role, never conversation history. */\n internalContext?: string;\n // Canonical conversation truth. When omitted, this is a fresh first\n // message; ordinary messages never deserialize an SDK RunState.\n historyItems?: AgentInputItem[] | null;\n sandboxEnvelope?: Record<string, unknown> | null;\n }\n | {\n kind: \"approval\";\n serializedRunState: string;\n approvalId: string;\n decision: \"approve\" | \"reject\";\n message?: string;\n }\n | {\n kind: \"human_input\";\n serializedRunState: string;\n toolCallId: string;\n };\n\nexport type PreparedAgentInput = {\n input: string | AgentInputItem[] | RunState<any, any>;\n sandboxSessionState?: SandboxSessionState;\n};\n\nexport const HUMAN_INPUT_TOOL_NAME = \"request_human_input\";\n\nexport type SerializedHumanInputInterruption = {\n toolCallId: string;\n input: ReturnType<typeof RequestHumanInputToolInput.parse>;\n};\n\nexport type SandboxFileDownload = {\n fileId: string;\n mountPath: string;\n filename: string;\n url?: string;\n content?: Uint8Array;\n expiresAt?: Date | string;\n sizeBytes?: number;\n};\n\nexport type SandboxFileDownloadFailure = {\n fileId: string;\n filename: string;\n path: string;\n reason: string;\n exitCode?: number;\n output?: string;\n};\n\nexport type SandboxFileDownloadMaterializationResult = {\n failures: SandboxFileDownloadFailure[];\n};\n\nlet runtimeMetricsHooks: RuntimeMetricsHooks | null = null;\n\nexport function configureRuntimeMetricsHooks(hooks: RuntimeMetricsHooks | null | undefined): void {\n runtimeMetricsHooks = hooks ?? null;\n}\n\nexport type OpenGeniRuntime = {\n configure: (settings: Settings) => void;\n // Multi-provider per-turn model routing. Returns the resolved provider, its\n // (cached) client, the provider-bound Model instance, and the configured-model\n // shape; null when the turn's model is not in the registry, so the caller\n // falls back to the legacy global-client path (settings.openaiModel).\n resolveTurnModel: (settings: Settings, modelId: string) => ReturnType<typeof resolveTurnModel>;\n buildAgent: (\n settings: Settings,\n resources: ResourceRef[],\n options?: BuildAgentOptions,\n ) => Agent<any, any>;\n prepareTools: (\n settings: Settings,\n tools: ToolRef[],\n options?: PrepareToolsOptions,\n ) => Promise<PreparedAgentTools>;\n prepareInput: (\n agent: Agent<any, any>,\n input: AgentSegmentInput,\n options?: PrepareInputOptions,\n ) => Promise<PreparedAgentInput>;\n runStream: (\n agent: Agent<any, any>,\n input: PreparedAgentInput,\n settings: Settings,\n options?: RunAgentStreamOptions,\n ) => Promise<Awaited<ReturnType<typeof runAgentStream>>>;\n serializeApprovals: (interruptions: unknown[]) => unknown[];\n serializeHumanInputRequests?: (interruptions: unknown[]) => SerializedHumanInputInterruption[];\n};\n\nexport type ProductionRuntimeOverrides = {\n model?: Model;\n sandboxClient?: unknown;\n metrics?: RuntimeMetricsHooks;\n};\n\nexport function createProductionAgentRuntime(\n overrides: ProductionRuntimeOverrides = {},\n): OpenGeniRuntime {\n return {\n configure: (settings) => {\n configureRuntimeMetricsHooks(overrides.metrics);\n configureOpenAI(settings);\n },\n // A test/override model shadows the registry routing entirely (the scripted\n // model used in worker tests is not in any provider's allow-list), so when\n // one is supplied resolveTurnModel reports \"no resolution\" and the caller\n // keeps the legacy global-client path with the override model.\n resolveTurnModel: (settings, modelId) =>\n overrides.model ? null : resolveTurnModel(settings, modelId),\n buildAgent: (settings, resources, options) =>\n buildOpenGeniAgent(settings, resources, {\n ...options,\n ...(overrides.model ? { model: overrides.model } : {}),\n }),\n prepareTools: prepareAgentTools,\n prepareInput: prepareRunInput,\n runStream: async (agent, input, settings, options) =>\n await runAgentStream(agent, input, settings, {\n ...options,\n sandboxClient: overrides.sandboxClient,\n }),\n serializeApprovals,\n serializeHumanInputRequests,\n };\n}\n\n/**\n * Build an OpenAI client from settings for the configured provider. Mirrors the\n * client construction in configureOpenAI so a direct API call (the compaction\n * summarizer) uses the same Azure/OpenAI auth and base URL. Returns null when\n * the OpenAI-platform path has only a key (the SDK default client is used via\n * setDefaultOpenAIKey there); the caller then constructs a key-only client.\n */\nexport function buildOpenAIClientFromSettings(\n settings: Settings,\n providerId: string = settings.openaiProvider,\n): OpenAI {\n if (settings.openaiProvider === \"azure\") {\n const baseURL = settings.azureOpenaiBaseUrl ?? azureDeploymentBaseUrl(settings);\n const apiKey = settings.azureOpenaiApiKey ?? settings.azureOpenaiAdToken ?? \"azure-ad-token\";\n return new OpenAI({\n apiKey,\n baseURL,\n maxRetries: settings.openaiMaxRetries,\n defaultQuery: azureOpenAIDefaultQuery(settings, baseURL),\n defaultHeaders:\n settings.azureOpenaiAdToken && !settings.azureOpenaiApiKey\n ? { Authorization: `Bearer ${settings.azureOpenaiAdToken}` }\n : undefined,\n // Rewrite every outbound /responses computer_call to the ACTIONS-ONLY shape\n // the GA Azure computer tool accepts. This is the lowest reachable\n // seam — below the SDK responses converter, which always re-synthesizes BOTH\n // `action` and `actions` (rejected 400 \"exactly one of action or actions\").\n // See computerCallNormalizingFetch / rewriteComputerCallsToActionsOnly.\n fetch: computerCallNormalizingFetch(instrumentedModelFetch(providerId, globalThis.fetch)),\n });\n }\n return new OpenAI({\n apiKey: settings.openaiApiKey ?? process.env.OPENAI_API_KEY,\n ...(settings.openaiBaseUrl ? { baseURL: settings.openaiBaseUrl } : {}),\n maxRetries: settings.openaiMaxRetries,\n fetch: instrumentedModelFetch(providerId, globalThis.fetch),\n });\n}\n\n/**\n * One OpenAI client per resolved provider id, built lazily and cached for the\n * process. The built-in openai/azure provider reuses\n * buildOpenAIClientFromSettings verbatim (so its Azure AD/api-version/base-URL\n * construction stays byte-for-byte identical to configureOpenAI); a registry\n * provider gets a plain client pointed at its base URL with its resolved key,\n * the shared maxRetries budget, and its declared defaultQuery/defaultHeaders.\n * Caching by provider.id keeps concurrent multi-provider turns sharing one\n * connection pool per provider rather than reconstructing a client per turn.\n */\nconst providerClientCache = new Map<string, OpenAI>();\n\nexport function buildProviderClient(provider: ResolvedModelProvider, settings: Settings): OpenAI {\n const cached = providerClientCache.get(provider.id);\n if (cached) {\n return cached;\n }\n const client = provider.builtin\n ? buildOpenAIClientFromSettings(settings, provider.id)\n : provider.kind === \"codex-subscription\"\n ? // Codex subscription: the static apiKey is a placeholder — the real per-request\n // bearer + ChatGPT-Account-ID, the /responses->/codex/responses rewrite, and the\n // body normalization are all injected by codexSubscriptionFetch, which reads the\n // per-workspace token from codexRequestStorage (AsyncLocalStorage) at call time.\n // The provider id is constant (\"codex-subscription\"), so one cached client serves\n // every workspace without baking a token into it.\n new OpenAI({\n apiKey: provider.apiKey ?? \"codex-subscription\",\n ...(provider.baseUrl ? { baseURL: provider.baseUrl } : {}),\n // Codex transport owns exactly one explicit 401 refresh/retry. Blind\n // SDK retries on network/5xx/partial streams can replay provider work\n // or external tool side effects without a durable checkpoint.\n maxRetries: 0,\n // The Codex transport owns finer headers/idle/whole deadlines and\n // emits typed durable evidence. Keep the SDK's opaque envelope beyond\n // that whole-response budget so `Request timed out.` cannot win first.\n timeout: CODEX_RESPONSE_SDK_OUTER_TIMEOUT_MS,\n fetch: codexSubscriptionFetch(instrumentedModelFetch(provider.id, globalThis.fetch)),\n })\n : // ResolvedModelProvider.apiKey is already the resolved key (configuredProviders\n // ran resolveProviderApiKey at config time, collapsing apiKey/apiKeyEnv), so it\n // is passed straight through here rather than re-resolved.\n new OpenAI({\n ...(provider.apiKey ? { apiKey: provider.apiKey } : {}),\n ...(provider.baseUrl ? { baseURL: provider.baseUrl } : {}),\n maxRetries: settings.openaiMaxRetries,\n ...(provider.defaultQuery ? { defaultQuery: provider.defaultQuery } : {}),\n ...(provider.defaultHeaders ? { defaultHeaders: provider.defaultHeaders } : {}),\n fetch: instrumentedModelFetch(provider.id, globalThis.fetch),\n });\n providerClientCache.set(provider.id, client);\n return client;\n}\n\n/**\n * Bind a model id to a provider's OpenAI client as an @openai/agents `Model`\n * instance, choosing the wire API by the provider's declared `api`: the \"chat\"\n * providers (e.g. Fireworks) get an OpenAIChatCompletionsModel that speaks\n * /v1/chat/completions, the \"responses\" providers (built-in OpenAI/Azure) get\n * an OpenAIResponsesModel that speaks /v1/responses. Passing this Model into\n * the agent is what routes a turn to its provider without mutating the global\n * default client.\n */\nexport function buildModelInstance(\n provider: ResolvedModelProvider,\n client: OpenAI,\n modelId: string,\n): Model {\n return provider.api === \"chat\"\n ? new OpenAIChatCompletionsModel(client, modelId)\n : new OpenAIResponsesModel(client, modelId);\n}\n\n/**\n * Resolved per-turn model routing: the provider that serves `modelId`, its\n * (cached) OpenAI client, the provider-bound `Model` instance, and the\n * configured-model shape (label/api/contextWindow/reasoningEffort/hostedWebSearch).\n * Returns null when the model is not in the registry — the caller then falls\n * back to the legacy global-client path (settings.openaiModel + the default\n * client configured by configureOpenAI), preserved byte-for-byte.\n */\nexport function resolveTurnModel(\n settings: Settings,\n modelId: string,\n): {\n provider: ResolvedModelProvider;\n client: OpenAI;\n model: Model;\n configured: ConfiguredModel;\n} | null {\n const resolved = resolveModelProvider(settings, modelId);\n if (!resolved) {\n return null;\n }\n const client = buildProviderClient(resolved.provider, settings);\n return {\n provider: resolved.provider,\n client,\n model: buildModelInstance(resolved.provider, client, resolved.model.upstreamModelId),\n configured: resolved.model,\n };\n}\n\n/**\n * Routes a model *name* to its provider-bound Model (Fireworks chat model for a\n * registry model id, the built-in OpenAI/Azure responses model otherwise) via\n * `resolveTurnModel`. This is the load-bearing piece for the sandbox path:\n * passing a Model *instance* as `agent.model` only survives the in-process\n * (`sandboxBackend: \"none\"`) run — on the SandboxAgent/Modal path the instance\n * is dropped and the model *name* is re-resolved through the run's\n * `modelProvider` (or the global default). Without this router that re-resolution\n * hits the default client (e.g. Azure) and a registry model 404s\n * (\"deployment does not exist\"); with it the name resolves back to the right\n * provider. Installed both as the run-scoped `Runner.config.modelProvider` (every\n * run in runAgentStream goes through `runScopedRunner(settings)`, built from the\n * per-turn settings) and as the process default (see configureOpenAI). The\n * run-scoped instance is the load-bearing one: a `Runner` resolves string model\n * names against ITS OWN modelProvider, not the lazy global default, so each\n * concurrent turn routes codex/registry names against its own settings and a\n * foreign turn's setDefaultModelProvider can never clobber this turn's routing.\n * The process default remains only as a boot-time fallback. Falls back to the\n * SDK default provider for a model that is in no provider's allow-list.\n */\nexport class MultiProviderModelProvider implements ModelProvider {\n private fallback: OpenAIProvider | undefined;\n\n constructor(private readonly settings: Settings) {}\n\n async getModel(modelName?: string): Promise<Model> {\n if (modelName) {\n const resolved = resolveTurnModel(\n settingsForRunScopedModelResolution(this.settings, modelName),\n modelName,\n );\n if (resolved) {\n // Fail-loud floor (defense in depth): a `codex/<slug>` id must only ever\n // resolve through the synthetic codex-subscription provider (which installs\n // fetch: codexSubscriptionFetch + the per-workspace bearer). If a future\n // settings path re-introduces a built-in/registry shadow that binds a\n // `codex/` id to any other provider kind, that would silently ship the id\n // to Azure/OpenAI as a deployment name (DeploymentNotFound 404). Refuse it\n // here so codex can never reach a non-codex client on ANY backend; the\n // primary fix (config configuredModels) keeps this a no-op in practice.\n if (\n modelName.startsWith(CODEX_MODEL_ID_PREFIX) &&\n resolved.provider.kind !== \"codex-subscription\"\n ) {\n throw new CodexSubscriptionUnavailableError(modelName);\n }\n return resolved.model;\n }\n // A `codex/<slug>` id only resolves when the per-workspace worker overlay\n // (settingsWithCodexCredential) has injected the synthetic codex-subscription\n // provider — which it does ONLY for a workspace with an *active* connected\n // Codex subscription. If it did not resolve, the subscription is not\n // connected for this workspace, so the codex provider is absent. Falling\n // through to the built-in OpenAIProvider below would ship `codex/<slug>` to\n // the global default (Azure) client as a deployment name and surface a\n // misleading \"DeploymentNotFound\" 404. Throw a clear, user-actionable error\n // instead; it propagates through the worker's agentRunFailurePayload as the\n // turn.failed message the session UI shows. Mirrors the codex-prefix\n // awareness of assertConfiguredModel at apps/api/src/domain/sessions.ts.\n if (modelName.startsWith(CODEX_MODEL_ID_PREFIX)) {\n throw new CodexSubscriptionUnavailableError(modelName);\n }\n }\n // A non-codex model in no provider's allow-list falls back to the SDK's\n // default OpenAIProvider, which uses the global default client/key\n // configureOpenAI set up (the built-in OpenAI/Azure provider).\n this.fallback ??= new OpenAIProvider();\n return this.fallback.getModel(modelName);\n }\n}\n\nfunction settingsForRunScopedModelResolution(settings: Settings, modelName: string): Settings {\n if (modelName !== settings.openaiModel) {\n return settings;\n }\n const builtinAllowed = splitOpenaiAllowedModels(settings.openaiAllowedModels);\n const fallbackBuiltin = builtinAllowed.find((id) => id !== modelName);\n if (!fallbackBuiltin) {\n return settings;\n }\n // The worker sets runSettings.openaiModel to the turn's model. For namespaced\n // registry ids configuredModels filters the built-in entry out, but a unique\n // bare registry id would otherwise be claimed by the built-in only because of\n // that per-turn override. Resolve the run-scoped router against the deployment\n // allow-list head instead; real built-in models stay in the allow-list.\n return builtinAllowed.includes(modelName)\n ? settings\n : { ...settings, openaiModel: fallbackBuiltin };\n}\n\nfunction splitOpenaiAllowedModels(value: string): string[] {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\n/**\n * A `codex/<slug>` turn reached the model router but the workspace has no active\n * Codex subscription connected (the worker overlay never injected the synthetic\n * provider, so resolveTurnModel returned nothing). Thrown instead of silently\n * routing the id to the built-in Azure/OpenAI client — that produced an opaque\n * \"DeploymentNotFound\" 404. The message is user-actionable (connect/reconnect)\n * and carries no status/code, so agentRunFailurePayload surfaces it verbatim as\n * a non-retryable turn.failed the session UI shows.\n */\nexport class CodexSubscriptionUnavailableError extends Error {\n constructor(modelName: string) {\n super(\n `Codex subscription model \"${modelName}\" is unavailable: no active Codex subscription is connected for this workspace. ` +\n `Connect (or reconnect) your ChatGPT/Codex subscription in Settings, then retry.`,\n );\n this.name = \"CodexSubscriptionUnavailableError\";\n }\n}\n\n/**\n * The workspace's model policy blocks the provider/model this turn resolved\n * to. Thrown at the worker's post-resolution gate INSTEAD of running the turn\n * on the blocked provider — a policy-restricted workspace (e.g. fail-closed to\n * the Codex subscription) must never silently remap to, or fall through to,\n * the paid built-in client. Like CodexSubscriptionUnavailableError the message\n * is user-actionable and surfaces verbatim as a non-retryable turn.failed.\n */\nexport class WorkspaceModelPolicyBlockedError extends Error {\n constructor(modelName: string, providerId: string, reason: \"provider\" | \"model\") {\n super(\n reason === \"provider\"\n ? `Model \"${modelName}\" is not available in this workspace: its provider (\"${providerId}\") is not in the workspace's allowed providers. ` +\n `Pick an allowed model, or ask a workspace admin to change the workspace model policy.`\n : `Model \"${modelName}\" is not in this workspace's allowed models. ` +\n `Pick an allowed model, or ask a workspace admin to change the workspace model policy.`,\n );\n this.name = \"WorkspaceModelPolicyBlockedError\";\n }\n}\n\nexport function configureOpenAI(settings: Settings): void {\n setOpenAIResponsesTransport(settings.openaiResponsesTransport);\n setTracingDisabled(settings.disableOpenaiTracing || !settings.observabilityOtlpEndpoint);\n // Install the registry-aware router as the process default model provider so a\n // model name re-resolved on the SandboxAgent/Modal path (where a Model instance\n // does not survive) routes to its provider instead of the built-in client.\n // Built before the default-client calls below so it captures the same settings.\n const router = new MultiProviderModelProvider(settings);\n if (settings.openaiProvider === \"azure\") {\n setDefaultOpenAIClient(buildOpenAIClientFromSettings(settings));\n setDefaultModelProvider(router);\n return;\n }\n if (settings.openaiApiKey) {\n setDefaultOpenAIKey(settings.openaiApiKey);\n }\n if (settings.openaiBaseUrl) {\n setDefaultOpenAIClient(buildOpenAIClientFromSettings(settings));\n }\n setDefaultModelProvider(router);\n}\n\nfunction instrumentedModelFetch(provider: string, inner: typeof fetch): typeof fetch {\n return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n if (!isModelCallFetch(input)) {\n return await inner(input, init);\n }\n const started = performance.now();\n try {\n const response = await inner(input, init);\n recordModelCallMetric(provider, response.ok ? \"completed\" : \"failed\", started);\n return response;\n } catch (error) {\n recordModelCallMetric(provider, \"failed\", started);\n throw error;\n }\n }) as typeof fetch;\n}\n\nfunction isModelCallFetch(input: Parameters<typeof fetch>[0]): boolean {\n const rawUrl =\n typeof input === \"string\"\n ? input\n : input instanceof URL\n ? input.toString()\n : (input as { url?: unknown }).url;\n if (typeof rawUrl !== \"string\" || rawUrl.length === 0) {\n return false;\n }\n try {\n const pathname = new URL(rawUrl, \"http://opengeni.local\").pathname;\n return (\n pathname.endsWith(\"/responses\") ||\n pathname.endsWith(\"/chat/completions\") ||\n pathname.endsWith(\"/codex/responses\")\n );\n } catch {\n return /\\/(?:codex\\/)?responses(?:\\?|$)|\\/chat\\/completions(?:\\?|$)/.test(rawUrl);\n }\n}\n\nfunction recordModelCallMetric(\n provider: string,\n outcome: \"completed\" | \"failed\",\n started: number,\n): void {\n const durationSeconds = Math.max(0, (performance.now() - started) / 1000);\n try {\n runtimeMetricsHooks?.onModelCall?.({ provider, outcome, durationSeconds });\n } catch {\n // Metrics emission must never affect a model call.\n }\n}\n\n/**\n * Run the compaction summarizer as one plain, tool-less, non-streaming model\n * call against the resolved provider. `input` is the active history plus\n * Codex's checkpoint prompt. Provider failures propagate to the compaction\n * lifecycle; there is no non-model fallback that silently discards history.\n * The call deliberately does NOT\n * request reasoning encryption, tools, or inline provider compaction; it is a\n * self-contained summarize.\n *\n * Provider-aware: the summary always runs on the SAME provider that serves the\n * turn (registry providers can't summarize through OpenAI/Azure, and vice\n * versa). `api: \"chat\"` providers (Fireworks) speak /v1/chat/completions, where\n * the summary is choices[0].message.content; `api: \"responses\"` (the default,\n * built-in OpenAI/Azure) speaks /v1/responses as before. When no client/api is\n * supplied it uses the built-in OpenAI/Azure Responses path. store:false is set\n * only on the OpenAI-platform Responses path (Azure rejects it; chat ignores it).\n */\nexport async function summarizeForCompaction(\n settings: Settings,\n input: Array<Record<string, unknown>>,\n options: {\n client?: OpenAI;\n api?: ModelProviderApi;\n maxOutputTokens?: number;\n model?: string;\n promptCacheKey?: string;\n systemInstructions?: string;\n onUsage?: (usage: ModelResponseUsage) => void | Promise<void>;\n } = {},\n): Promise<string> {\n const client = options.client ?? buildOpenAIClientFromSettings(settings);\n const api = options.api ?? \"responses\";\n const model = options.model ?? settings.openaiModel;\n const maxTokens = options.maxOutputTokens ?? SUMMARY_BUFFER_TOKENS;\n if (api === \"chat\") {\n const transcript = renderCompactionPromptInputForChat(input);\n let completion: unknown;\n try {\n completion = await client.chat.completions.create({\n model,\n max_tokens: maxTokens,\n messages: [{ role: \"user\", content: transcript }],\n ...(options.promptCacheKey ? { prompt_cache_key: options.promptCacheKey } : {}),\n } as any);\n } catch (error) {\n throw new CompactionProviderResponseError(compactionProviderFailureDiagnostics(error), error);\n }\n const usage = modelResponseUsageFromResponse(completion);\n if (usage) {\n await options.onUsage?.(usage);\n }\n const text = (completion as { choices?: Array<{ message?: { content?: unknown } }> })\n .choices?.[0]?.message?.content;\n const summary = typeof text === \"string\" ? text.trim() : \"\";\n if (!summary) {\n throw new EmptyCompactionSummaryError(compactionResponseDiagnostics(completion, summary));\n }\n return summary;\n }\n // Use the same SDK Responses adapter as the real agent call. It converts the\n // structured AgentInputItems (callId/providerData/etc.) to provider wire\n // items without flattening tool history into a fake user transcript.\n const request: ModelRequest = {\n systemInstructions: options.systemInstructions ?? \"\",\n input: input as AgentInputItem[],\n modelSettings: {\n maxTokens,\n // Azure rejects store:false; the Codex subscription transport enforces\n // it independently. The OpenAI platform path remains explicitly storeless.\n ...(settings.openaiProvider === \"azure\" ? {} : { store: false }),\n ...(options.promptCacheKey\n ? { providerData: { prompt_cache_key: options.promptCacheKey } }\n : {}),\n },\n tools: [],\n toolsExplicitlyProvided: true,\n outputType: \"text\",\n handoffs: [],\n tracing: false,\n };\n let response: unknown;\n try {\n response = await new CompactionResponsesModel(client, model).fetchResponse(request);\n } catch (error) {\n throw new CompactionProviderResponseError(compactionProviderFailureDiagnostics(error), error);\n }\n const usage = modelResponseUsageFromResponse(response);\n if (usage) {\n await options.onUsage?.(usage);\n }\n if (isFailedCompactionProviderResponse(response)) {\n throw new CompactionProviderResponseError(compactionProviderFailureDiagnostics(response));\n }\n const summary = extractResponseOutputText(response).trim();\n if (!summary) {\n throw new EmptyCompactionSummaryError(compactionResponseDiagnostics(response, summary));\n }\n return summary;\n}\n\n/**\n * Codex remote compaction v2: send active history + `compaction_trigger`, collect\n * exactly one `{ type: \"compaction\", encrypted_content }` output item.\n * Must run inside Codex ALS with `remote_compaction_v2` beta + turn metadata.\n */\nexport async function requestRemoteCompactionV2(\n settings: Settings,\n input: Array<Record<string, unknown>>,\n options: {\n client: OpenAI;\n model: string;\n promptCacheKey?: string;\n onUsage?: (usage: ModelResponseUsage) => void | Promise<void>;\n },\n): Promise<Record<string, unknown>> {\n const promptInput = buildRemoteCompactionV2PromptInput(input);\n const request: ModelRequest = {\n systemInstructions: \"\",\n input: promptInput as AgentInputItem[],\n modelSettings: {\n // Azure rejects store:false; Codex transport enforces store:false itself.\n ...(settings.openaiProvider === \"azure\" ? {} : { store: false }),\n ...(options.promptCacheKey\n ? { providerData: { prompt_cache_key: options.promptCacheKey } }\n : {}),\n },\n tools: [],\n toolsExplicitlyProvided: true,\n outputType: \"text\",\n handoffs: [],\n tracing: false,\n };\n let response: unknown;\n try {\n response = await new CompactionResponsesModel(options.client, options.model).fetchResponse(\n request,\n );\n } catch (error) {\n throw new CompactionProviderResponseError(compactionProviderFailureDiagnostics(error), error);\n }\n const usage = modelResponseUsageFromResponse(response);\n if (usage) {\n await options.onUsage?.(usage);\n }\n if (isFailedCompactionProviderResponse(response)) {\n throw new CompactionProviderResponseError(compactionProviderFailureDiagnostics(response));\n }\n try {\n return extractRemoteCompactionV2OutputItem(response);\n } catch (error) {\n if (error instanceof EmptyCompactionSummaryError) {\n throw new EmptyCompactionSummaryError({\n ...compactionResponseDiagnostics(response, \"\"),\n ...error.diagnostics,\n stage: \"remote_v2_extract\",\n });\n }\n throw error;\n }\n}\n\nfunction isFailedCompactionProviderResponse(response: unknown): boolean {\n if (!response || typeof response !== \"object\") return false;\n const record = response as Record<string, unknown>;\n return (\n record.status === \"failed\" ||\n record.status === \"incomplete\" ||\n (record.error !== null && record.error !== undefined)\n );\n}\n\n/** Bounded provider diagnostics: identifiers and classifications, never messages or model data. */\nexport function compactionProviderFailureDiagnostics(error: unknown): Record<string, unknown> {\n let current = error;\n let errorName: string | null = null;\n let httpStatus: number | null = null;\n let responseStatus: string | null = null;\n let responseId: string | null = null;\n let code: string | null = null;\n let type: string | null = null;\n let requestId: string | null = null;\n let eventType: string | null = null;\n const seen = new Set<object>();\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 record = current as Record<string, unknown>;\n if (!errorName && current instanceof Error) {\n errorName = boundCompactionDiagnosticField(current.name);\n }\n if (\n httpStatus === null &&\n typeof record.status === \"number\" &&\n Number.isFinite(record.status)\n ) {\n httpStatus = record.status;\n }\n if (responseStatus === null && typeof record.status === \"string\") {\n responseStatus = boundCompactionDiagnosticField(record.status);\n }\n const directResponseStatus = record.response_status ?? record.responseStatus;\n if (responseStatus === null && typeof directResponseStatus === \"string\") {\n responseStatus = boundCompactionDiagnosticField(directResponseStatus);\n }\n const directResponseId = record.response_id ?? record.responseId ?? record.id;\n if (responseId === null && typeof directResponseId === \"string\") {\n responseId = boundCompactionDiagnosticField(directResponseId);\n }\n if (code === null && typeof record.code === \"string\") {\n code = boundCompactionDiagnosticField(record.code);\n }\n if (type === null && typeof record.type === \"string\") {\n type = boundCompactionDiagnosticField(record.type);\n }\n const directEventType = record.event_type ?? record.eventType;\n if (eventType === null && typeof directEventType === \"string\") {\n eventType = boundCompactionDiagnosticField(directEventType);\n }\n if (requestId === null) {\n const directRequestId = record.request_id ?? record.requestId ?? record._request_id;\n if (typeof directRequestId === \"string\") {\n requestId = boundCompactionDiagnosticField(directRequestId);\n }\n const headers = record.headers;\n if (!requestId && headers && typeof headers === \"object\") {\n const get = (headers as { get?: unknown }).get;\n if (typeof get === \"function\") {\n const headerId = get.call(headers, \"x-request-id\");\n if (typeof headerId === \"string\") {\n requestId = boundCompactionDiagnosticField(headerId);\n }\n }\n }\n }\n const nestedError = record.error;\n if (nestedError && typeof nestedError === \"object\" && !seen.has(nestedError)) {\n const nested = nestedError as Record<string, unknown>;\n if (code === null && typeof nested.code === \"string\") {\n code = boundCompactionDiagnosticField(nested.code);\n }\n if (type === null && typeof nested.type === \"string\") {\n type = boundCompactionDiagnosticField(nested.type);\n }\n const nestedResponseStatus = nested.response_status ?? nested.responseStatus;\n if (responseStatus === null && typeof nestedResponseStatus === \"string\") {\n responseStatus = boundCompactionDiagnosticField(nestedResponseStatus);\n }\n const nestedResponseId = nested.response_id ?? nested.responseId ?? nested.id;\n if (responseId === null && typeof nestedResponseId === \"string\") {\n responseId = boundCompactionDiagnosticField(nestedResponseId);\n }\n const nestedEventType = nested.event_type ?? nested.eventType;\n if (eventType === null && typeof nestedEventType === \"string\") {\n eventType = boundCompactionDiagnosticField(nestedEventType);\n }\n }\n current = record.cause;\n }\n return {\n errorName,\n httpStatus,\n responseStatus,\n responseId,\n code,\n type,\n requestId,\n ...(eventType ? { eventType } : {}),\n };\n}\n\nconst COMPACTION_DIAGNOSTIC_FIELD_MAX_BYTES = 256;\nconst COMPACTION_DIAGNOSTIC_TRUNCATION_MARKER = \"…[truncated]\";\n\nfunction boundCompactionDiagnosticField(value: string): string {\n const bytes = Buffer.from(value, \"utf8\");\n if (bytes.length <= COMPACTION_DIAGNOSTIC_FIELD_MAX_BYTES) return value;\n const markerBytes = Buffer.byteLength(COMPACTION_DIAGNOSTIC_TRUNCATION_MARKER, \"utf8\");\n let end = COMPACTION_DIAGNOSTIC_FIELD_MAX_BYTES - markerBytes;\n while (end > 0 && isUtf8ContinuationByte(bytes[end]!)) end -= 1;\n return `${bytes.subarray(0, end).toString(\"utf8\")}${COMPACTION_DIAGNOSTIC_TRUNCATION_MARKER}`;\n}\n\nfunction isUtf8ContinuationByte(value: number): boolean {\n return (value & 0xc0) === 0x80;\n}\n\n/** Bounded, content-free diagnostics for a semantically empty checkpoint. */\nexport function compactionResponseDiagnostics(\n response: unknown,\n extractedText = extractResponseOutputText(response).trim(),\n): Record<string, unknown> {\n if (!response || typeof response !== \"object\") {\n return { responseShape: typeof response, extractedTextLength: extractedText.length };\n }\n const record = response as Record<string, unknown>;\n const output = Array.isArray(record.output) ? record.output : [];\n const outputItems = output.slice(0, 50).map((item) => {\n if (!item || typeof item !== \"object\") return { type: typeof item };\n const value = item as Record<string, unknown>;\n const content = Array.isArray(value.content) ? value.content : [];\n return {\n type: typeof value.type === \"string\" ? value.type : null,\n role: typeof value.role === \"string\" ? value.role : null,\n status: typeof value.status === \"string\" ? value.status : null,\n contentPartTypes: content\n .slice(0, 50)\n .map((part) =>\n part && typeof part === \"object\" && typeof (part as { type?: unknown }).type === \"string\"\n ? (part as { type: string }).type\n : typeof part,\n ),\n contentPartCount: content.length,\n };\n });\n const choices = Array.isArray(record.choices) ? record.choices : [];\n const usage = modelResponseUsageFromResponse(response)?.usage;\n const incomplete =\n record.incomplete_details && typeof record.incomplete_details === \"object\"\n ? (record.incomplete_details as Record<string, unknown>)\n : null;\n return {\n responseId: typeof record.id === \"string\" ? record.id : null,\n status: typeof record.status === \"string\" ? record.status : null,\n outputItemCount: output.length,\n outputItems,\n choiceCount: choices.length,\n finishReasons: choices\n .slice(0, 20)\n .map((choice) =>\n choice && typeof choice === \"object\"\n ? ((choice as Record<string, unknown>).finish_reason ?? null)\n : null,\n ),\n incompleteReason:\n incomplete && typeof incomplete.reason === \"string\" ? incomplete.reason : null,\n inputTokens: usage?.inputTokens ?? null,\n outputTokens: usage?.outputTokens ?? null,\n totalTokens: usage?.totalTokens ?? null,\n extractedTextLength: extractedText.length,\n };\n}\n\n/**\n * Pull the assistant text out of a Responses API result, shape-tolerant. Only\n * `role === \"assistant\"` message items contribute: a provider whose Responses\n * endpoint echoes the user input back as an output `message` item (Fireworks'\n * beta /v1/responses does exactly this — see docs/model-providers.md) would\n * otherwise corrupt the summary with the prompt it was given. The OpenAI/Azure\n * Responses API only emits assistant messages, so this guard is a no-op there.\n */\nexport function extractResponseOutputText(response: unknown): string {\n if (!response || typeof response !== \"object\") {\n return \"\";\n }\n const direct = (response as { output_text?: unknown }).output_text;\n if (typeof direct === \"string\") {\n return direct;\n }\n const output = (response as { output?: unknown }).output;\n if (!Array.isArray(output)) {\n return \"\";\n }\n const parts: string[] = [];\n for (const item of output) {\n if (!item || typeof item !== \"object\") {\n continue;\n }\n if ((item as { type?: unknown }).type !== \"message\") {\n continue;\n }\n // Read assistant messages only; skip any input-echo (role \"user\"/\"system\").\n if ((item as { role?: unknown }).role !== \"assistant\") {\n continue;\n }\n const content = (item as { content?: unknown }).content;\n if (!Array.isArray(content)) {\n continue;\n }\n for (const part of content) {\n if (\n part &&\n typeof part === \"object\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n parts.push((part as { text: string }).text);\n }\n }\n }\n return parts.join(\"\");\n}\n\n/**\n * The public SDK getResponse() method is runner-facing and always opens a\n * tracing span. Compaction is a standalone model call, so use the same SDK\n * request conversion and Responses transport without manufacturing a runner\n * trace solely to satisfy that wrapper.\n */\nclass CompactionResponsesModel extends OpenAIResponsesModel {\n fetchResponse(request: ModelRequest) {\n return this._fetchResponse(request, false);\n }\n}\n\nexport type GitTokenSeeds = Partial<Record<GitCredentialProvider, string>>;\nexport type GitCredentialBindingSeed = {\n credentialBindingId: string;\n provider: GitCredentialProvider;\n token: string;\n transport?: GitCredentialTransport;\n expiresAt?: string;\n /** Total active bindings for this provider, used to suppress unsafe aliases. */\n providerBindingCount?: number;\n};\nexport type GitCredentialTokenWriterSession = SandboxSessionLike;\nexport type ToolspaceTokenWriterSession = SandboxSessionLike;\n\nexport type EffectiveSkillSelection = Readonly<{\n id: string;\n name: string;\n source: \"bundled\" | \"library\" | \"pack\" | \"session\";\n version: string | null;\n contentSha256: string | null;\n reason: string;\n}>;\n\nconst agentSkillSelections = new WeakMap<object, readonly EffectiveSkillSelection[]>();\nconst emptySkillSelections: readonly EffectiveSkillSelection[] = Object.freeze([]);\n\n/**\n * Read-only, secret-free skill provenance for an already-built agent. This is\n * intentionally separate from the model instructions and sandbox manifest so\n * effective configuration inspection cannot accidentally expose credentials or\n * turn skill activation into an authorization change.\n */\nexport function effectiveSkillSelectionsForAgent(\n agent: object,\n): readonly EffectiveSkillSelection[] {\n return agentSkillSelections.get(agent) ?? emptySkillSelections;\n}\n\nexport type BuildAgentOptions = {\n model?: Model;\n /** Settled response for the one internal human-input interruption resumed by this run. */\n humanInputResponse?: {\n requestId: string;\n toolCallId: string;\n response: HumanInputResponse;\n };\n reasoningEffort?: ReasoningEffort;\n /** Product latency selection frozen onto this turn. */\n latencyMode?: LatencyMode;\n /** Provider-specific wire value resolved by the worker (`fast` or `priority`). */\n serviceTier?: \"fast\" | \"priority\";\n // Per-turn gating overrides for the multi-provider path. Each defaults to\n // today's settings-derived behaviour when omitted, so the legacy\n // global-client callers (no model resolution) are byte-for-byte unchanged.\n //\n // - hostedWebSearch: attach the hosted web_search tool. Only the providers\n // that actually execute it (built-in OpenAI/Azure; a registry model that\n // opts in) should get it — Fireworks accepts the param but no-ops it, which\n // would hand the agent a dead tool. Default: settings.webSearchEnabled.\n // - encryptedReasoning: round-trip reasoning.encrypted_content via\n // providerData.include. Only the Responses API carries it; the chat wire\n // API has no such field, so registry \"chat\" providers turn it off.\n // Default: settings.openaiReasoningEncryptedContent.\n // - structuredToolTransport: whether the backend supports the Responses\n // STRUCTURED/HOSTED sandbox-tool transport — the hosted `apply_patch` tool\n // type and structured `view_image` output. The SDK's sandbox capabilities\n // pick hosted-vs-function purely from the bound model instance's constructor\n // name (supportsApplyPatchTransport / supportsStructuredToolOutputTransport).\n // Our codex turns run the OpenAIResponsesModel — which the SDK reads as\n // hosted-capable — but route it to the ChatGPT/Codex backend, which REJECTS\n // the hosted `apply_patch` type (\"Unsupported tool type: apply_patch\",\n // verified live). Set false for that backend so filesystem emits the\n // function `apply_patch` + text `view_image` variants it accepts. Default\n // true (let the SDK decide from the model instance) — non-codex paths are\n // byte-for-byte unchanged.\n hostedWebSearch?: boolean;\n encryptedReasoning?: boolean;\n structuredToolTransport?: boolean;\n // EXPLICIT computer-use tool transport, decided where provider identity is\n // authoritative (the worker's model resolution — agent-turn.ts). Threaded into\n // buildAgentCapabilities → computerUse({toolMode}) so tool selection never rests\n // on the SDK's constructor-name sniff. Omitted means disabled/fail-closed.\n computerToolMode?: ComputerToolMode;\n /**\n * Invoked once, immediately before the first real computer action and after\n * the display is ready. Merely advertising computer-use does not call it.\n * The worker uses this seam for computer-use-only recording; ordinary\n * shell/filesystem turns never pay that cost.\n */\n onComputerUseReady?: (session: SandboxSessionLike) => Promise<void>;\n // The LIVE, by-reference connector-namespace Set from prepareAgentTools\n // (codexConnectorNamespaces): fills during each turn's codex_apps tools/list,\n // read per model call by the codex tool_search description so the model sees\n // the account's ACTUALLY-connected sources (codex-rs parity). Only meaningful\n // on the codex tool-search path.\n codexConnectorNamespaces?: ReadonlySet<string>;\n // Stable per-session routing key for provider-side prompt prefix caches. The\n // worker passes this only for transports whose docs/API surface accept\n // prompt_cache_key; registry providers that use a different affinity field stay\n // unset to avoid unknown-parameter 400s.\n promptCacheKey?: string;\n sandboxEnvironment?: Record<string, string>;\n // The EFFECTIVE/active compute backend for this turn. `settings.sandboxBackend`\n // is the session's HOME backend (the default cloud group box it was created\n // with); when a session has swapped its active sandbox to a connected machine\n // (active_sandbox_id → a selfhosted lease, while the home backend stays the\n // cloud default), the worker passes that machine's backend here so\n // filesystem-touching lifecycle hooks key off where the agent ACTUALLY runs,\n // not where it was created. The one such hook today is the repository clone\n // (sandboxRepositoryCloneHooks): a bring-your-own machine owns its real disk,\n // so the platform must NEVER `git clone` onto it. Defaults to\n // settings.sandboxBackend, so the legacy cloud paths are byte-for-byte\n // unchanged and a session whose HOME backend is \"selfhosted\" is gated with no\n // caller change.\n activeSandboxBackend?: Settings[\"sandboxBackend\"];\n fileResourceDownloads?: SandboxFileDownload[];\n mcpServers?: MCPServer[];\n // Workspace Memory V1 working-set block, resolved by the worker per turn.\n // Composed after the workspace persona/CORE/toolspace substrate and before\n // per-session instructions. Omitted/blank ⇒ byte-identical instructions.\n workspaceMemory?: string;\n workspaceEnvironment?: WorkspaceEnvironmentContext;\n // M3 rig runtime binding (all absent ⇒ a rig-less turn, byte-for-byte today).\n // - `rig`: renders the non-bypassable rig doctrine block in the CORE.\n // - `rigSetup`: the rig version's setup script, run ONCE per box (marker-\n // guarded) as the FIRST beforeAgentStart hook so later hooks see its tooling.\n // - `rigCredentialHookIds`: the rig version's credential_hooks, unioned with\n // the deployment preparation-profile hooks. Resolved (and VALIDATED — an\n // unknown name throws here, at build = per-turn resolution time) so a typo'd\n // hook fails the turn instead of being silently ignored.\n rig?: RigInstructionsContext;\n rigSetup?: RigSetupDescriptor;\n rigCredentialHookIds?: string[];\n // TOKEN-BROKER (B1): the run-scoped GitHub App installation token alias,\n // minted ONCE per turn by the worker (sandboxEnvironmentForRun's `gitToken`).\n // Kept for back-compat; internally it maps to gitTokenSeeds.github.\n gitTokenSeed?: string;\n // Provider-token map for GitHub/GitLab/Azure DevOps. Threaded here OFF-\n // MANIFEST — it is NOT part of sandboxEnvironment (the manifest env), so token\n // VALUES never trigger the SDK's provided-session env-delta guard even though\n // they rotate every turn. buildAgent stashes them alongside the agent's\n // repository-clone hooks; runStream forwards them into the hook context, which\n // seeds provider token FILES before the clone/setup runs.\n gitTokenSeeds?: GitTokenSeeds;\n // Provider-neutral, independently mintable credentials. Binding ids remain\n // off-manifest and are hashed before they influence sandbox paths.\n gitCredentialBindings?: GitCredentialBindingSeed[];\n // TOOLSPACE: the run-scoped delegated token to seed into\n // $OPENGENI_TOOLSPACE_TOKEN_FILE. Like gitTokenSeed, this stays off the\n // manifest/env delta and is written into the sandbox filesystem by a lifecycle\n // hook before the agent starts.\n toolspaceTokenSeed?: string;\n // Durable OpenGeni session identity used only to derive the off-manifest,\n // per-session token file. Required together with toolspaceTokenSeed so two\n // sessions sharing one box never overwrite the same pointer.\n toolspaceTokenSessionId?: string;\n // Genesis turn only: inject a one-shot instruction into the FIRST model\n // call telling it to title the session via opengeni__set_session_title.\n // Keeping this out of the persistent Agent.instructions prevents every\n // tool-follow-up model call in a long first turn from re-running setup.\n genesisTitleHint?: boolean;\n // Persistent session settings, resolved by the worker from the durable\n // session row at turn start. Tool schemas are rebuilt on every turn, so\n // without this factual state the model can mistake persistent metadata tools\n // for per-turn initialization and re-apply the same title/notification mode.\n // Values only — never the user-controlled title text — enter instructions.\n persistentSessionSettings?: PersistentSessionSettings;\n // Per-call agent persona override (the white-label surface). Resolved by the\n // caller as session > workspace > deployment default; when omitted the\n // runtime falls back to settings.agentInstructionsTemplate. The runtime\n // substitutes the non-bypassable CORE at AGENT_INSTRUCTIONS_CORE_PLACEHOLDER\n // (or appends it when the template omits the marker), so an override can\n // restyle the persona but never drop the goal-loop contract or environment\n // block.\n instructionsTemplate?: string;\n // Per-SESSION persona/system instructions (the per-agent-type prompt lever an\n // embedding host supplies at session create). Composed AFTER the workspace\n // instructionsTemplate + the non-bypassable CORE, so it refines the workspace\n // persona for this one session without dropping the goal-loop/environment\n // contract. Rides the SAME instructions channel (system-level) — NEVER a user/\n // timeline message. Omitted ⇒ the composed instructions are byte-identical to\n // a workspace-only persona.\n sessionInstructions?: string;\n // Host context for this exact accepted turn. Composed system-level after the\n // durable session persona and omitted from all later turns.\n turnInstructions?: string;\n // Skills delivered by enabled capability packs. They join the bundled\n // skills in the sandbox skill index (mounted under .agents/) so\n // skills/<name> references resolve like any other indexed skill.\n packSkills?: PackSkill[];\n // Inline skills fixed onto this session at creation. They use the SDK's lazy\n // skill source and are materialized only when the model loads one.\n sessionSkills?: PackSkill[];\n // Explicitly selected, immutable curated-library skill content. These are\n // separate from packSkills so repository-local/pack compatibility does not\n // turn a curated entry into a mutable override.\n skillLibrarySkills?: PackSkill[];\n // Secret-free provenance for effective-configuration inspection. The worker\n // resolves exact ids/versions/hashes before constructing the agent.\n skillLibrarySelections?: EffectiveSkillSelection[];\n /**\n * Internal per-attempt cancellation boundary. The worker supplies Temporal's\n * signal so an in-flight shell process is interrupted immediately instead of\n * holding Steer/Pause behind its requested yield or natural exit.\n */\n turnCancellationSignal?: AbortSignal;\n /**\n * Receives the physical sandbox-tool fence at agent construction time. A\n * cancelled/fenced worker attempt must await it before publishing its durable\n * attempt-quiesced receipt.\n */\n onToolCancellationFence?: (fence: TurnToolCancellationFence) => void;\n};\n\nexport type PackSkillFile = {\n // Relative POSIX path inside the skill directory, e.g. \"SKILL.md\" or\n // \"references/runbook.md\".\n path: string;\n content: string;\n};\n\nexport type PackSkill = {\n name: string;\n description?: string | null | undefined;\n files: PackSkillFile[];\n};\n\n/**\n * Operator-facing metadata for the workspace environment attached to a run.\n * Surfaced verbatim in the agent instructions: the description is where\n * operators document how the exported credentials are meant to be used\n * (e.g. which variable holds a deploy key and how to clone with it), so an\n * agent must not have to rediscover that by enumerating `env` and guessing.\n * Only metadata belongs here — never variable values.\n */\nexport type WorkspaceEnvironmentContext = {\n name: string;\n description?: string | null;\n variableNames?: string[];\n};\n\nexport type PersistentSessionSettings = {\n titleIsSet: boolean;\n};\n\n/**\n * The rig a session rides (M3): its name + the active version pinned onto the\n * session. Surfaced verbatim in the non-bypassable CORE instructions so the\n * agent understands its sandbox is a disposable fork of a shared, versioned\n * machine definition and how to promote a durable change. Absent for rig-less\n * sessions (the block never renders).\n */\nexport type RigInstructionsContext = {\n name: string;\n version: number;\n};\n\nexport function rigInstructions(rig: RigInstructionsContext): string[] {\n return [\n `This session runs on rig \"${rig.name}\" (active version v${rig.version}) — a shared, versioned sandbox machine definition for your workspace.`,\n \"Your sandbox is an EPHEMERAL FORK of that rig: you have root and may install anything freely, but everything you change here is junk that dies with the box and never reaches the rig or other sessions.\",\n \"For a DURABLE, team-wide change (tooling every future session on this rig should have), propose it with rig_propose_change, passing the EXACT command that already worked in this box — never assume an unverified change propagates.\",\n \"If tooling you expect is missing, consult rig_get to see the rig's current setup and checks before reinstalling.\",\n ];\n}\n\nexport function workspaceEnvironmentInstructions(\n environment: WorkspaceEnvironmentContext,\n): string[] {\n const lines = [\n `A workspace environment named \"${environment.name}\" is attached to this session; its variables are exported in the sandbox shell environment.`,\n ];\n const variableNames = (environment.variableNames ?? []).filter((name) => name.length > 0);\n if (variableNames.length > 0) {\n lines.push(`Exported environment variables: ${[...variableNames].sort().join(\", \")}.`);\n }\n const description = environment.description?.trim();\n if (description) {\n lines.push(`Environment notes from the operator: ${description}`);\n }\n return lines;\n}\n\n/**\n * The non-bypassable CORE of the agent instructions: the goal-loop ownership\n * line (which names the opengeni__goal_* tools and is what keeps a long-running\n * session driving itself) followed by the dynamic workspace-environment block.\n * Returned as ordered lines so the caller joins them with the rest of the\n * instructions by \" \", exactly as the historical preamble did.\n *\n * This is the slice a white-labelled persona template must never be able to\n * drop: composeAgentInstructions() substitutes it at the persona template's\n * {{core}} marker, and appends it when the marker is absent.\n */\nexport function coreInstructions(\n workspaceEnvironment?: WorkspaceEnvironmentContext,\n rig?: RigInstructionsContext,\n): string[] {\n return [\n \"If the session has a goal, you own it: keep working until you call opengeni__goal_complete with concrete evidence or opengeni__goal_pause with a rationale; revise it with opengeni__goal_update; create one with opengeni__goal_set when given a long-running objective.\",\n ...(workspaceEnvironment ? workspaceEnvironmentInstructions(workspaceEnvironment) : []),\n // Rig doctrine (M3): data-conditional, inside the non-bypassable CORE so a\n // white-label persona template can never drop it. Absent for rig-less sessions.\n ...(rig ? rigInstructions(rig) : []),\n ];\n}\n\n/**\n * Composes the final agent instructions from a (possibly white-labelled)\n * persona template and the non-bypassable CORE. The CORE is substituted at the\n * template's {{core}} marker; if the template omits the marker, the CORE is\n * appended after it instead (the non-bypassable fail-safe). The substitution\n * and the append both join by \" \", so the DEFAULT_AGENT_INSTRUCTIONS template\n * with an empty environment reproduces the historical preamble byte-for-byte.\n */\nexport function composeAgentInstructions(\n template: string,\n workspaceEnvironment?: WorkspaceEnvironmentContext,\n rig?: RigInstructionsContext,\n): string {\n const core = coreInstructions(workspaceEnvironment, rig).join(\" \");\n if (template.includes(AGENT_INSTRUCTIONS_CORE_PLACEHOLDER)) {\n return template.split(AGENT_INSTRUCTIONS_CORE_PLACEHOLDER).join(core);\n }\n return core ? `${template} ${core}` : template;\n}\n\n/**\n * Appends the per-session persona instructions to the already-composed\n * (workspace + CORE) instructions, joined by \" \" — exactly the join used\n * throughout the persona composition. The session slice is intentionally LAST\n * (session-specific refinement of the workspace persona). An absent/blank value\n * is a no-op that returns the composed string byte-for-byte.\n */\nexport function appendSessionInstructions(composed: string, sessionInstructions?: string): string {\n const trimmed = sessionInstructions?.trim();\n return trimmed ? `${composed} ${trimmed}` : composed;\n}\n\n/** Append system instructions that apply to this exact turn only. */\nexport function appendTurnInstructions(composed: string, turnInstructions?: string): string {\n const trimmed = turnInstructions?.trim();\n return trimmed ? `${composed} ${trimmed}` : composed;\n}\n\n/**\n * Append the durable session metadata the model otherwise cannot observe.\n * This is deliberately declarative and excludes the title text: the title is\n * user-controlled display metadata, while the agent only needs to know whether\n * initialization has already happened. The block is present on every turn when\n * supplied so compaction cannot erase knowledge that these settings persist.\n */\nexport function appendPersistentSessionSettings(\n composed: string,\n settings?: PersistentSessionSettings,\n): string {\n if (!settings) {\n return composed;\n }\n return `${composed} Persistent session settings already in effect: the display title is ${settings.titleIsSet ? \"set\" : \"not set\"}. This setting persists across turns, continuations, and interruptions. Do not call opengeni__set_session_title merely to reassert an unchanged value; call it only when the current value actually needs to change.`;\n}\n\n/**\n * Appends the workspace memory working-set block to the already-composed\n * (workspace + CORE + generic substrate) instructions, joined by \" \". The\n * memory slice is workspace-ground and intentionally lands before\n * per-session instructions. An absent/blank value is a no-op that returns the\n * composed string byte-for-byte.\n */\nexport function appendWorkspaceMemory(composed: string, workspaceMemory?: string): string {\n const trimmed = workspaceMemory?.trim();\n return trimmed ? `${composed} ${trimmed}` : composed;\n}\n\n/**\n * Appends the generic programmatic-tool-calling (toolspace) directive to the\n * composed workspace + CORE instructions, joined by \" \". This is GENERIC\n * substrate prompting — the same text for every host, never per-host copy.\n *\n * Included ONLY when `toolspaceAvailable` is true, which the caller sets from the\n * exact condition that gates the sandbox token mint: the toolspace feature is\n * enabled AND a toolspace token was minted for THIS turn. That mint now happens\n * on every backend including selfhosted (connected machines get the token too),\n * so the block appears there as well; a turn with no minted token (feature off)\n * has no toolspace URL/token in its sandbox and must not advertise a capability\n * that is not there — the gate is false and this is a no-op. Placed BEFORE the\n * per-session instructions so host/session specificity still wins over this\n * substrate note.\n */\nexport function appendToolspaceInstructions(composed: string, toolspaceAvailable: boolean): string {\n return toolspaceAvailable ? `${composed} ${TOOLSPACE_PROGRAMMATIC_DIRECTIVE}` : composed;\n}\n\nconst GIT_BINDING_DISCOVERY_DIRECTIVE =\n \"This managed sandbox has multiple credential bindings for at least one Git provider. Native Git selects credentials from the repository remote. For gh, glab, or az, run inside the intended attached repository so its origin selects the binding; when running elsewhere, inspect $HOME/.opengeni/git-bindings.json and set OPENGENI_GIT_BINDING to the listed credentialBindingId. The inventory contains identifiers and repository routes, never credential values. A binding marked git_http_broker is Git-only, so use the configured provider MCP tools for provider API operations on it.\";\n\n/**\n * Make multi-account provider-CLI selection discoverable to the model.\n *\n * Binding ids are opaque routing identifiers, not credentials. The detailed,\n * secret-free repository mapping is materialized in the sandbox by the Git\n * setup hook so prompts stay compact.\n */\nexport function appendGitCredentialBindingInstructions(\n composed: string,\n bindings: GitCredentialBindingSeed[] | undefined,\n activeSandboxBackend?: Settings[\"sandboxBackend\"],\n): string {\n if (activeSandboxBackend === \"selfhosted\" || !bindings?.length) {\n return composed;\n }\n const bindingsByProvider = new Map<GitCredentialProvider, Set<string>>();\n for (const binding of bindings) {\n const ids = bindingsByProvider.get(binding.provider) ?? new Set<string>();\n ids.add(binding.credentialBindingId);\n bindingsByProvider.set(binding.provider, ids);\n }\n return [...bindingsByProvider.values()].some((ids) => ids.size > 1)\n ? `${composed} ${GIT_BINDING_DISCOVERY_DIRECTIVE}`\n : composed;\n}\n\n/**\n * Appends the one-shot genesis title directive (genesis turn only), joined by\n * \" \" and always LAST so a white-label persona template or a per-session\n * instruction can't drop it. A no-op when the hint is absent.\n */\nexport function appendGenesisTitleDirective(\n instructions: string,\n genesisTitleHint?: boolean,\n): string {\n return genesisTitleHint ? `${instructions} ${GENESIS_TITLE_DIRECTIVE}` : instructions;\n}\n\nconst agentFileDownloads = new WeakMap<object, SandboxFileDownload[]>();\nconst agentRepositoryCloneHooks = new WeakMap<object, SandboxLifecycleHook[]>();\n// TOKEN-BROKER (B1): the per-turn provider git token seeds, stashed alongside\n// the agent's repository-clone hooks (a parallel map keyed by the agent). Kept\n// OFF the manifest/defaultManifest so rotating values never ride the SDK's\n// provided-session env; runStream reads them to build the clone hook context.\n// Absent when no brokered repo is attached / on the selfhosted path.\nconst agentGitTokenSeeds = new WeakMap<object, GitTokenSeeds>();\nconst agentGitCredentialBindings = new WeakMap<object, GitCredentialBindingSeed[]>();\nconst agentToolspaceTokenSeed = new WeakMap<object, string>();\nconst agentToolspaceTokenSessionId = new WeakMap<object, string>();\n// A genesis directive is consumed by runAgentStream exactly once for the\n// freshly-built agent. It must not remain in Agent.instructions: those\n// instructions are presented again on every internal model/tool loop.\nconst agentsNeedingGenesisTitleDirective = new WeakSet<object>();\n// The EFFECTIVE backend the turn resolved for this agent (undefined -> the home\n// backend). Read by runStream's owned branch to keep platform box-setup hooks off\n// connected machines (a user's real computer).\nconst agentActiveSandboxBackend = new WeakMap<object, Settings[\"sandboxBackend\"]>();\n// M3: the rig-setup descriptor + resolved rig credential hooks for this agent's\n// turn (kept off the manifest like the clone hooks). Read by runStream to build\n// the rig-setup hook and to union the rig credential hooks with the deployment\n// preparation-profile hooks. Absent for a rig-less turn.\nconst agentRigSetup = new WeakMap<object, RigSetupDescriptor>();\nconst agentRigCredentialHooks = new WeakMap<object, SandboxLifecycleHook[]>();\n\n/**\n * The tool output emitted for an MCP tool call that FAILED with a THROWN error\n * — a JSON-RPC protocol error (e.g. -32602 invalid params), an auth 401/403, a\n * transport failure, a timeout, or tool-not-found. Shaped as an MCP\n * `{ isError: true, content }` result so the failure is CARRIED on the tool\n * output rather than erased.\n *\n * The SDK's `defaultToolErrorFunction` would instead turn a thrown tool error\n * into a plain STRING (\"An error occurred while running the tool…\") returned as\n * a NORMAL, successful-looking result — so `agent.toolCall.output` carried no\n * error signal and the timeline rendered the failure as success. `normalizeSdkEvent`\n * captures `RunToolCallOutputItem.output` (the raw function return) verbatim, so\n * returning this object makes the emitted payload's `output.isError === true`,\n * which the timeline projection's `isErrorOutput` (packages/react/src/timeline/\n * projection.ts) settles to \"failed\" and downstream client normalizers read the same field.\n *\n * SCOPE: this only covers THROWN MCP failures (the ones that reach an\n * errorFunction). An MCP tool result carrying `isError: true` INLINE alongside\n * content is stripped to its `content` by @openai/agents-core's streamable-http\n * shim (dist/shims/mcp-server/node.js `callTool` returns `parsed.content`,\n * dropping `parsed.isError`) BEFORE the runtime ever sees it. Covering that mode\n * requires an SDK-level change (preserve `isError`) or reading the raw\n * CallToolResult — tracked separately.\n */\nexport function mcpToolErrorOutput(error: unknown): {\n isError: true;\n content: [{ type: \"text\"; text: string }];\n} {\n const details = redactSensitiveText(error instanceof Error ? error.message : String(error));\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `An error occurred while running the tool. Please try again. Error: ${details}`,\n },\n ],\n };\n}\n\n// Applied to EVERY MCP server via the agent's `mcpConfig.errorFunction`\n// (server-level errorFunctions would win, but PrefixedMcpServer sets none). The\n// SDK types the return as `string`; the runtime actually stores the raw return\n// as the tool output, so we return the MCP-shaped error object and cast — this\n// is the only way to attach an `isError` flag to a failed MCP tool call's output.\nconst mcpToolErrorFunction: MCPToolErrorFunction = ({ error }) =>\n mcpToolErrorOutput(error) as unknown as string;\n\nexport function buildOpenGeniAgent(\n settings: Settings,\n resources: ResourceRef[],\n options: BuildAgentOptions = {},\n): Agent<any, any> {\n if (Boolean(options.toolspaceTokenSeed) !== Boolean(options.toolspaceTokenSessionId)) {\n throw new Error(\"toolspaceTokenSeed and toolspaceTokenSessionId must be supplied together\");\n }\n // Resolved per-turn gating. Each override defaults to today's settings-derived\n // behaviour, so the legacy global-client callers (no resolved model) build the\n // exact same agent as before; the multi-provider worker path passes the\n // resolved provider's api/window/web-search instead.\n const hostedWebSearch = options.hostedWebSearch ?? settings.webSearchEnabled;\n const encryptedReasoning = options.encryptedReasoning ?? settings.openaiReasoningEncryptedContent;\n // Wire value must be provider-mapped by the caller (OpenAI `fast`, Azure/Codex\n // `priority`). Do not fall back to latencyMode itself — that would send\n // invalid Azure tiers.\n const serviceTier = options.serviceTier;\n const providerData = {\n ...(encryptedReasoning ? { include: [\"reasoning.encrypted_content\"] } : {}),\n ...(options.promptCacheKey ? { prompt_cache_key: options.promptCacheKey } : {}),\n ...(serviceTier ? { service_tier: serviceTier } : {}),\n };\n // Native hosted tools attached to every constructed agent. webSearchEnabled\n // is ON by default and provider-unconditional on the built-in path (the live\n // Azure Responses path executes the hosted web_search tool); a registry model\n // only gets it when it opts in (resolved via options.hostedWebSearch), since\n // a provider that no-ops the param would hand the agent a dead tool. The SDK\n // merges this explicit `tools` array with the MCP-server tools\n // (Agent.getAllTools = [...mcpTools, ...tools]) and, on the SandboxAgent path,\n // with the sandbox capability tools (prepareSandboxAgent: tools =\n // [...agent.tools, ...capability.tools()]), so hosted web_search coexists with\n // both rather than overriding them.\n const hostedTools = hostedWebSearch ? [webSearchTool()] : [];\n const humanInputTool = agentTool({\n name: HUMAN_INPUT_TOOL_NAME,\n description:\n \"Pause this turn and request structured human input. Use for decisions or missing information that only a person can provide. Supports free text, single-select, multi-select, an optional Other value, multiple questions, explicit skip policy, and an optional expiry.\",\n parameters: RequestHumanInputToolInput,\n needsApproval: true,\n // A missing/mismatched durable response is a protocol integrity failure,\n // not model-visible tool output the agent may reason past.\n errorFunction: null,\n execute: (_input, _context, details) => {\n const settled = options.humanInputResponse;\n if (!settled) {\n throw new Error(\"Human-input tool resumed without a durable response\");\n }\n const resumedCallId = details?.toolCall?.callId;\n if (resumedCallId && resumedCallId !== settled.toolCallId) {\n throw new Error(\"Human-input response does not belong to the resumed tool call\");\n }\n return JSON.stringify({ requestId: settled.requestId, ...settled.response });\n },\n });\n const agentTools = [...hostedTools, humanInputTool];\n const baseConfig = {\n name: \"OpenGeni Agent\",\n model: options.model ?? settings.openaiModel,\n // White-label persona composition. The effective template is the per-call\n // override (options.instructionsTemplate, resolved by the caller as\n // session > workspace) falling back to the deployment default\n // (settings.agentInstructionsTemplate, default DEFAULT_AGENT_INSTRUCTIONS).\n // composeAgentInstructions substitutes the non-bypassable CORE (goal-loop\n // ownership + workspace-environment block) at the {{core}} marker, or\n // appends it when the template omits the marker. With the default template\n // and no environment this is byte-identical to the historical preamble.\n // Persona composition order (all one system-level instructions string):\n // 1. workspace instructionsTemplate (or deployment default) with the\n // non-bypassable CORE substituted at {{core}} — composeAgentInstructions,\n // 2. + the generic programmatic-tool-calling (toolspace) directive, ONLY\n // when a toolspace token was minted for this turn (feature enabled + a\n // per-turn seed — the mint gate, which includes selfhosted turns since\n // they now receive the token too) — appendToolspaceInstructions,\n // 3. + managed-sandbox Git binding discovery, ONLY when one provider has\n // multiple credential bindings,\n // 4. + workspace memory working set, ONLY when the workspace setting is on\n // and the worker resolved a nonblank block — appendWorkspaceMemory,\n // 5. + the per-session persona instructions (session-specific, so it\n // refines both the workspace persona and the substrate note),\n // 6. + host context for this exact turn, when supplied,\n // 7. + durable session-setting state (title present + child notification\n // mode), when supplied by the worker,\n // The genesis title directive is deliberately NOT part of this persistent\n // string. runAgentStream injects it into the first model call only.\n instructions: appendPersistentSessionSettings(\n appendTurnInstructions(\n appendSessionInstructions(\n appendWorkspaceMemory(\n appendGitCredentialBindingInstructions(\n appendToolspaceInstructions(\n composeAgentInstructions(\n options.instructionsTemplate ?? settings.agentInstructionsTemplate,\n options.workspaceEnvironment,\n options.rig,\n ),\n settings.toolspaceEnabled && Boolean(options.toolspaceTokenSeed),\n ),\n options.gitCredentialBindings,\n options.activeSandboxBackend,\n ),\n options.workspaceMemory,\n ),\n options.sessionInstructions,\n ),\n options.turnInstructions,\n ),\n options.persistentSessionSettings,\n ),\n modelSettings: {\n reasoning: {\n effort: options.reasoningEffort ?? settings.openaiReasoningEffort,\n summary: \"detailed\",\n },\n // Round-trip the encrypted reasoning payload with every call so chains\n // of thought survive without provider-side response storage (which is\n // what stripped provider item ids opt us out of — see\n // stripProviderItemIds). providerData.include replaces any\n // tool-derived include entries; OpenGeni's tools are MCP/sandbox\n // function tools, which contribute none. Gated on the resolved\n // encryptedReasoning flag: the chat wire API has no encrypted_content\n // field, so registry \"chat\" providers turn it off.\n ...(Object.keys(providerData).length > 0 ? { providerData } : {}),\n },\n // Explicit hosted tools (web_search when enabled). Threaded into BOTH the\n // `new Agent(baseConfig)` path (sandboxBackend === \"none\") and the\n // `new SandboxAgent({ ...baseConfig, ... })` path via the shared baseConfig\n // spread; the SDK concatenates these with MCP and sandbox capability tools.\n tools: agentTools,\n ...(options.mcpServers?.length ? { mcpServers: options.mcpServers } : {}),\n // Surface FAILED MCP tool calls as `{ isError: true }` tool output (see\n // mcpToolErrorFunction / mcpToolErrorOutput) instead of the SDK's default\n // flat error string, so a thrown MCP failure (protocol error, auth, timeout,\n // tool-not-found) settles the timeline tool to \"failed\" rather than rendering\n // as success. Applies to every MCP server on this agent (session, first-party,\n // capability, codex_apps) since none set a server-level errorFunction.\n mcpConfig: { errorFunction: mcpToolErrorFunction },\n } as const;\n\n if (settings.sandboxBackend === \"none\") {\n const agent = new Agent(baseConfig);\n if (options.genesisTitleHint) {\n agentsNeedingGenesisTitleDirective.add(agent);\n }\n maybeInstallCodexToolSearch(agent, settings, options);\n applyMcpApprovalPolicy(agent, settings);\n return agent;\n }\n\n const runAs = sandboxRunAs(settings);\n const agent = new SandboxAgent({\n ...baseConfig,\n defaultManifest: buildManifest(\n settings,\n resources,\n options.sandboxEnvironment,\n options.fileResourceDownloads,\n ),\n ...(runAs ? { runAs } : {}),\n capabilities: buildAgentCapabilities(settings, options.packSkills ?? [], {\n ...(options.skillLibrarySkills?.length\n ? { skillLibrarySkills: options.skillLibrarySkills }\n : {}),\n ...(options.sessionSkills?.length ? { sessionSkills: options.sessionSkills } : {}),\n ...repositoryWorkspaceSkillPathsOption(resources),\n ...(options.structuredToolTransport !== undefined\n ? { structuredToolTransport: options.structuredToolTransport }\n : {}),\n ...(options.computerToolMode !== undefined\n ? { computerToolMode: options.computerToolMode }\n : {}),\n ...(options.onComputerUseReady ? { onComputerUseReady: options.onComputerUseReady } : {}),\n ...(options.turnCancellationSignal\n ? { turnCancellationSignal: options.turnCancellationSignal }\n : {}),\n ...(options.onToolCancellationFence\n ? { onToolCancellationFence: options.onToolCancellationFence }\n : {}),\n }),\n });\n agentSkillSelections.set(\n agent,\n Object.freeze(\n effectiveSkillSelections(\n options.skillLibrarySelections ?? [],\n options.skillLibrarySkills ?? [],\n options.packSkills ?? [],\n options.sessionSkills ?? [],\n ).map((selection) => Object.freeze(selection)),\n ),\n );\n if (options.genesisTitleHint) {\n agentsNeedingGenesisTitleDirective.add(agent);\n }\n agentFileDownloads.set(\n agent,\n normalizeSandboxFileDownloads(options.fileResourceDownloads ?? []).filter(\n (download) => !download.content,\n ),\n );\n agentRepositoryCloneHooks.set(\n agent,\n sandboxRepositoryCloneHooks(settings, resources, options.activeSandboxBackend),\n );\n // Stash the EFFECTIVE backend so runStream's owned branch can skip the direct\n // beforeAgentStart hook run on a connected machine: the box there is the user's\n // REAL computer — the platform must not run setup (az login) against it. The\n // clone hooks are already excluded for selfhosted at construction (above); this\n // keeps the built-in hooks equally out.\n if (options.activeSandboxBackend) {\n agentActiveSandboxBackend.set(agent, options.activeSandboxBackend);\n }\n // TOKEN-BROKER (B1): stash per-turn provider seeds off-manifest so runStream\n // can seed the setup hook without tokens ever touching defaultManifest /\n // sandboxEnvironment. `gitTokenSeed` remains the GitHub alias.\n const gitTokenSeeds = {\n ...(options.gitTokenSeeds ?? {}),\n ...(options.gitTokenSeed ? { github: options.gitTokenSeed } : {}),\n } satisfies GitTokenSeeds;\n if (Object.keys(gitTokenSeeds).length > 0) {\n agentGitTokenSeeds.set(agent, gitTokenSeeds);\n }\n if (options.gitCredentialBindings && options.gitCredentialBindings.length > 0) {\n agentGitCredentialBindings.set(agent, options.gitCredentialBindings);\n }\n if (options.toolspaceTokenSeed) {\n agentToolspaceTokenSeed.set(agent, options.toolspaceTokenSeed);\n agentToolspaceTokenSessionId.set(agent, options.toolspaceTokenSessionId!);\n }\n // M3: stash the rig setup descriptor + RESOLVE the rig credential hooks now.\n // sandboxLifecycleHooksForIds throws on an unknown hook name, so a typo'd rig\n // credential_hook fails the turn HERE (per-turn resolution) rather than being\n // silently dropped — the fail-visible contract the brief requires.\n if (options.rigSetup) {\n agentRigSetup.set(agent, options.rigSetup);\n }\n if (options.rigCredentialHookIds && options.rigCredentialHookIds.length > 0) {\n agentRigCredentialHooks.set(agent, sandboxLifecycleHooksForIds(options.rigCredentialHookIds));\n }\n maybeInstallCodexToolSearch(agent, settings, options);\n applyMcpApprovalPolicy(agent, settings);\n return agent;\n}\n\n/**\n * Enable Codex-CLI-style progressive MCP disclosure on a Codex turn when the\n * flag is on. Gated on `structuredToolTransport === false` — the same signal that\n * identifies a Codex-subscription turn (the ChatGPT backend that rejects hosted\n * tools) — so no non-Codex turn is ever touched. On qualifying turns it wraps\n * `getAllTools` (clone-survivingly — see {@link installCodexToolSearch}) to defer\n * selected non-mandatory MCP schemas and add the client tool_search tool. The\n * description combines live connector namespaces with selected server identities.\n */\nfunction maybeInstallCodexToolSearch(\n agent: Agent<any, any>,\n settings: Settings,\n options: BuildAgentOptions,\n): void {\n if (settings.codexToolSearchEnabled && options.structuredToolTransport === false) {\n const mcpServers = options.mcpServers ?? [];\n // `defer_loading:true` removes these MCP schemas from provider context until\n // tool_search discloses a bounded match. Keep the compaction estimator on\n // that same wire truth; otherwise a large deferred catalog can falsely trip\n // compaction before the first real model request. OpenGeni remains eager.\n for (const server of mcpServers) {\n if (server.name === \"opengeni\") continue;\n (\n server as MCPServer & {\n deferModelToolSchemaAccounting?: () => void;\n }\n ).deferModelToolSchemaAccounting?.();\n }\n installCodexToolSearch(\n agent as unknown as Parameters<typeof installCodexToolSearch>[0],\n options.codexConnectorNamespaces ?? new Set<string>(),\n new Set(mcpServers.map((server) => server.name)),\n );\n }\n}\n\n/** True when the unprefixed tool `name` requires approval under `policy`. */\nfunction mcpToolRequiresApproval(\n policy: boolean | ReadonlySet<string>,\n unprefixedName: string,\n): boolean {\n return policy === true || (policy !== false && policy.has(unprefixedName));\n}\n\n/** A per-server approval policy keyed by the server's `<id>__` tool prefix. */\ntype McpApprovalPolicy = {\n prefix: string;\n requireApproval: boolean | ReadonlySet<string>;\n};\n\n/** The subset of the agent surface the approval wrap needs — including `clone`. */\ntype ApprovalCapableAgent = {\n getMcpTools: (runContext: unknown) => Promise<Tool<any>[]>;\n clone?: (config: unknown) => ApprovalCapableAgent;\n};\n\n/**\n * Install the approval wrap on a single agent instance: replace `getMcpTools`\n * with one that stamps `needsApproval: () => true` on every MCP tool whose\n * server policy demands it. Tools are matched by the server's `<id>__` prefix\n * (LONGEST prefix first — see {@link applyMcpApprovalPolicy}), then the\n * unprefixed tool name.\n *\n * CLONE SURVIVAL (mirrors {@link installCodexToolSearch}): the sandbox runtime\n * resolves tools not on the agent we build here but on a FRESH clone —\n * `prepareSandboxAgent` calls `agent.clone(...)`, and `SandboxAgent.clone`\n * reconstructs from a FIXED field list (name/tools/mcpServers/…), so an\n * instance-own `getMcpTools` override is dropped and approval would silently\n * bypass on every sandbox turn. We therefore also wrap `clone` to RE-INSTALL the\n * policy onto every clone, recursively — covering clone-of-clone and the resume\n * paths. The base (non-sandbox) `Agent.clone` spreads `...this` and would carry\n * the override, but re-installing is idempotent there and keeps one code path.\n */\nfunction installMcpApprovalPolicy(\n agent: ApprovalCapableAgent,\n policies: McpApprovalPolicy[],\n): void {\n const listMcpTools = agent.getMcpTools.bind(agent);\n agent.getMcpTools = async (runContext: unknown) => {\n const tools = await listMcpTools(runContext);\n return tools.map((tool) => {\n if (tool.type !== \"function\") {\n return tool;\n }\n const policy = policies.find((entry) => tool.name.startsWith(entry.prefix));\n if (!policy) {\n return tool;\n }\n const unprefixed = tool.name.slice(policy.prefix.length);\n return mcpToolRequiresApproval(policy.requireApproval, unprefixed)\n ? { ...tool, needsApproval: async () => true }\n : tool;\n });\n };\n const originalClone = agent.clone?.bind(agent);\n if (originalClone) {\n agent.clone = (config: unknown) => {\n const cloned = originalClone(config);\n installMcpApprovalPolicy(cloned, policies);\n return cloned;\n };\n }\n}\n\n/**\n * Enforce per-MCP-server human approval. `settings.mcpServers[].requireApproval`\n * is `true` (every tool of that server requires approval) or a string[] of\n * UNPREFIXED tool names (only those do); absent = auto-run. The SDK converts MCP\n * tools to function tools with `needsApproval` unset (defaults false) and exposes\n * no per-server/agent approval knob, so we wrap the agent's `getMcpTools` to\n * attach a `needsApproval: () => true` predicate to the matching tools — matched\n * by the server's `<id>__` prefix, then the unprefixed tool name. A tool that\n * needs approval raises a run INTERRUPTION, which the worker turns into\n * `session.requiresAction` and resolves via `user.approvalDecision`\n * (resumeApproval) — the same generic path shell/computer-use approvals use, so\n * no extra plumbing. No-op when no server requests approval, so the default\n * (auto-run everything) is byte-for-byte unchanged.\n *\n * Two robustness properties the wrap must hold:\n * - LONGEST-PREFIX-FIRST. Server ids can be prefixes of one another (`my` vs\n * `my_`), so their tool prefixes collide (`my__` vs `my___`): a tool like\n * `my___run` (from server `my_`) also `startsWith` `my__` (server `my`). A\n * first-match `find` over unsorted policies could bind it to the WRONG\n * server's policy and bypass gating. Sorting policies by DESCENDING prefix\n * length makes the most-specific (longest) prefix win, so each tool resolves\n * to its own server.\n * - CLONE SURVIVAL. The wrap is re-installed onto every clone; see\n * {@link installMcpApprovalPolicy}.\n */\nfunction applyMcpApprovalPolicy(agent: Agent<any, any>, settings: Settings): void {\n const policies: McpApprovalPolicy[] = settings.mcpServers\n .filter(\n (server) =>\n server.requireApproval === true ||\n (Array.isArray(server.requireApproval) && server.requireApproval.length > 0),\n )\n .map((server) => ({\n prefix: prefixedMcpToolName(server.id, \"\"),\n requireApproval:\n server.requireApproval === true ? true : new Set(server.requireApproval as string[]),\n }))\n .sort((a, b) => b.prefix.length - a.prefix.length);\n if (policies.length === 0) {\n return;\n }\n installMcpApprovalPolicy(agent as unknown as ApprovalCapableAgent, policies);\n}\n\n/**\n * Force a sandbox capability to emit its FUNCTION-transport tool variants instead\n * of the hosted ones, by dropping the model instance the SDK's transport\n * detection keys off. See {@link buildAgentCapabilities} for why (codex routes the\n * OpenAIResponsesModel to the ChatGPT backend, which rejects the hosted\n * `apply_patch` AND `computer_use_preview` tool types). The SDK reads\n * hosted-vs-function ONLY from `_modelInstance` (set via `bindModel`); overriding\n * `bindModel` to discard the instance leaves `_modelInstance` undefined, so\n * `supportsApplyPatchTransport` / `supportsStructuredToolOutputTransport` return\n * false and `tools()` emits the function variants — `apply_patch` + text\n * `view_image` for filesystem, and the `computer_*` function tools + text\n * `computer_screenshot` for computer-use. `bindModel` still returns the capability\n * so the SDK's bind chain (`.bind().bindRunAs().bindModel()`) is preserved.\n */\nfunction neutralizeStructuredToolTransport(\n capability: ReturnType<typeof filesystem> | ReturnType<typeof computerUse>,\n): void {\n // Use `this` (NOT a captured reference to `capability`): the SandboxAgent binds\n // via `cap.clone().bind(session).bindRunAs(runAs).bindModel(model, instance)` and\n // runs tools() on the object the CHAIN returns. Capability.clone() copies this\n // override onto the fresh per-run instance, so bindModel must operate on and\n // RETURN `this` (the clone) — a version that mutated/returned the ORIGINAL\n // capability leaves the clone (which .bind() set `_session` on) out of the chain,\n // so tools() runs on the unbound original and throws \"Filesystem capability is\n // not bound to a SandboxSession\". Dropping the model instance is all we need:\n // supportsApplyPatchTransport(undefined) is false → the function apply_patch.\n const forceFunctionTransport = function (this: Record<string, unknown>): unknown {\n this._modelInstance = undefined;\n return this;\n };\n (capability as unknown as { bindModel: typeof forceFunctionTransport }).bindModel =\n forceFunctionTransport;\n}\n\n/**\n * Build the SandboxAgent capability set explicitly. The SDK default includes\n * its inline provider compaction capability; OpenGeni deliberately omits it\n * because durable portable compaction owns the full history transition.\n */\n/**\n * Wrap the shell capability's `exec_command` so its execution runs inside a\n * tool-call correlation context (op-correlation.ts): the SDK's tool machinery\n * passes `details.toolCall` (the model's function_call, with its durable\n * `callId`) into every function-tool `invoke`, and binding an\n * AsyncLocalStorage around the invocation makes that id visible to the sandbox\n * transport underneath — which mints the DURABLE op id `{callId}:{ordinal}`\n * (op-stream ruling B1). A re-dispatched turn re-executes the same\n * function_call with the same callId, so the transport's idempotent OpStart\n * ATTACHES to the already-running/completed op instead of re-running it.\n * Without a callId (no details on the invocation) the tool runs unwrapped and\n * the transport falls back to a random unique id — today's semantics.\n */\nfunction withExecOpCorrelation(tools: Tool<unknown>[]): Tool<unknown>[] {\n return tools.map((capabilityTool) => {\n if (capabilityTool.type !== \"function\" || capabilityTool.name !== \"exec_command\") {\n return capabilityTool;\n }\n const invoke = capabilityTool.invoke;\n return {\n ...capabilityTool,\n invoke: (runContext, input, details) => {\n const callId = details?.toolCall?.callId;\n if (!callId) {\n return invoke(runContext, input, details);\n }\n return runWithToolCallCorrelation(callId, () => invoke(runContext, input, details));\n },\n };\n });\n}\n\n/**\n * Codex accepts ordinary FUNCTION tools but also accepts `input_image` content\n * inside a function_call_output (the same transport used by codex-rs\n * view_image). The SDK filesystem capability unnecessarily couples this choice\n * to hosted apply_patch support; when hosted tools are disabled it degrades\n * view_image to a giant text data URL, charging roughly one token per four\n * base64 characters. Re-wrap only successful data-URL results as a structured\n * image. Text errors remain text, and the tool itself remains a normal function.\n */\nexport function withStructuredViewImageFunctionResults(tools: Tool<unknown>[]): Tool<unknown>[] {\n return tools.map((capabilityTool) => {\n if (capabilityTool.type !== \"function\" || capabilityTool.name !== \"view_image\") {\n return capabilityTool;\n }\n const invoke = capabilityTool.invoke;\n return {\n ...capabilityTool,\n invoke: async (runContext, input, details) => {\n const output = await invoke(runContext, input, details);\n const dataUrl =\n typeof output === \"string\"\n ? output\n : output &&\n typeof output === \"object\" &&\n typeof (output as { text?: unknown }).text === \"string\"\n ? (output as { text: string }).text\n : null;\n return dataUrl?.startsWith(\"data:image/\")\n ? { type: \"image\" as const, image: { url: dataUrl } }\n : output;\n },\n };\n });\n}\n\nexport function buildAgentCapabilities(\n settings: Settings,\n packSkills: PackSkill[],\n options: {\n skillLibrarySkills?: PackSkill[];\n sessionSkills?: PackSkill[];\n workspaceSkillPaths?: readonly WorkspaceSkillSearchPath[];\n structuredToolTransport?: boolean;\n // EXPLICIT computer-use transport (see BuildAgentOptions.computerToolMode).\n // Omitted/unproven transport fails closed with no computer tools.\n computerToolMode?: ComputerToolMode;\n onComputerUseReady?: (session: SandboxSessionLike) => Promise<void>;\n turnCancellationSignal?: AbortSignal;\n onToolCancellationFence?: (fence: TurnToolCancellationFence) => void;\n } = {},\n): ReturnType<typeof Capabilities.default> {\n const toolCancellation =\n options.turnCancellationSignal || options.onToolCancellationFence\n ? createTurnToolCancellationController(options.turnCancellationSignal)\n : null;\n if (toolCancellation) options.onToolCancellationFence?.(toolCancellation);\n // The `filesystem()` capability picks hosted-vs-function tool variants from the\n // bound model instance (supportsApplyPatchTransport / structured tool output).\n // When the caller declares the backend does NOT support that structured/hosted\n // transport (codex → the ChatGPT backend rejects the hosted `apply_patch` type),\n // neutralize this capability's model binding so tools() falls to the function\n // `apply_patch` + text `view_image` variants the backend accepts — the SDK\n // handles their function_call round-trip natively, so no reimplementation.\n // Scoped to filesystem: shell() is always a function-tool transport.\n const filesystemCapability = filesystem({\n ...(options.structuredToolTransport === false\n ? { configureTools: withStructuredViewImageFunctionResults }\n : {}),\n });\n if (options.structuredToolTransport === false) {\n neutralizeStructuredToolTransport(filesystemCapability);\n }\n const caps: ReturnType<typeof Capabilities.default> = [\n filesystemCapability,\n shell({ ...(toolCancellation ? {} : { configureTools: withExecOpCorrelation }) }),\n ];\n const sessionSkills = sessionSkillsForMaterialization(\n packSkills,\n options.skillLibrarySkills ?? [],\n options.sessionSkills ?? [],\n );\n caps.push(\n skills({\n lazyFrom: lazySkillSourceWithPackSkills(\n [...packSkills, ...sessionSkills],\n options.skillLibrarySkills ?? [],\n ),\n }),\n );\n if (options.workspaceSkillPaths?.length) {\n caps.push(\n workspaceSkills(options.workspaceSkillPaths, [\n ...bundledSkillDirNames(bundledSkillsDir()),\n ...(options.skillLibrarySkills ?? []).map((skill) => skill.name),\n ...packSkills.map((skill) => skill.name),\n ...sessionSkills.map((skill) => skill.name),\n ]),\n );\n }\n // P4.3 computer-use: the agent drives the SAME :0 humans watch (xdotool/XTEST +\n // scrot), but only when the desktop tier is ON, computer-use is enabled, and the\n // backend is one whose image carries the X stack (descriptorgate — honest about\n // which backends are desktop-capable today; headless/dev backends never get the\n // tool, so a misconfigured non-desktop box can't register a tool that always\n // fails). The capability's tools() bind to the live externally-owned session at\n // run time (the SandboxAgent merge); xdotool drives :0 regardless of whether any\n // viewer is attached, so no pixel-tunnel dependency.\n if (\n settings.computerUseEnabled &&\n settings.sandboxDesktopEnabled &&\n desktopCapableBackend(settings.sandboxBackend)\n ) {\n // computer-use is transport-aware, exactly like filesystem: `tools()` emits the\n // HOSTED `computer_use_preview` tool on the structured transport and a set of\n // FUNCTION `computer_*` tools on the text transport. The ChatGPT/Codex backend\n // rejects hosted tool types (only function/custom/web_search accepted).\n //\n // The worker declares an explicit mode from authoritative provider resolution.\n // Exported/public callers that omit it are unproven and therefore disabled.\n const computerCapability = computerUse({\n dimensions: [settings.streamResolutionWidth, settings.streamResolutionHeight],\n readOnly: settings.computerUseReadOnly,\n ...(options.onComputerUseReady ? { onReady: options.onComputerUseReady } : {}),\n toolMode: options.computerToolMode ?? \"disabled\",\n });\n caps.push(computerCapability as unknown as ReturnType<typeof Capabilities.default>[number]);\n }\n if (toolCancellation) {\n for (const capability of caps) {\n wrapCapabilityToolsForTurnCancellation(\n capability as unknown as { tools(): Tool<unknown>[] },\n toolCancellation,\n );\n }\n }\n return caps;\n}\n\nexport function sandboxRunAs(_settings: Settings): string | undefined {\n return undefined;\n}\n\nexport type PreparedAgentTools = {\n mcpServers: MCPServer[];\n close: () => Promise<void>;\n // P4 (Part B.1): the live, by-reference Set of ORIGINAL-dotted connector\n // namespaces the codex_apps transport saw across this turn's tools/list calls.\n // Accumulates as the agent lists tools during the run, so the worker reads it\n // AFTER the turn (in its finally) to cache the serving account's connector set.\n // Empty when this turn has no codex_apps server (or it never listed any\n // namespaced tool) — the worker only persists a non-empty set.\n codexConnectorNamespaces: Set<string>;\n};\n\nexport type PrepareToolsOptions = {\n accountId?: string;\n workspaceId?: string;\n // Worker-asserted session scope for first-party MCP calls; enables\n // session-scoped tools such as goal management on the API side.\n sessionId?: string;\n // The calling turn's id, signed into the token so tools can classify the\n // caller from its own identity instead of the session's live active pointer.\n turnId?: string;\n // The exact executing attempt that owns the MCP call.\n attemptId?: string;\n executionGeneration?: number;\n subjectId?: string;\n subjectLabel?: string;\n // Immutable human authority used only for subject-owned connection lookup.\n // This is intentionally separate from the worker's first-party MCP identity.\n credentialSubjectId?: string;\n // Overrides the fixed first-party MCP permission set for this session's\n // delegated token (manager-style sessions). The caller is responsible for\n // having validated the set against the session creator's grant.\n firstPartyPermissions?: Permission[];\n // Exact model-visible catalog selection for the broad first-party server.\n // Permissions are signed separately and remain the authorization boundary.\n firstPartyTools?: FirstPartyMcpToolName[];\n resolveCredential?: (\n input: ResolveConnectionCredentialInput,\n ) => Promise<ResolveConnectionCredentialResult>;\n onAuthNeeded?: (payload: ToolAuthNeededPayload) => Promise<void> | void;\n /** Injectable final MCP transport for tests and embedded hosts. */\n mcpFetchImpl?: FetchLike;\n};\n\ntype ConnectedMcpServerBatch = Awaited<ReturnType<typeof connectMcpServers>>;\n\nexport type ConnectedMcpServerBatches = {\n active: MCPServer[];\n failed: MCPServer[];\n errors: ReadonlyMap<MCPServer, Error>;\n close: () => Promise<void>;\n};\n\n/**\n * Connect SDK-managed MCP servers in stable, bounded batches. The SDK cleans a\n * failing strict batch; this wrapper additionally closes every earlier batch\n * before rethrowing, so a later-batch failure cannot leak live connections.\n */\nexport async function connectMcpServersInBatches(\n servers: MCPServer[],\n options: { strict: boolean; connectTimeoutMs?: number },\n): Promise<ConnectedMcpServerBatches> {\n assertMcpServerSelectionWithinBounds(servers);\n const batches: ConnectedMcpServerBatch[] = [];\n try {\n for (let offset = 0; offset < servers.length; offset += MCP_MAX_CONCURRENT_SERVER_OPERATIONS) {\n batches.push(\n await connectMcpServers(\n servers.slice(offset, offset + MCP_MAX_CONCURRENT_SERVER_OPERATIONS),\n {\n ...(options.connectTimeoutMs === undefined\n ? {}\n : { connectTimeoutMs: options.connectTimeoutMs }),\n connectInParallel: true,\n strict: options.strict,\n },\n ),\n );\n }\n } catch (error) {\n await closeMcpServerBatches(batches).catch(() => undefined);\n throw error;\n }\n\n const errors = new Map<MCPServer, Error>();\n for (const batch of batches) {\n for (const [server, error] of batch.errors) errors.set(server, error);\n }\n return {\n active: batches.flatMap((batch) => batch.active),\n failed: batches.flatMap((batch) => batch.failed),\n errors,\n close: async () => {\n await closeMcpServerBatches(batches);\n },\n };\n}\n\nasync function closeMcpServerBatches(batches: ConnectedMcpServerBatch[]): Promise<void> {\n let firstError: unknown;\n for (const batch of [...batches].reverse()) {\n try {\n await batch.close();\n } catch (error) {\n firstError ??= error;\n }\n }\n if (firstError !== undefined) throw firstError;\n}\n\nexport async function prepareAgentTools(\n settings: Settings,\n tools: ToolRef[],\n options: PrepareToolsOptions = {},\n): Promise<PreparedAgentTools> {\n // P4 (Part B.1): one Set per prepareTools call, shared by reference into the\n // codex_apps sanitizing fetch so every tools/list this turn accumulates the\n // account's connector namespaces. Surfaced on PreparedAgentTools for the worker.\n const codexConnectorNamespaces = new Set<string>();\n assertMcpServerSelectionWithinBounds(tools);\n if (tools.length === 0) {\n return { mcpServers: [], close: async () => {}, codexConnectorNamespaces };\n }\n const registry = new Map(settings.mcpServers.map((server) => [server.id, server]));\n const subjectOwnedTool = tools.find(\n (tool) => registry.get(tool.id)?.connectionRef?.subjectScope === \"subject\",\n );\n if (subjectOwnedTool && !options.credentialSubjectId) {\n throw new Error(\n `subject-owned connection for MCP server ${subjectOwnedTool.id} requires a human turn initiator`,\n );\n }\n const aggregateToolBudget = new McpAggregateToolListBudget();\n // npm Undici's dispatcher transport can hang indefinitely under Bun even\n // after an AbortSignal fires. Bun's native fetch is the supported runtime\n // transport there; destination policy validation still runs before every\n // credential-bearing MCP request.\n const useBunNativeFetch = options.mcpFetchImpl === undefined && !!process.versions.bun;\n const mcpFetchImpl =\n options.mcpFetchImpl ?? (useBunNativeFetch ? globalThis.fetch.bind(globalThis) : undiciFetch);\n const servers = await boundedParallelMap(\n tools,\n MCP_MAX_CONCURRENT_SERVER_OPERATIONS,\n async (tool, index) => {\n const config = registry.get(tool.id);\n if (!config) {\n throw new Error(`Unknown MCP server id: ${tool.id}`);\n }\n const url = firstPartyMcpServerUrlForRun(settings, config, options.workspaceId) ?? config.url;\n const firstParty = isFirstPartyMcpServer(settings, config);\n const baseFetch = isCodexAppsMcpServer(config)\n ? codexAppsSanitizingFetch(mcpFetchImpl, codexConnectorNamespaces)\n : mcpFetchImpl;\n const guardedFetch = guardedMcpFetch(\n firstParty ? { ...settings, integrationsAllowPrivateNetworkTargets: true } : settings,\n baseFetch,\n {\n ...(firstParty ? { requireHttpsOutsideLocalTest: false } : {}),\n ...(useBunNativeFetch ? { pinResolvedDestination: false } : {}),\n },\n );\n const fetchImpl = config.connectionRef\n ? connectionBrokerFetch(guardedFetch, config, options)\n : firstParty\n ? firstPartyAuthFetch(guardedFetch, settings, options)\n : guardedFetch;\n // A server is connected BEST-EFFORT (a connect OR tools-list failure drops\n // it — its tools go unavailable for the turn — instead of failing the turn)\n // in two cases:\n // - codex_apps: connector availability is RUNTIME-DISCOVERED — the\n // device-code login may lack the connector scopes, and the backend can\n // reject the bearer at the initialize/tools-list handshake, so a 401/403\n // (or a missing/failed token) drops the server.\n // - an optional ToolRef: either an auto-attached workspace-default\n // capability MCP or a client/pack-selected portable ref. A\n // broken/expired credential or unavailable endpoint skips the server\n // with a warning, never killing the turn before the model runs. Bare\n // refs stay strict (below), preserving the fail-loud default.\n // The connect-time drop is handled by connectMcpServers({ strict: false });\n // the tools-list-time drop is enforced inside PrefixedMcpServer.listTools —\n // a best-effort server whose tools/list throws (e.g. an expired connection\n // credential surfacing as a StreamableHTTP \"authentication required\" 401)\n // degrades to zero tools rather than throwing out of the SDK's run-time\n // getAllMcpTools and failing an unrelated turn. The actionable\n // tool.auth_needed signal is preserved: the connection-broker fetch\n // publishes it before returning the 401 that provokes the throw.\n const optional = tool.optional === true;\n const bestEffort = isCodexAppsMcpServer(config) || optional || !!config.connectionRef;\n const server = new PrefixedMcpServer(\n new MCPServerStreamableHttp({\n url,\n name: config.name ?? config.id,\n cacheToolsList: config.cacheToolsList,\n // The upstream transport logger receives raw thrown errors, whose\n // messages may contain response bodies, URLs, headers, or echoed\n // credentials. Keep its diagnostic surface structural only.\n logger: safeMcpTransportLogger(config.id),\n // codex_apps returns connector tools with empty `outputSchema: {}` that the\n // MCP SDK's strict Tool schema rejects (fails the turn during tools/list);\n // sanitize the response on the wire before validation. The namespace Set\n // also captures each tool's original connector namespace (P4 Part B.1).\n fetch: fetchImpl,\n ...(await mcpServerRequestInit(settings, config)),\n ...(config.timeoutMs\n ? {\n timeout: config.timeoutMs,\n clientSessionTimeoutSeconds: Math.ceil(config.timeoutMs / 1000),\n }\n : {}),\n }),\n config.id,\n config.allowedTools,\n bestEffort,\n aggregateToolBudget,\n `${config.id}:${index}`,\n );\n return {\n server,\n bestEffort,\n optional,\n timeoutMs: config.timeoutMs,\n };\n },\n );\n const requiredEntries = servers.filter((entry) => !entry.bestEffort);\n const bestEffortEntries = servers.filter((entry) => entry.bestEffort);\n const requiredServers = requiredEntries.map((entry) => entry.server);\n const bestEffortServers = bestEffortEntries.map((entry) => entry.server);\n // Names of the OPTIONAL servers (not codex_apps) so a drop is surfaced as a\n // warning; codex_apps keeps its historically-quiet drop (a not-logged-in\n // ChatGPT plan is a normal, non-noteworthy state).\n const optionalServerNames = new Set(\n servers.filter((entry) => entry.optional).map((entry) => entry.server.name),\n );\n const connectedRequired = await connectMcpServersInBatches(requiredServers, {\n strict: true,\n connectTimeoutMs: mcpOuterConnectTimeoutMs(requiredEntries.map((entry) => entry.timeoutMs)),\n });\n let connectedBestEffort: ConnectedMcpServerBatches | null = null;\n try {\n connectedBestEffort = bestEffortServers.length\n ? await connectMcpServersInBatches(bestEffortServers, {\n strict: false,\n connectTimeoutMs: mcpOuterConnectTimeoutMs(\n bestEffortEntries.map((entry) => entry.timeoutMs),\n ),\n })\n : null;\n } catch (error) {\n await connectedRequired.close().catch(() => undefined);\n throw error;\n }\n if (connectedBestEffort) {\n for (const failed of connectedBestEffort.failed) {\n if (failed instanceof PrefixedMcpServer) {\n failed.releaseAggregateBudget();\n }\n if (!optionalServerNames.has(failed.name)) {\n continue;\n }\n const error = connectedBestEffort.errors.get(failed);\n console.warn(\n `[mcp] optional server \"${failed.name}\" failed to connect/list tools; skipping it for this turn`,\n safeMcpErrorFields(error),\n );\n }\n }\n return {\n mcpServers: [...connectedRequired.active, ...(connectedBestEffort?.active ?? [])],\n close: async () => {\n let firstError: unknown;\n if (connectedBestEffort) {\n try {\n await connectedBestEffort.close();\n } catch (error) {\n firstError ??= error;\n }\n }\n try {\n await connectedRequired.close();\n } catch (error) {\n firstError ??= error;\n }\n if (firstError !== undefined) throw firstError;\n },\n codexConnectorNamespaces,\n };\n}\n\nfunction connectionBrokerFetch(\n baseFetch: FetchLike,\n config: Settings[\"mcpServers\"][number],\n options: PrepareToolsOptions,\n): FetchLike {\n const connectionRef = config.connectionRef;\n if (!connectionRef) {\n return baseFetch;\n }\n return async (input, init) => {\n const request = await mcpRequestInfo(input, init);\n const destinationUrl = mcpRequestDestinationUrl(input);\n const first = await resolveConnectionForRequest(\n options,\n config.id,\n connectionRef,\n destinationUrl,\n request.toolName,\n false,\n );\n if (first.status === \"auth_needed\") {\n return await authNeededFetchResponse(options, config.id, request, first, connectionRef);\n }\n const response = await baseFetch(\n fetchInputForAttempt(input),\n withConnectionHeaders(input, init, first.headers),\n );\n if (response.status === 401) {\n await cancelMcpResponseBody(response);\n const refreshed = await resolveConnectionForRequest(\n options,\n config.id,\n connectionRef,\n destinationUrl,\n request.toolName,\n true,\n );\n if (refreshed.status === \"auth_needed\") {\n return await authNeededFetchResponse(options, config.id, request, refreshed, connectionRef);\n }\n const retry = await baseFetch(\n fetchInputForAttempt(input),\n withConnectionHeaders(input, init, refreshed.headers),\n );\n if (retry.status === 403) {\n const auth = insufficientScopeAuth(retry.headers, connectionRef, refreshed.connectionId);\n if (auth) {\n await cancelMcpResponseBody(retry);\n return await authNeededFetchResponse(options, config.id, request, auth, connectionRef);\n }\n return retry;\n }\n if (retry.status === 401) {\n await cancelMcpResponseBody(retry);\n return await authNeededFetchResponse(\n options,\n config.id,\n request,\n {\n status: \"auth_needed\",\n reason: \"expired\",\n providerDomain: connectionRef.providerDomain,\n ...(connectionRef.provider ? { provider: connectionRef.provider } : {}),\n connectionId: refreshed.connectionId,\n ...(connectionRef.scopes ? { scopes: connectionRef.scopes } : {}),\n ...(connectionRef.resource ? { resource: connectionRef.resource } : {}),\n ...(connectionRef.selectedResources\n ? { selectedResources: connectionRef.selectedResources }\n : {}),\n },\n connectionRef,\n );\n }\n return retry;\n }\n if (response.status === 403) {\n const auth = insufficientScopeAuth(response.headers, connectionRef, first.connectionId);\n if (auth) {\n await cancelMcpResponseBody(response);\n return await authNeededFetchResponse(options, config.id, request, auth, connectionRef);\n }\n return response;\n }\n return response;\n };\n}\n\nasync function resolveConnectionForRequest(\n options: PrepareToolsOptions,\n serverId: string,\n connectionRef: McpServerConnectionRef,\n destinationUrl: string,\n toolName: string | undefined,\n forceRefresh: boolean,\n): Promise<ResolveConnectionCredentialResult> {\n if (!options.workspaceId || !options.resolveCredential) {\n return {\n status: \"auth_needed\",\n reason: \"missing_connection\",\n providerDomain: connectionRef.providerDomain,\n ...(connectionRef.provider ? { provider: connectionRef.provider } : {}),\n ...(connectionRef.connectionId ? { connectionId: connectionRef.connectionId } : {}),\n ...(connectionRef.scopes ? { scopes: connectionRef.scopes } : {}),\n ...(connectionRef.resource ? { resource: connectionRef.resource } : {}),\n ...(connectionRef.selectedResources\n ? { selectedResources: connectionRef.selectedResources }\n : {}),\n };\n }\n const request: ResolveConnectionCredentialInput = {\n workspaceId: options.workspaceId,\n serverId,\n connectionRef,\n destinationUrl,\n forceRefresh,\n ...(toolName ? { toolName } : {}),\n ...(options.credentialSubjectId ? { subjectId: options.credentialSubjectId } : {}),\n };\n try {\n return await options.resolveCredential(request);\n } catch {\n return {\n status: \"auth_needed\",\n reason: \"refresh_failed\",\n providerDomain: connectionRef.providerDomain,\n ...(connectionRef.provider ? { provider: connectionRef.provider } : {}),\n ...(connectionRef.connectionId ? { connectionId: connectionRef.connectionId } : {}),\n ...(connectionRef.scopes ? { scopes: connectionRef.scopes } : {}),\n ...(connectionRef.resource ? { resource: connectionRef.resource } : {}),\n ...(connectionRef.selectedResources\n ? { selectedResources: connectionRef.selectedResources }\n : {}),\n };\n }\n}\n\nfunction insufficientScopeAuth(\n headers: Headers,\n connectionRef: McpServerConnectionRef,\n connectionId: string,\n): Extract<ResolveConnectionCredentialResult, { status: \"auth_needed\" }> | null {\n const challenge = parseWwwAuthenticate(headers.get(\"www-authenticate\"));\n if (challenge.error !== \"insufficient_scope\") {\n return null;\n }\n return {\n status: \"auth_needed\",\n reason: \"insufficient_scope\",\n providerDomain: connectionRef.providerDomain,\n ...(connectionRef.provider ? { provider: connectionRef.provider } : {}),\n connectionId,\n ...(challenge.scope?.length\n ? { scopes: challenge.scope }\n : connectionRef.scopes\n ? { scopes: connectionRef.scopes }\n : {}),\n ...(challenge.resource\n ? { resource: challenge.resource }\n : connectionRef.resource\n ? { resource: connectionRef.resource }\n : {}),\n ...(connectionRef.selectedResources\n ? { selectedResources: connectionRef.selectedResources }\n : {}),\n };\n}\n\nasync function authNeededFetchResponse(\n options: PrepareToolsOptions,\n serverId: string,\n request: McpRequestInfo,\n auth: Extract<ResolveConnectionCredentialResult, { status: \"auth_needed\" }>,\n connectionRef: McpServerConnectionRef,\n): Promise<Response> {\n const connectionId = auth.connectionId ?? connectionRef.connectionId;\n await publishAuthNeeded(options, {\n serverId,\n toolName: request.toolName ?? null,\n providerDomain: auth.providerDomain,\n ...(auth.provider\n ? { provider: auth.provider }\n : connectionRef.provider\n ? { provider: connectionRef.provider }\n : {}),\n reason: auth.reason,\n ...(connectionId ? { connectionId } : {}),\n ...(auth.scopes\n ? { scopes: auth.scopes }\n : connectionRef.scopes\n ? { scopes: connectionRef.scopes }\n : {}),\n ...(auth.resource\n ? { resource: auth.resource }\n : connectionRef.resource\n ? { resource: connectionRef.resource }\n : {}),\n ...(auth.selectedResources\n ? { selectedResources: auth.selectedResources }\n : connectionRef.selectedResources\n ? { selectedResources: connectionRef.selectedResources }\n : {}),\n ...(auth.authorizationUrl ? { authorizationUrl: auth.authorizationUrl } : {}),\n ...(options.subjectId ? { subjectId: options.subjectId } : {}),\n });\n if (request.method === \"tools/call\") {\n return mcpToolAuthNeededResponse(request.id);\n }\n return new Response(\"Authentication required for MCP server connection\", {\n status: 401,\n });\n}\n\nasync function publishAuthNeeded(\n options: PrepareToolsOptions,\n payload: ToolAuthNeededPayload,\n): Promise<void> {\n try {\n await options.onAuthNeeded?.(payload);\n } catch {\n // Auth-needed events are advisory UI/audit signals; a publisher failure must\n // not turn an auth-recoverable tool condition into a failed agent turn.\n }\n}\n\ntype McpRequestInfo = {\n method?: string;\n id?: string | number | null;\n toolName?: string;\n};\n\nfunction mcpRequestDestinationUrl(input: string | URL | Request): string {\n return new URL(input instanceof Request ? input.url : input.toString()).toString();\n}\n\nasync function mcpRequestInfo(\n input: string | URL | Request,\n init?: RequestInit,\n): Promise<McpRequestInfo> {\n const body =\n typeof init?.body === \"string\"\n ? init.body\n : input instanceof Request && (init?.method ?? input.method).toUpperCase() === \"POST\"\n ? await input\n .clone()\n .text()\n .catch(() => \"\")\n : \"\";\n if (!body) {\n return {};\n }\n try {\n const parsed = JSON.parse(body) as {\n id?: unknown;\n method?: unknown;\n params?: { name?: unknown };\n };\n const method = typeof parsed.method === \"string\" ? parsed.method : undefined;\n const id =\n typeof parsed.id === \"string\" || typeof parsed.id === \"number\" || parsed.id === null\n ? parsed.id\n : undefined;\n const toolName =\n method === \"tools/call\" && typeof parsed.params?.name === \"string\"\n ? parsed.params.name\n : undefined;\n return {\n ...(method ? { method } : {}),\n ...(id !== undefined ? { id } : {}),\n ...(toolName ? { toolName } : {}),\n };\n } catch {\n return {};\n }\n}\n\nfunction withConnectionHeaders(\n input: string | URL | Request,\n init: RequestInit | undefined,\n authHeaders: Record<string, string>,\n): RequestInit {\n const headers = new Headers(\n init?.headers ?? (input instanceof Request ? input.headers : undefined),\n );\n for (const [name, value] of Object.entries(authHeaders)) {\n headers.set(name, value);\n }\n return { ...init, headers };\n}\n\nfunction fetchInputForAttempt(input: string | URL | Request): string | URL | Request {\n return input instanceof Request ? input.clone() : input;\n}\n\nfunction parseWwwAuthenticate(header: string | null): {\n error?: string;\n scope?: string[];\n resource?: string;\n} {\n if (!header) {\n return {};\n }\n const bearerIndex = header.toLowerCase().indexOf(\"bearer\");\n if (bearerIndex < 0) {\n return {};\n }\n const paramsText = header.slice(bearerIndex + \"bearer\".length);\n const params: Record<string, string> = {};\n const re = /([a-zA-Z_][a-zA-Z0-9_-]*)\\s*=\\s*(\"(?:[^\"\\\\]|\\\\.)*\"|[^,\\s]+)/g;\n let match: RegExpExecArray | null;\n while ((match = re.exec(paramsText)) !== null) {\n const raw = match[2]!;\n params[match[1]!.toLowerCase()] = raw.startsWith('\"')\n ? raw.slice(1, -1).replace(/\\\\\"/g, '\"')\n : raw;\n }\n return {\n ...(params.error ? { error: params.error } : {}),\n ...(params.scope ? { scope: params.scope.split(/\\s+/).filter(Boolean) } : {}),\n ...(params.resource ? { resource: params.resource } : {}),\n };\n}\n\n// Application-defined JSON-RPC error code marking \"this tool call needs a\n// connection\". A RESULT carrying inline `isError: true` cannot be used here:\n// the agents SDK's streamable-http shim strips `isError` and returns only the\n// content, erasing the failure. A JSON-RPC error survives the shim as a thrown\n// McpError, which PrefixedMcpServer.callTool converts back into an MCP-shaped\n// `{ isError: true }` output for the model.\nconst MCP_AUTH_NEEDED_ERROR = {\n // OpenGeni application-defined JSON-RPC code. Keep this positive so it cannot\n // collide with MCP SDK transport errors such as RequestTimeout (-32001).\n code: 40_101,\n message: \"Authentication required - a connection link was posted to the session.\",\n} as const;\n\nfunction mcpToolAuthNeededResponse(id: string | number | null | undefined): Response {\n return new Response(\n JSON.stringify({\n jsonrpc: \"2.0\",\n id: id ?? null,\n error: {\n code: MCP_AUTH_NEEDED_ERROR.code,\n message: MCP_AUTH_NEEDED_ERROR.message,\n },\n }),\n {\n status: 200,\n headers: { \"content-type\": \"application/json\" },\n },\n );\n}\n\nfunction isAuthNeededMcpError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = (error as { code?: unknown }).code;\n return (\n code === MCP_AUTH_NEEDED_ERROR.code &&\n (error.message === MCP_AUTH_NEEDED_ERROR.message ||\n error.message === `MCP error ${MCP_AUTH_NEEDED_ERROR.code}: ${MCP_AUTH_NEEDED_ERROR.message}`)\n );\n}\n\n// Model-facing text for a best-effort server whose tool call failed for a\n// non-auth reason (transport 401/403 that never became the broker's JSON-RPC\n// short-circuit, a provider 5xx, a network blip). The copy is LOOP-SAFE: it\n// tells the model the tool is dead for the REST OF THIS TURN and to NOT retry\n// it, so a model that would otherwise burn the turn re-calling the same broken\n// optional tool moves on instead. Only the safe error surface (JS error class +\n// numeric HTTP status) is interpolated — NEVER the raw error message/response\n// body, which for a broker 401/403 can echo request URLs/headers/credentials.\nfunction mcpToolUnavailableMessage(reason: string): string {\n return `This tool is unavailable for the rest of this turn (${reason}). Do not retry it — continue without it or use another approach.`;\n}\n\n// The only error detail safe to surface to the model or the logs: the JS error\n// constructor name and, when present, a numeric HTTP status. A StreamableHTTP\n// transport error carries the raw response BODY in its `.message` (a broker\n// 401/403 body can echo request detail), so `.message` is never included; the\n// numeric `.code`/`.status` (e.g. 401) is safe and useful.\nfunction safeMcpErrorFields(error: unknown): {\n errorClass: string;\n status?: number;\n} {\n const errorClass = error instanceof Error ? error.constructor.name : typeof error;\n const raw = (error as { code?: unknown; status?: unknown } | null)?.code;\n const status = typeof raw === \"number\" ? raw : undefined;\n if (status === undefined) {\n const altRaw = (error as { status?: unknown } | null)?.status;\n return typeof altRaw === \"number\" ? { errorClass, status: altRaw } : { errorClass };\n }\n return { errorClass, status };\n}\n\ntype SafeMcpTransportError = Error & {\n status?: number;\n code?: number;\n mcpTransportFailureKind?: \"request_timeout\";\n};\n\n/**\n * Preserve the MCP SDK's exact request-timeout meaning without retaining or\n * exposing a raw HTTP response body. The numeric code is not sufficient:\n * Streamable HTTP also uses -32001 for \"Session not found\" and arbitrary\n * AbortSignal reasons, so only the SDK's two owned timeout messages qualify.\n */\nexport function isMcpRequestTimeoutError(error: unknown, seen = new WeakSet<object>()): boolean {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n if (seen.has(error)) {\n return false;\n }\n seen.add(error);\n const record = error as Record<string, unknown>;\n if (record.mcpTransportFailureKind === \"request_timeout\") {\n return true;\n }\n const code = typeof record.code === \"number\" ? record.code : record.status;\n const message = typeof record.message === \"string\" ? record.message : \"\";\n const sdkTimeoutMessages = new Set([\n \"Request timed out\",\n \"MCP error -32001: Request timed out\",\n \"Maximum total timeout exceeded\",\n \"MCP error -32001: Maximum total timeout exceeded\",\n ]);\n if (code === -32_001 && sdkTimeoutMessages.has(message)) {\n return true;\n }\n return [\"error\", \"cause\", \"response\", \"data\"].some((key) =>\n isMcpRequestTimeoutError(record[key], seen),\n );\n}\n\nexport function safeMcpTransportError(error: unknown): SafeMcpTransportError {\n const fields = safeMcpErrorFields(error);\n const safeError = new Error(\n `MCP transport operation failed (${mcpErrorReason(fields)})`,\n ) as SafeMcpTransportError;\n safeError.name = \"McpTransportError\";\n if (fields.status !== undefined) {\n safeError.status = fields.status;\n safeError.code = fields.status;\n }\n if (isMcpRequestTimeoutError(error)) {\n safeError.mcpTransportFailureKind = \"request_timeout\";\n }\n return safeError;\n}\n\nfunction safeMcpTransportLogger(serverId: string) {\n const logFailure = (_message: string, ...args: unknown[]) => {\n let error: unknown;\n for (let index = args.length - 1; index >= 0; index -= 1) {\n if (args[index] instanceof Error) {\n error = args[index];\n break;\n }\n }\n console.warn(\"[mcp] transport operation failed\", {\n serverId,\n ...safeMcpErrorFields(error),\n });\n };\n return {\n namespace: \"opengeni:mcp-transport\",\n debug: () => undefined,\n error: logFailure,\n warn: logFailure,\n dontLogModelData: true,\n dontLogToolData: true,\n };\n}\n\n// Compose the safe model/log reason string (\"StreamableHTTPError 401\", or just\n// the class when no numeric status is available). Never carries the raw body.\nfunction mcpErrorReason(fields: { errorClass: string; status?: number }): string {\n return fields.status === undefined ? fields.errorClass : `${fields.errorClass} ${fields.status}`;\n}\n\nasync function mcpServerRequestInit(\n settings: Settings,\n config: Settings[\"mcpServers\"][number],\n): Promise<{ requestInit: { headers: Record<string, string> } } | {}> {\n // codex_apps is checked FIRST so the static-headers path can never apply to\n // it: its refreshing ChatGPT/Codex bearer is resolved per-connect from the\n // codex ALS, never from a baked `config.headers` value.\n if (isCodexAppsMcpServer(config)) {\n return await codexAppsMcpRequestInit(settings);\n }\n if (isFirstPartyMcpServer(settings, config)) {\n return await firstPartyMcpRequestInit(settings, config);\n }\n // Third-party MCP servers get their configured credential headers (for\n // example workspace-enabled capability MCP credentials) and nothing else —\n // never OpenGeni's own access key or delegated tokens.\n if (config.headers && Object.keys(config.headers).length > 0) {\n return { requestInit: { headers: { ...config.headers } } };\n }\n return {};\n}\n\nasync function firstPartyMcpRequestInit(\n settings: Settings,\n config: Settings[\"mcpServers\"][number],\n): Promise<{ requestInit: { headers: Record<string, string> } } | {}> {\n if (!isFirstPartyMcpServer(settings, config)) {\n return {};\n }\n const headers: Record<string, string> = {};\n if (settings.authRequired && settings.accessKey) {\n headers[\"x-opengeni-access-key\"] = settings.accessKey;\n }\n // The delegated bearer is deliberately NOT baked here. It is re-signed PER\n // REQUEST by firstPartyAuthFetch (wired in prepareAgentTools) so a turn or\n // persistent MCP connection that outlives the token's 1h TTL never sends a\n // stale bearer — an expired first-party bearer 401s (\"authentication\n // required\"), and because the first-party server is REQUIRED that killed the\n // turn on any run past ~1h. This function keeps only NON-expiring static\n // headers (the access key); the per-request fetch wrapper is the single source\n // of truth for the ever-refreshed Authorization header.\n if (Object.keys(headers).length === 0) {\n return {};\n }\n return {\n requestInit: {\n headers,\n },\n };\n}\n\n// Sign a FRESH first-party delegated bearer for a single request. Returns null\n// when the run lacks the inputs to mint one (no delegation secret / account /\n// workspace), in which case the request proceeds with whatever static headers\n// requestInit already set. The 1h TTL is safe precisely because this runs per\n// request: the token on the wire is always seconds old, never near expiry.\nasync function signFirstPartyDelegatedBearer(\n settings: Settings,\n options: PrepareToolsOptions,\n): Promise<string | null> {\n if (!settings.delegationSecret || !options.accountId || !options.workspaceId) {\n return null;\n }\n const attemptClaims = [\n options.sessionId,\n options.turnId,\n options.attemptId,\n options.executionGeneration,\n ];\n const hasAnyAttemptClaim = attemptClaims.some((claim) => claim !== undefined);\n const hasExactAttemptClaims = attemptClaims.every((claim) => claim !== undefined);\n if (hasAnyAttemptClaim && !hasExactAttemptClaims) {\n return null;\n }\n return await signDelegatedAccessToken(settings.delegationSecret, {\n accountId: options.accountId,\n workspaceId: options.workspaceId,\n subjectId: options.subjectId ?? \"worker:first-party-mcp\",\n ...(options.subjectLabel ? { subjectLabel: options.subjectLabel } : {}),\n permissions: options.firstPartyPermissions ?? [...DEFAULT_FIRST_PARTY_MCP_PERMISSIONS],\n principalKind: hasExactAttemptClaims ? \"agent_attempt\" : \"service\",\n firstPartyMcpTools: options.firstPartyTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS],\n ...(hasExactAttemptClaims\n ? {\n sessionId: options.sessionId!,\n turnId: options.turnId!,\n attemptId: options.attemptId!,\n executionGeneration: options.executionGeneration!,\n }\n : {}),\n exp: Math.floor(Date.now() / 1000) + 60 * 60,\n });\n}\n\n// Per-request auth for the FIRST-PARTY MCP server: re-sign the delegated bearer\n// on EVERY request (connect/initialize, every tools/list re-list, every\n// tools/call) and set it as the Authorization header, so a turn or connection\n// outliving the 1h token TTL never sends an expired bearer. This is the fix for\n// the prod grind where a >1h turn's next re-list/tool-call 401'd on the stale\n// first-party bearer and — the first-party server being required — failed the\n// whole turn. Scoped STRICTLY to the token WE mint; external OAuth (connectionRef\n// servers) go through connectionBrokerFetch and are untouched.\nfunction firstPartyAuthFetch(\n baseFetch: FetchLike,\n settings: Settings,\n options: PrepareToolsOptions,\n): FetchLike {\n return async (input, init) => {\n const bearer = await signFirstPartyDelegatedBearer(settings, options);\n if (!bearer) {\n return await baseFetch(input, init);\n }\n return await baseFetch(\n fetchInputForAttempt(input),\n withConnectionHeaders(input, init, { authorization: `Bearer ${bearer}` }),\n );\n };\n}\n\n/**\n * Builds the connect-time auth headers for the codex_apps connectors MCP. The\n * bearer is resolved from codexRequestStorage — the SAME refreshing token source\n * the model fetch uses (proactive refresh + single-flight + db persist) — so the\n * token is valid at connect. A missing store (non-codex turn, or prepareTools\n * ran outside the ALS) or a token failure (needs_relogin) returns {} so the\n * best-effort connect drops the server rather than crashing the turn.\n */\nasync function codexAppsMcpRequestInit(\n settings: Settings,\n): Promise<{ requestInit: { headers: Record<string, string> } } | {}> {\n const ctx = codexRequestStorage.getStore();\n if (!ctx) {\n return {};\n }\n let token;\n try {\n token = await ctx.getToken();\n } catch {\n return {};\n }\n const headers: Record<string, string> = {\n authorization: `Bearer ${token.accessToken}`,\n // The ChatGPT backend sits behind Cloudflare, which 403s requests bearing a\n // default runtime User-Agent (confirmed live: an HTML bot-block page, NOT an\n // auth failure). Send the codex client identity — the same originator/version/\n // User-Agent the model fetch uses — so the MCP connect handshake passes the edge.\n originator: CODEX_ORIGINATOR,\n \"user-agent\": `${CODEX_ORIGINATOR}/${ctx.clientVersion}`,\n version: ctx.clientVersion,\n };\n if (token.chatgptAccountId) {\n headers[\"chatgpt-account-id\"] = token.chatgptAccountId;\n }\n if (settings.codexProductSku) {\n headers[\"X-OpenAI-Product-Sku\"] = settings.codexProductSku;\n }\n return { requestInit: { headers } };\n}\n\n// The first-party MCP permission set signed into a worker's delegated token\n// when the session does not specify its own. POWERFUL BY DEFAULT: it carries\n// every permission that unlocks a first-party tool — session orchestration\n// (sessions:*), workspace variable sets (variable-sets:*), rigs:use\n// (list/get/propose/verify only), and GitHub (github:use) — so agents are fully capable out of the box. A user DEMOTES a\n// specific session by setting a narrower session.firstPartyMcpPermissions (the\n// create-session permission picker), which the worker uses instead. Account-\n// level scopes (billing/account/members/api_keys/workspace:admin) are\n// intentionally excluded: they gate no first-party tool and are not agent\n// capabilities. (A finer-grained capability model comes later.)\n// codex_apps is third-party-by-trust (the external ChatGPT connectors backend)\n// but needs DYNAMIC auth, so it is its own category — deliberately NOT folded\n// into the first-party allowlist, which would wrongly sign an OpenGeni delegated\n// token to chatgpt.com.\nfunction isCodexAppsMcpServer(config: Settings[\"mcpServers\"][number]): boolean {\n return config.id === CODEX_APPS_MCP_SERVER_ID;\n}\n\nfunction isFirstPartyMcpServer(\n settings: Settings,\n config: Settings[\"mcpServers\"][number],\n): boolean {\n if (![\"opengeni\", \"files\", \"docs\"].includes(config.id)) {\n return false;\n }\n if (config.url.includes(\"{workspaceId}\")) {\n return true;\n }\n const url = normalizeUrl(config.url);\n if (!url) {\n return false;\n }\n return firstPartyMcpUrls(settings).some((candidate) => candidate === url);\n}\n\nfunction firstPartyMcpServerUrlForRun(\n settings: Settings,\n config: Settings[\"mcpServers\"][number],\n workspaceId: string | undefined,\n): string | null {\n if (!workspaceId || ![\"opengeni\", \"files\", \"docs\"].includes(config.id)) {\n return null;\n }\n if (config.url.includes(\"{workspaceId}\")) {\n return config.url.replaceAll(\"{workspaceId}\", workspaceId);\n }\n if (!isFirstPartyMcpServer(settings, config)) {\n return null;\n }\n const rawBase = settings.opengeniMcpUrl?.includes(\"{workspaceId}\")\n ? settings.opengeniMcpUrl.replaceAll(\"{workspaceId}\", workspaceId)\n : settings.opengeniMcpUrl\n ? scopedMcpUrlFromConfiguredBase(settings.opengeniMcpUrl, workspaceId)\n : // unset → the shared loopback default (a `{workspaceId}` template owned by\n // @opengeni/config's firstPartyMcpBaseUrl), scoped to this run's workspace.\n firstPartyMcpBaseUrl(settings).replaceAll(\"{workspaceId}\", workspaceId);\n const url = new URL(rawBase);\n if (config.id === \"docs\") {\n url.pathname = `${url.pathname.replace(/\\/+$/, \"\")}/docs`;\n }\n return url.toString();\n}\n\nfunction scopedMcpUrlFromConfiguredBase(raw: string, workspaceId: string): string {\n const url = new URL(raw);\n url.pathname = `/v1/workspaces/${workspaceId}/mcp`;\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n}\n\nfunction firstPartyMcpUrls(settings: Settings): string[] {\n // Route the unset case through the shared loopback default so the literal\n // lives in exactly one place (@opengeni/config's firstPartyMcpBaseUrl).\n const base = normalizeUrl(settings.opengeniMcpUrl ?? firstPartyMcpBaseUrl(settings));\n if (!base) {\n return [];\n }\n const docs = new URL(base);\n docs.pathname = `${docs.pathname.replace(/\\/+$/, \"\")}/docs`;\n return [base, normalizeUrl(docs.toString())].filter((value): value is string => Boolean(value));\n}\n\nfunction normalizeUrl(raw: string): string | null {\n try {\n const url = new URL(raw);\n url.hash = \"\";\n url.pathname = url.pathname.replace(/\\/+$/, \"\");\n return url.toString();\n } catch {\n return null;\n }\n}\n\nexport function prefixedMcpToolName(registryId: string, toolName: string): string {\n return sharedPrefixedMcpToolName(registryId, toolName);\n}\n\nclass PrefixedMcpServer implements MCPServer {\n readonly cacheToolsList: boolean;\n readonly name: string;\n readonly prefix: string;\n private readonly allowedTools: Set<string> | undefined;\n // Best-effort servers (optional refs, connectionRef-backed capability MCPs,\n // codex_apps) must never fail a turn: a tools/list throw degrades to zero\n // tools instead of propagating. Deduplicate the warn so one degraded server\n // doesn't spam the log when the SDK re-lists across model turns.\n private readonly bestEffort: boolean;\n private loggedListToolsFailure = false;\n private listedToolSchemaTokens = 0;\n private modelToolSchemaAccountingDeferred = false;\n\n constructor(\n private readonly inner: MCPServer,\n registryId: string,\n allowedTools?: string[],\n bestEffort = false,\n private readonly aggregateToolBudget?: McpAggregateToolListBudget,\n private readonly aggregateSourceId = registryId,\n ) {\n this.name = registryId;\n this.prefix = prefixedMcpToolName(registryId, \"\");\n this.cacheToolsList = inner.cacheToolsList;\n this.allowedTools = allowedTools ? new Set(allowedTools) : undefined;\n this.bestEffort = bestEffort;\n }\n\n connect(): Promise<void> {\n return this.inner.connect().catch((error: unknown) => {\n // connectMcpServers has its own global logger and logs the thrown Error.\n // Never let a raw transport response body cross that logging boundary.\n throw safeMcpTransportError(error);\n });\n }\n\n close(): Promise<void> {\n this.releaseAggregateBudget();\n return this.inner.close();\n }\n\n releaseAggregateBudget(): void {\n this.aggregateToolBudget?.remove(this.aggregateSourceId);\n }\n\n async listTools(): Promise<RuntimeMcpTool[]> {\n try {\n const tools = assertMcpToolListWithinBounds(await this.inner.listTools()) as RuntimeMcpTool[];\n const exposed = tools\n .filter((tool) => this.isAllowed(tool.name))\n .map((tool) => ({\n ...tool,\n name: prefixedMcpToolName(this.name, tool.name),\n }));\n const bounded = (this.aggregateToolBudget?.replace(this.aggregateSourceId, exposed) ??\n assertMcpToolListWithinBounds(exposed)) as RuntimeMcpTool[];\n this.listedToolSchemaTokens = estimateSerializedValueTokens(bounded);\n return bounded;\n } catch (error) {\n // A REQUIRED server's tools/list failure is fatal (fail-loud default): the\n // caller explicitly requested it, so its absence must fail the turn.\n if (!this.bestEffort) {\n throw error;\n }\n // Best-effort isolation. The SDK's run-time getAllMcpTools calls listTools\n // OUTSIDE the connect-time connectMcpServers({ strict: false }) guard, so a\n // best-effort server whose tools/list throws here — for ANY reason (an\n // expired/failed connection credential surfacing as a StreamableHTTP\n // \"authentication required\" 401, a provider 5xx, a network blip) — would\n // otherwise take down an unrelated turn. Drop this server's tools for the\n // turn instead. An auth failure additionally published tool.auth_needed via\n // the connection-broker fetch before the throw (so that actionable signal\n // is preserved), but a non-auth failure has NO such signal — the structured\n // warn below is its only visibility, so a chronically-dead optional\n // integration surfaces in logs/metrics rather than being silently swallowed.\n // Warn once per degraded server per turn (instances are per-turn), so a\n // re-list across model turns does not spam the log.\n if (!this.loggedListToolsFailure) {\n this.loggedListToolsFailure = true;\n console.warn(\n \"[mcp] best-effort server tools/list failed; its tools are unavailable this turn\",\n // Safe surface only (class + numeric status), never the raw error\n // message/response body — a broker 401/403 body can echo request detail.\n { serverId: this.name, ...safeMcpErrorFields(error) },\n );\n }\n this.releaseAggregateBudget();\n return [];\n }\n }\n\n /** Latest exact tools/list projection used to build the model request. */\n modelToolSchemaTokens(): number {\n return this.modelToolSchemaAccountingDeferred ? 0 : this.listedToolSchemaTokens;\n }\n\n /**\n * Keep model-input accounting aligned with Codex `defer_loading`: the full\n * schema is not provider context until a tool_search_output discloses it.\n * Instances are turn-local, so this cannot leak into a non-Codex turn.\n */\n deferModelToolSchemaAccounting(): void {\n this.modelToolSchemaAccountingDeferred = true;\n }\n\n async callTool(\n toolName: string,\n args: Record<string, unknown> | null,\n meta?: Record<string, unknown> | null,\n ): Promise<any> {\n const unprefixed = this.unprefixToolName(toolName);\n if (!this.isAllowed(unprefixed)) {\n throw new Error(`MCP tool ${unprefixed} is not allowed for server ${this.name}`);\n }\n try {\n const output = await this.inner.callTool(unprefixed, args, meta);\n assertMcpPayloadWithinBytes(output, MCP_MAX_TOOL_RESULT_BYTES, \"MCP tool result\");\n return output;\n } catch (error) {\n // The connection broker's auth-needed short-circuit arrives as a thrown\n // JSON-RPC error (an inline isError result would be stripped by the SDK\n // shim). Surface it to the model as a failed-but-recoverable tool result\n // instead of failing the turn; the timeline chip was already published.\n // This applies to ANY server — an auth-needed is recoverable once the user\n // re-links, so even a required tool degrades gracefully here.\n if (isAuthNeededMcpError(error)) {\n return {\n isError: true,\n content: [{ type: \"text\", text: MCP_AUTH_NEEDED_ERROR.message }],\n };\n }\n // Best-effort INVOCATION isolation (sibling to the listTools guard). When\n // the model calls a best-effort server's tool and the call throws for ANY\n // other reason — a raw transport 401/403 that never became the broker's\n // JSON-RPC short-circuit (e.g. a codex_apps bearer that expired mid-turn,\n // or a 403 with no insufficient_scope challenge), a provider 5xx, or a\n // network blip — the whole turn would otherwise die. Return a tool-error\n // RESULT the model sees instead, so it adapts (tries another approach,\n // tells the user) and the turn survives. Required servers keep the\n // fail-loud default: the caller depends on them, so their tool failure\n // still fails the turn. For auth cases the actionable tool.auth_needed was\n // already published upstream by the connection-broker fetch before the\n // throw, so degrading here never silences it.\n if (this.bestEffort) {\n const fields = safeMcpErrorFields(error);\n console.warn(\n \"[mcp] best-effort server tool call failed; returning an unavailable result for this turn\",\n { serverId: this.name, toolName: unprefixed, ...fields },\n );\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: mcpToolUnavailableMessage(mcpErrorReason(fields)),\n },\n ],\n };\n }\n throw error;\n }\n }\n\n invalidateToolsCache(): Promise<void> {\n return this.inner.invalidateToolsCache();\n }\n\n async listResources(params?: Record<string, unknown>): Promise<any> {\n const resourcesServer = this.inner as MCPServer & {\n listResources?: (params?: Record<string, unknown>) => Promise<any>;\n };\n if (!resourcesServer.listResources) {\n throw new Error(`MCP server ${this.name} does not support resources`);\n }\n return await resourcesServer.listResources(params);\n }\n\n async listResourceTemplates(params?: Record<string, unknown>): Promise<any> {\n const resourcesServer = this.inner as MCPServer & {\n listResourceTemplates?: (params?: Record<string, unknown>) => Promise<any>;\n };\n if (!resourcesServer.listResourceTemplates) {\n throw new Error(`MCP server ${this.name} does not support resource templates`);\n }\n return await resourcesServer.listResourceTemplates(params);\n }\n\n async readResource(uri: string): Promise<any> {\n const resourcesServer = this.inner as MCPServer & {\n readResource?: (uri: string) => Promise<any>;\n };\n if (!resourcesServer.readResource) {\n throw new Error(`MCP server ${this.name} does not support resource reads`);\n }\n return await resourcesServer.readResource(uri);\n }\n\n private isAllowed(toolName: string): boolean {\n return !this.allowedTools || this.allowedTools.has(toolName);\n }\n\n private unprefixToolName(toolName: string): string {\n if (!toolName.startsWith(this.prefix)) {\n throw new Error(`MCP tool ${toolName} is missing expected ${this.name} prefix`);\n }\n return toolName.slice(this.prefix.length);\n }\n}\n\n// createSandboxClient (+ withDockerNetwork / connectDockerNetwork) moved to the\n// agent-loop-free leaf ./sandbox; re-exported via `export * from \"./sandbox\"`.\n\nexport type PrepareInputOptions = {\n sandboxClient?: unknown;\n};\n\nexport async function prepareRunInput(\n agent: Agent<any, any>,\n input: AgentSegmentInput,\n options: PrepareInputOptions = {},\n): Promise<PreparedAgentInput> {\n if (input.kind === \"message\") {\n const trailingMessages: AgentInputItem[] = [];\n if (input.internalContext?.trim()) {\n trailingMessages.push({\n type: \"message\",\n role: \"system\",\n content: input.internalContext,\n } as AgentInputItem);\n }\n if (input.text?.trim()) {\n trailingMessages.push({\n type: \"message\",\n role: \"user\",\n content: input.text,\n } as AgentInputItem);\n }\n if (\n trailingMessages.length === 0 &&\n (input.historyItems === undefined ||\n input.historyItems === null ||\n input.historyItems.length === 0)\n ) {\n throw new Error(\"Message input requires a user prompt or internal context\");\n }\n // Conversation truth comes only from durable history items. Sanitize the\n // in-memory copy before it reaches the model so a corrupt tool-call pair is\n // non-fatal; stored audit rows remain untouched.\n const sanitizedHistory = sanitizeHistoryItemsForModel(\n (input.historyItems ?? []) as unknown as Array<Record<string, unknown>>,\n ) as unknown as AgentInputItem[];\n const sandboxSessionState = input.sandboxEnvelope\n ? await restoredSandboxSessionStateFromEntry(input.sandboxEnvelope, options.sandboxClient)\n : undefined;\n const assembled = [...sanitizedHistory, ...trailingMessages];\n if (assembled.length === 0) {\n throw new Error(\"Message input requires durable history or internal context\");\n }\n return {\n // Preserve the SDK's simple first-message form without creating a second\n // history path: this is merely the zero-history representation.\n input:\n sanitizedHistory.length === 0 && !input.internalContext?.trim() && input.text?.trim()\n ? input.text\n : assembled,\n ...(sandboxSessionState ? { sandboxSessionState } : {}),\n };\n }\n // An interrupted tool can only be resumed against a real saved run state. If the\n // latest blob is the cleared sentinel the awaiting turn was wiped (the API\n // refuses clear in requires_action, so this is a defensive guard) — fail with\n // an honest message instead of the cryptic SDK \"missing schema version\".\n if (isClearedRunStateBlob(input.serializedRunState)) {\n throw new Error(\n \"Cannot resume an interrupted tool: the session context was cleared, so the awaiting run state no longer exists.\",\n );\n }\n const state = await RunState.fromString(agent, input.serializedRunState);\n const interruptions = state.getInterruptions();\n const interruptionId = input.kind === \"human_input\" ? input.toolCallId : input.approvalId;\n const target = interruptions.find((item: any) => approvalIdentifier(item) === interruptionId);\n if (!target) {\n throw new Error(`Interrupted tool not found in saved run state: ${interruptionId}`);\n }\n if (input.kind === \"human_input\") {\n state.approve(target as any);\n } else if (input.decision === \"approve\") {\n state.approve(target as any);\n } else {\n state.reject(target as any, input.message ? { message: input.message } : undefined);\n }\n return { input: state };\n}\n\nexport type RunAgentStreamOptions = {\n /** Abort the provider/tool loop when the owning activity is cancelled. */\n signal?: AbortSignal;\n sandboxClient?: unknown;\n sandboxEnvironment?: Record<string, string>;\n onRuntimeEvent?: (event: NormalizedRuntimeEvent) => Promise<void> | void;\n contextCompactionSignal?: () => ProviderContextTokenSignal | null | undefined;\n contextCompactionRequested?: () => boolean | Promise<boolean>;\n // Host-managed git credential renewal registration. Called only after the\n // initial token-file seed completed on a real provisioned box. The worker\n // owns the multi-day timer and uses this pinned, un-proxied session to\n // atomically replace token files; runtime never mints credentials itself.\n onGitCredentialSessionReady?: (session: GitCredentialTokenWriterSession) => Promise<void> | void;\n // OpenGeni-minted Toolspace token renewal registration. Called only after the\n // initial token file reached the real sandbox session.\n onToolspaceTokenSessionReady?: (session: ToolspaceTokenWriterSession) => Promise<void> | void;\n // Host-owned run material is seeded off-manifest before setup and every\n // agent-created process sources the active immutable generation. The worker\n // owns resolution/renewal/fencing; runtime owns sandbox transport.\n runCredentialSessionId?: string;\n onRunCredentialSessionReady?: RunCredentialSessionReady;\n // OWNERSHIP INVERSION (P1.2): an externally-owned, already-live sandbox\n // session resolved by the per-turn resume-by-id path. When present,\n // runAgentStream does NOT build (or resume, or discard) a client — it threads\n // these straight into runOptions.sandbox as a NON-OWNED session. The SDK\n // registers a provided session non-owned (manager.js) and NEVER reaps it on a\n // normal finish (proven by spikes/sdk-keystone) — that is the keystone: the\n // one box survives across turns. Mutually exclusive with the per-run\n // createSandboxClient path (the owned branch takes precedence when both set).\n // Agent-dependent decorators (file-downloads, lifecycle/repo-clone hooks) are\n // re-applied around the resumed client here; the live `session`/`sessionState`\n // carry the box, so no create()/resume() is re-invoked inside run().\n ownedSandbox?: {\n client: unknown; // built by the per-turn resume path (the raw provider client)\n session: unknown; // SandboxSessionLike — the live, NON-OWNED handle (never reaped)\n sessionState?: unknown; // SandboxSessionState the box was resumed from\n // The UN-PROXIED established box for platform setup (lifecycle hooks + file\n // resource materialization). `session` may be the mid-turn routing proxy whose\n // every exec re-reads the active pointer — platform-initiated setup must NOT\n // follow a swap onto a connected machine (the user's real computer), so it\n // runs against this pinned handle instead. Absent -> falls back to `session`.\n setupSession?: unknown;\n // True when the caller already ran file-resource materialization for this\n // provided session and threaded any failures into the model input.\n fileDownloadsMaterialized?: boolean;\n // Lazy sandbox provisioning injects a synthetic provided session at run start;\n // the real box does not exist until the first sandbox op. In that path the\n // worker provisioner runs runOwnedSandboxSetup against the un-proxied real box\n // after establish, so runAgentStream must not run it eagerly here.\n deferredSetup?: boolean;\n };\n /**\n * The attempt's authoritative physical sandbox-operation fence. Platform\n * lifecycle commands use its command runner too, so Steer/Pause can interrupt\n * repository clone, rig setup, file materialization, and credential seeding\n * before the attempt-quiesced receipt opens queue admission.\n */\n turnToolCancellationFence?: TurnToolCancellationFence;\n // A per-turn model-input filter chained AFTER the provider-item-id strip.\n // Used by the genesis-title injection to prepend a hidden, NON-PERSISTED\n // directive: a callModelInputFilter mutates only `modelData.input` for each\n // model call and never touches `state.history`/`originalInput`, so the\n // reconcile dual-write never sees it.\n callModelInputFilter?: CallModelInputFilter;\n};\n\nexport type ContextRobustnessFilterOptions = {\n contextCompactionSignal?: () => ProviderContextTokenSignal | null | undefined;\n contextCompactionRequested?: () => boolean | Promise<boolean>;\n throwOnCompactionNeeded?: boolean;\n};\n\n// One-shot directive injected into the FIRST model call on the genesis turn\n// (see buildOpenGeniAgent's genesisTitleHint). Delivered through the\n// authoritative instructions channel so the model reliably obeys; references\n// the prefixed tool name the agent actually sees (opengeni__set_session_title).\nexport const GENESIS_TITLE_DIRECTIVE =\n \"This is the first turn of a new session. Before responding to the user, call the opengeni__set_session_title tool with a concise 3-7 word title that summarizes what this session is about, then address the user's request normally.\";\n\n/**\n * Inject the genesis-title directive into exactly one model request. Agent\n * instructions are reused for every model call in a tool loop, so placing this\n * directive there turned a nominally one-shot setup action into repeated title\n * calls. The closure is intentionally consumed even when the first request\n * fails: a retry/recovery must continue the task, not restart setup.\n */\nexport function oneShotGenesisTitleInputFilter(): CallModelInputFilter {\n let pending = true;\n return ({ modelData }) => {\n if (!pending) {\n return modelData;\n }\n pending = false;\n return {\n ...modelData,\n instructions: modelData.instructions\n ? `${modelData.instructions} ${GENESIS_TITLE_DIRECTIVE}`\n : GENESIS_TITLE_DIRECTIVE,\n };\n };\n}\n\nfunction takeGenesisTitleInputFilter(agent: Agent<any, any>): CallModelInputFilter | undefined {\n if (!agentsNeedingGenesisTitleDirective.has(agent)) {\n return undefined;\n }\n agentsNeedingGenesisTitleDirective.delete(agent);\n return oneShotGenesisTitleInputFilter();\n}\n\n// Generic substrate prompting for programmatic tool calling (toolspace). Same\n// text for every host; gated per-turn by appendToolspaceInstructions on the\n// presence of a minted toolspace token, so it only appears when the sandbox\n// exposes $OPENGENI_TOOLSPACE_URL/_TOKEN_FILE. Stock images carry ogtool;\n// custom environments get only an exact deployment-pinned bootstrap hint.\nexport const TOOLSPACE_PROGRAMMATIC_DIRECTIVE =\n \"Every tool on your MCP surface is also callable programmatically from the sandbox shell, so scripts can invoke tools without a model round trip per call. If `ogtool` is installed, run `ogtool list` to see the available tools and their input schemas (from tools/list), then `ogtool call <tool-name> '<json-args>'`. If it is absent and both npm and $OPENGENI_OGTOOL_PACKAGE_SPEC are available, run the exact deployment-pinned package with `npm exec --yes --package=\\\"$OPENGENI_OGTOOL_PACKAGE_SPEC\\\" -- ogtool ...`; never guess a version or install `latest`. Otherwise POST MCP JSON-RPC directly to $OPENGENI_TOOLSPACE_URL with the bearer token read from $OPENGENI_TOOLSPACE_TOKEN_FILE. Prefer programmatic calls for loops, polling, and bulk filtering: their results stay in the sandbox and do not consume your context window. Tools that require human approval must still be invoked normally — called programmatically they return a typed error.\";\n\n/**\n * callModelInputFilter that removes provider-assigned item ids (rs_/msg_/fc_…)\n * from every input item immediately before each model call. Responses-API\n * requests that carry item ids are resolved against the provider's stored\n * responses, and that store is not durable enough to anchor long runs on: a\n * response that streamed successfully can be missing from the store on the\n * very next call, which then fails with 400 \"Item with id ... not found\"\n * (observed live on Azure OpenAI mid-turn). All item content — including the\n * encrypted reasoning payload carried in providerData when\n * `openaiReasoningEncryptedContent` is on — is sent inline, so the ids add\n * fragility without adding information. Pairing fields (`call_id`/`callId`)\n * are separate properties and stay untouched; items are cloned, never mutated.\n */\nexport const stripProviderItemIdsFilter: CallModelInputFilter = ({ modelData }) => ({\n ...modelData,\n input: modelData.input.map((item) => {\n if (item && typeof item === \"object\" && \"id\" in item) {\n const { id: _id, ...rest } = item as Record<string, unknown>;\n return rest as AgentInputItem;\n }\n return item;\n }),\n});\n\n/**\n * callModelInputFilter that normalizes every `computer_call` carrying BOTH\n * `action` and `actions` down to EXACTLY ONE (keeps `actions`, drops `action`).\n * The Azure computer-use endpoint rejects a request whose computer_call has\n * both with `400 Computer call input must include exactly one of `action` or\n * `actions``; and (live-proven against gpt-5.6-sol's GA computer tool) it also\n * rejects the `action`-only form, accepting ONLY the batched plural `actions`.\n * The SDK 0.11.6 schema allows both, so a freshly-emitted\n * screenshot call carries the redundant pair. This filter runs before EVERY\n * model call — the turn-start history replay AND every mid-turn follow-up — so\n * it covers the just-emitted (non-replayed) computer_call on the same turn,\n * which the turn-start `prepareRunInput` sanitizer never sees. Items are cloned,\n * never mutated.\n */\nexport const normalizeComputerCallsFilter: CallModelInputFilter = ({ modelData }) => ({\n ...modelData,\n input: normalizeComputerCallActions(\n modelData.input as unknown as Array<Record<string, unknown>>,\n ) as unknown as AgentInputItem[],\n});\n\n/**\n * Canonical Codex-style tool-result bound at the final model-input seam. The\n * identical pure normalizer also runs before conversation rows are persisted,\n * so this is a live-turn defense rather than a request-only alternate history.\n */\nexport function boundModelToolOutputsFilterForSettings(settings: Settings): CallModelInputFilter {\n return ({ modelData }) => ({\n ...modelData,\n input: boundModelToolOutputItems(\n modelData.input as unknown as Array<Record<string, unknown>>,\n settings.modelToolOutputTruncationTokens,\n ) as unknown as AgentInputItem[],\n });\n}\n\nfunction estimateAgentToolSchemaTokens(agent: Agent<any, any>): number {\n const localTools = Array.isArray((agent as { tools?: unknown }).tools)\n ? ((agent as { tools: unknown[] }).tools ?? [])\n : [];\n const localDescriptors = localTools.map((candidate) => {\n if (!candidate || typeof candidate !== \"object\") return candidate;\n const tool = candidate as Record<string, unknown>;\n return {\n type: tool.type,\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n inputSchema: tool.inputSchema,\n strict: tool.strict,\n providerData: tool.providerData,\n };\n });\n const mcpServers = Array.isArray((agent as { mcpServers?: unknown }).mcpServers)\n ? ((agent as { mcpServers: unknown[] }).mcpServers ?? [])\n : [];\n const mcpTokens = mcpServers.reduce<number>((total, server) => {\n const getter = (server as { modelToolSchemaTokens?: () => number } | null)\n ?.modelToolSchemaTokens;\n return total + (typeof getter === \"function\" ? getter.call(server) : 0);\n }, 0);\n return estimateSerializedValueTokens(localDescriptors) + mcpTokens;\n}\n\nexport function contextRobustnessFilterForSettings(\n settings: Settings,\n options: ContextRobustnessFilterOptions = {},\n): CallModelInputFilter {\n const thresholdTokens = compactionThresholdTokens(settings);\n let previousRequest: { revision: number; footprint: CompleteModelInputFootprint } | null = null;\n let requestRevision = 0;\n return async ({ modelData, agent }) => {\n const input = modelData.input;\n if (options.throwOnCompactionNeeded) {\n const reported = options.contextCompactionSignal?.();\n const current: CompleteModelInputFootprint = {\n input: input as unknown as Array<Record<string, unknown>>,\n instructionsTokens: estimateSerializedValueTokens(modelData.instructions ?? \"\"),\n toolSchemaTokens: estimateAgentToolSchemaTokens(agent),\n };\n // Stream consumption can lag the SDK's background model loop. A provider\n // usage signal is safe only when its response revision belongs to the\n // immediately preceding request. Never attach a delayed response count to\n // a newer footprint: doing so can hide all model output produced between\n // them and recreate an under-counting compaction loop.\n const boundProvider =\n reported &&\n previousRequest &&\n reported.revision === previousRequest.revision &&\n hasModelGeneratedItem(current.input)\n ? reported\n : null;\n const estimate = estimateCompleteModelInput({\n current,\n provider: boundProvider,\n providerRequestFootprint: boundProvider ? (previousRequest?.footprint ?? null) : null,\n });\n const signalTokens = estimate.tokens;\n previousRequest = { revision: ++requestRevision, footprint: current };\n if (await options.contextCompactionRequested?.()) {\n throw new CompactionNeededError({\n signalTokens,\n thresholdTokens,\n signalSource: boundProvider ? \"provider\" : \"estimate\",\n trigger: \"operator\",\n });\n }\n if (signalTokens >= thresholdTokens) {\n throw new CompactionNeededError({\n signalTokens,\n thresholdTokens,\n signalSource: boundProvider ? \"provider\" : \"estimate\",\n });\n }\n }\n return { ...modelData, input };\n };\n}\n\n/**\n * Compose a list of callModelInputFilters into one, applied left-to-right so\n * each sees the prior filter's output.\n */\nfunction composeCallModelInputFilters(filters: CallModelInputFilter[]): CallModelInputFilter {\n return async (args) => {\n let modelData = args.modelData;\n for (const filter of filters) {\n modelData = await filter({ ...args, modelData });\n }\n return modelData;\n };\n}\n\n/**\n * The model-input filter applied before every model call. The computer_call\n * action/actions normalizer is ALWAYS on (the Azure endpoint 400s without it);\n * the provider-item-id strip is layered on top when the configured policy\n * selects it; the context-robustness guard then raises the proactive durable\n * compaction signal on the client-compaction path. It never trims history from\n * an individual request.\n */\nexport function callModelInputFilterForSettings(\n settings: Settings,\n options: ContextRobustnessFilterOptions = {},\n): CallModelInputFilter | undefined {\n const filters: CallModelInputFilter[] = [\n normalizeComputerCallsFilter,\n boundModelToolOutputsFilterForSettings(settings),\n ];\n if (settings.openaiProviderItemIds === \"strip\") {\n filters.push(stripProviderItemIdsFilter);\n }\n filters.push(contextRobustnessFilterForSettings(settings, options));\n return composeCallModelInputFilters(filters);\n}\n\nexport async function runAgentStream(\n agent: Agent<any, any>,\n input: PreparedAgentInput | string | RunState<any, any>,\n settings: Settings,\n overrides: RunAgentStreamOptions = {},\n) {\n const prepared: PreparedAgentInput =\n typeof input === \"string\" || input instanceof RunState ? { input } : input;\n const environment = overrides.sandboxEnvironment ?? collectSandboxEnvironment(settings);\n const toolspaceTokenFile = toolspaceTokenFileForAgent(agent, environment);\n const genesisTitleInputFilter = takeGenesisTitleInputFilter(agent);\n if (overrides.onRunCredentialSessionReady && !overrides.runCredentialSessionId) {\n throw new Error(\"runCredentialSessionId is required when run credential setup is enabled\");\n }\n\n // OWNED PATH (P1.2 ownership inversion): the per-turn resume path injected a\n // live, externally-owned box. We thread the live `session` straight into\n // runOptions.sandbox so the SDK registers it NON-OWNED and never reaps it on\n // a normal finish (the keystone). We re-apply ONLY the agent-dependent\n // decorators (file-downloads + lifecycle/repo-clone hooks) around the resumed\n // client — the manifest-refresh-on-resume wrap is a no-op when a live\n // `session` is supplied (resume is not re-invoked). This branch is reached\n // ONLY when sandboxOwnershipEnabled gated the activity into resolving a box;\n // with the flag off the activity never sets `ownedSandbox` and this whole\n // block is skipped (byte-for-byte the legacy path).\n if (overrides.ownedSandbox) {\n const { client: ownedClient, session, sessionState } = overrides.ownedSandbox;\n // Platform setup (hooks + file materialization) execs against the UN-PROXIED\n // established box when the caller pinned one — never through the routing proxy,\n // whose per-op pointer re-read could land these execs on a machine swapped in\n // mid-turn.\n const setupSession = (overrides.ownedSandbox.setupSession ?? session) as SandboxSessionLike;\n const credentialAgentSession = overrides.runCredentialSessionId\n ? withRunCredentialsSession(session as SandboxSessionLike, overrides.runCredentialSessionId)\n : (session as SandboxSessionLike);\n const agentSession = toolspaceTokenFile\n ? withToolspaceTokenSession(credentialAgentSession, toolspaceTokenFile)\n : credentialAgentSession;\n const credentialSetupSession = overrides.runCredentialSessionId\n ? withRunCredentialsSession(setupSession, overrides.runCredentialSessionId)\n : setupSession;\n const decoratedSetupSession = toolspaceTokenFile\n ? withToolspaceTokenSession(credentialSetupSession, toolspaceTokenFile)\n : credentialSetupSession;\n // Platform setup (manifest-env pin + beforeAgentStart hooks + file downloads)\n // against the UN-proxied established box — the ONE-TRUTH helper shared with the\n // lazy provisioner. Eager path: runs here, before the run starts (unchanged).\n if (!overrides.ownedSandbox.deferredSetup) {\n await overrides.onRunCredentialSessionReady?.(session as SandboxSessionLike);\n await runOwnedSandboxSetup(agent, session as SandboxSessionLike, decoratedSetupSession, {\n settings,\n environment,\n preparedInput: prepared,\n ...(overrides.ownedSandbox.fileDownloadsMaterialized\n ? { fileDownloadsMaterialized: true }\n : {}),\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n ...(overrides.turnToolCancellationFence\n ? {\n commandRunner: overrides.turnToolCancellationFence.runSandboxCommand.bind(\n overrides.turnToolCancellationFence,\n ),\n }\n : {}),\n });\n if (toolspaceTokenSeedForAgent(agent)) {\n await overrides.onToolspaceTokenSessionReady?.(agentSession);\n }\n await overrides.onGitCredentialSessionReady?.(setupSession);\n }\n const runAs = sandboxRunAs(settings);\n const fileDownloads = sandboxFileDownloadsForAgent(agent);\n const resourceClient =\n fileDownloads.length > 0\n ? withSandboxFileDownloads(ownedClient as SandboxClient, fileDownloads, {\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n ...(overrides.turnToolCancellationFence\n ? {\n commandRunner: overrides.turnToolCancellationFence.runSandboxCommand.bind(\n overrides.turnToolCancellationFence,\n ),\n }\n : {}),\n })\n : (ownedClient as SandboxClient);\n // TOKEN-BROKER (B1): the per-turn git token seed, forwarded OFF-MANIFEST so the\n // repository-clone hook seeds it to the box's token file before the clone.\n const ownedGitTokenSeeds = gitTokenSeedsForAgent(agent);\n const ownedGitCredentialBindings = gitCredentialBindingsForAgent(agent);\n const ownedToolspaceTokenSeed = toolspaceTokenSeedForAgent(agent);\n const ownedRigSetup = rigSetupDescriptorForAgent(agent);\n const ownedHooks = [\n // M3: rig setup runs FIRST so any tooling it installs is present for the\n // credential / repository-clone hooks below. The rig's credential hooks are\n // unioned into the deployment preparation-profile hooks (deduped by id).\n ...sandboxRigSetupHooksForAgent(agent),\n ...unionCredentialHooks(\n sandboxLifecycleHooksForIds(sandboxLifecycleHookIds(settings)),\n rigCredentialHooksForAgent(agent),\n ),\n ...sandboxToolspaceTokenHooksForAgent(agent),\n ...toolspaceTokenSessionRegistrationHooks(\n ownedToolspaceTokenSeed ? overrides.onToolspaceTokenSessionReady : undefined,\n ),\n ...sandboxRepositoryCloneHooksForAgent(agent),\n ...gitCredentialSessionRegistrationHooks(overrides.onGitCredentialSessionReady),\n ];\n const ownedHookContext: SandboxLifecycleHookContext = {\n environment,\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n ...(ownedGitTokenSeeds ? { gitTokenSeeds: ownedGitTokenSeeds } : {}),\n ...(ownedGitCredentialBindings ? { gitCredentialBindings: ownedGitCredentialBindings } : {}),\n ...(ownedToolspaceTokenSeed ? { toolspaceTokenSeed: ownedToolspaceTokenSeed } : {}),\n ...(toolspaceTokenFile ? { toolspaceTokenFile } : {}),\n ...(ownedRigSetup ? { rigSetup: ownedRigSetup } : {}),\n };\n // Keep both credential seeding and lifecycle decoration as a safety net for\n // any session the SDK does create/resume during this run. They are inert for\n // the provided session, which remains the normal ownership-inverted path.\n const credentialResourceClient = overrides.runCredentialSessionId\n ? withRunCredentialsClient(\n resourceClient,\n overrides.runCredentialSessionId,\n overrides.onRunCredentialSessionReady,\n )\n : resourceClient;\n const toolspaceResourceClient = toolspaceTokenFile\n ? withToolspaceTokenClient(credentialResourceClient, toolspaceTokenFile)\n : credentialResourceClient;\n const decoratedClient = withSandboxLifecycleHooks(\n toolspaceResourceClient,\n ownedHooks,\n ownedHookContext,\n );\n const ownedFilter = composeCallModelInputFilters(\n [\n callModelInputFilterForSettings(settings),\n genesisTitleInputFilter,\n overrides.callModelInputFilter,\n // A caller filter may synthesize model input. Re-apply the idempotent\n // canonical bound at the literal final seam before accounting/provider\n // serialization so no extension can bypass the policy.\n boundModelToolOutputsFilterForSettings(settings),\n contextRobustnessFilterForSettings(settings, {\n throwOnCompactionNeeded: Boolean(\n overrides.contextCompactionSignal || overrides.contextCompactionRequested,\n ),\n ...(overrides.contextCompactionSignal\n ? { contextCompactionSignal: overrides.contextCompactionSignal }\n : {}),\n ...(overrides.contextCompactionRequested\n ? { contextCompactionRequested: overrides.contextCompactionRequested }\n : {}),\n }),\n ].filter((f): f is CallModelInputFilter => Boolean(f)),\n );\n const ownedRunOptions: Parameters<typeof run>[2] = {\n stream: true,\n maxTurns: settings.agentMaxModelCallsPerTurn,\n callModelInputFilter: ownedFilter,\n ...(overrides.signal ? { signal: overrides.signal } : {}),\n };\n ownedRunOptions.sandbox = {\n client: decoratedClient,\n session: agentSession,\n ...(sessionState ? { sessionState } : {}),\n } as SandboxRunConfig;\n return await runScopedRunner(settings).run(agent, prepared.input, ownedRunOptions);\n }\n\n const rawClient = overrides.sandboxClient ?? createSandboxClient(settings, environment);\n const refreshedClient = rawClient\n ? withManifestRefreshOnResume(\n rawClient as SandboxClient,\n (agent as { defaultManifest?: Manifest }).defaultManifest,\n {\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n },\n )\n : undefined;\n const runAs = sandboxRunAs(settings);\n const fileDownloads = sandboxFileDownloadsForAgent(agent);\n const resourceClient =\n refreshedClient && fileDownloads.length > 0\n ? withSandboxFileDownloads(refreshedClient, fileDownloads, {\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n })\n : refreshedClient;\n const credentialClient =\n resourceClient && overrides.runCredentialSessionId\n ? withRunCredentialsClient(\n resourceClient,\n overrides.runCredentialSessionId,\n overrides.onRunCredentialSessionReady,\n )\n : resourceClient;\n const toolspaceClient =\n credentialClient && toolspaceTokenFile\n ? withToolspaceTokenClient(credentialClient, toolspaceTokenFile)\n : credentialClient;\n // TOKEN-BROKER (B1): the per-turn git token seed, forwarded OFF-MANIFEST so the\n // repository-clone hook seeds it to the box's token file before the clone.\n const gitTokenSeeds = gitTokenSeedsForAgent(agent);\n const gitCredentialBindings = gitCredentialBindingsForAgent(agent);\n const toolspaceTokenSeed = toolspaceTokenSeedForAgent(agent);\n const legacyRigSetup = rigSetupDescriptorForAgent(agent);\n const client = toolspaceClient\n ? withSandboxLifecycleHooks(\n toolspaceClient,\n [\n // M3: same rig-setup-first ordering + credential-hook union as the owned\n // path (this legacy create/resume decoration path is byte-for-byte today\n // for a rig-less turn — the rig hooks are empty then).\n ...sandboxRigSetupHooksForAgent(agent),\n ...unionCredentialHooks(\n sandboxLifecycleHooksForIds(sandboxLifecycleHookIds(settings)),\n rigCredentialHooksForAgent(agent),\n ),\n ...sandboxToolspaceTokenHooksForAgent(agent),\n ...toolspaceTokenSessionRegistrationHooks(\n toolspaceTokenSeed ? overrides.onToolspaceTokenSessionReady : undefined,\n ),\n ...sandboxRepositoryCloneHooksForAgent(agent),\n ...gitCredentialSessionRegistrationHooks(overrides.onGitCredentialSessionReady),\n ],\n {\n environment,\n ...(overrides.onRuntimeEvent ? { onRuntimeEvent: overrides.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n ...(gitTokenSeeds ? { gitTokenSeeds } : {}),\n ...(gitCredentialBindings ? { gitCredentialBindings } : {}),\n ...(toolspaceTokenSeed ? { toolspaceTokenSeed } : {}),\n ...(toolspaceTokenFile ? { toolspaceTokenFile } : {}),\n ...(legacyRigSetup ? { rigSetup: legacyRigSetup } : {}),\n },\n )\n : undefined;\n const sandboxSessionState = prepared.sandboxSessionState;\n // Apply the built-in per-call filters (computer-call normalization, optional\n // provider-id stripping, image/budget guard), then any per-turn filter\n // (genesis title directive). A callModelInputFilter only shapes the per-call\n // model input; the SDK persists filtered clones into its session view, while\n // OpenGeni's durable conversation truth is still reconciled explicitly below.\n const callModelInputFilter = composeCallModelInputFilters(\n [\n callModelInputFilterForSettings(settings),\n genesisTitleInputFilter,\n overrides.callModelInputFilter,\n boundModelToolOutputsFilterForSettings(settings),\n contextRobustnessFilterForSettings(settings, {\n throwOnCompactionNeeded: Boolean(\n overrides.contextCompactionSignal || overrides.contextCompactionRequested,\n ),\n ...(overrides.contextCompactionSignal\n ? { contextCompactionSignal: overrides.contextCompactionSignal }\n : {}),\n ...(overrides.contextCompactionRequested\n ? { contextCompactionRequested: overrides.contextCompactionRequested }\n : {}),\n }),\n ].filter((f): f is CallModelInputFilter => Boolean(f)),\n );\n const runOptions: Parameters<typeof run>[2] = {\n stream: true,\n maxTurns: settings.agentMaxModelCallsPerTurn,\n // Built-in per-call guard chain: normalize computer calls, optionally strip\n // provider ids, trim to the input budget on the client-compaction path, and\n // raise the proactive compaction signal. This runs for turn-start replay AND\n // every mid-turn follow-up.\n callModelInputFilter,\n ...(overrides.signal ? { signal: overrides.signal } : {}),\n };\n if (client) {\n runOptions.sandbox = {\n client,\n ...(sandboxSessionState ? { sessionState: sandboxSessionState } : {}),\n } as SandboxRunConfig;\n }\n return await runScopedRunner(settings).run(agent, prepared.input, runOptions);\n}\n\nfunction appendSandboxFileDownloadFailureNote(\n input: PreparedAgentInput,\n failures: SandboxFileDownloadFailure[],\n): void {\n const note = sandboxFileDownloadFailureNote(failures);\n if (!note) {\n return;\n }\n if (typeof input.input === \"string\") {\n input.input = [input.input, \"\", note].join(\"\\n\");\n return;\n }\n if (Array.isArray(input.input)) {\n input.input = [\n ...input.input,\n { type: \"message\", role: \"user\", content: note } as AgentInputItem,\n ];\n }\n}\n\n/**\n * A per-run `Runner` whose `modelProvider` is built from THIS turn's settings.\n *\n * The standalone `run()` uses a process-global default Runner whose modelProvider\n * is the lazy global default (whatever the last `configureOpenAI` /\n * `setDefaultModelProvider` installed). The worker runs ~100 activities\n * concurrently in one process, so a concurrently-starting turn for a DIFFERENT\n * workspace can overwrite that global between this turn's `configure` and a\n * per-call `getModel()` during the stream — leaving the global router with no\n * codex provider and throwing CodexSubscriptionUnavailableError on a\n * `codex/<slug>` name re-resolution (the SandboxAgent/Modal path drops the Model\n * instance and re-resolves by NAME). Pinning a run-scoped Runner makes the\n * mutable global irrelevant to correctness: each concurrent turn resolves names\n * against its OWN settings (which carry the codex-subscription provider via\n * withCodexProvider for an active workspace, and the registry providers). The\n * Runner inherits the SDK's default config for everything else, identical to the\n * default runner. setDefaultModelProvider remains only as a boot-time fallback.\n */\nfunction runScopedRunner(settings: Settings): Runner {\n return new Runner({\n modelProvider: new MultiProviderModelProvider(settings),\n });\n}\n\nexport { MaxTurnsExceededError } from \"@openai/agents\";\n\n/**\n * Detects the agents SDK per-segment turn cap. The cap is a pacing valve, not\n * a session failure: callers should end the segment gracefully (idle) so an\n * active goal's continuation loop -- or a follow-up user message -- resumes\n * the work. When the SDK attached the run state at the moment the cap hit,\n * the serialized form is returned so the resumed turn keeps full context.\n */\nexport function maxTurnsExceededRunState(\n error: unknown,\n): { serializedRunState: string | null } | null {\n if (!(error instanceof MaxTurnsExceededError)) {\n return null;\n }\n try {\n return { serializedRunState: error.state ? error.state.toString() : null };\n } catch {\n return { serializedRunState: null };\n }\n}\n\n/**\n * Serialized run state attached to any agents SDK error, when present.\n * Provider failures usually surface as raw API errors without state; callers\n * must treat a null here as \"resume from the previous snapshot\" rather than\n * an error.\n */\nexport function agentsErrorRunState(error: unknown): string | null {\n if (!(error instanceof AgentsError) || !error.state) {\n return null;\n }\n try {\n return error.state.toString();\n } catch {\n return null;\n }\n}\n\nexport function withManifestRefreshOnResume(\n client: SandboxClient,\n targetManifest: Manifest | undefined,\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\"> = {},\n): SandboxClient {\n if (!targetManifest || !client.resume) {\n return client;\n }\n return {\n backendId: client.backendId,\n ...(client.supportsDefaultOptions !== undefined\n ? { supportsDefaultOptions: client.supportsDefaultOptions }\n : {}),\n ...(client.create\n ? {\n create: async (...args: any[]) => await (client.create as any)(...args),\n }\n : {}),\n resume: async (state: SandboxSessionState) => {\n const session = await client.resume!(state);\n await applyMissingManifestEntries(session, targetManifest, context);\n return session;\n },\n ...(client.delete\n ? {\n delete: async (state: SandboxSessionState) => await client.delete!(state),\n }\n : {}),\n ...(client.serializeSessionState\n ? {\n serializeSessionState: async (state: SandboxSessionState, options) =>\n await client.serializeSessionState!(state, options),\n }\n : {}),\n ...(client.canPersistOwnedSessionState\n ? {\n canPersistOwnedSessionState: async (state: SandboxSessionState) =>\n await client.canPersistOwnedSessionState!(state),\n }\n : {}),\n ...(client.canReusePreservedOwnedSession\n ? {\n canReusePreservedOwnedSession: async (state: SandboxSessionState) =>\n await client.canReusePreservedOwnedSession!(state),\n }\n : {}),\n ...(client.deserializeSessionState\n ? {\n deserializeSessionState: async (state: Record<string, unknown>) =>\n await client.deserializeSessionState!(state),\n }\n : {}),\n };\n}\n\n// OWNED-RESUME manifest refresh. This path runs ONLY for SDK-owned sessions\n// (withManifestRefreshOnResume wraps client.resume, which the SDK never calls\n// when handed a live provided session — the ownedSandbox branch bypasses this\n// entirely). Owned applyManifest MERGES env safely with no guard, and this\n// refresh is a FEATURE: it is how a workspace-env edit reaches a long-lived\n// owned local/docker box that rarely recycles. The provided-session env pin\n// (pinProvidedSessionManifestEnvironment below) — NOT this function — is the\n// fix for the SDK's validateNoEnvironmentDelta session-fatal guard. Drift is\n// additionally REPORTED here (key names only, never values) so any env\n// recompute change stays attributable from the DB alone.\nexport async function applyMissingManifestEntries(\n session: SandboxSessionLike,\n targetManifest: Manifest,\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\"> = {},\n): Promise<void> {\n const currentManifestValue = (\n session as {\n state?: {\n manifest?:\n | Manifest\n | {\n root?: string;\n entries?: Record<string, any>;\n environment?: Record<string, any>;\n };\n };\n }\n ).state?.manifest;\n const currentManifest = currentManifestValue ? ensureManifest(currentManifestValue) : undefined;\n const target = ensureManifest(targetManifest);\n if (!currentManifest) {\n if (Object.keys(target.entries).length === 0) {\n return;\n }\n throw new Error(\n \"Resumed sandbox session cannot apply new manifest entries because current manifest state is unavailable\",\n );\n }\n // Drift detection runs on EVERY resume (even no-op ones): the durable trace\n // that makes an env-recompute regression attributable from the DB instead of\n // from rotated worker logs.\n await reportManifestEnvironmentDrift(currentManifest, target, context);\n if (!session.applyManifest && !session.materializeEntry) {\n if (Object.keys(target.entries).length === 0) {\n return;\n }\n throw new Error(\n \"Resumed sandbox session cannot apply new manifest entries because it does not support applyManifest() or materializeEntry()\",\n );\n }\n if (Object.keys(target.entries).length === 0) {\n return;\n }\n if (currentManifest.root !== target.root) {\n throw new Error(\"Cannot apply per-turn resources to a sandbox with a different manifest root\");\n }\n const entries: Record<string, any> = {};\n for (const [path, entry] of Object.entries(target.entries)) {\n const existing = (currentManifest.entries as Record<string, unknown>)[path];\n if (existing === undefined) {\n entries[path] = entry;\n continue;\n }\n if (stableJson(existing) !== stableJson(entry)) {\n throw new Error(`Cannot replace existing sandbox manifest entry: ${path}`);\n }\n }\n const environmentChanged =\n stableJson(currentManifest.environment) !== stableJson(target.environment);\n if (environmentChanged && !session.applyManifest) {\n throw new Error(\n \"Resumed sandbox session cannot refresh manifest environment because it does not support applyManifest()\",\n );\n }\n if (Object.keys(entries).length === 0 && !environmentChanged) {\n return;\n }\n // Carry path grants through manifest rebuilds: since @openai/agents 0.11.0\n // they gate local source materialization, and run states saved before the\n // upgrade have manifests without grants.\n const extraPathGrants = mergePathGrants(currentManifest.extraPathGrants, target.extraPathGrants);\n const delta = new Manifest({\n root: currentManifest.root,\n entries,\n environment: target.environment,\n ...(extraPathGrants.length ? { extraPathGrants } : {}),\n });\n if (session.applyManifest) {\n await session.applyManifest(delta);\n } else {\n for (const [path, entry] of Object.entries(entries)) {\n await session.materializeEntry!({ path, entry });\n }\n }\n (session as { state?: { manifest?: Manifest } }).state!.manifest = new Manifest({\n root: currentManifest.root,\n environment: environmentChanged ? target.environment : currentManifest.environment,\n entries: {\n ...currentManifest.entries,\n ...entries,\n },\n ...(extraPathGrants.length ? { extraPathGrants } : {}),\n });\n}\n\n/**\n * Key-level diff of the live box's baked manifest env vs the freshly recomputed\n * target env. Returns null when identical. Key NAMES only — values are secrets\n * and must never leave this function's comparison.\n */\nexport function manifestEnvironmentDrift(\n current: Manifest,\n target: Manifest,\n): { added: string[]; removed: string[]; changed: string[] } | null {\n const currentEnv = (current.environment ?? {}) as Record<string, unknown>;\n const targetEnv = (target.environment ?? {}) as Record<string, unknown>;\n const added: string[] = [];\n const removed: string[] = [];\n const changed: string[] = [];\n for (const key of Object.keys(targetEnv)) {\n if (!(key in currentEnv)) {\n added.push(key);\n } else if (stableJson(currentEnv[key]) !== stableJson(targetEnv[key])) {\n changed.push(key);\n }\n }\n for (const key of Object.keys(currentEnv)) {\n if (!(key in targetEnv)) {\n removed.push(key);\n }\n }\n if (added.length === 0 && removed.length === 0 && changed.length === 0) {\n return null;\n }\n return {\n added: added.sort(),\n removed: removed.sort(),\n changed: changed.sort(),\n };\n}\n\nasync function reportManifestEnvironmentDrift(\n current: Manifest,\n target: Manifest,\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\">,\n): Promise<ReturnType<typeof manifestEnvironmentDrift>> {\n const drift = manifestEnvironmentDrift(current, target);\n if (!drift) {\n return null;\n }\n // Reporting must never break a resume: the drift itself is benign under the\n // env pin (the box keeps running on its baked env); only the SIGNAL matters.\n try {\n await context.onRuntimeEvent?.({\n type: \"sandbox.env.drift\",\n payload: drift,\n });\n } catch {\n // Swallow: a failed emit must not fail the turn.\n }\n return drift;\n}\n\n/**\n * ENV PIN for provided sessions (the ownership-inversion turn path). The SDK\n * validates the FULL target manifest environment against a live provided\n * session's baked env BEFORE reducing to its entry-only delta\n * (validateNoEnvironmentDelta -> session-fatal UserError on ANY difference).\n * So a turn resuming an existing box must declare the box's OWN env,\n * byte-identical — never the fresh recompute. This replaces the agent's\n * defaultManifest environment with the baked one and reports the drift (key\n * names only) instead of letting it kill the session. Fresh env lands at the\n * next cold-create; rotating values ride OFF-manifest (TOKEN-BROKER B1/B2).\n */\nexport async function pinProvidedSessionManifestEnvironment(\n agent: Agent<any, any>,\n session: SandboxSessionLike,\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\"> = {},\n): Promise<void> {\n const holder = agent as { defaultManifest?: Manifest };\n const currentManifestValue = (\n session as {\n state?: {\n manifest?:\n | Manifest\n | {\n root?: string;\n entries?: Record<string, any>;\n environment?: Record<string, any>;\n };\n };\n }\n ).state?.manifest;\n if (!holder.defaultManifest || !currentManifestValue) {\n return;\n }\n const current = ensureManifest(currentManifestValue);\n const target = ensureManifest(holder.defaultManifest);\n const drift = await reportManifestEnvironmentDrift(current, target, context);\n if (!drift) {\n return;\n }\n holder.defaultManifest = new Manifest({\n ...(target.root ? { root: target.root } : {}),\n entries: target.entries,\n environment: current.environment,\n ...(target.extraPathGrants?.length ? { extraPathGrants: target.extraPathGrants } : {}),\n });\n}\n\n/**\n * The one-truth owned-path platform setup: the manifest-env pin (align the turn's\n * manifest to the live box's baked env + report drift, NEVER die on it) plus the\n * beforeAgentStart hooks (repository clone with B1 token/askpass seed, toolspace\n * token seed, azure-cli-login) and signed-URL file materialization — all executed\n * DIRECTLY against the pinned, UN-proxied established box (the SDK never calls\n * client.create/resume for a provided session, so these decorations would never\n * fire on their own).\n *\n * Extracted verbatim from `runStream`'s owned branch so both the EAGER path\n * (runStream, before the run starts) and the LAZY path (the worker's first-op\n * provisioner, after the box is established) run the IDENTICAL setup. A pure\n * refactor for the eager path: same order, same gates, same idempotency\n * (clone skips a materialized tree, token seed overwrites — the desired per-turn\n * refresh, az login is idempotent). The connected-machine (selfhosted) branch\n * keeps platform setup OFF the user's real box and seeds ONLY the toolspace token.\n *\n * `gitTokenSeedsOverride` lets the lazy provisioner pass its own freshly-minted\n * run-scoped provider tokens (minted at establish time, not turn start);\n * unset ⇒ read the seeds off the agent exactly as the eager path does.\n */\nexport async function runOwnedSandboxSetup(\n agent: Agent<any, any>,\n session: SandboxSessionLike,\n setupSession: SandboxSessionLike,\n opts: {\n settings: Settings;\n environment: Record<string, string>;\n preparedInput?: PreparedAgentInput;\n fileDownloadsMaterialized?: boolean;\n onRuntimeEvent?: SandboxLifecycleHookContext[\"onRuntimeEvent\"];\n gitTokenSeedsOverride?: GitTokenSeeds;\n gitTokenSeedOverride?: string;\n gitCredentialBindingsOverride?: GitCredentialBindingSeed[];\n toolspaceTokenSeedOverride?: string;\n commandRunner?: SandboxLifecycleCommandRunner;\n },\n): Promise<void> {\n const { settings, environment } = opts;\n // ENV PIN (provided sessions): the SDK validates the FULL recomputed manifest\n // env against the live box's baked env before applying its entry-only delta\n // (validateNoEnvironmentDelta — session-fatal on ANY drift; killed a 4-day\n // prod manager session 2026-07-06). Align the turn's manifest to the box's\n // own env and REPORT the drift instead of dying on it.\n await pinProvidedSessionManifestEnvironment(agent, session, {\n ...(opts.onRuntimeEvent ? { onRuntimeEvent: opts.onRuntimeEvent } : {}),\n });\n const runAs = sandboxRunAs(settings);\n const fileDownloads = sandboxFileDownloadsForAgent(agent);\n // TOKEN-BROKER (B1): per-turn provider token seeds, forwarded OFF-MANIFEST so\n // the repository-clone hook writes provider token files before the clone. The\n // lazy provisioner overrides them with its own establish-time mint.\n const ownedGitTokenSeeds = {\n ...(gitTokenSeedsForAgent(agent) ?? {}),\n ...(opts.gitTokenSeedOverride ? { github: opts.gitTokenSeedOverride } : {}),\n ...(opts.gitTokenSeedsOverride ?? {}),\n } satisfies GitTokenSeeds;\n const ownedGitCredentialBindings =\n opts.gitCredentialBindingsOverride ?? gitCredentialBindingsForAgent(agent);\n const ownedToolspaceTokenSeed =\n opts.toolspaceTokenSeedOverride ?? toolspaceTokenSeedForAgent(agent);\n const ownedToolspaceTokenFile = toolspaceTokenFileForAgent(agent, environment);\n const ownedRigSetup = rigSetupDescriptorForAgent(agent);\n const ownedHooks = [\n // M3: rig setup runs FIRST so any tooling it installs is present for the\n // credential / repository-clone hooks below; the rig's credential hooks are\n // unioned into the deployment preparation-profile hooks (deduped by id).\n // This is the LIVE owned-path execution (the provided session skips the\n // client create/resume decoration), so the rig hooks MUST be here or a\n // rig-bound turn would start without ever running the frozen setup script.\n ...sandboxRigSetupHooksForAgent(agent),\n ...unionCredentialHooks(\n sandboxLifecycleHooksForIds(sandboxLifecycleHookIds(settings)),\n rigCredentialHooksForAgent(agent),\n ),\n ...sandboxToolspaceTokenHooksForAgent(agent),\n ...sandboxRepositoryCloneHooksForAgent(agent),\n ];\n const ownedHookContext: SandboxLifecycleHookContext = {\n environment,\n ...(opts.onRuntimeEvent ? { onRuntimeEvent: opts.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n ...(Object.keys(ownedGitTokenSeeds).length > 0 ? { gitTokenSeeds: ownedGitTokenSeeds } : {}),\n ...(ownedGitCredentialBindings ? { gitCredentialBindings: ownedGitCredentialBindings } : {}),\n ...(ownedToolspaceTokenSeed ? { toolspaceTokenSeed: ownedToolspaceTokenSeed } : {}),\n ...(ownedToolspaceTokenFile ? { toolspaceTokenFile: ownedToolspaceTokenFile } : {}),\n ...(ownedRigSetup ? { rigSetup: ownedRigSetup } : {}),\n ...(opts.commandRunner ? { commandRunner: opts.commandRunner } : {}),\n };\n // OWNED-PATH HOOKS: run the beforeAgentStart hooks directly against the provided\n // box, once per turn, BEFORE the run starts (repository-clone hook seeds the B1\n // askpass + token file; azure-cli-login on lease-owned boxes). Re-running on a\n // warm box is safe by construction (clone skips a materialized tree, token seed\n // overwrites the file, az login is idempotent). EXCEPT on a connected machine\n // (effective backend \"selfhosted\"): the box is the user's REAL computer — the\n // platform must not run setup against it (clone hooks are already empty there;\n // this keeps az login off it too).\n if (agentActiveSandboxBackend.get(agent) !== \"selfhosted\") {\n await runBeforeAgentStartHooks(setupSession, ownedHooks, ownedHookContext);\n // FILE RESOURCES: withSandboxFileDownloads has the IDENTICAL provided-session\n // blind spot (it too wraps only create/resume), so signed-URL file\n // materialization must also run directly against the pinned box. The download\n // command is idempotent (skips an existing file) and atomic (tmp + rename).\n if (fileDownloads.length > 0 && !opts.fileDownloadsMaterialized) {\n const materialized = await materializeSandboxFileDownloads(setupSession, fileDownloads, {\n ...(opts.onRuntimeEvent ? { onRuntimeEvent: opts.onRuntimeEvent } : {}),\n ...(runAs ? { runAs } : {}),\n ...(opts.commandRunner ? { commandRunner: opts.commandRunner } : {}),\n });\n if (opts.preparedInput) {\n appendSandboxFileDownloadFailureNote(opts.preparedInput, materialized.failures);\n }\n }\n } else {\n // SELFHOSTED TOOLSPACE (parity): the platform setup hooks and file\n // materialization stay OFF the user's real machine — but the toolspace token\n // seed is the ONE piece of per-turn material that must reach it (a scoped,\n // own-session-bound token written to $OPENGENI_TOOLSPACE_TOKEN_FILE over the\n // same off-manifest exec channel the clone-seed uses; the machine's only path\n // to programmatic tool calling). Seed it (only) here.\n const toolspaceHooks = sandboxToolspaceTokenHooksForAgent(agent);\n if (toolspaceHooks.length > 0) {\n await runBeforeAgentStartHooks(setupSession, toolspaceHooks, ownedHookContext);\n }\n }\n}\n\nfunction mergePathGrants(\n current: Manifest[\"extraPathGrants\"] | undefined,\n target: Manifest[\"extraPathGrants\"] | undefined,\n): Manifest[\"extraPathGrants\"] {\n const merged = new Map<string, Manifest[\"extraPathGrants\"][number]>();\n for (const grant of [...(current ?? []), ...(target ?? [])]) {\n merged.set(grant.path, grant);\n }\n return [...merged.values()];\n}\n\nexport function withSandboxFileDownloads(\n client: SandboxClient,\n downloads: SandboxFileDownload[],\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\" | \"runAs\" | \"commandRunner\"> = {},\n): SandboxClient {\n const normalizedDownloads = normalizeSandboxFileDownloads(downloads);\n if (normalizedDownloads.length === 0) {\n return client;\n }\n const completed = new WeakSet<object>();\n const wrapSession = async <T extends SandboxSessionLike>(session: T): Promise<T> => {\n if (typeof session === \"object\" && session !== null && !completed.has(session)) {\n await materializeSandboxFileDownloads(session, normalizedDownloads, context);\n completed.add(session);\n }\n return session;\n };\n return {\n backendId: client.backendId,\n ...(client.supportsDefaultOptions !== undefined\n ? { supportsDefaultOptions: client.supportsDefaultOptions }\n : {}),\n ...(client.create\n ? {\n create: async (...args: any[]) =>\n await wrapSession(await (client.create as any)(...args)),\n }\n : {}),\n ...(client.resume\n ? {\n resume: async (state: SandboxSessionState) =>\n await wrapSession(await client.resume!(state)),\n }\n : {}),\n ...(client.delete\n ? {\n delete: async (state: SandboxSessionState) => await client.delete!(state),\n }\n : {}),\n ...(client.serializeSessionState\n ? {\n serializeSessionState: async (state: SandboxSessionState, options) =>\n await client.serializeSessionState!(state, options),\n }\n : {}),\n ...(client.canPersistOwnedSessionState\n ? {\n canPersistOwnedSessionState: async (state: SandboxSessionState) =>\n await client.canPersistOwnedSessionState!(state),\n }\n : {}),\n ...(client.canReusePreservedOwnedSession\n ? {\n canReusePreservedOwnedSession: async (state: SandboxSessionState) =>\n await client.canReusePreservedOwnedSession!(state),\n }\n : {}),\n ...(client.deserializeSessionState\n ? {\n deserializeSessionState: async (state: Record<string, unknown>) =>\n await client.deserializeSessionState!(state),\n }\n : {}),\n };\n}\n\nexport async function materializeSandboxFileDownloads(\n session: SandboxSessionLike,\n downloads: SandboxFileDownload[],\n context: Pick<SandboxLifecycleHookContext, \"onRuntimeEvent\" | \"runAs\" | \"commandRunner\"> = {},\n): Promise<SandboxFileDownloadMaterializationResult> {\n const normalizedDownloads = normalizeSandboxFileDownloads(downloads);\n if (normalizedDownloads.length === 0) {\n return { failures: [] };\n }\n const failures: SandboxFileDownloadFailure[] = [];\n for (const download of normalizedDownloads) {\n const targetPath = sandboxDownloadTargetPath(download);\n const payload = {\n fileId: download.fileId,\n path: targetPath,\n sizeBytes: download.sizeBytes ?? null,\n expiresAt: download.expiresAt ? new Date(download.expiresAt).toISOString() : null,\n };\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.started\",\n payload: { name: \"file-resource-download\", ...payload },\n });\n if (!session.exec && !session.execCommand) {\n const failure = sandboxFileDownloadFailure(\n download,\n targetPath,\n \"Sandbox file download materialization requires command execution support\",\n );\n failures.push(failure);\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.failed\",\n payload: {\n name: \"file-resource-download\",\n ...payload,\n error: failure.reason,\n },\n });\n continue;\n }\n let result: unknown;\n try {\n result = await runSandboxLifecycleCommand(\n session,\n {\n cmd: sandboxFileDownloadCommand(download, targetPath),\n workdir: \"/workspace\",\n ...(context.runAs ? { runAs: context.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 20_000,\n },\n context.commandRunner,\n );\n assertSandboxCommandSucceeded(result, `Sandbox file resource download ${download.fileId}`);\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.completed\",\n payload: { name: \"file-resource-download\", ...payload },\n });\n } catch (error) {\n if (error instanceof TurnSandboxCommandCancelledError) throw error;\n const failure = sandboxFileDownloadFailure(download, targetPath, error, result);\n failures.push(failure);\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.failed\",\n payload: {\n name: \"file-resource-download\",\n ...payload,\n error: failure.reason,\n ...(failure.exitCode !== undefined ? { exitCode: failure.exitCode } : {}),\n ...(failure.output ? { output: failure.output } : {}),\n },\n });\n }\n }\n return { failures };\n}\n\nfunction sandboxFileDownloadFailure(\n download: SandboxFileDownload,\n targetPath: string,\n error: unknown,\n result?: unknown,\n): SandboxFileDownloadFailure {\n const exitCode = sandboxCommandExitCode(result);\n const output = sandboxCommandOutput(result);\n return {\n fileId: download.fileId,\n filename: download.filename,\n path: targetPath,\n reason: error instanceof Error ? error.message : String(error),\n ...(exitCode !== null ? { exitCode } : {}),\n ...(output ? { output } : {}),\n };\n}\n\nexport function sandboxFileDownloadFailureNote(failures: SandboxFileDownloadFailure[]): string {\n if (failures.length === 0) {\n return \"\";\n }\n return [\n \"The following attached files could not be loaded into the sandbox and are unavailable this turn:\",\n ...failures.map((failure) => `- ${failure.filename} (${failure.reason})`),\n \"Continue without them or tell the user.\",\n ].join(\"\\n\");\n}\n\nexport function sandboxFileDownloadsForAgent(agent: unknown): SandboxFileDownload[] {\n return typeof agent === \"object\" && agent !== null\n ? [...(agentFileDownloads.get(agent) ?? [])]\n : [];\n}\n\nfunction ensureManifest(\n manifest:\n | Manifest\n | {\n root?: string;\n entries?: Record<string, any>;\n environment?: Record<string, any>;\n extraPathGrants?: any[];\n },\n): Manifest {\n if (\n manifest instanceof Manifest &&\n typeof manifest.mountTargetsForMaterialization === \"function\"\n ) {\n return manifest;\n }\n return new Manifest({\n ...(manifest.root ? { root: manifest.root } : {}),\n entries: manifest.entries ?? {},\n environment: manifest.environment ?? {},\n ...(manifest.extraPathGrants?.length ? { extraPathGrants: manifest.extraPathGrants } : {}),\n });\n}\n\nfunction base64DecodedByteLength(value: string): number {\n const padding = value.endsWith(\"==\") ? 2 : value.endsWith(\"=\") ? 1 : 0;\n return Math.max(0, Math.floor((value.length * 3) / 4) - padding);\n}\n\n/** Determine image byte length without allocating another binary/base64 copy. */\nfunction imageDataByteLength(data: unknown): number | null {\n if (ArrayBuffer.isView(data)) return data.byteLength;\n if (data instanceof ArrayBuffer) return data.byteLength;\n if (Array.isArray(data)) {\n return data.every((value) => typeof value === \"number\") ? data.length : null;\n }\n if (!data || typeof data !== \"object\") return null;\n const record = data as Record<string, unknown>;\n if (record.type === \"Buffer\" && Array.isArray(record.data)) {\n return record.data.every((value) => typeof value === \"number\") ? record.data.length : null;\n }\n const keys = Object.keys(record);\n return keys.length > 0 &&\n keys.every((key) => /^\\d+$/.test(key) && typeof record[key] === \"number\")\n ? keys.length\n : null;\n}\n\n/**\n * Convert one image-shaped tool result into a content-free audit fact. This is\n * intentionally different from model history: the model keeps its structured\n * image item, while `session_events` never becomes an implicit image blob store.\n */\nfunction toolOutputMediaPreview(value: unknown): SessionEventMediaPreview | null {\n if (typeof value === \"string\") {\n return sessionEventMediaPreviewFromDataUrl(value);\n }\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const record = value as Record<string, unknown>;\n if (record.type === \"input_image\") {\n const source = record.image ?? record.image_url ?? record.imageUrl;\n const url =\n typeof source === \"string\"\n ? source\n : source && typeof source === \"object\"\n ? (source as Record<string, unknown>).url\n : null;\n if (typeof url !== \"string\" || url.length === 0) return null;\n return sessionEventMediaPreviewFromDataUrl(url) ?? sessionEventMediaPreview(\"image/*\", null);\n }\n if (record.type !== \"image\" || !record.image || typeof record.image !== \"object\") return null;\n const image = record.image as Record<string, unknown>;\n const mediaType =\n typeof image.mediaType === \"string\" && image.mediaType.length > 0\n ? image.mediaType\n : \"image/png\";\n if (typeof image.url === \"string\" && image.url.length > 0) {\n return (\n sessionEventMediaPreviewFromDataUrl(image.url) ?? sessionEventMediaPreview(mediaType, null)\n );\n }\n if (typeof image.data === \"string\") {\n return (\n sessionEventMediaPreviewFromDataUrl(image.data) ??\n sessionEventMediaPreview(mediaType, base64DecodedByteLength(image.data))\n );\n }\n const byteLength = imageDataByteLength(image.data);\n return byteLength === null ? null : sessionEventMediaPreview(mediaType, byteLength);\n}\n\n/**\n * Normalize a tool-call output for the lossy `agent.toolCall.output` audit event.\n * Inline image bytes/data URLs become a compact `media_preview` with exact byte\n * length where knowable and `fullOutputAvailable:false`. The model-facing output\n * is not changed here, and mixed arrays retain their non-image text/error facts.\n */\nexport function normalizeToolOutputForEvent(output: unknown): unknown {\n const single = toolOutputMediaPreview(output);\n if (single !== null) {\n return single;\n }\n if (Array.isArray(output)) {\n const normalized = output.map((el) => toolOutputMediaPreview(el) ?? el);\n if (normalized.length === 1 && normalized[0]?.type === \"media_preview\") {\n return normalized[0];\n }\n return normalized;\n }\n return output;\n}\n\n/**\n * Hosted web_search progresses on the raw Responses stream\n * (`response.output_item.added/done` with `web_search_call`) long before the SDK\n * materializes a `RunToolCallItem` at `response_done`. Without this mapping the\n * timeline only sees search cards after the whole model round finishes — or\n * never mid-turn — while assistant prose (\"Search 1/5\") streams live.\n */\nfunction hostedWebSearchToolCallFromResponsesEvent(raw: unknown): NormalizedRuntimeEvent | null {\n if (!raw || typeof raw !== \"object\") {\n return null;\n }\n const event = raw as {\n type?: unknown;\n item?: {\n id?: unknown;\n type?: unknown;\n status?: unknown;\n action?: unknown;\n [key: string]: unknown;\n };\n };\n const eventType = typeof event.type === \"string\" ? event.type : \"\";\n if (\n !(\n (eventType === \"response.output_item.added\" || eventType === \"response.output_item.done\") &&\n event.item?.type === \"web_search_call\"\n )\n ) {\n // Progress-only `response.web_search_call.*` events lack the action\n // payload; added/done are enough for a live, query-bearing card.\n return null;\n }\n const item = event.item;\n const itemId = typeof item.id === \"string\" ? item.id : null;\n if (!itemId) {\n return null;\n }\n const status =\n typeof item.status === \"string\"\n ? item.status\n : eventType === \"response.output_item.done\"\n ? \"completed\"\n : \"in_progress\";\n const action = item.action ?? null;\n // Codex frequently emits `output_item.added` for web_search_call before the\n // action payload exists. Persist that so the timeline can show \"Searching…\",\n // then the matching `done` (same id) fills in query/queries via merge.\n const { status: _status, ...providerData } = item;\n\n return {\n type: \"agent.toolCall.created\",\n payload: {\n id: itemId,\n name: \"web_search_call\",\n arguments: action,\n raw: {\n type: \"hosted_tool_call\",\n id: itemId,\n name: \"web_search_call\",\n status,\n providerData,\n },\n },\n };\n}\n\nexport function normalizeSdkEvent(event: RunStreamEvent): NormalizedRuntimeEvent[] {\n const out: NormalizedRuntimeEvent[] = [];\n if (event.type === \"raw_model_stream_event\") {\n const data = (event as any).data;\n if (data?.type === \"output_text_delta\" && typeof data.delta === \"string\") {\n out.push({ type: \"agent.message.delta\", payload: { text: data.delta } });\n return out;\n }\n if (data?.type === \"response_done\") {\n return out;\n }\n }\n if (isOpenAIResponsesRawModelStreamEvent(event)) {\n const raw = (event as any).data?.event;\n if (raw?.type === \"response.reasoning_summary_text.delta\" && typeof raw.delta === \"string\") {\n out.push({ type: \"agent.reasoning.delta\", payload: { text: raw.delta } });\n }\n const webSearch = hostedWebSearchToolCallFromResponsesEvent(raw);\n if (webSearch) {\n out.push(webSearch);\n }\n return out;\n }\n if (event.type === \"agent_updated_stream_event\") {\n out.push({\n type: \"agent.updated\",\n payload: { agent: (event as any).agent?.name ?? null },\n });\n return out;\n }\n if (event.type !== \"run_item_stream_event\") {\n return out;\n }\n const item = (event as any).item;\n if (!item) {\n return out;\n }\n if (item.type === \"tool_call_item\") {\n const raw = item.rawItem ?? {};\n out.push({\n type: \"agent.toolCall.created\",\n payload: {\n id: raw.callId ?? raw.id ?? item.id ?? null,\n name: raw.name ?? raw.type ?? \"tool\",\n arguments: raw.arguments ?? raw.input ?? null,\n raw,\n },\n });\n } else if (item.type === \"tool_call_output_item\") {\n out.push({\n type: \"agent.toolCall.output\",\n payload: {\n id: item.rawItem?.callId ?? item.id ?? null,\n // Inline media becomes a content-free audit fact. Model history keeps\n // the provider's real structured image output on its separate path.\n output: normalizeToolOutputForEvent(item.output),\n },\n });\n } else if (item.type === \"tool_search_call_item\") {\n // Progressive connector disclosure: surface the model's tool search as a\n // regular tool-call event so the session stream shows the step (parity with\n // the Codex CLI, which renders its searches). Arguments may be an object\n // (the live wire shape) or a string.\n const raw = item.rawItem ?? {};\n out.push({\n type: \"agent.toolCall.created\",\n payload: {\n id: raw.call_id ?? raw.callId ?? raw.id ?? item.id ?? null,\n name: \"tool_search\",\n arguments: raw.arguments ?? null,\n raw,\n },\n });\n } else if (item.type === \"tool_search_output_item\") {\n const raw = item.rawItem ?? {};\n const disclosed = Array.isArray(raw.tools)\n ? raw.tools\n .map((tool: { name?: unknown }) => (typeof tool?.name === \"string\" ? tool.name : \"\"))\n .filter(Boolean)\n : [];\n out.push({\n type: \"agent.toolCall.output\",\n payload: {\n id: raw.call_id ?? raw.callId ?? item.id ?? null,\n output: {\n type: \"text\",\n text:\n disclosed.length > 0\n ? `Disclosed tools: ${disclosed.join(\", \")}`\n : \"No matching tools found.\",\n },\n },\n });\n } else if (item.type === \"message_output_item\") {\n const text = typeof item.text === \"string\" ? item.text : undefined;\n if (text) {\n out.push({ type: \"agent.message.completed\", payload: { text } });\n }\n }\n return out;\n}\n\nexport function modelResponseUsageFromSdkEvent(event: RunStreamEvent): ModelResponseUsage | null {\n const response = modelResponseFromSdkEvent(event);\n return modelResponseUsageFromResponse(response);\n}\n\n/** Normalize usage from either a Responses or Chat Completions result. */\nexport function modelResponseUsageFromResponse(response: unknown): ModelResponseUsage | null {\n const usage = usageFromResponse(response);\n if (!usage) {\n return null;\n }\n const responseId =\n typeof (response as { id?: unknown } | null)?.id === \"string\"\n ? (response as { id: string }).id\n : typeof (response as { responseId?: unknown } | null)?.responseId === \"string\"\n ? (response as { responseId: string }).responseId\n : undefined;\n const serviceTier = modelResponseServiceTierFromResponse(response);\n return {\n ...(responseId ? { responseId } : {}),\n ...(serviceTier ? { serviceTier } : {}),\n usage,\n };\n}\n\nexport type ModelResponseServiceTierEvent = {\n source: \"normalized\" | \"provider\";\n serviceTier: string | null;\n};\n\n/**\n * Read the provider's terminal service tier without depending on usage being\n * present. The normalized terminal can omit provider-only fields, so callers\n * should treat the raw provider response as the fail-closed authority.\n */\nexport function modelResponseServiceTierFromSdkEvent(\n event: RunStreamEvent,\n): ModelResponseServiceTierEvent | null {\n if (event.type === \"raw_model_stream_event\") {\n const data = (event as any).data;\n if (data?.type === \"response_done\") {\n return {\n source: \"normalized\",\n serviceTier: modelResponseServiceTierFromResponse(data.response),\n };\n }\n }\n if (isOpenAIResponsesRawModelStreamEvent(event)) {\n const raw = (event as any).data?.event;\n if (raw?.type === \"response.completed\") {\n return {\n source: \"provider\",\n serviceTier: modelResponseServiceTierFromResponse(raw.response),\n };\n }\n }\n return null;\n}\n\nfunction modelResponseServiceTierFromResponse(response: unknown): string | null {\n if (!response || typeof response !== \"object\") {\n return null;\n }\n const record = response as Record<string, unknown>;\n const direct = record.service_tier ?? record.serviceTier;\n if (typeof direct === \"string\" && direct.length > 0) {\n return direct;\n }\n const providerData =\n record.providerData && typeof record.providerData === \"object\"\n ? (record.providerData as Record<string, unknown>)\n : null;\n const nested = providerData?.service_tier ?? providerData?.serviceTier;\n return typeof nested === \"string\" && nested.length > 0 ? nested : null;\n}\n\nfunction modelResponseFromSdkEvent(event: RunStreamEvent): any {\n if (event.type === \"raw_model_stream_event\") {\n const data = (event as any).data;\n if (data?.type === \"response_done\") {\n return data.response;\n }\n }\n if (isOpenAIResponsesRawModelStreamEvent(event)) {\n const raw = (event as any).data?.event;\n if (raw?.type === \"response.completed\") {\n return raw.response;\n }\n }\n return null;\n}\n\nfunction usageFromResponse(response: unknown): ModelResponseUsage[\"usage\"] | null {\n const raw = (response as { usage?: unknown } | null)?.usage;\n if (!raw || typeof raw !== \"object\") {\n return null;\n }\n const record = raw as Record<string, unknown>;\n const usage = {\n ...numberProp(\n record,\n \"inputTokens\",\n \"inputTokens\",\n \"input_tokens\",\n \"promptTokens\",\n \"prompt_tokens\",\n ),\n ...numberProp(\n record,\n \"outputTokens\",\n \"outputTokens\",\n \"output_tokens\",\n \"completionTokens\",\n \"completion_tokens\",\n ),\n ...numberProp(record, \"totalTokens\", \"totalTokens\", \"total_tokens\"),\n ...inputTokenDetailsProp(record),\n ...outputTokenDetailsProp(record),\n ...requestUsageEntriesProp(record),\n };\n return Object.keys(usage).length > 0 ? usage : null;\n}\n\nfunction numberProp(\n raw: Record<string, unknown>,\n outputKey: \"inputTokens\" | \"outputTokens\" | \"totalTokens\",\n ...keys: string[]\n): Partial<ModelResponseUsage[\"usage\"]> {\n const value = keys.map((key) => raw[key]).find((candidate) => candidate !== undefined);\n // Preserve numeric provider values verbatim here, including malformed ones.\n // The shared usage normalizer is the single bounded validation boundary and\n // needs to see NaN/infinite/fractional/oversized values so it can emit safe\n // field-path diagnostics rather than silently erasing the evidence.\n return typeof value === \"number\" ? { [outputKey]: value } : {};\n}\n\nfunction inputTokenDetailsProp(raw: Record<string, unknown>): Partial<ModelResponseUsage[\"usage\"]> {\n const details =\n raw.inputTokensDetails ??\n raw.input_tokens_details ??\n raw.promptTokensDetails ??\n raw.prompt_tokens_details;\n if (details === undefined || details === null) {\n return {};\n }\n return {\n inputTokensDetails: details as Record<string, number> | Array<Record<string, number>>,\n };\n}\n\nfunction outputTokenDetailsProp(\n raw: Record<string, unknown>,\n): Partial<ModelResponseUsage[\"usage\"]> {\n const details = raw.outputTokensDetails ?? raw.output_tokens_details;\n const normalized = details ?? raw.completionTokensDetails ?? raw.completion_tokens_details;\n if (normalized === undefined || normalized === null) {\n return {};\n }\n return {\n outputTokensDetails: normalized as Record<string, number> | Array<Record<string, number>>,\n };\n}\n\nfunction requestUsageEntriesProp(\n raw: Record<string, unknown>,\n): Partial<ModelResponseUsage[\"usage\"]> {\n const entries = raw.requestUsageEntries ?? raw.request_usage_entries;\n if (entries === undefined || entries === null) {\n return {};\n }\n return {\n // The normalizer validates every entry and all supported field aliases.\n // Preserve the SDK objects rather than rebuilding them and accidentally\n // dropping provider detail fields such as cache_write_tokens.\n requestUsageEntries: entries as NonNullable<ModelResponseUsage[\"usage\"][\"requestUsageEntries\"]>,\n };\n}\n\nexport function serializeApprovals(interruptions: unknown[]): unknown[] {\n return interruptions\n .filter((item) => interruptionToolName(item) !== HUMAN_INPUT_TOOL_NAME)\n .map((item: any) => {\n if (typeof item?.toJSON === \"function\") {\n return item.toJSON();\n }\n return {\n id: approvalIdentifier(item) ?? \"approval\",\n name: item?.name ?? item?.rawItem?.name ?? \"tool\",\n arguments: item?.arguments ?? item?.rawItem?.arguments ?? null,\n raw: item,\n };\n });\n}\n\nexport function serializeHumanInputRequests(\n interruptions: unknown[],\n): SerializedHumanInputInterruption[] {\n return interruptions\n .filter((item) => interruptionToolName(item) === HUMAN_INPUT_TOOL_NAME)\n .map((item: any) => {\n const rawArguments = item?.arguments ?? item?.rawItem?.arguments;\n let parsedArguments: unknown = rawArguments;\n if (typeof rawArguments === \"string\") {\n try {\n parsedArguments = JSON.parse(rawArguments);\n } catch {\n throw new Error(\"Human-input interruption contains invalid JSON arguments\");\n }\n }\n const toolCallId = approvalIdentifier(item);\n if (!toolCallId) {\n throw new Error(\"Human-input interruption is missing a stable tool-call identity\");\n }\n return {\n toolCallId,\n input: RequestHumanInputToolInput.parse(parsedArguments),\n };\n });\n}\n\nexport function buildManifest(\n settings: Settings,\n resources: ResourceRef[],\n environment = collectSandboxEnvironment(settings),\n fileResourceDownloads: SandboxFileDownload[] = [],\n): Manifest {\n assertUniqueResourceMountPaths(resources);\n const entries: Record<string, any> = {};\n const downloadsByFileId = new Map(\n normalizeSandboxFileDownloads(fileResourceDownloads).map((download) => [\n download.fileId,\n download,\n ]),\n );\n for (const resource of resources) {\n if (resource.kind === \"repository\") {\n const url = new URL(resource.uri);\n const host = url.host.toLowerCase();\n const repo = url.pathname.replace(/^\\/+|\\/+$/g, \"\").replace(/\\.git$/, \"\");\n const mountPath = resourceMountPath(resource);\n if (repositoryUsesSandboxClone(settings, resource)) {\n entries[mountPath] = dir();\n continue;\n }\n entries[mountPath] = gitRepo({\n host,\n repo,\n ref: resource.ref,\n ...(resource.subpath ? { subpath: normalizeRepositorySubpath(resource.subpath) } : {}),\n });\n continue;\n }\n if (resource.kind === \"file\") {\n const mountPath = resourceMountPath(resource);\n const download = downloadsByFileId.get(resource.fileId);\n entries[mountPath] = download\n ? sandboxDownloadDirectory(download, mountPath)\n : objectStorageFileMount(settings, `files/${resource.fileId}/original`);\n }\n }\n // No extraPathGrants here: remote sandbox clients (Modal) reject manifests\n // that carry them at create/apply time, which broke every Modal session.\n // The lazy bundled-skills source no longer needs a grant because\n // bundledSkillsDir() stages the skills inside the process working directory\n // whenever the packaged copy lives outside it.\n return new Manifest({\n root: \"/workspace\",\n entries,\n environment,\n });\n}\n\nexport function repositoryWorkspaceSkillPathsOption(resources: readonly ResourceRef[]): {\n workspaceSkillPaths?: readonly WorkspaceSkillSearchPath[];\n} {\n const repositories = resources.filter(\n (resource): resource is Extract<ResourceRef, { kind: \"repository\" }> =>\n resource.kind === \"repository\",\n );\n if (repositories.length === 0) return {};\n\n const paths = new Map<string, WorkspaceSkillSearchPath>();\n const add = (path: string, source: string): void => {\n if (!paths.has(path)) paths.set(path, { path, source });\n };\n // A Connected Machine maps /workspace to its configured working directory,\n // which may itself be the selected repository. Managed sandboxes normally use\n // the repository mount paths below. Checking both keeps the rule portable.\n add(\".agents/skills\", \"workspace .agents/skills\");\n add(\".claude/skills\", \"workspace .claude/skills\");\n for (const repository of repositories) {\n const mountPath = resourceMountPath(repository);\n add(`${mountPath}/.agents/skills`, `${mountPath}/.agents/skills`);\n add(`${mountPath}/.claude/skills`, `${mountPath}/.claude/skills`);\n }\n return { workspaceSkillPaths: [...paths.values()] };\n}\n\nfunction sandboxDownloadDirectory(download: SandboxFileDownload, mountPath: string): any {\n if (download.mountPath !== mountPath) {\n throw new Error(\n `File download materialization path mismatch for ${download.fileId}: expected ${mountPath}, got ${download.mountPath}`,\n );\n }\n assertSafeSandboxFilename(download.filename, download.fileId);\n if (download.content) {\n return dir({\n children: {\n [download.filename]: file({ content: download.content }),\n },\n });\n }\n return dir();\n}\n\nfunction objectStorageFileMount(settings: Settings, prefix: string): any {\n // Descriptor-driven: a nativeBucketMount backend (modal) mounts via the\n // provider's own bucket-mount strategy and cannot mount Azure Blob entries —\n // it needs pre-signed downloads instead. Reading the descriptor (not a\n // hard-coded backend name) keeps this honest as providers are added.\n const nativeBucketMount = CAPABILITY_DESCRIPTORS[settings.sandboxBackend].nativeBucketMount;\n if (settings.objectStorageBackend === \"azure-blob\") {\n if (nativeBucketMount) {\n throw new Error(\n \"Modal sandbox Azure Blob file resources require pre-signed download materialization because the current OpenAI Agents SDK Modal client does not support Azure Blob mount entries.\",\n );\n }\n const config = azureBlobMountConfig(settings);\n return azureBlobMount({\n container: config.container,\n prefix,\n accountName: config.accountName,\n accountKey: config.accountKey,\n endpointUrl: config.endpointUrl,\n readOnly: true,\n mountStrategy: inContainerMountStrategy({\n pattern: { type: \"rclone\", mode: \"fuse\" },\n }),\n });\n }\n if (settings.objectStorageBackend === \"aws-s3\" || settings.objectStorageBackend === \"gcs\") {\n throw new Error(\n `${settings.objectStorageBackend} file resources require pre-signed download materialization`,\n );\n }\n const config = s3CompatibleMountConfig(settings);\n return s3Mount({\n bucket: config.bucket,\n prefix,\n endpointUrl: config.endpointUrl,\n region: config.region,\n s3Provider: config.s3Provider,\n accessKeyId: config.accessKeyId,\n secretAccessKey: config.secretAccessKey,\n readOnly: true,\n mountStrategy: nativeBucketMount\n ? new ModalCloudBucketMountStrategy()\n : inContainerMountStrategy({ pattern: { type: \"rclone\", mode: \"fuse\" } }),\n });\n}\n\nfunction s3CompatibleMountConfig(settings: Settings): {\n bucket: string;\n endpointUrl: string;\n region: string;\n s3Provider: string;\n accessKeyId: string;\n secretAccessKey: string;\n} {\n const endpointUrl = settings.objectStorageSandboxEndpoint ?? settings.objectStorageEndpoint;\n if (\n !endpointUrl ||\n !settings.objectStorageAccessKeyId ||\n !settings.objectStorageSecretAccessKey\n ) {\n throw new Error(\"File resources require configured S3-compatible object storage\");\n }\n return {\n bucket: settings.objectStorageBucket,\n endpointUrl,\n region: settings.objectStorageRegion,\n s3Provider: settings.objectStorageS3Provider,\n accessKeyId: settings.objectStorageAccessKeyId,\n secretAccessKey: settings.objectStorageSecretAccessKey,\n };\n}\n\nfunction azureBlobMountConfig(settings: Settings): {\n container: string;\n accountName: string;\n accountKey: string;\n endpointUrl?: string;\n} {\n const parsed = settings.objectStorageAzureConnectionString\n ? parseAzureConnectionString(settings.objectStorageAzureConnectionString)\n : {};\n const accountName = settings.objectStorageAzureAccountName ?? parsed.AccountName;\n const accountKey = settings.objectStorageAzureAccountKey ?? parsed.AccountKey;\n if (!accountName || !accountKey) {\n throw new Error(\"File resources require Azure Blob account name and account key\");\n }\n const endpointUrl = azureBlobManifestEndpoint(\n settings.objectStorageAzureEndpoint ?? parsed.BlobEndpoint,\n accountName,\n );\n return {\n container: settings.objectStorageBucket,\n accountName,\n accountKey,\n ...(endpointUrl ? { endpointUrl } : {}),\n };\n}\n\nfunction azureBlobManifestEndpoint(\n endpoint: string | undefined,\n accountName: string,\n): string | undefined {\n if (!endpoint) {\n return undefined;\n }\n const normalized = endpoint.replace(/\\/+$/, \"\");\n const standardAccountEndpoint = `https://${accountName}.blob.core.windows.net`;\n return normalized === standardAccountEndpoint ? undefined : normalized;\n}\n\nfunction parseAzureConnectionString(value: string): Record<string, string> {\n return Object.fromEntries(\n value\n .split(\";\")\n .map((part) => part.trim())\n .filter(Boolean)\n .map((part) => {\n const index = part.indexOf(\"=\");\n return index === -1 ? [part, \"\"] : [part.slice(0, index), part.slice(index + 1)];\n }),\n );\n}\n\nfunction normalizeManifestPath(path: string): string {\n return normalizeResourceMountPath(path);\n}\n\nfunction normalizeSandboxFileDownloads(downloads: SandboxFileDownload[]): SandboxFileDownload[] {\n return downloads.map((download) => {\n const mountPath = normalizeManifestPath(download.mountPath);\n assertSafeSandboxFilename(download.filename, download.fileId);\n if (!download.content && !download.url?.trim()) {\n throw new Error(\n `File download materialization requires content or a URL for ${download.fileId}`,\n );\n }\n return {\n ...download,\n mountPath,\n };\n });\n}\n\nfunction assertSafeSandboxFilename(filename: string, fileId: string): void {\n if (\n !filename ||\n filename.includes(\"/\") ||\n filename.includes(\"\\\\\") ||\n filename === \".\" ||\n filename === \"..\" ||\n filename.includes(\"..\")\n ) {\n throw new Error(`Invalid sandbox file name for ${fileId}: ${filename}`);\n }\n}\n\nfunction sandboxDownloadTargetPath(download: SandboxFileDownload): string {\n return posixPath.join(\"/workspace\", download.mountPath, download.filename);\n}\n\nfunction sandboxFileDownloadCommand(download: SandboxFileDownload, targetPath: string): string {\n if (!download.url) {\n throw new Error(`File download materialization URL is empty for ${download.fileId}`);\n }\n const targetDir = posixPath.dirname(targetPath);\n const tmpPath = `${targetPath}.opengeni-download-$$`;\n return [\n \"set +x\",\n \"set -eu\",\n `mkdir -p -- ${shellQuote(targetDir)}`,\n `if [ ! -f ${shellQuote(targetPath)} ]; then`,\n ` tmp=${shellQuote(tmpPath)}`,\n ' cleanup() { rm -f -- \"$tmp\"; }',\n \" trap cleanup EXIT\",\n ` curl --fail --location --silent --show-error --retry 3 --retry-delay 1 --output \"$tmp\" ${shellQuote(download.url)}`,\n ` mv -- \"$tmp\" ${shellQuote(targetPath)}`,\n \" trap - EXIT\",\n \"fi\",\n `chmod a-w -- ${shellQuote(targetPath)} 2>/dev/null || true`,\n ].join(\"\\n\");\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nexport type SandboxLifecycleHookPhase = \"beforeAgentStart\";\n\nexport type SandboxLifecycleCommandRunner = (\n session: TurnSandboxCommandSession,\n args: TurnSandboxCommandArgs,\n) => Promise<unknown>;\n\nexport type SandboxLifecycleHookContext = {\n environment: Record<string, string>;\n onRuntimeEvent?: (event: NormalizedRuntimeEvent) => Promise<void> | void;\n runAs?: string;\n // TOKEN-BROKER (B1): back-compat GitHub alias for gitTokenSeeds.github.\n gitTokenSeed?: string;\n // Provider tokens to seed into box token FILES before repository clone/setup\n // runs. Threaded OFF-MANIFEST — they ride ONLY the setup exec command prefix,\n // NEVER the box/agent manifest env (validateNoEnvironmentDelta must never see\n // rotating values).\n gitTokenSeeds?: GitTokenSeeds;\n gitCredentialBindings?: GitCredentialBindingSeed[];\n toolspaceTokenSeed?: string;\n toolspaceTokenFile?: string;\n // M3: the rig setup descriptor for the rig-setup hook (the script + marker\n // version id + the rig's own timeout). Present only on a rig-bound turn.\n rigSetup?: RigSetupDescriptor;\n commandRunner?: SandboxLifecycleCommandRunner;\n};\n\nasync function runSandboxLifecycleCommand(\n session: SandboxSessionLike,\n args: TurnSandboxCommandArgs,\n commandRunner?: SandboxLifecycleCommandRunner,\n): Promise<unknown> {\n if (commandRunner) {\n return await commandRunner(session as TurnSandboxCommandSession, args);\n }\n if (session.exec) return await session.exec(args);\n if (session.execCommand) return await session.execCommand(args);\n throw new Error(\"Sandbox session does not support command execution\");\n}\n\n// M3: everything the rig-setup hook needs to run the frozen rig version's setup\n// script exactly once per box. `versionId` keys the idempotence marker\n// (/var/opengeni/rig-setup-<versionId>.done); `timeoutMs` is the rig-specific\n// budget (settings.rigSetupTimeoutMs), NOT the 120s lifecycle default; `rigName`\n// is for human-readable events/errors only.\nexport type RigSetupDescriptor = {\n rigId: string;\n versionId: string;\n rigName: string;\n script: string;\n timeoutMs: number;\n};\n\nexport type SandboxLifecycleHook = {\n id: string;\n phase: SandboxLifecycleHookPhase;\n shouldRun?: (context: SandboxLifecycleHookContext) => boolean;\n run: (session: SandboxSessionLike, context: SandboxLifecycleHookContext) => Promise<void>;\n};\n\nconst builtInSandboxLifecycleHooks: Record<string, SandboxLifecycleHook> = {\n \"azure-cli-login\": {\n id: \"azure-cli-login\",\n phase: \"beforeAgentStart\",\n shouldRun: ({ environment }) => hasAzureServicePrincipal(environment),\n run: runAzureCliLoginHook,\n },\n};\n\nexport function sandboxLifecycleHooksForIds(ids: string[]): SandboxLifecycleHook[] {\n return ids.map((id) => {\n const hook = builtInSandboxLifecycleHooks[id];\n if (!hook) {\n throw new Error(`Unknown sandbox lifecycle hook ${id}`);\n }\n return hook;\n });\n}\n\nfunction applicableBeforeAgentStartHooks(\n hooks: SandboxLifecycleHook[],\n context: SandboxLifecycleHookContext,\n): SandboxLifecycleHook[] {\n return hooks.filter(\n (hook) => hook.phase === \"beforeAgentStart\" && (hook.shouldRun?.(context) ?? true),\n );\n}\n\n/**\n * Run the beforeAgentStart lifecycle hooks directly against an already-live box.\n *\n * The create/resume decoration (withSandboxLifecycleHooks) is structurally blind to\n * the PROVIDED-session path: when runStream hands the SDK a live `session`\n * (runOptions.sandbox.session — the lease-owned box resolved by the turn activity),\n * SandboxRuntimeManager uses it as-is and never calls client.create/resume, so a\n * wrapper around those methods never fires. Callers on that path invoke this\n * before starting the run so the box still gets its beforeAgentStart preparation\n * (repository clone + B1 askpass/token-file seed, azure-cli-login).\n */\nexport async function runBeforeAgentStartHooks(\n session: SandboxSessionLike,\n hooks: SandboxLifecycleHook[],\n context: SandboxLifecycleHookContext,\n): Promise<void> {\n for (const hook of applicableBeforeAgentStartHooks(hooks, context)) {\n await hook.run(session, context);\n }\n}\n\nexport function withSandboxLifecycleHooks(\n client: SandboxClient,\n hooks: SandboxLifecycleHook[],\n context: SandboxLifecycleHookContext,\n): SandboxClient {\n const beforeAgentStartHooks = applicableBeforeAgentStartHooks(hooks, context);\n if (beforeAgentStartHooks.length === 0) {\n return client;\n }\n const seen = new WeakSet<object>();\n const wrapSession = async <T extends SandboxSessionLike>(session: T): Promise<T> => {\n if (typeof session === \"object\" && session !== null && !seen.has(session)) {\n for (const hook of beforeAgentStartHooks) {\n await hook.run(session, context);\n }\n seen.add(session);\n }\n return session;\n };\n const wrapped: SandboxClient = {\n backendId: client.backendId,\n ...(client.supportsDefaultOptions !== undefined\n ? { supportsDefaultOptions: client.supportsDefaultOptions }\n : {}),\n ...(client.create\n ? {\n create: async (...args: any[]) =>\n await wrapSession(await (client.create as any)(...args)),\n }\n : {}),\n ...(client.resume\n ? {\n resume: async (state: SandboxSessionState) =>\n await wrapSession(await client.resume!(state)),\n }\n : {}),\n ...(client.delete\n ? {\n delete: async (state: SandboxSessionState) => await client.delete!(state),\n }\n : {}),\n ...(client.serializeSessionState\n ? {\n serializeSessionState: async (state: SandboxSessionState, options) =>\n await client.serializeSessionState!(state, options),\n }\n : {}),\n ...(client.canPersistOwnedSessionState\n ? {\n canPersistOwnedSessionState: async (state: SandboxSessionState) =>\n await client.canPersistOwnedSessionState!(state),\n }\n : {}),\n ...(client.canReusePreservedOwnedSession\n ? {\n canReusePreservedOwnedSession: async (state: SandboxSessionState) =>\n await client.canReusePreservedOwnedSession!(state),\n }\n : {}),\n ...(client.deserializeSessionState\n ? {\n deserializeSessionState: async (state: Record<string, unknown>) =>\n await client.deserializeSessionState!(state),\n }\n : {}),\n };\n return wrapped;\n}\n\nfunction sandboxRepositoryCloneHooksForAgent(agent: Agent<any, any>): SandboxLifecycleHook[] {\n return agentRepositoryCloneHooks.get(agent) ?? [];\n}\n\n// TOKEN-BROKER (B1): the per-turn git token seed stashed for this agent (undefined\n// when no repo is attached / on the selfhosted path). Read into the clone hook\n// context at runStream so the token is seeded off-manifest.\nfunction gitTokenSeedsForAgent(agent: Agent<any, any>): GitTokenSeeds | undefined {\n return agentGitTokenSeeds.get(agent);\n}\n\nfunction gitCredentialBindingsForAgent(\n agent: Agent<any, any>,\n): GitCredentialBindingSeed[] | undefined {\n return agentGitCredentialBindings.get(agent);\n}\n\nfunction toolspaceTokenSeedForAgent(agent: Agent<any, any>): string | undefined {\n return agentToolspaceTokenSeed.get(agent);\n}\n\nfunction toolspaceTokenSessionIdForAgent(agent: Agent<any, any>): string | undefined {\n return agentToolspaceTokenSessionId.get(agent);\n}\n\nfunction toolspaceTokenFileForAgent(\n agent: Agent<any, any>,\n environment: Readonly<Record<string, string>>,\n): string | undefined {\n if (!toolspaceTokenSeedForAgent(agent)) return undefined;\n const sessionId = toolspaceTokenSessionIdForAgent(agent);\n if (!sessionId) {\n throw new Error(\"Toolspace token seed is missing its session identity\");\n }\n return toolspaceTokenFileFromEnvironment(environment, sessionId);\n}\n\nfunction sandboxToolspaceTokenHooksForAgent(agent: Agent<any, any>): SandboxLifecycleHook[] {\n return toolspaceTokenSeedForAgent(agent)\n ? [\n {\n id: \"toolspace-token\",\n phase: \"beforeAgentStart\",\n run: runToolspaceTokenSeedHook,\n },\n ]\n : [];\n}\n\n// M3: the rig-setup hook for this agent (present only on a rig-bound turn whose\n// frozen version carries a non-empty setup script). It runs FIRST among the\n// owned beforeAgentStart hooks so any tooling it installs is available to the\n// repository-clone / credential hooks that follow. The descriptor is threaded\n// through the hook context (rigSetupHookContext) so runRigSetupHook reads it.\nfunction sandboxRigSetupHooksForAgent(agent: Agent<any, any>): SandboxLifecycleHook[] {\n return agentRigSetup.get(agent)\n ? [\n {\n id: \"rig-setup\",\n phase: \"beforeAgentStart\",\n run: runRigSetupHook,\n },\n ]\n : [];\n}\n\nfunction rigSetupDescriptorForAgent(agent: Agent<any, any>): RigSetupDescriptor | undefined {\n return agentRigSetup.get(agent);\n}\n\n// M3: the rig version's credential hooks (already resolved + validated at build\n// time). Unioned with the deployment preparation-profile hooks by the caller.\nfunction rigCredentialHooksForAgent(agent: Agent<any, any>): SandboxLifecycleHook[] {\n return agentRigCredentialHooks.get(agent) ?? [];\n}\n\n// M3: union the deployment preparation-profile hooks with the rig version's\n// credential hooks, deduped by id (a hook named by BOTH the deployment profile\n// and the rig runs once). Deployment hooks keep their leading position.\nfunction unionCredentialHooks(\n deploymentHooks: SandboxLifecycleHook[],\n rigHooks: SandboxLifecycleHook[],\n): SandboxLifecycleHook[] {\n if (rigHooks.length === 0) {\n return deploymentHooks;\n }\n const seen = new Set(deploymentHooks.map((hook) => hook.id));\n return [...deploymentHooks, ...rigHooks.filter((hook) => !seen.has(hook.id))];\n}\n\nfunction gitCredentialSessionRegistrationHooks(\n callback: RunAgentStreamOptions[\"onGitCredentialSessionReady\"],\n): SandboxLifecycleHook[] {\n return callback\n ? [\n {\n id: \"git-credential-renewal-registration\",\n phase: \"beforeAgentStart\",\n run: async (session) => {\n await callback(session);\n },\n },\n ]\n : [];\n}\n\nfunction toolspaceTokenSessionRegistrationHooks(\n callback: RunAgentStreamOptions[\"onToolspaceTokenSessionReady\"],\n): SandboxLifecycleHook[] {\n return callback\n ? [\n {\n id: \"toolspace-token-renewal-registration\",\n phase: \"beforeAgentStart\",\n run: async (session) => {\n await callback(session);\n },\n },\n ]\n : [];\n}\n\nfunction sandboxRepositoryCloneHooks(\n settings: Settings,\n resources: ResourceRef[],\n activeSandboxBackend: Settings[\"sandboxBackend\"] = settings.sandboxBackend,\n): SandboxLifecycleHook[] {\n const repositories = resources.filter(\n (resource): resource is Extract<ResourceRef, { kind: \"repository\" }> =>\n resource.kind === \"repository\" &&\n repositoryUsesSandboxClone(settings, resource, activeSandboxBackend),\n );\n if (repositories.length === 0) {\n return [];\n }\n return [\n {\n id: \"repository-clone\",\n phase: \"beforeAgentStart\",\n run: async (session, context) => {\n await runRepositoryCloneHook(session, repositories, context);\n },\n },\n ];\n}\n\n/**\n * Whether the platform should seed a repository resource by `git clone` inside\n * the sandbox before the agent starts.\n *\n * SAFETY GATE (selfhosted/bring-your-own machine): the clone hook writes into\n * `posixPath.join(\"/workspace\", mountPath)`, which a selfhosted agent rewrites\n * to a path under its REAL launch directory — so a platform-initiated clone\n * lands on the user's actual disk. A connected machine already owns its\n * filesystem; the platform must NEVER clone onto it. We therefore key the\n * decision off the EFFECTIVE/active backend, not just the session's HOME backend\n * (`settings.sandboxBackend`): a session can run on the cloud default while its\n * active sandbox has been swapped to a connected machine (active_sandbox_id → a\n * selfhosted lease), in which case the agent actually executes on the user's\n * machine even though the home backend is e.g. \"modal\". `activeSandboxBackend`\n * defaults to the home backend, so a session whose HOME backend is \"selfhosted\"\n * is gated with no caller change, and every cloud path is byte-for-byte\n * unchanged.\n */\nexport function repositoryUsesSandboxClone(\n settings: Settings,\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n activeSandboxBackend: Settings[\"sandboxBackend\"] = settings.sandboxBackend,\n): boolean {\n if (activeSandboxBackend === \"selfhosted\") {\n return false;\n }\n return (\n settings.sandboxBackend === \"modal\" ||\n Boolean(resource.githubInstallationId && resource.githubRepositoryId) ||\n Boolean(resource.provider)\n );\n}\n\nconst GIT_CREDENTIAL_PROVIDERS = [\n \"github\",\n \"gitlab\",\n \"azure_devops\",\n] as const satisfies readonly GitCredentialProvider[];\n\nfunction gitProviderSeedEnv(provider: GitCredentialProvider): string {\n return `OPENGENI_GIT_${provider.toUpperCase()}_TOKEN_SEED`;\n}\n\nexport function gitCredentialBindingHash(credentialBindingId: string): string {\n return createHash(\"sha256\").update(credentialBindingId, \"utf8\").digest(\"hex\").slice(0, 32);\n}\n\nfunction gitBindingSeedEnv(binding: GitCredentialBindingSeed): string {\n return `OPENGENI_GIT_BINDING_${gitCredentialBindingHash(binding.credentialBindingId).toUpperCase()}_TOKEN_SEED`;\n}\n\nfunction gitCredentialBindingSeedExportPrefix(bindings: GitCredentialBindingSeed[]): string {\n return bindings\n .map((binding) => `export ${gitBindingSeedEnv(binding)}=${shellQuote(binding.token)}`)\n .join(\"\\n\");\n}\n\nfunction gitTokenSeedExportPrefix(seeds: GitTokenSeeds): string {\n const lines: string[] = [];\n for (const provider of GIT_CREDENTIAL_PROVIDERS) {\n const token = seeds[provider];\n if (!token) {\n continue;\n }\n lines.push(`export ${gitProviderSeedEnv(provider)}=${shellQuote(token)}`);\n if (provider === \"github\") {\n lines.push(`export OPENGENI_GIT_TOKEN_SEED=${shellQuote(token)}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\ntype RuntimeGitBindingDescriptor = {\n provider: GitCredentialProvider;\n credentialBindingId: string;\n bindingHash: string;\n protocol: string;\n host: string;\n path: string;\n uri: string;\n mountPath: string;\n};\n\ntype RuntimeGitHttpBrokerRouteDescriptor = {\n provider: GitCredentialProvider;\n credentialBindingId: string;\n bindingHash: string;\n repositoryUri: string;\n brokerUri: string;\n protocol: \"https\";\n host: string;\n path: string;\n};\n\nfunction runtimeGitBindingDescriptors(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n): RuntimeGitBindingDescriptor[] {\n const remoteBindings = new Map<string, string>();\n const bindingProviders = new Map<string, GitCredentialProvider>();\n return resources.map((resource) => {\n const url = new URL(resource.uri);\n const credentialProvider = gitCredentialProviderForRepository(resource);\n // Provider-less public/legacy resources retain the historical GitHub\n // askpass fallback, but credential-bound resources derive through the\n // shared contracts helper used by the worker and core.\n const provider = credentialProvider ?? \"github\";\n const credentialBindingId =\n gitCredentialBindingIdForRepository(resource, credentialProvider) ?? provider;\n const path = url.pathname.replace(/^\\/+|\\/+$/g, \"\");\n const remote = `${url.protocol.toLowerCase()}//${url.host.toLowerCase()}/${path.replace(/\\.git$/, \"\")}`;\n const bindingKey = `${provider}\\u0000${credentialBindingId}`;\n const boundProvider = bindingProviders.get(credentialBindingId);\n if (boundProvider && boundProvider !== provider) {\n throw new Error(\n `credential binding ${credentialBindingId} is assigned to multiple Git providers`,\n );\n }\n bindingProviders.set(credentialBindingId, provider);\n const claimed = remoteBindings.get(remote);\n if (claimed && claimed !== bindingKey) {\n throw new Error(\n `repository remote ${resource.uri} is claimed by multiple credential bindings`,\n );\n }\n remoteBindings.set(remote, bindingKey);\n return {\n provider,\n credentialBindingId,\n bindingHash: gitCredentialBindingHash(credentialBindingId),\n protocol: url.protocol.replace(/:$/, \"\").toLowerCase(),\n host: url.host.toLowerCase(),\n path,\n uri: resource.uri,\n mountPath: `/workspace/${resourceMountPath(resource)}`,\n };\n });\n}\n\nfunction gitCredentialBindingInventoryCommandLines(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n bindings: GitCredentialBindingSeed[],\n): string[] {\n type GitBindingInventoryTransport = \"direct_token\" | \"git_http_broker\";\n type GitBindingInventoryEntry = {\n credentialBindingId: string;\n provider: GitCredentialProvider;\n transport: GitBindingInventoryTransport;\n repositories: Array<{ uri: string; mountPath: string }>;\n };\n const bindingTransports = new Map<string, GitBindingInventoryTransport>(\n bindings.map((binding) => [\n gitCredentialBindingKey(binding.provider, binding.credentialBindingId),\n binding.transport?.kind === \"http_broker\" ? \"git_http_broker\" : \"direct_token\",\n ]),\n );\n const entries = new Map<string, GitBindingInventoryEntry>();\n for (const descriptor of runtimeGitBindingDescriptors(resources)) {\n const key = gitCredentialBindingKey(descriptor.provider, descriptor.credentialBindingId);\n const transport = bindingTransports.get(key);\n if (!transport) continue;\n const entry: GitBindingInventoryEntry = entries.get(key) ?? {\n credentialBindingId: descriptor.credentialBindingId,\n provider: descriptor.provider,\n transport,\n repositories: [],\n };\n entry.repositories.push({ uri: descriptor.uri, mountPath: descriptor.mountPath });\n entries.set(key, entry);\n }\n const inventory = `${JSON.stringify(\n {\n version: 1,\n bindings: [...entries.values()],\n },\n null,\n 2,\n )}\\n`;\n return [\n 'git_binding_inventory=\"${OPENGENI_GIT_BINDINGS_FILE:-$HOME/.opengeni/git-bindings.json}\"',\n 'mkdir -p \"$(dirname \"$git_binding_inventory\")\"',\n 'inventory_umask=\"$(umask)\"',\n \"umask 077\",\n `printf '%s' ${shellQuote(inventory)} > \"$git_binding_inventory.tmp.$$\"`,\n 'mv -f \"$git_binding_inventory.tmp.$$\" \"$git_binding_inventory\"',\n 'umask \"$inventory_umask\"',\n ];\n}\n\nfunction gitCredentialBindingKey(\n provider: GitCredentialProvider,\n credentialBindingId: string,\n): string {\n return `${provider}\\u0000${credentialBindingId}`;\n}\n\nfunction brokeredGitCredentialBindingKeys(\n bindings: GitCredentialBindingSeed[],\n): ReadonlySet<string> {\n return new Set(\n bindings\n .filter((binding) => binding.transport?.kind === \"http_broker\")\n .map((binding) => gitCredentialBindingKey(binding.provider, binding.credentialBindingId)),\n );\n}\n\nfunction runtimeGitHttpBrokerRouteDescriptors(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n bindings: GitCredentialBindingSeed[],\n): RuntimeGitHttpBrokerRouteDescriptor[] {\n const resourceDescriptors = runtimeGitBindingDescriptors(resources);\n const byBindingAndUri = new Map<string, RuntimeGitBindingDescriptor>();\n for (const descriptor of resourceDescriptors) {\n byBindingAndUri.set(\n `${gitCredentialBindingKey(descriptor.provider, descriptor.credentialBindingId)}\\u0000${descriptor.uri}`,\n descriptor,\n );\n }\n\n const routes: RuntimeGitHttpBrokerRouteDescriptor[] = [];\n const claimedRepositoryUris = new Set<string>();\n const claimedBrokerUris = new Set<string>();\n for (const binding of bindings) {\n if (!binding.transport) continue;\n if (\n typeof binding.transport !== \"object\" ||\n binding.transport.kind !== \"http_broker\" ||\n !Array.isArray(binding.transport.repositories)\n ) {\n throw new Error(\n `Git credential binding ${binding.credentialBindingId} uses an unsupported transport`,\n );\n }\n const bindingKey = gitCredentialBindingKey(binding.provider, binding.credentialBindingId);\n const expected = resourceDescriptors.filter(\n (descriptor) =>\n gitCredentialBindingKey(descriptor.provider, descriptor.credentialBindingId) === bindingKey,\n );\n if (expected.length === 0 || binding.transport.repositories.length !== expected.length) {\n throw new Error(\n `Git HTTP broker binding ${binding.credentialBindingId} does not cover its exact repository set`,\n );\n }\n for (const route of binding.transport.repositories) {\n if (\n !route ||\n typeof route !== \"object\" ||\n typeof route.repositoryUri !== \"string\" ||\n typeof route.brokerUri !== \"string\"\n ) {\n throw new Error(\n `Git HTTP broker binding ${binding.credentialBindingId} contains an invalid repository route`,\n );\n }\n const descriptor = byBindingAndUri.get(`${bindingKey}\\u0000${route.repositoryUri}`);\n if (!descriptor || claimedRepositoryUris.has(route.repositoryUri)) {\n throw new Error(\n `Git HTTP broker binding ${binding.credentialBindingId} contains an unexpected repository route`,\n );\n }\n let brokerUrl: URL;\n try {\n brokerUrl = new URL(route.brokerUri);\n } catch {\n throw new Error(\n `Git HTTP broker binding ${binding.credentialBindingId} contains an invalid broker URI`,\n );\n }\n if (\n brokerUrl.protocol !== \"https:\" ||\n brokerUrl.username ||\n brokerUrl.password ||\n brokerUrl.search ||\n brokerUrl.hash ||\n brokerUrl.href !== route.brokerUri ||\n claimedBrokerUris.has(brokerUrl.href)\n ) {\n throw new Error(\n `Git HTTP broker binding ${binding.credentialBindingId} contains an unsafe broker URI`,\n );\n }\n claimedRepositoryUris.add(route.repositoryUri);\n claimedBrokerUris.add(brokerUrl.href);\n routes.push({\n provider: binding.provider,\n credentialBindingId: binding.credentialBindingId,\n bindingHash: gitCredentialBindingHash(binding.credentialBindingId),\n repositoryUri: route.repositoryUri,\n brokerUri: route.brokerUri,\n protocol: \"https\",\n host: brokerUrl.host.toLowerCase(),\n path: brokerUrl.pathname.replace(/^\\/+|\\/+$/g, \"\"),\n });\n }\n }\n return routes;\n}\n\nfunction gitUsernameForProvider(provider: GitCredentialProvider): string {\n if (provider === \"github\") return \"x-access-token\";\n if (provider === \"gitlab\") return \"oauth2\";\n return \"opengeni\";\n}\n\nfunction gitCredentialHelperBindingCaseLines(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n bindings: GitCredentialBindingSeed[],\n): string[] {\n const brokeredBindings = brokeredGitCredentialBindingKeys(bindings);\n return runtimeGitBindingDescriptors(resources)\n .filter(\n (descriptor) =>\n !brokeredBindings.has(\n gitCredentialBindingKey(descriptor.provider, descriptor.credentialBindingId),\n ),\n )\n .flatMap((descriptor) => {\n const paths = new Set([\n descriptor.path,\n descriptor.path.replace(/\\.git$/, \"\"),\n `${descriptor.path.replace(/\\.git$/, \"\")}.git`,\n ]);\n return [...paths].map(\n (path) =>\n ` ${shellQuote(`${descriptor.protocol}|${descriptor.host}|${path}`)}) username=${shellQuote(gitUsernameForProvider(descriptor.provider))}; token_file=\"$credential_dir/${descriptor.bindingHash}-token\" ;;`,\n );\n });\n}\n\nfunction gitCredentialHelperBrokerCaseLines(\n routes: RuntimeGitHttpBrokerRouteDescriptor[],\n): string[] {\n return routes.flatMap((route) => {\n const paths = new Set([\n route.path,\n route.path.replace(/\\.git$/, \"\"),\n `${route.path.replace(/\\.git$/, \"\")}.git`,\n ]);\n return [...paths].map(\n (path) =>\n ` ${shellQuote(`${route.protocol}|${route.host}|${path}`)}) username=opengeni; token_file=\"$credential_dir/${route.bindingHash}-token\" ;;`,\n );\n });\n}\n\nfunction gitAskpassHostProviderCaseLines(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n brokerRoutes: RuntimeGitHttpBrokerRouteDescriptor[],\n): string[] {\n const hosts = new Map<string, { provider: GitCredentialProvider; bindings: Set<string> }>();\n for (const descriptor of runtimeGitBindingDescriptors(resources)) {\n const entry = hosts.get(descriptor.host) ?? {\n provider: descriptor.provider,\n bindings: new Set<string>(),\n };\n entry.bindings.add(`${descriptor.provider}\\u0000${descriptor.credentialBindingId}`);\n hosts.set(descriptor.host, entry);\n }\n const brokerHosts = [...new Set(brokerRoutes.map((route) => route.host))]\n .sort((a, b) => a.localeCompare(b))\n .map((hostname) => ` ${shellQuote(hostname)}) printf '\\\\n'; return 0 ;;`);\n return [\n ...brokerHosts,\n ...[...hosts.entries()]\n .filter(([, entry]) => entry.bindings.size === 1)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(\n ([hostname, entry]) =>\n ` ${shellQuote(hostname)}) printf '%s\\\\n' ${entry.provider}; return 0 ;;`,\n ),\n ];\n}\n\nfunction gitCredentialTokenWriterCommandLines(bindings: GitCredentialBindingSeed[] = []): string[] {\n const bindingWrites = bindings.flatMap((binding) => {\n const hash = gitCredentialBindingHash(binding.credentialBindingId);\n const seedEnv = gitBindingSeedEnv(binding);\n const count = Math.max(1, binding.providerBindingCount ?? 1);\n const provider = binding.provider;\n const lines = [`write_git_binding_token ${shellQuote(hash)} \"\\${${seedEnv}:-}\"`];\n if (count === 1 && binding.transport?.kind !== \"http_broker\") {\n lines.push(`write_git_provider_token ${shellQuote(provider)} \"\\${${seedEnv}:-}\"`);\n } else {\n lines.push(`remove_git_provider_token ${shellQuote(provider)}`);\n }\n return lines;\n });\n return [\n // TOKEN-BROKER (B1/B2): seed run-scoped provider tokens into stable files and\n // atomically replace each provider file. Token VALUES are supplied only by\n // the per-exec command prefix\n // (OPENGENI_GIT_*_TOKEN_SEED), never by the box/agent manifest. Helper paths\n // are stable manifest values from @opengeni/config.\n \"git_provider_token_file() {\",\n ' provider=\"$1\"',\n ' case \"$provider\" in',\n \" github) printf '%s\\\\n' \\\"${OPENGENI_GIT_TOKEN_FILE:-$HOME/.opengeni/git-token}\\\" ;;\",\n \" *) printf '%s\\\\n' \\\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/$provider-token\\\" ;;\",\n \" esac\",\n \"}\",\n \"write_git_binding_token() {\",\n ' binding_hash=\"$1\"',\n ' token=\"$2\"',\n ' [ -n \"$token\" ] || return 0',\n ' credential_dir=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}\"',\n ' mkdir -p \"$credential_dir\"',\n ' token_file=\"$credential_dir/$binding_hash-token\"',\n ' printf \\'%s\\' \"$token\" > \"$token_file.tmp.$$\"',\n ' mv -f \"$token_file.tmp.$$\" \"$token_file\"',\n \"}\",\n \"remove_git_provider_token() {\",\n ' provider=\"$1\"',\n ' rm -f \"$(git_provider_token_file \"$provider\")\"',\n ' if [ \"$provider\" = github ]; then',\n ' rm -f \"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/github-token\"',\n \" fi\",\n \"}\",\n \"write_git_provider_token() {\",\n ' provider=\"$1\"',\n ' token=\"$2\"',\n ' [ -n \"$token\" ] || return 0',\n ' token_file=\"$(git_provider_token_file \"$provider\")\"',\n ' mkdir -p \"$(dirname \"$token_file\")\"',\n ' printf \\'%s\\' \"$token\" > \"$token_file.tmp.$$\"',\n ' mv -f \"$token_file.tmp.$$\" \"$token_file\"',\n ' if [ \"$provider\" = github ]; then',\n ' credential_dir=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}\"',\n ' mkdir -p \"$credential_dir\"',\n ' printf \\'%s\\' \"$token\" > \"$credential_dir/github-token.tmp.$$\"',\n ' mv -f \"$credential_dir/github-token.tmp.$$\" \"$credential_dir/github-token\"',\n \" fi\",\n \"}\",\n 'seed_umask=\"$(umask)\"',\n \"umask 077\",\n 'write_git_provider_token github \"${OPENGENI_GIT_GITHUB_TOKEN_SEED:-${OPENGENI_GIT_TOKEN_SEED:-}}\"',\n 'write_git_provider_token gitlab \"${OPENGENI_GIT_GITLAB_TOKEN_SEED:-}\"',\n 'write_git_provider_token azure_devops \"${OPENGENI_GIT_AZURE_DEVOPS_TOKEN_SEED:-}\"',\n ...bindingWrites,\n 'umask \"$seed_umask\"',\n ];\n}\n\nfunction gitHttpBrokerConfigCommandLines(routes: RuntimeGitHttpBrokerRouteDescriptor[]): string[] {\n return [\n 'git_http_broker_config=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/http-broker.gitconfig\"',\n 'mkdir -p \"$(dirname \"$git_http_broker_config\")\"',\n 'broker_umask=\"$(umask)\"',\n \"umask 077\",\n ': > \"$git_http_broker_config.tmp.$$\"',\n ...routes.map(\n (route) =>\n `git config --file \"$git_http_broker_config.tmp.$$\" --add ${shellQuote(`url.${route.brokerUri}.insteadOf`)} ${shellQuote(route.repositoryUri)}`,\n ),\n 'mv -f \"$git_http_broker_config.tmp.$$\" \"$git_http_broker_config\"',\n 'umask \"$broker_umask\"',\n 'git config --global --unset-all include.path \"$git_http_broker_config\" >/dev/null 2>&1 || true',\n 'git config --global --add include.path \"$git_http_broker_config\"',\n ];\n}\n\nfunction gitCredentialHelperCommandLines(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[] = [],\n bindings: GitCredentialBindingSeed[] = [],\n): string[] {\n const brokerRoutes = runtimeGitHttpBrokerRouteDescriptors(resources, bindings);\n const hostProviderCases = gitAskpassHostProviderCaseLines(resources, brokerRoutes);\n const bindingCases = [\n ...gitCredentialHelperBindingCaseLines(resources, bindings),\n ...gitCredentialHelperBrokerCaseLines(brokerRoutes),\n ];\n const descriptors = runtimeGitBindingDescriptors(resources);\n const brokeredBindings = brokeredGitCredentialBindingKeys(bindings);\n const wrapperDescriptors =\n bindings.length > 0\n ? descriptors.filter(\n (descriptor) =>\n !brokeredBindings.has(\n gitCredentialBindingKey(descriptor.provider, descriptor.credentialBindingId),\n ),\n )\n : [];\n const bindingProviders = new Map<GitCredentialProvider, Set<string>>();\n for (const descriptor of runtimeGitBindingDescriptors(resources)) {\n const ids = bindingProviders.get(descriptor.provider) ?? new Set<string>();\n ids.add(descriptor.credentialBindingId);\n bindingProviders.set(descriptor.provider, ids);\n }\n const strictAskpass = [...bindingProviders.values()].some((ids) => ids.size > 1);\n const allowedWrapperHashes = [\n ...new Set(wrapperDescriptors.map((item) => `${item.provider}|${item.bindingHash}`)),\n ].map((key) => ` ${shellQuote(key)}) return 0 ;;`);\n const originWrapperHashes = wrapperDescriptors.flatMap((item) => {\n const base = item.uri.replace(/\\.git$/, \"\");\n return [...new Set([item.uri, base, `${base}.git`])].map(\n (uri) =>\n ` ${shellQuote(`${item.provider}|${uri}`)}) printf '%s\\\\n' ${shellQuote(item.bindingHash)}; return 0 ;;`,\n );\n });\n const soleWrapperHashes = [...bindingProviders.entries()].flatMap(([provider, ids]) => {\n if (ids.size !== 1) return [];\n const descriptor = wrapperDescriptors.find((item) => item.provider === provider);\n return descriptor\n ? [\n ` ${shellQuote(provider)}) printf '%s\\\\n' ${shellQuote(descriptor.bindingHash)}; return 0 ;;`,\n ]\n : [];\n });\n const multiWrapperProviders =\n bindings.length > 0\n ? [...bindingProviders.entries()]\n .filter(([, ids]) => ids.size > 1)\n .map(([provider]) => provider)\n : [];\n const brokeredOriginCases = brokerRoutes.flatMap((route) => {\n const base = route.repositoryUri.replace(/\\.git$/, \"\");\n return [...new Set([route.repositoryUri, base, `${base}.git`])].map(\n (uri) => ` ${shellQuote(`${route.provider}|${uri}`)}) return 0 ;;`,\n );\n });\n const brokeredBindingHashCases = bindings\n .filter((binding) => binding.transport?.kind === \"http_broker\")\n .map(\n (binding) =>\n ` ${shellQuote(`${binding.provider}|${gitCredentialBindingHash(binding.credentialBindingId)}`)}) return 0 ;;`,\n );\n const providerBindingKinds = new Map<\n GitCredentialProvider,\n { direct: number; brokered: number }\n >();\n for (const binding of bindings) {\n const counts = providerBindingKinds.get(binding.provider) ?? { direct: 0, brokered: 0 };\n if (binding.transport?.kind === \"http_broker\") counts.brokered += 1;\n else counts.direct += 1;\n providerBindingKinds.set(binding.provider, counts);\n }\n const brokerOnlyProviders = [...providerBindingKinds.entries()]\n .filter(([, counts]) => counts.brokered > 0 && counts.direct === 0)\n .map(([provider]) => provider);\n return [\n ...gitCredentialTokenWriterCommandLines(bindings),\n ...gitCredentialBindingInventoryCommandLines(resources, bindings),\n // Provision git/provider-CLI helpers at SETUP (runtime) before any clone\n // runs. Renewal updates only token files and deliberately leaves these\n // repository-specific host mappings intact.\n 'git_askpass=\"${GIT_ASKPASS:-$HOME/.opengeni/askpass}\"',\n 'mkdir -p \"$(dirname \"$git_askpass\")\"',\n \"cat > \\\"$git_askpass.tmp.$$\\\" <<'ASKPASS_EOF'\",\n \"#!/usr/bin/env sh\",\n \"prompt_host() {\",\n \" prompt_lower=\\\"$(printf '%s\\\\n' \\\"$1\\\" | tr '[:upper:]' '[:lower:]')\\\"\",\n ' case \"$prompt_lower\" in',\n \" *://*) ;;\",\n \" *) printf '\\\\n'; return 0 ;;\",\n \" esac\",\n ' rest=\"${prompt_lower#*://}\"',\n ' rest=\"${rest#*@}\"',\n ' host=\"${rest%%/*}\"',\n ' host=\"$(printf \\'%s\\\\n\\' \"$host\" | tr -d \"\\'\")\"',\n ' host=\"${host%:}\"',\n \" printf '%s\\\\n' \\\"$host\\\"\",\n \"}\",\n \"provider_for_prompt() {\",\n ' host=\"$(prompt_host \"$1\")\"',\n ' case \"$host\" in',\n ...(hostProviderCases.length > 0 ? hostProviderCases : [' \"\") : ;;']),\n \" esac\",\n \" case \\\"$(printf '%s\\\\n' \\\"$1\\\" | tr '[:upper:]' '[:lower:]')\\\" in\",\n \" *github.com*|*githubusercontent.com*) printf '%s\\\\n' github ;;\",\n \" *gitlab*) printf '%s\\\\n' gitlab ;;\",\n \" *dev.azure.com*|*.visualstudio.com*) printf '%s\\\\n' azure_devops ;;\",\n strictAskpass ? \" *) printf '\\\\n' ;;\" : \" *) printf '%s\\\\n' github ;;\",\n \" esac\",\n \"}\",\n \"token_file_for_provider() {\",\n ' case \"$1\" in',\n \" github) printf '%s\\\\n' \\\"${OPENGENI_GIT_TOKEN_FILE:-$HOME/.opengeni/git-token}\\\" ;;\",\n \" *) printf '%s\\\\n' \\\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/$1-token\\\" ;;\",\n \" esac\",\n \"}\",\n \"username_for_provider() {\",\n ' case \"$1\" in',\n \" github) printf '%s\\\\n' \\\"x-access-token\\\" ;;\",\n \" gitlab) printf '%s\\\\n' \\\"oauth2\\\" ;;\",\n \" azure_devops) printf '%s\\\\n' \\\"opengeni\\\" ;;\",\n \" *) printf '\\\\n' ;;\",\n \" esac\",\n \"}\",\n 'provider=\"$(provider_for_prompt \"$1\")\"',\n 'case \"$1\" in',\n ' *Username*) username_for_provider \"$provider\" ;;',\n ' *Password*) cat \"$(token_file_for_provider \"$provider\")\" 2>/dev/null || printf \\'\\\\n\\' ;;',\n \" *) printf '\\\\n' ;;\",\n \"esac\",\n \"ASKPASS_EOF\",\n 'chmod 0755 \"$git_askpass.tmp.$$\"',\n 'mv -f \"$git_askpass.tmp.$$\" \"$git_askpass\"',\n 'git_credential_helper=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/helper\"',\n 'mkdir -p \"$(dirname \"$git_credential_helper\")\"',\n \"cat > \\\"$git_credential_helper.tmp.$$\\\" <<'GIT_CREDENTIAL_HELPER_EOF'\",\n \"#!/usr/bin/env sh\",\n \"set -eu\",\n '[ \"${1:-get}\" = get ] || exit 0',\n \"protocol= host= path=\",\n \"while IFS='=' read -r key value; do\",\n ' case \"$key\" in',\n \" protocol) protocol=\\\"$(printf '%s' \\\"$value\\\" | tr '[:upper:]' '[:lower:]')\\\" ;;\",\n \" host) host=\\\"$(printf '%s' \\\"$value\\\" | tr '[:upper:]' '[:lower:]')\\\" ;;\",\n ' path) path=\"${value#/}\" ;;',\n \" esac\",\n \"done\",\n 'credential_dir=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}\"',\n \"username= token_file=\",\n 'case \"$protocol|$host|$path\" in',\n ...bindingCases,\n \" *) exit 0 ;;\",\n \"esac\",\n '[ -r \"$token_file\" ] || exit 0',\n 'password=\"$(cat \"$token_file\" 2>/dev/null || true)\"',\n '[ -n \"$password\" ] || exit 0',\n 'printf \\'username=%s\\\\npassword=%s\\\\n\\' \"$username\" \"$password\"',\n \"GIT_CREDENTIAL_HELPER_EOF\",\n 'chmod 0755 \"$git_credential_helper.tmp.$$\"',\n 'mv -f \"$git_credential_helper.tmp.$$\" \"$git_credential_helper\"',\n // Empty helper resets lower-priority/system helpers; our exact path-aware\n // helper returns no credential for an unbound remote, so multi-binding\n // sessions fail closed instead of falling through to ambient credentials.\n \"git config --global --unset-all credential.helper >/dev/null 2>&1 || true\",\n \"git config --global --add credential.helper ''\",\n 'git config --global --add credential.helper \"$git_credential_helper\"',\n \"git config --global credential.useHttpPath true\",\n ...gitHttpBrokerConfigCommandLines(brokerRoutes),\n 'wrapper_dir=\"${OPENGENI_GIT_CLI_WRAPPER_DIR:-$HOME/.opengeni/bin}\"',\n 'mkdir -p \"$wrapper_dir\"',\n \"for opengeni_git_cli_tool in gh glab az; do\",\n ' wrapper=\"$wrapper_dir/$opengeni_git_cli_tool\"',\n \" cat > \\\"$wrapper.tmp.$$\\\" <<'CLI_WRAPPER_EOF'\",\n \"#!/usr/bin/env sh\",\n \"set -eu\",\n 'tool=\"${0##*/}\"',\n 'case \"$tool\" in',\n \" gh) provider=github; token_env=GH_TOKEN ;;\",\n \" glab) provider=gitlab; token_env=GITLAB_TOKEN ;;\",\n \" az) provider=azure_devops; token_env=AZURE_DEVOPS_EXT_PAT ;;\",\n \" *) provider=; token_env= ;;\",\n \"esac\",\n \"hash_binding_id() {\",\n \" if command -v sha256sum >/dev/null 2>&1; then printf '%s' \\\"$1\\\" | sha256sum | cut -c1-32; return; fi\",\n \" if command -v shasum >/dev/null 2>&1; then printf '%s' \\\"$1\\\" | shasum -a 256 | cut -c1-32; return; fi\",\n \" if command -v openssl >/dev/null 2>&1; then printf '%s' \\\"$1\\\" | openssl dgst -sha256 | sed 's/^.*= //' | cut -c1-32; return; fi\",\n \" printf '%s\\\\n' 'No SHA-256 utility is available to select OPENGENI_GIT_BINDING' >&2\",\n \" return 127\",\n \"}\",\n \"binding_hash_allowed() {\",\n ' case \"$provider|$1\" in',\n ...allowedWrapperHashes,\n \" *) return 1 ;;\",\n \" esac\",\n \"}\",\n \"binding_hash_is_brokered() {\",\n ' case \"$provider|$1\" in',\n ...brokeredBindingHashCases,\n \" *) return 1 ;;\",\n \" esac\",\n \"}\",\n \"binding_hash_for_origin() {\",\n ' case \"$provider|$1\" in',\n ...originWrapperHashes,\n \" *) return 1 ;;\",\n \" esac\",\n \"}\",\n \"origin_is_brokered() {\",\n ' case \"$provider|$1\" in',\n ...brokeredOriginCases,\n \" *) return 1 ;;\",\n \" esac\",\n \"}\",\n \"sole_binding_hash() {\",\n ' case \"$provider\" in',\n ...soleWrapperHashes,\n \" *) return 1 ;;\",\n \" esac\",\n \"}\",\n `multi_binding_providers=${shellQuote(multiWrapperProviders.join(\" \"))}`,\n `broker_only_providers=${shellQuote(brokerOnlyProviders.join(\" \"))}`,\n 'if [ -n \"$provider\" ]; then',\n \" binding_hash=\",\n ' if [ -n \"${OPENGENI_GIT_BINDING:-}\" ]; then',\n ' binding_hash=\"$(hash_binding_id \"$OPENGENI_GIT_BINDING\")\"',\n ' binding_hash_is_brokered \"$binding_hash\" && { printf \\'%s\\\\n\\' \"$tool provider API authentication is host-brokered for OPENGENI_GIT_BINDING; use the configured provider MCP tools\" >&2; exit 2; }',\n ' binding_hash_allowed \"$binding_hash\" || { printf \\'%s\\\\n\\' \"OPENGENI_GIT_BINDING does not select a $provider credential attached to this session\" >&2; exit 2; }',\n \" elif command -v git >/dev/null 2>&1; then\",\n ' origin=\"$(git config --get remote.origin.url 2>/dev/null || true)\"',\n ' [ -z \"$origin\" ] || ! origin_is_brokered \"$origin\" || { printf \\'%s\\\\n\\' \"$tool provider API authentication is host-brokered for this repository; use the configured provider MCP tools\" >&2; exit 2; }',\n ' [ -z \"$origin\" ] || binding_hash=\"$(binding_hash_for_origin \"$origin\" 2>/dev/null || true)\"',\n \" fi\",\n ' [ -n \"$binding_hash\" ] || binding_hash=\"$(sole_binding_hash 2>/dev/null || true)\"',\n ' if [ -n \"$binding_hash\" ]; then',\n ' token_file=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/$binding_hash-token\"',\n \" else\",\n ' case \" $broker_only_providers \" in',\n ' *\" $provider \"*) printf \\'%s\\\\n\\' \"$tool provider API authentication is host-brokered for this session; use the configured provider MCP tools\" >&2; exit 2 ;;',\n \" esac\",\n ' case \" $multi_binding_providers \" in',\n ' *\" $provider \"*) printf \\'%s\\\\n\\' \"Unable to select one of multiple $provider credentials; run inside an attached repository, or inspect ${OPENGENI_GIT_BINDINGS_FILE:-$HOME/.opengeni/git-bindings.json} and set OPENGENI_GIT_BINDING\" >&2; exit 2 ;;',\n \" esac\",\n ' case \"$provider\" in',\n ' github) token_file=\"${OPENGENI_GIT_TOKEN_FILE:-$HOME/.opengeni/git-token}\" ;;',\n ' *) token_file=\"${OPENGENI_GIT_CREDENTIALS_DIR:-$HOME/.opengeni/git-credentials}/$provider-token\" ;;',\n \" esac\",\n \" fi\",\n ' if [ -f \"$token_file\" ]; then',\n ' token=\"$(cat \"$token_file\" 2>/dev/null || true)\"',\n ' if [ -n \"$token\" ]; then',\n ' case \"$token_env\" in',\n ' GH_TOKEN) export GH_TOKEN=\"$token\" ;;',\n ' GITLAB_TOKEN) export GITLAB_TOKEN=\"$token\" ;;',\n ' AZURE_DEVOPS_EXT_PAT) export AZURE_DEVOPS_EXT_PAT=\"$token\" ;;',\n \" esac\",\n \" fi\",\n \" fi\",\n \"fi\",\n 'self_real=\"$(readlink -f \"$0\" 2>/dev/null || printf \\'%s\\\\n\\' \"$0\")\"',\n 'old_ifs=\"$IFS\"',\n \"IFS=:\",\n \"for dir in $PATH; do\",\n ' [ -n \"$dir\" ] || dir=.',\n ' candidate=\"$dir/$tool\"',\n ' [ -x \"$candidate\" ] || continue',\n ' candidate_real=\"$(readlink -f \"$candidate\" 2>/dev/null || printf \\'%s\\\\n\\' \"$candidate\")\"',\n ' [ \"$candidate_real\" = \"$self_real\" ] && continue',\n ' IFS=\"$old_ifs\"',\n ' exec \"$candidate\" \"$@\"',\n \"done\",\n 'IFS=\"$old_ifs\"',\n \"printf '%s\\\\n' \\\"$tool: real command not found on PATH\\\" >&2\",\n \"exit 127\",\n \"CLI_WRAPPER_EOF\",\n ' chmod 0755 \"$wrapper.tmp.$$\"',\n ' mv -f \"$wrapper.tmp.$$\" \"$wrapper\"',\n \"done\",\n ];\n}\n\n/**\n * Build the off-manifest command used to atomically replace provider token files.\n *\n * Token values exist only in this one sandbox exec command. The stable askpass\n * and provider-CLI wrappers always read the files at invocation time, so an\n * in-flight multi-day turn observes the replacement without changing its\n * manifest environment or rebuilding the sandbox.\n */\nexport function gitProviderTokenRefreshCommand(seeds: GitTokenSeeds): string {\n const seedPrefix = gitTokenSeedExportPrefix(seeds);\n if (!seedPrefix) {\n return \"\";\n }\n return [\n \"set +x\",\n seedPrefix,\n \"set -eu\",\n 'export HOME=\"${HOME:-/workspace}\"',\n ...gitCredentialTokenWriterCommandLines(),\n ].join(\"\\n\");\n}\n\nexport function gitCredentialBindingTokenRefreshCommand(\n bindings: GitCredentialBindingSeed[],\n): string {\n const seedPrefix = gitCredentialBindingSeedExportPrefix(bindings);\n if (!seedPrefix) return \"\";\n return [\n \"set +x\",\n seedPrefix,\n \"set -eu\",\n 'export HOME=\"${HOME:-/workspace}\"',\n ...gitCredentialTokenWriterCommandLines(bindings),\n ].join(\"\\n\");\n}\n\nexport async function refreshGitProviderTokenFiles(\n session: GitCredentialTokenWriterSession,\n seeds: GitTokenSeeds,\n options: { runAs?: string; commandRunner?: SandboxLifecycleCommandRunner } = {},\n): Promise<void> {\n const command = gitProviderTokenRefreshCommand(seeds);\n if (!command) {\n return;\n }\n const args = {\n cmd: command,\n workdir: \"/workspace\",\n ...(options.runAs ? { runAs: options.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 4_000,\n };\n assertSandboxCommandSucceeded(\n await runSandboxLifecycleCommand(session, args, options.commandRunner),\n \"Git credential refresh\",\n );\n}\n\nexport async function refreshGitCredentialBindingTokenFiles(\n session: GitCredentialTokenWriterSession,\n bindings: GitCredentialBindingSeed[],\n options: { runAs?: string; commandRunner?: SandboxLifecycleCommandRunner } = {},\n): Promise<void> {\n const command = gitCredentialBindingTokenRefreshCommand(bindings);\n if (!command) return;\n const args = {\n cmd: command,\n workdir: \"/workspace\",\n ...(options.runAs ? { runAs: options.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 4_000,\n };\n assertSandboxCommandSucceeded(\n await runSandboxLifecycleCommand(session, args, options.commandRunner),\n \"Git credential binding refresh\",\n );\n}\n\nexport function repositoryCloneCommand(\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n bindings: GitCredentialBindingSeed[] = [],\n): string {\n assertUniqueResourceMountPaths(resources);\n const commands = [\n \"set +x\",\n \"set -eu\",\n 'export HOME=\"${HOME:-/workspace}\"',\n 'export GIT_TERMINAL_PROMPT=\"${GIT_TERMINAL_PROMPT:-0}\"',\n \"ensure_git() {\",\n \" if command -v git >/dev/null 2>&1; then\",\n \" return 0\",\n \" fi\",\n \" if command -v apt-get >/dev/null 2>&1; then\",\n \" export DEBIAN_FRONTEND=noninteractive\",\n \" apt-get update >/dev/null\",\n \" apt-get install -y --no-install-recommends ca-certificates git >/dev/null\",\n \" rm -rf /var/lib/apt/lists/*\",\n \" command -v git >/dev/null 2>&1 && return 0\",\n \" fi\",\n ' echo \"git is not installed in the sandbox and could not be bootstrapped\" >&2',\n \" exit 127\",\n \"}\",\n \"ensure_git\",\n ...gitCredentialHelperCommandLines(resources, bindings),\n \"clone_repository() {\",\n ' target=\"$1\"',\n ' uri=\"$2\"',\n ' ref=\"$3\"',\n ' subpath=\"$4\"',\n ' if [ -e \"$target\" ] && { [ -f \"$target\" ] || [ -n \"$(find \"$target\" -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null)\" ]; }; then',\n // This hook re-runs every turn on a long-lived box, so \\\"non-empty\\\" alone is not\n // proof of a completed materialization: an interrupted clone (worker crash /\n // lifecycle timeout mid-mv/cp) leaves a partial tree that would otherwise pass\n // this check forever. A full-repo target must actually BE a work tree to be\n // skipped; a partial one is wiped and rebuilt (nothing legitimate writes under\n // the mount path before the repo exists). Subpath extracts are not git repos —\n // for those the plain non-empty check stands (no stronger signal available).\n ' if [ -n \"$subpath\" ] || git -C \"$target\" rev-parse --is-inside-work-tree >/dev/null 2>&1; then',\n ' echo \"Repository resource already present at $target\"',\n \" return 0\",\n \" fi\",\n ' echo \"Re-materializing partial repository resource at $target\" >&2',\n ' find \"$target\" -mindepth 1 -maxdepth 1 -exec rm -rf {} +',\n \" fi\",\n ' mkdir -p \"$(dirname \"$target\")\"',\n ' tmp=\"${target}.tmp.$$\"',\n ' rm -rf \"$tmp\"',\n // Fetch failures must not leak the pid-suffixed tmp clone beside the mount\n // (set -eu would exit before any cleanup).\n ' if ! { git init \"$tmp\" >/dev/null && git -C \"$tmp\" remote add origin \"$uri\" && git -C \"$tmp\" fetch --depth 1 --no-tags --filter=blob:none origin \"$ref\" && git -C \"$tmp\" checkout --detach FETCH_HEAD >/dev/null; }; then',\n ' rm -rf \"$tmp\"',\n ' echo \"Repository resource fetch failed for $target\" >&2',\n \" exit 1\",\n \" fi\",\n ' if [ -n \"$subpath\" ]; then',\n ' if [ ! -e \"$tmp/$subpath\" ]; then',\n ' echo \"Repository subpath not found: $subpath\" >&2',\n ' rm -rf \"$tmp\"',\n \" exit 1\",\n \" fi\",\n ' if [ -d \"$tmp/$subpath\" ]; then',\n ' mkdir -p \"$target\"',\n ' cp -a \"$tmp/$subpath/.\" \"$target/\"',\n \" else\",\n ' rmdir \"$target\" 2>/dev/null || true',\n ' cp -a \"$tmp/$subpath\" \"$target\"',\n \" fi\",\n ' rm -rf \"$tmp\"',\n \" else\",\n ' rmdir \"$target\" 2>/dev/null || true',\n // Two concurrent turn holders can race this install: without the existence\n // re-check the loser's un-flagged `mv` would nest its tmp clone INSIDE the\n // winner's tree as <name>.tmp.<pid>. If the winner produced a valid work tree,\n // accept it; a non-empty non-repo survivor here is a mount point the manifest\n // re-filled — install into it by content copy instead of rename.\n ' if [ -e \"$target\" ]; then',\n ' if git -C \"$target\" rev-parse --is-inside-work-tree >/dev/null 2>&1; then',\n ' rm -rf \"$tmp\"',\n ' echo \"Repository resource already present at $target\"',\n \" return 0\",\n \" fi\",\n ' cp -a \"$tmp/.\" \"$target/\"',\n ' rm -rf \"$tmp\"',\n \" else\",\n ' mv \"$tmp\" \"$target\"',\n \" fi\",\n ' git -C \"$target\" rev-parse --is-inside-work-tree >/dev/null',\n \" fi\",\n ' if [ ! -e \"$target\" ]; then',\n ' echo \"Repository resource was not materialized at $target\" >&2',\n \" exit 1\",\n \" fi\",\n ' echo \"Repository resource ready at $target\"',\n \"}\",\n ];\n for (const resource of resources) {\n const mountPath = resourceMountPath(resource);\n commands.push(\n [\n \"clone_repository\",\n shellQuote(posixPath.join(\"/workspace\", mountPath)),\n shellQuote(resource.uri),\n shellQuote(resource.ref),\n shellQuote(resource.subpath ? normalizeRepositorySubpath(resource.subpath) : \"\"),\n ].join(\" \"),\n );\n }\n return commands.join(\"\\n\");\n}\n\nexport function toolspaceTokenSeedCommand(\n options: { tokenFile?: string; legacyTokenFile?: string } = {},\n): string {\n return [\n \"set +x\",\n \"set -eu\",\n 'export HOME=\"${HOME:-/workspace}\"',\n 'if [ -n \"${OPENGENI_TOOLSPACE_TOKEN_SEED:-}\" ]; then',\n ' seed_umask=\"$(umask)\"',\n \" umask 077\",\n options.tokenFile\n ? ` token_file=${shellToolspacePath(options.tokenFile)}`\n : ' token_file=\"${OPENGENI_TOOLSPACE_TOKEN_FILE:-$HOME/.opengeni/toolspace-token}\"',\n options.legacyTokenFile\n ? ` legacy_token_file=${shellToolspacePath(options.legacyTokenFile)}`\n : ' legacy_token_file=\"\"',\n ' mkdir -p \"$(dirname \"$token_file\")\"',\n ' printf \\'%s\\' \"$OPENGENI_TOOLSPACE_TOKEN_SEED\" > \"$token_file.tmp.$$\"',\n ' mv -f \"$token_file.tmp.$$\" \"$token_file\"',\n ' if [ -n \"$legacy_token_file\" ] && [ \"$legacy_token_file\" != \"$token_file\" ]; then',\n ' rm -f -- \"$legacy_token_file\"',\n \" fi\",\n ' umask \"$seed_umask\"',\n \"fi\",\n ].join(\"\\n\");\n}\n\nexport async function runToolspaceTokenSeedHook(\n session: SandboxSessionLike,\n context: SandboxLifecycleHookContext,\n): Promise<void> {\n if (!context.toolspaceTokenSeed) {\n return;\n }\n const command = `set +x\\nexport OPENGENI_TOOLSPACE_TOKEN_SEED=${shellQuote(context.toolspaceTokenSeed)}\\n${toolspaceTokenSeedCommand(\n {\n ...(context.toolspaceTokenFile ? { tokenFile: context.toolspaceTokenFile } : {}),\n ...(context.toolspaceTokenFile && context.environment.OPENGENI_TOOLSPACE_TOKEN_FILE\n ? { legacyTokenFile: context.environment.OPENGENI_TOOLSPACE_TOKEN_FILE }\n : {}),\n },\n )}`;\n const result = await runSandboxLifecycleCommand(\n session,\n {\n cmd: command,\n workdir: \"/workspace\",\n ...(context.runAs ? { runAs: context.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 4_000,\n },\n context.commandRunner,\n );\n assertSandboxCommandSucceeded(result, \"Toolspace token seed hook\");\n}\n\nexport async function refreshToolspaceTokenFile(\n session: ToolspaceTokenWriterSession,\n token: string,\n options: {\n runAs?: string;\n commandRunner?: SandboxLifecycleCommandRunner;\n tokenFile?: string;\n legacyTokenFile?: string;\n } = {},\n): Promise<void> {\n const command = `set +x\\nexport OPENGENI_TOOLSPACE_TOKEN_SEED=${shellQuote(token)}\\n${toolspaceTokenSeedCommand(\n {\n ...(options.tokenFile ? { tokenFile: options.tokenFile } : {}),\n ...(options.legacyTokenFile ? { legacyTokenFile: options.legacyTokenFile } : {}),\n },\n )}`;\n const result = await runSandboxLifecycleCommand(\n session,\n {\n cmd: command,\n workdir: \"/workspace\",\n ...(options.runAs ? { runAs: options.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 4_000,\n },\n options.commandRunner,\n );\n assertSandboxCommandSucceeded(result, \"Toolspace token refresh\");\n}\n\n// Bounds the setup output tail carried on a rig.setup failure event/error so a\n// runaway script can't bloat the session's event stream or the turn error.\nconst RIG_SETUP_OUTPUT_TAIL_LIMIT = 4_000;\n\n// A distinctive sentinel the guard prints when the idempotence marker already\n// exists, so the runtime can tell a SKIP from an actual run without a second\n// exec round-trip.\nconst RIG_SETUP_SKIPPED_SENTINEL = \"__OPENGENI_RIG_SETUP_SKIPPED__\";\n\n/**\n * The rig-setup command (M3). One idempotent bash program:\n * 1. `mkdir -p /var/opengeni` and, if the per-version marker already exists,\n * print the SKIP sentinel and exit 0 (a warm box re-running the hook).\n * 2. otherwise atomically claim a per-version lock directory. A loser waits\n * for the winner's marker, then skips; if the winner fails and releases the\n * lock, the loser retries the claim.\n * 3. the winner writes the rig's setup script to a temp file and runs it under\n * coreutils `timeout` (NOT `bash -e` — the script opts into `set -e`\n * itself if it wants), then captures the exit code and `touch`es the marker\n * ONLY on success (exit 0) so a failed/timed-out setup re-runs next turn.\n * The heredoc delimiter is quoted, so the script content is executed verbatim\n * with no host-side expansion.\n */\nexport function rigSetupScriptCommand(\n script: string,\n versionId: string,\n timeoutMs = 600_000,\n markerRoot = \"/var/opengeni\",\n): string {\n const timeoutSecs = Math.max(1, Math.ceil(timeoutMs / 1000));\n const lockWaitSecs = timeoutSecs + 6;\n const marker = `${markerRoot.replace(/\\/+$/, \"\")}/rig-setup-${versionId}.done`;\n return [\n \"set -u\",\n `mkdir -p ${shellQuote(markerRoot)}`,\n `__OG_RIG_MARKER=${shellQuote(marker)}`,\n '__OG_RIG_LOCK=\"$__OG_RIG_MARKER.lock\"',\n `__OG_RIG_TIMEOUT_SECS=${timeoutSecs}`,\n `__OG_RIG_LOCK_WAIT_SECS=${lockWaitSecs}`,\n `if [ -f \"$__OG_RIG_MARKER\" ]; then printf '%s\\\\n' ${shellQuote(RIG_SETUP_SKIPPED_SENTINEL)}; exit 0; fi`,\n \"while :; do\",\n ' if mkdir \"$__OG_RIG_LOCK\" 2>/dev/null; then',\n \" trap 'rm -rf \\\"$__OG_RIG_LOCK\\\"' EXIT\",\n ` if [ -f \"$__OG_RIG_MARKER\" ]; then printf '%s\\\\n' ${shellQuote(RIG_SETUP_SKIPPED_SENTINEL)}; exit 0; fi`,\n '__OG_RIG_SCRIPT=\"$(mktemp)\"',\n \"cat > \\\"$__OG_RIG_SCRIPT\\\" <<'__OPENGENI_RIG_SETUP_SCRIPT_EOF__'\",\n script,\n \"__OPENGENI_RIG_SETUP_SCRIPT_EOF__\",\n ' timeout -k 5s \"${__OG_RIG_TIMEOUT_SECS}s\" bash \"$__OG_RIG_SCRIPT\"',\n \"__OG_RIG_RC=$?\",\n ' rm -f \"$__OG_RIG_SCRIPT\"',\n ' if [ \"$__OG_RIG_RC\" -eq 0 ]; then touch \"$__OG_RIG_MARKER\"; fi',\n ' exit \"$__OG_RIG_RC\"',\n \" fi\",\n \" __OG_RIG_WAITED=0\",\n ' while [ \"$__OG_RIG_WAITED\" -lt \"$__OG_RIG_LOCK_WAIT_SECS\" ]; do',\n ` if [ -f \"$__OG_RIG_MARKER\" ]; then printf '%s\\\\n' ${shellQuote(RIG_SETUP_SKIPPED_SENTINEL)}; exit 0; fi`,\n ' if [ ! -d \"$__OG_RIG_LOCK\" ]; then break; fi',\n \" sleep 1\",\n \" __OG_RIG_WAITED=$((__OG_RIG_WAITED + 1))\",\n \" done\",\n ` if [ -f \"$__OG_RIG_MARKER\" ]; then printf '%s\\\\n' ${shellQuote(RIG_SETUP_SKIPPED_SENTINEL)}; exit 0; fi`,\n ' if [ ! -d \"$__OG_RIG_LOCK\" ]; then continue; fi',\n ' rmdir \"$__OG_RIG_LOCK\" 2>/dev/null || true',\n \"done\",\n ].join(\"\\n\");\n}\n\n/**\n * The rig-setup beforeAgentStart hook (M3). Runs the frozen rig version's setup\n * script exactly once per box (marker-guarded), under the RIG's own timeout\n * (context.rigSetup.timeoutMs, NOT the 120s lifecycle default). Emits\n * rig.setup.started, then one terminal event:\n * - rig.setup.skipped — marker already present,\n * - rig.setup.completed — script ran and exited 0,\n * - rig.setup.failed — nonzero exit / timeout,\n * and on failure THROWS (fail the turn closed) with a message naming the\n * rig/version and a bounded tail of the setup output.\n */\nexport async function runRigSetupHook(\n session: SandboxSessionLike,\n context: SandboxLifecycleHookContext = { environment: {} },\n): Promise<void> {\n const rigSetup = context.rigSetup;\n if (!rigSetup) {\n return;\n }\n const payload = {\n rigId: rigSetup.rigId,\n versionId: rigSetup.versionId,\n rigName: rigSetup.rigName,\n };\n await context.onRuntimeEvent?.({ type: \"rig.setup.started\", payload });\n const command = rigSetupScriptCommand(rigSetup.script, rigSetup.versionId, rigSetup.timeoutMs);\n const execArgs = {\n cmd: command,\n workdir: \"/workspace\",\n ...(context.runAs ? { runAs: context.runAs } : {}),\n // The in-box coreutils timeout is the hard deadline; the SDK yield waits a\n // little longer so it observes timeout's non-zero exit instead of a live\n // still-running process.\n yieldTimeMs: rigSetup.timeoutMs + 7_000,\n maxOutputTokens: 20_000,\n };\n let result: unknown;\n try {\n result = await runSandboxLifecycleCommand(session, execArgs, context.commandRunner);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n await context.onRuntimeEvent?.({\n type: \"rig.setup.failed\",\n payload: {\n ...payload,\n error: message.slice(-RIG_SETUP_OUTPUT_TAIL_LIMIT),\n },\n });\n throw new Error(\n `Rig setup failed for rig \"${rigSetup.rigName}\" (version ${rigSetup.versionId}): ${message}`,\n { cause: error },\n );\n }\n const output = sandboxCommandOutput(result);\n // Marker present → the guard skipped the script. Distinct terminal signal.\n if (output.includes(RIG_SETUP_SKIPPED_SENTINEL)) {\n await context.onRuntimeEvent?.({ type: \"rig.setup.skipped\", payload });\n return;\n }\n // Ran → classify. A \"still running\" result means the script outlived the rig\n // timeout; any nonzero/absent exit code is a setup failure. Both fail closed.\n const stillRunning = sandboxCommandStillRunning(result);\n const exitCode = sandboxCommandExitCode(result);\n if (stillRunning || exitCode === null || exitCode !== 0) {\n const tail =\n output.length > RIG_SETUP_OUTPUT_TAIL_LIMIT\n ? output.slice(-RIG_SETUP_OUTPUT_TAIL_LIMIT)\n : output;\n const reason = stillRunning\n ? `did not finish within the rig setup timeout (${rigSetup.timeoutMs}ms)`\n : exitCode === null\n ? \"did not report an exit code\"\n : `exited with code ${exitCode}`;\n const failure = new Error(\n `Rig setup failed for rig \"${rigSetup.rigName}\" (version ${rigSetup.versionId}): the setup script ${reason}${tail ? `:\\n${tail}` : \"\"}`,\n );\n await context.onRuntimeEvent?.({\n type: \"rig.setup.failed\",\n payload: {\n ...payload,\n error: failure.message.slice(-RIG_SETUP_OUTPUT_TAIL_LIMIT),\n },\n });\n throw failure;\n }\n await context.onRuntimeEvent?.({\n type: \"rig.setup.completed\",\n payload: { ...payload, skipped: false },\n });\n}\n\nexport async function runRepositoryCloneHook(\n session: SandboxSessionLike,\n resources: Extract<ResourceRef, { kind: \"repository\" }>[],\n context: SandboxLifecycleHookContext = { environment: {} },\n): Promise<void> {\n const payload = {\n name: \"repository-clone\",\n repositoryCount: resources.length,\n };\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.started\",\n payload,\n });\n try {\n // TOKEN-BROKER (B1): thread run-scoped provider tokens PER-EXEC, never on\n // the manifest. The SDK's ExecCommandArgs has no `environment` field (exec\n // inherits the box's manifest env), so we can't hand seeds through an exec\n // option — and we MUST NOT put them on the manifest (validateNoEnvironmentDelta\n // would see rotating values). We inline ephemeral `export` prefixes on THIS\n // exec's command text only. The clone command writes them to provider token\n // FILES before fetch/CLI use. Absent seeds -> no prefix; helper wrappers still\n // install and passthrough cleanly.\n const gitTokenSeeds = {\n ...(context.gitTokenSeeds ?? {}),\n ...(context.gitTokenSeed ? { github: context.gitTokenSeed } : {}),\n } satisfies GitTokenSeeds;\n const gitCredentialBindings = context.gitCredentialBindings ?? [];\n const seedPrefix = [\n gitTokenSeedExportPrefix(gitTokenSeeds),\n gitCredentialBindingSeedExportPrefix(gitCredentialBindings),\n ]\n .filter(Boolean)\n .join(\"\\n\");\n const cloneCommand = repositoryCloneCommand(resources, gitCredentialBindings);\n const command = seedPrefix ? `set +x\\n${seedPrefix}\\n${cloneCommand}` : cloneCommand;\n const result = await runSandboxLifecycleCommand(\n session,\n {\n cmd: command,\n workdir: \"/workspace\",\n ...(context.runAs ? { runAs: context.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 20_000,\n },\n context.commandRunner,\n );\n assertSandboxCommandSucceeded(result, \"Repository clone hook\");\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.completed\",\n payload,\n });\n } catch (error) {\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.failed\",\n payload: {\n ...payload,\n error: error instanceof Error ? error.message : String(error),\n },\n });\n throw error;\n }\n}\n\nexport function azureCliLoginCommand(): string {\n return [\n \"set +x\",\n 'export HOME=\"${HOME:-/workspace}\"',\n 'mkdir -p \"$HOME/.azure\"',\n 'CLIENT_ID=\"${AZURE_CLIENT_ID:-${ARM_CLIENT_ID:-}}\"',\n 'CLIENT_SECRET=\"${AZURE_CLIENT_SECRET:-${ARM_CLIENT_SECRET:-}}\"',\n 'TENANT_ID=\"${AZURE_TENANT_ID:-${ARM_TENANT_ID:-}}\"',\n 'SUBSCRIPTION_ID=\"${AZURE_SUBSCRIPTION_ID:-${ARM_SUBSCRIPTION_ID:-}}\"',\n 'if [ -n \"$CLIENT_ID\" ] && [ -n \"$CLIENT_SECRET\" ] && [ -n \"$TENANT_ID\" ]; then',\n ' command -v az >/dev/null 2>&1 || { echo \"Azure CLI is not installed in the sandbox\" >&2; exit 127; }',\n ' az account show --only-show-errors >/dev/null 2>&1 || az login --service-principal --username \"$CLIENT_ID\" --password \"$CLIENT_SECRET\" --tenant \"$TENANT_ID\" --allow-no-subscriptions --only-show-errors --output none',\n // if/fi, NOT `[ -n ] && az`: this line ends the credentialed if-body, so with a\n // no-subscription SP (an explicitly supported config — the login above passes\n // --allow-no-subscriptions) the bare `[ -n ]` would exit the whole script 1 and\n // fail the turn.\n ' if [ -n \"$SUBSCRIPTION_ID\" ]; then az account set --subscription \"$SUBSCRIPTION_ID\" --only-show-errors; fi',\n \"fi\",\n ].join(\"\\n\");\n}\n\nexport function sandboxCommandExitCode(result: unknown): number | null {\n if (typeof result === \"string\") {\n const match = result.match(/Process exited with code (-?\\d+)/);\n return match ? Number(match[1]) : null;\n }\n if (!result || typeof result !== \"object\") {\n return null;\n }\n const candidate = result as {\n exitCode?: unknown;\n exit_code?: unknown;\n code?: unknown;\n status?: unknown;\n };\n for (const value of [candidate.exitCode, candidate.exit_code, candidate.code, candidate.status]) {\n if (typeof value === \"number\") {\n return value;\n }\n }\n return null;\n}\n\nexport function sandboxCommandOutput(result: unknown): string {\n if (typeof result === \"string\") {\n const outputIndex = result.indexOf(\"Output:\");\n return outputIndex >= 0 ? result.slice(outputIndex + \"Output:\".length).trim() : result.trim();\n }\n if (!result || typeof result !== \"object\") {\n return \"\";\n }\n const candidate = result as {\n output?: unknown;\n stdout?: unknown;\n stderr?: unknown;\n };\n return [candidate.output, candidate.stderr, candidate.stdout]\n .filter((value): value is string => typeof value === \"string\" && value.length > 0)\n .join(\"\\n\");\n}\n\nfunction assertSandboxCommandSucceeded(result: unknown, operation: string): void {\n const output = sandboxCommandOutput(result);\n if (sandboxCommandStillRunning(result)) {\n throw new Error(\n `${operation} did not finish before the lifecycle command timeout${output ? `:\\n${output}` : \"\"}`,\n );\n }\n const exitCode = sandboxCommandExitCode(result);\n if (exitCode !== null && exitCode !== 0) {\n throw new Error(\n `${operation} failed with exit code ${exitCode}${output ? `:\\n${output}` : \"\"}`,\n );\n }\n if (exitCode === null) {\n throw new Error(output || `${operation} did not return a command exit code`);\n }\n}\n\nexport function sandboxCommandStillRunning(result: unknown): boolean {\n if (typeof result === \"string\") {\n return /Process running with session ID \\d+/u.test(result);\n }\n if (!result || typeof result !== \"object\") {\n return false;\n }\n const candidate = result as { sessionId?: unknown; session_id?: unknown };\n return typeof candidate.sessionId === \"number\" || typeof candidate.session_id === \"number\";\n}\n\nfunction hasAzureServicePrincipal(environment: Record<string, string>): boolean {\n const clientId = environment.AZURE_CLIENT_ID || environment.ARM_CLIENT_ID;\n const clientSecret = environment.AZURE_CLIENT_SECRET || environment.ARM_CLIENT_SECRET;\n const tenantId = environment.AZURE_TENANT_ID || environment.ARM_TENANT_ID;\n return Boolean(clientId && clientSecret && tenantId);\n}\n\nexport async function runAzureCliLoginHook(\n session: SandboxSessionLike,\n context: SandboxLifecycleHookContext = { environment: {} },\n): Promise<void> {\n const payload = {\n name: \"azure-cli-login\",\n command: \"az login --service-principal\",\n };\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.started\",\n payload,\n });\n try {\n const result = await runSandboxLifecycleCommand(\n session,\n {\n cmd: azureCliLoginCommand(),\n workdir: \"/workspace\",\n ...(context.runAs ? { runAs: context.runAs } : {}),\n yieldTimeMs: SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS,\n maxOutputTokens: 20_000,\n },\n context.commandRunner,\n );\n assertSandboxCommandSucceeded(result, \"Azure CLI login hook\");\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.completed\",\n payload,\n });\n } catch (error) {\n await context.onRuntimeEvent?.({\n type: \"sandbox.operation.failed\",\n payload: {\n ...payload,\n error: error instanceof Error ? error.message : String(error),\n },\n });\n throw error;\n }\n}\n\nfunction azureDeploymentBaseUrl(settings: Settings): string {\n const endpoint = settings.azureOpenaiEndpoint?.replace(/\\/+$/, \"\");\n if (!endpoint || !settings.azureOpenaiDeployment) {\n throw new Error(\"Azure OpenAI endpoint/deployment settings are incomplete\");\n }\n return `${endpoint}/openai/deployments/${settings.azureOpenaiDeployment}`;\n}\n\nexport function azureOpenAIDefaultQuery(\n settings: Pick<Settings, \"azureOpenaiApiVersion\">,\n baseURL: string,\n): Record<string, string> | undefined {\n if (!settings.azureOpenaiApiVersion) return undefined;\n const normalized = baseURL.replace(/\\/+$/, \"\").toLowerCase();\n if (normalized.endsWith(\"/openai/v1\")) {\n return undefined;\n }\n return { \"api-version\": settings.azureOpenaiApiVersion };\n}\n\n// Since @openai/agents 0.11.0 local sandbox sources (including the lazy\n// bundled-skills source) must stay within the SDK process working directory:\n// reads outside it require manifest.extraPathGrants, and remote sandbox\n// clients such as Modal reject manifests that carry extra path grants. The\n// packaged skills live inside the runtime package — outside the worker's cwd\n// in production — so stage a copy under the working directory once per\n// process instead of granting the packaged path.\nlet stagedBundledSkillsDir: string | null = null;\n\nfunction bundledSkillsDir(): string {\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const packaged =\n [\n join(moduleDir, \"bundled_hashicorp_terraform_skills\"),\n join(moduleDir, \"..\", \"src\", \"bundled_hashicorp_terraform_skills\"),\n ].find((candidate) => existsSync(candidate)) ??\n join(moduleDir, \"bundled_hashicorp_terraform_skills\");\n if (isPathWithin(process.cwd(), packaged)) {\n return packaged;\n }\n if (!stagedBundledSkillsDir) {\n stagedBundledSkillsDir = stageBundledSkills(\n packaged,\n join(process.cwd(), \".opengeni\", \"bundled_hashicorp_terraform_skills\"),\n );\n }\n return stagedBundledSkillsDir;\n}\n\nfunction stageBundledSkills(packaged: string, target: string): string {\n const tmp = `${target}.tmp-${process.pid}`;\n rmSync(tmp, { recursive: true, force: true });\n mkdirSync(dirname(tmp), { recursive: true });\n cpSync(packaged, tmp, { recursive: true });\n rmSync(target, { recursive: true, force: true });\n try {\n renameSync(tmp, target);\n } catch (error) {\n // Another process staged the same content between our rm and rename.\n rmSync(tmp, { recursive: true, force: true });\n if (!existsSync(target)) {\n throw error;\n }\n }\n return target;\n}\n\nfunction isPathWithin(root: string, candidate: string): boolean {\n const relativePath = relative(root, candidate);\n return relativePath === \"\" || (!relativePath.startsWith(\"..\") && !isAbsolute(relativePath));\n}\n\n/**\n * The skill source fed to the SDK Skills capability. Without pack or curated\n * skills this is the plain bundled local-dir source, byte-for-byte the\n * pre-pack behavior. With either selected source it becomes a single\n * in-memory dir source combining bundled skill directories (as local_dir\n * entries the SDK materializes lazily) with selected in-memory skill\n * directories — one skill index, one `## Skills` instruction section, lazy\n * `load_skill` for all of them. A pack skill shadows a bundled or curated\n * skill with the same directory name, case-insensitively.\n */\nexport function lazySkillSourceWithPackSkills(\n packSkills: PackSkill[],\n skillLibrarySkills: PackSkill[] = [],\n): LocalDirLazySkillSource {\n const bundledDir = bundledSkillsDir();\n const bundled = localDirLazySkillSource({ src: bundledDir });\n if (packSkills.length === 0 && skillLibrarySkills.length === 0) {\n return bundled;\n }\n const children: Record<string, Entry> = {};\n for (const name of bundledSkillDirNames(bundledDir)) {\n children[name] = localDir({ src: join(bundledDir, name) });\n }\n const libraryIndex: SkillIndexEntry[] = [];\n const libraryNameKeys = new Set<string>();\n for (const skill of skillLibrarySkills) {\n assertSafePackSkillName(skill.name);\n const key = skill.name.toLowerCase();\n if (libraryNameKeys.has(key)) {\n throw new Error(`Duplicate curated skill name: ${skill.name}`);\n }\n libraryNameKeys.add(key);\n removeSkillChildByNameKey(children, key);\n children[skill.name] = packSkillDirEntry(skill);\n libraryIndex.push({\n name: skill.name,\n description: packSkillDescription(skill),\n path: skill.name,\n });\n }\n const packIndex: SkillIndexEntry[] = [];\n const packNameKeys = new Set<string>();\n for (const skill of packSkills) {\n assertSafePackSkillName(skill.name);\n if (packNameKeys.has(skill.name.toLowerCase())) {\n throw new Error(`Duplicate pack skill name: ${skill.name}`);\n }\n packNameKeys.add(skill.name.toLowerCase());\n removeSkillChildByNameKey(children, skill.name.toLowerCase());\n children[skill.name] = packSkillDirEntry(skill);\n packIndex.push({\n name: skill.name,\n description: packSkillDescription(skill),\n path: skill.name,\n });\n }\n return {\n source: dir({ children }),\n getIndex: (manifest, skillsPath) => [\n ...(bundled.getIndex?.(manifest, skillsPath) ?? []).filter(\n (entry) =>\n !packNameKeys.has((entry.path ?? entry.name).toLowerCase()) &&\n !libraryNameKeys.has((entry.path ?? entry.name).toLowerCase()),\n ),\n ...libraryIndex.filter(\n (entry) => !packNameKeys.has((entry.path ?? entry.name).toLowerCase()),\n ),\n ...packIndex,\n ],\n };\n}\n\nfunction effectiveSkillSelections(\n librarySelections: readonly EffectiveSkillSelection[],\n librarySkills: readonly PackSkill[],\n packSkills: readonly PackSkill[],\n sessionSkills: readonly PackSkill[],\n): readonly EffectiveSkillSelection[] {\n const defaultSelections = bundledSkillDirNames(bundledSkillsDir()).map((name) => ({\n id: `bundled:${name}`,\n name,\n source: \"bundled\" as const,\n version: null,\n contentSha256: null,\n reason: \"deployment default skill bundle\",\n }));\n const libraryNameKeys = new Set(librarySkills.map((skill) => skill.name.toLowerCase()));\n const packNameKeys = new Set(packSkills.map((skill) => skill.name.toLowerCase()));\n const effectiveSessionSkills = sessionSkillsForMaterialization(\n packSkills,\n librarySkills,\n sessionSkills,\n );\n const sessionNameKeys = new Set(effectiveSessionSkills.map((skill) => skill.name.toLowerCase()));\n const selected = librarySelections.filter((selection) =>\n libraryNameKeys.has(selection.name.toLowerCase()),\n );\n return [\n ...defaultSelections.filter(\n (selection) =>\n !libraryNameKeys.has(selection.name.toLowerCase()) &&\n !packNameKeys.has(selection.name.toLowerCase()) &&\n !sessionNameKeys.has(selection.name.toLowerCase()),\n ),\n ...selected.filter(\n (selection) =>\n !packNameKeys.has(selection.name.toLowerCase()) &&\n !sessionNameKeys.has(selection.name.toLowerCase()),\n ),\n ...packSkills.map((skill) => ({\n id: `pack:${skill.name}`,\n name: skill.name,\n source: \"pack\" as const,\n version: null,\n contentSha256: null,\n reason: \"enabled capability pack\",\n })),\n ...effectiveSessionSkills.map((skill) => ({\n id: `session:${skill.name}`,\n name: skill.name,\n source: \"session\" as const,\n version: null,\n contentSha256: null,\n reason: \"attached to session\",\n })),\n ];\n}\n\nfunction sessionSkillsForMaterialization(\n packSkills: readonly PackSkill[],\n librarySkills: readonly PackSkill[],\n sessionSkills: readonly PackSkill[],\n): PackSkill[] {\n const configured = new Map<string, PackSkill>();\n for (const skill of [...librarySkills, ...packSkills]) {\n configured.set(skill.name.toLowerCase(), skill);\n }\n const bundledNames = new Set(\n bundledSkillDirNames(bundledSkillsDir()).map((name) => name.toLowerCase()),\n );\n const selected = new Map<string, PackSkill>();\n for (const skill of sessionSkills) {\n assertSafePackSkillName(skill.name);\n const key = skill.name.toLowerCase();\n if (bundledNames.has(key)) {\n throw new Error(`Session skill \"${skill.name}\" conflicts with a bundled skill`);\n }\n const existing = selected.get(key) ?? configured.get(key);\n if (existing) {\n if (skillFingerprint(existing) !== skillFingerprint(skill)) {\n throw new Error(`Conflicting skill definitions for \"${skill.name}\"`);\n }\n continue;\n }\n selected.set(key, skill);\n }\n return [...selected.values()];\n}\n\nfunction skillFingerprint(skill: PackSkill): string {\n return JSON.stringify(\n [...skill.files]\n .sort((left, right) => left.path.localeCompare(right.path))\n .map(({ path, content }) => ({ path, content })),\n );\n}\n\nfunction removeSkillChildByNameKey(children: Record<string, Entry>, nameKey: string): void {\n for (const name of Object.keys(children)) {\n if (name.toLowerCase() === nameKey) {\n delete children[name];\n }\n }\n}\n\nfunction bundledSkillDirNames(root: string): string[] {\n return readdirSync(root, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && existsSync(join(root, entry.name, \"SKILL.md\")))\n .map((entry) => entry.name)\n .sort();\n}\n\ntype PackSkillDirNode = {\n dirs: Map<string, PackSkillDirNode>;\n files: Map<string, string>;\n};\n\nfunction packSkillDirEntry(skill: PackSkill): Dir {\n const root: PackSkillDirNode = { dirs: new Map(), files: new Map() };\n for (const skillFile of skill.files) {\n const segments = packSkillPathSegments(skill.name, skillFile.path);\n let node = root;\n for (const segment of segments.slice(0, -1)) {\n if (node.files.has(segment)) {\n throw new Error(`Pack skill ${skill.name} uses ${segment} as both a file and a directory`);\n }\n let next = node.dirs.get(segment);\n if (!next) {\n next = { dirs: new Map(), files: new Map() };\n node.dirs.set(segment, next);\n }\n node = next;\n }\n const filename = segments[segments.length - 1]!;\n if (node.dirs.has(filename) || node.files.has(filename)) {\n throw new Error(`Duplicate pack skill file path in ${skill.name}: ${skillFile.path}`);\n }\n node.files.set(filename, skillFile.content);\n }\n if (!root.files.has(\"SKILL.md\")) {\n throw new Error(`Pack skill ${skill.name} is missing a top-level SKILL.md file`);\n }\n return packSkillDirFromNode(root);\n}\n\nfunction packSkillDirFromNode(node: PackSkillDirNode): Dir {\n const children: Record<string, Entry> = {};\n for (const [name, child] of node.dirs) {\n children[name] = packSkillDirFromNode(child);\n }\n for (const [name, content] of node.files) {\n children[name] = file({ content });\n }\n return dir({ children });\n}\n\nfunction assertSafePackSkillName(name: string): void {\n if (packSkillPathSegments(name, name).length !== 1) {\n throw new Error(`Invalid pack skill name: ${name}`);\n }\n}\n\nfunction packSkillPathSegments(skillName: string, path: string): string[] {\n const segments = path.split(\"/\");\n if (\n path.startsWith(\"/\") ||\n path.includes(\"\\\\\") ||\n segments.some((segment) => segment.length === 0 || segment === \".\" || segment === \"..\")\n ) {\n throw new Error(`Invalid pack skill file path for ${skillName}: ${path}`);\n }\n return segments;\n}\n\nfunction packSkillDescription(skill: PackSkill): string {\n const explicit = skill.description?.trim();\n if (explicit) {\n return explicit;\n }\n const markdown = skill.files.find((skillFile) => skillFile.path === \"SKILL.md\")?.content ?? \"\";\n return skillFrontmatterDescription(markdown) ?? \"No description provided.\";\n}\n\nfunction skillFrontmatterDescription(markdown: string): string | null {\n const lines = markdown.split(/\\r?\\n/);\n if (lines[0]?.trim() !== \"---\") {\n return null;\n }\n const end = lines.findIndex((line, index) => index > 0 && line.trim() === \"---\");\n if (end === -1) {\n return null;\n }\n const collected: string[] = [];\n let inDescription = false;\n for (const line of lines.slice(1, end)) {\n const match = line.match(/^description:\\s*(.*)$/);\n if (match) {\n const inline = match[1]!.trim();\n if (inline && inline !== \">-\" && inline !== \">\" && inline !== \"|\" && inline !== \"|-\") {\n return unquoteFrontmatterValue(inline);\n }\n inDescription = true;\n continue;\n }\n if (inDescription) {\n if (/^\\s+\\S/.test(line)) {\n collected.push(line.trim());\n continue;\n }\n break;\n }\n }\n const blockValue = collected.join(\" \").trim();\n return blockValue ? blockValue : null;\n}\n\nfunction unquoteFrontmatterValue(value: string): string {\n if (\n value.length >= 2 &&\n value[0] === value[value.length - 1] &&\n (value[0] === '\"' || value[0] === \"'\")\n ) {\n return value.slice(1, -1);\n }\n return value;\n}\n\nfunction isAsyncIterable<T>(source: Iterable<T> | AsyncIterable<T>): source is AsyncIterable<T> {\n return typeof (source as AsyncIterable<T>)[Symbol.asyncIterator] === \"function\";\n}\n\nfunction stableJson(value: unknown): string {\n return JSON.stringify(sortJson(value));\n}\n\nfunction sortJson(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortJson);\n }\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, nested]) => [key, sortJson(nested)]),\n );\n }\n return value;\n}\nfunction interruptionToolName(item: unknown): string {\n const candidate = item as {\n toolName?: unknown;\n name?: unknown;\n rawItem?: { name?: unknown };\n };\n const name = candidate?.toolName ?? candidate?.name ?? candidate?.rawItem?.name;\n return typeof name === \"string\" ? name : \"\";\n}\n",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"// The legible \"screen capture failed\" error card the history-sanitizer wire seam\n// substitutes for an EMPTY `computer_call_output` image_url (see\n// `rewriteEmptyComputerCallOutputImageUrls`). The hosted `computer_use_preview`\n// protocol has only an IMAGE channel back to the model, so a capture failure has to\n// be a legible IMAGE — otherwise the SDK's empty-output placeholder (a 1×1\n// transparent PNG) reaches the model as a plausible-but-wrong BLANK DESKTOP it then\n// confidently reports (the exact failure mode of the 0.1.3 TCC-denied incident).\n//\n// This is a valid 8-bit RGBA PNG (verified: signature + per-chunk CRC + IDAT inflates\n// to the exact scanline size) rendered from a fixed message, so the provider's image\n// decoder accepts it (an invalid/empty image_url is what 400s the turn). The specific\n// failure REASON (permission denied / null image / timeout / display down) is not in\n// the card — it is logged worker-side by `NativeDesktopComputer.screenshot()`; the\n// card's job is only to stop the model from hallucinating a real blank desktop.\n//\n// Regenerate with: `bun run scripts/gen-screenshot-error-card.mjs`\n// Rendered text:\n// SCREEN CAPTURE FAILED\n// THE DESKTOP COULD NOT BE CAPTURED.\n// THIS IS A PLACEHOLDER, NOT THE REAL SCREEN.\n// DO NOT SAY THE SCREEN IS BLANK.\n// TELL THE USER TO CHECK THE DISPLAY AND GRANT\n// SCREEN RECORDING PERMISSION.\nexport const SCREENSHOT_FAILURE_CARD_IMAGE_URL =\n \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABVMAAAGYCAYAAABPvXKBAAAh90lEQVR42u3dMXLkxhJF0VnEGDQQXLY2CaedtkcLkEJBBaqrXmYe43j6bDZQKGTd+RH89df39x8A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KY6VImpYqp1Jab6eWKq51dMtU7FVDEVAEBMdahyGBFTrSsx1aFeTBWp7M9iqpgqpjr4AQBiavGYmvS/dRjpfeizruYdIh3q+9xfkWreP+553qxT+2TdfzwDAMRUMVX0chgRU60rMdXPE1PFVDHVOhVTxVQxFQAQUx2qHEbEVOtKTHWoF1M9v/Zn69T8Yp8UUwEAMdWhyuHVoc+6ElMd6kUCkcr+7L3qPWOfFFMBADFVTHV4deizrsRUMUYkEKm898VU7xn7pJgKALSLqT8dSHYMLjt+l6Qh9NT37Xyduxz60u9v0l5y6jMq3t9T97LzYb3ioT4pUk1775s3vHu8B8VUAEBMFVPFVDFVTBVTxVQxVUy1rswb3j3eg2IqACCmiqkON2KqmCqmiqliqpgqpoqpYqqYKqYCAGKqmOpwI6aKqWKqmGrfEFPFVDFVTBVTxVQAQEwVUx1uRBEx1YFWTBVTxVQxVUwVU8VUMRUAEFMBAAAAABBTAQAAAADEVAAAAAAAMRUAAAAAQEwFAAAAABBTAQAAAADEVAAAAAAAMRUAAAAAADEVAAAAAEBMBQAAAAAQUwEAAAAAxFQAAAAAADEVAAAAAEBMBQAAAAAQUwEAAAAAxFQAAAAAAMRUAAAAAAAxFQAAAABATAUAAAAAEFMBAAAAAMRUAAAAAAAxFQAAAABATAUAAAAAQEwFAAAAAPh//gZFPTu5uGIZdgAAAABJRU5ErkJggg==\";\n","/**\n * Read-path sanitizer for replayed conversation history (issue: orphaned\n * tool outputs brick a session).\n *\n * Conversation truth is persisted as a flat list of SDK history items in\n * `session_history_items` and replayed verbatim into the model on every turn.\n * The OpenAI Responses API rejects the whole request (HTTP 400) when that list\n * violates its tool-call pairing rules — most destructively:\n *\n * `400 No tool call found for function call output with call_id <X>`\n *\n * when a `function_call_result` (a.k.a. function_call_output) has no matching\n * `function_call` earlier in the list. Because the corrupt item is replayed on\n * every subsequent turn, one orphaned output permanently bricks the session\n * across revival — it stays dead until the row is hand-deleted.\n *\n * This module is the reliability net: before history items are sent to the\n * model they pass through `sanitizeHistoryItemsForModel`, which removes any\n * item that would make the request invalid. It mirrors the SDK's own\n * `dropOrphanToolCalls` continuation logic (which only runs over the SDK's\n * in-memory `state.history`, not over rows we reload from the database) so a\n * reloaded history is shaped exactly like a freshly-generated one.\n *\n * It is a pure function over plain JSON item shapes (no SDK import, no I/O) so\n * it is cheap to unit-test exhaustively. It NEVER mutates its input items and\n * NEVER touches the stored rows — only the in-memory copy sent to the model is\n * filtered, keeping the persisted audit trail intact.\n */\n\nimport { SCREENSHOT_FAILURE_CARD_IMAGE_URL } from \"./screenshot-error-card\";\nimport {\n boundModelToolOutputItems,\n DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n} from \"@opengeni/codex\";\n\n/** A history item is any JSON object; we only inspect a few discriminator fields. */\nexport type HistoryItem = Record<string, unknown>;\n\n/**\n * @deprecated Model-visible history is append-only outside the explicit\n * durable compaction transition. This compatibility identity function performs\n * no elision and returns the exact input array with every item untouched and in\n * its original order.\n */\nexport function elideSupersededViewImagePairs<T extends HistoryItem>(items: readonly T[]): T[] {\n return items as T[];\n}\n\n/**\n * Tool-call item types and the result-item type that settles them. Kept in\n * sync with the SDK's `TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE`; `function_call` is\n * the one observed live, the rest are included so the same pairing logic holds\n * for every tool-call kind the SDK can emit.\n */\nexport const TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE: Record<string, string> = {\n function_call: \"function_call_result\",\n computer_call: \"computer_call_result\",\n shell_call: \"shell_call_output\",\n apply_patch_call: \"apply_patch_call_output\",\n // Progressive connector disclosure (codex tool_search): a replayed\n // `tool_search_call` must be settled by its `tool_search_output` exactly like a\n // function call — an unpaired one 400s the store:false replay. The SDK pairs\n // these OUTSIDE its own TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE (sessionPersistence's\n // hasToolSearchCallId), so we mirror the semantics here; the correlation id can\n // additionally ride providerData (see callIdOf).\n tool_search_call: \"tool_search_output\",\n};\n\nconst RESULT_TYPE_BY_CALL_TYPE = TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE;\nconst RESULT_TYPES = new Set(Object.values(RESULT_TYPE_BY_CALL_TYPE));\n\nfunction itemType(item: unknown): string | undefined {\n if (!item || typeof item !== \"object\") {\n return undefined;\n }\n const type = (item as { type?: unknown }).type;\n return typeof type === \"string\" ? type : undefined;\n}\n\n/**\n * Correlation id for a tool call / result. The SDK's canonical history shape\n * uses camelCase `callId`; the raw Responses wire shape uses snake_case\n * `call_id`. Persisted rows are the SDK shape, but we accept either so a row\n * written by any code path (or hand-repaired) still correlates.\n */\nfunction callIdOf(item: unknown): string | undefined {\n if (!item || typeof item !== \"object\") {\n return undefined;\n }\n const record = item as { callId?: unknown; call_id?: unknown; providerData?: unknown };\n if (typeof record.callId === \"string\" && record.callId.length > 0) {\n return record.callId;\n }\n if (typeof record.call_id === \"string\" && record.call_id.length > 0) {\n return record.call_id;\n }\n // tool_search items may carry their correlation id ONLY in providerData\n // (mirrors the SDK's getToolSearchProviderCallId: providerData.call_id ??\n // providerData.callId ?? call_id ?? callId). Harmless for other item kinds —\n // their ids never live there.\n const provider = record.providerData as\n | { call_id?: unknown; callId?: unknown }\n | null\n | undefined;\n if (provider && typeof provider === \"object\") {\n if (typeof provider.call_id === \"string\" && provider.call_id.length > 0) {\n return provider.call_id;\n }\n if (typeof provider.callId === \"string\" && provider.callId.length > 0) {\n return provider.callId;\n }\n }\n return undefined;\n}\n\n/**\n * Sanitize a replayed history item list into a sequence the Responses API\n * accepts. Pure: returns a new array of the same item references in order,\n * with invalid items omitted. Valid histories come back byte-identical\n * (same references, same order).\n *\n * Rules, each motivated by a concrete 400 the API raises:\n *\n * 1. Drop every tool-call RESULT whose matching tool CALL does not appear\n * earlier in the list. This is the session-bricking orphan: a\n * `function_call_result` with no preceding `function_call` of the same\n * `call_id`. (\"No tool call found for function call output…\")\n *\n * 2. Drop every tool CALL that has no matching RESULT anywhere after it.\n * The Responses API requires each tool call to be settled by its output\n * before the conversation can continue; a dangling call left in replayed\n * history 400s with \"No tool output found for function call…\". Dropping\n * the dangling call (rather than synthesizing a fake output) is what the\n * SDK itself does for in-memory continuation, so a reloaded history is\n * shaped identically. The matching result, if it later exists, is kept;\n * only genuinely unpaired calls are removed.\n *\n * 3. Drop any `reasoning` item that immediately precedes (across a run of\n * reasoning items) a dropped tool call. The Responses API ties an\n * encrypted reasoning item to the tool call it produced; a reasoning item\n * orphaned by rule 2 trips \"Item 'rs_…' of type 'reasoning' was provided\n * without its required following item\". Mirrors the SDK's\n * `dropReasoningItemsPrecedingDroppedCalls`.\n *\n * A `call_id` is paired only when BOTH a call and a result of the matching\n * types exist with that id, the call appearing before the result. Calls and\n * results that satisfy that survive untouched.\n */\nexport function sanitizeHistoryItemsForModel<T extends HistoryItem>(\n items: readonly T[],\n toolOutputTruncationTokens = DEFAULT_MODEL_TOOL_OUTPUT_TRUNCATION_TOKENS,\n): T[] {\n if (items.length === 0) {\n return [];\n }\n\n // Pre-scan: for every (call-type, call_id) record the index of a RESULT that\n // appears strictly after the call. A call is valid only when such a result\n // exists; a result is valid only when its call appears strictly before it.\n // We resolve pairs in order so ordering is enforced both ways (a result that\n // precedes its call is an orphan, and a call whose only result precedes it is\n // dangling).\n const dropped = new Set<number>();\n\n // For each result-type, the call_ids of CALLs we have seen so far that are\n // still waiting to be settled by a following result.\n const openCallIdsByResultType = new Map<string, Set<string>>();\n\n items.forEach((item, index) => {\n const type = itemType(item);\n const callId = callIdOf(item);\n if (!type || !callId) {\n return;\n }\n const callResultType = RESULT_TYPE_BY_CALL_TYPE[type];\n if (callResultType) {\n const open = openCallIdsByResultType.get(callResultType) ?? new Set<string>();\n open.add(callId);\n openCallIdsByResultType.set(callResultType, open);\n return;\n }\n if (RESULT_TYPES.has(type)) {\n const open = openCallIdsByResultType.get(type);\n if (open && open.has(callId)) {\n // Settles a call we have already seen — keep both, close the call.\n open.delete(callId);\n } else {\n // Rule 1: result whose call is absent or appears later — the orphan.\n dropped.add(index);\n }\n }\n });\n\n // Rule 2: any call still open after the full scan has no result after it —\n // a dangling call the API rejects. Drop those calls. We re-walk to find the\n // indices of the still-open call_ids (the last unmatched call per id).\n const stillOpen = new Map<string, Set<string>>();\n for (const [resultType, open] of openCallIdsByResultType) {\n if (open.size > 0) {\n stillOpen.set(resultType, new Set(open));\n }\n }\n if (stillOpen.size > 0) {\n for (let index = items.length - 1; index >= 0; index -= 1) {\n const item = items[index];\n const type = itemType(item);\n const callId = callIdOf(item);\n if (!type || !callId) {\n continue;\n }\n const resultType = RESULT_TYPE_BY_CALL_TYPE[type];\n if (!resultType) {\n continue;\n }\n const open = stillOpen.get(resultType);\n if (open && open.has(callId)) {\n dropped.add(index);\n open.delete(callId);\n }\n }\n }\n\n if (dropped.size > 0) {\n // Rule 3: drop reasoning items stranded by a dropped tool call. A reasoning\n // item is stranded when the next non-reasoning item after it is dropped.\n for (let index = 0; index < items.length; index += 1) {\n if (dropped.has(index) || itemType(items[index]) !== \"reasoning\") {\n continue;\n }\n for (let next = index + 1; next < items.length; next += 1) {\n if (itemType(items[next]) === \"reasoning\") {\n continue;\n }\n if (dropped.has(next)) {\n dropped.add(index);\n }\n break;\n }\n }\n }\n\n const paired =\n dropped.size === 0 ? items.slice() : items.filter((_item, index) => !dropped.has(index));\n return boundModelToolOutputItems(\n paired.map(stripInternalResumeMarker),\n toolOutputTruncationTokens,\n );\n}\n\n/**\n * Internal marker stamping machine-generated resume/continuation messages\n * (turn-resumed notices, goal continuations) so compaction housekeeping can\n * recognize them in STORED history. Lives here (not context-compaction, which\n * imports from this module) so the wire sanitizer below can strip it without\n * an import cycle; context-compaction re-exports it.\n */\nexport const INTERNAL_RESUME_MESSAGE_MARKER = \"opengeni_internal_resume\";\n\n/**\n * Remove the {@link INTERNAL_RESUME_MESSAGE_MARKER} providerData key from a\n * single item before it reaches ANY model wire. Pure + non-mutating; returns\n * the SAME reference when there is nothing to strip (keeping the common path\n * byte-identical, mirroring {@link stripReasoningEncryptedContent}).\n *\n * WHY. The @openai/agents SDK serializes providerData keys verbatim into the\n * request item, and strict Responses backends reject unknown per-item fields —\n * observed in production as `400 Unknown parameter:\n * 'input[N].opengeni_internal_resume'`, which deterministically failed every\n * turn whose replayed history contained a marked resume message (the marker is\n * durable in conversation truth, so retries could never succeed). Detection\n * (isInternalResumeMessage) reads STORED items and also keeps a text-prefix\n * fallback, so stripping at the wire degrades housekeeping gracefully and\n * never the turn.\n */\nexport function stripInternalResumeMarker<T extends HistoryItem>(item: T): T {\n const providerData = (item as Record<string, unknown>).providerData;\n if (\n !providerData ||\n typeof providerData !== \"object\" ||\n !(INTERNAL_RESUME_MESSAGE_MARKER in (providerData as Record<string, unknown>))\n ) {\n return item;\n }\n const { [INTERNAL_RESUME_MESSAGE_MARKER]: _dropped, ...rest } = providerData as Record<\n string,\n unknown\n >;\n const next: Record<string, unknown> = { ...(item as Record<string, unknown>) };\n if (Object.keys(rest).length > 0) {\n next.providerData = rest;\n } else {\n delete next.providerData;\n }\n return next as T;\n}\n\n/**\n * Drop the account/org-bound `reasoning.encrypted_content` blob from a single\n * history item, preserving everything else (the visible chain-of-thought text in\n * `summary`/`content`, and every non-reasoning field). Pure + non-mutating: when\n * there is nothing to strip the SAME reference is returned (so the common,\n * same-account path stays byte-identical); otherwise a shallow clone is returned.\n *\n * WHY. A codex-subscription turn round-trips `reasoning.encrypted_content` — an\n * opaque blob minted by the ChatGPT/Codex backend that is bound to the account\n * (org) that produced it. After a manual switch from codex account A to B, the\n * carried history items still hold A-minted blobs; replaying them into a turn\n * running on B is rejected (400). The blob is purely a chain-of-thought\n * continuity optimization — dropping it costs at most one turn of lost CoT\n * continuity and never any message content.\n *\n * USED FOR `compaction` items only on the history-items read path: a foreign\n * `compaction` summary carries account-bound `encrypted_content` but its summary\n * is real conversation content that must be preserved, so we strip only the blob\n * (we do NOT drop the whole item). Foreign `reasoning` items are instead dropped\n * WHOLESALE by the caller (id + blob), because the Responses backend validates\n * the foreign `rs_…` id and rejects a reasoning item that has a foreign id and no\n * encrypted_content (so blanking the blob alone is not enough — see\n * {@link applyCodexHistoryStrip}).\n *\n * The SDK's Responses converter reads the blob via `providerData.encryptedContent`\n * (camel) or `providerData.encrypted_content` (snake); persisted rows use the\n * snake form, but we delete both casings defensively. We also clear a top-level\n * `encrypted_content` (the `compaction`-item shape) belt-and-braces — that blob\n * is likewise source-bound. Only `reasoning` and `compaction` items are touched;\n * messages, tool calls, and tool outputs pass through untouched by reference.\n */\nexport function stripReasoningEncryptedContent<T extends HistoryItem>(item: T): T {\n const type = itemType(item);\n if (type !== \"reasoning\" && type !== \"compaction\") {\n return item;\n }\n const record = item as Record<string, unknown>;\n const providerData = record.providerData;\n const providerHasBlob =\n !!providerData &&\n typeof providerData === \"object\" &&\n (\"encryptedContent\" in (providerData as Record<string, unknown>) ||\n \"encrypted_content\" in (providerData as Record<string, unknown>));\n const topLevelHasBlob = \"encrypted_content\" in record;\n if (!providerHasBlob && !topLevelHasBlob) {\n // Nothing encrypted to strip — return the same reference (byte-identical).\n return item;\n }\n const clone: Record<string, unknown> = { ...record };\n if (providerHasBlob) {\n const providerClone = { ...(providerData as Record<string, unknown>) };\n delete providerClone.encryptedContent;\n delete providerClone.encrypted_content;\n clone.providerData = providerClone;\n }\n if (topLevelHasBlob) {\n delete clone.encrypted_content;\n }\n return clone as unknown as T;\n}\n\n/**\n * Neutralize the account/org-bound identity of EVERY `reasoning` item embedded\n * in a serialized RunState JSON string, returning the re-serialized string. Pure:\n * a parse failure or a no-op returns the SAME string reference (so an unchanged\n * or non-codex run-state replays byte-for-byte).\n *\n * WHY (HOLE C — approval replay). An approval decision resumes the serialized\n * RunState blob. That blob round-trips `reasoning.encrypted_content` minted by the ChatGPT/Codex\n * backend (bound to the freezing account/org — a foreign account 400s it) AND the\n * foreign `rs_…` reasoning ids the Responses backend validates (rejected once the\n * blob is gone). Unlike `session_history_items`, the blob carries NO per-item\n * producer tag, so foreign-ness cannot be decided per item; the worker instead\n * records the FREEZING codex account on the run-state row and calls this only when\n * the resuming turn's codex account DIFFERS from it. When the accounts differ we\n * conservatively neutralize every reasoning item: delete its provider id and its\n * `encrypted_content` (both casings, in `providerData`). The visible reasoning\n * `content`/`summary` and every message / tool-call / tool-output item are left\n * intact (message and tool content are never account-bound).\n *\n * A reasoning item with no id and no encrypted_content is exactly the shape the\n * production Azure path already sends (see `stripProviderItemIdsFilter`), so it\n * deserializes and replays cleanly. Reasoning items live in several places in the\n * blob — `originalInput` (when an array), each `modelResponses[].output`,\n * `lastModelResponse.output`, and the `generatedItems` wrappers (`reasoning_item`\n * → `rawItem`) — and we scrub all of them. `compaction` items are deliberately\n * left untouched: their `encrypted_content` is a protocol-REQUIRED field whose\n * removal would fail the SDK's run-state schema validation on deserialize.\n */\nexport function stripReasoningIdentityFromSerializedRunState(serialized: string): string {\n let parsed: unknown;\n try {\n parsed = JSON.parse(serialized);\n } catch {\n // Not JSON (e.g. a cleared-state sentinel handled elsewhere): forward as-is.\n return serialized;\n }\n if (!parsed || typeof parsed !== \"object\") {\n return serialized;\n }\n let changed = false;\n const scrubReasoning = (candidate: unknown): void => {\n if (!candidate || typeof candidate !== \"object\") {\n return;\n }\n const record = candidate as Record<string, unknown>;\n if (record.type !== \"reasoning\") {\n return;\n }\n if (\"id\" in record) {\n delete record.id;\n changed = true;\n }\n const providerData = record.providerData;\n if (providerData && typeof providerData === \"object\") {\n const provider = providerData as Record<string, unknown>;\n if (\"encryptedContent\" in provider) {\n delete provider.encryptedContent;\n changed = true;\n }\n if (\"encrypted_content\" in provider) {\n delete provider.encrypted_content;\n changed = true;\n }\n }\n if (\"encrypted_content\" in record) {\n delete record.encrypted_content;\n changed = true;\n }\n };\n const scrubItemArray = (arr: unknown): void => {\n if (Array.isArray(arr)) {\n for (const item of arr) {\n scrubReasoning(item);\n }\n }\n };\n const root = parsed as Record<string, unknown>;\n // 1. originalInput is either a string (no items) or an array of protocol items.\n scrubItemArray(root.originalInput);\n // 2. generatedItems are SDK run-item wrappers; a `reasoning_item` carries the\n // protocol reasoning shape under `rawItem`.\n if (Array.isArray(root.generatedItems)) {\n for (const wrapper of root.generatedItems) {\n if (\n wrapper &&\n typeof wrapper === \"object\" &&\n \"rawItem\" in (wrapper as Record<string, unknown>)\n ) {\n scrubReasoning((wrapper as Record<string, unknown>).rawItem);\n }\n }\n }\n // 3. modelResponses[].output and lastModelResponse.output hold protocol items.\n const scrubResponseOutput = (response: unknown): void => {\n if (response && typeof response === \"object\") {\n scrubItemArray((response as Record<string, unknown>).output);\n }\n };\n if (Array.isArray(root.modelResponses)) {\n for (const response of root.modelResponses) {\n scrubResponseOutput(response);\n }\n }\n scrubResponseOutput(root.lastModelResponse);\n if (!changed) {\n return serialized;\n }\n return JSON.stringify(parsed);\n}\n\n/**\n * Neutralize tool_search items IN PLACE in a serialized RunState blob for a\n * cross-account codex resume — the run-state sibling of\n * `applyCodexHistoryStrip`'s tool_search rule, but COUNT-PRESERVING (HOLE E: the\n * blob path's reconcile watermark counts the blob's history length, so items\n * must never be removed — only mutated, exactly like the reasoning\n * neutralization above).\n *\n * The hazard: on deserialize, the SDK re-runs the registered CLIENT tool_search\n * execute callback per frozen pair (`rehydrateToolSearchRuntimeTools`) and\n * THROWS a UserError when the re-run's runtime-tool keys mismatch the serialized\n * expectation — which is exactly what happens when the RESUMING account's\n * connector pool differs from the FREEZING account's. The SDK skips that\n * rehydration entirely for `execution === 'server'` calls, so flipping the\n * frozen pairs' `execution` to `\"server\"` in place defuses the throw without\n * touching counts, ids, pairing, or content. The flipped shape is wire-safe:\n * LIVE-VERIFIED against /codex/responses — a replayed server-execution pair is\n * accepted (200) and its disclosure still holds. The account-bound `tsc_…` id is\n * separately stripped by the codex transport normalizer (all input item ids).\n *\n * Walks the same blob locations as {@link stripReasoningIdentityFromSerializedRunState}:\n * `originalInput` (array form), `generatedItems` (SDK run-item wrappers — the\n * raw shape under `rawItem`), every `modelResponses[].output`, and\n * `lastModelResponse.output`. Returns the input string unchanged when nothing\n * matched.\n */\nexport function neutralizeToolSearchItemsInSerializedRunState(serialized: string): string {\n let parsed: unknown;\n try {\n parsed = JSON.parse(serialized);\n } catch {\n return serialized;\n }\n if (!parsed || typeof parsed !== \"object\") {\n return serialized;\n }\n let changed = false;\n const neutralize = (candidate: unknown): void => {\n if (!candidate || typeof candidate !== \"object\") {\n return;\n }\n const record = candidate as Record<string, unknown>;\n if (record.type !== \"tool_search_call\" && record.type !== \"tool_search_output\") {\n return;\n }\n if (record.execution !== \"server\") {\n record.execution = \"server\";\n changed = true;\n }\n };\n const neutralizeArray = (arr: unknown): void => {\n if (Array.isArray(arr)) {\n for (const item of arr) {\n neutralize(item);\n }\n }\n };\n const root = parsed as Record<string, unknown>;\n neutralizeArray(root.originalInput);\n if (Array.isArray(root.generatedItems)) {\n for (const wrapper of root.generatedItems) {\n if (\n wrapper &&\n typeof wrapper === \"object\" &&\n \"rawItem\" in (wrapper as Record<string, unknown>)\n ) {\n neutralize((wrapper as Record<string, unknown>).rawItem);\n }\n }\n }\n const neutralizeResponseOutput = (response: unknown): void => {\n if (response && typeof response === \"object\") {\n neutralizeArray((response as Record<string, unknown>).output);\n }\n };\n if (Array.isArray(root.modelResponses)) {\n for (const response of root.modelResponses) {\n neutralizeResponseOutput(response);\n }\n }\n neutralizeResponseOutput(root.lastModelResponse);\n if (!changed) {\n return serialized;\n }\n return JSON.stringify(parsed);\n}\n\n/**\n * Normalize `computer_call` items so each carries EXACTLY ONE of the two\n * mutually-exclusive action fields the provider accepts.\n *\n * The OpenAI Agents SDK 0.11.6 `computer_call` schema (protocol.mjs) carries\n * BOTH the legacy singular `action` and the GA batched `actions`, each\n * `.optional()`, and only requires \"at least one\" (its superRefine errors only\n * when both are absent). The Azure computer-use endpoint is stricter: it\n * requires EXACTLY one and rejects the whole request with\n *\n * `400 Computer call input must include exactly one of `action` or `actions`.`\n *\n * when an emitted `computer_call` carries both (observed live: a screenshot\n * call carrying `action:{type:\"screenshot\"}` AND `actions:[{type:\"screenshot\"}]`).\n *\n * Which singular do we keep? LIVE-PROVEN against the deployed Azure deployment\n * (gpt-5.6-sol-2026-04-24): for gpt-5.6-sol the SDK serializes the GA computer tool as\n * `{type:\"computer\"}` (not the legacy `computer_use_preview`), and that GA tool\n * accepts ONLY the batched plural `actions`. Probing all three shapes:\n * - `action`-only -> 400 \"exactly one of action or actions\" (STILL rejected)\n * - `actions`-only -> passes the action/actions structural validation\n * - both -> 400 \"exactly one …\"\n * The \"exactly one\" wording is misleading: only the `actions`-only form is\n * accepted by the GA tool. So when both are present we KEEP `actions` (the GA\n * batched plural) and DROP `action`. Calls that already carry exactly one field\n * — or the legacy `action`-only form — pass through untouched (this transform's\n * sole job is to resolve the both-present conflict, not to rewrite singulars).\n *\n * Pure and non-mutating: only the conflicting item(s) are cloned; every other\n * item passes through by reference (byte-identical). Unlike\n * {@link sanitizeHistoryItemsForModel} (which only *filters* items), this is a\n * read-path *transform* of a single item's shape.\n */\nexport function normalizeComputerCallActions<T extends HistoryItem>(items: readonly T[]): T[] {\n let changed = false;\n const out = items.map((item) => {\n if (itemType(item) !== \"computer_call\") {\n return item;\n }\n const record = item as Record<string, unknown>;\n const hasAction = record.action !== undefined && record.action !== null;\n const hasActions = Array.isArray(record.actions) && (record.actions as unknown[]).length > 0;\n if (hasAction && hasActions) {\n changed = true;\n const { action: _droppedAction, ...rest } = record;\n return rest as unknown as T;\n }\n return item;\n });\n return changed ? out : items.slice();\n}\n\n/**\n * Rewrite EVERY `computer_call` item in a serialized Responses request body to\n * the ACTIONS-ONLY shape the GA Azure computer tool accepts, mutating the parsed\n * JSON object in place and returning whether anything changed.\n *\n * WHY THIS LIVES AT THE WIRE LEVEL (not the input-item filter). The input-item\n * normalizer above ({@link normalizeComputerCallActions}, wired as a\n * callModelInputFilter) runs BEFORE the SDK's responses converter\n * (`convertAgentItemToResponsesInput`). That converter then re-derives the wire\n * payload from the item: when `actions` is present it emits BOTH\n * `{action: ..., actions: [...]}`, and when only `action` is present it emits\n * `action`-only. It can NEVER emit actions-only. Probed live against the\n * deployed Azure gpt-5.6-sol-2026-04-24 GA computer tool (`{type:\"computer\"}`):\n * - `action`-only -> 400 \"Computer call input must include exactly one of\n * `action` or `actions`.\" (rejected)\n * - both -> 400 same message (rejected)\n * - `actions`-only -> passes the action/actions structural validation\n * So neither the input-filter nor the converter can produce an accepted body.\n * The ONLY seam that sees — and can rewrite — the final serialized JSON is a\n * custom `fetch` on the OpenAI client (it runs after the converter and after\n * `responses.create` serialization). This function is that rewriter's core.\n *\n * It collapses each computer_call to actions-only: it prefers an existing\n * non-empty `actions` array, else wraps the singular `action` into\n * `actions:[action]`, then deletes `action`. A computer_call with neither field\n * is left untouched (nothing to derive; let the provider report it).\n *\n * Mutates `body` in place (the caller has already JSON.parsed a private copy of\n * the request body). Returns `true` iff at least one computer_call was changed.\n */\nexport function rewriteComputerCallsToActionsOnly(body: unknown): boolean {\n if (!body || typeof body !== \"object\") {\n return false;\n }\n const input = (body as Record<string, unknown>).input;\n if (!Array.isArray(input)) {\n return false;\n }\n let changed = false;\n for (const item of input) {\n if (!item || typeof item !== \"object\") {\n continue;\n }\n const record = item as Record<string, unknown>;\n if (record.type !== \"computer_call\") {\n continue;\n }\n const existingActions =\n Array.isArray(record.actions) && (record.actions as unknown[]).length > 0\n ? (record.actions as unknown[])\n : undefined;\n const actions =\n existingActions ??\n (record.action !== undefined && record.action !== null ? [record.action] : undefined);\n if (actions === undefined) {\n // Neither action nor actions present: nothing to normalize.\n continue;\n }\n const hadAction = \"action\" in record;\n const actionsAlreadyExact = existingActions !== undefined && !hadAction;\n if (actionsAlreadyExact) {\n // Already actions-only with a non-empty array — leave byte-identical.\n continue;\n }\n delete record.action;\n record.actions = actions;\n changed = true;\n }\n return changed;\n}\n\n/**\n * Backstop for the empty `computer_call_output` image_url: walk the `input` array of\n * a serialized Responses request body and replace any `computer_call_output` item\n * whose `output.image_url` is empty/missing with a LEGIBLE \"screen capture failed\"\n * error card ({@link SCREENSHOT_FAILURE_CARD_IMAGE_URL}).\n *\n * WHY A CARD, NOT A BLANK. An empty `image_url` reaches this seam ONLY when the\n * computer op genuinely FAILED to produce a screen: agents-core's `toolExecution.mjs`\n * catch sets `output = ''` when the action OR the follow-up `computer.screenshot()`\n * throws, building `{type:\"computer_call_output\",output:{type:\"computer_screenshot\",\n * image_url:\"\"}}`. Azure then rejects the whole request with\n * `400 Invalid 'input[N].output.image_url'`. The previous fix substituted a 1×1\n * TRANSPARENT placeholder to dodge the 400 — but that reaches the model as a\n * plausible BLANK DESKTOP it confidently reports (\"the screen appears blank/empty\"),\n * turning a hard capture FAILURE into a silent, wrong observation. That is the worst\n * failure mode for computer use, and it is exactly what the 0.1.3 TCC-denied incident\n * produced. Substituting a legible error card instead makes the failure REACH THE\n * MODEL as an error (the only channel the hosted `computer_use_preview` protocol has\n * is the image), so the model stops and tells the user rather than hallucinating.\n *\n * WHY THIS IS SAFE (empty = failure, never an intentional blank). Post-af289e3 the\n * intentional-blank cases carry a NON-empty data URI already: agents-core's\n * tool-approval-rejection screenshot is its own non-empty 1×1 placeholder, and the\n * SandboxComputer action-timeout now warn+returns to a REAL screenshot rather than an\n * empty output. So an EMPTY image_url at this seam is unambiguously a capture/interact\n * FAILURE — the error card is the correct substitution for every empty case, and this\n * function never touches a non-empty (real screenshot OR intentional blank) output.\n *\n * The failure REASON (permission denied / null image / timeout / display down) is not\n * on the card; it is logged worker-side by `NativeDesktopComputer.screenshot()`.\n *\n * Mutates `body` in place (the caller has already JSON.parsed a private copy).\n * Returns `true` iff at least one image_url was replaced.\n */\nexport function rewriteEmptyComputerCallOutputImageUrls(body: unknown): boolean {\n if (!body || typeof body !== \"object\") {\n return false;\n }\n const input = (body as Record<string, unknown>).input;\n if (!Array.isArray(input)) {\n return false;\n }\n let changed = false;\n for (const item of input) {\n if (!item || typeof item !== \"object\") {\n continue;\n }\n const record = item as Record<string, unknown>;\n if (record.type !== \"computer_call_output\") {\n continue;\n }\n const output = record.output;\n if (!output || typeof output !== \"object\") {\n continue;\n }\n const out = output as Record<string, unknown>;\n const imageUrl = out.image_url;\n // Replace the image_url when it is not a non-empty string (covers: \"\", null,\n // undefined, missing) — an empty output is always a genuine capture failure, so\n // it becomes the legible error card, never a silent blank.\n if (typeof imageUrl !== \"string\" || imageUrl.length === 0) {\n out.image_url = SCREENSHOT_FAILURE_CARD_IMAGE_URL;\n changed = true;\n }\n }\n return changed;\n}\n\n/**\n * Wrap a `fetch` so every outbound OpenAI Responses request body that contains a\n * `computer_call` is rewritten to the ACTIONS-ONLY shape (see\n * {@link rewriteComputerCallsToActionsOnly}) before it reaches the network, AND\n * any `computer_call_output` item with an empty/missing `output.image_url` is\n * patched with the 1×1 transparent PNG placeholder (see\n * {@link rewriteEmptyComputerCallOutputImageUrls}).\n *\n * Installed as the `fetch:` option on the Azure OpenAI client, this is the\n * lowest reachable seam — below the agents-core input filter and below the SDK's\n * responses converter — so it neutralizes the converter's both-fields synthesis\n * regardless of what the input item carried, and backstops the action-timeout\n * empty image_url regardless of how it was produced.\n *\n * Surgical and cheap: it only parses the body when it is a string that contains\n * the prefix `\"computer_call` (matching both `\"computer_call\"` action items and\n * `\"computer_call_output\"` result items). Every other request — non-computer-use\n * turns, streaming SSE responses, non-string bodies — forwards untouched, the\n * SAME `init` reference, so streaming and other providers are unaffected. A JSON\n * parse failure or a no-op rewrite also forwards the original `init` unchanged.\n *\n * Typed structurally (the `(input, init) => Promise<Response>` call signature)\n * rather than as the DOM `typeof fetch` so it omits the `preconnect` static the\n * global type carries; this matches the OpenAI SDK's `Fetch` option, which only\n * needs the call signature. The wiring site passes it as the client `fetch:`.\n */\ntype FetchLike = (\n input: Parameters<typeof fetch>[0],\n init?: Parameters<typeof fetch>[1],\n) => Promise<Response>;\n\nexport function computerCallNormalizingFetch(base: FetchLike): FetchLike {\n return (input, init) => {\n // Match any request that mentions either `computer_call` (the action call) or\n // `computer_call_output` (the output/result item). Both strings begin with\n // `\"computer_call` so a single prefix-substring check covers both.\n if (init && typeof init.body === \"string\" && init.body.includes('\"computer_call')) {\n try {\n const parsed = JSON.parse(init.body) as unknown;\n const changed1 = rewriteComputerCallsToActionsOnly(parsed);\n const changed2 = rewriteEmptyComputerCallOutputImageUrls(parsed);\n if (changed1 || changed2) {\n return base(input, { ...init, body: JSON.stringify(parsed) });\n }\n } catch {\n // Non-JSON or parse failure: forward the request unchanged.\n }\n }\n return base(input, init);\n };\n}\n","// Progressive MCP disclosure for the ChatGPT/Codex backend — parity with how the\n// Codex CLI surfaces its ~217 `codex_apps` connector tools WITHOUT paying their\n// schemas in every turn's context, while applying the same bounded search seam to\n// other selected MCP servers.\n//\n// WHY. OpenGeni connects MCP servers as CLIENTs and the SDK materializes every\n// selected MCP tool as a `function` tool in request.tools[] on a Codex turn. The\n// Codex CLI instead uses the backend's NATIVE tool-search: the model gets one\n// compact search tool + deferred MCP tools (schemas dropped from model context),\n// searches by capability, and only matched tools are disclosed back and become\n// callable.\n//\n// PROVEN LIVE (Phase 0 probe against /codex/responses on gpt-5.6-sol): the backend\n// HONORS `defer_loading:true` on function tools — 50 fat tools dropped input_tokens\n// 6766 → 108 — AND makes a tool callable purely because a prior `tool_search_output`\n// disclosed it (V3). The model emits `tool_search_call` on our slug.\n//\n// HOW. We wrap the agent's `getAllTools` (codex turns only, flag-gated): tag every\n// non-mandatory MCP function tool `deferLoading = true` (converTool then serializes\n// `defer_loading:true`, dropping the schema from context) and append one\n// client-executed `toolSearchTool`. The SDK routes a `tool_search_call` to our\n// executor (ClientToolSearchExecutor), which BM25-ranks the deferred pool and\n// returns matched tools BY REFERENCE — the SDK emits the `tool_search_output` that\n// discloses them; the subsequent `function_call` resolves through the normal\n// `PrefixedMcpServer.callTool` path (auth + name-sanitize + structuredContent\n// inline all unchanged). Invocation is untouched; only the wire tool-set shrinks.\n\nimport { toolSearchTool, type Tool } from \"@openai/agents\";\nimport {\n MCP_MAX_TOOL_DEFINITION_BYTES,\n MCP_MAX_TOOL_SEARCH_DESCRIPTION_BYTES,\n MCP_MAX_TOOL_SEARCH_DISCLOSURE_BYTES,\n MCP_MAX_TOOL_SEARCH_SOURCE_LABEL_LENGTH,\n MCP_MAX_TOOL_SEARCH_SOURCES,\n mcpSerializedSizeBytes,\n} from \"./mcp-network\";\n\n/** The prefix OpenGeni's PrefixedMcpServer stamps on codex_apps connector tools. */\nexport const CODEX_APPS_TOOL_PREFIX = \"codex_apps__\";\nconst DEFAULT_SEARCH_LIMIT = 8;\nconst MAX_SEARCH_LIMIT = 20;\n\n/** True for a materialized codex_apps connector function tool. */\nexport function isCodexAppsFunctionTool(\n tool: unknown,\n): tool is Tool & { name: string; deferLoading?: boolean } {\n return (\n !!tool &&\n typeof tool === \"object\" &&\n (tool as { type?: unknown }).type === \"function\" &&\n typeof (tool as { name?: unknown }).name === \"string\" &&\n (tool as { name: string }).name.startsWith(CODEX_APPS_TOOL_PREFIX)\n );\n}\n\nconst MCP_TOOL_NAME_SEPARATOR = \"__\";\nconst MANDATORY_FIRST_PARTY_MCP_SERVER_ID = \"opengeni\";\nconst NO_MCP_SERVER_IDS: ReadonlySet<string> = new Set();\n\n/** Return the authorized server id for a runtime MCP function tool name. */\nfunction mcpServerIdForTool(tool: unknown, mcpServerIds: ReadonlySet<string>): string | null {\n if (!tool || typeof tool !== \"object\") return null;\n if ((tool as { type?: unknown }).type !== \"function\") return null;\n const name = (tool as { name?: unknown }).name;\n if (typeof name !== \"string\") return null;\n let match: string | null = null;\n for (const serverId of mcpServerIds) {\n if (\n typeof serverId !== \"string\" ||\n serverId.length === 0 ||\n !name.startsWith(`${serverId}${MCP_TOOL_NAME_SEPARATOR}`)\n ) {\n continue;\n }\n if (match === null || serverId.length > match.length) {\n match = serverId;\n }\n }\n return match;\n}\n\n/**\n * True for non-mandatory MCP function tools on the effective agent surface.\n * The prefix is the same runtime namespace used by PrefixedMcpServer; this\n * intentionally does not inspect the global registry, connection metadata, or\n * credentials, so search cannot widen the already-authorized tool set.\n */\nexport function isSearchableMcpFunctionTool(\n tool: unknown,\n mcpServerIds: ReadonlySet<string> = NO_MCP_SERVER_IDS,\n): tool is Tool & { name: string; deferLoading?: boolean } {\n const serverId = mcpServerIdForTool(tool, mcpServerIds);\n return serverId !== null && serverId !== MANDATORY_FIRST_PARTY_MCP_SERVER_ID;\n}\n\nfunction truncateUtf8(value: string, maxBytes: number): string {\n if (Buffer.byteLength(value) <= maxBytes) return value;\n let output = \"\";\n for (const character of value) {\n const candidate = output + character;\n if (Buffer.byteLength(candidate) > maxBytes) break;\n output = candidate;\n }\n return output;\n}\n\nfunction searchSourceForTool(tool: Tool, mcpServerIds: ReadonlySet<string>): string | null {\n const serverId = mcpServerIdForTool(tool, mcpServerIds);\n return serverId && serverId !== MANDATORY_FIRST_PARTY_MCP_SERVER_ID\n ? truncateUtf8(serverId, MCP_MAX_TOOL_SEARCH_SOURCE_LABEL_LENGTH)\n : null;\n}\n\nfunction searchSourcesForTools(\n connectorNamespaces: ReadonlySet<string>,\n tools: readonly Tool[],\n mcpServerIds: ReadonlySet<string>,\n): Set<string> {\n const sources = new Set<string>();\n for (const source of connectorNamespaces) {\n if (typeof source !== \"string\" || source.length === 0) continue;\n if (sources.size >= MCP_MAX_TOOL_SEARCH_SOURCES) break;\n sources.add(truncateUtf8(source, MCP_MAX_TOOL_SEARCH_SOURCE_LABEL_LENGTH));\n }\n for (const tool of tools) {\n // Codex connector labels come from the transport's original namespace set\n // (for example, `gmail`), not from the synthetic `codex_apps__` prefix.\n // Keep that authoritative path intact; derive fallback labels only for\n // directly materialized non-Codex MCP tools such as selected Slack tools.\n const source =\n isSearchableMcpFunctionTool(tool, mcpServerIds) && !isCodexAppsFunctionTool(tool)\n ? searchSourceForTool(tool, mcpServerIds)\n : null;\n if (!source || sources.has(source)) continue;\n if (sources.size >= MCP_MAX_TOOL_SEARCH_SOURCES) break;\n sources.add(source);\n }\n return sources;\n}\n\n// Minimal English stopword set: query phrasings like \"send an email to someone\"\n// should match on capability words, not drown in glue words (parity with\n// codex-rs, whose search normalizes tokens server-side).\nconst STOPWORDS = new Set([\n \"a\",\n \"an\",\n \"the\",\n \"and\",\n \"or\",\n \"of\",\n \"to\",\n \"in\",\n \"on\",\n \"for\",\n \"with\",\n \"by\",\n \"at\",\n \"is\",\n \"are\",\n \"be\",\n \"do\",\n \"does\",\n \"my\",\n \"me\",\n \"your\",\n \"you\",\n \"it\",\n \"its\",\n \"this\",\n \"that\",\n \"from\",\n \"as\",\n \"up\",\n \"out\",\n \"all\",\n \"some\",\n \"any\",\n \"can\",\n \"will\",\n \"would\",\n \"should\",\n \"want\",\n \"need\",\n \"please\",\n \"user\",\n \"users\",\n]);\n\n/** Light suffix stemmer so \"emails\"/\"email\", \"creating\"/\"create\" co-match (min-stem guards, no over-stripping). */\nfunction stem(token: string): string {\n if (token.length > 5 && token.endsWith(\"ing\")) return token.slice(0, -3);\n if (token.length > 4 && token.endsWith(\"ed\")) return token.slice(0, -2);\n if (token.length > 4 && token.endsWith(\"es\")) return token.slice(0, -2);\n if (token.length > 3 && token.endsWith(\"s\") && !token.endsWith(\"ss\")) return token.slice(0, -1);\n return token;\n}\n\n/** Split snake_case/camelCase/dotted text into stemmed lowercase word tokens (len ≥ 2, stopwords removed). */\nfunction tokenize(text: string): string[] {\n return text\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 1 && !STOPWORDS.has(t))\n .map(stem);\n}\n\n/** The searchable text of a connector tool: name (weighted ×2) + description + param names. */\nfunction toolSearchText(tool: Tool): string {\n const raw = (tool as { name?: string }).name ?? \"\";\n const name = raw.startsWith(CODEX_APPS_TOOL_PREFIX)\n ? raw.slice(CODEX_APPS_TOOL_PREFIX.length)\n : raw;\n const description =\n typeof (tool as { description?: unknown }).description === \"string\"\n ? (tool as { description: string }).description\n : \"\";\n const params = (tool as { parameters?: { properties?: Record<string, unknown> } }).parameters\n ?.properties;\n const paramNames = params && typeof params === \"object\" ? Object.keys(params).join(\" \") : \"\";\n return `${name} ${name} ${description} ${paramNames}`;\n}\n\n/**\n * Rank connector tools against a plain-language query with BM25 (Okapi, k1=1.5,\n * b=0.75) over tokenized name+description+params. Returns the top `limit` tools\n * with a positive score, most-relevant first. An empty or no-match query returns\n * [] — matching codex-rs, whose search returns empty rather than arbitrary tools;\n * disclosing unrelated (and thereby CALLABLE) tools on a miss feeds the model\n * noise. The SDK normalizes an empty executor result into an empty\n * tool_search_output, which the model reads as \"nothing matched — rephrase\".\n */\nexport function bm25RankTools(tools: Tool[], query: string, limit: number): Tool[] {\n const qTokens = Array.from(new Set(tokenize(query)));\n if (tools.length === 0 || qTokens.length === 0) return [];\n\n const docs = tools.map((tool) => {\n const tokens = tokenize(toolSearchText(tool));\n const tf = new Map<string, number>();\n for (const t of tokens) tf.set(t, (tf.get(t) ?? 0) + 1);\n return { tool, len: tokens.length, tf };\n });\n const N = docs.length;\n const avgdl = Math.max(1, docs.reduce((s, d) => s + d.len, 0) / N);\n const df = new Map<string, number>();\n for (const d of docs) for (const t of d.tf.keys()) df.set(t, (df.get(t) ?? 0) + 1);\n\n const k1 = 1.5;\n const b = 0.75;\n const scored = docs.map((d) => {\n let score = 0;\n for (const qt of qTokens) {\n const n = df.get(qt);\n const f = d.tf.get(qt);\n if (!n || !f) continue;\n const idf = Math.log(1 + (N - n + 0.5) / (n + 0.5));\n score += idf * ((f * (k1 + 1)) / (f + k1 * (1 - b + (b * d.len) / avgdl)));\n }\n return { tool: d.tool, score };\n });\n const hits = scored.filter((s) => s.score > 0).sort((a, b2) => b2.score - a.score);\n return hits.slice(0, limit).map((s) => s.tool); // no hits ⇒ [] (codex-rs parity; see doc)\n}\n\n/** Parse `{query, limit}` from a tool_search_call's arguments (string or object). */\nfunction parseSearchArgs(raw: unknown): { query: string; limit: number } {\n let obj: Record<string, unknown> = {};\n try {\n obj =\n typeof raw === \"string\"\n ? raw.length\n ? JSON.parse(raw)\n : {}\n : raw && typeof raw === \"object\"\n ? (raw as Record<string, unknown>)\n : {};\n } catch {\n obj = {};\n }\n const query = typeof obj.query === \"string\" ? obj.query : \"\";\n const limitRaw =\n typeof obj.limit === \"number\" && Number.isFinite(obj.limit) ? obj.limit : DEFAULT_SEARCH_LIMIT;\n return { query, limit: Math.max(1, Math.min(MAX_SEARCH_LIMIT, Math.round(limitRaw))) };\n}\n\n/**\n * Render the search tool's description from the account's ACTUALLY-connected\n * sources — codex-rs parity (its create_tool_search_tool builds \"You have access\n * to tools from the following sources:\\n- <name>\" from the live enabled-source\n * list). With defer_loading stripping every connector schema (and name) from\n * model context, this description is the model's ONLY signal of which apps\n * exist, so a hardcoded list would both advertise absent connectors and hide\n * present ones.\n */\nexport function renderSearchToolDescription(connectorNamespaces: ReadonlySet<string>): string {\n const base =\n \"Search the user's connected app tools by capability. \" +\n 'Describe in plain language WHAT you need to do (for example: \"send an email\", \"create a calendar event\") ' +\n \"rather than guessing exact tool names. Returns the matching connector tools, which then become callable.\";\n const sources = Array.from(connectorNamespaces)\n .filter((n) => typeof n === \"string\" && n.length > 0)\n .slice(0, MCP_MAX_TOOL_SEARCH_SOURCES)\n .map((source) => truncateUtf8(source, MCP_MAX_TOOL_SEARCH_SOURCE_LABEL_LENGTH))\n .filter(Boolean)\n .sort();\n if (sources.length === 0) {\n return `${base}\\nConnected sources: none currently available.`;\n }\n const header = `${base}\\nYou have access to tools from the following sources:`;\n const lines: string[] = [];\n for (const source of sources) {\n const candidate = `${header}${[...lines, `- ${source}`].map((line) => `\\n${line}`).join(\"\")}`;\n if (Buffer.byteLength(candidate) > MCP_MAX_TOOL_SEARCH_DESCRIPTION_BYTES) break;\n lines.push(`- ${source}`);\n }\n return lines.length > 0\n ? `${header}\\n${lines.join(\"\\n\")}`\n : `${base}\\nConnected sources: none currently available.`;\n}\n\nconst SEARCH_TOOL_PARAMETERS = {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"Plain-language description of the capability you need.\",\n },\n limit: { type: \"number\", description: \"Maximum number of tools to return (default 8).\" },\n },\n required: [\"query\"],\n additionalProperties: false,\n} as const;\n\n/**\n * The client tool-search executor: BM25 over the deferred MCP pool from the\n * turn's live `availableTools`, returning matched tools BY REFERENCE (the only legal\n * return — the SDK emits the disclosing `tool_search_output` and flips the loaded\n * gate; returning copies would throw). Stateless — reads the pool per call.\n */\nfunction codexToolSearchExecutor(\n args: {\n availableTools?: Tool[];\n toolCall?: { arguments?: unknown };\n },\n mcpServerIds: ReadonlySet<string>,\n): Tool[] {\n const deferred = (args.availableTools ?? []).filter((tool) =>\n isSearchableMcpFunctionTool(tool, mcpServerIds),\n );\n if (deferred.length === 0) return [];\n const { query, limit } = parseSearchArgs(args.toolCall?.arguments);\n const ranked = bm25RankTools(deferred, query, limit);\n const bounded: Tool[] = [];\n let disclosedBytes = 0;\n for (const tool of ranked) {\n const toolBytes = mcpSerializedSizeBytes(tool);\n if (toolBytes > MCP_MAX_TOOL_DEFINITION_BYTES) {\n continue;\n }\n if (disclosedBytes + toolBytes > MCP_MAX_TOOL_SEARCH_DISCLOSURE_BYTES) {\n break;\n }\n disclosedBytes += toolBytes;\n bounded.push(tool);\n }\n return bounded;\n}\n\nconst NO_NAMESPACES: ReadonlySet<string> = new Set();\n\n/** True when the namespace set contains at least one usable (non-empty string) source — mirrors {@link renderSearchToolDescription}'s filter, so it is TRUE exactly when the render produces the \"following sources\" list and FALSE when it produces \"none currently available\". */\nfunction hasConnectorSources(connectorNamespaces: ReadonlySet<string>): boolean {\n for (const namespace of connectorNamespaces) {\n if (typeof namespace === \"string\" && namespace.length > 0) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * A per-TURN freeze cell for the tool_search description (AM-8). The connector Set\n * `installCodexToolSearch` reads is LIVE and by-reference — it fills as the turn's\n * codex_apps tools/list resolves and can change between a turn's model calls.\n * Re-rendering the description per call from a changed Set flips the tools block,\n * and because tools precede the history in the request prefix, ANY change misses the\n * ENTIRE conversation prefix from that point on — a proven prompt-cache breaker.\n *\n * We therefore freeze the description ONCE, at the first model call whose Set has\n * been populated (connectors discovered), and reuse that frozen string for the rest\n * of the turn — trading a slightly staler connector list for a byte-stable prefix.\n * The freeze is created per {@link installCodexToolSearch} (once per turn) and shared\n * by reference into every clone re-install, so all of a turn's clones agree.\n */\nexport type CodexToolSearchDescriptionFreeze = { value: string | null };\n\n/**\n * Resolve the tool_search description for this model call, honoring the per-turn\n * freeze (AM-8):\n * - Already frozen ⇒ return the frozen string (byte-stable for the rest of the turn).\n * - Not yet frozen + connectors DISCOVERED (non-empty Set) ⇒ render and FREEZE it,\n * locking the discovered list against a later same-turn Set mutation.\n * - Not yet frozen + Set still EMPTY ⇒ render live (\"none currently available\") but\n * do NOT freeze. This is the load-bearing safety of AM-8: the Set fills lazily and\n * best-effort, so an empty Set means \"not discovered yet\", not \"no connectors\".\n * Freezing \"none\" here would silently disable the turn's connectors (capability\n * loss). Leaving it unfrozen is still byte-stable while the Set stays empty (the\n * empty render is a constant), and lets a later call freeze the real list once it\n * resolves — at most ONE prefix transition, versus today's per-call churn.\n * With no freeze cell (the default / direct callers + tests) this is a live render,\n * byte-for-byte the pre-AM-8 behavior.\n */\nfunction resolveSearchToolDescription(\n connectorNamespaces: ReadonlySet<string>,\n freeze?: CodexToolSearchDescriptionFreeze,\n): string {\n if (freeze?.value != null) {\n return freeze.value;\n }\n const rendered = renderSearchToolDescription(connectorNamespaces);\n if (freeze && hasConnectorSources(connectorNamespaces)) {\n freeze.value = rendered;\n }\n return rendered;\n}\n\n/** Build the client-executed tool_search tool from an already-rendered description. */\nfunction buildCodexToolSearchToolFromDescription(\n description: string,\n mcpServerIds: ReadonlySet<string>,\n): Tool {\n return toolSearchTool({\n execution: \"client\",\n description,\n parameters: SEARCH_TOOL_PARAMETERS as unknown as Record<string, unknown>,\n execute: ((args: Parameters<typeof codexToolSearchExecutor>[0]) =>\n codexToolSearchExecutor(args, mcpServerIds)) as never,\n }) as unknown as Tool;\n}\n\n/** Build the client-executed tool_search tool that discloses deferred MCP tools on demand. */\nexport function buildCodexToolSearchTool(\n connectorNamespaces: ReadonlySet<string> = NO_NAMESPACES,\n mcpServerIds: ReadonlySet<string> = NO_MCP_SERVER_IDS,\n): Tool {\n return buildCodexToolSearchToolFromDescription(\n renderSearchToolDescription(connectorNamespaces),\n mcpServerIds,\n );\n}\n\n/** True for the built-in tool_search tool (so we never add a second one). */\nfunction isToolSearchTool(tool: unknown): boolean {\n const t = tool as { name?: unknown; providerData?: { type?: unknown } } | null;\n return !!t && (t.name === \"tool_search\" || t.providerData?.type === \"tool_search\");\n}\n\n/**\n * The transform applied to a turn's resolved tool list: tag every searchable\n * non-mandatory MCP function tool `deferLoading = true`, and — unless one is already\n * present — append the client tool_search tool. Pure (mutates the passed tools +\n * returns the possibly-extended array); the SDK's `getTools` gate requires a\n * tool_search whenever a deferred tool is present, which appending here satisfies\n * in the same request.\n *\n * The search tool is appended UNCONDITIONALLY (even when the turn has no\n * searchable MCP tools, e.g. a best-effort connector was dropped this\n * turn): a prior turn's history may carry tool_search_call/output items, and\n * replaying those without a tool_search tool in the request risks a backend\n * reject; a search over an empty pool simply discloses nothing. The description\n * reflects the LIVE connector namespaces, so an empty turn reads\n * \"none currently available\".\n */\nexport function applyCodexToolSearch(\n tools: Tool[],\n connectorNamespaces: ReadonlySet<string> = NO_NAMESPACES,\n descriptionFreeze?: CodexToolSearchDescriptionFreeze,\n mcpServerIds: ReadonlySet<string> = NO_MCP_SERVER_IDS,\n): Tool[] {\n for (const tool of tools) {\n if (\n isSearchableMcpFunctionTool(tool, mcpServerIds) &&\n (tool as { deferLoading?: boolean }).deferLoading !== true\n ) {\n (tool as { deferLoading?: boolean }).deferLoading = true;\n }\n }\n if (tools.some(isToolSearchTool)) {\n return tools;\n }\n // AM-8: render through the per-turn freeze so the tools-block prefix stays\n // byte-stable across a turn's model calls once connectors are discovered.\n const description = resolveSearchToolDescription(\n searchSourcesForTools(connectorNamespaces, tools, mcpServerIds),\n descriptionFreeze,\n );\n return [...tools, buildCodexToolSearchToolFromDescription(description, mcpServerIds)];\n}\n\ntype CloneCapableAgent = {\n getAllTools: (runContext: unknown) => Promise<Tool[]>;\n clone?: (config: unknown) => CloneCapableAgent;\n};\n\n/**\n * Install progressive MCP disclosure on a Codex-path agent by wrapping\n * `getAllTools` so every per-model-call tool resolution runs\n * {@link applyCodexToolSearch}. Idempotent-per-call (re-tags each\n * freshly-materialized MCP tool under cacheToolsList:false). Gated by the caller\n * (flag + Codex path).\n *\n * CLONE SURVIVAL (the part that makes this work on the REAL sandbox path): the\n * SDK's sandbox runtime routes EVERY model call through\n * `prepareSandboxAgent → agent.clone(...)` (agentPreparation.js), and\n * `SandboxAgent.clone` constructs a FRESH agent from a fixed field list — an\n * instance-own `getAllTools` override is NOT copied, so patching only this\n * instance would silently no-op the whole feature on sandbox turns (the run\n * loop resolves tools on the CLONE). We therefore also wrap `clone` to\n * RE-INSTALL onto every clone, recursively — covering clone-of-clone and the\n * RunState resume paths. `connectorNamespaces` is the LIVE, by-reference Set the\n * codex_apps sanitizing transport fills during each turn's tools/list\n * (prepareAgentTools), so by the time the wrapper post-processes getAllTools the\n * current turn's connector sources are known.\n */\nexport function installCodexToolSearch(\n agent: CloneCapableAgent,\n connectorNamespaces: ReadonlySet<string> = NO_NAMESPACES,\n mcpServerIds: ReadonlySet<string> = NO_MCP_SERVER_IDS,\n): void {\n // ONE freeze cell per install (i.e. per turn), shared BY REFERENCE into every\n // clone re-install below so the whole turn — the built agent and every clone the\n // sandbox runtime resolves tools on — agrees on the same frozen description\n // (AM-8). Created here, at the top-level install, never per clone.\n installCodexToolSearchWithFreeze(agent, connectorNamespaces, mcpServerIds, { value: null });\n}\n\nfunction installCodexToolSearchWithFreeze(\n agent: CloneCapableAgent,\n connectorNamespaces: ReadonlySet<string>,\n mcpServerIds: ReadonlySet<string>,\n descriptionFreeze: CodexToolSearchDescriptionFreeze,\n): void {\n const originalGetAllTools = agent.getAllTools.bind(agent);\n agent.getAllTools = (async (runContext: unknown) =>\n applyCodexToolSearch(\n await originalGetAllTools(runContext),\n connectorNamespaces,\n descriptionFreeze,\n mcpServerIds,\n )) as typeof agent.getAllTools;\n const originalClone = agent.clone?.bind(agent);\n if (originalClone) {\n const cloneWithToolSearch: NonNullable<CloneCapableAgent[\"clone\"]> = (config: unknown) => {\n const cloned = originalClone(config);\n installCodexToolSearchWithFreeze(\n cloned,\n connectorNamespaces,\n mcpServerIds,\n descriptionFreeze,\n );\n return cloned;\n };\n agent.clone = cloneWithToolSearch;\n }\n}\n","/**\n * Portable conversation context compaction, following Codex CLI's local path.\n *\n * The checkpoint model sees the current active history plus one fixed\n * checkpoint prompt, then the active history is rebuilt from the newest real\n * user messages within one cumulative 20k-token budget plus one summary.\n * Assistant messages, tool calls/results, reasoning, and images are removed\n * from the active model-facing history; the database audit rows remain.\n */\n\nimport {\n TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE,\n sanitizeHistoryItemsForModel,\n} from \"./history-sanitizer\";\nimport { boundModelToolOutputItem } from \"@opengeni/codex\";\nimport { createHash } from \"node:crypto\";\n\nexport type CompactionItem = Record<string, unknown>;\n\n/**\n * Marker stored on the synthetic summary item so the UI can render it and the\n * next rebuild can exclude old summaries from the retained user-message set.\n */\nexport const COMPACTION_SUMMARY_MARKER = \"opengeni_context_summary\";\n\nexport const SUMMARY_BUFFER_TOKENS = 20_000;\n// A single cumulative budget for all retained real user messages, matching\n// Codex core's build_compacted_history_with_limit (not a per-message allowance).\nexport const COMPACT_USER_MESSAGE_MAX_TOKENS = 20_000;\n/** Codex CLI remote compaction v2 retained-message budget (codex-rs). */\nexport const REMOTE_V2_RETAINED_MESSAGE_TOKEN_BUDGET = 64_000;\nexport const REMOTE_COMPACTION_V2_IMPLEMENTATION = \"responses_compaction_v2\" as const;\nexport const REMOTE_COMPACTION_V2_BETA_FEATURE = \"remote_compaction_v2\" as const;\n// 0.9: compact as LATE as possible — retained context is worth more than early\n// headroom now that declared per-model windows are honest. Model-catalog\n// explicit limits take precedence; the ratio is used for models without one.\nexport const DEFAULT_COMPACTION_THRESHOLD_RATIO = 0.9;\nexport const MIN_COMPACTION_THRESHOLD_RATIO = 0.3;\nexport const MAX_COMPACTION_THRESHOLD_RATIO = 0.9;\n\n// Verbatim from Codex CLI:\n// codex-rs/prompts/templates/compact/prompt.md\nexport const COMPACTION_PROMPT = [\n \"You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.\",\n \"\",\n \"Include:\",\n \"- Current progress and key decisions made\",\n \"- Important context, constraints, or user preferences\",\n \"- What remains to be done (clear next steps)\",\n \"- Any critical data, examples, or references needed to continue\",\n \"\",\n \"Be concise, structured, and focused on helping the next LLM seamlessly continue the work.\",\n].join(\"\\n\");\n\n// Verbatim from Codex CLI:\n// codex-rs/prompts/templates/compact/summary_prefix.md\nexport const SUMMARY_PREFIX =\n \"Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:\";\n\nexport const USER_MESSAGE_TRUNCATION_MARKER =\n \"\\n[... middle truncated for context compaction ...]\\n\";\n\nconst RESULT_TYPE_BY_CALL_TYPE = TOOL_CALL_RESULT_TYPE_BY_CALL_TYPE;\nconst RESULT_TYPES = new Set(Object.values(RESULT_TYPE_BY_CALL_TYPE));\nconst MODEL_GENERATED_ITEM_TYPES = new Set([\n \"reasoning\",\n \"function_call\",\n \"custom_tool_call\",\n \"tool_search_call\",\n \"web_search_call\",\n \"image_generation_call\",\n \"computer_call\",\n \"shell_call\",\n \"apply_patch_call\",\n \"compaction\",\n \"context_compaction\",\n]);\n\nfunction itemType(item: unknown): string | undefined {\n if (!item || typeof item !== \"object\") {\n return undefined;\n }\n const type = (item as { type?: unknown }).type;\n return typeof type === \"string\" ? type : undefined;\n}\n\nfunction itemRole(item: unknown): string | undefined {\n if (!item || typeof item !== \"object\") {\n return undefined;\n }\n const role = (item as { role?: unknown }).role;\n return typeof role === \"string\" ? role : undefined;\n}\n\n/** A user-authored `message` item is the only legal turn boundary. */\nexport function isUserMessage(item: unknown): boolean {\n return itemType(item) === \"message\" && itemRole(item) === \"user\";\n}\n\n/** True for our synthetic compaction summary item. */\nexport function isCompactionSummary(item: unknown): boolean {\n return (\n isUserMessage(item) && (item as Record<string, unknown>)[COMPACTION_SUMMARY_MARKER] === true\n );\n}\n\n/**\n * Conservative tokenizer-independent text estimate used for every local input\n * budget. Preserve the stable ASCII `chars / 4` heuristic, but never discount\n * Unicode as UTF-16 length/4: each non-ASCII code unit costs at least one token\n * (CJK ≈ 1/code point; an astral emoji's surrogate pair ≈ 2). This intentionally\n * errs toward compaction rather than letting multilingual current input exceed\n * a provider context window before an authoritative usage anchor exists.\n */\nexport function estimateTextTokens(text: string): number {\n let asciiCodeUnits = 0;\n let nonAsciiCodeUnits = 0;\n for (let index = 0; index < text.length; index += 1) {\n if (text.charCodeAt(index) <= 0x7f) asciiCodeUnits += 1;\n else nonAsciiCodeUnits += 1;\n }\n return nonAsciiCodeUnits + Math.ceil(asciiCodeUnits / 4);\n}\n\nconst IMAGE_LOW_DETAIL_TOKENS = 85;\nconst IMAGE_HIGH_DETAIL_BASE_TOKENS = 85;\nconst IMAGE_HIGH_DETAIL_TILE_TOKENS = 170;\nconst IMAGE_HIGH_DETAIL_TILE_SIZE = 512;\nconst IMAGE_HIGH_DETAIL_MAX_SIDE = 2_048;\nconst IMAGE_HIGH_DETAIL_TARGET_SHORT_SIDE = 768;\nexport const UNKNOWN_IMAGE_TOKENS = 4_096;\nexport const MAX_NATIVE_IMAGE_TOKENS = 8_192;\n\nexport type NativeImageEstimateReason = \"dimensions\" | \"bounded_fallback\";\nexport type NativeImageTokenEstimate = {\n tokens: number;\n width: number | null;\n height: number | null;\n detail: string;\n reason: NativeImageEstimateReason;\n};\n\nexport type ModelInputTokenBreakdown = {\n totalTokens: number;\n textTokens: number;\n imageTokens: number;\n imageCount: number;\n imageFallbackCount: number;\n};\n\ntype ImageDescriptor = {\n source: unknown;\n detail: string;\n width: number | null;\n height: number | null;\n};\n\ntype NativeImageProjection = {\n value: unknown;\n imageTokens: number;\n imageCount: number;\n imageFallbackCount: number;\n};\n\nfunction finitePositiveInteger(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0\n ? Math.floor(value)\n : null;\n}\n\nfunction dimensionsFromRecord(record: Record<string, unknown>): [number, number] | null {\n const width = finitePositiveInteger(record.width);\n const height = finitePositiveInteger(record.height);\n if (width && height) return [width, height];\n if (Array.isArray(record.dimensions) && record.dimensions.length >= 2) {\n const dimensionsWidth = finitePositiveInteger(record.dimensions[0]);\n const dimensionsHeight = finitePositiveInteger(record.dimensions[1]);\n if (dimensionsWidth && dimensionsHeight) return [dimensionsWidth, dimensionsHeight];\n }\n return null;\n}\n\nfunction dataUrlBytesPrefix(value: string, maxBytes = 262_144): Uint8Array | null {\n const match = /^data:image\\/[a-z0-9.+-]+;base64,([a-z0-9+/=\\r\\n]+)$/i.exec(value);\n if (!match) return null;\n try {\n const maxBase64CodeUnits = Math.ceil(maxBytes / 3) * 4;\n return new Uint8Array(Buffer.from(match[1]!.slice(0, maxBase64CodeUnits), \"base64\"));\n } catch {\n return null;\n }\n}\n\nfunction base64BytesPrefix(value: string, maxBytes = 262_144): Uint8Array | null {\n if (!/^[a-z0-9+/=\\r\\n]+$/i.test(value)) return null;\n try {\n const maxBase64CodeUnits = Math.ceil(maxBytes / 3) * 4;\n return new Uint8Array(Buffer.from(value.slice(0, maxBase64CodeUnits), \"base64\"));\n } catch {\n return null;\n }\n}\n\nfunction uint16BigEndian(bytes: Uint8Array, offset: number): number {\n return ((bytes[offset] ?? 0) << 8) | (bytes[offset + 1] ?? 0);\n}\n\nfunction uint32BigEndian(bytes: Uint8Array, offset: number): number {\n return (\n ((bytes[offset] ?? 0) * 0x1000000 +\n ((bytes[offset + 1] ?? 0) << 16) +\n ((bytes[offset + 2] ?? 0) << 8) +\n (bytes[offset + 3] ?? 0)) >>>\n 0\n );\n}\n\nfunction crc32(bytes: Uint8Array, start: number, end: number): number {\n let crc = 0xffff_ffff;\n for (let offset = start; offset < end; offset += 1) {\n crc ^= bytes[offset] ?? 0;\n for (let bit = 0; bit < 8; bit += 1) {\n crc = (crc >>> 1) ^ (crc & 1 ? 0xedb8_8320 : 0);\n }\n }\n return (crc ^ 0xffff_ffff) >>> 0;\n}\n\nfunction dimensionsFromImageBytes(bytes: Uint8Array): [number, number] | null {\n // PNG IHDR: trust geometry only from a complete first IHDR chunk whose CRC32\n // authenticates the 4-byte chunk type plus 13-byte data. This inspects exactly\n // the bounded 33-byte prefix and never decodes the rest of the image.\n if (\n bytes.length >= 33 &&\n bytes[0] === 0x89 &&\n bytes[1] === 0x50 &&\n bytes[2] === 0x4e &&\n bytes[3] === 0x47 &&\n bytes[4] === 0x0d &&\n bytes[5] === 0x0a &&\n bytes[6] === 0x1a &&\n bytes[7] === 0x0a &&\n uint32BigEndian(bytes, 8) === 13 &&\n bytes[12] === 0x49 &&\n bytes[13] === 0x48 &&\n bytes[14] === 0x44 &&\n bytes[15] === 0x52 &&\n crc32(bytes, 12, 29) === uint32BigEndian(bytes, 29)\n ) {\n const width = uint32BigEndian(bytes, 16);\n const height = uint32BigEndian(bytes, 20);\n return width > 0 && height > 0 ? [width, height] : null;\n }\n // GIF logical screen descriptor.\n if (\n bytes.length >= 10 &&\n bytes[0] === 0x47 &&\n bytes[1] === 0x49 &&\n bytes[2] === 0x46 &&\n bytes[3] === 0x38\n ) {\n const width = (bytes[6] ?? 0) | ((bytes[7] ?? 0) << 8);\n const height = (bytes[8] ?? 0) | ((bytes[9] ?? 0) << 8);\n return width > 0 && height > 0 ? [width, height] : null;\n }\n // WebP VP8X canvas size (24-bit little-endian, stored minus one).\n if (\n bytes.length >= 30 &&\n bytes[0] === 0x52 &&\n bytes[1] === 0x49 &&\n bytes[2] === 0x46 &&\n bytes[3] === 0x46 &&\n bytes[8] === 0x57 &&\n bytes[9] === 0x45 &&\n bytes[10] === 0x42 &&\n bytes[11] === 0x50 &&\n bytes[12] === 0x56 &&\n bytes[13] === 0x50 &&\n bytes[14] === 0x38 &&\n bytes[15] === 0x58\n ) {\n const width = 1 + (bytes[24] ?? 0) + ((bytes[25] ?? 0) << 8) + ((bytes[26] ?? 0) << 16);\n const height = 1 + (bytes[27] ?? 0) + ((bytes[28] ?? 0) << 8) + ((bytes[29] ?? 0) << 16);\n return width > 0 && height > 0 ? [width, height] : null;\n }\n // JPEG SOF markers can appear after variable-length metadata segments.\n if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {\n let offset = 2;\n while (offset + 8 < bytes.length) {\n if (bytes[offset] !== 0xff) {\n offset += 1;\n continue;\n }\n const marker = bytes[offset + 1] ?? 0;\n offset += 2;\n if (marker === 0xd8 || marker === 0xd9 || marker === 0x01) continue;\n if (marker >= 0xd0 && marker <= 0xd7) continue;\n if (offset + 2 > bytes.length) break;\n const segmentLength = uint16BigEndian(bytes, offset);\n if (segmentLength < 2 || offset + segmentLength > bytes.length) break;\n const isStartOfFrame =\n (marker >= 0xc0 && marker <= 0xc3) ||\n (marker >= 0xc5 && marker <= 0xc7) ||\n (marker >= 0xc9 && marker <= 0xcb) ||\n (marker >= 0xcd && marker <= 0xcf);\n if (isStartOfFrame && segmentLength >= 7) {\n const height = uint16BigEndian(bytes, offset + 3);\n const width = uint16BigEndian(bytes, offset + 5);\n return width > 0 && height > 0 ? [width, height] : null;\n }\n offset += segmentLength;\n }\n }\n return null;\n}\n\nfunction dimensionsFromImageSource(source: unknown): [number, number] | null {\n if (source instanceof Uint8Array) {\n return dimensionsFromImageBytes(source);\n }\n if (typeof source === \"string\") {\n const bytes = dataUrlBytesPrefix(source);\n return bytes ? dimensionsFromImageBytes(bytes) : null;\n }\n if (!source || typeof source !== \"object\") return null;\n const record = source as Record<string, unknown>;\n const rawData = record.data;\n const mediaType = record.mediaType ?? record.media_type;\n const rawDataDimensions =\n rawData instanceof Uint8Array\n ? dimensionsFromImageBytes(rawData)\n : typeof rawData === \"string\" &&\n typeof mediaType === \"string\" &&\n mediaType.toLowerCase().startsWith(\"image/\")\n ? dimensionsFromImageBytes(base64BytesPrefix(rawData) ?? new Uint8Array())\n : null;\n return (\n dimensionsFromRecord(record) ??\n rawDataDimensions ??\n dimensionsFromImageSource(record.url) ??\n dimensionsFromImageSource(rawData)\n );\n}\n\nfunction highDetailImageTokens(width: number, height: number): number {\n let scaledWidth = width;\n let scaledHeight = height;\n const longest = Math.max(scaledWidth, scaledHeight);\n if (longest > IMAGE_HIGH_DETAIL_MAX_SIDE) {\n const scale = IMAGE_HIGH_DETAIL_MAX_SIDE / longest;\n scaledWidth *= scale;\n scaledHeight *= scale;\n }\n const shortest = Math.min(scaledWidth, scaledHeight);\n if (shortest > IMAGE_HIGH_DETAIL_TARGET_SHORT_SIDE) {\n const scale = IMAGE_HIGH_DETAIL_TARGET_SHORT_SIDE / shortest;\n scaledWidth *= scale;\n scaledHeight *= scale;\n }\n const tiles =\n Math.ceil(scaledWidth / IMAGE_HIGH_DETAIL_TILE_SIZE) *\n Math.ceil(scaledHeight / IMAGE_HIGH_DETAIL_TILE_SIZE);\n return Math.min(\n MAX_NATIVE_IMAGE_TOKENS,\n IMAGE_HIGH_DETAIL_BASE_TOKENS + IMAGE_HIGH_DETAIL_TILE_TOKENS * Math.max(1, tiles),\n );\n}\n\n/**\n * Provider-neutral local estimate for one native image. Inline bytes are used\n * only to recover dimensions; their base64 length never becomes text tokens.\n */\nexport function estimateNativeImageTokens(input: {\n source?: unknown;\n width?: number | null;\n height?: number | null;\n detail?: unknown;\n}): NativeImageTokenEstimate {\n const explicitWidth = finitePositiveInteger(input.width);\n const explicitHeight = finitePositiveInteger(input.height);\n const sourceDimensions = dimensionsFromImageSource(input.source);\n const width = explicitWidth ?? sourceDimensions?.[0] ?? null;\n const height = explicitHeight ?? sourceDimensions?.[1] ?? null;\n const detail =\n typeof input.detail === \"string\" && input.detail.length > 0 ? input.detail : \"auto\";\n if (detail === \"low\") {\n return { tokens: IMAGE_LOW_DETAIL_TOKENS, width, height, detail, reason: \"dimensions\" };\n }\n if (!width || !height) {\n return {\n tokens: UNKNOWN_IMAGE_TOKENS,\n width: null,\n height: null,\n detail,\n reason: \"bounded_fallback\",\n };\n }\n return {\n tokens: highDetailImageTokens(width, height),\n width,\n height,\n detail,\n reason: \"dimensions\",\n };\n}\n\nfunction imageDescriptor(record: Record<string, unknown>): ImageDescriptor | null {\n const type = typeof record.type === \"string\" ? record.type : \"\";\n if (!new Set([\"input_image\", \"image_url\", \"image\", \"computer_screenshot\"]).has(type)) {\n return null;\n }\n const imageUrl = record.image_url;\n const nestedImageUrl =\n imageUrl && typeof imageUrl === \"object\" ? (imageUrl as Record<string, unknown>).url : imageUrl;\n const source =\n record.image ??\n record.imageUrl ??\n nestedImageUrl ??\n record.data ??\n record.url ??\n record.fileId ??\n record.file_id ??\n record.artifact ??\n record.artifactReference;\n const nestedDetail =\n imageUrl && typeof imageUrl === \"object\"\n ? (imageUrl as Record<string, unknown>).detail\n : undefined;\n const dimensions =\n dimensionsFromRecord(record) ??\n (source && typeof source === \"object\"\n ? dimensionsFromRecord(source as Record<string, unknown>)\n : null);\n return {\n source,\n detail:\n typeof record.detail === \"string\"\n ? record.detail\n : typeof nestedDetail === \"string\"\n ? nestedDetail\n : \"auto\",\n width: dimensions?.[0] ?? null,\n height: dimensions?.[1] ?? null,\n };\n}\n\nfunction projectNativeImages(value: unknown, seen: WeakSet<object>): NativeImageProjection {\n if (!value || typeof value !== \"object\") {\n return { value, imageTokens: 0, imageCount: 0, imageFallbackCount: 0 };\n }\n if (seen.has(value)) {\n return { value: \"[circular]\", imageTokens: 0, imageCount: 0, imageFallbackCount: 0 };\n }\n seen.add(value);\n if (Array.isArray(value)) {\n let imageTokens = 0;\n let imageCount = 0;\n let imageFallbackCount = 0;\n const projected = value.map((entry) => {\n const result = projectNativeImages(entry, seen);\n imageTokens += result.imageTokens;\n imageCount += result.imageCount;\n imageFallbackCount += result.imageFallbackCount;\n return result.value;\n });\n seen.delete(value);\n return { value: projected, imageTokens, imageCount, imageFallbackCount };\n }\n\n const record = value as Record<string, unknown>;\n const descriptor = imageDescriptor(record);\n if (descriptor) {\n const estimate = estimateNativeImageTokens(descriptor);\n const projected: Record<string, unknown> = {};\n const payloadKeys = new Set([\n \"image\",\n \"image_url\",\n \"imageUrl\",\n \"data\",\n \"url\",\n \"fileId\",\n \"file_id\",\n \"artifact\",\n \"artifactReference\",\n ]);\n for (const [key, entry] of Object.entries(record)) {\n projected[key] = payloadKeys.has(key) ? \"[native image]\" : entry;\n }\n projected.image_estimate = {\n width: estimate.width,\n height: estimate.height,\n detail: estimate.detail,\n reason: estimate.reason,\n };\n seen.delete(value);\n return {\n value: projected,\n imageTokens: estimate.tokens,\n imageCount: 1,\n imageFallbackCount: estimate.reason === \"bounded_fallback\" ? 1 : 0,\n };\n }\n\n let imageTokens = 0;\n let imageCount = 0;\n let imageFallbackCount = 0;\n const projected: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(record)) {\n const result = projectNativeImages(entry, seen);\n projected[key] = result.value;\n imageTokens += result.imageTokens;\n imageCount += result.imageCount;\n imageFallbackCount += result.imageFallbackCount;\n }\n seen.delete(value);\n return { value: projected, imageTokens, imageCount, imageFallbackCount };\n}\n\n/**\n * Codex CLI `estimate_reasoning_length`: opaque encrypted payloads are not\n * model-visible as raw JSON/base64. Visible bytes ≈ `len * 3/4 - 650`.\n */\nexport function estimateOpaqueEncryptedModelVisibleBytes(encodedLen: number): number {\n const length = Math.max(0, Math.floor(encodedLen));\n return Math.max(0, Math.floor((length * 3) / 4) - 650);\n}\n\n/** Codex CLI bytes→tokens for opaque encrypted content (`ceil(bytes / 4)`). */\nexport function estimateOpaqueEncryptedTokens(encodedLen: number): number {\n const bytes = estimateOpaqueEncryptedModelVisibleBytes(encodedLen);\n return bytes === 0 ? 0 : Math.ceil(bytes / 4);\n}\n\n/**\n * Length of opaque encrypted content that must use the Codex encrypted\n * estimator instead of JSON.stringify (compaction blobs and reasoning).\n */\nexport function opaqueEncryptedContentLength(item: unknown): number | null {\n if (!item || typeof item !== \"object\") return null;\n const record = item as Record<string, unknown>;\n const type = typeof record.type === \"string\" ? record.type : \"\";\n if (\n (type === \"compaction\" || type === \"context_compaction\" || type === \"reasoning\") &&\n typeof record.encrypted_content === \"string\" &&\n record.encrypted_content.length > 0\n ) {\n return record.encrypted_content.length;\n }\n if (type === \"reasoning\") {\n const providerData =\n record.providerData && typeof record.providerData === \"object\"\n ? (record.providerData as Record<string, unknown>)\n : null;\n const nested =\n providerData && typeof providerData.encrypted_content === \"string\"\n ? providerData.encrypted_content\n : providerData && typeof providerData.encryptedContent === \"string\"\n ? providerData.encryptedContent\n : null;\n if (nested && nested.length > 0) return nested.length;\n }\n return null;\n}\n\n/** Native-image-aware item estimate for pre-call accounting and retained budgets. */\nexport function estimateItemTokenBreakdown(item: CompactionItem): ModelInputTokenBreakdown {\n const opaqueLen = opaqueEncryptedContentLength(item);\n if (opaqueLen !== null) {\n // Match Codex: Compaction / encrypted reasoning use the opaque byte\n // heuristic only — never JSON-stringify the ciphertext into the budget.\n const textTokens = estimateOpaqueEncryptedTokens(opaqueLen);\n return {\n totalTokens: textTokens,\n textTokens,\n imageTokens: 0,\n imageCount: 0,\n imageFallbackCount: 0,\n };\n }\n const projected = projectNativeImages(item, new WeakSet<object>());\n let text: string;\n try {\n text = JSON.stringify(projected.value);\n } catch {\n text = String(projected.value);\n }\n const textTokens = estimateTextTokens(text);\n return {\n totalTokens: textTokens + projected.imageTokens,\n textTokens,\n imageTokens: projected.imageTokens,\n imageCount: projected.imageCount,\n imageFallbackCount: projected.imageFallbackCount,\n };\n}\n\nexport function estimateItemTokens(item: CompactionItem): number {\n return estimateItemTokenBreakdown(item).totalTokens;\n}\n\nexport function estimateTokens(items: readonly CompactionItem[]): number {\n let total = 0;\n for (const item of items) {\n total += estimateItemTokens(item);\n }\n return total;\n}\n\nexport function estimateTokensBreakdown(\n items: readonly CompactionItem[],\n): ModelInputTokenBreakdown {\n const total: ModelInputTokenBreakdown = {\n totalTokens: 0,\n textTokens: 0,\n imageTokens: 0,\n imageCount: 0,\n imageFallbackCount: 0,\n };\n for (const item of items) {\n const estimate = estimateItemTokenBreakdown(item);\n total.totalTokens += estimate.totalTokens;\n total.textTokens += estimate.textTokens;\n total.imageTokens += estimate.imageTokens;\n total.imageCount += estimate.imageCount;\n total.imageFallbackCount += estimate.imageFallbackCount;\n }\n return total;\n}\n\nexport function estimateSerializedValueTokens(value: unknown): number {\n let serialized: string;\n try {\n serialized = typeof value === \"string\" ? value : JSON.stringify(value);\n } catch {\n serialized = String(value);\n }\n return estimateTextTokens(serialized ?? \"\");\n}\n\nexport type CompleteModelInputFootprint = {\n input: readonly CompactionItem[];\n instructionsTokens: number;\n toolSchemaTokens: number;\n};\n\nexport type ProviderContextTokenSignal = {\n /** Monotonic within one sampled run; advances after every model response. */\n revision: number;\n /** Provider total tokens after that response (input + generated output). */\n totalTokens: number;\n};\n\nexport type CompleteModelInputEstimate = {\n tokens: number;\n source: \"complete_estimate\" | \"provider_plus_local\";\n inputTokens: number;\n inputTextTokens: number;\n inputImageTokens: number;\n inputImageCount: number;\n inputImageFallbackCount: number;\n instructionsTokens: number;\n toolSchemaTokens: number;\n appendedAfterModelTokens: number;\n};\n\n/**\n * Match Codex history accounting: after one provider response, start from its\n * authoritative TOTAL token count and add only local items placed after the\n * newest model-generated item. System instructions and tool schemas are\n * compared with the exact request footprint that produced the provider count;\n * positive growth is added. Without a bound anchor, estimate the entire\n * outgoing request rather than trusting stale usage from an earlier turn.\n */\nexport function estimateCompleteModelInput(input: {\n current: CompleteModelInputFootprint;\n provider?: ProviderContextTokenSignal | null;\n providerRequestFootprint?: CompleteModelInputFootprint | null;\n}): CompleteModelInputEstimate {\n const inputEstimate = estimateTokensBreakdown(input.current.input);\n const inputTokens = inputEstimate.totalTokens;\n const instructionsTokens = input.current.instructionsTokens;\n const toolSchemaTokens = input.current.toolSchemaTokens;\n if (!input.provider || !input.providerRequestFootprint || input.provider.totalTokens <= 0) {\n return {\n tokens: inputTokens + instructionsTokens + toolSchemaTokens,\n source: \"complete_estimate\",\n inputTokens,\n inputTextTokens: inputEstimate.textTokens,\n inputImageTokens: inputEstimate.imageTokens,\n inputImageCount: inputEstimate.imageCount,\n inputImageFallbackCount: inputEstimate.imageFallbackCount,\n instructionsTokens,\n toolSchemaTokens,\n appendedAfterModelTokens: 0,\n };\n }\n\n const appended = itemsAfterLastModelGeneratedItem(input.current.input);\n const appendedAfterModelTokens = estimateTokens(appended);\n const instructionGrowth = Math.max(\n 0,\n instructionsTokens - input.providerRequestFootprint.instructionsTokens,\n );\n const toolSchemaGrowth = Math.max(\n 0,\n toolSchemaTokens - input.providerRequestFootprint.toolSchemaTokens,\n );\n return {\n tokens:\n input.provider.totalTokens + appendedAfterModelTokens + instructionGrowth + toolSchemaGrowth,\n source: \"provider_plus_local\",\n inputTokens,\n inputTextTokens: inputEstimate.textTokens,\n inputImageTokens: inputEstimate.imageTokens,\n inputImageCount: inputEstimate.imageCount,\n inputImageFallbackCount: inputEstimate.imageFallbackCount,\n instructionsTokens,\n toolSchemaTokens,\n appendedAfterModelTokens,\n };\n}\n\nexport function itemsAfterLastModelGeneratedItem(\n items: readonly CompactionItem[],\n): CompactionItem[] {\n for (let index = items.length - 1; index >= 0; index -= 1) {\n if (isModelGeneratedItem(items[index])) {\n return items.slice(index + 1);\n }\n }\n // Codex treats a provider token anchor without any model-generated item as\n // unbound. Callers therefore fall back to a complete estimate in that case.\n return items.slice();\n}\n\nexport function hasModelGeneratedItem(items: readonly CompactionItem[]): boolean {\n return items.some(isModelGeneratedItem);\n}\n\nfunction isModelGeneratedItem(item: unknown): boolean {\n const type = itemType(item);\n if (type === \"message\") return itemRole(item) === \"assistant\";\n return MODEL_GENERATED_ITEM_TYPES.has(type ?? \"\");\n}\n\nexport function clampCompactionThresholdRatio(value: number | undefined | null): number {\n const numeric =\n typeof value === \"number\" && Number.isFinite(value)\n ? value\n : DEFAULT_COMPACTION_THRESHOLD_RATIO;\n return Math.min(\n MAX_COMPACTION_THRESHOLD_RATIO,\n Math.max(MIN_COMPACTION_THRESHOLD_RATIO, numeric),\n );\n}\n\nexport function compactionThresholdTokens(input: {\n contextWindowTokens: number;\n contextReservedOutputTokens: number;\n contextAutoCompactThresholdTokens?: number | null | undefined;\n contextCompactionThresholdRatio?: number | null | undefined;\n}): number {\n const window = Math.max(0, input.contextWindowTokens);\n const codexMaximum = Math.floor(window * MAX_COMPACTION_THRESHOLD_RATIO);\n if (\n typeof input.contextAutoCompactThresholdTokens === \"number\" &&\n Number.isFinite(input.contextAutoCompactThresholdTokens) &&\n input.contextAutoCompactThresholdTokens > 0\n ) {\n return Math.min(Math.floor(input.contextAutoCompactThresholdTokens), codexMaximum);\n }\n return Math.floor(window * clampCompactionThresholdRatio(input.contextCompactionThresholdRatio));\n}\n\nexport type CompactionDecision = {\n shouldCompact: boolean;\n reason: \"force\" | \"above_threshold\" | \"below_threshold\" | \"no_history\";\n signalTokens: number;\n thresholdTokens: number;\n};\n\nexport function decideCompaction(input: {\n items: readonly CompactionItem[];\n lastInputTokens?: number | null;\n contextWindowTokens: number;\n contextReservedOutputTokens: number;\n contextAutoCompactThresholdTokens?: number | null | undefined;\n contextCompactionThresholdRatio?: number | null | undefined;\n force?: boolean;\n}): CompactionDecision {\n const thresholdTokens = compactionThresholdTokens(input);\n const recorded =\n typeof input.lastInputTokens === \"number\" && input.lastInputTokens > 0\n ? input.lastInputTokens\n : 0;\n const activeHistoryEstimate = estimateTokens(input.items);\n // A durable provider count belongs to an earlier request. The full active\n // estimate is a conservative cross-turn floor until an exact same-run anchor\n // is available in the per-call guard.\n const signalTokens = Math.max(recorded, activeHistoryEstimate);\n if (input.items.length === 0) {\n return {\n shouldCompact: false,\n reason: \"no_history\",\n signalTokens,\n thresholdTokens,\n };\n }\n if (input.force) {\n return {\n shouldCompact: true,\n reason: \"force\",\n signalTokens,\n thresholdTokens,\n };\n }\n if (signalTokens >= thresholdTokens) {\n return {\n shouldCompact: true,\n reason: \"above_threshold\",\n signalTokens,\n thresholdTokens,\n };\n }\n return {\n shouldCompact: false,\n reason: \"below_threshold\",\n signalTokens,\n thresholdTokens,\n };\n}\n\nexport class CompactionNeededError extends Error {\n readonly signalTokens: number;\n readonly thresholdTokens: number;\n readonly signalSource: \"provider\" | \"estimate\";\n readonly trigger: \"threshold\" | \"operator\";\n\n constructor(input: {\n signalTokens: number;\n thresholdTokens: number;\n signalSource: \"provider\" | \"estimate\";\n trigger?: \"threshold\" | \"operator\";\n }) {\n const trigger = input.trigger ?? \"threshold\";\n super(\n trigger === \"operator\"\n ? \"Context compaction requested by the operator\"\n : `Context compaction needed: signal ${input.signalTokens} tokens exceeded threshold ${input.thresholdTokens}`,\n );\n this.name = \"CompactionNeededError\";\n this.signalTokens = input.signalTokens;\n this.thresholdTokens = input.thresholdTokens;\n this.signalSource = input.signalSource;\n this.trigger = trigger;\n }\n}\n\nexport class EmptyCompactionSummaryError extends Error {\n readonly diagnostics: Record<string, unknown>;\n\n constructor(diagnostics: Record<string, unknown> = {}) {\n const compact = JSON.stringify(diagnostics).slice(0, 2_000);\n super(\n `Compaction summarizer returned no assistant text; active history was preserved${compact ? ` (${compact})` : \"\"}`,\n );\n this.name = \"EmptyCompactionSummaryError\";\n this.diagnostics = diagnostics;\n }\n}\n\n/**\n * The checkpoint model request ended in a provider/transport failure rather\n * than a successful response with an empty assistant message. Diagnostics are\n * deliberately bounded and content-free so this error can be persisted on a\n * turn without copying provider messages or conversation input into events.\n */\nexport class CompactionProviderResponseError extends Error {\n readonly diagnostics: Record<string, unknown>;\n readonly status?: number;\n readonly code?: string;\n readonly type?: string;\n override readonly cause?: unknown;\n\n constructor(diagnostics: Record<string, unknown> = {}, cause?: unknown) {\n const compact = JSON.stringify(diagnostics).slice(0, 2_000);\n super(\n `Compaction provider request failed; active history was preserved${compact ? ` (${compact})` : \"\"}`,\n );\n this.name = \"CompactionProviderResponseError\";\n this.diagnostics = diagnostics;\n if (typeof diagnostics.httpStatus === \"number\") this.status = diagnostics.httpStatus;\n if (typeof diagnostics.code === \"string\") this.code = diagnostics.code;\n if (typeof diagnostics.type === \"string\") this.type = diagnostics.type;\n if (cause !== undefined) {\n Object.defineProperty(this, \"cause\", { value: cause, enumerable: false });\n }\n }\n}\n\nexport function findCompactionNeededError(\n error: unknown,\n seen = new WeakSet<object>(),\n): CompactionNeededError | null {\n if (error instanceof CompactionNeededError) {\n return error;\n }\n if (!error || typeof error !== \"object\") {\n return null;\n }\n if (seen.has(error)) {\n return null;\n }\n seen.add(error);\n const record = error as Record<string, unknown>;\n return (\n findCompactionNeededError(record.cause, seen) ?? findCompactionNeededError(record.error, seen)\n );\n}\n\n/**\n * The exact checkpoint input shape: current active history followed by Codex's\n * checkpoint prompt as a synthesized user message.\n */\nexport function buildCompactionPromptInput(items: readonly CompactionItem[]): CompactionItem[] {\n return [\n ...items,\n {\n type: \"message\",\n role: \"user\",\n content: COMPACTION_PROMPT,\n },\n ];\n}\n\nexport type PreparedCompactionPromptInput = {\n input: CompactionItem[];\n estimatedInputTokens: number;\n rewrittenToolOutputs: number;\n droppedHistoryItems: number;\n};\n\n/**\n * Fit the explicit checkpoint request without mutating canonical history.\n *\n * Codex first replaces oversized tool outputs in its temporary remote-\n * compaction input. OpenGeni does the same oldest-first, preserving the most\n * recent tool detail for the plaintext summary. If that is still insufficient,\n * whole oldest user-delimited work units are removed and the remaining suffix\n * is protocol-sanitized so no call/result/reasoning fragment is orphaned.\n * The raw active history is still the source for the eventual replacement and\n * remains unchanged if the provider call fails.\n */\nexport function prepareCompactionPromptInput(\n items: readonly CompactionItem[],\n maxInputTokens: number,\n): PreparedCompactionPromptInput {\n const budget = Math.max(0, Math.floor(maxInputTokens));\n let history = items.slice();\n let estimatedInputTokens = estimateTokens(buildCompactionPromptInput(history));\n let rewrittenToolOutputs = 0;\n\n for (let index = 0; index < history.length && estimatedInputTokens > budget; index += 1) {\n const current = history[index]!;\n const replacement = minimalToolResultForCompaction(current);\n if (replacement === current) continue;\n const before = estimateItemTokens(current);\n const after = estimateItemTokens(replacement);\n if (after >= before) continue;\n history[index] = replacement;\n estimatedInputTokens -= before - after;\n rewrittenToolOutputs += 1;\n }\n\n const beforeDropLength = history.length;\n if (estimatedInputTokens > budget && history.length > 0) {\n const prefixTokens = new Array<number>(history.length + 1).fill(0);\n for (let index = 0; index < history.length; index += 1) {\n prefixTokens[index + 1] = prefixTokens[index]! + estimateItemTokens(history[index]!);\n }\n const cuts = oldestLogicalUnitCuts(history);\n const cut =\n cuts.find((candidate) => estimatedInputTokens - prefixTokens[candidate]! <= budget) ??\n history.length;\n history = sanitizeHistoryItemsForModel(history.slice(cut));\n estimatedInputTokens = estimateTokens(buildCompactionPromptInput(history));\n // The synthesized checkpoint instruction is the irreducible floor. The\n // real model budgets are far above it, but keep the helper total for tests\n // and malformed configuration instead of constructing invalid fragments.\n if (estimatedInputTokens > budget) {\n history = [];\n estimatedInputTokens = estimateTokens(buildCompactionPromptInput(history));\n }\n }\n\n return {\n input: buildCompactionPromptInput(history),\n estimatedInputTokens,\n rewrittenToolOutputs,\n droppedHistoryItems: beforeDropLength - history.length,\n };\n}\n\nfunction minimalToolResultForCompaction(item: CompactionItem): CompactionItem {\n const type = itemType(item);\n if (!type || !RESULT_TYPES.has(type)) return item;\n if (type === \"tool_search_output\" && Array.isArray(item.tools) && item.tools.length > 0) {\n return { ...item, tools: [] };\n }\n return boundModelToolOutputItem(item, 0);\n}\n\nfunction oldestLogicalUnitCuts(items: readonly CompactionItem[]): number[] {\n const userMessageIndexes: number[] = [];\n for (let index = 0; index < items.length; index += 1) {\n if (isUserMessage(items[index])) userMessageIndexes.push(index);\n }\n const cuts: number[] = [];\n if (userMessageIndexes.length === 0) {\n return [items.length];\n }\n if (userMessageIndexes[0]! > 0) cuts.push(userMessageIndexes[0]!);\n for (const index of userMessageIndexes.slice(1)) cuts.push(index);\n cuts.push(items.length);\n return cuts;\n}\n\n/**\n * Build the active history after compaction:\n * the newest real user messages that fit one cumulative 20k-token budget\n * (prior summaries excluded, images removed) plus one marked summary item.\n */\nexport function buildCompactionReplacementHistory(\n items: readonly CompactionItem[],\n summaryBody: string,\n): CompactionItem[] {\n const retainedReversed: CompactionItem[] = [];\n let remaining = COMPACT_USER_MESSAGE_MAX_TOKENS;\n for (let index = items.length - 1; index >= 0 && remaining > 0; index -= 1) {\n const item = items[index]!;\n if (!isUserMessage(item) || isCompactionSummary(item)) {\n continue;\n }\n const textTokens = estimateTextTokens(messageText(item));\n retainedReversed.push(compactMessageToTokenBudget(item, remaining));\n if (textTokens > remaining) {\n remaining = 0;\n break;\n }\n remaining -= textTokens;\n }\n const history = retainedReversed.reverse();\n history.push(buildSummaryItem(summaryBody));\n return history;\n}\n\n/** True for a Codex remote-compaction output item with opaque encrypted content. */\nexport function isRemoteCompactionItem(item: unknown): item is CompactionItem {\n if (!item || typeof item !== \"object\") return false;\n const record = item as Record<string, unknown>;\n return (\n record.type === \"compaction\" &&\n typeof record.encrypted_content === \"string\" &&\n record.encrypted_content.length > 0\n );\n}\n\n/** Messages retained beside a remote v2 compaction blob (user + developer). */\nexport function isRetainedRemoteV2Message(item: unknown): boolean {\n if (isCompactionSummary(item) || itemType(item) === \"compaction\") return false;\n const role = itemRole(item);\n return itemType(item) === \"message\" && (role === \"user\" || role === \"developer\");\n}\n\n/**\n * Build the active history after Codex remote compaction v2:\n * newest retained user/developer messages within the CLI 64k budget plus the\n * opaque `{ type: \"compaction\", encrypted_content }` item.\n */\nexport function buildRemoteV2ReplacementHistory(\n items: readonly CompactionItem[],\n compactionItem: CompactionItem,\n): CompactionItem[] {\n if (!isRemoteCompactionItem(compactionItem)) {\n throw new EmptyCompactionSummaryError({ stage: \"remote_v2_compaction_item\" });\n }\n const retainedReversed: CompactionItem[] = [];\n let remaining = REMOTE_V2_RETAINED_MESSAGE_TOKEN_BUDGET;\n for (let index = items.length - 1; index >= 0 && remaining > 0; index -= 1) {\n const item = items[index]!;\n if (!isRetainedRemoteV2Message(item)) continue;\n const textTokens = estimateTextTokens(messageText(item));\n retainedReversed.push(compactMessageToTokenBudget(item, remaining));\n if (textTokens > remaining) {\n remaining = 0;\n break;\n }\n remaining -= textTokens;\n }\n const history = retainedReversed.reverse();\n history.push({\n type: \"compaction\",\n encrypted_content: compactionItem.encrypted_content,\n ...(typeof compactionItem.summary === \"string\" ? { summary: compactionItem.summary } : {}),\n });\n return history;\n}\n\n/**\n * Append the transient compaction_trigger used only for the remote v2 request.\n *\n * The OpenAI Agents SDK's Responses converter rejects a bare\n * `{ type: \"compaction_trigger\" }` (`UserError: Unsupported item`). It does\n * accept `type: \"unknown\"` and forwards `providerData` onto the wire, which is\n * how we deliver the Codex-only trigger through CompactionResponsesModel into\n * the Codex fetch normalizer (which allowlists top-level `compaction_trigger`).\n */\nexport function buildRemoteCompactionV2PromptInput(\n items: readonly CompactionItem[],\n): CompactionItem[] {\n return [\n ...items,\n {\n type: \"unknown\",\n providerData: { type: \"compaction_trigger\" },\n },\n ];\n}\n\n/** Extract exactly one compaction output item from a Responses payload. */\nexport function extractRemoteCompactionV2OutputItem(response: unknown): CompactionItem {\n if (!response || typeof response !== \"object\") {\n throw new EmptyCompactionSummaryError({ stage: \"remote_v2_extract\", reason: \"no_response\" });\n }\n const record = response as Record<string, unknown>;\n const output = Array.isArray(record.output) ? record.output : [];\n const compactionItems = output.filter(isRemoteCompactionItem);\n if (compactionItems.length !== 1) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_extract\",\n reason: \"expected_exactly_one_compaction\",\n found: compactionItems.length,\n });\n }\n return compactionItems[0]!;\n}\n\nexport function compactionReplacementFingerprint(items: readonly CompactionItem[]): string {\n // PostgreSQL JSONB does not preserve JavaScript object-key insertion order.\n // Canonicalize recursively so a replacement has the same identity before\n // and after its durable round trip.\n const serialized = JSON.stringify(canonicalJsonValue(items));\n return createHash(\"sha256\").update(serialized, \"utf8\").digest(\"hex\");\n}\n\nfunction canonicalJsonValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalJsonValue);\n if (!value || typeof value !== \"object\") return value;\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => [key, canonicalJsonValue(entry)]),\n );\n}\n\n/** Fingerprint the latest durable replacement prefix in active history. */\nexport function latestCompactionReplacementFingerprint(\n items: readonly CompactionItem[],\n): string | null {\n for (let index = items.length - 1; index >= 0; index -= 1) {\n if (isCompactionSummary(items[index])) {\n return compactionReplacementFingerprint(items.slice(0, index + 1));\n }\n }\n return null;\n}\n\n/**\n * Build the synthetic summary item (a plain user message) appended to the\n * rebuilt active history.\n */\nexport function buildSummaryItem(summaryBody: string): CompactionItem {\n const trimmed = summaryBody.trim();\n if (!trimmed) {\n throw new EmptyCompactionSummaryError({ stage: \"build_summary_item\" });\n }\n return {\n type: \"message\",\n role: \"user\",\n content: `${SUMMARY_PREFIX}\\n${trimmed}`,\n [COMPACTION_SUMMARY_MARKER]: true,\n };\n}\n\nfunction compactMessageToTokenBudget(item: CompactionItem, maxTokens: number): CompactionItem {\n const text = messageText(item);\n const next = { ...item };\n if (estimateTextTokens(text) > maxTokens) {\n next.content = truncateMiddleByEstimatedTokens(text, maxTokens);\n return next;\n }\n next.content = contentWithoutImages(item);\n return next;\n}\n\nfunction truncateMiddleByEstimatedTokens(text: string, maxTokens: number): string {\n const budget = Math.max(0, Math.floor(maxTokens));\n if (estimateTextTokens(text) <= budget) {\n return text;\n }\n if (estimateTextTokens(USER_MESSAGE_TRUNCATION_MARKER) > budget) {\n return tokenBoundedPrefix(USER_MESSAGE_TRUNCATION_MARKER, budget);\n }\n\n let low = 0;\n let high = text.length;\n let best = USER_MESSAGE_TRUNCATION_MARKER;\n while (low <= high) {\n const keepCodeUnits = Math.floor((low + high) / 2);\n const candidate = middleTruncationCandidate(text, keepCodeUnits);\n if (estimateTextTokens(candidate) <= budget) {\n best = candidate;\n low = keepCodeUnits + 1;\n } else {\n high = keepCodeUnits - 1;\n }\n }\n return best;\n}\n\nfunction middleTruncationCandidate(text: string, keepCodeUnits: number): string {\n const headTarget = Math.ceil(keepCodeUnits / 2);\n const tailTarget = Math.floor(keepCodeUnits / 2);\n const headEnd = validPrefixBoundary(text, headTarget);\n const tailStart = validSuffixBoundary(text, text.length - tailTarget);\n return `${text.slice(0, headEnd)}${USER_MESSAGE_TRUNCATION_MARKER}${text.slice(tailStart)}`;\n}\n\nfunction tokenBoundedPrefix(text: string, maxTokens: number): string {\n let low = 0;\n let high = text.length;\n let best = \"\";\n while (low <= high) {\n const target = Math.floor((low + high) / 2);\n const end = validPrefixBoundary(text, target);\n const candidate = text.slice(0, end);\n if (estimateTextTokens(candidate) <= maxTokens) {\n best = candidate;\n low = target + 1;\n } else {\n high = target - 1;\n }\n }\n return best;\n}\n\n/** Largest boundary at or below target that does not split a surrogate pair. */\nfunction validPrefixBoundary(text: string, target: number): number {\n let boundary = Math.max(0, Math.min(text.length, target));\n if (\n boundary > 0 &&\n boundary < text.length &&\n isHighSurrogate(text.charCodeAt(boundary - 1)) &&\n isLowSurrogate(text.charCodeAt(boundary))\n ) {\n boundary -= 1;\n }\n return boundary;\n}\n\n/** Smallest boundary at or above target that does not split a surrogate pair. */\nfunction validSuffixBoundary(text: string, target: number): number {\n let boundary = Math.max(0, Math.min(text.length, target));\n if (\n boundary > 0 &&\n boundary < text.length &&\n isHighSurrogate(text.charCodeAt(boundary - 1)) &&\n isLowSurrogate(text.charCodeAt(boundary))\n ) {\n boundary += 1;\n }\n return boundary;\n}\n\nfunction isHighSurrogate(codeUnit: number): boolean {\n return codeUnit >= 0xd800 && codeUnit <= 0xdbff;\n}\n\nfunction isLowSurrogate(codeUnit: number): boolean {\n return codeUnit >= 0xdc00 && codeUnit <= 0xdfff;\n}\n\nfunction contentWithoutImages(item: CompactionItem): unknown {\n const content = (item as { content?: unknown }).content;\n if (!Array.isArray(content)) {\n return content;\n }\n return content.filter((part) => {\n if (!part || typeof part !== \"object\") {\n return true;\n }\n const type = (part as { type?: unknown }).type;\n return type !== \"input_image\" && type !== \"image_url\";\n });\n}\n\nfunction messageText(item: CompactionItem): string {\n const content = (item as { content?: unknown }).content;\n if (typeof content === \"string\") {\n return content;\n }\n if (Array.isArray(content)) {\n return content\n .map((part) => {\n if (part && typeof part === \"object\") {\n const record = part as { text?: unknown; content?: unknown };\n if (typeof record.text === \"string\") {\n return record.text;\n }\n if (typeof record.content === \"string\") {\n return record.content;\n }\n }\n return \"\";\n })\n .join(\"\");\n }\n return \"\";\n}\n\nexport function renderCompactionPromptInputForChat(input: readonly CompactionItem[]): string {\n return input.map(renderItem).join(\"\\n\");\n}\n\nfunction renderItem(item: CompactionItem): string {\n const type = itemType(item) ?? \"unknown\";\n if (type === \"message\") {\n const role = itemRole(item) ?? \"assistant\";\n return `[${role}] ${messageText(item)}`;\n }\n if (type === \"reasoning\") {\n return \"[reasoning] (omitted)\";\n }\n if (RESULT_TYPES.has(type)) {\n return `[tool_result] ${resultText(item)}`;\n }\n if (RESULT_TYPE_BY_CALL_TYPE[type]) {\n return `[tool_call ${type}] ${callText(item)}`;\n }\n return `[${type}] ${safeStringify(item)}`;\n}\n\nfunction resultText(item: CompactionItem): string {\n const output = (item as { output?: unknown }).output;\n if (typeof output === \"string\") {\n return output;\n }\n return safeStringify(output ?? item);\n}\n\nfunction callText(item: CompactionItem): string {\n const name = (item as { name?: unknown }).name;\n const args = (item as { arguments?: unknown }).arguments;\n const namePart = typeof name === \"string\" ? name : \"\";\n const argPart = typeof args === \"string\" ? args : safeStringify(args ?? {});\n return `${namePart} ${argPart}`.trim();\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n","// packages/runtime/src/sandbox-computer.ts — the agent computer-use surface (P4.3).\n//\n// A `Computer` impl backed by xdotool (mouse/keyboard/move/click/type/key) +\n// scrot (screenshots), issued through the SAME externally-owned `session` the\n// human watches over Channel B. The agent and the human share ONE :0 display —\n// zero projection: ffmpeg reads exactly the pixels xdotool draws. Exposed to the\n// Agents SDK as a `computerTool` carried by `ComputerUseCapability`, pushed into\n// `buildAgentCapabilities` when `computerUseEnabled && desktopCapableBackend`.\n//\n// This file lives OUTSIDE the @opengeni/runtime/sandbox agent-loop-free leaf\n// (it imports `computerTool` from the @openai/agents root, which the leaf forbids)\n// and is wired into the agent-loop barrel (packages/runtime/src/index.ts).\n//\n// ── Adversarial-review fixes folded in (module 05 §Adversarial) ──────────────\n// F1 exec is OPTIONAL on every provider (Modal has only execCommand) — the\n// primitive dual-paths `session.exec ?? session.execCommand`.\n// F2 execCommand returns a FORMATTED STRING with a metadata preamble, not raw\n// stdout — screenshots read the PNG by running `base64 <path>` over the SAME\n// command primitive and stripping the banner (NOT `session.readFile`: Modal's\n// readFile path-validates against the /workspace root and THROWS\n// \"Sandbox path /tmp/…png escapes the workspace root\", so the /tmp scrot can\n// never be read → empty frame → `image_url: ''` → model 400). This mirrors\n// recording.ts/channel-a fsReadViaExec. Exit codes come from the established\n// `sandboxCommandExitCode` parser, not a `.exitCode` field.\n// F3 exec/execCommand YIELDS (does not wait) — `sandboxCommandStillRunning` is\n// treated as a retriable failure, and the input commands complete well under\n// the yield window.\n// F4 import paths: `computerTool`/`Computer` from `@openai/agents` (root, via\n// the agents-core star re-export); `Capability`/`requireBoundSession` from\n// `@openai/agents/sandbox`. `Button` is NOT exported — the union is inlined.\n// F5 scroll deltas are model PIXELS (often hundreds) — divided by a notch step\n// and clamped, NOT used as literal wheel-click `--repeat` counts.\n\nimport { computerTool, tool, type Computer, type Tool } from \"@openai/agents\";\nimport { Capability, type SandboxSessionLike } from \"@openai/agents/sandbox\";\nimport {\n KeyAction,\n PointerAction,\n PointerButton,\n type DesktopInputRequest,\n} from \"@opengeni/agent-proto\";\nimport { redactSensitiveText } from \"@opengeni/contracts\";\n\nimport { sandboxCommandExitCode, sandboxCommandOutput, sandboxCommandStillRunning } from \"./index\";\n// `stripExecBanner` is the SAME pure helper recording.ts uses to recover the raw\n// command body from Modal's execCommand banner (\"…Output:\\n<body>\"). Imported from\n// the agent-loop-free leaf (importing a pure parser FROM the leaf is allowed — the\n// leaf boundary only forbids the leaf importing the agent loop, not the reverse).\nimport { ensureDisplayStack, stripExecBanner } from \"./sandbox\";\n\n// `requireBoundSession` lives in @openai/agents-core/sandbox/capabilities/base\n// but is NOT re-exported from the public @openai/agents/sandbox barrel, so we\n// inline the trivial bound-session guard (parity with the SDK's own helper).\nfunction requireBoundSession(\n capabilityType: string,\n session?: SandboxSessionLike,\n): SandboxSessionLike {\n if (!session) {\n throw new ComputerUnavailableError(`capability \"${capabilityType}\" used before bind(session)`);\n }\n return session;\n}\n\n// `Button` is intentionally NOT imported (it is not a public export, F4) — the\n// union is inlined and kept in lockstep with @openai/agents-core/computer.d.ts.\ntype ComputerButton = \"left\" | \"right\" | \"wheel\" | \"back\" | \"forward\";\n\nconst DEFAULT_DISPLAY = \":0\";\nconst DEFAULT_DIMENSIONS: [number, number] = [1280, 800];\n// Commands must complete well under this (F3): xdotool/scrot of a 1280x800 PNG is\n// sub-second; the wait gives headroom on a cold gVisor box without masking a wedge.\nconst ACTION_YIELD_MS = 15_000;\n// Model scroll deltas are pixels (F5); one wheel \"notch\" ≈ this many pixels. e2b\n// uses a similar divisor. Clamp keeps a runaway delta from spamming the wheel.\nconst SCROLL_NOTCH_PIXELS = 100;\nconst SCROLL_MAX_CLICKS = 15;\n// screenshot() never hands the model an empty image_url (the SDK turns \"\" into\n// `image_url: ''`, which the model API 400s). A cold/not-yet-painting :0 can yield\n// zero-byte frames for the WHOLE warm-up window of a freshly cold-booted box — Xvfb\n// + XFCE + dbus + font-cache under gVisor routinely take 20s+, and the recovery path\n// after a machine→sandbox swap ALWAYS hits a stone-cold Modal box on its first turn.\n// So we retry across a bounded WALL-CLOCK budget (not a tiny fixed attempt count) with\n// a short pause between tries, so that first post-cold / post-swap screenshot self-heals\n// as the display warms — then FAIL LOUD once the budget is genuinely spent (a display\n// that is dead, not merely warming). ~800ms of retries (the prior 3×400ms) was far too\n// short to ride out a cold gVisor XFCE boot, so the turn failed loud on a transient.\nconst SCREENSHOT_WARMUP_BUDGET_MS = 30_000;\nconst SCREENSHOT_RETRY_DELAY_MS = 750;\n// The screenshot PNG is read back off the box by base64-ing it over the provider's exec\n// channel. Modal's exec collects stdout into a BOUNDED buffer that silently EMPTIES a\n// single oversized read: a fully-painted 1280x800 desktop PNG (~222 KB) base64s to\n// ~296 KB, which trips the cap and returns \"\" — the blank-frame incident. A partly-\n// painted frame (~200 KB base64) slipped under it, which is why this only surfaced once\n// the paint gate began delivering FULLY-painted frames. (Channel-A's file read already\n// caps its own base64-over-exec output for the same reason; the screenshot read was the\n// one large read that didn't bound itself.) We therefore read the file in 3-byte-aligned\n// CHUNKS whose per-read base64 (~131 KB) stays well under the cap, then VALIDATE the\n// reconstructed byte count against the on-box file size. 98304 = 96 KiB, divisible by 3\n// so each chunk's base64 is self-contained (no cross-chunk padding) and concatenating the\n// decoded chunks reconstructs the PNG byte-exactly.\nconst SCREENSHOT_READ_CHUNK_BYTES = 98_304;\n\nexport type SandboxComputerOptions = {\n display?: string; // \":0\"\n dimensions?: [number, number]; // must match the Xvfb geometry\n runAs?: string; // provider runAs (modal/docker: \"sandbox\"); undefined otherwise\n typeDelayMs?: number; // xdotool type --delay (default 12ms)\n readOnly?: boolean; // when true, every WRITE action throws ComputerReadOnlyError\n screenshotTmpDir?: string; // \"/tmp\"\n // How long screenshot() keeps retrying an empty (still-warming) frame before it\n // FAILS LOUD, and the pause between tries. Defaults to the cold-boot warm-up budget;\n // exposed mainly so tests can shrink it (a real caller wants the full budget).\n screenshotWarmupBudgetMs?: number;\n screenshotRetryDelayMs?: number;\n /**\n * One turn-scoped preparation hook, invoked by the first real computer action.\n * The agent may advertise computer-use on every turn, but merely advertising the\n * tool must not boot Xvfb/XFCE or start a recording. The runtime capability owns\n * this hook and uses it to bring up :0 (and optionally notify the worker) only\n * after the model actually chooses a computer tool.\n */\n prepare?: (session: SandboxSessionLike) => Promise<void>;\n};\n\n// X keysym map for keypress(): model key names → xdotool keysyms.\nconst KEYSYM: Record<string, string> = {\n ctrl: \"ctrl\",\n control: \"ctrl\",\n alt: \"alt\",\n option: \"alt\",\n shift: \"shift\",\n cmd: \"super\",\n meta: \"super\",\n win: \"super\",\n super: \"super\",\n enter: \"Return\",\n return: \"Return\",\n tab: \"Tab\",\n esc: \"Escape\",\n escape: \"Escape\",\n backspace: \"BackSpace\",\n delete: \"Delete\",\n space: \"space\",\n up: \"Up\",\n down: \"Down\",\n left: \"Left\",\n right: \"Right\",\n pageup: \"Prior\",\n pagedown: \"Next\",\n home: \"Home\",\n end: \"End\",\n};\nfunction toKeysym(k: string): string {\n const low = k.toLowerCase();\n if (KEYSYM[low]) return KEYSYM[low];\n if (/^f([1-9]|1[0-2])$/.test(low)) return low.toUpperCase();\n return low.length === 1 ? low : k;\n}\nconst BUTTON_NUM: Record<ComputerButton, number> = {\n left: 1,\n wheel: 2,\n right: 3,\n back: 8,\n forward: 9,\n};\n\n// The structural slice of a provider session computer-use drives. exec and\n// execCommand are optional because the SDK's SandboxSessionLike leaves them\n// optional (Modal implements execCommand, not exec — F1). readFile is intentionally\n// NOT in this type: screenshots read the /tmp PNG via `base64 <path>` over\n// exec/execCommand (readFile path-validates against /workspace and rejects /tmp).\ntype ExecResultLike = {\n output?: string;\n stdout?: string;\n stderr?: string;\n exitCode?: number | null;\n sessionId?: number;\n};\ntype ComputerSession = {\n // A native provider exec returns a structured `ExecResultLike`; the routing proxy\n // fronting a Modal box returns the execCommand banner STRING. Both are handled.\n exec?: (args: {\n cmd: string;\n runAs?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<ExecResultLike | string>;\n execCommand?: (args: {\n cmd: string;\n runAs?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<string>;\n};\n\n/** No exec/execCommand on the session, or the display is not up. */\nexport class ComputerUnavailableError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ComputerUnavailableError\";\n }\n}\n/** The screenshot file read back SHORT of its on-box byte size — a chunk was truncated\n * by the provider's exec-output cap. This is deterministic, NOT a warm-up transient, so\n * it fails LOUD immediately with the byte counts (never a silent blank the model would\n * read as a real empty screen) and is not retried. */\nexport class ScreenshotReadError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ScreenshotReadError\";\n }\n}\n/** A write action attempted while readOnly. */\nexport class ComputerReadOnlyError extends Error {\n constructor() {\n super(\"computer-use is read-only — write actions are disabled\");\n this.name = \"ComputerReadOnlyError\";\n }\n}\n/** A nonzero xdotool/scrot exit, OR a command that did not finish before the\n * yield window (F3 — \"still running\" is a failure, not a silent success). */\nexport class ComputerActionError extends Error {\n constructor(\n public cmd: string,\n public exitCode: number,\n public stderr: string,\n ) {\n super(`computer action failed (${exitCode}): ${cmd}${stderr ? `\\n${stderr}` : \"\"}`);\n this.name = \"ComputerActionError\";\n }\n}\n\n/**\n * The Computer the agent drives. Every action issues ONE shell line through the\n * externally-owned session (exec ?? execCommand, F1), prefixed with the display.\n * screenshot() scrots to a /tmp file and reads the RAW bytes by running\n * `base64 <path>` over the SAME command primitive and stripping the banner — NOT\n * `session.readFile` (Modal's readFile path-validates against /workspace and rejects\n * /tmp with \"escapes the workspace root\", which would yield an empty frame and 400\n * the model). The base64-over-exec path is /tmp-readable and binary-safe.\n */\nexport class SandboxComputer implements Computer {\n readonly environment = \"ubuntu\" as const;\n readonly dimensions: [number, number];\n private session: ComputerSession & SandboxSessionLike;\n private readonly display: string;\n private readonly runAs?: string;\n private readonly typeDelayMs: number;\n private readonly readOnly: boolean;\n private readonly tmp: string;\n private readonly screenshotWarmupBudgetMs: number;\n private readonly screenshotRetryDelayMs: number;\n private readonly prepare: ((session: SandboxSessionLike) => Promise<void>) | undefined;\n private prepared = false;\n private preparation: Promise<void> | null = null;\n\n constructor(session: SandboxSessionLike, opts: SandboxComputerOptions = {}) {\n this.session = session as ComputerSession & SandboxSessionLike;\n this.display = opts.display ?? DEFAULT_DISPLAY;\n this.dimensions = opts.dimensions ?? DEFAULT_DIMENSIONS;\n if (opts.runAs !== undefined) {\n this.runAs = opts.runAs;\n }\n this.typeDelayMs = opts.typeDelayMs ?? 12;\n this.readOnly = opts.readOnly ?? false;\n this.tmp = opts.screenshotTmpDir ?? \"/tmp\";\n this.screenshotWarmupBudgetMs = opts.screenshotWarmupBudgetMs ?? SCREENSHOT_WARMUP_BUDGET_MS;\n this.screenshotRetryDelayMs = opts.screenshotRetryDelayMs ?? SCREENSHOT_RETRY_DELAY_MS;\n this.prepare = opts.prepare;\n }\n\n /** Rebind to a freshly resumed-by-id session after a box rollover / re-establish. */\n rebind(session: SandboxSessionLike) {\n this.session = session as ComputerSession & SandboxSessionLike;\n this.prepared = false;\n this.preparation = null;\n }\n\n private async prepareOnce(): Promise<void> {\n if (this.prepared) return;\n if (!this.prepare) {\n // No lazy hook means the caller handed us an already-ready display, which\n // is the historical direct-construction behavior used by embedders/tests.\n this.prepared = true;\n return;\n }\n this.preparation ??= this.prepare(this.session);\n try {\n await this.preparation;\n this.prepared = true;\n } catch (error) {\n // A viewer may have contended the display flock or a provider operation may\n // have failed transiently. Let a later computer call retry; never cache a\n // rejected preparation as the permanent state of the turn.\n this.preparation = null;\n throw error;\n }\n }\n\n // The single command primitive. Dual-paths exec/execCommand (F1), then uses the\n // established string-aware parsers (F2/F3): exitCode from the preamble, and\n // \"still running\" → a retriable failure. Returns the command OUTPUT body.\n private async x(cmd: string): Promise<string> {\n await this.prepareOnce();\n const args = {\n cmd: `DISPLAY=${this.display} ${cmd}`,\n ...(this.runAs ? { runAs: this.runAs } : {}),\n yieldTimeMs: ACTION_YIELD_MS,\n maxOutputTokens: 4_000,\n };\n let result: ExecResultLike | string;\n if (typeof this.session.exec === \"function\") {\n result = await this.session.exec(args);\n } else if (typeof this.session.execCommand === \"function\") {\n result = await this.session.execCommand(args);\n } else {\n throw new ComputerUnavailableError(\"session cannot run commands (no exec/execCommand)\");\n }\n const output = sandboxCommandOutput(result);\n if (sandboxCommandStillRunning(result)) {\n // F3: the command exceeded the yield window. WARN AND RETURN rather than\n // throw. Throwing here causes the SDK's catch in `_runComputerActionAndScreenshot`\n // to set output='' and build `{image_url:\"\"}` → Azure 400. By returning\n // instead, the SDK proceeds past the action loop and calls computer.screenshot()\n // so the model gets the REAL current frame for its next step.\n //\n // screenshot()'s FAIL-LOUD + retry contract is preserved: if scrot itself\n // times out (very unlikely at 15 s), x() returns here, readScreenshotBytes\n // produces empty bytes, and the retry loop eventually throws. The wire-level\n // backstop in computerCallNormalizingFetch is also in place as a second net.\n console.warn(\n `[SandboxComputer] action command did not finish before the ${ACTION_YIELD_MS}ms yield window — proceeding to screenshot: ${redactSensitiveText(cmd)}`,\n );\n return output;\n }\n const exitCode = sandboxCommandExitCode(result);\n if (exitCode !== null && exitCode !== 0) {\n throw new ComputerActionError(cmd, exitCode, output);\n }\n return output;\n }\n\n private guardWrite() {\n if (this.readOnly) throw new ComputerReadOnlyError();\n }\n private shq(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n }\n\n async screenshot(): Promise<string> {\n // F2: scrot to a /tmp file, then read the RAW PNG bytes by running `base64\n // <path>` over the SAME command primitive (exec ?? execCommand) and stripping\n // the banner — NOT `session.readFile`. On Modal, readFile path-validates the\n // path against the /workspace root and THROWS for /tmp (\"Sandbox path\n // /tmp/og-shot-*.png escapes the workspace root\"), so the scrot could never be\n // read → empty frame → `image_url: ''` → the model 400s. The base64-over-exec\n // mechanism (mirroring Channel A's bounded file reads\n // fsReadViaExec) is /tmp-readable and binary-safe. We do NOT use execCommand's\n // body via the `this.x()` parser — that drops the execCommand string body; the\n // banner is stripped explicitly here so the base64 payload survives intact.\n //\n // CRITICAL CONTRACT: this NEVER returns an empty string. The Agents SDK builds\n // the model-facing image as `data:image/png;base64,${output}` — so an empty\n // `output` becomes `image_url: ''`, which the model API rejects with\n // \"400 Invalid input[N].output.image_url, expected a valid URL\" and kills the\n // turn. An empty/failed frame is therefore a THROW (a clear action failure the\n // SDK surfaces), never a silent \"\". We also self-heal a transient cold-display\n // frame: bounded retries with a short wait between attempts, so a :0 that is up\n // but momentarily not painting (XFCE/dbus still warming) recovers without\n // failing the turn.\n let lastError: unknown;\n const deadline = Date.now() + this.screenshotWarmupBudgetMs;\n let attempt = 0;\n // Retry across a WALL-CLOCK budget (not a fixed count): a stone-cold box on the\n // first post-swap / post-cold turn can take 20s+ to paint, and a zero-byte frame\n // is a KNOWN transient during that warm-up — not a reason to fail the turn.\n while (true) {\n if (attempt > 0) {\n await new Promise((r) => setTimeout(r, this.screenshotRetryDelayMs));\n }\n attempt++;\n const f = `${this.tmp}/og-shot-${Date.now()}-${Math.random().toString(36).slice(2)}.png`;\n try {\n await this.x(`scrot --pointer --overwrite ${f}`);\n const bytes = await this.readScreenshotBytes(f);\n if (bytes.length === 0) {\n // A cold/not-yet-painting :0 yields a zero-byte frame. Retry rather than\n // hand the model an empty image_url; throw once the budget is spent.\n throw new ComputerUnavailableError(\n \"scrot produced an empty screenshot (display not up?)\",\n );\n }\n return Buffer.from(bytes).toString(\"base64\");\n } catch (error) {\n lastError = error;\n // A short/truncated read is deterministic (the exec-output cap), not a warm-up\n // transient — retrying only burns the budget and delays a legible failure. Fail\n // loud NOW (the `finally` still cleans up the temp file).\n if (error instanceof ScreenshotReadError) {\n throw error;\n }\n } finally {\n // Best-effort cleanup on every attempt (success OR failure); never mask the\n // screenshot result.\n // If preparation itself failed, scrot never ran and no file exists. Do\n // not route cleanup through x(), because that would retry the expensive\n // display preparation merely to delete a nonexistent path.\n if (this.prepared) {\n await this.x(`rm -f ${f}`).catch(() => undefined);\n }\n }\n // Stop once the warm-up budget is spent — the NEXT sleep would push us past it.\n if (Date.now() + this.screenshotRetryDelayMs >= deadline) {\n break;\n }\n }\n // Exhausted the warm-up budget: FAIL LOUD. A clear throw is the only acceptable\n // outcome — returning \"\" here would surface to the model as an invalid empty\n // image_url. Reaching here means the display was still dead after ~30s, not merely\n // warming, so a hard action failure is correct.\n if (lastError instanceof Error) {\n throw lastError;\n }\n throw new ComputerUnavailableError(\"scrot produced an empty screenshot (display not up?)\");\n }\n\n // Run a read-only command over the SAME command primitive computer actions use\n // (exec ?? execCommand) and return its RAW stdout body — NOT `session.readFile` (Modal\n // path-validates against /workspace and rejects /tmp) and NOT `this.x()` (its\n // `sandboxCommandOutput` parser drops the execCommand STRING body). exec exposes a\n // structured stdout; execCommand returns the formatted STRING, so we strip its banner\n // (\"…Output:\\n<body>\") to recover the body.\n //\n // ROUTING-PROXY SEAM: when the selfhosted feature is on, the turn's box is wrapped in a\n // `RoutingSandboxSession`, which ALWAYS exposes an `exec` method — but for a Modal-backed\n // box (no native `exec`) that method internally falls back to `execCommand` and returns\n // the formatted STRING, not a `{output}` object. `sandboxCommandOutput` returns \"\" for a\n // string, so a naive `sandboxCommandOutput(await session.exec())` silently dropped the\n // whole screenshot body → empty read → \"display not up\" error card on EVERY Modal\n // computer-use turn once routing was enabled. So a STRING exec result is banner-stripped\n // exactly like the direct execCommand path; only a structured object goes to\n // sandboxCommandOutput.\n private async readCmdRaw(cmd: string): Promise<string> {\n const args = {\n cmd,\n ...(this.runAs ? { runAs: this.runAs } : {}),\n yieldTimeMs: ACTION_YIELD_MS,\n // null disables the provider's TOKEN truncation; the byte cap this method chunks\n // around is a separate, lower-level exec-stdout buffer limit.\n maxOutputTokens: null as unknown as number,\n };\n if (typeof this.session.exec === \"function\") {\n const result = await this.session.exec(args);\n // A routing proxy fronting a Modal box returns the execCommand banner STRING;\n // a native structured exec returns an object. Handle both so neither silently\n // yields an empty body.\n return typeof result === \"string\" ? stripExecBanner(result) : sandboxCommandOutput(result);\n }\n if (typeof this.session.execCommand === \"function\") {\n return stripExecBanner(await this.session.execCommand(args));\n }\n throw new ComputerUnavailableError(\n \"session cannot run commands (no exec/execCommand) — screenshots unavailable\",\n );\n }\n\n // Read the screenshot PNG bytes off the box. A SINGLE `base64 <file>` over Modal's\n // exec silently returns \"\" once the base64 exceeds the exec-stdout buffer cap (a full\n // desktop ~296 KB base64 trips it — the blank-frame incident). So we size the file\n // first, then base64 it in SCREENSHOT_READ_CHUNK_BYTES-sized, 3-byte-aligned chunks\n // (each read's base64 stays well under the cap) and reconstruct — validating the total\n // against the on-box size and failing LOUD on any short read rather than handing back a\n // truncated/blank frame. Binary-safe: base64 is plain ASCII over stdout.\n private async readScreenshotBytes(path: string): Promise<Uint8Array> {\n // On-box byte size (tiny output — always safe). A still-warming :0 can yield a\n // zero-byte scrot file; report empty so the caller retries within its warm-up budget.\n const sizeRaw = (await this.readCmdRaw(`wc -c < ${path} 2>/dev/null`)).replace(/[^0-9]/g, \"\");\n const fileSize = Number.parseInt(sizeRaw, 10);\n if (!Number.isFinite(fileSize) || fileSize <= 0) return new Uint8Array();\n\n const chunks: Buffer[] = [];\n const nChunks = Math.ceil(fileSize / SCREENSHOT_READ_CHUNK_BYTES);\n for (let i = 0; i < nChunks; i++) {\n // `dd bs=CHUNK skip=i count=1` reads bytes [i*CHUNK, (i+1)*CHUNK); CHUNK % 3 == 0\n // so each chunk's base64 is self-contained and decoded chunks concatenate exactly.\n const raw = await this.readCmdRaw(\n `dd if=${path} bs=${SCREENSHOT_READ_CHUNK_BYTES} skip=${i} count=1 2>/dev/null | base64`,\n );\n chunks.push(Buffer.from(raw.replace(/\\s+/g, \"\"), \"base64\"));\n }\n const bytes = Buffer.concat(chunks);\n if (bytes.length !== fileSize) {\n throw new ScreenshotReadError(\n `screenshot read reconstructed ${bytes.length}B of ${fileSize}B (${nChunks} chunk(s), path=${path}) — a chunk was truncated by the exec-output cap; frame incomplete`,\n );\n }\n return new Uint8Array(bytes);\n }\n\n async click(xp: number, yp: number, button: ComputerButton) {\n this.guardWrite();\n await this.x(`xdotool mousemove --sync ${xp} ${yp} click ${BUTTON_NUM[button] ?? 1}`);\n }\n async doubleClick(xp: number, yp: number) {\n this.guardWrite();\n await this.x(`xdotool mousemove --sync ${xp} ${yp} click --repeat 2 --delay 60 1`);\n }\n async move(xp: number, yp: number) {\n this.guardWrite();\n await this.x(`xdotool mousemove --sync ${xp} ${yp}`);\n }\n async scroll(xp: number, yp: number, sx: number, sy: number) {\n this.guardWrite();\n // F5: model deltas are PIXELS — convert to wheel notches, clamp.\n const notches = (px: number): number =>\n Math.min(SCROLL_MAX_CLICKS, Math.max(0, Math.round(Math.abs(px) / SCROLL_NOTCH_PIXELS)));\n const vBtn = sy < 0 ? 4 : 5;\n const hBtn = sx < 0 ? 6 : 7;\n const vN = notches(sy);\n const hN = notches(sx);\n let cmd = `xdotool mousemove --sync ${xp} ${yp}`;\n if (vN) cmd += ` click --repeat ${vN} ${vBtn}`;\n if (hN) cmd += ` click --repeat ${hN} ${hBtn}`;\n await this.x(cmd);\n }\n async type(text: string) {\n this.guardWrite();\n await this.x(`xdotool type --delay ${this.typeDelayMs} -- ${this.shq(text)}`);\n }\n async keypress(keys: string[]) {\n this.guardWrite();\n const combo = keys.map(toKeysym).join(\"+\");\n await this.x(`xdotool key -- ${this.shq(combo)}`);\n }\n async drag(path: [number, number][]) {\n this.guardWrite();\n if (path.length === 0) return;\n const [sx0, sy0] = path[0]!;\n let cmd = `xdotool mousemove --sync ${sx0} ${sy0} mousedown 1`;\n for (const [px, py] of path.slice(1)) cmd += ` mousemove --sync ${px} ${py}`;\n cmd += ` mouseup 1`;\n await this.x(cmd);\n }\n async wait() {\n await new Promise((r) => setTimeout(r, 1000));\n }\n}\n\n// ── The native-desktop computer (self-hosted / macOS) ────────────────────────\n//\n// `SandboxComputer` drives the desktop by shelling out to xdotool/scrot over the\n// session's `exec` — which needs those X utilities installed in the box image and\n// only works under X11. A SELF-HOSTED machine (macOS OR bring-your-own Linux) has\n// neither guarantee, so it drives the desktop NATIVELY over the control plane: the\n// Rust agent injects input via CGEvent (macOS) / XTEST (Linux) and captures via\n// ScreenCaptureKit / x11, exposed as the two `SelfhostedSession` ops below. No\n// xdotool/scrot dependency; works on macOS.\n\n/** The structural slice of a self-hosted session the native computer drives — the\n * two control-plane ops added in session.ts. Kept structural (NOT an import of\n * `SelfhostedSession`) so this agent-loop file never hard-couples to the sandbox\n * leaf; the duck-typed `isNativeDesktopSession` probe (below) selects on it. */\nexport type NativeDesktopSession = {\n desktopInput(event: DesktopInputRequest[\"event\"]): Promise<void>;\n // `nativeWidth`/`nativeHeight` are the PRE-DOWNSCALE capture geometry (equal to\n // width/height when the agent did not have to shrink the PNG to fit the transport\n // budget). NativeDesktopComputer scales model clicks from the ENCODED pixel space\n // back to native pixels using their ratio before injecting.\n screenshot(): Promise<{\n png: Uint8Array;\n width: number;\n height: number;\n nativeWidth: number;\n nativeHeight: number;\n }>;\n};\n\n/** Model `Button` → wire `PointerButton`. The proto has no back/forward button, so\n * those degrade to UNSPECIFIED (the agent ignores an unmapped button rather than\n * mis-clicking). A total record so indexing is exhaustive. */\nconst POINTER_BUTTON: Record<ComputerButton, PointerButton> = {\n left: PointerButton.POINTER_BUTTON_LEFT,\n right: PointerButton.POINTER_BUTTON_RIGHT,\n wheel: PointerButton.POINTER_BUTTON_MIDDLE,\n back: PointerButton.POINTER_BUTTON_UNSPECIFIED,\n forward: PointerButton.POINTER_BUTTON_UNSPECIFIED,\n};\n\n// Native capture (ScreenCaptureKit / x11) can hand back a null/empty FIRST frame in\n// the moments right after the agent connects — the capture stream still warming — the\n// same class of transient the scrot path retries around for a cold :0. Native capture\n// is normally sub-second, so the warm-up budget is much shorter than the scrot path's\n// 30 s cold-Modal-box budget; enough to ride a first-frame miss, not enough to hang a\n// turn on a genuinely dead capture. A TERMINAL failure (permission denied) short-\n// circuits the budget and fails immediately.\nconst NATIVE_SCREENSHOT_WARMUP_BUDGET_MS = 6_000;\nconst NATIVE_SCREENSHOT_RETRY_DELAY_MS = 400;\n\nexport type NativeDesktopComputerOptions = {\n dimensions?: [number, number]; // the display geometry (must match the capture size)\n environment?: NonNullable<Computer[\"environment\"]>; // \"ubuntu\" (default) | \"mac\" | ...; model uses it for OS key conventions\n readOnly?: boolean; // when true, every WRITE action throws ComputerReadOnlyError\n screenshotWarmupBudgetMs?: number; // wall-clock budget to retry a warming/empty first frame\n screenshotRetryDelayMs?: number; // delay between warm-up retries\n};\n\n/** A capture failure that RETRYING cannot cure — Screen Recording (TCC) has not been\n * granted to the agent, so every capture will deny until the user grants it. We fail\n * FAST on this rather than burn the warm-up budget, and surface the reason verbatim so\n * the operator sees \"grant Screen Recording\", not a blank screen. Matches the agent's\n * `capture_rgba` denial strings (\"Screen Recording permission is not granted\",\n * \"no shareable content (Screen Recording denied?)\"). */\nfunction isTerminalCaptureDenial(error: unknown): boolean {\n const msg = (error instanceof Error ? error.message : String(error ?? \"\")).toLowerCase();\n return (\n msg.includes(\"screen recording\") ||\n msg.includes(\"permission is not granted\") ||\n msg.includes(\"consent\")\n );\n}\n\n/**\n * A `Computer` that drives a SELF-HOSTED machine's OWN desktop NATIVELY over the\n * control plane (`desktopInput` inject + `screenshot` capture on the bound\n * `SelfhostedSession`) instead of xdotool/scrot over `exec`. Consent + epoch are\n * enforced AGENT-side, so an unconsented inject surfaces the session's mapped\n * control error.\n *\n * screenshot() returns raw base64 with NO data-URL prefix — the EXACT contract of\n * `SandboxComputer.screenshot`: the Agents SDK wraps it as\n * `data:image/png;base64,${output}`, so an empty string would become\n * `image_url: ''` and 400 the model turn. An empty PNG therefore THROWS\n * `ComputerUnavailableError` (mirroring SandboxComputer's empty-guard) — the model\n * never receives an empty image_url.\n */\nexport class NativeDesktopComputer implements Computer {\n readonly environment: NonNullable<Computer[\"environment\"]>;\n readonly dimensions: [number, number];\n private session: NativeDesktopSession;\n private readonly readOnly: boolean;\n private readonly screenshotWarmupBudgetMs: number;\n private readonly screenshotRetryDelayMs: number;\n // The ENCODED vs NATIVE geometry of the MOST RECENT screenshot the model saw. The\n // model computes click coordinates in the encoded-pixel space of that screenshot;\n // when the agent downscaled the PNG to fit the transport budget, encoded < native,\n // so we scale coordinates back up to native pixels before injecting (the agent's\n // native inject — macOS CGEvent / Linux XTEST — expects native-pixel coordinates,\n // exactly as it received them pre-downscale). Null until the first screenshot;\n // equal encoded==native (or absent) ⇒ scale factor 1.0 ⇒ byte-identical behavior.\n private lastEncoded: [number, number] | null = null;\n private lastNative: [number, number] | null = null;\n\n constructor(session: NativeDesktopSession, opts: NativeDesktopComputerOptions = {}) {\n this.session = session;\n this.dimensions = opts.dimensions ?? DEFAULT_DIMENSIONS;\n // Default \"ubuntu\" (self-hosted Linux is the near-term target); a macOS session\n // should pass \"mac\" so the model uses ⌘-based shortcuts — see the coordinate TODO.\n this.environment = opts.environment ?? \"ubuntu\";\n this.readOnly = opts.readOnly ?? false;\n this.screenshotWarmupBudgetMs =\n opts.screenshotWarmupBudgetMs ?? NATIVE_SCREENSHOT_WARMUP_BUDGET_MS;\n this.screenshotRetryDelayMs = opts.screenshotRetryDelayMs ?? NATIVE_SCREENSHOT_RETRY_DELAY_MS;\n }\n\n /** Rebind to a freshly resumed-by-id session after a box rollover / re-establish. */\n rebind(session: NativeDesktopSession) {\n this.session = session;\n }\n\n private guardWrite() {\n if (this.readOnly) throw new ComputerReadOnlyError();\n }\n\n /** Scale a coordinate the model expressed in the MOST RECENT screenshot's\n * ENCODED pixel space back to NATIVE pixels. When the last frame was not\n * downscaled (encoded == native), or no screenshot has been taken yet, this is a\n * 1:1 identity — the byte-identical current behavior. The agent then applies its\n * own platform mapping (macOS divides native pixels by the backing scale to reach\n * CGEvent points; Linux XTEST is 1:1) exactly as it did pre-downscale. */\n private toNative(x: number, y: number): { x: number; y: number } {\n const enc = this.lastEncoded;\n const nat = this.lastNative;\n if (!enc || !nat || enc[0] <= 0 || enc[1] <= 0) return { x, y };\n if (enc[0] === nat[0] && enc[1] === nat[1]) return { x, y };\n return {\n x: Math.round((x * nat[0]) / enc[0]),\n y: Math.round((y * nat[1]) / enc[1]),\n };\n }\n\n private async pointer(\n x: number,\n y: number,\n action: PointerAction,\n button: PointerButton,\n ): Promise<void> {\n // COORDINATE SEAM: the model computes x/y against the pixels of the screenshot it\n // just saw — which the agent may have DOWNSCALED to fit the transport's max\n // payload (a full-res Retina/busy screen exceeds NATS's 1 MiB default). We scale\n // those encoded-pixel coordinates back to native pixels here, using the native\n // geometry the last screenshot reported, so the agent's native inject lands the\n // click where the model intended. When no downscale occurred the factor is 1.0\n // and the coordinates pass through unchanged. Self-hosted Linux (XTEST/x11) and\n // any non-downscaled frame are 1:1 and unaffected.\n const n = this.toNative(x, y);\n await this.session.desktopInput({\n $case: \"pointer\",\n pointer: { x: n.x, y: n.y, action, button },\n });\n }\n\n async screenshot(): Promise<string> {\n // CRITICAL CONTRACT (mirrors SandboxComputer.screenshot): NEVER return \"\". The\n // Agents SDK builds the model image as `data:image/png;base64,${output}`; an\n // empty output → `image_url: ''`. On the hosted computer_use_preview path the SDK\n // catches a throw here, sets output='', and the wire-seam sanitizer rewrites the\n // empty image_url to a BLANK 1×1 placeholder to dodge a 400 — so a capture MISS\n // silently reaches the model as a \"blank desktop\" it then confidently reports.\n //\n // Native capture (ScreenCaptureKit / x11) can hand back a null/empty FIRST frame\n // in the moments right after the agent connects (the capture stream warming) — the\n // same transient the scrot path retries around for a cold :0. This path previously\n // did a SINGLE capture, so one warm-up miss became a blank. We now RETRY across a\n // bounded budget and, on a terminal failure, FAIL LOUD with the agent's actual\n // reason (logged) — never a silent blank. A permission (TCC) denial is terminal:\n // retrying cannot grant Screen Recording, so we break immediately.\n let lastError: unknown;\n const deadline = Date.now() + this.screenshotWarmupBudgetMs;\n let attempt = 0;\n while (true) {\n if (attempt > 0) {\n await new Promise((r) => setTimeout(r, this.screenshotRetryDelayMs));\n }\n attempt++;\n try {\n const { png, width, height, nativeWidth, nativeHeight } = await this.session.screenshot();\n if (png.length === 0) {\n // A warming capture yields an empty frame — retry rather than hand the model\n // a blank; throw once the budget is spent.\n throw new ComputerUnavailableError(\n \"native desktop screenshot returned an empty frame (display not up?)\",\n );\n }\n // Record the encoded (what the model sees) vs native geometry of THIS frame so\n // the next click/move/scroll/drag scales its coordinates back to native pixels.\n this.lastEncoded = [width, height];\n this.lastNative = [nativeWidth || width, nativeHeight || height];\n return Buffer.from(png).toString(\"base64\");\n } catch (error) {\n lastError = error;\n // A permission denial will deny on every retry — fail fast with the reason.\n if (isTerminalCaptureDenial(error)) break;\n }\n // Stop once the warm-up budget is spent — the NEXT sleep would push us past it.\n if (Date.now() + this.screenshotRetryDelayMs >= deadline) {\n break;\n }\n }\n // Exhausted the budget (or hit a terminal denial): FAIL LOUD. Log the specific\n // reason so the failure is DIAGNOSABLE (not a silent blank the model misreads),\n // then rethrow — never return \"\".\n const reason = redactSensitiveText(\n lastError instanceof Error ? lastError.message : String(lastError),\n );\n console.warn(\n `[NativeDesktopComputer] screenshot failed after ${attempt} attempt(s): ${reason}`,\n );\n if (lastError instanceof Error) {\n throw lastError;\n }\n throw new ComputerUnavailableError(\n \"native desktop screenshot returned an empty frame (display not up?)\",\n );\n }\n\n async click(x: number, y: number, button: ComputerButton) {\n this.guardWrite();\n await this.pointer(\n x,\n y,\n PointerAction.POINTER_ACTION_CLICK,\n POINTER_BUTTON[button] ?? PointerButton.POINTER_BUTTON_LEFT,\n );\n }\n async doubleClick(x: number, y: number) {\n this.guardWrite();\n await this.pointer(\n x,\n y,\n PointerAction.POINTER_ACTION_DOUBLE_CLICK,\n PointerButton.POINTER_BUTTON_LEFT,\n );\n }\n async move(x: number, y: number) {\n this.guardWrite();\n await this.pointer(\n x,\n y,\n PointerAction.POINTER_ACTION_MOVE,\n PointerButton.POINTER_BUTTON_UNSPECIFIED,\n );\n }\n async scroll(x: number, y: number, sx: number, sy: number) {\n this.guardWrite();\n // The scroll ANCHOR (x,y) is a screenshot-pixel position → scale to native like a\n // click. The deltas (sx,sy) are relative scroll AMOUNTS, not positions; the agent\n // owns the platform-appropriate wheel translation, so they pass through unscaled\n // (no xdotool \"notch\" quantization here — that is an xdotool-specific artifact).\n const n = this.toNative(x, y);\n await this.session.desktopInput({\n $case: \"scroll\",\n scroll: { x: n.x, y: n.y, deltaX: sx, deltaY: sy },\n });\n }\n async type(text: string) {\n this.guardWrite();\n // A literal text burst: isText:true tells the agent to type the string verbatim\n // (Unicode-aware) rather than interpret it as a key name.\n await this.session.desktopInput({\n $case: \"key\",\n key: { key: text, isText: true, action: KeyAction.KEY_ACTION_PRESS },\n });\n }\n async keypress(keys: string[]) {\n this.guardWrite();\n // A chord (\"ctrl+c\") as ONE non-text KeyEvent (isText:false ⇒ interpret as key\n // names). We send the model's PLATFORM-INDEPENDENT key names joined with \"+\" —\n // NOT xdotool X keysyms (SandboxComputer's toKeysym maps to \"Return\"/\"super\"/\n // \"Prior\", which are X-specific and wrong for the macOS CGEvent path). The agent\n // owns the per-platform key-name → keycode mapping (the KeyEvent.key contract).\n await this.session.desktopInput({\n $case: \"key\",\n key: { key: keys.join(\"+\"), isText: false, action: KeyAction.KEY_ACTION_PRESS },\n });\n }\n async drag(path: [number, number][]) {\n this.guardWrite();\n if (path.length === 0) return;\n // Press at the start, move through each waypoint with the button held, release at\n // the last point. The agent tracks button state across the DOWN → MOVE… → UP.\n const [sx, sy] = path[0]!;\n await this.pointer(\n sx,\n sy,\n PointerAction.POINTER_ACTION_DOWN,\n PointerButton.POINTER_BUTTON_LEFT,\n );\n for (const [px, py] of path.slice(1)) {\n await this.pointer(\n px,\n py,\n PointerAction.POINTER_ACTION_MOVE,\n PointerButton.POINTER_BUTTON_LEFT,\n );\n }\n const [ex, ey] = path[path.length - 1]!;\n await this.pointer(ex, ey, PointerAction.POINTER_ACTION_UP, PointerButton.POINTER_BUTTON_LEFT);\n }\n async wait() {\n await new Promise((r) => setTimeout(r, 1000));\n }\n}\n\n/**\n * Backend-aware SELECTION discriminator: a SELF-HOSTED session exposes the two\n * native control-plane ops (`desktopInput` + `screenshot`); a MODAL session does\n * not (it drives the desktop via xdotool/scrot over `exec`). Duck-typing on those\n * two methods keeps this file from hard-importing `SelfhostedSession` (avoiding an\n * agent-loop ↔ sandbox-leaf import coupling) and is future-proof: any backend that\n * grows native inject/capture is picked up automatically.\n */\nexport function isNativeDesktopSession(\n session: SandboxSessionLike,\n): session is SandboxSessionLike & NativeDesktopSession {\n const s = session as Partial<NativeDesktopSession>;\n return typeof s.desktopInput === \"function\" && typeof s.screenshot === \"function\";\n}\n\n// ── Function-transport (codex / text backend) computer tools ─────────────────\n//\n// The SDK emits computer-use ONLY as the HOSTED `computer_use_preview` tool, which\n// the codex / ChatGPT backend rejects (it accepts only function/custom/web_search\n// tool types) — so on codex the hosted tool is unusable and the agent has nothing\n// to drive the desktop with. We mirror EXACTLY how the SDK's filesystem capability\n// degrades `view_image` for the text transport: when the bound model does NOT\n// support the structured tool-output transport, emit a set of FUNCTION tools that\n// route to the SAME bound `Computer`, and hand the model the screen by rendering\n// the screenshot image-output as a text-transport data URL — the identical two-step\n// `imageOutputFromBytes` → `renderImageForTextTransport` the SDK's text `view_image`\n// uses. Those three helpers are NOT public exports of `@openai/agents` /\n// `@openai/agents/sandbox` (they live in the SDK's private capabilities/transport +\n// shared/media modules, unreachable via the package `exports` map), so — mirroring\n// selfhosted/session.ts's local `sniffImageMediaType` — the three tiny pure helpers\n// are reimplemented here in lockstep with the SDK.\n\n/** The SDK's tool-output image shape (@openai/agents-core shared/media `ToolOutputImage`). */\ntype ToolOutputImage = { type: \"image\"; image: { data: Uint8Array; mediaType: string } };\n\n/** Magic-byte image sniff, in lockstep with the SDK's `sniffImageMediaType`\n * (shared/media). Screenshots are always PNG (scrot / ScreenCaptureKit / x11), so\n * an unrecognized header defaults to image/png rather than failing the frame. */\nfunction sniffScreenshotMediaType(bytes: Uint8Array): string {\n if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47)\n return \"image/png\";\n if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return \"image/jpeg\";\n if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38)\n return \"image/gif\";\n if (\n bytes[0] === 0x52 &&\n bytes[1] === 0x49 &&\n bytes[2] === 0x46 &&\n bytes[3] === 0x46 &&\n bytes[8] === 0x57 &&\n bytes[9] === 0x45 &&\n bytes[10] === 0x42 &&\n bytes[11] === 0x50\n )\n return \"image/webp\";\n return \"image/png\";\n}\n\n/** Build the SDK `ToolOutputImage` from raw screenshot bytes — the structured shape\n * the SDK's `imageOutputFromBytes` produces (`{type:'image', image:{data,mediaType}}`). */\nfunction imageOutputFromScreenshotBytes(bytes: Uint8Array): ToolOutputImage {\n return {\n type: \"image\",\n image: { data: Uint8Array.from(bytes), mediaType: sniffScreenshotMediaType(bytes) },\n };\n}\n\n/** Render an image tool-output as a text-transport string, in lockstep with the\n * SDK's private `renderImageForTextTransport` (capabilities/filesystem). Our image\n * output always carries `data` as bytes, so it becomes a `data:<mediaType>;base64,…`\n * URL — the exact form the text-backend `view_image` hands the model. */\nfunction renderImageForTextTransport(output: ToolOutputImage | string): string {\n if (typeof output === \"string\") return output;\n const { image } = output;\n const mediaType =\n typeof image.mediaType === \"string\" ? image.mediaType : \"application/octet-stream\";\n return `data:${mediaType};base64,${Buffer.from(image.data).toString(\"base64\")}`;\n}\n\nconst COMPUTER_READ_ONLY_MESSAGE =\n \"computer-use is read-only for this session — click, double_click, move, scroll, type, keypress, and drag are disabled. Call computer_screenshot to observe the desktop.\";\n\n// The two coordinate properties every pointer tool shares. Raw JSON schema (NOT\n// zod: zod is not a @opengeni/runtime dependency) with `strict:false`, mirroring the\n// SDK's own `apply_patch` function-tool schema style.\nconst COORD_PROPS = {\n x: {\n type: \"integer\",\n description: \"X coordinate in the pixels of the most recent computer_screenshot\",\n },\n y: {\n type: \"integer\",\n description: \"Y coordinate in the pixels of the most recent computer_screenshot\",\n },\n} as const;\n\nfunction objectSchema(\n properties: Record<string, unknown>,\n required: string[],\n): Record<string, unknown> {\n return { type: \"object\", properties, required, additionalProperties: false };\n}\n\n/**\n * The FUNCTION-transport computer tools for the codex / text backend, each routing\n * to the SAME bound `Computer` the hosted `computer_use_preview` tool would drive.\n * `computer_screenshot` hands the model the desktop two ways, selected by\n * `imageFunctionResults`:\n * • false (chat-completions providers, the default) → the text-transport\n * `data:image/png;base64,…` URL (imageOutputFromBytes → renderImageForTextTransport,\n * the SDK's text `view_image` path) — those backends can't read structured image\n * tool results.\n * • true (the codex/ChatGPT backend) → the structured `{type:'image'}` tool output,\n * which agents-core normalizes into an `input_image` content item inside the\n * function_call_output — the codex /responses backend accepts and SEES it (a text\n * data-URL there is just unreadable text). See index.ts for why it's on there.\n * Write tools return a concise confirmation; when read-only they return\n * {@link COMPUTER_READ_ONLY_MESSAGE} instead of throwing, and any action error is\n * returned as a string so a failed action never kills the turn. Exported so it can be\n * unit-tested against a fake `Computer`.\n */\nexport function computerFunctionTools(\n computer: Computer,\n readOnly: boolean,\n needsApproval?: ComputerUseArgs[\"needsApproval\"],\n imageFunctionResults = false,\n): Tool<unknown>[] {\n const approval = needsApproval !== undefined ? { needsApproval: needsApproval as never } : {};\n // Perform a WRITE action, surfacing read-only / failures as a model-readable\n // string rather than an uncaught throw (an uncaught throw becomes a tool error\n // the backend may 400 on, or kills the step).\n const write = async (\n confirmation: string,\n action: () => void | Promise<void>,\n ): Promise<string> => {\n if (readOnly) return COMPUTER_READ_ONLY_MESSAGE;\n try {\n await action();\n return confirmation;\n } catch (error) {\n if (error instanceof ComputerReadOnlyError) return COMPUTER_READ_ONLY_MESSAGE;\n return `computer action failed: ${error instanceof Error ? error.message : String(error)}`;\n }\n };\n\n return [\n tool({\n name: \"computer_screenshot\",\n description:\n \"Capture the current desktop and return it as an image. Call this FIRST and again after each action — all coordinates for click/move/scroll/drag are pixels of the most recent screenshot.\",\n parameters: objectSchema({}, []) as never,\n strict: false,\n execute: async () => {\n // screenshot() returns raw base64 PNG and NEVER an empty string (it throws\n // instead), so the model can't receive an empty image_url.\n const b64 = await computer.screenshot();\n const bytes = Uint8Array.from(Buffer.from(b64, \"base64\"));\n const image = imageOutputFromScreenshotBytes(bytes);\n // On the codex backend return the structured image output so the model SEES\n // the desktop (agents-core normalizes {type:'image'} → an input_image data-URL\n // content item in the function_call_output); chat-completions providers get\n // the text data-URL string they expect.\n return imageFunctionResults ? image : renderImageForTextTransport(image);\n },\n }),\n tool({\n name: \"computer_click\",\n description:\n \"Click the mouse at (x, y). `button` is one of left|right|wheel|back|forward (default left). Take a computer_screenshot first to find coordinates.\",\n parameters: objectSchema(\n {\n ...COORD_PROPS,\n button: {\n type: \"string\",\n enum: [\"left\", \"right\", \"wheel\", \"back\", \"forward\"],\n description: \"Mouse button; defaults to left\",\n },\n },\n [\"x\", \"y\"],\n ) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { x, y, button } = input as { x: number; y: number; button?: ComputerButton };\n return write(`clicked ${button ?? \"left\"} at (${x}, ${y})`, () =>\n computer.click(x, y, button ?? \"left\"),\n );\n },\n }),\n tool({\n name: \"computer_double_click\",\n description:\n \"Double-click the left mouse button at (x, y). Take a computer_screenshot first to find coordinates.\",\n parameters: objectSchema({ ...COORD_PROPS }, [\"x\", \"y\"]) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { x, y } = input as { x: number; y: number };\n return write(`double-clicked at (${x}, ${y})`, () => computer.doubleClick(x, y));\n },\n }),\n tool({\n name: \"computer_move\",\n description: \"Move the mouse cursor to (x, y) without clicking.\",\n parameters: objectSchema({ ...COORD_PROPS }, [\"x\", \"y\"]) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { x, y } = input as { x: number; y: number };\n return write(`moved to (${x}, ${y})`, () => computer.move(x, y));\n },\n }),\n tool({\n name: \"computer_scroll\",\n description:\n \"Scroll at (x, y) by scroll_x / scroll_y pixels (positive scroll_y scrolls down, negative up; positive scroll_x scrolls right).\",\n parameters: objectSchema(\n {\n ...COORD_PROPS,\n scroll_x: {\n type: \"integer\",\n description: \"Horizontal scroll amount in pixels (positive = right)\",\n },\n scroll_y: {\n type: \"integer\",\n description: \"Vertical scroll amount in pixels (positive = down)\",\n },\n },\n [\"x\", \"y\", \"scroll_x\", \"scroll_y\"],\n ) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { x, y, scroll_x, scroll_y } = input as {\n x: number;\n y: number;\n scroll_x: number;\n scroll_y: number;\n };\n return write(`scrolled (${scroll_x}, ${scroll_y}) at (${x}, ${y})`, () =>\n computer.scroll(x, y, scroll_x, scroll_y),\n );\n },\n }),\n tool({\n name: \"computer_type\",\n description:\n \"Type a literal text string at the current keyboard focus. Click the target field first.\",\n parameters: objectSchema(\n { text: { type: \"string\", description: \"The literal text to type\" } },\n [\"text\"],\n ) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { text } = input as { text: string };\n return write(`typed ${text.length} character(s)`, () => computer.type(text));\n },\n }),\n tool({\n name: \"computer_keypress\",\n description:\n 'Press a key or chord. `keys` is an ordered list pressed together, e.g. [\"ctrl\",\"c\"] or [\"Enter\"]. Use key names (ctrl, alt, shift, cmd, enter, tab, esc, arrows…), not characters.',\n parameters: objectSchema(\n {\n keys: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Keys pressed together as a chord\",\n },\n },\n [\"keys\"],\n ) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { keys } = input as { keys: string[] };\n return write(`pressed ${keys.join(\"+\")}`, () => computer.keypress(keys));\n },\n }),\n tool({\n name: \"computer_drag\",\n description:\n \"Drag the left mouse button along a path of points. `path` is an ordered list of {x, y} pixels; the button is pressed at the first point, moved through each, and released at the last.\",\n parameters: objectSchema(\n {\n path: {\n type: \"array\",\n description: \"Ordered list of points to drag through\",\n items: {\n type: \"object\",\n properties: { x: { type: \"integer\" }, y: { type: \"integer\" } },\n required: [\"x\", \"y\"],\n additionalProperties: false,\n },\n },\n },\n [\"path\"],\n ) as never,\n strict: false,\n ...approval,\n execute: async (input) => {\n const { path } = input as { path: Array<{ x: number; y: number }> };\n const points = path.map((p) => [p.x, p.y] as [number, number]);\n return write(`dragged through ${points.length} point(s)`, () => computer.drag(points));\n },\n }),\n ] as unknown as Tool<unknown>[];\n}\n\n// ── The capability (the SDK seam) ────────────────────────────────────────────\n\n/**\n * EXPLICIT tool-transport selection, decided by the caller that knows the\n * provider's true wire identity (the worker's model resolution — see agent-turn.ts),\n * never inferred from the bound model instance's constructor name:\n * • \"hosted\" → the single hosted `computer_use_preview` tool (Responses backends).\n * • \"function-image\" → the FUNCTION `computer_*` tools with screenshots delivered as a\n * structured `{type:'image'}` output (the codex/ChatGPT backend,\n * which rejects hosted tool types but SEES structured image results).\n * • \"disabled\" → no computer tools. Providers without a proven visual image\n * transport fail closed instead of receiving base64 as text.\n * • \"function-text\" → deprecated fail-closed alias retained for source compatibility.\n * • omitted → fail closed exactly like \"disabled\"; public runtime callers must\n * prove the transport explicitly before computer tools are exposed.\n */\nexport type ComputerToolMode = \"hosted\" | \"function-image\" | \"disabled\" | \"function-text\";\n\nexport type ComputerUseArgs = {\n dimensions?: [number, number];\n readOnly?: boolean;\n display?: string;\n needsApproval?: boolean | ((ctx: unknown, action: unknown) => boolean | Promise<boolean>);\n /** @deprecated Use `toolMode: \"function-image\"`. Omitted transport now fails closed. */\n imageFunctionResults?: boolean;\n // EXPLICIT transport selection (see {@link ComputerToolMode}). When absent, tools()\n // returns no computer tools; constructor-name sniffing is never a transport proof.\n toolMode?: ComputerToolMode;\n /** Called after the display is ready on the first actual computer action. */\n onReady?: (session: SandboxSessionLike) => Promise<void>;\n};\n\nexport function computerUse(args: ComputerUseArgs = {}): ComputerUseCapability {\n return new ComputerUseCapability(args);\n}\n\n/**\n * A `Capability` subclass merged into the agent's tool set by SandboxAgent\n * (`tools = [...agent.tools, ...capability.tools()]`). `bind(session)` hands it\n * the LIVE externally-owned session, so the agent's actions and the viewers'\n * pixels are one display.\n *\n * `tools()` is transport-aware only through `ComputerUseArgs.toolMode`. The bound\n * model instance is intentionally ignored: a constructor name cannot prove whether\n * screenshots travel as hosted computer output or structured function images.\n */\nexport class ComputerUseCapability extends Capability {\n readonly type = \"computer-use\";\n constructor(private args: ComputerUseArgs = {}) {\n super();\n }\n\n override tools(): Tool<unknown>[] {\n const session = requireBoundSession(\"computer-use\", this._session);\n // Backend-aware: a SELF-HOSTED session (macOS OR bring-your-own Linux) drives the\n // desktop NATIVELY (CGEvent/XTEST inject + ScreenCaptureKit/x11 capture over the\n // control plane) — no xdotool/scrot on the user's machine required. Everything\n // else (Modal) keeps the xdotool/scrot-over-exec SandboxComputer. See\n // `isNativeDesktopSession` for the duck-typed discriminator.\n const computer: Computer = isNativeDesktopSession(session)\n ? new NativeDesktopComputer(session, {\n ...(this.args.dimensions ? { dimensions: this.args.dimensions } : {}),\n ...(this.args.readOnly !== undefined ? { readOnly: this.args.readOnly } : {}),\n })\n : new SandboxComputer(session, {\n ...(this.args.dimensions ? { dimensions: this.args.dimensions } : {}),\n ...(this.args.readOnly !== undefined ? { readOnly: this.args.readOnly } : {}),\n ...(this.args.display ? { display: this.args.display } : {}),\n // The SDK base exposes the bound runAs as a protected field.\n ...(typeof this._runAs === \"string\" ? { runAs: this._runAs } : {}),\n // Crucially lazy: tool registration does no provider work. The first\n // click/type/screenshot boots the display, then lets the worker start\n // any computer-use-only recording. One SandboxComputer instance caches\n // this for the rest of the turn.\n prepare: async (preparedSession) => {\n await ensureDisplayStack(preparedSession, {\n telemetryContext: { callerKind: \"computer\" },\n });\n await this.args.onReady?.(preparedSession);\n },\n });\n // Tool selection must not depend on the model instance's constructor name. The\n // worker supplies a proven explicit mode; public callers that omit it fail closed.\n switch (this.args.toolMode) {\n case \"hosted\":\n return [this.hostedComputerTool(computer)];\n case \"function-image\":\n return computerFunctionTools(\n computer,\n this.args.readOnly ?? false,\n this.args.needsApproval,\n true,\n );\n case \"disabled\":\n case \"function-text\":\n case undefined:\n // A text data URL is not a visual observation for the provider and can\n // consume hundreds of thousands of apparent text tokens. Disable the\n // entire coordinate-dependent capability: action tools without a usable\n // screenshot would be blind and unsafe.\n return [];\n }\n // Runtime callers may bypass TypeScript or pass a value from a newer client.\n // Unknown transport modes must remain fail-closed.\n return [];\n }\n\n /** The single HOSTED `computer_use_preview` tool bound to `computer`. */\n private hostedComputerTool(computer: Computer): Tool<unknown> {\n return computerTool({\n computer,\n ...(this.args.needsApproval !== undefined\n ? { needsApproval: this.args.needsApproval as never }\n : {}),\n }) as unknown as Tool<unknown>;\n }\n}\n","import { createHash } from \"node:crypto\";\n\nimport { Capability, type SandboxSessionLike } from \"@openai/agents/sandbox\";\n\nconst SKILL_FILE = \"SKILL.md\";\nconst MAX_DISCOVERED_SKILLS = 256;\nconst MAX_SKILL_ENTRIES = 1_024;\nconst MAX_SKILL_BYTES = 32 * 1024 * 1024;\nconst SAFE_SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\nexport type WorkspaceSkillSearchPath = Readonly<{\n path: string;\n source: string;\n}>;\n\ntype WorkspaceSkill = Readonly<{\n name: string;\n description: string;\n path: string;\n fingerprint: string;\n source: string;\n}>;\n\n/**\n * Index skills that already exist in the live workspace.\n *\n * Unlike the SDK's `skills({ from })` and `skills({ lazyFrom })` sources, this\n * capability deliberately contributes no manifest entries and materializes\n * nothing. Repository resources and Connected Machines already own these\n * files; the bound sandbox session is the one portable way to inspect them.\n */\nexport class WorkspaceSkillsCapability extends Capability {\n readonly type = \"workspace-skills\";\n private discovery?: Promise<readonly WorkspaceSkill[]>;\n\n constructor(\n private readonly searchPaths: readonly WorkspaceSkillSearchPath[],\n private readonly reservedNames: ReadonlySet<string> = new Set(),\n ) {\n super();\n }\n\n override async instructions(): Promise<string | null> {\n const session = requireWorkspaceSkillSession(this._session);\n this.discovery ??= discoverWorkspaceSkills(\n session,\n this.searchPaths,\n this.reservedNames,\n this._runAs,\n );\n const skills = await this.discovery;\n if (skills.length === 0) return null;\n\n const available = skills\n .map((skill) => `- ${skill.name}: ${skill.description} (file: ${skill.path})`)\n .join(\"\\n\");\n return `## Repository skills\n\nRepository skills are instructions already present in the live workspace. They do not need to be loaded or copied.\n\n### Available repository skills\n${available}\n\n### How to use repository skills\n- If the user names a skill, or the task clearly matches a skill description, read its complete SKILL.md before acting.\n- Resolve referenced scripts, references, assets, and templates relative to that skill directory.\n- Use only the minimum relevant skills for the turn, and say briefly which ones you are using.\n- Do not assume a skill remains applicable on later turns; evaluate the current request again.`;\n }\n}\n\nexport function workspaceSkills(\n searchPaths: readonly WorkspaceSkillSearchPath[],\n reservedNames: Iterable<string> = [],\n): WorkspaceSkillsCapability {\n return new WorkspaceSkillsCapability(\n searchPaths,\n new Set([...reservedNames].map((name) => name.toLowerCase())),\n );\n}\n\nexport async function discoverWorkspaceSkills(\n session: SandboxSessionLike,\n searchPaths: readonly WorkspaceSkillSearchPath[],\n reservedNames: ReadonlySet<string> = new Set(),\n runAs?: string,\n): Promise<readonly WorkspaceSkill[]> {\n if (!session.listDir || !session.readFile) {\n throw new Error(\"Workspace skill discovery requires sandbox listDir() and readFile() support\");\n }\n const discovered = new Map<string, WorkspaceSkill>();\n let candidates = 0;\n for (const searchPath of searchPaths) {\n let entries;\n try {\n entries = await session.listDir({ path: searchPath.path, ...(runAs ? { runAs } : {}) });\n } catch {\n continue;\n }\n for (const entry of [...entries].sort((left, right) => left.name.localeCompare(right.name))) {\n if (entry.type !== \"dir\") continue;\n candidates += 1;\n if (candidates > MAX_DISCOVERED_SKILLS) {\n throw new Error(`Repository skill discovery exceeds ${MAX_DISCOVERED_SKILLS} directories`);\n }\n const skillMarkdownPath = joinWorkspacePath(entry.path, SKILL_FILE);\n let markdown: string;\n try {\n const content = await session.readFile({\n path: skillMarkdownPath,\n ...(runAs ? { runAs } : {}),\n });\n markdown = typeof content === \"string\" ? content : new TextDecoder().decode(content);\n } catch {\n continue;\n }\n const frontmatter = parseSkillFrontmatter(markdown);\n const name = frontmatter.name?.trim() || entry.name;\n if (name.length > 64 || !SAFE_SKILL_NAME.test(name)) {\n throw new Error(`Repository skill has an invalid name: ${name.slice(0, 64)}`);\n }\n const description = frontmatter.description?.trim() || \"No description provided.\";\n if (description.length > 2_048 || /[\\r\\n]/.test(description)) {\n throw new Error(`Repository skill \"${name}\" has an invalid description`);\n }\n const key = name.toLowerCase();\n if (reservedNames.has(key)) {\n throw new Error(`Workspace skill \"${name}\" conflicts with a configured OpenGeni skill`);\n }\n const candidate: WorkspaceSkill = {\n name,\n description,\n path: skillMarkdownPath,\n fingerprint: await fingerprintWorkspaceDirectory(session, entry.path, runAs),\n source: searchPath.source,\n };\n const existing = discovered.get(key);\n if (!existing) {\n discovered.set(key, candidate);\n continue;\n }\n if (existing.fingerprint !== candidate.fingerprint) {\n throw new Error(\n `Workspace skill \"${name}\" has conflicting definitions in ${existing.source} and ${candidate.source}`,\n );\n }\n }\n }\n return [...discovered.values()].sort((left, right) => left.name.localeCompare(right.name));\n}\n\nasync function fingerprintWorkspaceDirectory(\n session: SandboxSessionLike,\n root: string,\n runAs?: string,\n): Promise<string> {\n const hash = createHash(\"sha256\");\n let entryCount = 0;\n let byteCount = 0;\n\n async function visit(path: string, relativePath: string): Promise<void> {\n const entries = await session.listDir!({ path, ...(runAs ? { runAs } : {}) });\n for (const entry of [...entries].sort((left, right) => left.name.localeCompare(right.name))) {\n entryCount += 1;\n if (entryCount > MAX_SKILL_ENTRIES) {\n throw new Error(`Workspace skill exceeds ${MAX_SKILL_ENTRIES} filesystem entries`);\n }\n const childRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;\n hash.update(entry.type);\n hash.update(\"\\0\");\n hash.update(childRelativePath);\n hash.update(\"\\0\");\n if (entry.type === \"dir\") {\n await visit(entry.path, childRelativePath);\n continue;\n }\n if (entry.type !== \"file\") continue;\n const content = await session.readFile!({\n path: entry.path,\n ...(runAs ? { runAs } : {}),\n });\n const bytes = typeof content === \"string\" ? new TextEncoder().encode(content) : content;\n byteCount += bytes.byteLength;\n if (byteCount > MAX_SKILL_BYTES) {\n throw new Error(`Workspace skill exceeds ${MAX_SKILL_BYTES} bytes`);\n }\n hash.update(bytes);\n hash.update(\"\\0\");\n }\n }\n\n await visit(root, \"\");\n return hash.digest(\"hex\");\n}\n\nfunction parseSkillFrontmatter(markdown: string): {\n name?: string;\n description?: string;\n} {\n const lines = markdown.split(/\\r?\\n/);\n if (lines[0]?.trim() !== \"---\") return {};\n const end = lines.findIndex((line, index) => index > 0 && line.trim() === \"---\");\n if (end === -1) return {};\n const values: Record<string, string> = {};\n for (const line of lines.slice(1, end)) {\n const separator = line.indexOf(\":\");\n if (separator === -1) continue;\n const key = line.slice(0, separator).trim();\n if (key !== \"name\" && key !== \"description\") continue;\n values[key] = unquote(line.slice(separator + 1).trim());\n }\n return values;\n}\n\nfunction unquote(value: string): string {\n if (\n value.length >= 2 &&\n value[0] === value[value.length - 1] &&\n (value[0] === '\"' || value[0] === \"'\")\n ) {\n return value.slice(1, -1);\n }\n return value;\n}\n\nfunction joinWorkspacePath(parent: string, child: string): string {\n return `${parent.replace(/\\/+$/, \"\")}/${child}`;\n}\n\nfunction requireWorkspaceSkillSession(session: SandboxSessionLike | undefined): SandboxSessionLike {\n if (!session) {\n throw new Error('capability \"workspace-skills\" used before bind(session)');\n }\n return session;\n}\n","type UsageDetails = Record<string, unknown> | Array<Record<string, unknown>>;\n\ntype RequestUsageEntry = {\n inputTokens?: unknown;\n input_tokens?: unknown;\n outputTokens?: unknown;\n output_tokens?: unknown;\n totalTokens?: unknown;\n total_tokens?: unknown;\n inputTokensDetails?: UsageDetails | undefined;\n input_tokens_details?: UsageDetails | undefined;\n outputTokensDetails?: UsageDetails | undefined;\n output_tokens_details?: UsageDetails | undefined;\n};\n\nexport type ModelCallUsageInput = {\n inputTokens?: unknown;\n outputTokens?: unknown;\n totalTokens?: unknown;\n inputTokensDetails?: UsageDetails | undefined;\n outputTokensDetails?: UsageDetails | undefined;\n requestUsageEntries?: RequestUsageEntry[] | undefined;\n};\n\n/**\n * A single provider usage frame above one billion tokens is outside every\n * supported OpenGeni model contract. Keeping the ceiling explicit also prevents\n * malformed-but-finite provider values from corrupting durable accounting or a\n * process-lifetime Prometheus counter.\n */\nexport const MAX_MODEL_USAGE_TOKEN_COUNT = 1_000_000_000;\n\nexport type ModelCallUsageTelemetry = {\n inputTokens: number | null;\n outputTokens: number | null;\n cachedTokens: number | null;\n cacheWriteTokens: number | null;\n reasoningTokens: number | null;\n};\n\nexport type ModelCallUsageNormalization = {\n telemetry: ModelCallUsageTelemetry;\n totalTokens: number | null;\n /** Bounded field paths only; raw provider values are never retained. */\n rejectedFields: string[];\n};\n\nexport function modelUsageTokenCountOrNull(value: unknown): number | null {\n return typeof value === \"number\" &&\n Number.isSafeInteger(value) &&\n value >= 0 &&\n value <= MAX_MODEL_USAGE_TOKEN_COUNT\n ? value\n : null;\n}\n\nexport function normalizeModelCallUsage(\n usage: ModelCallUsageInput | null | undefined,\n): ModelCallUsageNormalization {\n const rejectedFields = new Set<string>();\n if (!usage) {\n return {\n telemetry: {\n inputTokens: null,\n outputTokens: null,\n cachedTokens: null,\n cacheWriteTokens: null,\n reasoningTokens: null,\n },\n totalTokens: null,\n rejectedFields: [],\n };\n }\n\n const requestEntries = requestUsageEntries(usage.requestUsageEntries, rejectedFields);\n const topLevelInputTokens = reportedTokenCount(usage.inputTokens, \"inputTokens\", rejectedFields);\n const topLevelOutputTokens = reportedTokenCount(\n usage.outputTokens,\n \"outputTokens\",\n rejectedFields,\n );\n const topLevelTotalTokens = reportedTokenCount(usage.totalTokens, \"totalTokens\", rejectedFields);\n const requestInputTokens = completeRequestTokenAggregate(\n requestEntries,\n [\"inputTokens\", \"input_tokens\"],\n \"inputTokens.requestUsageEntries\",\n rejectedFields,\n );\n const requestOutputTokens = completeRequestTokenAggregate(\n requestEntries,\n [\"outputTokens\", \"output_tokens\"],\n \"outputTokens.requestUsageEntries\",\n rejectedFields,\n );\n let requestTotalTokens = completeRequestTokenAggregate(\n requestEntries,\n [\"totalTokens\", \"total_tokens\"],\n \"totalTokens.requestUsageEntries\",\n rejectedFields,\n );\n if (rejectInconsistentRequestTotals(requestEntries, rejectedFields)) {\n requestTotalTokens = { ...requestTotalTokens, status: \"invalid\", value: null };\n }\n\n // Complete per-request aggregates are the installed SDK's request-level\n // truth. A conflicting top-level field is diagnostic only; it must never\n // override the request sum with a smaller billable/context value. Invalid\n // complete request aggregates fail closed rather than falling back to a\n // potentially undercounting top-level number.\n const inputTokens = canonicalTokenDimension({\n topLevel: topLevelInputTokens,\n topLevelReported: isReported(usage.inputTokens),\n topLevelPath: \"inputTokens\",\n requestAggregate: requestInputTokens,\n rejectedFields,\n });\n const outputTokens = canonicalTokenDimension({\n topLevel: topLevelOutputTokens,\n topLevelReported: isReported(usage.outputTokens),\n topLevelPath: \"outputTokens\",\n requestAggregate: requestOutputTokens,\n rejectedFields,\n });\n const totalTokens = canonicalTotalTokens({\n inputTokens,\n outputTokens,\n topLevel: topLevelTotalTokens,\n topLevelReported: isReported(usage.totalTokens),\n requestAggregate: requestTotalTokens,\n rejectedFields,\n });\n\n const inputDetailSource = preferredDetailSource(\n usage.inputTokensDetails,\n \"inputTokensDetails\",\n requestEntries,\n [\"inputTokensDetails\", \"input_tokens_details\"],\n );\n const outputDetailSource = preferredDetailSource(\n usage.outputTokensDetails,\n \"outputTokensDetails\",\n requestEntries,\n [\"outputTokensDetails\", \"output_tokens_details\"],\n );\n\n return {\n telemetry: {\n inputTokens,\n outputTokens,\n cachedTokens: aggregateDetailTokenCount(\n inputDetailSource,\n [\"cached_tokens\", \"cachedInputTokens\", \"cached_input_tokens\"],\n \"cachedTokens\",\n rejectedFields,\n ),\n cacheWriteTokens: aggregateDetailTokenCount(\n inputDetailSource,\n [\"cache_write_tokens\", \"cacheWriteTokens\"],\n \"cacheWriteTokens\",\n rejectedFields,\n ),\n reasoningTokens: aggregateDetailTokenCount(\n outputDetailSource,\n [\"reasoning_tokens\", \"reasoningTokens\", \"reasoning_output_tokens\"],\n \"reasoningTokens\",\n rejectedFields,\n ),\n },\n totalTokens,\n rejectedFields: [...rejectedFields].slice(0, 32),\n };\n}\n\nexport function modelCallUsageTelemetry(\n usage: ModelCallUsageInput | null | undefined,\n): ModelCallUsageTelemetry {\n return normalizeModelCallUsage(usage).telemetry;\n}\n\nfunction requestUsageEntries(\n value: RequestUsageEntry[] | undefined,\n rejectedFields: Set<string>,\n): RequestUsageEntry[] {\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n rejectField(rejectedFields, \"requestUsageEntries\");\n return [];\n }\n const entries: RequestUsageEntry[] = [];\n for (const [index, entry] of value.entries()) {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n rejectField(rejectedFields, `requestUsageEntries[${index}]`);\n // Preserve the request slot as unknown. Dropping it would let fallback\n // aggregation silently undercount only the well-formed requests.\n entries.push({});\n continue;\n }\n entries.push(entry);\n }\n return entries;\n}\n\ntype RequestTokenAggregate = {\n status: \"absent\" | \"incomplete\" | \"invalid\" | \"complete\";\n value: number | null;\n};\n\nfunction completeRequestTokenAggregate(\n requestEntries: RequestUsageEntry[],\n requestKeys: string[],\n aggregatePath: string,\n rejectedFields: Set<string>,\n): RequestTokenAggregate {\n if (requestEntries.length === 0) {\n return { status: \"absent\", value: null };\n }\n const values: Array<number | null> = [];\n let incomplete = false;\n let invalid = false;\n for (const [index, entry] of requestEntries.entries()) {\n const selected = firstPresentEntry(entry as Record<string, unknown>, requestKeys);\n if (!selected || selected.value === null) {\n incomplete = true;\n continue;\n }\n const parsed = reportedTokenCount(\n selected.value,\n `requestUsageEntries[${index}].${selected.key}`,\n rejectedFields,\n );\n if (parsed === null) invalid = true;\n values.push(parsed);\n }\n if (invalid) {\n return { status: \"invalid\", value: null };\n }\n if (incomplete) {\n return { status: \"incomplete\", value: null };\n }\n const value = boundedTokenSum(values, aggregatePath, rejectedFields);\n return value === null ? { status: \"invalid\", value: null } : { status: \"complete\", value };\n}\n\nfunction canonicalTokenDimension(input: {\n topLevel: number | null;\n topLevelReported: boolean;\n topLevelPath: string;\n requestAggregate: RequestTokenAggregate;\n rejectedFields: Set<string>;\n}): number | null {\n if (input.requestAggregate.status === \"complete\") {\n if (\n input.topLevelReported &&\n input.topLevel !== null &&\n input.topLevel !== input.requestAggregate.value\n ) {\n rejectField(input.rejectedFields, input.topLevelPath);\n }\n return input.requestAggregate.value;\n }\n if (input.requestAggregate.status === \"invalid\") {\n if (input.topLevelReported) {\n rejectField(input.rejectedFields, input.topLevelPath);\n }\n return null;\n }\n return input.topLevel;\n}\n\nfunction canonicalTotalTokens(input: {\n inputTokens: number | null;\n outputTokens: number | null;\n topLevel: number | null;\n topLevelReported: boolean;\n requestAggregate: RequestTokenAggregate;\n rejectedFields: Set<string>;\n}): number | null {\n if (input.inputTokens !== null && input.outputTokens !== null) {\n const derived = boundedTokenSum(\n [input.inputTokens, input.outputTokens],\n \"totalTokens.aggregate\",\n input.rejectedFields,\n );\n if (derived === null) {\n // Both canonical components are known and exceed the supported aggregate\n // ceiling. Any bounded reported total necessarily undercounts them.\n if (input.topLevelReported) rejectField(input.rejectedFields, \"totalTokens\");\n if (input.requestAggregate.status === \"complete\") {\n rejectField(input.rejectedFields, \"totalTokens.requestUsageEntries\");\n }\n return null;\n }\n if (input.topLevelReported && input.topLevel !== null && input.topLevel !== derived) {\n rejectField(input.rejectedFields, \"totalTokens\");\n }\n if (input.requestAggregate.status === \"complete\" && input.requestAggregate.value !== derived) {\n rejectField(input.rejectedFields, \"totalTokens.requestUsageEntries\");\n }\n return derived;\n }\n\n if (input.requestAggregate.status === \"complete\") {\n const requestTotal = input.requestAggregate.value;\n if (\n requestTotal === null ||\n !totalCoversKnownComponents(requestTotal, input.inputTokens, input.outputTokens)\n ) {\n rejectField(input.rejectedFields, \"totalTokens.requestUsageEntries\");\n if (input.topLevelReported) rejectField(input.rejectedFields, \"totalTokens\");\n return null;\n }\n if (input.topLevelReported && input.topLevel !== null && input.topLevel !== requestTotal) {\n rejectField(input.rejectedFields, \"totalTokens\");\n }\n return requestTotal;\n }\n if (input.requestAggregate.status === \"invalid\") {\n if (input.topLevelReported) rejectField(input.rejectedFields, \"totalTokens\");\n return null;\n }\n if (\n input.topLevel !== null &&\n !totalCoversKnownComponents(input.topLevel, input.inputTokens, input.outputTokens)\n ) {\n rejectField(input.rejectedFields, \"totalTokens\");\n return null;\n }\n return input.topLevel;\n}\n\nfunction totalCoversKnownComponents(\n total: number,\n inputTokens: number | null,\n outputTokens: number | null,\n): boolean {\n return (\n (inputTokens === null || total >= inputTokens) &&\n (outputTokens === null || total >= outputTokens)\n );\n}\n\nfunction rejectInconsistentRequestTotals(\n requestEntries: RequestUsageEntry[],\n rejectedFields: Set<string>,\n): boolean {\n let inconsistent = false;\n for (const [index, entry] of requestEntries.entries()) {\n const record = entry as Record<string, unknown>;\n const selectedInput = firstPresentEntry(record, [\"inputTokens\", \"input_tokens\"]);\n const selectedOutput = firstPresentEntry(record, [\"outputTokens\", \"output_tokens\"]);\n const selectedTotal = firstPresentEntry(record, [\"totalTokens\", \"total_tokens\"]);\n if (!selectedInput || !selectedOutput || !selectedTotal) continue;\n const inputTokens = modelUsageTokenCountOrNull(selectedInput.value);\n const outputTokens = modelUsageTokenCountOrNull(selectedOutput.value);\n const totalTokens = modelUsageTokenCountOrNull(selectedTotal.value);\n if (inputTokens === null || outputTokens === null || totalTokens === null) continue;\n const derived =\n inputTokens <= MAX_MODEL_USAGE_TOKEN_COUNT - outputTokens ? inputTokens + outputTokens : null;\n if (derived === null || totalTokens !== derived) {\n rejectField(rejectedFields, `requestUsageEntries[${index}].${selectedTotal.key}`);\n inconsistent = true;\n }\n }\n return inconsistent;\n}\n\nfunction isReported(value: unknown): boolean {\n return value !== undefined && value !== null;\n}\n\nfunction preferredDetailSource(\n aggregateDetails: UsageDetails | undefined,\n aggregatePath: string,\n requestEntries: RequestUsageEntry[],\n requestKeys: string[],\n): Array<{ details: unknown; path: string; missing?: boolean }> {\n const requestDetails: Array<{ details: unknown; path: string; missing?: boolean }> = [];\n let sawRequestDetails = false;\n for (const [index, entry] of requestEntries.entries()) {\n const selected = firstPresentEntry(entry as Record<string, unknown>, requestKeys);\n if (!selected) {\n requestDetails.push({\n details: undefined,\n path: `requestUsageEntries[${index}].${requestKeys[0]}`,\n missing: true,\n });\n continue;\n }\n sawRequestDetails = true;\n requestDetails.push({\n details: selected.value,\n path: `requestUsageEntries[${index}].${selected.key}`,\n });\n }\n // The installed Agents SDK explicitly carries per-request entries. Prefer\n // them when they include detail records; otherwise fall back to the aggregate\n // detail arrays that Usage.add() appends in request order.\n return sawRequestDetails\n ? requestDetails\n : aggregateDetails === undefined\n ? []\n : [{ details: aggregateDetails, path: aggregatePath }];\n}\n\nfunction aggregateDetailTokenCount(\n sources: Array<{ details: unknown; path: string; missing?: boolean }>,\n keys: string[],\n field: string,\n rejectedFields: Set<string>,\n): number | null {\n const values: Array<number | null> = [];\n let sawReportedValue = false;\n let sawMissingValue = false;\n for (const source of sources) {\n if (source.missing) {\n sawMissingValue = true;\n continue;\n }\n const details = detailRecords(source.details, source.path, rejectedFields);\n if (!details.complete) {\n sawMissingValue = true;\n }\n for (const detail of details.records) {\n const selected = firstPresentEntry(detail.record, keys);\n if (!selected) {\n sawMissingValue = true;\n continue;\n }\n sawReportedValue = true;\n values.push(\n reportedTokenCount(selected.value, `${detail.path}.${selected.key}`, rejectedFields),\n );\n }\n }\n return sawReportedValue && !sawMissingValue\n ? boundedTokenSum(values, `${field}.aggregate`, rejectedFields)\n : null;\n}\n\nfunction detailRecords(\n details: unknown,\n path: string,\n rejectedFields: Set<string>,\n): {\n records: Array<{ record: Record<string, unknown>; path: string }>;\n complete: boolean;\n} {\n const entries = Array.isArray(details) ? details : [details];\n const records: Array<{ record: Record<string, unknown>; path: string }> = [];\n let complete = true;\n for (const [index, entry] of entries.entries()) {\n const entryPath = Array.isArray(details) ? `${path}[${index}]` : path;\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n rejectField(rejectedFields, entryPath);\n complete = false;\n continue;\n }\n records.push({ record: entry as Record<string, unknown>, path: entryPath });\n }\n return { records, complete };\n}\n\nfunction firstPresentEntry(\n record: Record<string, unknown>,\n keys: string[],\n): { key: string; value: unknown } | null {\n for (const key of keys) {\n if (Object.prototype.hasOwnProperty.call(record, key) && record[key] !== undefined) {\n // One request can expose the same value under provider and SDK aliases.\n // Pick the first canonical alias instead of adding aliases together.\n return { key, value: record[key] };\n }\n }\n return null;\n}\n\nfunction reportedTokenCount(\n value: unknown,\n field: string,\n rejectedFields: Set<string>,\n): number | null {\n if (value === undefined || value === null) {\n return null;\n }\n const normalized = modelUsageTokenCountOrNull(value);\n if (normalized === null) {\n rejectField(rejectedFields, field);\n }\n return normalized;\n}\n\nfunction boundedTokenSum(\n values: Array<number | null>,\n field: string,\n rejectedFields: Set<string>,\n): number | null {\n if (values.length === 0 || values.some((value) => value === null)) {\n return null;\n }\n let total = 0;\n for (const value of values as number[]) {\n if (value > MAX_MODEL_USAGE_TOKEN_COUNT - total) {\n rejectField(rejectedFields, field);\n return null;\n }\n total += value;\n }\n return total;\n}\n\nfunction rejectField(rejectedFields: Set<string>, field: string): void {\n if (rejectedFields.size < 32) {\n rejectedFields.add(field);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;AAAA,EACE;AAAA,EACA,6BAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA,0BAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,uBAAuB;AAAA,EACvB;AAAA,EACA,uBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAcK;;;OC3CAC,aAAY;;;ACEZ,IAAM,WAAW;EACtB,QAA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A,SAAS,qBAAqB,MAAuB;AACnD,QAAM,YAAY;AAKlB,QAAM,OAAO,WAAW,YAAY,WAAW,QAAQ,WAAW,SAAS;AAC3E,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;","names":["collectSandboxEnvironment","CAPABILITY_DESCRIPTORS","redactSensitiveText","OpenAI","OpenAI","isRecord","isRecord","tool","isRecord","skills","openaiTool","openaiIncludes","webSearchTool","entry","response","isRecord","OpenAI","getCompatibleToolChoice","tool","file","isMessageItem","isRecord","response","tool","getResponseFormat","getCompatibleToolChoice","OpenAI","isRecord","child","isRecord","OpenAI","iterator","OpenAI","OpenAI","logger","resolveClient","OpenAI","METADATA","metadata_default","HEADERS","metadata_default","logger","OpenAI","boundModelToolOutputItems","createHash","tool","tool","RESULT_TYPE_BY_CALL_TYPE","RESULT_TYPES","itemType","imageTokens","imageCount","imageFallbackCount","projected","textTokens","window","createHash","skills","createHash","OpenAI","usage","summary","redactSensitiveText","agent","tool","boundModelToolOutputItems","collectSandboxEnvironment","runAs","fileDownloads","resourceClient","CAPABILITY_DESCRIPTORS","config","createHash"]}
|