@vib-rato/agent-core 0.16.0

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 (69) hide show
  1. package/CHANGELOG.md +852 -0
  2. package/README.md +493 -0
  3. package/dist/types/agent-loop.d.ts +229 -0
  4. package/dist/types/agent.d.ts +533 -0
  5. package/dist/types/append-only-context.d.ts +141 -0
  6. package/dist/types/attempt-scope.d.ts +84 -0
  7. package/dist/types/compaction/adaptive.d.ts +31 -0
  8. package/dist/types/compaction/branch-summarization.d.ts +103 -0
  9. package/dist/types/compaction/compaction.d.ts +330 -0
  10. package/dist/types/compaction/entries.d.ts +124 -0
  11. package/dist/types/compaction/errors.d.ts +26 -0
  12. package/dist/types/compaction/index.d.ts +12 -0
  13. package/dist/types/compaction/messages.d.ts +61 -0
  14. package/dist/types/compaction/openai.d.ts +65 -0
  15. package/dist/types/compaction/pruning.d.ts +130 -0
  16. package/dist/types/compaction/utils.d.ts +32 -0
  17. package/dist/types/compaction.d.ts +1 -0
  18. package/dist/types/harmony-leak.d.ts +100 -0
  19. package/dist/types/heap-eviction-retainers.test.d.ts +1 -0
  20. package/dist/types/image-placeholder-guard.d.ts +4 -0
  21. package/dist/types/index.d.ts +13 -0
  22. package/dist/types/proxy.d.ts +95 -0
  23. package/dist/types/run-collector.d.ts +223 -0
  24. package/dist/types/run-resource-ledger.d.ts +2 -0
  25. package/dist/types/telemetry.d.ts +605 -0
  26. package/dist/types/thinking.d.ts +18 -0
  27. package/dist/types/tool-dispatch-identity.d.ts +27 -0
  28. package/dist/types/types.d.ts +790 -0
  29. package/package.json +72 -0
  30. package/src/agent-loop.ts +5632 -0
  31. package/src/agent.ts +2437 -0
  32. package/src/append-only-context.ts +496 -0
  33. package/src/attempt-scope.ts +195 -0
  34. package/src/compaction/adaptive.ts +92 -0
  35. package/src/compaction/branch-summarization.ts +358 -0
  36. package/src/compaction/compaction.ts +1569 -0
  37. package/src/compaction/entries.ts +158 -0
  38. package/src/compaction/errors.ts +31 -0
  39. package/src/compaction/index.ts +13 -0
  40. package/src/compaction/messages.ts +212 -0
  41. package/src/compaction/openai.ts +580 -0
  42. package/src/compaction/prompts/auto-handoff-threshold-focus.md +1 -0
  43. package/src/compaction/prompts/branch-summary-context.md +5 -0
  44. package/src/compaction/prompts/branch-summary-preamble.md +2 -0
  45. package/src/compaction/prompts/branch-summary.md +30 -0
  46. package/src/compaction/prompts/compaction-short-summary.md +9 -0
  47. package/src/compaction/prompts/compaction-summary-context.md +5 -0
  48. package/src/compaction/prompts/compaction-summary.md +38 -0
  49. package/src/compaction/prompts/compaction-turn-prefix.md +17 -0
  50. package/src/compaction/prompts/compaction-update-summary.md +45 -0
  51. package/src/compaction/prompts/file-operations.md +10 -0
  52. package/src/compaction/prompts/handoff-document.md +56 -0
  53. package/src/compaction/prompts/summarization-system.md +3 -0
  54. package/src/compaction/pruning.ts +1026 -0
  55. package/src/compaction/utils.ts +189 -0
  56. package/src/compaction.ts +1 -0
  57. package/src/harmony-leak.ts +457 -0
  58. package/src/heap-eviction-retainers.test.ts +293 -0
  59. package/src/image-placeholder-guard.ts +20 -0
  60. package/src/index.ts +23 -0
  61. package/src/prompts/escaped-nonascii-recovery.md +3 -0
  62. package/src/prompts/repeated-tool-failure-recovery.md +1 -0
  63. package/src/proxy.ts +408 -0
  64. package/src/run-collector.ts +728 -0
  65. package/src/run-resource-ledger.ts +345 -0
  66. package/src/telemetry.ts +2161 -0
  67. package/src/thinking.ts +20 -0
  68. package/src/tool-dispatch-identity.ts +87 -0
  69. package/src/types.ts +882 -0
@@ -0,0 +1,92 @@
1
+ export interface AdaptiveCompactionState {
2
+ turnsSinceCompact: number;
3
+ callsInWindow: number;
4
+ windowStart: number;
5
+ lastContextTokens: number;
6
+ lastCompactContextTokens: number | null;
7
+ lastCompactTs: number | null;
8
+ }
9
+
10
+ export interface AdaptiveCompactionDecisionState {
11
+ turnsSinceCompact: number;
12
+ callsInWindow: number;
13
+ lastContextTokens?: number;
14
+ }
15
+
16
+ export interface AdaptiveCompactionOptions {
17
+ enabled: boolean;
18
+ turnWindow: number;
19
+ baseThresholdPercent: number;
20
+ aggression: number;
21
+ minThresholdPercent?: number;
22
+ }
23
+
24
+ export class AdaptiveCompactionTracker {
25
+ #state: AdaptiveCompactionState;
26
+ windowMs: number;
27
+
28
+ constructor(windowMs = 60_000, now = Date.now()) {
29
+ this.windowMs = Number.isFinite(windowMs) && windowMs > 0 ? windowMs : 60_000;
30
+ this.#state = {
31
+ turnsSinceCompact: 0,
32
+ callsInWindow: 0,
33
+ windowStart: now,
34
+ lastContextTokens: 0,
35
+ lastCompactContextTokens: null,
36
+ lastCompactTs: null,
37
+ };
38
+ }
39
+
40
+ setWindowMs(windowMs: number, now = Date.now()): void {
41
+ if (!Number.isFinite(windowMs)) return;
42
+ const nextWindowMs = Math.max(1, windowMs);
43
+ if (nextWindowMs === this.windowMs) return;
44
+ this.windowMs = nextWindowMs;
45
+ this.#state.windowStart = now;
46
+ this.#state.callsInWindow = 0;
47
+ }
48
+
49
+ reset(now = Date.now()): void {
50
+ this.#state = {
51
+ turnsSinceCompact: 0,
52
+ callsInWindow: 0,
53
+ windowStart: now,
54
+ lastContextTokens: 0,
55
+ lastCompactContextTokens: null,
56
+ lastCompactTs: null,
57
+ };
58
+ }
59
+
60
+ recordCall(contextTokens: number, now = Date.now()): void {
61
+ const timestamp = Number.isFinite(now) ? now : Date.now();
62
+ this.#state.turnsSinceCompact += 1;
63
+ if (timestamp - this.#state.windowStart >= this.windowMs) {
64
+ this.#state.windowStart = timestamp;
65
+ this.#state.callsInWindow = 0;
66
+ }
67
+ this.#state.callsInWindow += 1;
68
+ this.#state.lastContextTokens = contextTokens;
69
+ }
70
+
71
+ recordCompact(contextTokens: number, now = Date.now()): void {
72
+ const timestamp = Number.isFinite(now) ? now : Date.now();
73
+ this.#state.turnsSinceCompact = 0;
74
+ this.#state.callsInWindow = 0;
75
+ this.#state.windowStart = timestamp;
76
+ this.#state.lastContextTokens = contextTokens;
77
+ this.#state.lastCompactContextTokens = contextTokens;
78
+ this.#state.lastCompactTs = timestamp;
79
+ }
80
+
81
+ snapshot(): AdaptiveCompactionState {
82
+ return { ...this.#state };
83
+ }
84
+
85
+ decisionState(): AdaptiveCompactionDecisionState {
86
+ return {
87
+ turnsSinceCompact: this.#state.turnsSinceCompact,
88
+ callsInWindow: this.#state.callsInWindow,
89
+ lastContextTokens: this.#state.lastContextTokens,
90
+ };
91
+ }
92
+ }
@@ -0,0 +1,358 @@
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
+
8
+ import type { Model, ProviderSessionState } from "@vib-rato/ai";
9
+ import { prompt } from "@vib-rato/utils";
10
+ import { type AgentTelemetry, instrumentedCompleteSimple } from "../telemetry";
11
+ import type { AgentMessage } from "../types";
12
+ import { estimateMessageTokensHeuristic } from "./compaction";
13
+ import type { ReadonlySessionManager, SessionEntry } from "./entries";
14
+ import {
15
+ type ConvertToLlm,
16
+ convertToLlm,
17
+ createBranchSummaryMessage,
18
+ createCompactionSummaryMessage,
19
+ createCustomMessage,
20
+ } from "./messages";
21
+ import branchSummaryPrompt from "./prompts/branch-summary.md" with { type: "text" };
22
+ import branchSummaryPreamble from "./prompts/branch-summary-preamble.md" with { type: "text" };
23
+ import {
24
+ computeFileLists,
25
+ createFileOps,
26
+ extractFileOpsFromMessage,
27
+ type FileOperations,
28
+ SUMMARIZATION_SYSTEM_PROMPT,
29
+ serializeConversation,
30
+ upsertFileOperations,
31
+ } from "./utils";
32
+
33
+ // ============================================================================
34
+ // Types
35
+ // ============================================================================
36
+
37
+ export interface BranchSummaryResult {
38
+ summary?: string;
39
+ readFiles?: string[];
40
+ modifiedFiles?: string[];
41
+ aborted?: boolean;
42
+ error?: string;
43
+ }
44
+
45
+ /** Details stored in BranchSummaryEntry.details for file tracking */
46
+ export interface BranchSummaryDetails {
47
+ readFiles: string[];
48
+ modifiedFiles: string[];
49
+ }
50
+
51
+ export type { FileOperations } from "./utils";
52
+
53
+ export interface BranchPreparation {
54
+ /** Messages extracted for summarization, in chronological order */
55
+ messages: AgentMessage[];
56
+ /** File operations extracted from tool calls */
57
+ fileOps: FileOperations;
58
+ /** Total estimated tokens in messages */
59
+ totalTokens: number;
60
+ }
61
+
62
+ export interface CollectEntriesResult {
63
+ /** Entries to summarize, in chronological order */
64
+ entries: SessionEntry[];
65
+ /** Common ancestor between old and new position, if any */
66
+ commonAncestorId: string | null;
67
+ }
68
+
69
+ export interface GenerateBranchSummaryOptions {
70
+ /** Model to use for summarization */
71
+ model: Model;
72
+ /** API key for the model */
73
+ apiKey: string;
74
+ /** Abort signal for cancellation */
75
+ signal: AbortSignal;
76
+ /** Optional custom instructions for summarization */
77
+ customInstructions?: string;
78
+ /** Tokens reserved for prompt + LLM response (default 16384) */
79
+ reserveTokens?: number;
80
+ /** Optional metadata forwarded to the underlying API request (e.g. user_id for session attribution). */
81
+ metadata?: Record<string, unknown>;
82
+ /** Convert app-specific messages before serializing the branch summary prompt. */
83
+ convertToLlm?: ConvertToLlm;
84
+ /**
85
+ * Optional telemetry handle. When provided, the branch summary LLM call is
86
+ * wrapped in an OTEL chat span tagged with `pi.gen_ai.oneshot.kind = "branch_summary"`.
87
+ */
88
+ telemetry?: AgentTelemetry;
89
+ /**
90
+ * Provider session affinity id forwarded to the branch summary LLM call so it
91
+ * reuses the live turn's provider/WebSocket session.
92
+ */
93
+ sessionId?: string;
94
+ /** Shared provider state map so the branch summary call reuses session-scoped transport/session caches. */
95
+ providerSessionState?: Map<string, ProviderSessionState>;
96
+ /** Hint that websocket transport should be preferred when supported by the provider implementation. */
97
+ preferWebsockets?: boolean;
98
+ }
99
+
100
+ // ============================================================================
101
+ // Entry Collection
102
+ // ============================================================================
103
+
104
+ /**
105
+ * Collect entries that should be summarized when navigating from one position to another.
106
+ *
107
+ * Walks from oldLeafId back to the common ancestor with targetId, collecting entries
108
+ * along the way. Does NOT stop at compaction boundaries - those are included and their
109
+ * summaries become context.
110
+ *
111
+ * @param session - Session manager (read-only access)
112
+ * @param oldLeafId - Current position (where we're navigating from)
113
+ * @param targetId - Target position (where we're navigating to)
114
+ * @returns Entries to summarize and the common ancestor
115
+ */
116
+ export function collectEntriesForBranchSummary(
117
+ session: ReadonlySessionManager,
118
+ oldLeafId: string | null,
119
+ targetId: string,
120
+ ): CollectEntriesResult {
121
+ // If no old position, nothing to summarize
122
+ if (!oldLeafId) {
123
+ return { entries: [], commonAncestorId: null };
124
+ }
125
+
126
+ // Find common ancestor (deepest node that's on both paths)
127
+ const oldPath = new Set(session.getBranch(oldLeafId).map(e => e.id));
128
+ const targetPath = session.getBranch(targetId);
129
+
130
+ // targetPath is root-first, so iterate backwards to find deepest common ancestor
131
+ let commonAncestorId: string | null = null;
132
+ for (let i = targetPath.length - 1; i >= 0; i--) {
133
+ if (oldPath.has(targetPath[i].id)) {
134
+ commonAncestorId = targetPath[i].id;
135
+ break;
136
+ }
137
+ }
138
+
139
+ // Collect entries from old leaf back to common ancestor
140
+ const entries: SessionEntry[] = [];
141
+ let current: string | null = oldLeafId;
142
+
143
+ while (current && current !== commonAncestorId) {
144
+ const entry = session.getEntry(current);
145
+ if (!entry) break;
146
+ entries.push(entry);
147
+ current = entry.parentId;
148
+ }
149
+
150
+ // Reverse to get chronological order
151
+ entries.reverse();
152
+
153
+ return { entries, commonAncestorId };
154
+ }
155
+
156
+ // ============================================================================
157
+ // Entry to Message Conversion
158
+ // ============================================================================
159
+
160
+ /**
161
+ * Extract AgentMessage from a session entry.
162
+ * Similar to getMessageFromEntry in compaction.ts but also handles compaction entries.
163
+ */
164
+ function getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {
165
+ switch (entry.type) {
166
+ case "message":
167
+ // Skip tool results - context is in assistant's tool call
168
+ if (entry.message.role === "toolResult") return undefined;
169
+ return entry.message;
170
+
171
+ case "custom_message":
172
+ return createCustomMessage(
173
+ entry.customType,
174
+ entry.content,
175
+ entry.display,
176
+ entry.details,
177
+ entry.timestamp,
178
+ entry.attribution,
179
+ );
180
+
181
+ case "branch_summary":
182
+ return createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);
183
+
184
+ case "compaction":
185
+ return createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp, entry.shortSummary);
186
+
187
+ // These don't contribute to conversation content
188
+ case "thinking_level_change":
189
+ case "model_change":
190
+ case "custom":
191
+ case "label":
192
+ case "service_tier_change":
193
+ case "ttsr_injection":
194
+ case "mcp_tool_selection":
195
+ case "session_init":
196
+ case "mode_change":
197
+ return undefined;
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Prepare entries for summarization with token budget.
203
+ *
204
+ * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.
205
+ * This ensures we keep the most recent context when the branch is too long.
206
+ *
207
+ * Also collects file operations from:
208
+ * - Tool calls in assistant messages
209
+ * - Existing branch_summary entries' details (for cumulative tracking)
210
+ *
211
+ * @param entries - Entries in chronological order
212
+ * @param tokenBudget - Maximum tokens to include (0 = no limit)
213
+ */
214
+ export function prepareBranchEntries(entries: SessionEntry[], tokenBudget: number = 0): BranchPreparation {
215
+ const messages: AgentMessage[] = [];
216
+ const fileOps = createFileOps();
217
+ let totalTokens = 0;
218
+
219
+ // First pass: collect file ops from ALL entries (even if they don't fit in token budget)
220
+ // This ensures we capture cumulative file tracking from nested branch summaries
221
+ // Only extract from pi-generated summaries (fromExtension !== true), not extension-generated ones
222
+ for (const entry of entries) {
223
+ if (entry.type === "branch_summary" && !entry.fromExtension && entry.details) {
224
+ const details = entry.details as BranchSummaryDetails;
225
+ if (Array.isArray(details.readFiles)) {
226
+ for (const f of details.readFiles) fileOps.read.add(f);
227
+ }
228
+ if (Array.isArray(details.modifiedFiles)) {
229
+ // Modified files go into both edited and written for proper deduplication
230
+ for (const f of details.modifiedFiles) {
231
+ fileOps.edited.add(f);
232
+ }
233
+ }
234
+ }
235
+ }
236
+
237
+ // Second pass: walk from newest to oldest, adding messages until token budget
238
+ for (let i = entries.length - 1; i >= 0; i--) {
239
+ const entry = entries[i];
240
+ const message = getMessageFromEntry(entry);
241
+ if (!message) continue;
242
+
243
+ // Extract file ops from assistant messages (tool calls)
244
+ extractFileOpsFromMessage(message, fileOps);
245
+
246
+ const tokens = estimateMessageTokensHeuristic(message);
247
+
248
+ // Check budget before adding
249
+ if (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {
250
+ // If this is a summary entry, try to fit it anyway as it's important context
251
+ if (entry.type === "compaction" || entry.type === "branch_summary") {
252
+ if (totalTokens < tokenBudget * 0.9) {
253
+ messages.unshift(message);
254
+ totalTokens += tokens;
255
+ }
256
+ }
257
+ // Stop - we've hit the budget
258
+ break;
259
+ }
260
+
261
+ messages.unshift(message);
262
+ totalTokens += tokens;
263
+ }
264
+
265
+ return { messages, fileOps, totalTokens };
266
+ }
267
+
268
+ // ============================================================================
269
+ // Summary Generation
270
+ // ============================================================================
271
+
272
+ const BRANCH_SUMMARY_PREAMBLE = prompt.render(branchSummaryPreamble);
273
+
274
+ const BRANCH_SUMMARY_PROMPT = prompt.render(branchSummaryPrompt);
275
+
276
+ /**
277
+ * Generate a summary of abandoned branch entries.
278
+ *
279
+ * @param entries - Session entries to summarize (chronological order)
280
+ * @param options - Generation options
281
+ */
282
+ export async function generateBranchSummary(
283
+ entries: SessionEntry[],
284
+ options: GenerateBranchSummaryOptions,
285
+ ): Promise<BranchSummaryResult> {
286
+ const {
287
+ model,
288
+ apiKey,
289
+ signal,
290
+ customInstructions,
291
+ reserveTokens = 16384,
292
+ metadata,
293
+ sessionId,
294
+ providerSessionState,
295
+ preferWebsockets,
296
+ } = options;
297
+
298
+ // Token budget = context window minus reserved space for prompt + response
299
+ const contextWindow = model.contextWindow || 128000;
300
+ const tokenBudget = contextWindow - reserveTokens;
301
+
302
+ const { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);
303
+
304
+ if (messages.length === 0) {
305
+ return { summary: "No content to summarize" };
306
+ }
307
+
308
+ // Transform to LLM-compatible messages, then serialize to text
309
+ // Serialization prevents the model from treating it as a conversation to continue
310
+ const llmMessages = (options.convertToLlm ?? convertToLlm)(messages);
311
+ const conversationText = serializeConversation(llmMessages);
312
+
313
+ // Build prompt
314
+ const instructions = customInstructions || BRANCH_SUMMARY_PROMPT;
315
+ const promptText = `<conversation>\n${conversationText}\n</conversation>\n\n${instructions}`;
316
+
317
+ const summarizationMessages = [
318
+ {
319
+ role: "user" as const,
320
+ content: [{ type: "text" as const, text: promptText }],
321
+ timestamp: Date.now(),
322
+ },
323
+ ];
324
+
325
+ // Call LLM for summarization
326
+ const response = await instrumentedCompleteSimple(
327
+ model,
328
+ { systemPrompt: [SUMMARIZATION_SYSTEM_PROMPT], messages: summarizationMessages },
329
+ { apiKey, signal, maxTokens: 2048, metadata, sessionId, providerSessionState, preferWebsockets },
330
+ { telemetry: options.telemetry, oneshotKind: "branch_summary" },
331
+ );
332
+
333
+ // Check if aborted or errored
334
+ if (response.stopReason === "aborted") {
335
+ return { aborted: true };
336
+ }
337
+ if (response.stopReason === "error") {
338
+ return { error: response.errorMessage || "Summarization failed" };
339
+ }
340
+
341
+ let summary = response.content
342
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
343
+ .map(c => c.text)
344
+ .join("\n");
345
+
346
+ // Prepend preamble to provide context about the branch summary
347
+ summary = BRANCH_SUMMARY_PREAMBLE + summary;
348
+
349
+ // Compute file lists and append to summary
350
+ const { readFiles, modifiedFiles } = computeFileLists(fileOps);
351
+ summary = upsertFileOperations(summary, readFiles, modifiedFiles);
352
+
353
+ return {
354
+ summary: summary || "No summary generated",
355
+ readFiles,
356
+ modifiedFiles,
357
+ };
358
+ }