u-foo 3.1.7 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/README.md +172 -13
  2. package/README.zh-CN.md +108 -13
  3. package/SKILLS/ufoo/SKILL.md +15 -3
  4. package/SKILLS/ufoo-bus/SKILL.md +21 -1
  5. package/bin/uclaude.js +4 -0
  6. package/bin/ucodex.js +4 -0
  7. package/bin/ufoo.js +3 -1
  8. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  9. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  10. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  11. package/dist/tui/linux-x64/ufoo-tui +0 -0
  12. package/package.json +10 -3
  13. package/scripts/postinstall-skills.js +53 -0
  14. package/scripts/postinstall.js +11 -16
  15. package/scripts/smoke-native-messages.js +214 -0
  16. package/src/agents/activity/activityStateWriter.js +37 -38
  17. package/src/agents/capabilities/agentManagement/index.js +4 -0
  18. package/src/agents/capabilities/agentManagement/service.js +113 -0
  19. package/src/agents/capabilities/agentRouting/index.js +4 -0
  20. package/src/agents/capabilities/coding/index.js +32 -0
  21. package/src/agents/capabilities/coordination/index.js +37 -0
  22. package/src/agents/capabilities/globalRouting/index.js +5 -0
  23. package/src/agents/capabilities/groups/index.js +3 -0
  24. package/src/agents/capabilities/index.js +25 -0
  25. package/src/agents/capabilities/planning/index.js +123 -0
  26. package/src/agents/capabilities/planning/main.js +28 -0
  27. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  28. package/src/agents/capabilities/scheduling/index.js +3 -0
  29. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  30. package/src/agents/capabilities/skills/index.js +12 -0
  31. package/src/agents/capabilities/taskExecution/index.js +3 -0
  32. package/src/agents/capabilities/taskReports/index.js +6 -0
  33. package/src/agents/controller/controllerToolExecutor.js +6 -4
  34. package/src/agents/controller/loopRuntime.js +85 -221
  35. package/src/agents/controller/ufooAgent.js +1 -0
  36. package/src/agents/internal/internalRunner.js +103 -32
  37. package/src/agents/launch/launcher.js +88 -6
  38. package/src/agents/launch/nativeCapabilities.js +40 -0
  39. package/src/agents/launch/nativeMessages.js +362 -0
  40. package/src/agents/launch/notifier.js +13 -18
  41. package/src/agents/launch/readyDetector.js +26 -12
  42. package/src/agents/profiles/coding.js +6 -0
  43. package/src/agents/profiles/globalRouter.js +2 -0
  44. package/src/agents/profiles/main.js +5 -0
  45. package/src/agents/prompts/groupBootstrap.js +10 -0
  46. package/src/agents/prompts/mainAgent.js +39 -0
  47. package/src/agents/prompts/native/tasks.js +2 -2
  48. package/src/agents/prompts/native/ufoo.js +3 -0
  49. package/src/agents/providers/claudeEventTranslator.js +6 -1
  50. package/src/agents/providers/claudeThreadProvider.js +44 -2
  51. package/src/agents/providers/codexEventTranslator.js +47 -7
  52. package/src/agents/providers/codexThreadProvider.js +3 -2
  53. package/src/agents/providers/controllerJsonTransport.js +28 -0
  54. package/src/agents/providers/credentials/claude.js +10 -3
  55. package/src/agents/providers/nativeTransport.js +1135 -0
  56. package/src/agents/providers/runtimeConfig.js +186 -0
  57. package/src/agents/providers/thinkingLevels.js +132 -0
  58. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  59. package/src/agents/providers/transports/index.js +10 -0
  60. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  61. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  62. package/src/agents/providers/transports/responsesProtocol.js +499 -0
  63. package/src/agents/providers/transports/systemBlocks.js +16 -0
  64. package/src/agents/providers/transports/transportContract.js +50 -0
  65. package/src/agents/providers/transports/visionBlocks.js +151 -0
  66. package/src/agents/providers/upstreamTransport.js +13 -4
  67. package/src/agents/runtime/composeCapabilities.js +89 -0
  68. package/src/agents/runtime/context/commandStore.js +43 -0
  69. package/src/agents/runtime/context/contextWindow.js +119 -0
  70. package/src/agents/runtime/context/fileLock.js +36 -0
  71. package/src/agents/runtime/context/runtimeStore.js +126 -0
  72. package/src/agents/runtime/context/sessionJournal.js +360 -0
  73. package/src/agents/runtime/context/sessionStore.js +57 -0
  74. package/src/agents/runtime/core/agentLoop.js +270 -0
  75. package/src/agents/runtime/core/stableJson.js +29 -0
  76. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  77. package/src/agents/runtime/createAgentRuntime.js +247 -0
  78. package/src/agents/runtime/index.js +14 -0
  79. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  80. package/src/agents/runtime/protocol/materialize.js +107 -0
  81. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  82. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  83. package/src/agents/runtime/tasks/scheduler.js +73 -0
  84. package/src/agents/runtime/tools/registry.js +57 -0
  85. package/src/app/chat/ChatController.js +14 -3
  86. package/src/app/chat/agentDirectory.js +8 -2
  87. package/src/app/chat/commandExecutor.js +36 -46
  88. package/src/app/chat/commands.js +14 -7
  89. package/src/app/chat/daemonConnection.js +58 -5
  90. package/src/app/chat/daemonMessageRouter.js +61 -3
  91. package/src/app/chat/inputSubmitHandler.js +14 -2
  92. package/src/app/chat/launchRequestContext.js +42 -0
  93. package/src/app/chat/multiWindow/paneManager.js +85 -165
  94. package/src/app/chat/streamState.js +3 -3
  95. package/src/app/chat/transport.js +1 -1
  96. package/src/app/cli/busCoreCommands.js +9 -0
  97. package/src/app/cli/features/doctor.js +33 -0
  98. package/src/app/cli/features/skills.js +16 -4
  99. package/src/app/cli/reportCoreCommands.js +37 -0
  100. package/src/app/cli/run.js +40 -39
  101. package/src/code/agent.js +16 -4
  102. package/src/code/context/artifacts.js +12 -11
  103. package/src/code/context/assembler.js +2 -1
  104. package/src/code/context/promptLayers.js +1 -13
  105. package/src/code/context/stableJson.js +2 -27
  106. package/src/code/contextWindow.js +2 -117
  107. package/src/code/conversation/sessionJournal.js +3 -349
  108. package/src/code/internalThread.js +100 -0
  109. package/src/code/nativeRunner.js +36 -2667
  110. package/src/code/protocol/faultHarness.js +2 -88
  111. package/src/code/protocol/materialize.js +2 -105
  112. package/src/code/protocol/toolCallLedger.js +5 -215
  113. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  114. package/src/code/providers/openaiChatTransport.js +2 -114
  115. package/src/code/providers/openaiResponsesTransport.js +2 -117
  116. package/src/code/providers/responsesProtocol.js +2 -497
  117. package/src/code/providers/transportContract.js +2 -48
  118. package/src/code/providers/visionBlocks.js +2 -149
  119. package/src/code/sessionStore.js +24 -96
  120. package/src/code/thinkingLevels.js +1 -130
  121. package/src/code/toolLoopGuard.js +3 -49
  122. package/src/code/tools/artifactRead.js +1 -1
  123. package/src/code/tools/executor.js +373 -0
  124. package/src/code/tools/specs.js +312 -0
  125. package/src/config.js +81 -67
  126. package/src/coordination/bus/deliveryQueue.js +16 -2
  127. package/src/coordination/bus/index.js +2 -6
  128. package/src/coordination/bus/inject.js +13 -5
  129. package/src/coordination/bus/nativeReceipts.js +100 -0
  130. package/src/coordination/bus/queue.js +1 -3
  131. package/src/coordination/bus/utils.js +7 -3
  132. package/src/coordination/history/agentSurface.js +142 -0
  133. package/src/coordination/history/controllerSummary.js +23 -0
  134. package/src/coordination/memory/index.js +5 -21
  135. package/src/coordination/report/store.js +103 -83
  136. package/src/coordination/state/agentsStore.js +57 -3
  137. package/src/coordination/state/fileLock.js +2 -0
  138. package/src/coordination/state/workspaceAccess.js +36 -0
  139. package/src/runtime/contracts/agentMode.js +17 -0
  140. package/src/runtime/contracts/eventContract.js +3 -0
  141. package/src/runtime/contracts/uiProtocol.js +4 -0
  142. package/src/runtime/daemon/agentHost.js +375 -0
  143. package/src/runtime/daemon/busBridge.js +396 -0
  144. package/src/runtime/daemon/claudeChannel.js +159 -0
  145. package/src/runtime/daemon/controlPlaneService.js +27 -17
  146. package/src/runtime/daemon/cronOps.js +25 -17
  147. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  148. package/src/runtime/daemon/executionPaths.js +30 -0
  149. package/src/runtime/daemon/globalDaemon.js +28 -1
  150. package/src/runtime/daemon/groupOrchestrator.js +1 -0
  151. package/src/runtime/daemon/index.js +114 -344
  152. package/src/runtime/daemon/ipcServer.js +32 -10
  153. package/src/runtime/daemon/mcpConfigure.js +113 -20
  154. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  155. package/src/runtime/daemon/mcpServer.js +7 -4
  156. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  157. package/src/runtime/daemon/ops.js +22 -17
  158. package/src/runtime/daemon/promptRequest.js +23 -4
  159. package/src/runtime/daemon/providerSessions.js +67 -33
  160. package/src/runtime/daemon/reportControlBus.js +59 -25
  161. package/src/runtime/daemon/status.js +4 -0
  162. package/src/runtime/privacy/redactor.js +2 -2
  163. package/src/runtime/projects/identity.js +2 -1
  164. package/src/runtime/projects/registry.js +98 -38
  165. package/src/tools/controllerSchemas.js +24 -0
  166. package/src/tools/handlers/dispatchMessage.js +5 -2
  167. package/src/tools/handlers/listAgents.js +3 -1
  168. package/src/tools/handlers/readBusSummary.js +3 -1
  169. package/src/tools/handlers/readProjectRegistry.js +29 -2
  170. package/src/tools/handlers/routeAgent.js +35 -0
  171. package/src/tools/index.js +1 -0
  172. package/src/tools/registry.js +2 -0
  173. package/src/tools/schemaFixtures.js +16 -3
  174. package/src/tools/tier1/routeAgent.js +2 -2
  175. package/src/tools/tier2/runtimeCoordination.js +38 -0
  176. package/src/tools/types.js +2 -0
  177. package/src/ui/agentPresentation.js +109 -0
  178. package/src/ui/agentSurface.js +270 -0
  179. package/src/ui/format/banner.js +8 -11
  180. package/src/ui/format/startupBanner.js +50 -0
  181. package/src/ui/multiPaneBusMirror.js +29 -3
  182. package/src/ui/rustChatHost.js +170 -438
  183. package/src/ui/rustMultiSession.js +225 -51
  184. package/src/ui/rustUcodeHost.js +20 -87
  185. package/src/ui/settingsBridge.js +7 -4
  186. package/src/app/chat/agentEnter.js +0 -70
  187. package/src/app/chat/multiWindow/index.js +0 -310
  188. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  189. package/src/app/chat/multiWindow/renderer.js +0 -420
  190. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  191. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  192. package/src/ui/multiWindowHandoff.js +0 -232
  193. package/src/ui/ptyHandoff.js +0 -23
@@ -302,23 +302,23 @@ function buildShellEnvPrefix(extraEnv = {}) {
302
302
  // would stay blocked until restart.
303
303
  const APPLESCRIPT_TIMEOUT_MS = 10000;
304
304
 
305
- function killAfterTimeout(proc, cmd, onTimeout) {
305
+ function killAfterTimeout(proc, cmd, onTimeout, timeoutMs = APPLESCRIPT_TIMEOUT_MS) {
306
306
  return setTimeout(() => {
307
307
  try {
308
308
  proc.kill("SIGKILL");
309
309
  } catch {
310
310
  // process already exited, nothing to kill
311
311
  }
312
- onTimeout(new Error(`${cmd} timeout after ${APPLESCRIPT_TIMEOUT_MS}ms`));
313
- }, APPLESCRIPT_TIMEOUT_MS);
312
+ onTimeout(new Error(`${cmd} timeout after ${timeoutMs}ms`));
313
+ }, timeoutMs);
314
314
  }
315
315
 
316
- function runAppleScript(lines) {
316
+ function runAppleScript(lines, options = {}) {
317
317
  return new Promise((resolve, reject) => {
318
318
  const proc = spawn("osascript", lines.flatMap((l) => ["-e", l]));
319
319
  let stderr = "";
320
320
  let stdout = "";
321
- const timeout = killAfterTimeout(proc, "osascript", reject);
321
+ const timeout = killAfterTimeout(proc, "osascript", reject, options.timeoutMs);
322
322
  proc.stderr.on("data", (d) => {
323
323
  stderr += d.toString("utf8");
324
324
  });
@@ -451,7 +451,7 @@ async function closeTerminalWindowByTty(ttyPath, preferApp = "") {
451
451
  "end tell",
452
452
  'return "not found"',
453
453
  ];
454
- const res = await runAppleScript(script);
454
+ const res = await runAppleScript(script, { timeoutMs: 1000 });
455
455
  return res === "ok";
456
456
  };
457
457
 
@@ -470,7 +470,7 @@ async function closeTerminalWindowByTty(ttyPath, preferApp = "") {
470
470
  "end tell",
471
471
  'return "not found"',
472
472
  ];
473
- const res = await runAppleScript(script);
473
+ const res = await runAppleScript(script, { timeoutMs: 1000 });
474
474
  return res === "ok";
475
475
  };
476
476
 
@@ -598,6 +598,7 @@ async function spawnManagedHostAgent(
598
598
  const EventBus = require("../../coordination/bus");
599
599
  const existing = listSubscribers(projectRoot, agentType);
600
600
  let subscriberId = "";
601
+ let agentHandle = "";
601
602
  let preRegistrationError = null;
602
603
  try {
603
604
  const bus = new EventBus(projectRoot);
@@ -607,11 +608,11 @@ async function spawnManagedHostAgent(
607
608
  subscriberId = `${agentType}:${sessionToken}`;
608
609
  const defaultNickname = agentType === "ufoo-code" ? "ucode" : normalizedAgent;
609
610
  const finalNickname = nickname || defaultNickname;
610
- await bus.subscriberManager.join(sessionToken, agentType, finalNickname, {
611
- launchMode: "host",
611
+ const registration = await require("./controlPlaneService").registerAgentFull(projectRoot, {
612
+ sessionId: sessionToken, agentType, nickname: finalNickname, launchMode: "host",
612
613
  parentPid: process.pid,
613
- });
614
- bus.saveBusData();
614
+ }, { validateParentPid: true, notifyDaemon: false });
615
+ agentHandle = registration.agent_handle;
615
616
  }
616
617
  } catch (err) {
617
618
  preRegistrationError = err;
@@ -629,6 +630,7 @@ async function spawnManagedHostAgent(
629
630
  };
630
631
  if (subscriberId) {
631
632
  env.UFOO_SUBSCRIBER_ID = subscriberId;
633
+ env.UFOO_AGENT_HANDLE = agentHandle;
632
634
  }
633
635
  if (nickname) {
634
636
  env.UFOO_NICKNAME = nickname;
@@ -718,6 +720,7 @@ async function spawnInternalAgent(
718
720
  const replaceAgentId = typeof options.replaceAgentId === "string" ? options.replaceAgentId.trim() : "";
719
721
  if (replaceAgentId && bus.busData.agents && bus.busData.agents[replaceAgentId]) {
720
722
  delete bus.busData.agents[replaceAgentId];
723
+ bus.saveBusData();
721
724
  }
722
725
 
723
726
  const requestedNickname = nickname
@@ -727,14 +730,14 @@ async function spawnInternalAgent(
727
730
  const launchMode = "internal";
728
731
 
729
732
  // 传递 launch_mode 和 parent PID 到 join
730
- const joinResult = await bus.subscriberManager.join(sessionId, agentType, requestedNickname, {
733
+ const joinResult = await require("./controlPlaneService").registerAgentFull(projectRoot, {
734
+ sessionId, agentType, nickname: requestedNickname,
731
735
  launchMode,
732
736
  parentPid: originalPid,
733
737
  providerSessionId,
734
738
  scopedNickname: String(extraEnv.UFOO_SCOPED_NICKNAME || "").trim(),
735
- });
739
+ }, { validateParentPid: true, notifyDaemon: false });
736
740
  const finalNickname = joinResult.nickname || requestedNickname || "";
737
- bus.saveBusData();
738
741
 
739
742
  const managedBootstrap = applyDefaultManagedBootstrap(projectRoot, normalizedAgent, extraArgs, extraEnv);
740
743
  const runnerCmd = "agent-runner";
@@ -748,6 +751,7 @@ async function spawnInternalAgent(
748
751
  ...(managedBootstrap.extraEnv && typeof managedBootstrap.extraEnv === "object" ? managedBootstrap.extraEnv : {}),
749
752
  UFOO_INTERNAL_AGENT: "1",
750
753
  UFOO_SUBSCRIBER_ID: subscriberId,
754
+ UFOO_AGENT_HANDLE: joinResult.agent_handle,
751
755
  UFOO_NICKNAME: finalNickname,
752
756
  UFOO_LAUNCH_MODE: "internal",
753
757
  UFOO_PARENT_PID: String(originalPid),
@@ -969,7 +973,7 @@ function spawnTmuxPane(
969
973
 
970
974
  async function launchAgent(projectRoot, agent, count = 1, nickname = "", processManager = null, options = {}) {
971
975
  const config = loadConfig(projectRoot);
972
- const mode = resolveConfiguredLaunchMode(config.launchMode, options);
976
+ const mode = options.internalOnly ? "internal" : resolveConfiguredLaunchMode(config.launchMode, options);
973
977
  const launchScope = normalizeLaunchScope(options.launchScope, "inplace");
974
978
  const terminalApp = normalizeTerminalAppPreference(options.terminalApp);
975
979
  const extraEnvObject = options.extraEnv && typeof options.extraEnv === "object" ? options.extraEnv : {};
@@ -1339,8 +1343,9 @@ async function closeAgent(projectRoot, agentId) {
1339
1343
  }
1340
1344
 
1341
1345
  if (canCloseWindow) {
1342
- // Non-blocking: don't hold close response on AppleScript window operations.
1343
- void closeTerminalWindowByTty(tty, terminalApp).catch(() => false);
1346
+ // Complete the bounded cleanup before returning; detached attempts can
1347
+ // outlive their project runtime and use stale terminal/agent metadata.
1348
+ await closeTerminalWindowByTty(tty, terminalApp).catch(() => false);
1344
1349
  }
1345
1350
 
1346
1351
  // Tmux pane cleanup: kill the pane after sending SIGTERM to the process.
@@ -121,6 +121,9 @@ async function handlePromptRequest(options = {}) {
121
121
  runPromptWithControllerLoop: injectedLoopRunner = runPromptWithControllerLoop,
122
122
  runUfooAgent,
123
123
  runUfooRouteAgent,
124
+ runMainAgent = null,
125
+ runCompatibility = null,
126
+ selectExecutionPath = null,
124
127
  dispatchMessages,
125
128
  handleOps,
126
129
  ackBus,
@@ -151,6 +154,10 @@ async function handlePromptRequest(options = {}) {
151
154
  if (controllerMode === CONTROLLER_MODES.LEGACY && resolvedLoopRuntime.enabled) {
152
155
  controllerMode = CONTROLLER_MODES.LOOP;
153
156
  }
157
+ if (selectExecutionPath) {
158
+ try { controllerMode = selectExecutionPath({ sessionId: req.session_id || requestMeta.session_id || "main-default", requestedMode: requestedControllerMode, mode: controllerMode }); }
159
+ catch (error) { socket.write(`${JSON.stringify({ type: IPC_RESPONSE_TYPES.ERROR, error: error.message, code: error.code })}\n`); return false; }
160
+ }
154
161
  const controllerObserver = createLoopObserver({
155
162
  projectRoot,
156
163
  enabled: true,
@@ -171,6 +178,7 @@ async function handlePromptRequest(options = {}) {
171
178
  enabled: controllerMode === CONTROLLER_MODES.LOOP,
172
179
  };
173
180
  const shadowEnabled = controllerMode === CONTROLLER_MODES.SHADOW;
181
+ const useNativeMain = controllerMode === CONTROLLER_MODES.MAIN && typeof runMainAgent === "function";
174
182
 
175
183
  if (isGlobalController && forcedProjectRoot) {
176
184
  try {
@@ -263,7 +271,7 @@ async function handlePromptRequest(options = {}) {
263
271
  })
264
272
  : null;
265
273
 
266
- if (!useGlobalProjectRouter && gateRouterEligibility.enabled && typeof runUfooRouteAgent === "function") {
274
+ if (!useNativeMain && !useGlobalProjectRouter && gateRouterEligibility.enabled && typeof runUfooRouteAgent === "function") {
267
275
  logGateRouterEvent("controller.gate_router_attempted", {
268
276
  flag: gateRouterEligibility.executionPath,
269
277
  intent_reason: gateRouterEligibility.intent.reason,
@@ -341,6 +349,10 @@ async function handlePromptRequest(options = {}) {
341
349
  );
342
350
  return true;
343
351
  } catch (err) {
352
+ if (err.code === "uncertain_effect") {
353
+ socket.write(`${JSON.stringify({ type: IPC_RESPONSE_TYPES.ERROR, error: err.message, code: err.code })}\n`);
354
+ return false;
355
+ }
344
356
  attachGateRouterMeta("dispatch_failed", {
345
357
  target: route.target,
346
358
  confidence: Number(route.confidence || 0),
@@ -360,14 +372,14 @@ async function handlePromptRequest(options = {}) {
360
372
  }
361
373
 
362
374
  const promptText = buildPromptWithPrivateReports(req.text || "", privateReports, nextRequestMeta);
363
- const promptRunner = loopRuntime.enabled
375
+ const promptRunner = useNativeMain ? runMainAgent : loopRuntime.enabled
364
376
  && !forceMainRouterFallback
365
377
  && typeof injectedLoopRunner === "function"
366
378
  ? injectedLoopRunner
367
379
  : runPromptWithAssistant;
368
380
 
369
381
  try {
370
- const handled = await promptRunner({
382
+ const runnerOptions = {
371
383
  projectRoot,
372
384
  prompt: promptText,
373
385
  provider,
@@ -385,7 +397,14 @@ async function handlePromptRequest(options = {}) {
385
397
  ufooAgentOptions,
386
398
  finalizeLocally: !useGlobalProjectRouter,
387
399
  loopRuntime,
388
- });
400
+ requestId: messageId || undefined,
401
+ sessionId: req.session_id || requestMeta.session_id || "main-default",
402
+ originalPrompt: req.text || "",
403
+ requestMeta,
404
+ };
405
+ const handled = !useNativeMain && runCompatibility
406
+ ? await runCompatibility(runnerOptions, () => promptRunner(runnerOptions))
407
+ : await promptRunner(runnerOptions);
389
408
 
390
409
  if (!handled.ok) {
391
410
  log(`agent-fail ${handled.error || "agent failed"}`);
@@ -1,20 +1,24 @@
1
1
  const fs = require("fs");
2
2
  const os = require("os");
3
3
  const path = require("path");
4
- const { loadAgentsData, saveAgentsData } = require("../../coordination/state/agentsStore");
4
+ const { loadAgentsData, updateAgentsData } = require("../../coordination/state/agentsStore");
5
5
  const { getUfooPaths } = require("../../coordination/state/paths");
6
6
 
7
7
  function persistProviderSession(projectRoot, subscriberId, payload) {
8
8
  const filePath = getUfooPaths(projectRoot).agentsFile;
9
- const data = loadAgentsData(filePath);
10
- const meta = data.agents[subscriberId] || {};
11
- data.agents[subscriberId] = {
12
- ...meta,
13
- provider_session_id: payload.sessionId || "",
14
- provider_session_source: payload.source || "",
15
- provider_session_updated_at: new Date().toISOString(),
16
- };
17
- saveAgentsData(filePath, data);
9
+ return updateAgentsData(filePath, (data) => {
10
+ const meta = data.agents[subscriberId] || {};
11
+ if (meta.status === "inactive") return false;
12
+ if (Object.entries(data.agents).some(([id, other]) => id !== subscriberId
13
+ && other.status === "active" && other.provider_session_id === payload.sessionId)) return false;
14
+ data.agents[subscriberId] = {
15
+ ...meta,
16
+ provider_session_id: payload.sessionId || "",
17
+ provider_session_source: payload.source || "",
18
+ provider_session_updated_at: new Date().toISOString(),
19
+ };
20
+ return true;
21
+ });
18
22
  }
19
23
 
20
24
  function loadProviderSessionCache(projectRoot) {
@@ -56,9 +60,46 @@ function resolveClaudeSessionFromFile(pid) {
56
60
  * Codex writes ~/.codex/sessions/YYYY/MM/DD/rollout-<ts>-<id>.jsonl
57
61
  * First line contains { type: "session_meta", payload: { id, cwd, ... } }
58
62
  */
59
- function resolveCodexSessionFromFile(cwd) {
63
+ function readFirstJsonLine(filePath) {
64
+ const fd = fs.openSync(filePath, "r");
65
+ const chunks = [];
66
+ let total = 0;
67
+ try {
68
+ // Modern session_meta includes base instructions and can exceed 4 KB.
69
+ // Bound memory while reading the complete first JSON record.
70
+ while (total < 2 * 1024 * 1024) {
71
+ const buffer = Buffer.alloc(64 * 1024);
72
+ const size = fs.readSync(fd, buffer, 0, buffer.length, null);
73
+ if (!size) return JSON.parse(Buffer.concat(chunks).toString("utf8"));
74
+ const newline = buffer.subarray(0, size).indexOf(10);
75
+ chunks.push(buffer.subarray(0, newline === -1 ? size : newline));
76
+ total += size;
77
+ if (newline !== -1) return JSON.parse(Buffer.concat(chunks).toString("utf8"));
78
+ }
79
+ return null;
80
+ } finally { fs.closeSync(fd); }
81
+ }
82
+
83
+ function resolveCodexSessionFromFile(cwd, options = {}) {
60
84
  if (!cwd) return null;
61
85
  try {
86
+ let expectedSession = String(options.sessionId || "");
87
+ let startedAt = options.startedAt || "";
88
+ let claimedSessions = new Set();
89
+ if (options.projectRoot && options.subscriberId) {
90
+ const data = loadAgentsData(getUfooPaths(options.projectRoot).agentsFile);
91
+ const own = data.agents[options.subscriberId];
92
+ if (!own || own.status !== "active") return null;
93
+ expectedSession = expectedSession || own.provider_session_id || "";
94
+ startedAt = startedAt || own.joined_at || "";
95
+ const peers = Object.entries(data.agents).filter(([id, meta]) => id !== options.subscriberId
96
+ && meta.status === "active" && meta.agent_type === "codex");
97
+ // Cwd is not a process identity. Parallel launches must bind through an
98
+ // exact provider session id instead of racing for the newest rollout.
99
+ if (!expectedSession && peers.length) return null;
100
+ claimedSessions = new Set(peers.map(([, meta]) => meta.provider_session_id).filter(Boolean));
101
+ }
102
+ const startedAtMs = Date.parse(startedAt);
62
103
  const now = new Date();
63
104
  // Check today and yesterday (session may have started before midnight)
64
105
  const dates = [now];
@@ -66,14 +107,14 @@ function resolveCodexSessionFromFile(cwd) {
66
107
  yesterday.setDate(yesterday.getDate() - 1);
67
108
  dates.push(yesterday);
68
109
 
69
- let bestMatch = null;
70
- let bestMtime = 0;
110
+ const matches = new Map();
71
111
 
72
112
  for (const d of dates) {
73
113
  const yyyy = String(d.getFullYear());
74
114
  const mm = String(d.getMonth() + 1).padStart(2, "0");
75
115
  const dd = String(d.getDate()).padStart(2, "0");
76
- const dir = path.join(os.homedir(), ".codex", "sessions", yyyy, mm, dd);
116
+ const codexHome = options.codexHome || process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
117
+ const dir = path.join(codexHome, "sessions", yyyy, mm, dd);
77
118
  if (!fs.existsSync(dir)) continue;
78
119
 
79
120
  const files = fs.readdirSync(dir)
@@ -83,31 +124,24 @@ function resolveCodexSessionFromFile(cwd) {
83
124
  const filePath = path.join(dir, file);
84
125
  try {
85
126
  const stat = fs.statSync(filePath);
86
- if (stat.mtimeMs <= bestMtime) continue;
87
-
88
- // Read first line for session_meta
89
- const fd = fs.openSync(filePath, "r");
90
- const buf = Buffer.alloc(4096);
91
- const bytesRead = fs.readSync(fd, buf, 0, 4096, 0);
92
- fs.closeSync(fd);
93
- const firstLine = buf.toString("utf8", 0, bytesRead).split("\n")[0];
94
- if (!firstLine) continue;
95
-
96
- const record = JSON.parse(firstLine);
127
+ const record = readFirstJsonLine(filePath);
128
+ if (!record) continue;
97
129
  const payload = record.payload || record;
98
130
  const sessionCwd = payload.cwd || "";
99
131
  const sessionId = payload.id || "";
100
132
 
101
- if (sessionId && sessionCwd === cwd && stat.mtimeMs > bestMtime) {
102
- bestMatch = { sessionId, source: filePath };
103
- bestMtime = stat.mtimeMs;
104
- }
133
+ if (!sessionId || sessionCwd !== cwd || claimedSessions.has(sessionId)) continue;
134
+ if (expectedSession && sessionId !== expectedSession) continue;
135
+ const createdAt = Date.parse(payload.timestamp || record.timestamp || "");
136
+ if (!expectedSession && Number.isFinite(startedAtMs)
137
+ && (Number.isFinite(createdAt) ? createdAt : stat.birthtimeMs) < startedAtMs) continue;
138
+ matches.set(sessionId, { sessionId, source: filePath });
105
139
  } catch {
106
140
  continue;
107
141
  }
108
142
  }
109
143
  }
110
- return bestMatch;
144
+ return matches.size === 1 ? matches.values().next().value : null;
111
145
  } catch {
112
146
  return null;
113
147
  }
@@ -158,7 +192,7 @@ function resolveSessionFromFile(agentType, opts = {}) {
158
192
  return resolveClaudeSessionFromFile(opts.pid);
159
193
  }
160
194
  if (agentType === "codex") {
161
- return resolveCodexSessionFromFile(opts.cwd);
195
+ return resolveCodexSessionFromFile(opts.cwd, opts);
162
196
  }
163
197
  if (agentType === "kimi") {
164
198
  return resolveKimiSessionFromIndex(opts.cwd);
@@ -222,13 +256,13 @@ function scheduleProviderSessionResolve({
222
256
  }
223
257
 
224
258
  // 1. Try direct file read (fast, non-invasive)
225
- const fileOpts = { pid: agentPid, cwd: agentCwd || projectRoot };
259
+ const fileOpts = { pid: agentPid, cwd: agentCwd || projectRoot, projectRoot, subscriberId };
226
260
  const fileResolved = await resolveSessionFromFileWithRetries(
227
261
  agentType, fileOpts, fileAttempts, fileIntervalMs,
228
262
  );
229
263
  if (cancelled) return;
230
264
  if (fileResolved && fileResolved.sessionId) {
231
- persistProviderSession(projectRoot, subscriberId, fileResolved);
265
+ if (!persistProviderSession(projectRoot, subscriberId, fileResolved)) return;
232
266
  if (typeof onResolved === "function") {
233
267
  onResolved(subscriberId, fileResolved);
234
268
  }
@@ -15,6 +15,9 @@ const {
15
15
  const REPORT_CONTROL_TARGET = "ufoo-agent";
16
16
  const REPORT_CONTROL_EVENT = "agent_report";
17
17
  const REPORT_CONTROL_TYPE = "control/report";
18
+ const { withFileLock } = require("../../coordination/state/fileLock");
19
+ const { normalizeReportInput, normalizePhase, loadReportState } = require("../../coordination/report/store");
20
+ const draining = new Set();
18
21
 
19
22
  function getReportControlQueueDir(projectRoot) {
20
23
  const paths = getUfooPaths(projectRoot);
@@ -60,35 +63,66 @@ function buildReportControlEvent(report = {}, options = {}) {
60
63
 
61
64
  async function enqueueAgentReport(projectRoot, report, options = {}) {
62
65
  ensureReportControlQueue(projectRoot);
66
+ return withFileLock(getReportControlQueueFile(projectRoot), () => {
67
+ const queue = new DeliveryQueue(getReportControlQueueFile(projectRoot));
68
+ const publisher = options.publisher || resolveReportPublisher(report);
69
+ const pending = { ...(loadReportState(projectRoot).agents[publisher]?.pending || {}) };
70
+ const controls = [...queue.processingFiles().flatMap((file) => {
71
+ return require("../../coordination/bus/utils").readJSONL(file);
72
+ }), ...queue.readPendingRaw()];
73
+ for (const control of controls) {
74
+ const entry = control.data?.report;
75
+ if (!entry || entry.agent_id !== publisher) continue;
76
+ if (["start", "progress"].includes(entry.phase)) pending[entry.task_id] = entry;
77
+ else delete pending[entry.task_id];
78
+ }
79
+ let taskId = String(report.task_id || report.taskId || report.task || "").trim();
80
+ if (!taskId && normalizePhase(report.phase) !== "start") {
81
+ const tasks = Object.keys(pending);
82
+ if (tasks.length > 1) throw new Error("Multiple active tasks; specify --task / task_id for this report");
83
+ taskId = tasks[0];
84
+ }
85
+ const entry = normalizeReportInput({ ...report, agent_id: publisher, task_id: taskId });
86
+ const event = normalizeQueueEnvelope(buildReportControlEvent(entry, options), {
87
+ queueType: QUEUE_TYPES.REPORT,
88
+ delivery: { mode: "daemon_consume", gate: "none", max_inflight: 1 },
89
+ ack: { policy: "on_consume" },
90
+ });
91
+ queue.append(event);
63
92
 
64
- const event = normalizeQueueEnvelope(buildReportControlEvent(report, options), {
65
- queueType: QUEUE_TYPES.REPORT,
66
- delivery: { mode: "daemon_consume", gate: "none", max_inflight: 1 },
67
- ack: { policy: "on_consume" },
93
+ return {
94
+ queued: true,
95
+ request_id: event.data.request_id,
96
+ target: REPORT_CONTROL_TARGET,
97
+ targets: [REPORT_CONTROL_TARGET],
98
+ report: entry,
99
+ };
68
100
  });
69
- new DeliveryQueue(getReportControlQueueFile(projectRoot)).append(event);
70
-
71
- return {
72
- queued: true,
73
- request_id: event.data.request_id,
74
- target: REPORT_CONTROL_TARGET,
75
- targets: [REPORT_CONTROL_TARGET],
76
- report,
77
- };
78
101
  }
79
102
 
80
- function takeReportControlEvents(projectRoot) {
103
+ async function drainReportControlEvents(projectRoot, handle) {
81
104
  const queueFile = getReportControlQueueFile(projectRoot);
105
+ if (draining.has(queueFile)) return 0;
106
+ draining.add(queueFile);
82
107
  const queue = new DeliveryQueue(queueFile);
83
- const events = [];
84
- queue.recover();
85
- while (true) {
86
- const claim = queue.claimNext();
87
- if (!claim) break;
88
- events.push(claim.event);
89
- queue.completeClaim(claim);
90
- }
91
- return events;
108
+ let consumed = 0;
109
+ try {
110
+ while (true) {
111
+ const claim = withFileLock(queueFile, () => {
112
+ queue.recover();
113
+ if (queue.processingFiles().length) return null;
114
+ return queue.claimNext();
115
+ });
116
+ if (!claim) break;
117
+ try {
118
+ const handled = await handle(claim.event);
119
+ if (handled === false) { queue.restoreClaim(claim); break; }
120
+ queue.completeClaim(claim);
121
+ consumed += 1;
122
+ } catch (error) { queue.restoreClaim(claim); throw error; }
123
+ }
124
+ return consumed;
125
+ } finally { draining.delete(queueFile); }
92
126
  }
93
127
 
94
128
  function isAgentReportControlEvent(evt) {
@@ -104,7 +138,7 @@ function extractAgentReportControl(evt) {
104
138
  if (!isAgentReportControlEvent(evt)) return null;
105
139
  const data = evt.data && typeof evt.data === "object" ? evt.data : {};
106
140
  return {
107
- report: data.report,
141
+ report: normalizeReportInput(data.report, { entry_id: data.request_id, ts: data.report.ts || data.queued_at || evt.timestamp || evt.ts }),
108
142
  request_id: data.request_id || "",
109
143
  queued_at: data.queued_at || evt.timestamp || evt.ts || "",
110
144
  };
@@ -121,7 +155,7 @@ module.exports = {
121
155
  buildReportControlData,
122
156
  buildReportControlEvent,
123
157
  enqueueAgentReport,
124
- takeReportControlEvents,
158
+ drainReportControlEvents,
125
159
  isAgentReportControlEvent,
126
160
  extractAgentReportControl,
127
161
  };
@@ -168,6 +168,10 @@ function buildStatus(projectRoot, options = {}) {
168
168
  activity_state,
169
169
  activity_since,
170
170
  activity_detail,
171
+ native_delivery: meta?.native_delivery || "",
172
+ native_delivery_ready: meta?.native_delivery_ready === true,
173
+ native_delivery_version: meta?.native_delivery_version || "",
174
+ native_delivery_diagnostic: meta?.native_delivery_diagnostic || "",
171
175
  host_inject_sock: meta?.host_inject_sock || "",
172
176
  host_daemon_sock: meta?.host_daemon_sock || "",
173
177
  host_name: meta?.host_name || "",
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
 
3
3
  const REDACTED = "[REDACTED]";
4
- const SENSITIVE_KEY_PATTERN = /(^|_|-)(authorization|accesstoken|access_token|refreshtoken|refresh_token|apikey|api_key|tokenhash|token_hash)$/i;
4
+ const SENSITIVE_KEY_PATTERN = /(^|_|-)(authorization|accesstoken|access_token|refreshtoken|refresh_token|apikey|api_key|tokenhash|token_hash|agenthandle|agent_handle)$/i;
5
5
  const BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]+\b/gi;
6
- const INLINE_SECRET_ASSIGNMENT_PATTERN = /\b(api[_-]?key|access[_-]?token|refresh[_-]?token|token)\s*[:=]\s*["']?([A-Za-z0-9._~+/=-]{8,})["']?/gi;
6
+ const INLINE_SECRET_ASSIGNMENT_PATTERN = /\b(api[_-]?key|access[_-]?token|refresh[_-]?token|(?:UFOO_)?agent[_-]?handle|token)\s*[:=]\s*["']?([A-Za-z0-9._~+/=-]{8,})["']?/gi;
7
7
 
8
8
  function isPlainObject(value) {
9
9
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -13,7 +13,8 @@ function normalizeProjectRoot(projectRoot) {
13
13
  }
14
14
 
15
15
  function resolveGlobalControllerProjectRoot() {
16
- return trimTrailingSlashes(path.resolve(os.homedir()));
16
+ const root = trimTrailingSlashes(path.resolve(os.homedir()));
17
+ try { return canonicalProjectRoot(root); } catch { return root; }
17
18
  }
18
19
 
19
20
  function resolveGlobalControllerUfooDir() {