u-foo 4.0.5 → 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 (149) hide show
  1. package/README.md +224 -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 +5 -3
  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 +36 -20
  49. package/src/agents/providers/providerId.js +17 -0
  50. package/src/agents/providers/runtimeConfig.js +26 -19
  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 -2
  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 +95 -32
  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/features/doctor.js +21 -0
  80. package/src/app/cli/metricsCommands.js +1 -1
  81. package/src/app/cli/run.js +80 -1
  82. package/src/app/cli/setupCommands.js +200 -0
  83. package/src/code/UcodeController.js +31 -1
  84. package/src/code/agent.js +41 -7
  85. package/src/code/busConsumer.js +13 -12
  86. package/src/code/commands.js +0 -1
  87. package/src/code/context/assembler.js +11 -88
  88. package/src/code/context/planGraphService.js +83 -9
  89. package/src/code/context/planProjection.js +10 -2
  90. package/src/code/context/reducers.js +172 -4
  91. package/src/code/context/stateCommit.js +0 -32
  92. package/src/code/context/transcript.js +7 -4
  93. package/src/code/internalThread.js +9 -1
  94. package/src/code/launcher/ucode.js +4 -2
  95. package/src/code/nativeRunner.js +221 -10
  96. package/src/code/repl.js +27 -1
  97. package/src/code/runtime/agentWakeup.js +20 -3
  98. package/src/code/runtime/backgroundWakeHost.js +45 -0
  99. package/src/code/runtime/taskFocusContext.js +7 -0
  100. package/src/code/runtime/taskLoop.js +24 -1
  101. package/src/code/sessionStore.js +14 -10
  102. package/src/code/taskDecomposer.js +13 -7
  103. package/src/code/tools/backgroundProcess.js +23 -0
  104. package/src/code/tools/bash.js +764 -12
  105. package/src/code/tools/executor.js +12 -4
  106. package/src/code/tools/specs.js +60 -3
  107. package/src/code/tools/taskRun.js +38 -0
  108. package/src/config.js +92 -6
  109. package/src/coordination/bus/subscriber.js +1 -1
  110. package/src/coordination/history/agentPerformance.js +18 -18
  111. package/src/coordination/history/agentTrace.js +7 -3
  112. package/src/coordination/state/workspaceAccess.js +3 -1
  113. package/src/orchestration/groups/modelConfig.js +66 -0
  114. package/src/orchestration/groups/validateTemplate.js +2 -0
  115. package/src/runtime/browser/broker.js +1027 -0
  116. package/src/runtime/browser/brokerClient.js +108 -0
  117. package/src/runtime/browser/componentInstaller.js +275 -0
  118. package/src/runtime/browser/installState.js +329 -0
  119. package/src/runtime/browser/manifest.js +145 -0
  120. package/src/runtime/browser/native-host-runner.js +198 -0
  121. package/src/runtime/browser/nativeHost.js +213 -0
  122. package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
  123. package/src/runtime/browser/paths.js +134 -0
  124. package/src/runtime/browser/playwrightSession.js +614 -0
  125. package/src/runtime/daemon/agentHost.js +175 -30
  126. package/src/runtime/daemon/busBridge.js +2 -1
  127. package/src/runtime/daemon/globalDaemon.js +20 -0
  128. package/src/runtime/daemon/groupOrchestrator.js +20 -1
  129. package/src/runtime/daemon/index.js +5 -4
  130. package/src/runtime/daemon/ops.js +14 -8
  131. package/src/tools/handlers/listAgents.js +1 -1
  132. package/src/tools/handlers/readBusSummary.js +1 -1
  133. package/src/tools/handlers/routeAgent.js +122 -5
  134. package/src/tools/schemaFixtures.js +1 -1
  135. package/src/ui/agentSurface.js +26 -3
  136. package/src/ui/format/index.js +34 -2
  137. package/src/ui/rustChatHost.js +22 -7
  138. package/src/ui/rustMultiSession.js +14 -2
  139. package/src/ui/rustUcodeHost.js +246 -77
  140. package/src/ui/ucodeAgentSession.js +88 -0
  141. package/templates/groups/build-lane.json +57 -3
  142. package/templates/groups/build-ultra.json +114 -6
  143. package/templates/groups/design-system.json +57 -3
  144. package/templates/groups/product-discovery.json +57 -3
  145. package/templates/groups/ui-plan-review.json +57 -3
  146. package/templates/groups/ui-polish.json +57 -3
  147. package/templates/groups/verify-ship.json +57 -3
  148. package/src/agents/runtime/context/checkpointStore.js +0 -52
  149. package/src/agents/runtime/context/compaction.js +0 -171
@@ -4,12 +4,22 @@ const { randomUUID } = require("crypto");
4
4
  const ledgerApi = require("../protocol/toolCallLedger");
5
5
  const { materializeResolvedToolResults } = require("../protocol/materialize");
6
6
  const { withFaultPoint } = require("../protocol/faultHarness");
7
+ const { ToolErrorGuard } = require("./toolErrorGuard");
7
8
  const { ToolLoopGuard } = require("./toolLoopGuard");
8
- const { buildContextMeter, contextTokensFromUsage } = require("../context/contextWindow");
9
- const { isContextOverflow } = require("../context/compaction");
9
+ const { buildContextMeter, contextTokensFromUsage, isContextOverflow } = require("../context/contextWindow");
10
10
  const { buildRunObservation, observationFingerprint } = require("../protocol/runObservation");
11
11
 
12
12
  const clone = (value) => JSON.parse(JSON.stringify(value));
13
+ function clonePreservingSymbols(value) {
14
+ const copy = clone(value);
15
+ if (value && copy && typeof value === "object" && typeof copy === "object") {
16
+ for (const sym of Object.getOwnPropertySymbols(value)) {
17
+ const desc = Object.getOwnPropertyDescriptor(value, sym);
18
+ if (desc) Object.defineProperty(copy, sym, desc);
19
+ }
20
+ }
21
+ return copy;
22
+ }
13
23
  const count = (value) => Number.isFinite(Number(value)) && Number(value) > 0 ? Math.floor(Number(value)) : 0;
14
24
 
15
25
  function createExecutionGuards({ signal = null, timeoutMs = 43200000 } = {}) {
@@ -37,6 +47,7 @@ async function runAgentLoop({
37
47
  artifactNamespace = "ucode",
38
48
  contextManager = null, historyOffset: restoredHistoryOffset = null,
39
49
  onConversationUpdate = null,
50
+ runtimeHooks = null,
40
51
  } = {}) {
41
52
  const requestModel = String(model || "").trim();
42
53
  if (!requestModel) throw new Error("agent model is not configured");
@@ -52,8 +63,8 @@ async function runAgentLoop({
52
63
  const companionItems = new Set();
53
64
  const currentTurnItems = () => clone(messages.slice(outputStart).filter((message, index) => {
54
65
  if (String(message.role || "").toLowerCase() !== "user" || companionItems.has(index)) return true;
55
- const companion = Array.isArray(message.content)
56
- && message.content.some(block => ["tool_result", "image", "image_url"].includes(block.type));
66
+ const companion = Boolean(message.durableUserPrompt) || (Array.isArray(message.content)
67
+ && message.content.some(block => ["tool_result", "image", "image_url"].includes(block.type)));
57
68
  // Keep indices stable after one-shot image bytes retire to text markers.
58
69
  if (companion) companionItems.add(index);
59
70
  return companion;
@@ -67,6 +78,9 @@ async function runAgentLoop({
67
78
  let streamed = false;
68
79
  let toolCallsExecuted = 0;
69
80
  let toolErrors = 0;
81
+ const toolErrorGuard = new ToolErrorGuard(toolBudget);
82
+ let errorStop = null;
83
+ let errorWarning = "";
70
84
  let emptyRetries = 0;
71
85
  let activeLedger = null;
72
86
  let lastLedger = null;
@@ -87,6 +101,20 @@ async function runAgentLoop({
87
101
  if (onEvent) await onEvent({ type, time: new Date().toISOString(), projectId, agentId, sessionId, taskId, taskRunId, attemptId, requestId, turnId,
88
102
  traceId: traceId || taskId || taskRunId, parentTaskRunId, parentSessionId, ...data });
89
103
  };
104
+ const recordToolResult = async (name, result) => {
105
+ toolCallsExecuted += 1;
106
+ const failed = !result || result.ok === false;
107
+ if (failed) toolErrors += 1;
108
+ const action = toolErrorGuard.observe(failed);
109
+ if (action) {
110
+ await event(action.kind === "stop" ? "loop.stopped" : "loop.warning", action);
111
+ if (action.kind === "stop") {
112
+ const detail = [name, result && result.error].filter(Boolean).join(": ");
113
+ errorStop = { stopReason: action.code, error: `${action.message}${detail ? `: ${detail}` : ""}` };
114
+ errorWarning = "";
115
+ } else errorWarning = action.message;
116
+ } else if (!toolErrorGuard.warned) errorWarning = "";
117
+ };
90
118
  const policyStop = async (hook, extra = {}) => {
91
119
  for (const policy of policies) {
92
120
  const stop = policy[hook] && await policy[hook]({ ...context(), ...extra });
@@ -99,7 +127,7 @@ async function runAgentLoop({
99
127
  const resolve = (call, result) => ledgerApi.resolveCall(activeLedger, callId(call), { result: sanitizeResult(result), isError: !result || result.ok === false });
100
128
  const mirror = () => {
101
129
  if (providerMessages === messages) return;
102
- messages.push(...clone(providerMessages.slice(isolatedPrefix)));
130
+ messages.push(...providerMessages.slice(isolatedPrefix).map(clonePreservingSymbols));
103
131
  isolatedPrefix = providerMessages.length;
104
132
  };
105
133
  const finish = (extra = {}) => ({
@@ -130,7 +158,7 @@ async function runAgentLoop({
130
158
  }
131
159
  return null;
132
160
  };
133
- const toolContext = (extra = {}) => ({ workspaceRoot, onToolEvent: typeof onToolEvent === "function" ? event => onToolEvent({ ...event,
161
+ const toolContext = (extra = {}) => ({ workspaceRoot, runtimeHooks, onToolEvent: typeof onToolEvent === "function" ? event => onToolEvent({ ...event,
134
162
  ...(event.origin ? { parentToolCallId: extra.toolCallId } : { toolCallId: extra.toolCallId }) }) : null, sessionId, onArtifactPersisted, executionState, signal,
135
163
  projectId, agentId, taskId, taskRunId, attemptId, requestId, turnId, traceId: traceId || taskId || taskRunId, parentTaskRunId, parentSessionId, artifactNamespace, ...extra });
136
164
  if (onEvent) await event("run.config", { configuration: buildRunObservation({ provider, model: requestModel,
@@ -140,14 +168,15 @@ async function runAgentLoop({
140
168
 
141
169
  try { while (true) {
142
170
  activeGuards.ensureActive();
143
- const turnStop = await policyStop("beforeTurn");
171
+ const turnStop = errorStop ? null : await policyStop("beforeTurn");
144
172
  if (turnStop) return finish(turnStop);
145
- if (usage.turns >= maxRounds) return finish({ stopReason: "budget_exceeded" });
173
+ if (usage.turns >= maxRounds) return finish(errorStop || { stopReason: "budget_exceeded" });
146
174
  turnId = `turn_${randomUUID()}`;
147
175
  providerMessages = messages;
148
- for (const policy of policies) {
176
+ for (const policy of errorStop ? [] : policies) {
149
177
  if (policy.prepareTurn) providerMessages = await policy.prepareTurn({ ...context(), providerMessages }) || providerMessages;
150
178
  }
179
+ const isIsolatedTurn = providerMessages !== messages;
151
180
  isolatedPrefix = providerMessages.length;
152
181
  if (activeLedger) {
153
182
  if (providerTurnGate) providerTurnGate(activeLedger);
@@ -155,26 +184,41 @@ async function runAgentLoop({
155
184
  throw new Error("unresolved tool calls before provider turn");
156
185
  }
157
186
  }
158
- const action = loopGuard.nextAction();
187
+ const action = errorStop ? null : loopGuard.nextAction();
159
188
  if (action) await event(`loop.${action.kind === "stop" ? "stopped" : "warning"}`, { code: "repeated_tool_calls", repeatedSteps: loopGuard.count, toolNames: loopGuard.names });
160
189
  if (action && action.kind === "stop") return finish({ error: action.message, stopReason: "repeated_tool_calls" });
161
190
  if (action && action.kind === "warn") providerMessages.push({ role: "user", content: action.message });
191
+ if (errorStop) {
192
+ providerMessages.push({ role: "user", content: `Tool execution has stopped: ${errorStop.error}. No tools are available. Give one brief final response in the task user's language describing verified progress, the blocker, and the next useful action. Do not claim the task succeeded or issue further tool calls.` });
193
+ } else if (errorWarning) {
194
+ providerMessages.push({ role: "user", content: errorWarning });
195
+ errorWarning = "";
196
+ }
162
197
  mirror();
198
+ const requestTools = errorStop ? [] : tools.toOpenAiTools();
163
199
 
164
200
  let maxOutputTokens;
165
201
  if (contextManager) {
202
+ let sysPrefix = 0;
203
+ while (sysPrefix < providerMessages.length && String(providerMessages[sysPrefix]?.role || "").toLowerCase() === "system") sysPrefix += 1;
204
+ const prepareHistoryOffset = isIsolatedTurn
205
+ ? sysPrefix
206
+ : Math.min(providerMessages.length, sysPrefix + historyOffset);
207
+ const logicalTurnId = taskRunId || (sessionId ? `${sessionId}:${historyOffset}` : `offset_${historyOffset}`);
166
208
  let prepared;
167
209
  try { prepared = await contextManager.prepare({ messages: providerMessages, model: requestModel, systemPrompt, systemBlocks,
168
- tools: tools.toOpenAiTools(), transport, signal, onPhase, onEvent: event,
210
+ tools: requestTools, transport, signal, onPhase, onEvent: event,
169
211
  lastUsage: usage.lastContextTokens, lastEstimate: lastContextEstimate,
170
- force: forceCompaction,
212
+ force: forceCompaction, historyOffset: prepareHistoryOffset, requestKind, turnId: logicalTurnId, resume,
213
+ isolated: isIsolatedTurn,
171
214
  request: { url: requestUrl, apiKey, provider, accountId, requestHeaders, requestProfile, sessionId } }); }
172
215
  catch (error) {
173
216
  // Preflight runs only after tool results are paired. Keep this complete
174
217
  // transcript even when compression is cancelled or storage is broken.
175
- return finish({ error: error.message, stopReason: error.code || "context_compression_failed" });
218
+ return finish(errorStop || { error: error.message, stopReason: error.code || "context_compression_failed" });
176
219
  }
177
220
  providerMessages = prepared.messages;
221
+ isolatedPrefix = providerMessages.length;
178
222
  lastContextEstimate = prepared.estimatedTokens;
179
223
  maxOutputTokens = prepared.maxOutputTokens;
180
224
  forceCompaction = false;
@@ -191,9 +235,10 @@ async function runAgentLoop({
191
235
  let turnResult;
192
236
  let turnError = null;
193
237
  const outputBeforeTurn = aggregated.length;
238
+ let stepStreamedText = false;
194
239
  try { turnResult = await transport.runTurn({
195
240
  url: requestUrl, apiKey, model: requestModel, provider, accountId, requestHeaders, requestProfile, thinkingLevel,
196
- systemPrompt, systemBlocks, messages: providerMessages, tools: tools.toOpenAiTools(),
241
+ systemPrompt, systemBlocks, messages: providerMessages, tools: requestTools,
197
242
  ...(maxOutputTokens ? { maxOutputTokens } : {}),
198
243
  sessionId, signal, timeoutMs,
199
244
  onPhase(phase) {
@@ -207,6 +252,10 @@ async function runAgentLoop({
207
252
  onTextDelta(chunk) {
208
253
  const text = String(chunk || "");
209
254
  if (!text) return;
255
+ if (!stepStreamedText && aggregated && !aggregated.endsWith("\n") && !/^\s/.test(text)) {
256
+ aggregated += "\n\n";
257
+ }
258
+ stepStreamedText = true;
210
259
  aggregated += text;
211
260
  if (onEvent) {
212
261
  streamed = true;
@@ -220,6 +269,7 @@ async function runAgentLoop({
220
269
  }
221
270
  if (turnError) {
222
271
  await event("model.failed", { error: turnError.message, code: turnError.code || "provider_error", durationMs: Date.now() - modelStarted });
272
+ if (errorStop) return finish({ ...errorStop, summaryError: turnError.message });
223
273
  if (!contextManager || !isContextOverflow(turnError)) throw turnError;
224
274
  if (contextRetry || aggregated.length !== outputBeforeTurn) return finish({ error: turnError.message, stopReason: "context_budget_exceeded" });
225
275
  contextRetry = true;
@@ -238,6 +288,18 @@ async function runAgentLoop({
238
288
  if (typeof onContextUsage === "function") {
239
289
  try { onContextUsage(buildContextMeter({ usedTokens: usage.lastContextTokens, model: requestModel })); } catch { /* observer only */ }
240
290
  }
291
+ if (errorStop) {
292
+ // Exactly one text-only closing attempt: never execute tool/legacy commands,
293
+ // retry an empty response, or enter a policy auto-continuation here.
294
+ const text = String(turnResult.text || "").trim();
295
+ if (text) {
296
+ transport.appendFinalAssistantMessage({ messages: providerMessages, turnResult: { text } });
297
+ mirror();
298
+ await commitConversation();
299
+ }
300
+ if (!aggregated.trim() && text) aggregated = text;
301
+ return finish({ ...errorStop, finalText: text });
302
+ }
241
303
  const calls = transport.getToolCalls(turnResult);
242
304
  if (!calls.length) {
243
305
  loopGuard.reset();
@@ -260,6 +322,7 @@ async function runAgentLoop({
260
322
  const result = await tools.execute(legacy.tool, legacy.args, toolContext({ origin: legacy.origin }));
261
323
  activeGuards.ensureActive();
262
324
  if (result && result.executionState) executionState = result.executionState;
325
+ await recordToolResult(legacy.tool, result);
263
326
  providerMessages.push({ role: "user", content: JSON.stringify({ type: legacy.resultType, ...sanitizeResult(result && result.status ? result : { status: "rejected", ok: false, error: `${legacy.tool} failed` }) }) });
264
327
  mirror();
265
328
  await commitConversation();
@@ -304,19 +367,17 @@ async function runAgentLoop({
304
367
  await withFaultPoint("before_tool_exec", () => {});
305
368
  let batchError = null;
306
369
  for (const policy of policies) if (policy.validateBatch) { batchError = policy.validateBatch(pending); if (batchError) break; }
307
- if (batchError) {
308
- for (const call of pending) {
309
- await event("tool.rejected", { toolCallId: callId(call), toolName: call.name, code: batchError.code || "invalid_batch", argumentFingerprint: observationFingerprint(call.args) });
310
- resolve(call, batchError); toolCallsExecuted += 1; toolErrors += 1;
311
- }
312
- flush(pending);
313
- await commitConversation();
314
- continue;
315
- }
316
370
  let deferred = null;
317
371
  let toolStop = null;
318
372
  for (const call of pending) {
319
373
  const name = String(call.name || "").trim().toLowerCase();
374
+ if (errorStop) {
375
+ // These calls were declared but never executed; pair explicit rejections.
376
+ const rejected = { ok: false, code: errorStop.stopReason, error: "not executed: tool failure limit reached" };
377
+ resolve(call, rejected);
378
+ await event("tool.rejected", { toolCallId: callId(call), toolName: name, code: rejected.code, argumentFingerprint: observationFingerprint(call.args) });
379
+ continue;
380
+ }
320
381
  const before = toolStop || await policyStop("beforeTool", { call });
321
382
  if (before) {
322
383
  toolStop = before;
@@ -324,11 +385,13 @@ async function runAgentLoop({
324
385
  resolve(call, { ok: false, code: before.stopReason || "stopped", error: "execution stopped before tool invocation" });
325
386
  continue;
326
387
  }
327
- let blocked = null;
328
- for (const policy of policies) if (policy.validateTool) { blocked = policy.validateTool(name, executionState); if (blocked) break; }
388
+ let blocked = batchError;
389
+ for (const policy of blocked ? [] : policies) if (policy.validateTool) { blocked = policy.validateTool(name, executionState); if (blocked) break; }
329
390
  if (blocked) {
330
391
  await event("tool.rejected", { toolCallId: callId(call), toolName: name, code: blocked.code || "tool_not_allowed", argumentFingerprint: observationFingerprint(call.args) });
331
- toolCallsExecuted += 1; toolErrors += 1; resolve(call, blocked); continue;
392
+ resolve(call, blocked);
393
+ await recordToolResult(name, blocked);
394
+ continue;
332
395
  }
333
396
  const resumeCall = tools.deferableTools().includes(name) ? { toolCallId: callId(call), toolName: name, call: { name: call.name, args: call.args, source: call.source } } : null;
334
397
  ledgerApi.markExecuting(activeLedger, callId(call));
@@ -343,8 +406,7 @@ async function runAgentLoop({
343
406
  throw error;
344
407
  }
345
408
  if (result && result.executionState) executionState = result.executionState;
346
- toolCallsExecuted += 1;
347
- if (!result || result.ok === false) toolErrors += 1;
409
+ await recordToolResult(name, result);
348
410
  if (resumeCall && result && result.deferToolResult) {
349
411
  for (const policy of policies) if (policy.onDeferred) policy.onDeferred({ executionState, resume: resumeCall, provider });
350
412
  ledgerApi.deferCall(activeLedger, callId(call), { reason: name });
@@ -358,13 +420,14 @@ async function runAgentLoop({
358
420
  toolStop = await policyStop("afterTool", { call, result });
359
421
  if (toolStop) continue;
360
422
  if (toolBudget.maxToolCalls != null && toolCallsExecuted >= toolBudget.maxToolCalls) throw new Error(`tool call budget exceeded (${toolBudget.maxToolCalls})`);
361
- if (toolErrors >= (toolBudget.maxToolErrors ?? 20)) {
362
- const detail = [call.name, result && result.error].filter(Boolean).join(": ");
363
- throw new Error(`tool error budget exceeded (${toolBudget.maxToolErrors ?? 20})${detail ? `: ${detail}` : ""}`);
364
- }
365
423
  }
366
424
  flush(pending);
367
425
  if (!ledgerApi.listUnresolved(activeLedger).length && !ledgerApi.listDeferred(activeLedger).length) await commitConversation();
426
+ if (errorStop) {
427
+ // Never send an unresolved deferred call back to the provider.
428
+ if (ledgerApi.listDeferred(activeLedger).length) return finish(errorStop);
429
+ continue;
430
+ }
368
431
  if (toolStop) return finish(toolStop);
369
432
  const interaction = pendingInteraction();
370
433
  if (deferred || interaction) return finish({ waitingUserInteraction: true, interactionId: deferred && deferred.interactionId || interaction && interaction.id || "" });
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
 
3
3
  const DEFAULT_TASK_TIMEOUT_MS = 43200000;
4
- const DEFAULT_MAX_TOOL_ERRORS = 20;
4
+ // Legacy setting name: now limits consecutive failures, not lifetime errors.
5
+ const DEFAULT_MAX_TOOL_ERRORS = 5;
5
6
 
6
7
  function parseMaxToolCalls(value) {
7
8
  if (value == null || String(value).trim().toLowerCase() === "none") return null;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+
3
+ const { DEFAULT_MAX_TOOL_ERRORS } = require("./executionBudget");
4
+
5
+ // Track recoverable tool failures independently of transport retries and loop signatures.
6
+ class ToolErrorGuard {
7
+ constructor({ maxToolErrors = DEFAULT_MAX_TOOL_ERRORS } = {}) {
8
+ this.limit = Number.isSafeInteger(maxToolErrors) && maxToolErrors > 0 ? maxToolErrors : DEFAULT_MAX_TOOL_ERRORS;
9
+ this.consecutive = 0;
10
+ this.recent = [];
11
+ this.warned = false;
12
+ }
13
+
14
+ observe(failed) {
15
+ this.consecutive = failed ? this.consecutive + 1 : 0;
16
+ this.recent.push(Boolean(failed));
17
+ if (this.recent.length > 20) this.recent.shift();
18
+ const recentErrors = this.recent.filter(Boolean).length;
19
+ const warningAt = Math.max(1, Math.ceil(this.limit / 2));
20
+ const consecutiveLimit = this.consecutive >= this.limit;
21
+ const windowLimit = this.recent.length === 20 && recentErrors >= 12;
22
+ if (consecutiveLimit || windowLimit) {
23
+ return { kind: "stop", code: "tool_error_budget_exceeded", consecutiveErrors: this.consecutive, recentErrors,
24
+ message: consecutiveLimit
25
+ ? `tool error budget exceeded (${this.limit}): ${this.consecutive} consecutive failures`
26
+ : "tool error budget exceeded: 12 or more failures in the last 20 tool calls" };
27
+ }
28
+ const warning = this.consecutive >= warningAt || (this.recent.length === 20 && recentErrors >= 10);
29
+ if (!warning) this.warned = false;
30
+ if (warning && !this.warned) {
31
+ this.warned = true;
32
+ return { kind: "warn", code: "tool_error_warning", consecutiveErrors: this.consecutive, recentErrors,
33
+ message: `Tool failures are accumulating (${this.consecutive} consecutive; ${recentErrors} in the last ${this.recent.length} calls). Inspect the errors and change your approach. Execution stops at ${this.limit} consecutive failures or 12 failures in a full 20-call window. A successful call only resets the consecutive count.` };
34
+ }
35
+ return null;
36
+ }
37
+ }
38
+
39
+ module.exports = { ToolErrorGuard };
@@ -6,6 +6,7 @@ const { assertTransport } = require("../providers/transports/transportContract")
6
6
  const { randomUUID, createHash } = require("crypto");
7
7
  const { createCommandStore } = require("./context/commandStore");
8
8
  const { stableStringify } = require("./core/stableJson");
9
+ const { createRuntimeHooks, formatWakeEvent } = require("./tasks/hooks");
9
10
 
10
11
  const terminal = new Set(["completed", "failed", "cancelled", "interrupted", "waiting_user"]);
11
12
  const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error.code !== "ESRCH"; } };
@@ -29,6 +30,8 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
29
30
  let activeRun = null;
30
31
  let runController = null;
31
32
  let closePromise = null;
33
+ let hooks = host.runtimeHooks || null;
34
+ const ownsHooks = !hooks && Boolean(host.hookSources && host.sessionStore);
32
35
  const ownerId = randomUUID();
33
36
  const waiters = new Map();
34
37
  const storage = host.sessionStore;
@@ -59,16 +62,23 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
59
62
  if (task && terminal.has(task.status)) { listeners.forEach((resolve) => resolve(task)); waiters.delete(id); }
60
63
  }
61
64
  };
65
+ let interruptedTasks = [];
62
66
  if (store) store.transaction((state) => {
63
67
  if (state.profile && state.profile !== (profile && profile.id || "custom")) throw new Error("session profile is pinned; use a new session or explicit checkpoint migration");
64
68
  if (state.owner && pidAlive(state.owner.pid)) throw Object.assign(new Error("runtime session already owned"), { code: "runtime_busy" });
65
69
  const selectedCapabilities = composition.capabilities.map((capability) => capability.id);
66
- if (state.capabilities && stableStringify(state.capabilities) !== stableStringify(selectedCapabilities)
70
+ const matchesAdditively = Array.isArray(state.capabilities)
71
+ && stableStringify(state.capabilities) === stableStringify(selectedCapabilities.filter((id) => !["turn-recall", "browser"].includes(id) || state.capabilities.includes(id)));
72
+ if (state.capabilities && stableStringify(state.capabilities) !== stableStringify(selectedCapabilities) && !matchesAdditively
67
73
  && Object.values(state.tasks).some((task) => ["queued", "running", "waiting_user"].includes(task.status))) throw new Error("cannot change capabilities with unfinished state; use a new session or explicit migration");
68
- return [...Object.values(state.tasks).filter((task) => task.status === "running").map((task) => ({
74
+ interruptedTasks = Object.values(state.tasks).filter((task) => task.status === "running");
75
+ return [...interruptedTasks.map((task) => ({
69
76
  type: "task.interrupted", taskRunId: task.taskRunId, error: "owner stopped; inspect effects before resubmitting",
70
77
  })), { type: "runtime.opened", owner: { id: ownerId, pid: process.pid, profile: profile && profile.id || "custom", capabilities: selectedCapabilities } }];
71
78
  });
79
+ if (interruptedTasks.length && typeof host.onTasksInterrupted === "function") {
80
+ try { host.onTasksInterrupted(interruptedTasks); } catch {}
81
+ }
72
82
  const record = async (event) => {
73
83
  const before = store.read();
74
84
  const task = before.tasks[event.taskRunId];
@@ -96,7 +106,10 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
96
106
  };
97
107
  async function pump() {
98
108
  while (!closed) {
99
- const task = Object.values(store.read().tasks).filter((item) => item.status === "queued").sort((a, b) => a.sequence - b.sequence)[0];
109
+ const snapshot = store.read();
110
+ const waitingUser = Object.values(snapshot.tasks).some(item => item.status === "waiting_user");
111
+ const task = Object.values(snapshot.tasks).filter((item) => item.status === "queued" && (!item.request.runtimeEvent || !waitingUser))
112
+ .sort((a, b) => Number(Boolean(a.request.runtimeEvent)) - Number(Boolean(b.request.runtimeEvent)) || a.sequence - b.sequence)[0];
100
113
  if (!task) return;
101
114
  activeTask = task.taskRunId;
102
115
  controller = new AbortController();
@@ -108,6 +121,7 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
108
121
  ? await host.resumeRequest(task, task.answer)
109
122
  : host.prepareRequest ? await host.prepareRequest(task.request, task) : { prompt: task.request.text };
110
123
  return runtime.run({ ...prepared, requestId: task.request.requestId,
124
+ requestKind: task.request.requestKind || prepared.requestKind,
111
125
  taskId: task.request.taskId || task.taskRunId, taskRunId: task.taskRunId, attemptId,
112
126
  traceId: task.request.traceId || task.request.taskId || task.taskRunId,
113
127
  parentTaskRunId: task.request.parentTaskRunId || "", parentSessionId: task.request.parentSessionId || "",
@@ -118,15 +132,47 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
118
132
  : await execute(controller.signal);
119
133
  if (controller.signal.aborted) throw Object.assign(new Error("agent cancelled"), { code: "cancelled" });
120
134
  if (result.error || result.stopReason) throw Object.assign(new Error(result.error || `agent stopped: ${result.stopReason}`), { code: result.stopReason || "runtime_error", result });
135
+ const terminal = result.waitingUserInteraction ? result : terminalResult(result);
136
+ const slicedTurnMessages = Array.isArray(result.messages) && Number.isInteger(result.historyOffset)
137
+ ? result.messages.filter((message) => message.role !== "system").slice(result.historyOffset)
138
+ : (terminal.messages || []);
139
+ if (typeof host.onTurnSettled === "function") {
140
+ try {
141
+ const settledEvent = await host.onTurnSettled({
142
+ task,
143
+ outcome: result.waitingUserInteraction ? "paused" : "completed",
144
+ result,
145
+ messages: slicedTurnMessages,
146
+ historyOffset: Number.isInteger(result.historyOffset) ? result.historyOffset : 0,
147
+ });
148
+ if (settledEvent && settledEvent.type) await record(settledEvent);
149
+ } catch {}
150
+ }
121
151
  await record({ type: result.waitingUserInteraction ? "task.paused" : "task.completed", taskRunId: activeTask,
122
- result: result.waitingUserInteraction ? result : terminalResult(result) });
152
+ result: terminal });
123
153
  } catch (error) {
124
154
  if (store.read().tasks[activeTask]?.status === "completed") {
125
155
  if (host.onError) host.onError(error);
126
156
  continue;
127
157
  }
128
- await record({ type: controller.signal.aborted || error.code === "cancelled" ? "task.cancelled" : "task.failed",
129
- taskRunId: activeTask, error: error.message, code: error.code || "runtime_error", ...(error.result ? { result: terminalResult(error.result) } : {}) });
158
+ const cancelled = controller.signal.aborted || error.code === "cancelled";
159
+ const errTerminal = error.result ? terminalResult(error.result) : null;
160
+ if (typeof host.onTurnSettled === "function") {
161
+ try {
162
+ const settledEvent = await host.onTurnSettled({
163
+ task,
164
+ outcome: cancelled ? "cancelled" : "failed",
165
+ error: error.message,
166
+ code: error.code || "runtime_error",
167
+ result: error.result || null,
168
+ messages: errTerminal && Array.isArray(errTerminal.messages) ? errTerminal.messages : [],
169
+ historyOffset: Number.isInteger(error.result?.historyOffset) ? error.result.historyOffset : 0,
170
+ });
171
+ if (settledEvent && settledEvent.type) await record(settledEvent);
172
+ } catch {}
173
+ }
174
+ await record({ type: cancelled ? "task.cancelled" : "task.failed",
175
+ taskRunId: activeTask, error: error.message, code: error.code || "runtime_error", ...(error.result ? { result: errTerminal } : {}) });
130
176
  } finally { activeTask = ""; controller = null; }
131
177
  }
132
178
  }
@@ -137,7 +183,8 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
137
183
  }).finally(() => {
138
184
  pumpPromise = null;
139
185
  notify();
140
- if (!closed && Object.values(store.read().tasks).some((task) => task.status === "queued")) startPump();
186
+ const tasks = Object.values(store.read().tasks);
187
+ if (!closed && tasks.some(task => task.status === "queued" && (!task.request.runtimeEvent || !tasks.some(item => item.status === "waiting_user")))) startPump();
141
188
  });
142
189
  }
143
190
  const runtime = Object.freeze({
@@ -145,6 +192,7 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
145
192
  capabilities: composition.capabilities,
146
193
  buildContext: composition.buildContext,
147
194
  promptSections: composition.promptSections,
195
+ get hooks() { return hooks; },
148
196
  async run(input = {}) {
149
197
  if (closed) throw Object.assign(new Error("agent runtime is closed"), { code: "runtime_closed" });
150
198
  if (running) throw Object.assign(new Error("agent runtime is already running"), { code: "runtime_busy" });
@@ -159,11 +207,16 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
159
207
  try {
160
208
  activeRun = runAgentLoop({
161
209
  ...defaults, ...input, transport,
210
+ runtimeHooks: hooks,
162
211
  tools: composition.tools, policies: composition.policies,
163
212
  signal: runController.signal,
164
213
  });
165
214
  return await activeRun;
166
215
  } finally {
216
+ if (runController.signal.aborted && runController.signal.reason !== "runtime_closed") {
217
+ hooks?.cancelOwner(input.taskRunId);
218
+ if (input.requestKind === "system_wake" && input.parentTaskRunId) hooks?.cancelOwner(input.parentTaskRunId);
219
+ }
167
220
  running = false;
168
221
  activeRun = null;
169
222
  runController = null;
@@ -193,6 +246,11 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
193
246
  startPump();
194
247
  return { accepted: true, requestId: request.requestId, taskRunId: id, status: state.tasks[id].status, sequence: state.sequence };
195
248
  },
249
+ wake(event) {
250
+ const original = store.read().tasks[event.ownerTaskRunId]?.request.text || "";
251
+ return runtime.submit({ requestId: event.id, text: `${formatWakeEvent(event)}\nOriginal task (historical context; preserve its language): ${JSON.stringify(original)}`, runtimeEvent: event.id,
252
+ parentTaskRunId: event.ownerTaskRunId, requestKind: "system_wake" });
253
+ },
196
254
  async resume({ interactionId, answer } = {}) {
197
255
  requireStore();
198
256
  if (closed) throw new Error("agent runtime is closed");
@@ -216,6 +274,11 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
216
274
  requireStore();
217
275
  const task = store.read().tasks[taskRunId];
218
276
  if (!task) throw new Error("task not found");
277
+ hooks?.cancelOwner(taskRunId);
278
+ store.transaction(state => Object.values(state.tasks).filter(item => item.request.runtimeEvent && item.request.parentTaskRunId === taskRunId && item.status === "queued")
279
+ .map(item => ({ type: "task.cancelled", taskRunId: item.taskRunId, error: reason })));
280
+ if (controller && store.read().tasks[activeTask]?.request.runtimeEvent && store.read().tasks[activeTask]?.request.parentTaskRunId === taskRunId) controller.abort(reason);
281
+ notify();
219
282
  if (terminal.has(task.status) && task.status !== "waiting_user") return { taskRunId, status: task.status };
220
283
  if (activeTask === taskRunId && controller) {
221
284
  store.append({ type: "task.cancel_requested", taskRunId, reason });
@@ -236,6 +299,7 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
236
299
  async close() {
237
300
  if (closePromise) return closePromise;
238
301
  closed = true;
302
+ if (ownsHooks) hooks?.close();
239
303
  if (controller) controller.abort("runtime_closed");
240
304
  if (runController) runController.abort("runtime_closed");
241
305
  closePromise = (async () => {
@@ -245,6 +309,9 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
245
309
  for (const capability of composition.capabilities.slice().reverse()) if (capability.dispose) {
246
310
  try { await capability.dispose(); } catch (error) { disposalError = disposalError || error; }
247
311
  }
312
+ if (typeof host.onClose === "function") {
313
+ try { await host.onClose(); } catch (error) { disposalError = disposalError || error; }
314
+ }
248
315
  if (store) store.transaction((state) => state.owner && state.owner.id === ownerId ? [{ type: "runtime.closed" }] : []);
249
316
  notify();
250
317
  if (disposalError) throw disposalError;
@@ -252,6 +319,12 @@ function createAgentRuntime({ profile, transport, capabilities, host = {}, defau
252
319
  return closePromise;
253
320
  },
254
321
  });
322
+ if (ownsHooks) {
323
+ hooks = createRuntimeHooks({ store, sources: host.hookSources, deliver: event => runtime.wake(event),
324
+ canDeliver: () => !closed && !running && !Object.values(store.read().tasks).some(task => ["running", "queued", "waiting_user"].includes(task.status)),
325
+ onError: error => host.onError?.(error) });
326
+ hooks.start();
327
+ }
255
328
  if (store) startPump();
256
329
  return runtime;
257
330
  }
@@ -9,6 +9,11 @@ module.exports = {
9
9
  ...require("./context/sessionStore"),
10
10
  ...require("./context/runtimeStore"),
11
11
  ...require("./context/commandStore"),
12
+ ...require("./context/turnIndexStore"),
13
+ ...require("./context/turnAnalyzer"),
14
+ ...require("./context/topicSelector"),
15
+ ...require("./context/slidingWindowManager"),
12
16
  ...require("./tasks/scheduler"),
13
17
  ...require("./tasks/resourceLease"),
18
+ ...require("./tasks/hooks"),
14
19
  };
@@ -79,7 +79,7 @@ function materializeAnswerToolResult(messages = [], resume = null, answer = {},
79
79
  if (!call || !call.source) return { ok: false, error: "missing deferred tool call" };
80
80
  const transportName = String(resume.transport || "openai-chat");
81
81
  const content = clip(toJsonString(answer), 12000);
82
- if (transportName === "anthropic-messages") {
82
+ if (transportName === "anthropic-messages" || transportName === "antigravity") {
83
83
  messages.push({
84
84
  role: "user",
85
85
  content: [{