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
@@ -8,11 +8,12 @@ const { buildStatus } = require("./status");
8
8
  const EventBus = require("../../coordination/bus");
9
9
  const { AgentProcessManager } = require("./agentProcessManager");
10
10
  const NicknameManager = require("../../coordination/bus/nickname");
11
- const { DeliveryQueue } = require("../../coordination/bus/deliveryQueue");
12
- const { generateInstanceId, subscriberToSafeName } = require("../../coordination/bus/utils");
11
+ const { generateInstanceId } = require("../../coordination/bus/utils");
13
12
  const { createDaemonIpcServer } = require("./ipcServer");
14
13
  const { IPC_REQUEST_TYPES, IPC_RESPONSE_TYPES, BUS_STATUS_PHASES } = require("../contracts/eventContract");
15
14
  const { getUfooPaths } = require("../../coordination/state/paths");
15
+ const { loadAgentsData } = require("../../coordination/state/agentsStore");
16
+ const { isInternalAgentMeta } = require("../contracts/agentMode");
16
17
  const {
17
18
  upsertProjectRuntime,
18
19
  markProjectDormant,
@@ -27,11 +28,8 @@ const { normalizeFormat, renderGroupDiagramFromTemplate, renderGroupDiagramFromR
27
28
  const { runPromptWithAssistant } = require("./promptLoop");
28
29
  const { handlePromptRequest } = require("./promptRequest");
29
30
  const { recordAgentReport } = require("./reporting");
30
- const {
31
- isAgentReportControlEvent,
32
- extractAgentReportControl,
33
- takeReportControlEvents,
34
- } = require("./reportControlBus");
31
+ const { startBusBridge } = require("./busBridge");
32
+ const { createAgentHost } = require("./agentHost");
35
33
  const { isGlobalControllerProjectRoot } = require("../projects");
36
34
  const {
37
35
  assignSoloRoleToExistingAgent,
@@ -572,6 +570,13 @@ async function handleOps(projectRoot, ops = [], processManager = null, runtimeSe
572
570
  // Check for existing agent with same nickname
573
571
  const { existing, cleaned } = checkAndCleanupNickname(projectRoot, nickname, { scopedNickname, agentType: agent });
574
572
  if (existing) {
573
+ if (op.internal_only || runtimeServices.internalOnly) {
574
+ const meta = loadAgentsData(getUfooPaths(projectRoot).agentsFile).agents[existing];
575
+ if (!isInternalAgentMeta(meta)) {
576
+ results.push({ action: "launch", ok: false, agent, error: "nickname belongs to a non-internal agent; choose another nickname" });
577
+ continue;
578
+ }
579
+ }
575
580
  // Agent with this nickname already exists and is active
576
581
  results.push({
577
582
  action: "launch",
@@ -588,6 +593,7 @@ async function handleOps(projectRoot, ops = [], processManager = null, runtimeSe
588
593
  }
589
594
  // eslint-disable-next-line no-await-in-loop
590
595
  const launchResult = await launchAgent(projectRoot, agent, count, nickname, processManager, {
596
+ internalOnly: op.internal_only === true || runtimeServices.internalOnly === true,
591
597
  scopedNickname,
592
598
  launchScope: op.launch_scope || "",
593
599
  terminalApp: op.terminal_app || "",
@@ -802,8 +808,9 @@ async function handleOps(projectRoot, ops = [], processManager = null, runtimeSe
802
808
  return results;
803
809
  }
804
810
 
805
- async function dispatchMessages(projectRoot, dispatch = []) {
811
+ async function dispatchMessages(projectRoot, dispatch = [], { strict = false } = {}) {
806
812
  const eventBus = new EventBus(projectRoot);
813
+ const receipts = [];
807
814
  // Always use "ufoo-agent" as the publisher for daemon messages
808
815
  const defaultPublisher = "ufoo-agent";
809
816
  const resolveDispatchTarget = (target) => {
@@ -852,342 +859,19 @@ async function dispatchMessages(projectRoot, dispatch = []) {
852
859
  };
853
860
  try {
854
861
  if (target === "broadcast") {
855
- await eventBus.broadcast(item.message, pub, sendOptions);
862
+ receipts.push({ ok: true, ...await eventBus.broadcast(item.message, pub, sendOptions) });
856
863
  } else {
857
- await eventBus.send(target, item.message, pub, sendOptions);
864
+ receipts.push({ ok: true, ...await eventBus.send(target, item.message, pub, sendOptions) });
858
865
  }
859
866
  } catch (err) {
860
867
  appendControlLog(
861
868
  projectRoot,
862
869
  `dispatch failed target=${JSON.stringify(item.target)} resolved=${JSON.stringify(target)} error=${err && err.message ? err.message : String(err)}`
863
870
  );
871
+ if (strict) { err.receipts = receipts; throw err; }
864
872
  }
865
873
  }
866
- }
867
-
868
- function startBusBridge(
869
- projectRoot,
870
- provider,
871
- onEvent,
872
- onStatus,
873
- shouldDrain,
874
- onReport,
875
- options = {}
876
- ) {
877
- const state = {
878
- subscriber: null,
879
- queueFile: null,
880
- pending: new Set(),
881
- watchedAgents: new Set(),
882
- lastEventSeq: 0,
883
- emittedEventKeys: [],
884
- emittedEventKeySet: new Set(),
885
- };
886
- const eventBus = options.eventBus || new EventBus(projectRoot);
887
- const reportJoinError = typeof options.onJoinError === "function"
888
- ? options.onJoinError
889
- : () => {};
890
- let joinInProgress = null;
891
- let lastJoinError = "";
892
- let stopped = false;
893
- let polling = false;
894
-
895
- function getAgentNickname(agentId) {
896
- if (!agentId) return agentId;
897
- try {
898
- const busPath = getUfooPaths(projectRoot).agentsFile;
899
- const bus = JSON.parse(fs.readFileSync(busPath, "utf8"));
900
- const meta = bus.agents && bus.agents[agentId];
901
- if (meta && meta.nickname) {
902
- return meta.nickname;
903
- }
904
- } catch {
905
- // Ignore errors, return original ID
906
- }
907
- return agentId;
908
- }
909
-
910
- function getEventDedupeKey(evt) {
911
- if (!evt || typeof evt !== "object") return "";
912
- const seq = Number(evt.seq);
913
- if (Number.isFinite(seq) && seq > 0) return `seq:${seq}`;
914
- return [
915
- "event",
916
- evt.timestamp || evt.ts || "",
917
- evt.event || "",
918
- evt.publisher || "",
919
- evt.target || "",
920
- JSON.stringify(evt.data || {}),
921
- ].join(":");
922
- }
923
-
924
- function rememberEmittedEvent(evt) {
925
- const key = getEventDedupeKey(evt);
926
- if (!key) return false;
927
- if (state.emittedEventKeySet.has(key)) return true;
928
- state.emittedEventKeySet.add(key);
929
- state.emittedEventKeys.push(key);
930
- if (state.emittedEventKeys.length > 500) {
931
- const removed = state.emittedEventKeys.splice(0, state.emittedEventKeys.length - 500);
932
- for (const item of removed) state.emittedEventKeySet.delete(item);
933
- }
934
- return false;
935
- }
936
-
937
- function hasPositiveSeq(seq) {
938
- const value = Number(seq);
939
- return Number.isFinite(value) && value > 0;
940
- }
941
-
942
- function toBridgeEvent(evt) {
943
- const data = evt.data && typeof evt.data === "object" ? evt.data : {};
944
- return {
945
- seq: evt.seq,
946
- event: evt.event,
947
- publisher: evt.publisher,
948
- target: evt.target,
949
- data,
950
- message: data.message || "",
951
- state: data.state || "",
952
- previous: data.previous || "",
953
- subscriber: data.subscriber || "",
954
- source: data.source || "",
955
- injection_mode: data.injection_mode || "",
956
- ts: evt.timestamp || evt.ts,
957
- };
958
- }
959
-
960
- function emitBusEvent(evt) {
961
- if (!evt || !onEvent) return;
962
- if (rememberEmittedEvent(evt)) return;
963
- onEvent(toBridgeEvent(evt));
964
- }
965
-
966
- function readAgentsData() {
967
- try {
968
- const busPath = getUfooPaths(projectRoot).agentsFile;
969
- return JSON.parse(fs.readFileSync(busPath, "utf8"));
970
- } catch {
971
- return {};
972
- }
973
- }
974
-
975
- function buildWatchedAliases() {
976
- const aliases = new Set();
977
- const bus = readAgentsData();
978
- for (const agentId of state.watchedAgents) {
979
- aliases.add(agentId);
980
- const meta = bus.agents && bus.agents[agentId];
981
- if (!meta) continue;
982
- if (meta.nickname) aliases.add(meta.nickname);
983
- if (meta.scoped_nickname) aliases.add(meta.scoped_nickname);
984
- if (meta.display_nickname) aliases.add(meta.display_nickname);
985
- }
986
- return aliases;
987
- }
988
-
989
- function isWatchedEvent(evt, aliases = buildWatchedAliases()) {
990
- if (!evt || (evt.event !== "message" && evt.event !== "activity_state_changed")) return false;
991
- const publisher = String(evt.publisher || "");
992
- const target = String(evt.target || "");
993
- const subscriber = evt.data && evt.data.subscriber ? String(evt.data.subscriber) : "";
994
- return aliases.has(publisher) || aliases.has(target) || aliases.has(subscriber);
995
- }
996
-
997
- function getEventFiles() {
998
- try {
999
- const dir = getUfooPaths(projectRoot).busEventsDir;
1000
- return fs.readdirSync(dir)
1001
- .filter((name) => name.endsWith(".jsonl"))
1002
- .sort()
1003
- .map((name) => path.join(dir, name));
1004
- } catch {
1005
- return [];
1006
- }
1007
- }
1008
-
1009
- function readCurrentSeq() {
1010
- try {
1011
- const raw = fs.readFileSync(path.join(getUfooPaths(projectRoot).busDir, "seq.counter"), "utf8").trim();
1012
- const seq = Number(raw);
1013
- return Number.isFinite(seq) ? seq : 0;
1014
- } catch {
1015
- return 0;
1016
- }
1017
- }
1018
-
1019
- function readEventFile(file) {
1020
- try {
1021
- return fs.readFileSync(file, "utf8")
1022
- .split(/\r?\n/)
1023
- .filter(Boolean)
1024
- .map((line) => {
1025
- try {
1026
- return JSON.parse(line);
1027
- } catch {
1028
- return null;
1029
- }
1030
- })
1031
- .filter(Boolean);
1032
- } catch {
1033
- return [];
1034
- }
1035
- }
1036
-
1037
- function pollWatchedEvents() {
1038
- if (state.watchedAgents.size === 0) {
1039
- state.lastEventSeq = readCurrentSeq();
1040
- return;
1041
- }
1042
- const aliases = buildWatchedAliases();
1043
- let maxSeq = state.lastEventSeq;
1044
- for (const file of getEventFiles().slice(-2)) {
1045
- for (const evt of readEventFile(file)) {
1046
- const seq = Number(evt.seq);
1047
- if (hasPositiveSeq(seq)) {
1048
- if (seq <= state.lastEventSeq) continue;
1049
- if (seq > maxSeq) maxSeq = seq;
1050
- }
1051
- if (isWatchedEvent(evt, aliases)) emitBusEvent(evt);
1052
- }
1053
- }
1054
- state.lastEventSeq = Math.max(state.lastEventSeq, maxSeq);
1055
- }
1056
-
1057
- async function ensureSubscriber() {
1058
- if (stopped || state.subscriber) return state.subscriber;
1059
- if (joinInProgress) return joinInProgress;
1060
- joinInProgress = (async () => {
1061
- try {
1062
- // Determine agent type based on provider configuration
1063
- const agentType = provider === "codex-cli" ? "codex" : (provider === "ucode" ? "ufoo-code" : "claude-code");
1064
- // Use fixed ID "ufoo-agent" for daemon's bus identity with explicit nickname
1065
- const sub = await eventBus.join("ufoo-agent", agentType, "ufoo-agent");
1066
- if (!sub || stopped) return null;
1067
- state.subscriber = sub;
1068
- const safe = subscriberToSafeName(sub);
1069
- state.queueFile = path.join(getUfooPaths(projectRoot).busQueuesDir, safe, "pending.jsonl");
1070
- lastJoinError = "";
1071
- return sub;
1072
- } catch (err) {
1073
- const detail = err && err.message ? err.message : String(err || "unknown join error");
1074
- if (detail !== lastJoinError) {
1075
- lastJoinError = detail;
1076
- try {
1077
- reportJoinError(err);
1078
- } catch {
1079
- // Diagnostics must never turn a recoverable join failure into an
1080
- // unhandled rejection in the process-wide global daemon.
1081
- }
1082
- }
1083
- return null;
1084
- } finally {
1085
- joinInProgress = null;
1086
- }
1087
- })();
1088
- return joinInProgress;
1089
- }
1090
-
1091
- async function handleReportControlEvent(evt) {
1092
- if (!isAgentReportControlEvent(evt)) return false;
1093
- if (typeof onReport !== "function") return false;
1094
- const control = extractAgentReportControl(evt);
1095
- if (!control) return false;
1096
- await onReport(control.report, {
1097
- event: evt,
1098
- requestId: control.request_id,
1099
- queuedAt: control.queued_at,
1100
- });
1101
- return true;
1102
- }
1103
-
1104
- async function pollReportControlQueue() {
1105
- const events = takeReportControlEvents(projectRoot);
1106
- if (!events.length) return;
1107
- for (const evt of events) {
1108
- if (await handleReportControlEvent(evt)) continue;
1109
- }
1110
- }
1111
-
1112
- function pollQueue() {
1113
- if (!state.queueFile) return;
1114
- const queue = new DeliveryQueue(state.queueFile);
1115
- queue.recover();
1116
- while (true) {
1117
- const claim = queue.claimNext();
1118
- if (!claim) break;
1119
- const evt = claim.event;
1120
- if (!evt) {
1121
- queue.completeClaim(claim);
1122
- continue;
1123
- }
1124
- try {
1125
- emitBusEvent(evt);
1126
- queue.completeClaim(claim);
1127
- } catch {
1128
- queue.restoreClaim(claim);
1129
- continue;
1130
- }
1131
- if (evt.publisher && state.pending.has(evt.publisher)) {
1132
- state.pending.delete(evt.publisher);
1133
- if (onStatus) {
1134
- const displayName = getAgentNickname(evt.publisher);
1135
- onStatus({ phase: BUS_STATUS_PHASES.DONE, text: `${displayName} done`, key: evt.publisher });
1136
- }
1137
- }
1138
- }
1139
- }
1140
-
1141
- async function poll() {
1142
- if (polling) return;
1143
- polling = true;
1144
- try {
1145
- await ensureSubscriber();
1146
- await pollReportControlQueue();
1147
- if (typeof shouldDrain === "function" && !shouldDrain()) return;
1148
- pollQueue();
1149
- pollWatchedEvents();
1150
- } finally {
1151
- polling = false;
1152
- }
1153
- }
1154
-
1155
- const interval = setInterval(() => {
1156
- poll().catch(() => {});
1157
- }, 1000);
1158
- return {
1159
- markPending(target) {
1160
- if (!target) return;
1161
- state.pending.add(target);
1162
- if (onStatus) {
1163
- const displayName = getAgentNickname(target);
1164
- onStatus({ phase: BUS_STATUS_PHASES.START, text: `${displayName} processing`, key: target });
1165
- }
1166
- },
1167
- getSubscriber() {
1168
- void ensureSubscriber();
1169
- return state.subscriber;
1170
- },
1171
- refresh() {
1172
- return poll();
1173
- },
1174
- watchAgent(agentId, enabled = true) {
1175
- if (!agentId) return;
1176
- if (enabled) {
1177
- state.watchedAgents.add(agentId);
1178
- state.lastEventSeq = Math.max(state.lastEventSeq, readCurrentSeq());
1179
- } else {
1180
- state.watchedAgents.delete(agentId);
1181
- if (state.watchedAgents.size === 0) {
1182
- state.lastEventSeq = readCurrentSeq();
1183
- }
1184
- }
1185
- },
1186
- stop() {
1187
- stopped = true;
1188
- clearInterval(interval);
1189
- },
1190
- };
874
+ return receipts;
1191
875
  }
1192
876
 
1193
877
  function startDaemon({
@@ -1341,12 +1025,23 @@ function startDaemon({
1341
1025
  cronController: null,
1342
1026
  groupOrchestrator: null,
1343
1027
  };
1344
- const handleRuntimeOps = (root, ops, manager = processManager) =>
1345
- handleOps(root, ops, manager, runtimeServices);
1028
+ const handleRuntimeOps = async (root, ops, manager = processManager, leaseContext = {}) => {
1029
+ if (!ops.some((op) => op.action === "launch") || !runtimeServices.workspaceAccess) return handleOps(root, ops, manager, runtimeServices);
1030
+ const result = await runtimeServices.workspaceAccess.leases.run({ key: fs.realpathSync(root), ownerId: leaseContext.leaseOwnerId || `ops-${require("crypto").randomUUID()}` },
1031
+ () => handleOps(root, ops, manager, runtimeServices));
1032
+ if (result?.code === "workspace_busy") throw Object.assign(new Error("workspace writer is active; inspect or cancel its task before launching workers"), { code: "workspace_busy" });
1033
+ return result;
1034
+ };
1346
1035
  const daemonCronController = projectRuntime.own("cronController", createDaemonCronController({
1347
1036
  projectRoot,
1348
- dispatch: async ({ taskId, target, message }) => {
1349
- await dispatchMessages(projectRoot, [{ target, message }]);
1037
+ dispatch: async ({ taskId, occurrenceId, target, message }) => {
1038
+ if (target === "ufoo-agent") {
1039
+ mainAgentHost.submit({ requestId: `cron-${require("crypto").createHash("sha256").update(occurrenceId).digest("hex").slice(0, 32)}`,
1040
+ text: message, requestMeta: { source: "cron", scheduleId: taskId, occurrenceId } }, "main-schedules");
1041
+ return;
1042
+ }
1043
+ await mainAgentHost.management.commands.execute({ commandId: `cron-${require("crypto").createHash("sha256").update(`${occurrenceId}:${target}`).digest("hex").slice(0, 32)}`,
1044
+ kind: "cron-delivery", args: { taskId, target, message } }, () => dispatchMessages(projectRoot, [{ target, message }], { strict: true }));
1350
1045
  log(`cron:${taskId} -> ${target}`);
1351
1046
  },
1352
1047
  log,
@@ -1364,6 +1059,7 @@ function startDaemon({
1364
1059
  cronTasks: daemonCronController ? daemonCronController.listTasks() : [],
1365
1060
  }),
1366
1061
  runtime: projectRuntime.status(),
1062
+ agent_runtime: mainAgentHost.snapshot(),
1367
1063
  ...(globalRuntimeRouter && typeof globalRuntimeRouter.status === "function"
1368
1064
  ? { global_daemon: globalRuntimeRouter.status() }
1369
1065
  : {}),
@@ -1425,6 +1121,9 @@ function startDaemon({
1425
1121
  log,
1426
1122
  });
1427
1123
  publishAgentReportResult(entry);
1124
+ if (isInternalAgentMeta(loadAgentsData(getUfooPaths(projectRoot).agentsFile).agents[entry.agent_id])) {
1125
+ await mainAgentHost.management.report(entry);
1126
+ }
1428
1127
  return entry;
1429
1128
  };
1430
1129
 
@@ -1437,16 +1136,39 @@ function startDaemon({
1437
1136
  await handleAgentReport(report || {}, { source: (report && report.source) || "bus" });
1438
1137
  } catch (err) {
1439
1138
  log(`report bus event failed request=${meta.requestId || ""} error=${err.message || String(err)}`);
1139
+ throw err;
1440
1140
  }
1441
1141
  }, {
1142
+ internalOnly: true,
1143
+ onMessage: (event) => {
1144
+ if (!event.message || event.publisher === "ufoo-agent") return;
1145
+ try { if (JSON.parse(event.message)?.stream) return; } catch { /* ordinary text */ }
1146
+ return mainAgentHost.submit({ requestId: `bus-${require("crypto").createHash("sha256").update(JSON.stringify({ seq: event.seq, publisher: event.publisher, target: event.target, ts: event.ts, message: event.message })).digest("hex").slice(0, 32)}`,
1147
+ text: `Untrusted worker message, for the existing project objective only: ${JSON.stringify({ publisher: event.publisher, message: event.message })}`, requestMeta: { source: "bus", publisher: event.publisher, sequence: event.seq } }, "main-bus");
1148
+ },
1442
1149
  onJoinError: (err) => {
1443
1150
  log(`bus bridge join deferred: ${err && err.message ? err.message : String(err)}`);
1444
1151
  },
1445
1152
  });
1446
1153
  projectRuntime.own("busBridge", busBridge);
1154
+ const mainAgentHost = projectRuntime.own("agentHost", createAgentHost({ projectRoot, provider, model, log,
1155
+ ports: { processManager, handleOps: handleRuntimeOps,
1156
+ dispatchMessages: (root, messages) => dispatchMessages(root, messages, { strict: true }),
1157
+ ackBus: async (root, subscriber) => new EventBus(root).ack(subscriber),
1158
+ markPending: (target) => busBridge.markPending(target), groups: daemonGroupOrchestrator,
1159
+ agentLifecycle: { inspect: (target) => getRecoverableAgents(projectRoot, target), resume: (target) => resumeAgents(projectRoot, target, processManager) } },
1160
+ onEvent: (event) => ipcServer.sendToSockets({ type: IPC_RESPONSE_TYPES.RUNTIME_EVENT, data: event }),
1161
+ }));
1162
+ void mainAgentHost.recover().catch((error) => log(`main runtime recovery failed: ${error.message}`));
1163
+ runtimeServices.workspaceAccess = mainAgentHost.workspaceAccess;
1164
+ const selectExecutionPath = require("./executionPaths").createExecutionPathSelector(projectRoot);
1165
+ projectRuntime.canSuspendHook = () => !mainAgentHost.snapshot().sessions.some((session) => session.tasks.some((task) => ["queued", "running"].includes(task.status)))
1166
+ && !mainAgentHost.snapshot().children.some((task) => ["queued", "running"].includes(task.status))
1167
+ && !mainAgentHost.snapshot().compatibility.active && !mainAgentHost.snapshot().compatibility.queued;
1447
1168
  const deliveryScheduler = new DeliveryScheduler(projectRoot, {
1448
1169
  log,
1449
- emitDelivery: async ({ subscriber, status, error } = {}) => {
1170
+ emitDelivery: async ({ subscriber, event, status, error, errorCode } = {}) => {
1171
+ mainAgentHost.management.delivery({ subscriber, event, status, errorCode });
1450
1172
  if (status === "error") {
1451
1173
  log(`delivery failed subscriber=${subscriber || "unknown"} error=${error || "unknown"}`);
1452
1174
  }
@@ -1524,7 +1246,33 @@ function startDaemon({
1524
1246
  await globalRuntimeRouter.handleRequest(routedProjectRoot, req, socket);
1525
1247
  return;
1526
1248
  }
1249
+ if (globalRuntimeRouter && sameProjectRoot(projectRoot, globalRuntimeRouter.controllerRoot)) {
1250
+ globalRuntimeRouter.bindControllerClient?.(socket);
1251
+ }
1527
1252
  if (await runtimeControlPlane.handleRequest(req, socket)) return;
1253
+ if (req.type === IPC_REQUEST_TYPES.AGENT_RUNTIME) {
1254
+ try {
1255
+ const session = ["cancel", "resume"].includes(req.operation)
1256
+ ? mainAgentHost.findRuntime({ sessionId: req.session_id, taskRunId: req.task_run_id, interactionId: req.interaction_id })
1257
+ : ["submit", "events"].includes(req.operation) ? mainAgentHost.resolveRuntime(req.session_id || "main-default") : null;
1258
+ let result;
1259
+ if (req.operation === "submit") result = session.submit({ requestId: req.request_id, text: req.text, attachments: req.attachments || [] });
1260
+ else if (req.operation === "cancel") result = session.cancel({ taskRunId: req.task_run_id, reason: req.reason });
1261
+ else if (req.operation === "resume") result = await session.resume({ interactionId: req.interaction_id, answer: req.answer });
1262
+ else if (req.operation === "events") {
1263
+ const events = session.events({ after: Number(req.after_sequence) || 0 });
1264
+ result = { events: events.slice(0, 1000).map(mainAgentHost.publicEvent), has_more: events.length > 1000,
1265
+ next_sequence: events[Math.min(events.length, 1000) - 1]?.sequence || Number(req.after_sequence) || 0 };
1266
+ }
1267
+ else if (req.operation === "tasks") result = await mainAgentHost.taskPort.execute(req.arguments || {}, { sessionId: req.session_id || "main-default", requestId: req.request_id });
1268
+ else if (req.operation === "status") result = mainAgentHost.snapshot();
1269
+ else throw new Error("unknown agent_runtime operation");
1270
+ if (!socket.destroyed) socket.write(`${JSON.stringify({ type: IPC_RESPONSE_TYPES.RUNTIME_RESULT, request_id: req.request_id, data: result })}\n`);
1271
+ } catch (error) {
1272
+ if (!socket.destroyed) socket.write(`${JSON.stringify({ type: IPC_RESPONSE_TYPES.ERROR, request_id: req.request_id, error: error.message, code: error.code || "runtime_error" })}\n`);
1273
+ }
1274
+ return;
1275
+ }
1528
1276
  if (req.type === IPC_REQUEST_TYPES.MCP_STATUS || req.type === IPC_REQUEST_TYPES.MCP_RESTART) {
1529
1277
  if (!isGlobalControllerProjectRoot(projectRoot)) {
1530
1278
  socket.write(`${JSON.stringify({
@@ -1568,6 +1316,13 @@ function startDaemon({
1568
1316
  return;
1569
1317
  }
1570
1318
  if (req.type === IPC_REQUEST_TYPES.PROMPT) {
1319
+ req.request_id = req.request_id || require("crypto").randomUUID();
1320
+ let effectIndex = 0;
1321
+ const effect = async (kind, args, invoke) => {
1322
+ const result = await mainAgentHost.management.commands.execute({ commandId: `prompt-${require("crypto").createHash("sha256").update(`${req.request_id}:${effectIndex++}`).digest("hex").slice(0, 32)}`, kind, args }, invoke);
1323
+ if (result?.code === "uncertain_effect") throw Object.assign(new Error("effect outcome is unknown; inspect its receipt before retrying"), { code: "uncertain_effect" });
1324
+ return result;
1325
+ };
1571
1326
  await handlePromptRequest({
1572
1327
  projectRoot,
1573
1328
  req,
@@ -1578,8 +1333,11 @@ function startDaemon({
1578
1333
  runPromptWithAssistant,
1579
1334
  runUfooAgent,
1580
1335
  runUfooRouteAgent,
1581
- dispatchMessages,
1582
- handleOps: handleRuntimeOps,
1336
+ selectExecutionPath,
1337
+ runMainAgent: ({ originalPrompt, requestId, sessionId, requestMeta }) => mainAgentHost.runPrompt({ prompt: originalPrompt, requestId, sessionId, requestMeta }),
1338
+ runCompatibility: (request, invoke) => mainAgentHost.runCompatibility(request, invoke),
1339
+ dispatchMessages: (root, messages) => effect("prompt-dispatch", { root, messages }, () => dispatchMessages(root, messages, { strict: true })),
1340
+ handleOps: (root, ops, manager) => effect("prompt-ops", { root, ops }, () => handleRuntimeOps(root, ops, manager)),
1583
1341
  markPending: (target) => busBridge.markPending(target),
1584
1342
  reportTaskStatus: async (report) => {
1585
1343
  await recordAgentReport({
@@ -1605,6 +1363,7 @@ function startDaemon({
1605
1363
  if (!root) {
1606
1364
  return { ok: false, error: "target project root is required" };
1607
1365
  }
1366
+ return effect("project-forward", { root, prompt, requestMeta }, async () => {
1608
1367
  if (!fs.existsSync(root)) {
1609
1368
  return { ok: false, error: `target project not found: ${root}` };
1610
1369
  }
@@ -1642,11 +1401,14 @@ function startDaemon({
1642
1401
  type: IPC_REQUEST_TYPES.PROMPT,
1643
1402
  text: String(prompt || ""),
1644
1403
  request_meta: nextMeta,
1404
+ request_id: req.request_id || req.message_id || req.id,
1405
+ session_id: req.session_id,
1645
1406
  };
1646
1407
  if (globalRuntimeRouter && typeof globalRuntimeRouter.request === "function") {
1647
1408
  return globalRuntimeRouter.request(root, routedRequest, { timeoutMs: 12000 });
1648
1409
  }
1649
1410
  return sendPromptRequestToProject(root, routedRequest);
1411
+ });
1650
1412
  },
1651
1413
  log,
1652
1414
  });
@@ -1685,6 +1447,7 @@ function startDaemon({
1685
1447
  `${JSON.stringify({
1686
1448
  type: IPC_RESPONSE_TYPES.ERROR,
1687
1449
  error: "bus_send requires target and message",
1450
+ ...(req.request_id ? { request_id: req.request_id } : {}),
1688
1451
  })}
1689
1452
  `,
1690
1453
  );
@@ -1709,6 +1472,7 @@ function startDaemon({
1709
1472
  socket.write(
1710
1473
  `${JSON.stringify({
1711
1474
  type: IPC_RESPONSE_TYPES.BUS_SEND_OK,
1475
+ ...(req.request_id ? { request_id: req.request_id } : {}),
1712
1476
  })}
1713
1477
  `,
1714
1478
  );
@@ -1718,6 +1482,7 @@ function startDaemon({
1718
1482
  `${JSON.stringify({
1719
1483
  type: IPC_RESPONSE_TYPES.ERROR,
1720
1484
  error: err.message || "bus_send failed",
1485
+ ...(req.request_id ? { request_id: req.request_id } : {}),
1721
1486
  })}
1722
1487
  `,
1723
1488
  );
@@ -1885,6 +1650,7 @@ function startDaemon({
1885
1650
  }
1886
1651
  const op = {
1887
1652
  action: "launch",
1653
+ internal_only: req.internal_only === true,
1888
1654
  agent: normalizedAgent,
1889
1655
  count: finalCount,
1890
1656
  nickname: explicitNickname,
@@ -2169,6 +1935,7 @@ function startDaemon({
2169
1935
  const result = await daemonGroupOrchestrator.runGroup({
2170
1936
  alias,
2171
1937
  instance,
1938
+ internal_only: req.internal_only === true,
2172
1939
  dry_run: dryRun,
2173
1940
  host_inject_sock: hostInjectSock,
2174
1941
  host_daemon_sock: hostDaemonSock,
@@ -2606,6 +2373,7 @@ function startDaemon({
2606
2373
  type: IPC_RESPONSE_TYPES.REGISTER_OK,
2607
2374
  subscriberId,
2608
2375
  nickname: resolvedNickname,
2376
+ agentHandle: result.agent_handle,
2609
2377
  })}
2610
2378
  `,
2611
2379
  );
@@ -2641,11 +2409,12 @@ function startDaemon({
2641
2409
  const resolved = resolveSessionFromFile(agentType, {
2642
2410
  pid: parsedAgentPid,
2643
2411
  cwd: projectRoot,
2412
+ projectRoot,
2413
+ subscriberId,
2644
2414
  });
2645
- if (resolved && resolved.sessionId) {
2415
+ if (resolved && resolved.sessionId && persistProviderSession(projectRoot, subscriberId, resolved)) {
2646
2416
  const attemptNote = attempt > 1 ? ` (attempt ${attempt})` : "";
2647
2417
  log(`agent_ready session resolved from file for ${subscriberId}: ${resolved.sessionId}${attemptNote}`);
2648
- persistProviderSession(projectRoot, subscriberId, resolved);
2649
2418
  if (providerSessions) {
2650
2419
  providerSessions.set(subscriberId, {
2651
2420
  sessionId: resolved.sessionId,
@@ -2837,6 +2606,7 @@ function startDaemon({
2837
2606
  if (daemonCronController) {
2838
2607
  daemonCronController.stopAll();
2839
2608
  }
2609
+ void mainAgentHost.close().catch((error) => writeLog(`main runtime shutdown failed: ${error.message}`));
2840
2610
 
2841
2611
  runtimeControlPlane.stop();
2842
2612
  if (mcpHttpServer) {