import { BaseAgent as BaseAgent5 } from "@google/adk"; /** * @license * Copyright 2025 PAI * SPDX-License-Identifier: MIT */ type ExternalAgentAuthKind = "none" | "env" | "custom"; interface ExternalAgentCredential { kind: ExternalAgentAuthKind; /** Redacted identifier for diagnostics; never store raw secrets here. */ label?: string; env?: Record; } interface CredentialRequest { providerId: string; envAllowlist?: readonly string[]; } interface ExternalAgentCredentialProvider { getCredential(request: CredentialRequest): Promise; } declare class NoopCredentialProvider implements ExternalAgentCredentialProvider { getCredential(): Promise; } import { BaseAgent as BaseAgent3, Event as Event2, InvocationContext as InvocationContext3 } from "@google/adk"; import { BaseAgent as BaseAgent2, BaseTool, InvocationContext as InvocationContext2 } from "@google/adk"; /** * @license * Copyright 2025 PAI * SPDX-License-Identifier: MIT */ /** Lifecycle and output events emitted by external coding-agent runtimes. */ type ExternalAgentEvent = ExternalAgentStartedEvent | ExternalAgentOutputEvent | ExternalAgentToolCallEvent | ExternalAgentToolResultEvent | ExternalAgentErrorEvent | ExternalAgentStateDeltaEvent | ExternalAgentCompletedEvent; interface ExternalAgentStartedEvent { type: "started"; runId?: string; providerId: string; timestamp?: number; } interface ExternalAgentOutputEvent { type: "output"; content: string; stream?: "stdout" | "stderr"; partial?: boolean; turnComplete?: boolean; metadata?: Record; timestamp?: number; } interface ExternalAgentToolCallEvent { type: "tool_call"; name: string; input?: unknown; callId?: string; metadata?: Record; timestamp?: number; } interface ExternalAgentToolResultEvent { type: "tool_result"; name: string; result: unknown; callId?: string; error?: string; metadata?: Record; timestamp?: number; } interface ExternalAgentErrorEvent { type: "error"; message: string; code?: string; recoverable?: boolean; timestamp?: number; } interface ExternalAgentStateDeltaEvent { type: "state_delta"; stateDelta: Record; timestamp?: number; } interface ExternalAgentCompletedEvent { type: "completed"; exitCode?: number; signal?: string; timestamp?: number; } declare function isExternalAgentEvent(value: unknown): value is ExternalAgentEvent; /** * @license * Copyright 2025 PAI * SPDX-License-Identifier: MIT */ type ExternalAgentPermissionMode = "read-only" | "ask" | "workspace-write" | "full-access"; interface ExternalAgentPermissionPolicy { mode: ExternalAgentPermissionMode; allowNetwork?: boolean; allowedPaths?: readonly string[]; } interface ProviderPermissionFlags { readOnly?: boolean; requireApproval?: boolean; workspaceWrite?: boolean; fullAccess?: boolean; network?: boolean; paths?: readonly string[]; } declare const CODEX_ENV_ALLOWLIST: readonly ["CODEX_API_KEY", "CODEX_ACCESS_TOKEN", "CODEX_HOME", "CODEX_EXECUTABLE", "CODEX_CLI_PATH", "CODEX_CA_CERTIFICATE", "SSL_CERT_FILE"]; declare const CODEX_PROVIDER: ExternalAgentProviderDefinition; /** * @license * Copyright 2025 PAI * SPDX-License-Identifier: MIT */ type ExternalAgentProviderId = "codex" | "claude" | "gemini-cli" | (string & {}); interface ExternalAgentProviderDefinition { /** Stable provider id used in events, registries, and configuration. */ id: ExternalAgentProviderId; /** Human-readable provider name. */ name: string; /** Optional executable name. The foundation does not execute it at import time. */ command?: string; /** Environment variables this provider is allowed to read for auth/config. */ envAllowlist?: readonly string[]; } declare const CLAUDE_PROVIDER: ExternalAgentProviderDefinition; /** * @license * Copyright 2025 PAI * SPDX-License-Identifier: MIT */ interface AgentRuntimeCapabilities { tools?: boolean; subagents?: boolean; mcpServers?: boolean; streaming?: boolean; sessions?: boolean; permissions?: boolean; } /** * @license * Copyright 2025 PAI * SPDX-License-Identifier: MIT */ interface AgentRuntimeSession { id: string; parentId?: string; rootAgentName?: string; metadata?: Record; } import { BaseAgent, Event, InvocationContext } from "@google/adk"; interface RunSubAgentInput { agentName: string; task: string; } interface RunSubAgentExecutionSummary { events: number; textEvents: number; toolCalls: number; errors: number; durationMs: number; } interface RunSubAgentResult { agentName: string; output: string; events: number; summary: RunSubAgentExecutionSummary; stateDelta?: Record; error?: string; } type ToolGatewayEventSink = (event: Event) => void; interface ToolGatewayConfig { rootAgent: BaseAgent; subAgents: readonly BaseAgent[]; parentContext: InvocationContext; parentPermissions?: ExternalAgentPermissionPolicy; eventSink?: ToolGatewayEventSink; exposeSubAgentEvents?: boolean; } declare class ToolGateway { private; constructor(config: ToolGatewayConfig); listSubAgents(): readonly BaseAgent[]; runSubAgent(input: RunSubAgentInput): Promise; private findSubAgent; private createChildContext; private createFunctionCallEvent; private createFunctionResponseEvent; private emit; } interface ExternalAgentRunRequest { provider: ExternalAgentProviderDefinition; context: InvocationContext2; instruction?: string; workingDirectory?: string; credential?: ExternalAgentCredential; permissions?: ExternalAgentPermissionPolicy; agent?: BaseAgent2; rootAgent?: BaseAgent2; subAgents?: readonly BaseAgent2[]; tools?: readonly BaseTool[]; toolGateway?: ToolGateway; runtimeSession?: AgentRuntimeSession; /** * First-class cancellation signal for the run. When this signal aborts, * drivers MUST stop streaming and release any spawned subprocess/SDK * resources (e.g. via the SDK's own abort/interrupt mechanism). * * This is the single, shared cancellation contract for all external-agent * drivers. When unset, drivers SHOULD fall back to * {@link InvocationContext.abortSignal} (`context.abortSignal`) for backward * compatibility. Use {@link resolveAbortSignal} to obtain the effective * signal honoring both sources. */ abortSignal?: AbortSignal; } /** * Resolve the effective cancellation signal for a run, preferring the * first-class {@link ExternalAgentRunRequest.abortSignal} and falling back to * the ADK {@link InvocationContext.abortSignal}. Returns `undefined` when * neither is present. * * This is the one place every driver should call so they share a single * cancellation contract. */ declare function resolveAbortSignal(request: Pick): AbortSignal | undefined; interface ExternalAgentDriver { readonly providerId: string; capabilities?(): AgentRuntimeCapabilities; run(request: ExternalAgentRunRequest): AsyncIterable; } declare class PlaceholderExternalAgentDriver implements ExternalAgentDriver { readonly providerId: string; constructor(providerId: string); run(): AsyncIterable; } interface ExternalAgentConfig { name: string; description?: string; provider: ExternalAgentProviderDefinition; driver?: ExternalAgentDriver; credentialProvider?: ExternalAgentCredentialProvider; instruction?: string; workingDirectory?: string; permissions?: ExternalAgentPermissionPolicy; subAgents?: BaseAgent3[]; } declare class ExternalAgent extends BaseAgent3 { readonly provider: ExternalAgentProviderDefinition; readonly driver: ExternalAgentDriver; readonly credentialProvider: ExternalAgentCredentialProvider; readonly instruction?: string; readonly workingDirectory?: string; readonly permissions?: ExternalAgentPermissionPolicy; constructor(config: ExternalAgentConfig); protected createInvocationContext(parentContext: InvocationContext3): InvocationContext3; protected runAsyncImpl(context: InvocationContext3): AsyncGenerator; protected runLiveImpl(context: InvocationContext3): AsyncGenerator; protected toAdkEvent(event: ExternalAgentEvent, context: InvocationContext3): Event2 | undefined; private toolCallToContent; private toolResultToContent; } type ExternalAgentRuntimeKind = "sdk" | "cli" | "jsonl" | (string & {}); interface ExternalAgentDefinition { /** Provider metadata used in events, auth, and registry lookups. */ provider: ExternalAgentProviderDefinition; /** Runtime integration style. Useful for docs, diagnostics, and future factories. */ runtime?: ExternalAgentRuntimeKind; /** Capabilities exposed by the default runtime driver. */ capabilities?: AgentRuntimeCapabilities; /** Creates the default driver for this runtime. */ createDriver?: () => ExternalAgentDriver; /** Creates the default credential provider for this runtime. */ createCredentialProvider?: () => ExternalAgentCredentialProvider; } type ExternalAgentDefinitionConfig = Omit; declare function createExternalAgentConfig(definition: ExternalAgentDefinition, config: ExternalAgentDefinitionConfig): ExternalAgentConfig; declare function createExternalAgent(definition: ExternalAgentDefinition, config: ExternalAgentDefinitionConfig): ExternalAgent; declare class ExternalAgentDefinitionRegistry { private; constructor(definitions?: readonly ExternalAgentDefinition[]); register(definition: ExternalAgentDefinition): void; get(id: string): ExternalAgentDefinition | undefined; has(id: string): boolean; list(): ExternalAgentDefinition[]; create(id: string, config: ExternalAgentDefinitionConfig): ExternalAgent; } declare function createDefaultExternalAgentDefinitionRegistry(): ExternalAgentDefinitionRegistry; declare const externalAgentDefinitionRegistry: ExternalAgentDefinitionRegistry; type EnvSource = Record; declare function readAllowedEnv(env: EnvSource, allowlist?: readonly string[]): Record; declare class EnvCredentialProvider implements ExternalAgentCredentialProvider { private readonly env; constructor(env?: EnvSource); getCredential(request: CredentialRequest): Promise; } declare const CLAUDE_AGENT_DEFINITION: ExternalAgentDefinition; type ClaudeAgentConfig = ExternalAgentDefinitionConfig; declare class ClaudeAgent extends ExternalAgent { static readonly definition: ExternalAgentDefinition; constructor(config: ClaudeAgentConfig); } declare const CODEX_AGENT_DEFINITION: ExternalAgentDefinition; type CodexAgentConfig = ExternalAgentDefinitionConfig; declare class CodexAgent extends ExternalAgent { static readonly definition: ExternalAgentDefinition; constructor(config: CodexAgentConfig); } interface SubprocessJsonlDriverConfig { providerId: string; command: string; args?: readonly string[]; } /** * Foundation placeholder for JSONL subprocess-backed drivers. * * The class intentionally performs no work until `run` is called, which keeps * imports free of CLI execution, auth prompts, and other side effects. */ declare class SubprocessJsonlDriver implements ExternalAgentDriver { readonly providerId: string; readonly command: string; readonly args: readonly string[]; constructor(config: SubprocessJsonlDriverConfig); run(_request: ExternalAgentRunRequest): AsyncIterable; parseLine(line: string): ExternalAgentEvent; } interface CodexCliSpawnOptions { cwd?: string; env: Record; } interface CodexCliSubprocess { stdout?: LineSource; stderr?: LineSource; exited: Promise; } type LineSource = ReadableStream | AsyncIterable; type CodexCliSpawn = (command: string, args: readonly string[], options: CodexCliSpawnOptions) => CodexCliSubprocess; interface CodexCliDriverConfig { command?: string; args?: readonly string[]; spawn?: CodexCliSpawn; env?: Record; } declare class CodexCliDriver extends SubprocessJsonlDriver { private; constructor(config?: CodexCliDriverConfig); run(request: ExternalAgentRunRequest): AsyncIterable; buildArgs(request: ExternalAgentRunRequest): readonly string[]; buildEnv(request: ExternalAgentRunRequest): Record; parseLine(line: string): ExternalAgentEvent; } declare function mapPolicyToCodexArgs(policy?: ExternalAgentPermissionPolicy): readonly string[]; import { Content } from "@google/genai"; type CodexInputPart = { type: "text"; text: string; } | { type: "local_image"; path: string; }; interface CodexInputMapping { input: string | CodexInputPart[]; cleanup: () => Promise; } interface CodexInputMapperOptions { tmpDir?: string; idPrefix?: string; } /** * Convert an ADK Content (the current user turn) into Codex SDK input. * * Codex accepts either a string or an array of text / local_image parts. * Non-text/image parts (file URIs, tool calls/responses, code) are flattened * into short text markers that mirror Phase-1's transcript style. */ declare function userContentToCodexInput(content: Content, opts?: CodexInputMapperOptions): CodexInputMapping; /** * Render every content except the last (the current user turn) into a textual * transcript suitable for prepending to a fresh Codex thread when no saved * thread id exists. Returns "" when there is no prior history. */ declare function summarizeHistoryForColdStart(contents: ReadonlyArray): string; import { Content as Content2 } from "@google/genai"; /** * Anthropic ContentBlockParam variant subset we emit. The full union from * `@anthropic-ai/sdk/resources/messages` is much broader, but we only use a * handful of block kinds when translating ADK history into Claude messages. */ type ClaudeBase64ImageMediaType = "image/jpeg" | "image/png" | "image/gif" | "image/webp"; type ClaudeBase64ImageSource = { type: "base64"; media_type: ClaudeBase64ImageMediaType; data: string; }; type ClaudeURLImageSource = { type: "url"; url: string; }; type ClaudeBase64PDFSource = { type: "base64"; media_type: "application/pdf"; data: string; }; type ClaudeURLDocumentSource = { type: "url"; url: string; }; type ClaudeTextBlockParam = { type: "text"; text: string; }; type ClaudeImageBlockParam = { type: "image"; source: ClaudeBase64ImageSource | ClaudeURLImageSource; }; type ClaudeDocumentBlockParam = { type: "document"; source: ClaudeBase64PDFSource | ClaudeURLDocumentSource; }; type ClaudeToolUseBlockParam = { type: "tool_use"; id: string; name: string; input: Record; }; type ClaudeToolResultBlockParam = { type: "tool_result"; tool_use_id: string; content: string; }; type ClaudeContentBlockParam = ClaudeTextBlockParam | ClaudeImageBlockParam | ClaudeDocumentBlockParam | ClaudeToolUseBlockParam | ClaudeToolResultBlockParam; type ClaudeMessageParam = { role: "user" | "assistant"; content: ClaudeContentBlockParam[]; }; /** * Minimal structural type matching `SDKUserMessage` from * `@anthropic-ai/claude-agent-sdk`. We avoid importing the SDK type directly * because the SDK is an optional dependency. */ type SDKUserMessage = { type: "user"; message: ClaudeMessageParam; parent_tool_use_id: string | null; isSynthetic?: boolean; shouldQuery?: boolean; }; /** * Translate ADK history (`Content[]`) into a sequence of Claude SDK user * messages with native multimodal `ContentBlockParam` blocks. The final * emitted message is marked `shouldQuery: true` so the SDK triggers an * assistant turn; preceding messages are appended as synthetic transcript * entries. */ declare function contentsToSdkMessages(contents: ReadonlyArray): SDKUserMessage[]; type ClaudeAgentSdkPermissionMode = "default" | "acceptEdits" | "bypassPermissions" | "plan" | "dontAsk" | "auto"; type ClaudeAgentSdkSettingSource = "user" | "project" | "local"; type ClaudeAgentSdkOptions = { cwd?: string; env?: Record; abortController?: AbortController; permissionMode?: ClaudeAgentSdkPermissionMode; additionalDirectories?: string[]; pathToClaudeCodeExecutable?: string; settingSources?: ClaudeAgentSdkSettingSource[]; maxTurns?: number; model?: string; systemPrompt?: string | { type: "preset"; preset: "claude_code"; append?: string; }; allowDangerouslySkipPermissions?: true; mcpServers?: Record; allowedTools?: string[]; resume?: string; forkSession?: boolean; }; type ClaudeAgentSdkMessage = Record; type ClaudeAgentSdkToolResult = { content: Array<{ type: "text"; text: string; }>; isError?: boolean; }; type ClaudeAgentSdkToolDefinition = unknown; /** * The object returned by `query()`. The real SDK returns a `Query` (an * `AsyncGenerator` that additionally exposes `interrupt()`); generator-based * test fakes expose `return()`. Both are used to tear down the spawned * subprocess on early break/error (LIFECYCLE-1). */ type ClaudeAgentSdkQuery = AsyncIterable & { interrupt?(): Promise | void; return?(value?: unknown): Promise | unknown; }; type ClaudeAgentSdkLike = { query(params: { prompt: string | AsyncIterable; options?: ClaudeAgentSdkOptions; }): ClaudeAgentSdkQuery; createSdkMcpServer?(options: { name: string; version?: string; tools?: ClaudeAgentSdkToolDefinition[]; alwaysLoad?: boolean; }): unknown; tool?(name: string, description: string, inputSchema: Record, handler: (args: Record, extra: unknown) => Promise, extras?: Record): ClaudeAgentSdkToolDefinition; }; interface ClaudeExecutableResolution { path?: string; checked: string[]; } interface ClaudeAgentSdkDriverConfig { sdk?: ClaudeAgentSdkLike; importSdk?: () => Promise; pathToClaudeCodeExecutable?: string; executableSearchPaths?: string[]; env?: Record; settingSources?: ClaudeAgentSdkSettingSource[]; maxTurns?: number; model?: string; debugEvents?: boolean; /** * AUTH-2: opt-in plain-string system prompt. When set, it REPLACES the * `claude_code` preset (and `request.instruction` is appended to it) so a * non-coding agent is not forced into the full coding-agent persona/token * cost. When unset, the driver keeps the preset+append default. */ systemPrompt?: string; /** * If set, the driver passes this session id to the Claude SDK * `options.resume` field and sends only the current user turn (not the full * ADK history) so the SDK appends to the resumed session instead of * re-feeding history that the SDK already has on disk. */ resumeSessionId?: string; /** * Pass-through for the Claude SDK `options.forkSession` flag. Use with * `resumeSessionId` to fork rather than continue the previous session. */ forkSession?: boolean; } declare class ClaudeAgentSdkDriver { private; readonly providerId: ExternalAgentProviderId; constructor(config?: ClaudeAgentSdkDriverConfig); run(request: ExternalAgentRunRequest): AsyncIterable; buildOptions(request: ExternalAgentRunRequest): ClaudeAgentSdkOptions; /** * AUTH-2: resolve the system prompt. A configured plain-string * `systemPrompt` replaces the `claude_code` preset (with the run instruction * appended); otherwise the preset+append default is kept. */ private buildSystemPrompt; /** * Build the SDK `prompt` input from a run request. Returns: * - a plain string for text-only single-turn invocations (fast path); * - an `AsyncIterable` carrying lossless multimodal blocks * for multi-turn or multimodal history; * - an empty string when no content can be collected (defensive fallback). * * When `resumeSessionId` is configured, only the last collected `Content` * is sent so the resumed session continues from existing transcript on disk * rather than re-feeding history. */ buildPromptInput(request: ExternalAgentRunRequest): string | AsyncIterable; resolveClaudeExecutable(request: ExternalAgentRunRequest): ClaudeExecutableResolution; buildEnv(request: ExternalAgentRunRequest): Record; /** * Build the `AbortController` wired into `options.abortController` (LIFECYCLE-1). * The SDK aborts the spawned `claude` subprocess and releases resources when * this controller fires. We bridge the shared run cancellation signal * (`request.abortSignal` ?? `context.abortSignal`) onto a fresh controller so * the driver also owns a handle it can abort from its own `finally` cleanup. */ private buildAbortController; /** * Tear down a Query (LIFECYCLE-1). When the loop ends early (break/throw) * the turn is still in flight, so `interrupt()` is requested first to stop * the spawned subprocess gracefully; `return()` then finalizes the * generator. Both are best-effort — disposal must never mask the original * outcome, so all errors here are swallowed. */ private disposeQuery; normalizeMessage(message: ClaudeAgentSdkMessage): ExternalAgentEvent[]; buildOptionsForRun(request: ExternalAgentRunRequest, sdk: ClaudeAgentSdkLike): Promise; private buildSubAgentMcpServer; private describeError; private loadSdk; } declare function mapPolicyToClaudeSdkPermission(permissions?: ExternalAgentPermissionPolicy): { permissionMode: ClaudeAgentSdkPermissionMode; allowDangerouslySkipPermissions?: true; }; interface ClaudeCliSubprocess { stdout?: LineSource2 | null; stderr?: LineSource2 | null; exited: Promise; } interface ClaudeCliSpawnOptions { cwd?: string; env?: Record; } type LineSource2 = ReadableStream | AsyncIterable | Iterable; type ClaudeCliSpawn = (command: string, args: readonly string[], options: ClaudeCliSpawnOptions) => ClaudeCliSubprocess; interface ClaudeCliDriverConfig { command?: string; args?: readonly string[]; spawn?: ClaudeCliSpawn; env?: Record; } declare class ClaudeCliDriver extends SubprocessJsonlDriver { private; constructor(config?: ClaudeCliDriverConfig); run(request: ExternalAgentRunRequest): AsyncIterable; buildArgs(request: ExternalAgentRunRequest): readonly string[]; buildEnv(request: ExternalAgentRunRequest): Record; parseClaudeLine(line: string): ExternalAgentEvent | undefined; } declare function mapClaudePermissionArgs(permissions?: ExternalAgentPermissionPolicy): string[]; interface GeminiCliSubprocess { stdout?: AsyncIterable | Iterable | ReadableStream | null; stderr?: AsyncIterable | Iterable | ReadableStream | null; exited: Promise; } interface GeminiCliSpawnOptions { cwd?: string; env?: Record; } type GeminiCliSpawn = (command: string, args: readonly string[], options: GeminiCliSpawnOptions) => GeminiCliSubprocess; interface GeminiCliDriverConfig { command?: string; spawn?: GeminiCliSpawn; env?: Record; } declare class GeminiCliDriver extends SubprocessJsonlDriver { private; constructor(config?: GeminiCliDriverConfig); run(request: ExternalAgentRunRequest): AsyncIterable; parseGeminiLine(line: string): ExternalAgentEvent | undefined; } declare function buildGeminiArgs(prompt: string, permissions?: ExternalAgentPermissionPolicy): string[]; declare function mapGeminiPermissionArgs(permissions?: ExternalAgentPermissionPolicy): string[]; declare const GEMINI_CLI_AGENT_DEFINITION: ExternalAgentDefinition; type GeminiCliAgentConfig = ExternalAgentDefinitionConfig; declare class GeminiCliAgent extends ExternalAgent { static readonly definition: ExternalAgentDefinition; constructor(config: GeminiCliAgentConfig); } declare function mapPermissionPolicyToFlags(policy: ExternalAgentPermissionPolicy): ProviderPermissionFlags; declare function mapPermissionModeToPolicy(mode: ExternalAgentPermissionMode): ExternalAgentPermissionPolicy; declare function deriveSubAgentPermissionPolicy(parent?: ExternalAgentPermissionPolicy, child?: ExternalAgentPermissionPolicy): ExternalAgentPermissionPolicy; declare class ExternalAgentProviderRegistry { private; constructor(providers?: readonly ExternalAgentProviderDefinition[]); register(provider: ExternalAgentProviderDefinition): void; get(id: string): ExternalAgentProviderDefinition | undefined; has(id: string): boolean; list(): ExternalAgentProviderDefinition[]; } declare function createDefaultExternalAgentProviderRegistry(): ExternalAgentProviderRegistry; declare const externalAgentProviderRegistry: ExternalAgentProviderRegistry; declare const GEMINI_CLI_ENV_ALLOWLIST: readonly ["GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GENAI_USE_VERTEXAI", "GOOGLE_CLOUD_PROJECT", "GOOGLE_CLOUD_PROJECT_ID", "GOOGLE_CLOUD_LOCATION", "GOOGLE_APPLICATION_CREDENTIALS"]; declare const GEMINI_CLI_PROVIDER: ExternalAgentProviderDefinition; import { InvocationContext as InvocationContext4 } from "@google/adk"; import { Content as Content3 } from "@google/genai"; /** * Reimplementation of ADK's `getContents` (see * node_modules/@google/adk/dist/esm/agents/processors/content_processor_utils.js) * that is not exposed via the package's public `exports` map. Walks the session * event history for the current invocation, filters events by branch and * visibility, rewrites foreign-agent turns into user-role context markers, and * reorders async function-call/response pairs so each response sits adjacent to * its call. */ declare function collectContents(context: InvocationContext4): Content3[]; /** * Render `Content[]` into a deterministic prompt string suitable for external * runtimes that consume a single text turn. */ declare function flattenContentsToPrompt(contents: ReadonlyArray): string; /** * @license * Copyright 2025 PAI * SPDX-License-Identifier: MIT */ /** * Shared error-classification helper for external-agent drivers. * * Both the Codex (`@openai/codex-sdk`) and Claude * (`@anthropic-ai/claude-agent-sdk`) drivers historically labelled every error * `recoverable: true`, which causes upstream retry loops to spin on unfixable * conditions (auth/billing/missing-binary/quota). This module centralizes the * recoverable-vs-non-recoverable decision so both drivers share ONE contract. * * Classification is heuristic: the underlying SDKs frequently expose only a * free-form message string, so callers may pass a known typed subtype (when * available) and/or the raw message text. A known subtype always wins over the * message heuristic. */ /** Result of classifying an error condition. */ interface RecoverableClassification { /** Whether retrying the operation could plausibly succeed. */ recoverable: boolean; /** Stable, machine-readable code describing the classified condition. */ code: string; } /** Input to {@link classifyRecoverable}. */ interface ClassifyRecoverableInput { /** * A known typed subtype from the SDK (e.g. Claude's * `SDKAssistantMessageError` / `SDKResultError` subtypes, or a synthetic * Codex subtype). Takes precedence over the message heuristic. */ subtype?: string | null; /** Free-form error message text used for heuristic classification. */ message?: string | null; /** * Fallback code to emit when no subtype or message signal matches. Defaults * to `UNKNOWN_ERROR`. */ fallbackCode?: string; /** * Default recoverability when no signal matches. Defaults to `true` * (preserve the historical "assume transient" behavior for truly unknown * errors). */ defaultRecoverable?: boolean; } /** * Classify an error as recoverable (retry may succeed) or non-recoverable * (retrying is futile until the operator fixes the underlying condition). * * Precedence: known {@link ClassifyRecoverableInput.subtype} > message * heuristic > configured fallback. */ declare function classifyRecoverable(input: ClassifyRecoverableInput): RecoverableClassification; /** * @license * Copyright 2025 PAI * SPDX-License-Identifier: MIT */ interface AgentRuntimeRequestMetadata { agentName: string; rootAgentName: string; subAgentNames: readonly string[]; } type CodexSdkApprovalMode = "never" | "on-request" | "on-failure" | "untrusted"; type CodexSdkSandboxMode = "read-only" | "workspace-write" | "danger-full-access"; type CodexSdkModelReasoningEffort = "minimal" | "low" | "medium" | "high" | "xhigh"; type CodexSdkWebSearchMode = "disabled" | "cached" | "live"; type CodexSdkConfigValue = string | number | boolean | CodexSdkConfigValue[] | CodexSdkConfigObject; type CodexSdkConfigObject = { [key: string]: CodexSdkConfigValue; }; type CodexSdkOptions = { codexPathOverride?: string; baseUrl?: string; apiKey?: string; config?: CodexSdkConfigObject; env?: Record; }; type CodexSdkThreadOptions = { model?: string; sandboxMode?: CodexSdkSandboxMode; workingDirectory?: string; skipGitRepoCheck?: boolean; modelReasoningEffort?: CodexSdkModelReasoningEffort; networkAccessEnabled?: boolean; webSearchMode?: CodexSdkWebSearchMode; webSearchEnabled?: boolean; approvalPolicy?: CodexSdkApprovalMode; additionalDirectories?: string[]; }; type CodexSdkTurnOptions = { signal?: AbortSignal; outputSchema?: Record; }; type CodexSdkThreadEvent = Record; type CodexSdkInput = string | CodexInputPart[]; type CodexSdkThreadLike = { readonly id?: string | null; runStreamed(input: CodexSdkInput, options?: CodexSdkTurnOptions): Promise<{ events: AsyncGenerator; }>; }; type CodexSdkClientLike = { startThread(options?: CodexSdkThreadOptions): CodexSdkThreadLike; resumeThread(id: string, options?: CodexSdkThreadOptions): CodexSdkThreadLike; }; type CodexSdkConstructor = new (options?: CodexSdkOptions) => CodexSdkClientLike; type CodexSdkModuleLike = { Codex: CodexSdkConstructor; }; interface CodexBinaryResolution { path?: string; checked: string[]; } interface CodexSdkDriverConfig { sdk?: CodexSdkClientLike; Codex?: CodexSdkConstructor; importSdk?: () => Promise; codexPathOverride?: string; env?: Record; baseUrl?: string; apiKey?: string; config?: CodexSdkConfigObject; model?: string; modelReasoningEffort?: CodexSdkModelReasoningEffort; skipGitRepoCheck?: boolean; webSearchMode?: CodexSdkWebSearchMode; webSearchEnabled?: boolean; outputSchema?: Record; /** * Computes the `session.state` key used to persist Codex thread IDs so a * subsequent invocation can call `resumeThread(savedId)` instead of starting * a fresh thread. Defaults to `"codex_thread:" + agentName`. */ threadStateKey?: (agentName: string) => string; } declare class CodexSdkDriver { private; readonly providerId: ExternalAgentProviderId; constructor(config?: CodexSdkDriverConfig); capabilities(): { streaming: boolean; sessions: boolean; permissions: boolean; tools: boolean; mcpServers: boolean; }; run(request: ExternalAgentRunRequest): AsyncIterable; buildClientOptions(request: ExternalAgentRunRequest): CodexSdkOptions; buildThreadOptions(request: ExternalAgentRunRequest): CodexSdkThreadOptions; resolveCodexBinary(request: ExternalAgentRunRequest): CodexBinaryResolution; buildEnv(request: ExternalAgentRunRequest): Record; normalizeEvent(event: CodexSdkThreadEvent): ExternalAgentEvent[]; private loadSdk; private loadConstructor; private describeError; } declare function mapPolicyToCodexSdkThreadOptions(permissions?: ExternalAgentPermissionPolicy): CodexSdkThreadOptions; export { AgentRuntimeCapabilities, AgentRuntimeRequestMetadata, AgentRuntimeSession, BaseAgent5 as BaseAgent, CLAUDE_AGENT_DEFINITION, CLAUDE_PROVIDER, CODEX_AGENT_DEFINITION, CODEX_ENV_ALLOWLIST, CODEX_PROVIDER, ClassifyRecoverableInput, ClaudeAgent, ClaudeAgentConfig, ClaudeAgentSdkDriver, ClaudeAgentSdkDriverConfig, ClaudeCliDriver, ClaudeCliDriverConfig, ClaudeCliSpawn, ClaudeCliSpawnOptions, ClaudeCliSubprocess, ClaudeContentBlockParam, ClaudeMessageParam, CodexAgent, CodexAgentConfig, CodexCliDriver, CodexCliDriverConfig, CodexCliSpawn, CodexCliSpawnOptions, CodexCliSubprocess, CodexInputMapperOptions, CodexInputMapping, CodexInputPart, CodexSdkDriver, CodexSdkDriverConfig, CredentialRequest, EnvCredentialProvider, ExternalAgent, ExternalAgentAuthKind, ExternalAgentCompletedEvent, ExternalAgentConfig, ExternalAgentCredential, ExternalAgentCredentialProvider, ExternalAgentDefinition, ExternalAgentDefinitionConfig, ExternalAgentDefinitionRegistry, ExternalAgentDriver, ExternalAgentErrorEvent, ExternalAgentEvent, ExternalAgentOutputEvent, ExternalAgentPermissionMode, ExternalAgentPermissionPolicy, ExternalAgentProviderDefinition, ExternalAgentProviderId, ExternalAgentProviderRegistry, ExternalAgentRunRequest, ExternalAgentRuntimeKind, ExternalAgentStartedEvent, ExternalAgentStateDeltaEvent, ExternalAgentToolCallEvent, ExternalAgentToolResultEvent, GEMINI_CLI_AGENT_DEFINITION, GEMINI_CLI_ENV_ALLOWLIST, GEMINI_CLI_PROVIDER, GeminiCliAgent, GeminiCliAgentConfig, GeminiCliDriver, GeminiCliDriverConfig, GeminiCliSpawn, GeminiCliSpawnOptions, GeminiCliSubprocess, NoopCredentialProvider, PlaceholderExternalAgentDriver, ProviderPermissionFlags, RecoverableClassification, RunSubAgentInput, RunSubAgentResult, SDKUserMessage, SubprocessJsonlDriver, SubprocessJsonlDriverConfig, ToolGateway, ToolGatewayConfig, buildGeminiArgs, classifyRecoverable, collectContents, contentsToSdkMessages, createDefaultExternalAgentDefinitionRegistry, createDefaultExternalAgentProviderRegistry, createExternalAgent, createExternalAgentConfig, deriveSubAgentPermissionPolicy, externalAgentDefinitionRegistry, externalAgentProviderRegistry, flattenContentsToPrompt, isExternalAgentEvent, mapClaudePermissionArgs, mapGeminiPermissionArgs, mapPermissionModeToPolicy, mapPermissionPolicyToFlags, mapPolicyToClaudeSdkPermission, mapPolicyToCodexArgs, mapPolicyToCodexSdkThreadOptions, readAllowedEnv, resolveAbortSignal, summarizeHistoryForColdStart, userContentToCodexInput };