@sayknow-cli/agent-core 0.4.1 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/types/agent-loop.d.ts +108 -0
- package/dist/types/agent.d.ts +443 -0
- package/dist/types/append-only-context.d.ts +137 -0
- package/dist/types/compaction/branch-summarization.d.ts +103 -0
- package/dist/types/compaction/compaction.d.ts +323 -0
- package/dist/types/compaction/entries.d.ts +124 -0
- package/dist/types/compaction/errors.d.ts +26 -0
- package/dist/types/compaction/index.d.ts +11 -0
- package/dist/types/compaction/messages.d.ts +61 -0
- package/dist/types/compaction/openai.d.ts +63 -0
- package/dist/types/compaction/pruning.d.ts +73 -0
- package/dist/types/compaction/utils.d.ts +32 -0
- package/dist/types/compaction.d.ts +1 -0
- package/dist/types/harmony-leak.d.ts +100 -0
- package/dist/types/image-placeholder-guard.d.ts +4 -0
- package/dist/types/index.d.ts +11 -0
- package/dist/types/proxy.d.ts +95 -0
- package/dist/types/run-collector.d.ts +196 -0
- package/dist/types/telemetry.d.ts +596 -0
- package/dist/types/thinking.d.ts +18 -0
- package/dist/types/types.d.ts +526 -0
- package/package.json +11 -10
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent loop that works with AgentMessage throughout.
|
|
3
|
+
* Transforms to Message[] only at the LLM call boundary.
|
|
4
|
+
*/
|
|
5
|
+
import { type Context, EventStream } from "@sayknow-cli/ai";
|
|
6
|
+
import { type AgentRunCoverage, type AgentRunSummary } from "./run-collector";
|
|
7
|
+
import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, StreamFn } from "./types";
|
|
8
|
+
/** Sentinel returned by the abort race in `streamAssistantResponse`. */
|
|
9
|
+
/**
|
|
10
|
+
* Defensive caps for a provisional managed attempt. These are intentionally
|
|
11
|
+
* well above ordinary streamed responses; they only bound memory when an
|
|
12
|
+
* upstream emits an unbounded event stream before the attempt can commit.
|
|
13
|
+
*/
|
|
14
|
+
export declare const MANAGED_ATTEMPT_MAX_STAGED_EVENTS = 10000;
|
|
15
|
+
export declare const MANAGED_ATTEMPT_MAX_STAGED_BYTES: number;
|
|
16
|
+
/**
|
|
17
|
+
* Start an agent loop with a new prompt message.
|
|
18
|
+
* The prompt is added to the context and events are emitted for it.
|
|
19
|
+
*/
|
|
20
|
+
export declare function agentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn, emitManagedAgentStart?: boolean): EventStream<AgentEvent, AgentMessage[]>;
|
|
21
|
+
/**
|
|
22
|
+
* Continue an agent loop from the current context without adding a new message.
|
|
23
|
+
* Used for retries - context already has user message or tool results.
|
|
24
|
+
*
|
|
25
|
+
* **Important:** The last message in context must convert to a `user` or `toolResult` message
|
|
26
|
+
* via `convertToLlm`. If it doesn't, the LLM provider will reject the request.
|
|
27
|
+
* This cannot be validated here since `convertToLlm` is only called once per turn.
|
|
28
|
+
*/
|
|
29
|
+
export declare function agentLoopContinue(context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn, emitManagedAgentStart?: boolean): EventStream<AgentEvent, AgentMessage[]>;
|
|
30
|
+
/**
|
|
31
|
+
* Hard work budget for one degraded snapshot: every visited node AND every
|
|
32
|
+
* enumerated own key is debited against this budget before it is processed
|
|
33
|
+
* (accessor keys and re-visits of shared objects included), and any remainder
|
|
34
|
+
* collapses to the deterministic `"[truncated]"` placeholder. Well above
|
|
35
|
+
* ordinary streamed events; it only bounds hostile graphs.
|
|
36
|
+
*/
|
|
37
|
+
export declare const MANAGED_SNAPSHOT_MAX_NODES = 100000;
|
|
38
|
+
/**
|
|
39
|
+
* Cycle-aware deep clone that always returns a detached, JSON-serializable
|
|
40
|
+
* value. Used whenever a detached snapshot cannot be safely obtained or
|
|
41
|
+
* measured: after `structuredClone` fails, and again when a (successfully
|
|
42
|
+
* cloned) snapshot cannot be serialized for byte accounting.
|
|
43
|
+
*
|
|
44
|
+
* Totality rules — the walk must never dispatch through payload-controlled
|
|
45
|
+
* code, throw, or do unbounded work:
|
|
46
|
+
* - proxies (revoked or live) are collapsed to `"[unserializable]"` BEFORE
|
|
47
|
+
* any reflective operation, so `ownKeys`/descriptor traps are never
|
|
48
|
+
* dispatched (`util.types.isProxy` identifies proxies without touching
|
|
49
|
+
* their handlers);
|
|
50
|
+
* - only intrinsics are used on the remaining ordinary objects (no
|
|
51
|
+
* `input.map`, no `input.getTime()`, no `input.length` reads);
|
|
52
|
+
* - arrays are enumerated through their own present keys, never their
|
|
53
|
+
* declared length, so a sparse array cannot force a dense allocation
|
|
54
|
+
* proportional to `length`; sparse/exotic arrays degrade to a null-proto
|
|
55
|
+
* record of their present indices, and the dense-shape decision verifies
|
|
56
|
+
* every index against its ordinal;
|
|
57
|
+
* - the walk debits `maxNodes` budget per visited node and per enumerated
|
|
58
|
+
* key before processing it; anything beyond the budget becomes
|
|
59
|
+
* `"[truncated]"` (the one linear primitive per visited node is a single
|
|
60
|
+
* `Object.keys` call on a non-proxy object the process already holds);
|
|
61
|
+
* - property values are read via own-property descriptors, so accessors are
|
|
62
|
+
* never invoked (a snapshot must not cause observable side effects) and are
|
|
63
|
+
* replaced with `"[accessor]"`;
|
|
64
|
+
* - functions/symbols and any property that cannot be read safely become
|
|
65
|
+
* short placeholders, `bigint` becomes its decimal string, and references
|
|
66
|
+
* back into the current path collapse to `"[Circular]"`;
|
|
67
|
+
* - records are built on a null prototype so a `__proto__` key cannot mutate
|
|
68
|
+
* the clone's prototype chain.
|
|
69
|
+
*
|
|
70
|
+
* Exported for direct regression coverage of the budget accounting; runtime
|
|
71
|
+
* callers use the default budget via {@link managedAttemptSnapshot}.
|
|
72
|
+
*/
|
|
73
|
+
export declare function sanitizedDetachedClone<T>(value: T, maxNodes?: number): T;
|
|
74
|
+
/**
|
|
75
|
+
* Detailed-result handle returned by {@link agentLoopDetailed}. Adds the
|
|
76
|
+
* run-level telemetry/coverage rollup to the existing `AgentMessage[]`
|
|
77
|
+
* payload without changing the resolved type of `stream.result()`.
|
|
78
|
+
*/
|
|
79
|
+
export interface AgentLoopDetailedResult {
|
|
80
|
+
readonly messages: AgentMessage[];
|
|
81
|
+
readonly telemetry: AgentRunSummary | undefined;
|
|
82
|
+
readonly coverage: AgentRunCoverage | undefined;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Convenience wrapper over {@link agentLoop} that exposes the run-level
|
|
86
|
+
* summary + coverage alongside the messages. The returned `stream` is the
|
|
87
|
+
* same `EventStream` callers already consume; `detailed()` awaits the
|
|
88
|
+
* stream's `agent_end` event and returns the additive fields.
|
|
89
|
+
*
|
|
90
|
+
* Existing `stream.result()` semantics are preserved — it still resolves to
|
|
91
|
+
* `AgentMessage[]`. Use {@link agentLoopDetailed} when you need the rollup;
|
|
92
|
+
* use {@link agentLoop} when you do not.
|
|
93
|
+
*/
|
|
94
|
+
export declare function agentLoopDetailed(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): {
|
|
95
|
+
readonly stream: EventStream<AgentEvent, AgentMessage[]>;
|
|
96
|
+
readonly detailed: () => Promise<AgentLoopDetailedResult>;
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* Like {@link agentLoopDetailed} but built on top of
|
|
100
|
+
* {@link agentLoopContinue}.
|
|
101
|
+
*/
|
|
102
|
+
export declare function agentLoopContinueDetailed(context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): {
|
|
103
|
+
readonly stream: EventStream<AgentEvent, AgentMessage[]>;
|
|
104
|
+
readonly detailed: () => Promise<AgentLoopDetailedResult>;
|
|
105
|
+
};
|
|
106
|
+
export declare function normalizeMessagesForProvider(messages: Context["messages"], model: AgentLoopConfig["model"]): Context["messages"];
|
|
107
|
+
export declare const INTENT_FIELD = "_i";
|
|
108
|
+
export declare function normalizeTools(tools: AgentContext["tools"], injectIntent: boolean): Context["tools"];
|
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
/** Agent class that uses the agent-loop directly.
|
|
2
|
+
* No transport abstraction - calls streamSimple via the loop.
|
|
3
|
+
*/
|
|
4
|
+
import { type AssistantMessage, type AssistantMessageEvent, type CursorExecHandlers, type CursorToolResultHandler, type Effort, type ImageContent, type Message, type Model, type ProviderSessionState, type ServiceTier, type SimpleStreamOptions, type ThinkingBudgets, type ToolChoice } from "@sayknow-cli/ai";
|
|
5
|
+
import type { AppendOnlyContextManager } from "./append-only-context";
|
|
6
|
+
import type { HarmonyAuditEvent } from "./harmony-leak";
|
|
7
|
+
import type { AgentEvent, AgentLoopConfig, AgentMessage, AgentState, AgentTool, AgentToolContext, ManagedLogicalRunId, RunTerminalRequest, StreamFn, ToolCallContext } from "./types";
|
|
8
|
+
/**
|
|
9
|
+
* Whether persisted history ends at a point where a new model turn can resume.
|
|
10
|
+
* Assistant-ended histories require an in-memory queued message and are handled
|
|
11
|
+
* separately by `Agent.continue()`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function canContinuePersistedHistory(messages: readonly AgentMessage[]): boolean;
|
|
14
|
+
export declare class ManagedCursorInvariantError extends Error {
|
|
15
|
+
constructor(message?: string);
|
|
16
|
+
}
|
|
17
|
+
export declare class AgentBusyError extends Error {
|
|
18
|
+
constructor(message?: string);
|
|
19
|
+
}
|
|
20
|
+
export interface AgentOptions {
|
|
21
|
+
initialState?: Partial<AgentState>;
|
|
22
|
+
/**
|
|
23
|
+
* Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
|
|
24
|
+
* Default filters to user/assistant/toolResult and converts attachments.
|
|
25
|
+
*/
|
|
26
|
+
convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
|
|
27
|
+
/**
|
|
28
|
+
* Optional transform applied to context before convertToLlm.
|
|
29
|
+
* Use for context pruning, injecting external context, etc.
|
|
30
|
+
*/
|
|
31
|
+
transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
|
|
32
|
+
/**
|
|
33
|
+
* Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
|
|
34
|
+
*/
|
|
35
|
+
steeringMode?: "all" | "one-at-a-time";
|
|
36
|
+
/**
|
|
37
|
+
* Follow-up mode: "all" = send all follow-up messages at once, "one-at-a-time" = one per turn
|
|
38
|
+
*/
|
|
39
|
+
followUpMode?: "all" | "one-at-a-time";
|
|
40
|
+
/**
|
|
41
|
+
* When to interrupt tool execution for steering messages.
|
|
42
|
+
* - "immediate": check after each tool call (default)
|
|
43
|
+
* - "wait": defer steering until the current turn completes
|
|
44
|
+
*/
|
|
45
|
+
interruptMode?: "immediate" | "wait";
|
|
46
|
+
/** Cooperative pause checkpoint passed through to AgentLoopConfig.shouldPause. */
|
|
47
|
+
shouldPause?: AgentLoopConfig["shouldPause"];
|
|
48
|
+
/**
|
|
49
|
+
* API format for Kimi Code provider: "openai" or "anthropic" (default: "anthropic")
|
|
50
|
+
*/
|
|
51
|
+
kimiApiFormat?: "openai" | "anthropic";
|
|
52
|
+
/** Hint that websocket transport should be preferred when supported by the provider implementation. */
|
|
53
|
+
preferWebsockets?: boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Custom stream function (for proxy backends, etc.). Default uses streamSimple.
|
|
56
|
+
*/
|
|
57
|
+
streamFn?: StreamFn;
|
|
58
|
+
/**
|
|
59
|
+
* Optional session identifier forwarded to LLM providers.
|
|
60
|
+
* Used by providers that support session-based caching (e.g., OpenAI code provider).
|
|
61
|
+
*/
|
|
62
|
+
sessionId?: string;
|
|
63
|
+
/** Provider-facing cache/session affinity identifier. */
|
|
64
|
+
providerSessionId?: string;
|
|
65
|
+
/**
|
|
66
|
+
* Shared provider state map for session-scoped transport/session caches.
|
|
67
|
+
*/
|
|
68
|
+
providerSessionState?: Map<string, ProviderSessionState>;
|
|
69
|
+
/**
|
|
70
|
+
* Resolves an API key dynamically for each LLM call.
|
|
71
|
+
* Useful for expiring tokens (e.g., GitHub Copilot OAuth).
|
|
72
|
+
*/
|
|
73
|
+
getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
|
|
74
|
+
getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
|
|
75
|
+
/**
|
|
76
|
+
* Inspect or replace provider payloads before they are sent.
|
|
77
|
+
*/
|
|
78
|
+
onPayload?: SimpleStreamOptions["onPayload"];
|
|
79
|
+
/**
|
|
80
|
+
* Inspect provider response metadata after headers arrive and before streaming body consumption.
|
|
81
|
+
*/
|
|
82
|
+
onResponse?: SimpleStreamOptions["onResponse"];
|
|
83
|
+
/**
|
|
84
|
+
* Inspect raw Server-Sent Events from HTTP streaming providers.
|
|
85
|
+
*/
|
|
86
|
+
onSseEvent?: SimpleStreamOptions["onSseEvent"];
|
|
87
|
+
/**
|
|
88
|
+
* Inspect assistant streaming events before they are emitted to subscribers.
|
|
89
|
+
* Use this when abort decisions must happen before buffered events continue flowing.
|
|
90
|
+
*/
|
|
91
|
+
onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
|
|
92
|
+
/** Called for non-content tool-choice incapability stream events. */
|
|
93
|
+
onToolChoiceIncapability?: AgentLoopConfig["onToolChoiceIncapability"];
|
|
94
|
+
/**
|
|
95
|
+
* Called when GPT-5 Harmony protocol leakage is detected and mitigated.
|
|
96
|
+
*/
|
|
97
|
+
onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
|
|
98
|
+
/**
|
|
99
|
+
* Custom token budgets for thinking levels (token-based providers only).
|
|
100
|
+
*/
|
|
101
|
+
thinkingBudgets?: ThinkingBudgets;
|
|
102
|
+
/**
|
|
103
|
+
* Sampling temperature for LLM calls. `undefined` uses provider default.
|
|
104
|
+
*/
|
|
105
|
+
temperature?: number;
|
|
106
|
+
/** Additional sampling controls for providers that support them. */
|
|
107
|
+
topP?: number;
|
|
108
|
+
topK?: number;
|
|
109
|
+
minP?: number;
|
|
110
|
+
presencePenalty?: number;
|
|
111
|
+
repetitionPenalty?: number;
|
|
112
|
+
serviceTier?: ServiceTier;
|
|
113
|
+
/**
|
|
114
|
+
* If true, request that the underlying provider omit reasoning/thinking summaries
|
|
115
|
+
* from the response. The model still reasons internally; only the human-readable
|
|
116
|
+
* summary stream is suppressed. Useful when the UI hides thinking blocks anyway.
|
|
117
|
+
*/
|
|
118
|
+
hideThinkingSummary?: boolean;
|
|
119
|
+
/**
|
|
120
|
+
* Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
|
|
121
|
+
* If the server's requested delay exceeds this value, the request fails immediately,
|
|
122
|
+
* allowing higher-level retry logic to handle it with user visibility.
|
|
123
|
+
* Default: 60000 (60 seconds). Set to 0 to disable the cap.
|
|
124
|
+
*/
|
|
125
|
+
maxRetryDelayMs?: number;
|
|
126
|
+
/** Provider request retry budget. Counts retries, not the initial attempt. */
|
|
127
|
+
requestMaxRetries?: number;
|
|
128
|
+
/** Provider stream replay retry budget. Counts retries, not the initial attempt. */
|
|
129
|
+
streamMaxRetries?: number;
|
|
130
|
+
/**
|
|
131
|
+
* Provides tool execution context, resolved per tool call.
|
|
132
|
+
* Use for late-bound UI or session state access.
|
|
133
|
+
*/
|
|
134
|
+
getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
|
|
135
|
+
/**
|
|
136
|
+
* Optional transform applied to tool call arguments before execution.
|
|
137
|
+
* Use for deobfuscating secrets or rewriting arguments.
|
|
138
|
+
*/
|
|
139
|
+
transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
|
|
140
|
+
/** Enable intent tracing schema injection/stripping in the harness. */
|
|
141
|
+
intentTracing?: boolean;
|
|
142
|
+
/** Dynamic tool choice override, resolved per LLM call. */
|
|
143
|
+
getToolChoice?: () => ToolChoice | undefined;
|
|
144
|
+
/**
|
|
145
|
+
* Cursor exec handlers for local tool execution.
|
|
146
|
+
*/
|
|
147
|
+
cursorExecHandlers?: CursorExecHandlers;
|
|
148
|
+
/**
|
|
149
|
+
* Cursor tool result callback for exec tool responses.
|
|
150
|
+
*/
|
|
151
|
+
cursorOnToolResult?: CursorToolResultHandler;
|
|
152
|
+
/**
|
|
153
|
+
* Called after a tool call has been validated and is about to execute.
|
|
154
|
+
* See {@link AgentLoopConfig.beforeToolCall} for full semantics.
|
|
155
|
+
*/
|
|
156
|
+
beforeToolCall?: AgentLoopConfig["beforeToolCall"];
|
|
157
|
+
/**
|
|
158
|
+
* Called after a tool finishes executing, before `tool_execution_end` and the tool-result
|
|
159
|
+
* message are emitted. See {@link AgentLoopConfig.afterToolCall} for full semantics.
|
|
160
|
+
*/
|
|
161
|
+
afterToolCall?: AgentLoopConfig["afterToolCall"];
|
|
162
|
+
/**
|
|
163
|
+
* Opt-in OpenTelemetry instrumentation. Passing `{}` enables the loop's
|
|
164
|
+
* GenAI-semantic-convention spans using the global tracer provider. See
|
|
165
|
+
* {@link AgentLoopConfig.telemetry} for the full surface.
|
|
166
|
+
*/
|
|
167
|
+
telemetry?: AgentLoopConfig["telemetry"];
|
|
168
|
+
/**
|
|
169
|
+
* Immutable context mode — stabilizes system prompt + tool spec bytes
|
|
170
|
+
* across turns so DeepSeek/Anthropic prefix caches hit at maximum rate.
|
|
171
|
+
*/
|
|
172
|
+
appendOnlyContext?: AppendOnlyContextManager;
|
|
173
|
+
}
|
|
174
|
+
export interface AgentPromptOptions {
|
|
175
|
+
toolChoice?: ToolChoice;
|
|
176
|
+
/** Disable transport replay; fallback accounting is owned by the caller. */
|
|
177
|
+
fallbackManaged?: boolean;
|
|
178
|
+
/** Called synchronously after this invocation claims the agent run, before asynchronous provider work. */
|
|
179
|
+
onRunAccepted?: () => void;
|
|
180
|
+
/** Called once immediately before every managed upstream request. */
|
|
181
|
+
nextFallbackAttempt?: AgentLoopConfig["nextFallbackAttempt"];
|
|
182
|
+
/** Called after a managed upstream request is accepted and committed. */
|
|
183
|
+
onManagedAttemptAccepted?: AgentLoopConfig["onManagedAttemptAccepted"];
|
|
184
|
+
/** Receives a discarded managed attempt without exposing assistant lifecycle events. */
|
|
185
|
+
onManagedAttemptOutcome?: AgentLoopConfig["onManagedAttemptOutcome"];
|
|
186
|
+
}
|
|
187
|
+
export type AgentQueueSnapshot = {
|
|
188
|
+
steering: AgentMessage[];
|
|
189
|
+
followUp: AgentMessage[];
|
|
190
|
+
};
|
|
191
|
+
export declare class Agent {
|
|
192
|
+
#private;
|
|
193
|
+
get intentTracing(): boolean;
|
|
194
|
+
streamFn: StreamFn;
|
|
195
|
+
getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
|
|
196
|
+
getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
|
|
197
|
+
/**
|
|
198
|
+
* Hook invoked after tool arguments are validated and before execution.
|
|
199
|
+
* Reassign at any time to swap the implementation (e.g. on extension reload).
|
|
200
|
+
*/
|
|
201
|
+
beforeToolCall?: AgentLoopConfig["beforeToolCall"];
|
|
202
|
+
/**
|
|
203
|
+
* Hook invoked after tool execution and before `tool_execution_end` / tool-result
|
|
204
|
+
* message emission. Reassign at any time to swap the implementation.
|
|
205
|
+
*/
|
|
206
|
+
afterToolCall?: AgentLoopConfig["afterToolCall"];
|
|
207
|
+
constructor(opts?: AgentOptions);
|
|
208
|
+
/**
|
|
209
|
+
* Get the current session ID used for provider caching.
|
|
210
|
+
*/
|
|
211
|
+
get sessionId(): string | undefined;
|
|
212
|
+
/**
|
|
213
|
+
* Set the session ID for provider caching.
|
|
214
|
+
* Call this when switching sessions (new session, branch, resume).
|
|
215
|
+
*/
|
|
216
|
+
set sessionId(value: string | undefined);
|
|
217
|
+
get providerSessionId(): string | undefined;
|
|
218
|
+
set providerSessionId(value: string | undefined);
|
|
219
|
+
/**
|
|
220
|
+
* Whether websocket transport is preferred when the provider implementation
|
|
221
|
+
* supports it. Read by maintenance one-shot calls (compaction, handoff,
|
|
222
|
+
* branch summary) so they forward the same transport preference as live turns.
|
|
223
|
+
*/
|
|
224
|
+
get preferWebsockets(): boolean | undefined;
|
|
225
|
+
/**
|
|
226
|
+
* Static metadata forwarded to every API request when no resolver is installed
|
|
227
|
+
* (e.g. `metadata.user_id` for Anthropic session attribution). Setting this
|
|
228
|
+
* clears any installed resolver.
|
|
229
|
+
*
|
|
230
|
+
* For live/provider-aware metadata (e.g. Anthropic OAuth `account_uuid` that
|
|
231
|
+
* must reflect the credential selected per-request), use
|
|
232
|
+
* {@link setMetadataResolver} and read via {@link metadataForProvider}.
|
|
233
|
+
*/
|
|
234
|
+
get metadata(): Record<string, unknown> | undefined;
|
|
235
|
+
set metadata(value: Record<string, unknown> | undefined);
|
|
236
|
+
/**
|
|
237
|
+
* Resolve request metadata for the given provider at call time. When a
|
|
238
|
+
* resolver is installed via {@link setMetadataResolver}, it is invoked with
|
|
239
|
+
* the provider string so the result can be scoped (e.g. `account_uuid` is
|
|
240
|
+
* only included for `"anthropic"` requests). Falls back to the static
|
|
241
|
+
* {@link metadata} value when no resolver is set.
|
|
242
|
+
*/
|
|
243
|
+
metadataForProvider(provider: string): Record<string, unknown> | undefined;
|
|
244
|
+
/**
|
|
245
|
+
* Install a function that resolves request metadata at call time. The
|
|
246
|
+
* resolver receives the target provider string and can gate provider-specific
|
|
247
|
+
* fields (e.g. `account_uuid` only for `"anthropic"`). Invoked per LLM
|
|
248
|
+
* request by `agent-loop` after `getApiKey` selects the session-sticky
|
|
249
|
+
* credential. Pass `undefined` to clear and revert to the static
|
|
250
|
+
* {@link metadata} value.
|
|
251
|
+
*/
|
|
252
|
+
setMetadataResolver(resolver: ((provider: string) => Record<string, unknown> | undefined) | undefined): void;
|
|
253
|
+
/**
|
|
254
|
+
* Read the active OpenTelemetry configuration. Returns `undefined` when
|
|
255
|
+
* instrumentation is disabled. Callers spawning child runs (e.g. subagent
|
|
256
|
+
* dispatch) forward this to the child's loop so its spans appear under the
|
|
257
|
+
* parent's active context with the subagent's own identity stamped.
|
|
258
|
+
*/
|
|
259
|
+
get telemetry(): AgentLoopConfig["telemetry"] | undefined;
|
|
260
|
+
/**
|
|
261
|
+
* Replace the active OpenTelemetry configuration. Pass `undefined` to
|
|
262
|
+
* disable instrumentation. Applies to the *next* `agentLoop` invocation —
|
|
263
|
+
* in-flight loops keep the configuration they started with.
|
|
264
|
+
*/
|
|
265
|
+
setTelemetry(telemetry: AgentLoopConfig["telemetry"] | undefined): void;
|
|
266
|
+
/**
|
|
267
|
+
* Get provider-scoped mutable session state store.
|
|
268
|
+
*/
|
|
269
|
+
get providerSessionState(): Map<string, ProviderSessionState> | undefined;
|
|
270
|
+
/**
|
|
271
|
+
* Set provider-scoped mutable session state store.
|
|
272
|
+
*/
|
|
273
|
+
set providerSessionState(value: Map<string, ProviderSessionState> | undefined);
|
|
274
|
+
/**
|
|
275
|
+
* Get the current thinking budgets.
|
|
276
|
+
*/
|
|
277
|
+
get thinkingBudgets(): ThinkingBudgets | undefined;
|
|
278
|
+
/**
|
|
279
|
+
* Set custom thinking budgets for token-based providers.
|
|
280
|
+
*/
|
|
281
|
+
set thinkingBudgets(value: ThinkingBudgets | undefined);
|
|
282
|
+
/**
|
|
283
|
+
* Get the current sampling temperature.
|
|
284
|
+
*/
|
|
285
|
+
get temperature(): number | undefined;
|
|
286
|
+
/**
|
|
287
|
+
* Set sampling temperature for LLM calls. `undefined` uses provider default.
|
|
288
|
+
*/
|
|
289
|
+
set temperature(value: number | undefined);
|
|
290
|
+
get topP(): number | undefined;
|
|
291
|
+
set topP(value: number | undefined);
|
|
292
|
+
get topK(): number | undefined;
|
|
293
|
+
set topK(value: number | undefined);
|
|
294
|
+
get minP(): number | undefined;
|
|
295
|
+
set minP(value: number | undefined);
|
|
296
|
+
get presencePenalty(): number | undefined;
|
|
297
|
+
set presencePenalty(value: number | undefined);
|
|
298
|
+
get repetitionPenalty(): number | undefined;
|
|
299
|
+
set repetitionPenalty(value: number | undefined);
|
|
300
|
+
get serviceTier(): ServiceTier | undefined;
|
|
301
|
+
set serviceTier(value: ServiceTier | undefined);
|
|
302
|
+
get hideThinkingSummary(): boolean | undefined;
|
|
303
|
+
set hideThinkingSummary(value: boolean | undefined);
|
|
304
|
+
/**
|
|
305
|
+
* Get the current max retry delay in milliseconds.
|
|
306
|
+
*/
|
|
307
|
+
get maxRetryDelayMs(): number | undefined;
|
|
308
|
+
/**
|
|
309
|
+
* Set the maximum delay to wait for server-requested retries.
|
|
310
|
+
* Set to 0 to disable the cap.
|
|
311
|
+
*/
|
|
312
|
+
set maxRetryDelayMs(value: number | undefined);
|
|
313
|
+
get requestMaxRetries(): number | undefined;
|
|
314
|
+
set requestMaxRetries(value: number | undefined);
|
|
315
|
+
get streamMaxRetries(): number | undefined;
|
|
316
|
+
set streamMaxRetries(value: number | undefined);
|
|
317
|
+
get state(): AgentState;
|
|
318
|
+
get contextRevision(): number;
|
|
319
|
+
get appendOnlyContext(): AppendOnlyContextManager | undefined;
|
|
320
|
+
setAppendOnlyContext(manager?: AppendOnlyContextManager): void;
|
|
321
|
+
subscribe(fn: (e: AgentEvent) => void): () => void;
|
|
322
|
+
setProviderResponseInterceptor(fn: SimpleStreamOptions["onResponse"] | undefined): void;
|
|
323
|
+
setRawSseEventInterceptor(fn: SimpleStreamOptions["onSseEvent"] | undefined): void;
|
|
324
|
+
setAssistantMessageEventInterceptor(fn: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined): void;
|
|
325
|
+
setOnBeforeYield(fn: (() => Promise<void> | void) | undefined): void;
|
|
326
|
+
setShouldPause(fn: AgentLoopConfig["shouldPause"] | undefined): void;
|
|
327
|
+
setMaintainContext(fn: AgentLoopConfig["maintainContext"] | undefined): void;
|
|
328
|
+
emitExternalEvent(event: AgentEvent): void;
|
|
329
|
+
createExternalEventEmitterForCurrentRun(): ((event: AgentEvent) => void) | undefined;
|
|
330
|
+
setSystemPrompt(v: string[]): void;
|
|
331
|
+
setModel(m: Model | undefined): void;
|
|
332
|
+
setThinkingLevel(l: Effort | undefined): void;
|
|
333
|
+
setSteeringMode(mode: "all" | "one-at-a-time"): void;
|
|
334
|
+
getSteeringMode(): "all" | "one-at-a-time";
|
|
335
|
+
setFollowUpMode(mode: "all" | "one-at-a-time"): void;
|
|
336
|
+
getFollowUpMode(): "all" | "one-at-a-time";
|
|
337
|
+
setInterruptMode(mode: "immediate" | "wait"): void;
|
|
338
|
+
getInterruptMode(): "immediate" | "wait";
|
|
339
|
+
setTools(t: AgentTool<any>[]): void;
|
|
340
|
+
replaceMessages(ms: AgentMessage[]): void;
|
|
341
|
+
appendMessage(m: AgentMessage): void;
|
|
342
|
+
popMessage(): AgentMessage | undefined;
|
|
343
|
+
/**
|
|
344
|
+
* For callers that mutate committed messages or the system prompt in place
|
|
345
|
+
* outside Agent-owned mutators.
|
|
346
|
+
*/
|
|
347
|
+
touchContext(): void;
|
|
348
|
+
/**
|
|
349
|
+
* Queue a steering message to interrupt the agent mid-run.
|
|
350
|
+
* Delivered after current tool execution, skips remaining tools.
|
|
351
|
+
*/
|
|
352
|
+
steer(m: AgentMessage): void;
|
|
353
|
+
/**
|
|
354
|
+
* Queue a follow-up message to be processed after the agent finishes.
|
|
355
|
+
* Delivered only when agent has no more tool calls or steering messages.
|
|
356
|
+
*
|
|
357
|
+
* `forceOneAtATime` lets UI composer queues preserve prompt-by-prompt
|
|
358
|
+
* delivery even when the session-wide follow-up mode is set to `all` for
|
|
359
|
+
* other integration paths.
|
|
360
|
+
*/
|
|
361
|
+
followUp(m: AgentMessage, options?: {
|
|
362
|
+
forceOneAtATime?: boolean;
|
|
363
|
+
}): void;
|
|
364
|
+
clearSteeringQueue(): void;
|
|
365
|
+
clearFollowUpQueue(): void;
|
|
366
|
+
clearAllQueues(): void;
|
|
367
|
+
hasQueuedMessages(): boolean;
|
|
368
|
+
hasQueuedSteering(): boolean;
|
|
369
|
+
/**
|
|
370
|
+
* Snapshot the steering queue without mutating it. Used to preserve queued
|
|
371
|
+
* steering across maintenance ops (compaction/handoff) that call reset().
|
|
372
|
+
*/
|
|
373
|
+
snapshotSteering(): AgentMessage[];
|
|
374
|
+
/**
|
|
375
|
+
* Restore previously snapshotted steering messages ahead of any newly
|
|
376
|
+
* queued ones. No-op for an empty snapshot.
|
|
377
|
+
*/
|
|
378
|
+
restoreSteering(messages: AgentMessage[]): void;
|
|
379
|
+
/** Snapshot the follow-up queue without mutating it. */
|
|
380
|
+
snapshotFollowUp(): AgentMessage[];
|
|
381
|
+
/** Restore previously snapshotted follow-up messages ahead of any newly queued ones. */
|
|
382
|
+
restoreFollowUp(messages: AgentMessage[]): void;
|
|
383
|
+
/** Snapshot both executable queues as one atomic session-level view. */
|
|
384
|
+
snapshotQueues(): AgentQueueSnapshot;
|
|
385
|
+
/** Replace both executable queues with a prior snapshot. */
|
|
386
|
+
restoreQueues(snapshot: AgentQueueSnapshot): void;
|
|
387
|
+
/**
|
|
388
|
+
* Remove and return the last steering message from the queue (LIFO).
|
|
389
|
+
* Used by dequeue keybinding.
|
|
390
|
+
*/
|
|
391
|
+
popLastSteer(): AgentMessage | undefined;
|
|
392
|
+
removeSteerAt(index: number): AgentMessage | undefined;
|
|
393
|
+
moveSteer(fromIndex: number, toIndex: number): boolean;
|
|
394
|
+
/**
|
|
395
|
+
* Remove and return the last follow-up message from the queue (LIFO).
|
|
396
|
+
* Used by dequeue keybinding.
|
|
397
|
+
*/
|
|
398
|
+
popLastFollowUp(): AgentMessage | undefined;
|
|
399
|
+
removeFollowUpAt(index: number): AgentMessage | undefined;
|
|
400
|
+
moveFollowUp(fromIndex: number, toIndex: number): boolean;
|
|
401
|
+
/** Remove queued steering+follow-up messages matching `predicate`, preserving order of the rest. */
|
|
402
|
+
removeQueuedMessages(predicate: (message: AgentMessage) => boolean): {
|
|
403
|
+
steering: number;
|
|
404
|
+
followUp: number;
|
|
405
|
+
total: number;
|
|
406
|
+
};
|
|
407
|
+
clearMessages(): void;
|
|
408
|
+
abort(): void;
|
|
409
|
+
/**
|
|
410
|
+
* Force the current run out of the busy/streaming state when cooperative abort
|
|
411
|
+
* did not drain. The abandoned provider/tool stream may still settle later, so
|
|
412
|
+
* #runLoop guards every state mutation with a run id.
|
|
413
|
+
*/
|
|
414
|
+
forceAbort(reason?: string): boolean;
|
|
415
|
+
waitForIdle(): Promise<void>;
|
|
416
|
+
/** The active per-attempt run identifier. */
|
|
417
|
+
get activeRunId(): number | undefined;
|
|
418
|
+
/**
|
|
419
|
+
* Stable identifier for the active managed logical run, shared by every retry
|
|
420
|
+
* attempt. Pass this value to requestRunTerminal(); never retain activeRunId
|
|
421
|
+
* for managed terminal completion.
|
|
422
|
+
*/
|
|
423
|
+
get currentManagedLogicalRunId(): ManagedLogicalRunId | undefined;
|
|
424
|
+
/**
|
|
425
|
+
* Request terminal completion through the single logical-run keyed finalizer.
|
|
426
|
+
*
|
|
427
|
+
* For managed runs, logicalRunId must be currentManagedLogicalRunId from any
|
|
428
|
+
* attempt in the retry chain. Non-managed runs use their activeRunId. Terminal
|
|
429
|
+
* requests with messages emit a committed message_start/message_end lifecycle
|
|
430
|
+
* for each diagnostic before agent_end. Requests without messages (such as
|
|
431
|
+
* cancellation) emit only agent_end.
|
|
432
|
+
*/
|
|
433
|
+
requestRunTerminal(logicalRunId: ManagedLogicalRunId, request: RunTerminalRequest): boolean;
|
|
434
|
+
reset(): void;
|
|
435
|
+
/** Send a prompt with an AgentMessage */
|
|
436
|
+
prompt(message: AgentMessage | AgentMessage[], options?: AgentPromptOptions): Promise<void>;
|
|
437
|
+
prompt(input: string, options?: AgentPromptOptions): Promise<void>;
|
|
438
|
+
prompt(input: string, images?: ImageContent[], options?: AgentPromptOptions): Promise<void>;
|
|
439
|
+
/**
|
|
440
|
+
* Continue from current context (used for retries and resuming queued messages).
|
|
441
|
+
*/
|
|
442
|
+
continue(options?: AgentPromptOptions): Promise<void>;
|
|
443
|
+
}
|