@0xkahi/pi-qol 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +24 -10
  2. package/assets/config.schema.json +5 -0
  3. package/package.json +4 -4
  4. package/src/extensions/context-view/capture.ts +74 -35
  5. package/src/extensions/context-view/codemap.md +24 -16
  6. package/src/extensions/context-view/constants.ts +3 -0
  7. package/src/extensions/context-view/context-view-controller.ts +47 -13
  8. package/src/extensions/context-view/index.ts +25 -9
  9. package/src/extensions/context-view/measure.ts +2 -1
  10. package/src/extensions/context-view/model.ts +44 -3
  11. package/src/extensions/context-view/presentation.ts +6 -0
  12. package/src/extensions/context-view/prompt-additions.ts +5 -3
  13. package/src/extensions/context-view/ui/codemap.md +60 -93
  14. package/src/extensions/context-view/ui/context-view-dialog.ts +14 -7
  15. package/src/extensions/context-view/ui/copy.ts +42 -0
  16. package/src/extensions/context-view/ui/highlight.ts +91 -0
  17. package/src/extensions/context-view/ui/injections-model.ts +52 -0
  18. package/src/extensions/context-view/ui/injections-view.ts +124 -27
  19. package/src/extensions/context-view/ui/search.ts +28 -0
  20. package/src/extensions/context-view/ui/searchable-preview.ts +175 -0
  21. package/src/extensions/context-view/ui/usage-block-layer.ts +18 -7
  22. package/src/extensions/context-view/ui/usage-view.ts +57 -24
  23. package/src/extensions/custom-footer/footer-component.ts +1 -1
  24. package/src/extensions/model-select/codemap.md +1 -1
  25. package/src/libs/modal/README.md +13 -6
  26. package/src/libs/modal/codemap.md +6 -6
  27. package/src/libs/modal/index.ts +1 -1
  28. package/src/libs/modal/modal-dialog.ts +44 -3
  29. package/src/libs/modal/preview-layer.ts +3 -3
  30. package/src/libs/modal/sectioned-modal.ts +3 -3
  31. package/src/libs/modal/types.ts +11 -0
  32. package/src/libs/subscription-usage/codemap.md +4 -3
  33. package/src/libs/subscription-usage/credential-resolver.ts +12 -4
  34. package/src/libs/subscription-usage/index.ts +1 -0
  35. package/src/libs/subscription-usage/provider-color.ts +1 -0
  36. package/src/libs/subscription-usage/strategy/opencode-go-usage.strategy.ts +45 -0
  37. package/src/libs/subscription-usage/subscription-usage-api.util.ts +4 -1
  38. package/src/libs/subscription-usage/subscription-usage-cache.ts +11 -1
  39. package/src/schemas/context-view.config.schema.ts +2 -0
  40. package/src/extensions/context-view/ui/wheel-preview-layer.ts +0 -104
  41. package/src/extensions/context-view/ui/wheel.ts +0 -66
package/README.md CHANGED
@@ -48,10 +48,11 @@ Favourites, ordered custom group tabs, provider filtering, and inline or overlay
48
48
  - **shared filtering** across Favourites, group, and Search tabs
49
49
  - **bidirectional tab navigation** with Tab and Shift+Tab
50
50
  - **provider filtering** for Search without removing models from favourite tabs
51
- - **sections**: opens on Select Model; `Ctrl+]` switches to the next section and
52
- `Ctrl+[` to the previous (both wrap). Without the Kitty keyboard protocol,
53
- `Ctrl+[` acts as Esc instead. Tab/Shift+Tab stay within the active section.
54
- - **Usage**: `[Claude]` and `[Codex]` tabs show every subscription rate window,
51
+ - **sections**: opens on Select Model; `Ctrl+L` switches to the next section and
52
+ `Ctrl+H` to the previous (both wrap). `Ctrl+H` needs a terminal that reports it
53
+ distinctly (Kitty, CSI-u, or modifyOtherKeys); otherwise it acts as Backspace.
54
+ `Ctrl+L` works everywhere. Tab/Shift+Tab stay within the active section.
55
+ - **Usage**: `[Claude]` `[Codex]` `[OC-GO]` tabs show every subscription rate window,
55
56
  separated by blank lines, with a progress bar, used percentage, reset time,
56
57
  pace, and data freshness. Fixed provider colors match the custom footer. Missing
57
58
  credentials and request failures are shown explicitly. Usage shares the footer
@@ -65,9 +66,13 @@ allow keybindings with [pi-vim-keys](https://github.com/0xKahi/pi-vim-keys) with
65
66
 
66
67
  Replaces pi's built-in interactive footer with the same three-line layout, but
67
68
  shows the current directory as an icon plus basename, supports hex color overrides,
68
- can hide token/cache clusters, and adds an OAuth subscription-usage progress bar
69
- for supported providers (Anthropic and OpenAI Codex). Usage colors are fixed:
70
- Claude `#D97706` and Codex `#10B981`; former usage-color overrides are ignored.
69
+ can hide token/cache clusters, and adds a subscription-usage progress bar
70
+ for supported providers (Anthropic, OpenAI Codex, and OpenCode Go via model provider
71
+ `opencode-go`, not OpenCode Zen `opencode`). Usage colors are fixed: Claude
72
+ `#D97706`, Codex `#10B981`, and OC-GO `#00ADD8`; former usage-color overrides are ignored.
73
+ OpenCode Go shows `5h`, `Week`, and `Month` windows and requires an `opencode-go`
74
+ entry of type `api_key` in `~/.pi/agent/auth.json`, with the secret in `key`;
75
+ `OPENCODE_API_KEY` alone is not used. Claude and Codex require OAuth entries.
71
76
 
72
77
  - **Directory line** — optional inverse-styled agent badge followed by the
73
78
  directory icon + basename, with optional git branch and session name. The badge
@@ -77,7 +82,7 @@ Claude `#D97706` and Codex `#10B981`; former usage-color overrides are ignored.
77
82
  right-aligned model name (with provider prefix when multiple providers are
78
83
  available).
79
84
  - **Subscription usage** — a colored progress bar plus percentage and reset time
80
- for the active OAuth provider. Usage is fetched lazily and cached, refreshing
85
+ for the active subscription provider. Usage is fetched lazily and cached, refreshing
81
86
  at most once every 60 seconds per provider; auth/network failures simply hide
82
87
  the segment.
83
88
 
@@ -128,7 +133,8 @@ them (project overrides global):
128
133
  },
129
134
  "context_view": {
130
135
  "enabled": true,
131
- "layout": "inline"
136
+ "layout": "inline",
137
+ "auto_probing": true
132
138
  },
133
139
  "custom_footer": {
134
140
  "enabled": true,
@@ -197,10 +203,18 @@ Duplicate favourite declarations remain first-entry-wins.
197
203
  | --------- | --------- | ------- | ----------- |
198
204
  | `enabled` | `boolean` | `false` | Enable the Context View capture and interface. |
199
205
  | `layout` | `enum` | `inline` | Context View presentation: `inline` or centered `overlay`. |
206
+ | `auto_probing` | `boolean` | `true` | Turn the silent initial-capture probe on/off; ordinary turn capture remains enabled. |
200
207
 
201
208
  ### Context View
202
209
 
203
- Context View is a fork of Dmitry Makarov's [pi-context-view](https://github.com/dimk90/pi-context-view), adapted into one unified tabbed interface with Vim-friendly keybindings. Enable it, then run `/context-view` with no arguments. The Usage tab opens first; Tab and Shift+Tab switch between Usage and Injections. Use `j`/`k` or arrows to move, `Ctrl+u`/`Ctrl+d` to move by a page, `gg`/`G` to jump to the beginning/end, Enter to preview, and Esc or `q` to return or close. By default it opens inline; set `context_view.layout` to `overlay` for a centered overlay. Other extensions can open the same view by emitting `pi.vimKeys.event:pi-qol.context_view`.
210
+ Context View is a fork of Dmitry Makarov's [pi-context-view](https://github.com/dimk90/pi-context-view), aligned with upstream v0.8.3 and adapted into one unified tabbed interface with Vim-friendly keybindings. **Context View requires Pi 0.87+** for system-inclusive capture. Enable it, then run `/context-view` with no arguments. The Usage tab opens first; Tab and Shift+Tab switch between Usage and Injections. Use `j`/`k` or arrows to move, `Ctrl+u`/`Ctrl+d` to move by a page, `gg`/`G` to jump to the beginning/end, Enter to preview, and Esc or `q` to return or close. By default it opens inline; set `context_view.layout` to `overlay` for a centered overlay. Other extensions can open the same view by emitting `pi.vimKeys.event:pi-qol.context_view`.
211
+
212
+ #### Context View keys
213
+
214
+ - **Injections filter**: `/` edits the filter; Tab/Shift+Tab toggles Name/Content mode while editing, Enter confirms, and Esc clears. Name matches retain subtrees; Content matches preview text. Matching is literal and case-insensitive.
215
+ - **Preview search**: `/` searches rendered text in injection and complete-content previews; Enter confirms, then `n`/`N` moves to the next/previous match with wrap-around. Esc clears while editing. To clear a confirmed filter or search, press `/` then Esc; outside editing, Esc goes back/closes. The Usage block stream itself does not bind `/`.
216
+ - **Copy**: `y` copies the selected injection item's raw text, a group's filter-visible content, a Usage category's chronological entries, the selected Usage block's full text, or the open preview's full raw content. Buffer/free rows have nothing to copy. Clipboard availability depends on the terminal/host; success, empty content, and failures produce a footer notice.
217
+ - **Usage percentages**: `p` switches category percentages between share of the context **window** (default) and estimated context **used**, when either denominator is positive. Used mode omits buffer/free percentages; the summary always uses the window. This is independent of `z` map zoom.
204
218
 
205
219
  #### `custom_footer`
206
220
 
@@ -266,6 +266,7 @@
266
266
  "context_view": {
267
267
  "default": {
268
268
  "enabled": false,
269
+ "auto_probing": true,
269
270
  "layout": "inline"
270
271
  },
271
272
  "type": "object",
@@ -274,6 +275,10 @@
274
275
  "default": false,
275
276
  "type": "boolean"
276
277
  },
278
+ "auto_probing": {
279
+ "default": true,
280
+ "type": "boolean"
281
+ },
277
282
  "layout": {
278
283
  "default": "inline",
279
284
  "type": "string",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xkahi/pi-qol",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "description": "quality of life pi extensions",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -45,9 +45,9 @@
45
45
  "devDependencies": {
46
46
  "@biomejs/biome": "^2.4.15",
47
47
  "@changesets/cli": "^2.31.0",
48
- "@earendil-works/pi-ai": "^1.3.0",
49
- "@earendil-works/pi-coding-agent": "^1.3.0",
50
- "@earendil-works/pi-tui": "^1.3.0",
48
+ "@earendil-works/pi-ai": "^1.5.0",
49
+ "@earendil-works/pi-coding-agent": "^1.5.0",
50
+ "@earendil-works/pi-tui": "^1.5.0",
51
51
  "@types/bun": "latest",
52
52
  "@types/node": "^24.0.0",
53
53
  "bun-types": "latest",
@@ -80,16 +80,16 @@ export interface SyntheticMessageIdentity {
80
80
  interface CapturePreparation {
81
81
  readonly promptOptions: PromptOptionsSlice;
82
82
  readonly toolSnippets?: Readonly<Record<string, string>>;
83
+ readonly hiddenTools?: readonly string[];
83
84
  /** Prompt as of this extension's own handler, bounding later extensions' additions. */
84
85
  readonly promptAtHandler?: string;
85
86
  }
86
87
 
87
88
  /**
88
- * Lifecycle of the single probe attempt. Ownership outlives the attempt's own
89
- * completion, so a probe run arriving after a timeout or after an unattributed
90
- * run is still claimed, aborted, and sanitized.
89
+ * Lifecycle of the single probe attempt. Failed claims release ownership so
90
+ * unrelated or nested runs can never arm the abort guard.
91
91
  */
92
- type ProbePhase = 'idle' | 'waiting' | 'running' | 'settled';
92
+ type ProbePhase = 'idle' | 'waiting' | 'claimed' | 'running' | 'settled';
93
93
 
94
94
  /**
95
95
  * Capture-once state machine. `prepare()` refreshes the structured options on
@@ -123,6 +123,7 @@ export class InitialCaptureState {
123
123
  this.pendingPreparation = {
124
124
  promptOptions: copyPromptOptions(options),
125
125
  toolSnippets: options.toolSnippets === undefined ? undefined : { ...options.toolSnippets },
126
+ hiddenTools: options.hiddenTools?.slice(),
126
127
  promptAtHandler,
127
128
  };
128
129
  }
@@ -141,6 +142,7 @@ export class InitialCaptureState {
141
142
  const preparation = this.pendingPreparation;
142
143
  const tools = captureActiveTools(input.allTools, input.activeToolNames, {
143
144
  toolSnippets: preparation.toolSnippets,
145
+ hiddenTools: preparation.hiddenTools,
144
146
  });
145
147
  const items = [
146
148
  ...analyzeSystemPrompt(input.systemPrompt, preparation.promptOptions, tools, {
@@ -193,17 +195,26 @@ export class CompactionState {
193
195
  */
194
196
  export class SilentProbeState {
195
197
  private phase: ProbePhase = 'idle';
198
+ private recordedUser = false;
196
199
  private readonly identities = new Map<string, SyntheticMessageIdentity>();
197
200
  private attempt: ProbeAttempt | undefined;
198
201
  private resolveCompletion: ((outcome: ProbeOutcome) => void) | undefined;
199
202
  private outcome: ProbeOutcome | undefined;
200
203
  private timeout: NodeJS.Timeout | undefined;
201
204
 
202
- /** True while the probe owns the in-flight agent run (including after a timeout). */
205
+ /** True only after a successful run claim, until settlement or failure. */
203
206
  public get isCurrentRun(): boolean {
204
207
  return this.phase === 'running';
205
208
  }
206
209
 
210
+ public get isPending(): boolean {
211
+ return this.phase === 'waiting' || this.phase === 'claimed';
212
+ }
213
+
214
+ public ownsAttemptToken(token: ProbeToken | undefined): boolean {
215
+ return this.ownsToken(token);
216
+ }
217
+
207
218
  /** Defensive copies of the recorded probe message identities. */
208
219
  public get syntheticMessages(): readonly SyntheticMessageIdentity[] {
209
220
  return [...this.identities.values()].map(identity => ({ ...identity }));
@@ -235,7 +246,7 @@ export class SilentProbeState {
235
246
  this.resolveCompletion = resolve;
236
247
  });
237
248
  this.timeout = setTimeout(() => {
238
- this.resolve({ status: 'failed', reason: 'Silent probe timed out.' });
249
+ this.fail('Silent probe timed out (timeout).');
239
250
  }, timeoutMs);
240
251
  this.attempt = { started: true, token: createProbeToken(), completion };
241
252
  return this.attempt;
@@ -246,21 +257,30 @@ export class SilentProbeState {
246
257
  * is causal rather than textual: the token is visible only inside the async
247
258
  * context of this extension's own `sendUserMessage()` call.
248
259
  */
249
- public isProbeInput(source: InputSource, token: ProbeToken | undefined): boolean {
250
- return this.phase === 'waiting' && source === 'extension' && this.ownsToken(token);
260
+ public isProbeInput(source: InputSource, token: ProbeToken | undefined, streamingBehavior?: 'steer' | 'followUp'): boolean {
261
+ if (!this.ownsToken(token)) return false;
262
+ if (this.phase === 'claimed' || this.phase === 'running') {
263
+ this.fail('Silent probe failed (nested-send): the empty probe prompt may reach the model.');
264
+ return false;
265
+ }
266
+ if (this.phase !== 'waiting' || source !== 'extension' || streamingBehavior !== undefined) return false;
267
+ this.phase = 'claimed';
268
+ return true;
251
269
  }
252
270
 
253
271
  /**
254
272
  * Claim the run this probe started, identified by the token it carries. A run
255
273
  * without the token is not provably ours, so it fails the attempt instead of
256
- * activating the abort guard: it may belong to the user or to another
257
- * extension and must run untouched. Ownership stays open afterwards so a
258
- * delayed probe run is still claimed.
274
+ * activating the abort guard: foreign runs and delayed sends stay untouched.
259
275
  */
260
- public beginRun(token: ProbeToken | undefined): boolean {
261
- if (this.phase !== 'waiting') return false;
262
- if (!this.ownsToken(token)) {
263
- this.fail('Another agent run started before the silent probe was recognized.');
276
+ public beginRun(token: ProbeToken | undefined, messageType: 'user' | 'custom' = 'user'): boolean {
277
+ if (this.phase === 'running') {
278
+ this.fail('Silent probe failed (foreign-run): another agent run started during the silent probe.');
279
+ return false;
280
+ }
281
+ if (this.phase !== 'waiting' && this.phase !== 'claimed') return false;
282
+ if (messageType !== 'user' || !this.ownsToken(token)) {
283
+ this.fail('Silent probe failed (foreign-run): another agent run started before the silent probe was recognized.');
264
284
  return false;
265
285
  }
266
286
  this.phase = 'running';
@@ -269,7 +289,12 @@ export class SilentProbeState {
269
289
 
270
290
  /** Record probe user/assistant identities as their message events arrive. */
271
291
  public recordMessage(message: ContextEvent['messages'][number]): void {
272
- if (!this.isCurrentRun || (message.role !== 'user' && message.role !== 'assistant')) return;
292
+ if (!this.isCurrentRun) return;
293
+ if (message.role === 'user') {
294
+ if (this.recordedUser) return;
295
+ this.recordedUser = true;
296
+ }
297
+ if (!qualifiesProbeMessage(message)) return;
273
298
  const identity = { role: message.role, timestamp: message.timestamp } satisfies SyntheticMessageIdentity;
274
299
  this.identities.set(identityKey(identity), identity);
275
300
  }
@@ -280,7 +305,7 @@ export class SilentProbeState {
280
305
  * model contexts; blanking keeps them out of the transcript.
281
306
  */
282
307
  public sanitizeMessage(message: ContextEvent['messages'][number]): ContextEvent['messages'][number] | undefined {
283
- if (!this.isCurrentRun) return undefined;
308
+ if (!qualifiesProbeMessage(message)) return undefined;
284
309
  if (message.role === 'user') return this.blankProbePrompt(message);
285
310
  if (message.role === 'assistant') return this.blankProbeAbort(message);
286
311
  return undefined;
@@ -290,7 +315,7 @@ export class SilentProbeState {
290
315
  public filterMessages(messages: ContextEvent['messages']): ContextEvent['messages'] {
291
316
  if (this.identities.size === 0) return messages;
292
317
  return messages.filter(message => {
293
- if (message.role !== 'user' && message.role !== 'assistant') return true;
318
+ if (!qualifiesProbeMessage(message)) return true;
294
319
  return !this.identities.has(identityKey(message));
295
320
  });
296
321
  }
@@ -304,11 +329,11 @@ export class SilentProbeState {
304
329
  }
305
330
 
306
331
  /**
307
- * End a pending attempt during shutdown or a synchronous startup failure.
308
- * Ownership is untouched: only the attempt's own completion is resolved.
332
+ * End a pending attempt and release the abort guard.
309
333
  */
310
334
  public fail(reason: string): void {
311
335
  if (this.attempt === undefined) return;
336
+ this.phase = 'settled';
312
337
  this.resolve({ status: 'failed', reason });
313
338
  }
314
339
 
@@ -327,7 +352,7 @@ export class SilentProbeState {
327
352
  * setup as an error instead of the legacy aborted stop reason.
328
353
  */
329
354
  private blankProbeAbort(message: Extract<ContextEvent['messages'][number], { role: 'assistant' }>): ContextEvent['messages'][number] | undefined {
330
- const isProbeAbort = message.stopReason === 'aborted' || (message.stopReason === 'error' && message.errorMessage === SETUP_ABORT_ERROR_MESSAGE);
355
+ const isProbeAbort = message.stopReason === 'error' && message.errorMessage === SETUP_ABORT_ERROR_MESSAGE;
331
356
  if (!isProbeAbort || !this.ownsMessage(message)) return undefined;
332
357
  return { ...message, content: [], stopReason: 'stop', errorMessage: undefined };
333
358
  }
@@ -402,18 +427,21 @@ export function buildUsageSnapshot(input: UsageSnapshotInput): InitialSnapshot {
402
427
  const state = replaySystemMessages([...input.messages, ...patches]);
403
428
  if (state === undefined) return mergeRequestOnlyMessages(buildNativeSnapshot(input), input.initial);
404
429
  const registered = new Map(input.allTools.map(tool => [tool.name, tool]));
405
- const tools: ToolSlice[] = state.tools.map(tool => {
406
- const metadata = registered.get(tool.name);
407
- const snippetLine = state.sections.tools?.split('\n').find(line => line.startsWith(`- ${tool.name}: `));
408
- return {
409
- name: tool.name,
410
- description: tool.description,
411
- parametersJson: JSON.stringify(tool.parameters),
412
- snippet: snippetLine?.slice(`- ${tool.name}: `.length),
413
- guidelines: normalizeGuidelines(metadata?.promptGuidelines),
414
- source: metadata?.sourceInfo.source ?? 'unattributed',
415
- };
416
- });
430
+ const tools: ToolSlice[] = state.tools
431
+ .filter(tool => registered.get(tool.name)?.exposure !== 'hidden' && !input.options.hiddenTools?.includes(tool.name))
432
+ .map(tool => {
433
+ const metadata = registered.get(tool.name);
434
+ const snippetLine = state.sections.tools?.split('\n').find(line => line.startsWith(`- ${tool.name}: `));
435
+ return {
436
+ name: tool.name,
437
+ description: tool.description,
438
+ parametersJson: JSON.stringify(tool.parameters),
439
+ snippet: snippetLine?.slice(`- ${tool.name}: `.length),
440
+ guidelines: normalizeGuidelines(metadata?.promptGuidelines),
441
+ source: metadata?.sourceInfo.source ?? 'unattributed',
442
+ path: metadata?.sourceInfo.path,
443
+ };
444
+ });
417
445
  const options = copyPromptOptions(input.options);
418
446
  const items = analyzeSystemPrompt(
419
447
  systemMessageText(state),
@@ -507,12 +535,12 @@ function addPromptSource(sources: Map<string, CollectedPromptSource>, sourceInfo
507
535
  export function captureActiveTools(
508
536
  allTools: readonly ToolInfo[],
509
537
  activeToolNames: readonly string[],
510
- options: { readonly toolSnippets?: Readonly<Record<string, string>> },
538
+ options: { readonly toolSnippets?: Readonly<Record<string, string>>; readonly hiddenTools?: readonly string[] },
511
539
  ): ToolSlice[] {
512
540
  const byName = new Map(allTools.map(tool => [tool.name, tool]));
513
541
  return [...new Set(activeToolNames)]
514
542
  .map(name => byName.get(name))
515
- .filter(tool => tool !== undefined)
543
+ .filter((tool): tool is ToolInfo => tool !== undefined && tool.exposure !== 'hidden' && !options.hiddenTools?.includes(tool.name))
516
544
  .map(tool => ({
517
545
  name: tool.name,
518
546
  description: tool.description,
@@ -520,6 +548,7 @@ export function captureActiveTools(
520
548
  snippet: options.toolSnippets?.[tool.name],
521
549
  guidelines: normalizeGuidelines(tool.promptGuidelines),
522
550
  source: tool.sourceInfo.source,
551
+ path: tool.sourceInfo.path,
523
552
  }));
524
553
  }
525
554
 
@@ -634,6 +663,16 @@ function serializedPreview(text: string): MessagePreview {
634
663
  return { text, jsonSpan: { start: 0, end: text.length } };
635
664
  }
636
665
 
666
+ /** Identity alone is never sufficient: same-millisecond real messages must survive. */
667
+ function qualifiesProbeMessage(
668
+ message: ContextEvent['messages'][number],
669
+ ): message is Extract<ContextEvent['messages'][number], { role: 'user' | 'assistant' }> {
670
+ if (message.role === 'user') {
671
+ return typeof message.content === 'string' ? message.content === '' : message.content.every(block => block.type === 'text' && block.text === '');
672
+ }
673
+ return message.role === 'assistant' && message.stopReason === 'error' && message.errorMessage === SETUP_ABORT_ERROR_MESSAGE;
674
+ }
675
+
637
676
  /** Map key uniquely identifying one probe message by role and timestamp. */
638
677
  function identityKey(identity: SyntheticMessageIdentity): string {
639
678
  return `${identity.role}:${identity.timestamp}`;
@@ -30,6 +30,7 @@ Pure types shared by capture, measurement, and UI.
30
30
  - Injection types: `InjectionItem`, `InjectionGroup`, `InitialSnapshot`, `InjectionSource`, `InjectionKind`, `InjectionPhase`, `CaptureOrigin`.
31
31
  - Prompt-structure types: `TextSpan`, `JsonSpan`, `InjectedReference`, `InjectionSection`; items carry optional `sections`, `children`, `dropped`, `moved`, `jsonSpan`, `injectedReferences`, `requestOnly`, and `systemMessage` (`{ message: SystemMessage; index }`).
32
32
  - Usage types: `UsageCategory`, `UsagePreviewEntry`, `ContextUsageSnapshot`, `ReportedContextUsage`, `InvisibleReasoningEstimate`.
33
+ - `extensionSource(source, path)` keys path-loaded `local`/`auto`/`cli` extensions as `tool-source:${source}:${path}`; prompt and tool sources share this keying. Snapshot labels use the shortest unique trailing path suffix after dropping `index.ts`/`index.js`; package labels remain unchanged.
33
34
  - `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.
34
35
 
35
36
  ### `transcript.ts` — System-message replay
@@ -75,14 +76,15 @@ Pure, deliberately heuristic attribution of text after pi's prompt footer.
75
76
 
76
77
  Stateful capture, compaction tracking, and the single allowed silent probe.
77
78
 
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
+ - `InitialCaptureState`: `prepare()` (every `before_agent_start`, owning structured options and the handler-bounded prompt) and `finalize()` (first eligible `context_with_system` event). `snapshot` is frozen after the first successful finalization; `promptOptions` stays current for the controller fallback.
79
80
  - `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
+ - `SilentProbeState`: owns the probe lifecycle (`idle → waiting → claimed → 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
82
  - `parsePersistedIdentities()`: defensive parse of persisted probe identities.
82
83
  - `buildNativeSnapshot()`: view-local pi-native snapshot without freezing the main capture state.
83
84
  - `buildUsageSnapshot()`: replays the branch's system messages plus frozen request-only system patches to measure the current prompt/tools.
84
85
  - `mergeRequestOnlyMessages()`: overlays frozen non-system request-only messages onto a current snapshot.
85
86
  - `copyPromptOptions()`, `collectPromptSources()`, `captureActiveTools()`, `measureInjectedMessages()`.
87
+ - Active-tool measurement excludes `exposure === 'hidden'` and names in `systemPromptOptions.hiddenTools` (missing means empty), both during capture and in native/replayed controller fallbacks.
86
88
 
87
89
  ### `usage.ts` — Usage classification
88
90
 
@@ -108,7 +110,8 @@ Pure composition of the Usage view.
108
110
 
109
111
  Command/event data preparation and degraded native fallback.
110
112
 
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.
113
+ - `prepareContextViewData()`: opens frozen snapshots immediately; otherwise checks probe safety and may trigger the silent probe. Builds a current branch snapshot from `getSystemPromptOptions()` / `getSystemPrompt()` (replaying transcript state and merging request-only messages), reads the compaction reserve, and computes usage.
114
+ - `checkProbeStartConditions()` checks in order: `auto_probing`, `canPresent`, wait for idle (or verify idle if waiting is unavailable), compaction inactive, no pending input, selected model, non-virtual model, configured auth, then trusted merged settings readability, idle cache warming disabled, and usage below `shouldCompact` threshold. Settings errors block probing; unknown usage does not. Rejections do not consume the single attempt; reasons feed the degraded native fallback.
112
115
  - Returns `ContextViewData` with `initial`, `usage`, and optional `degradedReason`.
113
116
 
114
117
  ### `index.ts` — Registration, lifecycle, persistence
@@ -125,7 +128,8 @@ Wires the extension into `ExtensionAPI`.
125
128
  - `turn_start`: aborts the real turn when the probe owns the run.
126
129
  - `message_start`: records probe message identities.
127
130
  - `message_end`: sanitizes probe messages (blank prompt, empty successful stop for aborts).
128
- - `context`: filters probe messages, finalizes the Initial snapshot.
131
+ - `context`: filters probe messages before later context handlers see them.
132
+ - `context_with_system`: observe-only finalization; returns nothing, locally re-filters probe messages, skips Pi's leading complete system prompt (already measured), and captures other system-role additions.
129
133
  - `agent_settled`: settles the probe and persists new identities.
130
134
  - `session_shutdown`: fails the probe and persists identities.
131
135
  - Command handler validates enabled flag, no arguments, and TUI mode before opening the dialog.
@@ -153,7 +157,7 @@ Stateful Usage tab (`ModalTab`).
153
157
 
154
158
  - Renders a proportional 14×14 context-window map (`UsageMap`), category legend, and reported/estimated summary within the shell-provided content height.
155
159
  - Map scale toggles between `window` (reported context window) and `fit` (115% headroom, rounded to 2 significant digits) with `z` when applicable.
156
- - Preview (Enter) pushes a `PreviewLayer` showing chronological content entries for the selected category; scrolling/paging/bounds are handled by the layer via shell navigation actions.
160
+ - Preview (Enter) pushes a chronological `UsageBlockLayer`; truncated blocks open a complete-content `SearchablePreview`. `y` copies category entries or the selected block. `p` toggles category percentage basis between window and estimated used tokens, independently of map zoom; the summary stays window-based.
157
161
  - Handles invisible-reasoning metadata display in Agent Thinking Messages.
158
162
  - Caches rendered output via the library's `RenderCache` and invalidates on theme/selection/scroll changes.
159
163
 
@@ -162,7 +166,8 @@ Stateful Usage tab (`ModalTab`).
162
166
  Stateful Injections tab (`ModalTab`).
163
167
 
164
168
  - Renders the hierarchical Initial snapshot: groups (source), items, sub-items (children), and a non-selectable TOTAL row.
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.
169
+ - `/` edits a Name/Content filter (Tab/Shift+Tab toggle mode, Enter confirms, Esc clears while editing); fixed-height rendering reserves a prompt/status row. `y` copies item text or filter-visible group content.
170
+ - Preview (Enter) pushes a `SearchablePreview` showing the raw text of the selected injection item, with section subheaders, dropped/moved markers, JSON expansion, and injected prompt-line references.
166
171
  - Tree rendering uses `├─`/`└─`/`│` prefixes and a stable shared value column.
167
172
  - Currently only the `[INITIAL]` tab is rendered; `[Runtime]` is intentionally hidden until implemented.
168
173
 
@@ -193,10 +198,13 @@ Pure 14×14 proportional map model.
193
198
  - `ContextMarker` (`dropped`, `moved`, `guess`) with `MARKER_ORDER`.
194
199
  - `droppedMarker()` / `movedMarker()` / `guessMarker()` and `markerLegendLines()`: themed glyphs and legend for prompt-part provenance.
195
200
 
196
- ### `ui/wheel.ts` / `ui/wheel-preview-layer.ts`
201
+ ### UI search, copy, and wheel input
197
202
 
198
- - `parseWheelDirection()` / `readWheelScrollLines()`: decode terminal wheel input and configured scroll lines.
199
- - `WheelPreviewLayer` (`ModalLayer`): a preview layer that scrolls on wheel events.
203
+ - `ui/searchable-preview.ts`: injection/full-content preview layer with `/` search, Enter confirm, Esc clear while editing, wrapped `n/N` navigation, and `y` raw-content copy.
204
+ - `ui/search.ts`: shared literal case-insensitive matching with normalized query whitespace; content filtering also normalizes target whitespace.
205
+ - `ui/highlight.ts`: ANSI-safe visible-column match highlighting, distinguishing the current match.
206
+ - `ui/copy.ts`: Pi clipboard adapter with normalization and transient success/empty/failure notices.
207
+ - Wheel input uses `handleMouse` and host-normalized `wheelDelta` without rescaling. `wheel.ts` and `wheel-preview-layer.ts` were removed.
200
208
 
201
209
  ### `ui/section-preview.ts`
202
210
 
@@ -214,7 +222,7 @@ Preview-only recognition of pi `<skill name="...">` wrappers.
214
222
  1. `registerContextView()` waits for the first enabled `session_start`, then calls `activateContextView()`.
215
223
  2. `activateContextView()` restores any persisted probe identities from custom session entries.
216
224
  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.
225
+ 4. On `context`, `probe.filterMessages()` removes qualified synthetic messages. On `context_with_system`, an observe-only handler re-filters locally, omits Pi's leading complete prompt, diffs against the branch baseline, and freezes Initial with `capture.finalize()` without returning a replacement list.
218
226
  5. On `agent_settled`, the probe is settled and new identities are persisted to `pi-context-view:probe-identities`.
219
227
  6. When the user invokes `/context-view` or the Vim event, `prepareContextViewData()`:
220
228
  - waits for agent idle;
@@ -238,22 +246,22 @@ Preview-only recognition of pi `<skill name="...">` wrappers.
238
246
  ### SilentProbeState
239
247
 
240
248
  - `start()` → `idle → waiting`; creates a timeout; returns the existing completion on re-entry.
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.
249
+ - `isProbeInput(source, token, streamingBehavior)` claims only a waiting, token-matched extension input with no streaming behavior (`waiting → claimed`). A second token-bearing input after claim fails as `nested-send` without aborting either run.
250
+ - `beginRun(token, messageType)` requires a matching token and user run (`waiting/claimed → running`); foreign/custom runs fail as `foreign-run` without arming the abort guard. Only a successfully claimed running probe is aborted at `turn_start`.
251
+ - `recordMessage()` records only the claimed run's first user message when empty and exact setup-abort assistant messages. Filtering/blanking requires both a recorded role/timestamp identity and qualifying content (empty user, or error-stop assistant with the exact setup-abort message), including restored identities; timestamp collisions cannot hide unrelated content.
244
252
  - `settle(captured)` → `running → settled`.
245
253
  - `fail(reason)` → resolves a pending attempt.
246
254
  - Identities are persisted only after settlement or shutdown.
247
255
 
248
256
  ### ContextViewDialog
249
257
 
250
- - `usage ↔ injections` via `Tab`/`Shift+Tab`, including while a preview layer is open.
258
+ - `usage ↔ injections` via `Tab`/`Shift+Tab`, including with previews open, except while a target captures raw input for filter/search editing.
251
259
  - The active tab handles selection and scroll via navigation actions; Enter pushes a preview layer.
252
260
  - `Esc`/`q` pops the active tab's preview layer first, then closes the dialog.
253
261
 
254
262
  ## Integration Points
255
263
 
256
- - **Config**: `config-loader.isEnabled('context_view')` gates activation and command use; `config-loader.getContextView().layout` selects inline or overlay presentation (default `inline`).
264
+ - **Config**: `config-loader.isEnabled('context_view')` gates activation and command use; `getContextView().layout` selects inline/overlay (default `inline`), and `auto_probing` (default `true`) controls only the silent initial-capture probe.
257
265
  - **ExtensionAPI**: `pi.on(...)`, `pi.registerCommand(...)`, `pi.events.on(...)`, `pi.appendEntry(...)`, `pi.getAllTools()`, `pi.getActiveTools()`, `pi.getCommands()`, `pi.sendUserMessage('')`.
258
266
  - **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
267
  - **Pi host runtime**: `buildSessionContext`, `convertToLlm`, `estimateTokens`, `formatSize`, `SettingsManager`, `SystemMessage`/`ContextEvent` types, `ToolInfo`/`SlashCommandInfo`/`SourceInfo`.
@@ -271,6 +279,6 @@ Preview-only recognition of pi `<skill name="...">` wrappers.
271
279
  - Captured prompt, tool, skill, context-file, and message content stays process-local and must never be logged or serialized.
272
280
  - Only synthetic probe `role + timestamp` identities may be persisted.
273
281
  - The silent probe is limited to one attempt per session; it aborts the real turn and cleans up the transcript.
274
- - The view requires TUI mode; it warns in non-TUI modes.
282
+ - Requires Pi 0.87+ for `context_with_system`. `presentation.ts` exports `canPresent(ctx) = ctx.mode === 'tui' && ctx.hasUI`, shared by command/event presentation, capture preparation/finalization, and probe start; non-presentable hosts do not capture.
275
283
  - The command accepts no arguments.
276
284
  - `PageUp`/`PageDown`/`Home`/`End` are intentionally replaced by Vim bindings.
@@ -1,4 +1,7 @@
1
1
  import { piVimKeyEventId } from '../../constants';
2
2
 
3
+ /** Pi does not export its virtual-model API discriminator. */
4
+ export const VIRTUAL_MODEL_API = 'pi-virtual';
5
+
3
6
  export const COMMAND_NAME = 'context-view';
4
7
  export const PI_VIM_KEY_EVENT_ID = piVimKeyEventId('context_view');
@@ -4,6 +4,8 @@ import {
4
4
  type ExtensionAPI,
5
5
  type ExtensionCommandContext,
6
6
  type ExtensionContext,
7
+ SettingsManager,
8
+ shouldCompact,
7
9
  } from '@earendil-works/pi-coding-agent';
8
10
  import {
9
11
  buildNativeSnapshot,
@@ -13,7 +15,9 @@ import {
13
15
  type InitialCaptureState,
14
16
  type SilentProbeState,
15
17
  } from './capture';
18
+ import { VIRTUAL_MODEL_API } from './constants';
16
19
  import type { ContextUsageSnapshot, InitialSnapshot } from './model';
20
+ import { canPresent } from './presentation';
17
21
  import { runWithProbeToken } from './probe-token';
18
22
  import { readAutoCompactReserveTokens } from './settings';
19
23
  import { computeUsage, toReportedUsage } from './usage';
@@ -30,6 +34,10 @@ type PromptContext = ExtensionContext & {
30
34
  };
31
35
 
32
36
  interface ContextViewDependencies {
37
+ autoProbing?: boolean;
38
+ readProbeSettings?: (
39
+ ctx: PromptContext,
40
+ ) => Pick<SettingsManager, 'getCacheWarmingMode' | 'getCompactionSettings'> & Partial<Pick<SettingsManager, 'drainErrors'>>;
33
41
  readAutoCompactReserveTokens?: (ctx: PromptContext) => number | undefined;
34
42
  }
35
43
 
@@ -38,6 +46,39 @@ function defaultReserveReader(ctx: PromptContext): number | undefined {
38
46
  return readAutoCompactReserveTokens(ctx as unknown as ExtensionCommandContext);
39
47
  }
40
48
 
49
+ /** Ordered safety gates. A rejection never consumes the one probe attempt. */
50
+ export async function checkProbeStartConditions(
51
+ ctx: PromptContext,
52
+ deps: ContextViewDependencies & { compaction: CompactionState },
53
+ ): Promise<'ok' | string> {
54
+ if (deps.autoProbing === false) return 'automatic probing is disabled';
55
+ if (!canPresent(ctx)) return 'TUI presentation is unavailable';
56
+ try {
57
+ if (ctx.waitForIdle) await ctx.waitForIdle();
58
+ else if (!ctx.isIdle()) return 'the agent is not idle and waiting for idle is unavailable';
59
+ } catch {
60
+ return 'waiting for idle failed';
61
+ }
62
+ if (deps.compaction.isActive) return 'context compaction is in progress';
63
+ if (ctx.hasPendingMessages()) return 'queued input is pending';
64
+ if (!ctx.model) return 'no model is selected';
65
+ if (ctx.model.api === VIRTUAL_MODEL_API) return 'a virtual model is selected';
66
+ if (!ctx.modelRegistry.hasConfiguredAuth(ctx.model)) return `${ctx.model.provider} has no configured authentication`;
67
+ try {
68
+ const settings = deps.readProbeSettings?.(ctx) ?? SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() });
69
+ if (settings.drainErrors?.().length) return 'settings unreadable';
70
+ if (settings.getCacheWarmingMode() === 'idle') return 'idle cache warming is enabled';
71
+ const compactionSettings = settings.getCompactionSettings(ctx.model);
72
+ const usage = ctx.getContextUsage();
73
+ if (usage?.tokens !== null && usage?.tokens !== undefined && shouldCompact(usage.tokens, usage.contextWindow, compactionSettings)) {
74
+ return 'usage is at the auto-compaction threshold';
75
+ }
76
+ } catch {
77
+ return 'settings unreadable';
78
+ }
79
+ return 'ok';
80
+ }
81
+
41
82
  /** Prepare Context View data without requiring command-only APIs for event callers. */
42
83
  export async function prepareContextViewData(
43
84
  pi: ExtensionAPI,
@@ -50,21 +91,14 @@ export async function prepareContextViewData(
50
91
  let initial = capture.snapshot;
51
92
  let degradedReason: string | undefined;
52
93
 
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.
94
+ // Frozen snapshots open immediately; only probing requires an idle session.
55
95
  if (!initial) {
56
- if (ctx.waitForIdle) await ctx.waitForIdle();
96
+ const condition = await checkProbeStartConditions(ctx, { ...dependencies, compaction });
57
97
  initial = capture.snapshot;
58
- }
59
-
60
- if (!initial) {
61
- if (compaction.isActive) {
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.`;
67
- } else {
98
+ // A real turn may have supplied the snapshot during the idle wait.
99
+ if (!initial && condition !== 'ok') {
100
+ degradedReason = `Silent probe unavailable: ${condition}. Extension additions were not observed.`;
101
+ } else if (!initial) {
68
102
  const attempt = probe.start();
69
103
  if (attempt.started) {
70
104
  ctx.ui.setWorkingVisible(false);