agent-comm-hub 0.9.1 → 0.11.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/README.md +75 -18
- package/README.zh.md +5 -5
- package/agents/SKILL.md +114 -33
- package/agents/install-all.ps1 +25 -160
- package/agents/registry.json +175 -7
- package/lib/cli.js +2609 -284
- package/lib/index.js +2343 -222
- package/lib/setup.js +184 -26
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { createServer } from "node:http";
|
|
3
3
|
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
4
4
|
import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
5
|
-
import { dirname as dirname2 } from "node:path";
|
|
5
|
+
import { dirname as dirname2, join } from "node:path";
|
|
6
6
|
|
|
7
7
|
// src/herdr-ctl.ts
|
|
8
8
|
import { execFile } from "node:child_process";
|
|
@@ -415,6 +415,104 @@ function socketSend(socketPath, method, params) {
|
|
|
415
415
|
});
|
|
416
416
|
}
|
|
417
417
|
|
|
418
|
+
// src/runner.ts
|
|
419
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
420
|
+
var DEFAULT_RUN_TIMEOUT_MS = 12e4;
|
|
421
|
+
var MAX_RUN_NOTE_CHARS = 4e3;
|
|
422
|
+
function validateRunnerConfig(config, index) {
|
|
423
|
+
const where = `runners[${index}]`;
|
|
424
|
+
if (typeof config.peer !== "string" || config.peer === "") throw new Error(`${where}: peer must be a non-empty string`);
|
|
425
|
+
if (config.kind !== "cli" && config.kind !== "herdr") throw new Error(`${where}: kind must be 'cli' or 'herdr'`);
|
|
426
|
+
if (config.kind === "cli") {
|
|
427
|
+
if (typeof config.command !== "string" || config.command === "") throw new Error(`${where}: cli needs a command`);
|
|
428
|
+
if (config.args !== void 0 && (!Array.isArray(config.args) || config.args.some((arg) => typeof arg !== "string"))) {
|
|
429
|
+
throw new Error(`${where}: args must be an array of strings`);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
if (config.timeoutMs !== void 0 && (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0)) {
|
|
433
|
+
throw new Error(`${where}: timeoutMs must be a positive number`);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
var truncate = (text) => text.length > MAX_RUN_NOTE_CHARS ? `${text.slice(0, MAX_RUN_NOTE_CHARS)}\u2026 (truncated)` : text;
|
|
437
|
+
function substitute(arg, request) {
|
|
438
|
+
const values = {
|
|
439
|
+
prompt: request.prompt,
|
|
440
|
+
context: request.context,
|
|
441
|
+
deliverable: request.deliverable,
|
|
442
|
+
taskId: request.taskId,
|
|
443
|
+
peer: request.peer
|
|
444
|
+
};
|
|
445
|
+
return arg.replace(/\{(\w+)\}/g, (whole, key) => values[key] ?? whole);
|
|
446
|
+
}
|
|
447
|
+
function cliRunner(config) {
|
|
448
|
+
const command = config.command;
|
|
449
|
+
const args = config.args ?? [];
|
|
450
|
+
const timeout = config.timeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;
|
|
451
|
+
return {
|
|
452
|
+
name: `cli:${command}`,
|
|
453
|
+
run: (request) => new Promise((resolve) => {
|
|
454
|
+
execFile2(
|
|
455
|
+
command,
|
|
456
|
+
args.map((arg) => substitute(arg, request)),
|
|
457
|
+
// No shell, a bounded buffer, and a hard timeout: a hung runner must
|
|
458
|
+
// not hold the task open forever.
|
|
459
|
+
{ timeout, maxBuffer: 4 * 1024 * 1024, windowsHide: true },
|
|
460
|
+
(error, stdout, stderr) => {
|
|
461
|
+
const out = stdout.trim();
|
|
462
|
+
if (error !== null) {
|
|
463
|
+
const detail = stderr.trim() !== "" ? stderr.trim() : error.message;
|
|
464
|
+
resolve({ status: "failed", note: truncate(`runner failed: ${detail}${out !== "" ? `
|
|
465
|
+
${out}` : ""}`) });
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
resolve({ status: "done", note: truncate(out === "" ? "(runner produced no output)" : out) });
|
|
469
|
+
}
|
|
470
|
+
);
|
|
471
|
+
})
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
function herdrRunner(config, ctl) {
|
|
475
|
+
const target = config.target ?? config.peer;
|
|
476
|
+
const timeout = config.timeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;
|
|
477
|
+
return {
|
|
478
|
+
name: `herdr:${target}`,
|
|
479
|
+
run: async (request) => {
|
|
480
|
+
try {
|
|
481
|
+
const text = [request.prompt, request.context].filter((part) => part !== void 0 && part !== "").join("\n\n");
|
|
482
|
+
await ctl.promptSmart(target, text, { wait: true, timeoutMs: timeout });
|
|
483
|
+
const read = await ctl.readSmart(target, { lines: 200 });
|
|
484
|
+
return { status: "done", note: truncate(read.text.trim() === "" ? "(no output read back)" : read.text) };
|
|
485
|
+
} catch (error) {
|
|
486
|
+
return { status: "failed", note: truncate(`herdr runner failed: ${error.message}`) };
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
function createRunner(config, deps = {}) {
|
|
492
|
+
if (config.kind === "cli") return cliRunner(config);
|
|
493
|
+
if (deps.herdr === void 0) throw new Error(`runner for '${config.peer}': kind 'herdr' needs herdr to be enabled`);
|
|
494
|
+
return herdrRunner(config, deps.herdr);
|
|
495
|
+
}
|
|
496
|
+
var RunnerRegistry = class {
|
|
497
|
+
runners = /* @__PURE__ */ new Map();
|
|
498
|
+
constructor(configs = [], deps = {}) {
|
|
499
|
+
configs.forEach((config, index) => {
|
|
500
|
+
validateRunnerConfig(config, index);
|
|
501
|
+
this.runners.set(config.peer, createRunner(config, deps));
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
get(peer) {
|
|
505
|
+
return this.runners.get(peer);
|
|
506
|
+
}
|
|
507
|
+
/** Peer ids that have a runner (for startup logging). */
|
|
508
|
+
peers() {
|
|
509
|
+
return [...this.runners.keys()];
|
|
510
|
+
}
|
|
511
|
+
get size() {
|
|
512
|
+
return this.runners.size;
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
|
|
418
516
|
// src/hub.ts
|
|
419
517
|
import { randomUUID } from "node:crypto";
|
|
420
518
|
|
|
@@ -422,8 +520,47 @@ import { randomUUID } from "node:crypto";
|
|
|
422
520
|
var KINDS = ["chat", "task", "notice", "ack"];
|
|
423
521
|
var PEER_ID_PATTERN = /^[A-Za-z0-9._:-]{1,64}$/;
|
|
424
522
|
var BROADCAST = "all";
|
|
523
|
+
var HUB_PEER = "hub";
|
|
524
|
+
var SSE_METHOD = "notifications/message";
|
|
525
|
+
var SSE_EVENT_PEERS_CHANGED = "peers_changed";
|
|
526
|
+
var SSE_EVENT_MESSAGE = "message";
|
|
527
|
+
var SSE_EVENT_TASK_CHANGED = "task_changed";
|
|
425
528
|
var MAX_HOP = 5;
|
|
426
|
-
var
|
|
529
|
+
var MAX_REPLY_CHAIN = 50;
|
|
530
|
+
function a2aState(status) {
|
|
531
|
+
switch (status) {
|
|
532
|
+
case "pending":
|
|
533
|
+
case "accepted":
|
|
534
|
+
return "submitted";
|
|
535
|
+
case "working":
|
|
536
|
+
return "working";
|
|
537
|
+
case "input-required":
|
|
538
|
+
return "input-required";
|
|
539
|
+
case "done":
|
|
540
|
+
return "completed";
|
|
541
|
+
case "canceled":
|
|
542
|
+
return "canceled";
|
|
543
|
+
case "failed":
|
|
544
|
+
case "timeout":
|
|
545
|
+
return "failed";
|
|
546
|
+
case "rejected":
|
|
547
|
+
return "rejected";
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
var CLIENT_ACK_STATUSES = ["accepted", "working", "input-required", "rejected", "done", "failed"];
|
|
551
|
+
var ALL_ACK_STATUSES = [...CLIENT_ACK_STATUSES, "canceled"];
|
|
552
|
+
var TERMINAL_TASK_STATUSES = ["rejected", "done", "failed", "timeout", "canceled"];
|
|
553
|
+
var ALL_TASK_STATUSES = [
|
|
554
|
+
"pending",
|
|
555
|
+
"accepted",
|
|
556
|
+
"working",
|
|
557
|
+
"input-required",
|
|
558
|
+
"rejected",
|
|
559
|
+
"done",
|
|
560
|
+
"failed",
|
|
561
|
+
"timeout",
|
|
562
|
+
"canceled"
|
|
563
|
+
];
|
|
427
564
|
function ackToTaskStatus(ack) {
|
|
428
565
|
return ack;
|
|
429
566
|
}
|
|
@@ -438,6 +575,9 @@ function nextTaskStatus(current, ack) {
|
|
|
438
575
|
case "working":
|
|
439
576
|
if (next === "accepted") return "working";
|
|
440
577
|
return next;
|
|
578
|
+
case "input-required":
|
|
579
|
+
if (next === "accepted") return "input-required";
|
|
580
|
+
return next;
|
|
441
581
|
default:
|
|
442
582
|
return null;
|
|
443
583
|
}
|
|
@@ -445,6 +585,7 @@ function nextTaskStatus(current, ack) {
|
|
|
445
585
|
function aggregateTaskStatus(assignees) {
|
|
446
586
|
if (assignees.length === 0) return "pending";
|
|
447
587
|
const statuses = assignees.map((a) => a.status);
|
|
588
|
+
if (statuses.some((s) => s === "input-required")) return "input-required";
|
|
448
589
|
const active = statuses.filter((s) => s === "pending" || s === "accepted" || s === "working");
|
|
449
590
|
if (active.length > 0) {
|
|
450
591
|
if (active.some((s) => s === "working")) return "working";
|
|
@@ -454,13 +595,14 @@ function aggregateTaskStatus(assignees) {
|
|
|
454
595
|
if (statuses.every((s) => s === "done")) return "done";
|
|
455
596
|
if (statuses.some((s) => s === "failed")) return "failed";
|
|
456
597
|
if (statuses.some((s) => s === "timeout")) return "timeout";
|
|
598
|
+
if (statuses.some((s) => s === "canceled")) return "canceled";
|
|
457
599
|
return "rejected";
|
|
458
600
|
}
|
|
459
601
|
function encodeContent(payload) {
|
|
460
602
|
return JSON.stringify(payload);
|
|
461
603
|
}
|
|
462
604
|
function decodeContent(kind, content) {
|
|
463
|
-
if (kind !== "task" && kind !== "ack") return content;
|
|
605
|
+
if (kind !== "task" && kind !== "ack" && kind !== "notice") return content;
|
|
464
606
|
try {
|
|
465
607
|
const parsed = JSON.parse(content);
|
|
466
608
|
if (parsed !== null && typeof parsed === "object") return parsed;
|
|
@@ -472,20 +614,140 @@ function decodeContent(kind, content) {
|
|
|
472
614
|
// src/hub.ts
|
|
473
615
|
var MAX_PROFILES = 512;
|
|
474
616
|
var MAX_TASKS = 1024;
|
|
617
|
+
var MAX_DEAD_LETTERS = 200;
|
|
618
|
+
var MAX_TASK_ACKS = 200;
|
|
619
|
+
var MAX_TASK_ARTIFACTS = 50;
|
|
475
620
|
var MAX_TIMER_DELAY_MS = 2147483647;
|
|
476
|
-
var
|
|
621
|
+
var DEFAULT_PARKED_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
622
|
+
var DEFAULT_LEASE_TTL_MS = 6e4;
|
|
623
|
+
var DEFAULT_MAX_ATTEMPTS = 5;
|
|
624
|
+
var MAX_EVENTS = 500;
|
|
625
|
+
var AgentHub = class _AgentHub {
|
|
477
626
|
constructor(options) {
|
|
478
627
|
this.options = options;
|
|
479
628
|
const idle = options.peerIdleTimeoutMs ?? 6e5;
|
|
629
|
+
const parkedTtl = options.parkedTtlMs ?? DEFAULT_PARKED_TTL_MS;
|
|
480
630
|
if (idle > 0) {
|
|
481
631
|
const interval = Math.min(6e4, Math.max(1e3, idle / 2));
|
|
482
632
|
this.gcTimer = setInterval(() => this.gcTick(idle), interval);
|
|
483
633
|
this.gcTimer.unref?.();
|
|
634
|
+
} else if (parkedTtl > 0) {
|
|
635
|
+
const interval = Math.min(6e4, Math.max(1e3, parkedTtl / 2));
|
|
636
|
+
this.gcTimer = setInterval(() => this.expireParkedMailboxes(Date.now()), interval);
|
|
637
|
+
this.gcTimer.unref?.();
|
|
484
638
|
}
|
|
485
639
|
}
|
|
486
640
|
queues = /* @__PURE__ */ new Map();
|
|
641
|
+
/** When each parked (peer-gone-but-kept) mailbox was parked, for the TTL sweep.
|
|
642
|
+
* A queue in this map has no registered peer; see {@link unregister}. */
|
|
643
|
+
parkedAt = /* @__PURE__ */ new Map();
|
|
644
|
+
/** Highest {@link BridgeMessage.seq} handed out so far. Restored history can
|
|
645
|
+
* raise it (see importHistory) but nothing lowers it: a client's `since` cursor
|
|
646
|
+
* has to keep meaning the same thing across a restart. */
|
|
647
|
+
seqCounter = 0;
|
|
648
|
+
/**
|
|
649
|
+
* Record one operational event.
|
|
650
|
+
*
|
|
651
|
+
* Deliberately NOT the same thing as history: history is the messages that
|
|
652
|
+
* flowed (what peers said to each other), this is what the HUB did — a peer
|
|
653
|
+
* joined, a mailbox was dropped, a task moved. History can be read per peer and
|
|
654
|
+
* is persisted; events are global, per-run, and never persisted, because they
|
|
655
|
+
* describe the life of this process.
|
|
656
|
+
*/
|
|
657
|
+
recordEvent(kind, input = {}) {
|
|
658
|
+
this.eventRing.push({
|
|
659
|
+
seq: ++this.eventSeq,
|
|
660
|
+
ts: Date.now(),
|
|
661
|
+
kind,
|
|
662
|
+
...input.peer !== void 0 ? { peer: input.peer } : {},
|
|
663
|
+
detail: input.detail ?? {}
|
|
664
|
+
});
|
|
665
|
+
while (this.eventRing.length > MAX_EVENTS) this.eventRing.shift();
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Read recorded events, oldest first.
|
|
669
|
+
*
|
|
670
|
+
* `since` is exclusive ("give me what happened after seq N"), which makes it the
|
|
671
|
+
* natural cursor: pass the `lastSeq` of the previous call. `truncated` says the
|
|
672
|
+
* requested window is no longer in the ring, so the caller knows it missed
|
|
673
|
+
* entries instead of assuming it saw everything.
|
|
674
|
+
*/
|
|
675
|
+
events(options = {}) {
|
|
676
|
+
const limit = Math.max(1, Math.min(options.limit ?? 100, MAX_EVENTS));
|
|
677
|
+
const since = options.since ?? 0;
|
|
678
|
+
const available = this.eventRing.filter((event) => event.seq > since);
|
|
679
|
+
const truncated = since > 0 && available.length > 0 && available[0].seq > since + 1;
|
|
680
|
+
return {
|
|
681
|
+
events: available.slice(-limit),
|
|
682
|
+
lastSeq: this.eventSeq,
|
|
683
|
+
truncated
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
/** The task hook, plus the event it implies.
|
|
687
|
+
*
|
|
688
|
+
* Every status change in this class already reports through
|
|
689
|
+
* `options.onTaskChanged`, so recording the event HERE needs no new call sites:
|
|
690
|
+
* the hook IS the transition signal. That is also why the event can carry the
|
|
691
|
+
* aggregate status without the caller having to say what changed — it is read
|
|
692
|
+
* from the record at the moment the transition is announced. */
|
|
693
|
+
taskChanged(record) {
|
|
694
|
+
if (record !== void 0) {
|
|
695
|
+
this.recordEvent("task_transition", {
|
|
696
|
+
peer: record.from,
|
|
697
|
+
detail: { taskId: record.id, status: record.status, assignees: record.assignees.length }
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
this.options.onTaskChanged?.(record);
|
|
701
|
+
}
|
|
702
|
+
/** Record an event from outside the hub.
|
|
703
|
+
*
|
|
704
|
+
* The runner layer lives in `index.ts` and knows when a run starts and ends,
|
|
705
|
+
* which the hub cannot see. Deliberately narrow: a caller can ADD an event but
|
|
706
|
+
* cannot read or clear the ring through this.
|
|
707
|
+
*/
|
|
708
|
+
noteEvent(kind, input = {}) {
|
|
709
|
+
this.recordEvent(kind, input);
|
|
710
|
+
}
|
|
711
|
+
/** Append one event to a task's ack timeline, keeping the timeline bounded
|
|
712
|
+
* (see {@link MAX_TASK_ACKS}). */
|
|
713
|
+
pushAckEvent(record, event) {
|
|
714
|
+
record.acks.push(event);
|
|
715
|
+
this.trimAcks(record.acks);
|
|
716
|
+
}
|
|
717
|
+
/** Append one event to one assignee's timeline, with the SAME bound
|
|
718
|
+
* ({@link MAX_TASK_ACKS}). A single assignee that keeps acking `working`
|
|
719
|
+
* grows its own timeline without limit otherwise — and `exportTasks`
|
|
720
|
+
* serializes the whole ledger on every flush. */
|
|
721
|
+
pushAssigneeAck(assignee, event) {
|
|
722
|
+
assignee.acks.push({ ...event });
|
|
723
|
+
this.trimAcks(assignee.acks);
|
|
724
|
+
}
|
|
725
|
+
/** Evict from one ack timeline until it fits {@link MAX_TASK_ACKS}.
|
|
726
|
+
*
|
|
727
|
+
* Order, oldest first within each class:
|
|
728
|
+
* 1. a `system: true` event is protected to the very end. Those rows are the
|
|
729
|
+
* DROP EVIDENCE (`noteTaskDeliveryDropped` writes `applied: false,
|
|
730
|
+
* system: true`), and a long task acking `working` 200 times would
|
|
731
|
+
* otherwise throw away "this delivery was lost" before a single chatty
|
|
732
|
+
* status update — the one thing a reader must be able to find out.
|
|
733
|
+
* 2. then an `applied: false` ack: it recorded a rejection and moved no
|
|
734
|
+
* ledger state.
|
|
735
|
+
* 3. then any non-system ack (the audited transitions a reader wants).
|
|
736
|
+
* 4. only if the timeline is STILL over the limit: a system row. */
|
|
737
|
+
trimAcks(events) {
|
|
738
|
+
while (events.length > MAX_TASK_ACKS) {
|
|
739
|
+
let victim = events.findIndex((item) => item.system !== true && item.applied !== true);
|
|
740
|
+
if (victim < 0) victim = events.findIndex((item) => item.system !== true);
|
|
741
|
+
if (victim < 0) victim = 0;
|
|
742
|
+
events.splice(victim, 1);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
487
745
|
waiters = /* @__PURE__ */ new Map();
|
|
488
746
|
historyRing = [];
|
|
747
|
+
/** Structured operational events, newest last. A ring, not a log: the hub is a
|
|
748
|
+
* long-running process and an unbounded event list is a leak. See {@link events}. */
|
|
749
|
+
eventRing = [];
|
|
750
|
+
eventSeq = 0;
|
|
489
751
|
lastSeen = /* @__PURE__ */ new Map();
|
|
490
752
|
/** Identity metadata keyed by peer id; outlives registration (see {@link PeerProfile}). */
|
|
491
753
|
profiles = /* @__PURE__ */ new Map();
|
|
@@ -508,9 +770,163 @@ var AgentHub = class {
|
|
|
508
770
|
if (now - (this.lastSeen.get(peerId) ?? 0) > idleTimeoutMs) {
|
|
509
771
|
if (this.options.isPeerLive?.(peerId) === true) continue;
|
|
510
772
|
this.options.onPeerGc?.(peerId);
|
|
511
|
-
this.unregister(peerId);
|
|
773
|
+
this.unregister(peerId, { keepMailbox: true });
|
|
512
774
|
}
|
|
513
775
|
}
|
|
776
|
+
for (const peerId of [...this.leases.keys()]) this.reapLeases(peerId, now);
|
|
777
|
+
this.expireParkedMailboxes(now);
|
|
778
|
+
}
|
|
779
|
+
/** Drop parked mailboxes older than `parkedTtlMs` (0 disables expiry). */
|
|
780
|
+
expireParkedMailboxes(now) {
|
|
781
|
+
const ttl = this.options.parkedTtlMs ?? DEFAULT_PARKED_TTL_MS;
|
|
782
|
+
if (ttl <= 0) return;
|
|
783
|
+
for (const [peerId, parkedMs] of [...this.parkedAt]) {
|
|
784
|
+
if (this.lastSeen.has(peerId)) {
|
|
785
|
+
this.parkedAt.delete(peerId);
|
|
786
|
+
continue;
|
|
787
|
+
}
|
|
788
|
+
if (now - parkedMs <= ttl) continue;
|
|
789
|
+
const dropped = this.dropMailboxState(
|
|
790
|
+
peerId,
|
|
791
|
+
(message) => this.failTaskForGoneAssignee(message.id, peerId, now, ttl)
|
|
792
|
+
).length;
|
|
793
|
+
if (dropped > 0) {
|
|
794
|
+
this.options.onMailboxesChanged?.();
|
|
795
|
+
this.recordEvent("mailbox_dropped", { peer: peerId, detail: { reason: "expired", dropped, ttlMs: ttl } });
|
|
796
|
+
this.options.onMailboxExpired?.(peerId, dropped);
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
/** Reconcile the task ledger after `peerId`'s parked mailbox was destroyed with
|
|
801
|
+
* the task still inside it.
|
|
802
|
+
*
|
|
803
|
+
* The task fails as a SYSTEM event, not as an ack: nobody acked anything, the
|
|
804
|
+
* peer simply never came back. Marking only this assignee's row keeps a
|
|
805
|
+
* broadcast task's other recipients intact, and the aggregate status is
|
|
806
|
+
* recomputed the same way every other transition does it. */
|
|
807
|
+
failTaskForGoneAssignee(taskId, peerId, now, ttl) {
|
|
808
|
+
const record = this.taskLedger.get(taskId);
|
|
809
|
+
if (record === void 0) return;
|
|
810
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) return;
|
|
811
|
+
const assignee = record.assignees.find((a) => a.peerId === peerId);
|
|
812
|
+
if (assignee === void 0 || TERMINAL_TASK_STATUSES.includes(assignee.status)) return;
|
|
813
|
+
const event = {
|
|
814
|
+
from: peerId,
|
|
815
|
+
status: "failed",
|
|
816
|
+
note: `recipient '${peerId}' never came back: its parked mailbox expired after ${ttl}ms and the task was dropped with it`,
|
|
817
|
+
ts: now,
|
|
818
|
+
messageId: syntheticEventId(taskId, "expired"),
|
|
819
|
+
applied: true,
|
|
820
|
+
system: true
|
|
821
|
+
};
|
|
822
|
+
this.pushAckEvent(record, event);
|
|
823
|
+
assignee.status = "failed";
|
|
824
|
+
this.pushAssigneeAck(assignee, event);
|
|
825
|
+
record.status = aggregateTaskStatus(record.assignees);
|
|
826
|
+
record.updatedAt = now;
|
|
827
|
+
this.realignTaskTimer(record);
|
|
828
|
+
this.taskChanged(this.taskOf(taskId));
|
|
829
|
+
this.notifyTaskEnded(record, `recipient '${peerId}' never came back: its parked mailbox expired after ${ttl}ms and its copy of the task was dropped with it`);
|
|
830
|
+
}
|
|
831
|
+
/** Tell the SENDER of `record` that this delivery is over for good — the one
|
|
832
|
+
* thing it has to act on (re-send the task, or abandon it).
|
|
833
|
+
*
|
|
834
|
+
* Guarded by the same reachability precheck as {@link noteTaskDeliveryDropped}:
|
|
835
|
+
* a sender that has itself left the hub has nobody to warn, and `route` would
|
|
836
|
+
* throw on the drop path. Best effort by design — a terminal verdict is
|
|
837
|
+
* already in the ledger whether or not the notice can be delivered. */
|
|
838
|
+
notifyTaskEnded(record, why) {
|
|
839
|
+
if (!this.lastSeen.has(record.from) && !this.parkedAt.has(record.from)) return;
|
|
840
|
+
this.route(HUB_PEER, record.from, "notice", encodeContent({
|
|
841
|
+
message: `task ${record.id}: ${why}. That copy of the task can never be picked up or acked (task status: ${record.status}) \u2014 bridge_task can re-send it, or consider it abandoned.`,
|
|
842
|
+
level: "warn"
|
|
843
|
+
}), void 0, record.threadId, void 0, true);
|
|
844
|
+
}
|
|
845
|
+
/** Reconcile the task ledger after a `task` message was dropped for `peerId`
|
|
846
|
+
* because the PEER ITSELF is gone.
|
|
847
|
+
*
|
|
848
|
+
* This is one of exactly TWO drops that write a terminal state, and both mean
|
|
849
|
+
* the same thing — the recipient can never recover the task: this one (the
|
|
850
|
+
* peer left the hub, or a manager kicked it) and
|
|
851
|
+
* {@link failTaskForGoneAssignee} (its parked mailbox expired after
|
|
852
|
+
* `parkedTtlMs`). Terminal is right there on purpose: the assignee no longer
|
|
853
|
+
* exists, so there is no path back — no revival, no later ack — and a
|
|
854
|
+
* `pending` row would leave the sender waiting forever. Every other drop
|
|
855
|
+
* reason (`expired`, `rate`, `overflow`, dead-letter) stays NON-terminal
|
|
856
|
+
* instead (see {@link noteTaskDeliveryDropped}), because:
|
|
857
|
+
* - a dead letter can be revived with `bridge_nack`, and a task already
|
|
858
|
+
* marked `failed` would then refuse the revived assignee's `done`
|
|
859
|
+
* (`nextTaskStatus('failed', 'done')` is null → `applied: false`), so the
|
|
860
|
+
* sender would see a failure the hub itself declared unfixable;
|
|
861
|
+
* - `overflow` and `rate` are driven by THIRD-PARTY traffic — any peer
|
|
862
|
+
* sending ~maxQueue messages can push a task out of someone else's mailbox
|
|
863
|
+
* — so a terminal write there is a veto any peer can exercise over a task
|
|
864
|
+
* it was never assigned.
|
|
865
|
+
*
|
|
866
|
+
* Like the parked-mail reconcile, the failure is a SYSTEM event (nobody acked
|
|
867
|
+
* anything), only this assignee's row is marked — a fan-out task's other
|
|
868
|
+
* recipients keep their state — and the aggregate is recomputed the way every
|
|
869
|
+
* other transition does it. `reason` is the drop kind the caller counted, so
|
|
870
|
+
* the note and the `mailbox_dropped` event can be read together. */
|
|
871
|
+
failTaskForDroppedMessage(message, peerId, reason, now) {
|
|
872
|
+
const record = this.taskLedger.get(message.id);
|
|
873
|
+
if (record === void 0) return;
|
|
874
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) return;
|
|
875
|
+
const assignee = record.assignees.find((a) => a.peerId === peerId);
|
|
876
|
+
if (assignee === void 0 || TERMINAL_TASK_STATUSES.includes(assignee.status)) return;
|
|
877
|
+
const event = {
|
|
878
|
+
from: peerId,
|
|
879
|
+
status: "failed",
|
|
880
|
+
note: `message dropped for '${peerId}' (${reason}): the task will never be handed to it and cannot be acked`,
|
|
881
|
+
ts: now,
|
|
882
|
+
messageId: syntheticEventId(record.id, reason),
|
|
883
|
+
applied: true,
|
|
884
|
+
system: true
|
|
885
|
+
};
|
|
886
|
+
this.pushAckEvent(record, event);
|
|
887
|
+
assignee.status = "failed";
|
|
888
|
+
delete assignee.deliveredMs;
|
|
889
|
+
this.pushAssigneeAck(assignee, event);
|
|
890
|
+
record.status = aggregateTaskStatus(record.assignees);
|
|
891
|
+
record.updatedAt = now;
|
|
892
|
+
this.realignTaskTimer(record);
|
|
893
|
+
this.taskChanged(this.taskOf(record.id));
|
|
894
|
+
this.notifyTaskEnded(record, reason === "dead-letter-evicted" ? `its last copy for '${peerId}' was evicted from the dead letters (${reason}) and can never be revived` : `'${peerId}' left the hub (${reason}) and its queued copy of the task went with it`);
|
|
895
|
+
}
|
|
896
|
+
/** Record that one delivery of a task was dropped, WITHOUT closing the task.
|
|
897
|
+
*
|
|
898
|
+
* Two things happen and nothing else (`expired` / `rate` / `overflow` /
|
|
899
|
+
* dead-letter drops all land here; `unregister` keeps the terminal reconcile
|
|
900
|
+
* above):
|
|
901
|
+
* 1. the ledger gets a `system: true, applied: false` event naming the drop —
|
|
902
|
+
* `applied: false` is the whole point, it says "recorded, state untouched";
|
|
903
|
+
* 2. the task's SENDER gets a `notice` from the hub: it is the only party
|
|
904
|
+
* that can react (re-send, or revive a dead letter with `bridge_nack`).
|
|
905
|
+
* ONE notice per task, not per dropped copy — see `dropNotified`.
|
|
906
|
+
*
|
|
907
|
+
* See {@link failTaskForDroppedMessage} for why a terminal write here would
|
|
908
|
+
* be wrong. */
|
|
909
|
+
noteTaskDeliveryDropped(message, peerId, reason, now) {
|
|
910
|
+
const record = this.taskLedger.get(message.id);
|
|
911
|
+
if (record === void 0) return;
|
|
912
|
+
this.pushAckEvent(record, {
|
|
913
|
+
from: peerId,
|
|
914
|
+
status: "failed",
|
|
915
|
+
note: `a delivery of this task to '${peerId}' was dropped (${reason}); the task itself is unchanged and still waiting`,
|
|
916
|
+
ts: now,
|
|
917
|
+
messageId: syntheticEventId(record.id, reason),
|
|
918
|
+
applied: false,
|
|
919
|
+
system: true
|
|
920
|
+
});
|
|
921
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) return;
|
|
922
|
+
if (record.dropNotified !== void 0) return;
|
|
923
|
+
if (!this.lastSeen.has(record.from) && !this.parkedAt.has(record.from)) return;
|
|
924
|
+
record.dropNotified = now;
|
|
925
|
+
const hint = reason === "dead-letter" ? ` \u2014 the copy is parked in the dead letters of '${peerId}', so only that peer can revive it (bridge_nack { ids: ["${message.id}"] }); you can also re-issue the task` : " \u2014 bridge_task_status shows the task, bridge_notice or bridge_task can re-send it";
|
|
926
|
+
this.route(HUB_PEER, record.from, "notice", encodeContent({
|
|
927
|
+
message: `task ${record.id}: a delivery of it to '${peerId}' was dropped (${reason}). The task is still open${hint}.`,
|
|
928
|
+
level: "warn"
|
|
929
|
+
}), void 0, record.threadId, void 0, true);
|
|
514
930
|
}
|
|
515
931
|
/** All registered peer ids, insertion order. */
|
|
516
932
|
peers() {
|
|
@@ -518,10 +934,24 @@ var AgentHub = class {
|
|
|
518
934
|
}
|
|
519
935
|
/** Register a peer; throws if the id is already taken. Client metadata
|
|
520
936
|
* (when provided) refreshes the profile — with same-name sessions sharing a
|
|
521
|
-
* peer, the freshest connect wins, which self-heals stale metadata.
|
|
522
|
-
|
|
937
|
+
* peer, the freshest connect wins, which self-heals stale metadata.
|
|
938
|
+
*
|
|
939
|
+
* `reclaim` is the caller asserting "this id is my own identity coming back":
|
|
940
|
+
* a parked peer still owns its mailbox, and only the identity may unwrap it
|
|
941
|
+
* into use again (see {@link ownsMailbox}). Every caller has to say so
|
|
942
|
+
* explicitly, so a new path cannot inherit someone else's mail by accident. */
|
|
943
|
+
register(peerId, client, options) {
|
|
944
|
+
if (peerId === BROADCAST) throw new Error(`reserved peer id: ${peerId} (it is the broadcast address)`);
|
|
945
|
+
if (peerId === HUB_PEER) throw new Error(`reserved peer id: ${peerId} (the hub uses it for its own notices)`);
|
|
946
|
+
if (this.groups.has(peerId)) {
|
|
947
|
+
throw new Error(`peer id '${peerId}' collides with a group: peer and group ids share one 'to' namespace, and the group would take every message addressed to it`);
|
|
948
|
+
}
|
|
523
949
|
if (this.lastSeen.has(peerId)) throw new Error(`peer already registered: ${peerId}`);
|
|
950
|
+
if (!(options?.reclaim === true) && this.ownsMailbox(peerId)) {
|
|
951
|
+
throw new Error(`peer id '${peerId}' is parked: it still owns a mailbox for the peer that went quiet (only that identity can reclaim it; a manager can release it with bridge_unregister { peer })`);
|
|
952
|
+
}
|
|
524
953
|
this.lastSeen.set(peerId, Date.now());
|
|
954
|
+
this.parkedAt.delete(peerId);
|
|
525
955
|
const existing = this.profiles.get(peerId);
|
|
526
956
|
this.profiles.set(peerId, {
|
|
527
957
|
...existing,
|
|
@@ -531,13 +961,28 @@ var AgentHub = class {
|
|
|
531
961
|
...client?.version !== void 0 ? { clientVersion: client.version } : existing?.clientVersion !== void 0 ? { clientVersion: existing.clientVersion } : {}
|
|
532
962
|
});
|
|
533
963
|
this.evictOverflowProfiles();
|
|
964
|
+
this.recordEvent("peer_joined", { peer: peerId, detail: { clientName: client?.name } });
|
|
534
965
|
this.options.onPeersChanged?.(this.peers());
|
|
535
966
|
}
|
|
536
|
-
/** Remove a peer
|
|
537
|
-
*
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
967
|
+
/** Remove a peer; pending waiters resolve as timeouts. The profile is kept so
|
|
968
|
+
* a reconnecting peer keeps its alias.
|
|
969
|
+
*
|
|
970
|
+
* `keepMailbox` is what the idle GC passes: the peer's queued messages stay in
|
|
971
|
+
* `queues` (marked parked) so a returning agent drains what was sent while it
|
|
972
|
+
* was away. An explicit `bridge_unregister` and a manager kick leave it off,
|
|
973
|
+
* i.e. they still drop the mail — leaving the hub is a deliberate act. */
|
|
974
|
+
unregister(peerId, options) {
|
|
975
|
+
const queue = this.queues.get(peerId) ?? [];
|
|
976
|
+
const keep = options?.keepMailbox === true;
|
|
977
|
+
if (queue.length > 0) this.options.onMailboxesChanged?.();
|
|
978
|
+
if (keep) {
|
|
979
|
+
this.parkedAt.set(peerId, Date.now());
|
|
980
|
+
this.recordEvent("peer_parked", { peer: peerId, detail: { queued: queue.length } });
|
|
981
|
+
} else {
|
|
982
|
+
this.recordEvent("peer_left", { peer: peerId, detail: { queued: queue.length } });
|
|
983
|
+
const now = Date.now();
|
|
984
|
+
this.dropMailboxState(peerId, (message) => this.failTaskForDroppedMessage(message, peerId, "unregistered", now));
|
|
985
|
+
}
|
|
541
986
|
for (const waiter of this.waiters.get(peerId) ?? []) {
|
|
542
987
|
clearTimeout(waiter.timer);
|
|
543
988
|
waiter.onAbort();
|
|
@@ -546,6 +991,35 @@ var AgentHub = class {
|
|
|
546
991
|
this.lastSeen.delete(peerId);
|
|
547
992
|
this.options.onPeersChanged?.(this.peers());
|
|
548
993
|
}
|
|
994
|
+
/** Forget EVERYTHING a mailbox owns — queue, in-flight leases, dead letters
|
|
995
|
+
* and the per-message attempt counters — in one step, calling `reconcile` on
|
|
996
|
+
* the tasks found in any of them.
|
|
997
|
+
*
|
|
998
|
+
* The pieces have to go together. Anything left behind does not just leak: a
|
|
999
|
+
* lease that outlives its mailbox is re-queued by the next reap under a peer
|
|
1000
|
+
* that has neither a registration nor a `parkedAt`, so no take and no TTL
|
|
1001
|
+
* sweep ever sees it and the message (and its task) stays pending forever.
|
|
1002
|
+
* Both callers — an explicit `unregister` (the peer left) and
|
|
1003
|
+
* `expireParkedMailboxes` (the parked TTL ran out) — mean the same thing
|
|
1004
|
+
* here, and only the ledger verdict differs, which is why that is the
|
|
1005
|
+
* parameter. Returns every message that went with the mailbox. */
|
|
1006
|
+
dropMailboxState(peerId, reconcile) {
|
|
1007
|
+
const queue = this.queues.get(peerId) ?? [];
|
|
1008
|
+
const inFlight = (this.leases.get(peerId) ?? []).map((lease) => lease.message);
|
|
1009
|
+
const deadLettered = this.deadLetters.get(peerId) ?? [];
|
|
1010
|
+
this.leases.delete(peerId);
|
|
1011
|
+
this.deadLetters.delete(peerId);
|
|
1012
|
+
for (const key of [...this.leaseAttempts.keys()]) {
|
|
1013
|
+
if (key.startsWith(`${peerId}\0`)) this.leaseAttempts.delete(key);
|
|
1014
|
+
}
|
|
1015
|
+
this.queues.delete(peerId);
|
|
1016
|
+
this.parkedAt.delete(peerId);
|
|
1017
|
+
const all = [...queue, ...inFlight, ...deadLettered];
|
|
1018
|
+
for (const message of all) {
|
|
1019
|
+
if (message.kind === "task") reconcile(message);
|
|
1020
|
+
}
|
|
1021
|
+
return all;
|
|
1022
|
+
}
|
|
549
1023
|
/** Identity metadata for `peerId`, if the hub ever saw it. */
|
|
550
1024
|
profileOf(peerId) {
|
|
551
1025
|
return this.profiles.get(peerId);
|
|
@@ -554,6 +1028,44 @@ var AgentHub = class {
|
|
|
554
1028
|
exportProfiles() {
|
|
555
1029
|
return [...this.profiles.values()].map((profile) => ({ ...profile }));
|
|
556
1030
|
}
|
|
1031
|
+
/** Record what a peer says about itself. Creates the profile if the peer is
|
|
1032
|
+
* new: a card is identity, and identity outlives a connection. */
|
|
1033
|
+
announceCard(peerId, card) {
|
|
1034
|
+
const existing = this.profiles.get(peerId);
|
|
1035
|
+
const profile = { ...existing, id: peerId, registeredAt: existing?.registeredAt ?? Date.now(), card };
|
|
1036
|
+
this.profiles.set(peerId, profile);
|
|
1037
|
+
this.evictOverflowProfiles();
|
|
1038
|
+
this.options.onPeersChanged?.(this.peers());
|
|
1039
|
+
return profile;
|
|
1040
|
+
}
|
|
1041
|
+
/** Every peer whose announced card matches `filter`, with the load a caller
|
|
1042
|
+
* needs to pick one.
|
|
1043
|
+
*
|
|
1044
|
+
* `acceptsTasks` defaults to TRUE — and that default is the point: discover is
|
|
1045
|
+
* for finding somebody to HAND WORK TO, and "has a skill" is not "wants a
|
|
1046
|
+
* task". Pass `false` to drop the requirement and list peers regardless. */
|
|
1047
|
+
discover(filter = {}) {
|
|
1048
|
+
const requireAccept = filter.acceptsTasks !== false;
|
|
1049
|
+
const out = [];
|
|
1050
|
+
for (const profile of this.profiles.values()) {
|
|
1051
|
+
const card = profile.card;
|
|
1052
|
+
if (card === void 0) continue;
|
|
1053
|
+
if (requireAccept && card.acceptsTasks !== true) continue;
|
|
1054
|
+
const skills = card.skills ?? [];
|
|
1055
|
+
if (filter.skill !== void 0 && !skills.some((skill) => skill.id === filter.skill)) continue;
|
|
1056
|
+
if (filter.tag !== void 0 && !skills.some((skill) => (skill.tags ?? []).includes(filter.tag))) continue;
|
|
1057
|
+
const load = {
|
|
1058
|
+
queued: this.queues.get(profile.id)?.length ?? 0,
|
|
1059
|
+
waiting: this.waiters.get(profile.id)?.length ?? 0,
|
|
1060
|
+
running: [...this.taskLedger.values()].filter(
|
|
1061
|
+
(record) => !TERMINAL_TASK_STATUSES.includes(record.status) && record.assignees.some((a) => a.peerId === profile.id)
|
|
1062
|
+
).length
|
|
1063
|
+
};
|
|
1064
|
+
if (filter.idleOnly === true && (load.queued > 0 || load.waiting > 0 || load.running > 0)) continue;
|
|
1065
|
+
out.push({ peerId: profile.id, ...profile.alias !== void 0 ? { alias: profile.alias } : {}, card, load });
|
|
1066
|
+
}
|
|
1067
|
+
return out;
|
|
1068
|
+
}
|
|
557
1069
|
/** Load persisted profiles at boot. Invalid entries are dropped; `null`-ish
|
|
558
1070
|
* and non-finite fields are sanitized. Returns the imported count. Silent
|
|
559
1071
|
* for roster observers — this runs before the server accepts requests. */
|
|
@@ -564,7 +1076,7 @@ var AgentHub = class {
|
|
|
564
1076
|
if (typeof raw !== "object" || raw === null) continue;
|
|
565
1077
|
const candidate = raw;
|
|
566
1078
|
const id = candidate.id;
|
|
567
|
-
if (typeof id !== "string" || !PEER_ID_PATTERN.test(id) || id === BROADCAST) continue;
|
|
1079
|
+
if (typeof id !== "string" || !PEER_ID_PATTERN.test(id) || id === BROADCAST || id === HUB_PEER) continue;
|
|
568
1080
|
if (this.profiles.has(id)) continue;
|
|
569
1081
|
const profile = {
|
|
570
1082
|
id,
|
|
@@ -573,6 +1085,7 @@ var AgentHub = class {
|
|
|
573
1085
|
if (typeof candidate.alias === "string" && candidate.alias !== "") profile.alias = candidate.alias;
|
|
574
1086
|
if (typeof candidate.clientName === "string" && candidate.clientName !== "") profile.clientName = candidate.clientName;
|
|
575
1087
|
if (typeof candidate.clientVersion === "string" && candidate.clientVersion !== "") profile.clientVersion = candidate.clientVersion;
|
|
1088
|
+
if (candidate.card !== null && typeof candidate.card === "object") profile.card = candidate.card;
|
|
576
1089
|
this.profiles.set(id, profile);
|
|
577
1090
|
count++;
|
|
578
1091
|
}
|
|
@@ -600,19 +1113,41 @@ var AgentHub = class {
|
|
|
600
1113
|
if (oldId === newId) return;
|
|
601
1114
|
if (!this.lastSeen.has(oldId)) throw new Error(`unknown peer: ${oldId}`);
|
|
602
1115
|
if (newId === BROADCAST) throw new Error(`reserved peer id: ${newId}`);
|
|
1116
|
+
if (newId === HUB_PEER) throw new Error(`reserved peer id: ${newId}`);
|
|
603
1117
|
if (!PEER_ID_PATTERN.test(newId)) throw new Error(`invalid peerId: ${newId} (expected [A-Za-z0-9._:-]{1,64})`);
|
|
604
1118
|
if (this.lastSeen.has(newId)) throw new Error(`peer already registered: ${newId}`);
|
|
1119
|
+
if (this.groups.has(newId)) {
|
|
1120
|
+
throw new Error(`peer id '${newId}' collides with a group: peer and group ids share one 'to' namespace, and the group would take every message addressed to it`);
|
|
1121
|
+
}
|
|
1122
|
+
if (this.ownsMailbox(newId)) {
|
|
1123
|
+
throw new Error(`peer id '${newId}' is parked: it still owns a mailbox and will be delivered to when its owner returns (its owner takes it back with bridge_register { peerId }; a manager can release it with bridge_unregister { peer })`);
|
|
1124
|
+
}
|
|
605
1125
|
const queue = this.queues.get(oldId);
|
|
606
1126
|
const waiters = this.waiters.get(oldId);
|
|
607
1127
|
const seen = this.lastSeen.get(oldId) ?? Date.now();
|
|
608
1128
|
const profile = this.profiles.get(oldId);
|
|
609
1129
|
const stale = this.profiles.get(newId);
|
|
1130
|
+
this.parkedAt.delete(oldId);
|
|
1131
|
+
this.parkedAt.delete(newId);
|
|
610
1132
|
this.queues.delete(oldId);
|
|
611
1133
|
this.waiters.delete(oldId);
|
|
612
1134
|
this.lastSeen.delete(oldId);
|
|
613
1135
|
this.profiles.delete(oldId);
|
|
614
1136
|
if (queue !== void 0) this.queues.set(newId, queue);
|
|
615
1137
|
if (waiters !== void 0) this.waiters.set(newId, waiters);
|
|
1138
|
+
const leases = this.leases.get(oldId);
|
|
1139
|
+
const deadLetters = this.deadLetters.get(oldId);
|
|
1140
|
+
this.leases.delete(oldId);
|
|
1141
|
+
this.deadLetters.delete(oldId);
|
|
1142
|
+
if (leases !== void 0) this.leases.set(newId, leases);
|
|
1143
|
+
if (deadLetters !== void 0) this.deadLetters.set(newId, deadLetters);
|
|
1144
|
+
const oldLeasePrefix = _AgentHub.leaseKey(oldId, "");
|
|
1145
|
+
for (const key of [...this.leaseAttempts.keys()]) {
|
|
1146
|
+
if (!key.startsWith(oldLeasePrefix)) continue;
|
|
1147
|
+
const attempts = this.leaseAttempts.get(key);
|
|
1148
|
+
this.leaseAttempts.delete(key);
|
|
1149
|
+
if (attempts !== void 0) this.leaseAttempts.set(_AgentHub.leaseKey(newId, key.slice(oldLeasePrefix.length)), attempts);
|
|
1150
|
+
}
|
|
616
1151
|
this.lastSeen.set(newId, seen);
|
|
617
1152
|
if (profile !== void 0) {
|
|
618
1153
|
const merged = {
|
|
@@ -636,8 +1171,71 @@ var AgentHub = class {
|
|
|
636
1171
|
if (message.from === oldId) message.from = newId;
|
|
637
1172
|
if (message.to === oldId) message.to = newId;
|
|
638
1173
|
}
|
|
1174
|
+
for (const record of this.taskLedger.values()) {
|
|
1175
|
+
if (record.from === oldId) record.from = newId;
|
|
1176
|
+
if (record.to === oldId && !this.groups.has(oldId)) record.to = newId;
|
|
1177
|
+
for (const event of record.acks) if (event.from === oldId) event.from = newId;
|
|
1178
|
+
for (const assignee of record.assignees) {
|
|
1179
|
+
if (assignee.peerId === oldId) assignee.peerId = newId;
|
|
1180
|
+
for (const event of assignee.acks) if (event.from === oldId) event.from = newId;
|
|
1181
|
+
}
|
|
1182
|
+
this.foldDuplicateAssignees(record);
|
|
1183
|
+
}
|
|
1184
|
+
let groupsChanged = false;
|
|
1185
|
+
for (const group of this.groups.values()) {
|
|
1186
|
+
if (!group.members.includes(oldId)) continue;
|
|
1187
|
+
group.members = [...new Set(group.members.map((member) => member === oldId ? newId : member))];
|
|
1188
|
+
groupsChanged = true;
|
|
1189
|
+
}
|
|
1190
|
+
if (groupsChanged) this.options.onGroupsChanged?.();
|
|
639
1191
|
this.options.onPeersChanged?.(this.peers());
|
|
640
1192
|
}
|
|
1193
|
+
/** Collapse assignee rows that ended up sharing a `peerId` (a rename onto an
|
|
1194
|
+
* id the task already had a row for).
|
|
1195
|
+
*
|
|
1196
|
+
* Duplicate rows break the ledger: `applyAckToLedger` finds the FIRST row for
|
|
1197
|
+
* the acking peer, so the second one never advances and the aggregate can sit
|
|
1198
|
+
* on a status no row supports. The merge prefers the row that is still open
|
|
1199
|
+
* (a rename must not close a task), keeps both timelines, and keeps the
|
|
1200
|
+
* EARLIEST delivery booking. */
|
|
1201
|
+
foldDuplicateAssignees(record) {
|
|
1202
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1203
|
+
let duplicated = false;
|
|
1204
|
+
for (const assignee of record.assignees) {
|
|
1205
|
+
if (seen.has(assignee.peerId)) {
|
|
1206
|
+
duplicated = true;
|
|
1207
|
+
break;
|
|
1208
|
+
}
|
|
1209
|
+
seen.add(assignee.peerId);
|
|
1210
|
+
}
|
|
1211
|
+
if (!duplicated) return;
|
|
1212
|
+
const wasTerminal = TERMINAL_TASK_STATUSES.includes(record.status);
|
|
1213
|
+
const byPeer = /* @__PURE__ */ new Map();
|
|
1214
|
+
const folded = [];
|
|
1215
|
+
for (const assignee of record.assignees) {
|
|
1216
|
+
const first = byPeer.get(assignee.peerId);
|
|
1217
|
+
if (first === void 0) {
|
|
1218
|
+
const copy = { ...assignee, acks: [...assignee.acks] };
|
|
1219
|
+
byPeer.set(assignee.peerId, copy);
|
|
1220
|
+
folded.push(copy);
|
|
1221
|
+
continue;
|
|
1222
|
+
}
|
|
1223
|
+
const firstOpen = !TERMINAL_TASK_STATUSES.includes(first.status);
|
|
1224
|
+
if (!(firstOpen && TERMINAL_TASK_STATUSES.includes(assignee.status))) {
|
|
1225
|
+
first.status = assignee.status;
|
|
1226
|
+
}
|
|
1227
|
+
first.acks.push(...assignee.acks);
|
|
1228
|
+
this.trimAcks(first.acks);
|
|
1229
|
+
if (assignee.deliveredMs !== void 0 && (first.deliveredMs === void 0 || assignee.deliveredMs < first.deliveredMs)) {
|
|
1230
|
+
first.deliveredMs = assignee.deliveredMs;
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
record.assignees = folded;
|
|
1234
|
+
record.status = aggregateTaskStatus(folded);
|
|
1235
|
+
if (wasTerminal && record.deadlineAt !== void 0 && !TERMINAL_TASK_STATUSES.includes(record.status)) {
|
|
1236
|
+
this.scheduleTaskTimeout(record);
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
641
1239
|
/** Keep the profile map bounded: drop the oldest profiles of peers that are
|
|
642
1240
|
* NOT currently registered (live peers are never evicted). */
|
|
643
1241
|
evictOverflowProfiles() {
|
|
@@ -658,6 +1256,20 @@ var AgentHub = class {
|
|
|
658
1256
|
has(peerId) {
|
|
659
1257
|
return this.lastSeen.has(peerId);
|
|
660
1258
|
}
|
|
1259
|
+
/** Does `peerId` still own state it never released — a parked record or a
|
|
1260
|
+
* queued mailbox? This is identity, not liveness: `has()` is false for such a
|
|
1261
|
+
* peer, yet the id is still taken. `register({ reclaim })` and `renamePeer`
|
|
1262
|
+
* both key off this, so "taken" cannot drift between the two write points. */
|
|
1263
|
+
ownsMailbox(peerId) {
|
|
1264
|
+
return this.parkedAt.has(peerId) || this.queues.has(peerId);
|
|
1265
|
+
}
|
|
1266
|
+
/** Is the peer parked — gone from the live registry through idle GC, but still
|
|
1267
|
+
* holding its mailbox and still addressable? `has()` is false for it, so a
|
|
1268
|
+
* guard written only as `has()` will decide there is nothing to do and leave
|
|
1269
|
+
* the peer reachable. A manager kick has to cover this state explicitly. */
|
|
1270
|
+
isParked(peerId) {
|
|
1271
|
+
return this.parkedAt.has(peerId);
|
|
1272
|
+
}
|
|
661
1273
|
/** Is the peer "active" (tool/activity within the connected window)? */
|
|
662
1274
|
isActive(peerId) {
|
|
663
1275
|
const last = this.lastSeen.get(peerId);
|
|
@@ -665,38 +1277,159 @@ var AgentHub = class {
|
|
|
665
1277
|
}
|
|
666
1278
|
/** Send a chat/notice text message to `to` (or {@link BROADCAST}). */
|
|
667
1279
|
send(from, to, kind, content, opts) {
|
|
668
|
-
return this.route(from, to, kind, content, opts?.ref, opts?.threadId);
|
|
1280
|
+
return this.route(from, to, kind, content, opts?.ref, opts?.threadId, opts?.expiresAt, false, opts?.priority);
|
|
669
1281
|
}
|
|
670
1282
|
/** Send a structured task message to `to` (peer, {@link BROADCAST}, or a
|
|
671
1283
|
* group id). Records a ledger entry so the sender can later query status /
|
|
672
|
-
* wait for acks.
|
|
673
|
-
|
|
1284
|
+
* wait for acks.
|
|
1285
|
+
*
|
|
1286
|
+
* `ref` marks the task this one answers. When the parent is itself a task the
|
|
1287
|
+
* new one is a **re-delegation**, and that chain is capped at {@link MAX_HOP}
|
|
1288
|
+
* — without a way to express the parent, the cap would be unreachable and a
|
|
1289
|
+
* hand-off loop unobservable. */
|
|
1290
|
+
sendTask(from, to, task, ref, expiresAt) {
|
|
674
1291
|
const threadId = task.threadId;
|
|
675
|
-
const message = this.compose(from, to, "task", JSON.stringify(task),
|
|
1292
|
+
const message = this.compose(from, to, "task", JSON.stringify(task), ref, threadId, expiresAt, false, task.priority);
|
|
676
1293
|
this.recordTask(message, task);
|
|
677
1294
|
this.dispatch(message);
|
|
678
1295
|
return message;
|
|
679
1296
|
}
|
|
680
1297
|
/** Send an acknowledgement back to the sender of `ref`. Updates the task
|
|
681
1298
|
* ledger when `ref` is a known task (looked up in the ledger first, so acks
|
|
682
|
-
* survive history-ring eviction); chat/notice refs still route via history.
|
|
1299
|
+
* survive history-ring eviction); chat/notice refs still route via history.
|
|
1300
|
+
*
|
|
1301
|
+
* Only an ASSIGNEE may ack a task. Everyone else could otherwise close someone
|
|
1302
|
+
* else's task — and land their own artifacts in it — just by learning the
|
|
1303
|
+
* message id. A ref that is not a task carries no ledger row to protect, so an
|
|
1304
|
+
* ack for chat/notice keeps routing without any permission check. The single
|
|
1305
|
+
* place this is decided is here: `bridge_ack` adds no rule of its own, so the
|
|
1306
|
+
* direct API (`ackForRunner`, an assignee by construction) is unaffected. */
|
|
683
1307
|
sendAck(from, ref, ack) {
|
|
684
1308
|
const task = this.taskLedger.get(ref);
|
|
685
1309
|
let target;
|
|
1310
|
+
let threadId;
|
|
686
1311
|
if (task !== void 0) {
|
|
1312
|
+
if (!task.assignees.some((assignee) => assignee.peerId === from)) {
|
|
1313
|
+
throw new Error("only an assignee of this task can ack it");
|
|
1314
|
+
}
|
|
687
1315
|
target = task.from;
|
|
1316
|
+
threadId = task.threadId;
|
|
688
1317
|
} else {
|
|
689
1318
|
const original = this.historyRing.findLast((message2) => message2.id === ref);
|
|
690
1319
|
if (!original) throw new Error(`cannot ack unknown message: ${ref}`);
|
|
691
1320
|
target = original.from;
|
|
1321
|
+
threadId = original.threadId;
|
|
692
1322
|
}
|
|
693
|
-
const message = this.route(from, target, "ack", JSON.stringify(ack), ref);
|
|
1323
|
+
const message = this.route(from, target, "ack", JSON.stringify(ack), ref, threadId);
|
|
694
1324
|
this.applyAckToLedger(message, from, ref, ack);
|
|
695
1325
|
return message;
|
|
696
1326
|
}
|
|
1327
|
+
/** Record an ack the hub produced ON BEHALF of a peer whose runner finished
|
|
1328
|
+
* its task (see `src/runner.ts`).
|
|
1329
|
+
*
|
|
1330
|
+
* Unlike {@link sendAck} the sender is not a live session — it may be parked,
|
|
1331
|
+
* or not connected at all — so the "sender must be registered" check does not
|
|
1332
|
+
* apply. This is the hub acting for a peer it is executing for, never a
|
|
1333
|
+
* caller-supplied identity; nothing from a request reaches `from` here.
|
|
1334
|
+
* Everything else (ledger update, routing to the task's sender) is identical. */
|
|
1335
|
+
ackForRunner(peer, ref, ack) {
|
|
1336
|
+
const task = this.taskLedger.get(ref);
|
|
1337
|
+
if (task === void 0) throw new Error(`runner cannot ack unknown task: ${ref}`);
|
|
1338
|
+
const message = this.route(peer, task.from, "ack", JSON.stringify(ack), ref, void 0, void 0, true);
|
|
1339
|
+
this.applyAckToLedger(message, peer, ref, ack);
|
|
1340
|
+
return message;
|
|
1341
|
+
}
|
|
1342
|
+
/** Cancel a task. EITHER side may do it — the sender stops work it no longer
|
|
1343
|
+
* wants, an assignee reports it will not finish — and the cancel is both
|
|
1344
|
+
* recorded on the ledger and routed to the OTHER side, so whoever did not
|
|
1345
|
+
* press the button finds out. Cancelling an already-terminal task is an error
|
|
1346
|
+
* rather than a silent no-op: the caller asked for something that did not
|
|
1347
|
+
* happen. */
|
|
1348
|
+
cancelTask(from, ref, reason) {
|
|
1349
|
+
const record = this.taskLedger.get(ref);
|
|
1350
|
+
if (record === void 0) throw new Error(`cannot cancel unknown task: ${ref}`);
|
|
1351
|
+
const isSender = from === record.from;
|
|
1352
|
+
if (!isSender && !record.assignees.some((a) => a.peerId === from)) {
|
|
1353
|
+
throw new Error(`only the sender or an assignee can cancel task ${ref}`);
|
|
1354
|
+
}
|
|
1355
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) {
|
|
1356
|
+
throw new Error(`task ${ref} is already ${record.status}`);
|
|
1357
|
+
}
|
|
1358
|
+
const ack = { status: "canceled", ...reason !== void 0 ? { note: reason } : {} };
|
|
1359
|
+
if (!isSender) {
|
|
1360
|
+
return this.sendAck(from, ref, ack);
|
|
1361
|
+
}
|
|
1362
|
+
let last;
|
|
1363
|
+
for (const assignee of record.assignees) {
|
|
1364
|
+
if (TERMINAL_TASK_STATUSES.includes(assignee.status)) continue;
|
|
1365
|
+
const message = this.route(from, assignee.peerId, "ack", JSON.stringify(ack), ref, record.threadId);
|
|
1366
|
+
const event = {
|
|
1367
|
+
from,
|
|
1368
|
+
status: "canceled",
|
|
1369
|
+
...reason !== void 0 ? { note: reason } : {},
|
|
1370
|
+
ts: message.ts,
|
|
1371
|
+
messageId: message.id,
|
|
1372
|
+
applied: true
|
|
1373
|
+
};
|
|
1374
|
+
this.pushAckEvent(record, event);
|
|
1375
|
+
assignee.status = "canceled";
|
|
1376
|
+
this.pushAssigneeAck(assignee, event);
|
|
1377
|
+
last = message;
|
|
1378
|
+
}
|
|
1379
|
+
if (last === void 0) throw new Error(`task ${ref} has no assignee left to cancel`);
|
|
1380
|
+
record.status = aggregateTaskStatus(record.assignees);
|
|
1381
|
+
record.updatedAt = last.ts;
|
|
1382
|
+
this.taskChanged(this.taskOf(ref));
|
|
1383
|
+
return last;
|
|
1384
|
+
}
|
|
1385
|
+
/** Answer an `input-required` interrupt. Only the task's SENDER can answer — it
|
|
1386
|
+
* is the side the assignee asked. The answer is delivered to the waiting
|
|
1387
|
+
* assignee as an `ack` carrying the task id, so a `bridge_wait { ref }` picks
|
|
1388
|
+
* it up, and the task resumes (`working`). */
|
|
1389
|
+
taskInput(from, ref, input) {
|
|
1390
|
+
const record = this.taskLedger.get(ref);
|
|
1391
|
+
if (record === void 0) throw new Error(`cannot answer unknown task: ${ref}`);
|
|
1392
|
+
if (from !== record.from) {
|
|
1393
|
+
throw new Error(`only the sender of task ${ref} can answer it (an assignee resumes by acking 'working')`);
|
|
1394
|
+
}
|
|
1395
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) {
|
|
1396
|
+
throw new Error(`task ${ref} is already ${record.status}`);
|
|
1397
|
+
}
|
|
1398
|
+
const waiting = record.assignees.filter((a) => a.status === "input-required");
|
|
1399
|
+
const targets = waiting.length > 0 ? waiting : record.assignees;
|
|
1400
|
+
const ack = { status: "working", note: input };
|
|
1401
|
+
let last;
|
|
1402
|
+
for (const assignee of targets) {
|
|
1403
|
+
const message = this.route(from, assignee.peerId, "ack", JSON.stringify(ack), ref, record.threadId);
|
|
1404
|
+
const event = { from, status: "working", note: input, ts: message.ts, messageId: message.id, applied: true };
|
|
1405
|
+
this.pushAckEvent(record, event);
|
|
1406
|
+
if (assignee.status === "input-required") {
|
|
1407
|
+
assignee.status = "working";
|
|
1408
|
+
this.pushAssigneeAck(assignee, event);
|
|
1409
|
+
}
|
|
1410
|
+
last = message;
|
|
1411
|
+
}
|
|
1412
|
+
if (last === void 0) throw new Error(`task ${ref} has no assignee to answer`);
|
|
1413
|
+
record.status = aggregateTaskStatus(record.assignees);
|
|
1414
|
+
record.updatedAt = last.ts;
|
|
1415
|
+
this.taskChanged(this.taskOf(ref));
|
|
1416
|
+
return last;
|
|
1417
|
+
}
|
|
1418
|
+
/** Every peer a fan-out can reach: the live registry **plus** parked peers.
|
|
1419
|
+
*
|
|
1420
|
+
* Parked peers keep their mailbox and stay addressable (that is the point of
|
|
1421
|
+
* parking, see {@link isParked}), and a group send already delivered to its
|
|
1422
|
+
* parked members because it reads the member list rather than the live roster.
|
|
1423
|
+
* Broadcast read the live roster, so `peer-x` showed up in `bridge_peers` as
|
|
1424
|
+
* addressable yet silently missed every broadcast. Both resolve here now. */
|
|
1425
|
+
audience() {
|
|
1426
|
+
const ids = new Set(this.lastSeen.keys());
|
|
1427
|
+
for (const id of this.parkedAt.keys()) ids.add(id);
|
|
1428
|
+
return [...ids];
|
|
1429
|
+
}
|
|
697
1430
|
/** Resolve the peer ids a task is assigned to (broadcast / group fan-out). */
|
|
698
1431
|
resolveAssignees(from, to) {
|
|
699
|
-
if (to === BROADCAST) return this.
|
|
1432
|
+
if (to === BROADCAST) return this.audience().filter((peer) => peer !== from);
|
|
700
1433
|
const group = this.groups.get(to);
|
|
701
1434
|
if (group !== void 0) return group.members.filter((member) => member !== from);
|
|
702
1435
|
return [to];
|
|
@@ -725,7 +1458,7 @@ var AgentHub = class {
|
|
|
725
1458
|
this.taskLedger.set(message.id, record);
|
|
726
1459
|
this.scheduleTaskTimeout(record);
|
|
727
1460
|
this.evictOverflowTasks();
|
|
728
|
-
this.
|
|
1461
|
+
this.taskChanged(this.taskOf(record.id));
|
|
729
1462
|
}
|
|
730
1463
|
/** Arm the SLA timer for a task that supplied `timeoutMs`. A deadline
|
|
731
1464
|
* beyond {@link MAX_TIMER_DELAY_MS} cannot be expressed as one delay — the
|
|
@@ -757,17 +1490,17 @@ var AgentHub = class {
|
|
|
757
1490
|
applied: true,
|
|
758
1491
|
system: true
|
|
759
1492
|
};
|
|
760
|
-
|
|
1493
|
+
this.pushAckEvent(record, event);
|
|
761
1494
|
for (const assignee of record.assignees) {
|
|
762
1495
|
if (!TERMINAL_TASK_STATUSES.includes(assignee.status)) {
|
|
763
1496
|
assignee.status = "timeout";
|
|
764
|
-
|
|
1497
|
+
this.pushAssigneeAck(assignee, event);
|
|
765
1498
|
}
|
|
766
1499
|
}
|
|
767
1500
|
record.status = "timeout";
|
|
768
1501
|
record.updatedAt = now;
|
|
769
1502
|
this.clearTaskTimer(taskId);
|
|
770
|
-
this.
|
|
1503
|
+
this.taskChanged(this.taskOf(taskId));
|
|
771
1504
|
}
|
|
772
1505
|
clearTaskTimer(taskId) {
|
|
773
1506
|
const timer = this.taskTimers.get(taskId);
|
|
@@ -776,6 +1509,23 @@ var AgentHub = class {
|
|
|
776
1509
|
this.taskTimers.delete(taskId);
|
|
777
1510
|
}
|
|
778
1511
|
}
|
|
1512
|
+
/** Bring the SLA timer back in line with the AGGREGATE status after a
|
|
1513
|
+
* per-assignee write ({@link failTaskForGoneAssignee},
|
|
1514
|
+
* {@link failTaskForDroppedMessage}).
|
|
1515
|
+
*
|
|
1516
|
+
* A terminal task must not fire a second, contradictory timeout. A task that
|
|
1517
|
+
* is still open — a fan-out with one recipient lost and another working —
|
|
1518
|
+
* must keep its deadline: clearing the timer there left a task that stays
|
|
1519
|
+
* non-terminal forever, because `deadlineAt` is only read by the timer. */
|
|
1520
|
+
realignTaskTimer(record) {
|
|
1521
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) {
|
|
1522
|
+
this.clearTaskTimer(record.id);
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
if (record.deadlineAt === void 0) return;
|
|
1526
|
+
if (this.taskTimers.has(record.id)) return;
|
|
1527
|
+
this.scheduleTaskTimeout(record);
|
|
1528
|
+
}
|
|
779
1529
|
/** Note that `target` has taken delivery of a task (waiter handoff / queue). */
|
|
780
1530
|
markTaskDelivered(taskId, target, ts) {
|
|
781
1531
|
const record = this.taskLedger.get(taskId);
|
|
@@ -784,7 +1534,7 @@ var AgentHub = class {
|
|
|
784
1534
|
if (assignee === void 0 || assignee.deliveredMs !== void 0) return;
|
|
785
1535
|
assignee.deliveredMs = ts;
|
|
786
1536
|
record.updatedAt = ts;
|
|
787
|
-
this.
|
|
1537
|
+
this.taskChanged(this.taskOf(taskId));
|
|
788
1538
|
}
|
|
789
1539
|
/**
|
|
790
1540
|
* Fold an ack into the task's timeline and (when legal) its status.
|
|
@@ -795,32 +1545,32 @@ var AgentHub = class {
|
|
|
795
1545
|
applyAckToLedger(message, from, ref, ack) {
|
|
796
1546
|
const record = this.taskLedger.get(ref);
|
|
797
1547
|
if (record === void 0) return;
|
|
798
|
-
const next = nextTaskStatus(record.status, ack.status);
|
|
799
1548
|
const assignee = record.assignees.find((a) => a.peerId === from);
|
|
800
1549
|
const assigneeNext = assignee === void 0 ? null : nextTaskStatus(assignee.status, ack.status);
|
|
801
|
-
const applied =
|
|
1550
|
+
const applied = assignee !== void 0 && assigneeNext !== null;
|
|
802
1551
|
const event = {
|
|
803
1552
|
from,
|
|
804
1553
|
status: ack.status,
|
|
805
1554
|
...ack.note !== void 0 ? { note: ack.note } : {},
|
|
806
1555
|
...typeof ack.progress === "number" && Number.isFinite(ack.progress) ? { progress: Math.max(0, Math.min(100, ack.progress)) } : {},
|
|
1556
|
+
...ack.artifacts !== void 0 && ack.artifacts.length > 0 ? { artifacts: ack.artifacts } : {},
|
|
807
1557
|
ts: message.ts,
|
|
808
1558
|
messageId: message.id,
|
|
809
1559
|
applied
|
|
810
1560
|
};
|
|
811
|
-
|
|
1561
|
+
this.pushAckEvent(record, event);
|
|
1562
|
+
if (applied && event.artifacts !== void 0) {
|
|
1563
|
+
const merged = [...record.artifacts ?? [], ...event.artifacts];
|
|
1564
|
+
record.artifacts = merged.length > MAX_TASK_ARTIFACTS ? merged.slice(-MAX_TASK_ARTIFACTS) : merged;
|
|
1565
|
+
}
|
|
812
1566
|
if (assignee !== void 0 && assigneeNext !== null) {
|
|
813
1567
|
assignee.status = assigneeNext;
|
|
814
|
-
|
|
1568
|
+
this.pushAssigneeAck(assignee, event);
|
|
815
1569
|
}
|
|
816
|
-
if (record.assignees.length
|
|
817
|
-
|
|
818
|
-
} else {
|
|
819
|
-
record.status = aggregateTaskStatus(record.assignees);
|
|
820
|
-
}
|
|
821
|
-
record.updatedAt = message.ts;
|
|
1570
|
+
if (record.assignees.length > 0) record.status = aggregateTaskStatus(record.assignees);
|
|
1571
|
+
if (applied) record.updatedAt = message.ts;
|
|
822
1572
|
if (TERMINAL_TASK_STATUSES.includes(record.status)) this.clearTaskTimer(record.id);
|
|
823
|
-
this.
|
|
1573
|
+
this.taskChanged(this.taskOf(record.id));
|
|
824
1574
|
}
|
|
825
1575
|
/** Keep the ledger bounded: drop oldest terminal tasks first. */
|
|
826
1576
|
evictOverflowTasks() {
|
|
@@ -839,7 +1589,10 @@ var AgentHub = class {
|
|
|
839
1589
|
const record = this.taskLedger.get(ref);
|
|
840
1590
|
if (record === void 0) return void 0;
|
|
841
1591
|
return {
|
|
842
|
-
|
|
1592
|
+
// `dropNotified` is INTERNAL bookkeeping (see protocol.ts). A shallow
|
|
1593
|
+
// spread used to hand it to bridge_task_status / bridge_tasks, which made
|
|
1594
|
+
// an implementation detail part of the published task shape.
|
|
1595
|
+
...omit(record, "dropNotified"),
|
|
843
1596
|
acks: record.acks.map((a) => ({ ...a })),
|
|
844
1597
|
assignees: record.assignees.map((a) => ({ ...a, acks: a.acks.map((e) => ({ ...e })) }))
|
|
845
1598
|
};
|
|
@@ -874,6 +1627,35 @@ var AgentHub = class {
|
|
|
874
1627
|
exportTasks() {
|
|
875
1628
|
return [...this.taskLedger.values()].map((record) => this.taskOf(record.id)).filter(Boolean);
|
|
876
1629
|
}
|
|
1630
|
+
/** Accept a peer id read from a persisted snapshot, or `undefined` when the
|
|
1631
|
+
* row that carries it is unusable. A state file is external input and the
|
|
1632
|
+
* ledger is an AUTHORIZATION source (ack rights, `bridge_task_status`,
|
|
1633
|
+
* `bridge_task_input`), so a row attributed to `hub`, to the broadcast
|
|
1634
|
+
* address, to a malformed id or to a group id would hand that identity rights
|
|
1635
|
+
* over someone else's task. Every place a snapshot names a peer goes through
|
|
1636
|
+
* here — the task sender, an ack author, an assignee — so the four fields
|
|
1637
|
+
* cannot drift apart. */
|
|
1638
|
+
importPeerRef(value) {
|
|
1639
|
+
if (typeof value !== "string") return void 0;
|
|
1640
|
+
if (!PEER_ID_PATTERN.test(value) || value === BROADCAST || value === HUB_PEER) return void 0;
|
|
1641
|
+
if (this.groups.has(value)) return void 0;
|
|
1642
|
+
return value;
|
|
1643
|
+
}
|
|
1644
|
+
/** Accept an ACK AUTHOR read from a persisted snapshot.
|
|
1645
|
+
*
|
|
1646
|
+
* Deliberately weaker than {@link importPeerRef} in exactly one direction: an
|
|
1647
|
+
* ack row authorizes nothing (the ledger's authorization sources are the
|
|
1648
|
+
* sender and the assignee rows, both checked strictly), while the hub itself
|
|
1649
|
+
* authors terminal markers under the task's RECIPIENT address — `from: "hub"`
|
|
1650
|
+
* for the "restored as unattributable" marker and `from: record.to` (a group
|
|
1651
|
+
* id, or `all`) for a fan-out timeout. Refusing those ids here would delete the
|
|
1652
|
+
* evidence that a task timed out, and the unattributable marker would be
|
|
1653
|
+
* re-appended on every boot because its idempotency test looks for the stored
|
|
1654
|
+
* `import-<id>` row. Malformed ids are still refused. */
|
|
1655
|
+
importAckRef(value) {
|
|
1656
|
+
if (typeof value !== "string" || !PEER_ID_PATTERN.test(value)) return void 0;
|
|
1657
|
+
return value;
|
|
1658
|
+
}
|
|
877
1659
|
/** Restore the task ledger at boot (and re-arm SLA timers). */
|
|
878
1660
|
importTasks(tasks) {
|
|
879
1661
|
if (!Array.isArray(tasks)) return 0;
|
|
@@ -882,13 +1664,16 @@ var AgentHub = class {
|
|
|
882
1664
|
if (typeof raw !== "object" || raw === null) continue;
|
|
883
1665
|
const t = raw;
|
|
884
1666
|
if (typeof t.id !== "string" || typeof t.from !== "string" || typeof t.to !== "string" || typeof t.prompt !== "string") continue;
|
|
885
|
-
if (typeof t.status !== "string" || !
|
|
1667
|
+
if (typeof t.status !== "string" || !ALL_TASK_STATUSES.includes(t.status)) continue;
|
|
1668
|
+
const from = this.importPeerRef(t.from);
|
|
1669
|
+
if (from === void 0) continue;
|
|
886
1670
|
const acks = Array.isArray(t.acks) ? t.acks.flatMap((rawAck) => {
|
|
887
1671
|
if (typeof rawAck !== "object" || rawAck === null) return [];
|
|
888
1672
|
const a = rawAck;
|
|
889
|
-
|
|
1673
|
+
const ackFrom = this.importAckRef(a.from);
|
|
1674
|
+
if (ackFrom === void 0 || typeof a.status !== "string" || !ALL_ACK_STATUSES.includes(a.status) || typeof a.ts !== "number" || typeof a.messageId !== "string") return [];
|
|
890
1675
|
return [{
|
|
891
|
-
from:
|
|
1676
|
+
from: ackFrom,
|
|
892
1677
|
status: a.status,
|
|
893
1678
|
...typeof a.note === "string" ? { note: a.note } : {},
|
|
894
1679
|
...typeof a.progress === "number" ? { progress: a.progress } : {},
|
|
@@ -898,20 +1683,22 @@ var AgentHub = class {
|
|
|
898
1683
|
...a.system === true ? { system: true } : {}
|
|
899
1684
|
}];
|
|
900
1685
|
}) : [];
|
|
901
|
-
const
|
|
1686
|
+
const storedAssignees = Array.isArray(t.assignees) ? t.assignees.flatMap((rawA) => {
|
|
902
1687
|
if (typeof rawA !== "object" || rawA === null) return [];
|
|
903
1688
|
const a = rawA;
|
|
904
|
-
|
|
1689
|
+
const assigneeId = this.importPeerRef(a.peerId);
|
|
1690
|
+
if (assigneeId === void 0 || typeof a.status !== "string" || !ALL_TASK_STATUSES.includes(a.status)) return [];
|
|
905
1691
|
return [{
|
|
906
|
-
peerId:
|
|
1692
|
+
peerId: assigneeId,
|
|
907
1693
|
status: a.status,
|
|
908
1694
|
...typeof a.deliveredMs === "number" ? { deliveredMs: a.deliveredMs } : {},
|
|
909
1695
|
acks: Array.isArray(a.acks) ? a.acks.flatMap((rawE) => {
|
|
910
1696
|
if (typeof rawE !== "object" || rawE === null) return [];
|
|
911
1697
|
const e = rawE;
|
|
912
|
-
|
|
1698
|
+
const eventFrom = this.importAckRef(e.from);
|
|
1699
|
+
if (eventFrom === void 0 || typeof e.status !== "string" || !ALL_ACK_STATUSES.includes(e.status) || typeof e.ts !== "number" || typeof e.messageId !== "string") return [];
|
|
913
1700
|
return [{
|
|
914
|
-
from:
|
|
1701
|
+
from: eventFrom,
|
|
915
1702
|
status: e.status,
|
|
916
1703
|
...typeof e.note === "string" ? { note: e.note } : {},
|
|
917
1704
|
ts: e.ts,
|
|
@@ -920,10 +1707,12 @@ var AgentHub = class {
|
|
|
920
1707
|
}];
|
|
921
1708
|
}) : []
|
|
922
1709
|
}];
|
|
923
|
-
}) : [
|
|
1710
|
+
}) : [];
|
|
1711
|
+
const unattributable = storedAssignees.length === 0 && (t.to === BROADCAST || this.groups.has(t.to) || !PEER_ID_PATTERN.test(t.to));
|
|
1712
|
+
const assignees = storedAssignees.length > 0 ? storedAssignees : unattributable ? [] : [{ peerId: t.to, status: t.status, acks: [] }];
|
|
924
1713
|
const record = {
|
|
925
1714
|
id: t.id,
|
|
926
|
-
from
|
|
1715
|
+
from,
|
|
927
1716
|
to: t.to,
|
|
928
1717
|
prompt: t.prompt,
|
|
929
1718
|
...typeof t.context === "string" ? { context: t.context } : {},
|
|
@@ -937,6 +1726,21 @@ var AgentHub = class {
|
|
|
937
1726
|
createdAt: typeof t.createdAt === "number" ? t.createdAt : Date.now(),
|
|
938
1727
|
updatedAt: typeof t.updatedAt === "number" ? t.updatedAt : Date.now()
|
|
939
1728
|
};
|
|
1729
|
+
if (unattributable) {
|
|
1730
|
+
record.status = "failed";
|
|
1731
|
+
if (!record.acks.some((event) => event.messageId === `import-${record.id}`)) {
|
|
1732
|
+
this.pushAckEvent(record, {
|
|
1733
|
+
from: HUB_PEER,
|
|
1734
|
+
status: "failed",
|
|
1735
|
+
note: `restored as failed: the stored record has no assignee row and its recipient '${t.to}' is not a peer id, so the task cannot be attributed to anyone and can never be acked`,
|
|
1736
|
+
ts: record.updatedAt,
|
|
1737
|
+
messageId: `import-${record.id}`,
|
|
1738
|
+
applied: true,
|
|
1739
|
+
system: true
|
|
1740
|
+
});
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
if (assignees.length > 0) record.status = aggregateTaskStatus(assignees);
|
|
940
1744
|
this.taskLedger.set(record.id, record);
|
|
941
1745
|
this.scheduleTaskTimeout(record);
|
|
942
1746
|
count++;
|
|
@@ -944,33 +1748,49 @@ var AgentHub = class {
|
|
|
944
1748
|
this.evictOverflowTasks();
|
|
945
1749
|
return count;
|
|
946
1750
|
}
|
|
1751
|
+
/** Highest sequence number handed out so far — a client's "start from now"
|
|
1752
|
+
* cursor (`bridge_status.lastSeq`). */
|
|
1753
|
+
lastSeq() {
|
|
1754
|
+
return this.seqCounter;
|
|
1755
|
+
}
|
|
947
1756
|
/** Recent messages involving `peer` (inbound and outbound, plus group
|
|
948
|
-
* channels the peer belongs to), newest first.
|
|
949
|
-
|
|
1757
|
+
* channels the peer belongs to), newest first. `since` restricts the result to
|
|
1758
|
+
* messages newer than that sequence number (a resume cursor); omitting it keeps
|
|
1759
|
+
* the original behaviour, which includes history recorded before cursors
|
|
1760
|
+
* existed. */
|
|
1761
|
+
history(peerId, limit, since) {
|
|
950
1762
|
const memberOf = new Set(
|
|
951
1763
|
[...this.groups.values()].filter((group) => group.members.includes(peerId)).map((group) => group.id)
|
|
952
1764
|
);
|
|
953
1765
|
const filtered = this.historyRing.filter(
|
|
954
|
-
(message) => message.from === peerId || message.to === peerId || message.to === BROADCAST || message.channel !== void 0 && memberOf.has(message.channel)
|
|
1766
|
+
(message) => (since === void 0 || (message.seq ?? 0) > since) && (message.from === peerId || message.to === peerId || message.to === BROADCAST || message.channel !== void 0 && memberOf.has(message.channel))
|
|
955
1767
|
);
|
|
956
1768
|
return filtered.slice(-Math.max(0, limit)).reverse();
|
|
957
1769
|
}
|
|
958
1770
|
/** Recent messages of one group channel, newest first. */
|
|
959
|
-
historyChannel(groupId, limit) {
|
|
960
|
-
const filtered = this.historyRing.filter(
|
|
1771
|
+
historyChannel(groupId, limit, since) {
|
|
1772
|
+
const filtered = this.historyRing.filter(
|
|
1773
|
+
(message) => (since === void 0 || (message.seq ?? 0) > since) && (message.channel === groupId || message.to === groupId && message.channel === void 0 && this.groups.has(groupId))
|
|
1774
|
+
);
|
|
961
1775
|
return filtered.slice(-Math.max(0, limit)).reverse();
|
|
962
1776
|
}
|
|
963
1777
|
/** Most recent messages across every peer, unfiltered (newest first).
|
|
964
1778
|
* Backs `bridge_history { peer: "all" }` — lets an archiver (the desktop
|
|
965
1779
|
* app) capture peer-to-peer traffic it is not a party of. */
|
|
966
|
-
historyAll(limit) {
|
|
967
|
-
|
|
1780
|
+
historyAll(limit, since) {
|
|
1781
|
+
const filtered = since === void 0 ? this.historyRing : this.historyRing.filter((message) => (message.seq ?? 0) > since);
|
|
1782
|
+
return filtered.slice(-Math.max(0, limit)).reverse();
|
|
968
1783
|
}
|
|
969
1784
|
// ---- groups (group channel) ------------------------------------------------
|
|
970
1785
|
/** Create a channel; throws when the id is taken or a member is unknown. */
|
|
971
1786
|
createGroup(id, members, createdBy, name) {
|
|
972
1787
|
if (this.groups.has(id)) throw new Error(`group already exists: ${id}`);
|
|
973
1788
|
if (!PEER_ID_PATTERN.test(id)) throw new Error(`invalid group id: ${id} (expected [A-Za-z0-9._:-]{1,64})`);
|
|
1789
|
+
if (id === BROADCAST) throw new Error(`group id '${id}' is taken: it is the broadcast address in the namespace peer and group ids share`);
|
|
1790
|
+
if (id === HUB_PEER) throw new Error(`group id '${id}' is taken: the hub uses it for its own notices`);
|
|
1791
|
+
if (this.lastSeen.has(id) || this.ownsMailbox(id) || this.profiles.has(id)) {
|
|
1792
|
+
throw new Error(`group id '${id}' collides with a peer: peer and group ids share one 'to' namespace, and a group would win every message addressed to that peer`);
|
|
1793
|
+
}
|
|
974
1794
|
const unique = [...new Set(members)];
|
|
975
1795
|
if (unique.length === 0) throw new Error("a group needs at least one member");
|
|
976
1796
|
for (const member of unique) {
|
|
@@ -1022,11 +1842,14 @@ var AgentHub = class {
|
|
|
1022
1842
|
}
|
|
1023
1843
|
/** Send a chat message to every member of a group except the sender;
|
|
1024
1844
|
* members that went offline are skipped (they read the group history).
|
|
1025
|
-
* The message carries `to` and `channel` = the group id.
|
|
1845
|
+
* The message carries `to` and `channel` = the group id.
|
|
1846
|
+
*
|
|
1847
|
+
* Membership is enforced once, in {@link compose} — the single path this and
|
|
1848
|
+
* a plain `bridge_chat { to: <group> }` both go through. The `unknown group`
|
|
1849
|
+
* check stays here so a caller naming a non-group gets that error instead of
|
|
1850
|
+
* compose's generic "unknown recipient". */
|
|
1026
1851
|
sendToGroup(from, groupId, content) {
|
|
1027
|
-
|
|
1028
|
-
if (group === void 0) throw new Error(`unknown group: ${groupId}`);
|
|
1029
|
-
if (!group.members.includes(from)) throw new Error(`peer '${from}' is not a member of group '${groupId}'`);
|
|
1852
|
+
if (!this.groups.has(groupId)) throw new Error(`unknown group: ${groupId}`);
|
|
1030
1853
|
return this.route(from, groupId, "chat", content);
|
|
1031
1854
|
}
|
|
1032
1855
|
/** Snapshot of every group for persistence. */
|
|
@@ -1042,6 +1865,8 @@ var AgentHub = class {
|
|
|
1042
1865
|
if (typeof raw !== "object" || raw === null) continue;
|
|
1043
1866
|
const candidate = raw;
|
|
1044
1867
|
if (typeof candidate.id !== "string" || !PEER_ID_PATTERN.test(candidate.id) || this.groups.has(candidate.id)) continue;
|
|
1868
|
+
if (candidate.id === BROADCAST || candidate.id === HUB_PEER) continue;
|
|
1869
|
+
if (this.lastSeen.has(candidate.id) || this.profiles.has(candidate.id)) continue;
|
|
1045
1870
|
if (!Array.isArray(candidate.members) || candidate.members.length === 0) continue;
|
|
1046
1871
|
const members = [...new Set(candidate.members.filter((m) => typeof m === "string" && PEER_ID_PATTERN.test(m)))];
|
|
1047
1872
|
if (members.length === 0) continue;
|
|
@@ -1052,13 +1877,19 @@ var AgentHub = class {
|
|
|
1052
1877
|
createdAt: typeof candidate.createdAt === "number" && Number.isFinite(candidate.createdAt) ? candidate.createdAt : Date.now(),
|
|
1053
1878
|
...typeof candidate.name === "string" && candidate.name !== "" ? { name: candidate.name } : {}
|
|
1054
1879
|
});
|
|
1880
|
+
this.queues.delete(candidate.id);
|
|
1881
|
+
this.parkedAt.delete(candidate.id);
|
|
1055
1882
|
count++;
|
|
1056
1883
|
}
|
|
1057
1884
|
return count;
|
|
1058
1885
|
}
|
|
1059
1886
|
// ---- persistence import/export (remote-mode SQLite store) -----------
|
|
1060
1887
|
/** Restore the history ring at boot. Shape-invalid rows are dropped; only
|
|
1061
|
-
* the newest {@link HubOptions.historyLimit} survive.
|
|
1888
|
+
* the newest {@link HubOptions.historyLimit} survive.
|
|
1889
|
+
*
|
|
1890
|
+
* Restoring is a FIELD WHITELIST: a wire field that is not listed here is
|
|
1891
|
+
* silently lost across a restart (that is how `priority` went missing), so
|
|
1892
|
+
* every new field on {@link BridgeMessage} has to be added below. */
|
|
1062
1893
|
importHistory(messages) {
|
|
1063
1894
|
if (!Array.isArray(messages)) return 0;
|
|
1064
1895
|
const valid = [];
|
|
@@ -1078,25 +1909,70 @@ var AgentHub = class {
|
|
|
1078
1909
|
...typeof m.channel === "string" ? { channel: m.channel } : {},
|
|
1079
1910
|
...typeof m.threadId === "string" ? { threadId: m.threadId } : {},
|
|
1080
1911
|
...hop !== void 0 ? { hop } : {},
|
|
1912
|
+
// Absent in databases written before the column existed; such a message
|
|
1913
|
+
// is simply unreachable through a `since` cursor, which is the honest
|
|
1914
|
+
// state for history that predates the cursor.
|
|
1915
|
+
...typeof m.seq === "number" && Number.isFinite(m.seq) && m.seq > 0 ? { seq: m.seq } : {},
|
|
1916
|
+
...typeof m.expiresAt === "number" && Number.isFinite(m.expiresAt) && m.expiresAt > 0 ? { expiresAt: m.expiresAt } : {},
|
|
1917
|
+
// Same guard as compose: only a real 0 | 1 | 2 is written back, an
|
|
1918
|
+
// absent one stays absent so no reader has to tell 0 from "unset".
|
|
1919
|
+
...m.priority === 0 || m.priority === 1 || m.priority === 2 ? { priority: m.priority } : {},
|
|
1081
1920
|
ts: m.ts
|
|
1082
1921
|
});
|
|
1083
1922
|
}
|
|
1923
|
+
for (const message of valid) {
|
|
1924
|
+
if (message.seq !== void 0 && message.seq > this.seqCounter) this.seqCounter = message.seq;
|
|
1925
|
+
}
|
|
1084
1926
|
for (const message of valid.slice(-this.options.historyLimit)) this.historyRing.push(message);
|
|
1085
1927
|
return Math.min(valid.length, this.options.historyLimit);
|
|
1086
1928
|
}
|
|
1087
|
-
/** Snapshot of every offline mailbox, keyed by peer (persistence).
|
|
1929
|
+
/** Snapshot of every offline mailbox, keyed by peer (persistence).
|
|
1930
|
+
*
|
|
1931
|
+
* Manual-ack leases ride along inside the peer's queue array: appended after
|
|
1932
|
+
* the queued mail, in lease order, and deliberately NOT re-sorted (the
|
|
1933
|
+
* restore path re-orders, see {@link importMailboxes}). A lease is a
|
|
1934
|
+
* delivery in progress — the message left the queue but was never committed
|
|
1935
|
+
* — and leaving it out is how an uncommitted message used to be in neither
|
|
1936
|
+
* `queues` nor SQLite and vanished on restart.
|
|
1937
|
+
*
|
|
1938
|
+
* EVERY lease is exported, expired or not: this is a snapshot of what the
|
|
1939
|
+
* hub knows was handed out, not a reachability verdict. Expiry is decided by
|
|
1940
|
+
* the CONSUMER (`poll` / `wait` / `reapLeases`), which drops an expired
|
|
1941
|
+
* message, counts it as `droppedExpired` and reconciles the ledger. Filtering
|
|
1942
|
+
* on `expiresAt` here created a window with no owner at all: a lease that
|
|
1943
|
+
* expired but was never reaped (no take, and `gcTick` does not run when
|
|
1944
|
+
* `peerIdleTimeoutMs` is 0) was written out by the next unrelated flush or
|
|
1945
|
+
* by a graceful shutdown — i.e. neither in the queue nor in the snapshot —
|
|
1946
|
+
* and the message was gone for good.
|
|
1947
|
+
*
|
|
1948
|
+
* No new top-level key on purpose: an older hub reading this snapshot sees
|
|
1949
|
+
* ordinary queued mail and redelivers it once, which is exactly the
|
|
1950
|
+
* at-least-once half of the lease contract.
|
|
1951
|
+
*
|
|
1952
|
+
* `attempts` does NOT survive: the counter lives in `leaseAttempts` (memory
|
|
1953
|
+
* only), so a restarted hub starts the message over at attempt 1. Treat
|
|
1954
|
+
* `maxAttempts` as a bound per PROCESS, not per message lifetime. */
|
|
1088
1955
|
exportMailboxes() {
|
|
1089
1956
|
const out = {};
|
|
1090
1957
|
for (const [peer, queue] of this.queues) {
|
|
1091
1958
|
if (queue.length > 0) out[peer] = queue.map((message) => ({ ...message }));
|
|
1092
1959
|
}
|
|
1960
|
+
for (const [peer, leases] of this.leases) {
|
|
1961
|
+
if (leases.length === 0) continue;
|
|
1962
|
+
const messages = out[peer] ?? (out[peer] = []);
|
|
1963
|
+
for (const lease of leases) messages.push({ ...lease.message });
|
|
1964
|
+
}
|
|
1093
1965
|
return out;
|
|
1094
1966
|
}
|
|
1095
|
-
/** Restore offline mailboxes at boot (peer reconnects and drains later).
|
|
1967
|
+
/** Restore offline mailboxes at boot (peer reconnects and drains later).
|
|
1968
|
+
*
|
|
1969
|
+
* Like {@link importHistory} this is a FIELD WHITELIST — a new wire field
|
|
1970
|
+
* must be added in both places or it is lost across a restart. */
|
|
1096
1971
|
importMailboxes(mailboxes) {
|
|
1097
1972
|
if (typeof mailboxes !== "object" || mailboxes === null) return 0;
|
|
1098
1973
|
let count = 0;
|
|
1099
1974
|
for (const [peer, queue] of Object.entries(mailboxes)) {
|
|
1975
|
+
if (!PEER_ID_PATTERN.test(peer) || peer === BROADCAST || peer === HUB_PEER || this.groups.has(peer)) continue;
|
|
1100
1976
|
if (!Array.isArray(queue) || queue.length === 0) continue;
|
|
1101
1977
|
const restored = [];
|
|
1102
1978
|
for (const raw of queue) {
|
|
@@ -1114,12 +1990,32 @@ var AgentHub = class {
|
|
|
1114
1990
|
...typeof m.channel === "string" ? { channel: m.channel } : {},
|
|
1115
1991
|
...typeof m.threadId === "string" ? { threadId: m.threadId } : {},
|
|
1116
1992
|
...hop !== void 0 ? { hop } : {},
|
|
1993
|
+
// Restored mail must keep its deadline and its sequence number: the
|
|
1994
|
+
// deadline decides whether it is still deliverable at all, and the
|
|
1995
|
+
// cursor has to stay continuous across a restart.
|
|
1996
|
+
...typeof m.seq === "number" && Number.isFinite(m.seq) && m.seq > 0 ? { seq: m.seq } : {},
|
|
1997
|
+
...typeof m.expiresAt === "number" && Number.isFinite(m.expiresAt) && m.expiresAt > 0 ? { expiresAt: m.expiresAt } : {},
|
|
1998
|
+
// Priority decides both the mailbox order and what overflow drops, so
|
|
1999
|
+
// dropping it here would quietly downgrade restored mail to FIFO.
|
|
2000
|
+
...m.priority === 0 || m.priority === 1 || m.priority === 2 ? { priority: m.priority } : {},
|
|
1117
2001
|
ts: m.ts
|
|
1118
2002
|
});
|
|
1119
2003
|
}
|
|
1120
2004
|
if (restored.length > 0) {
|
|
1121
|
-
|
|
1122
|
-
|
|
2005
|
+
const mailbox = [];
|
|
2006
|
+
insertByPriority(mailbox, [...restored].sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0)));
|
|
2007
|
+
const now = Date.now();
|
|
2008
|
+
while (mailbox.length > this.options.maxQueue) {
|
|
2009
|
+
const victimIndex = lowestPriorityIndex(mailbox);
|
|
2010
|
+
if (victimIndex < 0) break;
|
|
2011
|
+
const [evicted] = mailbox.splice(victimIndex, 1);
|
|
2012
|
+
if (evicted === void 0) break;
|
|
2013
|
+
this.countDrop(peer, "overflow", now, evicted);
|
|
2014
|
+
if (evicted.kind === "task") this.noteTaskDeliveryDropped(evicted, peer, "overflow", now);
|
|
2015
|
+
}
|
|
2016
|
+
this.queues.set(peer, mailbox);
|
|
2017
|
+
if (!this.lastSeen.has(peer)) this.parkedAt.set(peer, Date.now());
|
|
2018
|
+
count += mailbox.length;
|
|
1123
2019
|
}
|
|
1124
2020
|
}
|
|
1125
2021
|
return count;
|
|
@@ -1132,54 +2028,426 @@ var AgentHub = class {
|
|
|
1132
2028
|
const now = Date.now();
|
|
1133
2029
|
return {
|
|
1134
2030
|
server: "agent-comm-hub",
|
|
1135
|
-
peers: this.
|
|
1136
|
-
const alias = this.profiles.get(peer)?.alias;
|
|
1137
|
-
return {
|
|
1138
|
-
id: peer,
|
|
1139
|
-
...alias !== void 0 ? { alias } : {},
|
|
1140
|
-
connected: this.isActive(peer) || livePeers?.has(peer) === true,
|
|
1141
|
-
lastSeenMs: this.lastSeen.get(peer) ?? 0,
|
|
1142
|
-
queued: (this.queues.get(peer) ?? []).length,
|
|
1143
|
-
waiting: (this.waiters.get(peer) ?? []).length
|
|
1144
|
-
};
|
|
1145
|
-
}),
|
|
2031
|
+
peers: this.rosterRows(livePeers),
|
|
1146
2032
|
historyLimit: this.options.historyLimit,
|
|
1147
|
-
maxQueue: this.options.maxQueue
|
|
2033
|
+
maxQueue: this.options.maxQueue,
|
|
2034
|
+
// A client that wants only what happened since it last looked reads this
|
|
2035
|
+
// and passes it back as `bridge_history { since }`.
|
|
2036
|
+
lastSeq: this.seqCounter
|
|
2037
|
+
};
|
|
2038
|
+
}
|
|
2039
|
+
/** Registered peers plus parked ones (gone but still holding mail).
|
|
2040
|
+
* Parked rows are what lets a sender tell "queued, will be delivered when it
|
|
2041
|
+
* comes back" apart from "vanished" — without them the message just looks lost.
|
|
2042
|
+
*/
|
|
2043
|
+
rosterRows(livePeers) {
|
|
2044
|
+
const rows = this.peers().map((peer) => {
|
|
2045
|
+
const alias = this.profiles.get(peer)?.alias;
|
|
2046
|
+
const connected = this.isActive(peer) || livePeers?.has(peer) === true;
|
|
2047
|
+
return {
|
|
2048
|
+
id: peer,
|
|
2049
|
+
...alias !== void 0 ? { alias } : {},
|
|
2050
|
+
connected,
|
|
2051
|
+
reachable: connected ? "online" : "idle",
|
|
2052
|
+
lastSeenMs: this.lastSeen.get(peer) ?? 0,
|
|
2053
|
+
queued: (this.queues.get(peer) ?? []).length,
|
|
2054
|
+
waiting: (this.waiters.get(peer) ?? []).length,
|
|
2055
|
+
...this.leases.get(peer) !== void 0 ? { inFlight: this.leases.get(peer).length } : {},
|
|
2056
|
+
...this.drops.get(peer) !== void 0 && this.drops.get(peer).overflow > 0 ? { droppedOverflow: this.drops.get(peer).overflow } : {},
|
|
2057
|
+
...this.drops.get(peer) !== void 0 && this.drops.get(peer).expired > 0 ? { droppedExpired: this.drops.get(peer).expired } : {},
|
|
2058
|
+
...this.drops.get(peer) !== void 0 && this.drops.get(peer).rate > 0 ? { droppedRate: this.drops.get(peer).rate } : {},
|
|
2059
|
+
...this.deadLetters.get(peer) !== void 0 ? { deadLettered: this.deadLetters.get(peer).length } : {}
|
|
2060
|
+
};
|
|
2061
|
+
});
|
|
2062
|
+
for (const [peerId, parkedMs] of this.parkedAt) {
|
|
2063
|
+
if (this.lastSeen.has(peerId)) continue;
|
|
2064
|
+
const alias = this.profiles.get(peerId)?.alias;
|
|
2065
|
+
rows.push({
|
|
2066
|
+
id: peerId,
|
|
2067
|
+
...alias !== void 0 ? { alias } : {},
|
|
2068
|
+
connected: false,
|
|
2069
|
+
reachable: "parked",
|
|
2070
|
+
lastSeenMs: parkedMs,
|
|
2071
|
+
queued: (this.queues.get(peerId) ?? []).length,
|
|
2072
|
+
waiting: 0,
|
|
2073
|
+
...this.leases.get(peerId) !== void 0 ? { inFlight: this.leases.get(peerId).length } : {},
|
|
2074
|
+
...this.deadLetters.get(peerId) !== void 0 ? { deadLettered: this.deadLetters.get(peerId).length } : {}
|
|
2075
|
+
});
|
|
2076
|
+
}
|
|
2077
|
+
return rows;
|
|
2078
|
+
}
|
|
2079
|
+
// ---- manual-ack leases -----------------------------------------------------
|
|
2080
|
+
/** A message handed out but not yet committed, and when its lease ends. */
|
|
2081
|
+
leases = /* @__PURE__ */ new Map();
|
|
2082
|
+
/** Hand-out count per (peer, message). Kept OUTSIDE the message so requeueing
|
|
2083
|
+
* preserves it and so it is never persisted as part of the message. */
|
|
2084
|
+
leaseAttempts = /* @__PURE__ */ new Map();
|
|
2085
|
+
/** Messages that ran out of attempts; `nack` revives them. */
|
|
2086
|
+
deadLetters = /* @__PURE__ */ new Map();
|
|
2087
|
+
// ---- drop accounting --------------------------------------------------------
|
|
2088
|
+
/** Per-peer drop counters, surfaced in the roster. Memory-only on purpose:
|
|
2089
|
+
* these are operational counters for the current run, not durable state. */
|
|
2090
|
+
drops = /* @__PURE__ */ new Map();
|
|
2091
|
+
/** Per-peer token bucket for the MAILBOX. See {@link HubOptions.ratePerMin}. */
|
|
2092
|
+
buckets = /* @__PURE__ */ new Map();
|
|
2093
|
+
/** Traffic counters, per peer: how much this peer sent, was sent, and acked.
|
|
2094
|
+
* Deliberately separate from the mailbox — "how much has this peer sent" is not
|
|
2095
|
+
* "how much is queued", and a drained queue must not erase the history of what
|
|
2096
|
+
* went through it. Memory-only, like {@link drops}: operational, not durable. */
|
|
2097
|
+
traffic = /* @__PURE__ */ new Map();
|
|
2098
|
+
bumpTraffic(peerId, field) {
|
|
2099
|
+
const row = this.traffic.get(peerId) ?? { sent: 0, received: 0, acked: 0 };
|
|
2100
|
+
row[field]++;
|
|
2101
|
+
this.traffic.set(peerId, row);
|
|
2102
|
+
}
|
|
2103
|
+
/**
|
|
2104
|
+
* Observability snapshot: per-peer and global counters.
|
|
2105
|
+
*
|
|
2106
|
+
* Everything here is either derived from live state or from a counter the hub
|
|
2107
|
+
* already keeps — nothing is estimated, and nothing is sampled. `messagesTotal`
|
|
2108
|
+
* is the history `seq` (monotonic, never resets in a run), so it is a true count
|
|
2109
|
+
* of composed messages rather than a rolling window.
|
|
2110
|
+
*/
|
|
2111
|
+
metrics() {
|
|
2112
|
+
const tasksByStatus = {};
|
|
2113
|
+
for (const record of this.taskLedger.values()) {
|
|
2114
|
+
tasksByStatus[record.status] = (tasksByStatus[record.status] ?? 0) + 1;
|
|
2115
|
+
}
|
|
2116
|
+
const ids = /* @__PURE__ */ new Set([
|
|
2117
|
+
...this.lastSeen.keys(),
|
|
2118
|
+
...this.parkedAt.keys(),
|
|
2119
|
+
...this.queues.keys(),
|
|
2120
|
+
...this.traffic.keys()
|
|
2121
|
+
]);
|
|
2122
|
+
const peers = [...ids].map((peerId) => {
|
|
2123
|
+
const row = this.traffic.get(peerId) ?? { sent: 0, received: 0, acked: 0 };
|
|
2124
|
+
const drop = this.drops.get(peerId) ?? { overflow: 0, expired: 0, rate: 0 };
|
|
2125
|
+
return {
|
|
2126
|
+
peerId,
|
|
2127
|
+
sent: row.sent,
|
|
2128
|
+
received: row.received,
|
|
2129
|
+
acked: row.acked,
|
|
2130
|
+
queued: this.queues.get(peerId)?.length ?? 0,
|
|
2131
|
+
inFlight: this.leases.get(peerId)?.length ?? 0,
|
|
2132
|
+
deadLettered: this.deadLetters.get(peerId)?.length ?? 0,
|
|
2133
|
+
droppedOverflow: drop.overflow,
|
|
2134
|
+
droppedExpired: drop.expired,
|
|
2135
|
+
droppedRate: drop.rate,
|
|
2136
|
+
// Same definition the roster uses: recent activity OR a live SSE channel.
|
|
2137
|
+
connected: this.isActive(peerId) || this.options.isPeerLive?.(peerId) === true
|
|
2138
|
+
};
|
|
2139
|
+
});
|
|
2140
|
+
return {
|
|
2141
|
+
global: {
|
|
2142
|
+
messagesTotal: this.seqCounter,
|
|
2143
|
+
peers: peers.length,
|
|
2144
|
+
connectedPeers: peers.filter((p) => p.connected).length,
|
|
2145
|
+
parkedPeers: peers.filter((p) => !p.connected && this.parkedAt.has(p.peerId)).length,
|
|
2146
|
+
waitersNow: [...this.waiters.values()].reduce((sum, list) => sum + list.length, 0),
|
|
2147
|
+
queuedTotal: peers.reduce((sum, p) => sum + p.queued, 0),
|
|
2148
|
+
tasksByStatus,
|
|
2149
|
+
droppedOverflow: peers.reduce((sum, p) => sum + p.droppedOverflow, 0),
|
|
2150
|
+
droppedExpired: peers.reduce((sum, p) => sum + p.droppedExpired, 0),
|
|
2151
|
+
droppedRate: peers.reduce((sum, p) => sum + p.droppedRate, 0),
|
|
2152
|
+
deadLettered: peers.reduce((sum, p) => sum + p.deadLettered, 0),
|
|
2153
|
+
inFlight: peers.reduce((sum, p) => sum + p.inFlight, 0)
|
|
2154
|
+
},
|
|
2155
|
+
peers: peers.sort((a, b) => a.peerId.localeCompare(b.peerId))
|
|
2156
|
+
};
|
|
2157
|
+
}
|
|
2158
|
+
/** Count a dropped message for `peerId` and, if that peer is waiting right
|
|
2159
|
+
* now, tell it. The notice is NOT queued: the mailbox is either full
|
|
2160
|
+
* (overflow) or the message already expired, and queueing the notice would
|
|
2161
|
+
* push yet another message out. An offline peer just sees the counters. */
|
|
2162
|
+
/** May this peer's mailbox accept one more message right now?
|
|
2163
|
+
*
|
|
2164
|
+
* Applied on the QUEUE path only, never on a waiter handoff: a waiting peer
|
|
2165
|
+
* already controls its own rate (it gets one message per `bridge_wait`), while a
|
|
2166
|
+
* mailbox is filled by traffic the recipient never asked for. That is the whole
|
|
2167
|
+
* point of the bucket.
|
|
2168
|
+
*/
|
|
2169
|
+
takeToken(peerId, now) {
|
|
2170
|
+
const rate = this.options.ratePerMin ?? 0;
|
|
2171
|
+
if (rate <= 0) return true;
|
|
2172
|
+
const bucket = this.buckets.get(peerId) ?? { tokens: rate, last: now };
|
|
2173
|
+
const elapsed = Math.max(0, now - bucket.last);
|
|
2174
|
+
bucket.tokens = Math.min(rate, bucket.tokens + elapsed * rate / 6e4);
|
|
2175
|
+
bucket.last = now;
|
|
2176
|
+
if (bucket.tokens < 1) {
|
|
2177
|
+
this.buckets.set(peerId, bucket);
|
|
2178
|
+
return false;
|
|
2179
|
+
}
|
|
2180
|
+
bucket.tokens -= 1;
|
|
2181
|
+
this.buckets.set(peerId, bucket);
|
|
2182
|
+
return true;
|
|
2183
|
+
}
|
|
2184
|
+
/** Count a dropped message. `message` (when the caller has it) names the loss
|
|
2185
|
+
* in the event detail: the counter alone told an operator that something went
|
|
2186
|
+
* missing, never what — and a dropped task is reconciled in the ledger, which
|
|
2187
|
+
* has to be matchable back to this event. */
|
|
2188
|
+
countDrop(peerId, kind, now, message) {
|
|
2189
|
+
const stats = this.drops.get(peerId) ?? { overflow: 0, expired: 0, rate: 0 };
|
|
2190
|
+
stats[kind] += 1;
|
|
2191
|
+
this.drops.set(peerId, stats);
|
|
2192
|
+
const total = stats.overflow + stats.expired + stats.rate;
|
|
2193
|
+
this.recordEvent("mailbox_dropped", {
|
|
2194
|
+
peer: peerId,
|
|
2195
|
+
detail: {
|
|
2196
|
+
reason: kind,
|
|
2197
|
+
total,
|
|
2198
|
+
...message !== void 0 ? { messageId: message.id } : {},
|
|
2199
|
+
// The ledger is keyed by the task's message id, so this repeats
|
|
2200
|
+
// `messageId` today; it is spelled out so a consumer looking for "the
|
|
2201
|
+
// task this drop killed" does not have to know that.
|
|
2202
|
+
...message !== void 0 && message.kind === "task" ? { taskId: message.id } : {}
|
|
2203
|
+
}
|
|
2204
|
+
});
|
|
2205
|
+
const notice = {
|
|
2206
|
+
id: randomUUID(),
|
|
2207
|
+
seq: ++this.seqCounter,
|
|
2208
|
+
from: HUB_PEER,
|
|
2209
|
+
to: peerId,
|
|
2210
|
+
kind: "notice",
|
|
2211
|
+
content: encodeContent({
|
|
2212
|
+
message: kind === "overflow" ? `mailbox overflow: an older message was dropped before you read it (${total} dropped so far)` : kind === "rate" ? `rate limit: messages addressed to you arrived faster than ${this.options.ratePerMin ?? 0}/min and were dropped (${total} dropped so far)` : `a message addressed to you expired before delivery and was dropped (${total} dropped so far)`,
|
|
2213
|
+
level: "warn"
|
|
2214
|
+
}),
|
|
2215
|
+
ts: now
|
|
1148
2216
|
};
|
|
2217
|
+
if (kind === "expired") {
|
|
2218
|
+
const queue = this.queues.get(peerId) ?? [];
|
|
2219
|
+
if (queue.length < this.options.maxQueue) {
|
|
2220
|
+
queue.push(notice);
|
|
2221
|
+
this.queues.set(peerId, queue);
|
|
2222
|
+
this.options.onQueued?.(notice, peerId);
|
|
2223
|
+
this.options.onMailboxesChanged?.();
|
|
2224
|
+
return;
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
this.deliverToWaiter(peerId, notice);
|
|
2228
|
+
}
|
|
2229
|
+
/** Drop counters for `peerId` (undefined when nothing was ever dropped). */
|
|
2230
|
+
dropsFor(peerId) {
|
|
2231
|
+
return this.drops.get(peerId);
|
|
2232
|
+
}
|
|
2233
|
+
/** Hand `message` to a matching live waiter, if there is one. Never queues —
|
|
2234
|
+
* used for notices about a mailbox that must not grow. Returns whether it
|
|
2235
|
+
* was handed over. */
|
|
2236
|
+
deliverToWaiter(target, message) {
|
|
2237
|
+
const list = this.waiters.get(target) ?? [];
|
|
2238
|
+
const index = list.findIndex((waiter2) => matchesWaiter(waiter2, message, this.taskLedger));
|
|
2239
|
+
if (index < 0) return false;
|
|
2240
|
+
const [waiter] = list.splice(index, 1);
|
|
2241
|
+
this.waiters.set(target, list);
|
|
2242
|
+
clearTimeout(waiter.timer);
|
|
2243
|
+
waiter.resolve({ type: "message", message: this.handOut(target, message, waiter.manual === true, message.ts) });
|
|
2244
|
+
return true;
|
|
2245
|
+
}
|
|
2246
|
+
static leaseKey(peerId, messageId) {
|
|
2247
|
+
return `${peerId}\0${messageId}`;
|
|
2248
|
+
}
|
|
2249
|
+
/** Drop every queued message of `peerId` whose deadline passed, counting each
|
|
2250
|
+
* loss. Shared by `poll` and `wait`: an expired message must never be handed
|
|
2251
|
+
* out, and it must not sit at the head of the mailbox looking deliverable
|
|
2252
|
+
* either.
|
|
2253
|
+
*
|
|
2254
|
+
* The attempt counter goes with it. Nothing can hand the message out again,
|
|
2255
|
+
* so keeping the key would leak one `leaseAttempts` entry per expired message
|
|
2256
|
+
* in a long-running process. */
|
|
2257
|
+
sweepExpired(peerId, queue, now) {
|
|
2258
|
+
for (let i = queue.length - 1; i >= 0; i--) {
|
|
2259
|
+
const queued = queue[i];
|
|
2260
|
+
if (queued.expiresAt === void 0 || queued.expiresAt > now) continue;
|
|
2261
|
+
queue.splice(i, 1);
|
|
2262
|
+
this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, queued.id));
|
|
2263
|
+
this.countDrop(peerId, "expired", now, queued);
|
|
2264
|
+
if (queued.kind === "task") this.noteTaskDeliveryDropped(queued, peerId, "expired", now);
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
/** Return expired leases to the queue in priority order, or dead-letter them
|
|
2268
|
+
* once they have been handed out too many times. Called before every take, so
|
|
2269
|
+
* expiry needs no timer of its own. */
|
|
2270
|
+
reapLeases(peerId, now) {
|
|
2271
|
+
const list = this.leases.get(peerId);
|
|
2272
|
+
if (list === void 0 || list.length === 0) return;
|
|
2273
|
+
const max = this.options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
2274
|
+
const still = [];
|
|
2275
|
+
const back = [];
|
|
2276
|
+
const dead = [];
|
|
2277
|
+
for (const lease of list) {
|
|
2278
|
+
if (lease.expiresAt > now) {
|
|
2279
|
+
still.push(lease);
|
|
2280
|
+
continue;
|
|
2281
|
+
}
|
|
2282
|
+
const attempts = this.leaseAttempts.get(_AgentHub.leaseKey(peerId, lease.message.id)) ?? 0;
|
|
2283
|
+
if (max > 0 && attempts >= max) {
|
|
2284
|
+
dead.push(lease.message);
|
|
2285
|
+
continue;
|
|
2286
|
+
}
|
|
2287
|
+
back.push(lease.message);
|
|
2288
|
+
}
|
|
2289
|
+
if (still.length > 0) this.leases.set(peerId, still);
|
|
2290
|
+
else this.leases.delete(peerId);
|
|
2291
|
+
if (back.length > 0) this.requeue(peerId, back, now);
|
|
2292
|
+
if (dead.length > 0) this.deadLetter(peerId, dead, now);
|
|
2293
|
+
}
|
|
2294
|
+
/** Put messages back into `peerId`'s mailbox, trimming to `maxQueue`.
|
|
2295
|
+
*
|
|
2296
|
+
* A message coming BACK competes for a slot exactly like arriving mail, so it
|
|
2297
|
+
* can never grow a full mailbox: `insertByPriority` orders it, then the tail
|
|
2298
|
+
* (lowest priority, newest) is what does not fit. Those go to the dead letters
|
|
2299
|
+
* instead of being dropped — a requeued message is a message the hub promised
|
|
2300
|
+
* to keep, and `bridge_nack` can still revive it. Returns how many really made
|
|
2301
|
+
* it into the queue. */
|
|
2302
|
+
requeue(peerId, messages, now) {
|
|
2303
|
+
if (messages.length === 0) return 0;
|
|
2304
|
+
const queue = this.queues.get(peerId) ?? [];
|
|
2305
|
+
insertByPriority(queue, messages);
|
|
2306
|
+
this.queues.set(peerId, queue);
|
|
2307
|
+
const overflow = [];
|
|
2308
|
+
while (queue.length > this.options.maxQueue) overflow.push(queue.pop());
|
|
2309
|
+
this.options.onMailboxesChanged?.();
|
|
2310
|
+
if (overflow.length > 0) this.deadLetter(peerId, overflow, now);
|
|
2311
|
+
const inQueue = new Set(queue);
|
|
2312
|
+
return messages.reduce((kept, message) => kept + (inQueue.has(message) ? 1 : 0), 0);
|
|
2313
|
+
}
|
|
2314
|
+
/** Park messages that can no longer be handed out (attempts exhausted, or no
|
|
2315
|
+
* room in the mailbox). One bounded list per peer — see MAX_DEAD_LETTERS.
|
|
2316
|
+
*
|
|
2317
|
+
* The OLDEST entry is evicted first: it is the one a `bridge_nack` is least
|
|
2318
|
+
* likely to still want, and reviving resets attempts anyway. The eviction is
|
|
2319
|
+
* COUNTED (`droppedOverflow` + a `mailbox_dropped` event naming the message)
|
|
2320
|
+
* rather than silent, so a full dead-letter list is still visible.
|
|
2321
|
+
*
|
|
2322
|
+
* An evicted TASK is the exception: it settles as a terminal failure. A dead
|
|
2323
|
+
* letter is the last copy of a message the hub promised to keep, and the
|
|
2324
|
+
* sender was told `bridge_nack` can revive it — once it is evicted, no
|
|
2325
|
+
* revival path exists, so leaving the ledger non-terminal would keep
|
|
2326
|
+
* promising something that cannot happen (same rule as `unregistered`). */
|
|
2327
|
+
deadLetter(peerId, messages, now) {
|
|
2328
|
+
const dead = this.deadLetters.get(peerId) ?? [];
|
|
2329
|
+
dead.push(...messages);
|
|
2330
|
+
const evicted = dead.length > MAX_DEAD_LETTERS ? dead.splice(0, dead.length - MAX_DEAD_LETTERS) : [];
|
|
2331
|
+
this.deadLetters.set(peerId, dead);
|
|
2332
|
+
for (const message of messages) {
|
|
2333
|
+
if (message.kind === "task") this.noteTaskDeliveryDropped(message, peerId, "dead-letter", now);
|
|
2334
|
+
}
|
|
2335
|
+
for (const message of evicted) {
|
|
2336
|
+
this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, message.id));
|
|
2337
|
+
this.countDrop(peerId, "overflow", now, message);
|
|
2338
|
+
if (message.kind === "task") this.failTaskForDroppedMessage(message, peerId, "dead-letter-evicted", now);
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
/** Hand a message to `peerId`. Without `manual` it is gone; with it the hub
|
|
2342
|
+
* keeps a lease and the peer must `commit` or `nack` before it expires. */
|
|
2343
|
+
handOut(peerId, message, manual, now) {
|
|
2344
|
+
if (!manual) return message;
|
|
2345
|
+
const key = _AgentHub.leaseKey(peerId, message.id);
|
|
2346
|
+
const attempts = (this.leaseAttempts.get(key) ?? 0) + 1;
|
|
2347
|
+
this.leaseAttempts.set(key, attempts);
|
|
2348
|
+
const expiresAt = now + (this.options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS);
|
|
2349
|
+
const list = this.leases.get(peerId) ?? [];
|
|
2350
|
+
list.push({ message, expiresAt });
|
|
2351
|
+
this.leases.set(peerId, list);
|
|
2352
|
+
this.options.onMailboxesChanged?.();
|
|
2353
|
+
return { ...message, attempts, leaseExpiresAt: expiresAt };
|
|
2354
|
+
}
|
|
2355
|
+
/** Mark leased messages as consumed; returns how many leases were released. */
|
|
2356
|
+
commit(peerId, ids) {
|
|
2357
|
+
const wanted = new Set(ids);
|
|
2358
|
+
const list = this.leases.get(peerId);
|
|
2359
|
+
if (list === void 0) return 0;
|
|
2360
|
+
const still = [];
|
|
2361
|
+
const released = [];
|
|
2362
|
+
for (const lease of list) {
|
|
2363
|
+
if (wanted.has(lease.message.id)) released.push(lease.message);
|
|
2364
|
+
else still.push(lease);
|
|
2365
|
+
}
|
|
2366
|
+
for (const message of released) this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, message.id));
|
|
2367
|
+
if (still.length > 0) this.leases.set(peerId, still);
|
|
2368
|
+
else this.leases.delete(peerId);
|
|
2369
|
+
if (released.length > 0) this.options.onMailboxesChanged?.();
|
|
2370
|
+
return released.length;
|
|
2371
|
+
}
|
|
2372
|
+
/** Give messages back NOW — from live leases or from the dead letters. Attempts
|
|
2373
|
+
* are kept, so a message that keeps failing still eventually dead-letters;
|
|
2374
|
+
* reviving a dead letter resets its count, which is the point of reviving it. */
|
|
2375
|
+
nack(peerId, ids) {
|
|
2376
|
+
const wanted = new Set(ids);
|
|
2377
|
+
const back = [];
|
|
2378
|
+
const list = this.leases.get(peerId);
|
|
2379
|
+
if (list !== void 0) {
|
|
2380
|
+
const still = [];
|
|
2381
|
+
for (const lease of list) {
|
|
2382
|
+
if (wanted.has(lease.message.id)) back.push(lease.message);
|
|
2383
|
+
else still.push(lease);
|
|
2384
|
+
}
|
|
2385
|
+
if (still.length > 0) this.leases.set(peerId, still);
|
|
2386
|
+
else this.leases.delete(peerId);
|
|
2387
|
+
}
|
|
2388
|
+
const dead = this.deadLetters.get(peerId);
|
|
2389
|
+
if (dead !== void 0) {
|
|
2390
|
+
const still = [];
|
|
2391
|
+
for (const message of dead) {
|
|
2392
|
+
if (wanted.has(message.id)) {
|
|
2393
|
+
back.push(message);
|
|
2394
|
+
this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, message.id));
|
|
2395
|
+
} else still.push(message);
|
|
2396
|
+
}
|
|
2397
|
+
if (still.length > 0) this.deadLetters.set(peerId, still);
|
|
2398
|
+
else this.deadLetters.delete(peerId);
|
|
2399
|
+
}
|
|
2400
|
+
return this.requeue(peerId, back, Date.now());
|
|
1149
2401
|
}
|
|
1150
2402
|
/** Non-blocking drain of everything queued for `peer` (optionally from one sender). */
|
|
1151
|
-
poll(peerId, from) {
|
|
2403
|
+
poll(peerId, from, options) {
|
|
2404
|
+
const now = Date.now();
|
|
2405
|
+
this.reapLeases(peerId, now);
|
|
1152
2406
|
const queue = this.queues.get(peerId) ?? [];
|
|
2407
|
+
this.sweepExpired(peerId, queue, now);
|
|
1153
2408
|
const drained = from === void 0 ? queue.splice(0, queue.length) : drainFrom(queue, from);
|
|
1154
2409
|
if (drained.length > 0) this.options.onMailboxesChanged?.();
|
|
1155
|
-
return drained;
|
|
2410
|
+
return drained.map((message) => this.handOut(peerId, message, options?.manual === true, now));
|
|
1156
2411
|
}
|
|
1157
2412
|
/**
|
|
1158
2413
|
* Long-poll for the next message addressed to `peer`: resolves immediately
|
|
1159
2414
|
* when a matching one is queued, otherwise waits up to `timeoutMs` (capped
|
|
1160
2415
|
* by `waitTimeoutMs`) or until `signal` aborts. `from` narrows to one sender.
|
|
1161
|
-
* `ref` narrows to
|
|
2416
|
+
* `ref` narrows to that task's reply — an ack, or the `chat` an assignee hands
|
|
2417
|
+
* the result back in — with `statuses` / `terminalOnly` narrowing the ack half
|
|
2418
|
+
* (see {@link matchesWaiter}).
|
|
1162
2419
|
*
|
|
1163
2420
|
* Takes ONLY the first matching queued message. Calling poll() here would
|
|
1164
2421
|
* drain the whole mailbox and discard every message after the first —
|
|
1165
2422
|
* a multi-message burst (or a reconnect with a full queue) would silently
|
|
1166
2423
|
* lose messages that never reach wait/poll again.
|
|
1167
2424
|
*/
|
|
1168
|
-
wait(peerId, timeoutMs, from, signal, ref, threadId) {
|
|
2425
|
+
wait(peerId, timeoutMs, from, signal, ref, threadId, manual, maxMessages = 1, statuses, terminalOnly) {
|
|
1169
2426
|
const startedAt = Date.now();
|
|
1170
|
-
const matches = (message) => {
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
return
|
|
2427
|
+
const matches = (message) => matchesWaiter({ from, ref, statuses, terminalOnly, threadId }, message, this.taskLedger);
|
|
2428
|
+
const isParty = (record) => record.from === peerId || record.assignees.some((assignee) => assignee.peerId === peerId);
|
|
2429
|
+
const timedOut = () => {
|
|
2430
|
+
const record = ref === void 0 ? void 0 : this.taskLedger.get(ref);
|
|
2431
|
+
return {
|
|
2432
|
+
type: "timeout",
|
|
2433
|
+
waitedMs: Date.now() - startedAt,
|
|
2434
|
+
...record !== void 0 && isParty(record) ? { ref: { status: record.status, a2aState: a2aState(record.status) } } : {}
|
|
2435
|
+
};
|
|
1175
2436
|
};
|
|
2437
|
+
this.reapLeases(peerId, startedAt);
|
|
1176
2438
|
const queue = this.queues.get(peerId);
|
|
2439
|
+
if (queue !== void 0) this.sweepExpired(peerId, queue, startedAt);
|
|
1177
2440
|
if (queue !== void 0 && queue.length > 0) {
|
|
1178
|
-
const
|
|
1179
|
-
|
|
1180
|
-
|
|
2441
|
+
const take = Math.max(1, Math.floor(maxMessages));
|
|
2442
|
+
const taken = [];
|
|
2443
|
+
for (let i = 0; i < queue.length && taken.length < take; ) {
|
|
2444
|
+
if (matches(queue[i])) taken.push(...queue.splice(i, 1));
|
|
2445
|
+
else i++;
|
|
2446
|
+
}
|
|
2447
|
+
if (taken.length > 0) {
|
|
1181
2448
|
this.options.onMailboxesChanged?.();
|
|
1182
|
-
|
|
2449
|
+
const delivered = taken.map((queued) => this.handOut(peerId, queued, manual === true, startedAt));
|
|
2450
|
+
return Promise.resolve(take > 1 ? { type: "messages", messages: delivered } : { type: "message", message: delivered[0] });
|
|
1183
2451
|
}
|
|
1184
2452
|
}
|
|
1185
2453
|
const budget = Math.max(1, Math.min(Math.floor(timeoutMs), this.options.waitTimeoutMs));
|
|
@@ -1194,7 +2462,7 @@ var AgentHub = class {
|
|
|
1194
2462
|
};
|
|
1195
2463
|
const onAbort = () => {
|
|
1196
2464
|
removeFromRegistry();
|
|
1197
|
-
settle(
|
|
2465
|
+
settle(timedOut());
|
|
1198
2466
|
};
|
|
1199
2467
|
const removeFromRegistry = () => {
|
|
1200
2468
|
const list2 = this.waiters.get(peerId);
|
|
@@ -1202,7 +2470,7 @@ var AgentHub = class {
|
|
|
1202
2470
|
};
|
|
1203
2471
|
const timer = setTimeout(() => {
|
|
1204
2472
|
removeFromRegistry();
|
|
1205
|
-
settle(
|
|
2473
|
+
settle(timedOut());
|
|
1206
2474
|
}, budget);
|
|
1207
2475
|
if (signal?.aborted) {
|
|
1208
2476
|
onAbort();
|
|
@@ -1216,15 +2484,21 @@ var AgentHub = class {
|
|
|
1216
2484
|
onAbort,
|
|
1217
2485
|
...from !== void 0 ? { from } : {},
|
|
1218
2486
|
...ref !== void 0 ? { ref } : {},
|
|
1219
|
-
...
|
|
2487
|
+
...statuses !== void 0 ? { statuses } : {},
|
|
2488
|
+
...terminalOnly === true ? { terminalOnly } : {},
|
|
2489
|
+
...threadId !== void 0 ? { threadId } : {},
|
|
2490
|
+
...manual === true ? { manual } : {},
|
|
2491
|
+
// A batch request keeps the batch SHAPE even when the wait ends with a
|
|
2492
|
+
// single message, so the caller's field access does not depend on timing.
|
|
2493
|
+
...maxMessages > 1 ? { batch: true } : {}
|
|
1220
2494
|
});
|
|
1221
2495
|
this.waiters.set(peerId, list);
|
|
1222
2496
|
});
|
|
1223
2497
|
}
|
|
1224
2498
|
/** Create a message from `from` addressed to `to` and deliver it. `to` may
|
|
1225
2499
|
* be a peer id, {@link BROADCAST}, or a group id. */
|
|
1226
|
-
route(from, to, kind, content, ref, threadId) {
|
|
1227
|
-
const message = this.compose(from, to, kind, content, ref, threadId);
|
|
2500
|
+
route(from, to, kind, content, ref, threadId, expiresAt, system = false, priority) {
|
|
2501
|
+
const message = this.compose(from, to, kind, content, ref, threadId, expiresAt, system, priority);
|
|
1228
2502
|
this.dispatch(message);
|
|
1229
2503
|
return message;
|
|
1230
2504
|
}
|
|
@@ -1232,22 +2506,25 @@ var AgentHub = class {
|
|
|
1232
2506
|
* peer id, {@link BROADCAST}, or a group id). Composing and dispatching are
|
|
1233
2507
|
* separate steps because a caller may need ledger state to exist before
|
|
1234
2508
|
* anything reaches a recipient — {@link sendTask} books delivery times. */
|
|
1235
|
-
compose(from, to, kind, content, ref, threadId) {
|
|
1236
|
-
if (!this.lastSeen.has(from)) throw new Error(`sender not registered: ${from}`);
|
|
2509
|
+
compose(from, to, kind, content, ref, threadId, expiresAt, system = false, priority) {
|
|
2510
|
+
if (!system && !this.lastSeen.has(from)) throw new Error(`sender not registered: ${from}`);
|
|
1237
2511
|
const group = this.groups.get(to);
|
|
1238
|
-
|
|
2512
|
+
const known = this.lastSeen.has(to) || this.parkedAt.has(to);
|
|
2513
|
+
if (to !== BROADCAST && group === void 0 && !known) {
|
|
1239
2514
|
throw new Error(`unknown recipient: ${to} (registered peers: ${this.peers().join(", ") || "none"})`);
|
|
1240
2515
|
}
|
|
2516
|
+
if (group !== void 0 && !system && !group.members.includes(from)) {
|
|
2517
|
+
throw new Error(`peer '${from}' is not a member of group '${to}'`);
|
|
2518
|
+
}
|
|
1241
2519
|
let hop = 0;
|
|
1242
2520
|
if (ref !== void 0) {
|
|
1243
2521
|
const parent = this.historyRing.findLast((m) => m.id === ref);
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
throw new Error(`hop limit exceeded (max ${MAX_HOP}): start a new task/thread instead of extending this chain`);
|
|
1247
|
-
}
|
|
2522
|
+
const ceiling = kind === "task" && parent?.kind === "task" ? MAX_HOP : MAX_REPLY_CHAIN;
|
|
2523
|
+
hop = Math.min((parent?.hop ?? 0) + 1, ceiling);
|
|
1248
2524
|
}
|
|
1249
2525
|
const message = {
|
|
1250
2526
|
id: randomUUID(),
|
|
2527
|
+
seq: ++this.seqCounter,
|
|
1251
2528
|
from,
|
|
1252
2529
|
to,
|
|
1253
2530
|
kind,
|
|
@@ -1256,9 +2533,15 @@ var AgentHub = class {
|
|
|
1256
2533
|
...threadId !== void 0 ? { threadId } : {},
|
|
1257
2534
|
...group !== void 0 ? { channel: group.id } : {},
|
|
1258
2535
|
...hop > 0 ? { hop } : {},
|
|
2536
|
+
...expiresAt !== void 0 ? { expiresAt } : {},
|
|
2537
|
+
// Only a real priority is stored: an unset one must not appear on the wire,
|
|
2538
|
+
// or every reader has to distinguish 0 from "absent" for no reason.
|
|
2539
|
+
...priority !== void 0 ? { priority } : {},
|
|
1259
2540
|
ts: Date.now()
|
|
1260
2541
|
};
|
|
1261
|
-
this.lastSeen.set(from, message.ts);
|
|
2542
|
+
if (!system) this.lastSeen.set(from, message.ts);
|
|
2543
|
+
this.bumpTraffic(from, "sent");
|
|
2544
|
+
if (kind === "ack") this.bumpTraffic(from, "acked");
|
|
1262
2545
|
this.remember(message);
|
|
1263
2546
|
return message;
|
|
1264
2547
|
}
|
|
@@ -1266,7 +2549,7 @@ var AgentHub = class {
|
|
|
1266
2549
|
* or the single addressed peer. */
|
|
1267
2550
|
dispatch(message) {
|
|
1268
2551
|
if (message.to === BROADCAST) {
|
|
1269
|
-
for (const peer of this.
|
|
2552
|
+
for (const peer of this.audience()) {
|
|
1270
2553
|
if (peer !== message.from) this.deliver(peer, message);
|
|
1271
2554
|
}
|
|
1272
2555
|
return;
|
|
@@ -1284,26 +2567,43 @@ var AgentHub = class {
|
|
|
1284
2567
|
* History / onMessage are recorded by the caller (route / sendToGroup) —
|
|
1285
2568
|
* exactly once per message, never per fan-out target. */
|
|
1286
2569
|
deliver(target, message) {
|
|
2570
|
+
this.bumpTraffic(target, "received");
|
|
2571
|
+
if (message.expiresAt !== void 0 && message.expiresAt <= Date.now()) {
|
|
2572
|
+
const now = Date.now();
|
|
2573
|
+
this.countDrop(target, "expired", now, message);
|
|
2574
|
+
if (message.kind === "task") this.noteTaskDeliveryDropped(message, target, "expired", now);
|
|
2575
|
+
return;
|
|
2576
|
+
}
|
|
1287
2577
|
const list = this.waiters.get(target) ?? [];
|
|
1288
|
-
const index = list.findIndex((waiter) =>
|
|
1289
|
-
if (waiter.from !== void 0 && waiter.from !== message.from) return false;
|
|
1290
|
-
if (waiter.ref !== void 0 && !(message.kind === "ack" && message.ref === waiter.ref)) return false;
|
|
1291
|
-
if (waiter.threadId !== void 0 && message.threadId !== waiter.threadId) return false;
|
|
1292
|
-
return true;
|
|
1293
|
-
});
|
|
1294
|
-
if (message.kind === "task") this.markTaskDelivered(message.id, target, message.ts);
|
|
2578
|
+
const index = list.findIndex((waiter) => matchesWaiter(waiter, message, this.taskLedger));
|
|
1295
2579
|
if (index >= 0) {
|
|
2580
|
+
if (message.kind === "task") this.markTaskDelivered(message.id, target, message.ts);
|
|
1296
2581
|
const [waiter] = list.splice(index, 1);
|
|
1297
2582
|
this.waiters.set(target, list);
|
|
1298
2583
|
clearTimeout(waiter.timer);
|
|
1299
|
-
|
|
2584
|
+
const delivered = this.handOut(target, message, waiter.manual === true, message.ts);
|
|
2585
|
+
waiter.resolve(waiter.batch === true ? { type: "messages", messages: [delivered] } : { type: "message", message: delivered });
|
|
2586
|
+
return;
|
|
2587
|
+
}
|
|
2588
|
+
if (!this.takeToken(target, Date.now())) {
|
|
2589
|
+
const now = Date.now();
|
|
2590
|
+
this.countDrop(target, "rate", now, message);
|
|
2591
|
+
if (message.kind === "task") this.noteTaskDeliveryDropped(message, target, "rate", now);
|
|
1300
2592
|
return;
|
|
1301
2593
|
}
|
|
1302
2594
|
const queue = this.queues.get(target) ?? [];
|
|
1303
|
-
if (queue.length >= this.options.maxQueue)
|
|
1304
|
-
|
|
2595
|
+
if (queue.length >= this.options.maxQueue) {
|
|
2596
|
+
const [evicted] = queue.splice(lowestPriorityIndex(queue), 1);
|
|
2597
|
+
const now = Date.now();
|
|
2598
|
+
if (evicted !== void 0) this.leaseAttempts.delete(_AgentHub.leaseKey(target, evicted.id));
|
|
2599
|
+
this.countDrop(target, "overflow", now, evicted);
|
|
2600
|
+
if (evicted !== void 0 && evicted.kind === "task") this.noteTaskDeliveryDropped(evicted, target, "overflow", now);
|
|
2601
|
+
}
|
|
2602
|
+
insertByPriority(queue, [message]);
|
|
1305
2603
|
this.queues.set(target, queue);
|
|
2604
|
+
if (message.kind === "task") this.markTaskDelivered(message.id, target, message.ts);
|
|
1306
2605
|
this.options.onQueued?.(message, target);
|
|
2606
|
+
if (message.kind === "task") this.options.onTaskQueued?.(message, target);
|
|
1307
2607
|
}
|
|
1308
2608
|
/** Append a sent message to the history ring (and fire the persistence /
|
|
1309
2609
|
* relay hooks). Exactly one call per message — see route() / sendToGroup(). */
|
|
@@ -1316,11 +2616,29 @@ var AgentHub = class {
|
|
|
1316
2616
|
function importHop(value) {
|
|
1317
2617
|
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
|
|
1318
2618
|
}
|
|
2619
|
+
function insertByPriority(queue, messages) {
|
|
2620
|
+
for (const message of messages) {
|
|
2621
|
+
let at = queue.length;
|
|
2622
|
+
while (at > 0 && priorityOf(queue[at - 1]) < priorityOf(message)) at--;
|
|
2623
|
+
queue.splice(at, 0, message);
|
|
2624
|
+
}
|
|
2625
|
+
}
|
|
2626
|
+
function lowestPriorityIndex(queue) {
|
|
2627
|
+
if (queue.length === 0) return -1;
|
|
2628
|
+
const lowest = priorityOf(queue[queue.length - 1]);
|
|
2629
|
+
let victim = queue.length - 1;
|
|
2630
|
+
while (victim > 0 && priorityOf(queue[victim - 1]) === lowest) victim--;
|
|
2631
|
+
return victim;
|
|
2632
|
+
}
|
|
2633
|
+
function priorityOf(message) {
|
|
2634
|
+
const value = message.priority;
|
|
2635
|
+
return value === 1 || value === 2 ? value : 0;
|
|
2636
|
+
}
|
|
1319
2637
|
function drainFrom(queue, from) {
|
|
1320
2638
|
const kept = [];
|
|
1321
2639
|
const drained = [];
|
|
1322
2640
|
for (const message of queue) {
|
|
1323
|
-
if (message.from === from) drained.push(message);
|
|
2641
|
+
if (message.from === from || message.from === HUB_PEER) drained.push(message);
|
|
1324
2642
|
else kept.push(message);
|
|
1325
2643
|
}
|
|
1326
2644
|
queue.splice(0, queue.length, ...kept);
|
|
@@ -1330,6 +2648,41 @@ function omit(value, key) {
|
|
|
1330
2648
|
const { [key]: _dropped, ...rest } = value;
|
|
1331
2649
|
return rest;
|
|
1332
2650
|
}
|
|
2651
|
+
function matchesWaiter(waiter, message, ledger) {
|
|
2652
|
+
const fromHub = message.from === HUB_PEER;
|
|
2653
|
+
if (!fromHub && waiter.from !== void 0 && message.from !== waiter.from) return false;
|
|
2654
|
+
if (!fromHub && waiter.ref !== void 0) {
|
|
2655
|
+
if (message.ref !== waiter.ref) return false;
|
|
2656
|
+
if (message.kind !== "ack" && message.kind !== "chat") return false;
|
|
2657
|
+
if (message.kind === "chat") {
|
|
2658
|
+
const record = ledger.get(waiter.ref);
|
|
2659
|
+
if (record !== void 0 && record.from !== message.from && !record.assignees.some((assignee) => assignee.peerId === message.from)) return false;
|
|
2660
|
+
}
|
|
2661
|
+
if (waiter.statuses !== void 0 || waiter.terminalOnly === true) {
|
|
2662
|
+
const status = ackStatusOf(message);
|
|
2663
|
+
if (status === void 0) return false;
|
|
2664
|
+
if (waiter.statuses !== void 0 && !waiter.statuses.includes(status)) return false;
|
|
2665
|
+
if (waiter.terminalOnly === true && !TERMINAL_TASK_STATUSES.includes(ackToTaskStatus(status))) return false;
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
if (waiter.threadId !== void 0 && message.threadId !== waiter.threadId) return false;
|
|
2669
|
+
return true;
|
|
2670
|
+
}
|
|
2671
|
+
function ackStatusOf(message) {
|
|
2672
|
+
if (message.kind !== "ack") return void 0;
|
|
2673
|
+
const decoded = decodeContent("ack", message.content);
|
|
2674
|
+
if (typeof decoded === "string") return void 0;
|
|
2675
|
+
const status = decoded.status;
|
|
2676
|
+
if (typeof status !== "string") return void 0;
|
|
2677
|
+
return ALL_ACK_STATUSES.includes(status) ? status : void 0;
|
|
2678
|
+
}
|
|
2679
|
+
function syntheticEventId(taskId, reason) {
|
|
2680
|
+
if (reason === "expired") return `expired-${taskId}`;
|
|
2681
|
+
if (reason === "dead-letter") return `dead-letter-${taskId}`;
|
|
2682
|
+
if (reason === "dead-letter-evicted") return `evicted-${taskId}`;
|
|
2683
|
+
if (reason === "unregistered") return `unregistered-${taskId}`;
|
|
2684
|
+
return `dropped-${taskId}`;
|
|
2685
|
+
}
|
|
1333
2686
|
|
|
1334
2687
|
// src/auth.ts
|
|
1335
2688
|
import { randomBytes } from "node:crypto";
|
|
@@ -1337,6 +2690,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSyn
|
|
|
1337
2690
|
import { dirname } from "node:path";
|
|
1338
2691
|
var ANON_JOIN_PEER = "__join__";
|
|
1339
2692
|
var TOKEN_PATTERN = /^[A-Za-z0-9._:-]{16,128}$/;
|
|
2693
|
+
var PLACEHOLDER_TOKEN = /CHANGE[-_]?ME/i;
|
|
1340
2694
|
function loadTokenFile(file) {
|
|
1341
2695
|
let parsed;
|
|
1342
2696
|
try {
|
|
@@ -1355,7 +2709,10 @@ function loadTokenFile(file) {
|
|
|
1355
2709
|
if (typeof token !== "string" || !TOKEN_PATTERN.test(token)) {
|
|
1356
2710
|
throw new Error(msg("has an invalid token (expect 16-128 chars of [A-Za-z0-9._:-])"));
|
|
1357
2711
|
}
|
|
1358
|
-
if (
|
|
2712
|
+
if (PLACEHOLDER_TOKEN.test(token)) {
|
|
2713
|
+
throw new Error(msg("uses the example placeholder token \u2014 generate one with `agent-comm-hub auth gen`"));
|
|
2714
|
+
}
|
|
2715
|
+
if (typeof peer !== "string" || !PEER_ID_PATTERN.test(peer) || peer === BROADCAST || peer === HUB_PEER) {
|
|
1359
2716
|
throw new Error(msg(`has an invalid peer id '${String(peer)}'`));
|
|
1360
2717
|
}
|
|
1361
2718
|
if (role !== "agent" && role !== "manager") {
|
|
@@ -1370,8 +2727,19 @@ function loadTokenFile(file) {
|
|
|
1370
2727
|
peers.add(peer);
|
|
1371
2728
|
});
|
|
1372
2729
|
if (table.size === 0) throw new Error(`auth token file ${file}: no tokens defined`);
|
|
2730
|
+
warnIfTokenFileIsReadableByOthers(file);
|
|
1373
2731
|
return table;
|
|
1374
2732
|
}
|
|
2733
|
+
function warnIfTokenFileIsReadableByOthers(file) {
|
|
2734
|
+
if (process.platform === "win32") return;
|
|
2735
|
+
try {
|
|
2736
|
+
const mode = statSync(file).mode & 511;
|
|
2737
|
+
if ((mode & 63) !== 0) {
|
|
2738
|
+
console.warn(`warning: ${file} is readable by group/other (mode ${mode.toString(8)}) \u2014 chmod 600 it`);
|
|
2739
|
+
}
|
|
2740
|
+
} catch {
|
|
2741
|
+
}
|
|
2742
|
+
}
|
|
1375
2743
|
function tokenTable(map) {
|
|
1376
2744
|
return {
|
|
1377
2745
|
authenticate: (token) => token === void 0 ? void 0 : map.get(token)
|
|
@@ -1467,7 +2835,10 @@ function loadTokenFileVoid(rows) {
|
|
|
1467
2835
|
const peers = /* @__PURE__ */ new Set();
|
|
1468
2836
|
for (const { token, peer, role, owner } of rows) {
|
|
1469
2837
|
if (!TOKEN_PATTERN.test(token)) throw new Error(`invalid token for peer '${peer}'`);
|
|
1470
|
-
if (
|
|
2838
|
+
if (PLACEHOLDER_TOKEN.test(token)) {
|
|
2839
|
+
throw new Error(`example placeholder token for peer '${peer}' \u2014 generate one with \`agent-comm-hub auth gen\``);
|
|
2840
|
+
}
|
|
2841
|
+
if (!PEER_ID_PATTERN.test(peer) || peer === BROADCAST || peer === HUB_PEER) throw new Error(`invalid peer id '${peer}'`);
|
|
1471
2842
|
if (role !== "agent" && role !== "manager") throw new Error(`invalid role '${role}'`);
|
|
1472
2843
|
if (table.has(token)) throw new Error("duplicate token");
|
|
1473
2844
|
if (peers.has(peer)) throw new Error(`duplicate peer '${peer}'`);
|
|
@@ -1486,6 +2857,9 @@ function present(message) {
|
|
|
1486
2857
|
...channel !== void 0 ? { channel } : {},
|
|
1487
2858
|
...threadId !== void 0 ? { threadId } : {},
|
|
1488
2859
|
...hop !== void 0 ? { hop } : {},
|
|
2860
|
+
// A2A speaks `taskId` / `contextId`; our names stay, these ride along.
|
|
2861
|
+
...message.kind === "ack" && ref !== void 0 ? { taskId: ref } : {},
|
|
2862
|
+
...threadId !== void 0 ? { contextId: threadId } : {},
|
|
1489
2863
|
content: decodeContent(message.kind, message.content)
|
|
1490
2864
|
};
|
|
1491
2865
|
}
|
|
@@ -1506,12 +2880,13 @@ function autoRegisterPeer(hub, registry, sessionId, clientName, clientVersion) {
|
|
|
1506
2880
|
if (bound !== void 0) return bound;
|
|
1507
2881
|
if (registry.isSuppressed(sessionId)) return void 0;
|
|
1508
2882
|
const tokenPeer = registry.tokenFor(sessionId)?.peer;
|
|
1509
|
-
const
|
|
2883
|
+
const derived = tokenPeer === ANON_JOIN_PEER ? `join-${sanitizePeerId(clientName ?? "agent")}-${Math.random().toString(36).slice(2, 6)}` : tokenPeer ?? sanitizePeerId(clientName ?? "agent");
|
|
2884
|
+
const peerId = derived === BROADCAST || derived === HUB_PEER || hub.groupOf(derived) !== void 0 ? `agent-${Math.random().toString(36).slice(2, 6)}` : derived;
|
|
1510
2885
|
if (!hub.has(peerId)) {
|
|
1511
2886
|
hub.register(peerId, {
|
|
1512
2887
|
...clientName !== void 0 ? { name: clientName } : {},
|
|
1513
2888
|
...clientVersion !== void 0 ? { version: clientVersion } : {}
|
|
1514
|
-
});
|
|
2889
|
+
}, { reclaim: true });
|
|
1515
2890
|
}
|
|
1516
2891
|
registry.bindPeer(sessionId, peerId);
|
|
1517
2892
|
hub.touch(peerId);
|
|
@@ -1550,13 +2925,29 @@ function rosterFor(hub, registry) {
|
|
|
1550
2925
|
...alias !== void 0 ? { alias } : {},
|
|
1551
2926
|
...clientName !== void 0 ? { clientName } : {},
|
|
1552
2927
|
...clientVersion !== void 0 ? { clientVersion } : {},
|
|
2928
|
+
// The announced card rides with the roster: `bridge_peers` is how an agent
|
|
2929
|
+
// sees who else is here, and a card nobody can read is not announced.
|
|
2930
|
+
...profile?.card !== void 0 ? { card: profile.card } : {},
|
|
1553
2931
|
...peerAnon.get(peer.id) === true ? { anonymous: true } : {},
|
|
1554
2932
|
...ips !== void 0 && ips.length > 0 ? { clientIps: ips } : {},
|
|
1555
2933
|
connected: peer.connected,
|
|
2934
|
+
// W7: keep the reachability verdict and the queue depth in the tool output —
|
|
2935
|
+
// `connected: false` alone cannot say "idle, will read it later" apart from
|
|
2936
|
+
// "gone, and your message is nowhere".
|
|
2937
|
+
reachable: peer.reachable,
|
|
2938
|
+
queued: peer.queued,
|
|
1556
2939
|
lastSeenMs: peer.lastSeenMs
|
|
1557
2940
|
};
|
|
1558
2941
|
});
|
|
1559
2942
|
}
|
|
2943
|
+
var MAX_LEASE_IDS = 1e3;
|
|
2944
|
+
function isManagerCaller(registry, sessionId, peer, options) {
|
|
2945
|
+
if (registry.tokenFor(sessionId)?.role === "manager") return true;
|
|
2946
|
+
if (options.managerTokenRequired === true) return registry.isManagerSession(sessionId);
|
|
2947
|
+
const managers = options.managerPeers ?? "all";
|
|
2948
|
+
if (managers === "all") return true;
|
|
2949
|
+
return peer !== void 0 && managers.has(peer);
|
|
2950
|
+
}
|
|
1560
2951
|
function hubTools(hub, registry, options) {
|
|
1561
2952
|
const schema = (properties, required = []) => ({
|
|
1562
2953
|
type: "object",
|
|
@@ -1567,6 +2958,108 @@ function hubTools(hub, registry, options) {
|
|
|
1567
2958
|
const str = (description) => ({ type: "string", description });
|
|
1568
2959
|
const int = (description) => ({ type: "integer", description });
|
|
1569
2960
|
const optStr = str;
|
|
2961
|
+
const priorityField = () => ({
|
|
2962
|
+
type: "integer",
|
|
2963
|
+
enum: [0, 1, 2],
|
|
2964
|
+
description: "Delivery importance inside the recipient's mailbox: 2 beats 1 beats 0. Default 0 (plain FIFO). Also decides what overflow drops \u2014 the LEAST important queued message goes, not the oldest."
|
|
2965
|
+
});
|
|
2966
|
+
const optPriority = (value) => value === 0 || value === 1 || value === 2 ? { priority: value } : {};
|
|
2967
|
+
const idList = (value, tool) => {
|
|
2968
|
+
if (!Array.isArray(value)) throw new Error(`${tool} expects ids: an array of message ids`);
|
|
2969
|
+
if (value.length > MAX_LEASE_IDS) {
|
|
2970
|
+
throw new Error(`${tool} accepts at most ${MAX_LEASE_IDS} ids per call (got ${value.length}); commit or nack in batches`);
|
|
2971
|
+
}
|
|
2972
|
+
const ids = value.filter((id) => typeof id === "string" && id !== "");
|
|
2973
|
+
if (ids.length === 0) throw new Error(`${tool} expects at least one message id`);
|
|
2974
|
+
return ids;
|
|
2975
|
+
};
|
|
2976
|
+
const ackStatuses = (value, terminalOnly) => {
|
|
2977
|
+
if (value === void 0) return void 0;
|
|
2978
|
+
if (!Array.isArray(value)) throw new Error("statuses must be an array of ack statuses");
|
|
2979
|
+
if (value.length === 0) throw new Error("statuses must not be empty \u2014 omit it to wait for any ack");
|
|
2980
|
+
const out = [];
|
|
2981
|
+
for (const entry of value) {
|
|
2982
|
+
if (typeof entry !== "string" || !ALL_ACK_STATUSES.includes(entry)) {
|
|
2983
|
+
throw new Error(`invalid statuses entry: ${JSON.stringify(entry)} (expected one of ${ALL_ACK_STATUSES.join(" | ")})`);
|
|
2984
|
+
}
|
|
2985
|
+
out.push(entry);
|
|
2986
|
+
}
|
|
2987
|
+
if (terminalOnly) {
|
|
2988
|
+
const terminalAcks = TERMINAL_TASK_STATUSES.filter((status) => ALL_ACK_STATUSES.includes(status));
|
|
2989
|
+
if (!out.some((status) => terminalAcks.includes(ackToTaskStatus(status)))) {
|
|
2990
|
+
throw new Error(`statuses and terminalOnly are combined by intersection, and ${out.join(" | ")} contains no terminal ack status (${terminalAcks.join(" | ")}) \u2014 the wait could never resolve`);
|
|
2991
|
+
}
|
|
2992
|
+
}
|
|
2993
|
+
return out;
|
|
2994
|
+
};
|
|
2995
|
+
const deadline = (value) => {
|
|
2996
|
+
const at = Number(value);
|
|
2997
|
+
if (!Number.isFinite(at) || at <= 0) throw new Error(`invalid expiresAt: ${String(value)} (expected epoch milliseconds)`);
|
|
2998
|
+
if (at <= Date.now()) throw new Error(`expiresAt is already in the past: ${new Date(at).toISOString()}`);
|
|
2999
|
+
return at;
|
|
3000
|
+
};
|
|
3001
|
+
const parseArtifacts = (value) => {
|
|
3002
|
+
if (value === void 0) return void 0;
|
|
3003
|
+
if (!Array.isArray(value)) throw new Error("artifacts must be an array of {name, text?/url?} objects");
|
|
3004
|
+
const out = [];
|
|
3005
|
+
for (const [index, entry] of value.entries()) {
|
|
3006
|
+
if (typeof entry !== "object" || entry === null) throw new Error(`artifacts[${index}] must be an object`);
|
|
3007
|
+
const raw = entry;
|
|
3008
|
+
if (typeof raw.name !== "string" || raw.name === "") throw new Error(`artifacts[${index}].name is required`);
|
|
3009
|
+
const artifact = { name: raw.name };
|
|
3010
|
+
if (typeof raw.mimeType === "string" && raw.mimeType !== "") artifact.mimeType = raw.mimeType;
|
|
3011
|
+
if (typeof raw.text === "string") artifact.text = raw.text;
|
|
3012
|
+
if (typeof raw.url === "string" && raw.url !== "") artifact.url = raw.url;
|
|
3013
|
+
if (artifact.text === void 0 && artifact.url === void 0) {
|
|
3014
|
+
throw new Error(`artifacts[${index}] needs text or url \u2014 an artifact with neither says nothing`);
|
|
3015
|
+
}
|
|
3016
|
+
out.push(artifact);
|
|
3017
|
+
}
|
|
3018
|
+
return out.length > 0 ? out : void 0;
|
|
3019
|
+
};
|
|
3020
|
+
const parseCard = (value) => {
|
|
3021
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("card must be an object");
|
|
3022
|
+
const raw = value;
|
|
3023
|
+
const card = {};
|
|
3024
|
+
if (raw.skills !== void 0) {
|
|
3025
|
+
if (!Array.isArray(raw.skills)) throw new Error("card.skills must be an array");
|
|
3026
|
+
card.skills = raw.skills.map((entry, index) => {
|
|
3027
|
+
if (typeof entry !== "object" || entry === null) throw new Error(`card.skills[${index}] must be an object`);
|
|
3028
|
+
const skill = entry;
|
|
3029
|
+
if (typeof skill.id !== "string" || skill.id === "") throw new Error(`card.skills[${index}].id is required`);
|
|
3030
|
+
if (typeof skill.name !== "string" || skill.name === "") throw new Error(`card.skills[${index}].name is required`);
|
|
3031
|
+
return {
|
|
3032
|
+
id: skill.id,
|
|
3033
|
+
name: skill.name,
|
|
3034
|
+
...typeof skill.description === "string" ? { description: skill.description } : {},
|
|
3035
|
+
...Array.isArray(skill.tags) ? { tags: skill.tags.filter((tag) => typeof tag === "string") } : {}
|
|
3036
|
+
};
|
|
3037
|
+
});
|
|
3038
|
+
}
|
|
3039
|
+
if (raw.acceptsTasks !== void 0) {
|
|
3040
|
+
if (typeof raw.acceptsTasks !== "boolean") throw new Error("card.acceptsTasks must be a boolean");
|
|
3041
|
+
card.acceptsTasks = raw.acceptsTasks;
|
|
3042
|
+
}
|
|
3043
|
+
if (raw.concurrency !== void 0) {
|
|
3044
|
+
if (!Number.isInteger(raw.concurrency) || raw.concurrency < 0) throw new Error("card.concurrency must be a non-negative integer");
|
|
3045
|
+
card.concurrency = raw.concurrency;
|
|
3046
|
+
}
|
|
3047
|
+
for (const key of ["inputModes", "outputModes"]) {
|
|
3048
|
+
const list = raw[key];
|
|
3049
|
+
if (list === void 0) continue;
|
|
3050
|
+
if (!Array.isArray(list)) throw new Error(`card.${key} must be an array of strings`);
|
|
3051
|
+
card[key] = list.filter((entry) => typeof entry === "string");
|
|
3052
|
+
}
|
|
3053
|
+
if (raw.runner !== void 0) {
|
|
3054
|
+
if (!["herdr", "cli", "http", "none"].includes(String(raw.runner))) throw new Error("card.runner must be one of herdr | cli | http | none");
|
|
3055
|
+
card.runner = raw.runner;
|
|
3056
|
+
}
|
|
3057
|
+
if (raw.endpoint !== void 0) {
|
|
3058
|
+
if (typeof raw.endpoint !== "string" || raw.endpoint === "") throw new Error("card.endpoint must be a non-empty string");
|
|
3059
|
+
card.endpoint = raw.endpoint;
|
|
3060
|
+
}
|
|
3061
|
+
return card;
|
|
3062
|
+
};
|
|
1570
3063
|
const requirePeer = (sessionId) => {
|
|
1571
3064
|
const bound = registry.peerFor(sessionId);
|
|
1572
3065
|
if (bound !== void 0) {
|
|
@@ -1583,16 +3076,26 @@ function hubTools(hub, registry, options) {
|
|
|
1583
3076
|
const receipt = (message) => ({
|
|
1584
3077
|
ok: true,
|
|
1585
3078
|
id: message.id,
|
|
3079
|
+
// The sender needs this back: it is the cursor to record.
|
|
3080
|
+
...message.seq !== void 0 ? { seq: message.seq } : {},
|
|
1586
3081
|
from: message.from,
|
|
1587
3082
|
to: message.to,
|
|
1588
3083
|
kind: message.kind,
|
|
1589
3084
|
...message.ref !== void 0 ? { ref: message.ref } : {},
|
|
1590
3085
|
...message.channel !== void 0 ? { channel: message.channel } : {},
|
|
3086
|
+
// A2A aliases (additive): a task receipt answers with `taskId`, and a
|
|
3087
|
+
// threaded message carries its `contextId`.
|
|
3088
|
+
...message.kind === "task" ? { taskId: message.id } : {},
|
|
3089
|
+
...message.threadId !== void 0 ? { contextId: message.threadId } : {},
|
|
1591
3090
|
...message.threadId !== void 0 ? { threadId: message.threadId } : {},
|
|
1592
3091
|
...message.hop !== void 0 ? { hop: message.hop } : {},
|
|
1593
3092
|
ts: message.ts
|
|
1594
3093
|
});
|
|
1595
|
-
const presentWait = (result) =>
|
|
3094
|
+
const presentWait = (result) => {
|
|
3095
|
+
if (result.type === "timeout") return result;
|
|
3096
|
+
if (result.type === "messages") return { type: "messages", messages: result.messages.map(present) };
|
|
3097
|
+
return { type: "message", message: present(result.message) };
|
|
3098
|
+
};
|
|
1596
3099
|
const checkControl = (peer) => {
|
|
1597
3100
|
const herdr = options.herdr;
|
|
1598
3101
|
if (herdr === void 0) {
|
|
@@ -1605,17 +3108,27 @@ function hubTools(hub, registry, options) {
|
|
|
1605
3108
|
return herdr;
|
|
1606
3109
|
};
|
|
1607
3110
|
const requireManager = (peer, action, sessionId) => {
|
|
1608
|
-
if (registry
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
}
|
|
3111
|
+
if (isManagerCaller(registry, sessionId, peer, options)) return;
|
|
3112
|
+
throw new Error(
|
|
3113
|
+
options.managerTokenRequired === true ? `peer '${peer}' is not a hub manager \u2014 ${action} requires the manager token (Authorization: Bearer <token>)` : `peer '${peer}' is not a hub manager \u2014 ${action} requires manager rights`
|
|
3114
|
+
);
|
|
1613
3115
|
};
|
|
1614
3116
|
const asStatuses = (value) => {
|
|
1615
3117
|
if (!Array.isArray(value)) return void 0;
|
|
1616
3118
|
const statuses = value.map(String).filter((status) => AGENT_STATUSES.includes(status));
|
|
1617
3119
|
return statuses.length > 0 ? statuses : void 0;
|
|
1618
3120
|
};
|
|
3121
|
+
const requireArgs = (tool, handler) => {
|
|
3122
|
+
const required = tool.inputSchema.required ?? [];
|
|
3123
|
+
if (required.length === 0) return handler;
|
|
3124
|
+
return async (args, sessionId) => {
|
|
3125
|
+
const missing = required.filter((name) => args?.[name] === void 0);
|
|
3126
|
+
if (missing.length > 0) {
|
|
3127
|
+
throw new Error(`missing required argument(s) for ${tool.name}: ${missing.join(", ")}`);
|
|
3128
|
+
}
|
|
3129
|
+
return handler(args, sessionId);
|
|
3130
|
+
};
|
|
3131
|
+
};
|
|
1619
3132
|
const wrap = (peerAware, handler) => async (args, sessionId) => {
|
|
1620
3133
|
const peer = peerAware ? requirePeer(sessionId) : "";
|
|
1621
3134
|
return handler(args, peer, sessionId);
|
|
@@ -1629,13 +3142,20 @@ function hubTools(hub, registry, options) {
|
|
|
1629
3142
|
alias: optStr("Optional display name (1-64 chars, spaces/CJK allowed). Routing still uses peerId.")
|
|
1630
3143
|
}, ["peerId"]),
|
|
1631
3144
|
handler: async (args, sessionId) => {
|
|
1632
|
-
const
|
|
3145
|
+
const boundId = registry.peerFor(sessionId);
|
|
3146
|
+
const peerId = args.peerId === void 0 ? boundId : String(args.peerId);
|
|
3147
|
+
if (peerId === void 0) {
|
|
3148
|
+
throw new Error('no peer to register \u2014 pass peerId (e.g. {"peerId":"mavis"}); this session is not bound to a peer yet');
|
|
3149
|
+
}
|
|
1633
3150
|
if (!PEER_ID_PATTERN.test(peerId)) {
|
|
1634
3151
|
throw new Error(`invalid peerId: ${peerId} (expected [A-Za-z0-9._:-]{1,64})`);
|
|
1635
3152
|
}
|
|
1636
3153
|
if (peerId === BROADCAST) {
|
|
1637
3154
|
throw new Error(`reserved peer id: ${peerId} (it is the broadcast address)`);
|
|
1638
3155
|
}
|
|
3156
|
+
if (peerId === HUB_PEER) {
|
|
3157
|
+
throw new Error(`reserved peer id: ${peerId} (the hub uses it for its own notices)`);
|
|
3158
|
+
}
|
|
1639
3159
|
const alias = args.alias === void 0 ? void 0 : sanitizeAlias(String(args.alias));
|
|
1640
3160
|
const tokenPeer = registry.tokenFor(sessionId)?.peer;
|
|
1641
3161
|
if (tokenPeer !== void 0 && peerId !== tokenPeer) {
|
|
@@ -1645,6 +3165,9 @@ function hubTools(hub, registry, options) {
|
|
|
1645
3165
|
throw new Error(`peer already registered by another connection: ${peerId}`);
|
|
1646
3166
|
}
|
|
1647
3167
|
const current = registry.peerFor(sessionId);
|
|
3168
|
+
if (hub.ownsMailbox(peerId) && current !== peerId && registry.attachedCount(peerId) > 0) {
|
|
3169
|
+
throw new Error(`peer id '${peerId}' is parked but still attached to another connection: it keeps its mailbox and is still addressable`);
|
|
3170
|
+
}
|
|
1648
3171
|
if (current !== void 0 && current !== peerId) {
|
|
1649
3172
|
if (registry.attachedCount(current) === 1) {
|
|
1650
3173
|
hub.renamePeer(current, peerId);
|
|
@@ -1654,8 +3177,8 @@ function hubTools(hub, registry, options) {
|
|
|
1654
3177
|
if (registry.attachedCount(current) === 0) hub.unregister(current);
|
|
1655
3178
|
}
|
|
1656
3179
|
}
|
|
1657
|
-
if (!hub.has(peerId)) hub.register(peerId);
|
|
1658
3180
|
registry.bindPeer(sessionId, peerId);
|
|
3181
|
+
if (!hub.has(peerId)) hub.register(peerId, void 0, { reclaim: true });
|
|
1659
3182
|
registry.clearSuppress(sessionId);
|
|
1660
3183
|
hub.touch(peerId);
|
|
1661
3184
|
if (alias !== void 0) hub.setAlias(peerId, alias);
|
|
@@ -1683,7 +3206,7 @@ function hubTools(hub, registry, options) {
|
|
|
1683
3206
|
if (caller === void 0) throw new Error("not registered \u2014 call bridge_register(peerId) first");
|
|
1684
3207
|
const target = String(args.peer);
|
|
1685
3208
|
requireManager(caller, `kicking '${target}'`, sessionId);
|
|
1686
|
-
if (!hub.has(target)) {
|
|
3209
|
+
if (!hub.has(target) && !hub.isParked(target)) {
|
|
1687
3210
|
return { ok: true, peerId: null, kicked: false };
|
|
1688
3211
|
}
|
|
1689
3212
|
hub.unregister(target);
|
|
@@ -1693,7 +3216,7 @@ function hubTools(hub, registry, options) {
|
|
|
1693
3216
|
},
|
|
1694
3217
|
{
|
|
1695
3218
|
name: "bridge_rename",
|
|
1696
|
-
description: "Rename on the hub, two layers: (1) `alias` sets a display name \u2014 cosmetic only, it shows up in bridge_peers / bridge_status and the desktop roster while routing, mailboxes, and history keep the immutable peer id; renaming yourself is open to everyone. (2) `peerId` truly re-keys another registered peer (manager rights required): mailbox, waiters, session bindings, and history attribution move atomically, so queued messages and acks stay continuous. Renaming ANOTHER peer (either layer) requires manager rights (hub managerPeers).",
|
|
3219
|
+
description: "Rename on the hub, two layers: (1) `alias` sets a display name \u2014 cosmetic only, it shows up in bridge_peers / bridge_status and the desktop roster while routing, mailboxes, and history keep the immutable peer id; renaming yourself is open to everyone. (2) `peerId` truly re-keys another registered peer (manager rights required): mailbox, waiters, in-flight manual leases, dead letters, session bindings, and history attribution move atomically, so queued messages and acks stay continuous and a lease you took under the old id is still yours to commit. Renaming ANOTHER peer (either layer) requires manager rights (hub managerPeers).",
|
|
1697
3220
|
inputSchema: schema({
|
|
1698
3221
|
alias: optStr("New display name (1-64 chars, spaces/CJK allowed; empty string clears back to no alias)."),
|
|
1699
3222
|
peerId: optStr("New routing id for `peer` \u2014 a true rename that moves all state (manager only). Target must be a registered peer."),
|
|
@@ -1705,17 +3228,26 @@ function hubTools(hub, registry, options) {
|
|
|
1705
3228
|
if (!hasAlias && !hasPeerId) {
|
|
1706
3229
|
throw new Error("nothing to rename: pass alias and/or peerId");
|
|
1707
3230
|
}
|
|
3231
|
+
if (hasPeerId && args.peer === void 0) {
|
|
3232
|
+
throw new Error("peerId requires peer \u2014 to change your own id, call bridge_register(newId)");
|
|
3233
|
+
}
|
|
3234
|
+
const tokenPeer = registry.tokenFor(sessionId)?.peer;
|
|
3235
|
+
if (hasPeerId && tokenPeer !== void 0) {
|
|
3236
|
+
requireManager(peer, `re-keying '${args.peer === void 0 ? peer : String(args.peer)}'`, sessionId);
|
|
3237
|
+
}
|
|
1708
3238
|
let target = args.peer === void 0 ? peer : String(args.peer);
|
|
1709
3239
|
if (target !== peer) requireManager(peer, `renaming '${target}'`, sessionId);
|
|
1710
3240
|
let previousId;
|
|
1711
3241
|
if (hasPeerId) {
|
|
1712
|
-
if (args.peer === void 0) {
|
|
1713
|
-
throw new Error("peerId requires peer \u2014 to change your own id, call bridge_register(newId)");
|
|
1714
|
-
}
|
|
1715
3242
|
const newId = String(args.peerId);
|
|
1716
3243
|
if (!PEER_ID_PATTERN.test(newId)) {
|
|
1717
3244
|
throw new Error(`invalid peerId: ${newId} (expected [A-Za-z0-9._:-]{1,64})`);
|
|
1718
3245
|
}
|
|
3246
|
+
const boundPeers = new Set(options.tokenPeers?.() ?? []);
|
|
3247
|
+
for (const identity of registry.tokenBindings.values()) boundPeers.add(identity.peer);
|
|
3248
|
+
if (boundPeers.has(newId) && newId !== tokenPeer) {
|
|
3249
|
+
throw new Error(`peerId '${newId}' is bound to an access token \u2014 a token's identity cannot be reassigned by a rename`);
|
|
3250
|
+
}
|
|
1719
3251
|
previousId = target;
|
|
1720
3252
|
hub.renamePeer(target, newId);
|
|
1721
3253
|
registry.rebindPeerId(target, newId);
|
|
@@ -1731,32 +3263,67 @@ function hubTools(hub, registry, options) {
|
|
|
1731
3263
|
},
|
|
1732
3264
|
{
|
|
1733
3265
|
name: "bridge_chat",
|
|
1734
|
-
description: 'Send a chat message to another agent on the hub. Use bridge_wait (long-poll) or bridge_poll to receive replies. `to` is the target peerId, a group id, or "all" to broadcast. Optional `threadId` groups multi-turn dialogs; optional `ref` marks a reply-to.',
|
|
3266
|
+
description: 'Send a chat message to another agent on the hub. Use bridge_wait (long-poll) or bridge_poll to receive replies. `to` is the target peerId, a group id, or "all" to broadcast. Optional `threadId` groups multi-turn dialogs; optional `ref` marks a reply-to and carries the chain depth in `hop`. Reply chains are counted, not enforced (50 hops for chat/ack, 5 for a task replying to a task): past the ceiling the message and its `ref` are delivered unchanged and only `hop` stops counting, so nothing is ever refused and no correlation is lost.',
|
|
1735
3267
|
inputSchema: schema(
|
|
1736
3268
|
{
|
|
1737
|
-
to: str('Target peerId, group id, or "all" to broadcast.'),
|
|
3269
|
+
to: str('Target peerId, group id, or "all" to broadcast. A group id fans out to its members, so you must be one of them.'),
|
|
1738
3270
|
message: str("The message text."),
|
|
1739
3271
|
threadId: optStr("Optional conversation / workflow thread id."),
|
|
1740
|
-
|
|
3272
|
+
priority: priorityField(),
|
|
3273
|
+
ref: optStr("Optional reply-to message id."),
|
|
3274
|
+
expiresAt: int("Optional absolute epoch-ms deadline. A message still queued (or about to be handed over) after it is dropped and counted as droppedExpired instead of delivered \u2014 a stale instruction is worse than none.")
|
|
1741
3275
|
},
|
|
1742
3276
|
["to", "message"]
|
|
1743
3277
|
),
|
|
1744
3278
|
handler: wrap(true, async (args, peer) => receipt(hub.send(peer, String(args.to), "chat", String(args.message), {
|
|
1745
3279
|
...args.threadId !== void 0 ? { threadId: String(args.threadId) } : {},
|
|
1746
|
-
...
|
|
3280
|
+
...optPriority(args.priority),
|
|
3281
|
+
...args.ref !== void 0 ? { ref: String(args.ref) } : {},
|
|
3282
|
+
...args.expiresAt !== void 0 ? { expiresAt: deadline(args.expiresAt) } : {}
|
|
1747
3283
|
})))
|
|
1748
3284
|
},
|
|
3285
|
+
{
|
|
3286
|
+
name: "bridge_notice",
|
|
3287
|
+
description: 'Send a system-flavoured notice to another agent (peer, group id, or "all"). Use it for things the recipient should see differently from chat: "your mailbox dropped 3 messages", "hub restarting", "that task was cancelled". `level` is info | warn | error (default info). The payload is structured ({message, level}) rather than plain text, and the message is a normal routed message \u2014 it queues for a parked peer like any other. It does NOT create a task ledger row.',
|
|
3288
|
+
inputSchema: schema(
|
|
3289
|
+
{
|
|
3290
|
+
to: str('Target peerId, group id, or "all" to broadcast. A group id fans out to its members, so you must be one of them.'),
|
|
3291
|
+
message: str("The notice text."),
|
|
3292
|
+
level: { type: "string", enum: ["info", "warn", "error"], description: "Severity (default info)." },
|
|
3293
|
+
threadId: optStr("Optional conversation / workflow thread id."),
|
|
3294
|
+
priority: priorityField()
|
|
3295
|
+
},
|
|
3296
|
+
["to", "message"]
|
|
3297
|
+
),
|
|
3298
|
+
handler: wrap(true, async (args, peer) => {
|
|
3299
|
+
const level = args.level === void 0 ? void 0 : String(args.level);
|
|
3300
|
+
if (level !== void 0 && level !== "info" && level !== "warn" && level !== "error") {
|
|
3301
|
+
throw new Error(`invalid level: ${level} (expected info | warn | error)`);
|
|
3302
|
+
}
|
|
3303
|
+
const payload = {
|
|
3304
|
+
message: String(args.message),
|
|
3305
|
+
...level !== void 0 ? { level } : {}
|
|
3306
|
+
};
|
|
3307
|
+
return receipt(hub.send(peer, String(args.to), "notice", encodeContent(payload), {
|
|
3308
|
+
...args.threadId !== void 0 ? { threadId: String(args.threadId) } : {},
|
|
3309
|
+
...optPriority(args.priority)
|
|
3310
|
+
}));
|
|
3311
|
+
})
|
|
3312
|
+
},
|
|
1749
3313
|
{
|
|
1750
3314
|
name: "bridge_task",
|
|
1751
|
-
description: 'Delegate a structured task to another agent (peer, group, or "all"). The assignee acks with accepted | working | rejected | done | failed (bridge_ack). Track with bridge_task_status(ref) / bridge_tasks; wait for the
|
|
3315
|
+
description: 'Delegate a structured task to another agent (peer, group, or "all"). The assignee acks with accepted | working | rejected | done | failed (bridge_ack). Track with bridge_task_status(ref) / bridge_tasks; wait for the reply with bridge_wait({ ref }). A `ref` wait can resolve on an intermediate beat (`working`) or on the result chat, so pass `terminalOnly: true` when you want the outcome. Optional timeoutMs marks the task `timeout` when the SLA expires without a terminal ack; any positive duration is honored, including multi-day deadlines (the hub re-arms its timer instead of overflowing it). Optional `ref` names the task this one answers \u2014 when the parent is itself a task the new one is a re-delegation, and `hop` counts that chain depth (saturating at 5; the task is always delivered).',
|
|
1752
3316
|
inputSchema: schema(
|
|
1753
3317
|
{
|
|
1754
|
-
to: str('Target peerId, group id, or "all" to broadcast.'),
|
|
3318
|
+
to: str('Target peerId, group id, or "all" to broadcast. A group id fans out to its members, so you must be one of them.'),
|
|
1755
3319
|
prompt: str("What the receiving agent should do."),
|
|
1756
3320
|
context: optStr("Optional background information for the task."),
|
|
1757
3321
|
deliverable: optStr("Optional expected deliverable description."),
|
|
1758
3322
|
timeoutMs: int("Optional soft SLA in ms from now (e.g. 30000). No upper bound \u2014 a deadline past ~24.8 days is honored as well."),
|
|
1759
|
-
threadId: optStr("Optional conversation / workflow thread id.")
|
|
3323
|
+
threadId: optStr("Optional conversation / workflow thread id."),
|
|
3324
|
+
priority: priorityField(),
|
|
3325
|
+
ref: optStr("Optional: the task message id this one answers (makes it a re-delegation when the parent is a task; that chain is capped at 5 hops)."),
|
|
3326
|
+
expiresAt: int("Optional absolute epoch-ms deadline for DELIVERY (distinct from timeoutMs, which is the assignee's SLA after it arrives). A task still undelivered at that moment is dropped and counted as droppedExpired.")
|
|
1760
3327
|
},
|
|
1761
3328
|
["to", "prompt"]
|
|
1762
3329
|
),
|
|
@@ -1765,8 +3332,9 @@ function hubTools(hub, registry, options) {
|
|
|
1765
3332
|
...args.context !== void 0 ? { context: String(args.context) } : {},
|
|
1766
3333
|
...args.deliverable !== void 0 ? { deliverable: String(args.deliverable) } : {},
|
|
1767
3334
|
...args.timeoutMs !== void 0 ? { timeoutMs: Number(args.timeoutMs) } : {},
|
|
1768
|
-
...args.threadId !== void 0 ? { threadId: String(args.threadId) } : {}
|
|
1769
|
-
|
|
3335
|
+
...args.threadId !== void 0 ? { threadId: String(args.threadId) } : {},
|
|
3336
|
+
...optPriority(args.priority)
|
|
3337
|
+
}, args.ref === void 0 ? void 0 : String(args.ref), args.expiresAt === void 0 ? void 0 : deadline(args.expiresAt))))
|
|
1770
3338
|
},
|
|
1771
3339
|
{
|
|
1772
3340
|
name: "bridge_ack",
|
|
@@ -1774,31 +3342,34 @@ function hubTools(hub, registry, options) {
|
|
|
1774
3342
|
inputSchema: schema(
|
|
1775
3343
|
{
|
|
1776
3344
|
ref: str("The id of the message being acknowledged."),
|
|
1777
|
-
status: { type: "string", enum: [
|
|
3345
|
+
status: { type: "string", enum: [...CLIENT_ACK_STATUSES], description: "acknowledgement status. `input-required` is an INTERRUPT: it asks the sender for information without ending the task \u2014 the sender answers with bridge_task_input and work resumes. To stop a task use bridge_task_cancel, not an ack." },
|
|
1778
3346
|
note: optStr("Optional explanation for the acknowledgement."),
|
|
3347
|
+
artifacts: { type: "array", description: "Optional output attached to this ack: [{name, mimeType?, text? | url?}]. A `done` ack with artifacts is how you hand back what you produced; they show up in bridge_task_status.", items: { type: "object" } },
|
|
1779
3348
|
progress: int("Optional 0-100 progress (meaningful with status=working).")
|
|
1780
3349
|
},
|
|
1781
3350
|
["ref", "status"]
|
|
1782
3351
|
),
|
|
1783
3352
|
handler: wrap(true, async (args, peer) => {
|
|
1784
3353
|
const status = String(args.status);
|
|
1785
|
-
const valid =
|
|
3354
|
+
const valid = CLIENT_ACK_STATUSES;
|
|
1786
3355
|
if (!valid.includes(status)) {
|
|
1787
3356
|
throw new Error(`invalid ack status: ${status} (expected ${valid.join(" | ")})`);
|
|
1788
3357
|
}
|
|
3358
|
+
const artifacts = parseArtifacts(args.artifacts);
|
|
1789
3359
|
return receipt(hub.sendAck(peer, String(args.ref), {
|
|
1790
3360
|
status,
|
|
1791
3361
|
...args.note !== void 0 ? { note: String(args.note) } : {},
|
|
3362
|
+
...artifacts !== void 0 ? { artifacts } : {},
|
|
1792
3363
|
...args.progress !== void 0 ? { progress: Number(args.progress) } : {}
|
|
1793
3364
|
}));
|
|
1794
3365
|
})
|
|
1795
3366
|
},
|
|
1796
3367
|
{
|
|
1797
3368
|
name: "bridge_tasks",
|
|
1798
|
-
description: "List delegated tasks involving you, newest first. role=sent = tasks you assigned; role=received = tasks assigned to you (or broadcast/group); status filters the ledger state (pending/accepted/working/rejected/done/failed/timeout). Each row carries the full ack timeline and per-assignee state.",
|
|
3369
|
+
description: "List delegated tasks involving you, newest first. role=sent = tasks you assigned; role=received = tasks assigned to you (or broadcast/group); status filters the ledger state (pending/accepted/working/input-required/rejected/done/failed/timeout/canceled). Each row carries the full ack timeline and per-assignee state.",
|
|
1799
3370
|
inputSchema: schema({
|
|
1800
3371
|
role: { type: "string", enum: ["sent", "received", "all"], description: "Which side of the task to list (default all)." },
|
|
1801
|
-
status: { type: "string", enum: [
|
|
3372
|
+
status: { type: "string", enum: [...ALL_TASK_STATUSES], description: "Only tasks whose current ledger status matches." },
|
|
1802
3373
|
peer: optStr('Manager only: "all" or another peerId for the admin board.'),
|
|
1803
3374
|
limit: int("How many tasks to return (default 50).")
|
|
1804
3375
|
}),
|
|
@@ -1808,14 +3379,15 @@ function hubTools(hub, registry, options) {
|
|
|
1808
3379
|
throw new Error(`invalid role: ${role} (expected sent | received | all)`);
|
|
1809
3380
|
}
|
|
1810
3381
|
const status = args.status === void 0 ? void 0 : String(args.status);
|
|
1811
|
-
const validStatus =
|
|
3382
|
+
const validStatus = ALL_TASK_STATUSES;
|
|
1812
3383
|
if (status !== void 0 && !validStatus.includes(status)) {
|
|
1813
3384
|
throw new Error(`invalid status: ${status} (expected ${validStatus.join(" | ")})`);
|
|
1814
3385
|
}
|
|
1815
3386
|
let target = peer;
|
|
1816
3387
|
if (args.peer !== void 0) {
|
|
1817
3388
|
target = String(args.peer);
|
|
1818
|
-
if (target
|
|
3389
|
+
if (target === BROADCAST) requireManager(peer, "listing the full task ledger", sessionId);
|
|
3390
|
+
else if (target !== peer) requireManager(peer, `listing tasks of '${target}'`, sessionId);
|
|
1819
3391
|
}
|
|
1820
3392
|
const tasks = hub.listTasks(target === "all" ? "all" : target, {
|
|
1821
3393
|
...role !== void 0 ? { role } : {},
|
|
@@ -1827,7 +3399,7 @@ function hubTools(hub, registry, options) {
|
|
|
1827
3399
|
},
|
|
1828
3400
|
{
|
|
1829
3401
|
name: "bridge_task_status",
|
|
1830
|
-
description: "Status of one delegated task: current ledger state (pending \u2192 accepted/working \u2192 done/failed/timeout, or rejected), the original prompt/context/deliverable, per-assignee state, and every ack event (who, status, note, progress, when). Use the task message id (the same id you pass as bridge_ack ref). Readable by the sender, by an assignee (a group task carries the GROUP id in `to`, so its assignees read it through their assignee row) and by a group member; everyone else needs manager rights.",
|
|
3402
|
+
description: "Status of one delegated task: current ledger state (pending \u2192 accepted/working \u2192 done/failed/timeout, or input-required/rejected/canceled), the original prompt/context/deliverable, per-assignee state, and every ack event (who, status, note, progress, when). Use the task message id (the same id you pass as bridge_ack ref). Readable by the sender, by an assignee (a group task carries the GROUP id in `to`, so its assignees read it through their assignee row) and by a group member; everyone else needs manager rights.",
|
|
1831
3403
|
inputSchema: schema({ ref: str("Task message id (the id returned by bridge_task, also used as ack ref).") }, ["ref"]),
|
|
1832
3404
|
handler: wrap(true, async (args, peer, sessionId) => {
|
|
1833
3405
|
const ref = String(args.ref);
|
|
@@ -1838,17 +3410,97 @@ function hubTools(hub, registry, options) {
|
|
|
1838
3410
|
if (task.from !== peer && task.to !== peer && task.to !== BROADCAST && !isAssignee && !isGroupMember) {
|
|
1839
3411
|
requireManager(peer, `reading task '${ref}'`, sessionId);
|
|
1840
3412
|
}
|
|
1841
|
-
return {
|
|
3413
|
+
return {
|
|
3414
|
+
task,
|
|
3415
|
+
// A2A naming aliases: the same task under the names an A2A client
|
|
3416
|
+
// already uses. `task.id` stays authoritative.
|
|
3417
|
+
taskId: task.id,
|
|
3418
|
+
...task.threadId !== void 0 ? { contextId: task.threadId } : {},
|
|
3419
|
+
a2aState: a2aState(task.status)
|
|
3420
|
+
};
|
|
1842
3421
|
})
|
|
1843
3422
|
},
|
|
3423
|
+
{
|
|
3424
|
+
name: "bridge_task_cancel",
|
|
3425
|
+
description: "Cancel a delegated task. Either side may do it: the sender stops work it no longer wants, an assignee reports it will not finish. The cancel is recorded on the ledger (`canceled`, terminal) and routed to the OTHER side so whoever did not press the button finds out. Cancelling an already-terminal task is an error, not a silent no-op.",
|
|
3426
|
+
inputSchema: schema(
|
|
3427
|
+
{
|
|
3428
|
+
ref: str("Task message id (the id returned by bridge_task)."),
|
|
3429
|
+
reason: optStr("Optional reason, delivered with the cancel and kept on the timeline.")
|
|
3430
|
+
},
|
|
3431
|
+
["ref"]
|
|
3432
|
+
),
|
|
3433
|
+
handler: wrap(true, async (args, peer) => receipt(hub.cancelTask(peer, String(args.ref), args.reason === void 0 ? void 0 : String(args.reason))))
|
|
3434
|
+
},
|
|
3435
|
+
{
|
|
3436
|
+
name: "bridge_task_input",
|
|
3437
|
+
description: "Answer a task whose assignee acked `input-required`: only the task's SENDER can answer it. The answer is delivered to the waiting assignee as an ack carrying the task id (so its `bridge_wait { ref }` picks it up) and the task resumes (`working`). An assignee does not call this \u2014 it resumes by acking `working` itself.",
|
|
3438
|
+
inputSchema: schema(
|
|
3439
|
+
{
|
|
3440
|
+
ref: str("Task message id."),
|
|
3441
|
+
input: str("The information the assignee asked for.")
|
|
3442
|
+
},
|
|
3443
|
+
["ref", "input"]
|
|
3444
|
+
),
|
|
3445
|
+
handler: wrap(true, async (args, peer) => receipt(hub.taskInput(peer, String(args.ref), String(args.input))))
|
|
3446
|
+
},
|
|
3447
|
+
{
|
|
3448
|
+
name: "bridge_announce",
|
|
3449
|
+
description: "Say what you can do, so other agents can find you: skills (id + name, optional tags), whether you accept tasks, how many at once, your input/output modes, and how you are executed when not polling. Replaces your previous card. `bridge_discover` only offers peers that set acceptsTasks \u2014 announcing a skill alone does not mean you want work.",
|
|
3450
|
+
inputSchema: schema(
|
|
3451
|
+
{
|
|
3452
|
+
card: {
|
|
3453
|
+
type: "object",
|
|
3454
|
+
description: 'Your card: {skills?: [{id, name, description?, tags?}], acceptsTasks?: boolean, concurrency?: number, inputModes?: string[], outputModes?: string[], runner?: "herdr"|"cli"|"http"|"none", endpoint?: string}.'
|
|
3455
|
+
}
|
|
3456
|
+
},
|
|
3457
|
+
["card"]
|
|
3458
|
+
),
|
|
3459
|
+
handler: wrap(true, async (args, peer) => {
|
|
3460
|
+
const profile = hub.announceCard(peer, parseCard(args.card));
|
|
3461
|
+
return { ok: true, peer, card: profile.card };
|
|
3462
|
+
})
|
|
3463
|
+
},
|
|
3464
|
+
{
|
|
3465
|
+
name: "bridge_discover",
|
|
3466
|
+
description: "Find a peer to hand work to. Returns the peers whose announced card matches, each with its current load (queued mailbox depth, live waiters, non-terminal tasks assigned to it). By default only peers that announced `acceptsTasks: true` are returned \u2014 pass acceptsTasks:false to list peers regardless. Peers that never announced a card are never returned.",
|
|
3467
|
+
inputSchema: schema(
|
|
3468
|
+
{
|
|
3469
|
+
skill: optStr("Only peers declaring this skill id."),
|
|
3470
|
+
tag: optStr("Only peers whose skills carry this tag."),
|
|
3471
|
+
acceptsTasks: { type: "boolean", description: "Require the peer to accept tasks (default true). Pass false to drop that requirement." },
|
|
3472
|
+
idleOnly: { type: "boolean", description: "Only peers with nothing queued, no waiter and no running task." }
|
|
3473
|
+
},
|
|
3474
|
+
[]
|
|
3475
|
+
),
|
|
3476
|
+
handler: wrap(true, async (args) => ({
|
|
3477
|
+
peers: hub.discover({
|
|
3478
|
+
...args.skill !== void 0 ? { skill: String(args.skill) } : {},
|
|
3479
|
+
...args.tag !== void 0 ? { tag: String(args.tag) } : {},
|
|
3480
|
+
...args.acceptsTasks !== void 0 ? { acceptsTasks: args.acceptsTasks === true } : {},
|
|
3481
|
+
...args.idleOnly !== void 0 ? { idleOnly: args.idleOnly === true } : {}
|
|
3482
|
+
})
|
|
3483
|
+
}))
|
|
3484
|
+
},
|
|
1844
3485
|
{
|
|
1845
3486
|
name: "bridge_wait",
|
|
1846
|
-
description:
|
|
3487
|
+
description: 'Wait (long-poll) for the next message addressed to you. Resolves immediately when one is queued; otherwise blocks until one arrives or the timeout fires. `from` narrows to one sender \u2014 but it never hides a notice sent by the hub itself (`from: "hub"`), so a sender waiting with `from: <assignee>` still hears "that delivery was dropped" and "the task is over". Hub notices (`from: "hub"`) are not filtered by `from`, by `ref`, or by `statuses` / `terminalOnly`, so a `ref` wait still hears that its delivery was dropped or that its assignee is gone (a `threadId` filter still narrows them, like any other message). `ref` waits for that task\'s reply: an ack OR the chat an assignee sends the result back in (a chat carrying a task id nobody but that task\'s sender or assignees sent is ignored). An ack is a STATUS BEAT, not a verdict \u2014 an assignee that acks `working` and then `done` resolves a plain `ref` wait on the FIRST one, so pass `terminalOnly: true` (or `statuses`) when you need the outcome rather than "it started"; combining the two is an intersection, and a pair that can never match is rejected rather than waited out. A wait that times out returns the task\'s current ledger status under `ref` when you passed a ref and are a party to it (only the sender and the assignees read a task\'s state that way). `threadId` narrows to one conversation thread. Loop this tool to hold a real-time conversation. With `ack: "manual"` the message is LEASED rather than consumed: it comes back (with `attempts` incremented) if you do not call bridge_commit in time, and is dead-lettered after too many hand-outs. Use it when losing a message would be worse than handling one twice.',
|
|
1847
3488
|
inputSchema: schema({
|
|
1848
|
-
from: optStr(
|
|
1849
|
-
ref: optStr("Only wait for the ack of
|
|
3489
|
+
from: optStr('Only wait for messages from this peerId. Hub notices (from "hub") are never filtered out.'),
|
|
3490
|
+
ref: optStr("Only wait for a reply carrying this ref: the ack of that task id (bridge_task id), or a chat answering it. A chat carrying a task id sent by a peer that is neither that task's sender nor one of its assignees is ignored."),
|
|
3491
|
+
statuses: {
|
|
3492
|
+
type: "array",
|
|
3493
|
+
items: { type: "string", enum: [...ALL_ACK_STATUSES] },
|
|
3494
|
+
description: "With `ref`: only resolve on an ack carrying one of these statuses. A chat reply has no status, so it never matches a status filter. An ack whose payload carries no valid status never matches either. Combined with `terminalOnly` by intersection: a list containing no terminal status is rejected instead of waiting out the timeout."
|
|
3495
|
+
},
|
|
3496
|
+
terminalOnly: {
|
|
3497
|
+
type: "boolean",
|
|
3498
|
+
description: "With `ref`: only resolve on a TERMINAL ack (rejected | done | failed | canceled) \u2014 skip the `accepted` / `working` / `input-required` beats. A chat reply is not a terminal ack and is skipped as well. Combined with `statuses` by intersection."
|
|
3499
|
+
},
|
|
1850
3500
|
threadId: optStr("Only wait for messages carrying this threadId."),
|
|
1851
|
-
timeoutMs: int(`Max wait in milliseconds (default ${DEFAULT_WAIT_MS}, ceiling is server waitTimeoutMs).`)
|
|
3501
|
+
timeoutMs: int(`Max wait in milliseconds (default ${DEFAULT_WAIT_MS}, ceiling is server waitTimeoutMs).`),
|
|
3502
|
+
maxMessages: int('Take up to this many already-queued messages in one call (default 1). With > 1 the result is {type:"messages", messages:[\u2026]} instead of {type:"message", message:{\u2026}} \u2014 the shape follows the request, not how many happened to be queued.'),
|
|
3503
|
+
ack: { type: "string", enum: ["auto", "manual"], description: '"auto" (default) consumes the message; "manual" leases it until bridge_commit (or bridge_nack).' }
|
|
1852
3504
|
}),
|
|
1853
3505
|
handler: wrap(true, async (args, peer) => presentWait(await hub.wait(
|
|
1854
3506
|
peer,
|
|
@@ -1856,14 +3508,41 @@ function hubTools(hub, registry, options) {
|
|
|
1856
3508
|
args.from === void 0 ? void 0 : String(args.from),
|
|
1857
3509
|
void 0,
|
|
1858
3510
|
args.ref === void 0 ? void 0 : String(args.ref),
|
|
1859
|
-
args.threadId === void 0 ? void 0 : String(args.threadId)
|
|
3511
|
+
args.threadId === void 0 ? void 0 : String(args.threadId),
|
|
3512
|
+
args.ack === "manual",
|
|
3513
|
+
args.maxMessages === void 0 ? 1 : Math.max(1, Number(args.maxMessages)),
|
|
3514
|
+
ackStatuses(args.statuses, args.terminalOnly === true),
|
|
3515
|
+
args.terminalOnly === true
|
|
1860
3516
|
)))
|
|
1861
3517
|
},
|
|
1862
3518
|
{
|
|
1863
3519
|
name: "bridge_poll",
|
|
1864
|
-
description:
|
|
1865
|
-
inputSchema: schema({
|
|
1866
|
-
|
|
3520
|
+
description: 'Non-blocking: drain every message currently queued for you. Empty list when nothing is waiting. `from` narrows to one sender (a hub notice with `from: "hub"` is always included). `ack: "manual"` leases what it drains (see bridge_wait) instead of consuming it.',
|
|
3521
|
+
inputSchema: schema({
|
|
3522
|
+
from: optStr('Only drain messages from this peerId. Hub notices (from "hub") are never filtered out.'),
|
|
3523
|
+
ack: { type: "string", enum: ["auto", "manual"], description: '"auto" (default) consumes; "manual" leases until bridge_commit.' }
|
|
3524
|
+
}),
|
|
3525
|
+
handler: wrap(true, async (args, peer) => ({
|
|
3526
|
+
messages: hub.poll(peer, args.from === void 0 ? void 0 : String(args.from), { manual: args.ack === "manual" }).map(present)
|
|
3527
|
+
}))
|
|
3528
|
+
},
|
|
3529
|
+
{
|
|
3530
|
+
name: "bridge_commit",
|
|
3531
|
+
description: 'Acknowledge messages you received under a manual lease (bridge_wait / bridge_poll with ack: "manual"). Until you commit, the hub keeps them in flight and hands them out again once the lease expires \u2014 committing is what makes handling them final. Returns how many leases were released.',
|
|
3532
|
+
inputSchema: schema(
|
|
3533
|
+
{ ids: { type: "array", items: { type: "string" }, description: "Message ids you received and have finished handling. At most 1000 per call." } },
|
|
3534
|
+
["ids"]
|
|
3535
|
+
),
|
|
3536
|
+
handler: wrap(true, async (args, peer) => ({ committed: hub.commit(peer, idList(args.ids, "bridge_commit")) }))
|
|
3537
|
+
},
|
|
3538
|
+
{
|
|
3539
|
+
name: "bridge_nack",
|
|
3540
|
+
description: "Give leased messages back NOW instead of waiting for the lease to expire \u2014 use it when handling failed. They go back into your mailbox in normal delivery order (another session of the same peer can retry), their attempt count is kept, and a message that keeps failing ends up dead-lettered instead of looping. It also revives a dead-lettered message (resetting its attempts). Requeued mail competes for a slot like arriving mail, so if the mailbox is already full what does not fit stays dead-lettered (revive it again later). Returns how many were requeued.",
|
|
3541
|
+
inputSchema: schema(
|
|
3542
|
+
{ ids: { type: "array", items: { type: "string" }, description: "Message ids to give back. At most 1000 per call." } },
|
|
3543
|
+
["ids"]
|
|
3544
|
+
),
|
|
3545
|
+
handler: wrap(true, async (args, peer) => ({ requeued: hub.nack(peer, idList(args.ids, "bridge_nack")) }))
|
|
1867
3546
|
},
|
|
1868
3547
|
{
|
|
1869
3548
|
name: "bridge_status",
|
|
@@ -1871,6 +3550,21 @@ function hubTools(hub, registry, options) {
|
|
|
1871
3550
|
inputSchema: schema({}),
|
|
1872
3551
|
handler: wrap(true, async () => hub.status(livePeersFor(registry)))
|
|
1873
3552
|
},
|
|
3553
|
+
{
|
|
3554
|
+
name: "bridge_metrics",
|
|
3555
|
+
description: "Operational counters, per peer and global. Per peer: sent / received / acked (traffic counters that survive a drained queue), queued, inFlight, deadLettered, droppedOverflow, droppedExpired, connected. Global: messagesTotal (the history seq \u2014 a true count, not a rolling window), peers / connectedPeers / parkedPeers, waitersNow, queuedTotal, tasksByStatus, and the drop / lease totals. Every number is derived from live state or from a counter the hub already keeps; nothing is estimated. Counters are per run and reset on restart.",
|
|
3556
|
+
inputSchema: schema({}),
|
|
3557
|
+
handler: wrap(true, async () => hub.metrics())
|
|
3558
|
+
},
|
|
3559
|
+
{
|
|
3560
|
+
name: "bridge_events",
|
|
3561
|
+
description: "Read the hub's own operational event stream, oldest first. These are what the HUB did, not what peers said: `peer_joined` / `peer_left` / `peer_parked` / `mailbox_dropped` / `task_transition` / `runner_started` / `runner_finished`. Each event has a monotonic `seq` (never resets in a run), a `ts`, and a kind-specific `detail`. Pass `since` (exclusive) with the `lastSeq` of your previous call to poll for new events only. `truncated: true` means the window you asked for is older than the ring still holds, so you missed entries \u2014 re-read from the start rather than assuming you saw everything. Events are per-run and in-memory; a restart starts a new sequence.",
|
|
3562
|
+
inputSchema: schema({
|
|
3563
|
+
since: { type: "number", description: "Return only events with a seq greater than this (exclusive)." },
|
|
3564
|
+
limit: { type: "number", description: "Maximum events to return, newest kept (default 100, max 500)." }
|
|
3565
|
+
}),
|
|
3566
|
+
handler: wrap(true, async (args) => hub.events(args))
|
|
3567
|
+
},
|
|
1874
3568
|
{
|
|
1875
3569
|
name: "bridge_peers",
|
|
1876
3570
|
description: "List registered peers with their display identity and connection state: id (immutable routing name), optional alias (display name), client name/version reported at connect, whether connected (recent activity or a live SSE channel), and lastSeenMs.",
|
|
@@ -1883,22 +3577,30 @@ function hubTools(hub, registry, options) {
|
|
|
1883
3577
|
inputSchema: schema({
|
|
1884
3578
|
peer: optStr('PeerId whose conversation to inspect; "all" = every peer; default: yourself. Other peers / "all" require manager rights.'),
|
|
1885
3579
|
channel: optStr("Read a group channel history instead of a peer conversation (you must be a member, or a manager)."),
|
|
1886
|
-
limit: int("How many messages to return (default 20).")
|
|
3580
|
+
limit: int("How many messages to return (default 20)."),
|
|
3581
|
+
since: int('Resume cursor: return only messages with seq greater than this. Read bridge_status.lastSeq to start from "now"; omit to include history recorded before cursors existed.')
|
|
1887
3582
|
}),
|
|
1888
3583
|
handler: wrap(true, async (args, peer, sessionId) => {
|
|
1889
3584
|
const limit = Math.min(args.limit === void 0 ? 20 : Number(args.limit), 1e3);
|
|
3585
|
+
const sinceRaw = args.since === void 0 ? void 0 : Number(args.since);
|
|
3586
|
+
if (sinceRaw !== void 0 && (!Number.isFinite(sinceRaw) || sinceRaw < 0)) {
|
|
3587
|
+
throw new Error(`invalid since: ${String(args.since)} (expected a non-negative sequence number)`);
|
|
3588
|
+
}
|
|
3589
|
+
const since = sinceRaw;
|
|
1890
3590
|
const target = args.peer === void 0 ? peer : String(args.peer);
|
|
1891
|
-
if (target
|
|
1892
|
-
requireManager(peer,
|
|
3591
|
+
if (target === BROADCAST) {
|
|
3592
|
+
requireManager(peer, "reading the full history", sessionId);
|
|
3593
|
+
} else if (target !== peer) {
|
|
3594
|
+
requireManager(peer, `reading peer '${target}' history`, sessionId);
|
|
1893
3595
|
}
|
|
1894
3596
|
if (args.channel !== void 0) {
|
|
1895
3597
|
const groupId = String(args.channel);
|
|
1896
3598
|
const group = hub.groupOf(groupId);
|
|
1897
3599
|
if (group === void 0) throw new Error(`unknown group: ${groupId}`);
|
|
1898
3600
|
if (!group.members.includes(peer)) requireManager(peer, `reading group '${groupId}' history`, sessionId);
|
|
1899
|
-
return { messages: hub.historyChannel(groupId, limit).map(present) };
|
|
3601
|
+
return { messages: hub.historyChannel(groupId, limit, since).map(present) };
|
|
1900
3602
|
}
|
|
1901
|
-
const messages = target === BROADCAST ? hub.historyAll(limit) : hub.history(target, limit);
|
|
3603
|
+
const messages = target === BROADCAST ? hub.historyAll(limit, since) : hub.history(target, limit, since);
|
|
1902
3604
|
return { messages: messages.map(present) };
|
|
1903
3605
|
})
|
|
1904
3606
|
},
|
|
@@ -2174,11 +3876,11 @@ function hubTools(hub, registry, options) {
|
|
|
2174
3876
|
return read === null ? { matched: null } : { matched: read };
|
|
2175
3877
|
})
|
|
2176
3878
|
}
|
|
2177
|
-
];
|
|
3879
|
+
].map((tool) => ({ ...tool, handler: requireArgs(tool, tool.handler) }));
|
|
2178
3880
|
}
|
|
2179
3881
|
|
|
2180
3882
|
// src/mcp-server.ts
|
|
2181
|
-
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
3883
|
+
import { randomUUID as randomUUID2, timingSafeEqual } from "node:crypto";
|
|
2182
3884
|
import { readFileSync as readFileSync2 } from "node:fs";
|
|
2183
3885
|
var ADMIN_PATH = "/admin";
|
|
2184
3886
|
var ADMIN_API_PATH = "/admin/api";
|
|
@@ -2193,6 +3895,7 @@ var SUPPORTED_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
|
|
2193
3895
|
var LATEST_VERSION = SUPPORTED_VERSIONS[0];
|
|
2194
3896
|
var MAX_BODY_BYTES = 1048576;
|
|
2195
3897
|
var HEARTBEAT_MS = 2e4;
|
|
3898
|
+
var DEFAULT_SESSION_TTL_MS = 30 * 6e4;
|
|
2196
3899
|
var SessionRegistry = class {
|
|
2197
3900
|
sessions = /* @__PURE__ */ new Set();
|
|
2198
3901
|
/** sessionId → peerId claimed via `bridge_register`. */
|
|
@@ -2205,8 +3908,17 @@ var SessionRegistry = class {
|
|
|
2205
3908
|
ensureSession(sessionId) {
|
|
2206
3909
|
const id = sessionId ?? randomUUID2();
|
|
2207
3910
|
this.sessions.add(id);
|
|
3911
|
+
this.lastUsedAt.set(id, Date.now());
|
|
2208
3912
|
return id;
|
|
2209
3913
|
}
|
|
3914
|
+
/** Has this session id ever been minted here and not terminated since?
|
|
3915
|
+
* A request presenting an id the registry does not know must be answered 404
|
|
3916
|
+
* (spec MUST) so the client starts a new session, instead of being adopted
|
|
3917
|
+
* silently — which is how a client kept talking to a hub that had restarted
|
|
3918
|
+
* and already forgotten it. */
|
|
3919
|
+
hasSession(sessionId) {
|
|
3920
|
+
return this.sessions.has(sessionId);
|
|
3921
|
+
}
|
|
2210
3922
|
/** Peer bound to a session, if any. */
|
|
2211
3923
|
peerFor(sessionId) {
|
|
2212
3924
|
if (sessionId === void 0) return void 0;
|
|
@@ -2262,6 +3974,47 @@ var SessionRegistry = class {
|
|
|
2262
3974
|
isSuppressed(sessionId) {
|
|
2263
3975
|
return sessionId !== void 0 && this.suppressedAuto.has(sessionId);
|
|
2264
3976
|
}
|
|
3977
|
+
/** Session → the last time a request presented it.
|
|
3978
|
+
*
|
|
3979
|
+
* The registry is the only thing that knows a session exists, so it is also the
|
|
3980
|
+
* only thing that can decide one is finished. Without this the maps below only
|
|
3981
|
+
* ever grew, `hasSession` was true forever, and "this session is over" was not
|
|
3982
|
+
* expressible — so the 404 path could never fire for a session the hub had
|
|
3983
|
+
* genuinely finished with. */
|
|
3984
|
+
lastUsedAt = /* @__PURE__ */ new Map();
|
|
3985
|
+
/** Record that `sessionId` was just used (a request carried its id). */
|
|
3986
|
+
touch(sessionId) {
|
|
3987
|
+
if (sessionId !== void 0 && this.sessions.has(sessionId)) this.lastUsedAt.set(sessionId, Date.now());
|
|
3988
|
+
}
|
|
3989
|
+
/**
|
|
3990
|
+
* Forget sessions that are finished: no live SSE stream, and unused for `ttlMs`.
|
|
3991
|
+
* Returns the ids removed. `ttlMs <= 0` disables reaping.
|
|
3992
|
+
*
|
|
3993
|
+
* Safe because a client that gets 404 is REQUIRED by the spec to send a fresh
|
|
3994
|
+
* `initialize`, and the hub auto-registers it under the same peer id — it comes
|
|
3995
|
+
* back with its mailbox intact. A live SSE stream pins a session regardless of
|
|
3996
|
+
* age: that is the one signal that means "still connected", and it wins.
|
|
3997
|
+
*/
|
|
3998
|
+
sweep(now, ttlMs) {
|
|
3999
|
+
if (ttlMs <= 0) return [];
|
|
4000
|
+
const removed = [];
|
|
4001
|
+
for (const sessionId of [...this.sessions]) {
|
|
4002
|
+
if (this.liveStreams.has(sessionId)) continue;
|
|
4003
|
+
const last = this.lastUsedAt.get(sessionId) ?? now;
|
|
4004
|
+
if (now - last <= ttlMs) continue;
|
|
4005
|
+
this.sessions.delete(sessionId);
|
|
4006
|
+
this.lastUsedAt.delete(sessionId);
|
|
4007
|
+
this.peerBindings.delete(sessionId);
|
|
4008
|
+
this.clientNames.delete(sessionId);
|
|
4009
|
+
this.clientVersions.delete(sessionId);
|
|
4010
|
+
this.sessionIps.delete(sessionId);
|
|
4011
|
+
this.tokenBindings.delete(sessionId);
|
|
4012
|
+
this.managerSessions.delete(sessionId);
|
|
4013
|
+
this.suppressedAuto.delete(sessionId);
|
|
4014
|
+
removed.push(sessionId);
|
|
4015
|
+
}
|
|
4016
|
+
return removed;
|
|
4017
|
+
}
|
|
2265
4018
|
/** Session → client IP (remote mode: the admin roster shows where a peer
|
|
2266
4019
|
* connects from, so the operator can tell Zhang San's kimi-code from Li Si's). */
|
|
2267
4020
|
sessionIps = /* @__PURE__ */ new Map();
|
|
@@ -2280,6 +4033,19 @@ var SessionRegistry = class {
|
|
|
2280
4033
|
if (sessionId === void 0) return void 0;
|
|
2281
4034
|
return this.tokenBindings.get(sessionId);
|
|
2282
4035
|
}
|
|
4036
|
+
/** Sessions that presented the loopback manager token (`--manager-token`).
|
|
4037
|
+
* Distinct from a token-table identity: loopback mode has no token table, so
|
|
4038
|
+
* the manager secret is the only thing separating "the operator's GUI" from
|
|
4039
|
+
* "any other local MCP client". */
|
|
4040
|
+
managerSessions = /* @__PURE__ */ new Set();
|
|
4041
|
+
/** Remember that this session proved it holds the manager token. */
|
|
4042
|
+
markManagerSession(sessionId) {
|
|
4043
|
+
this.managerSessions.add(sessionId);
|
|
4044
|
+
}
|
|
4045
|
+
/** Did this session present the manager token? */
|
|
4046
|
+
isManagerSession(sessionId) {
|
|
4047
|
+
return sessionId !== void 0 && this.managerSessions.has(sessionId);
|
|
4048
|
+
}
|
|
2283
4049
|
/** Mark a session's SSE stream open (server→client channel alive). */
|
|
2284
4050
|
markSseOpen(sessionId) {
|
|
2285
4051
|
this.liveStreams.add(sessionId);
|
|
@@ -2338,7 +4104,7 @@ var SessionRegistry = class {
|
|
|
2338
4104
|
var McpStreamableHttpServer = class {
|
|
2339
4105
|
constructor(tools, info, registry, log = () => {
|
|
2340
4106
|
}, onInitialize = () => {
|
|
2341
|
-
}, authenticate, adminApi, heartbeatMs) {
|
|
4107
|
+
}, authenticate, adminApi, heartbeatMs, originPolicy, managerToken, sessionTtlMs = DEFAULT_SESSION_TTL_MS) {
|
|
2342
4108
|
this.tools = tools;
|
|
2343
4109
|
this.info = info;
|
|
2344
4110
|
this.registry = registry;
|
|
@@ -2347,29 +4113,54 @@ var McpStreamableHttpServer = class {
|
|
|
2347
4113
|
this.authenticate = authenticate;
|
|
2348
4114
|
this.adminApi = adminApi;
|
|
2349
4115
|
this.heartbeatMs = heartbeatMs;
|
|
4116
|
+
this.originPolicy = originPolicy;
|
|
4117
|
+
this.managerToken = managerToken;
|
|
4118
|
+
this.sessionTtlMs = sessionTtlMs;
|
|
2350
4119
|
}
|
|
2351
4120
|
sseStreams = /* @__PURE__ */ new Map();
|
|
2352
4121
|
heartbeatTimer;
|
|
4122
|
+
sessionSweepTimer;
|
|
4123
|
+
/** Does this request carry the loopback manager token? */
|
|
4124
|
+
presentedManagerToken(req) {
|
|
4125
|
+
if (this.managerToken === void 0) return false;
|
|
4126
|
+
const header = headerValue(req.headers.authorization);
|
|
4127
|
+
if (header === void 0) return false;
|
|
4128
|
+
const match = /^Bearer\s+(.+)$/i.exec(header);
|
|
4129
|
+
return match !== null && secretEquals(match[1].trim(), this.managerToken);
|
|
4130
|
+
}
|
|
2353
4131
|
/** Attach request handling for `path` (e.g. `/mcp`) to an http server. */
|
|
2354
4132
|
attach(server, path2) {
|
|
2355
4133
|
this.heartbeatTimer = setInterval(() => {
|
|
2356
4134
|
if (this.sseStreams.size === 0) return;
|
|
2357
|
-
this.notifyAll(
|
|
4135
|
+
this.notifyAll(SSE_METHOD, {
|
|
2358
4136
|
level: "debug",
|
|
2359
4137
|
logger: "bridge",
|
|
2360
4138
|
data: { event: "heartbeat", ts: Date.now() }
|
|
2361
4139
|
});
|
|
2362
4140
|
}, this.heartbeatMs ?? HEARTBEAT_MS);
|
|
2363
4141
|
this.heartbeatTimer.unref?.();
|
|
4142
|
+
if (this.sessionTtlMs > 0) {
|
|
4143
|
+
const interval = Math.min(6e4, Math.max(1e3, this.sessionTtlMs / 4));
|
|
4144
|
+
this.sessionSweepTimer = setInterval(() => {
|
|
4145
|
+
const removed = this.registry.sweep(Date.now(), this.sessionTtlMs);
|
|
4146
|
+
if (removed.length > 0) this.log(`sessions reaped: ${removed.length}`);
|
|
4147
|
+
}, interval);
|
|
4148
|
+
this.sessionSweepTimer.unref?.();
|
|
4149
|
+
}
|
|
2364
4150
|
server.on("request", (req, res) => {
|
|
2365
4151
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
4152
|
+
if (!this.originAllowed(req)) {
|
|
4153
|
+
res.writeHead(403, { ...this.corsFor(req), "Content-Type": "application/json; charset=utf-8", "Mcp-Protocol-Version": messageProtocolVersion(req) });
|
|
4154
|
+
res.end(JSON.stringify({ error: `origin not allowed: ${headerValue(req.headers.origin) ?? ""}` }));
|
|
4155
|
+
return;
|
|
4156
|
+
}
|
|
2366
4157
|
if (url.pathname === ADMIN_PATH && req.method === "GET") {
|
|
2367
4158
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-cache" });
|
|
2368
4159
|
res.end(adminPage());
|
|
2369
4160
|
return;
|
|
2370
4161
|
}
|
|
2371
4162
|
if (url.pathname === "/healthz") {
|
|
2372
|
-
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", ...
|
|
4163
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", ...this.corsFor(req) });
|
|
2373
4164
|
res.end(JSON.stringify({ ok: true, ts: Date.now() }));
|
|
2374
4165
|
return;
|
|
2375
4166
|
}
|
|
@@ -2390,15 +4181,16 @@ var McpStreamableHttpServer = class {
|
|
|
2390
4181
|
return;
|
|
2391
4182
|
}
|
|
2392
4183
|
if (req.method === "OPTIONS") {
|
|
2393
|
-
res.writeHead(204,
|
|
4184
|
+
res.writeHead(204, this.corsFor(req)).end();
|
|
2394
4185
|
return;
|
|
2395
4186
|
}
|
|
2396
|
-
res.writeHead(405,
|
|
4187
|
+
res.writeHead(405, { ...this.corsFor(req), "Mcp-Protocol-Version": messageProtocolVersion(req) }).end();
|
|
2397
4188
|
});
|
|
2398
4189
|
}
|
|
2399
4190
|
/** Close all open SSE streams (called on server shutdown). */
|
|
2400
4191
|
close() {
|
|
2401
4192
|
if (this.heartbeatTimer !== void 0) clearInterval(this.heartbeatTimer);
|
|
4193
|
+
if (this.sessionSweepTimer !== void 0) clearInterval(this.sessionSweepTimer);
|
|
2402
4194
|
for (const stream of this.sseStreams.values()) stream.end();
|
|
2403
4195
|
this.sseStreams.clear();
|
|
2404
4196
|
}
|
|
@@ -2426,33 +4218,107 @@ data: ${JSON.stringify({ jsonrpc: "2.0", method, params })}
|
|
|
2426
4218
|
}
|
|
2427
4219
|
}
|
|
2428
4220
|
}
|
|
4221
|
+
/**
|
|
4222
|
+
* Cross-origin gate. A request is allowed when:
|
|
4223
|
+
* - it carries no `Origin` (curl, MCP clients, the desktop app — never browsers), or
|
|
4224
|
+
* - the origin is explicitly listed (`--allow-origins`, or 'all'), or
|
|
4225
|
+
* - the origin is a loopback hostname (the bundled admin page, local tooling), or
|
|
4226
|
+
* - it presents a valid bearer token AND its origin host matches the `Host`
|
|
4227
|
+
* header (the admin page behind a TLS reverse proxy, where the hub cannot
|
|
4228
|
+
* know its own public origin).
|
|
4229
|
+
*
|
|
4230
|
+
* The last clause is deliberately credential-gated, not identity-gated: with
|
|
4231
|
+
* `--allow-join` the transport mints an anonymous identity for a request that
|
|
4232
|
+
* carries nothing at all, so testing only `authenticate(req) !== undefined`
|
|
4233
|
+
* would re-open this branch to exactly the rebinding page it exists to stop.
|
|
4234
|
+
* A real `Authorization` header is required as well.
|
|
4235
|
+
*/
|
|
4236
|
+
originAllowed(req) {
|
|
4237
|
+
const origin = headerValue(req.headers.origin);
|
|
4238
|
+
if (origin === void 0) return true;
|
|
4239
|
+
const policy = this.originPolicy;
|
|
4240
|
+
if (policy?.allow === "all") return true;
|
|
4241
|
+
if (policy?.allow?.has(origin) === true) return true;
|
|
4242
|
+
if (origin.includes(",") || /\s/.test(origin)) return false;
|
|
4243
|
+
const originHost = originHostname(origin);
|
|
4244
|
+
if (originHost === void 0) return false;
|
|
4245
|
+
if (isLoopbackHost(originHost)) return true;
|
|
4246
|
+
const identity = this.authenticate?.(req);
|
|
4247
|
+
if (identity === void 0 || identity.anonymous === true) return false;
|
|
4248
|
+
const host = headerValue(req.headers.host);
|
|
4249
|
+
return host !== void 0 && hostHeaderName(host) === originHost;
|
|
4250
|
+
}
|
|
4251
|
+
/** CORS headers for one request: echoes the origin only when it is allowed. */
|
|
4252
|
+
corsFor(req) {
|
|
4253
|
+
if (req === void 0) return corsHeaders();
|
|
4254
|
+
const origin = headerValue(req.headers.origin);
|
|
4255
|
+
return corsHeaders(origin !== void 0 && this.originAllowed(req) ? origin : void 0);
|
|
4256
|
+
}
|
|
2429
4257
|
handleGet(req, res) {
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
4258
|
+
let streamIdentity;
|
|
4259
|
+
if (this.authenticate !== void 0) {
|
|
4260
|
+
streamIdentity = this.authenticate(req);
|
|
4261
|
+
if (streamIdentity === void 0) {
|
|
4262
|
+
res.writeHead(401, { ...this.corsFor(req), "Content-Type": "application/json; charset=utf-8", "Mcp-Protocol-Version": messageProtocolVersion(req) });
|
|
4263
|
+
res.end(JSON.stringify({ error: "unauthorized: missing or invalid bearer token" }));
|
|
4264
|
+
return;
|
|
4265
|
+
}
|
|
4266
|
+
const existing = this.registry.sessionIdFor(req);
|
|
4267
|
+
const bound = existing === void 0 ? void 0 : this.registry.tokenFor(existing);
|
|
4268
|
+
const bothAnonymous = bound?.anonymous === true && streamIdentity.anonymous === true;
|
|
4269
|
+
if (bound !== void 0 && !bothAnonymous && (bound.peer !== streamIdentity.peer || bound.role !== streamIdentity.role)) {
|
|
4270
|
+
this.unauthorized(req, res, null, "token does not match this session");
|
|
4271
|
+
return;
|
|
4272
|
+
}
|
|
4273
|
+
}
|
|
4274
|
+
if (this.protocolVersionRejected(req, res)) return;
|
|
4275
|
+
const streamSession = this.registry.sessionIdFor(req);
|
|
4276
|
+
if (streamSession !== void 0 && !this.registry.hasSession(streamSession)) {
|
|
4277
|
+
this.jsonRpcError(req, res, null, -32001, "session not found \u2014 send a new initialize request", void 0, 404);
|
|
2433
4278
|
return;
|
|
2434
4279
|
}
|
|
2435
|
-
|
|
2436
|
-
const
|
|
2437
|
-
if (
|
|
4280
|
+
this.registry.touch(streamSession);
|
|
4281
|
+
const sessionId = this.registry.ensureSession(streamSession);
|
|
4282
|
+
if (this.presentedManagerToken(req)) this.registry.markManagerSession(sessionId);
|
|
4283
|
+
if (streamIdentity !== void 0) this.registry.bindToken(sessionId, streamIdentity);
|
|
2438
4284
|
res.writeHead(200, {
|
|
2439
|
-
...
|
|
4285
|
+
...this.corsFor(req),
|
|
2440
4286
|
"Content-Type": "text/event-stream; charset=utf-8",
|
|
2441
4287
|
"Cache-Control": "no-cache",
|
|
2442
4288
|
Connection: "keep-alive",
|
|
4289
|
+
// nginx (and anything else speaking X-Accel) buffers proxied responses by
|
|
4290
|
+
// default, which breaks SSE completely: events sit in the proxy until its
|
|
4291
|
+
// buffer fills or the stream ends, so a client never sees a push. This header
|
|
4292
|
+
// is the in-band way to turn that off — it needs no proxy configuration, and
|
|
4293
|
+
// a proxy that ignores it is unaffected.
|
|
4294
|
+
"X-Accel-Buffering": "no",
|
|
4295
|
+
// Same header the POST path sets: the client should see the version the
|
|
4296
|
+
// server is speaking on every 200, not only on JSON responses.
|
|
4297
|
+
"Mcp-Protocol-Version": messageProtocolVersion(req),
|
|
2443
4298
|
...req.headers["mcp-session-id"] ? {} : { "Mcp-Session-Id": sessionId }
|
|
2444
4299
|
});
|
|
2445
4300
|
res.write(": connected\n\n");
|
|
2446
4301
|
this.sseStreams.set(sessionId, res);
|
|
2447
4302
|
this.registry.markSseOpen(sessionId);
|
|
2448
4303
|
req.on("close", () => {
|
|
2449
|
-
this.sseStreams.delete(sessionId);
|
|
2450
|
-
this.registry.markSseClosed(sessionId);
|
|
4304
|
+
if (this.sseStreams.get(sessionId) === res) this.sseStreams.delete(sessionId);
|
|
4305
|
+
if (!this.sseStreams.has(sessionId)) this.registry.markSseClosed(sessionId);
|
|
2451
4306
|
});
|
|
2452
4307
|
}
|
|
2453
4308
|
/** Reject a request without a valid token (remote auth mode). */
|
|
2454
|
-
unauthorized(res, id, why) {
|
|
2455
|
-
res.writeHead(401, {
|
|
4309
|
+
unauthorized(req, res, id, why) {
|
|
4310
|
+
res.writeHead(401, {
|
|
4311
|
+
...this.corsFor(req),
|
|
4312
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
4313
|
+
// MCP authorization spec: a 401 MUST carry WWW-Authenticate. The hub does not
|
|
4314
|
+
// implement OAuth (authorization is OPTIONAL in MCP), so there is no
|
|
4315
|
+
// resource_metadata to advertise — the bare scheme is still required.
|
|
4316
|
+
"WWW-Authenticate": "Bearer",
|
|
4317
|
+
// Every response names the protocol version the server is speaking, errors
|
|
4318
|
+
// included: a client that only sees 401s still needs to know what it is
|
|
4319
|
+
// talking to before it can decide whether to retry.
|
|
4320
|
+
"Mcp-Protocol-Version": messageProtocolVersion(req)
|
|
4321
|
+
});
|
|
2456
4322
|
res.end(JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32001, message: `unauthorized: ${why}` } }));
|
|
2457
4323
|
}
|
|
2458
4324
|
/** Management API for the bundled admin page: issue/revoke tokens and list
|
|
@@ -2460,7 +4326,7 @@ data: ${JSON.stringify({ jsonrpc: "2.0", method, params })}
|
|
|
2460
4326
|
* and must resolve to a MANAGER role — an agent token gets 403. */
|
|
2461
4327
|
async handleAdminApi(req, res, url) {
|
|
2462
4328
|
const respond = (status, body) => {
|
|
2463
|
-
res.writeHead(status, { ...
|
|
4329
|
+
res.writeHead(status, { ...this.corsFor(req), "Content-Type": "application/json; charset=utf-8" });
|
|
2464
4330
|
res.end(JSON.stringify(body));
|
|
2465
4331
|
};
|
|
2466
4332
|
const identity = this.authenticate?.(req);
|
|
@@ -2509,49 +4375,57 @@ data: ${JSON.stringify({ jsonrpc: "2.0", method, params })}
|
|
|
2509
4375
|
if (this.authenticate !== void 0) {
|
|
2510
4376
|
authIdentity = this.authenticate(req);
|
|
2511
4377
|
if (authIdentity === void 0) {
|
|
2512
|
-
this.unauthorized(res, null, "missing or invalid bearer token");
|
|
4378
|
+
this.unauthorized(req, res, null, "missing or invalid bearer token");
|
|
2513
4379
|
return;
|
|
2514
4380
|
}
|
|
2515
4381
|
const existingSession = this.registry.sessionIdFor(req);
|
|
2516
4382
|
const bound = existingSession === void 0 ? void 0 : this.registry.tokenFor(existingSession);
|
|
2517
4383
|
const bothAnonymous = bound?.anonymous === true && authIdentity.anonymous === true;
|
|
2518
4384
|
if (bound !== void 0 && !bothAnonymous && (bound.peer !== authIdentity.peer || bound.role !== authIdentity.role)) {
|
|
2519
|
-
this.unauthorized(res, null, "token does not match this session");
|
|
4385
|
+
this.unauthorized(req, res, null, "token does not match this session");
|
|
2520
4386
|
return;
|
|
2521
4387
|
}
|
|
2522
4388
|
if (existingSession !== void 0 && bound === void 0 && !authIdentity.anonymous) {
|
|
2523
4389
|
this.registry.bindToken(existingSession, authIdentity);
|
|
2524
4390
|
}
|
|
2525
4391
|
}
|
|
4392
|
+
if (this.protocolVersionRejected(req, res)) return;
|
|
4393
|
+
const presentedSession = this.registry.sessionIdFor(req);
|
|
4394
|
+
if (presentedSession !== void 0 && !this.registry.hasSession(presentedSession)) {
|
|
4395
|
+
this.jsonRpcError(req, res, null, -32001, "session not found \u2014 send a new initialize request", void 0, 404);
|
|
4396
|
+
return;
|
|
4397
|
+
}
|
|
4398
|
+
this.registry.touch(presentedSession);
|
|
2526
4399
|
let body;
|
|
2527
4400
|
try {
|
|
2528
4401
|
body = await readBody(req);
|
|
2529
4402
|
} catch (error) {
|
|
2530
|
-
this.jsonRpcError(res, null, -32700, `parse error: ${error.message}`);
|
|
4403
|
+
this.jsonRpcError(req, res, null, -32700, `parse error: ${error.message}`);
|
|
2531
4404
|
return;
|
|
2532
4405
|
}
|
|
2533
4406
|
let message;
|
|
2534
4407
|
try {
|
|
2535
4408
|
message = JSON.parse(body.toString("utf8"));
|
|
2536
4409
|
} catch {
|
|
2537
|
-
this.jsonRpcError(res, null, -32700, "parse error: invalid JSON");
|
|
4410
|
+
this.jsonRpcError(req, res, null, -32700, "parse error: invalid JSON");
|
|
2538
4411
|
return;
|
|
2539
4412
|
}
|
|
2540
4413
|
if (typeof message !== "object" || message === null || message.method === void 0) {
|
|
2541
|
-
this.jsonRpcError(res, message?.id ?? null, -32600, "invalid request");
|
|
4414
|
+
this.jsonRpcError(req, res, message?.id ?? null, -32600, "invalid request");
|
|
2542
4415
|
return;
|
|
2543
4416
|
}
|
|
2544
4417
|
const id = message.id ?? null;
|
|
2545
4418
|
const sessionId = this.registry.sessionIdFor(req);
|
|
2546
4419
|
if (sessionId !== void 0) this.registry.sessionIps.set(sessionId, clientIp(req));
|
|
4420
|
+
if (sessionId !== void 0 && this.presentedManagerToken(req)) this.registry.markManagerSession(sessionId);
|
|
2547
4421
|
if (id === null) {
|
|
2548
|
-
res.writeHead(202, { ...
|
|
4422
|
+
res.writeHead(202, { ...this.corsFor(req), "Content-Length": "0" }).end();
|
|
2549
4423
|
return;
|
|
2550
4424
|
}
|
|
2551
4425
|
try {
|
|
2552
4426
|
const { result, extraHeaders } = await this.dispatch(message, sessionId, authIdentity);
|
|
2553
4427
|
res.writeHead(200, {
|
|
2554
|
-
...
|
|
4428
|
+
...this.corsFor(req),
|
|
2555
4429
|
"Content-Type": "application/json; charset=utf-8",
|
|
2556
4430
|
"Mcp-Protocol-Version": messageProtocolVersion(req),
|
|
2557
4431
|
...extraHeaders
|
|
@@ -2559,7 +4433,7 @@ data: ${JSON.stringify({ jsonrpc: "2.0", method, params })}
|
|
|
2559
4433
|
res.end(JSON.stringify({ jsonrpc: "2.0", id, result }));
|
|
2560
4434
|
} catch (error) {
|
|
2561
4435
|
const code = error.code ?? -32603;
|
|
2562
|
-
this.jsonRpcError(res, id, code, error.message
|
|
4436
|
+
this.jsonRpcError(req, res, id, code, error.message);
|
|
2563
4437
|
}
|
|
2564
4438
|
}
|
|
2565
4439
|
async dispatch(message, sessionId, authIdentity) {
|
|
@@ -2622,11 +4496,27 @@ data: ${JSON.stringify({ jsonrpc: "2.0", method, params })}
|
|
|
2622
4496
|
throw rpcError(-32601, `method not found: ${method}`);
|
|
2623
4497
|
}
|
|
2624
4498
|
}
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
4499
|
+
/** Spec MUST: a request carrying an `MCP-Protocol-Version` this server does
|
|
4500
|
+
* not implement gets 400. Absent is fine — an absent header means the client is
|
|
4501
|
+
* on the newest revision this server knows, which is what responses advertise
|
|
4502
|
+
* (`messageProtocolVersion` returns LATEST_VERSION) —
|
|
4503
|
+
* but *present and unknown* is a client speaking a revision whose rules this
|
|
4504
|
+
* server would otherwise be guessing at. Writes the response itself and
|
|
4505
|
+
* reports whether it did. */
|
|
4506
|
+
protocolVersionRejected(req, res) {
|
|
4507
|
+
const presented = req.headers["mcp-protocol-version"];
|
|
4508
|
+
if (presented === void 0) return false;
|
|
4509
|
+
if (typeof presented === "string" && SUPPORTED_VERSIONS.includes(presented)) return false;
|
|
4510
|
+
this.jsonRpcError(req, res, null, -32600, `unsupported MCP-Protocol-Version: ${String(presented).slice(0, 64)} (supported: ${SUPPORTED_VERSIONS.join(", ")})`, void 0, 400);
|
|
4511
|
+
return true;
|
|
4512
|
+
}
|
|
4513
|
+
jsonRpcError(req, res, id, code, message, data, status) {
|
|
4514
|
+
const code400 = code === -32700 || code === -32600;
|
|
4515
|
+
const httpStatus = status ?? (code400 ? 400 : 200);
|
|
4516
|
+
res.writeHead(httpStatus, {
|
|
4517
|
+
...this.corsFor(req),
|
|
2628
4518
|
"Content-Type": "application/json; charset=utf-8",
|
|
2629
|
-
|
|
4519
|
+
"Mcp-Protocol-Version": messageProtocolVersion(req)
|
|
2630
4520
|
});
|
|
2631
4521
|
res.end(JSON.stringify({ jsonrpc: "2.0", id, error: { code, message, ...data !== void 0 ? { data } : {} } }));
|
|
2632
4522
|
}
|
|
@@ -2637,7 +4527,8 @@ function rpcError(code, message) {
|
|
|
2637
4527
|
return error;
|
|
2638
4528
|
}
|
|
2639
4529
|
function messageProtocolVersion(req) {
|
|
2640
|
-
|
|
4530
|
+
const presented = req.headers["mcp-protocol-version"];
|
|
4531
|
+
return typeof presented === "string" && SUPPORTED_VERSIONS.includes(presented) ? presented : LATEST_VERSION;
|
|
2641
4532
|
}
|
|
2642
4533
|
function clientIp(req) {
|
|
2643
4534
|
const forwarded = req.headers["x-forwarded-for"];
|
|
@@ -2647,10 +4538,44 @@ function clientIp(req) {
|
|
|
2647
4538
|
}
|
|
2648
4539
|
return (req.socket.remoteAddress ?? "?").replace(/^::ffff:/, "");
|
|
2649
4540
|
}
|
|
2650
|
-
function
|
|
4541
|
+
function headerValue(value) {
|
|
4542
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
4543
|
+
return typeof raw === "string" && raw.trim() !== "" ? raw.trim() : void 0;
|
|
4544
|
+
}
|
|
4545
|
+
function secretEquals(a, b) {
|
|
4546
|
+
const left = Buffer.from(a, "utf8");
|
|
4547
|
+
const right = Buffer.from(b, "utf8");
|
|
4548
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
4549
|
+
}
|
|
4550
|
+
function originHostname(origin) {
|
|
4551
|
+
try {
|
|
4552
|
+
return new URL(origin).hostname.toLowerCase();
|
|
4553
|
+
} catch {
|
|
4554
|
+
return void 0;
|
|
4555
|
+
}
|
|
4556
|
+
}
|
|
4557
|
+
function hostHeaderName(host) {
|
|
4558
|
+
try {
|
|
4559
|
+
return new URL(`http://${host}`).hostname.toLowerCase();
|
|
4560
|
+
} catch {
|
|
4561
|
+
return void 0;
|
|
4562
|
+
}
|
|
4563
|
+
}
|
|
4564
|
+
function isLoopbackHost(host) {
|
|
4565
|
+
const name = host.trim().toLowerCase().replace(/\.$/, "");
|
|
4566
|
+
if (name === "localhost" || name === "::1" || name === "[::1]") return true;
|
|
4567
|
+
const quad = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(name);
|
|
4568
|
+
return quad !== null && quad.slice(1).every((octet) => Number(octet) <= 255);
|
|
4569
|
+
}
|
|
4570
|
+
var ALLOWED_REQUEST_HEADERS = "content-type, mcp-session-id, mcp-protocol-version, authorization";
|
|
4571
|
+
function corsHeaders(allowOrigin) {
|
|
2651
4572
|
return {
|
|
2652
|
-
|
|
2653
|
-
"Access-Control-Allow-
|
|
4573
|
+
Vary: "Origin",
|
|
4574
|
+
...allowOrigin !== void 0 ? { "Access-Control-Allow-Origin": allowOrigin } : {},
|
|
4575
|
+
"Access-Control-Allow-Headers": ALLOWED_REQUEST_HEADERS,
|
|
4576
|
+
// Exposed so a cross-origin browser client can actually READ the version the
|
|
4577
|
+
// server is speaking: without this the header is set but invisible to script.
|
|
4578
|
+
"Access-Control-Expose-Headers": "Mcp-Session-Id, Mcp-Protocol-Version",
|
|
2654
4579
|
"Access-Control-Allow-Methods": "GET, POST, OPTIONS"
|
|
2655
4580
|
};
|
|
2656
4581
|
}
|
|
@@ -2676,7 +4601,7 @@ function readBody(req) {
|
|
|
2676
4601
|
import { DatabaseSync } from "node:sqlite";
|
|
2677
4602
|
var KIND_NAMES = ["chat", "task", "notice", "ack"];
|
|
2678
4603
|
function messageToRow(message) {
|
|
2679
|
-
return [message.id, message.from, message.to, message.kind, message.content, message.ref ?? null, message.channel ?? null, message.threadId ?? null, message.ts, message.hop ?? null];
|
|
4604
|
+
return [message.id, message.from, message.to, message.kind, message.content, message.ref ?? null, message.channel ?? null, message.threadId ?? null, message.ts, message.hop ?? null, message.seq ?? null, message.expiresAt ?? null, message.priority ?? null];
|
|
2680
4605
|
}
|
|
2681
4606
|
function rowToMessage(row) {
|
|
2682
4607
|
const id = row.id;
|
|
@@ -2699,6 +4624,23 @@ function rowToMessage(row) {
|
|
|
2699
4624
|
// Chain depth: rows written before the hop column restore without it
|
|
2700
4625
|
// (treated as a chain origin by importHistory — never as a bogus depth).
|
|
2701
4626
|
...typeof row.hop === "number" && Number.isFinite(row.hop) && row.hop > 0 ? { hop: row.hop } : {},
|
|
4627
|
+
// Cursors: rows written before the mseq column restore without it, and are
|
|
4628
|
+
// then reachable only without a `since` cursor (never mistaken for seq 0).
|
|
4629
|
+
...typeof row.mseq === "number" && Number.isFinite(row.mseq) && row.mseq > 0 ? { seq: row.mseq } : {},
|
|
4630
|
+
// Deadline: restored so a message that expired while the hub was down is
|
|
4631
|
+
// dropped rather than delivered late.
|
|
4632
|
+
...typeof row.expires_at === "number" && Number.isFinite(row.expires_at) && row.expires_at > 0 ? { expiresAt: row.expires_at } : {},
|
|
4633
|
+
// Delivery priority: ONLY a real 0 | 1 | 2 restores. Anything else — NULL
|
|
4634
|
+
// from a database written before this column existed, or an out-of-range
|
|
4635
|
+
// value — restores as UNSET, deliberately not as 0. An absent priority is a
|
|
4636
|
+
// different claim from "the sender asked for 0": `compose` keeps an unset
|
|
4637
|
+
// one off the wire and `priorityOf` reads absent as 0 anyway, so writing 0
|
|
4638
|
+
// here would hand every restored message a priority its sender never gave.
|
|
4639
|
+
// That matters because a restored message is re-inserted (lease return,
|
|
4640
|
+
// nack, mail queued while the hub was down) and `insertByPriority` +
|
|
4641
|
+
// overflow dropping then act on it: a p2 instruction restored as p0 loses
|
|
4642
|
+
// its slot to chatter, which is exactly the bug this column prevents.
|
|
4643
|
+
...row.priority === 0 || row.priority === 1 || row.priority === 2 ? { priority: row.priority } : {},
|
|
2702
4644
|
ts
|
|
2703
4645
|
};
|
|
2704
4646
|
}
|
|
@@ -2709,15 +4651,15 @@ var SQLiteStateStore = class {
|
|
|
2709
4651
|
this.db.exec("PRAGMA journal_mode = WAL");
|
|
2710
4652
|
this.db.exec(`
|
|
2711
4653
|
CREATE TABLE IF NOT EXISTS profiles (
|
|
2712
|
-
id TEXT PRIMARY KEY, alias TEXT, client_name TEXT, client_version TEXT, registered_at INTEGER
|
|
4654
|
+
id TEXT PRIMARY KEY, alias TEXT, client_name TEXT, client_version TEXT, registered_at INTEGER, card TEXT
|
|
2713
4655
|
);
|
|
2714
4656
|
CREATE TABLE IF NOT EXISTS messages (
|
|
2715
4657
|
seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, from_peer TEXT NOT NULL,
|
|
2716
|
-
to_peer TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL, ref TEXT, channel TEXT, thread_id TEXT, ts INTEGER NOT NULL, hop INTEGER
|
|
4658
|
+
to_peer TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL, ref TEXT, channel TEXT, thread_id TEXT, ts INTEGER NOT NULL, hop INTEGER, mseq INTEGER, expires_at INTEGER, priority INTEGER
|
|
2717
4659
|
);
|
|
2718
4660
|
CREATE TABLE IF NOT EXISTS mailboxes (
|
|
2719
4661
|
peer TEXT NOT NULL, seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, from_peer TEXT NOT NULL,
|
|
2720
|
-
to_peer TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL, ref TEXT, channel TEXT, thread_id TEXT, ts INTEGER NOT NULL, hop INTEGER
|
|
4662
|
+
to_peer TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL, ref TEXT, channel TEXT, thread_id TEXT, ts INTEGER NOT NULL, hop INTEGER, mseq INTEGER, expires_at INTEGER, priority INTEGER
|
|
2721
4663
|
);
|
|
2722
4664
|
CREATE TABLE IF NOT EXISTS groups (
|
|
2723
4665
|
id TEXT PRIMARY KEY, name TEXT, members TEXT NOT NULL, created_by TEXT NOT NULL, created_at INTEGER NOT NULL
|
|
@@ -2727,13 +4669,17 @@ var SQLiteStateStore = class {
|
|
|
2727
4669
|
);
|
|
2728
4670
|
`);
|
|
2729
4671
|
for (const table of ["messages", "mailboxes"]) {
|
|
2730
|
-
for (const column of ["thread_id TEXT", "hop INTEGER"]) {
|
|
4672
|
+
for (const column of ["thread_id TEXT", "hop INTEGER", "mseq INTEGER", "expires_at INTEGER", "priority INTEGER"]) {
|
|
2731
4673
|
try {
|
|
2732
4674
|
this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column}`);
|
|
2733
4675
|
} catch {
|
|
2734
4676
|
}
|
|
2735
4677
|
}
|
|
2736
4678
|
}
|
|
4679
|
+
try {
|
|
4680
|
+
this.db.exec("ALTER TABLE profiles ADD COLUMN card TEXT");
|
|
4681
|
+
} catch {
|
|
4682
|
+
}
|
|
2737
4683
|
log.info(`sqlite state open: ${file}`);
|
|
2738
4684
|
}
|
|
2739
4685
|
db;
|
|
@@ -2745,24 +4691,24 @@ var SQLiteStateStore = class {
|
|
|
2745
4691
|
/** Insert buffered messages and re-snapshot mailboxes/profiles/groups/tasks. */
|
|
2746
4692
|
flush(snapshot) {
|
|
2747
4693
|
const insert = this.db.prepare(
|
|
2748
|
-
"INSERT INTO messages (id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
4694
|
+
"INSERT INTO messages (id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop, mseq, expires_at, priority) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
2749
4695
|
);
|
|
2750
4696
|
for (const message of this.buffer.splice(0, this.buffer.length)) {
|
|
2751
4697
|
insert.run(...messageToRow(message));
|
|
2752
4698
|
}
|
|
2753
4699
|
this.db.exec("DELETE FROM mailboxes");
|
|
2754
4700
|
const insertMail = this.db.prepare(
|
|
2755
|
-
"INSERT INTO mailboxes (peer, id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
4701
|
+
"INSERT INTO mailboxes (peer, id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop, mseq, expires_at, priority) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
2756
4702
|
);
|
|
2757
4703
|
for (const [peer, queue] of Object.entries(snapshot.mailboxes)) {
|
|
2758
4704
|
for (const message of queue) insertMail.run(peer, ...messageToRow(message));
|
|
2759
4705
|
}
|
|
2760
4706
|
this.db.exec("DELETE FROM profiles");
|
|
2761
4707
|
const insertProfile = this.db.prepare(
|
|
2762
|
-
"INSERT INTO profiles (id, alias, client_name, client_version, registered_at) VALUES (?, ?, ?, ?, ?)"
|
|
4708
|
+
"INSERT INTO profiles (id, alias, client_name, client_version, registered_at, card) VALUES (?, ?, ?, ?, ?, ?)"
|
|
2763
4709
|
);
|
|
2764
4710
|
for (const profile of snapshot.profiles) {
|
|
2765
|
-
insertProfile.run(profile.id, profile.alias ?? null, profile.clientName ?? null, profile.clientVersion ?? null, profile.registeredAt);
|
|
4711
|
+
insertProfile.run(profile.id, profile.alias ?? null, profile.clientName ?? null, profile.clientVersion ?? null, profile.registeredAt, profile.card === void 0 ? null : JSON.stringify(profile.card));
|
|
2766
4712
|
}
|
|
2767
4713
|
this.db.exec("DELETE FROM groups");
|
|
2768
4714
|
const insertGroup = this.db.prepare(
|
|
@@ -2794,7 +4740,9 @@ var SQLiteStateStore = class {
|
|
|
2794
4740
|
...typeof row.alias === "string" && row.alias !== "" ? { alias: row.alias } : {},
|
|
2795
4741
|
...typeof row.client_name === "string" && row.client_name !== "" ? { clientName: row.client_name } : {},
|
|
2796
4742
|
...typeof row.client_version === "string" && row.client_version !== "" ? { clientVersion: row.client_version } : {},
|
|
2797
|
-
registeredAt: typeof row.registered_at === "number" ? row.registered_at : Date.now()
|
|
4743
|
+
registeredAt: typeof row.registered_at === "number" ? row.registered_at : Date.now(),
|
|
4744
|
+
// A corrupt card row must not take the whole roster down.
|
|
4745
|
+
...cardField(row.card)
|
|
2798
4746
|
});
|
|
2799
4747
|
}
|
|
2800
4748
|
const messages = [];
|
|
@@ -2842,10 +4790,19 @@ var SQLiteStateStore = class {
|
|
|
2842
4790
|
this.db.close();
|
|
2843
4791
|
}
|
|
2844
4792
|
};
|
|
4793
|
+
function cardField(raw) {
|
|
4794
|
+
if (typeof raw !== "string" || raw === "") return {};
|
|
4795
|
+
try {
|
|
4796
|
+
const parsed = JSON.parse(raw);
|
|
4797
|
+
return typeof parsed === "object" && parsed !== null ? { card: parsed } : {};
|
|
4798
|
+
} catch {
|
|
4799
|
+
return {};
|
|
4800
|
+
}
|
|
4801
|
+
}
|
|
2845
4802
|
|
|
2846
4803
|
// src/index.ts
|
|
2847
4804
|
var SERVER_NAME = "agent-comm-hub";
|
|
2848
|
-
var SERVER_VERSION = "0.
|
|
4805
|
+
var SERVER_VERSION = "0.11.0";
|
|
2849
4806
|
var DEFAULT_HOST = "127.0.0.1";
|
|
2850
4807
|
var DEFAULT_PORT = 18764;
|
|
2851
4808
|
var DEFAULT_PATH = "/mcp";
|
|
@@ -2896,23 +4853,60 @@ function writeRosterFile(file, profiles) {
|
|
|
2896
4853
|
writeFileSync2(tmp, JSON.stringify({ version: 1, savedAt: Date.now(), profiles }), "utf8");
|
|
2897
4854
|
renameSync2(tmp, file);
|
|
2898
4855
|
}
|
|
4856
|
+
function readManagerTokenFile(stateFile) {
|
|
4857
|
+
if (stateFile === void 0) return void 0;
|
|
4858
|
+
const file = join(dirname2(stateFile), "manager.token");
|
|
4859
|
+
try {
|
|
4860
|
+
const raw = readFileSync3(file, "utf8").trim();
|
|
4861
|
+
return raw === "" ? void 0 : raw;
|
|
4862
|
+
} catch (error) {
|
|
4863
|
+
if (error.code === "ENOENT") return void 0;
|
|
4864
|
+
throw new Error(`cannot read the manager token ${file}: ${error.message}`);
|
|
4865
|
+
}
|
|
4866
|
+
}
|
|
2899
4867
|
function startHub(config = {}, log = console) {
|
|
2900
4868
|
const overrides = Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
|
|
2901
4869
|
const resolved = { ...DEFAULT_CONFIG, ...overrides };
|
|
4870
|
+
const managerToken = resolved.managerToken ?? readManagerTokenFile(resolved.stateFile);
|
|
4871
|
+
if (!isLoopbackHost(resolved.host) && resolved.authTokens === void 0 && resolved.insecure !== true) {
|
|
4872
|
+
throw new Error(
|
|
4873
|
+
`refusing to bind ${resolved.host} without --auth-tokens: the hub has no authentication, so every client that can reach the port would be trusted. Pass --auth-tokens <file> (recommended), or --insecure to accept the risk on an already-isolated network.`
|
|
4874
|
+
);
|
|
4875
|
+
}
|
|
4876
|
+
if (managerToken === void 0 && resolved.managerPeers !== "all" && !isLoopbackHost(resolved.host)) {
|
|
4877
|
+
log.warn(
|
|
4878
|
+
`manager peer ids are claimable by any client that can reach ${resolved.host}:${resolved.port} \u2014 set --manager-token (or run with --auth-tokens) to require a credential`
|
|
4879
|
+
);
|
|
4880
|
+
}
|
|
4881
|
+
if (managerToken !== void 0 && resolved.authTokens !== void 0) {
|
|
4882
|
+
log.warn(
|
|
4883
|
+
"both --manager-token and --auth-tokens are set: the token table owns the Authorization header, so the manager token is ignored. Grant manager rights with `auth add <peer> --role manager` instead."
|
|
4884
|
+
);
|
|
4885
|
+
}
|
|
2902
4886
|
let mcp;
|
|
2903
4887
|
let dbStore;
|
|
2904
4888
|
const pushRoster = () => {
|
|
2905
|
-
mcp.notifyAll(
|
|
4889
|
+
mcp.notifyAll(SSE_METHOD, {
|
|
2906
4890
|
level: "info",
|
|
2907
4891
|
logger: "bridge",
|
|
2908
|
-
data: { event:
|
|
4892
|
+
data: { event: SSE_EVENT_PEERS_CHANGED, peers: rosterFor(hub, registry) }
|
|
2909
4893
|
});
|
|
2910
4894
|
};
|
|
4895
|
+
const streamCursor = /* @__PURE__ */ new Map();
|
|
4896
|
+
const oneStreamPer = (key, candidates) => {
|
|
4897
|
+
if (candidates.length === 0) return [];
|
|
4898
|
+
const streamed = registry.liveSessions();
|
|
4899
|
+
const open = candidates.filter((id) => streamed.has(id));
|
|
4900
|
+
const pool = open.length > 0 ? open : candidates;
|
|
4901
|
+
const at = (streamCursor.get(key) ?? 0) % pool.length;
|
|
4902
|
+
streamCursor.set(key, (at + 1) % pool.length);
|
|
4903
|
+
return [pool[at]];
|
|
4904
|
+
};
|
|
2911
4905
|
const pushQueued = (message, target) => {
|
|
2912
|
-
mcp.notify(registry.sessionsForPeer(target),
|
|
4906
|
+
mcp.notify(oneStreamPer(`peer:${target}`, registry.sessionsForPeer(target)), SSE_METHOD, {
|
|
2913
4907
|
level: "info",
|
|
2914
4908
|
logger: "bridge",
|
|
2915
|
-
data: { event:
|
|
4909
|
+
data: { event: SSE_EVENT_MESSAGE, message: present(message) }
|
|
2916
4910
|
});
|
|
2917
4911
|
};
|
|
2918
4912
|
const managerSet = resolved.managerPeers === "all" ? void 0 : new Set(resolved.managerPeers);
|
|
@@ -2921,18 +4915,39 @@ function startHub(config = {}, log = console) {
|
|
|
2921
4915
|
for (const sessionId of registry.liveSessions()) {
|
|
2922
4916
|
const peer = registry.peerFor(sessionId);
|
|
2923
4917
|
if (peer === void 0) continue;
|
|
2924
|
-
if (registry
|
|
4918
|
+
if (isManagerCaller(registry, sessionId, peer, { managerPeers: managerSet, managerTokenRequired: managerToken !== void 0 })) {
|
|
2925
4919
|
managers.push(sessionId);
|
|
2926
4920
|
}
|
|
2927
4921
|
}
|
|
2928
4922
|
if (managers.length > 0) {
|
|
2929
|
-
mcp.notify(managers,
|
|
4923
|
+
mcp.notify(oneStreamPer("relay", managers), SSE_METHOD, {
|
|
2930
4924
|
level: "info",
|
|
2931
4925
|
logger: "bridge",
|
|
2932
|
-
data: { event:
|
|
4926
|
+
data: { event: SSE_EVENT_MESSAGE, message: present(message) }
|
|
2933
4927
|
});
|
|
2934
4928
|
}
|
|
2935
4929
|
};
|
|
4930
|
+
const MAX_TASK_PUSH_MEMORY = 512;
|
|
4931
|
+
const lastTaskPush = /* @__PURE__ */ new Map();
|
|
4932
|
+
const pushTaskChanged = (task) => {
|
|
4933
|
+
const data = {
|
|
4934
|
+
event: SSE_EVENT_TASK_CHANGED,
|
|
4935
|
+
taskId: task.id,
|
|
4936
|
+
status: task.status,
|
|
4937
|
+
// A2A naming, so a client that speaks A2A does not have to carry the
|
|
4938
|
+
// ledger's own vocabulary — same mapping bridge_task_status publishes.
|
|
4939
|
+
a2aState: a2aState(task.status),
|
|
4940
|
+
updatedAt: task.updatedAt
|
|
4941
|
+
};
|
|
4942
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4943
|
+
for (const peer of [task.from, ...task.assignees.map((assignee) => assignee.peerId)]) {
|
|
4944
|
+
if (seen.has(peer)) continue;
|
|
4945
|
+
seen.add(peer);
|
|
4946
|
+
const sessions = registry.sessionsForPeer(peer);
|
|
4947
|
+
if (sessions.length === 0) continue;
|
|
4948
|
+
mcp.notify(oneStreamPer(`task:${peer}`, sessions), SSE_METHOD, { level: "info", logger: "bridge", data });
|
|
4949
|
+
}
|
|
4950
|
+
};
|
|
2936
4951
|
let saveTimer;
|
|
2937
4952
|
let rosterDirty = false;
|
|
2938
4953
|
let dbDirty = false;
|
|
@@ -2963,12 +4978,64 @@ function startHub(config = {}, log = console) {
|
|
|
2963
4978
|
}, 500);
|
|
2964
4979
|
saveTimer.unref?.();
|
|
2965
4980
|
};
|
|
4981
|
+
let runnerRegistry;
|
|
4982
|
+
const runnerQueue = /* @__PURE__ */ new Map();
|
|
4983
|
+
const taskPayload = (content) => {
|
|
4984
|
+
try {
|
|
4985
|
+
const parsed = JSON.parse(content);
|
|
4986
|
+
return {
|
|
4987
|
+
prompt: typeof parsed.prompt === "string" ? parsed.prompt : content,
|
|
4988
|
+
...typeof parsed.context === "string" ? { context: parsed.context } : {},
|
|
4989
|
+
...typeof parsed.deliverable === "string" ? { deliverable: parsed.deliverable } : {},
|
|
4990
|
+
...typeof parsed.threadId === "string" ? { threadId: parsed.threadId } : {}
|
|
4991
|
+
};
|
|
4992
|
+
} catch {
|
|
4993
|
+
return { prompt: content };
|
|
4994
|
+
}
|
|
4995
|
+
};
|
|
4996
|
+
function runTask(message, target) {
|
|
4997
|
+
const runner = runnerRegistry?.get(target);
|
|
4998
|
+
if (runner === void 0) return;
|
|
4999
|
+
const previous = runnerQueue.get(target) ?? Promise.resolve();
|
|
5000
|
+
const next = previous.then(async () => {
|
|
5001
|
+
const payload = taskPayload(message.content);
|
|
5002
|
+
hub.noteEvent("runner_started", { peer: target, detail: { taskId: message.id, runner: runner.name } });
|
|
5003
|
+
try {
|
|
5004
|
+
const result = await runner.run({ taskId: message.id, peer: target, ...payload });
|
|
5005
|
+
hub.noteEvent("runner_finished", { peer: target, detail: { taskId: message.id, runner: runner.name, status: result.status } });
|
|
5006
|
+
hub.ackForRunner(target, message.id, { status: result.status, note: result.note });
|
|
5007
|
+
log.info(`runner ${runner.name}: task ${message.id} for '${target}' -> ${result.status}`);
|
|
5008
|
+
} catch (error) {
|
|
5009
|
+
hub.noteEvent("runner_finished", { peer: target, detail: { taskId: message.id, runner: runner.name, status: "failed", error: error.message } });
|
|
5010
|
+
try {
|
|
5011
|
+
hub.ackForRunner(target, message.id, { status: "failed", note: `runner error: ${error.message}` });
|
|
5012
|
+
} catch {
|
|
5013
|
+
}
|
|
5014
|
+
log.warn(`runner ${runner.name} errored on task ${message.id}: ${error.message}`);
|
|
5015
|
+
}
|
|
5016
|
+
});
|
|
5017
|
+
runnerQueue.set(target, next.catch(() => {
|
|
5018
|
+
}));
|
|
5019
|
+
}
|
|
2966
5020
|
const hub = new AgentHub({
|
|
2967
5021
|
maxQueue: resolved.maxQueue,
|
|
2968
5022
|
historyLimit: resolved.historyLimit,
|
|
2969
5023
|
waitTimeoutMs: resolved.waitTimeoutMs,
|
|
2970
5024
|
connectedWindowMs: resolved.connectedWindowMs,
|
|
2971
5025
|
peerIdleTimeoutMs: resolved.peerIdleTimeoutMs,
|
|
5026
|
+
parkedTtlMs: resolved.parkedTtlMs,
|
|
5027
|
+
leaseTtlMs: resolved.leaseTtlMs,
|
|
5028
|
+
maxAttempts: resolved.maxAttempts,
|
|
5029
|
+
ratePerMin: resolved.ratePerMin,
|
|
5030
|
+
// A parked mailbox that expires is data loss: say so, and make the store
|
|
5031
|
+
// re-snapshot so the dropped rows cannot resurrect on the next restart.
|
|
5032
|
+
onMailboxExpired: (peerId, dropped) => {
|
|
5033
|
+
log.warn(`parked mailbox for '${peerId}' expired after ${resolved.parkedTtlMs ?? DEFAULT_PARKED_TTL_MS}ms: ${dropped} message(s) dropped`);
|
|
5034
|
+
if (dbStore !== void 0) {
|
|
5035
|
+
dbDirty = true;
|
|
5036
|
+
scheduleSave();
|
|
5037
|
+
}
|
|
5038
|
+
},
|
|
2972
5039
|
onPeerGc: (peerId) => registry.unbindPeerId(peerId),
|
|
2973
5040
|
// Remote persistence: buffer every history append; re-snapshot when a
|
|
2974
5041
|
// mailbox is consumed so drained messages cannot resurrect on restart.
|
|
@@ -2993,11 +5060,26 @@ function startHub(config = {}, log = console) {
|
|
|
2993
5060
|
},
|
|
2994
5061
|
// Task ledger transitions (ack folding, SLA timeout, first delivery) are
|
|
2995
5062
|
// their own persistence trigger: without it a crash between two roster
|
|
2996
|
-
// events loses the ledger state the admin board reads back.
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
|
|
5063
|
+
// events loses the ledger state the admin board reads back. They are also
|
|
5064
|
+
// the SSE `task_changed` signal for the two parties of a task.
|
|
5065
|
+
onTaskChanged: (task) => {
|
|
5066
|
+
if (dbStore !== void 0) {
|
|
5067
|
+
dbDirty = true;
|
|
5068
|
+
scheduleSave();
|
|
5069
|
+
}
|
|
5070
|
+
if (lastTaskPush.get(task.id) === task.status) return;
|
|
5071
|
+
try {
|
|
5072
|
+
pushTaskChanged(task);
|
|
5073
|
+
} catch (error) {
|
|
5074
|
+
log.warn(`task_changed notification failed: ${error.message}`);
|
|
5075
|
+
}
|
|
5076
|
+
lastTaskPush.delete(task.id);
|
|
5077
|
+
lastTaskPush.set(task.id, task.status);
|
|
5078
|
+
while (lastTaskPush.size > MAX_TASK_PUSH_MEMORY) {
|
|
5079
|
+
const oldest = lastTaskPush.keys().next().value;
|
|
5080
|
+
if (oldest === void 0) break;
|
|
5081
|
+
lastTaskPush.delete(oldest);
|
|
5082
|
+
}
|
|
3001
5083
|
},
|
|
3002
5084
|
onGroupsChanged: () => {
|
|
3003
5085
|
if (dbStore === void 0) return;
|
|
@@ -3024,6 +5106,17 @@ function startHub(config = {}, log = console) {
|
|
|
3024
5106
|
} catch (error) {
|
|
3025
5107
|
log.warn(`message notification failed: ${error.message}`);
|
|
3026
5108
|
}
|
|
5109
|
+
},
|
|
5110
|
+
// A task that reached a mailbox has nobody polling for it. If this peer has
|
|
5111
|
+
// a runner configured, wake it — that is the whole point of a runner.
|
|
5112
|
+
// `runnerRegistry` is filled in below, once the herdr adapter exists; this
|
|
5113
|
+
// hook only ever fires after the hub is serving.
|
|
5114
|
+
onTaskQueued: (message, target) => {
|
|
5115
|
+
try {
|
|
5116
|
+
runTask(message, target);
|
|
5117
|
+
} catch (error) {
|
|
5118
|
+
log.warn(`runner dispatch failed for '${target}': ${error.message}`);
|
|
5119
|
+
}
|
|
3027
5120
|
}
|
|
3028
5121
|
});
|
|
3029
5122
|
const registry = new SessionRegistry();
|
|
@@ -3046,9 +5139,9 @@ function startHub(config = {}, log = console) {
|
|
|
3046
5139
|
log.info(`roster restored: ${importedProfiles} profile(s) from ${resolved.db}`);
|
|
3047
5140
|
}
|
|
3048
5141
|
const restoredMessages = hub.importHistory(state.messages);
|
|
3049
|
-
const restoredQueued = hub.importMailboxes(state.mailboxes);
|
|
3050
5142
|
const restoredGroups = hub.importGroups(state.groups);
|
|
3051
5143
|
const restoredTasks = hub.importTasks(state.tasks);
|
|
5144
|
+
const restoredQueued = hub.importMailboxes(state.mailboxes);
|
|
3052
5145
|
if (restoredMessages + restoredQueued + restoredGroups > 0) {
|
|
3053
5146
|
log.info(`state restored from ${resolved.db}: ${restoredMessages} message(s), ${restoredQueued} queued, ${restoredGroups} group(s)`);
|
|
3054
5147
|
dbDirty = true;
|
|
@@ -3076,6 +5169,8 @@ function startHub(config = {}, log = console) {
|
|
|
3076
5169
|
socketPath: resolved.herdrSocketPath,
|
|
3077
5170
|
sendRequest: resolved.herdrSendRequest
|
|
3078
5171
|
});
|
|
5172
|
+
runnerRegistry = new RunnerRegistry(resolved.runners ?? [], { herdr });
|
|
5173
|
+
if (runnerRegistry.size > 0) log.info(`runners configured for: ${runnerRegistry.peers().join(", ")}`);
|
|
3079
5174
|
let auth;
|
|
3080
5175
|
let authReload;
|
|
3081
5176
|
if (resolved.authTokens !== void 0) {
|
|
@@ -3101,7 +5196,14 @@ function startHub(config = {}, log = console) {
|
|
|
3101
5196
|
waitTimeoutMs: resolved.waitTimeoutMs,
|
|
3102
5197
|
herdr,
|
|
3103
5198
|
herdrControlPeers: resolved.herdrControlPeers === "all" || resolved.herdrControlPeers === void 0 ? "all" : new Set(resolved.herdrControlPeers),
|
|
3104
|
-
managerPeers: resolved.managerPeers === "all" ? "all" : new Set(resolved.managerPeers ?? DEFAULT_CONFIG.managerPeers)
|
|
5199
|
+
managerPeers: resolved.managerPeers === "all" ? "all" : new Set(resolved.managerPeers ?? DEFAULT_CONFIG.managerPeers),
|
|
5200
|
+
managerTokenRequired: managerToken !== void 0,
|
|
5201
|
+
// Token identities are an authorization fact of the TABLE, not of the live
|
|
5202
|
+
// sessions: `bridge_rename` must not re-key onto a configured id whose
|
|
5203
|
+
// owner has not connected yet. Read from the file on every call because
|
|
5204
|
+
// the token admin API adds/removes rows at runtime (and `readTokens`
|
|
5205
|
+
// returns [] in loopback mode, where no id is reserved).
|
|
5206
|
+
...resolved.authTokens === void 0 ? {} : { tokenPeers: () => new Set(readTokens(resolved.authTokens).map((row) => row.peer)) }
|
|
3105
5207
|
}),
|
|
3106
5208
|
{ name: SERVER_NAME, version: SERVER_VERSION },
|
|
3107
5209
|
registry,
|
|
@@ -3128,12 +5230,15 @@ function startHub(config = {}, log = console) {
|
|
|
3128
5230
|
},
|
|
3129
5231
|
auth,
|
|
3130
5232
|
authTokensAdmin(resolved.authTokens, authReload),
|
|
3131
|
-
resolved.heartbeatMs
|
|
5233
|
+
resolved.heartbeatMs,
|
|
5234
|
+
resolved.allowOrigins === void 0 || resolved.allowOrigins.length === 0 ? void 0 : { allow: new Set(resolved.allowOrigins) },
|
|
5235
|
+
managerToken,
|
|
5236
|
+
resolved.sessionTtlMs
|
|
3132
5237
|
);
|
|
3133
5238
|
const server = createServer();
|
|
3134
5239
|
mcp.attach(server, resolved.path);
|
|
3135
5240
|
server.on("error", (error) => log.warn(`hub http server error: ${error.message}`));
|
|
3136
|
-
server.listen(resolved.port, resolved.host, () => {
|
|
5241
|
+
server.listen(resolved.port, resolved.host.trim(), () => {
|
|
3137
5242
|
log.info(`agent-comm-hub listening on http://${resolved.host}:${resolved.port}${resolved.path}`);
|
|
3138
5243
|
});
|
|
3139
5244
|
return {
|
|
@@ -3164,26 +5269,41 @@ function startHub(config = {}, log = console) {
|
|
|
3164
5269
|
}
|
|
3165
5270
|
export {
|
|
3166
5271
|
AGENT_STATUSES,
|
|
5272
|
+
ALL_ACK_STATUSES,
|
|
5273
|
+
ALL_TASK_STATUSES,
|
|
3167
5274
|
AgentHub,
|
|
3168
5275
|
BROADCAST,
|
|
5276
|
+
CLIENT_ACK_STATUSES,
|
|
3169
5277
|
DEFAULT_CONFIG,
|
|
3170
5278
|
DEFAULT_HOST,
|
|
3171
5279
|
DEFAULT_PATH,
|
|
3172
5280
|
DEFAULT_PORT,
|
|
5281
|
+
DEFAULT_RUN_TIMEOUT_MS,
|
|
5282
|
+
HUB_PEER,
|
|
3173
5283
|
HerdrCtl,
|
|
3174
5284
|
KINDS,
|
|
5285
|
+
MAX_EVENTS,
|
|
3175
5286
|
MAX_HOP,
|
|
5287
|
+
MAX_REPLY_CHAIN,
|
|
5288
|
+
MAX_RUN_NOTE_CHARS,
|
|
3176
5289
|
McpStreamableHttpServer,
|
|
3177
5290
|
PEER_ID_PATTERN,
|
|
5291
|
+
RunnerRegistry,
|
|
3178
5292
|
SERVER_NAME,
|
|
3179
5293
|
SERVER_VERSION,
|
|
3180
5294
|
SQLiteStateStore,
|
|
5295
|
+
SSE_EVENT_MESSAGE,
|
|
5296
|
+
SSE_EVENT_PEERS_CHANGED,
|
|
5297
|
+
SSE_EVENT_TASK_CHANGED,
|
|
5298
|
+
SSE_METHOD,
|
|
3181
5299
|
SessionRegistry,
|
|
3182
5300
|
TERMINAL_TASK_STATUSES,
|
|
5301
|
+
a2aState,
|
|
3183
5302
|
ackToTaskStatus,
|
|
3184
5303
|
addToken,
|
|
3185
5304
|
aggregateTaskStatus,
|
|
3186
5305
|
autoRegisterPeer,
|
|
5306
|
+
createRunner,
|
|
3187
5307
|
decodeContent,
|
|
3188
5308
|
encodeContent,
|
|
3189
5309
|
generateToken,
|
|
@@ -3197,5 +5317,6 @@ export {
|
|
|
3197
5317
|
sanitizePeerId,
|
|
3198
5318
|
startHub,
|
|
3199
5319
|
tokenTable,
|
|
5320
|
+
validateRunnerConfig,
|
|
3200
5321
|
watchTokenFile
|
|
3201
5322
|
};
|