@0xkahi/pi-qol 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +13 -0
  2. package/assets/config.schema.json +23 -0
  3. package/package.json +4 -4
  4. package/src/codemap.md +3 -2
  5. package/src/config-loader.ts +4 -0
  6. package/src/constants.ts +1 -0
  7. package/src/extensions/auto-session-name/title-generator.ts +1 -1
  8. package/src/extensions/codemap.md +9 -2
  9. package/src/extensions/context-view/capture.ts +394 -0
  10. package/src/extensions/context-view/codemap.md +28 -0
  11. package/src/extensions/context-view/constants.ts +4 -0
  12. package/src/extensions/context-view/context-view-controller.ts +67 -0
  13. package/src/extensions/context-view/index.ts +120 -0
  14. package/src/extensions/context-view/measure.ts +307 -0
  15. package/src/extensions/context-view/model.ts +207 -0
  16. package/src/extensions/context-view/ui/context-view-dialog.ts +81 -0
  17. package/src/extensions/context-view/ui/injections-model.ts +257 -0
  18. package/src/extensions/context-view/ui/injections-view.ts +396 -0
  19. package/src/extensions/context-view/ui/layout.ts +88 -0
  20. package/src/extensions/context-view/ui/navigation.ts +37 -0
  21. package/src/extensions/context-view/ui/skill-preview.ts +82 -0
  22. package/src/extensions/context-view/ui/usage-map.ts +133 -0
  23. package/src/extensions/context-view/ui/usage-view.ts +734 -0
  24. package/src/extensions/context-view/usage.ts +432 -0
  25. package/src/extensions/model-select/index.ts +12 -6
  26. package/src/extensions/model-select/model-select-dialog.ts +2 -1
  27. package/src/extensions/model-select/types.ts +2 -0
  28. package/src/index.ts +2 -0
  29. package/src/schemas/codemap.md +2 -2
  30. package/src/schemas/config.schema.ts +3 -0
  31. package/src/schemas/context-view.config.schema.ts +13 -0
  32. package/src/schemas/model-select.config.schema.ts +3 -1
package/README.md CHANGED
@@ -109,6 +109,9 @@ them (project overrides global):
109
109
  ],
110
110
  "hide_tabs": { "groups": false, "search": false }
111
111
  },
112
+ "context_view": {
113
+ "enabled": true
114
+ },
112
115
  "custom_footer": {
113
116
  "enabled": true,
114
117
  "colors": {
@@ -166,6 +169,16 @@ through visible tabs. A favourite can belong to multiple groups; group tabs
166
169
  contain only resolved, authenticated favourites and preserve favourite order.
167
170
  Duplicate favourite declarations remain first-entry-wins.
168
171
 
172
+ #### `context_view`
173
+
174
+ | Key | Type | Default | Description |
175
+ | --------- | --------- | ------- | ----------- |
176
+ | `enabled` | `boolean` | `false` | Enable the Context View capture and interface. |
177
+
178
+ ### Context View
179
+
180
+ 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. Other extensions can open the same view by emitting `pi.vimKeys.event:pi-qol.context_view`.
181
+
169
182
  #### `custom_footer`
170
183
 
171
184
  | Key | Type | Default | Description |
@@ -131,6 +131,17 @@
131
131
  "minLength": 1
132
132
  }
133
133
  },
134
+ "default_reasoning": {
135
+ "type": "string",
136
+ "enum": [
137
+ "off",
138
+ "minimal",
139
+ "low",
140
+ "medium",
141
+ "high",
142
+ "xhigh"
143
+ ]
144
+ },
134
145
  "layout": {
135
146
  "default": "inline",
136
147
  "type": "string",
@@ -243,6 +254,18 @@
243
254
  }
244
255
  }
245
256
  }
257
+ },
258
+ "context_view": {
259
+ "default": {
260
+ "enabled": false
261
+ },
262
+ "type": "object",
263
+ "properties": {
264
+ "enabled": {
265
+ "default": false,
266
+ "type": "boolean"
267
+ }
268
+ }
246
269
  }
247
270
  }
248
271
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xkahi/pi-qol",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "description": "quality of life pi extensions",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -43,9 +43,9 @@
43
43
  "@earendil-works/pi-tui": "*"
44
44
  },
45
45
  "devDependencies": {
46
- "@earendil-works/pi-ai": "^0.79.4",
47
- "@earendil-works/pi-coding-agent": "^0.79.4",
48
- "@earendil-works/pi-tui": "^0.79.4",
46
+ "@earendil-works/pi-ai": "^0.83.0",
47
+ "@earendil-works/pi-coding-agent": "^0.83.0",
48
+ "@earendil-works/pi-tui": "^0.83.0",
49
49
  "@biomejs/biome": "^2.4.15",
50
50
  "@changesets/cli": "^2.31.0",
51
51
  "@types/node": "^24.0.0",
package/src/codemap.md CHANGED
@@ -4,11 +4,12 @@
4
4
 
5
5
  Top-level source root for `pi-qol`, a Pi coding-agent extension that layers small quality-of-life features onto the agent core.
6
6
 
7
- It coordinates three feature modules:
7
+ It coordinates four feature modules:
8
8
 
9
9
  - **auto_session_name**: Generates and applies a concise session title from the user's first message before the agent runs.
10
10
  - **model_select**: Registers a `/select-model` command (plus a cross-extension event) for picking or searching available models with favourites, ordered custom groups, provider filtering, and an inline or overlay layout.
11
11
  - **custom_footer**: Replaces the default footer with a richer status bar showing cwd/branch/session, token/cost/cache stats, context-window usage, subscription-rate usage, and the current model/thinking level.
12
+ - **context_view**: Lazily captures the initial provider context and opens a bounded half-height inline Usage/Injections interface through `/context-view` or `pi.vimKeys.event:pi-qol.context_view`.
12
13
 
13
14
  Shared concerns live here too: extension configuration loading, path resolution, model/auth resolution, and Zod schemas for every feature.
14
15
 
@@ -27,7 +28,7 @@ Shared concerns live here too: extension configuration loading, path resolution,
27
28
  1. **Bootstrap** (`index.ts`)
28
29
  - Creates `ConfigLoader`.
29
30
  - On every `session_start`, calls `config.initializeConfig(ctx)`; surfaces validation errors via `ctx.ui.notify`.
30
- - Registers the three feature modules, passing the shared loader.
31
+ - Registers the four feature modules, passing the shared loader.
31
32
 
32
33
  2. **Config loading** (`config-loader.ts`, `utils/path.util.ts`, `schemas/*.schema.ts`)
33
34
  - Defaults → global `~/.pi/extensions/pi-qol/config.json` → project `.pi/extensions/pi-qol/config.json` (if trusted).
@@ -28,6 +28,10 @@ export class ConfigLoader {
28
28
  return this.config.custom_footer;
29
29
  }
30
30
 
31
+ getContextView(): Config['context_view'] {
32
+ return this.config.context_view;
33
+ }
34
+
31
35
  initializeConfig(ctx: ExtensionContext): { success: boolean; error?: string } {
32
36
  let merged: Config = this.defaultConfig;
33
37
 
package/src/constants.ts CHANGED
@@ -6,6 +6,7 @@ const SUB_EXTENSION_IDS = {
6
6
  auto_session_name: 'auto_session_name',
7
7
  model_select: 'model_select',
8
8
  custom_footer: 'custom_footer',
9
+ context_view: 'context_view',
9
10
  } as const;
10
11
 
11
12
  export type SubExtentionIds = ObjectValues<typeof SUB_EXTENSION_IDS>;
@@ -1,5 +1,5 @@
1
1
  import type { Api, AssistantMessage, Context, Model, SimpleStreamOptions, TextContent } from '@earendil-works/pi-ai';
2
- import { completeSimple } from '@earendil-works/pi-ai';
2
+ import { completeSimple } from '@earendil-works/pi-ai/compat';
3
3
  import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
4
4
  import type { ResolvedModel } from '../../utils/model-resolver.util';
5
5
  import { MAX_RETRIES, MAX_TITLE_LENGTH, TITLE_MAX_TOKENS } from './constants';
@@ -9,6 +9,7 @@ Current features:
9
9
  - `auto-session-name` – automatically generates and applies a concise session title from the user’s first message.
10
10
  - `model-select` – provides an interactive `/select-model` command (and cross-extension activation hook) for choosing models from the registry with permanent Favourites, ordered custom groups, Search, provider filtering, and inline or overlay layout.
11
11
  - `custom-footer` – replaces the TUI footer with a richer status bar showing cwd, git branch, session name, model, token/cost usage, context-window usage, and subscription usage.
12
+ - `context-view` – captures initial context contributions and displays Usage/Injections in a bounded half-height inline tabbed interface with Vim navigation.
12
13
 
13
14
  ## Design Patterns
14
15
 
@@ -19,7 +20,7 @@ Current features:
19
20
  - **TUI component pattern**: `custom-footer` constructs a `Component` that renders live on each frame, invalidating Pi’s default footer rendering.
20
21
  - **Guard classes**: `auto-session-name/guards.ts` isolates predicate logic (session name already set, child session, first user turn) for easy testing and readable early returns.
21
22
  - **Pure helpers / formatters**: `model-formatter.ts`, `token-stats.ts`, `model-lists.ts`, and `prompt.ts` keep transformation and rendering logic free of side effects.
22
- - **Cross-extension event bus**: `model-select` listens on a dedicated `pi.events` channel (`PI_VIM_KEY_EVENT_ID`) so other extensions can open the picker without invoking the slash command directly.
23
+ - **Cross-extension event bus**: `model-select` and `context-view` listen on dedicated `pi.events` channels so other extensions can open their interfaces without invoking slash commands directly.
23
24
  - **Abortable async work**: `auto-session-name` keeps an `AbortController` and cancels in-flight title generation on `session_shutdown` or a new `before_agent_start`.
24
25
 
25
26
  ## Data & Control Flow
@@ -43,7 +44,13 @@ Current features:
43
44
  - The dialog uses one fuzzy query across dynamically visible Favourites/group/Search tabs, preserves per-tab selection, keeps the active tab represented at narrow widths, and renders in an inline or overlay layout; selection is applied via `pi.setModel`.
44
45
  - The event-bus handler captures the latest context so the picker can also be opened without a command context.
45
46
 
46
- 4. **custom-footer flow**
47
+ 4. **context-view flow**
48
+ - Lazily activates only when `context_view.enabled` is true at session start.
49
+ - Captures owned prompt/tool/message inputs, freezes the first provider-context snapshot, and filters exact synthetic-probe identities.
50
+ - `/context-view` and `pi.vimKeys.event:pi-qol.context_view` share data preparation and open a bounded half-height Usage-first inline interface.
51
+ - The dialog retains Usage/Injections child state and routes Tab plus Vim navigation (`j/k`, `Ctrl+u/d`, `gg/G`).
52
+
53
+ 5. **custom-footer flow**
47
54
  - On `session_start`, installs a `CustomFooterComponent` factory via `ctx.ui.setFooter`.
48
55
  - Each render reads from `ExtensionContext` (cwd, session name, model, context usage, entries), `FooterDataProvider` (git branch, extension statuses, available providers), and a cached `SubscriptionUsageManager`.
49
56
  - The component builds and truncates lines to the available terminal width and requests re-renders via `tui.requestRender()` when branch changes or subscription usage updates.
@@ -0,0 +1,394 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Initial capture state and conversion from pi event data to the semantic
4
+ * model. Event registration remains in index.ts; this module is independently
5
+ * unit-testable.
6
+ */
7
+ import { type BuildSystemPromptOptions, type ContextEvent, estimateTokens, type InputSource, type ToolInfo } from '@earendil-works/pi-coding-agent';
8
+
9
+ import { analyzeSystemPrompt, type PromptOptionsSlice, type ToolSlice } from './measure';
10
+ import { AGGREGATE_SOURCE_ID, buildSnapshot, type CaptureOrigin, type InitialSnapshot, type InjectionItem, type InjectionSource } from './model';
11
+
12
+ /** Session custom-entry type persisting probe message identities across extension runtimes. */
13
+ export const PROBE_IDENTITIES_CUSTOM_TYPE = 'pi-context-view:probe-identities';
14
+
15
+ const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
16
+ const AGGREGATE_SOURCE: InjectionSource = {
17
+ id: AGGREGATE_SOURCE_ID,
18
+ label: 'extensions (aggregate)',
19
+ native: false,
20
+ };
21
+
22
+ /** Everything available when the first context event finalizes a snapshot. */
23
+ export interface CaptureFinalization {
24
+ systemPrompt: string;
25
+ messages: ContextEvent['messages'];
26
+ baselineMessages: ContextEvent['messages'];
27
+ allTools: readonly ToolInfo[];
28
+ activeToolNames: readonly string[];
29
+ origin: CaptureOrigin;
30
+ capturedAt?: Date;
31
+ }
32
+
33
+ /** Inputs for an on-demand pi-native prompt/tool snapshot. */
34
+ export interface NativeSnapshotInput {
35
+ systemPrompt: string;
36
+ options: BuildSystemPromptOptions;
37
+ allTools: readonly ToolInfo[];
38
+ activeToolNames: readonly string[];
39
+ capturedAt?: Date;
40
+ }
41
+
42
+ /** Result of the one allowed silent-probe attempt. */
43
+ export type ProbeOutcome = { readonly status: 'captured' } | { readonly status: 'failed'; readonly reason: string };
44
+
45
+ /** A probe start request; concurrent callers share `completion`. */
46
+ export interface ProbeAttempt {
47
+ readonly started: boolean;
48
+ readonly completion: Promise<ProbeOutcome>;
49
+ }
50
+
51
+ /** Exact identity used to remove only synthetic probe messages. */
52
+ export interface SyntheticMessageIdentity {
53
+ readonly role: 'user' | 'assistant';
54
+ readonly timestamp: number;
55
+ }
56
+
57
+ /** Owned structured inputs prepared before later extension handlers can mutate shared event data. */
58
+ interface CapturePreparation {
59
+ readonly promptOptions: PromptOptionsSlice;
60
+ readonly toolSnippets?: Readonly<Record<string, string>>;
61
+ }
62
+
63
+ /** Lifecycle of the single probe attempt, including ownership retained after its completion times out. */
64
+ type ProbePhase = 'idle' | 'waiting' | 'waiting-after-timeout' | 'running' | 'running-after-timeout' | 'failed' | 'settled';
65
+
66
+ /**
67
+ * Capture-once state machine. `prepare()` refreshes the structured options on
68
+ * every run until `finalize()` succeeds; subsequent finalizations return the
69
+ * original snapshot unchanged.
70
+ */
71
+ export class InitialCaptureState {
72
+ private pendingPreparation: CapturePreparation | undefined;
73
+ private latestOptions: BuildSystemPromptOptions | undefined;
74
+ private initialSnapshot: InitialSnapshot | undefined;
75
+
76
+ /** The frozen Initial snapshot, or undefined until `finalize()` succeeds. */
77
+ public get snapshot(): InitialSnapshot | undefined {
78
+ return this.initialSnapshot;
79
+ }
80
+
81
+ /** Latest owned structured inputs for Usage, kept process-local only. */
82
+ public get promptOptions(): BuildSystemPromptOptions | undefined {
83
+ return this.latestOptions;
84
+ }
85
+
86
+ /** Own structured prompt inputs from every `before_agent_start`; freeze only the Initial preparation. */
87
+ public prepare(options: BuildSystemPromptOptions): void {
88
+ this.latestOptions = structuredClone(options);
89
+ if (this.initialSnapshot !== undefined) return;
90
+ this.pendingPreparation = {
91
+ promptOptions: copyPromptOptions(options),
92
+ toolSnippets: options.toolSnippets === undefined ? undefined : { ...options.toolSnippets },
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Freeze the Initial snapshot from the first context event. Returns the
98
+ * existing snapshot on repeat calls, or undefined when `prepare()` never ran.
99
+ */
100
+ public finalize(input: CaptureFinalization): InitialSnapshot | undefined {
101
+ if (this.initialSnapshot !== undefined) return this.initialSnapshot;
102
+ if (this.pendingPreparation === undefined) return undefined;
103
+
104
+ const preparation = this.pendingPreparation;
105
+ const tools = captureActiveTools(input.allTools, input.activeToolNames, {
106
+ toolSnippets: preparation.toolSnippets,
107
+ });
108
+ const items = [
109
+ ...analyzeSystemPrompt(input.systemPrompt, preparation.promptOptions, tools),
110
+ ...measureInjectedMessages(input.messages, input.baselineMessages),
111
+ ];
112
+ this.initialSnapshot = buildSnapshot(items, input.origin, input.capturedAt ?? new Date());
113
+ this.pendingPreparation = undefined;
114
+ return this.initialSnapshot;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * State for one on-demand silent probe. It owns the timeout and exact synthetic
120
+ * message identities, but leaves pi API calls and UI restoration to index.ts.
121
+ */
122
+ export class SilentProbeState {
123
+ private phase: ProbePhase = 'idle';
124
+ private inputObserved = false;
125
+ private readonly identities = new Map<string, SyntheticMessageIdentity>();
126
+ private completion: Promise<ProbeOutcome> | undefined;
127
+ private resolveCompletion: ((outcome: ProbeOutcome) => void) | undefined;
128
+ private outcome: ProbeOutcome | undefined;
129
+ private timeout: NodeJS.Timeout | undefined;
130
+
131
+ /** True while the probe owns the in-flight agent run (including after a timeout). */
132
+ public get isCurrentRun(): boolean {
133
+ return this.phase === 'running' || this.phase === 'running-after-timeout';
134
+ }
135
+
136
+ /** Defensive copies of the recorded probe message identities. */
137
+ public get syntheticMessages(): readonly SyntheticMessageIdentity[] {
138
+ return [...this.identities.values()].map(identity => ({ ...identity }));
139
+ }
140
+
141
+ /**
142
+ * Merge probe identities persisted by an earlier extension runtime so prior
143
+ * probe messages stay excluded after resume/reload/fork. Restoration only
144
+ * seeds the identity map; it neither consumes this runtime's single probe
145
+ * attempt nor associates any run with the probe.
146
+ */
147
+ public restoreIdentities(identities: readonly SyntheticMessageIdentity[]): void {
148
+ for (const identity of identities) {
149
+ this.identities.set(identityKey(identity), { role: identity.role, timestamp: identity.timestamp });
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Begin the one allowed probe attempt with a failure timeout. Repeat calls
155
+ * return the original attempt's completion with `started: false`.
156
+ */
157
+ public start(timeoutMs = DEFAULT_PROBE_TIMEOUT_MS): ProbeAttempt {
158
+ if (this.completion !== undefined) {
159
+ return { started: false, completion: this.completion };
160
+ }
161
+
162
+ this.phase = 'waiting';
163
+ this.completion = new Promise<ProbeOutcome>(resolve => {
164
+ this.resolveCompletion = resolve;
165
+ });
166
+ this.timeout = setTimeout(() => {
167
+ if (this.phase === 'waiting') {
168
+ this.phase = 'waiting-after-timeout';
169
+ } else if (this.phase === 'running') {
170
+ this.phase = 'running-after-timeout';
171
+ }
172
+ this.resolve({ status: 'failed', reason: 'Silent probe timed out.' });
173
+ }, timeoutMs);
174
+ return { started: true, completion: this.completion };
175
+ }
176
+
177
+ /** Mark the exact extension-originated empty input that starts the probe. */
178
+ public observeInput(source: InputSource, text: string): void {
179
+ const awaitingInput = this.phase === 'waiting' || this.phase === 'waiting-after-timeout';
180
+ if (awaitingInput && source === 'extension' && text === '') this.inputObserved = true;
181
+ }
182
+
183
+ /** Associate the next matching lifecycle with the probe, not a real turn. */
184
+ public beginRun(prompt: string): boolean {
185
+ const ownsPendingInput = this.phase === 'waiting' || this.phase === 'waiting-after-timeout';
186
+ if (!ownsPendingInput || !this.inputObserved || prompt !== '') return false;
187
+ this.phase = this.phase === 'waiting-after-timeout' ? 'running-after-timeout' : 'running';
188
+ return true;
189
+ }
190
+
191
+ /** Record probe user/assistant identities as their message events arrive. */
192
+ public recordMessage(message: ContextEvent['messages'][number]): void {
193
+ if (!this.isCurrentRun || (message.role !== 'user' && message.role !== 'assistant')) return;
194
+ const identity = { role: message.role, timestamp: message.timestamp } satisfies SyntheticMessageIdentity;
195
+ this.identities.set(identityKey(identity), identity);
196
+ }
197
+
198
+ /**
199
+ * Replace only the probe's aborted assistant with an empty successful message
200
+ * so pi does not render an "Operation aborted" transcript row.
201
+ */
202
+ public sanitizeAssistant(message: ContextEvent['messages'][number]): ContextEvent['messages'][number] | undefined {
203
+ if (!this.isCurrentRun || message.role !== 'assistant' || message.stopReason !== 'aborted') {
204
+ return undefined;
205
+ }
206
+ this.recordMessage(message);
207
+ const identity = { role: 'assistant', timestamp: message.timestamp } satisfies SyntheticMessageIdentity;
208
+ if (!this.identities.has(identityKey(identity))) return undefined;
209
+ return { ...message, content: [], stopReason: 'stop', errorMessage: undefined };
210
+ }
211
+
212
+ /** Remove only messages whose exact role+timestamp identity belongs to the probe. */
213
+ public filterMessages(messages: ContextEvent['messages']): ContextEvent['messages'] {
214
+ if (this.identities.size === 0) return messages;
215
+ return messages.filter(message => {
216
+ if (message.role !== 'user' && message.role !== 'assistant') return true;
217
+ return !this.identities.has(identityKey(message));
218
+ });
219
+ }
220
+
221
+ /** Resolve a running attempt from `agent_settled`. */
222
+ public settle(captured: boolean): boolean {
223
+ if (!this.isCurrentRun) return false;
224
+ this.phase = 'settled';
225
+ if (this.outcome === undefined) {
226
+ this.resolve(captured ? { status: 'captured' } : { status: 'failed', reason: 'Silent probe settled without a context snapshot.' });
227
+ }
228
+ return true;
229
+ }
230
+
231
+ /** End a pending attempt during shutdown or a synchronous startup failure. */
232
+ public fail(reason: string): void {
233
+ if (this.completion === undefined || this.phase === 'failed' || this.phase === 'settled') return;
234
+ this.phase = 'failed';
235
+ if (this.outcome === undefined) this.resolve({ status: 'failed', reason });
236
+ }
237
+
238
+ /** Settle the completion promise exactly once and clear the timeout. */
239
+ private resolve(outcome: ProbeOutcome): void {
240
+ if (this.outcome !== undefined) return;
241
+ if (this.timeout !== undefined) clearTimeout(this.timeout);
242
+ this.timeout = undefined;
243
+ this.outcome = outcome;
244
+ const resolve = this.resolveCompletion;
245
+ this.resolveCompletion = undefined;
246
+ resolve?.(outcome);
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Parse one persisted probe-identities entry payload. Malformed or foreign
252
+ * records are ignored so a corrupt entry can never suppress genuine messages.
253
+ */
254
+ export function parsePersistedIdentities(data: unknown): SyntheticMessageIdentity[] {
255
+ if (typeof data !== 'object' || data === null) return [];
256
+ const messages = (data as { messages?: unknown }).messages;
257
+ if (!Array.isArray(messages)) return [];
258
+ const identities: SyntheticMessageIdentity[] = [];
259
+ for (const message of messages) {
260
+ if (typeof message !== 'object' || message === null) continue;
261
+ const { role, timestamp } = message as { role?: unknown; timestamp?: unknown };
262
+ if ((role === 'user' || role === 'assistant') && typeof timestamp === 'number' && Number.isFinite(timestamp)) {
263
+ identities.push({ role, timestamp });
264
+ }
265
+ }
266
+ return identities;
267
+ }
268
+
269
+ /** Build a view-local pi-native snapshot without freezing the main capture state. */
270
+ export function buildNativeSnapshot(input: NativeSnapshotInput): InitialSnapshot {
271
+ const options = copyPromptOptions(input.options);
272
+ const tools = captureActiveTools(input.allTools, input.activeToolNames, input.options);
273
+ const items = analyzeSystemPrompt(input.systemPrompt, options, tools);
274
+ return buildSnapshot(items, 'synthetic-probe', input.capturedAt ?? new Date());
275
+ }
276
+
277
+ /** Add frozen context-only messages to a current prompt/tool snapshot for Usage. */
278
+ export function mergeContextOnlyMessages(snapshot: InitialSnapshot, initial: InitialSnapshot): InitialSnapshot {
279
+ const contextOnly = initial.groups.flatMap(group => group.items.filter(item => item.kind === 'message' && item.contextOnly === true));
280
+ if (contextOnly.length === 0) return snapshot;
281
+ const items = [...snapshot.groups.flatMap(group => group.items), ...contextOnly];
282
+ return buildSnapshot(items, snapshot.origin, snapshot.capturedAt);
283
+ }
284
+
285
+ /** Copy the prompt-options slice used by measurement, without shared nested references. */
286
+ export function copyPromptOptions(options: BuildSystemPromptOptions): PromptOptionsSlice {
287
+ return {
288
+ cwd: options.cwd,
289
+ homeDir: process.env.HOME,
290
+ customPrompt: options.customPrompt,
291
+ appendSystemPrompt: options.appendSystemPrompt,
292
+ contextFilePaths: options.contextFiles?.map(file => file.path),
293
+ skills: options.skills
294
+ ?.filter(skill => !skill.disableModelInvocation)
295
+ .map(skill => ({
296
+ name: skill.name,
297
+ description: skill.description,
298
+ filePath: skill.filePath,
299
+ })),
300
+ };
301
+ }
302
+
303
+ /** Snapshot the final active tool set with provenance and payload definitions. */
304
+ export function captureActiveTools(
305
+ allTools: readonly ToolInfo[],
306
+ activeToolNames: readonly string[],
307
+ options: { readonly toolSnippets?: Readonly<Record<string, string>> },
308
+ ): ToolSlice[] {
309
+ const active = new Set(activeToolNames);
310
+ return allTools
311
+ .filter(tool => active.has(tool.name))
312
+ .map(tool => ({
313
+ name: tool.name,
314
+ description: tool.description,
315
+ parametersJson: JSON.stringify(tool.parameters ?? {}),
316
+ snippet: options.toolSnippets?.[tool.name],
317
+ guidelines: normalizeGuidelines(tool.promptGuidelines),
318
+ source: tool.sourceInfo.source,
319
+ }));
320
+ }
321
+
322
+ /**
323
+ * Measure extension messages while excluding ordinary session history. Custom
324
+ * messages remain attributable by customType; other roles are captured only
325
+ * when they differ from the session-branch baseline.
326
+ */
327
+ export function measureInjectedMessages(messages: ContextEvent['messages'], baselineMessages: ContextEvent['messages']): InjectionItem[] {
328
+ const baseline = messageSignatureCounts(baselineMessages);
329
+ const occurrences = new Map<string, number>();
330
+ const items: InjectionItem[] = [];
331
+ for (const message of messages) {
332
+ const contextOnly = !consumeMessageSignature(baseline, message);
333
+ if (message.role !== 'custom' && !contextOnly) continue;
334
+
335
+ const identity = message.role === 'custom' ? message.customType : message.role;
336
+ const occurrence = occurrences.get(identity) ?? 0;
337
+ occurrences.set(identity, occurrence + 1);
338
+ const text = messageText(message);
339
+ items.push({
340
+ id: message.role === 'custom' ? `message:${message.customType}:${occurrence}` : `message:context:${message.role}:${occurrence}`,
341
+ phase: 'initial',
342
+ kind: 'message',
343
+ source: message.role === 'custom' ? messageSource(message.customType) : AGGREGATE_SOURCE,
344
+ label: message.role === 'custom' ? 'message' : `${message.role} message`,
345
+ chars: text.length,
346
+ tokens: estimateTokens(message),
347
+ text,
348
+ contextOnly: contextOnly || undefined,
349
+ });
350
+ }
351
+ return items;
352
+ }
353
+
354
+ /** Count structurally identical baseline messages for order-independent diffing. */
355
+ function messageSignatureCounts(messages: ContextEvent['messages']): Map<string, number> {
356
+ const counts = new Map<string, number>();
357
+ for (const message of messages) {
358
+ const signature = JSON.stringify(message);
359
+ counts.set(signature, (counts.get(signature) ?? 0) + 1);
360
+ }
361
+ return counts;
362
+ }
363
+
364
+ /** Consume one matching baseline occurrence, returning false for a context-only message. */
365
+ function consumeMessageSignature(counts: Map<string, number>, message: ContextEvent['messages'][number]): boolean {
366
+ const signature = JSON.stringify(message);
367
+ const count = counts.get(signature) ?? 0;
368
+ if (count === 0) return false;
369
+ if (count === 1) counts.delete(signature);
370
+ else counts.set(signature, count - 1);
371
+ return true;
372
+ }
373
+
374
+ /** Extract provider-bound message content for raw preview. */
375
+ function messageText(message: ContextEvent['messages'][number]): string {
376
+ if (!('content' in message)) return JSON.stringify(message);
377
+ return typeof message.content === 'string' ? message.content : JSON.stringify(message.content);
378
+ }
379
+
380
+ /** Map key uniquely identifying one probe message by role and timestamp. */
381
+ function identityKey(identity: SyntheticMessageIdentity): string {
382
+ return `${identity.role}:${identity.timestamp}`;
383
+ }
384
+
385
+ /** Attribute a custom-role message to its customType; the actual injector is unknowable. */
386
+ function messageSource(customType: string): InjectionSource {
387
+ return { id: `message-type:${customType}`, label: customType, native: false };
388
+ }
389
+
390
+ /** Normalize the string-or-array promptGuidelines field to an owned array. */
391
+ function normalizeGuidelines(guidelines: string | string[] | undefined): string[] {
392
+ if (guidelines === undefined) return [];
393
+ return Array.isArray(guidelines) ? [...guidelines] : [guidelines];
394
+ }
@@ -0,0 +1,28 @@
1
+ # src/extensions/context-view/
2
+
3
+ ## Responsibility
4
+
5
+ Provides optional inspection of model-context occupancy and initial context injections. It is disabled by default and lazily registers capture, command, and Vim-event integration only after an enabled session starts.
6
+
7
+ ## Architecture
8
+
9
+ - `index.ts`: registration, lifecycle hooks, synthetic-probe filtering/persistence, `/context-view`, and `pi.vimKeys.event:pi-qol.context_view`.
10
+ - `capture.ts`: owned prompt inputs, capture-once snapshot state, active tools, context-only messages, and single-attempt probe state.
11
+ - `context-view-controller.ts`: shared command/event data preparation and degraded native fallback.
12
+ - `model.ts`, `measure.ts`, `usage.ts`: pure semantic models, prompt/tool measurement, and usage classification.
13
+ - `ui/context-view-dialog.ts`: bounded half-height inline shell, visible Usage/Injections tabs, tab state retention, and global input routing.
14
+ - `ui/usage-view.ts`, `ui/injections-view.ts`: stateful child views and previews.
15
+ - `ui/navigation.ts`: shared `j/k`, arrows, `Ctrl+u/d`, `gg/G` semantics; PageUp/PageDown/Home/End are intentionally ignored.
16
+ - Other `ui/` modules provide map, layout, hierarchy, scrolling, sanitization, and skill-preview helpers.
17
+
18
+ ## Data Flow
19
+
20
+ 1. Enabled `session_start` lazily installs the feature and restores persisted role/timestamp probe identities.
21
+ 2. `before_agent_start` owns structured prompt options; `context` freezes the first eligible provider snapshot.
22
+ 3. Opening before capture attempts one silent empty probe; exact synthetic messages are aborted, sanitized, filtered, and persisted by identity only.
23
+ 4. The controller combines the initial snapshot, current native prompt/tool data, filtered session messages, and reported usage.
24
+ 5. `ContextViewDialog` opens Usage-first as an inline component bounded to 50% of terminal height and preserves both child states while tabs switch.
25
+
26
+ ## Constraints
27
+
28
+ Captured prompt, tool, skill, context-file, and message content remains process-local and must never be logged or serialized. Only synthetic probe role/timestamp identities may be persisted.
@@ -0,0 +1,4 @@
1
+ import { piVimKeyEventId } from '../../constants';
2
+
3
+ export const COMMAND_NAME = 'context-view';
4
+ export const PI_VIM_KEY_EVENT_ID = piVimKeyEventId('context_view');
@@ -0,0 +1,67 @@
1
+ import { buildSessionContext, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+ import { buildNativeSnapshot, type InitialCaptureState, mergeContextOnlyMessages, type SilentProbeState } from './capture';
3
+ import type { ContextUsageSnapshot, InitialSnapshot } from './model';
4
+ import { computeUsage, toReportedUsage } from './usage';
5
+
6
+ export interface ContextViewData {
7
+ initial: InitialSnapshot;
8
+ usage: ContextUsageSnapshot;
9
+ degradedReason?: string;
10
+ }
11
+
12
+ type PromptContext = ExtensionContext & {
13
+ getSystemPromptOptions?: () => Parameters<typeof buildNativeSnapshot>[0]['options'];
14
+ waitForIdle?: () => Promise<void>;
15
+ };
16
+
17
+ /** Prepare Context View data without requiring command-only APIs for event callers. */
18
+ export async function prepareContextViewData(
19
+ pi: ExtensionAPI,
20
+ ctx: PromptContext,
21
+ capture: InitialCaptureState,
22
+ probe: SilentProbeState,
23
+ ): Promise<ContextViewData> {
24
+ if (ctx.waitForIdle) await ctx.waitForIdle();
25
+ let initial = capture.snapshot;
26
+ let degradedReason: string | undefined;
27
+
28
+ if (!initial) {
29
+ const attempt = probe.start();
30
+ if (attempt.started && ctx.model && ctx.modelRegistry.hasConfiguredAuth(ctx.model)) {
31
+ try {
32
+ pi.sendUserMessage('');
33
+ } catch (error) {
34
+ probe.fail(error instanceof Error ? error.message : String(error));
35
+ }
36
+ } else if (attempt.started) {
37
+ probe.fail('Silent probe unavailable: no authenticated model is selected.');
38
+ }
39
+ const outcome = await attempt.completion;
40
+ initial = capture.snapshot;
41
+ if (!initial)
42
+ degradedReason = `${outcome.status === 'failed' ? outcome.reason : 'Silent probe did not capture Initial.'} Extension additions were not observed.`;
43
+ }
44
+
45
+ const options = capture.promptOptions ?? ctx.getSystemPromptOptions?.();
46
+ if (!options) {
47
+ throw new Error('Context View has not received prompt options yet. Start an agent turn and try again.');
48
+ }
49
+ const current = buildNativeSnapshot({
50
+ systemPrompt: ctx.getSystemPrompt(),
51
+ options,
52
+ allTools: pi.getAllTools(),
53
+ activeToolNames: pi.getActiveTools(),
54
+ });
55
+ const fallback = initial ?? current;
56
+ const messages = probe.filterMessages(buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId()).messages);
57
+ return {
58
+ initial: fallback,
59
+ degradedReason,
60
+ usage: computeUsage({
61
+ snapshot: mergeContextOnlyMessages(current, fallback),
62
+ messages,
63
+ reported: toReportedUsage(ctx.getContextUsage()),
64
+ modelLabel: ctx.model?.id,
65
+ }),
66
+ };
67
+ }