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,70 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { getUfooPaths } = require("../../coordination/state/paths");
6
+ const { updateAgentsData } = require("../../coordination/state/agentsStore");
7
+ const { withFileLock } = require("../../coordination/state/fileLock");
8
+
9
+ const validGroupId = (id) => typeof id === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(id);
10
+
11
+ function loadRecoveryGroups(projectRoot) {
12
+ const dir = getUfooPaths(projectRoot).groupsDir;
13
+ if (!fs.existsSync(dir)) return [];
14
+ const groups = [];
15
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
16
+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
17
+ try {
18
+ const runtime = JSON.parse(fs.readFileSync(path.join(dir, entry.name), "utf8"));
19
+ if (validGroupId(runtime.group_id) && entry.name === `${runtime.group_id}.json` && Array.isArray(runtime.members)) groups.push(runtime);
20
+ } catch { /* A damaged group must not hide other recoverable sessions. */ }
21
+ }
22
+ return groups;
23
+ }
24
+
25
+ function resolveRecoveryGroup(groups, subscriberId, meta = {}) {
26
+ const matches = groups.filter((group) => group.members.some((member) => member?.subscriber_id === subscriberId));
27
+ const group = meta.group_id
28
+ ? groups.find((item) => item.group_id === meta.group_id)
29
+ : matches.length === 1 ? matches[0] : null;
30
+ const groupId = group?.group_id || (validGroupId(meta.group_id) ? meta.group_id : "");
31
+ const member = group?.members.find((item) => item?.subscriber_id === subscriberId);
32
+ return {
33
+ group_id: groupId,
34
+ group_member_id: member?.id || meta.group_member_id || "",
35
+ group_template_alias: group?.template_alias || meta.group_template_alias || "",
36
+ };
37
+ }
38
+
39
+ function associateAgentWithGroup(projectRoot, subscriberId, association) {
40
+ if (!subscriberId || !validGroupId(association.group_id)) return;
41
+ updateAgentsData(getUfooPaths(projectRoot).agentsFile, (data) => {
42
+ const meta = data.agents[subscriberId];
43
+ if (!meta) return false;
44
+ Object.assign(meta, association);
45
+ });
46
+ }
47
+
48
+ function recordGroupMemberResume(projectRoot, association, previousId, subscriberId) {
49
+ if (!validGroupId(association.group_id)) return;
50
+ const file = path.join(getUfooPaths(projectRoot).groupsDir, `${association.group_id}.json`);
51
+ if (!fs.existsSync(file)) return;
52
+ withFileLock(file, () => {
53
+ const runtime = JSON.parse(fs.readFileSync(file, "utf8"));
54
+ const member = runtime.members?.find((item) => item.subscriber_id === previousId);
55
+ if (!member) return;
56
+ const now = new Date().toISOString();
57
+ member.previous_subscriber_id = previousId;
58
+ member.subscriber_id = subscriberId;
59
+ if (member.bootstrapped_subscriber_id === previousId) member.bootstrapped_subscriber_id = subscriberId;
60
+ member.status = "active";
61
+ member.resumed_at = now;
62
+ delete member.stop;
63
+ member.launch = { ...member.launch, mode: "internal", subscriber_ids: [subscriberId], resumed: true };
64
+ runtime.status = runtime.members.every((item) => ["active", "reused"].includes(item.status)) ? "active" : "partial";
65
+ runtime.updated_at = now;
66
+ fs.writeFileSync(file, `${JSON.stringify(runtime, null, 2)}\n`, "utf8");
67
+ });
68
+ }
69
+
70
+ module.exports = { loadRecoveryGroups, resolveRecoveryGroup, associateAgentWithGroup, recordGroupMemberResume };
@@ -0,0 +1,396 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const EventBus = require("../../coordination/bus");
6
+ const { DeliveryQueue } = require("../../coordination/bus/deliveryQueue");
7
+ const { subscriberToSafeName } = require("../../coordination/bus/utils");
8
+ const { getUfooPaths } = require("../../coordination/state/paths");
9
+ const { BUS_STATUS_PHASES } = require("../contracts/eventContract");
10
+ const { isInternalAgentMeta, isInternalDashboardEvent } = require("../contracts/agentMode");
11
+ const { isAgentReportControlEvent, extractAgentReportControl, drainReportControlEvents } = require("./reportControlBus");
12
+
13
+ function startBusBridge(
14
+ projectRoot,
15
+ provider,
16
+ onEvent,
17
+ onStatus,
18
+ shouldDrain,
19
+ onReport,
20
+ options = {}
21
+ ) {
22
+ const state = {
23
+ subscriber: null,
24
+ queueFile: null,
25
+ pending: new Set(),
26
+ watchedAgents: new Set(),
27
+ lastEventSeq: 0,
28
+ emittedEventKeys: [],
29
+ emittedEventKeySet: new Set(),
30
+ };
31
+ const eventBus = options.eventBus || new EventBus(projectRoot);
32
+ const reportJoinError = typeof options.onJoinError === "function"
33
+ ? options.onJoinError
34
+ : () => {};
35
+ let joinInProgress = null;
36
+ let lastJoinError = "";
37
+ let stopped = false;
38
+ let polling = false;
39
+ let observationWatch = null;
40
+ let observationTimer = null;
41
+ const eventCursors = new Map();
42
+ let watchStartSeq = 0;
43
+
44
+ function watchObservations() {
45
+ if (observationWatch || stopped || state.watchedAgents.size === 0) return;
46
+ try {
47
+ observationWatch = fs.watch(getUfooPaths(projectRoot).busEventsDir, () => {
48
+ if (stopped || observationTimer) return;
49
+ observationTimer = setTimeout(() => {
50
+ observationTimer = null;
51
+ poll().catch(() => {});
52
+ }, 25);
53
+ observationTimer.unref?.();
54
+ });
55
+ observationWatch.unref?.();
56
+ observationWatch.on("error", () => { observationWatch?.close(); observationWatch = null; });
57
+ } catch { /* The regular poll also retries after workspace initialization. */ }
58
+ }
59
+
60
+ function getAgentNickname(agentId) {
61
+ if (!agentId) return agentId;
62
+ try {
63
+ const busPath = getUfooPaths(projectRoot).agentsFile;
64
+ const bus = JSON.parse(fs.readFileSync(busPath, "utf8"));
65
+ const meta = bus.agents && bus.agents[agentId];
66
+ if (meta && meta.nickname) {
67
+ return meta.nickname;
68
+ }
69
+ } catch {
70
+ // Ignore errors, return original ID
71
+ }
72
+ return agentId;
73
+ }
74
+
75
+ function getEventDedupeKey(evt) {
76
+ if (!evt || typeof evt !== "object") return "";
77
+ const seq = Number(evt.seq);
78
+ if (Number.isFinite(seq) && seq > 0) return `seq:${seq}`;
79
+ return [
80
+ "event",
81
+ evt.timestamp || evt.ts || "",
82
+ evt.event || "",
83
+ evt.publisher || "",
84
+ evt.target || "",
85
+ JSON.stringify(evt.data || {}),
86
+ ].join(":");
87
+ }
88
+
89
+ function rememberEmittedEvent(evt) {
90
+ const key = getEventDedupeKey(evt);
91
+ if (!key) return false;
92
+ if (state.emittedEventKeySet.has(key)) return true;
93
+ state.emittedEventKeySet.add(key);
94
+ state.emittedEventKeys.push(key);
95
+ if (state.emittedEventKeys.length > 500) {
96
+ const removed = state.emittedEventKeys.splice(0, state.emittedEventKeys.length - 500);
97
+ for (const item of removed) state.emittedEventKeySet.delete(item);
98
+ }
99
+ return false;
100
+ }
101
+
102
+ function hasPositiveSeq(seq) {
103
+ const value = Number(seq);
104
+ return Number.isFinite(value) && value > 0;
105
+ }
106
+
107
+ function toBridgeEvent(evt) {
108
+ const data = evt.data && typeof evt.data === "object" ? evt.data : {};
109
+ return {
110
+ seq: evt.seq,
111
+ event: evt.event,
112
+ publisher: evt.publisher,
113
+ target: evt.target,
114
+ data,
115
+ message: data.message || "",
116
+ state: data.state || "",
117
+ previous: data.previous || "",
118
+ subscriber: data.subscriber || "",
119
+ source: data.source || "",
120
+ injection_mode: data.injection_mode || "",
121
+ ts: evt.timestamp || evt.ts,
122
+ };
123
+ }
124
+
125
+ function emitBusEvent(evt) {
126
+ if (!evt || !onEvent) return;
127
+ if (options.internalOnly && !acceptsEvent(evt)) return;
128
+ if (rememberEmittedEvent(evt)) return;
129
+ onEvent(toBridgeEvent(evt));
130
+ }
131
+
132
+ function readAgentsData() {
133
+ try {
134
+ const busPath = getUfooPaths(projectRoot).agentsFile;
135
+ return JSON.parse(fs.readFileSync(busPath, "utf8"));
136
+ } catch {
137
+ return {};
138
+ }
139
+ }
140
+
141
+ function acceptsEvent(evt) {
142
+ const agents = readAgentsData().agents || {};
143
+ return isInternalDashboardEvent(toBridgeEvent(evt), (id) => agents[id]);
144
+ }
145
+
146
+ function buildWatchedAliases() {
147
+ const aliases = new Set();
148
+ const bus = readAgentsData();
149
+ for (const agentId of state.watchedAgents) {
150
+ const meta = bus.agents && bus.agents[agentId];
151
+ if (options.internalOnly && !isInternalAgentMeta(meta)) {
152
+ state.watchedAgents.delete(agentId);
153
+ continue;
154
+ }
155
+ aliases.add(agentId);
156
+ if (!meta) continue;
157
+ if (meta.nickname) aliases.add(meta.nickname);
158
+ if (meta.scoped_nickname) aliases.add(meta.scoped_nickname);
159
+ if (meta.display_nickname) aliases.add(meta.display_nickname);
160
+ }
161
+ return aliases;
162
+ }
163
+
164
+ function isWatchedEvent(evt, aliases = buildWatchedAliases()) {
165
+ if (!evt || !["message", "activity_state_changed", "agent_surface"].includes(evt.event)) return false;
166
+ const publisher = String(evt.publisher || "");
167
+ const target = String(evt.target || "");
168
+ const subscriber = evt.data && evt.data.subscriber ? String(evt.data.subscriber) : "";
169
+ return aliases.has(publisher) || aliases.has(target) || aliases.has(subscriber);
170
+ }
171
+
172
+ function getEventFiles() {
173
+ try {
174
+ const dir = getUfooPaths(projectRoot).busEventsDir;
175
+ return fs.readdirSync(dir)
176
+ .filter((name) => name.endsWith(".jsonl"))
177
+ .sort()
178
+ .map((name) => path.join(dir, name));
179
+ } catch {
180
+ return [];
181
+ }
182
+ }
183
+
184
+ function readCurrentSeq() {
185
+ try {
186
+ const raw = fs.readFileSync(path.join(getUfooPaths(projectRoot).busDir, "seq.counter"), "utf8").trim();
187
+ const seq = Number(raw);
188
+ return Number.isFinite(seq) ? seq : 0;
189
+ } catch {
190
+ return 0;
191
+ }
192
+ }
193
+
194
+ function readEventFile(file) {
195
+ let fd;
196
+ try {
197
+ fd = fs.openSync(file, "r");
198
+ const size = fs.fstatSync(fd).size;
199
+ let cursor = eventCursors.get(file) || { offset: 0, partial: Buffer.alloc(0) };
200
+ if (size < cursor.offset) cursor = { offset: 0, partial: Buffer.alloc(0) };
201
+ const buffer = Buffer.alloc(Math.min(size - cursor.offset, 512 * 1024));
202
+ const read = fs.readSync(fd, buffer, 0, buffer.length, cursor.offset);
203
+ cursor.offset += read;
204
+ const content = Buffer.concat([cursor.partial, buffer.subarray(0, read)]);
205
+ const end = content.lastIndexOf(10);
206
+ cursor.partial = content.subarray(end + 1);
207
+ eventCursors.set(file, cursor);
208
+ if (end < 0) return [];
209
+ return content.subarray(0, end).toString("utf8")
210
+ .split(/\r?\n/)
211
+ .filter(Boolean)
212
+ .map((line) => {
213
+ try {
214
+ return JSON.parse(line);
215
+ } catch {
216
+ return null;
217
+ }
218
+ })
219
+ .filter(Boolean);
220
+ } catch {
221
+ return [];
222
+ } finally {
223
+ if (fd !== undefined) fs.closeSync(fd);
224
+ }
225
+ }
226
+
227
+ function pollWatchedEvents() {
228
+ if (state.watchedAgents.size === 0) {
229
+ state.lastEventSeq = readCurrentSeq();
230
+ return;
231
+ }
232
+ const aliases = buildWatchedAliases();
233
+ let maxSeq = state.lastEventSeq;
234
+ for (const file of getEventFiles().slice(-2)) {
235
+ for (const evt of readEventFile(file)) {
236
+ const seq = Number(evt.seq);
237
+ if (hasPositiveSeq(seq)) {
238
+ // Append order can differ from sequence allocation across processes.
239
+ // File cursors and emission dedupe avoid dropping a late append.
240
+ if (seq <= watchStartSeq) continue;
241
+ if (seq > maxSeq) maxSeq = seq;
242
+ }
243
+ if (isWatchedEvent(evt, aliases)) emitBusEvent(evt);
244
+ }
245
+ }
246
+ state.lastEventSeq = Math.max(state.lastEventSeq, maxSeq);
247
+ }
248
+
249
+ async function ensureSubscriber() {
250
+ if (stopped || state.subscriber) return state.subscriber;
251
+ if (joinInProgress) return joinInProgress;
252
+ joinInProgress = (async () => {
253
+ try {
254
+ // Determine agent type based on provider configuration
255
+ const agentType = provider === "codex-cli" ? "codex" : (provider === "ucode" ? "ucode" : "claude-code");
256
+ // Use fixed ID "ufoo-agent" for daemon's bus identity with explicit nickname
257
+ const sub = await eventBus.join("ufoo-agent", agentType, "ufoo-agent");
258
+ if (!sub || stopped) return null;
259
+ state.subscriber = sub;
260
+ const safe = subscriberToSafeName(sub);
261
+ state.queueFile = path.join(getUfooPaths(projectRoot).busQueuesDir, safe, "pending.jsonl");
262
+ lastJoinError = "";
263
+ return sub;
264
+ } catch (err) {
265
+ const detail = err && err.message ? err.message : String(err || "unknown join error");
266
+ if (detail !== lastJoinError) {
267
+ lastJoinError = detail;
268
+ try {
269
+ reportJoinError(err);
270
+ } catch {
271
+ // Diagnostics must never turn a recoverable join failure into an
272
+ // unhandled rejection in the process-wide global daemon.
273
+ }
274
+ }
275
+ return null;
276
+ } finally {
277
+ joinInProgress = null;
278
+ }
279
+ })();
280
+ return joinInProgress;
281
+ }
282
+
283
+ async function handleReportControlEvent(evt) {
284
+ if (!isAgentReportControlEvent(evt)) return false;
285
+ if (typeof onReport !== "function") return false;
286
+ const control = extractAgentReportControl(evt);
287
+ if (!control) return false;
288
+ await onReport(control.report, {
289
+ event: evt,
290
+ requestId: control.request_id,
291
+ queuedAt: control.queued_at,
292
+ });
293
+ if (["done", "error"].includes(control.report.phase)) {
294
+ const agentId = control.report.agent_id || evt.publisher;
295
+ const reportState = require("../../coordination/report/store").loadReportState(projectRoot);
296
+ if (!reportState.agents[agentId]?.pending_count && state.pending.delete(agentId) && onStatus) {
297
+ onStatus({ phase: control.report.phase === "error" ? BUS_STATUS_PHASES.ERROR : BUS_STATUS_PHASES.DONE,
298
+ text: `${getAgentNickname(agentId)} ${control.report.phase}`, key: agentId });
299
+ }
300
+ }
301
+ return true;
302
+ }
303
+
304
+ async function pollReportControlQueue() {
305
+ await drainReportControlEvents(projectRoot, handleReportControlEvent);
306
+ }
307
+
308
+ async function pollQueue() {
309
+ if (!state.queueFile) return;
310
+ const queue = new DeliveryQueue(state.queueFile);
311
+ queue.recover();
312
+ while (true) {
313
+ const claim = queue.claimNext();
314
+ if (!claim) break;
315
+ const evt = claim.event;
316
+ if (!evt) {
317
+ queue.completeClaim(claim);
318
+ continue;
319
+ }
320
+ try {
321
+ if (evt.event === "message" && typeof options.onMessage === "function"
322
+ && (!options.internalOnly || acceptsEvent(evt))) await options.onMessage(toBridgeEvent(evt));
323
+ emitBusEvent(evt);
324
+ queue.completeClaim(claim);
325
+ } catch {
326
+ queue.restoreClaim(claim);
327
+ break;
328
+ }
329
+ }
330
+ }
331
+
332
+ async function poll() {
333
+ if (polling) return;
334
+ polling = true;
335
+ try {
336
+ await ensureSubscriber();
337
+ watchObservations();
338
+ await pollReportControlQueue();
339
+ if (typeof shouldDrain === "function" && !shouldDrain() && typeof options.onMessage !== "function") return;
340
+ await pollQueue();
341
+ pollWatchedEvents();
342
+ } finally {
343
+ polling = false;
344
+ }
345
+ }
346
+
347
+ const interval = setInterval(() => {
348
+ poll().catch(() => {});
349
+ }, 1000);
350
+ return {
351
+ markPending(target) {
352
+ if (!target) return;
353
+ state.pending.add(target);
354
+ if (onStatus) {
355
+ const displayName = getAgentNickname(target);
356
+ onStatus({ phase: BUS_STATUS_PHASES.START, text: `${displayName} processing`, key: target });
357
+ }
358
+ },
359
+ getSubscriber() {
360
+ void ensureSubscriber();
361
+ return state.subscriber;
362
+ },
363
+ refresh() {
364
+ return poll();
365
+ },
366
+ watchAgent(agentId, enabled = true) {
367
+ if (!agentId) return;
368
+ if (enabled && options.internalOnly && !isInternalAgentMeta(readAgentsData().agents?.[agentId])) return;
369
+ if (enabled) {
370
+ if (state.watchedAgents.size === 0) {
371
+ watchStartSeq = readCurrentSeq();
372
+ state.lastEventSeq = watchStartSeq;
373
+ eventCursors.clear();
374
+ for (const file of getEventFiles().slice(-2)) {
375
+ try { eventCursors.set(file, { offset: fs.statSync(file).size, partial: Buffer.alloc(0) }); } catch {}
376
+ }
377
+ }
378
+ state.watchedAgents.add(agentId);
379
+ watchObservations();
380
+ } else {
381
+ state.watchedAgents.delete(agentId);
382
+ if (state.watchedAgents.size === 0) {
383
+ state.lastEventSeq = readCurrentSeq();
384
+ }
385
+ }
386
+ },
387
+ stop() {
388
+ stopped = true;
389
+ clearInterval(interval);
390
+ if (observationTimer) clearTimeout(observationTimer);
391
+ observationWatch?.close();
392
+ },
393
+ };
394
+ }
395
+
396
+ module.exports = { startBusBridge };
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const net = require("net");
5
+ const crypto = require("crypto");
6
+ const { Server } = require("@modelcontextprotocol/sdk/server/index.js");
7
+ const { StdioServerTransport } = require("@modelcontextprotocol/sdk/server/stdio.js");
8
+ const { ListToolsRequestSchema, CallToolRequestSchema } = require("@modelcontextprotocol/sdk/types.js");
9
+ const { ensureBusLoaded, assertAgentHandle } = require("./controlPlaneService");
10
+ const { setNativeMetadata, nativeError } = require("../../agents/launch/nativeMessages");
11
+ const { getToolDefinition } = require("../../tools/registry");
12
+
13
+ async function createClaudeChannel(options = {}) {
14
+ const projectRoot = options.projectRoot || process.cwd();
15
+ const subscriber = options.subscriber || process.env.UFOO_SUBSCRIBER_ID;
16
+ const agentHandle = options.agentHandle || process.env.UFOO_AGENT_HANDLE;
17
+ const socketPath = options.socketPath || process.env.UFOO_NATIVE_CHANNEL_SOCK;
18
+ if (!subscriber || !agentHandle || !socketPath) throw nativeError("Claude channel must be launched by a ufoo host");
19
+ const authenticate = () => {
20
+ const bus = ensureBusLoaded(projectRoot);
21
+ const meta = assertAgentHandle(bus, subscriber, { agent_handle: agentHandle });
22
+ if (meta.mcp_bridge === true || meta.native_delivery !== "claude_channel" || meta.native_delivery_instance !== socketPath) {
23
+ throw nativeError("Claude channel requires its managed host identity");
24
+ }
25
+ return bus;
26
+ };
27
+ authenticate();
28
+ const nonce = crypto.randomBytes(24).toString("hex");
29
+ let ready = false;
30
+ let closing = false;
31
+ const clients = new Set();
32
+ const receipts = new Map();
33
+ const probeTimers = new Set();
34
+ const stopProbes = () => { for (const timer of probeTimers) clearTimeout(timer); probeTimers.clear(); };
35
+ const sharedNames = ["dispatch_message", "ack_bus"];
36
+ const server = new Server({ name: "ufoo_channel", version: require("../../../package.json").version }, {
37
+ capabilities: { experimental: { "claude/channel": {} }, tools: {} },
38
+ instructions: "ufoo messages arrive through this channel. Only call channel_ready after receiving its native startup probe, using the probe nonce. Channel dispatch_message and ack_bus are bound to your host identity; do not provide another subscriber or handle. Process bus messages and acknowledge their through_seq. Send a reply only when there is a concrete result for the sender. Sending confirms queue persistence, not task completion.",
39
+ });
40
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [
41
+ { name: "channel_ready", description: "Confirm receipt of the native channel startup probe; its nonce is present only in that event.",
42
+ inputSchema: { type: "object", properties: { nonce: { type: "string" } }, required: ["nonce"], additionalProperties: false } },
43
+ ...sharedNames.map((name) => {
44
+ const tool = getToolDefinition(name);
45
+ return { name, description: tool.description, inputSchema: tool.input_schema };
46
+ }),
47
+ ] }));
48
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
49
+ try {
50
+ const bus = authenticate();
51
+ const args = request.params.arguments || {};
52
+ let result;
53
+ if (request.params.name === "channel_ready") {
54
+ if (args.nonce !== nonce) throw nativeError("Invalid channel probe receipt");
55
+ ready = true;
56
+ stopProbes();
57
+ setNativeMetadata(projectRoot, subscriber, { native_delivery_ready: true });
58
+ result = { ok: true, subscriber, channel_ready: true };
59
+ } else {
60
+ if (!sharedNames.includes(request.params.name)) throw nativeError("Unknown channel tool");
61
+ if (args.agent_handle || args.project_root || (args.subscriber && args.subscriber !== subscriber)) {
62
+ throw nativeError("Channel tools are bound to this host identity");
63
+ }
64
+ const tool = getToolDefinition(request.params.name);
65
+ result = await tool.handler({ projectRoot, subscriber, callerTier: "worker", eventBus: bus }, args);
66
+ }
67
+ return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
68
+ } catch (err) {
69
+ return { isError: true, content: [{ type: "text", text: err.message }] };
70
+ }
71
+ });
72
+ const listener = net.createServer((client) => {
73
+ clients.add(client);
74
+ client.on("error", () => {});
75
+ client.once("close", () => clients.delete(client));
76
+ client.setTimeout(10000, () => client.destroy());
77
+ let buffer = "";
78
+ let handled = false;
79
+ client.on("data", (data) => {
80
+ if (handled) return;
81
+ buffer += data;
82
+ if (buffer.length > 1024 * 1024) { client.destroy(); return; }
83
+ if (!buffer.includes("\n")) return;
84
+ handled = true;
85
+ void (async () => {
86
+ const request = JSON.parse(buffer.slice(0, buffer.indexOf("\n")));
87
+ authenticate();
88
+ if (!ready || closing) throw nativeError("Claude has not confirmed native channel readiness");
89
+ if (typeof request.command !== "string" || !request.command.trim() || !request.deliveryId) throw nativeError("Invalid native delivery request");
90
+ const id = String(request.deliveryId);
91
+ const digest = crypto.createHash("sha256").update(request.command).digest("hex");
92
+ let previous = receipts.get(id);
93
+ if (previous && previous.digest !== digest) throw nativeError("Delivery ID was reused for different content");
94
+ if (previous?.failed && request.retryAuthorized === true) {
95
+ receipts.delete(id);
96
+ previous = null;
97
+ }
98
+ if (!previous) {
99
+ // Record before the write. Never emit the same event twice if its
100
+ // socket receipt is lost; the host also keeps durable write receipts.
101
+ const receipt = { digest };
102
+ receipts.set(id, receipt);
103
+ receipt.write = server.notification({ method: "notifications/claude/channel", params: {
104
+ content: request.command,
105
+ meta: { subscriber, delivery_id: id, ...(request.through_seq ? { through_seq: String(request.through_seq) } : {}) },
106
+ } }).catch((error) => { receipt.failed = true; throw error; });
107
+ }
108
+ // Concurrent socket retries share the write and its failure outcome.
109
+ await receipts.get(id).write;
110
+ client.end(`${JSON.stringify({ ok: true, queued: true })}\n`);
111
+ })().catch((err) => {
112
+ if (!client.destroyed) client.end(`${JSON.stringify({ ok: false, error: err.message, code: err.code || "native_outcome_unknown" })}\n`);
113
+ });
114
+ });
115
+ });
116
+ await new Promise((resolve, reject) => { listener.once("error", reject); listener.listen(socketPath, resolve); });
117
+ fs.chmodSync(socketPath, 0o600);
118
+ const close = async () => {
119
+ if (closing) return;
120
+ closing = true;
121
+ ready = false;
122
+ stopProbes();
123
+ try {
124
+ authenticate();
125
+ setNativeMetadata(projectRoot, subscriber, { native_delivery_ready: false });
126
+ } catch { /* host may already have left or replaced this receiver */ }
127
+ for (const client of clients) client.destroy();
128
+ await new Promise((resolve) => listener.close(resolve));
129
+ fs.rmSync(socketPath, { force: true });
130
+ await server.close();
131
+ };
132
+ server.onclose = () => { void close(); };
133
+ server.oninitialized = () => {
134
+ // Claude installs its channel notification handler after initialization.
135
+ // An immediate notification can be lost before that handler exists.
136
+ for (const delay of [250, 1000, 3000]) {
137
+ const timer = setTimeout(() => {
138
+ probeTimers.delete(timer);
139
+ if (ready || closing) return;
140
+ void server.notification({ method: "notifications/claude/channel", params: {
141
+ content: `ufoo native channel startup probe. Call channel_ready with nonce ${nonce} to confirm this event arrived. This probe is not a user task.`,
142
+ meta: { kind: "startup_probe" },
143
+ } }).catch(() => close());
144
+ }, delay);
145
+ probeTimers.add(timer);
146
+ }
147
+ };
148
+ try { await server.connect(options.transport || new StdioServerTransport()); }
149
+ catch (err) { await close(); throw err; }
150
+ return { server, close, socketPath };
151
+ }
152
+
153
+ async function runClaudeChannel() {
154
+ const channel = await createClaudeChannel();
155
+ for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => { void channel.close().finally(() => process.exit(0)); });
156
+ return channel;
157
+ }
158
+
159
+ module.exports = { createClaudeChannel, runClaudeChannel };