@agentier/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/loop.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type { AgentConfig, AgentResult, RunOptions } from './types';
2
+ /**
3
+ * Executes the core agent reasoning loop: repeatedly calls the model, executes
4
+ * any requested tools, appends results to the conversation, and repeats until
5
+ * the model responds without tool calls or a termination condition is met.
6
+ *
7
+ * This is the main engine behind {@link Agent.run}. It handles:
8
+ * - Building the initial message history (from memory, options, or scratch)
9
+ * - System prompt injection (with optional structured output instructions)
10
+ * - Model calls (streaming or non-streaming)
11
+ * - Parallel tool execution with validation
12
+ * - Middleware dispatch for all actions
13
+ * - Token budgeting, iteration limits, and timeouts
14
+ * - Structured output parsing with retry
15
+ * - Memory persistence
16
+ *
17
+ * @typeParam T - The expected output type. Defaults to `string`.
18
+ * @param config - The agent configuration.
19
+ * @param prompt - The user prompt to process.
20
+ * @param options - Optional per-run overrides and callbacks.
21
+ * @returns A promise resolving to the complete {@link AgentResult}.
22
+ * @throws {AgentError} When a model call fails, output parsing fails, or other unrecoverable errors occur.
23
+ */
24
+ export declare function runAgentLoop<T = string>(config: AgentConfig, prompt: string, options?: RunOptions<T>): Promise<AgentResult<T>>;
@@ -0,0 +1,45 @@
1
+ import type { AgentAction, AgentActionType, Middleware } from './types';
2
+ /**
3
+ * Creates a new {@link AgentAction} with the given type, payload, and optional metadata.
4
+ *
5
+ * The `timestamp` is automatically set to the current time (`Date.now()`).
6
+ *
7
+ * @typeParam T - The specific action type being created.
8
+ * @param type - The action type discriminator.
9
+ * @param payload - The type-safe payload for this action.
10
+ * @param metadata - Optional arbitrary metadata to attach to the action.
11
+ * @returns A new {@link AgentAction} instance.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const action = createAction('tool_call', {
16
+ * id: 'call_1',
17
+ * name: 'search',
18
+ * arguments: { query: 'hello' },
19
+ * })
20
+ * ```
21
+ */
22
+ export declare function createAction<T extends AgentActionType>(type: T, payload: AgentAction<T>['payload'], metadata?: Record<string, unknown>): AgentAction<T>;
23
+ /**
24
+ * Executes an action through a chain of middleware functions using the "onion" pattern.
25
+ *
26
+ * Each middleware receives the action and a `next()` function. Calling `next()`
27
+ * passes control to the subsequent middleware, or to the core `execute` handler
28
+ * if all middleware has been traversed. Middleware can inspect, modify, or
29
+ * short-circuit the action before or after calling `next()`.
30
+ *
31
+ * @param middlewares - The ordered list of middleware functions to run.
32
+ * @param action - The action to process through the chain.
33
+ * @param execute - The core handler invoked after all middleware has run.
34
+ * @returns A promise resolving to the final (possibly modified) action.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * const result = await runMiddlewareChain(
39
+ * [loggingMiddleware, metricsMiddleware],
40
+ * action,
41
+ * async () => coreHandler(action),
42
+ * )
43
+ * ```
44
+ */
45
+ export declare function runMiddlewareChain(middlewares: Middleware[], action: AgentAction, execute: () => Promise<AgentAction>): Promise<AgentAction>;
package/dist/tool.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ import { type ZodType } from 'zod';
2
+ import type { Tool, JsonSchema, ToolJsonSchema } from './types';
3
+ /**
4
+ * Creates a fully configured {@link Tool} with resolved JSON Schema metadata.
5
+ *
6
+ * This is the recommended way to define tools. It accepts either a Zod schema
7
+ * or a plain JSON Schema for parameter validation, and eagerly resolves the
8
+ * internal JSON Schema representation used when communicating with model providers.
9
+ *
10
+ * @typeParam TParams - The validated parameter type for the tool.
11
+ * @typeParam TResult - The return type of the tool's execute function.
12
+ * @param config - The tool configuration object.
13
+ * @param config.name - A unique name identifying the tool.
14
+ * @param config.description - A human-readable description of what the tool does.
15
+ * @param config.parameters - A Zod schema or plain JSON Schema defining accepted parameters.
16
+ * @param config.execute - The async function that performs the tool's work.
17
+ * @returns A fully configured {@link Tool} instance ready to be passed to an agent.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { z } from 'zod'
22
+ * import { defineTool } from '@agenti/core'
23
+ *
24
+ * const weatherTool = defineTool({
25
+ * name: 'get_weather',
26
+ * description: 'Get current weather for a city',
27
+ * parameters: z.object({ city: z.string() }),
28
+ * execute: async ({ city }) => {
29
+ * const data = await fetchWeather(city)
30
+ * return `${data.temp}°C, ${data.condition}`
31
+ * },
32
+ * })
33
+ * ```
34
+ */
35
+ export declare function defineTool<TParams, TResult = unknown>(config: {
36
+ name: string;
37
+ description: string;
38
+ parameters: ZodType<TParams> | JsonSchema;
39
+ execute: (params: TParams, context: {
40
+ callId: string;
41
+ signal: AbortSignal;
42
+ messages: readonly import('./types').Message[];
43
+ }) => Promise<TResult>;
44
+ }): Tool<TParams, TResult>;
45
+ /**
46
+ * Converts a {@link Tool} into its JSON Schema wire format ({@link ToolJsonSchema})
47
+ * suitable for sending to a model provider.
48
+ *
49
+ * If the tool's internal JSON Schema has not been resolved yet (i.e. the tool was
50
+ * not created via {@link defineTool}), this function resolves it lazily.
51
+ *
52
+ * @param tool - The tool to convert.
53
+ * @returns The tool's name, description, and parameters as a {@link ToolJsonSchema}.
54
+ */
55
+ export declare function toolToJsonSchema(tool: Tool): ToolJsonSchema;
56
+ /**
57
+ * Validates tool call arguments against the tool's parameter schema.
58
+ *
59
+ * When the tool uses a Zod schema, full parsing and validation is performed.
60
+ * When the tool uses a plain JSON Schema, the arguments are returned as-is
61
+ * (validation is assumed to be handled by the model or externally).
62
+ *
63
+ * @param tool - The tool whose schema to validate against.
64
+ * @param args - The raw arguments from the model's tool call.
65
+ * @returns The validated (and possibly transformed) arguments.
66
+ * @throws {ZodError} If the tool uses a Zod schema and validation fails.
67
+ */
68
+ export declare function validateToolArgs(tool: Tool, args: Record<string, unknown>): unknown;
@@ -0,0 +1,185 @@
1
+ import type { ZodType } from 'zod';
2
+ import type { Message } from './message';
3
+ import type { ModelProvider } from './provider';
4
+ import type { Tool } from './tool';
5
+ import type { Middleware } from './middleware';
6
+ import type { MemoryProvider } from './memory';
7
+ /**
8
+ * Configuration options for creating an agent via {@link createAgent}.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const config: AgentConfig = {
13
+ * model: 'gpt-4o',
14
+ * provider: openaiProvider,
15
+ * systemPrompt: 'You are a helpful assistant.',
16
+ * tools: [searchTool, calculatorTool],
17
+ * maxIterations: 15,
18
+ * }
19
+ * ```
20
+ */
21
+ export interface AgentConfig {
22
+ /** The model identifier to use for completions (e.g. `'gpt-4o'`, `'claude-sonnet-4-20250514'`). */
23
+ model: string;
24
+ /** The model provider implementation that handles API communication. */
25
+ provider: ModelProvider;
26
+ /** An optional system prompt prepended to the conversation to guide the model's behavior. */
27
+ systemPrompt?: string;
28
+ /** Tools available for the agent to invoke during its reasoning loop. */
29
+ tools?: Tool[];
30
+ /** Middleware functions that intercept and can transform actions in the agent loop. */
31
+ middleware?: Middleware[];
32
+ /** A memory provider for persisting conversation history across sessions. */
33
+ memory?: MemoryProvider;
34
+ /** Maximum number of model call iterations before the loop terminates. Defaults to `10`. */
35
+ maxIterations?: number;
36
+ /** Maximum total token usage before the loop terminates. Defaults to `Infinity`. */
37
+ maxTokens?: number;
38
+ /** Maximum wall-clock time in milliseconds before the loop is aborted. Defaults to `60000`. */
39
+ timeout?: number;
40
+ /** Default sampling temperature for model calls. Can be overridden per-run. */
41
+ temperature?: number;
42
+ /** Default nucleus sampling parameter for model calls. */
43
+ topP?: number;
44
+ /** Default maximum output tokens for model responses. Can be overridden per-run. */
45
+ maxOutputTokens?: number;
46
+ }
47
+ /**
48
+ * A record of a single tool call that was executed during an agent run,
49
+ * including its arguments, result, and timing.
50
+ */
51
+ export interface ExecutedToolCall {
52
+ /** The unique identifier of the tool call. */
53
+ id: string;
54
+ /** The name of the tool that was called. */
55
+ name: string;
56
+ /** The arguments that were passed to the tool. */
57
+ arguments: Record<string, unknown>;
58
+ /** The value returned by the tool (or an error message string if execution failed). */
59
+ result: unknown;
60
+ /** How long the tool execution took, in milliseconds. */
61
+ duration: number;
62
+ }
63
+ /**
64
+ * Aggregated token usage statistics for an agent run.
65
+ */
66
+ export interface UsageStats {
67
+ /** Total tokens consumed (input + output). */
68
+ totalTokens: number;
69
+ /** Total input (prompt) tokens across all model calls. */
70
+ inputTokens: number;
71
+ /** Total output (completion) tokens across all model calls. */
72
+ outputTokens: number;
73
+ /** The number of model call iterations performed. */
74
+ iterations: number;
75
+ /** An optional estimated monetary cost for the run. */
76
+ estimatedCost?: number;
77
+ }
78
+ /**
79
+ * The result returned after an agent completes a run.
80
+ *
81
+ * @typeParam T - The type of the output. Defaults to `string`, but when an
82
+ * `outputSchema` is provided it will be the validated type.
83
+ */
84
+ export interface AgentResult<T = string> {
85
+ /** The final output produced by the agent. */
86
+ output: T;
87
+ /** The complete conversation history including all messages exchanged during the run. */
88
+ messages: Message[];
89
+ /** All tool calls that were executed during the run. */
90
+ toolCalls: ExecutedToolCall[];
91
+ /** Aggregated token usage statistics. */
92
+ usage: UsageStats;
93
+ /** Total wall-clock duration of the run in milliseconds. */
94
+ duration: number;
95
+ }
96
+ /**
97
+ * Options that can be passed to {@link Agent.run} to customize a single run.
98
+ *
99
+ * @typeParam T - The expected output type. When `outputSchema` is provided,
100
+ * the agent will parse and validate the model's response into this type.
101
+ */
102
+ export interface RunOptions<T = string> {
103
+ /** Initial messages to prepend to the conversation (overrides memory loading). */
104
+ messages?: Message[];
105
+ /**
106
+ * A Zod schema for structured output. When provided, the agent instructs the model
107
+ * to respond with JSON conforming to this schema and validates the result.
108
+ */
109
+ outputSchema?: ZodType<T>;
110
+ /** Sampling temperature override for this run. */
111
+ temperature?: number;
112
+ /** Maximum output tokens override for this run. */
113
+ maxOutputTokens?: number;
114
+ /**
115
+ * Callback invoked for each text token as it streams from the model.
116
+ *
117
+ * @param token - The text chunk received.
118
+ */
119
+ onToken?: (token: string) => void;
120
+ /**
121
+ * Callback invoked when the model requests a tool call.
122
+ *
123
+ * @param name - The name of the tool being called.
124
+ * @param args - The arguments passed to the tool.
125
+ */
126
+ onToolCall?: (name: string, args: Record<string, unknown>) => void;
127
+ /**
128
+ * Callback invoked when a tool returns a result.
129
+ *
130
+ * @param name - The name of the tool that returned.
131
+ * @param result - The value produced by the tool.
132
+ */
133
+ onToolResult?: (name: string, result: unknown) => void;
134
+ /**
135
+ * Callback invoked when the agent run completes successfully.
136
+ *
137
+ * @param result - The final agent result.
138
+ */
139
+ onComplete?: (result: AgentResult<T>) => void;
140
+ /**
141
+ * Callback invoked when the agent run encounters an error.
142
+ *
143
+ * @param error - The error that occurred.
144
+ */
145
+ onError?: (error: Error) => void;
146
+ /** Maximum number of model call iterations for this run. Overrides {@link AgentConfig.maxIterations}. */
147
+ maxIterations?: number;
148
+ /** Maximum total token budget for this run. Overrides {@link AgentConfig.maxTokens}. */
149
+ maxTokens?: number;
150
+ /** Maximum wall-clock time in milliseconds for this run. Overrides {@link AgentConfig.timeout}. */
151
+ timeout?: number;
152
+ /** An external abort signal to cancel the run. */
153
+ signal?: AbortSignal;
154
+ /** The session ID used for memory persistence. Defaults to `'default'`. */
155
+ sessionId?: string;
156
+ /** When `true`, skips saving the conversation to memory after the run completes. */
157
+ skipMemorySave?: boolean;
158
+ }
159
+ /**
160
+ * The public interface of an agent created by {@link createAgent}.
161
+ */
162
+ export interface Agent {
163
+ /**
164
+ * Runs the agent with the given prompt and returns the result.
165
+ *
166
+ * @typeParam T - The output type. Defaults to `string`; when `outputSchema` is
167
+ * provided in options, it matches the schema's output type.
168
+ * @param prompt - The user message to send to the agent.
169
+ * @param options - Optional run-time configuration and callbacks.
170
+ * @returns A promise resolving to the agent's result including output, messages, and usage stats.
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * const result = await agent.run('What is the weather in Berlin?')
175
+ * console.log(result.output)
176
+ * ```
177
+ */
178
+ run<T = string>(prompt: string, options?: RunOptions<T>): Promise<AgentResult<T>>;
179
+ /**
180
+ * Returns a frozen (read-only) copy of the agent's configuration.
181
+ *
182
+ * @returns The agent's configuration object.
183
+ */
184
+ getConfig(): Readonly<AgentConfig>;
185
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Re-exports all public types from the `@agenti/core` type system.
3
+ *
4
+ * @module types
5
+ */
6
+ export type { Role, ToolCall, Message } from './message';
7
+ export type { ToolContext, JsonSchema, ToolJsonSchema, Tool } from './tool';
8
+ export type { ChatParams, ModelResponse, StreamEvent, ModelProvider } from './provider';
9
+ export type { AgentActionType, ActionPayloadMap, AgentAction, Middleware } from './middleware';
10
+ export type { MemoryProvider } from './memory';
11
+ export type { AgentConfig, ExecutedToolCall, UsageStats, AgentResult, RunOptions, Agent, } from './agent';
@@ -0,0 +1,41 @@
1
+ import type { Message } from './message';
2
+ /**
3
+ * Interface for persisting and retrieving conversation history across sessions.
4
+ *
5
+ * Implementations can store messages in-memory, on disk, in a database, or
6
+ * any other backing store. The agent uses this to maintain context between
7
+ * separate `run()` invocations.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const memory: MemoryProvider = {
12
+ * async load(sessionId) { return db.getMessages(sessionId) },
13
+ * async save(sessionId, messages) { await db.setMessages(sessionId, messages) },
14
+ * async clear(sessionId) { await db.deleteMessages(sessionId) },
15
+ * }
16
+ * ```
17
+ */
18
+ export interface MemoryProvider {
19
+ /**
20
+ * Loads the stored conversation history for the given session.
21
+ *
22
+ * @param sessionId - The unique identifier for the conversation session.
23
+ * @returns A promise resolving to the array of messages in this session.
24
+ */
25
+ load(sessionId: string): Promise<Message[]>;
26
+ /**
27
+ * Saves the conversation history for the given session, replacing any previously stored messages.
28
+ *
29
+ * @param sessionId - The unique identifier for the conversation session.
30
+ * @param messages - The complete message history to persist.
31
+ * @returns A promise that resolves when saving is complete.
32
+ */
33
+ save(sessionId: string, messages: Message[]): Promise<void>;
34
+ /**
35
+ * Clears all stored messages for the given session.
36
+ *
37
+ * @param sessionId - The unique identifier for the conversation session.
38
+ * @returns A promise that resolves when the session data has been deleted.
39
+ */
40
+ clear(sessionId: string): Promise<void>;
41
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Represents the role of a participant in a conversation.
3
+ *
4
+ * - `'system'` - System-level instructions that guide the model's behavior.
5
+ * - `'user'` - A message from the end user.
6
+ * - `'assistant'` - A response generated by the model.
7
+ * - `'tool'` - The result of a tool invocation.
8
+ */
9
+ export type Role = 'system' | 'user' | 'assistant' | 'tool';
10
+ /**
11
+ * Represents a tool invocation requested by the model.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const call: ToolCall = {
16
+ * id: 'call_abc123',
17
+ * name: 'get_weather',
18
+ * arguments: { city: 'Berlin' },
19
+ * }
20
+ * ```
21
+ */
22
+ export interface ToolCall {
23
+ /** Unique identifier for this tool call, used to match results back to the request. */
24
+ id: string;
25
+ /** The name of the tool to invoke. */
26
+ name: string;
27
+ /** The parsed arguments to pass to the tool's execute function. */
28
+ arguments: Record<string, unknown>;
29
+ }
30
+ /**
31
+ * A single message in the conversation history exchanged between participants.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * const userMsg: Message = { role: 'user', content: 'Hello!' }
36
+ * const toolResult: Message = {
37
+ * role: 'tool',
38
+ * content: '{"temp": 22}',
39
+ * toolCallId: 'call_abc123',
40
+ * }
41
+ * ```
42
+ */
43
+ export interface Message {
44
+ /** The role of the message author. */
45
+ role: Role;
46
+ /** The text content of the message, or `null` when the assistant response consists solely of tool calls. */
47
+ content: string | null;
48
+ /** Tool calls requested by the assistant in this message, if any. */
49
+ toolCalls?: ToolCall[];
50
+ /** The ID of the tool call this message is a response to (only for `role: 'tool'`). */
51
+ toolCallId?: string;
52
+ /** An optional display name for the message author. */
53
+ name?: string;
54
+ }
@@ -0,0 +1,123 @@
1
+ import type { AgentConfig, AgentResult } from './agent';
2
+ import type { Message } from './message';
3
+ import type { ModelResponse, ToolJsonSchema } from '../types';
4
+ /**
5
+ * The discriminated set of action types that flow through the middleware pipeline.
6
+ *
7
+ * - `'loop_start'` - The agent loop has begun processing a prompt.
8
+ * - `'loop_end'` - The agent loop has finished (successfully or due to a limit).
9
+ * - `'model_call'` - A request is about to be sent to the model provider.
10
+ * - `'model_response'` - A response has been received from the model provider.
11
+ * - `'tool_call'` - A tool is about to be invoked.
12
+ * - `'tool_result'` - A tool has returned a result.
13
+ * - `'error'` - An error occurred during model or tool execution.
14
+ */
15
+ export type AgentActionType = 'loop_start' | 'loop_end' | 'model_call' | 'model_response' | 'tool_call' | 'tool_result' | 'error';
16
+ /**
17
+ * Maps each {@link AgentActionType} to its corresponding payload shape.
18
+ * Used to provide type-safe payloads on {@link AgentAction}.
19
+ */
20
+ export interface ActionPayloadMap {
21
+ /** Payload for the `loop_start` action. */
22
+ loop_start: {
23
+ /** The user prompt that initiated the loop. */
24
+ prompt: string;
25
+ /** The agent configuration in effect. */
26
+ config: AgentConfig;
27
+ };
28
+ /** Payload for the `loop_end` action. */
29
+ loop_end: {
30
+ /** The final result produced by the agent. */
31
+ result: AgentResult;
32
+ /** The reason the loop ended. */
33
+ reason: 'complete' | 'max_iterations' | 'max_tokens' | 'timeout' | 'aborted';
34
+ };
35
+ /** Payload for the `model_call` action. */
36
+ model_call: {
37
+ /** The messages being sent to the model. */
38
+ messages: Message[];
39
+ /** The tool definitions being sent to the model. */
40
+ tools: ToolJsonSchema[];
41
+ /** The model identifier being called. */
42
+ model: string;
43
+ };
44
+ /** Payload for the `model_response` action. */
45
+ model_response: {
46
+ /** The model's response. */
47
+ response: ModelResponse;
48
+ /** Token usage for this call. */
49
+ usage: {
50
+ inputTokens: number;
51
+ outputTokens: number;
52
+ };
53
+ };
54
+ /** Payload for the `tool_call` action. */
55
+ tool_call: {
56
+ /** The tool call ID. */
57
+ id: string;
58
+ /** The name of the tool being called. */
59
+ name: string;
60
+ /** The arguments passed to the tool. */
61
+ arguments: Record<string, unknown>;
62
+ };
63
+ /** Payload for the `tool_result` action. */
64
+ tool_result: {
65
+ /** The tool call ID this result corresponds to. */
66
+ id: string;
67
+ /** The name of the tool that was called. */
68
+ name: string;
69
+ /** The value returned by the tool. */
70
+ result: unknown;
71
+ /** How long the tool execution took, in milliseconds. */
72
+ duration: number;
73
+ };
74
+ /** Payload for the `error` action. */
75
+ error: {
76
+ /** Where the error originated. */
77
+ source: 'model' | 'tool' | 'internal';
78
+ /** The error that occurred. */
79
+ error: Error;
80
+ /** The name of the tool, if the error originated from a tool. */
81
+ name?: string;
82
+ /** Whether the operation that caused this error can be retried. */
83
+ retryable: boolean;
84
+ };
85
+ }
86
+ /**
87
+ * A typed action object that flows through the middleware pipeline.
88
+ * Each action carries a discriminated type, its payload, a timestamp, and arbitrary metadata.
89
+ *
90
+ * @typeParam T - The specific {@link AgentActionType} this action represents.
91
+ */
92
+ export interface AgentAction<T extends AgentActionType = AgentActionType> {
93
+ /** The action type discriminator. */
94
+ type: T;
95
+ /** The type-safe payload associated with this action. */
96
+ payload: T extends keyof ActionPayloadMap ? ActionPayloadMap[T] : never;
97
+ /** Unix timestamp (milliseconds) when the action was created. */
98
+ timestamp: number;
99
+ /** Arbitrary metadata attached to the action by middleware or the agent. */
100
+ metadata: Record<string, unknown>;
101
+ }
102
+ /**
103
+ * A middleware function that intercepts actions flowing through the agent loop.
104
+ *
105
+ * Middleware can inspect, modify, or short-circuit actions. It follows the
106
+ * standard "onion" pattern: call `next()` to pass control to the next
107
+ * middleware (or the core executor), and optionally transform the result.
108
+ *
109
+ * @param action - The action being processed.
110
+ * @param next - Calls the next middleware in the chain (or the core handler).
111
+ * @returns A promise resolving to the (possibly modified) action.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * const loggingMiddleware: Middleware = async (action, next) => {
116
+ * console.log('Before:', action.type)
117
+ * const result = await next()
118
+ * console.log('After:', result.type)
119
+ * return result
120
+ * }
121
+ * ```
122
+ */
123
+ export type Middleware = (action: AgentAction, next: () => Promise<AgentAction>) => Promise<AgentAction>;
@@ -0,0 +1,114 @@
1
+ import type { Message, ToolCall } from './message';
2
+ import type { ToolJsonSchema } from './tool';
3
+ /**
4
+ * Parameters for a chat completion request sent to a model provider.
5
+ */
6
+ export interface ChatParams {
7
+ /** The model identifier (e.g. `'gpt-4o'`, `'claude-sonnet-4-20250514'`). */
8
+ model: string;
9
+ /** The conversation messages to send to the model. */
10
+ messages: Message[];
11
+ /** Tool definitions available for the model to call. When omitted, no tools are provided. */
12
+ tools?: ToolJsonSchema[];
13
+ /** Sampling temperature (0-2). Lower values are more deterministic, higher values more creative. */
14
+ temperature?: number;
15
+ /** Nucleus sampling parameter. Only tokens with cumulative probability up to `topP` are considered. */
16
+ topP?: number;
17
+ /** Maximum number of tokens the model may generate in its response. */
18
+ maxOutputTokens?: number;
19
+ /**
20
+ * Constrains the model output to conform to a JSON schema.
21
+ * When set, the model will produce structured JSON output.
22
+ */
23
+ responseFormat?: {
24
+ /** The format type. Currently only `'json_schema'` is supported. */
25
+ type: 'json_schema';
26
+ /** The JSON Schema the model output must conform to. */
27
+ schema: Record<string, unknown>;
28
+ };
29
+ /** An abort signal that cancels the in-flight request when triggered. */
30
+ signal?: AbortSignal;
31
+ }
32
+ /**
33
+ * The complete response returned by a model provider after a non-streaming chat call.
34
+ */
35
+ export interface ModelResponse {
36
+ /** The text content of the model's response, or `null` if the response is tool-calls only. */
37
+ content: string | null;
38
+ /** Any tool calls the model requested. Empty array when the model did not invoke tools. */
39
+ toolCalls: ToolCall[];
40
+ /** Token usage statistics for this request. */
41
+ usage: {
42
+ /** The number of tokens in the input (prompt). */
43
+ inputTokens: number;
44
+ /** The number of tokens in the output (completion). */
45
+ outputTokens: number;
46
+ };
47
+ /** The raw, provider-specific response object for advanced use cases. */
48
+ raw?: unknown;
49
+ }
50
+ /**
51
+ * Events emitted during a streaming model response.
52
+ *
53
+ * - `token` - A chunk of generated text.
54
+ * - `tool_call_start` - The model has begun a tool call.
55
+ * - `tool_call_delta` - An incremental chunk of tool call arguments.
56
+ * - `tool_call_end` - The tool call is complete with fully assembled arguments.
57
+ * - `done` - The stream has finished; includes the full {@link ModelResponse}.
58
+ * - `error` - An error occurred during streaming.
59
+ */
60
+ export type StreamEvent = {
61
+ type: 'token';
62
+ text: string;
63
+ } | {
64
+ type: 'tool_call_start';
65
+ id: string;
66
+ name: string;
67
+ } | {
68
+ type: 'tool_call_delta';
69
+ id: string;
70
+ argumentsDelta: string;
71
+ } | {
72
+ type: 'tool_call_end';
73
+ id: string;
74
+ call: ToolCall;
75
+ } | {
76
+ type: 'done';
77
+ response: ModelResponse;
78
+ } | {
79
+ type: 'error';
80
+ error: Error;
81
+ };
82
+ /**
83
+ * Interface that model providers must implement to be used with the agent.
84
+ *
85
+ * A provider adapts a specific LLM API (OpenAI, Anthropic, etc.) into the
86
+ * common interface the agent loop expects.
87
+ *
88
+ * @example
89
+ * ```ts
90
+ * const provider: ModelProvider = {
91
+ * name: 'openai',
92
+ * async chat(params) { ... },
93
+ * async *stream(params) { ... },
94
+ * }
95
+ * ```
96
+ */
97
+ export interface ModelProvider {
98
+ /** A human-readable name identifying this provider (e.g. `'openai'`, `'anthropic'`). */
99
+ readonly name: string;
100
+ /**
101
+ * Sends a chat completion request and returns the full response.
102
+ *
103
+ * @param params - The chat request parameters including model, messages, and tools.
104
+ * @returns A promise resolving to the model's complete response.
105
+ */
106
+ chat(params: ChatParams): Promise<ModelResponse>;
107
+ /**
108
+ * Sends a chat completion request and returns a stream of incremental events.
109
+ *
110
+ * @param params - The chat request parameters including model, messages, and tools.
111
+ * @returns An async iterable of {@link StreamEvent} objects.
112
+ */
113
+ stream(params: ChatParams): AsyncIterable<StreamEvent>;
114
+ }