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
@@ -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 {
@@ -41,7 +40,7 @@ function normalizeBusAgentType(agentType = "") {
41
40
  const value = String(agentType || "").trim().toLowerCase();
42
41
  if (!value) return "mcp-agent";
43
42
  if (value === "claude") return "claude-code";
44
- if (value === "ucode" || value === "ufoo") return "ufoo-code";
43
+ if (value === "ucode") return "ucode";
45
44
  return value;
46
45
  }
47
46
 
@@ -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);
@@ -1,5 +1,6 @@
1
1
  const fs = require("fs");
2
2
  const path = require("path");
3
+ const { randomUUID } = require("crypto");
3
4
  const { getUfooPaths } = require("../../coordination/state/paths");
4
5
  const {
5
6
  parseIntervalMs,
@@ -231,17 +232,21 @@ function createDaemonCronController(options = {}) {
231
232
  createdAt: task.createdAt,
232
233
  lastRunAt: task.lastRunAt,
233
234
  tickCount: task.tickCount,
235
+ scheduleId: task.scheduleId,
234
236
  })),
235
237
  };
236
238
 
239
+ const tmpFile = `${persistedFile}.${randomUUID()}.tmp`;
237
240
  try {
238
241
  fsModule.mkdirSync(pathModule.dirname(persistedFile), { recursive: true });
239
- const tmpFile = `${persistedFile}.tmp`;
240
- fsModule.writeFileSync(tmpFile, JSON.stringify(state, null, 2), "utf8");
242
+ fsModule.writeFileSync(tmpFile, JSON.stringify(state, null, 2), { encoding: "utf8", mode: 0o600 });
241
243
  fsModule.renameSync(tmpFile, persistedFile);
242
244
  } catch (err) {
243
245
  const detail = err && err.message ? err.message : String(err || "persist failed");
244
246
  log(`cron persist failed: ${detail}`);
247
+ throw err;
248
+ } finally {
249
+ try { fsModule.unlinkSync(tmpFile); } catch {}
245
250
  }
246
251
  }
247
252
 
@@ -263,13 +268,18 @@ function createDaemonCronController(options = {}) {
263
268
  }
264
269
 
265
270
  function runTask(task) {
271
+ if (!tasks.includes(task)) return;
272
+ const previous = { lastRunAt: task.lastRunAt, tickCount: task.tickCount };
266
273
  task.lastRunAt = nowFn();
267
274
  task.tickCount += 1;
275
+ // Reserve the occurrence before effects. A restart never sends this tick twice.
276
+ try { persistState(); } catch (error) { Object.assign(task, previous); throw error; }
268
277
 
269
278
  for (const target of task.targets) {
270
279
  try {
271
280
  Promise.resolve(dispatch({
272
281
  taskId: task.id,
282
+ occurrenceId: `${task.scheduleId}:${task.tickCount}`,
273
283
  target,
274
284
  message: task.prompt,
275
285
  })).catch((err) => {
@@ -290,9 +300,9 @@ function createDaemonCronController(options = {}) {
290
300
  if (idx < 0) return false;
291
301
 
292
302
  const task = tasks[idx];
293
- clearTaskTimer(task);
294
303
  tasks.splice(idx, 1);
295
- persistState();
304
+ try { persistState(); } catch (error) { tasks.splice(idx, 0, task); throw error; }
305
+ clearTaskTimer(task);
296
306
  return true;
297
307
  }
298
308
 
@@ -300,15 +310,13 @@ function createDaemonCronController(options = {}) {
300
310
  if (task.onceAtMs > 0) {
301
311
  const delay = Math.max(0, task.onceAtMs - nowFn());
302
312
  task.timer = detachTimer(setTimeoutFn(() => {
303
- runTask(task);
304
- stopTask(task.id);
313
+ try { runTask(task); stopTask(task.id); } catch (error) { log(`cron occurrence not dispatched: ${error.message}`); }
305
314
  }, delay));
306
315
  return;
307
316
  }
308
317
 
309
318
  task.timer = detachTimer(setIntervalFn(() => {
310
- runTask(task);
311
- persistState();
319
+ try { runTask(task); } catch (error) { log(`cron occurrence not dispatched: ${error.message}`); }
312
320
  }, task.intervalMs));
313
321
  }
314
322
 
@@ -338,13 +346,14 @@ function createDaemonCronController(options = {}) {
338
346
  createdAt: nowFn(),
339
347
  lastRunAt: 0,
340
348
  tickCount: 0,
349
+ scheduleId: randomUUID(),
341
350
  timer: null,
342
351
  };
343
352
 
344
- attachTaskTimer(task);
345
- runTask(task);
346
353
  tasks.push(task);
347
- persistState();
354
+ try { persistState(); } catch (error) { tasks.pop(); throw error; }
355
+ attachTaskTimer(task);
356
+ if (!useOnce) runTask(task);
348
357
 
349
358
  return formatCronTask(task);
350
359
  }
@@ -356,11 +365,9 @@ function createDaemonCronController(options = {}) {
356
365
  function stopAll() {
357
366
  if (tasks.length === 0) return 0;
358
367
  const count = tasks.length;
359
- while (tasks.length > 0) {
360
- const task = tasks.pop();
361
- clearTaskTimer(task);
362
- }
363
- persistState();
368
+ const removed = tasks.splice(0);
369
+ try { persistState(); } catch (error) { tasks.push(...removed); throw error; }
370
+ removed.forEach(clearTaskTimer);
364
371
  return count;
365
372
  }
366
373
 
@@ -415,7 +422,7 @@ function createDaemonCronController(options = {}) {
415
422
  }
416
423
 
417
424
  if (Number.isFinite(onceAtMs) && onceAtMs > 0) {
418
- if (onceAtMs <= now) {
425
+ if (Number(item.tickCount) > 0) {
419
426
  changed = true;
420
427
  continue;
421
428
  }
@@ -434,6 +441,7 @@ function createDaemonCronController(options = {}) {
434
441
  createdAt: Number(item && item.createdAt) || now,
435
442
  lastRunAt: Number(item && item.lastRunAt) || 0,
436
443
  tickCount: Number(item && item.tickCount) || 0,
444
+ scheduleId: item.scheduleId || `legacy-${rawId}-${Number(item.createdAt) || now}`,
437
445
  timer: null,
438
446
  };
439
447
 
@@ -191,6 +191,18 @@ class DeliveryScheduler {
191
191
  if (meta.mcp_bridge === true) {
192
192
  return { ok: false, reason: "external_receive" };
193
193
  }
194
+ // Startup confirmation is a transport gate, not a stale activity sample.
195
+ // Even immediate messages and queue-age overrides must wait for the host.
196
+ if (meta.launcher_ready === false) {
197
+ return { ok: false, reason: "launcher_not_ready" };
198
+ }
199
+ if (meta.native_delivery) {
200
+ // The provider queues work while busy. PTY activity snapshots must not
201
+ // gate a native receive, including messages waiting for the next turn.
202
+ return meta.native_delivery_ready === true
203
+ ? { ok: true, reason: "native_receiver" }
204
+ : { ok: false, reason: "native_not_ready" };
205
+ }
194
206
  const launchMode = String(meta.launch_mode || "").trim();
195
207
  const adapter = this.adapterRouter.getAdapter({ launchMode, agentId: subscriber, meta });
196
208
  if (!adapter.capabilities.supportsNotifierInjector) {
@@ -376,6 +388,15 @@ class DeliveryScheduler {
376
388
  } else {
377
389
  this.graceWarned.delete(subscriber);
378
390
  }
391
+ if (selectedEvent && this.getAgentMeta(subscriber).meta?.native_delivery) {
392
+ const receipt = require("../../coordination/bus/nativeReceipts").readNativeReceipt(
393
+ this.projectRoot, subscriber, `${subscriber}:${this.pendingEventKey(selectedEvent)}`
394
+ );
395
+ if (receipt && ["unknown", "inflight"].includes(receipt.state)) {
396
+ this.noteDeferral(subscriber, "native_outcome_unknown");
397
+ return { ok: true, delivered: 0, deferred: true, reason: "native_outcome_unknown", receipt_id: receipt.id };
398
+ }
399
+ }
379
400
  this.clearDeferral(subscriber);
380
401
 
381
402
  const selectedKey = selectedEvent ? this.pendingEventKey(selectedEvent) : "";
@@ -416,7 +437,12 @@ class DeliveryScheduler {
416
437
  const { agents } = this.getAgentMeta(subscriber);
417
438
  const injectionText = this.buildInjectionText(envelope, subscriber, agents);
418
439
  try {
419
- await this.injector.inject(subscriber, injectionText);
440
+ if (agents[subscriber]?.native_delivery) {
441
+ await this.injector.inject(subscriber, injectionText, {
442
+ deliveryId: `${subscriber}:${this.pendingEventKey(evt)}`,
443
+ through_seq: Number(evt.seq) || undefined,
444
+ });
445
+ } else await this.injector.inject(subscriber, injectionText);
420
446
  queue.completeClaim(claim);
421
447
  this.clearPendingTracking(subscriber, evt);
422
448
  // Close the idle gate immediately. PTY ActivityDetector will refresh
@@ -428,21 +454,22 @@ class DeliveryScheduler {
428
454
  } catch {
429
455
  // activity stamp must never undo a successful inject
430
456
  }
431
- await this.emitDelivery({
457
+ try { await this.emitDelivery({
432
458
  subscriber,
433
459
  event: envelope,
434
460
  status: "ok",
435
- });
461
+ }); } catch (error) { this.log(`delivery observer failed after confirmed inject: ${error.message}`); }
436
462
  return { ok: true, delivered: 1, event: envelope };
437
463
  } catch (err) {
438
464
  queue.restoreClaim(claim);
439
465
  if (gate.forceOverride) this.noteForceFailure(subscriber, gate.pending);
440
- await this.emitDelivery({
466
+ try { await this.emitDelivery({
441
467
  subscriber,
442
468
  event: envelope,
443
469
  status: "error",
444
470
  error: err && err.message ? err.message : String(err || "inject failed"),
445
- });
471
+ errorCode: err && err.code || "",
472
+ }); } catch (error) { this.log(`delivery observer failed: ${error.message}`); }
446
473
  return {
447
474
  ok: false,
448
475
  delivered: 0,
@@ -103,6 +103,8 @@ class GlobalDaemon {
103
103
  runtimeFactory: (context) => this.createHostedRuntime(context),
104
104
  });
105
105
  this.activeGatewayRequests = new Map();
106
+ this.clientProjects = new WeakMap();
107
+ this.clientSubscriptions = new WeakMap();
106
108
  this.projectRuntimeGateway = {
107
109
  call: (projectRoot, operation, args, context) =>
108
110
  this.callProjectOperation(projectRoot, operation, args, context),
@@ -166,9 +168,11 @@ class GlobalDaemon {
166
168
  err.code = "PROJECT_RUNTIME_UNAVAILABLE";
167
169
  throw err;
168
170
  }
171
+ const socket = callContext.requestContext.socket;
172
+ if (this.clientProjects.get(socket) === context.projectRoot) this.bindClientSocket(socket, hostHandle);
169
173
  return hostHandle.handleRequest(
170
174
  callContext.requestContext.request,
171
- callContext.requestContext.socket
175
+ socket
172
176
  );
173
177
  });
174
178
  for (const operation of [
@@ -316,6 +320,11 @@ class GlobalDaemon {
316
320
 
317
321
  async handleRequest(projectRoot, request, socket) {
318
322
  const canonicalRoot = this.resolveProjectRoot(projectRoot);
323
+ if (socket && typeof socket.on === "function") {
324
+ const previousRoot = this.clientProjects.get(socket);
325
+ this.clientProjects.set(socket, canonicalRoot);
326
+ if (previousRoot !== canonicalRoot) this.bindClientSocket(socket, null);
327
+ }
319
328
  const config = this.loadProjectConfig(canonicalRoot);
320
329
  const provider = config.agentProvider || "codex-cli";
321
330
  const model = config.agentModel || defaultAgentModelForProvider(provider);
@@ -332,6 +341,24 @@ class GlobalDaemon {
332
341
  });
333
342
  }
334
343
 
344
+ bindClientSocket(socket, host) {
345
+ if (!socket || typeof socket.on !== "function") return;
346
+ const next = host?.runtime?.resource("ipcServer") || null;
347
+ const previous = this.clientSubscriptions.get(socket)
348
+ || this.controller?.runtime?.resource("ipcServer");
349
+ if (previous === next) return;
350
+ previous?.detachSocket?.(socket);
351
+ next?.attachSocket?.(socket);
352
+ if (next) this.clientSubscriptions.set(socket, next);
353
+ else this.clientSubscriptions.delete(socket);
354
+ }
355
+
356
+ bindControllerClient(socket) {
357
+ if (!socket || typeof socket.on !== "function") return;
358
+ this.clientProjects.set(socket, this.controllerRoot);
359
+ this.bindClientSocket(socket, this.controller);
360
+ }
361
+
335
362
  async callProjectOperation(projectRoot, operation, args = {}, context = {}) {
336
363
  const canonicalRoot = this.resolveProjectRoot(projectRoot);
337
364
  const config = this.loadProjectConfig(canonicalRoot);
@@ -13,6 +13,9 @@ const {
13
13
  } = require("../../orchestration/groups/bootstrap");
14
14
  const { validateTemplateTarget: validateGroupTemplateTarget } = require("../../orchestration/groups/templateValidation");
15
15
  const { getUfooPaths } = require("../../coordination/state/paths");
16
+ const { associateAgentWithGroup } = require("./agentRecoveryGroups");
17
+ const { reconcileGroupStatus } = require("./groupStatus");
18
+ const { normalizeInternalAgentType } = require("../contracts/agentMode");
16
19
  const {
17
20
  normalizeNicknameSegment,
18
21
  buildProjectNicknamePrefix,
@@ -308,12 +311,13 @@ function pickRosterMembers(roster = [], nicknames = []) {
308
311
  return roster.filter((item) => wanted.has(item.nickname));
309
312
  }
310
313
 
311
- function resolveAutoAgentType(projectRoot, requestedType) {
314
+ function resolveAutoAgentType(projectRoot, requestedType, internalOnly = false) {
312
315
  const normalizedRequested = asTrimmedString(requestedType);
313
316
  if (normalizedRequested && normalizedRequested !== "auto") return normalizedRequested;
314
317
 
315
318
  const provider = asTrimmedString(loadConfig(projectRoot).agentProvider);
316
319
  if (provider === "claude-cli") return "claude";
320
+ if (internalOnly) return provider === "codex-cli" ? "codex" : "ucode";
317
321
  if (provider === "ucode") return "ucode";
318
322
  if (provider === "agy-cli") return "agy";
319
323
  if (provider === "kimi-cli") return "kimi";
@@ -329,6 +333,7 @@ function buildExecutionPlan({
329
333
  plan,
330
334
  promptRegistry,
331
335
  promptProfiles,
336
+ internalOnly = false,
332
337
  }) {
333
338
  const profileByNickname = new Map();
334
339
  for (const item of promptProfiles || []) {
@@ -339,7 +344,7 @@ function buildExecutionPlan({
339
344
  const relationships = buildRelationshipMaps(templateDoc, plan);
340
345
 
341
346
  const roster = plan.map((item) => {
342
- const resolvedType = resolveAutoAgentType(projectRoot, item.requested_type || item.type);
347
+ const resolvedType = resolveAutoAgentType(projectRoot, item.requested_type || item.type, internalOnly);
343
348
  const profile = profileByNickname.get(item.nickname) || null;
344
349
  const runtimeNickname = buildRuntimeNickname(projectNicknamePrefix, item.nickname);
345
350
  return {
@@ -365,7 +370,7 @@ function buildExecutionPlan({
365
370
  : {};
366
371
 
367
372
  const executionPlan = plan.map((item) => {
368
- const resolvedType = resolveAutoAgentType(projectRoot, item.requested_type || item.type);
373
+ const resolvedType = resolveAutoAgentType(projectRoot, item.requested_type || item.type, internalOnly);
369
374
  const profile = profileByNickname.get(item.nickname) || null;
370
375
  const resolvedProfile = profile ? registryById.get(profile.resolved_profile) || null : null;
371
376
  const relation = relationships.get(item.nickname) || { upstream: [], downstream: [] };
@@ -809,8 +814,12 @@ function createGroupOrchestrator(options = {}) {
809
814
  plan,
810
815
  promptRegistry: validated.promptRegistry,
811
816
  promptProfiles: validated.promptProfiles,
817
+ internalOnly: params.internal_only === true,
812
818
  });
813
819
 
820
+ const unsupported = params.internal_only === true && compiled.executionPlan.find((item) => !normalizeInternalAgentType(item.type));
821
+ if (unsupported) return { ok: false, status: "failed", error: `unsupported internal agent type: ${unsupported.type}; use codex, claude or ucode` };
822
+
814
823
  if (dryRun) {
815
824
  return {
816
825
  ok: true,
@@ -949,6 +958,7 @@ function createGroupOrchestrator(options = {}) {
949
958
 
950
959
  const op = {
951
960
  action: "launch",
961
+ internal_only: params.internal_only === true,
952
962
  agent: item.type,
953
963
  count: 1,
954
964
  nickname: item.scoped_nickname || item.runtime_nickname,
@@ -988,6 +998,11 @@ function createGroupOrchestrator(options = {}) {
988
998
  member.status = reused ? "reused" : "active";
989
999
  member.managed = !reused;
990
1000
  member.subscriber_id = subscriberId || "";
1001
+ associateAgentWithGroup(projectRoot, subscriberId, {
1002
+ group_id: runtime.group_id,
1003
+ group_member_id: item.id,
1004
+ group_template_alias: runtime.template_alias,
1005
+ });
991
1006
  member.launched_at = nowIso();
992
1007
  member.launch = launchResult;
993
1008
  member.bootstrap_error = "";
@@ -1211,10 +1226,11 @@ function createGroupOrchestrator(options = {}) {
1211
1226
  if (!group) {
1212
1227
  return { ok: false, error: `group not found: ${groupId}` };
1213
1228
  }
1214
- return { ok: true, group };
1229
+ return { ok: true, group: reconcileGroupStatus(group, readBusAgents(projectRoot)) };
1215
1230
  }
1216
1231
 
1217
- const groups = listGroupStates(projectRoot).map((runtime) => summarizeGroup(runtime));
1232
+ const agents = readBusAgents(projectRoot);
1233
+ const groups = listGroupStates(projectRoot).map((runtime) => summarizeGroup(reconcileGroupStatus(runtime, agents)));
1218
1234
  groups.sort((a, b) => String(b.updated_at || "").localeCompare(String(a.updated_at || "")));
1219
1235
  return { ok: true, count: groups.length, groups };
1220
1236
  }
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+
3
+ const { isMetaActive } = require("../../coordination/bus/utils");
4
+
5
+ /** Group files retain launch history; registrations determine current liveness. */
6
+ function reconcileGroupStatus(runtime = {}, agents = {}) {
7
+ const members = (Array.isArray(runtime.members) ? runtime.members : []).map((member) => {
8
+ if (!member || !["active", "reused"].includes(member.status)) return member;
9
+ const meta = agents[member.subscriber_id];
10
+ return isMetaActive(meta) ? member : { ...member, status: "inactive" };
11
+ });
12
+ let status = runtime.status;
13
+ if (members.length && ["active", "partial", "inactive"].includes(status)) {
14
+ const active = members.filter((member) => member && ["active", "reused"].includes(member.status)).length;
15
+ status = active === members.length ? "active" : active ? "partial" : "inactive";
16
+ }
17
+ return { ...runtime, status, members };
18
+ }
19
+
20
+ module.exports = { reconcileGroupStatus };