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
@@ -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 } = {}) {
@@ -36,6 +46,8 @@ async function runAgentLoop({
36
46
  traceId = "", parentTaskRunId = "", parentSessionId = "",
37
47
  artifactNamespace = "ucode",
38
48
  contextManager = null, historyOffset: restoredHistoryOffset = null,
49
+ onConversationUpdate = null,
50
+ runtimeHooks = null,
39
51
  } = {}) {
40
52
  const requestModel = String(model || "").trim();
41
53
  if (!requestModel) throw new Error("agent model is not configured");
@@ -48,10 +60,15 @@ async function runAgentLoop({
48
60
  const historyOffset = restoredHistoryOffset ?? (resume ? 0 : messages.filter(message => message.role !== "system").length);
49
61
  if (!resume) transport.prepareMessages({ messages, systemPrompt, prompt });
50
62
  const outputStart = messages.length;
51
- const currentTurnItems = () => clone(messages.slice(outputStart)).filter((message) => (
52
- String(message.role || "").toLowerCase() !== "user" || Array.isArray(message.content)
53
- && message.content.some((block) => ["tool_result", "image", "image_url"].includes(block.type))
54
- ));
63
+ const companionItems = new Set();
64
+ const currentTurnItems = () => clone(messages.slice(outputStart).filter((message, index) => {
65
+ if (String(message.role || "").toLowerCase() !== "user" || companionItems.has(index)) return true;
66
+ const companion = Boolean(message.durableUserPrompt) || (Array.isArray(message.content)
67
+ && message.content.some(block => ["tool_result", "image", "image_url"].includes(block.type)));
68
+ // Keep indices stable after one-shot image bytes retire to text markers.
69
+ if (companion) companionItems.add(index);
70
+ return companion;
71
+ }));
55
72
  let executionState = initialState;
56
73
  for (const policy of policies) if (policy.initializeState) executionState = policy.initializeState(executionState);
57
74
  if (!executionState || typeof executionState !== "object") executionState = {};
@@ -61,9 +78,15 @@ async function runAgentLoop({
61
78
  let streamed = false;
62
79
  let toolCallsExecuted = 0;
63
80
  let toolErrors = 0;
81
+ const toolErrorGuard = new ToolErrorGuard(toolBudget);
82
+ let errorStop = null;
83
+ let errorWarning = "";
64
84
  let emptyRetries = 0;
65
85
  let activeLedger = null;
66
86
  let lastLedger = null;
87
+ let activePending = [];
88
+ let flushedLedgerId = "";
89
+ let flushAttemptedLedgerId = "";
67
90
  let autoContinues = 0;
68
91
  let lastContinueKey = "";
69
92
  let emptyContinues = 0;
@@ -78,6 +101,20 @@ async function runAgentLoop({
78
101
  if (onEvent) await onEvent({ type, time: new Date().toISOString(), projectId, agentId, sessionId, taskId, taskRunId, attemptId, requestId, turnId,
79
102
  traceId: traceId || taskId || taskRunId, parentTaskRunId, parentSessionId, ...data });
80
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
+ };
81
118
  const policyStop = async (hook, extra = {}) => {
82
119
  for (const policy of policies) {
83
120
  const stop = policy[hook] && await policy[hook]({ ...context(), ...extra });
@@ -90,7 +127,7 @@ async function runAgentLoop({
90
127
  const resolve = (call, result) => ledgerApi.resolveCall(activeLedger, callId(call), { result: sanitizeResult(result), isError: !result || result.ok === false });
91
128
  const mirror = () => {
92
129
  if (providerMessages === messages) return;
93
- messages.push(...clone(providerMessages.slice(isolatedPrefix)));
130
+ messages.push(...providerMessages.slice(isolatedPrefix).map(clonePreservingSymbols));
94
131
  isolatedPrefix = providerMessages.length;
95
132
  };
96
133
  const finish = (extra = {}) => ({
@@ -98,11 +135,21 @@ async function runAgentLoop({
98
135
  turnItems: currentTurnItems(), usage, executionState,
99
136
  protocolLedger: lastLedger || ledgerApi.snapshotLedger(activeLedger), historyOffset, ...extra,
100
137
  });
138
+ let committedMessages = messages.length;
139
+ let committedItems = [];
140
+ const commitConversation = async () => {
141
+ // A persistence port is awaited, unlike display/telemetry observers.
142
+ committedMessages = messages.length;
143
+ committedItems = currentTurnItems();
144
+ if (onConversationUpdate) await onConversationUpdate(finish({ turnItems: committedItems }));
145
+ };
101
146
  const flush = (calls) => {
147
+ flushAttemptedLedgerId = activeLedger.turnId;
102
148
  const pendingById = Object.fromEntries(calls.map((call) => [callId(call), call]));
103
149
  materializeResolvedToolResults(activeLedger, { transport, messages: providerMessages, pendingById });
104
150
  mirror();
105
151
  lastLedger = ledgerApi.snapshotLedger(activeLedger);
152
+ flushedLedgerId = activeLedger.turnId;
106
153
  };
107
154
  const pendingInteraction = () => {
108
155
  for (const policy of policies) {
@@ -111,7 +158,7 @@ async function runAgentLoop({
111
158
  }
112
159
  return null;
113
160
  };
114
- const toolContext = (extra = {}) => ({ workspaceRoot, onToolEvent: typeof onToolEvent === "function" ? event => onToolEvent({ ...event,
161
+ const toolContext = (extra = {}) => ({ workspaceRoot, runtimeHooks, onToolEvent: typeof onToolEvent === "function" ? event => onToolEvent({ ...event,
115
162
  ...(event.origin ? { parentToolCallId: extra.toolCallId } : { toolCallId: extra.toolCallId }) }) : null, sessionId, onArtifactPersisted, executionState, signal,
116
163
  projectId, agentId, taskId, taskRunId, attemptId, requestId, turnId, traceId: traceId || taskId || taskRunId, parentTaskRunId, parentSessionId, artifactNamespace, ...extra });
117
164
  if (onEvent) await event("run.config", { configuration: buildRunObservation({ provider, model: requestModel,
@@ -119,16 +166,17 @@ async function runAgentLoop({
119
166
  tools: tools.toOpenAiTools(), resume, requestKind, engineFingerprint: LOOP_IMPLEMENTATION_FINGERPRINT }) });
120
167
  if (resume) await withFaultPoint("before_provider_resume", () => {});
121
168
 
122
- while (true) {
169
+ try { while (true) {
123
170
  activeGuards.ensureActive();
124
- const turnStop = await policyStop("beforeTurn");
171
+ const turnStop = errorStop ? null : await policyStop("beforeTurn");
125
172
  if (turnStop) return finish(turnStop);
126
- if (usage.turns >= maxRounds) return finish({ stopReason: "budget_exceeded" });
173
+ if (usage.turns >= maxRounds) return finish(errorStop || { stopReason: "budget_exceeded" });
127
174
  turnId = `turn_${randomUUID()}`;
128
175
  providerMessages = messages;
129
- for (const policy of policies) {
176
+ for (const policy of errorStop ? [] : policies) {
130
177
  if (policy.prepareTurn) providerMessages = await policy.prepareTurn({ ...context(), providerMessages }) || providerMessages;
131
178
  }
179
+ const isIsolatedTurn = providerMessages !== messages;
132
180
  isolatedPrefix = providerMessages.length;
133
181
  if (activeLedger) {
134
182
  if (providerTurnGate) providerTurnGate(activeLedger);
@@ -136,26 +184,41 @@ async function runAgentLoop({
136
184
  throw new Error("unresolved tool calls before provider turn");
137
185
  }
138
186
  }
139
- const action = loopGuard.nextAction();
187
+ const action = errorStop ? null : loopGuard.nextAction();
140
188
  if (action) await event(`loop.${action.kind === "stop" ? "stopped" : "warning"}`, { code: "repeated_tool_calls", repeatedSteps: loopGuard.count, toolNames: loopGuard.names });
141
189
  if (action && action.kind === "stop") return finish({ error: action.message, stopReason: "repeated_tool_calls" });
142
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
+ }
143
197
  mirror();
198
+ const requestTools = errorStop ? [] : tools.toOpenAiTools();
144
199
 
145
200
  let maxOutputTokens;
146
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}`);
147
208
  let prepared;
148
209
  try { prepared = await contextManager.prepare({ messages: providerMessages, model: requestModel, systemPrompt, systemBlocks,
149
- tools: tools.toOpenAiTools(), transport, signal, onPhase, onEvent: event,
210
+ tools: requestTools, transport, signal, onPhase, onEvent: event,
150
211
  lastUsage: usage.lastContextTokens, lastEstimate: lastContextEstimate,
151
- force: forceCompaction,
212
+ force: forceCompaction, historyOffset: prepareHistoryOffset, requestKind, turnId: logicalTurnId, resume,
213
+ isolated: isIsolatedTurn,
152
214
  request: { url: requestUrl, apiKey, provider, accountId, requestHeaders, requestProfile, sessionId } }); }
153
215
  catch (error) {
154
216
  // Preflight runs only after tool results are paired. Keep this complete
155
217
  // transcript even when compression is cancelled or storage is broken.
156
- return finish({ error: error.message, stopReason: error.code || "context_compression_failed" });
218
+ return finish(errorStop || { error: error.message, stopReason: error.code || "context_compression_failed" });
157
219
  }
158
220
  providerMessages = prepared.messages;
221
+ isolatedPrefix = providerMessages.length;
159
222
  lastContextEstimate = prepared.estimatedTokens;
160
223
  maxOutputTokens = prepared.maxOutputTokens;
161
224
  forceCompaction = false;
@@ -172,9 +235,10 @@ async function runAgentLoop({
172
235
  let turnResult;
173
236
  let turnError = null;
174
237
  const outputBeforeTurn = aggregated.length;
238
+ let stepStreamedText = false;
175
239
  try { turnResult = await transport.runTurn({
176
240
  url: requestUrl, apiKey, model: requestModel, provider, accountId, requestHeaders, requestProfile, thinkingLevel,
177
- systemPrompt, systemBlocks, messages: providerMessages, tools: tools.toOpenAiTools(),
241
+ systemPrompt, systemBlocks, messages: providerMessages, tools: requestTools,
178
242
  ...(maxOutputTokens ? { maxOutputTokens } : {}),
179
243
  sessionId, signal, timeoutMs,
180
244
  onPhase(phase) {
@@ -188,6 +252,10 @@ async function runAgentLoop({
188
252
  onTextDelta(chunk) {
189
253
  const text = String(chunk || "");
190
254
  if (!text) return;
255
+ if (!stepStreamedText && aggregated && !aggregated.endsWith("\n") && !/^\s/.test(text)) {
256
+ aggregated += "\n\n";
257
+ }
258
+ stepStreamedText = true;
191
259
  aggregated += text;
192
260
  if (onEvent) {
193
261
  streamed = true;
@@ -201,6 +269,7 @@ async function runAgentLoop({
201
269
  }
202
270
  if (turnError) {
203
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 });
204
273
  if (!contextManager || !isContextOverflow(turnError)) throw turnError;
205
274
  if (contextRetry || aggregated.length !== outputBeforeTurn) return finish({ error: turnError.message, stopReason: "context_budget_exceeded" });
206
275
  contextRetry = true;
@@ -219,6 +288,18 @@ async function runAgentLoop({
219
288
  if (typeof onContextUsage === "function") {
220
289
  try { onContextUsage(buildContextMeter({ usedTokens: usage.lastContextTokens, model: requestModel })); } catch { /* observer only */ }
221
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
+ }
222
303
  const calls = transport.getToolCalls(turnResult);
223
304
  if (!calls.length) {
224
305
  loopGuard.reset();
@@ -229,6 +310,7 @@ async function runAgentLoop({
229
310
  await event("model.retry", { code: "empty_response", retry: emptyRetries });
230
311
  providerMessages.push({ role: "user", content: "Continue the current task after the tool results. Call any remaining tools, or provide a concrete final answer to the user. Do not end the turn with an empty response." });
231
312
  mirror();
313
+ await commitConversation();
232
314
  continue;
233
315
  }
234
316
  emptyRetries = 0;
@@ -240,11 +322,14 @@ async function runAgentLoop({
240
322
  const result = await tools.execute(legacy.tool, legacy.args, toolContext({ origin: legacy.origin }));
241
323
  activeGuards.ensureActive();
242
324
  if (result && result.executionState) executionState = result.executionState;
325
+ await recordToolResult(legacy.tool, result);
243
326
  providerMessages.push({ role: "user", content: JSON.stringify({ type: legacy.resultType, ...sanitizeResult(result && result.status ? result : { status: "rejected", ok: false, error: `${legacy.tool} failed` }) }) });
244
327
  mirror();
328
+ await commitConversation();
245
329
  continue;
246
330
  }
247
331
  mirror();
332
+ await commitConversation();
248
333
  if (!aggregated.trim() && text) aggregated = text;
249
334
  let continuation = false;
250
335
  if (autoContinues < maxAutoContinues) {
@@ -266,6 +351,7 @@ async function runAgentLoop({
266
351
  emptyRetries = 0;
267
352
  const pending = transport.prepareToolCalls({ messages: providerMessages, turnResult, toolCalls: calls });
268
353
  if (!pending) { mirror(); return finish(); }
354
+ activePending = pending;
269
355
  loopGuard.observe(pending);
270
356
  activeLedger = ledgerApi.createToolCallLedger({ provider, sessionId, deferableTools: tools.deferableTools() });
271
357
  for (const call of pending) {
@@ -281,18 +367,17 @@ async function runAgentLoop({
281
367
  await withFaultPoint("before_tool_exec", () => {});
282
368
  let batchError = null;
283
369
  for (const policy of policies) if (policy.validateBatch) { batchError = policy.validateBatch(pending); if (batchError) break; }
284
- if (batchError) {
285
- for (const call of pending) {
286
- await event("tool.rejected", { toolCallId: callId(call), toolName: call.name, code: batchError.code || "invalid_batch", argumentFingerprint: observationFingerprint(call.args) });
287
- resolve(call, batchError); toolCallsExecuted += 1; toolErrors += 1;
288
- }
289
- flush(pending);
290
- continue;
291
- }
292
370
  let deferred = null;
293
371
  let toolStop = null;
294
372
  for (const call of pending) {
295
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
+ }
296
381
  const before = toolStop || await policyStop("beforeTool", { call });
297
382
  if (before) {
298
383
  toolStop = before;
@@ -300,11 +385,13 @@ async function runAgentLoop({
300
385
  resolve(call, { ok: false, code: before.stopReason || "stopped", error: "execution stopped before tool invocation" });
301
386
  continue;
302
387
  }
303
- let blocked = null;
304
- 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; }
305
390
  if (blocked) {
306
391
  await event("tool.rejected", { toolCallId: callId(call), toolName: name, code: blocked.code || "tool_not_allowed", argumentFingerprint: observationFingerprint(call.args) });
307
- toolCallsExecuted += 1; toolErrors += 1; resolve(call, blocked); continue;
392
+ resolve(call, blocked);
393
+ await recordToolResult(name, blocked);
394
+ continue;
308
395
  }
309
396
  const resumeCall = tools.deferableTools().includes(name) ? { toolCallId: callId(call), toolName: name, call: { name: call.name, args: call.args, source: call.source } } : null;
310
397
  ledgerApi.markExecuting(activeLedger, callId(call));
@@ -318,10 +405,8 @@ async function runAgentLoop({
318
405
  outcome: "unknown", durationMs: Date.now() - toolStarted });
319
406
  throw error;
320
407
  }
321
- activeGuards.ensureActive();
322
408
  if (result && result.executionState) executionState = result.executionState;
323
- toolCallsExecuted += 1;
324
- if (!result || result.ok === false) toolErrors += 1;
409
+ await recordToolResult(name, result);
325
410
  if (resumeCall && result && result.deferToolResult) {
326
411
  for (const policy of policies) if (policy.onDeferred) policy.onDeferred({ executionState, resume: resumeCall, provider });
327
412
  ledgerApi.deferCall(activeLedger, callId(call), { reason: name });
@@ -331,18 +416,38 @@ async function runAgentLoop({
331
416
  }
332
417
  resolve(call, result);
333
418
  await event("tool.completed", { toolCallId: callId(call), toolName: name, result: sanitizeResult(result), durationMs: Date.now() - toolStarted });
419
+ activeGuards.ensureActive();
334
420
  toolStop = await policyStop("afterTool", { call, result });
335
421
  if (toolStop) continue;
336
422
  if (toolBudget.maxToolCalls != null && toolCallsExecuted >= toolBudget.maxToolCalls) throw new Error(`tool call budget exceeded (${toolBudget.maxToolCalls})`);
337
- if (toolErrors >= (toolBudget.maxToolErrors ?? 20)) {
338
- const detail = [call.name, result && result.error].filter(Boolean).join(": ");
339
- throw new Error(`tool error budget exceeded (${toolBudget.maxToolErrors ?? 20})${detail ? `: ${detail}` : ""}`);
340
- }
341
423
  }
342
424
  flush(pending);
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
+ }
343
431
  if (toolStop) return finish(toolStop);
344
432
  const interaction = pendingInteraction();
345
433
  if (deferred || interaction) return finish({ waitingUserInteraction: true, interactionId: deferred && deferred.interactionId || interaction && interaction.id || "" });
434
+ } } catch (error) {
435
+ if (!error || typeof error !== "object") error = new Error(String(error));
436
+ if (activeLedger && activeLedger.turnId !== flushedLedgerId && activeLedger.turnId !== flushAttemptedLedgerId
437
+ && !ledgerApi.listUnresolved(activeLedger).length && !ledgerApi.listDeferred(activeLedger).length) {
438
+ // Cancellation/budget checks can fail immediately after the last tool
439
+ // returned a known result. That completed batch still belongs in history.
440
+ flush(activePending);
441
+ try { await commitConversation(); }
442
+ catch (persistenceError) { error = persistenceError; }
443
+ }
444
+ // Preserve completed units without exposing a newly declared, interrupted
445
+ // tool batch as a valid continuation transcript. The ledger retains its
446
+ // unresolved/unknown effects for recovery inspection.
447
+ error.result = finish({ error: error.message, stopReason: error.code || "runtime_error",
448
+ messages: clone(messages.slice(0, committedMessages)), turnItems: clone(committedItems),
449
+ protocolLedger: ledgerApi.snapshotLedger(activeLedger) || lastLedger });
450
+ throw error;
346
451
  }
347
452
  }
348
453
 
@@ -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: [{