u-foo 3.1.6 → 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 -2668
  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
@@ -11,6 +11,7 @@ const {
11
11
  const { redactSecrets } = require("../../runtime/privacy/redactor");
12
12
  const { canonicalProjectRoot } = require("../../runtime/projects/projectId");
13
13
  const { getUfooPaths } = require("../state/paths");
14
+ const { withFileLock } = require("../state/fileLock");
14
15
 
15
16
  const SCHEMA_VERSION = "1.0";
16
17
  const ID_PREFIX = "mem-";
@@ -20,11 +21,6 @@ const HISTORY_CACHE_TTL_MS = 60 * 60 * 1000;
20
21
  const DEFAULT_PREFIX_MAX_TOKENS = 1500;
21
22
  const prefixCache = new Map();
22
23
 
23
- function sleepSync(ms) {
24
- const buffer = new SharedArrayBuffer(4);
25
- const array = new Int32Array(buffer);
26
- Atomics.wait(array, 0, 0, ms);
27
- }
28
24
 
29
25
  function normalizeId(value = "") {
30
26
  return String(value || "").trim();
@@ -168,23 +164,11 @@ class MemoryManager {
168
164
 
169
165
  withLock(fn) {
170
166
  ensureDir(this.memoryDir);
171
- const started = Date.now();
172
- while (true) {
173
- try {
174
- fs.mkdirSync(this.lockDir);
175
- break;
176
- } catch (err) {
177
- if (err && err.code !== "EEXIST") throw err;
178
- if (Date.now() - started > 5000) {
179
- throw buildMemoryError("memory_lock_timeout", "timed out waiting for memory lock");
180
- }
181
- sleepSync(10);
182
- }
183
- }
184
167
  try {
185
- return fn();
186
- } finally {
187
- fs.rmSync(this.lockDir, { recursive: true, force: true });
168
+ return withFileLock(this.indexFile, fn, { lockfilePath: this.lockDir });
169
+ } catch (error) {
170
+ if (error.code === "ELOCKED") throw buildMemoryError("memory_lock_timeout", "timed out waiting for memory lock");
171
+ throw error;
188
172
  }
189
173
  }
190
174
 
@@ -2,6 +2,8 @@ const fs = require("fs");
2
2
  const path = require("path");
3
3
  const { getUfooPaths } = require("../state/paths");
4
4
  const { redactSecrets } = require("../../runtime/privacy/redactor");
5
+ const { withFileLock } = require("../state/fileLock");
6
+ const { writeFileAtomic } = require("../bus/utils");
5
7
 
6
8
  const REPORT_PHASES = {
7
9
  START: "start",
@@ -38,7 +40,7 @@ function normalizeScope(value = "") {
38
40
  }
39
41
 
40
42
  function normalizeReportInput(input = {}, options = {}) {
41
- const ts = options.ts || new Date().toISOString();
43
+ const ts = options.ts || input.ts || new Date().toISOString();
42
44
  let phase = normalizePhase(input.phase || options.phase);
43
45
  const entryId = String(
44
46
  input.entry_id
@@ -53,7 +55,7 @@ function normalizeReportInput(input = {}, options = {}) {
53
55
  || input.task
54
56
  || options.task_id
55
57
  || options.taskId
56
- || `task-${Date.now()}`
58
+ || `task-${require("crypto").randomUUID()}`
57
59
  ).trim();
58
60
  const agentId = String(
59
61
  input.agent_id
@@ -101,7 +103,11 @@ function normalizeReportInput(input = {}, options = {}) {
101
103
  function appendReport(projectRoot, entry) {
102
104
  ensureReportDir(projectRoot);
103
105
  const { reportsFile } = getReportPaths(projectRoot);
104
- fs.appendFileSync(reportsFile, `${JSON.stringify(redactSecrets(entry))}\n`, "utf8");
106
+ return withFileLock(reportsFile, () => {
107
+ if (entry.entry_id && parseJsonLines(reportsFile).some((row) => row.entry_id === entry.entry_id)) return false;
108
+ fs.appendFileSync(reportsFile, `${JSON.stringify(redactSecrets(entry))}\n`, "utf8");
109
+ return true;
110
+ });
105
111
  }
106
112
 
107
113
  function parseJsonLines(file) {
@@ -152,34 +158,40 @@ function loadReportState(projectRoot) {
152
158
  function saveReportState(projectRoot, state) {
153
159
  ensureReportDir(projectRoot);
154
160
  const { stateFile } = getReportPaths(projectRoot);
155
- fs.writeFileSync(stateFile, JSON.stringify(redactSecrets(state), null, 2));
161
+ writeFileAtomic(stateFile, JSON.stringify(redactSecrets(state), null, 2));
156
162
  }
157
163
 
158
164
  function updateReportState(projectRoot, entry) {
159
- const state = loadReportState(projectRoot);
160
- const current = state.agents[entry.agent_id] && typeof state.agents[entry.agent_id] === "object"
161
- ? state.agents[entry.agent_id]
162
- : {};
163
- const pending = current.pending && typeof current.pending === "object"
164
- ? { ...current.pending }
165
- : {};
166
-
167
- if (entry.phase === REPORT_PHASES.START || entry.phase === REPORT_PHASES.PROGRESS) {
168
- pending[entry.task_id] = entry;
169
- } else {
170
- delete pending[entry.task_id];
171
- }
165
+ return withFileLock(getReportPaths(projectRoot).stateFile, () => {
166
+ const state = loadReportState(projectRoot);
167
+ const current = state.agents[entry.agent_id] && typeof state.agents[entry.agent_id] === "object"
168
+ ? state.agents[entry.agent_id]
169
+ : {};
170
+ const lastByTask = current.last_by_task || {};
171
+ const previous = lastByTask[entry.task_id];
172
+ if (previous && (previous.entry_id === entry.entry_id || previous.ts > entry.ts)) return state;
173
+ const pending = current.pending && typeof current.pending === "object"
174
+ ? { ...current.pending }
175
+ : {};
176
+
177
+ if (entry.phase === REPORT_PHASES.START || entry.phase === REPORT_PHASES.PROGRESS) {
178
+ pending[entry.task_id] = entry;
179
+ } else {
180
+ delete pending[entry.task_id];
181
+ }
172
182
 
173
- state.agents[entry.agent_id] = {
174
- ...current,
175
- pending,
176
- pending_count: Object.keys(pending).length,
177
- last: entry,
178
- updated_at: entry.ts,
179
- };
180
- state.updated_at = entry.ts;
181
- saveReportState(projectRoot, state);
182
- return state;
183
+ state.agents[entry.agent_id] = {
184
+ ...current,
185
+ last_by_task: { ...lastByTask, [entry.task_id]: entry },
186
+ pending,
187
+ pending_count: Object.keys(pending).length,
188
+ last: entry,
189
+ updated_at: entry.ts,
190
+ };
191
+ state.updated_at = entry.ts;
192
+ saveReportState(projectRoot, state);
193
+ return state;
194
+ });
183
195
  }
184
196
 
185
197
  function isSummaryHiddenEntry(entry) {
@@ -206,7 +218,11 @@ function getControllerInboxFile(projectRoot, controllerId = "ufoo-agent") {
206
218
  function appendControllerInboxEntry(projectRoot, controllerId, entry) {
207
219
  const file = getControllerInboxFile(projectRoot, controllerId);
208
220
  fs.mkdirSync(path.dirname(file), { recursive: true });
209
- fs.appendFileSync(file, `${JSON.stringify(redactSecrets(entry))}\n`, "utf8");
221
+ return withFileLock(file, () => {
222
+ if (entry.entry_id && parseJsonLines(file).some((row) => row.entry_id === entry.entry_id)) return false;
223
+ fs.appendFileSync(file, `${JSON.stringify(redactSecrets(entry))}\n`, "utf8");
224
+ return true;
225
+ });
210
226
  }
211
227
 
212
228
  function listControllerInboxEntries(projectRoot, controllerId = "ufoo-agent", options = {}) {
@@ -224,75 +240,79 @@ function countControllerInboxEntries(projectRoot, controllerId = "ufoo-agent") {
224
240
 
225
241
  function clearControllerInbox(projectRoot, controllerId = "ufoo-agent") {
226
242
  const file = getControllerInboxFile(projectRoot, controllerId);
227
- try {
228
- if (fs.existsSync(file)) fs.rmSync(file, { force: true });
229
- } catch {
230
- // ignore clear errors
231
- }
243
+ return withFileLock(file, () => {
244
+ try {
245
+ if (fs.existsSync(file)) fs.rmSync(file, { force: true });
246
+ } catch {
247
+ // ignore clear errors
248
+ }
249
+ });
232
250
  }
233
251
 
234
252
  function consumeControllerInboxEntries(projectRoot, controllerId = "ufoo-agent", consumed = []) {
235
253
  const file = getControllerInboxFile(projectRoot, controllerId);
236
- if (!fs.existsSync(file)) return { removed: 0, remaining: 0 };
237
- const list = Array.isArray(consumed) ? consumed : [];
238
- if (list.length === 0) {
239
- const current = parseJsonLines(file);
240
- return { removed: 0, remaining: current.length };
241
- }
242
-
243
- const idSet = new Set();
244
- const legacySerialized = new Set();
245
- for (const item of list) {
246
- if (!item) continue;
247
- if (typeof item === "string") {
248
- idSet.add(item);
249
- continue;
254
+ return withFileLock(file, () => {
255
+ if (!fs.existsSync(file)) return { removed: 0, remaining: 0 };
256
+ const list = Array.isArray(consumed) ? consumed : [];
257
+ if (list.length === 0) {
258
+ const current = parseJsonLines(file);
259
+ return { removed: 0, remaining: current.length };
250
260
  }
251
- if (typeof item === "object") {
252
- if (item.entry_id) {
253
- idSet.add(String(item.entry_id));
254
- } else {
255
- legacySerialized.add(JSON.stringify(item));
261
+
262
+ const idSet = new Set();
263
+ const legacySerialized = new Set();
264
+ for (const item of list) {
265
+ if (!item) continue;
266
+ if (typeof item === "string") {
267
+ idSet.add(item);
268
+ continue;
269
+ }
270
+ if (typeof item === "object") {
271
+ if (item.entry_id) {
272
+ idSet.add(String(item.entry_id));
273
+ } else {
274
+ legacySerialized.add(JSON.stringify(item));
275
+ }
256
276
  }
257
277
  }
258
- }
259
278
 
260
- const raw = fs.readFileSync(file, "utf8");
261
- const lines = raw.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
262
- if (lines.length === 0) {
263
- return { removed: 0, remaining: 0 };
264
- }
265
-
266
- const keptLines = [];
267
- let removed = 0;
268
- for (const line of lines) {
269
- let parsed = null;
270
- try {
271
- parsed = JSON.parse(line);
272
- } catch {
273
- parsed = null;
279
+ const raw = fs.readFileSync(file, "utf8");
280
+ const lines = raw.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
281
+ if (lines.length === 0) {
282
+ return { removed: 0, remaining: 0 };
274
283
  }
275
- if (parsed && typeof parsed === "object") {
276
- const id = parsed.entry_id ? String(parsed.entry_id) : "";
277
- if (id && idSet.has(id)) {
278
- removed += 1;
279
- continue;
284
+
285
+ const keptLines = [];
286
+ let removed = 0;
287
+ for (const line of lines) {
288
+ let parsed = null;
289
+ try {
290
+ parsed = JSON.parse(line);
291
+ } catch {
292
+ parsed = null;
280
293
  }
281
- if (!id && legacySerialized.has(JSON.stringify(parsed))) {
282
- removed += 1;
283
- continue;
294
+ if (parsed && typeof parsed === "object") {
295
+ const id = parsed.entry_id ? String(parsed.entry_id) : "";
296
+ if (id && idSet.has(id)) {
297
+ removed += 1;
298
+ continue;
299
+ }
300
+ if (!id && legacySerialized.has(JSON.stringify(parsed))) {
301
+ removed += 1;
302
+ continue;
303
+ }
284
304
  }
305
+ keptLines.push(line);
285
306
  }
286
- keptLines.push(line);
287
- }
288
307
 
289
- if (keptLines.length === 0) {
290
- fs.rmSync(file, { force: true });
291
- return { removed, remaining: 0 };
292
- }
308
+ if (keptLines.length === 0) {
309
+ fs.rmSync(file, { force: true });
310
+ return { removed, remaining: 0 };
311
+ }
293
312
 
294
- fs.writeFileSync(file, `${keptLines.join("\n")}\n`, "utf8");
295
- return { removed, remaining: keptLines.length };
313
+ writeFileAtomic(file, `${keptLines.join("\n")}\n`);
314
+ return { removed, remaining: keptLines.length };
315
+ });
296
316
  }
297
317
 
298
318
  function readReportSummary(projectRoot) {
@@ -2,6 +2,33 @@ const { getTimestamp, readJSON, writeJSON } = require("../bus/utils");
2
2
  const { appendAgentRegistryDiagnostic, summarizeAgents } = require("./agentRegistryDiagnostics");
3
3
 
4
4
  const AGENTS_SCHEMA_VERSION = 1;
5
+ const { withFileLock } = require("./fileLock");
6
+ const snapshots = new WeakMap();
7
+ const clone = (value) => JSON.parse(JSON.stringify(value));
8
+
9
+ function remember(data) {
10
+ snapshots.set(data, clone(data));
11
+ return data;
12
+ }
13
+
14
+ // Apply only fields changed since this caller's load. Unchanged fields and
15
+ // agents created by another process belong to the latest disk snapshot.
16
+ function applyChanges(current, baseline, next) {
17
+ const result = { ...current };
18
+ for (const key of new Set([...Object.keys(baseline), ...Object.keys(next)])) {
19
+ if (JSON.stringify(baseline[key]) === JSON.stringify(next[key])) continue;
20
+ if (!Object.prototype.hasOwnProperty.call(next, key)) {
21
+ delete result[key];
22
+ } else if (baseline[key] && next[key] && typeof baseline[key] === "object"
23
+ && typeof next[key] === "object" && !Array.isArray(next[key])) {
24
+ // A stale writer must not resurrect a concurrently removed record.
25
+ if (result[key]) result[key] = applyChanges(result[key], baseline[key], next[key]);
26
+ } else {
27
+ result[key] = next[key];
28
+ }
29
+ }
30
+ return result;
31
+ }
5
32
 
6
33
  function toSafeString(value) {
7
34
  return typeof value === "string" ? value : "";
@@ -94,7 +121,7 @@ function loadAgentsData(filePath) {
94
121
  source: "ufoo.agentsStore.loadAgentsData",
95
122
  reason: "missing_or_unreadable_registry",
96
123
  });
97
- return normalizeAgentsData({});
124
+ return remember(normalizeAgentsData({}));
98
125
  }
99
126
  const normalized = normalizeAgentsData(data);
100
127
  const beforeSummary = summarizeAgents(data);
@@ -106,7 +133,7 @@ function loadAgentsData(filePath) {
106
133
  after: afterSummary,
107
134
  });
108
135
  }
109
- return normalized;
136
+ return remember(normalized);
110
137
  }
111
138
 
112
139
  function parseTimestampMs(value) {
@@ -137,18 +164,31 @@ function mergeExternalActivityFields(targetMeta, diskMeta) {
137
164
  if (preferDisk) {
138
165
  targetMeta.activity_state = diskState;
139
166
  targetMeta.activity_since = diskSince;
167
+ if (diskMeta.activity_detail) targetMeta.activity_detail = diskMeta.activity_detail;
168
+ else delete targetMeta.activity_detail;
140
169
  }
141
170
  }
142
171
 
143
172
  function saveAgentsData(filePath, data, options = {}) {
173
+ return withFileLock(filePath, () => saveAgentsDataUnlocked(filePath, data, options));
174
+ }
175
+
176
+ function saveAgentsDataUnlocked(filePath, data, options = {}) {
144
177
  const source = typeof options.source === "string" && options.source
145
178
  ? options.source
146
179
  : "ufoo.agentsStore.saveAgentsData";
147
- const normalized = normalizeAgentsData(data);
180
+ let normalized = normalizeAgentsData(data);
148
181
 
149
182
  // Merge externally-managed fields from disk to avoid daemon in-memory writes
150
183
  // overwriting fresher runner/notifier state updates.
151
184
  const disk = readJSON(filePath, null);
185
+ if (!disk && require("fs").existsSync(filePath)) throw new Error(`Refusing to overwrite unreadable agent registry: ${filePath}`);
186
+ const baseline = snapshots.get(data);
187
+ if (disk) {
188
+ normalized = normalizeAgentsData(baseline
189
+ ? applyChanges(normalizeAgentsData(disk), baseline, normalized)
190
+ : { ...disk, ...normalized, agents: { ...disk.agents, ...normalized.agents } });
191
+ }
152
192
  if (disk && disk.agents && normalized.agents) {
153
193
  const droppedIds = Object.keys(disk.agents)
154
194
  .filter((id) => !Object.prototype.hasOwnProperty.call(normalized.agents, id))
@@ -177,6 +217,19 @@ function saveAgentsData(filePath, data, options = {}) {
177
217
  });
178
218
  }
179
219
  writeJSON(filePath, normalized);
220
+ Object.assign(data, normalized);
221
+ remember(data);
222
+ return normalized;
223
+ }
224
+
225
+ function updateAgentsData(filePath, mutate, options = {}) {
226
+ return withFileLock(filePath, () => {
227
+ const data = loadAgentsData(filePath);
228
+ const result = mutate(data);
229
+ if (result && typeof result.then === "function") throw new Error("Agent mutations must be synchronous");
230
+ if (result !== false) saveAgentsDataUnlocked(filePath, data, options);
231
+ return result;
232
+ });
180
233
  }
181
234
 
182
235
  module.exports = {
@@ -184,4 +237,5 @@ module.exports = {
184
237
  loadAgentsData,
185
238
  saveAgentsData,
186
239
  normalizeAgentsData,
240
+ updateAgentsData,
187
241
  };
@@ -0,0 +1,2 @@
1
+ // Preserve one lock-owner map across shared runtime and coordination stores.
2
+ module.exports = require("../../agents/runtime/context/fileLock");
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { createResourceLease } = require("../../agents/runtime/tasks/resourceLease");
6
+
7
+ function createWorkspaceAccess({ projectRoot, externalWriters = () => [] } = {}) {
8
+ const root = fs.realpathSync(projectRoot);
9
+ const key = (workspaceRoot) => fs.realpathSync(workspaceRoot || root);
10
+ const stores = new Map();
11
+ function storeFor(workspaceRoot) {
12
+ const workspace = key(workspaceRoot);
13
+ if (!stores.has(workspace)) stores.set(workspace, createResourceLease({ file: path.join(workspace, ".ufoo", "agent", "runtime", "workspace-leases.json") }));
14
+ return stores.get(workspace);
15
+ }
16
+ // All hosts accessing the same directory use its lease, including a native
17
+ // ucode opened directly in a linked worktree.
18
+ const leases = Object.freeze(Object.fromEntries(["acquire", "release", "run"].map((method) => [method,
19
+ (args, ...rest) => storeFor(args.key)[method]({ ...args, key: key(args.key) }, ...rest)])));
20
+ return Object.freeze({
21
+ leases,
22
+ async run(context, operation) {
23
+ if (!["write", "edit", "bash"].includes(context.tool)) return operation();
24
+ const workspace = key(context.workspaceRoot);
25
+ const writers = workspace === root ? externalWriters(context) : [];
26
+ if (writers.length) return { ok: false, code: "workspace_busy", error: "external workers own or may write this workspace", owners: writers };
27
+ return leases.run({ key: workspace, ownerId: context.taskRunId || context.sessionId || `process-${process.pid}`, signal: context.signal }, operation);
28
+ },
29
+ async runTask(context, operation) {
30
+ const workspace = key(context.workspaceRoot);
31
+ return leases.run({ key: workspace, ownerId: context.taskRunId, signal: context.signal, wait: true }, operation);
32
+ },
33
+ });
34
+ }
35
+
36
+ module.exports = { createWorkspaceAccess };
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+
3
+ function isInternalAgentMeta(meta = {}) {
4
+ return Boolean(meta) && String(meta.launch_mode || meta.launchMode || "").trim().toLowerCase() === "internal";
5
+ }
6
+
7
+ function isInternalDashboardEvent(data = {}, getMeta = () => null) {
8
+ const agentId = data.event === "activity_state_changed"
9
+ ? data.subscriber || data.publisher
10
+ : data.report?.agent_id || data.publisher;
11
+ if (agentId === "ufoo-agent" || String(agentId || "").endsWith(":ufoo-agent")) {
12
+ return !data.target || data.target === "ufoo-agent" || isInternalAgentMeta(getMeta(data.target));
13
+ }
14
+ return isInternalAgentMeta(getMeta(agentId));
15
+ }
16
+
17
+ module.exports = { isInternalAgentMeta, isInternalDashboardEvent };
@@ -3,6 +3,7 @@
3
3
  const IPC_REQUEST_TYPES = {
4
4
  STATUS: "status",
5
5
  PROMPT: "prompt",
6
+ AGENT_RUNTIME: "agent_runtime",
6
7
  CRON: "cron",
7
8
  BUS_SEND: "bus_send",
8
9
  BUS_WATCH: "bus_watch",
@@ -30,6 +31,8 @@ const IPC_REQUEST_TYPES = {
30
31
  const IPC_RESPONSE_TYPES = {
31
32
  STATUS: "status",
32
33
  RESPONSE: "response",
34
+ RUNTIME_EVENT: "runtime_event",
35
+ RUNTIME_RESULT: "runtime_result",
33
36
  BUS: "bus",
34
37
  ERROR: "error",
35
38
  BUS_SEND_OK: "bus_send_ok",
@@ -45,9 +45,13 @@ const COMMAND_NAMES = Object.freeze([
45
45
  "ui.resync.request",
46
46
  "app.exit",
47
47
  "multi.exit",
48
+ "multi.open",
49
+ "multi.toggle",
48
50
  "multi.focus",
49
51
  "multi.viewport",
50
52
  "multi.raw",
53
+ "multi.scroll",
54
+ "multi.expand",
51
55
  ]);
52
56
 
53
57
  const EVENT_NAMES = Object.freeze([