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
@@ -1,12 +1,21 @@
1
1
  const fs = require("fs");
2
+ const { randomUUID } = require("crypto");
3
+ const { createAgentSurfacePublisher } = require("../../coordination/history/agentSurface");
4
+ const { contextMeterForUsage } = require("../../ui/agentPresentation");
5
+ const { updateAgentsData } = require("../../coordination/state/agentsStore");
2
6
  const path = require("path");
3
7
  const { getUfooPaths } = require("../../coordination/state/paths");
4
8
  const { spawnSync } = require("child_process");
5
9
  const EventBus = require("../../coordination/bus");
6
- const { readJSON, writeJSON } = require("../../coordination/bus/utils");
10
+ const { normalizeInternalAgentType } = require("../../runtime/contracts/agentMode");
11
+ const { readJSON } = require("../../coordination/bus/utils");
7
12
  const { createActivityStatePublisher } = require("../activity/activityStatePublisher");
8
13
  const { createActivityTracker } = require("../activity/activityTracker");
9
- const { loadConfig, normalizeCodexInternalThreadMode } = require("../../config");
14
+ const { normalizeTraceContext } = require("../runtime/protocol/traceContext");
15
+ const { buildRunObservation, observationFingerprint } = require("../runtime/protocol/runObservation");
16
+ const { getTaskIdFromEvent } = require("../../coordination/bus/messageMeta");
17
+ const { enqueueAgentReport } = require("../../runtime/daemon/reportControlBus");
18
+ const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../../config");
10
19
  const { createCodexThreadProvider } = require("../providers/codexThreadProvider");
11
20
  const { createClaudeThreadProvider } = require("../providers/claudeThreadProvider");
12
21
  const { resolveClaudeUpstreamCredentials } = require("../providers/credentials/claude");
@@ -21,7 +30,13 @@ const {
21
30
  buildDefaultStartupBootstrapPrompt,
22
31
  isValueForCodexOption,
23
32
  } = require("../prompts/defaultBootstrap");
24
- const { hasSharedUfooProtocolPrompt } = require("../prompts/groupBootstrap");
33
+ const {
34
+ hasSharedUfooProtocolPrompt,
35
+ INTERNAL_BUS_DELIVERY_GUIDANCE,
36
+ } = require("../prompts/groupBootstrap");
37
+ const { REPORTING_GUIDANCE } = require("../prompts/reporting");
38
+ const { RESPONSE_LANGUAGE_GUIDANCE } = require("../runtime/prompts/responseLanguage");
39
+ const { COOPERATION_GUIDANCE } = require("../prompts/cooperation");
25
40
  const { buildPromptInjectionText } = require("../../coordination/bus/promptEnvelope");
26
41
 
27
42
  function sleep(ms) {
@@ -145,6 +160,11 @@ function resolveInternalBootstrap({
145
160
  promptText = [defaultPrompt, promptText.trim()].filter(Boolean).join("\n\n");
146
161
  }
147
162
 
163
+ // Stored group/resume bootstraps may predate current runtime guidance.
164
+ if (!promptText.includes(REPORTING_GUIDANCE)) promptText = [promptText, REPORTING_GUIDANCE].join("\n\n");
165
+ if (!promptText.includes(INTERNAL_BUS_DELIVERY_GUIDANCE)) promptText = [promptText, INTERNAL_BUS_DELIVERY_GUIDANCE].join("\n\n");
166
+ if (!promptText.includes(RESPONSE_LANGUAGE_GUIDANCE)) promptText = [promptText, RESPONSE_LANGUAGE_GUIDANCE].join("\n\n");
167
+ if (!promptText.includes(COOPERATION_GUIDANCE)) promptText = [promptText, COOPERATION_GUIDANCE].join("\n\n");
148
168
  return {
149
169
  promptText,
150
170
  extraArgs: nextArgs,
@@ -170,12 +190,13 @@ function readAgentsMap(projectRoot) {
170
190
 
171
191
  function buildInternalPromptMessage(projectRoot, subscriber, evt = {}) {
172
192
  const message = String((evt.data && evt.data.message) || "");
173
- if (evt.__agentViewRaw) return message;
193
+ if (evt.__internalRawInput) return message;
174
194
  return buildPromptInjectionText(evt, subscriber, readAgentsMap(projectRoot));
175
195
  }
176
196
 
177
197
  function createBusSender(projectRoot, subscriber) {
178
198
  const eventBus = new EventBus(projectRoot);
199
+ const surface = createAgentSurfacePublisher(projectRoot, subscriber);
179
200
  let sendQueue = Promise.resolve();
180
201
 
181
202
  function enqueue(target, message) {
@@ -190,24 +211,27 @@ function createBusSender(projectRoot, subscriber) {
190
211
  async function flush() {
191
212
  try {
192
213
  await sendQueue;
214
+ await surface.flush();
193
215
  } catch {
194
216
  // ignore flush errors
195
217
  }
196
218
  }
197
219
 
198
- return { enqueue, flush };
220
+ return { enqueue, flush, surface: surface.enqueue,
221
+ report: report => enqueueAgentReport(projectRoot, { ...report, agent_id: subscriber, source: "runtime" }) };
199
222
  }
200
223
 
201
224
  function isChatUiSource(source = "") {
202
225
  const value = String(source || "").trim();
203
226
  return value === "chat-direct"
204
227
  || value === "chat-agent-view"
205
- || value === "chat-internal-agent-view";
228
+ || value === "chat-internal-agent-view"
229
+ || value === "rust-multi-window";
206
230
  }
207
231
 
208
232
  function isUfooAgentDispatchSource(source = "") {
209
233
  const value = String(source || "").trim();
210
- return value === "ufoo-agent" || value === "ufoo-agent-gate-router";
234
+ return value === "ufoo-agent";
211
235
  }
212
236
 
213
237
  function shouldStreamReplyToPublisher(projectRoot, publisher, evt = {}) {
@@ -228,7 +252,7 @@ function claimQueuedEvents(queueFile) {
228
252
  return claims;
229
253
  }
230
254
 
231
- function parseAgentViewRawInput(message) {
255
+ function parseInternalRawInput(message) {
232
256
  if (typeof message !== "string" || !message.trim()) return null;
233
257
  try {
234
258
  const parsed = JSON.parse(message);
@@ -236,7 +260,7 @@ function parseAgentViewRawInput(message) {
236
260
  return parsed.data;
237
261
  }
238
262
  } catch {
239
- // Not a raw agent-view envelope.
263
+ // Not a raw internal-input envelope.
240
264
  }
241
265
  return null;
242
266
  }
@@ -307,7 +331,8 @@ async function handleEvent(
307
331
  extraArgs = [],
308
332
  threadRuntime = null,
309
333
  bootstrapText = "",
310
- tracker = null
334
+ tracker = null,
335
+ signal = null
311
336
  ) {
312
337
  if (!evt || !evt.data || !evt.data.message) return;
313
338
  const memoryPrefix = buildMemoryPrefix(projectRoot);
@@ -318,6 +343,27 @@ async function handleEvent(
318
343
  .join("\n\n");
319
344
  const publisher = evt.publisher || "unknown";
320
345
  const streamToPublisher = shouldStreamReplyToPublisher(projectRoot, publisher, evt);
346
+ const inherited = normalizeTraceContext(evt.data.runtime_context);
347
+ const taskId = getTaskIdFromEvent(evt) || inherited.taskId || `worker-${randomUUID()}`;
348
+ const runtimeContext = { ...inherited, taskId, traceId: inherited.traceId || taskId,
349
+ taskRunId: `worker-run-${randomUUID()}`, requestId: `bus-${evt.seq || randomUUID()}`, attemptId: `attempt-${randomUUID()}`,
350
+ requestKind: publisher === "ufoo-agent" && getTaskIdFromEvent(evt) ? "worker-task" : "bus-message" };
351
+ const emitSurface = event => busSender.surface?.({ ...runtimeContext, task_id: taskId, agentId: subscriber,
352
+ provider, model, sessionId: threadRuntime?.thread?.id || "", ...event });
353
+ const delegated = publisher === "ufoo-agent" && Boolean(getTaskIdFromEvent(evt));
354
+ const reportLifecycle = async (phase, error = "", meta = {}) => {
355
+ if (!delegated || typeof busSender.report !== "function") return;
356
+ await busSender.report({ task_id: taskId, phase, scope: "private", controller_id: "ufoo-agent", error,
357
+ meta: { ...runtimeContext, ...meta } });
358
+ };
359
+ emitSurface({ type: "task_started", message: evt.data.message, publisher, queueSequence: evt.seq });
360
+ if (provider !== "ucode") emitSurface({ type: "run_config", configuration: buildRunObservation({ provider, model,
361
+ executionKind: "sdk", systemPrompt: bootstrapText, prompt: evt.data.message,
362
+ requestKind: runtimeContext.requestKind,
363
+ engineFingerprint: observationFingerprint(handleThreadedEvent.toString()),
364
+ tools: threadRuntime?.toolRuntime?.tools || [],
365
+ thinkingLevel: String(threadRuntime?.thread?.threadOptions?.modelReasoningEffort || threadRuntime?.thread?.agentOptions?.effort || "") }) });
366
+ await reportLifecycle("start");
321
367
 
322
368
  const emitStreamDelta = (delta) => {
323
369
  const text = String(delta || "");
@@ -330,17 +376,25 @@ async function handleEvent(
330
376
  return handleThreadedEvent({
331
377
  agentType,
332
378
  provider,
379
+ model,
333
380
  publisher,
334
381
  prompt,
382
+ userMessage: evt.data.message,
335
383
  busSender,
336
384
  emitStreamDelta,
337
385
  streamToPublisher,
338
386
  threadRuntime,
339
387
  tracker,
388
+ emitSurface,
389
+ runtimeContext,
390
+ reportLifecycle,
391
+ signal,
340
392
  });
341
393
  }
342
394
 
343
- const errorText = `[internal:${agentType}] error: no thread runtime available for provider ${provider}; cliRunner fallback has been removed`;
395
+ const errorText = `[internal:${agentType}] error: ${threadRuntime?.error?.message || `agent runtime not initialized for provider ${provider}`}`;
396
+ emitSurface({ type: "task_failed", error: errorText });
397
+ await reportLifecycle("error", errorText);
344
398
  // eslint-disable-next-line no-console
345
399
  console.error(errorText);
346
400
  if (streamToPublisher) {
@@ -350,6 +404,7 @@ async function handleEvent(
350
404
  busSender.enqueue(publisher, errorText);
351
405
  }
352
406
  await busSender.flush();
407
+ return { ok: false, error: errorText };
353
408
  }
354
409
 
355
410
  function compactToolDetail(value = "", maxLength = 120) {
@@ -380,20 +435,21 @@ function toNonNegativeInt(value) {
380
435
  }
381
436
 
382
437
  // Normalizes provider usage payloads (claude/codex thread events) onto the
383
- // metric fields read by extractModelMetrics in agents/controller/loopRuntime.js.
438
+ // metric fields used by provider usage summaries.
384
439
  function normalizeTurnUsage(usage = null) {
385
440
  const item = usage && typeof usage === "object" ? usage : {};
386
441
  return {
387
- input_tokens: toNonNegativeInt(item.input_tokens || item.prompt_tokens),
388
- output_tokens: toNonNegativeInt(item.output_tokens || item.completion_tokens),
442
+ input_tokens: toNonNegativeInt(item.input_tokens ?? item.prompt_tokens ?? item.input),
443
+ output_tokens: toNonNegativeInt(item.output_tokens ?? item.completion_tokens ?? item.output),
389
444
  cache_read_tokens: toNonNegativeInt(
390
445
  item.cache_read_tokens
391
446
  || item.cache_read_input_tokens
392
447
  || item.cached_input_tokens
448
+ || item.cacheRead
393
449
  || (item.input_tokens_details && item.input_tokens_details.cached_tokens)
394
450
  ),
395
451
  cache_creation_tokens: toNonNegativeInt(
396
- item.cache_creation_tokens || item.cache_creation_input_tokens
452
+ item.cache_creation_tokens || item.cache_creation_input_tokens || item.cacheCreation
397
453
  ),
398
454
  };
399
455
  }
@@ -401,23 +457,38 @@ function normalizeTurnUsage(usage = null) {
401
457
  async function handleThreadedEvent({
402
458
  agentType,
403
459
  provider,
460
+ model = "",
404
461
  publisher,
405
462
  prompt,
463
+ userMessage = "",
406
464
  busSender,
407
465
  emitStreamDelta,
408
466
  streamToPublisher = true,
409
467
  threadRuntime,
410
468
  tracker = null,
469
+ emitSurface = () => {},
470
+ runtimeContext = {},
471
+ reportLifecycle = async () => {},
472
+ signal = null,
411
473
  }) {
412
474
  try {
413
475
  const plainReplyParts = [];
476
+ let finalReply;
414
477
  let turnUsage = null;
415
478
  let stopReason = "";
479
+ let waitingForUser = false;
416
480
  if (tracker && typeof tracker.notifyTurnStart === "function") {
417
481
  tracker.notifyTurnStart();
418
482
  }
419
- for await (const event of threadRuntime.thread.runStreamed(prompt, {})) {
483
+ const started = Date.now();
484
+ for await (const event of threadRuntime.thread.runStreamed(prompt, { ...(signal ? { signal } : {}), runtimeContext, ...(provider === "ucode" ? { userInput: userMessage } : {}) })) {
420
485
  if (!event || typeof event !== "object") continue;
486
+ emitSurface(event.type === "tool_call" && event.args !== undefined
487
+ ? { ...event, argumentFingerprint: observationFingerprint(event.args) } : event);
488
+ if (["usage", "turn_completed"].includes(event.type) && event.usage && provider !== "ucode") {
489
+ emitSurface({ type: "context_usage", meter: contextMeterForUsage(event.usage, model || threadRuntime.thread.model, provider) });
490
+ }
491
+ if (event.type === "interaction" || (event.type === "status" && event.state === "waiting_input")) waitingForUser = true;
421
492
  if (typeof threadRuntime.syncProviderSessionId === "function") {
422
493
  threadRuntime.syncProviderSessionId();
423
494
  }
@@ -435,9 +506,16 @@ async function handleThreadedEvent({
435
506
  if (streamToPublisher && summary) {
436
507
  emitStreamDelta(`\nTool: ${summary}\n`);
437
508
  }
509
+ } else if (event.type === "tool_result" && streamToPublisher) {
510
+ const output = typeof event.output === "string" ? event.output
511
+ : Array.isArray(event.output) ? event.output.map((block) => block && block.text || "").join("\n")
512
+ : event.output && typeof event.output === "object" ? JSON.stringify(event.output) : "";
513
+ if (output) emitStreamDelta(output.slice(0, 4000) + (output.endsWith("\n") ? "" : "\n"));
514
+ if (Number.isFinite(event.exitCode) && event.exitCode !== 0) emitStreamDelta(`[exit ${event.exitCode}]\n`);
438
515
  } else if (event.type === "usage" && event.usage) {
439
516
  turnUsage = normalizeTurnUsage(event.usage);
440
517
  } else if (event.type === "turn_completed") {
518
+ if (typeof event.finalText === "string") finalReply = event.finalText;
441
519
  if (event.usage) turnUsage = normalizeTurnUsage(event.usage);
442
520
  if (event.stopReason) stopReason = String(event.stopReason);
443
521
  } else if (event.type === "turn_failed") {
@@ -447,13 +525,18 @@ async function handleThreadedEvent({
447
525
  if (typeof threadRuntime.syncProviderSessionId === "function") {
448
526
  threadRuntime.syncProviderSessionId();
449
527
  }
528
+ const reply = (finalReply === undefined ? plainReplyParts.join("") : finalReply).trim();
529
+ emitSurface({ type: waitingForUser ? "task_paused" : "task_completed", usage: turnUsage, durationMs: Date.now() - started,
530
+ finalTextCharacters: [...reply].length });
531
+ if (waitingForUser && tracker?.requestUserInput) tracker.requestUserInput("reply");
450
532
 
451
533
  if (streamToPublisher) {
452
534
  const doneEnvelope = { stream: true, done: true, reason: "complete" };
453
535
  if (turnUsage) doneEnvelope.usage = turnUsage;
454
536
  busSender.enqueue(publisher, JSON.stringify(doneEnvelope));
455
537
  } else {
456
- const reply = plainReplyParts.join("").trim();
538
+ // Live progress belongs to the worker pane. Peers receive only the final
539
+ // answer, including an explicitly empty ack-only result.
457
540
  if (reply) busSender.enqueue(publisher, reply);
458
541
  }
459
542
  await busSender.flush();
@@ -465,13 +548,18 @@ async function handleThreadedEvent({
465
548
  },
466
549
  };
467
550
  } catch (err) {
468
- if (threadRuntime && typeof threadRuntime.rebuildThread === "function") {
469
- await threadRuntime.rebuildThread();
470
- }
471
551
  if (tracker && typeof tracker.markIdle === "function") {
472
552
  tracker.markIdle();
473
553
  }
474
554
  const errorText = `[internal:${agentType}] error: ${err && err.message ? err.message : "unknown error"}`;
555
+ const cancelled = signal?.aborted || err?.code === "cancelled" || err?.name === "AbortError";
556
+ emitSurface(cancelled
557
+ ? { type: "task_cancelled" } : { type: "task_failed", error: errorText });
558
+ await reportLifecycle("error", errorText, { cancelled });
559
+ if (!cancelled && threadRuntime && typeof threadRuntime.rebuildThread === "function") {
560
+ try { await threadRuntime.rebuildThread(); }
561
+ catch (recoveryError) { console.error(`[internal:${agentType}] recovery failed: ${recoveryError?.message || "unknown error"}`); }
562
+ }
475
563
  // eslint-disable-next-line no-console
476
564
  console.error(errorText);
477
565
  if (streamToPublisher) {
@@ -491,14 +579,6 @@ async function handleThreadedEvent({
491
579
  }
492
580
  }
493
581
 
494
- function getCodexThreadMode(projectRoot) {
495
- const envValue = process.env.UFOO_CODEX_INTERNAL_THREAD_MODE;
496
- if (typeof envValue === "string" && envValue.trim()) {
497
- return normalizeCodexInternalThreadMode(envValue);
498
- }
499
- return loadConfig(projectRoot).codexInternalThreadMode;
500
- }
501
-
502
582
  function getWorkerThreadToolMode() {
503
583
  return normalizeWorkerThreadToolMode(process.env.UFOO_CODEX_INTERNAL_THREAD_TOOLS);
504
584
  }
@@ -587,14 +667,6 @@ function buildWorkerThreadToolRuntime({ projectRoot, subscriber, observer }) {
587
667
  };
588
668
  }
589
669
 
590
- function getClaudeThreadMode() {
591
- const envValue = process.env.UFOO_CLAUDE_INTERNAL_THREAD_MODE;
592
- const raw = String(envValue || "").trim().toLowerCase();
593
- if (raw === "legacy" || raw === "off" || raw === "disabled" || raw === "0") return "legacy";
594
- if (raw === "api") return "api";
595
- return "api";
596
- }
597
-
598
670
  function buildClaudeAuthProvider(projectRoot) {
599
671
  const config = loadConfig(projectRoot);
600
672
  return async () => {
@@ -612,29 +684,49 @@ function persistProviderSessionId(projectRoot, subscriber, providerSessionId) {
612
684
  if (!projectRoot || !subscriber || !id) return false;
613
685
  try {
614
686
  const agentsFile = getUfooPaths(projectRoot).agentsFile;
615
- const parsed = fs.existsSync(agentsFile)
616
- ? readJSON(agentsFile, null)
617
- : {};
618
- if (!parsed) return false;
619
- if (!parsed.agents || typeof parsed.agents !== "object") return false;
620
- if (!parsed.agents[subscriber] || typeof parsed.agents[subscriber] !== "object") {
621
- appendAgentRegistryDiagnostic(agentsFile, "provider_session_subscriber_missing", {
622
- source: "agent.internalRunner.persistProviderSessionId",
623
- subscriber,
624
- known_ids: Object.keys(parsed.agents || {}).sort(),
625
- });
626
- return false;
627
- }
628
- if (parsed.agents[subscriber].provider_session_id === id) return false;
629
- parsed.agents[subscriber].provider_session_id = id;
630
- parsed.agents[subscriber].provider_session_updated_at = new Date().toISOString();
631
- writeJSON(agentsFile, parsed);
632
- return true;
687
+ if (!fs.existsSync(agentsFile)) return false;
688
+ return updateAgentsData(agentsFile, (parsed) => {
689
+ if (!parsed.agents || typeof parsed.agents !== "object") return false;
690
+ if (!parsed.agents[subscriber] || typeof parsed.agents[subscriber] !== "object") {
691
+ appendAgentRegistryDiagnostic(agentsFile, "provider_session_subscriber_missing", {
692
+ source: "agent.internalRunner.persistProviderSessionId",
693
+ subscriber,
694
+ known_ids: Object.keys(parsed.agents || {}).sort(),
695
+ });
696
+ return false;
697
+ }
698
+ if (parsed.agents[subscriber].provider_session_id === id) return false;
699
+ parsed.agents[subscriber].provider_session_id = id;
700
+ parsed.agents[subscriber].provider_session_updated_at = new Date().toISOString();
701
+ return true;
702
+ });
633
703
  } catch {
634
704
  return false;
635
705
  }
636
706
  }
637
707
 
708
+ function resolveInternalModel({ projectRoot, provider, extraArgs = [], env = process.env }) {
709
+ for (let index = 0; index < extraArgs.length; index++) {
710
+ if (["-m", "--model"].includes(extraArgs[index]) && extraArgs[index + 1]) return String(extraArgs[index + 1]);
711
+ if (String(extraArgs[index]).startsWith("--model=")) return String(extraArgs[index]).slice(8);
712
+ }
713
+ if (env.UFOO_AGENT_MODEL) return String(env.UFOO_AGENT_MODEL);
714
+ // Native ucode resolves its own provider/model in the coding host.
715
+ if (provider === "ucode") return "";
716
+ const config = loadConfig(projectRoot);
717
+ return (sameModelProvider(config.agentProvider, provider) && config.agentModel)
718
+ || defaultAgentModelForProvider(provider);
719
+ }
720
+
721
+ function resolveInternalCodexEffort(extraArgs = []) {
722
+ for (let index = 0; index < extraArgs.length; index++) {
723
+ if (!["-c", "--config"].includes(extraArgs[index])) continue;
724
+ const match = String(extraArgs[index + 1] || "").match(/^model_reasoning_effort\s*=\s*["']?(none|minimal|low|medium|high|xhigh|max)["']?$/);
725
+ if (match) return match[1];
726
+ }
727
+ return "medium";
728
+ }
729
+
638
730
  function createThreadRuntime({ projectRoot, provider, model, extraArgs = [], subscriber = "", providerSessionId = "" }) {
639
731
  const disabledRuntime = {
640
732
  enabled: false,
@@ -656,11 +748,18 @@ function createThreadRuntime({ projectRoot, provider, model, extraArgs = [], sub
656
748
  return changed;
657
749
  }
658
750
 
659
- if (provider === "codex-cli") {
660
- if (getCodexThreadMode(projectRoot) !== "api") {
661
- return disabledRuntime;
662
- }
751
+ if (provider === "ucode") {
752
+ const { createInternalCodingThread } = require("../../code/internalThread");
753
+ const thread = createInternalCodingThread({ workspaceRoot: projectRoot, model, sessionId: initialProviderSessionId });
754
+ return {
755
+ enabled: true, thread,
756
+ syncProviderSessionId: () => rememberProviderSessionId(thread),
757
+ rebuildThread: async () => {},
758
+ close: () => thread.close(),
759
+ };
760
+ }
663
761
 
762
+ if (provider === "codex-cli") {
664
763
  try {
665
764
  const toolRuntime = buildWorkerThreadToolRuntime({
666
765
  projectRoot,
@@ -671,6 +770,7 @@ function createThreadRuntime({ projectRoot, provider, model, extraArgs = [], sub
671
770
  cwd: projectRoot,
672
771
  extraArgs,
673
772
  tools: toolRuntime.tools,
773
+ threadOptions: { modelReasoningEffort: resolveInternalCodexEffort(extraArgs) },
674
774
  });
675
775
  let thread = initialProviderSessionId
676
776
  ? providerInstance.resumeThread(initialProviderSessionId)
@@ -694,6 +794,7 @@ function createThreadRuntime({ projectRoot, provider, model, extraArgs = [], sub
694
794
  cwd: projectRoot,
695
795
  extraArgs,
696
796
  tools: toolRuntime.tools,
797
+ threadOptions: { modelReasoningEffort: resolveInternalCodexEffort(extraArgs) },
697
798
  });
698
799
  thread = savedProviderSessionId
699
800
  ? providerInstance.resumeThread(savedProviderSessionId)
@@ -705,15 +806,12 @@ function createThreadRuntime({ projectRoot, provider, model, extraArgs = [], sub
705
806
  }
706
807
  },
707
808
  };
708
- } catch {
709
- return disabledRuntime;
809
+ } catch (error) {
810
+ return { ...disabledRuntime, error };
710
811
  }
711
812
  }
712
813
 
713
814
  if (provider === "claude-cli") {
714
- if (getClaudeThreadMode() !== "api") {
715
- return disabledRuntime;
716
- }
717
815
  if (typeof createClaudeThreadProvider !== "function") {
718
816
  return disabledRuntime;
719
817
  }
@@ -755,8 +853,8 @@ function createThreadRuntime({ projectRoot, provider, model, extraArgs = [], sub
755
853
  }
756
854
  },
757
855
  };
758
- } catch {
759
- return disabledRuntime;
856
+ } catch (error) {
857
+ return { ...disabledRuntime, error };
760
858
  }
761
859
  }
762
860
 
@@ -764,15 +862,16 @@ function createThreadRuntime({ projectRoot, provider, model, extraArgs = [], sub
764
862
  }
765
863
 
766
864
  async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs = [] }) {
865
+ const normalizedAgentType = normalizeInternalAgentType(agentType);
866
+ if (!normalizedAgentType) throw new Error(`unsupported internal agent type: ${agentType}; use codex, claude or ucode`);
767
867
  // Internal runner 必须由 daemon 启动,UFOO_SUBSCRIBER_ID 应该已经设置
768
868
  const { subscriber, agentType: parsedAgentType, sessionId } = parseSubscriberId();
769
869
  const nickname = process.env.UFOO_NICKNAME || "";
770
870
 
771
871
  const queueDir = path.join(getUfooPaths(projectRoot).busQueuesDir, safeSubscriber(subscriber));
772
872
  const queueFile = path.join(queueDir, "pending.jsonl");
773
- const normalizedAgentType = String(agentType || "").trim().toLowerCase();
774
- const provider = normalizedAgentType === "codex" ? "codex-cli" : "claude-cli";
775
- const model = process.env.UFOO_AGENT_MODEL || "";
873
+ const provider = { ucode: "ucode", codex: "codex-cli", claude: "claude-cli" }[normalizedAgentType];
874
+ const model = resolveInternalModel({ projectRoot, provider, extraArgs });
776
875
  const bootstrap = resolveInternalBootstrap({
777
876
  projectRoot,
778
877
  agentType: normalizedAgentType,
@@ -794,9 +893,14 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
794
893
  let processing = false;
795
894
  let lastHeartbeat = 0;
796
895
  const HEARTBEAT_INTERVAL = 30000; // 30秒心跳间隔
896
+ const runnerAbort = new AbortController();
797
897
 
798
898
  const stop = () => {
799
899
  running = false;
900
+ runnerAbort.abort("runner_stopped");
901
+ // Closing the provider aborts an in-flight turn, which records cancellation
902
+ // and queues a terminal report before the runner drains and exits.
903
+ threadRuntime.close().catch(error => console.error(`[internal] stop failed: ${error.message}`));
800
904
  };
801
905
 
802
906
  process.on("SIGTERM", stop);
@@ -859,7 +963,7 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
859
963
  for (const claim of claims) {
860
964
  const evt = claim.event;
861
965
  const runnableEvents = [];
862
- const rawInput = parseAgentViewRawInput(evt && evt.data ? evt.data.message : "");
966
+ const rawInput = parseInternalRawInput(evt && evt.data ? evt.data.message : "");
863
967
  if (rawInput === null) {
864
968
  runnableEvents.push(evt);
865
969
  } else {
@@ -868,7 +972,7 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
868
972
  for (const message of submissions) {
869
973
  runnableEvents.push({
870
974
  ...evt,
871
- __agentViewRaw: true,
975
+ __internalRawInput: true,
872
976
  data: {
873
977
  ...(evt.data || {}),
874
978
  message,
@@ -896,9 +1000,10 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
896
1000
  bootstrap.extraArgs,
897
1001
  threadRuntime,
898
1002
  bootstrap.promptText,
899
- activityTracker
1003
+ activityTracker,
1004
+ runnerAbort.signal
900
1005
  );
901
- if (runnableEvent.__agentViewRaw) {
1006
+ if (runnableEvent.__internalRawInput) {
902
1007
  getInteractiveSession(runnableEvent.publisher || "unknown").writeResponsePrompt();
903
1008
  }
904
1009
  }
@@ -912,7 +1017,7 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
912
1017
  // 处理消息后更新心跳
913
1018
  updateHeartbeat();
914
1019
  lastHeartbeat = now;
915
- if (handledAny) {
1020
+ if (handledAny && activityTracker.getState().state !== "waiting_input") {
916
1021
  activityTracker.markIdle();
917
1022
  }
918
1023
  await busSender.flush();
@@ -934,13 +1039,13 @@ module.exports = {
934
1039
  handleEvent,
935
1040
  handleThreadedEvent,
936
1041
  createThreadRuntime,
937
- getCodexThreadMode,
1042
+ resolveInternalModel,
1043
+ resolveInternalCodexEffort,
938
1044
  getWorkerThreadToolMode,
939
1045
  buildWorkerThreadToolRuntime,
940
1046
  normalizeWorkerThreadToolMode,
941
- getClaudeThreadMode,
942
1047
  buildClaudeAuthProvider,
943
- parseAgentViewRawInput,
1048
+ parseInternalRawInput,
944
1049
  createInteractiveInputSession,
945
1050
  resolveInternalBootstrap,
946
1051
  persistProviderSessionId,
@@ -7,6 +7,5 @@ module.exports = {
7
7
  ReadyDetector: require("./readyDetector"),
8
8
  ...require("./agyConversation"),
9
9
  ...require("./launchEnvironment"),
10
- ...require("./ptyRunner"),
11
10
  ...require("./publisherRouting"),
12
11
  };