@0xkahi/pi-qol 0.1.1 → 1.0.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 (44) hide show
  1. package/README.md +13 -0
  2. package/assets/config.schema.json +12 -0
  3. package/package.json +4 -4
  4. package/src/codemap.md +26 -16
  5. package/src/config-loader.ts +4 -0
  6. package/src/constants.ts +1 -0
  7. package/src/extensions/auto-session-name/codemap.md +17 -12
  8. package/src/extensions/auto-session-name/title-generator.ts +1 -1
  9. package/src/extensions/codemap.md +173 -13
  10. package/src/extensions/context-view/capture.ts +394 -0
  11. package/src/extensions/context-view/codemap.md +213 -0
  12. package/src/extensions/context-view/constants.ts +4 -0
  13. package/src/extensions/context-view/context-view-controller.ts +67 -0
  14. package/src/extensions/context-view/index.ts +120 -0
  15. package/src/extensions/context-view/measure.ts +307 -0
  16. package/src/extensions/context-view/model.ts +207 -0
  17. package/src/extensions/context-view/ui/codemap.md +82 -0
  18. package/src/extensions/context-view/ui/context-view-dialog.ts +59 -0
  19. package/src/extensions/context-view/ui/injections-model.ts +118 -0
  20. package/src/extensions/context-view/ui/injections-view.ts +264 -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 +613 -0
  24. package/src/extensions/context-view/usage.ts +432 -0
  25. package/src/extensions/model-select/codemap.md +34 -17
  26. package/src/extensions/model-select/model-select-dialog.ts +85 -324
  27. package/src/index.ts +2 -0
  28. package/src/libs/codemap.md +8 -1
  29. package/src/libs/modal/README.md +212 -0
  30. package/src/libs/modal/codemap.md +34 -0
  31. package/src/libs/modal/index.ts +29 -0
  32. package/src/libs/modal/list-navigator.ts +167 -0
  33. package/src/libs/modal/modal-dialog.ts +297 -0
  34. package/src/libs/modal/navigation/pi-scheme.ts +33 -0
  35. package/src/libs/modal/navigation/vim-scheme.ts +56 -0
  36. package/src/libs/modal/preview-layer.ts +87 -0
  37. package/src/libs/modal/render-cache.ts +33 -0
  38. package/src/libs/modal/tab-strip.ts +87 -0
  39. package/src/libs/modal/tabs/list-tab.ts +159 -0
  40. package/src/libs/modal/text.ts +88 -0
  41. package/src/libs/modal/types.ts +70 -0
  42. package/src/schemas/codemap.md +100 -18
  43. package/src/schemas/config.schema.ts +3 -0
  44. package/src/schemas/context-view.config.schema.ts +13 -0
@@ -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,213 @@
1
+ # src/extensions/context-view/
2
+
3
+ ## Responsibility
4
+
5
+ Provides optional, TUI-only inspection of model-context occupancy and Initial-phase context injections. Disabled by default; lazily registered only after a session starts with `context_view` enabled. Two inspection surfaces are exposed:
6
+
7
+ - `/context-view` command (registered as `context-view`).
8
+ - `pi.vimKeys.event:pi-qol.context_view` Vim event (defined in `constants.ts` and `src/constants.ts`).
9
+
10
+ All 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.
11
+
12
+ ## Architecture & Design Patterns
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.
16
+ - **Controller / data preparation**: `context-view-controller.ts` isolates the command/UI data path from the event-driven capture path.
17
+ - **Stateful UI shell with stateful child tabs**: `ContextViewDialog` (shell) retains `UsageView` and `InjectionsView` instances; navigation is shared via `VimNavigation`.
18
+ - **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
+
21
+ ## Module Roles
22
+
23
+ ### `model.ts` — Semantic model
24
+
25
+ Pure types shared by capture, measurement, and UI.
26
+
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.
30
+ - `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
+
32
+ ### `measure.ts` — Prompt/tool measurement
33
+
34
+ Pure measurement of the captured system prompt.
35
+
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.
42
+
43
+ ### `capture.ts` — Capture-once state + silent probe
44
+
45
+ Stateful capture and the single allowed silent probe.
46
+
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.
50
+ - `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.
52
+
53
+ ### `usage.ts` — Usage classification
54
+
55
+ Pure composition of the Usage view.
56
+
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).
60
+ - `collectPreviewEntries()`: flattens a category for chronological preview rendering.
61
+ - `toReportedUsage()`: converts pi's `ContextUsage` into the view model.
62
+
63
+ ### `context-view-controller.ts` — Data preparation
64
+
65
+ Command/event data preparation and degraded native fallback.
66
+
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.
68
+ - Returns `ContextViewData` with `initial`, `usage`, and optional `degradedReason`.
69
+
70
+ ### `index.ts` — Registration, lifecycle, persistence
71
+
72
+ Wires the extension into `ExtensionAPI`.
73
+
74
+ - `registerContextView()`: lazy registration on the first enabled `session_start`.
75
+ - `activateContextView()`: installs event handlers, restores/persists probe identities, and registers the command and Vim event.
76
+ - 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.
81
+ - `message_start`: records probe message identities.
82
+ - `message_end`: sanitizes aborted probe assistant messages.
83
+ - `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.
86
+ - Command handler validates enabled flag, no arguments, and TUI mode before opening the dialog.
87
+ - Vim event handler opens the dialog from the latest context.
88
+
89
+ ### `constants.ts`
90
+
91
+ - `COMMAND_NAME = 'context-view'`.
92
+ - `PI_VIM_KEY_EVENT_ID`: shared Vim event id helper.
93
+
94
+ ## UI Roles
95
+
96
+ ### `ui/context-view-dialog.ts`
97
+
98
+ Bounded half-height inline shell.
99
+
100
+ - `ContextViewDialog`: implements `Component` and `Focusable` by wrapping a `ModalDialog` from the shared modal library (`src/libs/modal/`), configured with the Vim navigation scheme, half-height bound, and the degraded reason as a shell notice.
101
+ - `Tab`/`Shift+Tab` switches between `usage` and `injections`; both tab instances are retained so each preserves its scroll/selection/preview-layer state.
102
+ - Vim keys (`j/k`, arrows, `Ctrl+u/d`, `gg/G`, Enter, Esc/`q`) are parsed by the library's `VimNavigationScheme`; unhandled input goes to the active tab.
103
+ - Height is bounded to half the terminal by the shell.
104
+
105
+ ### `ui/usage-view.ts`
106
+
107
+ Stateful Usage tab (`ModalTab`).
108
+
109
+ - Renders a proportional 14×14 context-window map (`UsageMap`), category legend, and reported/estimated summary within the shell-provided content height.
110
+ - Map scale toggles between `window` (reported context window) and `fit` (115% headroom, rounded to 2 significant digits) with `z` when applicable.
111
+ - 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.
112
+ - Handles invisible-reasoning metadata display in Agent Thinking Messages.
113
+ - Caches rendered output via the library's `RenderCache` and invalidates on theme/selection/scroll changes.
114
+
115
+ ### `ui/injections-view.ts`
116
+
117
+ Stateful Injections tab (`ModalTab`).
118
+
119
+ - 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.
121
+ - Tree rendering uses `├─`/`└─`/`│` prefixes and a stable shared value column.
122
+ - Currently only the `[INITIAL]` tab is rendered; `[Runtime]` is intentionally hidden until implemented.
123
+
124
+ ### `ui/injections-model.ts`
125
+
126
+ Pure presentation model for Injections.
127
+
128
+ - `InjectionRow`: flattened row types (`group`, `item`, `separator`, `total`).
129
+ - `buildInjectionRows()`: flattens `InitialSnapshot` into rows.
130
+ - `collectItemsById()`: indexes items (including children) for preview lookup.
131
+ - `normalizePreviewText()` / `normalizeInlineText()`: sanitize terminal escape sequences and collapse whitespace.
132
+ - `ListNavigator`/`PreviewScroller` moved to the shared modal library (`src/libs/modal/list-navigator.ts`).
133
+
134
+ ### `ui/usage-map.ts`
135
+
136
+ Pure 14×14 proportional map model.
137
+
138
+ - `buildUsageMap()`: assigns cells to categories by largest overlap; fills `full`, `partial`, `buffer`, or `free`.
139
+ - `calculateFitMapScale()`: computes a Fit denominator with 115% headroom, capped at the reported context window and floored at 10,000 tokens.
140
+
141
+ ### Shared modal library
142
+
143
+ `ui/navigation.ts` and `ui/layout.ts` were absorbed into `src/libs/modal/`:
144
+
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`.
147
+
148
+ ### `ui/skill-preview.ts`
149
+
150
+ Preview-only recognition of pi `<skill name="...">` wrappers.
151
+
152
+ - `splitSkillPreview()`: splits user-message text into `text` and `skill` segments so the UI can render compact skill badges.
153
+
154
+ ## Data Flow
155
+
156
+ 1. `registerContextView()` waits for the first enabled `session_start`, then calls `activateContextView()`.
157
+ 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.
160
+ 5. On `agent_settled`, the probe is settled and new identities are persisted to `pi-context-view:probe-identities`.
161
+ 6. When the user invokes `/context-view` or the Vim event, `prepareContextViewData()`:
162
+ - waits for agent idle;
163
+ - 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`.
167
+ 7. `ContextViewDialog` opens on the Usage tab, bounded to half terminal height, and routes input to the active tab while retaining both tab states.
168
+
169
+ ## State Transitions
170
+
171
+ ### InitialCaptureState
172
+
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.
175
+
176
+ ### SilentProbeState
177
+
178
+ - `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.
182
+ - `settle(captured)` → `running → settled`.
183
+ - `fail(reason)` → any pending phase → `failed`.
184
+ - Identities are persisted only after settlement or shutdown.
185
+
186
+ ### ContextViewDialog
187
+
188
+ - `usage ↔ injections` via `Tab`/`Shift+Tab`, including while a preview layer is open.
189
+ - The active tab handles selection and scroll via navigation actions; Enter pushes a preview layer.
190
+ - `Esc`/`q` pops the active tab's preview layer first, then closes the dialog.
191
+
192
+ ## Integration Points
193
+
194
+ - **Config**: `config-loader.isEnabled('context_view')` gates activation and command use.
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()`.
197
+ - **TUI**: `TUI`, `Theme`, `KeybindingsManager`, `Component`, `Focusable`, `Key`, `matchesKey`, `visibleWidth`, `wrapTextWithAnsi`.
198
+ - **Modal library**: `src/libs/modal/` (`ModalDialog`, `VimNavigationScheme`, `ModalTab`, `PreviewLayer`, `ListNavigator`, `RenderCache`, text/layout helpers).
199
+ - **Pi constants**: `piVimKeyEventId()` from `src/constants.ts`.
200
+ - **Custom session entry**: `pi-context-view:probe-identities` for cross-runtime identity persistence.
201
+
202
+ ## Child Map
203
+
204
+ - See [`ui/codemap.md`](ui/codemap.md) for a detailed map of the Usage and Injections view internals, navigation, and rendering utilities.
205
+
206
+ ## Constraints
207
+
208
+ - Captured prompt, tool, skill, context-file, and message content stays process-local and must never be logged or serialized.
209
+ - Only synthetic probe `role + timestamp` identities may be persisted.
210
+ - The silent probe is limited to one attempt per session; it aborts the real turn and cleans up the transcript.
211
+ - The view requires TUI mode; it warns in non-TUI modes.
212
+ - The command accepts no arguments.
213
+ - `PageUp`/`PageDown`/`Home`/`End` are intentionally replaced by Vim bindings.
@@ -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');