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