jeopi-agent-core 16.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +1016 -0
  2. package/README.md +473 -0
  3. package/dist/types/agent-loop.d.ts +66 -0
  4. package/dist/types/agent.d.ts +427 -0
  5. package/dist/types/append-only-context.d.ts +133 -0
  6. package/dist/types/compaction/branch-summarization.d.ts +101 -0
  7. package/dist/types/compaction/compaction-v2-streaming.d.ts +82 -0
  8. package/dist/types/compaction/compaction.d.ts +283 -0
  9. package/dist/types/compaction/entries.d.ts +110 -0
  10. package/dist/types/compaction/errors.d.ts +26 -0
  11. package/dist/types/compaction/index.d.ts +12 -0
  12. package/dist/types/compaction/messages.d.ts +77 -0
  13. package/dist/types/compaction/openai.d.ts +77 -0
  14. package/dist/types/compaction/pruning.d.ts +105 -0
  15. package/dist/types/compaction/shake.d.ts +92 -0
  16. package/dist/types/compaction/tool-protection.d.ts +17 -0
  17. package/dist/types/compaction/utils.d.ts +58 -0
  18. package/dist/types/compaction.d.ts +1 -0
  19. package/dist/types/index.d.ts +12 -0
  20. package/dist/types/proxy.d.ts +85 -0
  21. package/dist/types/replay-policy.d.ts +5 -0
  22. package/dist/types/run-collector.d.ts +196 -0
  23. package/dist/types/telemetry.d.ts +590 -0
  24. package/dist/types/thinking.d.ts +17 -0
  25. package/dist/types/tokenizer.d.ts +1 -0
  26. package/dist/types/types.d.ts +640 -0
  27. package/dist/types/utils/yield.d.ts +71 -0
  28. package/package.json +78 -0
  29. package/src/agent-loop.ts +2188 -0
  30. package/src/agent.ts +1457 -0
  31. package/src/append-only-context.ts +348 -0
  32. package/src/compaction/branch-summarization.ts +370 -0
  33. package/src/compaction/compaction-v2-streaming.ts +719 -0
  34. package/src/compaction/compaction.ts +1553 -0
  35. package/src/compaction/entries.ts +142 -0
  36. package/src/compaction/errors.ts +31 -0
  37. package/src/compaction/index.ts +13 -0
  38. package/src/compaction/messages.ts +237 -0
  39. package/src/compaction/openai.ts +581 -0
  40. package/src/compaction/prompts/auto-handoff-threshold-focus.md +1 -0
  41. package/src/compaction/prompts/branch-summary-context.md +5 -0
  42. package/src/compaction/prompts/branch-summary-preamble.md +2 -0
  43. package/src/compaction/prompts/branch-summary.md +30 -0
  44. package/src/compaction/prompts/compaction-short-summary.md +9 -0
  45. package/src/compaction/prompts/compaction-summary-context.md +5 -0
  46. package/src/compaction/prompts/compaction-summary.md +38 -0
  47. package/src/compaction/prompts/compaction-turn-prefix.md +17 -0
  48. package/src/compaction/prompts/compaction-update-summary.md +45 -0
  49. package/src/compaction/prompts/file-operations.md +5 -0
  50. package/src/compaction/prompts/handoff-document.md +49 -0
  51. package/src/compaction/prompts/snapcompact-archive-context.md +3 -0
  52. package/src/compaction/prompts/summarization-system.md +3 -0
  53. package/src/compaction/pruning.ts +424 -0
  54. package/src/compaction/shake.ts +429 -0
  55. package/src/compaction/tool-protection.ts +55 -0
  56. package/src/compaction/utils.ts +323 -0
  57. package/src/compaction.ts +1 -0
  58. package/src/index.ts +24 -0
  59. package/src/proxy.ts +376 -0
  60. package/src/replay-policy.ts +13 -0
  61. package/src/run-collector.ts +631 -0
  62. package/src/telemetry.ts +2034 -0
  63. package/src/thinking.ts +19 -0
  64. package/src/tokenizer.ts +17 -0
  65. package/src/types.ts +718 -0
  66. package/src/utils/yield.ts +183 -0
@@ -0,0 +1,427 @@
1
+ import { type ApiKey, type AssistantMessage, type AssistantMessageEvent, type Context, type CursorExecHandlers, type CursorToolResultHandler, type Effort, type ImageContent, type Message, type Model, type ProviderSessionState, type ServiceTier, type SimpleStreamOptions, type ThinkingBudgets, type ToolChoice } from "jeopi-ai";
2
+ import type { Dialect } from "jeopi-ai/dialect";
3
+ import type { HarmonyAuditEvent } from "jeopi-ai/utils/harmony-leak";
4
+ import type { AppendOnlyContextManager } from "./append-only-context";
5
+ import type { AgentEvent, AgentLoopConfig, AgentMessage, AgentState, AgentTool, AgentToolContext, AgentTurnEndContext, AsideMessage, StreamFn, ToolCallContext, ToolChoiceDirective } from "./types";
6
+ export declare class AgentBusyError extends Error {
7
+ constructor(message?: string);
8
+ }
9
+ export interface AgentOptions {
10
+ initialState?: Partial<AgentState>;
11
+ /**
12
+ * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
13
+ * Default filters to user/assistant/toolResult and converts attachments.
14
+ */
15
+ convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
16
+ /**
17
+ * Optional transform applied to context before convertToLlm.
18
+ * Use for context pruning, injecting external context, etc.
19
+ */
20
+ transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
21
+ /**
22
+ * Optional transform applied after provider context assembly and before
23
+ * telemetry capture/provider send.
24
+ */
25
+ transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
26
+ /**
27
+ * Steering mode: "all" = send all steering messages at once, "one-at-a-time" = one per turn
28
+ */
29
+ steeringMode?: "all" | "one-at-a-time";
30
+ /**
31
+ * Follow-up mode: "all" = send all follow-up messages at once, "one-at-a-time" = one per turn
32
+ */
33
+ followUpMode?: "all" | "one-at-a-time";
34
+ /**
35
+ * When to interrupt tool execution for steering messages.
36
+ * - "immediate": check after each tool call (default)
37
+ * - "wait": defer steering until the current turn completes
38
+ */
39
+ interruptMode?: "immediate" | "wait";
40
+ /**
41
+ * API format for Kimi Code provider: "openai" or "anthropic" (default: "anthropic")
42
+ */
43
+ kimiApiFormat?: "openai" | "anthropic";
44
+ /** Hint that websocket transport should be preferred when supported by the provider implementation. */
45
+ preferWebsockets?: boolean;
46
+ /**
47
+ * Custom stream function (for proxy backends, etc.). Default uses streamSimple.
48
+ */
49
+ streamFn?: StreamFn;
50
+ /** Absolute wall-clock deadline in Unix epoch milliseconds. */
51
+ deadline?: number;
52
+ /**
53
+ * Optional session identifier forwarded to LLM providers.
54
+ * Used by providers that support session-based caching (e.g., OpenAI Codex).
55
+ */
56
+ sessionId?: string;
57
+ /**
58
+ * Optional prompt cache key forwarded to LLM providers.
59
+ * When omitted, providers may fall back to sessionId.
60
+ */
61
+ promptCacheKey?: string;
62
+ /**
63
+ * Shared provider state map for session-scoped transport/session caches.
64
+ */
65
+ providerSessionState?: Map<string, ProviderSessionState>;
66
+ /**
67
+ * Resolves an API key or resolver dynamically for each LLM call.
68
+ * Useful for expiring tokens and model-scoped credential routing.
69
+ */
70
+ getApiKey?: (model: Model) => Promise<ApiKey | undefined> | ApiKey | undefined;
71
+ /**
72
+ * Inspect or replace provider payloads before they are sent.
73
+ */
74
+ onPayload?: SimpleStreamOptions["onPayload"];
75
+ /**
76
+ * Inspect provider response metadata after headers arrive and before streaming body consumption.
77
+ */
78
+ onResponse?: SimpleStreamOptions["onResponse"];
79
+ /**
80
+ * Inspect raw Server-Sent Events from HTTP streaming providers.
81
+ */
82
+ onSseEvent?: SimpleStreamOptions["onSseEvent"];
83
+ /**
84
+ * Inspect assistant streaming events before they are emitted to subscribers.
85
+ * Use this when abort decisions must happen before buffered events continue flowing.
86
+ */
87
+ onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
88
+ /**
89
+ * Called when GPT-5 Harmony protocol leakage is detected and mitigated.
90
+ */
91
+ onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
92
+ /**
93
+ * Custom token budgets for thinking levels (token-based providers only).
94
+ */
95
+ thinkingBudgets?: ThinkingBudgets;
96
+ /**
97
+ * Sampling temperature for LLM calls. `undefined` uses provider default.
98
+ */
99
+ temperature?: number;
100
+ /** Additional sampling controls for providers that support them. */
101
+ topP?: number;
102
+ topK?: number;
103
+ minP?: number;
104
+ presencePenalty?: number;
105
+ repetitionPenalty?: number;
106
+ serviceTier?: ServiceTier;
107
+ /**
108
+ * Per-call effective service-tier resolver. When set, it authoritatively
109
+ * supplies the request's tier (replacing the static `serviceTier` and its
110
+ * telemetry) per model — used to scope a provider/model into a priority
111
+ * serving path without mutating the shared session `serviceTier`.
112
+ */
113
+ serviceTierResolver?: (model: Model) => ServiceTier | undefined;
114
+ /**
115
+ * If true, request that the underlying provider omit reasoning/thinking summaries
116
+ * from the response. The model still reasons internally; only the human-readable
117
+ * summary stream is suppressed. Useful when the UI hides thinking blocks anyway.
118
+ */
119
+ hideThinkingSummary?: boolean;
120
+ /**
121
+ * Maximum delay in milliseconds to wait for a retry when the server requests a long wait.
122
+ * If the server's requested delay exceeds this value, the request fails immediately,
123
+ * allowing higher-level retry logic to handle it with user visibility.
124
+ * Default: 60000 (60 seconds). Set to 0 to disable the cap.
125
+ */
126
+ maxRetryDelayMs?: number;
127
+ /**
128
+ * Provides tool execution context, resolved per tool call.
129
+ * Use for late-bound UI or session state access.
130
+ */
131
+ getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
132
+ /**
133
+ * Optional transform applied to tool call arguments before execution.
134
+ * Use for deobfuscating secrets or rewriting arguments.
135
+ */
136
+ transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
137
+ /** Enable intent tracing schema injection/stripping in the harness. */
138
+ intentTracing?: boolean;
139
+ /**
140
+ * Strip tool descriptions from provider-bound tool specs (top-level + nested
141
+ * schema annotations). Use when the full catalog is rendered into the system
142
+ * prompt so descriptions are not duplicated on the wire. Native tool calling only.
143
+ */
144
+ pruneToolDescriptions?: boolean;
145
+ /** Owned tool-calling dialect. Undefined keeps provider-native tool calling. */
146
+ dialect?: Dialect;
147
+ /**
148
+ * When owned tool calling is active and the model fabricates a tool result
149
+ * mid-turn: `true` (default) aborts the provider request immediately; `false`
150
+ * drains the request and discards the fabricated continuation. Forwarded to
151
+ * the loop's {@link AgentLoopConfig.abortOnFabricatedToolResult}.
152
+ */
153
+ abortOnFabricatedToolResult?: boolean;
154
+ /** Dynamic tool-choice directive (hard {@link ToolChoice} or {@link SoftToolRequirement}), resolved once per turn. */
155
+ getToolChoice?: () => ToolChoiceDirective | undefined;
156
+ /**
157
+ * Cursor exec handlers for local tool execution.
158
+ */
159
+ cursorExecHandlers?: CursorExecHandlers;
160
+ /**
161
+ * Cursor tool result callback for exec tool responses.
162
+ */
163
+ cursorOnToolResult?: CursorToolResultHandler;
164
+ /** Current working directory used by local tool execution. */
165
+ cwd?: string;
166
+ /**
167
+ * Resolver for the live working directory, re-read on every turn. When set, it
168
+ * overrides the static {@link cwd} at config-build time so a session move
169
+ * (`/move`, which updates the host's cwd without reconstructing the Agent) is
170
+ * reflected in provider options — e.g. GitLab Duo Agent namespace/project
171
+ * discovery keys off this cwd's git remote. Falls back to `cwd` when it returns
172
+ * `undefined`.
173
+ */
174
+ cwdResolver?: () => string | undefined;
175
+ /**
176
+ * Called after a tool call has been validated and is about to execute.
177
+ * See {@link AgentLoopConfig.beforeToolCall} for full semantics.
178
+ */
179
+ beforeToolCall?: AgentLoopConfig["beforeToolCall"];
180
+ /**
181
+ * Called after a tool finishes executing, before `tool_execution_end` and the tool-result
182
+ * message are emitted. See {@link AgentLoopConfig.afterToolCall} for full semantics.
183
+ */
184
+ afterToolCall?: AgentLoopConfig["afterToolCall"];
185
+ /**
186
+ * Called once an assistant message is finalized, before it reaches the
187
+ * context, the UI, or tool dispatch. May mutate the message in place (text +
188
+ * tool-call arguments). See {@link AgentLoopConfig.transformAssistantMessage}.
189
+ */
190
+ transformAssistantMessage?: AgentLoopConfig["transformAssistantMessage"];
191
+ /**
192
+ * Opt-in OpenTelemetry instrumentation. Passing `{}` enables the loop's
193
+ * GenAI-semantic-convention spans using the global tracer provider. See
194
+ * {@link AgentLoopConfig.telemetry} for the full surface.
195
+ */
196
+ telemetry?: AgentLoopConfig["telemetry"];
197
+ /**
198
+ * Immutable context mode — stabilizes system prompt + tool spec bytes
199
+ * across turns so DeepSeek/Anthropic prefix caches hit at maximum rate.
200
+ */
201
+ appendOnlyContext?: AppendOnlyContextManager;
202
+ }
203
+ export interface AgentPromptOptions {
204
+ toolChoice?: ToolChoice;
205
+ }
206
+ export declare class Agent {
207
+ #private;
208
+ streamFn: StreamFn;
209
+ getApiKey?: (model: Model) => Promise<ApiKey | undefined> | ApiKey | undefined;
210
+ /**
211
+ * Hook invoked after tool arguments are validated and before execution.
212
+ * Reassign at any time to swap the implementation (e.g. on extension reload).
213
+ */
214
+ beforeToolCall?: AgentLoopConfig["beforeToolCall"];
215
+ /**
216
+ * Hook invoked after tool execution and before `tool_execution_end` / tool-result
217
+ * message emission. Reassign at any time to swap the implementation.
218
+ */
219
+ afterToolCall?: AgentLoopConfig["afterToolCall"];
220
+ /**
221
+ * Hook invoked once an assistant message is finalized, before context append,
222
+ * UI emission, and tool dispatch. Reassign at any time to swap the implementation.
223
+ */
224
+ transformAssistantMessage?: AgentLoopConfig["transformAssistantMessage"];
225
+ /**
226
+ * Hook that peeks whether interrupting IRC asides are queued for the next boundary.
227
+ */
228
+ hasIrcInterrupts?: AgentLoopConfig["hasIrcInterrupts"];
229
+ constructor(opts?: AgentOptions);
230
+ /**
231
+ * Get the current session ID used for provider caching.
232
+ */
233
+ get sessionId(): string | undefined;
234
+ /**
235
+ * Set the session ID for provider caching.
236
+ * Call this when switching sessions (new session, branch, resume).
237
+ */
238
+ set sessionId(value: string | undefined);
239
+ /**
240
+ * Get the prompt cache key forwarded to providers.
241
+ */
242
+ get promptCacheKey(): string | undefined;
243
+ /**
244
+ * Set the prompt cache key forwarded to providers.
245
+ */
246
+ set promptCacheKey(value: string | undefined);
247
+ /**
248
+ * Static metadata forwarded to every API request when no resolver is installed
249
+ * (e.g. `metadata.user_id` for Anthropic session attribution). Setting this
250
+ * clears any installed resolver.
251
+ *
252
+ * For live/provider-aware metadata (e.g. Anthropic OAuth `account_uuid` that
253
+ * must reflect the credential selected per-request), use
254
+ * {@link setMetadataResolver} and read via {@link metadataForProvider}.
255
+ */
256
+ get metadata(): Record<string, unknown> | undefined;
257
+ set metadata(value: Record<string, unknown> | undefined);
258
+ /**
259
+ * Resolve request metadata for the given provider at call time. When a
260
+ * resolver is installed via {@link setMetadataResolver}, it is invoked with
261
+ * the provider string so the result can be scoped (e.g. `account_uuid` is
262
+ * only included for `"anthropic"` requests). Falls back to the static
263
+ * {@link metadata} value when no resolver is set.
264
+ */
265
+ metadataForProvider(provider: string): Record<string, unknown> | undefined;
266
+ /**
267
+ * Install a function that resolves request metadata at call time. The
268
+ * resolver receives the target provider string and can gate provider-specific
269
+ * fields (e.g. `account_uuid` only for `"anthropic"`). Invoked per LLM
270
+ * request by `agent-loop` after `getApiKey` selects the session-sticky
271
+ * credential. Pass `undefined` to clear and revert to the static
272
+ * {@link metadata} value.
273
+ */
274
+ setMetadataResolver(resolver: ((provider: string) => Record<string, unknown> | undefined) | undefined): void;
275
+ /**
276
+ * Read the active OpenTelemetry configuration. Returns `undefined` when
277
+ * instrumentation is disabled. Callers spawning child runs (e.g. subagent
278
+ * dispatch) forward this to the child's loop so its spans appear under the
279
+ * parent's active context with the subagent's own identity stamped.
280
+ */
281
+ get telemetry(): AgentLoopConfig["telemetry"] | undefined;
282
+ /**
283
+ * Replace the active OpenTelemetry configuration. Pass `undefined` to
284
+ * disable instrumentation. Applies to the *next* `agentLoop` invocation —
285
+ * in-flight loops keep the configuration they started with.
286
+ */
287
+ setTelemetry(telemetry: AgentLoopConfig["telemetry"] | undefined): void;
288
+ /**
289
+ * Get provider-scoped mutable session state store.
290
+ */
291
+ get providerSessionState(): Map<string, ProviderSessionState> | undefined;
292
+ /**
293
+ * Set provider-scoped mutable session state store.
294
+ */
295
+ set providerSessionState(value: Map<string, ProviderSessionState> | undefined);
296
+ /**
297
+ * Get the current thinking budgets.
298
+ */
299
+ get thinkingBudgets(): ThinkingBudgets | undefined;
300
+ /**
301
+ * Set custom thinking budgets for token-based providers.
302
+ */
303
+ set thinkingBudgets(value: ThinkingBudgets | undefined);
304
+ /**
305
+ * Get the current sampling temperature.
306
+ */
307
+ get temperature(): number | undefined;
308
+ /**
309
+ * Set sampling temperature for LLM calls. `undefined` uses provider default.
310
+ */
311
+ set temperature(value: number | undefined);
312
+ get topP(): number | undefined;
313
+ set topP(value: number | undefined);
314
+ get topK(): number | undefined;
315
+ set topK(value: number | undefined);
316
+ get minP(): number | undefined;
317
+ set minP(value: number | undefined);
318
+ get presencePenalty(): number | undefined;
319
+ set presencePenalty(value: number | undefined);
320
+ get repetitionPenalty(): number | undefined;
321
+ set repetitionPenalty(value: number | undefined);
322
+ get serviceTier(): ServiceTier | undefined;
323
+ set serviceTier(value: ServiceTier | undefined);
324
+ get serviceTierResolver(): ((model: Model) => ServiceTier | undefined) | undefined;
325
+ set serviceTierResolver(value: ((model: Model) => ServiceTier | undefined) | undefined);
326
+ get hideThinkingSummary(): boolean | undefined;
327
+ set hideThinkingSummary(value: boolean | undefined);
328
+ /**
329
+ * Get the current max retry delay in milliseconds.
330
+ */
331
+ get maxRetryDelayMs(): number | undefined;
332
+ /**
333
+ * Set the maximum delay to wait for server-requested retries.
334
+ * Set to 0 to disable the cap.
335
+ */
336
+ set maxRetryDelayMs(value: number | undefined);
337
+ get state(): AgentState;
338
+ get appendOnlyContext(): AppendOnlyContextManager | undefined;
339
+ setAppendOnlyContext(manager?: AppendOnlyContextManager): void;
340
+ /**
341
+ * Assemble the provider Context for a side-channel (no-loop) request, mirroring
342
+ * the main loop's prefix (system + normalized tools) so it shares the prompt
343
+ * cache. Never touches the append-only log or the tool-choice queue. Owned/
344
+ * in-band dialect sessions stay tools-less (matching their no-native-tools wire
345
+ * shape and avoiding tool-markup leakage). `llmMessages` is already converted
346
+ * (and, in production, obfuscated) by the caller.
347
+ *
348
+ * `systemPrompt` defaults to the live agent prompt so the side request hits the
349
+ * same cached prefix as the main loop. Callers that must pin a different prompt
350
+ * (e.g. handoff generation, which uses the base prompt rather than a per-turn
351
+ * `before_agent_start` hook override) pass it explicitly.
352
+ */
353
+ buildSideRequestContext(llmMessages: Message[], systemPrompt?: string[]): Promise<Context>;
354
+ subscribe(fn: (e: AgentEvent) => void): () => void;
355
+ setProviderResponseInterceptor(fn: SimpleStreamOptions["onResponse"] | undefined): void;
356
+ setRawSseEventInterceptor(fn: SimpleStreamOptions["onSseEvent"] | undefined): void;
357
+ setAssistantMessageEventInterceptor(fn: ((message: AssistantMessage, event: AssistantMessageEvent) => void) | undefined): void;
358
+ setOnBeforeYield(fn: (() => Promise<void> | void) | undefined): void;
359
+ setOnTurnEnd(fn: ((messages: AgentMessage[], signal?: AbortSignal, context?: AgentTurnEndContext) => Promise<void> | void) | undefined): void;
360
+ /**
361
+ * Provide a source of non-interrupting "aside" messages (e.g. background-job
362
+ * completions, late LSP diagnostics) drained at each step boundary. Never
363
+ * aborts in-flight tools. See `AgentLoopConfig.getAsideMessages`.
364
+ */
365
+ setAsideMessageProvider(fn: (() => AsideMessage[] | Promise<AsideMessage[]>) | undefined): void;
366
+ emitExternalEvent(event: AgentEvent): void;
367
+ setSystemPrompt(v: string[] | string): void;
368
+ setModel(m: Model): void;
369
+ setThinkingLevel(l: Effort | undefined): void;
370
+ setDisableReasoning(disabled: boolean): void;
371
+ setSteeringMode(mode: "all" | "one-at-a-time"): void;
372
+ getSteeringMode(): "all" | "one-at-a-time";
373
+ setFollowUpMode(mode: "all" | "one-at-a-time"): void;
374
+ getFollowUpMode(): "all" | "one-at-a-time";
375
+ setInterruptMode(mode: "immediate" | "wait"): void;
376
+ getInterruptMode(): "immediate" | "wait";
377
+ setTools(t: AgentTool<any>[]): void;
378
+ replaceMessages(ms: AgentMessage[]): void;
379
+ replaceQueues(steering: AgentMessage[], followUp: AgentMessage[]): void;
380
+ appendMessage(m: AgentMessage): void;
381
+ popMessage(): AgentMessage | undefined;
382
+ /**
383
+ * Queue a steering message to interrupt the agent mid-run.
384
+ * Delivered after current tool execution, skips remaining tools.
385
+ */
386
+ steer(m: AgentMessage): void;
387
+ /**
388
+ * Queue a follow-up message to be processed after the agent finishes.
389
+ * Delivered only when agent has no more tool calls or steering messages.
390
+ */
391
+ followUp(m: AgentMessage): void;
392
+ clearSteeringQueue(): void;
393
+ clearFollowUpQueue(): void;
394
+ clearAllQueues(): void;
395
+ hasQueuedMessages(): boolean;
396
+ /** Non-consuming view of the pending steering queue (insertion order, newest
397
+ * last). The session layer derives its queued-message display/count from
398
+ * this live view instead of a mirror, so the agent-core queue stays the
399
+ * single source of truth. */
400
+ peekSteeringQueue(): readonly AgentMessage[];
401
+ /** Non-consuming view of the pending follow-up queue. See
402
+ * {@link peekSteeringQueue}. */
403
+ peekFollowUpQueue(): readonly AgentMessage[];
404
+ get isAborting(): boolean;
405
+ /**
406
+ * Remove and return the last steering message from the queue (LIFO).
407
+ * Used by dequeue keybinding.
408
+ */
409
+ popLastSteer(): AgentMessage | undefined;
410
+ /**
411
+ * Remove and return the last follow-up message from the queue (LIFO).
412
+ * Used by dequeue keybinding.
413
+ */
414
+ popLastFollowUp(): AgentMessage | undefined;
415
+ clearMessages(): void;
416
+ abort(reason?: unknown): void;
417
+ waitForIdle(): Promise<void>;
418
+ reset(): void;
419
+ /** Send a prompt with an AgentMessage */
420
+ prompt(message: AgentMessage | AgentMessage[], options?: AgentPromptOptions): Promise<void>;
421
+ prompt(input: string, options?: AgentPromptOptions): Promise<void>;
422
+ prompt(input: string, images?: ImageContent[], options?: AgentPromptOptions): Promise<void>;
423
+ /**
424
+ * Continue from current context (used for retries and resuming queued messages).
425
+ */
426
+ continue(): Promise<void>;
427
+ }
@@ -0,0 +1,133 @@
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 "jeopi-ai";
17
+ import type { Dialect } from "jeopi-ai/dialect";
18
+ import type { AgentContext } from "./types";
19
+ /** Frozen system prompt + tool spec snapshot. */
20
+ export interface StablePrefixSnapshot {
21
+ systemPrompt: string[];
22
+ tools: Tool[];
23
+ fingerprint: string;
24
+ }
25
+ /** Options threaded through `build()` so the snapshot reflects loop-time settings. */
26
+ export interface BuildOptions {
27
+ /** Inject the `i` intent field into tool schemas (must match agent-loop's normalizeTools). */
28
+ intentTracing: boolean;
29
+ exampleDialect?: Dialect;
30
+ /** Strip tool descriptions from the provider-bound specs (must match normalizeTools). */
31
+ pruneToolDescriptions?: boolean;
32
+ }
33
+ /**
34
+ * A frozen prefix (system prompt + tools) that produces stable byte
35
+ * sequences across `build()` calls.
36
+ *
37
+ * The first `build()` snapshots the live state. Subsequent calls reuse
38
+ * the cached copy until `invalidate()` is called or the live state's
39
+ * fingerprint changes.
40
+ */
41
+ export declare class StablePrefix {
42
+ #private;
43
+ get fingerprint(): string;
44
+ get version(): number;
45
+ get built(): boolean;
46
+ /**
47
+ * Build or rebuild from live context.
48
+ * Returns `true` if the prefix actually changed (cache miss imminent).
49
+ */
50
+ build(context: AgentContext, options: BuildOptions): boolean;
51
+ /** Force rebuild on the next `build()` call. */
52
+ invalidate(): void;
53
+ /**
54
+ * Returns the cached prefix.
55
+ * @throws if `build()` was never called.
56
+ */
57
+ toContext(): {
58
+ systemPrompt: string[];
59
+ tools: Tool[];
60
+ };
61
+ }
62
+ /**
63
+ * Append-only message log at the `Message[]` (provider-level) layer.
64
+ *
65
+ * The only mutation path is `replaceTail()`, reserved for compaction.
66
+ * Every other operation is append-only.
67
+ */
68
+ export declare class AppendOnlyLog {
69
+ #private;
70
+ get length(): number;
71
+ append(message: any): void;
72
+ extend(messages: any[]): void;
73
+ /** Replace the last entry — only legal for compaction. */
74
+ replaceTail(replacement: any): void;
75
+ /** Returns a shallow copy of all entries. */
76
+ toMessages(): Message[];
77
+ /** Direct readonly access for in-place inspection. */
78
+ entries(): readonly Message[];
79
+ /** Drop entries past index `count`, keeping the first `count` byte-stable.
80
+ * Used by {@link AppendOnlyContextManager.syncMessages} to preserve the
81
+ * already-on-the-wire prefix when a later message diverges. */
82
+ truncate(count: number): void;
83
+ clear(): void;
84
+ }
85
+ /**
86
+ * Manages a stable prefix + append-only log for the agent loop.
87
+ *
88
+ * Call `build(context)` each turn to get a `Context` with stable
89
+ * `systemPrompt` and `tools` and append-only messages. Call
90
+ * `syncMessages(normalizedMessages)` after `convertToLlm` each
91
+ * turn to keep the log in sync.
92
+ *
93
+ * Example:
94
+ * ```
95
+ * const mgr = new AppendOnlyContextManager();
96
+ * const ctx = mgr.build(context); // first call snapshots prefix
97
+ * mgr.syncMessages(normalized); // grow the log
98
+ * ctx = mgr.build(context); // subsequent calls use cache
99
+ * ```
100
+ */
101
+ export declare class AppendOnlyContextManager {
102
+ #private;
103
+ readonly prefix: StablePrefix;
104
+ readonly log: AppendOnlyLog;
105
+ build(context: AgentContext, options: BuildOptions): Context;
106
+ /**
107
+ * Sync normalized (provider-level) messages into the append-only log.
108
+ *
109
+ * Three cases:
110
+ *
111
+ * 1. **Append**: same prefix, new tail → push the new entries.
112
+ * 2. **Compaction**: shorter array → clear the log and replay.
113
+ * 3. **In-place rewrite** (per-turn pruning, transformContext re-render,
114
+ * image strip, etc.): find the longest byte-stable prefix between
115
+ * the previously-synced messages and the new ones, drop the log
116
+ * down to that prefix, then append the diverged tail. Earlier
117
+ * revisions cleared the whole log on any digest change, which on
118
+ * llama.cpp / local backends forced a full ~40k-token re-prefill
119
+ * every turn that an extension, prune pass, or steering re-wrap
120
+ * rewrote a single message (#3406). Preserving the stable prefix
121
+ * lets the provider's KV cache stay warm up to the divergence
122
+ * point — the model only re-prefills from the changed message on.
123
+ */
124
+ syncMessages(normalizedMessages: any[]): void;
125
+ /** Reset prefix + log for a model/provider switch while mode stays active. */
126
+ invalidateForModelChange(): void;
127
+ /** Reset the sync cursor AND clear the log. */
128
+ resetSyncCursor(): void;
129
+ appendMessage(message: any): void;
130
+ replaceTailMessage(message: any): void;
131
+ invalidate(): void;
132
+ reset(context: AgentContext, options: BuildOptions): void;
133
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Branch summarization for tree navigation.
3
+ *
4
+ * When navigating to a different point in the session tree, this generates
5
+ * a summary of the branch being left so context isn't lost.
6
+ */
7
+ import type { Api, ApiKey, AssistantMessage, Context, Model, SimpleStreamOptions } from "jeopi-ai";
8
+ import { type AgentTelemetry } from "../telemetry";
9
+ import type { AgentMessage } from "../types";
10
+ import type { ReadonlySessionManager, SessionEntry } from "./entries";
11
+ import { type ConvertToLlm } from "./messages";
12
+ import { type FileOperations } from "./utils";
13
+ export interface BranchSummaryResult {
14
+ summary?: string;
15
+ readFiles?: string[];
16
+ modifiedFiles?: string[];
17
+ aborted?: boolean;
18
+ error?: string;
19
+ }
20
+ /** Details stored in BranchSummaryEntry.details for file tracking */
21
+ export interface BranchSummaryDetails {
22
+ readFiles: string[];
23
+ modifiedFiles: string[];
24
+ }
25
+ export type { FileOperations } from "./utils";
26
+ export interface BranchPreparation {
27
+ /** Messages extracted for summarization, in chronological order */
28
+ messages: AgentMessage[];
29
+ /** File operations extracted from tool calls */
30
+ fileOps: FileOperations;
31
+ /** Total estimated tokens in messages */
32
+ totalTokens: number;
33
+ }
34
+ export interface CollectEntriesResult {
35
+ /** Entries to summarize, in chronological order */
36
+ entries: SessionEntry[];
37
+ /** Common ancestor between old and new position, if any */
38
+ commonAncestorId: string | null;
39
+ }
40
+ export interface GenerateBranchSummaryOptions {
41
+ /** Model to use for summarization */
42
+ model: Model;
43
+ /** API key for the model */
44
+ apiKey: ApiKey;
45
+ /** Abort signal for cancellation */
46
+ signal: AbortSignal;
47
+ /** Optional custom instructions for summarization */
48
+ customInstructions?: string;
49
+ /** Tokens reserved for prompt + LLM response (default 16384) */
50
+ reserveTokens?: number;
51
+ /** Optional metadata forwarded to the underlying API request (e.g. user_id for session attribution). */
52
+ metadata?: Record<string, unknown>;
53
+ /** Convert app-specific messages before serializing the branch summary prompt. */
54
+ convertToLlm?: ConvertToLlm;
55
+ /**
56
+ * Optional telemetry handle. When provided, the branch summary LLM call is
57
+ * wrapped in an OTEL chat span tagged with `pi.gen_ai.oneshot.kind = "branch_summary"`.
58
+ */
59
+ telemetry?: AgentTelemetry;
60
+ /**
61
+ * Optional completion transport override (same contract as
62
+ * {@link SummaryOptions.completeImpl}). Lets the host route the branch
63
+ * summary HTTP request through its provider-concurrency limiter instead
64
+ * of the default `completeSimple` transport.
65
+ */
66
+ completeImpl?: <TApi extends Api>(model: Model<TApi>, ctx: Context, options: SimpleStreamOptions) => Promise<AssistantMessage>;
67
+ }
68
+ /**
69
+ * Collect entries that should be summarized when navigating from one position to another.
70
+ *
71
+ * Walks from oldLeafId back to the common ancestor with targetId, collecting entries
72
+ * along the way. Does NOT stop at compaction boundaries - those are included and their
73
+ * summaries become context.
74
+ *
75
+ * @param session - Session manager (read-only access)
76
+ * @param oldLeafId - Current position (where we're navigating from)
77
+ * @param targetId - Target position (where we're navigating to)
78
+ * @returns Entries to summarize and the common ancestor
79
+ */
80
+ export declare function collectEntriesForBranchSummary(session: ReadonlySessionManager, oldLeafId: string | null, targetId: string): CollectEntriesResult;
81
+ /**
82
+ * Prepare entries for summarization with token budget.
83
+ *
84
+ * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.
85
+ * This ensures we keep the most recent context when the branch is too long.
86
+ *
87
+ * Also collects file operations from:
88
+ * - Tool calls in assistant messages
89
+ * - Existing branch_summary entries' details (for cumulative tracking)
90
+ *
91
+ * @param entries - Entries in chronological order
92
+ * @param tokenBudget - Maximum tokens to include (0 = no limit)
93
+ */
94
+ export declare function prepareBranchEntries(entries: SessionEntry[], tokenBudget?: number): BranchPreparation;
95
+ /**
96
+ * Generate a summary of abandoned branch entries.
97
+ *
98
+ * @param entries - Session entries to summarize (chronological order)
99
+ * @param options - Generation options
100
+ */
101
+ export declare function generateBranchSummary(entries: SessionEntry[], options: GenerateBranchSummaryOptions): Promise<BranchSummaryResult>;