/** * Shared type definitions for tooled-prompt */ import type { ZodType } from 'zod'; import type { TooledPromptEvents } from './events.js'; import type { HistoryMessage, MessagesSentinel } from './messages.js'; import type { Usage } from './providers/types.js'; /** * Object containing a single named function for tool() syntax * Example: tool({ myFunc }) extracts name "myFunc" from the key */ export type NamedFunction = { [key: string]: (...args: any[]) => any; }; /** * Symbol used to mark functions as LLM tools * Using Symbol.for() ensures the same symbol across module boundaries */ export declare const TOOL_SYMBOL: unique symbol; /** * JSON Schema type for tool parameters */ export interface JsonSchema { type: 'object'; properties: Record; required?: string[]; [key: string]: unknown; } /** * Simple schema format: { field: 'description', 'field?': 'optional description' } */ export type SimpleSchema = Record; /** * A single arg descriptor: string description, [name, description] tuple, or Zod schema */ export type ArgDescriptor = string | [string, string] | ZodType; /** * Recursively maps a function's parameter tuple to a tuple of arg descriptors. * Each position accepts a string, [name, desc] tuple, or a type-checked Zod schema. */ type ArgDescriptorTuple = T extends [] ? [] : T extends [infer H, ...infer R extends any[]] ? [ string | [string, string] | { _zod: { output: H; }; } | { _zod: { output: H | undefined; }; }, ...ArgDescriptorTuple ] : T extends [(infer H)?] ? [ (string | [string, string] | { _zod: { output: NonNullable; }; } | { _zod: { output: NonNullable | undefined; }; })? ] : []; /** * Valid args for a tool function: always an array of arg descriptors. * 0-arg functions get `never` (no args allowed). */ export type ArgsForFn any> = Parameters['length'] extends 0 ? never : ArgDescriptorTuple>; /** * Type-safe options for tool() */ export interface ToolOptions any = (...args: any[]) => any> { description?: string; args?: ArgsForFn; /** Return type description: plain string or Zod schema (type-checked against function return type) */ returns?: string | { _zod: { output: Awaited>; }; }; } /** * Metadata describing a tool function */ export interface ToolMetadata { name: string; description: string; parameters: JsonSchema; /** Resolved return type description (if provided via ToolOptions.returns) */ returns?: string; /** JSON Schema for the return type (set when returns is a Zod schema) */ returnsSchema?: Record; /** Runtime parser for return values (set when returns is a Zod schema) */ parseReturn?: (raw: unknown) => unknown; } /** * A function that has been wrapped with tool metadata */ export interface ToolFunction any = (...args: any[]) => any> { (...args: Parameters): ReturnType; [TOOL_SYMBOL]: ToolMetadata; } /** * Check if a value is a Zod schema */ export declare function isZodSchema(value: unknown): value is ZodType; /** * Check if a value is a SimpleSchema (plain object with string values) */ export declare function isSimpleSchema(value: unknown): value is SimpleSchema; /** * A resolved schema ready for use by executor/store — contains a JSON Schema * and a parse function. Abstracts over ZodType and SimpleSchema so downstream * code never imports Zod directly. */ export interface ResolvedSchema { jsonSchema: Record; parse(data: unknown): T; } /** * Convert SimpleSchema to JSON Schema directly (no Zod needed). * All SimpleSchema fields are strings; optional fields are indicated by a trailing '?'. */ export declare function simpleSchemaToJsonSchema(simple: SimpleSchema): JsonSchema; /** * Create a parser/validator for a SimpleSchema. * Checks that required string fields are present and all values are strings. */ export declare function createSimpleSchemaParser(simple: SimpleSchema): (data: unknown) => Record; /** * Resolve a ZodType or SimpleSchema into a ResolvedSchema. * - ZodType path: uses requireZod().toJSONSchema() + schema.parse() (user has Zod) * - SimpleSchema path: uses simpleSchemaToJsonSchema + createSimpleSchemaParser (no Zod) */ export declare function resolveSchema(schema: ZodType | SimpleSchema): ResolvedSchema; /** * Configuration options (all fields optional for user-facing API) */ export interface TooledPromptConfig { /** LLM API endpoint URL */ apiUrl?: string; /** Model name to use */ modelName?: string; /** API key for authentication */ apiKey?: string; /** Maximum iterations in tool loop */ maxIterations?: number; /** Temperature for generation */ temperature?: number; /** Enable streaming output */ stream?: boolean; /** Request timeout in milliseconds */ timeout?: number; /** When true, suppresses default console output. Custom event handlers still fire. */ silent?: boolean; /** When true, streams full thinking content. When false (default), shows only [Thinking] ... label. */ showThinking?: boolean; /** Provider to use for API communication */ provider?: 'openai' | 'ollama' | 'anthropic' | (string & {}); /** Maximum tokens for the response (required by Anthropic, useful for others) */ maxTokens?: number; /** System prompt: plain string or callback with tagged template for tool refs and images */ systemPrompt?: string | SystemPromptBuilder; /** Maximum length for tool result strings. When set, results exceeding this length are truncated. No limit by default. */ maxToolResultLength?: number; /** Tools to include in every prompt execution. setConfig replaces factory tools; per-call tools are concatenated. */ tools?: ToolFunction[]; /** Per-chunk deadline for streaming responses. Resets on every chunk; if no chunk arrives within this window the stream aborts. Defaults to 30000ms. */ streamChunkTimeoutMs?: number; /** * User-supplied AbortSignal. When fired during a call, the in-flight fetch * is aborted, any open response body is cancelled, and the executor throws * `DOMException('Aborted', 'AbortError')`. Distinct from `timeout`, which * throws `Error('Request timeout after Xms')`. */ signal?: AbortSignal; } /** * Resolved configuration (all fields have values after merging defaults) */ export interface ResolvedTooledPromptConfig { /** LLM API endpoint URL */ apiUrl: string; /** Model name to use */ modelName: string; /** API key for authentication */ apiKey: string | undefined; /** Maximum iterations in tool loop */ maxIterations: number | undefined; /** Temperature for generation */ temperature: number | undefined; /** Enable streaming output */ stream: boolean; /** Request timeout in milliseconds */ timeout: number; /** When true, suppresses default console output. Custom event handlers still fire. */ silent: boolean; /** When true, streams full thinking content. When false (default), shows only [Thinking] ... label. */ showThinking: boolean; /** Provider to use for API communication */ provider: 'openai' | 'ollama' | 'anthropic' | (string & {}); /** Maximum tokens for the response */ maxTokens: number | undefined; /** System prompt */ systemPrompt: string | SystemPromptBuilder | undefined; /** Maximum length for tool result strings. When set, results exceeding this length are truncated. */ maxToolResultLength: number | undefined; /** Per-chunk deadline for streaming responses (ms). Undefined uses the provider default (30000ms). */ streamChunkTimeoutMs: number | undefined; /** User-supplied AbortSignal for hard cancellation. Optional. */ signal: AbortSignal | undefined; } /** * Result from executing a prompt (without schema) */ export interface ExecutionResult { /** Whether execution completed successfully */ success: boolean; /** Final message from the LLM */ message?: string; /** Error message if failed */ error?: string; } /** * Tagged template function for creating prompts. * Used for both `prompt` and `next` (conversation continuation). */ export type PromptTaggedTemplate = ((strings: TemplateStringsArray, ...values: unknown[]) => PromptExecutor) & { /** Sentinel value — use in template to capture structured output via a store tool */ readonly return: object; /** Create a messages sentinel to inject conversation history */ readonly messages: (messages: HistoryMessage[]) => MessagesSentinel; }; export type { Usage }; /** * Token usage breakdown for a prompt result. * - `call`: tokens used in this specific prompt/next invocation (including all tool-loop iterations) * - `cumulative`: total tokens across the entire conversation chain (prompt + all next calls) */ export interface PromptUsage { call: Usage; cumulative: Usage; } /** * Wrapper for prompt execution results. * * @example * ```ts * const r1 = await prompt`Summarize: ${text}`(); * console.log(r1.usage?.call.totalTokens); // tokens for this call * console.log(r1.usage?.cumulative.totalTokens); // same as call for first prompt * * const r2 = await r1.next`Now extract entities`(); * console.log(r2.usage?.cumulative.totalTokens); // total across both calls * ``` */ export interface PromptResult { data?: T; /** Token usage for this call and cumulative across the conversation chain */ usage?: PromptUsage; /** Continue the conversation with a follow-up prompt, preserving history and tools */ next: PromptTaggedTemplate; } /** * Prompt executor - callable function returned by prompt`` * (Defined here to avoid circular imports between factory and prompt) */ export interface PromptExecutor { /** Execute without schema - returns string message */ (config?: TooledPromptConfig): Promise>; /** Execute with Zod schema - returns typed, validated data */ (schema: ZodType, config?: TooledPromptConfig): Promise>; /** Execute with SimpleSchema - returns object with string fields */ (schema: T, config?: TooledPromptConfig): Promise>; } /** * A tooled-prompt instance with its own configuration */ export interface TooledPromptInstance { /** Tagged template for creating prompts, with `.return` sentinel and `.messages()` for history injection */ prompt: PromptTaggedTemplate; /** Tool wrapper function */ tool: typeof import('./tool.js').tool; /** Update the instance configuration */ setConfig: (config: TooledPromptConfig) => void; /** Subscribe to an event */ on(event: K, handler: TooledPromptEvents[K]): void; /** Unsubscribe from an event */ off(event: K, handler: TooledPromptEvents[K]): void; } /** * A single content part in a multi-part user message (text or image) */ export type ContentPart = { type: 'text'; text: string; } | { type: 'image_url'; image_url: { url: string; }; }; /** * Prompt content: plain string when no images, content array when images are present */ export type PromptContent = string | ContentPart[]; /** * Result of processing a system prompt template */ export interface ProcessedSystemPrompt { content: PromptContent; tools: ToolFunction[]; images: ContentPart[]; } /** * The tagged template function passed to the builder callback */ export type SystemPromptTag = (strings: TemplateStringsArray, ...values: unknown[]) => ProcessedSystemPrompt; /** * Builder callback: receives a tagged template, returns processed result */ export type SystemPromptBuilder = (prompt: SystemPromptTag) => ProcessedSystemPrompt; export type { TooledPromptEvents } from './events.js'; //# sourceMappingURL=types.d.ts.map