@astralyn/pi 0.81.1-1 → 0.82.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 (185) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +690 -677
  3. package/dist/cli/args.d.ts.map +1 -1
  4. package/dist/cli/args.js +1 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/cli/config-selector.d.ts.map +1 -1
  7. package/dist/cli/config-selector.js +1 -1
  8. package/dist/cli/config-selector.js.map +1 -1
  9. package/dist/cli/startup-ui.d.ts.map +1 -1
  10. package/dist/cli/startup-ui.js +1 -1
  11. package/dist/cli/startup-ui.js.map +1 -1
  12. package/dist/cli.js +0 -0
  13. package/dist/core/agent-session.d.ts +11 -0
  14. package/dist/core/agent-session.d.ts.map +1 -1
  15. package/dist/core/agent-session.js +7 -8
  16. package/dist/core/agent-session.js.map +1 -1
  17. package/dist/core/compaction/compaction.d.ts.map +1 -1
  18. package/dist/core/compaction/compaction.js +11 -3
  19. package/dist/core/compaction/compaction.js.map +1 -1
  20. package/dist/core/extensions/runner.d.ts.map +1 -1
  21. package/dist/core/extensions/runner.js +4 -0
  22. package/dist/core/extensions/runner.js.map +1 -1
  23. package/dist/core/extensions/types.d.ts +9 -1
  24. package/dist/core/extensions/types.d.ts.map +1 -1
  25. package/dist/core/extensions/types.js.map +1 -1
  26. package/dist/core/model-config.d.ts +30 -0
  27. package/dist/core/model-config.d.ts.map +1 -1
  28. package/dist/core/model-config.js +6 -0
  29. package/dist/core/model-config.js.map +1 -1
  30. package/dist/core/model-registry.d.ts.map +1 -1
  31. package/dist/core/model-registry.js +2 -2
  32. package/dist/core/model-registry.js.map +1 -1
  33. package/dist/core/model-resolver.d.ts.map +1 -1
  34. package/dist/core/model-resolver.js +7 -0
  35. package/dist/core/model-resolver.js.map +1 -1
  36. package/dist/core/model-runtime.d.ts +0 -1
  37. package/dist/core/model-runtime.d.ts.map +1 -1
  38. package/dist/core/model-runtime.js +3 -5
  39. package/dist/core/model-runtime.js.map +1 -1
  40. package/dist/core/remote-catalog-provider.d.ts +1 -1
  41. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  42. package/dist/core/remote-catalog-provider.js +5 -10
  43. package/dist/core/remote-catalog-provider.js.map +1 -1
  44. package/dist/core/settings-manager.d.ts +1 -1
  45. package/dist/core/settings-manager.d.ts.map +1 -1
  46. package/dist/core/settings-manager.js.map +1 -1
  47. package/dist/core/system-prompt.d.ts.map +1 -1
  48. package/dist/core/system-prompt.js +1 -1
  49. package/dist/core/system-prompt.js.map +1 -1
  50. package/dist/core/tools/bash.d.ts +2 -1
  51. package/dist/core/tools/bash.d.ts.map +1 -1
  52. package/dist/core/tools/bash.js +114 -24
  53. package/dist/core/tools/bash.js.map +1 -1
  54. package/dist/core/tools/find.d.ts.map +1 -1
  55. package/dist/core/tools/find.js +1 -0
  56. package/dist/core/tools/find.js.map +1 -1
  57. package/dist/core/tools/read.d.ts.map +1 -1
  58. package/dist/core/tools/read.js +4 -3
  59. package/dist/core/tools/read.js.map +1 -1
  60. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  61. package/dist/core/tools/tool-definition-wrapper.js +5 -1
  62. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  63. package/dist/extensions/index.d.ts.map +1 -1
  64. package/dist/extensions/index.js +2 -0
  65. package/dist/extensions/index.js.map +1 -1
  66. package/dist/extensions/llama/provider.d.ts.map +1 -1
  67. package/dist/extensions/llama/provider.js +1 -2
  68. package/dist/extensions/llama/provider.js.map +1 -1
  69. package/dist/extensions/subagent/activity.d.ts +16 -0
  70. package/dist/extensions/subagent/activity.d.ts.map +1 -0
  71. package/dist/extensions/subagent/activity.js +150 -0
  72. package/dist/extensions/subagent/activity.js.map +1 -0
  73. package/dist/extensions/subagent/agents.d.ts +7 -0
  74. package/dist/extensions/subagent/agents.d.ts.map +1 -0
  75. package/dist/extensions/subagent/agents.js +218 -0
  76. package/dist/extensions/subagent/agents.js.map +1 -0
  77. package/dist/extensions/subagent/constants.d.ts +22 -0
  78. package/dist/extensions/subagent/constants.d.ts.map +1 -0
  79. package/dist/extensions/subagent/constants.js +32 -0
  80. package/dist/extensions/subagent/constants.js.map +1 -0
  81. package/dist/extensions/subagent/index.d.ts +3 -0
  82. package/dist/extensions/subagent/index.d.ts.map +1 -0
  83. package/dist/extensions/subagent/index.js +249 -0
  84. package/dist/extensions/subagent/index.js.map +1 -0
  85. package/dist/extensions/subagent/picker.d.ts +31 -0
  86. package/dist/extensions/subagent/picker.d.ts.map +1 -0
  87. package/dist/extensions/subagent/picker.js +116 -0
  88. package/dist/extensions/subagent/picker.js.map +1 -0
  89. package/dist/extensions/subagent/render.d.ts +8 -0
  90. package/dist/extensions/subagent/render.d.ts.map +1 -0
  91. package/dist/extensions/subagent/render.js +322 -0
  92. package/dist/extensions/subagent/render.js.map +1 -0
  93. package/dist/extensions/subagent/resolve.d.ts +16 -0
  94. package/dist/extensions/subagent/resolve.d.ts.map +1 -0
  95. package/dist/extensions/subagent/resolve.js +103 -0
  96. package/dist/extensions/subagent/resolve.js.map +1 -0
  97. package/dist/extensions/subagent/runner.d.ts +30 -0
  98. package/dist/extensions/subagent/runner.d.ts.map +1 -0
  99. package/dist/extensions/subagent/runner.js +355 -0
  100. package/dist/extensions/subagent/runner.js.map +1 -0
  101. package/dist/extensions/subagent/schema.d.ts +28 -0
  102. package/dist/extensions/subagent/schema.d.ts.map +1 -0
  103. package/dist/extensions/subagent/schema.js +33 -0
  104. package/dist/extensions/subagent/schema.js.map +1 -0
  105. package/dist/extensions/subagent/sdk-runner.d.ts +14 -0
  106. package/dist/extensions/subagent/sdk-runner.d.ts.map +1 -0
  107. package/dist/extensions/subagent/sdk-runner.js +210 -0
  108. package/dist/extensions/subagent/sdk-runner.js.map +1 -0
  109. package/dist/extensions/subagent/settings.d.ts +9 -0
  110. package/dist/extensions/subagent/settings.d.ts.map +1 -0
  111. package/dist/extensions/subagent/settings.js +131 -0
  112. package/dist/extensions/subagent/settings.js.map +1 -0
  113. package/dist/extensions/subagent/types.d.ts +99 -0
  114. package/dist/extensions/subagent/types.d.ts.map +1 -0
  115. package/dist/extensions/subagent/types.js +2 -0
  116. package/dist/extensions/subagent/types.js.map +1 -0
  117. package/dist/modes/interactive/components/extension-editor.d.ts +1 -2
  118. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  119. package/dist/modes/interactive/components/extension-editor.js +16 -46
  120. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  121. package/dist/modes/interactive/components/index.d.ts +1 -0
  122. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  123. package/dist/modes/interactive/components/index.js +1 -0
  124. package/dist/modes/interactive/components/index.js.map +1 -1
  125. package/dist/modes/interactive/components/tool-execution.d.ts +2 -0
  126. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  127. package/dist/modes/interactive/components/tool-execution.js +25 -4
  128. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  129. package/dist/modes/interactive/components/tool-group.d.ts +16 -0
  130. package/dist/modes/interactive/components/tool-group.d.ts.map +1 -0
  131. package/dist/modes/interactive/components/tool-group.js +64 -0
  132. package/dist/modes/interactive/components/tool-group.js.map +1 -0
  133. package/dist/modes/interactive/external-editor.d.ts +12 -0
  134. package/dist/modes/interactive/external-editor.d.ts.map +1 -0
  135. package/dist/modes/interactive/external-editor.js +37 -0
  136. package/dist/modes/interactive/external-editor.js.map +1 -0
  137. package/dist/modes/interactive/interactive-mode.d.ts +3 -1
  138. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  139. package/dist/modes/interactive/interactive-mode.js +61 -62
  140. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  141. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  142. package/dist/modes/rpc/rpc-mode.js +1 -0
  143. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  144. package/dist/rpc-entry.js +0 -0
  145. package/dist/utils/clipboard.d.ts.map +1 -1
  146. package/dist/utils/clipboard.js +19 -8
  147. package/dist/utils/clipboard.js.map +1 -1
  148. package/dist/utils/version-check.d.ts.map +1 -1
  149. package/dist/utils/version-check.js +3 -1
  150. package/dist/utils/version-check.js.map +1 -1
  151. package/docs/compaction.md +401 -401
  152. package/docs/containerization.md +111 -111
  153. package/docs/custom-provider.md +766 -763
  154. package/docs/environment-variables.md +88 -0
  155. package/docs/extensions.md +2961 -2953
  156. package/docs/index.md +80 -77
  157. package/docs/models.md +6 -2
  158. package/docs/packages.md +228 -228
  159. package/docs/providers.md +8 -1
  160. package/docs/quickstart.md +165 -165
  161. package/docs/rpc.md +1576 -1559
  162. package/docs/sdk.md +1186 -1186
  163. package/docs/session-format.md +436 -436
  164. package/docs/settings.md +1 -1
  165. package/docs/termux.md +127 -127
  166. package/docs/tui.md +942 -942
  167. package/docs/usage.md +0 -13
  168. package/examples/extensions/README.md +213 -213
  169. package/examples/extensions/custom-compaction.ts +3 -0
  170. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  171. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  172. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  173. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  174. package/examples/extensions/doom-overlay/doom/build.sh +0 -0
  175. package/examples/extensions/gondolin/package-lock.json +2 -2
  176. package/examples/extensions/gondolin/package.json +1 -1
  177. package/examples/extensions/handoff.ts +9 -1
  178. package/examples/extensions/sandbox/package-lock.json +2 -2
  179. package/examples/extensions/sandbox/package.json +1 -1
  180. package/examples/extensions/summarize.ts +3 -0
  181. package/examples/extensions/with-deps/package-lock.json +2 -2
  182. package/examples/extensions/with-deps/package.json +1 -1
  183. package/examples/sdk/README.md +140 -140
  184. package/npm-shrinkwrap.json +16 -15
  185. package/package.json +10 -4
@@ -1,401 +1,401 @@
1
- # Compaction & Branch Summarization
2
-
3
- LLMs have limited context windows. When conversations grow too long, pi uses compaction to summarize older content while preserving recent work. This page covers both auto-compaction and branch summarization.
4
-
5
- **Source files** ([pi-mono](https://github.com/earendil-works/pi-mono)):
6
- - [`packages/coding-agent/src/core/compaction/compaction.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/compaction.ts) - Auto-compaction logic
7
- - [`packages/coding-agent/src/core/compaction/branch-summarization.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts) - Branch summarization
8
- - [`packages/coding-agent/src/core/compaction/utils.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/utils.ts) - Shared utilities (file tracking, serialization)
9
- - [`packages/coding-agent/src/core/session-manager.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/session-manager.ts) - Entry types (`CompactionEntry`, `BranchSummaryEntry`)
10
- - [`packages/coding-agent/src/core/extensions/types.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/extensions/types.ts) - Extension event types
11
-
12
- For TypeScript definitions in your project, inspect `node_modules/@astralyn/pi/dist/`.
13
-
14
- ## Overview
15
-
16
- Pi has two summarization mechanisms:
17
-
18
- | Mechanism | Trigger | Purpose |
19
- |-----------|---------|---------|
20
- | Compaction | Context exceeds threshold, or `/compact` | Summarize old messages to free up context |
21
- | Branch summarization | `/tree` navigation | Preserve context when switching branches |
22
-
23
- Both use the same structured summary format and track file operations cumulatively.
24
-
25
- ## Compaction
26
-
27
- ### When It Triggers
28
-
29
- Auto-compaction triggers when:
30
-
31
- ```
32
- contextTokens > contextWindow - reserveTokens
33
- ```
34
-
35
- By default, `reserveTokens` is 16384 tokens (configurable in `~/.pi/agent/settings.json` or `<project-dir>/.pi/settings.json`). This leaves room for the LLM's response.
36
-
37
- You can also trigger manually with `/compact [instructions]`, where optional instructions focus the summary.
38
-
39
- ### How It Works
40
-
41
- 1. **Find cut point**: Walk backwards from newest message, accumulating token estimates until `keepRecentTokens` (default 20k, configurable in `~/.pi/agent/settings.json` or `<project-dir>/.pi/settings.json`) is reached
42
- 2. **Extract messages**: Collect messages from the previous kept boundary (or session start) up to the cut point
43
- 3. **Generate summary**: Call LLM to summarize with structured format, passing the previous summary as iterative context when present
44
- 4. **Append entry**: Save `CompactionEntry` with summary and `firstKeptEntryId`
45
- 5. **Reload**: Session reloads, using summary + messages from `firstKeptEntryId` onwards
46
-
47
- ```
48
- Before compaction:
49
-
50
- entry: 0 1 2 3 4 5 6 7 8 9
51
- ┌─────┬─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┐
52
- │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│
53
- └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┘
54
- └────────┬───────┘ └──────────────┬──────────────┘
55
- messagesToSummarize kept messages
56
- ↑
57
- firstKeptEntryId (entry 4)
58
-
59
- After compaction (new entry appended):
60
-
61
- entry: 0 1 2 3 4 5 6 7 8 9 10
62
- ┌─────┬─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬─────┐
63
- │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│ cmp │
64
- └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┴─────┘
65
- └──────────┬──────┘ └──────────────────────┬───────────────────┘
66
- not sent to LLM sent to LLM
67
- ↑
68
- starts from firstKeptEntryId
69
-
70
- What the LLM sees:
71
-
72
- ┌────────┬─────────┬─────┬─────┬──────┬──────┬─────┬──────┐
73
- │ system │ summary │ usr │ ass │ tool │ tool │ ass │ tool │
74
- └────────┴─────────┴─────┴─────┴──────┴──────┴─────┴──────┘
75
- ↑ ↑ └─────────────────┬────────────────┘
76
- prompt from cmp messages from firstKeptEntryId
77
- ```
78
-
79
- On repeated compactions, the summarized span starts at the previous compaction's kept boundary (`firstKeptEntryId`), not at the compaction entry itself, falling back to the entry after the previous compaction if that kept entry cannot be found in the path. This preserves messages that survived the earlier compaction by including them in the next summarization pass as well. Pi also recalculates `tokensBefore` from the rebuilt session context before writing the new `CompactionEntry`, so the token count reflects the actual pre-compaction context being replaced.
80
-
81
- ### Split Turns
82
-
83
- A "turn" starts with a user message and includes all assistant responses and tool calls until the next user message. Normally, compaction cuts at turn boundaries.
84
-
85
- When a single turn exceeds `keepRecentTokens`, the cut point lands mid-turn at an assistant message. This is a "split turn":
86
-
87
- ```
88
- Split turn (one huge turn exceeds budget):
89
-
90
- entry: 0 1 2 3 4 5 6 7 8
91
- ┌─────┬─────┬─────┬──────┬─────┬──────┬──────┬─────┬──────┐
92
- │ hdr │ usr │ ass │ tool │ ass │ tool │ tool │ ass │ tool │
93
- └─────┴─────┴─────┴──────┴─────┴──────┴──────┴─────┴──────┘
94
- ↑ ↑
95
- turnStartIndex = 1 firstKeptEntryId = 7
96
- │ │
97
- └──── turnPrefixMessages (1-6) ───────┘
98
- └── kept (7-8)
99
-
100
- isSplitTurn = true
101
- messagesToSummarize = [] (no complete turns before)
102
- turnPrefixMessages = [usr, ass, tool, ass, tool, tool]
103
- ```
104
-
105
- For split turns, pi generates two summaries and merges them:
106
- 1. **History summary**: Previous context (if any)
107
- 2. **Turn prefix summary**: The early part of the split turn
108
-
109
- ### Cut Point Rules
110
-
111
- Valid cut points are:
112
- - User messages
113
- - Assistant messages
114
- - BashExecution messages
115
- - Custom messages (custom_message, branch_summary)
116
-
117
- Never cut at tool results (they must stay with their tool call).
118
-
119
- ### CompactionEntry Structure
120
-
121
- Defined in [`session-manager.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/session-manager.ts):
122
-
123
- ```typescript
124
- interface CompactionEntry<T = unknown> {
125
- type: "compaction";
126
- id: string;
127
- parentId: string;
128
- timestamp: number;
129
- summary: string;
130
- firstKeptEntryId: string;
131
- tokensBefore: number;
132
- usage?: Usage; // LLM usage that generated the summary
133
- fromHook?: boolean; // true if provided by extension (legacy field name)
134
- details?: T; // implementation-specific data
135
- }
136
-
137
- // Default compaction uses this for details (from compaction.ts):
138
- interface CompactionDetails {
139
- readFiles: string[];
140
- modifiedFiles: string[];
141
- }
142
- ```
143
-
144
- Extensions can store any JSON-serializable data in `details`. The default compaction tracks file operations, but custom extension implementations can use their own structure. Generated and extension-provided summaries store their LLM `usage` when available so session totals include summarization work.
145
-
146
- See [`prepareCompaction()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/compaction.ts) and [`compact()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/compaction.ts) for the implementation. For direct programmatic summarization, `generateSummary()` returns the summary text and `generateSummaryWithUsage()` returns `{ text, usage }`.
147
-
148
- ## Branch Summarization
149
-
150
- ### When It Triggers
151
-
152
- When you use `/tree` to navigate to a different branch, pi offers to summarize the work you're leaving. This injects context from the left branch into the new branch.
153
-
154
- ### How It Works
155
-
156
- 1. **Find common ancestor**: Deepest node shared by old and new positions
157
- 2. **Collect entries**: Walk from old leaf back to common ancestor
158
- 3. **Prepare with budget**: Include messages up to token budget (newest first)
159
- 4. **Generate summary**: Call LLM with structured format
160
- 5. **Append entry**: Save `BranchSummaryEntry` at navigation point
161
-
162
- ```
163
- Tree before navigation:
164
-
165
- ┌─ B ─ C ─ D (old leaf, being abandoned)
166
- A ───┤
167
- └─ E ─ F (target)
168
-
169
- Common ancestor: A
170
- Entries to summarize: B, C, D
171
-
172
- After navigation with summary:
173
-
174
- ┌─ B ─ C ─ D ─ [summary of B,C,D]
175
- A ───┤
176
- └─ E ─ F (new leaf)
177
- ```
178
-
179
- ### Cumulative File Tracking
180
-
181
- Both compaction and branch summarization track files cumulatively. When generating a summary, pi extracts file operations from:
182
- - Tool calls in the messages being summarized
183
- - Previous compaction or branch summary `details` (if any)
184
-
185
- This means file tracking accumulates across multiple compactions or nested branch summaries, preserving the full history of read and modified files.
186
-
187
- ### BranchSummaryEntry Structure
188
-
189
- Defined in [`session-manager.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/session-manager.ts):
190
-
191
- ```typescript
192
- interface BranchSummaryEntry<T = unknown> {
193
- type: "branch_summary";
194
- id: string;
195
- parentId: string;
196
- timestamp: number;
197
- summary: string;
198
- fromId: string; // Entry we navigated from
199
- usage?: Usage; // LLM usage that generated the summary
200
- fromHook?: boolean; // true if provided by extension (legacy field name)
201
- details?: T; // implementation-specific data
202
- }
203
-
204
- // Default branch summarization uses this for details (from branch-summarization.ts):
205
- interface BranchSummaryDetails {
206
- readFiles: string[];
207
- modifiedFiles: string[];
208
- }
209
- ```
210
-
211
- Same as compaction, extensions can store custom data in `details`.
212
-
213
- See [`collectEntriesForBranchSummary()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts), [`prepareBranchEntries()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts), and [`generateBranchSummary()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts) for the implementation.
214
-
215
- ## Summary Format
216
-
217
- Both compaction and branch summarization use the same structured format:
218
-
219
- ```markdown
220
- ## Goal
221
- [What the user is trying to accomplish]
222
-
223
- ## Constraints & Preferences
224
- - [Requirements mentioned by user]
225
-
226
- ## Progress
227
- ### Done
228
- - [x] [Completed tasks]
229
-
230
- ### In Progress
231
- - [ ] [Current work]
232
-
233
- ### Blocked
234
- - [Issues, if any]
235
-
236
- ## Key Decisions
237
- - **[Decision]**: [Rationale]
238
-
239
- ## Next Steps
240
- 1. [What should happen next]
241
-
242
- ## Critical Context
243
- - [Data needed to continue]
244
-
245
- <read-files>
246
- path/to/file1.ts
247
- path/to/file2.ts
248
- </read-files>
249
-
250
- <modified-files>
251
- path/to/changed.ts
252
- </modified-files>
253
- ```
254
-
255
- ### Message Serialization
256
-
257
- Before summarization, messages are serialized to text via [`serializeConversation()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/utils.ts):
258
-
259
- ```
260
- [User]: What they said
261
- [Assistant thinking]: Internal reasoning
262
- [Assistant]: Response text
263
- [Assistant tool calls]: read(path="foo.ts"); edit(path="bar.ts", ...)
264
- [Tool result]: Output from tool
265
- ```
266
-
267
- This prevents the model from treating it as a conversation to continue.
268
-
269
- Tool results are truncated to 2000 characters during serialization. Content beyond that limit is replaced with a marker indicating how many characters were truncated. This keeps summarization requests within reasonable token budgets, since tool results (especially from `read` and `bash`) are typically the largest contributors to context size.
270
-
271
- ## Custom Summarization via Extensions
272
-
273
- Extensions can intercept and customize both compaction and branch summarization. See [`extensions/types.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/extensions/types.ts) for event type definitions.
274
-
275
- ### session_before_compact
276
-
277
- Fired before auto-compaction or `/compact`. Can cancel or provide custom summary. See `SessionBeforeCompactEvent` and `CompactionPreparation` in the types file.
278
-
279
- ```typescript
280
- pi.on("session_before_compact", async (event, ctx) => {
281
- const { preparation, branchEntries, customInstructions, reason, willRetry, signal } = event;
282
-
283
- // preparation.messagesToSummarize - messages to summarize
284
- // preparation.turnPrefixMessages - split turn prefix (if isSplitTurn)
285
- // preparation.previousSummary - previous compaction summary
286
- // preparation.fileOps - extracted file operations
287
- // preparation.tokensBefore - context tokens before compaction
288
- // preparation.firstKeptEntryId - where kept messages start
289
- // preparation.settings - compaction settings
290
-
291
- // branchEntries - all entries on current branch (for custom state)
292
- // reason - "manual" (/compact), "threshold", or "overflow"
293
- // willRetry - whether the aborted turn is retried after compaction (overflow recovery)
294
- // signal - AbortSignal (pass to LLM calls)
295
-
296
- // Cancel:
297
- return { cancel: true };
298
-
299
- // Custom summary:
300
- return {
301
- compaction: {
302
- summary: "Your summary...",
303
- firstKeptEntryId: preparation.firstKeptEntryId,
304
- tokensBefore: preparation.tokensBefore,
305
- // usage: summaryResponse.usage, // Optional; included in session totals
306
- details: { /* custom data */ },
307
- }
308
- };
309
- });
310
- ```
311
-
312
- #### Converting Messages to Text
313
-
314
- To generate a summary with your own model, convert messages to text using `serializeConversation`:
315
-
316
- ```typescript
317
- import { convertToLlm, serializeConversation } from "@astralyn/pi";
318
-
319
- pi.on("session_before_compact", async (event, ctx) => {
320
- const { preparation } = event;
321
-
322
- // Convert AgentMessage[] to Message[], then serialize to text
323
- const conversationText = serializeConversation(
324
- convertToLlm(preparation.messagesToSummarize)
325
- );
326
- // Returns:
327
- // [User]: message text
328
- // [Assistant thinking]: thinking content
329
- // [Assistant]: response text
330
- // [Assistant tool calls]: read(path="..."); bash(command="...")
331
- // [Tool result]: output text
332
-
333
- // Now send to your model for summarization
334
- const { summary, usage } = await myModel.summarize(conversationText);
335
-
336
- return {
337
- compaction: {
338
- summary,
339
- firstKeptEntryId: preparation.firstKeptEntryId,
340
- tokensBefore: preparation.tokensBefore,
341
- usage,
342
- }
343
- };
344
- });
345
- ```
346
-
347
- See [custom-compaction.ts](../examples/extensions/custom-compaction.ts) for a complete example using a different model.
348
-
349
- ### session_before_tree
350
-
351
- Fired before `/tree` navigation. Always fires regardless of whether user chose to summarize. Can cancel navigation or provide custom summary.
352
-
353
- ```typescript
354
- pi.on("session_before_tree", async (event, ctx) => {
355
- const { preparation, signal } = event;
356
-
357
- // preparation.targetId - where we're navigating to
358
- // preparation.oldLeafId - current position (being abandoned)
359
- // preparation.commonAncestorId - shared ancestor
360
- // preparation.entriesToSummarize - entries that would be summarized
361
- // preparation.userWantsSummary - whether user chose to summarize
362
-
363
- // Cancel navigation entirely:
364
- return { cancel: true };
365
-
366
- // Provide custom summary (only used if userWantsSummary is true):
367
- if (preparation.userWantsSummary) {
368
- return {
369
- summary: {
370
- summary: "Your summary...",
371
- // usage: summaryResponse.usage, // Optional; included in session totals
372
- details: { /* custom data */ },
373
- }
374
- };
375
- }
376
- });
377
- ```
378
-
379
- See `SessionBeforeTreeEvent` and `TreePreparation` in the types file.
380
-
381
- ## Settings
382
-
383
- Configure compaction in `~/.pi/agent/settings.json` or `<project-dir>/.pi/settings.json`:
384
-
385
- ```json
386
- {
387
- "compaction": {
388
- "enabled": true,
389
- "reserveTokens": 16384,
390
- "keepRecentTokens": 20000
391
- }
392
- }
393
- ```
394
-
395
- | Setting | Default | Description |
396
- |---------|---------|-------------|
397
- | `enabled` | `true` | Enable auto-compaction |
398
- | `reserveTokens` | `16384` | Tokens to reserve for LLM response |
399
- | `keepRecentTokens` | `20000` | Recent tokens to keep (not summarized) |
400
-
401
- Disable auto-compaction with `"enabled": false`. You can still compact manually with `/compact`.
1
+ # Compaction & Branch Summarization
2
+
3
+ LLMs have limited context windows. When conversations grow too long, pi uses compaction to summarize older content while preserving recent work. This page covers both auto-compaction and branch summarization.
4
+
5
+ **Source files** ([pi-mono](https://github.com/earendil-works/pi-mono)):
6
+ - [`packages/coding-agent/src/core/compaction/compaction.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/compaction.ts) - Auto-compaction logic
7
+ - [`packages/coding-agent/src/core/compaction/branch-summarization.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts) - Branch summarization
8
+ - [`packages/coding-agent/src/core/compaction/utils.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/utils.ts) - Shared utilities (file tracking, serialization)
9
+ - [`packages/coding-agent/src/core/session-manager.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/session-manager.ts) - Entry types (`CompactionEntry`, `BranchSummaryEntry`)
10
+ - [`packages/coding-agent/src/core/extensions/types.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/extensions/types.ts) - Extension event types
11
+
12
+ For TypeScript definitions in your project, inspect `node_modules/@astralyn/pi/dist/`.
13
+
14
+ ## Overview
15
+
16
+ Pi has two summarization mechanisms:
17
+
18
+ | Mechanism | Trigger | Purpose |
19
+ |-----------|---------|---------|
20
+ | Compaction | Context exceeds threshold, or `/compact` | Summarize old messages to free up context |
21
+ | Branch summarization | `/tree` navigation | Preserve context when switching branches |
22
+
23
+ Both use the same structured summary format and track file operations cumulatively. Compaction and branch-summary requests use fresh routing session IDs and, where supported by the provider, disable prompt-cache writes because these one-off prompts are unlikely to be reused.
24
+
25
+ ## Compaction
26
+
27
+ ### When It Triggers
28
+
29
+ Auto-compaction triggers when:
30
+
31
+ ```
32
+ contextTokens > contextWindow - reserveTokens
33
+ ```
34
+
35
+ By default, `reserveTokens` is 16384 tokens (configurable in `~/.pi/agent/settings.json` or `<project-dir>/.pi/settings.json`). This leaves room for the LLM's response.
36
+
37
+ You can also trigger manually with `/compact [instructions]`, where optional instructions focus the summary.
38
+
39
+ ### How It Works
40
+
41
+ 1. **Find cut point**: Walk backwards from newest message, accumulating token estimates until `keepRecentTokens` (default 20k, configurable in `~/.pi/agent/settings.json` or `<project-dir>/.pi/settings.json`) is reached
42
+ 2. **Extract messages**: Collect messages from the previous kept boundary (or session start) up to the cut point
43
+ 3. **Generate summary**: Call LLM to summarize with structured format, passing the previous summary as iterative context when present
44
+ 4. **Append entry**: Save `CompactionEntry` with summary and `firstKeptEntryId`
45
+ 5. **Reload**: Session reloads, using summary + messages from `firstKeptEntryId` onwards
46
+
47
+ ```
48
+ Before compaction:
49
+
50
+ entry: 0 1 2 3 4 5 6 7 8 9
51
+ ┌─────┬─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┐
52
+ │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│
53
+ └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┘
54
+ └────────┬───────┘ └──────────────┬──────────────┘
55
+ messagesToSummarize kept messages
56
+ ↑
57
+ firstKeptEntryId (entry 4)
58
+
59
+ After compaction (new entry appended):
60
+
61
+ entry: 0 1 2 3 4 5 6 7 8 9 10
62
+ ┌─────┬─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬─────┐
63
+ │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│ cmp │
64
+ └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┴─────┘
65
+ └──────────┬──────┘ └──────────────────────┬───────────────────┘
66
+ not sent to LLM sent to LLM
67
+ ↑
68
+ starts from firstKeptEntryId
69
+
70
+ What the LLM sees:
71
+
72
+ ┌────────┬─────────┬─────┬─────┬──────┬──────┬─────┬──────┐
73
+ │ system │ summary │ usr │ ass │ tool │ tool │ ass │ tool │
74
+ └────────┴─────────┴─────┴─────┴──────┴──────┴─────┴──────┘
75
+ ↑ ↑ └─────────────────┬────────────────┘
76
+ prompt from cmp messages from firstKeptEntryId
77
+ ```
78
+
79
+ On repeated compactions, the summarized span starts at the previous compaction's kept boundary (`firstKeptEntryId`), not at the compaction entry itself, falling back to the entry after the previous compaction if that kept entry cannot be found in the path. This preserves messages that survived the earlier compaction by including them in the next summarization pass as well. Pi also recalculates `tokensBefore` from the rebuilt session context before writing the new `CompactionEntry`, so the token count reflects the actual pre-compaction context being replaced.
80
+
81
+ ### Split Turns
82
+
83
+ A "turn" starts with a user message and includes all assistant responses and tool calls until the next user message. Normally, compaction cuts at turn boundaries.
84
+
85
+ When a single turn exceeds `keepRecentTokens`, the cut point lands mid-turn at an assistant message. This is a "split turn":
86
+
87
+ ```
88
+ Split turn (one huge turn exceeds budget):
89
+
90
+ entry: 0 1 2 3 4 5 6 7 8
91
+ ┌─────┬─────┬─────┬──────┬─────┬──────┬──────┬─────┬──────┐
92
+ │ hdr │ usr │ ass │ tool │ ass │ tool │ tool │ ass │ tool │
93
+ └─────┴─────┴─────┴──────┴─────┴──────┴──────┴─────┴──────┘
94
+ ↑ ↑
95
+ turnStartIndex = 1 firstKeptEntryId = 7
96
+ │ │
97
+ └──── turnPrefixMessages (1-6) ───────┘
98
+ └── kept (7-8)
99
+
100
+ isSplitTurn = true
101
+ messagesToSummarize = [] (no complete turns before)
102
+ turnPrefixMessages = [usr, ass, tool, ass, tool, tool]
103
+ ```
104
+
105
+ For split turns, pi generates two summaries and merges them:
106
+ 1. **History summary**: Previous context (if any)
107
+ 2. **Turn prefix summary**: The early part of the split turn
108
+
109
+ ### Cut Point Rules
110
+
111
+ Valid cut points are:
112
+ - User messages
113
+ - Assistant messages
114
+ - BashExecution messages
115
+ - Custom messages (custom_message, branch_summary)
116
+
117
+ Never cut at tool results (they must stay with their tool call).
118
+
119
+ ### CompactionEntry Structure
120
+
121
+ Defined in [`session-manager.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/session-manager.ts):
122
+
123
+ ```typescript
124
+ interface CompactionEntry<T = unknown> {
125
+ type: "compaction";
126
+ id: string;
127
+ parentId: string;
128
+ timestamp: number;
129
+ summary: string;
130
+ firstKeptEntryId: string;
131
+ tokensBefore: number;
132
+ usage?: Usage; // LLM usage that generated the summary
133
+ fromHook?: boolean; // true if provided by extension (legacy field name)
134
+ details?: T; // implementation-specific data
135
+ }
136
+
137
+ // Default compaction uses this for details (from compaction.ts):
138
+ interface CompactionDetails {
139
+ readFiles: string[];
140
+ modifiedFiles: string[];
141
+ }
142
+ ```
143
+
144
+ Extensions can store any JSON-serializable data in `details`. The default compaction tracks file operations, but custom extension implementations can use their own structure. Generated and extension-provided summaries store their LLM `usage` when available so session totals include summarization work.
145
+
146
+ See [`prepareCompaction()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/compaction.ts) and [`compact()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/compaction.ts) for the implementation. For direct programmatic summarization, `generateSummary()` returns the summary text and `generateSummaryWithUsage()` returns `{ text, usage }`.
147
+
148
+ ## Branch Summarization
149
+
150
+ ### When It Triggers
151
+
152
+ When you use `/tree` to navigate to a different branch, pi offers to summarize the work you're leaving. This injects context from the left branch into the new branch.
153
+
154
+ ### How It Works
155
+
156
+ 1. **Find common ancestor**: Deepest node shared by old and new positions
157
+ 2. **Collect entries**: Walk from old leaf back to common ancestor
158
+ 3. **Prepare with budget**: Include messages up to token budget (newest first)
159
+ 4. **Generate summary**: Call LLM with structured format
160
+ 5. **Append entry**: Save `BranchSummaryEntry` at navigation point
161
+
162
+ ```
163
+ Tree before navigation:
164
+
165
+ ┌─ B ─ C ─ D (old leaf, being abandoned)
166
+ A ───┤
167
+ └─ E ─ F (target)
168
+
169
+ Common ancestor: A
170
+ Entries to summarize: B, C, D
171
+
172
+ After navigation with summary:
173
+
174
+ ┌─ B ─ C ─ D ─ [summary of B,C,D]
175
+ A ───┤
176
+ └─ E ─ F (new leaf)
177
+ ```
178
+
179
+ ### Cumulative File Tracking
180
+
181
+ Both compaction and branch summarization track files cumulatively. When generating a summary, pi extracts file operations from:
182
+ - Tool calls in the messages being summarized
183
+ - Previous compaction or branch summary `details` (if any)
184
+
185
+ This means file tracking accumulates across multiple compactions or nested branch summaries, preserving the full history of read and modified files.
186
+
187
+ ### BranchSummaryEntry Structure
188
+
189
+ Defined in [`session-manager.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/session-manager.ts):
190
+
191
+ ```typescript
192
+ interface BranchSummaryEntry<T = unknown> {
193
+ type: "branch_summary";
194
+ id: string;
195
+ parentId: string;
196
+ timestamp: number;
197
+ summary: string;
198
+ fromId: string; // Entry we navigated from
199
+ usage?: Usage; // LLM usage that generated the summary
200
+ fromHook?: boolean; // true if provided by extension (legacy field name)
201
+ details?: T; // implementation-specific data
202
+ }
203
+
204
+ // Default branch summarization uses this for details (from branch-summarization.ts):
205
+ interface BranchSummaryDetails {
206
+ readFiles: string[];
207
+ modifiedFiles: string[];
208
+ }
209
+ ```
210
+
211
+ Same as compaction, extensions can store custom data in `details`.
212
+
213
+ See [`collectEntriesForBranchSummary()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts), [`prepareBranchEntries()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts), and [`generateBranchSummary()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts) for the implementation.
214
+
215
+ ## Summary Format
216
+
217
+ Both compaction and branch summarization use the same structured format:
218
+
219
+ ```markdown
220
+ ## Goal
221
+ [What the user is trying to accomplish]
222
+
223
+ ## Constraints & Preferences
224
+ - [Requirements mentioned by user]
225
+
226
+ ## Progress
227
+ ### Done
228
+ - [x] [Completed tasks]
229
+
230
+ ### In Progress
231
+ - [ ] [Current work]
232
+
233
+ ### Blocked
234
+ - [Issues, if any]
235
+
236
+ ## Key Decisions
237
+ - **[Decision]**: [Rationale]
238
+
239
+ ## Next Steps
240
+ 1. [What should happen next]
241
+
242
+ ## Critical Context
243
+ - [Data needed to continue]
244
+
245
+ <read-files>
246
+ path/to/file1.ts
247
+ path/to/file2.ts
248
+ </read-files>
249
+
250
+ <modified-files>
251
+ path/to/changed.ts
252
+ </modified-files>
253
+ ```
254
+
255
+ ### Message Serialization
256
+
257
+ Before summarization, messages are serialized to text via [`serializeConversation()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/utils.ts):
258
+
259
+ ```
260
+ [User]: What they said
261
+ [Assistant thinking]: Internal reasoning
262
+ [Assistant]: Response text
263
+ [Assistant tool calls]: read(path="foo.ts"); edit(path="bar.ts", ...)
264
+ [Tool result]: Output from tool
265
+ ```
266
+
267
+ This prevents the model from treating it as a conversation to continue.
268
+
269
+ Tool results are truncated to 2000 characters during serialization. Content beyond that limit is replaced with a marker indicating how many characters were truncated. This keeps summarization requests within reasonable token budgets, since tool results (especially from `read` and `bash`) are typically the largest contributors to context size.
270
+
271
+ ## Custom Summarization via Extensions
272
+
273
+ Extensions can intercept and customize both compaction and branch summarization. See [`extensions/types.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/extensions/types.ts) for event type definitions.
274
+
275
+ ### session_before_compact
276
+
277
+ Fired before auto-compaction or `/compact`. Can cancel or provide custom summary. See `SessionBeforeCompactEvent` and `CompactionPreparation` in the types file.
278
+
279
+ ```typescript
280
+ pi.on("session_before_compact", async (event, ctx) => {
281
+ const { preparation, branchEntries, customInstructions, reason, willRetry, signal } = event;
282
+
283
+ // preparation.messagesToSummarize - messages to summarize
284
+ // preparation.turnPrefixMessages - split turn prefix (if isSplitTurn)
285
+ // preparation.previousSummary - previous compaction summary
286
+ // preparation.fileOps - extracted file operations
287
+ // preparation.tokensBefore - context tokens before compaction
288
+ // preparation.firstKeptEntryId - where kept messages start
289
+ // preparation.settings - compaction settings
290
+
291
+ // branchEntries - all entries on current branch (for custom state)
292
+ // reason - "manual" (/compact), "threshold", or "overflow"
293
+ // willRetry - whether the aborted turn is retried after compaction (overflow recovery)
294
+ // signal - AbortSignal (pass to LLM calls)
295
+
296
+ // Cancel:
297
+ return { cancel: true };
298
+
299
+ // Custom summary:
300
+ return {
301
+ compaction: {
302
+ summary: "Your summary...",
303
+ firstKeptEntryId: preparation.firstKeptEntryId,
304
+ tokensBefore: preparation.tokensBefore,
305
+ // usage: summaryResponse.usage, // Optional; included in session totals
306
+ details: { /* custom data */ },
307
+ }
308
+ };
309
+ });
310
+ ```
311
+
312
+ #### Converting Messages to Text
313
+
314
+ To generate a summary with your own model, convert messages to text using `serializeConversation`:
315
+
316
+ ```typescript
317
+ import { convertToLlm, serializeConversation } from "@astralyn/pi";
318
+
319
+ pi.on("session_before_compact", async (event, ctx) => {
320
+ const { preparation } = event;
321
+
322
+ // Convert AgentMessage[] to Message[], then serialize to text
323
+ const conversationText = serializeConversation(
324
+ convertToLlm(preparation.messagesToSummarize)
325
+ );
326
+ // Returns:
327
+ // [User]: message text
328
+ // [Assistant thinking]: thinking content
329
+ // [Assistant]: response text
330
+ // [Assistant tool calls]: read(path="..."); bash(command="...")
331
+ // [Tool result]: output text
332
+
333
+ // Now send to your model for summarization
334
+ const { summary, usage } = await myModel.summarize(conversationText);
335
+
336
+ return {
337
+ compaction: {
338
+ summary,
339
+ firstKeptEntryId: preparation.firstKeptEntryId,
340
+ tokensBefore: preparation.tokensBefore,
341
+ usage,
342
+ }
343
+ };
344
+ });
345
+ ```
346
+
347
+ See [custom-compaction.ts](../examples/extensions/custom-compaction.ts) for a complete example using a different model.
348
+
349
+ ### session_before_tree
350
+
351
+ Fired before `/tree` navigation. Always fires regardless of whether user chose to summarize. Can cancel navigation or provide custom summary.
352
+
353
+ ```typescript
354
+ pi.on("session_before_tree", async (event, ctx) => {
355
+ const { preparation, signal } = event;
356
+
357
+ // preparation.targetId - where we're navigating to
358
+ // preparation.oldLeafId - current position (being abandoned)
359
+ // preparation.commonAncestorId - shared ancestor
360
+ // preparation.entriesToSummarize - entries that would be summarized
361
+ // preparation.userWantsSummary - whether user chose to summarize
362
+
363
+ // Cancel navigation entirely:
364
+ return { cancel: true };
365
+
366
+ // Provide custom summary (only used if userWantsSummary is true):
367
+ if (preparation.userWantsSummary) {
368
+ return {
369
+ summary: {
370
+ summary: "Your summary...",
371
+ // usage: summaryResponse.usage, // Optional; included in session totals
372
+ details: { /* custom data */ },
373
+ }
374
+ };
375
+ }
376
+ });
377
+ ```
378
+
379
+ See `SessionBeforeTreeEvent` and `TreePreparation` in the types file.
380
+
381
+ ## Settings
382
+
383
+ Configure compaction in `~/.pi/agent/settings.json` or `<project-dir>/.pi/settings.json`:
384
+
385
+ ```json
386
+ {
387
+ "compaction": {
388
+ "enabled": true,
389
+ "reserveTokens": 16384,
390
+ "keepRecentTokens": 20000
391
+ }
392
+ }
393
+ ```
394
+
395
+ | Setting | Default | Description |
396
+ |---------|---------|-------------|
397
+ | `enabled` | `true` | Enable auto-compaction |
398
+ | `reserveTokens` | `16384` | Tokens to reserve for LLM response |
399
+ | `keepRecentTokens` | `20000` | Recent tokens to keep (not summarized) |
400
+
401
+ Disable auto-compaction with `"enabled": false`. You can still compact manually with `/compact`.