diff --git a/pkgs/message-bridge/worker/src/fleet.js b/pkgs/message-bridge/worker/src/fleet.js index 19683f424..64b2109f7 100644 --- a/pkgs/message-bridge/worker/src/fleet.js +++ b/pkgs/message-bridge/worker/src/fleet.js @@ -64,7 +64,16 @@ // // `to` names recipients as "agent:" (or a bare name), "group:" // (every registered agent in that group) or "all" (every registered -// agent); a list or a comma-separated string mixes them. kind is +// agent); a list or a comma-separated string mixes them. An agent name +// containing "*" is a glob over registered agents (agent:f*), resolved +// in name order; an optional `limit: N` on a send delivers to only the +// first N matches, and the send returns a match report {matched, +// delivered, recipients, remaining}. Every send records a distribution +// (bridge_distribution: batch, sender, pattern, limit, matched and +// delivered sets); a follow-up send with `broaden: ` and an +// optional new limit or pattern delivers the original body to exactly +// the matched-but-undelivered remainder. The notes surface (notes.js) +// follows the same matching rule per identity segment. kind is // "message" (default) or "command". Central, a connector or another // agent (relay.js) can send either; a row another assistant or agent // sent carries its address in from_addr ("channel:chatgpt", @@ -85,6 +94,7 @@ // word to any connector or agent. import { MIN_TOKEN_LENGTH, matchTokenPath, safeEqual, tokenConfigured } from "./auth.js"; +import { GLOB_SEGMENT, globMatch, isGlob } from "./glob.js"; import { InputError, MAX_BODY, MAX_SENDER } from "./messages.js"; import { normalizeNoteIdentity, noteTokenHash } from "./notes.js"; import { relay, replyAddress } from "./relay.js"; @@ -185,9 +195,46 @@ function boolParam(v, dflt) { throw new InputError("expected true or false"); } +/** Validates an agent glob ("f*", "muse-*"): name characters plus "*". */ +export function normalizePattern(raw) { + if (typeof raw !== "string") throw new InputError("agent pattern must be a string"); + const p = raw.trim().toLowerCase(); + if (!GLOB_SEGMENT.test(p)) { + throw new InputError("agent pattern must be 1-64 of a-z 0-9 . _ - and * starting with a letter, digit or *"); + } + return p; +} + +/** An agent target: an exact name, or a glob when it contains "*". */ +function normalizeAgentTarget(raw) { + return isGlob(raw) ? normalizePattern(raw) : normalizeName(raw, "agent"); +} + +/** The raw `to` as one string, for the distribution record's pattern column. */ +function rawPattern(to) { + if (typeof to === "string") return to; + if (Array.isArray(to)) return to.join(","); + return null; +} + +function normalizeLimit(v) { + const n = intParam(v, "limit", { min: 1 }); + if (n !== null && n > MAX_RECIPIENTS) throw new InputError(`limit must be at most ${MAX_RECIPIENTS}`); + return n; +} + +const BATCH = /^[A-Za-z0-9_-]{8,40}$/; + +function normalizeBatch(v, what = "batch") { + if (typeof v !== "string" || !BATCH.test(v)) throw new InputError(`${what} must be a batch id`); + return v; +} + /** - * Parses `to` into { agents: [names], groups: [names], all: bool }. - * "agent:x" or "x" is an agent, "group:g" a group, "all" every agent. + * Parses `to` into { agents: [names and globs], groups: [names], all: bool }. + * "agent:x" or "x" is an agent (a glob when x contains "*"), "group:g" + * a group, "all" every agent. Globs resolve against the registry at + * send time (fleetOp "send"), in name order. */ export function parseTargets(to) { if (to === undefined || to === null || to === "") throw new InputError("to must name at least one recipient"); @@ -205,7 +252,7 @@ export function parseTargets(to) { const g = normalizeName(t.slice(6), "group"); if (!groups.includes(g)) groups.push(g); } else { - const a = normalizeName(t.startsWith("agent:") ? t.slice(6) : t, "agent"); + const a = normalizeAgentTarget(t.startsWith("agent:") ? t.slice(6) : t); if (!agents.includes(a)) agents.push(a); } } @@ -263,13 +310,26 @@ export function normalizeFleetOp(op, a = {}) { targets: parseTargets(a.to), kind: normalizeFleetKind(a.kind), sender: normalizeSender(a.sender), - batch: typeof a.batch === "string" && /^[A-Za-z0-9_-]{8,40}$/.test(a.batch) ? a.batch : null, + batch: typeof a.batch === "string" && BATCH.test(a.batch) ? a.batch : null, from_addr: normalizeFromAddr(a.from_addr), // relay.js: the sending agent never gets its own message, and // "all" reaching no agent yet isn't an error when it also // reached a connector. exclude: a.exclude === undefined || a.exclude === null ? null : normalizeName(a.exclude), lenient: a.lenient === true, + // Pattern addressing (§4.1): an optional cap on deliveries and + // the raw address text, recorded on the distribution. + limit: normalizeLimit(a.limit), + pattern: rawPattern(a.to), + }; + case "broaden": + return { + batch: normalizeBatch(a.batch, "broaden"), + targets: a.to === undefined || a.to === null || a.to === "" ? null : parseTargets(a.to), + pattern: rawPattern(a.to), + limit: normalizeLimit(a.limit), + from_addr: normalizeFromAddr(a.from_addr), + exclude: a.exclude === undefined || a.exclude === null ? null : normalizeName(a.exclude), }; case "origin": return { agent: normalizeName(a.agent), id: intParam(a.id, "id", { min: 1 }) }; @@ -347,6 +407,41 @@ export function fleetSchema(sql) { revoked_at TEXT, created TEXT NOT NULL )`); + // One record per pattern send (design §4.1): what the address + // resolved to and who actually got a row, so a later broaden can + // deliver to exactly the matched-but-undelivered remainder. The + // notes surface writes its distributions here too (same store). + sql.exec(`CREATE TABLE IF NOT EXISTS bridge_distribution ( + batch TEXT PRIMARY KEY, + sender_addr TEXT, + pattern TEXT, + limit_n INTEGER, + matched TEXT NOT NULL, + delivered TEXT NOT NULL, + ts TEXT NOT NULL + )`); +} + +/** Records (or replaces) one send's distribution; matched/delivered are name lists. */ +export function recordDistribution(sql, { batch, sender_addr, pattern, limit_n, matched, delivered, ts }) { + sql.exec( + `INSERT OR REPLACE INTO bridge_distribution (batch, sender_addr, pattern, limit_n, matched, delivered, ts) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + batch, + sender_addr ?? null, + pattern ?? null, + limit_n ?? null, + JSON.stringify(matched), + JSON.stringify(delivered), + ts, + ); +} + +/** One distribution record by batch, or null. */ +export function getDistribution(sql, batch) { + const r = sql.exec("SELECT * FROM bridge_distribution WHERE batch = ?", batch).toArray()[0]; + if (!r) return null; + return { ...r, matched: JSON.parse(r.matched), delivered: JSON.parse(r.delivered) }; } const rows = (cursor) => cursor.toArray().map((r) => ({ ...r })); @@ -389,12 +484,45 @@ function mailboxStats(sql, agent) { return { ...s }; } -function randomBatch() { +export function randomBatch() { const b = new Uint8Array(12); crypto.getRandomValues(b); return b64url(b); } +/** + * Resolves parsed targets against the registry, in name order. + * Returns { matched: [names] } or { error }. Exact names resolve to + * themselves (registered or not, as fleet sends have always done); + * globs, groups and all resolve over registered agents, the sender + * excluded. A glob, group or all matching nobody is an error, except + * a lenient all (relay.js: it also reached a connector). + */ +function resolveTargets(registered, targets, { exclude = null, lenient = false } = {}) { + const others = registered.filter((r) => r.name !== exclude); + const matched = new Set(); + for (const t of targets.agents) { + if (isGlob(t)) { + const hits = others.filter((r) => globMatch(t, r.name)); + if (!hits.length) return { error: `no registered agent matches agent:${t}` }; + for (const r of hits) matched.add(r.name); + } else { + if (exclude && t === exclude) return { error: "an agent can't send to itself" }; + matched.add(t); + } + } + if (targets.all) { + if (!others.length && !lenient) return { error: "no agents have registered yet" }; + for (const r of others) matched.add(r.name); + } + for (const g of targets.groups) { + const members = others.filter((r) => r.groups.includes(g)); + if (!members.length) return { error: `no registered agent is in group ${g}` }; + for (const r of members) matched.add(r.name); + } + return { matched: [...matched].sort() }; +} + /** * One store operation over normalized arguments. State-dependent * refusals come back as { error } (an InputError doesn't survive the @@ -483,23 +611,15 @@ export function fleetOp(sql, op, a, now = new Date().toISOString()) { } case "send": { const registered = rows(sql.exec("SELECT * FROM fleet_agent ORDER BY name")).map(agentRow); - const names = new Set(a.targets.agents); - if (a.exclude && names.has(a.exclude)) return { error: "an agent can't send to itself" }; - const others = registered.filter((r) => r.name !== a.exclude); - if (a.targets.all) { - if (!others.length && !a.lenient) return { error: "no agents have registered yet" }; - for (const r of others) names.add(r.name); - } - for (const g of a.targets.groups) { - const members = others.filter((r) => r.groups.includes(g)); - if (!members.length) return { error: `no registered agent is in group ${g}` }; - for (const r of members) names.add(r.name); - } - if (names.size > MAX_RECIPIENTS) return { error: `that reaches more than ${MAX_RECIPIENTS} agents` }; + const resolved = resolveTargets(registered, a.targets, { exclude: a.exclude, lenient: a.lenient }); + if (resolved.error) return { error: resolved.error }; + const matched = resolved.matched; + if (!a.limit && matched.length > MAX_RECIPIENTS) return { error: `that reaches more than ${MAX_RECIPIENTS} agents` }; + const recipients = a.limit ? matched.slice(0, a.limit) : matched; const known = new Set(registered.map((r) => r.name)); const batch = a.batch ?? randomBatch(); const messages = []; - for (const agent of [...names].sort()) { + for (const agent of recipients) { messages.push({ ...sql .exec( @@ -516,7 +636,87 @@ export function fleetOp(sql, op, a, now = new Date().toISOString()) { .toArray()[0], }); } - return { batch, messages, unregistered: [...names].filter((n) => !known.has(n)).sort() }; + recordDistribution(sql, { + batch, + sender_addr: a.from_addr, + pattern: a.pattern, + limit_n: a.limit, + matched, + delivered: recipients, + ts: now, + }); + return { + batch, + messages, + unregistered: recipients.filter((n) => !known.has(n)), + matched: matched.length, + delivered: recipients.length, + recipients, + remaining: matched.length - recipients.length, + }; + } + case "broaden": { + const dist = getDistribution(sql, a.batch); + if (!dist) return { error: `no distribution recorded for batch ${a.batch}` }; + // Broadening re-sends under the original sender's identity, so + // only that sender may broaden — or central (from_addr null, + // the owner token), who may broaden any distribution. + if (a.from_addr !== null && dist.sender_addr !== null && a.from_addr !== dist.sender_addr) { + return { error: "only the original sender can broaden this distribution" }; + } + const sample = sql + .exec("SELECT * FROM fleet_message WHERE batch = ? AND direction = 'inbound' ORDER BY id ASC LIMIT 1", a.batch) + .toArray()[0]; + if (!sample) return { error: `batch ${a.batch} has no fleet messages to broaden` }; + let matched = dist.matched; + if (a.targets) { + const registered = rows(sql.exec("SELECT * FROM fleet_agent ORDER BY name")).map(agentRow); + const resolved = resolveTargets(registered, a.targets, { exclude: a.exclude }); + if (resolved.error) return { error: resolved.error }; + matched = [...new Set([...dist.matched, ...resolved.matched])].sort(); + } + const deliveredSet = new Set(dist.delivered); + const pending = matched.filter((n) => !deliveredSet.has(n)); + const recipients = a.limit ? pending.slice(0, a.limit) : pending; + const messages = []; + for (const agent of recipients) { + messages.push({ + ...sql + .exec( + `INSERT INTO fleet_message (ts, agent, direction, kind, sender, body, batch, from_addr) + VALUES (?, ?, 'inbound', ?, ?, ?, ?, ?) RETURNING *`, + now, + agent, + sample.kind, + sample.sender, + sample.body, + a.batch, + sample.from_addr, + ) + .toArray()[0], + }); + deliveredSet.add(agent); + } + const delivered = [...deliveredSet].sort(); + recordDistribution(sql, { + batch: a.batch, + sender_addr: dist.sender_addr, + pattern: a.pattern ?? dist.pattern, + limit_n: a.limit ?? dist.limit_n, + matched, + delivered, + ts: now, + }); + const known = new Set(rows(sql.exec("SELECT name FROM fleet_agent")).map((r) => r.name)); + return { + batch: a.batch, + messages, + unregistered: recipients.filter((n) => !known.has(n)), + matched: matched.length, + delivered: recipients.length, + recipients, + remaining: matched.length - delivered.length, + }; } case "origin": { const orig = sql @@ -835,6 +1035,19 @@ const query = (url) => Object.fromEntries(url.searchParams.entries()); * another assistant or agent sent) through relay.js to any address. */ async function agentSend(store, d, delivered) { + if (d.broaden !== undefined && d.broaden !== null && (d.to === undefined || d.to === null || d.to === "")) { + // Broadening one of the agent's own earlier distributions: the + // store re-delivers its body to the matched-but-undelivered rest. + const agent = normalizeName(d.agent); + const out = await store.fleet("broaden", { + batch: d.broaden, + limit: d.limit, + exclude: agent, + from_addr: `agent:${agent}`, + }); + delivered({ messages: [], fleet: out.messages }); + return out; + } if (d.to === undefined || d.to === null || d.to === "") { let origin = null; if (d.reply_to !== undefined && d.reply_to !== null) { @@ -850,7 +1063,15 @@ async function agentSend(store, d, delivered) { if (d.reply_to !== undefined && d.reply_to !== null) { await store.fleet("origin", { agent, id: d.reply_to }); // must be a row to this agent } - const out = await relay(store, { from: `agent:${agent}`, to: d.to, body: d.body, kind: d.kind, sender: d.sender ?? agent }); + const out = await relay(store, { + from: `agent:${agent}`, + to: d.to, + body: d.body, + kind: d.kind, + sender: d.sender ?? agent, + limit: d.limit, + broaden: d.broaden, + }); if (d.reply_to !== undefined && d.reply_to !== null) await store.fleet("ack", { agent, ids: [d.reply_to] }); delivered(out); return out; @@ -929,7 +1150,12 @@ async function ownerRoute(request, store, what, url, delivered) { if (what === "send") { if (request.method !== "POST") return notAllowed("POST"); const d = await readJson(request); - const out = await store.fleet("send", { body: d.body, to: d.to, kind: d.kind, sender: d.sender }); + if (d.broaden !== undefined && d.broaden !== null) { + const out = await store.fleet("broaden", { batch: d.broaden, to: d.to, limit: d.limit }); + delivered({ messages: [], fleet: out.messages }); + return json(out, 201); + } + const out = await store.fleet("send", { body: d.body, to: d.to, kind: d.kind, sender: d.sender, limit: d.limit }); delivered({ messages: [], fleet: out.messages }); return json(out, 201); } diff --git a/pkgs/message-bridge/worker/src/glob.js b/pkgs/message-bridge/worker/src/glob.js new file mode 100644 index 000000000..1f56d22cf --- /dev/null +++ b/pkgs/message-bridge/worker/src/glob.js @@ -0,0 +1,23 @@ +// One matching rule for bridge addressing (design +// doc/2026-11-24_design_message-bridge-buildout.md §4.1): a glob is a +// name segment in which "*" matches any run of segment characters +// (including none); every other character matches itself. Matching is +// case-insensitive — callers lower-case names and patterns first, as +// every bridge surface already does — and resolution enumerates +// matches in deterministic name order, so a limit always picks the +// same first N. + +/** A valid glob segment: name characters plus "*", 1-64 long, starting with a letter, digit or "*". */ +export const GLOB_SEGMENT = /^[a-z0-9*][a-z0-9._*-]{0,63}$/; + +/** True when the segment is a glob (contains "*") rather than an exact name. */ +export const isGlob = (s) => typeof s === "string" && s.includes("*"); + +const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +/** True when `value` matches the glob `pattern` (both already lower-cased). */ +export function globMatch(pattern, value) { + if (!isGlob(pattern)) return pattern === value; + const re = new RegExp(`^${pattern.split("*").map(escape).join(".*")}$`); + return re.test(value); +} diff --git a/pkgs/message-bridge/worker/src/index.js b/pkgs/message-bridge/worker/src/index.js index 3b34e1dce..72fc500f5 100644 --- a/pkgs/message-bridge/worker/src/index.js +++ b/pkgs/message-bridge/worker/src/index.js @@ -20,6 +20,8 @@ import { fleetCredentialRevokeSql, fleetOp, fleetSchema, + getDistribution, + recordDistribution, } from "./fleet.js"; import { route } from "./routes.js"; @@ -111,6 +113,10 @@ export class MessageStore extends DurableObject { body TEXT NOT NULL, ack_at TEXT )`); + // Sends carry their distribution batch (design §4.1); rows from + // before pattern addressing have none. + const noteCols = this.sql.exec("PRAGMA table_info(note_message)").toArray(); + if (!noteCols.some((c) => c.name === "batch")) this.sql.exec("ALTER TABLE note_message ADD COLUMN batch TEXT"); this.sql.exec("CREATE INDEX IF NOT EXISTS note_message_inbox ON note_message (recipient, ack_at, id)"); } @@ -257,7 +263,7 @@ export class MessageStore extends DurableObject { return this.sql.exec("SELECT identity FROM note_identity ORDER BY identity").toArray().map((r) => r.identity); } - noteDeliver({ from, recipients, note }) { + noteDeliver({ from, recipients, note, batch = null, pattern = null, limit_n = null, matched = null }) { const ts = new Date().toISOString(); const notes = []; for (const recipient of recipients) { @@ -265,19 +271,88 @@ export class MessageStore extends DurableObject { if (!known) continue; const row = this.sql .exec( - "INSERT INTO note_message (ts, recipient, sender, body) VALUES (?, ?, ?, ?) RETURNING id, ts, recipient, sender, body", + "INSERT INTO note_message (ts, recipient, sender, body, batch) VALUES (?, ?, ?, ?, ?) RETURNING id, ts, recipient, sender, body, batch", ts, recipient, from, note, + batch, ) .one(); this.sql.exec("UPDATE note_identity SET signal_counter = signal_counter + 1 WHERE identity = ?", recipient); - notes.push({ id: row.id, recipient: row.recipient, from: row.sender, note: row.body, ts: row.ts }); + notes.push({ id: row.id, recipient: row.recipient, from: row.sender, note: row.body, ts: row.ts, batch: row.batch }); + } + if (batch) { + recordDistribution(this.sql, { + batch, + sender_addr: from, + pattern, + limit_n, + matched: matched ?? notes.map((n) => n.recipient), + delivered: notes.map((n) => n.recipient), + ts, + }); } return { delivered: notes.length, recipients: notes.map((n) => n.recipient), notes }; } + /** + * Broadening a notes distribution: only the original sender, only + * the matched-but-undelivered remainder (widened by extra_matched, + * which the caller resolved from the call's new address). State + * refusals come back as { error }, like fleet ops. + */ + noteBroaden({ from, batch, extra_matched = [], pattern = null, limit = null }) { + const dist = getDistribution(this.sql, batch); + if (!dist) return { error: `no distribution recorded for batch ${batch}` }; + if (dist.sender_addr !== from) return { error: "only the original sender can broaden this distribution" }; + const sample = this.sql + .exec("SELECT sender, body FROM note_message WHERE batch = ? ORDER BY id ASC LIMIT 1", batch) + .toArray()[0]; + if (!sample) return { error: `batch ${batch} has no notes to broaden` }; + const matched = [...new Set([...dist.matched, ...extra_matched])].sort(); + const deliveredSet = new Set(dist.delivered); + const pending = matched.filter((n) => !deliveredSet.has(n)); + const recipients = limit ? pending.slice(0, limit) : pending; + const ts = new Date().toISOString(); + const notes = []; + for (const recipient of recipients) { + const known = this.sql.exec("SELECT 1 FROM note_identity WHERE identity = ?", recipient).toArray().length > 0; + if (!known) continue; + const row = this.sql + .exec( + "INSERT INTO note_message (ts, recipient, sender, body, batch) VALUES (?, ?, ?, ?, ?) RETURNING id, ts, recipient, sender, body, batch", + ts, + recipient, + sample.sender, + sample.body, + batch, + ) + .one(); + this.sql.exec("UPDATE note_identity SET signal_counter = signal_counter + 1 WHERE identity = ?", recipient); + deliveredSet.add(recipient); + notes.push({ id: row.id, recipient: row.recipient, from: row.sender, note: row.body, ts: row.ts, batch: row.batch }); + } + const delivered = [...deliveredSet].sort(); + recordDistribution(this.sql, { + batch, + sender_addr: dist.sender_addr, + pattern: pattern ?? dist.pattern, + limit_n: limit ?? dist.limit_n, + matched, + delivered, + ts, + }); + return { + batch, + matched: matched.length, + delivered: notes.length, + recipients: notes.map((n) => n.recipient), + remaining: matched.length - delivered.length, + notes, + }; + } + noteInbox(identity) { return this.sql .exec( @@ -550,6 +625,7 @@ function storeFor(env) { noteAuth: (token_hash) => stub.noteAuth(token_hash), noteIdentities: () => stub.noteIdentities(), noteDeliver: (delivery) => stub.noteDeliver(delivery), + noteBroaden: (broaden) => stub.noteBroaden(broaden), noteInbox: (identity) => stub.noteInbox(identity), noteAck: (identity, sel) => stub.noteAck(identity, sel), noteSignal: (identity) => stub.noteSignal(identity), diff --git a/pkgs/message-bridge/worker/src/mcp.js b/pkgs/message-bridge/worker/src/mcp.js index 853aacecf..7306a3d50 100644 --- a/pkgs/message-bridge/worker/src/mcp.js +++ b/pkgs/message-bridge/worker/src/mcp.js @@ -62,8 +62,19 @@ export const TOOLS = [ }, reply_to: { type: "integer", minimum: 1, description: "Id of an inbound message this answers." }, sender: { type: "string", description: "Optional label for who is sending, e.g. 'claude' or 'chatgpt'." }, + limit: { + type: "integer", + minimum: 1, + maximum: 200, + description: "Cap fleet deliveries: the first N agents the addresses match, in name order. The result's report says how many matched, were delivered and remain.", + }, + broaden: { + type: "string", + description: + "Batch id of an earlier fleet send: re-delivers its body to the matched-but-undelivered remainder (widened by to when given). No body needed, and nobody is sent the same batch twice.", + }, }, - required: ["body"], + required: [], additionalProperties: false, }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, @@ -140,7 +151,7 @@ export async function callTool(name, args, store, channel = "claude", delivered if (typeof args !== "object" || Array.isArray(args)) throw new InputError("arguments must be an object"); switch (name) { case "send_message": { - rejectUnknownArgs(args, ["body", "sender", "to", "kind", "reply_to"]); + rejectUnknownArgs(args, ["body", "sender", "to", "kind", "reply_to", "limit", "broaden"]); let to = args.to; let answering = null; if (args.reply_to !== undefined && args.reply_to !== null) { @@ -156,6 +167,8 @@ export async function callTool(name, args, store, channel = "claude", delivered body: args.body, kind: args.kind, sender: args.sender, + limit: args.limit, + broaden: args.broaden, }); if (answering && answering.read_at === null) await store.ack({ ids: [answering.id], channel }); delivered(out); @@ -166,6 +179,17 @@ export async function callTool(name, args, store, channel = "claude", delivered messages, ...(out.fleet.length ? { fleet: out.fleet } : {}), ...(out.unregistered.length ? { unregistered: out.unregistered } : {}), + ...(out.report + ? { + report: { + batch: out.report.batch, + matched: out.report.matched, + delivered: out.report.delivered, + recipients: out.report.recipients, + remaining: out.report.remaining, + }, + } + : {}), }; } case "read_messages": { diff --git a/pkgs/message-bridge/worker/src/messages.js b/pkgs/message-bridge/worker/src/messages.js index 68ca654e6..291afa757 100644 --- a/pkgs/message-bridge/worker/src/messages.js +++ b/pkgs/message-bridge/worker/src/messages.js @@ -185,6 +185,7 @@ export class MemoryStore { this.noteTokens = new Map(); this.noteRows = []; this.noteNextId = 1; + this.distributions = new Map(); this.fleetCredentials = new Map(); this.enrollTokens = new Map(); } @@ -251,17 +252,68 @@ export class MemoryStore { async noteIdentities() { return [...this.noteCounters.keys()].sort(); } - async noteDeliver({ from, recipients, note }) { + async noteDeliver({ from, recipients, note, batch = null, pattern = null, limit_n = null, matched = null }) { const notes = []; for (const recipient of recipients) { if (!this.noteCounters.has(recipient)) continue; - const row = { id: this.noteNextId++, ts: this.now(), recipient, from, note, ack_at: null }; + const row = { id: this.noteNextId++, ts: this.now(), recipient, from, note, batch, ack_at: null }; this.noteRows.push(row); this.noteCounters.set(recipient, this.noteCounters.get(recipient) + 1); - notes.push({ id: row.id, recipient, from, note, ts: row.ts }); + notes.push({ id: row.id, recipient, from, note, ts: row.ts, batch }); + } + if (batch) { + this.distributions.set(batch, { + batch, + sender_addr: from, + pattern, + limit_n, + matched: matched ?? notes.map((n) => n.recipient), + delivered: notes.map((n) => n.recipient), + ts: this.now(), + }); } return { delivered: notes.length, recipients: notes.map((n) => n.recipient), notes }; } + // Broadening a notes distribution (notes.js), same semantics as the + // Durable Object: only the original sender, only the remainder. The + // caller resolves a broaden call's new address to extra_matched. + async noteBroaden({ from, batch, extra_matched = [], pattern = null, limit }) { + const dist = this.distributions.get(batch); + if (!dist) return { error: `no distribution recorded for batch ${batch}` }; + if (dist.sender_addr !== from) return { error: "only the original sender can broaden this distribution" }; + const sample = this.noteRows.find((r) => r.batch === batch); + if (!sample) return { error: `batch ${batch} has no notes to broaden` }; + const matched = [...new Set([...dist.matched, ...extra_matched])].sort(); + const deliveredSet = new Set(dist.delivered); + const pending = matched.filter((n) => !deliveredSet.has(n)); + const recipients = limit ? pending.slice(0, limit) : pending; + const notes = []; + for (const recipient of recipients) { + if (!this.noteCounters.has(recipient)) continue; + const row = { id: this.noteNextId++, ts: this.now(), recipient, from: sample.from, note: sample.note, batch, ack_at: null }; + this.noteRows.push(row); + this.noteCounters.set(recipient, this.noteCounters.get(recipient) + 1); + deliveredSet.add(recipient); + notes.push({ id: row.id, recipient, from: row.from, note: row.note, ts: row.ts, batch }); + } + const delivered = [...deliveredSet].sort(); + this.distributions.set(batch, { + ...dist, + pattern: pattern ?? dist.pattern, + limit_n: limit ?? dist.limit_n, + matched, + delivered, + ts: this.now(), + }); + return { + batch, + matched: matched.length, + delivered: notes.length, + recipients: notes.map((n) => n.recipient), + remaining: matched.length - delivered.length, + notes, + }; + } async noteInbox(identity) { return this.noteRows .filter((r) => r.recipient === identity && r.ack_at === null) diff --git a/pkgs/message-bridge/worker/src/notes.js b/pkgs/message-bridge/worker/src/notes.js index 977595aae..aa4f9449e 100644 --- a/pkgs/message-bridge/worker/src/notes.js +++ b/pkgs/message-bridge/worker/src/notes.js @@ -17,6 +17,8 @@ // response carries no content and no registration marker. import { safeEqual, tokenConfigured } from "./auth.js"; +import { randomBatch } from "./fleet.js"; +import { GLOB_SEGMENT, globMatch, isGlob } from "./glob.js"; import { InputError, MAX_BODY } from "./messages.js"; export const NOTE_SEGMENT = /^[a-z0-9][a-z0-9._-]{0,63}$/; @@ -66,20 +68,31 @@ export function normalizeNoteIdentity(value) { return `${segment(parts[0], "identity class")}/${segment(parts[1], "identity name")}`; } -/** Validates a recipient address: an identity with either segment optionally `*`. */ +/** + * Validates a recipient address: an identity whose segments are exact + * names, `*`, or globs (`f*`) — the same matching rule as fleet + * addressing (design §4.1), applied per segment. + */ export function normalizeNoteAddress(value) { if (typeof value !== "string") throw new InputError("to must be class/name"); const parts = value.trim().toLowerCase().split("/"); if (parts.length !== 2) throw new InputError("to must be class/name, with * allowed in either segment"); - const parse = (raw, what) => (raw === "*" ? "*" : segment(raw, what)); + const parse = (raw, what) => { + if (raw === "*") return "*"; + if (isGlob(raw)) { + if (!GLOB_SEGMENT.test(raw)) throw new InputError(`${what} must be 1-64 of a-z 0-9 . _ - and *`); + return raw; + } + return segment(raw, what); + }; return `${parse(parts[0], "address class")}/${parse(parts[1], "address name")}`; } -/** True when a wildcard address names an identity. */ +/** True when a wildcard or glob address names an identity. */ export function noteAddressMatches(address, identity) { const [ac, an] = address.split("/"); const [ic, iname] = identity.split("/"); - return (ac === "*" || ac === ic) && (an === "*" || an === iname); + return globMatch(ac, ic) && globMatch(an, iname); } function boolField(value, dflt, what) { @@ -102,12 +115,36 @@ export function normalizeNoteRegister(data) { }; } -/** Validates a send body: `{to, note}`. */ +const NOTE_BATCH = /^[A-Za-z0-9_-]{8,40}$/; +export const NOTE_MAX_LIMIT = 200; + +function noteLimit(value) { + if (value === undefined || value === null) return null; + if (!Number.isInteger(value) || value < 1) throw new InputError("limit must be a positive integer"); + if (value > NOTE_MAX_LIMIT) throw new InputError(`limit must be at most ${NOTE_MAX_LIMIT}`); + return value; +} + +/** + * Validates a send body: `{to, note, limit?}`, or a broaden follow-up + * `{broaden, to?, limit?}` (no note: the original body is re-delivered + * to the distribution's matched-but-undelivered remainder). + */ export function normalizeNoteSend(data) { if (!data || typeof data !== "object" || Array.isArray(data)) throw new InputError("body must be a JSON object"); + const limit = noteLimit(data.limit); + if (data.broaden !== undefined && data.broaden !== null) { + if (typeof data.broaden !== "string" || !NOTE_BATCH.test(data.broaden)) throw new InputError("broaden must be a batch id"); + return { + broaden: data.broaden, + to: data.to === undefined || data.to === null || data.to === "" ? null : normalizeNoteAddress(data.to), + note: null, + limit, + }; + } if (typeof data.note !== "string" || data.note.trim() === "") throw new InputError("note must be a non-empty string"); if (data.note.length > MAX_BODY) throw new InputError(`note is longer than ${MAX_BODY} characters`); - return { to: normalizeNoteAddress(data.to), note: data.note }; + return { broaden: null, to: normalizeNoteAddress(data.to), note: data.note, limit }; } /** Validates an ack body: `{id}`, `{ids}` or `{up_to_id}`. */ @@ -201,7 +238,7 @@ async function readJson(request) { /** * Handles the authenticated note API: * POST /notes/register owner access token as Bearer; {identity, token, can_send?, can_inbox?} - * POST /notes/send identity token; {to, note} + * POST /notes/send identity token; {to, note, limit?} or {broaden, to?, limit?} * GET /notes/inbox identity token; pending notes for that identity * POST /notes/ack identity token; {id | ids | up_to_id} * Returns null when the path is not this API's. @@ -236,9 +273,36 @@ export async function handleNotes(request, env, url, getStore) { if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405, headers: { allow: "POST" } }); if (!auth.can_send) return json({ error: "this token cannot send notes" }, 403); const data = normalizeNoteSend(await readJson(request)); - const recipients = (await store.noteIdentities()).filter((identity) => noteAddressMatches(data.to, identity)); - if (!recipients.length) throw new InputError(`no registered identity matches ${data.to}`); - return json(await store.noteDeliver({ from: auth.identity, recipients, note: data.note }), 201); + if (data.broaden) { + const extra_matched = data.to + ? (await store.noteIdentities()).filter((identity) => noteAddressMatches(data.to, identity)) + : []; + const out = await store.noteBroaden({ + from: auth.identity, + batch: data.broaden, + extra_matched, + pattern: data.to, + limit: data.limit, + }); + if (out && typeof out.error === "string") throw new InputError(out.error); + return json(out, 201); + } + // Identities come back in name order, so a limit takes the first + // N matches deterministically; the response is the match report. + const matched = (await store.noteIdentities()).filter((identity) => noteAddressMatches(data.to, identity)); + if (!matched.length) throw new InputError(`no registered identity matches ${data.to}`); + const recipients = data.limit ? matched.slice(0, data.limit) : matched; + const batch = randomBatch(); + const out = await store.noteDeliver({ + from: auth.identity, + recipients, + note: data.note, + batch, + pattern: data.to, + limit_n: data.limit, + matched, + }); + return json({ ...out, batch, matched: matched.length, remaining: matched.length - recipients.length }, 201); } if (what === "inbox") { if (request.method !== "GET") return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET" } }); diff --git a/pkgs/message-bridge/worker/src/relay.js b/pkgs/message-bridge/worker/src/relay.js index a0b47ed29..e1c8a8c1f 100644 --- a/pkgs/message-bridge/worker/src/relay.js +++ b/pkgs/message-bridge/worker/src/relay.js @@ -9,11 +9,19 @@ // did); from an agent, a post to central // claude, chatgpt a connector's channel (also channel:) // connectors every other connector -// agent: one fleet agent (a bare name works too) +// agent: one fleet agent (a bare name works too); +// "*" in the name makes it a glob over +// registered agents (agent:f*), resolved +// in name order, optionally capped by limit // group: every registered agent in that group // agents every registered agent // all every other connector and every agent // +// A fleet send records a distribution (batch, pattern, matched and +// delivered sets); a later send with broaden: and an optional +// new pattern and/or limit delivers the same body to exactly the +// matched-but-undelivered remainder — never a duplicate. +// // The sender is never its own recipient: "all" and "connectors" leave it // out, and naming yourself is an error. kind is "message" (default) or // "instruction" ("command" is the same thing; agents' mailboxes call it @@ -24,9 +32,10 @@ // from_addr ("channel:claude", "agent:muse-3"), so the recipient can tell // it from something Drew sent and answer it with reply_to. +import { GLOB_SEGMENT, isGlob } from "./glob.js"; import { CHANNELS, CHANNEL_NAMES, InputError, MAX_BODY } from "./messages.js"; -export const ADDRESS_HELP = "drew, claude, chatgpt, connectors, agent:, group:, agents or all"; +export const ADDRESS_HELP = "drew, claude, chatgpt, connectors, agent:, group:, agents or all"; const DREW = ["drew", "owner", "central"]; const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/; const MAX_ADDRESSES = 200; @@ -83,8 +92,12 @@ export function parseAddresses(to, from) { out.fleet.push(t); } else { const name = t.startsWith("agent:") ? t.slice(6) : t; - if (!NAME.test(name)) throw new InputError(`unknown address ${JSON.stringify(raw)}; use ${ADDRESS_HELP}`); - if (name === me.agent) throw new InputError("an agent can't send to itself"); + if (isGlob(name)) { + if (!GLOB_SEGMENT.test(name)) throw new InputError(`unknown address ${JSON.stringify(raw)}; use ${ADDRESS_HELP}`); + } else { + if (!NAME.test(name)) throw new InputError(`unknown address ${JSON.stringify(raw)}; use ${ADDRESS_HELP}`); + if (name === me.agent) throw new InputError("an agent can't send to itself"); + } out.fleet.push(`agent:${name}`); } } @@ -100,8 +113,31 @@ export function parseAddresses(to, from) { * the fleet rows it stored, so the caller can wake their recipients. * Everything is validated before the first row is written; the fleet * send goes first because only it can fail on state (an empty group). + * + * With `broaden` (a batch from an earlier fleet send) there is no body: + * the fleet part re-delivers the original body to the distribution's + * matched-but-undelivered remainder, widened by `to` when given. The + * fleet outcome rides back as `report` (the send's match report). */ -export async function relay(store, { from, to, body, kind, sender }) { +export async function relay(store, { from, to, body, kind, sender, limit, broaden }) { + const me = self(from); + if (broaden !== undefined && broaden !== null) { + // No `to` is fine: it widens nothing, it just delivers more of the + // original distribution's remainder (up to the new limit). + const hasTo = !(to === undefined || to === null || to === "" || (Array.isArray(to) && !to.length)); + const where = hasTo ? parseAddresses(to, from) : { drew: false, channels: [], fleet: [] }; + if (where.drew || where.channels.length) { + throw new InputError("broaden only widens a fleet distribution: name agent, group or all addresses"); + } + const out = await store.fleet("broaden", { + batch: broaden, + to: where.fleet.length ? where.fleet : undefined, + limit, + from_addr: from, + exclude: me.agent, + }); + return { messages: [], fleet: out.messages, unregistered: out.unregistered ?? [], report: out }; + } if (typeof body !== "string" || body.trim() === "") throw new InputError("body must be a non-empty string"); if (body.length > MAX_BODY) throw new InputError(`body is longer than ${MAX_BODY} characters`); const k = relayKind(kind); @@ -109,10 +145,10 @@ export async function relay(store, { from, to, body, kind, sender }) { if (where.drew && k === "instruction") { throw new InputError("Drew gets messages, not instructions: send kind message to drew"); } - const me = self(from); const source = me.channel ? "mcp" : "fleet"; let fleet = []; let unregistered = []; + let report = null; if (where.fleet.length) { const out = await store.fleet("send", { body, @@ -122,9 +158,11 @@ export async function relay(store, { from, to, body, kind, sender }) { from_addr: from, exclude: me.agent, lenient: where.all, + limit, }); fleet = out.messages; unregistered = out.unregistered ?? []; + report = out; } const messages = []; for (const channel of where.channels) { @@ -137,7 +175,7 @@ export async function relay(store, { from, to, body, kind, sender }) { fleet.push((await store.fleet("post", { agent: me.agent, body })).message); } } - return { messages, fleet, unregistered }; + return { messages, fleet, unregistered, report }; } /** A from_addr as the address that answers it: null (Drew) stays "drew". */ diff --git a/pkgs/message-bridge/worker/test/fleet.test.mjs b/pkgs/message-bridge/worker/test/fleet.test.mjs index 425b6db6d..2811ec7c4 100644 --- a/pkgs/message-bridge/worker/test/fleet.test.mjs +++ b/pkgs/message-bridge/worker/test/fleet.test.mjs @@ -4,7 +4,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { DatabaseSync } from "node:sqlite"; -import { deriveFleetToken, fleetCall, fleetOp, fleetSchema, fleetToken, parseTargets } from "../src/fleet.js"; +import { deriveFleetToken, fleetCall, fleetOp, fleetSchema, fleetToken, getDistribution, parseTargets } from "../src/fleet.js"; import { MemoryStore } from "../src/messages.js"; import { route } from "../src/routes.js"; @@ -237,3 +237,103 @@ test("inbox mark_read hands each message out once", async () => { assert.equal(box.messages.length, 0); assert.equal(box.stats.unread_commands + box.stats.unread_messages, 0); }); + +test("glob targets parse like names, and malformed globs are refused", () => { + assert.deepEqual(parseTargets("agent:f*"), { agents: ["f*"], groups: [], all: false }); + assert.deepEqual(parseTargets(["agent:Muse-*", "group:muse"]), { agents: ["muse-*"], groups: ["muse"], all: false }); + for (const bad of ["agent:f o*", "agent:-*", `agent:${"*".repeat(65)}`]) { + assert.throws(() => parseTargets(bad), /pattern|agent/, JSON.stringify(bad)); + } +}); + +test("pattern send with limit: first match in name order, match report, broaden remainder", async () => { + const { agent, owner } = await harness(); + await agent.hello({ agent: "fable" }); + await agent.hello({ agent: "falcon" }); + await agent.hello({ agent: "muse-1", groups: ["muse"] }); + + // Oracle (#14367): agent:f* matches two registered agents; limit 1 + // delivers to exactly the first by name order and reports the rest. + const res = await owner.send({ body: "take the next task", to: "agent:f*", kind: "command", limit: 1 }); + assert.equal(res.status, 201); + const sent = await res.json(); + assert.equal(sent.matched, 2); + assert.equal(sent.delivered, 1); + assert.deepEqual(sent.recipients, ["fable"]); + assert.equal(sent.remaining, 1); + assert.equal((await (await agent.inbox({ agent: "fable" })).json()).messages.length, 1); + assert.equal((await (await agent.inbox({ agent: "falcon" })).json()).messages.length, 0); + + // Broaden with limit 2 delivers to exactly the remaining agent. + const b1 = await (await owner.send({ broaden: sent.batch, limit: 2 })).json(); + assert.equal(b1.matched, 2); + assert.equal(b1.delivered, 1); + assert.deepEqual(b1.recipients, ["falcon"]); + assert.equal(b1.remaining, 0); + const falconBox = (await (await agent.inbox({ agent: "falcon" })).json()).messages; + assert.equal(falconBox.length, 1); + assert.equal(falconBox[0].body, "take the next task"); + assert.equal(falconBox[0].batch, sent.batch); + + // A second identical broaden delivers nothing — never a duplicate. + const b2 = await (await owner.send({ broaden: sent.batch, limit: 2 })).json(); + assert.equal(b2.delivered, 0); + assert.deepEqual(b2.messages, []); + assert.equal((await (await agent.inbox({ agent: "fable" })).json()).messages.length, 1); + assert.equal((await (await agent.inbox({ agent: "falcon" })).json()).messages.length, 1); +}); + +test("a glob matching nobody is an error, like an empty group", async () => { + const { agent, owner } = await harness(); + await agent.hello({ agent: "fable" }); + const res = await owner.send({ body: "x", to: "agent:z*" }); + assert.equal(res.status, 400); + assert.match((await res.json()).error, /no registered agent matches agent:z\*/); +}); + +test("limit applies across group and all sends, in name order", async () => { + const { agent, owner } = await harness(); + await agent.hello({ agent: "fable" }); + await agent.hello({ agent: "falcon", groups: ["crew"] }); + await agent.hello({ agent: "muse-1", groups: ["crew"] }); + const sent = await (await owner.send({ body: "crew task", to: "group:crew", limit: 1 })).json(); + assert.equal(sent.matched, 2); + assert.deepEqual(sent.recipients, ["falcon"]); + assert.equal(sent.remaining, 1); + const all = await (await owner.send({ body: "everyone", to: "all", limit: 2 })).json(); + assert.equal(all.matched, 3); + assert.deepEqual(all.recipients, ["fable", "falcon"]); + assert.equal(all.remaining, 1); +}); + +test("broaden can widen the pattern and still never re-delivers", async () => { + const { agent, owner } = await harness(); + await agent.hello({ agent: "fable" }); + await agent.hello({ agent: "falcon" }); + await agent.hello({ agent: "muse-1" }); + const sent = await (await owner.send({ body: "widen me", to: "agent:f*", limit: 1 })).json(); + assert.deepEqual(sent.recipients, ["fable"]); + const b = await (await owner.send({ broaden: sent.batch, to: "agent:m*", limit: 5 })).json(); + assert.equal(b.matched, 3); + assert.deepEqual(b.recipients, ["falcon", "muse-1"]); + assert.equal(b.remaining, 0); + assert.equal((await (await agent.inbox({ agent: "fable" })).json()).messages.length, 1); +}); + +test("every pattern send writes its bridge_distribution record", async () => { + const sql = sqlite(); + fleetSchema(sql); + const stub = { fleet: (op, args) => fleetOp(sql, op, args, "2026-11-24T00:00:00.000Z") }; + const call = (op, args) => fleetCall(stub, op, args); + await call("hello", { agent: "fable" }); + await call("hello", { agent: "falcon" }); + const sent = await call("send", { body: "b", to: "agent:f*", limit: 1 }); + const dist = getDistribution(sql, sent.batch); + assert.equal(dist.pattern, "agent:f*"); + assert.equal(dist.limit_n, 1); + assert.equal(dist.sender_addr, null); + assert.deepEqual(dist.matched, ["fable", "falcon"]); + assert.deepEqual(dist.delivered, ["fable"]); + await call("broaden", { batch: sent.batch, limit: 5 }); + assert.deepEqual(getDistribution(sql, sent.batch).delivered, ["fable", "falcon"]); +}); diff --git a/pkgs/message-bridge/worker/test/notes.test.mjs b/pkgs/message-bridge/worker/test/notes.test.mjs index e5a72f5cb..6d400d22b 100644 --- a/pkgs/message-bridge/worker/test/notes.test.mjs +++ b/pkgs/message-bridge/worker/test/notes.test.mjs @@ -123,3 +123,47 @@ test("direct and wildcard delivery, inbox isolation, ack, and signal change", as const unmatched = await send(DREW, "ghost/nobody", "nope"); assert.equal(unmatched.status, 400); }); + +test("notes pattern sends: limit, match report, glob segments, broaden remainder", async () => { + const { call, bearer, register } = harness(); + assert.equal((await register("muse/archer", ARCHER)).status, 201); + assert.equal((await register("muse/other", OTHER)).status, 201); + assert.equal((await register("user/drew", DREW)).status, 201); + const sendRaw = (token, body) => + call("/notes/send", { method: "POST", headers: bearer(token), body: JSON.stringify(body) }); + + // Oracle (#14367): muse/* matches two identities; limit 1 delivers + // to exactly the first in name order and reports the rest. + const sentRes = await sendRaw(ARCHER, { to: "muse/*", note: "first only", limit: 1 }); + assert.equal(sentRes.status, 201); + const sent = await sentRes.json(); + assert.equal(sent.matched, 2); + assert.equal(sent.delivered, 1); + assert.deepEqual(sent.recipients, ["muse/archer"]); + assert.equal(sent.remaining, 1); + assert.ok(sent.batch, "the send names its distribution batch"); + + // A segment glob follows the same rule: muse/o* names muse/other alone. + const glob = await (await sendRaw(ARCHER, { to: "muse/o*", note: "just other" })).json(); + assert.equal(glob.matched, 1); + assert.deepEqual(glob.recipients, ["muse/other"]); + assert.equal(glob.remaining, 0); + + // Broaden delivers the original note to exactly the remainder. + const b1 = await (await sendRaw(ARCHER, { broaden: sent.batch, limit: 2 })).json(); + assert.equal(b1.matched, 2); + assert.equal(b1.delivered, 1); + assert.deepEqual(b1.recipients, ["muse/other"]); + assert.equal(b1.remaining, 0); + assert.equal(b1.notes[0].note, "first only"); + + // A second identical broaden delivers nothing — never a duplicate. + const b2 = await (await sendRaw(ARCHER, { broaden: sent.batch, limit: 2 })).json(); + assert.equal(b2.delivered, 0); + assert.deepEqual(b2.notes, []); + + // Only the original sender may broaden a distribution. + const foreign = await sendRaw(OTHER, { broaden: sent.batch, limit: 2 }); + assert.equal(foreign.status, 400); + assert.match((await foreign.json()).error, /only the original sender/); +}); diff --git a/pkgs/message-bridge/worker/test/relay.test.mjs b/pkgs/message-bridge/worker/test/relay.test.mjs index ae8851cff..2e1ed0fb1 100644 --- a/pkgs/message-bridge/worker/test/relay.test.mjs +++ b/pkgs/message-bridge/worker/test/relay.test.mjs @@ -287,3 +287,32 @@ test("the wake text names ids and message senders, an instruction as Drew's, nev assert.match(t, /including instructions/); assert.ok(!t.includes("hidden")); }); + +test("addresses accept agent globs and refuse malformed ones", () => { + assert.deepEqual(parseAddresses("agent:f*", "channel:claude").fleet, ["agent:f*"]); + assert.throws(() => parseAddresses("agent:f o*", "channel:claude"), /unknown address/); +}); + +test("a connector sends to a glob with a limit, reports the match, then broadens", async () => { + const { tool, agent } = await harness(); + await agent.hello({ agent: "fable" }); + await agent.hello({ agent: "falcon" }); + + // Oracle (#14367) over the relay grammar: agent:f* with limit 1. + const sent = await tool(TOKEN, "send_message", { body: "take the next task", to: "agent:f*", kind: "instruction", limit: 1 }); + assert.equal(sent.report.matched, 2); + assert.equal(sent.report.delivered, 1); + assert.deepEqual(sent.report.recipients, ["fable"]); + assert.equal(sent.report.remaining, 1); + assert.equal((await agent.inbox("fable")).messages.length, 1); + assert.equal((await agent.inbox("falcon")).messages.length, 0); + + const b1 = await tool(TOKEN, "send_message", { broaden: sent.report.batch, limit: 2 }); + assert.equal(b1.report.delivered, 1); + assert.deepEqual(b1.report.recipients, ["falcon"]); + assert.equal(b1.report.remaining, 0); + + const b2 = await tool(TOKEN, "send_message", { broaden: sent.report.batch, limit: 2 }); + assert.equal(b2.report.delivered, 0); + assert.equal((await agent.inbox("falcon")).messages.length, 1); +});