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,100 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const crypto = require("crypto");
4
+ const { getUfooPaths } = require("../state/paths");
5
+ const { withFileLock } = require("../state/fileLock");
6
+ const { writeFileAtomic, subscriberToSafeName, isPidAlive } = require("./utils");
7
+
8
+ function submissionId(value) {
9
+ const bytes = crypto.createHash("sha256").update(String(value)).digest().subarray(0, 16);
10
+ bytes[6] = (bytes[6] & 0x0f) | 0x50;
11
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
12
+ const hex = bytes.toString("hex");
13
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
14
+ }
15
+
16
+ function receiptDirectory(projectRoot, subscriber) {
17
+ if (!/^[a-zA-Z0-9._:-]+$/.test(subscriber) || [".", ".."].includes(subscriber)) throw new Error("Invalid subscriber ID");
18
+ return path.join(getUfooPaths(projectRoot).busQueuesDir, subscriberToSafeName(subscriber), "native-receipts");
19
+ }
20
+
21
+ function receiptFile(projectRoot, subscriber, id) {
22
+ if (!/^[a-f0-9-]{36}$/.test(id)) throw new Error("Invalid receipt ID");
23
+ return path.join(receiptDirectory(projectRoot, subscriber), `${id}.json`);
24
+ }
25
+
26
+ function readNativeReceipt(projectRoot, subscriber, deliveryId) {
27
+ const file = receiptFile(projectRoot, subscriber, submissionId(deliveryId));
28
+ try { return JSON.parse(fs.readFileSync(file, "utf8")); }
29
+ catch (error) { if (error.code === "ENOENT") return null; throw error; }
30
+ }
31
+
32
+ function listNativeReceipts(projectRoot, subscriber) {
33
+ const dir = receiptDirectory(projectRoot, subscriber);
34
+ if (!fs.existsSync(dir)) return [];
35
+ return fs.readdirSync(dir).filter((name) => /^[a-f0-9-]{36}\.json$/.test(name))
36
+ .map((name) => JSON.parse(fs.readFileSync(path.join(dir, name), "utf8")));
37
+ }
38
+
39
+ function writeReceipt(file, receipt) {
40
+ writeFileAtomic(file, JSON.stringify({ ...receipt, updated_at: new Date().toISOString() }), { mode: 0o600 });
41
+ }
42
+
43
+ function resolveNativeReceipt(projectRoot, subscriber, id, resolution) {
44
+ if (!["accepted", "retry"].includes(resolution)) throw new Error("Resolution must be accepted or retry");
45
+ const file = receiptFile(projectRoot, subscriber, id);
46
+ return withFileLock(file, () => {
47
+ const receipt = JSON.parse(fs.readFileSync(file, "utf8"));
48
+ if (!["unknown", "inflight"].includes(receipt.state)) throw new Error("Only uncertain receipts can be resolved");
49
+ if (receipt.state === "inflight" && isPidAlive(receipt.owner_pid)) throw new Error("Delivery is still in flight; wait for its response");
50
+ const next = { ...receipt, state: resolution === "accepted" ? "accepted" : "retry_allowed",
51
+ resolution, resolved_at: new Date().toISOString(), result: resolution === "accepted" ? { queued: true, resolved_by: "operator" } : undefined };
52
+ writeReceipt(file, next);
53
+ return next;
54
+ });
55
+ }
56
+
57
+ function withNativeReceipts({ projectRoot, subscriber, send }) {
58
+ const dir = receiptDirectory(projectRoot, subscriber);
59
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
60
+ const inflight = new Map();
61
+ return async (request) => {
62
+ if (!request.deliveryId) throw Object.assign(new Error("Native delivery requires a stable delivery ID; use the updated daemon"), { code: "native_not_ready" });
63
+ const deliveryId = String(request.deliveryId);
64
+ const digest = crypto.createHash("sha256").update(request.command).digest("hex");
65
+ if (inflight.has(deliveryId)) {
66
+ const previous = inflight.get(deliveryId);
67
+ if (previous.digest !== digest) throw Object.assign(new Error("Delivery ID was reused for different content"), { code: "native_not_ready" });
68
+ return previous.operation;
69
+ }
70
+ const id = submissionId(deliveryId);
71
+ const file = receiptFile(projectRoot, subscriber, id);
72
+ const cached = withFileLock(file, () => {
73
+ const receipt = readNativeReceipt(projectRoot, subscriber, deliveryId);
74
+ if (receipt && receipt.digest !== digest) throw Object.assign(new Error("Delivery ID was reused for different content"), { code: "native_not_ready" });
75
+ if (receipt?.state === "accepted") return receipt.result;
76
+ if (receipt && receipt.state !== "retry_allowed") throw Object.assign(new Error(`Delivery outcome is unknown; inspect ufoo bus deliveries ${subscriber}`), { code: "native_outcome_unknown" });
77
+ writeReceipt(file, { ...receipt, id, delivery_id: deliveryId, digest, state: "inflight", owner_pid: process.pid,
78
+ retry_authorized: receipt?.state === "retry_allowed", attempt: (receipt?.attempt || 0) + 1 });
79
+ return null;
80
+ });
81
+ if (cached) return cached;
82
+ const operation = (async () => {
83
+ try {
84
+ const result = await send({ ...request, deliveryId, retryAuthorized: readNativeReceipt(projectRoot, subscriber, deliveryId)?.retry_authorized === true });
85
+ withFileLock(file, () => writeReceipt(file, { ...readNativeReceipt(projectRoot, subscriber, deliveryId), id, delivery_id: deliveryId, digest, state: "accepted", result }));
86
+ return result;
87
+ } catch (error) {
88
+ withFileLock(file, () => {
89
+ if (error.remoteRejected || error.code === "native_not_ready") fs.rmSync(file, { force: true });
90
+ else writeReceipt(file, { ...readNativeReceipt(projectRoot, subscriber, deliveryId), id, delivery_id: deliveryId, digest, state: "unknown", error: error.message });
91
+ });
92
+ throw error;
93
+ } finally { inflight.delete(deliveryId); }
94
+ })();
95
+ inflight.set(deliveryId, { digest, operation });
96
+ return operation;
97
+ };
98
+ }
99
+
100
+ module.exports = { submissionId, readNativeReceipt, listNativeReceipts, resolveNativeReceipt, withNativeReceipts };
@@ -14,7 +14,7 @@ const AUTO_NICKNAME_PREFIXES = new Set([
14
14
  function resolveAutoNicknamePrefix(agentType = "") {
15
15
  const normalized = String(agentType || "").trim().toLowerCase();
16
16
  if (normalized === "claude" || normalized === "claude-code") return "claude";
17
- if (normalized === "ufoo" || normalized === "ucode" || normalized === "ufoo-code") return "ucode";
17
+ if (normalized === "ucode") return "ucode";
18
18
  return normalized;
19
19
  }
20
20
 
@@ -3,7 +3,6 @@ const path = require("path");
3
3
  const {
4
4
  subscriberToSafeName,
5
5
  ensureDir,
6
- truncateFile,
7
6
  } = require("./utils");
8
7
  const {
9
8
  DeliveryQueue,
@@ -116,8 +115,7 @@ class QueueManager {
116
115
  * 清空待处理消息
117
116
  */
118
117
  async clearPending(subscriber) {
119
- const pendingPath = this.getPendingPath(subscriber);
120
- truncateFile(pendingPath);
118
+ this.getDeliveryQueue(subscriber).writePending([]);
121
119
  }
122
120
 
123
121
  /**
@@ -1,6 +1,6 @@
1
1
  const fs = require("fs");
2
2
  const path = require("path");
3
- const { getTimestamp, isAgentPidAlive, isMetaActive, isValidTty, getTtyProcessInfo } = require("./utils");
3
+ const { getTimestamp, isAgentPidAlive, isMetaActive, isValidTty, getTtyProcessInfo, normalizeAgentTypeAlias } = require("./utils");
4
4
  const NicknameManager = require("./nickname");
5
5
  const { isMismatchedAutoNickname } = require("./nickname");
6
6
  const { spawnSync } = require("child_process");
@@ -184,7 +184,7 @@ class SubscriberManager {
184
184
  : (await this.queueManager.readTty(id));
185
185
  if (!metaTty) continue;
186
186
  if (metaTty === ttyPath) {
187
- const sameAgentType = !currentAgentType || meta?.agent_type === currentAgentType;
187
+ const sameAgentType = !currentAgentType || normalizeAgentTypeAlias(meta?.agent_type) === normalizeAgentTypeAlias(currentAgentType);
188
188
  // Inherit user-set nickname only when replacing the same agent type.
189
189
  if (
190
190
  sameAgentType
@@ -229,6 +229,7 @@ class SubscriberManager {
229
229
  * 加入总线
230
230
  */
231
231
  async join(sessionId, agentType, nickname = null, options = {}) {
232
+ if (normalizeAgentTypeAlias(agentType) === "ucode") agentType = "ucode";
232
233
  // Special case: ufoo-agent uses fixed ID without suffix
233
234
  const subscriber = (sessionId === "ufoo-agent")
234
235
  ? "ufoo-agent"
@@ -184,12 +184,16 @@ function appendFileAtomic(filePath, content) {
184
184
  /**
185
185
  * 原子性地写入文件
186
186
  */
187
- function writeFileAtomic(filePath, content) {
187
+ function writeFileAtomic(filePath, content, options = {}) {
188
188
  ensureDir(path.dirname(filePath));
189
189
  // Include pid + random suffix to avoid collisions across concurrent writers in the same millisecond.
190
190
  const tmpFile = `${filePath}.tmp.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}`;
191
- fs.writeFileSync(tmpFile, content, "utf8");
192
- fs.renameSync(tmpFile, filePath);
191
+ try {
192
+ fs.writeFileSync(tmpFile, content, { encoding: "utf8", ...options });
193
+ fs.renameSync(tmpFile, filePath);
194
+ } finally {
195
+ fs.rmSync(tmpFile, { force: true });
196
+ }
193
197
  }
194
198
 
195
199
  /**
@@ -368,7 +372,7 @@ function normalizeAgentTypeAlias(value = "") {
368
372
  if (text === "agy") return "agy";
369
373
  if (text === "grok" || text === "ugrok" || text === "grok-build" || text === "xai") return "grok";
370
374
  if (text === "kimi" || text === "ukimi" || text === "kimi-cli" || text === "kimi-code") return "kimi";
371
- if (text === "ufoo" || text === "ucode" || text === "ufoo-code") return "ufoo-code";
375
+ if (text === "ucode") return "ucode";
372
376
  return text;
373
377
  }
374
378
 
@@ -0,0 +1,279 @@
1
+ "use strict";
2
+
3
+ const terminal = new Set(["completed", "failed", "cancelled", "interrupted"]);
4
+ const number = value => value != null && Number.isFinite(Number(value)) && Number(value) >= 0 ? Number(value) : null;
5
+ const time = value => Number.isFinite(Date.parse(value)) ? Date.parse(value) : null;
6
+ const difference = (end, start) => end !== null && start !== null && end >= start ? end - start : null;
7
+ const rate = (a, b) => b ? a / b : null;
8
+
9
+ function distribution(values) {
10
+ const sorted = values.filter(value => value !== null && Number.isFinite(value)).sort((a, b) => a - b);
11
+ const percentile = fraction => sorted.length ? sorted[Math.max(0, Math.ceil(sorted.length * fraction) - 1)] : null;
12
+ return { samples: sorted.length, mean: sorted.length ? sorted.reduce((a, b) => a + b, 0) / sorted.length : null,
13
+ p50: percentile(0.5), p95: percentile(0.95), max: sorted.at(-1) ?? null };
14
+ }
15
+
16
+ function normalizedUsage(usage) {
17
+ if (!usage || typeof usage !== "object") return null;
18
+ const value = { input: number(usage.input ?? usage.input_tokens ?? usage.prompt_tokens),
19
+ output: number(usage.output ?? usage.output_tokens ?? usage.completion_tokens),
20
+ cacheRead: number(usage.cacheRead ?? usage.cache_read_tokens ?? usage.cache_read_input_tokens ?? usage.cached_input_tokens
21
+ ?? usage.input_tokens_details?.cached_tokens ?? usage.input_token_details?.cached_tokens ?? usage.prompt_tokens_details?.cached_tokens),
22
+ cacheCreation: number(usage.cacheCreation ?? usage.cache_creation_tokens ?? usage.cache_creation_input_tokens
23
+ ?? usage.input_tokens_details?.cache_write_tokens ?? usage.prompt_tokens_details?.cache_write_tokens) };
24
+ if (!Object.values(value).some(v => v !== null)) return null;
25
+ value.inputIncludesCache = typeof usage.inputIncludesCache === "boolean" ? usage.inputIncludesCache
26
+ : usage.prompt_tokens != null || usage.input_tokens_details || usage.input_token_details || usage.cached_input_tokens != null ? true
27
+ : usage.cache_read_input_tokens != null || usage.cache_creation_input_tokens != null ? false : null;
28
+ return value;
29
+ }
30
+
31
+ function cacheObservation(samples, configuration, provider) {
32
+ const transport = configuration?.transport || "";
33
+ const includesCache = transport.startsWith("openai") ? true : transport.startsWith("anthropic") ? false
34
+ : ["openai", "codex", "codex-cli", "kimi", "grok", "grok-build"].includes(provider) ? true
35
+ : ["claude", "claude-code", "anthropic"].includes(provider) ? false : null;
36
+ const pairs = samples.flatMap(usage => {
37
+ if (usage.input === null || usage.cacheRead === null) return [];
38
+ const inclusive = usage.inputIncludesCache ?? includesCache;
39
+ if (inclusive === null || !inclusive && usage.cacheCreation === null) return [];
40
+ const prompt = inclusive ? usage.input : usage.input + usage.cacheRead + usage.cacheCreation;
41
+ return usage.cacheRead <= prompt ? [{ cached: usage.cacheRead, prompt }] : [];
42
+ });
43
+ const cachedTokens = pairs.length ? pairs.reduce((sum, pair) => sum + pair.cached, 0) : null;
44
+ const promptTokens = pairs.length ? pairs.reduce((sum, pair) => sum + pair.prompt, 0) : null;
45
+ return { samples: pairs.length, usageSamples: samples.length, cachedTokens, promptTokens, hitRate: rate(cachedTokens, promptTokens) };
46
+ }
47
+
48
+ function aggregateCache(runs, scope) {
49
+ const sum = key => {
50
+ const values = runs.map(run => run[scope][key]).filter(value => value !== null);
51
+ return values.length ? values.reduce((a, b) => a + b, 0) : null;
52
+ };
53
+ const cachedTokens = sum("cachedTokens"), promptTokens = sum("promptTokens");
54
+ return { samples: sum("samples") || 0, usageSamples: sum("usageSamples") || 0,
55
+ cachedTokens, promptTokens, hitRate: rate(cachedTokens, promptTokens) };
56
+ }
57
+
58
+ function aggregate(runs) {
59
+ const outcomes = Object.fromEntries(["completed", "failed", "cancelled", "interrupted", "running", "waiting_user", "queued", "unknown"].map(key => [key, runs.filter(r => r.status === key).length]));
60
+ const finished = Object.entries(outcomes).filter(([key]) => terminal.has(key)).reduce((sum, [, count]) => sum + count, 0);
61
+ const counts = {};
62
+ for (const run of runs) for (const [key, value] of Object.entries(run.counts)) counts[key] = (counts[key] || 0) + value;
63
+ const latency = {};
64
+ for (const key of ["elapsedMs", "activeMs", "queueMs", "firstTextMs", "firstThinkingMs", "modelMs", "toolMs", "compactionMs", "waitingUserMs", "idleMs"]) latency[key] = distribution(runs.map(r => r.timings[key]));
65
+ const tokenTotals = {};
66
+ for (const scope of ["usage", "compactionUsage"]) {
67
+ tokenTotals[scope] = {};
68
+ for (const key of ["input", "output", "cacheRead", "cacheCreation"]) {
69
+ const observed = runs.map(r => r[scope][key]).filter(v => v !== null);
70
+ tokenTotals[scope][key] = { samples: observed.length, sum: observed.length ? observed.reduce((a, b) => a + b, 0) : null };
71
+ }
72
+ }
73
+ return { runs: runs.length, outcomes, completedOfFinished: rate(outcomes.completed, finished), finished,
74
+ counts, latency, ...tokenTotals, finalTextCharacters: distribution(runs.map(r => r.finalTextCharacters)),
75
+ cache: aggregateCache(runs, "cache"), compactionCache: aggregateCache(runs, "compactionCache"),
76
+ signals: Object.fromEntries([...new Set(runs.flatMap(r => r.signals))].map(key => [key, runs.filter(r => r.signals.includes(key)).length])) };
77
+ }
78
+
79
+ /** Derived observations, never a quality grade or lifecycle authority. */
80
+ function summarizeAgentPerformance(events, tasks = [], queues = [], options = {}) {
81
+ const now = options.now ?? Date.now();
82
+ const parseBound = key => {
83
+ if (!options[key]) return null;
84
+ const parsed = time(options[key]);
85
+ if (parsed === null) throw new Error(`${key} must be an ISO timestamp`);
86
+ return parsed;
87
+ };
88
+ const since = parseBound("since"), until = parseBound("until");
89
+ if (since !== null && until !== null && since > until) throw new Error("since must not be after until");
90
+ const runs = new Map();
91
+ const reportsByTask = new Map();
92
+ const enqueuedBySequence = new Map();
93
+ for (const event of events.filter(e => e.type === "queue.enqueued")) enqueuedBySequence.set(`${event.agentId}:${event.busSequence}`, time(event.time));
94
+ for (const event of events.filter(e => e.type?.startsWith("report."))) {
95
+ const key = `${event.taskId}:${event.agentId}`;
96
+ if (!reportsByTask.has(key)) reportsByTask.set(key, []);
97
+ reportsByTask.get(key).push(event);
98
+ }
99
+ let uncorrelatedEvents = 0;
100
+ for (const event of events) {
101
+ const type = event.type || "";
102
+ if (!/^(?:task\.|request.accepted|run.config|model\.|tool\.|message.delta|thinking.delta|context.compaction|loop\.|interaction\.)/.test(type)) continue;
103
+ if (!event.taskRunId) { uncorrelatedEvents += 1; continue; }
104
+ let run = runs.get(event.taskRunId);
105
+ if (!run) {
106
+ run = { taskRunId: event.taskRunId, taskId: event.taskId || event.taskRunId, agentId: event.agentId || "", sessionId: event.sessionId || "",
107
+ parentTaskRunId: event.parentTaskRunId || null, traceId: event.traceId || null, status: "unknown", configuration: null,
108
+ accepted: null, enqueued: null, started: null, ended: null, lastActivity: null, firstText: null, firstThinking: null,
109
+ activeStart: null, pausedAt: null, activeMs: 0, waitingUserMs: 0, attempts: new Set(), tools: new Map(),
110
+ usageSamples: [], modelOutcomes: 0, compactionUsageSamples: [], terminalUsage: null, finalTextCharacters: null, streamedCharacters: 0,
111
+ counts: { modelCalls: 0, sdkTurns: 0, modelFailures: 0, toolCalls: 0, toolErrors: 0, toolExceptions: 0, toolRejections: 0, unresolvedTools: 0,
112
+ repeatedToolCalls: 0, loopWarnings: 0, loopStops: 0, modelRetries: 0, compactionAttempts: 0, compactions: 0, compactionFailures: 0 },
113
+ modelDurations: [], modelStarts: new Map(), toolDurations: [], compactionDurations: [], fingerprints: new Map(), errorCodes: {} };
114
+ runs.set(event.taskRunId, run);
115
+ }
116
+ run.agentId ||= event.agentId || "";
117
+ run.sessionId ||= event.sessionId || "";
118
+ const timestamp = time(event.time);
119
+ if (timestamp !== null) run.lastActivity = Math.max(run.lastActivity ?? timestamp, timestamp);
120
+ if (event.attemptId) run.attempts.add(event.attemptId);
121
+ if (type === "run.config") run.configuration = event.configuration || null;
122
+ if (type === "request.accepted") { run.accepted ??= timestamp; if (run.started === null) run.status = "queued"; }
123
+ if (type === "task.started") {
124
+ run.started ??= timestamp;
125
+ if (event.queueSequence != null) run.enqueued ??= enqueuedBySequence.get(`${run.agentId}:${event.queueSequence}`) ?? null;
126
+ // SDK/native presentation can repeat the same committed lifecycle.
127
+ if (run.activeStart === null) run.activeStart = timestamp;
128
+ if (run.pausedAt !== null) { run.waitingUserMs += difference(timestamp, run.pausedAt) || 0; run.pausedAt = null; }
129
+ run.status = "running";
130
+ }
131
+ if (type === "task.paused" || /^task\.(completed|failed|cancelled|interrupted)$/.test(type)) {
132
+ if (run.activeStart !== null) { run.activeMs += difference(timestamp, run.activeStart) || 0; run.activeStart = null; }
133
+ run.status = type === "task.paused" ? "waiting_user" : type.slice(5);
134
+ if (type === "task.paused") run.pausedAt ??= timestamp;
135
+ else run.ended = timestamp;
136
+ run.terminalUsage = normalizedUsage(event.usage) || run.terminalUsage;
137
+ if (number(event.finalTextCharacters) !== null) run.finalTextCharacters = event.finalTextCharacters;
138
+ }
139
+ if (type === "message.delta" && event.textCharacters > 0) { run.firstText ??= timestamp; run.streamedCharacters += event.textCharacters; }
140
+ if (type === "thinking.delta" && event.textCharacters > 0) run.firstThinking ??= timestamp;
141
+ if (type === "model.started") {
142
+ run.counts[event.modelScope === "sdk-turn" ? "sdkTurns" : "modelCalls"] += 1;
143
+ run.provider ||= event.provider || ""; run.model ||= event.model || "";
144
+ run.modelStarts.set(event.turnId || event.modelScope || "api-call", timestamp);
145
+ }
146
+ if (["model.completed", "model.failed"].includes(type)) {
147
+ run.modelOutcomes += 1;
148
+ const key = event.turnId || event.modelScope || "api-call";
149
+ const duration = number(event.durationMs) ?? difference(timestamp, run.modelStarts.get(key) ?? null);
150
+ if (duration !== null) run.modelDurations.push(duration);
151
+ run.modelStarts.delete(key);
152
+ if (type === "model.failed") run.counts.modelFailures += 1;
153
+ else { const usage = normalizedUsage(event.usage); if (usage) run.usageSamples.push(usage); }
154
+ }
155
+ if (type === "model.retry") run.counts.modelRetries += 1;
156
+ if (type === "loop.warning") run.counts.loopWarnings += 1;
157
+ if (type === "loop.stopped") run.counts.loopStops += 1;
158
+ if (["tool.started", "tool.completed", "tool.failed", "tool.rejected"].includes(type)) {
159
+ const id = event.toolCallId || event.id;
160
+ const tool = run.tools.get(id) || { started: false, ended: false, outcome: null, startedAt: null, name: event.toolName || "" };
161
+ tool.name ||= event.toolName || "";
162
+ if (type === "tool.started" && !tool.started) {
163
+ tool.started = true; tool.startedAt = timestamp; run.counts.toolCalls += 1;
164
+ if (event.argumentFingerprint) {
165
+ const key = `${tool.name}:${event.argumentFingerprint}`;
166
+ if (run.fingerprints.has(key)) run.counts.repeatedToolCalls += 1;
167
+ run.fingerprints.set(key, (run.fingerprints.get(key) || 0) + 1);
168
+ }
169
+ } else if (type !== "tool.started" && !tool.ended) {
170
+ tool.ended = true;
171
+ tool.outcome = type === "tool.failed" ? "unknown" : type === "tool.rejected" ? "rejected" : event.ok === false ? "error" : "ok";
172
+ if (tool.outcome === "error") run.counts.toolErrors += 1;
173
+ if (type === "tool.failed") run.counts.toolExceptions += 1;
174
+ if (tool.outcome === "rejected") run.counts.toolRejections += 1;
175
+ const duration = number(event.durationMs) ?? difference(timestamp, tool.startedAt);
176
+ if (duration !== null) run.toolDurations.push(duration);
177
+ }
178
+ run.tools.set(id, tool);
179
+ }
180
+ if (type === "context.compaction.started") run.counts.compactionAttempts += 1;
181
+ if (type === "context.compaction.completed") {
182
+ run.counts.compactions += 1;
183
+ const usage = normalizedUsage(event.usage);
184
+ if (usage) run.compactionUsageSamples.push(usage);
185
+ }
186
+ if (type === "context.compaction.failed") run.counts.compactionFailures += 1;
187
+ if (["context.compaction.completed", "context.compaction.failed"].includes(type) && number(event.durationMs) !== null) run.compactionDurations.push(event.durationMs);
188
+ const code = event.code || event.resultCode;
189
+ if (code && (type.endsWith("failed") || type === "tool.rejected" || type === "model.retry" || event.ok === false)) run.errorCodes[code] = (run.errorCodes[code] || 0) + 1;
190
+ }
191
+ const rows = [];
192
+ for (const run of runs.values()) {
193
+ const anchor = run.started ?? run.accepted ?? run.lastActivity;
194
+ const config = run.configuration;
195
+ const provider = config?.provider || run.provider || "unknown", model = config?.model || run.model || "unknown";
196
+ if (since !== null && (anchor === null || anchor < since) || until !== null && (anchor === null || anchor >= until)) continue;
197
+ if (options.provider && provider !== options.provider || options.model && model !== options.model) continue;
198
+ const end = run.ended ?? now;
199
+ const paired = [...run.tools.values()];
200
+ run.counts.unresolvedTools = paired.filter(t => !t.ended || t.outcome === "unknown").length;
201
+ const modelStarts = run.counts.modelCalls + run.counts.sdkTurns;
202
+ // Terminal native usage is an accumulator with zero defaults. Do not use
203
+ // it to invent token counts when observed model calls omitted usage.
204
+ const usage = run.usageSamples.length ? run.usageSamples : !modelStarts && !run.modelOutcomes && run.terminalUsage ? [run.terminalUsage] : [];
205
+ const cache = cacheObservation(usage, config, provider);
206
+ const usageComplete = modelStarts ? run.usageSamples.length === modelStarts : !run.modelOutcomes && usage.length > 0;
207
+ const sumUsage = samples => Object.fromEntries(["input", "output", "cacheRead", "cacheCreation"].map(key => {
208
+ const values = samples.map(u => u[key]).filter(v => v !== null);
209
+ return [key, values.length ? values.reduce((a, b) => a + b, 0) : null];
210
+ }));
211
+ const signals = [];
212
+ if (run.counts.toolErrors) signals.push("tool_errors");
213
+ if (run.counts.unresolvedTools) signals.push("unresolved_tools");
214
+ if (run.counts.toolRejections) signals.push("rejected_tool_calls");
215
+ if (run.counts.repeatedToolCalls) signals.push("repeated_tool_arguments");
216
+ if (run.counts.loopStops) signals.push("loop_guard_stopped");
217
+ if (run.counts.compactionFailures) signals.push("compaction_failed");
218
+ const idleMs = terminal.has(run.status) ? null : difference(now, run.lastActivity);
219
+ if (run.status === "running" && idleMs > (options.idleThresholdMs || 300000)) signals.push("running_without_recent_events");
220
+ const reports = reportsByTask.get(`${run.taskId}:${run.agentId}`) || [];
221
+ const reportLengths = reports.map(r => number(r.reportCharacters)).filter(v => v !== null);
222
+ if (reportLengths.some(value => value > 600)) signals.push("long_report");
223
+ const lifecycleComplete = run.started !== null && (terminal.has(run.status) ? run.ended !== null : true);
224
+ const durations = values => values.length ? values.reduce((a, b) => a + b, 0) : null;
225
+ rows.push({ taskRunId: run.taskRunId, taskId: run.taskId, agentId: run.agentId, sessionId: run.sessionId,
226
+ parentTaskRunId: run.parentTaskRunId, traceId: run.traceId, status: run.status, provider, model,
227
+ startedAt: run.started !== null ? new Date(run.started).toISOString() : null,
228
+ endedAt: run.ended !== null ? new Date(run.ended).toISOString() : null,
229
+ configuration: config, attempts: run.attempts.size || null, counts: run.counts, usage: sumUsage(usage), compactionUsage: sumUsage(run.compactionUsageSamples),
230
+ cache, compactionCache: cacheObservation(run.compactionUsageSamples, config, provider),
231
+ queueTimingSource: run.enqueued !== null ? "bus.sequence" : run.accepted !== null ? "request.accepted" : "unknown",
232
+ finalTextCharacters: run.finalTextCharacters, streamedCharacters: run.streamedCharacters,
233
+ reportCharacters: distribution(reportLengths), errorCodes: run.errorCodes, signals,
234
+ coverage: { configuration: Boolean(config), lifecycle: lifecycleComplete, usage: usage.length > 0,
235
+ usageComplete, cache: cache.samples > 0, cacheComplete: usageComplete && cache.samples === usage.length,
236
+ toolFingerprints: run.counts.toolCalls ? [...run.fingerprints.values()].reduce((a, b) => a + b, 0) : 0 },
237
+ timings: { elapsedMs: lifecycleComplete ? difference(end, run.started) : null,
238
+ activeMs: lifecycleComplete ? run.activeMs + (run.activeStart !== null ? difference(end, run.activeStart) || 0 : 0) : null,
239
+ queueMs: difference(run.started, run.enqueued ?? run.accepted), firstTextMs: difference(run.firstText, run.started),
240
+ firstThinkingMs: difference(run.firstThinking, run.started), modelMs: durations(run.modelDurations), toolMs: durations(run.toolDurations),
241
+ compactionMs: durations(run.compactionDurations), waitingUserMs: run.waitingUserMs + (run.pausedAt !== null ? difference(end, run.pausedAt) || 0 : 0), idleMs } });
242
+ }
243
+ rows.sort((a, b) => String(a.startedAt || "").localeCompare(String(b.startedAt || "")) || a.taskRunId.localeCompare(b.taskRunId));
244
+ const groups = new Map();
245
+ for (const run of rows) {
246
+ const cohort = { provider: run.provider, model: run.model, thinkingLevel: run.configuration?.thinkingLevel || "unknown",
247
+ engineFingerprint: run.configuration?.engineFingerprint || "unknown",
248
+ requestKind: run.configuration?.requestKind || "unknown",
249
+ runtimeVersion: run.configuration?.runtimeVersion || "unknown", executionKind: run.configuration?.executionKind || (run.counts.sdkTurns ? "sdk" : "native") };
250
+ const key = JSON.stringify(cohort);
251
+ if (!groups.has(key)) groups.set(key, { cohort, runs: [] });
252
+ groups.get(key).runs.push(run);
253
+ }
254
+ const taskIds = new Set(rows.flatMap(run => [run.taskId, run.taskRunId]));
255
+ const selectedTasks = tasks.filter(task => (since === null && until === null && !options.provider && !options.model) || [task.taskId, task.taskRunId, task.id].some(id => id && taskIds.has(id)));
256
+ const delegated = selectedTasks.filter(task => task.taskId && task.workerId);
257
+ const accepted = delegated.filter(t => t.status === "accepted").length, rejected = delegated.filter(t => t.status === "rejected").length;
258
+ const reported = delegated.filter(t => ["done", "error"].includes(t.report?.phase)).length;
259
+ const warnings = [...(options.warnings || [])];
260
+ if (groups.size > 100) warnings.push({ code: "performance_cohort_limit", total: groups.size, read: 100 });
261
+ if (uncorrelatedEvents) warnings.push({ code: "performance_uncorrelated_events", count: uncorrelatedEvents });
262
+ const partialRuns = rows.filter(r => !r.coverage.lifecycle).length;
263
+ if (partialRuns) warnings.push({ code: "performance_partial_lifecycle", count: partialRuns });
264
+ const limit = options.includeRuns === false ? 0 : Math.min(100, Math.max(1, Math.floor(Number(options.limit) || 20)));
265
+ return { version: 1, generatedAt: new Date(now).toISOString(), window: { since: options.since || null, until: options.until || null, selection: "run-start; until exclusive" },
266
+ summary: aggregate(rows), cohorts: [...groups.values()].sort((a, b) => b.runs.length - a.runs.length).slice(0, 100).map(g => ({ ...g.cohort, ...aggregate(g.runs) })),
267
+ delegations: { tasks: delegated.length, accepted, rejected, reported, awaitingAcceptance: delegated.filter(t => t.status === "reported").length,
268
+ failed: delegated.filter(t => t.status === "failed").length, deliveryUncertain: delegated.filter(t => t.status === "delivery_uncertain").length,
269
+ acceptedOfReviewed: rate(accepted, accepted + rejected), acceptedOfReported: rate(accepted, reported),
270
+ reportToAcceptanceMs: distribution(delegated.map(task => difference(time(task.acceptance?.time), time(task.report?.ts)))) },
271
+ queues: queues.map(q => ({ ...q, ageMs: difference(now, time(q.enqueuedAt)) })).slice(-100),
272
+ coverage: { runsWithConfiguration: rows.filter(r => r.coverage.configuration).length, runsWithUsage: rows.filter(r => r.coverage.usage).length,
273
+ runsWithCompleteUsage: rows.filter(r => r.coverage.usageComplete).length,
274
+ runsWithCache: rows.filter(r => r.coverage.cache).length, runsWithCompleteCache: rows.filter(r => r.coverage.cacheComplete).length,
275
+ partialRuns, uncorrelatedEvents, retainedRuns: Math.min(rows.length, limit), runLimit: limit },
276
+ runs: limit ? rows.slice(-limit) : [], incomplete: warnings.length > 0, warnings };
277
+ }
278
+
279
+ module.exports = { summarizeAgentPerformance, distribution };
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const MessageManager = require("../bus/message");
6
+ const { getUfooPaths } = require("../state/paths");
7
+ const { redactSecrets } = require("../../runtime/privacy/redactor");
8
+
9
+ // Display events are observations, not messages. They never enter an agent's
10
+ // inbox and never depend on which peer receives the task's final reply.
11
+ function createAgentSurfacePublisher(projectRoot, subscriber) {
12
+ const paths = getUfooPaths(projectRoot);
13
+ const sequence = new MessageManager(paths.busDir, {}, null);
14
+ let pending = Promise.resolve();
15
+ let batch = [];
16
+ let timer = null;
17
+ let lastError = "";
18
+ function reportError(error) {
19
+ const message = redactSecrets(String(error?.message || "unknown display stream error"));
20
+ if (message !== lastError) process.stderr.write(`[internal] display stream unavailable: ${message}\n`);
21
+ lastError = message;
22
+ }
23
+ function drain() {
24
+ if (timer) clearTimeout(timer);
25
+ timer = null;
26
+ const events = batch;
27
+ batch = [];
28
+ for (const safeEvent of events) {
29
+ pending = pending.then(async () => {
30
+ fs.mkdirSync(paths.busEventsDir, { recursive: true });
31
+ const seq = await sequence.getNextSeq();
32
+ const timestamp = new Date().toISOString();
33
+ fs.appendFileSync(path.join(paths.busEventsDir, `${timestamp.slice(0, 10)}.jsonl`), JSON.stringify({
34
+ seq, timestamp, type: "status/agent-surface", event: "agent_surface",
35
+ publisher: subscriber, target: "*", data: { subscriber, surface: safeEvent },
36
+ }) + "\n");
37
+ lastError = "";
38
+ }).catch(reportError);
39
+ }
40
+ }
41
+ function enqueue(event) {
42
+ let safeEvent;
43
+ try { safeEvent = JSON.parse(redactSecrets(JSON.stringify(event))); }
44
+ catch (error) { reportError(error); return; }
45
+ const last = batch.at(-1);
46
+ if (["text_delta", "thinking_delta"].includes(safeEvent.type) && last?.type === safeEvent.type
47
+ && String(last.delta || "").length < 32000) last.delta = String(last.delta || "") + String(safeEvent.delta || "");
48
+ else batch.push(safeEvent);
49
+ if (!timer) { timer = setTimeout(drain, 40); timer.unref?.(); }
50
+ }
51
+ return { enqueue, flush: () => { drain(); return pending; } };
52
+ }
53
+
54
+ function readAgentSurfaceEvents(projectRoot, agentIds, maxBytes = 2 * 1024 * 1024) {
55
+ const accepted = new Set(agentIds);
56
+ const dir = getUfooPaths(projectRoot).busEventsDir;
57
+ let files;
58
+ try { files = fs.readdirSync(dir).filter((file) => file.endsWith(".jsonl")).sort().slice(-2); }
59
+ catch { return []; }
60
+ const events = [];
61
+ for (const file of files) {
62
+ let fd;
63
+ try {
64
+ fd = fs.openSync(path.join(dir, file), "r");
65
+ const size = fs.fstatSync(fd).size;
66
+ const start = Math.max(0, size - maxBytes);
67
+ const buffer = Buffer.alloc(Math.min(size, maxBytes));
68
+ fs.readSync(fd, buffer, 0, buffer.length, start);
69
+ const lines = buffer.toString("utf8").split("\n");
70
+ if (start) lines.shift();
71
+ for (const line of lines) {
72
+ try {
73
+ const event = JSON.parse(line);
74
+ if (event.event === "agent_surface" && accepted.has(event.publisher) && event.data?.surface?.type) events.push(event);
75
+ } catch { /* An incomplete tail is picked up by the live bridge. */ }
76
+ }
77
+ } catch { /* History can rotate while a pane attaches. */ }
78
+ finally { if (fd !== undefined) fs.closeSync(fd); }
79
+ }
80
+ return events.sort((a, b) => (a.seq || 0) - (b.seq || 0));
81
+ }
82
+
83
+ // Keep partial rows as bytes: a provider can append in the middle of a UTF-8
84
+ // character. File offsets, rather than sequence high-water marks, retain late
85
+ // appends from concurrent writers.
86
+ function createAgentSurfaceReader(projectRoot, maxBytes = 2 * 1024 * 1024) {
87
+ const cursors = new Map();
88
+ const dir = getUfooPaths(projectRoot).busEventsDir;
89
+ return {
90
+ read(agentIds) {
91
+ const accepted = new Set(agentIds);
92
+ let files;
93
+ try { files = fs.readdirSync(dir).filter((name) => name.endsWith(".jsonl")).sort().slice(-2); }
94
+ catch { return []; }
95
+ const events = [];
96
+ for (const name of files) {
97
+ let fd;
98
+ try {
99
+ fd = fs.openSync(path.join(dir, name), "r");
100
+ const stat = fs.fstatSync(fd);
101
+ let cursor = cursors.get(name);
102
+ if (!cursor || cursor.ino !== stat.ino || stat.size < cursor.offset) {
103
+ cursor = { ino: stat.ino, offset: Math.max(0, stat.size - maxBytes), partial: Buffer.alloc(0) };
104
+ cursor.skipFirst = cursor.offset > 0;
105
+ }
106
+ if (stat.size - cursor.offset > maxBytes) {
107
+ cursor.offset = stat.size - maxBytes;
108
+ cursor.partial = Buffer.alloc(0);
109
+ cursor.skipFirst = true;
110
+ }
111
+ const buffer = Buffer.alloc(Math.max(0, stat.size - cursor.offset));
112
+ const read = fs.readSync(fd, buffer, 0, buffer.length, cursor.offset);
113
+ cursor.offset += read;
114
+ const content = Buffer.concat([cursor.partial, buffer.subarray(0, read)]);
115
+ const end = content.lastIndexOf(10);
116
+ const skipFirst = cursor.skipFirst;
117
+ if (end >= 0) cursor.skipFirst = false;
118
+ cursor.partial = content.subarray(end + 1);
119
+ if (cursor.partial.length > maxBytes) {
120
+ cursor.partial = cursor.partial.subarray(-maxBytes);
121
+ cursor.skipFirst = true;
122
+ }
123
+ cursors.set(name, cursor);
124
+ if (end < 0) continue;
125
+ const lines = content.subarray(0, end).toString("utf8").split("\n");
126
+ if (skipFirst) lines.shift();
127
+ for (const line of lines) {
128
+ try {
129
+ const event = JSON.parse(line);
130
+ if (event.event === "agent_surface" && accepted.has(event.publisher) && event.data?.surface?.type) events.push(event);
131
+ } catch { /* Ignore unrelated or malformed observations. */ }
132
+ }
133
+ } catch { /* A writer can rotate the file between stat and read. */ }
134
+ finally { if (fd !== undefined) fs.closeSync(fd); }
135
+ }
136
+ for (const name of cursors.keys()) if (!files.includes(name)) cursors.delete(name);
137
+ return events;
138
+ },
139
+ };
140
+ }
141
+
142
+ module.exports = { createAgentSurfacePublisher, readAgentSurfaceEvents, createAgentSurfaceReader };