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
package/src/config.js CHANGED
@@ -1,6 +1,8 @@
1
1
  const fs = require("fs");
2
2
  const os = require("os");
3
3
  const path = require("path");
4
+ const { withFileLock } = require("./coordination/state/fileLock");
5
+ const { writeFileAtomic } = require("./coordination/bus/utils");
4
6
 
5
7
  const UCODE_FIELDS = [
6
8
  "ucodeProvider",
@@ -13,8 +15,8 @@ const UCODE_FIELDS = [
13
15
 
14
16
  const SETTINGS_MODEL_DEFAULTS = Object.freeze({
15
17
  agent: Object.freeze({
16
- codex: "gpt-5.5",
17
- claude: "opus-4.7",
18
+ codex: "gpt-6.1-sol",
19
+ claude: "claude-opus-5-5",
18
20
  // agy (Antigravity CLI) only supports model selection via in-REPL
19
21
  // `/model` slash command, which persists across launches. There is no
20
22
  // command-line flag for model, so the value here is a placeholder for
@@ -25,30 +27,23 @@ const SETTINGS_MODEL_DEFAULTS = Object.freeze({
25
27
  kimi: "",
26
28
  "grok-build": "grok-4.6",
27
29
  }),
28
- router: Object.freeze({
29
- codex: "gpt-5.3-codex-spark",
30
- claude: "sonnet-4.7",
31
- agy: "",
32
- kimi: "",
33
- "grok-build": "grok-4.6",
34
- }),
35
30
  });
36
31
 
37
32
  const DEFAULT_CONFIG = {
38
33
  launchMode: "auto",
39
34
  daemonTopology: "global",
40
35
  agentProvider: "codex-cli",
41
- controllerMode: "main",
42
36
  mcpPort: 47631,
43
- codexInternalThreadMode: "api",
44
37
  codexAuthPath: "",
45
38
  codexOauthRefreshWindowSec: 300,
46
39
  claudeOauthProfile: "",
47
40
  claudeOauthTokenPath: "",
48
41
  claudeOauthRefreshWindowSec: 300,
49
42
  agentModel: "",
50
- routerProvider: "",
51
- routerModel: "",
43
+ agentBaseUrl: "",
44
+ agentApiKey: "",
45
+ agentThinking: "medium",
46
+ agentModelRevision: 0,
52
47
  autoResume: false,
53
48
  };
54
49
 
@@ -79,6 +74,7 @@ function normalizeDaemonTopology(value) {
79
74
  }
80
75
 
81
76
  function normalizeAgentProvider(value) {
77
+ if (value === "custom") return "custom";
82
78
  if (value === "claude-cli") return "claude-cli";
83
79
  if (value === "agy-cli" || value === "agy" || value === "antigravity") return "agy-cli";
84
80
  if (value === "kimi-cli" || value === "kimi") return "kimi-cli";
@@ -88,6 +84,7 @@ function normalizeAgentProvider(value) {
88
84
 
89
85
  function providerKey(value = "") {
90
86
  const text = String(value || "").trim().toLowerCase();
87
+ if (text === "custom" || text === "openai") return "openai";
91
88
  if (text === "claude" || text === "claude-cli" || text === "claude-code" || text === "anthropic") return "claude";
92
89
  if (text === "agy" || text === "agy-cli" || text === "antigravity") return "agy";
93
90
  if (text === "kimi" || text === "kimi-cli" || text === "kimi-code") return "kimi";
@@ -102,45 +99,15 @@ function sameModelProvider(left = "", right = "") {
102
99
  }
103
100
 
104
101
  function defaultAgentModelForProvider(value = "") {
102
+ if (value === "custom") return "";
105
103
  return SETTINGS_MODEL_DEFAULTS.agent[providerKey(value)] || SETTINGS_MODEL_DEFAULTS.agent.codex;
106
104
  }
107
105
 
108
- function defaultRouterProviderForAgentProvider(value = "") {
109
- const key = providerKey(value);
110
- if (key === "claude") return "claude";
111
- // agy has no router-model API; fall back to codex (the controller still
112
- // routes via codex/claude regardless of which agent provider runs).
113
- if (key === "agy") return "codex";
114
- // kimi likewise manages its own models; router falls back to codex.
115
- if (key === "kimi") return "codex";
116
- return "codex";
117
- }
118
-
119
- function defaultRouterModelForProvider(value = "") {
120
- return SETTINGS_MODEL_DEFAULTS.router[providerKey(value)] || SETTINGS_MODEL_DEFAULTS.router.codex;
121
- }
122
-
123
106
  function normalizeModel(value, fallback = "") {
124
107
  const text = typeof value === "string" ? value.trim() : "";
125
108
  return text || fallback;
126
109
  }
127
110
 
128
- function normalizeControllerMode(value) {
129
- const raw = String(value || "").trim().toLowerCase();
130
- if (raw === "shadow") return "shadow";
131
- if (raw === "router-api") return "main";
132
- if (raw === "main") return "main";
133
- if (raw === "loop") return "loop";
134
- return "legacy";
135
- }
136
-
137
- function normalizeCodexInternalThreadMode(value) {
138
- const raw = String(value || "").trim().toLowerCase();
139
- if (raw === "api" || raw === "direct" || raw === "direct-api" || raw === "upstream") return "api";
140
- if (raw === "sdk") return "api";
141
- return "legacy";
142
- }
143
-
144
111
  function normalizeMcpPort(value) {
145
112
  const parsed = Number.parseInt(value, 10);
146
113
  if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535) return DEFAULT_CONFIG.mcpPort;
@@ -187,15 +154,30 @@ function loadJsonSafe(filePath) {
187
154
  }
188
155
  }
189
156
 
157
+ function loadJsonForUpdate(filePath) {
158
+ try {
159
+ const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
160
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected a JSON object");
161
+ return value;
162
+ } catch (error) {
163
+ if (error.code === "ENOENT") return {};
164
+ throw new Error(`Refusing to overwrite unreadable configuration: ${filePath}`, { cause: error });
165
+ }
166
+ }
167
+
168
+ function withoutRemovedSettings(config) {
169
+ const next = { ...config };
170
+ for (const key of ["controllerMode", "routerProvider", "routerModel", "routerTimeoutMs", "routerConfidenceThreshold", "codexInternalThreadMode"]) {
171
+ delete next[key];
172
+ }
173
+ return next;
174
+ }
175
+
190
176
  function loadConfig(projectRoot) {
191
177
  try {
192
- const raw = loadJsonSafe(configPath(projectRoot));
178
+ const raw = withoutRemovedSettings(loadJsonSafe(configPath(projectRoot)));
193
179
  const globalRaw = loadJsonSafe(globalConfigPath());
194
180
  const agentProvider = normalizeAgentProvider(raw.agentProvider);
195
- const routerProvider = normalizeModel(
196
- raw.routerProvider,
197
- defaultRouterProviderForAgentProvider(agentProvider)
198
- );
199
181
  return {
200
182
  ...DEFAULT_CONFIG,
201
183
  ...raw,
@@ -207,32 +189,21 @@ function loadConfig(projectRoot) {
207
189
  ),
208
190
  agentProvider,
209
191
  agentModel: normalizeModel(raw.agentModel, defaultAgentModelForProvider(agentProvider)),
210
- routerProvider,
211
- routerModel: normalizeModel(raw.routerModel, defaultRouterModelForProvider(routerProvider)),
212
- controllerMode: Object.prototype.hasOwnProperty.call(raw, "controllerMode")
213
- ? normalizeControllerMode(raw.controllerMode)
214
- : DEFAULT_CONFIG.controllerMode,
215
192
  mcpPort: normalizeMcpPort(raw.mcpPort),
216
- codexInternalThreadMode: Object.prototype.hasOwnProperty.call(raw, "codexInternalThreadMode")
217
- ? normalizeCodexInternalThreadMode(raw.codexInternalThreadMode)
218
- : DEFAULT_CONFIG.codexInternalThreadMode,
219
193
  codexAuthPath: normalizeCodexAuthPath(raw.codexAuthPath),
220
194
  codexOauthRefreshWindowSec: normalizeCodexOauthRefreshWindowSec(raw.codexOauthRefreshWindowSec),
221
195
  claudeOauthProfile: normalizeClaudeOauthProfile(raw.claudeOauthProfile),
222
196
  claudeOauthTokenPath: normalizeClaudeOauthTokenPath(raw.claudeOauthTokenPath),
223
197
  claudeOauthRefreshWindowSec: normalizeClaudeOauthRefreshWindowSec(raw.claudeOauthRefreshWindowSec),
224
- autoResume: raw.autoResume !== false,
198
+ autoResume: typeof raw.autoResume === "boolean" ? raw.autoResume : DEFAULT_CONFIG.autoResume,
225
199
  // Merge ucode fields from global config so callers still see them
226
200
  ...loadGlobalUcodeConfig(),
227
201
  };
228
202
  } catch {
229
203
  const agentProvider = DEFAULT_CONFIG.agentProvider;
230
- const routerProvider = defaultRouterProviderForAgentProvider(agentProvider);
231
204
  return {
232
205
  ...DEFAULT_CONFIG,
233
206
  agentModel: defaultAgentModelForProvider(agentProvider),
234
- routerProvider,
235
- routerModel: defaultRouterModelForProvider(routerProvider),
236
207
  ...DEFAULT_UCODE_CONFIG,
237
208
  };
238
209
  }
@@ -240,56 +211,49 @@ function loadConfig(projectRoot) {
240
211
 
241
212
  function saveConfig(projectRoot, config) {
242
213
  const target = configPath(projectRoot);
243
- fs.mkdirSync(path.dirname(target), { recursive: true });
244
- let existing = {};
245
- try {
246
- existing = JSON.parse(fs.readFileSync(target, "utf8"));
247
- } catch {
248
- existing = {};
249
- }
250
- // Strip ucode fields — they belong in global config only
251
- const projectUpdates = {};
252
- for (const [k, v] of Object.entries(config)) {
253
- if (!UCODE_FIELDS.includes(k)) {
254
- projectUpdates[k] = v;
214
+ return withFileLock(target, () => {
215
+ fs.mkdirSync(path.dirname(target), { recursive: true });
216
+ const existing = loadJsonForUpdate(target);
217
+ // Strip ucode fields — they belong in global config only
218
+ const projectUpdates = {};
219
+ for (const [k, v] of Object.entries(config)) {
220
+ if (!UCODE_FIELDS.includes(k)) {
221
+ projectUpdates[k] = v;
222
+ }
255
223
  }
256
- }
257
- const merged = {
258
- ...DEFAULT_CONFIG,
259
- ...existing,
260
- ...projectUpdates,
261
- };
262
- const hasProjectDaemonTopology =
263
- Object.prototype.hasOwnProperty.call(existing, "daemonTopology")
264
- || Object.prototype.hasOwnProperty.call(projectUpdates, "daemonTopology");
265
- // Remove any stale ucode fields from project config
266
- for (const f of UCODE_FIELDS) {
267
- delete merged[f];
268
- }
269
- merged.launchMode = normalizeLaunchMode(merged.launchMode);
270
- if (hasProjectDaemonTopology) {
271
- merged.daemonTopology = normalizeDaemonTopology(merged.daemonTopology);
272
- } else {
273
- // Topology is a machine-wide rollout setting unless a project explicitly
274
- // opts into an override. Do not persist the default and accidentally pin
275
- // this project to project-daemon mode forever.
276
- delete merged.daemonTopology;
277
- }
278
- merged.agentProvider = normalizeAgentProvider(merged.agentProvider);
279
- merged.agentModel = typeof merged.agentModel === "string" ? merged.agentModel.trim() : "";
280
- merged.routerProvider = typeof merged.routerProvider === "string" ? merged.routerProvider.trim() : "";
281
- merged.routerModel = typeof merged.routerModel === "string" ? merged.routerModel.trim() : "";
282
- merged.controllerMode = normalizeControllerMode(merged.controllerMode);
283
- merged.mcpPort = normalizeMcpPort(merged.mcpPort);
284
- merged.codexInternalThreadMode = normalizeCodexInternalThreadMode(merged.codexInternalThreadMode);
285
- merged.codexAuthPath = normalizeCodexAuthPath(merged.codexAuthPath);
286
- merged.codexOauthRefreshWindowSec = normalizeCodexOauthRefreshWindowSec(merged.codexOauthRefreshWindowSec);
287
- merged.claudeOauthProfile = normalizeClaudeOauthProfile(merged.claudeOauthProfile);
288
- merged.claudeOauthTokenPath = normalizeClaudeOauthTokenPath(merged.claudeOauthTokenPath);
289
- merged.claudeOauthRefreshWindowSec = normalizeClaudeOauthRefreshWindowSec(merged.claudeOauthRefreshWindowSec);
290
- merged.autoResume = merged.autoResume !== false;
291
- fs.writeFileSync(target, JSON.stringify(merged, null, 2));
292
- return merged;
224
+ const merged = withoutRemovedSettings({
225
+ ...DEFAULT_CONFIG,
226
+ ...existing,
227
+ ...projectUpdates,
228
+ });
229
+ const hasProjectDaemonTopology =
230
+ Object.prototype.hasOwnProperty.call(existing, "daemonTopology")
231
+ || Object.prototype.hasOwnProperty.call(projectUpdates, "daemonTopology");
232
+ // Remove any stale ucode fields from project config
233
+ for (const f of UCODE_FIELDS) {
234
+ delete merged[f];
235
+ }
236
+ merged.launchMode = normalizeLaunchMode(merged.launchMode);
237
+ if (hasProjectDaemonTopology) {
238
+ merged.daemonTopology = normalizeDaemonTopology(merged.daemonTopology);
239
+ } else {
240
+ // Topology is a machine-wide rollout setting unless a project explicitly
241
+ // opts into an override. Do not persist the default and accidentally pin
242
+ // this project to project-daemon mode forever.
243
+ delete merged.daemonTopology;
244
+ }
245
+ merged.agentProvider = normalizeAgentProvider(merged.agentProvider);
246
+ merged.agentModel = typeof merged.agentModel === "string" ? merged.agentModel.trim() : "";
247
+ merged.mcpPort = normalizeMcpPort(merged.mcpPort);
248
+ merged.codexAuthPath = normalizeCodexAuthPath(merged.codexAuthPath);
249
+ merged.codexOauthRefreshWindowSec = normalizeCodexOauthRefreshWindowSec(merged.codexOauthRefreshWindowSec);
250
+ merged.claudeOauthProfile = normalizeClaudeOauthProfile(merged.claudeOauthProfile);
251
+ merged.claudeOauthTokenPath = normalizeClaudeOauthTokenPath(merged.claudeOauthTokenPath);
252
+ merged.claudeOauthRefreshWindowSec = normalizeClaudeOauthRefreshWindowSec(merged.claudeOauthRefreshWindowSec);
253
+ merged.autoResume = typeof merged.autoResume === "boolean" ? merged.autoResume : DEFAULT_CONFIG.autoResume;
254
+ writeFileAtomic(target, JSON.stringify(merged, null, 2), { mode: 0o600 });
255
+ return merged;
256
+ });
293
257
  }
294
258
 
295
259
  function loadGlobalUcodeConfig() {
@@ -306,16 +270,18 @@ function loadGlobalUcodeConfig() {
306
270
 
307
271
  function saveGlobalUcodeConfig(updates = {}) {
308
272
  const target = globalConfigPath();
309
- fs.mkdirSync(path.dirname(target), { recursive: true });
310
- const existing = loadJsonSafe(target);
311
- const merged = { ...existing };
312
- for (const [k, v] of Object.entries(updates)) {
313
- if (UCODE_FIELDS.includes(k)) {
314
- merged[k] = typeof v === "string" ? v : "";
273
+ return withFileLock(target, () => {
274
+ fs.mkdirSync(path.dirname(target), { recursive: true });
275
+ const existing = loadJsonForUpdate(target);
276
+ const merged = withoutRemovedSettings(existing);
277
+ for (const [k, v] of Object.entries(updates)) {
278
+ if (UCODE_FIELDS.includes(k)) {
279
+ merged[k] = typeof v === "string" ? v : "";
280
+ }
315
281
  }
316
- }
317
- fs.writeFileSync(target, JSON.stringify(merged, null, 2));
318
- return merged;
282
+ writeFileAtomic(target, JSON.stringify(merged, null, 2), { mode: 0o600 });
283
+ return merged;
284
+ });
319
285
  }
320
286
 
321
287
  function loadGlobalDaemonConfig() {
@@ -327,14 +293,16 @@ function loadGlobalDaemonConfig() {
327
293
 
328
294
  function saveGlobalDaemonConfig(updates = {}) {
329
295
  const target = globalConfigPath();
330
- fs.mkdirSync(path.dirname(target), { recursive: true });
331
- const existing = loadJsonSafe(target);
332
- const merged = { ...existing };
333
- if (Object.prototype.hasOwnProperty.call(updates, "daemonTopology")) {
334
- merged.daemonTopology = normalizeDaemonTopology(updates.daemonTopology);
335
- }
336
- fs.writeFileSync(target, JSON.stringify(merged, null, 2));
337
- return loadGlobalDaemonConfig();
296
+ return withFileLock(target, () => {
297
+ fs.mkdirSync(path.dirname(target), { recursive: true });
298
+ const existing = loadJsonForUpdate(target);
299
+ const merged = withoutRemovedSettings(existing);
300
+ if (Object.prototype.hasOwnProperty.call(updates, "daemonTopology")) {
301
+ merged.daemonTopology = normalizeDaemonTopology(updates.daemonTopology);
302
+ }
303
+ writeFileAtomic(target, JSON.stringify(merged, null, 2), { mode: 0o600 });
304
+ return loadGlobalDaemonConfig();
305
+ });
338
306
  }
339
307
 
340
308
  module.exports = {
@@ -351,11 +319,7 @@ module.exports = {
351
319
  providerKey,
352
320
  sameModelProvider,
353
321
  defaultAgentModelForProvider,
354
- defaultRouterProviderForAgentProvider,
355
- defaultRouterModelForProvider,
356
- normalizeControllerMode,
357
322
  normalizeMcpPort,
358
- normalizeCodexInternalThreadMode,
359
323
  normalizeCodexAuthPath,
360
324
  normalizeCodexOauthRefreshWindowSec,
361
325
  normalizeClaudeOauthProfile,
@@ -15,6 +15,7 @@ const {
15
15
  } = require("./utils");
16
16
 
17
17
  const PROCESSING_STALE_MS = 30000;
18
+ const { withFileLock } = require("../state/fileLock");
18
19
 
19
20
  function positiveSeq(event) {
20
21
  const seq = Number(event && event.seq);
@@ -241,12 +242,15 @@ class DeliveryQueue {
241
242
  .filter((file) => this.isRecoverableProcessingFile(file, options));
242
243
  if (files.length === 0) return { recovered: 0, files: [] };
243
244
 
244
- const all = [...this.readPendingRaw()];
245
+ const all = [];
245
246
  for (const file of files) {
246
247
  all.push(...readJsonlLoose(file));
247
248
  }
249
+ const pending = this.readPendingRaw();
250
+ all.push(...pending);
248
251
 
249
- const merged = this.mergeAndSort(all);
252
+ const latestPending = new Map(pending.filter((event) => positiveSeq(event)).map((event) => [positiveSeq(event), event]));
253
+ const merged = this.mergeAndSort(all).map((event) => latestPending.get(positiveSeq(event)) || event);
250
254
  this.writePending(merged);
251
255
 
252
256
  for (const file of files) {
@@ -319,6 +323,16 @@ class DeliveryQueue {
319
323
  }
320
324
  }
321
325
 
326
+ // All queue mutations share the same cross-process transaction, including
327
+ // nested recovery and pending rewrites. Atomic rename alone cannot protect an
328
+ // append from a concurrent read-modify-write consumer.
329
+ for (const method of ["append", "writePending", "recover", "claimNext", "completeClaim", "restoreClaim", "readPending"]) {
330
+ const implementation = DeliveryQueue.prototype[method];
331
+ DeliveryQueue.prototype[method] = function (...args) {
332
+ return withFileLock(this.pendingFile, () => implementation.apply(this, args));
333
+ };
334
+ }
335
+
322
336
  module.exports = {
323
337
  DeliveryQueue,
324
338
  QUEUE_TYPES,
@@ -11,7 +11,6 @@ const {
11
11
  generateInstanceId,
12
12
  subscriberToSafeName,
13
13
  isPidAlive,
14
- truncateFile,
15
14
  getCurrentTty,
16
15
  sleep,
17
16
  } = require("./utils");
@@ -330,6 +329,7 @@ class EventBus {
330
329
  if (options.envelope === false) data.envelope = false;
331
330
  const result = eventName === "message"
332
331
  ? await this.messageManager.send(target, message, publisher, {
332
+ ...options,
333
333
  data,
334
334
  injectionMode: options.injectionMode,
335
335
  source: options.source,
@@ -407,7 +407,11 @@ class EventBus {
407
407
  console.log();
408
408
  }
409
409
 
410
- console.log(`${colors.cyan}After handling, run: ufoo bus ack ${subscriber}${colors.reset}`);
410
+ if (this.messageManager.isRunnerManaged(subscriber)) {
411
+ console.log(`${colors.cyan}Internal runner confirms completed tasks automatically; queued messages are retained.${colors.reset}`);
412
+ } else {
413
+ console.log(`${colors.cyan}After handling, run: ufoo bus ack ${subscriber}${colors.reset}`);
414
+ }
411
415
 
412
416
  if (autoAck) {
413
417
  await this.ack(subscriber);
@@ -500,7 +504,9 @@ class EventBus {
500
504
 
501
505
  const count = await this.messageManager.ack(subscriber);
502
506
 
503
- if (count > 0) {
507
+ if (this.messageManager.isRunnerManaged(subscriber)) {
508
+ logOk("Internal runner confirms completed tasks automatically; queued messages are retained");
509
+ } else if (count > 0) {
504
510
  logOk(`Acknowledged and cleared ${count} message(s)`);
505
511
  } else {
506
512
  logOk("No pending messages to acknowledge");
@@ -518,7 +524,9 @@ class EventBus {
518
524
 
519
525
  const count = await this.messageManager.ackThrough(subscriber, throughSeq);
520
526
 
521
- if (count > 0) {
527
+ if (this.messageManager.isRunnerManaged(subscriber)) {
528
+ logOk("Internal runner confirms completed tasks automatically; queued messages are retained");
529
+ } else if (count > 0) {
522
530
  logOk(`Acknowledged ${count} message(s) through seq=${throughSeq}`);
523
531
  } else {
524
532
  logOk(`No pending messages through seq=${throughSeq}`);
@@ -891,13 +899,10 @@ class EventBus {
891
899
 
892
900
  const queuePath = this.queueManager.getPendingPath(target);
893
901
  this.queueManager.ensureQueueDir(target);
894
- if (!fs.existsSync(queuePath)) {
895
- fs.writeFileSync(queuePath, "", "utf8");
896
- }
897
902
 
898
903
  if (options.reset) {
899
904
  console.log("[listen] Resetting queue...");
900
- truncateFile(queuePath);
905
+ await this.queueManager.clearPending(target);
901
906
  }
902
907
 
903
908
  const readLines = () => {
@@ -958,7 +963,7 @@ class EventBus {
958
963
  async inject(subscriber, commandOverride) {
959
964
  this.ensureBus();
960
965
  const injector = new Injector(this.busDir, this.agentsFile);
961
- await injector.inject(subscriber, commandOverride);
966
+ await injector.inject(subscriber, commandOverride, { deliveryId: `manual:${require("crypto").randomUUID()}` });
962
967
  }
963
968
  }
964
969
 
@@ -387,16 +387,17 @@ class Injector {
387
387
  /**
388
388
  * 使用指定路径的 PTY socket 注入命令
389
389
  */
390
- async injectPtyAtPath(sockPath, command) {
390
+ async injectPtyAtPath(sockPath, command, options = {}) {
391
391
  return new Promise((resolve, reject) => {
392
392
  const client = net.createConnection(sockPath, () => {
393
- client.write(JSON.stringify({ type: "inject", command }) + "\n");
393
+ client.write(JSON.stringify({ type: "inject", command, ...options }) + "\n");
394
394
  });
395
395
 
396
396
  let buffer = "";
397
+ let received = false;
397
398
  const timeout = setTimeout(() => {
398
399
  client.destroy();
399
- reject(new Error("PTY inject timeout"));
400
+ reject(Object.assign(new Error("Inject response timed out"), options.deliveryId ? { code: "native_outcome_unknown" } : {}));
400
401
  }, 5000);
401
402
 
402
403
  client.on("data", (data) => {
@@ -406,6 +407,7 @@ class Injector {
406
407
 
407
408
  for (const line of lines) {
408
409
  if (!line.trim()) continue;
410
+ received = true;
409
411
  clearTimeout(timeout);
410
412
  try {
411
413
  const res = JSON.parse(line);
@@ -413,7 +415,7 @@ class Injector {
413
415
  if (res.ok) {
414
416
  resolve();
415
417
  } else {
416
- reject(new Error(res.error || "PTY inject failed"));
418
+ reject(Object.assign(new Error(res.error || "PTY inject failed"), { code: res.code }));
417
419
  }
418
420
  } catch (err) {
419
421
  client.end();
@@ -430,6 +432,7 @@ class Injector {
430
432
 
431
433
  client.on("close", () => {
432
434
  clearTimeout(timeout);
435
+ if (!received) reject(Object.assign(new Error("Inject socket closed without a receipt"), options.deliveryId ? { code: "native_outcome_unknown" } : {}));
433
436
  });
434
437
  });
435
438
  }
@@ -455,9 +458,9 @@ class Injector {
455
458
  * 2. tmux send-keys(无需权限)
456
459
  * 3. Terminal.app/iTerm2 tty lookup(terminal mode fallback)
457
460
  */
458
- async inject(subscriber, commandOverride) {
459
- if (String(subscriber || "").startsWith("ufoo-code:")) {
460
- throw new Error(`Inject disabled for ${subscriber}. ufoo-code consumes bus internally.`);
461
+ async inject(subscriber, commandOverride, delivery = {}) {
462
+ if (/^ucode:/.test(String(subscriber || ""))) {
463
+ throw new Error(`Inject disabled for ${subscriber}. ucode consumes bus internally.`);
461
464
  }
462
465
 
463
466
  // Terminal injection is a delivery adapter for explicit prompt text.
@@ -471,6 +474,11 @@ class Injector {
471
474
  }
472
475
 
473
476
  const meta = this.getAgentMeta(subscriber) || {};
477
+ if (meta.native_delivery) {
478
+ // A native write may already be accepted. Never fall back to keystrokes
479
+ // after a native failure; the scheduler retains the queued work.
480
+ return this.injectPtyAtPath(this.getInjectSockPath(subscriber), command, delivery);
481
+ }
474
482
  const launchMode = meta.launch_mode || "";
475
483
  const adapterRouter = createTerminalAdapterRouter();
476
484
  const adapter = adapterRouter.getAdapter({ launchMode, agentId: subscriber, meta });
@@ -15,6 +15,7 @@ const { buildMessageData } = require("./messageMeta");
15
15
  const { getUfooPaths } = require("../state/paths");
16
16
  const { applyProjectNicknamePrefix } = require("../../runtime/daemon/nicknameScope");
17
17
  const { QUEUE_TYPES, normalizeQueueEnvelope } = require("./deliveryQueue");
18
+ const { isInternalAgentMeta } = require("../../runtime/contracts/agentMode");
18
19
 
19
20
  const SEQ_LOCK_TIMEOUT_MS = 5000;
20
21
  const SEQ_LOCK_POLL_MS = 25;
@@ -523,13 +524,26 @@ class MessageManager {
523
524
  }
524
525
 
525
526
  /**
526
- * 确认消息(清空待处理队列)
527
+ * Internal runners own delivery claims and complete them after execution.
528
+ * Model-issued acknowledgements must never claim future internal tasks.
527
529
  */
530
+ isRunnerManaged(subscriber) {
531
+ return isInternalAgentMeta(this.busData?.agents?.[subscriber]);
532
+ }
533
+
528
534
  async ack(subscriber) {
535
+ if (this.isRunnerManaged(subscriber)) return 0;
529
536
  return this.queueManager.ackPending(subscriber);
530
537
  }
531
538
 
532
539
  async ackThrough(subscriber, throughSeq) {
540
+ if (this.isRunnerManaged(subscriber)) {
541
+ const limit = Number(throughSeq);
542
+ if (!Number.isFinite(limit) || limit <= 0) {
543
+ throw new Error("ack --through requires a positive sequence");
544
+ }
545
+ return 0;
546
+ }
533
547
  return this.queueManager.ackPendingThrough(subscriber, throughSeq);
534
548
  }
535
549