u-foo 3.0.31 → 3.1.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "u-foo",
3
- "version": "3.0.31",
3
+ "version": "3.1.0",
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",
@@ -11,6 +11,10 @@ const iterm2 = require("../../runtime/terminal/iterm2");
11
11
  const { createActivityStatePublisher } = require("../activity/activityStatePublisher");
12
12
  const { buildPromptInjectionText } = require("../../coordination/bus/promptEnvelope");
13
13
  const { DeliveryQueue } = require("../../coordination/bus/deliveryQueue");
14
+ const {
15
+ INJECTION_MODES,
16
+ getInjectionModeFromEvent,
17
+ } = require("../../coordination/bus/messageMeta");
14
18
 
15
19
  /**
16
20
  * Agent 消息通知监听器
@@ -182,6 +186,16 @@ class AgentNotifier {
182
186
  || value === "blocked";
183
187
  }
184
188
 
189
+ isImmediateEvent(event) {
190
+ return getInjectionModeFromEvent(event, INJECTION_MODES.IMMEDIATE) === INJECTION_MODES.IMMEDIATE;
191
+ }
192
+
193
+ pendingEventKey(event = {}) {
194
+ const seq = Number(event.seq);
195
+ if (Number.isFinite(seq) && seq > 0) return `seq:${seq}`;
196
+ return `event:${JSON.stringify(event)}`;
197
+ }
198
+
185
199
  /**
186
200
  * 获取当前队列中的消息数量
187
201
  */
@@ -242,11 +256,19 @@ class AgentNotifier {
242
256
  return 0;
243
257
  }
244
258
 
259
+ const pending = this.deliveryQueue.readPending();
260
+ if (pending.length === 0) return 0;
261
+
262
+ let selectedEvent = pending[0];
245
263
  if (this.isBusyState(this.getCurrentActivityState())) {
246
- return 0;
264
+ selectedEvent = pending.find((event) => this.isImmediateEvent(event));
265
+ if (!selectedEvent) return 0;
247
266
  }
248
267
 
249
- const claim = this.deliveryQueue.claimNext();
268
+ const selectedKey = this.pendingEventKey(selectedEvent);
269
+ const claim = this.deliveryQueue.claimNext(
270
+ (event) => this.pendingEventKey(event) === selectedKey
271
+ );
250
272
  if (!claim) return 0;
251
273
 
252
274
  const evt = claim.event;
@@ -256,7 +278,7 @@ class AgentNotifier {
256
278
  }
257
279
 
258
280
  const activityState = this.getCurrentActivityState();
259
- if (this.isBusyState(activityState)) {
281
+ if (!this.isImmediateEvent(evt) && this.isBusyState(activityState)) {
260
282
  this.deliveryQueue.restoreClaim(claim);
261
283
  return 0;
262
284
  }
@@ -1609,14 +1609,15 @@ async function runCli(argv) {
1609
1609
  });
1610
1610
  bus
1611
1611
  .command("inject")
1612
- .description("Inject /bus into a Terminal.app tab by subscriber ID")
1612
+ .description("Inject explicit raw prompt text into an agent terminal")
1613
1613
  .argument("<subscriber>", "Subscriber ID to inject into")
1614
- .action((subscriber) => {
1614
+ .argument("<text...>", "Prompt text to inject")
1615
+ .action((subscriber, text) => {
1615
1616
  const EventBus = require("../../coordination/bus");
1616
1617
  const eventBus = new EventBus(process.cwd());
1617
1618
  (async () => {
1618
1619
  try {
1619
- await eventBus.inject(subscriber);
1620
+ await eventBus.inject(subscriber, text.join(" "));
1620
1621
  } catch (err) {
1621
1622
  console.error(err.message);
1622
1623
  process.exitCode = 1;
@@ -1625,7 +1626,7 @@ async function runCli(argv) {
1625
1626
  });
1626
1627
  bus
1627
1628
  .command("wake")
1628
- .description("Wake an agent (inject /ubus into its terminal)")
1629
+ .description("Send a notify-only wake event without injecting prompt text")
1629
1630
  .argument("<target>", "Subscriber ID or nickname")
1630
1631
  .option("--reason <reason>", "Wake reason")
1631
1632
  .option("--no-shake", "Disable window shake")
@@ -2448,7 +2449,11 @@ async function runCli(argv) {
2448
2449
  if (!subscriber) {
2449
2450
  throw new Error("inject requires <subscriber-id>");
2450
2451
  }
2451
- await eventBus.inject(subscriber);
2452
+ const text = rest.slice(2).join(" ").trim();
2453
+ if (!text) {
2454
+ throw new Error("inject requires <subscriber-id> <text>");
2455
+ }
2456
+ await eventBus.inject(subscriber, text);
2452
2457
  } catch (err) {
2453
2458
  console.error(err.message);
2454
2459
  process.exitCode = 1;
@@ -1,5 +1,9 @@
1
1
  const fs = require("fs");
2
2
  const path = require("path");
3
+ const {
4
+ INJECTION_MODES,
5
+ getInjectionModeFromEvent,
6
+ } = require("./messageMeta");
3
7
  const {
4
8
  ensureDir,
5
9
  appendJSONL,
@@ -61,7 +65,9 @@ function inferQueueType(event = {}) {
61
65
 
62
66
  function defaultDeliveryForType(queueType) {
63
67
  if (queueType === QUEUE_TYPES.AGENT_MESSAGE) {
64
- return { mode: "inject", gate: "idle", max_inflight: 1 };
68
+ // Agent messages default to immediate delivery; explicit queued messages
69
+ // are assigned the idle gate in normalizeQueueEnvelope below.
70
+ return { mode: "inject", gate: "none", max_inflight: 1 };
65
71
  }
66
72
  if (queueType === QUEUE_TYPES.WAKE) {
67
73
  return { mode: "notify_only", gate: "none", max_inflight: 1 };
@@ -84,14 +90,21 @@ function normalizeQueueEnvelope(event = {}, overrides = {}) {
84
90
  const overrideDelivery = overrides.delivery && typeof overrides.delivery === "object" ? overrides.delivery : {};
85
91
  const existingAck = event.ack && typeof event.ack === "object" ? event.ack : {};
86
92
  const overrideAck = overrides.ack && typeof overrides.ack === "object" ? overrides.ack : {};
93
+ const delivery = {
94
+ ...defaultDeliveryForType(queueType),
95
+ ...existingDelivery,
96
+ ...overrideDelivery,
97
+ };
98
+ if (queueType === QUEUE_TYPES.AGENT_MESSAGE && delivery.mode === "inject") {
99
+ // injection_mode is the public contract and must override stale persisted
100
+ // gate metadata from releases that wrote every agent message as idle-gated.
101
+ const injectionMode = getInjectionModeFromEvent(event, INJECTION_MODES.IMMEDIATE);
102
+ delivery.gate = injectionMode === INJECTION_MODES.QUEUED ? "idle" : "none";
103
+ }
87
104
  return {
88
105
  ...event,
89
106
  queue_type: queueType,
90
- delivery: {
91
- ...defaultDeliveryForType(queueType),
92
- ...existingDelivery,
93
- ...overrideDelivery,
94
- },
107
+ delivery,
95
108
  ack: {
96
109
  ...defaultAckForType(queueType),
97
110
  ...existingAck,
@@ -247,13 +260,21 @@ class DeliveryQueue {
247
260
  return { recovered: merged.length, files };
248
261
  }
249
262
 
250
- claimNext() {
263
+ claimNext(predicate = null) {
251
264
  this.recover();
252
265
  const pending = this.readPendingRaw();
253
266
  if (pending.length === 0) return null;
254
267
 
255
- const event = pending[0];
256
- const remaining = pending.slice(1);
268
+ const index = typeof predicate === "function"
269
+ ? pending.findIndex((event, eventIndex) => predicate(event, eventIndex, pending))
270
+ : 0;
271
+ if (index < 0) return null;
272
+
273
+ const event = pending[index];
274
+ const remaining = [
275
+ ...pending.slice(0, index),
276
+ ...pending.slice(index + 1),
277
+ ];
257
278
  const processingFile = `${this.pendingFile}.processing.${process.pid}.${Date.now()}.${generateInstanceId()}`;
258
279
  this.ensureQueueDir();
259
280
  writeFileAtomic(processingFile, eventToJsonl([event]));
@@ -829,7 +829,7 @@ class EventBus {
829
829
  }
830
830
 
831
831
  /**
832
- * 远程唤醒本地 agent(触发 /ubus 注入)
832
+ * Notify a local agent without injecting a synthetic prompt.
833
833
  */
834
834
  async wake(subscriber, options = {}) {
835
835
  this.ensureBus();
@@ -847,6 +847,7 @@ class EventBus {
847
847
  throw new Error(`Target "${subscriber}" not found`);
848
848
  }
849
849
 
850
+ const injector = new Injector(this.busDir, this.agentsFile);
850
851
  for (const target of targets) {
851
852
  const safeName = subscriberToSafeName(target);
852
853
  const queueDir = path.join(this.busDir, "queues", safeName);
@@ -860,10 +861,8 @@ class EventBus {
860
861
  const countAfter = after.trim() ? after.trim().split(/\r?\n/).length : 0;
861
862
 
862
863
  if (countAfter > countBefore) {
863
- await sleep(50);
864
- await this.injector.inject(target, options.command || "");
865
864
  if (options.shake !== false) {
866
- const tty = this.injector.readTty(target);
865
+ const tty = injector.readTty(target);
867
866
  if (tty) shakeTerminalByTty(tty, { skipFrontmost: true });
868
867
  }
869
868
  }
@@ -956,7 +955,7 @@ class EventBus {
956
955
  /**
957
956
  * 注入命令到订阅者终端
958
957
  */
959
- async inject(subscriber, commandOverride = "") {
958
+ async inject(subscriber, commandOverride) {
960
959
  this.ensureBus();
961
960
  const injector = new Injector(this.busDir, this.agentsFile);
962
961
  await injector.inject(subscriber, commandOverride);
@@ -455,23 +455,20 @@ class Injector {
455
455
  * 2. tmux send-keys(无需权限)
456
456
  * 3. Terminal.app/iTerm2 tty lookup(terminal mode fallback)
457
457
  */
458
- async inject(subscriber, commandOverride = "") {
458
+ async inject(subscriber, commandOverride) {
459
459
  if (String(subscriber || "").startsWith("ufoo-code:")) {
460
460
  throw new Error(`Inject disabled for ${subscriber}. ufoo-code consumes bus internally.`);
461
461
  }
462
462
 
463
- // 确定注入命令:
464
- // - codex: 裸 "ubus"(codex 没有 slash-command 命名空间)
465
- // - agy/grok: 裸 "ubus"(它们的 `/` 是自己的 slash-command 命名空间,
466
- // "/ubus" 会被识别为 unknown slash command 而不是 prompt)
467
- // - claude-code 及其他: "/ubus"
468
- const command = commandOverride
469
- ? String(commandOverride)
470
- : (
471
- subscriber.startsWith("codex:") || subscriber.startsWith("agy:") || subscriber.startsWith("grok:")
472
- ? "ubus"
473
- : "/ubus"
474
- );
463
+ // Terminal injection is a delivery adapter for explicit prompt text.
464
+ // Never synthesize a command for an empty payload: doing so turns wake or
465
+ // acknowledgement-adjacent lifecycle activity into a visible user turn.
466
+ const command = commandOverride === undefined || commandOverride === null
467
+ ? ""
468
+ : String(commandOverride);
469
+ if (!command.trim()) {
470
+ throw new Error(`Inject requires non-empty prompt text for ${subscriber}`);
471
+ }
475
472
 
476
473
  const meta = this.getAgentMeta(subscriber) || {};
477
474
  const launchMode = meta.launch_mode || "";
@@ -449,7 +449,7 @@ class MessageManager {
449
449
  };
450
450
  const queueEvent = normalizeQueueEnvelope(event, {
451
451
  queueType: QUEUE_TYPES.AGENT_MESSAGE,
452
- delivery: { mode: "inject", gate: "idle", max_inflight: 1 },
452
+ delivery: { mode: "inject", max_inflight: 1 },
453
453
  ack: { policy: "on_delivery" },
454
454
  });
455
455
 
@@ -166,7 +166,24 @@ class DeliveryScheduler {
166
166
  };
167
167
  }
168
168
 
169
- shouldDeliver(subscriber) {
169
+ readPendingEvents(queue) {
170
+ try {
171
+ return queue && typeof queue.readPending === "function"
172
+ ? queue.readPending().filter(Boolean)
173
+ : [];
174
+ } catch {
175
+ return [];
176
+ }
177
+ }
178
+
179
+ eventNeedsIdleGate(event) {
180
+ if (!event) return true;
181
+ const envelope = normalizeQueueEnvelope(event);
182
+ const delivery = envelope.delivery || {};
183
+ return delivery.mode === "inject" && delivery.gate === "idle";
184
+ }
185
+
186
+ shouldDeliver(subscriber, options = {}) {
170
187
  const { meta } = this.getAgentMeta(subscriber);
171
188
  if (!meta || meta.status === "inactive") {
172
189
  return { ok: false, reason: "missing_or_inactive" };
@@ -179,6 +196,9 @@ class DeliveryScheduler {
179
196
  if (!adapter.capabilities.supportsNotifierInjector) {
180
197
  return { ok: false, reason: launchMode ? "unsupported_launch_mode" : "missing_launch_mode" };
181
198
  }
199
+ if (options.requireIdle === false) {
200
+ return { ok: true, reason: "deliverable" };
201
+ }
182
202
  const activityState = asState(meta.activity_state);
183
203
  if (!isDeliverableActivityState(activityState)) {
184
204
  if (activityState === "waiting_input" || activityState === "blocked") {
@@ -225,7 +245,9 @@ class DeliveryScheduler {
225
245
  this.forceWarned.delete(trackingKey);
226
246
  this.forceRetries.delete(trackingKey);
227
247
  }
228
- this.pendingSeen.delete(subscriber);
248
+ if (!event || !tracked || tracked.key === key) {
249
+ this.pendingSeen.delete(subscriber);
250
+ }
229
251
  }
230
252
 
231
253
  clearTrackedKey(subscriber, key) {
@@ -292,9 +314,12 @@ class DeliveryScheduler {
292
314
  }
293
315
 
294
316
  resolveGate(subscriber, queue, eventOverride = null) {
295
- const gate = this.shouldDeliver(subscriber);
317
+ const event = eventOverride || this.readPendingEvents(queue)[0] || null;
318
+ const gate = this.shouldDeliver(subscriber, {
319
+ requireIdle: this.eventNeedsIdleGate(event),
320
+ });
296
321
  if (gate.ok || !gate.activityBlocked) return gate;
297
- const pending = this.resolvePendingWait(subscriber, queue, eventOverride);
322
+ const pending = this.resolvePendingWait(subscriber, queue, event);
298
323
  if (!pending || pending.waitedMs < this.forceDeliveryAfterMs) return gate;
299
324
  const retry = this.forceRetries.get(`${subscriber}:${pending.key}`);
300
325
  if (retry && this.now() < retry.nextAtMs) {
@@ -323,7 +348,25 @@ class DeliveryScheduler {
323
348
  this.locks.set(subscriber, { sinceMs: this.now(), lastWarnAtMs: 0 });
324
349
  try {
325
350
  const queue = this.queueFactory(subscriber);
326
- const gate = this.resolveGate(subscriber, queue);
351
+ const transportGate = this.shouldDeliver(subscriber, { requireIdle: false });
352
+ if (!transportGate.ok) {
353
+ this.noteDeferral(subscriber, transportGate.reason);
354
+ return { ok: true, delivered: 0, deferred: true, reason: transportGate.reason };
355
+ }
356
+
357
+ const pendingEvents = this.readPendingEvents(queue);
358
+ let selectedEvent = pendingEvents[0] || null;
359
+ let gate = this.resolveGate(subscriber, queue, selectedEvent);
360
+ if (!gate.ok) {
361
+ // A queued item must not head-of-line block a later immediate message.
362
+ // This also lets explicit immediate delivery ignore stale/incorrect
363
+ // activity snapshots, notably Grok Build's current working state.
364
+ const bypassEvent = pendingEvents.find((event) => !this.eventNeedsIdleGate(event));
365
+ if (bypassEvent && bypassEvent !== selectedEvent) {
366
+ selectedEvent = bypassEvent;
367
+ gate = this.resolveGate(subscriber, queue, selectedEvent);
368
+ }
369
+ }
327
370
  if (!gate.ok) {
328
371
  this.noteDeferral(subscriber, gate.reason);
329
372
  return { ok: true, delivered: 0, deferred: true, reason: gate.reason };
@@ -335,9 +378,12 @@ class DeliveryScheduler {
335
378
  }
336
379
  this.clearDeferral(subscriber);
337
380
 
338
- const claim = queue.claimNext();
381
+ const selectedKey = selectedEvent ? this.pendingEventKey(selectedEvent) : "";
382
+ const claim = queue.claimNext(selectedKey
383
+ ? (event) => this.pendingEventKey(event) === selectedKey
384
+ : undefined);
339
385
  if (!claim) {
340
- this.clearPendingTracking(subscriber);
386
+ if (pendingEvents.length === 0) this.clearPendingTracking(subscriber);
341
387
  return { ok: true, delivered: 0, reason: "empty" };
342
388
  }
343
389