@caupulican/pi-agent-core 0.81.27 → 0.81.30
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/dist/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/compaction/branch-summarization.js +5 -3
- package/dist/compaction/branch-summarization.js.map +1 -1
- package/dist/compaction/extraction.d.ts.map +1 -1
- package/dist/compaction/extraction.js +12 -2
- package/dist/compaction/extraction.js.map +1 -1
- package/dist/compaction/verification.d.ts.map +1 -1
- package/dist/compaction/verification.js +27 -14
- package/dist/compaction/verification.js.map +1 -1
- package/dist/proxy.d.ts.map +1 -1
- package/dist/proxy.js +30 -5
- package/dist/proxy.js.map +1 -1
- package/dist/session/session-manager.d.ts +12 -0
- package/dist/session/session-manager.d.ts.map +1 -1
- package/dist/session/session-manager.js +270 -46
- package/dist/session/session-manager.js.map +1 -1
- package/dist/utils/streaming-lines.d.ts +20 -0
- package/dist/utils/streaming-lines.d.ts.map +1 -0
- package/dist/utils/streaming-lines.js +79 -0
- package/dist/utils/streaming-lines.js.map +1 -0
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verification.d.ts","sourceRoot":"","sources":["../../src/compaction/verification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAErF,MAAM,WAAW,mBAAmB;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,kBAAkB;IAClC,EAAE,EAAE,OAAO,CAAC;IACZ,QAAQ,EAAE,mBAAmB,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,0BAA0B;IAC1C,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,kBAAkB,CAAC;IACjC,OAAO,EAAE,OAAO,CAAC;CACjB;AAED,eAAO,MAAM,2BAA2B,MAAM,CAAC;AAC/C,eAAO,MAAM,iCAAiC,MAAM,CAAC;AACrD,eAAO,MAAM,gCAAgC,MAAM,CAAC;AACpD,eAAO,MAAM,gCAAgC,MAAM,CAAC;AACpD,eAAO,MAAM,wBAAwB,MAAM,CAAC;AAC5C,eAAO,MAAM,4BAA4B,MAAM,CAAC;AA+BhD,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,GAAG,kBAAkB,CA0GzF;AAED,wBAAgB,qCAAqC,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAU9E;AAED,wBAAgB,gCAAgC,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,GAAG,0BAA0B,CA+FpH;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,kBAAkB,EAAE,eAAe,CAAC,EAAE,MAAM,GAAG,MAAM,CAI7F;AA4FD,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAQlD;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,MAAM,CAWzE;AAED,wBAAgB,OAAO,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,MAAM,CAY9D","sourcesContent":["import { ACTIVE_TASK_SOURCE_MAX_CHARS, type CompactionFacts } from \"./extraction.ts\";\n\nexport interface VerificationFailure {\n\tcheck: string;\n\tdetail: string;\n}\n\nexport interface VerificationReport {\n\tok: boolean;\n\tfailures: VerificationFailure[];\n}\n\nexport interface DeterministicGapFillResult {\n\tsummary: string;\n\tverification: VerificationReport;\n\tchanged: boolean;\n}\n\nexport const FILES_READ_RECALL_THRESHOLD = 0.8;\nexport const ACTIVE_TASK_CONTAINMENT_THRESHOLD = 0.9;\nexport const MANDATORY_RULES_RECALL_THRESHOLD = 0.7;\nexport const CANCELLED_WORK_DROPPED_THRESHOLD = 0.1;\nexport const ACTIONS_RECALL_THRESHOLD = 0.6;\nexport const OPEN_ERRORS_RECALL_THRESHOLD = 0.7;\n\nconst SECTION_FILES = \"files\";\nconst SECTION_WORKING_SET = \"working set\";\nconst SECTION_OPEN_PROBLEMS = \"open problems\";\nconst SECTION_DONE = \"done\";\nconst SECTION_ACTIVE_TASK = \"active task\";\nconst SECTION_MANDATORY_RULES = \"mandatory rules\";\nconst SECTION_KEY_DECISIONS = \"key decisions\";\nconst SECTION_CONSTRAINTS = \"constraints & preferences\";\nconst SECTION_CRITICAL_CONTEXT = \"critical context\";\n\ninterface ParsedSummarySection {\n\theading: string;\n\tnormalized: string;\n\tlevel: \"##\" | \"###\";\n\tlines: string[];\n}\n\nconst REQUIRED_SUMMARY_SECTIONS: Array<{ heading: string; normalized: string; level: \"##\" | \"###\" }> = [\n\t{ heading: \"Active Task\", normalized: SECTION_ACTIVE_TASK, level: \"##\" },\n\t{ heading: \"Mandatory Rules\", normalized: SECTION_MANDATORY_RULES, level: \"###\" },\n\t{ heading: \"Working Set\", normalized: SECTION_WORKING_SET, level: \"##\" },\n\t{ heading: \"Files\", normalized: SECTION_FILES, level: \"##\" },\n\t{ heading: \"Open Problems\", normalized: SECTION_OPEN_PROBLEMS, level: \"##\" },\n\t{ heading: \"Done\", normalized: SECTION_DONE, level: \"##\" },\n\t{ heading: \"Key Decisions\", normalized: SECTION_KEY_DECISIONS, level: \"##\" },\n\t{ heading: \"Constraints & Preferences\", normalized: SECTION_CONSTRAINTS, level: \"##\" },\n\t{ heading: \"Critical Context\", normalized: SECTION_CRITICAL_CONTEXT, level: \"##\" },\n];\n\nexport function verifySummary(summary: string, facts: CompactionFacts): VerificationReport {\n\tif (factsAreEmpty(facts)) {\n\t\treturn { ok: true, failures: [] };\n\t}\n\n\tconst sections = extractSections(summary);\n\tconst failures: VerificationFailure[] = [];\n\tconst filesSection = sections[SECTION_FILES] ?? \"\";\n\tconst workingSetSection = sections[SECTION_WORKING_SET] ?? \"\";\n\tconst openProblemsSection = sections[SECTION_OPEN_PROBLEMS] ?? \"\";\n\tconst doneSection = sections[SECTION_DONE] ?? \"\";\n\tconst activeTaskSection = sections[SECTION_ACTIVE_TASK] ?? \"\";\n\tconst mandatoryRulesSection = sections[SECTION_MANDATORY_RULES] ?? \"\";\n\n\tconst modifiedFiles = facts.files.filter((file) => file.kind !== \"read\");\n\tconst missingModifiedFiles = modifiedFiles.map((file) => file.path).filter((path) => !filesSection.includes(path));\n\tif (missingModifiedFiles.length > 0) {\n\t\tfailures.push({\n\t\t\tcheck: \"files-modified-recall\",\n\t\t\tdetail: `Missing modified/created files in ## Files: ${missingModifiedFiles.join(\", \")}`,\n\t\t});\n\t}\n\n\tconst workingSetPaths = facts.workingSet.map((file) => file.path);\n\tconst missingWorkingSetPaths = workingSetPaths.filter((path) => !workingSetSection.includes(path));\n\tif (missingWorkingSetPaths.length > 0) {\n\t\tfailures.push({\n\t\t\tcheck: \"working-set-recall\",\n\t\t\tdetail: `Missing working-set files in ## Working Set: ${missingWorkingSetPaths.join(\", \")}`,\n\t\t});\n\t}\n\n\tconst readPaths = facts.files.filter((file) => file.kind === \"read\").map((file) => file.path);\n\tif (readPaths.length > 0) {\n\t\tconst score = containment(tokenSet(readPaths.join(\"\\n\")), tokenSet(filesSection));\n\t\tif (score < FILES_READ_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"files-read-recall\",\n\t\t\t\tdetail: `Read file recall ${formatScore(score)} below ${FILES_READ_RECALL_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.activeTaskSource) {\n\t\tconst score = containment(\n\t\t\ttokenSet(facts.activeTaskSource.slice(0, ACTIVE_TASK_SOURCE_MAX_CHARS)),\n\t\t\ttokenSet(activeTaskSection),\n\t\t);\n\t\tif (score < ACTIVE_TASK_CONTAINMENT_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"active-task-containment\",\n\t\t\t\tdetail: `Active task containment ${formatScore(score)} below ${ACTIVE_TASK_CONTAINMENT_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const prohibition of facts.prohibitions) {\n\t\tconst score = containment(tokenSet(prohibition), tokenSet(mandatoryRulesSection));\n\t\tif (score < MANDATORY_RULES_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"mandatory-rules-recall\",\n\t\t\t\tdetail: `Missing mandatory rule: ${prohibition}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.cancelledText) {\n\t\tconst summaryOutsideMandatoryRules = removeSection(summary, SECTION_MANDATORY_RULES);\n\t\t// File paths from the facts are REQUIRED elsewhere (files-modified/read-recall demand them\n\t\t// in ## Files), so counting them as cancelled-work leakage would make the two gates\n\t\t// unsatisfiable together whenever a reversal message references a touched file.\n\t\tconst factPathTokens = tokenSet(facts.files.map((file) => file.path).join(\"\\n\"));\n\t\tconst cancelledTokens = new Set([...tokenSet(facts.cancelledText)].filter((token) => !factPathTokens.has(token)));\n\t\tconst score = containment(cancelledTokens, tokenSet(summaryOutsideMandatoryRules));\n\t\tif (score > CANCELLED_WORK_DROPPED_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"cancelled-work-dropped\",\n\t\t\t\tdetail: `Cancelled work leakage ${formatScore(score)} above ${CANCELLED_WORK_DROPPED_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const error of facts.errorFacts) {\n\t\tconst score = containment(tokenSet(`${error.operation}: ${error.error}`), tokenSet(openProblemsSection));\n\t\tif (score < OPEN_ERRORS_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"open-errors-recall\",\n\t\t\t\tdetail: `Open error recall ${formatScore(score)} below ${OPEN_ERRORS_RECALL_THRESHOLD}: ${error.operation}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.actions.length > 0) {\n\t\t// Asymmetric on purpose: the update path carries prior ## Done items forward (bounded), so a\n\t\t// symmetric overlap metric would punish faithful carry-over — the gate demands only that the\n\t\t// NEW span's actions are recalled in ## Done, however much history rides alongside them.\n\t\tconst score = containment(tokenSet(facts.actions.join(\"\\n\")), tokenSet(doneSection));\n\t\tif (score < ACTIONS_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"actions-recall\",\n\t\t\t\tdetail: `New-action recall in ## Done ${formatScore(score)} below ${ACTIONS_RECALL_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { ok: failures.length === 0, failures };\n}\n\nexport function isCompactionSummaryStructurallyUsable(summary: string): boolean {\n\tif (summary.trim().length === 0) return false;\n\tconst sections = extractSections(summary);\n\treturn (\n\t\tsections[SECTION_ACTIVE_TASK] !== undefined ||\n\t\tsections[SECTION_FILES] !== undefined ||\n\t\tsections[SECTION_DONE] !== undefined ||\n\t\tsections[SECTION_WORKING_SET] !== undefined ||\n\t\tsections[SECTION_OPEN_PROBLEMS] !== undefined\n\t);\n}\n\nexport function deterministicallyFillSummaryGaps(summary: string, facts: CompactionFacts): DeterministicGapFillResult {\n\tif (!isCompactionSummaryStructurallyUsable(summary)) {\n\t\treturn { summary, verification: verifySummary(summary, facts), changed: false };\n\t}\n\n\tconst sections = parseSummarySections(summary);\n\tconst sectionByName = new Map<string, ParsedSummarySection>();\n\tconst extraSections: ParsedSummarySection[] = [];\n\tfor (const section of sections) {\n\t\tif (REQUIRED_SUMMARY_SECTIONS.some((required) => required.normalized === section.normalized)) {\n\t\t\tconst existing = sectionByName.get(section.normalized);\n\t\t\tif (existing) {\n\t\t\t\texisting.lines.push(...section.lines);\n\t\t\t} else {\n\t\t\t\tsectionByName.set(section.normalized, section);\n\t\t\t}\n\t\t} else {\n\t\t\textraSections.push(section);\n\t\t}\n\t}\n\n\tfor (const required of REQUIRED_SUMMARY_SECTIONS) {\n\t\tif (!sectionByName.has(required.normalized)) {\n\t\t\tsectionByName.set(required.normalized, {\n\t\t\t\theading: required.heading,\n\t\t\t\tnormalized: required.normalized,\n\t\t\t\tlevel: required.level,\n\t\t\t\tlines: [\"(none)\"],\n\t\t\t});\n\t\t}\n\t}\n\n\tremoveCancelledWorkLines(sectionByName, facts);\n\n\tif (facts.activeTaskSource) {\n\t\tconst activeTask = sectionByName.get(SECTION_ACTIVE_TASK)!;\n\t\tif (\n\t\t\tcontainment(tokenSet(facts.activeTaskSource), tokenSet(activeTask.lines.join(\"\\n\"))) <\n\t\t\tACTIVE_TASK_CONTAINMENT_THRESHOLD\n\t\t) {\n\t\t\tappendContentLine(activeTask.lines, `User: ${facts.activeTaskSource}`);\n\t\t}\n\t}\n\n\tconst mandatoryRules = sectionByName.get(SECTION_MANDATORY_RULES)!;\n\tfor (const rule of facts.prohibitions) {\n\t\tif (containment(tokenSet(rule), tokenSet(mandatoryRules.lines.join(\"\\n\"))) < MANDATORY_RULES_RECALL_THRESHOLD) {\n\t\t\tappendContentLine(mandatoryRules.lines, `- ${rule}`);\n\t\t}\n\t}\n\n\tconst workingSet = sectionByName.get(SECTION_WORKING_SET)!;\n\tfor (const file of facts.workingSet) {\n\t\tif (!workingSet.lines.join(\"\\n\").includes(file.path)) {\n\t\t\tappendContentLine(workingSet.lines, `- ${file.path} — ${file.note || file.kind}`);\n\t\t}\n\t}\n\n\tconst files = sectionByName.get(SECTION_FILES)!;\n\tfor (const file of facts.files) {\n\t\tif (!files.lines.join(\"\\n\").includes(file.path)) {\n\t\t\tappendContentLine(files.lines, `- ${file.path}`);\n\t\t}\n\t}\n\n\tconst openProblems = sectionByName.get(SECTION_OPEN_PROBLEMS)!;\n\tfor (const error of facts.errorFacts) {\n\t\tconst required = `${error.operation}: ${error.error}`;\n\t\tif (containment(tokenSet(required), tokenSet(openProblems.lines.join(\"\\n\"))) < OPEN_ERRORS_RECALL_THRESHOLD) {\n\t\t\tappendContentLine(openProblems.lines, `- ${required}`);\n\t\t}\n\t}\n\n\tconst done = sectionByName.get(SECTION_DONE)!;\n\tconst doneText = done.lines.join(\"\\n\");\n\tif (\n\t\tfacts.actions.length > 0 &&\n\t\tcontainment(tokenSet(facts.actions.join(\"\\n\")), tokenSet(doneText)) < ACTIONS_RECALL_THRESHOLD\n\t) {\n\t\tlet nextNumber = findNextDoneNumber(done.lines);\n\t\tfor (const action of facts.actions) {\n\t\t\tif (done.lines.join(\"\\n\").includes(action)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tappendContentLine(done.lines, `${nextNumber}. ${action}`);\n\t\t\tnextNumber++;\n\t\t}\n\t}\n\n\tconst filledSummary = renderSummarySections(sectionByName, extraSections);\n\treturn {\n\t\tsummary: filledSummary,\n\t\tverification: verifySummary(filledSummary, facts),\n\t\tchanged: filledSummary !== summary,\n\t};\n}\n\nexport function buildRetryPrompt(report: VerificationReport, previousAttempt?: string): string {\n\tconst failures = report.failures.map((failure) => `${failure.check}: ${failure.detail}`).join(\"; \");\n\tconst previous = previousAttempt ? `\\n\\n<previous-attempt>\\n${previousAttempt}\\n</previous-attempt>` : \"\";\n\treturn `Your previous checkpoint failed verification: ${failures}. Fix ONLY these omissions.${previous}`;\n}\n\nfunction parseSummarySections(summary: string): ParsedSummarySection[] {\n\tconst sections: ParsedSummarySection[] = [];\n\tlet current: ParsedSummarySection | undefined;\n\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tcurrent = {\n\t\t\t\theading: match[2],\n\t\t\t\tnormalized: normalizeHeading(match[2]),\n\t\t\t\tlevel: match[1] as \"##\" | \"###\",\n\t\t\t\tlines: [],\n\t\t\t};\n\t\t\tsections.push(current);\n\t\t\tcontinue;\n\t\t}\n\t\tif (current) {\n\t\t\tcurrent.lines.push(line);\n\t\t}\n\t}\n\n\treturn sections;\n}\n\nfunction renderSummarySections(\n\tsectionByName: Map<string, ParsedSummarySection>,\n\textraSections: ParsedSummarySection[],\n): string {\n\tconst rendered: string[] = [];\n\tfor (const required of REQUIRED_SUMMARY_SECTIONS) {\n\t\tconst section = sectionByName.get(required.normalized)!;\n\t\trendered.push(`${required.level} ${required.heading}`);\n\t\tconst body = normalizeSectionLines(section.lines);\n\t\trendered.push(...body);\n\t\trendered.push(\"\");\n\t}\n\tfor (const section of extraSections) {\n\t\trendered.push(`${section.level} ${section.heading}`);\n\t\trendered.push(...normalizeSectionLines(section.lines));\n\t\trendered.push(\"\");\n\t}\n\treturn rendered.join(\"\\n\").trimEnd();\n}\n\nfunction normalizeSectionLines(lines: string[]): string[] {\n\tconst trimmed = lines.map((line) => line.trimEnd());\n\twhile (trimmed.length > 0 && trimmed[0].trim() === \"\") trimmed.shift();\n\twhile (trimmed.length > 0 && trimmed[trimmed.length - 1].trim() === \"\") trimmed.pop();\n\treturn trimmed.length > 0 ? trimmed : [\"(none)\"];\n}\n\nfunction appendContentLine(lines: string[], line: string): void {\n\tconst normalized = normalizeSectionLines(lines).filter((existing) => existing.trim() !== \"(none)\");\n\tnormalized.push(line);\n\tlines.length = 0;\n\tlines.push(...normalized);\n}\n\nfunction findNextDoneNumber(lines: string[]): number {\n\tlet max = 0;\n\tfor (const line of lines) {\n\t\tconst match = /^\\s*(\\d+)\\./.exec(line);\n\t\tif (!match) continue;\n\t\tmax = Math.max(max, Number(match[1]));\n\t}\n\treturn max + 1;\n}\n\nfunction removeCancelledWorkLines(sectionByName: Map<string, ParsedSummarySection>, facts: CompactionFacts): void {\n\tif (!facts.cancelledText) return;\n\tconst factPathTokens = tokenSet(facts.files.map((file) => file.path).join(\"\\n\"));\n\tconst cancelledTokens = new Set([...tokenSet(facts.cancelledText)].filter((token) => !factPathTokens.has(token)));\n\tif (cancelledTokens.size === 0) return;\n\n\tfor (const section of sectionByName.values()) {\n\t\tif (section.normalized === SECTION_MANDATORY_RULES) continue;\n\t\tsection.lines = section.lines.filter((line) => !lineShouldBeDroppedAsCancelledWork(line, cancelledTokens));\n\t}\n}\n\nfunction lineShouldBeDroppedAsCancelledWork(line: string, cancelledTokens: Set<string>): boolean {\n\tconst lineTokens = tokenSet(line);\n\tif (lineTokens.size === 0) return false;\n\tlet overlap = 0;\n\tfor (const token of lineTokens) {\n\t\tif (cancelledTokens.has(token)) overlap++;\n\t}\n\treturn overlap >= 2 && overlap / lineTokens.size >= 0.6;\n}\n\nexport function tokenSet(text: string): Set<string> {\n\treturn new Set(\n\t\ttext\n\t\t\t.toLowerCase()\n\t\t\t.split(/[^a-z0-9_./-]+/)\n\t\t\t.map((token) => token.trim())\n\t\t\t.filter((token) => token.length >= 3),\n\t);\n}\n\nexport function containment(needle: Set<string>, hay: Set<string>): number {\n\tif (needle.size === 0) {\n\t\treturn 1;\n\t}\n\tlet hits = 0;\n\tfor (const token of needle) {\n\t\tif (hay.has(token)) {\n\t\t\thits += 1;\n\t\t}\n\t}\n\treturn hits / needle.size;\n}\n\nexport function jaccard(a: Set<string>, b: Set<string>): number {\n\tif (a.size === 0 && b.size === 0) {\n\t\treturn 1;\n\t}\n\tlet intersection = 0;\n\tfor (const token of a) {\n\t\tif (b.has(token)) {\n\t\t\tintersection += 1;\n\t\t}\n\t}\n\tconst union = new Set([...a, ...b]).size;\n\treturn union === 0 ? 1 : intersection / union;\n}\n\nfunction factsAreEmpty(facts: CompactionFacts): boolean {\n\treturn (\n\t\tfacts.files.length === 0 &&\n\t\tfacts.workingSet.length === 0 &&\n\t\tfacts.actions.length === 0 &&\n\t\tfacts.errorFacts.length === 0 &&\n\t\tfacts.prohibitions.length === 0 &&\n\t\tfacts.cancelledText === \"\" &&\n\t\tfacts.activeTaskSource === \"\"\n\t);\n}\n\nfunction extractSections(summary: string): Record<string, string> {\n\tconst sections: Record<string, string> = {};\n\tlet current: string | undefined;\n\tlet bucket: string[] = [];\n\n\tconst flush = (): void => {\n\t\tif (current) {\n\t\t\tsections[current] = bucket.join(\"\\n\").trim();\n\t\t}\n\t\tbucket = [];\n\t};\n\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(?:##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tflush();\n\t\t\tcurrent = normalizeHeading(match[1]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (current) {\n\t\t\tbucket.push(line);\n\t\t}\n\t}\n\tflush();\n\treturn sections;\n}\n\nfunction removeSection(summary: string, heading: string): string {\n\tconst normalizedHeading = normalizeHeading(heading);\n\tconst kept: string[] = [];\n\tlet skipping = false;\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(?:##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tskipping = normalizeHeading(match[1]) === normalizedHeading;\n\t\t\tif (skipping) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (!skipping) {\n\t\t\tkept.push(line);\n\t\t}\n\t}\n\treturn kept.join(\"\\n\");\n}\n\nfunction normalizeHeading(heading: string): string {\n\treturn heading.trim().toLowerCase();\n}\n\nfunction formatScore(score: number): string {\n\treturn score.toFixed(2);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"verification.d.ts","sourceRoot":"","sources":["../../src/compaction/verification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAErF,MAAM,WAAW,mBAAmB;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,kBAAkB;IAClC,EAAE,EAAE,OAAO,CAAC;IACZ,QAAQ,EAAE,mBAAmB,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,0BAA0B;IAC1C,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,kBAAkB,CAAC;IACjC,OAAO,EAAE,OAAO,CAAC;CACjB;AAED,eAAO,MAAM,2BAA2B,MAAM,CAAC;AAC/C,eAAO,MAAM,iCAAiC,MAAM,CAAC;AACrD,eAAO,MAAM,gCAAgC,MAAM,CAAC;AACpD,eAAO,MAAM,gCAAgC,MAAM,CAAC;AACpD,eAAO,MAAM,wBAAwB,MAAM,CAAC;AAC5C,eAAO,MAAM,4BAA4B,MAAM,CAAC;AA+BhD,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,GAAG,kBAAkB,CA0GzF;AAED,wBAAgB,qCAAqC,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAU9E;AAED,wBAAgB,gCAAgC,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,GAAG,0BAA0B,CA8FpH;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,kBAAkB,EAAE,eAAe,CAAC,EAAE,MAAM,GAAG,MAAM,CAI7F;AA0GD,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAQlD;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,MAAM,CAWzE;AAED,wBAAgB,OAAO,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,MAAM,CAY9D","sourcesContent":["import { ACTIVE_TASK_SOURCE_MAX_CHARS, type CompactionFacts } from \"./extraction.ts\";\n\nexport interface VerificationFailure {\n\tcheck: string;\n\tdetail: string;\n}\n\nexport interface VerificationReport {\n\tok: boolean;\n\tfailures: VerificationFailure[];\n}\n\nexport interface DeterministicGapFillResult {\n\tsummary: string;\n\tverification: VerificationReport;\n\tchanged: boolean;\n}\n\nexport const FILES_READ_RECALL_THRESHOLD = 0.8;\nexport const ACTIVE_TASK_CONTAINMENT_THRESHOLD = 0.9;\nexport const MANDATORY_RULES_RECALL_THRESHOLD = 0.7;\nexport const CANCELLED_WORK_DROPPED_THRESHOLD = 0.1;\nexport const ACTIONS_RECALL_THRESHOLD = 0.6;\nexport const OPEN_ERRORS_RECALL_THRESHOLD = 0.7;\n\nconst SECTION_FILES = \"files\";\nconst SECTION_WORKING_SET = \"working set\";\nconst SECTION_OPEN_PROBLEMS = \"open problems\";\nconst SECTION_DONE = \"done\";\nconst SECTION_ACTIVE_TASK = \"active task\";\nconst SECTION_MANDATORY_RULES = \"mandatory rules\";\nconst SECTION_KEY_DECISIONS = \"key decisions\";\nconst SECTION_CONSTRAINTS = \"constraints & preferences\";\nconst SECTION_CRITICAL_CONTEXT = \"critical context\";\n\ninterface ParsedSummarySection {\n\theading: string;\n\tnormalized: string;\n\tlevel: \"##\" | \"###\";\n\tlines: string[];\n}\n\nconst REQUIRED_SUMMARY_SECTIONS: Array<{ heading: string; normalized: string; level: \"##\" | \"###\" }> = [\n\t{ heading: \"Active Task\", normalized: SECTION_ACTIVE_TASK, level: \"##\" },\n\t{ heading: \"Mandatory Rules\", normalized: SECTION_MANDATORY_RULES, level: \"###\" },\n\t{ heading: \"Working Set\", normalized: SECTION_WORKING_SET, level: \"##\" },\n\t{ heading: \"Files\", normalized: SECTION_FILES, level: \"##\" },\n\t{ heading: \"Open Problems\", normalized: SECTION_OPEN_PROBLEMS, level: \"##\" },\n\t{ heading: \"Done\", normalized: SECTION_DONE, level: \"##\" },\n\t{ heading: \"Key Decisions\", normalized: SECTION_KEY_DECISIONS, level: \"##\" },\n\t{ heading: \"Constraints & Preferences\", normalized: SECTION_CONSTRAINTS, level: \"##\" },\n\t{ heading: \"Critical Context\", normalized: SECTION_CRITICAL_CONTEXT, level: \"##\" },\n];\n\nexport function verifySummary(summary: string, facts: CompactionFacts): VerificationReport {\n\tif (factsAreEmpty(facts)) {\n\t\treturn { ok: true, failures: [] };\n\t}\n\n\tconst sections = extractSections(summary);\n\tconst failures: VerificationFailure[] = [];\n\tconst filesSection = sections[SECTION_FILES] ?? \"\";\n\tconst workingSetSection = sections[SECTION_WORKING_SET] ?? \"\";\n\tconst openProblemsSection = sections[SECTION_OPEN_PROBLEMS] ?? \"\";\n\tconst doneSection = sections[SECTION_DONE] ?? \"\";\n\tconst activeTaskSection = sections[SECTION_ACTIVE_TASK] ?? \"\";\n\tconst mandatoryRulesSection = sections[SECTION_MANDATORY_RULES] ?? \"\";\n\n\tconst modifiedFiles = facts.files.filter((file) => file.kind !== \"read\");\n\tconst missingModifiedFiles = modifiedFiles.map((file) => file.path).filter((path) => !filesSection.includes(path));\n\tif (missingModifiedFiles.length > 0) {\n\t\tfailures.push({\n\t\t\tcheck: \"files-modified-recall\",\n\t\t\tdetail: `Missing modified/created files in ## Files: ${missingModifiedFiles.join(\", \")}`,\n\t\t});\n\t}\n\n\tconst workingSetPaths = facts.workingSet.map((file) => file.path);\n\tconst missingWorkingSetPaths = workingSetPaths.filter((path) => !workingSetSection.includes(path));\n\tif (missingWorkingSetPaths.length > 0) {\n\t\tfailures.push({\n\t\t\tcheck: \"working-set-recall\",\n\t\t\tdetail: `Missing working-set files in ## Working Set: ${missingWorkingSetPaths.join(\", \")}`,\n\t\t});\n\t}\n\n\tconst readPaths = facts.files.filter((file) => file.kind === \"read\").map((file) => file.path);\n\tif (readPaths.length > 0) {\n\t\tconst score = containment(tokenSet(readPaths.join(\"\\n\")), tokenSet(filesSection));\n\t\tif (score < FILES_READ_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"files-read-recall\",\n\t\t\t\tdetail: `Read file recall ${formatScore(score)} below ${FILES_READ_RECALL_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.activeTaskSource) {\n\t\tconst score = containment(\n\t\t\ttokenSet(facts.activeTaskSource.slice(0, ACTIVE_TASK_SOURCE_MAX_CHARS)),\n\t\t\ttokenSet(activeTaskSection),\n\t\t);\n\t\tif (score < ACTIVE_TASK_CONTAINMENT_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"active-task-containment\",\n\t\t\t\tdetail: `Active task containment ${formatScore(score)} below ${ACTIVE_TASK_CONTAINMENT_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const prohibition of facts.prohibitions) {\n\t\tconst score = containment(tokenSet(prohibition), tokenSet(mandatoryRulesSection));\n\t\tif (score < MANDATORY_RULES_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"mandatory-rules-recall\",\n\t\t\t\tdetail: `Missing mandatory rule: ${prohibition}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.cancelledText) {\n\t\tconst summaryOutsideMandatoryRules = removeSection(summary, SECTION_MANDATORY_RULES);\n\t\t// File paths from the facts are REQUIRED elsewhere (files-modified/read-recall demand them\n\t\t// in ## Files), so counting them as cancelled-work leakage would make the two gates\n\t\t// unsatisfiable together whenever a reversal message references a touched file.\n\t\tconst factPathTokens = tokenSet(facts.files.map((file) => file.path).join(\"\\n\"));\n\t\tconst cancelledTokens = new Set([...tokenSet(facts.cancelledText)].filter((token) => !factPathTokens.has(token)));\n\t\tconst score = containment(cancelledTokens, tokenSet(summaryOutsideMandatoryRules));\n\t\tif (score > CANCELLED_WORK_DROPPED_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"cancelled-work-dropped\",\n\t\t\t\tdetail: `Cancelled work leakage ${formatScore(score)} above ${CANCELLED_WORK_DROPPED_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const error of facts.errorFacts) {\n\t\tconst score = containment(tokenSet(`${error.operation}: ${error.error}`), tokenSet(openProblemsSection));\n\t\tif (score < OPEN_ERRORS_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"open-errors-recall\",\n\t\t\t\tdetail: `Open error recall ${formatScore(score)} below ${OPEN_ERRORS_RECALL_THRESHOLD}: ${error.operation}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.actions.length > 0) {\n\t\t// Asymmetric on purpose: the update path carries prior ## Done items forward (bounded), so a\n\t\t// symmetric overlap metric would punish faithful carry-over — the gate demands only that the\n\t\t// NEW span's actions are recalled in ## Done, however much history rides alongside them.\n\t\tconst score = containment(tokenSet(facts.actions.join(\"\\n\")), tokenSet(doneSection));\n\t\tif (score < ACTIONS_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"actions-recall\",\n\t\t\t\tdetail: `New-action recall in ## Done ${formatScore(score)} below ${ACTIONS_RECALL_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { ok: failures.length === 0, failures };\n}\n\nexport function isCompactionSummaryStructurallyUsable(summary: string): boolean {\n\tif (summary.trim().length === 0) return false;\n\tconst sections = extractSections(summary);\n\treturn (\n\t\tsections[SECTION_ACTIVE_TASK] !== undefined ||\n\t\tsections[SECTION_FILES] !== undefined ||\n\t\tsections[SECTION_DONE] !== undefined ||\n\t\tsections[SECTION_WORKING_SET] !== undefined ||\n\t\tsections[SECTION_OPEN_PROBLEMS] !== undefined\n\t);\n}\n\nexport function deterministicallyFillSummaryGaps(summary: string, facts: CompactionFacts): DeterministicGapFillResult {\n\tif (!isCompactionSummaryStructurallyUsable(summary)) {\n\t\treturn { summary, verification: verifySummary(summary, facts), changed: false };\n\t}\n\n\tconst sections = parseSummarySections(summary);\n\tconst sectionByName = new Map<string, ParsedSummarySection>();\n\tconst extraSections: ParsedSummarySection[] = [];\n\tfor (const section of sections) {\n\t\tif (REQUIRED_SUMMARY_SECTIONS.some((required) => required.normalized === section.normalized)) {\n\t\t\tconst existing = sectionByName.get(section.normalized);\n\t\t\tif (existing) {\n\t\t\t\texisting.lines.push(...section.lines);\n\t\t\t} else {\n\t\t\t\tsectionByName.set(section.normalized, section);\n\t\t\t}\n\t\t} else {\n\t\t\textraSections.push(section);\n\t\t}\n\t}\n\n\tfor (const required of REQUIRED_SUMMARY_SECTIONS) {\n\t\tif (!sectionByName.has(required.normalized)) {\n\t\t\tsectionByName.set(required.normalized, {\n\t\t\t\theading: required.heading,\n\t\t\t\tnormalized: required.normalized,\n\t\t\t\tlevel: required.level,\n\t\t\t\tlines: [\"(none)\"],\n\t\t\t});\n\t\t}\n\t}\n\n\tremoveCancelledWorkLines(sectionByName, facts);\n\n\tif (facts.activeTaskSource) {\n\t\tconst activeTask = sectionByName.get(SECTION_ACTIVE_TASK)!;\n\t\tif (\n\t\t\tcontainment(tokenSet(facts.activeTaskSource), tokenSetFromLines(activeTask.lines)) <\n\t\t\tACTIVE_TASK_CONTAINMENT_THRESHOLD\n\t\t) {\n\t\t\tappendContentLine(activeTask.lines, `User: ${facts.activeTaskSource}`);\n\t\t}\n\t}\n\n\tconst mandatoryRules = sectionByName.get(SECTION_MANDATORY_RULES)!;\n\tfor (const rule of facts.prohibitions) {\n\t\tif (containment(tokenSet(rule), tokenSetFromLines(mandatoryRules.lines)) < MANDATORY_RULES_RECALL_THRESHOLD) {\n\t\t\tappendContentLine(mandatoryRules.lines, `- ${rule}`);\n\t\t}\n\t}\n\n\tconst workingSet = sectionByName.get(SECTION_WORKING_SET)!;\n\tfor (const file of facts.workingSet) {\n\t\tif (!sectionLinesContain(workingSet.lines, file.path)) {\n\t\t\tappendContentLine(workingSet.lines, `- ${file.path} — ${file.note || file.kind}`);\n\t\t}\n\t}\n\n\tconst files = sectionByName.get(SECTION_FILES)!;\n\tfor (const file of facts.files) {\n\t\tif (!sectionLinesContain(files.lines, file.path)) {\n\t\t\tappendContentLine(files.lines, `- ${file.path}`);\n\t\t}\n\t}\n\n\tconst openProblems = sectionByName.get(SECTION_OPEN_PROBLEMS)!;\n\tfor (const error of facts.errorFacts) {\n\t\tconst required = `${error.operation}: ${error.error}`;\n\t\tif (containment(tokenSet(required), tokenSetFromLines(openProblems.lines)) < OPEN_ERRORS_RECALL_THRESHOLD) {\n\t\t\tappendContentLine(openProblems.lines, `- ${required}`);\n\t\t}\n\t}\n\n\tconst done = sectionByName.get(SECTION_DONE)!;\n\tif (\n\t\tfacts.actions.length > 0 &&\n\t\tcontainment(tokenSet(facts.actions.join(\"\\n\")), tokenSetFromLines(done.lines)) < ACTIONS_RECALL_THRESHOLD\n\t) {\n\t\tlet nextNumber = findNextDoneNumber(done.lines);\n\t\tfor (const action of facts.actions) {\n\t\t\tif (sectionLinesContain(done.lines, action)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tappendContentLine(done.lines, `${nextNumber}. ${action}`);\n\t\t\tnextNumber++;\n\t\t}\n\t}\n\n\tconst filledSummary = renderSummarySections(sectionByName, extraSections);\n\treturn {\n\t\tsummary: filledSummary,\n\t\tverification: verifySummary(filledSummary, facts),\n\t\tchanged: filledSummary !== summary,\n\t};\n}\n\nexport function buildRetryPrompt(report: VerificationReport, previousAttempt?: string): string {\n\tconst failures = report.failures.map((failure) => `${failure.check}: ${failure.detail}`).join(\"; \");\n\tconst previous = previousAttempt ? `\\n\\n<previous-attempt>\\n${previousAttempt}\\n</previous-attempt>` : \"\";\n\treturn `Your previous checkpoint failed verification: ${failures}. Fix ONLY these omissions.${previous}`;\n}\n\nfunction parseSummarySections(summary: string): ParsedSummarySection[] {\n\tconst sections: ParsedSummarySection[] = [];\n\tlet current: ParsedSummarySection | undefined;\n\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tcurrent = {\n\t\t\t\theading: match[2],\n\t\t\t\tnormalized: normalizeHeading(match[2]),\n\t\t\t\tlevel: match[1] as \"##\" | \"###\",\n\t\t\t\tlines: [],\n\t\t\t};\n\t\t\tsections.push(current);\n\t\t\tcontinue;\n\t\t}\n\t\tif (current) {\n\t\t\tcurrent.lines.push(line);\n\t\t}\n\t}\n\n\treturn sections;\n}\n\nfunction renderSummarySections(\n\tsectionByName: Map<string, ParsedSummarySection>,\n\textraSections: ParsedSummarySection[],\n): string {\n\tconst rendered: string[] = [];\n\tfor (const required of REQUIRED_SUMMARY_SECTIONS) {\n\t\tconst section = sectionByName.get(required.normalized)!;\n\t\trendered.push(`${required.level} ${required.heading}`);\n\t\tconst body = normalizeSectionLines(section.lines);\n\t\trendered.push(...body);\n\t\trendered.push(\"\");\n\t}\n\tfor (const section of extraSections) {\n\t\trendered.push(`${section.level} ${section.heading}`);\n\t\trendered.push(...normalizeSectionLines(section.lines));\n\t\trendered.push(\"\");\n\t}\n\treturn rendered.join(\"\\n\").trimEnd();\n}\n\nfunction normalizeSectionLines(lines: string[]): string[] {\n\tlet start = 0;\n\tlet end = lines.length;\n\twhile (start < end && lines[start].trim() === \"\") start++;\n\twhile (end > start && lines[end - 1].trim() === \"\") end--;\n\tif (start === end) return [\"(none)\"];\n\treturn lines.slice(start, end).map((line) => line.trimEnd());\n}\n\nfunction sectionLinesContain(lines: readonly string[], value: string): boolean {\n\treturn lines.some((line) => line.includes(value));\n}\n\nfunction tokenSetFromLines(lines: readonly string[]): Set<string> {\n\tconst tokens = new Set<string>();\n\tfor (const line of lines) {\n\t\tfor (const token of tokenSet(line)) tokens.add(token);\n\t}\n\treturn tokens;\n}\n\nfunction appendContentLine(lines: string[], line: string): void {\n\tconst normalized = normalizeSectionLines(lines).filter((existing) => existing.trim() !== \"(none)\");\n\tnormalized.push(line);\n\tlines.length = 0;\n\tlines.push(...normalized);\n}\n\nfunction findNextDoneNumber(lines: string[]): number {\n\tlet max = 0;\n\tfor (const line of lines) {\n\t\tconst match = /^\\s*(\\d+)\\./.exec(line);\n\t\tif (!match) continue;\n\t\tmax = Math.max(max, Number(match[1]));\n\t}\n\treturn max + 1;\n}\n\nfunction removeCancelledWorkLines(sectionByName: Map<string, ParsedSummarySection>, facts: CompactionFacts): void {\n\tif (!facts.cancelledText) return;\n\tconst factPathTokens = tokenSet(facts.files.map((file) => file.path).join(\"\\n\"));\n\tconst cancelledTokens = new Set([...tokenSet(facts.cancelledText)].filter((token) => !factPathTokens.has(token)));\n\tif (cancelledTokens.size === 0) return;\n\n\tfor (const section of sectionByName.values()) {\n\t\tif (section.normalized === SECTION_MANDATORY_RULES) continue;\n\t\tsection.lines = section.lines.filter((line) => !lineShouldBeDroppedAsCancelledWork(line, cancelledTokens));\n\t}\n}\n\nfunction lineShouldBeDroppedAsCancelledWork(line: string, cancelledTokens: Set<string>): boolean {\n\tconst lineTokens = tokenSet(line);\n\tif (lineTokens.size === 0) return false;\n\tlet overlap = 0;\n\tfor (const token of lineTokens) {\n\t\tif (cancelledTokens.has(token)) overlap++;\n\t}\n\treturn overlap >= 2 && overlap / lineTokens.size >= 0.6;\n}\n\nexport function tokenSet(text: string): Set<string> {\n\treturn new Set(\n\t\ttext\n\t\t\t.toLowerCase()\n\t\t\t.split(/[^a-z0-9_./-]+/)\n\t\t\t.map((token) => token.trim())\n\t\t\t.filter((token) => token.length >= 3),\n\t);\n}\n\nexport function containment(needle: Set<string>, hay: Set<string>): number {\n\tif (needle.size === 0) {\n\t\treturn 1;\n\t}\n\tlet hits = 0;\n\tfor (const token of needle) {\n\t\tif (hay.has(token)) {\n\t\t\thits += 1;\n\t\t}\n\t}\n\treturn hits / needle.size;\n}\n\nexport function jaccard(a: Set<string>, b: Set<string>): number {\n\tif (a.size === 0 && b.size === 0) {\n\t\treturn 1;\n\t}\n\tlet intersection = 0;\n\tfor (const token of a) {\n\t\tif (b.has(token)) {\n\t\t\tintersection += 1;\n\t\t}\n\t}\n\tconst union = new Set([...a, ...b]).size;\n\treturn union === 0 ? 1 : intersection / union;\n}\n\nfunction factsAreEmpty(facts: CompactionFacts): boolean {\n\treturn (\n\t\tfacts.files.length === 0 &&\n\t\tfacts.workingSet.length === 0 &&\n\t\tfacts.actions.length === 0 &&\n\t\tfacts.errorFacts.length === 0 &&\n\t\tfacts.prohibitions.length === 0 &&\n\t\tfacts.cancelledText === \"\" &&\n\t\tfacts.activeTaskSource === \"\"\n\t);\n}\n\nfunction extractSections(summary: string): Record<string, string> {\n\tconst sections: Record<string, string> = {};\n\tlet current: string | undefined;\n\tlet bucket: string[] = [];\n\n\tconst flush = (): void => {\n\t\tif (current) {\n\t\t\tsections[current] = bucket.join(\"\\n\").trim();\n\t\t}\n\t\tbucket = [];\n\t};\n\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(?:##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tflush();\n\t\t\tcurrent = normalizeHeading(match[1]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (current) {\n\t\t\tbucket.push(line);\n\t\t}\n\t}\n\tflush();\n\treturn sections;\n}\n\nfunction removeSection(summary: string, heading: string): string {\n\tconst normalizedHeading = normalizeHeading(heading);\n\tconst kept: string[] = [];\n\tlet skipping = false;\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(?:##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tskipping = normalizeHeading(match[1]) === normalizedHeading;\n\t\t\tif (skipping) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (!skipping) {\n\t\t\tkept.push(line);\n\t\t}\n\t}\n\treturn kept.join(\"\\n\");\n}\n\nfunction normalizeHeading(heading: string): string {\n\treturn heading.trim().toLowerCase();\n}\n\nfunction formatScore(score: number): string {\n\treturn score.toFixed(2);\n}\n"]}
|
|
@@ -163,43 +163,42 @@ export function deterministicallyFillSummaryGaps(summary, facts) {
|
|
|
163
163
|
removeCancelledWorkLines(sectionByName, facts);
|
|
164
164
|
if (facts.activeTaskSource) {
|
|
165
165
|
const activeTask = sectionByName.get(SECTION_ACTIVE_TASK);
|
|
166
|
-
if (containment(tokenSet(facts.activeTaskSource),
|
|
166
|
+
if (containment(tokenSet(facts.activeTaskSource), tokenSetFromLines(activeTask.lines)) <
|
|
167
167
|
ACTIVE_TASK_CONTAINMENT_THRESHOLD) {
|
|
168
168
|
appendContentLine(activeTask.lines, `User: ${facts.activeTaskSource}`);
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
171
|
const mandatoryRules = sectionByName.get(SECTION_MANDATORY_RULES);
|
|
172
172
|
for (const rule of facts.prohibitions) {
|
|
173
|
-
if (containment(tokenSet(rule),
|
|
173
|
+
if (containment(tokenSet(rule), tokenSetFromLines(mandatoryRules.lines)) < MANDATORY_RULES_RECALL_THRESHOLD) {
|
|
174
174
|
appendContentLine(mandatoryRules.lines, `- ${rule}`);
|
|
175
175
|
}
|
|
176
176
|
}
|
|
177
177
|
const workingSet = sectionByName.get(SECTION_WORKING_SET);
|
|
178
178
|
for (const file of facts.workingSet) {
|
|
179
|
-
if (!workingSet.lines
|
|
179
|
+
if (!sectionLinesContain(workingSet.lines, file.path)) {
|
|
180
180
|
appendContentLine(workingSet.lines, `- ${file.path} — ${file.note || file.kind}`);
|
|
181
181
|
}
|
|
182
182
|
}
|
|
183
183
|
const files = sectionByName.get(SECTION_FILES);
|
|
184
184
|
for (const file of facts.files) {
|
|
185
|
-
if (!files.lines
|
|
185
|
+
if (!sectionLinesContain(files.lines, file.path)) {
|
|
186
186
|
appendContentLine(files.lines, `- ${file.path}`);
|
|
187
187
|
}
|
|
188
188
|
}
|
|
189
189
|
const openProblems = sectionByName.get(SECTION_OPEN_PROBLEMS);
|
|
190
190
|
for (const error of facts.errorFacts) {
|
|
191
191
|
const required = `${error.operation}: ${error.error}`;
|
|
192
|
-
if (containment(tokenSet(required),
|
|
192
|
+
if (containment(tokenSet(required), tokenSetFromLines(openProblems.lines)) < OPEN_ERRORS_RECALL_THRESHOLD) {
|
|
193
193
|
appendContentLine(openProblems.lines, `- ${required}`);
|
|
194
194
|
}
|
|
195
195
|
}
|
|
196
196
|
const done = sectionByName.get(SECTION_DONE);
|
|
197
|
-
const doneText = done.lines.join("\n");
|
|
198
197
|
if (facts.actions.length > 0 &&
|
|
199
|
-
containment(tokenSet(facts.actions.join("\n")),
|
|
198
|
+
containment(tokenSet(facts.actions.join("\n")), tokenSetFromLines(done.lines)) < ACTIONS_RECALL_THRESHOLD) {
|
|
200
199
|
let nextNumber = findNextDoneNumber(done.lines);
|
|
201
200
|
for (const action of facts.actions) {
|
|
202
|
-
if (done.lines
|
|
201
|
+
if (sectionLinesContain(done.lines, action)) {
|
|
203
202
|
continue;
|
|
204
203
|
}
|
|
205
204
|
appendContentLine(done.lines, `${nextNumber}. ${action}`);
|
|
@@ -256,12 +255,26 @@ function renderSummarySections(sectionByName, extraSections) {
|
|
|
256
255
|
return rendered.join("\n").trimEnd();
|
|
257
256
|
}
|
|
258
257
|
function normalizeSectionLines(lines) {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
258
|
+
let start = 0;
|
|
259
|
+
let end = lines.length;
|
|
260
|
+
while (start < end && lines[start].trim() === "")
|
|
261
|
+
start++;
|
|
262
|
+
while (end > start && lines[end - 1].trim() === "")
|
|
263
|
+
end--;
|
|
264
|
+
if (start === end)
|
|
265
|
+
return ["(none)"];
|
|
266
|
+
return lines.slice(start, end).map((line) => line.trimEnd());
|
|
267
|
+
}
|
|
268
|
+
function sectionLinesContain(lines, value) {
|
|
269
|
+
return lines.some((line) => line.includes(value));
|
|
270
|
+
}
|
|
271
|
+
function tokenSetFromLines(lines) {
|
|
272
|
+
const tokens = new Set();
|
|
273
|
+
for (const line of lines) {
|
|
274
|
+
for (const token of tokenSet(line))
|
|
275
|
+
tokens.add(token);
|
|
276
|
+
}
|
|
277
|
+
return tokens;
|
|
265
278
|
}
|
|
266
279
|
function appendContentLine(lines, line) {
|
|
267
280
|
const normalized = normalizeSectionLines(lines).filter((existing) => existing.trim() !== "(none)");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verification.js","sourceRoot":"","sources":["../../src/compaction/verification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAwB,MAAM,iBAAiB,CAAC;AAkBrF,MAAM,CAAC,MAAM,2BAA2B,GAAG,GAAG,CAAC;AAC/C,MAAM,CAAC,MAAM,iCAAiC,GAAG,GAAG,CAAC;AACrD,MAAM,CAAC,MAAM,gCAAgC,GAAG,GAAG,CAAC;AACpD,MAAM,CAAC,MAAM,gCAAgC,GAAG,GAAG,CAAC;AACpD,MAAM,CAAC,MAAM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AyB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnD,IAAI,KAAK,EAAE,CAAC;YACX,QAAQ,GAAG,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,iBAAiB,CAAC;YAC5D,IAAI,QAAQ,EAAE,CAAC;gBACd,SAAS;YACV,CAAC;QACF,CAAC;QACD,IAAI,CAAC,QAAQ,EAAE,CAAC;YACf,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjB,CAAC;IACF,CAAC;IACD,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACvB;AAED,SAAS,gBAAgB,CAAC,OAAe,EAAU;IAClD,OAAO,OAAO,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AAAA,CACpC;AAED,SAAS,WAAW,CAAC,KAAa,EAAU;IAC3C,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAAA,CACxB","sourcesContent":["import { ACTIVE_TASK_SOURCE_MAX_CHARS, type CompactionFacts } from \"./extraction.ts\";\n\nexport interface VerificationFailure {\n\tcheck: string;\n\tdetail: string;\n}\n\nexport interface VerificationReport {\n\tok: boolean;\n\tfailures: VerificationFailure[];\n}\n\nexport interface DeterministicGapFillResult {\n\tsummary: string;\n\tverification: VerificationReport;\n\tchanged: boolean;\n}\n\nexport const FILES_READ_RECALL_THRESHOLD = 0.8;\nexport const ACTIVE_TASK_CONTAINMENT_THRESHOLD = 0.9;\nexport const MANDATORY_RULES_RECALL_THRESHOLD = 0.7;\nexport const CANCELLED_WORK_DROPPED_THRESHOLD = 0.1;\nexport const ACTIONS_RECALL_THRESHOLD = 0.6;\nexport const OPEN_ERRORS_RECALL_THRESHOLD = 0.7;\n\nconst SECTION_FILES = \"files\";\nconst SECTION_WORKING_SET = \"working set\";\nconst SECTION_OPEN_PROBLEMS = \"open problems\";\nconst SECTION_DONE = \"done\";\nconst SECTION_ACTIVE_TASK = \"active task\";\nconst SECTION_MANDATORY_RULES = \"mandatory rules\";\nconst SECTION_KEY_DECISIONS = \"key decisions\";\nconst SECTION_CONSTRAINTS = \"constraints & preferences\";\nconst SECTION_CRITICAL_CONTEXT = \"critical context\";\n\ninterface ParsedSummarySection {\n\theading: string;\n\tnormalized: string;\n\tlevel: \"##\" | \"###\";\n\tlines: string[];\n}\n\nconst REQUIRED_SUMMARY_SECTIONS: Array<{ heading: string; normalized: string; level: \"##\" | \"###\" }> = [\n\t{ heading: \"Active Task\", normalized: SECTION_ACTIVE_TASK, level: \"##\" },\n\t{ heading: \"Mandatory Rules\", normalized: SECTION_MANDATORY_RULES, level: \"###\" },\n\t{ heading: \"Working Set\", normalized: SECTION_WORKING_SET, level: \"##\" },\n\t{ heading: \"Files\", normalized: SECTION_FILES, level: \"##\" },\n\t{ heading: \"Open Problems\", normalized: SECTION_OPEN_PROBLEMS, level: \"##\" },\n\t{ heading: \"Done\", normalized: SECTION_DONE, level: \"##\" },\n\t{ heading: \"Key Decisions\", normalized: SECTION_KEY_DECISIONS, level: \"##\" },\n\t{ heading: \"Constraints & Preferences\", normalized: SECTION_CONSTRAINTS, level: \"##\" },\n\t{ heading: \"Critical Context\", normalized: SECTION_CRITICAL_CONTEXT, level: \"##\" },\n];\n\nexport function verifySummary(summary: string, facts: CompactionFacts): VerificationReport {\n\tif (factsAreEmpty(facts)) {\n\t\treturn { ok: true, failures: [] };\n\t}\n\n\tconst sections = extractSections(summary);\n\tconst failures: VerificationFailure[] = [];\n\tconst filesSection = sections[SECTION_FILES] ?? \"\";\n\tconst workingSetSection = sections[SECTION_WORKING_SET] ?? \"\";\n\tconst openProblemsSection = sections[SECTION_OPEN_PROBLEMS] ?? \"\";\n\tconst doneSection = sections[SECTION_DONE] ?? \"\";\n\tconst activeTaskSection = sections[SECTION_ACTIVE_TASK] ?? \"\";\n\tconst mandatoryRulesSection = sections[SECTION_MANDATORY_RULES] ?? \"\";\n\n\tconst modifiedFiles = facts.files.filter((file) => file.kind !== \"read\");\n\tconst missingModifiedFiles = modifiedFiles.map((file) => file.path).filter((path) => !filesSection.includes(path));\n\tif (missingModifiedFiles.length > 0) {\n\t\tfailures.push({\n\t\t\tcheck: \"files-modified-recall\",\n\t\t\tdetail: `Missing modified/created files in ## Files: ${missingModifiedFiles.join(\", \")}`,\n\t\t});\n\t}\n\n\tconst workingSetPaths = facts.workingSet.map((file) => file.path);\n\tconst missingWorkingSetPaths = workingSetPaths.filter((path) => !workingSetSection.includes(path));\n\tif (missingWorkingSetPaths.length > 0) {\n\t\tfailures.push({\n\t\t\tcheck: \"working-set-recall\",\n\t\t\tdetail: `Missing working-set files in ## Working Set: ${missingWorkingSetPaths.join(\", \")}`,\n\t\t});\n\t}\n\n\tconst readPaths = facts.files.filter((file) => file.kind === \"read\").map((file) => file.path);\n\tif (readPaths.length > 0) {\n\t\tconst score = containment(tokenSet(readPaths.join(\"\\n\")), tokenSet(filesSection));\n\t\tif (score < FILES_READ_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"files-read-recall\",\n\t\t\t\tdetail: `Read file recall ${formatScore(score)} below ${FILES_READ_RECALL_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.activeTaskSource) {\n\t\tconst score = containment(\n\t\t\ttokenSet(facts.activeTaskSource.slice(0, ACTIVE_TASK_SOURCE_MAX_CHARS)),\n\t\t\ttokenSet(activeTaskSection),\n\t\t);\n\t\tif (score < ACTIVE_TASK_CONTAINMENT_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"active-task-containment\",\n\t\t\t\tdetail: `Active task containment ${formatScore(score)} below ${ACTIVE_TASK_CONTAINMENT_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const prohibition of facts.prohibitions) {\n\t\tconst score = containment(tokenSet(prohibition), tokenSet(mandatoryRulesSection));\n\t\tif (score < MANDATORY_RULES_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"mandatory-rules-recall\",\n\t\t\t\tdetail: `Missing mandatory rule: ${prohibition}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.cancelledText) {\n\t\tconst summaryOutsideMandatoryRules = removeSection(summary, SECTION_MANDATORY_RULES);\n\t\t// File paths from the facts are REQUIRED elsewhere (files-modified/read-recall demand them\n\t\t// in ## Files), so counting them as cancelled-work leakage would make the two gates\n\t\t// unsatisfiable together whenever a reversal message references a touched file.\n\t\tconst factPathTokens = tokenSet(facts.files.map((file) => file.path).join(\"\\n\"));\n\t\tconst cancelledTokens = new Set([...tokenSet(facts.cancelledText)].filter((token) => !factPathTokens.has(token)));\n\t\tconst score = containment(cancelledTokens, tokenSet(summaryOutsideMandatoryRules));\n\t\tif (score > CANCELLED_WORK_DROPPED_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"cancelled-work-dropped\",\n\t\t\t\tdetail: `Cancelled work leakage ${formatScore(score)} above ${CANCELLED_WORK_DROPPED_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const error of facts.errorFacts) {\n\t\tconst score = containment(tokenSet(`${error.operation}: ${error.error}`), tokenSet(openProblemsSection));\n\t\tif (score < OPEN_ERRORS_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"open-errors-recall\",\n\t\t\t\tdetail: `Open error recall ${formatScore(score)} below ${OPEN_ERRORS_RECALL_THRESHOLD}: ${error.operation}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.actions.length > 0) {\n\t\t// Asymmetric on purpose: the update path carries prior ## Done items forward (bounded), so a\n\t\t// symmetric overlap metric would punish faithful carry-over — the gate demands only that the\n\t\t// NEW span's actions are recalled in ## Done, however much history rides alongside them.\n\t\tconst score = containment(tokenSet(facts.actions.join(\"\\n\")), tokenSet(doneSection));\n\t\tif (score < ACTIONS_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"actions-recall\",\n\t\t\t\tdetail: `New-action recall in ## Done ${formatScore(score)} below ${ACTIONS_RECALL_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { ok: failures.length === 0, failures };\n}\n\nexport function isCompactionSummaryStructurallyUsable(summary: string): boolean {\n\tif (summary.trim().length === 0) return false;\n\tconst sections = extractSections(summary);\n\treturn (\n\t\tsections[SECTION_ACTIVE_TASK] !== undefined ||\n\t\tsections[SECTION_FILES] !== undefined ||\n\t\tsections[SECTION_DONE] !== undefined ||\n\t\tsections[SECTION_WORKING_SET] !== undefined ||\n\t\tsections[SECTION_OPEN_PROBLEMS] !== undefined\n\t);\n}\n\nexport function deterministicallyFillSummaryGaps(summary: string, facts: CompactionFacts): DeterministicGapFillResult {\n\tif (!isCompactionSummaryStructurallyUsable(summary)) {\n\t\treturn { summary, verification: verifySummary(summary, facts), changed: false };\n\t}\n\n\tconst sections = parseSummarySections(summary);\n\tconst sectionByName = new Map<string, ParsedSummarySection>();\n\tconst extraSections: ParsedSummarySection[] = [];\n\tfor (const section of sections) {\n\t\tif (REQUIRED_SUMMARY_SECTIONS.some((required) => required.normalized === section.normalized)) {\n\t\t\tconst existing = sectionByName.get(section.normalized);\n\t\t\tif (existing) {\n\t\t\t\texisting.lines.push(...section.lines);\n\t\t\t} else {\n\t\t\t\tsectionByName.set(section.normalized, section);\n\t\t\t}\n\t\t} else {\n\t\t\textraSections.push(section);\n\t\t}\n\t}\n\n\tfor (const required of REQUIRED_SUMMARY_SECTIONS) {\n\t\tif (!sectionByName.has(required.normalized)) {\n\t\t\tsectionByName.set(required.normalized, {\n\t\t\t\theading: required.heading,\n\t\t\t\tnormalized: required.normalized,\n\t\t\t\tlevel: required.level,\n\t\t\t\tlines: [\"(none)\"],\n\t\t\t});\n\t\t}\n\t}\n\n\tremoveCancelledWorkLines(sectionByName, facts);\n\n\tif (facts.activeTaskSource) {\n\t\tconst activeTask = sectionByName.get(SECTION_ACTIVE_TASK)!;\n\t\tif (\n\t\t\tcontainment(tokenSet(facts.activeTaskSource), tokenSet(activeTask.lines.join(\"\\n\"))) <\n\t\t\tACTIVE_TASK_CONTAINMENT_THRESHOLD\n\t\t) {\n\t\t\tappendContentLine(activeTask.lines, `User: ${facts.activeTaskSource}`);\n\t\t}\n\t}\n\n\tconst mandatoryRules = sectionByName.get(SECTION_MANDATORY_RULES)!;\n\tfor (const rule of facts.prohibitions) {\n\t\tif (containment(tokenSet(rule), tokenSet(mandatoryRules.lines.join(\"\\n\"))) < MANDATORY_RULES_RECALL_THRESHOLD) {\n\t\t\tappendContentLine(mandatoryRules.lines, `- ${rule}`);\n\t\t}\n\t}\n\n\tconst workingSet = sectionByName.get(SECTION_WORKING_SET)!;\n\tfor (const file of facts.workingSet) {\n\t\tif (!workingSet.lines.join(\"\\n\").includes(file.path)) {\n\t\t\tappendContentLine(workingSet.lines, `- ${file.path} — ${file.note || file.kind}`);\n\t\t}\n\t}\n\n\tconst files = sectionByName.get(SECTION_FILES)!;\n\tfor (const file of facts.files) {\n\t\tif (!files.lines.join(\"\\n\").includes(file.path)) {\n\t\t\tappendContentLine(files.lines, `- ${file.path}`);\n\t\t}\n\t}\n\n\tconst openProblems = sectionByName.get(SECTION_OPEN_PROBLEMS)!;\n\tfor (const error of facts.errorFacts) {\n\t\tconst required = `${error.operation}: ${error.error}`;\n\t\tif (containment(tokenSet(required), tokenSet(openProblems.lines.join(\"\\n\"))) < OPEN_ERRORS_RECALL_THRESHOLD) {\n\t\t\tappendContentLine(openProblems.lines, `- ${required}`);\n\t\t}\n\t}\n\n\tconst done = sectionByName.get(SECTION_DONE)!;\n\tconst doneText = done.lines.join(\"\\n\");\n\tif (\n\t\tfacts.actions.length > 0 &&\n\t\tcontainment(tokenSet(facts.actions.join(\"\\n\")), tokenSet(doneText)) < ACTIONS_RECALL_THRESHOLD\n\t) {\n\t\tlet nextNumber = findNextDoneNumber(done.lines);\n\t\tfor (const action of facts.actions) {\n\t\t\tif (done.lines.join(\"\\n\").includes(action)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tappendContentLine(done.lines, `${nextNumber}. ${action}`);\n\t\t\tnextNumber++;\n\t\t}\n\t}\n\n\tconst filledSummary = renderSummarySections(sectionByName, extraSections);\n\treturn {\n\t\tsummary: filledSummary,\n\t\tverification: verifySummary(filledSummary, facts),\n\t\tchanged: filledSummary !== summary,\n\t};\n}\n\nexport function buildRetryPrompt(report: VerificationReport, previousAttempt?: string): string {\n\tconst failures = report.failures.map((failure) => `${failure.check}: ${failure.detail}`).join(\"; \");\n\tconst previous = previousAttempt ? `\\n\\n<previous-attempt>\\n${previousAttempt}\\n</previous-attempt>` : \"\";\n\treturn `Your previous checkpoint failed verification: ${failures}. Fix ONLY these omissions.${previous}`;\n}\n\nfunction parseSummarySections(summary: string): ParsedSummarySection[] {\n\tconst sections: ParsedSummarySection[] = [];\n\tlet current: ParsedSummarySection | undefined;\n\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tcurrent = {\n\t\t\t\theading: match[2],\n\t\t\t\tnormalized: normalizeHeading(match[2]),\n\t\t\t\tlevel: match[1] as \"##\" | \"###\",\n\t\t\t\tlines: [],\n\t\t\t};\n\t\t\tsections.push(current);\n\t\t\tcontinue;\n\t\t}\n\t\tif (current) {\n\t\t\tcurrent.lines.push(line);\n\t\t}\n\t}\n\n\treturn sections;\n}\n\nfunction renderSummarySections(\n\tsectionByName: Map<string, ParsedSummarySection>,\n\textraSections: ParsedSummarySection[],\n): string {\n\tconst rendered: string[] = [];\n\tfor (const required of REQUIRED_SUMMARY_SECTIONS) {\n\t\tconst section = sectionByName.get(required.normalized)!;\n\t\trendered.push(`${required.level} ${required.heading}`);\n\t\tconst body = normalizeSectionLines(section.lines);\n\t\trendered.push(...body);\n\t\trendered.push(\"\");\n\t}\n\tfor (const section of extraSections) {\n\t\trendered.push(`${section.level} ${section.heading}`);\n\t\trendered.push(...normalizeSectionLines(section.lines));\n\t\trendered.push(\"\");\n\t}\n\treturn rendered.join(\"\\n\").trimEnd();\n}\n\nfunction normalizeSectionLines(lines: string[]): string[] {\n\tconst trimmed = lines.map((line) => line.trimEnd());\n\twhile (trimmed.length > 0 && trimmed[0].trim() === \"\") trimmed.shift();\n\twhile (trimmed.length > 0 && trimmed[trimmed.length - 1].trim() === \"\") trimmed.pop();\n\treturn trimmed.length > 0 ? trimmed : [\"(none)\"];\n}\n\nfunction appendContentLine(lines: string[], line: string): void {\n\tconst normalized = normalizeSectionLines(lines).filter((existing) => existing.trim() !== \"(none)\");\n\tnormalized.push(line);\n\tlines.length = 0;\n\tlines.push(...normalized);\n}\n\nfunction findNextDoneNumber(lines: string[]): number {\n\tlet max = 0;\n\tfor (const line of lines) {\n\t\tconst match = /^\\s*(\\d+)\\./.exec(line);\n\t\tif (!match) continue;\n\t\tmax = Math.max(max, Number(match[1]));\n\t}\n\treturn max + 1;\n}\n\nfunction removeCancelledWorkLines(sectionByName: Map<string, ParsedSummarySection>, facts: CompactionFacts): void {\n\tif (!facts.cancelledText) return;\n\tconst factPathTokens = tokenSet(facts.files.map((file) => file.path).join(\"\\n\"));\n\tconst cancelledTokens = new Set([...tokenSet(facts.cancelledText)].filter((token) => !factPathTokens.has(token)));\n\tif (cancelledTokens.size === 0) return;\n\n\tfor (const section of sectionByName.values()) {\n\t\tif (section.normalized === SECTION_MANDATORY_RULES) continue;\n\t\tsection.lines = section.lines.filter((line) => !lineShouldBeDroppedAsCancelledWork(line, cancelledTokens));\n\t}\n}\n\nfunction lineShouldBeDroppedAsCancelledWork(line: string, cancelledTokens: Set<string>): boolean {\n\tconst lineTokens = tokenSet(line);\n\tif (lineTokens.size === 0) return false;\n\tlet overlap = 0;\n\tfor (const token of lineTokens) {\n\t\tif (cancelledTokens.has(token)) overlap++;\n\t}\n\treturn overlap >= 2 && overlap / lineTokens.size >= 0.6;\n}\n\nexport function tokenSet(text: string): Set<string> {\n\treturn new Set(\n\t\ttext\n\t\t\t.toLowerCase()\n\t\t\t.split(/[^a-z0-9_./-]+/)\n\t\t\t.map((token) => token.trim())\n\t\t\t.filter((token) => token.length >= 3),\n\t);\n}\n\nexport function containment(needle: Set<string>, hay: Set<string>): number {\n\tif (needle.size === 0) {\n\t\treturn 1;\n\t}\n\tlet hits = 0;\n\tfor (const token of needle) {\n\t\tif (hay.has(token)) {\n\t\t\thits += 1;\n\t\t}\n\t}\n\treturn hits / needle.size;\n}\n\nexport function jaccard(a: Set<string>, b: Set<string>): number {\n\tif (a.size === 0 && b.size === 0) {\n\t\treturn 1;\n\t}\n\tlet intersection = 0;\n\tfor (const token of a) {\n\t\tif (b.has(token)) {\n\t\t\tintersection += 1;\n\t\t}\n\t}\n\tconst union = new Set([...a, ...b]).size;\n\treturn union === 0 ? 1 : intersection / union;\n}\n\nfunction factsAreEmpty(facts: CompactionFacts): boolean {\n\treturn (\n\t\tfacts.files.length === 0 &&\n\t\tfacts.workingSet.length === 0 &&\n\t\tfacts.actions.length === 0 &&\n\t\tfacts.errorFacts.length === 0 &&\n\t\tfacts.prohibitions.length === 0 &&\n\t\tfacts.cancelledText === \"\" &&\n\t\tfacts.activeTaskSource === \"\"\n\t);\n}\n\nfunction extractSections(summary: string): Record<string, string> {\n\tconst sections: Record<string, string> = {};\n\tlet current: string | undefined;\n\tlet bucket: string[] = [];\n\n\tconst flush = (): void => {\n\t\tif (current) {\n\t\t\tsections[current] = bucket.join(\"\\n\").trim();\n\t\t}\n\t\tbucket = [];\n\t};\n\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(?:##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tflush();\n\t\t\tcurrent = normalizeHeading(match[1]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (current) {\n\t\t\tbucket.push(line);\n\t\t}\n\t}\n\tflush();\n\treturn sections;\n}\n\nfunction removeSection(summary: string, heading: string): string {\n\tconst normalizedHeading = normalizeHeading(heading);\n\tconst kept: string[] = [];\n\tlet skipping = false;\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(?:##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tskipping = normalizeHeading(match[1]) === normalizedHeading;\n\t\t\tif (skipping) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (!skipping) {\n\t\t\tkept.push(line);\n\t\t}\n\t}\n\treturn kept.join(\"\\n\");\n}\n\nfunction normalizeHeading(heading: string): string {\n\treturn heading.trim().toLowerCase();\n}\n\nfunction formatScore(score: number): string {\n\treturn score.toFixed(2);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"verification.js","sourceRoot":"","sources":["../../src/compaction/verification.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAwB,MAAM,iBAAiB,CAAC;AAkBrF,MAAM,CAAC,MAAM,2BAA2B,GAAG,GAAG,CAAC;AAC/C,MAAM,CAAC,MAAM,iCAAiC,GAAG,GAAG,CAAC;AACrD,MAAM,CAAC,MAAM,gCAAgC,GAAG,GAAG,CAAC;AACpD,MAAM,CAAC,MAAM,gCAAgC,GAAG,GAAG,CAAC;AACpD,MAAM,CAAC,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAC5C,MAAM,CAAC,MAAM,4BAA4B,GAAG,GAAG,CAAC;AAEhD,MAAM,aAAa,GAAG,OAAO,CAAC;AAC9B,MAAM,mBAAmB,GAAG,aAAa,CAAC;AAC1C,MAAM,qBAAqB,GAAG,eAAe,CAAC;AAC9C,MAAM,YAAY,GAAG,MAAM,CAAC;AAC5B,MAAM,mBAAmB,GAAG,aAAa,CAAC;AAC1C,MAAM,uBAAuB,GAAG,iBAAiB,CAAC;AAClD,MAAM,qBAAqB,GAAG,eAAe,CAAC;AAC9C,MAAM,mBAAmB,GAAG,2BAA2B,CAAC;AACxD,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;AASpD,MAAM,yBAAyB,GAAwE;IACtG,EAAE,OAAO,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AAE,CAAC;YACf,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjB,CAAC;IACF,CAAC;IACD,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACvB;AAED,SAAS,gBAAgB,CAAC,OAAe,EAAU;IAClD,OAAO,OAAO,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AAAA,CACpC;AAED,SAAS,WAAW,CAAC,KAAa,EAAU;IAC3C,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAAA,CACxB","sourcesContent":["import { ACTIVE_TASK_SOURCE_MAX_CHARS, type CompactionFacts } from \"./extraction.ts\";\n\nexport interface VerificationFailure {\n\tcheck: string;\n\tdetail: string;\n}\n\nexport interface VerificationReport {\n\tok: boolean;\n\tfailures: VerificationFailure[];\n}\n\nexport interface DeterministicGapFillResult {\n\tsummary: string;\n\tverification: VerificationReport;\n\tchanged: boolean;\n}\n\nexport const FILES_READ_RECALL_THRESHOLD = 0.8;\nexport const ACTIVE_TASK_CONTAINMENT_THRESHOLD = 0.9;\nexport const MANDATORY_RULES_RECALL_THRESHOLD = 0.7;\nexport const CANCELLED_WORK_DROPPED_THRESHOLD = 0.1;\nexport const ACTIONS_RECALL_THRESHOLD = 0.6;\nexport const OPEN_ERRORS_RECALL_THRESHOLD = 0.7;\n\nconst SECTION_FILES = \"files\";\nconst SECTION_WORKING_SET = \"working set\";\nconst SECTION_OPEN_PROBLEMS = \"open problems\";\nconst SECTION_DONE = \"done\";\nconst SECTION_ACTIVE_TASK = \"active task\";\nconst SECTION_MANDATORY_RULES = \"mandatory rules\";\nconst SECTION_KEY_DECISIONS = \"key decisions\";\nconst SECTION_CONSTRAINTS = \"constraints & preferences\";\nconst SECTION_CRITICAL_CONTEXT = \"critical context\";\n\ninterface ParsedSummarySection {\n\theading: string;\n\tnormalized: string;\n\tlevel: \"##\" | \"###\";\n\tlines: string[];\n}\n\nconst REQUIRED_SUMMARY_SECTIONS: Array<{ heading: string; normalized: string; level: \"##\" | \"###\" }> = [\n\t{ heading: \"Active Task\", normalized: SECTION_ACTIVE_TASK, level: \"##\" },\n\t{ heading: \"Mandatory Rules\", normalized: SECTION_MANDATORY_RULES, level: \"###\" },\n\t{ heading: \"Working Set\", normalized: SECTION_WORKING_SET, level: \"##\" },\n\t{ heading: \"Files\", normalized: SECTION_FILES, level: \"##\" },\n\t{ heading: \"Open Problems\", normalized: SECTION_OPEN_PROBLEMS, level: \"##\" },\n\t{ heading: \"Done\", normalized: SECTION_DONE, level: \"##\" },\n\t{ heading: \"Key Decisions\", normalized: SECTION_KEY_DECISIONS, level: \"##\" },\n\t{ heading: \"Constraints & Preferences\", normalized: SECTION_CONSTRAINTS, level: \"##\" },\n\t{ heading: \"Critical Context\", normalized: SECTION_CRITICAL_CONTEXT, level: \"##\" },\n];\n\nexport function verifySummary(summary: string, facts: CompactionFacts): VerificationReport {\n\tif (factsAreEmpty(facts)) {\n\t\treturn { ok: true, failures: [] };\n\t}\n\n\tconst sections = extractSections(summary);\n\tconst failures: VerificationFailure[] = [];\n\tconst filesSection = sections[SECTION_FILES] ?? \"\";\n\tconst workingSetSection = sections[SECTION_WORKING_SET] ?? \"\";\n\tconst openProblemsSection = sections[SECTION_OPEN_PROBLEMS] ?? \"\";\n\tconst doneSection = sections[SECTION_DONE] ?? \"\";\n\tconst activeTaskSection = sections[SECTION_ACTIVE_TASK] ?? \"\";\n\tconst mandatoryRulesSection = sections[SECTION_MANDATORY_RULES] ?? \"\";\n\n\tconst modifiedFiles = facts.files.filter((file) => file.kind !== \"read\");\n\tconst missingModifiedFiles = modifiedFiles.map((file) => file.path).filter((path) => !filesSection.includes(path));\n\tif (missingModifiedFiles.length > 0) {\n\t\tfailures.push({\n\t\t\tcheck: \"files-modified-recall\",\n\t\t\tdetail: `Missing modified/created files in ## Files: ${missingModifiedFiles.join(\", \")}`,\n\t\t});\n\t}\n\n\tconst workingSetPaths = facts.workingSet.map((file) => file.path);\n\tconst missingWorkingSetPaths = workingSetPaths.filter((path) => !workingSetSection.includes(path));\n\tif (missingWorkingSetPaths.length > 0) {\n\t\tfailures.push({\n\t\t\tcheck: \"working-set-recall\",\n\t\t\tdetail: `Missing working-set files in ## Working Set: ${missingWorkingSetPaths.join(\", \")}`,\n\t\t});\n\t}\n\n\tconst readPaths = facts.files.filter((file) => file.kind === \"read\").map((file) => file.path);\n\tif (readPaths.length > 0) {\n\t\tconst score = containment(tokenSet(readPaths.join(\"\\n\")), tokenSet(filesSection));\n\t\tif (score < FILES_READ_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"files-read-recall\",\n\t\t\t\tdetail: `Read file recall ${formatScore(score)} below ${FILES_READ_RECALL_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.activeTaskSource) {\n\t\tconst score = containment(\n\t\t\ttokenSet(facts.activeTaskSource.slice(0, ACTIVE_TASK_SOURCE_MAX_CHARS)),\n\t\t\ttokenSet(activeTaskSection),\n\t\t);\n\t\tif (score < ACTIVE_TASK_CONTAINMENT_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"active-task-containment\",\n\t\t\t\tdetail: `Active task containment ${formatScore(score)} below ${ACTIVE_TASK_CONTAINMENT_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const prohibition of facts.prohibitions) {\n\t\tconst score = containment(tokenSet(prohibition), tokenSet(mandatoryRulesSection));\n\t\tif (score < MANDATORY_RULES_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"mandatory-rules-recall\",\n\t\t\t\tdetail: `Missing mandatory rule: ${prohibition}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.cancelledText) {\n\t\tconst summaryOutsideMandatoryRules = removeSection(summary, SECTION_MANDATORY_RULES);\n\t\t// File paths from the facts are REQUIRED elsewhere (files-modified/read-recall demand them\n\t\t// in ## Files), so counting them as cancelled-work leakage would make the two gates\n\t\t// unsatisfiable together whenever a reversal message references a touched file.\n\t\tconst factPathTokens = tokenSet(facts.files.map((file) => file.path).join(\"\\n\"));\n\t\tconst cancelledTokens = new Set([...tokenSet(facts.cancelledText)].filter((token) => !factPathTokens.has(token)));\n\t\tconst score = containment(cancelledTokens, tokenSet(summaryOutsideMandatoryRules));\n\t\tif (score > CANCELLED_WORK_DROPPED_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"cancelled-work-dropped\",\n\t\t\t\tdetail: `Cancelled work leakage ${formatScore(score)} above ${CANCELLED_WORK_DROPPED_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const error of facts.errorFacts) {\n\t\tconst score = containment(tokenSet(`${error.operation}: ${error.error}`), tokenSet(openProblemsSection));\n\t\tif (score < OPEN_ERRORS_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"open-errors-recall\",\n\t\t\t\tdetail: `Open error recall ${formatScore(score)} below ${OPEN_ERRORS_RECALL_THRESHOLD}: ${error.operation}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tif (facts.actions.length > 0) {\n\t\t// Asymmetric on purpose: the update path carries prior ## Done items forward (bounded), so a\n\t\t// symmetric overlap metric would punish faithful carry-over — the gate demands only that the\n\t\t// NEW span's actions are recalled in ## Done, however much history rides alongside them.\n\t\tconst score = containment(tokenSet(facts.actions.join(\"\\n\")), tokenSet(doneSection));\n\t\tif (score < ACTIONS_RECALL_THRESHOLD) {\n\t\t\tfailures.push({\n\t\t\t\tcheck: \"actions-recall\",\n\t\t\t\tdetail: `New-action recall in ## Done ${formatScore(score)} below ${ACTIONS_RECALL_THRESHOLD}`,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn { ok: failures.length === 0, failures };\n}\n\nexport function isCompactionSummaryStructurallyUsable(summary: string): boolean {\n\tif (summary.trim().length === 0) return false;\n\tconst sections = extractSections(summary);\n\treturn (\n\t\tsections[SECTION_ACTIVE_TASK] !== undefined ||\n\t\tsections[SECTION_FILES] !== undefined ||\n\t\tsections[SECTION_DONE] !== undefined ||\n\t\tsections[SECTION_WORKING_SET] !== undefined ||\n\t\tsections[SECTION_OPEN_PROBLEMS] !== undefined\n\t);\n}\n\nexport function deterministicallyFillSummaryGaps(summary: string, facts: CompactionFacts): DeterministicGapFillResult {\n\tif (!isCompactionSummaryStructurallyUsable(summary)) {\n\t\treturn { summary, verification: verifySummary(summary, facts), changed: false };\n\t}\n\n\tconst sections = parseSummarySections(summary);\n\tconst sectionByName = new Map<string, ParsedSummarySection>();\n\tconst extraSections: ParsedSummarySection[] = [];\n\tfor (const section of sections) {\n\t\tif (REQUIRED_SUMMARY_SECTIONS.some((required) => required.normalized === section.normalized)) {\n\t\t\tconst existing = sectionByName.get(section.normalized);\n\t\t\tif (existing) {\n\t\t\t\texisting.lines.push(...section.lines);\n\t\t\t} else {\n\t\t\t\tsectionByName.set(section.normalized, section);\n\t\t\t}\n\t\t} else {\n\t\t\textraSections.push(section);\n\t\t}\n\t}\n\n\tfor (const required of REQUIRED_SUMMARY_SECTIONS) {\n\t\tif (!sectionByName.has(required.normalized)) {\n\t\t\tsectionByName.set(required.normalized, {\n\t\t\t\theading: required.heading,\n\t\t\t\tnormalized: required.normalized,\n\t\t\t\tlevel: required.level,\n\t\t\t\tlines: [\"(none)\"],\n\t\t\t});\n\t\t}\n\t}\n\n\tremoveCancelledWorkLines(sectionByName, facts);\n\n\tif (facts.activeTaskSource) {\n\t\tconst activeTask = sectionByName.get(SECTION_ACTIVE_TASK)!;\n\t\tif (\n\t\t\tcontainment(tokenSet(facts.activeTaskSource), tokenSetFromLines(activeTask.lines)) <\n\t\t\tACTIVE_TASK_CONTAINMENT_THRESHOLD\n\t\t) {\n\t\t\tappendContentLine(activeTask.lines, `User: ${facts.activeTaskSource}`);\n\t\t}\n\t}\n\n\tconst mandatoryRules = sectionByName.get(SECTION_MANDATORY_RULES)!;\n\tfor (const rule of facts.prohibitions) {\n\t\tif (containment(tokenSet(rule), tokenSetFromLines(mandatoryRules.lines)) < MANDATORY_RULES_RECALL_THRESHOLD) {\n\t\t\tappendContentLine(mandatoryRules.lines, `- ${rule}`);\n\t\t}\n\t}\n\n\tconst workingSet = sectionByName.get(SECTION_WORKING_SET)!;\n\tfor (const file of facts.workingSet) {\n\t\tif (!sectionLinesContain(workingSet.lines, file.path)) {\n\t\t\tappendContentLine(workingSet.lines, `- ${file.path} — ${file.note || file.kind}`);\n\t\t}\n\t}\n\n\tconst files = sectionByName.get(SECTION_FILES)!;\n\tfor (const file of facts.files) {\n\t\tif (!sectionLinesContain(files.lines, file.path)) {\n\t\t\tappendContentLine(files.lines, `- ${file.path}`);\n\t\t}\n\t}\n\n\tconst openProblems = sectionByName.get(SECTION_OPEN_PROBLEMS)!;\n\tfor (const error of facts.errorFacts) {\n\t\tconst required = `${error.operation}: ${error.error}`;\n\t\tif (containment(tokenSet(required), tokenSetFromLines(openProblems.lines)) < OPEN_ERRORS_RECALL_THRESHOLD) {\n\t\t\tappendContentLine(openProblems.lines, `- ${required}`);\n\t\t}\n\t}\n\n\tconst done = sectionByName.get(SECTION_DONE)!;\n\tif (\n\t\tfacts.actions.length > 0 &&\n\t\tcontainment(tokenSet(facts.actions.join(\"\\n\")), tokenSetFromLines(done.lines)) < ACTIONS_RECALL_THRESHOLD\n\t) {\n\t\tlet nextNumber = findNextDoneNumber(done.lines);\n\t\tfor (const action of facts.actions) {\n\t\t\tif (sectionLinesContain(done.lines, action)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tappendContentLine(done.lines, `${nextNumber}. ${action}`);\n\t\t\tnextNumber++;\n\t\t}\n\t}\n\n\tconst filledSummary = renderSummarySections(sectionByName, extraSections);\n\treturn {\n\t\tsummary: filledSummary,\n\t\tverification: verifySummary(filledSummary, facts),\n\t\tchanged: filledSummary !== summary,\n\t};\n}\n\nexport function buildRetryPrompt(report: VerificationReport, previousAttempt?: string): string {\n\tconst failures = report.failures.map((failure) => `${failure.check}: ${failure.detail}`).join(\"; \");\n\tconst previous = previousAttempt ? `\\n\\n<previous-attempt>\\n${previousAttempt}\\n</previous-attempt>` : \"\";\n\treturn `Your previous checkpoint failed verification: ${failures}. Fix ONLY these omissions.${previous}`;\n}\n\nfunction parseSummarySections(summary: string): ParsedSummarySection[] {\n\tconst sections: ParsedSummarySection[] = [];\n\tlet current: ParsedSummarySection | undefined;\n\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tcurrent = {\n\t\t\t\theading: match[2],\n\t\t\t\tnormalized: normalizeHeading(match[2]),\n\t\t\t\tlevel: match[1] as \"##\" | \"###\",\n\t\t\t\tlines: [],\n\t\t\t};\n\t\t\tsections.push(current);\n\t\t\tcontinue;\n\t\t}\n\t\tif (current) {\n\t\t\tcurrent.lines.push(line);\n\t\t}\n\t}\n\n\treturn sections;\n}\n\nfunction renderSummarySections(\n\tsectionByName: Map<string, ParsedSummarySection>,\n\textraSections: ParsedSummarySection[],\n): string {\n\tconst rendered: string[] = [];\n\tfor (const required of REQUIRED_SUMMARY_SECTIONS) {\n\t\tconst section = sectionByName.get(required.normalized)!;\n\t\trendered.push(`${required.level} ${required.heading}`);\n\t\tconst body = normalizeSectionLines(section.lines);\n\t\trendered.push(...body);\n\t\trendered.push(\"\");\n\t}\n\tfor (const section of extraSections) {\n\t\trendered.push(`${section.level} ${section.heading}`);\n\t\trendered.push(...normalizeSectionLines(section.lines));\n\t\trendered.push(\"\");\n\t}\n\treturn rendered.join(\"\\n\").trimEnd();\n}\n\nfunction normalizeSectionLines(lines: string[]): string[] {\n\tlet start = 0;\n\tlet end = lines.length;\n\twhile (start < end && lines[start].trim() === \"\") start++;\n\twhile (end > start && lines[end - 1].trim() === \"\") end--;\n\tif (start === end) return [\"(none)\"];\n\treturn lines.slice(start, end).map((line) => line.trimEnd());\n}\n\nfunction sectionLinesContain(lines: readonly string[], value: string): boolean {\n\treturn lines.some((line) => line.includes(value));\n}\n\nfunction tokenSetFromLines(lines: readonly string[]): Set<string> {\n\tconst tokens = new Set<string>();\n\tfor (const line of lines) {\n\t\tfor (const token of tokenSet(line)) tokens.add(token);\n\t}\n\treturn tokens;\n}\n\nfunction appendContentLine(lines: string[], line: string): void {\n\tconst normalized = normalizeSectionLines(lines).filter((existing) => existing.trim() !== \"(none)\");\n\tnormalized.push(line);\n\tlines.length = 0;\n\tlines.push(...normalized);\n}\n\nfunction findNextDoneNumber(lines: string[]): number {\n\tlet max = 0;\n\tfor (const line of lines) {\n\t\tconst match = /^\\s*(\\d+)\\./.exec(line);\n\t\tif (!match) continue;\n\t\tmax = Math.max(max, Number(match[1]));\n\t}\n\treturn max + 1;\n}\n\nfunction removeCancelledWorkLines(sectionByName: Map<string, ParsedSummarySection>, facts: CompactionFacts): void {\n\tif (!facts.cancelledText) return;\n\tconst factPathTokens = tokenSet(facts.files.map((file) => file.path).join(\"\\n\"));\n\tconst cancelledTokens = new Set([...tokenSet(facts.cancelledText)].filter((token) => !factPathTokens.has(token)));\n\tif (cancelledTokens.size === 0) return;\n\n\tfor (const section of sectionByName.values()) {\n\t\tif (section.normalized === SECTION_MANDATORY_RULES) continue;\n\t\tsection.lines = section.lines.filter((line) => !lineShouldBeDroppedAsCancelledWork(line, cancelledTokens));\n\t}\n}\n\nfunction lineShouldBeDroppedAsCancelledWork(line: string, cancelledTokens: Set<string>): boolean {\n\tconst lineTokens = tokenSet(line);\n\tif (lineTokens.size === 0) return false;\n\tlet overlap = 0;\n\tfor (const token of lineTokens) {\n\t\tif (cancelledTokens.has(token)) overlap++;\n\t}\n\treturn overlap >= 2 && overlap / lineTokens.size >= 0.6;\n}\n\nexport function tokenSet(text: string): Set<string> {\n\treturn new Set(\n\t\ttext\n\t\t\t.toLowerCase()\n\t\t\t.split(/[^a-z0-9_./-]+/)\n\t\t\t.map((token) => token.trim())\n\t\t\t.filter((token) => token.length >= 3),\n\t);\n}\n\nexport function containment(needle: Set<string>, hay: Set<string>): number {\n\tif (needle.size === 0) {\n\t\treturn 1;\n\t}\n\tlet hits = 0;\n\tfor (const token of needle) {\n\t\tif (hay.has(token)) {\n\t\t\thits += 1;\n\t\t}\n\t}\n\treturn hits / needle.size;\n}\n\nexport function jaccard(a: Set<string>, b: Set<string>): number {\n\tif (a.size === 0 && b.size === 0) {\n\t\treturn 1;\n\t}\n\tlet intersection = 0;\n\tfor (const token of a) {\n\t\tif (b.has(token)) {\n\t\t\tintersection += 1;\n\t\t}\n\t}\n\tconst union = new Set([...a, ...b]).size;\n\treturn union === 0 ? 1 : intersection / union;\n}\n\nfunction factsAreEmpty(facts: CompactionFacts): boolean {\n\treturn (\n\t\tfacts.files.length === 0 &&\n\t\tfacts.workingSet.length === 0 &&\n\t\tfacts.actions.length === 0 &&\n\t\tfacts.errorFacts.length === 0 &&\n\t\tfacts.prohibitions.length === 0 &&\n\t\tfacts.cancelledText === \"\" &&\n\t\tfacts.activeTaskSource === \"\"\n\t);\n}\n\nfunction extractSections(summary: string): Record<string, string> {\n\tconst sections: Record<string, string> = {};\n\tlet current: string | undefined;\n\tlet bucket: string[] = [];\n\n\tconst flush = (): void => {\n\t\tif (current) {\n\t\t\tsections[current] = bucket.join(\"\\n\").trim();\n\t\t}\n\t\tbucket = [];\n\t};\n\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(?:##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tflush();\n\t\t\tcurrent = normalizeHeading(match[1]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (current) {\n\t\t\tbucket.push(line);\n\t\t}\n\t}\n\tflush();\n\treturn sections;\n}\n\nfunction removeSection(summary: string, heading: string): string {\n\tconst normalizedHeading = normalizeHeading(heading);\n\tconst kept: string[] = [];\n\tlet skipping = false;\n\tfor (const line of summary.split(/\\r?\\n/)) {\n\t\tconst match = /^(?:##|###)\\s+(.+?)\\s*$/.exec(line);\n\t\tif (match) {\n\t\t\tskipping = normalizeHeading(match[1]) === normalizedHeading;\n\t\t\tif (skipping) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (!skipping) {\n\t\t\tkept.push(line);\n\t\t}\n\t}\n\treturn kept.join(\"\\n\");\n}\n\nfunction normalizeHeading(heading: string): string {\n\treturn heading.trim().toLowerCase();\n}\n\nfunction formatScore(score: number): string {\n\treturn score.toFixed(2);\n}\n"]}
|
package/dist/proxy.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EACN,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,OAAO,EACZ,WAAW,EACX,KAAK,KAAK,EAEV,KAAK,mBAAmB,EACxB,KAAK,UAAU,EAEf,MAAM,mBAAmB,CAAC;AAG3B,cAAM,uBAAwB,SAAQ,WAAW,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;IACzF,cASC;CACD;AAED;;GAEG;AACH,MAAM,MAAM,0BAA0B,GACnC;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,GACjB;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAC5C;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC3D;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAAE,GACrE;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAChD;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC/D;IAAE,IAAI,EAAE,cA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OAAO,EAAE,OAAO,EAAE,kBAAkB,GAAG,uBAAuB,CA4HrH","sourcesContent":["/**\n * Proxy stream function for apps that route LLM calls through a server.\n * The server manages auth and proxies requests to LLM providers.\n */\n\n// Internal import for JSON parsing utility\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\ttype Model,\n\tparseStreamingJson,\n\ttype SimpleStreamOptions,\n\ttype StopReason,\n\ttype ToolCall,\n} from \"@caupulican/pi-ai\";\n\n// Create stream class matching ProxyMessageEventStream\nclass ProxyMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") return event.message;\n\t\t\t\tif (event.type === \"error\") return event.error;\n\t\t\t\tthrow new Error(\"Unexpected event type\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/**\n * Proxy event types - server sends these with partial field stripped to reduce bandwidth.\n */\nexport type ProxyAssistantMessageEvent =\n\t| { type: \"start\" }\n\t| { type: \"text_start\"; contentIndex: number }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string }\n\t| { type: \"text_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"thinking_start\"; contentIndex: number }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string }\n\t| { type: \"thinking_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"toolcall_start\"; contentIndex: number; id: string; toolName: string }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string }\n\t| { type: \"toolcall_end\"; contentIndex: number }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\">;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\treason: Extract<StopReason, \"aborted\" | \"error\">;\n\t\t\terrorMessage?: string;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t };\n\ntype ProxySerializableStreamOptions = Pick<\n\tSimpleStreamOptions,\n\t| \"temperature\"\n\t| \"maxTokens\"\n\t| \"reasoning\"\n\t| \"cacheRetention\"\n\t| \"sessionId\"\n\t| \"headers\"\n\t| \"metadata\"\n\t| \"transport\"\n\t| \"thinkingBudgets\"\n\t| \"maxRetryDelayMs\"\n>;\n\nexport interface ProxyStreamOptions extends ProxySerializableStreamOptions {\n\t/** Local abort signal for the proxy request */\n\tsignal?: AbortSignal;\n\t/** Auth token for the proxy server */\n\tauthToken: string;\n\t/** Proxy server URL (e.g., \"https://genai.example.com\") */\n\tproxyUrl: string;\n}\n\n/**\n * Stream function that proxies through a server instead of calling LLM providers directly.\n * The server strips the partial field from delta events to reduce bandwidth.\n * We reconstruct the partial message client-side.\n *\n * Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * streamFn: (model, context, options) =>\n * streamProxy(model, context, {\n * ...options,\n * authToken: await getAuthToken(),\n * proxyUrl: \"https://genai.example.com\",\n * }),\n * });\n * ```\n */\nfunction buildProxyRequestOptions(options: ProxyStreamOptions): ProxySerializableStreamOptions {\n\treturn {\n\t\ttemperature: options.temperature,\n\t\tmaxTokens: options.maxTokens,\n\t\treasoning: options.reasoning,\n\t\tcacheRetention: options.cacheRetention,\n\t\tsessionId: options.sessionId,\n\t\theaders: options.headers,\n\t\tmetadata: options.metadata,\n\t\ttransport: options.transport,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t};\n}\n\nexport function streamProxy(model: Model<any>, context: Context, options: ProxyStreamOptions): ProxyMessageEventStream {\n\tconst stream = new ProxyMessageEventStream();\n\n\t(async () => {\n\t\t// Initialize the partial message that we'll build up from events\n\t\tconst partial: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: \"stop\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t\tlet terminalPushed = false;\n\n\t\tconst abortHandler = () => {\n\t\t\tif (reader) {\n\t\t\t\treader.cancel(\"Request aborted by user\").catch(() => {});\n\t\t\t}\n\t\t};\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener(\"abort\", abortHandler);\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch(`${options.proxyUrl}/api/stream`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${options.authToken}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions: buildProxyRequestOptions(options),\n\t\t\t\t}),\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet errorMessage = `Proxy error: ${response.status} ${response.statusText}`;\n\t\t\t\ttry {\n\t\t\t\t\tconst errorData = (await response.json()) as { error?: string };\n\t\t\t\t\tif (errorData.error) {\n\t\t\t\t\t\terrorMessage = `Proxy error: ${errorData.error}`;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Couldn't parse error response\n\t\t\t\t}\n\t\t\t\tthrow new Error(errorMessage);\n\t\t\t}\n\n\t\t\treader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tif (line.startsWith(\"data: \")) {\n\t\t\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\t\t\tif (data) {\n\t\t\t\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\t\t\tif (event) {\n\t\t\t\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalPushed = true;\n\t\t\t\t\t\t\t\tstream.push(event);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\n\t\t\tif (!terminalPushed) {\n\t\t\t\tpartial.stopReason = \"error\";\n\t\t\t\tpartial.errorMessage = \"stream ended before terminal event\";\n\t\t\t\tstream.push({ type: \"error\", reason: \"error\", error: partial });\n\t\t\t}\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tconst reason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tif (options.signal) {\n\t\t\t\toptions.signal.removeEventListener(\"abort\", abortHandler);\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Process a proxy event and update the partial message.\n */\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.text,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.thinking,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} satisfies ToolCall & { partialJson: string } as ToolCall;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content }; // Trigger reactivity\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\ttoolCall: content,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcase \"done\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\n\t\tcase \"error\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EACN,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC1B,KAAK,OAAO,EACZ,WAAW,EACX,KAAK,KAAK,EAEV,KAAK,mBAAmB,EACxB,KAAK,UAAU,EAEf,MAAM,mBAAmB,CAAC;AAI3B,cAAM,uBAAwB,SAAQ,WAAW,CAAC,qBAAqB,EAAE,gBAAgB,CAAC;IACzF,cASC;CACD;AAED;;GAEG;AACH,MAAM,MAAM,0BAA0B,GACnC;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,GACjB;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAC5C;IAAE,IAAI,EAAE,Y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Aa,GACb,WAAW,GACX,WAAW,GACX,gBAAgB,GAChB,WAAW,GACX,SAAS,GACT,UAAU,GACV,WAAW,GACX,iBAAiB,GACjB,iBAAiB,CACnB,CAAC;AAEF,MAAM,WAAW,kBAAmB,SAAQ,8BAA8B;IACzE,+CAA+C;IAC/C,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,2DAA2D;IAC3D,QAAQ,EAAE,MAAM,CAAC;CACjB;AAoCD,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,kBAAkB,GAAG,uBAAuB,CAgJrH","sourcesContent":["/**\n * Proxy stream function for apps that route LLM calls through a server.\n * The server manages auth and proxies requests to LLM providers.\n */\n\n// Internal import for JSON parsing utility\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\ttype Model,\n\tparseStreamingJson,\n\ttype SimpleStreamOptions,\n\ttype StopReason,\n\ttype ToolCall,\n} from \"@caupulican/pi-ai\";\nimport { StreamingLineDecoder } from \"./utils/streaming-lines.ts\";\n\n// Create stream class matching ProxyMessageEventStream\nclass ProxyMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") return event.message;\n\t\t\t\tif (event.type === \"error\") return event.error;\n\t\t\t\tthrow new Error(\"Unexpected event type\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/**\n * Proxy event types - server sends these with partial field stripped to reduce bandwidth.\n */\nexport type ProxyAssistantMessageEvent =\n\t| { type: \"start\" }\n\t| { type: \"text_start\"; contentIndex: number }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string }\n\t| { type: \"text_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"thinking_start\"; contentIndex: number }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string }\n\t| { type: \"thinking_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"toolcall_start\"; contentIndex: number; id: string; toolName: string }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string }\n\t| { type: \"toolcall_end\"; contentIndex: number }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\">;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\treason: Extract<StopReason, \"aborted\" | \"error\">;\n\t\t\terrorMessage?: string;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t };\n\ntype ProxySerializableStreamOptions = Pick<\n\tSimpleStreamOptions,\n\t| \"temperature\"\n\t| \"maxTokens\"\n\t| \"reasoning\"\n\t| \"cacheRetention\"\n\t| \"sessionId\"\n\t| \"headers\"\n\t| \"metadata\"\n\t| \"transport\"\n\t| \"thinkingBudgets\"\n\t| \"maxRetryDelayMs\"\n>;\n\nexport interface ProxyStreamOptions extends ProxySerializableStreamOptions {\n\t/** Local abort signal for the proxy request */\n\tsignal?: AbortSignal;\n\t/** Auth token for the proxy server */\n\tauthToken: string;\n\t/** Proxy server URL (e.g., \"https://genai.example.com\") */\n\tproxyUrl: string;\n}\n\n/**\n * Stream function that proxies through a server instead of calling LLM providers directly.\n * The server strips the partial field from delta events to reduce bandwidth.\n * We reconstruct the partial message client-side.\n *\n * Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * streamFn: (model, context, options) =>\n * streamProxy(model, context, {\n * ...options,\n * authToken: await getAuthToken(),\n * proxyUrl: \"https://genai.example.com\",\n * }),\n * });\n * ```\n */\nfunction buildProxyRequestOptions(options: ProxyStreamOptions): ProxySerializableStreamOptions {\n\treturn {\n\t\ttemperature: options.temperature,\n\t\tmaxTokens: options.maxTokens,\n\t\treasoning: options.reasoning,\n\t\tcacheRetention: options.cacheRetention,\n\t\tsessionId: options.sessionId,\n\t\theaders: options.headers,\n\t\tmetadata: options.metadata,\n\t\ttransport: options.transport,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t};\n}\n\nexport function streamProxy(model: Model<any>, context: Context, options: ProxyStreamOptions): ProxyMessageEventStream {\n\tconst stream = new ProxyMessageEventStream();\n\n\t(async () => {\n\t\t// Initialize the partial message that we'll build up from events\n\t\tconst partial: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: \"stop\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t\tlet terminalPushed = false;\n\n\t\tconst abortHandler = () => {\n\t\t\tif (reader) {\n\t\t\t\treader.cancel(\"Request aborted by user\").catch(() => {});\n\t\t\t}\n\t\t};\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener(\"abort\", abortHandler);\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch(`${options.proxyUrl}/api/stream`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${options.authToken}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions: buildProxyRequestOptions(options),\n\t\t\t\t}),\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet errorMessage = `Proxy error: ${response.status} ${response.statusText}`;\n\t\t\t\ttry {\n\t\t\t\t\tconst errorData = (await response.json()) as { error?: string };\n\t\t\t\t\tif (errorData.error) {\n\t\t\t\t\t\terrorMessage = `Proxy error: ${errorData.error}`;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Couldn't parse error response\n\t\t\t\t}\n\t\t\t\tthrow new Error(errorMessage);\n\t\t\t}\n\n\t\t\treader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tconst lines = new StreamingLineDecoder(64 * 1024 * 1024);\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tfor (const line of lines.push(decoder.decode(value, { stream: true }))) {\n\t\t\t\t\tif (line.startsWith(\"data: \")) {\n\t\t\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\t\t\tif (data) {\n\t\t\t\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\t\t\tif (event) {\n\t\t\t\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalPushed = true;\n\t\t\t\t\t\t\t\tstream.push(event);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const line of lines.push(decoder.decode())) {\n\t\t\t\tif (!line.startsWith(\"data: \")) continue;\n\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\tif (!data) continue;\n\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\tif (event) {\n\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalPushed = true;\n\t\t\t\t\tstream.push(event);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst finalLine = lines.finish();\n\t\t\tif (finalLine?.startsWith(\"data: \")) {\n\t\t\t\tconst data = finalLine.slice(6).trim();\n\t\t\t\tif (data) {\n\t\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\tif (event) {\n\t\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalPushed = true;\n\t\t\t\t\t\tstream.push(event);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\n\t\t\tif (!terminalPushed) {\n\t\t\t\tpartial.stopReason = \"error\";\n\t\t\t\tpartial.errorMessage = \"stream ended before terminal event\";\n\t\t\t\tstream.push({ type: \"error\", reason: \"error\", error: partial });\n\t\t\t}\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tconst reason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tif (options.signal) {\n\t\t\t\toptions.signal.removeEventListener(\"abort\", abortHandler);\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Process a proxy event and update the partial message.\n */\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.text,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.thinking,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} satisfies ToolCall & { partialJson: string } as ToolCall;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content }; // Trigger reactivity\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\ttoolCall: content,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcase \"done\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\n\t\tcase \"error\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n"]}
|
package/dist/proxy.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
// Internal import for JSON parsing utility
|
|
6
6
|
import { EventStream, parseStreamingJson, } from "@caupulican/pi-ai";
|
|
7
|
+
import { StreamingLineDecoder } from "./utils/streaming-lines.js";
|
|
7
8
|
// Create stream class matching ProxyMessageEventStream
|
|
8
9
|
class ProxyMessageEventStream extends EventStream {
|
|
9
10
|
constructor() {
|
|
@@ -109,7 +110,7 @@ export function streamProxy(model, context, options) {
|
|
|
109
110
|
}
|
|
110
111
|
reader = response.body.getReader();
|
|
111
112
|
const decoder = new TextDecoder();
|
|
112
|
-
|
|
113
|
+
const lines = new StreamingLineDecoder(64 * 1024 * 1024);
|
|
113
114
|
while (true) {
|
|
114
115
|
const { done, value } = await reader.read();
|
|
115
116
|
if (done)
|
|
@@ -117,10 +118,7 @@ export function streamProxy(model, context, options) {
|
|
|
117
118
|
if (options.signal?.aborted) {
|
|
118
119
|
throw new Error("Request aborted by user");
|
|
119
120
|
}
|
|
120
|
-
|
|
121
|
-
const lines = buffer.split("\n");
|
|
122
|
-
buffer = lines.pop() || "";
|
|
123
|
-
for (const line of lines) {
|
|
121
|
+
for (const line of lines.push(decoder.decode(value, { stream: true }))) {
|
|
124
122
|
if (line.startsWith("data: ")) {
|
|
125
123
|
const data = line.slice(6).trim();
|
|
126
124
|
if (data) {
|
|
@@ -135,6 +133,33 @@ export function streamProxy(model, context, options) {
|
|
|
135
133
|
}
|
|
136
134
|
}
|
|
137
135
|
}
|
|
136
|
+
for (const line of lines.push(decoder.decode())) {
|
|
137
|
+
if (!line.startsWith("data: "))
|
|
138
|
+
continue;
|
|
139
|
+
const data = line.slice(6).trim();
|
|
140
|
+
if (!data)
|
|
141
|
+
continue;
|
|
142
|
+
const proxyEvent = JSON.parse(data);
|
|
143
|
+
const event = processProxyEvent(proxyEvent, partial);
|
|
144
|
+
if (event) {
|
|
145
|
+
if (event.type === "done" || event.type === "error")
|
|
146
|
+
terminalPushed = true;
|
|
147
|
+
stream.push(event);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const finalLine = lines.finish();
|
|
151
|
+
if (finalLine?.startsWith("data: ")) {
|
|
152
|
+
const data = finalLine.slice(6).trim();
|
|
153
|
+
if (data) {
|
|
154
|
+
const proxyEvent = JSON.parse(data);
|
|
155
|
+
const event = processProxyEvent(proxyEvent, partial);
|
|
156
|
+
if (event) {
|
|
157
|
+
if (event.type === "done" || event.type === "error")
|
|
158
|
+
terminalPushed = true;
|
|
159
|
+
stream.push(event);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
138
163
|
if (options.signal?.aborted) {
|
|
139
164
|
throw new Error("Request aborted by user");
|
|
140
165
|
}
|
package/dist/proxy.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,2CAA2C;AAC3C,OAAO,EAIN,WAAW,EAEX,kBAAkB,GAIlB,MAAM,mBAAmB,CAAC;AAE3B,uDAAuD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,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;QACrE,CAAC;QAED,KAAK,cAAc,EAAE,CAAC;YACrB,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;YACzD,IAAI,OAAO,EAAE,IAAI,KAAK,UAAU,EAAE,CAAC;gBAClC,OAAQ,OAAe,CAAC,WAAW,CAAC;gBACpC,OAAO;oBACN,IAAI,EAAE,cAAc;oBACpB,YAAY,EAAE,UAAU,CAAC,YAAY;oBACrC,QAAQ,EAAE,OAAO;oBACjB,OAAO;iBACP,CAAC;YACH,CAAC;YACD,OAAO,SAAS,CAAC;QAClB,CAAC;QAED,KAAK,MAAM;YACV,OAAO,CAAC,UAAU,GAAG,UAAU,CAAC,MAAM,CAAC;YACvC,OAAO,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;YACjC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;QAEtE,KAAK,OAAO;YACX,OAAO,CAAC,UAAU,GAAG,UAAU,CAAC,MAAM,CAAC;YACvC,OAAO,CAAC,YAAY,GAAG,UAAU,CAAC,YAAY,CAAC;YAC/C,OAAO,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;YACjC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;QAErE,SAAS,CAAC;YACT,MAAM,gBAAgB,GAAU,UAAU,CAAC;YAC3C,OAAO,CAAC,IAAI,CAAC,+BAAgC,UAAkB,CAAC,IAAI,EAAE,CAAC,CAAC;YACxE,OAAO,SAAS,CAAC;QAClB,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["/**\n * Proxy stream function for apps that route LLM calls through a server.\n * The server manages auth and proxies requests to LLM providers.\n */\n\n// Internal import for JSON parsing utility\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\ttype Model,\n\tparseStreamingJson,\n\ttype SimpleStreamOptions,\n\ttype StopReason,\n\ttype ToolCall,\n} from \"@caupulican/pi-ai\";\n\n// Create stream class matching ProxyMessageEventStream\nclass ProxyMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") return event.message;\n\t\t\t\tif (event.type === \"error\") return event.error;\n\t\t\t\tthrow new Error(\"Unexpected event type\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/**\n * Proxy event types - server sends these with partial field stripped to reduce bandwidth.\n */\nexport type ProxyAssistantMessageEvent =\n\t| { type: \"start\" }\n\t| { type: \"text_start\"; contentIndex: number }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string }\n\t| { type: \"text_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"thinking_start\"; contentIndex: number }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string }\n\t| { type: \"thinking_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"toolcall_start\"; contentIndex: number; id: string; toolName: string }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string }\n\t| { type: \"toolcall_end\"; contentIndex: number }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\">;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\treason: Extract<StopReason, \"aborted\" | \"error\">;\n\t\t\terrorMessage?: string;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t };\n\ntype ProxySerializableStreamOptions = Pick<\n\tSimpleStreamOptions,\n\t| \"temperature\"\n\t| \"maxTokens\"\n\t| \"reasoning\"\n\t| \"cacheRetention\"\n\t| \"sessionId\"\n\t| \"headers\"\n\t| \"metadata\"\n\t| \"transport\"\n\t| \"thinkingBudgets\"\n\t| \"maxRetryDelayMs\"\n>;\n\nexport interface ProxyStreamOptions extends ProxySerializableStreamOptions {\n\t/** Local abort signal for the proxy request */\n\tsignal?: AbortSignal;\n\t/** Auth token for the proxy server */\n\tauthToken: string;\n\t/** Proxy server URL (e.g., \"https://genai.example.com\") */\n\tproxyUrl: string;\n}\n\n/**\n * Stream function that proxies through a server instead of calling LLM providers directly.\n * The server strips the partial field from delta events to reduce bandwidth.\n * We reconstruct the partial message client-side.\n *\n * Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * streamFn: (model, context, options) =>\n * streamProxy(model, context, {\n * ...options,\n * authToken: await getAuthToken(),\n * proxyUrl: \"https://genai.example.com\",\n * }),\n * });\n * ```\n */\nfunction buildProxyRequestOptions(options: ProxyStreamOptions): ProxySerializableStreamOptions {\n\treturn {\n\t\ttemperature: options.temperature,\n\t\tmaxTokens: options.maxTokens,\n\t\treasoning: options.reasoning,\n\t\tcacheRetention: options.cacheRetention,\n\t\tsessionId: options.sessionId,\n\t\theaders: options.headers,\n\t\tmetadata: options.metadata,\n\t\ttransport: options.transport,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t};\n}\n\nexport function streamProxy(model: Model<any>, context: Context, options: ProxyStreamOptions): ProxyMessageEventStream {\n\tconst stream = new ProxyMessageEventStream();\n\n\t(async () => {\n\t\t// Initialize the partial message that we'll build up from events\n\t\tconst partial: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: \"stop\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t\tlet terminalPushed = false;\n\n\t\tconst abortHandler = () => {\n\t\t\tif (reader) {\n\t\t\t\treader.cancel(\"Request aborted by user\").catch(() => {});\n\t\t\t}\n\t\t};\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener(\"abort\", abortHandler);\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch(`${options.proxyUrl}/api/stream`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${options.authToken}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions: buildProxyRequestOptions(options),\n\t\t\t\t}),\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet errorMessage = `Proxy error: ${response.status} ${response.statusText}`;\n\t\t\t\ttry {\n\t\t\t\t\tconst errorData = (await response.json()) as { error?: string };\n\t\t\t\t\tif (errorData.error) {\n\t\t\t\t\t\terrorMessage = `Proxy error: ${errorData.error}`;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Couldn't parse error response\n\t\t\t\t}\n\t\t\t\tthrow new Error(errorMessage);\n\t\t\t}\n\n\t\t\treader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tif (line.startsWith(\"data: \")) {\n\t\t\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\t\t\tif (data) {\n\t\t\t\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\t\t\tif (event) {\n\t\t\t\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalPushed = true;\n\t\t\t\t\t\t\t\tstream.push(event);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\n\t\t\tif (!terminalPushed) {\n\t\t\t\tpartial.stopReason = \"error\";\n\t\t\t\tpartial.errorMessage = \"stream ended before terminal event\";\n\t\t\t\tstream.push({ type: \"error\", reason: \"error\", error: partial });\n\t\t\t}\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tconst reason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tif (options.signal) {\n\t\t\t\toptions.signal.removeEventListener(\"abort\", abortHandler);\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Process a proxy event and update the partial message.\n */\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.text,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.thinking,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} satisfies ToolCall & { partialJson: string } as ToolCall;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content }; // Trigger reactivity\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\ttoolCall: content,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcase \"done\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\n\t\tcase \"error\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,2CAA2C;AAC3C,OAAO,EAIN,WAAW,EAEX,kBAAkB,GAIlB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAElE,uDAAuD;AACvD,MAAM,uBAAwB,SAAQ,WAAoD;IACzF,cAAc;QACb,KAAK,CACJ,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAC1D,CAAC,KAAK,EAAE,EAAE,CAAC;YACV,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;gBAAE,OAAO,KAAK,CAAC,OAAO,CAAC;YAChD,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;gBAAE,OAAO,KAAK,CAAC,KAAK,CAAC;YAC/C,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;QAAA,CACz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AAC,MAAM,CAAC;YACvC,OAAO,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;YACjC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;QAEtE,KAAK,OAAO;YACX,OAAO,CAAC,UAAU,GAAG,UAAU,CAAC,MAAM,CAAC;YACvC,OAAO,CAAC,YAAY,GAAG,UAAU,CAAC,YAAY,CAAC;YAC/C,OAAO,CAAC,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;YACjC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;QAErE,SAAS,CAAC;YACT,MAAM,gBAAgB,GAAU,UAAU,CAAC;YAC3C,OAAO,CAAC,IAAI,CAAC,+BAAgC,UAAkB,CAAC,IAAI,EAAE,CAAC,CAAC;YACxE,OAAO,SAAS,CAAC;QAClB,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["/**\n * Proxy stream function for apps that route LLM calls through a server.\n * The server manages auth and proxies requests to LLM providers.\n */\n\n// Internal import for JSON parsing utility\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\ttype Model,\n\tparseStreamingJson,\n\ttype SimpleStreamOptions,\n\ttype StopReason,\n\ttype ToolCall,\n} from \"@caupulican/pi-ai\";\nimport { StreamingLineDecoder } from \"./utils/streaming-lines.ts\";\n\n// Create stream class matching ProxyMessageEventStream\nclass ProxyMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") return event.message;\n\t\t\t\tif (event.type === \"error\") return event.error;\n\t\t\t\tthrow new Error(\"Unexpected event type\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/**\n * Proxy event types - server sends these with partial field stripped to reduce bandwidth.\n */\nexport type ProxyAssistantMessageEvent =\n\t| { type: \"start\" }\n\t| { type: \"text_start\"; contentIndex: number }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string }\n\t| { type: \"text_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"thinking_start\"; contentIndex: number }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string }\n\t| { type: \"thinking_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"toolcall_start\"; contentIndex: number; id: string; toolName: string }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string }\n\t| { type: \"toolcall_end\"; contentIndex: number }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\">;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\treason: Extract<StopReason, \"aborted\" | \"error\">;\n\t\t\terrorMessage?: string;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t };\n\ntype ProxySerializableStreamOptions = Pick<\n\tSimpleStreamOptions,\n\t| \"temperature\"\n\t| \"maxTokens\"\n\t| \"reasoning\"\n\t| \"cacheRetention\"\n\t| \"sessionId\"\n\t| \"headers\"\n\t| \"metadata\"\n\t| \"transport\"\n\t| \"thinkingBudgets\"\n\t| \"maxRetryDelayMs\"\n>;\n\nexport interface ProxyStreamOptions extends ProxySerializableStreamOptions {\n\t/** Local abort signal for the proxy request */\n\tsignal?: AbortSignal;\n\t/** Auth token for the proxy server */\n\tauthToken: string;\n\t/** Proxy server URL (e.g., \"https://genai.example.com\") */\n\tproxyUrl: string;\n}\n\n/**\n * Stream function that proxies through a server instead of calling LLM providers directly.\n * The server strips the partial field from delta events to reduce bandwidth.\n * We reconstruct the partial message client-side.\n *\n * Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * streamFn: (model, context, options) =>\n * streamProxy(model, context, {\n * ...options,\n * authToken: await getAuthToken(),\n * proxyUrl: \"https://genai.example.com\",\n * }),\n * });\n * ```\n */\nfunction buildProxyRequestOptions(options: ProxyStreamOptions): ProxySerializableStreamOptions {\n\treturn {\n\t\ttemperature: options.temperature,\n\t\tmaxTokens: options.maxTokens,\n\t\treasoning: options.reasoning,\n\t\tcacheRetention: options.cacheRetention,\n\t\tsessionId: options.sessionId,\n\t\theaders: options.headers,\n\t\tmetadata: options.metadata,\n\t\ttransport: options.transport,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t};\n}\n\nexport function streamProxy(model: Model<any>, context: Context, options: ProxyStreamOptions): ProxyMessageEventStream {\n\tconst stream = new ProxyMessageEventStream();\n\n\t(async () => {\n\t\t// Initialize the partial message that we'll build up from events\n\t\tconst partial: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: \"stop\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t\tlet terminalPushed = false;\n\n\t\tconst abortHandler = () => {\n\t\t\tif (reader) {\n\t\t\t\treader.cancel(\"Request aborted by user\").catch(() => {});\n\t\t\t}\n\t\t};\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener(\"abort\", abortHandler);\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch(`${options.proxyUrl}/api/stream`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${options.authToken}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions: buildProxyRequestOptions(options),\n\t\t\t\t}),\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet errorMessage = `Proxy error: ${response.status} ${response.statusText}`;\n\t\t\t\ttry {\n\t\t\t\t\tconst errorData = (await response.json()) as { error?: string };\n\t\t\t\t\tif (errorData.error) {\n\t\t\t\t\t\terrorMessage = `Proxy error: ${errorData.error}`;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Couldn't parse error response\n\t\t\t\t}\n\t\t\t\tthrow new Error(errorMessage);\n\t\t\t}\n\n\t\t\treader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tconst lines = new StreamingLineDecoder(64 * 1024 * 1024);\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tfor (const line of lines.push(decoder.decode(value, { stream: true }))) {\n\t\t\t\t\tif (line.startsWith(\"data: \")) {\n\t\t\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\t\t\tif (data) {\n\t\t\t\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\t\t\tif (event) {\n\t\t\t\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalPushed = true;\n\t\t\t\t\t\t\t\tstream.push(event);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const line of lines.push(decoder.decode())) {\n\t\t\t\tif (!line.startsWith(\"data: \")) continue;\n\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\tif (!data) continue;\n\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\tif (event) {\n\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalPushed = true;\n\t\t\t\t\tstream.push(event);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst finalLine = lines.finish();\n\t\t\tif (finalLine?.startsWith(\"data: \")) {\n\t\t\t\tconst data = finalLine.slice(6).trim();\n\t\t\t\tif (data) {\n\t\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\tif (event) {\n\t\t\t\t\t\tif (event.type === \"done\" || event.type === \"error\") terminalPushed = true;\n\t\t\t\t\t\tstream.push(event);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\n\t\t\tif (!terminalPushed) {\n\t\t\t\tpartial.stopReason = \"error\";\n\t\t\t\tpartial.errorMessage = \"stream ended before terminal event\";\n\t\t\t\tstream.push({ type: \"error\", reason: \"error\", error: partial });\n\t\t\t}\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tconst reason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tif (options.signal) {\n\t\t\t\toptions.signal.removeEventListener(\"abort\", abortHandler);\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Process a proxy event and update the partial message.\n */\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.text,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.thinking,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} satisfies ToolCall & { partialJson: string } as ToolCall;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content }; // Trigger reactivity\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\ttoolCall: content,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcase \"done\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\n\t\tcase \"error\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n"]}
|