Files
pi-lens/prompt-parser.ts
wonder 922e1c3be2 Initial commit: pi-lens session observability for pi
- collector, classify, prompt-parser, server (TypeScript)
- web panel (app.js, index.html, style.css)
- smoke and load-test scripts
- DESIGN.md and README.md
2026-10-04 19:54:34 +08:00

185 lines
5.9 KiB
TypeScript

/**
* prompt-parser.ts — segment pi's rendered system prompt into colored source blocks.
*
* pi builds the system prompt from named sections; every section except `preamble`
* is wrapped as `<name>\n…\n</name>` (see pi dist/core/system-prompt.js):
* preamble | tools | rules | docs | addendum | project_context | skills | cwd | <custom…>
*
* Nested markers we unwrap into child segments:
* <project_instructions path="…">, <skill><name>…<location>…, "- tool: " lines in <tools>
*
* The parser is byte-accurate: separator gaps between blocks are folded into the
* adjacent segment, so segment contents sum to the full rendered prompt.
*/
import { sectionKind } from "./classify.ts";
import type { ContextKind } from "./types.ts";
export interface Segment {
name: string;
kind: ContextKind;
source: string;
content: string;
}
const BUILTIN_TAGS = ["tools", "rules", "docs", "addendum", "project_context", "skills", "cwd"];
interface Child {
name: string;
source: string;
content: string;
start: number;
end: number;
}
interface Span {
start: number;
end: number;
tag: string;
innerStart: number;
innerEnd: number;
}
function findTagSpans(text: string, tagSet: Set<string>): Span[] {
const spans: Span[] = [];
const re = /<([a-z][a-z0-9_-]*)>([\s\S]*?)<\/\1>/g;
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
const tag = m[1];
if (!tagSet.has(tag)) continue;
const start = m.index;
const end = m.index + m[0].length;
const openTagLen = tag.length + 2;
spans.push({ start, end, tag, innerStart: start + openTagLen, innerEnd: end - (tag.length + 3) });
}
return spans;
}
function projectContextChildren(inner: string): Child[] {
const out: Child[] = [];
const re = /<project_instructions path="([^"]*)">([\s\S]*?)<\/project_instructions>/g;
let m: RegExpExecArray | null;
while ((m = re.exec(inner)) !== null) {
out.push({
name: `project_context:${m[1]}`,
source: m[1],
content: m[0],
start: m.index,
end: m.index + m[0].length,
});
}
return out;
}
function skillChildren(inner: string): Child[] {
const out: Child[] = [];
const re = /<skill>([\s\S]*?)<\/skill>/g;
let m: RegExpExecArray | null;
while ((m = re.exec(inner)) !== null) {
const body = m[1];
const name = (body.match(/<name>([\s\S]*?)<\/name>/) ?? [])[1]?.trim() ?? "(skill)";
const location = (body.match(/<location>([\s\S]*?)<\/location>/) ?? [])[1]?.trim() ?? "";
out.push({
name: `skills:${name}`,
source: location || name,
content: m[0],
start: m.index,
end: m.index + m[0].length,
});
}
return out;
}
function toolChildren(inner: string): Child[] {
const out: Child[] = [];
const re = /^- ([^\s:]+): (.*)$/gm;
let m: RegExpExecArray | null;
while ((m = re.exec(inner)) !== null) {
out.push({
name: `tools:${m[1]}`,
source: m[1],
content: m[0],
start: m.index,
end: m.index + m[0].length,
});
}
return out;
}
/**
* Parse a rendered system prompt into ordered segments.
* `customTags` are extension-provided section names (from systemPromptOptions.sections).
*/
export function parseSystemPrompt(rendered: string, customTags: string[] = []): Segment[] {
const tagSet = new Set<string>([
...BUILTIN_TAGS,
...customTags.filter((t) => /^[a-z][a-z0-9_-]*$/.test(t) && t !== "preamble"),
]);
const spans = findTagSpans(rendered, tagSet);
const segments: Segment[] = [];
const firstStart = spans.length > 0 ? spans[0].start : rendered.length;
if (firstStart > 0) {
segments.push({ name: "preamble", kind: "preamble", source: "pi", content: rendered.slice(0, firstStart) });
}
let pos = firstStart;
for (const span of spans) {
const gap = rendered.slice(pos, span.start);
pos = span.end;
const inner = rendered.slice(span.innerStart, span.innerEnd);
const kind = sectionKind(span.tag);
let children: Child[] = [];
if (span.tag === "project_context") children = projectContextChildren(inner);
else if (span.tag === "skills") children = skillChildren(inner);
else if (span.tag === "tools") children = toolChildren(inner);
const block: Segment[] = [];
// Residual wrapper text (open tag, headers, close tag) with children cut out.
let residual = "";
let cursor = 0;
for (const child of children) {
residual += inner.slice(cursor, child.start);
cursor = child.end;
}
residual += inner.slice(cursor);
const wrapperText =
rendered.slice(span.start, span.innerStart) + residual + rendered.slice(span.innerEnd, span.end);
if (wrapperText.length > 0) {
block.push({ name: span.tag, kind, source: span.tag, content: wrapperText });
}
for (const child of children) {
block.push({ name: child.name, kind, source: child.source, content: child.content });
}
if (block.length === 0) {
block.push({ name: span.tag, kind, source: span.tag, content: "" });
}
// Fold the separator gap before this block into its first segment.
block[0].content = gap + block[0].content;
segments.push(...block);
}
// Trailing text after the last block attaches to the last segment.
if (segments.length > 0 && pos < rendered.length) {
segments[segments.length - 1].content += rendered.slice(pos);
}
return segments;
}
/** Segment an opaque forced prompt as a single block. */
export function forcedSegment(text: string): Segment[] {
return [{ name: "forceSystemPrompt", kind: "forced", source: "extension", content: text }];
}
export function customPromptSegment(text: string): Segment[] {
return [{ name: "customPrompt", kind: "forced", source: "extension", content: text }];
}
/** Guard used by tests: parsing must cover the prompt without inventing bytes. */
export function coverageRatio(rendered: string, segments: Segment[]): number {
const covered = segments.reduce((n, s) => n + s.content.length, 0);
return rendered.length === 0 ? 1 : Math.min(1, covered / rendered.length);
}