u-foo 3.1.1 → 3.1.3

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.
package/README.md CHANGED
@@ -269,6 +269,19 @@ and `agent_handle`. Include the handle in heartbeat, activity, send, receive,
269
269
  acknowledgement, report, and unregister calls. The handle is an ownership
270
270
  capability: do not send it to peers or print it in reports.
271
271
 
272
+ For a new external registration, ufoo assigns both the subscriber's
273
+ eight-character session suffix and its automatic `<agent-prefix>-<number>`
274
+ nickname on the server, using the same identity generators as wrapper launches.
275
+ A Cursor MCP registration with `agent_type: "cursor"`, for example, receives
276
+ `cursor:<8-hex>` and `cursor-N`; the model selected inside Cursor does not
277
+ replace the Cursor Agent type.
278
+ A stable `client_instance_id` recovers that same identity after a transport
279
+ restart; even when that value is a UUID, it is not used as the subscriber
280
+ suffix. Legacy MCP subscribers whose suffix is the client UUID are superseded
281
+ by the short server-assigned identity on their next registration. MCP Agents
282
+ cannot self-assign or update these identity fields; an explicit operator rename
283
+ remains available through the controller/CLI rename path.
284
+
272
285
  - **Codex App:** call MCP `wait_for_message` in the foreground with
273
286
  the registered subscriber and handle, `after_seq: 0`, and
274
287
  `timeout_seconds: 0`. The tool call stays pending inside the dedicated
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "u-foo",
3
- "version": "3.1.1",
3
+ "version": "3.1.3",
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,
@@ -115,6 +116,14 @@ const DEFAULT_MAX_NATIVE_TOOL_CALLS = 100;
115
116
  const DEFAULT_MAX_NATIVE_TOOL_ERRORS = 20;
116
117
  const MAX_EMPTY_TERMINAL_RETRIES = 2;
117
118
  const DEFAULT_NATIVE_TIMEOUT_MS = 43200000; // 12 hours
119
+ // Node's fetch is backed by Undici, whose default headers/body idle timeout is
120
+ // 300 seconds. Reasoning providers can legitimately stay silent longer than
121
+ // that between SSE chunks, so leave the absolute deadline to our existing
122
+ // AbortController instead of inheriting Undici's shorter hidden deadline.
123
+ const NATIVE_SSE_DISPATCHER_OPTIONS = Object.freeze({
124
+ headersTimeout: 0,
125
+ bodyTimeout: 0,
126
+ });
118
127
  /** Max text-only auto-continues while a plan is waiting on a task (per user submit). */
119
128
  const DEFAULT_MAX_PLAN_AUTO_CONTINUES = 24;
120
129
  // Anthropic Messages rejects max_tokens above the model's real cap (64K on
@@ -141,6 +150,40 @@ function normalizeTimeoutMs(value) {
141
150
  return Math.max(1000, Math.floor(parsed));
142
151
  }
143
152
 
153
+ let nativeSseDispatcher = null;
154
+
155
+ function createNativeSseDispatcher() {
156
+ return new UndiciAgent({ ...NATIVE_SSE_DISPATCHER_OPTIONS });
157
+ }
158
+
159
+ function getNativeSseDispatcher() {
160
+ if (!nativeSseDispatcher || nativeSseDispatcher.destroyed) {
161
+ nativeSseDispatcher = createNativeSseDispatcher();
162
+ }
163
+ return nativeSseDispatcher;
164
+ }
165
+
166
+ function enrichProviderTransportError(err) {
167
+ if (!err || typeof err !== "object") return err;
168
+
169
+ const cause = err.cause && typeof err.cause === "object" ? err.cause : null;
170
+ const code = String((cause && cause.code) || err.code || "").trim();
171
+ const causeMessage = String((cause && cause.message) || "").trim();
172
+ if (!code && !causeMessage) return err;
173
+
174
+ const message = String(err.message || "provider transport failed").trim();
175
+ const details = [code, causeMessage]
176
+ .filter(Boolean)
177
+ .filter((value, index, values) => values.indexOf(value) === index)
178
+ .join(": ");
179
+ if (!details || message.includes(details)) return err;
180
+
181
+ const enriched = new Error(`${message} (${details})`);
182
+ enriched.code = code || err.code;
183
+ enriched.cause = err;
184
+ return enriched;
185
+ }
186
+
144
187
  function normalizePositiveInt(value, fallback) {
145
188
  const parsed = Number.parseInt(String(value || ""), 10);
146
189
  if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
@@ -1216,6 +1259,7 @@ async function runSseRequest({
1216
1259
  headers,
1217
1260
  body: JSON.stringify(payload),
1218
1261
  signal: request.signal,
1262
+ dispatcher: getNativeSseDispatcher(),
1219
1263
  });
1220
1264
 
1221
1265
  if (!response.ok) {
@@ -1275,7 +1319,7 @@ async function runSseRequest({
1275
1319
  cancelError.code = "cancelled";
1276
1320
  throw cancelError;
1277
1321
  }
1278
- throw err;
1322
+ throw enrichProviderTransportError(err);
1279
1323
  } finally {
1280
1324
  request.cleanup();
1281
1325
  }
@@ -2847,6 +2891,7 @@ module.exports = {
2847
2891
  resolveTransport,
2848
2892
  resolveThinkingBudgetTokens,
2849
2893
  resolveReasoningEffort,
2894
+ createNativeSseDispatcher,
2850
2895
  buildCoreToolSpecs,
2851
2896
  buildAnthropicToolSpecs,
2852
2897
  };
@@ -4,6 +4,7 @@
4
4
  const AUTO_NICKNAME_PREFIXES = new Set([
5
5
  "claude",
6
6
  "codex",
7
+ "cursor",
7
8
  "agy",
8
9
  "grok",
9
10
  "kimi",
@@ -362,6 +362,7 @@ function isMetaActive(meta) {
362
362
  function normalizeAgentTypeAlias(value = "") {
363
363
  const text = String(value || "").trim().toLowerCase();
364
364
  if (!text) return "";
365
+ if (text === "cursor") return "cursor";
365
366
  if (text === "codex") return "codex";
366
367
  if (text === "claude" || text === "claude-code") return "claude-code";
367
368
  if (text === "agy") return "agy";
@@ -45,6 +45,16 @@ function normalizeBusAgentType(agentType = "") {
45
45
  return value;
46
46
  }
47
47
 
48
+ function assertServerOwnedExternalIdentity(args = {}, fields = [], operation = "register_agent") {
49
+ const field = fields.find((name) => Object.prototype.hasOwnProperty.call(args, name));
50
+ if (!field) return;
51
+ const err = new Error(
52
+ `${operation} ${field} is server-assigned; use the subscriber and nickname returned by ufoo`
53
+ );
54
+ err.code = "external_identity_field_forbidden";
55
+ throw err;
56
+ }
57
+
48
58
  function ensureBusLoaded(projectRoot) {
49
59
  const bus = new EventBus(projectRoot);
50
60
  bus.ensureBus();
@@ -72,14 +82,14 @@ function resolveSubscriberArg(args = {}) {
72
82
  return subscriber;
73
83
  }
74
84
 
75
- function createSessionId() {
76
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
77
- }
78
-
79
85
  function createCryptoSessionId() {
80
86
  return crypto.randomBytes(4).toString("hex");
81
87
  }
82
88
 
89
+ function isServerAllocatedExternalSessionId(sessionId = "") {
90
+ return /^[0-9a-f]{8}$/.test(String(sessionId || ""));
91
+ }
92
+
83
93
  function createAgentHandle() {
84
94
  return crypto.randomBytes(32).toString("base64url");
85
95
  }
@@ -174,7 +184,9 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
174
184
  ).trim();
175
185
  const bus = ensureBusLoaded(projectRoot);
176
186
 
177
- // Session ID: explicit > reuse > generate
187
+ // Wrapper launches may provide resume metadata. External MCP registrations
188
+ // recover only through client_instance_id; otherwise the server owns the
189
+ // short session id so subscriber shapes stay consistent across launch modes.
178
190
  let sessionId;
179
191
  const explicitSessionId = String(args.session_id || args.sessionId || "").trim();
180
192
  const reuseSession = args.reuseSession && typeof args.reuseSession === "object"
@@ -187,14 +199,18 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
187
199
  const reuseProviderSessionId = typeof reuseSession?.providerSessionId === "string"
188
200
  ? reuseSession.providerSessionId.trim() : "";
189
201
 
190
- const recoveredEntry = !validateParentPid && clientInstanceId
191
- ? Object.entries(bus.busData.agents || {}).find(([, meta]) => (
202
+ const clientInstanceEntries = !validateParentPid && clientInstanceId
203
+ ? Object.entries(bus.busData.agents || {}).filter(([, meta]) => (
192
204
  meta
193
205
  && meta.mcp_bridge === true
194
- && meta.agent_type === agentType
195
206
  && meta.mcp_client_instance_id === clientInstanceId
196
207
  ))
197
- : null;
208
+ : [];
209
+ const recoveredEntry = clientInstanceEntries.find(([subscriber, meta]) => (
210
+ meta.agent_type === agentType
211
+ && subscriber.startsWith(`${agentType}:`)
212
+ && isServerAllocatedExternalSessionId(subscriber.slice(agentType.length + 1))
213
+ ));
198
214
  const recoveredSubscriber = recoveredEntry ? recoveredEntry[0] : "";
199
215
  const recoveredSessionId = recoveredSubscriber.startsWith(`${agentType}:`)
200
216
  ? recoveredSubscriber.slice(agentType.length + 1)
@@ -202,12 +218,16 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
202
218
 
203
219
  if (recoveredSessionId) {
204
220
  sessionId = recoveredSessionId;
205
- } else if (explicitSessionId) {
221
+ } else if (validateParentPid && explicitSessionId) {
206
222
  sessionId = explicitSessionId;
207
- } else if (reuseSessionId && reuseSubscriberId === `${agentType}:${reuseSessionId}`) {
223
+ } else if (
224
+ validateParentPid
225
+ && reuseSessionId
226
+ && reuseSubscriberId === `${agentType}:${reuseSessionId}`
227
+ ) {
208
228
  sessionId = reuseSessionId;
209
229
  } else {
210
- sessionId = validateParentPid ? createCryptoSessionId() : createSessionId();
230
+ sessionId = createCryptoSessionId();
211
231
  }
212
232
 
213
233
  // parentPid validation
@@ -284,6 +304,20 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
284
304
  extendMcpAgentLease(meta);
285
305
  }
286
306
  if (hostCapabilities) meta.mcp_capabilities = hostCapabilities;
307
+ const supersededSubscribers = [];
308
+ if (!validateParentPid && clientInstanceId) {
309
+ for (const [previousSubscriber, previousMeta] of clientInstanceEntries) {
310
+ if (previousSubscriber === subscriber) continue;
311
+ const revokedAt = nowIso();
312
+ previousMeta.mcp_revoked_at = revokedAt;
313
+ previousMeta.mcp_lease_expires_at = revokedAt;
314
+ previousMeta.mcp_superseded_by = subscriber;
315
+ await bus.subscriberManager.leave(previousSubscriber);
316
+ previousMeta.status = "inactive";
317
+ previousMeta.activity_state = "";
318
+ supersededSubscribers.push(previousSubscriber);
319
+ }
320
+ }
287
321
  bus.saveBusData();
288
322
  notifyDaemonRefresh(projectRoot);
289
323
  return {
@@ -301,6 +335,7 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
301
335
  lease_expires_at: meta.mcp_lease_expires_at,
302
336
  client_instance_id: clientInstanceId,
303
337
  recovered: Boolean(recoveredSubscriber),
338
+ ...(supersededSubscribers.length > 0 ? { superseded_subscribers: supersededSubscribers } : {}),
304
339
  } : {}),
305
340
  reuseProviderSessionId,
306
341
  skipSessionResolve: !!args.skipSessionResolve,
@@ -308,6 +343,18 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
308
343
  }
309
344
 
310
345
  async function registerAgent(projectRoot, args = {}) {
346
+ if (!String(args.agent_type || args.agentType || "").trim()) {
347
+ const err = new Error("register_agent requires agent_type for canonical identity allocation");
348
+ err.code = "external_agent_type_required";
349
+ throw err;
350
+ }
351
+ assertServerOwnedExternalIdentity(args, [
352
+ "session_id",
353
+ "sessionId",
354
+ "nickname",
355
+ "scoped_nickname",
356
+ "scopedNickname",
357
+ ]);
311
358
  return registerAgentFull(projectRoot, args, {
312
359
  validateParentPid: false,
313
360
  checkNicknameConflicts: false,
@@ -360,13 +407,14 @@ async function publishActivityState(projectRoot, args = {}) {
360
407
  }
361
408
 
362
409
  async function updateAgentMetadata(projectRoot, args = {}) {
410
+ assertServerOwnedExternalIdentity(args, [
411
+ "nickname",
412
+ "scoped_nickname",
413
+ "scopedNickname",
414
+ ], "update_agent_metadata");
363
415
  const subscriber = resolveSubscriberArg(args);
364
416
  const bus = ensureBusLoaded(projectRoot);
365
417
  const meta = assertAgentHandle(bus, subscriber, args);
366
- const nickname = String(args.nickname || "").trim();
367
- if (nickname) {
368
- await bus.subscriberManager.rename(subscriber, nickname);
369
- }
370
418
  const metadata = args.metadata && typeof args.metadata === "object" ? args.metadata : {};
371
419
  if (Object.keys(metadata).length > 0) {
372
420
  meta.mcp_metadata = {
@@ -631,7 +679,6 @@ module.exports = {
631
679
  ensureBusLoaded,
632
680
  assertSubscriberExists,
633
681
  resolveSubscriberArg,
634
- createSessionId,
635
682
  createAgentHandle,
636
683
  hashAgentHandle,
637
684
  assertAgentHandle,
@@ -73,6 +73,7 @@ function sleep(ms) {
73
73
  function normalizeBusAgentType(agentType = "") {
74
74
  const value = String(agentType || "").trim().toLowerCase();
75
75
  if (!value) return "claude-code";
76
+ if (value === "cursor") return "cursor";
76
77
  if (value === "codex") return "codex";
77
78
  if (value === "claude" || value === "claude-code") return "claude-code";
78
79
  if (value === "agy" || value === "antigravity") return "agy";
@@ -51,16 +51,16 @@ const CUSTOM_TOOL_DEFINITIONS = Object.freeze([
51
51
  },
52
52
  {
53
53
  name: "register_agent",
54
- description: "Register an externally launched Agent only when its shell has no wrapper-provided UFOO_SUBSCRIBER_ID.",
54
+ description: "Register an externally launched Agent only when its shell has no wrapper-provided UFOO_SUBSCRIBER_ID. ufoo assigns the subscriber id and nickname with the same format used by wrapper launches (for example, cursor:<8-hex> and cursor-N).",
55
55
  input_schema: {
56
56
  type: "object",
57
- required: ["project_root"],
57
+ required: ["project_root", "agent_type"],
58
58
  properties: {
59
59
  project_root: { type: "string" },
60
- agent_type: { type: "string" },
61
- session_id: { type: "string" },
62
- nickname: { type: "string" },
63
- scoped_nickname: { type: "string" },
60
+ agent_type: {
61
+ type: "string",
62
+ description: "Agent family used as the subscriber and automatic nickname prefix, such as cursor, codex, claude, agy, grok, kimi, or ucode.",
63
+ },
64
64
  launch_mode: { type: "string" },
65
65
  capabilities: { type: "object", additionalProperties: true },
66
66
  client_instance_id: {
@@ -107,7 +107,7 @@ const CUSTOM_TOOL_DEFINITIONS = Object.freeze([
107
107
  },
108
108
  {
109
109
  name: "update_agent_metadata",
110
- description: "Update the caller agent nickname or MCP metadata in its project bus.",
110
+ description: "Update caller-owned MCP metadata in the project bus.",
111
111
  input_schema: {
112
112
  type: "object",
113
113
  required: ["project_root", "subscriber", "agent_handle"],
@@ -115,7 +115,6 @@ const CUSTOM_TOOL_DEFINITIONS = Object.freeze([
115
115
  project_root: { type: "string" },
116
116
  subscriber: { type: "string" },
117
117
  agent_handle: { type: "string" },
118
- nickname: { type: "string" },
119
118
  metadata: { type: "object", additionalProperties: true },
120
119
  },
121
120
  additionalProperties: false,