u-foo 4.0.3 → 4.0.10

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 (160) hide show
  1. package/README.md +239 -19
  2. package/README.zh-CN.md +3 -3
  3. package/bin/ucode.js +10 -2
  4. package/bin/ufoo.js +3 -0
  5. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  6. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  7. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  8. package/dist/tui/linux-x64/ufoo-tui +0 -0
  9. package/{OBSERVABILITY.md → docs/OBSERVABILITY.md} +3 -3
  10. package/docs/README.md +27 -0
  11. package/extensions/ufoo-browser/LICENSE +152 -0
  12. package/extensions/ufoo-browser/NOTICE +10 -0
  13. package/extensions/ufoo-browser/README.md +30 -0
  14. package/extensions/ufoo-browser/background.js +409 -0
  15. package/extensions/ufoo-browser/icons/icon-128.png +0 -0
  16. package/extensions/ufoo-browser/icons/icon-16.png +0 -0
  17. package/extensions/ufoo-browser/icons/icon-256.png +0 -0
  18. package/extensions/ufoo-browser/icons/icon-32.png +0 -0
  19. package/extensions/ufoo-browser/icons/icon-48.png +0 -0
  20. package/extensions/ufoo-browser/icons/logo.png +0 -0
  21. package/extensions/ufoo-browser/icons/toolbar-16.png +0 -0
  22. package/extensions/ufoo-browser/icons/toolbar-32.png +0 -0
  23. package/extensions/ufoo-browser/icons/toolbar-logo.png +0 -0
  24. package/extensions/ufoo-browser/manifest.json +30 -0
  25. package/extensions/ufoo-browser/popup.css +71 -0
  26. package/extensions/ufoo-browser/popup.html +44 -0
  27. package/extensions/ufoo-browser/popup.js +153 -0
  28. package/package.json +7 -5
  29. package/scripts/postinstall.js +6 -0
  30. package/src/agents/capabilities/browser/index.js +49 -0
  31. package/src/agents/capabilities/coding/backgroundHooks.js +94 -0
  32. package/src/agents/capabilities/coding/index.js +30 -1
  33. package/src/agents/capabilities/index.js +5 -2
  34. package/src/agents/capabilities/planning/index.js +44 -5
  35. package/src/agents/capabilities/turnRecall/index.js +341 -0
  36. package/src/agents/controller/controllerToolExecutor.js +2 -2
  37. package/src/agents/internal/internalRunner.js +30 -8
  38. package/src/agents/internal/taskControl.js +107 -0
  39. package/src/agents/profiles/coding.js +1 -1
  40. package/src/agents/profiles/main.js +1 -1
  41. package/src/agents/prompts/mainAgent.js +1 -0
  42. package/src/agents/prompts/native/toolDescriptions/bash.js +7 -1
  43. package/src/agents/providers/claudeSessionFiles.js +1 -1
  44. package/src/agents/providers/codexThreadProvider.js +6 -1
  45. package/src/agents/providers/credentials/agy.js +171 -0
  46. package/src/agents/providers/directAuthStatus.js +20 -2
  47. package/src/agents/providers/modelsCatalog.js +26 -5
  48. package/src/agents/providers/nativeTransport.js +145 -73
  49. package/src/agents/providers/providerId.js +17 -0
  50. package/src/agents/providers/runtimeConfig.js +67 -20
  51. package/src/agents/providers/transports/antigravityTransport.js +242 -0
  52. package/src/agents/providers/transports/index.js +1 -0
  53. package/src/agents/providers/transports/openaiChatTransport.js +3 -2
  54. package/src/agents/providers/transports/openaiResponsesTransport.js +2 -1
  55. package/src/agents/providers/transports/responsesProtocol.js +119 -18
  56. package/src/agents/providers/transports/transportContract.js +1 -0
  57. package/src/agents/providers/upstreamRuntime.js +3 -1
  58. package/src/agents/runtime/context/contextBudget.js +1 -19
  59. package/src/agents/runtime/context/contextWindow.js +5 -0
  60. package/src/agents/runtime/context/replayHistory.js +16 -10
  61. package/src/agents/runtime/context/runtimeStore.js +0 -1
  62. package/src/agents/runtime/context/sessionJournal.js +1 -1
  63. package/src/agents/runtime/context/slidingWindowManager.js +792 -0
  64. package/src/agents/runtime/context/topicSelector.js +338 -0
  65. package/src/agents/runtime/context/turnAnalyzer.js +767 -0
  66. package/src/agents/runtime/context/turnIndexStore.js +515 -0
  67. package/src/agents/runtime/core/agentLoop.js +140 -35
  68. package/src/agents/runtime/core/executionBudget.js +2 -1
  69. package/src/agents/runtime/core/toolErrorGuard.js +39 -0
  70. package/src/agents/runtime/createAgentRuntime.js +80 -7
  71. package/src/agents/runtime/index.js +5 -0
  72. package/src/agents/runtime/protocol/materialize.js +1 -1
  73. package/src/agents/runtime/tasks/hooks.js +137 -0
  74. package/src/app/chat/ChatController.js +8 -4
  75. package/src/app/chat/daemonMessageRouter.js +3 -1
  76. package/src/app/chat/inputSubmitHandler.js +2 -2
  77. package/src/app/chat/transport.js +1 -1
  78. package/src/app/cli/browserCommands.js +340 -0
  79. package/src/app/cli/busCoreCommands.js +63 -3
  80. package/src/app/cli/features/doctor.js +21 -0
  81. package/src/app/cli/metricsCommands.js +1 -1
  82. package/src/app/cli/run.js +81 -1
  83. package/src/app/cli/setupCommands.js +200 -0
  84. package/src/code/UcodeController.js +31 -1
  85. package/src/code/agent.js +76 -25
  86. package/src/code/busConsumer.js +13 -12
  87. package/src/code/commands.js +0 -1
  88. package/src/code/context/assembler.js +11 -88
  89. package/src/code/context/planGraphService.js +121 -6
  90. package/src/code/context/planProjection.js +10 -2
  91. package/src/code/context/reducers.js +172 -4
  92. package/src/code/context/stateCommit.js +0 -32
  93. package/src/code/context/transcript.js +7 -4
  94. package/src/code/internalThread.js +9 -1
  95. package/src/code/launcher/ucode.js +4 -2
  96. package/src/code/modelCommand.js +6 -5
  97. package/src/code/nativeRunner.js +232 -62
  98. package/src/code/repl.js +27 -1
  99. package/src/code/runtime/agentWakeup.js +20 -3
  100. package/src/code/runtime/backgroundWakeHost.js +45 -0
  101. package/src/code/runtime/taskFocusContext.js +7 -0
  102. package/src/code/runtime/taskLoop.js +24 -1
  103. package/src/code/sessionStore.js +14 -10
  104. package/src/code/taskDecomposer.js +16 -7
  105. package/src/code/tools/backgroundProcess.js +23 -0
  106. package/src/code/tools/bash.js +764 -12
  107. package/src/code/tools/executor.js +13 -4
  108. package/src/code/tools/planGraph.js +1 -0
  109. package/src/code/tools/specs.js +62 -4
  110. package/src/code/tools/taskRun.js +38 -0
  111. package/src/config.js +92 -6
  112. package/src/coordination/bus/index.js +2 -2
  113. package/src/coordination/bus/message.js +10 -1
  114. package/src/coordination/bus/nickname.js +3 -1
  115. package/src/coordination/bus/subscriber.js +25 -10
  116. package/src/coordination/bus/utils.js +4 -0
  117. package/src/coordination/bus/wakeEndpoint.js +198 -0
  118. package/src/coordination/history/agentPerformance.js +18 -18
  119. package/src/coordination/history/agentTrace.js +7 -3
  120. package/src/coordination/state/paths.js +4 -0
  121. package/src/coordination/state/workspaceAccess.js +3 -1
  122. package/src/orchestration/groups/modelConfig.js +66 -0
  123. package/src/orchestration/groups/validateTemplate.js +2 -0
  124. package/src/runtime/browser/broker.js +1027 -0
  125. package/src/runtime/browser/brokerClient.js +108 -0
  126. package/src/runtime/browser/componentInstaller.js +275 -0
  127. package/src/runtime/browser/installState.js +329 -0
  128. package/src/runtime/browser/manifest.js +145 -0
  129. package/src/runtime/browser/native-host-runner.js +198 -0
  130. package/src/runtime/browser/nativeHost.js +213 -0
  131. package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
  132. package/src/runtime/browser/paths.js +134 -0
  133. package/src/runtime/browser/playwrightSession.js +614 -0
  134. package/src/runtime/daemon/agentHost.js +175 -28
  135. package/src/runtime/daemon/busBridge.js +2 -1
  136. package/src/runtime/daemon/deliveryScheduler.js +70 -2
  137. package/src/runtime/daemon/globalDaemon.js +20 -0
  138. package/src/runtime/daemon/groupOrchestrator.js +20 -1
  139. package/src/runtime/daemon/index.js +6 -4
  140. package/src/runtime/daemon/ops.js +14 -8
  141. package/src/tools/handlers/listAgents.js +1 -1
  142. package/src/tools/handlers/readBusSummary.js +1 -1
  143. package/src/tools/handlers/routeAgent.js +122 -5
  144. package/src/tools/schemaFixtures.js +1 -1
  145. package/src/ui/agentSurface.js +60 -6
  146. package/src/ui/format/index.js +34 -2
  147. package/src/ui/format/markdownRenderer.js +4 -2
  148. package/src/ui/rustChatHost.js +22 -7
  149. package/src/ui/rustMultiSession.js +14 -2
  150. package/src/ui/rustUcodeHost.js +249 -80
  151. package/src/ui/ucodeAgentSession.js +88 -0
  152. package/templates/groups/build-lane.json +57 -3
  153. package/templates/groups/build-ultra.json +114 -6
  154. package/templates/groups/design-system.json +57 -3
  155. package/templates/groups/product-discovery.json +57 -3
  156. package/templates/groups/ui-plan-review.json +57 -3
  157. package/templates/groups/ui-polish.json +57 -3
  158. package/templates/groups/verify-ship.json +57 -3
  159. package/src/agents/runtime/context/checkpointStore.js +0 -38
  160. package/src/agents/runtime/context/compaction.js +0 -151
@@ -1,7 +1,6 @@
1
1
  const fs = require("fs");
2
2
  const path = require("path");
3
3
  const { execSync } = require("child_process");
4
- const { createBusProgressReporter } = require("./taskDecomposer");
5
4
  const { DeliveryQueue } = require("../coordination/bus/deliveryQueue");
6
5
 
7
6
  function shellQuote(value = "") {
@@ -307,6 +306,14 @@ function parseBusCheckOutput(raw = "") {
307
306
  .filter(Boolean);
308
307
  }
309
308
 
309
+ // An intentionally silent model turn must stay silent on the bus. Terminal
310
+ // display fallbacks ("Done") and automatic progress ACKs otherwise wake peers.
311
+ function formatBusReply(result, formatNl) {
312
+ if (result?.ok && !result.cancelled && !String(result.summary || "").trim()
313
+ && !(result.artifacts || []).length) return "";
314
+ return String(formatNl(result, false) || "").replace(/\s+/g, " ").trim();
315
+ }
316
+
310
317
  async function runUbusCommand(state = {}, options = {}) {
311
318
  const runtimeWorkspace = resolveUfooProjectRoot(String(
312
319
  options.workspaceRoot
@@ -375,16 +382,10 @@ async function runUbusCommand(state = {}, options = {}) {
375
382
  });
376
383
  }
377
384
 
378
- // Create progress reporter for this message
379
- const progressReporter = createBusProgressReporter(shell, message.publisher);
380
-
381
385
  try {
382
- // Send initial acknowledgment
383
- shell(`ufoo bus send ${shellQuote(message.publisher)} ${shellQuote("🚀 Starting task...")}`);
384
-
385
386
  // eslint-disable-next-line no-await-in-loop
386
387
  nlResult = await runNl(message.task, state, {
387
- onProgress: progressReporter,
388
+ onProgress: options.onProgress,
388
389
  signal: options.signal,
389
390
  });
390
391
  } catch (err) {
@@ -395,8 +396,8 @@ async function runUbusCommand(state = {}, options = {}) {
395
396
  shell(`ufoo bus send ${shellQuote(message.publisher)} ${shellQuote(`❌ Error: ${errorMessage}`)}`);
396
397
  break;
397
398
  }
398
- const reply = String(formatNl(nlResult, false) || "").replace(/\s+/g, " ").trim() || "Done.";
399
- const sendRes = shell(`ufoo bus send ${shellQuote(message.publisher)} ${shellQuote(reply.slice(0, 2000))}`);
399
+ const reply = formatBusReply(nlResult, formatNl);
400
+ const sendRes = reply ? shell(`ufoo bus send ${shellQuote(message.publisher)} ${shellQuote(reply.slice(0, 2000))}`) : { ok: true };
400
401
  if (!sendRes.ok) {
401
402
  sendErrors.push(`reply to ${message.publisher} failed: ${sendRes.error || "send failed"}`);
402
403
  queue.restoreClaim(claim);
@@ -446,8 +447,8 @@ async function runUbusCommand(state = {}, options = {}) {
446
447
  const nlResult = await runNl(item.task, state, {
447
448
  signal: options.signal,
448
449
  });
449
- const reply = String(formatNl(nlResult, false) || "").replace(/\s+/g, " ").trim() || "Done.";
450
- const sendRes = shell(`ufoo bus send ${shellQuote(item.publisher)} ${shellQuote(reply.slice(0, 2000))}`);
450
+ const reply = formatBusReply(nlResult, formatNl);
451
+ const sendRes = reply ? shell(`ufoo bus send ${shellQuote(item.publisher)} ${shellQuote(reply.slice(0, 2000))}`) : { ok: true };
451
452
  if (!sendRes.ok) {
452
453
  sendErrors.push(`reply to ${item.publisher} failed: ${sendRes.error || "send failed"}`);
453
454
  continue;
@@ -34,7 +34,6 @@ const UCODE_COMMAND_TREE = {
34
34
  "/model": {
35
35
  desc: "Show or switch model, then pick thinking intensity",
36
36
  hasArguments: true,
37
- optionalArguments: true,
38
37
  },
39
38
  "/plan": {
40
39
  desc: "Show plan progress or set plan mode",
@@ -19,9 +19,6 @@ const {
19
19
  renderStateEpoch,
20
20
  applyStateCommit,
21
21
  applyValidatedStateCommit,
22
- buildDeterministicToolCommit,
23
- resolveCommitInterval,
24
- shouldCommitAfterToolCall,
25
22
  ensureStateEpoch,
26
23
  } = require("./stateCommit");
27
24
  const {
@@ -34,7 +31,7 @@ const { renderExecutionSegmentContext } = require("./executionSegment");
34
31
  const { renderPlanModeContext } = require("./planMode");
35
32
  const { drainAgentMailboxForTurn } = require("../runtime/agentWakeup");
36
33
  const { stripVisionBase64, degradeVisionContent } = require("../providers/visionBlocks");
37
- const { DEFAULT_CONTEXT_POLICY } = require("../../agents/runtime/context/compaction");
34
+ const { DEFAULT_V2_POLICY } = require("../../agents/runtime/context/slidingWindowManager");
38
35
 
39
36
  const DEFAULT_TRANSCRIPT_WINDOW = 12;
40
37
  const DEFAULT_RECENT_TOOL_EVENTS = 4;
@@ -45,10 +42,9 @@ function resolveTranscriptWindow(env = process.env) {
45
42
  return DEFAULT_TRANSCRIPT_WINDOW;
46
43
  }
47
44
 
48
- function defaultContextPolicy(env = process.env) {
45
+ function defaultContextPolicy() {
49
46
  return {
50
- ...DEFAULT_CONTEXT_POLICY,
51
- commitInterval: resolveCommitInterval(env),
47
+ ...DEFAULT_V2_POLICY,
52
48
  };
53
49
  }
54
50
 
@@ -64,12 +60,15 @@ function eventToModelMessage(event = {}, options = {}) {
64
60
  if (!event || typeof event !== "object") return null;
65
61
 
66
62
  if (preferArtifact && event.artifactId) {
63
+ const hasFullContent = event.content !== undefined && event.content !== null && event.content !== "";
67
64
  return {
68
65
  role: event.role || "tool",
69
- content: JSON.stringify({
70
- artifactId: event.artifactId,
71
- preview: event.preview || "",
72
- }),
66
+ content: hasFullContent
67
+ ? event.content
68
+ : JSON.stringify({
69
+ artifactId: event.artifactId,
70
+ preview: event.preview || "",
71
+ }),
73
72
  tool_call_id: event.toolCallId,
74
73
  };
75
74
  }
@@ -85,70 +84,6 @@ function eventToModelMessage(event = {}, options = {}) {
85
84
  return message;
86
85
  }
87
86
 
88
- function buildRollingSummary(transcriptEvents = [], existingSummary = "", session = null) {
89
- const events = Array.isArray(transcriptEvents) ? transcriptEvents : [];
90
- const window = resolveTranscriptWindow();
91
- const parts = [];
92
-
93
- const contract = session && session.taskContract && typeof session.taskContract === "object"
94
- ? session.taskContract
95
- : null;
96
- if (contract && contract.objective) {
97
- parts.push(`Objective: ${String(contract.objective).slice(0, 200)}`);
98
- }
99
-
100
- const epoch = session && session.stateEpoch && session.stateEpoch.snapshot
101
- ? session.stateEpoch.snapshot
102
- : null;
103
- if (epoch) {
104
- if (epoch.currentObjective) {
105
- parts.push(`Current objective: ${String(epoch.currentObjective).slice(0, 160)}`);
106
- }
107
- if (Array.isArray(epoch.facts) && epoch.facts.length > 0) {
108
- parts.push(`Facts: ${epoch.facts.slice(-4).map((f) => String(f).slice(0, 120)).join(" | ")}`);
109
- }
110
- if (Array.isArray(epoch.decisions) && epoch.decisions.length > 0) {
111
- parts.push(`Decisions: ${epoch.decisions.slice(-3).map((d) => String(d).slice(0, 120)).join(" | ")}`);
112
- }
113
- }
114
-
115
- const modified = session
116
- && session.executionState
117
- && Array.isArray(session.executionState.modifiedFiles)
118
- ? session.executionState.modifiedFiles.slice(-8)
119
- : [];
120
- if (modified.length > 0) {
121
- parts.push(`Modified files: ${modified.join(", ")}`);
122
- }
123
-
124
- if (events.length > window) {
125
- const omitted = events.length - window;
126
- parts.push(`Earlier transcript (${omitted} events omitted from model input).`);
127
- const userGoals = events
128
- .filter((e) => e.role === "user")
129
- .map((e) => {
130
- const text = typeof e.content === "string" ? e.content : "";
131
- return text.split(/\r?\n/)[0].trim();
132
- })
133
- .filter(Boolean)
134
- .slice(-3);
135
- const toolErrors = events
136
- .filter((e) => e.preview && /error|failed/i.test(e.preview))
137
- .slice(-2)
138
- .map((e) => String(e.preview).slice(0, 160));
139
- if (userGoals.length > 0) parts.push(`Recent goals: ${userGoals.join(" | ")}`);
140
- if (toolErrors.length > 0) parts.push(`Recent errors: ${toolErrors.join(" | ")}`);
141
- }
142
-
143
- const prior = String(existingSummary || "").trim();
144
- // Keep a short prior digest only when it adds distinct content.
145
- if (prior && !parts.some((part) => prior.includes(part.slice(0, 40)))) {
146
- parts.unshift(prior.split(/\n/).slice(0, 3).join("\n").slice(0, 400));
147
- }
148
-
149
- return parts.join("\n").slice(0, 1800);
150
- }
151
-
152
87
  function selectRecentToolArtifactIds(events = [], limit = DEFAULT_RECENT_TOOL_EVENTS) {
153
88
  const list = Array.isArray(events) ? events : [];
154
89
  const ids = [];
@@ -473,10 +408,9 @@ function persistToolResultToContext({
473
408
  };
474
409
  }
475
410
 
476
- function recordToolCallInSession(session = {}, persisted = {}, workspaceRoot = process.cwd()) {
411
+ function recordToolCallInSession(session = {}, persisted = {}) {
477
412
  if (!session || typeof session !== "object") return;
478
413
  ensureStateEpoch(session);
479
- session.toolCallsSinceCommit = (Number(session.toolCallsSinceCommit) || 0) + 1;
480
414
  if (!Array.isArray(session.workingSet)) session.workingSet = [];
481
415
  if (!session.executionState || typeof session.executionState !== "object") {
482
416
  session.executionState = require("./executionSegment").emptyExecutionState();
@@ -538,16 +472,6 @@ function recordToolCallInSession(session = {}, persisted = {}, workspaceRoot = p
538
472
  retries[toolKey] = (Number(retries[toolKey]) || 0) + 1;
539
473
  session.executionState.retries = retries;
540
474
  }
541
-
542
- const interval = resolveCommitInterval();
543
- if (shouldCommitAfterToolCall(session, interval)) {
544
- const commit = buildDeterministicToolCommit(persisted);
545
- if (commit) {
546
- applyValidatedStateCommit(session, commit, workspaceRoot);
547
- } else {
548
- session.toolCallsSinceCommit = 0;
549
- }
550
- }
551
475
  }
552
476
 
553
477
  function applyContextSideEffects(session = {}, sideEffects = {}, workspaceRoot = process.cwd()) {
@@ -601,7 +525,6 @@ module.exports = {
601
525
  DEFAULT_TRANSCRIPT_WINDOW,
602
526
  DEFAULT_RECENT_TOOL_EVENTS,
603
527
  defaultContextPolicy,
604
- buildRollingSummary,
605
528
  buildRecentMessages,
606
529
  buildModelMessagesFromTranscript,
607
530
  selectRecentToolArtifactIds,
@@ -200,6 +200,44 @@ function rejected(errors = [], extras = {}) {
200
200
  };
201
201
  }
202
202
 
203
+ function validateCommandNodes(command, validateToolArgs = false) {
204
+ const errors = [];
205
+ const specs = validateToolArgs ? new Map(require("../tools/specs").buildCoreToolSpecs()
206
+ .map(({ function: spec }) => [spec.name, spec.parameters])) : null;
207
+ const visit = (node, field) => {
208
+ if (!node || typeof node !== "object" || Array.isArray(node)) return;
209
+ if (node.type === "tool" || node.tool) {
210
+ if (Object.hasOwn(node, "arguments")) errors.push({ code: "INVALID_NODE_ARGUMENTS", field: `${field}.arguments`, nodeId: node.id || "",
211
+ message: `${field}.arguments is unsupported; use ${field}.args for tool parameters` });
212
+ if (node.args != null && (typeof node.args !== "object" || Array.isArray(node.args))) errors.push({ code: "INVALID_NODE_ARGUMENTS", field: `${field}.args`, nodeId: node.id || "", message: `${field}.args must be an object` });
213
+ if (!Object.hasOwn(node, "arguments")) {
214
+ const requiredKeys = [...(specs?.get(node.tool)?.required || [])];
215
+ if (specs?.has("bash") && node.tool === "bash") {
216
+ const bashAction = String((node.args && node.args.action) || "run").trim().toLowerCase() || "run";
217
+ if (bashAction === "run") requiredKeys.push("command");
218
+ else if (["logs", "status", "stop"].includes(bashAction)) requiredKeys.push("backgroundId");
219
+ }
220
+ for (const key of requiredKeys) {
221
+ if (!Object.hasOwn(node.args || {}, key)) errors.push({ code: "MISSING_TOOL_ARGUMENT", field: `${field}.args.${key}`, nodeId: node.id || "",
222
+ message: `${field}.args.${key} is required for ${node.tool}; correct the node and resubmit the command` });
223
+ }
224
+ }
225
+ }
226
+ for (const key of ["nodes", "children", "steps"]) if (Array.isArray(node[key])) node[key].forEach((child, index) => visit(child, `${field}.${key}[${index}]`));
227
+ for (const key of ["node", "with", "subgraph"]) if (node[key]) visit(node[key], `${field}.${key}`);
228
+ };
229
+ if (command.operation === "create") visit(command.graph, "graph");
230
+ if (command.operation === "patch") (command.operations || []).forEach((op, index) => visit(op, `operations[${index}]`));
231
+ return errors;
232
+ }
233
+
234
+ function planRecovery(nodes = []) {
235
+ const failures = nodes.filter(node => node.status === "failed" || node.status === "blocked")
236
+ .map(node => ({ nodeId: node.id, tool: node.tool || "", error: String(node.error || node.result?.error || node.result?.summary || "blocked").slice(0, 1000) }));
237
+ return failures.length ? { needed: true, failures,
238
+ hint: "Inspect is read-only and cannot retry failed nodes. Correct the plan using patch, or use control.skip_node/control.cancel_subtree for obsolete nodes. If recovery requires user input, explain the concrete blocker." } : null;
239
+ }
240
+
203
241
  function accepted(payload = {}) {
204
242
  return {
205
243
  ok: true,
@@ -383,6 +421,7 @@ function buildAdvanceSummary(result = {}, beforeStatuses = new Map()) {
383
421
  type: node.type,
384
422
  status: node.status,
385
423
  summary: (node.result && node.result.summary) || node.error || node.status,
424
+ ...(node.error || node.result?.error ? { error: String(node.error || node.result.error).slice(0, 1000) } : {}),
386
425
  };
387
426
  if (node.status === "succeeded") executedNodes.push(entry);
388
427
  if (node.status === "failed") failedNodes.push(entry);
@@ -482,6 +521,7 @@ function projectPlanView(planGraph = {}) {
482
521
  execution: node.execution || "",
483
522
  generated: Boolean(node.generated),
484
523
  summary: (node.result && node.result.summary) || "",
524
+ ...(node.error || node.result?.error ? { error: String(node.error || node.result.error).slice(0, 1000) } : {}),
485
525
  children: byParent.get(node.id) || [],
486
526
  }));
487
527
  }
@@ -514,8 +554,10 @@ function inspectPlanGraph(planGraph = {}) {
514
554
  parentTaskId: node.parentTaskId || "",
515
555
  execution: node.execution || "",
516
556
  generated: Boolean(node.generated),
557
+ ...(node.error || node.result?.error ? { error: String(node.error || node.result.error).slice(0, 1000) } : {}),
517
558
  })),
518
559
  planView: projectPlanView(planGraph),
560
+ recovery: planRecovery(nodes),
519
561
  validationWarnings: [],
520
562
  });
521
563
  }
@@ -591,10 +633,15 @@ function runPlanGraphCommand(commandInput = {}, options = {}) {
591
633
  const payload = rejected([{ code: "MISSING_OPERATION", message: "operation is required" }]);
592
634
  return { ...payload, executionState, modelPayload: payload };
593
635
  }
636
+ const nodeErrors = validateCommandNodes(command, options.validateToolArgs === true);
637
+ if (nodeErrors.length) {
638
+ const payload = rejected(nodeErrors);
639
+ return { ...payload, executionState, modelPayload: payload };
640
+ }
594
641
 
595
- // create/control always target the primary agent graph; patch/inspect may
596
- // select a TaskLoop child via command.graphId.
597
- const selected = (operation === "patch" || operation === "inspect")
642
+ // create/cancel_graph/clear target the primary agent graph; patch/inspect/control
643
+ // may select a TaskLoop child via command.graphId.
644
+ const selected = (operation === "patch" || operation === "inspect" || operation === "control")
598
645
  ? selectGraphForCommand(executionState, command)
599
646
  : {
600
647
  ok: true,
@@ -613,6 +660,7 @@ function runPlanGraphCommand(commandInput = {}, options = {}) {
613
660
 
614
661
  const primaryGraphId = selected.primaryGraphId
615
662
  || String(executionState.planGraph && executionState.planGraph.graphId || "");
663
+ const priorMode = executionState.mode || "single_action";
616
664
  // Work on the selected graph for this command; restore primary afterward if child.
617
665
  if (!selected.isPrimary) {
618
666
  executionState.planGraph = selected.graph;
@@ -623,13 +671,42 @@ function runPlanGraphCommand(commandInput = {}, options = {}) {
623
671
  if (executionState.planGraph && executionState.planGraph.graphId) {
624
672
  executionState.graphs[executionState.planGraph.graphId] = executionState.planGraph;
625
673
  }
626
- if (!selected.isPrimary && primaryGraphId && executionState.graphs[primaryGraphId]) {
627
- executionState.planGraph = executionState.graphs[primaryGraphId];
674
+ if (!selected.isPrimary) {
675
+ if (primaryGraphId && executionState.graphs[primaryGraphId]) {
676
+ executionState.planGraph = executionState.graphs[primaryGraphId];
677
+ } else {
678
+ executionState.planGraph = emptyPlanGraphState();
679
+ executionState.mode = priorMode === "plan_graph" && primaryGraphId ? "plan_graph" : "single_action";
680
+ }
628
681
  } else if (executionState.planGraph && executionState.planGraph.graphId) {
629
682
  executionState.graphs[executionState.planGraph.graphId] = executionState.planGraph;
630
683
  }
631
684
  }
632
685
 
686
+ function attachChildTaskLoopHint(payload = null, resumed = null, targetGraph = null) {
687
+ if (
688
+ selected.isPrimary
689
+ || !payload
690
+ || payload.status !== "accepted"
691
+ || !resumed
692
+ || resumed.yieldReason !== "awaiting_complete_task"
693
+ || !targetGraph
694
+ || !targetGraph.owner
695
+ || !targetGraph.owner.taskRunId
696
+ ) {
697
+ return;
698
+ }
699
+ const ownerRunId = String(targetGraph.owner.taskRunId);
700
+ const parentBound = Boolean(targetGraph.parentNodeId);
701
+ const nextAction = parentBound
702
+ ? `All child nodes finished for taskRunId="${ownerRunId}". Call plan_graph operation="control" with actions=[{"op":"complete_task","taskRunId":"${ownerRunId}","result":{"summary":"..."}}] to finish this TaskRun, or patch graphId="${targetGraph.graphId}" if more steps are needed.`
703
+ : `All child nodes finished for standalone taskRunId="${ownerRunId}". Call task_run operation="complete" with taskRunId="${ownerRunId}" and result={"summary":"..."} to finish this TaskRun, or patch graphId="${targetGraph.graphId}" if more steps are needed.`;
704
+ payload.taskRunId = ownerRunId;
705
+ payload.awaitingCompleteTask = true;
706
+ payload.nextAction = nextAction;
707
+ payload.summary = `${payload.summary || "graph_terminal"} — ${nextAction}`;
708
+ }
709
+
633
710
  function resumeChildTaskLoopIfNeeded(payload = null) {
634
711
  if (selected.isPrimary) return null;
635
712
  if (!payload || payload.status !== "accepted") return null;
@@ -713,11 +790,38 @@ function runPlanGraphCommand(commandInput = {}, options = {}) {
713
790
  };
714
791
  }
715
792
  if (advanced.advance) advance = advanced.advance;
793
+ } else if (
794
+ controlResult.ok
795
+ && touchedStatus
796
+ && options.autoAdvance !== false
797
+ && executionState.planGraph
798
+ && Array.isArray(executionState.planGraph.nodes)
799
+ && executionState.planGraph.nodes.length > 0
800
+ && !executionState.planGraph.waitingFor
801
+ ) {
802
+ const terminalSet = new Set(["succeeded", "failed", "blocked", "cancelled", "skipped"]);
803
+ const allTerminal = executionState.planGraph.nodes.every((n) => (
804
+ n && terminalSet.has(String(n.status || "").trim().toLowerCase())
805
+ ));
806
+ if (allTerminal) {
807
+ advance = { ...advance, yieldReason: "graph_terminal" };
808
+ executionState.planGraph.lastYieldReason = "graph_terminal";
809
+ }
716
810
  }
717
811
  const completedGraph = executionState.planGraph;
718
812
  const terminal = selected.isPrimary
719
813
  ? finalizeTerminalPrimaryPlan(executionState, completedGraph, advance)
720
814
  : null;
815
+ if (!terminal && !selected.isPrimary && advance.yieldReason === "graph_terminal") {
816
+ const childId = String(completedGraph.graphId || "").trim();
817
+ if (childId) {
818
+ executionState.graphs[childId] = {
819
+ ...completedGraph,
820
+ completedAt: new Date().toISOString(),
821
+ lastYieldReason: "graph_terminal",
822
+ };
823
+ }
824
+ }
721
825
  const live = terminal
722
826
  ? completedGraph
723
827
  : executionState.planGraph;
@@ -748,6 +852,7 @@ function runPlanGraphCommand(commandInput = {}, options = {}) {
748
852
  waitingFor: terminal ? null : (live.waitingFor || null),
749
853
  advance,
750
854
  planView: terminal ? [] : projectPlanView(live),
855
+ recovery: terminal ? null : planRecovery(live.nodes),
751
856
  validationWarnings: [],
752
857
  ...(terminal ? {
753
858
  planCompleted: true,
@@ -763,7 +868,15 @@ function runPlanGraphCommand(commandInput = {}, options = {}) {
763
868
  cacheCommand(executionState.planGraph, commandId, payload);
764
869
  }
765
870
  restorePrimaryGraph();
766
- return { ...payload, executionState, modelPayload: payload, ok: payload.status === "accepted" };
871
+ const resumed = resumeChildTaskLoopIfNeeded(payload);
872
+ attachChildTaskLoopHint(payload, resumed, completedGraph);
873
+ return {
874
+ ...payload,
875
+ executionState,
876
+ modelPayload: payload,
877
+ ok: payload.status === "accepted",
878
+ taskLoopResume: resumed || null,
879
+ };
767
880
  }
768
881
 
769
882
  if (operation === "cancel_graph" || operation === "clear") {
@@ -1114,6 +1227,7 @@ function runPlanGraphCommand(commandInput = {}, options = {}) {
1114
1227
  stoppedAt: terminal ? "graph_terminal" : (live.lastStoppedAt || ""),
1115
1228
  advance,
1116
1229
  planView: terminal ? [] : projectPlanView(live),
1230
+ recovery: terminal ? null : planRecovery(live.nodes),
1117
1231
  validationWarnings: preferredCompile.warnings || [],
1118
1232
  summary: terminal
1119
1233
  ? terminal.completionSummary
@@ -1150,6 +1264,7 @@ function runPlanGraphCommand(commandInput = {}, options = {}) {
1150
1264
 
1151
1265
  restorePrimaryGraph();
1152
1266
  const resumed = resumeChildTaskLoopIfNeeded(payload);
1267
+ attachChildTaskLoopHint(payload, resumed, completedGraph);
1153
1268
 
1154
1269
  return {
1155
1270
  ...payload,
@@ -543,12 +543,20 @@ function buildPlanUiProjection(executionState = null, options = {}) {
543
543
  const narrow = cols < 60;
544
544
  const activityMessage = String(options.activityMessage || "").trim();
545
545
 
546
- const pg = state.planGraph && typeof state.planGraph === "object" ? state.planGraph : {};
546
+ const rawPg = state.planGraph && typeof state.planGraph === "object" ? state.planGraph : {};
547
+ const activeRuns = listActiveWritingTaskRuns(state);
548
+ const isChildGraph = Boolean(rawPg.owner && rawPg.owner.kind === "task_loop");
549
+ const isTerminalGraph = String(rawPg.lastYieldReason || "").trim().toLowerCase() === "graph_terminal"
550
+ && !rawPg.waitingFor
551
+ && activeRuns.length === 0;
552
+ let pg = (isChildGraph || isTerminalGraph) ? {} : rawPg;
553
+ if (!pg.graphId && activeRuns.length > 0 && activeRuns[0].childGraphId && state.graphs && state.graphs[activeRuns[0].childGraphId]) {
554
+ pg = state.graphs[activeRuns[0].childGraphId];
555
+ }
547
556
  const view = projectPlanView(pg);
548
557
  const taskNodes = view.filter((node) => node && node.type === "task" && !node.generated);
549
558
  const hasPlan = Boolean(pg.graphId) && taskNodes.length > 0;
550
559
  const progress = countTaskProgress(view);
551
- const activeRuns = listActiveWritingTaskRuns(state);
552
560
  const focus = resolveFocus(view, pg, activeRuns);
553
561
  const taskRun = buildTaskRunProjection(state, view);
554
562
  const leaseHeld = hasActiveWriteLease(state);
@@ -1,7 +1,102 @@
1
1
  "use strict";
2
2
 
3
3
  const PREVIEW_MAX_CHARS = 600;
4
- const MODEL_PAYLOAD_MAX_CHARS = 4000;
4
+ const MODEL_PAYLOAD_MAX_CHARS = 16000;
5
+ const JSON_ARRAY_FOLD_LIMIT = 12;
6
+ const JSON_OBJECT_KEY_LIMIT = 60;
7
+ const JSON_STRING_FIELD_MAX_CHARS = 1600;
8
+ const BASH_JSON_MAX_CHARS = 3600;
9
+ const BASH_STDOUT_MAX_CHARS = 2200;
10
+ const BASH_STDERR_MAX_CHARS = 1200;
11
+
12
+ function looksLikeLargeBase64(value = "") {
13
+ if (typeof value !== "string") return false;
14
+ const trimmed = value.trim();
15
+ if (trimmed.length < 256) return false;
16
+ if (/^data:[a-zA-Z0-9.+-]+\/[a-zA-Z0-9.+-]+;base64,/i.test(trimmed)) return true;
17
+ const compact = trimmed.replace(/\r?\n/g, "");
18
+ if (compact.length < 256 || /\s/.test(compact)) return false;
19
+ if (!/^[A-Za-z0-9+/=_-]+$/.test(compact)) return false;
20
+ // Require a mix of upper, lower, and digits or base64 padding/symbols so
21
+ // ordinary long paths or repeated single-char banners are not misclassified.
22
+ const hasUpper = /[A-Z]/.test(compact);
23
+ const hasLower = /[a-z]/.test(compact);
24
+ const hasDigitOrSym = /[0-9+/=]/.test(compact);
25
+ return hasUpper && hasLower && hasDigitOrSym;
26
+ }
27
+
28
+ function stripEmbeddedBase64(text = "") {
29
+ const source = String(text || "");
30
+ if (!source) return "";
31
+ return source
32
+ .replace(/data:[a-zA-Z0-9.+-]+\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=\s]{128,}/gi, (match) => `[omitted data-uri base64 (${match.length} chars)]`)
33
+ .replace(/\b[A-Za-z0-9+/]{256,}={0,2}\b/g, (match) => (looksLikeLargeBase64(match) ? `[omitted base64 blob (${match.length} chars)]` : match));
34
+ }
35
+
36
+ function dehydrateJsonValue(value, {
37
+ maxArrayItems = JSON_ARRAY_FOLD_LIMIT,
38
+ maxObjectKeys = JSON_OBJECT_KEY_LIMIT,
39
+ maxStringChars = JSON_STRING_FIELD_MAX_CHARS,
40
+ depth = 0,
41
+ } = {}) {
42
+ if (value === null || value === undefined) return value;
43
+ if (typeof value === "string") {
44
+ if (looksLikeLargeBase64(value)) {
45
+ return `[omitted base64 blob (${value.length} chars)]`;
46
+ }
47
+ const cleaned = stripEmbeddedBase64(value);
48
+ return cleaned.length > maxStringChars ? clipText(cleaned, maxStringChars) : cleaned;
49
+ }
50
+ if (typeof value !== "object") return value;
51
+ if (depth >= 8) {
52
+ return Array.isArray(value) ? `[array(${value.length})]` : "[object]";
53
+ }
54
+ if (Array.isArray(value)) {
55
+ const kept = value
56
+ .slice(0, maxArrayItems)
57
+ .map((item) => dehydrateJsonValue(item, { maxArrayItems, maxObjectKeys, maxStringChars, depth: depth + 1 }));
58
+ if (value.length > maxArrayItems) {
59
+ kept.push(`[omitted ${value.length - maxArrayItems} additional items]`);
60
+ }
61
+ return kept;
62
+ }
63
+ const keys = Object.keys(value);
64
+ const out = {};
65
+ const sliceKeys = keys.slice(0, maxObjectKeys);
66
+ for (const key of sliceKeys) {
67
+ out[key] = dehydrateJsonValue(value[key], { maxArrayItems, maxObjectKeys, maxStringChars, depth: depth + 1 });
68
+ }
69
+ if (keys.length > maxObjectKeys) {
70
+ out._omittedKeys = keys.length - maxObjectKeys;
71
+ }
72
+ return out;
73
+ }
74
+
75
+ function compactToolOutputForPrompt(rawText = "", {
76
+ maxArrayItems = JSON_ARRAY_FOLD_LIMIT,
77
+ maxJsonChars = BASH_JSON_MAX_CHARS,
78
+ maxTextChars = BASH_STDOUT_MAX_CHARS,
79
+ tailLineCount = 20,
80
+ } = {}) {
81
+ const source = String(rawText || "");
82
+ if (!source) return "";
83
+ const trimmed = source.trim();
84
+ if ((trimmed.startsWith("{") && trimmed.endsWith("}")) || (trimmed.startsWith("[") && trimmed.endsWith("]"))) {
85
+ try {
86
+ const parsed = JSON.parse(trimmed);
87
+ if (parsed && typeof parsed === "object") {
88
+ const dehydrated = dehydrateJsonValue(parsed, { maxArrayItems });
89
+ const serialized = JSON.stringify(dehydrated, null, 2);
90
+ return clipText(serialized, maxJsonChars);
91
+ }
92
+ } catch {
93
+ // Fall through to text dehydration when output is not valid JSON.
94
+ }
95
+ }
96
+ const stripped = stripEmbeddedBase64(source);
97
+ const tailed = tailLineCount > 0 ? tailLines(stripped, tailLineCount) : stripped;
98
+ return clipText(tailed, maxTextChars);
99
+ }
5
100
 
6
101
  function clipText(value = "", maxChars = PREVIEW_MAX_CHARS) {
7
102
  const text = String(value || "");
@@ -206,6 +301,63 @@ function reduceBashResult(raw = {}, artifactId = "", args = {}) {
206
301
  const stderr = String(source.stderr || "");
207
302
  const command = String((args && args.command) || source.command || "");
208
303
 
304
+ if (source.kind === "background_bash") {
305
+ if (source.action === "list") {
306
+ const processes = Array.isArray(source.processes) ? source.processes : [];
307
+ const runningCount = Number.isFinite(source.runningCount)
308
+ ? source.runningCount
309
+ : processes.filter((item) => item && item.running).length;
310
+ const summary = `bash bg list (${runningCount}/${processes.length} running)`;
311
+ return {
312
+ preview: summary,
313
+ summary,
314
+ modelPayload: {
315
+ ok: source.ok !== false,
316
+ artifactId,
317
+ kind: "background_bash",
318
+ action: "list",
319
+ count: processes.length,
320
+ runningCount,
321
+ processes,
322
+ error: source.error ? String(source.error) : undefined,
323
+ },
324
+ };
325
+ }
326
+
327
+ const logOutput = String(source.logOutput ?? stdout);
328
+ const previewLines = tailLines(logOutput, 8);
329
+ const statusLabel = source.status || (source.running ? "running" : "exited");
330
+ const summary = `bash bg ${source.action || "run"} ${source.backgroundId || ""} status=${statusLabel}`.trim();
331
+ const preview = clipText(
332
+ [summary, previewLines ? `logs:\n${previewLines}` : ""].filter(Boolean).join("\n"),
333
+ PREVIEW_MAX_CHARS,
334
+ );
335
+ return {
336
+ preview,
337
+ summary,
338
+ modelPayload: {
339
+ ok: source.ok !== false,
340
+ artifactId,
341
+ kind: "background_bash",
342
+ action: source.action || "run",
343
+ backgroundId: source.backgroundId || "",
344
+ pid: source.pid ?? null,
345
+ running: Boolean(source.running),
346
+ status: statusLabel,
347
+ exitCode: source.exitCode ?? source.code ?? null,
348
+ signal: source.signal || undefined,
349
+ command: source.command || command || undefined,
350
+ logPath: source.logPath || undefined,
351
+ offset: Number.isFinite(source.offset) ? source.offset : 0,
352
+ nextOffset: Number.isFinite(source.nextOffset) ? source.nextOffset : 0,
353
+ totalBytes: Number.isFinite(source.totalBytes) ? source.totalBytes : 0,
354
+ truncated: Boolean(source.truncated) || logOutput.length > 12000,
355
+ logOutput: clipText(logOutput, 12000),
356
+ error: source.error ? String(source.error) : undefined,
357
+ },
358
+ };
359
+ }
360
+
209
361
  if (isTestCommand(command, stdout)) {
210
362
  return reduceTestResult(raw, artifactId, args);
211
363
  }
@@ -216,8 +368,20 @@ function reduceBashResult(raw = {}, artifactId = "", args = {}) {
216
368
  return reduceSearchResult(raw, artifactId, args);
217
369
  }
218
370
 
371
+ const compactedStdout = compactToolOutputForPrompt(stdout, {
372
+ maxArrayItems: JSON_ARRAY_FOLD_LIMIT,
373
+ maxJsonChars: BASH_JSON_MAX_CHARS,
374
+ maxTextChars: BASH_STDOUT_MAX_CHARS,
375
+ tailLineCount: 20,
376
+ });
377
+ const compactedStderr = compactToolOutputForPrompt(stderr, {
378
+ maxArrayItems: JSON_ARRAY_FOLD_LIMIT,
379
+ maxJsonChars: BASH_STDERR_MAX_CHARS,
380
+ maxTextChars: BASH_STDERR_MAX_CHARS,
381
+ tailLineCount: 20,
382
+ });
219
383
  const preview = clipText(
220
- [stdout ? `stdout:\n${tailLines(stdout, 8)}` : "", stderr ? `stderr:\n${tailLines(stderr, 8)}` : ""]
384
+ [compactedStdout ? `stdout:\n${tailLines(compactedStdout, 8)}` : "", compactedStderr ? `stderr:\n${tailLines(compactedStderr, 8)}` : ""]
221
385
  .filter(Boolean)
222
386
  .join("\n"),
223
387
  PREVIEW_MAX_CHARS,
@@ -229,8 +393,8 @@ function reduceBashResult(raw = {}, artifactId = "", args = {}) {
229
393
  ok: source.ok !== false,
230
394
  artifactId,
231
395
  exitCode: source.code ?? source.exitCode ?? null,
232
- stdoutTail: tailLines(stdout, 20),
233
- stderrTail: tailLines(stderr, 20),
396
+ stdoutTail: compactedStdout,
397
+ stderrTail: compactedStderr,
234
398
  error: source.error ? String(source.error) : undefined,
235
399
  },
236
400
  };
@@ -360,4 +524,8 @@ module.exports = {
360
524
  reduceWriteResult,
361
525
  reduceEditResult,
362
526
  reduceArtifactReadResult,
527
+ looksLikeLargeBase64,
528
+ stripEmbeddedBase64,
529
+ dehydrateJsonValue,
530
+ compactToolOutputForPrompt,
363
531
  };