@0xkahi/pi-qol 1.0.4 → 1.0.6

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/README.md CHANGED
@@ -54,8 +54,9 @@ shows the current directory as an icon plus basename, supports hex color overrid
54
54
  can hide token/cache clusters, and adds an OAuth subscription-usage progress bar
55
55
  for supported providers (Anthropic and OpenAI Codex).
56
56
 
57
- - **Directory line** — directory icon + basename, with optional git branch and
58
- session name.
57
+ - **Directory line** — optional inverse-styled agent badge followed by the
58
+ directory icon + basename, with optional git branch and session name. The badge
59
+ is disabled by default.
59
60
  - **Stats line** — cumulative input/output tokens, cache read/write/hit cluster,
60
61
  session cost (or `(sub)` when on a subscription), context-window usage, and the
61
62
  right-aligned model name (with provider prefix when multiple providers are
@@ -117,12 +118,15 @@ them (project overrides global):
117
118
  "enabled": true,
118
119
  "colors": {
119
120
  "directory": "#A78BFA",
120
- "modelName": "#60A5FA"
121
+ "modelName": "#60A5FA",
122
+ "agentName": "#FBBF24"
121
123
  },
122
124
  "display": {
123
125
  "tokens": true,
124
- "cache": true
125
- }
126
+ "cache": true,
127
+ "agentName": true
128
+ },
129
+ "defaultAgentName": "DEFAULT"
126
130
  }
127
131
  }
128
132
  ```
@@ -188,8 +192,11 @@ Context View is a fork of Dmitry Makarov's [pi-context-view](https://github.com/
188
192
  | `enabled` | `boolean` | `false` | Replace pi's built-in interactive footer. |
189
193
  | `display.tokens` | `boolean` | `true` | Show cumulative input/output token counts. |
190
194
  | `display.cache` | `boolean` | `true` | Show the custom cache read/write/hit cluster. |
195
+ | `display.agentName` | `boolean` | `false` | Prefix the first line with a padded bold inverse agent badge. |
196
+ | `defaultAgentName` | `string` | `DEFAULT` | Agent name restored at the start of each session. |
191
197
  | `colors.directory` | `hex` | — | Color the directory icon and basename. |
192
198
  | `colors.modelName` | `hex` | — | Color the right-aligned model name. |
199
+ | `colors.agentName` | `hex` | — | Agent badge foreground color before inversion. |
193
200
  | `colors.anthropicUsage` | `hex` | `#D97706` | Color the Claude subscription usage segment (bar + percentage). |
194
201
  | `colors.codexUsage` | `hex` | `#10B981` | Color the Codex subscription usage segment (bar + percentage). |
195
202
  | `icons.directory` | `string` | nerd font | Glyph shown before the directory basename. |
@@ -198,6 +205,29 @@ Context View is a fork of Dmitry Makarov's [pi-context-view](https://github.com/
198
205
  | `icons.cacheWrite` | `string` | nerd font | Glyph for cache-write tokens. |
199
206
  | `icons.refresh` | `string` | nerd font | Glyph shown before the subscription reset time. |
200
207
 
208
+ When enabled, the badge has no brackets, uses bold and inverse styling, and adds
209
+ one styled padding space on each side of the name. One normal, unstyled space
210
+ separates the trailing badge padding from the directory. Names are trimmed and
211
+ sanitized. Names wider than ten terminal columns are rendered as their first ten
212
+ visible columns plus `...`; badge padding does not count toward that limit, and
213
+ wide Unicode characters are never split. Badge color precedence is a valid event
214
+ color,
215
+ `colors.agentName`, then pi's `accent` theme color. Event-selected names and
216
+ colors are session-scoped: every `session_start` restores `defaultAgentName` and
217
+ clears the event color.
218
+
219
+ Other extensions can update the current identity through pi's event bus:
220
+
221
+ ```ts
222
+ pi.events.emit('pi.qol.event:set-agent-name', {
223
+ agentName: 'Reviewer',
224
+ color: '#FFFFFF', // optional; must be #RRGGBB
225
+ });
226
+ ```
227
+
228
+ Invalid or empty names are ignored. A missing or invalid event color clears any
229
+ previous event color and uses the normal fallback precedence.
230
+
201
231
  Project config shallow-merges each top-level section over global config. Arrays
202
232
  replace lower-precedence arrays, so project `model_select.favourite` or
203
233
  `model_select.groups` replaces the corresponding global array. Nested objects are
@@ -168,8 +168,10 @@
168
168
  },
169
169
  "display": {
170
170
  "tokens": true,
171
- "cache": true
172
- }
171
+ "cache": true,
172
+ "agentName": false
173
+ },
174
+ "defaultAgentName": "DEFAULT"
173
175
  },
174
176
  "type": "object",
175
177
  "properties": {
@@ -192,6 +194,10 @@
192
194
  "type": "string",
193
195
  "pattern": "^#[0-9a-fA-F]{6}$"
194
196
  },
197
+ "agentName": {
198
+ "type": "string",
199
+ "pattern": "^#[0-9a-fA-F]{6}$"
200
+ },
195
201
  "anthropicUsage": {
196
202
  "default": "#D97706",
197
203
  "type": "string",
@@ -239,7 +245,8 @@
239
245
  "display": {
240
246
  "default": {
241
247
  "tokens": true,
242
- "cache": true
248
+ "cache": true,
249
+ "agentName": false
243
250
  },
244
251
  "type": "object",
245
252
  "properties": {
@@ -250,8 +257,16 @@
250
257
  "cache": {
251
258
  "default": true,
252
259
  "type": "boolean"
260
+ },
261
+ "agentName": {
262
+ "default": false,
263
+ "type": "boolean"
253
264
  }
254
265
  }
266
+ },
267
+ "defaultAgentName": {
268
+ "default": "DEFAULT",
269
+ "type": "string"
255
270
  }
256
271
  }
257
272
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xkahi/pi-qol",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "quality of life pi extensions",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -43,13 +43,14 @@
43
43
  "@earendil-works/pi-tui": "*"
44
44
  },
45
45
  "devDependencies": {
46
- "@earendil-works/pi-ai": "^0.84.0",
47
- "@earendil-works/pi-coding-agent": "^0.84.0",
48
- "@earendil-works/pi-tui": "^0.84.0",
49
46
  "@biomejs/biome": "^2.4.15",
50
47
  "@changesets/cli": "^2.31.0",
51
- "@types/node": "^24.0.0",
48
+ "@earendil-works/pi-ai": "^0.85.0",
49
+ "@earendil-works/pi-coding-agent": "^0.85.0",
50
+ "@earendil-works/pi-server": "0.85.0",
51
+ "@earendil-works/pi-tui": "^0.85.0",
52
52
  "@types/bun": "latest",
53
+ "@types/node": "^24.0.0",
53
54
  "bun-types": "latest",
54
55
  "typescript": "^5"
55
56
  },
package/src/constants.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { ObjectValues } from './types';
2
2
 
3
3
  export const EXTENSION_ID = 'pi-qol';
4
+ export const SET_AGENT_NAME_EVENT_ID = 'pi.qol.event:set-agent-name';
4
5
 
5
6
  const SUB_EXTENSION_IDS = {
6
7
  auto_session_name: 'auto_session_name',
@@ -13,6 +13,7 @@ import { AGGREGATE_SOURCE_ID, buildSnapshot, type CaptureOrigin, type InitialSna
13
13
  export const PROBE_IDENTITIES_CUSTOM_TYPE = 'pi-context-view:probe-identities';
14
14
 
15
15
  const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
16
+ const SETUP_ABORT_ERROR_MESSAGE = 'This operation was aborted';
16
17
  const AGGREGATE_SOURCE: InjectionSource = {
17
18
  id: AGGREGATE_SOURCE_ID,
18
19
  label: 'extensions (aggregate)',
@@ -97,10 +98,11 @@ export class InitialCaptureState {
97
98
  * Freeze the Initial snapshot from the first context event. Returns the
98
99
  * existing snapshot on repeat calls, or undefined when `prepare()` never ran.
99
100
  */
100
- public finalize(input: CaptureFinalization): InitialSnapshot | undefined {
101
+ public finalize(buildInput: CaptureFinalization | (() => CaptureFinalization)): InitialSnapshot | undefined {
101
102
  if (this.initialSnapshot !== undefined) return this.initialSnapshot;
102
103
  if (this.pendingPreparation === undefined) return undefined;
103
104
 
105
+ const input = typeof buildInput === 'function' ? buildInput() : buildInput;
104
106
  const preparation = this.pendingPreparation;
105
107
  const tools = captureActiveTools(input.allTools, input.activeToolNames, {
106
108
  toolSnippets: preparation.toolSnippets,
@@ -115,6 +117,33 @@ export class InitialCaptureState {
115
117
  }
116
118
  }
117
119
 
120
+ /** Track the currently active session compaction without retaining stale signals. */
121
+ export class CompactionState {
122
+ private currentSignal: AbortSignal | undefined;
123
+
124
+ public get isActive(): boolean {
125
+ return this.currentSignal !== undefined && !this.currentSignal.aborted;
126
+ }
127
+
128
+ /** Begin tracking a live compaction signal; already-aborted signals are ignored. */
129
+ public begin(signal: AbortSignal): void {
130
+ if (signal.aborted) return;
131
+ this.currentSignal = signal;
132
+ signal.addEventListener(
133
+ 'abort',
134
+ () => {
135
+ if (this.currentSignal === signal) this.currentSignal = undefined;
136
+ },
137
+ { once: true },
138
+ );
139
+ }
140
+
141
+ /** Finish either a successful or failed compaction lifecycle. */
142
+ public finish(): void {
143
+ this.currentSignal = undefined;
144
+ }
145
+ }
146
+
118
147
  /**
119
148
  * State for one on-demand silent probe. It owns the timeout and exact synthetic
120
149
  * message identities, but leaves pi API calls and UI restoration to index.ts.
@@ -200,10 +229,10 @@ export class SilentProbeState {
200
229
  * so pi does not render an "Operation aborted" transcript row.
201
230
  */
202
231
  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);
232
+ const expectedAbort =
233
+ message.role === 'assistant' &&
234
+ (message.stopReason === 'aborted' || (message.stopReason === 'error' && message.errorMessage === SETUP_ABORT_ERROR_MESSAGE));
235
+ if (!this.isCurrentRun || !expectedAbort) return undefined;
207
236
  const identity = { role: 'assistant', timestamp: message.timestamp } satisfies SyntheticMessageIdentity;
208
237
  if (!this.identities.has(identityKey(identity))) return undefined;
209
238
  return { ...message, content: [], stopReason: 'stop', errorMessage: undefined };
@@ -1,5 +1,5 @@
1
- import { buildSessionContext, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
- import { buildNativeSnapshot, type InitialCaptureState, mergeContextOnlyMessages, type SilentProbeState } from './capture';
1
+ import { buildSessionContext, type ExtensionAPI, type ExtensionContext, SettingsManager } from '@earendil-works/pi-coding-agent';
2
+ import { buildNativeSnapshot, type CompactionState, type InitialCaptureState, mergeContextOnlyMessages, type SilentProbeState } from './capture';
3
3
  import type { ContextUsageSnapshot, InitialSnapshot } from './model';
4
4
  import { computeUsage, toReportedUsage } from './usage';
5
5
 
@@ -14,32 +14,53 @@ type PromptContext = ExtensionContext & {
14
14
  waitForIdle?: () => Promise<void>;
15
15
  };
16
16
 
17
+ interface ContextViewDependencies {
18
+ readAutoCompactReserveTokens?: (ctx: PromptContext) => number | undefined;
19
+ }
20
+
21
+ /** Read Pi's effective merged compaction reserve; optional settings never block the view. */
22
+ export function readAutoCompactReserveTokens(ctx: PromptContext): number | undefined {
23
+ try {
24
+ const settings = SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() });
25
+ if (!settings.getCompactionEnabled()) return undefined;
26
+ return settings.getCompactionReserveTokens();
27
+ } catch {
28
+ return undefined;
29
+ }
30
+ }
31
+
17
32
  /** Prepare Context View data without requiring command-only APIs for event callers. */
18
33
  export async function prepareContextViewData(
19
34
  pi: ExtensionAPI,
20
35
  ctx: PromptContext,
21
36
  capture: InitialCaptureState,
22
37
  probe: SilentProbeState,
38
+ compaction: CompactionState,
39
+ dependencies: ContextViewDependencies = {},
23
40
  ): Promise<ContextViewData> {
24
41
  if (ctx.waitForIdle) await ctx.waitForIdle();
25
42
  let initial = capture.snapshot;
26
43
  let degradedReason: string | undefined;
27
44
 
28
45
  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));
46
+ if (compaction.isActive) {
47
+ degradedReason = 'Silent probe unavailable: context compaction is in progress. Extension additions were not observed.';
48
+ } else {
49
+ const attempt = probe.start();
50
+ if (attempt.started && ctx.model && ctx.modelRegistry.hasConfiguredAuth(ctx.model)) {
51
+ try {
52
+ pi.sendUserMessage('');
53
+ } catch (error) {
54
+ probe.fail(error instanceof Error ? error.message : String(error));
55
+ }
56
+ } else if (attempt.started) {
57
+ probe.fail('Silent probe unavailable: no authenticated model is selected.');
35
58
  }
36
- } else if (attempt.started) {
37
- probe.fail('Silent probe unavailable: no authenticated model is selected.');
59
+ const outcome = await attempt.completion;
60
+ initial = capture.snapshot;
61
+ if (!initial)
62
+ degradedReason = `${outcome.status === 'failed' ? outcome.reason : 'Silent probe did not capture Initial.'} Extension additions were not observed.`;
38
63
  }
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
64
  }
44
65
 
45
66
  const options = capture.promptOptions ?? ctx.getSystemPromptOptions?.();
@@ -54,6 +75,7 @@ export async function prepareContextViewData(
54
75
  });
55
76
  const fallback = initial ?? current;
56
77
  const messages = probe.filterMessages(buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId()).messages);
78
+ const reserveReader = dependencies.readAutoCompactReserveTokens ?? readAutoCompactReserveTokens;
57
79
  return {
58
80
  initial: fallback,
59
81
  degradedReason,
@@ -62,6 +84,7 @@ export async function prepareContextViewData(
62
84
  messages,
63
85
  reported: toReportedUsage(ctx.getContextUsage()),
64
86
  modelLabel: ctx.model?.id,
87
+ autoCompactReserveTokens: reserveReader(ctx),
65
88
  }),
66
89
  };
67
90
  }
@@ -1,7 +1,7 @@
1
1
  import { buildSessionContext, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
2
  import type { ConfigLoader } from '../../config-loader';
3
3
  import { presentModal } from '../../libs/modal';
4
- import { InitialCaptureState, PROBE_IDENTITIES_CUSTOM_TYPE, parsePersistedIdentities, SilentProbeState } from './capture';
4
+ import { CompactionState, InitialCaptureState, PROBE_IDENTITIES_CUSTOM_TYPE, parsePersistedIdentities, SilentProbeState } from './capture';
5
5
  import { COMMAND_NAME, PI_VIM_KEY_EVENT_ID } from './constants';
6
6
  import { prepareContextViewData } from './context-view-controller';
7
7
  import { ContextViewDialog } from './ui/context-view-dialog';
@@ -9,6 +9,7 @@ import { ContextViewDialog } from './ui/context-view-dialog';
9
9
  function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; initialCtx: ExtensionContext }): void {
10
10
  const capture = new InitialCaptureState();
11
11
  const probe = new SilentProbeState();
12
+ const compaction = new CompactionState();
12
13
  let persistedIdentityCount = 0;
13
14
  let latestCtx: ExtensionContext = deps.initialCtx;
14
15
  const enabled = () => deps.config.isEnabled('context_view');
@@ -28,7 +29,7 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
28
29
  persistedIdentityCount = identities.length;
29
30
  };
30
31
  const openContextView = async (ctx: ExtensionContext) => {
31
- const data = await prepareContextViewData(pi, ctx, capture, probe);
32
+ const data = await prepareContextViewData(pi, ctx, capture, probe, compaction);
32
33
  const config = deps.config.getContextView();
33
34
  await presentModal(
34
35
  ctx.ui,
@@ -40,8 +41,14 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
40
41
  restoreProbeIdentities(deps.initialCtx);
41
42
  pi.on('session_start', (_event, ctx) => {
42
43
  latestCtx = ctx;
44
+ compaction.finish();
43
45
  if (enabled()) restoreProbeIdentities(ctx);
44
46
  });
47
+ pi.on('session_before_compact', event => {
48
+ if (enabled()) compaction.begin(event.signal);
49
+ });
50
+ pi.on('session_compact', () => compaction.finish());
51
+ pi.on('session_compact_failed', () => compaction.finish());
45
52
  pi.on('input', event => {
46
53
  if (enabled()) probe.observeInput(event.source, event.text);
47
54
  });
@@ -64,15 +71,14 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
64
71
  pi.on('context', (event, ctx) => {
65
72
  if (!enabled()) return;
66
73
  const messages = probe.filterMessages(event.messages);
67
- const baselineMessages = probe.filterMessages(buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId()).messages);
68
- capture.finalize({
74
+ capture.finalize(() => ({
69
75
  systemPrompt: ctx.getSystemPrompt(),
70
76
  messages,
71
- baselineMessages,
77
+ baselineMessages: probe.filterMessages(buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId()).messages),
72
78
  allTools: pi.getAllTools(),
73
79
  activeToolNames: pi.getActiveTools(),
74
80
  origin: probe.isCurrentRun ? 'synthetic-probe' : 'real-turn',
75
- });
81
+ }));
76
82
  return messages === event.messages ? undefined : { messages };
77
83
  });
78
84
  pi.on('agent_settled', (_event, ctx) => {
@@ -82,6 +88,7 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
82
88
  persistProbeIdentities();
83
89
  });
84
90
  pi.on('session_shutdown', () => {
91
+ compaction.finish();
85
92
  if (!enabled()) return;
86
93
  persistProbeIdentities();
87
94
  probe.fail('Session ended before the silent probe completed.');
@@ -12,7 +12,7 @@
12
12
  * optionally preceded by a "Current date" line (pi 0.80)
13
13
  * → anything after that footer was appended by before_agent_start handlers.
14
14
  */
15
- import { AGGREGATE_SOURCE_ID, type InjectionItem, type InjectionKind, type InjectionSource, PI_SOURCE_ID } from './model';
15
+ import { AGGREGATE_SOURCE_ID, type InjectionItem, type InjectionKind, type InjectionSection, type InjectionSource, PI_SOURCE_ID } from './model';
16
16
 
17
17
  const PI_SOURCE: InjectionSource = { id: PI_SOURCE_ID, label: 'pi', native: true };
18
18
  const AGGREGATE_SOURCE: InjectionSource = {
@@ -87,7 +87,11 @@ export function analyzeSystemPrompt(systemPrompt: string, options: PromptOptions
87
87
 
88
88
  /** Same chars/4 heuristic pi's estimateTokens uses for text content. */
89
89
  export function textTokens(text: string): number {
90
- return Math.ceil(text.length / 4);
90
+ return charTokens(text.length);
91
+ }
92
+
93
+ function charTokens(chars: number): number {
94
+ return Math.ceil(chars / 4);
91
95
  }
92
96
 
93
97
  /**
@@ -96,30 +100,18 @@ export function textTokens(text: string): number {
96
100
  * tools collapse into one aggregate pi-native item.
97
101
  */
98
102
  function measureTools(base: string, tools: ToolSlice[], items: InjectionItem[], carvedSpans: Span[]): void {
103
+ const carver = createPromptCarver(base, carvedSpans);
104
+ const claimedGuidelines = new Set(piOwnedGuidelines(tools));
99
105
  const builtinChildren: InjectionItem[] = [];
100
106
  for (const tool of tools) {
101
- const definition = `${tool.name}: ${tool.description}\n${tool.parametersJson}`;
107
+ const ownedGuidelines = claimGuidelines(tool, claimedGuidelines);
108
+ const definition: SectionDraft = { label: 'Definition', text: `${tool.name}: ${tool.description}\n${tool.parametersJson}` };
102
109
  if (tool.source === 'builtin') {
103
- builtinChildren.push(createItem(`tool:builtin:${tool.name}`, 'tool', PI_SOURCE, tool.name, definition));
110
+ builtinChildren.push(createToolItem(`tool:builtin:${tool.name}`, PI_SOURCE, tool.name, [definition]));
104
111
  continue;
105
112
  }
106
- let promptText = '';
107
- if (tool.snippet !== undefined) {
108
- const span = findExactSpan(base, `\n- ${tool.name}: ${tool.snippet}`);
109
- if (span !== undefined) {
110
- promptText += base.slice(span.start, span.end);
111
- carvedSpans.push(span);
112
- }
113
- }
114
- for (const guideline of tool.guidelines) {
115
- const span = findExactSpan(base, `\n- ${guideline.trim()}`);
116
- if (span !== undefined) {
117
- promptText += base.slice(span.start, span.end);
118
- carvedSpans.push(span);
119
- }
120
- }
121
- const source = extensionSource(tool.source);
122
- items.push(createItem(`tool:${tool.source}:${tool.name}`, 'tool', source, tool.name, promptText + definition));
113
+ const sections = [...carveToolPromptSections(carver, tool, ownedGuidelines), definition];
114
+ items.push(createToolItem(`tool:${tool.source}:${tool.name}`, extensionSource(tool.source), tool.name, sections));
123
115
  }
124
116
  if (builtinChildren.length > 0) {
125
117
  builtinChildren.sort((a, b) => b.tokens - a.tokens);
@@ -134,6 +126,74 @@ function measureTools(base: string, tools: ToolSlice[], items: InjectionItem[],
134
126
  }
135
127
  }
136
128
 
129
+ interface SectionDraft {
130
+ readonly label: string;
131
+ readonly text: string;
132
+ }
133
+
134
+ function carveToolPromptSections(carver: PromptCarver, tool: ToolSlice, ownedGuidelines: string[]): SectionDraft[] {
135
+ const sections: SectionDraft[] = [];
136
+ const snippet = tool.snippet === undefined ? undefined : carveBlockLine(carver, carver.toolsBlock, `\n- ${tool.name}: ${tool.snippet}`);
137
+ if (snippet !== undefined) sections.push({ label: 'Prompt Snippet', text: snippet });
138
+ let bullets = '';
139
+ for (const guideline of ownedGuidelines) bullets += carveBlockLine(carver, carver.guidelinesBlock, `\n- ${guideline}`) ?? '';
140
+ if (bullets.length > 0) sections.push({ label: 'Guidelines', text: bullets });
141
+ return sections;
142
+ }
143
+
144
+ interface PromptCarver {
145
+ readonly base: string;
146
+ readonly toolsBlock: Span | undefined;
147
+ readonly guidelinesBlock: Span | undefined;
148
+ readonly carvedSpans: Span[];
149
+ }
150
+
151
+ function createPromptCarver(base: string, carvedSpans: Span[]): PromptCarver {
152
+ return {
153
+ base,
154
+ toolsBlock: findBulletBlock(base, '\nAvailable tools:\n'),
155
+ guidelinesBlock: findBulletBlock(base, '\nGuidelines:\n'),
156
+ carvedSpans,
157
+ };
158
+ }
159
+
160
+ function findBulletBlock(text: string, header: string): Span | undefined {
161
+ const headerStart = text.indexOf(header);
162
+ if (headerStart === -1) return undefined;
163
+ const start = headerStart + header.length - 1;
164
+ const blank = text.indexOf('\n\n', start);
165
+ return { start, end: blank === -1 ? text.length : blank };
166
+ }
167
+
168
+ function carveBlockLine(carver: PromptCarver, block: Span | undefined, line: string): string | undefined {
169
+ if (block === undefined) return undefined;
170
+ const start = carver.base.indexOf(line, block.start);
171
+ if (start === -1 || start + line.length > block.end) return undefined;
172
+ const span = { start, end: start + line.length };
173
+ carver.carvedSpans.push(span);
174
+ return carver.base.slice(span.start, span.end);
175
+ }
176
+
177
+ function piOwnedGuidelines(tools: ToolSlice[]): string[] {
178
+ const names = new Set(tools.map(tool => tool.name));
179
+ const shellOnly = (names.has('bash') || names.has('powershell')) && !names.has('grep') && !names.has('find') && !names.has('ls');
180
+ if (!shellOnly) return [];
181
+ if (names.has('bash') && names.has('powershell')) return ['Use bash or PowerShell for file operations like listing, searching, and finding files'];
182
+ if (names.has('powershell')) return ['Use PowerShell for file operations like listing, searching, and finding files'];
183
+ return ['Use bash for file operations like ls, rg, find'];
184
+ }
185
+
186
+ function claimGuidelines(tool: ToolSlice, claimed: Set<string>): string[] {
187
+ const owned: string[] = [];
188
+ for (const guideline of tool.guidelines) {
189
+ const text = guideline.trim();
190
+ if (text.length === 0 || claimed.has(text)) continue;
191
+ claimed.add(text);
192
+ owned.push(text);
193
+ }
194
+ return owned;
195
+ }
196
+
137
197
  /** Measure context-file contents without counting pi's XML transport scaffolding. */
138
198
  function measureContextFiles(base: string, options: PromptOptionsSlice, items: InjectionItem[], carvedSpans: Span[]): void {
139
199
  const sectionSpan = findContextSectionSpan(base);
@@ -187,6 +247,25 @@ function createItem(id: string, kind: InjectionKind, source: InjectionSource, la
187
247
  };
188
248
  }
189
249
 
250
+ /** Build a tool item whose text is exactly the concatenation of its sections. */
251
+ function createToolItem(id: string, source: InjectionSource, label: string, sections: SectionDraft[]): InjectionItem {
252
+ const text = sections.map(section => section.text).join('');
253
+ return { ...createItem(id, 'tool', source, label, text), sections: allocateSectionTokens(sections) };
254
+ }
255
+
256
+ /** Allocate cumulative token deltas so rounded sections reconcile exactly. */
257
+ function allocateSectionTokens(sections: SectionDraft[]): InjectionSection[] {
258
+ let chars = 0;
259
+ let allocated = 0;
260
+ return sections.map(section => {
261
+ chars += section.text.length;
262
+ const cumulative = charTokens(chars);
263
+ const tokens = cumulative - allocated;
264
+ allocated = cumulative;
265
+ return { ...section, tokens };
266
+ });
267
+ }
268
+
190
269
  /** Build an aggregate whose totals exactly reconcile with its child items. */
191
270
  function createAggregateItem(id: string, kind: InjectionKind, source: InjectionSource, label: string, children: InjectionItem[]): InjectionItem {
192
271
  return {
@@ -253,12 +332,6 @@ function findBasePromptFooter(systemPrompt: string, cwd: string): Span | undefin
253
332
  return undefined;
254
333
  }
255
334
 
256
- /** Span of the first exact occurrence of needle, or undefined. */
257
- function findExactSpan(haystack: string, needle: string): Span | undefined {
258
- const start = haystack.indexOf(needle);
259
- return start === -1 ? undefined : { start, end: start + needle.length };
260
- }
261
-
262
335
  /** Span of pi's complete project-context transport section. */
263
336
  function findContextSectionSpan(systemPrompt: string): Span | undefined {
264
337
  return findDelimitedSpan(systemPrompt, '<project_context>', '</project_context>');
@@ -27,6 +27,14 @@ export interface InjectionSource {
27
27
  readonly native: boolean;
28
28
  }
29
29
 
30
+ /** One labeled part of an item's raw text, used only to shape its preview. */
31
+ export interface InjectionSection {
32
+ readonly label: string;
33
+ readonly text: string;
34
+ /** Share of the parent estimate; sections sum exactly to the item total. */
35
+ readonly tokens: number;
36
+ }
37
+
30
38
  /** One measured context injection. */
31
39
  export interface InjectionItem {
32
40
  /** Stable id, unique within a snapshot. */
@@ -41,6 +49,8 @@ export interface InjectionItem {
41
49
  readonly tokens: number;
42
50
  /** Raw injected text for preview. Process-local; never log or persist. */
43
51
  readonly text: string;
52
+ /** Labeled parts of `text`; never additional tokens. */
53
+ readonly sections?: readonly InjectionSection[];
44
54
  /** True when a message exists only in the transformed provider context, not the session branch. */
45
55
  readonly contextOnly?: boolean;
46
56
  /** Constituent sub-items (e.g. individual built-in tools or skills), largest first. */
@@ -99,6 +109,8 @@ export interface UsagePreviewEntry {
99
109
  readonly invisibleReasoning?: InvisibleReasoningEstimate;
100
110
  /** Raw content for preview. Process-local; never log or persist. */
101
111
  readonly text: string;
112
+ /** Labeled parts carried from a measured snapshot item. */
113
+ readonly sections?: readonly InjectionSection[];
102
114
  }
103
115
 
104
116
  /** Pi-reported usage; tokens/percent are omitted when unknown (e.g. right after compaction). */
@@ -168,6 +180,7 @@ function copyItem(item: InjectionItem): InjectionItem {
168
180
  return {
169
181
  ...item,
170
182
  source: { ...item.source },
183
+ sections: item.sections?.map(section => ({ ...section })),
171
184
  children: item.children?.map(child => copyItem(child)),
172
185
  };
173
186
  }
@@ -23,6 +23,7 @@ import {
23
23
  } from '../../../libs/modal';
24
24
  import type { InitialSnapshot, InjectionItem } from '../model';
25
25
  import { buildInjectionRows, collectItemsById, type InjectionRow, normalizeInlineText, normalizePreviewText } from './injections-model';
26
+ import { previewBodyLines } from './section-preview';
26
27
 
27
28
  const LIST_DESCRIPTION = 'Injections into the model context for the first turn, with token estimates.';
28
29
  const CURSOR_COLUMN_WIDTH = 2;
@@ -146,19 +147,18 @@ export class InjectionsView implements ModalTab {
146
147
  if (this.previewItem === item && this.previewLines !== undefined && this.previewWrapWidth === wrapWidth) {
147
148
  return this.previewLines;
148
149
  }
149
- const text = normalizePreviewText(item.text);
150
- const lines: string[] = [];
151
- for (const paragraph of text.split('\n')) {
152
- const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
153
- if (wrapped.length === 0) {
154
- lines.push('');
155
- continue;
150
+ const wrapText = (text: string): string[] => {
151
+ const lines: string[] = [];
152
+ for (const paragraph of normalizePreviewText(text).split('\n')) {
153
+ const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
154
+ if (wrapped.length === 0) lines.push('');
155
+ else for (const line of wrapped) lines.push(`${BODY_INDENT}${line}`);
156
156
  }
157
- for (const line of wrapped) lines.push(`${BODY_INDENT}${line}`);
158
- }
159
- this.previewLines = lines;
157
+ return lines;
158
+ };
159
+ this.previewLines = previewBodyLines(this.theme, item, wrapWidth, wrapText);
160
160
  this.previewWrapWidth = wrapWidth;
161
- return lines;
161
+ return this.previewLines;
162
162
  }
163
163
 
164
164
  // === List rendering ===
@@ -0,0 +1,29 @@
1
+ /** Shared rendering for preview content split into labeled measured sections. */
2
+ import type { Theme } from '@earendil-works/pi-coding-agent';
3
+ import { wrapTextWithAnsi } from '@earendil-works/pi-tui';
4
+ import { BODY_INDENT } from '../../../libs/modal';
5
+ import type { InjectionSection } from '../model';
6
+ import { normalizeInlineText } from './injections-model';
7
+
8
+ export interface SectionedContent {
9
+ readonly text: string;
10
+ readonly sections?: readonly InjectionSection[];
11
+ }
12
+
13
+ export function previewBodyLines(theme: Theme, content: SectionedContent, wrapWidth: number, wrapText: (text: string) => string[]): string[] {
14
+ const sections = content.sections ?? [];
15
+ if (sections.length === 0) return wrapText(content.text);
16
+ const lines: string[] = [];
17
+ for (const section of sections) {
18
+ if (lines.length > 0) lines.push('');
19
+ lines.push(...sectionHeaderLines(theme, section, wrapWidth));
20
+ lines.push(...wrapText(section.text.replace(/^\n+/, '')));
21
+ }
22
+ return lines;
23
+ }
24
+
25
+ function sectionHeaderLines(theme: Theme, section: InjectionSection, wrapWidth: number): string[] {
26
+ const label = theme.fg('syntaxFunction', theme.bold(normalizeInlineText(section.label)));
27
+ const tokens = theme.fg('muted', ` · ${section.tokens.toLocaleString('en-US')} tokens`);
28
+ return wrapTextWithAnsi(`${label}${tokens}`, wrapWidth).map(line => `${BODY_INDENT}${line}`);
29
+ }