import type { $ZodObject, $ZodShape, $ZodType, infer as zodInfer } from 'zod/v4/core'; import type * as models from '../models/index.js'; import type { StreamEvents } from '../models/index.js'; import type { ModelResult } from './model-result.js'; /** * Tool type enum for enhanced tools */ export declare enum ToolType { Function = "function" } /** * Turn context passed to tool execute functions and async parameter resolution * Contains information about the current conversation state */ export interface TurnContext { /** The specific tool call being executed (only available during tool execution) */ toolCall?: models.FunctionCallItem; /** Number of tool execution turns so far (1-indexed: first turn = 1, 0 = initial request) */ numberOfTurns: number; /** The full request being sent to the API (only available during tool execution) */ turnRequest?: models.ResponsesRequest; } /** * Extract context schema type from a tool definition * Returns the inferred type of the tool's contextSchema, or empty object if none */ export type InferToolContext = T extends { function: { contextSchema: infer S; }; } ? S extends $ZodType ? zodInfer : Record : Record; /** * Extract tool name from a tool definition */ type InferToolName = T extends { function: { name: infer N extends string; }; } ? N : string; /** * Flat execute context passed as the second argument to tool execute functions. * Merges TurnContext fields with a `local` getter (own tool context) and `setContext()`. * * @template TName - The tool's literal name string * @template TContext - The shape of the tool's contextSchema * @template TShared - The shape of the sharedContextSchema */ export type ToolExecuteContext = Record, TShared extends Record = Record> = TurnContext & { /** The tool's name (type-level only, for generic inference) */ readonly _toolName?: TName; /** This tool's own context (reads from the store, frozen snapshot) */ local: Readonly; /** Mutate this tool's context in the shared store (persists across turns) */ setContext(partial: Partial): void; /** Shared context visible to all tools */ shared: Readonly; /** Mutate the shared context in the store (persists across turns) */ setSharedContext(partial: Partial): void; }; /** * Context map keyed by tool name for callModel's `context` option. * Each key is a tool's name, each value is that tool's inferred context type. */ export type ToolContextMap = { [K in T[number] as InferToolName]: InferToolContext; }; /** * Context map with an optional `shared` key for shared context. * When TShared is provided (non-empty), a `shared` key is added to the map. */ export type ToolContextMapWithShared = Record> = ToolContextMap & (TShared extends Record ? {} : { shared: TShared; }); /** * Reserved key in the context store for shared context data. * The tool name 'shared' is forbidden — it's reserved for this purpose. */ export declare const SHARED_CONTEXT_KEY: "shared"; /** * Context passed to nextTurnParams functions * Contains current request state for parameter computation * Allows modification of key request parameters between turns */ export type NextTurnParamsContext = { /** Current input (messages) */ input: models.InputsUnion; /** Current model selection */ model: string; /** Current models array */ models: string[]; /** Current temperature */ temperature: number | null; /** Current maxOutputTokens */ maxOutputTokens: number | null; /** Current topP */ topP: number | null; /** Current topK */ topK?: number | undefined; /** Current instructions */ instructions: string | null; }; /** * Functions to compute next turn parameters * Each function receives the tool's input params and current request context */ export type NextTurnParamsFunctions = { [K in keyof NextTurnParamsContext]?: (params: TInput, context: NextTurnParamsContext) => NextTurnParamsContext[K] | Promise; }; /** * Tool-level approval check function type * Receives the tool's input params and turn context * Returns true if approval is required, false otherwise */ export type ToolApprovalCheck = (params: TInput, context: TurnContext) => boolean | Promise; /** * Base tool function interface with inputSchema * @template TInput - Zod schema for tool input */ export interface BaseToolFunction> { name: string; description?: string; inputSchema: TInput; /** Zod schema declaring the context data this tool needs */ contextSchema?: $ZodObject<$ZodShape>; nextTurnParams?: NextTurnParamsFunctions>; /** * Whether this tool requires human approval before execution * Can be a boolean or an async function that receives the tool's input params and context */ requireApproval?: boolean | ToolApprovalCheck>; } /** * Regular tool with synchronous or asynchronous execute function and optional outputSchema * @template TContext - Shape of the tool's context (inferred from contextSchema) * @template TName - The tool's literal name string */ export interface ToolFunctionWithExecute, TOutput extends $ZodType = $ZodType, TContext extends Record = Record, TName extends string = string> extends BaseToolFunction { outputSchema?: TOutput; execute: (params: zodInfer, context?: ToolExecuteContext) => Promise> | zodInfer; } /** * Generator-based tool with async generator execute function * Emits preliminary events (validated by eventSchema) during execution * and a final output (validated by outputSchema) as the last emission * * The generator can yield both events and the final output. * All yields are validated against eventSchema (which should be a union of event and output types), * and the last yield is additionally validated against outputSchema. * * @example * ```typescript * { * eventSchema: z.object({ status: z.string() }), // For progress events * outputSchema: z.object({ result: z.number() }), // For final output * execute: async function* (params) { * yield { status: "processing..." }; // Event * yield { status: "almost done..." }; // Event * yield { result: 42 }; // Final output (must be last) * } * } * ``` */ export interface ToolFunctionWithGenerator, TEvent extends $ZodType = $ZodType, TOutput extends $ZodType = $ZodType, TContext extends Record = Record, TName extends string = string> extends BaseToolFunction { eventSchema: TEvent; outputSchema: TOutput; execute: (params: zodInfer, context?: ToolExecuteContext) => AsyncGenerator | zodInfer, zodInfer | void>; } /** * Manual tool without execute function - requires manual handling by developer */ export interface ManualToolFunction, TOutput extends $ZodType = $ZodType> extends BaseToolFunction { outputSchema?: TOutput; } /** * Tool with execute function (regular or generator) */ export type ToolWithExecute = $ZodObject<$ZodShape>, TOutput extends $ZodType = $ZodType, TContext extends Record = Record> = { type: ToolType.Function; function: ToolFunctionWithExecute; }; /** * Tool with generator execute function */ export type ToolWithGenerator = $ZodObject<$ZodShape>, TEvent extends $ZodType = $ZodType, TOutput extends $ZodType = $ZodType, TContext extends Record = Record> = { type: ToolType.Function; function: ToolFunctionWithGenerator; }; /** * Tool without execute function (manual handling) */ export type ManualTool = $ZodObject<$ZodShape>, TOutput extends $ZodType = $ZodType> = { type: ToolType.Function; function: ManualToolFunction; }; /** * Union type of all enhanced tool types */ export type Tool = ToolWithExecute<$ZodObject<$ZodShape>, $ZodType> | ToolWithGenerator<$ZodObject<$ZodShape>, $ZodType, $ZodType> | ManualTool<$ZodObject<$ZodShape>, $ZodType>; /** * Extracts the input type from a tool definition */ export type InferToolInput = T extends { function: { inputSchema: infer S; }; } ? S extends $ZodType ? zodInfer : unknown : unknown; /** * Extracts the output type from a tool definition */ export type InferToolOutput = T extends { function: { outputSchema: infer S; }; } ? S extends $ZodType ? zodInfer : unknown : unknown; /** * A tool call with typed arguments based on the tool's inputSchema */ export type TypedToolCall = { id: string; name: T extends { function: { name: infer N; }; } ? N : string; arguments: InferToolInput; }; /** * Union of typed tool calls for a tuple of tools */ export type TypedToolCallUnion = { [K in keyof T]: T[K] extends Tool ? TypedToolCall : never; }[number]; /** * Union of typed tool execution results for a tuple of tools */ export type ToolExecutionResultUnion = { [K in keyof T]: T[K] extends Tool ? ToolExecutionResult : never; }[number]; /** * Union of output types for all tools in a tuple * Used for typing tool result events */ export type InferToolOutputsUnion = { [K in keyof T]: T[K] extends Tool ? InferToolOutput : never; }[number]; /** * Extracts the event type from a generator tool definition * Returns `never` for non-generator tools */ export type InferToolEvent = T extends { function: { eventSchema: infer S; }; } ? S extends $ZodType ? zodInfer : never : never; /** * Union of event types for all generator tools in a tuple * Filters out non-generator tools (which return `never`) */ export type InferToolEventsUnion = { [K in keyof T]: T[K] extends Tool ? InferToolEvent : never; }[number]; /** * Type guard to check if a tool has an execute function */ export declare function hasExecuteFunction(tool: Tool): tool is ToolWithExecute | ToolWithGenerator; /** * Type guard to check if a tool uses a generator (has eventSchema) */ export declare function isGeneratorTool(tool: Tool): tool is ToolWithGenerator; /** * Type guard to check if a tool is a regular execution tool (not generator) */ export declare function isRegularExecuteTool(tool: Tool): tool is ToolWithExecute; /** * Type guard to check if a tool is a manual tool (no execute function) */ export declare function isManualTool(tool: Tool): tool is ManualTool; /** * Parsed tool call from API response * @template T - The tool type to infer argument types from */ export interface ParsedToolCall { id: string; name: T extends { function: { name: infer N; }; } ? N : string; arguments: InferToolInput; } /** * Result of tool execution * @template T - The tool type to infer result types from */ export interface ToolExecutionResult { toolCallId: string; toolName: string; result: T extends ToolWithExecute<$ZodObject<$ZodShape>, infer O> | ToolWithGenerator<$ZodObject<$ZodShape>, $ZodType, infer O> ? zodInfer : unknown; preliminaryResults?: T extends ToolWithGenerator<$ZodObject<$ZodShape>, infer E> ? zodInfer[] : undefined; error?: Error; } /** * Warning from step execution */ export interface Warning { type: string; message: string; } /** * Result of a single step in the tool execution loop * Compatible with Vercel AI SDK pattern */ export interface StepResult { readonly stepType: 'initial' | 'continue'; readonly text: string; readonly toolCalls: TypedToolCallUnion[]; readonly toolResults: ToolExecutionResultUnion[]; readonly response: models.OpenResponsesResult; readonly usage?: models.Usage | null | undefined; readonly finishReason?: string | undefined; readonly warnings?: Warning[] | undefined; readonly experimental_providerMetadata?: Record | undefined; } /** * A condition function that determines whether to stop tool execution * Returns true to STOP execution, false to CONTINUE * (Matches Vercel AI SDK semantics) */ export type StopCondition = (options: { readonly steps: ReadonlyArray>; }) => boolean | Promise; /** * Stop condition configuration * Can be a single condition or array of conditions */ export type StopWhen = StopCondition | ReadonlyArray>; /** * Result of executeTools operation */ export interface ExecuteToolsResult { finalResponse: ModelResult; allResponses: ModelResult[]; toolResults: Map; } /** * Standard tool format for OpenRouter API (JSON Schema based) * Matches ResponsesRequestToolFunction structure */ export interface APITool { type: 'function'; name: string; description?: string | null; strict?: boolean | null; parameters: { [k: string]: unknown; } | null; } /** * Tool preliminary result event emitted during generator tool execution * @template TEvent - The event type from the tool's eventSchema */ export type ToolPreliminaryResultEvent = { type: 'tool.preliminary_result'; toolCallId: string; result: TEvent; timestamp: number; }; /** * Tool result event emitted when a tool execution completes * Contains the final result and any preliminary results that were emitted * @template TResult - The result type from the tool's outputSchema * @template TPreliminaryResults - The event type from generator tools' eventSchema */ export type ToolResultEvent = { type: 'tool.result'; toolCallId: string; result: TResult; timestamp: number; preliminaryResults?: TPreliminaryResults[]; }; /** * Tool call output event carrying the fully-formed FunctionCallOutputItem. * Broadcast by executeToolRound so passive consumers (getItemsStream) can yield * tool results in real-time without owning tool execution. */ export type ToolCallOutputEvent = { type: 'tool.call_output'; output: models.FunctionCallOutputItem; timestamp: number; }; /** * Turn start event emitted at the beginning of each API turn * Turn 0 is the initial request, subsequent turns follow tool execution */ export type TurnStartEvent = { type: 'turn.start'; turnNumber: number; timestamp: number; }; /** * Turn end event emitted at the end of each API turn */ export type TurnEndEvent = { type: 'turn.end'; turnNumber: number; timestamp: number; }; /** * Enhanced stream event types for getFullResponsesStream * Extends StreamEvents with tool preliminary results, tool results, * and turn delimiter events for multi-turn streaming * @template TEvent - The event type from generator tools * @template TResult - The result type from tool execution */ export type ResponseStreamEvent = StreamEvents | ToolPreliminaryResultEvent | ToolResultEvent | ToolCallOutputEvent | TurnStartEvent | TurnEndEvent; /** * Type guard to check if an event is a tool preliminary result event */ export declare function isToolPreliminaryResultEvent(event: ResponseStreamEvent): event is ToolPreliminaryResultEvent; /** * Type guard to check if an event is a tool result event */ export declare function isToolResultEvent(event: ResponseStreamEvent): event is ToolResultEvent; /** * Type guard to check if an event is a tool call output event */ export declare function isToolCallOutputEvent(event: ResponseStreamEvent): event is ToolCallOutputEvent; /** * Type guard to check if an event is a turn start event */ export declare function isTurnStartEvent(event: ResponseStreamEvent): event is TurnStartEvent; /** * Type guard to check if an event is a turn end event */ export declare function isTurnEndEvent(event: ResponseStreamEvent): event is TurnEndEvent; /** * Tool stream event types for getToolStream * Includes both argument deltas and preliminary results * @template TEvent - The event type from generator tools */ export type ToolStreamEvent = { type: 'delta'; content: string; } | { type: 'preliminary_result'; toolCallId: string; result: TEvent; }; /** * Chat stream event types for getFullChatStream * Includes content deltas, completion events, and tool preliminary results * @template TEvent - The event type from generator tools */ export type ChatStreamEvent = { type: 'content.delta'; delta: string; } | { type: 'message.complete'; response: models.OpenResponsesResult; } | { type: 'tool.preliminary_result'; toolCallId: string; result: TEvent; } | { type: string; event: StreamEvents; }; /** * Result of a tool execution that hasn't been sent to the model yet * Used for interrupted or awaiting approval states * @template TTools - The tools array type for proper type inference */ export interface UnsentToolResult { /** The ID of the tool call this result is for */ callId: string; /** The name of the tool that was executed */ name: TTools[number]['function']['name']; /** The output of the tool execution */ output: unknown; /** Error message if the tool call was rejected or failed */ error?: string; } /** * Partial response captured during interruption * @template TTools - The tools array type for proper type inference */ export interface PartialResponse { /** Partial text response accumulated before interruption */ text?: string; /** Tool calls that were in progress when interrupted */ toolCalls?: Array>; } /** * Status of a conversation state */ export type ConversationStatus = 'complete' | 'interrupted' | 'awaiting_approval' | 'in_progress'; /** * State for multi-turn conversations with persistence and approval gates * @template TTools - The tools array type for proper type inference */ export interface ConversationState { /** Unique identifier for this conversation */ id: string; /** Full message history */ messages: models.InputsUnion; /** Previous response ID for chaining (OpenRouter server-side optimization) */ previousResponseId?: string; /** Tool calls awaiting human approval */ pendingToolCalls?: Array>; /** Tool results executed but not yet sent to the model */ unsentToolResults?: Array>; /** Partial response data captured during interruption */ partialResponse?: PartialResponse; /** Signal from a new request to interrupt this conversation */ interruptedBy?: string; /** Current status of the conversation */ status: ConversationStatus; /** Creation timestamp (Unix ms) */ createdAt: number; /** Last update timestamp (Unix ms) */ updatedAt: number; } /** * State accessor for loading and saving conversation state * Enables any storage backend (memory, Redis, database, etc.) * @template TTools - The tools array type for proper type inference */ export interface StateAccessor { /** Load the current conversation state, or null if none exists */ load: () => Promise | null>; /** Save the conversation state */ save: (state: ConversationState) => Promise; } /** * Check if a single tool has approval configured (non-false, non-undefined) * Returns true if the tool definitely requires approval, * false if it definitely doesn't, or boolean if it's uncertain */ export type ToolHasApproval = T extends { function: { requireApproval: true | ToolApprovalCheck; }; } ? true : T extends { function: { requireApproval: false; }; } ? false : T extends { function: { requireApproval: undefined; }; } ? false : boolean; /** * Check if ANY tool in an array has approval configured * Returns true if at least one tool might require approval */ export type HasApprovalTools = TTools extends readonly [infer First extends Tool, ...infer Rest extends Tool[]] ? ToolHasApproval extends true ? true : HasApprovalTools : false; /** * Type guard to check if a tool has approval configured at runtime */ export declare function toolHasApprovalConfigured(tool: Tool): boolean; /** * Type guard to check if any tools in array have approval configured at runtime */ export declare function hasApprovalRequiredTools(tools: readonly Tool[]): boolean; export {}; //# sourceMappingURL=tool-types.d.ts.map