@vib-rato/agent-core 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +852 -0
  2. package/README.md +493 -0
  3. package/dist/types/agent-loop.d.ts +229 -0
  4. package/dist/types/agent.d.ts +533 -0
  5. package/dist/types/append-only-context.d.ts +141 -0
  6. package/dist/types/attempt-scope.d.ts +84 -0
  7. package/dist/types/compaction/adaptive.d.ts +31 -0
  8. package/dist/types/compaction/branch-summarization.d.ts +103 -0
  9. package/dist/types/compaction/compaction.d.ts +330 -0
  10. package/dist/types/compaction/entries.d.ts +124 -0
  11. package/dist/types/compaction/errors.d.ts +26 -0
  12. package/dist/types/compaction/index.d.ts +12 -0
  13. package/dist/types/compaction/messages.d.ts +61 -0
  14. package/dist/types/compaction/openai.d.ts +65 -0
  15. package/dist/types/compaction/pruning.d.ts +130 -0
  16. package/dist/types/compaction/utils.d.ts +32 -0
  17. package/dist/types/compaction.d.ts +1 -0
  18. package/dist/types/harmony-leak.d.ts +100 -0
  19. package/dist/types/heap-eviction-retainers.test.d.ts +1 -0
  20. package/dist/types/image-placeholder-guard.d.ts +4 -0
  21. package/dist/types/index.d.ts +13 -0
  22. package/dist/types/proxy.d.ts +95 -0
  23. package/dist/types/run-collector.d.ts +223 -0
  24. package/dist/types/run-resource-ledger.d.ts +2 -0
  25. package/dist/types/telemetry.d.ts +605 -0
  26. package/dist/types/thinking.d.ts +18 -0
  27. package/dist/types/tool-dispatch-identity.d.ts +27 -0
  28. package/dist/types/types.d.ts +790 -0
  29. package/package.json +72 -0
  30. package/src/agent-loop.ts +5632 -0
  31. package/src/agent.ts +2437 -0
  32. package/src/append-only-context.ts +496 -0
  33. package/src/attempt-scope.ts +195 -0
  34. package/src/compaction/adaptive.ts +92 -0
  35. package/src/compaction/branch-summarization.ts +358 -0
  36. package/src/compaction/compaction.ts +1569 -0
  37. package/src/compaction/entries.ts +158 -0
  38. package/src/compaction/errors.ts +31 -0
  39. package/src/compaction/index.ts +13 -0
  40. package/src/compaction/messages.ts +212 -0
  41. package/src/compaction/openai.ts +580 -0
  42. package/src/compaction/prompts/auto-handoff-threshold-focus.md +1 -0
  43. package/src/compaction/prompts/branch-summary-context.md +5 -0
  44. package/src/compaction/prompts/branch-summary-preamble.md +2 -0
  45. package/src/compaction/prompts/branch-summary.md +30 -0
  46. package/src/compaction/prompts/compaction-short-summary.md +9 -0
  47. package/src/compaction/prompts/compaction-summary-context.md +5 -0
  48. package/src/compaction/prompts/compaction-summary.md +38 -0
  49. package/src/compaction/prompts/compaction-turn-prefix.md +17 -0
  50. package/src/compaction/prompts/compaction-update-summary.md +45 -0
  51. package/src/compaction/prompts/file-operations.md +10 -0
  52. package/src/compaction/prompts/handoff-document.md +56 -0
  53. package/src/compaction/prompts/summarization-system.md +3 -0
  54. package/src/compaction/pruning.ts +1026 -0
  55. package/src/compaction/utils.ts +189 -0
  56. package/src/compaction.ts +1 -0
  57. package/src/harmony-leak.ts +457 -0
  58. package/src/heap-eviction-retainers.test.ts +293 -0
  59. package/src/image-placeholder-guard.ts +20 -0
  60. package/src/index.ts +23 -0
  61. package/src/prompts/escaped-nonascii-recovery.md +3 -0
  62. package/src/prompts/repeated-tool-failure-recovery.md +1 -0
  63. package/src/proxy.ts +408 -0
  64. package/src/run-collector.ts +728 -0
  65. package/src/run-resource-ledger.ts +345 -0
  66. package/src/telemetry.ts +2161 -0
  67. package/src/thinking.ts +20 -0
  68. package/src/tool-dispatch-identity.ts +87 -0
  69. package/src/types.ts +882 -0
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Shared utilities for compaction and branch summarization.
3
+ */
4
+
5
+ import type { Message } from "@vib-rato/ai";
6
+ import { prompt } from "@vib-rato/utils";
7
+ import type { AgentMessage } from "../types";
8
+ import fileOperationsTemplate from "./prompts/file-operations.md" with { type: "text" };
9
+ import summarizationSystemPrompt from "./prompts/summarization-system.md" with { type: "text" };
10
+
11
+ // ============================================================================
12
+ // File Operation Tracking
13
+ // ============================================================================
14
+
15
+ export interface FileOperations {
16
+ read: Set<string>;
17
+ written: Set<string>;
18
+ edited: Set<string>;
19
+ }
20
+
21
+ export function createFileOps(): FileOperations {
22
+ return {
23
+ read: new Set(),
24
+ written: new Set(),
25
+ edited: new Set(),
26
+ };
27
+ }
28
+
29
+ /**
30
+ * Extract file operations from tool calls in an assistant message.
31
+ */
32
+ export function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {
33
+ if (message.role !== "assistant") return;
34
+ if (!("content" in message) || !Array.isArray(message.content)) return;
35
+
36
+ for (const block of message.content) {
37
+ if (typeof block !== "object" || block === null) continue;
38
+ if (!("type" in block) || block.type !== "toolCall") continue;
39
+ if (!("arguments" in block) || !("name" in block)) continue;
40
+
41
+ const args = block.arguments as Record<string, unknown> | undefined;
42
+ if (!args) continue;
43
+
44
+ const path = typeof args.path === "string" ? args.path : undefined;
45
+ if (!path) continue;
46
+
47
+ switch (block.name) {
48
+ case "read":
49
+ fileOps.read.add(path);
50
+ break;
51
+ case "write":
52
+ fileOps.written.add(path);
53
+ break;
54
+ case "edit":
55
+ fileOps.edited.add(path);
56
+ break;
57
+ }
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Compute final file lists from file operations.
63
+ * Returns readFiles (files only read, not modified) and modifiedFiles.
64
+ */
65
+ export function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {
66
+ const modified = new Set([...fileOps.edited, ...fileOps.written]);
67
+ const readOnly = [...fileOps.read].filter(f => !modified.has(f)).sort();
68
+ const modifiedFiles = [...modified].sort();
69
+ return { readFiles: readOnly, modifiedFiles };
70
+ }
71
+
72
+ /**
73
+ * Format file operations as XML tags for summary.
74
+ */
75
+ const FILE_OPERATION_SUMMARY_LIMIT = 20;
76
+
77
+ function truncateFileList(files: string[]): string[] {
78
+ if (files.length <= FILE_OPERATION_SUMMARY_LIMIT) return files;
79
+ const omitted = files.length - FILE_OPERATION_SUMMARY_LIMIT;
80
+ return [...files.slice(0, FILE_OPERATION_SUMMARY_LIMIT), `… (${omitted} more files omitted)`];
81
+ }
82
+
83
+ function stripFileOperationTags(summary: string): string {
84
+ const withoutReadFiles = summary.replace(/<read-files>[\s\S]*?<\/read-files>\s*/g, "");
85
+ const withoutModifiedFiles = withoutReadFiles.replace(/<modified-files>[\s\S]*?<\/modified-files>\s*/g, "");
86
+ return withoutModifiedFiles.trimEnd();
87
+ }
88
+ export function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {
89
+ if (readFiles.length === 0 && modifiedFiles.length === 0) return "";
90
+ return prompt.render(fileOperationsTemplate, {
91
+ readFiles: truncateFileList(readFiles),
92
+ modifiedFiles: truncateFileList(modifiedFiles),
93
+ });
94
+ }
95
+
96
+ export function upsertFileOperations(summary: string, readFiles: string[], modifiedFiles: string[]): string {
97
+ const baseSummary = stripFileOperationTags(summary);
98
+ const fileOperations = formatFileOperations(readFiles, modifiedFiles);
99
+ if (!fileOperations) return baseSummary;
100
+ if (!baseSummary) return fileOperations;
101
+ return `${baseSummary}\n\n${fileOperations}`;
102
+ }
103
+
104
+ // ============================================================================
105
+ // Message Serialization
106
+ // ============================================================================
107
+
108
+ /** Maximum characters for a tool result in serialized summaries. */
109
+ const TOOL_RESULT_MAX_CHARS = 2000;
110
+
111
+ /**
112
+ * Truncate text to a maximum character length for summarization.
113
+ * Keeps the beginning and appends a truncation marker.
114
+ */
115
+ function truncateForSummary(text: string, maxChars: number): string {
116
+ if (text.length <= maxChars) return text;
117
+ const truncatedChars = text.length - maxChars;
118
+ return `${text.slice(0, maxChars)}\n\n[... ${truncatedChars} more characters truncated]`;
119
+ }
120
+
121
+ /**
122
+ * Serialize LLM messages to text for summarization.
123
+ * This prevents the model from treating it as a conversation to continue.
124
+ * Call convertToLlm() first to handle custom message types.
125
+ */
126
+ export function serializeConversation(messages: Message[]): string {
127
+ const parts: string[] = [];
128
+
129
+ for (const msg of messages) {
130
+ if (msg.role === "user") {
131
+ const content =
132
+ typeof msg.content === "string"
133
+ ? msg.content
134
+ : msg.content
135
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
136
+ .map(c => c.text)
137
+ .join("");
138
+ if (content) parts.push(`[User]: ${content}`);
139
+ } else if (msg.role === "assistant") {
140
+ const textParts: string[] = [];
141
+ const thinkingParts: string[] = [];
142
+ const toolCalls: string[] = [];
143
+
144
+ for (const block of msg.content) {
145
+ if (block.type === "text") {
146
+ textParts.push(block.text);
147
+ } else if (block.type === "thinking") {
148
+ thinkingParts.push(block.thinking);
149
+ } else if (block.type === "toolCall") {
150
+ // `arguments` is typed non-null, but persisted history can carry a
151
+ // null/non-object payload from an aborted or malformed tool call.
152
+ // Summarization must never throw here: this runs inside compaction,
153
+ // which is itself the recovery path for context overflow.
154
+ const args = block.arguments as Record<string, unknown> | null | undefined;
155
+ const argsStr = Object.entries(args && typeof args === "object" ? args : {})
156
+ .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
157
+ .join(", ");
158
+ toolCalls.push(`${block.name}(${argsStr})`);
159
+ }
160
+ }
161
+
162
+ if (thinkingParts.length > 0) {
163
+ parts.push(`[Assistant thinking]: ${thinkingParts.join("\n")}`);
164
+ }
165
+ if (textParts.length > 0) {
166
+ parts.push(`[Assistant]: ${textParts.join("\n")}`);
167
+ }
168
+ if (toolCalls.length > 0) {
169
+ parts.push(`[Assistant tool calls]: ${toolCalls.join("; ")}`);
170
+ }
171
+ } else if (msg.role === "toolResult") {
172
+ const content = msg.content
173
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
174
+ .map(c => c.text)
175
+ .join("");
176
+ if (content) {
177
+ parts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);
178
+ }
179
+ }
180
+ }
181
+
182
+ return parts.join("\n\n");
183
+ }
184
+
185
+ // ============================================================================
186
+ // Summarization System Prompt
187
+ // ============================================================================
188
+
189
+ export const SUMMARIZATION_SYSTEM_PROMPT = prompt.render(summarizationSystemPrompt);
@@ -0,0 +1 @@
1
+ export * from "./compaction/index";
@@ -0,0 +1,457 @@
1
+ /**
2
+ * GPT-5 Harmony-header leakage detection and recovery.
3
+ *
4
+ * Background and policy: see `docs/ERRATA-GPT5-HARMONY.md`. This module
5
+ * implements §3 of that document: detection by signal fusion, plus a
6
+ * truncate-and-resume primitive for the `edit` tool when its input is in
7
+ * hashline DSL form. Other tools and surfaces fall through to
8
+ * abort-and-retry handled by the agent loop.
9
+ */
10
+ import type { AssistantMessage, Model, ToolCall } from "@vib-rato/ai";
11
+
12
+ // Single source of truth for the marker pattern. `M` in the errata.
13
+ // Use a fresh non-global instance for `.test()` to avoid lastIndex pitfalls.
14
+ const MARKER_RE = /\bto=functions\.[A-Za-z_]\w*/g;
15
+ const HARMONY_RE = /<\|(start|end|channel|message|call|return)\|>/g;
16
+
17
+ // Leaked tool-call envelope (`I`): a structurally-committed Anthropic-style
18
+ // invoke block (an opening tag carrying a name attribute). openai-codex models
19
+ // use native function calling, so such an envelope appearing as visible
20
+ // assistant text / thinking is always a leaked tool call — a different dialect
21
+ // of the §1 phenomenon where the tool-call intent collapses into the content
22
+ // channel (frequently prefixed by a glitch token such as a bare `court` line).
23
+ // High precision: requires the opening tag AND a committed body (a parameter
24
+ // tag or a closing invoke tag) within a short window, so prose that merely
25
+ // mentions the tag does not trip. Like `H`, it trips on its own (outside code
26
+ // fences). Source spelled with `\s` so this module does not self-trip.
27
+ const INVOKE_OPEN_RE = /<invoke\s+name="[^"]+"\s*>/g;
28
+ const INVOKE_BODY_RE = /<parameter\s+name="|<\/invoke>/;
29
+
30
+ // Channel-word adjacency (`C`): channel/role name appearing immediately before the marker.
31
+ const CHANNEL_WORD_RE = /\b(?:analysis|commentary|assistant|user|system|developer|tool)\s+to=functions\./;
32
+
33
+ // Glitch-token adjacency (`G`). The Japgolly literal is escaped so this regex
34
+ // source itself does not trip detection if the file is scanned (e.g. when
35
+ // editing this module via the same agent that detects).
36
+ const GLITCH_RE = /\b(?:changedFiles|RTLU|Jsii(?:_commentary)?|\x4aapgolly)\b/;
37
+
38
+ // Body-channel cascade (`B`): marker followed by ` code` then another marker
39
+ // within 200 chars. Single regex; no manual slicing needed.
40
+ const BODY_CASCADE_RE = /to=functions\.\w+\s+code\b[\s\S]{0,200}?to=functions\./;
41
+
42
+ // Fake-result framing (`R`): marker followed within 80 chars by Cell N: framing.
43
+ const FAKE_RESULT_RE = /to=functions\.\w+[\s\S]{0,80}?code_output\s*\nCell\s+\d+:/;
44
+
45
+ const FENCE_RE = /^\s*(?:```+|~~~+)/;
46
+
47
+ // Non-Latin scripts seen in the corpus: CJK + ext, Hangul + Jamo,
48
+ // Cyrillic, Thai, Georgian, Armenian, Kannada, Telugu, Devanagari,
49
+ // Arabic, Malayalam.
50
+ const SCRIPT_CLASS =
51
+ "\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u0400-\u04FF\u0E00-\u0E7F\u10A0-\u10FF\u0530-\u058F\u0C80-\u0CFF\u0C00-\u0C7F\u0900-\u097F\u0600-\u06FF\u0D00-\u0D7F";
52
+ const SCRIPT_RUN_RE = new RegExp(`[${SCRIPT_CLASS}]{2,}`, "u");
53
+
54
+ // Recovery registry. Each entry's parser must recognize the configured
55
+ // sentinel (per-tool, see eval/parse.ts and hashline/parser.ts) and surface
56
+ // a warning to the model so it knows to re-issue any remaining work.
57
+ // `accepts` gates on input shape: tools whose contaminated input doesn't
58
+ // match the parser's expected DSL fall through to abort-and-retry.
59
+ //
60
+ // • `edit`: hashline DSL input begins with `@<path>`. Apply_patch envelopes
61
+ // (`*** Begin Patch …`) and JSON-schema variants are not recoverable —
62
+ // their parsers don't recognize `*** Abort`.
63
+ // • `eval`: any string is a parseable cell sequence (the parser is lenient
64
+ // and falls back to implicit-cell mode on bare strings).
65
+ interface RecoveryConfig {
66
+ sentinel: string;
67
+ accepts: (input: string) => boolean;
68
+ }
69
+ const RECOVERY_REGISTRY: Record<string, RecoveryConfig> = {
70
+ edit: {
71
+ sentinel: "\n*** Abort\n",
72
+ accepts: input => input.replace(/^\s+/, "").startsWith("@"),
73
+ },
74
+ eval: {
75
+ sentinel: "\n*** Abort\n",
76
+ accepts: () => true,
77
+ },
78
+ };
79
+
80
+ const SIGNAL_ORDER = ["M", "C", "G", "S", "B", "R", "T"] as const;
81
+
82
+ export type HarmonySignalClass = "H" | "I" | (typeof SIGNAL_ORDER)[number];
83
+
84
+ export type HarmonySurface = "assistant_text" | "assistant_thinking" | "tool_arg";
85
+
86
+ export interface HarmonySignal {
87
+ classes: HarmonySignalClass[];
88
+ start: number;
89
+ end: number;
90
+ text: string;
91
+ }
92
+
93
+ export interface HarmonyDetection {
94
+ surface: HarmonySurface;
95
+ contentIndex?: number;
96
+ toolName?: string;
97
+ toolCallId?: string;
98
+ signals: HarmonySignal[];
99
+ }
100
+
101
+ export interface HarmonyAuditEvent {
102
+ action: "truncate_resume" | "abort_retry" | "escalated";
103
+ surface: HarmonySurface;
104
+ signal: string;
105
+ retryN: number;
106
+ model: string;
107
+ provider: string;
108
+ toolName?: string;
109
+ removedLen: number;
110
+ removedSha8: string;
111
+ removedPreview: string;
112
+ removedBlob?: string;
113
+ }
114
+
115
+ export interface HarmonyRecoveredToolCall {
116
+ message: AssistantMessage;
117
+ removed: string;
118
+ }
119
+
120
+ /**
121
+ * Whether to run leak detection on responses from this model. We default-on
122
+ * for every OpenAI code provider model rather than enumerating ids, so a future
123
+ * gpt-5.6 (or whatever) doesn't silently bypass the mitigation. Detection
124
+ * itself is cheap; the cost of missing a leak on a new model is not.
125
+ */
126
+ export function isHarmonyLeakMitigationTarget(model: Model): boolean {
127
+ return model.provider === "openai-codex";
128
+ }
129
+
130
+ export function shouldMitigateHarmonyLeak(model: Model, detection: HarmonyDetection): boolean {
131
+ if (isHarmonyLeakMitigationTarget(model)) return true;
132
+ return detection.signals.some(signal => signal.classes.includes("I"));
133
+ }
134
+
135
+ export function signalListLabel(signals: readonly HarmonySignal[]): string {
136
+ const seen: string[] = [];
137
+ for (const signal of signals) {
138
+ const label = signal.classes.join("+");
139
+ if (!seen.includes(label)) seen.push(label);
140
+ }
141
+ return seen.join(",") || "none";
142
+ }
143
+
144
+ /**
145
+ * Detect harmony-protocol leakage in `text`. Returns undefined if clean.
146
+ *
147
+ * Trip rule: `H` alone, or `M` paired with at least one co-signal
148
+ * (`C`/`G`/`S`/`B`/`R`/`T`). Bare `M` does not trip — this document, its
149
+ * tests, and bug reports legitimately carry the marker.
150
+ *
151
+ * `parsedEnd`, when supplied, marks the byte at which a structurally valid
152
+ * tool-argument parse ends; markers strictly after it set the `T` co-signal.
153
+ * `contentIndex`/`toolName`/`toolCallId` flow through to the returned
154
+ * detection for downstream auditing.
155
+ */
156
+ export function detectHarmonyLeak(
157
+ text: string,
158
+ surface: HarmonySurface,
159
+ options: {
160
+ parsedEnd?: number;
161
+ contentIndex?: number;
162
+ toolName?: string;
163
+ toolCallId?: string;
164
+ } = {},
165
+ ): HarmonyDetection | undefined {
166
+ const fences = computeFenceRanges(text);
167
+ const signals: HarmonySignal[] = [];
168
+
169
+ for (const match of text.matchAll(HARMONY_RE)) {
170
+ const start = match.index ?? 0;
171
+ if (isInsideFence(fences, start)) continue;
172
+ signals.push(makeSignal(["H"], start, start + match[0].length, match[0]));
173
+ }
174
+
175
+ for (const match of text.matchAll(INVOKE_OPEN_RE)) {
176
+ const start = match.index ?? 0;
177
+ if (isInsideFence(fences, start)) continue;
178
+ // Require a committed body nearby so a bare mention of the tag in prose
179
+ // does not trip; a real leaked envelope continues into parameters or a
180
+ // close tag.
181
+ const forward = text.slice(start, Math.min(text.length, start + 400));
182
+ if (!INVOKE_BODY_RE.test(forward)) continue;
183
+ signals.push(makeSignal(["I"], start, start + match[0].length, match[0]));
184
+ }
185
+
186
+ for (const match of text.matchAll(MARKER_RE)) {
187
+ const start = match.index ?? 0;
188
+ if (isInsideFence(fences, start)) continue;
189
+ const end = start + match[0].length;
190
+ const classes: HarmonySignalClass[] = ["M"];
191
+
192
+ const adjacent = text.slice(Math.max(0, start - 64), Math.min(text.length, end + 16));
193
+ const near = text.slice(Math.max(0, start - 16), Math.min(text.length, end + 16));
194
+ const forward = text.slice(start, Math.min(text.length, start + 240));
195
+
196
+ if (CHANNEL_WORD_RE.test(adjacent)) classes.push("C");
197
+ if (GLITCH_RE.test(near)) classes.push("G");
198
+ if (hasScriptMismatchNear(text, start, end)) classes.push("S");
199
+ if (BODY_CASCADE_RE.test(forward)) classes.push("B");
200
+ if (FAKE_RESULT_RE.test(forward)) classes.push("R");
201
+ if (options.parsedEnd !== undefined && start >= options.parsedEnd) classes.push("T");
202
+
203
+ // `M` alone never trips: legitimate documentation/tests carry it.
204
+ if (classes.length > 1) {
205
+ signals.push(makeSignal(classes, start, end, match[0]));
206
+ }
207
+ }
208
+
209
+ if (signals.length === 0) return undefined;
210
+ signals.sort((a, b) => a.start - b.start || a.end - b.end);
211
+ return {
212
+ surface,
213
+ contentIndex: options.contentIndex,
214
+ toolName: options.toolName,
215
+ toolCallId: options.toolCallId,
216
+ signals,
217
+ };
218
+ }
219
+
220
+ /** Scan an assistant message's content blocks; return the first detection. */
221
+ export function detectHarmonyLeakInAssistantMessage(message: AssistantMessage): HarmonyDetection | undefined {
222
+ for (let i = 0; i < message.content.length; i++) {
223
+ const block = message.content[i];
224
+ if (block.type === "text") {
225
+ const d = detectHarmonyLeak(block.text, "assistant_text", { contentIndex: i });
226
+ if (d) return d;
227
+ } else if (block.type === "thinking") {
228
+ const d = detectHarmonyLeak(block.thinking, "assistant_thinking", { contentIndex: i });
229
+ if (d) return d;
230
+ } else if (block.type === "toolCall") {
231
+ const argText = getToolArgumentText(block);
232
+ if (argText !== undefined) {
233
+ const d = detectHarmonyLeak(argText, "tool_arg", {
234
+ contentIndex: i,
235
+ toolName: block.name,
236
+ toolCallId: block.id,
237
+ });
238
+ if (d) return d;
239
+ }
240
+ }
241
+ }
242
+ return undefined;
243
+ }
244
+
245
+ /**
246
+ * Truncate a contaminated tool call at the start of the contaminated line and
247
+ * append the tool's recovery sentinel. Returns a recovered AssistantMessage
248
+ * (containing only the cleaned tool call), a synthetic continuation user
249
+ * message asking the model to re-issue the rest, and the removed substring
250
+ * for auditing. Returns undefined when the tool is not recovery-eligible or
251
+ * the truncation would leave nothing meaningful to dispatch.
252
+ *
253
+ * `providerPayload` is dropped from the recovered message: for OpenAI code backend the
254
+ * encrypted reasoning blob is opaque/signed and we cannot validate that it is
255
+ * uncontaminated. The model re-reasons on the next turn.
256
+ */
257
+ export function recoverHarmonyToolCall(
258
+ message: AssistantMessage,
259
+ detection: HarmonyDetection,
260
+ ): HarmonyRecoveredToolCall | undefined {
261
+ if (detection.surface !== "tool_arg" || detection.contentIndex === undefined) return undefined;
262
+ const block = message.content[detection.contentIndex];
263
+ if (block?.type !== "toolCall") return undefined;
264
+
265
+ const config = RECOVERY_REGISTRY[block.name];
266
+ if (!config) return undefined;
267
+
268
+ const input = block.arguments?.input;
269
+ if (typeof input !== "string") return undefined;
270
+ if (!config.accepts(input)) return undefined;
271
+
272
+ const offset = detection.signals[0]?.start;
273
+ if (offset === undefined) return undefined;
274
+
275
+ const truncated = truncateAtLineAndAppendSentinel(input, offset, config.sentinel);
276
+ if (truncated === undefined) return undefined;
277
+
278
+ const cleanToolCall: ToolCall = {
279
+ ...block,
280
+ arguments: { ...block.arguments, input: truncated.clean },
281
+ };
282
+ const cleanMessage: AssistantMessage = {
283
+ ...message,
284
+ content: [cleanToolCall],
285
+ // Drop encrypted reasoning blob: opaque, possibly carries the leak forward.
286
+ providerPayload: undefined,
287
+ stopReason: "toolUse",
288
+ errorMessage: undefined,
289
+ };
290
+ return { message: cleanMessage, removed: truncated.removed };
291
+ }
292
+
293
+ /**
294
+ * Return the contaminated substring from `message` for audit purposes when
295
+ * recovery is not applicable (abort path). Walks from the first detected
296
+ * signal to end-of-content within the relevant block. Returns "" if the
297
+ * detection cannot be resolved against the message.
298
+ */
299
+ export function extractHarmonyRemoved(message: AssistantMessage, detection: HarmonyDetection): string {
300
+ if (detection.contentIndex === undefined) return "";
301
+ const block = message.content[detection.contentIndex];
302
+ if (!block) return "";
303
+ const start = detection.signals[0]?.start ?? 0;
304
+ if (block.type === "text") return block.text.slice(start);
305
+ if (block.type === "thinking") return block.thinking.slice(start);
306
+ if (block.type === "toolCall") {
307
+ const text = getToolArgumentText(block);
308
+ return text ? text.slice(start) : "";
309
+ }
310
+ return "";
311
+ }
312
+
313
+ export function createHarmonyAuditEvent(params: {
314
+ action: HarmonyAuditEvent["action"];
315
+ detection: HarmonyDetection;
316
+ model: Model;
317
+ retryN: number;
318
+ removed: string;
319
+ }): HarmonyAuditEvent {
320
+ return {
321
+ action: params.action,
322
+ surface: params.detection.surface,
323
+ signal: signalListLabel(params.detection.signals),
324
+ retryN: params.retryN,
325
+ model: params.model.id,
326
+ provider: params.model.provider,
327
+ toolName: params.detection.toolName,
328
+ removedLen: params.removed.length,
329
+ removedSha8: sha8(params.removed),
330
+ removedPreview: redactedJunkPreview(params.removed),
331
+ removedBlob: Bun.env.VIB_HARMONY_DEBUG === "1" ? params.removed : undefined,
332
+ };
333
+ }
334
+
335
+ // ─── internals ──────────────────────────────────────────────────────────────
336
+
337
+ function makeSignal(classes: HarmonySignalClass[], start: number, end: number, text: string): HarmonySignal {
338
+ if (classes[0] === "H" || classes[0] === "I") return { classes: [classes[0]], start, end, text };
339
+ const sorted: HarmonySignalClass[] = [];
340
+ for (const cls of SIGNAL_ORDER) {
341
+ if (classes.includes(cls)) sorted.push(cls);
342
+ }
343
+ return { classes: sorted, start, end, text };
344
+ }
345
+
346
+ /**
347
+ * Precompute fenced-code-block ranges once per text. Each range is a
348
+ * [start, end) span of bytes inside any ```/~~~ fence. O(n) once instead of
349
+ * O(n) per detected match.
350
+ */
351
+ function computeFenceRanges(text: string): Array<[number, number]> {
352
+ const ranges: Array<[number, number]> = [];
353
+ let inFence = false;
354
+ let fenceStart = 0;
355
+ let lineStart = 0;
356
+ while (lineStart <= text.length) {
357
+ const newline = text.indexOf("\n", lineStart);
358
+ const lineEnd = newline === -1 ? text.length : newline;
359
+ const line = text.slice(lineStart, lineEnd);
360
+ if (FENCE_RE.test(line)) {
361
+ if (inFence) {
362
+ ranges.push([fenceStart, lineEnd]);
363
+ inFence = false;
364
+ } else {
365
+ fenceStart = lineStart;
366
+ inFence = true;
367
+ }
368
+ }
369
+ if (newline === -1) break;
370
+ lineStart = newline + 1;
371
+ }
372
+ if (inFence) ranges.push([fenceStart, text.length]);
373
+ return ranges;
374
+ }
375
+
376
+ function isInsideFence(ranges: Array<[number, number]>, position: number): boolean {
377
+ for (const [start, end] of ranges) {
378
+ if (position >= start && position < end) return true;
379
+ if (start > position) break;
380
+ }
381
+ return false;
382
+ }
383
+
384
+ function hasScriptMismatchNear(text: string, start: number, end: number): boolean {
385
+ const near = text.slice(Math.max(0, start - 32), Math.min(text.length, end + 32));
386
+ if (!SCRIPT_RUN_RE.test(near)) return false;
387
+ const surrounding = text.slice(Math.max(0, start - 200), Math.min(text.length, end + 200));
388
+ if (surrounding.length === 0) return false;
389
+ let ascii = 0;
390
+ for (let i = 0; i < surrounding.length; i++) {
391
+ if (surrounding.charCodeAt(i) < 128) ascii++;
392
+ }
393
+ return ascii / surrounding.length >= 0.85;
394
+ }
395
+
396
+ /**
397
+ * Tool-call argument text used for detection scanning. For tools whose args
398
+ * include a free-form `input` string we scan that directly so reported byte
399
+ * offsets line up with the original. For everything else we fall back to a
400
+ * JSON-stringified blob so detection still fires; that path's offsets are
401
+ * NOT meaningful for slicing the original args, but the recovery path gates
402
+ * on `block.arguments.input` being a string and only ever slices that.
403
+ */
404
+ function getToolArgumentText(toolCall: ToolCall): string | undefined {
405
+ if (typeof toolCall.arguments?.input === "string") return toolCall.arguments.input;
406
+ try {
407
+ return JSON.stringify(toolCall.arguments);
408
+ } catch {
409
+ return undefined;
410
+ }
411
+ }
412
+
413
+ function truncateAtLineAndAppendSentinel(
414
+ input: string,
415
+ offset: number,
416
+ sentinel: string,
417
+ ): { clean: string; removed: string } | undefined {
418
+ const lineStart = offset <= 0 ? 0 : input.lastIndexOf("\n", offset - 1) + 1;
419
+ if (lineStart === 0) return undefined; // would cut everything
420
+ const head = input.slice(0, lineStart).replace(/\s+$/, "");
421
+ if (head.length === 0) return undefined;
422
+ return {
423
+ clean: head + sentinel,
424
+ removed: input.slice(lineStart),
425
+ };
426
+ }
427
+
428
+ function sha8(text: string): string {
429
+ return Bun.sha(text, "hex").slice(0, 8);
430
+ }
431
+
432
+ const PREVIEW_KEEP_RE = new RegExp(`[${SCRIPT_CLASS}\\s】【”“…」「、。]`, "u");
433
+ const PREVIEW_TOKEN_RE =
434
+ /^(?:to=functions\.[A-Za-z_]\w*|<\/?invoke\b[^>]*>|<parameter\b[^>]*>|analysis|commentary|assistant|user|system|developer|tool|changedFiles|RTLU|Jsii(?:_commentary)?|\x4aapgolly)/;
435
+
436
+ /**
437
+ * Privacy-safe preview for the audit log: keeps marker/channel/glitch tokens,
438
+ * non-Latin script chars, and CJK punctuation; replaces everything else
439
+ * (potential source/secrets) with `·`. Sufficient to grow the glitch-token
440
+ * denylist from logs without exposing source content. Capped at 64 chars.
441
+ */
442
+ function redactedJunkPreview(text: string): string {
443
+ const source = text.slice(0, 64);
444
+ let out = "";
445
+ for (let i = 0; i < source.length; ) {
446
+ const tok = PREVIEW_TOKEN_RE.exec(source.slice(i));
447
+ if (tok) {
448
+ out += tok[0];
449
+ i += tok[0].length;
450
+ continue;
451
+ }
452
+ const ch = source[i] ?? "";
453
+ out += PREVIEW_KEEP_RE.test(ch) ? ch : "·";
454
+ i++;
455
+ }
456
+ return out;
457
+ }