u-foo 3.1.7 → 4.0.1

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 (266) hide show
  1. package/OBSERVABILITY.md +65 -0
  2. package/README.md +238 -21
  3. package/README.zh-CN.md +165 -20
  4. package/SKILLS/ufoo/SKILL.md +40 -4
  5. package/SKILLS/ufoo-bus/SKILL.md +46 -3
  6. package/bin/uclaude.js +4 -0
  7. package/bin/ucodex.js +4 -0
  8. package/bin/ufoo.js +6 -4
  9. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  10. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  11. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  12. package/dist/tui/linux-x64/ufoo-tui +0 -0
  13. package/package.json +14 -7
  14. package/scripts/postinstall-skills.js +53 -0
  15. package/scripts/postinstall.js +11 -16
  16. package/scripts/smoke-native-messages.js +214 -0
  17. package/src/agents/activity/activityDetector.js +1 -1
  18. package/src/agents/activity/activityStateWriter.js +37 -38
  19. package/src/agents/capabilities/agentManagement/index.js +4 -0
  20. package/src/agents/capabilities/agentManagement/service.js +140 -0
  21. package/src/agents/capabilities/agentRouting/index.js +4 -0
  22. package/src/agents/capabilities/coding/index.js +32 -0
  23. package/src/agents/capabilities/coordination/index.js +37 -0
  24. package/src/agents/capabilities/globalRouting/index.js +5 -0
  25. package/src/agents/capabilities/groups/index.js +3 -0
  26. package/src/agents/capabilities/index.js +25 -0
  27. package/src/agents/capabilities/planning/index.js +123 -0
  28. package/src/agents/capabilities/planning/main.js +28 -0
  29. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  30. package/src/agents/capabilities/scheduling/index.js +3 -0
  31. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  32. package/src/agents/capabilities/skills/index.js +12 -0
  33. package/src/agents/capabilities/taskExecution/index.js +3 -0
  34. package/src/agents/capabilities/taskReports/index.js +6 -0
  35. package/src/agents/controller/controllerToolExecutor.js +40 -22
  36. package/src/agents/controller/index.js +1 -6
  37. package/src/agents/internal/internalRunner.js +181 -76
  38. package/src/agents/launch/index.js +0 -1
  39. package/src/agents/launch/launcher.js +96 -14
  40. package/src/agents/launch/nativeCapabilities.js +40 -0
  41. package/src/agents/launch/nativeMessages.js +362 -0
  42. package/src/agents/launch/notifier.js +15 -20
  43. package/src/agents/launch/readyDetector.js +28 -14
  44. package/src/agents/profiles/coding.js +6 -0
  45. package/src/agents/profiles/globalRouter.js +2 -0
  46. package/src/agents/profiles/main.js +5 -0
  47. package/src/agents/prompts/cooperation.js +14 -0
  48. package/src/agents/prompts/defaultBootstrap.js +1 -1
  49. package/src/agents/prompts/groupBootstrap.js +32 -6
  50. package/src/agents/prompts/mainAgent.js +48 -0
  51. package/src/agents/prompts/native/system.js +4 -1
  52. package/src/agents/prompts/native/tasks.js +2 -2
  53. package/src/agents/prompts/native/ufoo.js +14 -3
  54. package/src/agents/prompts/promptProfiles.js +2 -0
  55. package/src/agents/prompts/reporting.js +16 -0
  56. package/src/agents/providers/claudeEventTranslator.js +9 -1
  57. package/src/agents/providers/claudeThreadProvider.js +47 -4
  58. package/src/agents/providers/clientIdentity.js +75 -0
  59. package/src/agents/providers/codexEventTranslator.js +68 -7
  60. package/src/agents/providers/codexThreadProvider.js +18 -8
  61. package/src/agents/providers/credentials/claude.js +10 -3
  62. package/src/agents/providers/credentials/index.js +2 -0
  63. package/src/agents/providers/directAuthStatus.js +1 -1
  64. package/src/agents/providers/index.js +1 -1
  65. package/src/agents/providers/modelSettings.js +34 -0
  66. package/src/agents/providers/modelsCatalog.js +379 -0
  67. package/src/agents/providers/nativeTransport.js +1146 -0
  68. package/src/agents/providers/runtimeConfig.js +188 -0
  69. package/src/agents/providers/thinkingLevels.js +106 -0
  70. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  71. package/src/agents/providers/transports/index.js +10 -0
  72. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  73. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  74. package/src/agents/providers/transports/responsesProtocol.js +504 -0
  75. package/src/agents/providers/transports/systemBlocks.js +16 -0
  76. package/src/agents/providers/transports/transportContract.js +50 -0
  77. package/src/agents/providers/transports/visionBlocks.js +151 -0
  78. package/src/agents/providers/upstreamRuntime.js +135 -0
  79. package/src/agents/runtime/composeCapabilities.js +89 -0
  80. package/src/agents/runtime/context/checkpointStore.js +38 -0
  81. package/src/agents/runtime/context/commandStore.js +43 -0
  82. package/src/agents/runtime/context/compaction.js +151 -0
  83. package/src/agents/runtime/context/contextBudget.js +93 -0
  84. package/src/agents/runtime/context/contextWindow.js +119 -0
  85. package/src/agents/runtime/context/fileLock.js +36 -0
  86. package/src/agents/runtime/context/replayHistory.js +28 -0
  87. package/src/agents/runtime/context/runtimeStore.js +127 -0
  88. package/src/agents/runtime/context/sessionJournal.js +360 -0
  89. package/src/agents/runtime/context/sessionStore.js +57 -0
  90. package/src/agents/runtime/core/agentLoop.js +351 -0
  91. package/src/agents/runtime/core/executionBudget.js +36 -0
  92. package/src/agents/runtime/core/stableJson.js +29 -0
  93. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  94. package/src/agents/runtime/createAgentRuntime.js +259 -0
  95. package/src/agents/runtime/index.js +14 -0
  96. package/src/agents/runtime/prompts/responseLanguage.js +12 -0
  97. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  98. package/src/agents/runtime/protocol/materialize.js +107 -0
  99. package/src/agents/runtime/protocol/runObservation.js +24 -0
  100. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  101. package/src/agents/runtime/protocol/traceContext.js +9 -0
  102. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  103. package/src/agents/runtime/tasks/scheduler.js +73 -0
  104. package/src/agents/runtime/tools/registry.js +57 -0
  105. package/src/app/chat/ChatController.js +29 -45
  106. package/src/app/chat/agentDirectory.js +9 -18
  107. package/src/app/chat/bootstrap.js +1 -2
  108. package/src/app/chat/commandExecutor.js +111 -313
  109. package/src/app/chat/commands.js +39 -45
  110. package/src/app/chat/daemonConnection.js +58 -5
  111. package/src/app/chat/daemonMessageRouter.js +61 -48
  112. package/src/app/chat/historyStore.js +12 -48
  113. package/src/app/chat/inputSubmitHandler.js +21 -35
  114. package/src/app/chat/internalAgentLogHistory.js +19 -60
  115. package/src/app/chat/launchRequestContext.js +42 -0
  116. package/src/app/chat/multiWindow/paneManager.js +91 -164
  117. package/src/app/chat/streamState.js +3 -7
  118. package/src/app/chat/transport.js +1 -1
  119. package/src/app/cli/busCoreCommands.js +9 -0
  120. package/src/app/cli/features/doctor.js +33 -0
  121. package/src/app/cli/features/init.js +5 -5
  122. package/src/app/cli/features/skills.js +16 -4
  123. package/src/app/cli/metricsCommands.js +68 -0
  124. package/src/app/cli/reportCoreCommands.js +37 -0
  125. package/src/app/cli/run.js +82 -42
  126. package/src/app/cli/traceCommands.js +36 -0
  127. package/src/code/agent.js +34 -17
  128. package/src/code/busConsumer.js +1 -3
  129. package/src/code/commands.js +1 -1
  130. package/src/code/context/artifacts.js +12 -11
  131. package/src/code/context/assembler.js +9 -9
  132. package/src/code/context/promptLayers.js +1 -13
  133. package/src/code/context/stableJson.js +2 -27
  134. package/src/code/context/stateCommit.js +2 -1
  135. package/src/code/contextWindow.js +2 -117
  136. package/src/code/conversation/sessionJournal.js +3 -349
  137. package/src/code/internalThread.js +107 -0
  138. package/src/code/launcher/ucode.js +1 -1
  139. package/src/code/launcher/ucodeBootstrap.js +1 -1
  140. package/src/code/modelCommand.js +11 -35
  141. package/src/code/nativeRunner.js +104 -2697
  142. package/src/code/protocol/faultHarness.js +2 -88
  143. package/src/code/protocol/materialize.js +2 -105
  144. package/src/code/protocol/toolCallLedger.js +5 -215
  145. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  146. package/src/code/providers/modelsCatalog.js +1 -317
  147. package/src/code/providers/openaiChatTransport.js +2 -114
  148. package/src/code/providers/openaiResponsesTransport.js +2 -117
  149. package/src/code/providers/responsesProtocol.js +2 -497
  150. package/src/code/providers/transportContract.js +2 -48
  151. package/src/code/providers/visionBlocks.js +2 -149
  152. package/src/code/repl.js +2 -11
  153. package/src/code/sessionStore.js +27 -99
  154. package/src/code/taskDecomposer.js +18 -0
  155. package/src/code/thinkingLevels.js +1 -130
  156. package/src/code/toolBudget.js +1 -17
  157. package/src/code/toolLoopGuard.js +3 -49
  158. package/src/code/tools/artifactRead.js +1 -1
  159. package/src/code/tools/executor.js +373 -0
  160. package/src/code/tools/specs.js +312 -0
  161. package/src/config.js +95 -131
  162. package/src/coordination/bus/deliveryQueue.js +16 -2
  163. package/src/coordination/bus/index.js +14 -9
  164. package/src/coordination/bus/inject.js +15 -7
  165. package/src/coordination/bus/message.js +15 -1
  166. package/src/coordination/bus/nativeReceipts.js +100 -0
  167. package/src/coordination/bus/nickname.js +1 -1
  168. package/src/coordination/bus/queue.js +1 -3
  169. package/src/coordination/bus/subscriber.js +3 -2
  170. package/src/coordination/bus/utils.js +8 -4
  171. package/src/coordination/history/agentPerformance.js +279 -0
  172. package/src/coordination/history/agentSurface.js +142 -0
  173. package/src/coordination/history/agentTrace.js +249 -0
  174. package/src/coordination/memory/index.js +5 -21
  175. package/src/coordination/report/store.js +103 -83
  176. package/src/coordination/state/agentsStore.js +57 -3
  177. package/src/coordination/state/fileLock.js +2 -0
  178. package/src/coordination/state/workspaceAccess.js +36 -0
  179. package/src/orchestration/controller/index.js +1 -8
  180. package/src/orchestration/controller/launchRouting.js +1 -1
  181. package/src/orchestration/solo/commands.js +3 -1
  182. package/src/runtime/contracts/agentMode.js +26 -0
  183. package/src/runtime/contracts/eventContract.js +3 -0
  184. package/src/runtime/contracts/uiProtocol.js +20 -17
  185. package/src/runtime/daemon/agentHost.js +407 -0
  186. package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
  187. package/src/runtime/daemon/busBridge.js +396 -0
  188. package/src/runtime/daemon/claudeChannel.js +159 -0
  189. package/src/runtime/daemon/controlPlaneService.js +28 -18
  190. package/src/runtime/daemon/cronOps.js +25 -17
  191. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  192. package/src/runtime/daemon/globalDaemon.js +28 -1
  193. package/src/runtime/daemon/groupOrchestrator.js +21 -5
  194. package/src/runtime/daemon/groupStatus.js +20 -0
  195. package/src/runtime/daemon/index.js +120 -375
  196. package/src/runtime/daemon/ipcServer.js +32 -10
  197. package/src/runtime/daemon/mcpConfigure.js +113 -20
  198. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  199. package/src/runtime/daemon/mcpServer.js +8 -5
  200. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  201. package/src/runtime/daemon/nicknameScope.js +1 -1
  202. package/src/runtime/daemon/ops.js +68 -40
  203. package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
  204. package/src/runtime/daemon/promptRequest.js +92 -570
  205. package/src/runtime/daemon/providerSessions.js +67 -33
  206. package/src/runtime/daemon/reportControlBus.js +59 -25
  207. package/src/runtime/daemon/status.js +9 -6
  208. package/src/runtime/privacy/redactor.js +2 -2
  209. package/src/runtime/projects/identity.js +2 -1
  210. package/src/runtime/projects/registry.js +98 -38
  211. package/src/tools/controllerSchemas.js +28 -0
  212. package/src/tools/handlers/dispatchMessage.js +5 -2
  213. package/src/tools/handlers/listAgents.js +3 -1
  214. package/src/tools/handlers/readBusSummary.js +3 -1
  215. package/src/tools/handlers/readProjectRegistry.js +29 -2
  216. package/src/tools/handlers/routeAgent.js +35 -0
  217. package/src/tools/handlers/tier2.js +4 -2
  218. package/src/tools/index.js +1 -0
  219. package/src/tools/registry.js +6 -0
  220. package/src/tools/schemaFixtures.js +42 -5
  221. package/src/tools/tier0/readAgentMetrics.js +14 -0
  222. package/src/tools/tier0/readAgentTrace.js +12 -0
  223. package/src/tools/tier1/routeAgent.js +2 -2
  224. package/src/tools/tier2/runtimeCoordination.js +38 -0
  225. package/src/tools/types.js +2 -0
  226. package/src/ui/agentPresentation.js +109 -0
  227. package/src/ui/agentSettingsController.js +107 -0
  228. package/src/ui/agentSurface.js +270 -0
  229. package/src/ui/dashboardBridge.js +1 -1
  230. package/src/ui/format/banner.js +9 -15
  231. package/src/ui/format/index.js +14 -10
  232. package/src/ui/format/loopSummary.js +50 -0
  233. package/src/ui/format/markdownRenderer.js +3 -4
  234. package/src/ui/format/startupBanner.js +50 -0
  235. package/src/ui/multiPaneBusMirror.js +29 -3
  236. package/src/ui/rustChatHost.js +316 -599
  237. package/src/ui/rustMultiSession.js +288 -73
  238. package/src/ui/rustUcodeHost.js +21 -88
  239. package/src/ui/settingsBridge.js +34 -14
  240. package/src/ui/toolMergeBridge.js +0 -4
  241. package/src/ui/uiHostServer.js +5 -8
  242. package/src/agents/controller/loopObservability.js +0 -200
  243. package/src/agents/controller/loopRuntime.js +0 -472
  244. package/src/agents/controller/ufooAgent.js +0 -829
  245. package/src/agents/launch/ptyRunner.js +0 -1135
  246. package/src/agents/providers/upstreamTransport.js +0 -689
  247. package/src/app/chat/agentBar.js +0 -135
  248. package/src/app/chat/agentEnter.js +0 -70
  249. package/src/app/chat/agentSockets.js +0 -225
  250. package/src/app/chat/dashboardView.js +0 -405
  251. package/src/app/chat/multiWindow/index.js +0 -310
  252. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  253. package/src/app/chat/multiWindow/renderer.js +0 -420
  254. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  255. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  256. package/src/app/chat/rawKeyMap.js +0 -42
  257. package/src/app/chat/settingsController.js +0 -111
  258. package/src/orchestration/controller/flags.js +0 -167
  259. package/src/orchestration/controller/gateRouter.js +0 -211
  260. package/src/orchestration/controller/routerFastPath.js +0 -22
  261. package/src/orchestration/controller/routerFinalize.js +0 -222
  262. package/src/orchestration/controller/shadowGuard.js +0 -280
  263. package/src/runtime/daemon/promptLoop.js +0 -136
  264. package/src/runtime/privacy/shadowDiff.js +0 -174
  265. package/src/ui/multiWindowHandoff.js +0 -232
  266. package/src/ui/ptyHandoff.js +0 -23
@@ -0,0 +1,373 @@
1
+ "use strict";
2
+
3
+ const dispatchTools = require("../dispatch");
4
+ const runToolCall = dispatchTools.runToolCall;
5
+ const runToolCallAsync = typeof dispatchTools.runToolCallAsync === "function"
6
+ ? dispatchTools.runToolCallAsync : async (...args) => runToolCall(...args);
7
+ const { runTaskRunTool } = require("./taskRun");
8
+ const { persistToolResultToContext } = require("../context/assembler");
9
+ const { emptyExecutionState } = require("../context/executionSegment");
10
+ const { runPlanGraphCommand } = require("../context/planGraphService");
11
+ const { runAskUserTool, syncInteractionFromPlanGraph } = require("../context/userInteraction");
12
+ const fs = require("fs");
13
+ const path = require("path");
14
+ const { createResourceLease } = require("../../agents/runtime/tasks/resourceLease");
15
+ function writerLease(options) {
16
+ const workspaceRoot = fs.realpathSync(options.workspaceRoot || process.cwd());
17
+ return { lease: createResourceLease({ file: path.join(workspaceRoot, ".ufoo", "agent", "runtime", "workspace-leases.json") }),
18
+ key: workspaceRoot, ownerId: options.taskRunId || options.sessionId || `process-${process.pid}` };
19
+ }
20
+ function runCoreTool(options = {}) {
21
+ if (!["write", "edit", "bash"].includes(normalizeToolName(options.tool))) return runCoreToolUnlocked(options);
22
+ const { lease, key, ownerId } = writerLease(options);
23
+ const acquired = lease.acquire({ key, ownerId });
24
+ if (!acquired.ok) return { ...acquired, error: "workspace writer is active" };
25
+ try { return runCoreToolUnlocked(options); }
26
+ finally { if (!acquired.reentrant) lease.release({ key, token: acquired.token }); }
27
+ }
28
+
29
+ const CORE_TOOL_NAMES = new Set([
30
+ "read",
31
+ "read_image",
32
+ "write",
33
+ "edit",
34
+ "bash",
35
+ "artifact_read",
36
+ "plan_graph",
37
+ "task_run",
38
+ "ask_user",
39
+ ]);
40
+ const EXECUTABLE_GRAPH_TOOLS = new Set([
41
+ "read",
42
+ "read_image",
43
+ "write",
44
+ "edit",
45
+ "bash",
46
+ "artifact_read",
47
+ ]);
48
+ const CONTROL_PLANE_TOOLS = new Set(["plan_graph", "task_run"]);
49
+ function normalizeToolName(value = "") {
50
+ const name = String(value || "").trim().toLowerCase();
51
+ if (!CORE_TOOL_NAMES.has(name)) return "";
52
+ return name;
53
+ }
54
+
55
+ function emitToolEvent(callback, event = {}) {
56
+ if (typeof callback !== "function") return;
57
+ try {
58
+ const payload = event && typeof event === "object" ? { ...event } : {};
59
+ if (payload.origin == null) delete payload.origin;
60
+ callback(payload);
61
+ } catch {
62
+ // ignore callback failures
63
+ }
64
+ }
65
+
66
+ function runCoreToolUnlocked({
67
+ tool = "",
68
+ args = {},
69
+ workspaceRoot = process.cwd(),
70
+ onToolEvent = null,
71
+ sessionId = "",
72
+ onArtifactPersisted = null,
73
+ executionState = null,
74
+ origin = null,
75
+ resume = null,
76
+ artifactNamespace = "ucode",
77
+ } = {}) {
78
+ const normalizedTool = normalizeToolName(tool);
79
+ if (!normalizedTool) {
80
+ emitToolEvent(onToolEvent, {
81
+ tool: String(tool || "unknown"),
82
+ phase: "error",
83
+ args: args && typeof args === "object" ? { ...args } : {},
84
+ error: `unsupported tool: ${tool}`,
85
+ origin,
86
+ });
87
+ return {
88
+ ok: false,
89
+ error: `unsupported tool: ${tool}`,
90
+ };
91
+ }
92
+
93
+ const safeArgs = args && typeof args === "object" ? { ...args } : {};
94
+ if (normalizedTool === "artifact_read" && sessionId && !safeArgs.sessionId) {
95
+ safeArgs.sessionId = sessionId;
96
+ }
97
+ emitToolEvent(onToolEvent, {
98
+ tool: normalizedTool,
99
+ phase: "start",
100
+ args: safeArgs,
101
+ error: "",
102
+ origin,
103
+ });
104
+
105
+ if (normalizedTool === "plan_graph") {
106
+ const state = executionState && typeof executionState === "object"
107
+ ? executionState
108
+ : emptyExecutionState();
109
+ const result = runPlanGraphCommand(safeArgs, {
110
+ executionState: state,
111
+ autoAdvance: true,
112
+ parallel: true,
113
+ runTool: ({ node, args: nestedArgs, tool: nestedTool, stepId }) => {
114
+ const nested = runCoreTool({
115
+ tool: nestedTool,
116
+ args: nestedArgs,
117
+ workspaceRoot,
118
+ onToolEvent,
119
+ sessionId,
120
+ onArtifactPersisted,
121
+ executionState: state,
122
+ origin: {
123
+ kind: "plan_graph",
124
+ graphId: String(state.planGraph && state.planGraph.graphId || ""),
125
+ graphRevision: Number(state.planGraph && state.planGraph.specRevision) || 0,
126
+ commandRevision: Number(state.planGraph && state.planGraph.specRevision) || 0,
127
+ nodeId: stepId || (node && node.id) || "",
128
+ attempt: Number(node && node.attempt) || 0,
129
+ },
130
+ });
131
+ return nested;
132
+ },
133
+ });
134
+ if (result.ok === false) {
135
+ emitToolEvent(onToolEvent, {
136
+ tool: "plan_graph",
137
+ phase: "error",
138
+ args: safeArgs,
139
+ error: Array.isArray(result.errors)
140
+ ? result.errors.map((e) => e.message || e.code).join("; ")
141
+ : "plan_graph rejected",
142
+ origin,
143
+ });
144
+ } else {
145
+ syncInteractionFromPlanGraph(result.executionState || state);
146
+ }
147
+ return {
148
+ ...result.modelPayload,
149
+ ok: result.status === "accepted",
150
+ // Keep executionState for the runner only; sanitizeToolResultForModel
151
+ // strips it before the payload enters provider messages.
152
+ executionState: result.executionState || state,
153
+ };
154
+ }
155
+
156
+ if (normalizedTool === "task_run") {
157
+ const state = executionState && typeof executionState === "object"
158
+ ? executionState
159
+ : emptyExecutionState();
160
+ const result = runTaskRunTool(safeArgs, {
161
+ executionState: state,
162
+ runTool: ({ node, args: nestedArgs, tool: nestedTool, stepId }) => {
163
+ const nested = runCoreTool({
164
+ tool: nestedTool,
165
+ args: nestedArgs,
166
+ workspaceRoot,
167
+ onToolEvent,
168
+ sessionId,
169
+ onArtifactPersisted,
170
+ executionState: state,
171
+ origin: {
172
+ kind: "task_run",
173
+ taskRunId: String(safeArgs.taskRunId || ""),
174
+ nodeId: stepId || (node && node.id) || "",
175
+ attempt: Number(node && node.attempt) || 0,
176
+ },
177
+ });
178
+ return nested;
179
+ },
180
+ });
181
+ const ok = result.ok !== false && result.status !== "rejected";
182
+ emitToolEvent(onToolEvent, {
183
+ tool: "task_run",
184
+ phase: ok ? "end" : "error",
185
+ args: safeArgs,
186
+ result,
187
+ error: ok
188
+ ? ""
189
+ : (Array.isArray(result.errors)
190
+ ? result.errors.map((e) => e.message || e.code).join("; ")
191
+ : (result.error || "task_run rejected")),
192
+ origin,
193
+ });
194
+ return {
195
+ ...result,
196
+ ok,
197
+ executionState: result.executionState || state,
198
+ };
199
+ }
200
+
201
+ if (normalizedTool === "ask_user") {
202
+ const state = executionState && typeof executionState === "object"
203
+ ? executionState
204
+ : emptyExecutionState();
205
+ const result = runAskUserTool(safeArgs, {
206
+ executionState: state,
207
+ resume: resume || null,
208
+ });
209
+ const ok = result.ok !== false && result.status !== "rejected";
210
+ emitToolEvent(onToolEvent, {
211
+ tool: "ask_user",
212
+ phase: ok ? "end" : "error",
213
+ args: safeArgs,
214
+ result: result.modelPayload || result,
215
+ error: ok ? "" : (result.error || "ask_user rejected"),
216
+ origin,
217
+ });
218
+ return {
219
+ ...(result.modelPayload || result),
220
+ ok,
221
+ status: result.status,
222
+ waiting_user: Boolean(result.waiting_user || result.status === "waiting_user"),
223
+ interactionId: result.interactionId || "",
224
+ executionState: result.executionState || state,
225
+ deferToolResult: ok && result.status === "waiting_user",
226
+ };
227
+ }
228
+
229
+ const toolOptions = { workspaceRoot, cwd: workspaceRoot };
230
+ if (artifactNamespace !== "ucode") toolOptions.artifactNamespace = artifactNamespace;
231
+ if (normalizedTool === "artifact_read" && sessionId) {
232
+ toolOptions.sessionId = sessionId;
233
+ }
234
+ const result = runToolCall(
235
+ { tool: normalizedTool, args: safeArgs },
236
+ toolOptions,
237
+ );
238
+
239
+ if (!result || result.ok === false) {
240
+ emitToolEvent(onToolEvent, {
241
+ tool: normalizedTool,
242
+ phase: "error",
243
+ args: safeArgs,
244
+ error: String((result && result.error) || `${normalizedTool} failed`),
245
+ origin,
246
+ });
247
+ return result;
248
+ }
249
+
250
+ emitToolEvent(onToolEvent, { tool: normalizedTool, phase: "end", args: safeArgs, result, error: "", origin });
251
+
252
+ if (normalizedTool !== "artifact_read" && EXECUTABLE_GRAPH_TOOLS.has(normalizedTool)) {
253
+ const persisted = persistToolResultToContext({
254
+ workspaceRoot,
255
+ sessionId,
256
+ tool: normalizedTool,
257
+ args: safeArgs,
258
+ rawResult: result,
259
+ artifactNamespace,
260
+ });
261
+ if (typeof onArtifactPersisted === "function") {
262
+ try {
263
+ onArtifactPersisted(persisted);
264
+ } catch {
265
+ // ignore
266
+ }
267
+ }
268
+ const payload = persisted.modelPayload || result;
269
+ if (origin) payload.origin = origin;
270
+ return payload;
271
+ }
272
+
273
+ if (origin && result && typeof result === "object") {
274
+ return { ...result, origin };
275
+ }
276
+ return result;
277
+ }
278
+
279
+ /**
280
+ * Async companion for the native loop. Control-plane tools intentionally keep
281
+ * their synchronous scheduler for now; data-plane tools use the async
282
+ * dispatcher so bash can terminate on the caller's AbortSignal.
283
+ */
284
+ async function runCoreToolAsync(options = {}) {
285
+ if (["write", "edit", "bash"].includes(normalizeToolName(options.tool))) {
286
+ const { lease, key, ownerId } = writerLease(options);
287
+ return lease.run({ key, ownerId, signal: options.signal }, () => runCoreToolAsyncUnlocked(options));
288
+ }
289
+ return runCoreToolAsyncUnlocked(options);
290
+ }
291
+ async function runCoreToolAsyncUnlocked(options = {}) {
292
+ const normalizedTool = normalizeToolName(options.tool);
293
+ if (!normalizedTool || CONTROL_PLANE_TOOLS.has(normalizedTool) || normalizedTool === "ask_user") {
294
+ return runCoreTool(options);
295
+ }
296
+
297
+ const {
298
+ args = {},
299
+ workspaceRoot = process.cwd(),
300
+ onToolEvent = null,
301
+ sessionId = "",
302
+ onArtifactPersisted = null,
303
+ origin = null,
304
+ signal = null,
305
+ artifactNamespace = "ucode",
306
+ } = options;
307
+ const safeArgs = args && typeof args === "object" ? { ...args } : {};
308
+ if (normalizedTool === "artifact_read" && sessionId && !safeArgs.sessionId) {
309
+ safeArgs.sessionId = sessionId;
310
+ }
311
+ emitToolEvent(onToolEvent, {
312
+ tool: normalizedTool,
313
+ phase: "start",
314
+ args: safeArgs,
315
+ error: "",
316
+ origin,
317
+ });
318
+
319
+ const toolOptions = {
320
+ workspaceRoot,
321
+ cwd: workspaceRoot,
322
+ };
323
+ if (artifactNamespace !== "ucode") toolOptions.artifactNamespace = artifactNamespace;
324
+ if (signal) toolOptions.signal = signal;
325
+ if (normalizedTool === "artifact_read" && sessionId) {
326
+ toolOptions.sessionId = sessionId;
327
+ }
328
+ const result = await runToolCallAsync(
329
+ { tool: normalizedTool, args: safeArgs },
330
+ toolOptions,
331
+ );
332
+
333
+ if (!result || result.ok === false) {
334
+ emitToolEvent(onToolEvent, {
335
+ tool: normalizedTool,
336
+ phase: "error",
337
+ args: safeArgs,
338
+ error: String((result && result.error) || `${normalizedTool} failed`),
339
+ origin,
340
+ });
341
+ return result;
342
+ }
343
+
344
+ emitToolEvent(onToolEvent, { tool: normalizedTool, phase: "end", args: safeArgs, result, error: "", origin });
345
+
346
+ if (normalizedTool !== "artifact_read" && EXECUTABLE_GRAPH_TOOLS.has(normalizedTool)) {
347
+ const persisted = persistToolResultToContext({
348
+ workspaceRoot,
349
+ sessionId,
350
+ tool: normalizedTool,
351
+ args: safeArgs,
352
+ rawResult: result,
353
+ artifactNamespace,
354
+ });
355
+ if (typeof onArtifactPersisted === "function") {
356
+ try {
357
+ onArtifactPersisted(persisted);
358
+ } catch {
359
+ // ignore
360
+ }
361
+ }
362
+ const payload = persisted.modelPayload || result;
363
+ if (origin) payload.origin = origin;
364
+ return payload;
365
+ }
366
+
367
+ if (origin && result && typeof result === "object") {
368
+ return { ...result, origin };
369
+ }
370
+ return result;
371
+ }
372
+
373
+ module.exports = { runCoreTool, runCoreToolAsync };
@@ -0,0 +1,312 @@
1
+ "use strict";
2
+
3
+ const { getReadToolDescription } = require("../../agents/prompts/native/toolDescriptions/read");
4
+ const { getReadImageToolDescription } = require("../../agents/prompts/native/toolDescriptions/readImage");
5
+ const { getWriteToolDescription } = require("../../agents/prompts/native/toolDescriptions/write");
6
+ const { getEditToolDescription } = require("../../agents/prompts/native/toolDescriptions/edit");
7
+ const { getBashToolDescription } = require("../../agents/prompts/native/toolDescriptions/bash");
8
+
9
+ function buildCoreToolSpecs() {
10
+ return [
11
+ {
12
+ type: "function",
13
+ function: {
14
+ name: "read",
15
+ description: getReadToolDescription(),
16
+ parameters: {
17
+ type: "object",
18
+ properties: {
19
+ path: { type: "string" },
20
+ startLine: { type: "integer" },
21
+ endLine: { type: "integer" },
22
+ maxBytes: { type: "integer" },
23
+ },
24
+ required: ["path"],
25
+ },
26
+ },
27
+ },
28
+ {
29
+ type: "function",
30
+ function: {
31
+ name: "read_image",
32
+ description: getReadImageToolDescription(),
33
+ parameters: {
34
+ type: "object",
35
+ properties: {
36
+ path: {
37
+ type: "string",
38
+ description: "Workspace-relative path to a png, jpeg, gif, or webp image.",
39
+ },
40
+ },
41
+ required: ["path"],
42
+ },
43
+ },
44
+ },
45
+ {
46
+ type: "function",
47
+ function: {
48
+ name: "write",
49
+ description: getWriteToolDescription(),
50
+ parameters: {
51
+ type: "object",
52
+ properties: {
53
+ path: { type: "string" },
54
+ content: { type: "string" },
55
+ mode: {
56
+ type: "string",
57
+ enum: ["overwrite", "append"],
58
+ description: 'Write mode: "overwrite" replaces the file (default), "append" adds to its end.',
59
+ },
60
+ append: { type: "boolean" },
61
+ },
62
+ required: ["path", "content"],
63
+ },
64
+ },
65
+ },
66
+ {
67
+ type: "function",
68
+ function: {
69
+ name: "edit",
70
+ description: getEditToolDescription(),
71
+ parameters: {
72
+ type: "object",
73
+ properties: {
74
+ path: { type: "string" },
75
+ find: { type: "string" },
76
+ replace: { type: "string" },
77
+ all: { type: "boolean" },
78
+ },
79
+ required: ["path", "find", "replace"],
80
+ },
81
+ },
82
+ },
83
+ {
84
+ type: "function",
85
+ function: {
86
+ name: "bash",
87
+ description: getBashToolDescription(),
88
+ parameters: {
89
+ type: "object",
90
+ properties: {
91
+ command: { type: "string" },
92
+ timeoutMs: { type: "integer" },
93
+ },
94
+ required: ["command"],
95
+ },
96
+ },
97
+ },
98
+ {
99
+ type: "function",
100
+ function: {
101
+ name: "artifact_read",
102
+ description: [
103
+ "Read previously stored tool output by artifactId.",
104
+ "This does not read workspace files; use `read` for repository paths.",
105
+ "Optionally read a slice with startLine/endLine, maxChars, or tailLines.",
106
+ ].join(" "),
107
+ parameters: {
108
+ type: "object",
109
+ properties: {
110
+ artifactId: { type: "string" },
111
+ sessionId: { type: "string" },
112
+ startLine: { type: "integer" },
113
+ endLine: { type: "integer" },
114
+ maxChars: { type: "integer" },
115
+ tailLines: { type: "integer" },
116
+ },
117
+ required: ["artifactId"],
118
+ },
119
+ },
120
+ },
121
+ {
122
+ type: "function",
123
+ function: {
124
+ name: "plan_graph",
125
+ description: [
126
+ "Manage the persistent Plan Graph and graph-bound TaskRuns.",
127
+ "TaskRuns are orthogonal to Plan Mode; for a standalone TaskRun without a plan, use `task_run` instead.",
128
+ "Use create, patch, inspect, or cancel_graph for graph operations, and control for graph-bound TaskRun lifecycle.",
129
+ "`control.start_task` starts a graph `task_loop` asynchronously and returns immediately.",
130
+ "Use `inline_llm` for work handled by the current graph owner,",
131
+ "`expand` for tasks that must be lowered into child nodes,",
132
+ "and `task_loop` for asynchronous work in an independent TaskLoop attached to a plan node.",
133
+ "Do not call `plan_graph` together with data-plane tools in the same assistant turn.",
134
+ ].join(" "),
135
+ parameters: {
136
+ type: "object",
137
+ properties: {
138
+ operation: {
139
+ type: "string",
140
+ enum: [
141
+ "create",
142
+ "patch",
143
+ "inspect",
144
+ "clear",
145
+ "cancel_graph",
146
+ "control",
147
+ ],
148
+ description: [
149
+ "create/patch/inspect/cancel_graph mutate or inspect the graph spec;",
150
+ "control runs TaskRun lifecycle and node status actions.",
151
+ ].join(" "),
152
+ },
153
+ graph: {
154
+ type: "object",
155
+ description: "Full graph for create (objective + nodes). group is input sugar only.",
156
+ },
157
+ operations: {
158
+ type: "array",
159
+ description: [
160
+ "Patch ops only: add_node, expand_node, add_dependency, remove_dependency.",
161
+ "Status actions (complete_task, skip_node, cancel_subtree) belong under control.actions.",
162
+ ].join(" "),
163
+ items: { type: "object" },
164
+ },
165
+ actions: {
166
+ type: "array",
167
+ description: [
168
+ "Control actions: start_task, cancel_task, fail_task, complete_task, skip_node, cancel_subtree.",
169
+ "complete_task with taskRunId finishes a TaskLoop TaskRun;",
170
+ "complete_task with nodeId finishes a waiting_llm inline task owned by the graph owner.",
171
+ ].join(" "),
172
+ items: { type: "object" },
173
+ },
174
+ reason: {
175
+ type: "string",
176
+ description: "Optional reason for cancel_graph or fail/cancel task.",
177
+ },
178
+ commandId: {
179
+ type: "string",
180
+ description: [
181
+ "Optional idempotency key for explicit replay.",
182
+ "When omitted, the Runtime should derive one from the tool invocation when available.",
183
+ ].join(" "),
184
+ },
185
+ expectedSpecRevision: {
186
+ type: "integer",
187
+ description: "Optional optimistic concurrency token for patch.",
188
+ },
189
+ graphId: {
190
+ type: "string",
191
+ description: "Optional graph id check for patch/control.",
192
+ },
193
+ },
194
+ required: ["operation"],
195
+ },
196
+ },
197
+ },
198
+ {
199
+ type: "function",
200
+ function: {
201
+ name: "task_run",
202
+ description: [
203
+ "Start, inspect, cancel, fail, or complete a TaskRun.",
204
+ "TaskRuns are orthogonal to Plan Mode and do not require a plan_graph.",
205
+ "Use operation=start with an objective for a standalone single-point TaskRun; it returns immediately.",
206
+ "On complex multi-goal work, decompose into concrete objectives and start one or more TaskRuns.",
207
+ "Use plan_graph control.start_task only when the TaskRun is attached to a plan_graph task_loop node.",
208
+ "Do not call `task_run` together with data-plane tools in the same assistant turn.",
209
+ ].join(" "),
210
+ parameters: {
211
+ type: "object",
212
+ properties: {
213
+ operation: {
214
+ type: "string",
215
+ enum: ["start", "cancel", "fail", "complete", "inspect"],
216
+ description: [
217
+ "start creates a standalone TaskRun from objective;",
218
+ "cancel/fail/complete/inspect address an existing taskRunId",
219
+ "(cancel/fail may also use nodeId for graph-bound runs).",
220
+ ].join(" "),
221
+ },
222
+ objective: {
223
+ type: "string",
224
+ description: "Required for start: concrete TaskRun objective.",
225
+ },
226
+ title: {
227
+ type: "string",
228
+ description: "Optional short title for start.",
229
+ },
230
+ taskRunId: {
231
+ type: "string",
232
+ description: "TaskRun id for cancel, fail, complete, or inspect.",
233
+ },
234
+ nodeId: {
235
+ type: "string",
236
+ description: "Optional graph node id for cancel/fail of a graph-bound TaskRun.",
237
+ },
238
+ reason: {
239
+ type: "string",
240
+ description: "Optional reason for cancel or fail.",
241
+ },
242
+ result: {
243
+ type: "object",
244
+ description: "Optional result payload for complete (TaskLoop owner).",
245
+ },
246
+ commandId: {
247
+ type: "string",
248
+ description: "Optional idempotency key for explicit replay.",
249
+ },
250
+ },
251
+ required: ["operation"],
252
+ },
253
+ },
254
+ },
255
+ {
256
+ type: "function",
257
+ function: {
258
+ name: "ask_user",
259
+ description: [
260
+ "Ask the user for input and pause the current Agent loop until the reply arrives.",
261
+ "Use only when user input is required to proceed, not for routine updates or decisions the agent can safely make.",
262
+ "`kind=approval` requests yes/no confirmation; `kind=choice` presents the supplied options; `kind=chat` requests free text.",
263
+ "This must be the only tool call in the turn.",
264
+ "The reply is returned only as this tool result, not as a separate user message or pending user prompt.",
265
+ "After the tool returns, continue from the answer and do not ask the same question again.",
266
+ "Running TaskRuns are not paused automatically.",
267
+ ].join(" "),
268
+ parameters: {
269
+ type: "object",
270
+ properties: {
271
+ kind: {
272
+ type: "string",
273
+ enum: ["approval", "choice", "chat"],
274
+ description: "Interaction type.",
275
+ },
276
+ prompt: {
277
+ type: "string",
278
+ description: "Question shown to the user.",
279
+ },
280
+ options: {
281
+ type: "array",
282
+ description: "For choice: option labels (or {key,label} objects). Ignored for chat.",
283
+ items: {
284
+ oneOf: [
285
+ { type: "string" },
286
+ {
287
+ type: "object",
288
+ properties: {
289
+ key: { type: "string" },
290
+ label: { type: "string" },
291
+ },
292
+ },
293
+ ],
294
+ },
295
+ },
296
+ },
297
+ required: ["kind", "prompt"],
298
+ },
299
+ },
300
+ },
301
+ ];
302
+ }
303
+
304
+ function buildAnthropicToolSpecs() {
305
+ return buildCoreToolSpecs().map((spec) => ({
306
+ name: spec.function.name,
307
+ description: spec.function.description,
308
+ input_schema: spec.function.parameters,
309
+ }));
310
+ }
311
+
312
+ module.exports = { buildCoreToolSpecs, buildAnthropicToolSpecs };