Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
272 changes: 249 additions & 23 deletions pkgs/message-bridge/worker/src/fleet.js

Large diffs are not rendered by default.

23 changes: 23 additions & 0 deletions pkgs/message-bridge/worker/src/glob.js
Original file line number Diff line number Diff line change
@@ -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);
}
82 changes: 79 additions & 3 deletions pkgs/message-bridge/worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import {
fleetCredentialRevokeSql,
fleetOp,
fleetSchema,
getDistribution,
recordDistribution,
} from "./fleet.js";
import { route } from "./routes.js";

Expand Down Expand Up @@ -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)");
}

Expand Down Expand Up @@ -257,27 +263,96 @@ 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) {
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) 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(
Expand Down Expand Up @@ -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),
Expand Down
28 changes: 26 additions & 2 deletions pkgs/message-bridge/worker/src/mcp.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down Expand Up @@ -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) {
Expand All @@ -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);
Expand All @@ -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": {
Expand Down
58 changes: 55 additions & 3 deletions pkgs/message-bridge/worker/src/messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down Expand Up @@ -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)
Expand Down
Loading