diff --git a/pkgs/message-bridge/worker/README.md b/pkgs/message-bridge/worker/README.md index 58d84d248..d514385ea 100644 --- a/pkgs/message-bridge/worker/README.md +++ b/pkgs/message-bridge/worker/README.md @@ -110,6 +110,24 @@ their mailbox, mark what they handled, and post replies and reports back | `POST /api//fleet/credentials/mint` | owner | `{agent, scopes?, addr?}`: mint a credential for an agent or a service (below); the value is returned once, only its hash stored | | `GET /fleet//agents` | credential (`read`) | the agents list, as the owner's | | `GET /fleet//messages` | credential (`read`) | the fleet message log, as the owner's (`agent`, `direction`, `kind`, `since_id`, `before_id`, `limit`, `order`) | +| `POST /api//fleet/offer` | owner | `{body, to, kind?, slots, sender?, ttl_seconds?}`: post an offer (below) | +| `GET /api//fleet/offers` | owner | every offer with its claims (agent, time, delivered row) | +| `POST /fleet//offer` | fleet | `{agent, body, to, kind?, slots, ttl_seconds?}`: an agent posts an offer | +| `GET /fleet//offers` | fleet | `agent`, `groups`: the open offers this agent may claim (also in the inbox response) | +| `POST /fleet//claim` | fleet | `{agent, offer_id}`: claim an offer; past the last slot the answer is `filled` | + +An **offer** is claim-style distribution: instead of fanning a row out +to every match, a sender posts the work once with a slot count (`slots: +2`, addressed to a name, glob, group or `all`), and the next N eligible +agents who claim it are delivered a normal mailbox row on the offer's +batch — so a claimant's reply threads onto the batch, and the owner +reads the offer, its claims and the replies together (the offers list +above, or the pipeline filtered by that batch). Eligibility is matched +against the registry at claim time; a claim is one atomic store op, so +racing claims cannot oversubscribe the slots. An offer may carry a +`ttl_seconds`, after which claims answer `expired`. A claimed command +names no sender, like every command; the poster never claims its own +offer. The **fleet token** opens only `/fleet/...`. It is derived from the access token (HMAC-SHA256 of `ACCESS_TOKEN` over the label diff --git a/pkgs/message-bridge/worker/src/fleet.js b/pkgs/message-bridge/worker/src/fleet.js index f72caf69a..9b764ae38 100644 --- a/pkgs/message-bridge/worker/src/fleet.js +++ b/pkgs/message-bridge/worker/src/fleet.js @@ -34,6 +34,37 @@ // POST /api//fleet/send {body, to, kind?, sender?}: one // inbound row per recipient // +// Offers: claim-style distribution (design §4.2, #14371). A fan-out +// send cannot express "the next task goes to the next N agents who +// pick it up", so a sender can instead post an offer — stored once in +// fleet_offer, never fanned out: +// +// POST /api//fleet/offer {body, to, kind?, slots, sender?, +// ttl_seconds?}: post an offer +// GET /api//fleet/offers every offer with its claims +// (agent, time, delivered row) +// POST /fleet//offer {agent, body, to, kind?, slots, +// ttl_seconds?}: an agent posts one +// GET /fleet//offers ?agent=&groups=: the open offers +// this agent may claim (the inbox +// response carries the same list in +// its "offers" section) +// POST /fleet//claim {agent, offer_id}: claim one +// +// Eligibility is the offer's address (a name, glob, group or all) +// matched against the registry at claim time. A claim is one atomic +// store op: while slots remain it delivers a normal mailbox row to the +// claimer — on the offer's batch, so the claimer's reply threads onto +// the batch and the owner reads claims and replies together (the +// offer list above, and the pipeline filtered by batch) — and records +// the claim in fleet_offer_claim. Past the last slot a claim gets a +// definite "filled" answer and no row; an expired offer (ttl_seconds) +// answers "expired", a second claim by the same agent "already +// claimed", and an agent outside the address can neither see nor +// claim the offer. A command offer reaches its claimers with no +// sender, like every command (commandForAgent); the owner still sees +// who posted it. +// // Per-agent credentials and bootstrap enrollment (#14368, design §4.5): // the routes above also answer to a per-agent credential in place of // the fleet token (/fleet//...). A credential is a random @@ -132,6 +163,7 @@ import { relay, replyAddress } from "./relay.js"; export const FLEET_KINDS = ["message", "command"]; export const FLEET_DIRECTIONS = ["inbound", "outbound"]; export const MAX_RECIPIENTS = 200; +export const OFFER_MAX_TTL_SECONDS = 30 * 24 * 3600; export const MAX_GROUPS = 16; export const FLEET_DEFAULT_LIMIT = 50; export const FLEET_MAX_LIMIT = 200; @@ -363,6 +395,34 @@ export function normalizeFleetOp(op, a = {}) { from_addr: normalizeFromAddr(a.from_addr), exclude: a.exclude === undefined || a.exclude === null ? null : normalizeName(a.exclude), }; + case "offer": { + const slots = intParam(a.slots, "slots", { min: 1 }); + if (slots === null) throw new InputError("slots must be an integer >= 1"); + if (slots > MAX_RECIPIENTS) throw new InputError(`slots must be at most ${MAX_RECIPIENTS}`); + const ttl = intParam(a.ttl_seconds, "ttl_seconds", { min: 1 }); + if (ttl !== null && ttl > OFFER_MAX_TTL_SECONDS) { + throw new InputError(`ttl_seconds must be at most ${OFFER_MAX_TTL_SECONDS}`); + } + return { + body: normalizeBody(a.body), + targets: parseTargets(a.to), + kind: normalizeFleetKind(a.kind), + sender: normalizeSender(a.sender), + from_addr: normalizeFromAddr(a.from_addr), + pattern: rawPattern(a.to), + slots, + ttl_seconds: ttl, + }; + } + case "offers": + return { agent: normalizeName(a.agent), groups: normalizeGroups(a.groups) }; + case "claim": { + const offer_id = intParam(a.offer_id, "offer_id", { min: 1 }); + if (offer_id === null) throw new InputError("offer_id must be a positive integer"); + return { agent: normalizeName(a.agent), offer_id }; + } + case "offer-list": + return {}; case "origin": return { agent: normalizeName(a.agent), id: intParam(a.id, "id", { min: 1 }) }; case "agents": @@ -456,6 +516,30 @@ export function fleetSchema(sql) { delivered TEXT NOT NULL, ts TEXT NOT NULL )`); + // Offer pool (design §4.2): an offer is stored once, not fanned out; + // a claim (fleet_offer_claim, one row per claimer) is what delivers + // a mailbox row. state is 'open' until the last slot is claimed + // ('filled'); expiry is derived from expires_at at read time. + sql.exec(`CREATE TABLE IF NOT EXISTS fleet_offer ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + batch TEXT NOT NULL, + body TEXT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('message', 'command')), + pattern TEXT, + slots INTEGER NOT NULL, + sender TEXT, + sender_addr TEXT, + ts TEXT NOT NULL, + expires_at TEXT, + state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'filled')) + )`); + sql.exec(`CREATE TABLE IF NOT EXISTS fleet_offer_claim ( + offer_id INTEGER NOT NULL, + agent TEXT NOT NULL, + claimed_at TEXT NOT NULL, + message_id INTEGER, + PRIMARY KEY (offer_id, agent) + )`); } /** Records (or replaces) one send's distribution; matched/delivered are name lists. */ @@ -480,6 +564,92 @@ export function getDistribution(sql, batch) { return { ...r, matched: JSON.parse(r.matched), delivered: JSON.parse(r.delivered) }; } +// ---- offers (design §4.2) ---- + +/** One offer's claims, oldest first: [{agent, claimed_at, message_id}]. */ +function offerClaims(sql, offer_id) { + return sql + .exec("SELECT agent, claimed_at, message_id FROM fleet_offer_claim WHERE offer_id = ? ORDER BY claimed_at, agent", offer_id) + .toArray() + .map((r) => ({ ...r })); +} + +/** An offer's state as of now: the stored state, or "expired" past its expiry. */ +function offerState(offer, claimed, now) { + if (offer.state === "filled" || claimed >= offer.slots) return "filled"; + if (offer.expires_at && offer.expires_at <= now) return "expired"; + return "open"; +} + +/** The owner's view of one offer: real sender, claims named. */ +function offerForOwner(sql, offer, now) { + const claims = offerClaims(sql, offer.id); + return { + ...offer, + state: offerState(offer, claims.length, now), + claimed: claims.length, + remaining: offer.slots - claims.length, + claims, + }; +} + +/** + * An eligible agent's view of one offer. A command offer names no + * sender here either (the anonymity rule, §4.3): the claimer treats + * it as Drew's, exactly like a delivered command. + */ +function offerForAgent(offer, claimed, now) { + const command = offer.kind === "command"; + return { + id: offer.id, + batch: offer.batch, + body: offer.body, + kind: offer.kind, + slots: offer.slots, + claimed, + remaining: offer.slots - claimed, + ts: offer.ts, + expires_at: offer.expires_at, + state: offerState(offer, claimed, now), + sender: command ? null : offer.sender, + from_addr: command ? null : offer.sender_addr, + }; +} + +/** + * Whether the offer's address names this agent, matched against the + * registry row at claim time (design §4.2): a glob over its name, one + * of its groups, an exact name, or all. The poster never claims its + * own offer. + */ +function offerEligible(offer, agent) { + if (offer.sender_addr === `agent:${agent.name}`) return false; + let targets; + try { + targets = parseTargets(offer.pattern); + } catch { + return false; + } + if (targets.all) return true; + if (targets.groups.some((g) => agent.groups.includes(g))) return true; + return targets.agents.some((t) => (isGlob(t) ? globMatch(t, agent.name) : t === agent.name)); +} + +/** The open offers this agent may still claim, oldest first, in agent projection. */ +function openOffersFor(sql, agent, now) { + const me = agentRow(sql.exec("SELECT * FROM fleet_agent WHERE name = ?", agent).toArray()[0]); + if (!me) return []; + const out = []; + for (const offer of sql.exec("SELECT * FROM fleet_offer WHERE state = 'open' ORDER BY id ASC").toArray()) { + const claims = offerClaims(sql, offer.id); + if (claims.some((c) => c.agent === agent)) continue; + if (offerState(offer, claims.length, now) !== "open") continue; + if (!offerEligible(offer, me)) continue; + out.push(offerForAgent(offer, claims.length, now)); + } + return out; +} + const rows = (cursor) => cursor.toArray().map((r) => ({ ...r })); function agentRow(r) { @@ -591,7 +761,7 @@ export function fleetOp(sql, op, a, now = new Date().toISOString()) { } } } - return { agent, messages, next_since_id: next, stats: mailboxStats(sql, a.agent) }; + return { agent, messages, next_since_id: next, stats: mailboxStats(sql, a.agent), offers: openOffersFor(sql, a.agent, now) }; } case "ack": { let acked = 0; @@ -754,6 +924,97 @@ export function fleetOp(sql, op, a, now = new Date().toISOString()) { remaining: matched.length - delivered.length, }; } + case "offer": { + const batch = randomBatch(); + const expires_at = a.ttl_seconds ? new Date(Date.parse(now) + a.ttl_seconds * 1000).toISOString() : null; + const offer = { + ...sql + .exec( + `INSERT INTO fleet_offer (batch, body, kind, pattern, slots, sender, sender_addr, ts, expires_at, state) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'open') RETURNING *`, + batch, + a.body, + a.kind, + a.pattern, + a.slots, + a.sender, + a.from_addr, + now, + expires_at, + ) + .toArray()[0], + }; + return { offer: offerForOwner(sql, offer, now) }; + } + case "offers": { + touch(sql, a.agent, a.groups, now); + return { offers: openOffersFor(sql, a.agent, now) }; + } + case "claim": { + touch(sql, a.agent, null, now); + const offer = sql.exec("SELECT * FROM fleet_offer WHERE id = ?", a.offer_id).toArray()[0]; + if (!offer) return { error: `offer ${a.offer_id} does not exist` }; + const me = agentRow(sql.exec("SELECT * FROM fleet_agent WHERE name = ?", a.agent).toArray()[0]); + if (!offerEligible(offer, me)) return { error: `${a.agent} is not eligible for offer ${offer.id}` }; + const claims = offerClaims(sql, offer.id); + if (claims.some((c) => c.agent === a.agent)) return { error: `${a.agent} has already claimed offer ${offer.id}` }; + if (offer.expires_at && offer.expires_at <= now) return { error: `offer ${offer.id} has expired` }; + if (offer.state !== "open" || claims.length >= offer.slots) return { error: `offer ${offer.id} is filled` }; + // The claim itself is one conditional insert: it lands only + // while a slot remains on an open offer and this agent has not + // claimed — so racing claims cannot oversubscribe the slots, + // whatever order the store runs them in. + const landed = sql + .exec( + `INSERT INTO fleet_offer_claim (offer_id, agent, claimed_at, message_id) + SELECT ?, ?, ?, NULL + WHERE (SELECT COUNT(*) FROM fleet_offer_claim WHERE offer_id = ?) < (SELECT slots FROM fleet_offer WHERE id = ? AND state = 'open') + AND NOT EXISTS (SELECT 1 FROM fleet_offer_claim WHERE offer_id = ? AND agent = ?) + RETURNING offer_id`, + offer.id, + a.agent, + now, + offer.id, + offer.id, + offer.id, + a.agent, + ) + .toArray(); + if (!landed.length) { + const again = offerClaims(sql, offer.id); + if (again.some((c) => c.agent === a.agent)) return { error: `${a.agent} has already claimed offer ${offer.id}` }; + return { error: `offer ${offer.id} is filled` }; + } + const message = { + ...sql + .exec( + `INSERT INTO fleet_message (ts, agent, direction, kind, sender, body, batch, from_addr) + VALUES (?, ?, 'inbound', ?, ?, ?, ?, ?) RETURNING *`, + now, + a.agent, + offer.kind, + offer.sender, + offer.body, + offer.batch, + offer.sender_addr, + ) + .toArray()[0], + }; + sql.exec("UPDATE fleet_offer_claim SET message_id = ? WHERE offer_id = ? AND agent = ?", message.id, offer.id, a.agent); + const claimed = offerClaims(sql, offer.id).length; + if (claimed >= offer.slots) sql.exec("UPDATE fleet_offer SET state = 'filled' WHERE id = ?", offer.id); + return { + offer: offerForAgent(offer, claimed, now), + message, + claimed, + remaining: offer.slots - claimed, + stats: mailboxStats(sql, a.agent), + }; + } + case "offer-list": { + const offers = rows(sql.exec("SELECT * FROM fleet_offer ORDER BY id ASC")).map((r) => offerForOwner(sql, r, now)); + return { offers }; + } case "origin": { const orig = sql .exec("SELECT id, from_addr, batch FROM fleet_message WHERE id = ? AND agent = ? AND direction = 'inbound'", a.id, a.agent) @@ -1239,6 +1500,44 @@ async function agentRoute(request, store, what, url, delivered, cred = null) { } return json(await agentSend(store, d, delivered), 201); } + if (what === "offers") { + if (request.method !== "GET") return notAllowed("GET"); + if (cred && (!scoped("inbox") || credOwnName(url.searchParams.get("agent"), cred) === null)) return notFound(); + return json(await store.fleet("offers", query(url))); + } + if (what === "offer") { + if (request.method !== "POST") return notAllowed("POST"); + const d = await readJson(request); + let fromAddr = null; + if (cred) { + if (!scoped("send") || credOwnName(d.agent, cred) === null) return notFound(); + // from_addr is fixed to the credential's address (agent:, or service: for a service credential, #14373); + // the sender label follows it, whatever the body claims. + d.sender = cred.addr ?? cred.agent; + fromAddr = cred.addr ?? `agent:${cred.agent}`; + } + const agent = normalizeName(d.agent); + const out = await store.fleet("offer", { + body: d.body, + to: d.to, + kind: d.kind, + slots: d.slots, + ttl_seconds: d.ttl_seconds, + sender: d.sender ?? agent, + from_addr: fromAddr ?? `agent:${agent}`, + }); + return json(out, 201); + } + if (what === "claim") { + if (request.method !== "POST") return notAllowed("POST"); + const d = await readJson(request); + if (cred && (!scoped("inbox") || credOwnName(d.agent, cred) === null)) return notFound(); + const out = await store.fleet("claim", d); + // The delivered row is projected like any inbox row: a claimed + // command names no sender. + return json({ ...out, message: commandForAgent(out.message) }); + } // The owner's pipeline views, for a credential holding the "read" // scope (a service credential, #14373): the same store ops the owner // routes answer, nothing more. Enroll-minted agent credentials never @@ -1273,6 +1572,24 @@ async function ownerRoute(request, store, what, url, delivered) { delivered({ messages: [], fleet: out.messages }); return json(out, 201); } + if (what === "offer") { + if (request.method !== "POST") return notAllowed("POST"); + const d = await readJson(request); + // An offer delivers nothing yet, so there is nobody to wake. + const out = await store.fleet("offer", { + body: d.body, + to: d.to, + kind: d.kind, + sender: d.sender, + slots: d.slots, + ttl_seconds: d.ttl_seconds, + }); + return json(out, 201); + } + if (what === "offers") { + if (request.method !== "GET") return notAllowed("GET"); + return json(await store.fleet("offer-list", {})); + } return notFound(); } diff --git a/pkgs/message-bridge/worker/src/routes.js b/pkgs/message-bridge/worker/src/routes.js index 0226e283b..3b1960880 100644 --- a/pkgs/message-bridge/worker/src/routes.js +++ b/pkgs/message-bridge/worker/src/routes.js @@ -43,6 +43,16 @@ // the token is the shared fleet token // or one agent's own credential // (#14368), which acts only as itself +// POST /api//fleet/offer owner: post an offer (claim-style +// distribution, fleet.js): {body, to, +// kind?, slots, sender?, ttl_seconds?} +// GET /api//fleet/offers owner: every offer with its claims +// POST /fleet//offer an agent posts an offer +// GET /fleet//offers the open offers one agent may claim +// (also the inbox response's section) +// POST /fleet//claim {agent, offer_id}: claim an offer; +// the first N claimants are delivered +// the row, the rest get "filled" // POST /api//enroll-tokens owner: mint a bootstrap enroll // token bound to a name/kind/groups; // the value is returned once diff --git a/pkgs/message-bridge/worker/test/offers.test.mjs b/pkgs/message-bridge/worker/test/offers.test.mjs new file mode 100644 index 000000000..e6cb130bb --- /dev/null +++ b/pkgs/message-bridge/worker/test/offers.test.mjs @@ -0,0 +1,313 @@ +// Offer pool (src/fleet.js, design §4.2, #14371): claim-style +// distribution routed end to end through route(), with the real +// fleetOp SQL running on node:sqlite in place of the Durable Object's +// storage (same harness as fleet.test.mjs), plus a controllable clock +// for the expiry cases. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { DatabaseSync } from "node:sqlite"; +import { fleetCall, fleetOp, fleetSchema, fleetToken } from "../src/fleet.js"; +import { MemoryStore } from "../src/messages.js"; +import { noteTokenHash } from "../src/notes.js"; +import { route } from "../src/routes.js"; + +const TOKEN = "o".repeat(20) + "0123456789abcdefXYZ_-"; +const CHATGPT = "c".repeat(40); +const env = { ACCESS_TOKEN: TOKEN, CHATGPT_TOKEN: CHATGPT }; +const BASE = "https://bridge.example"; + +/** The Durable Object's sql.exec over node:sqlite. */ +function sqlite() { + const db = new DatabaseSync(":memory:"); + return { + exec(q, ...args) { + const out = db.prepare(q).all(...args); + return { toArray: () => out, one: () => out[0] }; + }, + }; +} + +async function harness() { + const sql = sqlite(); + fleetSchema(sql); + let nowMs = Date.parse("2026-11-24T00:00:00.000Z"); + const now = () => new Date(nowMs).toISOString(); + const stub = { fleet: (op, args) => fleetOp(sql, op, args, now()) }; + const store = new MemoryStore(now); + store.fleet = (op, args) => fleetCall(stub, op, args); + const call = (path, init) => route(new Request(BASE + path, init), env, () => store); + const ft = await fleetToken(env); + const post = (path, body) => + call(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const agent = { + hello: (body) => post(`/fleet/${ft}/hello`, body), + inbox: (qs) => call(`/fleet/${ft}/inbox?${new URLSearchParams(qs)}`), + send: (body) => post(`/fleet/${ft}/send`, body), + offer: (body) => post(`/fleet/${ft}/offer`, body), + offers: (qs) => call(`/fleet/${ft}/offers?${new URLSearchParams(qs)}`), + claim: (body) => post(`/fleet/${ft}/claim`, body), + }; + const owner = { + send: (body) => post(`/api/${TOKEN}/fleet/send`, body), + offer: (body) => post(`/api/${TOKEN}/fleet/offer`, body), + offers: () => call(`/api/${TOKEN}/fleet/offers`), + messages: (qs = {}) => call(`/api/${TOKEN}/fleet/messages?${new URLSearchParams(qs)}`), + pipeline: (qs = {}) => call(`/api/${TOKEN}/pipeline?${new URLSearchParams(qs)}`), + }; + return { store, sql, call, ft, post, agent, owner, advance: (secs) => (nowMs += secs * 1000) }; +} + +async function register(agent) { + assert.equal((await agent.hello({ agent: "fable" })).status, 200); + assert.equal((await agent.hello({ agent: "falcon", groups: ["crew"] })).status, 200); + assert.equal((await agent.hello({ agent: "fennel" })).status, 200); + assert.equal((await agent.hello({ agent: "muse-1", groups: ["crew"] })).status, 200); +} + +test("slots 2, three eligible claimants: exactly the first two are delivered, the third is filled", async () => { + const { agent, owner } = await harness(); + await register(agent); + + const res = await owner.offer({ body: "take the next task", to: "agent:f*", kind: "command", slots: 2, sender: "drew" }); + assert.equal(res.status, 201); + const { offer } = await res.json(); + assert.equal(offer.state, "open"); + assert.equal(offer.claimed, 0); + assert.equal(offer.remaining, 2); + assert.deepEqual(offer.claims, []); + + // Stored once, not fanned out: no mailbox rows anywhere yet, but the + // eligible agents see the offer in their inbox's offers section. + for (const name of ["fable", "falcon", "fennel", "muse-1"]) { + const box = await (await agent.inbox({ agent: name })).json(); + assert.deepEqual(box.messages, [], name); + } + assert.deepEqual((await (await agent.inbox({ agent: "fable" })).json()).offers.map((o) => o.id), [offer.id]); + assert.deepEqual((await (await agent.offers({ agent: "falcon" })).json()).offers.map((o) => o.id), [offer.id]); + assert.deepEqual((await (await agent.inbox({ agent: "muse-1" })).json()).offers, [], "outside the pattern: no offer shown"); + + // First two claims win a normal mailbox row on the offer's batch. + const c1 = await agent.claim({ agent: "fable", offer_id: offer.id }); + assert.equal(c1.status, 200); + const claim1 = await c1.json(); + assert.equal(claim1.message.body, "take the next task"); + assert.equal(claim1.message.batch, offer.batch); + assert.equal(claim1.remaining, 1); + const c2 = await agent.claim({ agent: "falcon", offer_id: offer.id }); + assert.equal(c2.status, 200); + const claim2 = await c2.json(); + assert.equal(claim2.remaining, 0); + + // The third eligible claim gets a definite "filled" — and no row. + const c3 = await agent.claim({ agent: "fennel", offer_id: offer.id }); + assert.equal(c3.status, 400); + assert.match((await c3.json()).error, /filled/); + assert.deepEqual((await (await agent.inbox({ agent: "fennel" })).json()).messages, []); + assert.deepEqual((await (await owner.messages({ agent: "fennel" })).json()).messages, []); + + // The owner's list names the claimants, their times and their rows. + const list = (await (await owner.offers()).json()).offers; + assert.equal(list.length, 1); + assert.equal(list[0].state, "filled"); + assert.equal(list[0].claimed, 2); + assert.deepEqual( + list[0].claims.map((c) => [c.agent, c.message_id]), + [ + ["fable", claim1.message.id], + ["falcon", claim2.message.id], + ], + ); + assert.ok(list[0].claims.every((c) => typeof c.claimed_at === "string" && c.claimed_at.length > 0)); +}); + +test("an agent outside the offer's pattern can neither see nor claim it", async () => { + const { agent, owner } = await harness(); + await register(agent); + const { offer } = await (await owner.offer({ body: "crew only", to: "group:crew", slots: 1 })).json(); + // fennel is registered but not in crew; ghost is not registered at all. + assert.deepEqual((await (await agent.offers({ agent: "fennel" })).json()).offers, []); + const denied = await agent.claim({ agent: "fennel", offer_id: offer.id }); + assert.equal(denied.status, 400); + assert.match((await denied.json()).error, /not eligible/); + const ghost = await agent.claim({ agent: "ghost", offer_id: offer.id }); + assert.equal(ghost.status, 400); + assert.match((await ghost.json()).error, /not eligible/); + // A crew member sees and claims it. + assert.deepEqual((await (await agent.offers({ agent: "muse-1" })).json()).offers.map((o) => o.id), [offer.id]); + assert.equal((await agent.claim({ agent: "muse-1", offer_id: offer.id })).status, 200); +}); + +test("a claimant's reply threads onto the offer batch, visible to the owner with the claimant named", async () => { + const { agent, owner } = await harness(); + await register(agent); + const { offer } = await (await owner.offer({ body: "do the thing", to: "agent:f*", slots: 1, sender: "drew" })).json(); + const claim = await (await agent.claim({ agent: "falcon", offer_id: offer.id })).json(); + + const res = await agent.send({ agent: "falcon", body: "thing done", reply_to: claim.message.id }); + assert.equal(res.status, 201); + const reply = (await res.json()).message; + assert.equal(reply.batch, offer.batch); + assert.equal(reply.agent, "falcon"); + + // The pipeline filtered by the batch shows delivery and reply together. + const feed = (await (await owner.pipeline({ batch: offer.batch })).json()).messages; + assert.deepEqual( + feed.map((m) => [m.surface, m.direction, m.receiver ?? m.sender_addr, m.body]), + [ + ["fleet", "inbound", "agent:falcon", "do the thing"], + ["fleet", "outbound", "user:drew", "thing done"], + ], + ); + const list = (await (await owner.offers()).json()).offers; + assert.equal(list[0].claims[0].agent, "falcon"); + assert.equal(list[0].claims[0].message_id, claim.message.id); +}); + +test("an instruction offer reaches claimants sender-stripped; the owner sees the real sender", async () => { + const { agent, owner } = await harness(); + await register(agent); + + // Owner-posted command offer: claim response and inbox show no sender. + const { offer } = await (await owner.offer({ body: "quiet task", to: "agent:fable", kind: "command", slots: 1, sender: "drew" })).json(); + const seen = (await (await agent.offers({ agent: "fable" })).json()).offers[0]; + assert.equal(seen.sender, null); + assert.equal(seen.from_addr, null); + const claim = await (await agent.claim({ agent: "fable", offer_id: offer.id })).json(); + assert.equal(claim.message.sender, null); + assert.equal(claim.message.from_addr, null); + const box = (await (await agent.inbox({ agent: "fable", unread_only: "false" })).json()).messages; + assert.equal(box[0].sender, null); + + // Agent-posted command offer: the owner list names the poster; the + // claimer still sees no sender. + const posted = await (await agent.offer({ agent: "muse-1", body: "agent task", to: "group:crew", kind: "command", slots: 1 })).json(); + assert.equal(posted.offer.sender_addr, "agent:muse-1"); + const list = (await (await owner.offers()).json()).offers; + assert.equal(list.find((o) => o.id === posted.offer.id).sender_addr, "agent:muse-1"); + const claim2 = await (await agent.claim({ agent: "falcon", offer_id: posted.offer.id })).json(); + assert.equal(claim2.message.sender, null); + assert.equal(claim2.message.from_addr, null); + + // A plain message offer keeps its sender, like any plain message. + const { offer: msgOffer } = await (await owner.offer({ body: "fyi all", to: "all", slots: 1, sender: "drew" })).json(); + const claim3 = await (await agent.claim({ agent: "fennel", offer_id: msgOffer.id })).json(); + assert.equal(claim3.message.sender, "drew"); +}); + +test("concurrent claims cannot oversubscribe the slots", async () => { + const { agent, owner } = await harness(); + await register(agent); + await agent.hello({ agent: "fiona" }); + await agent.hello({ agent: "flora" }); + const { offer } = await (await owner.offer({ body: "race me", to: "agent:f*", slots: 2 })).json(); + + const names = ["fable", "falcon", "fennel", "fiona", "flora"]; + const results = await Promise.all(names.map((name) => agent.claim({ agent: name, offer_id: offer.id }))); + const won = results.filter((r) => r.status === 200); + const lost = results.filter((r) => r.status === 400); + assert.equal(won.length, 2, "exactly the slot count wins"); + assert.equal(lost.length, 3); + for (const r of lost) assert.match((await r.json()).error, /filled/); + + const list = (await (await owner.offers()).json()).offers; + assert.equal(list[0].claimed, 2); + assert.equal(list[0].state, "filled"); + const delivered = (await (await owner.messages({ direction: "inbound" })).json()).messages; + assert.equal(delivered.length, 2, "one mailbox row per winning claim, no more"); +}); + +test("a claim after the offer's expiry is refused, and the offer reads expired", async () => { + const { agent, owner, advance } = await harness(); + await register(agent); + const { offer } = await (await owner.offer({ body: "short lived", to: "all", slots: 1, ttl_seconds: 60 })).json(); + assert.ok(offer.expires_at > offer.ts); + advance(61); + const res = await agent.claim({ agent: "fable", offer_id: offer.id }); + assert.equal(res.status, 400); + assert.match((await res.json()).error, /expired/); + assert.deepEqual((await (await agent.offers({ agent: "fable" })).json()).offers, [], "expired offers leave the open list"); + const list = (await (await owner.offers()).json()).offers; + assert.equal(list[0].state, "expired"); + assert.equal(list[0].claimed, 0); +}); + +test("a second claim by the same agent is refused and delivers nothing twice", async () => { + const { agent, owner } = await harness(); + await register(agent); + const { offer } = await (await owner.offer({ body: "once only", to: "all", slots: 3 })).json(); + assert.equal((await agent.claim({ agent: "fable", offer_id: offer.id })).status, 200); + const again = await agent.claim({ agent: "fable", offer_id: offer.id }); + assert.equal(again.status, 400); + assert.match((await again.json()).error, /already claimed/); + assert.equal((await (await agent.inbox({ agent: "fable", unread_only: "false" })).json()).messages.length, 1); + const list = (await (await owner.offers()).json()).offers; + assert.equal(list[0].claimed, 1); + assert.equal(list[0].state, "open", "slots remain for other agents"); + // And the claimer no longer sees it as open. + assert.deepEqual((await (await agent.offers({ agent: "fable" })).json()).offers, []); +}); + +test("the poster cannot claim its own offer", async () => { + const { agent, owner } = await harness(); + await register(agent); + const posted = await (await agent.offer({ agent: "muse-1", body: "for the crew", to: "group:crew", slots: 2 })).json(); + const own = await agent.claim({ agent: "muse-1", offer_id: posted.offer.id }); + assert.equal(own.status, 400); + assert.match((await own.json()).error, /not eligible/); + assert.equal((await agent.claim({ agent: "falcon", offer_id: posted.offer.id })).status, 200); + const list = (await (await owner.offers()).json()).offers; + assert.deepEqual(list[0].claims.map((c) => c.agent), ["falcon"]); +}); + +test("offer and claim input is checked", async () => { + const { agent, owner } = await harness(); + await register(agent); + for (const body of [ + { body: "x", to: "all" }, // no slots + { body: "x", to: "all", slots: 0 }, + { body: "x", to: "all", slots: 201 }, + { body: "x", to: "all", slots: 1.5 }, + { body: "", to: "all", slots: 1 }, + { body: "x", slots: 1 }, // no address + { body: "x", to: "agent:z*", slots: 1, ttl_seconds: 0 }, + { body: "x", to: "all", slots: 1, kind: "shout" }, + ]) { + const r = await owner.offer(body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.ok((await r.json()).error); + } + const missing = await agent.claim({ agent: "fable", offer_id: 999 }); + assert.equal(missing.status, 400); + assert.match((await missing.json()).error, /does not exist/); + assert.equal((await agent.claim({ agent: "fable" })).status, 400); +}); + +test("a per-agent credential claims and posts only as itself, within its scopes", async () => { + const { store, post, call, ft, agent, owner } = await harness(); + await register(agent); + const { offer } = await (await owner.offer({ body: "cred task", to: "agent:f*", slots: 2 })).json(); + + // A credential for fable with only the send scope: it may post an + // offer but may not claim (claiming acts on its mailbox: inbox scope). + const sendOnly = "s".repeat(43); + await store.fleetCredentialPut({ token_hash: await noteTokenHash(sendOnly), agent: "fable", scopes: ["send"], created: "2026-11-24T00:00:00.000Z" }); + const denied = await post(`/fleet/${sendOnly}/claim`, { agent: "fable", offer_id: offer.id }); + assert.equal(denied.status, 404, "no inbox scope: the plain 404 every refusal gets"); + const posted = await post(`/fleet/${sendOnly}/offer`, { agent: "fable", body: "from cred", to: "all", slots: 1 }); + assert.equal(posted.status, 201); + assert.equal((await posted.json()).offer.sender_addr, "agent:fable", "the credential fixes the sender to its own name"); + + // A credential with both scopes claims as itself — and only itself. + const both = "b".repeat(43); + await store.fleetCredentialPut({ token_hash: await noteTokenHash(both), agent: "falcon", scopes: ["inbox", "send"], created: "2026-11-24T00:00:00.000Z" }); + const asOther = await post(`/fleet/${both}/claim`, { agent: "fable", offer_id: offer.id }); + assert.equal(asOther.status, 404, "a credential cannot claim for another agent"); + const mine = await post(`/fleet/${both}/claim`, { agent: "falcon", offer_id: offer.id }); + assert.equal(mine.status, 200); + assert.equal((await mine.json()).message.agent, "falcon"); + const seen = await call(`/fleet/${both}/offers?agent=falcon`); + assert.equal(seen.status, 200); + const seenOther = await call(`/fleet/${both}/offers?agent=fable`); + assert.equal(seenOther.status, 404); + assert.ok(ft.length > 0); +});