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/cli.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { createServer } from "node:http";
|
|
5
5
|
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
6
6
|
import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
7
|
-
import { dirname as dirname2 } from "node:path";
|
|
7
|
+
import { dirname as dirname2, join } from "node:path";
|
|
8
8
|
|
|
9
9
|
// src/herdr-ctl.ts
|
|
10
10
|
import { execFile } from "node:child_process";
|
|
@@ -417,6 +417,104 @@ function socketSend(socketPath, method, params) {
|
|
|
417
417
|
});
|
|
418
418
|
}
|
|
419
419
|
|
|
420
|
+
// src/runner.ts
|
|
421
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
422
|
+
var DEFAULT_RUN_TIMEOUT_MS = 12e4;
|
|
423
|
+
var MAX_RUN_NOTE_CHARS = 4e3;
|
|
424
|
+
function validateRunnerConfig(config, index) {
|
|
425
|
+
const where = `runners[${index}]`;
|
|
426
|
+
if (typeof config.peer !== "string" || config.peer === "") throw new Error(`${where}: peer must be a non-empty string`);
|
|
427
|
+
if (config.kind !== "cli" && config.kind !== "herdr") throw new Error(`${where}: kind must be 'cli' or 'herdr'`);
|
|
428
|
+
if (config.kind === "cli") {
|
|
429
|
+
if (typeof config.command !== "string" || config.command === "") throw new Error(`${where}: cli needs a command`);
|
|
430
|
+
if (config.args !== void 0 && (!Array.isArray(config.args) || config.args.some((arg) => typeof arg !== "string"))) {
|
|
431
|
+
throw new Error(`${where}: args must be an array of strings`);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
if (config.timeoutMs !== void 0 && (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0)) {
|
|
435
|
+
throw new Error(`${where}: timeoutMs must be a positive number`);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
var truncate = (text) => text.length > MAX_RUN_NOTE_CHARS ? `${text.slice(0, MAX_RUN_NOTE_CHARS)}\u2026 (truncated)` : text;
|
|
439
|
+
function substitute(arg, request2) {
|
|
440
|
+
const values = {
|
|
441
|
+
prompt: request2.prompt,
|
|
442
|
+
context: request2.context,
|
|
443
|
+
deliverable: request2.deliverable,
|
|
444
|
+
taskId: request2.taskId,
|
|
445
|
+
peer: request2.peer
|
|
446
|
+
};
|
|
447
|
+
return arg.replace(/\{(\w+)\}/g, (whole, key) => values[key] ?? whole);
|
|
448
|
+
}
|
|
449
|
+
function cliRunner(config) {
|
|
450
|
+
const command = config.command;
|
|
451
|
+
const args = config.args ?? [];
|
|
452
|
+
const timeout = config.timeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;
|
|
453
|
+
return {
|
|
454
|
+
name: `cli:${command}`,
|
|
455
|
+
run: (request2) => new Promise((resolve) => {
|
|
456
|
+
execFile2(
|
|
457
|
+
command,
|
|
458
|
+
args.map((arg) => substitute(arg, request2)),
|
|
459
|
+
// No shell, a bounded buffer, and a hard timeout: a hung runner must
|
|
460
|
+
// not hold the task open forever.
|
|
461
|
+
{ timeout, maxBuffer: 4 * 1024 * 1024, windowsHide: true },
|
|
462
|
+
(error, stdout, stderr) => {
|
|
463
|
+
const out = stdout.trim();
|
|
464
|
+
if (error !== null) {
|
|
465
|
+
const detail = stderr.trim() !== "" ? stderr.trim() : error.message;
|
|
466
|
+
resolve({ status: "failed", note: truncate(`runner failed: ${detail}${out !== "" ? `
|
|
467
|
+
${out}` : ""}`) });
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
resolve({ status: "done", note: truncate(out === "" ? "(runner produced no output)" : out) });
|
|
471
|
+
}
|
|
472
|
+
);
|
|
473
|
+
})
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
function herdrRunner(config, ctl) {
|
|
477
|
+
const target = config.target ?? config.peer;
|
|
478
|
+
const timeout = config.timeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;
|
|
479
|
+
return {
|
|
480
|
+
name: `herdr:${target}`,
|
|
481
|
+
run: async (request2) => {
|
|
482
|
+
try {
|
|
483
|
+
const text = [request2.prompt, request2.context].filter((part) => part !== void 0 && part !== "").join("\n\n");
|
|
484
|
+
await ctl.promptSmart(target, text, { wait: true, timeoutMs: timeout });
|
|
485
|
+
const read = await ctl.readSmart(target, { lines: 200 });
|
|
486
|
+
return { status: "done", note: truncate(read.text.trim() === "" ? "(no output read back)" : read.text) };
|
|
487
|
+
} catch (error) {
|
|
488
|
+
return { status: "failed", note: truncate(`herdr runner failed: ${error.message}`) };
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
function createRunner(config, deps = {}) {
|
|
494
|
+
if (config.kind === "cli") return cliRunner(config);
|
|
495
|
+
if (deps.herdr === void 0) throw new Error(`runner for '${config.peer}': kind 'herdr' needs herdr to be enabled`);
|
|
496
|
+
return herdrRunner(config, deps.herdr);
|
|
497
|
+
}
|
|
498
|
+
var RunnerRegistry = class {
|
|
499
|
+
runners = /* @__PURE__ */ new Map();
|
|
500
|
+
constructor(configs = [], deps = {}) {
|
|
501
|
+
configs.forEach((config, index) => {
|
|
502
|
+
validateRunnerConfig(config, index);
|
|
503
|
+
this.runners.set(config.peer, createRunner(config, deps));
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
get(peer) {
|
|
507
|
+
return this.runners.get(peer);
|
|
508
|
+
}
|
|
509
|
+
/** Peer ids that have a runner (for startup logging). */
|
|
510
|
+
peers() {
|
|
511
|
+
return [...this.runners.keys()];
|
|
512
|
+
}
|
|
513
|
+
get size() {
|
|
514
|
+
return this.runners.size;
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
|
|
420
518
|
// src/hub.ts
|
|
421
519
|
import { randomUUID } from "node:crypto";
|
|
422
520
|
|
|
@@ -424,8 +522,47 @@ import { randomUUID } from "node:crypto";
|
|
|
424
522
|
var KINDS = ["chat", "task", "notice", "ack"];
|
|
425
523
|
var PEER_ID_PATTERN = /^[A-Za-z0-9._:-]{1,64}$/;
|
|
426
524
|
var BROADCAST = "all";
|
|
525
|
+
var HUB_PEER = "hub";
|
|
526
|
+
var SSE_METHOD = "notifications/message";
|
|
527
|
+
var SSE_EVENT_PEERS_CHANGED = "peers_changed";
|
|
528
|
+
var SSE_EVENT_MESSAGE = "message";
|
|
529
|
+
var SSE_EVENT_TASK_CHANGED = "task_changed";
|
|
427
530
|
var MAX_HOP = 5;
|
|
428
|
-
var
|
|
531
|
+
var MAX_REPLY_CHAIN = 50;
|
|
532
|
+
function a2aState(status) {
|
|
533
|
+
switch (status) {
|
|
534
|
+
case "pending":
|
|
535
|
+
case "accepted":
|
|
536
|
+
return "submitted";
|
|
537
|
+
case "working":
|
|
538
|
+
return "working";
|
|
539
|
+
case "input-required":
|
|
540
|
+
return "input-required";
|
|
541
|
+
case "done":
|
|
542
|
+
return "completed";
|
|
543
|
+
case "canceled":
|
|
544
|
+
return "canceled";
|
|
545
|
+
case "failed":
|
|
546
|
+
case "timeout":
|
|
547
|
+
return "failed";
|
|
548
|
+
case "rejected":
|
|
549
|
+
return "rejected";
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
var CLIENT_ACK_STATUSES = ["accepted", "working", "input-required", "rejected", "done", "failed"];
|
|
553
|
+
var ALL_ACK_STATUSES = [...CLIENT_ACK_STATUSES, "canceled"];
|
|
554
|
+
var TERMINAL_TASK_STATUSES = ["rejected", "done", "failed", "timeout", "canceled"];
|
|
555
|
+
var ALL_TASK_STATUSES = [
|
|
556
|
+
"pending",
|
|
557
|
+
"accepted",
|
|
558
|
+
"working",
|
|
559
|
+
"input-required",
|
|
560
|
+
"rejected",
|
|
561
|
+
"done",
|
|
562
|
+
"failed",
|
|
563
|
+
"timeout",
|
|
564
|
+
"canceled"
|
|
565
|
+
];
|
|
429
566
|
function ackToTaskStatus(ack) {
|
|
430
567
|
return ack;
|
|
431
568
|
}
|
|
@@ -440,6 +577,9 @@ function nextTaskStatus(current, ack) {
|
|
|
440
577
|
case "working":
|
|
441
578
|
if (next === "accepted") return "working";
|
|
442
579
|
return next;
|
|
580
|
+
case "input-required":
|
|
581
|
+
if (next === "accepted") return "input-required";
|
|
582
|
+
return next;
|
|
443
583
|
default:
|
|
444
584
|
return null;
|
|
445
585
|
}
|
|
@@ -447,6 +587,7 @@ function nextTaskStatus(current, ack) {
|
|
|
447
587
|
function aggregateTaskStatus(assignees) {
|
|
448
588
|
if (assignees.length === 0) return "pending";
|
|
449
589
|
const statuses = assignees.map((a) => a.status);
|
|
590
|
+
if (statuses.some((s) => s === "input-required")) return "input-required";
|
|
450
591
|
const active = statuses.filter((s) => s === "pending" || s === "accepted" || s === "working");
|
|
451
592
|
if (active.length > 0) {
|
|
452
593
|
if (active.some((s) => s === "working")) return "working";
|
|
@@ -456,10 +597,14 @@ function aggregateTaskStatus(assignees) {
|
|
|
456
597
|
if (statuses.every((s) => s === "done")) return "done";
|
|
457
598
|
if (statuses.some((s) => s === "failed")) return "failed";
|
|
458
599
|
if (statuses.some((s) => s === "timeout")) return "timeout";
|
|
600
|
+
if (statuses.some((s) => s === "canceled")) return "canceled";
|
|
459
601
|
return "rejected";
|
|
460
602
|
}
|
|
603
|
+
function encodeContent(payload) {
|
|
604
|
+
return JSON.stringify(payload);
|
|
605
|
+
}
|
|
461
606
|
function decodeContent(kind, content) {
|
|
462
|
-
if (kind !== "task" && kind !== "ack") return content;
|
|
607
|
+
if (kind !== "task" && kind !== "ack" && kind !== "notice") return content;
|
|
463
608
|
try {
|
|
464
609
|
const parsed = JSON.parse(content);
|
|
465
610
|
if (parsed !== null && typeof parsed === "object") return parsed;
|
|
@@ -471,20 +616,140 @@ function decodeContent(kind, content) {
|
|
|
471
616
|
// src/hub.ts
|
|
472
617
|
var MAX_PROFILES = 512;
|
|
473
618
|
var MAX_TASKS = 1024;
|
|
619
|
+
var MAX_DEAD_LETTERS = 200;
|
|
620
|
+
var MAX_TASK_ACKS = 200;
|
|
621
|
+
var MAX_TASK_ARTIFACTS = 50;
|
|
474
622
|
var MAX_TIMER_DELAY_MS = 2147483647;
|
|
475
|
-
var
|
|
623
|
+
var DEFAULT_PARKED_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
624
|
+
var DEFAULT_LEASE_TTL_MS = 6e4;
|
|
625
|
+
var DEFAULT_MAX_ATTEMPTS = 5;
|
|
626
|
+
var MAX_EVENTS = 500;
|
|
627
|
+
var AgentHub = class _AgentHub {
|
|
476
628
|
constructor(options) {
|
|
477
629
|
this.options = options;
|
|
478
630
|
const idle = options.peerIdleTimeoutMs ?? 6e5;
|
|
631
|
+
const parkedTtl = options.parkedTtlMs ?? DEFAULT_PARKED_TTL_MS;
|
|
479
632
|
if (idle > 0) {
|
|
480
633
|
const interval = Math.min(6e4, Math.max(1e3, idle / 2));
|
|
481
634
|
this.gcTimer = setInterval(() => this.gcTick(idle), interval);
|
|
482
635
|
this.gcTimer.unref?.();
|
|
636
|
+
} else if (parkedTtl > 0) {
|
|
637
|
+
const interval = Math.min(6e4, Math.max(1e3, parkedTtl / 2));
|
|
638
|
+
this.gcTimer = setInterval(() => this.expireParkedMailboxes(Date.now()), interval);
|
|
639
|
+
this.gcTimer.unref?.();
|
|
483
640
|
}
|
|
484
641
|
}
|
|
485
642
|
queues = /* @__PURE__ */ new Map();
|
|
643
|
+
/** When each parked (peer-gone-but-kept) mailbox was parked, for the TTL sweep.
|
|
644
|
+
* A queue in this map has no registered peer; see {@link unregister}. */
|
|
645
|
+
parkedAt = /* @__PURE__ */ new Map();
|
|
646
|
+
/** Highest {@link BridgeMessage.seq} handed out so far. Restored history can
|
|
647
|
+
* raise it (see importHistory) but nothing lowers it: a client's `since` cursor
|
|
648
|
+
* has to keep meaning the same thing across a restart. */
|
|
649
|
+
seqCounter = 0;
|
|
650
|
+
/**
|
|
651
|
+
* Record one operational event.
|
|
652
|
+
*
|
|
653
|
+
* Deliberately NOT the same thing as history: history is the messages that
|
|
654
|
+
* flowed (what peers said to each other), this is what the HUB did — a peer
|
|
655
|
+
* joined, a mailbox was dropped, a task moved. History can be read per peer and
|
|
656
|
+
* is persisted; events are global, per-run, and never persisted, because they
|
|
657
|
+
* describe the life of this process.
|
|
658
|
+
*/
|
|
659
|
+
recordEvent(kind, input = {}) {
|
|
660
|
+
this.eventRing.push({
|
|
661
|
+
seq: ++this.eventSeq,
|
|
662
|
+
ts: Date.now(),
|
|
663
|
+
kind,
|
|
664
|
+
...input.peer !== void 0 ? { peer: input.peer } : {},
|
|
665
|
+
detail: input.detail ?? {}
|
|
666
|
+
});
|
|
667
|
+
while (this.eventRing.length > MAX_EVENTS) this.eventRing.shift();
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Read recorded events, oldest first.
|
|
671
|
+
*
|
|
672
|
+
* `since` is exclusive ("give me what happened after seq N"), which makes it the
|
|
673
|
+
* natural cursor: pass the `lastSeq` of the previous call. `truncated` says the
|
|
674
|
+
* requested window is no longer in the ring, so the caller knows it missed
|
|
675
|
+
* entries instead of assuming it saw everything.
|
|
676
|
+
*/
|
|
677
|
+
events(options = {}) {
|
|
678
|
+
const limit = Math.max(1, Math.min(options.limit ?? 100, MAX_EVENTS));
|
|
679
|
+
const since = options.since ?? 0;
|
|
680
|
+
const available = this.eventRing.filter((event) => event.seq > since);
|
|
681
|
+
const truncated = since > 0 && available.length > 0 && available[0].seq > since + 1;
|
|
682
|
+
return {
|
|
683
|
+
events: available.slice(-limit),
|
|
684
|
+
lastSeq: this.eventSeq,
|
|
685
|
+
truncated
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
/** The task hook, plus the event it implies.
|
|
689
|
+
*
|
|
690
|
+
* Every status change in this class already reports through
|
|
691
|
+
* `options.onTaskChanged`, so recording the event HERE needs no new call sites:
|
|
692
|
+
* the hook IS the transition signal. That is also why the event can carry the
|
|
693
|
+
* aggregate status without the caller having to say what changed — it is read
|
|
694
|
+
* from the record at the moment the transition is announced. */
|
|
695
|
+
taskChanged(record) {
|
|
696
|
+
if (record !== void 0) {
|
|
697
|
+
this.recordEvent("task_transition", {
|
|
698
|
+
peer: record.from,
|
|
699
|
+
detail: { taskId: record.id, status: record.status, assignees: record.assignees.length }
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
this.options.onTaskChanged?.(record);
|
|
703
|
+
}
|
|
704
|
+
/** Record an event from outside the hub.
|
|
705
|
+
*
|
|
706
|
+
* The runner layer lives in `index.ts` and knows when a run starts and ends,
|
|
707
|
+
* which the hub cannot see. Deliberately narrow: a caller can ADD an event but
|
|
708
|
+
* cannot read or clear the ring through this.
|
|
709
|
+
*/
|
|
710
|
+
noteEvent(kind, input = {}) {
|
|
711
|
+
this.recordEvent(kind, input);
|
|
712
|
+
}
|
|
713
|
+
/** Append one event to a task's ack timeline, keeping the timeline bounded
|
|
714
|
+
* (see {@link MAX_TASK_ACKS}). */
|
|
715
|
+
pushAckEvent(record, event) {
|
|
716
|
+
record.acks.push(event);
|
|
717
|
+
this.trimAcks(record.acks);
|
|
718
|
+
}
|
|
719
|
+
/** Append one event to one assignee's timeline, with the SAME bound
|
|
720
|
+
* ({@link MAX_TASK_ACKS}). A single assignee that keeps acking `working`
|
|
721
|
+
* grows its own timeline without limit otherwise — and `exportTasks`
|
|
722
|
+
* serializes the whole ledger on every flush. */
|
|
723
|
+
pushAssigneeAck(assignee, event) {
|
|
724
|
+
assignee.acks.push({ ...event });
|
|
725
|
+
this.trimAcks(assignee.acks);
|
|
726
|
+
}
|
|
727
|
+
/** Evict from one ack timeline until it fits {@link MAX_TASK_ACKS}.
|
|
728
|
+
*
|
|
729
|
+
* Order, oldest first within each class:
|
|
730
|
+
* 1. a `system: true` event is protected to the very end. Those rows are the
|
|
731
|
+
* DROP EVIDENCE (`noteTaskDeliveryDropped` writes `applied: false,
|
|
732
|
+
* system: true`), and a long task acking `working` 200 times would
|
|
733
|
+
* otherwise throw away "this delivery was lost" before a single chatty
|
|
734
|
+
* status update — the one thing a reader must be able to find out.
|
|
735
|
+
* 2. then an `applied: false` ack: it recorded a rejection and moved no
|
|
736
|
+
* ledger state.
|
|
737
|
+
* 3. then any non-system ack (the audited transitions a reader wants).
|
|
738
|
+
* 4. only if the timeline is STILL over the limit: a system row. */
|
|
739
|
+
trimAcks(events) {
|
|
740
|
+
while (events.length > MAX_TASK_ACKS) {
|
|
741
|
+
let victim = events.findIndex((item) => item.system !== true && item.applied !== true);
|
|
742
|
+
if (victim < 0) victim = events.findIndex((item) => item.system !== true);
|
|
743
|
+
if (victim < 0) victim = 0;
|
|
744
|
+
events.splice(victim, 1);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
486
747
|
waiters = /* @__PURE__ */ new Map();
|
|
487
748
|
historyRing = [];
|
|
749
|
+
/** Structured operational events, newest last. A ring, not a log: the hub is a
|
|
750
|
+
* long-running process and an unbounded event list is a leak. See {@link events}. */
|
|
751
|
+
eventRing = [];
|
|
752
|
+
eventSeq = 0;
|
|
488
753
|
lastSeen = /* @__PURE__ */ new Map();
|
|
489
754
|
/** Identity metadata keyed by peer id; outlives registration (see {@link PeerProfile}). */
|
|
490
755
|
profiles = /* @__PURE__ */ new Map();
|
|
@@ -507,20 +772,188 @@ var AgentHub = class {
|
|
|
507
772
|
if (now - (this.lastSeen.get(peerId) ?? 0) > idleTimeoutMs) {
|
|
508
773
|
if (this.options.isPeerLive?.(peerId) === true) continue;
|
|
509
774
|
this.options.onPeerGc?.(peerId);
|
|
510
|
-
this.unregister(peerId);
|
|
775
|
+
this.unregister(peerId, { keepMailbox: true });
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
for (const peerId of [...this.leases.keys()]) this.reapLeases(peerId, now);
|
|
779
|
+
this.expireParkedMailboxes(now);
|
|
780
|
+
}
|
|
781
|
+
/** Drop parked mailboxes older than `parkedTtlMs` (0 disables expiry). */
|
|
782
|
+
expireParkedMailboxes(now) {
|
|
783
|
+
const ttl = this.options.parkedTtlMs ?? DEFAULT_PARKED_TTL_MS;
|
|
784
|
+
if (ttl <= 0) return;
|
|
785
|
+
for (const [peerId, parkedMs] of [...this.parkedAt]) {
|
|
786
|
+
if (this.lastSeen.has(peerId)) {
|
|
787
|
+
this.parkedAt.delete(peerId);
|
|
788
|
+
continue;
|
|
789
|
+
}
|
|
790
|
+
if (now - parkedMs <= ttl) continue;
|
|
791
|
+
const dropped = this.dropMailboxState(
|
|
792
|
+
peerId,
|
|
793
|
+
(message) => this.failTaskForGoneAssignee(message.id, peerId, now, ttl)
|
|
794
|
+
).length;
|
|
795
|
+
if (dropped > 0) {
|
|
796
|
+
this.options.onMailboxesChanged?.();
|
|
797
|
+
this.recordEvent("mailbox_dropped", { peer: peerId, detail: { reason: "expired", dropped, ttlMs: ttl } });
|
|
798
|
+
this.options.onMailboxExpired?.(peerId, dropped);
|
|
511
799
|
}
|
|
512
800
|
}
|
|
513
801
|
}
|
|
802
|
+
/** Reconcile the task ledger after `peerId`'s parked mailbox was destroyed with
|
|
803
|
+
* the task still inside it.
|
|
804
|
+
*
|
|
805
|
+
* The task fails as a SYSTEM event, not as an ack: nobody acked anything, the
|
|
806
|
+
* peer simply never came back. Marking only this assignee's row keeps a
|
|
807
|
+
* broadcast task's other recipients intact, and the aggregate status is
|
|
808
|
+
* recomputed the same way every other transition does it. */
|
|
809
|
+
failTaskForGoneAssignee(taskId, peerId, now, ttl) {
|
|
810
|
+
const record = this.taskLedger.get(taskId);
|
|
811
|
+
if (record === void 0) return;
|
|
812
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) return;
|
|
813
|
+
const assignee = record.assignees.find((a) => a.peerId === peerId);
|
|
814
|
+
if (assignee === void 0 || TERMINAL_TASK_STATUSES.includes(assignee.status)) return;
|
|
815
|
+
const event = {
|
|
816
|
+
from: peerId,
|
|
817
|
+
status: "failed",
|
|
818
|
+
note: `recipient '${peerId}' never came back: its parked mailbox expired after ${ttl}ms and the task was dropped with it`,
|
|
819
|
+
ts: now,
|
|
820
|
+
messageId: syntheticEventId(taskId, "expired"),
|
|
821
|
+
applied: true,
|
|
822
|
+
system: true
|
|
823
|
+
};
|
|
824
|
+
this.pushAckEvent(record, event);
|
|
825
|
+
assignee.status = "failed";
|
|
826
|
+
this.pushAssigneeAck(assignee, event);
|
|
827
|
+
record.status = aggregateTaskStatus(record.assignees);
|
|
828
|
+
record.updatedAt = now;
|
|
829
|
+
this.realignTaskTimer(record);
|
|
830
|
+
this.taskChanged(this.taskOf(taskId));
|
|
831
|
+
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`);
|
|
832
|
+
}
|
|
833
|
+
/** Tell the SENDER of `record` that this delivery is over for good — the one
|
|
834
|
+
* thing it has to act on (re-send the task, or abandon it).
|
|
835
|
+
*
|
|
836
|
+
* Guarded by the same reachability precheck as {@link noteTaskDeliveryDropped}:
|
|
837
|
+
* a sender that has itself left the hub has nobody to warn, and `route` would
|
|
838
|
+
* throw on the drop path. Best effort by design — a terminal verdict is
|
|
839
|
+
* already in the ledger whether or not the notice can be delivered. */
|
|
840
|
+
notifyTaskEnded(record, why) {
|
|
841
|
+
if (!this.lastSeen.has(record.from) && !this.parkedAt.has(record.from)) return;
|
|
842
|
+
this.route(HUB_PEER, record.from, "notice", encodeContent({
|
|
843
|
+
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.`,
|
|
844
|
+
level: "warn"
|
|
845
|
+
}), void 0, record.threadId, void 0, true);
|
|
846
|
+
}
|
|
847
|
+
/** Reconcile the task ledger after a `task` message was dropped for `peerId`
|
|
848
|
+
* because the PEER ITSELF is gone.
|
|
849
|
+
*
|
|
850
|
+
* This is one of exactly TWO drops that write a terminal state, and both mean
|
|
851
|
+
* the same thing — the recipient can never recover the task: this one (the
|
|
852
|
+
* peer left the hub, or a manager kicked it) and
|
|
853
|
+
* {@link failTaskForGoneAssignee} (its parked mailbox expired after
|
|
854
|
+
* `parkedTtlMs`). Terminal is right there on purpose: the assignee no longer
|
|
855
|
+
* exists, so there is no path back — no revival, no later ack — and a
|
|
856
|
+
* `pending` row would leave the sender waiting forever. Every other drop
|
|
857
|
+
* reason (`expired`, `rate`, `overflow`, dead-letter) stays NON-terminal
|
|
858
|
+
* instead (see {@link noteTaskDeliveryDropped}), because:
|
|
859
|
+
* - a dead letter can be revived with `bridge_nack`, and a task already
|
|
860
|
+
* marked `failed` would then refuse the revived assignee's `done`
|
|
861
|
+
* (`nextTaskStatus('failed', 'done')` is null → `applied: false`), so the
|
|
862
|
+
* sender would see a failure the hub itself declared unfixable;
|
|
863
|
+
* - `overflow` and `rate` are driven by THIRD-PARTY traffic — any peer
|
|
864
|
+
* sending ~maxQueue messages can push a task out of someone else's mailbox
|
|
865
|
+
* — so a terminal write there is a veto any peer can exercise over a task
|
|
866
|
+
* it was never assigned.
|
|
867
|
+
*
|
|
868
|
+
* Like the parked-mail reconcile, the failure is a SYSTEM event (nobody acked
|
|
869
|
+
* anything), only this assignee's row is marked — a fan-out task's other
|
|
870
|
+
* recipients keep their state — and the aggregate is recomputed the way every
|
|
871
|
+
* other transition does it. `reason` is the drop kind the caller counted, so
|
|
872
|
+
* the note and the `mailbox_dropped` event can be read together. */
|
|
873
|
+
failTaskForDroppedMessage(message, peerId, reason, now) {
|
|
874
|
+
const record = this.taskLedger.get(message.id);
|
|
875
|
+
if (record === void 0) return;
|
|
876
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) return;
|
|
877
|
+
const assignee = record.assignees.find((a) => a.peerId === peerId);
|
|
878
|
+
if (assignee === void 0 || TERMINAL_TASK_STATUSES.includes(assignee.status)) return;
|
|
879
|
+
const event = {
|
|
880
|
+
from: peerId,
|
|
881
|
+
status: "failed",
|
|
882
|
+
note: `message dropped for '${peerId}' (${reason}): the task will never be handed to it and cannot be acked`,
|
|
883
|
+
ts: now,
|
|
884
|
+
messageId: syntheticEventId(record.id, reason),
|
|
885
|
+
applied: true,
|
|
886
|
+
system: true
|
|
887
|
+
};
|
|
888
|
+
this.pushAckEvent(record, event);
|
|
889
|
+
assignee.status = "failed";
|
|
890
|
+
delete assignee.deliveredMs;
|
|
891
|
+
this.pushAssigneeAck(assignee, event);
|
|
892
|
+
record.status = aggregateTaskStatus(record.assignees);
|
|
893
|
+
record.updatedAt = now;
|
|
894
|
+
this.realignTaskTimer(record);
|
|
895
|
+
this.taskChanged(this.taskOf(record.id));
|
|
896
|
+
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`);
|
|
897
|
+
}
|
|
898
|
+
/** Record that one delivery of a task was dropped, WITHOUT closing the task.
|
|
899
|
+
*
|
|
900
|
+
* Two things happen and nothing else (`expired` / `rate` / `overflow` /
|
|
901
|
+
* dead-letter drops all land here; `unregister` keeps the terminal reconcile
|
|
902
|
+
* above):
|
|
903
|
+
* 1. the ledger gets a `system: true, applied: false` event naming the drop —
|
|
904
|
+
* `applied: false` is the whole point, it says "recorded, state untouched";
|
|
905
|
+
* 2. the task's SENDER gets a `notice` from the hub: it is the only party
|
|
906
|
+
* that can react (re-send, or revive a dead letter with `bridge_nack`).
|
|
907
|
+
* ONE notice per task, not per dropped copy — see `dropNotified`.
|
|
908
|
+
*
|
|
909
|
+
* See {@link failTaskForDroppedMessage} for why a terminal write here would
|
|
910
|
+
* be wrong. */
|
|
911
|
+
noteTaskDeliveryDropped(message, peerId, reason, now) {
|
|
912
|
+
const record = this.taskLedger.get(message.id);
|
|
913
|
+
if (record === void 0) return;
|
|
914
|
+
this.pushAckEvent(record, {
|
|
915
|
+
from: peerId,
|
|
916
|
+
status: "failed",
|
|
917
|
+
note: `a delivery of this task to '${peerId}' was dropped (${reason}); the task itself is unchanged and still waiting`,
|
|
918
|
+
ts: now,
|
|
919
|
+
messageId: syntheticEventId(record.id, reason),
|
|
920
|
+
applied: false,
|
|
921
|
+
system: true
|
|
922
|
+
});
|
|
923
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) return;
|
|
924
|
+
if (record.dropNotified !== void 0) return;
|
|
925
|
+
if (!this.lastSeen.has(record.from) && !this.parkedAt.has(record.from)) return;
|
|
926
|
+
record.dropNotified = now;
|
|
927
|
+
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";
|
|
928
|
+
this.route(HUB_PEER, record.from, "notice", encodeContent({
|
|
929
|
+
message: `task ${record.id}: a delivery of it to '${peerId}' was dropped (${reason}). The task is still open${hint}.`,
|
|
930
|
+
level: "warn"
|
|
931
|
+
}), void 0, record.threadId, void 0, true);
|
|
932
|
+
}
|
|
514
933
|
/** All registered peer ids, insertion order. */
|
|
515
934
|
peers() {
|
|
516
935
|
return [...this.lastSeen.keys()];
|
|
517
936
|
}
|
|
518
937
|
/** Register a peer; throws if the id is already taken. Client metadata
|
|
519
938
|
* (when provided) refreshes the profile — with same-name sessions sharing a
|
|
520
|
-
* peer, the freshest connect wins, which self-heals stale metadata.
|
|
521
|
-
|
|
939
|
+
* peer, the freshest connect wins, which self-heals stale metadata.
|
|
940
|
+
*
|
|
941
|
+
* `reclaim` is the caller asserting "this id is my own identity coming back":
|
|
942
|
+
* a parked peer still owns its mailbox, and only the identity may unwrap it
|
|
943
|
+
* into use again (see {@link ownsMailbox}). Every caller has to say so
|
|
944
|
+
* explicitly, so a new path cannot inherit someone else's mail by accident. */
|
|
945
|
+
register(peerId, client, options) {
|
|
946
|
+
if (peerId === BROADCAST) throw new Error(`reserved peer id: ${peerId} (it is the broadcast address)`);
|
|
947
|
+
if (peerId === HUB_PEER) throw new Error(`reserved peer id: ${peerId} (the hub uses it for its own notices)`);
|
|
948
|
+
if (this.groups.has(peerId)) {
|
|
949
|
+
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`);
|
|
950
|
+
}
|
|
522
951
|
if (this.lastSeen.has(peerId)) throw new Error(`peer already registered: ${peerId}`);
|
|
952
|
+
if (!(options?.reclaim === true) && this.ownsMailbox(peerId)) {
|
|
953
|
+
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 })`);
|
|
954
|
+
}
|
|
523
955
|
this.lastSeen.set(peerId, Date.now());
|
|
956
|
+
this.parkedAt.delete(peerId);
|
|
524
957
|
const existing = this.profiles.get(peerId);
|
|
525
958
|
this.profiles.set(peerId, {
|
|
526
959
|
...existing,
|
|
@@ -530,13 +963,28 @@ var AgentHub = class {
|
|
|
530
963
|
...client?.version !== void 0 ? { clientVersion: client.version } : existing?.clientVersion !== void 0 ? { clientVersion: existing.clientVersion } : {}
|
|
531
964
|
});
|
|
532
965
|
this.evictOverflowProfiles();
|
|
966
|
+
this.recordEvent("peer_joined", { peer: peerId, detail: { clientName: client?.name } });
|
|
533
967
|
this.options.onPeersChanged?.(this.peers());
|
|
534
968
|
}
|
|
535
|
-
/** Remove a peer
|
|
536
|
-
*
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
969
|
+
/** Remove a peer; pending waiters resolve as timeouts. The profile is kept so
|
|
970
|
+
* a reconnecting peer keeps its alias.
|
|
971
|
+
*
|
|
972
|
+
* `keepMailbox` is what the idle GC passes: the peer's queued messages stay in
|
|
973
|
+
* `queues` (marked parked) so a returning agent drains what was sent while it
|
|
974
|
+
* was away. An explicit `bridge_unregister` and a manager kick leave it off,
|
|
975
|
+
* i.e. they still drop the mail — leaving the hub is a deliberate act. */
|
|
976
|
+
unregister(peerId, options) {
|
|
977
|
+
const queue = this.queues.get(peerId) ?? [];
|
|
978
|
+
const keep = options?.keepMailbox === true;
|
|
979
|
+
if (queue.length > 0) this.options.onMailboxesChanged?.();
|
|
980
|
+
if (keep) {
|
|
981
|
+
this.parkedAt.set(peerId, Date.now());
|
|
982
|
+
this.recordEvent("peer_parked", { peer: peerId, detail: { queued: queue.length } });
|
|
983
|
+
} else {
|
|
984
|
+
this.recordEvent("peer_left", { peer: peerId, detail: { queued: queue.length } });
|
|
985
|
+
const now = Date.now();
|
|
986
|
+
this.dropMailboxState(peerId, (message) => this.failTaskForDroppedMessage(message, peerId, "unregistered", now));
|
|
987
|
+
}
|
|
540
988
|
for (const waiter of this.waiters.get(peerId) ?? []) {
|
|
541
989
|
clearTimeout(waiter.timer);
|
|
542
990
|
waiter.onAbort();
|
|
@@ -545,6 +993,35 @@ var AgentHub = class {
|
|
|
545
993
|
this.lastSeen.delete(peerId);
|
|
546
994
|
this.options.onPeersChanged?.(this.peers());
|
|
547
995
|
}
|
|
996
|
+
/** Forget EVERYTHING a mailbox owns — queue, in-flight leases, dead letters
|
|
997
|
+
* and the per-message attempt counters — in one step, calling `reconcile` on
|
|
998
|
+
* the tasks found in any of them.
|
|
999
|
+
*
|
|
1000
|
+
* The pieces have to go together. Anything left behind does not just leak: a
|
|
1001
|
+
* lease that outlives its mailbox is re-queued by the next reap under a peer
|
|
1002
|
+
* that has neither a registration nor a `parkedAt`, so no take and no TTL
|
|
1003
|
+
* sweep ever sees it and the message (and its task) stays pending forever.
|
|
1004
|
+
* Both callers — an explicit `unregister` (the peer left) and
|
|
1005
|
+
* `expireParkedMailboxes` (the parked TTL ran out) — mean the same thing
|
|
1006
|
+
* here, and only the ledger verdict differs, which is why that is the
|
|
1007
|
+
* parameter. Returns every message that went with the mailbox. */
|
|
1008
|
+
dropMailboxState(peerId, reconcile) {
|
|
1009
|
+
const queue = this.queues.get(peerId) ?? [];
|
|
1010
|
+
const inFlight = (this.leases.get(peerId) ?? []).map((lease) => lease.message);
|
|
1011
|
+
const deadLettered = this.deadLetters.get(peerId) ?? [];
|
|
1012
|
+
this.leases.delete(peerId);
|
|
1013
|
+
this.deadLetters.delete(peerId);
|
|
1014
|
+
for (const key of [...this.leaseAttempts.keys()]) {
|
|
1015
|
+
if (key.startsWith(`${peerId}\0`)) this.leaseAttempts.delete(key);
|
|
1016
|
+
}
|
|
1017
|
+
this.queues.delete(peerId);
|
|
1018
|
+
this.parkedAt.delete(peerId);
|
|
1019
|
+
const all = [...queue, ...inFlight, ...deadLettered];
|
|
1020
|
+
for (const message of all) {
|
|
1021
|
+
if (message.kind === "task") reconcile(message);
|
|
1022
|
+
}
|
|
1023
|
+
return all;
|
|
1024
|
+
}
|
|
548
1025
|
/** Identity metadata for `peerId`, if the hub ever saw it. */
|
|
549
1026
|
profileOf(peerId) {
|
|
550
1027
|
return this.profiles.get(peerId);
|
|
@@ -553,6 +1030,44 @@ var AgentHub = class {
|
|
|
553
1030
|
exportProfiles() {
|
|
554
1031
|
return [...this.profiles.values()].map((profile) => ({ ...profile }));
|
|
555
1032
|
}
|
|
1033
|
+
/** Record what a peer says about itself. Creates the profile if the peer is
|
|
1034
|
+
* new: a card is identity, and identity outlives a connection. */
|
|
1035
|
+
announceCard(peerId, card) {
|
|
1036
|
+
const existing = this.profiles.get(peerId);
|
|
1037
|
+
const profile = { ...existing, id: peerId, registeredAt: existing?.registeredAt ?? Date.now(), card };
|
|
1038
|
+
this.profiles.set(peerId, profile);
|
|
1039
|
+
this.evictOverflowProfiles();
|
|
1040
|
+
this.options.onPeersChanged?.(this.peers());
|
|
1041
|
+
return profile;
|
|
1042
|
+
}
|
|
1043
|
+
/** Every peer whose announced card matches `filter`, with the load a caller
|
|
1044
|
+
* needs to pick one.
|
|
1045
|
+
*
|
|
1046
|
+
* `acceptsTasks` defaults to TRUE — and that default is the point: discover is
|
|
1047
|
+
* for finding somebody to HAND WORK TO, and "has a skill" is not "wants a
|
|
1048
|
+
* task". Pass `false` to drop the requirement and list peers regardless. */
|
|
1049
|
+
discover(filter = {}) {
|
|
1050
|
+
const requireAccept = filter.acceptsTasks !== false;
|
|
1051
|
+
const out = [];
|
|
1052
|
+
for (const profile of this.profiles.values()) {
|
|
1053
|
+
const card = profile.card;
|
|
1054
|
+
if (card === void 0) continue;
|
|
1055
|
+
if (requireAccept && card.acceptsTasks !== true) continue;
|
|
1056
|
+
const skills = card.skills ?? [];
|
|
1057
|
+
if (filter.skill !== void 0 && !skills.some((skill) => skill.id === filter.skill)) continue;
|
|
1058
|
+
if (filter.tag !== void 0 && !skills.some((skill) => (skill.tags ?? []).includes(filter.tag))) continue;
|
|
1059
|
+
const load = {
|
|
1060
|
+
queued: this.queues.get(profile.id)?.length ?? 0,
|
|
1061
|
+
waiting: this.waiters.get(profile.id)?.length ?? 0,
|
|
1062
|
+
running: [...this.taskLedger.values()].filter(
|
|
1063
|
+
(record) => !TERMINAL_TASK_STATUSES.includes(record.status) && record.assignees.some((a) => a.peerId === profile.id)
|
|
1064
|
+
).length
|
|
1065
|
+
};
|
|
1066
|
+
if (filter.idleOnly === true && (load.queued > 0 || load.waiting > 0 || load.running > 0)) continue;
|
|
1067
|
+
out.push({ peerId: profile.id, ...profile.alias !== void 0 ? { alias: profile.alias } : {}, card, load });
|
|
1068
|
+
}
|
|
1069
|
+
return out;
|
|
1070
|
+
}
|
|
556
1071
|
/** Load persisted profiles at boot. Invalid entries are dropped; `null`-ish
|
|
557
1072
|
* and non-finite fields are sanitized. Returns the imported count. Silent
|
|
558
1073
|
* for roster observers — this runs before the server accepts requests. */
|
|
@@ -563,7 +1078,7 @@ var AgentHub = class {
|
|
|
563
1078
|
if (typeof raw !== "object" || raw === null) continue;
|
|
564
1079
|
const candidate = raw;
|
|
565
1080
|
const id = candidate.id;
|
|
566
|
-
if (typeof id !== "string" || !PEER_ID_PATTERN.test(id) || id === BROADCAST) continue;
|
|
1081
|
+
if (typeof id !== "string" || !PEER_ID_PATTERN.test(id) || id === BROADCAST || id === HUB_PEER) continue;
|
|
567
1082
|
if (this.profiles.has(id)) continue;
|
|
568
1083
|
const profile = {
|
|
569
1084
|
id,
|
|
@@ -572,6 +1087,7 @@ var AgentHub = class {
|
|
|
572
1087
|
if (typeof candidate.alias === "string" && candidate.alias !== "") profile.alias = candidate.alias;
|
|
573
1088
|
if (typeof candidate.clientName === "string" && candidate.clientName !== "") profile.clientName = candidate.clientName;
|
|
574
1089
|
if (typeof candidate.clientVersion === "string" && candidate.clientVersion !== "") profile.clientVersion = candidate.clientVersion;
|
|
1090
|
+
if (candidate.card !== null && typeof candidate.card === "object") profile.card = candidate.card;
|
|
575
1091
|
this.profiles.set(id, profile);
|
|
576
1092
|
count++;
|
|
577
1093
|
}
|
|
@@ -599,19 +1115,41 @@ var AgentHub = class {
|
|
|
599
1115
|
if (oldId === newId) return;
|
|
600
1116
|
if (!this.lastSeen.has(oldId)) throw new Error(`unknown peer: ${oldId}`);
|
|
601
1117
|
if (newId === BROADCAST) throw new Error(`reserved peer id: ${newId}`);
|
|
1118
|
+
if (newId === HUB_PEER) throw new Error(`reserved peer id: ${newId}`);
|
|
602
1119
|
if (!PEER_ID_PATTERN.test(newId)) throw new Error(`invalid peerId: ${newId} (expected [A-Za-z0-9._:-]{1,64})`);
|
|
603
1120
|
if (this.lastSeen.has(newId)) throw new Error(`peer already registered: ${newId}`);
|
|
1121
|
+
if (this.groups.has(newId)) {
|
|
1122
|
+
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`);
|
|
1123
|
+
}
|
|
1124
|
+
if (this.ownsMailbox(newId)) {
|
|
1125
|
+
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 })`);
|
|
1126
|
+
}
|
|
604
1127
|
const queue = this.queues.get(oldId);
|
|
605
1128
|
const waiters = this.waiters.get(oldId);
|
|
606
1129
|
const seen = this.lastSeen.get(oldId) ?? Date.now();
|
|
607
1130
|
const profile = this.profiles.get(oldId);
|
|
608
1131
|
const stale = this.profiles.get(newId);
|
|
1132
|
+
this.parkedAt.delete(oldId);
|
|
1133
|
+
this.parkedAt.delete(newId);
|
|
609
1134
|
this.queues.delete(oldId);
|
|
610
1135
|
this.waiters.delete(oldId);
|
|
611
1136
|
this.lastSeen.delete(oldId);
|
|
612
1137
|
this.profiles.delete(oldId);
|
|
613
1138
|
if (queue !== void 0) this.queues.set(newId, queue);
|
|
614
1139
|
if (waiters !== void 0) this.waiters.set(newId, waiters);
|
|
1140
|
+
const leases = this.leases.get(oldId);
|
|
1141
|
+
const deadLetters = this.deadLetters.get(oldId);
|
|
1142
|
+
this.leases.delete(oldId);
|
|
1143
|
+
this.deadLetters.delete(oldId);
|
|
1144
|
+
if (leases !== void 0) this.leases.set(newId, leases);
|
|
1145
|
+
if (deadLetters !== void 0) this.deadLetters.set(newId, deadLetters);
|
|
1146
|
+
const oldLeasePrefix = _AgentHub.leaseKey(oldId, "");
|
|
1147
|
+
for (const key of [...this.leaseAttempts.keys()]) {
|
|
1148
|
+
if (!key.startsWith(oldLeasePrefix)) continue;
|
|
1149
|
+
const attempts = this.leaseAttempts.get(key);
|
|
1150
|
+
this.leaseAttempts.delete(key);
|
|
1151
|
+
if (attempts !== void 0) this.leaseAttempts.set(_AgentHub.leaseKey(newId, key.slice(oldLeasePrefix.length)), attempts);
|
|
1152
|
+
}
|
|
615
1153
|
this.lastSeen.set(newId, seen);
|
|
616
1154
|
if (profile !== void 0) {
|
|
617
1155
|
const merged = {
|
|
@@ -635,8 +1173,71 @@ var AgentHub = class {
|
|
|
635
1173
|
if (message.from === oldId) message.from = newId;
|
|
636
1174
|
if (message.to === oldId) message.to = newId;
|
|
637
1175
|
}
|
|
1176
|
+
for (const record of this.taskLedger.values()) {
|
|
1177
|
+
if (record.from === oldId) record.from = newId;
|
|
1178
|
+
if (record.to === oldId && !this.groups.has(oldId)) record.to = newId;
|
|
1179
|
+
for (const event of record.acks) if (event.from === oldId) event.from = newId;
|
|
1180
|
+
for (const assignee of record.assignees) {
|
|
1181
|
+
if (assignee.peerId === oldId) assignee.peerId = newId;
|
|
1182
|
+
for (const event of assignee.acks) if (event.from === oldId) event.from = newId;
|
|
1183
|
+
}
|
|
1184
|
+
this.foldDuplicateAssignees(record);
|
|
1185
|
+
}
|
|
1186
|
+
let groupsChanged = false;
|
|
1187
|
+
for (const group of this.groups.values()) {
|
|
1188
|
+
if (!group.members.includes(oldId)) continue;
|
|
1189
|
+
group.members = [...new Set(group.members.map((member) => member === oldId ? newId : member))];
|
|
1190
|
+
groupsChanged = true;
|
|
1191
|
+
}
|
|
1192
|
+
if (groupsChanged) this.options.onGroupsChanged?.();
|
|
638
1193
|
this.options.onPeersChanged?.(this.peers());
|
|
639
1194
|
}
|
|
1195
|
+
/** Collapse assignee rows that ended up sharing a `peerId` (a rename onto an
|
|
1196
|
+
* id the task already had a row for).
|
|
1197
|
+
*
|
|
1198
|
+
* Duplicate rows break the ledger: `applyAckToLedger` finds the FIRST row for
|
|
1199
|
+
* the acking peer, so the second one never advances and the aggregate can sit
|
|
1200
|
+
* on a status no row supports. The merge prefers the row that is still open
|
|
1201
|
+
* (a rename must not close a task), keeps both timelines, and keeps the
|
|
1202
|
+
* EARLIEST delivery booking. */
|
|
1203
|
+
foldDuplicateAssignees(record) {
|
|
1204
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1205
|
+
let duplicated = false;
|
|
1206
|
+
for (const assignee of record.assignees) {
|
|
1207
|
+
if (seen.has(assignee.peerId)) {
|
|
1208
|
+
duplicated = true;
|
|
1209
|
+
break;
|
|
1210
|
+
}
|
|
1211
|
+
seen.add(assignee.peerId);
|
|
1212
|
+
}
|
|
1213
|
+
if (!duplicated) return;
|
|
1214
|
+
const wasTerminal = TERMINAL_TASK_STATUSES.includes(record.status);
|
|
1215
|
+
const byPeer = /* @__PURE__ */ new Map();
|
|
1216
|
+
const folded = [];
|
|
1217
|
+
for (const assignee of record.assignees) {
|
|
1218
|
+
const first = byPeer.get(assignee.peerId);
|
|
1219
|
+
if (first === void 0) {
|
|
1220
|
+
const copy = { ...assignee, acks: [...assignee.acks] };
|
|
1221
|
+
byPeer.set(assignee.peerId, copy);
|
|
1222
|
+
folded.push(copy);
|
|
1223
|
+
continue;
|
|
1224
|
+
}
|
|
1225
|
+
const firstOpen = !TERMINAL_TASK_STATUSES.includes(first.status);
|
|
1226
|
+
if (!(firstOpen && TERMINAL_TASK_STATUSES.includes(assignee.status))) {
|
|
1227
|
+
first.status = assignee.status;
|
|
1228
|
+
}
|
|
1229
|
+
first.acks.push(...assignee.acks);
|
|
1230
|
+
this.trimAcks(first.acks);
|
|
1231
|
+
if (assignee.deliveredMs !== void 0 && (first.deliveredMs === void 0 || assignee.deliveredMs < first.deliveredMs)) {
|
|
1232
|
+
first.deliveredMs = assignee.deliveredMs;
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
record.assignees = folded;
|
|
1236
|
+
record.status = aggregateTaskStatus(folded);
|
|
1237
|
+
if (wasTerminal && record.deadlineAt !== void 0 && !TERMINAL_TASK_STATUSES.includes(record.status)) {
|
|
1238
|
+
this.scheduleTaskTimeout(record);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
640
1241
|
/** Keep the profile map bounded: drop the oldest profiles of peers that are
|
|
641
1242
|
* NOT currently registered (live peers are never evicted). */
|
|
642
1243
|
evictOverflowProfiles() {
|
|
@@ -657,6 +1258,20 @@ var AgentHub = class {
|
|
|
657
1258
|
has(peerId) {
|
|
658
1259
|
return this.lastSeen.has(peerId);
|
|
659
1260
|
}
|
|
1261
|
+
/** Does `peerId` still own state it never released — a parked record or a
|
|
1262
|
+
* queued mailbox? This is identity, not liveness: `has()` is false for such a
|
|
1263
|
+
* peer, yet the id is still taken. `register({ reclaim })` and `renamePeer`
|
|
1264
|
+
* both key off this, so "taken" cannot drift between the two write points. */
|
|
1265
|
+
ownsMailbox(peerId) {
|
|
1266
|
+
return this.parkedAt.has(peerId) || this.queues.has(peerId);
|
|
1267
|
+
}
|
|
1268
|
+
/** Is the peer parked — gone from the live registry through idle GC, but still
|
|
1269
|
+
* holding its mailbox and still addressable? `has()` is false for it, so a
|
|
1270
|
+
* guard written only as `has()` will decide there is nothing to do and leave
|
|
1271
|
+
* the peer reachable. A manager kick has to cover this state explicitly. */
|
|
1272
|
+
isParked(peerId) {
|
|
1273
|
+
return this.parkedAt.has(peerId);
|
|
1274
|
+
}
|
|
660
1275
|
/** Is the peer "active" (tool/activity within the connected window)? */
|
|
661
1276
|
isActive(peerId) {
|
|
662
1277
|
const last = this.lastSeen.get(peerId);
|
|
@@ -664,38 +1279,159 @@ var AgentHub = class {
|
|
|
664
1279
|
}
|
|
665
1280
|
/** Send a chat/notice text message to `to` (or {@link BROADCAST}). */
|
|
666
1281
|
send(from, to, kind, content, opts) {
|
|
667
|
-
return this.route(from, to, kind, content, opts?.ref, opts?.threadId);
|
|
1282
|
+
return this.route(from, to, kind, content, opts?.ref, opts?.threadId, opts?.expiresAt, false, opts?.priority);
|
|
668
1283
|
}
|
|
669
1284
|
/** Send a structured task message to `to` (peer, {@link BROADCAST}, or a
|
|
670
1285
|
* group id). Records a ledger entry so the sender can later query status /
|
|
671
|
-
* wait for acks.
|
|
672
|
-
|
|
1286
|
+
* wait for acks.
|
|
1287
|
+
*
|
|
1288
|
+
* `ref` marks the task this one answers. When the parent is itself a task the
|
|
1289
|
+
* new one is a **re-delegation**, and that chain is capped at {@link MAX_HOP}
|
|
1290
|
+
* — without a way to express the parent, the cap would be unreachable and a
|
|
1291
|
+
* hand-off loop unobservable. */
|
|
1292
|
+
sendTask(from, to, task, ref, expiresAt) {
|
|
673
1293
|
const threadId = task.threadId;
|
|
674
|
-
const message = this.compose(from, to, "task", JSON.stringify(task),
|
|
1294
|
+
const message = this.compose(from, to, "task", JSON.stringify(task), ref, threadId, expiresAt, false, task.priority);
|
|
675
1295
|
this.recordTask(message, task);
|
|
676
1296
|
this.dispatch(message);
|
|
677
1297
|
return message;
|
|
678
1298
|
}
|
|
679
1299
|
/** Send an acknowledgement back to the sender of `ref`. Updates the task
|
|
680
1300
|
* ledger when `ref` is a known task (looked up in the ledger first, so acks
|
|
681
|
-
* survive history-ring eviction); chat/notice refs still route via history.
|
|
1301
|
+
* survive history-ring eviction); chat/notice refs still route via history.
|
|
1302
|
+
*
|
|
1303
|
+
* Only an ASSIGNEE may ack a task. Everyone else could otherwise close someone
|
|
1304
|
+
* else's task — and land their own artifacts in it — just by learning the
|
|
1305
|
+
* message id. A ref that is not a task carries no ledger row to protect, so an
|
|
1306
|
+
* ack for chat/notice keeps routing without any permission check. The single
|
|
1307
|
+
* place this is decided is here: `bridge_ack` adds no rule of its own, so the
|
|
1308
|
+
* direct API (`ackForRunner`, an assignee by construction) is unaffected. */
|
|
682
1309
|
sendAck(from, ref, ack) {
|
|
683
1310
|
const task = this.taskLedger.get(ref);
|
|
684
1311
|
let target;
|
|
1312
|
+
let threadId;
|
|
685
1313
|
if (task !== void 0) {
|
|
1314
|
+
if (!task.assignees.some((assignee) => assignee.peerId === from)) {
|
|
1315
|
+
throw new Error("only an assignee of this task can ack it");
|
|
1316
|
+
}
|
|
686
1317
|
target = task.from;
|
|
1318
|
+
threadId = task.threadId;
|
|
687
1319
|
} else {
|
|
688
1320
|
const original = this.historyRing.findLast((message2) => message2.id === ref);
|
|
689
1321
|
if (!original) throw new Error(`cannot ack unknown message: ${ref}`);
|
|
690
1322
|
target = original.from;
|
|
1323
|
+
threadId = original.threadId;
|
|
691
1324
|
}
|
|
692
|
-
const message = this.route(from, target, "ack", JSON.stringify(ack), ref);
|
|
1325
|
+
const message = this.route(from, target, "ack", JSON.stringify(ack), ref, threadId);
|
|
693
1326
|
this.applyAckToLedger(message, from, ref, ack);
|
|
694
1327
|
return message;
|
|
695
1328
|
}
|
|
1329
|
+
/** Record an ack the hub produced ON BEHALF of a peer whose runner finished
|
|
1330
|
+
* its task (see `src/runner.ts`).
|
|
1331
|
+
*
|
|
1332
|
+
* Unlike {@link sendAck} the sender is not a live session — it may be parked,
|
|
1333
|
+
* or not connected at all — so the "sender must be registered" check does not
|
|
1334
|
+
* apply. This is the hub acting for a peer it is executing for, never a
|
|
1335
|
+
* caller-supplied identity; nothing from a request reaches `from` here.
|
|
1336
|
+
* Everything else (ledger update, routing to the task's sender) is identical. */
|
|
1337
|
+
ackForRunner(peer, ref, ack) {
|
|
1338
|
+
const task = this.taskLedger.get(ref);
|
|
1339
|
+
if (task === void 0) throw new Error(`runner cannot ack unknown task: ${ref}`);
|
|
1340
|
+
const message = this.route(peer, task.from, "ack", JSON.stringify(ack), ref, void 0, void 0, true);
|
|
1341
|
+
this.applyAckToLedger(message, peer, ref, ack);
|
|
1342
|
+
return message;
|
|
1343
|
+
}
|
|
1344
|
+
/** Cancel a task. EITHER side may do it — the sender stops work it no longer
|
|
1345
|
+
* wants, an assignee reports it will not finish — and the cancel is both
|
|
1346
|
+
* recorded on the ledger and routed to the OTHER side, so whoever did not
|
|
1347
|
+
* press the button finds out. Cancelling an already-terminal task is an error
|
|
1348
|
+
* rather than a silent no-op: the caller asked for something that did not
|
|
1349
|
+
* happen. */
|
|
1350
|
+
cancelTask(from, ref, reason) {
|
|
1351
|
+
const record = this.taskLedger.get(ref);
|
|
1352
|
+
if (record === void 0) throw new Error(`cannot cancel unknown task: ${ref}`);
|
|
1353
|
+
const isSender = from === record.from;
|
|
1354
|
+
if (!isSender && !record.assignees.some((a) => a.peerId === from)) {
|
|
1355
|
+
throw new Error(`only the sender or an assignee can cancel task ${ref}`);
|
|
1356
|
+
}
|
|
1357
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) {
|
|
1358
|
+
throw new Error(`task ${ref} is already ${record.status}`);
|
|
1359
|
+
}
|
|
1360
|
+
const ack = { status: "canceled", ...reason !== void 0 ? { note: reason } : {} };
|
|
1361
|
+
if (!isSender) {
|
|
1362
|
+
return this.sendAck(from, ref, ack);
|
|
1363
|
+
}
|
|
1364
|
+
let last;
|
|
1365
|
+
for (const assignee of record.assignees) {
|
|
1366
|
+
if (TERMINAL_TASK_STATUSES.includes(assignee.status)) continue;
|
|
1367
|
+
const message = this.route(from, assignee.peerId, "ack", JSON.stringify(ack), ref, record.threadId);
|
|
1368
|
+
const event = {
|
|
1369
|
+
from,
|
|
1370
|
+
status: "canceled",
|
|
1371
|
+
...reason !== void 0 ? { note: reason } : {},
|
|
1372
|
+
ts: message.ts,
|
|
1373
|
+
messageId: message.id,
|
|
1374
|
+
applied: true
|
|
1375
|
+
};
|
|
1376
|
+
this.pushAckEvent(record, event);
|
|
1377
|
+
assignee.status = "canceled";
|
|
1378
|
+
this.pushAssigneeAck(assignee, event);
|
|
1379
|
+
last = message;
|
|
1380
|
+
}
|
|
1381
|
+
if (last === void 0) throw new Error(`task ${ref} has no assignee left to cancel`);
|
|
1382
|
+
record.status = aggregateTaskStatus(record.assignees);
|
|
1383
|
+
record.updatedAt = last.ts;
|
|
1384
|
+
this.taskChanged(this.taskOf(ref));
|
|
1385
|
+
return last;
|
|
1386
|
+
}
|
|
1387
|
+
/** Answer an `input-required` interrupt. Only the task's SENDER can answer — it
|
|
1388
|
+
* is the side the assignee asked. The answer is delivered to the waiting
|
|
1389
|
+
* assignee as an `ack` carrying the task id, so a `bridge_wait { ref }` picks
|
|
1390
|
+
* it up, and the task resumes (`working`). */
|
|
1391
|
+
taskInput(from, ref, input) {
|
|
1392
|
+
const record = this.taskLedger.get(ref);
|
|
1393
|
+
if (record === void 0) throw new Error(`cannot answer unknown task: ${ref}`);
|
|
1394
|
+
if (from !== record.from) {
|
|
1395
|
+
throw new Error(`only the sender of task ${ref} can answer it (an assignee resumes by acking 'working')`);
|
|
1396
|
+
}
|
|
1397
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) {
|
|
1398
|
+
throw new Error(`task ${ref} is already ${record.status}`);
|
|
1399
|
+
}
|
|
1400
|
+
const waiting = record.assignees.filter((a) => a.status === "input-required");
|
|
1401
|
+
const targets = waiting.length > 0 ? waiting : record.assignees;
|
|
1402
|
+
const ack = { status: "working", note: input };
|
|
1403
|
+
let last;
|
|
1404
|
+
for (const assignee of targets) {
|
|
1405
|
+
const message = this.route(from, assignee.peerId, "ack", JSON.stringify(ack), ref, record.threadId);
|
|
1406
|
+
const event = { from, status: "working", note: input, ts: message.ts, messageId: message.id, applied: true };
|
|
1407
|
+
this.pushAckEvent(record, event);
|
|
1408
|
+
if (assignee.status === "input-required") {
|
|
1409
|
+
assignee.status = "working";
|
|
1410
|
+
this.pushAssigneeAck(assignee, event);
|
|
1411
|
+
}
|
|
1412
|
+
last = message;
|
|
1413
|
+
}
|
|
1414
|
+
if (last === void 0) throw new Error(`task ${ref} has no assignee to answer`);
|
|
1415
|
+
record.status = aggregateTaskStatus(record.assignees);
|
|
1416
|
+
record.updatedAt = last.ts;
|
|
1417
|
+
this.taskChanged(this.taskOf(ref));
|
|
1418
|
+
return last;
|
|
1419
|
+
}
|
|
1420
|
+
/** Every peer a fan-out can reach: the live registry **plus** parked peers.
|
|
1421
|
+
*
|
|
1422
|
+
* Parked peers keep their mailbox and stay addressable (that is the point of
|
|
1423
|
+
* parking, see {@link isParked}), and a group send already delivered to its
|
|
1424
|
+
* parked members because it reads the member list rather than the live roster.
|
|
1425
|
+
* Broadcast read the live roster, so `peer-x` showed up in `bridge_peers` as
|
|
1426
|
+
* addressable yet silently missed every broadcast. Both resolve here now. */
|
|
1427
|
+
audience() {
|
|
1428
|
+
const ids = new Set(this.lastSeen.keys());
|
|
1429
|
+
for (const id of this.parkedAt.keys()) ids.add(id);
|
|
1430
|
+
return [...ids];
|
|
1431
|
+
}
|
|
696
1432
|
/** Resolve the peer ids a task is assigned to (broadcast / group fan-out). */
|
|
697
1433
|
resolveAssignees(from, to) {
|
|
698
|
-
if (to === BROADCAST) return this.
|
|
1434
|
+
if (to === BROADCAST) return this.audience().filter((peer) => peer !== from);
|
|
699
1435
|
const group = this.groups.get(to);
|
|
700
1436
|
if (group !== void 0) return group.members.filter((member) => member !== from);
|
|
701
1437
|
return [to];
|
|
@@ -724,7 +1460,7 @@ var AgentHub = class {
|
|
|
724
1460
|
this.taskLedger.set(message.id, record);
|
|
725
1461
|
this.scheduleTaskTimeout(record);
|
|
726
1462
|
this.evictOverflowTasks();
|
|
727
|
-
this.
|
|
1463
|
+
this.taskChanged(this.taskOf(record.id));
|
|
728
1464
|
}
|
|
729
1465
|
/** Arm the SLA timer for a task that supplied `timeoutMs`. A deadline
|
|
730
1466
|
* beyond {@link MAX_TIMER_DELAY_MS} cannot be expressed as one delay — the
|
|
@@ -756,17 +1492,17 @@ var AgentHub = class {
|
|
|
756
1492
|
applied: true,
|
|
757
1493
|
system: true
|
|
758
1494
|
};
|
|
759
|
-
|
|
1495
|
+
this.pushAckEvent(record, event);
|
|
760
1496
|
for (const assignee of record.assignees) {
|
|
761
1497
|
if (!TERMINAL_TASK_STATUSES.includes(assignee.status)) {
|
|
762
1498
|
assignee.status = "timeout";
|
|
763
|
-
|
|
1499
|
+
this.pushAssigneeAck(assignee, event);
|
|
764
1500
|
}
|
|
765
1501
|
}
|
|
766
1502
|
record.status = "timeout";
|
|
767
1503
|
record.updatedAt = now;
|
|
768
1504
|
this.clearTaskTimer(taskId);
|
|
769
|
-
this.
|
|
1505
|
+
this.taskChanged(this.taskOf(taskId));
|
|
770
1506
|
}
|
|
771
1507
|
clearTaskTimer(taskId) {
|
|
772
1508
|
const timer = this.taskTimers.get(taskId);
|
|
@@ -775,6 +1511,23 @@ var AgentHub = class {
|
|
|
775
1511
|
this.taskTimers.delete(taskId);
|
|
776
1512
|
}
|
|
777
1513
|
}
|
|
1514
|
+
/** Bring the SLA timer back in line with the AGGREGATE status after a
|
|
1515
|
+
* per-assignee write ({@link failTaskForGoneAssignee},
|
|
1516
|
+
* {@link failTaskForDroppedMessage}).
|
|
1517
|
+
*
|
|
1518
|
+
* A terminal task must not fire a second, contradictory timeout. A task that
|
|
1519
|
+
* is still open — a fan-out with one recipient lost and another working —
|
|
1520
|
+
* must keep its deadline: clearing the timer there left a task that stays
|
|
1521
|
+
* non-terminal forever, because `deadlineAt` is only read by the timer. */
|
|
1522
|
+
realignTaskTimer(record) {
|
|
1523
|
+
if (TERMINAL_TASK_STATUSES.includes(record.status)) {
|
|
1524
|
+
this.clearTaskTimer(record.id);
|
|
1525
|
+
return;
|
|
1526
|
+
}
|
|
1527
|
+
if (record.deadlineAt === void 0) return;
|
|
1528
|
+
if (this.taskTimers.has(record.id)) return;
|
|
1529
|
+
this.scheduleTaskTimeout(record);
|
|
1530
|
+
}
|
|
778
1531
|
/** Note that `target` has taken delivery of a task (waiter handoff / queue). */
|
|
779
1532
|
markTaskDelivered(taskId, target, ts) {
|
|
780
1533
|
const record = this.taskLedger.get(taskId);
|
|
@@ -783,7 +1536,7 @@ var AgentHub = class {
|
|
|
783
1536
|
if (assignee === void 0 || assignee.deliveredMs !== void 0) return;
|
|
784
1537
|
assignee.deliveredMs = ts;
|
|
785
1538
|
record.updatedAt = ts;
|
|
786
|
-
this.
|
|
1539
|
+
this.taskChanged(this.taskOf(taskId));
|
|
787
1540
|
}
|
|
788
1541
|
/**
|
|
789
1542
|
* Fold an ack into the task's timeline and (when legal) its status.
|
|
@@ -794,32 +1547,32 @@ var AgentHub = class {
|
|
|
794
1547
|
applyAckToLedger(message, from, ref, ack) {
|
|
795
1548
|
const record = this.taskLedger.get(ref);
|
|
796
1549
|
if (record === void 0) return;
|
|
797
|
-
const next = nextTaskStatus(record.status, ack.status);
|
|
798
1550
|
const assignee = record.assignees.find((a) => a.peerId === from);
|
|
799
1551
|
const assigneeNext = assignee === void 0 ? null : nextTaskStatus(assignee.status, ack.status);
|
|
800
|
-
const applied =
|
|
1552
|
+
const applied = assignee !== void 0 && assigneeNext !== null;
|
|
801
1553
|
const event = {
|
|
802
1554
|
from,
|
|
803
1555
|
status: ack.status,
|
|
804
1556
|
...ack.note !== void 0 ? { note: ack.note } : {},
|
|
805
1557
|
...typeof ack.progress === "number" && Number.isFinite(ack.progress) ? { progress: Math.max(0, Math.min(100, ack.progress)) } : {},
|
|
1558
|
+
...ack.artifacts !== void 0 && ack.artifacts.length > 0 ? { artifacts: ack.artifacts } : {},
|
|
806
1559
|
ts: message.ts,
|
|
807
1560
|
messageId: message.id,
|
|
808
1561
|
applied
|
|
809
1562
|
};
|
|
810
|
-
|
|
1563
|
+
this.pushAckEvent(record, event);
|
|
1564
|
+
if (applied && event.artifacts !== void 0) {
|
|
1565
|
+
const merged = [...record.artifacts ?? [], ...event.artifacts];
|
|
1566
|
+
record.artifacts = merged.length > MAX_TASK_ARTIFACTS ? merged.slice(-MAX_TASK_ARTIFACTS) : merged;
|
|
1567
|
+
}
|
|
811
1568
|
if (assignee !== void 0 && assigneeNext !== null) {
|
|
812
1569
|
assignee.status = assigneeNext;
|
|
813
|
-
|
|
1570
|
+
this.pushAssigneeAck(assignee, event);
|
|
814
1571
|
}
|
|
815
|
-
if (record.assignees.length
|
|
816
|
-
|
|
817
|
-
} else {
|
|
818
|
-
record.status = aggregateTaskStatus(record.assignees);
|
|
819
|
-
}
|
|
820
|
-
record.updatedAt = message.ts;
|
|
1572
|
+
if (record.assignees.length > 0) record.status = aggregateTaskStatus(record.assignees);
|
|
1573
|
+
if (applied) record.updatedAt = message.ts;
|
|
821
1574
|
if (TERMINAL_TASK_STATUSES.includes(record.status)) this.clearTaskTimer(record.id);
|
|
822
|
-
this.
|
|
1575
|
+
this.taskChanged(this.taskOf(record.id));
|
|
823
1576
|
}
|
|
824
1577
|
/** Keep the ledger bounded: drop oldest terminal tasks first. */
|
|
825
1578
|
evictOverflowTasks() {
|
|
@@ -838,7 +1591,10 @@ var AgentHub = class {
|
|
|
838
1591
|
const record = this.taskLedger.get(ref);
|
|
839
1592
|
if (record === void 0) return void 0;
|
|
840
1593
|
return {
|
|
841
|
-
|
|
1594
|
+
// `dropNotified` is INTERNAL bookkeeping (see protocol.ts). A shallow
|
|
1595
|
+
// spread used to hand it to bridge_task_status / bridge_tasks, which made
|
|
1596
|
+
// an implementation detail part of the published task shape.
|
|
1597
|
+
...omit(record, "dropNotified"),
|
|
842
1598
|
acks: record.acks.map((a) => ({ ...a })),
|
|
843
1599
|
assignees: record.assignees.map((a) => ({ ...a, acks: a.acks.map((e) => ({ ...e })) }))
|
|
844
1600
|
};
|
|
@@ -873,6 +1629,35 @@ var AgentHub = class {
|
|
|
873
1629
|
exportTasks() {
|
|
874
1630
|
return [...this.taskLedger.values()].map((record) => this.taskOf(record.id)).filter(Boolean);
|
|
875
1631
|
}
|
|
1632
|
+
/** Accept a peer id read from a persisted snapshot, or `undefined` when the
|
|
1633
|
+
* row that carries it is unusable. A state file is external input and the
|
|
1634
|
+
* ledger is an AUTHORIZATION source (ack rights, `bridge_task_status`,
|
|
1635
|
+
* `bridge_task_input`), so a row attributed to `hub`, to the broadcast
|
|
1636
|
+
* address, to a malformed id or to a group id would hand that identity rights
|
|
1637
|
+
* over someone else's task. Every place a snapshot names a peer goes through
|
|
1638
|
+
* here — the task sender, an ack author, an assignee — so the four fields
|
|
1639
|
+
* cannot drift apart. */
|
|
1640
|
+
importPeerRef(value) {
|
|
1641
|
+
if (typeof value !== "string") return void 0;
|
|
1642
|
+
if (!PEER_ID_PATTERN.test(value) || value === BROADCAST || value === HUB_PEER) return void 0;
|
|
1643
|
+
if (this.groups.has(value)) return void 0;
|
|
1644
|
+
return value;
|
|
1645
|
+
}
|
|
1646
|
+
/** Accept an ACK AUTHOR read from a persisted snapshot.
|
|
1647
|
+
*
|
|
1648
|
+
* Deliberately weaker than {@link importPeerRef} in exactly one direction: an
|
|
1649
|
+
* ack row authorizes nothing (the ledger's authorization sources are the
|
|
1650
|
+
* sender and the assignee rows, both checked strictly), while the hub itself
|
|
1651
|
+
* authors terminal markers under the task's RECIPIENT address — `from: "hub"`
|
|
1652
|
+
* for the "restored as unattributable" marker and `from: record.to` (a group
|
|
1653
|
+
* id, or `all`) for a fan-out timeout. Refusing those ids here would delete the
|
|
1654
|
+
* evidence that a task timed out, and the unattributable marker would be
|
|
1655
|
+
* re-appended on every boot because its idempotency test looks for the stored
|
|
1656
|
+
* `import-<id>` row. Malformed ids are still refused. */
|
|
1657
|
+
importAckRef(value) {
|
|
1658
|
+
if (typeof value !== "string" || !PEER_ID_PATTERN.test(value)) return void 0;
|
|
1659
|
+
return value;
|
|
1660
|
+
}
|
|
876
1661
|
/** Restore the task ledger at boot (and re-arm SLA timers). */
|
|
877
1662
|
importTasks(tasks) {
|
|
878
1663
|
if (!Array.isArray(tasks)) return 0;
|
|
@@ -881,13 +1666,16 @@ var AgentHub = class {
|
|
|
881
1666
|
if (typeof raw !== "object" || raw === null) continue;
|
|
882
1667
|
const t = raw;
|
|
883
1668
|
if (typeof t.id !== "string" || typeof t.from !== "string" || typeof t.to !== "string" || typeof t.prompt !== "string") continue;
|
|
884
|
-
if (typeof t.status !== "string" || !
|
|
1669
|
+
if (typeof t.status !== "string" || !ALL_TASK_STATUSES.includes(t.status)) continue;
|
|
1670
|
+
const from = this.importPeerRef(t.from);
|
|
1671
|
+
if (from === void 0) continue;
|
|
885
1672
|
const acks = Array.isArray(t.acks) ? t.acks.flatMap((rawAck) => {
|
|
886
1673
|
if (typeof rawAck !== "object" || rawAck === null) return [];
|
|
887
1674
|
const a = rawAck;
|
|
888
|
-
|
|
1675
|
+
const ackFrom = this.importAckRef(a.from);
|
|
1676
|
+
if (ackFrom === void 0 || typeof a.status !== "string" || !ALL_ACK_STATUSES.includes(a.status) || typeof a.ts !== "number" || typeof a.messageId !== "string") return [];
|
|
889
1677
|
return [{
|
|
890
|
-
from:
|
|
1678
|
+
from: ackFrom,
|
|
891
1679
|
status: a.status,
|
|
892
1680
|
...typeof a.note === "string" ? { note: a.note } : {},
|
|
893
1681
|
...typeof a.progress === "number" ? { progress: a.progress } : {},
|
|
@@ -897,20 +1685,22 @@ var AgentHub = class {
|
|
|
897
1685
|
...a.system === true ? { system: true } : {}
|
|
898
1686
|
}];
|
|
899
1687
|
}) : [];
|
|
900
|
-
const
|
|
1688
|
+
const storedAssignees = Array.isArray(t.assignees) ? t.assignees.flatMap((rawA) => {
|
|
901
1689
|
if (typeof rawA !== "object" || rawA === null) return [];
|
|
902
1690
|
const a = rawA;
|
|
903
|
-
|
|
1691
|
+
const assigneeId = this.importPeerRef(a.peerId);
|
|
1692
|
+
if (assigneeId === void 0 || typeof a.status !== "string" || !ALL_TASK_STATUSES.includes(a.status)) return [];
|
|
904
1693
|
return [{
|
|
905
|
-
peerId:
|
|
1694
|
+
peerId: assigneeId,
|
|
906
1695
|
status: a.status,
|
|
907
1696
|
...typeof a.deliveredMs === "number" ? { deliveredMs: a.deliveredMs } : {},
|
|
908
1697
|
acks: Array.isArray(a.acks) ? a.acks.flatMap((rawE) => {
|
|
909
1698
|
if (typeof rawE !== "object" || rawE === null) return [];
|
|
910
1699
|
const e = rawE;
|
|
911
|
-
|
|
1700
|
+
const eventFrom = this.importAckRef(e.from);
|
|
1701
|
+
if (eventFrom === void 0 || typeof e.status !== "string" || !ALL_ACK_STATUSES.includes(e.status) || typeof e.ts !== "number" || typeof e.messageId !== "string") return [];
|
|
912
1702
|
return [{
|
|
913
|
-
from:
|
|
1703
|
+
from: eventFrom,
|
|
914
1704
|
status: e.status,
|
|
915
1705
|
...typeof e.note === "string" ? { note: e.note } : {},
|
|
916
1706
|
ts: e.ts,
|
|
@@ -919,10 +1709,12 @@ var AgentHub = class {
|
|
|
919
1709
|
}];
|
|
920
1710
|
}) : []
|
|
921
1711
|
}];
|
|
922
|
-
}) : [
|
|
1712
|
+
}) : [];
|
|
1713
|
+
const unattributable = storedAssignees.length === 0 && (t.to === BROADCAST || this.groups.has(t.to) || !PEER_ID_PATTERN.test(t.to));
|
|
1714
|
+
const assignees = storedAssignees.length > 0 ? storedAssignees : unattributable ? [] : [{ peerId: t.to, status: t.status, acks: [] }];
|
|
923
1715
|
const record = {
|
|
924
1716
|
id: t.id,
|
|
925
|
-
from
|
|
1717
|
+
from,
|
|
926
1718
|
to: t.to,
|
|
927
1719
|
prompt: t.prompt,
|
|
928
1720
|
...typeof t.context === "string" ? { context: t.context } : {},
|
|
@@ -936,6 +1728,21 @@ var AgentHub = class {
|
|
|
936
1728
|
createdAt: typeof t.createdAt === "number" ? t.createdAt : Date.now(),
|
|
937
1729
|
updatedAt: typeof t.updatedAt === "number" ? t.updatedAt : Date.now()
|
|
938
1730
|
};
|
|
1731
|
+
if (unattributable) {
|
|
1732
|
+
record.status = "failed";
|
|
1733
|
+
if (!record.acks.some((event) => event.messageId === `import-${record.id}`)) {
|
|
1734
|
+
this.pushAckEvent(record, {
|
|
1735
|
+
from: HUB_PEER,
|
|
1736
|
+
status: "failed",
|
|
1737
|
+
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`,
|
|
1738
|
+
ts: record.updatedAt,
|
|
1739
|
+
messageId: `import-${record.id}`,
|
|
1740
|
+
applied: true,
|
|
1741
|
+
system: true
|
|
1742
|
+
});
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
if (assignees.length > 0) record.status = aggregateTaskStatus(assignees);
|
|
939
1746
|
this.taskLedger.set(record.id, record);
|
|
940
1747
|
this.scheduleTaskTimeout(record);
|
|
941
1748
|
count++;
|
|
@@ -943,33 +1750,49 @@ var AgentHub = class {
|
|
|
943
1750
|
this.evictOverflowTasks();
|
|
944
1751
|
return count;
|
|
945
1752
|
}
|
|
1753
|
+
/** Highest sequence number handed out so far — a client's "start from now"
|
|
1754
|
+
* cursor (`bridge_status.lastSeq`). */
|
|
1755
|
+
lastSeq() {
|
|
1756
|
+
return this.seqCounter;
|
|
1757
|
+
}
|
|
946
1758
|
/** Recent messages involving `peer` (inbound and outbound, plus group
|
|
947
|
-
* channels the peer belongs to), newest first.
|
|
948
|
-
|
|
1759
|
+
* channels the peer belongs to), newest first. `since` restricts the result to
|
|
1760
|
+
* messages newer than that sequence number (a resume cursor); omitting it keeps
|
|
1761
|
+
* the original behaviour, which includes history recorded before cursors
|
|
1762
|
+
* existed. */
|
|
1763
|
+
history(peerId, limit, since) {
|
|
949
1764
|
const memberOf = new Set(
|
|
950
1765
|
[...this.groups.values()].filter((group) => group.members.includes(peerId)).map((group) => group.id)
|
|
951
1766
|
);
|
|
952
1767
|
const filtered = this.historyRing.filter(
|
|
953
|
-
(message) => message.from === peerId || message.to === peerId || message.to === BROADCAST || message.channel !== void 0 && memberOf.has(message.channel)
|
|
1768
|
+
(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))
|
|
954
1769
|
);
|
|
955
1770
|
return filtered.slice(-Math.max(0, limit)).reverse();
|
|
956
1771
|
}
|
|
957
1772
|
/** Recent messages of one group channel, newest first. */
|
|
958
|
-
historyChannel(groupId, limit) {
|
|
959
|
-
const filtered = this.historyRing.filter(
|
|
1773
|
+
historyChannel(groupId, limit, since) {
|
|
1774
|
+
const filtered = this.historyRing.filter(
|
|
1775
|
+
(message) => (since === void 0 || (message.seq ?? 0) > since) && (message.channel === groupId || message.to === groupId && message.channel === void 0 && this.groups.has(groupId))
|
|
1776
|
+
);
|
|
960
1777
|
return filtered.slice(-Math.max(0, limit)).reverse();
|
|
961
1778
|
}
|
|
962
1779
|
/** Most recent messages across every peer, unfiltered (newest first).
|
|
963
1780
|
* Backs `bridge_history { peer: "all" }` — lets an archiver (the desktop
|
|
964
1781
|
* app) capture peer-to-peer traffic it is not a party of. */
|
|
965
|
-
historyAll(limit) {
|
|
966
|
-
|
|
1782
|
+
historyAll(limit, since) {
|
|
1783
|
+
const filtered = since === void 0 ? this.historyRing : this.historyRing.filter((message) => (message.seq ?? 0) > since);
|
|
1784
|
+
return filtered.slice(-Math.max(0, limit)).reverse();
|
|
967
1785
|
}
|
|
968
1786
|
// ---- groups (group channel) ------------------------------------------------
|
|
969
1787
|
/** Create a channel; throws when the id is taken or a member is unknown. */
|
|
970
1788
|
createGroup(id, members, createdBy, name) {
|
|
971
1789
|
if (this.groups.has(id)) throw new Error(`group already exists: ${id}`);
|
|
972
1790
|
if (!PEER_ID_PATTERN.test(id)) throw new Error(`invalid group id: ${id} (expected [A-Za-z0-9._:-]{1,64})`);
|
|
1791
|
+
if (id === BROADCAST) throw new Error(`group id '${id}' is taken: it is the broadcast address in the namespace peer and group ids share`);
|
|
1792
|
+
if (id === HUB_PEER) throw new Error(`group id '${id}' is taken: the hub uses it for its own notices`);
|
|
1793
|
+
if (this.lastSeen.has(id) || this.ownsMailbox(id) || this.profiles.has(id)) {
|
|
1794
|
+
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`);
|
|
1795
|
+
}
|
|
973
1796
|
const unique = [...new Set(members)];
|
|
974
1797
|
if (unique.length === 0) throw new Error("a group needs at least one member");
|
|
975
1798
|
for (const member of unique) {
|
|
@@ -1021,11 +1844,14 @@ var AgentHub = class {
|
|
|
1021
1844
|
}
|
|
1022
1845
|
/** Send a chat message to every member of a group except the sender;
|
|
1023
1846
|
* members that went offline are skipped (they read the group history).
|
|
1024
|
-
* The message carries `to` and `channel` = the group id.
|
|
1847
|
+
* The message carries `to` and `channel` = the group id.
|
|
1848
|
+
*
|
|
1849
|
+
* Membership is enforced once, in {@link compose} — the single path this and
|
|
1850
|
+
* a plain `bridge_chat { to: <group> }` both go through. The `unknown group`
|
|
1851
|
+
* check stays here so a caller naming a non-group gets that error instead of
|
|
1852
|
+
* compose's generic "unknown recipient". */
|
|
1025
1853
|
sendToGroup(from, groupId, content) {
|
|
1026
|
-
|
|
1027
|
-
if (group === void 0) throw new Error(`unknown group: ${groupId}`);
|
|
1028
|
-
if (!group.members.includes(from)) throw new Error(`peer '${from}' is not a member of group '${groupId}'`);
|
|
1854
|
+
if (!this.groups.has(groupId)) throw new Error(`unknown group: ${groupId}`);
|
|
1029
1855
|
return this.route(from, groupId, "chat", content);
|
|
1030
1856
|
}
|
|
1031
1857
|
/** Snapshot of every group for persistence. */
|
|
@@ -1041,6 +1867,8 @@ var AgentHub = class {
|
|
|
1041
1867
|
if (typeof raw !== "object" || raw === null) continue;
|
|
1042
1868
|
const candidate = raw;
|
|
1043
1869
|
if (typeof candidate.id !== "string" || !PEER_ID_PATTERN.test(candidate.id) || this.groups.has(candidate.id)) continue;
|
|
1870
|
+
if (candidate.id === BROADCAST || candidate.id === HUB_PEER) continue;
|
|
1871
|
+
if (this.lastSeen.has(candidate.id) || this.profiles.has(candidate.id)) continue;
|
|
1044
1872
|
if (!Array.isArray(candidate.members) || candidate.members.length === 0) continue;
|
|
1045
1873
|
const members = [...new Set(candidate.members.filter((m) => typeof m === "string" && PEER_ID_PATTERN.test(m)))];
|
|
1046
1874
|
if (members.length === 0) continue;
|
|
@@ -1051,13 +1879,19 @@ var AgentHub = class {
|
|
|
1051
1879
|
createdAt: typeof candidate.createdAt === "number" && Number.isFinite(candidate.createdAt) ? candidate.createdAt : Date.now(),
|
|
1052
1880
|
...typeof candidate.name === "string" && candidate.name !== "" ? { name: candidate.name } : {}
|
|
1053
1881
|
});
|
|
1882
|
+
this.queues.delete(candidate.id);
|
|
1883
|
+
this.parkedAt.delete(candidate.id);
|
|
1054
1884
|
count++;
|
|
1055
1885
|
}
|
|
1056
1886
|
return count;
|
|
1057
1887
|
}
|
|
1058
1888
|
// ---- persistence import/export (remote-mode SQLite store) -----------
|
|
1059
1889
|
/** Restore the history ring at boot. Shape-invalid rows are dropped; only
|
|
1060
|
-
* the newest {@link HubOptions.historyLimit} survive.
|
|
1890
|
+
* the newest {@link HubOptions.historyLimit} survive.
|
|
1891
|
+
*
|
|
1892
|
+
* Restoring is a FIELD WHITELIST: a wire field that is not listed here is
|
|
1893
|
+
* silently lost across a restart (that is how `priority` went missing), so
|
|
1894
|
+
* every new field on {@link BridgeMessage} has to be added below. */
|
|
1061
1895
|
importHistory(messages) {
|
|
1062
1896
|
if (!Array.isArray(messages)) return 0;
|
|
1063
1897
|
const valid = [];
|
|
@@ -1077,25 +1911,70 @@ var AgentHub = class {
|
|
|
1077
1911
|
...typeof m.channel === "string" ? { channel: m.channel } : {},
|
|
1078
1912
|
...typeof m.threadId === "string" ? { threadId: m.threadId } : {},
|
|
1079
1913
|
...hop !== void 0 ? { hop } : {},
|
|
1914
|
+
// Absent in databases written before the column existed; such a message
|
|
1915
|
+
// is simply unreachable through a `since` cursor, which is the honest
|
|
1916
|
+
// state for history that predates the cursor.
|
|
1917
|
+
...typeof m.seq === "number" && Number.isFinite(m.seq) && m.seq > 0 ? { seq: m.seq } : {},
|
|
1918
|
+
...typeof m.expiresAt === "number" && Number.isFinite(m.expiresAt) && m.expiresAt > 0 ? { expiresAt: m.expiresAt } : {},
|
|
1919
|
+
// Same guard as compose: only a real 0 | 1 | 2 is written back, an
|
|
1920
|
+
// absent one stays absent so no reader has to tell 0 from "unset".
|
|
1921
|
+
...m.priority === 0 || m.priority === 1 || m.priority === 2 ? { priority: m.priority } : {},
|
|
1080
1922
|
ts: m.ts
|
|
1081
1923
|
});
|
|
1082
1924
|
}
|
|
1925
|
+
for (const message of valid) {
|
|
1926
|
+
if (message.seq !== void 0 && message.seq > this.seqCounter) this.seqCounter = message.seq;
|
|
1927
|
+
}
|
|
1083
1928
|
for (const message of valid.slice(-this.options.historyLimit)) this.historyRing.push(message);
|
|
1084
1929
|
return Math.min(valid.length, this.options.historyLimit);
|
|
1085
1930
|
}
|
|
1086
|
-
/** Snapshot of every offline mailbox, keyed by peer (persistence).
|
|
1931
|
+
/** Snapshot of every offline mailbox, keyed by peer (persistence).
|
|
1932
|
+
*
|
|
1933
|
+
* Manual-ack leases ride along inside the peer's queue array: appended after
|
|
1934
|
+
* the queued mail, in lease order, and deliberately NOT re-sorted (the
|
|
1935
|
+
* restore path re-orders, see {@link importMailboxes}). A lease is a
|
|
1936
|
+
* delivery in progress — the message left the queue but was never committed
|
|
1937
|
+
* — and leaving it out is how an uncommitted message used to be in neither
|
|
1938
|
+
* `queues` nor SQLite and vanished on restart.
|
|
1939
|
+
*
|
|
1940
|
+
* EVERY lease is exported, expired or not: this is a snapshot of what the
|
|
1941
|
+
* hub knows was handed out, not a reachability verdict. Expiry is decided by
|
|
1942
|
+
* the CONSUMER (`poll` / `wait` / `reapLeases`), which drops an expired
|
|
1943
|
+
* message, counts it as `droppedExpired` and reconciles the ledger. Filtering
|
|
1944
|
+
* on `expiresAt` here created a window with no owner at all: a lease that
|
|
1945
|
+
* expired but was never reaped (no take, and `gcTick` does not run when
|
|
1946
|
+
* `peerIdleTimeoutMs` is 0) was written out by the next unrelated flush or
|
|
1947
|
+
* by a graceful shutdown — i.e. neither in the queue nor in the snapshot —
|
|
1948
|
+
* and the message was gone for good.
|
|
1949
|
+
*
|
|
1950
|
+
* No new top-level key on purpose: an older hub reading this snapshot sees
|
|
1951
|
+
* ordinary queued mail and redelivers it once, which is exactly the
|
|
1952
|
+
* at-least-once half of the lease contract.
|
|
1953
|
+
*
|
|
1954
|
+
* `attempts` does NOT survive: the counter lives in `leaseAttempts` (memory
|
|
1955
|
+
* only), so a restarted hub starts the message over at attempt 1. Treat
|
|
1956
|
+
* `maxAttempts` as a bound per PROCESS, not per message lifetime. */
|
|
1087
1957
|
exportMailboxes() {
|
|
1088
1958
|
const out = {};
|
|
1089
1959
|
for (const [peer, queue] of this.queues) {
|
|
1090
1960
|
if (queue.length > 0) out[peer] = queue.map((message) => ({ ...message }));
|
|
1091
1961
|
}
|
|
1962
|
+
for (const [peer, leases] of this.leases) {
|
|
1963
|
+
if (leases.length === 0) continue;
|
|
1964
|
+
const messages = out[peer] ?? (out[peer] = []);
|
|
1965
|
+
for (const lease of leases) messages.push({ ...lease.message });
|
|
1966
|
+
}
|
|
1092
1967
|
return out;
|
|
1093
1968
|
}
|
|
1094
|
-
/** Restore offline mailboxes at boot (peer reconnects and drains later).
|
|
1969
|
+
/** Restore offline mailboxes at boot (peer reconnects and drains later).
|
|
1970
|
+
*
|
|
1971
|
+
* Like {@link importHistory} this is a FIELD WHITELIST — a new wire field
|
|
1972
|
+
* must be added in both places or it is lost across a restart. */
|
|
1095
1973
|
importMailboxes(mailboxes) {
|
|
1096
1974
|
if (typeof mailboxes !== "object" || mailboxes === null) return 0;
|
|
1097
1975
|
let count = 0;
|
|
1098
1976
|
for (const [peer, queue] of Object.entries(mailboxes)) {
|
|
1977
|
+
if (!PEER_ID_PATTERN.test(peer) || peer === BROADCAST || peer === HUB_PEER || this.groups.has(peer)) continue;
|
|
1099
1978
|
if (!Array.isArray(queue) || queue.length === 0) continue;
|
|
1100
1979
|
const restored = [];
|
|
1101
1980
|
for (const raw of queue) {
|
|
@@ -1113,12 +1992,32 @@ var AgentHub = class {
|
|
|
1113
1992
|
...typeof m.channel === "string" ? { channel: m.channel } : {},
|
|
1114
1993
|
...typeof m.threadId === "string" ? { threadId: m.threadId } : {},
|
|
1115
1994
|
...hop !== void 0 ? { hop } : {},
|
|
1995
|
+
// Restored mail must keep its deadline and its sequence number: the
|
|
1996
|
+
// deadline decides whether it is still deliverable at all, and the
|
|
1997
|
+
// cursor has to stay continuous across a restart.
|
|
1998
|
+
...typeof m.seq === "number" && Number.isFinite(m.seq) && m.seq > 0 ? { seq: m.seq } : {},
|
|
1999
|
+
...typeof m.expiresAt === "number" && Number.isFinite(m.expiresAt) && m.expiresAt > 0 ? { expiresAt: m.expiresAt } : {},
|
|
2000
|
+
// Priority decides both the mailbox order and what overflow drops, so
|
|
2001
|
+
// dropping it here would quietly downgrade restored mail to FIFO.
|
|
2002
|
+
...m.priority === 0 || m.priority === 1 || m.priority === 2 ? { priority: m.priority } : {},
|
|
1116
2003
|
ts: m.ts
|
|
1117
2004
|
});
|
|
1118
2005
|
}
|
|
1119
2006
|
if (restored.length > 0) {
|
|
1120
|
-
|
|
1121
|
-
|
|
2007
|
+
const mailbox = [];
|
|
2008
|
+
insertByPriority(mailbox, [...restored].sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0)));
|
|
2009
|
+
const now = Date.now();
|
|
2010
|
+
while (mailbox.length > this.options.maxQueue) {
|
|
2011
|
+
const victimIndex = lowestPriorityIndex(mailbox);
|
|
2012
|
+
if (victimIndex < 0) break;
|
|
2013
|
+
const [evicted] = mailbox.splice(victimIndex, 1);
|
|
2014
|
+
if (evicted === void 0) break;
|
|
2015
|
+
this.countDrop(peer, "overflow", now, evicted);
|
|
2016
|
+
if (evicted.kind === "task") this.noteTaskDeliveryDropped(evicted, peer, "overflow", now);
|
|
2017
|
+
}
|
|
2018
|
+
this.queues.set(peer, mailbox);
|
|
2019
|
+
if (!this.lastSeen.has(peer)) this.parkedAt.set(peer, Date.now());
|
|
2020
|
+
count += mailbox.length;
|
|
1122
2021
|
}
|
|
1123
2022
|
}
|
|
1124
2023
|
return count;
|
|
@@ -1131,54 +2030,426 @@ var AgentHub = class {
|
|
|
1131
2030
|
const now = Date.now();
|
|
1132
2031
|
return {
|
|
1133
2032
|
server: "agent-comm-hub",
|
|
1134
|
-
peers: this.
|
|
1135
|
-
const alias = this.profiles.get(peer)?.alias;
|
|
1136
|
-
return {
|
|
1137
|
-
id: peer,
|
|
1138
|
-
...alias !== void 0 ? { alias } : {},
|
|
1139
|
-
connected: this.isActive(peer) || livePeers?.has(peer) === true,
|
|
1140
|
-
lastSeenMs: this.lastSeen.get(peer) ?? 0,
|
|
1141
|
-
queued: (this.queues.get(peer) ?? []).length,
|
|
1142
|
-
waiting: (this.waiters.get(peer) ?? []).length
|
|
1143
|
-
};
|
|
1144
|
-
}),
|
|
2033
|
+
peers: this.rosterRows(livePeers),
|
|
1145
2034
|
historyLimit: this.options.historyLimit,
|
|
1146
|
-
maxQueue: this.options.maxQueue
|
|
2035
|
+
maxQueue: this.options.maxQueue,
|
|
2036
|
+
// A client that wants only what happened since it last looked reads this
|
|
2037
|
+
// and passes it back as `bridge_history { since }`.
|
|
2038
|
+
lastSeq: this.seqCounter
|
|
2039
|
+
};
|
|
2040
|
+
}
|
|
2041
|
+
/** Registered peers plus parked ones (gone but still holding mail).
|
|
2042
|
+
* Parked rows are what lets a sender tell "queued, will be delivered when it
|
|
2043
|
+
* comes back" apart from "vanished" — without them the message just looks lost.
|
|
2044
|
+
*/
|
|
2045
|
+
rosterRows(livePeers) {
|
|
2046
|
+
const rows = this.peers().map((peer) => {
|
|
2047
|
+
const alias = this.profiles.get(peer)?.alias;
|
|
2048
|
+
const connected = this.isActive(peer) || livePeers?.has(peer) === true;
|
|
2049
|
+
return {
|
|
2050
|
+
id: peer,
|
|
2051
|
+
...alias !== void 0 ? { alias } : {},
|
|
2052
|
+
connected,
|
|
2053
|
+
reachable: connected ? "online" : "idle",
|
|
2054
|
+
lastSeenMs: this.lastSeen.get(peer) ?? 0,
|
|
2055
|
+
queued: (this.queues.get(peer) ?? []).length,
|
|
2056
|
+
waiting: (this.waiters.get(peer) ?? []).length,
|
|
2057
|
+
...this.leases.get(peer) !== void 0 ? { inFlight: this.leases.get(peer).length } : {},
|
|
2058
|
+
...this.drops.get(peer) !== void 0 && this.drops.get(peer).overflow > 0 ? { droppedOverflow: this.drops.get(peer).overflow } : {},
|
|
2059
|
+
...this.drops.get(peer) !== void 0 && this.drops.get(peer).expired > 0 ? { droppedExpired: this.drops.get(peer).expired } : {},
|
|
2060
|
+
...this.drops.get(peer) !== void 0 && this.drops.get(peer).rate > 0 ? { droppedRate: this.drops.get(peer).rate } : {},
|
|
2061
|
+
...this.deadLetters.get(peer) !== void 0 ? { deadLettered: this.deadLetters.get(peer).length } : {}
|
|
2062
|
+
};
|
|
2063
|
+
});
|
|
2064
|
+
for (const [peerId, parkedMs] of this.parkedAt) {
|
|
2065
|
+
if (this.lastSeen.has(peerId)) continue;
|
|
2066
|
+
const alias = this.profiles.get(peerId)?.alias;
|
|
2067
|
+
rows.push({
|
|
2068
|
+
id: peerId,
|
|
2069
|
+
...alias !== void 0 ? { alias } : {},
|
|
2070
|
+
connected: false,
|
|
2071
|
+
reachable: "parked",
|
|
2072
|
+
lastSeenMs: parkedMs,
|
|
2073
|
+
queued: (this.queues.get(peerId) ?? []).length,
|
|
2074
|
+
waiting: 0,
|
|
2075
|
+
...this.leases.get(peerId) !== void 0 ? { inFlight: this.leases.get(peerId).length } : {},
|
|
2076
|
+
...this.deadLetters.get(peerId) !== void 0 ? { deadLettered: this.deadLetters.get(peerId).length } : {}
|
|
2077
|
+
});
|
|
2078
|
+
}
|
|
2079
|
+
return rows;
|
|
2080
|
+
}
|
|
2081
|
+
// ---- manual-ack leases -----------------------------------------------------
|
|
2082
|
+
/** A message handed out but not yet committed, and when its lease ends. */
|
|
2083
|
+
leases = /* @__PURE__ */ new Map();
|
|
2084
|
+
/** Hand-out count per (peer, message). Kept OUTSIDE the message so requeueing
|
|
2085
|
+
* preserves it and so it is never persisted as part of the message. */
|
|
2086
|
+
leaseAttempts = /* @__PURE__ */ new Map();
|
|
2087
|
+
/** Messages that ran out of attempts; `nack` revives them. */
|
|
2088
|
+
deadLetters = /* @__PURE__ */ new Map();
|
|
2089
|
+
// ---- drop accounting --------------------------------------------------------
|
|
2090
|
+
/** Per-peer drop counters, surfaced in the roster. Memory-only on purpose:
|
|
2091
|
+
* these are operational counters for the current run, not durable state. */
|
|
2092
|
+
drops = /* @__PURE__ */ new Map();
|
|
2093
|
+
/** Per-peer token bucket for the MAILBOX. See {@link HubOptions.ratePerMin}. */
|
|
2094
|
+
buckets = /* @__PURE__ */ new Map();
|
|
2095
|
+
/** Traffic counters, per peer: how much this peer sent, was sent, and acked.
|
|
2096
|
+
* Deliberately separate from the mailbox — "how much has this peer sent" is not
|
|
2097
|
+
* "how much is queued", and a drained queue must not erase the history of what
|
|
2098
|
+
* went through it. Memory-only, like {@link drops}: operational, not durable. */
|
|
2099
|
+
traffic = /* @__PURE__ */ new Map();
|
|
2100
|
+
bumpTraffic(peerId, field) {
|
|
2101
|
+
const row = this.traffic.get(peerId) ?? { sent: 0, received: 0, acked: 0 };
|
|
2102
|
+
row[field]++;
|
|
2103
|
+
this.traffic.set(peerId, row);
|
|
2104
|
+
}
|
|
2105
|
+
/**
|
|
2106
|
+
* Observability snapshot: per-peer and global counters.
|
|
2107
|
+
*
|
|
2108
|
+
* Everything here is either derived from live state or from a counter the hub
|
|
2109
|
+
* already keeps — nothing is estimated, and nothing is sampled. `messagesTotal`
|
|
2110
|
+
* is the history `seq` (monotonic, never resets in a run), so it is a true count
|
|
2111
|
+
* of composed messages rather than a rolling window.
|
|
2112
|
+
*/
|
|
2113
|
+
metrics() {
|
|
2114
|
+
const tasksByStatus = {};
|
|
2115
|
+
for (const record of this.taskLedger.values()) {
|
|
2116
|
+
tasksByStatus[record.status] = (tasksByStatus[record.status] ?? 0) + 1;
|
|
2117
|
+
}
|
|
2118
|
+
const ids = /* @__PURE__ */ new Set([
|
|
2119
|
+
...this.lastSeen.keys(),
|
|
2120
|
+
...this.parkedAt.keys(),
|
|
2121
|
+
...this.queues.keys(),
|
|
2122
|
+
...this.traffic.keys()
|
|
2123
|
+
]);
|
|
2124
|
+
const peers = [...ids].map((peerId) => {
|
|
2125
|
+
const row = this.traffic.get(peerId) ?? { sent: 0, received: 0, acked: 0 };
|
|
2126
|
+
const drop = this.drops.get(peerId) ?? { overflow: 0, expired: 0, rate: 0 };
|
|
2127
|
+
return {
|
|
2128
|
+
peerId,
|
|
2129
|
+
sent: row.sent,
|
|
2130
|
+
received: row.received,
|
|
2131
|
+
acked: row.acked,
|
|
2132
|
+
queued: this.queues.get(peerId)?.length ?? 0,
|
|
2133
|
+
inFlight: this.leases.get(peerId)?.length ?? 0,
|
|
2134
|
+
deadLettered: this.deadLetters.get(peerId)?.length ?? 0,
|
|
2135
|
+
droppedOverflow: drop.overflow,
|
|
2136
|
+
droppedExpired: drop.expired,
|
|
2137
|
+
droppedRate: drop.rate,
|
|
2138
|
+
// Same definition the roster uses: recent activity OR a live SSE channel.
|
|
2139
|
+
connected: this.isActive(peerId) || this.options.isPeerLive?.(peerId) === true
|
|
2140
|
+
};
|
|
2141
|
+
});
|
|
2142
|
+
return {
|
|
2143
|
+
global: {
|
|
2144
|
+
messagesTotal: this.seqCounter,
|
|
2145
|
+
peers: peers.length,
|
|
2146
|
+
connectedPeers: peers.filter((p) => p.connected).length,
|
|
2147
|
+
parkedPeers: peers.filter((p) => !p.connected && this.parkedAt.has(p.peerId)).length,
|
|
2148
|
+
waitersNow: [...this.waiters.values()].reduce((sum, list) => sum + list.length, 0),
|
|
2149
|
+
queuedTotal: peers.reduce((sum, p) => sum + p.queued, 0),
|
|
2150
|
+
tasksByStatus,
|
|
2151
|
+
droppedOverflow: peers.reduce((sum, p) => sum + p.droppedOverflow, 0),
|
|
2152
|
+
droppedExpired: peers.reduce((sum, p) => sum + p.droppedExpired, 0),
|
|
2153
|
+
droppedRate: peers.reduce((sum, p) => sum + p.droppedRate, 0),
|
|
2154
|
+
deadLettered: peers.reduce((sum, p) => sum + p.deadLettered, 0),
|
|
2155
|
+
inFlight: peers.reduce((sum, p) => sum + p.inFlight, 0)
|
|
2156
|
+
},
|
|
2157
|
+
peers: peers.sort((a, b) => a.peerId.localeCompare(b.peerId))
|
|
1147
2158
|
};
|
|
1148
2159
|
}
|
|
2160
|
+
/** Count a dropped message for `peerId` and, if that peer is waiting right
|
|
2161
|
+
* now, tell it. The notice is NOT queued: the mailbox is either full
|
|
2162
|
+
* (overflow) or the message already expired, and queueing the notice would
|
|
2163
|
+
* push yet another message out. An offline peer just sees the counters. */
|
|
2164
|
+
/** May this peer's mailbox accept one more message right now?
|
|
2165
|
+
*
|
|
2166
|
+
* Applied on the QUEUE path only, never on a waiter handoff: a waiting peer
|
|
2167
|
+
* already controls its own rate (it gets one message per `bridge_wait`), while a
|
|
2168
|
+
* mailbox is filled by traffic the recipient never asked for. That is the whole
|
|
2169
|
+
* point of the bucket.
|
|
2170
|
+
*/
|
|
2171
|
+
takeToken(peerId, now) {
|
|
2172
|
+
const rate = this.options.ratePerMin ?? 0;
|
|
2173
|
+
if (rate <= 0) return true;
|
|
2174
|
+
const bucket = this.buckets.get(peerId) ?? { tokens: rate, last: now };
|
|
2175
|
+
const elapsed = Math.max(0, now - bucket.last);
|
|
2176
|
+
bucket.tokens = Math.min(rate, bucket.tokens + elapsed * rate / 6e4);
|
|
2177
|
+
bucket.last = now;
|
|
2178
|
+
if (bucket.tokens < 1) {
|
|
2179
|
+
this.buckets.set(peerId, bucket);
|
|
2180
|
+
return false;
|
|
2181
|
+
}
|
|
2182
|
+
bucket.tokens -= 1;
|
|
2183
|
+
this.buckets.set(peerId, bucket);
|
|
2184
|
+
return true;
|
|
2185
|
+
}
|
|
2186
|
+
/** Count a dropped message. `message` (when the caller has it) names the loss
|
|
2187
|
+
* in the event detail: the counter alone told an operator that something went
|
|
2188
|
+
* missing, never what — and a dropped task is reconciled in the ledger, which
|
|
2189
|
+
* has to be matchable back to this event. */
|
|
2190
|
+
countDrop(peerId, kind, now, message) {
|
|
2191
|
+
const stats = this.drops.get(peerId) ?? { overflow: 0, expired: 0, rate: 0 };
|
|
2192
|
+
stats[kind] += 1;
|
|
2193
|
+
this.drops.set(peerId, stats);
|
|
2194
|
+
const total = stats.overflow + stats.expired + stats.rate;
|
|
2195
|
+
this.recordEvent("mailbox_dropped", {
|
|
2196
|
+
peer: peerId,
|
|
2197
|
+
detail: {
|
|
2198
|
+
reason: kind,
|
|
2199
|
+
total,
|
|
2200
|
+
...message !== void 0 ? { messageId: message.id } : {},
|
|
2201
|
+
// The ledger is keyed by the task's message id, so this repeats
|
|
2202
|
+
// `messageId` today; it is spelled out so a consumer looking for "the
|
|
2203
|
+
// task this drop killed" does not have to know that.
|
|
2204
|
+
...message !== void 0 && message.kind === "task" ? { taskId: message.id } : {}
|
|
2205
|
+
}
|
|
2206
|
+
});
|
|
2207
|
+
const notice = {
|
|
2208
|
+
id: randomUUID(),
|
|
2209
|
+
seq: ++this.seqCounter,
|
|
2210
|
+
from: HUB_PEER,
|
|
2211
|
+
to: peerId,
|
|
2212
|
+
kind: "notice",
|
|
2213
|
+
content: encodeContent({
|
|
2214
|
+
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)`,
|
|
2215
|
+
level: "warn"
|
|
2216
|
+
}),
|
|
2217
|
+
ts: now
|
|
2218
|
+
};
|
|
2219
|
+
if (kind === "expired") {
|
|
2220
|
+
const queue = this.queues.get(peerId) ?? [];
|
|
2221
|
+
if (queue.length < this.options.maxQueue) {
|
|
2222
|
+
queue.push(notice);
|
|
2223
|
+
this.queues.set(peerId, queue);
|
|
2224
|
+
this.options.onQueued?.(notice, peerId);
|
|
2225
|
+
this.options.onMailboxesChanged?.();
|
|
2226
|
+
return;
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
this.deliverToWaiter(peerId, notice);
|
|
2230
|
+
}
|
|
2231
|
+
/** Drop counters for `peerId` (undefined when nothing was ever dropped). */
|
|
2232
|
+
dropsFor(peerId) {
|
|
2233
|
+
return this.drops.get(peerId);
|
|
2234
|
+
}
|
|
2235
|
+
/** Hand `message` to a matching live waiter, if there is one. Never queues —
|
|
2236
|
+
* used for notices about a mailbox that must not grow. Returns whether it
|
|
2237
|
+
* was handed over. */
|
|
2238
|
+
deliverToWaiter(target, message) {
|
|
2239
|
+
const list = this.waiters.get(target) ?? [];
|
|
2240
|
+
const index = list.findIndex((waiter2) => matchesWaiter(waiter2, message, this.taskLedger));
|
|
2241
|
+
if (index < 0) return false;
|
|
2242
|
+
const [waiter] = list.splice(index, 1);
|
|
2243
|
+
this.waiters.set(target, list);
|
|
2244
|
+
clearTimeout(waiter.timer);
|
|
2245
|
+
waiter.resolve({ type: "message", message: this.handOut(target, message, waiter.manual === true, message.ts) });
|
|
2246
|
+
return true;
|
|
2247
|
+
}
|
|
2248
|
+
static leaseKey(peerId, messageId) {
|
|
2249
|
+
return `${peerId}\0${messageId}`;
|
|
2250
|
+
}
|
|
2251
|
+
/** Drop every queued message of `peerId` whose deadline passed, counting each
|
|
2252
|
+
* loss. Shared by `poll` and `wait`: an expired message must never be handed
|
|
2253
|
+
* out, and it must not sit at the head of the mailbox looking deliverable
|
|
2254
|
+
* either.
|
|
2255
|
+
*
|
|
2256
|
+
* The attempt counter goes with it. Nothing can hand the message out again,
|
|
2257
|
+
* so keeping the key would leak one `leaseAttempts` entry per expired message
|
|
2258
|
+
* in a long-running process. */
|
|
2259
|
+
sweepExpired(peerId, queue, now) {
|
|
2260
|
+
for (let i = queue.length - 1; i >= 0; i--) {
|
|
2261
|
+
const queued = queue[i];
|
|
2262
|
+
if (queued.expiresAt === void 0 || queued.expiresAt > now) continue;
|
|
2263
|
+
queue.splice(i, 1);
|
|
2264
|
+
this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, queued.id));
|
|
2265
|
+
this.countDrop(peerId, "expired", now, queued);
|
|
2266
|
+
if (queued.kind === "task") this.noteTaskDeliveryDropped(queued, peerId, "expired", now);
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
/** Return expired leases to the queue in priority order, or dead-letter them
|
|
2270
|
+
* once they have been handed out too many times. Called before every take, so
|
|
2271
|
+
* expiry needs no timer of its own. */
|
|
2272
|
+
reapLeases(peerId, now) {
|
|
2273
|
+
const list = this.leases.get(peerId);
|
|
2274
|
+
if (list === void 0 || list.length === 0) return;
|
|
2275
|
+
const max = this.options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
2276
|
+
const still = [];
|
|
2277
|
+
const back = [];
|
|
2278
|
+
const dead = [];
|
|
2279
|
+
for (const lease of list) {
|
|
2280
|
+
if (lease.expiresAt > now) {
|
|
2281
|
+
still.push(lease);
|
|
2282
|
+
continue;
|
|
2283
|
+
}
|
|
2284
|
+
const attempts = this.leaseAttempts.get(_AgentHub.leaseKey(peerId, lease.message.id)) ?? 0;
|
|
2285
|
+
if (max > 0 && attempts >= max) {
|
|
2286
|
+
dead.push(lease.message);
|
|
2287
|
+
continue;
|
|
2288
|
+
}
|
|
2289
|
+
back.push(lease.message);
|
|
2290
|
+
}
|
|
2291
|
+
if (still.length > 0) this.leases.set(peerId, still);
|
|
2292
|
+
else this.leases.delete(peerId);
|
|
2293
|
+
if (back.length > 0) this.requeue(peerId, back, now);
|
|
2294
|
+
if (dead.length > 0) this.deadLetter(peerId, dead, now);
|
|
2295
|
+
}
|
|
2296
|
+
/** Put messages back into `peerId`'s mailbox, trimming to `maxQueue`.
|
|
2297
|
+
*
|
|
2298
|
+
* A message coming BACK competes for a slot exactly like arriving mail, so it
|
|
2299
|
+
* can never grow a full mailbox: `insertByPriority` orders it, then the tail
|
|
2300
|
+
* (lowest priority, newest) is what does not fit. Those go to the dead letters
|
|
2301
|
+
* instead of being dropped — a requeued message is a message the hub promised
|
|
2302
|
+
* to keep, and `bridge_nack` can still revive it. Returns how many really made
|
|
2303
|
+
* it into the queue. */
|
|
2304
|
+
requeue(peerId, messages, now) {
|
|
2305
|
+
if (messages.length === 0) return 0;
|
|
2306
|
+
const queue = this.queues.get(peerId) ?? [];
|
|
2307
|
+
insertByPriority(queue, messages);
|
|
2308
|
+
this.queues.set(peerId, queue);
|
|
2309
|
+
const overflow = [];
|
|
2310
|
+
while (queue.length > this.options.maxQueue) overflow.push(queue.pop());
|
|
2311
|
+
this.options.onMailboxesChanged?.();
|
|
2312
|
+
if (overflow.length > 0) this.deadLetter(peerId, overflow, now);
|
|
2313
|
+
const inQueue = new Set(queue);
|
|
2314
|
+
return messages.reduce((kept, message) => kept + (inQueue.has(message) ? 1 : 0), 0);
|
|
2315
|
+
}
|
|
2316
|
+
/** Park messages that can no longer be handed out (attempts exhausted, or no
|
|
2317
|
+
* room in the mailbox). One bounded list per peer — see MAX_DEAD_LETTERS.
|
|
2318
|
+
*
|
|
2319
|
+
* The OLDEST entry is evicted first: it is the one a `bridge_nack` is least
|
|
2320
|
+
* likely to still want, and reviving resets attempts anyway. The eviction is
|
|
2321
|
+
* COUNTED (`droppedOverflow` + a `mailbox_dropped` event naming the message)
|
|
2322
|
+
* rather than silent, so a full dead-letter list is still visible.
|
|
2323
|
+
*
|
|
2324
|
+
* An evicted TASK is the exception: it settles as a terminal failure. A dead
|
|
2325
|
+
* letter is the last copy of a message the hub promised to keep, and the
|
|
2326
|
+
* sender was told `bridge_nack` can revive it — once it is evicted, no
|
|
2327
|
+
* revival path exists, so leaving the ledger non-terminal would keep
|
|
2328
|
+
* promising something that cannot happen (same rule as `unregistered`). */
|
|
2329
|
+
deadLetter(peerId, messages, now) {
|
|
2330
|
+
const dead = this.deadLetters.get(peerId) ?? [];
|
|
2331
|
+
dead.push(...messages);
|
|
2332
|
+
const evicted = dead.length > MAX_DEAD_LETTERS ? dead.splice(0, dead.length - MAX_DEAD_LETTERS) : [];
|
|
2333
|
+
this.deadLetters.set(peerId, dead);
|
|
2334
|
+
for (const message of messages) {
|
|
2335
|
+
if (message.kind === "task") this.noteTaskDeliveryDropped(message, peerId, "dead-letter", now);
|
|
2336
|
+
}
|
|
2337
|
+
for (const message of evicted) {
|
|
2338
|
+
this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, message.id));
|
|
2339
|
+
this.countDrop(peerId, "overflow", now, message);
|
|
2340
|
+
if (message.kind === "task") this.failTaskForDroppedMessage(message, peerId, "dead-letter-evicted", now);
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2343
|
+
/** Hand a message to `peerId`. Without `manual` it is gone; with it the hub
|
|
2344
|
+
* keeps a lease and the peer must `commit` or `nack` before it expires. */
|
|
2345
|
+
handOut(peerId, message, manual, now) {
|
|
2346
|
+
if (!manual) return message;
|
|
2347
|
+
const key = _AgentHub.leaseKey(peerId, message.id);
|
|
2348
|
+
const attempts = (this.leaseAttempts.get(key) ?? 0) + 1;
|
|
2349
|
+
this.leaseAttempts.set(key, attempts);
|
|
2350
|
+
const expiresAt = now + (this.options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS);
|
|
2351
|
+
const list = this.leases.get(peerId) ?? [];
|
|
2352
|
+
list.push({ message, expiresAt });
|
|
2353
|
+
this.leases.set(peerId, list);
|
|
2354
|
+
this.options.onMailboxesChanged?.();
|
|
2355
|
+
return { ...message, attempts, leaseExpiresAt: expiresAt };
|
|
2356
|
+
}
|
|
2357
|
+
/** Mark leased messages as consumed; returns how many leases were released. */
|
|
2358
|
+
commit(peerId, ids) {
|
|
2359
|
+
const wanted = new Set(ids);
|
|
2360
|
+
const list = this.leases.get(peerId);
|
|
2361
|
+
if (list === void 0) return 0;
|
|
2362
|
+
const still = [];
|
|
2363
|
+
const released = [];
|
|
2364
|
+
for (const lease of list) {
|
|
2365
|
+
if (wanted.has(lease.message.id)) released.push(lease.message);
|
|
2366
|
+
else still.push(lease);
|
|
2367
|
+
}
|
|
2368
|
+
for (const message of released) this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, message.id));
|
|
2369
|
+
if (still.length > 0) this.leases.set(peerId, still);
|
|
2370
|
+
else this.leases.delete(peerId);
|
|
2371
|
+
if (released.length > 0) this.options.onMailboxesChanged?.();
|
|
2372
|
+
return released.length;
|
|
2373
|
+
}
|
|
2374
|
+
/** Give messages back NOW — from live leases or from the dead letters. Attempts
|
|
2375
|
+
* are kept, so a message that keeps failing still eventually dead-letters;
|
|
2376
|
+
* reviving a dead letter resets its count, which is the point of reviving it. */
|
|
2377
|
+
nack(peerId, ids) {
|
|
2378
|
+
const wanted = new Set(ids);
|
|
2379
|
+
const back = [];
|
|
2380
|
+
const list = this.leases.get(peerId);
|
|
2381
|
+
if (list !== void 0) {
|
|
2382
|
+
const still = [];
|
|
2383
|
+
for (const lease of list) {
|
|
2384
|
+
if (wanted.has(lease.message.id)) back.push(lease.message);
|
|
2385
|
+
else still.push(lease);
|
|
2386
|
+
}
|
|
2387
|
+
if (still.length > 0) this.leases.set(peerId, still);
|
|
2388
|
+
else this.leases.delete(peerId);
|
|
2389
|
+
}
|
|
2390
|
+
const dead = this.deadLetters.get(peerId);
|
|
2391
|
+
if (dead !== void 0) {
|
|
2392
|
+
const still = [];
|
|
2393
|
+
for (const message of dead) {
|
|
2394
|
+
if (wanted.has(message.id)) {
|
|
2395
|
+
back.push(message);
|
|
2396
|
+
this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, message.id));
|
|
2397
|
+
} else still.push(message);
|
|
2398
|
+
}
|
|
2399
|
+
if (still.length > 0) this.deadLetters.set(peerId, still);
|
|
2400
|
+
else this.deadLetters.delete(peerId);
|
|
2401
|
+
}
|
|
2402
|
+
return this.requeue(peerId, back, Date.now());
|
|
2403
|
+
}
|
|
1149
2404
|
/** Non-blocking drain of everything queued for `peer` (optionally from one sender). */
|
|
1150
|
-
poll(peerId, from) {
|
|
2405
|
+
poll(peerId, from, options) {
|
|
2406
|
+
const now = Date.now();
|
|
2407
|
+
this.reapLeases(peerId, now);
|
|
1151
2408
|
const queue = this.queues.get(peerId) ?? [];
|
|
2409
|
+
this.sweepExpired(peerId, queue, now);
|
|
1152
2410
|
const drained = from === void 0 ? queue.splice(0, queue.length) : drainFrom(queue, from);
|
|
1153
2411
|
if (drained.length > 0) this.options.onMailboxesChanged?.();
|
|
1154
|
-
return drained;
|
|
2412
|
+
return drained.map((message) => this.handOut(peerId, message, options?.manual === true, now));
|
|
1155
2413
|
}
|
|
1156
2414
|
/**
|
|
1157
2415
|
* Long-poll for the next message addressed to `peer`: resolves immediately
|
|
1158
2416
|
* when a matching one is queued, otherwise waits up to `timeoutMs` (capped
|
|
1159
2417
|
* by `waitTimeoutMs`) or until `signal` aborts. `from` narrows to one sender.
|
|
1160
|
-
* `ref` narrows to
|
|
2418
|
+
* `ref` narrows to that task's reply — an ack, or the `chat` an assignee hands
|
|
2419
|
+
* the result back in — with `statuses` / `terminalOnly` narrowing the ack half
|
|
2420
|
+
* (see {@link matchesWaiter}).
|
|
1161
2421
|
*
|
|
1162
2422
|
* Takes ONLY the first matching queued message. Calling poll() here would
|
|
1163
2423
|
* drain the whole mailbox and discard every message after the first —
|
|
1164
2424
|
* a multi-message burst (or a reconnect with a full queue) would silently
|
|
1165
2425
|
* lose messages that never reach wait/poll again.
|
|
1166
2426
|
*/
|
|
1167
|
-
wait(peerId, timeoutMs, from, signal, ref, threadId) {
|
|
2427
|
+
wait(peerId, timeoutMs, from, signal, ref, threadId, manual, maxMessages = 1, statuses, terminalOnly) {
|
|
1168
2428
|
const startedAt = Date.now();
|
|
1169
|
-
const matches = (message) => {
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
return
|
|
2429
|
+
const matches = (message) => matchesWaiter({ from, ref, statuses, terminalOnly, threadId }, message, this.taskLedger);
|
|
2430
|
+
const isParty = (record) => record.from === peerId || record.assignees.some((assignee) => assignee.peerId === peerId);
|
|
2431
|
+
const timedOut = () => {
|
|
2432
|
+
const record = ref === void 0 ? void 0 : this.taskLedger.get(ref);
|
|
2433
|
+
return {
|
|
2434
|
+
type: "timeout",
|
|
2435
|
+
waitedMs: Date.now() - startedAt,
|
|
2436
|
+
...record !== void 0 && isParty(record) ? { ref: { status: record.status, a2aState: a2aState(record.status) } } : {}
|
|
2437
|
+
};
|
|
1174
2438
|
};
|
|
2439
|
+
this.reapLeases(peerId, startedAt);
|
|
1175
2440
|
const queue = this.queues.get(peerId);
|
|
2441
|
+
if (queue !== void 0) this.sweepExpired(peerId, queue, startedAt);
|
|
1176
2442
|
if (queue !== void 0 && queue.length > 0) {
|
|
1177
|
-
const
|
|
1178
|
-
|
|
1179
|
-
|
|
2443
|
+
const take = Math.max(1, Math.floor(maxMessages));
|
|
2444
|
+
const taken = [];
|
|
2445
|
+
for (let i = 0; i < queue.length && taken.length < take; ) {
|
|
2446
|
+
if (matches(queue[i])) taken.push(...queue.splice(i, 1));
|
|
2447
|
+
else i++;
|
|
2448
|
+
}
|
|
2449
|
+
if (taken.length > 0) {
|
|
1180
2450
|
this.options.onMailboxesChanged?.();
|
|
1181
|
-
|
|
2451
|
+
const delivered = taken.map((queued) => this.handOut(peerId, queued, manual === true, startedAt));
|
|
2452
|
+
return Promise.resolve(take > 1 ? { type: "messages", messages: delivered } : { type: "message", message: delivered[0] });
|
|
1182
2453
|
}
|
|
1183
2454
|
}
|
|
1184
2455
|
const budget = Math.max(1, Math.min(Math.floor(timeoutMs), this.options.waitTimeoutMs));
|
|
@@ -1193,7 +2464,7 @@ var AgentHub = class {
|
|
|
1193
2464
|
};
|
|
1194
2465
|
const onAbort = () => {
|
|
1195
2466
|
removeFromRegistry();
|
|
1196
|
-
settle(
|
|
2467
|
+
settle(timedOut());
|
|
1197
2468
|
};
|
|
1198
2469
|
const removeFromRegistry = () => {
|
|
1199
2470
|
const list2 = this.waiters.get(peerId);
|
|
@@ -1201,7 +2472,7 @@ var AgentHub = class {
|
|
|
1201
2472
|
};
|
|
1202
2473
|
const timer = setTimeout(() => {
|
|
1203
2474
|
removeFromRegistry();
|
|
1204
|
-
settle(
|
|
2475
|
+
settle(timedOut());
|
|
1205
2476
|
}, budget);
|
|
1206
2477
|
if (signal?.aborted) {
|
|
1207
2478
|
onAbort();
|
|
@@ -1215,15 +2486,21 @@ var AgentHub = class {
|
|
|
1215
2486
|
onAbort,
|
|
1216
2487
|
...from !== void 0 ? { from } : {},
|
|
1217
2488
|
...ref !== void 0 ? { ref } : {},
|
|
1218
|
-
...
|
|
2489
|
+
...statuses !== void 0 ? { statuses } : {},
|
|
2490
|
+
...terminalOnly === true ? { terminalOnly } : {},
|
|
2491
|
+
...threadId !== void 0 ? { threadId } : {},
|
|
2492
|
+
...manual === true ? { manual } : {},
|
|
2493
|
+
// A batch request keeps the batch SHAPE even when the wait ends with a
|
|
2494
|
+
// single message, so the caller's field access does not depend on timing.
|
|
2495
|
+
...maxMessages > 1 ? { batch: true } : {}
|
|
1219
2496
|
});
|
|
1220
2497
|
this.waiters.set(peerId, list);
|
|
1221
2498
|
});
|
|
1222
2499
|
}
|
|
1223
2500
|
/** Create a message from `from` addressed to `to` and deliver it. `to` may
|
|
1224
2501
|
* be a peer id, {@link BROADCAST}, or a group id. */
|
|
1225
|
-
route(from, to, kind, content, ref, threadId) {
|
|
1226
|
-
const message = this.compose(from, to, kind, content, ref, threadId);
|
|
2502
|
+
route(from, to, kind, content, ref, threadId, expiresAt, system = false, priority) {
|
|
2503
|
+
const message = this.compose(from, to, kind, content, ref, threadId, expiresAt, system, priority);
|
|
1227
2504
|
this.dispatch(message);
|
|
1228
2505
|
return message;
|
|
1229
2506
|
}
|
|
@@ -1231,22 +2508,25 @@ var AgentHub = class {
|
|
|
1231
2508
|
* peer id, {@link BROADCAST}, or a group id). Composing and dispatching are
|
|
1232
2509
|
* separate steps because a caller may need ledger state to exist before
|
|
1233
2510
|
* anything reaches a recipient — {@link sendTask} books delivery times. */
|
|
1234
|
-
compose(from, to, kind, content, ref, threadId) {
|
|
1235
|
-
if (!this.lastSeen.has(from)) throw new Error(`sender not registered: ${from}`);
|
|
2511
|
+
compose(from, to, kind, content, ref, threadId, expiresAt, system = false, priority) {
|
|
2512
|
+
if (!system && !this.lastSeen.has(from)) throw new Error(`sender not registered: ${from}`);
|
|
1236
2513
|
const group = this.groups.get(to);
|
|
1237
|
-
|
|
2514
|
+
const known = this.lastSeen.has(to) || this.parkedAt.has(to);
|
|
2515
|
+
if (to !== BROADCAST && group === void 0 && !known) {
|
|
1238
2516
|
throw new Error(`unknown recipient: ${to} (registered peers: ${this.peers().join(", ") || "none"})`);
|
|
1239
2517
|
}
|
|
2518
|
+
if (group !== void 0 && !system && !group.members.includes(from)) {
|
|
2519
|
+
throw new Error(`peer '${from}' is not a member of group '${to}'`);
|
|
2520
|
+
}
|
|
1240
2521
|
let hop = 0;
|
|
1241
2522
|
if (ref !== void 0) {
|
|
1242
2523
|
const parent = this.historyRing.findLast((m) => m.id === ref);
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
throw new Error(`hop limit exceeded (max ${MAX_HOP}): start a new task/thread instead of extending this chain`);
|
|
1246
|
-
}
|
|
2524
|
+
const ceiling = kind === "task" && parent?.kind === "task" ? MAX_HOP : MAX_REPLY_CHAIN;
|
|
2525
|
+
hop = Math.min((parent?.hop ?? 0) + 1, ceiling);
|
|
1247
2526
|
}
|
|
1248
2527
|
const message = {
|
|
1249
2528
|
id: randomUUID(),
|
|
2529
|
+
seq: ++this.seqCounter,
|
|
1250
2530
|
from,
|
|
1251
2531
|
to,
|
|
1252
2532
|
kind,
|
|
@@ -1255,9 +2535,15 @@ var AgentHub = class {
|
|
|
1255
2535
|
...threadId !== void 0 ? { threadId } : {},
|
|
1256
2536
|
...group !== void 0 ? { channel: group.id } : {},
|
|
1257
2537
|
...hop > 0 ? { hop } : {},
|
|
2538
|
+
...expiresAt !== void 0 ? { expiresAt } : {},
|
|
2539
|
+
// Only a real priority is stored: an unset one must not appear on the wire,
|
|
2540
|
+
// or every reader has to distinguish 0 from "absent" for no reason.
|
|
2541
|
+
...priority !== void 0 ? { priority } : {},
|
|
1258
2542
|
ts: Date.now()
|
|
1259
2543
|
};
|
|
1260
|
-
this.lastSeen.set(from, message.ts);
|
|
2544
|
+
if (!system) this.lastSeen.set(from, message.ts);
|
|
2545
|
+
this.bumpTraffic(from, "sent");
|
|
2546
|
+
if (kind === "ack") this.bumpTraffic(from, "acked");
|
|
1261
2547
|
this.remember(message);
|
|
1262
2548
|
return message;
|
|
1263
2549
|
}
|
|
@@ -1265,7 +2551,7 @@ var AgentHub = class {
|
|
|
1265
2551
|
* or the single addressed peer. */
|
|
1266
2552
|
dispatch(message) {
|
|
1267
2553
|
if (message.to === BROADCAST) {
|
|
1268
|
-
for (const peer of this.
|
|
2554
|
+
for (const peer of this.audience()) {
|
|
1269
2555
|
if (peer !== message.from) this.deliver(peer, message);
|
|
1270
2556
|
}
|
|
1271
2557
|
return;
|
|
@@ -1283,26 +2569,43 @@ var AgentHub = class {
|
|
|
1283
2569
|
* History / onMessage are recorded by the caller (route / sendToGroup) —
|
|
1284
2570
|
* exactly once per message, never per fan-out target. */
|
|
1285
2571
|
deliver(target, message) {
|
|
2572
|
+
this.bumpTraffic(target, "received");
|
|
2573
|
+
if (message.expiresAt !== void 0 && message.expiresAt <= Date.now()) {
|
|
2574
|
+
const now = Date.now();
|
|
2575
|
+
this.countDrop(target, "expired", now, message);
|
|
2576
|
+
if (message.kind === "task") this.noteTaskDeliveryDropped(message, target, "expired", now);
|
|
2577
|
+
return;
|
|
2578
|
+
}
|
|
1286
2579
|
const list = this.waiters.get(target) ?? [];
|
|
1287
|
-
const index = list.findIndex((waiter) =>
|
|
1288
|
-
if (waiter.from !== void 0 && waiter.from !== message.from) return false;
|
|
1289
|
-
if (waiter.ref !== void 0 && !(message.kind === "ack" && message.ref === waiter.ref)) return false;
|
|
1290
|
-
if (waiter.threadId !== void 0 && message.threadId !== waiter.threadId) return false;
|
|
1291
|
-
return true;
|
|
1292
|
-
});
|
|
1293
|
-
if (message.kind === "task") this.markTaskDelivered(message.id, target, message.ts);
|
|
2580
|
+
const index = list.findIndex((waiter) => matchesWaiter(waiter, message, this.taskLedger));
|
|
1294
2581
|
if (index >= 0) {
|
|
2582
|
+
if (message.kind === "task") this.markTaskDelivered(message.id, target, message.ts);
|
|
1295
2583
|
const [waiter] = list.splice(index, 1);
|
|
1296
2584
|
this.waiters.set(target, list);
|
|
1297
2585
|
clearTimeout(waiter.timer);
|
|
1298
|
-
|
|
2586
|
+
const delivered = this.handOut(target, message, waiter.manual === true, message.ts);
|
|
2587
|
+
waiter.resolve(waiter.batch === true ? { type: "messages", messages: [delivered] } : { type: "message", message: delivered });
|
|
2588
|
+
return;
|
|
2589
|
+
}
|
|
2590
|
+
if (!this.takeToken(target, Date.now())) {
|
|
2591
|
+
const now = Date.now();
|
|
2592
|
+
this.countDrop(target, "rate", now, message);
|
|
2593
|
+
if (message.kind === "task") this.noteTaskDeliveryDropped(message, target, "rate", now);
|
|
1299
2594
|
return;
|
|
1300
2595
|
}
|
|
1301
2596
|
const queue = this.queues.get(target) ?? [];
|
|
1302
|
-
if (queue.length >= this.options.maxQueue)
|
|
1303
|
-
|
|
2597
|
+
if (queue.length >= this.options.maxQueue) {
|
|
2598
|
+
const [evicted] = queue.splice(lowestPriorityIndex(queue), 1);
|
|
2599
|
+
const now = Date.now();
|
|
2600
|
+
if (evicted !== void 0) this.leaseAttempts.delete(_AgentHub.leaseKey(target, evicted.id));
|
|
2601
|
+
this.countDrop(target, "overflow", now, evicted);
|
|
2602
|
+
if (evicted !== void 0 && evicted.kind === "task") this.noteTaskDeliveryDropped(evicted, target, "overflow", now);
|
|
2603
|
+
}
|
|
2604
|
+
insertByPriority(queue, [message]);
|
|
1304
2605
|
this.queues.set(target, queue);
|
|
2606
|
+
if (message.kind === "task") this.markTaskDelivered(message.id, target, message.ts);
|
|
1305
2607
|
this.options.onQueued?.(message, target);
|
|
2608
|
+
if (message.kind === "task") this.options.onTaskQueued?.(message, target);
|
|
1306
2609
|
}
|
|
1307
2610
|
/** Append a sent message to the history ring (and fire the persistence /
|
|
1308
2611
|
* relay hooks). Exactly one call per message — see route() / sendToGroup(). */
|
|
@@ -1315,11 +2618,29 @@ var AgentHub = class {
|
|
|
1315
2618
|
function importHop(value) {
|
|
1316
2619
|
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
|
|
1317
2620
|
}
|
|
2621
|
+
function insertByPriority(queue, messages) {
|
|
2622
|
+
for (const message of messages) {
|
|
2623
|
+
let at = queue.length;
|
|
2624
|
+
while (at > 0 && priorityOf(queue[at - 1]) < priorityOf(message)) at--;
|
|
2625
|
+
queue.splice(at, 0, message);
|
|
2626
|
+
}
|
|
2627
|
+
}
|
|
2628
|
+
function lowestPriorityIndex(queue) {
|
|
2629
|
+
if (queue.length === 0) return -1;
|
|
2630
|
+
const lowest = priorityOf(queue[queue.length - 1]);
|
|
2631
|
+
let victim = queue.length - 1;
|
|
2632
|
+
while (victim > 0 && priorityOf(queue[victim - 1]) === lowest) victim--;
|
|
2633
|
+
return victim;
|
|
2634
|
+
}
|
|
2635
|
+
function priorityOf(message) {
|
|
2636
|
+
const value = message.priority;
|
|
2637
|
+
return value === 1 || value === 2 ? value : 0;
|
|
2638
|
+
}
|
|
1318
2639
|
function drainFrom(queue, from) {
|
|
1319
2640
|
const kept = [];
|
|
1320
2641
|
const drained = [];
|
|
1321
2642
|
for (const message of queue) {
|
|
1322
|
-
if (message.from === from) drained.push(message);
|
|
2643
|
+
if (message.from === from || message.from === HUB_PEER) drained.push(message);
|
|
1323
2644
|
else kept.push(message);
|
|
1324
2645
|
}
|
|
1325
2646
|
queue.splice(0, queue.length, ...kept);
|
|
@@ -1329,6 +2650,41 @@ function omit(value, key) {
|
|
|
1329
2650
|
const { [key]: _dropped, ...rest } = value;
|
|
1330
2651
|
return rest;
|
|
1331
2652
|
}
|
|
2653
|
+
function matchesWaiter(waiter, message, ledger) {
|
|
2654
|
+
const fromHub = message.from === HUB_PEER;
|
|
2655
|
+
if (!fromHub && waiter.from !== void 0 && message.from !== waiter.from) return false;
|
|
2656
|
+
if (!fromHub && waiter.ref !== void 0) {
|
|
2657
|
+
if (message.ref !== waiter.ref) return false;
|
|
2658
|
+
if (message.kind !== "ack" && message.kind !== "chat") return false;
|
|
2659
|
+
if (message.kind === "chat") {
|
|
2660
|
+
const record = ledger.get(waiter.ref);
|
|
2661
|
+
if (record !== void 0 && record.from !== message.from && !record.assignees.some((assignee) => assignee.peerId === message.from)) return false;
|
|
2662
|
+
}
|
|
2663
|
+
if (waiter.statuses !== void 0 || waiter.terminalOnly === true) {
|
|
2664
|
+
const status = ackStatusOf(message);
|
|
2665
|
+
if (status === void 0) return false;
|
|
2666
|
+
if (waiter.statuses !== void 0 && !waiter.statuses.includes(status)) return false;
|
|
2667
|
+
if (waiter.terminalOnly === true && !TERMINAL_TASK_STATUSES.includes(ackToTaskStatus(status))) return false;
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
if (waiter.threadId !== void 0 && message.threadId !== waiter.threadId) return false;
|
|
2671
|
+
return true;
|
|
2672
|
+
}
|
|
2673
|
+
function ackStatusOf(message) {
|
|
2674
|
+
if (message.kind !== "ack") return void 0;
|
|
2675
|
+
const decoded = decodeContent("ack", message.content);
|
|
2676
|
+
if (typeof decoded === "string") return void 0;
|
|
2677
|
+
const status = decoded.status;
|
|
2678
|
+
if (typeof status !== "string") return void 0;
|
|
2679
|
+
return ALL_ACK_STATUSES.includes(status) ? status : void 0;
|
|
2680
|
+
}
|
|
2681
|
+
function syntheticEventId(taskId, reason) {
|
|
2682
|
+
if (reason === "expired") return `expired-${taskId}`;
|
|
2683
|
+
if (reason === "dead-letter") return `dead-letter-${taskId}`;
|
|
2684
|
+
if (reason === "dead-letter-evicted") return `evicted-${taskId}`;
|
|
2685
|
+
if (reason === "unregistered") return `unregistered-${taskId}`;
|
|
2686
|
+
return `dropped-${taskId}`;
|
|
2687
|
+
}
|
|
1332
2688
|
|
|
1333
2689
|
// src/auth.ts
|
|
1334
2690
|
import { randomBytes } from "node:crypto";
|
|
@@ -1336,6 +2692,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSyn
|
|
|
1336
2692
|
import { dirname } from "node:path";
|
|
1337
2693
|
var ANON_JOIN_PEER = "__join__";
|
|
1338
2694
|
var TOKEN_PATTERN = /^[A-Za-z0-9._:-]{16,128}$/;
|
|
2695
|
+
var PLACEHOLDER_TOKEN = /CHANGE[-_]?ME/i;
|
|
1339
2696
|
function loadTokenFile(file) {
|
|
1340
2697
|
let parsed;
|
|
1341
2698
|
try {
|
|
@@ -1354,7 +2711,10 @@ function loadTokenFile(file) {
|
|
|
1354
2711
|
if (typeof token !== "string" || !TOKEN_PATTERN.test(token)) {
|
|
1355
2712
|
throw new Error(msg("has an invalid token (expect 16-128 chars of [A-Za-z0-9._:-])"));
|
|
1356
2713
|
}
|
|
1357
|
-
if (
|
|
2714
|
+
if (PLACEHOLDER_TOKEN.test(token)) {
|
|
2715
|
+
throw new Error(msg("uses the example placeholder token \u2014 generate one with `agent-comm-hub auth gen`"));
|
|
2716
|
+
}
|
|
2717
|
+
if (typeof peer !== "string" || !PEER_ID_PATTERN.test(peer) || peer === BROADCAST || peer === HUB_PEER) {
|
|
1358
2718
|
throw new Error(msg(`has an invalid peer id '${String(peer)}'`));
|
|
1359
2719
|
}
|
|
1360
2720
|
if (role !== "agent" && role !== "manager") {
|
|
@@ -1369,8 +2729,19 @@ function loadTokenFile(file) {
|
|
|
1369
2729
|
peers.add(peer);
|
|
1370
2730
|
});
|
|
1371
2731
|
if (table.size === 0) throw new Error(`auth token file ${file}: no tokens defined`);
|
|
2732
|
+
warnIfTokenFileIsReadableByOthers(file);
|
|
1372
2733
|
return table;
|
|
1373
2734
|
}
|
|
2735
|
+
function warnIfTokenFileIsReadableByOthers(file) {
|
|
2736
|
+
if (process.platform === "win32") return;
|
|
2737
|
+
try {
|
|
2738
|
+
const mode = statSync(file).mode & 511;
|
|
2739
|
+
if ((mode & 63) !== 0) {
|
|
2740
|
+
console.warn(`warning: ${file} is readable by group/other (mode ${mode.toString(8)}) \u2014 chmod 600 it`);
|
|
2741
|
+
}
|
|
2742
|
+
} catch {
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
1374
2745
|
function watchTokenFile(file, log2) {
|
|
1375
2746
|
let table = loadTokenFile(file);
|
|
1376
2747
|
const reload = () => {
|
|
@@ -1461,7 +2832,10 @@ function loadTokenFileVoid(rows) {
|
|
|
1461
2832
|
const peers = /* @__PURE__ */ new Set();
|
|
1462
2833
|
for (const { token, peer, role, owner } of rows) {
|
|
1463
2834
|
if (!TOKEN_PATTERN.test(token)) throw new Error(`invalid token for peer '${peer}'`);
|
|
1464
|
-
if (
|
|
2835
|
+
if (PLACEHOLDER_TOKEN.test(token)) {
|
|
2836
|
+
throw new Error(`example placeholder token for peer '${peer}' \u2014 generate one with \`agent-comm-hub auth gen\``);
|
|
2837
|
+
}
|
|
2838
|
+
if (!PEER_ID_PATTERN.test(peer) || peer === BROADCAST || peer === HUB_PEER) throw new Error(`invalid peer id '${peer}'`);
|
|
1465
2839
|
if (role !== "agent" && role !== "manager") throw new Error(`invalid role '${role}'`);
|
|
1466
2840
|
if (table.has(token)) throw new Error("duplicate token");
|
|
1467
2841
|
if (peers.has(peer)) throw new Error(`duplicate peer '${peer}'`);
|
|
@@ -1480,6 +2854,9 @@ function present(message) {
|
|
|
1480
2854
|
...channel !== void 0 ? { channel } : {},
|
|
1481
2855
|
...threadId !== void 0 ? { threadId } : {},
|
|
1482
2856
|
...hop !== void 0 ? { hop } : {},
|
|
2857
|
+
// A2A speaks `taskId` / `contextId`; our names stay, these ride along.
|
|
2858
|
+
...message.kind === "ack" && ref !== void 0 ? { taskId: ref } : {},
|
|
2859
|
+
...threadId !== void 0 ? { contextId: threadId } : {},
|
|
1483
2860
|
content: decodeContent(message.kind, message.content)
|
|
1484
2861
|
};
|
|
1485
2862
|
}
|
|
@@ -1500,12 +2877,13 @@ function autoRegisterPeer(hub, registry, sessionId, clientName, clientVersion) {
|
|
|
1500
2877
|
if (bound !== void 0) return bound;
|
|
1501
2878
|
if (registry.isSuppressed(sessionId)) return void 0;
|
|
1502
2879
|
const tokenPeer = registry.tokenFor(sessionId)?.peer;
|
|
1503
|
-
const
|
|
2880
|
+
const derived = tokenPeer === ANON_JOIN_PEER ? `join-${sanitizePeerId(clientName ?? "agent")}-${Math.random().toString(36).slice(2, 6)}` : tokenPeer ?? sanitizePeerId(clientName ?? "agent");
|
|
2881
|
+
const peerId = derived === BROADCAST || derived === HUB_PEER || hub.groupOf(derived) !== void 0 ? `agent-${Math.random().toString(36).slice(2, 6)}` : derived;
|
|
1504
2882
|
if (!hub.has(peerId)) {
|
|
1505
2883
|
hub.register(peerId, {
|
|
1506
2884
|
...clientName !== void 0 ? { name: clientName } : {},
|
|
1507
2885
|
...clientVersion !== void 0 ? { version: clientVersion } : {}
|
|
1508
|
-
});
|
|
2886
|
+
}, { reclaim: true });
|
|
1509
2887
|
}
|
|
1510
2888
|
registry.bindPeer(sessionId, peerId);
|
|
1511
2889
|
hub.touch(peerId);
|
|
@@ -1544,13 +2922,29 @@ function rosterFor(hub, registry) {
|
|
|
1544
2922
|
...alias !== void 0 ? { alias } : {},
|
|
1545
2923
|
...clientName !== void 0 ? { clientName } : {},
|
|
1546
2924
|
...clientVersion !== void 0 ? { clientVersion } : {},
|
|
2925
|
+
// The announced card rides with the roster: `bridge_peers` is how an agent
|
|
2926
|
+
// sees who else is here, and a card nobody can read is not announced.
|
|
2927
|
+
...profile?.card !== void 0 ? { card: profile.card } : {},
|
|
1547
2928
|
...peerAnon.get(peer.id) === true ? { anonymous: true } : {},
|
|
1548
2929
|
...ips !== void 0 && ips.length > 0 ? { clientIps: ips } : {},
|
|
1549
2930
|
connected: peer.connected,
|
|
2931
|
+
// W7: keep the reachability verdict and the queue depth in the tool output —
|
|
2932
|
+
// `connected: false` alone cannot say "idle, will read it later" apart from
|
|
2933
|
+
// "gone, and your message is nowhere".
|
|
2934
|
+
reachable: peer.reachable,
|
|
2935
|
+
queued: peer.queued,
|
|
1550
2936
|
lastSeenMs: peer.lastSeenMs
|
|
1551
2937
|
};
|
|
1552
2938
|
});
|
|
1553
2939
|
}
|
|
2940
|
+
var MAX_LEASE_IDS = 1e3;
|
|
2941
|
+
function isManagerCaller(registry, sessionId, peer, options) {
|
|
2942
|
+
if (registry.tokenFor(sessionId)?.role === "manager") return true;
|
|
2943
|
+
if (options.managerTokenRequired === true) return registry.isManagerSession(sessionId);
|
|
2944
|
+
const managers = options.managerPeers ?? "all";
|
|
2945
|
+
if (managers === "all") return true;
|
|
2946
|
+
return peer !== void 0 && managers.has(peer);
|
|
2947
|
+
}
|
|
1554
2948
|
function hubTools(hub, registry, options) {
|
|
1555
2949
|
const schema = (properties, required = []) => ({
|
|
1556
2950
|
type: "object",
|
|
@@ -1561,6 +2955,108 @@ function hubTools(hub, registry, options) {
|
|
|
1561
2955
|
const str = (description) => ({ type: "string", description });
|
|
1562
2956
|
const int = (description) => ({ type: "integer", description });
|
|
1563
2957
|
const optStr = str;
|
|
2958
|
+
const priorityField = () => ({
|
|
2959
|
+
type: "integer",
|
|
2960
|
+
enum: [0, 1, 2],
|
|
2961
|
+
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."
|
|
2962
|
+
});
|
|
2963
|
+
const optPriority = (value) => value === 0 || value === 1 || value === 2 ? { priority: value } : {};
|
|
2964
|
+
const idList = (value, tool) => {
|
|
2965
|
+
if (!Array.isArray(value)) throw new Error(`${tool} expects ids: an array of message ids`);
|
|
2966
|
+
if (value.length > MAX_LEASE_IDS) {
|
|
2967
|
+
throw new Error(`${tool} accepts at most ${MAX_LEASE_IDS} ids per call (got ${value.length}); commit or nack in batches`);
|
|
2968
|
+
}
|
|
2969
|
+
const ids = value.filter((id) => typeof id === "string" && id !== "");
|
|
2970
|
+
if (ids.length === 0) throw new Error(`${tool} expects at least one message id`);
|
|
2971
|
+
return ids;
|
|
2972
|
+
};
|
|
2973
|
+
const ackStatuses = (value, terminalOnly) => {
|
|
2974
|
+
if (value === void 0) return void 0;
|
|
2975
|
+
if (!Array.isArray(value)) throw new Error("statuses must be an array of ack statuses");
|
|
2976
|
+
if (value.length === 0) throw new Error("statuses must not be empty \u2014 omit it to wait for any ack");
|
|
2977
|
+
const out = [];
|
|
2978
|
+
for (const entry of value) {
|
|
2979
|
+
if (typeof entry !== "string" || !ALL_ACK_STATUSES.includes(entry)) {
|
|
2980
|
+
throw new Error(`invalid statuses entry: ${JSON.stringify(entry)} (expected one of ${ALL_ACK_STATUSES.join(" | ")})`);
|
|
2981
|
+
}
|
|
2982
|
+
out.push(entry);
|
|
2983
|
+
}
|
|
2984
|
+
if (terminalOnly) {
|
|
2985
|
+
const terminalAcks = TERMINAL_TASK_STATUSES.filter((status) => ALL_ACK_STATUSES.includes(status));
|
|
2986
|
+
if (!out.some((status) => terminalAcks.includes(ackToTaskStatus(status)))) {
|
|
2987
|
+
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`);
|
|
2988
|
+
}
|
|
2989
|
+
}
|
|
2990
|
+
return out;
|
|
2991
|
+
};
|
|
2992
|
+
const deadline = (value) => {
|
|
2993
|
+
const at = Number(value);
|
|
2994
|
+
if (!Number.isFinite(at) || at <= 0) throw new Error(`invalid expiresAt: ${String(value)} (expected epoch milliseconds)`);
|
|
2995
|
+
if (at <= Date.now()) throw new Error(`expiresAt is already in the past: ${new Date(at).toISOString()}`);
|
|
2996
|
+
return at;
|
|
2997
|
+
};
|
|
2998
|
+
const parseArtifacts = (value) => {
|
|
2999
|
+
if (value === void 0) return void 0;
|
|
3000
|
+
if (!Array.isArray(value)) throw new Error("artifacts must be an array of {name, text?/url?} objects");
|
|
3001
|
+
const out = [];
|
|
3002
|
+
for (const [index, entry] of value.entries()) {
|
|
3003
|
+
if (typeof entry !== "object" || entry === null) throw new Error(`artifacts[${index}] must be an object`);
|
|
3004
|
+
const raw = entry;
|
|
3005
|
+
if (typeof raw.name !== "string" || raw.name === "") throw new Error(`artifacts[${index}].name is required`);
|
|
3006
|
+
const artifact = { name: raw.name };
|
|
3007
|
+
if (typeof raw.mimeType === "string" && raw.mimeType !== "") artifact.mimeType = raw.mimeType;
|
|
3008
|
+
if (typeof raw.text === "string") artifact.text = raw.text;
|
|
3009
|
+
if (typeof raw.url === "string" && raw.url !== "") artifact.url = raw.url;
|
|
3010
|
+
if (artifact.text === void 0 && artifact.url === void 0) {
|
|
3011
|
+
throw new Error(`artifacts[${index}] needs text or url \u2014 an artifact with neither says nothing`);
|
|
3012
|
+
}
|
|
3013
|
+
out.push(artifact);
|
|
3014
|
+
}
|
|
3015
|
+
return out.length > 0 ? out : void 0;
|
|
3016
|
+
};
|
|
3017
|
+
const parseCard = (value) => {
|
|
3018
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("card must be an object");
|
|
3019
|
+
const raw = value;
|
|
3020
|
+
const card = {};
|
|
3021
|
+
if (raw.skills !== void 0) {
|
|
3022
|
+
if (!Array.isArray(raw.skills)) throw new Error("card.skills must be an array");
|
|
3023
|
+
card.skills = raw.skills.map((entry, index) => {
|
|
3024
|
+
if (typeof entry !== "object" || entry === null) throw new Error(`card.skills[${index}] must be an object`);
|
|
3025
|
+
const skill = entry;
|
|
3026
|
+
if (typeof skill.id !== "string" || skill.id === "") throw new Error(`card.skills[${index}].id is required`);
|
|
3027
|
+
if (typeof skill.name !== "string" || skill.name === "") throw new Error(`card.skills[${index}].name is required`);
|
|
3028
|
+
return {
|
|
3029
|
+
id: skill.id,
|
|
3030
|
+
name: skill.name,
|
|
3031
|
+
...typeof skill.description === "string" ? { description: skill.description } : {},
|
|
3032
|
+
...Array.isArray(skill.tags) ? { tags: skill.tags.filter((tag) => typeof tag === "string") } : {}
|
|
3033
|
+
};
|
|
3034
|
+
});
|
|
3035
|
+
}
|
|
3036
|
+
if (raw.acceptsTasks !== void 0) {
|
|
3037
|
+
if (typeof raw.acceptsTasks !== "boolean") throw new Error("card.acceptsTasks must be a boolean");
|
|
3038
|
+
card.acceptsTasks = raw.acceptsTasks;
|
|
3039
|
+
}
|
|
3040
|
+
if (raw.concurrency !== void 0) {
|
|
3041
|
+
if (!Number.isInteger(raw.concurrency) || raw.concurrency < 0) throw new Error("card.concurrency must be a non-negative integer");
|
|
3042
|
+
card.concurrency = raw.concurrency;
|
|
3043
|
+
}
|
|
3044
|
+
for (const key of ["inputModes", "outputModes"]) {
|
|
3045
|
+
const list = raw[key];
|
|
3046
|
+
if (list === void 0) continue;
|
|
3047
|
+
if (!Array.isArray(list)) throw new Error(`card.${key} must be an array of strings`);
|
|
3048
|
+
card[key] = list.filter((entry) => typeof entry === "string");
|
|
3049
|
+
}
|
|
3050
|
+
if (raw.runner !== void 0) {
|
|
3051
|
+
if (!["herdr", "cli", "http", "none"].includes(String(raw.runner))) throw new Error("card.runner must be one of herdr | cli | http | none");
|
|
3052
|
+
card.runner = raw.runner;
|
|
3053
|
+
}
|
|
3054
|
+
if (raw.endpoint !== void 0) {
|
|
3055
|
+
if (typeof raw.endpoint !== "string" || raw.endpoint === "") throw new Error("card.endpoint must be a non-empty string");
|
|
3056
|
+
card.endpoint = raw.endpoint;
|
|
3057
|
+
}
|
|
3058
|
+
return card;
|
|
3059
|
+
};
|
|
1564
3060
|
const requirePeer = (sessionId) => {
|
|
1565
3061
|
const bound = registry.peerFor(sessionId);
|
|
1566
3062
|
if (bound !== void 0) {
|
|
@@ -1577,16 +3073,26 @@ function hubTools(hub, registry, options) {
|
|
|
1577
3073
|
const receipt = (message) => ({
|
|
1578
3074
|
ok: true,
|
|
1579
3075
|
id: message.id,
|
|
3076
|
+
// The sender needs this back: it is the cursor to record.
|
|
3077
|
+
...message.seq !== void 0 ? { seq: message.seq } : {},
|
|
1580
3078
|
from: message.from,
|
|
1581
3079
|
to: message.to,
|
|
1582
3080
|
kind: message.kind,
|
|
1583
3081
|
...message.ref !== void 0 ? { ref: message.ref } : {},
|
|
1584
3082
|
...message.channel !== void 0 ? { channel: message.channel } : {},
|
|
3083
|
+
// A2A aliases (additive): a task receipt answers with `taskId`, and a
|
|
3084
|
+
// threaded message carries its `contextId`.
|
|
3085
|
+
...message.kind === "task" ? { taskId: message.id } : {},
|
|
3086
|
+
...message.threadId !== void 0 ? { contextId: message.threadId } : {},
|
|
1585
3087
|
...message.threadId !== void 0 ? { threadId: message.threadId } : {},
|
|
1586
3088
|
...message.hop !== void 0 ? { hop: message.hop } : {},
|
|
1587
3089
|
ts: message.ts
|
|
1588
3090
|
});
|
|
1589
|
-
const presentWait = (result) =>
|
|
3091
|
+
const presentWait = (result) => {
|
|
3092
|
+
if (result.type === "timeout") return result;
|
|
3093
|
+
if (result.type === "messages") return { type: "messages", messages: result.messages.map(present) };
|
|
3094
|
+
return { type: "message", message: present(result.message) };
|
|
3095
|
+
};
|
|
1590
3096
|
const checkControl = (peer) => {
|
|
1591
3097
|
const herdr = options.herdr;
|
|
1592
3098
|
if (herdr === void 0) {
|
|
@@ -1599,17 +3105,27 @@ function hubTools(hub, registry, options) {
|
|
|
1599
3105
|
return herdr;
|
|
1600
3106
|
};
|
|
1601
3107
|
const requireManager = (peer, action, sessionId) => {
|
|
1602
|
-
if (registry
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
}
|
|
3108
|
+
if (isManagerCaller(registry, sessionId, peer, options)) return;
|
|
3109
|
+
throw new Error(
|
|
3110
|
+
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`
|
|
3111
|
+
);
|
|
1607
3112
|
};
|
|
1608
3113
|
const asStatuses = (value) => {
|
|
1609
3114
|
if (!Array.isArray(value)) return void 0;
|
|
1610
3115
|
const statuses = value.map(String).filter((status) => AGENT_STATUSES.includes(status));
|
|
1611
3116
|
return statuses.length > 0 ? statuses : void 0;
|
|
1612
3117
|
};
|
|
3118
|
+
const requireArgs = (tool, handler) => {
|
|
3119
|
+
const required = tool.inputSchema.required ?? [];
|
|
3120
|
+
if (required.length === 0) return handler;
|
|
3121
|
+
return async (args, sessionId) => {
|
|
3122
|
+
const missing = required.filter((name) => args?.[name] === void 0);
|
|
3123
|
+
if (missing.length > 0) {
|
|
3124
|
+
throw new Error(`missing required argument(s) for ${tool.name}: ${missing.join(", ")}`);
|
|
3125
|
+
}
|
|
3126
|
+
return handler(args, sessionId);
|
|
3127
|
+
};
|
|
3128
|
+
};
|
|
1613
3129
|
const wrap = (peerAware, handler) => async (args, sessionId) => {
|
|
1614
3130
|
const peer = peerAware ? requirePeer(sessionId) : "";
|
|
1615
3131
|
return handler(args, peer, sessionId);
|
|
@@ -1623,13 +3139,20 @@ function hubTools(hub, registry, options) {
|
|
|
1623
3139
|
alias: optStr("Optional display name (1-64 chars, spaces/CJK allowed). Routing still uses peerId.")
|
|
1624
3140
|
}, ["peerId"]),
|
|
1625
3141
|
handler: async (args, sessionId) => {
|
|
1626
|
-
const
|
|
3142
|
+
const boundId = registry.peerFor(sessionId);
|
|
3143
|
+
const peerId = args.peerId === void 0 ? boundId : String(args.peerId);
|
|
3144
|
+
if (peerId === void 0) {
|
|
3145
|
+
throw new Error('no peer to register \u2014 pass peerId (e.g. {"peerId":"mavis"}); this session is not bound to a peer yet');
|
|
3146
|
+
}
|
|
1627
3147
|
if (!PEER_ID_PATTERN.test(peerId)) {
|
|
1628
3148
|
throw new Error(`invalid peerId: ${peerId} (expected [A-Za-z0-9._:-]{1,64})`);
|
|
1629
3149
|
}
|
|
1630
3150
|
if (peerId === BROADCAST) {
|
|
1631
3151
|
throw new Error(`reserved peer id: ${peerId} (it is the broadcast address)`);
|
|
1632
3152
|
}
|
|
3153
|
+
if (peerId === HUB_PEER) {
|
|
3154
|
+
throw new Error(`reserved peer id: ${peerId} (the hub uses it for its own notices)`);
|
|
3155
|
+
}
|
|
1633
3156
|
const alias = args.alias === void 0 ? void 0 : sanitizeAlias(String(args.alias));
|
|
1634
3157
|
const tokenPeer = registry.tokenFor(sessionId)?.peer;
|
|
1635
3158
|
if (tokenPeer !== void 0 && peerId !== tokenPeer) {
|
|
@@ -1639,6 +3162,9 @@ function hubTools(hub, registry, options) {
|
|
|
1639
3162
|
throw new Error(`peer already registered by another connection: ${peerId}`);
|
|
1640
3163
|
}
|
|
1641
3164
|
const current = registry.peerFor(sessionId);
|
|
3165
|
+
if (hub.ownsMailbox(peerId) && current !== peerId && registry.attachedCount(peerId) > 0) {
|
|
3166
|
+
throw new Error(`peer id '${peerId}' is parked but still attached to another connection: it keeps its mailbox and is still addressable`);
|
|
3167
|
+
}
|
|
1642
3168
|
if (current !== void 0 && current !== peerId) {
|
|
1643
3169
|
if (registry.attachedCount(current) === 1) {
|
|
1644
3170
|
hub.renamePeer(current, peerId);
|
|
@@ -1648,8 +3174,8 @@ function hubTools(hub, registry, options) {
|
|
|
1648
3174
|
if (registry.attachedCount(current) === 0) hub.unregister(current);
|
|
1649
3175
|
}
|
|
1650
3176
|
}
|
|
1651
|
-
if (!hub.has(peerId)) hub.register(peerId);
|
|
1652
3177
|
registry.bindPeer(sessionId, peerId);
|
|
3178
|
+
if (!hub.has(peerId)) hub.register(peerId, void 0, { reclaim: true });
|
|
1653
3179
|
registry.clearSuppress(sessionId);
|
|
1654
3180
|
hub.touch(peerId);
|
|
1655
3181
|
if (alias !== void 0) hub.setAlias(peerId, alias);
|
|
@@ -1677,7 +3203,7 @@ function hubTools(hub, registry, options) {
|
|
|
1677
3203
|
if (caller === void 0) throw new Error("not registered \u2014 call bridge_register(peerId) first");
|
|
1678
3204
|
const target = String(args.peer);
|
|
1679
3205
|
requireManager(caller, `kicking '${target}'`, sessionId);
|
|
1680
|
-
if (!hub.has(target)) {
|
|
3206
|
+
if (!hub.has(target) && !hub.isParked(target)) {
|
|
1681
3207
|
return { ok: true, peerId: null, kicked: false };
|
|
1682
3208
|
}
|
|
1683
3209
|
hub.unregister(target);
|
|
@@ -1687,7 +3213,7 @@ function hubTools(hub, registry, options) {
|
|
|
1687
3213
|
},
|
|
1688
3214
|
{
|
|
1689
3215
|
name: "bridge_rename",
|
|
1690
|
-
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).",
|
|
3216
|
+
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).",
|
|
1691
3217
|
inputSchema: schema({
|
|
1692
3218
|
alias: optStr("New display name (1-64 chars, spaces/CJK allowed; empty string clears back to no alias)."),
|
|
1693
3219
|
peerId: optStr("New routing id for `peer` \u2014 a true rename that moves all state (manager only). Target must be a registered peer."),
|
|
@@ -1699,17 +3225,26 @@ function hubTools(hub, registry, options) {
|
|
|
1699
3225
|
if (!hasAlias && !hasPeerId) {
|
|
1700
3226
|
throw new Error("nothing to rename: pass alias and/or peerId");
|
|
1701
3227
|
}
|
|
3228
|
+
if (hasPeerId && args.peer === void 0) {
|
|
3229
|
+
throw new Error("peerId requires peer \u2014 to change your own id, call bridge_register(newId)");
|
|
3230
|
+
}
|
|
3231
|
+
const tokenPeer = registry.tokenFor(sessionId)?.peer;
|
|
3232
|
+
if (hasPeerId && tokenPeer !== void 0) {
|
|
3233
|
+
requireManager(peer, `re-keying '${args.peer === void 0 ? peer : String(args.peer)}'`, sessionId);
|
|
3234
|
+
}
|
|
1702
3235
|
let target = args.peer === void 0 ? peer : String(args.peer);
|
|
1703
3236
|
if (target !== peer) requireManager(peer, `renaming '${target}'`, sessionId);
|
|
1704
3237
|
let previousId;
|
|
1705
3238
|
if (hasPeerId) {
|
|
1706
|
-
if (args.peer === void 0) {
|
|
1707
|
-
throw new Error("peerId requires peer \u2014 to change your own id, call bridge_register(newId)");
|
|
1708
|
-
}
|
|
1709
3239
|
const newId = String(args.peerId);
|
|
1710
3240
|
if (!PEER_ID_PATTERN.test(newId)) {
|
|
1711
3241
|
throw new Error(`invalid peerId: ${newId} (expected [A-Za-z0-9._:-]{1,64})`);
|
|
1712
3242
|
}
|
|
3243
|
+
const boundPeers = new Set(options.tokenPeers?.() ?? []);
|
|
3244
|
+
for (const identity of registry.tokenBindings.values()) boundPeers.add(identity.peer);
|
|
3245
|
+
if (boundPeers.has(newId) && newId !== tokenPeer) {
|
|
3246
|
+
throw new Error(`peerId '${newId}' is bound to an access token \u2014 a token's identity cannot be reassigned by a rename`);
|
|
3247
|
+
}
|
|
1713
3248
|
previousId = target;
|
|
1714
3249
|
hub.renamePeer(target, newId);
|
|
1715
3250
|
registry.rebindPeerId(target, newId);
|
|
@@ -1725,32 +3260,67 @@ function hubTools(hub, registry, options) {
|
|
|
1725
3260
|
},
|
|
1726
3261
|
{
|
|
1727
3262
|
name: "bridge_chat",
|
|
1728
|
-
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.',
|
|
3263
|
+
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.',
|
|
1729
3264
|
inputSchema: schema(
|
|
1730
3265
|
{
|
|
1731
|
-
to: str('Target peerId, group id, or "all" to broadcast.'),
|
|
3266
|
+
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.'),
|
|
1732
3267
|
message: str("The message text."),
|
|
1733
3268
|
threadId: optStr("Optional conversation / workflow thread id."),
|
|
1734
|
-
|
|
3269
|
+
priority: priorityField(),
|
|
3270
|
+
ref: optStr("Optional reply-to message id."),
|
|
3271
|
+
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.")
|
|
1735
3272
|
},
|
|
1736
3273
|
["to", "message"]
|
|
1737
3274
|
),
|
|
1738
3275
|
handler: wrap(true, async (args, peer) => receipt(hub.send(peer, String(args.to), "chat", String(args.message), {
|
|
1739
3276
|
...args.threadId !== void 0 ? { threadId: String(args.threadId) } : {},
|
|
1740
|
-
...
|
|
3277
|
+
...optPriority(args.priority),
|
|
3278
|
+
...args.ref !== void 0 ? { ref: String(args.ref) } : {},
|
|
3279
|
+
...args.expiresAt !== void 0 ? { expiresAt: deadline(args.expiresAt) } : {}
|
|
1741
3280
|
})))
|
|
1742
3281
|
},
|
|
3282
|
+
{
|
|
3283
|
+
name: "bridge_notice",
|
|
3284
|
+
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.',
|
|
3285
|
+
inputSchema: schema(
|
|
3286
|
+
{
|
|
3287
|
+
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.'),
|
|
3288
|
+
message: str("The notice text."),
|
|
3289
|
+
level: { type: "string", enum: ["info", "warn", "error"], description: "Severity (default info)." },
|
|
3290
|
+
threadId: optStr("Optional conversation / workflow thread id."),
|
|
3291
|
+
priority: priorityField()
|
|
3292
|
+
},
|
|
3293
|
+
["to", "message"]
|
|
3294
|
+
),
|
|
3295
|
+
handler: wrap(true, async (args, peer) => {
|
|
3296
|
+
const level = args.level === void 0 ? void 0 : String(args.level);
|
|
3297
|
+
if (level !== void 0 && level !== "info" && level !== "warn" && level !== "error") {
|
|
3298
|
+
throw new Error(`invalid level: ${level} (expected info | warn | error)`);
|
|
3299
|
+
}
|
|
3300
|
+
const payload = {
|
|
3301
|
+
message: String(args.message),
|
|
3302
|
+
...level !== void 0 ? { level } : {}
|
|
3303
|
+
};
|
|
3304
|
+
return receipt(hub.send(peer, String(args.to), "notice", encodeContent(payload), {
|
|
3305
|
+
...args.threadId !== void 0 ? { threadId: String(args.threadId) } : {},
|
|
3306
|
+
...optPriority(args.priority)
|
|
3307
|
+
}));
|
|
3308
|
+
})
|
|
3309
|
+
},
|
|
1743
3310
|
{
|
|
1744
3311
|
name: "bridge_task",
|
|
1745
|
-
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
|
|
3312
|
+
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).',
|
|
1746
3313
|
inputSchema: schema(
|
|
1747
3314
|
{
|
|
1748
|
-
to: str('Target peerId, group id, or "all" to broadcast.'),
|
|
3315
|
+
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.'),
|
|
1749
3316
|
prompt: str("What the receiving agent should do."),
|
|
1750
3317
|
context: optStr("Optional background information for the task."),
|
|
1751
3318
|
deliverable: optStr("Optional expected deliverable description."),
|
|
1752
3319
|
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."),
|
|
1753
|
-
threadId: optStr("Optional conversation / workflow thread id.")
|
|
3320
|
+
threadId: optStr("Optional conversation / workflow thread id."),
|
|
3321
|
+
priority: priorityField(),
|
|
3322
|
+
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)."),
|
|
3323
|
+
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.")
|
|
1754
3324
|
},
|
|
1755
3325
|
["to", "prompt"]
|
|
1756
3326
|
),
|
|
@@ -1759,8 +3329,9 @@ function hubTools(hub, registry, options) {
|
|
|
1759
3329
|
...args.context !== void 0 ? { context: String(args.context) } : {},
|
|
1760
3330
|
...args.deliverable !== void 0 ? { deliverable: String(args.deliverable) } : {},
|
|
1761
3331
|
...args.timeoutMs !== void 0 ? { timeoutMs: Number(args.timeoutMs) } : {},
|
|
1762
|
-
...args.threadId !== void 0 ? { threadId: String(args.threadId) } : {}
|
|
1763
|
-
|
|
3332
|
+
...args.threadId !== void 0 ? { threadId: String(args.threadId) } : {},
|
|
3333
|
+
...optPriority(args.priority)
|
|
3334
|
+
}, args.ref === void 0 ? void 0 : String(args.ref), args.expiresAt === void 0 ? void 0 : deadline(args.expiresAt))))
|
|
1764
3335
|
},
|
|
1765
3336
|
{
|
|
1766
3337
|
name: "bridge_ack",
|
|
@@ -1768,31 +3339,34 @@ function hubTools(hub, registry, options) {
|
|
|
1768
3339
|
inputSchema: schema(
|
|
1769
3340
|
{
|
|
1770
3341
|
ref: str("The id of the message being acknowledged."),
|
|
1771
|
-
status: { type: "string", enum: [
|
|
3342
|
+
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." },
|
|
1772
3343
|
note: optStr("Optional explanation for the acknowledgement."),
|
|
3344
|
+
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" } },
|
|
1773
3345
|
progress: int("Optional 0-100 progress (meaningful with status=working).")
|
|
1774
3346
|
},
|
|
1775
3347
|
["ref", "status"]
|
|
1776
3348
|
),
|
|
1777
3349
|
handler: wrap(true, async (args, peer) => {
|
|
1778
3350
|
const status = String(args.status);
|
|
1779
|
-
const valid =
|
|
3351
|
+
const valid = CLIENT_ACK_STATUSES;
|
|
1780
3352
|
if (!valid.includes(status)) {
|
|
1781
3353
|
throw new Error(`invalid ack status: ${status} (expected ${valid.join(" | ")})`);
|
|
1782
3354
|
}
|
|
3355
|
+
const artifacts = parseArtifacts(args.artifacts);
|
|
1783
3356
|
return receipt(hub.sendAck(peer, String(args.ref), {
|
|
1784
3357
|
status,
|
|
1785
3358
|
...args.note !== void 0 ? { note: String(args.note) } : {},
|
|
3359
|
+
...artifacts !== void 0 ? { artifacts } : {},
|
|
1786
3360
|
...args.progress !== void 0 ? { progress: Number(args.progress) } : {}
|
|
1787
3361
|
}));
|
|
1788
3362
|
})
|
|
1789
3363
|
},
|
|
1790
3364
|
{
|
|
1791
3365
|
name: "bridge_tasks",
|
|
1792
|
-
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.",
|
|
3366
|
+
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.",
|
|
1793
3367
|
inputSchema: schema({
|
|
1794
3368
|
role: { type: "string", enum: ["sent", "received", "all"], description: "Which side of the task to list (default all)." },
|
|
1795
|
-
status: { type: "string", enum: [
|
|
3369
|
+
status: { type: "string", enum: [...ALL_TASK_STATUSES], description: "Only tasks whose current ledger status matches." },
|
|
1796
3370
|
peer: optStr('Manager only: "all" or another peerId for the admin board.'),
|
|
1797
3371
|
limit: int("How many tasks to return (default 50).")
|
|
1798
3372
|
}),
|
|
@@ -1802,14 +3376,15 @@ function hubTools(hub, registry, options) {
|
|
|
1802
3376
|
throw new Error(`invalid role: ${role} (expected sent | received | all)`);
|
|
1803
3377
|
}
|
|
1804
3378
|
const status = args.status === void 0 ? void 0 : String(args.status);
|
|
1805
|
-
const validStatus =
|
|
3379
|
+
const validStatus = ALL_TASK_STATUSES;
|
|
1806
3380
|
if (status !== void 0 && !validStatus.includes(status)) {
|
|
1807
3381
|
throw new Error(`invalid status: ${status} (expected ${validStatus.join(" | ")})`);
|
|
1808
3382
|
}
|
|
1809
3383
|
let target = peer;
|
|
1810
3384
|
if (args.peer !== void 0) {
|
|
1811
3385
|
target = String(args.peer);
|
|
1812
|
-
if (target
|
|
3386
|
+
if (target === BROADCAST) requireManager(peer, "listing the full task ledger", sessionId);
|
|
3387
|
+
else if (target !== peer) requireManager(peer, `listing tasks of '${target}'`, sessionId);
|
|
1813
3388
|
}
|
|
1814
3389
|
const tasks = hub.listTasks(target === "all" ? "all" : target, {
|
|
1815
3390
|
...role !== void 0 ? { role } : {},
|
|
@@ -1821,7 +3396,7 @@ function hubTools(hub, registry, options) {
|
|
|
1821
3396
|
},
|
|
1822
3397
|
{
|
|
1823
3398
|
name: "bridge_task_status",
|
|
1824
|
-
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.",
|
|
3399
|
+
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.",
|
|
1825
3400
|
inputSchema: schema({ ref: str("Task message id (the id returned by bridge_task, also used as ack ref).") }, ["ref"]),
|
|
1826
3401
|
handler: wrap(true, async (args, peer, sessionId) => {
|
|
1827
3402
|
const ref = String(args.ref);
|
|
@@ -1832,17 +3407,97 @@ function hubTools(hub, registry, options) {
|
|
|
1832
3407
|
if (task.from !== peer && task.to !== peer && task.to !== BROADCAST && !isAssignee && !isGroupMember) {
|
|
1833
3408
|
requireManager(peer, `reading task '${ref}'`, sessionId);
|
|
1834
3409
|
}
|
|
1835
|
-
return {
|
|
3410
|
+
return {
|
|
3411
|
+
task,
|
|
3412
|
+
// A2A naming aliases: the same task under the names an A2A client
|
|
3413
|
+
// already uses. `task.id` stays authoritative.
|
|
3414
|
+
taskId: task.id,
|
|
3415
|
+
...task.threadId !== void 0 ? { contextId: task.threadId } : {},
|
|
3416
|
+
a2aState: a2aState(task.status)
|
|
3417
|
+
};
|
|
3418
|
+
})
|
|
3419
|
+
},
|
|
3420
|
+
{
|
|
3421
|
+
name: "bridge_task_cancel",
|
|
3422
|
+
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.",
|
|
3423
|
+
inputSchema: schema(
|
|
3424
|
+
{
|
|
3425
|
+
ref: str("Task message id (the id returned by bridge_task)."),
|
|
3426
|
+
reason: optStr("Optional reason, delivered with the cancel and kept on the timeline.")
|
|
3427
|
+
},
|
|
3428
|
+
["ref"]
|
|
3429
|
+
),
|
|
3430
|
+
handler: wrap(true, async (args, peer) => receipt(hub.cancelTask(peer, String(args.ref), args.reason === void 0 ? void 0 : String(args.reason))))
|
|
3431
|
+
},
|
|
3432
|
+
{
|
|
3433
|
+
name: "bridge_task_input",
|
|
3434
|
+
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.",
|
|
3435
|
+
inputSchema: schema(
|
|
3436
|
+
{
|
|
3437
|
+
ref: str("Task message id."),
|
|
3438
|
+
input: str("The information the assignee asked for.")
|
|
3439
|
+
},
|
|
3440
|
+
["ref", "input"]
|
|
3441
|
+
),
|
|
3442
|
+
handler: wrap(true, async (args, peer) => receipt(hub.taskInput(peer, String(args.ref), String(args.input))))
|
|
3443
|
+
},
|
|
3444
|
+
{
|
|
3445
|
+
name: "bridge_announce",
|
|
3446
|
+
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.",
|
|
3447
|
+
inputSchema: schema(
|
|
3448
|
+
{
|
|
3449
|
+
card: {
|
|
3450
|
+
type: "object",
|
|
3451
|
+
description: 'Your card: {skills?: [{id, name, description?, tags?}], acceptsTasks?: boolean, concurrency?: number, inputModes?: string[], outputModes?: string[], runner?: "herdr"|"cli"|"http"|"none", endpoint?: string}.'
|
|
3452
|
+
}
|
|
3453
|
+
},
|
|
3454
|
+
["card"]
|
|
3455
|
+
),
|
|
3456
|
+
handler: wrap(true, async (args, peer) => {
|
|
3457
|
+
const profile = hub.announceCard(peer, parseCard(args.card));
|
|
3458
|
+
return { ok: true, peer, card: profile.card };
|
|
1836
3459
|
})
|
|
1837
3460
|
},
|
|
3461
|
+
{
|
|
3462
|
+
name: "bridge_discover",
|
|
3463
|
+
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.",
|
|
3464
|
+
inputSchema: schema(
|
|
3465
|
+
{
|
|
3466
|
+
skill: optStr("Only peers declaring this skill id."),
|
|
3467
|
+
tag: optStr("Only peers whose skills carry this tag."),
|
|
3468
|
+
acceptsTasks: { type: "boolean", description: "Require the peer to accept tasks (default true). Pass false to drop that requirement." },
|
|
3469
|
+
idleOnly: { type: "boolean", description: "Only peers with nothing queued, no waiter and no running task." }
|
|
3470
|
+
},
|
|
3471
|
+
[]
|
|
3472
|
+
),
|
|
3473
|
+
handler: wrap(true, async (args) => ({
|
|
3474
|
+
peers: hub.discover({
|
|
3475
|
+
...args.skill !== void 0 ? { skill: String(args.skill) } : {},
|
|
3476
|
+
...args.tag !== void 0 ? { tag: String(args.tag) } : {},
|
|
3477
|
+
...args.acceptsTasks !== void 0 ? { acceptsTasks: args.acceptsTasks === true } : {},
|
|
3478
|
+
...args.idleOnly !== void 0 ? { idleOnly: args.idleOnly === true } : {}
|
|
3479
|
+
})
|
|
3480
|
+
}))
|
|
3481
|
+
},
|
|
1838
3482
|
{
|
|
1839
3483
|
name: "bridge_wait",
|
|
1840
|
-
description:
|
|
3484
|
+
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.',
|
|
1841
3485
|
inputSchema: schema({
|
|
1842
|
-
from: optStr(
|
|
1843
|
-
ref: optStr("Only wait for the ack of
|
|
3486
|
+
from: optStr('Only wait for messages from this peerId. Hub notices (from "hub") are never filtered out.'),
|
|
3487
|
+
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."),
|
|
3488
|
+
statuses: {
|
|
3489
|
+
type: "array",
|
|
3490
|
+
items: { type: "string", enum: [...ALL_ACK_STATUSES] },
|
|
3491
|
+
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."
|
|
3492
|
+
},
|
|
3493
|
+
terminalOnly: {
|
|
3494
|
+
type: "boolean",
|
|
3495
|
+
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."
|
|
3496
|
+
},
|
|
1844
3497
|
threadId: optStr("Only wait for messages carrying this threadId."),
|
|
1845
|
-
timeoutMs: int(`Max wait in milliseconds (default ${DEFAULT_WAIT_MS}, ceiling is server waitTimeoutMs).`)
|
|
3498
|
+
timeoutMs: int(`Max wait in milliseconds (default ${DEFAULT_WAIT_MS}, ceiling is server waitTimeoutMs).`),
|
|
3499
|
+
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.'),
|
|
3500
|
+
ack: { type: "string", enum: ["auto", "manual"], description: '"auto" (default) consumes the message; "manual" leases it until bridge_commit (or bridge_nack).' }
|
|
1846
3501
|
}),
|
|
1847
3502
|
handler: wrap(true, async (args, peer) => presentWait(await hub.wait(
|
|
1848
3503
|
peer,
|
|
@@ -1850,14 +3505,41 @@ function hubTools(hub, registry, options) {
|
|
|
1850
3505
|
args.from === void 0 ? void 0 : String(args.from),
|
|
1851
3506
|
void 0,
|
|
1852
3507
|
args.ref === void 0 ? void 0 : String(args.ref),
|
|
1853
|
-
args.threadId === void 0 ? void 0 : String(args.threadId)
|
|
3508
|
+
args.threadId === void 0 ? void 0 : String(args.threadId),
|
|
3509
|
+
args.ack === "manual",
|
|
3510
|
+
args.maxMessages === void 0 ? 1 : Math.max(1, Number(args.maxMessages)),
|
|
3511
|
+
ackStatuses(args.statuses, args.terminalOnly === true),
|
|
3512
|
+
args.terminalOnly === true
|
|
1854
3513
|
)))
|
|
1855
3514
|
},
|
|
1856
3515
|
{
|
|
1857
3516
|
name: "bridge_poll",
|
|
1858
|
-
description:
|
|
1859
|
-
inputSchema: schema({
|
|
1860
|
-
|
|
3517
|
+
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.',
|
|
3518
|
+
inputSchema: schema({
|
|
3519
|
+
from: optStr('Only drain messages from this peerId. Hub notices (from "hub") are never filtered out.'),
|
|
3520
|
+
ack: { type: "string", enum: ["auto", "manual"], description: '"auto" (default) consumes; "manual" leases until bridge_commit.' }
|
|
3521
|
+
}),
|
|
3522
|
+
handler: wrap(true, async (args, peer) => ({
|
|
3523
|
+
messages: hub.poll(peer, args.from === void 0 ? void 0 : String(args.from), { manual: args.ack === "manual" }).map(present)
|
|
3524
|
+
}))
|
|
3525
|
+
},
|
|
3526
|
+
{
|
|
3527
|
+
name: "bridge_commit",
|
|
3528
|
+
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.',
|
|
3529
|
+
inputSchema: schema(
|
|
3530
|
+
{ ids: { type: "array", items: { type: "string" }, description: "Message ids you received and have finished handling. At most 1000 per call." } },
|
|
3531
|
+
["ids"]
|
|
3532
|
+
),
|
|
3533
|
+
handler: wrap(true, async (args, peer) => ({ committed: hub.commit(peer, idList(args.ids, "bridge_commit")) }))
|
|
3534
|
+
},
|
|
3535
|
+
{
|
|
3536
|
+
name: "bridge_nack",
|
|
3537
|
+
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.",
|
|
3538
|
+
inputSchema: schema(
|
|
3539
|
+
{ ids: { type: "array", items: { type: "string" }, description: "Message ids to give back. At most 1000 per call." } },
|
|
3540
|
+
["ids"]
|
|
3541
|
+
),
|
|
3542
|
+
handler: wrap(true, async (args, peer) => ({ requeued: hub.nack(peer, idList(args.ids, "bridge_nack")) }))
|
|
1861
3543
|
},
|
|
1862
3544
|
{
|
|
1863
3545
|
name: "bridge_status",
|
|
@@ -1865,6 +3547,21 @@ function hubTools(hub, registry, options) {
|
|
|
1865
3547
|
inputSchema: schema({}),
|
|
1866
3548
|
handler: wrap(true, async () => hub.status(livePeersFor(registry)))
|
|
1867
3549
|
},
|
|
3550
|
+
{
|
|
3551
|
+
name: "bridge_metrics",
|
|
3552
|
+
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.",
|
|
3553
|
+
inputSchema: schema({}),
|
|
3554
|
+
handler: wrap(true, async () => hub.metrics())
|
|
3555
|
+
},
|
|
3556
|
+
{
|
|
3557
|
+
name: "bridge_events",
|
|
3558
|
+
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.",
|
|
3559
|
+
inputSchema: schema({
|
|
3560
|
+
since: { type: "number", description: "Return only events with a seq greater than this (exclusive)." },
|
|
3561
|
+
limit: { type: "number", description: "Maximum events to return, newest kept (default 100, max 500)." }
|
|
3562
|
+
}),
|
|
3563
|
+
handler: wrap(true, async (args) => hub.events(args))
|
|
3564
|
+
},
|
|
1868
3565
|
{
|
|
1869
3566
|
name: "bridge_peers",
|
|
1870
3567
|
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.",
|
|
@@ -1877,22 +3574,30 @@ function hubTools(hub, registry, options) {
|
|
|
1877
3574
|
inputSchema: schema({
|
|
1878
3575
|
peer: optStr('PeerId whose conversation to inspect; "all" = every peer; default: yourself. Other peers / "all" require manager rights.'),
|
|
1879
3576
|
channel: optStr("Read a group channel history instead of a peer conversation (you must be a member, or a manager)."),
|
|
1880
|
-
limit: int("How many messages to return (default 20).")
|
|
3577
|
+
limit: int("How many messages to return (default 20)."),
|
|
3578
|
+
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.')
|
|
1881
3579
|
}),
|
|
1882
3580
|
handler: wrap(true, async (args, peer, sessionId) => {
|
|
1883
3581
|
const limit = Math.min(args.limit === void 0 ? 20 : Number(args.limit), 1e3);
|
|
3582
|
+
const sinceRaw = args.since === void 0 ? void 0 : Number(args.since);
|
|
3583
|
+
if (sinceRaw !== void 0 && (!Number.isFinite(sinceRaw) || sinceRaw < 0)) {
|
|
3584
|
+
throw new Error(`invalid since: ${String(args.since)} (expected a non-negative sequence number)`);
|
|
3585
|
+
}
|
|
3586
|
+
const since = sinceRaw;
|
|
1884
3587
|
const target = args.peer === void 0 ? peer : String(args.peer);
|
|
1885
|
-
if (target
|
|
1886
|
-
requireManager(peer,
|
|
3588
|
+
if (target === BROADCAST) {
|
|
3589
|
+
requireManager(peer, "reading the full history", sessionId);
|
|
3590
|
+
} else if (target !== peer) {
|
|
3591
|
+
requireManager(peer, `reading peer '${target}' history`, sessionId);
|
|
1887
3592
|
}
|
|
1888
3593
|
if (args.channel !== void 0) {
|
|
1889
3594
|
const groupId = String(args.channel);
|
|
1890
3595
|
const group = hub.groupOf(groupId);
|
|
1891
3596
|
if (group === void 0) throw new Error(`unknown group: ${groupId}`);
|
|
1892
3597
|
if (!group.members.includes(peer)) requireManager(peer, `reading group '${groupId}' history`, sessionId);
|
|
1893
|
-
return { messages: hub.historyChannel(groupId, limit).map(present) };
|
|
3598
|
+
return { messages: hub.historyChannel(groupId, limit, since).map(present) };
|
|
1894
3599
|
}
|
|
1895
|
-
const messages = target === BROADCAST ? hub.historyAll(limit) : hub.history(target, limit);
|
|
3600
|
+
const messages = target === BROADCAST ? hub.historyAll(limit, since) : hub.history(target, limit, since);
|
|
1896
3601
|
return { messages: messages.map(present) };
|
|
1897
3602
|
})
|
|
1898
3603
|
},
|
|
@@ -2168,11 +3873,11 @@ function hubTools(hub, registry, options) {
|
|
|
2168
3873
|
return read === null ? { matched: null } : { matched: read };
|
|
2169
3874
|
})
|
|
2170
3875
|
}
|
|
2171
|
-
];
|
|
3876
|
+
].map((tool) => ({ ...tool, handler: requireArgs(tool, tool.handler) }));
|
|
2172
3877
|
}
|
|
2173
3878
|
|
|
2174
3879
|
// src/mcp-server.ts
|
|
2175
|
-
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
3880
|
+
import { randomUUID as randomUUID2, timingSafeEqual } from "node:crypto";
|
|
2176
3881
|
import { readFileSync as readFileSync2 } from "node:fs";
|
|
2177
3882
|
var ADMIN_PATH = "/admin";
|
|
2178
3883
|
var ADMIN_API_PATH = "/admin/api";
|
|
@@ -2187,6 +3892,7 @@ var SUPPORTED_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
|
|
2187
3892
|
var LATEST_VERSION = SUPPORTED_VERSIONS[0];
|
|
2188
3893
|
var MAX_BODY_BYTES = 1048576;
|
|
2189
3894
|
var HEARTBEAT_MS = 2e4;
|
|
3895
|
+
var DEFAULT_SESSION_TTL_MS = 30 * 6e4;
|
|
2190
3896
|
var SessionRegistry = class {
|
|
2191
3897
|
sessions = /* @__PURE__ */ new Set();
|
|
2192
3898
|
/** sessionId → peerId claimed via `bridge_register`. */
|
|
@@ -2199,8 +3905,17 @@ var SessionRegistry = class {
|
|
|
2199
3905
|
ensureSession(sessionId) {
|
|
2200
3906
|
const id = sessionId ?? randomUUID2();
|
|
2201
3907
|
this.sessions.add(id);
|
|
3908
|
+
this.lastUsedAt.set(id, Date.now());
|
|
2202
3909
|
return id;
|
|
2203
3910
|
}
|
|
3911
|
+
/** Has this session id ever been minted here and not terminated since?
|
|
3912
|
+
* A request presenting an id the registry does not know must be answered 404
|
|
3913
|
+
* (spec MUST) so the client starts a new session, instead of being adopted
|
|
3914
|
+
* silently — which is how a client kept talking to a hub that had restarted
|
|
3915
|
+
* and already forgotten it. */
|
|
3916
|
+
hasSession(sessionId) {
|
|
3917
|
+
return this.sessions.has(sessionId);
|
|
3918
|
+
}
|
|
2204
3919
|
/** Peer bound to a session, if any. */
|
|
2205
3920
|
peerFor(sessionId) {
|
|
2206
3921
|
if (sessionId === void 0) return void 0;
|
|
@@ -2256,6 +3971,47 @@ var SessionRegistry = class {
|
|
|
2256
3971
|
isSuppressed(sessionId) {
|
|
2257
3972
|
return sessionId !== void 0 && this.suppressedAuto.has(sessionId);
|
|
2258
3973
|
}
|
|
3974
|
+
/** Session → the last time a request presented it.
|
|
3975
|
+
*
|
|
3976
|
+
* The registry is the only thing that knows a session exists, so it is also the
|
|
3977
|
+
* only thing that can decide one is finished. Without this the maps below only
|
|
3978
|
+
* ever grew, `hasSession` was true forever, and "this session is over" was not
|
|
3979
|
+
* expressible — so the 404 path could never fire for a session the hub had
|
|
3980
|
+
* genuinely finished with. */
|
|
3981
|
+
lastUsedAt = /* @__PURE__ */ new Map();
|
|
3982
|
+
/** Record that `sessionId` was just used (a request carried its id). */
|
|
3983
|
+
touch(sessionId) {
|
|
3984
|
+
if (sessionId !== void 0 && this.sessions.has(sessionId)) this.lastUsedAt.set(sessionId, Date.now());
|
|
3985
|
+
}
|
|
3986
|
+
/**
|
|
3987
|
+
* Forget sessions that are finished: no live SSE stream, and unused for `ttlMs`.
|
|
3988
|
+
* Returns the ids removed. `ttlMs <= 0` disables reaping.
|
|
3989
|
+
*
|
|
3990
|
+
* Safe because a client that gets 404 is REQUIRED by the spec to send a fresh
|
|
3991
|
+
* `initialize`, and the hub auto-registers it under the same peer id — it comes
|
|
3992
|
+
* back with its mailbox intact. A live SSE stream pins a session regardless of
|
|
3993
|
+
* age: that is the one signal that means "still connected", and it wins.
|
|
3994
|
+
*/
|
|
3995
|
+
sweep(now, ttlMs) {
|
|
3996
|
+
if (ttlMs <= 0) return [];
|
|
3997
|
+
const removed = [];
|
|
3998
|
+
for (const sessionId of [...this.sessions]) {
|
|
3999
|
+
if (this.liveStreams.has(sessionId)) continue;
|
|
4000
|
+
const last = this.lastUsedAt.get(sessionId) ?? now;
|
|
4001
|
+
if (now - last <= ttlMs) continue;
|
|
4002
|
+
this.sessions.delete(sessionId);
|
|
4003
|
+
this.lastUsedAt.delete(sessionId);
|
|
4004
|
+
this.peerBindings.delete(sessionId);
|
|
4005
|
+
this.clientNames.delete(sessionId);
|
|
4006
|
+
this.clientVersions.delete(sessionId);
|
|
4007
|
+
this.sessionIps.delete(sessionId);
|
|
4008
|
+
this.tokenBindings.delete(sessionId);
|
|
4009
|
+
this.managerSessions.delete(sessionId);
|
|
4010
|
+
this.suppressedAuto.delete(sessionId);
|
|
4011
|
+
removed.push(sessionId);
|
|
4012
|
+
}
|
|
4013
|
+
return removed;
|
|
4014
|
+
}
|
|
2259
4015
|
/** Session → client IP (remote mode: the admin roster shows where a peer
|
|
2260
4016
|
* connects from, so the operator can tell Zhang San's kimi-code from Li Si's). */
|
|
2261
4017
|
sessionIps = /* @__PURE__ */ new Map();
|
|
@@ -2274,6 +4030,19 @@ var SessionRegistry = class {
|
|
|
2274
4030
|
if (sessionId === void 0) return void 0;
|
|
2275
4031
|
return this.tokenBindings.get(sessionId);
|
|
2276
4032
|
}
|
|
4033
|
+
/** Sessions that presented the loopback manager token (`--manager-token`).
|
|
4034
|
+
* Distinct from a token-table identity: loopback mode has no token table, so
|
|
4035
|
+
* the manager secret is the only thing separating "the operator's GUI" from
|
|
4036
|
+
* "any other local MCP client". */
|
|
4037
|
+
managerSessions = /* @__PURE__ */ new Set();
|
|
4038
|
+
/** Remember that this session proved it holds the manager token. */
|
|
4039
|
+
markManagerSession(sessionId) {
|
|
4040
|
+
this.managerSessions.add(sessionId);
|
|
4041
|
+
}
|
|
4042
|
+
/** Did this session present the manager token? */
|
|
4043
|
+
isManagerSession(sessionId) {
|
|
4044
|
+
return sessionId !== void 0 && this.managerSessions.has(sessionId);
|
|
4045
|
+
}
|
|
2277
4046
|
/** Mark a session's SSE stream open (server→client channel alive). */
|
|
2278
4047
|
markSseOpen(sessionId) {
|
|
2279
4048
|
this.liveStreams.add(sessionId);
|
|
@@ -2332,7 +4101,7 @@ var SessionRegistry = class {
|
|
|
2332
4101
|
var McpStreamableHttpServer = class {
|
|
2333
4102
|
constructor(tools, info, registry, log2 = () => {
|
|
2334
4103
|
}, onInitialize = () => {
|
|
2335
|
-
}, authenticate, adminApi, heartbeatMs) {
|
|
4104
|
+
}, authenticate, adminApi, heartbeatMs, originPolicy, managerToken, sessionTtlMs = DEFAULT_SESSION_TTL_MS) {
|
|
2336
4105
|
this.tools = tools;
|
|
2337
4106
|
this.info = info;
|
|
2338
4107
|
this.registry = registry;
|
|
@@ -2341,29 +4110,54 @@ var McpStreamableHttpServer = class {
|
|
|
2341
4110
|
this.authenticate = authenticate;
|
|
2342
4111
|
this.adminApi = adminApi;
|
|
2343
4112
|
this.heartbeatMs = heartbeatMs;
|
|
4113
|
+
this.originPolicy = originPolicy;
|
|
4114
|
+
this.managerToken = managerToken;
|
|
4115
|
+
this.sessionTtlMs = sessionTtlMs;
|
|
2344
4116
|
}
|
|
2345
4117
|
sseStreams = /* @__PURE__ */ new Map();
|
|
2346
4118
|
heartbeatTimer;
|
|
4119
|
+
sessionSweepTimer;
|
|
4120
|
+
/** Does this request carry the loopback manager token? */
|
|
4121
|
+
presentedManagerToken(req) {
|
|
4122
|
+
if (this.managerToken === void 0) return false;
|
|
4123
|
+
const header = headerValue(req.headers.authorization);
|
|
4124
|
+
if (header === void 0) return false;
|
|
4125
|
+
const match = /^Bearer\s+(.+)$/i.exec(header);
|
|
4126
|
+
return match !== null && secretEquals(match[1].trim(), this.managerToken);
|
|
4127
|
+
}
|
|
2347
4128
|
/** Attach request handling for `path` (e.g. `/mcp`) to an http server. */
|
|
2348
4129
|
attach(server, path2) {
|
|
2349
4130
|
this.heartbeatTimer = setInterval(() => {
|
|
2350
4131
|
if (this.sseStreams.size === 0) return;
|
|
2351
|
-
this.notifyAll(
|
|
4132
|
+
this.notifyAll(SSE_METHOD, {
|
|
2352
4133
|
level: "debug",
|
|
2353
4134
|
logger: "bridge",
|
|
2354
4135
|
data: { event: "heartbeat", ts: Date.now() }
|
|
2355
4136
|
});
|
|
2356
4137
|
}, this.heartbeatMs ?? HEARTBEAT_MS);
|
|
2357
4138
|
this.heartbeatTimer.unref?.();
|
|
4139
|
+
if (this.sessionTtlMs > 0) {
|
|
4140
|
+
const interval = Math.min(6e4, Math.max(1e3, this.sessionTtlMs / 4));
|
|
4141
|
+
this.sessionSweepTimer = setInterval(() => {
|
|
4142
|
+
const removed = this.registry.sweep(Date.now(), this.sessionTtlMs);
|
|
4143
|
+
if (removed.length > 0) this.log(`sessions reaped: ${removed.length}`);
|
|
4144
|
+
}, interval);
|
|
4145
|
+
this.sessionSweepTimer.unref?.();
|
|
4146
|
+
}
|
|
2358
4147
|
server.on("request", (req, res) => {
|
|
2359
4148
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
4149
|
+
if (!this.originAllowed(req)) {
|
|
4150
|
+
res.writeHead(403, { ...this.corsFor(req), "Content-Type": "application/json; charset=utf-8", "Mcp-Protocol-Version": messageProtocolVersion(req) });
|
|
4151
|
+
res.end(JSON.stringify({ error: `origin not allowed: ${headerValue(req.headers.origin) ?? ""}` }));
|
|
4152
|
+
return;
|
|
4153
|
+
}
|
|
2360
4154
|
if (url.pathname === ADMIN_PATH && req.method === "GET") {
|
|
2361
4155
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-cache" });
|
|
2362
4156
|
res.end(adminPage());
|
|
2363
4157
|
return;
|
|
2364
4158
|
}
|
|
2365
4159
|
if (url.pathname === "/healthz") {
|
|
2366
|
-
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", ...
|
|
4160
|
+
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", ...this.corsFor(req) });
|
|
2367
4161
|
res.end(JSON.stringify({ ok: true, ts: Date.now() }));
|
|
2368
4162
|
return;
|
|
2369
4163
|
}
|
|
@@ -2384,15 +4178,16 @@ var McpStreamableHttpServer = class {
|
|
|
2384
4178
|
return;
|
|
2385
4179
|
}
|
|
2386
4180
|
if (req.method === "OPTIONS") {
|
|
2387
|
-
res.writeHead(204,
|
|
4181
|
+
res.writeHead(204, this.corsFor(req)).end();
|
|
2388
4182
|
return;
|
|
2389
4183
|
}
|
|
2390
|
-
res.writeHead(405,
|
|
4184
|
+
res.writeHead(405, { ...this.corsFor(req), "Mcp-Protocol-Version": messageProtocolVersion(req) }).end();
|
|
2391
4185
|
});
|
|
2392
4186
|
}
|
|
2393
4187
|
/** Close all open SSE streams (called on server shutdown). */
|
|
2394
4188
|
close() {
|
|
2395
4189
|
if (this.heartbeatTimer !== void 0) clearInterval(this.heartbeatTimer);
|
|
4190
|
+
if (this.sessionSweepTimer !== void 0) clearInterval(this.sessionSweepTimer);
|
|
2396
4191
|
for (const stream of this.sseStreams.values()) stream.end();
|
|
2397
4192
|
this.sseStreams.clear();
|
|
2398
4193
|
}
|
|
@@ -2420,33 +4215,107 @@ data: ${JSON.stringify({ jsonrpc: "2.0", method, params })}
|
|
|
2420
4215
|
}
|
|
2421
4216
|
}
|
|
2422
4217
|
}
|
|
4218
|
+
/**
|
|
4219
|
+
* Cross-origin gate. A request is allowed when:
|
|
4220
|
+
* - it carries no `Origin` (curl, MCP clients, the desktop app — never browsers), or
|
|
4221
|
+
* - the origin is explicitly listed (`--allow-origins`, or 'all'), or
|
|
4222
|
+
* - the origin is a loopback hostname (the bundled admin page, local tooling), or
|
|
4223
|
+
* - it presents a valid bearer token AND its origin host matches the `Host`
|
|
4224
|
+
* header (the admin page behind a TLS reverse proxy, where the hub cannot
|
|
4225
|
+
* know its own public origin).
|
|
4226
|
+
*
|
|
4227
|
+
* The last clause is deliberately credential-gated, not identity-gated: with
|
|
4228
|
+
* `--allow-join` the transport mints an anonymous identity for a request that
|
|
4229
|
+
* carries nothing at all, so testing only `authenticate(req) !== undefined`
|
|
4230
|
+
* would re-open this branch to exactly the rebinding page it exists to stop.
|
|
4231
|
+
* A real `Authorization` header is required as well.
|
|
4232
|
+
*/
|
|
4233
|
+
originAllowed(req) {
|
|
4234
|
+
const origin = headerValue(req.headers.origin);
|
|
4235
|
+
if (origin === void 0) return true;
|
|
4236
|
+
const policy = this.originPolicy;
|
|
4237
|
+
if (policy?.allow === "all") return true;
|
|
4238
|
+
if (policy?.allow?.has(origin) === true) return true;
|
|
4239
|
+
if (origin.includes(",") || /\s/.test(origin)) return false;
|
|
4240
|
+
const originHost = originHostname(origin);
|
|
4241
|
+
if (originHost === void 0) return false;
|
|
4242
|
+
if (isLoopbackHost(originHost)) return true;
|
|
4243
|
+
const identity = this.authenticate?.(req);
|
|
4244
|
+
if (identity === void 0 || identity.anonymous === true) return false;
|
|
4245
|
+
const host = headerValue(req.headers.host);
|
|
4246
|
+
return host !== void 0 && hostHeaderName(host) === originHost;
|
|
4247
|
+
}
|
|
4248
|
+
/** CORS headers for one request: echoes the origin only when it is allowed. */
|
|
4249
|
+
corsFor(req) {
|
|
4250
|
+
if (req === void 0) return corsHeaders();
|
|
4251
|
+
const origin = headerValue(req.headers.origin);
|
|
4252
|
+
return corsHeaders(origin !== void 0 && this.originAllowed(req) ? origin : void 0);
|
|
4253
|
+
}
|
|
2423
4254
|
handleGet(req, res) {
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
4255
|
+
let streamIdentity;
|
|
4256
|
+
if (this.authenticate !== void 0) {
|
|
4257
|
+
streamIdentity = this.authenticate(req);
|
|
4258
|
+
if (streamIdentity === void 0) {
|
|
4259
|
+
res.writeHead(401, { ...this.corsFor(req), "Content-Type": "application/json; charset=utf-8", "Mcp-Protocol-Version": messageProtocolVersion(req) });
|
|
4260
|
+
res.end(JSON.stringify({ error: "unauthorized: missing or invalid bearer token" }));
|
|
4261
|
+
return;
|
|
4262
|
+
}
|
|
4263
|
+
const existing = this.registry.sessionIdFor(req);
|
|
4264
|
+
const bound = existing === void 0 ? void 0 : this.registry.tokenFor(existing);
|
|
4265
|
+
const bothAnonymous = bound?.anonymous === true && streamIdentity.anonymous === true;
|
|
4266
|
+
if (bound !== void 0 && !bothAnonymous && (bound.peer !== streamIdentity.peer || bound.role !== streamIdentity.role)) {
|
|
4267
|
+
this.unauthorized(req, res, null, "token does not match this session");
|
|
4268
|
+
return;
|
|
4269
|
+
}
|
|
4270
|
+
}
|
|
4271
|
+
if (this.protocolVersionRejected(req, res)) return;
|
|
4272
|
+
const streamSession = this.registry.sessionIdFor(req);
|
|
4273
|
+
if (streamSession !== void 0 && !this.registry.hasSession(streamSession)) {
|
|
4274
|
+
this.jsonRpcError(req, res, null, -32001, "session not found \u2014 send a new initialize request", void 0, 404);
|
|
2427
4275
|
return;
|
|
2428
4276
|
}
|
|
2429
|
-
|
|
2430
|
-
const
|
|
2431
|
-
if (
|
|
4277
|
+
this.registry.touch(streamSession);
|
|
4278
|
+
const sessionId = this.registry.ensureSession(streamSession);
|
|
4279
|
+
if (this.presentedManagerToken(req)) this.registry.markManagerSession(sessionId);
|
|
4280
|
+
if (streamIdentity !== void 0) this.registry.bindToken(sessionId, streamIdentity);
|
|
2432
4281
|
res.writeHead(200, {
|
|
2433
|
-
...
|
|
4282
|
+
...this.corsFor(req),
|
|
2434
4283
|
"Content-Type": "text/event-stream; charset=utf-8",
|
|
2435
4284
|
"Cache-Control": "no-cache",
|
|
2436
4285
|
Connection: "keep-alive",
|
|
4286
|
+
// nginx (and anything else speaking X-Accel) buffers proxied responses by
|
|
4287
|
+
// default, which breaks SSE completely: events sit in the proxy until its
|
|
4288
|
+
// buffer fills or the stream ends, so a client never sees a push. This header
|
|
4289
|
+
// is the in-band way to turn that off — it needs no proxy configuration, and
|
|
4290
|
+
// a proxy that ignores it is unaffected.
|
|
4291
|
+
"X-Accel-Buffering": "no",
|
|
4292
|
+
// Same header the POST path sets: the client should see the version the
|
|
4293
|
+
// server is speaking on every 200, not only on JSON responses.
|
|
4294
|
+
"Mcp-Protocol-Version": messageProtocolVersion(req),
|
|
2437
4295
|
...req.headers["mcp-session-id"] ? {} : { "Mcp-Session-Id": sessionId }
|
|
2438
4296
|
});
|
|
2439
4297
|
res.write(": connected\n\n");
|
|
2440
4298
|
this.sseStreams.set(sessionId, res);
|
|
2441
4299
|
this.registry.markSseOpen(sessionId);
|
|
2442
4300
|
req.on("close", () => {
|
|
2443
|
-
this.sseStreams.delete(sessionId);
|
|
2444
|
-
this.registry.markSseClosed(sessionId);
|
|
4301
|
+
if (this.sseStreams.get(sessionId) === res) this.sseStreams.delete(sessionId);
|
|
4302
|
+
if (!this.sseStreams.has(sessionId)) this.registry.markSseClosed(sessionId);
|
|
2445
4303
|
});
|
|
2446
4304
|
}
|
|
2447
4305
|
/** Reject a request without a valid token (remote auth mode). */
|
|
2448
|
-
unauthorized(res, id, why) {
|
|
2449
|
-
res.writeHead(401, {
|
|
4306
|
+
unauthorized(req, res, id, why) {
|
|
4307
|
+
res.writeHead(401, {
|
|
4308
|
+
...this.corsFor(req),
|
|
4309
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
4310
|
+
// MCP authorization spec: a 401 MUST carry WWW-Authenticate. The hub does not
|
|
4311
|
+
// implement OAuth (authorization is OPTIONAL in MCP), so there is no
|
|
4312
|
+
// resource_metadata to advertise — the bare scheme is still required.
|
|
4313
|
+
"WWW-Authenticate": "Bearer",
|
|
4314
|
+
// Every response names the protocol version the server is speaking, errors
|
|
4315
|
+
// included: a client that only sees 401s still needs to know what it is
|
|
4316
|
+
// talking to before it can decide whether to retry.
|
|
4317
|
+
"Mcp-Protocol-Version": messageProtocolVersion(req)
|
|
4318
|
+
});
|
|
2450
4319
|
res.end(JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32001, message: `unauthorized: ${why}` } }));
|
|
2451
4320
|
}
|
|
2452
4321
|
/** Management API for the bundled admin page: issue/revoke tokens and list
|
|
@@ -2454,7 +4323,7 @@ data: ${JSON.stringify({ jsonrpc: "2.0", method, params })}
|
|
|
2454
4323
|
* and must resolve to a MANAGER role — an agent token gets 403. */
|
|
2455
4324
|
async handleAdminApi(req, res, url) {
|
|
2456
4325
|
const respond = (status, body) => {
|
|
2457
|
-
res.writeHead(status, { ...
|
|
4326
|
+
res.writeHead(status, { ...this.corsFor(req), "Content-Type": "application/json; charset=utf-8" });
|
|
2458
4327
|
res.end(JSON.stringify(body));
|
|
2459
4328
|
};
|
|
2460
4329
|
const identity = this.authenticate?.(req);
|
|
@@ -2503,49 +4372,57 @@ data: ${JSON.stringify({ jsonrpc: "2.0", method, params })}
|
|
|
2503
4372
|
if (this.authenticate !== void 0) {
|
|
2504
4373
|
authIdentity = this.authenticate(req);
|
|
2505
4374
|
if (authIdentity === void 0) {
|
|
2506
|
-
this.unauthorized(res, null, "missing or invalid bearer token");
|
|
4375
|
+
this.unauthorized(req, res, null, "missing or invalid bearer token");
|
|
2507
4376
|
return;
|
|
2508
4377
|
}
|
|
2509
4378
|
const existingSession = this.registry.sessionIdFor(req);
|
|
2510
4379
|
const bound = existingSession === void 0 ? void 0 : this.registry.tokenFor(existingSession);
|
|
2511
4380
|
const bothAnonymous = bound?.anonymous === true && authIdentity.anonymous === true;
|
|
2512
4381
|
if (bound !== void 0 && !bothAnonymous && (bound.peer !== authIdentity.peer || bound.role !== authIdentity.role)) {
|
|
2513
|
-
this.unauthorized(res, null, "token does not match this session");
|
|
4382
|
+
this.unauthorized(req, res, null, "token does not match this session");
|
|
2514
4383
|
return;
|
|
2515
4384
|
}
|
|
2516
4385
|
if (existingSession !== void 0 && bound === void 0 && !authIdentity.anonymous) {
|
|
2517
4386
|
this.registry.bindToken(existingSession, authIdentity);
|
|
2518
4387
|
}
|
|
2519
4388
|
}
|
|
4389
|
+
if (this.protocolVersionRejected(req, res)) return;
|
|
4390
|
+
const presentedSession = this.registry.sessionIdFor(req);
|
|
4391
|
+
if (presentedSession !== void 0 && !this.registry.hasSession(presentedSession)) {
|
|
4392
|
+
this.jsonRpcError(req, res, null, -32001, "session not found \u2014 send a new initialize request", void 0, 404);
|
|
4393
|
+
return;
|
|
4394
|
+
}
|
|
4395
|
+
this.registry.touch(presentedSession);
|
|
2520
4396
|
let body;
|
|
2521
4397
|
try {
|
|
2522
4398
|
body = await readBody(req);
|
|
2523
4399
|
} catch (error) {
|
|
2524
|
-
this.jsonRpcError(res, null, -32700, `parse error: ${error.message}`);
|
|
4400
|
+
this.jsonRpcError(req, res, null, -32700, `parse error: ${error.message}`);
|
|
2525
4401
|
return;
|
|
2526
4402
|
}
|
|
2527
4403
|
let message;
|
|
2528
4404
|
try {
|
|
2529
4405
|
message = JSON.parse(body.toString("utf8"));
|
|
2530
4406
|
} catch {
|
|
2531
|
-
this.jsonRpcError(res, null, -32700, "parse error: invalid JSON");
|
|
4407
|
+
this.jsonRpcError(req, res, null, -32700, "parse error: invalid JSON");
|
|
2532
4408
|
return;
|
|
2533
4409
|
}
|
|
2534
4410
|
if (typeof message !== "object" || message === null || message.method === void 0) {
|
|
2535
|
-
this.jsonRpcError(res, message?.id ?? null, -32600, "invalid request");
|
|
4411
|
+
this.jsonRpcError(req, res, message?.id ?? null, -32600, "invalid request");
|
|
2536
4412
|
return;
|
|
2537
4413
|
}
|
|
2538
4414
|
const id = message.id ?? null;
|
|
2539
4415
|
const sessionId = this.registry.sessionIdFor(req);
|
|
2540
4416
|
if (sessionId !== void 0) this.registry.sessionIps.set(sessionId, clientIp(req));
|
|
4417
|
+
if (sessionId !== void 0 && this.presentedManagerToken(req)) this.registry.markManagerSession(sessionId);
|
|
2541
4418
|
if (id === null) {
|
|
2542
|
-
res.writeHead(202, { ...
|
|
4419
|
+
res.writeHead(202, { ...this.corsFor(req), "Content-Length": "0" }).end();
|
|
2543
4420
|
return;
|
|
2544
4421
|
}
|
|
2545
4422
|
try {
|
|
2546
4423
|
const { result, extraHeaders } = await this.dispatch(message, sessionId, authIdentity);
|
|
2547
4424
|
res.writeHead(200, {
|
|
2548
|
-
...
|
|
4425
|
+
...this.corsFor(req),
|
|
2549
4426
|
"Content-Type": "application/json; charset=utf-8",
|
|
2550
4427
|
"Mcp-Protocol-Version": messageProtocolVersion(req),
|
|
2551
4428
|
...extraHeaders
|
|
@@ -2553,7 +4430,7 @@ data: ${JSON.stringify({ jsonrpc: "2.0", method, params })}
|
|
|
2553
4430
|
res.end(JSON.stringify({ jsonrpc: "2.0", id, result }));
|
|
2554
4431
|
} catch (error) {
|
|
2555
4432
|
const code = error.code ?? -32603;
|
|
2556
|
-
this.jsonRpcError(res, id, code, error.message
|
|
4433
|
+
this.jsonRpcError(req, res, id, code, error.message);
|
|
2557
4434
|
}
|
|
2558
4435
|
}
|
|
2559
4436
|
async dispatch(message, sessionId, authIdentity) {
|
|
@@ -2616,11 +4493,27 @@ data: ${JSON.stringify({ jsonrpc: "2.0", method, params })}
|
|
|
2616
4493
|
throw rpcError(-32601, `method not found: ${method}`);
|
|
2617
4494
|
}
|
|
2618
4495
|
}
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
4496
|
+
/** Spec MUST: a request carrying an `MCP-Protocol-Version` this server does
|
|
4497
|
+
* not implement gets 400. Absent is fine — an absent header means the client is
|
|
4498
|
+
* on the newest revision this server knows, which is what responses advertise
|
|
4499
|
+
* (`messageProtocolVersion` returns LATEST_VERSION) —
|
|
4500
|
+
* but *present and unknown* is a client speaking a revision whose rules this
|
|
4501
|
+
* server would otherwise be guessing at. Writes the response itself and
|
|
4502
|
+
* reports whether it did. */
|
|
4503
|
+
protocolVersionRejected(req, res) {
|
|
4504
|
+
const presented = req.headers["mcp-protocol-version"];
|
|
4505
|
+
if (presented === void 0) return false;
|
|
4506
|
+
if (typeof presented === "string" && SUPPORTED_VERSIONS.includes(presented)) return false;
|
|
4507
|
+
this.jsonRpcError(req, res, null, -32600, `unsupported MCP-Protocol-Version: ${String(presented).slice(0, 64)} (supported: ${SUPPORTED_VERSIONS.join(", ")})`, void 0, 400);
|
|
4508
|
+
return true;
|
|
4509
|
+
}
|
|
4510
|
+
jsonRpcError(req, res, id, code, message, data, status) {
|
|
4511
|
+
const code400 = code === -32700 || code === -32600;
|
|
4512
|
+
const httpStatus = status ?? (code400 ? 400 : 200);
|
|
4513
|
+
res.writeHead(httpStatus, {
|
|
4514
|
+
...this.corsFor(req),
|
|
2622
4515
|
"Content-Type": "application/json; charset=utf-8",
|
|
2623
|
-
|
|
4516
|
+
"Mcp-Protocol-Version": messageProtocolVersion(req)
|
|
2624
4517
|
});
|
|
2625
4518
|
res.end(JSON.stringify({ jsonrpc: "2.0", id, error: { code, message, ...data !== void 0 ? { data } : {} } }));
|
|
2626
4519
|
}
|
|
@@ -2631,7 +4524,8 @@ function rpcError(code, message) {
|
|
|
2631
4524
|
return error;
|
|
2632
4525
|
}
|
|
2633
4526
|
function messageProtocolVersion(req) {
|
|
2634
|
-
|
|
4527
|
+
const presented = req.headers["mcp-protocol-version"];
|
|
4528
|
+
return typeof presented === "string" && SUPPORTED_VERSIONS.includes(presented) ? presented : LATEST_VERSION;
|
|
2635
4529
|
}
|
|
2636
4530
|
function clientIp(req) {
|
|
2637
4531
|
const forwarded = req.headers["x-forwarded-for"];
|
|
@@ -2641,10 +4535,44 @@ function clientIp(req) {
|
|
|
2641
4535
|
}
|
|
2642
4536
|
return (req.socket.remoteAddress ?? "?").replace(/^::ffff:/, "");
|
|
2643
4537
|
}
|
|
2644
|
-
function
|
|
4538
|
+
function headerValue(value) {
|
|
4539
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
4540
|
+
return typeof raw === "string" && raw.trim() !== "" ? raw.trim() : void 0;
|
|
4541
|
+
}
|
|
4542
|
+
function secretEquals(a, b) {
|
|
4543
|
+
const left = Buffer.from(a, "utf8");
|
|
4544
|
+
const right = Buffer.from(b, "utf8");
|
|
4545
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
4546
|
+
}
|
|
4547
|
+
function originHostname(origin) {
|
|
4548
|
+
try {
|
|
4549
|
+
return new URL(origin).hostname.toLowerCase();
|
|
4550
|
+
} catch {
|
|
4551
|
+
return void 0;
|
|
4552
|
+
}
|
|
4553
|
+
}
|
|
4554
|
+
function hostHeaderName(host) {
|
|
4555
|
+
try {
|
|
4556
|
+
return new URL(`http://${host}`).hostname.toLowerCase();
|
|
4557
|
+
} catch {
|
|
4558
|
+
return void 0;
|
|
4559
|
+
}
|
|
4560
|
+
}
|
|
4561
|
+
function isLoopbackHost(host) {
|
|
4562
|
+
const name = host.trim().toLowerCase().replace(/\.$/, "");
|
|
4563
|
+
if (name === "localhost" || name === "::1" || name === "[::1]") return true;
|
|
4564
|
+
const quad = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(name);
|
|
4565
|
+
return quad !== null && quad.slice(1).every((octet) => Number(octet) <= 255);
|
|
4566
|
+
}
|
|
4567
|
+
var ALLOWED_REQUEST_HEADERS = "content-type, mcp-session-id, mcp-protocol-version, authorization";
|
|
4568
|
+
function corsHeaders(allowOrigin) {
|
|
2645
4569
|
return {
|
|
2646
|
-
|
|
2647
|
-
"Access-Control-Allow-
|
|
4570
|
+
Vary: "Origin",
|
|
4571
|
+
...allowOrigin !== void 0 ? { "Access-Control-Allow-Origin": allowOrigin } : {},
|
|
4572
|
+
"Access-Control-Allow-Headers": ALLOWED_REQUEST_HEADERS,
|
|
4573
|
+
// Exposed so a cross-origin browser client can actually READ the version the
|
|
4574
|
+
// server is speaking: without this the header is set but invisible to script.
|
|
4575
|
+
"Access-Control-Expose-Headers": "Mcp-Session-Id, Mcp-Protocol-Version",
|
|
2648
4576
|
"Access-Control-Allow-Methods": "GET, POST, OPTIONS"
|
|
2649
4577
|
};
|
|
2650
4578
|
}
|
|
@@ -2670,7 +4598,7 @@ function readBody(req) {
|
|
|
2670
4598
|
import { DatabaseSync } from "node:sqlite";
|
|
2671
4599
|
var KIND_NAMES = ["chat", "task", "notice", "ack"];
|
|
2672
4600
|
function messageToRow(message) {
|
|
2673
|
-
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];
|
|
4601
|
+
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];
|
|
2674
4602
|
}
|
|
2675
4603
|
function rowToMessage(row) {
|
|
2676
4604
|
const id = row.id;
|
|
@@ -2693,6 +4621,23 @@ function rowToMessage(row) {
|
|
|
2693
4621
|
// Chain depth: rows written before the hop column restore without it
|
|
2694
4622
|
// (treated as a chain origin by importHistory — never as a bogus depth).
|
|
2695
4623
|
...typeof row.hop === "number" && Number.isFinite(row.hop) && row.hop > 0 ? { hop: row.hop } : {},
|
|
4624
|
+
// Cursors: rows written before the mseq column restore without it, and are
|
|
4625
|
+
// then reachable only without a `since` cursor (never mistaken for seq 0).
|
|
4626
|
+
...typeof row.mseq === "number" && Number.isFinite(row.mseq) && row.mseq > 0 ? { seq: row.mseq } : {},
|
|
4627
|
+
// Deadline: restored so a message that expired while the hub was down is
|
|
4628
|
+
// dropped rather than delivered late.
|
|
4629
|
+
...typeof row.expires_at === "number" && Number.isFinite(row.expires_at) && row.expires_at > 0 ? { expiresAt: row.expires_at } : {},
|
|
4630
|
+
// Delivery priority: ONLY a real 0 | 1 | 2 restores. Anything else — NULL
|
|
4631
|
+
// from a database written before this column existed, or an out-of-range
|
|
4632
|
+
// value — restores as UNSET, deliberately not as 0. An absent priority is a
|
|
4633
|
+
// different claim from "the sender asked for 0": `compose` keeps an unset
|
|
4634
|
+
// one off the wire and `priorityOf` reads absent as 0 anyway, so writing 0
|
|
4635
|
+
// here would hand every restored message a priority its sender never gave.
|
|
4636
|
+
// That matters because a restored message is re-inserted (lease return,
|
|
4637
|
+
// nack, mail queued while the hub was down) and `insertByPriority` +
|
|
4638
|
+
// overflow dropping then act on it: a p2 instruction restored as p0 loses
|
|
4639
|
+
// its slot to chatter, which is exactly the bug this column prevents.
|
|
4640
|
+
...row.priority === 0 || row.priority === 1 || row.priority === 2 ? { priority: row.priority } : {},
|
|
2696
4641
|
ts
|
|
2697
4642
|
};
|
|
2698
4643
|
}
|
|
@@ -2703,15 +4648,15 @@ var SQLiteStateStore = class {
|
|
|
2703
4648
|
this.db.exec("PRAGMA journal_mode = WAL");
|
|
2704
4649
|
this.db.exec(`
|
|
2705
4650
|
CREATE TABLE IF NOT EXISTS profiles (
|
|
2706
|
-
id TEXT PRIMARY KEY, alias TEXT, client_name TEXT, client_version TEXT, registered_at INTEGER
|
|
4651
|
+
id TEXT PRIMARY KEY, alias TEXT, client_name TEXT, client_version TEXT, registered_at INTEGER, card TEXT
|
|
2707
4652
|
);
|
|
2708
4653
|
CREATE TABLE IF NOT EXISTS messages (
|
|
2709
4654
|
seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, from_peer TEXT NOT NULL,
|
|
2710
|
-
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
|
|
4655
|
+
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
|
|
2711
4656
|
);
|
|
2712
4657
|
CREATE TABLE IF NOT EXISTS mailboxes (
|
|
2713
4658
|
peer TEXT NOT NULL, seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, from_peer TEXT NOT NULL,
|
|
2714
|
-
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
|
|
4659
|
+
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
|
|
2715
4660
|
);
|
|
2716
4661
|
CREATE TABLE IF NOT EXISTS groups (
|
|
2717
4662
|
id TEXT PRIMARY KEY, name TEXT, members TEXT NOT NULL, created_by TEXT NOT NULL, created_at INTEGER NOT NULL
|
|
@@ -2721,13 +4666,17 @@ var SQLiteStateStore = class {
|
|
|
2721
4666
|
);
|
|
2722
4667
|
`);
|
|
2723
4668
|
for (const table of ["messages", "mailboxes"]) {
|
|
2724
|
-
for (const column of ["thread_id TEXT", "hop INTEGER"]) {
|
|
4669
|
+
for (const column of ["thread_id TEXT", "hop INTEGER", "mseq INTEGER", "expires_at INTEGER", "priority INTEGER"]) {
|
|
2725
4670
|
try {
|
|
2726
4671
|
this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column}`);
|
|
2727
4672
|
} catch {
|
|
2728
4673
|
}
|
|
2729
4674
|
}
|
|
2730
4675
|
}
|
|
4676
|
+
try {
|
|
4677
|
+
this.db.exec("ALTER TABLE profiles ADD COLUMN card TEXT");
|
|
4678
|
+
} catch {
|
|
4679
|
+
}
|
|
2731
4680
|
log2.info(`sqlite state open: ${file}`);
|
|
2732
4681
|
}
|
|
2733
4682
|
db;
|
|
@@ -2739,24 +4688,24 @@ var SQLiteStateStore = class {
|
|
|
2739
4688
|
/** Insert buffered messages and re-snapshot mailboxes/profiles/groups/tasks. */
|
|
2740
4689
|
flush(snapshot) {
|
|
2741
4690
|
const insert = this.db.prepare(
|
|
2742
|
-
"INSERT INTO messages (id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
4691
|
+
"INSERT INTO messages (id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop, mseq, expires_at, priority) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
2743
4692
|
);
|
|
2744
4693
|
for (const message of this.buffer.splice(0, this.buffer.length)) {
|
|
2745
4694
|
insert.run(...messageToRow(message));
|
|
2746
4695
|
}
|
|
2747
4696
|
this.db.exec("DELETE FROM mailboxes");
|
|
2748
4697
|
const insertMail = this.db.prepare(
|
|
2749
|
-
"INSERT INTO mailboxes (peer, id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
4698
|
+
"INSERT INTO mailboxes (peer, id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop, mseq, expires_at, priority) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
2750
4699
|
);
|
|
2751
4700
|
for (const [peer, queue] of Object.entries(snapshot.mailboxes)) {
|
|
2752
4701
|
for (const message of queue) insertMail.run(peer, ...messageToRow(message));
|
|
2753
4702
|
}
|
|
2754
4703
|
this.db.exec("DELETE FROM profiles");
|
|
2755
4704
|
const insertProfile = this.db.prepare(
|
|
2756
|
-
"INSERT INTO profiles (id, alias, client_name, client_version, registered_at) VALUES (?, ?, ?, ?, ?)"
|
|
4705
|
+
"INSERT INTO profiles (id, alias, client_name, client_version, registered_at, card) VALUES (?, ?, ?, ?, ?, ?)"
|
|
2757
4706
|
);
|
|
2758
4707
|
for (const profile of snapshot.profiles) {
|
|
2759
|
-
insertProfile.run(profile.id, profile.alias ?? null, profile.clientName ?? null, profile.clientVersion ?? null, profile.registeredAt);
|
|
4708
|
+
insertProfile.run(profile.id, profile.alias ?? null, profile.clientName ?? null, profile.clientVersion ?? null, profile.registeredAt, profile.card === void 0 ? null : JSON.stringify(profile.card));
|
|
2760
4709
|
}
|
|
2761
4710
|
this.db.exec("DELETE FROM groups");
|
|
2762
4711
|
const insertGroup = this.db.prepare(
|
|
@@ -2788,7 +4737,9 @@ var SQLiteStateStore = class {
|
|
|
2788
4737
|
...typeof row.alias === "string" && row.alias !== "" ? { alias: row.alias } : {},
|
|
2789
4738
|
...typeof row.client_name === "string" && row.client_name !== "" ? { clientName: row.client_name } : {},
|
|
2790
4739
|
...typeof row.client_version === "string" && row.client_version !== "" ? { clientVersion: row.client_version } : {},
|
|
2791
|
-
registeredAt: typeof row.registered_at === "number" ? row.registered_at : Date.now()
|
|
4740
|
+
registeredAt: typeof row.registered_at === "number" ? row.registered_at : Date.now(),
|
|
4741
|
+
// A corrupt card row must not take the whole roster down.
|
|
4742
|
+
...cardField(row.card)
|
|
2792
4743
|
});
|
|
2793
4744
|
}
|
|
2794
4745
|
const messages = [];
|
|
@@ -2836,10 +4787,19 @@ var SQLiteStateStore = class {
|
|
|
2836
4787
|
this.db.close();
|
|
2837
4788
|
}
|
|
2838
4789
|
};
|
|
4790
|
+
function cardField(raw) {
|
|
4791
|
+
if (typeof raw !== "string" || raw === "") return {};
|
|
4792
|
+
try {
|
|
4793
|
+
const parsed = JSON.parse(raw);
|
|
4794
|
+
return typeof parsed === "object" && parsed !== null ? { card: parsed } : {};
|
|
4795
|
+
} catch {
|
|
4796
|
+
return {};
|
|
4797
|
+
}
|
|
4798
|
+
}
|
|
2839
4799
|
|
|
2840
4800
|
// src/index.ts
|
|
2841
4801
|
var SERVER_NAME = "agent-comm-hub";
|
|
2842
|
-
var SERVER_VERSION = "0.
|
|
4802
|
+
var SERVER_VERSION = "0.11.0";
|
|
2843
4803
|
var DEFAULT_HOST = "127.0.0.1";
|
|
2844
4804
|
var DEFAULT_PORT = 18764;
|
|
2845
4805
|
var DEFAULT_PATH = "/mcp";
|
|
@@ -2890,23 +4850,60 @@ function writeRosterFile(file, profiles) {
|
|
|
2890
4850
|
writeFileSync2(tmp, JSON.stringify({ version: 1, savedAt: Date.now(), profiles }), "utf8");
|
|
2891
4851
|
renameSync2(tmp, file);
|
|
2892
4852
|
}
|
|
4853
|
+
function readManagerTokenFile(stateFile) {
|
|
4854
|
+
if (stateFile === void 0) return void 0;
|
|
4855
|
+
const file = join(dirname2(stateFile), "manager.token");
|
|
4856
|
+
try {
|
|
4857
|
+
const raw = readFileSync3(file, "utf8").trim();
|
|
4858
|
+
return raw === "" ? void 0 : raw;
|
|
4859
|
+
} catch (error) {
|
|
4860
|
+
if (error.code === "ENOENT") return void 0;
|
|
4861
|
+
throw new Error(`cannot read the manager token ${file}: ${error.message}`);
|
|
4862
|
+
}
|
|
4863
|
+
}
|
|
2893
4864
|
function startHub(config = {}, log2 = console) {
|
|
2894
4865
|
const overrides = Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
|
|
2895
4866
|
const resolved = { ...DEFAULT_CONFIG, ...overrides };
|
|
4867
|
+
const managerToken = resolved.managerToken ?? readManagerTokenFile(resolved.stateFile);
|
|
4868
|
+
if (!isLoopbackHost(resolved.host) && resolved.authTokens === void 0 && resolved.insecure !== true) {
|
|
4869
|
+
throw new Error(
|
|
4870
|
+
`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.`
|
|
4871
|
+
);
|
|
4872
|
+
}
|
|
4873
|
+
if (managerToken === void 0 && resolved.managerPeers !== "all" && !isLoopbackHost(resolved.host)) {
|
|
4874
|
+
log2.warn(
|
|
4875
|
+
`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`
|
|
4876
|
+
);
|
|
4877
|
+
}
|
|
4878
|
+
if (managerToken !== void 0 && resolved.authTokens !== void 0) {
|
|
4879
|
+
log2.warn(
|
|
4880
|
+
"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."
|
|
4881
|
+
);
|
|
4882
|
+
}
|
|
2896
4883
|
let mcp;
|
|
2897
4884
|
let dbStore;
|
|
2898
4885
|
const pushRoster = () => {
|
|
2899
|
-
mcp.notifyAll(
|
|
4886
|
+
mcp.notifyAll(SSE_METHOD, {
|
|
2900
4887
|
level: "info",
|
|
2901
4888
|
logger: "bridge",
|
|
2902
|
-
data: { event:
|
|
4889
|
+
data: { event: SSE_EVENT_PEERS_CHANGED, peers: rosterFor(hub, registry) }
|
|
2903
4890
|
});
|
|
2904
4891
|
};
|
|
4892
|
+
const streamCursor = /* @__PURE__ */ new Map();
|
|
4893
|
+
const oneStreamPer = (key, candidates) => {
|
|
4894
|
+
if (candidates.length === 0) return [];
|
|
4895
|
+
const streamed = registry.liveSessions();
|
|
4896
|
+
const open = candidates.filter((id) => streamed.has(id));
|
|
4897
|
+
const pool = open.length > 0 ? open : candidates;
|
|
4898
|
+
const at = (streamCursor.get(key) ?? 0) % pool.length;
|
|
4899
|
+
streamCursor.set(key, (at + 1) % pool.length);
|
|
4900
|
+
return [pool[at]];
|
|
4901
|
+
};
|
|
2905
4902
|
const pushQueued = (message, target) => {
|
|
2906
|
-
mcp.notify(registry.sessionsForPeer(target),
|
|
4903
|
+
mcp.notify(oneStreamPer(`peer:${target}`, registry.sessionsForPeer(target)), SSE_METHOD, {
|
|
2907
4904
|
level: "info",
|
|
2908
4905
|
logger: "bridge",
|
|
2909
|
-
data: { event:
|
|
4906
|
+
data: { event: SSE_EVENT_MESSAGE, message: present(message) }
|
|
2910
4907
|
});
|
|
2911
4908
|
};
|
|
2912
4909
|
const managerSet = resolved.managerPeers === "all" ? void 0 : new Set(resolved.managerPeers);
|
|
@@ -2915,18 +4912,39 @@ function startHub(config = {}, log2 = console) {
|
|
|
2915
4912
|
for (const sessionId of registry.liveSessions()) {
|
|
2916
4913
|
const peer = registry.peerFor(sessionId);
|
|
2917
4914
|
if (peer === void 0) continue;
|
|
2918
|
-
if (registry
|
|
4915
|
+
if (isManagerCaller(registry, sessionId, peer, { managerPeers: managerSet, managerTokenRequired: managerToken !== void 0 })) {
|
|
2919
4916
|
managers.push(sessionId);
|
|
2920
4917
|
}
|
|
2921
4918
|
}
|
|
2922
4919
|
if (managers.length > 0) {
|
|
2923
|
-
mcp.notify(managers,
|
|
4920
|
+
mcp.notify(oneStreamPer("relay", managers), SSE_METHOD, {
|
|
2924
4921
|
level: "info",
|
|
2925
4922
|
logger: "bridge",
|
|
2926
|
-
data: { event:
|
|
4923
|
+
data: { event: SSE_EVENT_MESSAGE, message: present(message) }
|
|
2927
4924
|
});
|
|
2928
4925
|
}
|
|
2929
4926
|
};
|
|
4927
|
+
const MAX_TASK_PUSH_MEMORY = 512;
|
|
4928
|
+
const lastTaskPush = /* @__PURE__ */ new Map();
|
|
4929
|
+
const pushTaskChanged = (task) => {
|
|
4930
|
+
const data = {
|
|
4931
|
+
event: SSE_EVENT_TASK_CHANGED,
|
|
4932
|
+
taskId: task.id,
|
|
4933
|
+
status: task.status,
|
|
4934
|
+
// A2A naming, so a client that speaks A2A does not have to carry the
|
|
4935
|
+
// ledger's own vocabulary — same mapping bridge_task_status publishes.
|
|
4936
|
+
a2aState: a2aState(task.status),
|
|
4937
|
+
updatedAt: task.updatedAt
|
|
4938
|
+
};
|
|
4939
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4940
|
+
for (const peer of [task.from, ...task.assignees.map((assignee) => assignee.peerId)]) {
|
|
4941
|
+
if (seen.has(peer)) continue;
|
|
4942
|
+
seen.add(peer);
|
|
4943
|
+
const sessions = registry.sessionsForPeer(peer);
|
|
4944
|
+
if (sessions.length === 0) continue;
|
|
4945
|
+
mcp.notify(oneStreamPer(`task:${peer}`, sessions), SSE_METHOD, { level: "info", logger: "bridge", data });
|
|
4946
|
+
}
|
|
4947
|
+
};
|
|
2930
4948
|
let saveTimer;
|
|
2931
4949
|
let rosterDirty = false;
|
|
2932
4950
|
let dbDirty = false;
|
|
@@ -2957,12 +4975,64 @@ function startHub(config = {}, log2 = console) {
|
|
|
2957
4975
|
}, 500);
|
|
2958
4976
|
saveTimer.unref?.();
|
|
2959
4977
|
};
|
|
4978
|
+
let runnerRegistry;
|
|
4979
|
+
const runnerQueue = /* @__PURE__ */ new Map();
|
|
4980
|
+
const taskPayload = (content) => {
|
|
4981
|
+
try {
|
|
4982
|
+
const parsed = JSON.parse(content);
|
|
4983
|
+
return {
|
|
4984
|
+
prompt: typeof parsed.prompt === "string" ? parsed.prompt : content,
|
|
4985
|
+
...typeof parsed.context === "string" ? { context: parsed.context } : {},
|
|
4986
|
+
...typeof parsed.deliverable === "string" ? { deliverable: parsed.deliverable } : {},
|
|
4987
|
+
...typeof parsed.threadId === "string" ? { threadId: parsed.threadId } : {}
|
|
4988
|
+
};
|
|
4989
|
+
} catch {
|
|
4990
|
+
return { prompt: content };
|
|
4991
|
+
}
|
|
4992
|
+
};
|
|
4993
|
+
function runTask(message, target) {
|
|
4994
|
+
const runner = runnerRegistry?.get(target);
|
|
4995
|
+
if (runner === void 0) return;
|
|
4996
|
+
const previous = runnerQueue.get(target) ?? Promise.resolve();
|
|
4997
|
+
const next = previous.then(async () => {
|
|
4998
|
+
const payload = taskPayload(message.content);
|
|
4999
|
+
hub.noteEvent("runner_started", { peer: target, detail: { taskId: message.id, runner: runner.name } });
|
|
5000
|
+
try {
|
|
5001
|
+
const result = await runner.run({ taskId: message.id, peer: target, ...payload });
|
|
5002
|
+
hub.noteEvent("runner_finished", { peer: target, detail: { taskId: message.id, runner: runner.name, status: result.status } });
|
|
5003
|
+
hub.ackForRunner(target, message.id, { status: result.status, note: result.note });
|
|
5004
|
+
log2.info(`runner ${runner.name}: task ${message.id} for '${target}' -> ${result.status}`);
|
|
5005
|
+
} catch (error) {
|
|
5006
|
+
hub.noteEvent("runner_finished", { peer: target, detail: { taskId: message.id, runner: runner.name, status: "failed", error: error.message } });
|
|
5007
|
+
try {
|
|
5008
|
+
hub.ackForRunner(target, message.id, { status: "failed", note: `runner error: ${error.message}` });
|
|
5009
|
+
} catch {
|
|
5010
|
+
}
|
|
5011
|
+
log2.warn(`runner ${runner.name} errored on task ${message.id}: ${error.message}`);
|
|
5012
|
+
}
|
|
5013
|
+
});
|
|
5014
|
+
runnerQueue.set(target, next.catch(() => {
|
|
5015
|
+
}));
|
|
5016
|
+
}
|
|
2960
5017
|
const hub = new AgentHub({
|
|
2961
5018
|
maxQueue: resolved.maxQueue,
|
|
2962
5019
|
historyLimit: resolved.historyLimit,
|
|
2963
5020
|
waitTimeoutMs: resolved.waitTimeoutMs,
|
|
2964
5021
|
connectedWindowMs: resolved.connectedWindowMs,
|
|
2965
5022
|
peerIdleTimeoutMs: resolved.peerIdleTimeoutMs,
|
|
5023
|
+
parkedTtlMs: resolved.parkedTtlMs,
|
|
5024
|
+
leaseTtlMs: resolved.leaseTtlMs,
|
|
5025
|
+
maxAttempts: resolved.maxAttempts,
|
|
5026
|
+
ratePerMin: resolved.ratePerMin,
|
|
5027
|
+
// A parked mailbox that expires is data loss: say so, and make the store
|
|
5028
|
+
// re-snapshot so the dropped rows cannot resurrect on the next restart.
|
|
5029
|
+
onMailboxExpired: (peerId, dropped) => {
|
|
5030
|
+
log2.warn(`parked mailbox for '${peerId}' expired after ${resolved.parkedTtlMs ?? DEFAULT_PARKED_TTL_MS}ms: ${dropped} message(s) dropped`);
|
|
5031
|
+
if (dbStore !== void 0) {
|
|
5032
|
+
dbDirty = true;
|
|
5033
|
+
scheduleSave();
|
|
5034
|
+
}
|
|
5035
|
+
},
|
|
2966
5036
|
onPeerGc: (peerId) => registry.unbindPeerId(peerId),
|
|
2967
5037
|
// Remote persistence: buffer every history append; re-snapshot when a
|
|
2968
5038
|
// mailbox is consumed so drained messages cannot resurrect on restart.
|
|
@@ -2987,11 +5057,26 @@ function startHub(config = {}, log2 = console) {
|
|
|
2987
5057
|
},
|
|
2988
5058
|
// Task ledger transitions (ack folding, SLA timeout, first delivery) are
|
|
2989
5059
|
// their own persistence trigger: without it a crash between two roster
|
|
2990
|
-
// events loses the ledger state the admin board reads back.
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
5060
|
+
// events loses the ledger state the admin board reads back. They are also
|
|
5061
|
+
// the SSE `task_changed` signal for the two parties of a task.
|
|
5062
|
+
onTaskChanged: (task) => {
|
|
5063
|
+
if (dbStore !== void 0) {
|
|
5064
|
+
dbDirty = true;
|
|
5065
|
+
scheduleSave();
|
|
5066
|
+
}
|
|
5067
|
+
if (lastTaskPush.get(task.id) === task.status) return;
|
|
5068
|
+
try {
|
|
5069
|
+
pushTaskChanged(task);
|
|
5070
|
+
} catch (error) {
|
|
5071
|
+
log2.warn(`task_changed notification failed: ${error.message}`);
|
|
5072
|
+
}
|
|
5073
|
+
lastTaskPush.delete(task.id);
|
|
5074
|
+
lastTaskPush.set(task.id, task.status);
|
|
5075
|
+
while (lastTaskPush.size > MAX_TASK_PUSH_MEMORY) {
|
|
5076
|
+
const oldest = lastTaskPush.keys().next().value;
|
|
5077
|
+
if (oldest === void 0) break;
|
|
5078
|
+
lastTaskPush.delete(oldest);
|
|
5079
|
+
}
|
|
2995
5080
|
},
|
|
2996
5081
|
onGroupsChanged: () => {
|
|
2997
5082
|
if (dbStore === void 0) return;
|
|
@@ -3018,6 +5103,17 @@ function startHub(config = {}, log2 = console) {
|
|
|
3018
5103
|
} catch (error) {
|
|
3019
5104
|
log2.warn(`message notification failed: ${error.message}`);
|
|
3020
5105
|
}
|
|
5106
|
+
},
|
|
5107
|
+
// A task that reached a mailbox has nobody polling for it. If this peer has
|
|
5108
|
+
// a runner configured, wake it — that is the whole point of a runner.
|
|
5109
|
+
// `runnerRegistry` is filled in below, once the herdr adapter exists; this
|
|
5110
|
+
// hook only ever fires after the hub is serving.
|
|
5111
|
+
onTaskQueued: (message, target) => {
|
|
5112
|
+
try {
|
|
5113
|
+
runTask(message, target);
|
|
5114
|
+
} catch (error) {
|
|
5115
|
+
log2.warn(`runner dispatch failed for '${target}': ${error.message}`);
|
|
5116
|
+
}
|
|
3021
5117
|
}
|
|
3022
5118
|
});
|
|
3023
5119
|
const registry = new SessionRegistry();
|
|
@@ -3040,9 +5136,9 @@ function startHub(config = {}, log2 = console) {
|
|
|
3040
5136
|
log2.info(`roster restored: ${importedProfiles} profile(s) from ${resolved.db}`);
|
|
3041
5137
|
}
|
|
3042
5138
|
const restoredMessages = hub.importHistory(state.messages);
|
|
3043
|
-
const restoredQueued = hub.importMailboxes(state.mailboxes);
|
|
3044
5139
|
const restoredGroups = hub.importGroups(state.groups);
|
|
3045
5140
|
const restoredTasks = hub.importTasks(state.tasks);
|
|
5141
|
+
const restoredQueued = hub.importMailboxes(state.mailboxes);
|
|
3046
5142
|
if (restoredMessages + restoredQueued + restoredGroups > 0) {
|
|
3047
5143
|
log2.info(`state restored from ${resolved.db}: ${restoredMessages} message(s), ${restoredQueued} queued, ${restoredGroups} group(s)`);
|
|
3048
5144
|
dbDirty = true;
|
|
@@ -3070,6 +5166,8 @@ function startHub(config = {}, log2 = console) {
|
|
|
3070
5166
|
socketPath: resolved.herdrSocketPath,
|
|
3071
5167
|
sendRequest: resolved.herdrSendRequest
|
|
3072
5168
|
});
|
|
5169
|
+
runnerRegistry = new RunnerRegistry(resolved.runners ?? [], { herdr });
|
|
5170
|
+
if (runnerRegistry.size > 0) log2.info(`runners configured for: ${runnerRegistry.peers().join(", ")}`);
|
|
3073
5171
|
let auth;
|
|
3074
5172
|
let authReload;
|
|
3075
5173
|
if (resolved.authTokens !== void 0) {
|
|
@@ -3095,7 +5193,14 @@ function startHub(config = {}, log2 = console) {
|
|
|
3095
5193
|
waitTimeoutMs: resolved.waitTimeoutMs,
|
|
3096
5194
|
herdr,
|
|
3097
5195
|
herdrControlPeers: resolved.herdrControlPeers === "all" || resolved.herdrControlPeers === void 0 ? "all" : new Set(resolved.herdrControlPeers),
|
|
3098
|
-
managerPeers: resolved.managerPeers === "all" ? "all" : new Set(resolved.managerPeers ?? DEFAULT_CONFIG.managerPeers)
|
|
5196
|
+
managerPeers: resolved.managerPeers === "all" ? "all" : new Set(resolved.managerPeers ?? DEFAULT_CONFIG.managerPeers),
|
|
5197
|
+
managerTokenRequired: managerToken !== void 0,
|
|
5198
|
+
// Token identities are an authorization fact of the TABLE, not of the live
|
|
5199
|
+
// sessions: `bridge_rename` must not re-key onto a configured id whose
|
|
5200
|
+
// owner has not connected yet. Read from the file on every call because
|
|
5201
|
+
// the token admin API adds/removes rows at runtime (and `readTokens`
|
|
5202
|
+
// returns [] in loopback mode, where no id is reserved).
|
|
5203
|
+
...resolved.authTokens === void 0 ? {} : { tokenPeers: () => new Set(readTokens(resolved.authTokens).map((row) => row.peer)) }
|
|
3099
5204
|
}),
|
|
3100
5205
|
{ name: SERVER_NAME, version: SERVER_VERSION },
|
|
3101
5206
|
registry,
|
|
@@ -3122,12 +5227,15 @@ function startHub(config = {}, log2 = console) {
|
|
|
3122
5227
|
},
|
|
3123
5228
|
auth,
|
|
3124
5229
|
authTokensAdmin(resolved.authTokens, authReload),
|
|
3125
|
-
resolved.heartbeatMs
|
|
5230
|
+
resolved.heartbeatMs,
|
|
5231
|
+
resolved.allowOrigins === void 0 || resolved.allowOrigins.length === 0 ? void 0 : { allow: new Set(resolved.allowOrigins) },
|
|
5232
|
+
managerToken,
|
|
5233
|
+
resolved.sessionTtlMs
|
|
3126
5234
|
);
|
|
3127
5235
|
const server = createServer();
|
|
3128
5236
|
mcp.attach(server, resolved.path);
|
|
3129
5237
|
server.on("error", (error) => log2.warn(`hub http server error: ${error.message}`));
|
|
3130
|
-
server.listen(resolved.port, resolved.host, () => {
|
|
5238
|
+
server.listen(resolved.port, resolved.host.trim(), () => {
|
|
3131
5239
|
log2.info(`agent-comm-hub listening on http://${resolved.host}:${resolved.port}${resolved.path}`);
|
|
3132
5240
|
});
|
|
3133
5241
|
return {
|
|
@@ -3161,20 +5269,30 @@ function startHub(config = {}, log2 = console) {
|
|
|
3161
5269
|
import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3162
5270
|
import { existsSync as existsSync3 } from "node:fs";
|
|
3163
5271
|
import { homedir as homedir2 } from "node:os";
|
|
3164
|
-
import { dirname as dirname4, join as
|
|
5272
|
+
import { dirname as dirname4, join as join3 } from "node:path";
|
|
3165
5273
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
3166
5274
|
|
|
3167
5275
|
// src/discover.ts
|
|
3168
5276
|
import { execFileSync } from "node:child_process";
|
|
3169
5277
|
import { existsSync as existsSync2, readdirSync, accessSync, readFileSync as readFileSync4, constants as fsConstants } from "node:fs";
|
|
3170
5278
|
import { homedir } from "node:os";
|
|
3171
|
-
import { dirname as dirname3, join, sep } from "node:path";
|
|
5279
|
+
import { dirname as dirname3, join as join2, sep } from "node:path";
|
|
3172
5280
|
import { fileURLToPath } from "node:url";
|
|
5281
|
+
var CREDENTIAL_FILES = [
|
|
5282
|
+
"~/.claude.json",
|
|
5283
|
+
"~/.dsh/.credentials.yaml",
|
|
5284
|
+
"~/.dsh/settings.yaml",
|
|
5285
|
+
"~/.codex/auth.json",
|
|
5286
|
+
"~/.qwen/mcp-oauth-tokens.json"
|
|
5287
|
+
];
|
|
5288
|
+
function configsForPlatform(agent, platform) {
|
|
5289
|
+
return agent.configs.filter((config) => config.os === void 0 || config.os.includes(platform));
|
|
5290
|
+
}
|
|
3173
5291
|
function registryFile() {
|
|
3174
|
-
return
|
|
5292
|
+
return join2(dirname3(fileURLToPath(import.meta.url)), "..", "agents", "registry.json");
|
|
3175
5293
|
}
|
|
3176
5294
|
function expandHome(file, home) {
|
|
3177
|
-
return file.startsWith("~/") ?
|
|
5295
|
+
return file.startsWith("~/") ? join2(home, file.slice(2)) : file;
|
|
3178
5296
|
}
|
|
3179
5297
|
function expandConfigFile(file, home) {
|
|
3180
5298
|
const expanded = expandHome(file, home);
|
|
@@ -3184,7 +5302,10 @@ function expandConfigFile(file, home) {
|
|
|
3184
5302
|
const suffix = expanded.slice(star + 1);
|
|
3185
5303
|
const base = prefix.slice(0, prefix.lastIndexOf(sep));
|
|
3186
5304
|
if (!existsSync2(base)) return [];
|
|
3187
|
-
|
|
5305
|
+
if (suffix.startsWith(sep) === false) {
|
|
5306
|
+
return readdirSync(base, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(suffix)).map((entry) => join2(base, entry.name));
|
|
5307
|
+
}
|
|
5308
|
+
return readdirSync(base, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join2(base, entry.name, suffix));
|
|
3188
5309
|
}
|
|
3189
5310
|
function validateRegistry(registry) {
|
|
3190
5311
|
if (!Array.isArray(registry.agents)) throw new Error('registry: missing "agents" array');
|
|
@@ -3197,6 +5318,17 @@ function validateRegistry(registry) {
|
|
|
3197
5318
|
ids.add(agent.id);
|
|
3198
5319
|
if (!Array.isArray(agent.probe)) throw new Error(`registry: ${agent.id}: probe must be an array`);
|
|
3199
5320
|
if (agent.npm !== void 0 && !Array.isArray(agent.npm)) throw new Error(`registry: ${agent.id}: npm must be an array`);
|
|
5321
|
+
if (agent.probePaths !== void 0) {
|
|
5322
|
+
if (!Array.isArray(agent.probePaths)) throw new Error(`registry: ${agent.id}: probePaths must be an array`);
|
|
5323
|
+
for (const probePath of agent.probePaths) {
|
|
5324
|
+
if (typeof probePath !== "string" || !probePath.startsWith("~/")) {
|
|
5325
|
+
throw new Error(`registry: ${agent.id}: probePath must be '~'-relative`);
|
|
5326
|
+
}
|
|
5327
|
+
if (probePath.split("/").includes("..")) {
|
|
5328
|
+
throw new Error(`registry: ${agent.id}: probePath must not contain '..'`);
|
|
5329
|
+
}
|
|
5330
|
+
}
|
|
5331
|
+
}
|
|
3200
5332
|
if (!Array.isArray(agent.configs)) throw new Error(`registry: ${agent.id}: configs must be an array`);
|
|
3201
5333
|
for (const config of agent.configs) {
|
|
3202
5334
|
if (typeof config.file !== "string" || !config.file.startsWith("~/")) {
|
|
@@ -3208,14 +5340,23 @@ function validateRegistry(registry) {
|
|
|
3208
5340
|
if (config.file.split("*").length > 2) {
|
|
3209
5341
|
throw new Error(`registry: ${agent.id}: at most one '*' segment allowed`);
|
|
3210
5342
|
}
|
|
3211
|
-
if (!["json", "toml", "dsh"].includes(config.strategy)) {
|
|
5343
|
+
if (!["json", "toml", "dsh", "yaml-array"].includes(config.strategy)) {
|
|
3212
5344
|
throw new Error(`registry: ${agent.id}: unknown strategy '${config.strategy}'`);
|
|
3213
5345
|
}
|
|
3214
|
-
if (config.
|
|
3215
|
-
throw new Error(`registry: ${agent.id}:
|
|
5346
|
+
if (config.os !== void 0 && (!Array.isArray(config.os) || config.os.length === 0 || config.os.some((entry) => !["win32", "darwin", "linux"].includes(entry)))) {
|
|
5347
|
+
throw new Error(`registry: ${agent.id}: invalid config os list`);
|
|
3216
5348
|
}
|
|
3217
|
-
if (
|
|
3218
|
-
throw new Error(
|
|
5349
|
+
if (CREDENTIAL_FILES.includes(config.file)) {
|
|
5350
|
+
throw new Error(
|
|
5351
|
+
`registry: ${agent.id}: ${config.file} holds credentials and must never be written \u2014 point the record at a separate MCP config file, or leave the agent manual (AGENTS.md invariant 6)`
|
|
5352
|
+
);
|
|
5353
|
+
}
|
|
5354
|
+
const keyed = config.strategy === "json" || config.strategy === "yaml-array";
|
|
5355
|
+
if (keyed && (typeof config.section !== "string" || config.entry === null)) {
|
|
5356
|
+
throw new Error(`registry: ${agent.id}: ${config.strategy} strategy needs a section and an entry`);
|
|
5357
|
+
}
|
|
5358
|
+
if (!keyed && config.entry !== null) {
|
|
5359
|
+
throw new Error(`registry: ${agent.id}: only json/yaml-array strategy may carry an entry`);
|
|
3219
5360
|
}
|
|
3220
5361
|
}
|
|
3221
5362
|
if (agent.skill !== null && (typeof agent.skill !== "string" || !agent.skill.startsWith("~/"))) {
|
|
@@ -3240,7 +5381,7 @@ function commandOnPath(command, pathEnv, pathext, platform) {
|
|
|
3240
5381
|
for (const dir of dirs) {
|
|
3241
5382
|
const base = dir === "" ? "." : dir;
|
|
3242
5383
|
for (const ext of extensions) {
|
|
3243
|
-
const candidate =
|
|
5384
|
+
const candidate = join2(base, command + ext);
|
|
3244
5385
|
try {
|
|
3245
5386
|
accessSync(candidate, fsConstants.X_OK);
|
|
3246
5387
|
return true;
|
|
@@ -3255,7 +5396,7 @@ function readNpmNames(root) {
|
|
|
3255
5396
|
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
|
3256
5397
|
if (!entry.isDirectory()) continue;
|
|
3257
5398
|
if (entry.name.startsWith("@")) {
|
|
3258
|
-
const scopeDir =
|
|
5399
|
+
const scopeDir = join2(root, entry.name);
|
|
3259
5400
|
for (const sub of readdirSync(scopeDir, { withFileTypes: true })) {
|
|
3260
5401
|
if (sub.isDirectory()) names.push(sub.name);
|
|
3261
5402
|
}
|
|
@@ -3275,13 +5416,13 @@ function npmGlobalRoot(platform) {
|
|
|
3275
5416
|
}
|
|
3276
5417
|
function npmFallbackRoots(home, platform) {
|
|
3277
5418
|
if (platform === "win32") {
|
|
3278
|
-
const appData = process.env.APPDATA ??
|
|
3279
|
-
return [
|
|
5419
|
+
const appData = process.env.APPDATA ?? join2(home, "AppData", "Roaming");
|
|
5420
|
+
return [join2(appData, "npm", "node_modules")];
|
|
3280
5421
|
}
|
|
3281
5422
|
return [
|
|
3282
5423
|
"/usr/local/lib/node_modules",
|
|
3283
5424
|
"/usr/lib/node_modules",
|
|
3284
|
-
...existsSync2(
|
|
5425
|
+
...existsSync2(join2(home, ".nvm", "versions", "node")) ? readdirSync(join2(home, ".nvm", "versions", "node")).map((dir) => join2(home, ".nvm", "versions", "node", dir, "lib", "node_modules")) : []
|
|
3285
5426
|
];
|
|
3286
5427
|
}
|
|
3287
5428
|
function discover(registry, options = {}) {
|
|
@@ -3311,21 +5452,25 @@ function discover(registry, options = {}) {
|
|
|
3311
5452
|
return registry.agents.filter((agent) => agent.os === void 0 || agent.os.includes(platform)).map((agent) => {
|
|
3312
5453
|
let source = "none";
|
|
3313
5454
|
const configFiles = [];
|
|
3314
|
-
for (const config of agent
|
|
5455
|
+
for (const config of configsForPlatform(agent, platform)) {
|
|
3315
5456
|
for (const file of expandConfigFile(config.file, home)) {
|
|
3316
|
-
if (existsSync2(file))
|
|
3317
|
-
configFiles.push(file);
|
|
3318
|
-
if (source === "none") source = "config";
|
|
3319
|
-
}
|
|
5457
|
+
if (existsSync2(file)) configFiles.push(file);
|
|
3320
5458
|
}
|
|
3321
5459
|
}
|
|
3322
|
-
|
|
5460
|
+
let installed = false;
|
|
5461
|
+
if (agent.probe.some((command) => commandOnPath(command, pathEnv, pathext, platform))) {
|
|
3323
5462
|
source = "path";
|
|
3324
|
-
|
|
3325
|
-
if (
|
|
5463
|
+
installed = true;
|
|
5464
|
+
} else if (npmNames !== null && (agent.probe.some((command) => npmNames.includes(command)) || (agent.npm ?? []).some((name) => npmNames.includes(name)))) {
|
|
3326
5465
|
source = "npm";
|
|
5466
|
+
installed = true;
|
|
5467
|
+
} else if ((agent.probePaths ?? []).some((probePath) => existsSync2(expandHome(probePath, home)))) {
|
|
5468
|
+
source = "probe-path";
|
|
5469
|
+
installed = true;
|
|
3327
5470
|
}
|
|
3328
|
-
|
|
5471
|
+
const configOnly = !installed && configFiles.length > 0;
|
|
5472
|
+
if (!installed && configOnly) source = "config";
|
|
5473
|
+
return { id: agent.id, source, configFiles, present: installed, configOnly };
|
|
3329
5474
|
});
|
|
3330
5475
|
}
|
|
3331
5476
|
function runDiscover(options = {}) {
|
|
@@ -3344,7 +5489,7 @@ function runDiscover(options = {}) {
|
|
|
3344
5489
|
var DEFAULT_URL = "http://127.0.0.1:18764/mcp";
|
|
3345
5490
|
var DEFAULT_SERVER = "agent-hub";
|
|
3346
5491
|
function defaultSkillSrc() {
|
|
3347
|
-
return
|
|
5492
|
+
return join3(dirname4(fileURLToPath2(import.meta.url)), "..", "agents", "SKILL.md");
|
|
3348
5493
|
}
|
|
3349
5494
|
function stamp() {
|
|
3350
5495
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -3380,6 +5525,19 @@ function resolveSection(doc, section) {
|
|
|
3380
5525
|
}
|
|
3381
5526
|
return node;
|
|
3382
5527
|
}
|
|
5528
|
+
function sameJson(a, b) {
|
|
5529
|
+
if (a === b) return true;
|
|
5530
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
|
|
5531
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
5532
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
5533
|
+
return a.length === b.length && a.every((item, index) => sameJson(item, b[index]));
|
|
5534
|
+
}
|
|
5535
|
+
const left = a;
|
|
5536
|
+
const right = b;
|
|
5537
|
+
const leftKeys = Object.keys(left);
|
|
5538
|
+
if (leftKeys.length !== Object.keys(right).length) return false;
|
|
5539
|
+
return leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && sameJson(left[key], right[key]));
|
|
5540
|
+
}
|
|
3383
5541
|
async function mergeJsonServer(file, section, entry, opts) {
|
|
3384
5542
|
if (!existsSync3(file)) return "skipped";
|
|
3385
5543
|
const doc = await readJson(file);
|
|
@@ -3393,10 +5551,7 @@ async function mergeJsonServer(file, section, entry, opts) {
|
|
|
3393
5551
|
await writeJsonNoBom(file, doc);
|
|
3394
5552
|
return "removed";
|
|
3395
5553
|
}
|
|
3396
|
-
if (has)
|
|
3397
|
-
const existing = servers[opts.serverName];
|
|
3398
|
-
if (existing?.url === opts.url) return "unchanged";
|
|
3399
|
-
}
|
|
5554
|
+
if (has && sameJson(servers[opts.serverName], entry)) return "unchanged";
|
|
3400
5555
|
servers[opts.serverName] = entry;
|
|
3401
5556
|
await backup(file);
|
|
3402
5557
|
await writeJsonNoBom(file, doc);
|
|
@@ -3407,19 +5562,25 @@ async function mergeTomlSection(file, opts) {
|
|
|
3407
5562
|
const text = await readFile(file, "utf8");
|
|
3408
5563
|
const marker = `[mcp_servers.${opts.serverName}]`;
|
|
3409
5564
|
const markerRe = new RegExp(`^\\[mcp_servers\\.${escapeRegExp(opts.serverName)}\\]`, "m");
|
|
5565
|
+
const sectionRe = new RegExp(`^\\[mcp_servers\\.${escapeRegExp(opts.serverName)}\\][^\\r\\n]*(\\r?\\n(?!\\[).*)*(\\r?\\n)?`, "m");
|
|
3410
5566
|
if (opts.remove) {
|
|
3411
5567
|
if (!markerRe.test(text)) return "absent";
|
|
3412
|
-
const cleaned = text.replace(
|
|
5568
|
+
const cleaned = text.replace(sectionRe, "");
|
|
3413
5569
|
await backup(file);
|
|
3414
5570
|
await writeFile(file, cleaned, "utf8");
|
|
3415
5571
|
return "removed";
|
|
3416
5572
|
}
|
|
3417
|
-
if (markerRe.test(text)) return "unchanged";
|
|
3418
5573
|
const block = `
|
|
3419
5574
|
${marker}
|
|
3420
5575
|
type = "streamable-http"
|
|
3421
5576
|
url = "${opts.url}"
|
|
3422
5577
|
`;
|
|
5578
|
+
if (markerRe.test(text)) {
|
|
5579
|
+
if (text.includes(block.trimStart())) return "unchanged";
|
|
5580
|
+
await backup(file);
|
|
5581
|
+
await writeFile(file, text.replace(sectionRe, "").trimEnd() + block, "utf8");
|
|
5582
|
+
return "changed";
|
|
5583
|
+
}
|
|
3423
5584
|
await backup(file);
|
|
3424
5585
|
await writeFile(file, text.trimEnd() + block, "utf8");
|
|
3425
5586
|
return "changed";
|
|
@@ -3482,6 +5643,82 @@ async function mergeDshPatch(file, opts) {
|
|
|
3482
5643
|
await writeFile(file, withoutHubEntries().trimEnd() + dshPatchBlock(opts.url, opts.serverName), "utf8");
|
|
3483
5644
|
return "changed";
|
|
3484
5645
|
}
|
|
5646
|
+
async function mergeYamlArrayServer(file, opts) {
|
|
5647
|
+
if (!existsSync3(file)) return "skipped";
|
|
5648
|
+
const text = await readFile(file, "utf8");
|
|
5649
|
+
const lines = text.split("\n");
|
|
5650
|
+
const keyIndex = lines.findIndex((line) => /^mcpServers:\s*(#.*)?$/.test(line));
|
|
5651
|
+
const inlineKey = lines.findIndex((line) => /^mcpServers:\s*\S/.test(line));
|
|
5652
|
+
if (keyIndex === -1) {
|
|
5653
|
+
if (inlineKey !== -1) return "unrecognized";
|
|
5654
|
+
}
|
|
5655
|
+
const blockEnd = (from) => {
|
|
5656
|
+
for (let i = from + 1; i < lines.length; i++) {
|
|
5657
|
+
const line = lines[i];
|
|
5658
|
+
if (line.trim() === "" || line.startsWith("#")) continue;
|
|
5659
|
+
if (!/^\s/.test(line)) return i;
|
|
5660
|
+
}
|
|
5661
|
+
return lines.length;
|
|
5662
|
+
};
|
|
5663
|
+
const items = (from, to2) => {
|
|
5664
|
+
const starts = [];
|
|
5665
|
+
for (let i = from; i < to2; i++) {
|
|
5666
|
+
if (/^\s*-\s/.test(lines[i])) starts.push(i);
|
|
5667
|
+
}
|
|
5668
|
+
return starts.map((start, k) => ({ start, end: k + 1 < starts.length ? starts[k + 1] : to2 }));
|
|
5669
|
+
};
|
|
5670
|
+
const isOurs = (item) => lines.slice(item.start, item.end).some((line) => new RegExp(`^\\s*-?\\s*name:\\s*${opts.serverName}\\s*$`).test(line));
|
|
5671
|
+
if (keyIndex === -1) {
|
|
5672
|
+
if (opts.remove) return "absent";
|
|
5673
|
+
await backup(file);
|
|
5674
|
+
const block = `mcpServers:
|
|
5675
|
+
${yamlArrayItem(opts.serverName, opts.url, opts.entry, " ")}`;
|
|
5676
|
+
await writeFile(file, `${text.replace(/\n*$/, "")}
|
|
5677
|
+
${block}
|
|
5678
|
+
`, "utf8");
|
|
5679
|
+
return "changed";
|
|
5680
|
+
}
|
|
5681
|
+
const to = blockEnd(keyIndex);
|
|
5682
|
+
const ours = items(keyIndex + 1, to).filter(isOurs);
|
|
5683
|
+
const all = items(keyIndex + 1, to);
|
|
5684
|
+
const bodyLines = lines.slice(keyIndex + 1, to).filter((line) => line.trim() !== "" && !line.trim().startsWith("#"));
|
|
5685
|
+
if (all.length === 0 && bodyLines.length > 0) return "unrecognized";
|
|
5686
|
+
const indent = ours.length > 0 ? lines[ours[0].start].match(/^(\s*)/)?.[1] ?? " " : all.length > 0 ? lines[all[0].start].match(/^(\s*)/)?.[1] ?? " " : " ";
|
|
5687
|
+
if (opts.remove) {
|
|
5688
|
+
if (ours.length === 0) return "absent";
|
|
5689
|
+
await backup(file);
|
|
5690
|
+
const out2 = lines.slice();
|
|
5691
|
+
for (const item of ours.reverse()) out2.splice(item.start, item.end - item.start);
|
|
5692
|
+
await writeFile(file, out2.join("\n"), "utf8");
|
|
5693
|
+
return "removed";
|
|
5694
|
+
}
|
|
5695
|
+
const wanted = yamlArrayItem(opts.serverName, opts.url, opts.entry, indent);
|
|
5696
|
+
if (ours.length === 1 && lines.slice(ours[0].start, ours[0].end).join("\n").trimEnd() === wanted.trimEnd()) {
|
|
5697
|
+
return "unchanged";
|
|
5698
|
+
}
|
|
5699
|
+
await backup(file);
|
|
5700
|
+
const out = lines.slice();
|
|
5701
|
+
const first = ours[0]?.start ?? to;
|
|
5702
|
+
for (const item of ours.reverse()) out.splice(item.start, item.end - item.start);
|
|
5703
|
+
const insertAt = ours.length > 0 ? first : to;
|
|
5704
|
+
out.splice(insertAt, 0, ...wanted.replace(/\n$/, "").split("\n"));
|
|
5705
|
+
await writeFile(file, out.join("\n"), "utf8");
|
|
5706
|
+
return "changed";
|
|
5707
|
+
}
|
|
5708
|
+
function yamlArrayItem(serverName, url, entry, indent) {
|
|
5709
|
+
const substituted = substitute2(entry, { url, serverName });
|
|
5710
|
+
const keys = Object.entries(substituted);
|
|
5711
|
+
const inner = `${indent} `;
|
|
5712
|
+
const head = `${indent}- name: ${serverName}
|
|
5713
|
+
`;
|
|
5714
|
+
return head + keys.map(([key, value]) => `${inner}${key}: ${yamlScalar(value)}
|
|
5715
|
+
`).join("");
|
|
5716
|
+
}
|
|
5717
|
+
function yamlScalar(value) {
|
|
5718
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
5719
|
+
const text = String(value ?? "");
|
|
5720
|
+
return /^[A-Za-z0-9._/:@-]+$/.test(text) ? text : JSON.stringify(text);
|
|
5721
|
+
}
|
|
3485
5722
|
async function syncSkill(skillDir, skillSrc, remove, log2) {
|
|
3486
5723
|
if (remove) {
|
|
3487
5724
|
if (existsSync3(skillDir)) {
|
|
@@ -3496,14 +5733,14 @@ async function syncSkill(skillDir, skillSrc, remove, log2) {
|
|
|
3496
5733
|
return;
|
|
3497
5734
|
}
|
|
3498
5735
|
await mkdir(skillDir, { recursive: true });
|
|
3499
|
-
await copyFile(skillSrc,
|
|
3500
|
-
log2(` skill -> ${
|
|
5736
|
+
await copyFile(skillSrc, join3(skillDir, "SKILL.md"));
|
|
5737
|
+
log2(` skill -> ${join3(skillDir, "SKILL.md")}`);
|
|
3501
5738
|
}
|
|
3502
5739
|
async function rmRecursive(dir) {
|
|
3503
5740
|
const { rm } = await import("node:fs/promises");
|
|
3504
5741
|
await rm(dir, { recursive: true, force: true });
|
|
3505
5742
|
}
|
|
3506
|
-
function
|
|
5743
|
+
function substitute2(entry, values) {
|
|
3507
5744
|
const out = {};
|
|
3508
5745
|
for (const [key, value] of Object.entries(entry)) {
|
|
3509
5746
|
if (typeof value === "string") {
|
|
@@ -3521,13 +5758,14 @@ async function runSetup(options = {}) {
|
|
|
3521
5758
|
const skillSrc = options.skillSrc ?? defaultSkillSrc();
|
|
3522
5759
|
const remove = options.remove === true;
|
|
3523
5760
|
const log2 = options.log ?? ((message) => console.log(message));
|
|
3524
|
-
const summary = { done: [], unchanged: [], skipped: [], errors: [] };
|
|
5761
|
+
const summary = { done: [], unchanged: [], skipped: [], refused: [], errors: [] };
|
|
3525
5762
|
const record = (status, label, file) => {
|
|
3526
5763
|
if (status === "changed" || status === "removed") summary.done.push(`${label}: ${file}`);
|
|
3527
5764
|
else if (status === "unchanged" || status === "absent") summary.unchanged.push(`${label}: ${file}`);
|
|
3528
5765
|
else if (status === "skipped") summary.skipped.push(`${label}: ${file}`);
|
|
5766
|
+
else if (status === "unrecognized") summary.refused.push(`${label}: ${file}`);
|
|
3529
5767
|
};
|
|
3530
|
-
const registry = loadRegistry();
|
|
5768
|
+
const registry = loadRegistry(options.registryFile);
|
|
3531
5769
|
const found = discover(registry, { homeDir: home, pathEnv: options.pathEnv, noNpm: options.noNpm === true });
|
|
3532
5770
|
const only = options.agent;
|
|
3533
5771
|
let targetAgents = [];
|
|
@@ -3540,16 +5778,43 @@ async function runSetup(options = {}) {
|
|
|
3540
5778
|
log2(`configure only: ${only}`);
|
|
3541
5779
|
}
|
|
3542
5780
|
} else {
|
|
3543
|
-
|
|
5781
|
+
const installed = found.filter((agent) => agent.present);
|
|
5782
|
+
targetAgents = installed.map((agent) => registry.agents.find((entry) => entry.id === agent.id));
|
|
5783
|
+
const configOnly = found.filter((agent) => agent.configOnly);
|
|
5784
|
+
if (options.force === true) {
|
|
5785
|
+
for (const agent of configOnly) {
|
|
5786
|
+
const entry = registry.agents.find((candidate) => candidate.id === agent.id);
|
|
5787
|
+
if (entry !== void 0 && !targetAgents.includes(entry)) targetAgents.push(entry);
|
|
5788
|
+
}
|
|
5789
|
+
} else if (configOnly.length > 0) {
|
|
5790
|
+
for (const agent of configOnly) {
|
|
5791
|
+
summary.skipped.push(`${agent.id}: config-only (${agent.configFiles[0]}) \u2014 agent not installed; use --force or --agent ${agent.id}`);
|
|
5792
|
+
}
|
|
5793
|
+
log2(`skipped (config-only, agent not installed): ${configOnly.map((agent) => agent.id).join(", ")} \u2014 use --force to configure anyway`);
|
|
5794
|
+
}
|
|
3544
5795
|
const present2 = targetAgents.map((agent) => agent.id);
|
|
3545
5796
|
log2(`discovered: ${present2.length > 0 ? present2.join(", ") : "none"}`);
|
|
3546
5797
|
}
|
|
3547
5798
|
for (const agent of targetAgents) {
|
|
3548
|
-
for (const config of agent.
|
|
5799
|
+
for (const config of configsForPlatform(agent, process.platform)) {
|
|
3549
5800
|
const nameFor = config.serverName ?? agent.serverName ?? serverName;
|
|
3550
5801
|
for (const file of expandConfigFile(config.file, home)) {
|
|
3551
5802
|
try {
|
|
3552
|
-
|
|
5803
|
+
let status;
|
|
5804
|
+
switch (config.strategy) {
|
|
5805
|
+
case "json":
|
|
5806
|
+
status = await mergeJsonServer(file, config.section, substitute2(config.entry, { url, serverName: nameFor }), { serverName: nameFor, url, remove });
|
|
5807
|
+
break;
|
|
5808
|
+
case "toml":
|
|
5809
|
+
status = await mergeTomlSection(file, { serverName: nameFor, url, remove });
|
|
5810
|
+
break;
|
|
5811
|
+
case "yaml-array":
|
|
5812
|
+
status = await mergeYamlArrayServer(file, { serverName: nameFor, url, remove, entry: config.entry ?? {} });
|
|
5813
|
+
break;
|
|
5814
|
+
case "dsh":
|
|
5815
|
+
status = await mergeDshPatch(file, { serverName: nameFor, url, remove });
|
|
5816
|
+
break;
|
|
5817
|
+
}
|
|
3553
5818
|
record(status, agent.id, file);
|
|
3554
5819
|
} catch (error) {
|
|
3555
5820
|
summary.errors.push(`${agent.id}: ${file} \u2014 ${error.message}`);
|
|
@@ -3558,9 +5823,10 @@ async function runSetup(options = {}) {
|
|
|
3558
5823
|
}
|
|
3559
5824
|
}
|
|
3560
5825
|
}
|
|
3561
|
-
const skillDirs = [
|
|
5826
|
+
const skillDirs = [];
|
|
5827
|
+
if (targetAgents.length > 0 || remove) skillDirs.push(join3(home, ".agents", "skills", serverName));
|
|
3562
5828
|
for (const agent of targetAgents) {
|
|
3563
|
-
if (agent.skill !== null) skillDirs.push(
|
|
5829
|
+
if (agent.skill !== null) skillDirs.push(join3(expandHome(agent.skill, home), serverName));
|
|
3564
5830
|
}
|
|
3565
5831
|
for (const dir of skillDirs) {
|
|
3566
5832
|
try {
|
|
@@ -3580,7 +5846,7 @@ import { execFileSync as execFileSync2 } from "node:child_process";
|
|
|
3580
5846
|
import { request } from "node:http";
|
|
3581
5847
|
import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
|
|
3582
5848
|
import { homedir as homedir3 } from "node:os";
|
|
3583
|
-
import { dirname as dirname5, join as
|
|
5849
|
+
import { dirname as dirname5, join as join4 } from "node:path";
|
|
3584
5850
|
import { fileURLToPath as fileURLToPath3 } from "node:url";
|
|
3585
5851
|
async function runStatus(options = {}) {
|
|
3586
5852
|
const host = options.host ?? "127.0.0.1";
|
|
@@ -3633,7 +5899,7 @@ async function runStatus(options = {}) {
|
|
|
3633
5899
|
function runUpdate() {
|
|
3634
5900
|
const messages = [];
|
|
3635
5901
|
try {
|
|
3636
|
-
const pkgFile =
|
|
5902
|
+
const pkgFile = join4(dirname5(fileURLToPath3(import.meta.url)), "..", "package.json");
|
|
3637
5903
|
const before = JSON.parse(readFileSync5(pkgFile, "utf8")).version ?? "?";
|
|
3638
5904
|
messages.push(`current version: ${before}`);
|
|
3639
5905
|
const script = [
|
|
@@ -3678,9 +5944,9 @@ function runService(options) {
|
|
|
3678
5944
|
const platform = options.platform ?? process.platform;
|
|
3679
5945
|
try {
|
|
3680
5946
|
if (platform === "win32") {
|
|
3681
|
-
const appData = process.env.APPDATA ??
|
|
3682
|
-
const launcherDir =
|
|
3683
|
-
const vbs =
|
|
5947
|
+
const appData = process.env.APPDATA ?? join4(homedir3(), "AppData", "Roaming");
|
|
5948
|
+
const launcherDir = join4(appData, "agent-comm-hub");
|
|
5949
|
+
const vbs = join4(launcherDir, "agent-comm-hub.vbs");
|
|
3684
5950
|
const runKey = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
|
|
3685
5951
|
const valueName = "agent-comm-hub";
|
|
3686
5952
|
if (options.action === "install") {
|
|
@@ -3713,8 +5979,8 @@ function runService(options) {
|
|
|
3713
5979
|
return { ok: true, messages };
|
|
3714
5980
|
}
|
|
3715
5981
|
if (platform === "linux") {
|
|
3716
|
-
const unitDir =
|
|
3717
|
-
const unitFile =
|
|
5982
|
+
const unitDir = join4(homedir3(), ".config", "systemd", "user");
|
|
5983
|
+
const unitFile = join4(unitDir, "agent-comm-hub.service");
|
|
3718
5984
|
if (options.action === "install") {
|
|
3719
5985
|
const unit = `[Unit]
|
|
3720
5986
|
Description=agent-comm-hub (multi-peer MCP hub)
|
|
@@ -3750,10 +6016,10 @@ WantedBy=default.target
|
|
|
3750
6016
|
return { ok: true, messages };
|
|
3751
6017
|
}
|
|
3752
6018
|
if (platform === "darwin") {
|
|
3753
|
-
const launchAgentsDir =
|
|
6019
|
+
const launchAgentsDir = join4(homedir3(), "Library", "LaunchAgents");
|
|
3754
6020
|
const label = "com.agent-comm-hub";
|
|
3755
|
-
const plist =
|
|
3756
|
-
const logFile =
|
|
6021
|
+
const plist = join4(launchAgentsDir, `${label}.plist`);
|
|
6022
|
+
const logFile = join4(homedir3(), "Library", "Logs", "agent-comm-hub.log");
|
|
3757
6023
|
const uid = typeof process.getuid === "function" ? process.getuid() : 0;
|
|
3758
6024
|
const plistContent = `<?xml version="1.0" encoding="UTF-8"?>
|
|
3759
6025
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
@@ -3822,29 +6088,46 @@ WantedBy=default.target
|
|
|
3822
6088
|
|
|
3823
6089
|
// src/cli.ts
|
|
3824
6090
|
import { homedir as homedir4 } from "node:os";
|
|
3825
|
-
import { join as
|
|
3826
|
-
var STRING_FLAGS = /* @__PURE__ */ new Set(["--host", "--path", "--url", "--server-name", "--agent", "--herdr-bin", "--manager-peers", "--state-file", "--auth-tokens", "--db", "--file", "--role", "--owner", "--token"]);
|
|
3827
|
-
var DEFAULT_STATE_FILE =
|
|
3828
|
-
var DEFAULT_DB =
|
|
3829
|
-
var DEFAULT_AUTH_FILE =
|
|
6091
|
+
import { join as join5 } from "node:path";
|
|
6092
|
+
var STRING_FLAGS = /* @__PURE__ */ new Set(["--host", "--path", "--url", "--server-name", "--agent", "--herdr-bin", "--manager-peers", "--state-file", "--auth-tokens", "--db", "--file", "--role", "--owner", "--token", "--allow-origins", "--manager-token"]);
|
|
6093
|
+
var DEFAULT_STATE_FILE = join5(homedir4(), ".agent-comm-hub", "roster.json");
|
|
6094
|
+
var DEFAULT_DB = join5(homedir4(), ".agent-comm-hub", "state.db");
|
|
6095
|
+
var DEFAULT_AUTH_FILE = join5(homedir4(), ".agent-comm-hub", "tokens.json");
|
|
6096
|
+
function parseRunners(value) {
|
|
6097
|
+
if (value === void 0) return void 0;
|
|
6098
|
+
let parsed;
|
|
6099
|
+
try {
|
|
6100
|
+
parsed = JSON.parse(value);
|
|
6101
|
+
} catch (error) {
|
|
6102
|
+
throw new Error(`--runner expects JSON: ${error.message}`);
|
|
6103
|
+
}
|
|
6104
|
+
const list = Array.isArray(parsed) ? parsed : [parsed];
|
|
6105
|
+
for (const [index, entry] of list.entries()) {
|
|
6106
|
+
if (typeof entry !== "object" || entry === null) throw new Error(`--runner[${index}] must be an object`);
|
|
6107
|
+
validateRunnerConfig(entry, index);
|
|
6108
|
+
}
|
|
6109
|
+
return list;
|
|
6110
|
+
}
|
|
3830
6111
|
function parseArgs(argv) {
|
|
3831
6112
|
const args = {};
|
|
3832
|
-
const numeric = /* @__PURE__ */ new Set(["--port", "--max-queue", "--history-limit", "--wait-timeout-ms", "--default-wait-ms", "--connected-window-ms", "--peer-idle-timeout-ms", "--herdr-timeout-ms", "--heartbeat-ms"]);
|
|
3833
|
-
const string = /* @__PURE__ */ new Set(["--host", "--path", "--url", "--server-name", "--agent", "--herdr-bin", "--manager-peers", "--state-file", "--auth-tokens", "--db", "--file", "--role", "--owner", "--token"]);
|
|
6113
|
+
const numeric = /* @__PURE__ */ new Set(["--port", "--max-queue", "--history-limit", "--wait-timeout-ms", "--default-wait-ms", "--connected-window-ms", "--peer-idle-timeout-ms", "--parked-ttl-ms", "--lease-ttl-ms", "--max-attempts", "--herdr-timeout-ms", "--heartbeat-ms", "--session-ttl-ms", "--rate-per-min"]);
|
|
6114
|
+
const string = /* @__PURE__ */ new Set(["--host", "--path", "--url", "--server-name", "--agent", "--herdr-bin", "--manager-peers", "--state-file", "--auth-tokens", "--db", "--file", "--role", "--owner", "--token", "--allow-origins", "--manager-token", "--runner"]);
|
|
3834
6115
|
for (let i = 0; i < argv.length; i++) {
|
|
3835
6116
|
const flag = argv[i];
|
|
3836
6117
|
if (flag === "--help" || flag === "-h" || flag === "--version" || flag === "-V") {
|
|
3837
6118
|
args[flag] = true;
|
|
3838
6119
|
continue;
|
|
3839
6120
|
}
|
|
3840
|
-
if (flag === "--remove" || flag === "--dry-run" || flag === "--reveal" || flag === "--allow-join") {
|
|
6121
|
+
if (flag === "--remove" || flag === "--dry-run" || flag === "--reveal" || flag === "--allow-join" || flag === "--insecure" || flag === "--force") {
|
|
3841
6122
|
args[flag] = true;
|
|
3842
6123
|
continue;
|
|
3843
6124
|
}
|
|
3844
6125
|
const value = argv[i + 1];
|
|
3845
6126
|
if (numeric.has(flag)) {
|
|
3846
6127
|
const parsed = Number(value);
|
|
3847
|
-
|
|
6128
|
+
const zeroMeansOff = flag === "--peer-idle-timeout-ms" || flag === "--parked-ttl-ms" || flag === "--max-attempts" || flag === "--session-ttl-ms" || flag === "--rate-per-min";
|
|
6129
|
+
const bad = !Number.isFinite(parsed) || (zeroMeansOff ? parsed < 0 : parsed <= 0);
|
|
6130
|
+
if (bad) throw new Error(`${flag} expects ${zeroMeansOff ? "a number >= 0" : "a positive number"}, got '${value}'`);
|
|
3848
6131
|
args[flag] = parsed;
|
|
3849
6132
|
i++;
|
|
3850
6133
|
} else if (string.has(flag)) {
|
|
@@ -3891,10 +6174,26 @@ Hub options:
|
|
|
3891
6174
|
--wait-timeout-ms <n> Long-poll ceiling for bridge_wait (default 60000)
|
|
3892
6175
|
--default-wait-ms <n> bridge_wait default budget (default 30000)
|
|
3893
6176
|
--connected-window-ms <n> Peer counts as active within this window (default 30000)
|
|
3894
|
-
--peer-idle-timeout-ms <n>
|
|
6177
|
+
--peer-idle-timeout-ms <n> Park (not delete) idle peers after this; 0 disables the
|
|
6178
|
+
GC entirely (default 600000)
|
|
6179
|
+
--parked-ttl-ms <n> Drop a parked mailbox after this; 0 disables expiry
|
|
6180
|
+
(default 604800000 = 7 days)
|
|
6181
|
+
--session-ttl-ms <n> Forget a session unused this long with no live SSE
|
|
6182
|
+
stream (default 1800000 = 30 min); 0 disables
|
|
6183
|
+
--lease-ttl-ms <n> How long a manual-ack lease lasts before the message
|
|
6184
|
+
is offered again (default 60000)
|
|
6185
|
+
--rate-per-min <n> Per-peer mailbox rate limit (messages per minute);
|
|
6186
|
+
0 (default) is unlimited. Guards the recipient against
|
|
6187
|
+
a broadcast storm; excess is counted as droppedRate
|
|
6188
|
+
--max-attempts <n> Hand-outs before a leased message is dead-lettered
|
|
6189
|
+
instead of requeued; 0 disables (default 5)
|
|
3895
6190
|
--herdr-bin <path> herdr CLI binary for bridge_agent_* control tools
|
|
3896
6191
|
(default herdr, resolved via PATH)
|
|
3897
6192
|
--herdr-timeout-ms <n> Default cap for one herdr call in ms (default 30000)
|
|
6193
|
+
--runner <json> Executor for a peer that is not polling: one JSON
|
|
6194
|
+
object or an array, e.g.
|
|
6195
|
+
'{"peer":"codex","kind":"cli","command":"codex","args":["exec","{prompt}"]}'
|
|
6196
|
+
or {"peer":"mcode","kind":"herdr"}. Off by default.
|
|
3898
6197
|
--manager-peers <ids> Comma-separated peer ids allowed to manage the
|
|
3899
6198
|
roster (rename others / kick), or "all".
|
|
3900
6199
|
(default agent-hub-cli,hub-admin \u2014 the desktop
|
|
@@ -3923,6 +6222,20 @@ Auth options (agent-comm-hub auth <action>):
|
|
|
3923
6222
|
the public internet). Each gets a unique peer id
|
|
3924
6223
|
+ source IP shown in the admin roster for you to
|
|
3925
6224
|
claim (rename) or issue a token to.
|
|
6225
|
+
--allow-origins <list> Comma-separated browser origins allowed to call the
|
|
6226
|
+
MCP endpoint (e.g. https://hub.example.com). Requests
|
|
6227
|
+
without an Origin header and loopback origins are
|
|
6228
|
+
always allowed; anything else gets 403. This is the
|
|
6229
|
+
DNS-rebinding guard the MCP spec requires.
|
|
6230
|
+
--manager-token <secret> Require this secret (Authorization: Bearer <secret>)
|
|
6231
|
+
to claim a peer id listed in --manager-peers.
|
|
6232
|
+
Without it, <state-file dir>/manager.token is read
|
|
6233
|
+
when present; with neither, manager ids stay a
|
|
6234
|
+
convention that any local client can claim.
|
|
6235
|
+
--insecure Allow --host to bind a non-loopback address with NO
|
|
6236
|
+
token table. Without this, such a start is refused:
|
|
6237
|
+
the hub would accept unauthenticated clients from
|
|
6238
|
+
the whole network.
|
|
3926
6239
|
--reveal auth list: include the plaintext tokens
|
|
3927
6240
|
|
|
3928
6241
|
Setup options:
|
|
@@ -3930,6 +6243,8 @@ Setup options:
|
|
|
3930
6243
|
--server-name <name> Config key (default agent-hub)
|
|
3931
6244
|
--agent <id> Only configure one registry agent (e.g. codex)
|
|
3932
6245
|
--remove Uninstall instead of install
|
|
6246
|
+
--force Also configure agents whose config file exists but
|
|
6247
|
+
which are not installed (leftover dotfiles)
|
|
3933
6248
|
|
|
3934
6249
|
-h, --help Show this help
|
|
3935
6250
|
-V, --version Show version
|
|
@@ -3955,6 +6270,7 @@ try {
|
|
|
3955
6270
|
serverName: args2["--server-name"],
|
|
3956
6271
|
agent: args2["--agent"],
|
|
3957
6272
|
remove: args2["--remove"] === true,
|
|
6273
|
+
force: args2["--force"] === true,
|
|
3958
6274
|
log: (message) => log.info(message)
|
|
3959
6275
|
});
|
|
3960
6276
|
process.exit(0);
|
|
@@ -4112,6 +6428,12 @@ try {
|
|
|
4112
6428
|
defaultWaitMs: args["--default-wait-ms"],
|
|
4113
6429
|
connectedWindowMs: args["--connected-window-ms"],
|
|
4114
6430
|
peerIdleTimeoutMs: args["--peer-idle-timeout-ms"],
|
|
6431
|
+
parkedTtlMs: args["--parked-ttl-ms"],
|
|
6432
|
+
runners: parseRunners(args["--runner"]),
|
|
6433
|
+
sessionTtlMs: args["--session-ttl-ms"],
|
|
6434
|
+
leaseTtlMs: args["--lease-ttl-ms"],
|
|
6435
|
+
ratePerMin: args["--rate-per-min"],
|
|
6436
|
+
maxAttempts: args["--max-attempts"],
|
|
4115
6437
|
herdrBin: args["--herdr-bin"],
|
|
4116
6438
|
herdrTimeoutMs: args["--herdr-timeout-ms"],
|
|
4117
6439
|
managerPeers: args["--manager-peers"] === void 0 ? void 0 : args["--manager-peers"] === "all" ? "all" : String(args["--manager-peers"]).split(",").map((id) => id.trim()).filter((id) => id !== ""),
|
|
@@ -4119,7 +6441,10 @@ try {
|
|
|
4119
6441
|
authTokens: args["--auth-tokens"] === void 0 ? void 0 : String(args["--auth-tokens"]),
|
|
4120
6442
|
allowJoin: args["--allow-join"] === true,
|
|
4121
6443
|
db: args["--db"] === void 0 ? DEFAULT_DB : args["--db"] === "off" ? void 0 : String(args["--db"]),
|
|
4122
|
-
heartbeatMs: args["--heartbeat-ms"]
|
|
6444
|
+
heartbeatMs: args["--heartbeat-ms"],
|
|
6445
|
+
allowOrigins: args["--allow-origins"] === void 0 ? void 0 : String(args["--allow-origins"]).split(",").map((o) => o.trim()).filter((o) => o !== ""),
|
|
6446
|
+
managerToken: args["--manager-token"] === void 0 ? void 0 : String(args["--manager-token"]),
|
|
6447
|
+
insecure: args["--insecure"] === true
|
|
4123
6448
|
}, log);
|
|
4124
6449
|
const shutdown = () => {
|
|
4125
6450
|
log.info("agent-comm-hub shutting down");
|