@0xkahi/pi-qol 1.0.6 → 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.
- package/package.json +4 -5
- package/src/extensions/context-view/capture.ts +311 -83
- package/src/extensions/context-view/codemap.md +111 -48
- package/src/extensions/context-view/context-view-controller.ts +65 -27
- package/src/extensions/context-view/index.ts +22 -6
- package/src/extensions/context-view/measure.ts +713 -78
- package/src/extensions/context-view/model.ts +132 -14
- package/src/extensions/context-view/probe-token.ts +28 -0
- package/src/extensions/context-view/prompt-additions.ts +174 -0
- package/src/extensions/context-view/prompt-blocks.ts +204 -0
- package/src/extensions/context-view/settings.ts +43 -0
- package/src/extensions/context-view/text.ts +48 -0
- package/src/extensions/context-view/transcript.ts +62 -0
- package/src/extensions/context-view/ui/codemap.md +28 -13
- package/src/extensions/context-view/ui/context-view-dialog.ts +6 -1
- package/src/extensions/context-view/ui/injections-model.ts +13 -28
- package/src/extensions/context-view/ui/injections-view.ts +82 -21
- package/src/extensions/context-view/ui/json-preview.ts +41 -0
- package/src/extensions/context-view/ui/markers.ts +96 -0
- package/src/extensions/context-view/ui/section-preview.ts +188 -10
- package/src/extensions/context-view/ui/usage-block-layer.ts +9 -4
- package/src/extensions/context-view/ui/usage-view.ts +70 -17
- package/src/extensions/context-view/ui/wheel-preview-layer.ts +104 -0
- package/src/extensions/context-view/ui/wheel.ts +66 -0
- package/src/extensions/context-view/usage.ts +64 -26
|
@@ -3,22 +3,75 @@
|
|
|
3
3
|
* Pure measurement logic: split a captured system prompt into semantic items
|
|
4
4
|
* and estimate token sizes. No pi API access — unit-testable.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
6
|
+
* Pi 0.86 uses independently replaceable XML sections. Their wrappers locate
|
|
7
|
+
* content; custom sections remain System Prompt parts rather than additions.
|
|
8
|
+
* The legacy parser below also recognizes pi 0.80–0.85 structural markers:
|
|
8
9
|
*
|
|
9
10
|
* - context files: <project_instructions path="...">...</project_instructions>
|
|
10
11
|
* - skills block: "The following skills provide..." through </available_skills>
|
|
11
|
-
* -
|
|
12
|
-
*
|
|
13
|
-
*
|
|
12
|
+
* - tool prompt lines: the bullet blocks under "Available tools:" and
|
|
13
|
+
* "Guidelines:", where pi renders each distinct bullet exactly once, in
|
|
14
|
+
* active-tool order (verified against pi 0.84.3)
|
|
15
|
+
* - base prompt blocks: the "Available tools:", "Guidelines:", and
|
|
16
|
+
* "Pi documentation" headers pi emits, which split its own prompt into the
|
|
17
|
+
* parts System Prompt presents as sub-items. A `before_agent_start` handler
|
|
18
|
+
* may relocate the two tool-surface blocks past pi's footer, so blocks are
|
|
19
|
+
* located independently and ordered by where they ended up
|
|
20
|
+
* - the "Current working directory" footer (pi 0.81), optionally preceded by a
|
|
21
|
+
* "Current date" line (pi 0.80), closes pi's own prompt: pi sends it with
|
|
22
|
+
* every request, so it is measured as the Current Dir part. Text after it
|
|
23
|
+
* is an extension addition unless it is a structurally recovered tool block.
|
|
14
24
|
*/
|
|
15
|
-
import {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
25
|
+
import {
|
|
26
|
+
AGGREGATE_SOURCE,
|
|
27
|
+
BUILT_IN_TOOLS_LABEL,
|
|
28
|
+
extensionSource,
|
|
29
|
+
INSTRUCTION_FILES_LABEL,
|
|
30
|
+
type InjectedReference,
|
|
31
|
+
type InjectionItem,
|
|
32
|
+
type InjectionKind,
|
|
33
|
+
type InjectionSection,
|
|
34
|
+
type InjectionSource,
|
|
35
|
+
type JsonSpan,
|
|
36
|
+
PI_SOURCE,
|
|
37
|
+
SKILLS_LABEL,
|
|
38
|
+
SYSTEM_PROMPT_LABEL,
|
|
39
|
+
} from './model';
|
|
40
|
+
import { type PromptAdditionOptions, splitPromptAdditions } from './prompt-additions';
|
|
41
|
+
import {
|
|
42
|
+
AVAILABLE_TOOLS_BLOCK,
|
|
43
|
+
BASE_PROMPT_BLOCKS,
|
|
44
|
+
DOCUMENTATION_BLOCK,
|
|
45
|
+
findPromptBlocks,
|
|
46
|
+
findPromptSections,
|
|
47
|
+
findSectionToolBlocks,
|
|
48
|
+
GUIDELINES_BLOCK,
|
|
49
|
+
type LocatedPromptBlock,
|
|
50
|
+
type PromptSection,
|
|
51
|
+
} from './prompt-blocks';
|
|
52
|
+
|
|
53
|
+
/** Part names shared by a tool's carved prompt lines and pi's own prompt blocks. */
|
|
54
|
+
const AVAILABLE_TOOLS_LABEL = AVAILABLE_TOOLS_BLOCK.label;
|
|
55
|
+
const GUIDELINES_LABEL = GUIDELINES_BLOCK.label;
|
|
56
|
+
|
|
57
|
+
/** System Prompt part hosting the text extensions appended after pi's footer. */
|
|
58
|
+
const EXTENSION_ADDITIONS_BLOCK = { id: 'base-prompt:additions', label: 'Extension Additions' };
|
|
59
|
+
|
|
60
|
+
/** Item name every prompt-addition owner carries, pi-adjacent rather than tool-shaped. */
|
|
61
|
+
const PROMPT_ADDITIONS_LABEL = 'system prompt additions';
|
|
62
|
+
|
|
63
|
+
/** Leading part of pi's prompt, before the first block header pi renders. */
|
|
64
|
+
const PREAMBLE_BLOCK = { id: 'base-prompt:preamble', label: 'Preamble' };
|
|
65
|
+
|
|
66
|
+
/** Known XML section names retain the existing semantic ids and labels. */
|
|
67
|
+
const SECTION_PARTS: Readonly<Record<string, { id: string; label: string }>> = {
|
|
68
|
+
tools: AVAILABLE_TOOLS_BLOCK,
|
|
69
|
+
rules: GUIDELINES_BLOCK,
|
|
70
|
+
docs: DOCUMENTATION_BLOCK,
|
|
71
|
+
addendum: { id: 'base-prompt:appended', label: 'Appended Prompt' },
|
|
72
|
+
cwd: { id: 'base-prompt:current-dir', label: 'Current Dir' },
|
|
73
|
+
project_context: { id: 'base-prompt:context-files', label: INSTRUCTION_FILES_LABEL },
|
|
74
|
+
skills: { id: 'base-prompt:skills', label: SKILLS_LABEL },
|
|
22
75
|
};
|
|
23
76
|
|
|
24
77
|
/** One visible skill before pi adds XML transport framing. */
|
|
@@ -35,6 +88,8 @@ export interface PromptOptionsSlice {
|
|
|
35
88
|
homeDir?: string;
|
|
36
89
|
customPrompt?: string;
|
|
37
90
|
appendSystemPrompt?: string;
|
|
91
|
+
/** Custom section bodies, including overrides of Pi's named sections. */
|
|
92
|
+
sections?: Record<string, string>;
|
|
38
93
|
contextFilePaths?: string[];
|
|
39
94
|
skills?: SkillSlice[];
|
|
40
95
|
}
|
|
@@ -57,9 +112,23 @@ export interface ToolSlice {
|
|
|
57
112
|
/**
|
|
58
113
|
* Split a captured system prompt into semantic items: pi base prompt,
|
|
59
114
|
* appended prompt, context files, skills, active tool contributions, and the
|
|
60
|
-
*
|
|
115
|
+
* additions extensions appended after pi's footer.
|
|
61
116
|
*/
|
|
62
|
-
export function analyzeSystemPrompt(
|
|
117
|
+
export function analyzeSystemPrompt(
|
|
118
|
+
systemPrompt: string,
|
|
119
|
+
options: PromptOptionsSlice,
|
|
120
|
+
tools: ToolSlice[] = [],
|
|
121
|
+
additions: PromptAdditionOptions = {},
|
|
122
|
+
): InjectionItem[] {
|
|
123
|
+
const names = new Set<string>();
|
|
124
|
+
const sections = findPromptSections(systemPrompt).filter(section => {
|
|
125
|
+
if (names.has(section.name)) return false;
|
|
126
|
+
names.add(section.name);
|
|
127
|
+
return true;
|
|
128
|
+
});
|
|
129
|
+
if (sections.some(section => !['project_context', 'available_skills'].includes(section.name))) {
|
|
130
|
+
return analyzePromptSections(systemPrompt, sections, options, tools, additions);
|
|
131
|
+
}
|
|
63
132
|
const items: InjectionItem[] = [];
|
|
64
133
|
const carvedSpans: Span[] = [];
|
|
65
134
|
|
|
@@ -67,122 +136,477 @@ export function analyzeSystemPrompt(systemPrompt: string, options: PromptOptions
|
|
|
67
136
|
const base = footer === undefined ? systemPrompt : systemPrompt.slice(0, footer.start);
|
|
68
137
|
|
|
69
138
|
const usesCustomPrompt = options.customPrompt !== undefined && options.customPrompt.length > 0;
|
|
70
|
-
|
|
139
|
+
// Exclude separately attributed content before looking for headers inside it
|
|
71
140
|
measureContextFiles(base, options, items, carvedSpans);
|
|
72
141
|
measureSkills(base, options, items, carvedSpans);
|
|
73
|
-
|
|
142
|
+
const appended = carveAppendedPrompt(base, options, carvedSpans);
|
|
143
|
+
const appendedStart = appended === undefined ? undefined : carvedSpans[carvedSpans.length - 1]?.start;
|
|
144
|
+
// A custom prompt drops pi's blocks; a tool list added to it is not a relocation
|
|
145
|
+
const droppedIds = usesCustomPrompt ? BASE_PROMPT_BLOCKS.map(block => block.id) : [];
|
|
146
|
+
const located = usesCustomPrompt ? [] : findPromptBlocks(systemPrompt, base.length, tools, carvedSpans);
|
|
147
|
+
const tailBlocks = located.filter(block => block.start >= base.length);
|
|
148
|
+
const body = base + tailBlocks.map(block => systemPrompt.slice(block.start, block.end)).join('');
|
|
149
|
+
const bodyBlocks = positionBodyBlocks(located, base.length);
|
|
150
|
+
const toolItems: InjectionItem[] = [];
|
|
151
|
+
const promptLines = measureTools(body, tools, toolItems, carvedSpans, droppedIds, bodyBlocks);
|
|
152
|
+
items.unshift(...toolItems);
|
|
153
|
+
|
|
154
|
+
const remaining = carve(body, carvedSpans);
|
|
155
|
+
const blocks = usesCustomPrompt
|
|
156
|
+
? droppedBasePromptParts(remaining, promptLines.dropped)
|
|
157
|
+
: addInjectedReferences(
|
|
158
|
+
splitBasePromptParts(
|
|
159
|
+
remaining,
|
|
160
|
+
bodyBlocks.map(block => ({
|
|
161
|
+
...block,
|
|
162
|
+
start: carve(body.slice(0, block.start), carvedSpans).length,
|
|
163
|
+
})),
|
|
164
|
+
),
|
|
165
|
+
body,
|
|
166
|
+
carvedSpans,
|
|
167
|
+
promptLines.carved,
|
|
168
|
+
);
|
|
169
|
+
const references = footer === undefined ? [] : measurePromptAdditions(systemPrompt, footer.end, { ...additions, excluded: tailBlocks }, items);
|
|
170
|
+
|
|
171
|
+
const parts = blocks;
|
|
172
|
+
if (appended !== undefined) {
|
|
173
|
+
parts.push({ id: 'base-prompt:appended', kind: 'append-prompt', label: 'Appended Prompt', text: appended });
|
|
174
|
+
}
|
|
175
|
+
if (footer !== undefined) {
|
|
176
|
+
const text = systemPrompt.slice(footer.start, footer.end);
|
|
177
|
+
parts.push({ id: 'base-prompt:current-dir', kind: 'base-prompt', label: 'Current Dir', text });
|
|
178
|
+
}
|
|
179
|
+
if (references.length > 0) {
|
|
180
|
+
parts.push({
|
|
181
|
+
id: EXTENSION_ADDITIONS_BLOCK.id,
|
|
182
|
+
kind: 'prompt-addition',
|
|
183
|
+
label: EXTENSION_ADDITIONS_BLOCK.label,
|
|
184
|
+
text: '',
|
|
185
|
+
injectedReferences: references,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
if (!usesCustomPrompt) orderPromptParts(parts, located, footer, appendedStart);
|
|
189
|
+
items.unshift(createSystemPromptItem(parts));
|
|
74
190
|
|
|
75
|
-
|
|
76
|
-
|
|
191
|
+
return items;
|
|
192
|
+
}
|
|
77
193
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
194
|
+
/** Measure XML section bodies once, keeping arbitrary sections out of extension attribution. */
|
|
195
|
+
function analyzePromptSections(
|
|
196
|
+
prompt: string,
|
|
197
|
+
sections: readonly PromptSection[],
|
|
198
|
+
options: PromptOptionsSlice,
|
|
199
|
+
tools: ToolSlice[],
|
|
200
|
+
additions: PromptAdditionOptions,
|
|
201
|
+
): InjectionItem[] {
|
|
202
|
+
const items: InjectionItem[] = [];
|
|
203
|
+
const spans: Span[] = [];
|
|
204
|
+
const parts: PromptPart[] = [];
|
|
205
|
+
const blocks = findSectionToolBlocks(prompt, sections);
|
|
206
|
+
const replaced = Boolean(options.customPrompt);
|
|
207
|
+
const droppedIds = replaced
|
|
208
|
+
? BASE_PROMPT_BLOCKS.filter(block => !sections.some(section => SECTION_PARTS[section.name]?.id === block.id)).map(block => block.id)
|
|
209
|
+
: [];
|
|
210
|
+
const lines = measureTools(prompt, tools, items, spans, droppedIds, blocks);
|
|
211
|
+
const preambleEnd = sections[0]?.start ?? prompt.length;
|
|
212
|
+
appendPromptPart(parts, PREAMBLE_BLOCK, prompt.slice(0, preambleEnd).trimEnd());
|
|
213
|
+
for (const block of BASE_PROMPT_BLOCKS) {
|
|
214
|
+
if (droppedIds.includes(block.id)) {
|
|
215
|
+
parts.push({ ...block, kind: 'base-prompt', text: '', dropped: true, injectedReferences: lines.dropped.get(block.id) });
|
|
82
216
|
}
|
|
83
217
|
}
|
|
84
|
-
|
|
218
|
+
for (const section of sections) {
|
|
219
|
+
const body = prompt.slice(section.body.start + 1, section.body.end);
|
|
220
|
+
if (measureGeneratedSection(section.name, body, options, items)) continue;
|
|
221
|
+
parts.push(measureSectionPart(prompt, section, spans, lines.carved, blocks.find(candidate => candidate.start === section.body.start)?.moved));
|
|
222
|
+
}
|
|
223
|
+
// Only unwrapped gaps are additions. Sections after cwd still belong to the
|
|
224
|
+
// prompt, even when an earlier handler never saw them or cwd was removed.
|
|
225
|
+
const references = measurePromptAdditions(prompt, preambleEnd, { ...additions, excluded: sections }, items);
|
|
226
|
+
if (references.length > 0) {
|
|
227
|
+
parts.push({ ...EXTENSION_ADDITIONS_BLOCK, kind: 'prompt-addition', text: '', injectedReferences: references });
|
|
228
|
+
}
|
|
229
|
+
items.unshift(createSystemPromptItem(parts));
|
|
85
230
|
return items;
|
|
86
231
|
}
|
|
87
232
|
|
|
233
|
+
/** Carve one XML section while preserving exact preview-reference offsets within its body. */
|
|
234
|
+
function measureSectionPart(
|
|
235
|
+
prompt: string,
|
|
236
|
+
section: PromptSection,
|
|
237
|
+
spans: readonly Span[],
|
|
238
|
+
injected: readonly InjectedSpan[],
|
|
239
|
+
moved: boolean | undefined,
|
|
240
|
+
): PromptPart {
|
|
241
|
+
const block = SECTION_PARTS[section.name] ?? { id: `base-prompt:section:${section.name}`, label: section.name };
|
|
242
|
+
const start = section.name === 'tools' || section.name === 'rules' ? section.body.start : section.body.start + 1;
|
|
243
|
+
const localSpans = spans
|
|
244
|
+
.filter(span => span.start >= start && span.end <= section.body.end)
|
|
245
|
+
.map(span => ({ start: span.start - start, end: span.end - start }));
|
|
246
|
+
const text = carve(prompt.slice(start, section.body.end), localSpans);
|
|
247
|
+
const references = injected
|
|
248
|
+
.filter(span => span.partId === block.id && span.start >= start && span.end <= section.body.end)
|
|
249
|
+
.sort((a, b) => a.start - b.start)
|
|
250
|
+
.map(span => ({
|
|
251
|
+
offset: carve(prompt.slice(start, span.start), localSpans).length,
|
|
252
|
+
text: prompt.slice(span.start, span.end),
|
|
253
|
+
itemId: span.itemId,
|
|
254
|
+
source: span.source,
|
|
255
|
+
tool: span.tool,
|
|
256
|
+
}));
|
|
257
|
+
return {
|
|
258
|
+
id: block.id,
|
|
259
|
+
label: block.label,
|
|
260
|
+
text,
|
|
261
|
+
kind: section.name === 'addendum' ? 'append-prompt' : 'base-prompt',
|
|
262
|
+
moved,
|
|
263
|
+
injectedReferences: references.length > 0 ? references : undefined,
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Split generated records only when present; overridden or unknown content stays visible. */
|
|
268
|
+
function measureGeneratedSection(name: string, body: string, options: PromptOptionsSlice, items: InjectionItem[]): boolean {
|
|
269
|
+
if (options.sections?.[name]) return false;
|
|
270
|
+
if (name === 'project_context' && body.includes('<project_instructions path=')) {
|
|
271
|
+
const paths: string[] = [];
|
|
272
|
+
for (const match of body.matchAll(/<project_instructions path="([^"]+)">/g)) {
|
|
273
|
+
const path = match[1];
|
|
274
|
+
if (path !== undefined) paths.push(path);
|
|
275
|
+
}
|
|
276
|
+
const section = `<project_context>\n${body}\n</project_context>`;
|
|
277
|
+
measureContextFiles(section, { ...options, contextFilePaths: paths }, items, []);
|
|
278
|
+
return true;
|
|
279
|
+
}
|
|
280
|
+
if (name === 'skills' && body.includes('<available_skills>')) {
|
|
281
|
+
// Read the captured records, not today's loader metadata after resume or a patch.
|
|
282
|
+
const record = /<skill>\s*<name>(.*?)<\/name>\s*<description>([\s\S]*?)<\/description>\s*<location>(.*?)<\/location>/g;
|
|
283
|
+
const skills: SkillSlice[] = [];
|
|
284
|
+
for (const match of body.matchAll(record)) {
|
|
285
|
+
const name = match[1];
|
|
286
|
+
const description = match[2];
|
|
287
|
+
const filePath = match[3];
|
|
288
|
+
if (name === undefined || description === undefined || filePath === undefined) continue;
|
|
289
|
+
skills.push({ name: decodeXml(name), description: decodeXml(description), filePath: decodeXml(filePath) });
|
|
290
|
+
}
|
|
291
|
+
if (skills.length === 0) return false;
|
|
292
|
+
const children = skills
|
|
293
|
+
.map(skill => createItem(`skill:${skill.name}`, 'skills', PI_SOURCE, skill.name, [skill.name, skill.description, skill.filePath].join('\n')))
|
|
294
|
+
.sort((a, b) => b.tokens - a.tokens);
|
|
295
|
+
items.push(createAggregateItem('skills', 'skills', PI_SOURCE, `${SKILLS_LABEL} (${children.length})`, children));
|
|
296
|
+
return true;
|
|
297
|
+
}
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Decode the five XML entities Pi escapes when rendering skill metadata. */
|
|
302
|
+
function decodeXml(text: string): string {
|
|
303
|
+
const entities: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
|
|
304
|
+
return text.replace(/&(amp|lt|gt|quot|apos);/g, (_match: string, name: string) => entities[name] ?? _match);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Attribute the text extensions appended after pi's footer, and return it as
|
|
309
|
+
* preview-only references on the System Prompt part it was taken from. Every
|
|
310
|
+
* run is counted by the extension it was guessed to belong to, or by the
|
|
311
|
+
* unattributed aggregate, never by pi's own prompt.
|
|
312
|
+
*/
|
|
313
|
+
function measurePromptAdditions(systemPrompt: string, start: number, options: PromptAdditionOptions, items: InjectionItem[]): InjectedReference[] {
|
|
314
|
+
if (systemPrompt.slice(start).trim().length === 0) return [];
|
|
315
|
+
const references: InjectedReference[] = [];
|
|
316
|
+
const owners = new Map<string, { source: InjectionSource; text: string }>();
|
|
317
|
+
for (const run of splitPromptAdditions(systemPrompt, start, options)) {
|
|
318
|
+
const itemId = additionItemId(run.source);
|
|
319
|
+
// One insertion point: the part itself holds no counted text of its own.
|
|
320
|
+
references.push({
|
|
321
|
+
offset: 0,
|
|
322
|
+
text: run.text,
|
|
323
|
+
itemId,
|
|
324
|
+
source: run.source,
|
|
325
|
+
tool: run.tool,
|
|
326
|
+
attribution: run.attribution,
|
|
327
|
+
});
|
|
328
|
+
const owner = owners.get(itemId);
|
|
329
|
+
if (owner === undefined) owners.set(itemId, { source: run.source, text: run.text });
|
|
330
|
+
else owner.text += run.text;
|
|
331
|
+
}
|
|
332
|
+
for (const [itemId, owner] of owners) {
|
|
333
|
+
items.push(createItem(itemId, 'prompt-addition', owner.source, PROMPT_ADDITIONS_LABEL, owner.text));
|
|
334
|
+
}
|
|
335
|
+
return references;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Stable id of the item counting one source's prompt additions. */
|
|
339
|
+
function additionItemId(source: InjectionSource): string {
|
|
340
|
+
return source.id === AGGREGATE_SOURCE.id ? 'prompt-addition:unattributed' : `prompt-addition:${source.label}`;
|
|
341
|
+
}
|
|
342
|
+
|
|
88
343
|
/** Same chars/4 heuristic pi's estimateTokens uses for text content. */
|
|
89
344
|
export function textTokens(text: string): number {
|
|
90
345
|
return charTokens(text.length);
|
|
91
346
|
}
|
|
92
347
|
|
|
348
|
+
/** Token estimate for an already known character count. */
|
|
93
349
|
function charTokens(chars: number): number {
|
|
94
350
|
return Math.ceil(chars / 4);
|
|
95
351
|
}
|
|
96
352
|
|
|
353
|
+
/** Where each tool's prompt lines ended up: carved out of pi's blocks, or dropped with them. */
|
|
354
|
+
interface ToolPromptLines {
|
|
355
|
+
/** Carved lines, restored as references on the System Prompt part each came from. */
|
|
356
|
+
readonly carved: InjectedSpan[];
|
|
357
|
+
/** Extension lines a replacement suppressed, keyed by the part that would have carried them. */
|
|
358
|
+
readonly dropped: Map<string, InjectedReference[]>;
|
|
359
|
+
}
|
|
360
|
+
|
|
97
361
|
/**
|
|
98
362
|
* Measure active tool contributions: per-tool definition payloads plus the
|
|
99
363
|
* prompt snippet/guideline lines carved out of the base prompt. Built-in
|
|
100
|
-
* tools collapse into one aggregate pi-native item.
|
|
364
|
+
* tools collapse into one aggregate pi-native item. Lines a `--system-prompt`
|
|
365
|
+
* replacement suppressed belong to the parts named by `droppedPartIds`; each
|
|
366
|
+
* tool keeps those as dropped, uncounted sections instead.
|
|
101
367
|
*/
|
|
102
|
-
function measureTools(
|
|
103
|
-
|
|
368
|
+
function measureTools(
|
|
369
|
+
base: string,
|
|
370
|
+
tools: ToolSlice[],
|
|
371
|
+
items: InjectionItem[],
|
|
372
|
+
carvedSpans: Span[],
|
|
373
|
+
droppedPartIds: readonly string[],
|
|
374
|
+
blocks: readonly LocatedPromptBlock[],
|
|
375
|
+
): ToolPromptLines {
|
|
376
|
+
const carver = createPromptCarver(base, carvedSpans, blocks);
|
|
104
377
|
const claimedGuidelines = new Set(piOwnedGuidelines(tools));
|
|
378
|
+
const dropped = new Map<string, InjectedReference[]>();
|
|
105
379
|
const builtinChildren: InjectionItem[] = [];
|
|
106
380
|
for (const tool of tools) {
|
|
381
|
+
// Built-in tools claim their bullets without carving them, so a later
|
|
382
|
+
// extension tool repeating one cannot take a line pi already renders for
|
|
383
|
+
// pi itself or for a built-in tool.
|
|
107
384
|
const ownedGuidelines = claimGuidelines(tool, claimedGuidelines);
|
|
108
|
-
const definition
|
|
385
|
+
const definition = createDefinitionSection(tool);
|
|
386
|
+
const droppedLines = droppedPromptLines(tool, ownedGuidelines).filter(line => droppedPartIds.includes(line.partId));
|
|
109
387
|
if (tool.source === 'builtin') {
|
|
110
|
-
|
|
388
|
+
// Pi renders built-in lines on its own behalf, so they become visible here only once dropped.
|
|
389
|
+
const sections = [...droppedSections(droppedLines), definition];
|
|
390
|
+
builtinChildren.push(createToolItem(`tool:builtin:${tool.name}`, PI_SOURCE, tool.name, sections));
|
|
111
391
|
continue;
|
|
112
392
|
}
|
|
113
|
-
const
|
|
114
|
-
|
|
393
|
+
const owner: InjectedOwner = {
|
|
394
|
+
itemId: `tool:${tool.source}:${tool.name}`,
|
|
395
|
+
source: extensionSource(tool.source),
|
|
396
|
+
tool: tool.name,
|
|
397
|
+
};
|
|
398
|
+
collectDroppedReferences(dropped, droppedLines, owner);
|
|
399
|
+
const promptSections = [...droppedSections(droppedLines), ...carveToolPromptSections(carver, tool, ownedGuidelines, owner)];
|
|
400
|
+
items.push(createToolItem(owner.itemId, owner.source, tool.name, [...promptSections, definition]));
|
|
115
401
|
}
|
|
116
402
|
if (builtinChildren.length > 0) {
|
|
117
403
|
builtinChildren.sort((a, b) => b.tokens - a.tokens);
|
|
118
|
-
const label =
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
404
|
+
const label = `${BUILT_IN_TOOLS_LABEL} (${builtinChildren.length})`;
|
|
405
|
+
items.push(createAggregateItem('tool:builtin', 'tool', PI_SOURCE, label, builtinChildren));
|
|
406
|
+
}
|
|
407
|
+
return { carved: carver.injectedSpans, dropped };
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** One prompt line a replacement suppressed, and the System Prompt part pi would have rendered it into. */
|
|
411
|
+
interface DroppedLine {
|
|
412
|
+
readonly partId: string;
|
|
413
|
+
/** Section name the line belongs to, shared by the part and the owning tool. */
|
|
414
|
+
readonly label: string;
|
|
415
|
+
/** Line exactly as pi would have rendered it, including its leading line break. */
|
|
416
|
+
readonly text: string;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Prompt lines pi would have rendered for one tool: its snippet bullet, then the guidelines it owns. */
|
|
420
|
+
function droppedPromptLines(tool: ToolSlice, ownedGuidelines: string[]): DroppedLine[] {
|
|
421
|
+
const lines: DroppedLine[] = [];
|
|
422
|
+
if (tool.snippet !== undefined) {
|
|
423
|
+
lines.push({
|
|
424
|
+
partId: AVAILABLE_TOOLS_BLOCK.id,
|
|
425
|
+
label: AVAILABLE_TOOLS_LABEL,
|
|
426
|
+
text: `\n- ${tool.name}: ${tool.snippet}`,
|
|
125
427
|
});
|
|
126
428
|
}
|
|
429
|
+
for (const guideline of ownedGuidelines) {
|
|
430
|
+
lines.push({ partId: GUIDELINES_BLOCK.id, label: GUIDELINES_LABEL, text: `\n- ${guideline}` });
|
|
431
|
+
}
|
|
432
|
+
return lines;
|
|
127
433
|
}
|
|
128
434
|
|
|
435
|
+
/**
|
|
436
|
+
* Group one tool's dropped lines into a preview-only section per part, so its
|
|
437
|
+
* preview shows what the replacement gave up without claiming tokens pi never
|
|
438
|
+
* sent.
|
|
439
|
+
*/
|
|
440
|
+
function droppedSections(lines: readonly DroppedLine[]): SectionDraft[] {
|
|
441
|
+
const sections: SectionDraft[] = [];
|
|
442
|
+
for (const line of lines) {
|
|
443
|
+
const last = sections.length - 1;
|
|
444
|
+
const current = sections[last];
|
|
445
|
+
if (current !== undefined && current.label === line.label) {
|
|
446
|
+
sections[last] = { ...current, text: current.text + line.text };
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
sections.push({ label: line.label, text: line.text, dropped: true });
|
|
450
|
+
}
|
|
451
|
+
return sections;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** Restore one extension tool's dropped lines as references on the parts pi would have rendered them into. */
|
|
455
|
+
function collectDroppedReferences(dropped: Map<string, InjectedReference[]>, lines: readonly DroppedLine[], owner: InjectedOwner): void {
|
|
456
|
+
for (const line of lines) {
|
|
457
|
+
// One insertion point: a dropped part holds no counted text of its own.
|
|
458
|
+
const reference: InjectedReference = { offset: 0, text: line.text, ...owner };
|
|
459
|
+
const references = dropped.get(line.partId);
|
|
460
|
+
if (references === undefined) dropped.set(line.partId, [reference]);
|
|
461
|
+
else references.push(reference);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** One labeled part of a tool item's text, before it receives its token share. */
|
|
129
466
|
interface SectionDraft {
|
|
130
467
|
readonly label: string;
|
|
131
468
|
readonly text: string;
|
|
469
|
+
/** True for text a `--system-prompt` replacement dropped: shown for reference, never counted. */
|
|
470
|
+
readonly dropped?: boolean;
|
|
471
|
+
/** True for a block an extension moved out of the region pi rendered it into. */
|
|
472
|
+
readonly moved?: boolean;
|
|
473
|
+
/** Serialized JSON inside `text`; marked here rather than detected in the preview. */
|
|
474
|
+
readonly jsonSpan?: JsonSpan;
|
|
475
|
+
/** Prompt-line insertions that affect only the preview, never this section's estimate. */
|
|
476
|
+
readonly injectedReferences?: readonly InjectedReference[];
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** The payload one tool sends with every request: its name, description, and parameter schema. */
|
|
480
|
+
function createDefinitionSection(tool: ToolSlice): SectionDraft {
|
|
481
|
+
const heading = `${tool.name}: ${tool.description}\n`;
|
|
482
|
+
return {
|
|
483
|
+
label: 'Definition',
|
|
484
|
+
text: `${heading}${tool.parametersJson}`,
|
|
485
|
+
jsonSpan: { start: heading.length, end: heading.length + tool.parametersJson.length },
|
|
486
|
+
};
|
|
132
487
|
}
|
|
133
488
|
|
|
134
|
-
|
|
489
|
+
/**
|
|
490
|
+
* Carve this tool's Available tools snippet and the Guidelines bullets it owns
|
|
491
|
+
* out of the base prompt, so its prompt lines are attributed to the tool that
|
|
492
|
+
* produced them.
|
|
493
|
+
*/
|
|
494
|
+
function carveToolPromptSections(carver: PromptCarver, tool: ToolSlice, ownedGuidelines: string[], owner: InjectedOwner): SectionDraft[] {
|
|
135
495
|
const sections: SectionDraft[] = [];
|
|
136
|
-
const snippet = tool.snippet === undefined ? undefined :
|
|
137
|
-
if (snippet !== undefined)
|
|
496
|
+
const snippet = tool.snippet === undefined ? undefined : carveInjectedLine(carver, carver.toolsBlock, `\n- ${tool.name}: ${tool.snippet}`, owner);
|
|
497
|
+
if (snippet !== undefined) {
|
|
498
|
+
sections.push({ label: AVAILABLE_TOOLS_LABEL, text: carver.base.slice(snippet.start, snippet.end) });
|
|
499
|
+
}
|
|
138
500
|
let bullets = '';
|
|
139
|
-
for (const guideline of ownedGuidelines)
|
|
140
|
-
|
|
501
|
+
for (const guideline of ownedGuidelines) {
|
|
502
|
+
const span = carveInjectedLine(carver, carver.guidelinesBlock, `\n- ${guideline}`, owner);
|
|
503
|
+
if (span === undefined) continue;
|
|
504
|
+
bullets += carver.base.slice(span.start, span.end);
|
|
505
|
+
}
|
|
506
|
+
if (bullets.length > 0) sections.push({ label: GUIDELINES_LABEL, text: bullets });
|
|
141
507
|
return sections;
|
|
142
508
|
}
|
|
143
509
|
|
|
510
|
+
/** Base-prompt regions where pi renders tool prompt lines, plus the carve log to append to. */
|
|
144
511
|
interface PromptCarver {
|
|
145
512
|
readonly base: string;
|
|
146
|
-
|
|
147
|
-
readonly
|
|
513
|
+
/** Bullet lines pi renders under "Available tools:". */
|
|
514
|
+
readonly toolsBlock: CarvedBlock;
|
|
515
|
+
/** Bullet lines pi renders under "Guidelines:". */
|
|
516
|
+
readonly guidelinesBlock: CarvedBlock;
|
|
148
517
|
readonly carvedSpans: Span[];
|
|
518
|
+
readonly injectedSpans: InjectedSpan[];
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** One System Prompt part and the region of it pi renders tool prompt lines into. */
|
|
522
|
+
interface CarvedBlock {
|
|
523
|
+
/** Id of the System Prompt part that keeps these lines as preview references. */
|
|
524
|
+
readonly partId: string;
|
|
525
|
+
readonly span: Span | undefined;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** The tool item that counts a carved prompt line. */
|
|
529
|
+
interface InjectedOwner {
|
|
530
|
+
readonly itemId: string;
|
|
531
|
+
readonly source: InjectionSource;
|
|
532
|
+
/** Tool of `source` that produced the line, rendered as a label qualifier. */
|
|
533
|
+
readonly tool?: string;
|
|
149
534
|
}
|
|
150
535
|
|
|
151
|
-
|
|
536
|
+
/** Original prompt location, owner, and System Prompt part of a carved prompt line. */
|
|
537
|
+
interface InjectedSpan extends Span, InjectedOwner {
|
|
538
|
+
readonly partId: string;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** Locate the two bullet blocks pi renders tool prompt lines into. */
|
|
542
|
+
function createPromptCarver(base: string, carvedSpans: Span[], blocks: readonly LocatedPromptBlock[]): PromptCarver {
|
|
152
543
|
return {
|
|
153
544
|
base,
|
|
154
|
-
toolsBlock:
|
|
155
|
-
|
|
545
|
+
toolsBlock: {
|
|
546
|
+
partId: AVAILABLE_TOOLS_BLOCK.id,
|
|
547
|
+
span: blocks.find(block => block.id === AVAILABLE_TOOLS_BLOCK.id)?.bullets,
|
|
548
|
+
},
|
|
549
|
+
guidelinesBlock: {
|
|
550
|
+
partId: GUIDELINES_BLOCK.id,
|
|
551
|
+
span: blocks.find(block => block.id === GUIDELINES_BLOCK.id)?.bullets,
|
|
552
|
+
},
|
|
156
553
|
carvedSpans,
|
|
554
|
+
injectedSpans: [],
|
|
157
555
|
};
|
|
158
556
|
}
|
|
159
557
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
558
|
+
/**
|
|
559
|
+
* Carve one rendered prompt line out of its block and remember where pi put it,
|
|
560
|
+
* so the part it left keeps it as a preview reference owned by its tool.
|
|
561
|
+
*/
|
|
562
|
+
function carveInjectedLine(carver: PromptCarver, block: CarvedBlock, line: string, owner: InjectedOwner): Span | undefined {
|
|
563
|
+
const span = carveBlockLine(carver, block.span, line);
|
|
564
|
+
if (span !== undefined) carver.injectedSpans.push({ ...span, ...owner, partId: block.partId });
|
|
565
|
+
return span;
|
|
166
566
|
}
|
|
167
567
|
|
|
168
|
-
|
|
568
|
+
/** Record one complete prompt bullet inside its block, never a prefix of another bullet. */
|
|
569
|
+
function carveBlockLine(carver: PromptCarver, block: Span | undefined, line: string): Span | undefined {
|
|
169
570
|
if (block === undefined) return undefined;
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
571
|
+
let start = carver.base.indexOf(line, block.start);
|
|
572
|
+
while (start !== -1 && start + line.length <= block.end) {
|
|
573
|
+
const end = start + line.length;
|
|
574
|
+
if (end === block.end || carver.base[end] === '\n') {
|
|
575
|
+
const span = { start, end };
|
|
576
|
+
carver.carvedSpans.push(span);
|
|
577
|
+
return span;
|
|
578
|
+
}
|
|
579
|
+
start = carver.base.indexOf(line, end);
|
|
580
|
+
}
|
|
581
|
+
return undefined;
|
|
175
582
|
}
|
|
176
583
|
|
|
584
|
+
/**
|
|
585
|
+
* Bullets pi's Guidelines section carries on its own behalf, reserved before
|
|
586
|
+
* any tool can claim one. Pi adds this file-exploration bullet ahead of tool
|
|
587
|
+
* guidelines, so an identical tool bullet is deduplicated away. Pi's two
|
|
588
|
+
* trailing bullets ("Be concise in your responses", "Show file paths clearly
|
|
589
|
+
* when working with files") need no reservation: pi appends them after tool
|
|
590
|
+
* guidelines, where a tool declaring one already owns the rendered line.
|
|
591
|
+
*/
|
|
177
592
|
function piOwnedGuidelines(tools: ToolSlice[]): string[] {
|
|
178
593
|
const names = new Set(tools.map(tool => tool.name));
|
|
179
594
|
const shellOnly = (names.has('bash') || names.has('powershell')) && !names.has('grep') && !names.has('find') && !names.has('ls');
|
|
180
595
|
if (!shellOnly) return [];
|
|
181
|
-
if (names.has('bash') && names.has('powershell'))
|
|
182
|
-
|
|
596
|
+
if (names.has('bash') && names.has('powershell')) {
|
|
597
|
+
return ['Use bash or PowerShell for file operations like listing, searching, and finding files'];
|
|
598
|
+
}
|
|
599
|
+
if (names.has('powershell')) {
|
|
600
|
+
return ['Use PowerShell for file operations like listing, searching, and finding files'];
|
|
601
|
+
}
|
|
183
602
|
return ['Use bash for file operations like ls, rg, find'];
|
|
184
603
|
}
|
|
185
604
|
|
|
605
|
+
/**
|
|
606
|
+
* Guideline texts this tool is the first to declare, in pi's active-tool
|
|
607
|
+
* order. Pi renders each distinct bullet once, so a later tool repeating one
|
|
608
|
+
* contributes no prompt line and must not count its tokens again.
|
|
609
|
+
*/
|
|
186
610
|
function claimGuidelines(tool: ToolSlice, claimed: Set<string>): string[] {
|
|
187
611
|
const owned: string[] = [];
|
|
188
612
|
for (const guideline of tool.guidelines) {
|
|
@@ -194,16 +618,62 @@ function claimGuidelines(tool: ToolSlice, claimed: Set<string>): string[] {
|
|
|
194
618
|
return owned;
|
|
195
619
|
}
|
|
196
620
|
|
|
197
|
-
/**
|
|
621
|
+
/** Retain actual block order, including movements past appended instructions or the CWD footer. */
|
|
622
|
+
function orderPromptParts(
|
|
623
|
+
parts: PromptPart[],
|
|
624
|
+
blocks: readonly LocatedPromptBlock[],
|
|
625
|
+
footer: Span | undefined,
|
|
626
|
+
appendedStart: number | undefined,
|
|
627
|
+
): void {
|
|
628
|
+
const positions = new Map(blocks.map(block => [block.id, block.start]));
|
|
629
|
+
positions.set(PREAMBLE_BLOCK.id, -1);
|
|
630
|
+
if (footer !== undefined) positions.set('base-prompt:current-dir', footer.start);
|
|
631
|
+
if (appendedStart !== undefined) positions.set('base-prompt:appended', appendedStart);
|
|
632
|
+
// Extension Additions consolidates all owners and always closes the preview
|
|
633
|
+
parts.sort((a, b) => (positions.get(a.id) ?? Infinity) - (positions.get(b.id) ?? Infinity));
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** Translate recovered tail coordinates into the local body used for carving and references. */
|
|
637
|
+
function positionBodyBlocks(blocks: readonly LocatedPromptBlock[], baseLength: number): LocatedPromptBlock[] {
|
|
638
|
+
let tailOffset = baseLength;
|
|
639
|
+
return blocks.map(block => {
|
|
640
|
+
if (block.start < baseLength) return block;
|
|
641
|
+
const shift = tailOffset - block.start;
|
|
642
|
+
tailOffset += block.end - block.start;
|
|
643
|
+
return {
|
|
644
|
+
...block,
|
|
645
|
+
start: block.start + shift,
|
|
646
|
+
end: block.end + shift,
|
|
647
|
+
bullets:
|
|
648
|
+
block.bullets === undefined
|
|
649
|
+
? undefined
|
|
650
|
+
: {
|
|
651
|
+
start: block.bullets.start + shift,
|
|
652
|
+
end: block.bullets.end + shift,
|
|
653
|
+
},
|
|
654
|
+
};
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* Carve pi's project-context section and expose each context file as a child of
|
|
660
|
+
* one Instruction Files aggregate, without counting the XML transport scaffolding.
|
|
661
|
+
*/
|
|
198
662
|
function measureContextFiles(base: string, options: PromptOptionsSlice, items: InjectionItem[], carvedSpans: Span[]): void {
|
|
199
663
|
const sectionSpan = findContextSectionSpan(base);
|
|
200
664
|
if (sectionSpan === undefined) return;
|
|
665
|
+
const children: InjectionItem[] = [];
|
|
201
666
|
for (const filePath of options.contextFilePaths ?? []) {
|
|
202
667
|
const content = findContextFileContent(base, filePath);
|
|
203
668
|
if (content === undefined) continue;
|
|
204
|
-
|
|
669
|
+
children.push(createItem(`context-file:${filePath}`, 'context-file', PI_SOURCE, abbreviateHome(filePath, options.homeDir), content));
|
|
205
670
|
}
|
|
671
|
+
children.sort((a, b) => b.tokens - a.tokens);
|
|
206
672
|
carvedSpans.push(expandLineBreaks(base, sectionSpan));
|
|
673
|
+
if (children.length === 0) return;
|
|
674
|
+
|
|
675
|
+
const label = `${INSTRUCTION_FILES_LABEL} (${children.length})`;
|
|
676
|
+
items.push(createAggregateItem('context-files', 'context-file', PI_SOURCE, label, children));
|
|
207
677
|
}
|
|
208
678
|
|
|
209
679
|
/** Carve the skills section and expose each semantic skill record as a child item. */
|
|
@@ -216,21 +686,144 @@ function measureSkills(base: string, options: PromptOptionsSlice, items: Injecti
|
|
|
216
686
|
carvedSpans.push(expandLineBreaks(base, sectionSpan));
|
|
217
687
|
if (children.length === 0) return;
|
|
218
688
|
|
|
219
|
-
items.push(createAggregateItem('skills', 'skills', PI_SOURCE,
|
|
689
|
+
items.push(createAggregateItem('skills', 'skills', PI_SOURCE, `${SKILLS_LABEL} (${children.length})`, children));
|
|
220
690
|
}
|
|
221
691
|
|
|
222
|
-
/**
|
|
223
|
-
|
|
692
|
+
/**
|
|
693
|
+
* Carve the --append-system-prompt text out of the base prompt so it becomes a
|
|
694
|
+
* labeled part of System Prompt instead of free text inside pi's own blocks.
|
|
695
|
+
*/
|
|
696
|
+
function carveAppendedPrompt(base: string, options: PromptOptionsSlice, carvedSpans: Span[]): string | undefined {
|
|
224
697
|
const append = options.appendSystemPrompt;
|
|
225
|
-
if (append === undefined || append.length === 0) return;
|
|
698
|
+
if (append === undefined || append.length === 0) return undefined;
|
|
226
699
|
const generatedStarts = [findContextSectionSpan(base)?.start, findSkillsSpan(base)?.start].filter((start): start is number => start !== undefined);
|
|
227
700
|
const generatedStart = generatedStarts.length === 0 ? base.length : Math.min(...generatedStarts);
|
|
228
701
|
const beforeGeneratedSections = Math.max(0, generatedStart - append.length);
|
|
229
702
|
const expectedStart = base.lastIndexOf(append, beforeGeneratedSections);
|
|
230
703
|
const start = expectedStart === -1 ? base.lastIndexOf(append) : expectedStart;
|
|
231
|
-
if (start === -1) return;
|
|
232
|
-
items.push(createItem('append-prompt', 'append-prompt', PI_SOURCE, 'appended system prompt', append));
|
|
704
|
+
if (start === -1) return undefined;
|
|
233
705
|
carvedSpans.push({ start, end: start + append.length });
|
|
706
|
+
return append;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/** One labeled part of the System Prompt item, before it receives its token share. */
|
|
710
|
+
interface PromptPart {
|
|
711
|
+
readonly id: string;
|
|
712
|
+
readonly kind: InjectionKind;
|
|
713
|
+
readonly label: string;
|
|
714
|
+
readonly text: string;
|
|
715
|
+
/** True for a block a `--system-prompt` replacement dropped: no pi text, no tokens. */
|
|
716
|
+
readonly dropped?: boolean;
|
|
717
|
+
/** True for a block an extension moved out of the region pi rendered it into. */
|
|
718
|
+
readonly moved?: boolean;
|
|
719
|
+
readonly injectedReferences?: readonly InjectedReference[];
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* Restore carved prompt lines as preview-only references in the part each was
|
|
724
|
+
* taken from. Offsets refer to the carved text, so all existing char counts,
|
|
725
|
+
* rounded token shares, and section concatenation remain unchanged.
|
|
726
|
+
*/
|
|
727
|
+
function addInjectedReferences(parts: PromptPart[], base: string, carvedSpans: Span[], injectedSpans: InjectedSpan[]): PromptPart[] {
|
|
728
|
+
if (injectedSpans.length === 0) return parts;
|
|
729
|
+
let offset = 0;
|
|
730
|
+
return parts.map(part => {
|
|
731
|
+
const partStart = offset;
|
|
732
|
+
offset += part.text.length;
|
|
733
|
+
const spans = injectedSpans.filter(span => span.partId === part.id);
|
|
734
|
+
if (spans.length === 0) return part;
|
|
735
|
+
return {
|
|
736
|
+
...part,
|
|
737
|
+
injectedReferences: spans
|
|
738
|
+
.sort((a, b) => a.start - b.start)
|
|
739
|
+
.map(span => ({
|
|
740
|
+
offset: carve(base.slice(0, span.start), carvedSpans).length - partStart,
|
|
741
|
+
text: base.slice(span.start, span.end),
|
|
742
|
+
itemId: span.itemId,
|
|
743
|
+
source: span.source,
|
|
744
|
+
tool: span.tool,
|
|
745
|
+
})),
|
|
746
|
+
};
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* Split pi's own prompt at the block headers it renders deterministically, so
|
|
752
|
+
* the tool list, guidelines, and documentation it already carries become
|
|
753
|
+
* visible parts. Headers are located independently and cut in the order they
|
|
754
|
+
* occur, because a relocated block appears after the ones pi wrote later. Text
|
|
755
|
+
* before the first header opens the list as the preamble.
|
|
756
|
+
*/
|
|
757
|
+
function splitBasePromptParts(base: string, cuts: readonly LocatedPromptBlock[]): PromptPart[] {
|
|
758
|
+
const parts: PromptPart[] = [];
|
|
759
|
+
let block: Pick<PromptPart, 'id' | 'label' | 'moved'> = PREAMBLE_BLOCK;
|
|
760
|
+
let start = 0;
|
|
761
|
+
for (const cut of cuts) {
|
|
762
|
+
appendPromptPart(parts, block, base.slice(start, cut.start));
|
|
763
|
+
block = cut;
|
|
764
|
+
start = cut.start;
|
|
765
|
+
}
|
|
766
|
+
appendPromptPart(parts, block, base.slice(start));
|
|
767
|
+
return parts;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* Parts of a replaced prompt: the replacement text itself, then every block pi
|
|
772
|
+
* would have assembled, kept visible as dropped so the view shows what the
|
|
773
|
+
* replacement gave up. A dropped block carries no pi-authored text — only the
|
|
774
|
+
* extension lines pi never rendered, as preview-only references.
|
|
775
|
+
*/
|
|
776
|
+
function droppedBasePromptParts(base: string, dropped: Map<string, InjectedReference[]>): PromptPart[] {
|
|
777
|
+
const parts: PromptPart[] = [];
|
|
778
|
+
appendPromptPart(parts, PREAMBLE_BLOCK, base);
|
|
779
|
+
for (const block of BASE_PROMPT_BLOCKS) {
|
|
780
|
+
parts.push({
|
|
781
|
+
id: block.id,
|
|
782
|
+
kind: 'base-prompt',
|
|
783
|
+
label: block.label,
|
|
784
|
+
text: '',
|
|
785
|
+
dropped: true,
|
|
786
|
+
injectedReferences: dropped.get(block.id),
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
return parts;
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/** Record one pi-authored part, skipping a block pi rendered no text into. */
|
|
793
|
+
function appendPromptPart(parts: PromptPart[], block: Pick<PromptPart, 'id' | 'label' | 'moved'>, text: string): void {
|
|
794
|
+
if (text.length === 0) return;
|
|
795
|
+
parts.push({ id: block.id, kind: 'base-prompt', label: block.label, text, moved: block.moved });
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* Build the System Prompt item from its labeled parts. Parts concatenate back to
|
|
800
|
+
* the item text and take cumulative shares of its estimate, so children break the
|
|
801
|
+
* item down without adding tokens. A prompt with one part stays undivided.
|
|
802
|
+
*/
|
|
803
|
+
function createSystemPromptItem(parts: readonly PromptPart[]): InjectionItem {
|
|
804
|
+
const text = countedText(parts);
|
|
805
|
+
const item = createItem('base-prompt', 'base-prompt', PI_SOURCE, SYSTEM_PROMPT_LABEL, text);
|
|
806
|
+
if (parts.length === 0 || (parts.length === 1 && parts[0]?.id === PREAMBLE_BLOCK.id)) return item;
|
|
807
|
+
const sections = allocateSectionTokens(
|
|
808
|
+
parts.map(part => ({
|
|
809
|
+
label: part.label,
|
|
810
|
+
text: part.text,
|
|
811
|
+
dropped: part.dropped,
|
|
812
|
+
moved: part.moved,
|
|
813
|
+
injectedReferences: part.injectedReferences,
|
|
814
|
+
})),
|
|
815
|
+
);
|
|
816
|
+
return {
|
|
817
|
+
...item,
|
|
818
|
+
sections,
|
|
819
|
+
children: parts.map((part, index) => ({
|
|
820
|
+
...createItem(part.id, part.kind, PI_SOURCE, part.label, part.text),
|
|
821
|
+
tokens: sections[index]?.tokens ?? 0,
|
|
822
|
+
dropped: part.dropped,
|
|
823
|
+
moved: part.moved,
|
|
824
|
+
injectedReferences: part.injectedReferences,
|
|
825
|
+
})),
|
|
826
|
+
};
|
|
234
827
|
}
|
|
235
828
|
|
|
236
829
|
/** Build an initial-phase InjectionItem with derived char/token sizes. */
|
|
@@ -247,17 +840,31 @@ function createItem(id: string, kind: InjectionKind, source: InjectionSource, la
|
|
|
247
840
|
};
|
|
248
841
|
}
|
|
249
842
|
|
|
250
|
-
/** Build a tool item whose text is exactly the concatenation of its sections. */
|
|
843
|
+
/** Build a tool item whose raw text is exactly the concatenation of its sections. */
|
|
251
844
|
function createToolItem(id: string, source: InjectionSource, label: string, sections: SectionDraft[]): InjectionItem {
|
|
252
|
-
const text = sections
|
|
845
|
+
const text = countedText(sections);
|
|
253
846
|
return { ...createItem(id, 'tool', source, label, text), sections: allocateSectionTokens(sections) };
|
|
254
847
|
}
|
|
255
848
|
|
|
256
|
-
/**
|
|
849
|
+
/** Text an item actually sends: everything but the parts a prompt replacement dropped. */
|
|
850
|
+
function countedText(parts: readonly { readonly text: string; readonly dropped?: boolean }[]): string {
|
|
851
|
+
return parts
|
|
852
|
+
.filter(part => part.dropped !== true)
|
|
853
|
+
.map(part => part.text)
|
|
854
|
+
.join('');
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
/**
|
|
858
|
+
* Give each section its share of the item estimate. Shares are cumulative
|
|
859
|
+
* differences rather than independently rounded counts, so they always sum to
|
|
860
|
+
* the item total. A dropped section reads 0 tokens and leaves the shares of
|
|
861
|
+
* the sections pi did send unchanged.
|
|
862
|
+
*/
|
|
257
863
|
function allocateSectionTokens(sections: SectionDraft[]): InjectionSection[] {
|
|
258
864
|
let chars = 0;
|
|
259
865
|
let allocated = 0;
|
|
260
866
|
return sections.map(section => {
|
|
867
|
+
if (section.dropped === true) return { ...section, tokens: 0 };
|
|
261
868
|
chars += section.text.length;
|
|
262
869
|
const cumulative = charTokens(chars);
|
|
263
870
|
const tokens = cumulative - allocated;
|
|
@@ -266,19 +873,47 @@ function allocateSectionTokens(sections: SectionDraft[]): InjectionSection[] {
|
|
|
266
873
|
});
|
|
267
874
|
}
|
|
268
875
|
|
|
269
|
-
/**
|
|
876
|
+
/** Line break joining consecutive child texts inside an aggregate's raw text. */
|
|
877
|
+
const CHILD_SEPARATOR = '\n';
|
|
878
|
+
|
|
879
|
+
/**
|
|
880
|
+
* Build an aggregate whose totals exactly reconcile with its child items and
|
|
881
|
+
* whose preview presents every child as its own labeled part, so each child
|
|
882
|
+
* keeps its subheader, token share, and marked JSON run.
|
|
883
|
+
*/
|
|
270
884
|
function createAggregateItem(id: string, kind: InjectionKind, source: InjectionSource, label: string, children: InjectionItem[]): InjectionItem {
|
|
271
885
|
return {
|
|
272
|
-
...createItem(id, kind, source, label, children.map(child => child.text).join(
|
|
886
|
+
...createItem(id, kind, source, label, children.map(child => child.text).join(CHILD_SEPARATOR)),
|
|
273
887
|
chars: children.reduce((sum, child) => sum + child.chars, 0),
|
|
274
888
|
tokens: children.reduce((sum, child) => sum + child.tokens, 0),
|
|
889
|
+
sections: children.map((child, index) => childSection(child, index === 0 ? '' : CHILD_SEPARATOR)),
|
|
275
890
|
children,
|
|
276
891
|
};
|
|
277
892
|
}
|
|
278
893
|
|
|
279
|
-
/**
|
|
280
|
-
|
|
281
|
-
|
|
894
|
+
/**
|
|
895
|
+
* One child as a labeled part of its aggregate, opening with the separator the
|
|
896
|
+
* aggregate text joins on; the preview drops that separator again.
|
|
897
|
+
*/
|
|
898
|
+
function childSection(child: InjectionItem, separator: string): InjectionSection {
|
|
899
|
+
const span = childJsonSpan(child);
|
|
900
|
+
return {
|
|
901
|
+
label: child.label,
|
|
902
|
+
text: `${separator}${child.text}`,
|
|
903
|
+
tokens: child.tokens,
|
|
904
|
+
jsonSpan: span === undefined ? undefined : { start: span.start + separator.length, end: span.end + separator.length },
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/**
|
|
909
|
+
* The JSON run marked inside a child's whole text: its own span, or the span of
|
|
910
|
+
* its single part. A child split into several parts marks each part separately,
|
|
911
|
+
* so no one run covers its text and the aggregate part expands nothing.
|
|
912
|
+
*/
|
|
913
|
+
function childJsonSpan(child: InjectionItem): JsonSpan | undefined {
|
|
914
|
+
const sections = child.sections;
|
|
915
|
+
if (sections === undefined) return child.jsonSpan;
|
|
916
|
+
return sections.length === 1 ? sections[0]?.jsonSpan : undefined;
|
|
282
917
|
}
|
|
283
918
|
|
|
284
919
|
/** Replace a leading home-directory prefix with `~` for compact path labels. */
|
|
@@ -308,7 +943,7 @@ interface Span {
|
|
|
308
943
|
}
|
|
309
944
|
|
|
310
945
|
/**
|
|
311
|
-
* Locate pi's dynamic CWD footer so it can be excluded from
|
|
946
|
+
* Locate pi's dynamic CWD footer so it can be excluded from System Prompt and
|
|
312
947
|
* extension additions. Pi 0.81 emits only the "Current working directory"
|
|
313
948
|
* line; pi 0.80 preceded it with a "Current date" line, still recognized for
|
|
314
949
|
* compatibility. The CWD line must match the exact resolved cwd on a complete
|