u-foo 3.1.2 → 3.1.4

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.
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "u-foo",
3
- "version": "3.1.2",
3
+ "version": "3.1.4",
4
4
  "description": "Multi-Agent Workspace Protocol. Just add u. claude → uclaude, codex → ucodex.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://ufoo.dev",
@@ -45,7 +45,7 @@
45
45
  ],
46
46
  "type": "commonjs",
47
47
  "engines": {
48
- "node": ">=18"
48
+ "node": ">=18.17"
49
49
  },
50
50
  "scripts": {
51
51
  "postinstall": "node scripts/postinstall.js",
@@ -65,6 +65,7 @@
65
65
  "commander": "^13.1.0",
66
66
  "gray-matter": "^4.0.3",
67
67
  "node-pty": "^1.1.0",
68
+ "undici": "^6.28.0",
68
69
  "ws": "^8.19.0"
69
70
  },
70
71
  "devDependencies": {
@@ -1,5 +1,6 @@
1
1
  const os = require("os");
2
2
  const { randomUUID } = require("crypto");
3
+ const { Agent: UndiciAgent } = require("undici");
3
4
  const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../config");
4
5
  const {
5
6
  readKimiAccessToken,
@@ -18,6 +19,7 @@ const {
18
19
  sanitizeModelMessages,
19
20
  } = require("./context/assembler");
20
21
  const { systemBlocksToAnthropicPayload } = require("./context/promptLayers");
22
+ const { retireMessageImages } = require("./providers/visionBlocks");
21
23
  const { parseStructuredSideEffects } = require("./context/stateCommit");
22
24
  const {
23
25
  emptyExecutionState,
@@ -115,6 +117,14 @@ const DEFAULT_MAX_NATIVE_TOOL_CALLS = 100;
115
117
  const DEFAULT_MAX_NATIVE_TOOL_ERRORS = 20;
116
118
  const MAX_EMPTY_TERMINAL_RETRIES = 2;
117
119
  const DEFAULT_NATIVE_TIMEOUT_MS = 43200000; // 12 hours
120
+ // Node's fetch is backed by Undici, whose default headers/body idle timeout is
121
+ // 300 seconds. Reasoning providers can legitimately stay silent longer than
122
+ // that between SSE chunks, so leave the absolute deadline to our existing
123
+ // AbortController instead of inheriting Undici's shorter hidden deadline.
124
+ const NATIVE_SSE_DISPATCHER_OPTIONS = Object.freeze({
125
+ headersTimeout: 0,
126
+ bodyTimeout: 0,
127
+ });
118
128
  /** Max text-only auto-continues while a plan is waiting on a task (per user submit). */
119
129
  const DEFAULT_MAX_PLAN_AUTO_CONTINUES = 24;
120
130
  // Anthropic Messages rejects max_tokens above the model's real cap (64K on
@@ -141,6 +151,40 @@ function normalizeTimeoutMs(value) {
141
151
  return Math.max(1000, Math.floor(parsed));
142
152
  }
143
153
 
154
+ let nativeSseDispatcher = null;
155
+
156
+ function createNativeSseDispatcher() {
157
+ return new UndiciAgent({ ...NATIVE_SSE_DISPATCHER_OPTIONS });
158
+ }
159
+
160
+ function getNativeSseDispatcher() {
161
+ if (!nativeSseDispatcher || nativeSseDispatcher.destroyed) {
162
+ nativeSseDispatcher = createNativeSseDispatcher();
163
+ }
164
+ return nativeSseDispatcher;
165
+ }
166
+
167
+ function enrichProviderTransportError(err) {
168
+ if (!err || typeof err !== "object") return err;
169
+
170
+ const cause = err.cause && typeof err.cause === "object" ? err.cause : null;
171
+ const code = String((cause && cause.code) || err.code || "").trim();
172
+ const causeMessage = String((cause && cause.message) || "").trim();
173
+ if (!code && !causeMessage) return err;
174
+
175
+ const message = String(err.message || "provider transport failed").trim();
176
+ const details = [code, causeMessage]
177
+ .filter(Boolean)
178
+ .filter((value, index, values) => values.indexOf(value) === index)
179
+ .join(": ");
180
+ if (!details || message.includes(details)) return err;
181
+
182
+ const enriched = new Error(`${message} (${details})`);
183
+ enriched.code = code || err.code;
184
+ enriched.cause = err;
185
+ return enriched;
186
+ }
187
+
144
188
  function normalizePositiveInt(value, fallback) {
145
189
  const parsed = Number.parseInt(String(value || ""), 10);
146
190
  if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
@@ -1216,6 +1260,7 @@ async function runSseRequest({
1216
1260
  headers,
1217
1261
  body: JSON.stringify(payload),
1218
1262
  signal: request.signal,
1263
+ dispatcher: getNativeSseDispatcher(),
1219
1264
  });
1220
1265
 
1221
1266
  if (!response.ok) {
@@ -1275,7 +1320,7 @@ async function runSseRequest({
1275
1320
  cancelError.code = "cancelled";
1276
1321
  throw cancelError;
1277
1322
  }
1278
- throw err;
1323
+ throw enrichProviderTransportError(err);
1279
1324
  } finally {
1280
1325
  request.cleanup();
1281
1326
  }
@@ -2324,6 +2369,12 @@ async function runNativeLoop({
2324
2369
  },
2325
2370
  });
2326
2371
 
2372
+ // Images belong to the request that just completed, not subsequent tool
2373
+ // iterations. Run only after success so failed requests retain their images.
2374
+ // TaskFocus may already have mirrored these blocks into the main transcript.
2375
+ retireMessageImages(providerMessages);
2376
+ if (providerMessages !== messages) retireMessageImages(messages);
2377
+
2327
2378
  usage.turns += 1;
2328
2379
  addUsageTotals(usage, turnResult && turnResult.usage);
2329
2380
  emitContextUsage(turnResult && turnResult.usage);
@@ -2847,6 +2898,7 @@ module.exports = {
2847
2898
  resolveTransport,
2848
2899
  resolveThinkingBudgetTokens,
2849
2900
  resolveReasoningEffort,
2901
+ createNativeSseDispatcher,
2850
2902
  buildCoreToolSpecs,
2851
2903
  buildAnthropicToolSpecs,
2852
2904
  };
@@ -99,6 +99,46 @@ function degradeVisionContent(content) {
99
99
  return texts.filter(Boolean).join("\n") || "[multimodal content]";
100
100
  }
101
101
 
102
+ // Retire only visual blocks after a successful model call. In particular,
103
+ // preserve Anthropic tool_result envelopes and their tool_use_id linkage.
104
+ function retireVisionContent(content) {
105
+ if (!Array.isArray(content)) return content;
106
+ let changed = false;
107
+ const retired = content.map((block) => {
108
+ if (!block || typeof block !== "object") return block;
109
+ const type = String(block.type || "").toLowerCase();
110
+ if (type === "image" || type === "image_url" || type === "input_image") {
111
+ changed = true;
112
+ const pathHint = block.path || (block.source && block.source.path) || "";
113
+ return {
114
+ type: "text",
115
+ text: pathHint
116
+ ? `[image already viewed: ${pathHint}; use read_image to view again]`
117
+ : "[image already viewed; use read_image with the recorded path to view again]",
118
+ };
119
+ }
120
+ if (Array.isArray(block.content)) {
121
+ const nested = retireVisionContent(block.content);
122
+ if (nested !== block.content) {
123
+ changed = true;
124
+ return { ...block, content: nested };
125
+ }
126
+ }
127
+ return block;
128
+ });
129
+ return changed ? retired : content;
130
+ }
131
+
132
+ function retireMessageImages(messages = []) {
133
+ for (let i = 0; i < messages.length; i += 1) {
134
+ const message = messages[i];
135
+ if (message && Array.isArray(message.content)) {
136
+ const content = retireVisionContent(message.content);
137
+ if (content !== message.content) messages[i] = { ...message, content };
138
+ }
139
+ }
140
+ }
141
+
102
142
  module.exports = {
103
143
  extractVisionPayload,
104
144
  isVisionToolResult,
@@ -107,4 +147,5 @@ module.exports = {
107
147
  toAnthropicImageBlock,
108
148
  toOpenAiImagePart,
109
149
  degradeVisionContent,
150
+ retireMessageImages,
110
151
  };
@@ -610,11 +610,11 @@ class EventBus {
610
610
  /**
611
611
  * 智能路由
612
612
  */
613
- async resolve(myId, targetType) {
613
+ async resolve(myId, target) {
614
614
  this.ensureBus();
615
615
  this.loadBusData();
616
616
 
617
- const result = await this.messageManager.resolve(myId, targetType);
617
+ const result = await this.messageManager.resolve(myId, target);
618
618
 
619
619
  if (result.single) {
620
620
  console.log(result.single);
@@ -622,11 +622,11 @@ class EventBus {
622
622
  }
623
623
 
624
624
  if (result.candidates.length === 0) {
625
- logError(`No ${targetType} agents found`);
625
+ logError(`No agents found for target "${target}"`);
626
626
  return null;
627
627
  }
628
628
 
629
- console.log(`Multiple ${targetType} agents found:`);
629
+ console.log(`Multiple agents found for target "${target}":`);
630
630
  for (const candidate of result.candidates) {
631
631
  const nickname = candidate.nickname ? ` (${candidate.nickname})` : "";
632
632
  console.log(` ${candidate.id}${nickname}`);
@@ -578,18 +578,12 @@ class MessageManager {
578
578
  /**
579
579
  * 智能路由解析(找出所有匹配的候选者)
580
580
  */
581
- async resolve(myId, targetType) {
582
- const normalizedTargetType = normalizeAgentTypeAlias(targetType);
581
+ async resolve(myId, target) {
583
582
  const subscribers = this.busData.agents || {};
584
- const candidates = Object.entries(subscribers)
585
- .filter(([id, meta]) => {
586
- if (id === myId) return false; // 排除自己
587
- if (meta.status !== "active") return false;
588
-
589
- if (normalizeAgentTypeAlias(meta.agent_type) === normalizedTargetType) return true;
590
-
591
- return false;
592
- })
583
+ const candidates = this.resolveTarget(target)
584
+ .filter((id) => id !== myId)
585
+ .map((id) => [id, subscribers[id]])
586
+ .filter(([, meta]) => meta && meta.status === "active")
593
587
  .map(([id, meta]) => {
594
588
  const nickname = meta.nickname || meta.scoped_nickname;
595
589
  return {
@@ -164,6 +164,14 @@ function notifyDaemonRefresh(projectRoot) {
164
164
  }
165
165
  }
166
166
 
167
+ function notifyDaemonRefreshIfEnabled(projectRoot, options = {}) {
168
+ if (options.notifyDaemon === false) return;
169
+ const notify = typeof options.notifyDaemonRefresh === "function"
170
+ ? options.notifyDaemonRefresh
171
+ : notifyDaemonRefresh;
172
+ notify(projectRoot);
173
+ }
174
+
167
175
  async function registerAgentFull(projectRoot, args = {}, options = {}) {
168
176
  const {
169
177
  validateParentPid = false,
@@ -319,7 +327,7 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
319
327
  }
320
328
  }
321
329
  bus.saveBusData();
322
- notifyDaemonRefresh(projectRoot);
330
+ notifyDaemonRefreshIfEnabled(projectRoot, options);
323
331
  return {
324
332
  ok: true,
325
333
  project_root: projectRoot,
@@ -342,7 +350,7 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
342
350
  };
343
351
  }
344
352
 
345
- async function registerAgent(projectRoot, args = {}) {
353
+ async function registerAgent(projectRoot, args = {}, options = {}) {
346
354
  if (!String(args.agent_type || args.agentType || "").trim()) {
347
355
  const err = new Error("register_agent requires agent_type for canonical identity allocation");
348
356
  err.code = "external_agent_type_required";
@@ -358,10 +366,12 @@ async function registerAgent(projectRoot, args = {}) {
358
366
  return registerAgentFull(projectRoot, args, {
359
367
  validateParentPid: false,
360
368
  checkNicknameConflicts: false,
369
+ notifyDaemon: options.notifyDaemon,
370
+ notifyDaemonRefresh: options.notifyDaemonRefresh,
361
371
  });
362
372
  }
363
373
 
364
- async function heartbeatAgent(projectRoot, args = {}) {
374
+ async function heartbeatAgent(projectRoot, args = {}, options = {}) {
365
375
  const subscriber = resolveSubscriberArg(args);
366
376
  const bus = ensureBusLoaded(projectRoot);
367
377
  const meta = assertAgentHandle(bus, subscriber, args);
@@ -369,7 +379,7 @@ async function heartbeatAgent(projectRoot, args = {}) {
369
379
  meta.status = "active";
370
380
  const leaseExpiresAt = extendMcpAgentLease(meta);
371
381
  bus.saveBusData();
372
- notifyDaemonRefresh(projectRoot);
382
+ notifyDaemonRefreshIfEnabled(projectRoot, options);
373
383
  return {
374
384
  ok: true,
375
385
  project_root: projectRoot,
@@ -379,7 +389,7 @@ async function heartbeatAgent(projectRoot, args = {}) {
379
389
  };
380
390
  }
381
391
 
382
- async function publishActivityState(projectRoot, args = {}) {
392
+ async function publishActivityState(projectRoot, args = {}, options = {}) {
383
393
  const subscriber = resolveSubscriberArg(args);
384
394
  const activityState = String(args.activity_state || args.activityState || "").trim();
385
395
  if (!activityState) {
@@ -395,7 +405,7 @@ async function publishActivityState(projectRoot, args = {}) {
395
405
  meta.activity_detail = String(args.detail || "").trim();
396
406
  meta.activity_since = String(args.since || "").trim() || nowIso();
397
407
  bus.saveBusData();
398
- notifyDaemonRefresh(projectRoot);
408
+ notifyDaemonRefreshIfEnabled(projectRoot, options);
399
409
  return {
400
410
  ok: true,
401
411
  project_root: projectRoot,
@@ -406,7 +416,7 @@ async function publishActivityState(projectRoot, args = {}) {
406
416
  };
407
417
  }
408
418
 
409
- async function updateAgentMetadata(projectRoot, args = {}) {
419
+ async function updateAgentMetadata(projectRoot, args = {}, options = {}) {
410
420
  assertServerOwnedExternalIdentity(args, [
411
421
  "nickname",
412
422
  "scoped_nickname",
@@ -424,7 +434,7 @@ async function updateAgentMetadata(projectRoot, args = {}) {
424
434
  }
425
435
  bus.subscriberManager.updateLastSeen(subscriber);
426
436
  bus.saveBusData();
427
- notifyDaemonRefresh(projectRoot);
437
+ notifyDaemonRefreshIfEnabled(projectRoot, options);
428
438
  const nextMeta = bus.subscriberManager.getSubscriber(subscriber) || meta;
429
439
  return {
430
440
  ok: true,
@@ -655,7 +665,7 @@ async function reportAgentStatus(projectRoot, args = {}) {
655
665
  };
656
666
  }
657
667
 
658
- async function unregisterAgent(projectRoot, args = {}) {
668
+ async function unregisterAgent(projectRoot, args = {}, options = {}) {
659
669
  const subscriber = resolveSubscriberArg(args);
660
670
  const bus = ensureBusLoaded(projectRoot);
661
671
  const meta = assertAgentHandle(bus, subscriber, args, {
@@ -666,7 +676,7 @@ async function unregisterAgent(projectRoot, args = {}) {
666
676
  meta.mcp_lease_expires_at = meta.mcp_revoked_at;
667
677
  const ok = await bus.subscriberManager.leave(subscriber);
668
678
  bus.saveBusData();
669
- notifyDaemonRefresh(projectRoot);
679
+ notifyDaemonRefreshIfEnabled(projectRoot, options);
670
680
  return {
671
681
  ok,
672
682
  project_root: projectRoot,
@@ -684,6 +694,7 @@ module.exports = {
684
694
  assertAgentHandle,
685
695
  extendMcpAgentLease,
686
696
  notifyDaemonRefresh,
697
+ notifyDaemonRefreshIfEnabled,
687
698
  registerAgentFull,
688
699
  registerAgent,
689
700
  heartbeatAgent,
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { randomUUID } = require("crypto");
4
4
  const fs = require("fs");
5
+ const path = require("path");
5
6
 
6
7
  const {
7
8
  defaultAgentModelForProvider,
@@ -15,9 +16,12 @@ const {
15
16
  } = require("../../coordination/state/agentsStore");
16
17
  const {
17
18
  canonicalProjectRoot,
19
+ isGlobalControllerProjectRoot,
20
+ listProjectRuntimes,
18
21
  markProjectStopped,
19
22
  resolveGlobalControllerProjectRoot,
20
23
  } = require("../projects");
24
+ const { isAgentPidAlive } = require("../../coordination/bus/utils");
21
25
  const { startDaemon } = require("./index");
22
26
  const { createProjectRuntime } = require("./projectRuntime");
23
27
  const { ProjectRuntimeManager } = require("./projectRuntimeManager");
@@ -27,6 +31,51 @@ const {
27
31
  executeProjectRuntimeOperation,
28
32
  } = require("./projectRuntimeGateway");
29
33
 
34
+ const MAX_REHYDRATION_SKIP_SAMPLES = 25;
35
+
36
+ function isSocketFile(filePath = "") {
37
+ if (!filePath) return false;
38
+ try {
39
+ return fs.statSync(filePath).isSocket();
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+
45
+ function hasPersistedCronTasks(projectRoot) {
46
+ const cronFile = path.join(getUfooPaths(projectRoot).runDir, "cron.tasks.json");
47
+ try {
48
+ const state = JSON.parse(fs.readFileSync(cronFile, "utf8"));
49
+ return Array.isArray(state.tasks) && state.tasks.length > 0;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+
55
+ function projectRuntimeRecoveryReasons(projectRoot, options = {}) {
56
+ const paths = getUfooPaths(projectRoot);
57
+ if (!fs.existsSync(paths.ufooDir)) return [];
58
+ const loadAgents = options.loadAgentsData || loadAgentsData;
59
+ const agentPidIsAlive = options.isAgentPidAlive || isAgentPidAlive;
60
+ const socketIsLive = options.isSocketFile || isSocketFile;
61
+ const reasons = [];
62
+ const data = fs.existsSync(paths.agentsFile)
63
+ ? loadAgents(paths.agentsFile)
64
+ : { agents: {} };
65
+ const hasLiveHostAgent = Object.entries(data.agents || {}).some(([subscriber, meta]) => {
66
+ if (!meta || meta.status !== "active" || meta.mcp_bridge === true) return false;
67
+ if (subscriber === "ufoo-agent" || meta.agent_type === "ufoo-agent") return false;
68
+ const pid = Number.parseInt(meta.pid, 10);
69
+ return agentPidIsAlive(pid) || socketIsLive(meta.host_inject_sock);
70
+ });
71
+ if (hasLiveHostAgent) reasons.push("live_host_agent");
72
+ const hasCronTasks = typeof options.hasPersistedCronTasks === "function"
73
+ ? options.hasPersistedCronTasks(projectRoot)
74
+ : hasPersistedCronTasks(projectRoot);
75
+ if (hasCronTasks) reasons.push("scheduled_task");
76
+ return reasons;
77
+ }
78
+
30
79
  class GlobalDaemon {
31
80
  constructor(options = {}) {
32
81
  this.controllerRoot = canonicalProjectRoot(
@@ -38,6 +87,12 @@ class GlobalDaemon {
38
87
  this.authorizeProjectRoot = typeof options.authorizeProjectRoot === "function"
39
88
  ? options.authorizeProjectRoot
40
89
  : (projectRoot) => fs.existsSync(getUfooPaths(projectRoot).ufooDir);
90
+ this.listProjectRuntimes = options.listProjectRuntimes || listProjectRuntimes;
91
+ this.projectRuntimeRecoveryReasons = options.projectRuntimeRecoveryReasons
92
+ || ((projectRoot) => projectRuntimeRecoveryReasons(projectRoot));
93
+ this.rehydrateProjects = options.rehydrateProjects === undefined
94
+ ? isGlobalControllerProjectRoot(this.controllerRoot)
95
+ : options.rehydrateProjects === true;
41
96
  this.controller = null;
42
97
  this.runtimeManager = options.runtimeManager || new ProjectRuntimeManager({
43
98
  authorizeProjectRoot: this.authorizeProjectRoot,
@@ -56,13 +111,24 @@ class GlobalDaemon {
56
111
  const projectRoot = this.activeGatewayRequests.get(id);
57
112
  return projectRoot ? this.runtimeManager.cancel(projectRoot, id) : false;
58
113
  },
59
- status: () => this.runtimeManager.status(),
114
+ status: () => ({
115
+ ...this.runtimeManager.status(),
116
+ rehydration: this.rehydration,
117
+ }),
60
118
  // GlobalDaemon owns the shared manager; MCP listener restart/cleanup
61
119
  // must not independently dispose project runtimes.
62
120
  dispose: () => {},
63
121
  };
64
122
  this.disposed = false;
65
123
  this.startedAt = "";
124
+ this.rehydration = {
125
+ state: this.rehydrateProjects ? "pending" : "disabled",
126
+ restored: [],
127
+ skipped: [],
128
+ skipped_count: 0,
129
+ failed: [],
130
+ };
131
+ this.rehydrationPromise = Promise.resolve(this.rehydration);
66
132
  }
67
133
 
68
134
  createHostedRuntime(context) {
@@ -175,6 +241,79 @@ class GlobalDaemon {
175
241
  return runtime.hostHandle;
176
242
  }
177
243
 
244
+ async restoreRegisteredProjectRuntimes() {
245
+ const startedAt = new Date().toISOString();
246
+ const restored = [];
247
+ const skipped = [];
248
+ let skippedCount = 0;
249
+ const failed = [];
250
+ const recordSkip = (entry) => {
251
+ skippedCount += 1;
252
+ if (skipped.length < MAX_REHYDRATION_SKIP_SAMPLES) skipped.push(entry);
253
+ };
254
+ this.rehydration = {
255
+ state: "running",
256
+ started_at: startedAt,
257
+ restored,
258
+ skipped,
259
+ skipped_count: skippedCount,
260
+ failed,
261
+ };
262
+ const rows = this.listProjectRuntimes({ validate: false, cleanupTmp: true });
263
+ const seen = new Set();
264
+ for (const row of rows) {
265
+ if (this.disposed) break;
266
+ const rawRoot = row && row.project_root;
267
+ if (!rawRoot) continue;
268
+ let projectRoot;
269
+ try {
270
+ projectRoot = canonicalProjectRoot(rawRoot);
271
+ } catch {
272
+ recordSkip({ project_root: String(rawRoot), reason: "missing_project_root" });
273
+ continue;
274
+ }
275
+ if (projectRoot === this.controllerRoot || seen.has(projectRoot)) continue;
276
+ seen.add(projectRoot);
277
+ let reasons;
278
+ try {
279
+ reasons = this.projectRuntimeRecoveryReasons(projectRoot);
280
+ } catch (err) {
281
+ failed.push({
282
+ project_root: projectRoot,
283
+ error: err && err.message ? err.message : String(err),
284
+ });
285
+ continue;
286
+ }
287
+ if (!Array.isArray(reasons) || reasons.length === 0) {
288
+ recordSkip({ project_root: projectRoot, reason: "no_live_runtime_owner" });
289
+ continue;
290
+ }
291
+ try {
292
+ // Preserve ordering and the manager's active-runtime bound rather than
293
+ // stampeding every registered project after a controller restart.
294
+ // eslint-disable-next-line no-await-in-loop
295
+ await this.activateProject(projectRoot);
296
+ restored.push({ project_root: projectRoot, reasons: reasons.slice() });
297
+ } catch (err) {
298
+ failed.push({
299
+ project_root: projectRoot,
300
+ reasons: reasons.slice(),
301
+ error: err && err.message ? err.message : String(err),
302
+ });
303
+ }
304
+ }
305
+ this.rehydration = {
306
+ state: failed.length > 0 ? "degraded" : "complete",
307
+ started_at: startedAt,
308
+ completed_at: new Date().toISOString(),
309
+ restored,
310
+ skipped,
311
+ skipped_count: skippedCount,
312
+ failed,
313
+ };
314
+ return this.rehydration;
315
+ }
316
+
178
317
  async handleRequest(projectRoot, request, socket) {
179
318
  const canonicalRoot = this.resolveProjectRoot(projectRoot);
180
319
  const config = this.loadProjectConfig(canonicalRoot);
@@ -347,6 +486,23 @@ class GlobalDaemon {
347
486
  beforeCleanup: () => this.disposeProjectRuntimes("global-controller-cleanup"),
348
487
  });
349
488
  this.startedAt = new Date().toISOString();
489
+ if (this.rehydrateProjects) {
490
+ this.rehydrationPromise = this.restoreRegisteredProjectRuntimes().catch((err) => {
491
+ this.rehydration = {
492
+ state: "failed",
493
+ started_at: this.rehydration.started_at || new Date().toISOString(),
494
+ completed_at: new Date().toISOString(),
495
+ restored: this.rehydration.restored || [],
496
+ skipped: this.rehydration.skipped || [],
497
+ skipped_count: this.rehydration.skipped_count || 0,
498
+ failed: [{
499
+ project_root: "",
500
+ error: err && err.message ? err.message : String(err),
501
+ }],
502
+ };
503
+ return this.rehydration;
504
+ });
505
+ }
350
506
  return this;
351
507
  }
352
508
 
@@ -378,6 +534,7 @@ class GlobalDaemon {
378
534
  active_runtime_count: manager.active_runtime_count,
379
535
  active_request_count: manager.active_request_count,
380
536
  activating_runtime_count: this.runtimeManager.activationPromises.size,
537
+ rehydration: this.rehydration,
381
538
  runtimes: manager.runtimes,
382
539
  };
383
540
  }
@@ -390,5 +547,7 @@ function startGlobalDaemon(options = {}) {
390
547
 
391
548
  module.exports = {
392
549
  GlobalDaemon,
550
+ hasPersistedCronTasks,
551
+ projectRuntimeRecoveryReasons,
393
552
  startGlobalDaemon,
394
553
  };
@@ -865,7 +865,15 @@ async function dispatchMessages(projectRoot, dispatch = []) {
865
865
  }
866
866
  }
867
867
 
868
- function startBusBridge(projectRoot, provider, onEvent, onStatus, shouldDrain, onReport) {
868
+ function startBusBridge(
869
+ projectRoot,
870
+ provider,
871
+ onEvent,
872
+ onStatus,
873
+ shouldDrain,
874
+ onReport,
875
+ options = {}
876
+ ) {
869
877
  const state = {
870
878
  subscriber: null,
871
879
  queueFile: null,
@@ -875,8 +883,13 @@ function startBusBridge(projectRoot, provider, onEvent, onStatus, shouldDrain, o
875
883
  emittedEventKeys: [],
876
884
  emittedEventKeySet: new Set(),
877
885
  };
878
- const eventBus = new EventBus(projectRoot);
879
- let joinInProgress = false;
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;
880
893
  let polling = false;
881
894
 
882
895
  function getAgentNickname(agentId) {
@@ -1041,31 +1054,38 @@ function startBusBridge(projectRoot, provider, onEvent, onStatus, shouldDrain, o
1041
1054
  state.lastEventSeq = Math.max(state.lastEventSeq, maxSeq);
1042
1055
  }
1043
1056
 
1044
- function ensureSubscriber() {
1045
- if (state.subscriber || joinInProgress) return;
1046
- const debugFile = path.join(getUfooPaths(projectRoot).runDir, "bus-join-debug.txt");
1047
- joinInProgress = true;
1048
- (async () => {
1057
+ async function ensureSubscriber() {
1058
+ if (stopped || state.subscriber) return state.subscriber;
1059
+ if (joinInProgress) return joinInProgress;
1060
+ joinInProgress = (async () => {
1049
1061
  try {
1050
- fs.writeFileSync(debugFile, `Attempting join at ${new Date().toISOString()}\n`, { flag: "a" });
1051
1062
  // Determine agent type based on provider configuration
1052
1063
  const agentType = provider === "codex-cli" ? "codex" : (provider === "ucode" ? "ufoo-code" : "claude-code");
1053
1064
  // Use fixed ID "ufoo-agent" for daemon's bus identity with explicit nickname
1054
1065
  const sub = await eventBus.join("ufoo-agent", agentType, "ufoo-agent");
1055
- if (!sub) {
1056
- fs.writeFileSync(debugFile, "Join returned empty subscriber\n", { flag: "a" });
1057
- return;
1058
- }
1066
+ if (!sub || stopped) return null;
1059
1067
  state.subscriber = sub;
1060
1068
  const safe = subscriberToSafeName(sub);
1061
1069
  state.queueFile = path.join(getUfooPaths(projectRoot).busQueuesDir, safe, "pending.jsonl");
1062
- fs.writeFileSync(debugFile, `Successfully joined as ${sub} (type: ${agentType})\n`, { flag: "a" });
1070
+ lastJoinError = "";
1071
+ return sub;
1063
1072
  } catch (err) {
1064
- fs.writeFileSync(debugFile, `Exception: ${err.message || err}\n`, { flag: "a" });
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;
1065
1084
  } finally {
1066
- joinInProgress = false;
1085
+ joinInProgress = null;
1067
1086
  }
1068
1087
  })();
1088
+ return joinInProgress;
1069
1089
  }
1070
1090
 
1071
1091
  async function handleReportControlEvent(evt) {
@@ -1122,7 +1142,7 @@ function startBusBridge(projectRoot, provider, onEvent, onStatus, shouldDrain, o
1122
1142
  if (polling) return;
1123
1143
  polling = true;
1124
1144
  try {
1125
- ensureSubscriber();
1145
+ await ensureSubscriber();
1126
1146
  await pollReportControlQueue();
1127
1147
  if (typeof shouldDrain === "function" && !shouldDrain()) return;
1128
1148
  pollQueue();
@@ -1145,13 +1165,12 @@ function startBusBridge(projectRoot, provider, onEvent, onStatus, shouldDrain, o
1145
1165
  }
1146
1166
  },
1147
1167
  getSubscriber() {
1148
- ensureSubscriber();
1149
- try {
1150
- fs.writeFileSync(path.join(getUfooPaths(projectRoot).runDir, "bridge-debug.txt"),
1151
- `subscriber: ${state.subscriber || "NULL"}\nqueue: ${state.queueFile || "NULL"}\n`);
1152
- } catch {}
1168
+ void ensureSubscriber();
1153
1169
  return state.subscriber;
1154
1170
  },
1171
+ refresh() {
1172
+ return poll();
1173
+ },
1155
1174
  watchAgent(agentId, enabled = true) {
1156
1175
  if (!agentId) return;
1157
1176
  if (enabled) {
@@ -1165,6 +1184,7 @@ function startBusBridge(projectRoot, provider, onEvent, onStatus, shouldDrain, o
1165
1184
  }
1166
1185
  },
1167
1186
  stop() {
1187
+ stopped = true;
1168
1188
  clearInterval(interval);
1169
1189
  },
1170
1190
  };
@@ -1418,6 +1438,10 @@ function startDaemon({
1418
1438
  } catch (err) {
1419
1439
  log(`report bus event failed request=${meta.requestId || ""} error=${err.message || String(err)}`);
1420
1440
  }
1441
+ }, {
1442
+ onJoinError: (err) => {
1443
+ log(`bus bridge join deferred: ${err && err.message ? err.message : String(err)}`);
1444
+ },
1421
1445
  });
1422
1446
  projectRuntime.own("busBridge", busBridge);
1423
1447
  const deliveryScheduler = new DeliveryScheduler(projectRoot, {
@@ -2968,6 +2992,7 @@ function stopDaemon(projectRoot, options = {}) {
2968
2992
 
2969
2993
  module.exports = {
2970
2994
  startDaemon,
2995
+ startBusBridge,
2971
2996
  stopDaemon,
2972
2997
  isRunning,
2973
2998
  cleanupStaleState,
@@ -36,7 +36,6 @@ const PACKAGE_ROOT = path.resolve(__dirname, "..", "..", "..");
36
36
  const PACKAGE_JSON = require(path.join(PACKAGE_ROOT, "package.json"));
37
37
 
38
38
  const EXPOSED_SHARED_TOOLS = MCP_EXPOSED_SHARED_TOOLS;
39
- const DEFAULT_PROJECT_RUNTIME_GATEWAY = createLocalProjectRuntimeGateway();
40
39
 
41
40
  const CUSTOM_TOOL_DEFINITIONS = Object.freeze([
42
41
  {
@@ -552,15 +551,22 @@ async function invokeTool(name, args = {}, ctx = {}) {
552
551
 
553
552
  class UfooMcpServer {
554
553
  constructor(options = {}) {
554
+ const autoStart = options.autoStart !== false;
555
555
  this.options = {
556
- autoStart: options.autoStart !== false,
556
+ autoStart,
557
557
  validateProjectRoot: options.validateProjectRoot !== false,
558
558
  startTimeoutMs: options.startTimeoutMs,
559
559
  waitPollIntervalMs: options.waitPollIntervalMs,
560
560
  waitHeartbeatIntervalMs: options.waitHeartbeatIntervalMs,
561
561
  waitNow: options.waitNow,
562
562
  waitSleep: options.waitSleep,
563
- projectRuntimeGateway: options.projectRuntimeGateway || DEFAULT_PROJECT_RUNTIME_GATEWAY,
563
+ projectRuntimeGateway: options.projectRuntimeGateway || createLocalProjectRuntimeGateway({
564
+ // An explicitly embedded/no-autostart server (notably unit and
565
+ // integration harnesses) must never wake the user's live daemon for a
566
+ // temporary project. The production stdio bridge uses the global HTTP
567
+ // server and does not rely on this local gateway.
568
+ notifyDaemonRefresh: autoStart,
569
+ }),
564
570
  };
565
571
  this.initialized = false;
566
572
  this.startup = null;
@@ -53,13 +53,20 @@ function unsupportedOperationError(operation = "") {
53
53
  return err;
54
54
  }
55
55
 
56
- function createControlPlaneHandlers(service = null) {
56
+ function createControlPlaneHandlers(service = null, options = {}) {
57
57
  const resolvedService = service || require("./controlPlaneService");
58
+ const notificationOptions = {
59
+ notifyDaemon: options.notifyDaemonRefresh !== false,
60
+ };
58
61
  return {
59
- register_agent: (projectRoot, args) => resolvedService.registerAgent(projectRoot, args),
60
- heartbeat_agent: (projectRoot, args) => resolvedService.heartbeatAgent(projectRoot, args),
61
- publish_activity_state: (projectRoot, args) => resolvedService.publishActivityState(projectRoot, args),
62
- update_agent_metadata: (projectRoot, args) => resolvedService.updateAgentMetadata(projectRoot, args),
62
+ register_agent: (projectRoot, args) =>
63
+ resolvedService.registerAgent(projectRoot, args, notificationOptions),
64
+ heartbeat_agent: (projectRoot, args) =>
65
+ resolvedService.heartbeatAgent(projectRoot, args, notificationOptions),
66
+ publish_activity_state: (projectRoot, args) =>
67
+ resolvedService.publishActivityState(projectRoot, args, notificationOptions),
68
+ update_agent_metadata: (projectRoot, args) =>
69
+ resolvedService.updateAgentMetadata(projectRoot, args, notificationOptions),
63
70
  poll_inbox: (projectRoot, args) => resolvedService.pollInbox(projectRoot, args),
64
71
  wait_for_message: (projectRoot, args, context) => resolvedService.waitForMessage(projectRoot, args, {
65
72
  signal: context.signal,
@@ -69,7 +76,8 @@ function createControlPlaneHandlers(service = null) {
69
76
  sleep: context.waitSleep,
70
77
  }),
71
78
  report_agent_status: (projectRoot, args) => resolvedService.reportAgentStatus(projectRoot, args),
72
- unregister_agent: (projectRoot, args) => resolvedService.unregisterAgent(projectRoot, args),
79
+ unregister_agent: (projectRoot, args) =>
80
+ resolvedService.unregisterAgent(projectRoot, args, notificationOptions),
73
81
  };
74
82
  }
75
83
 
@@ -82,7 +90,7 @@ async function executeProjectRuntimeOperation(
82
90
  ) {
83
91
  const name = String(operation || "").trim();
84
92
  const handlers = options.controlPlaneHandlers
85
- || createControlPlaneHandlers(options.controlPlaneService);
93
+ || createControlPlaneHandlers(options.controlPlaneService, options);
86
94
  const customHandler = handlers[name];
87
95
  if (customHandler) {
88
96
  return customHandler(projectRoot, args, context);
@@ -126,7 +134,13 @@ function assertExternalAgentHandle(bus, subscriber, args = {}, options = {}) {
126
134
 
127
135
  class LocalProjectRuntimeGateway {
128
136
  constructor(options = {}) {
129
- this.options = options;
137
+ this.options = {
138
+ // A local gateway is an in-process ownership boundary. It must not
139
+ // signal or activate a separate user daemon unless the caller opts in
140
+ // explicitly (the production global bridge uses a managed gateway).
141
+ notifyDaemonRefresh: false,
142
+ ...options,
143
+ };
130
144
  }
131
145
 
132
146
  call(projectRoot, operation, args = {}, context = {}) {