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