@linxiraos/pi-agent-core 1.1.9 → 1.1.10

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.
@@ -0,0 +1,815 @@
1
+ import type { ApiKey, AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream, Context, Effort, ImageContent, Message, Model, ServiceTier, SimpleStreamOptions, Static, streamSimple, TextContent, Tool, ToolCallProviderMetadata, ToolChoice, ToolResultMessage, ToolResultProviderMetadata, TSchema } from "@linxiraos/pi-ai";
2
+ import type { Dialect } from "@linxiraos/pi-ai/dialect";
3
+ import type { HarmonyAuditEvent } from "@linxiraos/pi-ai/utils/harmony-leak";
4
+ import type { AppendOnlyContextManager } from "./append-only-context.js";
5
+ import type { AgentRunCoverage, AgentRunSummary } from "./run-collector.js";
6
+ import type { AgentTelemetryConfig } from "./telemetry.js";
7
+ /** Stream function - can return sync or Promise for async config lookup */
8
+ export type StreamFn = (...args: Parameters<typeof streamSimple>) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>;
9
+ /** Called once an aside has been inserted into the agent's live context. */
10
+ export declare const ASIDE_MESSAGE_COMMIT: unique symbol;
11
+ /** Called when an aside was drained but the agent loop ended before inserting it. */
12
+ export declare const ASIDE_MESSAGE_DISCARD: unique symbol;
13
+ export type CommittableAsideMessage = AgentMessage & {
14
+ [ASIDE_MESSAGE_COMMIT]?: () => void;
15
+ [ASIDE_MESSAGE_DISCARD]?: (error: Error) => void;
16
+ };
17
+ /**
18
+ * An aside entry: a ready {@link AgentMessage}, or a sync thunk evaluated at
19
+ * injection time that returns the message to inject or `null` to skip it. Thunks
20
+ * let the producer make the final inject-or-drop decision against current state
21
+ * (e.g. dropping late diagnostics a newer edit superseded).
22
+ */
23
+ export type AsideMessage = CommittableAsideMessage | (() => CommittableAsideMessage | null);
24
+ export interface AgentTurnEndContext {
25
+ /** Assistant/user message that just completed this turn boundary. */
26
+ message: AgentMessage;
27
+ /** Tool results produced by this turn, already paired with `message` in the live context. */
28
+ toolResults: ToolResultMessage[];
29
+ /** True when the current tool-loop batch is continuing without yielding to post-turn steering. */
30
+ willContinue: boolean;
31
+ }
32
+ export interface AgentPreModelCallStop {
33
+ /** Stop the agent loop before sending the next provider request. */
34
+ stop: true;
35
+ /** Optional owner-facing reason, logged by the loop when it stops. */
36
+ reason?: string;
37
+ }
38
+ export type AgentPreModelCallResult = AgentPreModelCallStop | undefined;
39
+ /**
40
+ * A pre-model-call gate. Return {@link AgentPreModelCallStop} to refuse the
41
+ * request, or nothing to proceed; the signal aborts with the run.
42
+ */
43
+ export type AgentBeforeModelCall = (context: Context, signal?: AbortSignal) => AgentPreModelCallResult | void | Promise<AgentPreModelCallResult | void>;
44
+ /**
45
+ * A soft tool requirement: the host wants `toolName` called before the loop
46
+ * runs other tools or yields, but WITHOUT paying the forced-`toolChoice` cost
47
+ * up front (changing `tool_choice` invalidates the provider message cache).
48
+ * Returned from {@link AgentLoopConfig.getToolChoice} in place of a hard
49
+ * {@link ToolChoice}: the loop injects `reminder` once when a new `id` becomes
50
+ * active, runs with `toolChoice` unchanged, and escalates to a one-turn forced
51
+ * choice only if the model fails to call `toolName`. Auto-clears when the host
52
+ * stops returning it or `toolName` is no longer an active tool.
53
+ */
54
+ export interface SoftToolRequirement {
55
+ /** Discriminates a soft requirement from a hard {@link ToolChoice}. */
56
+ soft: true;
57
+ /**
58
+ * Stable id of the *current* requirement. The loop injects `reminder` when
59
+ * this id first becomes active and again whenever it changes (e.g. one
60
+ * stacked preview resolves and the next becomes the head), but never
61
+ * re-injects for an unchanged id across turns.
62
+ */
63
+ id: string;
64
+ /** Tool that must be called before the loop runs other tools or yields. */
65
+ toolName: string;
66
+ /**
67
+ * Per-call compliance check: a turn satisfies the requirement only when every
68
+ * tool call passes. Defaults to `name === toolName`. Lets a host demand a
69
+ * specific invocation shape (e.g. `write` targeting a virtual device path)
70
+ * instead of any call to `toolName`. Escalation still forces `toolName`.
71
+ */
72
+ satisfies?(toolCall: {
73
+ name: string;
74
+ arguments?: Record<string, unknown>;
75
+ }): boolean;
76
+ /** Host-owned reminder messages, injected once per `id` activation. */
77
+ reminder: AgentMessage[];
78
+ }
79
+ /**
80
+ * A per-turn tool-choice directive: either a hard provider {@link ToolChoice}
81
+ * (applied verbatim) or a {@link SoftToolRequirement} (remind-then-escalate).
82
+ */
83
+ export type ToolChoiceDirective = ToolChoice | SoftToolRequirement;
84
+ /** Mutable soft-requirement lifecycle retained across stopped agent runs. */
85
+ export interface SoftToolRequirementState {
86
+ id?: string;
87
+ forcedToolChoice?: ToolChoice;
88
+ escalations: number;
89
+ }
90
+ /** True when a {@link ToolChoiceDirective} is a soft requirement, not a hard choice. */
91
+ export declare function isSoftToolRequirement(directive: ToolChoiceDirective | undefined): directive is SoftToolRequirement;
92
+ /**
93
+ * Source category for a queued steering interrupt observed without consuming the queue.
94
+ * Distinguishes real-user, agent-authored, system/advisor, and unknown steering.
95
+ */
96
+ export type SteeringInterruptSource = "user" | "agent" | "system" | "unknown";
97
+ /** Non-consuming summary of whether queued steering should interrupt a tool batch. */
98
+ export interface SteeringQueueState {
99
+ /** True when at least one steering message is queued. */
100
+ queued: boolean;
101
+ /** Best-effort origin used only to word synthetic skipped-tool results. */
102
+ source?: SteeringInterruptSource;
103
+ }
104
+ /**
105
+ * Configuration for the agent loop.
106
+ */
107
+ export interface AgentLoopConfig extends SimpleStreamOptions {
108
+ model: Model;
109
+ /**
110
+ * When to interrupt tool execution for steering messages.
111
+ * - "immediate" = check after each tool call (default)
112
+ * - "wait" = defer steering until the current turn completes
113
+ */
114
+ interruptMode?: "immediate" | "wait";
115
+ /**
116
+ * Optional session identifier forwarded to LLM providers.
117
+ * Used by providers that support session-based caching (e.g., OpenAI Codex).
118
+ */
119
+ sessionId?: string;
120
+ /** Absolute wall-clock deadline in Unix epoch milliseconds. */
121
+ deadline?: number;
122
+ /**
123
+ * Optional resolver called per LLM request to produce request metadata.
124
+ * When set, the agent loop evaluates it **after** `getApiKey` resolves the
125
+ * session-sticky credential, ensuring the metadata's `account_uuid` reflects
126
+ * the credential actually used for the request (not the credential that was
127
+ * current when `AgentLoopConfig` was first constructed). Overrides the static
128
+ * `metadata` field when present.
129
+ */
130
+ metadataResolver?: (provider: string) => Record<string, unknown> | undefined;
131
+ /**
132
+ * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
133
+ *
134
+ * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage
135
+ * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,
136
+ * status messages) should be filtered out.
137
+ *
138
+ * @example
139
+ * ```typescript
140
+ * convertToLlm: (messages) => messages.flatMap(m => {
141
+ * if (m.role === "custom") {
142
+ * // Convert custom message to user message
143
+ * return [{ role: "user", content: m.content, timestamp: m.timestamp }];
144
+ * }
145
+ * if (m.role === "notification") {
146
+ * // Filter out UI-only messages
147
+ * return [];
148
+ * }
149
+ * // Pass through standard LLM messages
150
+ * return [m];
151
+ * })
152
+ * ```
153
+ */
154
+ convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
155
+ /**
156
+ * Optional transform applied to the context before `convertToLlm`.
157
+ *
158
+ * Use this for operations that work at the AgentMessage level:
159
+ * - Context window management (pruning old messages)
160
+ * - Injecting context from external sources
161
+ *
162
+ * @example
163
+ * ```typescript
164
+ * transformContext: async (messages) => {
165
+ * if (agent.tokenizer.countMessages(messages) > MAX_TOKENS) {
166
+ * return pruneOldMessages(messages);
167
+ * }
168
+ * return messages;
169
+ * }
170
+ * ```
171
+ */
172
+ transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
173
+ /**
174
+ * Optional transform applied to the final provider context after conversion,
175
+ * normalization, and append-only context handling, but before telemetry capture
176
+ * and provider send.
177
+ */
178
+ transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
179
+ /**
180
+ * Resolves the API key or resolver for the current model before each LLM call.
181
+ *
182
+ * Returning an ApiKeyResolver lets the stream retry policy refresh or rotate
183
+ * the model-scoped credential after auth/usage-limit errors.
184
+ */
185
+ getApiKey?: (model: Model) => Promise<ApiKey | undefined> | ApiKey | undefined;
186
+ /**
187
+ * Returns steering messages to inject into the conversation mid-run.
188
+ *
189
+ * Called at injection boundaries only (loop start and after a tool batch
190
+ * fully settles), so dequeued messages are immediately injected. The
191
+ * mid-batch interrupt poll uses {@link hasSteeringMessages} instead and
192
+ * never consumes the queue.
193
+ */
194
+ getSteeringMessages?: (signal?: AbortSignal) => Promise<AgentMessage[]>;
195
+ /**
196
+ * Peeks whether steering messages are queued, without consuming them.
197
+ *
198
+ * Polled while a tool batch runs (unless interruptMode is "wait") to decide
199
+ * whether to abort in-flight and skip not-yet-started *interruptible* waits;
200
+ * every other already-emitted call still executes and the message injects
201
+ * at the batch boundary. The queue keeps
202
+ * owning its messages until the loop reaches the next injection boundary and
203
+ * dequeues via {@link getSteeringMessages} — so callers can still cancel or
204
+ * restore queued messages while in-flight tools settle, and an external
205
+ * abort in that window leaves the queue intact for a post-abort continue.
206
+ *
207
+ * Returning `true` is treated as user-originated steering for compatibility.
208
+ * Return a {@link SteeringQueueState} when the queue can distinguish system
209
+ * advisories from real user messages.
210
+ *
211
+ * When omitted, steering never interrupts a running tool batch; queued
212
+ * messages are still delivered at the next injection boundary.
213
+ */
214
+ hasSteeringMessages?: () => boolean | SteeringQueueState | Promise<boolean | SteeringQueueState>;
215
+ /**
216
+ * Wakes the in-flight tool interrupt watcher when a steering message is queued.
217
+ * The callback must not consume the queue; the loop still calls
218
+ * {@link hasSteeringMessages} before aborting and injects through
219
+ * {@link getSteeringMessages}.
220
+ */
221
+ waitForSteeringMessages?: (signal?: AbortSignal) => Promise<void>;
222
+ /**
223
+ * Peeks whether IRC messages should interrupt an interruptible waiting tool.
224
+ *
225
+ * Uses the same delivery rules as steering: the poll is non-consuming, only
226
+ * runs for interruptible tools, and is ignored when interruptMode is "wait".
227
+ * The host owns message injection at the next boundary.
228
+ */
229
+ hasIrcInterrupts?: () => boolean | Promise<boolean>;
230
+ /**
231
+ * Returns follow-up messages to process after the agent would otherwise stop.
232
+ *
233
+ * Called when the agent has no more tool calls and no steering messages.
234
+ * If messages are returned, they're added to the context and the agent
235
+ * continues with another turn.
236
+ */
237
+ getFollowUpMessages?: (signal?: AbortSignal) => Promise<AgentMessage[]>;
238
+ /**
239
+ * Returns non-interrupting "aside" messages to inject at a step boundary.
240
+ *
241
+ * Polled after each tool batch (before the next LLM call) AND at the yield
242
+ * check. Unlike steering, these NEVER abort in-flight tools — they are passive
243
+ * notifications (e.g. background-job completions, late LSP diagnostics) that
244
+ * should reach the model between requests without waiting for the agent to
245
+ * fully stop. Returned messages are appended to the context with normal
246
+ * message events and keep the loop running so the model can react.
247
+ */
248
+ getAsideMessages?: () => Promise<AsideMessage[]>;
249
+ /**
250
+ * Hook fired right before the loop would exit.
251
+ *
252
+ * Called when the agent has no more tool calls and no steering messages,
253
+ * immediately before polling follow-up messages.
254
+ */
255
+ onBeforeYield?: () => Promise<void> | void;
256
+ /**
257
+ * Provides tool execution context, resolved per tool call.
258
+ * Use for late-bound UI or session state access.
259
+ */
260
+ getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
261
+ /**
262
+ * Refreshes prompt/tool context from live session state before each model call.
263
+ * Use this when tool availability or the system prompt can change mid-turn.
264
+ *
265
+ * Runs after pending messages are folded in and before provider conversion.
266
+ * Mutate the agent context here; use `beforeModelCall` to inspect the
267
+ * provider-bound context.
268
+ */
269
+ syncContextBeforeModelCall?: (context: AgentContext, signal?: AbortSignal) => void | Promise<void>;
270
+ /**
271
+ * Asked after the complete provider context has been built, including
272
+ * message conversion, provider transforms, normalized tools, and owned
273
+ * dialect prompt injection. Returning {@link AgentPreModelCallStop} ends
274
+ * the stream without emitting `turn_start`, so no turn is left open and no
275
+ * request is billed. Return nothing to proceed. The signal aborts when
276
+ * the run is canceled or its deadline expires.
277
+ */
278
+ beforeModelCall?: AgentBeforeModelCall;
279
+ /**
280
+ * Optional transform applied to tool call arguments before execution.
281
+ * Use for deobfuscating secrets or rewriting arguments.
282
+ */
283
+ transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
284
+ /**
285
+ * Resolve a tool call whose name matched no advertised tool (including
286
+ * `customWireName` aliases). Lets hosts route calls to tools they expose
287
+ * through side transports (e.g. `xd://` device mounts) instead of failing
288
+ * with "Tool not found". Returning `undefined` keeps the failure.
289
+ */
290
+ resolveFallbackTool?: (name: string) => AgentTool<any> | undefined;
291
+ /**
292
+ * Enable intent tracing for tool calls.
293
+ * When enabled, the harness injects a `string` field into tool schemas sent to the model,
294
+ * then strips from arguments before executing tools.
295
+ */
296
+ intentTracing?: boolean;
297
+ /**
298
+ * Strip tool descriptions (top-level + nested schema annotations) from the
299
+ * provider-bound tool specs. Use when the full catalog is rendered into the
300
+ * system prompt instead, so descriptions are not duplicated on the wire.
301
+ */
302
+ pruneToolDescriptions?: boolean;
303
+ /**
304
+ * Owned tool calling dialect.
305
+ *
306
+ * Undefined keeps provider-native tool calling. A dialect value sends no
307
+ * native `tools`, forces `toolChoice` off, appends that dialect's tool catalog
308
+ * instructions, re-encodes prior tool calls/results as text, and parses the
309
+ * model's text output back into canonical `toolCall` blocks.
310
+ */
311
+ dialect?: Dialect;
312
+ /**
313
+ * When owned (in-band) tool calling is active and the model starts
314
+ * fabricating a tool result inside its own turn, control how the loop reacts:
315
+ * - `true` (default): abort the provider request immediately so it stops
316
+ * generating the hallucinated continuation (cheaper, lower latency).
317
+ * - `false`: let the request finish and silently discard everything past the
318
+ * fabrication boundary (keeps the connection alive but pays for the tokens
319
+ * the model spends on the discarded tail).
320
+ * Only meaningful when {@link dialect} (or `PI_DIALECT`) selects an
321
+ * owned dialect; native tool calling never fabricates results in text.
322
+ */
323
+ abortOnFabricatedToolResult?: boolean;
324
+ /**
325
+ * Append-only context mode — stabilizes system prompt + tool spec bytes
326
+ * across turns so provider prefix caches hit at maximum rate.
327
+ *
328
+ * When set, the loop reads messages from the append-only log (stable
329
+ * byte prefix) and caches system prompt + tools. Tools exclude per-turn
330
+ * `i` intent fields.
331
+ */
332
+ appendOnlyContext?: AppendOnlyContextManager;
333
+ /**
334
+ * Inspect assistant streaming events before they are published to the outer agent event stream.
335
+ * Callers may abort synchronously to stop consuming buffered provider events.
336
+ */
337
+ onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
338
+ /**
339
+ * Called when GPT-5 Harmony protocol leakage is detected and mitigated.
340
+ */
341
+ onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
342
+ /**
343
+ * Dynamic tool-choice directive, resolved once per turn. Returns a hard
344
+ * {@link ToolChoice} (applied verbatim, overriding the static `toolChoice`),
345
+ * a {@link SoftToolRequirement} (the loop reminds-then-escalates instead of
346
+ * forcing `tool_choice` immediately, so a model that complies with the
347
+ * reminder pays no message-cache invalidation), or `undefined` to fall back
348
+ * to the static `toolChoice`.
349
+ */
350
+ getToolChoice?: () => ToolChoiceDirective | undefined;
351
+ /**
352
+ * Soft-requirement lifecycle retained by the host when a pre-model-call
353
+ * gate stops a run before its pending reminder or escalation is served.
354
+ */
355
+ softToolRequirementState?: SoftToolRequirementState;
356
+ /**
357
+ * Notifies the host that the pre-model-call gate stopped the run after a
358
+ * hard tool choice was obtained from {@link getToolChoice} but before it
359
+ * was served, so the host can retain it for the next admitted request.
360
+ */
361
+ onToolChoiceRejected?: () => void;
362
+ /**
363
+ * Dynamic reasoning effort override, resolved per LLM call.
364
+ * When set and returns a value, overrides the static `reasoning` captured
365
+ * at run-loop start. Use this so mid-run thinking-level changes apply on
366
+ * the next model call instead of waiting for the next prompt.
367
+ */
368
+ getReasoning?: () => Effort | undefined;
369
+ /**
370
+ * Dynamic model override, resolved once per LLM call. When set, each
371
+ * provider call re-reads the model (like {@link getReasoning}) so mid-run
372
+ * model switches — context promotion, retry fallback — apply on the next
373
+ * call instead of the run finishing on the stale model captured at
374
+ * run-loop start. Falls back to the static {@link model} when unset.
375
+ */
376
+ getModel?: () => Model;
377
+ /**
378
+ * Dynamic reasoning-disable override, resolved per LLM call. When set,
379
+ * its return value overrides the static `disableReasoning` from
380
+ * `SimpleStreamOptions` for that request. Pair with `getReasoning` so
381
+ * mid-run transitions into and out of the explicit `off` state propagate
382
+ * to the next provider call.
383
+ */
384
+ getDisableReasoning?: () => boolean | undefined;
385
+ /**
386
+ * Per-call effective service-tier resolver. Unlike {@link getReasoning},
387
+ * this is *authoritative*: when set, its return value (including
388
+ * `undefined`) fully replaces the static `serviceTier` for the request and
389
+ * its telemetry. The resolver receives the model being requested so the
390
+ * caller can scope the tier per provider/model without mutating the shared
391
+ * session `serviceTier` (e.g. opting a Fireworks model into the Priority
392
+ * serving path while leaving the OpenAI/Anthropic tier untouched).
393
+ */
394
+ getServiceTier?: (model: Model) => ServiceTier | undefined;
395
+ /**
396
+ * Per-call working-directory resolver, read once per LLM call. When set, its
397
+ * return value overrides the static {@link SimpleStreamOptions.cwd} for the
398
+ * request (falling back to that static `cwd` when it returns `undefined`).
399
+ * Lets the host reflect a session move (`/move`, which updates the working
400
+ * directory without reconstructing the loop config) into provider options —
401
+ * e.g. GitLab Duo Agent namespace/project discovery keys off this cwd's git
402
+ * remote, so a stale value would strand discovery on the original repo.
403
+ */
404
+ getCwd?: () => string | undefined;
405
+ /**
406
+ * Called once per tool call after argument validation, in call order, before
407
+ * the call is scheduled — ahead of concurrency resolution,
408
+ * `tool_execution_start`, and `tool.execute`. On the streamed path it runs
409
+ * before the assistant message's `message_start`/`message_end` are emitted.
410
+ *
411
+ * Return `{ block: true }` to prevent execution. The loop emits an error tool
412
+ * result instead (using `reason` as the error text, or a default if omitted).
413
+ *
414
+ * Return `{ args }` to replace the arguments the call runs with. The
415
+ * replacement is revalidated against the tool schema and written back to the
416
+ * tool-call block, making it the single source of truth: history, execution
417
+ * events, persistence, provider replay, concurrency scheduling, and
418
+ * `tool.execute` all see the revised arguments. Mutating `context.args` in
419
+ * place also survives into execution, but a returned `args` object wins.
420
+ *
421
+ * The hook receives the run's request abort signal and is responsible for
422
+ * honoring it. Throwing surfaces as a tool-error result and does not abort the
423
+ * rest of the batch.
424
+ */
425
+ beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined> | BeforeToolCallResult | undefined;
426
+ /**
427
+ * Called after a turn ends and before the loop polls steering/asides for the
428
+ * next iteration. `context` carries the just-finished turn; `context.willContinue`
429
+ * is true when the current tool-loop batch is continuing without yielding to
430
+ * post-turn steering.
431
+ */
432
+ onTurnEnd?: (messages: AgentMessage[], signal?: AbortSignal, context?: AgentTurnEndContext) => Promise<void> | void;
433
+ /**
434
+ * Called once an assistant message is finalized from the model stream, before
435
+ * it is appended to the context, emitted as `message_end`, or its tool calls
436
+ * are validated and dispatched. The hook may mutate the message in place —
437
+ * both its text content and its tool-call arguments — and those edits are seen
438
+ * by the transcript, the UI, and tool execution alike (single source of truth).
439
+ *
440
+ * Used for inline macro expansion: rewriting `@[[runtime.name(args)]]` tokens
441
+ * to host-computed values before anything downstream consumes the message.
442
+ * Runs at most once per assistant message; must not throw (a throw would abort
443
+ * the turn).
444
+ */
445
+ transformAssistantMessage?: (message: AssistantMessage, signal?: AbortSignal) => Promise<void> | void;
446
+ /**
447
+ * Called after a tool finishes executing, before `tool_execution_end` and the
448
+ * tool-result message are emitted.
449
+ *
450
+ * Return an `AfterToolCallResult` to override individual fields of the executed
451
+ * tool result. Omitted fields keep their original values; there is no deep merge.
452
+ *
453
+ * Throwing surfaces as a tool-error result and does not abort the rest of the batch.
454
+ */
455
+ afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined> | AfterToolCallResult | undefined;
456
+ /**
457
+ * Opt-in OpenTelemetry instrumentation. Passing `{}` enables the loop's
458
+ * GenAI-semantic-convention spans (`invoke_agent`, `chat`, `execute_tool`)
459
+ * using the global tracer provider. Leaving this field undefined disables
460
+ * the instrumentation entirely — the loop performs zero tracer lookups.
461
+ *
462
+ * See {@link AgentTelemetryConfig} for the full surface (hooks, content
463
+ * capture, cost estimator, agent identity).
464
+ */
465
+ telemetry?: AgentTelemetryConfig;
466
+ }
467
+ /**
468
+ * Batch/sequencing metadata for the tool call currently being processed.
469
+ */
470
+ export interface ToolCallContext {
471
+ batchId: string;
472
+ index: number;
473
+ total: number;
474
+ toolCalls: Array<{
475
+ id: string;
476
+ name: string;
477
+ }>;
478
+ /** Provider-native metadata for the current call, when present. */
479
+ providerMetadata?: ToolCallProviderMetadata;
480
+ /**
481
+ * Cooperative steering signal: aborted when a queued user/steering message
482
+ * (or an interrupting peer IRC) is detected while this tool batch runs.
483
+ * Unlike the hard abort signal it NEVER kills the tool — long-running
484
+ * tools MAY observe it (via `ctx.toolCall.steeringSignal`) to finish early
485
+ * or background themselves so the message injects promptly; ignoring it is
486
+ * always safe (the message injects at the next batch boundary).
487
+ */
488
+ steeringSignal?: AbortSignal;
489
+ }
490
+ /** A single tool-call content block emitted by an assistant message. */
491
+ export type AgentToolCall = Extract<AssistantMessage["content"][number], {
492
+ type: "toolCall";
493
+ }>;
494
+ /**
495
+ * Result returned from `beforeToolCall`.
496
+ *
497
+ * Set `block: true` to prevent the tool from executing. The loop emits an error tool
498
+ * result instead, using `reason` as the error text (or a default if omitted).
499
+ *
500
+ * Set `args` to replace the tool-call arguments. The replacement is revalidated
501
+ * against the tool schema (a failure surfaces as a validation-error tool result),
502
+ * written back to the tool-call block on the assistant message, and seen by
503
+ * history, scheduling, execution events, and `tool.execute` alike. It is
504
+ * ignored when `block` is true.
505
+ */
506
+ export interface BeforeToolCallResult {
507
+ block?: boolean;
508
+ reason?: string;
509
+ args?: Record<string, unknown>;
510
+ }
511
+ /**
512
+ * Partial override returned from `afterToolCall`.
513
+ *
514
+ * Merge semantics are field-by-field; omitted fields keep the executed values.
515
+ * No deep merge is performed.
516
+ */
517
+ export interface AfterToolCallResult {
518
+ /** If provided, replaces the tool result content array in full. */
519
+ content?: (TextContent | ImageContent)[];
520
+ /** If provided, replaces the tool result details payload in full. */
521
+ details?: unknown;
522
+ /** If provided, replaces the provider-native result metadata in full. */
523
+ providerMetadata?: ToolResultProviderMetadata;
524
+ /** If provided, replaces the error flag carried with the tool result. */
525
+ isError?: boolean;
526
+ /** If provided, replaces the contextually-useless flag carried with the tool result. */
527
+ useless?: boolean;
528
+ }
529
+ /** Context passed to `beforeToolCall`. */
530
+ export interface BeforeToolCallContext {
531
+ /** The assistant message that requested the tool call. */
532
+ assistantMessage: AssistantMessage;
533
+ /** The raw tool call block from `assistantMessage.content`. */
534
+ toolCall: AgentToolCall;
535
+ /** The resolved tool the call dispatches to. */
536
+ tool: AgentTool<any>;
537
+ /**
538
+ * Validated tool arguments. The same reference is forwarded to `tool.execute`
539
+ * (after any `transformToolCallArguments` pass), so in-place mutations stick;
540
+ * a returned `BeforeToolCallResult.args` replaces them entirely.
541
+ */
542
+ args: Record<string, unknown>;
543
+ /** Current agent context at the time the tool call is prepared. */
544
+ context: AgentContext;
545
+ }
546
+ /** Context passed to `afterToolCall`. */
547
+ export interface AfterToolCallContext {
548
+ /** The assistant message that requested the tool call. */
549
+ assistantMessage: AssistantMessage;
550
+ /** The raw tool call block from `assistantMessage.content`. */
551
+ toolCall: AgentToolCall;
552
+ /** Validated tool arguments used for execution (post `beforeToolCall` mutations). */
553
+ args: Record<string, unknown>;
554
+ /** The executed tool result before any `afterToolCall` overrides are applied. */
555
+ result: AgentToolResult<any>;
556
+ /** Whether the executed tool result is currently treated as an error. */
557
+ isError: boolean;
558
+ /** Current agent context at the time the tool call is finalized. */
559
+ context: AgentContext;
560
+ }
561
+ /**
562
+ * Extensible interface for custom app messages.
563
+ * Apps can extend via declaration merging:
564
+ *
565
+ * @example
566
+ * ```typescript
567
+ * declare module "@linxiraos/pi-agent-core" {
568
+ * interface CustomAgentMessages {
569
+ * artifact: ArtifactMessage;
570
+ * notification: NotificationMessage;
571
+ * }
572
+ * }
573
+ * ```
574
+ */
575
+ export interface CustomAgentMessages {
576
+ }
577
+ /**
578
+ * AgentMessage: Union of LLM messages + custom messages.
579
+ * This abstraction allows apps to add custom message types while maintaining
580
+ * type safety and compatibility with the base LLM messages.
581
+ */
582
+ export type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];
583
+ /**
584
+ * Agent state containing all configuration and conversation data.
585
+ */
586
+ export interface AgentState {
587
+ systemPrompt: string[];
588
+ model: Model;
589
+ thinkingLevel?: Effort;
590
+ disableReasoning?: boolean;
591
+ tools: AgentTool<any>[];
592
+ messages: AgentMessage[];
593
+ isStreaming: boolean;
594
+ streamMessage: AgentMessage | null;
595
+ pendingToolCalls: Set<string>;
596
+ error?: string;
597
+ }
598
+ export interface AgentToolResult<T = any, _TInput = unknown> {
599
+ content: (TextContent | ImageContent)[];
600
+ details?: T;
601
+ isError?: boolean;
602
+ /** Provider-native metadata that must survive into history replay unchanged. */
603
+ providerMetadata?: ToolResultProviderMetadata;
604
+ /** Marks the result as contextually useless: safe for compaction to elide once consumed (e.g. zero matches, wait timeout). Ignored when isError is set. */
605
+ useless?: boolean;
606
+ }
607
+ export type AgentToolUpdateCallback<T = any, TInput = unknown> = (partialResult: AgentToolResult<T, TInput>) => void;
608
+ /** Options passed to renderResult */
609
+ export interface RenderResultOptions {
610
+ /** Whether the result view is expanded */
611
+ expanded: boolean;
612
+ /** Whether this is a partial/streaming result */
613
+ isPartial: boolean;
614
+ /** Current spinner frame index for animated elements (optional) */
615
+ spinnerFrame?: number;
616
+ }
617
+ /** Capability tier a tool exercises. Determines which approval modes auto-approve it. */
618
+ export type ToolTier = "read" | "write" | "exec";
619
+ /**
620
+ * How an enabled tool is presented to the model. `"essential"` tools are exposed
621
+ * as normal top-level tools. `"discoverable"` tools are removed from the top-level
622
+ * schema and either mounted under `xd://` device URLs (when that transport is
623
+ * active) or surfaced through BM25 tool search — keeping their schemas off every
624
+ * request. Selection (settings, `hidden`, `defaultInactive`, explicit `--tools`,
625
+ * provider availability) decides whether a tool is enabled; `loadMode` only
626
+ * decides how an enabled tool is presented.
627
+ */
628
+ export type ToolLoadMode = "essential" | "discoverable";
629
+ /**
630
+ * Per-tool approval declaration.
631
+ * - bare tier ("read" / "write" / "exec") — static classification.
632
+ * - object form — adds a `reason` (shown in the prompt) and/or `override: true`
633
+ * (force-prompt even in modes that would otherwise auto-approve this tier).
634
+ * `policy: "deny"` blocks the call at the approval gate.
635
+ * - function — dynamic, given parsed args. Returns either form above.
636
+ *
637
+ * Omitted approvals are treated as "exec" by callers that enforce approvals.
638
+ */
639
+ export type ToolApprovalDecision = ToolTier | {
640
+ tier: ToolTier;
641
+ reason?: string;
642
+ override?: boolean;
643
+ policy?: "allow" | "deny" | "prompt";
644
+ /** User-policy key for this decision. When set, `tools.approval.<policyKey>`
645
+ * is consulted instead of `tools.approval.<tool.name>`. Lets a dispatcher
646
+ * tool (e.g. `write` for an `xd://` device call) scope user allow/deny/
647
+ * prompt policies to the tool it dispatches into. */
648
+ policyKey?: string;
649
+ };
650
+ export type ToolApproval = ToolApprovalDecision | ((args: unknown) => ToolApprovalDecision);
651
+ /**
652
+ * Context passed to tool execution.
653
+ * Apps can extend via declaration merging.
654
+ */
655
+ export interface AgentToolContext {
656
+ }
657
+ export type AgentToolExecFn<TParameters extends TSchema = TSchema, TDetails = any, TTheme = unknown> = (this: AgentTool<TParameters, TDetails, TTheme>, toolCallId: string, params: Static<TParameters>, signal?: AbortSignal, onUpdate?: AgentToolUpdateCallback<TDetails, TParameters>, context?: AgentToolContext) => Promise<AgentToolResult<TDetails, TParameters>>;
658
+ /** Live receiver for a tool call's streamed arguments (see AgentTool.openArgStream). */
659
+ export interface AgentToolArgStream {
660
+ /** Raw wire fragment of the arguments (JSON text, or verbatim payload for custom-format tools). */
661
+ push(delta: string): void;
662
+ /** Arguments are complete; `args` is the final parsed object the loop will pass to `execute`. */
663
+ end(args: unknown): void;
664
+ /** The call will never execute (stream error, abort, blocked). Release resources. */
665
+ cancel(): void;
666
+ }
667
+ export interface AgentToolArgStreamInit {
668
+ toolCallId: string;
669
+ toolName: string;
670
+ /** Wire-level name for custom-format tools; undefined for JSON function tools. */
671
+ customWireName?: string;
672
+ /** Push a serializable projection of the in-flight call (e.g. diff previews); surfaces as `tool_stream_update`. */
673
+ emit(update: unknown): void;
674
+ }
675
+ export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any, TTheme = unknown> extends Tool<TParameters> {
676
+ label: string;
677
+ /**
678
+ * Called at `toolcall_start`, before any argument delta. Return `undefined` to opt out.
679
+ */
680
+ openArgStream?: (init: AgentToolArgStreamInit) => AgentToolArgStream | undefined;
681
+ /** If true, tool is excluded unless explicitly listed in --tools or agent's tools field */
682
+ hidden?: boolean;
683
+ /** If true, tool can stage a pending action that requires explicit resolution via the resolve tool. */
684
+ deferrable?: boolean;
685
+ /** How an enabled tool is presented. See {@link ToolLoadMode}. Omitted is treated as `"essential"` for built-ins; custom-tool adapters normalize omission to `"discoverable"`. */
686
+ loadMode?: ToolLoadMode;
687
+ /** Short one-line summary used for tool discovery indexes. */
688
+ summary?: string;
689
+ /**
690
+ * Concurrency mode for tool scheduling when multiple calls are in one turn.
691
+ * - "shared": can run alongside other shared tools (default)
692
+ * - "exclusive": runs alone; other tools wait until it finishes
693
+ * - function: resolved per call from the (raw, pre-validation) arguments
694
+ */
695
+ concurrency?: "shared" | "exclusive" | ((args: Partial<Static<TParameters>>) => "shared" | "exclusive");
696
+ /** If true, argument validation errors are non-fatal: raw args are passed to execute() instead of returning an error to the LLM. */
697
+ lenientArgValidation?: boolean;
698
+ /**
699
+ * Whether the agent loop may abort this tool mid-execution — or skip it
700
+ * before it starts — to deliver a queued steering message. A function
701
+ * resolves this per call from the raw, pre-validation arguments.
702
+ *
703
+ * Enable only for calls that purely *wait* and observe their abort signal
704
+ * cleanly (e.g. `job` poll), so the abort surfaces the tool's current
705
+ * snapshot rather than corrupting a side effect. Every other call runs to
706
+ * completion even when steering is queued; the message lands at the next
707
+ * batch boundary. Honored only when `interruptMode` is "immediate".
708
+ */
709
+ interruptible?: boolean | ((args: Partial<Static<TParameters>>) => boolean);
710
+ /**
711
+ * Controls how the INTENT_FIELD (`i`) is handled for this tool.
712
+ * - `"require"` (default): `i` is injected and required in the parameter schema.
713
+ * - `"optional"`: `i` is injected as an optional/nullable field.
714
+ * - `"omit"`: `i` is NOT injected. Use for tools where intent is obvious (yield, resolve, todo, …).
715
+ * - function: `i` is NOT injected; intent is derived dynamically from (potentially partial / streaming) args.
716
+ */
717
+ intent?: "omit" | "optional" | "require" | ((args: Partial<Static<TParameters>>) => string | undefined);
718
+ /**
719
+ * Normalize (potentially partial) streamed arguments into the plain text that
720
+ * stream-content matchers (e.g. TTSR rules) should inspect — the real content
721
+ * the call introduces, without wire grammar such as patch prefixes or JSON
722
+ * string escaping. Return `undefined` to fall back to raw argument-delta
723
+ * matching.
724
+ */
725
+ matcherDigest?: (args: unknown) => string | undefined;
726
+ /**
727
+ * Surface the target file paths a (potentially partial) streamed call would
728
+ * touch, so path-scoped stream matchers (e.g. TTSR `tool:edit(*.ts)` globs)
729
+ * can match without a top-level `path`/`paths` argument. Used for tools whose
730
+ * wire grammar embeds paths inside the streamed payload (hashline section
731
+ * headers, apply_patch envelope markers). Return `undefined` (or an empty
732
+ * array) to fall back to the caller's top-level argument scan.
733
+ */
734
+ matcherPaths?: (args: unknown) => readonly string[] | undefined;
735
+ /**
736
+ * Per-file projection of a (potentially partial) streamed call, pairing each
737
+ * touched file path with the digest of only the lines added to that file.
738
+ * Path-scoped stream matchers (TTSR) evaluate each entry in isolation, so a
739
+ * scoped rule like `tool:edit(*.ts)` never fires on text that actually
740
+ * belongs to a sibling Markdown hunk in a multi-file payload. Takes
741
+ * precedence over {@link matcherDigest} + {@link matcherPaths} when present;
742
+ * returns `undefined` (or empty) to fall back to the combined hooks.
743
+ */
744
+ matcherEntries?: (args: unknown) => readonly {
745
+ path: string;
746
+ digest: string;
747
+ }[] | undefined;
748
+ /** Capability tier declaration used by approval gates. Omitted means "exec". */
749
+ approval?: ToolApproval;
750
+ /** Lines appended after the standard approval prompt header. */
751
+ formatApprovalDetails?: (args: unknown) => string | string[] | undefined;
752
+ /** The main execution callback for this tool. */
753
+ execute: AgentToolExecFn<TParameters, TDetails, TTheme>;
754
+ /** Optional custom rendering for tool call display (returns UI component) */
755
+ renderCall?: (args: Static<TParameters>, options: RenderResultOptions, theme: TTheme) => unknown;
756
+ /** Optional custom rendering for tool result display (returns UI component) */
757
+ renderResult?: (result: AgentToolResult<TDetails, TParameters>, options: RenderResultOptions, theme: TTheme) => unknown;
758
+ }
759
+ export interface AgentContext {
760
+ systemPrompt: string[];
761
+ messages: AgentMessage[];
762
+ tools?: AgentTool<any>[];
763
+ }
764
+ /**
765
+ * Events emitted by the Agent for UI updates.
766
+ * These events provide fine-grained lifecycle information for messages, turns, and tool executions.
767
+ */
768
+ export type AgentEvent = {
769
+ type: "agent_start";
770
+ } | {
771
+ type: "agent_end";
772
+ messages: AgentMessage[];
773
+ /** Present iff `AgentTelemetryConfig` was supplied on this run. */
774
+ telemetry?: AgentRunSummary;
775
+ coverage?: AgentRunCoverage;
776
+ } | {
777
+ type: "turn_start";
778
+ } | {
779
+ type: "turn_end";
780
+ message: AgentMessage;
781
+ toolResults: ToolResultMessage[];
782
+ } | {
783
+ type: "message_start";
784
+ message: AgentMessage;
785
+ } | {
786
+ type: "message_update";
787
+ message: AgentMessage;
788
+ assistantMessageEvent: AssistantMessageEvent;
789
+ } | {
790
+ type: "message_end";
791
+ message: AgentMessage;
792
+ } | {
793
+ type: "tool_execution_start";
794
+ toolCallId: string;
795
+ toolName: string;
796
+ args: any;
797
+ intent?: string;
798
+ } | {
799
+ type: "tool_execution_update";
800
+ toolCallId: string;
801
+ toolName: string;
802
+ args: any;
803
+ partialResult: any;
804
+ } | {
805
+ type: "tool_stream_update";
806
+ toolCallId: string;
807
+ toolName: string;
808
+ update: unknown;
809
+ } | {
810
+ type: "tool_execution_end";
811
+ toolCallId: string;
812
+ toolName: string;
813
+ result: any;
814
+ isError?: boolean;
815
+ };