u-foo 3.1.4 → 3.1.6

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/README.md CHANGED
@@ -67,6 +67,17 @@ Installed binaries:
67
67
  | `ukimi` | Kimi Code wrapper with ufoo bootstrap and bus identity. |
68
68
  | `ucode` | Native ufoo coding-agent CLI/TUI. |
69
69
 
70
+ `ucode` has no tool-call count limit by default. Set an optional per-run cap with
71
+ `ucode --max-tool-calls 200`, or `UFOO_UCODE_MAX_TOOL_CALLS=200 ucode`.
72
+ `ucode --max-tool-calls none` explicitly disables the cap, including an environment
73
+ override. The CLI option takes precedence. Limits count individual tool calls,
74
+ not model turns; timeouts and the tool-error budget still apply.
75
+ Consecutive identical tool batches trigger a model reminder, then stop the run
76
+ if repetition continues: read/plan-only batches warn at 4 steps and stop at 8;
77
+ other batches warn at 8 and stop at 12. Comparison uses tool names and arguments,
78
+ ignoring JSON key order and parallel call order. A different batch resets the
79
+ streak; this is not a semantic check of tool results or alternating loops.
80
+
70
81
  ## Quick Start
71
82
 
72
83
  Initialize a project and open the chat dashboard:
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "u-foo",
3
- "version": "3.1.4",
3
+ "version": "3.1.6",
4
4
  "description": "Multi-Agent Workspace Protocol. Just add u. claude → uclaude, codex → ucodex.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://ufoo.dev",
package/src/code/agent.js CHANGED
@@ -667,6 +667,7 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
667
667
  messages: historyMessages,
668
668
  sessionId: String(sessionIdValue || state.sessionId || ""),
669
669
  timeoutMs: timeoutOverrideMs,
670
+ maxToolCalls: state.maxToolCalls,
670
671
  onStreamDelta: onStream,
671
672
  onThinkingDelta,
672
673
  onPhase,
@@ -1178,6 +1179,7 @@ async function resumeAfterUserInteraction(answerText = "", state = {}, options =
1178
1179
  messages,
1179
1180
  sessionId: String(state.sessionId || ""),
1180
1181
  onToolEvent: pushToolLog,
1182
+ maxToolCalls: state.maxToolCalls,
1181
1183
  onStreamDelta: trackingOnDelta,
1182
1184
  onThinkingDelta: typeof options.onThinkingDelta === "function" ? options.onThinkingDelta : null,
1183
1185
  onPhase: typeof options.onPhase === "function" ? options.onPhase : null,
@@ -1311,6 +1313,7 @@ if (require.main === module) {
1311
1313
  systemPrompt: parsed.systemPrompt,
1312
1314
  sessionId: parsed.sessionId,
1313
1315
  timeoutMs: parsed.timeoutMs,
1316
+ maxToolCalls: parsed.maxToolCalls,
1314
1317
  jsonOutput: parsed.jsonOutput,
1315
1318
  forceTui: parsed.forceTui,
1316
1319
  disableTui: parsed.disableTui,
@@ -50,91 +50,84 @@ function expandHome(filePath = "") {
50
50
  return text;
51
51
  }
52
52
 
53
- /**
54
- * Extract image file paths from terminal paste / drag-drop text.
55
- * Supports file://, quoted paths with spaces, and bare absolute paths.
56
- */
57
- function extractImagePathsFromPaste(text = "") {
53
+ // Parse terminal shell quoting without evaluating shell expressions. Keep source
54
+ // spans so the exact pasted spelling (including escapes) can be removed later.
55
+ function imagePathMatches(text = "") {
58
56
  const raw = String(text || "");
59
- if (!raw.trim()) return [];
60
- const found = [];
61
- const seen = new Set();
62
-
63
- function pushPath(candidate) {
64
- let next = decodeFileUrl(String(candidate || "").trim());
65
- next = next.replace(/^['"]|['"]$/g, "");
66
- if (!looksLikeImagePath(next)) return;
67
- next = expandHome(next);
68
- const key = path.resolve(next);
69
- if (seen.has(key)) return;
70
- seen.add(key);
71
- found.push(next);
72
- }
73
-
74
- // Quoted paths (possibly with spaces)
75
- const quoted = /["']([^"']+\.(?:png|jpe?g|gif|webp))["']/gi;
76
- let match;
77
- while ((match = quoted.exec(raw))) {
78
- pushPath(match[1]);
79
- }
80
-
81
- // file:// URLs
82
- const fileUrls = /file:\/\/[^\s"'<>]+/gi;
83
- while ((match = fileUrls.exec(raw))) {
84
- pushPath(match[0]);
85
- }
86
-
87
- // Bare tokens / lines
88
- for (const line of raw.split(/\r?\n/)) {
89
- const trimmed = line.trim();
90
- if (!trimmed) continue;
91
- if (looksLikeImagePath(trimmed)) {
92
- pushPath(trimmed);
93
- continue;
57
+ const matches = [];
58
+ let offset = 0;
59
+ for (const line of raw.split(/\n/)) {
60
+ const tokens = [];
61
+ let i = 0;
62
+ while (i < line.length) {
63
+ if (/\s/.test(line[i])) { i += 1; continue; }
64
+ const start = i;
65
+ let value = "";
66
+ let quote = "";
67
+ const windowsPath = /^[A-Za-z]:[\\/]/.test(line.slice(i).replace(/^["']/, ""));
68
+ while (i < line.length) {
69
+ const ch = line[i];
70
+ if (!quote && /\s/.test(ch)) break;
71
+ if (ch === quote) { quote = ""; i += 1; continue; }
72
+ if (!quote && (ch === "'" || ch === '"')) { quote = ch; i += 1; continue; }
73
+ if (ch === "\\" && quote !== "'" && !windowsPath && i + 1 < line.length
74
+ && (!quote || /[\\"$`]/.test(line[i + 1]))) {
75
+ value += line[i + 1];
76
+ i += 2;
77
+ continue;
78
+ }
79
+ value += ch;
80
+ i += 1;
81
+ }
82
+ tokens.push({ value, start: offset + start, end: offset + i });
94
83
  }
95
- for (const token of trimmed.split(/\s+/)) {
96
- if (looksLikeImagePath(token)) pushPath(token);
84
+ const trimmed = line.trim();
85
+ // Preserve support for a raw, unquoted absolute filename containing spaces.
86
+ // Escaped or quoted terminal input always uses the tokenized path above.
87
+ const rawWholePath = !/[\\"']/.test(trimmed)
88
+ && looksLikeImagePath(trimmed)
89
+ && tokens.filter((token) => looksLikeImagePath(token.value)).length < 2
90
+ && !tokens.slice(1).some((token) => /^(?:\/|file:\/\/|~\/)/.test(token.value));
91
+ const candidates = rawWholePath
92
+ ? [{ value: trimmed, start: offset + line.indexOf(trimmed), end: offset + line.indexOf(trimmed) + trimmed.length }]
93
+ : tokens;
94
+ for (const token of candidates) {
95
+ if (!looksLikeImagePath(token.value)) continue;
96
+ matches.push({ ...token, path: expandHome(decodeFileUrl(token.value)) });
97
97
  }
98
+ offset += line.length + 1;
98
99
  }
100
+ return matches;
101
+ }
99
102
 
100
- return found;
103
+ function extractImagePathsFromPaste(text = "") {
104
+ const seen = new Set();
105
+ return imagePathMatches(text).flatMap((match) => {
106
+ const key = path.resolve(match.path);
107
+ if (seen.has(key)) return [];
108
+ seen.add(key);
109
+ return [match.path];
110
+ });
101
111
  }
102
112
 
103
113
  function stripExtractedPathsFromText(text = "", paths = []) {
104
114
  let out = String(text || "");
105
- for (const p of paths) {
106
- const variants = [
107
- `"${p}"`,
108
- `'${p}'`,
109
- p,
110
- p.startsWith("/") ? `file://${p}` : "",
111
- p.startsWith("/") ? `file://${encodeURI(p)}` : "",
112
- ].filter(Boolean);
113
- for (const v of variants) {
114
- out = out.split(v).join(" ");
115
- }
115
+ const selected = new Set(paths.map((p) => path.resolve(p)));
116
+ const matches = imagePathMatches(out).filter((match) => selected.has(path.resolve(match.path)));
117
+ for (const match of matches.reverse()) {
118
+ out = `${out.slice(0, match.start)} ${out.slice(match.end)}`;
116
119
  }
117
- return out
118
- .replace(/[ \t]+\n/g, "\n")
119
- .replace(/\n{3,}/g, "\n\n")
120
- .replace(/[ \t]{2,}/g, " ")
121
- .replace(/\s+"/g, " ")
122
- .replace(/"\s+/g, " ")
123
- .replace(/\s+'/g, " ")
124
- .replace(/'\s+/g, " ")
125
- .trim();
120
+ return out.replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n")
121
+ .replace(/[ \t]{2,}/g, " ").trim();
126
122
  }
127
123
 
128
- function formatImageLogLabel({ relPath = "", fileName = "", path: pathText = "" } = {}) {
129
- const name = String(fileName || "").trim()
130
- || path.basename(String(relPath || pathText || "").trim())
131
- || "image";
132
- return `[image: ${name}]`;
124
+ function formatImageLogLabel(_attachment = {}, index = 0) {
125
+ return `[Image #${index + 1}]`;
133
126
  }
134
127
 
135
128
  function formatUserLogWithAttachments(userText = "", attachments = []) {
136
129
  const labels = (Array.isArray(attachments) ? attachments : [])
137
- .map((item) => formatImageLogLabel(item))
130
+ .map((item, index) => formatImageLogLabel(item, index))
138
131
  .filter(Boolean);
139
132
  const body = String(userText || "").trim();
140
133
  if (labels.length === 0) return body;
@@ -315,14 +308,18 @@ function handleImagePaste(text = "", {
315
308
  const paths = extractImagePathsFromPaste(raw);
316
309
  const attachments = [];
317
310
  const errors = [];
311
+ const importedPaths = [];
318
312
 
319
313
  for (const sourcePath of paths) {
320
314
  const ingested = ingestImageFile({ sourcePath, workspaceRoot, sessionId });
321
- if (ingested.ok) attachments.push(ingested);
315
+ if (ingested.ok) {
316
+ attachments.push(ingested);
317
+ importedPaths.push(sourcePath);
318
+ }
322
319
  else errors.push(ingested.error || "ingest failed");
323
320
  }
324
321
 
325
- let remaining = stripExtractedPathsFromText(raw, paths);
322
+ let remaining = stripExtractedPathsFromText(raw, importedPaths);
326
323
 
327
324
  // If paste had no usable text/paths, try clipboard PNG (Cmd+V of a screenshot).
328
325
  const trimmedRemaining = remaining.trim();
@@ -330,7 +327,7 @@ function handleImagePaste(text = "", {
330
327
  || /[\x00-\x08\x0e-\x1f]/.test(raw)
331
328
  || (Buffer.byteLength(raw, "utf8") > 200 && paths.length === 0 && !/\s/.test(raw.slice(0, 40)));
332
329
 
333
- if (tryClipboard && attachments.length === 0 && looksEmptyOrBinary) {
330
+ if (tryClipboard && paths.length === 0 && attachments.length === 0 && looksEmptyOrBinary) {
334
331
  const clip = tryIngestClipboardImage({
335
332
  workspaceRoot,
336
333
  sessionId,
@@ -20,6 +20,8 @@ const {
20
20
  } = require("./context/assembler");
21
21
  const { systemBlocksToAnthropicPayload } = require("./context/promptLayers");
22
22
  const { retireMessageImages } = require("./providers/visionBlocks");
23
+ const { resolveMaxToolCalls } = require("./toolBudget");
24
+ const { ToolLoopGuard } = require("./toolLoopGuard");
23
25
  const { parseStructuredSideEffects } = require("./context/stateCommit");
24
26
  const {
25
27
  emptyExecutionState,
@@ -110,10 +112,8 @@ const DEFAULT_XAI_BASE_URL = "https://api.x.ai/v1";
110
112
  const DEFAULT_GROK_BUILD_BASE_URL = DEFAULT_XAI_BASE_URL;
111
113
  const DEFAULT_GROK_BUILD_MODEL = "grok-4.6";
112
114
  const DEFAULT_KIMI_MODEL = "k3";
113
- // Claude Code SDK defaults to no turn limit; built-in agents cap at 30 (DreamTask)
114
- // to 200 (fork). We count individual tool calls (not turns), so 100 leaves headroom
115
- // for non-trivial tasks while still catching runaway loops. Override via env.
116
- const DEFAULT_MAX_NATIVE_TOOL_CALLS = 100;
115
+ // No tool-call cap unless explicitly configured by the caller or environment.
116
+ const DEFAULT_MAX_NATIVE_TOOL_CALLS = null;
117
117
  const DEFAULT_MAX_NATIVE_TOOL_ERRORS = 20;
118
118
  const MAX_EMPTY_TERMINAL_RETRIES = 2;
119
119
  const DEFAULT_NATIVE_TIMEOUT_MS = 43200000; // 12 hours
@@ -191,9 +191,9 @@ function normalizePositiveInt(value, fallback) {
191
191
  return Math.floor(parsed);
192
192
  }
193
193
 
194
- function resolveNativeToolBudget(env = process.env) {
194
+ function resolveNativeToolBudget(maxToolCalls, env = process.env) {
195
195
  return {
196
- maxToolCalls: normalizePositiveInt(env.UFOO_UCODE_MAX_TOOL_CALLS, DEFAULT_MAX_NATIVE_TOOL_CALLS),
196
+ maxToolCalls: resolveMaxToolCalls(maxToolCalls, env),
197
197
  maxToolErrors: normalizePositiveInt(env.UFOO_UCODE_MAX_TOOL_ERRORS, DEFAULT_MAX_NATIVE_TOOL_ERRORS),
198
198
  };
199
199
  }
@@ -301,7 +301,7 @@ function enforceNativeToolBudget({
301
301
  lastTool = "",
302
302
  lastError = "",
303
303
  } = {}) {
304
- if (toolCallsExecuted >= maxToolCalls) {
304
+ if (maxToolCalls != null && toolCallsExecuted >= maxToolCalls) {
305
305
  throw new Error(`tool call budget exceeded (${maxToolCalls})`);
306
306
  }
307
307
  if (toolErrors >= maxToolErrors) {
@@ -2130,6 +2130,7 @@ async function runNativeLoop({
2130
2130
  provider = "",
2131
2131
  accountId = "",
2132
2132
  timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
2133
+ maxToolCalls = undefined,
2133
2134
  onStreamDelta = null,
2134
2135
  onThinkingDelta = null,
2135
2136
  onPhase = null,
@@ -2207,7 +2208,8 @@ async function runNativeLoop({
2207
2208
  : emptyExecutionState();
2208
2209
  if (typeof executionState.planMode !== "boolean") executionState.planMode = false;
2209
2210
  ensurePendingUserPrompts(executionState);
2210
- const toolBudget = resolveNativeToolBudget();
2211
+ const toolBudget = resolveNativeToolBudget(maxToolCalls);
2212
+ const toolLoopGuard = new ToolLoopGuard();
2211
2213
  const usage = createUsageTotals();
2212
2214
  // Shadow Tool Call Ledger (R1). Observes declare/defer/resolve; does not
2213
2215
  // materialize Provider messages yet. STRICT via UFOO_UCODE_PROTOCOL_STRICT=1.
@@ -2227,6 +2229,7 @@ async function runNativeLoop({
2227
2229
  function injectPendingUserReminders() {
2228
2230
  const nudges = drainUserPrompts(executionState);
2229
2231
  if (nudges.length === 0) return "";
2232
+ toolLoopGuard.reset();
2230
2233
  const waiting = executionState.planGraph && executionState.planGraph.waitingFor
2231
2234
  ? executionState.planGraph.waitingFor
2232
2235
  : null;
@@ -2237,6 +2240,7 @@ async function runNativeLoop({
2237
2240
  function injectRuntimeMailboxEvents(targetMessages) {
2238
2241
  const drained = drainAgentMailboxForTurn(executionState);
2239
2242
  if (!drained.text) return false;
2243
+ toolLoopGuard.reset();
2240
2244
  targetMessages.push({ role: "user", content: drained.text });
2241
2245
  return true;
2242
2246
  }
@@ -2268,6 +2272,7 @@ async function runNativeLoop({
2268
2272
  }
2269
2273
  const drained = drainAgentMailboxForTurn(executionState);
2270
2274
  const userNudge = injectPendingUserReminders();
2275
+ if (drained.events && drained.events.length > 0) toolLoopGuard.reset();
2271
2276
  const isolated = buildIsolatedTaskFocusTurn(executionState, {
2272
2277
  mailboxEvents: drained.events || [],
2273
2278
  userNudge,
@@ -2344,6 +2349,28 @@ async function runNativeLoop({
2344
2349
  runProviderTurnGate(activeLedger);
2345
2350
  }
2346
2351
 
2352
+ // Check only after the preceding batch has been fully materialized. A
2353
+ // warning must never split tool calls from their results, and a stop must
2354
+ // return the completed transcript instead of losing it through an exception.
2355
+ const loopAction = toolLoopGuard.nextAction();
2356
+ if (loopAction && loopAction.kind === "stop") {
2357
+ return {
2358
+ error: loopAction.message,
2359
+ stopReason: "repeated_tool_calls",
2360
+ text: aggregated,
2361
+ streamed,
2362
+ toolCallsExecuted,
2363
+ messages,
2364
+ turnItems: currentTurnItems(),
2365
+ usage,
2366
+ executionState,
2367
+ protocolLedger: lastProtocolLedger,
2368
+ };
2369
+ }
2370
+ if (loopAction && loopAction.kind === "warn") {
2371
+ providerMessages.push({ role: "user", content: loopAction.message });
2372
+ }
2373
+
2347
2374
  const turnResult = await transport.runTurn({
2348
2375
  url: requestUrl,
2349
2376
  apiKey,
@@ -2382,6 +2409,7 @@ async function runNativeLoop({
2382
2409
  const toolCalls = transport.getToolCalls(turnResult);
2383
2410
 
2384
2411
  if (toolCalls.length === 0) {
2412
+ toolLoopGuard.reset();
2385
2413
  const text = String(turnResult.text || "").trim();
2386
2414
  if (!text && toolCallsExecuted > 0) {
2387
2415
  if (emptyTerminalRetries >= MAX_EMPTY_TERMINAL_RETRIES) {
@@ -2475,6 +2503,7 @@ async function runNativeLoop({
2475
2503
  };
2476
2504
  }
2477
2505
 
2506
+ toolLoopGuard.observe(pendingCalls);
2478
2507
  activeLedger = createToolCallLedger({ provider, sessionId });
2479
2508
  shadowDeclarePendingCalls(activeLedger, pendingCalls);
2480
2509
  lastProtocolLedger = snapshotLedger(activeLedger);
@@ -2709,6 +2738,7 @@ async function runNativeAgentTask({
2709
2738
  messages = [],
2710
2739
  sessionId = "",
2711
2740
  timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
2741
+ maxToolCalls = undefined,
2712
2742
  onStreamDelta = null,
2713
2743
  onThinkingDelta = null,
2714
2744
  onPhase = null,
@@ -2816,6 +2846,7 @@ async function runNativeAgentTask({
2816
2846
  provider: runtime.provider,
2817
2847
  accountId,
2818
2848
  timeoutMs,
2849
+ maxToolCalls,
2819
2850
  onStreamDelta: trackingStreamDelta,
2820
2851
  onThinkingDelta,
2821
2852
  onPhase,
@@ -2855,8 +2886,9 @@ async function runNativeAgentTask({
2855
2886
  });
2856
2887
 
2857
2888
  return {
2858
- ok: true,
2859
- error: "",
2889
+ ok: !runResult.error,
2890
+ error: runResult.error || "",
2891
+ stopReason: runResult.stopReason || "",
2860
2892
  output: outputText,
2861
2893
  messages: cloneMessageList(runResult.messages),
2862
2894
  turnItems: cloneMessageList(runResult.turnItems),
package/src/code/repl.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const readline = require("readline");
2
+ const { parseMaxToolCalls } = require("./toolBudget");
2
3
  const { runToolCall, TOOL_NAMES } = require("./dispatch");
3
4
  const {
4
5
  runUcodeTui,
@@ -289,6 +290,7 @@ async function runUcodeCoreAgent({
289
290
  systemPrompt = "",
290
291
  sessionId = "",
291
292
  timeoutMs = 0,
293
+ maxToolCalls = undefined,
292
294
  jsonOutput = false,
293
295
  forceTui = false,
294
296
  disableTui = false,
@@ -346,6 +348,7 @@ async function runUcodeCoreAgent({
346
348
  nlMessages: [],
347
349
  sessionId: resolveSessionId(String(sessionId || "").trim()),
348
350
  timeoutMs: resolveNlTaskTimeoutMs(Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : NaN),
351
+ maxToolCalls,
349
352
  jsonOutput,
350
353
  };
351
354
  // Named levels sync into env; leave an explicit numeric budget override alone.
@@ -514,6 +517,7 @@ async function runUcodeCoreAgent({
514
517
  nlMessages: Array.isArray(state.nlMessages) ? state.nlMessages.slice() : [],
515
518
  sessionId: "",
516
519
  timeoutMs: state.timeoutMs,
520
+ maxToolCalls: state.maxToolCalls,
517
521
  jsonOutput: false,
518
522
  };
519
523
  const run = runNaturalLanguageTask(task, bgState)
@@ -824,6 +828,7 @@ function parseAgentArgs(argv = []) {
824
828
  systemPrompt: "",
825
829
  sessionId: "",
826
830
  timeoutMs: 0,
831
+ maxToolCalls: undefined,
827
832
  jsonOutput: false,
828
833
  forceTui: false,
829
834
  disableTui: false,
@@ -861,6 +866,12 @@ function parseAgentArgs(argv = []) {
861
866
  i += 1;
862
867
  continue;
863
868
  }
869
+ if (item === "--max-tool-calls" || item.startsWith("--max-tool-calls=")) {
870
+ const value = item === "--max-tool-calls" ? args[++i] : item.slice("--max-tool-calls=".length);
871
+ if (value === undefined) throw new Error("--max-tool-calls requires a positive integer or none");
872
+ out.maxToolCalls = parseMaxToolCalls(value);
873
+ continue;
874
+ }
864
875
  if (item === "--timeout-ms") {
865
876
  const parsed = Number(args[i + 1]);
866
877
  if (Number.isFinite(parsed)) out.timeoutMs = Math.max(1000, Math.floor(parsed));
@@ -221,6 +221,7 @@ async function runDecomposedTask({
221
221
  messages: stepMessages,
222
222
  sessionId,
223
223
  timeoutMs: step.timeoutMs,
224
+ maxToolCalls: state ? state.maxToolCalls : undefined,
224
225
  onToolEvent,
225
226
  signal,
226
227
  onArtifactPersisted: state
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+
3
+ function parseMaxToolCalls(value) {
4
+ if (value == null || String(value).trim().toLowerCase() === "none") return null;
5
+ const text = String(value).trim();
6
+ const count = Number(text);
7
+ if (!/^\d+$/.test(text) || !Number.isSafeInteger(count) || count <= 0) {
8
+ throw new Error("max tool calls must be a positive integer or none");
9
+ }
10
+ return count;
11
+ }
12
+
13
+ function resolveMaxToolCalls(value, env = process.env) {
14
+ if (value !== undefined) return parseMaxToolCalls(value);
15
+ const configured = env.UFOO_UCODE_MAX_TOOL_CALLS;
16
+ return configured == null || String(configured).trim() === ""
17
+ ? null
18
+ : parseMaxToolCalls(configured);
19
+ }
20
+
21
+ module.exports = { parseMaxToolCalls, resolveMaxToolCalls };
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+
3
+ const { createHash } = require("crypto");
4
+ const { stableStringify } = require("./context/stableJson");
5
+
6
+ const TIGHT_TOOLS = new Set(["read", "read_image", "artifact_read", "plan_graph"]);
7
+
8
+ // One observation is a model step, including its complete parallel tool batch.
9
+ // Ignore call IDs, JSON key order, and parallel ordering when comparing steps.
10
+ class ToolLoopGuard {
11
+ constructor() {
12
+ this.reset();
13
+ }
14
+
15
+ reset() {
16
+ this.signature = "";
17
+ this.count = 0;
18
+ this.warned = false;
19
+ this.names = [];
20
+ this.tight = false;
21
+ }
22
+
23
+ observe(calls) {
24
+ if (!calls.length) return this.reset();
25
+ const parts = calls.map((call) => stableStringify({ name: call.name, args: call.args }));
26
+ const signature = createHash("sha256").update(JSON.stringify(parts.sort())).digest("hex");
27
+ if (signature !== this.signature) this.reset();
28
+ this.signature = signature;
29
+ this.count += 1;
30
+ this.names = [...new Set(calls.map((call) => call.name))].sort();
31
+ this.tight = calls.every((call) => TIGHT_TOOLS.has(call.name));
32
+ }
33
+
34
+ nextAction() {
35
+ const warnAt = this.tight ? 4 : 8;
36
+ const stopAt = this.tight ? 8 : 12;
37
+ const tools = this.names.join(", ");
38
+ if (this.count >= stopAt) {
39
+ return {
40
+ kind: "stop",
41
+ message: `Stopped repeated tool calls: ${tools} used identical arguments for ${this.count} consecutive model steps after a warning. Change the approach or provide new information to continue.`,
42
+ };
43
+ }
44
+ if (this.count >= warnAt && !this.warned) {
45
+ this.warned = true;
46
+ return {
47
+ kind: "warn",
48
+ message: `You have repeated the same tool batch (${tools}) with identical arguments for ${this.count} consecutive model steps. Stop repeating it and use a different approach. If waiting for a task, use its supported waiting mechanism instead of repeatedly checking. If blocked, explain the blocker to the user. This run will stop at ${stopAt} consecutive identical steps.`,
49
+ };
50
+ }
51
+ return null;
52
+ }
53
+ }
54
+
55
+ module.exports = { ToolLoopGuard };
@@ -395,7 +395,7 @@ function redactUserMessageForLog(text = "") {
395
395
  const paths = [...block.matchAll(/^\s*-\s*(.+)$/gm)].map((m) => String(m[1] || "").trim());
396
396
  if (paths.length === 0) return "[image]";
397
397
  return paths
398
- .map((p) => `[image: ${require("path").basename(p)}]`)
398
+ .map((_, index) => `[Image #${index + 1}]`)
399
399
  .join(" ");
400
400
  },
401
401
  );
@@ -481,7 +481,7 @@ async function runUcodeRust(props = {}) {
481
481
  if (Array.isArray(outcome.errors) && outcome.errors.length > 0 && pendingAttachments.length === 0) {
482
482
  appendLog(`Image paste: ${outcome.errors[0]}`, "system");
483
483
  }
484
- const labels = pendingAttachments.map((item) => formatImageLogLabel(item) || "image");
484
+ const labels = pendingAttachments.map((item, index) => formatImageLogLabel(item, index));
485
485
  publish("attachments.set", {
486
486
  count: pendingAttachments.length,
487
487
  labels,
@@ -1007,6 +1007,7 @@ async function runUcodeRust(props = {}) {
1007
1007
  : [],
1008
1008
  sessionId: "",
1009
1009
  timeoutMs: props.state && props.state.timeoutMs,
1010
+ maxToolCalls: props.state ? props.state.maxToolCalls : undefined,
1010
1011
  jsonOutput: false,
1011
1012
  };
1012
1013
  Promise.resolve()