/** * Agent Types and Zod Schemas * * Canonical type definitions for agent configuration, events, hooks, * extensions, and results. * * ProviderConfig is left as `unknown` here so that shared stays * dependency-free of @cline/llms. Consuming packages narrow it * via re-exports. ModelInfo lives in shared (../llms/model-info) * and is used directly. */ import { z } from "zod"; import type { AgentRuntimeHooks, AgentTool, ProviderErrorClass } from "../agent"; import type { ExtensionContext } from "../extensions/context"; import type { AgentExtensionApi, AgentExtensionHooks, AgentExtensionRegistry as AgentExtensionRegistryGeneric, ContributionRegistryExtension, PluginManifest, PluginSetupContext } from "../extensions/contribution-registry"; import type { HookControl } from "../hooks/contracts"; import type { GeneratedMedia } from "../llms/media"; import type { Message, MessageWithMetadata } from "../llms/messages"; import type { ModelInfo } from "../llms/model-info"; import type { ModelTool } from "../llms/model-tools"; import { type ReasoningEffort } from "../llms/reasoning-options"; export { REASONING_LEVELS, type ReasoningEffort, ReasoningEffortSchema, type ReasoningLevel, ReasoningLevelSchema, } from "../llms/reasoning-options"; import type { ToolApprovalRequest, ToolApprovalResult, ToolCallRecord, ToolPolicy } from "../llms/tools"; import type { BasicLogger } from "../logging/logger"; import type { ITelemetryService } from "../services/telemetry"; import type { WorkspaceInfo } from "../session/workspace"; /** * Events emitted during agent execution */ export type AgentEvent = AgentContentStartEvent | AgentContentUpdateEvent | AgentContentEndEvent | AgentIterationStartEvent | AgentIterationEndEvent | AgentNoticeEvent | AgentUsageEvent | AgentDoneEvent | AgentErrorEvent; export type AgentContentType = "text" | "reasoning" | "media" | "tool"; export interface AgentEventMetadata { /** Current ID */ agentId?: string; /** Task ID */ conversationId?: string; /** ID of the agent that created this agent */ parentAgentId?: string | null; } export interface AgentContentStartEvent extends AgentEventMetadata { type: "content_start"; contentType: AgentContentType; /** The text chunk received from the model */ text?: string; /** Accumulated text so far in this turn */ accumulated?: string; /** The reasoning/thinking text from the model */ reasoning?: string; /** Whether this is redacted reasoning */ redacted?: boolean; /** Name of the tool being called */ toolName?: string; /** Unique identifier for this tool call */ toolCallId?: string; /** Input being passed to the tool */ input?: unknown; /** Where a model tool is executed; absent for ordinary local tools. */ execution?: "client" | "provider"; } export interface AgentContentUpdateEvent extends AgentEventMetadata { type: "content_update"; contentType: "tool"; /** Name of the tool emitting progress */ toolName?: string; /** Unique identifier for this tool call */ toolCallId?: string; /** Partial result emitted by the tool */ update: unknown; } export interface AgentContentEndEvent extends AgentEventMetadata { type: "content_end"; contentType: AgentContentType; /** Final text generated for this turn */ text?: string; /** Final reasoning/thinking text generated for this turn */ reasoning?: string; /** Generated media returned by the model. */ media?: GeneratedMedia; /** Name of the tool that completed */ toolName?: string; /** Unique identifier for this tool call */ toolCallId?: string; /** Output from the tool */ output?: unknown; /** Error message if the tool failed */ error?: string; /** Time taken in milliseconds for tool content */ durationMs?: number; /** Where a model tool is executed; absent for ordinary local tools. */ execution?: "client" | "provider"; } export interface AgentIterationStartEvent extends AgentEventMetadata { type: "iteration_start"; /** The iteration number (1-based) */ iteration: number; } export interface AgentIterationEndEvent extends AgentEventMetadata { type: "iteration_end"; /** The iteration number that just completed */ iteration: number; /** Whether this iteration had any tool calls */ hadToolCalls: boolean; /** Number of tool calls in this iteration */ toolCallCount: number; } export interface AgentUsageEvent extends AgentEventMetadata { type: "usage"; /** Number of input tokens for this turn */ inputTokens: number; /** Number of output tokens for this turn */ outputTokens: number; /** Tokens read from cache */ cacheReadTokens?: number; /** Tokens written to cache */ cacheWriteTokens?: number; /** Cost for this turn */ cost?: number; /** Accumulated totals */ totalInputTokens: number; totalCacheReadTokens?: number; totalCacheWriteTokens?: number; totalOutputTokens: number; totalCost?: number; } export interface AgentNoticeEvent extends AgentEventMetadata { type: "notice"; noticeType: "recovery" | "stop" | "status"; message: string; displayRole?: "system" | "status"; reason?: "api_error" | "invalid_tool_call" | "completion_without_submit" | "tool_execution_failed" | "mistake_limit" | "auto_compaction" | "manual_compaction" | "compaction_budget_emergency"; metadata?: Record; } export interface AgentDoneEvent extends AgentEventMetadata { type: "done"; /** The reason the agent stopped */ reason: AgentFinishReason; /** Final text output */ text: string; /** Total number of iterations */ iterations: number; /** Aggregated usage information */ usage?: LegacyAgentUsage; } export interface AgentErrorEvent extends AgentEventMetadata { type: "error"; /** The error that occurred */ error: Error; /** Classification of the provider error, when known. */ errorClass?: ProviderErrorClass; /** Whether the error is recoverable */ recoverable: boolean; /** Current iteration when error occurred */ iteration: number; } export interface ConsecutiveMistakeLimitContext { iteration: number; consecutiveMistakes: number; maxConsecutiveMistakes: number; reason: "api_error" | "invalid_tool_call" | "tool_execution_failed"; details?: string; } export type ConsecutiveMistakeLimitDecision = { action: "continue"; /** * Optional guidance appended as a user message before continuing. */ guidance?: string; } | { action: "stop"; /** * Optional reason surfaced when stopping due to the limit. */ reason?: string; }; export interface LoopDetectionConfig { softThreshold: number; hardThreshold: number; } export interface AgentExecutionConfig { /** * Maximum consecutive internal mistakes before escalation. * Mistakes include API turn failures, invalid/missing tool-call arguments, * and iterations where every executed tool call fails. * @default 6 */ maxConsecutiveMistakes?: number; /** * After this many consecutive iterations with tool calls, * inject a reminder text block asking the agent to answer if it has enough info. * Set to `0` or omit to disable. * @default 0 */ reminderAfterIterations?: number; /** * Custom reminder text to inject after `reminderAfterIterations`. * @default "REMINDER: If you have gathered enough information to answer the user's question, please provide your final answer now without using any more tools." */ reminderText?: string; /** * Repeated tool call loop detection. When enabled, the agent detects * consecutive identical tool calls and intervenes: * - At `softThreshold`: injects a recovery notice urging a different approach. * - At `hardThreshold`: triggers the consecutive-mistake-limit decision path. * * Set to `false` to explicitly disable. Omit or leave `undefined` for no detection. * The CLI enables this by default with `{ softThreshold: 3, hardThreshold: 5 }`. */ loopDetection?: false | Partial; } /** * Hook error handling behavior. * - "ignore": swallow hook errors and continue agent execution * - "throw": fail agent execution when a hook throws */ export type HookErrorMode = "ignore" | "throw"; /** * Common controls supported by lifecycle hooks. */ export type AgentHookControl = Omit & { /** * Optional messages appended to history. * Primarily used by before-agent-start hook stages. */ appendMessages?: Message[]; /** * Optional replacement message history. * Primarily used by before-agent-start hooks and host-owned context pipelines. */ replaceMessages?: Message[]; }; export interface AgentHookRunStartContext { /** * ID of the agent */ agentId: string; /** * Session ID */ conversationId: string; /** * ID of the agent that spawned the agent that is executing this run */ parentAgentId: string | null; /** * The prompt submitted by user */ userMessage: string; } export interface AgentHookScheduleContext { scheduleId: string; executionId?: string; trigger: "scheduled" | "manual"; triggeredAt?: string; } /** * Workspace location fields shared by session-scoped and run-scoped contexts. * * These fields are always sourced from the host session config — never from * `process.cwd()`. Plugins and hooks must use these values when they need to * resolve paths relative to the session's working directory or project root, * because the `--cwd` CLI flag sets the session cwd without calling * `process.chdir()`, so `process.cwd()` may return the wrong path. */ export interface SessionWorkspaceEnv { /** * The session's active working directory as configured by the host (e.g. * via `--cwd`). Always accurate — never use `process.cwd()` in plugins or * hooks; use this field instead. */ cwd?: string; /** * The workspace / project root when it differs from `cwd`. Global plugins * installed outside the project should use this rather than * `import.meta.url` tricks or `process.cwd()`. */ workspaceRoot?: string; /** * Structured workspace and git metadata for the session. * * Contains the same information as the `{{CLINE_METADATA}}` block in the * system prompt but in structured form: `rootPath`, `hint`, * `associatedRemoteUrls`, `latestGitCommitHash`, `latestGitBranchName`. * * Plugins and hooks can use this for branch-aware logic, commit * attribution, or tooling integrations without running their own `git` * calls. Populated once per session at session-start time. */ workspaceInfo?: WorkspaceInfo; } /** * Fired exactly once for the lifetime of an agent conversation, before the * first run starts. This is the right place for session-scoped setup. */ export interface AgentHookSessionStartContext extends SessionWorkspaceEnv { agentId: string; conversationId: string; parentAgentId: string | null; schedule?: AgentHookScheduleContext; } /** * Fired once per `run()` / `continue()` invocation after user input has been * accepted and before the loop enters its first iteration. */ export interface AgentHookRunEndContext { agentId: string; conversationId: string; parentAgentId: string | null; result: AgentResult; } /** * Fired at the top of every loop iteration, before any turn-level prompt or * model preparation occurs. */ export interface AgentHookIterationStartContext { agentId: string; conversationId: string; parentAgentId: string | null; iteration: number; } export interface AgentHookIterationEndContext { agentId: string; conversationId: string; parentAgentId: string | null; iteration: number; hadToolCalls: boolean; toolCallCount: number; } export interface AgentHookTurnStartContext { agentId: string; conversationId: string; parentAgentId: string | null; iteration: number; messages: Message[]; } /** * Fired immediately before the model call for an iteration. * * Compared with `onIterationStart`, this hook runs later: after turn-start * processing and with the exact message list that will be sent to the model. * It can still influence the upcoming turn by replacing the system prompt, * appending messages, or cancelling the run. */ export interface AgentHookBeforeAgentStartContext { agentId: string; conversationId: string; parentAgentId: string | null; iteration: number; systemPrompt: string; messages: Message[]; } export interface AgentHookTurnEndContext { agentId: string; conversationId: string; parentAgentId: string | null; iteration: number; turn: ProcessedTurn; } export interface AgentHookToolCallStartContext { agentId: string; conversationId: string; parentAgentId: string | null; iteration: number; call: PendingToolCall; } export interface AgentHookToolCallEndContext { agentId: string; conversationId: string; parentAgentId: string | null; iteration: number; record: ToolCallRecord; } export interface AgentHookErrorContext { agentId: string; conversationId: string; parentAgentId: string | null; iteration: number; error: Error; } export interface AgentHookStopErrorContext { agentId: string; conversationId: string; parentAgentId: string | null; iteration: number; error: Error; } export interface AgentHookSessionShutdownContext { agentId: string; conversationId: string; /** Stable core session id for the root session, when provided by the host. */ sessionId?: string; parentAgentId: string | null; /** * Optional reason for shutdown (e.g. "ctrl_d", "process_exit") */ reason?: string; } export interface AgentExtensionRuntimeEventContext { agentId: string; conversationId: string; parentAgentId: string | null; event: AgentEvent; } export interface AgentExtensionSessionStartContext extends SessionWorkspaceEnv { agentId: string; conversationId: string; parentAgentId: string | null; schedule?: AgentHookScheduleContext; } export interface AgentExtensionSessionShutdownContext { agentId: string; conversationId: string; /** Stable core session id for the root session, when provided by the host. */ sessionId?: string; parentAgentId: string | null; reason?: string; } export interface AgentExtensionContext extends PluginSetupContext { } export interface AgentExtension extends ContributionRegistryExtension { name: string; manifest: PluginManifest; hooks?: AgentExtensionHooks; setup?: (api: AgentExtensionApi, ctx: AgentExtensionContext) => void | Promise; } export type AgentLoopExtensionRegistry = AgentExtensionRegistryGeneric; /** * Lifecycle hooks for observing or influencing agent execution. */ export type AgentHooks = Partial; /** * Reasons why the agent stopped executing */ export type AgentFinishReason = "completed" | "max_iterations" | "aborted" | "mistake_limit" | "error"; export declare const AgentFinishReasonSchema: z.ZodEnum<{ error: "error"; completed: "completed"; aborted: "aborted"; mistake_limit: "mistake_limit"; max_iterations: "max_iterations"; }>; /** * Aggregated token usage and cost information (legacy, host-facing shape). * * Renamed from `AgentUsage` to make room for the runtime's stricter * `AgentUsage` (see `../agent.ts`). Retained because * the host-facing `AgentResult`/`AgentUsageEvent` surface and the * `AgentUsageSchema` Zod schema use this more-permissive shape (all * cache/cost fields optional). The facade adapter converts between the * two shapes at runtime. */ export interface LegacyAgentUsage { /** Total input tokens across all iterations */ inputTokens: number; /** Total output tokens across all iterations */ outputTokens: number; /** Total tokens read from cache */ cacheReadTokens?: number; /** Total tokens written to cache */ cacheWriteTokens?: number; /** Total cost in dollars */ totalCost?: number; } export declare const AgentUsageSchema: z.ZodObject<{ inputTokens: z.ZodNumber; outputTokens: z.ZodNumber; cacheReadTokens: z.ZodOptional; cacheWriteTokens: z.ZodOptional; totalCost: z.ZodOptional; }, z.core.$strip>; export interface AgentPrepareTurnContext { agentId: string; conversationId: string; parentAgentId: string | null; iteration: number; messages: MessageWithMetadata[]; apiMessages: MessageWithMetadata[]; abortSignal: AbortSignal; systemPrompt: string; tools: AgentTool[]; model: { id: string; provider: string; info?: ModelInfo; }; /** * Set when the previous model request was rejected as exceeding the * model's context window; asks the prepare-turn pipeline to force a * compaction rather than trust its token estimates. */ overflowRecovery?: boolean; emitStatusNotice?: (message: string, metadata?: Record) => void; } export interface AgentPrepareTurnResult { messages?: MessageWithMetadata[]; systemPrompt?: string; } /** * Result returned from Agent.run() */ export interface AgentResult { /** Final text output from the agent */ text: string; /** Aggregated token usage and cost */ usage: LegacyAgentUsage; /** Full conversation history */ messages: MessageWithMetadata[]; /** All tool calls made during execution */ toolCalls: ToolCallRecord[]; /** Number of loop iterations */ iterations: number; /** Why the agent stopped */ finishReason: AgentFinishReason; /** Model information used */ model: { id: string; provider: string; info?: ModelInfo; }; /** Start time of the run */ startedAt: Date; /** End time of the run */ endedAt: Date; /** Total duration in milliseconds */ durationMs: number; } export declare const AgentResultSchema: z.ZodObject<{ text: z.ZodString; usage: z.ZodObject<{ inputTokens: z.ZodNumber; outputTokens: z.ZodNumber; cacheReadTokens: z.ZodOptional; cacheWriteTokens: z.ZodOptional; totalCost: z.ZodOptional; }, z.core.$strip>; messages: z.ZodArray>; toolCalls: z.ZodArray>; input: z.ZodUnknown; output: z.ZodUnknown; error: z.ZodOptional; durationMs: z.ZodNumber; startedAt: z.ZodDate; endedAt: z.ZodDate; }, z.core.$strip>>; iterations: z.ZodNumber; finishReason: z.ZodEnum<{ error: "error"; completed: "completed"; aborted: "aborted"; mistake_limit: "mistake_limit"; max_iterations: "max_iterations"; }>; model: z.ZodObject<{ id: z.ZodString; provider: z.ZodString; info: z.ZodOptional; description: z.ZodOptional; maxTokens: z.ZodOptional; contextWindow: z.ZodOptional; maxInputTokens: z.ZodOptional; capabilities: z.ZodOptional>>; operation: z.ZodOptional>; operationModes: z.ZodOptional>>; modalities: z.ZodOptional>; output: z.ZodArray>; }, z.core.$strip>>; reasoningOptions: z.ZodOptional; }, z.core.$strict>, z.ZodObject<{ type: z.ZodLiteral<"effort">; values: z.ZodArray>>; }, z.core.$strict>, z.ZodObject<{ type: z.ZodLiteral<"budget_tokens">; min: z.ZodOptional; max: z.ZodOptional; }, z.core.$strict>], "type">>>; apiFormat: z.ZodOptional>; systemRole: z.ZodOptional>; temperature: z.ZodOptional; pricing: z.ZodOptional; output: z.ZodOptional; cacheWrite: z.ZodOptional; cacheRead: z.ZodOptional; }, z.core.$strip>>; thinkingConfig: z.ZodOptional; outputPrice: z.ZodOptional; thinkingLevel: z.ZodOptional>; }, z.core.$strip>>; status: z.ZodOptional>; deprecationNotice: z.ZodOptional; replacedBy: z.ZodOptional; releaseDate: z.ZodOptional; deprecationDate: z.ZodOptional; family: z.ZodOptional; metadata: z.ZodOptional; }, z.core.$catchall>>; }, z.core.$strip>>; }, z.core.$strip>; startedAt: z.ZodDate; endedAt: z.ZodDate; durationMs: z.ZodNumber; }, z.core.$strip>; /** * Configuration for creating an Agent */ export interface AgentConfig { /** Stable end-user identity used for provider and observability metadata. */ distinctId?: string; /** * Core/hub runtime session identifier. * * The host-owned lifecycle id for this task/session. Core uses it for * persistence, event routing, abort/stop operations, and approval delivery. * This is intentionally separate from `conversationId`, which identifies the * model transcript managed by the agent runtime. */ sessionId?: string; /** Provider ID (e.g., "anthropic", "openai", "gemini") */ providerId: string; /** Model ID to use */ modelId: string; /** API key for the provider */ apiKey?: string; /** Custom base URL for the API */ baseUrl?: string; /** Additional headers for API requests */ headers?: Record; /** * Called when a run fails with an auth-like provider error (e.g. an OAuth * access token that expired mid-run). Hosts refresh credentials and push * the new key into the runtime via `updateConnection`; returning `true` * makes the runtime retry the failed run once with the refreshed * connection. */ onAuthError?: () => Promise; /** Optional provider model catalog overrides */ knownModels?: Record; /** Optional pre-resolved provider configuration (includes provider-specific fields like aws/gcp). */ providerConfig?: unknown; /** * Optional preloaded conversation history for resume flows. * When provided, start by calling continue() to preserve history. */ initialMessages?: Message[]; /** System prompt for the agent */ systemPrompt: string; /** Tools available to the agent */ tools: AgentTool[]; /** Provider-executed tools enabled for the selected model. */ modelTools?: ModelTool[]; /** * Maximum number of loop iterations * If undefined, no iteration cap is enforced. */ maxIterations?: number; /** * Maximum number of tool calls to execute concurrently in a single iteration. * @default 8 */ maxParallelToolCalls?: number; /** * Maximum output tokens per API call */ maxTokensPerTurn?: number; /** * Sampling temperature per API call */ temperature?: number; /** * Timeout for each API call in milliseconds * @default 180000 (3 minutes) */ apiTimeoutMs?: number; /** * Optional runtime file-content loader used when user files are attached. * When omitted, attached files will be represented as loader errors. */ userFileContentLoader?: (path: string) => Promise; /** * Optional metadata merged into every tool execution context. * Hosts can use this to thread runtime-specific identifiers such as session IDs. */ toolContextMetadata?: Record; /** Execution guardrails and recovery settings. */ execution?: AgentExecutionConfig; /** * Reasoning effort level */ reasoningEffort?: ReasoningEffort; /** * Maximum tokens for thinking/reasoning */ thinkingBudgetTokens?: number; /** * Enable default thinking/reasoning behavior for supported models. */ thinking?: boolean; /** * Callback for agent events (streaming, progress, etc.) */ onEvent?: (event: AgentEvent) => void; /** * Lifecycle hooks for observing or influencing agent execution. */ hooks?: AgentHooks; /** * Optional parent agent ID for spawned/delegated runs. * Root agents should leave this undefined. */ parentAgentId?: string; /** * Extension modules that can intercept lifecycle events and register tools/commands. */ extensions?: AgentExtension[]; /** * How hook errors should be handled. * @default "ignore" */ hookErrorMode?: HookErrorMode; /** * Optional schedule metadata for runs initiated by scheduler services. * Used by session_start lifecycle hooks. */ schedule?: AgentHookScheduleContext; /** * Per-tool execution policy. Tool names not listed here default to enabled + autoApprove. */ toolPolicies?: Record; /** * Optional callback to request client approval when a tool policy disables auto-approval. */ requestToolApproval?: (request: ToolApprovalRequest) => Promise | ToolApprovalResult; /** * Optional callback invoked when consecutive mistakes reach maxConsecutiveMistakes. */ onConsecutiveMistakeLimitReached?: (context: ConsecutiveMistakeLimitContext) => Promise | ConsecutiveMistakeLimitDecision; /** * Optional logger for tracing agent loop lifecycle and recoverable failures. */ logger?: BasicLogger; /** * Optional request projection hook invoked before each model call. * * Returned messages affect only the provider request for the current call. * They do not replace the canonical runtime transcript, are not persisted as * session history, and are not reflected in AgentRunResult.messages. * * Hosts that need durable redaction or normalization must apply it before a * message enters the canonical transcript. */ prepareTurn?: (context: AgentPrepareTurnContext) => Promise | AgentPrepareTurnResult | undefined; /** * Optional Telemetry service for emitting structured events about agent execution to configured telemetry backends. */ telemetry?: ITelemetryService; /** * Ambient runtime context: user identity, client surface, workspace, logger, * and telemetry. Threaded through to ProviderConfig so handlers can access it. */ extensionContext?: ExtensionContext; /** * First-class runtime completion policy. Tool-based completion is resolved * from the final agent tool list, so built-in and plugin tools can opt in * with `lifecycle.completesRun`. * * `completionGuard` runs when the model returns no tool calls. * If it returns a non-empty string, that string is injected as a * system-level nudge and the loop continues instead of completing. * Use this to prevent premature exit when the agent has unfinished * obligations (e.g. in-progress team tasks). */ completionPolicy?: { requireCompletionTool?: boolean; completionGuard?: () => string | undefined; }; /** * Optional callback invoked at the top of each agent loop iteration * (after the first). If it returns a non-empty string, that string is * injected as a user message into the conversation before the next API * call. This allows the host to feed user input into a running loop * without waiting for the current run to finish. */ consumePendingUserMessage?: () => string | undefined; /** * Abort signal for cancellation */ abortSignal?: AbortSignal; } export declare const AgentConfigSchema: z.ZodObject<{ distinctId: z.ZodOptional; sessionId: z.ZodOptional; providerId: z.ZodString; modelId: z.ZodString; apiKey: z.ZodOptional; baseUrl: z.ZodOptional; headers: z.ZodOptional>; knownModels: z.ZodOptional; description: z.ZodOptional; maxTokens: z.ZodOptional; contextWindow: z.ZodOptional; maxInputTokens: z.ZodOptional; capabilities: z.ZodOptional>>; operation: z.ZodOptional>; operationModes: z.ZodOptional>>; modalities: z.ZodOptional>; output: z.ZodArray>; }, z.core.$strip>>; reasoningOptions: z.ZodOptional; }, z.core.$strict>, z.ZodObject<{ type: z.ZodLiteral<"effort">; values: z.ZodArray>>; }, z.core.$strict>, z.ZodObject<{ type: z.ZodLiteral<"budget_tokens">; min: z.ZodOptional; max: z.ZodOptional; }, z.core.$strict>], "type">>>; apiFormat: z.ZodOptional>; systemRole: z.ZodOptional>; temperature: z.ZodOptional; pricing: z.ZodOptional; output: z.ZodOptional; cacheWrite: z.ZodOptional; cacheRead: z.ZodOptional; }, z.core.$strip>>; thinkingConfig: z.ZodOptional; outputPrice: z.ZodOptional; thinkingLevel: z.ZodOptional>; }, z.core.$strip>>; status: z.ZodOptional>; deprecationNotice: z.ZodOptional; replacedBy: z.ZodOptional; releaseDate: z.ZodOptional; deprecationDate: z.ZodOptional; family: z.ZodOptional; metadata: z.ZodOptional; }, z.core.$catchall>>; }, z.core.$strip>>>; providerConfig: z.ZodOptional; initialMessages: z.ZodOptional>>; systemPrompt: z.ZodString; tools: z.ZodArray, AgentTool>>; modelTools: z.ZodOptional>>; maxIterations: z.ZodOptional; maxParallelToolCalls: z.ZodDefault; maxTokensPerTurn: z.ZodOptional; temperature: z.ZodOptional; apiTimeoutMs: z.ZodDefault; userFileContentLoader: z.ZodOptional, z.ZodPromise>>; toolContextMetadata: z.ZodOptional>; execution: z.ZodOptional; reminderAfterIterations: z.ZodOptional; reminderText: z.ZodOptional; loopDetection: z.ZodOptional, z.ZodObject<{ softThreshold: z.ZodOptional; hardThreshold: z.ZodOptional; }, z.core.$strip>]>>; }, z.core.$strip>>; reasoningEffort: z.ZodOptional>; thinkingBudgetTokens: z.ZodOptional; thinking: z.ZodOptional; onEvent: z.ZodOptional], z.core.$ZodFunctionOut>, z.ZodVoid>>; hooks: z.ZodOptional, Partial>>; parentAgentId: z.ZodOptional; extensions: z.ZodOptional>>; hookErrorMode: z.ZodDefault>; toolPolicies: z.ZodOptional; autoApprove: z.ZodOptional; }, z.core.$strip>>>; requestToolApproval: z.ZodOptional; autoApprove: z.ZodOptional; }, z.core.$strip>>; }, z.core.$strip>], z.core.$ZodFunctionOut>, z.ZodUnion; }, z.core.$strip>, z.ZodPromise; }, z.core.$strip>>]>>>; onConsecutiveMistakeLimitReached: z.ZodOptional; details: z.ZodOptional; }, z.core.$strip>], z.core.$ZodFunctionOut>, z.ZodUnion; guidance: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ action: z.ZodLiteral<"stop">; reason: z.ZodOptional; }, z.core.$strip>, z.ZodPromise; guidance: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ action: z.ZodLiteral<"stop">; reason: z.ZodOptional; }, z.core.$strip>]>>]>>>; logger: z.ZodOptional>; extensionContext: z.ZodOptional>; abortSignal: z.ZodOptional>; }, z.core.$strip>; /** * Pending tool call from the model */ export interface PendingToolCall { id: string; name: string; input: unknown; signature?: string; review?: boolean; } /** * Processed response from one turn of the loop */ export interface ProcessedTurn { /** Text output from the model */ text: string; /** Reasoning/thinking content */ reasoning?: string; /** Tool calls requested by the model */ toolCalls: PendingToolCall[]; /** Model-emitted tool calls that were invalid or missing required fields */ invalidToolCalls: Array<{ id: string; name?: string; input?: unknown; reason: "missing_name" | "missing_arguments" | "invalid_arguments"; }>; /** Token usage for this turn */ usage: { inputTokens: number; outputTokens: number; cacheReadTokens?: number; cacheWriteTokens?: number; cost?: number; }; /** Whether the response was truncated */ truncated: boolean; /** Response ID from the API */ responseId?: string; }