@0xkahi/pi-qol 1.0.6 → 1.1.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.6",
3
+ "version": "1.1.1",
4
4
  "description": "quality of life pi extensions",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -45,10 +45,9 @@
45
45
  "devDependencies": {
46
46
  "@biomejs/biome": "^2.4.15",
47
47
  "@changesets/cli": "^2.31.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",
48
+ "@earendil-works/pi-ai": "^0.87.0",
49
+ "@earendil-works/pi-coding-agent": "^0.87.0",
50
+ "@earendil-works/pi-tui": "^0.87.0",
52
51
  "@types/bun": "latest",
53
52
  "@types/node": "^24.0.0",
54
53
  "bun-types": "latest",
@@ -1,24 +1,39 @@
1
- /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
1
  /**
3
2
  * Initial capture state and conversion from pi event data to the semantic
4
3
  * model. Event registration remains in index.ts; this module is independently
5
4
  * unit-testable.
6
5
  */
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';
6
+ import {
7
+ type BuildSystemPromptOptions,
8
+ type ContextEvent,
9
+ convertToLlm,
10
+ estimateTokens,
11
+ formatSize,
12
+ type InputSource,
13
+ type SlashCommandInfo,
14
+ type SourceInfo,
15
+ type ToolInfo,
16
+ } from '@earendil-works/pi-coding-agent';
17
+
18
+ import { analyzeSystemPrompt, type PromptOptionsSlice, type ToolSlice, textTokens } from './measure';
19
+ import {
20
+ AGGREGATE_SOURCE,
21
+ buildSnapshot,
22
+ type CaptureOrigin,
23
+ type InitialSnapshot,
24
+ type InjectionItem,
25
+ type InjectionSource,
26
+ type JsonSpan,
27
+ } from './model';
28
+ import { createProbeToken, type ProbeToken } from './probe-token';
29
+ import type { PromptSourceSlice } from './prompt-additions';
30
+ import { copySystemMessage, replaySystemMessages, systemMessageText } from './transcript';
11
31
 
12
32
  /** Session custom-entry type persisting probe message identities across extension runtimes. */
13
33
  export const PROBE_IDENTITIES_CUSTOM_TYPE = 'pi-context-view:probe-identities';
14
34
 
15
35
  const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
16
36
  const SETUP_ABORT_ERROR_MESSAGE = 'This operation was aborted';
17
- const AGGREGATE_SOURCE: InjectionSource = {
18
- id: AGGREGATE_SOURCE_ID,
19
- label: 'extensions (aggregate)',
20
- native: false,
21
- };
22
37
 
23
38
  /** Everything available when the first context event finalizes a snapshot. */
24
39
  export interface CaptureFinalization {
@@ -27,6 +42,8 @@ export interface CaptureFinalization {
27
42
  baselineMessages: ContextEvent['messages'];
28
43
  allTools: readonly ToolInfo[];
29
44
  activeToolNames: readonly string[];
45
+ /** Loaded extension provenance, used only to guess who appended prompt text. */
46
+ promptSources?: readonly PromptSourceSlice[];
30
47
  origin: CaptureOrigin;
31
48
  capturedAt?: Date;
32
49
  }
@@ -37,15 +54,19 @@ export interface NativeSnapshotInput {
37
54
  options: BuildSystemPromptOptions;
38
55
  allTools: readonly ToolInfo[];
39
56
  activeToolNames: readonly string[];
57
+ /** Loaded extension provenance, used only to guess who appended prompt text. */
58
+ promptSources?: readonly PromptSourceSlice[];
40
59
  capturedAt?: Date;
41
60
  }
42
61
 
43
62
  /** Result of the one allowed silent-probe attempt. */
44
63
  export type ProbeOutcome = { readonly status: 'captured' } | { readonly status: 'failed'; readonly reason: string };
45
64
 
46
- /** A probe start request; concurrent callers share `completion`. */
65
+ /** A probe start request; concurrent callers share `token` and `completion`. */
47
66
  export interface ProbeAttempt {
48
67
  readonly started: boolean;
68
+ /** Correlation token to send the synthetic prompt under. */
69
+ readonly token: ProbeToken;
49
70
  readonly completion: Promise<ProbeOutcome>;
50
71
  }
51
72
 
@@ -59,10 +80,16 @@ export interface SyntheticMessageIdentity {
59
80
  interface CapturePreparation {
60
81
  readonly promptOptions: PromptOptionsSlice;
61
82
  readonly toolSnippets?: Readonly<Record<string, string>>;
83
+ /** Prompt as of this extension's own handler, bounding later extensions' additions. */
84
+ readonly promptAtHandler?: string;
62
85
  }
63
86
 
64
- /** Lifecycle of the single probe attempt, including ownership retained after its completion times out. */
65
- type ProbePhase = 'idle' | 'waiting' | 'waiting-after-timeout' | 'running' | 'running-after-timeout' | 'failed' | 'settled';
87
+ /**
88
+ * Lifecycle of the single probe attempt. Ownership outlives the attempt's own
89
+ * completion, so a probe run arriving after a timeout or after an unattributed
90
+ * run is still claimed, aborted, and sanitized.
91
+ */
92
+ type ProbePhase = 'idle' | 'waiting' | 'running' | 'settled';
66
93
 
67
94
  /**
68
95
  * Capture-once state machine. `prepare()` refreshes the structured options on
@@ -84,31 +111,42 @@ export class InitialCaptureState {
84
111
  return this.latestOptions;
85
112
  }
86
113
 
87
- /** Own structured prompt inputs from every `before_agent_start`; freeze only the Initial preparation. */
88
- public prepare(options: BuildSystemPromptOptions): void {
114
+ /**
115
+ * Own the structured prompt inputs from `before_agent_start`; no-op once
116
+ * frozen. `promptAtHandler` is the chained prompt as this extension observed
117
+ * it, which separates additions made before this extension loaded from those
118
+ * made after it.
119
+ */
120
+ public prepare(options: BuildSystemPromptOptions, promptAtHandler?: string): void {
89
121
  this.latestOptions = structuredClone(options);
90
122
  if (this.initialSnapshot !== undefined) return;
91
123
  this.pendingPreparation = {
92
124
  promptOptions: copyPromptOptions(options),
93
125
  toolSnippets: options.toolSnippets === undefined ? undefined : { ...options.toolSnippets },
126
+ promptAtHandler,
94
127
  };
95
128
  }
96
129
 
97
130
  /**
98
131
  * Freeze the Initial snapshot from the first context event. Returns the
99
132
  * existing snapshot on repeat calls, or undefined when `prepare()` never ran.
133
+ * `buildInput` runs only on the call that freezes, so callers may collect
134
+ * expensive inputs there without paying for them once per later event.
100
135
  */
101
- public finalize(buildInput: CaptureFinalization | (() => CaptureFinalization)): InitialSnapshot | undefined {
136
+ public finalize(buildInput: () => CaptureFinalization): InitialSnapshot | undefined {
102
137
  if (this.initialSnapshot !== undefined) return this.initialSnapshot;
103
138
  if (this.pendingPreparation === undefined) return undefined;
104
139
 
105
- const input = typeof buildInput === 'function' ? buildInput() : buildInput;
140
+ const input = buildInput();
106
141
  const preparation = this.pendingPreparation;
107
142
  const tools = captureActiveTools(input.allTools, input.activeToolNames, {
108
143
  toolSnippets: preparation.toolSnippets,
109
144
  });
110
145
  const items = [
111
- ...analyzeSystemPrompt(input.systemPrompt, preparation.promptOptions, tools),
146
+ ...analyzeSystemPrompt(input.systemPrompt, preparation.promptOptions, tools, {
147
+ sources: input.promptSources,
148
+ promptAtHandler: preparation.promptAtHandler,
149
+ }),
112
150
  ...measureInjectedMessages(input.messages, input.baselineMessages),
113
151
  ];
114
152
  this.initialSnapshot = buildSnapshot(items, input.origin, input.capturedAt ?? new Date());
@@ -117,17 +155,21 @@ export class InitialCaptureState {
117
155
  }
118
156
  }
119
157
 
120
- /** Track the currently active session compaction without retaining stale signals. */
158
+ /** Tracks the observable compaction lifecycle that makes a silent probe unsafe. */
121
159
  export class CompactionState {
122
160
  private currentSignal: AbortSignal | undefined;
123
161
 
162
+ /** Whether a compaction observed through `session_before_compact` is still active. */
124
163
  public get isActive(): boolean {
125
164
  return this.currentSignal !== undefined && !this.currentSignal.aborted;
126
165
  }
127
166
 
128
- /** Begin tracking a live compaction signal; already-aborted signals are ignored. */
167
+ /** Track the current compaction until success, abort, or agent settlement. */
129
168
  public begin(signal: AbortSignal): void {
130
- if (signal.aborted) return;
169
+ if (signal.aborted) {
170
+ this.currentSignal = undefined;
171
+ return;
172
+ }
131
173
  this.currentSignal = signal;
132
174
  signal.addEventListener(
133
175
  'abort',
@@ -138,28 +180,28 @@ export class CompactionState {
138
180
  );
139
181
  }
140
182
 
141
- /** Finish either a successful or failed compaction lifecycle. */
183
+ /** Clear the current lifecycle after compaction can no longer reject prompts. */
142
184
  public finish(): void {
143
185
  this.currentSignal = undefined;
144
186
  }
145
187
  }
146
188
 
147
189
  /**
148
- * State for one on-demand silent probe. It owns the timeout and exact synthetic
149
- * message identities, but leaves pi API calls and UI restoration to index.ts.
190
+ * State for one on-demand silent probe. It owns the correlation token, the
191
+ * timeout, and the exact synthetic message identities, but leaves pi API calls
192
+ * and UI restoration to index.ts.
150
193
  */
151
194
  export class SilentProbeState {
152
195
  private phase: ProbePhase = 'idle';
153
- private inputObserved = false;
154
196
  private readonly identities = new Map<string, SyntheticMessageIdentity>();
155
- private completion: Promise<ProbeOutcome> | undefined;
197
+ private attempt: ProbeAttempt | undefined;
156
198
  private resolveCompletion: ((outcome: ProbeOutcome) => void) | undefined;
157
199
  private outcome: ProbeOutcome | undefined;
158
200
  private timeout: NodeJS.Timeout | undefined;
159
201
 
160
202
  /** True while the probe owns the in-flight agent run (including after a timeout). */
161
203
  public get isCurrentRun(): boolean {
162
- return this.phase === 'running' || this.phase === 'running-after-timeout';
204
+ return this.phase === 'running';
163
205
  }
164
206
 
165
207
  /** Defensive copies of the recorded probe message identities. */
@@ -184,36 +226,44 @@ export class SilentProbeState {
184
226
  * return the original attempt's completion with `started: false`.
185
227
  */
186
228
  public start(timeoutMs = DEFAULT_PROBE_TIMEOUT_MS): ProbeAttempt {
187
- if (this.completion !== undefined) {
188
- return { started: false, completion: this.completion };
229
+ if (this.attempt !== undefined) {
230
+ return { ...this.attempt, started: false };
189
231
  }
190
232
 
191
233
  this.phase = 'waiting';
192
- this.completion = new Promise<ProbeOutcome>(resolve => {
234
+ const completion = new Promise<ProbeOutcome>(resolve => {
193
235
  this.resolveCompletion = resolve;
194
236
  });
195
237
  this.timeout = setTimeout(() => {
196
- if (this.phase === 'waiting') {
197
- this.phase = 'waiting-after-timeout';
198
- } else if (this.phase === 'running') {
199
- this.phase = 'running-after-timeout';
200
- }
201
238
  this.resolve({ status: 'failed', reason: 'Silent probe timed out.' });
202
239
  }, timeoutMs);
203
- return { started: true, completion: this.completion };
240
+ this.attempt = { started: true, token: createProbeToken(), completion };
241
+ return this.attempt;
204
242
  }
205
243
 
206
- /** Mark the exact extension-originated empty input that starts the probe. */
207
- public observeInput(source: InputSource, text: string): void {
208
- const awaitingInput = this.phase === 'waiting' || this.phase === 'waiting-after-timeout';
209
- if (awaitingInput && source === 'extension' && text === '') this.inputObserved = true;
244
+ /**
245
+ * Whether this input event is the probe's own synthetic prompt. Recognition
246
+ * is causal rather than textual: the token is visible only inside the async
247
+ * context of this extension's own `sendUserMessage()` call.
248
+ */
249
+ public isProbeInput(source: InputSource, token: ProbeToken | undefined): boolean {
250
+ return this.phase === 'waiting' && source === 'extension' && this.ownsToken(token);
210
251
  }
211
252
 
212
- /** Associate the next matching lifecycle with the probe, not a real turn. */
213
- public beginRun(prompt: string): boolean {
214
- const ownsPendingInput = this.phase === 'waiting' || this.phase === 'waiting-after-timeout';
215
- if (!ownsPendingInput || !this.inputObserved || prompt !== '') return false;
216
- this.phase = this.phase === 'waiting-after-timeout' ? 'running-after-timeout' : 'running';
253
+ /**
254
+ * Claim the run this probe started, identified by the token it carries. A run
255
+ * without the token is not provably ours, so it fails the attempt instead of
256
+ * activating the abort guard: it may belong to the user or to another
257
+ * extension and must run untouched. Ownership stays open afterwards so a
258
+ * delayed probe run is still claimed.
259
+ */
260
+ public beginRun(token: ProbeToken | undefined): boolean {
261
+ if (this.phase !== 'waiting') return false;
262
+ if (!this.ownsToken(token)) {
263
+ this.fail('Another agent run started before the silent probe was recognized.');
264
+ return false;
265
+ }
266
+ this.phase = 'running';
217
267
  return true;
218
268
  }
219
269
 
@@ -225,17 +275,15 @@ export class SilentProbeState {
225
275
  }
226
276
 
227
277
  /**
228
- * Replace only the probe's aborted assistant with an empty successful message
229
- * so pi does not render an "Operation aborted" transcript row.
278
+ * Replace a recorded probe message with an artifact-free version, or return
279
+ * undefined to keep pi's own. Filtering keeps probe messages out of later
280
+ * model contexts; blanking keeps them out of the transcript.
230
281
  */
231
- public sanitizeAssistant(message: ContextEvent['messages'][number]): ContextEvent['messages'][number] | undefined {
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;
236
- const identity = { role: 'assistant', timestamp: message.timestamp } satisfies SyntheticMessageIdentity;
237
- if (!this.identities.has(identityKey(identity))) return undefined;
238
- return { ...message, content: [], stopReason: 'stop', errorMessage: undefined };
282
+ public sanitizeMessage(message: ContextEvent['messages'][number]): ContextEvent['messages'][number] | undefined {
283
+ if (!this.isCurrentRun) return undefined;
284
+ if (message.role === 'user') return this.blankProbePrompt(message);
285
+ if (message.role === 'assistant') return this.blankProbeAbort(message);
286
+ return undefined;
239
287
  }
240
288
 
241
289
  /** Remove only messages whose exact role+timestamp identity belongs to the probe. */
@@ -251,17 +299,47 @@ export class SilentProbeState {
251
299
  public settle(captured: boolean): boolean {
252
300
  if (!this.isCurrentRun) return false;
253
301
  this.phase = 'settled';
254
- if (this.outcome === undefined) {
255
- this.resolve(captured ? { status: 'captured' } : { status: 'failed', reason: 'Silent probe settled without a context snapshot.' });
256
- }
302
+ this.resolve(captured ? { status: 'captured' } : { status: 'failed', reason: 'Silent probe settled without a context snapshot.' });
257
303
  return true;
258
304
  }
259
305
 
260
- /** End a pending attempt during shutdown or a synchronous startup failure. */
306
+ /**
307
+ * End a pending attempt during shutdown or a synchronous startup failure.
308
+ * Ownership is untouched: only the attempt's own completion is resolved.
309
+ */
261
310
  public fail(reason: string): void {
262
- if (this.completion === undefined || this.phase === 'failed' || this.phase === 'settled') return;
263
- this.phase = 'failed';
264
- if (this.outcome === undefined) this.resolve({ status: 'failed', reason });
311
+ if (this.attempt === undefined) return;
312
+ this.resolve({ status: 'failed', reason });
313
+ }
314
+
315
+ /**
316
+ * Empty the synthetic prompt so no stored message keeps text another
317
+ * extension's input transform added to it.
318
+ */
319
+ private blankProbePrompt(message: Extract<ContextEvent['messages'][number], { role: 'user' }>): ContextEvent['messages'][number] | undefined {
320
+ if (message.content.length === 0 || !this.ownsMessage(message)) return undefined;
321
+ return { ...message, content: [] };
322
+ }
323
+
324
+ /**
325
+ * Replace a recorded probe abort with an empty successful message so pi does
326
+ * not render an abort transcript row. Pi 0.84 reports an abort during stream
327
+ * setup as an error instead of the legacy aborted stop reason.
328
+ */
329
+ private blankProbeAbort(message: Extract<ContextEvent['messages'][number], { role: 'assistant' }>): ContextEvent['messages'][number] | undefined {
330
+ const isProbeAbort = message.stopReason === 'aborted' || (message.stopReason === 'error' && message.errorMessage === SETUP_ABORT_ERROR_MESSAGE);
331
+ if (!isProbeAbort || !this.ownsMessage(message)) return undefined;
332
+ return { ...message, content: [], stopReason: 'stop', errorMessage: undefined };
333
+ }
334
+
335
+ /** Whether this exact role and timestamp was recorded for the probe. */
336
+ private ownsMessage(message: { role: 'user' | 'assistant'; timestamp: number }): boolean {
337
+ return this.identities.has(identityKey({ role: message.role, timestamp: message.timestamp }));
338
+ }
339
+
340
+ /** Whether `token` identifies the current attempt. */
341
+ private ownsToken(token: ProbeToken | undefined): boolean {
342
+ return token !== undefined && token === this.attempt?.token;
265
343
  }
266
344
 
267
345
  /** Settle the completion promise exactly once and clear the timeout. */
@@ -299,15 +377,67 @@ export function parsePersistedIdentities(data: unknown): SyntheticMessageIdentit
299
377
  export function buildNativeSnapshot(input: NativeSnapshotInput): InitialSnapshot {
300
378
  const options = copyPromptOptions(input.options);
301
379
  const tools = captureActiveTools(input.allTools, input.activeToolNames, input.options);
302
- const items = analyzeSystemPrompt(input.systemPrompt, options, tools);
380
+ const items = analyzeSystemPrompt(input.systemPrompt, options, tools, { sources: input.promptSources });
303
381
  return buildSnapshot(items, 'synthetic-probe', input.capturedAt ?? new Date());
304
382
  }
305
383
 
306
- /** Add frozen context-only messages to a current prompt/tool snapshot for Usage. */
307
- export function mergeContextOnlyMessages(snapshot: InitialSnapshot, initial: InitialSnapshot): InitialSnapshot {
308
- const contextOnly = initial.groups.flatMap(group => group.items.filter(item => item.kind === 'message' && item.contextOnly === true));
309
- if (contextOnly.length === 0) return snapshot;
310
- const items = [...snapshot.groups.flatMap(group => group.items), ...contextOnly];
384
+ /** Inputs for Usage's branch-local prompt/tool estimate and frozen request-only patches. */
385
+ export interface UsageSnapshotInput extends NativeSnapshotInput {
386
+ messages: ContextEvent['messages'];
387
+ initial: InitialSnapshot;
388
+ }
389
+
390
+ /**
391
+ * Use replayed transcript state instead of today's loader prompt/tools when available.
392
+ * Request-only system patches remain frozen like other Initial injections; they are
393
+ * applied once here and never counted again as ordinary messages.
394
+ */
395
+ export function buildUsageSnapshot(input: UsageSnapshotInput): InitialSnapshot {
396
+ const patches = input.initial.groups
397
+ .flatMap(group => group.items)
398
+ .filter(item => item.requestOnly === true && item.systemMessage !== undefined)
399
+ .flatMap(item => (item.systemMessage === undefined ? [] : [item.systemMessage]))
400
+ .sort((a, b) => a.index - b.index)
401
+ .map(entry => entry.message);
402
+ const state = replaySystemMessages([...input.messages, ...patches]);
403
+ if (state === undefined) return mergeRequestOnlyMessages(buildNativeSnapshot(input), input.initial);
404
+ const registered = new Map(input.allTools.map(tool => [tool.name, tool]));
405
+ const tools: ToolSlice[] = state.tools.map(tool => {
406
+ const metadata = registered.get(tool.name);
407
+ const snippetLine = state.sections.tools?.split('\n').find(line => line.startsWith(`- ${tool.name}: `));
408
+ return {
409
+ name: tool.name,
410
+ description: tool.description,
411
+ parametersJson: JSON.stringify(tool.parameters),
412
+ snippet: snippetLine?.slice(`- ${tool.name}: `.length),
413
+ guidelines: normalizeGuidelines(metadata?.promptGuidelines),
414
+ source: metadata?.sourceInfo.source ?? 'unattributed',
415
+ };
416
+ });
417
+ const options = copyPromptOptions(input.options);
418
+ const items = analyzeSystemPrompt(
419
+ systemMessageText(state),
420
+ {
421
+ ...options,
422
+ // Current loader overrides are not evidence of what this branch recorded.
423
+ customPrompt: undefined,
424
+ appendSystemPrompt: undefined,
425
+ sections: undefined,
426
+ },
427
+ tools,
428
+ { sources: input.promptSources },
429
+ );
430
+ const snapshot = buildSnapshot(items, 'synthetic-probe', input.capturedAt ?? new Date());
431
+ return mergeRequestOnlyMessages(snapshot, input.initial);
432
+ }
433
+
434
+ /** Add frozen non-system request-only messages to a current prompt/tool snapshot for Usage. */
435
+ export function mergeRequestOnlyMessages(snapshot: InitialSnapshot, initial: InitialSnapshot): InitialSnapshot {
436
+ const requestOnly = initial.groups.flatMap(group =>
437
+ group.items.filter(item => item.kind === 'message' && item.requestOnly === true && item.systemMessage === undefined),
438
+ );
439
+ if (requestOnly.length === 0) return snapshot;
440
+ const items = [...snapshot.groups.flatMap(group => group.items), ...requestOnly];
311
441
  return buildSnapshot(items, snapshot.origin, snapshot.capturedAt);
312
442
  }
313
443
 
@@ -318,6 +448,7 @@ export function copyPromptOptions(options: BuildSystemPromptOptions): PromptOpti
318
448
  homeDir: process.env.HOME,
319
449
  customPrompt: options.customPrompt,
320
450
  appendSystemPrompt: options.appendSystemPrompt,
451
+ sections: options.sections === undefined ? undefined : { ...options.sections },
321
452
  contextFilePaths: options.contextFiles?.map(file => file.path),
322
453
  skills: options.skills
323
454
  ?.filter(skill => !skill.disableModelInvocation)
@@ -329,15 +460,59 @@ export function copyPromptOptions(options: BuildSystemPromptOptions): PromptOpti
329
460
  };
330
461
  }
331
462
 
332
- /** Snapshot the final active tool set with provenance and payload definitions. */
463
+ /**
464
+ * Collect the provenance of every loaded extension that registered a tool or a
465
+ * command, together with the names it registered. It is the only extension
466
+ * roster pi exposes, and it feeds attribution guesses alone: extensions
467
+ * registering neither are invisible here.
468
+ */
469
+ export function collectPromptSources(allTools: readonly ToolInfo[], commands: readonly SlashCommandInfo[]): PromptSourceSlice[] {
470
+ const sources = new Map<string, CollectedPromptSource>();
471
+ for (const tool of allTools) addPromptSource(sources, tool.sourceInfo, tool.name);
472
+ // Prompt text refers to a command the way a user types it, so keep its slash.
473
+ for (const command of commands) {
474
+ addPromptSource(sources, command.sourceInfo, command.name.startsWith('/') ? command.name : `/${command.name}`);
475
+ }
476
+ return [...sources.values()];
477
+ }
478
+
479
+ /** Slice under construction: its names arrive one tool or command at a time. */
480
+ interface CollectedPromptSource extends Omit<PromptSourceSlice, 'names'> {
481
+ readonly names: string[];
482
+ }
483
+
484
+ /** Record one registered name under its extension's provenance, skipping pi's own sources. */
485
+ function addPromptSource(sources: Map<string, CollectedPromptSource>, sourceInfo: SourceInfo, name: string): void {
486
+ if (sourceInfo.source === 'builtin' || sourceInfo.source === 'sdk') return;
487
+ const key = `${sourceInfo.source}\n${sourceInfo.path}`;
488
+ let collected = sources.get(key);
489
+ if (collected === undefined) {
490
+ collected = {
491
+ source: sourceInfo.source,
492
+ path: sourceInfo.path,
493
+ // A top-level extension's baseDir is a shared directory, not its own root.
494
+ baseDir: sourceInfo.origin === 'package' ? sourceInfo.baseDir : undefined,
495
+ names: [],
496
+ };
497
+ sources.set(key, collected);
498
+ }
499
+ if (!collected.names.includes(name)) collected.names.push(name);
500
+ }
501
+
502
+ /**
503
+ * Snapshot the final active tool set with provenance and payload definitions.
504
+ * Keep pi's active-tool order: it decides which tool owns a guideline bullet
505
+ * that several tools declare.
506
+ */
333
507
  export function captureActiveTools(
334
508
  allTools: readonly ToolInfo[],
335
509
  activeToolNames: readonly string[],
336
510
  options: { readonly toolSnippets?: Readonly<Record<string, string>> },
337
511
  ): ToolSlice[] {
338
- const active = new Set(activeToolNames);
339
- return allTools
340
- .filter(tool => active.has(tool.name))
512
+ const byName = new Map(allTools.map(tool => [tool.name, tool]));
513
+ return [...new Set(activeToolNames)]
514
+ .map(name => byName.get(name))
515
+ .filter(tool => tool !== undefined)
341
516
  .map(tool => ({
342
517
  name: tool.name,
343
518
  description: tool.description,
@@ -357,14 +532,14 @@ export function measureInjectedMessages(messages: ContextEvent['messages'], base
357
532
  const baseline = messageSignatureCounts(baselineMessages);
358
533
  const occurrences = new Map<string, number>();
359
534
  const items: InjectionItem[] = [];
360
- for (const message of messages) {
361
- const contextOnly = !consumeMessageSignature(baseline, message);
362
- if (message.role !== 'custom' && !contextOnly) continue;
535
+ for (const [index, message] of messages.entries()) {
536
+ const requestOnly = !consumeMessageSignature(baseline, message);
537
+ if (message.role !== 'custom' && !requestOnly) continue;
363
538
 
364
539
  const identity = message.role === 'custom' ? message.customType : message.role;
365
540
  const occurrence = occurrences.get(identity) ?? 0;
366
541
  occurrences.set(identity, occurrence + 1);
367
- const text = messageText(message);
542
+ const { text, jsonSpan } = messagePreview(message);
368
543
  items.push({
369
544
  id: message.role === 'custom' ? `message:${message.customType}:${occurrence}` : `message:context:${message.role}:${occurrence}`,
370
545
  phase: 'initial',
@@ -372,9 +547,11 @@ export function measureInjectedMessages(messages: ContextEvent['messages'], base
372
547
  source: message.role === 'custom' ? messageSource(message.customType) : AGGREGATE_SOURCE,
373
548
  label: message.role === 'custom' ? 'message' : `${message.role} message`,
374
549
  chars: text.length,
375
- tokens: estimateTokens(message),
550
+ tokens: message.role === 'system' ? textTokens(systemMessageText(message)) : estimateTokens(message),
376
551
  text,
377
- contextOnly: contextOnly || undefined,
552
+ jsonSpan,
553
+ requestOnly: requestOnly || undefined,
554
+ systemMessage: message.role === 'system' ? { message: copySystemMessage(message), index } : undefined,
378
555
  });
379
556
  }
380
557
  return items;
@@ -390,7 +567,7 @@ function messageSignatureCounts(messages: ContextEvent['messages']): Map<string,
390
567
  return counts;
391
568
  }
392
569
 
393
- /** Consume one matching baseline occurrence, returning false for a context-only message. */
570
+ /** Consume one matching baseline occurrence, returning false for a request-only message. */
394
571
  function consumeMessageSignature(counts: Map<string, number>, message: ContextEvent['messages'][number]): boolean {
395
572
  const signature = JSON.stringify(message);
396
573
  const count = counts.get(signature) ?? 0;
@@ -400,10 +577,61 @@ function consumeMessageSignature(counts: Map<string, number>, message: ContextEv
400
577
  return true;
401
578
  }
402
579
 
403
- /** Extract provider-bound message content for raw preview. */
404
- function messageText(message: ContextEvent['messages'][number]): string {
405
- if (!('content' in message)) return JSON.stringify(message);
406
- return typeof message.content === 'string' ? message.content : JSON.stringify(message.content);
580
+ /** Provider-bound message content for raw preview, with any serialization marked as JSON. */
581
+ interface MessagePreview {
582
+ readonly text: string;
583
+ readonly jsonSpan?: JsonSpan;
584
+ }
585
+
586
+ /** Extract content-only previews without raw image payloads or opaque assistant signatures. */
587
+ function messagePreview(message: ContextEvent['messages'][number]): MessagePreview {
588
+ if (message.role === 'system') return { text: systemMessageText(message) };
589
+ if (message.role === 'branchSummary' || message.role === 'compactionSummary') {
590
+ return { text: message.summary };
591
+ }
592
+ if (message.role === 'bashExecution') {
593
+ const content = convertToLlm([message])[0]?.content ?? '';
594
+ return {
595
+ text: typeof content === 'string' ? content : content.flatMap(block => (block.type === 'text' ? [block.text] : [])).join('\n'),
596
+ };
597
+ }
598
+ if (typeof message.content === 'string') return { text: message.content };
599
+ if (message.role === 'assistant') {
600
+ const content = message.content.map(block => {
601
+ if (block.type === 'text') {
602
+ const { textSignature, ...preview } = block;
603
+ return preview;
604
+ }
605
+ if (block.type === 'thinking') {
606
+ const { thinkingSignature, ...preview } = block;
607
+ return preview;
608
+ }
609
+ if (block.type === 'toolCall') {
610
+ const { thoughtSignature, ...preview } = block;
611
+ return preview;
612
+ }
613
+ return block;
614
+ });
615
+ return serializedPreview(JSON.stringify(content));
616
+ }
617
+ return serializedPreview(JSON.stringify(message.content.map(imagePreviewBlock)));
618
+ }
619
+
620
+ /**
621
+ * Replace a captured image payload with the size it occupied, so a preview
622
+ * reports what the message carried without retaining or rendering its bytes.
623
+ * Sizes measure the base64 text as captured, not the decoded image.
624
+ */
625
+ function imagePreviewBlock<Block extends { readonly type: string }>(block: Block): Block {
626
+ if (block.type !== 'image') return block;
627
+ const data = (block as { readonly data?: unknown }).data;
628
+ if (typeof data !== 'string') return block;
629
+ return { ...block, data: `<${formatSize(data.length)} omitted>` };
630
+ }
631
+
632
+ /** Preview whose whole text is one serialized JSON document. */
633
+ function serializedPreview(text: string): MessagePreview {
634
+ return { text, jsonSpan: { start: 0, end: text.length } };
407
635
  }
408
636
 
409
637
  /** Map key uniquely identifying one probe message by role and timestamp. */