@sayknow-cli/agent-core 0.3.13 → 0.3.15
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 +56 -0
- package/dist/types/agent.d.ts +403 -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 +298 -0
- package/dist/types/compaction/entries.d.ts +109 -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 +69 -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 +84 -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 +430 -0
- package/package.json +11 -10
- package/src/agent.ts +21 -0
|
@@ -0,0 +1,56 @@
|
|
|
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
|
+
/**
|
|
9
|
+
* Start an agent loop with a new prompt message.
|
|
10
|
+
* The prompt is added to the context and events are emitted for it.
|
|
11
|
+
*/
|
|
12
|
+
export declare function agentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
|
|
13
|
+
/**
|
|
14
|
+
* Continue an agent loop from the current context without adding a new message.
|
|
15
|
+
* Used for retries - context already has user message or tool results.
|
|
16
|
+
*
|
|
17
|
+
* **Important:** The last message in context must convert to a `user` or `toolResult` message
|
|
18
|
+
* via `convertToLlm`. If it doesn't, the LLM provider will reject the request.
|
|
19
|
+
* This cannot be validated here since `convertToLlm` is only called once per turn.
|
|
20
|
+
*/
|
|
21
|
+
export declare function agentLoopContinue(context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
|
|
22
|
+
/**
|
|
23
|
+
* Detailed-result handle returned by {@link agentLoopDetailed}. Adds the
|
|
24
|
+
* run-level telemetry/coverage rollup to the existing `AgentMessage[]`
|
|
25
|
+
* payload without changing the resolved type of `stream.result()`.
|
|
26
|
+
*/
|
|
27
|
+
export interface AgentLoopDetailedResult {
|
|
28
|
+
readonly messages: AgentMessage[];
|
|
29
|
+
readonly telemetry: AgentRunSummary | undefined;
|
|
30
|
+
readonly coverage: AgentRunCoverage | undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Convenience wrapper over {@link agentLoop} that exposes the run-level
|
|
34
|
+
* summary + coverage alongside the messages. The returned `stream` is the
|
|
35
|
+
* same `EventStream` callers already consume; `detailed()` awaits the
|
|
36
|
+
* stream's `agent_end` event and returns the additive fields.
|
|
37
|
+
*
|
|
38
|
+
* Existing `stream.result()` semantics are preserved — it still resolves to
|
|
39
|
+
* `AgentMessage[]`. Use {@link agentLoopDetailed} when you need the rollup;
|
|
40
|
+
* use {@link agentLoop} when you do not.
|
|
41
|
+
*/
|
|
42
|
+
export declare function agentLoopDetailed(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): {
|
|
43
|
+
readonly stream: EventStream<AgentEvent, AgentMessage[]>;
|
|
44
|
+
readonly detailed: () => Promise<AgentLoopDetailedResult>;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Like {@link agentLoopDetailed} but built on top of
|
|
48
|
+
* {@link agentLoopContinue}.
|
|
49
|
+
*/
|
|
50
|
+
export declare function agentLoopContinueDetailed(context: AgentContext, config: AgentLoopConfig, signal?: AbortSignal, streamFn?: StreamFn): {
|
|
51
|
+
readonly stream: EventStream<AgentEvent, AgentMessage[]>;
|
|
52
|
+
readonly detailed: () => Promise<AgentLoopDetailedResult>;
|
|
53
|
+
};
|
|
54
|
+
export declare function normalizeMessagesForProvider(messages: Context["messages"], model: AgentLoopConfig["model"]): Context["messages"];
|
|
55
|
+
export declare const INTENT_FIELD = "_i";
|
|
56
|
+
export declare function normalizeTools(tools: AgentContext["tools"], injectIntent: boolean): Context["tools"];
|
|
@@ -0,0 +1,403 @@
|
|
|
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, 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 AgentBusyError extends Error {
|
|
15
|
+
constructor(message?: string);
|
|
16
|
+
}
|
|
17
|
+
export interface AgentOptions {
|
|
18
|
+
initialState?: Partial<AgentState>;
|
|
19
|
+
/**
|
|
20
|
+
* Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
|
|
21
|
+
* Default filters to user/assistant/toolResult and converts attachments.
|
|
22
|
+
*/
|
|
23
|
+
convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
|
|
24
|
+
/**
|
|
25
|
+
* Optional transform applied to context before convertToLlm.
|
|
26
|
+
* Use for context pruning, injecting external context, etc.
|
|
27
|
+
*/
|
|
28
|
+
transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
|
|
29
|
+
/**
|
|
30
|
+
* Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
|
|
31
|
+
*/
|
|
32
|
+
steeringMode?: "all" | "one-at-a-time";
|
|
33
|
+
/**
|
|
34
|
+
* Follow-up mode: "all" = send all follow-up messages at once, "one-at-a-time" = one per turn
|
|
35
|
+
*/
|
|
36
|
+
followUpMode?: "all" | "one-at-a-time";
|
|
37
|
+
/**
|
|
38
|
+
* When to interrupt tool execution for steering messages.
|
|
39
|
+
* - "immediate": check after each tool call (default)
|
|
40
|
+
* - "wait": defer steering until the current turn completes
|
|
41
|
+
*/
|
|
42
|
+
interruptMode?: "immediate" | "wait";
|
|
43
|
+
/** Cooperative pause checkpoint passed through to AgentLoopConfig.shouldPause. */
|
|
44
|
+
shouldPause?: AgentLoopConfig["shouldPause"];
|
|
45
|
+
/**
|
|
46
|
+
* API format for Kimi Code provider: "openai" or "anthropic" (default: "anthropic")
|
|
47
|
+
*/
|
|
48
|
+
kimiApiFormat?: "openai" | "anthropic";
|
|
49
|
+
/** Hint that websocket transport should be preferred when supported by the provider implementation. */
|
|
50
|
+
preferWebsockets?: boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Custom stream function (for proxy backends, etc.). Default uses streamSimple.
|
|
53
|
+
*/
|
|
54
|
+
streamFn?: StreamFn;
|
|
55
|
+
/**
|
|
56
|
+
* Optional session identifier forwarded to LLM providers.
|
|
57
|
+
* Used by providers that support session-based caching (e.g., OpenAI code provider).
|
|
58
|
+
*/
|
|
59
|
+
sessionId?: string;
|
|
60
|
+
/** Provider-facing cache/session affinity identifier. */
|
|
61
|
+
providerSessionId?: 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 dynamically for each LLM call.
|
|
68
|
+
* Useful for expiring tokens (e.g., GitHub Copilot OAuth).
|
|
69
|
+
*/
|
|
70
|
+
getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
|
|
71
|
+
getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* Inspect or replace provider payloads before they are sent.
|
|
74
|
+
*/
|
|
75
|
+
onPayload?: SimpleStreamOptions["onPayload"];
|
|
76
|
+
/**
|
|
77
|
+
* Inspect provider response metadata after headers arrive and before streaming body consumption.
|
|
78
|
+
*/
|
|
79
|
+
onResponse?: SimpleStreamOptions["onResponse"];
|
|
80
|
+
/**
|
|
81
|
+
* Inspect raw Server-Sent Events from HTTP streaming providers.
|
|
82
|
+
*/
|
|
83
|
+
onSseEvent?: SimpleStreamOptions["onSseEvent"];
|
|
84
|
+
/**
|
|
85
|
+
* Inspect assistant streaming events before they are emitted to subscribers.
|
|
86
|
+
* Use this when abort decisions must happen before buffered events continue flowing.
|
|
87
|
+
*/
|
|
88
|
+
onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
|
|
89
|
+
/** Called for non-content tool-choice incapability stream events. */
|
|
90
|
+
onToolChoiceIncapability?: AgentLoopConfig["onToolChoiceIncapability"];
|
|
91
|
+
/**
|
|
92
|
+
* Called when GPT-5 Harmony protocol leakage is detected and mitigated.
|
|
93
|
+
*/
|
|
94
|
+
onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
|
|
95
|
+
/**
|
|
96
|
+
* Custom token budgets for thinking levels (token-based providers only).
|
|
97
|
+
*/
|
|
98
|
+
thinkingBudgets?: ThinkingBudgets;
|
|
99
|
+
/**
|
|
100
|
+
* Sampling temperature for LLM calls. `undefined` uses provider default.
|
|
101
|
+
*/
|
|
102
|
+
temperature?: number;
|
|
103
|
+
/** Additional sampling controls for providers that support them. */
|
|
104
|
+
topP?: number;
|
|
105
|
+
topK?: number;
|
|
106
|
+
minP?: number;
|
|
107
|
+
presencePenalty?: number;
|
|
108
|
+
repetitionPenalty?: number;
|
|
109
|
+
serviceTier?: ServiceTier;
|
|
110
|
+
/**
|
|
111
|
+
* If true, request that the underlying provider omit reasoning/thinking summaries
|
|
112
|
+
* from the response. The model still reasons internally; only the human-readable
|
|
113
|
+
* summary stream is suppressed. Useful when the UI hides thinking blocks anyway.
|
|
114
|
+
*/
|
|
115
|
+
hideThinkingSummary?: boolean;
|
|
116
|
+
/**
|
|
117
|
+
* Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
|
|
118
|
+
* If the server's requested delay exceeds this value, the request fails immediately,
|
|
119
|
+
* allowing higher-level retry logic to handle it with user visibility.
|
|
120
|
+
* Default: 60000 (60 seconds). Set to 0 to disable the cap.
|
|
121
|
+
*/
|
|
122
|
+
maxRetryDelayMs?: number;
|
|
123
|
+
/** Provider request retry budget. Counts retries, not the initial attempt. */
|
|
124
|
+
requestMaxRetries?: number;
|
|
125
|
+
/** Provider stream replay retry budget. Counts retries, not the initial attempt. */
|
|
126
|
+
streamMaxRetries?: 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
|
+
/** Enable intent tracing schema injection/stripping in the harness. */
|
|
138
|
+
intentTracing?: boolean;
|
|
139
|
+
/** Dynamic tool choice override, resolved per LLM call. */
|
|
140
|
+
getToolChoice?: () => ToolChoice | undefined;
|
|
141
|
+
/**
|
|
142
|
+
* Cursor exec handlers for local tool execution.
|
|
143
|
+
*/
|
|
144
|
+
cursorExecHandlers?: CursorExecHandlers;
|
|
145
|
+
/**
|
|
146
|
+
* Cursor tool result callback for exec tool responses.
|
|
147
|
+
*/
|
|
148
|
+
cursorOnToolResult?: CursorToolResultHandler;
|
|
149
|
+
/**
|
|
150
|
+
* Called after a tool call has been validated and is about to execute.
|
|
151
|
+
* See {@link AgentLoopConfig.beforeToolCall} for full semantics.
|
|
152
|
+
*/
|
|
153
|
+
beforeToolCall?: AgentLoopConfig["beforeToolCall"];
|
|
154
|
+
/**
|
|
155
|
+
* Called after a tool finishes executing, before `tool_execution_end` and the tool-result
|
|
156
|
+
* message are emitted. See {@link AgentLoopConfig.afterToolCall} for full semantics.
|
|
157
|
+
*/
|
|
158
|
+
afterToolCall?: AgentLoopConfig["afterToolCall"];
|
|
159
|
+
/**
|
|
160
|
+
* Opt-in OpenTelemetry instrumentation. Passing `{}` enables the loop's
|
|
161
|
+
* GenAI-semantic-convention spans using the global tracer provider. See
|
|
162
|
+
* {@link AgentLoopConfig.telemetry} for the full surface.
|
|
163
|
+
*/
|
|
164
|
+
telemetry?: AgentLoopConfig["telemetry"];
|
|
165
|
+
/**
|
|
166
|
+
* Immutable context mode — stabilizes system prompt + tool spec bytes
|
|
167
|
+
* across turns so DeepSeek/Anthropic prefix caches hit at maximum rate.
|
|
168
|
+
*/
|
|
169
|
+
appendOnlyContext?: AppendOnlyContextManager;
|
|
170
|
+
}
|
|
171
|
+
export interface AgentPromptOptions {
|
|
172
|
+
toolChoice?: ToolChoice;
|
|
173
|
+
}
|
|
174
|
+
export declare class Agent {
|
|
175
|
+
#private;
|
|
176
|
+
get intentTracing(): boolean;
|
|
177
|
+
streamFn: StreamFn;
|
|
178
|
+
getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
|
|
179
|
+
getAuthCredentialType?: (provider: string) => "api_key" | "oauth" | undefined;
|
|
180
|
+
/**
|
|
181
|
+
* Hook invoked after tool arguments are validated and before execution.
|
|
182
|
+
* Reassign at any time to swap the implementation (e.g. on extension reload).
|
|
183
|
+
*/
|
|
184
|
+
beforeToolCall?: AgentLoopConfig["beforeToolCall"];
|
|
185
|
+
/**
|
|
186
|
+
* Hook invoked after tool execution and before `tool_execution_end` / tool-result
|
|
187
|
+
* message emission. Reassign at any time to swap the implementation.
|
|
188
|
+
*/
|
|
189
|
+
afterToolCall?: AgentLoopConfig["afterToolCall"];
|
|
190
|
+
constructor(opts?: AgentOptions);
|
|
191
|
+
/**
|
|
192
|
+
* Get the current session ID used for provider caching.
|
|
193
|
+
*/
|
|
194
|
+
get sessionId(): string | undefined;
|
|
195
|
+
/**
|
|
196
|
+
* Set the session ID for provider caching.
|
|
197
|
+
* Call this when switching sessions (new session, branch, resume).
|
|
198
|
+
*/
|
|
199
|
+
set sessionId(value: string | undefined);
|
|
200
|
+
get providerSessionId(): string | undefined;
|
|
201
|
+
set providerSessionId(value: string | undefined);
|
|
202
|
+
/**
|
|
203
|
+
* Whether websocket transport is preferred when the provider implementation
|
|
204
|
+
* supports it. Read by maintenance one-shot calls (compaction, handoff,
|
|
205
|
+
* branch summary) so they forward the same transport preference as live turns.
|
|
206
|
+
*/
|
|
207
|
+
get preferWebsockets(): boolean | undefined;
|
|
208
|
+
/**
|
|
209
|
+
* Static metadata forwarded to every API request when no resolver is installed
|
|
210
|
+
* (e.g. `metadata.user_id` for Anthropic session attribution). Setting this
|
|
211
|
+
* clears any installed resolver.
|
|
212
|
+
*
|
|
213
|
+
* For live/provider-aware metadata (e.g. Anthropic OAuth `account_uuid` that
|
|
214
|
+
* must reflect the credential selected per-request), use
|
|
215
|
+
* {@link setMetadataResolver} and read via {@link metadataForProvider}.
|
|
216
|
+
*/
|
|
217
|
+
get metadata(): Record<string, unknown> | undefined;
|
|
218
|
+
set metadata(value: Record<string, unknown> | undefined);
|
|
219
|
+
/**
|
|
220
|
+
* Resolve request metadata for the given provider at call time. When a
|
|
221
|
+
* resolver is installed via {@link setMetadataResolver}, it is invoked with
|
|
222
|
+
* the provider string so the result can be scoped (e.g. `account_uuid` is
|
|
223
|
+
* only included for `"anthropic"` requests). Falls back to the static
|
|
224
|
+
* {@link metadata} value when no resolver is set.
|
|
225
|
+
*/
|
|
226
|
+
metadataForProvider(provider: string): Record<string, unknown> | undefined;
|
|
227
|
+
/**
|
|
228
|
+
* Install a function that resolves request metadata at call time. The
|
|
229
|
+
* resolver receives the target provider string and can gate provider-specific
|
|
230
|
+
* fields (e.g. `account_uuid` only for `"anthropic"`). Invoked per LLM
|
|
231
|
+
* request by `agent-loop` after `getApiKey` selects the session-sticky
|
|
232
|
+
* credential. Pass `undefined` to clear and revert to the static
|
|
233
|
+
* {@link metadata} value.
|
|
234
|
+
*/
|
|
235
|
+
setMetadataResolver(resolver: ((provider: string) => Record<string, unknown> | undefined) | undefined): void;
|
|
236
|
+
/**
|
|
237
|
+
* Read the active OpenTelemetry configuration. Returns `undefined` when
|
|
238
|
+
* instrumentation is disabled. Callers spawning child runs (e.g. subagent
|
|
239
|
+
* dispatch) forward this to the child's loop so its spans appear under the
|
|
240
|
+
* parent's active context with the subagent's own identity stamped.
|
|
241
|
+
*/
|
|
242
|
+
get telemetry(): AgentLoopConfig["telemetry"] | undefined;
|
|
243
|
+
/**
|
|
244
|
+
* Replace the active OpenTelemetry configuration. Pass `undefined` to
|
|
245
|
+
* disable instrumentation. Applies to the *next* `agentLoop` invocation —
|
|
246
|
+
* in-flight loops keep the configuration they started with.
|
|
247
|
+
*/
|
|
248
|
+
setTelemetry(telemetry: AgentLoopConfig["telemetry"] | undefined): void;
|
|
249
|
+
/**
|
|
250
|
+
* Get provider-scoped mutable session state store.
|
|
251
|
+
*/
|
|
252
|
+
get providerSessionState(): Map<string, ProviderSessionState> | undefined;
|
|
253
|
+
/**
|
|
254
|
+
* Set provider-scoped mutable session state store.
|
|
255
|
+
*/
|
|
256
|
+
set providerSessionState(value: Map<string, ProviderSessionState> | undefined);
|
|
257
|
+
/**
|
|
258
|
+
* Get the current thinking budgets.
|
|
259
|
+
*/
|
|
260
|
+
get thinkingBudgets(): ThinkingBudgets | undefined;
|
|
261
|
+
/**
|
|
262
|
+
* Set custom thinking budgets for token-based providers.
|
|
263
|
+
*/
|
|
264
|
+
set thinkingBudgets(value: ThinkingBudgets | undefined);
|
|
265
|
+
/**
|
|
266
|
+
* Get the current sampling temperature.
|
|
267
|
+
*/
|
|
268
|
+
get temperature(): number | undefined;
|
|
269
|
+
/**
|
|
270
|
+
* Set sampling temperature for LLM calls. `undefined` uses provider default.
|
|
271
|
+
*/
|
|
272
|
+
set temperature(value: number | undefined);
|
|
273
|
+
get topP(): number | undefined;
|
|
274
|
+
set topP(value: number | undefined);
|
|
275
|
+
get topK(): number | undefined;
|
|
276
|
+
set topK(value: number | undefined);
|
|
277
|
+
get minP(): number | undefined;
|
|
278
|
+
set minP(value: number | undefined);
|
|
279
|
+
get presencePenalty(): number | undefined;
|
|
280
|
+
set presencePenalty(value: number | undefined);
|
|
281
|
+
get repetitionPenalty(): number | undefined;
|
|
282
|
+
set repetitionPenalty(value: number | undefined);
|
|
283
|
+
get serviceTier(): ServiceTier | undefined;
|
|
284
|
+
set serviceTier(value: ServiceTier | undefined);
|
|
285
|
+
get hideThinkingSummary(): boolean | undefined;
|
|
286
|
+
set hideThinkingSummary(value: boolean | undefined);
|
|
287
|
+
/**
|
|
288
|
+
* Get the current max retry delay in milliseconds.
|
|
289
|
+
*/
|
|
290
|
+
get maxRetryDelayMs(): number | undefined;
|
|
291
|
+
/**
|
|
292
|
+
* Set the maximum delay to wait for server-requested retries.
|
|
293
|
+
* Set to 0 to disable the cap.
|
|
294
|
+
*/
|
|
295
|
+
set maxRetryDelayMs(value: number | undefined);
|
|
296
|
+
get requestMaxRetries(): number | undefined;
|
|
297
|
+
set requestMaxRetries(value: number | undefined);
|
|
298
|
+
get streamMaxRetries(): number | undefined;
|
|
299
|
+
set streamMaxRetries(value: number | undefined);
|
|
300
|
+
get state(): AgentState;
|
|
301
|
+
get contextRevision(): number;
|
|
302
|
+
get appendOnlyContext(): AppendOnlyContextManager | undefined;
|
|
303
|
+
setAppendOnlyContext(manager?: AppendOnlyContextManager): void;
|
|
304
|
+
subscribe(fn: (e: AgentEvent) => void): () => void;
|
|
305
|
+
setProviderResponseInterceptor(fn: SimpleStreamOptions["onResponse"] | undefined): void;
|
|
306
|
+
setRawSseEventInterceptor(fn: SimpleStreamOptions["onSseEvent"] | undefined): void;
|
|
307
|
+
setAssistantMessageEventInterceptor(fn: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined): void;
|
|
308
|
+
setOnBeforeYield(fn: (() => Promise<void> | void) | undefined): void;
|
|
309
|
+
setShouldPause(fn: AgentLoopConfig["shouldPause"] | undefined): void;
|
|
310
|
+
emitExternalEvent(event: AgentEvent): void;
|
|
311
|
+
createExternalEventEmitterForCurrentRun(): ((event: AgentEvent) => void) | undefined;
|
|
312
|
+
setSystemPrompt(v: string[]): void;
|
|
313
|
+
setModel(m: Model): void;
|
|
314
|
+
setThinkingLevel(l: Effort | undefined): void;
|
|
315
|
+
setSteeringMode(mode: "all" | "one-at-a-time"): void;
|
|
316
|
+
getSteeringMode(): "all" | "one-at-a-time";
|
|
317
|
+
setFollowUpMode(mode: "all" | "one-at-a-time"): void;
|
|
318
|
+
getFollowUpMode(): "all" | "one-at-a-time";
|
|
319
|
+
setInterruptMode(mode: "immediate" | "wait"): void;
|
|
320
|
+
getInterruptMode(): "immediate" | "wait";
|
|
321
|
+
setTools(t: AgentTool<any>[]): void;
|
|
322
|
+
replaceMessages(ms: AgentMessage[]): void;
|
|
323
|
+
appendMessage(m: AgentMessage): void;
|
|
324
|
+
popMessage(): AgentMessage | undefined;
|
|
325
|
+
/**
|
|
326
|
+
* For callers that mutate committed messages or the system prompt in place
|
|
327
|
+
* outside Agent-owned mutators.
|
|
328
|
+
*/
|
|
329
|
+
touchContext(): void;
|
|
330
|
+
/**
|
|
331
|
+
* Queue a steering message to interrupt the agent mid-run.
|
|
332
|
+
* Delivered after current tool execution, skips remaining tools.
|
|
333
|
+
*/
|
|
334
|
+
steer(m: AgentMessage): void;
|
|
335
|
+
/**
|
|
336
|
+
* Queue a follow-up message to be processed after the agent finishes.
|
|
337
|
+
* Delivered only when agent has no more tool calls or steering messages.
|
|
338
|
+
*
|
|
339
|
+
* `forceOneAtATime` lets UI composer queues preserve prompt-by-prompt
|
|
340
|
+
* delivery even when the session-wide follow-up mode is set to `all` for
|
|
341
|
+
* other integration paths.
|
|
342
|
+
*/
|
|
343
|
+
followUp(m: AgentMessage, options?: {
|
|
344
|
+
forceOneAtATime?: boolean;
|
|
345
|
+
}): void;
|
|
346
|
+
clearSteeringQueue(): void;
|
|
347
|
+
clearFollowUpQueue(): void;
|
|
348
|
+
clearAllQueues(): void;
|
|
349
|
+
hasQueuedMessages(): boolean;
|
|
350
|
+
hasQueuedSteering(): boolean;
|
|
351
|
+
/**
|
|
352
|
+
* Snapshot the steering queue without mutating it. Used to preserve queued
|
|
353
|
+
* steering across maintenance ops (compaction/handoff) that call reset().
|
|
354
|
+
*/
|
|
355
|
+
snapshotSteering(): AgentMessage[];
|
|
356
|
+
/**
|
|
357
|
+
* Restore previously snapshotted steering messages ahead of any newly
|
|
358
|
+
* queued ones. No-op for an empty snapshot.
|
|
359
|
+
*/
|
|
360
|
+
restoreSteering(messages: AgentMessage[]): void;
|
|
361
|
+
/** Snapshot the follow-up queue without mutating it. */
|
|
362
|
+
snapshotFollowUp(): AgentMessage[];
|
|
363
|
+
/** Restore previously snapshotted follow-up messages ahead of any newly queued ones. */
|
|
364
|
+
restoreFollowUp(messages: AgentMessage[]): void;
|
|
365
|
+
/**
|
|
366
|
+
* Remove and return the last steering message from the queue (LIFO).
|
|
367
|
+
* Used by dequeue keybinding.
|
|
368
|
+
*/
|
|
369
|
+
popLastSteer(): AgentMessage | undefined;
|
|
370
|
+
removeSteerAt(index: number): AgentMessage | undefined;
|
|
371
|
+
moveSteer(fromIndex: number, toIndex: number): boolean;
|
|
372
|
+
/**
|
|
373
|
+
* Remove and return the last follow-up message from the queue (LIFO).
|
|
374
|
+
* Used by dequeue keybinding.
|
|
375
|
+
*/
|
|
376
|
+
popLastFollowUp(): AgentMessage | undefined;
|
|
377
|
+
removeFollowUpAt(index: number): AgentMessage | undefined;
|
|
378
|
+
moveFollowUp(fromIndex: number, toIndex: number): boolean;
|
|
379
|
+
/** Remove queued steering+follow-up messages matching `predicate`, preserving order of the rest. */
|
|
380
|
+
removeQueuedMessages(predicate: (message: AgentMessage) => boolean): {
|
|
381
|
+
steering: number;
|
|
382
|
+
followUp: number;
|
|
383
|
+
total: number;
|
|
384
|
+
};
|
|
385
|
+
clearMessages(): void;
|
|
386
|
+
abort(): void;
|
|
387
|
+
/**
|
|
388
|
+
* Force the current run out of the busy/streaming state when cooperative abort
|
|
389
|
+
* did not drain. The abandoned provider/tool stream may still settle later, so
|
|
390
|
+
* #runLoop guards every state mutation with a run id.
|
|
391
|
+
*/
|
|
392
|
+
forceAbort(reason?: string): boolean;
|
|
393
|
+
waitForIdle(): Promise<void>;
|
|
394
|
+
reset(): void;
|
|
395
|
+
/** Send a prompt with an AgentMessage */
|
|
396
|
+
prompt(message: AgentMessage | AgentMessage[], options?: AgentPromptOptions): Promise<void>;
|
|
397
|
+
prompt(input: string, options?: AgentPromptOptions): Promise<void>;
|
|
398
|
+
prompt(input: string, images?: ImageContent[], options?: AgentPromptOptions): Promise<void>;
|
|
399
|
+
/**
|
|
400
|
+
* Continue from current context (used for retries and resuming queued messages).
|
|
401
|
+
*/
|
|
402
|
+
continue(): Promise<void>;
|
|
403
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Append-only context mode — stabilizes the byte prefix sent to the LLM
|
|
3
|
+
* across turns so provider prefix caches (DeepSeek, Anthropic, etc.)
|
|
4
|
+
* hit at the maximum possible rate.
|
|
5
|
+
*
|
|
6
|
+
* Two mechanisms:
|
|
7
|
+
*
|
|
8
|
+
* 1. **StablePrefix** — system prompt + tool specs are computed once
|
|
9
|
+
* and frozen. Subsequent turns reuse the exact same byte sequence
|
|
10
|
+
* unless `invalidate()` is called (e.g. after MCP reconnect).
|
|
11
|
+
*
|
|
12
|
+
* 2. **AppendOnlyLog** — messages only grow; prior turns are never
|
|
13
|
+
* re-serialized. Combined with a stable prefix, only the user's new
|
|
14
|
+
* message delta is a cache miss each turn.
|
|
15
|
+
*/
|
|
16
|
+
import type { Context, Message, Tool } from "@sayknow-cli/ai";
|
|
17
|
+
import type { AgentContext } from "./types";
|
|
18
|
+
/** Frozen system prompt + tool spec snapshot. */
|
|
19
|
+
export interface StablePrefixSnapshot {
|
|
20
|
+
systemPrompt: string[];
|
|
21
|
+
tools: Tool[];
|
|
22
|
+
fingerprint: string;
|
|
23
|
+
}
|
|
24
|
+
/** Options threaded through `build()` so the snapshot reflects loop-time settings. */
|
|
25
|
+
export interface BuildOptions {
|
|
26
|
+
/** Inject the `_i` intent field into tool schemas (must match agent-loop's normalizeTools). */
|
|
27
|
+
intentTracing: boolean;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* A frozen prefix (system prompt + tools) that produces stable byte
|
|
31
|
+
* sequences across `build()` calls.
|
|
32
|
+
*
|
|
33
|
+
* The first `build()` snapshots the live state. Subsequent calls reuse
|
|
34
|
+
* the cached copy until `invalidate()` is called or the live state's
|
|
35
|
+
* fingerprint changes.
|
|
36
|
+
*/
|
|
37
|
+
export declare class StablePrefix {
|
|
38
|
+
#private;
|
|
39
|
+
get fingerprint(): string;
|
|
40
|
+
get version(): number;
|
|
41
|
+
get built(): boolean;
|
|
42
|
+
exportSnapshot(): StablePrefixSnapshot | null;
|
|
43
|
+
importSnapshot(snapshot: StablePrefixSnapshot, options: BuildOptions): void;
|
|
44
|
+
/**
|
|
45
|
+
* Build or rebuild from live context.
|
|
46
|
+
* Returns `true` if the prefix actually changed (cache miss imminent).
|
|
47
|
+
*/
|
|
48
|
+
build(context: AgentContext, options: BuildOptions): boolean;
|
|
49
|
+
/** Force rebuild on the next `build()` call. */
|
|
50
|
+
invalidate(): void;
|
|
51
|
+
/**
|
|
52
|
+
* Returns the cached prefix.
|
|
53
|
+
* @throws if `build()` was never called.
|
|
54
|
+
*/
|
|
55
|
+
toContext(): {
|
|
56
|
+
systemPrompt: string[];
|
|
57
|
+
tools: Tool[];
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Append-only message log at the `Message[]` (provider-level) layer.
|
|
62
|
+
*
|
|
63
|
+
* The only mutation path is `replaceTail()`, reserved for compaction.
|
|
64
|
+
* Every other operation is append-only.
|
|
65
|
+
*/
|
|
66
|
+
export declare class AppendOnlyLog {
|
|
67
|
+
#private;
|
|
68
|
+
get length(): number;
|
|
69
|
+
append(message: any): void;
|
|
70
|
+
extend(messages: any[]): void;
|
|
71
|
+
/** Replace the last entry — only legal for compaction. */
|
|
72
|
+
replaceTail(replacement: any): void;
|
|
73
|
+
/** Returns a shallow copy of all entries. */
|
|
74
|
+
toMessages(): Message[];
|
|
75
|
+
/** Direct readonly access for in-place inspection. */
|
|
76
|
+
entries(): readonly Message[];
|
|
77
|
+
clear(): void;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Manages a stable prefix + append-only log for the agent loop.
|
|
81
|
+
*
|
|
82
|
+
* Call `build(context)` each turn to get a `Context` with stable
|
|
83
|
+
* `systemPrompt` and `tools` and append-only messages. Call
|
|
84
|
+
* `syncMessages(normalizedMessages)` after `convertToLlm` each
|
|
85
|
+
* turn to keep the log in sync.
|
|
86
|
+
*
|
|
87
|
+
* Example:
|
|
88
|
+
* ```
|
|
89
|
+
* const mgr = new AppendOnlyContextManager();
|
|
90
|
+
* const ctx = mgr.build(context); // first call snapshots prefix
|
|
91
|
+
* mgr.syncMessages(normalized); // grow the log
|
|
92
|
+
* ctx = mgr.build(context); // subsequent calls use cache
|
|
93
|
+
* ```
|
|
94
|
+
*/
|
|
95
|
+
export interface AppendOnlyContextManagerOptions {
|
|
96
|
+
/**
|
|
97
|
+
* Invoked whenever the stable prefix fingerprint changes on `build()` (a
|
|
98
|
+
* provider prompt-cache prefix reset). Used for per-session diagnostics; must
|
|
99
|
+
* not throw. `from` is `<unbuilt>` on the first build.
|
|
100
|
+
*/
|
|
101
|
+
readonly onPrefixChange?: (info: {
|
|
102
|
+
from: string;
|
|
103
|
+
to: string;
|
|
104
|
+
version: number;
|
|
105
|
+
}) => void;
|
|
106
|
+
}
|
|
107
|
+
export declare class AppendOnlyContextManager {
|
|
108
|
+
#private;
|
|
109
|
+
readonly prefix: StablePrefix;
|
|
110
|
+
readonly log: AppendOnlyLog;
|
|
111
|
+
constructor(options?: AppendOnlyContextManagerOptions);
|
|
112
|
+
static forkFromSeed(args: {
|
|
113
|
+
prefixSnapshot?: StablePrefixSnapshot;
|
|
114
|
+
messages?: readonly Message[];
|
|
115
|
+
options: BuildOptions;
|
|
116
|
+
}): AppendOnlyContextManager;
|
|
117
|
+
build(context: AgentContext, options: BuildOptions): Context;
|
|
118
|
+
/**
|
|
119
|
+
* Sync normalized (provider-level) messages into the append-only log.
|
|
120
|
+
*
|
|
121
|
+
* Detects both compaction (shorter array) and in-place rewrites
|
|
122
|
+
* (same length, changed content via a rolling digest).
|
|
123
|
+
*/
|
|
124
|
+
syncMessages(normalizedMessages: any[]): void;
|
|
125
|
+
seedNormalizedMessages(messages: readonly Message[], options?: {
|
|
126
|
+
reset?: boolean;
|
|
127
|
+
}): void;
|
|
128
|
+
/** Reset prefix + log for a model/provider switch while mode stays active. */
|
|
129
|
+
invalidateForModelChange(): void;
|
|
130
|
+
/** Reset the sync cursor AND clear the log. */
|
|
131
|
+
resetSyncCursor(): void;
|
|
132
|
+
appendMessage(message: any): void;
|
|
133
|
+
replaceTailMessage(message: any): void;
|
|
134
|
+
invalidate(): void;
|
|
135
|
+
reset(context: AgentContext, options: BuildOptions): void;
|
|
136
|
+
}
|
|
137
|
+
export declare function cloneJson<T>(value: T): T;
|