u-foo 3.1.6 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/README.md +172 -13
  2. package/README.zh-CN.md +108 -13
  3. package/SKILLS/ufoo/SKILL.md +15 -3
  4. package/SKILLS/ufoo-bus/SKILL.md +21 -1
  5. package/bin/uclaude.js +4 -0
  6. package/bin/ucodex.js +4 -0
  7. package/bin/ufoo.js +3 -1
  8. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  9. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  10. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  11. package/dist/tui/linux-x64/ufoo-tui +0 -0
  12. package/package.json +10 -3
  13. package/scripts/postinstall-skills.js +53 -0
  14. package/scripts/postinstall.js +11 -16
  15. package/scripts/smoke-native-messages.js +214 -0
  16. package/src/agents/activity/activityStateWriter.js +37 -38
  17. package/src/agents/capabilities/agentManagement/index.js +4 -0
  18. package/src/agents/capabilities/agentManagement/service.js +113 -0
  19. package/src/agents/capabilities/agentRouting/index.js +4 -0
  20. package/src/agents/capabilities/coding/index.js +32 -0
  21. package/src/agents/capabilities/coordination/index.js +37 -0
  22. package/src/agents/capabilities/globalRouting/index.js +5 -0
  23. package/src/agents/capabilities/groups/index.js +3 -0
  24. package/src/agents/capabilities/index.js +25 -0
  25. package/src/agents/capabilities/planning/index.js +123 -0
  26. package/src/agents/capabilities/planning/main.js +28 -0
  27. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  28. package/src/agents/capabilities/scheduling/index.js +3 -0
  29. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  30. package/src/agents/capabilities/skills/index.js +12 -0
  31. package/src/agents/capabilities/taskExecution/index.js +3 -0
  32. package/src/agents/capabilities/taskReports/index.js +6 -0
  33. package/src/agents/controller/controllerToolExecutor.js +6 -4
  34. package/src/agents/controller/loopRuntime.js +85 -221
  35. package/src/agents/controller/ufooAgent.js +1 -0
  36. package/src/agents/internal/internalRunner.js +103 -32
  37. package/src/agents/launch/launcher.js +88 -6
  38. package/src/agents/launch/nativeCapabilities.js +40 -0
  39. package/src/agents/launch/nativeMessages.js +362 -0
  40. package/src/agents/launch/notifier.js +13 -18
  41. package/src/agents/launch/readyDetector.js +26 -12
  42. package/src/agents/profiles/coding.js +6 -0
  43. package/src/agents/profiles/globalRouter.js +2 -0
  44. package/src/agents/profiles/main.js +5 -0
  45. package/src/agents/prompts/groupBootstrap.js +10 -0
  46. package/src/agents/prompts/mainAgent.js +39 -0
  47. package/src/agents/prompts/native/tasks.js +2 -2
  48. package/src/agents/prompts/native/ufoo.js +3 -0
  49. package/src/agents/providers/claudeEventTranslator.js +6 -1
  50. package/src/agents/providers/claudeThreadProvider.js +44 -2
  51. package/src/agents/providers/codexEventTranslator.js +47 -7
  52. package/src/agents/providers/codexThreadProvider.js +3 -2
  53. package/src/agents/providers/controllerJsonTransport.js +28 -0
  54. package/src/agents/providers/credentials/claude.js +10 -3
  55. package/src/agents/providers/nativeTransport.js +1135 -0
  56. package/src/agents/providers/runtimeConfig.js +186 -0
  57. package/src/agents/providers/thinkingLevels.js +132 -0
  58. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  59. package/src/agents/providers/transports/index.js +10 -0
  60. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  61. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  62. package/src/agents/providers/transports/responsesProtocol.js +499 -0
  63. package/src/agents/providers/transports/systemBlocks.js +16 -0
  64. package/src/agents/providers/transports/transportContract.js +50 -0
  65. package/src/agents/providers/transports/visionBlocks.js +151 -0
  66. package/src/agents/providers/upstreamTransport.js +13 -4
  67. package/src/agents/runtime/composeCapabilities.js +89 -0
  68. package/src/agents/runtime/context/commandStore.js +43 -0
  69. package/src/agents/runtime/context/contextWindow.js +119 -0
  70. package/src/agents/runtime/context/fileLock.js +36 -0
  71. package/src/agents/runtime/context/runtimeStore.js +126 -0
  72. package/src/agents/runtime/context/sessionJournal.js +360 -0
  73. package/src/agents/runtime/context/sessionStore.js +57 -0
  74. package/src/agents/runtime/core/agentLoop.js +270 -0
  75. package/src/agents/runtime/core/stableJson.js +29 -0
  76. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  77. package/src/agents/runtime/createAgentRuntime.js +247 -0
  78. package/src/agents/runtime/index.js +14 -0
  79. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  80. package/src/agents/runtime/protocol/materialize.js +107 -0
  81. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  82. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  83. package/src/agents/runtime/tasks/scheduler.js +73 -0
  84. package/src/agents/runtime/tools/registry.js +57 -0
  85. package/src/app/chat/ChatController.js +14 -3
  86. package/src/app/chat/agentDirectory.js +8 -2
  87. package/src/app/chat/commandExecutor.js +36 -46
  88. package/src/app/chat/commands.js +14 -7
  89. package/src/app/chat/daemonConnection.js +58 -5
  90. package/src/app/chat/daemonMessageRouter.js +61 -3
  91. package/src/app/chat/inputSubmitHandler.js +14 -2
  92. package/src/app/chat/launchRequestContext.js +42 -0
  93. package/src/app/chat/multiWindow/paneManager.js +85 -165
  94. package/src/app/chat/streamState.js +3 -3
  95. package/src/app/chat/transport.js +1 -1
  96. package/src/app/cli/busCoreCommands.js +9 -0
  97. package/src/app/cli/features/doctor.js +33 -0
  98. package/src/app/cli/features/skills.js +16 -4
  99. package/src/app/cli/reportCoreCommands.js +37 -0
  100. package/src/app/cli/run.js +40 -39
  101. package/src/code/agent.js +16 -4
  102. package/src/code/context/artifacts.js +12 -11
  103. package/src/code/context/assembler.js +2 -1
  104. package/src/code/context/promptLayers.js +1 -13
  105. package/src/code/context/stableJson.js +2 -27
  106. package/src/code/contextWindow.js +2 -117
  107. package/src/code/conversation/sessionJournal.js +3 -349
  108. package/src/code/internalThread.js +100 -0
  109. package/src/code/nativeRunner.js +36 -2668
  110. package/src/code/protocol/faultHarness.js +2 -88
  111. package/src/code/protocol/materialize.js +2 -105
  112. package/src/code/protocol/toolCallLedger.js +5 -215
  113. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  114. package/src/code/providers/openaiChatTransport.js +2 -114
  115. package/src/code/providers/openaiResponsesTransport.js +2 -117
  116. package/src/code/providers/responsesProtocol.js +2 -497
  117. package/src/code/providers/transportContract.js +2 -48
  118. package/src/code/providers/visionBlocks.js +2 -149
  119. package/src/code/sessionStore.js +24 -96
  120. package/src/code/thinkingLevels.js +1 -130
  121. package/src/code/toolLoopGuard.js +3 -49
  122. package/src/code/tools/artifactRead.js +1 -1
  123. package/src/code/tools/executor.js +373 -0
  124. package/src/code/tools/specs.js +312 -0
  125. package/src/config.js +81 -67
  126. package/src/coordination/bus/deliveryQueue.js +16 -2
  127. package/src/coordination/bus/index.js +2 -6
  128. package/src/coordination/bus/inject.js +13 -5
  129. package/src/coordination/bus/nativeReceipts.js +100 -0
  130. package/src/coordination/bus/queue.js +1 -3
  131. package/src/coordination/bus/utils.js +7 -3
  132. package/src/coordination/history/agentSurface.js +142 -0
  133. package/src/coordination/history/controllerSummary.js +23 -0
  134. package/src/coordination/memory/index.js +5 -21
  135. package/src/coordination/report/store.js +103 -83
  136. package/src/coordination/state/agentsStore.js +57 -3
  137. package/src/coordination/state/fileLock.js +2 -0
  138. package/src/coordination/state/workspaceAccess.js +36 -0
  139. package/src/runtime/contracts/agentMode.js +17 -0
  140. package/src/runtime/contracts/eventContract.js +3 -0
  141. package/src/runtime/contracts/uiProtocol.js +4 -0
  142. package/src/runtime/daemon/agentHost.js +375 -0
  143. package/src/runtime/daemon/busBridge.js +396 -0
  144. package/src/runtime/daemon/claudeChannel.js +159 -0
  145. package/src/runtime/daemon/controlPlaneService.js +27 -17
  146. package/src/runtime/daemon/cronOps.js +25 -17
  147. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  148. package/src/runtime/daemon/executionPaths.js +30 -0
  149. package/src/runtime/daemon/globalDaemon.js +28 -1
  150. package/src/runtime/daemon/groupOrchestrator.js +1 -0
  151. package/src/runtime/daemon/index.js +114 -344
  152. package/src/runtime/daemon/ipcServer.js +32 -10
  153. package/src/runtime/daemon/mcpConfigure.js +113 -20
  154. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  155. package/src/runtime/daemon/mcpServer.js +7 -4
  156. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  157. package/src/runtime/daemon/ops.js +22 -17
  158. package/src/runtime/daemon/promptRequest.js +23 -4
  159. package/src/runtime/daemon/providerSessions.js +67 -33
  160. package/src/runtime/daemon/reportControlBus.js +59 -25
  161. package/src/runtime/daemon/status.js +4 -0
  162. package/src/runtime/privacy/redactor.js +2 -2
  163. package/src/runtime/projects/identity.js +2 -1
  164. package/src/runtime/projects/registry.js +98 -38
  165. package/src/tools/controllerSchemas.js +24 -0
  166. package/src/tools/handlers/dispatchMessage.js +5 -2
  167. package/src/tools/handlers/listAgents.js +3 -1
  168. package/src/tools/handlers/readBusSummary.js +3 -1
  169. package/src/tools/handlers/readProjectRegistry.js +29 -2
  170. package/src/tools/handlers/routeAgent.js +35 -0
  171. package/src/tools/index.js +1 -0
  172. package/src/tools/registry.js +2 -0
  173. package/src/tools/schemaFixtures.js +16 -3
  174. package/src/tools/tier1/routeAgent.js +2 -2
  175. package/src/tools/tier2/runtimeCoordination.js +38 -0
  176. package/src/tools/types.js +2 -0
  177. package/src/ui/agentPresentation.js +109 -0
  178. package/src/ui/agentSurface.js +270 -0
  179. package/src/ui/format/banner.js +8 -11
  180. package/src/ui/format/startupBanner.js +50 -0
  181. package/src/ui/multiPaneBusMirror.js +29 -3
  182. package/src/ui/rustChatHost.js +170 -438
  183. package/src/ui/rustMultiSession.js +225 -51
  184. package/src/ui/rustUcodeHost.js +20 -87
  185. package/src/ui/settingsBridge.js +7 -4
  186. package/src/app/chat/agentEnter.js +0 -70
  187. package/src/app/chat/multiWindow/index.js +0 -310
  188. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  189. package/src/app/chat/multiWindow/renderer.js +0 -420
  190. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  191. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  192. package/src/ui/multiWindowHandoff.js +0 -232
  193. package/src/ui/ptyHandoff.js +0 -23
@@ -0,0 +1,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" ? "ufoo-code" : "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 };
@@ -9,7 +9,6 @@ const {
9
9
  releasePollLease,
10
10
  } = require("../../coordination/bus/poll");
11
11
  const { subscriberToSafeName } = require("../../coordination/bus/utils");
12
- const { normalizeReportInput } = require("../../coordination/report/store");
13
12
  const { enqueueAgentReport } = require("./reportControlBus");
14
13
  const { isRunning } = require("./index");
15
14
  const {
@@ -110,8 +109,8 @@ function extendMcpAgentLease(meta, nowMs = Date.now()) {
110
109
 
111
110
  function assertAgentHandle(bus, subscriber, args = {}, options = {}) {
112
111
  const meta = assertSubscriberExists(bus, subscriber);
113
- if (meta.mcp_bridge !== true || !meta.mcp_agent_handle_hash) {
114
- const err = new Error(`subscriber is not an MCP-registered Agent: ${subscriber}`);
112
+ if (!meta.mcp_agent_handle_hash) {
113
+ const err = new Error(`subscriber has no MCP capability: ${subscriber}`);
115
114
  err.code = "agent_handle_not_available";
116
115
  throw err;
117
116
  }
@@ -135,7 +134,7 @@ function assertAgentHandle(bus, subscriber, args = {}, options = {}) {
135
134
  }
136
135
  const expiresAtMs = Date.parse(String(meta.mcp_lease_expires_at || ""));
137
136
  if (
138
- options.allowExpired !== true
137
+ meta.mcp_bridge === true && options.allowExpired !== true
139
138
  && (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now())
140
139
  ) {
141
140
  const err = new Error(`Agent lease expired: ${subscriber}`);
@@ -145,6 +144,13 @@ function assertAgentHandle(bus, subscriber, args = {}, options = {}) {
145
144
  return meta;
146
145
  }
147
146
 
147
+ function assertExternalLifecycle(meta, operation) {
148
+ if (meta.mcp_bridge === true) return;
149
+ const err = new Error(`${operation} is owned by this Agent's wrapper or host`);
150
+ err.code = "managed_agent_lifecycle";
151
+ throw err;
152
+ }
153
+
148
154
  function notifyDaemonRefresh(projectRoot) {
149
155
  const endpoint = resolveDaemonEndpoint(projectRoot);
150
156
  const daemonRoot = endpoint.scope === "global"
@@ -250,9 +256,8 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
250
256
 
251
257
  // Nickname scope and conflict check
252
258
  let finalNickname = nickname;
253
- let scopedNickname = nickname
254
- ? applyProjectNicknamePrefix(projectRoot, nickname, { agentType })
255
- : "";
259
+ let scopedNickname = String(args.scoped_nickname || args.scopedNickname || "").trim()
260
+ || (nickname ? applyProjectNicknamePrefix(projectRoot, nickname, { agentType }) : "");
256
261
  if (checkNicknameConflicts && finalNickname) {
257
262
  const nickCheck = checkAndCleanupNickname(projectRoot, finalNickname, {
258
263
  tty: String(args.tty || ""),
@@ -276,6 +281,7 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
276
281
  hostName: String(args.host_name || args.hostName || "ufoo-mcp"),
277
282
  hostSessionId: String(args.hostSessionId || `mcp-${process.pid}`),
278
283
  hostCapabilities: hostCapabilities,
284
+ providerSessionId: String(args.providerSessionId || ""),
279
285
  scopedNickname: scopedNickname || String(args.scoped_nickname || args.scopedNickname || finalNickname || "").trim(),
280
286
  };
281
287
  if (args.skipSessionResolve) joinOptions.skipSessionResolve = true;
@@ -297,16 +303,16 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
297
303
  const result = await bus.subscriberManager.join(sessionId, agentType, finalNickname, joinOptions);
298
304
  const subscriber = result.subscriber;
299
305
  if (finalNickname) {
300
- bus.subscriberManager.rename(subscriber, finalNickname, "ufoo-agent", { scopedNickname });
306
+ await bus.subscriberManager.rename(subscriber, finalNickname, { scopedNickname });
301
307
  }
302
308
  const meta = bus.subscriberManager.getSubscriber(subscriber) || {};
303
- meta.activity_state = String(args.activity_state || "ready");
309
+ meta.activity_state = String(args.activity_state || (validateParentPid ? "starting" : "ready"));
304
310
  meta.activity_since = nowIso();
305
311
  meta.mcp_bridge = !validateParentPid;
306
- let agentHandle = "";
312
+ const agentHandle = createAgentHandle();
313
+ meta.mcp_agent_handle_hash = hashAgentHandle(agentHandle);
314
+ delete meta.mcp_revoked_at;
307
315
  if (!validateParentPid) {
308
- agentHandle = createAgentHandle();
309
- meta.mcp_agent_handle_hash = hashAgentHandle(agentHandle);
310
316
  meta.mcp_client_instance_id = clientInstanceId;
311
317
  meta.mcp_registered_at = meta.mcp_registered_at || nowIso();
312
318
  extendMcpAgentLease(meta);
@@ -340,7 +346,7 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
340
346
  launch_mode: launchMode,
341
347
  ...(agentHandle ? {
342
348
  agent_handle: agentHandle,
343
- lease_expires_at: meta.mcp_lease_expires_at,
349
+ lease_expires_at: meta.mcp_bridge === true ? meta.mcp_lease_expires_at : null,
344
350
  client_instance_id: clientInstanceId,
345
351
  recovered: Boolean(recoveredSubscriber),
346
352
  ...(supersededSubscribers.length > 0 ? { superseded_subscribers: supersededSubscribers } : {}),
@@ -377,7 +383,7 @@ async function heartbeatAgent(projectRoot, args = {}, options = {}) {
377
383
  const meta = assertAgentHandle(bus, subscriber, args);
378
384
  bus.subscriberManager.updateLastSeen(subscriber);
379
385
  meta.status = "active";
380
- const leaseExpiresAt = extendMcpAgentLease(meta);
386
+ const leaseExpiresAt = meta.mcp_bridge === true ? extendMcpAgentLease(meta) : null;
381
387
  bus.saveBusData();
382
388
  notifyDaemonRefreshIfEnabled(projectRoot, options);
383
389
  return {
@@ -399,6 +405,7 @@ async function publishActivityState(projectRoot, args = {}, options = {}) {
399
405
  }
400
406
  const bus = ensureBusLoaded(projectRoot);
401
407
  const meta = assertAgentHandle(bus, subscriber, args);
408
+ assertExternalLifecycle(meta, "publish_activity_state");
402
409
  bus.subscriberManager.updateLastSeen(subscriber);
403
410
  meta.status = "active";
404
411
  meta.activity_state = activityState;
@@ -569,6 +576,7 @@ async function waitForMessage(projectRoot, args = {}, options = {}) {
569
576
  const timeoutMs = timeoutSeconds > 0 ? timeoutSeconds * 1000 : null;
570
577
 
571
578
  const bus = ensureBusLoaded(projectRoot);
579
+ assertExternalLifecycle(assertAgentHandle(bus, subscriber, args), "wait_for_message");
572
580
  touchWaitingSubscriber(bus, subscriber, args);
573
581
  const lease = acquirePollLease(path.join(
574
582
  bus.busDir,
@@ -649,12 +657,13 @@ async function reportAgentStatus(projectRoot, args = {}) {
649
657
  const subscriber = resolveSubscriberArg(args);
650
658
  const bus = ensureBusLoaded(projectRoot);
651
659
  assertAgentHandle(bus, subscriber, args);
652
- const report = normalizeReportInput({
660
+ const reportInput = {
653
661
  ...args,
654
662
  agent_id: subscriber,
655
663
  source: "mcp",
656
- });
657
- const queued = await enqueueAgentReport(projectRoot, report, { publisher: subscriber });
664
+ };
665
+ const queued = await enqueueAgentReport(projectRoot, reportInput, { publisher: subscriber });
666
+ const report = queued.report;
658
667
  return {
659
668
  ok: true,
660
669
  project_root: projectRoot,
@@ -672,6 +681,7 @@ async function unregisterAgent(projectRoot, args = {}, options = {}) {
672
681
  allowExpired: true,
673
682
  allowInactive: true,
674
683
  });
684
+ assertExternalLifecycle(meta, "unregister_agent");
675
685
  meta.mcp_revoked_at = nowIso();
676
686
  meta.mcp_lease_expires_at = meta.mcp_revoked_at;
677
687
  const ok = await bus.subscriberManager.leave(subscriber);