@oh-my-pi/pi-coding-agent 1.337.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 (224) hide show
  1. package/CHANGELOG.md +1228 -0
  2. package/README.md +1041 -0
  3. package/docs/compaction.md +403 -0
  4. package/docs/custom-tools.md +541 -0
  5. package/docs/extension-loading.md +1004 -0
  6. package/docs/hooks.md +867 -0
  7. package/docs/rpc.md +1040 -0
  8. package/docs/sdk.md +994 -0
  9. package/docs/session-tree-plan.md +441 -0
  10. package/docs/session.md +240 -0
  11. package/docs/skills.md +290 -0
  12. package/docs/theme.md +637 -0
  13. package/docs/tree.md +197 -0
  14. package/docs/tui.md +341 -0
  15. package/examples/README.md +21 -0
  16. package/examples/custom-tools/README.md +124 -0
  17. package/examples/custom-tools/hello/index.ts +20 -0
  18. package/examples/custom-tools/question/index.ts +84 -0
  19. package/examples/custom-tools/subagent/README.md +172 -0
  20. package/examples/custom-tools/subagent/agents/planner.md +37 -0
  21. package/examples/custom-tools/subagent/agents/reviewer.md +35 -0
  22. package/examples/custom-tools/subagent/agents/scout.md +50 -0
  23. package/examples/custom-tools/subagent/agents/worker.md +24 -0
  24. package/examples/custom-tools/subagent/agents.ts +156 -0
  25. package/examples/custom-tools/subagent/commands/implement-and-review.md +10 -0
  26. package/examples/custom-tools/subagent/commands/implement.md +10 -0
  27. package/examples/custom-tools/subagent/commands/scout-and-plan.md +9 -0
  28. package/examples/custom-tools/subagent/index.ts +1002 -0
  29. package/examples/custom-tools/todo/index.ts +212 -0
  30. package/examples/hooks/README.md +56 -0
  31. package/examples/hooks/auto-commit-on-exit.ts +49 -0
  32. package/examples/hooks/confirm-destructive.ts +59 -0
  33. package/examples/hooks/custom-compaction.ts +116 -0
  34. package/examples/hooks/dirty-repo-guard.ts +52 -0
  35. package/examples/hooks/file-trigger.ts +41 -0
  36. package/examples/hooks/git-checkpoint.ts +53 -0
  37. package/examples/hooks/handoff.ts +150 -0
  38. package/examples/hooks/permission-gate.ts +34 -0
  39. package/examples/hooks/protected-paths.ts +30 -0
  40. package/examples/hooks/qna.ts +119 -0
  41. package/examples/hooks/snake.ts +343 -0
  42. package/examples/hooks/status-line.ts +40 -0
  43. package/examples/sdk/01-minimal.ts +22 -0
  44. package/examples/sdk/02-custom-model.ts +49 -0
  45. package/examples/sdk/03-custom-prompt.ts +44 -0
  46. package/examples/sdk/04-skills.ts +44 -0
  47. package/examples/sdk/05-tools.ts +90 -0
  48. package/examples/sdk/06-hooks.ts +61 -0
  49. package/examples/sdk/07-context-files.ts +36 -0
  50. package/examples/sdk/08-slash-commands.ts +42 -0
  51. package/examples/sdk/09-api-keys-and-oauth.ts +55 -0
  52. package/examples/sdk/10-settings.ts +38 -0
  53. package/examples/sdk/11-sessions.ts +48 -0
  54. package/examples/sdk/12-full-control.ts +95 -0
  55. package/examples/sdk/README.md +154 -0
  56. package/package.json +81 -0
  57. package/src/cli/args.ts +246 -0
  58. package/src/cli/file-processor.ts +72 -0
  59. package/src/cli/list-models.ts +104 -0
  60. package/src/cli/plugin-cli.ts +650 -0
  61. package/src/cli/session-picker.ts +41 -0
  62. package/src/cli.ts +10 -0
  63. package/src/commands/init.md +20 -0
  64. package/src/config.ts +159 -0
  65. package/src/core/agent-session.ts +1900 -0
  66. package/src/core/auth-storage.ts +236 -0
  67. package/src/core/bash-executor.ts +196 -0
  68. package/src/core/compaction/branch-summarization.ts +343 -0
  69. package/src/core/compaction/compaction.ts +742 -0
  70. package/src/core/compaction/index.ts +7 -0
  71. package/src/core/compaction/utils.ts +154 -0
  72. package/src/core/custom-tools/index.ts +21 -0
  73. package/src/core/custom-tools/loader.ts +248 -0
  74. package/src/core/custom-tools/types.ts +169 -0
  75. package/src/core/custom-tools/wrapper.ts +28 -0
  76. package/src/core/exec.ts +129 -0
  77. package/src/core/export-html/index.ts +211 -0
  78. package/src/core/export-html/template.css +781 -0
  79. package/src/core/export-html/template.html +54 -0
  80. package/src/core/export-html/template.js +1185 -0
  81. package/src/core/export-html/vendor/highlight.min.js +1213 -0
  82. package/src/core/export-html/vendor/marked.min.js +6 -0
  83. package/src/core/hooks/index.ts +16 -0
  84. package/src/core/hooks/loader.ts +312 -0
  85. package/src/core/hooks/runner.ts +434 -0
  86. package/src/core/hooks/tool-wrapper.ts +99 -0
  87. package/src/core/hooks/types.ts +773 -0
  88. package/src/core/index.ts +52 -0
  89. package/src/core/mcp/client.ts +158 -0
  90. package/src/core/mcp/config.ts +154 -0
  91. package/src/core/mcp/index.ts +45 -0
  92. package/src/core/mcp/loader.ts +68 -0
  93. package/src/core/mcp/manager.ts +181 -0
  94. package/src/core/mcp/tool-bridge.ts +148 -0
  95. package/src/core/mcp/transports/http.ts +316 -0
  96. package/src/core/mcp/transports/index.ts +6 -0
  97. package/src/core/mcp/transports/stdio.ts +252 -0
  98. package/src/core/mcp/types.ts +220 -0
  99. package/src/core/messages.ts +189 -0
  100. package/src/core/model-registry.ts +317 -0
  101. package/src/core/model-resolver.ts +393 -0
  102. package/src/core/plugins/doctor.ts +59 -0
  103. package/src/core/plugins/index.ts +38 -0
  104. package/src/core/plugins/installer.ts +189 -0
  105. package/src/core/plugins/loader.ts +338 -0
  106. package/src/core/plugins/manager.ts +672 -0
  107. package/src/core/plugins/parser.ts +105 -0
  108. package/src/core/plugins/paths.ts +32 -0
  109. package/src/core/plugins/types.ts +190 -0
  110. package/src/core/sdk.ts +760 -0
  111. package/src/core/session-manager.ts +1128 -0
  112. package/src/core/settings-manager.ts +443 -0
  113. package/src/core/skills.ts +437 -0
  114. package/src/core/slash-commands.ts +248 -0
  115. package/src/core/system-prompt.ts +439 -0
  116. package/src/core/timings.ts +25 -0
  117. package/src/core/tools/ask.ts +211 -0
  118. package/src/core/tools/bash-interceptor.ts +120 -0
  119. package/src/core/tools/bash.ts +250 -0
  120. package/src/core/tools/context.ts +32 -0
  121. package/src/core/tools/edit-diff.ts +475 -0
  122. package/src/core/tools/edit.ts +208 -0
  123. package/src/core/tools/exa/company.ts +59 -0
  124. package/src/core/tools/exa/index.ts +64 -0
  125. package/src/core/tools/exa/linkedin.ts +59 -0
  126. package/src/core/tools/exa/logger.ts +56 -0
  127. package/src/core/tools/exa/mcp-client.ts +368 -0
  128. package/src/core/tools/exa/render.ts +196 -0
  129. package/src/core/tools/exa/researcher.ts +90 -0
  130. package/src/core/tools/exa/search.ts +337 -0
  131. package/src/core/tools/exa/types.ts +168 -0
  132. package/src/core/tools/exa/websets.ts +248 -0
  133. package/src/core/tools/find.ts +261 -0
  134. package/src/core/tools/grep.ts +555 -0
  135. package/src/core/tools/index.ts +202 -0
  136. package/src/core/tools/ls.ts +140 -0
  137. package/src/core/tools/lsp/client.ts +605 -0
  138. package/src/core/tools/lsp/config.ts +147 -0
  139. package/src/core/tools/lsp/edits.ts +101 -0
  140. package/src/core/tools/lsp/index.ts +804 -0
  141. package/src/core/tools/lsp/render.ts +447 -0
  142. package/src/core/tools/lsp/rust-analyzer.ts +145 -0
  143. package/src/core/tools/lsp/types.ts +463 -0
  144. package/src/core/tools/lsp/utils.ts +486 -0
  145. package/src/core/tools/notebook.ts +229 -0
  146. package/src/core/tools/path-utils.ts +61 -0
  147. package/src/core/tools/read.ts +240 -0
  148. package/src/core/tools/renderers.ts +540 -0
  149. package/src/core/tools/task/agents.ts +153 -0
  150. package/src/core/tools/task/artifacts.ts +114 -0
  151. package/src/core/tools/task/bundled-agents/browser.md +71 -0
  152. package/src/core/tools/task/bundled-agents/explore.md +82 -0
  153. package/src/core/tools/task/bundled-agents/plan.md +54 -0
  154. package/src/core/tools/task/bundled-agents/reviewer.md +59 -0
  155. package/src/core/tools/task/bundled-agents/task.md +53 -0
  156. package/src/core/tools/task/bundled-commands/architect-plan.md +10 -0
  157. package/src/core/tools/task/bundled-commands/implement-with-critic.md +11 -0
  158. package/src/core/tools/task/bundled-commands/implement.md +11 -0
  159. package/src/core/tools/task/commands.ts +213 -0
  160. package/src/core/tools/task/discovery.ts +208 -0
  161. package/src/core/tools/task/executor.ts +367 -0
  162. package/src/core/tools/task/index.ts +388 -0
  163. package/src/core/tools/task/model-resolver.ts +115 -0
  164. package/src/core/tools/task/parallel.ts +38 -0
  165. package/src/core/tools/task/render.ts +232 -0
  166. package/src/core/tools/task/types.ts +99 -0
  167. package/src/core/tools/truncate.ts +265 -0
  168. package/src/core/tools/web-fetch.ts +2370 -0
  169. package/src/core/tools/web-search/auth.ts +193 -0
  170. package/src/core/tools/web-search/index.ts +537 -0
  171. package/src/core/tools/web-search/providers/anthropic.ts +198 -0
  172. package/src/core/tools/web-search/providers/exa.ts +302 -0
  173. package/src/core/tools/web-search/providers/perplexity.ts +195 -0
  174. package/src/core/tools/web-search/render.ts +182 -0
  175. package/src/core/tools/web-search/types.ts +180 -0
  176. package/src/core/tools/write.ts +99 -0
  177. package/src/index.ts +176 -0
  178. package/src/main.ts +464 -0
  179. package/src/migrations.ts +135 -0
  180. package/src/modes/index.ts +43 -0
  181. package/src/modes/interactive/components/armin.ts +382 -0
  182. package/src/modes/interactive/components/assistant-message.ts +86 -0
  183. package/src/modes/interactive/components/bash-execution.ts +196 -0
  184. package/src/modes/interactive/components/bordered-loader.ts +41 -0
  185. package/src/modes/interactive/components/branch-summary-message.ts +42 -0
  186. package/src/modes/interactive/components/compaction-summary-message.ts +45 -0
  187. package/src/modes/interactive/components/custom-editor.ts +122 -0
  188. package/src/modes/interactive/components/diff.ts +147 -0
  189. package/src/modes/interactive/components/dynamic-border.ts +25 -0
  190. package/src/modes/interactive/components/footer.ts +381 -0
  191. package/src/modes/interactive/components/hook-editor.ts +117 -0
  192. package/src/modes/interactive/components/hook-input.ts +64 -0
  193. package/src/modes/interactive/components/hook-message.ts +96 -0
  194. package/src/modes/interactive/components/hook-selector.ts +91 -0
  195. package/src/modes/interactive/components/model-selector.ts +247 -0
  196. package/src/modes/interactive/components/oauth-selector.ts +120 -0
  197. package/src/modes/interactive/components/plugin-settings.ts +479 -0
  198. package/src/modes/interactive/components/queue-mode-selector.ts +56 -0
  199. package/src/modes/interactive/components/session-selector.ts +204 -0
  200. package/src/modes/interactive/components/settings-selector.ts +453 -0
  201. package/src/modes/interactive/components/show-images-selector.ts +45 -0
  202. package/src/modes/interactive/components/theme-selector.ts +62 -0
  203. package/src/modes/interactive/components/thinking-selector.ts +64 -0
  204. package/src/modes/interactive/components/tool-execution.ts +675 -0
  205. package/src/modes/interactive/components/tree-selector.ts +866 -0
  206. package/src/modes/interactive/components/user-message-selector.ts +159 -0
  207. package/src/modes/interactive/components/user-message.ts +18 -0
  208. package/src/modes/interactive/components/visual-truncate.ts +50 -0
  209. package/src/modes/interactive/components/welcome.ts +183 -0
  210. package/src/modes/interactive/interactive-mode.ts +2516 -0
  211. package/src/modes/interactive/theme/dark.json +101 -0
  212. package/src/modes/interactive/theme/light.json +98 -0
  213. package/src/modes/interactive/theme/theme-schema.json +308 -0
  214. package/src/modes/interactive/theme/theme.ts +998 -0
  215. package/src/modes/print-mode.ts +128 -0
  216. package/src/modes/rpc/rpc-client.ts +527 -0
  217. package/src/modes/rpc/rpc-mode.ts +483 -0
  218. package/src/modes/rpc/rpc-types.ts +203 -0
  219. package/src/utils/changelog.ts +99 -0
  220. package/src/utils/clipboard.ts +265 -0
  221. package/src/utils/fuzzy.ts +108 -0
  222. package/src/utils/mime.ts +30 -0
  223. package/src/utils/shell.ts +276 -0
  224. package/src/utils/tools-manager.ts +274 -0
@@ -0,0 +1,742 @@
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 type { AgentMessage } from "@oh-my-pi/pi-agent-core";
9
+ import type { AssistantMessage, Model, Usage } from "@oh-my-pi/pi-ai";
10
+ import { complete, completeSimple } from "@oh-my-pi/pi-ai";
11
+ import { convertToLlm, createBranchSummaryMessage, createHookMessage } from "../messages.js";
12
+ import type { CompactionEntry, SessionEntry } from "../session-manager.js";
13
+ import {
14
+ computeFileLists,
15
+ createFileOps,
16
+ extractFileOpsFromMessage,
17
+ type FileOperations,
18
+ formatFileOperations,
19
+ SUMMARIZATION_SYSTEM_PROMPT,
20
+ serializeConversation,
21
+ } from "./utils.js";
22
+
23
+ // ============================================================================
24
+ // File Operation Tracking
25
+ // ============================================================================
26
+
27
+ /** Details stored in CompactionEntry.details for file tracking */
28
+ export interface CompactionDetails {
29
+ readFiles: string[];
30
+ modifiedFiles: string[];
31
+ }
32
+
33
+ /**
34
+ * Extract file operations from messages and previous compaction entries.
35
+ */
36
+ function extractFileOperations(
37
+ messages: AgentMessage[],
38
+ entries: SessionEntry[],
39
+ prevCompactionIndex: number,
40
+ ): FileOperations {
41
+ const fileOps = createFileOps();
42
+
43
+ // Collect from previous compaction's details (if pi-generated)
44
+ if (prevCompactionIndex >= 0) {
45
+ const prevCompaction = entries[prevCompactionIndex] as CompactionEntry;
46
+ if (!prevCompaction.fromHook && prevCompaction.details) {
47
+ const details = prevCompaction.details as CompactionDetails;
48
+ if (Array.isArray(details.readFiles)) {
49
+ for (const f of details.readFiles) fileOps.read.add(f);
50
+ }
51
+ if (Array.isArray(details.modifiedFiles)) {
52
+ for (const f of details.modifiedFiles) fileOps.edited.add(f);
53
+ }
54
+ }
55
+ }
56
+
57
+ // Extract from tool calls in messages
58
+ for (const msg of messages) {
59
+ extractFileOpsFromMessage(msg, fileOps);
60
+ }
61
+
62
+ return fileOps;
63
+ }
64
+
65
+ // ============================================================================
66
+ // Message Extraction
67
+ // ============================================================================
68
+
69
+ /**
70
+ * Extract AgentMessage from an entry if it produces one.
71
+ * Returns undefined for entries that don't contribute to LLM context.
72
+ */
73
+ function getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {
74
+ if (entry.type === "message") {
75
+ return entry.message;
76
+ }
77
+ if (entry.type === "custom_message") {
78
+ return createHookMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);
79
+ }
80
+ if (entry.type === "branch_summary") {
81
+ return createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);
82
+ }
83
+ return undefined;
84
+ }
85
+
86
+ /** Result from compact() - SessionManager adds uuid/parentUuid when saving */
87
+ export interface CompactionResult<T = unknown> {
88
+ summary: string;
89
+ firstKeptEntryId: string;
90
+ tokensBefore: number;
91
+ /** Hook-specific data (e.g., ArtifactIndex, version markers for structured compaction) */
92
+ details?: T;
93
+ }
94
+
95
+ // ============================================================================
96
+ // Types
97
+ // ============================================================================
98
+
99
+ export interface CompactionSettings {
100
+ enabled: boolean;
101
+ reserveTokens: number;
102
+ keepRecentTokens: number;
103
+ }
104
+
105
+ export const DEFAULT_COMPACTION_SETTINGS: CompactionSettings = {
106
+ enabled: true,
107
+ reserveTokens: 16384,
108
+ keepRecentTokens: 20000,
109
+ };
110
+
111
+ // ============================================================================
112
+ // Token calculation
113
+ // ============================================================================
114
+
115
+ /**
116
+ * Calculate total context tokens from usage.
117
+ * Uses the native totalTokens field when available, falls back to computing from components.
118
+ */
119
+ export function calculateContextTokens(usage: Usage): number {
120
+ return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
121
+ }
122
+
123
+ /**
124
+ * Get usage from an assistant message if available.
125
+ * Skips aborted and error messages as they don't have valid usage data.
126
+ */
127
+ function getAssistantUsage(msg: AgentMessage): Usage | undefined {
128
+ if (msg.role === "assistant" && "usage" in msg) {
129
+ const assistantMsg = msg as AssistantMessage;
130
+ if (assistantMsg.stopReason !== "aborted" && assistantMsg.stopReason !== "error" && assistantMsg.usage) {
131
+ return assistantMsg.usage;
132
+ }
133
+ }
134
+ return undefined;
135
+ }
136
+
137
+ /**
138
+ * Find the last non-aborted assistant message usage from session entries.
139
+ */
140
+ export function getLastAssistantUsage(entries: SessionEntry[]): Usage | undefined {
141
+ for (let i = entries.length - 1; i >= 0; i--) {
142
+ const entry = entries[i];
143
+ if (entry.type === "message") {
144
+ const usage = getAssistantUsage(entry.message);
145
+ if (usage) return usage;
146
+ }
147
+ }
148
+ return undefined;
149
+ }
150
+
151
+ /**
152
+ * Check if compaction should trigger based on context usage.
153
+ */
154
+ export function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean {
155
+ if (!settings.enabled) return false;
156
+ return contextTokens > contextWindow - settings.reserveTokens;
157
+ }
158
+
159
+ // ============================================================================
160
+ // Cut point detection
161
+ // ============================================================================
162
+
163
+ /**
164
+ * Estimate token count for a message using chars/4 heuristic.
165
+ * This is conservative (overestimates tokens).
166
+ */
167
+ export function estimateTokens(message: AgentMessage): number {
168
+ let chars = 0;
169
+
170
+ switch (message.role) {
171
+ case "user": {
172
+ const content = (message as { content: string | Array<{ type: string; text?: string }> }).content;
173
+ if (typeof content === "string") {
174
+ chars = content.length;
175
+ } else if (Array.isArray(content)) {
176
+ for (const block of content) {
177
+ if (block.type === "text" && block.text) {
178
+ chars += block.text.length;
179
+ }
180
+ }
181
+ }
182
+ return Math.ceil(chars / 4);
183
+ }
184
+ case "assistant": {
185
+ const assistant = message as AssistantMessage;
186
+ for (const block of assistant.content) {
187
+ if (block.type === "text") {
188
+ chars += block.text.length;
189
+ } else if (block.type === "thinking") {
190
+ chars += block.thinking.length;
191
+ } else if (block.type === "toolCall") {
192
+ chars += block.name.length + JSON.stringify(block.arguments).length;
193
+ }
194
+ }
195
+ return Math.ceil(chars / 4);
196
+ }
197
+ case "hookMessage":
198
+ case "toolResult": {
199
+ if (typeof message.content === "string") {
200
+ chars = message.content.length;
201
+ } else {
202
+ for (const block of message.content) {
203
+ if (block.type === "text" && block.text) {
204
+ chars += block.text.length;
205
+ }
206
+ if (block.type === "image") {
207
+ chars += 4800; // Estimate images as 4000 chars, or 1200 tokens
208
+ }
209
+ }
210
+ }
211
+ return Math.ceil(chars / 4);
212
+ }
213
+ case "bashExecution": {
214
+ chars = message.command.length + message.output.length;
215
+ return Math.ceil(chars / 4);
216
+ }
217
+ case "branchSummary":
218
+ case "compactionSummary": {
219
+ chars = message.summary.length;
220
+ return Math.ceil(chars / 4);
221
+ }
222
+ }
223
+
224
+ return 0;
225
+ }
226
+
227
+ /**
228
+ * Find valid cut points: indices of user, assistant, custom, or bashExecution messages.
229
+ * Never cut at tool results (they must follow their tool call).
230
+ * When we cut at an assistant message with tool calls, its tool results follow it
231
+ * and will be kept.
232
+ * BashExecutionMessage is treated like a user message (user-initiated context).
233
+ */
234
+ function findValidCutPoints(entries: SessionEntry[], startIndex: number, endIndex: number): number[] {
235
+ const cutPoints: number[] = [];
236
+ for (let i = startIndex; i < endIndex; i++) {
237
+ const entry = entries[i];
238
+ switch (entry.type) {
239
+ case "message": {
240
+ const role = entry.message.role;
241
+ switch (role) {
242
+ case "bashExecution":
243
+ case "hookMessage":
244
+ case "branchSummary":
245
+ case "compactionSummary":
246
+ case "user":
247
+ case "assistant":
248
+ cutPoints.push(i);
249
+ break;
250
+ case "toolResult":
251
+ break;
252
+ }
253
+ break;
254
+ }
255
+ case "thinking_level_change":
256
+ case "model_change":
257
+ case "compaction":
258
+ case "branch_summary":
259
+ case "custom":
260
+ case "custom_message":
261
+ case "label":
262
+ }
263
+ // branch_summary and custom_message are user-role messages, valid cut points
264
+ if (entry.type === "branch_summary" || entry.type === "custom_message") {
265
+ cutPoints.push(i);
266
+ }
267
+ }
268
+ return cutPoints;
269
+ }
270
+
271
+ /**
272
+ * Find the user message (or bashExecution) that starts the turn containing the given entry index.
273
+ * Returns -1 if no turn start found before the index.
274
+ * BashExecutionMessage is treated like a user message for turn boundaries.
275
+ */
276
+ export function findTurnStartIndex(entries: SessionEntry[], entryIndex: number, startIndex: number): number {
277
+ for (let i = entryIndex; i >= startIndex; i--) {
278
+ const entry = entries[i];
279
+ // branch_summary and custom_message are user-role messages, can start a turn
280
+ if (entry.type === "branch_summary" || entry.type === "custom_message") {
281
+ return i;
282
+ }
283
+ if (entry.type === "message") {
284
+ const role = entry.message.role;
285
+ if (role === "user" || role === "bashExecution") {
286
+ return i;
287
+ }
288
+ }
289
+ }
290
+ return -1;
291
+ }
292
+
293
+ export interface CutPointResult {
294
+ /** Index of first entry to keep */
295
+ firstKeptEntryIndex: number;
296
+ /** Index of user message that starts the turn being split, or -1 if not splitting */
297
+ turnStartIndex: number;
298
+ /** Whether this cut splits a turn (cut point is not a user message) */
299
+ isSplitTurn: boolean;
300
+ }
301
+
302
+ /**
303
+ * Find the cut point in session entries that keeps approximately `keepRecentTokens`.
304
+ *
305
+ * Algorithm: Walk backwards from newest, accumulating estimated message sizes.
306
+ * Stop when we've accumulated >= keepRecentTokens. Cut at that point.
307
+ *
308
+ * Can cut at user OR assistant messages (never tool results). When cutting at an
309
+ * assistant message with tool calls, its tool results come after and will be kept.
310
+ *
311
+ * Returns CutPointResult with:
312
+ * - firstKeptEntryIndex: the entry index to start keeping from
313
+ * - turnStartIndex: if cutting mid-turn, the user message that started that turn
314
+ * - isSplitTurn: whether we're cutting in the middle of a turn
315
+ *
316
+ * Only considers entries between `startIndex` and `endIndex` (exclusive).
317
+ */
318
+ export function findCutPoint(
319
+ entries: SessionEntry[],
320
+ startIndex: number,
321
+ endIndex: number,
322
+ keepRecentTokens: number,
323
+ ): CutPointResult {
324
+ const cutPoints = findValidCutPoints(entries, startIndex, endIndex);
325
+
326
+ if (cutPoints.length === 0) {
327
+ return { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };
328
+ }
329
+
330
+ // Walk backwards from newest, accumulating estimated message sizes
331
+ let accumulatedTokens = 0;
332
+ let cutIndex = cutPoints[0]; // Default: keep from first message (not header)
333
+
334
+ for (let i = endIndex - 1; i >= startIndex; i--) {
335
+ const entry = entries[i];
336
+ if (entry.type !== "message") continue;
337
+
338
+ // Estimate this message's size
339
+ const messageTokens = estimateTokens(entry.message);
340
+ accumulatedTokens += messageTokens;
341
+
342
+ // Check if we've exceeded the budget
343
+ if (accumulatedTokens >= keepRecentTokens) {
344
+ // Find the closest valid cut point at or after this entry
345
+ for (let c = 0; c < cutPoints.length; c++) {
346
+ if (cutPoints[c] >= i) {
347
+ cutIndex = cutPoints[c];
348
+ break;
349
+ }
350
+ }
351
+ break;
352
+ }
353
+ }
354
+
355
+ // Scan backwards from cutIndex to include any non-message entries (bash, settings, etc.)
356
+ while (cutIndex > startIndex) {
357
+ const prevEntry = entries[cutIndex - 1];
358
+ // Stop at session header or compaction boundaries
359
+ if (prevEntry.type === "compaction") {
360
+ break;
361
+ }
362
+ if (prevEntry.type === "message") {
363
+ // Stop if we hit any message
364
+ break;
365
+ }
366
+ // Include this non-message entry (bash, settings change, etc.)
367
+ cutIndex--;
368
+ }
369
+
370
+ // Determine if this is a split turn
371
+ const cutEntry = entries[cutIndex];
372
+ const isUserMessage = cutEntry.type === "message" && cutEntry.message.role === "user";
373
+ const turnStartIndex = isUserMessage ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);
374
+
375
+ return {
376
+ firstKeptEntryIndex: cutIndex,
377
+ turnStartIndex,
378
+ isSplitTurn: !isUserMessage && turnStartIndex !== -1,
379
+ };
380
+ }
381
+
382
+ // ============================================================================
383
+ // Summarization
384
+ // ============================================================================
385
+
386
+ const SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
387
+
388
+ Use this EXACT format:
389
+
390
+ ## Goal
391
+ [What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
392
+
393
+ ## Constraints & Preferences
394
+ - [Any constraints, preferences, or requirements mentioned by user]
395
+ - [Or "(none)" if none were mentioned]
396
+
397
+ ## Progress
398
+ ### Done
399
+ - [x] [Completed tasks/changes]
400
+
401
+ ### In Progress
402
+ - [ ] [Current work]
403
+
404
+ ### Blocked
405
+ - [Issues preventing progress, if any]
406
+
407
+ ## Key Decisions
408
+ - **[Decision]**: [Brief rationale]
409
+
410
+ ## Next Steps
411
+ 1. [Ordered list of what should happen next]
412
+
413
+ ## Critical Context
414
+ - [Any data, examples, or references needed to continue]
415
+ - [Or "(none)" if not applicable]
416
+
417
+ Keep each section concise. Preserve exact file paths, function names, and error messages.`;
418
+
419
+ const UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
420
+
421
+ Update the existing structured summary with new information. RULES:
422
+ - PRESERVE all existing information from the previous summary
423
+ - ADD new progress, decisions, and context from the new messages
424
+ - UPDATE the Progress section: move items from "In Progress" to "Done" when completed
425
+ - UPDATE "Next Steps" based on what was accomplished
426
+ - PRESERVE exact file paths, function names, and error messages
427
+ - If something is no longer relevant, you may remove it
428
+
429
+ Use this EXACT format:
430
+
431
+ ## Goal
432
+ [Preserve existing goals, add new ones if the task expanded]
433
+
434
+ ## Constraints & Preferences
435
+ - [Preserve existing, add new ones discovered]
436
+
437
+ ## Progress
438
+ ### Done
439
+ - [x] [Include previously done items AND newly completed items]
440
+
441
+ ### In Progress
442
+ - [ ] [Current work - update based on progress]
443
+
444
+ ### Blocked
445
+ - [Current blockers - remove if resolved]
446
+
447
+ ## Key Decisions
448
+ - **[Decision]**: [Brief rationale] (preserve all previous, add new)
449
+
450
+ ## Next Steps
451
+ 1. [Update based on current state]
452
+
453
+ ## Critical Context
454
+ - [Preserve important context, add new if needed]
455
+
456
+ Keep each section concise. Preserve exact file paths, function names, and error messages.`;
457
+
458
+ /**
459
+ * Generate a summary of the conversation using the LLM.
460
+ * If previousSummary is provided, uses the update prompt to merge.
461
+ */
462
+ export async function generateSummary(
463
+ currentMessages: AgentMessage[],
464
+ model: Model<any>,
465
+ reserveTokens: number,
466
+ apiKey: string,
467
+ signal?: AbortSignal,
468
+ customInstructions?: string,
469
+ previousSummary?: string,
470
+ ): Promise<string> {
471
+ const maxTokens = Math.floor(0.8 * reserveTokens);
472
+
473
+ // Use update prompt if we have a previous summary, otherwise initial prompt
474
+ let basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;
475
+ if (customInstructions) {
476
+ basePrompt = `${basePrompt}\n\nAdditional focus: ${customInstructions}`;
477
+ }
478
+
479
+ // Serialize conversation to text so model doesn't try to continue it
480
+ // Convert to LLM messages first (handles custom types like bashExecution, hookMessage, etc.)
481
+ const llmMessages = convertToLlm(currentMessages);
482
+ const conversationText = serializeConversation(llmMessages);
483
+
484
+ // Build the prompt with conversation wrapped in tags
485
+ let promptText = `<conversation>\n${conversationText}\n</conversation>\n\n`;
486
+ if (previousSummary) {
487
+ promptText += `<previous-summary>\n${previousSummary}\n</previous-summary>\n\n`;
488
+ }
489
+ promptText += basePrompt;
490
+
491
+ const summarizationMessages = [
492
+ {
493
+ role: "user" as const,
494
+ content: [{ type: "text" as const, text: promptText }],
495
+ timestamp: Date.now(),
496
+ },
497
+ ];
498
+
499
+ const response = await completeSimple(
500
+ model,
501
+ { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },
502
+ { maxTokens, signal, apiKey, reasoning: "high" },
503
+ );
504
+
505
+ if (response.stopReason === "error") {
506
+ throw new Error(`Summarization failed: ${response.errorMessage || "Unknown error"}`);
507
+ }
508
+
509
+ const textContent = response.content
510
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
511
+ .map((c) => c.text)
512
+ .join("\n");
513
+
514
+ return textContent;
515
+ }
516
+
517
+ // ============================================================================
518
+ // Compaction Preparation (for hooks)
519
+ // ============================================================================
520
+
521
+ export interface CompactionPreparation {
522
+ /** UUID of first entry to keep */
523
+ firstKeptEntryId: string;
524
+ /** Messages that will be summarized and discarded */
525
+ messagesToSummarize: AgentMessage[];
526
+ /** Messages that will be turned into turn prefix summary (if splitting) */
527
+ turnPrefixMessages: AgentMessage[];
528
+ /** Whether this is a split turn (cut point in middle of turn) */
529
+ isSplitTurn: boolean;
530
+ tokensBefore: number;
531
+ /** Summary from previous compaction, for iterative update */
532
+ previousSummary?: string;
533
+ /** File operations extracted from messagesToSummarize */
534
+ fileOps: FileOperations;
535
+ /** Compaction settions from settings.jsonl */
536
+ settings: CompactionSettings;
537
+ }
538
+
539
+ export function prepareCompaction(
540
+ pathEntries: SessionEntry[],
541
+ settings: CompactionSettings,
542
+ ): CompactionPreparation | undefined {
543
+ if (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === "compaction") {
544
+ return undefined;
545
+ }
546
+
547
+ let prevCompactionIndex = -1;
548
+ for (let i = pathEntries.length - 1; i >= 0; i--) {
549
+ if (pathEntries[i].type === "compaction") {
550
+ prevCompactionIndex = i;
551
+ break;
552
+ }
553
+ }
554
+ const boundaryStart = prevCompactionIndex + 1;
555
+ const boundaryEnd = pathEntries.length;
556
+
557
+ const lastUsage = getLastAssistantUsage(pathEntries);
558
+ const tokensBefore = lastUsage ? calculateContextTokens(lastUsage) : 0;
559
+
560
+ const cutPoint = findCutPoint(pathEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);
561
+
562
+ // Get UUID of first kept entry
563
+ const firstKeptEntry = pathEntries[cutPoint.firstKeptEntryIndex];
564
+ if (!firstKeptEntry?.id) {
565
+ return undefined; // Session needs migration
566
+ }
567
+ const firstKeptEntryId = firstKeptEntry.id;
568
+
569
+ const historyEnd = cutPoint.isSplitTurn ? cutPoint.turnStartIndex : cutPoint.firstKeptEntryIndex;
570
+
571
+ // Messages to summarize (will be discarded after summary)
572
+ const messagesToSummarize: AgentMessage[] = [];
573
+ for (let i = boundaryStart; i < historyEnd; i++) {
574
+ const msg = getMessageFromEntry(pathEntries[i]);
575
+ if (msg) messagesToSummarize.push(msg);
576
+ }
577
+
578
+ // Messages for turn prefix summary (if splitting a turn)
579
+ const turnPrefixMessages: AgentMessage[] = [];
580
+ if (cutPoint.isSplitTurn) {
581
+ for (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {
582
+ const msg = getMessageFromEntry(pathEntries[i]);
583
+ if (msg) turnPrefixMessages.push(msg);
584
+ }
585
+ }
586
+
587
+ // Get previous summary for iterative update
588
+ let previousSummary: string | undefined;
589
+ if (prevCompactionIndex >= 0) {
590
+ const prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;
591
+ previousSummary = prevCompaction.summary;
592
+ }
593
+
594
+ // Extract file operations from messages and previous compaction
595
+ const fileOps = extractFileOperations(messagesToSummarize, pathEntries, prevCompactionIndex);
596
+
597
+ // Also extract file ops from turn prefix if splitting
598
+ if (cutPoint.isSplitTurn) {
599
+ for (const msg of turnPrefixMessages) {
600
+ extractFileOpsFromMessage(msg, fileOps);
601
+ }
602
+ }
603
+
604
+ return {
605
+ firstKeptEntryId,
606
+ messagesToSummarize,
607
+ turnPrefixMessages,
608
+ isSplitTurn: cutPoint.isSplitTurn,
609
+ tokensBefore,
610
+ previousSummary,
611
+ fileOps,
612
+ settings,
613
+ };
614
+ }
615
+
616
+ // ============================================================================
617
+ // Main compaction function
618
+ // ============================================================================
619
+
620
+ const TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.
621
+
622
+ Summarize the prefix to provide context for the retained suffix:
623
+
624
+ ## Original Request
625
+ [What did the user ask for in this turn?]
626
+
627
+ ## Early Progress
628
+ - [Key decisions and work done in the prefix]
629
+
630
+ ## Context for Suffix
631
+ - [Information needed to understand the retained recent work]
632
+
633
+ Be concise. Focus on what's needed to understand the kept suffix.`;
634
+
635
+ /**
636
+ * Generate summaries for compaction using prepared data.
637
+ * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.
638
+ *
639
+ * @param preparation - Pre-calculated preparation from prepareCompaction()
640
+ * @param customInstructions - Optional custom focus for the summary
641
+ */
642
+ export async function compact(
643
+ preparation: CompactionPreparation,
644
+ model: Model<any>,
645
+ apiKey: string,
646
+ customInstructions?: string,
647
+ signal?: AbortSignal,
648
+ ): Promise<CompactionResult> {
649
+ const {
650
+ firstKeptEntryId,
651
+ messagesToSummarize,
652
+ turnPrefixMessages,
653
+ isSplitTurn,
654
+ tokensBefore,
655
+ previousSummary,
656
+ fileOps,
657
+ settings,
658
+ } = preparation;
659
+
660
+ // Generate summaries (can be parallel if both needed) and merge into one
661
+ let summary: string;
662
+
663
+ if (isSplitTurn && turnPrefixMessages.length > 0) {
664
+ // Generate both summaries in parallel
665
+ const [historyResult, turnPrefixResult] = await Promise.all([
666
+ messagesToSummarize.length > 0
667
+ ? generateSummary(
668
+ messagesToSummarize,
669
+ model,
670
+ settings.reserveTokens,
671
+ apiKey,
672
+ signal,
673
+ customInstructions,
674
+ previousSummary,
675
+ )
676
+ : Promise.resolve("No prior history."),
677
+ generateTurnPrefixSummary(turnPrefixMessages, model, settings.reserveTokens, apiKey, signal),
678
+ ]);
679
+ // Merge into single summary
680
+ summary = `${historyResult}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult}`;
681
+ } else {
682
+ // Just generate history summary
683
+ summary = await generateSummary(
684
+ messagesToSummarize,
685
+ model,
686
+ settings.reserveTokens,
687
+ apiKey,
688
+ signal,
689
+ customInstructions,
690
+ previousSummary,
691
+ );
692
+ }
693
+
694
+ // Compute file lists and append to summary
695
+ const { readFiles, modifiedFiles } = computeFileLists(fileOps);
696
+ summary += formatFileOperations(readFiles, modifiedFiles);
697
+
698
+ if (!firstKeptEntryId) {
699
+ throw new Error("First kept entry has no UUID - session may need migration");
700
+ }
701
+
702
+ return {
703
+ summary,
704
+ firstKeptEntryId,
705
+ tokensBefore,
706
+ details: { readFiles, modifiedFiles } as CompactionDetails,
707
+ };
708
+ }
709
+
710
+ /**
711
+ * Generate a summary for a turn prefix (when splitting a turn).
712
+ */
713
+ async function generateTurnPrefixSummary(
714
+ messages: AgentMessage[],
715
+ model: Model<any>,
716
+ reserveTokens: number,
717
+ apiKey: string,
718
+ signal?: AbortSignal,
719
+ ): Promise<string> {
720
+ const maxTokens = Math.floor(0.5 * reserveTokens); // Smaller budget for turn prefix
721
+
722
+ const transformedMessages = convertToLlm(messages);
723
+ const summarizationMessages = [
724
+ ...transformedMessages,
725
+ {
726
+ role: "user" as const,
727
+ content: [{ type: "text" as const, text: TURN_PREFIX_SUMMARIZATION_PROMPT }],
728
+ timestamp: Date.now(),
729
+ },
730
+ ];
731
+
732
+ const response = await complete(model, { messages: summarizationMessages }, { maxTokens, signal, apiKey });
733
+
734
+ if (response.stopReason === "error") {
735
+ throw new Error(`Turn prefix summarization failed: ${response.errorMessage || "Unknown error"}`);
736
+ }
737
+
738
+ return response.content
739
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
740
+ .map((c) => c.text)
741
+ .join("\n");
742
+ }