@0xkahi/pi-qol 1.0.6 → 1.1.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.
@@ -11,12 +11,14 @@ All captured prompt, tool, skill, context-file, and message content remains proc
11
11
 
12
12
  ## Architecture & Design Patterns
13
13
 
14
- - **Pure semantic model / pure functions**: `model.ts`, `measure.ts`, `usage.ts`, `ui/injections-model.ts`, `ui/usage-map.ts`, `ui/layout.ts`, `ui/skill-preview.ts` contain no pi or TUI API access and are independently unit-testable.
15
- - **State machines**: `InitialCaptureState` (capture-once) and `SilentProbeState` (single probe lifecycle) in `capture.ts` own explicit phases and transitions.
14
+ - **Pure semantic model / pure functions**: `model.ts`, `measure.ts`, `prompt-blocks.ts`, `prompt-additions.ts`, `usage.ts`, `ui/injections-model.ts`, `ui/usage-map.ts`, `ui/skill-preview.ts`, `ui/json-preview.ts`, and `ui/markers.ts` contain no pi or TUI API access and are independently unit-testable.
15
+ - **Process-local replay**: `transcript.ts` replays Pi 0.86 system messages (content appends, named section patches, tool add/remove deltas) into a `SystemState` so Usage measures the current branch's prompt and tools rather than today's loader metadata.
16
+ - **State machines**: `InitialCaptureState` (capture-once), `SilentProbeState` (single probe lifecycle), and `CompactionState` (compaction-active guard) in `capture.ts` own explicit phases and transitions.
17
+ - **Causal probe correlation**: `probe-token.ts` carries an `AsyncLocalStorage` token through this extension's own `sendUserMessage()` call, so lifecycle handlers recognize the probe run by causality instead of prompt text another extension may rewrite.
16
18
  - **Controller / data preparation**: `context-view-controller.ts` isolates the command/UI data path from the event-driven capture path.
17
19
  - **Stateful UI shell with stateful child tabs**: `ContextViewDialog` (shell) retains `UsageView` and `InjectionsView` instances; navigation is shared via `VimNavigation`. The shared modal presenter coordinates its semantic layout with the shell frame and host mounting.
20
+ - **Sanitize-before-persist**: `SilentProbeState` records only `role` and `timestamp` for synthetic messages; raw content is discarded. `text.ts` sanitizes every external string before it reaches the terminal.
18
21
  - **Event-driven registration**: `index.ts` hooks into `ExtensionAPI` events and only performs work when `config.isEnabled('context_view')` returns true.
19
- - **Sanitize-before-persist**: `SilentProbeState` records only `role` and `timestamp` for synthetic messages; raw content is discarded.
20
22
 
21
23
  ## Module Roles
22
24
 
@@ -24,47 +26,89 @@ All captured prompt, tool, skill, context-file, and message content remains proc
24
26
 
25
27
  Pure types shared by capture, measurement, and UI.
26
28
 
27
- - `InjectionItem`, `InjectionGroup`, `InitialSnapshot`: Initial-phase context decomposition.
28
- - `UsageCategory`, `UsagePreviewEntry`, `ContextUsageSnapshot`: Usage-view composition.
29
- - `ReportedContextUsage`, `InvisibleReasoningEstimate`: pi-reported usage metadata and reasoning-token estimates.
29
+ - Shared constants: `PI_SOURCE_ID`, `AGGREGATE_SOURCE_ID`, `PI_SOURCE`, `AGGREGATE_SOURCE` (label `unattributed`), `extensionSource()`, and the presentation labels `SYSTEM_PROMPT_LABEL`, `INSTRUCTION_FILES_LABEL`, `SKILLS_LABEL`, `BUILT_IN_TOOLS_LABEL`.
30
+ - Injection types: `InjectionItem`, `InjectionGroup`, `InitialSnapshot`, `InjectionSource`, `InjectionKind`, `InjectionPhase`, `CaptureOrigin`.
31
+ - Prompt-structure types: `TextSpan`, `JsonSpan`, `InjectedReference`, `InjectionSection`; items carry optional `sections`, `children`, `dropped`, `moved`, `jsonSpan`, `injectedReferences`, `requestOnly`, and `systemMessage` (`{ message: SystemMessage; index }`).
32
+ - Usage types: `UsageCategory`, `UsagePreviewEntry`, `ContextUsageSnapshot`, `ReportedContextUsage`, `InvisibleReasoningEstimate`.
30
33
  - `groupInjections()` / `buildSnapshot()`: group items by source with deterministic ordering (pi-native first, then extensions by size, aggregate last); items are copied to prevent later mutation.
31
34
 
35
+ ### `transcript.ts` — System-message replay
36
+
37
+ Pure replay of Pi 0.86 transcript-backed system state.
38
+
39
+ - `SystemMessage` (Pi's system-message shape), `SystemState` (`content`, `sections`, `tools`).
40
+ - `replaySystemMessages()`: content appends, sections patch by name (`null` deletes), removals precede additions, and replacing a name preserves insertion order; returns `undefined` for a legacy/empty transcript (not an explicitly empty state).
41
+ - `systemMessageText()`: content followed by non-deleted sections, matching Pi's complete-prompt rendering.
42
+ - `copySystemMessage()`: owned deep copy used when freezing request-only system patches.
43
+
44
+ ### `text.ts` — Terminal sanitizers
45
+
46
+ - `normalizePreviewText()`: normalize line endings/tabs and strip terminal strings, CSI/escape sequences, and control characters.
47
+ - `normalizeInlineText()`: preview text collapsed to one line.
48
+
32
49
  ### `measure.ts` — Prompt/tool measurement
33
50
 
34
51
  Pure measurement of the captured system prompt.
35
52
 
36
- - `analyzeSystemPrompt()`: splits the rendered system prompt into `base-prompt`, `append-prompt`, `context-file`, `skills`, `tool`, `prompt-addition` items.
37
- - `measureTools()`: per-tool definitions plus prompt snippets/guidelines carved from base prompt; built-in tools collapse into one aggregate pi-native item.
38
- - `measureContextFiles()`: extracts `<project_instructions>` file content without XML scaffolding.
39
- - `measureSkills()`: extracts `<available_skills>` section and each configured skill.
40
- - `measureAppendedPrompt()`: identifies `--append-system-prompt` text.
41
- - Uses a `Span` carving model to avoid double-counting base-prompt content; footer detection (`Current working directory: <cwd>`) separates pi base prompt from extension additions.
53
+ - `analyzeSystemPrompt(prompt, options, tools?, additions?)`: dual parser. Pi 0.86 XML sections are located by `prompt-blocks.ts`; generated records (`project_context`, `skills`) are split into semantic items unless overridden via `options.sections`, and unknown/overridden sections stay visible as System Prompt parts. The legacy 0.80–0.85 structural parser recognizes `<project_instructions>`, the skills block, tool bullet blocks, the block headers, and the CWD/date footer.
54
+ - `PromptOptionsSlice` (`cwd`, `homeDir`, `customPrompt`, `appendSystemPrompt`, `sections`, `contextFilePaths`, `skills`) and `ToolSlice` (`name`, `description`, `parametersJson`, `snippet`, `guidelines`, `source`).
55
+ - Builds the System Prompt item from labeled parts (Preamble, Available Tools, Guidelines, Documentation, Appended Prompt, Current Dir, Extension Additions), marks `dropped` parts a `--system-prompt` replacement suppressed and `moved` parts an extension relocated, attaches preview-only `injectedReferences` with exact offsets, marks JSON runs, and reconciles section/child token shares exactly.
56
+ - `measureTools()`: per-tool definition payloads plus prompt snippets/guidelines carved from pi's blocks; built-in tools collapse into one aggregate pi-native item.
57
+ - `measureContextFiles()`, `measureSkills()`, `measurePromptAdditions()`: Instruction Files and Skills aggregates plus owner-attributed additions.
58
+ - `textTokens()`: chars/4 heuristic matching pi's text estimate.
59
+
60
+ ### `prompt-blocks.ts` — Prompt block and section locator
42
61
 
43
- ### `capture.ts` — Capture-once state + silent probe
62
+ - `findPromptSections()`: locate Pi 0.86 top-level XML sections in rendered order, skipping whole sections and fenced examples.
63
+ - `findSectionToolBlocks()`: locate native `tools`/`rules` surfaces with bounded, consecutive bullet regions and positional (`moved`) markers.
64
+ - `findPromptBlocks()`: recover block headers and bullet regions independently of order, preferring the pre-footer occurrence and requiring exact active-tool snippet/guideline evidence before claiming a relocated block.
65
+ - Constants `AVAILABLE_TOOLS_BLOCK`, `GUIDELINES_BLOCK`, `DOCUMENTATION_BLOCK`, `BASE_PROMPT_BLOCKS`; types `PromptSection`, `LocatedPromptBlock`, `PromptBlockTool`.
44
66
 
45
- Stateful capture and the single allowed silent probe.
67
+ ### `prompt-additions.ts` — Addition attribution
46
68
 
47
- - `InitialCaptureState`: owns `prepare()` (every `before_agent_start`) and `finalize()` (first eligible `context` event). `snapshot` is frozen after the first successful finalization; `promptOptions` is kept current for the controller fallback.
48
- - `SilentProbeState`: manages the probe lifecycle (`idle → waiting → running → settled/failed`) and records synthetic message identities by `role + timestamp`. Restores persisted identities from `pi-context-view:probe-identities` custom session entries. Sanitizes aborted assistant messages into successful stop messages so the transcript does not show an operation-aborted row.
49
- - `measureInjectedMessages()`: diff the live provider `messages` against the session-branch baseline to identify context-only messages and custom messages.
69
+ Pure, deliberately heuristic attribution of text after pi's prompt footer.
70
+
71
+ - `splitPromptAdditions()`: bound blank-line blocks at this extension's handler position (`promptAtHandler`), keep recovered-block `excluded` spans separate, and guess an owner only on a unique package-name, path, or registered tool/command match; everything else is `unattributed`.
72
+ - `PromptSourceSlice` (public provenance only), `PromptAdditionOptions`, `PromptAdditionRun` (`text`, `source`, `tool`, `attribution: 'guess'`).
73
+
74
+ ### `capture.ts` — Capture state, compaction, and silent probe
75
+
76
+ Stateful capture, compaction tracking, and the single allowed silent probe.
77
+
78
+ - `InitialCaptureState`: `prepare()` (every `before_agent_start`, owning structured options and the handler-bounded prompt) and `finalize()` (first eligible `context` event). `snapshot` is frozen after the first successful finalization; `promptOptions` stays current for the controller fallback.
79
+ - `CompactionState`: tracks `session_before_compact` until success/abort/settlement, gating whether a silent probe is safe.
80
+ - `SilentProbeState`: owns the probe lifecycle (`idle → waiting → running → settled`), the correlation token, timeout, and exact synthetic `role + timestamp` identities. Restores persisted identities from `pi-context-view:probe-identities` custom session entries; sanitizes probe prompt/abort messages so the transcript shows no operation-aborted row.
81
+ - `parsePersistedIdentities()`: defensive parse of persisted probe identities.
50
82
  - `buildNativeSnapshot()`: view-local pi-native snapshot without freezing the main capture state.
51
- - `mergeContextOnlyMessages()`: overlays context-only messages from a frozen Initial snapshot onto the current snapshot.
83
+ - `buildUsageSnapshot()`: replays the branch's system messages plus frozen request-only system patches to measure the current prompt/tools.
84
+ - `mergeRequestOnlyMessages()`: overlays frozen non-system request-only messages onto a current snapshot.
85
+ - `copyPromptOptions()`, `collectPromptSources()`, `captureActiveTools()`, `measureInjectedMessages()`.
52
86
 
53
87
  ### `usage.ts` — Usage classification
54
88
 
55
89
  Pure composition of the Usage view.
56
90
 
57
- - `computeUsage()`: combines the frozen/captured snapshot with live filtered messages and reported usage into `ContextUsageSnapshot`.
58
- - `classifyPromptCategories()`: maps snapshot items into System Prompt, System Tools, Custom Tools, MCP Tools, Memory (AGENTS.md), Skills.
59
- - `classifyMessages()`: categorizes live messages into User Messages, Agent Text Messages, Agent Thinking Messages, Agent Tool Calls, Tool Output, Extension Messages, Compacted Data; handles invisible reasoning via `InvisibleReasoningEstimate` (provider-reported or signature-proxy).
91
+ - `computeUsage()`: combines the caller's current-state snapshot with live filtered messages and reported usage into `ContextUsageSnapshot`.
92
+ - `classifyPromptCategories()`: maps snapshot items into pi-qol's stable categories and order — System Prompt, System Tools, Custom Tools, MCP Tools, Memory (AGENTS.md), Skills — and returns prompt additions as per-owner categories.
93
+ - `classifyMessages()`: categorizes live messages and frozen request-only injections into User Messages, Agent Text Messages, Agent Thinking Messages, Agent Tool Call Messages, Tool Output (including Bash Executions), Extensions, and Compacted Data; handles invisible reasoning via `InvisibleReasoningEstimate` (provider-reported or signature-proxy).
60
94
  - `collectPreviewEntries()`: flattens a category for chronological preview rendering.
61
95
  - `toReportedUsage()`: converts pi's `ContextUsage` into the view model.
62
96
 
97
+ ### `settings.ts` — Compaction settings
98
+
99
+ - `readAutoCompactReserveTokens()`: read pi's merged `SettingsManager` compaction reserve (or `undefined` when disabled/unreadable) for the Usage map's buffer.
100
+ - `resolveAutoCompactReserveTokens()`: resolve a model's `compaction.modelOverrides` entry, else the ordinary reserve, else pi's default.
101
+ - `CompactionModel` (`provider`, `id`).
102
+
103
+ ### `probe-token.ts` — Probe correlation token
104
+
105
+ - `createProbeToken()`, `runWithProbeToken()`, `readProbeToken()`: an opaque, process-local token carried by `AsyncLocalStorage` through the probe's own `sendUserMessage()` async context.
106
+
63
107
  ### `context-view-controller.ts` — Data preparation
64
108
 
65
109
  Command/event data preparation and degraded native fallback.
66
110
 
67
- - `prepareContextViewData()`: waits for the agent to be idle, triggers the silent probe if no Initial snapshot exists, builds a current native snapshot from `getSystemPromptOptions()` / `getSystemPrompt()`, merges context-only messages, and computes usage.
111
+ - `prepareContextViewData()`: waits for the agent to be idle, triggers the silent probe if no Initial snapshot exists, builds a current branch snapshot from `getSystemPromptOptions()` / `getSystemPrompt()` (replaying transcript state and merging request-only messages), reads the compaction reserve, and computes usage.
68
112
  - Returns `ContextViewData` with `initial`, `usage`, and optional `degradedReason`.
69
113
 
70
114
  ### `index.ts` — Registration, lifecycle, persistence
@@ -74,15 +118,16 @@ Wires the extension into `ExtensionAPI`.
74
118
  - `registerContextView()`: lazy registration on the first enabled `session_start`.
75
119
  - `activateContextView()`: installs event handlers, restores/persists probe identities, and registers the command and Vim event.
76
120
  - Event handlers:
77
- - `session_start`: tracks latest context, restores probe identities.
78
- - `input`: observes empty extension inputs for the probe.
79
- - `before_agent_start`: begins probe run, prepares capture options.
80
- - `turn_start`: aborts real turn when the probe owns the run.
121
+ - `session_start`: tracks latest context, restores probe identities, clears compaction state.
122
+ - `session_before_compact` / `session_compact` / `session_compact_failed`: track the compaction-active guard.
123
+ - `input`: observes empty extension inputs for the probe and resets text earlier input transforms added to the synthetic prompt.
124
+ - `before_agent_start`: claims the probe run by token, prepares capture options and the handler-bounded prompt.
125
+ - `turn_start`: aborts the real turn when the probe owns the run.
81
126
  - `message_start`: records probe message identities.
82
- - `message_end`: sanitizes aborted probe assistant messages.
127
+ - `message_end`: sanitizes probe messages (blank prompt, empty successful stop for aborts).
83
128
  - `context`: filters probe messages, finalizes the Initial snapshot.
84
- - `agent_settled`: settles probe and persists new identities.
85
- - `session_shutdown`: fails probe and persists identities.
129
+ - `agent_settled`: settles the probe and persists new identities.
130
+ - `session_shutdown`: fails the probe and persists identities.
86
131
  - Command handler validates enabled flag, no arguments, and TUI mode before opening the dialog.
87
132
  - Vim event handler opens the dialog from the latest context.
88
133
 
@@ -117,7 +162,7 @@ Stateful Usage tab (`ModalTab`).
117
162
  Stateful Injections tab (`ModalTab`).
118
163
 
119
164
  - Renders the hierarchical Initial snapshot: groups (source), items, sub-items (children), and a non-selectable TOTAL row.
120
- - Preview (Enter) pushes a `PreviewLayer` showing the raw text of the selected injection item.
165
+ - Preview (Enter) pushes a `PreviewLayer` showing the raw text of the selected injection item, with section subheaders, dropped/moved markers, JSON expansion, and injected prompt-line references.
121
166
  - Tree rendering uses `├─`/`└─`/`│` prefixes and a stable shared value column.
122
167
  - Currently only the `[INITIAL]` tab is rendered; `[Runtime]` is intentionally hidden until implemented.
123
168
 
@@ -128,7 +173,7 @@ Pure presentation model for Injections.
128
173
  - `InjectionRow`: flattened row types (`group`, `item`, `separator`, `total`).
129
174
  - `buildInjectionRows()`: flattens `InitialSnapshot` into rows.
130
175
  - `collectItemsById()`: indexes items (including children) for preview lookup.
131
- - `normalizePreviewText()` / `normalizeInlineText()`: sanitize terminal escape sequences and collapse whitespace.
176
+ - `normalizePreviewText()` / `normalizeInlineText()` are re-exported from `text.ts` for previews.
132
177
  - `ListNavigator`/`PreviewScroller` moved to the shared modal library (`src/libs/modal/list-navigator.ts`).
133
178
 
134
179
  ### `ui/usage-map.ts`
@@ -138,12 +183,25 @@ Pure 14×14 proportional map model.
138
183
  - `buildUsageMap()`: assigns cells to categories by largest overlap; fills `full`, `partial`, `buffer`, or `free`.
139
184
  - `calculateFitMapScale()`: computes a Fit denominator with 115% headroom, capped at the reported context window and floored at 10,000 tokens.
140
185
 
141
- ### Shared modal library
186
+ ### `ui/json-preview.ts`
187
+
188
+ - `expandJsonSpan()`: expand a marked JSON run into pretty-printed text.
189
+ - `shiftJsonSpan()`: translate a JSON span when earlier text was removed for display.
190
+
191
+ ### `ui/markers.ts`
142
192
 
143
- `ui/navigation.ts` and `ui/layout.ts` were absorbed into `src/libs/modal/`:
193
+ - `ContextMarker` (`dropped`, `moved`, `guess`) with `MARKER_ORDER`.
194
+ - `droppedMarker()` / `movedMarker()` / `guessMarker()` and `markerLegendLines()`: themed glyphs and legend for prompt-part provenance.
144
195
 
145
- - `VimNavigationScheme` (`navigation/vim-scheme.ts`): maps `j/k`, arrows, `Ctrl+u/d`, `gg`, `G`, Enter, Esc/`q` into `NavigationAction`s; `PageUp`/`PageDown`/`Home`/`End` are intentionally swallowed.
146
- - `text.ts`: `calculateViewport()`, `fitToTerminalHeight()`, `fitLine()`, `spreadLine()`, `hintRow()`, `wrapDescriptionLines()`, `STEP_KEY_HINT`, `BODY_INDENT`.
196
+ ### `ui/wheel.ts` / `ui/wheel-preview-layer.ts`
197
+
198
+ - `parseWheelDirection()` / `readWheelScrollLines()`: decode terminal wheel input and configured scroll lines.
199
+ - `WheelPreviewLayer` (`ModalLayer`): a preview layer that scrolls on wheel events.
200
+
201
+ ### `ui/section-preview.ts`
202
+
203
+ - `previewLegendLines()` / `previewBodyLines()`: shared sectioned preview rendering (subheaders, JSON, references).
204
+ - `SectionedContent`, `PreviewDescriptionLayout`.
147
205
 
148
206
  ### `ui/skill-preview.ts`
149
207
 
@@ -155,32 +213,36 @@ Preview-only recognition of pi `<skill name="...">` wrappers.
155
213
 
156
214
  1. `registerContextView()` waits for the first enabled `session_start`, then calls `activateContextView()`.
157
215
  2. `activateContextView()` restores any persisted probe identities from custom session entries.
158
- 3. On `before_agent_start`, `capture.prepare()` saves owned prompt options; `probe.beginRun()` checks whether the empty input is an extension-originated probe.
159
- 4. On `context`, `probe.filterMessages()` removes synthetic probe messages; the remaining messages are diffed against the session baseline to identify context-only injections; `capture.finalize()` freezes the Initial snapshot.
216
+ 3. On `before_agent_start`, `capture.prepare()` saves owned prompt options and the handler-bounded prompt; `probe.beginRun()` claims the run by token.
217
+ 4. On `context`, `probe.filterMessages()` removes synthetic probe messages; the remaining messages are diffed against the session-branch baseline to identify request-only injections; `capture.finalize()` freezes the Initial snapshot.
160
218
  5. On `agent_settled`, the probe is settled and new identities are persisted to `pi-context-view:probe-identities`.
161
219
  6. When the user invokes `/context-view` or the Vim event, `prepareContextViewData()`:
162
220
  - waits for agent idle;
163
221
  - triggers a silent probe if no Initial snapshot exists;
164
- - builds a current native snapshot from live prompt/tool data;
165
- - merges context-only messages from the fallback snapshot;
166
- - computes the usage snapshot and opens `ContextViewDialog`.
222
+ - builds a current branch snapshot by replaying transcript system state and merging frozen request-only messages;
223
+ - reads the compaction reserve and computes the usage snapshot, then opens `ContextViewDialog`.
167
224
  7. The shared modal presenter opens `ContextViewDialog` using `context_view.layout`; the dialog starts on Usage, remains bounded to half terminal height, and routes input to the active tab while retaining both tab states.
168
225
 
169
226
  ## State Transitions
170
227
 
171
228
  ### InitialCaptureState
172
229
 
173
- - `prepare(options)` → stores `latestOptions` and `pendingPreparation` (only until snapshot frozen).
174
- - `finalize(input)` → if `initialSnapshot` is undefined, builds and freezes it; subsequent calls return the same snapshot.
230
+ - `prepare(options, promptAtHandler)` → stores latest options and `pendingPreparation` (only until snapshot frozen).
231
+ - `finalize(buildInput)` → if `initialSnapshot` is undefined, builds and freezes it; subsequent calls return the same snapshot.
232
+
233
+ ### CompactionState
234
+
235
+ - `begin(signal)` → tracks the active compaction signal.
236
+ - `finish()` → clears it after success/abort/settlement.
175
237
 
176
238
  ### SilentProbeState
177
239
 
178
240
  - `start()` → `idle → waiting`; creates a timeout; returns the existing completion on re-entry.
179
- - `observeInput(extension, '')` → sets `inputObserved`.
180
- - `beginRun('')` with `inputObserved` → `waiting → running` (or `*-after-timeout` if timeout already fired).
181
- - `recordMessage()` / `sanitizeAssistant()` → records identities and replaces aborted assistant messages.
241
+ - `isProbeInput(source, token)` with the matching token → the synthetic prompt is recognized.
242
+ - `beginRun(token)` with the matching token → `waiting → running`; a token-less run fails the attempt without arming the abort guard.
243
+ - `recordMessage()` / `sanitizeMessage()` → records identities and blanks probe prompt/abort messages.
182
244
  - `settle(captured)` → `running → settled`.
183
- - `fail(reason)` → any pending phase → `failed`.
245
+ - `fail(reason)` → resolves a pending attempt.
184
246
  - Identities are persisted only after settlement or shutdown.
185
247
 
186
248
  ### ContextViewDialog
@@ -192,8 +254,9 @@ Preview-only recognition of pi `<skill name="...">` wrappers.
192
254
  ## Integration Points
193
255
 
194
256
  - **Config**: `config-loader.isEnabled('context_view')` gates activation and command use; `config-loader.getContextView().layout` selects inline or overlay presentation (default `inline`).
195
- - **ExtensionAPI**: `pi.on(...)`, `pi.registerCommand(...)`, `pi.events.on(...)`, `pi.appendEntry(...)`, `pi.getAllTools()`, `pi.getActiveTools()`, `pi.sendUserMessage('')`.
196
- - **ExtensionContext**: `ctx.ui.custom<void>()`, `ctx.ui.notify()`, `ctx.abort()`, `ctx.getSystemPrompt()`, `ctx.getSystemPromptOptions()`, `ctx.getContextUsage()`, `ctx.waitForIdle()`, `ctx.mode`, `ctx.model`, `ctx.modelRegistry.hasConfiguredAuth()`, `ctx.sessionManager.getEntries()`, `ctx.sessionManager.getLeafId()`.
257
+ - **ExtensionAPI**: `pi.on(...)`, `pi.registerCommand(...)`, `pi.events.on(...)`, `pi.appendEntry(...)`, `pi.getAllTools()`, `pi.getActiveTools()`, `pi.getCommands()`, `pi.sendUserMessage('')`.
258
+ - **ExtensionContext**: `ctx.ui.custom<void>()`, `ctx.ui.notify()`, `ctx.abort()`, `ctx.getSystemPrompt()`, `ctx.getSystemPromptOptions()`, `ctx.getContextUsage()`, `ctx.waitForIdle()`, `ctx.mode`, `ctx.model`, `ctx.modelRegistry.hasConfiguredAuth()`, `ctx.sessionManager.getEntries()`, `ctx.sessionManager.getLeafId()`, `ctx.isProjectTrusted()`, `ctx.cwd`.
259
+ - **Pi host runtime**: `buildSessionContext`, `convertToLlm`, `estimateTokens`, `formatSize`, `SettingsManager`, `SystemMessage`/`ContextEvent` types, `ToolInfo`/`SlashCommandInfo`/`SourceInfo`.
197
260
  - **TUI**: `TUI`, `Theme`, `KeybindingsManager`, `Component`, `Focusable`, `Key`, `matchesKey`, `visibleWidth`, `wrapTextWithAnsi`.
198
261
  - **Modal library**: `src/libs/modal/` (`ModalDialog`, `VimNavigationScheme`, `ModalTab`, `PreviewLayer`, `ListNavigator`, `RenderCache`, text/layout helpers).
199
262
  - **Pi constants**: `piVimKeyEventId()` from `src/constants.ts`.
@@ -1,6 +1,21 @@
1
- import { buildSessionContext, type ExtensionAPI, type ExtensionContext, SettingsManager } from '@earendil-works/pi-coding-agent';
2
- import { buildNativeSnapshot, type CompactionState, type InitialCaptureState, mergeContextOnlyMessages, type SilentProbeState } from './capture';
1
+ import {
2
+ type BuildSystemPromptOptions,
3
+ buildSessionContext,
4
+ type ExtensionAPI,
5
+ type ExtensionCommandContext,
6
+ type ExtensionContext,
7
+ } from '@earendil-works/pi-coding-agent';
8
+ import {
9
+ buildNativeSnapshot,
10
+ buildUsageSnapshot,
11
+ type CompactionState,
12
+ collectPromptSources,
13
+ type InitialCaptureState,
14
+ type SilentProbeState,
15
+ } from './capture';
3
16
  import type { ContextUsageSnapshot, InitialSnapshot } from './model';
17
+ import { runWithProbeToken } from './probe-token';
18
+ import { readAutoCompactReserveTokens } from './settings';
4
19
  import { computeUsage, toReportedUsage } from './usage';
5
20
 
6
21
  export interface ContextViewData {
@@ -10,7 +25,7 @@ export interface ContextViewData {
10
25
  }
11
26
 
12
27
  type PromptContext = ExtensionContext & {
13
- getSystemPromptOptions?: () => Parameters<typeof buildNativeSnapshot>[0]['options'];
28
+ getSystemPromptOptions?: () => BuildSystemPromptOptions;
14
29
  waitForIdle?: () => Promise<void>;
15
30
  };
16
31
 
@@ -19,14 +34,8 @@ interface ContextViewDependencies {
19
34
  }
20
35
 
21
36
  /** Read Pi's effective merged compaction reserve; optional settings never block the view. */
22
- export function readAutoCompactReserveTokens(ctx: PromptContext): number | undefined {
23
- try {
24
- const settings = SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() });
25
- if (!settings.getCompactionEnabled()) return undefined;
26
- return settings.getCompactionReserveTokens();
27
- } catch {
28
- return undefined;
29
- }
37
+ function defaultReserveReader(ctx: PromptContext): number | undefined {
38
+ return readAutoCompactReserveTokens(ctx as unknown as ExtensionCommandContext);
30
39
  }
31
40
 
32
41
  /** Prepare Context View data without requiring command-only APIs for event callers. */
@@ -38,49 +47,78 @@ export async function prepareContextViewData(
38
47
  compaction: CompactionState,
39
48
  dependencies: ContextViewDependencies = {},
40
49
  ): Promise<ContextViewData> {
41
- if (ctx.waitForIdle) await ctx.waitForIdle();
42
50
  let initial = capture.snapshot;
43
51
  let degradedReason: string | undefined;
44
52
 
53
+ // A frozen Initial never needs the agent to settle first: opening the view
54
+ // during a run must show the captured state immediately, unlike a probe.
55
+ if (!initial) {
56
+ if (ctx.waitForIdle) await ctx.waitForIdle();
57
+ initial = capture.snapshot;
58
+ }
59
+
45
60
  if (!initial) {
46
61
  if (compaction.isActive) {
47
62
  degradedReason = 'Silent probe unavailable: context compaction is in progress. Extension additions were not observed.';
63
+ } else if (ctx.model === undefined) {
64
+ degradedReason = 'Silent probe unavailable: no model is selected. Extension additions were not observed.';
65
+ } else if (!ctx.modelRegistry.hasConfiguredAuth(ctx.model)) {
66
+ degradedReason = `Silent probe unavailable: ${ctx.model.provider} has no configured authentication. Extension additions were not observed.`;
48
67
  } else {
49
68
  const attempt = probe.start();
50
- if (attempt.started && ctx.model && ctx.modelRegistry.hasConfiguredAuth(ctx.model)) {
69
+ if (attempt.started) {
70
+ ctx.ui.setWorkingVisible(false);
51
71
  try {
52
- pi.sendUserMessage('');
72
+ // Pi emits `input` and `before_agent_start` from inside this call, so the
73
+ // token reaches both handlers and identifies the run even when another
74
+ // extension's input transform rewrites the prompt text.
75
+ runWithProbeToken(attempt.token, () => pi.sendUserMessage(''));
53
76
  } catch (error) {
54
77
  probe.fail(error instanceof Error ? error.message : String(error));
55
78
  }
56
- } else if (attempt.started) {
57
- probe.fail('Silent probe unavailable: no authenticated model is selected.');
58
79
  }
59
- const outcome = await attempt.completion;
60
- initial = capture.snapshot;
61
- if (!initial)
62
- degradedReason = `${outcome.status === 'failed' ? outcome.reason : 'Silent probe did not capture Initial.'} Extension additions were not observed.`;
80
+ try {
81
+ const outcome = await attempt.completion;
82
+ initial = capture.snapshot;
83
+ if (!initial) {
84
+ degradedReason = `${outcome.status === 'failed' ? outcome.reason : 'Silent probe did not capture Initial.'} Extension additions were not observed.`;
85
+ }
86
+ } finally {
87
+ if (attempt.started) ctx.ui.setWorkingVisible(true);
88
+ }
63
89
  }
64
90
  }
65
91
 
66
- const options = capture.promptOptions ?? ctx.getSystemPromptOptions?.();
92
+ const options = ctx.getSystemPromptOptions?.() ?? capture.promptOptions;
67
93
  if (!options) {
68
94
  throw new Error('Context View has not received prompt options yet. Start an agent turn and try again.');
69
95
  }
70
- const current = buildNativeSnapshot({
96
+ const allTools = pi.getAllTools();
97
+ const activeToolNames = pi.getActiveTools();
98
+ const promptSources = collectPromptSources(allTools, pi.getCommands());
99
+ const native = buildNativeSnapshot({
71
100
  systemPrompt: ctx.getSystemPrompt(),
72
101
  options,
73
- allTools: pi.getAllTools(),
74
- activeToolNames: pi.getActiveTools(),
102
+ allTools,
103
+ activeToolNames,
104
+ promptSources,
75
105
  });
76
- const fallback = initial ?? current;
106
+ const fallback = initial ?? native;
77
107
  const messages = probe.filterMessages(buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId()).messages);
78
- const reserveReader = dependencies.readAutoCompactReserveTokens ?? readAutoCompactReserveTokens;
108
+ const reserveReader = dependencies.readAutoCompactReserveTokens ?? defaultReserveReader;
79
109
  return {
80
110
  initial: fallback,
81
111
  degradedReason,
82
112
  usage: computeUsage({
83
- snapshot: mergeContextOnlyMessages(current, fallback),
113
+ snapshot: buildUsageSnapshot({
114
+ messages,
115
+ initial: fallback,
116
+ systemPrompt: ctx.getSystemPrompt(),
117
+ options,
118
+ allTools,
119
+ activeToolNames,
120
+ promptSources,
121
+ }),
84
122
  messages,
85
123
  reported: toReportedUsage(ctx.getContextUsage()),
86
124
  modelLabel: ctx.model?.id,
@@ -1,9 +1,17 @@
1
1
  import { buildSessionContext, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
2
  import type { ConfigLoader } from '../../config-loader';
3
3
  import { presentModal } from '../../libs/modal';
4
- import { CompactionState, InitialCaptureState, PROBE_IDENTITIES_CUSTOM_TYPE, parsePersistedIdentities, SilentProbeState } from './capture';
4
+ import {
5
+ CompactionState,
6
+ collectPromptSources,
7
+ InitialCaptureState,
8
+ PROBE_IDENTITIES_CUSTOM_TYPE,
9
+ parsePersistedIdentities,
10
+ SilentProbeState,
11
+ } from './capture';
5
12
  import { COMMAND_NAME, PI_VIM_KEY_EVENT_ID } from './constants';
6
13
  import { prepareContextViewData } from './context-view-controller';
14
+ import { readProbeToken } from './probe-token';
7
15
  import { ContextViewDialog } from './ui/context-view-dialog';
8
16
 
9
17
  function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; initialCtx: ExtensionContext }): void {
@@ -50,12 +58,18 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
50
58
  pi.on('session_compact', () => compaction.finish());
51
59
  pi.on('session_compact_failed', () => compaction.finish());
52
60
  pi.on('input', event => {
53
- if (enabled()) probe.observeInput(event.source, event.text);
61
+ if (!enabled()) return;
62
+ // Reset text earlier input transforms added to our own synthetic prompt:
63
+ // the probe carries no instructions, and its run is identified by token.
64
+ if (event.text === '' || !probe.isProbeInput(event.source, readProbeToken())) return undefined;
65
+ return { action: 'transform', text: '' } as const;
54
66
  });
55
67
  pi.on('before_agent_start', event => {
56
68
  if (!enabled()) return;
57
- probe.beginRun(event.prompt);
58
- capture.prepare(event.systemPromptOptions);
69
+ probe.beginRun(readProbeToken());
70
+ // The chained prompt here already carries additions from extensions loaded
71
+ // earlier; anything the context event adds came from extensions after us.
72
+ capture.prepare(event.systemPromptOptions, event.systemPrompt);
59
73
  });
60
74
  pi.on('turn_start', (_event, ctx) => {
61
75
  if (enabled() && probe.isCurrentRun) ctx.abort();
@@ -65,7 +79,7 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
65
79
  });
66
80
  pi.on('message_end', event => {
67
81
  if (!enabled()) return;
68
- const message = probe.sanitizeAssistant(event.message);
82
+ const message = probe.sanitizeMessage(event.message);
69
83
  return message === undefined ? undefined : { message };
70
84
  });
71
85
  pi.on('context', (event, ctx) => {
@@ -77,6 +91,7 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
77
91
  baselineMessages: probe.filterMessages(buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId()).messages),
78
92
  allTools: pi.getAllTools(),
79
93
  activeToolNames: pi.getActiveTools(),
94
+ promptSources: collectPromptSources(pi.getAllTools(), pi.getCommands()),
80
95
  origin: probe.isCurrentRun ? 'synthetic-probe' : 'real-turn',
81
96
  }));
82
97
  return messages === event.messages ? undefined : { messages };
@@ -89,7 +104,8 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
89
104
  });
90
105
  pi.on('session_shutdown', () => {
91
106
  compaction.finish();
92
- if (!enabled()) return;
107
+ // Once activated, cleanup runs even if config reloaded to disabled: the
108
+ // probe may already have written messages this runtime must identify.
93
109
  persistProbeIdentities();
94
110
  probe.fail('Session ended before the silent probe completed.');
95
111
  });