@linxiraos/pi-agent-core 1.0.4 → 1.0.5

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/CHANGELOG.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Changelog
2
2
 
3
- ## [Unreleased]
3
+ ## [1.0.5] - 2026-08-16
4
4
 
5
5
  ## [1.0.2] - 2026-08-15
6
6
 
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Agent loop that works with AgentMessage throughout.
3
+ * Transforms to Message[] only at the LLM call boundary.
4
+ */
5
+ import { type AssistantMessage, type Context, EventStream, type ToolResultMessage } from "@linxiraos/pi-ai";
6
+ import { type Dialect } from "@linxiraos/pi-ai/dialect";
7
+ import { type AgentRunCoverage, type AgentRunSummary } from "./run-collector.js";
8
+ import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, StreamFn } from "./types.js";
9
+ /** Stop-details marker for a provider error after assistant content/tool args already streamed. */
10
+ export declare const STREAM_INTERRUPTED_AFTER_CONTENT_STOP_DETAIL = "stream_interrupted_after_content";
11
+ /**
12
+ * Cadence (ms) for polling queued steering while an `interruptible` tool is in
13
+ * flight, so a steer cuts the wait short instead of sitting idle until the
14
+ * tool's own window elapses. A cheap synchronous queue check; latency-bounded
15
+ * at one tick.
16
+ */
17
+ /**
18
+ * Abort reason for a turn-wide interruption where only some tool calls caused
19
+ * the abort and sibling placeholders need neutral messages.
20
+ */
21
+ export interface ToolScopedAbortReason {
22
+ readonly kind: "tool-scoped-abort";
23
+ readonly message: string;
24
+ readonly toolCallMessages: Record<string, string>;
25
+ readonly defaultToolCallMessage: string;
26
+ }
27
+ /** Creates an abort reason that labels matching tool calls separately from siblings. */
28
+ export declare function createToolScopedAbortReason(message: string, toolCallMessages: Record<string, string>, defaultToolCallMessage: string): ToolScopedAbortReason;
29
+ /**
30
+ * Marks an abort raised by a completed post-tool hook as terminal for the
31
+ * current run. External/user aborts still synthesize an aborted assistant
32
+ * boundary; this reason stops after persisting the completed tool batch.
33
+ */
34
+ export declare const TERMINAL_TOOL_RESULT_ABORT_REASON: unique symbol;
35
+ export declare function resolveOwnedDialectFromEnv(value: string | undefined): Dialect | undefined;
36
+ /**
37
+ * Start an agent loop with a new prompt message.
38
+ * The prompt is added to the context and events are emitted for it.
39
+ */
40
+ export declare function agentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
41
+ /**
42
+ * Continue an agent loop from the current context without adding a new message.
43
+ * Used for retries - context already has user message or tool results.
44
+ *
45
+ * **Important:** The last message in context must convert to a `user` or `toolResult` message
46
+ * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.
47
+ * This cannot be validated here since `convertToLlm` is only called once per turn.
48
+ */
49
+ export declare function agentLoopContinue(context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
50
+ /**
51
+ * Detailed-result handle returned by {@link agentLoopDetailed}. Adds the
52
+ * run-level telemetry/coverage rollup to the existing `AgentMessage[]`
53
+ * payload without changing the resolved type of `stream.result()`.
54
+ */
55
+ export interface AgentLoopDetailedResult {
56
+ readonly messages: AgentMessage[];
57
+ readonly telemetry: AgentRunSummary | undefined;
58
+ readonly coverage: AgentRunCoverage | undefined;
59
+ }
60
+ /**
61
+ * Convenience wrapper over {@link agentLoop} that exposes the run-level
62
+ * summary + coverage alongside the messages. The returned `stream` is the
63
+ * same `EventStream` callers already consume; `detailed()` awaits the
64
+ * stream's `agent_end` event and returns the additive fields.
65
+ *
66
+ * Existing `stream.result()` semantics are preserved — it still resolves to
67
+ * `AgentMessage[]`. Use {@link agentLoopDetailed} when you need the rollup;
68
+ * use {@link agentLoop} when you do not.
69
+ */
70
+ export declare function agentLoopDetailed(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): {
71
+ readonly stream: EventStream<AgentEvent, AgentMessage[]>;
72
+ readonly detailed: () => Promise<AgentLoopDetailedResult>;
73
+ };
74
+ /**
75
+ * Like {@link agentLoopDetailed} but built on top of
76
+ * {@link agentLoopContinue}.
77
+ */
78
+ export declare function agentLoopContinueDetailed(context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): {
79
+ readonly stream: EventStream<AgentEvent, AgentMessage[]>;
80
+ readonly detailed: () => Promise<AgentLoopDetailedResult>;
81
+ };
82
+ export declare function normalizeMessagesForProvider(messages: Context["messages"], model: AgentLoopConfig["model"]): Context["messages"];
83
+ export interface NormalizeToolsOptions {
84
+ /** Inject the `i` intent field into tool schemas (subject to `PI_NO_INTENT`). */
85
+ injectIntent: boolean;
86
+ /** Strip descriptions from the wire specs when the catalog rides in the system prompt. */
87
+ pruneDescriptions?: boolean;
88
+ }
89
+ export declare function normalizeTools(tools: AgentContext["tools"], options: NormalizeToolsOptions): Context["tools"];
90
+ /** Resolve the human-readable reason an abort carried. A caller that aborts via
91
+ * `AbortController.abort(reason)` with a string or a non-`AbortError` `Error`
92
+ * (e.g. the coding agent's user-interrupt label) gets that text surfaced on the
93
+ * synthesized assistant message's `errorMessage`; a bare `abort()` (whose
94
+ * `signal.reason` is the default `AbortError` `DOMException`) falls back to the
95
+ * generic sentinel that downstream renderers treat as "no specific reason". */
96
+ export declare function abortReasonText(signal: AbortSignal | undefined): string;
97
+ /**
98
+ * Discriminator embedded in {@link AgentToolResult.details} and
99
+ * {@link ToolResultMessage.details} for tool calls that were emitted by the
100
+ * assistant but never actually invoked locally.
101
+ *
102
+ * The synthetic result exists only to preserve the tool_use / tool_result
103
+ * pairing the provider API requires; no `tool.execute()` ran. UI, telemetry,
104
+ * and history consumers can key on `__synthetic === true` to render or
105
+ * classify these as "call emitted, not executed" instead of a real local
106
+ * tool failure — the mislabeling this discriminator was introduced to fix
107
+ * (#4321): a provider-side stream error after tool-call emission (e.g. Codex
108
+ * websocket close) was surfaced by the CLI as if the local tool had failed.
109
+ *
110
+ * `source` names the state that prevented execution — either an assistant-side
111
+ * turn termination (`assistant_stop_*`) or a mid-batch interrupt that skipped a
112
+ * still-pending call to service queued steering/peer input (`interrupt_skipped`).
113
+ * `upstreamError` is the provider-reported message when the turn ended with
114
+ * `stopReason === "error"`.
115
+ */
116
+ export interface SyntheticToolResultDetails {
117
+ __synthetic: true;
118
+ source: "assistant_stop_aborted" | "assistant_stop_error" | "assistant_stop_skipped" | "assistant_stop_length" | "interrupt_skipped";
119
+ executed: false;
120
+ upstreamError?: string;
121
+ }
122
+ /**
123
+ * Narrow an {@link AgentMessage} to a synthetic {@link ToolResultMessage} —
124
+ * a tool_result emitted for a tool call the assistant never invoked (see
125
+ * {@link SyntheticToolResultDetails}). Consumers use this to look past the
126
+ * placeholder pairing back to the assistant turn that produced it, e.g.
127
+ * `AgentSession.retry()` walking back over the synthetic results a
128
+ * stalled/aborted mid-tool-call turn leaves behind.
129
+ */
130
+ export declare function isSyntheticToolResultMessage(message: AgentMessage | undefined): message is ToolResultMessage<SyntheticToolResultDetails>;
131
+ /**
132
+ * Create the persisted synthetic result for a tool call that was emitted by
133
+ * the assistant but never invoked locally.
134
+ */
135
+ export declare function createSyntheticToolResultMessage(toolCall: Extract<AssistantMessage["content"][number], {
136
+ type: "toolCall";
137
+ }>, reason: "aborted" | "error" | "skipped" | "length", errorMessage?: string): ToolResultMessage<SyntheticToolResultDetails>;
@@ -0,0 +1,465 @@
1
+ import { type ApiKey, type AssistantMessage, type AssistantMessageEvent, type Context, type CursorExecHandlers, type CursorToolResultHandler, type Effort, type ImageContent, type Message, type Model, type ProviderSessionState, type ServiceTier, type SimpleStreamOptions, type ThinkingBudgets, type ToolChoice } 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 { AgentBeforeModelCall, AgentEvent, AgentLoopConfig, AgentMessage, AgentState, AgentTool, AgentToolContext, AgentTurnEndContext, AsideMessage, StreamFn, ToolCallContext, ToolChoiceDirective } from "./types.js";
6
+ export declare class AgentBusyError extends Error {
7
+ constructor(message?: string);
8
+ }
9
+ export interface AgentOptions {
10
+ initialState?: Partial<AgentState>;
11
+ /**
12
+ * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
13
+ * Default filters to user/assistant/toolResult and converts attachments.
14
+ */
15
+ convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
16
+ /**
17
+ * Optional transform applied to context before convertToLlm.
18
+ * Use for context pruning, injecting external context, etc.
19
+ */
20
+ transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
21
+ /**
22
+ * Optional transform applied after provider context assembly and before
23
+ * telemetry capture/provider send.
24
+ */
25
+ transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
26
+ /**
27
+ * Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
28
+ */
29
+ steeringMode?: "all" | "one-at-a-time";
30
+ /**
31
+ * Follow-up mode: "all" = send all follow-up messages at once, "one-at-a-time" = one per turn
32
+ */
33
+ followUpMode?: "all" | "one-at-a-time";
34
+ /**
35
+ * When to interrupt tool execution for steering messages.
36
+ * - "immediate": check after each tool call (default)
37
+ * - "wait": defer steering until the current turn completes
38
+ */
39
+ interruptMode?: "immediate" | "wait";
40
+ /**
41
+ * API format for Kimi Code provider: "openai" or "anthropic" (default: "anthropic")
42
+ */
43
+ kimiApiFormat?: "openai" | "anthropic";
44
+ /** Hint that websocket transport should be preferred when supported by the provider implementation. */
45
+ preferWebsockets?: boolean;
46
+ /**
47
+ * Custom stream function (for proxy backends, etc.). Default uses streamSimple.
48
+ */
49
+ streamFn?: StreamFn;
50
+ /** Absolute wall-clock deadline in Unix epoch milliseconds. */
51
+ deadline?: number;
52
+ /**
53
+ * Optional session identifier forwarded to LLM providers.
54
+ * Used by providers that support session-based caching (e.g., OpenAI Codex).
55
+ */
56
+ sessionId?: string;
57
+ /**
58
+ * Optional prompt cache key forwarded to LLM providers.
59
+ * When omitted, providers may fall back to sessionId.
60
+ */
61
+ promptCacheKey?: string;
62
+ /**
63
+ * Shared provider state map for session-scoped transport/session caches.
64
+ */
65
+ providerSessionState?: Map<string, ProviderSessionState>;
66
+ /**
67
+ * Resolves an API key or resolver dynamically for each LLM call.
68
+ * Useful for expiring tokens and model-scoped credential routing.
69
+ */
70
+ getApiKey?: (model: Model) => Promise<ApiKey | undefined> | ApiKey | undefined;
71
+ /**
72
+ * Inspect or replace provider payloads before they are sent.
73
+ */
74
+ onPayload?: SimpleStreamOptions["onPayload"];
75
+ /**
76
+ * Inspect provider response metadata after headers arrive and before streaming body consumption.
77
+ */
78
+ onResponse?: SimpleStreamOptions["onResponse"];
79
+ /**
80
+ * Inspect raw Server-Sent Events from HTTP streaming providers.
81
+ */
82
+ onSseEvent?: SimpleStreamOptions["onSseEvent"];
83
+ /**
84
+ * Inspect assistant streaming events before they are emitted to subscribers.
85
+ * Use this when abort decisions must happen before buffered events continue flowing.
86
+ */
87
+ onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
88
+ /**
89
+ * Called when GPT-5 Harmony protocol leakage is detected and mitigated.
90
+ */
91
+ onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
92
+ /**
93
+ * Custom token budgets for thinking levels (token-based providers only).
94
+ */
95
+ thinkingBudgets?: ThinkingBudgets;
96
+ /**
97
+ * Sampling temperature for LLM calls. `undefined` uses provider default.
98
+ */
99
+ temperature?: number;
100
+ /** Additional sampling controls for providers that support them. */
101
+ topP?: number;
102
+ topK?: number;
103
+ minP?: number;
104
+ presencePenalty?: number;
105
+ repetitionPenalty?: number;
106
+ serviceTier?: ServiceTier;
107
+ /**
108
+ * Per-call effective service-tier resolver. When set, it authoritatively
109
+ * supplies the request's tier (replacing the static `serviceTier` and its
110
+ * telemetry) per model — used to scope a provider/model into a priority
111
+ * serving path without mutating the shared session `serviceTier`.
112
+ */
113
+ serviceTierResolver?: (model: Model) => ServiceTier | undefined;
114
+ /**
115
+ * If true, request that the underlying provider omit reasoning/thinking summaries
116
+ * from the response. The model still reasons internally; only the human-readable
117
+ * summary stream is suppressed. Useful when the UI hides thinking blocks anyway.
118
+ */
119
+ hideThinkingSummary?: boolean;
120
+ /**
121
+ * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
122
+ * If the server's requested delay exceeds this value, the request fails immediately,
123
+ * allowing higher-level retry logic to handle it with user visibility.
124
+ * Default: 60000 (60 seconds). Set to 0 to disable the cap.
125
+ */
126
+ maxRetryDelayMs?: number;
127
+ /**
128
+ * Provides tool execution context, resolved per tool call.
129
+ * Use for late-bound UI or session state access.
130
+ */
131
+ getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
132
+ /**
133
+ * Optional transform applied to tool call arguments before execution.
134
+ * Use for deobfuscating secrets or rewriting arguments.
135
+ */
136
+ transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
137
+ /**
138
+ * Resolve a tool call whose name matched no advertised tool. Lets hosts
139
+ * route calls to tools exposed through side transports (e.g. `xd://`
140
+ * device mounts) instead of failing with "Tool not found".
141
+ */
142
+ resolveFallbackTool?: (name: string) => AgentTool<any> | undefined;
143
+ /** Enable intent tracing schema injection/stripping in the harness. */
144
+ intentTracing?: boolean;
145
+ /**
146
+ * Strip tool descriptions from provider-bound tool specs (top-level + nested
147
+ * schema annotations). Use when the full catalog is rendered into the system
148
+ * prompt so descriptions are not duplicated on the wire. Native tool calling only.
149
+ */
150
+ pruneToolDescriptions?: boolean;
151
+ /** Owned tool-calling dialect. Undefined keeps provider-native tool calling. */
152
+ dialect?: Dialect;
153
+ /**
154
+ * When owned tool calling is active and the model fabricates a tool result
155
+ * mid-turn: `true` (default) aborts the provider request immediately; `false`
156
+ * drains the request and discards the fabricated continuation. Forwarded to
157
+ * the loop's {@link AgentLoopConfig.abortOnFabricatedToolResult}.
158
+ */
159
+ abortOnFabricatedToolResult?: boolean;
160
+ /** Dynamic tool-choice directive (hard {@link ToolChoice} or {@link SoftToolRequirement}), resolved once per turn. */
161
+ getToolChoice?: () => ToolChoiceDirective | undefined;
162
+ /** Reject a deferred hard choice when its named tool is no longer active. */
163
+ onToolChoiceUnavailable?: () => void;
164
+ /**
165
+ * Cursor exec handlers for local tool execution.
166
+ */
167
+ cursorExecHandlers?: CursorExecHandlers;
168
+ /** Additional tools Cursor executes through its MCP request-context bridge, resolved before each provider call. */
169
+ getCursorTools?: () => AgentTool[];
170
+ /**
171
+ * Optional rewrite of Cursor exec-channel tool results. May return a Promise.
172
+ *
173
+ * The Agent reserves the original result in its Cursor result buffer first,
174
+ * then awaits this hook and patches the reserved entry in place. That keeps
175
+ * the call paired even if `message_end` arrives while the Promise is still
176
+ * pending, and `#emitCursorSplitAssistantMessage` waits for any transformer
177
+ * still in flight before persisting, so a late rewrite is not lost. A
178
+ * rejecting transformer is swallowed and the reserved payload stands in.
179
+ * Hosts that only pass `cursorExecHandlers` (the coding-agent path) never
180
+ * hit this hook.
181
+ */
182
+ cursorOnToolResult?: CursorToolResultHandler;
183
+ /** Current working directory used by local tool execution. */
184
+ cwd?: string;
185
+ /**
186
+ * Resolver for the live working directory, re-read on every turn. When set, it
187
+ * overrides the static {@link cwd} at config-build time so a session move
188
+ * (`/move`, which updates the host's cwd without reconstructing the Agent) is
189
+ * reflected in provider options — e.g. GitLab Duo Agent namespace/project
190
+ * discovery keys off this cwd's git remote. Falls back to `cwd` when it returns
191
+ * `undefined`.
192
+ */
193
+ cwdResolver?: () => string | undefined;
194
+ /**
195
+ * Called after a tool call has been validated and is about to execute.
196
+ * See {@link AgentLoopConfig.beforeToolCall} for full semantics.
197
+ */
198
+ beforeToolCall?: AgentLoopConfig["beforeToolCall"];
199
+ /**
200
+ * Called after a tool finishes executing, before `tool_execution_end` and the tool-result
201
+ * message are emitted. See {@link AgentLoopConfig.afterToolCall} for full semantics.
202
+ */
203
+ afterToolCall?: AgentLoopConfig["afterToolCall"];
204
+ /**
205
+ * Called once an assistant message is finalized, before it reaches the
206
+ * context, the UI, or tool dispatch. May mutate the message in place (text +
207
+ * tool-call arguments). See {@link AgentLoopConfig.transformAssistantMessage}.
208
+ */
209
+ transformAssistantMessage?: AgentLoopConfig["transformAssistantMessage"];
210
+ /**
211
+ * Opt-in OpenTelemetry instrumentation. Passing `{}` enables the loop's
212
+ * GenAI-semantic-convention spans using the global tracer provider. See
213
+ * {@link AgentLoopConfig.telemetry} for the full surface.
214
+ */
215
+ telemetry?: AgentLoopConfig["telemetry"];
216
+ /**
217
+ * Immutable context mode — stabilizes system prompt + tool spec bytes
218
+ * across turns so DeepSeek/Anthropic prefix caches hit at maximum rate.
219
+ */
220
+ appendOnlyContext?: AppendOnlyContextManager;
221
+ }
222
+ export interface AgentPromptOptions {
223
+ toolChoice?: ToolChoice;
224
+ }
225
+ export declare class Agent {
226
+ #private;
227
+ streamFn: StreamFn;
228
+ getApiKey?: (model: Model) => Promise<ApiKey | undefined> | ApiKey | undefined;
229
+ /**
230
+ * Hook invoked after tool arguments are validated and before execution.
231
+ * Reassign at any time to swap the implementation (e.g. on extension reload).
232
+ */
233
+ beforeToolCall?: AgentLoopConfig["beforeToolCall"];
234
+ /**
235
+ * Hook invoked after tool execution and before `tool_execution_end` / tool-result
236
+ * message emission. Reassign at any time to swap the implementation.
237
+ */
238
+ afterToolCall?: AgentLoopConfig["afterToolCall"];
239
+ /**
240
+ * Hook invoked once an assistant message is finalized, before context append,
241
+ * UI emission, and tool dispatch. Reassign at any time to swap the implementation.
242
+ */
243
+ transformAssistantMessage?: AgentLoopConfig["transformAssistantMessage"];
244
+ /**
245
+ * Hook that peeks whether interrupting IRC asides are queued for the next boundary.
246
+ */
247
+ hasIrcInterrupts?: AgentLoopConfig["hasIrcInterrupts"];
248
+ constructor(opts?: AgentOptions);
249
+ /**
250
+ * Get the current session ID used for provider caching.
251
+ */
252
+ get sessionId(): string | undefined;
253
+ /**
254
+ * Set the session ID for provider caching.
255
+ * Call this when switching sessions (new session, branch, resume).
256
+ */
257
+ set sessionId(value: string | undefined);
258
+ /**
259
+ * Get the prompt cache key forwarded to providers.
260
+ */
261
+ get promptCacheKey(): string | undefined;
262
+ /**
263
+ * Set the prompt cache key forwarded to providers.
264
+ */
265
+ set promptCacheKey(value: string | undefined);
266
+ /**
267
+ * Static metadata forwarded to every API request when no resolver is installed
268
+ * (e.g. `metadata.user_id` for Anthropic session attribution). Setting this
269
+ * clears any installed resolver.
270
+ *
271
+ * For live/provider-aware metadata (e.g. Anthropic OAuth `account_uuid` that
272
+ * must reflect the credential selected per-request), use
273
+ * {@link setMetadataResolver} and read via {@link metadataForProvider}.
274
+ */
275
+ get metadata(): Record<string, unknown> | undefined;
276
+ set metadata(value: Record<string, unknown> | undefined);
277
+ /**
278
+ * Resolve request metadata for the given provider at call time. When a
279
+ * resolver is installed via {@link setMetadataResolver}, it is invoked with
280
+ * the provider string so the result can be scoped (e.g. `account_uuid` is
281
+ * only included for `"anthropic"` requests). Falls back to the static
282
+ * {@link metadata} value when no resolver is set.
283
+ */
284
+ metadataForProvider(provider: string): Record<string, unknown> | undefined;
285
+ /**
286
+ * Install a function that resolves request metadata at call time. The
287
+ * resolver receives the target provider string and can gate provider-specific
288
+ * fields (e.g. `account_uuid` only for `"anthropic"`). Invoked per LLM
289
+ * request by `agent-loop` after `getApiKey` selects the session-sticky
290
+ * credential. Pass `undefined` to clear and revert to the static
291
+ * {@link metadata} value.
292
+ */
293
+ setMetadataResolver(resolver: ((provider: string) => Record<string, unknown> | undefined) | undefined): void;
294
+ /**
295
+ * Read the active OpenTelemetry configuration. Returns `undefined` when
296
+ * instrumentation is disabled. Callers spawning child runs (e.g. subagent
297
+ * dispatch) forward this to the child's loop so its spans appear under the
298
+ * parent's active context with the subagent's own identity stamped.
299
+ */
300
+ get telemetry(): AgentLoopConfig["telemetry"] | undefined;
301
+ /**
302
+ * Replace the active OpenTelemetry configuration. Pass `undefined` to
303
+ * disable instrumentation. Applies to the *next* `agentLoop` invocation —
304
+ * in-flight loops keep the configuration they started with.
305
+ */
306
+ setTelemetry(telemetry: AgentLoopConfig["telemetry"] | undefined): void;
307
+ /**
308
+ * Get provider-scoped mutable session state store.
309
+ */
310
+ get providerSessionState(): Map<string, ProviderSessionState> | undefined;
311
+ /**
312
+ * Set provider-scoped mutable session state store.
313
+ */
314
+ set providerSessionState(value: Map<string, ProviderSessionState> | undefined);
315
+ /**
316
+ * Get the current thinking budgets.
317
+ */
318
+ get thinkingBudgets(): ThinkingBudgets | undefined;
319
+ /**
320
+ * Set custom thinking budgets for token-based providers.
321
+ */
322
+ set thinkingBudgets(value: ThinkingBudgets | undefined);
323
+ /**
324
+ * Get the current sampling temperature.
325
+ */
326
+ get temperature(): number | undefined;
327
+ /**
328
+ * Set sampling temperature for LLM calls. `undefined` uses provider default.
329
+ */
330
+ set temperature(value: number | undefined);
331
+ get topP(): number | undefined;
332
+ set topP(value: number | undefined);
333
+ get topK(): number | undefined;
334
+ set topK(value: number | undefined);
335
+ get minP(): number | undefined;
336
+ set minP(value: number | undefined);
337
+ get presencePenalty(): number | undefined;
338
+ set presencePenalty(value: number | undefined);
339
+ get repetitionPenalty(): number | undefined;
340
+ set repetitionPenalty(value: number | undefined);
341
+ get serviceTier(): ServiceTier | undefined;
342
+ set serviceTier(value: ServiceTier | undefined);
343
+ get serviceTierResolver(): ((model: Model) => ServiceTier | undefined) | undefined;
344
+ set serviceTierResolver(value: ((model: Model) => ServiceTier | undefined) | undefined);
345
+ get hideThinkingSummary(): boolean | undefined;
346
+ set hideThinkingSummary(value: boolean | undefined);
347
+ /**
348
+ * Get the current max retry delay in milliseconds.
349
+ */
350
+ get maxRetryDelayMs(): number | undefined;
351
+ /**
352
+ * Set the maximum delay to wait for server-requested retries.
353
+ * Set to 0 to disable the cap.
354
+ */
355
+ set maxRetryDelayMs(value: number | undefined);
356
+ get state(): AgentState;
357
+ get appendOnlyContext(): AppendOnlyContextManager | undefined;
358
+ setAppendOnlyContext(manager?: AppendOnlyContextManager): void;
359
+ /**
360
+ * Assemble the provider Context for a side-channel (no-loop) request, mirroring
361
+ * the main loop's prefix (system + normalized tools) so it shares the prompt
362
+ * cache. Never touches the append-only log or the tool-choice queue. Owned/
363
+ * in-band dialect sessions stay tools-less (matching their no-native-tools wire
364
+ * shape and avoiding tool-markup leakage). `llmMessages` is already converted
365
+ * (and, in production, obfuscated) by the caller.
366
+ *
367
+ * `systemPrompt` defaults to the live agent prompt so the side request hits the
368
+ * same cached prefix as the main loop. Callers that must pin a different prompt
369
+ * (e.g. handoff generation, which uses the base prompt rather than a per-turn
370
+ * `before_agent_start` hook override) pass it explicitly.
371
+ */
372
+ buildSideRequestContext(llmMessages: Message[], systemPrompt?: string[]): Promise<Context>;
373
+ subscribe(fn: (e: AgentEvent) => void): () => void;
374
+ /** Register an independently removable hook that runs before queued messages are consumed. */
375
+ addBeforeQueuedMessageDequeueHook(hook: (signal?: AbortSignal) => Promise<void> | void): () => void;
376
+ /** Register an independently removable hook that runs immediately before each model call. */
377
+ addBeforeModelCallHook(hook: (signal?: AbortSignal) => Promise<void> | void): () => void;
378
+ setProviderResponseInterceptor(fn: SimpleStreamOptions["onResponse"] | undefined): void;
379
+ setRawSseEventInterceptor(fn: SimpleStreamOptions["onSseEvent"] | undefined): void;
380
+ setAssistantMessageEventInterceptor(fn: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined): void;
381
+ setOnBeforeYield(fn: (() => Promise<void> | void) | undefined): void;
382
+ setOnTurnEnd(fn: ((messages: AgentMessage[], signal?: AbortSignal, context?: AgentTurnEndContext) => Promise<void> | void) | undefined): void;
383
+ /**
384
+ * Install or replace the host pre-model-call gate; pass `undefined` to
385
+ * remove it. Gates are sampled when a run starts: installing the first
386
+ * gate while a run is in flight takes effect on the next run.
387
+ */
388
+ setBeforeModelCall(fn: AgentBeforeModelCall | undefined): void;
389
+ /**
390
+ * Add a pre-model callback without replacing callbacks owned by the host.
391
+ * Returns a disposer that removes only this callback. Like
392
+ * {@link setBeforeModelCall}, the first gate installed while a run is in
393
+ * flight takes effect on the next run.
394
+ */
395
+ addBeforeModelCall(fn: AgentBeforeModelCall): () => void;
396
+ /**
397
+ * Provide a source of non-interrupting "aside" messages (e.g. background-job
398
+ * completions, late LSP diagnostics) drained at each step boundary. Never
399
+ * aborts in-flight tools. See `AgentLoopConfig.getAsideMessages`.
400
+ */
401
+ setAsideMessageProvider(fn: (() => AsideMessage[] | Promise<AsideMessage[]>) | undefined): void;
402
+ emitExternalEvent(event: AgentEvent): void;
403
+ setSystemPrompt(v: string[] | string): void;
404
+ setModel(m: Model): void;
405
+ setThinkingLevel(l: Effort | undefined): void;
406
+ setDisableReasoning(disabled: boolean): void;
407
+ setSteeringMode(mode: "all" | "one-at-a-time"): void;
408
+ getSteeringMode(): "all" | "one-at-a-time";
409
+ setFollowUpMode(mode: "all" | "one-at-a-time"): void;
410
+ getFollowUpMode(): "all" | "one-at-a-time";
411
+ setInterruptMode(mode: "immediate" | "wait"): void;
412
+ getInterruptMode(): "immediate" | "wait";
413
+ setTools(t: AgentTool<any>[]): void;
414
+ replaceMessages(ms: AgentMessage[]): void;
415
+ replaceQueues(steering: AgentMessage[], followUp: AgentMessage[]): void;
416
+ appendMessage(m: AgentMessage): void;
417
+ popMessage(): AgentMessage | undefined;
418
+ /**
419
+ * Queue a steering message to interrupt the agent mid-run.
420
+ * Delivered after current tool execution, skips remaining tools.
421
+ */
422
+ steer(m: AgentMessage): void;
423
+ /**
424
+ * Queue a follow-up message to be processed after the agent finishes.
425
+ * Delivered only when agent has no more tool calls or steering messages.
426
+ */
427
+ followUp(m: AgentMessage): void;
428
+ clearSteeringQueue(): void;
429
+ clearFollowUpQueue(): void;
430
+ /**
431
+ * Drop tool-directive state retained across a gate-stopped run: the
432
+ * deferred hard choice and the soft-requirement lifecycle.
433
+ */
434
+ clearDeferredToolDirectives(): void;
435
+ clearAllQueues(): void;
436
+ hasQueuedMessages(): boolean;
437
+ /** Non-consuming view of the pending steering queue (insertion order, newest
438
+ * last). The session layer derives its queued-message display/count from
439
+ * this live view instead of a mirror, so the agent-core queue stays the
440
+ * single source of truth. */
441
+ peekSteeringQueue(): readonly AgentMessage[];
442
+ /** Non-consuming view of the pending follow-up queue. See
443
+ * {@link peekSteeringQueue}. */
444
+ peekFollowUpQueue(): readonly AgentMessage[];
445
+ get isAborting(): boolean;
446
+ /**
447
+ * Remove and return the last steering message from the queue (LIFO).
448
+ * Used by dequeue keybinding.
449
+ */
450
+ popLastSteer(): AgentMessage | undefined;
451
+ /**
452
+ * Remove and return the last follow-up message from the queue (LIFO).
453
+ * Used by dequeue keybinding.
454
+ */
455
+ popLastFollowUp(): AgentMessage | undefined;
456
+ clearMessages(): void;
457
+ abort(reason?: unknown): void;
458
+ waitForIdle(): Promise<void>;
459
+ reset(): void;
460
+ /** Send a prompt with an AgentMessage */
461
+ prompt(message: AgentMessage | AgentMessage[], options?: AgentPromptOptions): Promise<void>;
462
+ prompt(input: string, options?: AgentPromptOptions): Promise<void>;
463
+ prompt(input: string, images?: ImageContent[], options?: AgentPromptOptions): Promise<void>;
464
+ continue(signal?: AbortSignal): Promise<void>;
465
+ }