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
@@ -2,7 +2,7 @@
2
2
  const path = require("path");
3
3
  const fs = require("fs");
4
4
  const os = require("os");
5
- const { removeLegacySkillAndCommandLinks } = require("./postinstall-skills");
5
+ const { removeLegacySkillAndCommandLinks, refreshInstalledOptionalSkills, installManagedSkillLink } = require("./postinstall-skills");
6
6
 
7
7
  // Fix node-pty spawn-helper permissions on macOS (both arm64 and x64)
8
8
  const platforms = ["darwin-arm64", "darwin-x64"];
@@ -59,26 +59,16 @@ function collectSkillSources(pkgRoot) {
59
59
  return sources;
60
60
  }
61
61
 
62
- function forceSymlink(target, linkPath) {
63
- try {
64
- const existing = fs.lstatSync(linkPath);
65
- if (existing.isSymbolicLink() || existing.isFile() || existing.isDirectory()) {
66
- fs.rmSync(linkPath, { recursive: true, force: true });
67
- }
68
- } catch {
69
- // doesn't exist - fine
70
- }
71
- fs.symlinkSync(target, linkPath);
72
- }
73
-
74
62
  function installSkillDirs(targetDir, sources, label) {
75
63
  fs.mkdirSync(targetDir, { recursive: true });
76
-
64
+ let available = 0;
77
65
  for (const { name, dir } of sources) {
78
- forceSymlink(dir, path.join(targetDir, name));
66
+ if (installManagedSkillLink(dir, path.join(targetDir, name)) === "conflict") {
67
+ console.log(`[postinstall] Preserved existing user skill: ${path.join(targetDir, name)}`);
68
+ } else available += 1;
79
69
  }
80
70
 
81
- console.log(`[postinstall] Installed ${sources.length} ufoo skill(s) to ${label}`);
71
+ console.log(`[postinstall] ${available} ufoo skill(s) available in ${label}`);
82
72
  }
83
73
 
84
74
  // Install ufoo skills for Claude and Codex at npm install time.
@@ -100,6 +90,11 @@ try {
100
90
 
101
91
  installSkillDirs(path.join(codexHome, "skills"), sources, `${codexHome}/skills`);
102
92
  }
93
+ const refreshed = refreshInstalledOptionalSkills({
94
+ pkgRoot,
95
+ targetDirs: [path.join(home, ".claude", "skills"), path.join(codexHome, "skills"), path.join(home, ".agents", "skills")],
96
+ });
97
+ if (refreshed.length) console.log(`[postinstall] Refreshed ${refreshed.length} installed optional ufoo skill(s)`);
103
98
  } catch (err) {
104
99
  // Non-fatal - skills can be installed manually via `ufoo skills install`
105
100
  console.log(`[postinstall] Skipped skills install: ${err.message}`);
@@ -0,0 +1,214 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // Optional local smoke test using installed vendor CLIs and an isolated fake
5
+ // model endpoint. No user settings, credentials or real inference are used.
6
+ const fs = require("fs");
7
+ const os = require("os");
8
+ const path = require("path");
9
+ const http = require("http");
10
+ const pty = require("node-pty");
11
+ const EventBus = require("../src/coordination/bus");
12
+ const { registerAgentFull } = require("../src/runtime/daemon/controlPlaneService");
13
+ const { resolveNativeMessageMode, setNativeMetadata } = require("../src/agents/launch/nativeMessages");
14
+ const Injector = require("../src/coordination/bus/inject");
15
+ const { getUfooPaths } = require("../src/coordination/state/paths");
16
+ const { loadAgentsData } = require("../src/coordination/state/agentsStore");
17
+
18
+ async function until(predicate, timeout = 20000) {
19
+ const deadline = Date.now() + timeout;
20
+ while (!predicate()) {
21
+ if (Date.now() > deadline) throw new Error("Native smoke condition timed out");
22
+ await new Promise((resolve) => setTimeout(resolve, 25));
23
+ }
24
+ }
25
+
26
+ function anthropicResponse(response, block) {
27
+ const messageId = "msg_ufoo_fixture";
28
+ const isTool = block.type === "tool_use";
29
+ response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
30
+ const send = (type, data) => response.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`);
31
+ send("message_start", { message: { id: messageId, type: "message", role: "assistant", content: [], model: "fixture", stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 0 } } });
32
+ send("content_block_start", { index: 0, content_block: isTool ? { ...block, input: {} } : { type: "text", text: "" } });
33
+ send("content_block_delta", { index: 0, delta: isTool ? { type: "input_json_delta", partial_json: JSON.stringify(block.input) } : { type: "text_delta", text: block.text } });
34
+ send("content_block_stop", { index: 0 });
35
+ send("message_delta", { delta: { stop_reason: isTool ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 1 } });
36
+ send("message_stop", {});
37
+ response.end();
38
+ }
39
+
40
+ async function main() {
41
+ const selected = process.argv[2] || "claude";
42
+ const legacyOptOut = process.argv.includes("--legacy");
43
+ // macOS's per-user temp path can exceed the Unix socket length limit once
44
+ // the wrapper's project-local bus socket suffix is appended.
45
+ const fixtureParent = process.platform === "darwin" ? "/private/tmp" : process.env.RUNNER_TEMP || os.tmpdir();
46
+ const root = fs.mkdtempSync(path.join(fixtureParent, "uf-smoke-"));
47
+ const ptyGroupsFile = path.join(root, "fixture-pty-groups");
48
+ const received = [];
49
+ let probeCalled = false;
50
+ const api = http.createServer((request, response) => {
51
+ let raw = "";
52
+ request.on("data", (chunk) => { raw += chunk; });
53
+ request.on("end", () => {
54
+ let body = {};
55
+ try { body = JSON.parse(raw || "{}"); } catch { /* non-model request */ }
56
+ if (request.url.includes("count_tokens")) {
57
+ response.writeHead(200, { "content-type": "application/json" }); response.end('{"input_tokens":1}'); return;
58
+ }
59
+ if (request.url.includes("messages")) {
60
+ const messages = JSON.stringify(body.messages || []);
61
+ const nonce = messages.match(/nonce ([0-9a-f]{48})/)?.[1];
62
+ const tool = body.tools?.find((item) => item.name.endsWith("__channel_ready"));
63
+ if (nonce && tool && !probeCalled) {
64
+ probeCalled = true;
65
+ anthropicResponse(response, { type: "tool_use", id: "tool_probe", name: tool.name, input: { nonce } });
66
+ } else {
67
+ for (const marker of ["ufoo_native_first", "ufoo_native_second"]) {
68
+ if (messages.includes(marker) && !received.includes(marker)) received.push(marker);
69
+ }
70
+ setTimeout(() => anthropicResponse(response, { type: "text", text: "Fixture message received." }), messages.includes("ufoo_native_first") ? 300 : 0);
71
+ }
72
+ return;
73
+ }
74
+ if (request.url.includes("responses")) {
75
+ const input = JSON.stringify(body.input || []);
76
+ for (const marker of ["ufoo_native_first", "ufoo_native_second"]) if (input.includes(marker) && !received.includes(marker)) received.push(marker);
77
+ response.writeHead(200, { "content-type": "text/event-stream" });
78
+ const item = { id: "msg_fixture", type: "message", role: "assistant", status: "completed", content: [{ type: "output_text", text: "Fixture message received.", annotations: [] }] };
79
+ const send = (data) => response.write(`data: ${JSON.stringify(data)}\n\n`);
80
+ send({ type: "response.created", response: { id: "resp_fixture", object: "response", status: "in_progress", output: [] } });
81
+ send({ type: "response.output_item.added", output_index: 0, item: { ...item, status: "in_progress", content: [] } });
82
+ send({ type: "response.output_text.delta", item_id: item.id, output_index: 0, content_index: 0, delta: "Fixture message received." });
83
+ send({ type: "response.output_item.done", output_index: 0, item });
84
+ setTimeout(() => {
85
+ send({ type: "response.completed", response: { id: "resp_fixture", object: "response", status: "completed", output: [item], usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 } } } });
86
+ response.end();
87
+ }, 300);
88
+ return;
89
+ }
90
+ response.writeHead(200, { "content-type": "application/json" }); response.end("{}");
91
+ });
92
+ });
93
+ await new Promise((resolve) => api.listen(0, "127.0.0.1", resolve));
94
+ const baseUrl = `http://127.0.0.1:${api.address().port}`;
95
+ const home = path.join(root, "home"); fs.mkdirSync(home);
96
+ const env = { PATH: process.env.PATH, LANG: process.env.LANG || "en_US.UTF-8", TERM: "xterm-256color", SHELL: process.env.SHELL || "/bin/sh", HOME: home, CODEX_HOME: path.join(home, "codex"), CLAUDE_CONFIG_DIR: path.join(home, "claude"), ANTHROPIC_API_KEY: "ufoo-local-fixture", ANTHROPIC_BASE_URL: baseUrl, DISABLE_UPDATES: "1" };
97
+ if (legacyOptOut) env.UFOO_NATIVE_MESSAGES = "0";
98
+ fs.mkdirSync(env.CODEX_HOME, { recursive: true });
99
+ fs.mkdirSync(env.CLAUDE_CONFIG_DIR, { recursive: true });
100
+ fs.writeFileSync(path.join(env.CLAUDE_CONFIG_DIR, ".claude.json"), JSON.stringify({ hasCompletedOnboarding: true, theme: "dark", customApiKeyResponses: { approved: [env.ANTHROPIC_API_KEY.slice(-20)], rejected: [] } }));
101
+ fs.writeFileSync(path.join(env.CODEX_HOME, "config.toml"), `model = "fixture"\nmodel_provider = "fixture"\n[model_providers.fixture]\nname = "fixture"\nbase_url = "${baseUrl}/v1"\nwire_api = "responses"\nrequires_openai_auth = false\nsupports_websockets = false\n`);
102
+ let terminal;
103
+ let output = "";
104
+ let exited = false;
105
+ try {
106
+ await new EventBus(root).init();
107
+ const agentType = selected === "codex" ? "codex" : "claude-code";
108
+ if (resolveNativeMessageMode({ agentType, env, stdinIsTTY: true, stdoutIsTTY: true }) === legacyOptOut) throw new Error("Interactive native delivery selection is incorrect");
109
+ const identity = await registerAgentFull(root, { agentType, sessionId: "smoke001", parentPid: process.pid, launchMode: "terminal", tty: "", skipSessionResolve: true }, { validateParentPid: true, notifyDaemon: false });
110
+ Object.assign(env, { UFOO_SUBSCRIBER_ID: identity.subscriber, UFOO_AGENT_HANDLE: identity.agent_handle });
111
+ if (legacyOptOut) setNativeMetadata(root, identity.subscriber, { native_delivery: "stale_receiver", native_delivery_ready: true, native_delivery_instance: "stale_socket" });
112
+ const args = selected === "codex" ? [] : ["--model", "fixture", "--allowedTools", "mcp__ufoo_channel__channel_ready", "--debug-file", path.join(root, "claude-debug.log")];
113
+ // Exercise the full shared launcher and its inject socket. Only daemon
114
+ // setup/registration use this fixture's already registered local identity.
115
+ const launcherScript = `
116
+ // Each Unix PTY owns a separate session. Record only this fixture's
117
+ // groups so cleanup can stop vendor descendants after wrapper exit.
118
+ const pty = require(${JSON.stringify(require.resolve("node-pty"))});
119
+ const spawnPty = pty.spawn;
120
+ pty.spawn = (...args) => {
121
+ const child = spawnPty(...args);
122
+ require("fs").appendFileSync(${JSON.stringify(ptyGroupsFile)}, String(child.pid) + "\\n");
123
+ return child;
124
+ };
125
+ const Launcher = require(${JSON.stringify(path.resolve(__dirname, "../src/agents/launch/launcher"))});
126
+ const launcher = new Launcher(${JSON.stringify(agentType)}, ${JSON.stringify(selected === "codex" ? "codex" : "claude")});
127
+ launcher.ensureInit = async () => {};
128
+ launcher.ensureDaemon = async () => "fixture";
129
+ launcher.getPreRegistered = async () => ({ subscriberId: process.env.UFOO_SUBSCRIBER_ID, sessionId: "smoke001", agentHandle: process.env.UFOO_AGENT_HANDLE });
130
+ launcher.launch(${JSON.stringify(args)});
131
+ `;
132
+ terminal = pty.spawn(process.execPath, ["-e", launcherScript], { cwd: root, env: { ...env, UFOO_SUPPRESS_LAUNCHER_BANNER: "1" }, name: "xterm-256color", cols: 120, rows: 40 });
133
+ const answered = new Set();
134
+ terminal.onExit(() => { exited = true; });
135
+ terminal.onData((data) => {
136
+ output = (output + data).slice(-24000);
137
+ const text = output.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "");
138
+ // Answer only setup dialogs in this isolated fixture session.
139
+ if (/want\s*to\s*use\s*this\s*API\s*key/i.test(text) && !answered.has("fixture-key")) {
140
+ answered.add("fixture-key"); setTimeout(() => terminal.write("\x1b[A\r"), 100);
141
+ }
142
+ if (/local\s*development/i.test(text) && !answered.has("development-channel")) {
143
+ answered.add("development-channel"); setTimeout(() => terminal.write("\r"), 100);
144
+ }
145
+ if (/(?:trust.*(?:folder|directory)|Yes,?\s*I\s*trust)/i.test(text) && !answered.has("workspace-trust")) {
146
+ answered.add("workspace-trust");
147
+ // Newer Claude versions default to "No, exit". This fixture creates
148
+ // its own disposable workspace; select its trust option explicitly.
149
+ const declineSelected = /[❯>]\s*No,?\s*exit/i.test(text);
150
+ if (declineSelected) {
151
+ setTimeout(() => terminal.write("\x1b[B"), 100);
152
+ setTimeout(() => terminal.write("\r"), 400);
153
+ } else {
154
+ setTimeout(() => terminal.write("\r"), 100);
155
+ }
156
+ }
157
+ for (const pattern of [/text\s*style.*terminal/i, /Press\s*Ente?r?\s*to\s*continue/i, /Use\s*this\s*MCP\s*server/i]) {
158
+ if (pattern.test(text) && !answered.has(pattern.source)) {
159
+ answered.add(pattern.source); setTimeout(() => terminal.write("\r"), 100);
160
+ }
161
+ }
162
+ });
163
+ if (legacyOptOut) {
164
+ await until(() => loadAgentsData(getUfooPaths(root).agentsFile).agents[identity.subscriber]?.native_delivery === null
165
+ && fs.existsSync(path.join(getUfooPaths(root).busQueuesDir, identity.subscriber.replace(/:/g, "_"), "inject.sock")));
166
+ console.log(JSON.stringify({ host: selected, ok: true, legacy_opt_out: true, stale_receiver_cleared: true }));
167
+ return;
168
+ }
169
+ await until(() => {
170
+ if (exited) throw new Error(`${selected} exited before channel readiness`);
171
+ return loadAgentsData(getUfooPaths(root).agentsFile).agents[identity.subscriber]?.native_delivery_ready === true;
172
+ });
173
+ const injector = new Injector(getUfooPaths(root).busDir, getUfooPaths(root).agentsFile);
174
+ await injector.inject(identity.subscriber, "ufoo_native_first", { deliveryId: "smoke:1" });
175
+ await until(() => received.includes("ufoo_native_first"));
176
+ await injector.inject(identity.subscriber, "ufoo_native_second", { deliveryId: "smoke:2" });
177
+ await until(() => received.includes("ufoo_native_second"));
178
+ console.log(JSON.stringify({ host: selected, ok: true, received, native_channel_probe: selected === "codex" ? null : probeCalled }));
179
+ } catch (err) {
180
+ const debugFile = path.join(root, "claude-debug.log");
181
+ const channelDiagnostics = fs.existsSync(debugFile) ? fs.readFileSync(debugFile, "utf8").split("\n").filter((line) => /channel|ufoo_channel|growthbook/i.test(line)).slice(-20) : [];
182
+ console.error(JSON.stringify({ host: selected, ok: false, error: err.message, probe_called: probeCalled, channel_diagnostics: channelDiagnostics, fixture_ui: output.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").slice(-1800) }));
183
+ process.exitCode = 1;
184
+ } finally {
185
+ const groups = new Set(terminal ? [terminal.pid] : []);
186
+ try {
187
+ for (const value of fs.readFileSync(ptyGroupsFile, "utf8").split("\n")) {
188
+ const pid = Number(value);
189
+ if (Number.isInteger(pid) && pid > 1) groups.add(pid);
190
+ }
191
+ } catch { /* The launcher may have failed before starting its PTY. */ }
192
+ const signalGroups = (signal) => {
193
+ for (const pid of groups) {
194
+ try { process.kill(-pid, signal); }
195
+ catch (err) { if (err.code !== "ESRCH") throw err; }
196
+ }
197
+ };
198
+ signalGroups("SIGTERM");
199
+ if (terminal && !exited) {
200
+ terminal.kill("SIGTERM");
201
+ try { await until(() => exited, 2500); }
202
+ catch { terminal.kill("SIGKILL"); }
203
+ }
204
+ await new Promise((resolve) => setTimeout(resolve, 250));
205
+ signalGroups("SIGKILL");
206
+ api.closeAllConnections();
207
+ await new Promise((resolve) => api.close(resolve));
208
+ await new Promise((resolve) => setTimeout(resolve, 200));
209
+ // Vendor processes can finish writing state just after the wrapper exits.
210
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
211
+ }
212
+ }
213
+
214
+ main().catch((err) => { console.error(err.message); process.exitCode = 1; });
@@ -161,7 +161,7 @@ class ActivityDetector {
161
161
  /**
162
162
  * @param {string} agentType - e.g. "claude-code", "codex"
163
163
  * @param {object} [options]
164
- * @param {string} [options.mode] - launch mode ("terminal"/"tmux"/"iterm2"/"pty-runner")
164
+ * @param {string} [options.mode] - launch mode ("internal"/"terminal"/"tmux"/"iterm2")
165
165
  * @param {number} [options.bufferSize=4000] - rolling buffer size in chars
166
166
  * @param {number} [options.tailLines=10] - number of tail lines used for quiet-time prompt detection
167
167
  * @param {boolean} [options.startOnOutput=false] - allow STARTING -> WORKING on first output
@@ -1,5 +1,5 @@
1
1
  const fs = require("fs");
2
- const { readJSON, writeJSON } = require("../../coordination/bus/utils");
2
+ const { updateAgentsData } = require("../../coordination/state/agentsStore");
3
3
  const { appendAgentRegistryDiagnostic } = require("../../coordination/state/agentRegistryDiagnostics");
4
4
 
5
5
  /**
@@ -18,47 +18,46 @@ function writeActivityState(agentsFilePath, subscriber, state, options = {}) {
18
18
  const detail = typeof options.detail === "string" ? options.detail : "";
19
19
  try {
20
20
  if (!agentsFilePath || !fs.existsSync(agentsFilePath)) return false;
21
- const data = readJSON(agentsFilePath, null);
22
- if (!data) return false;
23
- if (!data.agents || !data.agents[subscriber]) {
24
- appendAgentRegistryDiagnostic(agentsFilePath, "activity_state_subscriber_missing", {
25
- source: "agent.activityStateWriter.writeActivityState",
26
- subscriber,
27
- state,
28
- known_ids: Object.keys(data.agents || {}).sort(),
29
- });
30
- return false;
31
- }
21
+ return updateAgentsData(agentsFilePath, (data) => {
22
+ if (!data.agents || !data.agents[subscriber]) {
23
+ appendAgentRegistryDiagnostic(agentsFilePath, "activity_state_subscriber_missing", {
24
+ source: "agent.activityStateWriter.writeActivityState",
25
+ subscriber,
26
+ state,
27
+ known_ids: Object.keys(data.agents || {}).sort(),
28
+ });
29
+ return false;
30
+ }
32
31
 
33
- const agent = data.agents[subscriber];
34
- const currentState = agent.activity_state;
35
- const currentDetail = typeof agent.activity_detail === "string" ? agent.activity_detail : "";
32
+ const agent = data.agents[subscriber];
33
+ const currentState = agent.activity_state;
34
+ const currentDetail = typeof agent.activity_detail === "string" ? agent.activity_detail : "";
36
35
 
37
- if (currentState === state && currentDetail === detail) return false;
36
+ if (currentState === state && currentDetail === detail) return false;
38
37
 
39
- if (
40
- currentState !== state
41
- && !force
42
- && (currentState === "working" || currentState === "waiting_input" || currentState === "blocked")
43
- ) {
44
- if (state === "idle" || state === "ready") return false;
45
- }
38
+ if (
39
+ currentState !== state
40
+ && !force
41
+ && (currentState === "working" || currentState === "waiting_input" || currentState === "blocked")
42
+ ) {
43
+ if (state === "idle" || state === "ready") return false;
44
+ }
46
45
 
47
- agent.activity_state = state;
48
- if (detail) {
49
- agent.activity_detail = detail;
50
- } else {
51
- delete agent.activity_detail;
52
- }
53
- if (currentState !== state) {
54
- agent.activity_since = since
55
- ? new Date(since).toISOString()
56
- : new Date().toISOString();
57
- } else if (!agent.activity_since) {
58
- agent.activity_since = new Date().toISOString();
59
- }
60
- writeJSON(agentsFilePath, data);
61
- return true;
46
+ agent.activity_state = state;
47
+ if (detail) {
48
+ agent.activity_detail = detail;
49
+ } else {
50
+ delete agent.activity_detail;
51
+ }
52
+ if (currentState !== state) {
53
+ agent.activity_since = since
54
+ ? new Date(since).toISOString()
55
+ : new Date().toISOString();
56
+ } else if (!agent.activity_since) {
57
+ agent.activity_since = new Date().toISOString();
58
+ }
59
+ return true;
60
+ });
62
61
  } catch {
63
62
  return false;
64
63
  }
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ const { createCoordinationCapability } = require("../coordination");
3
+ module.exports = { createAgentManagementCapability: (host) => createCoordinationCapability({ host, id: "agent-management",
4
+ toolNames: ["list_agents", "launch_agent", "rename_agent", "close_agent", "delegate_task", "resume_agents"] }) };
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+
3
+ const { createHash } = require("crypto");
4
+ const { createCommandStore } = require("../../runtime");
5
+ const { stableStringify } = require("../../runtime/core/stableJson");
6
+ const { REPORTING_GUIDANCE } = require("../../prompts/reporting");
7
+ const { normalizeInternalAgentType } = require("../../../runtime/contracts/agentMode");
8
+
9
+ const digest = (value) => createHash("sha256").update(value).digest("hex").slice(0, 24);
10
+ const empty = () => ({ tasks: {} });
11
+ const reject = (code, error) => ({ ok: false, code, error });
12
+
13
+ /** Project host ports own launching/delivery; this adapter records business associations. */
14
+ function createAgentManagementService({ store, launch, dispatch, wake = async () => {}, emit = () => {}, validateEvidence = null, resolveTarget = (target) => target } = {}) {
15
+ const commands = createCommandStore(store);
16
+ const read = () => store.read().capabilityState["agent-management"]?.value || empty();
17
+ function update(mutator) {
18
+ return store.transaction((snapshot) => {
19
+ const state = snapshot.capabilityState["agent-management"]?.value || empty();
20
+ mutator(state);
21
+ return [{ type: "capability.state_committed", capabilityId: "agent-management", version: 1, value: state }];
22
+ });
23
+ }
24
+ function failed(taskId, stage, result) {
25
+ const failure = { ...result, ok: false, taskId };
26
+ update((state) => {
27
+ const task = state.tasks[taskId];
28
+ task.lastError = { code: failure.code || `${stage}_failed`, error: failure.error || `${stage} failed`, stage };
29
+ task.updatedAt = new Date().toISOString();
30
+ // An uncertain side effect must still be reconciled through its command
31
+ // receipt. A confirmed failure cannot remain a queued/running task.
32
+ if (failure.code !== "uncertain_effect") task.status = failure.code === "awaiting_registration" ? "awaiting_registration" : "failed";
33
+ });
34
+ emit({ type: "delegation.failed", taskId, stage, code: failure.code, error: failure.error });
35
+ return failure;
36
+ }
37
+ async function flushWakes() {
38
+ for (const task of Object.values(read().tasks)) {
39
+ if (!task.pendingWake) continue;
40
+ await wake({ requestId: task.pendingWake, text: `Review delegated task ${task.taskId}. Worker reports ${task.report.phase}. Validate the acceptance criteria and evidence before accepting.`,
41
+ taskId: task.taskId, parentTaskRunId: task.parentTaskRunId, report: task.report, acceptanceCriteria: task.acceptanceCriteria });
42
+ update((state) => { if (state.tasks[task.taskId].pendingWake === task.pendingWake) state.tasks[task.taskId].pendingWake = ""; });
43
+ }
44
+ }
45
+ return Object.freeze({
46
+ commands,
47
+ snapshot: read,
48
+ flushWakes,
49
+ delivery({ subscriber, event, status, errorCode }) {
50
+ const matched = Object.values(read().tasks).find((task) => task.workerId === subscriber && task.dispatchReceipt?.receipt?.seq === event?.seq);
51
+ if (!matched || !["queued", "delivery_uncertain"].includes(matched.status)) return { matched: false };
52
+ const next = status === "ok" ? "delivered" : errorCode === "native_outcome_unknown" ? "delivery_uncertain" : "queued";
53
+ update((state) => { state.tasks[matched.taskId].status = next; });
54
+ emit({ type: next === "delivery_uncertain" ? "delivery.uncertain" : "dispatch.delivered", taskId: matched.taskId, workerId: subscriber, deliveryStatus: next });
55
+ return { matched: true, status: next };
56
+ },
57
+ async delegate(args, context = {}) {
58
+ const id = String(args.command_id || "");
59
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,100}$/.test(id)) return reject("invalid_arguments", "delegate_task requires safe command_id");
60
+ if (!String(args.objective || "").trim()) return reject("invalid_arguments", "delegate_task requires objective");
61
+ if (!args.target && !args.agent) return reject("invalid_arguments", "delegate_task requires an existing target or an agent type to create");
62
+ if (!args.target && !normalizeInternalAgentType(args.agent)) return reject("invalid_arguments", "delegate_task supports internal codex, claude or ucode workers only");
63
+ const scope = context.requestId ? `${context.requestId}:${id}` : id;
64
+ const commandId = `delegate-${digest(scope)}`;
65
+ const taskId = `delegated-${digest(scope)}`;
66
+ const fingerprint = digest(stableStringify(args));
67
+ const target = args.target ? resolveTarget(args.target) : "";
68
+ if (args.target && !target) return reject("invalid_target", "delegation target is not an active project worker. To create one, omit target and pass agent plus optional nickname.");
69
+ update((state) => {
70
+ const existing = state.tasks[taskId];
71
+ if (existing && existing.fingerprint !== fingerprint) throw Object.assign(new Error("delegation command conflicts"), { code: "command_conflict" });
72
+ if (!existing) state.tasks[taskId] = { taskId, fingerprint, objective: args.objective,
73
+ commandIds: [`${commandId}:launch`, `${commandId}:dispatch`],
74
+ acceptanceCriteria: args.acceptance_criteria || [], parentTaskRunId: context.taskRunId || "",
75
+ parentSessionId: context.sessionId || "", traceId: context.traceId || context.taskId || context.taskRunId || taskId,
76
+ parentRequestId: context.requestId || "", createdAt: new Date().toISOString(), status: "planning", workerId: String(target), reportIds: [] };
77
+ });
78
+ let task = read().tasks[taskId];
79
+ if (["failed", "awaiting_registration"].includes(task.status)) return { ok: false, task: { ...task }, ...task.lastError };
80
+ if (task.status !== "planning") return { ok: true, task: { ...task } };
81
+ if (!task.workerId) {
82
+ const nickname = args.nickname || `worker-${digest(scope).slice(0, 12)}`;
83
+ const result = await commands.execute({ commandId: `${commandId}:launch`, kind: "launch_agent", args: { agent: args.agent, nickname } }, () => launch({ agent: args.agent, nickname, count: 1 }));
84
+ if (!result || result.ok === false) return failed(taskId, "launch", result);
85
+ const rows = Array.isArray(result.ops_results) ? result.ops_results : [result];
86
+ const workerId = rows.map((row) => row.agent_id || row.subscriber_ids?.[0] || "").find(Boolean);
87
+ if (!workerId) return failed(taskId, "launch", { code: "awaiting_registration", error: "Launch receipt has no concrete worker identity; reconcile before dispatch." });
88
+ update((state) => { state.tasks[taskId].workerId = workerId; });
89
+ task = read().tasks[taskId];
90
+ }
91
+ const message = [args.objective, `Task ID: ${taskId}`, "Controller: ufoo-agent. Report start/progress/done/error with this exact task ID and private scope.",
92
+ "Use ufoo report --task <id> --scope private --controller ufoo-agent, or MCP report_agent_status with task_id, scope=private, controller_id=ufoo-agent.",
93
+ REPORTING_GUIDANCE,
94
+ `Acceptance criteria: ${JSON.stringify(task.acceptanceCriteria)}`].join("\n\n");
95
+ const receipt = await commands.execute({ commandId: `${commandId}:dispatch`, kind: "dispatch_message", args: { target: task.workerId, message } },
96
+ () => dispatch({ target: task.workerId, message, taskId, runtimeContext: { traceId: task.traceId,
97
+ taskId, parentTaskRunId: task.parentTaskRunId, parentSessionId: task.parentSessionId, parentRequestId: task.parentRequestId } }));
98
+ if (!receipt || receipt.ok === false) return failed(taskId, "dispatch", receipt);
99
+ update((state) => { const entry = state.tasks[taskId]; if (entry.status === "planning") entry.status = "queued"; entry.queuedAt = new Date().toISOString(); entry.dispatchReceipt = receipt; });
100
+ emit({ type: "delegation.queued", taskId, workerId: task.workerId, parentTaskRunId: task.parentTaskRunId });
101
+ return { ok: true, task: read().tasks[taskId], deliveryStatus: "queued" };
102
+ },
103
+ async report(entry) {
104
+ const task = read().tasks[entry.task_id];
105
+ if (!task || task.workerId !== entry.agent_id) return { matched: false };
106
+ const reportId = entry.entry_id || digest(JSON.stringify(entry));
107
+ if (task.reportIds.includes(reportId)) { await flushWakes(); return { matched: true, duplicate: true }; }
108
+ update((state) => {
109
+ const current = state.tasks[entry.task_id];
110
+ current.reportIds.push(reportId);
111
+ if (["accepted", "rejected"].includes(current.status)) return;
112
+ if (current.report && ["done", "error"].includes(current.report.phase) && ["start", "progress"].includes(entry.phase)) return;
113
+ current.report = entry;
114
+ current.updatedAt = entry.ts || new Date().toISOString();
115
+ current.status = ["done", "error"].includes(entry.phase) ? "reported" : "running";
116
+ if (current.status === "reported") current.pendingWake = `report-${digest(`${current.taskId}:${reportId}`)}`;
117
+ });
118
+ await flushWakes();
119
+ return { matched: true, task: read().tasks[entry.task_id] };
120
+ },
121
+ accept({ task_id: taskId, outcome, reason, evidence = [] }, context = {}) {
122
+ if (!["accepted", "rejected"].includes(outcome)) return reject("invalid_arguments", "accept_task requires accepted or rejected outcome");
123
+ const existing = read().tasks[taskId];
124
+ if (!existing || existing.status !== "reported") return reject("invalid_task_state", "task has no unreviewed terminal report");
125
+ if (outcome === "accepted" && (!String(reason || "").trim() || !evidence.length || existing.report.phase !== "done")) return reject("acceptance_required", "acceptance requires a completed worker report, reason, and validation evidence");
126
+ if (outcome === "accepted" && (!validateEvidence || validateEvidence(evidence, existing, context) !== true)) return reject("invalid_evidence", "host did not verify the acceptance evidence");
127
+ update((state) => {
128
+ const task = state.tasks[taskId];
129
+ if (!task || task.status !== "reported") throw new Error("task has no unreviewed terminal report");
130
+ if (outcome === "accepted" && (!String(reason || "").trim() || !evidence.length || task.report.phase !== "done")) throw new Error("acceptance requires a completed worker report, reason, and validation evidence");
131
+ if (outcome === "accepted" && (!validateEvidence || validateEvidence(evidence, task, context) !== true)) throw new Error("host did not verify the acceptance evidence");
132
+ task.status = outcome;
133
+ task.acceptance = { outcome, reason, evidence, time: new Date().toISOString() };
134
+ });
135
+ return { ok: true, task: read().tasks[taskId] };
136
+ },
137
+ });
138
+ }
139
+
140
+ module.exports = { createAgentManagementService };
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ const { createCoordinationCapability } = require("../coordination");
3
+ module.exports = { createAgentRoutingCapability: (host) => createCoordinationCapability({ host, id: "agent-routing",
4
+ toolNames: ["route_agent", "dispatch_message", "read_bus_summary", "read_prompt_history", "read_open_decisions"] }) };
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+
3
+ const { buildCoreToolSpecs } = require("../../../code/tools/specs");
4
+ const { runCoreToolAsync } = require("../../../code/tools/executor");
5
+
6
+ const CODING_TOOLS = new Set(["read", "read_image", "write", "edit", "bash", "artifact_read"]);
7
+
8
+ function toolFromSpec(spec) {
9
+ const { name, description, parameters } = spec.function;
10
+ return {
11
+ name, description, inputSchema: parameters,
12
+ permissions: [name === "bash" ? "workspace.execute" : ["write", "edit"].includes(name) ? "workspace.write" : "workspace.read"],
13
+ tight: ["read", "read_image", "artifact_read"].includes(name),
14
+ handler: (args, context) => runCoreToolAsync({ ...context, tool: name, args }),
15
+ };
16
+ }
17
+
18
+ function createCodingCapability({ workspaceAccess = null } = {}) {
19
+ return {
20
+ id: "coding", version: "1.0",
21
+ requires: { providerFeatures: ["tool_calls", "vision"] },
22
+ tools: buildCoreToolSpecs().filter((spec) => CODING_TOOLS.has(spec.function.name)).map((spec) => {
23
+ const tool = toolFromSpec(spec);
24
+ return workspaceAccess ? { ...tool, async handler(args, context) {
25
+ const result = await workspaceAccess.run({ ...context, tool: tool.name, args }, () => tool.handler(args, context));
26
+ return { ...result, toolCallId: context.toolCallId };
27
+ } } : tool;
28
+ }),
29
+ };
30
+ }
31
+
32
+ module.exports = { createCodingCapability, toolFromSpec };
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+
3
+ const { listToolsForCallerTier } = require("../../../tools/registry");
4
+ const { CALLER_TIERS } = require("../../../tools/types");
5
+ const { executeControllerTool } = require("../../controller/controllerToolExecutor");
6
+
7
+ const TOOL_PERMISSIONS = Object.freeze({
8
+ launch_agent: "agents.manage", rename_agent: "agents.manage", close_agent: "agents.manage",
9
+ manage_cron: "schedules.manage", dispatch_message: "coordination.write", ack_bus: "coordination.write",
10
+ delegate_task: "agents.manage", resume_agents: "agents.manage", accept_task: "tasks.accept",
11
+ manage_tasks: "tasks.execute", manage_group: "groups.manage",
12
+ remember: "memory.write", edit_memory: "memory.write", forget: "memory.write",
13
+ });
14
+
15
+ /** Shared definitions retain the same schemas and tier checks used by MCP. */
16
+ function createCoordinationCapability({ host, id = "coordination", toolNames = null, policy = null } = {}) {
17
+ const definitions = listToolsForCallerTier(CALLER_TIERS.CONTROLLER)
18
+ .filter((tool) => (!toolNames || toolNames.includes(tool.name)) && (tool.requiredPorts || []).every((port) => host.coordination[port]));
19
+ const requestedPermissions = [...new Set(definitions.map((tool) => TOOL_PERMISSIONS[tool.name] || "coordination.read"))];
20
+ return {
21
+ id, version: 1, requires: { ports: ["coordination"] }, requestedPermissions, policy,
22
+ tools: definitions.map((tool) => ({
23
+ name: tool.name, description: tool.description, inputSchema: tool.input_schema,
24
+ permissions: [TOOL_PERMISSIONS[tool.name] || "coordination.read"],
25
+ async handler(args, context) {
26
+ const ports = host.coordination;
27
+ const invoke = ports.execute || executeControllerTool;
28
+ return invoke({ ...ports, projectRoot: context.workspaceRoot || ports.projectRoot,
29
+ subscriber: "ufoo-agent", turnId: context.turnId, taskId: context.taskId,
30
+ requestId: context.requestId, taskRunId: context.taskRunId, sessionId: context.sessionId, traceId: context.traceId },
31
+ { name: tool.name, arguments: args, id: context.toolCallId });
32
+ },
33
+ })),
34
+ };
35
+ }
36
+
37
+ module.exports = { createCoordinationCapability, TOOL_PERMISSIONS };
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ module.exports = { createGlobalRoutingCapability: () => ({ id: "global-routing", version: "1", requires: { ports: ["projectRouting"] }, tools: [],
3
+ promptSections: ["You are the global ufoo project router. Select only a registered project. Return a final JSON object with reply and optional project_route={project_root,project_name,prompt,reason}. The project host executes the handoff. You have no coding, agent launch, or project mutation tools."],
4
+ contextSources: [(_input, host) => host.projectRouting.list()],
5
+ }) };
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ const { createCoordinationCapability } = require("../coordination");
3
+ module.exports = { createGroupsCapability: (host) => createCoordinationCapability({ host, id: "groups", toolNames: ["manage_group"] }) };
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+
3
+ const { createCodingCapability } = require("./coding");
4
+ const { createMainPlanningCapability } = require("./planning/main");
5
+ const { createSkillsCapability } = require("./skills");
6
+ const { createAgentManagementCapability } = require("./agentManagement");
7
+ const { createAgentRoutingCapability } = require("./agentRouting");
8
+ const { createProjectDiscoveryCapability } = require("./projectDiscovery");
9
+ const { createSharedMemoryCapability } = require("./sharedMemory");
10
+ const { createTaskReportsCapability } = require("./taskReports");
11
+ const { createTaskExecutionCapability } = require("./taskExecution");
12
+ const { createGroupsCapability } = require("./groups");
13
+ const { createSchedulingCapability } = require("./scheduling");
14
+ const { createGlobalRoutingCapability } = require("./globalRouting");
15
+
16
+ function createMainCapabilities(host) {
17
+ return [createCodingCapability({ workspaceAccess: host.workspaceAccess }), createMainPlanningCapability(), createSkillsCapability(),
18
+ createAgentManagementCapability(host), createAgentRoutingCapability(host), createProjectDiscoveryCapability(host),
19
+ createSharedMemoryCapability(host), createTaskReportsCapability(host), createTaskExecutionCapability(host), createGroupsCapability(host), createSchedulingCapability(host)];
20
+ }
21
+ function createGlobalCapabilities(host) {
22
+ return [createProjectDiscoveryCapability(host), createGlobalRoutingCapability()];
23
+ }
24
+
25
+ module.exports = { createMainCapabilities, createGlobalCapabilities };