@ponythewhite/base-context-agent 1.0.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/LICENSE +23 -0
- package/NOTICE +22 -0
- package/README.md +551 -0
- package/dist/LICENSE +23 -0
- package/dist/NOTICE +22 -0
- package/dist/agent-loop.d.ts +24 -0
- package/dist/agent-loop.d.ts.map +1 -0
- package/dist/agent-loop.js +897 -0
- package/dist/agent-loop.js.map +1 -0
- package/dist/agent.d.ts +144 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +569 -0
- package/dist/agent.js.map +1 -0
- package/dist/build-info.json +14 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/invocation-output.d.ts +30 -0
- package/dist/invocation-output.d.ts.map +1 -0
- package/dist/invocation-output.js +125 -0
- package/dist/invocation-output.js.map +1 -0
- package/dist/proxy.d.ts +59 -0
- package/dist/proxy.d.ts.map +1 -0
- package/dist/proxy.js +268 -0
- package/dist/proxy.js.map +1 -0
- package/dist/types.d.ts +512 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +56 -0
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
import type { AssistantMessage, AssistantMessageEvent, ImageContent, Message, Model, ServiceTier, SimpleStreamOptions, streamSimple, TextContent, Tool, ToolResultMessage } from "@ponythewhite/base-context-ai";
|
|
2
|
+
import type { Static, TSchema } from "typebox";
|
|
3
|
+
/**
|
|
4
|
+
* Stream function used by the agent loop.
|
|
5
|
+
*
|
|
6
|
+
* Contract:
|
|
7
|
+
* - Must not throw or return a rejected promise for request/model/runtime failures.
|
|
8
|
+
* - Must return an AssistantMessageEventStream.
|
|
9
|
+
* - Failures must be encoded in the returned stream via protocol events and a
|
|
10
|
+
* final AssistantMessage with stopReason "error" or "aborted" and errorMessage.
|
|
11
|
+
*/
|
|
12
|
+
export type StreamFn = (...args: Parameters<typeof streamSimple>) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;
|
|
13
|
+
export interface AgentContextProjection {
|
|
14
|
+
messages: AgentMessage[];
|
|
15
|
+
/**
|
|
16
|
+
* Adopt this complete working set in the owning Agent and loop, not only for inference.
|
|
17
|
+
* It must include the current turn and pending tool closure. This is not a last-N tail.
|
|
18
|
+
* Omitted/false preserves the existing inference-only projection behavior.
|
|
19
|
+
*/
|
|
20
|
+
adoptMessages?: boolean;
|
|
21
|
+
streamContext?: unknown;
|
|
22
|
+
release?: () => Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
export type AgentContextBuildResult = void | AgentContextProjection;
|
|
25
|
+
export type AgentOwnedStreamFn = (...args: [...Parameters<StreamFn>, streamContext?: unknown]) => ReturnType<StreamFn>;
|
|
26
|
+
/**
|
|
27
|
+
* Configuration for how tool calls from a single assistant message are executed.
|
|
28
|
+
*
|
|
29
|
+
* - "sequential": each tool call is prepared, executed, and finalized before the next one starts.
|
|
30
|
+
* - "parallel": tool calls are prepared sequentially, then allowed tools execute concurrently.
|
|
31
|
+
* `tool_execution_end` is emitted in tool completion order after each tool is finalized,
|
|
32
|
+
* while tool-result message artifacts are emitted later in assistant source order.
|
|
33
|
+
*/
|
|
34
|
+
export type ToolExecutionMode = "sequential" | "parallel";
|
|
35
|
+
/** A tool-call content block emitted by an assistant message. */
|
|
36
|
+
export type AgentToolCall = Extract<AssistantMessage["content"][number], {
|
|
37
|
+
type: "toolCall";
|
|
38
|
+
}>;
|
|
39
|
+
/**
|
|
40
|
+
* Result returned from `beforeToolCall`.
|
|
41
|
+
*
|
|
42
|
+
* Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.
|
|
43
|
+
* `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.
|
|
44
|
+
*/
|
|
45
|
+
export interface BeforeToolCallResult {
|
|
46
|
+
block?: boolean;
|
|
47
|
+
reason?: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Partial override returned from `afterToolCall`.
|
|
51
|
+
*
|
|
52
|
+
* Merge semantics are field-by-field:
|
|
53
|
+
* - `content`: if provided, replaces the tool result content array in full
|
|
54
|
+
* - `details`: if provided, replaces the tool result details value in full
|
|
55
|
+
* - `isError`: if provided, replaces the tool result error flag
|
|
56
|
+
* - `terminate`: if provided, replaces the early-termination hint
|
|
57
|
+
*
|
|
58
|
+
* Omitted fields keep the original executed tool result values.
|
|
59
|
+
* There is no deep merge for `content` or `details`.
|
|
60
|
+
*/
|
|
61
|
+
export interface AfterToolCallResult {
|
|
62
|
+
content?: (TextContent | ImageContent)[];
|
|
63
|
+
details?: unknown;
|
|
64
|
+
isError?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Hint that the agent should stop after the current tool batch.
|
|
67
|
+
* Early termination only happens when every finalized tool result in the batch sets this to true.
|
|
68
|
+
*/
|
|
69
|
+
terminate?: boolean;
|
|
70
|
+
}
|
|
71
|
+
/** Context passed to `beforeToolCall` after arguments are validated. */
|
|
72
|
+
export interface BeforeToolCallContext {
|
|
73
|
+
/** Assistant message that requested the call. */
|
|
74
|
+
assistantMessage: AssistantMessage;
|
|
75
|
+
/** Raw tool-call block from `assistantMessage.content`. */
|
|
76
|
+
toolCall: AgentToolCall;
|
|
77
|
+
/** Validated arguments for the target tool schema. */
|
|
78
|
+
args: unknown;
|
|
79
|
+
/** Agent context when this call is prepared. */
|
|
80
|
+
context: AgentContext;
|
|
81
|
+
}
|
|
82
|
+
/** Context passed to `afterToolCall`. */
|
|
83
|
+
export interface AfterToolCallContext {
|
|
84
|
+
/** Assistant message that requested the call. */
|
|
85
|
+
assistantMessage: AssistantMessage;
|
|
86
|
+
/** Raw tool-call block from `assistantMessage.content`. */
|
|
87
|
+
toolCall: AgentToolCall;
|
|
88
|
+
/** Validated arguments for the target tool schema. */
|
|
89
|
+
args: unknown;
|
|
90
|
+
/** Executed result before any `afterToolCall` overrides. */
|
|
91
|
+
result: AgentToolResult<any>;
|
|
92
|
+
/** Whether the executed result is currently treated as an error. */
|
|
93
|
+
isError: boolean;
|
|
94
|
+
/** Agent context when this call is finalized. */
|
|
95
|
+
context: AgentContext;
|
|
96
|
+
}
|
|
97
|
+
/** What is known about the actual invocation, independently of middleware result overrides. */
|
|
98
|
+
export type ToolExecutionOutcome = "not_started" | "completed" | "failed" | "outcome_unknown";
|
|
99
|
+
/** Immutable invocation admitted by the execution owner before the tool can run. */
|
|
100
|
+
export interface ToolInvocation {
|
|
101
|
+
readonly executionId: string;
|
|
102
|
+
readonly sourceOrder: number;
|
|
103
|
+
readonly toolCallId: string;
|
|
104
|
+
readonly toolName: string;
|
|
105
|
+
/** Snapshot before argument preparation, validation, or tool middleware. */
|
|
106
|
+
readonly originalInput: unknown;
|
|
107
|
+
/** Arguments reserved for this invocation, not a live middleware object. */
|
|
108
|
+
readonly executedInput: unknown;
|
|
109
|
+
readonly toolExecution: ToolExecutionMode;
|
|
110
|
+
}
|
|
111
|
+
/** @internal Per-invocation owner closure; never serialized or supplied by result metadata. */
|
|
112
|
+
export interface BoundToolExecution {
|
|
113
|
+
run(execute: () => Promise<AgentToolResult<unknown>>): Promise<AgentToolResult<unknown>>;
|
|
114
|
+
finalize(exchange: FinalizedToolExchange, signal?: AbortSignal): void | Promise<void>;
|
|
115
|
+
}
|
|
116
|
+
/** Finalized source evidence; parallel exchanges retain assistant call order via sourceOrder. */
|
|
117
|
+
export interface FinalizedToolExchange extends Omit<ToolInvocation, "executedInput"> {
|
|
118
|
+
/** Snapshot at invocation; absent when execution never started. */
|
|
119
|
+
readonly executedInput?: unknown;
|
|
120
|
+
/** An aborted wait does not establish whether an external effect stopped. */
|
|
121
|
+
readonly executionOutcome: ToolExecutionOutcome;
|
|
122
|
+
readonly cancellationRequested: boolean;
|
|
123
|
+
/** Final middleware result, also used for the tool-result message. */
|
|
124
|
+
readonly result: ToolResultMessage;
|
|
125
|
+
}
|
|
126
|
+
/** Limits on the complete invocation result, not the working context or observer queues. */
|
|
127
|
+
export interface AgentOutputLimits {
|
|
128
|
+
maxMessages: number;
|
|
129
|
+
maxSourceBytes: number;
|
|
130
|
+
}
|
|
131
|
+
export interface AgentOutputRefusal extends AgentOutputLimits {
|
|
132
|
+
kind: "output_limit";
|
|
133
|
+
limit: "messages" | "source_bytes" | "value_encoding";
|
|
134
|
+
}
|
|
135
|
+
export interface AgentOutputPolicy {
|
|
136
|
+
limits: AgentOutputLimits;
|
|
137
|
+
/** Optional native update feed. Its synchronous refresh never revokes an ACK or throws a quota error. */
|
|
138
|
+
bindUpdates?(refresh: (message: AgentMessage) => boolean): () => void;
|
|
139
|
+
/** Close update admission and join the updates already accepted at this terminal boundary. */
|
|
140
|
+
settleUpdates?(): Promise<void>;
|
|
141
|
+
/** Copy one finalized value within the supplied JSON-byte budget; undefined means it does not fit. */
|
|
142
|
+
snapshot(message: AgentMessage, maxSourceBytes: number): {
|
|
143
|
+
message: AgentMessage;
|
|
144
|
+
sourceBytes: number;
|
|
145
|
+
} | undefined;
|
|
146
|
+
}
|
|
147
|
+
/** Context passed to `shouldStopAfterTurn` and both continuation callbacks. */
|
|
148
|
+
export interface ShouldStopAfterTurnContext {
|
|
149
|
+
/** Assistant message that completed the turn. */
|
|
150
|
+
message: AssistantMessage;
|
|
151
|
+
/** Tool-result messages included in the preceding `turn_end` event. */
|
|
152
|
+
toolResults: ToolResultMessage[];
|
|
153
|
+
/** Context after appending the turn's assistant message and tool results. */
|
|
154
|
+
context: AgentContext;
|
|
155
|
+
/** Messages returned by this invocation; prompts include initial prompts, continuations exclude prior context. */
|
|
156
|
+
newMessages: AgentMessage[];
|
|
157
|
+
}
|
|
158
|
+
/** The finalized loop decision, not a guess from the rendered message tail. */
|
|
159
|
+
export interface GetTurnOutcomeContext extends ShouldStopAfterTurnContext {
|
|
160
|
+
hasMoreToolCalls: boolean;
|
|
161
|
+
}
|
|
162
|
+
/** Control before queue polling; proceed keeps the ordinary loop policy. */
|
|
163
|
+
export type AgentTurnOutcome = {
|
|
164
|
+
kind: "proceed" | "finish" | "checkpoint_then_continue" | "cancelled";
|
|
165
|
+
};
|
|
166
|
+
export type GetContinuationMessagesContext = ShouldStopAfterTurnContext;
|
|
167
|
+
/** Runtime control at a natural turn boundary; message payload does not decide whether to restart. */
|
|
168
|
+
export type AgentContinuationOutcome = {
|
|
169
|
+
kind: "continue";
|
|
170
|
+
messages: AgentMessage[];
|
|
171
|
+
} | {
|
|
172
|
+
kind: "finish" | "wait_for_owned_work" | "cancelled";
|
|
173
|
+
};
|
|
174
|
+
export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
175
|
+
/** Opt-in bounded finalized results. Native sinks must join their message_end job. */
|
|
176
|
+
outputPolicy?: AgentOutputPolicy;
|
|
177
|
+
model: Model<any>;
|
|
178
|
+
/** Native owner barrier before transform/convert. Rejection stops context construction. */
|
|
179
|
+
beforeContextBuild?: () => Promise<AgentContextBuildResult>;
|
|
180
|
+
/** Internal state mirror for adopted working sets. Awaited and excluded from provider options. */
|
|
181
|
+
onContextAdopted?: (messages: AgentMessage[]) => void | Promise<void>;
|
|
182
|
+
/** Native owner recovery after an unsent request's projection has been released. */
|
|
183
|
+
recoverRequestPreparation?: (error: unknown, signal?: AbortSignal) => Promise<boolean>;
|
|
184
|
+
/** Retry a settled provider failure within this invocation and its output allowance. */
|
|
185
|
+
recoverProviderFailure?: (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean>;
|
|
186
|
+
/** Copied native owner callback; excluded from configured/provider stream options. */
|
|
187
|
+
ownedStreamFn?: AgentOwnedStreamFn;
|
|
188
|
+
/**
|
|
189
|
+
* Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
|
|
190
|
+
*
|
|
191
|
+
* Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage
|
|
192
|
+
* that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,
|
|
193
|
+
* status messages) should be filtered out.
|
|
194
|
+
*
|
|
195
|
+
* Contract: must not throw or reject. Return a safe fallback value instead.
|
|
196
|
+
* Throwing interrupts the low-level agent loop without producing a normal event sequence.
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* ```typescript
|
|
200
|
+
* convertToLlm: (messages) => messages.flatMap(m => {
|
|
201
|
+
* if (m.role === "custom") {
|
|
202
|
+
* // Convert custom message to user message
|
|
203
|
+
* return [{ role: "user", content: m.content, timestamp: m.timestamp }];
|
|
204
|
+
* }
|
|
205
|
+
* if (m.role === "notification") {
|
|
206
|
+
* // Filter out UI-only messages
|
|
207
|
+
* return [];
|
|
208
|
+
* }
|
|
209
|
+
* // Pass through standard LLM messages
|
|
210
|
+
* return [m];
|
|
211
|
+
* })
|
|
212
|
+
* ```
|
|
213
|
+
*/
|
|
214
|
+
convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
|
|
215
|
+
/**
|
|
216
|
+
* Optional transform applied to the context before `convertToLlm`.
|
|
217
|
+
*
|
|
218
|
+
* Use this for operations that work at the AgentMessage level:
|
|
219
|
+
* - Context window management (pruning old messages)
|
|
220
|
+
* - Injecting context from external sources
|
|
221
|
+
*
|
|
222
|
+
* Contract: must not throw or reject. Return the original messages or another
|
|
223
|
+
* safe fallback value instead.
|
|
224
|
+
*
|
|
225
|
+
* @example
|
|
226
|
+
* ```typescript
|
|
227
|
+
* transformContext: async (messages) => {
|
|
228
|
+
* if (estimateTokens(messages) > MAX_TOKENS) {
|
|
229
|
+
* return pruneOldMessages(messages);
|
|
230
|
+
* }
|
|
231
|
+
* return messages;
|
|
232
|
+
* }
|
|
233
|
+
* ```
|
|
234
|
+
*/
|
|
235
|
+
transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
|
|
236
|
+
/** Resolves the system prompt immediately before each LLM call. */
|
|
237
|
+
getSystemPrompt?: () => string;
|
|
238
|
+
/**
|
|
239
|
+
* Resolves an API key dynamically for each LLM call.
|
|
240
|
+
*
|
|
241
|
+
* Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire
|
|
242
|
+
* during long-running tool execution phases.
|
|
243
|
+
*
|
|
244
|
+
* Contract: must not throw or reject. Return undefined when no key is available.
|
|
245
|
+
*/
|
|
246
|
+
getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
|
|
247
|
+
/**
|
|
248
|
+
* Called after each turn fully completes and `turn_end` has been emitted.
|
|
249
|
+
*
|
|
250
|
+
* If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,
|
|
251
|
+
* without starting another LLM call. The current assistant response and any tool executions finish normally.
|
|
252
|
+
*
|
|
253
|
+
* Use this to request a graceful stop after the current turn, e.g. before context gets too full.
|
|
254
|
+
*
|
|
255
|
+
* Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.
|
|
256
|
+
*/
|
|
257
|
+
shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;
|
|
258
|
+
/** When present, this typed owner replaces shouldStopAfterTurn; it does not replace natural continuation. */
|
|
259
|
+
getTurnOutcome?: (context: GetTurnOutcomeContext, signal?: AbortSignal) => AgentTurnOutcome | Promise<AgentTurnOutcome>;
|
|
260
|
+
/**
|
|
261
|
+
* Called synchronously after a completed turn and before polling work for another turn.
|
|
262
|
+
* Return true to emit `agent_end` without starting another provider call. Work returned by
|
|
263
|
+
* an asynchronous poll owns that boundary; queue owners must suppress stale continuation
|
|
264
|
+
* results if their higher-level stop condition changes while generating them.
|
|
265
|
+
* The hook is never checked before the initial assistant turn.
|
|
266
|
+
*/
|
|
267
|
+
shouldStopBeforeTurn?: () => boolean;
|
|
268
|
+
/**
|
|
269
|
+
* Returns steering messages to inject into the conversation mid-run.
|
|
270
|
+
*
|
|
271
|
+
* Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.
|
|
272
|
+
* If messages are returned, they are added to the context before the next LLM call.
|
|
273
|
+
* Tool calls from the current assistant message are not skipped.
|
|
274
|
+
*
|
|
275
|
+
* Use this for "steering" the agent while it's working.
|
|
276
|
+
*
|
|
277
|
+
* Contract: must not throw or reject. Return [] when no steering messages are available.
|
|
278
|
+
*/
|
|
279
|
+
getSteeringMessages?: () => Promise<AgentMessage[]>;
|
|
280
|
+
/**
|
|
281
|
+
* Returns follow-up messages to process after the agent would otherwise stop.
|
|
282
|
+
*
|
|
283
|
+
* Called when the agent has no more tool calls and no steering messages.
|
|
284
|
+
* If messages are returned, they're added to the context and the agent
|
|
285
|
+
* continues with another turn.
|
|
286
|
+
*
|
|
287
|
+
* Use this for follow-up messages that should wait until the agent finishes.
|
|
288
|
+
*
|
|
289
|
+
* Contract: must not throw or reject. Return [] when no follow-up messages are available.
|
|
290
|
+
*/
|
|
291
|
+
getFollowUpMessages?: () => Promise<AgentMessage[]>;
|
|
292
|
+
/**
|
|
293
|
+
* Returns continuation messages when the agent would otherwise stop.
|
|
294
|
+
*
|
|
295
|
+
* Called after follow-up messages have been polled and none are available.
|
|
296
|
+
* If messages are returned, they're added to the context and the agent
|
|
297
|
+
* continues with another turn.
|
|
298
|
+
*
|
|
299
|
+
* Use this for host-owned continuation policies such as long-running goals.
|
|
300
|
+
* Explicit follow-up messages always take precedence over continuation messages.
|
|
301
|
+
*
|
|
302
|
+
* Contract: must not throw or reject. Return [] when no continuation should run.
|
|
303
|
+
*/
|
|
304
|
+
getContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;
|
|
305
|
+
/**
|
|
306
|
+
* Authoritative runtime continuation control, after steering and explicit follow-ups.
|
|
307
|
+
* When present, only this callback is called; getContinuationMessages is not polled.
|
|
308
|
+
* Only continue restarts this invocation. Waiting leaves future work with its existing owner.
|
|
309
|
+
*/
|
|
310
|
+
getContinuationOutcome?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentContinuationOutcome>;
|
|
311
|
+
/**
|
|
312
|
+
* Tool execution mode. Defaults to `"parallel"`.
|
|
313
|
+
* Parallel mode preflights calls sequentially, executes allowed calls concurrently, emits
|
|
314
|
+
* `tool_execution_end` in completion order, then emits tool-result messages in assistant source order.
|
|
315
|
+
*/
|
|
316
|
+
toolExecution?: ToolExecutionMode;
|
|
317
|
+
/**
|
|
318
|
+
* Awaited before invoking the tool. Rejection prevents execution and stops the loop.
|
|
319
|
+
* The owner records intent here; admission is not proof that an external effect occurred.
|
|
320
|
+
*/
|
|
321
|
+
onToolInvocationStarting?: (invocation: ToolInvocation, signal: AbortSignal | undefined, tool: AgentTool, execute: AgentTool["execute"], assistantMessage?: AssistantMessage) => void | BoundToolExecution | Promise<void> | Promise<BoundToolExecution | undefined>;
|
|
322
|
+
/**
|
|
323
|
+
* Native execution owner, awaited after final middleware and before observer/result events.
|
|
324
|
+
* Persist source evidence here. Rejection stops publication; this is not an observer hook.
|
|
325
|
+
* Cancellation does not skip settlement. The owner must bound its own persistence work.
|
|
326
|
+
*/
|
|
327
|
+
onToolExchangeFinalized?: (exchange: FinalizedToolExchange, signal?: AbortSignal, owner?: BoundToolExecution) => void | Promise<void>;
|
|
328
|
+
/**
|
|
329
|
+
* Called before a tool is executed, after arguments have been validated.
|
|
330
|
+
*
|
|
331
|
+
* Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.
|
|
332
|
+
* The hook receives the agent abort signal and is responsible for honoring it.
|
|
333
|
+
*/
|
|
334
|
+
beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
|
|
335
|
+
/**
|
|
336
|
+
* Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.
|
|
337
|
+
*
|
|
338
|
+
* Return an `AfterToolCallResult` to override parts of the executed tool result:
|
|
339
|
+
* - `content` replaces the full content array
|
|
340
|
+
* - `details` replaces the full details payload
|
|
341
|
+
* - `isError` replaces the error flag
|
|
342
|
+
* - `terminate` replaces the early-termination hint
|
|
343
|
+
*
|
|
344
|
+
* Any omitted fields keep their original values. No deep merge is performed.
|
|
345
|
+
* The hook receives the agent abort signal and is responsible for honoring it.
|
|
346
|
+
*/
|
|
347
|
+
afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Thinking/reasoning level for models that support it.
|
|
351
|
+
* Note: "xhigh" and "max" are only supported by selected model families. Use model
|
|
352
|
+
* thinking-level metadata from @ponythewhite/base-context-ai to detect support for a concrete model.
|
|
353
|
+
*/
|
|
354
|
+
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
355
|
+
/**
|
|
356
|
+
* Extensible interface for custom app messages.
|
|
357
|
+
* Apps can extend via declaration merging:
|
|
358
|
+
*
|
|
359
|
+
* @example
|
|
360
|
+
* ```typescript
|
|
361
|
+
* declare module "@mariozechner/agent" {
|
|
362
|
+
* interface CustomAgentMessages {
|
|
363
|
+
* artifact: ArtifactMessage;
|
|
364
|
+
* notification: NotificationMessage;
|
|
365
|
+
* }
|
|
366
|
+
* }
|
|
367
|
+
* ```
|
|
368
|
+
*/
|
|
369
|
+
export interface CustomAgentMessages {
|
|
370
|
+
}
|
|
371
|
+
export type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];
|
|
372
|
+
/**
|
|
373
|
+
* Public agent state.
|
|
374
|
+
*
|
|
375
|
+
* `tools` and `messages` use accessor properties so implementations can copy
|
|
376
|
+
* assigned arrays before storing them.
|
|
377
|
+
*/
|
|
378
|
+
export interface AgentState {
|
|
379
|
+
/** System prompt sent with each model request. */
|
|
380
|
+
systemPrompt: string;
|
|
381
|
+
/** Model used for future turns. */
|
|
382
|
+
model: Model<any>;
|
|
383
|
+
/** Requested reasoning level for future turns. */
|
|
384
|
+
thinkingLevel: ThinkingLevel;
|
|
385
|
+
/** Requested provider service tier for future turns. */
|
|
386
|
+
serviceTier: ServiceTier;
|
|
387
|
+
/** Available tools. Assigning a new array copies its top-level array. */
|
|
388
|
+
set tools(tools: AgentTool<any>[]);
|
|
389
|
+
get tools(): AgentTool<any>[];
|
|
390
|
+
/** Conversation transcript. Assigning a new array copies its top-level array. */
|
|
391
|
+
set messages(messages: AgentMessage[]);
|
|
392
|
+
get messages(): AgentMessage[];
|
|
393
|
+
/** True while processing a prompt or continuation, including awaited `agent_end` listeners. */
|
|
394
|
+
readonly isStreaming: boolean;
|
|
395
|
+
/** Partial assistant message for the active streamed response, if any. */
|
|
396
|
+
readonly streamingMessage?: AgentMessage;
|
|
397
|
+
/** Tool-call IDs currently executing. */
|
|
398
|
+
readonly pendingToolCalls: ReadonlySet<string>;
|
|
399
|
+
/** Error from the most recent failed or aborted assistant turn, if any. */
|
|
400
|
+
readonly errorMessage?: string;
|
|
401
|
+
}
|
|
402
|
+
/** Final or partial result produced by a tool. */
|
|
403
|
+
export interface AgentToolResult<T> {
|
|
404
|
+
/** Text or image content returned to the model. */
|
|
405
|
+
content: (TextContent | ImageContent)[];
|
|
406
|
+
/** Structured details for logs or UI rendering. */
|
|
407
|
+
details: T;
|
|
408
|
+
/**
|
|
409
|
+
* Hint that the agent should stop after the current tool batch.
|
|
410
|
+
* Early termination only happens when every finalized tool result in the batch sets this to true.
|
|
411
|
+
*/
|
|
412
|
+
terminate?: boolean;
|
|
413
|
+
}
|
|
414
|
+
/** Callback used by tools to publish partial execution updates. */
|
|
415
|
+
export type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;
|
|
416
|
+
/** Tool definition used by the agent runtime. */
|
|
417
|
+
export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {
|
|
418
|
+
/** Human-readable label for UI display. */
|
|
419
|
+
label: string;
|
|
420
|
+
/**
|
|
421
|
+
* Optional compatibility shim for raw tool-call arguments before schema validation.
|
|
422
|
+
* Must return an object that matches `TParameters`.
|
|
423
|
+
*/
|
|
424
|
+
prepareArguments?: (args: unknown) => Static<TParameters>;
|
|
425
|
+
/** Execute the tool call. Throw on failure instead of encoding errors in `content`. */
|
|
426
|
+
execute: (toolCallId: string, params: Static<TParameters>, signal?: AbortSignal, onUpdate?: AgentToolUpdateCallback<TDetails>) => Promise<AgentToolResult<TDetails>>;
|
|
427
|
+
/**
|
|
428
|
+
* Per-tool execution mode override.
|
|
429
|
+
* - "sequential": this tool must execute one at a time with other tool calls.
|
|
430
|
+
* - "parallel": this tool can execute concurrently with other tool calls.
|
|
431
|
+
*
|
|
432
|
+
* If omitted, the default execution mode applies.
|
|
433
|
+
*/
|
|
434
|
+
executionMode?: ToolExecutionMode;
|
|
435
|
+
}
|
|
436
|
+
/** Context snapshot passed to the low-level agent loop and tool hooks. */
|
|
437
|
+
export interface AgentContext {
|
|
438
|
+
/** System prompt included with the request. */
|
|
439
|
+
systemPrompt: string;
|
|
440
|
+
/** Transcript visible to the model. */
|
|
441
|
+
messages: AgentMessage[];
|
|
442
|
+
/** Tools available for this run. */
|
|
443
|
+
tools?: AgentTool<any>[];
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Events emitted by the Agent for UI updates.
|
|
447
|
+
*
|
|
448
|
+
* `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`
|
|
449
|
+
* listeners for that event are still part of run settlement. The agent becomes
|
|
450
|
+
* idle only after those listeners finish.
|
|
451
|
+
*/
|
|
452
|
+
export type AgentEvent =
|
|
453
|
+
/** Starts and ends one agent run; `agent_end` carries all messages produced by that run. */
|
|
454
|
+
{
|
|
455
|
+
type: "agent_start";
|
|
456
|
+
} | {
|
|
457
|
+
type: "agent_end";
|
|
458
|
+
messages: AgentMessage[];
|
|
459
|
+
refusal?: never;
|
|
460
|
+
} | {
|
|
461
|
+
type: "agent_end";
|
|
462
|
+
refusal: AgentOutputRefusal;
|
|
463
|
+
messages?: never;
|
|
464
|
+
}
|
|
465
|
+
/** One assistant response and its resulting tool calls. */
|
|
466
|
+
| {
|
|
467
|
+
type: "turn_start";
|
|
468
|
+
} | {
|
|
469
|
+
type: "turn_end";
|
|
470
|
+
message: AgentMessage;
|
|
471
|
+
toolResults: ToolResultMessage[];
|
|
472
|
+
/** Always populated by native execution; historical observer events may omit it. */
|
|
473
|
+
toolExecution?: ToolExecutionMode;
|
|
474
|
+
/** Settled calls in source order. Absent historical evidence is not reconstructed. */
|
|
475
|
+
exchanges?: readonly FinalizedToolExchange[];
|
|
476
|
+
}
|
|
477
|
+
/** Lifecycle events for user, assistant, and tool-result messages. */
|
|
478
|
+
| {
|
|
479
|
+
type: "message_start";
|
|
480
|
+
message: AgentMessage;
|
|
481
|
+
}
|
|
482
|
+
/** Only emitted for assistant messages during streaming. */
|
|
483
|
+
| {
|
|
484
|
+
type: "message_update";
|
|
485
|
+
message: AgentMessage;
|
|
486
|
+
assistantMessageEvent: AssistantMessageEvent;
|
|
487
|
+
} | {
|
|
488
|
+
type: "message_end";
|
|
489
|
+
message: AgentMessage;
|
|
490
|
+
}
|
|
491
|
+
/** Tool execution events; parallel calls may end in completion rather than source order. */
|
|
492
|
+
| {
|
|
493
|
+
type: "tool_execution_start";
|
|
494
|
+
toolCallId: string;
|
|
495
|
+
toolName: string;
|
|
496
|
+
args: any;
|
|
497
|
+
} | {
|
|
498
|
+
type: "tool_execution_update";
|
|
499
|
+
toolCallId: string;
|
|
500
|
+
toolName: string;
|
|
501
|
+
args: any;
|
|
502
|
+
partialResult: any;
|
|
503
|
+
} | {
|
|
504
|
+
type: "tool_execution_end";
|
|
505
|
+
toolCallId: string;
|
|
506
|
+
toolName: string;
|
|
507
|
+
result: any;
|
|
508
|
+
isError: boolean;
|
|
509
|
+
/** Always populated by native execution; absent for older observer events. */
|
|
510
|
+
exchange?: FinalizedToolExchange;
|
|
511
|
+
};
|
|
512
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,gBAAgB,EAChB,qBAAqB,EACrB,YAAY,EACZ,OA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ent,\n\tTool,\n\tToolResultMessage,\n} from \"@ponythewhite/base-context-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\nexport interface AgentContextProjection {\n\tmessages: AgentMessage[];\n\t/**\n\t * Adopt this complete working set in the owning Agent and loop, not only for inference.\n\t * It must include the current turn and pending tool closure. This is not a last-N tail.\n\t * Omitted/false preserves the existing inference-only projection behavior.\n\t */\n\tadoptMessages?: boolean;\n\tstreamContext?: unknown;\n\trelease?: () => Promise<void>;\n}\n\n// biome-ignore lint/suspicious/noConfusingVoidType: this return contract accepts existing Promise<void> context barriers.\nexport type AgentContextBuildResult = void | AgentContextProjection;\n\nexport type AgentOwnedStreamFn = (...args: [...Parameters<StreamFn>, streamContext?: unknown]) => ReturnType<StreamFn>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A tool-call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall` after arguments are validated. */\nexport interface BeforeToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Agent context when this call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Executed result before any `afterToolCall` overrides. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed result is currently treated as an error. */\n\tisError: boolean;\n\t/** Agent context when this call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** What is known about the actual invocation, independently of middleware result overrides. */\nexport type ToolExecutionOutcome = \"not_started\" | \"completed\" | \"failed\" | \"outcome_unknown\";\n\n/** Immutable invocation admitted by the execution owner before the tool can run. */\nexport interface ToolInvocation {\n\treadonly executionId: string;\n\treadonly sourceOrder: number;\n\treadonly toolCallId: string;\n\treadonly toolName: string;\n\t/** Snapshot before argument preparation, validation, or tool middleware. */\n\treadonly originalInput: unknown;\n\t/** Arguments reserved for this invocation, not a live middleware object. */\n\treadonly executedInput: unknown;\n\treadonly toolExecution: ToolExecutionMode;\n}\n\n/** @internal Per-invocation owner closure; never serialized or supplied by result metadata. */\nexport interface BoundToolExecution {\n\trun(execute: () => Promise<AgentToolResult<unknown>>): Promise<AgentToolResult<unknown>>;\n\tfinalize(exchange: FinalizedToolExchange, signal?: AbortSignal): void | Promise<void>;\n}\n\n/** Finalized source evidence; parallel exchanges retain assistant call order via sourceOrder. */\nexport interface FinalizedToolExchange extends Omit<ToolInvocation, \"executedInput\"> {\n\t/** Snapshot at invocation; absent when execution never started. */\n\treadonly executedInput?: unknown;\n\t/** An aborted wait does not establish whether an external effect stopped. */\n\treadonly executionOutcome: ToolExecutionOutcome;\n\treadonly cancellationRequested: boolean;\n\t/** Final middleware result, also used for the tool-result message. */\n\treadonly result: ToolResultMessage;\n}\n\n/** Limits on the complete invocation result, not the working context or observer queues. */\nexport interface AgentOutputLimits {\n\tmaxMessages: number;\n\tmaxSourceBytes: number;\n}\n\nexport interface AgentOutputRefusal extends AgentOutputLimits {\n\tkind: \"output_limit\";\n\tlimit: \"messages\" | \"source_bytes\" | \"value_encoding\";\n}\n\nexport interface AgentOutputPolicy {\n\tlimits: AgentOutputLimits;\n\t/** Optional native update feed. Its synchronous refresh never revokes an ACK or throws a quota error. */\n\tbindUpdates?(refresh: (message: AgentMessage) => boolean): () => void;\n\t/** Close update admission and join the updates already accepted at this terminal boundary. */\n\tsettleUpdates?(): Promise<void>;\n\t/** Copy one finalized value within the supplied JSON-byte budget; undefined means it does not fit. */\n\tsnapshot(message: AgentMessage, maxSourceBytes: number): { message: AgentMessage; sourceBytes: number } | undefined;\n}\n\n/** Context passed to `shouldStopAfterTurn` and both continuation callbacks. */\nexport interface ShouldStopAfterTurnContext {\n\t/** Assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool-result messages included in the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Context after appending the turn's assistant message and tool results. */\n\tcontext: AgentContext;\n\t/** Messages returned by this invocation; prompts include initial prompts, continuations exclude prior context. */\n\tnewMessages: AgentMessage[];\n}\n\n/** The finalized loop decision, not a guess from the rendered message tail. */\nexport interface GetTurnOutcomeContext extends ShouldStopAfterTurnContext {\n\thasMoreToolCalls: boolean;\n}\n\n/** Control before queue polling; proceed keeps the ordinary loop policy. */\nexport type AgentTurnOutcome = { kind: \"proceed\" | \"finish\" | \"checkpoint_then_continue\" | \"cancelled\" };\n\nexport type GetContinuationMessagesContext = ShouldStopAfterTurnContext;\n\n/** Runtime control at a natural turn boundary; message payload does not decide whether to restart. */\nexport type AgentContinuationOutcome =\n\t| { kind: \"continue\"; messages: AgentMessage[] }\n\t| { kind: \"finish\" | \"wait_for_owned_work\" | \"cancelled\" };\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\t/** Opt-in bounded finalized results. Native sinks must join their message_end job. */\n\toutputPolicy?: AgentOutputPolicy;\n\tmodel: Model<any>;\n\n\t/** Native owner barrier before transform/convert. Rejection stops context construction. */\n\tbeforeContextBuild?: () => Promise<AgentContextBuildResult>;\n\n\t/** Internal state mirror for adopted working sets. Awaited and excluded from provider options. */\n\tonContextAdopted?: (messages: AgentMessage[]) => void | Promise<void>;\n\n\t/** Native owner recovery after an unsent request's projection has been released. */\n\trecoverRequestPreparation?: (error: unknown, signal?: AbortSignal) => Promise<boolean>;\n\n\t/** Retry a settled provider failure within this invocation and its output allowance. */\n\trecoverProviderFailure?: (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean>;\n\n\t/** Copied native owner callback; excluded from configured/provider stream options. */\n\townedStreamFn?: AgentOwnedStreamFn;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/** Resolves the system prompt immediately before each LLM call. */\n\tgetSystemPrompt?: () => string;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/** When present, this typed owner replaces shouldStopAfterTurn; it does not replace natural continuation. */\n\tgetTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\n\t/**\n\t * Called synchronously after a completed turn and before polling work for another turn.\n\t * Return true to emit `agent_end` without starting another provider call. Work returned by\n\t * an asynchronous poll owns that boundary; queue owners must suppress stale continuation\n\t * results if their higher-level stop condition changes while generating them.\n\t * The hook is never checked before the initial assistant turn.\n\t */\n\tshouldStopBeforeTurn?: () => boolean;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns continuation messages when the agent would otherwise stop.\n\t *\n\t * Called after follow-up messages have been polled and none are available.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for host-owned continuation policies such as long-running goals.\n\t * Explicit follow-up messages always take precedence over continuation messages.\n\t *\n\t * Contract: must not throw or reject. Return [] when no continuation should run.\n\t */\n\tgetContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Authoritative runtime continuation control, after steering and explicit follow-ups.\n\t * When present, only this callback is called; getContinuationMessages is not polled.\n\t * Only continue restarts this invocation. Waiting leaves future work with its existing owner.\n\t */\n\tgetContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\n\t/**\n\t * Tool execution mode. Defaults to `\"parallel\"`.\n\t * Parallel mode preflights calls sequentially, executes allowed calls concurrently, emits\n\t * `tool_execution_end` in completion order, then emits tool-result messages in assistant source order.\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Awaited before invoking the tool. Rejection prevents execution and stops the loop.\n\t * The owner records intent here; admission is not proof that an external effect occurred.\n\t */\n\tonToolInvocationStarting?: (\n\t\tinvocation: ToolInvocation,\n\t\tsignal: AbortSignal | undefined,\n\t\ttool: AgentTool,\n\t\texecute: AgentTool[\"execute\"],\n\t\tassistantMessage?: AssistantMessage,\n\t) => void | BoundToolExecution | Promise<void> | Promise<BoundToolExecution | undefined>;\n\n\t/**\n\t * Native execution owner, awaited after final middleware and before observer/result events.\n\t * Persist source evidence here. Rejection stops publication; this is not an observer hook.\n\t * Cancellation does not skip settlement. The owner must bound its own persistence work.\n\t */\n\tonToolExchangeFinalized?: (\n\t\texchange: FinalizedToolExchange,\n\t\tsignal?: AbortSignal,\n\t\towner?: BoundToolExecution,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @ponythewhite/base-context-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {}\n\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Model used for future turns. */\n\tmodel: Model<any>;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/** Requested provider service tier for future turns. */\n\tserviceTier: ServiceTier;\n\t/** Available tools. Assigning a new array copies its top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies its top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/** True while processing a prompt or continuation, including awaited `agent_end` listeners. */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the active streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool-call IDs currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Structured details for logs or UI rendering. */\n\tdetails: T;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Callback used by tools to publish partial execution updates. */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Execute the tool call. Throw on failure instead of encoding errors in `content`. */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed to the low-level agent loop and tool hooks. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t/** Starts and ends one agent run; `agent_end` carries all messages produced by that run. */\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[]; refusal?: never }\n\t| { type: \"agent_end\"; refusal: AgentOutputRefusal; messages?: never }\n\t/** One assistant response and its resulting tool calls. */\n\t| { type: \"turn_start\" }\n\t| {\n\t\t\ttype: \"turn_end\";\n\t\t\tmessage: AgentMessage;\n\t\t\ttoolResults: ToolResultMessage[];\n\t\t\t/** Always populated by native execution; historical observer events may omit it. */\n\t\t\ttoolExecution?: ToolExecutionMode;\n\t\t\t/** Settled calls in source order. Absent historical evidence is not reconstructed. */\n\t\t\texchanges?: readonly FinalizedToolExchange[];\n\t }\n\t/** Lifecycle events for user, assistant, and tool-result messages. */\n\t| { type: \"message_start\"; message: AgentMessage }\n\t/** Only emitted for assistant messages during streaming. */\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t/** Tool execution events; parallel calls may end in completion rather than source order. */\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: any;\n\t\t\tisError: boolean;\n\t\t\t/** Always populated by native execution; absent for older observer events. */\n\t\t\texchange?: FinalizedToolExchange;\n\t };\n"]}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tServiceTier,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@ponythewhite/base-context-ai\";\nimport type { Static, TSchema } from \"typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\nexport interface AgentContextProjection {\n\tmessages: AgentMessage[];\n\t/**\n\t * Adopt this complete working set in the owning Agent and loop, not only for inference.\n\t * It must include the current turn and pending tool closure. This is not a last-N tail.\n\t * Omitted/false preserves the existing inference-only projection behavior.\n\t */\n\tadoptMessages?: boolean;\n\tstreamContext?: unknown;\n\trelease?: () => Promise<void>;\n}\n\n// biome-ignore lint/suspicious/noConfusingVoidType: this return contract accepts existing Promise<void> context barriers.\nexport type AgentContextBuildResult = void | AgentContextProjection;\n\nexport type AgentOwnedStreamFn = (...args: [...Parameters<StreamFn>, streamContext?: unknown]) => ReturnType<StreamFn>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * `tool_execution_end` is emitted in tool completion order after each tool is finalized,\n * while tool-result message artifacts are emitted later in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A tool-call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n * - `terminate`: if provided, replaces the early-termination hint\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Context passed to `beforeToolCall` after arguments are validated. */\nexport interface BeforeToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Agent context when this call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** Assistant message that requested the call. */\n\tassistantMessage: AssistantMessage;\n\t/** Raw tool-call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated arguments for the target tool schema. */\n\targs: unknown;\n\t/** Executed result before any `afterToolCall` overrides. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed result is currently treated as an error. */\n\tisError: boolean;\n\t/** Agent context when this call is finalized. */\n\tcontext: AgentContext;\n}\n\n/** What is known about the actual invocation, independently of middleware result overrides. */\nexport type ToolExecutionOutcome = \"not_started\" | \"completed\" | \"failed\" | \"outcome_unknown\";\n\n/** Immutable invocation admitted by the execution owner before the tool can run. */\nexport interface ToolInvocation {\n\treadonly executionId: string;\n\treadonly sourceOrder: number;\n\treadonly toolCallId: string;\n\treadonly toolName: string;\n\t/** Snapshot before argument preparation, validation, or tool middleware. */\n\treadonly originalInput: unknown;\n\t/** Arguments reserved for this invocation, not a live middleware object. */\n\treadonly executedInput: unknown;\n\treadonly toolExecution: ToolExecutionMode;\n}\n\n/** @internal Per-invocation owner closure; never serialized or supplied by result metadata. */\nexport interface BoundToolExecution {\n\trun(execute: () => Promise<AgentToolResult<unknown>>): Promise<AgentToolResult<unknown>>;\n\tfinalize(exchange: FinalizedToolExchange, signal?: AbortSignal): void | Promise<void>;\n}\n\n/** Finalized source evidence; parallel exchanges retain assistant call order via sourceOrder. */\nexport interface FinalizedToolExchange extends Omit<ToolInvocation, \"executedInput\"> {\n\t/** Snapshot at invocation; absent when execution never started. */\n\treadonly executedInput?: unknown;\n\t/** An aborted wait does not establish whether an external effect stopped. */\n\treadonly executionOutcome: ToolExecutionOutcome;\n\treadonly cancellationRequested: boolean;\n\t/** Final middleware result, also used for the tool-result message. */\n\treadonly result: ToolResultMessage;\n}\n\n/** Limits on the complete invocation result, not the working context or observer queues. */\nexport interface AgentOutputLimits {\n\tmaxMessages: number;\n\tmaxSourceBytes: number;\n}\n\nexport interface AgentOutputRefusal extends AgentOutputLimits {\n\tkind: \"output_limit\";\n\tlimit: \"messages\" | \"source_bytes\" | \"value_encoding\";\n}\n\nexport interface AgentOutputPolicy {\n\tlimits: AgentOutputLimits;\n\t/** Optional native update feed. Its synchronous refresh never revokes an ACK or throws a quota error. */\n\tbindUpdates?(refresh: (message: AgentMessage) => boolean): () => void;\n\t/** Close update admission and join the updates already accepted at this terminal boundary. */\n\tsettleUpdates?(): Promise<void>;\n\t/** Copy one finalized value within the supplied JSON-byte budget; undefined means it does not fit. */\n\tsnapshot(message: AgentMessage, maxSourceBytes: number): { message: AgentMessage; sourceBytes: number } | undefined;\n}\n\n/** Context passed to `shouldStopAfterTurn` and both continuation callbacks. */\nexport interface ShouldStopAfterTurnContext {\n\t/** Assistant message that completed the turn. */\n\tmessage: AssistantMessage;\n\t/** Tool-result messages included in the preceding `turn_end` event. */\n\ttoolResults: ToolResultMessage[];\n\t/** Context after appending the turn's assistant message and tool results. */\n\tcontext: AgentContext;\n\t/** Messages returned by this invocation; prompts include initial prompts, continuations exclude prior context. */\n\tnewMessages: AgentMessage[];\n}\n\n/** The finalized loop decision, not a guess from the rendered message tail. */\nexport interface GetTurnOutcomeContext extends ShouldStopAfterTurnContext {\n\thasMoreToolCalls: boolean;\n}\n\n/** Control before queue polling; proceed keeps the ordinary loop policy. */\nexport type AgentTurnOutcome = { kind: \"proceed\" | \"finish\" | \"checkpoint_then_continue\" | \"cancelled\" };\n\nexport type GetContinuationMessagesContext = ShouldStopAfterTurnContext;\n\n/** Runtime control at a natural turn boundary; message payload does not decide whether to restart. */\nexport type AgentContinuationOutcome =\n\t| { kind: \"continue\"; messages: AgentMessage[] }\n\t| { kind: \"finish\" | \"wait_for_owned_work\" | \"cancelled\" };\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\t/** Opt-in bounded finalized results. Native sinks must join their message_end job. */\n\toutputPolicy?: AgentOutputPolicy;\n\tmodel: Model<any>;\n\n\t/** Native owner barrier before transform/convert. Rejection stops context construction. */\n\tbeforeContextBuild?: () => Promise<AgentContextBuildResult>;\n\n\t/** Internal state mirror for adopted working sets. Awaited and excluded from provider options. */\n\tonContextAdopted?: (messages: AgentMessage[]) => void | Promise<void>;\n\n\t/** Native owner recovery after an unsent request's projection has been released. */\n\trecoverRequestPreparation?: (error: unknown, signal?: AbortSignal) => Promise<boolean>;\n\n\t/** Retry a settled provider failure within this invocation and its output allowance. */\n\trecoverProviderFailure?: (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean>;\n\n\t/** Copied native owner callback; excluded from configured/provider stream options. */\n\townedStreamFn?: AgentOwnedStreamFn;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/** Resolves the system prompt immediately before each LLM call. */\n\tgetSystemPrompt?: () => string;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Called after each turn fully completes and `turn_end` has been emitted.\n\t *\n\t * If it returns true, the loop emits `agent_end` and exits before polling steering or follow-up queues,\n\t * without starting another LLM call. The current assistant response and any tool executions finish normally.\n\t *\n\t * Use this to request a graceful stop after the current turn, e.g. before context gets too full.\n\t *\n\t * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t */\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;\n\n\t/** When present, this typed owner replaces shouldStopAfterTurn; it does not replace natural continuation. */\n\tgetTurnOutcome?: (\n\t\tcontext: GetTurnOutcomeContext,\n\t\tsignal?: AbortSignal,\n\t) => AgentTurnOutcome | Promise<AgentTurnOutcome>;\n\n\t/**\n\t * Called synchronously after a completed turn and before polling work for another turn.\n\t * Return true to emit `agent_end` without starting another provider call. Work returned by\n\t * an asynchronous poll owns that boundary; queue owners must suppress stale continuation\n\t * results if their higher-level stop condition changes while generating them.\n\t * The hook is never checked before the initial assistant turn.\n\t */\n\tshouldStopBeforeTurn?: () => boolean;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls, unless `shouldStopAfterTurn` exits first.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns continuation messages when the agent would otherwise stop.\n\t *\n\t * Called after follow-up messages have been polled and none are available.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for host-owned continuation policies such as long-running goals.\n\t * Explicit follow-up messages always take precedence over continuation messages.\n\t *\n\t * Contract: must not throw or reject. Return [] when no continuation should run.\n\t */\n\tgetContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Authoritative runtime continuation control, after steering and explicit follow-ups.\n\t * When present, only this callback is called; getContinuationMessages is not polled.\n\t * Only continue restarts this invocation. Waiting leaves future work with its existing owner.\n\t */\n\tgetContinuationOutcome?: (\n\t\tcontext: GetContinuationMessagesContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentContinuationOutcome>;\n\n\t/**\n\t * Tool execution mode. Defaults to `\"parallel\"`.\n\t * Parallel mode preflights calls sequentially, executes allowed calls concurrently, emits\n\t * `tool_execution_end` in completion order, then emits tool-result messages in assistant source order.\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Awaited before invoking the tool. Rejection prevents execution and stops the loop.\n\t * The owner records intent here; admission is not proof that an external effect occurred.\n\t */\n\tonToolInvocationStarting?: (\n\t\tinvocation: ToolInvocation,\n\t\tsignal: AbortSignal | undefined,\n\t\ttool: AgentTool,\n\t\texecute: AgentTool[\"execute\"],\n\t\tassistantMessage?: AssistantMessage,\n\t) => void | BoundToolExecution | Promise<void> | Promise<BoundToolExecution | undefined>;\n\n\t/**\n\t * Native execution owner, awaited after final middleware and before observer/result events.\n\t * Persist source evidence here. Rejection stops publication; this is not an observer hook.\n\t * Cancellation does not skip settlement. The owner must bound its own persistence work.\n\t */\n\tonToolExchangeFinalized?: (\n\t\texchange: FinalizedToolExchange,\n\t\tsignal?: AbortSignal,\n\t\towner?: BoundToolExecution,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before `tool_execution_end` and tool-result message events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t * - `terminate` replaces the early-termination hint\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from @ponythewhite/base-context-ai to detect support for a concrete model.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@mariozechner/agent\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {}\n\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Public agent state.\n *\n * `tools` and `messages` use accessor properties so implementations can copy\n * assigned arrays before storing them.\n */\nexport interface AgentState {\n\t/** System prompt sent with each model request. */\n\tsystemPrompt: string;\n\t/** Model used for future turns. */\n\tmodel: Model<any>;\n\t/** Requested reasoning level for future turns. */\n\tthinkingLevel: ThinkingLevel;\n\t/** Requested provider service tier for future turns. */\n\tserviceTier: ServiceTier;\n\t/** Available tools. Assigning a new array copies its top-level array. */\n\tset tools(tools: AgentTool<any>[]);\n\tget tools(): AgentTool<any>[];\n\t/** Conversation transcript. Assigning a new array copies its top-level array. */\n\tset messages(messages: AgentMessage[]);\n\tget messages(): AgentMessage[];\n\t/** True while processing a prompt or continuation, including awaited `agent_end` listeners. */\n\treadonly isStreaming: boolean;\n\t/** Partial assistant message for the active streamed response, if any. */\n\treadonly streamingMessage?: AgentMessage;\n\t/** Tool-call IDs currently executing. */\n\treadonly pendingToolCalls: ReadonlySet<string>;\n\t/** Error from the most recent failed or aborted assistant turn, if any. */\n\treadonly errorMessage?: string;\n}\n\n/** Final or partial result produced by a tool. */\nexport interface AgentToolResult<T> {\n\t/** Text or image content returned to the model. */\n\tcontent: (TextContent | ImageContent)[];\n\t/** Structured details for logs or UI rendering. */\n\tdetails: T;\n\t/**\n\t * Hint that the agent should stop after the current tool batch.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Callback used by tools to publish partial execution updates. */\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n/** Tool definition used by the agent runtime. */\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t/** Human-readable label for UI display. */\n\tlabel: string;\n\t/**\n\t * Optional compatibility shim for raw tool-call arguments before schema validation.\n\t * Must return an object that matches `TParameters`.\n\t */\n\tprepareArguments?: (args: unknown) => Static<TParameters>;\n\t/** Execute the tool call. Throw on failure instead of encoding errors in `content`. */\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n}\n\n/** Context snapshot passed to the low-level agent loop and tool hooks. */\nexport interface AgentContext {\n\t/** System prompt included with the request. */\n\tsystemPrompt: string;\n\t/** Transcript visible to the model. */\n\tmessages: AgentMessage[];\n\t/** Tools available for this run. */\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n *\n * `agent_end` is the last event emitted for a run, but awaited `Agent.subscribe()`\n * listeners for that event are still part of run settlement. The agent becomes\n * idle only after those listeners finish.\n */\nexport type AgentEvent =\n\t/** Starts and ends one agent run; `agent_end` carries all messages produced by that run. */\n\t| { type: \"agent_start\" }\n\t| { type: \"agent_end\"; messages: AgentMessage[]; refusal?: never }\n\t| { type: \"agent_end\"; refusal: AgentOutputRefusal; messages?: never }\n\t/** One assistant response and its resulting tool calls. */\n\t| { type: \"turn_start\" }\n\t| {\n\t\t\ttype: \"turn_end\";\n\t\t\tmessage: AgentMessage;\n\t\t\ttoolResults: ToolResultMessage[];\n\t\t\t/** Always populated by native execution; historical observer events may omit it. */\n\t\t\ttoolExecution?: ToolExecutionMode;\n\t\t\t/** Settled calls in source order. Absent historical evidence is not reconstructed. */\n\t\t\texchanges?: readonly FinalizedToolExchange[];\n\t }\n\t/** Lifecycle events for user, assistant, and tool-result messages. */\n\t| { type: \"message_start\"; message: AgentMessage }\n\t/** Only emitted for assistant messages during streaming. */\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t/** Tool execution events; parallel calls may end in completion rather than source order. */\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: any;\n\t\t\tisError: boolean;\n\t\t\t/** Always populated by native execution; absent for older observer events. */\n\t\t\texchange?: FinalizedToolExchange;\n\t };\n"]}
|