@sayknow-cli/agent-core 0.3.4 → 0.3.6

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