@foliox/transparent-compact-pi 0.13.1 → 0.13.3
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.
- package/CHANGELOG.md +8 -0
- package/README.md +79 -64
- package/extensions/index.ts +42 -152
- package/extensions/lib/config.ts +136 -0
- package/extensions/lib/main-agent-lookup.ts +2 -3
- package/extensions/lib/settings-menu.ts +342 -0
- package/extensions/lib/turn-context.ts +30 -1
- package/extensions/lib/turn-filter.ts +0 -6
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.13.2
|
|
4
|
+
|
|
5
|
+
- Add `/compact-settings` with session/project/global saves and a scoped-model
|
|
6
|
+
picker, replacing `/compaction-method` and `/cap-compaction`.
|
|
7
|
+
- Support Pi settings-file defaults alongside environment overrides.
|
|
8
|
+
- Fixed `/fl` turns, the now automatically prune during both manual and automatic
|
|
9
|
+
verbatim compaction once outside the retained tail. remove `/filter-auto`.
|
|
10
|
+
|
|
3
11
|
## 0.13.0
|
|
4
12
|
|
|
5
13
|
- Add `context_expand` to recover the original call and matched result behind a
|
package/README.md
CHANGED
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
Context compaction and pruning for [Pi](https://pi.dev/) that keeps conversation text verbatim instead of replacing it with a model-generated summary or truncation. It removes thinking and most tool output from the active context, while keeping user messages, assistant text, algorithmically compacted tool-call stubs and explicitly selected reads.
|
|
4
4
|
|
|
5
|
-
When the agent needs a detail that is no longer in context, it can use retrieval tools to search the recorded session history with a subagent. Compaction itself does not make a model call.
|
|
5
|
+
When the agent needs a detail that is no longer in context, it can use retrieval tools to search the recorded session history with a subagent (no extra extension required). Compaction itself does not make a model call.
|
|
6
6
|
|
|
7
7
|
The user can also [selectively manipulate which turns to hold in the current context](#filter-turns) in higher or lower fidelity, and [specify file reads to be retained in the context in full](#retain-reads), (e.g. a spec or plan).
|
|
8
8
|
|
|
9
9
|
This extension is aimed at addressing two main issues that other compaction techniques face, which are especially exacerbated in agents running on lightweight and local LLMs:
|
|
10
10
|
- Model summaries such as Pi's default method can lead to degradation and confabulation of details that can cause confident blunders.
|
|
11
|
-
-
|
|
11
|
+
- Mechanical compression (i.e. no model call) + retrieval systems like `pi-vcc` can be effective when the agent knows what to look for, but omitting session structure from the retained context can make the actual use of retrieval less reliable.
|
|
12
12
|
|
|
13
|
-
`transparent-compact` is also a retrieval
|
|
13
|
+
`transparent-compact` is also a mechanical compression + retrieval system, but its design keeps manipulation of conversation text to a minimum and maximises the agent's awareness of its own compacted state, with the aim of avoiding confabulation and encouraging accurate retrieval of historical details. [This study](https://arxiv.org/abs/2610.20116) found that a minimal approach outperformed more complex techniques with lightweight models and was at least as effective with frontier models.
|
|
14
14
|
|
|
15
15
|
The verbatim compaction system plays particularly nicely with manual pruning of the context. This allows you to decide which parts of the session remain important to the current work, without having to commit to a particular branching point with /tree or decide at the time of the prompt with something like claude's /btw.
|
|
16
16
|
|
|
@@ -29,7 +29,7 @@ pi install git:github.com/felixwoolford/transparent-compact-pi
|
|
|
29
29
|
pi install /absolute/path/to/transparent-compact
|
|
30
30
|
```
|
|
31
31
|
|
|
32
|
-
Once loaded, the extension uses verbatim compaction by default. Pi's automatic compaction continues to work, using the extension's configured method; to compact manually, enter:
|
|
32
|
+
Once loaded, the extension uses verbatim mechanical compaction by default. Pi's automatic compaction triggering continues to work, using the extension's configured method; to compact manually, enter:
|
|
33
33
|
|
|
34
34
|
```text
|
|
35
35
|
/compact
|
|
@@ -60,9 +60,9 @@ Each selection covers a user message and all following activity up to the next u
|
|
|
60
60
|
|
|
61
61
|
Navigate with **↑/↓**; use **←/→** to collapse or expand details. Press **Space** to prune a turn or restore it to PROSE, or **f** to cycle through all four modes. Press **Enter** to review changes, then **Enter** again to save; **Esc** goes back or cancels. The editor shows an estimated context size as you choose.
|
|
62
62
|
|
|
63
|
-
You can restore filtered turns later. Choices persist in the current session branch through later verbatim compactions and reloads. Turns overlapping Pi's retained recent history are locked until they can be filtered as a whole
|
|
63
|
+
You can restore filtered turns later. Choices persist in the current session branch through later verbatim compactions and reloads. Turns overlapping Pi's retained recent history are locked until they can be filtered as a whole.
|
|
64
64
|
|
|
65
|
-
PROSE+TOOLS and FULL can use substantial context.
|
|
65
|
+
PROSE+TOOLS and FULL can use substantial context. FULL includes only what was recorded; provider and model limitations can still affect thinking and images.
|
|
66
66
|
|
|
67
67
|
### Manual context editing and caching
|
|
68
68
|
Manual context edits typically reduce prompt-cache reuse for the next model request, so frequent edits of the retained reads or turn filters are discouraged, and the best time to adjust them is just after compaction, before the next request.
|
|
@@ -73,14 +73,15 @@ Treat filtering/pruning/read-retention as useful tools when the situation calls
|
|
|
73
73
|
### Flag an aside
|
|
74
74
|
|
|
75
75
|
```text
|
|
76
|
-
/filter-later <message> # send a turn and flag it for
|
|
76
|
+
/filter-later <message> # send a turn and flag it for pruning
|
|
77
77
|
/fl <message> # short alias
|
|
78
|
-
/filter-auto # show automatic filtering policy
|
|
79
|
-
/filter-auto on # apply flags during automatic compaction
|
|
80
|
-
/filter-auto off # stop automatically applying new flags
|
|
81
78
|
```
|
|
82
79
|
|
|
83
|
-
|
|
80
|
+
Flagged turns are automatically pruned during manual or automatic verbatim compaction once they are fully outside the retained recent history. Until then, they remain in context and are locked in the filtering editor.
|
|
81
|
+
|
|
82
|
+
Use `/filter-turns` to keep or restore a flagged turn. Manually restored turns stay restored.
|
|
83
|
+
|
|
84
|
+
`/fl` sends a normal conversation turn, not an isolated aside.
|
|
84
85
|
|
|
85
86
|
## Retain reads
|
|
86
87
|
|
|
@@ -90,7 +91,7 @@ Consecutive partial reads of the same file with connected ranges form one select
|
|
|
90
91
|
|
|
91
92
|
Retained outputs are historical snapshots of the read tool output, not current file contents.
|
|
92
93
|
|
|
93
|
-
### Automatic
|
|
94
|
+
### Automatic read retention
|
|
94
95
|
|
|
95
96
|
Nothing is retained automatically, but files can be declared for retention in `AGENTS.md` or `CLAUDE.md` like so:
|
|
96
97
|
|
|
@@ -103,91 +104,105 @@ latest: docs/WORKING-NOTES.md
|
|
|
103
104
|
|
|
104
105
|
Use one literal path per line, relative to the instruction file. Plain paths default to FIRST; `latest:` selects the latest read. These declarations do not read files themselves. Manual choices override the defaults.
|
|
105
106
|
|
|
106
|
-
## Control compaction
|
|
107
107
|
|
|
108
|
-
|
|
108
|
+
## Settings menu and configuration
|
|
109
109
|
|
|
110
|
-
|
|
110
|
+
Optionally, open `/compact-settings` while the agent is idle to configure compaction, checkpoint size limits, lookup models and recovery.
|
|
111
111
|
|
|
112
|
-
|
|
112
|
+
Use **↑/↓** to navigate and **Space** or **e** to edit. Press **d** to restore a setting's built-in default. A `*` marks pending edits.
|
|
113
113
|
|
|
114
|
-
|
|
114
|
+
Press **Enter** to review, then choose where to apply your changes:
|
|
115
115
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
/compaction-method summary # Pi's built-in summary compaction
|
|
120
|
-
```
|
|
116
|
+
- **Session:** use them in the current session branch.
|
|
117
|
+
- **Project:** also save defaults in `.pi/settings.json`.
|
|
118
|
+
- **Global:** also save defaults in `~/.pi/agent/settings.json`.
|
|
121
119
|
|
|
122
|
-
|
|
120
|
+
Press **Enter** again to confirm, or **Esc** to go back or cancel. Session choices survive compaction and resume.
|
|
123
121
|
|
|
124
|
-
###
|
|
122
|
+
### Compaction method
|
|
125
123
|
|
|
126
|
-
|
|
127
|
-
If you regularly reach the cap, consider starting a new session or using a different compaction method that is more suited to your workflow.
|
|
124
|
+
**Verbatim** is the default and enables transparent-compact's compaction and context pruning.
|
|
128
125
|
|
|
126
|
+
**Summary** uses Pi's original model-generated compaction instead, effectively disabling transparent-compact's compaction and pruning features. Use this if you just want to use model summary with the `context_lookup` tool. Note that the agent may use the tool less effectively in this mode.
|
|
129
127
|
|
|
130
|
-
|
|
131
|
-
/cap-compaction # show mode and budget
|
|
132
|
-
/cap-compaction warn # prompt before trimming (default)
|
|
133
|
-
/cap-compaction on # trim without prompting
|
|
134
|
-
/cap-compaction off # disable cap-based trimming
|
|
135
|
-
/cap-compaction warn 20000t # estimated token budget
|
|
136
|
-
/cap-compaction warn 25% # percentage of model context window
|
|
137
|
-
/cap-compaction on 80000c # character budget
|
|
138
|
-
/cap-compaction 40000c # change budget without changing mode
|
|
139
|
-
```
|
|
128
|
+
### Checkpoint size cap
|
|
140
129
|
|
|
141
|
-
|
|
130
|
+
By default, the extension warns before trimming a checkpoint that exceeds an estimated **25% of the model's context window**.
|
|
142
131
|
|
|
143
|
-
|
|
132
|
+
Choose a cap mode:
|
|
144
133
|
|
|
145
|
-
|
|
134
|
+
- **warn:** ask before trimming.
|
|
135
|
+
- **on:** trim without prompting.
|
|
136
|
+
- **off:** disable cap-based trimming.
|
|
146
137
|
|
|
147
|
-
|
|
138
|
+
And enter a budget such as `25%`, `20000t` for estimated tokens, or `80000c` for characters.
|
|
148
139
|
|
|
149
|
-
|
|
150
|
-
| --- | --- | --- |
|
|
151
|
-
| `MECH_COMPACT_MAX_SUMMARY_PERCENT` | `25` | Initial cap as a percentage of the model's context window (greater than 0, up to 100). |
|
|
152
|
-
| `MECH_COMPACT_MAX_SUMMARY_CHARS` | Unset | Initial fixed character budget; overrides the percentage. |
|
|
153
|
-
| `MECH_COMPACT_LOOKUP_MODEL` | Session model | Lookup model as `provider/modelId`; it must be available in Pi and support tool calls. An unresolved model falls back to the session model. |
|
|
154
|
-
| `MECH_COMPACT_LOOKUP_TURNS` | `25` | Maximum substantive search turns per lookup. |
|
|
155
|
-
| `MECH_COMPACT_LOOKUP_MAX_CALLS` | `3` | Maximum consecutive lookup attempts; `0` means unlimited. |
|
|
156
|
-
| `MECH_COMPACT_LOOKUP_SESSION_FILE` | Unset | Absolute path to a full session JSONL to search instead of the current branch, for harnesses using pruned forks. Leave unset for ordinary use. |
|
|
157
|
-
| `MECH_COMPACT_MAIN_AGENT_LOOKUP` | Unset | `1` opts into direct recovery; `0` overrides the file setting for sessions without a recorded choice. |
|
|
140
|
+
Trimming progressively reduces tool stubs before truncating assistant prose and, finally, user prose. Some content, including retained reads, is not trimmed. The cap applies only to verbatim checkpoints, not the whole model context; disabling it can leave too much context for the model.
|
|
158
141
|
|
|
159
|
-
For
|
|
142
|
+
For unattended use, choose **on**. Without an interactive UI, **warn** emits a warning and applies the cap.
|
|
160
143
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
```
|
|
144
|
+
### Lookup and recovery
|
|
145
|
+
|
|
146
|
+
By default, a subagent searches recorded history using the session model. The **Lookup model** picker offers Pi's scoped models—or all available models if no scope is configured. Search by model ID, provider or name, or choose **Use session model**.
|
|
165
147
|
|
|
166
|
-
|
|
148
|
+
**Lookup search turns** limits each search. **Consecutive lookups** limits consecutive retrieval attempts; `0` means unlimited.
|
|
167
149
|
|
|
168
|
-
|
|
150
|
+
**Direct recovery is experimental.** It lets the main agent search and read history itself, avoiding a separate model call but putting retrieved pages into the main context. The lookup-model and subagent search limits do not apply.
|
|
169
151
|
|
|
170
|
-
|
|
152
|
+
Choose recovery mode before the first compaction. Once direct recovery is enabled, or the session has compacted, the menu can only save recovery-mode defaults for new sessions.
|
|
153
|
+
|
|
154
|
+
### Settings files
|
|
155
|
+
|
|
156
|
+
If you save globally or locally the settings save to Pi's `~/.pi/agent/settings.json` or `.pi/settings.json`, e.g.:
|
|
171
157
|
|
|
172
158
|
```json
|
|
173
159
|
{
|
|
174
160
|
"transparentCompact": {
|
|
175
|
-
"
|
|
161
|
+
"maxSummaryPercent": 30,
|
|
162
|
+
"lookupMaxCalls": 5
|
|
176
163
|
}
|
|
177
164
|
}
|
|
178
165
|
```
|
|
179
166
|
|
|
180
|
-
|
|
167
|
+
| Key | Default | Values or purpose |
|
|
168
|
+
| --- | --- | --- |
|
|
169
|
+
| `compactionMethod` | `"verbatim"` | `"verbatim"` or `"summary"` |
|
|
170
|
+
| `capMode` | `"warn"` | `"warn"`, `"on"` or `"off"` |
|
|
171
|
+
| `maxSummaryPercent` | `25` | Cap as a percentage of the model's context window |
|
|
172
|
+
| `maxSummaryChars` | Unset | Fixed character cap; takes precedence over the percentage |
|
|
173
|
+
| `lookupModel` | Session model | `provider/modelId`; must support tool calls |
|
|
174
|
+
| `lookupTurns` | `25` | Maximum substantive search turns per lookup |
|
|
175
|
+
| `lookupMaxCalls` | `3` | Maximum consecutive lookup attempts; `0` means unlimited |
|
|
176
|
+
| `mainAgentLookup` | `false` | `true` enables experimental direct recovery |
|
|
177
|
+
|
|
178
|
+
Project settings override global settings. Environment overrides take precedence over files; recorded session choices take precedence over both.
|
|
179
|
+
|
|
180
|
+
### Environment overrides
|
|
181
|
+
|
|
182
|
+
For individual launches or automation:
|
|
181
183
|
|
|
182
|
-
|
|
184
|
+
| Variable | Corresponding setting |
|
|
185
|
+
| --- | --- |
|
|
186
|
+
| `MECH_COMPACT_MAX_SUMMARY_PERCENT` | `maxSummaryPercent` |
|
|
187
|
+
| `MECH_COMPACT_MAX_SUMMARY_CHARS` | `maxSummaryChars` |
|
|
188
|
+
| `MECH_COMPACT_LOOKUP_MODEL` | `lookupModel` |
|
|
189
|
+
| `MECH_COMPACT_LOOKUP_TURNS` | `lookupTurns` |
|
|
190
|
+
| `MECH_COMPACT_LOOKUP_MAX_CALLS` | `lookupMaxCalls` |
|
|
191
|
+
| `MECH_COMPACT_MAIN_AGENT_LOOKUP` | `mainAgentLookup`: `1` enables, `0` disables |
|
|
192
|
+
|
|
193
|
+
`MECH_COMPACT_LOOKUP_SESSION_FILE` optionally supplies an absolute session JSONL path for history retrieval instead of the current branch. Leave it unset for ordinary use.
|
|
194
|
+
|
|
195
|
+
## Other stuff
|
|
196
|
+
### Export the checkpoint
|
|
197
|
+
|
|
198
|
+
For debugging, use `/export-checkpoint [path]` to save the current checkpoint as plain text. Without a path, it writes `pi-checkpoint-<session-id>.txt` in the working directory; quote paths containing spaces.
|
|
183
199
|
|
|
184
|
-
|
|
185
|
-
This is a second-class operational mode and has not been tested in practice as much as the subagent lookup.
|
|
200
|
+
This exports the saved text, including confirmed filtering and read-retention edits, without rebuilding or changing context. Recent messages and separately reinserted PROSE+TOOLS/FULL messages are not included.
|
|
186
201
|
|
|
187
|
-
### Local inference
|
|
202
|
+
### Local inference suggestion
|
|
188
203
|
|
|
189
204
|
Lookups using the session model can disrupt the main session's prompt cache. For a single-slot llama.cpp server (`-np 1`), enable `--cache-ram <MiB>` with enough host memory for the main session state. On other engines, use prefix caching, KV offloading, or sufficient parallel capacity to keep both sessions resident.
|
|
190
205
|
|
|
191
|
-
|
|
206
|
+
### License
|
|
192
207
|
|
|
193
208
|
[MIT](LICENSE).
|
package/extensions/index.ts
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
* this history under ~/.pi/agent/sessions/; custom session locations and
|
|
8
8
|
* ephemeral sessions work too. Only the active branch is searched.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
10
|
+
* Preferences: transparentCompact in Pi settings.json (read via pi.getSettings()).
|
|
11
|
+
* Optional environment overrides:
|
|
11
12
|
* MECH_COMPACT_MAX_SUMMARY_CHARS initial character budget override (takes precedence over percent)
|
|
12
13
|
* MECH_COMPACT_MAX_SUMMARY_PERCENT initial percentage of model context (default 25; >0, <=100)
|
|
13
14
|
* MECH_COMPACT_LOOKUP_MODEL "provider/modelId" for the lookup subagent
|
|
@@ -34,19 +35,22 @@ import { buildSessionProjection, SessionManager } from "@earendil-works/pi-codin
|
|
|
34
35
|
import type { ExtensionAPI, ExtensionContext, ModelRegistry, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
35
36
|
import { capSpans, renderToolLine, renderToolStub, NORMAL_PREVIEW_CHARS, TIGHTENED_ATTR } from "./lib/checkpoint-cap.js";
|
|
36
37
|
import { recoveryText, startMainAgentLookup } from "./lib/main-agent-lookup.js";
|
|
38
|
+
import { CAP_ENTRY, parseCapBudget, capBudgetText, sessionPreferences } from "./lib/config.js";
|
|
39
|
+
import type { CapBudget, CapMode } from "./lib/config.js";
|
|
40
|
+
import { registerSettingsMenu } from "./lib/settings-menu.js";
|
|
37
41
|
import { expandTargets, expansionDigest, formatExpansionResult, pairedToolResults } from "./lib/context-expansion.js";
|
|
38
42
|
import type { ExpansionAnchor, ExpansionQuery, ExpansionResult, ExpansionTarget } from "./lib/context-expansion.js";
|
|
39
43
|
import { ToolRenderer, TOOL_DISPLAY_EXPLANATION } from "./lib/tool-stubs/renderer.mjs";
|
|
40
44
|
import { checkpointPath } from "./lib/tool-stubs/display.mjs";
|
|
41
45
|
import { Locations } from "./lib/tool-stubs/locations.mjs";
|
|
42
46
|
import type { ToolLines, ToolStub } from "./lib/checkpoint-cap.js";
|
|
43
|
-
import { FILTER_EXPLANATION, PREFLAG_ENTRY,
|
|
47
|
+
import { FILTER_EXPLANATION, PREFLAG_ENTRY, FILTER_REVISION_ENTRY, preflaggedTurns,
|
|
44
48
|
filterSpans, pickFilteredTurns, turnOwners } from "./lib/turn-filter.js";
|
|
45
49
|
import type { FilterTurn, TurnSpan, ReadPosition } from "./lib/turn-filter.js";
|
|
46
50
|
import { readPath as fileEvidenceKey, readCatalog, readRetentionState, selectedReads, renderRetainedReads, retainedReadOutputs, retainReadSpans, READ_RETENTION_ENTRY } from "./lib/read-retention.js";
|
|
47
51
|
import type { ReadOutput, ReadRetention } from "./lib/read-retention.js";
|
|
48
52
|
import { pickRetainedReads } from "./lib/read-retention-ui.js";
|
|
49
|
-
import { FIDELITY_EXPLANATION, fidelityMessages, fidelitySpans, locateSlots, expandCheckpoint,
|
|
53
|
+
import { CHECKPOINT_EXPLANATION, RECOVERY_HISTORY_NOTE, FIDELITY_EXPLANATION, fidelityMessages, fidelitySpans, locateSlots, expandCheckpoint, frameCheckpoint,
|
|
50
54
|
messageTokens, previewMessages, checkCheckpointBudget, checkContextBudget, isExpandedCheckpoint, checkpointContextMessages, retainedTailMessages, estimateContext } from "./lib/turn-context.js";
|
|
51
55
|
import type { ContextEstimate, NoticeTokens, TurnFidelities, TurnSelection, TurnSlot } from "./lib/turn-context.js";
|
|
52
56
|
|
|
@@ -55,49 +59,11 @@ import type { ContextEstimate, NoticeTokens, TurnFidelities, TurnSelection, Turn
|
|
|
55
59
|
// ============================================================================
|
|
56
60
|
|
|
57
61
|
const MECH_KIND = "mech-compact";
|
|
58
|
-
const
|
|
59
|
-
type CompactionMethod = "verbatim" | "summary";
|
|
60
|
-
|
|
61
|
-
const SUMMARY_COMPACTION_WARNING = "Applying summary compaction weakens the verbatim guarantee. You may switch back to verbatim compaction before summary compaction runs to leave the guarantee unchanged. If summary compaction runs (manually or automatically), it replaces older active context with a model-generated summary, which may omit or reinterpret details. Switching back afterward does not undo this: only subsequent verbatim spans retain the guarantee. Original history remains recoverable through context_lookup, but is no longer a direct expansion of the active context.";
|
|
62
|
+
const SUMMARY_COMPACTION_WARNING = "Summary uses Pi's original model-generated compaction, effectively disabling transparent-compact's compaction features. It is incompatible with context pruning and provides no verbatim guarantee for summarized content. context_lookup remains available, but may be used less effectively. Switching back before summary compaction runs preserves the existing verbatim context. Switching back afterward does not undo summarization: only subsequent verbatim spans retain the guarantee.";
|
|
62
63
|
const MIXED_CONTEXT_WARNING = "**Mixed context: earlier material is model-summarized, not verbatim.** The verbatim guarantee applies only to the labelled verbatim spans and uncompacted tail. The model-summary base may omit or reinterpret details; use `context_lookup` to recover original history.";
|
|
63
64
|
|
|
64
|
-
//
|
|
65
|
-
// and tree navigation all inherit only the choices on their own path.
|
|
66
|
-
function compactionMethod(entries: SessionEntry[]): CompactionMethod {
|
|
67
|
-
for (let i = entries.length - 1; i >= 0; i--) {
|
|
68
|
-
const entry = entries[i];
|
|
69
|
-
if (entry.type !== "custom" || entry.customType !== METHOD_ENTRY) continue;
|
|
70
|
-
const method = (entry.data as { method?: unknown } | undefined)?.method;
|
|
71
|
-
if (method === "verbatim" || method === "summary") return method;
|
|
72
|
-
}
|
|
73
|
-
return "verbatim";
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function intFromEnv(name: string, fallback: number): number {
|
|
77
|
-
const raw = process.env[name];
|
|
78
|
-
if (!raw) return fallback;
|
|
79
|
-
const n = Number.parseInt(raw, 10);
|
|
80
|
-
return Number.isFinite(n) && n > 0 ? n : fallback;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function percentFromEnv(name: string, fallback: number): number {
|
|
84
|
-
const n = Number(process.env[name]);
|
|
85
|
-
return Number.isFinite(n) && n > 0 && n <= 100 ? n : fallback;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
function lookupMaxCallsFromEnv(): number {
|
|
89
|
-
const raw = process.env.MECH_COMPACT_LOOKUP_MAX_CALLS?.trim();
|
|
90
|
-
const n = raw && /^\d+$/.test(raw) ? Number(raw) : NaN;
|
|
91
|
-
return Number.isSafeInteger(n) && n >= 0 ? n : 3;
|
|
92
|
-
}
|
|
93
|
-
|
|
65
|
+
// Internal output limits, not user preferences.
|
|
94
66
|
const cfg = {
|
|
95
|
-
defaultCapBudget: (process.env.MECH_COMPACT_MAX_SUMMARY_CHARS
|
|
96
|
-
? { unit: "chars", value: intFromEnv("MECH_COMPACT_MAX_SUMMARY_CHARS", 80_000) }
|
|
97
|
-
: { unit: "percent", value: percentFromEnv("MECH_COMPACT_MAX_SUMMARY_PERCENT", 25) }) as CapBudget,
|
|
98
|
-
lookupTurns: intFromEnv("MECH_COMPACT_LOOKUP_TURNS", 25),
|
|
99
|
-
lookupMaxCalls: lookupMaxCallsFromEnv(),
|
|
100
|
-
lookupModel: process.env.MECH_COMPACT_LOOKUP_MODEL?.trim() || undefined,
|
|
101
67
|
argSnippetChars: NORMAL_PREVIEW_CHARS,
|
|
102
68
|
listMaxChars: 12_000,
|
|
103
69
|
grepMaxChars: 12_000,
|
|
@@ -106,38 +72,11 @@ const cfg = {
|
|
|
106
72
|
};
|
|
107
73
|
|
|
108
74
|
// Cap policy is session/branch state, separate from the compaction method.
|
|
109
|
-
const CAP_ENTRY = "transparent-compact:cap-compaction";
|
|
110
|
-
type CapMode = "on" | "off" | "warn";
|
|
111
|
-
interface CapBudget { unit: "chars" | "tokens" | "percent"; value: number }
|
|
112
75
|
interface CapSettings { mode: CapMode; budget: CapBudget }
|
|
113
76
|
|
|
114
|
-
function
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
if (typeof n !== "number" || !Number.isFinite(n) || n <= 0) return false;
|
|
118
|
-
if (unit === "percent") return n <= 100;
|
|
119
|
-
return Number.isSafeInteger(n) && (unit === "chars" || (unit === "tokens" && n <= Number.MAX_SAFE_INTEGER / 4));
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function parseCapBudget(text: string): CapBudget | undefined {
|
|
123
|
-
const match = /^(\d+(?:\.\d+)?)(c|t|%)$/.exec(text);
|
|
124
|
-
if (!match) return;
|
|
125
|
-
const budget: CapBudget = { value: Number(match[1]), unit: match[2] === "c" ? "chars" : match[2] === "t" ? "tokens" : "percent" };
|
|
126
|
-
return validCapBudget(budget) ? budget : undefined;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
function capSettings(entries: SessionEntry[]): CapSettings {
|
|
130
|
-
for (let i = entries.length - 1; i >= 0; i--) {
|
|
131
|
-
const entry = entries[i];
|
|
132
|
-
if (entry.type !== "custom" || entry.customType !== CAP_ENTRY) continue;
|
|
133
|
-
const state = entry.data as CapSettings | undefined;
|
|
134
|
-
if (state && ["on", "off", "warn"].includes(state.mode) && validCapBudget(state.budget)) return state;
|
|
135
|
-
}
|
|
136
|
-
return { mode: "warn", budget: { ...cfg.defaultCapBudget } };
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
function capBudgetText(budget: CapBudget): string {
|
|
140
|
-
return `${budget.value}${budget.unit === "chars" ? "c" : budget.unit === "tokens" ? "t" : "%"}`;
|
|
77
|
+
function capSettings(entries: SessionEntry[], settings: unknown): CapSettings {
|
|
78
|
+
const values = sessionPreferences(settings, entries);
|
|
79
|
+
return { mode: values.capMode, budget: values.capBudget };
|
|
141
80
|
}
|
|
142
81
|
|
|
143
82
|
function capBudgetChars(budget: CapBudget, contextWindow?: number): number | undefined {
|
|
@@ -148,7 +87,7 @@ function capBudgetChars(budget: CapBudget, contextWindow?: number): number | und
|
|
|
148
87
|
return tokens <= Number.MAX_SAFE_INTEGER / 4 ? tokens * 4 : undefined;
|
|
149
88
|
}
|
|
150
89
|
|
|
151
|
-
function capDescription(state: CapSettings, contextWindow?: number): string {
|
|
90
|
+
export function capDescription(state: CapSettings, contextWindow?: number): string {
|
|
152
91
|
const chars = capBudgetChars(state.budget, contextWindow);
|
|
153
92
|
const resolved = chars === undefined ? "model context window unavailable" : state.budget.unit === "chars"
|
|
154
93
|
? `${chars.toLocaleString()} chars`
|
|
@@ -165,7 +104,7 @@ function persistCap(pi: ExtensionAPI, previous: CapSettings, next: CapSettings):
|
|
|
165
104
|
async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal: AbortSignal | undefined,
|
|
166
105
|
reason: string, size: { overhead: number; lineChars: number }, operation = "compaction"): Promise<number | undefined | null> {
|
|
167
106
|
try {
|
|
168
|
-
let state = capSettings(ctx.sessionManager.getBranch());
|
|
107
|
+
let state = capSettings(ctx.sessionManager.getBranch(), pi.getSettings());
|
|
169
108
|
for (;;) {
|
|
170
109
|
if (signal?.aborted) return null;
|
|
171
110
|
if (state.mode === "off") return undefined;
|
|
@@ -840,7 +779,6 @@ function checkpointEvidence(entries: SessionEntry[], firstKeptEntryId: string, c
|
|
|
840
779
|
};
|
|
841
780
|
}
|
|
842
781
|
|
|
843
|
-
const RECOVERY_HISTORY_NOTE = "Compaction hides earlier details from your current view. The original conversation history, including recorded tool outputs and your reasoning, is preserved in the session and can be retrieved.";
|
|
844
782
|
const RECOVERY_SOURCE_GUIDANCE = "Re-read project files for their current contents. Prefer lookup for what was observed earlier or to avoid repeating slow external research or expensive computations; cheap local rereads and recomputations remain reasonable.";
|
|
845
783
|
const RECOVERY_SCOPE_RULE = "Use the recovery tools for history established by this conversation or its checkpoint, not project discovery, requirements never supplied, other sessions, or abandoned branches.";
|
|
846
784
|
|
|
@@ -850,7 +788,6 @@ const REORIENT_BLOCK = `**Post-compaction re-orientation.** ${RECOVERY_HISTORY_N
|
|
|
850
788
|
3. **Distinguish earlier claims from supporting evidence.** Retained assistant prose records what was said, not independent verification. If a task-relevant claim has uncertain provenance or conflicts with new evidence, check its supporting output (using \`context_lookup\` if hidden) or the current source before treating it as established; label unresolved claims unverified. Retrieved reasoning remains a historical hypothesis, and historical outputs do not establish current file or build/test state.`;
|
|
851
789
|
|
|
852
790
|
const REVISION_NOTE_PREFIX = "- Checkpoint context revised: ";
|
|
853
|
-
const CHECKPOINT_EXPLANATION = `**Compacted conversation follows.** The earlier part of this conversation has been compacted into the checkpoint below. This is not the full transcript. ${RECOVERY_HISTORY_NOTE}`;
|
|
854
791
|
|
|
855
792
|
const RECOVERY_INSTRUCTIONS = `**Recovering hidden details.** Use \`context_lookup\` with a specific historical question: a subagent searches this conversation's full session history and returns relevant findings.`;
|
|
856
793
|
|
|
@@ -1354,6 +1291,7 @@ async function runLookupSubagent(opts: {
|
|
|
1354
1291
|
transcripts: Transcript[];
|
|
1355
1292
|
model: Model;
|
|
1356
1293
|
registry: ModelRegistry;
|
|
1294
|
+
lookupTurns: number;
|
|
1357
1295
|
signal: AbortSignal | undefined;
|
|
1358
1296
|
}): Promise<string> {
|
|
1359
1297
|
const toc = truncateHead(listEntries(opts.transcripts).split("\n").slice(0, 60).join("\n"), 4_000);
|
|
@@ -1415,14 +1353,14 @@ async function runLookupSubagent(opts: {
|
|
|
1415
1353
|
const sessionId = uuidv7();
|
|
1416
1354
|
// Continuations do not spend the substantive-search budget, but still cost
|
|
1417
1355
|
// inference. Bound ALL search-phase model calls, plus one final write-up.
|
|
1418
|
-
const maxModelCalls = Math.min(Number.MAX_SAFE_INTEGER,
|
|
1419
|
-
const searchLimit = `${
|
|
1356
|
+
const maxModelCalls = Math.min(Number.MAX_SAFE_INTEGER, opts.lookupTurns * 3);
|
|
1357
|
+
const searchLimit = `${opts.lookupTurns}-turn limit`;
|
|
1420
1358
|
let limit = `${maxModelCalls}-call total limit`;
|
|
1421
1359
|
let searchTurns = 0;
|
|
1422
1360
|
let pagingOnlyNotified = false;
|
|
1423
1361
|
let lastText = "";
|
|
1424
1362
|
for (let turn = 0; turn < maxModelCalls; turn++) {
|
|
1425
|
-
if (searchTurns >=
|
|
1363
|
+
if (searchTurns >= opts.lookupTurns) {
|
|
1426
1364
|
if (continuations.size === 0) { limit = searchLimit; break; }
|
|
1427
1365
|
if (!pagingOnlyNotified) {
|
|
1428
1366
|
messages.push({ role: "user", content: "The substantive search-turn budget is exhausted. Only follow previously issued continuation pages if needed, or answer now. Do not start new searches.", timestamp: Date.now() });
|
|
@@ -1455,7 +1393,7 @@ async function runLookupSubagent(opts: {
|
|
|
1455
1393
|
const keys = toolCalls.map((call) => lookupPageKey(String(call.name), (call.arguments ?? {}) as Record<string, any>));
|
|
1456
1394
|
const continuationOnly = keys.every((key) => key !== undefined && available.delete(key));
|
|
1457
1395
|
if (!continuationOnly) {
|
|
1458
|
-
if (searchTurns >=
|
|
1396
|
+
if (searchTurns >= opts.lookupTurns) { limit = searchLimit; break; }
|
|
1459
1397
|
searchTurns++;
|
|
1460
1398
|
}
|
|
1461
1399
|
// Consume before dispatch, so a sibling cannot consume a newly issued page.
|
|
@@ -1569,6 +1507,14 @@ function consecutiveLookups(ctx: { sessionManager: { getBranch: () => SessionEnt
|
|
|
1569
1507
|
// ============================================================================
|
|
1570
1508
|
|
|
1571
1509
|
export default function (pi: ExtensionAPI) {
|
|
1510
|
+
// Resolve from the active branch; never cache settings across tree navigation.
|
|
1511
|
+
const compactionMethod = (entries: SessionEntry[]) => sessionPreferences(pi.getSettings(), entries).compactionMethod;
|
|
1512
|
+
registerSettingsMenu(pi, (previous, next, ctx) => {
|
|
1513
|
+
if (previous.compactionMethod === next.compactionMethod) return;
|
|
1514
|
+
const entries = ctx.sessionManager.getBranch();
|
|
1515
|
+
if (next.compactionMethod === "summary") ctx.ui.notify(recoveryText(entries, SUMMARY_COMPACTION_WARNING), "warning");
|
|
1516
|
+
else if (collectBaseAndSpans(entries).base?.kind === "model-summary") ctx.ui.notify(recoveryText(entries, MIXED_CONTEXT_WARNING), "warning");
|
|
1517
|
+
});
|
|
1572
1518
|
// Only bridge a specific /filter-later (or /fl) submission to its actual persisted user
|
|
1573
1519
|
// message. The next input clears a failed/handled submission, so it cannot
|
|
1574
1520
|
// accidentally flag a later ordinary prompt. Durable state uses raw entries.
|
|
@@ -1622,7 +1568,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1622
1568
|
pi.on("context_with_system", (event, ctx) => {
|
|
1623
1569
|
const entries = ctx.sessionManager.getBranch();
|
|
1624
1570
|
try {
|
|
1625
|
-
const
|
|
1571
|
+
const projected = projectReorientation(projectCheckpoint(event.messages, entries), entries);
|
|
1572
|
+
const messages = latestVerbatimCompaction(entries) ? frameCheckpoint(projected) : projected;
|
|
1626
1573
|
if (Object.keys(turnFidelities(entries)).length) checkContextBudget(messages, ctx);
|
|
1627
1574
|
if (messages.length !== event.messages.length || messages.some((m, i) => m !== event.messages[i])) return { messages };
|
|
1628
1575
|
} catch (error) {
|
|
@@ -1632,52 +1579,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
1632
1579
|
}
|
|
1633
1580
|
});
|
|
1634
1581
|
|
|
1635
|
-
// Method selection never changes Pi's auto-compaction enabled setting.
|
|
1636
|
-
pi.registerCommand("compaction-method", {
|
|
1637
|
-
description: "Show or set the session compaction method: verbatim|summary (manual and automatic)",
|
|
1638
|
-
getArgumentCompletions: (prefix) => ["verbatim", "summary"]
|
|
1639
|
-
.filter((method) => method.startsWith(prefix))
|
|
1640
|
-
.map((method) => ({ value: method, label: method })),
|
|
1641
|
-
handler: async (args, ctx) => {
|
|
1642
|
-
const requested = args.trim();
|
|
1643
|
-
if (requested && requested !== "verbatim" && requested !== "summary") {
|
|
1644
|
-
ctx.ui.notify("Usage: /compaction-method [verbatim|summary]", "error");
|
|
1645
|
-
return;
|
|
1646
|
-
}
|
|
1647
|
-
const entries = ctx.sessionManager.getBranch();
|
|
1648
|
-
const previous = compactionMethod(entries);
|
|
1649
|
-
const method = requested || previous;
|
|
1650
|
-
const changed = method !== previous;
|
|
1651
|
-
if (changed) pi.appendEntry(METHOD_ENTRY, { method });
|
|
1652
|
-
ctx.ui.notify(`Compaction method: ${method} (manual, automatic, and overflow recovery).`, "info");
|
|
1653
|
-
if (changed && method === "summary") ctx.ui.notify(recoveryText(entries, SUMMARY_COMPACTION_WARNING), "warning");
|
|
1654
|
-
else if (changed && collectBaseAndSpans(entries).base?.kind === "model-summary") ctx.ui.notify(recoveryText(entries, MIXED_CONTEXT_WARNING), "warning");
|
|
1655
|
-
},
|
|
1656
|
-
});
|
|
1657
|
-
|
|
1658
|
-
pi.registerCommand("cap-compaction", {
|
|
1659
|
-
description: "Show or set verbatim compaction cap: on|off|warn [80000c|20000t|25%]",
|
|
1660
|
-
getArgumentCompletions: (prefix) => {
|
|
1661
|
-
const mode = /^(on|off|warn)\s/.exec(prefix)?.[1];
|
|
1662
|
-
const values = mode ? ["80000c", "20000t", "25%"].map((budget) => `${mode} ${budget}`)
|
|
1663
|
-
: ["on", "off", "warn", "80000c", "20000t", "25%"];
|
|
1664
|
-
return values.filter((value) => value.startsWith(prefix)).map((value) => ({ value, label: value }));
|
|
1665
|
-
},
|
|
1666
|
-
handler: async (args, ctx) => {
|
|
1667
|
-
const previous = capSettings(ctx.sessionManager.getBranch());
|
|
1668
|
-
const words = args.trim().split(/\s+/).filter(Boolean);
|
|
1669
|
-
const mode = ["on", "off", "warn"].includes(words[0]) ? words.shift() as CapMode : previous.mode;
|
|
1670
|
-
const budget = words.length === 0 ? previous.budget : words.length === 1 ? parseCapBudget(words[0]) : undefined;
|
|
1671
|
-
if (!budget) {
|
|
1672
|
-
ctx.ui.notify("Usage: /cap-compaction [on|off|warn] [<chars>c|<estimated tokens>t|<percent>%]; percentages must be >0 and <=100.", "error");
|
|
1673
|
-
return;
|
|
1674
|
-
}
|
|
1675
|
-
const next = { mode, budget };
|
|
1676
|
-
persistCap(pi, previous, next);
|
|
1677
|
-
ctx.ui.notify(`${capDescription(next, ctx.model?.contextWindow)} Applies only to verbatim compaction.`, "info");
|
|
1678
|
-
},
|
|
1679
|
-
});
|
|
1680
|
-
|
|
1681
1582
|
for (const name of ["filter-later", "fl"]) pi.registerCommand(name, {
|
|
1682
1583
|
description: "Submit a normal user turn pre-flagged for future checkpoint filtering",
|
|
1683
1584
|
handler: async (args, ctx) => {
|
|
@@ -1686,7 +1587,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1686
1587
|
ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before submitting an aside.", "warning"); return;
|
|
1687
1588
|
}
|
|
1688
1589
|
if (compactionMethod(ctx.sessionManager.getBranch()) !== "verbatim") {
|
|
1689
|
-
ctx.ui.notify(`/${name} requires verbatim compaction.
|
|
1590
|
+
ctx.ui.notify(`/${name} requires verbatim compaction. Change the method in /compact-settings first.`, "error"); return;
|
|
1690
1591
|
}
|
|
1691
1592
|
clearAsideSubmission();
|
|
1692
1593
|
requestedAside = { sessionId: ctx.sessionManager.getSessionId(), text: args };
|
|
@@ -1699,20 +1600,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
1699
1600
|
},
|
|
1700
1601
|
});
|
|
1701
1602
|
|
|
1702
|
-
pi.registerCommand("filter-auto", {
|
|
1703
|
-
description: "Show or set automatic application of pre-flagged asides: on|off (default off)",
|
|
1704
|
-
getArgumentCompletions: (prefix) => ["on", "off"].filter((value) => value.startsWith(prefix))
|
|
1705
|
-
.map((value) => ({ value, label: value })),
|
|
1706
|
-
handler: async (args, ctx) => {
|
|
1707
|
-
const value = args.trim();
|
|
1708
|
-
if (value && value !== "on" && value !== "off") { ctx.ui.notify("Usage: /filter-auto [on|off]", "error"); return; }
|
|
1709
|
-
const previous = autoFilterEnabled(ctx.sessionManager.getBranch());
|
|
1710
|
-
const enabled = value ? value === "on" : previous;
|
|
1711
|
-
if (enabled !== previous) pi.appendEntry(AUTO_FILTER_ENTRY, { enabled });
|
|
1712
|
-
ctx.ui.notify(`Automatic aside filtering: ${enabled ? "on" : "off"}. Applies user pre-flags during verbatim threshold/overflow compaction; no picker or automatic relevance judgments.`, "info");
|
|
1713
|
-
},
|
|
1714
|
-
});
|
|
1715
|
-
|
|
1716
1603
|
const filterTurns = {
|
|
1717
1604
|
description: "Choose checkpoint turn modes: pruned, prose, prose+tools or full; no compaction",
|
|
1718
1605
|
handler: async (args: string, ctx: ExtensionContext, reads = false) => {
|
|
@@ -1775,7 +1662,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1775
1662
|
pruned.size === previousExcluded.length && previousExcluded.every((id) => pruned.has(id)) &&
|
|
1776
1663
|
kept.size === previousKept.length && previousKept.every((id) => kept.has(id)) &&
|
|
1777
1664
|
JSON.stringify(Object.entries(modes).sort()) === JSON.stringify(Object.entries(previousFidelity).sort());
|
|
1778
|
-
const cap = capSettings(entries);
|
|
1665
|
+
const cap = capSettings(entries, pi.getSettings());
|
|
1779
1666
|
const renderCheckpoint = (pruned: Set<string>, modes: TurnFidelities, placements: TurnSlot[], preview: boolean, presentation?: { shortened: boolean }, expansionTargets?: ExpansionTarget[]) => buildMechanicalSummary({
|
|
1780
1667
|
reason: canonical.span.reason, tokensBefore: compaction.tokensBefore, branchEntries: entries,
|
|
1781
1668
|
now: canonical.span.at, revisedAt: new Date().toISOString(), spanLines: [], filteredTurnIds: [...pruned], fidelity: modes, slots: placements, presentation, expansionTargets,
|
|
@@ -1799,7 +1686,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1799
1686
|
const reminder: AgentMessage = { ...reorientationMessage(entries, compaction.id, pruned.size > 0,
|
|
1800
1687
|
revisionId ?? compaction.id, Object.keys(modes).length > 0), role: "custom", timestamp: 0 };
|
|
1801
1688
|
const messages = checkpointContextMessages(summary, placements, modes, entries, compaction.firstKeptEntryId);
|
|
1802
|
-
return { ...estimateContext([system, ...messages, reminder], ctx), tailTokens,
|
|
1689
|
+
return { ...estimateContext([system, ...frameCheckpoint(messages), reminder], ctx), tailTokens,
|
|
1803
1690
|
noticeTokens: contextNoticeTokens(messages, reminder), shortening };
|
|
1804
1691
|
};
|
|
1805
1692
|
const saved = latestFilterRevision(entries)?.data ?? { summary: compaction.summary,
|
|
@@ -1865,7 +1752,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1865
1752
|
ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before filtering turns.", "warning"); return;
|
|
1866
1753
|
}
|
|
1867
1754
|
if (compactionMethod(ctx.sessionManager.getBranch()) !== "verbatim") {
|
|
1868
|
-
ctx.ui.notify("/compact-filtered requires verbatim compaction.
|
|
1755
|
+
ctx.ui.notify("/compact-filtered requires verbatim compaction. Change the method in /compact-settings first.", "error"); return;
|
|
1869
1756
|
}
|
|
1870
1757
|
const sessionId = ctx.sessionManager.getSessionId(), leafId = ctx.sessionManager.getLeafId();
|
|
1871
1758
|
try {
|
|
@@ -1965,7 +1852,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
1965
1852
|
// --------------------------------------------------------------------------
|
|
1966
1853
|
pi.on("session_before_compact", async (event, ctx) => {
|
|
1967
1854
|
const { preparation, branchEntries, reason, signal } = event;
|
|
1968
|
-
const automaticFiltering = reason !== "manual" && autoFilterEnabled(branchEntries);
|
|
1969
1855
|
if (!preparation) return;
|
|
1970
1856
|
if (signal?.aborted) return;
|
|
1971
1857
|
if (preparation.messagesToSummarize.length === 0 && preparation.turnPrefixMessages.length === 0) return;
|
|
@@ -2057,8 +1943,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
2057
1943
|
const excluded = new Set(filteredTurns(branchEntries));
|
|
2058
1944
|
const keptAsides = new Set(keptAsideTurns(branchEntries));
|
|
2059
1945
|
const fidelity = { ...turnFidelities(branchEntries) }, slots: TurnSlot[] = [];
|
|
2060
|
-
|
|
2061
|
-
|
|
1946
|
+
// /fl is an explicit request to prune at the next eligible compaction,
|
|
1947
|
+
// manual or automatic. Never prune a turn that overlaps the recent tail,
|
|
1948
|
+
// or re-prune an aside the user explicitly kept/restored in the editor.
|
|
1949
|
+
const preflags = preflaggedTurns(branchEntries);
|
|
1950
|
+
if (preflags.size > 0) {
|
|
2062
1951
|
const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
|
|
2063
1952
|
const choices = filterChoices(branchEntries, [...collectBaseAndSpans(branchEntries).spans, span],
|
|
2064
1953
|
excluded, preparation.firstKeptEntryId, selectedReads(catalog, canonicalRetained), proposed);
|
|
@@ -2124,7 +2013,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2124
2013
|
};
|
|
2125
2014
|
} catch (err) {
|
|
2126
2015
|
// Fail closed rather than discard explicit filtering/fidelity/retention.
|
|
2127
|
-
const preserveFiltering =
|
|
2016
|
+
const preserveFiltering = preflaggedTurns(branchEntries).size > 0 || retainingReads || filteredTurns(branchEntries).length > 0 || Object.keys(turnFidelities(branchEntries)).length > 0;
|
|
2128
2017
|
ctx.ui?.notify?.(`transparent-compact: failed to build checkpoint (${errMsg(err)}); ${preserveFiltering ? "compaction cancelled" : "falling back to Pi's summary compaction"}`, "error");
|
|
2129
2018
|
return preserveFiltering ? { cancel: true } : undefined;
|
|
2130
2019
|
}
|
|
@@ -2144,6 +2033,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2144
2033
|
question: Type.String({ description: "A specific question about earlier in this conversation: an output, source of a finding, reason for a decision, or evidence behind notes that conflict with new observations." }),
|
|
2145
2034
|
}),
|
|
2146
2035
|
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
2036
|
+
const cfg = sessionPreferences(pi.getSettings(), ctx.sessionManager.getBranch());
|
|
2147
2037
|
if (cfg.lookupMaxCalls > 0 && consecutiveLookups(ctx, toolCallId) >= cfg.lookupMaxCalls) {
|
|
2148
2038
|
return {
|
|
2149
2039
|
content: [{ type: "text", text: `context_lookup consecutive-call limit reached (${cfg.lookupMaxCalls}).` }],
|
|
@@ -2157,7 +2047,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2157
2047
|
}
|
|
2158
2048
|
model = model ?? ctx.model;
|
|
2159
2049
|
if (!model) {
|
|
2160
|
-
return { content: [{ type: "text", text: "context_lookup needs a model (session model or MECH_COMPACT_LOOKUP_MODEL)." }], details: undefined };
|
|
2050
|
+
return { content: [{ type: "text", text: "context_lookup needs a model (session model, transparentCompact.lookupModel, or MECH_COMPACT_LOOKUP_MODEL)." }], details: undefined };
|
|
2161
2051
|
}
|
|
2162
2052
|
|
|
2163
2053
|
try {
|
|
@@ -2165,7 +2055,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2165
2055
|
const transcript = sessionTranscript(ctx);
|
|
2166
2056
|
if (transcript.index.length === 0)
|
|
2167
2057
|
return { content: [{ type: "text", text: "No entries found on the session branch." }], details: undefined };
|
|
2168
|
-
const answer = await runLookupSubagent({ question: params.question, transcripts: [transcript], model, registry: ctx.modelRegistry, signal });
|
|
2058
|
+
const answer = await runLookupSubagent({ question: params.question, transcripts: [transcript], model, registry: ctx.modelRegistry, lookupTurns: cfg.lookupTurns, signal });
|
|
2169
2059
|
return { content: [{ type: "text", text: answer }], details: undefined };
|
|
2170
2060
|
} catch (err) {
|
|
2171
2061
|
return { content: [{ type: "text", text: `context_lookup failed: ${errMsg(err)}` }], details: undefined };
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
/** Persistent preferences come from Pi's effective settings. */
|
|
4
|
+
export interface CapBudget { unit: "chars" | "tokens" | "percent"; value: number }
|
|
5
|
+
export type CapMode = "on" | "off" | "warn";
|
|
6
|
+
export type CompactionMethod = "verbatim" | "summary";
|
|
7
|
+
export interface Preferences {
|
|
8
|
+
compactionMethod: CompactionMethod;
|
|
9
|
+
capMode: CapMode;
|
|
10
|
+
capBudget: CapBudget;
|
|
11
|
+
lookupModel: string;
|
|
12
|
+
lookupTurns: number;
|
|
13
|
+
lookupMaxCalls: number;
|
|
14
|
+
mainAgentLookup: boolean;
|
|
15
|
+
}
|
|
16
|
+
export const DEFAULT_PREFERENCES: Readonly<Preferences> = {
|
|
17
|
+
compactionMethod: "verbatim",
|
|
18
|
+
capMode: "warn",
|
|
19
|
+
capBudget: { unit: "percent", value: 25 },
|
|
20
|
+
lookupModel: "",
|
|
21
|
+
lookupTurns: 25,
|
|
22
|
+
lookupMaxCalls: 3,
|
|
23
|
+
mainAgentLookup: false,
|
|
24
|
+
};
|
|
25
|
+
export type PreferenceKey = keyof Preferences;
|
|
26
|
+
export type PreferencePatch = { [K in PreferenceKey]?: Preferences[K] | null };
|
|
27
|
+
export const SETTINGS_ENTRY = "transparent-compact:settings";
|
|
28
|
+
export const METHOD_ENTRY = "transparent-compact:compaction-method";
|
|
29
|
+
export const CAP_ENTRY = "transparent-compact:cap-compaction";
|
|
30
|
+
export const MAIN_MODE_ENTRY = "transparent-compact:main-agent-lookup";
|
|
31
|
+
// DEPRECATED: legacy autoFilter settings and transparent-compact:auto-filter
|
|
32
|
+
// session entries are intentionally ignored. TODO(1.x.x): remove this note and
|
|
33
|
+
// the associated autoFilter compatibility fixtures; do not restore the option.
|
|
34
|
+
export const PREFERENCE_KEYS: PreferenceKey[] = ["compactionMethod", "capMode", "capBudget",
|
|
35
|
+
"lookupModel", "lookupTurns", "lookupMaxCalls", "mainAgentLookup"];
|
|
36
|
+
|
|
37
|
+
export function validCapBudget(value: unknown): value is CapBudget {
|
|
38
|
+
if (!value || typeof value !== "object") return false;
|
|
39
|
+
const { unit, value: n } = value as CapBudget;
|
|
40
|
+
if (typeof n !== "number" || !Number.isFinite(n) || n <= 0) return false;
|
|
41
|
+
if (unit === "percent") return n <= 100;
|
|
42
|
+
return Number.isSafeInteger(n) && (unit === "chars" || (unit === "tokens" && n <= Number.MAX_SAFE_INTEGER / 4));
|
|
43
|
+
}
|
|
44
|
+
export function parseCapBudget(text: string): CapBudget | undefined {
|
|
45
|
+
const match = /^(\d+(?:\.\d+)?)(c|t|%)$/.exec(text.trim());
|
|
46
|
+
if (!match) return;
|
|
47
|
+
const budget: CapBudget = { value: Number(match[1]), unit: match[2] === "c" ? "chars" : match[2] === "t" ? "tokens" : "percent" };
|
|
48
|
+
return validCapBudget(budget) ? budget : undefined;
|
|
49
|
+
}
|
|
50
|
+
export function capBudgetText(budget: CapBudget): string {
|
|
51
|
+
return `${budget.value}${budget.unit === "chars" ? "c" : budget.unit === "tokens" ? "t" : "%"}`;
|
|
52
|
+
}
|
|
53
|
+
export function validPreference(key: PreferenceKey, value: unknown): boolean {
|
|
54
|
+
switch (key) {
|
|
55
|
+
case "compactionMethod": return value === "verbatim" || value === "summary";
|
|
56
|
+
case "capMode": return value === "on" || value === "off" || value === "warn";
|
|
57
|
+
case "capBudget": return validCapBudget(value);
|
|
58
|
+
case "mainAgentLookup": return typeof value === "boolean";
|
|
59
|
+
case "lookupModel": return typeof value === "string" && (!value.trim() || /^[^/\s]+\/\S+$/.test(value.trim()));
|
|
60
|
+
case "lookupTurns": return integer(value, 1) !== undefined;
|
|
61
|
+
case "lookupMaxCalls": return integer(value, 0) !== undefined;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export function recoveryLocked(entries: readonly SessionEntry[]): boolean {
|
|
65
|
+
return entries.some((entry) => entry.type === "compaction" || (entry.type === "custom" && entry.customType === MAIN_MODE_ENTRY));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function object(value: unknown): Record<string, unknown> {
|
|
69
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function integer(value: unknown, minimum: number): number | undefined {
|
|
73
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum ? value : undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function percent(value: unknown): number | undefined {
|
|
77
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 && value <= 100 ? value : undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function nonempty(value: unknown): string | undefined {
|
|
81
|
+
return typeof value === "string" ? value.trim() || undefined : undefined;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function resolveConfig(settings: unknown, env: Record<string, string | undefined> = process.env) {
|
|
85
|
+
const config = object(object(settings).transparentCompact);
|
|
86
|
+
const envNumber = (name: string) => {
|
|
87
|
+
const raw = nonempty(env[name]);
|
|
88
|
+
return raw === undefined ? undefined : Number(raw);
|
|
89
|
+
};
|
|
90
|
+
// Invalid or empty overrides are ignored, just like invalid file values.
|
|
91
|
+
const chars = integer(envNumber("MECH_COMPACT_MAX_SUMMARY_CHARS"), 1) ?? integer(config.maxSummaryChars, 1);
|
|
92
|
+
const percentage = percent(envNumber("MECH_COMPACT_MAX_SUMMARY_PERCENT")) ?? percent(config.maxSummaryPercent) ?? DEFAULT_PREFERENCES.capBudget.value;
|
|
93
|
+
const direct = nonempty(env.MECH_COMPACT_MAIN_AGENT_LOOKUP);
|
|
94
|
+
return {
|
|
95
|
+
// Resolve each key's precedence first; a fixed character cap wins over a percentage.
|
|
96
|
+
defaultCapBudget: (chars === undefined ? { unit: "percent", value: percentage } : { unit: "chars", value: chars }) as CapBudget,
|
|
97
|
+
lookupTurns: integer(envNumber("MECH_COMPACT_LOOKUP_TURNS"), 1) ?? integer(config.lookupTurns, 1) ?? DEFAULT_PREFERENCES.lookupTurns,
|
|
98
|
+
lookupMaxCalls: integer(envNumber("MECH_COMPACT_LOOKUP_MAX_CALLS"), 0) ?? integer(config.lookupMaxCalls, 0) ?? DEFAULT_PREFERENCES.lookupMaxCalls,
|
|
99
|
+
lookupModel: nonempty(env.MECH_COMPACT_LOOKUP_MODEL) ?? nonempty(config.lookupModel),
|
|
100
|
+
mainAgentLookup: direct === "1" ? true : direct === "0" ? false
|
|
101
|
+
: typeof config.mainAgentLookup === "boolean" ? config.mainAgentLookup : DEFAULT_PREFERENCES.mainAgentLookup,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Branch-local overrides; null removes an override rather than freezing today's default. */
|
|
106
|
+
export function preferenceState(settings: unknown, entries: readonly SessionEntry[], env: Record<string, string | undefined> = process.env) {
|
|
107
|
+
const cfg = resolveConfig(settings, env), file = object(object(settings).transparentCompact);
|
|
108
|
+
const defaults: Preferences = {
|
|
109
|
+
compactionMethod: validPreference("compactionMethod", file.compactionMethod) ? file.compactionMethod as CompactionMethod : DEFAULT_PREFERENCES.compactionMethod,
|
|
110
|
+
capMode: validPreference("capMode", file.capMode) ? file.capMode as CapMode : DEFAULT_PREFERENCES.capMode,
|
|
111
|
+
capBudget: cfg.defaultCapBudget,
|
|
112
|
+
lookupModel: cfg.lookupModel ?? DEFAULT_PREFERENCES.lookupModel, lookupTurns: cfg.lookupTurns, lookupMaxCalls: cfg.lookupMaxCalls,
|
|
113
|
+
mainAgentLookup: cfg.mainAgentLookup,
|
|
114
|
+
};
|
|
115
|
+
const overrides: Partial<Preferences> = {};
|
|
116
|
+
const apply = (patch: Record<string, unknown>) => {
|
|
117
|
+
for (const key of PREFERENCE_KEYS) {
|
|
118
|
+
if (patch[key] === null) delete overrides[key];
|
|
119
|
+
else if (validPreference(key, patch[key])) Object.assign(overrides, { [key]: patch[key] });
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
for (const entry of entries) {
|
|
123
|
+
if (entry.type !== "custom") continue;
|
|
124
|
+
const data = object(entry.data);
|
|
125
|
+
if (entry.customType === SETTINGS_ENTRY) apply(data);
|
|
126
|
+
// These are also written by the cap-confirmation flow and existing session controls.
|
|
127
|
+
else if (entry.customType === CAP_ENTRY) apply({ capMode: data.mode, capBudget: data.budget });
|
|
128
|
+
else if (entry.customType === METHOD_ENTRY) apply({ compactionMethod: data.method });
|
|
129
|
+
}
|
|
130
|
+
const values = { ...defaults, ...overrides };
|
|
131
|
+
return { values, defaults, overrides };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function sessionPreferences(settings: unknown, entries: readonly SessionEntry[]): Preferences {
|
|
135
|
+
return preferenceState(settings, entries).values;
|
|
136
|
+
}
|
|
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
|
|
|
5
5
|
import { Type } from "typebox";
|
|
6
6
|
import type { TSchema } from "typebox";
|
|
7
7
|
import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { sessionPreferences } from "./config.js";
|
|
8
9
|
|
|
9
10
|
const MODE_ENTRY = "transparent-compact:main-agent-lookup";
|
|
10
11
|
const SKILL_PATH = fileURLToPath(new URL("./main-agent-retrieval.md", import.meta.url));
|
|
@@ -37,9 +38,7 @@ interface Backend { list: Retrieval; search: Retrieval; show: Retrieval }
|
|
|
37
38
|
export function startMainAgentLookup(pi: ExtensionAPI, ctx: ExtensionContext, backend: Backend, scope: string): void {
|
|
38
39
|
const entries = ctx.sessionManager.getEntries();
|
|
39
40
|
const saved = selected(entries);
|
|
40
|
-
const
|
|
41
|
-
const settings = pi.getSettings() as { transparentCompact?: { mainAgentLookup?: boolean } };
|
|
42
|
-
const requested = env === undefined ? settings.transparentCompact?.mainAgentLookup === true : env === "1";
|
|
41
|
+
const requested = sessionPreferences(pi.getSettings(), ctx.sessionManager.getBranch()).mainAgentLookup;
|
|
43
42
|
if (!saved && !requested) return;
|
|
44
43
|
if (!saved && entries.some((entry) => entry.type === "compaction")) {
|
|
45
44
|
ctx.ui.notify("Main-agent context lookup was not enabled: this session already has compactions. Its subagent lookup is unchanged. Start a new session to opt in.", "warning");
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { stripVTControlCharacters } from "node:util";
|
|
4
|
+
import { CONFIG_DIR_NAME, getAgentDir, SettingsManager, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import type { ExtensionAPI, ExtensionContext, Settings } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { fuzzyFilter, Input, Key, matchesKey, SelectList, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
7
|
+
import type { SelectItem } from "@earendil-works/pi-tui";
|
|
8
|
+
import { capBudgetText, DEFAULT_PREFERENCES, parseCapBudget, PREFERENCE_KEYS, preferenceState, recoveryLocked,
|
|
9
|
+
SETTINGS_ENTRY, validCapBudget, validPreference } from "./config.js";
|
|
10
|
+
import type { Preferences, PreferenceKey, PreferencePatch } from "./config.js";
|
|
11
|
+
|
|
12
|
+
type Scope = "session" | "project" | "global";
|
|
13
|
+
export interface SettingsChoice { changes: PreferencePatch; scope: Scope }
|
|
14
|
+
export interface SettingSourceLayer { label: string; values: Readonly<Preferences> }
|
|
15
|
+
const clean = (text: string) => stripVTControlCharacters(text).replace(/[\x00-\x1f\x7f]/g, " ");
|
|
16
|
+
const same = (a: unknown, b: unknown) => a === b ||
|
|
17
|
+
(validCapBudget(a) && validCapBudget(b) && a.unit === b.unit && a.value === b.value);
|
|
18
|
+
const labels: Record<PreferenceKey, string> = {
|
|
19
|
+
compactionMethod: "Compaction method", capMode: "Cap mode", capBudget: "Cap budget",
|
|
20
|
+
lookupModel: "Lookup model", lookupTurns: "Lookup search turns", lookupMaxCalls: "Consecutive lookups", mainAgentLookup: "Recovery mode",
|
|
21
|
+
};
|
|
22
|
+
const descriptions: Record<PreferenceKey, string> = {
|
|
23
|
+
compactionMethod: "Summary uses Pi's original compaction, effectively disabling transparent-compact. Context pruning is incompatible; context_lookup remains available but may be used less effectively.",
|
|
24
|
+
capMode: "Warn asks before trimming; on trims automatically; off disables the verbatim cap.",
|
|
25
|
+
capBudget: "Enter a percentage, characters (c), or estimated tokens (t), e.g. 25%, 80000c, 20000t. Tokens use 4 characters each.",
|
|
26
|
+
lookupModel: "Choose from Pi's scoped models, or use the session model. With no model scope configured, all available models are listed.",
|
|
27
|
+
lookupTurns: "Positive integer: maximum substantive search turns per subagent lookup. Continuation pages have a separate ceiling.",
|
|
28
|
+
lookupMaxCalls: "Non-negative integer: consecutive subagent lookup limit. Zero means unlimited.",
|
|
29
|
+
mainAgentLookup: "Subagent searches in a separate context; direct recovery exposes history tools to the main agent. Direct mode is experimental.",
|
|
30
|
+
};
|
|
31
|
+
export function settingText(key: PreferenceKey, value: Preferences[PreferenceKey]): string {
|
|
32
|
+
if (key === "capBudget") return capBudgetText(value as Preferences["capBudget"]);
|
|
33
|
+
if (key === "compactionMethod" && value === "summary") return "summary (Pi original)";
|
|
34
|
+
if (key === "mainAgentLookup") return value ? "direct (experimental)" : "subagent";
|
|
35
|
+
if (typeof value === "boolean") return value ? "on" : "off";
|
|
36
|
+
return key === "lookupModel" && !value ? "session model" : String(value);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Candidate values at each persistent scope, before any session overrides. */
|
|
40
|
+
export function settingSourceLayers(globalSettings: unknown, projectSettings: unknown, env: Record<string, string | undefined> = process.env): SettingSourceLayer[] {
|
|
41
|
+
const scoped = (settings: unknown): Partial<Settings> => ({
|
|
42
|
+
transparentCompact: settings && typeof settings === "object" && !Array.isArray(settings)
|
|
43
|
+
? (settings as Record<string, unknown>).transparentCompact : undefined,
|
|
44
|
+
} as Partial<Settings>);
|
|
45
|
+
const merged = SettingsManager.inMemory(scoped(globalSettings));
|
|
46
|
+
const global = preferenceState(merged.getSettings(), [], {}).values;
|
|
47
|
+
// Use Pi's merge semantics, including nulls masking inherited cap units.
|
|
48
|
+
merged.applyOverrides(scoped(projectSettings));
|
|
49
|
+
const project = preferenceState(merged.getSettings(), [], {}).values;
|
|
50
|
+
const environment = preferenceState(merged.getSettings(), [], env).values;
|
|
51
|
+
return [
|
|
52
|
+
{ label: "global setting", values: global },
|
|
53
|
+
{ label: "project setting", values: project },
|
|
54
|
+
{ label: "environment setting", values: environment },
|
|
55
|
+
];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function settingBadge(key: PreferenceKey, value: Preferences[PreferenceKey], layers: readonly SettingSourceLayer[]): string {
|
|
59
|
+
const matches = (candidate: Preferences[PreferenceKey]) => same(value, candidate) ||
|
|
60
|
+
(validCapBudget(value) && validCapBudget(candidate) && value.unit !== "percent" && candidate.unit !== "percent" &&
|
|
61
|
+
value.value * (value.unit === "tokens" ? 4 : 1) === candidate.value * (candidate.unit === "tokens" ? 4 : 1));
|
|
62
|
+
if (matches(DEFAULT_PREFERENCES[key])) return "default";
|
|
63
|
+
return layers.find((layer) => matches(layer.values[key]))?.label ?? "session setting";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Read only for badges; effective behavior still comes from pi.getSettings(). */
|
|
67
|
+
export function readSettingSourceLayers(ctx: Pick<ExtensionContext, "cwd" | "isProjectTrusted">, agentDir = getAgentDir(), env: Record<string, string | undefined> = process.env): SettingSourceLayer[] {
|
|
68
|
+
const read = (filename: string): unknown => {
|
|
69
|
+
try {
|
|
70
|
+
const value = JSON.parse(fs.readFileSync(filename, "utf8").replace(/^\uFEFF/, ""));
|
|
71
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
72
|
+
} catch { return {}; } // Missing/unreadable/invalid files cannot supply badge matches.
|
|
73
|
+
};
|
|
74
|
+
return settingSourceLayers(read(path.join(agentDir, "settings.json")),
|
|
75
|
+
ctx.isProjectTrusted() ? read(path.join(ctx.cwd, CONFIG_DIR_NAME, "settings.json")) : {}, env);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Read-merge-write inside Pi's file queue; never replace malformed configuration. */
|
|
79
|
+
export async function savePreferences(cwd: string, scope: "project" | "global", changes: PreferencePatch, agentDir = getAgentDir()): Promise<string> {
|
|
80
|
+
const filename = path.join(scope === "global" ? agentDir : path.join(cwd, CONFIG_DIR_NAME), "settings.json");
|
|
81
|
+
await withFileMutationQueue(filename, async () => {
|
|
82
|
+
let settings: Record<string, any> = {};
|
|
83
|
+
try { settings = JSON.parse(fs.readFileSync(filename, "utf8").replace(/^\uFEFF/, "")); }
|
|
84
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
85
|
+
const object = (v: unknown) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
86
|
+
if (!object(settings) || (settings.transparentCompact !== undefined && !object(settings.transparentCompact)))
|
|
87
|
+
throw new Error("Settings and transparentCompact must be JSON objects; the file was not changed.");
|
|
88
|
+
const config = { ...settings.transparentCompact };
|
|
89
|
+
for (const key of PREFERENCE_KEYS) {
|
|
90
|
+
if (!(key in changes)) continue;
|
|
91
|
+
const value = changes[key];
|
|
92
|
+
if (value !== null && !validPreference(key, value)) throw new Error(`Invalid ${key}; the file was not changed.`);
|
|
93
|
+
const remove = value === null || (scope === "global" && same(value, DEFAULT_PREFERENCES[key]));
|
|
94
|
+
if (key === "capBudget") {
|
|
95
|
+
if (remove) { delete config.maxSummaryChars; delete config.maxSummaryPercent; }
|
|
96
|
+
else {
|
|
97
|
+
const budget = value as Preferences["capBudget"];
|
|
98
|
+
// Null masks an inherited alternative unit in Pi's deep-merged settings.
|
|
99
|
+
config.maxSummaryChars = budget.unit === "percent" ? null : budget.value * (budget.unit === "tokens" ? 4 : 1);
|
|
100
|
+
config.maxSummaryPercent = budget.unit === "percent" ? budget.value : null;
|
|
101
|
+
}
|
|
102
|
+
} else if (remove) delete config[key];
|
|
103
|
+
else config[key] = value;
|
|
104
|
+
}
|
|
105
|
+
if (scope === "global" && Object.keys(config).length === 0) delete settings.transparentCompact;
|
|
106
|
+
else settings.transparentCompact = config;
|
|
107
|
+
fs.mkdirSync(path.dirname(filename), { recursive: true });
|
|
108
|
+
// Synchronous read/merge/write preserves symlinks and existing permissions.
|
|
109
|
+
fs.writeFileSync(filename, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
|
|
110
|
+
});
|
|
111
|
+
return filename;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function lookupModelItems(ctx: Pick<ExtensionContext, "scopedModels" | "modelRegistry" | "model">): SelectItem[] {
|
|
115
|
+
const models = ctx.scopedModels.length ? ctx.scopedModels.map((item) => item.model) : ctx.modelRegistry.getAvailable();
|
|
116
|
+
const seen = new Set<string>();
|
|
117
|
+
return [{ value: "", label: "Use session model", description: ctx.model
|
|
118
|
+
? clean(`Default; follows ${ctx.model.provider}/${ctx.model.id}`) : "Default; follows the session model" },
|
|
119
|
+
...[...models].sort((a, b) => a.provider.localeCompare(b.provider) || a.id.localeCompare(b.id)).flatMap((model) => {
|
|
120
|
+
const value = `${model.provider}/${model.id}`;
|
|
121
|
+
if (seen.has(value)) return [];
|
|
122
|
+
seen.add(value);
|
|
123
|
+
return [{ value, label: clean(`${model.id} [${model.provider}]`), description: clean(model.name ?? "") }];
|
|
124
|
+
})];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Local draft only. Enter reviews; a second Enter applies the selected scope. */
|
|
128
|
+
export async function pickSettings(ctx: ExtensionContext, state: ReturnType<typeof preferenceState>, locked: boolean,
|
|
129
|
+
layers: readonly SettingSourceLayer[] = []): Promise<SettingsChoice | undefined> {
|
|
130
|
+
return ctx.ui.custom<SettingsChoice | undefined>((tui, theme, kb, done) => {
|
|
131
|
+
const changes: Partial<Preferences> = {};
|
|
132
|
+
let cursor = 0, top = 0, review = false, reviewTop = 0, scopeIndex = 0, notice = "", editing: PreferenceKey | undefined;
|
|
133
|
+
let input: Input | undefined, focused = true, finished = false;
|
|
134
|
+
let modelItems: SelectItem[] = [], modelMatches: SelectItem[] = [], modelList: SelectList | undefined, modelRows = 1;
|
|
135
|
+
const scopes: Scope[] = ["session", "project", "global"];
|
|
136
|
+
const scopeLabels = ["Apply to this session", "Apply and save project defaults", "Apply and save global defaults"];
|
|
137
|
+
const value = (key: PreferenceKey) => changes[key] ?? state.values[key];
|
|
138
|
+
const edit = (key: PreferenceKey, next: Preferences[PreferenceKey]) => {
|
|
139
|
+
if (same(next, state.values[key])) delete changes[key]; else Object.assign(changes, { [key]: next });
|
|
140
|
+
notice = "";
|
|
141
|
+
};
|
|
142
|
+
const closeEditor = () => { editing = undefined; input = undefined; modelList = undefined; notice = ""; };
|
|
143
|
+
const buildModelList = (selectedValue: string | undefined) => {
|
|
144
|
+
const query = input!.getValue();
|
|
145
|
+
modelMatches = query ? fuzzyFilter(modelItems, query, (item) => `${item.value} ${item.label} ${item.description ?? ""}`) : modelItems;
|
|
146
|
+
modelList = new SelectList(modelMatches, modelRows, {
|
|
147
|
+
selectedPrefix: (text) => theme.fg("accent", text),
|
|
148
|
+
selectedText: (text) => theme.bg("selectedBg", theme.fg("accent", text)),
|
|
149
|
+
description: (text) => theme.fg("muted", text),
|
|
150
|
+
scrollInfo: (text) => theme.fg("dim", text),
|
|
151
|
+
noMatch: () => theme.fg("muted", "No matching models"),
|
|
152
|
+
});
|
|
153
|
+
modelList.setSelectedIndex(Math.max(0, modelMatches.findIndex((item) => item.value === selectedValue)));
|
|
154
|
+
modelList.onSelect = (item) => { edit("lookupModel", item.value); closeEditor(); };
|
|
155
|
+
modelList.onCancel = closeEditor;
|
|
156
|
+
};
|
|
157
|
+
const beginEdit = () => {
|
|
158
|
+
const key = PREFERENCE_KEYS[cursor], current = value(key);
|
|
159
|
+
if (key === "compactionMethod") edit(key, current === "verbatim" ? "summary" : "verbatim");
|
|
160
|
+
else if (key === "capMode") { const modes = ["warn", "on", "off"] as const; edit(key, modes[(modes.indexOf(current as any) + 1) % modes.length]); }
|
|
161
|
+
else if (typeof current === "boolean") edit(key, !current);
|
|
162
|
+
else if (key === "lookupModel") {
|
|
163
|
+
modelItems = lookupModelItems(ctx);
|
|
164
|
+
editing = key; input = new Input({ prompt: "Search: " }); input.focused = focused;
|
|
165
|
+
input.onEscape = closeEditor;
|
|
166
|
+
modelRows = Math.max(1, tui.terminal.rows - 9);
|
|
167
|
+
buildModelList(String(current));
|
|
168
|
+
} else {
|
|
169
|
+
editing = key; input = new Input(); input.focused = focused;
|
|
170
|
+
input.setValue(clean(settingText(key, current)));
|
|
171
|
+
input.onSubmit = (raw) => {
|
|
172
|
+
const next = key === "capBudget" ? parseCapBudget(raw) : /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : undefined;
|
|
173
|
+
if (!validPreference(key, next)) { notice = "Invalid value. " + descriptions[key]; return; }
|
|
174
|
+
edit(key, next!); closeEditor();
|
|
175
|
+
};
|
|
176
|
+
input.onEscape = closeEditor;
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
const finish = (choice?: SettingsChoice) => { if (finished) return; finished = true; done(choice); };
|
|
180
|
+
const render = (width: number): string[] => {
|
|
181
|
+
const rows = Math.max(1, tui.terminal.rows), framed = width >= 8, inner = Math.max(1, width - (framed ? 4 : 0));
|
|
182
|
+
const line = (text: string, selected = false) => {
|
|
183
|
+
const clipped = truncateToWidth(text, inner), padded = clipped + " ".repeat(Math.max(0, inner - visibleWidth(clipped)));
|
|
184
|
+
const content = selected ? theme.bg("selectedBg", padded) : padded;
|
|
185
|
+
return framed ? theme.fg("borderMuted", "│ ") + content + theme.fg("borderMuted", " │") : content;
|
|
186
|
+
};
|
|
187
|
+
const rule = (caption: string, end = false) => {
|
|
188
|
+
if (!framed) return truncateToWidth(caption, width);
|
|
189
|
+
const text = truncateToWidth(caption ? `─ ${caption} ` : "", Math.max(1, width - 2));
|
|
190
|
+
return theme.fg("borderMuted", (end ? "╰" : "╭") + text + "─".repeat(Math.max(0, width - 2 - visibleWidth(text))) + (end ? "╯" : "╮"));
|
|
191
|
+
};
|
|
192
|
+
const out = [rule(theme.fg("accent", theme.bold(`Compaction settings · ${review ? "2/2 Review" : "1/2 Edit"}`)))];
|
|
193
|
+
const room = rows >= 16;
|
|
194
|
+
if (room) out.push(line(theme.fg("muted", "Changes stay in this draft until you confirm. d restores the built-in default.")));
|
|
195
|
+
const footer = editing === "lookupModel" ? "↑/↓ Select · Type Search · Enter Choose · Esc Back" : editing ? "Enter Accept · Esc Back"
|
|
196
|
+
: review ? "↑/↓ Scope · Enter Confirm · Esc Back" : "↑/↓ Move · Space/e Edit · d Reset · Enter Review · Esc Cancel";
|
|
197
|
+
const footerLines = wrapTextWithAnsi(footer, inner);
|
|
198
|
+
let content: string[];
|
|
199
|
+
if (editing === "lookupModel") {
|
|
200
|
+
out.push(line(theme.fg("accent", ctx.scopedModels.length ? "Lookup model · scoped models" : "Lookup model · available models")));
|
|
201
|
+
if (room) out.push(line(theme.fg("muted", "Search by model, provider or name. Choosing a model only changes this draft.")));
|
|
202
|
+
out.push(...input!.render(inner).map((part) => line(part)));
|
|
203
|
+
const height = Math.max(1, rows - out.length - footerLines.length - 3);
|
|
204
|
+
if (height !== modelRows) { modelRows = height; buildModelList(modelList?.getSelectedItem()?.value); }
|
|
205
|
+
content = modelList!.render(Math.max(8, inner)).map((part) => line(part));
|
|
206
|
+
} else if (editing) {
|
|
207
|
+
out.push(line(theme.fg("accent", labels[editing])));
|
|
208
|
+
for (const part of wrapTextWithAnsi(descriptions[editing], inner).slice(0, 3)) out.push(line(theme.fg("muted", part)));
|
|
209
|
+
content = input!.render(inner).map((part) => line(part));
|
|
210
|
+
} else if (review) {
|
|
211
|
+
const keys = PREFERENCE_KEYS.filter((key) => key in changes);
|
|
212
|
+
content = scopes.map((_scope, i) => line(`${i === scopeIndex ? "›" : " "} ${scopeLabels[i]}`, i === scopeIndex));
|
|
213
|
+
const height = Math.max(1, rows - (room ? 11 : 8));
|
|
214
|
+
reviewTop = Math.max(0, Math.min(reviewTop, keys.length - height));
|
|
215
|
+
if (room) content.push(line(theme.fg("muted", `Changes ${reviewTop + 1}–${Math.min(keys.length, reviewTop + height)} / ${keys.length} · PgUp/PgDn scroll`)));
|
|
216
|
+
content.push(...keys.slice(reviewTop, reviewTop + height).map((key) => line(clean(`${labels[key]}: ${settingText(key, state.values[key])} → ${settingText(key, value(key))}${locked && key === "mainAgentLookup" ? " (new sessions only)" : ""}`))));
|
|
217
|
+
if (room) content.push(line(theme.fg("muted", "Only edited settings are saved. Project/environment defaults can mask global saves.")));
|
|
218
|
+
} else {
|
|
219
|
+
const height = Math.max(1, rows - (room ? 9 : 5));
|
|
220
|
+
top = Math.max(0, Math.min(top, cursor));
|
|
221
|
+
if (cursor >= top + height) top = cursor - height + 1;
|
|
222
|
+
content = PREFERENCE_KEYS.slice(top, top + height).map((key, i) => {
|
|
223
|
+
const source = settingBadge(key, value(key), layers);
|
|
224
|
+
const label = key === "mainAgentLookup" && locked ? "Recovery default (next session)" : labels[key];
|
|
225
|
+
return line(clean(`${top + i === cursor ? "›" : " "} ${label}: ${settingText(key, value(key))} [${source}]${key in changes ? "*" : ""}`), top + i === cursor);
|
|
226
|
+
});
|
|
227
|
+
if (room) {
|
|
228
|
+
content.push(line(""));
|
|
229
|
+
const hint = PREFERENCE_KEYS[cursor] === "mainAgentLookup" && locked
|
|
230
|
+
? "Recovery mode is locked in this session. This row edits defaults for new sessions only." : descriptions[PREFERENCE_KEYS[cursor]];
|
|
231
|
+
for (const part of wrapTextWithAnsi(hint, inner).slice(0, 2)) content.push(line(theme.fg("muted", clean(part))));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const tail = [line(theme.fg(notice ? "warning" : "muted", clean(notice || (review ? "Session changes persist through resume and forks." : "All settings are optional. * Unsaved changes.")))),
|
|
235
|
+
...footerLines.map((part) => line(theme.fg("accent", part))), rule("", true)];
|
|
236
|
+
out.push(...content.slice(0, Math.max(1, rows - out.length - tail.length)), ...tail);
|
|
237
|
+
return out.map((part) => truncateToWidth(part, width)).slice(0, rows);
|
|
238
|
+
};
|
|
239
|
+
return {
|
|
240
|
+
capturesViewportInput: true,
|
|
241
|
+
get focused() { return focused; },
|
|
242
|
+
set focused(value: boolean) { focused = value; if (input) input.focused = value; },
|
|
243
|
+
render,
|
|
244
|
+
invalidate() { input?.invalidate(); modelList?.invalidate(); },
|
|
245
|
+
handleInput(data: string) {
|
|
246
|
+
if (finished) return;
|
|
247
|
+
if (editing === "lookupModel") {
|
|
248
|
+
const before = input!.getValue();
|
|
249
|
+
if ((["tui.select.up", "tui.select.down", "tui.select.confirm", "tui.select.cancel"] as const).some((action) => kb.matches(data, action))) modelList!.handleInput(data);
|
|
250
|
+
else if (matchesKey(data, Key.pageUp) || matchesKey(data, Key.pageDown)) {
|
|
251
|
+
const index = modelMatches.findIndex((item) => item.value === modelList!.getSelectedItem()?.value);
|
|
252
|
+
modelList!.setSelectedIndex(index + (matchesKey(data, Key.pageUp) ? -modelRows : modelRows));
|
|
253
|
+
} else input!.handleInput(data);
|
|
254
|
+
if (editing === "lookupModel" && input!.getValue() !== before) buildModelList(undefined);
|
|
255
|
+
} else if (editing) input!.handleInput(data);
|
|
256
|
+
else if (kb.matches(data, "tui.select.cancel")) { if (review) { review = false; notice = ""; } else finish(); }
|
|
257
|
+
else if (review) {
|
|
258
|
+
if (kb.matches(data, "tui.select.up")) scopeIndex = Math.max(0, scopeIndex - 1);
|
|
259
|
+
else if (kb.matches(data, "tui.select.down")) scopeIndex = Math.min(2, scopeIndex + 1);
|
|
260
|
+
else if (matchesKey(data, Key.pageUp)) reviewTop = Math.max(0, reviewTop - 3);
|
|
261
|
+
else if (matchesKey(data, Key.pageDown)) reviewTop += 3;
|
|
262
|
+
else if (kb.matches(data, "tui.select.confirm")) {
|
|
263
|
+
if (locked && "mainAgentLookup" in changes && scopes[scopeIndex] === "session") notice = "Recovery mode is locked; save project/global defaults for new sessions instead.";
|
|
264
|
+
else finish({ changes, scope: scopes[scopeIndex] });
|
|
265
|
+
}
|
|
266
|
+
} else if (kb.matches(data, "tui.select.up")) cursor = Math.max(0, cursor - 1);
|
|
267
|
+
else if (kb.matches(data, "tui.select.down")) cursor = Math.min(PREFERENCE_KEYS.length - 1, cursor + 1);
|
|
268
|
+
else if (matchesKey(data, Key.home)) cursor = 0;
|
|
269
|
+
else if (matchesKey(data, Key.end)) cursor = PREFERENCE_KEYS.length - 1;
|
|
270
|
+
else if (matchesKey(data, Key.pageUp)) cursor = Math.max(0, cursor - 5);
|
|
271
|
+
else if (matchesKey(data, Key.pageDown)) cursor = Math.min(PREFERENCE_KEYS.length - 1, cursor + 5);
|
|
272
|
+
else if (matchesKey(data, "d")) {
|
|
273
|
+
const key = PREFERENCE_KEYS[cursor];
|
|
274
|
+
Object.assign(changes, { [key]: structuredClone(DEFAULT_PREFERENCES[key]) });
|
|
275
|
+
notice = "";
|
|
276
|
+
}
|
|
277
|
+
else if (matchesKey(data, Key.space) || matchesKey(data, "e") || matchesKey(data, Key.right) || matchesKey(data, Key.left)) beginEdit();
|
|
278
|
+
else if (kb.matches(data, "tui.select.confirm")) {
|
|
279
|
+
if (!Object.keys(changes).length) notice = "No changes. Edit a setting, or Esc to close.";
|
|
280
|
+
else { review = true; reviewTop = 0; scopeIndex = 0; notice = ""; }
|
|
281
|
+
}
|
|
282
|
+
tui.requestRender();
|
|
283
|
+
},
|
|
284
|
+
dispose() { finished = true; },
|
|
285
|
+
};
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function registerSettingsMenu(pi: ExtensionAPI, afterApply: (previous: Preferences, next: Preferences, ctx: ExtensionContext) => void): void {
|
|
290
|
+
pi.registerCommand("compact-settings", {
|
|
291
|
+
description: "Configure compaction and recovery; apply to session or save project/global defaults",
|
|
292
|
+
handler: async (args, ctx) => {
|
|
293
|
+
if (args.trim()) { ctx.ui.notify("Usage: /compact-settings", "error"); return; }
|
|
294
|
+
if (ctx.mode !== "tui" || !ctx.hasUI) { ctx.ui.notify("/compact-settings requires the interactive terminal UI.", "error"); return; }
|
|
295
|
+
if (!ctx.isIdle() || ctx.hasPendingMessages()) { ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before changing settings.", "warning"); return; }
|
|
296
|
+
const sessionId = ctx.sessionManager.getSessionId(), leaf = ctx.sessionManager.getLeafId();
|
|
297
|
+
const entries = ctx.sessionManager.getBranch(), all = ctx.sessionManager.getEntries();
|
|
298
|
+
const locked = recoveryLocked(all), state = preferenceState(pi.getSettings(), entries);
|
|
299
|
+
if (locked) {
|
|
300
|
+
// Edit the configured default, not the immutable choice of this session.
|
|
301
|
+
// Otherwise a current subagent session could not save an explicit false
|
|
302
|
+
// over an inherited true (or a direct session save true over false).
|
|
303
|
+
state.values.mainAgentLookup = state.defaults.mainAgentLookup;
|
|
304
|
+
}
|
|
305
|
+
const choice = await pickSettings(ctx, state, locked, readSettingSourceLayers(ctx));
|
|
306
|
+
if (!choice) return;
|
|
307
|
+
if (ctx.sessionManager.getSessionId() !== sessionId || ctx.sessionManager.getLeafId() !== leaf || !ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
308
|
+
ctx.ui.notify("Session changed; settings update cancelled.", "warning"); return;
|
|
309
|
+
}
|
|
310
|
+
const { changes, scope } = choice;
|
|
311
|
+
if (!["session", "project", "global"].includes(scope) || Object.keys(changes).some((key) => !PREFERENCE_KEYS.includes(key as PreferenceKey) ||
|
|
312
|
+
(changes[key as PreferenceKey] !== null && !validPreference(key as PreferenceKey, changes[key as PreferenceKey])))) {
|
|
313
|
+
ctx.ui.notify("Invalid settings; nothing was changed.", "error"); return;
|
|
314
|
+
}
|
|
315
|
+
if (locked && "mainAgentLookup" in changes && scope === "session") {
|
|
316
|
+
ctx.ui.notify("Recovery mode is locked in this session. Save project/global defaults for new sessions instead.", "warning"); return;
|
|
317
|
+
}
|
|
318
|
+
try {
|
|
319
|
+
// Save first: a filesystem failure must not partially apply the session changes.
|
|
320
|
+
const saved = scope === "session" ? undefined : await savePreferences(ctx.cwd, scope, changes);
|
|
321
|
+
if (ctx.sessionManager.getSessionId() !== sessionId || ctx.sessionManager.getLeafId() !== leaf || !ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
322
|
+
ctx.ui.notify(saved ? `Defaults saved to ${saved}; session changed, so they were not applied to this session.` : "Session changed; settings update cancelled.", "warning"); return;
|
|
323
|
+
}
|
|
324
|
+
const patch = { ...changes };
|
|
325
|
+
if (locked) delete patch.mainAgentLookup;
|
|
326
|
+
for (const key of PREFERENCE_KEYS) {
|
|
327
|
+
if (patch[key] === null && !(key in state.overrides)) delete patch[key];
|
|
328
|
+
else if (same(patch[key], state.overrides[key])) delete patch[key];
|
|
329
|
+
}
|
|
330
|
+
if (Object.keys(patch).length) pi.appendEntry(SETTINGS_ENTRY, patch);
|
|
331
|
+
const next = preferenceState(pi.getSettings(), ctx.sessionManager.getBranch()).values;
|
|
332
|
+
afterApply(state.values, next, ctx);
|
|
333
|
+
ctx.ui.notify(saved ? `Compaction settings applied and saved to ${saved}.${locked && "mainAgentLookup" in changes ? " Recovery default applies to new sessions only." : ""}`
|
|
334
|
+
: "Compaction settings applied to this session.", "info");
|
|
335
|
+
// Reload rebinds recovery tools and refreshes Pi's cached file settings.
|
|
336
|
+
if (saved || (!locked && "mainAgentLookup" in patch && next.mainAgentLookup !== state.values.mainAgentLookup)) { await ctx.reload(); return; }
|
|
337
|
+
} catch (error) {
|
|
338
|
+
ctx.ui.notify(`Could not save compaction settings: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
339
|
+
}
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
}
|
|
@@ -13,6 +13,9 @@ export interface TurnSlot { turnId: string; mode: Fidelity; offset: number; mark
|
|
|
13
13
|
export const MODE_LABELS: Record<TurnMode, string> = { pruned: "PRUNED", prose: "PROSE", tools: "PROSE+TOOLS", full: "FULL" };
|
|
14
14
|
export const MODE_SYMBOLS: Record<TurnMode, string> = { pruned: "X", prose: " ", tools: "○", full: "■" };
|
|
15
15
|
export const FIDELITY_EXPLANATION = "Selected PROSE+TOOLS/FULL turns are inserted as original context messages at their labelled positions, replacing their compacted copies. PROSE+TOOLS replaces recorded thinking blocks with [Thinking omitted]; FULL retains all recorded thinking. They are not shortened by the prose cap. Provider/model compatibility transformations still apply. Historical content and thinking are not verification of current facts.";
|
|
16
|
+
export const RECOVERY_HISTORY_NOTE = "Compaction hides earlier details from your current view. The original conversation history, including recorded tool outputs and your reasoning, is preserved in the session and can be retrieved.";
|
|
17
|
+
export const CHECKPOINT_EXPLANATION = `**Compacted conversation follows.** The earlier part of this conversation has been compacted into the checkpoint below. This is not the full transcript. ${RECOVERY_HISTORY_NOTE}`;
|
|
18
|
+
export const CHECKPOINT_MESSAGE = "transparent-compact:checkpoint";
|
|
16
19
|
/** Raw user boundaries define whole turns, independent of context edits. */
|
|
17
20
|
export function turnOwners(entries: SessionEntry[]): Map<string, string | null> {
|
|
18
21
|
let owner: string | null = null;
|
|
@@ -140,6 +143,32 @@ export function expandCheckpoint(message: Extract<AgentMessage, { role: "compact
|
|
|
140
143
|
return output;
|
|
141
144
|
}
|
|
142
145
|
|
|
146
|
+
/** Frame TC's active checkpoint for the model only. Pi converts custom
|
|
147
|
+
* messages to user messages without adding its compaction summary wrapper.
|
|
148
|
+
* A full-fidelity checkpoint may straddle native turns; frame it once.
|
|
149
|
+
*/
|
|
150
|
+
export function frameCheckpoint(messages: AgentMessage[]): AgentMessage[] {
|
|
151
|
+
const first = messages.findIndex((m) => m.role === "compactionSummary");
|
|
152
|
+
if (first < 0) return messages;
|
|
153
|
+
const last = messages.findLastIndex((m) => m.role === "compactionSummary");
|
|
154
|
+
return messages.map((message, i) => {
|
|
155
|
+
if (message.role !== "compactionSummary") return message;
|
|
156
|
+
let content = message.summary;
|
|
157
|
+
if (i === first) {
|
|
158
|
+
// Move only the generated second line, never a matching quote in the body.
|
|
159
|
+
const start = content.indexOf("\n") + 1;
|
|
160
|
+
const intro = `${CHECKPOINT_EXPLANATION}\n`;
|
|
161
|
+
if (start > 0 && content.startsWith(intro, start)) {
|
|
162
|
+
content = `${CHECKPOINT_EXPLANATION}\n\n<compacted-checkpoint>\n${content.slice(0, start)}${content.slice(start + intro.length)}`;
|
|
163
|
+
} else {
|
|
164
|
+
content = `<compacted-checkpoint>\n${content}`;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (i === last) content += "\n</compacted-checkpoint>";
|
|
168
|
+
return { role: "custom", customType: CHECKPOINT_MESSAGE, content, display: false, timestamp: message.timestamp };
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
143
172
|
export interface NoticeTokens { pruning: number; revision: number; fidelity: number }
|
|
144
173
|
export interface ContextEstimate {
|
|
145
174
|
tokens: number;
|
|
@@ -190,7 +219,7 @@ export function checkpointContextMessages(summary: string, slots: TurnSlot[], fi
|
|
|
190
219
|
|
|
191
220
|
export function checkCheckpointBudget(summary: string, slots: TurnSlot[], fidelity: TurnFidelities,
|
|
192
221
|
entries: SessionEntry[], boundary: string, ctx: ExtensionContext): void {
|
|
193
|
-
if (Object.keys(fidelity).length) checkContextBudget(checkpointContextMessages(summary, slots, fidelity, entries, boundary), ctx, true);
|
|
222
|
+
if (Object.keys(fidelity).length) checkContextBudget(frameCheckpoint(checkpointContextMessages(summary, slots, fidelity, entries, boundary)), ctx, true);
|
|
194
223
|
}
|
|
195
224
|
|
|
196
225
|
/** UI-only, complete text/arguments/output preview; image bytes are identified,
|
|
@@ -11,14 +11,8 @@ import { MODE_LABELS, MODE_SYMBOLS } from "./turn-context.js";
|
|
|
11
11
|
import type { ContextEstimate, ContextEstimator, Fidelity, TurnFidelities, TurnMode, TurnSelection } from "./turn-context.js";
|
|
12
12
|
|
|
13
13
|
export const PREFLAG_ENTRY = "transparent-compact:aside-turn";
|
|
14
|
-
export const AUTO_FILTER_ENTRY = "transparent-compact:auto-filter";
|
|
15
14
|
export const FILTER_REVISION_ENTRY = "transparent-compact:filter-revision";
|
|
16
15
|
|
|
17
|
-
export function autoFilterEnabled(entries: SessionEntry[]): boolean {
|
|
18
|
-
const entry = entries.findLast((entry) => entry.type === "custom" && entry.customType === AUTO_FILTER_ENTRY);
|
|
19
|
-
return entry?.type === "custom" && (entry.data as { enabled?: boolean })?.enabled === true;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
16
|
/** Written immediately before the aside's user message is persisted. Consume
|
|
23
17
|
* once at that raw boundary; the timestamp guards against an interrupted append.
|
|
24
18
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foliox/transparent-compact-pi",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.3",
|
|
4
4
|
"description": "Model-free, deterministic, and self-aware compaction; with session-backed subagent context recovery, and optional context pruning and fidelity controls.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|