import type { Model } from "../types"; import type { StandardSchemaV1 } from "../schema.js"; import type { JsonSchema, RequestOptions } from "../types.js"; /** Tool definition sent to the OpenResponses endpoint. */ export interface ORTool { type: "function"; name: string; description?: string; parameters?: JsonSchema; strict?: boolean; } /** Input item sent to the server as part of the items array. */ export type ORInputItem = ORMessageInputItem | ORFunctionCallInputItem | ORFunctionCallOutputItem; export interface ORMessageInputItem { type: "message"; role: "user" | "assistant" | "system" | "developer"; content: string; } export interface ORFunctionCallInputItem { type: "function_call"; call_id: string; name: string; arguments: string; } export interface ORFunctionCallOutputItem { type: "function_call_output"; call_id: string; output: string; } /** Text format for structured output (JSON Schema enforcement). */ export interface ORTextFormat { format: { type: "json_schema"; name: string; schema: JsonSchema; }; } /** Reasoning configuration. */ export interface ORReasoning { effort?: "low" | "medium" | "high"; summary?: string; } /** Request body for POST /v3/compat/openresponses. */ export interface ORRequest { input: string | ORInputItem[]; /** Model to use — a string, a `ModelConfig` with provider-specific options, or a fallback chain. */ model?: Model; instructions?: string; tools?: ORTool[]; stream?: boolean; temperature?: number; max_output_tokens?: number; previous_response_id?: string; tool_choice?: unknown; text?: ORTextFormat; reasoning?: ORReasoning; metadata?: Record; store?: boolean; truncation?: string; parallel_tool_calls?: boolean; max_tool_calls?: number; frequency_penalty?: number; presence_penalty?: number; top_p?: number; service_tier?: string; include?: string[]; } /** Output item returned from the server in the response. */ export type OROutputItem = ORMessageOutputItem | ORFunctionCallOutputItemResponse | ORReasoningOutputItem; export interface ORMessageOutputItem { type: "message"; id: string; role: "assistant"; status: string; content: ORContentPart[]; } export interface ORContentPart { type: string; text: string; annotations?: unknown[]; refusal?: string; } export interface ORFunctionCallOutputItemResponse { type: "function_call"; id: string; call_id: string; name: string; arguments: string; status: string; } export interface ORReasoningOutputItem { type: "reasoning"; id: string; summary: Array<{ type: string; text: string; }>; encrypted_content?: string; } /** Usage information from the server. */ export interface ORUsage { input_tokens: number; output_tokens: number; total_tokens: number; input_tokens_details?: { cached_tokens: number; }; output_tokens_details?: { reasoning_tokens: number; }; /** Execution cost in USD. Surfaced on streaming `response.completed`; non-stream uses the `X-Opper-Cost` header. */ cost?: number; } /** Error information from the server. */ export interface ORError { code: string; message: string; param?: string; type: string; } /** Response from POST /v3/compat/openresponses (stream: false). */ export interface ORResponse { id: string; object: string; status: string; created_at: number; completed_at?: number; model: string; output: OROutputItem[]; usage?: ORUsage; error?: ORError; instructions?: string; metadata?: Record; temperature?: number; max_output_tokens?: number; top_p?: number; frequency_penalty?: number; presence_penalty?: number; text?: ORTextFormat; reasoning?: ORReasoning; tools?: ORTool[]; tool_choice?: unknown; truncation?: string; service_tier?: string; incomplete_details?: unknown; parallel_tool_calls?: boolean; previous_response_id?: string; } /** SSE events from the OpenResponses endpoint (stream: true). */ export type ORStreamEvent = ORResponseCreatedEvent | ORResponseInProgressEvent | ORResponseCompletedEvent | ORResponseFailedEvent | ORResponseIncompleteEvent | OROutputItemAddedEvent | OROutputItemDoneEvent | ORContentPartAddedEvent | ORContentPartDoneEvent | OROutputTextDeltaEvent | OROutputTextDoneEvent | ORFunctionCallArgsDeltaEvent | ORFunctionCallArgsDoneEvent | ORReasoningSummaryDeltaEvent | ORReasoningSummaryDoneEvent | ORStreamErrorEvent; export interface ORResponseCreatedEvent { type: "response.created"; response: ORResponse; } export interface ORResponseInProgressEvent { type: "response.in_progress"; response: ORResponse; } export interface ORResponseCompletedEvent { type: "response.completed"; response: ORResponse; } export interface ORResponseFailedEvent { type: "response.failed"; response: ORResponse; } export interface ORResponseIncompleteEvent { type: "response.incomplete"; response: ORResponse; } export interface OROutputItemAddedEvent { type: "response.output_item.added"; output_index: number; item: OROutputItem; } export interface OROutputItemDoneEvent { type: "response.output_item.done"; output_index: number; item: OROutputItem; } export interface ORContentPartAddedEvent { type: "response.content_part.added"; output_index: number; content_index: number; part: ORContentPart; } export interface ORContentPartDoneEvent { type: "response.content_part.done"; output_index: number; content_index: number; part: ORContentPart; } export interface OROutputTextDeltaEvent { type: "response.output_text.delta"; output_index: number; content_index: number; delta: string; } export interface OROutputTextDoneEvent { type: "response.output_text.done"; output_index: number; content_index: number; text: string; } export interface ORFunctionCallArgsDeltaEvent { type: "response.function_call_arguments.delta"; output_index: number; call_id: string; delta: string; } export interface ORFunctionCallArgsDoneEvent { type: "response.function_call_arguments.done"; output_index: number; call_id: string; arguments: string; } export interface ORReasoningSummaryDeltaEvent { type: "response.reasoning_summary_text.delta"; output_index: number; delta: string; } export interface ORReasoningSummaryDoneEvent { type: "response.reasoning_summary_text.done"; output_index: number; text: string; } export interface ORStreamErrorEvent { type: "error"; error: { code: string; message: string; }; } /** Schema-like type: JSON Schema object or Standard Schema V1. */ export type SchemaLike = JsonSchema | StandardSchemaV1; /** Configuration for defining a tool with Standard Schema type inference. */ export interface ToolConfig { name: string; description: string; parameters?: TParams; timeoutMs?: number; execute: (input: TParams extends StandardSchemaV1 ? I : unknown) => unknown | Promise; } /** A resolved agent tool — parameters resolved to JSON Schema. */ export interface AgentTool { name: string; description: string; parameters?: JsonSchema; timeoutMs?: number; execute: (input: unknown) => unknown | Promise; /** @internal Set by `asTool()` to mark this tool as wrapping a sub-agent. */ _subAgent?: boolean; } /** A tool provider that dynamically supplies tools with lifecycle management. */ export interface ToolProvider { type: "tool_provider"; setup(): Promise; teardown(): Promise; } /** Type guard: is this an AgentTool or a ToolProvider? */ export declare function isToolProvider(t: AgentTool | ToolProvider): t is ToolProvider; /** Retry policy for transient LLM call failures. */ export interface RetryPolicy { /** Maximum number of retries before giving up. Default: 2 */ maxRetries?: number; /** Initial delay in milliseconds before the first retry. Default: 1000 */ initialDelayMs?: number; /** Multiplier applied to the delay after each retry. Default: 2 */ backoffMultiplier?: number; } /** Configuration for creating an Agent — with Standard Schema output type inference. */ export interface AgentConfig { name: string; instructions: string; tools?: (AgentTool | ToolProvider)[]; /** Model to use — a string, a `ModelConfig` with provider-specific options, or a fallback chain. */ model?: Model; outputSchema?: S; temperature?: number; maxTokens?: number; maxIterations?: number; reasoningEffort?: "low" | "medium" | "high"; /** Opt into thought summary streaming, e.g. `"auto"`. */ reasoningSummary?: string; parallelToolExecution?: boolean; hooks?: Hooks; /** Override the function name used for tracing. Defaults to `name`. */ traceName?: string; /** Enable/disable tracing. Defaults to `true`. Set to `false` to skip span creation. */ tracing?: boolean; client?: { apiKey?: string; baseUrl?: string; }; /** Retry policy for transient LLM call failures (5xx, rate limits, network errors). */ retry?: RetryPolicy; /** Behavior when max iterations is reached. `"throw"` (default) or `"return_partial"`. */ onMaxIterations?: "throw" | "return_partial"; /** * How to deliver a structured output when tools are also in play. * * - `"auto"` (default): consult the SDK's model-capability lookup. Models * on the whitelist use the native JSON-schema response format; others * fall back to a synthetic `final_answer` tool whose `parameters` are * the requested `outputSchema`. * - `"native"`: always use JSON-schema response format alongside tools, * even on models not known to support it (the provider may reject). * - `"tool"`: always use the `final_answer` synthetic-tool fallback. */ structuredOutputMode?: "auto" | "native" | "tool"; } /** * Infer the output type from an AgentConfig's outputSchema. * - StandardSchemaV1 → inferred output type * - plain JsonSchema / undefined → unknown */ export type InferAgentOutput = S extends StandardSchemaV1 ? O : unknown; /** Base context shared by all hooks. */ interface HookContextBase { agent: string; } /** Context for onAgentStart — fired before the loop begins. */ export interface AgentStartHookContext extends HookContextBase { input: string | ORInputItem[]; } /** Context for onAgentEnd — fired after the loop completes (success or error). */ export interface AgentEndHookContext extends HookContextBase { result?: RunResult; error?: Error; } /** Context for onIterationStart — fired at the beginning of each iteration. */ export interface IterationStartHookContext extends HookContextBase { iteration: number; } /** Context for onIterationEnd — fired at the end of each iteration. */ export interface IterationEndHookContext extends HookContextBase { iteration: number; usage: AggregatedUsage; } /** Context for onLLMCall — fired before calling the OpenResponses endpoint. */ export interface LLMCallHookContext extends HookContextBase { iteration: number; request: ORRequest; } /** Context for onLLMResponse — fired after receiving the response. */ export interface LLMResponseHookContext extends HookContextBase { iteration: number; response: ORResponse; } /** Context for onToolStart — fired before executing a tool. */ export interface ToolStartHookContext extends HookContextBase { iteration: number; name: string; callId: string; input: unknown; } /** Context for onToolEnd — fired after executing a tool. */ export interface ToolEndHookContext extends HookContextBase { iteration: number; name: string; callId: string; output: unknown; error?: string; durationMs: number; } /** Context for onError — fired when a recoverable error occurs and is injected as context. */ export interface ErrorHookContext extends HookContextBase { iteration: number; error: Error; willRetry: boolean; } /** Lifecycle hooks for observing and reacting to agent execution. */ export interface Hooks { onAgentStart?: (ctx: AgentStartHookContext) => void | Promise; onAgentEnd?: (ctx: AgentEndHookContext) => void | Promise; onIterationStart?: (ctx: IterationStartHookContext) => void | Promise; onIterationEnd?: (ctx: IterationEndHookContext) => void | Promise; onLLMCall?: (ctx: LLMCallHookContext) => void | Promise; onLLMResponse?: (ctx: LLMResponseHookContext) => void | Promise; onToolStart?: (ctx: ToolStartHookContext) => void | Promise; onToolEnd?: (ctx: ToolEndHookContext) => void | Promise; /** Fired when a recoverable error occurs (transient LLM failure, server error in response). */ onError?: (ctx: ErrorHookContext) => void | Promise; } /** Per-run option overrides. */ export interface RunOptions { /** Model to use — a string, a `ModelConfig` with provider-specific options, or a fallback chain. */ model?: Model; temperature?: number; maxTokens?: number; maxIterations?: number; reasoningEffort?: "low" | "medium" | "high"; /** Opt into thought summary streaming, e.g. `"auto"`. */ reasoningSummary?: string; signal?: AbortSignal; parentSpanId?: string; requestOptions?: RequestOptions; /** Per-run override of {@link AgentConfig.structuredOutputMode}. */ structuredOutputMode?: "auto" | "native" | "tool"; } /** Record of a single tool call made during the run. */ export interface ToolCallRecord { name: string; callId: string; input: unknown; output: unknown; error?: string; durationMs: number; } /** The result of running an agent. */ export interface RunResult { output: TOutput; meta: RunMeta; } /** Metadata from an agent run — usage, tool calls, iteration count. */ export interface RunMeta { usage: AggregatedUsage; iterations: number; toolCalls: ToolCallRecord[]; responseId?: string; /** Reasoning summaries, one per iteration that produced reasoning. */ reasoning?: string[]; } /** Aggregated token usage across all iterations. */ export interface AggregatedUsage { inputTokens: number; outputTokens: number; totalTokens: number; cachedTokens?: number; reasoningTokens?: number; } /** Events yielded by `agent.stream()`. */ export type AgentStreamEvent = IterationStartEvent | TextDeltaEvent | ReasoningDeltaEvent | ToolStartEvent | ToolEndEvent | IterationEndEvent | ResultEvent | StreamErrorEvent; export interface IterationStartEvent { type: "iteration_start"; iteration: number; } export interface TextDeltaEvent { type: "text_delta"; text: string; } export interface ReasoningDeltaEvent { type: "reasoning_delta"; text: string; } export interface ToolStartEvent { type: "tool_start"; name: string; callId: string; input: unknown; } export interface ToolEndEvent { type: "tool_end"; name: string; callId: string; output: unknown; error?: string; durationMs: number; } export interface IterationEndEvent { type: "iteration_end"; iteration: number; usage?: AggregatedUsage; } export interface ResultEvent { type: "result"; output: unknown; meta: RunMeta; } export interface StreamErrorEvent { type: "error"; error: Error; } /** Internal signal yielded by consumeStream when a tool call's arguments are fully received. */ export interface ToolReadySignal { type: "tool_ready"; call: ORFunctionCallOutputItemResponse; } export {};