@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,1569 @@
1
+ /**
2
+ * Context compaction for long sessions.
3
+ *
4
+ * Pure functions for compaction logic. The session manager handles I/O,
5
+ * and after compaction the session is reloaded.
6
+ */
7
+
8
+ import * as os from "node:os";
9
+ import {
10
+ type AssistantMessage,
11
+ Effort,
12
+ type Message,
13
+ type MessageAttribution,
14
+ type Model,
15
+ type ProviderSessionState,
16
+ type Usage,
17
+ } from "@vib-rato/ai";
18
+ import { logger, prompt } from "@vib-rato/utils";
19
+ import { type AgentTelemetry, instrumentedCompleteSimple } from "../telemetry";
20
+ import type { AgentMessage, AgentTool } from "../types";
21
+ import type { AdaptiveCompactionDecisionState, AdaptiveCompactionOptions } from "./adaptive";
22
+ import type { CompactionEntry, SessionEntry } from "./entries";
23
+ import { type ConvertToLlm, convertToLlm, createBranchSummaryMessage, createCustomMessage } from "./messages";
24
+ import {
25
+ buildOpenAiNativeHistory,
26
+ getPreservedOpenAiRemoteCompactionData,
27
+ requestOpenAiRemoteCompaction,
28
+ requestRemoteCompaction,
29
+ shouldUseOpenAiRemoteCompaction,
30
+ withOpenAiRemoteCompactionPreserveData,
31
+ } from "./openai";
32
+ import autoHandoffThresholdFocusPrompt from "./prompts/auto-handoff-threshold-focus.md" with { type: "text" };
33
+ import compactionSummaryPrompt from "./prompts/compaction-summary.md" with { type: "text" };
34
+ import compactionTurnPrefixPrompt from "./prompts/compaction-turn-prefix.md" with { type: "text" };
35
+ import compactionUpdateSummaryPrompt from "./prompts/compaction-update-summary.md" with { type: "text" };
36
+ import handoffDocumentPrompt from "./prompts/handoff-document.md" with { type: "text" };
37
+ import {
38
+ computeFileLists,
39
+ createFileOps,
40
+ extractFileOpsFromMessage,
41
+ type FileOperations,
42
+ SUMMARIZATION_SYSTEM_PROMPT,
43
+ serializeConversation,
44
+ upsertFileOperations,
45
+ } from "./utils";
46
+
47
+ // ============================================================================
48
+ // File Operation Tracking
49
+ // ============================================================================
50
+
51
+ /** Details stored in CompactionEntry.details for file tracking */
52
+ export interface CompactionDetails {
53
+ readFiles: string[];
54
+ modifiedFiles: string[];
55
+ }
56
+
57
+ /**
58
+ * Extract file operations from messages and previous compaction entries.
59
+ */
60
+ function extractFileOperations(
61
+ messages: AgentMessage[],
62
+ entries: SessionEntry[],
63
+ prevCompactionIndex: number,
64
+ ): FileOperations {
65
+ const fileOps = createFileOps();
66
+
67
+ // Collect from previous compaction's details (if pi-generated)
68
+ if (prevCompactionIndex >= 0) {
69
+ const prevCompaction = entries[prevCompactionIndex] as CompactionEntry;
70
+ if (!prevCompaction.fromExtension && prevCompaction.details) {
71
+ const details = prevCompaction.details as CompactionDetails;
72
+ if (Array.isArray(details.readFiles)) {
73
+ for (const f of details.readFiles) fileOps.read.add(f);
74
+ }
75
+ if (Array.isArray(details.modifiedFiles)) {
76
+ for (const f of details.modifiedFiles) fileOps.edited.add(f);
77
+ }
78
+ }
79
+ }
80
+
81
+ // Extract from tool calls in messages
82
+ for (const msg of messages) {
83
+ extractFileOpsFromMessage(msg, fileOps);
84
+ }
85
+
86
+ return fileOps;
87
+ }
88
+
89
+ // ============================================================================
90
+ // Message Extraction
91
+ // ============================================================================
92
+
93
+ /**
94
+ * Extract AgentMessage from an entry if it produces one.
95
+ * Returns undefined for entries that don't contribute to LLM context.
96
+ */
97
+ function getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {
98
+ if (entry.type === "message") {
99
+ return entry.message;
100
+ }
101
+ if (entry.type === "custom_message") {
102
+ return createCustomMessage(
103
+ entry.customType,
104
+ entry.content,
105
+ entry.display,
106
+ entry.details,
107
+ entry.timestamp,
108
+ entry.attribution,
109
+ );
110
+ }
111
+ if (entry.type === "branch_summary") {
112
+ return createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);
113
+ }
114
+ return undefined;
115
+ }
116
+
117
+ /** Result from compact() - SessionManager adds uuid/parentUuid when saving */
118
+ export interface CompactionResult<T = unknown> {
119
+ summary: string;
120
+ /** Short PR-style summary for display purposes. */
121
+ shortSummary?: string;
122
+ firstKeptEntryId: string;
123
+ tokensBefore: number;
124
+ /** Hook-specific data (e.g., ArtifactIndex, version markers for structured compaction) */
125
+ details?: T;
126
+ /** Hook-provided data to persist alongside compaction entry. */
127
+ preserveData?: Record<string, unknown>;
128
+ }
129
+
130
+ // ============================================================================
131
+ // Types
132
+ // ============================================================================
133
+
134
+ export interface CompactionSettings {
135
+ enabled: boolean;
136
+ strategy?: "context-full" | "handoff" | "off";
137
+ thresholdPercent?: number;
138
+ thresholdTokens?: number;
139
+ adaptive?: AdaptiveCompactionOptions;
140
+ adaptiveState?: AdaptiveCompactionDecisionState;
141
+ reserveTokens: number;
142
+ keepRecentTokens: number;
143
+ autoContinue?: boolean;
144
+ remoteEnabled?: boolean;
145
+ remoteEndpoint?: string;
146
+ }
147
+
148
+ export type RemoteCompactionFallbackHealthEvent =
149
+ | { kind: "success"; model: string; provider: string }
150
+ | { kind: "fallback"; model: string; provider: string; error: string };
151
+
152
+ export interface RemoteCompactionFallbackHealthHooks {
153
+ recordRemoteCompactionFallback(event: RemoteCompactionFallbackHealthEvent): void;
154
+ }
155
+
156
+ function isAbortError(error: unknown): boolean {
157
+ return error instanceof Error && error.name === "AbortError";
158
+ }
159
+
160
+ export const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {
161
+ enabled: true,
162
+ strategy: "context-full",
163
+ thresholdPercent: -1,
164
+ thresholdTokens: -1,
165
+ reserveTokens: 16384,
166
+ keepRecentTokens: 20000,
167
+ autoContinue: true,
168
+ remoteEnabled: true,
169
+ };
170
+
171
+ export function computeAdaptiveThresholdPercent(
172
+ basePercent: number,
173
+ contextTokens: number,
174
+ contextWindow: number,
175
+ state: AdaptiveCompactionDecisionState | undefined,
176
+ options: AdaptiveCompactionOptions | undefined,
177
+ ): number {
178
+ const clampedBasePercent = Number.isFinite(basePercent) ? Math.min(99, Math.max(1, basePercent)) : 85;
179
+ if (!options?.enabled) return basePercent;
180
+ if (!state || !Number.isFinite(contextWindow) || contextWindow <= 0) return clampedBasePercent;
181
+ if (!Number.isFinite(options.turnWindow) || options.turnWindow <= 0) return clampedBasePercent;
182
+
183
+ const safeContextTokens = Number.isFinite(contextTokens) ? Math.max(0, contextTokens) : 0;
184
+ const fillRatio = safeContextTokens / contextWindow;
185
+ const baseRatio = clampedBasePercent / 100;
186
+ if (fillRatio < baseRatio * 0.7) return clampedBasePercent;
187
+
188
+ const turnsSinceCompact = Number.isFinite(state.turnsSinceCompact) ? Math.max(0, state.turnsSinceCompact) : 0;
189
+ const callsInWindow = Number.isFinite(state.callsInWindow) ? Math.max(0, state.callsInWindow) : 0;
190
+ if (turnsSinceCompact <= 3) return clampedBasePercent;
191
+ const windowTurns = Math.max(1, options.turnWindow * 4);
192
+ const intensity = Math.min(1, callsInWindow / windowTurns);
193
+ const aggression = Number.isFinite(options.aggression) ? Math.min(1, Math.max(0, options.aggression)) : 0;
194
+ const configuredMinThresholdPercent = options.minThresholdPercent;
195
+ const minThresholdPercent = Math.min(
196
+ clampedBasePercent,
197
+ typeof configuredMinThresholdPercent === "number" && Number.isFinite(configuredMinThresholdPercent)
198
+ ? Math.max(1, configuredMinThresholdPercent)
199
+ : clampedBasePercent * 0.5,
200
+ );
201
+ const loweredPercent = clampedBasePercent - (clampedBasePercent - minThresholdPercent) * aggression * intensity;
202
+ return Math.max(1, Math.min(99, Math.round(loweredPercent)));
203
+ }
204
+
205
+ // ============================================================================
206
+ // Token calculation
207
+ // ============================================================================
208
+
209
+ /**
210
+ * Calculate total context tokens from usage.
211
+ * Uses the native totalTokens field when available, falls back to computing from components.
212
+ */
213
+ export function calculateContextTokens(usage: Usage): number {
214
+ return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
215
+ }
216
+
217
+ export function calculatePromptTokens(usage: Usage): number {
218
+ const promptTokens = usage.input + usage.cacheRead + usage.cacheWrite;
219
+ if (promptTokens > 0) {
220
+ return promptTokens;
221
+ }
222
+ return calculateContextTokens(usage);
223
+ }
224
+
225
+ /**
226
+ * Get usage from an assistant message if available.
227
+ * Skips aborted and error messages as they don't have valid usage data.
228
+ */
229
+ function getAssistantUsage(msg: AgentMessage): Usage | undefined {
230
+ if (msg.role === "assistant" && "usage" in msg) {
231
+ const assistantMsg = msg as AssistantMessage;
232
+ if (assistantMsg.stopReason !== "aborted" && assistantMsg.stopReason !== "error" && assistantMsg.usage) {
233
+ return assistantMsg.usage;
234
+ }
235
+ }
236
+ return undefined;
237
+ }
238
+
239
+ /**
240
+ * Find the last non-aborted assistant message usage from session entries.
241
+ */
242
+ export function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {
243
+ for (let i = entries.length - 1; i >= 0; i--) {
244
+ const entry = entries[i];
245
+ if (entry.type === "message") {
246
+ const usage = getAssistantUsage(entry.message);
247
+ if (usage) return usage;
248
+ }
249
+ }
250
+ return undefined;
251
+ }
252
+
253
+ /**
254
+ * Effective reserve: the largest of 15% of the context window, the configured floor,
255
+ * and the model's reserved completion budget (`maxOutputTokens`).
256
+ *
257
+ * Reserving `maxOutputTokens` keeps the safe input/prompt-packing budget below the
258
+ * *total* context window for models whose completion reservation exceeds the 15%
259
+ * floor (e.g. a 400K-context model with 128K max output reserves 128K, not 60K, so
260
+ * input is capped near 272K instead of 340K).
261
+ */
262
+ export function effectiveReserveTokens(
263
+ contextWindow: number,
264
+ settings: CompactionSettings,
265
+ maxOutputTokens = 0,
266
+ ): number {
267
+ return Math.max(Math.floor(contextWindow * 0.15), settings.reserveTokens, Math.max(0, maxOutputTokens));
268
+ }
269
+
270
+ /**
271
+ * Check if compaction should trigger based on context usage.
272
+ *
273
+ * `maxOutputTokens` is the model's reserved completion budget; it is excluded from
274
+ * the safe input budget so prompt + reserved output cannot exceed the total window.
275
+ */
276
+ export function shouldCompact(
277
+ contextTokens: number,
278
+ contextWindow: number,
279
+ settings: CompactionSettings,
280
+ maxOutputTokens = 0,
281
+ ): boolean {
282
+ if (!settings.enabled || settings.strategy === "off" || contextWindow <= 0) return false;
283
+ const thresholdTokens = resolveThresholdTokens(contextWindow, settings, maxOutputTokens, contextTokens);
284
+ return contextTokens > thresholdTokens;
285
+ }
286
+
287
+ /** Reason a compaction was triggered. `token` is the normal user-configurable path; the rest are emergency floors. */
288
+ export type CompactionTriggerReason =
289
+ | "token"
290
+ | "heap"
291
+ | "retainedMemory"
292
+ | "transcriptFile"
293
+ | "providerBytes"
294
+ | "messageCount"
295
+ | "imageBytes";
296
+
297
+ /** A point-in-time resource sample. Supplied by an injectable sampler so tests never read real RSS. */
298
+ export interface EmergencyCompactionSample {
299
+ /** Resident heap bytes (e.g. process.memoryUsage().heapUsed). */
300
+ heapUsedBytes: number;
301
+ /** Approximate serialized provider-context bytes. */
302
+ providerBytes: number;
303
+ /** Provider-visible message count. */
304
+ messageCount: number;
305
+ /** Approximate inline image bytes in the provider context. */
306
+ imageBytes: number;
307
+ /** Bytes retained by session resident image sentinels; separate from provider-visible bytes. */
308
+ sessionResidentImageBytes?: number;
309
+ /** Bytes retained by non-provider materialized/session-local caches. */
310
+ materializedResidentBytes?: number;
311
+ /** Number of live TUI chat-container children. */
312
+ tuiChatChildren?: number;
313
+ /** Bytes retained by TUI render caches. */
314
+ tuiCachedRenderBytes?: number;
315
+ /** On-disk JSONL transcript file size in bytes; 0/undefined when unknown. */
316
+ transcriptFileBytes?: number;
317
+ }
318
+
319
+ export interface EmergencyCompactionLimits {
320
+ heapUsedBytes: number;
321
+ providerBytes: number;
322
+ messageCount: number;
323
+ imageBytes: number;
324
+ retainedMemoryBytes?: number;
325
+ retainedMemoryDiagnosticBytes?: number;
326
+ tuiChatChildren?: number;
327
+ tuiChatChildrenDiagnostic?: number;
328
+ transcriptFileBytes?: number;
329
+ }
330
+
331
+ const MAX_EMERGENCY_HEAP_FLOOR_BYTES = 1_536 * 1024 * 1024; // 1.5 GiB resident heap
332
+ const EMERGENCY_RETAINED_MEMORY_BYTES = 128 * 1024 * 1024;
333
+ const DIAGNOSTIC_RETAINED_MEMORY_BYTES = 64 * 1024 * 1024;
334
+ const EMERGENCY_TUI_CHAT_CHILDREN = 1000;
335
+ const DIAGNOSTIC_TUI_CHAT_CHILDREN = 700;
336
+ const EMERGENCY_TRANSCRIPT_FILE_BYTES = 48 * 1024 * 1024; // 48 MiB (75% of the 64 MiB managed cap)
337
+ let retainedMemoryDiagnosticActive = false;
338
+ let tuiChatChildrenDiagnosticActive = false;
339
+
340
+ export function resetEmergencyRetainedMemoryDiagnosticsForTests(): void {
341
+ retainedMemoryDiagnosticActive = false;
342
+ tuiChatChildrenDiagnosticActive = false;
343
+ }
344
+
345
+ export function resolveEmergencyCompactionLimits(totalMemoryBytes: number = os.totalmem()): EmergencyCompactionLimits {
346
+ // Invalid or non-positive total memory (bad injection, exotic platform)
347
+ // must never disable the heap floor — fall back to the fixed 1.5 GiB cap.
348
+ const safeTotal =
349
+ Number.isFinite(totalMemoryBytes) && totalMemoryBytes > 0 ? totalMemoryBytes : Number.POSITIVE_INFINITY;
350
+ return {
351
+ heapUsedBytes: Math.min(MAX_EMERGENCY_HEAP_FLOOR_BYTES, Math.floor(0.5 * safeTotal)),
352
+ providerBytes: 24 * 1024 * 1024, // 24 MiB serialized provider context
353
+ messageCount: 4000,
354
+ imageBytes: 64 * 1024 * 1024, // 64 MiB inline image bytes
355
+ retainedMemoryBytes: EMERGENCY_RETAINED_MEMORY_BYTES,
356
+ retainedMemoryDiagnosticBytes: DIAGNOSTIC_RETAINED_MEMORY_BYTES,
357
+ tuiChatChildren: EMERGENCY_TUI_CHAT_CHILDREN,
358
+ tuiChatChildrenDiagnostic: DIAGNOSTIC_TUI_CHAT_CHILDREN,
359
+ transcriptFileBytes: EMERGENCY_TRANSCRIPT_FILE_BYTES,
360
+ };
361
+ }
362
+
363
+ /**
364
+ * Non-disableable emergency floors. These sit well above normal usage and exist so a
365
+ * long session on weak hardware compacts before OOM even when token-based compaction is
366
+ * disabled or its threshold is set too high. They are NOT user-tunable down to zero.
367
+ */
368
+ export const DEFAULT_EMERGENCY_COMPACTION_LIMITS: EmergencyCompactionLimits = resolveEmergencyCompactionLimits();
369
+
370
+ /**
371
+ * Returns the first emergency limit exceeded (heap > retainedMemory > transcriptFile > providerBytes > imageBytes > messageCount),
372
+ * or null when none is. Pure apart from retained-memory diagnostics; the caller routes the result through the
373
+ * normal pair-safe `compact()` cut logic so a tool_use/tool_result pair is never split.
374
+ */
375
+ export function emergencyCompactionReason(
376
+ sample: EmergencyCompactionSample,
377
+ limits: EmergencyCompactionLimits = resolveEmergencyCompactionLimits(),
378
+ ): CompactionTriggerReason | null {
379
+ const retainedMemoryBytes = (sample.materializedResidentBytes ?? 0) + (sample.tuiCachedRenderBytes ?? 0);
380
+ const tuiChatChildren = sample.tuiChatChildren ?? 0;
381
+ const retainedDiagnostic =
382
+ retainedMemoryBytes >= (limits.retainedMemoryDiagnosticBytes ?? DIAGNOSTIC_RETAINED_MEMORY_BYTES);
383
+ const childDiagnostic = tuiChatChildren >= (limits.tuiChatChildrenDiagnostic ?? DIAGNOSTIC_TUI_CHAT_CHILDREN);
384
+ if (retainedDiagnostic && !retainedMemoryDiagnosticActive) {
385
+ logger.warn("Emergency compaction retained-memory diagnostic threshold crossed", {
386
+ retainedMemoryBytes,
387
+ limitBytes: limits.retainedMemoryDiagnosticBytes ?? DIAGNOSTIC_RETAINED_MEMORY_BYTES,
388
+ });
389
+ }
390
+ if (childDiagnostic && !tuiChatChildrenDiagnosticActive) {
391
+ logger.warn("Emergency compaction TUI chat-child diagnostic threshold crossed", {
392
+ tuiChatChildren,
393
+ limit: limits.tuiChatChildrenDiagnostic ?? DIAGNOSTIC_TUI_CHAT_CHILDREN,
394
+ });
395
+ }
396
+ retainedMemoryDiagnosticActive = retainedDiagnostic;
397
+ tuiChatChildrenDiagnosticActive = childDiagnostic;
398
+
399
+ if (sample.heapUsedBytes > limits.heapUsedBytes) return "heap";
400
+ if (
401
+ retainedMemoryBytes >= (limits.retainedMemoryBytes ?? EMERGENCY_RETAINED_MEMORY_BYTES) ||
402
+ tuiChatChildren >= (limits.tuiChatChildren ?? EMERGENCY_TUI_CHAT_CHILDREN)
403
+ )
404
+ return "retainedMemory";
405
+ if (
406
+ sample.transcriptFileBytes &&
407
+ sample.transcriptFileBytes > (limits.transcriptFileBytes ?? EMERGENCY_TRANSCRIPT_FILE_BYTES)
408
+ )
409
+ return "transcriptFile";
410
+ if (sample.providerBytes > limits.providerBytes) return "providerBytes";
411
+ if (sample.imageBytes > limits.imageBytes) return "imageBytes";
412
+ if (sample.messageCount > limits.messageCount) return "messageCount";
413
+ return null;
414
+ }
415
+
416
+ export function resolveThresholdTokens(
417
+ contextWindow: number,
418
+ settings: CompactionSettings,
419
+ maxOutputTokens = 0,
420
+ contextTokens?: number,
421
+ ): number {
422
+ // Fixed token limit takes priority over percentage
423
+ const thresholdTokens = settings.thresholdTokens;
424
+ if (typeof thresholdTokens === "number" && Number.isFinite(thresholdTokens) && thresholdTokens > 0) {
425
+ // Clamp to [1, contextWindow - 1] so there's always room
426
+ return Math.min(contextWindow - 1, Math.max(1, thresholdTokens));
427
+ }
428
+
429
+ // Percentage-based threshold
430
+ const thresholdPercent = settings.thresholdPercent;
431
+ if (typeof thresholdPercent !== "number" || !Number.isFinite(thresholdPercent) || thresholdPercent <= 0) {
432
+ if (!settings.adaptive?.enabled) {
433
+ return contextWindow - effectiveReserveTokens(contextWindow, settings, maxOutputTokens);
434
+ }
435
+ const adaptiveBasePercent = Number.isFinite(settings.adaptive.baseThresholdPercent)
436
+ ? Math.min(99, Math.max(1, settings.adaptive.baseThresholdPercent))
437
+ : 85;
438
+ const adaptiveThresholdPercent = computeAdaptiveThresholdPercent(
439
+ adaptiveBasePercent,
440
+ adaptiveContextTokens(contextTokens, settings.adaptiveState?.lastContextTokens),
441
+ contextWindow,
442
+ settings.adaptiveState,
443
+ settings.adaptive,
444
+ );
445
+ return Math.floor(contextWindow * (adaptiveThresholdPercent / 100));
446
+ }
447
+ const clampedThresholdPercent = Math.min(99, Math.max(1, thresholdPercent));
448
+ const adaptiveThresholdPercent = computeAdaptiveThresholdPercent(
449
+ settings.adaptive?.baseThresholdPercent ?? clampedThresholdPercent,
450
+ adaptiveContextTokens(contextTokens, settings.adaptiveState?.lastContextTokens),
451
+ contextWindow,
452
+ settings.adaptiveState,
453
+ settings.adaptive,
454
+ );
455
+ const effectiveThresholdPercent = settings.adaptive?.enabled ? adaptiveThresholdPercent : clampedThresholdPercent;
456
+ return Math.floor(contextWindow * (effectiveThresholdPercent / 100));
457
+ }
458
+
459
+ function adaptiveContextTokens(contextTokens: number | undefined, lastContextTokens: number | undefined): number {
460
+ if (contextTokens !== undefined && Number.isFinite(contextTokens)) return Math.max(0, contextTokens);
461
+ if (typeof lastContextTokens === "number" && Number.isFinite(lastContextTokens))
462
+ return Math.max(0, lastContextTokens);
463
+ return 0;
464
+ }
465
+
466
+ // ============================================================================
467
+ // Cut point detection
468
+ // ============================================================================
469
+
470
+ /**
471
+ * Image content has no tokenizer representation; charge a fixed estimate
472
+ * matching what providers typically bill for inline images.
473
+ */
474
+ export const IMAGE_TOKEN_ESTIMATE = 1200;
475
+ /**
476
+ * Estimate tokens for collected message fragments using the native-free
477
+ * heuristic. Provider usage is the authoritative anchor for context-changing
478
+ * decisions (see {@link calculatePromptTokens}); this chars/4 estimate covers
479
+ * only unsent/trailing deltas and per-entry budgeting, and callers add a
480
+ * conservative inflation factor where threshold safety requires it.
481
+ */
482
+ function countCollectedMessageFragments(collected: { fragments: string[]; extra: number }): number {
483
+ return estimateTextTokensHeuristic(collected.fragments) + collected.extra;
484
+ }
485
+
486
+ /**
487
+ * Average bytes per token for the cheap heuristic. ~4 bytes/token is the
488
+ * conventional approximation for English/code text under modern BPE
489
+ * vocabularies; it intentionally errs slightly low-precision in exchange for
490
+ * never touching the native tokenizer (and its ~50MB BPE table).
491
+ */
492
+ const HEURISTIC_BYTES_PER_TOKEN = 4;
493
+
494
+ /**
495
+ * Token-dense character weight for the script-aware heuristic.
496
+ *
497
+ * Common-BMP CJK blocks (Hangul, unified/compat Han, Kana, CJK punctuation,
498
+ * full-width forms) tokenize at ~0.6–1.0 tokens per character under
499
+ * o200k-class BPE vocabularies (measured o200k_base: Hangul prose 0.604,
500
+ * spaceless Hangul 0.964, Han 0.793, Kana 0.740 tokens/char — versus the
501
+ * 0.25 the chars/4 heuristic assumes). Each such character is charged 1
502
+ * token: an upper bound for these measured blocks whose only failure mode is
503
+ * compacting slightly early, while undercounting risks overflowing the
504
+ * provider window.
505
+ *
506
+ * Surrogate code units are charged 0.5 each, i.e. 1 token per supplementary
507
+ * code point (supplementary Han extensions, emoji, and other astral chars).
508
+ * That is a floor rather than an upper bound — rare ideographs and emoji can
509
+ * cost several tokens — but it is strictly safer than the 0.5-per-pair the
510
+ * plain chars/4 rule produced.
511
+ */
512
+ function tokenDenseCharWeight(text: string): { weight: number; units: number } {
513
+ let weight = 0;
514
+ let units = 0;
515
+ for (let i = 0; i < text.length; i++) {
516
+ const c = text.charCodeAt(i);
517
+ if (
518
+ (c >= 0x1100 && c <= 0x11ff) || // Hangul Jamo
519
+ (c >= 0x3000 && c <= 0x303f) || // CJK symbols & punctuation
520
+ (c >= 0x3040 && c <= 0x30ff) || // Hiragana & Katakana
521
+ (c >= 0x3130 && c <= 0x318f) || // Hangul compatibility Jamo
522
+ (c >= 0x3400 && c <= 0x4dbf) || // CJK ideographs extension A
523
+ (c >= 0x4e00 && c <= 0x9fff) || // CJK unified ideographs
524
+ (c >= 0xac00 && c <= 0xd7af) || // Hangul syllables
525
+ (c >= 0xf900 && c <= 0xfaff) || // CJK compatibility ideographs
526
+ (c >= 0xff00 && c <= 0xffef) // Half/full-width forms
527
+ ) {
528
+ weight += 1;
529
+ units += 1;
530
+ } else if (c >= 0xd800 && c <= 0xdfff) {
531
+ // Surrogate half: a supplementary code point contributes two units.
532
+ weight += 0.5;
533
+ units += 1;
534
+ }
535
+ }
536
+ return { weight, units };
537
+ }
538
+
539
+ /**
540
+ * Script-aware native-free token estimate for a plain string fragment:
541
+ * token-dense characters cost ~1 token each, everything else chars/4.
542
+ */
543
+ function estimateFragmentTokensHeuristic(fragment: string): { dense: number; otherChars: number } {
544
+ const { weight, units } = tokenDenseCharWeight(fragment);
545
+ return { dense: weight, otherChars: fragment.length - units };
546
+ }
547
+
548
+ /**
549
+ * Native-free token estimate for a message. This is the only message
550
+ * token estimator: provider usage (see {@link calculatePromptTokens}) anchors
551
+ * the already-sent context, and this covers unsent/trailing deltas, per-entry
552
+ * budgeting, and display surfaces. Callers add a conservative inflation factor
553
+ * where compaction-threshold safety requires it.
554
+ */
555
+ export function estimateMessageTokensHeuristic(message: AgentMessage): number {
556
+ const { fragments, extra } = collectMessageFragments(message);
557
+ return extra + estimateTextTokensHeuristic(fragments);
558
+ }
559
+
560
+ /**
561
+ * Script-aware native-free token estimate for plain string fragments.
562
+ * Fragment-level counterpart of {@link estimateMessageTokensHeuristic}.
563
+ */
564
+ export function estimateTextTokensHeuristic(fragments: string | readonly string[]): number {
565
+ const list = typeof fragments === "string" ? [fragments] : fragments;
566
+ let dense = 0;
567
+ let otherChars = 0;
568
+ for (const fragment of list) {
569
+ const counts = estimateFragmentTokensHeuristic(fragment);
570
+ dense += counts.dense;
571
+ otherChars += counts.otherChars;
572
+ }
573
+ return Math.ceil(dense + Math.max(0, otherChars) / HEURISTIC_BYTES_PER_TOKEN);
574
+ }
575
+
576
+ /** Shared content walk for both the native and heuristic estimators. */
577
+ function collectMessageFragments(message: AgentMessage): { fragments: string[]; extra: number } {
578
+ const fragments: string[] = [];
579
+ let extra = 0;
580
+ if ((message as { role?: string }).role === "bashExecution") {
581
+ const bash = message as { command?: unknown; output?: unknown };
582
+ if (typeof bash.command === "string") fragments.push(bash.command);
583
+ if (typeof bash.output === "string") fragments.push(bash.output);
584
+ return { fragments, extra };
585
+ }
586
+
587
+ switch (message.role) {
588
+ case "user":
589
+ case "custom": {
590
+ const content = (message as { content: string | Array<{ type: string; text?: string }> }).content;
591
+ if (typeof content === "string") {
592
+ fragments.push(content);
593
+ } else if (Array.isArray(content)) {
594
+ for (const block of content) {
595
+ if (block.type === "text" && block.text) {
596
+ fragments.push(block.text);
597
+ }
598
+ }
599
+ }
600
+ break;
601
+ }
602
+ case "assistant": {
603
+ const assistant = message as AssistantMessage;
604
+ for (const block of assistant.content) {
605
+ if (block.type === "text") {
606
+ fragments.push(block.text);
607
+ } else if (block.type === "thinking") {
608
+ fragments.push(block.thinking);
609
+ } else if (block.type === "toolCall") {
610
+ fragments.push(block.name);
611
+ // `arguments` is typed non-null, but persisted history can carry a
612
+ // null/undefined payload from an aborted or malformed tool call;
613
+ // JSON.stringify returns undefined for those, and the token
614
+ // fingerprint below requires string fragments.
615
+ fragments.push(JSON.stringify(block.arguments) ?? "null");
616
+ }
617
+ }
618
+ break;
619
+ }
620
+ case "hookMessage":
621
+ case "toolResult": {
622
+ if (typeof message.content === "string") {
623
+ fragments.push(message.content);
624
+ } else {
625
+ for (const block of message.content) {
626
+ if (block.type === "text" && block.text) {
627
+ fragments.push(block.text);
628
+ } else if (block.type === "image") {
629
+ extra += IMAGE_TOKEN_ESTIMATE;
630
+ }
631
+ }
632
+ }
633
+ break;
634
+ }
635
+ case "branchSummary":
636
+ case "compactionSummary": {
637
+ fragments.push(message.summary);
638
+ break;
639
+ }
640
+ default:
641
+ break;
642
+ }
643
+
644
+ return { fragments, extra };
645
+ }
646
+
647
+ function entryTokenFingerprint(
648
+ entry: SessionEntry,
649
+ message: AgentMessage,
650
+ collected: { fragments: string[]; extra: number },
651
+ ): string {
652
+ const maybePruned = message as { prunedAt?: unknown };
653
+ let fingerprint = `${entry.type.length}:${entry.type}${(entry.id ?? "").length}:${entry.id ?? ""}${message.role.length}:${message.role}${String(collected.extra).length}:${String(collected.extra)}${collected.fragments.length}:`;
654
+ for (const fragment of collected.fragments) fingerprint += `${fragment.length}:${fragment}`;
655
+ if (maybePruned.prunedAt !== undefined) {
656
+ const prunedAt = String(maybePruned.prunedAt);
657
+ fingerprint += `prunedAt${prunedAt.length}:${prunedAt}`;
658
+ }
659
+ return fingerprint;
660
+ }
661
+
662
+ const entryTokenCache = new WeakMap<SessionEntry, { fingerprint: string; tokens: number }>();
663
+
664
+ export function estimateEntryTokens(entry: SessionEntry): number {
665
+ const msg = getMessageFromEntry(entry);
666
+ if (!msg) return 0;
667
+ const collected = collectMessageFragments(msg);
668
+ const fingerprint = entryTokenFingerprint(entry, msg, collected);
669
+ const cached = entryTokenCache.get(entry);
670
+ if (cached?.fingerprint === fingerprint) return cached.tokens;
671
+ const tokens = countCollectedMessageFragments(collected);
672
+ entryTokenCache.set(entry, { fingerprint, tokens });
673
+ return tokens;
674
+ }
675
+
676
+ export function estimateEntriesTokens(entries: SessionEntry[], startIndex: number, endIndex: number): number {
677
+ let total = 0;
678
+ for (let i = startIndex; i < endIndex; i++) {
679
+ total += estimateEntryTokens(entries[i]);
680
+ }
681
+ return total;
682
+ }
683
+
684
+ /**
685
+ * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.
686
+ * Never cut at tool results (they must follow their tool call).
687
+ * When we cut at an assistant message with tool calls, its tool results follow it
688
+ * and will be kept.
689
+ * BashExecutionMessage is treated like a user message (user-initiated context).
690
+ */
691
+ function findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {
692
+ const cutPoints: number[] = [];
693
+ for (let i = startIndex; i < endIndex; i++) {
694
+ const entry = entries[i];
695
+ switch (entry.type) {
696
+ case "message": {
697
+ const role = entry.message.role as string;
698
+ switch (role) {
699
+ case "bashExecution":
700
+ case "hookMessage":
701
+ case "branchSummary":
702
+ case "compactionSummary":
703
+ case "user":
704
+ case "assistant":
705
+ cutPoints.push(i);
706
+ break;
707
+ case "toolResult":
708
+ break;
709
+ }
710
+ break;
711
+ }
712
+ case "thinking_level_change":
713
+ case "model_change":
714
+ case "compaction":
715
+ case "branch_summary":
716
+ case "custom":
717
+ case "custom_message":
718
+ case "label":
719
+ }
720
+ // branch_summary and custom_message are user-role messages, valid cut points
721
+ if (entry.type === "branch_summary" || entry.type === "custom_message") {
722
+ cutPoints.push(i);
723
+ }
724
+ }
725
+ return cutPoints;
726
+ }
727
+
728
+ /**
729
+ * Find the user message (or bashExecution) that starts the turn containing the given entry index.
730
+ * Returns -1 if no turn start found before the index.
731
+ * BashExecutionMessage is treated like a user message for turn boundaries.
732
+ */
733
+ export function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {
734
+ for (let i = entryIndex; i >= startIndex; i--) {
735
+ const entry = entries[i];
736
+ // branch_summary and custom_message are user-role messages, can start a turn
737
+ if (entry.type === "branch_summary" || entry.type === "custom_message") {
738
+ return i;
739
+ }
740
+ if (entry.type === "message") {
741
+ const role = entry.message.role as string;
742
+ if (role === "user" || role === "bashExecution") {
743
+ return i;
744
+ }
745
+ }
746
+ }
747
+ return -1;
748
+ }
749
+
750
+ export interface CutPointResult {
751
+ /** Index of first entry to keep */
752
+ firstKeptEntryIndex: number;
753
+ /** Index of user message that starts the turn being split, or -1 if not splitting */
754
+ turnStartIndex: number;
755
+ /** Whether this cut splits a turn (cut point is not a user message) */
756
+ isSplitTurn: boolean;
757
+ }
758
+
759
+ /**
760
+ * Find the cut point in session entries that keeps approximately `keepRecentTokens`.
761
+ *
762
+ * Algorithm: Walk backwards from newest, accumulating estimated message sizes.
763
+ * Stop when we've accumulated >= keepRecentTokens. Cut at that point.
764
+ *
765
+ * Can cut at user OR assistant messages (never tool results). When cutting at an
766
+ * assistant message with tool calls, its tool results come after and will be kept.
767
+ *
768
+ * Returns CutPointResult with:
769
+ * - firstKeptEntryIndex: the entry index to start keeping from
770
+ * - turnStartIndex: if cutting mid-turn, the user message that started that turn
771
+ * - isSplitTurn: whether we're cutting in the middle of a turn
772
+ *
773
+ * Only considers entries between `startIndex` and `endIndex` (exclusive).
774
+ */
775
+ export function findCutPoint(
776
+ entries: SessionEntry[],
777
+ startIndex: number,
778
+ endIndex: number,
779
+ keepRecentTokens: number,
780
+ ): CutPointResult {
781
+ const cutPoints = findValidCutPoints(entries, startIndex, endIndex);
782
+
783
+ if (cutPoints.length === 0) {
784
+ return { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };
785
+ }
786
+
787
+ // Walk backwards from newest, accumulating estimated message sizes
788
+ let accumulatedTokens = 0;
789
+ let cutIndex = cutPoints[0]; // Default: keep from first message (not header)
790
+
791
+ for (let i = endIndex - 1; i >= startIndex; i--) {
792
+ const entry = entries[i];
793
+ // Estimate this message's size
794
+ const messageTokens = estimateEntryTokens(entry);
795
+ accumulatedTokens += messageTokens;
796
+
797
+ // Check if we've exceeded the budget
798
+ if (accumulatedTokens >= keepRecentTokens) {
799
+ // Find the closest valid cut point at or after this entry
800
+ let foundCutPoint = false;
801
+ for (let c = 0; c < cutPoints.length; c++) {
802
+ if (cutPoints[c] >= i) {
803
+ cutIndex = cutPoints[c];
804
+ foundCutPoint = true;
805
+ break;
806
+ }
807
+ }
808
+ if (!foundCutPoint) {
809
+ cutIndex = cutPoints[cutPoints.length - 1];
810
+ }
811
+ break;
812
+ }
813
+ }
814
+
815
+ // Scan backwards from cutIndex to include any non-message entries (bash, settings, etc.)
816
+ while (cutIndex > startIndex) {
817
+ const prevEntry = entries[cutIndex - 1];
818
+ // Stop at session header or compaction boundaries
819
+ if (prevEntry.type === "compaction") {
820
+ break;
821
+ }
822
+ if (prevEntry.type === "message") {
823
+ // Stop if we hit any message
824
+ break;
825
+ }
826
+ // Include this non-message entry (bash, settings change, etc.)
827
+ cutIndex--;
828
+ }
829
+
830
+ // Determine if this is a split turn
831
+ const cutEntry = entries[cutIndex];
832
+ const isUserMessage = cutEntry.type === "message" && cutEntry.message.role === "user";
833
+ const turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);
834
+
835
+ return {
836
+ firstKeptEntryIndex: cutIndex,
837
+ turnStartIndex,
838
+ isSplitTurn: !isUserMessage && turnStartIndex !== -1,
839
+ };
840
+ }
841
+
842
+ // ============================================================================
843
+ // Summarization
844
+ // ============================================================================
845
+
846
+ const SUMMARIZATION_PROMPT = prompt.render(compactionSummaryPrompt);
847
+
848
+ const UPDATE_SUMMARIZATION_PROMPT = prompt.render(compactionUpdateSummaryPrompt);
849
+
850
+ const HANDOFF_DOCUMENT_PROMPT = prompt.render(handoffDocumentPrompt);
851
+
852
+ export const AUTO_HANDOFF_THRESHOLD_FOCUS = prompt.render(autoHandoffThresholdFocusPrompt);
853
+
854
+ function formatAdditionalContext(context: string[] | undefined): string {
855
+ if (!context || context.length === 0) return "";
856
+ const lines = context.map(line => `- ${line}`).join("\n");
857
+ return `<additional-context>\n${lines}\n</additional-context>\n\n`;
858
+ }
859
+
860
+ /**
861
+ * Generate a summary of the conversation using the LLM.
862
+ * If previousSummary is provided, uses the update prompt to merge.
863
+ */
864
+ export interface SummaryOptions {
865
+ promptOverride?: string;
866
+ extraContext?: string[];
867
+ remoteEndpoint?: string;
868
+ remoteInstructions?: string;
869
+ initiatorOverride?: MessageAttribution;
870
+ metadata?: Record<string, unknown>;
871
+ convertToLlm?: ConvertToLlm;
872
+ /**
873
+ * Optional telemetry handle. When provided, every LLM call emitted during
874
+ * compaction is wrapped in an OTEL chat span tagged with
875
+ * `pi.gen_ai.oneshot.kind` (`compaction_summary` or `compaction_turn_prefix`).
876
+ */
877
+ telemetry?: AgentTelemetry;
878
+ authCredentialType?: "api_key" | "oauth";
879
+ /**
880
+ * Provider session affinity id forwarded to the maintenance LLM call so it
881
+ * reuses the live turn's provider/WebSocket session (matches the
882
+ * `providerSessionId ?? sessionId` the agent loop sends for normal turns).
883
+ */
884
+ sessionId?: string;
885
+ /** Shared provider state map so maintenance calls reuse session-scoped transport/session caches. */
886
+ providerSessionState?: Map<string, ProviderSessionState>;
887
+ /** Hint that websocket transport should be preferred when supported by the provider implementation. */
888
+ preferWebsockets?: boolean;
889
+ /** Session-owned health sink for remote-compaction fallback transition logging. */
890
+ remoteCompactionFallbackHealth?: RemoteCompactionFallbackHealthHooks;
891
+ }
892
+
893
+ /**
894
+ * Cap the serialized conversation fed to a summarization request so the request
895
+ * itself fits inside the model's context window.
896
+ *
897
+ * Without this, summarizing a near-full context serializes (nearly) the entire
898
+ * history back into a single summary request; on strict backends (e.g.
899
+ * OpenAI-code/Codex `context_length_exceeded`) that request itself overflows and
900
+ * throws, so context-overflow recovery cannot produce a summary and the agent
901
+ * fails to compact-and-continue — a non-interactive `vib -p` run then terminates
902
+ * on the very overflow the recovery was meant to absorb.
903
+ *
904
+ * The budget reserves the summary's own output tokens plus prompt/system/template
905
+ * overhead, and applies a conservative safety factor for estimator error on
906
+ * dense text (the reason the original overflow was missed).
907
+ * Truncation keeps the head (origin/goals) and the tail (most recent state) and
908
+ * elides the middle; it is a last resort that only triggers when the input would
909
+ * otherwise not fit.
910
+ */
911
+ export function boundConversationTextForSummary(
912
+ conversationText: string,
913
+ model: Model,
914
+ outputMaxTokens: number,
915
+ ): string {
916
+ const contextWindow = model.contextWindow;
917
+ if (!Number.isFinite(contextWindow) || contextWindow <= 0) return conversationText;
918
+
919
+ const OVERHEAD_TOKENS = 4096;
920
+ const SAFETY_FACTOR = 0.6;
921
+ const inputBudgetTokens = Math.floor(
922
+ (contextWindow - Math.max(0, outputMaxTokens) - OVERHEAD_TOKENS) * SAFETY_FACTOR,
923
+ );
924
+ const totalEstimatedTokens = estimateTextTokensHeuristic(conversationText);
925
+ const assemble = (head: string, tail: string): string => {
926
+ const elided = conversationText.length - head.length - tail.length;
927
+ return `${head}\n\n[... ${elided} characters of older conversation elided so this summarization request fits within the model context window ...]\n\n${tail}`;
928
+ };
929
+ const bareMarker = assemble("", "");
930
+ const fitsBudget = (candidate: string) => estimateTextTokensHeuristic(candidate) <= inputBudgetTokens;
931
+ if (inputBudgetTokens <= 0) {
932
+ // A window this small cannot fit any excerpt (not even the marker).
933
+ // Fail closed with an empty excerpt rather than submitting text into a
934
+ // request that is guaranteed to overflow.
935
+ return "";
936
+ }
937
+ if (totalEstimatedTokens <= inputBudgetTokens) return conversationText;
938
+
939
+ // Derive the character budget from the text's own measured token density
940
+ // instead of assuming 4 chars/token: a CJK-heavy conversation runs near
941
+ // 1 token/char, and a fixed 4-chars/token cut would overshoot the budget
942
+ // by up to ~4x — re-overflowing the very request this bound protects.
943
+ // Verify the complete assembled candidate (elision marker included)
944
+ // against the estimator and shrink until it fits.
945
+ const charsPerToken = conversationText.length / totalEstimatedTokens;
946
+ let budgetChars = Math.floor(inputBudgetTokens * charsPerToken);
947
+ for (let attempt = 0; attempt < 12 && budgetChars > 0; attempt++) {
948
+ const headChars = Math.floor(budgetChars * 0.35);
949
+ const tailChars = Math.max(0, budgetChars - headChars);
950
+ const head = conversationText.slice(0, headChars);
951
+ const tail = tailChars > 0 ? conversationText.slice(conversationText.length - tailChars) : "";
952
+ const assembled = assemble(head, tail);
953
+ if (fitsBudget(assembled)) return assembled;
954
+ budgetChars = Math.floor(budgetChars * 0.8);
955
+ }
956
+ // All attempts overshot (adversarially non-uniform density, or a budget
957
+ // smaller than the marker itself). Fail closed: return the bare marker
958
+ // only when it fits the budget, else an empty excerpt — never an
959
+ // over-budget result.
960
+ return fitsBudget(bareMarker) ? bareMarker : "";
961
+ }
962
+
963
+ export async function generateSummary(
964
+ currentMessages: AgentMessage[],
965
+ model: Model,
966
+ reserveTokens: number,
967
+ apiKey: string,
968
+ signal?: AbortSignal,
969
+ customInstructions?: string,
970
+ previousSummary?: string,
971
+ options?: SummaryOptions,
972
+ ): Promise<string> {
973
+ const maxTokens = Math.floor(0.8 * reserveTokens);
974
+
975
+ // Use update prompt if we have a previous summary, otherwise initial prompt
976
+ let basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;
977
+ if (options?.promptOverride) {
978
+ basePrompt = options.promptOverride;
979
+ }
980
+ if (customInstructions) {
981
+ basePrompt = `${basePrompt}\n\nAdditional focus: ${customInstructions}`;
982
+ }
983
+
984
+ // Serialize conversation to text so model doesn't try to continue it
985
+ // Convert to LLM messages first (handles custom app messages when caller provides a transformer).
986
+ const llmMessages = (options?.convertToLlm ?? convertToLlm)(currentMessages);
987
+ const conversationText = boundConversationTextForSummary(serializeConversation(llmMessages), model, maxTokens);
988
+
989
+ // Build the prompt with conversation wrapped in tags
990
+ let promptText = `<conversation>\n${conversationText}\n</conversation>\n\n`;
991
+ if (previousSummary) {
992
+ promptText += `<previous-summary>\n${previousSummary}\n</previous-summary>\n\n`;
993
+ }
994
+ promptText += formatAdditionalContext(options?.extraContext);
995
+ promptText += basePrompt;
996
+
997
+ const summarizationMessages = [
998
+ {
999
+ role: "user" as const,
1000
+ content: [{ type: "text" as const, text: promptText }],
1001
+ timestamp: Date.now(),
1002
+ },
1003
+ ];
1004
+
1005
+ if (options?.remoteEndpoint) {
1006
+ const remote = await requestRemoteCompaction(
1007
+ options.remoteEndpoint,
1008
+ {
1009
+ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT,
1010
+ prompt: promptText,
1011
+ },
1012
+ signal,
1013
+ );
1014
+ return remote.summary;
1015
+ }
1016
+
1017
+ const response = await instrumentedCompleteSimple(
1018
+ model,
1019
+ { systemPrompt: [SUMMARIZATION_SYSTEM_PROMPT], messages: summarizationMessages },
1020
+ {
1021
+ maxTokens,
1022
+ signal,
1023
+ apiKey,
1024
+ reasoning: Effort.High,
1025
+ initiatorOverride: options?.initiatorOverride,
1026
+ metadata: options?.metadata,
1027
+ sessionId: options?.sessionId,
1028
+ providerSessionState: options?.providerSessionState,
1029
+ preferWebsockets: options?.preferWebsockets,
1030
+ },
1031
+ { telemetry: options?.telemetry, oneshotKind: "compaction_summary" },
1032
+ );
1033
+
1034
+ if (response.stopReason === "error") {
1035
+ throw new Error(`Summarization failed: ${response.errorMessage || "Unknown error"}`);
1036
+ }
1037
+
1038
+ const textContent = response.content
1039
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
1040
+ .map(c => c.text)
1041
+ .join("\n");
1042
+
1043
+ return textContent;
1044
+ }
1045
+
1046
+ // ============================================================================
1047
+ // Handoff generation
1048
+ // ============================================================================
1049
+
1050
+ export interface HandoffOptions {
1051
+ /** Live agent system prompt — passed verbatim so providers hit the cached prefix. */
1052
+ systemPrompt: string[];
1053
+ /** Live agent tool list — same purpose. Forced to `toolChoice: "none"`. */
1054
+ tools?: AgentTool<any>[];
1055
+ customInstructions?: string;
1056
+ /**
1057
+ * Optional user-configured extension appended to the base handoff prompt.
1058
+ * It SUPPLEMENTS the immutable base (safety/continuity structure); it never
1059
+ * replaces `HANDOFF_DOCUMENT_PROMPT`.
1060
+ */
1061
+ promptExtension?: string;
1062
+ convertToLlm?: ConvertToLlm;
1063
+ initiatorOverride?: MessageAttribution;
1064
+ metadata?: Record<string, unknown>;
1065
+ /**
1066
+ * Optional telemetry handle. When provided, the handoff LLM call is
1067
+ * wrapped in an OTEL chat span tagged with `pi.gen_ai.oneshot.kind = "handoff"`.
1068
+ */
1069
+ telemetry?: AgentTelemetry;
1070
+ authCredentialType?: "api_key" | "oauth";
1071
+ /**
1072
+ * Provider session affinity id forwarded to the handoff LLM call so it
1073
+ * reuses the live turn's provider/WebSocket session.
1074
+ */
1075
+ sessionId?: string;
1076
+ /** Shared provider state map so the handoff call reuses session-scoped transport/session caches. */
1077
+ providerSessionState?: Map<string, ProviderSessionState>;
1078
+ /** Hint that websocket transport should be preferred when supported by the provider implementation. */
1079
+ preferWebsockets?: boolean;
1080
+ }
1081
+
1082
+ export function renderHandoffPrompt(customInstructions?: string, promptExtension?: string): string {
1083
+ if (!customInstructions && !promptExtension) return HANDOFF_DOCUMENT_PROMPT;
1084
+ return prompt.render(handoffDocumentPrompt, {
1085
+ additionalFocus: customInstructions,
1086
+ promptExtension,
1087
+ });
1088
+ }
1089
+
1090
+ export async function generateHandoff(
1091
+ messages: AgentMessage[],
1092
+ model: Model,
1093
+ apiKey: string,
1094
+ options: HandoffOptions,
1095
+ signal?: AbortSignal,
1096
+ ): Promise<string> {
1097
+ const llmMessages = (options.convertToLlm ?? convertToLlm)(messages);
1098
+ const requestMessages: Message[] = [
1099
+ ...llmMessages,
1100
+ {
1101
+ role: "user",
1102
+ content: [{ type: "text", text: renderHandoffPrompt(options.customInstructions, options.promptExtension) }],
1103
+ attribution: "agent",
1104
+ timestamp: Date.now(),
1105
+ },
1106
+ ];
1107
+
1108
+ const response = await instrumentedCompleteSimple(
1109
+ model,
1110
+ {
1111
+ systemPrompt: options.systemPrompt,
1112
+ messages: requestMessages,
1113
+ tools: options.tools,
1114
+ },
1115
+ {
1116
+ apiKey,
1117
+ signal,
1118
+ reasoning: Effort.High,
1119
+ toolChoice: "none",
1120
+ initiatorOverride: options.initiatorOverride,
1121
+ metadata: options.metadata,
1122
+ sessionId: options.sessionId,
1123
+ providerSessionState: options.providerSessionState,
1124
+ preferWebsockets: options.preferWebsockets,
1125
+ },
1126
+ { telemetry: options.telemetry, oneshotKind: "handoff" },
1127
+ );
1128
+
1129
+ if (response.stopReason === "error") {
1130
+ throw new Error(`Handoff generation failed: ${response.errorMessage || "Unknown error"}`);
1131
+ }
1132
+
1133
+ return response.content
1134
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
1135
+ .map(c => c.text)
1136
+ .join("\n");
1137
+ }
1138
+
1139
+ /** Derive a display summary locally to avoid a second compaction LLM request. */
1140
+ function deriveShortSummary(summary: string): string {
1141
+ const firstParagraph = summary.trim().split(/\n\s*\n/, 1)[0] ?? "";
1142
+ const maxLength = 2_000;
1143
+ return firstParagraph.length <= maxLength ? firstParagraph : `${firstParagraph.slice(0, maxLength - 1)}…`;
1144
+ }
1145
+
1146
+ // ============================================================================
1147
+ // Compaction Preparation (for hooks)
1148
+ // ============================================================================
1149
+
1150
+ export interface CompactionPreparation {
1151
+ /** UUID of first entry to keep */
1152
+ firstKeptEntryId: string;
1153
+ /** Messages that will be summarized and discarded */
1154
+ messagesToSummarize: AgentMessage[];
1155
+ /** Messages that will be turned into turn prefix summary (if splitting) */
1156
+ turnPrefixMessages: AgentMessage[];
1157
+ /** Messages kept in full after compaction (recent history) */
1158
+ recentMessages: AgentMessage[];
1159
+ /** Whether this is a split turn (cut point in middle of turn) */
1160
+ isSplitTurn: boolean;
1161
+ tokensBefore: number;
1162
+ /** Summary from previous compaction, for iterative update */
1163
+ previousSummary?: string;
1164
+ /** Preserved opaque compaction payload from the previous compaction, if any. */
1165
+ previousPreserveData?: Record<string, unknown>;
1166
+ /** File operations extracted from messagesToSummarize */
1167
+ fileOps: FileOperations;
1168
+ /** Compaction settions from settings.jsonl */
1169
+ settings: CompactionSettings;
1170
+ /**
1171
+ * Diagnostics for the keep-window token correction (Finding 7). `ratio` is the
1172
+ * clamped heuristic→actual correction that was applied (1 when none supplied);
1173
+ * `keepRecentTokensCorrected` is the heuristic budget findCutPoint actually used.
1174
+ */
1175
+ tokenCorrection: { ratio: number; keepRecentTokensCorrected: number };
1176
+ }
1177
+
1178
+ /** Bounds for the keep-window token correction (Finding 7): never trust a ratio
1179
+ * beyond 2x in either direction so a bad estimate cannot balloon or collapse the
1180
+ * kept window. */
1181
+ export const TOKEN_CORRECTION_MIN_RATIO = 0.5;
1182
+ export const TOKEN_CORRECTION_MAX_RATIO = 2;
1183
+
1184
+ export interface PrepareCompactionOptions {
1185
+ /**
1186
+ * Observed heuristic→actual token correction for the post-boundary keep window
1187
+ * (actualTokens / chars-4-heuristicTokens), supplied by the caller from per-turn
1188
+ * Usage deltas or a stable-prefix-subtracted comparison. Clamped to
1189
+ * [0.5, 2] and applied bidirectionally. When omitted, no correction is applied
1190
+ * (the confounded raw promptTokens/estimatedTokens quotient is never used).
1191
+ */
1192
+ tokenCorrectionRatio?: number;
1193
+ /**
1194
+ * Model context-window size. Windows below 66k retain the legacy fixed
1195
+ * keepRecentTokens behavior; larger windows scale the keep window to 30%.
1196
+ */
1197
+ contextWindow?: number;
1198
+ }
1199
+
1200
+ export function prepareCompaction(
1201
+ pathEntries: SessionEntry[],
1202
+ settings: CompactionSettings,
1203
+ options: PrepareCompactionOptions = {},
1204
+ ): CompactionPreparation | undefined {
1205
+ if (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === "compaction") {
1206
+ return undefined;
1207
+ }
1208
+
1209
+ let prevCompactionIndex = -1;
1210
+ for (let i = pathEntries.length - 1; i >= 0; i--) {
1211
+ if (pathEntries[i].type === "compaction") {
1212
+ prevCompactionIndex = i;
1213
+ break;
1214
+ }
1215
+ }
1216
+ const boundaryStart = prevCompactionIndex + 1;
1217
+ const boundaryEnd = pathEntries.length;
1218
+
1219
+ const lastUsage = getLastAssistantUsage(pathEntries);
1220
+ const tokensBefore = lastUsage ? calculateContextTokens(lastUsage) : 0;
1221
+
1222
+ // Correct the keep-window budget for the chars/4 heuristic error using the
1223
+ // caller-supplied observed ratio (actual/heuristic). The legacy raw
1224
+ // promptTokens/estimatedTokens quotient is intentionally NOT used: promptTokens
1225
+ // counts system+tools+full history while estimatedTokens counted only the
1226
+ // post-boundary slice, so it was confounded and only ever shrank the window.
1227
+ // Here the correction is bidirectional and clamped to [0.5, 2].
1228
+ const configuredKeepRecentTokens = settings.keepRecentTokens;
1229
+ const contextWindow = options.contextWindow;
1230
+ const thresholdSafeKeepRecentTokens =
1231
+ contextWindow !== undefined && Number.isFinite(contextWindow) && contextWindow > 1
1232
+ ? Math.max(
1233
+ 1,
1234
+ resolveThresholdTokens(contextWindow, settings) - effectiveReserveTokens(contextWindow, settings, 0),
1235
+ )
1236
+ : configuredKeepRecentTokens;
1237
+ const keepRecentTokens = Math.min(configuredKeepRecentTokens, thresholdSafeKeepRecentTokens);
1238
+ // Preserve the legacy fixed window for smaller models. At 66k and above,
1239
+ // retain up to 30% of the model context, but never enough to leave the
1240
+ // post-compaction prompt immediately above its configured threshold.
1241
+ const scaledKeepRecentTokens =
1242
+ contextWindow !== undefined && Number.isFinite(contextWindow) && contextWindow >= 66_000
1243
+ ? Math.min(thresholdSafeKeepRecentTokens, Math.max(keepRecentTokens, Math.floor(contextWindow * 0.3)))
1244
+ : keepRecentTokens;
1245
+ const rawRatio = options.tokenCorrectionRatio;
1246
+ const appliedRatio =
1247
+ rawRatio !== undefined && Number.isFinite(rawRatio) && rawRatio > 0
1248
+ ? Math.min(TOKEN_CORRECTION_MAX_RATIO, Math.max(TOKEN_CORRECTION_MIN_RATIO, rawRatio))
1249
+ : 1;
1250
+ // Preserve an explicit keep floor that already covers the whole history: manual
1251
+ // and emergency callers rely on prepareCompaction returning undefined rather
1252
+ // than manufacturing a summary with no useful reduction. Otherwise, a scaled
1253
+ // window that exceeds a short history falls back to the threshold-safe floor.
1254
+ const historyTokens = pathEntries
1255
+ .slice(boundaryStart, boundaryEnd)
1256
+ .reduce((tokens, entry) => tokens + estimateEntryTokens(entry), 0);
1257
+ const effectiveKeepRecentTokens =
1258
+ configuredKeepRecentTokens > historyTokens
1259
+ ? configuredKeepRecentTokens
1260
+ : scaledKeepRecentTokens > keepRecentTokens && scaledKeepRecentTokens > historyTokens
1261
+ ? keepRecentTokens
1262
+ : scaledKeepRecentTokens;
1263
+ const keepRecentTokensCorrected = Math.max(1, Math.round(effectiveKeepRecentTokens / appliedRatio));
1264
+
1265
+ const cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, keepRecentTokensCorrected);
1266
+
1267
+ // Get ID of first kept entry
1268
+ const firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];
1269
+ if (!firstKeptEntry?.id) {
1270
+ return undefined; // Session needs migration
1271
+ }
1272
+ const firstKeptEntryId = firstKeptEntry.id;
1273
+
1274
+ const historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;
1275
+
1276
+ // Messages to summarize (will be discarded after summary)
1277
+ const messagesToSummarize: AgentMessage[] = [];
1278
+ for (let i = boundaryStart; i < historyEnd; i++) {
1279
+ const msg = getMessageFromEntry(pathEntries[i]);
1280
+ if (msg) messagesToSummarize.push(msg);
1281
+ }
1282
+
1283
+ // Messages for turn prefix summary (if splitting a turn)
1284
+ const turnPrefixMessages: AgentMessage[] = [];
1285
+ if (cutPoint.isSplitTurn) {
1286
+ for (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {
1287
+ const msg = getMessageFromEntry(pathEntries[i]);
1288
+ if (msg) turnPrefixMessages.push(msg);
1289
+ }
1290
+ }
1291
+
1292
+ // Messages kept after compaction (recent history)
1293
+ const recentMessages: AgentMessage[] = [];
1294
+ for (let i = cutPoint.firstKeptEntryIndex; i < boundaryEnd; i++) {
1295
+ const msg = getMessageFromEntry(pathEntries[i]);
1296
+ if (msg) recentMessages.push(msg);
1297
+ }
1298
+ // Nothing to summarize means compaction would be a no-op.
1299
+ if (messagesToSummarize.length === 0 && turnPrefixMessages.length === 0) {
1300
+ return undefined;
1301
+ }
1302
+
1303
+ // Get previous summary and preserved data for iterative updates
1304
+ let previousSummary: string | undefined;
1305
+ let previousPreserveData: Record<string, unknown> | undefined;
1306
+ if (prevCompactionIndex >= 0) {
1307
+ const prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;
1308
+ previousSummary = prevCompaction.summary;
1309
+ previousPreserveData = prevCompaction.preserveData;
1310
+ }
1311
+
1312
+ // Extract file operations from messages and previous compaction
1313
+ const fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);
1314
+
1315
+ // Also extract file ops from turn prefix if splitting
1316
+ if (cutPoint.isSplitTurn) {
1317
+ for (const msg of turnPrefixMessages) {
1318
+ extractFileOpsFromMessage(msg, fileOps);
1319
+ }
1320
+ }
1321
+
1322
+ return {
1323
+ firstKeptEntryId,
1324
+ messagesToSummarize,
1325
+ turnPrefixMessages,
1326
+ recentMessages,
1327
+ isSplitTurn: cutPoint.isSplitTurn,
1328
+ tokensBefore,
1329
+ previousSummary,
1330
+ previousPreserveData,
1331
+ fileOps,
1332
+ settings,
1333
+ tokenCorrection: { ratio: appliedRatio, keepRecentTokensCorrected },
1334
+ };
1335
+ }
1336
+
1337
+ // ============================================================================
1338
+ // Main compaction function
1339
+ // ============================================================================
1340
+
1341
+ const TURN_PREFIX_SUMMARIZATION_PROMPT = prompt.render(compactionTurnPrefixPrompt);
1342
+
1343
+ /**
1344
+ * Generate summaries for compaction using prepared data.
1345
+ * Returns CompactionResult - SessionManager adds id/parentId when saving.
1346
+ *
1347
+ * @param preparation - Pre-calculated preparation from prepareCompaction()
1348
+ * @param customInstructions - Optional custom focus for the summary
1349
+ */
1350
+ export async function compact(
1351
+ preparation: CompactionPreparation,
1352
+ model: Model,
1353
+ apiKey: string,
1354
+ customInstructions?: string,
1355
+ signal?: AbortSignal,
1356
+ options?: SummaryOptions,
1357
+ ): Promise<CompactionResult> {
1358
+ const {
1359
+ firstKeptEntryId,
1360
+ messagesToSummarize,
1361
+ turnPrefixMessages,
1362
+ recentMessages,
1363
+ isSplitTurn,
1364
+ tokensBefore,
1365
+ previousSummary,
1366
+ previousPreserveData,
1367
+ fileOps,
1368
+ settings,
1369
+ } = preparation;
1370
+
1371
+ const summaryOptions: SummaryOptions = {
1372
+ promptOverride: options?.promptOverride,
1373
+ extraContext: options?.extraContext,
1374
+ remoteEndpoint: settings.remoteEnabled === false ? undefined : settings.remoteEndpoint,
1375
+ remoteInstructions: options?.remoteInstructions,
1376
+ initiatorOverride: options?.initiatorOverride,
1377
+ metadata: options?.metadata,
1378
+ convertToLlm: options?.convertToLlm,
1379
+ telemetry: options?.telemetry,
1380
+ sessionId: options?.sessionId,
1381
+ providerSessionState: options?.providerSessionState,
1382
+ preferWebsockets: options?.preferWebsockets,
1383
+ remoteCompactionFallbackHealth: options?.remoteCompactionFallbackHealth,
1384
+ };
1385
+
1386
+ let preserveData = withOpenAiRemoteCompactionPreserveData(previousPreserveData, undefined);
1387
+ if (settings.remoteEnabled !== false && shouldUseOpenAiRemoteCompaction(model)) {
1388
+ const previousRemoteCompaction = getPreservedOpenAiRemoteCompactionData(previousPreserveData);
1389
+ const remoteMessages = [...messagesToSummarize, ...turnPrefixMessages, ...recentMessages];
1390
+ const previousReplacementHistory =
1391
+ previousRemoteCompaction?.provider === model.provider
1392
+ ? previousRemoteCompaction.replacementHistory
1393
+ : undefined;
1394
+ const remoteHistory = buildOpenAiNativeHistory(
1395
+ (summaryOptions.convertToLlm ?? convertToLlm)(remoteMessages),
1396
+ model,
1397
+ previousReplacementHistory,
1398
+ );
1399
+ if (remoteHistory.length > 0) {
1400
+ try {
1401
+ const remote = await requestOpenAiRemoteCompaction(
1402
+ model,
1403
+ apiKey,
1404
+ remoteHistory,
1405
+ summaryOptions.remoteInstructions ?? SUMMARIZATION_SYSTEM_PROMPT,
1406
+ signal,
1407
+ { authCredentialType: options?.authCredentialType },
1408
+ );
1409
+ preserveData = withOpenAiRemoteCompactionPreserveData(previousPreserveData, remote);
1410
+ summaryOptions.remoteCompactionFallbackHealth?.recordRemoteCompactionFallback({
1411
+ kind: "success",
1412
+ model: model.id,
1413
+ provider: model.provider,
1414
+ });
1415
+ } catch (err) {
1416
+ if (signal?.aborted || isAbortError(err)) throw err;
1417
+ const error = err instanceof Error ? err.message : String(err);
1418
+ if (summaryOptions.remoteCompactionFallbackHealth) {
1419
+ summaryOptions.remoteCompactionFallbackHealth.recordRemoteCompactionFallback({
1420
+ kind: "fallback",
1421
+ error,
1422
+ model: model.id,
1423
+ provider: model.provider,
1424
+ });
1425
+ } else {
1426
+ logger.warn("OpenAI remote compaction failed, falling back to local summarization", {
1427
+ error,
1428
+ model: model.id,
1429
+ provider: model.provider,
1430
+ });
1431
+ }
1432
+ }
1433
+ }
1434
+ }
1435
+
1436
+ // Generate summaries (can be parallel if both needed) and merge into one
1437
+ let summary: string;
1438
+
1439
+ // A single active Codex WebSocket session cannot service two concurrent
1440
+ // requests ("websocket request already in progress"). When the maintenance
1441
+ // calls use the Codex Responses provider, share one provider session, and
1442
+ // websocket transport is not explicitly disabled, run the split-turn history
1443
+ // and turn-prefix summaries sequentially. This covers websocket activation
1444
+ // from config/env/model defaults too: the provider can select websockets even
1445
+ // when `preferWebsockets` is undefined, while non-Codex providers keep the
1446
+ // previous parallel behavior.
1447
+ const summariesMayShareWebSocketSession = Boolean(
1448
+ model.api === "openai-codex-responses" &&
1449
+ summaryOptions.providerSessionState &&
1450
+ summaryOptions.preferWebsockets !== false,
1451
+ );
1452
+
1453
+ if (isSplitTurn && turnPrefixMessages.length > 0) {
1454
+ const runHistorySummary = () =>
1455
+ messagesToSummarize.length > 0
1456
+ ? generateSummary(
1457
+ messagesToSummarize,
1458
+ model,
1459
+ settings.reserveTokens,
1460
+ apiKey,
1461
+ signal,
1462
+ customInstructions,
1463
+ previousSummary,
1464
+ summaryOptions,
1465
+ )
1466
+ : Promise.resolve("No prior history.");
1467
+ const runTurnPrefixSummary = () =>
1468
+ generateTurnPrefixSummary(turnPrefixMessages, model, settings.reserveTokens, apiKey, signal, summaryOptions);
1469
+
1470
+ let historyResult: string;
1471
+ let turnPrefixResult: string;
1472
+ if (summariesMayShareWebSocketSession) {
1473
+ // Sequential: avoids concurrent requests on the same provider session.
1474
+ historyResult = await runHistorySummary();
1475
+ turnPrefixResult = await runTurnPrefixSummary();
1476
+ } else {
1477
+ [historyResult, turnPrefixResult] = await Promise.all([runHistorySummary(), runTurnPrefixSummary()]);
1478
+ }
1479
+ // Merge into single summary
1480
+ summary = `${historyResult}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult}`;
1481
+ } else if (messagesToSummarize.length > 0) {
1482
+ // Generate history summary from messages to summarize
1483
+ summary = await generateSummary(
1484
+ messagesToSummarize,
1485
+ model,
1486
+ settings.reserveTokens,
1487
+ apiKey,
1488
+ signal,
1489
+ customInstructions,
1490
+ previousSummary,
1491
+ summaryOptions,
1492
+ );
1493
+ } else if (previousSummary) {
1494
+ // No new messages to summarize, preserve previous summary
1495
+ summary = previousSummary;
1496
+ } else {
1497
+ // No messages and no previous summary
1498
+ summary = "No prior history.";
1499
+ }
1500
+
1501
+ // Compute file lists and append to summary
1502
+ const { readFiles, modifiedFiles } = computeFileLists(fileOps);
1503
+ summary = upsertFileOperations(summary, readFiles, modifiedFiles);
1504
+ const shortSummary = deriveShortSummary(summary);
1505
+
1506
+ if (!firstKeptEntryId) {
1507
+ throw new Error("First kept entry has no ID - session may need migration");
1508
+ }
1509
+
1510
+ return {
1511
+ summary,
1512
+ shortSummary,
1513
+ firstKeptEntryId,
1514
+ tokensBefore,
1515
+ details: { readFiles, modifiedFiles } as CompactionDetails,
1516
+ preserveData,
1517
+ };
1518
+ }
1519
+
1520
+ /**
1521
+ * Generate a summary for a turn prefix (when splitting a turn).
1522
+ */
1523
+ async function generateTurnPrefixSummary(
1524
+ messages: AgentMessage[],
1525
+ model: Model,
1526
+ reserveTokens: number,
1527
+ apiKey: string,
1528
+ signal?: AbortSignal,
1529
+ options?: SummaryOptions,
1530
+ ): Promise<string> {
1531
+ const maxTokens = Math.floor(0.5 * reserveTokens); // Smaller budget for turn prefix
1532
+
1533
+ const llmMessages = (options?.convertToLlm ?? convertToLlm)(messages);
1534
+ const conversationText = boundConversationTextForSummary(serializeConversation(llmMessages), model, maxTokens);
1535
+ const promptText = `<conversation>\n${conversationText}\n</conversation>\n\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;
1536
+ const summarizationMessages = [
1537
+ {
1538
+ role: "user" as const,
1539
+ content: [{ type: "text" as const, text: promptText }],
1540
+ timestamp: Date.now(),
1541
+ },
1542
+ ];
1543
+
1544
+ const response = await instrumentedCompleteSimple(
1545
+ model,
1546
+ { systemPrompt: [SUMMARIZATION_SYSTEM_PROMPT], messages: summarizationMessages },
1547
+ {
1548
+ maxTokens,
1549
+ signal,
1550
+ apiKey,
1551
+ reasoning: Effort.High,
1552
+ initiatorOverride: options?.initiatorOverride,
1553
+ metadata: options?.metadata,
1554
+ sessionId: options?.sessionId,
1555
+ providerSessionState: options?.providerSessionState,
1556
+ preferWebsockets: options?.preferWebsockets,
1557
+ },
1558
+ { telemetry: options?.telemetry, oneshotKind: "compaction_turn_prefix" },
1559
+ );
1560
+
1561
+ if (response.stopReason === "error") {
1562
+ throw new Error(`Turn prefix summarization failed: ${response.errorMessage || "Unknown error"}`);
1563
+ }
1564
+
1565
+ return response.content
1566
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
1567
+ .map(c => c.text)
1568
+ .join("\n");
1569
+ }