jinzd-ai-cli 0.4.191 → 0.4.193

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.
@@ -0,0 +1,1058 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/tools/types.ts
4
+ function isFileWriteTool(name) {
5
+ return name === "write_file" || name === "edit_file" || name === "notebook_edit";
6
+ }
7
+ function getDangerLevel(toolName, args) {
8
+ if (toolName.startsWith("mcp__")) return "safe";
9
+ if (toolName === "bash") {
10
+ const cmd = String(args["command"] ?? "");
11
+ if (/\brm\s+[^\n]*(?:-\w*[rRfF]\w*|--recursive|--force)\b/.test(cmd)) return "destructive";
12
+ if (/\brm\s+\S/.test(cmd)) return "destructive";
13
+ if (/\brmdir\b|\bformat\b|\bmkfs\b|\bdd\s+if=|\bshred\b|\bfdisk\b|\bparted\b/.test(cmd)) return "destructive";
14
+ if (/\bshutdown\b|\breboot\b|\bhalt\b|\bpoweroff\b/.test(cmd)) return "destructive";
15
+ if (/\bkill\s+-9\b|\bkillall\b/.test(cmd)) return "destructive";
16
+ if (/\bRemove-Item\b|\bri\s+\S/i.test(cmd)) return "destructive";
17
+ if (/\brd\s+\/s\b|\brmdir\s+\/s\b/i.test(cmd)) return "destructive";
18
+ if (/\bdel\s+\S/.test(cmd)) return "destructive";
19
+ if (/\bShutdown(-Computer)?\b|\bRestart-Computer\b/i.test(cmd)) return "destructive";
20
+ if (/(?:^|[\s|;&])>>?\s*\S/.test(cmd)) return "write";
21
+ if (/\btee\b|\bcp\b|\bmv\b|\bln\s+-s/.test(cmd)) return "write";
22
+ if (/\bchmod\b|\bchown\b/.test(cmd)) return "write";
23
+ if (/\bSet-Content\b|\bOut-File\b|\bAdd-Content\b|\bCopy-Item\b|\bMove-Item\b|\bSet-ItemProperty\b|\bNew-ItemProperty\b/i.test(cmd)) return "write";
24
+ if (/\b(python3?|node|deno|bun|perl|ruby|php|bash|sh|zsh|pwsh|powershell)(\.exe)?\b[^\n]*?\s-(?:Command|EncodedCommand|c|e|p|r)\b/i.test(cmd)) return "write";
25
+ if (/\bcmd(\.exe)?\s+\/[ck]\b/i.test(cmd)) return "write";
26
+ return "safe";
27
+ }
28
+ if (toolName === "write_file") return "write";
29
+ if (toolName === "edit_file") return "write";
30
+ if (toolName === "save_last_response") return "write";
31
+ if (toolName === "run_interactive") {
32
+ const exe = String(args["executable"] ?? "").toLowerCase();
33
+ if (/\b(rm|rmdir|del|format|mkfs|Remove-Item)\b/i.test(exe)) return "destructive";
34
+ if (/\b(bash|sh|zsh|cmd|powershell|pwsh|python|node|ruby|perl)\b/i.test(exe)) return "write";
35
+ return "write";
36
+ }
37
+ if (toolName === "task_create" || toolName === "task_stop") return "write";
38
+ if (toolName === "task_list") return "safe";
39
+ if (toolName === "git_commit") return "write";
40
+ if (toolName === "git_status" || toolName === "git_diff" || toolName === "git_log") return "safe";
41
+ if (toolName === "notebook_edit") return "write";
42
+ if (toolName === "read_file" || toolName === "list_dir" || toolName === "grep_files" || toolName === "glob_files" || toolName === "web_fetch" || toolName === "save_memory" || toolName === "ask_user" || toolName === "write_todos" || toolName === "google_search" || toolName === "spawn_agent" || toolName === "run_tests") return "safe";
43
+ return "write";
44
+ }
45
+ function schemaToJsonSchema(schema) {
46
+ const result = {
47
+ type: schema.type,
48
+ description: schema.description
49
+ };
50
+ if (schema.enum) result["enum"] = schema.enum;
51
+ if (schema.items) result["items"] = schemaToJsonSchema(schema.items);
52
+ if (schema.properties) {
53
+ result["properties"] = Object.fromEntries(
54
+ Object.entries(schema.properties).map(([k, v]) => [k, schemaToJsonSchema(v)])
55
+ );
56
+ }
57
+ return result;
58
+ }
59
+
60
+ // src/tools/hallucination.ts
61
+ var HALLUCINATION_PATTERNS = [
62
+ /文件路径[::]\s*`?[^\s`]+\.\w{1,5}/,
63
+ // 文件路径: `path/to/file.ext`(要求文件扩展名)
64
+ /已生成[::!!]/,
65
+ // 已生成完成!
66
+ /已保存到?\s*[`'"]/,
67
+ // 已保存到 `path`(要求后跟路径引号)
68
+ /已写入[::!!]/,
69
+ // 已写入!
70
+ /已创建[::!!]/,
71
+ // 已创建!
72
+ /File\s+(?:written|saved|created)\s+(?:to|as|at)/i,
73
+ // File written to / saved as(要求介词)
74
+ /生成完成[!!]/,
75
+ // 生成完成!
76
+ /✅\s*(?:文件|已[生保写创]|第)\S*\.\w{1,5}/,
77
+ // ✅ 文件已保存 path.ext(要求文件扩展名)
78
+ /文件已[成功]?创建/,
79
+ // 文件已成功创建 / 文件已创建
80
+ /教案已[成功]?[生创保写]/,
81
+ // 教案已成功生成 / 教案已保存
82
+ /已成功[保写创生]入?[::!!\s`'"]/,
83
+ // 已成功保存 / 已成功写入 / 已成功创建
84
+ /保存[到至]了?\s*[`'"]/,
85
+ // 保存到了 `path` / 保存至 'path'
86
+ /内容如下[::]/,
87
+ // 内容如下:(后跟大段文件内容)
88
+ /以下是.*(?:教案|文件|内容)[::]/
89
+ // 以下是xx教案内容:(Kimi 常见模式)
90
+ ];
91
+ function detectsHallucinatedFileOp(content) {
92
+ return HALLUCINATION_PATTERNS.some((pattern) => pattern.test(content));
93
+ }
94
+ function hadPreviousWriteToolCalls(extraMessages) {
95
+ const msgs = extraMessages;
96
+ return msgs.some((msg) => {
97
+ if (msg.role === "assistant" && Array.isArray(msg.tool_calls)) {
98
+ return msg.tool_calls.some((tc) => {
99
+ const fn = tc.function;
100
+ const name = fn?.name ?? "";
101
+ return name === "write_file" || name === "edit_file";
102
+ });
103
+ }
104
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
105
+ return msg.content.some((block) => {
106
+ if (block.type !== "tool_use") return false;
107
+ const name = block.name ?? "";
108
+ return name === "write_file" || name === "edit_file";
109
+ });
110
+ }
111
+ if (msg.role === "model" && Array.isArray(msg.parts)) {
112
+ return msg.parts.some((part) => {
113
+ const fc = part.functionCall;
114
+ const name = fc?.name ?? "";
115
+ return name === "write_file" || name === "edit_file";
116
+ });
117
+ }
118
+ return false;
119
+ });
120
+ }
121
+ var TOOL_CALL_REMINDER = `
122
+
123
+ [\u26A0\uFE0F Mandatory Tool Call Policy]
124
+ When you need to create, write, or modify files, you MUST use the function calling API to invoke write_file or edit_file.
125
+ NEVER claim "file saved", "file created", "written to", etc. in your response text without actually calling the tool.
126
+ Describing file content in text without calling the tool = the file does not exist = task failure.
127
+ If multiple files need to be generated, you MUST call write_file separately for each file \u2014 do not skip any.
128
+ Do NOT output fake "completion summaries" unless you have actually completed all file writes via tool_calls.
129
+
130
+ CRITICAL \u2014 Batch file generation rules:
131
+ 1. You MUST call write_file once per file. There are NO shortcuts.
132
+ 2. After writing file N, immediately proceed to call write_file for file N+1. Do NOT stop to summarize.
133
+ 3. If you find yourself typing file content into your response text instead of into a write_file call, STOP and use the tool.
134
+ 4. Only produce a text summary AFTER all write_file calls have been made and returned success.
135
+ 5. The system compares every "file saved" claim against actual tool calls. Phantom claims trigger an automatic retry \u2014 do not waste rounds.`;
136
+ function buildWriteRoundReminder(writtenCount) {
137
+ return `
138
+
139
+ [Write Progress Reminder]
140
+ You have successfully called write_file ${writtenCount} time(s) so far in this turn. If there are more files to write, call write_file NOW for the next file. Do NOT produce a text summary until ALL files have been written via tool calls.`;
141
+ }
142
+ var HALLUCINATION_CORRECTION_MESSAGE = "You did NOT actually call the write_file tool \u2014 the file was NOT created! Please immediately use the write_file tool via the function calling API to perform the actual file write. Do NOT describe file content in text \u2014 you MUST invoke write_file through the tool_calls mechanism.";
143
+ function extractClaimedFilePaths(content) {
144
+ const paths = /* @__PURE__ */ new Set();
145
+ const add = (p) => {
146
+ const trimmed = p.trim().replace(/[,,。、;;::]+$/, "");
147
+ if (trimmed && /\.\w{1,6}$/.test(trimmed)) paths.add(trimmed);
148
+ };
149
+ let m;
150
+ const actionLineRe = /(?:已[生保写创]|saved|written|created|完成.*(?:写入|保存|创建|生成)|输出|file\s+(?:saved|written|created))/i;
151
+ const backtickRe = /`([^`\n]+?\.\w{1,6})`/g;
152
+ while ((m = backtickRe.exec(content)) !== null) {
153
+ let pos = m.index;
154
+ let linesBack = 0;
155
+ while (linesBack < 9 && pos > 0) {
156
+ pos--;
157
+ if (content[pos] === "\n") linesBack++;
158
+ }
159
+ const windowStart = pos === 0 ? 0 : pos + 1;
160
+ const lineEndIdx = content.indexOf("\n", m.index + m[0].length);
161
+ const window = content.slice(windowStart, lineEndIdx === -1 ? void 0 : lineEndIdx);
162
+ if (actionLineRe.test(window)) add(m[1]);
163
+ }
164
+ const zhRe = /(?:已保存(?:到)?|已写入(?:到)?|已创建|已生成|文件路径[::]|保存为|写入到)\s*[`'”””]?([^\s`'”””,,。\n]+?\.\w{1,6})/g;
165
+ while ((m = zhRe.exec(content)) !== null) add(m[1]);
166
+ const enRe = /(?:saved|written|created)\s+(?:to|as|at)\s+[`'”]?([^\s`'”\n,]+?\.\w{1,6})/gi;
167
+ while ((m = enRe.exec(content)) !== null) add(m[1]);
168
+ const checkRe = /✅[^\n`]*?[`'”]?([^\s`'”\n,,。]+?\.\w{1,6})/g;
169
+ while ((m = checkRe.exec(content)) !== null) {
170
+ let pos = m.index;
171
+ let linesBack = 0;
172
+ while (linesBack < 9 && pos > 0) {
173
+ pos--;
174
+ if (content[pos] === "\n") linesBack++;
175
+ }
176
+ const windowStart = pos === 0 ? 0 : pos + 1;
177
+ const lineEndIdx = content.indexOf("\n", m.index + m[0].length);
178
+ const window = content.slice(windowStart, lineEndIdx === -1 ? void 0 : lineEndIdx);
179
+ if (actionLineRe.test(window)) add(m[1]);
180
+ }
181
+ return Array.from(paths);
182
+ }
183
+ function extractWrittenFilePaths(extraMessages) {
184
+ const paths = /* @__PURE__ */ new Set();
185
+ const msgs = extraMessages;
186
+ const addFromArgs = (raw) => {
187
+ if (typeof raw === "string") {
188
+ try {
189
+ const parsed = JSON.parse(raw);
190
+ if (typeof parsed.path === "string") paths.add(parsed.path);
191
+ } catch {
192
+ }
193
+ } else if (raw && typeof raw === "object") {
194
+ const p = raw.path;
195
+ if (typeof p === "string") paths.add(p);
196
+ }
197
+ };
198
+ for (const msg of msgs) {
199
+ if (msg.role === "assistant" && Array.isArray(msg.tool_calls)) {
200
+ for (const tc of msg.tool_calls) {
201
+ const fn = tc.function;
202
+ const name = fn?.name ?? "";
203
+ if (name === "write_file" || name === "edit_file") {
204
+ addFromArgs(fn?.arguments);
205
+ }
206
+ }
207
+ }
208
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
209
+ for (const block of msg.content) {
210
+ if (block.type !== "tool_use") continue;
211
+ const name = block.name ?? "";
212
+ if (name === "write_file" || name === "edit_file") {
213
+ addFromArgs(block.input);
214
+ }
215
+ }
216
+ }
217
+ if (msg.role === "model" && Array.isArray(msg.parts)) {
218
+ for (const part of msg.parts) {
219
+ const fc = part.functionCall;
220
+ if (!fc) continue;
221
+ const name = fc.name ?? "";
222
+ if (name === "write_file" || name === "edit_file") {
223
+ addFromArgs(fc.args);
224
+ }
225
+ }
226
+ }
227
+ }
228
+ return Array.from(paths);
229
+ }
230
+ function extractBashCommands(extraMessages) {
231
+ const cmds = [];
232
+ const msgs = extraMessages;
233
+ const addCmd = (raw) => {
234
+ if (typeof raw === "string") {
235
+ try {
236
+ const parsed = JSON.parse(raw);
237
+ if (typeof parsed.command === "string") cmds.push(parsed.command);
238
+ } catch {
239
+ }
240
+ } else if (raw && typeof raw === "object") {
241
+ const c = raw.command;
242
+ if (typeof c === "string") cmds.push(c);
243
+ }
244
+ };
245
+ for (const msg of msgs) {
246
+ if (msg.role === "assistant" && Array.isArray(msg.tool_calls)) {
247
+ for (const tc of msg.tool_calls) {
248
+ const fn = tc.function;
249
+ if (fn?.name === "bash") addCmd(fn?.arguments);
250
+ }
251
+ }
252
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
253
+ for (const block of msg.content) {
254
+ if (block.type === "tool_use" && block.name === "bash") addCmd(block.input);
255
+ }
256
+ }
257
+ if (msg.role === "model" && Array.isArray(msg.parts)) {
258
+ for (const part of msg.parts) {
259
+ const fc = part.functionCall;
260
+ if (fc && fc.name === "bash") addCmd(fc.args);
261
+ }
262
+ }
263
+ }
264
+ return cmds;
265
+ }
266
+ function findPhantomClaims(content, extraMessages) {
267
+ const claimed = extractClaimedFilePaths(content);
268
+ if (claimed.length === 0) return [];
269
+ const normalize = (p) => p.replace(/\\/g, "/").toLowerCase().replace(/^\.\//, "");
270
+ const basename = (p) => {
271
+ const parts = normalize(p).split("/");
272
+ return parts[parts.length - 1] ?? "";
273
+ };
274
+ const written = extractWrittenFilePaths(extraMessages).map(normalize);
275
+ const writtenBases = new Set(written.map(basename));
276
+ const writtenFull = new Set(written);
277
+ const bashText = extractBashCommands(extraMessages).map((c) => c.replace(/\\/g, "/").toLowerCase()).join("\n");
278
+ return claimed.filter((raw) => {
279
+ const norm = normalize(raw);
280
+ if (writtenFull.has(norm)) return false;
281
+ for (const w of writtenFull) {
282
+ if (w.endsWith("/" + norm) || norm.endsWith("/" + w)) return false;
283
+ }
284
+ if (writtenBases.has(basename(norm))) return false;
285
+ const base = basename(norm);
286
+ if (base && bashText.includes(base)) return false;
287
+ return true;
288
+ });
289
+ }
290
+ function buildPhantomCorrectionMessage(phantoms) {
291
+ const list = phantoms.map((p) => ` - ${p}`).join("\n");
292
+ return "You claimed to have written the following file(s), but no matching write_file tool call was actually made in this turn:\n" + list + '\n\nEach of these files does NOT exist on disk. You MUST now invoke write_file (via the function calling API) for every missing file listed above. Do NOT output another "completion summary" until the tool calls have actually been made.';
293
+ }
294
+ var DSML_PIPE_CLASS = "[|\\uFF5C\\u2502\\u2503\\u01C0]";
295
+ var PSEUDO_TOOL_CALL_PATTERNS = [
296
+ // <tool_call name="..."> ... </tool_call> (DeepSeek V4 thinking, GLM)
297
+ /<tool_call\s+name\s*=\s*["'][\w._-]+["']/,
298
+ // <function_calls> ... </function_calls> (Anthropic-style as text)
299
+ /<\/?function_calls\s*>/,
300
+ // <invoke name="..." /> (Anthropic XML tool-call, which is real for
301
+ // Claude API but is text/garbage for any other provider's plain stream)
302
+ /<invoke\s+name\s*=\s*["'][\w._-]+["']/,
303
+ // <tool_use> ... <tool_use_id> (Claude flavor leaked into text)
304
+ /<tool_use(?:_id)?\b/,
305
+ // ```tool_call\n...\n``` markdown fences (Kimi/Zhipu fallback)
306
+ /```\s*tool_call\b/i,
307
+ // Bare JSON tool-call block: lines starting with `{"name":"...","arguments":`
308
+ /^\s*\{\s*"name"\s*:\s*"[\w._-]+"\s*,\s*"arguments"\s*:/m,
309
+ // v0.4.112: <think> ... </think> reasoning blocks. The REPL renderer
310
+ // suppresses these from terminal output, but tee mode writes the raw
311
+ // delta to disk → reasoning leaks into the saved file. We saw a 600-line
312
+ // 审计报告.md whose first 57 lines were the model's planning monologue.
313
+ /<think\b[^>]*>/i,
314
+ // v0.4.112: leading ```markdown / ```md fence wrapping the entire document.
315
+ // DeepSeek V4 Pro Thinking sometimes "politely" wraps its document output
316
+ // in a markdown fence. The fence ends up literally in the saved file.
317
+ /^\s*```\s*(?:markdown|md|gfm)\b/im,
318
+ // v0.4.173: DeepSeek V4 DSML pseudo-tool-call markup leaked as text. DeepSeek
319
+ // emits a fake tool call using its native special-token markup
320
+ // <||DSML||tool_calls> <||DSML||invoke name="write"> <||DSML||parameter …>
321
+ // where the "pipe" is U+FF5C FULLWIDTH VERTICAL LINE (the same token family as
322
+ // <|User|>/<|Assistant|>). We saw an exam paper saved via save_last_response
323
+ // whose tee stream was preamble + this DSML wrapper + the real document body.
324
+ // The earlier <invoke …> pattern uses ASCII < > and does NOT match these.
325
+ new RegExp(`<\\/?\\s*${DSML_PIPE_CLASS}+\\s*DSML\\s*${DSML_PIPE_CLASS}+`, "i")
326
+ ];
327
+ function detectPseudoToolCalls(content) {
328
+ if (!content || content.length === 0) return null;
329
+ for (const re of PSEUDO_TOOL_CALL_PATTERNS) {
330
+ if (re.test(content)) return re.source;
331
+ }
332
+ return null;
333
+ }
334
+ function stripPseudoToolCalls(content) {
335
+ if (!content) return content;
336
+ let out = content;
337
+ const dsmlBody = extractDsmlContent(out);
338
+ if (dsmlBody !== null) {
339
+ out = dsmlBody;
340
+ } else {
341
+ out = stripDsmlTags(out);
342
+ }
343
+ out = out.replace(/<tool_call\b[^>]*>[\s\S]*?<\/tool_call>/gi, "");
344
+ out = out.replace(/<tool_call\b[^>]*\/>/gi, "");
345
+ out = out.replace(/<function_calls\b[^>]*>[\s\S]*?<\/function_calls>/gi, "");
346
+ out = out.replace(/<invoke\b[^>]*>[\s\S]*?<\/invoke>/gi, "");
347
+ out = out.replace(/<invoke\b[^>]*\/>/gi, "");
348
+ out = out.replace(/<tool_use(?:_id)?\b[^>]*>[\s\S]*?<\/tool_use(?:_id)?>/gi, "");
349
+ out = out.replace(/```\s*tool_call\b[\s\S]*?```/gi, "");
350
+ out = out.replace(/<think\b[^>]*>[\s\S]*?<\/think>/gi, "");
351
+ out = out.replace(/<think\b[^>]*>[\s\S]*?(?=^#{1,3}\s+\S|\n\s*\n)/im, "");
352
+ out = out.replace(/^\s*\{\s*"name"\s*:\s*"[\w._-]+"\s*,\s*"arguments"\s*:[\s\S]*?\}\s*$/gm, "");
353
+ out = unwrapDocumentFence(out);
354
+ out = peelMetaNarration(out);
355
+ out = out.replace(/\n{3,}/g, "\n\n").trim();
356
+ return out;
357
+ }
358
+ function extractDsmlContent(content) {
359
+ if (!content) return null;
360
+ const P = DSML_PIPE_CLASS;
361
+ const re = new RegExp(
362
+ `<\\s*${P}+\\s*DSML\\s*${P}+\\s*parameter\\b[^>]*\\bname\\s*=\\s*["']content["'][^>]*>([\\s\\S]*?)<\\s*/\\s*${P}+\\s*DSML\\s*${P}+\\s*parameter\\s*>`,
363
+ "i"
364
+ );
365
+ const m = content.match(re);
366
+ if (m && typeof m[1] === "string") {
367
+ const body = m[1].trim();
368
+ return body.length > 0 ? body : null;
369
+ }
370
+ return null;
371
+ }
372
+ function stripDsmlTags(content) {
373
+ const P = DSML_PIPE_CLASS;
374
+ let out = content;
375
+ out = out.replace(
376
+ new RegExp(
377
+ `<\\s*${P}+\\s*DSML\\s*${P}+\\s*tool_calls\\b[\\s\\S]*?<\\s*/\\s*${P}+\\s*DSML\\s*${P}+\\s*tool_calls\\s*>`,
378
+ "gi"
379
+ ),
380
+ ""
381
+ );
382
+ out = out.replace(new RegExp(`<\\s*/?\\s*${P}+\\s*DSML\\s*${P}+[^>]*>`, "gi"), "");
383
+ return out;
384
+ }
385
+ function unwrapDocumentFence(content) {
386
+ const trimmed = content.trim();
387
+ const open = trimmed.match(/^```\s*(markdown|md|gfm)?\s*\n/i);
388
+ if (!open) return content;
389
+ const afterOpen = trimmed.slice(open[0].length);
390
+ const closeMatch = afterOpen.match(/\n```\s*$/);
391
+ if (!closeMatch) return content;
392
+ const inner = afterOpen.slice(0, afterOpen.length - closeMatch[0].length);
393
+ if (inner.length < 200) return content;
394
+ return inner;
395
+ }
396
+ function peelMetaNarration(content) {
397
+ let out = content;
398
+ const firstHeadingMatch = out.match(/^#{1,3}\s+\S.*$/m);
399
+ if (firstHeadingMatch && firstHeadingMatch.index !== void 0) {
400
+ const before = out.slice(0, firstHeadingMatch.index);
401
+ const hasIntroMarker = /(?:以下(?:即为|是|就是)|这是|Here\s+is|Below\s+is|完整的?(?:审计报告|内容|文档)|审计报告(?:如下|的完整内容))/i.test(before);
402
+ if (before.length > 0 && before.length < 800 && hasIntroMarker) {
403
+ out = out.slice(firstHeadingMatch.index);
404
+ }
405
+ if (out.startsWith("---\n")) {
406
+ const headingAfterRule = out.slice(4).match(/^#{1,3}\s+\S/m);
407
+ if (headingAfterRule && headingAfterRule.index !== void 0 && headingAfterRule.index < 100) {
408
+ out = out.slice(4 + headingAfterRule.index);
409
+ }
410
+ }
411
+ }
412
+ const codaMatch = out.match(/\n[^\n]*?(?:以上(?:即为|就是|内容|为完整的?)|Above\s+is\s+the|本报告已经|该报告(?:已经|包含)|报告(?:已|至此)结束)[^\n]*$/i);
413
+ if (codaMatch && codaMatch.index !== void 0 && codaMatch.index > out.length / 2) {
414
+ out = out.slice(0, codaMatch.index);
415
+ }
416
+ return out.trim();
417
+ }
418
+ var META_NARRATION_HARD_MARKERS = [
419
+ /\[⚠️\s*CONTENT GENERATION MODE\]/,
420
+ /CONTENT_ONLY_STREAM_REMINDER\b/,
421
+ /<system-reminder>/i
422
+ ];
423
+ var META_NARRATION_HEURISTICS = [
424
+ /\bthe user (?:is asking me|wants me|is requesting|expects me)\b/i,
425
+ /\blet me (?:re-?read|re-?consider|reconsider|think about|carefully (?:re-?read|consider))\b/i,
426
+ /\bI'?m (?:in (?:a )?content-only|in CONTENT-ONLY|currently in)\b/i,
427
+ /\bI think (?:there might be|I should|I cannot|the (?:user|best)|maybe)\b/i,
428
+ /\bWait,?\s+let me\b/i,
429
+ /\bActually,?\s+I\b/i,
430
+ /\bI need to be honest with the user\b/i,
431
+ /\bI(?:'m| am) in a special mode\b/i,
432
+ /\bGiven that I cannot\b/i
433
+ ];
434
+ function detectMetaNarration(content) {
435
+ if (!content) return null;
436
+ const head = content.slice(0, 2e3);
437
+ for (const re of META_NARRATION_HARD_MARKERS) {
438
+ if (re.test(head)) return re.source;
439
+ }
440
+ if (/^#{1,3}\s+\S/m.test(head)) return null;
441
+ let hits = 0;
442
+ let firstMatch = "";
443
+ for (const re of META_NARRATION_HEURISTICS) {
444
+ if (re.test(head)) {
445
+ hits++;
446
+ if (!firstMatch) firstMatch = re.source;
447
+ if (hits >= 2) return `meta-narration:${firstMatch}`;
448
+ }
449
+ }
450
+ return null;
451
+ }
452
+ function looksLikeDocumentBody(content) {
453
+ if (!content || content.length < 200) return false;
454
+ if (/^#{1,6}\s+\S/m.test(content)) return true;
455
+ const paragraphs = content.split(/\n\s*\n/).filter((p) => p.trim().length > 30);
456
+ if (paragraphs.length >= 3) return true;
457
+ return false;
458
+ }
459
+ function stripToolCallReminder(systemPrompt) {
460
+ if (!systemPrompt) return systemPrompt;
461
+ const idx = systemPrompt.indexOf("[\u26A0\uFE0F Mandatory Tool Call Policy]");
462
+ if (idx === -1) return systemPrompt;
463
+ return systemPrompt.slice(0, idx).trimEnd();
464
+ }
465
+ var TEE_FINAL_USER_NUDGE = `\u26A0\uFE0F STOP using tools NOW. The save_last_response tee stream is open and capturing every token of THIS response. Output ONLY the requested document body, in markdown. The very first character of your response must be the document's top-level heading (e.g. "# \u5BA1\u8BA1\u62A5\u544A" / "# Audit Report"). Do NOT print <tool_call>, </tool_call>, <function_calls>, <invoke>, <tool_use>, <think>, or any other tool-call markup. Do NOT narrate that you will produce the document \u2014 just produce it. Do NOT pretend to call tools \u2014 there are none in this stream.`;
466
+ var CONTENT_ONLY_STREAM_REMINDER = `
467
+
468
+ [\u26A0\uFE0F CONTENT GENERATION MODE]
469
+ You are now in a CONTENT-ONLY streaming pass. The file at the configured path will receive every token of THIS response.
470
+ - Do NOT emit <tool_call>, </tool_call>, <function_calls>, <invoke>, <tool_use>, or any tool-call XML/JSON markup.
471
+ - Do NOT print "I will now call ...", "let me read ...", "<think>" reasoning blocks (the surrounding REPL handles those separately \u2014 they should not enter the saved file).
472
+ - Do NOT pretend to call tools. There are NO tools available in this stream \u2014 only your text output is captured.
473
+ - Produce ONLY the requested document body. Markdown is fine. Code blocks are fine. Tool-call markup is NOT.
474
+ - If you accidentally start a <tool_call>, STOP and produce the document body instead.
475
+
476
+ The file is closed and named when this stream ends. If your output contains pseudo-tool-call markup, the save will be REJECTED and you will be asked to retry.`;
477
+ function isCleanDocumentBody(content) {
478
+ if (!content) return false;
479
+ if (detectMetaNarration(content)) return false;
480
+ if (detectPseudoToolCalls(content)) return false;
481
+ return looksLikeDocumentBody(content);
482
+ }
483
+ function teeFileStats(content) {
484
+ return { lines: content.split("\n").length, bytes: Buffer.byteLength(content, "utf-8") };
485
+ }
486
+ function evaluateTeeContent(rawContent, saveToFile, priorContent) {
487
+ const fallback = (matched) => {
488
+ if (priorContent && priorContent !== rawContent && isCleanDocumentBody(priorContent)) {
489
+ const body = priorContent.trim();
490
+ const { lines: lines2, bytes: bytes2 } = teeFileStats(body);
491
+ return {
492
+ kind: "fallback",
493
+ content: body,
494
+ matched,
495
+ summary: `File saved (fallback to last shown response): ${saveToFile} (${lines2} lines, ${bytes2} bytes). The fresh content-only stream produced no usable document body (matched: ${matched}); saved the response you previously displayed instead. Verify it is the intended document.`
496
+ };
497
+ }
498
+ return null;
499
+ };
500
+ const metaMatch = detectMetaNarration(rawContent);
501
+ if (metaMatch) {
502
+ return fallback(metaMatch) ?? {
503
+ kind: "reject",
504
+ reason: "meta-narration",
505
+ matched: metaMatch,
506
+ summary: `[save_last_response REJECTED] Your output was internal reasoning / meta-narration (e.g. "Let me re-read\u2026", "the user is asking me to\u2026") instead of the requested document body (matched: ${metaMatch}). ${saveToFile} was NOT saved.
507
+
508
+ This fresh stream has NO tools. Produce ONLY the document body: start with a markdown heading like "# \u5BA1\u8BA1\u62A5\u544A" / "# Audit Report" and write the full content. Do NOT narrate that you will produce the document \u2014 produce it.`
509
+ };
510
+ }
511
+ const pseudoMatch = detectPseudoToolCalls(rawContent);
512
+ if (pseudoMatch) {
513
+ const cleaned = stripPseudoToolCalls(rawContent);
514
+ if (looksLikeDocumentBody(cleaned)) {
515
+ const { lines: lines2, bytes: bytes2 } = teeFileStats(cleaned);
516
+ return {
517
+ kind: "salvaged",
518
+ content: cleaned,
519
+ matched: pseudoMatch,
520
+ summary: `File saved (with cleanup): ${saveToFile} (${lines2} lines, ${bytes2} bytes; pseudo-tool-call markup matching ${pseudoMatch} was stripped before save)`
521
+ };
522
+ }
523
+ return fallback(pseudoMatch) ?? {
524
+ kind: "reject",
525
+ reason: "pseudo-tool-call",
526
+ matched: pseudoMatch,
527
+ summary: `[save_last_response REJECTED] Your output was tool-call markup with no usable document body (matched: ${pseudoMatch}). ${saveToFile} was NOT saved.
528
+
529
+ This fresh stream has NO tools \u2014 output is captured verbatim. STOP emitting <tool_call>, <function_calls>, <invoke>, <think>, or JSON tool blocks. Produce the document body NOW: start with a markdown heading like "# \u5BA1\u8BA1\u62A5\u544A" and write the full report.`
530
+ };
531
+ }
532
+ const { lines, bytes } = teeFileStats(rawContent);
533
+ return {
534
+ kind: "ok",
535
+ content: rawContent,
536
+ summary: `File saved: ${saveToFile} (${lines} lines, ${bytes} bytes)`
537
+ };
538
+ }
539
+ function teeStreamErrorSummary(saveToFile, errMsg) {
540
+ return `[save_last_response failed] streaming was interrupted: ${errMsg}. ${saveToFile} (partial) was deleted. Retry \u2014 and consider producing a more compact output (split very large reports across multiple save_last_response calls if the previous attempt timed out).`;
541
+ }
542
+
543
+ // src/core/agent-loop.ts
544
+ function partialTagTail(s, tag) {
545
+ const max = Math.min(s.length, tag.length - 1);
546
+ for (let len = max; len > 0; len--) {
547
+ if (s.endsWith(tag.slice(0, len))) return len;
548
+ }
549
+ return 0;
550
+ }
551
+ var ThinkTagFilter = class {
552
+ inThink = false;
553
+ buf = "";
554
+ push(raw) {
555
+ this.buf += raw;
556
+ let out = "";
557
+ while (this.buf.length > 0) {
558
+ if (!this.inThink) {
559
+ const open = this.buf.indexOf("<think>");
560
+ if (open === -1) {
561
+ const keep = partialTagTail(this.buf, "<think>");
562
+ out += this.buf.slice(0, this.buf.length - keep);
563
+ this.buf = this.buf.slice(this.buf.length - keep);
564
+ break;
565
+ }
566
+ out += this.buf.slice(0, open);
567
+ this.buf = this.buf.slice(open + "<think>".length);
568
+ this.inThink = true;
569
+ } else {
570
+ const close = this.buf.indexOf("</think>");
571
+ if (close === -1) {
572
+ const keep = partialTagTail(this.buf, "</think>");
573
+ this.buf = this.buf.slice(this.buf.length - keep);
574
+ break;
575
+ }
576
+ this.buf = this.buf.slice(close + "</think>".length);
577
+ this.inThink = false;
578
+ }
579
+ }
580
+ return out;
581
+ }
582
+ /** 流结束:若仍持留可能的半截 '<think>' 前缀且并未进入 think 块,它是真实文本。 */
583
+ flush() {
584
+ if (!this.inThink && this.buf) {
585
+ const tail = this.buf;
586
+ this.buf = "";
587
+ return tail;
588
+ }
589
+ this.buf = "";
590
+ return "";
591
+ }
592
+ };
593
+ function repairToolCallArguments(raw, onWarn) {
594
+ const argStr = raw || "{}";
595
+ try {
596
+ return JSON.parse(argStr);
597
+ } catch {
598
+ const truncated = argStr.trimEnd();
599
+ const lastComma = truncated.lastIndexOf(",");
600
+ const fixed = lastComma > 0 ? truncated.slice(0, lastComma) + "}" : truncated.slice(0, truncated.indexOf("{") + 1) + "}";
601
+ try {
602
+ const repaired = JSON.parse(fixed);
603
+ onWarn?.("Tool call JSON was truncated and auto-repaired. Some parameters may be missing.");
604
+ return repaired;
605
+ } catch {
606
+ onWarn?.("Tool call JSON could not be parsed, using empty arguments.");
607
+ return {};
608
+ }
609
+ }
610
+ }
611
+ async function consumeToolCallStream(stream, hooks = {}) {
612
+ const textParts = [];
613
+ const accumulators = /* @__PURE__ */ new Map();
614
+ let usage;
615
+ let rawContent;
616
+ let reasoningContent;
617
+ let finishReason;
618
+ let aborted = false;
619
+ const thinkFilter = new ThinkTagFilter();
620
+ const emitText = (raw) => {
621
+ const visible = thinkFilter.push(raw);
622
+ if (visible) {
623
+ textParts.push(visible);
624
+ hooks.onText?.(visible);
625
+ }
626
+ };
627
+ try {
628
+ for await (const event of stream) {
629
+ if (hooks.signal?.aborted) {
630
+ aborted = true;
631
+ break;
632
+ }
633
+ switch (event.type) {
634
+ case "text_delta":
635
+ emitText(event.delta);
636
+ break;
637
+ case "thinking_start":
638
+ hooks.onThinkingStart?.();
639
+ break;
640
+ case "thinking_delta":
641
+ hooks.onThinkingDelta?.(event.delta);
642
+ break;
643
+ case "thinking_end":
644
+ hooks.onThinkingEnd?.();
645
+ break;
646
+ case "tool_call_start":
647
+ accumulators.set(event.index, { id: event.id, name: event.name, arguments: "" });
648
+ hooks.onToolCallStart?.(event.index, event.id, event.name);
649
+ break;
650
+ case "tool_call_delta": {
651
+ const acc = accumulators.get(event.index);
652
+ if (acc) acc.arguments += event.argumentsDelta;
653
+ break;
654
+ }
655
+ case "tool_call_end":
656
+ break;
657
+ case "done":
658
+ if (event.usage) usage = event.usage;
659
+ if (event.rawContent) rawContent = event.rawContent;
660
+ if (event.reasoningContent) reasoningContent = event.reasoningContent;
661
+ if (event.finishReason) finishReason = event.finishReason;
662
+ break;
663
+ }
664
+ }
665
+ } catch (err) {
666
+ if (err instanceof Error && (err.name === "AbortError" || err.message.includes("aborted"))) {
667
+ aborted = true;
668
+ } else {
669
+ throw err;
670
+ }
671
+ }
672
+ const tail = thinkFilter.flush();
673
+ if (tail && !aborted) {
674
+ textParts.push(tail);
675
+ hooks.onText?.(tail);
676
+ }
677
+ const textContent = textParts.join("");
678
+ if (aborted) {
679
+ return { textContent, toolCalls: [], usage, rawContent, reasoningContent, finishReason, aborted };
680
+ }
681
+ const toolCalls = [];
682
+ for (const [, acc] of accumulators) {
683
+ toolCalls.push({
684
+ id: acc.id,
685
+ name: acc.name,
686
+ arguments: repairToolCallArguments(acc.arguments, hooks.onWarn)
687
+ });
688
+ }
689
+ if (toolCalls.length > 0) {
690
+ if (rawContent) {
691
+ toolCalls._rawContent = rawContent;
692
+ }
693
+ if (textContent) {
694
+ toolCalls._streamedText = textContent;
695
+ }
696
+ }
697
+ return { textContent, toolCalls, usage, rawContent, reasoningContent, finishReason, aborted };
698
+ }
699
+ var FREE_ROUND_TOOLS = /* @__PURE__ */ new Set(["write_todos"]);
700
+ var MAX_CONSECUTIVE_FREE_ROUNDS = 3;
701
+ var FreeRoundTracker = class {
702
+ consecutive = 0;
703
+ /** 返回 true 表示本轮不消耗有效轮次(调用方执行 round--)。 */
704
+ apply(toolNames) {
705
+ const allFree = toolNames.length > 0 && toolNames.every((n) => FREE_ROUND_TOOLS.has(n));
706
+ if (!allFree) {
707
+ this.consecutive = 0;
708
+ return false;
709
+ }
710
+ this.consecutive++;
711
+ return this.consecutive <= MAX_CONSECUTIVE_FREE_ROUNDS;
712
+ }
713
+ };
714
+ var BudgetWarner = class {
715
+ constructor(maxToolRounds) {
716
+ this.maxToolRounds = maxToolRounds;
717
+ this.noteAt = Math.max(10, Math.floor(maxToolRounds * 0.2));
718
+ const lowRaw = Math.max(5, Math.floor(maxToolRounds * 0.1));
719
+ const criticalRaw = Math.max(3, Math.floor(maxToolRounds * 0.05));
720
+ this.lowAt = Math.min(lowRaw, this.noteAt - 1);
721
+ this.criticalAt = Math.min(criticalRaw, this.lowAt - 1);
722
+ }
723
+ noteAt;
724
+ lowAt;
725
+ criticalAt;
726
+ warnedNote = false;
727
+ warnedLow = false;
728
+ warnedCritical = false;
729
+ check(roundsLeft) {
730
+ if (!this.warnedCritical && roundsLeft <= this.criticalAt) {
731
+ this.warnedCritical = true;
732
+ return {
733
+ level: "critical",
734
+ injectMessage: `\u{1F6A8} Critical budget: Only ${roundsLeft} rounds left! Wrap up NOW \u2014 complete the current operation and give a final summary. Do NOT start new tasks.`,
735
+ displayMessage: `\u{1F6A8} Critical: ${roundsLeft} rounds remaining`
736
+ };
737
+ }
738
+ if (!this.warnedLow && roundsLeft <= this.lowAt) {
739
+ this.warnedLow = true;
740
+ return {
741
+ level: "low",
742
+ injectMessage: `\u26A0\uFE0F Budget warning: Only ${roundsLeft} tool rounds remaining. Prioritize completing the most critical task. Use efficient approaches (batch edits, fewer reads). If you cannot finish everything, summarize what's done and what remains.`,
743
+ displayMessage: `\u26A0\uFE0F Low budget: ${roundsLeft} rounds remaining`
744
+ };
745
+ }
746
+ if (!this.warnedNote && roundsLeft <= this.noteAt) {
747
+ this.warnedNote = true;
748
+ return {
749
+ level: "note",
750
+ injectMessage: `\u{1F4CA} Budget note: ${roundsLeft} tool rounds remaining out of ${this.maxToolRounds}. Plan your remaining work efficiently \u2014 use batch operations (e.g., replaceAll) when possible.`
751
+ };
752
+ }
753
+ return null;
754
+ }
755
+ };
756
+ var EMPTY_RESPONSE_NUDGE = "Your previous response was empty \u2014 no text and no tool calls. This usually means the context window is nearly full. Please either: (1) continue the task by calling the next tool you need, or (2) give a concise final text summary of what has been accomplished so far and what remains. Do NOT repeat earlier long outputs.";
757
+ function describeFinishReason(fr) {
758
+ if (fr === "length") return "output limit reached (finish_reason=length)";
759
+ if (fr === "content_filter") return "content blocked (finish_reason=content_filter)";
760
+ if (fr) return `empty response (finish_reason=${fr})`;
761
+ return "empty response";
762
+ }
763
+ function emptyResponseHint(fr) {
764
+ if (fr === "length") return "Output token limit hit \u2014 try /compact to reduce context, raise maxTokens, or /model to switch.";
765
+ if (fr === "content_filter") return "Content was blocked by the provider filter.";
766
+ return "Context window may be exhausted or max_tokens too low.";
767
+ }
768
+ var EmptyResponseGuard = class {
769
+ retries = 0;
770
+ onEmpty(canRetry, finishReason) {
771
+ if (this.retries === 0 && canRetry) {
772
+ this.retries++;
773
+ return {
774
+ action: "nudge",
775
+ injectMessage: EMPTY_RESPONSE_NUDGE,
776
+ displayMessage: `\u26A0 ${describeFinishReason(finishReason)} \u2014 nudging AI to continue...`
777
+ };
778
+ }
779
+ return {
780
+ action: "stop",
781
+ displayMessage: "\u26A0 AI returned empty responses twice in a row. Stopping agentic loop.",
782
+ hint: emptyResponseHint(finishReason)
783
+ };
784
+ }
785
+ /** 非空响应到达 → 重置计数(下次空响应仍可 nudge 一次)。 */
786
+ onNonEmpty() {
787
+ this.retries = 0;
788
+ }
789
+ };
790
+ var ContextPressureMonitor = class {
791
+ warned80 = false;
792
+ check(requestTokens, contextWindow) {
793
+ if (contextWindow <= 0) return { action: "ok", ratio: 0 };
794
+ const ratio = requestTokens / contextWindow;
795
+ if (ratio >= 0.95) return { action: "abort", ratio };
796
+ if (ratio >= 0.8 && !this.warned80) {
797
+ this.warned80 = true;
798
+ return {
799
+ action: "warn",
800
+ ratio,
801
+ injectMessage: `\u26A0\uFE0F Context pressure: ~${Math.round(ratio * 100)}% of the ${contextWindow.toLocaleString()}-token context window is used. Avoid reading more files or running broad scans. Finish the current critical step, then produce a final summary. Every unnecessary tool call now risks breaking the conversation.`
802
+ };
803
+ }
804
+ return { action: "ok", ratio };
805
+ }
806
+ };
807
+ function accumulateUsage(total, delta) {
808
+ if (!delta) return;
809
+ total.inputTokens += delta.inputTokens;
810
+ total.outputTokens += delta.outputTokens;
811
+ total.cacheCreationTokens += delta.cacheCreationTokens ?? 0;
812
+ total.cacheReadTokens += delta.cacheReadTokens ?? 0;
813
+ }
814
+ function buildRoundBudgetHint(opts) {
815
+ const pauseHint = opts.autoPauseInterval > 0 ? `
816
+ - Every ${opts.autoPauseInterval} rounds the user will be asked whether to continue \u2014 use this as a natural checkpoint to report progress.` : "";
817
+ if (opts.planMode) {
818
+ return `
819
+
820
+ [Tool Round Budget \u2014 Plan Mode]
821
+ You have a maximum of ${opts.maxToolRounds} tool call rounds. You are in READ-ONLY Plan Mode:
822
+ - Only use: read_file, list_dir, grep_files, glob_files, ask_user, write_todos
823
+ - Do NOT attempt to call bash, write_file, edit_file \u2014 they are disabled
824
+ - Do NOT write shell commands or code blocks as a substitute for tool calls
825
+ - Do NOT read the same file more than once
826
+ - Call write_todos ONCE to present your plan, then give a text summary
827
+ - If the user asks you to execute anything, respond: "Please type /plan execute to switch to execute mode."${pauseHint}`;
828
+ }
829
+ return `
830
+
831
+ [Tool Round Budget]
832
+ You have a maximum of ${opts.maxToolRounds} tool call rounds for this task. Plan efficiently:
833
+ - Prefer batch operations (e.g. global find-and-replace) over repetitive single edits.
834
+ - Do NOT read the same file more than once \u2014 use the content from previous reads.
835
+ - Prioritize the most critical tasks first in case rounds run out.
836
+ - When remaining rounds are low, focus on completing the current task and summarizing.${pauseHint}`;
837
+ }
838
+ function buildRoundsExhaustedPrompt(maxToolRounds) {
839
+ return `You have used all ${maxToolRounds} tool call rounds. Do not call any more tools. Summarize in text:
840
+ 1. What work has been completed so far
841
+ 2. What tasks remain unfinished
842
+ 3. What the user can do next (e.g. send another request to continue)`;
843
+ }
844
+ function buildUserStopMessage(effectiveRound, maxToolRounds) {
845
+ return `The user has stopped the task at round ${effectiveRound}/${maxToolRounds}. Do not call any more tools. Summarize what has been completed and what remains.`;
846
+ }
847
+ async function runAgentLoop(host) {
848
+ const { maxToolRounds, autoPauseInterval, usage } = host;
849
+ const extraMessages = [];
850
+ const budgetWarner = new BudgetWarner(maxToolRounds);
851
+ const emptyGuard = new EmptyResponseGuard();
852
+ const ctxMonitor = new ContextPressureMonitor();
853
+ const freeRounds = new FreeRoundTracker();
854
+ const roundToolHistory = [];
855
+ const hasWriteTools = host.toolDefs.some((t) => t.name === "write_file" || t.name === "edit_file");
856
+ for (let round = 0; round < maxToolRounds; round++) {
857
+ if (host.signal?.aborted) return { reason: "aborted", usage };
858
+ host.onRoundStart?.(round, maxToolRounds);
859
+ if (await host.beforeRound?.(round, extraMessages) === "stop") {
860
+ return { reason: "stopped", usage };
861
+ }
862
+ const warning = budgetWarner.check(maxToolRounds - round);
863
+ if (warning) {
864
+ extraMessages.push({ role: "user", content: warning.injectMessage });
865
+ host.onBudgetWarning?.(warning);
866
+ }
867
+ const interjection = host.pollInterjection?.();
868
+ if (interjection) extraMessages.push({ role: "user", content: interjection });
869
+ const ctxWindow = host.getContextWindow();
870
+ if (ctxWindow > 0) {
871
+ const pressure = ctxMonitor.check(host.estimateRequestTokens(extraMessages), ctxWindow);
872
+ if (pressure.action === "abort") {
873
+ host.onContextPressure?.(pressure, ctxWindow, round);
874
+ return { reason: "context-overflow", usage };
875
+ } else if (pressure.action === "warn") {
876
+ host.onContextPressure?.(pressure, ctxWindow, round);
877
+ extraMessages.push({ role: "user", content: pressure.injectMessage });
878
+ }
879
+ }
880
+ const outcome = await host.callModel(round, extraMessages);
881
+ if (host.signal?.aborted) return { reason: "aborted", usage };
882
+ accumulateUsage(usage, outcome.usage);
883
+ if (outcome.stopLoop) return { reason: "host-stop", usage };
884
+ const toolCalls = outcome.toolCalls ?? [];
885
+ if (toolCalls.length === 0) {
886
+ const content = outcome.content ?? "";
887
+ const alreadyRendered = !!outcome.alreadyRendered;
888
+ const alreadyWrote = hadPreviousWriteToolCalls(extraMessages);
889
+ const coarseHallucination = !host.planMode && hasWriteTools && !alreadyWrote && !!content && detectsHallucinatedFileOp(content);
890
+ const phantomPaths = (coarseHallucination || alreadyWrote) && !host.planMode && hasWriteTools && content ? findPhantomClaims(content, extraMessages) : [];
891
+ const bashRanThisTurn = extractBashCommands(extraMessages).length > 0;
892
+ const coarseShouldFire = coarseHallucination && !bashRanThisTurn;
893
+ if ((phantomPaths.length > 0 || coarseShouldFire) && round < maxToolRounds - 1) {
894
+ host.onHallucinationRetry?.({ phantomPaths, round, alreadyRendered });
895
+ const correctionMsg = phantomPaths.length > 0 ? buildPhantomCorrectionMessage(phantomPaths) : HALLUCINATION_CORRECTION_MESSAGE;
896
+ const reasoningField = outcome.reasoningContent ? { reasoning_content: outcome.reasoningContent } : host.providerId === "deepseek" ? { reasoning_content: "" } : {};
897
+ extraMessages.push(
898
+ { role: "assistant", content, ...reasoningField },
899
+ { role: "user", content: correctionMsg }
900
+ );
901
+ continue;
902
+ }
903
+ if (!content || content.trim() === "") {
904
+ const decision = emptyGuard.onEmpty(round < maxToolRounds - 1, outcome.finishReason);
905
+ host.onEmptyResponse?.(decision, { alreadyRendered, round });
906
+ if (decision.action === "nudge") {
907
+ extraMessages.push({ role: "user", content: decision.injectMessage });
908
+ continue;
909
+ }
910
+ return { reason: "empty-response", usage };
911
+ }
912
+ emptyGuard.onNonEmpty();
913
+ await host.onFinalContent(content, { reasoningContent: outcome.reasoningContent, alreadyRendered });
914
+ return { reason: "final", usage };
915
+ }
916
+ emptyGuard.onNonEmpty();
917
+ const saveCall = toolCalls.find((tc) => tc.name === "save_last_response");
918
+ const savePath = saveCall ? String(saveCall.arguments["path"] ?? "") : "";
919
+ if (saveCall && savePath && host.runSaveLastResponseTee) {
920
+ const directive = await host.runSaveLastResponseTee({
921
+ toolCalls,
922
+ call: saveCall,
923
+ saveToFile: savePath,
924
+ extraMessages,
925
+ reasoningContent: outcome.reasoningContent
926
+ });
927
+ if (directive === "stop") return { reason: "tee-stop", usage };
928
+ freeRounds.apply(toolCalls.map((tc) => tc.name));
929
+ continue;
930
+ }
931
+ const toolResults = await host.executeTools(toolCalls, extraMessages);
932
+ if (host.isInterrupted?.() || host.signal?.aborted) {
933
+ host.onInterrupted?.();
934
+ return { reason: "aborted", usage };
935
+ }
936
+ roundToolHistory.push({ round: round + 1, tools: toolCalls.map((tc) => tc.name) });
937
+ host.onToolsExecuted?.(toolCalls, toolResults, extraMessages);
938
+ extraMessages.push(...host.buildToolResultMessages(toolCalls, toolResults, outcome.reasoningContent));
939
+ for (const tc of toolCalls) {
940
+ if (tc.name.startsWith("mcp__")) host.onMcpToolUsed?.(tc.name);
941
+ }
942
+ host.persistRound?.(toolCalls, toolResults, {
943
+ assistantContent: outcome.content,
944
+ reasoningContent: outcome.reasoningContent
945
+ });
946
+ host.afterToolRoundPersist?.(toolCalls, toolResults, extraMessages);
947
+ if (freeRounds.apply(toolCalls.map((tc) => tc.name))) {
948
+ round--;
949
+ }
950
+ if (host.checkLoopHealth?.(toolCalls, extraMessages) === "skip-checkpoint") continue;
951
+ const postInterjection = host.pollInterjection?.();
952
+ if (postInterjection) extraMessages.push({ role: "user", content: postInterjection });
953
+ const effectiveRound = round + 1;
954
+ const remaining = maxToolRounds - effectiveRound;
955
+ if (autoPauseInterval > 0 && effectiveRound > 0 && effectiveRound % autoPauseInterval === 0 && remaining > 0 && !host.signal?.aborted && host.requestAutoPause) {
956
+ const toolSummary = summarizeRecentTools(roundToolHistory, autoPauseInterval);
957
+ const resp = await host.requestAutoPause({ effectiveRound, maxToolRounds, remaining, toolSummary });
958
+ if (host.signal?.aborted) return { reason: "aborted", usage };
959
+ if (resp.action === "stop") {
960
+ extraMessages.push({ role: "user", content: buildUserStopMessage(effectiveRound, maxToolRounds) });
961
+ break;
962
+ } else if (resp.action === "redirect" && resp.message) {
963
+ extraMessages.push({ role: "user", content: resp.message });
964
+ }
965
+ }
966
+ host.onRoundEnd?.(round);
967
+ }
968
+ let summaryContent = null;
969
+ try {
970
+ const summaryExtra = [
971
+ ...extraMessages,
972
+ { role: "user", content: buildRoundsExhaustedPrompt(maxToolRounds) }
973
+ ];
974
+ const summary = await host.callSummary(summaryExtra);
975
+ accumulateUsage(usage, summary.usage);
976
+ summaryContent = summary.content && summary.content.trim() ? summary.content : null;
977
+ } catch {
978
+ summaryContent = null;
979
+ }
980
+ await host.onRoundsExhausted(summaryContent);
981
+ return { reason: "rounds-exhausted", usage };
982
+ }
983
+ function summarizeRecentTools(history, interval) {
984
+ const recent = history.slice(-interval);
985
+ const counts = /* @__PURE__ */ new Map();
986
+ for (const rh of recent) {
987
+ for (const t of rh.tools) counts.set(t, (counts.get(t) || 0) + 1);
988
+ }
989
+ return [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([name, count]) => count > 1 ? `${name}\xD7${count}` : name).join(", ");
990
+ }
991
+ async function runLeanAgentLoop(opts) {
992
+ const extraMessages = [];
993
+ const usage = { inputTokens: 0, outputTokens: 0 };
994
+ let content = "";
995
+ let roundsUsed = 0;
996
+ let toolCallCount = 0;
997
+ try {
998
+ for (let round = 0; round < opts.maxRounds; round++) {
999
+ roundsUsed = round + 1;
1000
+ opts.onRoundStart?.(round, opts.maxRounds);
1001
+ const result = await opts.provider.chatWithTools(
1002
+ {
1003
+ messages: opts.messages,
1004
+ model: opts.model,
1005
+ systemPrompt: opts.systemPromptForRound(round, opts.maxRounds - round),
1006
+ stream: false,
1007
+ temperature: opts.chatParams?.temperature,
1008
+ maxTokens: opts.chatParams?.maxTokens,
1009
+ timeout: opts.chatParams?.timeout,
1010
+ thinking: opts.chatParams?.thinking,
1011
+ ...extraMessages.length > 0 ? { _extraMessages: extraMessages } : {}
1012
+ },
1013
+ opts.toolDefsForRound(round)
1014
+ );
1015
+ if (result.usage) {
1016
+ usage.inputTokens += result.usage.inputTokens;
1017
+ usage.outputTokens += result.usage.outputTokens;
1018
+ }
1019
+ if ("content" in result) {
1020
+ content = result.content;
1021
+ break;
1022
+ }
1023
+ toolCallCount += result.toolCalls.length;
1024
+ const toolResults = await opts.executeTools(result.toolCalls);
1025
+ const reasoningContent = "reasoningContent" in result ? result.reasoningContent : void 0;
1026
+ extraMessages.push(
1027
+ ...opts.provider.buildToolResultMessages(result.toolCalls, toolResults, reasoningContent)
1028
+ );
1029
+ }
1030
+ if (!content) content = opts.onRoundsExhausted(toolCallCount);
1031
+ } catch (err) {
1032
+ const errMsg = err instanceof Error ? err.message : String(err);
1033
+ content = opts.onError(errMsg);
1034
+ }
1035
+ return { content, usage, roundsUsed, toolCallCount };
1036
+ }
1037
+
1038
+ export {
1039
+ isFileWriteTool,
1040
+ getDangerLevel,
1041
+ schemaToJsonSchema,
1042
+ detectsHallucinatedFileOp,
1043
+ TOOL_CALL_REMINDER,
1044
+ buildWriteRoundReminder,
1045
+ extractWrittenFilePaths,
1046
+ stripToolCallReminder,
1047
+ TEE_FINAL_USER_NUDGE,
1048
+ CONTENT_ONLY_STREAM_REMINDER,
1049
+ evaluateTeeContent,
1050
+ teeStreamErrorSummary,
1051
+ ThinkTagFilter,
1052
+ repairToolCallArguments,
1053
+ consumeToolCallStream,
1054
+ accumulateUsage,
1055
+ buildRoundBudgetHint,
1056
+ runAgentLoop,
1057
+ runLeanAgentLoop
1058
+ };