@0xkahi/pi-qol 1.0.5 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +35 -5
  2. package/assets/config.schema.json +18 -3
  3. package/package.json +5 -5
  4. package/src/constants.ts +1 -0
  5. package/src/extensions/context-view/capture.ts +311 -83
  6. package/src/extensions/context-view/codemap.md +111 -48
  7. package/src/extensions/context-view/context-view-controller.ts +65 -27
  8. package/src/extensions/context-view/index.ts +22 -6
  9. package/src/extensions/context-view/measure.ts +713 -78
  10. package/src/extensions/context-view/model.ts +132 -14
  11. package/src/extensions/context-view/probe-token.ts +28 -0
  12. package/src/extensions/context-view/prompt-additions.ts +174 -0
  13. package/src/extensions/context-view/prompt-blocks.ts +204 -0
  14. package/src/extensions/context-view/settings.ts +43 -0
  15. package/src/extensions/context-view/text.ts +48 -0
  16. package/src/extensions/context-view/transcript.ts +62 -0
  17. package/src/extensions/context-view/ui/codemap.md +28 -13
  18. package/src/extensions/context-view/ui/context-view-dialog.ts +6 -1
  19. package/src/extensions/context-view/ui/injections-model.ts +13 -28
  20. package/src/extensions/context-view/ui/injections-view.ts +82 -21
  21. package/src/extensions/context-view/ui/json-preview.ts +41 -0
  22. package/src/extensions/context-view/ui/markers.ts +96 -0
  23. package/src/extensions/context-view/ui/section-preview.ts +188 -10
  24. package/src/extensions/context-view/ui/usage-block-layer.ts +9 -4
  25. package/src/extensions/context-view/ui/usage-view.ts +70 -17
  26. package/src/extensions/context-view/ui/wheel-preview-layer.ts +104 -0
  27. package/src/extensions/context-view/ui/wheel.ts +66 -0
  28. package/src/extensions/context-view/usage.ts +64 -26
  29. package/src/extensions/custom-footer/agent-display-state.ts +60 -0
  30. package/src/extensions/custom-footer/footer-component.ts +22 -0
  31. package/src/extensions/custom-footer/index.ts +17 -1
  32. package/src/extensions/custom-footer/types.ts +3 -1
  33. package/src/schemas/custom-footer-config.schema.ts +11 -0
@@ -5,9 +5,38 @@
5
5
  * never parse labels to recover source, kind, or parent/child relationships.
6
6
  */
7
7
 
8
+ import type { SystemMessage } from './transcript';
9
+
8
10
  export const PI_SOURCE_ID = 'pi';
9
11
  export const AGGREGATE_SOURCE_ID = 'aggregate:extensions';
10
12
 
13
+ /** Everything pi itself assembles: its prompt, context files, skills, and built-in tools. */
14
+ export const PI_SOURCE: InjectionSource = { id: PI_SOURCE_ID, label: 'pi', native: true };
15
+
16
+ /** Contributions no available signal attributes to one extension. */
17
+ export const AGGREGATE_SOURCE: InjectionSource = {
18
+ id: AGGREGATE_SOURCE_ID,
19
+ label: 'unattributed',
20
+ native: false,
21
+ };
22
+
23
+ /** Injection source for one non-builtin provenance string, e.g. `npm:pi-web-providers`. */
24
+ export function extensionSource(source: string): InjectionSource {
25
+ return { id: `tool-source:${source}`, label: source, native: false };
26
+ }
27
+
28
+ /** Shared name of pi's own prompt; Usage and Injections must present it identically. */
29
+ export const SYSTEM_PROMPT_LABEL = 'System Prompt';
30
+
31
+ /** Shared name of pi's context files; Usage and Injections must present it identically. */
32
+ export const INSTRUCTION_FILES_LABEL = 'Instruction Files';
33
+
34
+ /** Shared name of pi's skill records; Usage and Injections must present it identically. */
35
+ export const SKILLS_LABEL = 'Skills';
36
+
37
+ /** Shared name of pi's built-in tools; Usage and Injections must present it identically. */
38
+ export const BUILT_IN_TOOLS_LABEL = 'Built-in Tools';
39
+
11
40
  /** What produced the captured snapshot. */
12
41
  export type CaptureOrigin = 'real-turn' | 'synthetic-probe';
13
42
 
@@ -27,12 +56,67 @@ export interface InjectionSource {
27
56
  readonly native: boolean;
28
57
  }
29
58
 
59
+ /** Half-open `[start, end)` character range within captured text. */
60
+ export interface TextSpan {
61
+ readonly start: number;
62
+ readonly end: number;
63
+ }
64
+
65
+ /**
66
+ * Character range of a JSON document embedded in preview text, known from how
67
+ * the text was built rather than from inspecting it. Full-content previews
68
+ * expand the run; the compact provider-bound form still backs every estimate.
69
+ */
70
+ export interface JsonSpan {
71
+ readonly start: number;
72
+ readonly end: number;
73
+ }
74
+
75
+ /** A rendered prompt line counted by its owning tool, inserted only for prompt previews. */
76
+ export interface InjectedReference {
77
+ /** Insertion offset in the containing item's or section's counted text, in prompt order. */
78
+ readonly offset: number;
79
+ /** Captured line including its leading line break; never additional counted text. */
80
+ readonly text: string;
81
+ /** Stable id of the item that counts this text. */
82
+ readonly itemId: string;
83
+ readonly source: InjectionSource;
84
+ /**
85
+ * Tool or slash command of `source` this text belongs to, e.g. `web_search`
86
+ * or `/ask`. Qualifies the rendered source label only: `itemId` still names
87
+ * the item that counts the text.
88
+ */
89
+ readonly tool?: string;
90
+ /**
91
+ * Present when the source was inferred from the text itself. Pi reports no
92
+ * per-extension provenance for chained prompt edits, so such an attribution
93
+ * is a guess and must be rendered as one.
94
+ */
95
+ readonly attribution?: 'guess';
96
+ }
97
+
30
98
  /** One labeled part of an item's raw text, used only to shape its preview. */
31
99
  export interface InjectionSection {
100
+ /** Section name rendered as a preview subheader. */
32
101
  readonly label: string;
102
+ /** Slice of the parent item's text; sections concatenate back to it, except when dropped. */
33
103
  readonly text: string;
34
104
  /** Share of the parent estimate; sections sum exactly to the item total. */
35
105
  readonly tokens: number;
106
+ /**
107
+ * True when a `--system-prompt` replacement suppressed this part: pi never
108
+ * sent its text, so it carries no counted characters and always reads 0 tokens.
109
+ */
110
+ readonly dropped?: boolean;
111
+ /**
112
+ * True when an extension moved this part out of the region pi renders it
113
+ * into. Pi still sends the text, so it counts exactly as an unmoved part.
114
+ */
115
+ readonly moved?: boolean;
116
+ /** Serialized JSON inside `text`, e.g. a tool's parameter schema. */
117
+ readonly jsonSpan?: JsonSpan;
118
+ /** Preview-only extension prompt lines; their owning tools count them instead. */
119
+ readonly injectedReferences?: readonly InjectedReference[];
36
120
  }
37
121
 
38
122
  /** One measured context injection. */
@@ -49,10 +133,20 @@ export interface InjectionItem {
49
133
  readonly tokens: number;
50
134
  /** Raw injected text for preview. Process-local; never log or persist. */
51
135
  readonly text: string;
52
- /** Labeled parts of `text`; never additional tokens. */
136
+ /** Serialized JSON inside `text`, e.g. non-string message content. */
137
+ readonly jsonSpan?: JsonSpan;
138
+ /** Labeled parts of `text`, e.g. a tool's prompt lines and definition; never extra tokens. */
53
139
  readonly sections?: readonly InjectionSection[];
54
- /** True when a message exists only in the transformed provider context, not the session branch. */
55
- readonly contextOnly?: boolean;
140
+ /** True when a `--system-prompt` replacement suppressed this item; it reads 0 tokens. */
141
+ readonly dropped?: boolean;
142
+ /** True when an extension moved this part out of the region pi renders it into. */
143
+ readonly moved?: boolean;
144
+ /** Preview-only extension prompt lines for a standalone System Prompt part child. */
145
+ readonly injectedReferences?: readonly InjectedReference[];
146
+ /** True when a message exists only in the outgoing request, not the session branch. */
147
+ readonly requestOnly?: boolean;
148
+ /** Sanitized replay inputs for a captured system patch; index preserves request order across grouping. */
149
+ readonly systemMessage?: { readonly message: SystemMessage; readonly index: number };
56
150
  /** Constituent sub-items (e.g. individual built-in tools or skills), largest first. */
57
151
  readonly children?: readonly InjectionItem[];
58
152
  }
@@ -109,7 +203,9 @@ export interface UsagePreviewEntry {
109
203
  readonly invisibleReasoning?: InvisibleReasoningEstimate;
110
204
  /** Raw content for preview. Process-local; never log or persist. */
111
205
  readonly text: string;
112
- /** Labeled parts carried from a measured snapshot item. */
206
+ /** Serialized JSON inside `text`, e.g. tool-call arguments. */
207
+ readonly jsonSpan?: JsonSpan;
208
+ /** Labeled parts of `text`, carried from the measured item; never extra tokens. */
113
209
  readonly sections?: readonly InjectionSection[];
114
210
  }
115
211
 
@@ -135,8 +231,9 @@ export interface ContextUsageSnapshot {
135
231
  /**
136
232
  * Group measured items by source. Pi-native components come first, extension
137
233
  * sources follow by total size, and the unattributable aggregate comes last.
138
- * Items inside each group follow a fixed semantic order (base prompt, tools,
139
- * skills, then everything else by size). Returned objects own all nested data;
234
+ * Items inside each group follow the order pi assembles them into a request
235
+ * (base prompt, appended prompt, context files, skills, built-in tools, other
236
+ * tools, then everything else by size). Returned objects own all nested data;
140
237
  * later mutation of the input cannot change the groups.
141
238
  */
142
239
  export function groupInjections(items: readonly InjectionItem[]): InjectionGroup[] {
@@ -175,19 +272,37 @@ interface MutableGroup {
175
272
  totalTokens: number;
176
273
  }
177
274
 
178
- /** Owned copy of an item, including its nested source and children. */
275
+ /** Owned copy of an item, including its nested source, spans, and children. */
179
276
  function copyItem(item: InjectionItem): InjectionItem {
180
277
  return {
181
278
  ...item,
182
279
  source: { ...item.source },
183
- sections: item.sections?.map(section => ({ ...section })),
280
+ systemMessage: item.systemMessage === undefined ? undefined : structuredClone(item.systemMessage),
281
+ jsonSpan: copyJsonSpan(item.jsonSpan),
282
+ injectedReferences: copyInjectedReferences(item.injectedReferences),
283
+ sections: item.sections?.map(section => ({
284
+ ...section,
285
+ jsonSpan: copyJsonSpan(section.jsonSpan),
286
+ injectedReferences: copyInjectedReferences(section.injectedReferences),
287
+ })),
184
288
  children: item.children?.map(child => copyItem(child)),
185
289
  };
186
290
  }
187
291
 
292
+ /** Own reference records and their nested provenance without adding their text to totals. */
293
+ function copyInjectedReferences(references: readonly InjectedReference[] | undefined): InjectedReference[] | undefined {
294
+ return references?.map(reference => ({ ...reference, source: { ...reference.source } }));
295
+ }
296
+
297
+ /** Owned copy of an optional span. */
298
+ function copyJsonSpan(span: JsonSpan | undefined): JsonSpan | undefined {
299
+ return span === undefined ? undefined : { ...span };
300
+ }
301
+
188
302
  /**
189
- * Order items within a group: base/appended prompt first, then built-in tools,
190
- * other tools, skills, and finally everything else by size descending.
303
+ * Order items within a group by the order pi assembles them into a request:
304
+ * base prompt, appended prompt, context files, skills, built-in tools, other
305
+ * tools, and finally everything else by size descending.
191
306
  */
192
307
  function compareItems(a: InjectionItem, b: InjectionItem): number {
193
308
  const rankDelta = itemRank(a) - itemRank(b);
@@ -199,14 +314,17 @@ function compareItems(a: InjectionItem, b: InjectionItem): number {
199
314
  function itemRank(item: InjectionItem): number {
200
315
  switch (item.kind) {
201
316
  case 'base-prompt':
202
- case 'append-prompt':
203
317
  return 0;
204
- case 'tool':
205
- return item.id === 'tool:builtin' ? 1 : 2;
318
+ case 'append-prompt':
319
+ return 1;
320
+ case 'context-file':
321
+ return 2;
206
322
  case 'skills':
207
323
  return 3;
324
+ case 'tool':
325
+ return item.id === 'tool:builtin' ? 4 : 5;
208
326
  default:
209
- return 4;
327
+ return 6;
210
328
  }
211
329
  }
212
330
 
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Process-local correlation token for the silent probe. The token travels with
3
+ * the async execution context of this extension's own `sendUserMessage()` call,
4
+ * so lifecycle handlers can recognize the probe run itself instead of guessing
5
+ * from prompt text another extension's input transform may have rewritten.
6
+ */
7
+ import { AsyncLocalStorage } from 'node:async_hooks';
8
+ import { randomUUID } from 'node:crypto';
9
+
10
+ /** Opaque per-attempt correlation value. Never persisted, rendered, or logged. */
11
+ export type ProbeToken = string;
12
+
13
+ const PROBE_TOKEN_STORAGE = new AsyncLocalStorage<ProbeToken>();
14
+
15
+ /** Create the correlation token for one probe attempt. */
16
+ export function createProbeToken(): ProbeToken {
17
+ return randomUUID();
18
+ }
19
+
20
+ /** Run `send` so every handler pi invokes from that call observes `token`. */
21
+ export function runWithProbeToken<T>(token: ProbeToken, send: () => T): T {
22
+ return PROBE_TOKEN_STORAGE.run(token, send);
23
+ }
24
+
25
+ /** The token of the probe call the current handler runs inside, if any. */
26
+ export function readProbeToken(): ProbeToken | undefined {
27
+ return PROBE_TOKEN_STORAGE.getStore();
28
+ }
@@ -0,0 +1,174 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /** Pure, deliberately heuristic attribution of the text after pi's prompt footer. */
3
+ import { AGGREGATE_SOURCE, extensionSource, type InjectionSource, type TextSpan } from './model';
4
+
5
+ /** Public tool/command provenance only; no extension files are read to guess an owner. */
6
+ export interface PromptSourceSlice {
7
+ readonly source: string;
8
+ readonly path: string;
9
+ /** Package root only, never a shared directory of loose extension files. */
10
+ readonly baseDir?: string;
11
+ /** Tools and slash commands this source registered; commands carry their `/`. */
12
+ readonly names?: readonly string[];
13
+ }
14
+
15
+ /** Optional observations that improve guesses without claiming handler-level provenance. */
16
+ export interface PromptAdditionOptions {
17
+ readonly sources?: readonly PromptSourceSlice[];
18
+ /** Prompt seen at our latest before_agent_start handler; used only if still a prefix. */
19
+ readonly promptAtHandler?: string;
20
+ /** Ordered, non-overlapping ranges counted as recovered System Prompt blocks, not additions. */
21
+ readonly excluded?: readonly TextSpan[];
22
+ }
23
+
24
+ /** One contiguous captured run outside recovered prompt blocks and whitespace-only gaps. */
25
+ export interface PromptAdditionRun {
26
+ readonly text: string;
27
+ readonly source: InjectionSource;
28
+ /** Tool or command of `source` the run named, when exactly one of them occurs in it. */
29
+ readonly tool?: string;
30
+ readonly attribution?: 'guess';
31
+ }
32
+
33
+ /** Characters that may follow a matched path: its own separator, or ordinary prose punctuation. */
34
+ const PATH_BOUNDARY = '[/\\s"\'`<>\\[\\](),;:]';
35
+
36
+ /** Shortest registered name worth guessing; shorter tokens match ordinary prose too readily. */
37
+ const MIN_NAME_LENGTH = 3;
38
+
39
+ /**
40
+ * Bound blank-line blocks at our handler position, then guess a source only on
41
+ * a unique package-name or full-path match. Unmatched/ambiguous text stays
42
+ * unattributed. The boundary is internal and never establishes an owner.
43
+ */
44
+ export function splitPromptAdditions(prompt: string, start: number, options: PromptAdditionOptions): PromptAdditionRun[] {
45
+ const observed = options.promptAtHandler;
46
+ const boundary = observed !== undefined && observed.length > start && prompt.startsWith(observed) ? observed.length : start;
47
+ const regions = [
48
+ ...additionRegions(prompt, start, boundary, options.excluded ?? []),
49
+ ...additionRegions(prompt, boundary, prompt.length, options.excluded ?? []),
50
+ ];
51
+ const runs: Array<{ text: string; source: InjectionSource; tool?: string }> = [];
52
+ for (const region of regions) {
53
+ let previous: { text: string; source: InjectionSource; tool?: string } | undefined;
54
+ for (const text of splitBlocks(region)) {
55
+ const owner = guessOwner(text, options.sources ?? []);
56
+ // Merge only inside one region: text on either side of the boundary has different authors.
57
+ if (previous?.source.id === owner.source.id && previous.tool === owner.tool) {
58
+ previous.text += text;
59
+ continue;
60
+ }
61
+ previous = { text, ...owner };
62
+ runs.push(previous);
63
+ }
64
+ }
65
+ return runs.map(run => ({
66
+ ...run,
67
+ attribution: run.source.id === AGGREGATE_SOURCE.id ? undefined : 'guess',
68
+ }));
69
+ }
70
+
71
+ /** Keep gaps separate: removing a moved block must not join evidence from different additions. */
72
+ function additionRegions(prompt: string, start: number, end: number, excluded: readonly TextSpan[]): string[] {
73
+ const regions: string[] = [];
74
+ let cursor = start;
75
+ for (const span of excluded) {
76
+ if (span.end <= cursor || span.start >= end) continue;
77
+ if (span.start > cursor) regions.push(prompt.slice(cursor, span.start));
78
+ cursor = Math.min(end, span.end);
79
+ }
80
+ if (cursor < end) regions.push(prompt.slice(cursor, end));
81
+ return regions;
82
+ }
83
+
84
+ /** Keep separators with the following block; trailing whitespace stays with the final block. */
85
+ function splitBlocks(text: string): string[] {
86
+ const blocks: string[] = [];
87
+ let start = 0;
88
+ for (const separator of text.matchAll(/\r?\n[\t ]*\r?\n(?:[\t ]*\r?\n)*/g)) {
89
+ if (text.slice(start, separator.index).trim().length === 0) continue;
90
+ if (text.slice(separator.index).trim().length === 0) break;
91
+ blocks.push(text.slice(start, separator.index));
92
+ start = separator.index;
93
+ }
94
+ // Removing a relocated block can leave a separator behind; blank text has no author.
95
+ if (text.slice(start).trim().length > 0) blocks.push(text.slice(start));
96
+ return blocks;
97
+ }
98
+
99
+ /** Extension a block was guessed to belong to, and the tool or command it named. */
100
+ interface PromptAdditionOwner {
101
+ readonly source: InjectionSource;
102
+ readonly tool?: string;
103
+ }
104
+
105
+ /** Several tools/commands from one package are one candidate, not an ambiguous match. */
106
+ function guessOwner(text: string, sources: readonly PromptSourceSlice[]): PromptAdditionOwner {
107
+ const normalized = text.replaceAll('\\', '/');
108
+ const matches = new Set<string>();
109
+ for (const source of sources) {
110
+ if (source.source === 'builtin' || source.source === 'sdk') continue;
111
+ const packageName = source.source.match(/^npm:((?:@[^/]+\/)?[^@]+)(?:@.*)?$/)?.[1];
112
+ if (
113
+ containsPath(normalized, source.path) ||
114
+ containsPath(normalized, source.baseDir) ||
115
+ (packageName !== undefined && containsPackage(normalized, packageName)) ||
116
+ (/^(npm:|git:|https?:\/\/|ssh:\/\/)/.test(source.source) && containsPackage(normalized, source.source))
117
+ )
118
+ matches.add(source.source);
119
+ }
120
+ const [match] = matches;
121
+ if (matches.size !== 1 || match === undefined) return { source: AGGREGATE_SOURCE };
122
+ return { source: extensionSource(match), tool: guessTool(normalized, sources, match) };
123
+ }
124
+
125
+ /**
126
+ * Registered tool or command of the owning extension the block names, when
127
+ * exactly one of them occurs in it. Two mentions name no tool, as two packages
128
+ * name no extension; the result only qualifies a guessed label, so it never
129
+ * changes which item counts the text.
130
+ */
131
+ function guessTool(text: string, sources: readonly PromptSourceSlice[], owner: string): string | undefined {
132
+ const matches = new Set<string>();
133
+ for (const source of sources) {
134
+ if (source.source !== owner) continue;
135
+ for (const name of source.names ?? []) {
136
+ if (name.length >= MIN_NAME_LENGTH && containsName(text, name)) matches.add(name);
137
+ }
138
+ }
139
+ const [name] = matches;
140
+ return matches.size === 1 ? name : undefined;
141
+ }
142
+
143
+ /**
144
+ * Require a complete name token, so a longer identifier and a path segment are
145
+ * no mention: `web_search` matches in prose but not in `tools/web_search.md`,
146
+ * and the command `/ask` matches only where it is written with its slash.
147
+ */
148
+ function containsName(text: string, name: string): boolean {
149
+ return new RegExp(`(?<![\\w/-])${escapePattern(name)}(?![\\w-])`).test(text);
150
+ }
151
+
152
+ /**
153
+ * Require a complete package token: a longer package name must not match, while
154
+ * ordinary sentence punctuation after the name must, so `pi-web-providers` and
155
+ * `pi-web.js` are rejected where `npm:pi-web.` is accepted.
156
+ */
157
+ function containsPackage(text: string, name: string): boolean {
158
+ const escaped = escapePattern(name);
159
+ return new RegExp(`(?:^|[^\\w@/.-]|/node_modules/)${escaped}(?![\\w-])(?!\\.[\\w-])`).test(text);
160
+ }
161
+
162
+ /** Match absolute paths at boundaries; a package root may be followed by a child path. */
163
+ function containsPath(text: string, path: string | undefined): boolean {
164
+ if (path === undefined) return false;
165
+ const normalized = path.replaceAll('\\', '/').replace(/\/+$/, '');
166
+ // A relative or synthetic provenance such as `<builtin:read>` is no evidence of authorship.
167
+ if (!/^(\/|[A-Za-z]:\/).+/.test(normalized)) return false;
168
+ return new RegExp(`(?:^|[^\\w/.-])${escapePattern(normalized)}(?=$|${PATH_BOUNDARY})`).test(text);
169
+ }
170
+
171
+ /** Escape literal provenance before using it in a boundary-sensitive pattern. */
172
+ function escapePattern(text: string): string {
173
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
174
+ }
@@ -0,0 +1,204 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /** Locate pi's semantic prompt blocks without assuming extensions preserve their order. */
3
+ import type { TextSpan } from './model';
4
+
5
+ /** Block pi renders one bullet per visible tool into. */
6
+ export const AVAILABLE_TOOLS_BLOCK = {
7
+ id: 'base-prompt:available-tools',
8
+ label: 'Available Tools',
9
+ header: '\nAvailable tools:\n',
10
+ };
11
+ /** Block pi renders tool guideline bullets into. */
12
+ export const GUIDELINES_BLOCK = {
13
+ id: 'base-prompt:guidelines',
14
+ label: 'Guidelines',
15
+ header: '\nGuidelines:\n',
16
+ };
17
+ /** Block pi renders its own documentation into. */
18
+ export const DOCUMENTATION_BLOCK = {
19
+ id: 'base-prompt:documentation',
20
+ label: 'Documentation',
21
+ header: '\nPi documentation',
22
+ };
23
+
24
+ /** Pi's normal emission order, also the blocks a custom prompt replaces. */
25
+ export const BASE_PROMPT_BLOCKS = [AVAILABLE_TOOLS_BLOCK, GUIDELINES_BLOCK, DOCUMENTATION_BLOCK];
26
+
27
+ const UNIVERSAL_GUIDELINES = ['Be concise in your responses', 'Show file paths clearly when working with files'];
28
+ const CUSTOM_TOOLS_FILLER = 'In addition to the tools above, you may have access to other custom tools depending on the project.';
29
+
30
+ /** One complete top-level XML section, with transport framing separated from its body. */
31
+ export interface PromptSection extends TextSpan {
32
+ readonly name: string;
33
+ /** Includes the newline before the body, but not the newline before the closing tag. */
34
+ readonly body: TextSpan;
35
+ }
36
+
37
+ /**
38
+ * Locate Pi 0.86 sections in rendered order. Skip whole sections and fenced examples
39
+ * so tags in instruction files, skills, addenda, and custom sections are not blocks.
40
+ */
41
+ export function findPromptSections(prompt: string): PromptSection[] {
42
+ const sections: PromptSection[] = [];
43
+ let fence: string | undefined;
44
+ const pattern = /^<([a-z][a-z0-9_-]*)>\n|^ {0,3}(`{3,}|~{3,})([^\n]*)/gm;
45
+ for (let match = pattern.exec(prompt); match !== null; match = pattern.exec(prompt)) {
46
+ const marker = match[2];
47
+ if (marker !== undefined) {
48
+ if (fence === undefined) fence = marker;
49
+ else if (marker[0] === fence[0] && marker.length >= fence.length && (match[3] ?? '').trim() === '') fence = undefined;
50
+ continue;
51
+ }
52
+ if (fence !== undefined) continue;
53
+ const name = match[1];
54
+ if (name === undefined) continue;
55
+ const closing = `\n</${name}>`;
56
+ const end = prompt.indexOf(closing, pattern.lastIndex);
57
+ if (end === -1) continue;
58
+ const after = end + closing.length;
59
+ if (after < prompt.length && prompt[after] !== '\n') continue;
60
+ sections.push({ name, start: match.index, end: after, body: { start: pattern.lastIndex - 1, end } });
61
+ pattern.lastIndex = after;
62
+ }
63
+ return sections;
64
+ }
65
+
66
+ /** Locate native XML tool surfaces with bounded, consecutive bullet regions and positional markers. */
67
+ export function findSectionToolBlocks(prompt: string, sections: readonly PromptSection[]): LocatedPromptBlock[] {
68
+ const order = ['tools', 'rules', 'docs', 'addendum', 'project_context', 'skills', 'cwd'];
69
+ return sections.flatMap((section): LocatedPromptBlock[] => {
70
+ if (section.name !== 'tools' && section.name !== 'rules') return [];
71
+ const block = section.name === 'tools' ? AVAILABLE_TOOLS_BLOCK : GUIDELINES_BLOCK;
72
+ const moved = sections.some(other => other.start < section.start && order.indexOf(other.name) > order.indexOf(section.name));
73
+ const bullets = findBulletSpan(prompt, section.body.start);
74
+ return [{ ...block, ...section.body, bullets, moved: moved || undefined }];
75
+ });
76
+ }
77
+
78
+ /** Active-tool evidence used to distinguish relocated blocks from unrelated appended prose. */
79
+ export interface PromptBlockTool {
80
+ readonly name: string;
81
+ readonly snippet?: string;
82
+ readonly guidelines: readonly string[];
83
+ }
84
+
85
+ /** One selected header and its bounded content, in original prompt coordinates. */
86
+ export interface LocatedPromptBlock extends TextSpan {
87
+ readonly id: string;
88
+ readonly label: string;
89
+ /** Exact bullet region, including the newline before the first bullet. */
90
+ readonly bullets?: TextSpan;
91
+ /** Position differs from pi's normal block order; no claim about which handler moved it. */
92
+ readonly moved?: boolean;
93
+ }
94
+
95
+ /**
96
+ * Select one occurrence per block, preferring the pre-footer occurrence. Blocks
97
+ * outside pi's normal pre-documentation region need contiguous bullets and an
98
+ * exact active-tool snippet or known guideline match. Instructions, skills,
99
+ * appended prompts, and fenced examples are never evidence of relocation.
100
+ */
101
+ export function findPromptBlocks(
102
+ prompt: string,
103
+ baseEnd: number,
104
+ tools: readonly PromptBlockTool[],
105
+ ignored: readonly TextSpan[],
106
+ ): LocatedPromptBlock[] {
107
+ const excluded = [...ignored, ...findFencedSpans(prompt, ignored)];
108
+ const documentationStart = headerStarts(prompt, DOCUMENTATION_BLOCK.header, excluded).find(start => start < baseEnd);
109
+ const nativeEnd = documentationStart ?? baseEnd;
110
+ const found: LocatedPromptBlock[] = [];
111
+ for (const block of [AVAILABLE_TOOLS_BLOCK, GUIDELINES_BLOCK]) {
112
+ const candidates = headerStarts(prompt, block.header, excluded).flatMap(start => {
113
+ const headerEnd = start + block.header.length - (start === 0 && prompt[0] !== '\n' ? 1 : 0);
114
+ const bullets = findBulletSpan(prompt, headerEnd - 1);
115
+ const native = start < nativeEnd;
116
+ if (!native && (bullets === undefined || !hasKnownBullet(prompt, bullets, block.id, tools))) return [];
117
+ const end = bullets?.end ?? headerEnd;
118
+ return [{ ...block, start, end: includeFiller(prompt, end, block.id), bullets }];
119
+ });
120
+ const beforeFooter = candidates.find(candidate => candidate.start < baseEnd);
121
+ // Several post-footer copies are ambiguous; leave them as additions rather than guessing.
122
+ const chosen = beforeFooter ?? (candidates.length === 1 ? candidates[0] : undefined);
123
+ if (chosen !== undefined) found.push(chosen);
124
+ }
125
+ if (documentationStart !== undefined) {
126
+ found.push({ ...DOCUMENTATION_BLOCK, start: documentationStart, end: baseEnd });
127
+ }
128
+ return found
129
+ .map(block => ({
130
+ ...block,
131
+ moved:
132
+ block.id !== DOCUMENTATION_BLOCK.id &&
133
+ (block.start >= baseEnd ||
134
+ found.some(
135
+ other =>
136
+ BASE_PROMPT_BLOCKS.findIndex(entry => entry.id === other.id) > BASE_PROMPT_BLOCKS.findIndex(entry => entry.id === block.id) &&
137
+ other.start < block.start,
138
+ ))
139
+ ? true
140
+ : undefined,
141
+ }))
142
+ .sort((a, b) => a.start - b.start);
143
+ }
144
+
145
+ /** Line-start header matches outside separately attributed content and fenced examples. */
146
+ function headerStarts(prompt: string, header: string, excluded: readonly TextSpan[]): number[] {
147
+ const needle = header.slice(1);
148
+ const starts: number[] = [];
149
+ let position = prompt.indexOf(needle);
150
+ while (position !== -1) {
151
+ if ((position === 0 || prompt[position - 1] === '\n') && !excluded.some(span => position >= span.start && position < span.end)) {
152
+ starts.push(Math.max(0, position - 1));
153
+ }
154
+ position = prompt.indexOf(needle, position + needle.length);
155
+ }
156
+ return starts;
157
+ }
158
+
159
+ /** Consecutive complete bullet lines; stop before any unrelated prose or following header. */
160
+ function findBulletSpan(prompt: string, start: number): TextSpan | undefined {
161
+ let end = start;
162
+ while (prompt.startsWith('\n- ', end)) {
163
+ const newline = prompt.indexOf('\n', end + 1);
164
+ end = newline === -1 ? prompt.length : newline;
165
+ }
166
+ return end === start ? undefined : { start, end };
167
+ }
168
+
169
+ /** Complete line equality, not prefix matching: a longer bullet is not evidence of pi's text. */
170
+ function hasKnownBullet(prompt: string, span: TextSpan, blockId: string, tools: readonly PromptBlockTool[]): boolean {
171
+ const lines = new Set(prompt.slice(span.start + 1, span.end).split('\n'));
172
+ const known =
173
+ blockId === AVAILABLE_TOOLS_BLOCK.id
174
+ ? tools.filter(tool => tool.snippet).map(tool => `${tool.name}: ${tool.snippet}`)
175
+ : [...UNIVERSAL_GUIDELINES, ...tools.flatMap(tool => tool.guidelines)].map(line => line.trim());
176
+ return known.some(line => line.length > 0 && lines.has(`- ${line}`));
177
+ }
178
+
179
+ /** Pi's optional filler belongs to the tool list, never to an unrelated addition following it. */
180
+ function includeFiller(prompt: string, end: number, blockId: string): number {
181
+ if (blockId !== AVAILABLE_TOOLS_BLOCK.id) return end;
182
+ const match = prompt.slice(end).match(/^\n(?:[\t ]*\n)+/);
183
+ if (match === null) return end;
184
+ const start = end + match[0].length;
185
+ const fillerEnd = start + CUSTOM_TOOLS_FILLER.length;
186
+ return prompt.startsWith(CUSTOM_TOOLS_FILLER, start) && (fillerEnd === prompt.length || prompt[fillerEnd] === '\n') ? fillerEnd : end;
187
+ }
188
+
189
+ /** Fence-delimited examples are quoted content, even when they repeat real tool snippets. */
190
+ function findFencedSpans(prompt: string, ignored: readonly TextSpan[]): TextSpan[] {
191
+ const spans: TextSpan[] = [];
192
+ let open: { start: number; marker: string } | undefined;
193
+ for (const line of prompt.matchAll(/^ {0,3}(`{3,}|~{3,})([^\n]*)/gm)) {
194
+ if (ignored.some(span => line.index >= span.start && line.index < span.end)) continue;
195
+ const marker = line[1] ?? '';
196
+ if (open === undefined) open = { start: line.index, marker };
197
+ else if (marker[0] === open.marker[0] && marker.length >= open.marker.length && line[2]?.trim() === '') {
198
+ spans.push({ start: open.start, end: line.index + line[0].length });
199
+ open = undefined;
200
+ }
201
+ }
202
+ if (open !== undefined) spans.push({ start: open.start, end: prompt.length });
203
+ return spans;
204
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Read pi's own compaction settings for the Usage map. Only the auto-compaction
3
+ * reserve is needed: it is the headroom content can never occupy.
4
+ */
5
+ import { type ExtensionCommandContext, SettingsManager } from '@earendil-works/pi-coding-agent';
6
+
7
+ /** Identifies the `compaction.modelOverrides` entry pi would apply to a request. */
8
+ export interface CompactionModel {
9
+ readonly provider: string;
10
+ readonly id: string;
11
+ }
12
+
13
+ /**
14
+ * Read the auto-compaction reserve from the same merged settings files pi uses,
15
+ * or undefined when auto-compaction is disabled. Read at view-open time because
16
+ * `reserveTokens` has no runtime setter but `enabled` and the model can change.
17
+ */
18
+ export function readAutoCompactReserveTokens(context: ExtensionCommandContext): number | undefined {
19
+ try {
20
+ const settings = SettingsManager.create(context.cwd, undefined, {
21
+ projectTrusted: context.isProjectTrusted(),
22
+ });
23
+ return resolveAutoCompactReserveTokens(settings, context.model);
24
+ } catch {
25
+ // Unreadable settings degrade to a map without the buffer, not a failed view.
26
+ return undefined;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Resolve the reserve pi would apply to `model`: its `compaction.modelOverrides`
32
+ * entry, else the ordinary `compaction.reserveTokens`, else pi's default.
33
+ * Returns undefined when auto-compaction is disabled or a setting is invalid.
34
+ */
35
+ export function resolveAutoCompactReserveTokens(settings: SettingsManager, model?: CompactionModel): number | undefined {
36
+ try {
37
+ if (!settings.getCompactionEnabled()) return undefined;
38
+ return settings.getCompactionReserveTokens(model);
39
+ } catch {
40
+ // Pi rejects invalid reserve values; show no buffer rather than a wrong one.
41
+ return undefined;
42
+ }
43
+ }