u-foo 3.1.6 → 4.0.0

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 (193) hide show
  1. package/README.md +172 -13
  2. package/README.zh-CN.md +108 -13
  3. package/SKILLS/ufoo/SKILL.md +15 -3
  4. package/SKILLS/ufoo-bus/SKILL.md +21 -1
  5. package/bin/uclaude.js +4 -0
  6. package/bin/ucodex.js +4 -0
  7. package/bin/ufoo.js +3 -1
  8. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  9. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  10. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  11. package/dist/tui/linux-x64/ufoo-tui +0 -0
  12. package/package.json +10 -3
  13. package/scripts/postinstall-skills.js +53 -0
  14. package/scripts/postinstall.js +11 -16
  15. package/scripts/smoke-native-messages.js +214 -0
  16. package/src/agents/activity/activityStateWriter.js +37 -38
  17. package/src/agents/capabilities/agentManagement/index.js +4 -0
  18. package/src/agents/capabilities/agentManagement/service.js +113 -0
  19. package/src/agents/capabilities/agentRouting/index.js +4 -0
  20. package/src/agents/capabilities/coding/index.js +32 -0
  21. package/src/agents/capabilities/coordination/index.js +37 -0
  22. package/src/agents/capabilities/globalRouting/index.js +5 -0
  23. package/src/agents/capabilities/groups/index.js +3 -0
  24. package/src/agents/capabilities/index.js +25 -0
  25. package/src/agents/capabilities/planning/index.js +123 -0
  26. package/src/agents/capabilities/planning/main.js +28 -0
  27. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  28. package/src/agents/capabilities/scheduling/index.js +3 -0
  29. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  30. package/src/agents/capabilities/skills/index.js +12 -0
  31. package/src/agents/capabilities/taskExecution/index.js +3 -0
  32. package/src/agents/capabilities/taskReports/index.js +6 -0
  33. package/src/agents/controller/controllerToolExecutor.js +6 -4
  34. package/src/agents/controller/loopRuntime.js +85 -221
  35. package/src/agents/controller/ufooAgent.js +1 -0
  36. package/src/agents/internal/internalRunner.js +103 -32
  37. package/src/agents/launch/launcher.js +88 -6
  38. package/src/agents/launch/nativeCapabilities.js +40 -0
  39. package/src/agents/launch/nativeMessages.js +362 -0
  40. package/src/agents/launch/notifier.js +13 -18
  41. package/src/agents/launch/readyDetector.js +26 -12
  42. package/src/agents/profiles/coding.js +6 -0
  43. package/src/agents/profiles/globalRouter.js +2 -0
  44. package/src/agents/profiles/main.js +5 -0
  45. package/src/agents/prompts/groupBootstrap.js +10 -0
  46. package/src/agents/prompts/mainAgent.js +39 -0
  47. package/src/agents/prompts/native/tasks.js +2 -2
  48. package/src/agents/prompts/native/ufoo.js +3 -0
  49. package/src/agents/providers/claudeEventTranslator.js +6 -1
  50. package/src/agents/providers/claudeThreadProvider.js +44 -2
  51. package/src/agents/providers/codexEventTranslator.js +47 -7
  52. package/src/agents/providers/codexThreadProvider.js +3 -2
  53. package/src/agents/providers/controllerJsonTransport.js +28 -0
  54. package/src/agents/providers/credentials/claude.js +10 -3
  55. package/src/agents/providers/nativeTransport.js +1135 -0
  56. package/src/agents/providers/runtimeConfig.js +186 -0
  57. package/src/agents/providers/thinkingLevels.js +132 -0
  58. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  59. package/src/agents/providers/transports/index.js +10 -0
  60. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  61. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  62. package/src/agents/providers/transports/responsesProtocol.js +499 -0
  63. package/src/agents/providers/transports/systemBlocks.js +16 -0
  64. package/src/agents/providers/transports/transportContract.js +50 -0
  65. package/src/agents/providers/transports/visionBlocks.js +151 -0
  66. package/src/agents/providers/upstreamTransport.js +13 -4
  67. package/src/agents/runtime/composeCapabilities.js +89 -0
  68. package/src/agents/runtime/context/commandStore.js +43 -0
  69. package/src/agents/runtime/context/contextWindow.js +119 -0
  70. package/src/agents/runtime/context/fileLock.js +36 -0
  71. package/src/agents/runtime/context/runtimeStore.js +126 -0
  72. package/src/agents/runtime/context/sessionJournal.js +360 -0
  73. package/src/agents/runtime/context/sessionStore.js +57 -0
  74. package/src/agents/runtime/core/agentLoop.js +270 -0
  75. package/src/agents/runtime/core/stableJson.js +29 -0
  76. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  77. package/src/agents/runtime/createAgentRuntime.js +247 -0
  78. package/src/agents/runtime/index.js +14 -0
  79. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  80. package/src/agents/runtime/protocol/materialize.js +107 -0
  81. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  82. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  83. package/src/agents/runtime/tasks/scheduler.js +73 -0
  84. package/src/agents/runtime/tools/registry.js +57 -0
  85. package/src/app/chat/ChatController.js +14 -3
  86. package/src/app/chat/agentDirectory.js +8 -2
  87. package/src/app/chat/commandExecutor.js +36 -46
  88. package/src/app/chat/commands.js +14 -7
  89. package/src/app/chat/daemonConnection.js +58 -5
  90. package/src/app/chat/daemonMessageRouter.js +61 -3
  91. package/src/app/chat/inputSubmitHandler.js +14 -2
  92. package/src/app/chat/launchRequestContext.js +42 -0
  93. package/src/app/chat/multiWindow/paneManager.js +85 -165
  94. package/src/app/chat/streamState.js +3 -3
  95. package/src/app/chat/transport.js +1 -1
  96. package/src/app/cli/busCoreCommands.js +9 -0
  97. package/src/app/cli/features/doctor.js +33 -0
  98. package/src/app/cli/features/skills.js +16 -4
  99. package/src/app/cli/reportCoreCommands.js +37 -0
  100. package/src/app/cli/run.js +40 -39
  101. package/src/code/agent.js +16 -4
  102. package/src/code/context/artifacts.js +12 -11
  103. package/src/code/context/assembler.js +2 -1
  104. package/src/code/context/promptLayers.js +1 -13
  105. package/src/code/context/stableJson.js +2 -27
  106. package/src/code/contextWindow.js +2 -117
  107. package/src/code/conversation/sessionJournal.js +3 -349
  108. package/src/code/internalThread.js +100 -0
  109. package/src/code/nativeRunner.js +36 -2668
  110. package/src/code/protocol/faultHarness.js +2 -88
  111. package/src/code/protocol/materialize.js +2 -105
  112. package/src/code/protocol/toolCallLedger.js +5 -215
  113. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  114. package/src/code/providers/openaiChatTransport.js +2 -114
  115. package/src/code/providers/openaiResponsesTransport.js +2 -117
  116. package/src/code/providers/responsesProtocol.js +2 -497
  117. package/src/code/providers/transportContract.js +2 -48
  118. package/src/code/providers/visionBlocks.js +2 -149
  119. package/src/code/sessionStore.js +24 -96
  120. package/src/code/thinkingLevels.js +1 -130
  121. package/src/code/toolLoopGuard.js +3 -49
  122. package/src/code/tools/artifactRead.js +1 -1
  123. package/src/code/tools/executor.js +373 -0
  124. package/src/code/tools/specs.js +312 -0
  125. package/src/config.js +81 -67
  126. package/src/coordination/bus/deliveryQueue.js +16 -2
  127. package/src/coordination/bus/index.js +2 -6
  128. package/src/coordination/bus/inject.js +13 -5
  129. package/src/coordination/bus/nativeReceipts.js +100 -0
  130. package/src/coordination/bus/queue.js +1 -3
  131. package/src/coordination/bus/utils.js +7 -3
  132. package/src/coordination/history/agentSurface.js +142 -0
  133. package/src/coordination/history/controllerSummary.js +23 -0
  134. package/src/coordination/memory/index.js +5 -21
  135. package/src/coordination/report/store.js +103 -83
  136. package/src/coordination/state/agentsStore.js +57 -3
  137. package/src/coordination/state/fileLock.js +2 -0
  138. package/src/coordination/state/workspaceAccess.js +36 -0
  139. package/src/runtime/contracts/agentMode.js +17 -0
  140. package/src/runtime/contracts/eventContract.js +3 -0
  141. package/src/runtime/contracts/uiProtocol.js +4 -0
  142. package/src/runtime/daemon/agentHost.js +375 -0
  143. package/src/runtime/daemon/busBridge.js +396 -0
  144. package/src/runtime/daemon/claudeChannel.js +159 -0
  145. package/src/runtime/daemon/controlPlaneService.js +27 -17
  146. package/src/runtime/daemon/cronOps.js +25 -17
  147. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  148. package/src/runtime/daemon/executionPaths.js +30 -0
  149. package/src/runtime/daemon/globalDaemon.js +28 -1
  150. package/src/runtime/daemon/groupOrchestrator.js +1 -0
  151. package/src/runtime/daemon/index.js +114 -344
  152. package/src/runtime/daemon/ipcServer.js +32 -10
  153. package/src/runtime/daemon/mcpConfigure.js +113 -20
  154. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  155. package/src/runtime/daemon/mcpServer.js +7 -4
  156. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  157. package/src/runtime/daemon/ops.js +22 -17
  158. package/src/runtime/daemon/promptRequest.js +23 -4
  159. package/src/runtime/daemon/providerSessions.js +67 -33
  160. package/src/runtime/daemon/reportControlBus.js +59 -25
  161. package/src/runtime/daemon/status.js +4 -0
  162. package/src/runtime/privacy/redactor.js +2 -2
  163. package/src/runtime/projects/identity.js +2 -1
  164. package/src/runtime/projects/registry.js +98 -38
  165. package/src/tools/controllerSchemas.js +24 -0
  166. package/src/tools/handlers/dispatchMessage.js +5 -2
  167. package/src/tools/handlers/listAgents.js +3 -1
  168. package/src/tools/handlers/readBusSummary.js +3 -1
  169. package/src/tools/handlers/readProjectRegistry.js +29 -2
  170. package/src/tools/handlers/routeAgent.js +35 -0
  171. package/src/tools/index.js +1 -0
  172. package/src/tools/registry.js +2 -0
  173. package/src/tools/schemaFixtures.js +16 -3
  174. package/src/tools/tier1/routeAgent.js +2 -2
  175. package/src/tools/tier2/runtimeCoordination.js +38 -0
  176. package/src/tools/types.js +2 -0
  177. package/src/ui/agentPresentation.js +109 -0
  178. package/src/ui/agentSurface.js +270 -0
  179. package/src/ui/format/banner.js +8 -11
  180. package/src/ui/format/startupBanner.js +50 -0
  181. package/src/ui/multiPaneBusMirror.js +29 -3
  182. package/src/ui/rustChatHost.js +170 -438
  183. package/src/ui/rustMultiSession.js +225 -51
  184. package/src/ui/rustUcodeHost.js +20 -87
  185. package/src/ui/settingsBridge.js +7 -4
  186. package/src/app/chat/agentEnter.js +0 -70
  187. package/src/app/chat/multiWindow/index.js +0 -310
  188. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  189. package/src/app/chat/multiWindow/renderer.js +0 -420
  190. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  191. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  192. package/src/ui/multiWindowHandoff.js +0 -232
  193. package/src/ui/ptyHandoff.js +0 -23
@@ -0,0 +1,270 @@
1
+ "use strict";
2
+
3
+ const { randomUUID } = require("crypto");
4
+ const ledgerApi = require("../protocol/toolCallLedger");
5
+ const { materializeResolvedToolResults } = require("../protocol/materialize");
6
+ const { withFaultPoint } = require("../protocol/faultHarness");
7
+ const { ToolLoopGuard } = require("./toolLoopGuard");
8
+ const { buildContextMeter, contextTokensFromUsage } = require("../context/contextWindow");
9
+
10
+ const clone = (value) => JSON.parse(JSON.stringify(value));
11
+ const count = (value) => Number.isFinite(Number(value)) && Number(value) > 0 ? Math.floor(Number(value)) : 0;
12
+
13
+ function createExecutionGuards({ signal = null, timeoutMs = 43200000 } = {}) {
14
+ const started = Date.now();
15
+ return { ensureActive() {
16
+ if (signal && signal.aborted) throw Object.assign(new Error("agent cancelled"), { code: "cancelled" });
17
+ if (Date.now() - started > timeoutMs) throw Object.assign(new Error(`agent timeout (${timeoutMs}ms)`), { code: "timeout" });
18
+ } };
19
+ }
20
+
21
+ /** Shared model/tool loop. All business policies and tools are injected. */
22
+ async function runAgentLoop({
23
+ transport, tools, policies = [], workspaceRoot = process.cwd(),
24
+ prompt = "", systemPrompt = "", systemBlocks = null, historyMessages = [],
25
+ model = "", baseUrl = "", apiKey = "", provider = "", accountId = "", requestHeaders = {}, requestProfile = "",
26
+ timeoutMs = 43200000, onStreamDelta = null, onThinkingDelta = null,
27
+ onPhase = null, onToolEvent = null, onArtifactPersisted = null, onContextUsage = null,
28
+ sessionId = "", signal = null, guards = null, executionState: initialState = null,
29
+ resume = false, toolBudget = {}, maxAutoContinues = 24,
30
+ sanitizeMessages = (messages) => messages, retireImages = () => {},
31
+ providerTurnGate = null, maxRounds = Infinity, onEvent = null,
32
+ projectId = "", agentId = "", taskId = "", taskRunId = "", attemptId = "", requestId = "",
33
+ artifactNamespace = "ucode",
34
+ } = {}) {
35
+ const requestModel = String(model || "").trim();
36
+ if (!requestModel) throw new Error("agent model is not configured");
37
+ if (!tools || typeof tools.execute !== "function") throw new Error("agent tool registry is required");
38
+ const requestUrl = transport.resolveUrl(baseUrl);
39
+ if (!requestUrl) throw new Error("agent baseUrl is not configured");
40
+ const signalGuards = createExecutionGuards({ signal, timeoutMs });
41
+ const activeGuards = guards ? { ensureActive() { signalGuards.ensureActive(); guards.ensureActive(); } } : signalGuards;
42
+ const messages = sanitizeMessages(clone(historyMessages));
43
+ if (!resume) transport.prepareMessages({ messages, systemPrompt, prompt });
44
+ const outputStart = messages.length;
45
+ const currentTurnItems = () => clone(messages.slice(outputStart)).filter((message) => (
46
+ String(message.role || "").toLowerCase() !== "user" || Array.isArray(message.content)
47
+ && message.content.some((block) => ["tool_result", "image", "image_url"].includes(block.type))
48
+ ));
49
+ let executionState = initialState;
50
+ for (const policy of policies) if (policy.initializeState) executionState = policy.initializeState(executionState);
51
+ if (!executionState || typeof executionState !== "object") executionState = {};
52
+ const loopGuard = new ToolLoopGuard({ tightTools: tools.tightTools() });
53
+ const usage = { turns: 0, input: 0, output: 0, cacheRead: 0, cacheCreation: 0, lastContextTokens: 0 };
54
+ let aggregated = "";
55
+ let streamed = false;
56
+ let toolCallsExecuted = 0;
57
+ let toolErrors = 0;
58
+ let emptyRetries = 0;
59
+ let activeLedger = null;
60
+ let lastLedger = null;
61
+ let autoContinues = 0;
62
+ let lastContinueKey = "";
63
+ let emptyContinues = 0;
64
+ let providerMessages = messages;
65
+ let isolatedPrefix = 0;
66
+ let turnId = "";
67
+ const context = () => ({ executionState, messages, loopGuard, usage, toolCallsExecuted, toolErrors, turnId });
68
+ const event = async (type, data = {}) => {
69
+ if (onEvent) await onEvent({ type, projectId, agentId, sessionId, taskId, taskRunId, attemptId, requestId, turnId, ...data });
70
+ };
71
+ const policyStop = async (hook, extra = {}) => {
72
+ for (const policy of policies) {
73
+ const stop = policy[hook] && await policy[hook]({ ...context(), ...extra });
74
+ if (stop) return typeof stop === "string" ? { stopReason: stop } : stop;
75
+ }
76
+ return null;
77
+ };
78
+ const sanitizeResult = (result) => policies.reduce((value, policy) => policy.sanitizeResult ? policy.sanitizeResult(value) : value, result);
79
+ const callId = (call) => String(call.source && call.source.id || "");
80
+ const resolve = (call, result) => ledgerApi.resolveCall(activeLedger, callId(call), { result: sanitizeResult(result), isError: !result || result.ok === false });
81
+ const mirror = () => {
82
+ if (providerMessages === messages) return;
83
+ messages.push(...clone(providerMessages.slice(isolatedPrefix)));
84
+ isolatedPrefix = providerMessages.length;
85
+ };
86
+ const finish = (extra = {}) => ({
87
+ text: aggregated, streamed, toolCallsExecuted, messages,
88
+ turnItems: currentTurnItems(), usage, executionState,
89
+ protocolLedger: lastLedger || ledgerApi.snapshotLedger(activeLedger), ...extra,
90
+ });
91
+ const flush = (calls) => {
92
+ const pendingById = Object.fromEntries(calls.map((call) => [callId(call), call]));
93
+ materializeResolvedToolResults(activeLedger, { transport, messages: providerMessages, pendingById });
94
+ mirror();
95
+ lastLedger = ledgerApi.snapshotLedger(activeLedger);
96
+ };
97
+ const pendingInteraction = () => {
98
+ for (const policy of policies) {
99
+ const pending = policy.pendingInteraction && policy.pendingInteraction(executionState);
100
+ if (pending) return pending;
101
+ }
102
+ return null;
103
+ };
104
+ const toolContext = (extra = {}) => ({ workspaceRoot, onToolEvent, sessionId, onArtifactPersisted, executionState, signal,
105
+ projectId, agentId, taskId, taskRunId, attemptId, requestId, turnId, artifactNamespace, ...extra });
106
+ if (resume) await withFaultPoint("before_provider_resume", () => {});
107
+
108
+ while (true) {
109
+ activeGuards.ensureActive();
110
+ const turnStop = await policyStop("beforeTurn");
111
+ if (turnStop) return finish(turnStop);
112
+ if (usage.turns >= maxRounds) return finish({ stopReason: "budget_exceeded" });
113
+ turnId = `turn_${randomUUID()}`;
114
+ providerMessages = messages;
115
+ for (const policy of policies) {
116
+ if (policy.prepareTurn) providerMessages = policy.prepareTurn({ ...context(), providerMessages }) || providerMessages;
117
+ }
118
+ isolatedPrefix = providerMessages.length;
119
+ if (activeLedger) {
120
+ if (providerTurnGate) providerTurnGate(activeLedger);
121
+ else if (ledgerApi.listUnresolved(activeLedger).length || ledgerApi.listDeferred(activeLedger).length) {
122
+ throw new Error("unresolved tool calls before provider turn");
123
+ }
124
+ }
125
+ const action = loopGuard.nextAction();
126
+ if (action && action.kind === "stop") return finish({ error: action.message, stopReason: "repeated_tool_calls" });
127
+ if (action && action.kind === "warn") providerMessages.push({ role: "user", content: action.message });
128
+
129
+ await event("model.started");
130
+ const streamEvents = [];
131
+ let streamEventError = null;
132
+ let turnResult;
133
+ try { turnResult = await transport.runTurn({
134
+ url: requestUrl, apiKey, model: requestModel, provider, accountId, requestHeaders, requestProfile,
135
+ systemPrompt, systemBlocks, messages: providerMessages, tools: tools.toOpenAiTools(),
136
+ sessionId, signal, timeoutMs, onPhase, onThinkingDelta,
137
+ onTextDelta(chunk) {
138
+ const text = String(chunk || "");
139
+ if (!text) return;
140
+ aggregated += text;
141
+ if (onEvent) {
142
+ streamed = true;
143
+ streamEvents.push(event("message.delta", { text }).catch((error) => { streamEventError = streamEventError || error; }));
144
+ }
145
+ if (typeof onStreamDelta === "function") { streamed = true; onStreamDelta(text); }
146
+ },
147
+ }); } finally {
148
+ await Promise.all(streamEvents);
149
+ if (streamEventError) throw streamEventError;
150
+ }
151
+ activeGuards.ensureActive();
152
+ retireImages(providerMessages);
153
+ if (providerMessages !== messages) retireImages(messages);
154
+ usage.turns += 1;
155
+ for (const key of ["input", "output", "cacheRead", "cacheCreation"]) usage[key] += count(turnResult && turnResult.usage && turnResult.usage[key]);
156
+ usage.lastContextTokens = contextTokensFromUsage(turnResult && turnResult.usage);
157
+ await event("model.completed", { usage: turnResult && turnResult.usage || {} });
158
+ if (typeof onContextUsage === "function") {
159
+ try { onContextUsage(buildContextMeter({ usedTokens: usage.lastContextTokens, model: requestModel })); } catch { /* observer only */ }
160
+ }
161
+ const calls = transport.getToolCalls(turnResult);
162
+ if (!calls.length) {
163
+ loopGuard.reset();
164
+ const text = String(turnResult.text || "").trim();
165
+ if (!text && toolCallsExecuted > 0) {
166
+ if (emptyRetries >= 2) throw new Error("model returned an empty response after tool execution");
167
+ emptyRetries += 1;
168
+ 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." });
169
+ mirror();
170
+ continue;
171
+ }
172
+ emptyRetries = 0;
173
+ let legacy = null;
174
+ for (const policy of policies) if (policy.legacyCommand) { legacy = policy.legacyCommand(text); if (legacy) break; }
175
+ transport.appendFinalAssistantMessage({ messages: providerMessages, turnResult });
176
+ if (legacy) {
177
+ activeGuards.ensureActive();
178
+ const result = await tools.execute(legacy.tool, legacy.args, toolContext({ origin: legacy.origin }));
179
+ activeGuards.ensureActive();
180
+ if (result && result.executionState) executionState = result.executionState;
181
+ providerMessages.push({ role: "user", content: JSON.stringify({ type: legacy.resultType, ...sanitizeResult(result && result.status ? result : { status: "rejected", ok: false, error: `${legacy.tool} failed` }) }) });
182
+ mirror();
183
+ continue;
184
+ }
185
+ mirror();
186
+ if (!aggregated.trim() && text) aggregated = text;
187
+ let continuation = false;
188
+ if (autoContinues < maxAutoContinues) {
189
+ for (const policy of policies) {
190
+ const key = policy.continuationKey ? policy.continuationKey(context()) : "continuation";
191
+ if (emptyContinues >= 2 && key && key === lastContinueKey) continue;
192
+ if (policy.continueAfterFinal && policy.continueAfterFinal(context())) {
193
+ autoContinues += 1; emptyContinues += 1; lastContinueKey = key; continuation = true; break;
194
+ }
195
+ }
196
+ }
197
+ if (continuation) continue;
198
+ return finish();
199
+ }
200
+ emptyContinues = 0;
201
+ emptyRetries = 0;
202
+ const pending = transport.prepareToolCalls({ messages: providerMessages, turnResult, toolCalls: calls });
203
+ if (!pending) { mirror(); return finish(); }
204
+ loopGuard.observe(pending);
205
+ activeLedger = ledgerApi.createToolCallLedger({ provider, sessionId, deferableTools: tools.deferableTools() });
206
+ for (const call of pending) {
207
+ if (!call.source) call.source = {};
208
+ if (!call.source.id) call.source.id = `call_${randomUUID()}`;
209
+ }
210
+ if (new Set(pending.map(callId)).size !== pending.length) {
211
+ throw Object.assign(new Error("duplicate tool call IDs in provider turn"), { code: "duplicate_tool_call_id" });
212
+ }
213
+ ledgerApi.declareCalls(activeLedger, pending.map((call) => ({ callId: callId(call), name: String(call.name || "").toLowerCase(), args: call.args })));
214
+ lastLedger = ledgerApi.snapshotLedger(activeLedger);
215
+ await withFaultPoint("after_prepare_tool_calls", () => {});
216
+ await withFaultPoint("before_tool_exec", () => {});
217
+ let batchError = null;
218
+ for (const policy of policies) if (policy.validateBatch) { batchError = policy.validateBatch(pending); if (batchError) break; }
219
+ if (batchError) {
220
+ for (const call of pending) { resolve(call, batchError); toolCallsExecuted += 1; toolErrors += 1; }
221
+ flush(pending);
222
+ continue;
223
+ }
224
+ let deferred = null;
225
+ let toolStop = null;
226
+ for (const call of pending) {
227
+ const name = String(call.name || "").trim().toLowerCase();
228
+ const before = toolStop || await policyStop("beforeTool", { call });
229
+ if (before) {
230
+ toolStop = before;
231
+ resolve(call, { ok: false, code: before.stopReason || "stopped", error: "execution stopped before tool invocation" });
232
+ continue;
233
+ }
234
+ let blocked = null;
235
+ for (const policy of policies) if (policy.validateTool) { blocked = policy.validateTool(name, executionState); if (blocked) break; }
236
+ if (blocked) { toolCallsExecuted += 1; toolErrors += 1; resolve(call, blocked); continue; }
237
+ const resumeCall = tools.deferableTools().includes(name) ? { toolCallId: callId(call), toolName: name, call: { name: call.name, args: call.args, source: call.source } } : null;
238
+ ledgerApi.markExecuting(activeLedger, callId(call));
239
+ activeGuards.ensureActive();
240
+ await event("tool.started", { toolCallId: callId(call), toolName: name, args: call.args });
241
+ const result = await tools.execute(name, call.args, toolContext({ resume: resumeCall, toolCallId: callId(call) }));
242
+ activeGuards.ensureActive();
243
+ if (result && result.executionState) executionState = result.executionState;
244
+ toolCallsExecuted += 1;
245
+ if (!result || result.ok === false) toolErrors += 1;
246
+ if (resumeCall && result && result.deferToolResult) {
247
+ for (const policy of policies) if (policy.onDeferred) policy.onDeferred({ executionState, resume: resumeCall, provider });
248
+ ledgerApi.deferCall(activeLedger, callId(call), { reason: name });
249
+ deferred = { interactionId: result.interactionId || "" };
250
+ await event("interaction.requested", { toolCallId: callId(call), interactionId: deferred.interactionId });
251
+ continue;
252
+ }
253
+ resolve(call, result);
254
+ await event("tool.completed", { toolCallId: callId(call), toolName: name, result: sanitizeResult(result) });
255
+ toolStop = await policyStop("afterTool", { call, result });
256
+ if (toolStop) continue;
257
+ if (toolBudget.maxToolCalls != null && toolCallsExecuted >= toolBudget.maxToolCalls) throw new Error(`tool call budget exceeded (${toolBudget.maxToolCalls})`);
258
+ if (toolErrors >= (toolBudget.maxToolErrors ?? 20)) {
259
+ const detail = [call.name, result && result.error].filter(Boolean).join(": ");
260
+ throw new Error(`tool error budget exceeded (${toolBudget.maxToolErrors ?? 20})${detail ? `: ${detail}` : ""}`);
261
+ }
262
+ }
263
+ flush(pending);
264
+ if (toolStop) return finish(toolStop);
265
+ const interaction = pendingInteraction();
266
+ if (deferred || interaction) return finish({ waitingUserInteraction: true, interactionId: deferred && deferred.interactionId || interaction && interaction.id || "" });
267
+ }
268
+ }
269
+
270
+ module.exports = { runAgentLoop, createExecutionGuards };
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+
3
+ function stableValue(value) {
4
+ if (value === null || typeof value !== "object") return value;
5
+ if (Array.isArray(value)) return value.map((item) => stableValue(item));
6
+ const keys = Object.keys(value).sort();
7
+ const out = Object.create(null);
8
+ for (const key of keys) {
9
+ out[key] = stableValue(value[key]);
10
+ }
11
+ return out;
12
+ }
13
+
14
+ function stableStringify(value) {
15
+ try {
16
+ return JSON.stringify(stableValue(value));
17
+ } catch {
18
+ try {
19
+ return JSON.stringify(value);
20
+ } catch {
21
+ return String(value || "");
22
+ }
23
+ }
24
+ }
25
+
26
+ module.exports = {
27
+ stableValue,
28
+ stableStringify,
29
+ };
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+
3
+ const { createHash } = require("crypto");
4
+ const { stableStringify } = require("./stableJson");
5
+
6
+
7
+ // One observation is a model step, including its complete parallel tool batch.
8
+ // Ignore call IDs, JSON key order, and parallel ordering when comparing steps.
9
+ class ToolLoopGuard {
10
+ constructor({ tightTools = [] } = {}) {
11
+ this.tightTools = new Set(tightTools);
12
+ this.reset();
13
+ }
14
+
15
+ reset() {
16
+ this.signature = "";
17
+ this.count = 0;
18
+ this.warned = false;
19
+ this.names = [];
20
+ this.tight = false;
21
+ }
22
+
23
+ observe(calls) {
24
+ if (!calls.length) return this.reset();
25
+ const parts = calls.map((call) => stableStringify({ name: call.name, args: call.args }));
26
+ const signature = createHash("sha256").update(JSON.stringify(parts.sort())).digest("hex");
27
+ if (signature !== this.signature) this.reset();
28
+ this.signature = signature;
29
+ this.count += 1;
30
+ this.names = [...new Set(calls.map((call) => call.name))].sort();
31
+ this.tight = calls.every((call) => this.tightTools.has(call.name));
32
+ }
33
+
34
+ nextAction() {
35
+ const warnAt = this.tight ? 4 : 8;
36
+ const stopAt = this.tight ? 8 : 12;
37
+ const tools = this.names.join(", ");
38
+ if (this.count >= stopAt) {
39
+ return {
40
+ kind: "stop",
41
+ message: `Stopped repeated tool calls: ${tools} used identical arguments for ${this.count} consecutive model steps after a warning. Change the approach or provide new information to continue.`,
42
+ };
43
+ }
44
+ if (this.count >= warnAt && !this.warned) {
45
+ this.warned = true;
46
+ return {
47
+ kind: "warn",
48
+ message: `You have repeated the same tool batch (${tools}) with identical arguments for ${this.count} consecutive model steps. Stop repeating it and use a different approach. If waiting for a task, use its supported waiting mechanism instead of repeatedly checking. If blocked, explain the blocker to the user. This run will stop at ${stopAt} consecutive identical steps.`,
49
+ };
50
+ }
51
+ return null;
52
+ }
53
+ }
54
+
55
+ module.exports = { ToolLoopGuard };
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+
3
+ const { composeCapabilities } = require("./composeCapabilities");
4
+ const { runAgentLoop } = require("./core/agentLoop");
5
+ const { assertTransport } = require("../providers/transports/transportContract");
6
+ const { randomUUID, createHash } = require("crypto");
7
+ const { createCommandStore } = require("./context/commandStore");
8
+ const { stableStringify } = require("./core/stableJson");
9
+
10
+ const terminal = new Set(["completed", "failed", "cancelled", "interrupted", "waiting_user"]);
11
+ const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error.code !== "ESRCH"; } };
12
+
13
+ /** A host injects persistence and preparation; core owns accepted invocation lifecycle. */
14
+ function createAgentRuntime({ profile, transport, capabilities, host = {}, defaults = {} } = {}) {
15
+ assertTransport(transport);
16
+ const composition = composeCapabilities({ profile, capabilities, host, providerFeatures: transport.features || [] });
17
+ let running = false;
18
+ let closed = false;
19
+ let pumpPromise = null;
20
+ let controller = null;
21
+ let activeTask = "";
22
+ let activeRun = null;
23
+ let runController = null;
24
+ let closePromise = null;
25
+ const ownerId = randomUUID();
26
+ const waiters = new Map();
27
+ const storage = host.sessionStore;
28
+ const store = storage && Object.freeze({ ...storage,
29
+ transaction(mutator) {
30
+ return storage.transaction((state) => {
31
+ const additions = mutator(state) || [];
32
+ const events = [];
33
+ for (const event of additions) {
34
+ events.push(event);
35
+ for (const update of composition.reduceState(state.capabilityState, event)) {
36
+ events.push({ type: "capability.state_committed", ...update });
37
+ state.capabilityState[update.capabilityId] = { version: update.version, value: update.value };
38
+ }
39
+ }
40
+ return events;
41
+ });
42
+ },
43
+ append(event) { return this.transaction(() => [event]); },
44
+ });
45
+ const commandStore = store && createCommandStore(store);
46
+ const requireStore = () => { if (!store) throw new Error("durable runtime requires host.sessionStore"); };
47
+ const notify = () => {
48
+ if (!store) return;
49
+ const state = store.read();
50
+ for (const [id, listeners] of waiters) {
51
+ const task = state.tasks[id];
52
+ if (task && terminal.has(task.status)) { listeners.forEach((resolve) => resolve(task)); waiters.delete(id); }
53
+ }
54
+ };
55
+ if (store) store.transaction((state) => {
56
+ if (state.profile && state.profile !== (profile && profile.id || "custom")) throw new Error("session profile is pinned; use a new session or explicit checkpoint migration");
57
+ if (state.owner && pidAlive(state.owner.pid)) throw Object.assign(new Error("runtime session already owned"), { code: "runtime_busy" });
58
+ const selectedCapabilities = composition.capabilities.map((capability) => capability.id);
59
+ if (state.capabilities && stableStringify(state.capabilities) !== stableStringify(selectedCapabilities)
60
+ && 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");
61
+ return [...Object.values(state.tasks).filter((task) => task.status === "running").map((task) => ({
62
+ type: "task.interrupted", taskRunId: task.taskRunId, error: "owner stopped; inspect effects before resubmitting",
63
+ })), { type: "runtime.opened", owner: { id: ownerId, pid: process.pid, profile: profile && profile.id || "custom", capabilities: selectedCapabilities } }];
64
+ });
65
+ const record = async (event) => {
66
+ const before = store.read();
67
+ const task = before.tasks[event.taskRunId];
68
+ event = { version: 1, projectId: host.projectId || "", agentId: host.agentId || "", sessionId: before.sessionId,
69
+ requestId: task?.request.requestId || "", taskId: task?.request.taskId || event.taskRunId || "", attemptId: task?.attemptId || "", ...event };
70
+ let sequence;
71
+ const snapshot = store.transaction((state) => { sequence = state.sequence + 1; return [event]; });
72
+ const committed = store.events({ after: sequence - 1 }).find((entry) => entry.sequence === sequence);
73
+ notify();
74
+ if (host.eventSink) {
75
+ try { await host.eventSink(committed); }
76
+ catch (error) { if (host.onObserverError) host.onObserverError(error); }
77
+ }
78
+ const proposals = await composition.handleEvent(committed);
79
+ for (let index = 0; index < proposals.length; index += 1) {
80
+ const command = proposals[index];
81
+ if (!host.commandExecutor) throw new Error("host.commandExecutor is required for capability commands");
82
+ if ((command.permissions || []).some((permission) => !(host.grantedPermissions || []).includes(permission))) throw new Error("capability command exceeds host permissions");
83
+ const commandId = `event-${createHash("sha256").update(`${sequence}:${command.capabilityId}:${index}`).digest("hex").slice(0, 32)}`;
84
+ await commandStore.execute({ commandId, kind: command.name, args: command.args }, () => host.commandExecutor(command));
85
+ }
86
+ return snapshot;
87
+ };
88
+ async function pump() {
89
+ while (!closed) {
90
+ const task = Object.values(store.read().tasks).filter((item) => item.status === "queued").sort((a, b) => a.sequence - b.sequence)[0];
91
+ if (!task) return;
92
+ activeTask = task.taskRunId;
93
+ controller = new AbortController();
94
+ const attemptId = `attempt_${randomUUID()}`;
95
+ try {
96
+ const execute = async (signal) => {
97
+ await record({ type: "task.started", taskRunId: activeTask, attemptId });
98
+ const prepared = task.answer !== undefined && task.result && host.resumeRequest
99
+ ? await host.resumeRequest(task, task.answer)
100
+ : host.prepareRequest ? await host.prepareRequest(task.request, task) : { prompt: task.request.text };
101
+ return runtime.run({ ...prepared, requestId: task.request.requestId,
102
+ taskId: task.request.taskId || task.taskRunId, taskRunId: task.taskRunId, attemptId,
103
+ signal, onEvent: record });
104
+ };
105
+ const result = host.taskScheduler
106
+ ? await host.taskScheduler.schedule({ id: task.taskRunId, resourceKey: task.request.resourceKey || "", signal: controller.signal }, execute)
107
+ : await execute(controller.signal);
108
+ if (controller.signal.aborted) throw Object.assign(new Error("agent cancelled"), { code: "cancelled" });
109
+ if (result.error || result.stopReason) throw Object.assign(new Error(result.error || `agent stopped: ${result.stopReason}`), { code: result.stopReason || "runtime_error" });
110
+ await record({ type: result.waitingUserInteraction ? "task.paused" : "task.completed", taskRunId: activeTask, result });
111
+ } catch (error) {
112
+ if (store.read().tasks[activeTask]?.status === "completed") {
113
+ if (host.onError) host.onError(error);
114
+ continue;
115
+ }
116
+ await record({ type: controller.signal.aborted || error.code === "cancelled" ? "task.cancelled" : "task.failed",
117
+ taskRunId: activeTask, error: error.message });
118
+ } finally { activeTask = ""; controller = null; }
119
+ }
120
+ }
121
+ function startPump() {
122
+ if (pumpPromise || closed) return;
123
+ pumpPromise = Promise.resolve().then(pump).catch((error) => {
124
+ if (host.onError) host.onError(error);
125
+ }).finally(() => {
126
+ pumpPromise = null;
127
+ notify();
128
+ if (!closed && Object.values(store.read().tasks).some((task) => task.status === "queued")) startPump();
129
+ });
130
+ }
131
+ const runtime = Object.freeze({
132
+ tools: composition.tools,
133
+ capabilities: composition.capabilities,
134
+ buildContext: composition.buildContext,
135
+ promptSections: composition.promptSections,
136
+ async run(input = {}) {
137
+ if (closed) throw Object.assign(new Error("agent runtime is closed"), { code: "runtime_closed" });
138
+ if (running) throw Object.assign(new Error("agent runtime is already running"), { code: "runtime_busy" });
139
+ running = true;
140
+ runController = new AbortController();
141
+ const externalSignal = input.signal || defaults.signal;
142
+ const forwardAbort = () => runController && runController.abort(externalSignal.reason);
143
+ if (externalSignal) {
144
+ if (externalSignal.aborted) forwardAbort();
145
+ else externalSignal.addEventListener("abort", forwardAbort, { once: true });
146
+ }
147
+ try {
148
+ activeRun = runAgentLoop({
149
+ ...defaults, ...input, transport,
150
+ tools: composition.tools, policies: composition.policies,
151
+ signal: runController.signal,
152
+ });
153
+ return await activeRun;
154
+ } finally {
155
+ running = false;
156
+ activeRun = null;
157
+ runController = null;
158
+ if (externalSignal) externalSignal.removeEventListener("abort", forwardAbort);
159
+ }
160
+ },
161
+ submit(input = {}) {
162
+ requireStore();
163
+ if (closed) throw new Error("agent runtime is closed");
164
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(input.requestId || "")) throw new Error("requestId is required and must be a safe identifier");
165
+ if (typeof input.text !== "string" || !input.text.trim()) throw new Error("request text is required");
166
+ const request = JSON.parse(JSON.stringify(input));
167
+ if (Array.isArray(request.attachments) && !request.attachments.length) delete request.attachments;
168
+ if (request.requestMeta && !Object.keys(request.requestMeta).length) delete request.requestMeta;
169
+ const fingerprint = createHash("sha256").update(stableStringify(request)).digest("hex");
170
+ let id;
171
+ const state = store.transaction((current) => {
172
+ id = Object.prototype.hasOwnProperty.call(current.requests, request.requestId) ? current.requests[request.requestId] : "";
173
+ if (id) {
174
+ if (current.tasks[id].request.fingerprint !== fingerprint) throw Object.assign(new Error("requestId reused with different content"), { code: "request_conflict" });
175
+ return [];
176
+ }
177
+ if (Object.values(current.tasks).filter((task) => task.status === "queued").length >= (host.maxQueuedTasks || 128)) throw Object.assign(new Error("runtime queue is full"), { code: "queue_full" });
178
+ id = `task_${randomUUID()}`;
179
+ return [{ type: "request.accepted", taskRunId: id, request: { ...request, fingerprint } }];
180
+ });
181
+ startPump();
182
+ return { accepted: true, requestId: request.requestId, taskRunId: id, status: state.tasks[id].status, sequence: state.sequence };
183
+ },
184
+ async resume({ interactionId, answer } = {}) {
185
+ requireStore();
186
+ if (closed) throw new Error("agent runtime is closed");
187
+ if (typeof host.resumeRequest !== "function") throw new Error("host.resumeRequest is required for interactions");
188
+ const state = store.read();
189
+ const task = Object.values(state.tasks).find((item) => item.status === "waiting_user" && item.interactionId === interactionId);
190
+ if (!task) {
191
+ const previous = Object.values(state.tasks).find((item) => item.answeredInteractionId === interactionId);
192
+ if (previous && stableStringify(previous.answer) === stableStringify(answer)) return { accepted: true, taskRunId: previous.taskRunId, status: previous.status };
193
+ throw new Error("interaction is not pending or its answer conflicts");
194
+ }
195
+ if (host.validateAnswer) await host.validateAnswer(task, answer);
196
+ store.transaction((current) => {
197
+ if (current.tasks[task.taskRunId].status !== "waiting_user") throw new Error("interaction already answered");
198
+ return [{ type: "interaction.answered", taskRunId: task.taskRunId, interactionId, answer }];
199
+ });
200
+ startPump();
201
+ return { accepted: true, taskRunId: task.taskRunId };
202
+ },
203
+ cancel({ taskRunId, reason = "user_cancel" } = {}) {
204
+ requireStore();
205
+ const task = store.read().tasks[taskRunId];
206
+ if (!task) throw new Error("task not found");
207
+ if (terminal.has(task.status) && task.status !== "waiting_user") return { taskRunId, status: task.status };
208
+ if (activeTask === taskRunId && controller) {
209
+ store.append({ type: "task.cancel_requested", taskRunId, reason });
210
+ controller.abort(reason);
211
+ } else store.append({ type: "task.cancelled", taskRunId, error: reason });
212
+ notify();
213
+ return { taskRunId, status: activeTask === taskRunId ? "cancelling" : "cancelled" };
214
+ },
215
+ snapshot() { return store ? store.read() : { running, closed }; },
216
+ events(input) { requireStore(); return store.events(input); },
217
+ wait(taskRunId) {
218
+ requireStore();
219
+ const task = store.read().tasks[taskRunId];
220
+ if (!task) return Promise.reject(new Error("task not found"));
221
+ if (terminal.has(task.status)) return Promise.resolve(task);
222
+ return new Promise((resolve) => { const listeners = waiters.get(taskRunId) || []; listeners.push(resolve); waiters.set(taskRunId, listeners); });
223
+ },
224
+ async close() {
225
+ if (closePromise) return closePromise;
226
+ closed = true;
227
+ if (controller) controller.abort("runtime_closed");
228
+ if (runController) runController.abort("runtime_closed");
229
+ closePromise = (async () => {
230
+ if (activeRun) await activeRun.catch(() => {});
231
+ if (pumpPromise) await pumpPromise;
232
+ let disposalError;
233
+ for (const capability of composition.capabilities.slice().reverse()) if (capability.dispose) {
234
+ try { await capability.dispose(); } catch (error) { disposalError = disposalError || error; }
235
+ }
236
+ if (store) store.transaction((state) => state.owner && state.owner.id === ownerId ? [{ type: "runtime.closed" }] : []);
237
+ notify();
238
+ if (disposalError) throw disposalError;
239
+ })();
240
+ return closePromise;
241
+ },
242
+ });
243
+ if (store) startPump();
244
+ return runtime;
245
+ }
246
+
247
+ module.exports = { createAgentRuntime };
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+
3
+ module.exports = {
4
+ ...require("./createAgentRuntime"),
5
+ ...require("./composeCapabilities"),
6
+ ...require("./tools/registry"),
7
+ ...require("./core/agentLoop"),
8
+ ...require("./context/sessionJournal"),
9
+ ...require("./context/sessionStore"),
10
+ ...require("./context/runtimeStore"),
11
+ ...require("./context/commandStore"),
12
+ ...require("./tasks/scheduler"),
13
+ ...require("./tasks/resourceLease"),
14
+ };