@0xkahi/pi-qol 1.0.0 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xkahi/pi-qol",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "quality of life pi extensions",
5
5
  "type": "module",
6
6
  "keywords": [
package/src/codemap.md CHANGED
@@ -9,31 +9,32 @@ It coordinates four feature modules:
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
+ - **context_view**: Lazily captures and inspects the initial provider context, then opens a bounded half-height inline Usage/Injections interface through `/context-view` or `pi.vimKeys.event:pi-qol.context_view`.
13
13
 
14
- Shared concerns live here too: extension configuration loading, path resolution, model/auth resolution, and Zod schemas for every feature.
14
+ Shared concerns live here too: extension configuration loading, path resolution, model/auth resolution, Zod schemas for every feature, and shared libraries under `libs/` — `libs/subscription-usage/` (provider usage facade) and `libs/modal/` (the self-contained modal dialog library used by `model_select` and `context_view`).
15
15
 
16
16
  ## Design Patterns
17
17
 
18
- - **Plugin / Extension registration**: `index.ts` is a thin bootstrap that instantiates shared services and calls `register*` factory functions for each feature. Each feature registers itself against the `ExtensionAPI` event bus and command surface.
19
- - **Event-driven lifecycle**: Features hook into `session_start`, `session_shutdown`, and `before_agent_start` events. They gate behaviour behind config flags and store transient state in closure variables (`lastSessionStartReason`, `titleController`, `installed`, `latestCtx`).
18
+ - **Plugin / Extension registration**: `index.ts` is a thin bootstrap that creates a single `ConfigLoader` and calls each feature's `register*` factory. `registerContextView`, `registerCustomFooter`, and `registerModelSelect` are lazy-activated once per process when a `session_start` arrives with the feature enabled; `registerAutoSessionName` attaches its event listeners immediately.
19
+ - **Event-driven lifecycle**: Features hook into `session_start`, `session_shutdown`, `before_agent_start`, `input`, `turn_start`, `message_start`, `message_end`, `context`, `agent_settled`, and cross-extension events. They gate behaviour behind config flags and store transient state in closure variables (`lastSessionStartReason`, `titleController`, `installed`, `latestCtx`, `registered`, probe state, capture state).
20
20
  - **Configuration layering**: `ConfigLoader` merges a built-in default with a global JSON config and an optional project-level config, validated and typed with Zod. Only trusted projects load project-level overrides.
21
21
  - **Strategy pattern for subscription usage**: `SubscriptionUsageManager` dispatches to provider-specific `SubscriptionUsageStrategy` implementations (`AnthropicOauthUsageStrategy`, `OpenAiCodexUsageStrategy`) behind a common `SubscriptionUsageApi` interface.
22
- - **Component-based TUI**: `CustomFooterComponent` and `ModelSelectDialog` implement the host TUI's `Component`/`Focusable` interfaces, render to string arrays, and rely on the host for input routing and re-rendering.
22
+ - **Component-based TUI**: `CustomFooterComponent`, `ModelSelectDialog`, and `ContextViewDialog` implement the host TUI's `Component`/`Focusable` interfaces, render to string arrays, and rely on the host for input routing and re-rendering. Both dialogs are thin configurations of the shared `libs/modal/` `ModalDialog` shell (tab strategies, pluggable navigation schemes, per-tab preview layers).
23
23
  - **Abortable async work**: `auto_session_name` tracks an `AbortController` across `before_agent_start` invocations so stale title requests are cancelled before a new one starts.
24
+ - **Synthetic-probe capture**: `context_view` uses `InitialCaptureState` to freeze the first eligible provider context and `SilentProbeState` to emit a single empty probe when the user opens the view before any real turn has occurred.
24
25
  - **Utility classes as pure helpers**: `PathUtil`, `ModelResolver`, `ModelFormatter`, `AutoSessionNameGuard`, `AutoSessionNameTitleGenerator` are stateless or request-scoped helpers.
25
26
 
26
27
  ## Data & Control Flow
27
28
 
28
29
  1. **Bootstrap** (`index.ts`)
29
- - Creates `ConfigLoader`.
30
+ - Creates a singleton `ConfigLoader`.
30
31
  - On every `session_start`, calls `config.initializeConfig(ctx)`; surfaces validation errors via `ctx.ui.notify`.
31
- - Registers the four feature modules, passing the shared loader.
32
+ - Calls `registerAutoSessionName`, `registerModelSelect`, `registerCustomFooter`, and `registerContextView`, each receiving the shared loader.
32
33
 
33
34
  2. **Config loading** (`config-loader.ts`, `utils/path.util.ts`, `schemas/*.schema.ts`)
34
35
  - Defaults → global `~/.pi/extensions/pi-qol/config.json` → project `.pi/extensions/pi-qol/config.json` (if trusted).
35
36
  - Each partial config is shallow-merged per top-level key and re-validated by `ConfigSchema`.
36
- - `PathUtil` owns the config/auth file path conventions.
37
+ - `PathUtil` owns the config/auth file path conventions and shell-style variable expansion.
37
38
 
38
39
  3. **auto_session_name** (`extensions/auto-session-name/`)
39
40
  - Captures `session_start.reason`.
@@ -42,20 +43,28 @@ Shared concerns live here too: extension configuration loading, path resolution,
42
43
  - `AutoSessionNameTitleGenerator` builds a title-generation context, calls `completeSimple` from `pi-ai`, strips thinking tags/quotes, truncates to `MAX_TITLE_LENGTH`, and applies it via `pi.setSessionName`.
43
44
 
44
45
  4. **model_select** (`extensions/model-select/`)
45
- - Lazily registers once on `session_start` when enabled.
46
- - `/select-model [args]` handler refreshes the registry, attempts an exact provider/model match, otherwise opens a custom TUI dialog with Favourites, group, and Search tabs.
47
- - `ModelSelectDialog` filters search items with fuzzy matching, navigates favourites/search sections, and returns the chosen model to `pi.setModel`.
46
+ - Lazy-activates once on `session_start` when enabled.
47
+ - `/select-model [args]` handler waits for the session to be idle, refreshes the registry, attempts an exact provider/model match, otherwise opens a custom TUI dialog with Favourites, group, and Search tabs.
48
+ - `ModelSelectDialog` configures a shared `ModalDialog` with one `ListTab` per section (fuzzy filtering via the shell's shared filter input, wrap-around selection) and returns the chosen model to `pi.setModel` (optionally setting the configured default reasoning level).
48
49
  - `PI_VIM_KEY_EVENT_ID` allows other extensions to trigger the same picker.
49
50
 
50
- 5. **custom_footer** (`extensions/custom-footer/`)
51
+ 5. **context_view** (`extensions/context-view/`)
52
+ - Lazy-activates once on `session_start` when enabled; restores previously persisted probe message identities from the session manager.
53
+ - Owns `before_agent_start` prompt options; freezes the first eligible provider context snapshot on the `context` event.
54
+ - `input` observes extension empty inputs, `message_start`/`message_end` records probe identities, `turn_start` aborts the current probe, and `agent_settled`/`session_shutdown` settle the probe attempt.
55
+ - `/context-view` and the Vim event handler both call `prepareContextViewData`, which triggers a silent authenticated probe when no snapshot exists yet, then opens the `ContextViewDialog`.
56
+
57
+ 6. **custom_footer** (`extensions/custom-footer/`)
51
58
  - On first enabled `session_start`, installs a footer component via `ctx.ui.setFooter`.
52
59
  - Each render reads live data from `ExtensionContext` (`sessionManager`, `modelRegistry`, `model`, `getContextUsage`, `footerData`), calculates session totals, formats tokens/cost/context usage, and optionally fetches subscription usage through cached strategies.
53
60
 
54
61
  ## Integration Points
55
62
 
56
- - **@earendil-works/pi-coding-agent**: Provides `ExtensionAPI`, `ExtensionContext`, `ExtensionCommandContext`, events (`session_start`, `session_shutdown`, `before_agent_start`), command registration (`pi.registerCommand`), UI notifications (`ctx.ui.notify`), footer injection (`ctx.ui.setFooter`), custom dialogs (`ctx.ui.custom`), session naming (`pi.setSessionName`/`getSessionName`), and model selection (`pi.setModel`/`getThinkingLevel`).
57
- - **@earendil-works/pi-ai**: Used for `completeSimple`, `Model<Api>`, `modelsAreEqual`, and model-metadata types during title generation and model selection.
58
- - **@earendil-works/pi-tui**: Provides the `Component`/`Focusable` contracts, `TUI`, `Theme`, `Input`, and text-width helpers (`truncateToWidth`, `visibleWidth`, `fuzzyFilter`) used by the footer and model picker.
63
+ - **@earendil-works/pi-coding-agent**: Provides `ExtensionAPI`, `ExtensionContext`, `ExtensionCommandContext`, events (`session_start`, `session_shutdown`, `before_agent_start`, `input`, `turn_start`, `message_start`, `message_end`, `context`, `agent_settled`), command registration (`pi.registerCommand`), UI notifications (`ctx.ui.notify`), footer injection (`ctx.ui.setFooter`), custom dialogs (`ctx.ui.custom`), session naming (`pi.setSessionName`/`getSessionName`), model selection (`pi.setModel`/`getThinkingLevel`), session management (`ctx.sessionManager`), and tool registries (`pi.getAllTools`/`pi.getActiveTools`).
64
+ - **@earendil-works/pi-ai**: Used for `completeSimple`, `Model<Api>`, `modelsAreEqual`, `getSupportedThinkingLevels`, and model-metadata types during title generation and model selection.
65
+ - **@earendil-works/pi-tui**: Provides the `Component`/`Focusable` contracts, `TUI`, `Theme`, `Input`, `KeybindingsManager`, and text-width helpers (`truncateToWidth`, `visibleWidth`, `fuzzyFilter`) used by the footer, model picker, and context view.
59
66
  - **Filesystem**: Reads global and project JSON configs and `~/.pi/auth.json` for OAuth tokens.
60
67
  - **External provider APIs**: `SubscriptionUsageApi` and strategies call Anthropic/OpenAI Codex usage endpoints when OAuth auth is present.
61
- - **Cross-extension events**: `piVimKeyEventId` from `constants.ts` lets other Pi extensions emit events that `model_select` listens on.
68
+ - **Cross-extension events**: `piVimKeyEventId` from `constants.ts` generates event ids consumed by `model_select` (`pi-qol.model_select`) and `context_view` (`pi-qol.context_view`).
69
+
70
+ (End of file)
@@ -2,16 +2,16 @@
2
2
 
3
3
  ## Responsibility
4
4
 
5
- Automatically generate and apply a short, descriptive name for a Pi session based on the user's opening message. The extension runs once per session, only on the user's first turn, and only when no session name has already been set and the session is not a child/fork. Generated titles are surfaced through the normal Pi session name API so they appear in the UI and are persisted with the session.
5
+ Generate and apply a short, descriptive name for a Pi session based on the user's first user turn. The extension runs once per session, only on the user's first turn, and only when no session name has already been set and the session is not a child/fork. Generated titles are applied through the normal Pi session name API (`setSessionName`) so they appear in the UI and persist with the session.
6
6
 
7
7
  ## Design Patterns
8
8
 
9
9
  - **Event-driven extension registration**: `registerAutoSessionName` attaches handlers to Pi lifecycle events (`session_start`, `before_agent_start`, `session_shutdown`) and coordinates state across them.
10
- - **Guard object**: `AutoSessionNameGuard` isolates all preconditions (feature enabled check is kept in the caller) so the main flow reads as a simple chain of boolean decisions.
10
+ - **Guard object**: `AutoSessionNameGuard` isolates all preconditions (enabled check is kept in the caller) so the main flow reads as a simple chain of boolean decisions.
11
11
  - **Static command object**: `AutoSessionNameTitleGenerator` encapsulates the entire LLM-backed title generation as a single static entry point with pure helper methods for extraction, cleaning, and truncation.
12
12
  - **Prompt-as-data**: `prompt.ts` builds a `Context` value object containing a detailed system prompt and a single user message; no prompt logic leaks into the generator.
13
- - **Dependency injection by structural typing**: All collaborators are accepted as `Pick<...>` or local interfaces, making the extension easy to unit test and minimizing coupling to the full ExtensionAPI surface.
14
- - **Cancellation token**: A module-level `AbortController` is created per title request and aborted on `session_shutdown` or when a newer request starts, preventing stale completions from overwriting the session name.
13
+ - **Dependency injection by structural typing**: All collaborators are accepted as `Pick<...>` or local interfaces, and the LLM call is optionally parameterized by `completeFn`, making the extension easy to unit test and minimizing coupling to the full ExtensionAPI surface.
14
+ - **Cancellation token**: A module-level `AbortController` is created per title request. It is aborted before a newer request starts, on `session_shutdown`, and propagated into the LLM completion so stale completions cannot overwrite the session name.
15
15
  - **Defensive post-condition check**: After applying the title, the code compares `pi.getSessionName()` with the generated text and warns if they diverge.
16
16
 
17
17
  ## Data & Control Flow
@@ -23,12 +23,13 @@ Automatically generate and apply a short, descriptive name for a Pi session base
23
23
  - The session is not a child/fork (`startReason !== 'fork'` and no `parentSession` header).
24
24
  - This is the user's first turn (zero prior user messages in the branch).
25
25
  - The current user prompt is non-empty.
26
- 3. **Model resolution**: `ModelResolver` resolves the configured title model into a concrete `ResolvedModel` (model, API key, headers, reasoning preference). Errors are surfaced via `ctx.ui.notify`.
27
- 4. **Title generation**: `AutoSessionNameTitleGenerator.generateAndApplyTitle` sends a single-turn completion to the LLM using the context from `buildTitleContext`.
28
- 5. **Title cleaning**: The raw response has `<think>` blocks stripped, is reduced to the first non-empty line, has surrounding quotes removed, and is truncated to `MAX_TITLE_LENGTH`.
29
- 6. **Application**: The cleaned title is applied via `pi.setSessionName`. If application fails or returns a different value, a warning is shown.
30
- 7. **Feedback**: Success or failure is reported through `ctx.ui.notify`.
31
- 8. **Cancellation/reset**: `session_shutdown` aborts any pending request and clears the controller.
26
+ 3. **Cancellation of stale request**: Any existing `titleController` is aborted and replaced with a fresh `AbortController` for this request.
27
+ 4. **Model resolution**: `ModelResolver` resolves the configured title model (or the default fallback) into a concrete `ResolvedModel` (model, API key, headers, reasoning preference). Errors are surfaced via `ctx.ui.notify`.
28
+ 5. **Title generation**: `AutoSessionNameTitleGenerator.generateAndApplyTitle` sends a single-turn completion to the LLM using the context from `buildTitleContext`. The call carries `maxRetries`, `maxTokens`, and the abort signal.
29
+ 6. **Title cleaning**: The raw response has `<think>` blocks stripped, is reduced to the first non-empty line, has surrounding quotes removed, and is truncated to `MAX_TITLE_LENGTH`.
30
+ 7. **Application**: The cleaned title is applied via `pi.setSessionName`. If application fails or returns a different value, a warning is shown.
31
+ 8. **Feedback**: Success or failure is reported through `ctx.ui.notify`.
32
+ 9. **Cancellation/reset**: `session_shutdown` aborts any pending request and clears the controller.
32
33
 
33
34
  ## Integration Points
34
35
 
@@ -36,13 +37,17 @@ Automatically generate and apply a short, descriptive name for a Pi session base
36
37
  - Events: `session_start`, `session_shutdown`, `before_agent_start`.
37
38
  - Methods: `getSessionName`, `setSessionName`.
38
39
  - **Pi Context/session manager** (`ctx.sessionManager`):
39
- - `getBranch()` and `getHeader()` are used to detect first user turn and child sessions.
40
+ - `getBranch()` and `getHeader()` are used to detect the first user turn and child sessions.
40
41
  - **ConfigLoader** (`../../config-loader`):
41
42
  - `isEnabled('auto_session_name')` toggles the feature.
42
43
  - `getAutoSessionName()` supplies the optional per-feature model override.
43
44
  - **ModelResolver** (`../../utils/model-resolver.util`):
44
45
  - Resolves the configured model string into a full `ResolvedModel` usable by `pi-ai`.
45
- - **pi-ai** (`@earendil-works/pi-ai`):
46
+ - **pi-ai compat** (`@earendil-works/pi-ai/compat`):
46
47
  - `completeSimple` performs the actual LLM completion.
47
48
  - **Pi UI notifications** (`ctx.ui.notify`):
48
49
  - All user-facing status, warnings, and errors are emitted through the Pi notification channel.
50
+ - **Web/Node `AbortController`**:
51
+ - Used to cancel in-flight LLM completion requests.
52
+
53
+ (End of file)
@@ -7,19 +7,169 @@ This folder contains the feature-level extension modules for `pi-qol`. Each chil
7
7
  Current features:
8
8
 
9
9
  - `auto-session-name` – automatically generates and applies a concise session title from the user’s first message.
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.
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, fuzzy search, provider filtering, and inline or overlay layout.
11
+ - `context-view` – captures model context contributions and displays Usage/Injections in a bounded half-height inline tabbed interface opened by command or Vim event.
11
12
  - `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.
13
13
 
14
- ## Design Patterns
14
+ ---
15
15
 
16
- - **Registration function pattern**: each module exports a single `register*` function that takes `ExtensionAPI` and a `{ config: ConfigLoader }` dependency object. `src/index.ts` calls all three registration functions after initializing configuration.
17
- - **Event-driven lifecycle wiring**: registration is non-blocking; actual work is triggered by Pi runtime events (`session_start`, `session_shutdown`, `before_agent_start`).
18
- - **Lazy / once-only activation**: `model-select` and `custom-footer` use guard flags (`modelSelectRegistered`, `installed`) to ensure handlers or UI components are registered only once per process.
19
- - **Command registration**: `model-select` registers a slash command via `pi.registerCommand` and defers heavy work to an async handler.
20
- - **TUI component pattern**: `custom-footer` constructs a `Component` that renders live on each frame, invalidating Pi’s default footer rendering.
16
+ ## Extension Modules
17
+
18
+ ### 1. `auto-session-name`
19
+
20
+ #### Context view
21
+
22
+ `registerAutoSessionName` keeps a small module-level state: `lastSessionStartReason` (the `reason` from the latest `session_start`) and `titleController` (the current `AbortController` for the in-flight title generation). This state is intentionally minimal because the feature is single-shot per session.
23
+
24
+ #### Event / lifecycle registration
25
+
26
+ The registration function wires three `ExtensionAPI` events:
27
+
28
+ - `session_start` – stores the session start reason for later child-session detection.
29
+ - `session_shutdown` – aborts and clears any pending title request.
30
+ - `before_agent_start` – performs the guard checks, aborts the previous request, and starts the async title generation.
31
+
32
+ #### Data & control flow
33
+
34
+ 1. On `before_agent_start` the handler short-circuits unless:
35
+ - `auto_session_name` is enabled.
36
+ - No session name is currently set.
37
+ - The session is not a child/fork session (using `lastSessionStartReason` and `ctx.sessionManager`).
38
+ - This is the user’s first turn.
39
+ - The current prompt contains non-empty text.
40
+ 2. The configured model is resolved via `ModelResolver` from the per-feature config.
41
+ 3. `AutoSessionNameTitleGenerator.generateAndApplyTitle` builds a single-turn prompt, calls `completeSimple`, strips `<think>` blocks, cleans and truncates the result, and applies it via `pi.setSessionName`.
42
+ 4. A post-condition compares `pi.getSessionName()` with the generated title; a warning is shown if they diverge.
43
+ 5. Success or any failure is reported through `ctx.ui.notify`.
44
+
45
+ #### Integration points
46
+
47
+ - **`@earendil-works/pi-coding-agent`**: `ExtensionAPI` events (`session_start`, `session_shutdown`, `before_agent_start`), `getSessionName`, `setSessionName`, and `ctx.ui.notify`.
48
+ - **`@earendil-works/pi-ai`**: `completeSimple` for the LLM title completion.
49
+ - **`../../config-loader`**: `isEnabled('auto_session_name')` and `getAutoSessionName()` for the feature toggle and model override.
50
+ - **`../../utils/model-resolver.util`**: `ModelResolver` resolves provider/model/auth configuration.
51
+ - **`ctx.sessionManager`**: used by `AutoSessionNameGuard` to detect first user turns and parent sessions.
52
+
53
+ ---
54
+
55
+ ### 2. `model-select`
56
+
57
+ #### Context view
58
+
59
+ `registerModelSelect` exposes `applySelectedModel` and `showModelSelector` as the public action surface. The registration itself is lazy: `modelSelectRegistered` ensures `activateModelSelect` is only run once per process. `activateModelSelect` caches the most recent `ExtensionContext` in `latestCtx` so the cross-extension event bus can open the picker even when no command context is available.
60
+
61
+ #### Event / lifecycle registration
62
+
63
+ - `session_start` – the outer `registerModelSelect` listener checks the feature flag and lazily activates the module once.
64
+ - Inside `activateModelSelect`:
65
+ - `session_start` refreshes `latestCtx`.
66
+ - `pi.registerCommand(COMMAND_NAME)` registers `/select-model` with the interactive handler.
67
+ - `pi.events.on(PI_VIM_KEY_EVENT_ID)` listens for cross-extension activation (e.g., from `pi-vim-keys`).
68
+
69
+ #### Data & control flow
70
+
71
+ 1. The command handler records the latest context, checks the feature flag, and calls `showModelSelector`.
72
+ 2. `showModelSelector` waits for idle when available, refreshes `ctx.modelRegistry`, and attempts an exact provider/model match through `findExactModel`.
73
+ 3. If an exact match succeeds, the model is applied immediately via `applySelectedModel` and the dialog is skipped.
74
+ 4. Otherwise, `buildModelLists` prepares Favourites, ordered group subsets, and Search items. Provider filtering is applied only to Search, and favourite auth/registry warnings are collected.
75
+ 5. `ctx.ui.custom` creates a `ModelSelectDialog` configured with the current model, lists, tab visibility, warnings, initial search, and layout.
76
+ 6. The dialog shares a single query across visible tabs, preserves per-tab selection, cycles tabs, and renders either inline or as a centered overlay at 85% width.
77
+ 7. On selection, `applySelectedModel` calls `pi.setModel` and, if supported, sets the configured default reasoning level via `pi.setThinkingLevel`; missing auth is reported as an error.
78
+
79
+ #### Integration points
80
+
81
+ - **`@earendil-works/pi-coding-agent`**: `ExtensionAPI` command registration, event subscription, `setModel`, `setThinkingLevel`, and `getThinkingLevel`; `ExtensionContext` / `ExtensionCommandContext` for `modelRegistry`, `ui`, `hasUI`, `model`, and `waitForIdle`.
82
+ - **`@earendil-works/pi-ai`**: `Model<Api>` type, `getSupportedThinkingLevels`, and `modelsAreEqual` helpers.
83
+ - **`@earendil-works/pi-tui`**: `Component`, `Focusable`, `Input`, `fuzzyFilter`, `matchesKey`, `Theme`, and width/truncation helpers.
84
+ - **`../../config-loader`**: `isEnabled('model_select')` and the full `model_select` configuration.
85
+ - **`../../constants`**: `piVimKeyEventId` generates the shared event id used by the Vim-keys integration.
86
+ - **Cross-extension consumers**: `pi.events.emit(PI_VIM_KEY_EVENT_ID)` opens the picker without invoking the slash command.
87
+
88
+ ---
89
+
90
+ ### 3. `context-view`
91
+
92
+ #### Context view
93
+
94
+ `registerContextView` is disabled by default and only activates once an enabled session starts. The activation keeps `InitialCaptureState` for the first provider snapshot, `SilentProbeState` for synthetic-probe management, and `latestCtx` for the event-bus handler. The module is intentionally careful to persist only synthetic probe identities (role/timestamp) and never real prompt, tool, or message content.
95
+
96
+ #### Event / lifecycle registration
97
+
98
+ `activateContextView` registers a dense set of lifecycle hooks:
99
+
100
+ - `session_start` – refreshes `latestCtx` and restores persisted probe identities.
101
+ - `input` – observes owned user inputs.
102
+ - `before_agent_start` – begins a probe run and prepares capture from system prompt options.
103
+ - `turn_start` – aborts the current probe run if needed.
104
+ - `message_start` / `message_end` – records and sanitizes assistant messages.
105
+ - `context` – filters provider messages, freezes the first eligible snapshot, and can optionally replace the outgoing messages.
106
+ - `agent_settled` – settles the probe and persists new identities.
107
+ - `session_shutdown` – persists identities and fails the probe.
108
+ - `pi.registerCommand(COMMAND_NAME)` registers `/context-view`.
109
+ - `pi.events.on(PI_VIM_KEY_EVENT_ID)` opens the view from a Vim event.
110
+
111
+ #### Data & control flow
112
+
113
+ 1. On an enabled session start, the module is installed and any persisted probe identities are restored.
114
+ 2. `before_agent_start` prepares the initial capture; the `context` event freezes the first eligible provider snapshot.
115
+ 3. If the view is opened before capture completes, a silent probe runs; synthetic messages are filtered, sanitized, and persisted by identity only.
116
+ 4. `prepareContextViewData` combines the snapshot, current native prompt/tool data, filtered session messages, and reported usage.
117
+ 5. `ContextViewDialog` opens as a Usage-first inline component bounded to 50% of the terminal height, retaining state for both the Usage and Injections tabs.
118
+ 6. Shared navigation (`j`/`k`, arrows, `Ctrl+u`/`d`, `gg`/`G`) is routed through `ui/navigation.ts`.
119
+
120
+ #### Integration points
121
+
122
+ - **`@earendil-works/pi-coding-agent`**: `ExtensionAPI` events, `registerCommand`, `events` bus, `buildSessionContext`, and `ctx.sessionManager`.
123
+ - **`../../config-loader`**: `isEnabled('context_view')` gates registration and command handlers.
124
+ - **`../../constants`**: `piVimKeyEventId` generates the cross-extension event id.
125
+ - **`@earendil-works/pi-tui`**: `Component`, `Input`, and focus/routing helpers for the dialog and child views.
126
+ - **`ui/` and `capture.ts`**: module-local helpers classify, measure, and render context usage and injections.
127
+
128
+ ---
129
+
130
+ ### 4. `custom-footer`
131
+
132
+ #### Context view
133
+
134
+ `registerCustomFooter` stores a single `installed` flag to prevent duplicate footer registration. The actual component is created per render by the factory passed to `ctx.ui.setFooter`, receiving live `tui`, `theme`, `footerData`, `ExtensionContext`, `ConfigLoader`, and a `getThinkingLevel` accessor.
135
+
136
+ #### Event / lifecycle registration
137
+
138
+ - `session_start` – the only registration event. When the feature is enabled and the footer is not yet installed, it calls `ctx.ui.setFooter` with a factory that creates a `CustomFooterComponent` for each render.
139
+ - No shutdown handler is required because the component implements `dispose` for its own cleanup.
140
+
141
+ #### Data & control flow
142
+
143
+ 1. On `session_start`, `setFooter` installs the custom footer factory.
144
+ 2. The TUI calls `CustomFooterComponent.render(width)` on every footer repaint.
145
+ 3. If the feature is disabled at render time, the component calls `ctx.ui.setFooter(undefined)` once to restore the default footer and returns an empty array.
146
+ 4. The component assembles up to three lines:
147
+ - `renderPathLine`: directory (with optional custom color), git branch, and session name.
148
+ - `renderStatsLine`: token totals, cache read/write, cache hit rate, estimated cost, context-window usage, subscription usage, and active model.
149
+ - Extension status line when statuses exist.
150
+ 5. `token-stats.ts` aggregates assistant-message token counts and cache hit rates from `sessionManager.getEntries()`.
151
+ 6. `SubscriptionUsageManager` caches OAuth usage with a TTL and coalesces in-flight requests; on update it calls `tui.requestRender()` to refresh the footer.
152
+ 7. `FooterDataProvider` watches git branch changes and similarly requests re-renders; the callback is removed in `dispose`.
153
+
154
+ #### Integration points
155
+
156
+ - **`@earendil-works/pi-coding-agent`**: `ExtensionAPI` events, `getThinkingLevel`; `ExtensionContext` for `model`, `modelRegistry`, `sessionManager`, `getContextUsage`, and `ui.setFooter`.
157
+ - **`@earendil-works/pi-tui`**: `Component` interface, `truncateToWidth`, `visibleWidth`, and `TUI.requestRender`.
158
+ - **`../../config-loader`**: `isEnabled('custom_footer')` and full footer configuration (colors, icons, display toggles).
159
+ - **`../../libs/subscription-usage/`**: `SubscriptionUsageApi` and provider-specific strategies (Anthropic OAuth, OpenAI Codex) for subscription usage.
160
+ - **`@0xkahi/cli-dye`**: truecolor ANSI styling for directory, model, and subscription usage segments.
161
+
162
+ ---
163
+
164
+ ## Cross-Cutting Design Patterns
165
+
166
+ - **Registration function pattern**: each module exports a single `register*` function that takes `ExtensionAPI` and a `{ config: ConfigLoader }` dependency object. `src/index.ts` calls all four registration functions after initializing configuration.
167
+ - **Event-driven lifecycle wiring**: registration is non-blocking; actual work is triggered by Pi runtime events (`session_start`, `session_shutdown`, `before_agent_start`, `input`, `turn_start`, `message_start`, `message_end`, `context`, `agent_settled`).
168
+ - **Lazy / once-only activation**: `model-select`, `context-view`, and `custom-footer` use guard flags (`modelSelectRegistered`, `registered`, `installed`) to ensure handlers or UI components are registered only once per process.
169
+ - **Command registration**: `model-select` and `context-view` register slash commands via `pi.registerCommand` and defer work to async handlers.
170
+ - **TUI component pattern**: `custom-footer` and the two dialogs construct Pi TUI components that render on every frame and participate in focus/input routing.
21
171
  - **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.
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.
172
+ - **Pure helpers / formatters**: `model-formatter.ts`, `token-stats.ts`, `model-lists.ts`, `prompt.ts`, `measure.ts`, and `usage.ts` keep transformation and rendering logic free of side effects.
23
173
  - **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.
24
174
  - **Abortable async work**: `auto-session-name` keeps an `AbortController` and cancels in-flight title generation on `session_shutdown` or a new `before_agent_start`.
25
175
 
@@ -58,10 +208,13 @@ Current features:
58
208
  ## Integration Points
59
209
 
60
210
  - **`@earendil-works/pi-coding-agent`** – `ExtensionAPI`, `ExtensionContext`, `ExtensionCommandContext`, events, commands, session manager, and UI notifications.
61
- - **`@earendil-works/pi-ai`** – model types (`Model`, `Api`), `completeSimple`, and `modelsAreEqual`.
211
+ - **`@earendil-works/pi-ai`** – model types (`Model`, `Api`), `completeSimple`, `getSupportedThinkingLevels`, and `modelsAreEqual`.
62
212
  - **`@earendil-works/pi-tui`** – `Component`, `Focusable`, `Input`, `TUI`, `Theme`, `KeybindingsManager`, and width helpers.
63
- - **`src/config-loader.ts`** – shared `ConfigLoader` used by all three registration functions for feature flags and section config.
213
+ - **`src/config-loader.ts`** – shared `ConfigLoader` used by all four registration functions for feature flags and section config.
64
214
  - **`src/utils/model-resolver.util.ts`** – resolves provider/model/auth configuration for `auto-session-name`.
65
215
  - **`src/libs/subscription-usage/`** – `SubscriptionUsageApi` and provider-specific strategies used by the footer to fetch OAuth subscription usage.
66
- - **`src/constants.ts` / `piVimKeyEventId`** – generates the cross-extension event id consumed by `model-select`.
216
+ - **`src/constants.ts` / `piVimKeyEventId`** – generates the cross-extension event ids consumed by `model-select` and `context-view`.
67
217
  - **`src/index.ts`** – orchestrates config initialization and calls each `register*` function in a fixed order.
218
+ - **`@0xkahi/cli-dye`** – truecolor ANSI styling used by the custom footer.
219
+
220
+ (End of file)
@@ -2,27 +2,212 @@
2
2
 
3
3
  ## Responsibility
4
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.
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
6
 
7
- ## Architecture
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`).
8
9
 
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.
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.
17
153
 
18
154
  ## Data Flow
19
155
 
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.
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.
25
205
 
26
206
  ## Constraints
27
207
 
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.
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.