@0xkahi/pi-qol 0.1.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +13 -0
  2. package/assets/config.schema.json +12 -0
  3. package/package.json +4 -4
  4. package/src/codemap.md +26 -16
  5. package/src/config-loader.ts +4 -0
  6. package/src/constants.ts +1 -0
  7. package/src/extensions/auto-session-name/codemap.md +17 -12
  8. package/src/extensions/auto-session-name/title-generator.ts +1 -1
  9. package/src/extensions/codemap.md +173 -13
  10. package/src/extensions/context-view/capture.ts +394 -0
  11. package/src/extensions/context-view/codemap.md +213 -0
  12. package/src/extensions/context-view/constants.ts +4 -0
  13. package/src/extensions/context-view/context-view-controller.ts +67 -0
  14. package/src/extensions/context-view/index.ts +120 -0
  15. package/src/extensions/context-view/measure.ts +307 -0
  16. package/src/extensions/context-view/model.ts +207 -0
  17. package/src/extensions/context-view/ui/codemap.md +82 -0
  18. package/src/extensions/context-view/ui/context-view-dialog.ts +59 -0
  19. package/src/extensions/context-view/ui/injections-model.ts +118 -0
  20. package/src/extensions/context-view/ui/injections-view.ts +264 -0
  21. package/src/extensions/context-view/ui/skill-preview.ts +82 -0
  22. package/src/extensions/context-view/ui/usage-map.ts +133 -0
  23. package/src/extensions/context-view/ui/usage-view.ts +613 -0
  24. package/src/extensions/context-view/usage.ts +432 -0
  25. package/src/extensions/model-select/codemap.md +34 -17
  26. package/src/extensions/model-select/model-select-dialog.ts +85 -324
  27. package/src/index.ts +2 -0
  28. package/src/libs/codemap.md +8 -1
  29. package/src/libs/modal/README.md +212 -0
  30. package/src/libs/modal/codemap.md +34 -0
  31. package/src/libs/modal/index.ts +29 -0
  32. package/src/libs/modal/list-navigator.ts +167 -0
  33. package/src/libs/modal/modal-dialog.ts +297 -0
  34. package/src/libs/modal/navigation/pi-scheme.ts +33 -0
  35. package/src/libs/modal/navigation/vim-scheme.ts +56 -0
  36. package/src/libs/modal/preview-layer.ts +87 -0
  37. package/src/libs/modal/render-cache.ts +33 -0
  38. package/src/libs/modal/tab-strip.ts +87 -0
  39. package/src/libs/modal/tabs/list-tab.ts +159 -0
  40. package/src/libs/modal/text.ts +88 -0
  41. package/src/libs/modal/types.ts +70 -0
  42. package/src/schemas/codemap.md +100 -18
  43. package/src/schemas/config.schema.ts +3 -0
  44. package/src/schemas/context-view.config.schema.ts +13 -0
@@ -0,0 +1,67 @@
1
+ import { buildSessionContext, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+ import { buildNativeSnapshot, type InitialCaptureState, mergeContextOnlyMessages, type SilentProbeState } from './capture';
3
+ import type { ContextUsageSnapshot, InitialSnapshot } from './model';
4
+ import { computeUsage, toReportedUsage } from './usage';
5
+
6
+ export interface ContextViewData {
7
+ initial: InitialSnapshot;
8
+ usage: ContextUsageSnapshot;
9
+ degradedReason?: string;
10
+ }
11
+
12
+ type PromptContext = ExtensionContext & {
13
+ getSystemPromptOptions?: () => Parameters<typeof buildNativeSnapshot>[0]['options'];
14
+ waitForIdle?: () => Promise<void>;
15
+ };
16
+
17
+ /** Prepare Context View data without requiring command-only APIs for event callers. */
18
+ export async function prepareContextViewData(
19
+ pi: ExtensionAPI,
20
+ ctx: PromptContext,
21
+ capture: InitialCaptureState,
22
+ probe: SilentProbeState,
23
+ ): Promise<ContextViewData> {
24
+ if (ctx.waitForIdle) await ctx.waitForIdle();
25
+ let initial = capture.snapshot;
26
+ let degradedReason: string | undefined;
27
+
28
+ if (!initial) {
29
+ const attempt = probe.start();
30
+ if (attempt.started && ctx.model && ctx.modelRegistry.hasConfiguredAuth(ctx.model)) {
31
+ try {
32
+ pi.sendUserMessage('');
33
+ } catch (error) {
34
+ probe.fail(error instanceof Error ? error.message : String(error));
35
+ }
36
+ } else if (attempt.started) {
37
+ probe.fail('Silent probe unavailable: no authenticated model is selected.');
38
+ }
39
+ const outcome = await attempt.completion;
40
+ initial = capture.snapshot;
41
+ if (!initial)
42
+ degradedReason = `${outcome.status === 'failed' ? outcome.reason : 'Silent probe did not capture Initial.'} Extension additions were not observed.`;
43
+ }
44
+
45
+ const options = capture.promptOptions ?? ctx.getSystemPromptOptions?.();
46
+ if (!options) {
47
+ throw new Error('Context View has not received prompt options yet. Start an agent turn and try again.');
48
+ }
49
+ const current = buildNativeSnapshot({
50
+ systemPrompt: ctx.getSystemPrompt(),
51
+ options,
52
+ allTools: pi.getAllTools(),
53
+ activeToolNames: pi.getActiveTools(),
54
+ });
55
+ const fallback = initial ?? current;
56
+ const messages = probe.filterMessages(buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId()).messages);
57
+ return {
58
+ initial: fallback,
59
+ degradedReason,
60
+ usage: computeUsage({
61
+ snapshot: mergeContextOnlyMessages(current, fallback),
62
+ messages,
63
+ reported: toReportedUsage(ctx.getContextUsage()),
64
+ modelLabel: ctx.model?.id,
65
+ }),
66
+ };
67
+ }
@@ -0,0 +1,120 @@
1
+ import { buildSessionContext, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+ import type { ConfigLoader } from '../../config-loader';
3
+ import { InitialCaptureState, PROBE_IDENTITIES_CUSTOM_TYPE, parsePersistedIdentities, SilentProbeState } from './capture';
4
+ import { COMMAND_NAME, PI_VIM_KEY_EVENT_ID } from './constants';
5
+ import { prepareContextViewData } from './context-view-controller';
6
+ import { ContextViewDialog } from './ui/context-view-dialog';
7
+
8
+ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; initialCtx: ExtensionContext }): void {
9
+ const capture = new InitialCaptureState();
10
+ const probe = new SilentProbeState();
11
+ let persistedIdentityCount = 0;
12
+ let latestCtx: ExtensionContext = deps.initialCtx;
13
+ const enabled = () => deps.config.isEnabled('context_view');
14
+
15
+ const restoreProbeIdentities = (ctx: ExtensionContext) => {
16
+ for (const entry of ctx.sessionManager.getEntries()) {
17
+ if (entry.type === 'custom' && entry.customType === PROBE_IDENTITIES_CUSTOM_TYPE) {
18
+ probe.restoreIdentities(parsePersistedIdentities(entry.data));
19
+ }
20
+ }
21
+ persistedIdentityCount = probe.syntheticMessages.length;
22
+ };
23
+ const persistProbeIdentities = () => {
24
+ const identities = probe.syntheticMessages;
25
+ if (identities.length <= persistedIdentityCount) return;
26
+ pi.appendEntry(PROBE_IDENTITIES_CUSTOM_TYPE, { messages: identities });
27
+ persistedIdentityCount = identities.length;
28
+ };
29
+ const openContextView = async (ctx: ExtensionContext) => {
30
+ const data = await prepareContextViewData(pi, ctx, capture, probe);
31
+ await ctx.ui.custom<void>((tui, theme, keybindings, done) => new ContextViewDialog(tui, theme, keybindings, data, done));
32
+ };
33
+
34
+ restoreProbeIdentities(deps.initialCtx);
35
+ pi.on('session_start', (_event, ctx) => {
36
+ latestCtx = ctx;
37
+ if (enabled()) restoreProbeIdentities(ctx);
38
+ });
39
+ pi.on('input', event => {
40
+ if (enabled()) probe.observeInput(event.source, event.text);
41
+ });
42
+ pi.on('before_agent_start', event => {
43
+ if (!enabled()) return;
44
+ probe.beginRun(event.prompt);
45
+ capture.prepare(event.systemPromptOptions);
46
+ });
47
+ pi.on('turn_start', (_event, ctx) => {
48
+ if (enabled() && probe.isCurrentRun) ctx.abort();
49
+ });
50
+ pi.on('message_start', event => {
51
+ if (enabled()) probe.recordMessage(event.message);
52
+ });
53
+ pi.on('message_end', event => {
54
+ if (!enabled()) return;
55
+ const message = probe.sanitizeAssistant(event.message);
56
+ return message === undefined ? undefined : { message };
57
+ });
58
+ pi.on('context', (event, ctx) => {
59
+ if (!enabled()) return;
60
+ const messages = probe.filterMessages(event.messages);
61
+ const baselineMessages = probe.filterMessages(buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId()).messages);
62
+ capture.finalize({
63
+ systemPrompt: ctx.getSystemPrompt(),
64
+ messages,
65
+ baselineMessages,
66
+ allTools: pi.getAllTools(),
67
+ activeToolNames: pi.getActiveTools(),
68
+ origin: probe.isCurrentRun ? 'synthetic-probe' : 'real-turn',
69
+ });
70
+ return messages === event.messages ? undefined : { messages };
71
+ });
72
+ pi.on('agent_settled', (_event, ctx) => {
73
+ if (!enabled() || !probe.isCurrentRun) return;
74
+ if (ctx.mode === 'tui') ctx.ui.setWorkingVisible(true);
75
+ probe.settle(capture.snapshot !== undefined);
76
+ persistProbeIdentities();
77
+ });
78
+ pi.on('session_shutdown', () => {
79
+ if (!enabled()) return;
80
+ persistProbeIdentities();
81
+ probe.fail('Session ended before the silent probe completed.');
82
+ });
83
+
84
+ pi.registerCommand(COMMAND_NAME, {
85
+ description: 'Inspect model context usage and injections',
86
+ handler: async (args, ctx) => {
87
+ latestCtx = ctx;
88
+ if (!enabled()) {
89
+ ctx.ui.notify('(pi-qol) context_view is disabled', 'warning');
90
+ return;
91
+ }
92
+ if (args.trim()) {
93
+ ctx.ui.notify('/context-view accepts no arguments.', 'error');
94
+ return;
95
+ }
96
+ if (ctx.mode !== 'tui') {
97
+ ctx.ui.notify('/context-view requires TUI mode.', 'warning');
98
+ return;
99
+ }
100
+ await openContextView(ctx);
101
+ },
102
+ });
103
+
104
+ pi.events.on(PI_VIM_KEY_EVENT_ID, () => {
105
+ if (!enabled() || latestCtx.mode !== 'tui') return;
106
+ void openContextView(latestCtx).catch(error => {
107
+ latestCtx.ui.notify(`Failed to open Context View: ${error instanceof Error ? error.message : String(error)}`, 'error');
108
+ });
109
+ });
110
+ }
111
+
112
+ /** Lazily registers Context View only after an enabled session starts. */
113
+ export function registerContextView(pi: ExtensionAPI, deps: { config: ConfigLoader }): void {
114
+ let registered = false;
115
+ pi.on('session_start', (_event, ctx) => {
116
+ if (registered || !deps.config.isEnabled('context_view')) return;
117
+ activateContextView(pi, { config: deps.config, initialCtx: ctx });
118
+ registered = true;
119
+ });
120
+ }
@@ -0,0 +1,307 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Pure measurement logic: split a captured system prompt into semantic items
4
+ * and estimate token sizes. No pi API access — unit-testable.
5
+ *
6
+ * Splitting relies on structural markers that pi's buildSystemPrompt() emits
7
+ * deterministically (verified against pi 0.81.1 dist/core/system-prompt.js):
8
+ *
9
+ * - context files: <project_instructions path="...">...</project_instructions>
10
+ * - skills block: "The following skills provide..." through </available_skills>
11
+ * - base prompt ends before the "Current working directory" footer (pi 0.81),
12
+ * optionally preceded by a "Current date" line (pi 0.80)
13
+ * → anything after that footer was appended by before_agent_start handlers.
14
+ */
15
+ import { AGGREGATE_SOURCE_ID, type InjectionItem, type InjectionKind, type InjectionSource, PI_SOURCE_ID } from './model';
16
+
17
+ const PI_SOURCE: InjectionSource = { id: PI_SOURCE_ID, label: 'pi', native: true };
18
+ const AGGREGATE_SOURCE: InjectionSource = {
19
+ id: AGGREGATE_SOURCE_ID,
20
+ label: 'extensions (aggregate)',
21
+ native: false,
22
+ };
23
+
24
+ /** One visible skill before pi adds XML transport framing. */
25
+ export interface SkillSlice {
26
+ name: string;
27
+ description: string;
28
+ filePath: string;
29
+ }
30
+
31
+ /** Minimal slice of BuildSystemPromptOptions that measurement needs. */
32
+ export interface PromptOptionsSlice {
33
+ cwd: string;
34
+ /** Home directory used to abbreviate context-file paths; omitted disables it. */
35
+ homeDir?: string;
36
+ customPrompt?: string;
37
+ appendSystemPrompt?: string;
38
+ contextFilePaths?: string[];
39
+ skills?: SkillSlice[];
40
+ }
41
+
42
+ /** One active tool as it contributes to the initial context. */
43
+ export interface ToolSlice {
44
+ name: string;
45
+ /** Sent to the provider with every request. */
46
+ description: string;
47
+ /** JSON-serialized parameter schema; sent to the provider with every request. */
48
+ parametersJson: string;
49
+ /** One-line snippet rendered into the prompt's Available tools list. */
50
+ snippet?: string;
51
+ /** Guideline bullets rendered into the prompt's Guidelines section. */
52
+ guidelines: string[];
53
+ /** Provenance, e.g. "builtin" or "npm:pi-web-providers". */
54
+ source: string;
55
+ }
56
+
57
+ /**
58
+ * Split a captured system prompt into semantic items: pi base prompt,
59
+ * appended prompt, context files, skills, active tool contributions, and the
60
+ * aggregate appended by extensions.
61
+ */
62
+ export function analyzeSystemPrompt(systemPrompt: string, options: PromptOptionsSlice, tools: ToolSlice[] = []): InjectionItem[] {
63
+ const items: InjectionItem[] = [];
64
+ const carvedSpans: Span[] = [];
65
+
66
+ const footer = findBasePromptFooter(systemPrompt, options.cwd);
67
+ const base = footer === undefined ? systemPrompt : systemPrompt.slice(0, footer.start);
68
+
69
+ const usesCustomPrompt = options.customPrompt !== undefined && options.customPrompt.length > 0;
70
+ measureTools(usesCustomPrompt ? '' : base, tools, items, carvedSpans);
71
+ measureContextFiles(base, options, items, carvedSpans);
72
+ measureSkills(base, options, items, carvedSpans);
73
+ measureAppendedPrompt(base, options, items, carvedSpans);
74
+
75
+ const baseLabel = usesCustomPrompt ? 'Custom Prompt (--system-prompt)' : 'Base Prompt';
76
+ items.unshift(createItem('base-prompt', 'base-prompt', PI_SOURCE, baseLabel, carve(base, carvedSpans)));
77
+
78
+ if (footer !== undefined && footer.end < systemPrompt.length) {
79
+ const added = systemPrompt.slice(footer.end);
80
+ if (added.trim().length > 0) {
81
+ items.push(createItem('prompt-addition:aggregate', 'prompt-addition', AGGREGATE_SOURCE, 'system prompt additions', added));
82
+ }
83
+ }
84
+
85
+ return items;
86
+ }
87
+
88
+ /** Same chars/4 heuristic pi's estimateTokens uses for text content. */
89
+ export function textTokens(text: string): number {
90
+ return Math.ceil(text.length / 4);
91
+ }
92
+
93
+ /**
94
+ * Measure active tool contributions: per-tool definition payloads plus the
95
+ * prompt snippet/guideline lines carved out of the base prompt. Built-in
96
+ * tools collapse into one aggregate pi-native item.
97
+ */
98
+ function measureTools(base: string, tools: ToolSlice[], items: InjectionItem[], carvedSpans: Span[]): void {
99
+ const builtinChildren: InjectionItem[] = [];
100
+ for (const tool of tools) {
101
+ const definition = `${tool.name}: ${tool.description}\n${tool.parametersJson}`;
102
+ if (tool.source === 'builtin') {
103
+ builtinChildren.push(createItem(`tool:builtin:${tool.name}`, 'tool', PI_SOURCE, tool.name, definition));
104
+ continue;
105
+ }
106
+ let promptText = '';
107
+ if (tool.snippet !== undefined) {
108
+ const span = findExactSpan(base, `\n- ${tool.name}: ${tool.snippet}`);
109
+ if (span !== undefined) {
110
+ promptText += base.slice(span.start, span.end);
111
+ carvedSpans.push(span);
112
+ }
113
+ }
114
+ for (const guideline of tool.guidelines) {
115
+ const span = findExactSpan(base, `\n- ${guideline.trim()}`);
116
+ if (span !== undefined) {
117
+ promptText += base.slice(span.start, span.end);
118
+ carvedSpans.push(span);
119
+ }
120
+ }
121
+ const source = extensionSource(tool.source);
122
+ items.push(createItem(`tool:${tool.source}:${tool.name}`, 'tool', source, tool.name, promptText + definition));
123
+ }
124
+ if (builtinChildren.length > 0) {
125
+ builtinChildren.sort((a, b) => b.tokens - a.tokens);
126
+ const label = `Built-in Tools (${builtinChildren.length})`;
127
+ const text = builtinChildren.map(child => child.text).join('\n');
128
+ items.push({
129
+ ...createItem('tool:builtin', 'tool', PI_SOURCE, label, text),
130
+ chars: builtinChildren.reduce((sum, child) => sum + child.chars, 0),
131
+ tokens: builtinChildren.reduce((sum, child) => sum + child.tokens, 0),
132
+ children: builtinChildren,
133
+ });
134
+ }
135
+ }
136
+
137
+ /** Measure context-file contents without counting pi's XML transport scaffolding. */
138
+ function measureContextFiles(base: string, options: PromptOptionsSlice, items: InjectionItem[], carvedSpans: Span[]): void {
139
+ const sectionSpan = findContextSectionSpan(base);
140
+ if (sectionSpan === undefined) return;
141
+ for (const filePath of options.contextFilePaths ?? []) {
142
+ const content = findContextFileContent(base, filePath);
143
+ if (content === undefined) continue;
144
+ items.push(createItem(`context-file:${filePath}`, 'context-file', PI_SOURCE, abbreviateHome(filePath, options.homeDir), content));
145
+ }
146
+ carvedSpans.push(expandLineBreaks(base, sectionSpan));
147
+ }
148
+
149
+ /** Carve the skills section and expose each semantic skill record as a child item. */
150
+ function measureSkills(base: string, options: PromptOptionsSlice, items: InjectionItem[], carvedSpans: Span[]): void {
151
+ const sectionSpan = findSkillsSpan(base);
152
+ if (sectionSpan === undefined) return;
153
+ const children = (options.skills ?? [])
154
+ .map(skill => createItem(`skill:${skill.name}`, 'skills', PI_SOURCE, skill.name, [skill.name, skill.description, skill.filePath].join('\n')))
155
+ .sort((a, b) => b.tokens - a.tokens);
156
+ carvedSpans.push(expandLineBreaks(base, sectionSpan));
157
+ if (children.length === 0) return;
158
+
159
+ items.push(createAggregateItem('skills', 'skills', PI_SOURCE, `Skills (${children.length})`, children));
160
+ }
161
+
162
+ /** Carve the --append-system-prompt text out of the base prompt when present. */
163
+ function measureAppendedPrompt(base: string, options: PromptOptionsSlice, items: InjectionItem[], carvedSpans: Span[]): void {
164
+ const append = options.appendSystemPrompt;
165
+ if (append === undefined || append.length === 0) return;
166
+ const generatedStarts = [findContextSectionSpan(base)?.start, findSkillsSpan(base)?.start].filter((start): start is number => start !== undefined);
167
+ const generatedStart = generatedStarts.length === 0 ? base.length : Math.min(...generatedStarts);
168
+ const beforeGeneratedSections = Math.max(0, generatedStart - append.length);
169
+ const expectedStart = base.lastIndexOf(append, beforeGeneratedSections);
170
+ const start = expectedStart === -1 ? base.lastIndexOf(append) : expectedStart;
171
+ if (start === -1) return;
172
+ items.push(createItem('append-prompt', 'append-prompt', PI_SOURCE, 'appended system prompt', append));
173
+ carvedSpans.push({ start, end: start + append.length });
174
+ }
175
+
176
+ /** Build an initial-phase InjectionItem with derived char/token sizes. */
177
+ function createItem(id: string, kind: InjectionKind, source: InjectionSource, label: string, text: string): InjectionItem {
178
+ return {
179
+ id,
180
+ phase: 'initial',
181
+ kind,
182
+ source,
183
+ label,
184
+ chars: text.length,
185
+ tokens: textTokens(text),
186
+ text,
187
+ };
188
+ }
189
+
190
+ /** Build an aggregate whose totals exactly reconcile with its child items. */
191
+ function createAggregateItem(id: string, kind: InjectionKind, source: InjectionSource, label: string, children: InjectionItem[]): InjectionItem {
192
+ return {
193
+ ...createItem(id, kind, source, label, children.map(child => child.text).join('\n')),
194
+ chars: children.reduce((sum, child) => sum + child.chars, 0),
195
+ tokens: children.reduce((sum, child) => sum + child.tokens, 0),
196
+ children,
197
+ };
198
+ }
199
+
200
+ /** Injection source for a non-builtin tool provenance string. */
201
+ function extensionSource(source: string): InjectionSource {
202
+ return { id: `tool-source:${source}`, label: source, native: false };
203
+ }
204
+
205
+ /** Replace a leading home-directory prefix with `~` for compact path labels. */
206
+ function abbreviateHome(path: string, homeDir: string | undefined): string {
207
+ if (homeDir === undefined || homeDir.length === 0) return path;
208
+ if (path === homeDir) return '~';
209
+ if (path.startsWith(`${homeDir}/`)) return `~${path.slice(homeDir.length)}`;
210
+ return path;
211
+ }
212
+
213
+ /** Remove the given spans from text, tolerating overlaps, and return the remainder. */
214
+ function carve(text: string, spans: Span[]): string {
215
+ spans.sort((a, b) => a.start - b.start);
216
+ let remainder = '';
217
+ let cursor = 0;
218
+ for (const span of spans) {
219
+ if (span.start > cursor) remainder += text.slice(cursor, span.start);
220
+ cursor = Math.max(cursor, span.end);
221
+ }
222
+ return remainder + text.slice(cursor);
223
+ }
224
+
225
+ /** Half-open [start, end) character range within the base prompt. */
226
+ interface Span {
227
+ start: number;
228
+ end: number;
229
+ }
230
+
231
+ /**
232
+ * Locate pi's dynamic CWD footer so it can be excluded from Base Prompt and
233
+ * extension additions. Pi 0.81 emits only the "Current working directory"
234
+ * line; pi 0.80 preceded it with a "Current date" line, still recognized for
235
+ * compatibility. The CWD line must match the exact resolved cwd on a complete
236
+ * line (preceded by "\n", followed by "\n" or end of prompt) so ordinary
237
+ * prompt text mentioning the cwd is not mistaken for the footer.
238
+ */
239
+ function findBasePromptFooter(systemPrompt: string, cwd: string): Span | undefined {
240
+ const promptCwd = cwd.replace(/\\/g, '/');
241
+ const cwdLine = `\nCurrent working directory: ${promptCwd}`;
242
+ let cwdStart = systemPrompt.lastIndexOf(cwdLine);
243
+ while (cwdStart !== -1) {
244
+ const end = cwdStart + cwdLine.length;
245
+ if (end === systemPrompt.length || systemPrompt[end] === '\n') {
246
+ const dateStart = systemPrompt.lastIndexOf('\nCurrent date: ', cwdStart);
247
+ const dateLine = dateStart === -1 ? '' : systemPrompt.slice(dateStart, cwdStart);
248
+ const start = /^\nCurrent date: \d{4}-\d{2}-\d{2}$/.test(dateLine) ? dateStart : cwdStart;
249
+ return { start, end };
250
+ }
251
+ cwdStart = systemPrompt.lastIndexOf(cwdLine, cwdStart - 1);
252
+ }
253
+ return undefined;
254
+ }
255
+
256
+ /** Span of the first exact occurrence of needle, or undefined. */
257
+ function findExactSpan(haystack: string, needle: string): Span | undefined {
258
+ const start = haystack.indexOf(needle);
259
+ return start === -1 ? undefined : { start, end: start + needle.length };
260
+ }
261
+
262
+ /** Span of pi's complete project-context transport section. */
263
+ function findContextSectionSpan(systemPrompt: string): Span | undefined {
264
+ return findDelimitedSpan(systemPrompt, '<project_context>', '</project_context>');
265
+ }
266
+
267
+ /** Extract one context file's final content without its project-instructions wrapper. */
268
+ function findContextFileContent(systemPrompt: string, filePath: string): string | undefined {
269
+ const open = `<project_instructions path="${filePath}">`;
270
+ const close = '</project_instructions>';
271
+ const wrapper = findDelimitedSpan(systemPrompt, open, close);
272
+ if (wrapper === undefined) return undefined;
273
+ let start = wrapper.start + open.length;
274
+ let end = wrapper.end - close.length;
275
+ if (systemPrompt.startsWith('\r\n', start)) start += 2;
276
+ else if (systemPrompt[start] === '\n') start++;
277
+ if (systemPrompt.slice(Math.max(start, end - 2), end) === '\r\n') end -= 2;
278
+ else if (systemPrompt[end - 1] === '\n') end--;
279
+ return systemPrompt.slice(start, end);
280
+ }
281
+
282
+ /** Span of the skills intro sentence through </available_skills>. */
283
+ function findSkillsSpan(systemPrompt: string): Span | undefined {
284
+ const open = 'The following skills provide specialized instructions';
285
+ const close = '</available_skills>';
286
+ const start = systemPrompt.lastIndexOf(open);
287
+ if (start === -1) return undefined;
288
+ const end = systemPrompt.indexOf(close, start);
289
+ return end === -1 ? undefined : { start, end: end + close.length };
290
+ }
291
+
292
+ /** Locate a complete delimited transport wrapper. */
293
+ function findDelimitedSpan(text: string, open: string, close: string): Span | undefined {
294
+ const start = text.indexOf(open);
295
+ if (start === -1) return undefined;
296
+ const closeStart = text.indexOf(close, start + open.length);
297
+ return closeStart === -1 ? undefined : { start, end: closeStart + close.length };
298
+ }
299
+
300
+ /** Include surrounding transport-only line breaks when carving a generated section. */
301
+ function expandLineBreaks(text: string, span: Span): Span {
302
+ let start = span.start;
303
+ let end = span.end;
304
+ while (start > 0 && (text[start - 1] === '\n' || text[start - 1] === '\r')) start--;
305
+ while (end < text.length && (text[end] === '\n' || text[end] === '\r')) end++;
306
+ return { start, end };
307
+ }