diff --git a/pkgs/fleet/crates/fleet-bridge/src/lib.rs b/pkgs/fleet/crates/fleet-bridge/src/lib.rs index 31d3a5d7e4..d3e57defec 100644 --- a/pkgs/fleet/crates/fleet-bridge/src/lib.rs +++ b/pkgs/fleet/crates/fleet-bridge/src/lib.rs @@ -67,6 +67,18 @@ central (owner token): agents registered agents, groups, unread counts log [--agent A] [--direction inbound|outbound] [--kind message|command] [--since-id N] [--before-id N] [--limit N] [--order asc|desc] + pipeline [--kind K] [--sender S] [--receiver R] [--surface S] + [--batch B] [--unread] [--work-state W] [--since-id N] + [--before-id N] [--limit N] [--order asc|desc] + the unified owner feed over connector messages, fleet + mailboxes and notes, real senders shown + directory the unified agents list: fleet registry + and note identities, each row marked by surface + credentials per-agent credential state (active or + revoked, live scopes; never a hash) + revoke (--agent A | --identity I) + revoke an agent's fleet credentials, or a notes identity's + tokens (the owner's kill switch, #14368) agent (fleet token): hello [--agent A] [--groups g1,g2] register / refresh groups @@ -128,6 +140,45 @@ usage: fleet bridge log [--agent A] [--direction inbound|outbound] [--kind messa [--since-id N] [--before-id N] [--limit N] [--order asc|desc] central (owner token). The central message log, filtered." + } + "pipeline" => { + "\ +usage: fleet bridge pipeline [--kind K] [--sender S] [--receiver R] [--surface S] + [--batch B] [--unread] [--work-state W] [--since-id N] + [--before-id N] [--limit N] [--order asc|desc] + +central (owner token). The unified owner feed over connector +messages, fleet mailboxes and notes (#14369), real senders shown: +kind is message, instruction, command or note; sender and receiver +name an address or its bare name; surface is connector, fleet or +notes. --work-state is passed through for the work-item lifecycle +(#14372)." + } + "directory" => { + "\ +usage: fleet bridge directory + +central (owner token). The unified agents list (#14369): fleet +registry rows (groups, first/last seen, unread counts) and note +identities (scopes, signal counter), each row marked by surface. +Notes identities have no presence; the row says so." + } + "credentials" => { + "\ +usage: fleet bridge credentials + +central (owner token). Per-agent credential state (#14368): one row +per agent that has held a credential — active or revoked, the scopes +its live credentials carry, mint and revocation times. State only: +no hash or value is ever shown." + } + "revoke" => { + "\ +usage: fleet bridge revoke (--agent A | --identity I) + +central (owner token). Revoke every live fleet credential of an +agent (--agent), or every notes token of an identity (--identity): +the per-agent kill switch (#14368). Prints how many were revoked." } "hello" => { "\ @@ -471,7 +522,12 @@ struct Args { const VALUE_FLAGS: &[&str] = &[ "--to", "--sender", + "--receiver", + "--surface", + "--batch", + "--work-state", "--agent", + "--identity", "--groups", "--direction", "--kind", @@ -701,6 +757,83 @@ pub fn execute(ctx: &mut Ctx, args: &[String]) -> R { let token = owner_token(ctx)?; client_with(ctx, &token).call("GET", &format!("/api/{token}/fleet/messages{q}"), None) } + "pipeline" => { + let a = parse( + rest, + &["--unread"], + &[ + "--kind", + "--sender", + "--receiver", + "--surface", + "--batch", + "--work-state", + "--since-id", + "--before-id", + "--limit", + "--order", + ], + )?; + a.no_positional("pipeline")?; + let q = query(&[ + ("kind", a.last("--kind")), + ("sender", a.last("--sender")), + ("receiver", a.last("--receiver")), + ("surface", a.last("--surface")), + ("batch", a.last("--batch")), + ( + "unread_only", + a.has("--unread").then(|| "true".to_string()), + ), + ("work_state", a.last("--work-state")), + ("since_id", a.uint("--since-id")?.map(|n| n.to_string())), + ("before_id", a.uint("--before-id")?.map(|n| n.to_string())), + ("limit", a.uint("--limit")?.map(|n| n.to_string())), + ("order", a.last("--order")), + ]); + let token = owner_token(ctx)?; + client_with(ctx, &token).call("GET", &format!("/api/{token}/pipeline{q}"), None) + } + "directory" => { + let a = parse(rest, &[], &[])?; + a.no_positional("directory")?; + let token = owner_token(ctx)?; + client_with(ctx, &token).call("GET", &format!("/api/{token}/agents"), None) + } + "credentials" => { + let a = parse(rest, &[], &[])?; + a.no_positional("credentials")?; + let token = owner_token(ctx)?; + client_with(ctx, &token).call("GET", &format!("/api/{token}/fleet/credentials"), None) + } + "revoke" => { + let a = parse(rest, &[], &["--agent", "--identity"])?; + a.no_positional("revoke")?; + // Checked before any credential is resolved: a usage error + // is a usage error even on a seat with no tokens. + let target = match (a.last("--agent"), a.last("--identity")) { + (Some(agent), None) => ("fleet", agent), + (None, Some(identity)) => ("notes", identity), + _ => { + return Err(usage( + "revoke needs exactly one of --agent or --identity", + )); + } + }; + let token = owner_token(ctx)?; + match target { + ("fleet", agent) => client_with(ctx, &token).call( + "POST", + &format!("/api/{token}/fleet/credentials/revoke"), + Some(&json!({ "agent": agent })), + ), + (_, identity) => client_with(ctx, &token).call( + "POST", + &format!("/api/{token}/notes-tokens/revoke"), + Some(&json!({ "identity": identity })), + ), + } + } "hello" => { let a = parse(rest, &[], &["--agent", "--groups"])?; a.no_positional("hello")?; diff --git a/pkgs/fleet/crates/fleet-bridge/src/tests.rs b/pkgs/fleet/crates/fleet-bridge/src/tests.rs index f43a3eef3b..a36b2cbd70 100644 --- a/pkgs/fleet/crates/fleet-bridge/src/tests.rs +++ b/pkgs/fleet/crates/fleet-bridge/src/tests.rs @@ -158,7 +158,18 @@ fn every_verb_has_its_own_help() { // usage — its own usage line, the shared footer, and never the // whole-domain USAGE text. for verb in [ - "send", "agents", "log", "hello", "inbox", "post", "ack", "health", + "send", + "agents", + "log", + "pipeline", + "directory", + "credentials", + "revoke", + "hello", + "inbox", + "post", + "ack", + "health", ] { let text = verb_usage(verb).unwrap_or_else(|| panic!("no per-verb help for {verb}")); assert!( @@ -200,6 +211,13 @@ fn usage_errors_exit_2_before_any_request() { vec!["ack", "--agent", "a"], vec!["ack", "--agent", "a", "0"], vec!["log", "--limit", "many"], + vec!["pipeline", "--limit", "many"], + vec!["pipeline", "--bogus", "x"], + vec!["directory", "extra"], + vec!["credentials", "extra"], + vec!["revoke"], + vec!["revoke", "--agent", "a", "--identity", "muse/a"], + vec!["revoke", "felix"], ] { let e = run_with(url, &s, &args, "").unwrap_err(); assert_eq!(e.exit_code(), EXIT_USAGE, "{args:?}: {e}"); @@ -421,6 +439,56 @@ fn ack_log_and_agents_shapes() { ); } +#[test] +fn pipeline_directory_credentials_and_revoke_shapes() { + // #14374: the console's unified views and its revoke control, as + // owner-token calls on the bridge's own routes. + let (url, seen) = fake_bridge(|_, _, _| (200, r#"{"ok":true}"#.into())); + let s = secrets(&[(DEFAULT_BRIDGE_OWNER_TOKEN_NAME, OWNER)]); + run_with( + &url, + &s, + &[ + "pipeline", + "--kind", + "command", + "--sender", + "felix", + "--unread", + "--limit", + "25", + "--order", + "desc", + ], + "", + ) + .unwrap(); + run_with(&url, &s, &["directory"], "").unwrap(); + run_with(&url, &s, &["credentials"], "").unwrap(); + run_with(&url, &s, &["revoke", "--agent", "felix"], "").unwrap(); + run_with(&url, &s, &["revoke", "--identity", "muse/felix"], "").unwrap(); + let seen = seen.lock().unwrap(); + assert_eq!( + seen[0].url, + format!("/api/{OWNER}/pipeline?kind=command&sender=felix&unread_only=true&limit=25&order=desc") + ); + assert_eq!(seen[1].url, format!("/api/{OWNER}/agents")); + assert_eq!(seen[2].url, format!("/api/{OWNER}/fleet/credentials")); + assert_eq!( + seen[3].url, + format!("/api/{OWNER}/fleet/credentials/revoke") + ); + assert_eq!( + seen[3].body.as_ref().unwrap(), + &json!({"agent": "felix"}) + ); + assert_eq!(seen[4].url, format!("/api/{OWNER}/notes-tokens/revoke")); + assert_eq!( + seen[4].body.as_ref().unwrap(), + &json!({"identity": "muse/felix"}) + ); +} + #[test] fn http_errors_exit_4_and_never_show_the_token() { let (url, _) = fake_bridge(|_, path, _| { diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index cc36648953..c8d8d91dbe 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -1075,8 +1075,8 @@ fn run_domain_with_initializer( return fleet_orgs::run(&surface.config, args); } // The bridge domain runs for real: fleet mailboxes on the - // message bridge (central send/agents/log; agent - // hello/inbox/post/ack). + // message bridge (central send/agents/log/pipeline/ + // directory/credentials/revoke; agent hello/inbox/post/ack). #[cfg(feature = "bridge")] if d.name == "bridge" { return fleet_bridge::run(&surface.config, args); diff --git a/pkgs/message-bridge/worker/README.md b/pkgs/message-bridge/worker/README.md index d514385eaf..b926f40155 100644 --- a/pkgs/message-bridge/worker/README.md +++ b/pkgs/message-bridge/worker/README.md @@ -110,6 +110,10 @@ 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`) | +| `GET /api//fleet/credentials` | owner | per-agent credential state: active or revoked, live scopes, service addr, mint and revocation times — never a hash | +| `GET /fleet//pipeline` | credential (`read`) | the unified pipeline feed, as the owner's `/api//pipeline` (#14374) | +| `GET /fleet//directory` | credential (`read`) | the unified agents list, as the owner's `/api//agents` (#14374) | +| `GET /fleet//credentials` | credential (`read`) | per-agent credential state, as the owner's (state only: a credential can see a revocation, never make one) | | `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 | diff --git a/pkgs/message-bridge/worker/src/fleet.js b/pkgs/message-bridge/worker/src/fleet.js index 9b764ae382..06ca959bc7 100644 --- a/pkgs/message-bridge/worker/src/fleet.js +++ b/pkgs/message-bridge/worker/src/fleet.js @@ -111,13 +111,22 @@ // agent-sent (agent:) ones in the owner's log; a command still // reaches its agent with no sender, as every command does. // -// A third scope, "read", opens the owner's two pipeline views to the -// credential that holds it, at the agent-side address: +// A third scope, "read", opens the owner's views to the credential +// that holds it, at the agent-side address: // // GET /fleet//agents the registered agents (the // ownerRoute "agents" store op) // GET /fleet//messages the fleet message log (the // ownerRoute "messages" store op) +// GET /fleet//pipeline the unified pipeline feed +// (pipeline.js, #14374) +// GET /fleet//directory the unified agents list — +// fleet registry + note +// identities (pipeline.js) +// GET /fleet//credentials per-agent credential state +// (active / revoked; never a +// hash), as the owner's own +// GET /api//fleet/credentials // // Enroll-minted agent credentials never carry "read" (the exchange // mints CREDENTIAL_SCOPES only): the pipeline stays the owner's and @@ -158,6 +167,7 @@ import { MIN_TOKEN_LENGTH, matchTokenPath, safeEqual, tokenConfigured } from "./ import { GLOB_SEGMENT, globMatch, isGlob } from "./glob.js"; import { InputError, MAX_BODY, MAX_SENDER } from "./messages.js"; import { normalizeNoteIdentity, noteTokenHash } from "./notes.js"; +import { pipelineFeed, unifiedAgents } from "./pipeline.js"; import { relay, replyAddress } from "./relay.js"; export const FLEET_KINDS = ["message", "command"]; @@ -1161,6 +1171,65 @@ export async function mintFleetCredential(store, data, now = new Date().toISOStr return { agent: m.agent, addr: m.addr, scopes: m.scopes, credential: value }; } +/** + * Folds credential rows (hashes already stripped by the caller) into + * one state row per agent: whether the agent's credential stands + * active (at least one live credential) or revoked, the scopes its + * live credentials carry between them, the address a live service + * credential sends as, and when the state last changed (the first + * mint, or the final revocation). An agent part-revoked and part-live + * is active, and says no revocation time: a superseded credential's + * end is not the agent's. + */ +export function foldCredentialState(rows) { + const byAgent = new Map(); + for (const r of rows) { + let a = byAgent.get(r.agent); + if (!a) { + a = { + agent: r.agent, + state: "revoked", + scopes: [], + addr: null, + credentials: 0, + live: 0, + created: r.created, + revoked_at: null, + }; + byAgent.set(r.agent, a); + } + a.credentials++; + if (r.created < a.created) a.created = r.created; + if (r.revoked_at) { + if (!a.revoked_at || r.revoked_at > a.revoked_at) a.revoked_at = r.revoked_at; + } else { + a.live++; + for (const s of JSON.parse(r.scopes)) if (!a.scopes.includes(s)) a.scopes.push(s); + if (r.addr) a.addr = r.addr; + } + } + const out = [...byAgent.values()]; + for (const a of out) { + if (a.live > 0) { + a.state = "active"; + a.revoked_at = null; + } + } + return out.sort((x, y) => (x.agent < y.agent ? -1 : x.agent > y.agent ? 1 : 0)); +} + +/** + * Per-agent credential state for the owner's console (design §4.9): + * the fold above over every credential row. Only hashes are excluded + * — they never leave the store; this is state, not key material. + */ +export function fleetCredentialStateSql(sql) { + const rows = sql + .exec("SELECT agent, scopes, addr, created, revoked_at FROM fleet_credential ORDER BY agent, created") + .toArray(); + return foldCredentialState(rows); +} + /** Revokes every live credential of the agent; returns how many. */ export function fleetCredentialRevokeSql(sql, agent, now) { return sql @@ -1538,15 +1607,25 @@ async function agentRoute(request, store, what, url, delivered, cred = null) { // 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 - // hold the scope, and the shared fleet token does not open these. - if (what === "agents" || what === "messages") { + // The owner's views, for a credential holding the "read" scope (a + // service credential, #14373): the same store ops the owner routes + // answer, nothing more. #14374 adds the unified projections the + // console's Messages and Agents surfaces read — the pipeline feed, + // the unified agents list and per-agent credential state — the very + // functions the owner's /api routes answer with. All are reads; no + // credential value or hash is in any of them, and revoking stays an + // owner-token route: a service credential can see that a credential + // stands revoked, never revoke one. Enroll-minted agent credentials + // never hold the scope, and the shared fleet token does not open + // these. + if (what === "agents" || what === "messages" || what === "pipeline" || what === "directory" || what === "credentials") { if (request.method !== "GET") return notAllowed("GET"); if (!cred || !scoped("read")) return notFound(); if (what === "agents") return json(await store.fleet("agents", {})); - return json(await store.fleet("messages", query(url))); + if (what === "messages") return json(await store.fleet("messages", query(url))); + if (what === "pipeline") return json(await pipelineFeed(store, Object.fromEntries(url.searchParams.entries()))); + if (what === "directory") return json(await unifiedAgents(store)); + return json({ credentials: await store.fleetCredentialState() }); } return notFound(); } @@ -1633,6 +1712,10 @@ export async function handleFleet(request, env, url, getStore, deliveredFor = () if (!m || m.role !== "owner") return null; // not ours: the caller 404s const store = getStore(); if (parts[2] === "fleet") { + if (parts.length === 4 && parts[3] === "credentials") { + if (request.method !== "GET") return notAllowed("GET"); + return json({ credentials: await store.fleetCredentialState() }); + } if (parts.length === 4) return await ownerRoute(request, store, parts[3], url, deliveredFor(store)); if (parts.length === 5 && parts[3] === "credentials" && parts[4] === "revoke") { if (request.method !== "POST") return notAllowed("POST"); diff --git a/pkgs/message-bridge/worker/src/index.js b/pkgs/message-bridge/worker/src/index.js index 72fc500f59..6609586306 100644 --- a/pkgs/message-bridge/worker/src/index.js +++ b/pkgs/message-bridge/worker/src/index.js @@ -18,6 +18,7 @@ import { fleetCredentialAuthSql, fleetCredentialPutSql, fleetCredentialRevokeSql, + fleetCredentialStateSql, fleetOp, fleetSchema, getDistribution, @@ -140,6 +141,10 @@ export class MessageStore extends DurableObject { return fleetCredentialRevokeSql(this.sql, agent, new Date().toISOString()); } + fleetCredentialState() { + return fleetCredentialStateSql(this.sql); + } + enrollTokenMint(row) { return enrollTokenMintSql(this.sql, row); } @@ -637,6 +642,7 @@ function storeFor(env) { fleetCredentialAuth: (token_hash) => stub.fleetCredentialAuth(token_hash), fleetCredentialPut: (rec) => stub.fleetCredentialPut(rec), fleetCredentialRevoke: (agent) => stub.fleetCredentialRevoke(agent), + fleetCredentialState: () => stub.fleetCredentialState(), enrollTokenMint: (row) => stub.enrollTokenMint(row), enrollTokenGet: (token_hash) => stub.enrollTokenGet(token_hash), enrollTokenClaim: (token_hash, agent, now) => stub.enrollTokenClaim(token_hash, agent, now), diff --git a/pkgs/message-bridge/worker/src/messages.js b/pkgs/message-bridge/worker/src/messages.js index aca9e020ae..4a085b3b6b 100644 --- a/pkgs/message-bridge/worker/src/messages.js +++ b/pkgs/message-bridge/worker/src/messages.js @@ -217,6 +217,44 @@ export class MemoryStore { } return n; } + // Per-agent credential state (fleet.js foldCredentialState, #14374), + // folded the same way over this store's rows: state, never hashes. + async fleetCredentialState() { + const byAgent = new Map(); + for (const c of this.fleetCredentials.values()) { + let a = byAgent.get(c.agent); + if (!a) { + a = { + agent: c.agent, + state: "revoked", + scopes: [], + addr: null, + credentials: 0, + live: 0, + created: c.created, + revoked_at: null, + }; + byAgent.set(c.agent, a); + } + a.credentials++; + if (c.created < a.created) a.created = c.created; + if (c.revoked_at) { + if (!a.revoked_at || c.revoked_at > a.revoked_at) a.revoked_at = c.revoked_at; + } else { + a.live++; + for (const s of c.scopes) if (!a.scopes.includes(s)) a.scopes.push(s); + if (c.addr) a.addr = c.addr; + } + } + const out = [...byAgent.values()]; + for (const a of out) { + if (a.live > 0) { + a.state = "active"; + a.revoked_at = null; + } + } + return out.sort((x, y) => (x.agent < y.agent ? -1 : x.agent > y.agent ? 1 : 0)); + } async enrollTokenMint(row) { this.enrollTokens.set(row.token_hash, { ...row, groups: [...row.groups], used_at: null, revoked_at: null }); return { agent: row.agent, kind: row.kind, groups: [...row.groups], notes_identity: row.notes_identity, expires_at: row.expires_at, created: row.created }; diff --git a/pkgs/message-bridge/worker/src/routes.js b/pkgs/message-bridge/worker/src/routes.js index 3b1960880e..5eb0bf4f88 100644 --- a/pkgs/message-bridge/worker/src/routes.js +++ b/pkgs/message-bridge/worker/src/routes.js @@ -72,6 +72,15 @@ // GET /fleet//agents|messages the owner's pipeline // views, for a credential holding // the "read" scope (#14373) +// GET /api//fleet/credentials owner: per-agent credential +// state (active / revoked, scopes; +// never a hash) (#14374) +// GET /fleet//pipeline|directory|credentials the +// unified pipeline feed, the +// unified agents list and the +// credential state, for a +// credential holding the "read" +// scope (#14374) // POST /api//notes-tokens/revoke owner: revoke an identity's // notes token(s) // POST /notes/register owner Bearer token; registers a diff --git a/pkgs/message-bridge/worker/test/console-views.test.mjs b/pkgs/message-bridge/worker/test/console-views.test.mjs new file mode 100644 index 0000000000..875750708c --- /dev/null +++ b/pkgs/message-bridge/worker/test/console-views.test.mjs @@ -0,0 +1,261 @@ +// The console's bridge views (src/fleet.js, #14374, design §4.9): the +// PM console's Messages and Agents surfaces read the unified pipeline, +// the unified agents list and per-agent credential state through the +// PM stack's service credential (the "read" scope, #14373), and the +// owner reads credential state at his own address. Oracles: a +// read-scope credential sees the pipeline with real senders (an +// agent-to-agent command names its agent sender), the directory marks +// a notes-only identity with no invented presence, credential state +// flips to revoked when the owner revokes and the list reflects it, +// no hash ever appears in a state row, and none of these views open +// to a credential without the read scope, to the shared fleet token, +// or to a revoke attempted at the credential address (revoking stays +// the owner's). Harness as in pipeline.test.mjs / +// service-credential.test.mjs: real fleetOp SQL on node:sqlite, +// MemoryStore for the rest. All token values are fixtures or values +// the Worker itself generated inside the test. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { DatabaseSync } from "node:sqlite"; +import { + fleetCall, + fleetCredentialPutSql, + fleetCredentialRevokeSql, + fleetCredentialStateSql, + 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 DREW = "d".repeat(40); +const FELIX = "f".repeat(40); +const ARCHER = "a".repeat(40); +const SCOUT = "s".repeat(40); +const env = { ACCESS_TOKEN: TOKEN, MCP_TOKENS: JSON.stringify({ claude: "l".repeat(40), chatgpt: "c".repeat(40) }) }; +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 clock = 0; + const stub = { fleet: (op, args) => fleetOp(sql, op, args, `2026-11-24T00:00:${String(clock++).padStart(2, "0")}Z`) }; + const store = new MemoryStore(() => "2026-11-24T00:00:00.000Z"); + store.fleet = (op, args) => fleetCall(stub, op, args); + const call = (path, init) => route(new Request(BASE + path, init), env, () => store); + const post = (path, body, headers = {}) => + call(path, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) }); + const bearer = (token) => ({ authorization: `Bearer ${token}` }); + const ft = await fleetToken(env); + const as = (cred) => ({ + pipeline: (qs = {}) => call(`/fleet/${cred}/pipeline?${new URLSearchParams(qs)}`), + directory: () => call(`/fleet/${cred}/directory`), + credentials: () => call(`/fleet/${cred}/credentials`), + post: (what, body) => post(`/fleet/${cred}/${what}`, body), + }); + return { + store, + call, + ft, + as, + register: (identity, token, extra = {}) => post("/notes/register", { identity, token, ...extra }, bearer(TOKEN)), + noteSend: (token, to, note) => post("/notes/send", { to, note }, bearer(token)), + fleetHello: (body) => post(`/fleet/${ft}/hello`, body), + fleetSend: (body) => post(`/fleet/${ft}/send`, body), + ownerSend: (body) => post(`/api/${TOKEN}/messages`, body), + mintCred: (body) => post(`/api/${TOKEN}/fleet/credentials/mint`, body), + revokeCred: (body) => post(`/api/${TOKEN}/fleet/credentials/revoke`, body), + ownerCredentials: () => call(`/api/${TOKEN}/fleet/credentials`), + }; +} + +/** Mints the PM stack's service credential; returns its value. */ +async function mintPm(h) { + const res = await h.mintCred({ agent: "pm-stack", addr: "service:pm-stack" }); + assert.equal(res.status, 201); + return (await res.json()).credential; +} + +/** + * Rows on all three surfaces, plus credentials standing: + * - felix and archer registered on fleet (hello) and notes; scout on + * notes only + * - a fleet command from felix to archer (agent-to-agent) + * - a connector instruction Drew sent to Claude + * - a note from Drew to muse/felix + * - a directly minted agent credential for felix (inbox + send) + */ +async function seeded() { + const h = await harness(); + await h.register("user/drew", DREW); + await h.register("muse/felix", FELIX); + await h.register("muse/archer", ARCHER); + await h.register("muse/scout", SCOUT); + await h.fleetHello({ agent: "felix", groups: ["muse"] }); + await h.fleetHello({ agent: "archer", groups: ["muse"] }); + + const sent = await h.fleetSend({ agent: "felix", body: "archer, do the thing", to: "agent:archer", kind: "command" }); + assert.equal(sent.status, 201, await sent.text().catch(() => "")); + await h.ownerSend({ body: "owner instruction body", sender: "drew", to: "claude", kind: "instruction" }); + await h.noteSend(DREW, "muse/felix", "note for felix"); + + const mint = await h.mintCred({ agent: "felix" }); + assert.equal(mint.status, 201); + const felixCred = (await mint.json()).credential; + const pm = await mintPm(h); + return { ...h, felixCred, pm }; +} + +test("read scope: the pipeline through the PM credential shows every surface with its real sender", async () => { + const h = await seeded(); + const res = await h.as(h.pm).pipeline({ limit: "200" }); + assert.equal(res.status, 200); + const { messages } = await res.json(); + const byBody = new Map(messages.map((m) => [m.body, m])); + + const cmd = byBody.get("archer, do the thing"); + assert.equal(cmd.surface, "fleet"); + assert.equal(cmd.kind, "command"); + assert.equal(cmd.sender_addr, "agent:felix", "an agent-sent command names its real sender to the owner"); + assert.equal(cmd.receiver, "agent:archer"); + + const ins = byBody.get("owner instruction body"); + assert.equal(ins.surface, "connector"); + assert.equal(ins.kind, "instruction"); + assert.equal(ins.sender_addr, "user:drew"); + + const note = byBody.get("note for felix"); + assert.equal(note.surface, "notes"); + // A note's sender is its notes identity (user/drew), where a + // connector row spells the same person user:drew: each surface's + // own address, as the pipeline normalizes them. + assert.equal(note.sender_addr, "user/drew"); + assert.equal(note.receiver, "muse/felix"); + + // The same filters the console offers narrow it the same way. + const only = await (await h.as(h.pm).pipeline({ sender: "felix", limit: "200" })).json(); + assert.ok(only.messages.length > 0); + assert.ok(only.messages.every((m) => m.sender_addr === "agent:felix" || m.sender_addr === "muse/felix")); +}); + +test("read scope: the directory unifies the surfaces and invents no presence for notes", async () => { + const h = await seeded(); + const res = await h.as(h.pm).directory(); + assert.equal(res.status, 200); + const { agents } = await res.json(); + + const scout = agents.filter((a) => a.name === "muse/scout"); + assert.equal(scout.length, 1, "a notes-only identity appears once"); + assert.equal(scout[0].surface, "notes"); + assert.equal(scout[0].presence, "none"); + assert.equal(scout[0].last_seen, null); + + const felix = agents.filter((a) => a.name === "felix" || a.name === "muse/felix"); + assert.deepEqual( + felix.map((a) => a.surface).sort(), + ["fleet", "notes"], + "an agent on both surfaces has a row for each", + ); + const fleetFelix = felix.find((a) => a.surface === "fleet"); + assert.deepEqual(fleetFelix.groups, ["muse"]); + assert.equal(fleetFelix.presence, "last_seen"); +}); + +test("credential state: the owner and the read scope see active, then revoked after the owner revokes", async () => { + const h = await seeded(); + + const before = await (await h.ownerCredentials()).json(); + const felix = before.credentials.find((c) => c.agent === "felix"); + assert.equal(felix.state, "active"); + assert.deepEqual(felix.scopes.sort(), ["inbox", "send"]); + const pmRow = before.credentials.find((c) => c.agent === "pm-stack"); + assert.equal(pmRow.state, "active"); + assert.equal(pmRow.addr, "service:pm-stack"); + assert.deepEqual(pmRow.scopes.sort(), ["read", "send"]); + // State only: no hash, no value, in either view. + for (const view of [before, await (await h.as(h.pm).credentials()).json()]) { + const text = JSON.stringify(view); + assert.ok(!/token_hash|credential"/.test(text.replace(/"credentials"/g, "")), "no hash or value in the state view"); + assert.deepEqual(view.credentials.find((c) => c.agent === "felix").state, "active"); + } + + const revoked = await h.revokeCred({ agent: "felix" }); + assert.equal(revoked.status, 200); + assert.equal((await revoked.json()).revoked, 1); + + const after = await (await h.as(h.pm).credentials()).json(); + const gone = after.credentials.find((c) => c.agent === "felix"); + assert.equal(gone.state, "revoked"); + assert.ok(gone.revoked_at, "the revocation time is shown"); + assert.deepEqual(gone.scopes, [], "a revoked agent carries no live scopes"); + // And the revoked credential itself is turned away everywhere. + assert.equal((await h.as(h.felixCred).credentials()).status, 404); +}); + +test("no read scope, no views: an agent credential and the shared fleet token are turned away", async () => { + const h = await seeded(); + for (const cred of [h.felixCred, h.ft]) { + assert.equal((await h.as(cred).pipeline()).status, 404); + assert.equal((await h.as(cred).directory()).status, 404); + assert.equal((await h.as(cred).credentials()).status, 404); + } + // A wrong token is the same plain 404. + assert.equal((await h.as("x".repeat(43)).pipeline()).status, 404); +}); + +test("a service credential can read state but never revoke: revoking stays the owner's route", async () => { + const h = await seeded(); + // POST at the credential address is refused as a method, and there + // is no revoke verb at that address at all. + const post = await h.call(`/fleet/${h.pm}/credentials`, { method: "POST" }); + assert.equal(post.status, 405); + assert.equal((await h.as(h.pm).post("revoke", { agent: "felix" })).status, 404); + // The owner's state is untouched by the attempts. + const state = await (await h.ownerCredentials()).json(); + assert.equal(state.credentials.find((c) => c.agent === "felix").state, "active"); +}); + +test("sql: credential state folds live and revoked rows per agent, hashes never read out", async () => { + const sql = sqlite(); + fleetSchema(sql); + const store = { + fleetCredentialPut: (rec) => fleetCredentialPutSql(sql, rec), + }; + const one = await noteTokenHash("fixture-one"); + const two = await noteTokenHash("fixture-two"); + store.fleetCredentialPut({ token_hash: one, agent: "felix", scopes: ["inbox", "send"], created: "2026-11-24T00:00:00Z", addr: null }); + store.fleetCredentialPut({ token_hash: two, agent: "felix", scopes: ["inbox"], created: "2026-11-24T01:00:00Z", addr: null }); + + let state = fleetCredentialStateSql(sql); + assert.equal(state.length, 1); + assert.equal(state[0].state, "active"); + assert.equal(state[0].credentials, 2); + assert.equal(state[0].live, 2); + assert.deepEqual(state[0].scopes.sort(), ["inbox", "send"]); + assert.ok(!("token_hash" in state[0])); + + // Revoking one of two leaves the agent active; both, revoked. + sql.exec("UPDATE fleet_credential SET revoked_at = ? WHERE token_hash = ?", "2026-11-24T02:00:00Z", one); + state = fleetCredentialStateSql(sql); + assert.equal(state[0].state, "active"); + assert.equal(state[0].revoked_at, null, "a part-revoked agent says no revocation time"); + assert.equal(fleetCredentialRevokeSql(sql, "felix", "2026-11-24T03:00:00Z"), 1); + state = fleetCredentialStateSql(sql); + assert.equal(state[0].state, "revoked"); + assert.equal(state[0].revoked_at, "2026-11-24T03:00:00Z"); + assert.deepEqual(state[0].scopes, []); +}); diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index 97f93ee0bf..52f81e4971 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -24,7 +24,7 @@ owner does every day; everything else is under More. | Next | The queue in the order it will be claimed; move a task first, sooner or later; why tasks are blocked | | Needs me | Open questions (one tap to answer, undo for a few seconds), things only hands can do, reviews | | Ask | Say what you want in your own words (typed or dictated). It becomes an issue and a top-of-queue task in one pass | -| More | The plan (roadmaps, bugs, intake), queue by state, pull requests, ranked issues, agents, services, notifications, phones, releases, and the dashboard's pages | +| More | The plan (roadmaps, bugs, intake), queue by state, pull requests, ranked issues, agents, messages, services, notifications, phones, releases, and the dashboard's pages | The page never waits on a live fan-out. The server keeps three documents ready (`core`, `questions`, `ops`), each built from sections that are diff --git a/pm-stack/console/edge/src/direct.ts b/pm-stack/console/edge/src/direct.ts index 0d93a8cc73..08019a6f86 100644 --- a/pm-stack/console/edge/src/direct.ts +++ b/pm-stack/console/edge/src/direct.ts @@ -16,9 +16,10 @@ // into calls to the bridge Worker over its service binding, // presenting that credential, so a message the owner sends from the // app is delivered by the edge itself — as service:pm-stack, the -// bridge's name for the PM stack — and the agents list and message -// log are read there too. Without the credential and the binding, -// `fleet bridge` stays a machine's, exactly as before. +// bridge's name for the PM stack — and the agents list, the message +// log and the unified pipeline, directory and credential views +// (#14374) are read there too. Without the credential and the +// binding, `fleet bridge` stays a machine's, exactly as before. // // What stays a machine's: `fleet queue enqueue` (the fleet binary is // not here), `systemctl`, and anything that reads the dashboard or @@ -729,8 +730,13 @@ export const BRIDGE_AGENT = "pm-stack"; /** One `fleet bridge` call as a call to the bridge Worker over its * service binding, presenting the PM credential in the path (the * bridge's own way: /fleet//...). The verbs the console's - * classes use — send, agents, log — and no others: anything else is - * refused as a machine's, like every verb this side does not carry. + * classes use — send, agents, log, and the unified views pipeline, + * directory and credentials (#14374) — and no others: anything else + * is refused as a machine's, like every verb this side does not + * carry. `revoke` is deliberately not among them: the PM credential + * holds the read scope, and revoking is the owner's act through the + * owner token on a machine — the action is held for one instead + * (src/edge-proto.ts). * A failed call answers the way the fleet binary would: a non-zero * code with the reason on stderr. The bridge's plain 404 for a wrong * token is said plainly here — the credential unknown or revoked — @@ -769,6 +775,39 @@ async function bridgeCall( } const qs = query.toString(); path = `/fleet/${token}/messages${qs === "" ? "" : `?${qs}`}`; + } else if (what === "pipeline") { + // The unified owner feed (#14374): the same flag pairs as `log`, + // plus the pipeline's own filters and its --unread switch. + const query = new URLSearchParams(); + const names: Record = { + "--kind": "kind", + "--sender": "sender", + "--receiver": "receiver", + "--surface": "surface", + "--batch": "batch", + "--work-state": "work_state", + "--since-id": "since_id", + "--before-id": "before_id", + "--limit": "limit", + "--order": "order", + }; + for (let i = 0; i < rest.length; i++) { + if (rest[i] === "--unread") { + query.set("unread_only", "true"); + continue; + } + const name = names[rest[i]]; + if (!name || rest[i + 1] === undefined) throw new OpError(502, `fleet bridge pipeline: unexpected argument ${rest[i]}`); + query.set(name, rest[++i]); + } + const qs = query.toString(); + path = `/fleet/${token}/pipeline${qs === "" ? "" : `?${qs}`}`; + } else if (what === "directory") { + if (rest.length > 0) throw new OpError(502, "fleet bridge directory takes no arguments here"); + path = `/fleet/${token}/directory`; + } else if (what === "credentials") { + if (rest.length > 0) throw new OpError(502, "fleet bridge credentials takes no arguments here"); + path = `/fleet/${token}/credentials`; } else if (what === "send") { const to: string[] = []; let kind = "message"; diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index d164b926d2..cfa184d2da 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -2502,12 +2502,14 @@ export class Edge { } // What needs only GitHub, the queue store and the bridge is // read here, by the code a machine would read it with. The - // bridge's own read (the message log) is attempted only while - // this side holds the bridge credential: without it the log - // is a machine's to read, and the request goes to the host + // bridge's own reads (the message log, and the unified + // pipeline and directory, #14374) are attempted only while + // this side holds the bridge credential: without it they are + // a machine's to read, and the request goes to the host // below as it did before. const mine = this.mine(cfg); - if (mine && !(seg.length === 1 && seg[0] === "messages" && !this.bridgeReady())) { + const bridgeRead = seg.length === 1 && (seg[0] === "messages" || seg[0] === "pipeline" || seg[0] === "directory"); + if (mine && !(bridgeRead && !this.bridgeReady())) { const from = this.outwardN; let read: unknown; try { diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 78c2cbfe8a..d4dcf843fe 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -1665,6 +1665,7 @@ function viewMore() { tile("more/prs", "Pull requests", ops.prs ? `${ops.prs.filter((p) => !p.draft).length} ready of ${ops.prs.length}` : "open and ready to merge"), tile("more/issues", "Ranked issues", ops.priorities ? `${ops.priorities.issues.length} ranked` : "change what matters most"), tile("more/agents", "Agents", ops.agents ? `${ops.agents.length} registered` : "message one or all"), + tile("more/messages", "Messages", "every surface, who really sent what"), tile("more/services", "Services", ops.services ? `${ops.services.filter((u) => u.active === "failed").length} failed of ${ops.services.length}` : "start, stop, logs"), tile("more/notify", "Notifications", "choose what reaches this device"), tile("more/phone", "Phones", "the Android app and its home-screen widget"), @@ -3569,6 +3570,110 @@ function viewIssues() { ]; } +/** The Messages screen's filters, kept across draws (#14374). */ +let messageFilters = { kind: "", surface: "", sender: "", receiver: "", batch: "", work: "", unread: false }; + +/** + * Every message on every surface, with the sender it really came from + * (#14374, design §4.9). This is the owner's console: provenance here + * is complete — an instruction shows its true sender. (Anonymity is + * what agents see of an instruction, never this view.) Read-only: the + * composer is the Agents screen's, as before. + */ +async function viewMessages() { + const f = messageFilters; + const qs = new URLSearchParams({ limit: "100" }); + if (f.kind) qs.set("kind", f.kind); + if (f.surface) qs.set("surface", f.surface); + if (f.sender) qs.set("sender", f.sender); + if (f.receiver) qs.set("receiver", f.receiver); + if (f.batch) qs.set("batch", f.batch); + if (f.work) qs.set("work_state", f.work); + if (f.unread) qs.set("unread", "1"); + let rows = []; + let failed = ""; + try { + const got = await api(`pipeline?${qs}`); + if (Array.isArray(got)) rows = got; + } catch (error) { + failed = error.message; + } + const pick = (label, key, options) => + h( + "select", + { + class: "narrow", + "aria-label": label, + onchange: (e) => { + messageFilters[key] = e.target.value; + draw(); + }, + }, + h("option", { value: "" }, label), + options.map((o) => h("option", { value: o, selected: f[key] === o }, o)), + ); + const find = (label, key, placeholder) => + h("input", { + type: "search", + placeholder, + "aria-label": label, + value: f[key], + onchange: (e) => { + messageFilters[key] = e.target.value.trim(); + draw(); + }, + }); + const filters = card( + h( + "div", + { class: "row" }, + pick("Kind", "kind", ["message", "instruction", "command", "note"]), + pick("Surface", "surface", ["connector", "fleet", "notes"]), + find("Sender", "sender", "Sender"), + find("Receiver", "receiver", "Receiver"), + find("Batch", "batch", "Batch"), + find("Work state", "work", "Work state"), + h( + "label", + { class: "row check meta" }, + h("input", { + type: "checkbox", + checked: f.unread || undefined, + onchange: (e) => { + messageFilters.unread = e.target.checked; + draw(); + }, + }), + "Unread only", + ), + ), + ); + const row = (m) => { + const who = m.sender_label && m.sender_addr && m.sender_label !== m.sender_addr ? `${m.sender_label} (${m.sender_addr})` : (m.sender_addr ?? "—"); + const meta = [ + `${ago(m.ts)} · ${m.surface} · ${m.kind}`, + `${who} → ${m.receiver}`, + m.direction, + m.read_at ? `read ${ago(m.read_at)}` : "unread", + m.batch ? `batch ${m.batch}` : "", + m.reply_to != null ? `reply to #${m.reply_to}` : "", + m.work_state ? `work: ${m.work_state}${m.work_task_id ? ` (task ${m.work_task_id})` : ""}` : "", + ] + .filter(Boolean) + .join(" · "); + return card(h("p", { class: "meta" }, meta), h("p", {}, String(m.body ?? "").slice(0, 1200))); + }; + return [ + filters, + h("h2", {}, `Messages (${rows.length})`), + ...(failed + ? [empty(`The messages could not be read just now: ${failed}`)] + : rows.length + ? rows.map(row) + : [empty("No messages match. Loosen a filter to see more.")]), + ]; +} + async function viewAgents() { const agents = docs.ops?.agents || []; const to = h("select", { "aria-label": "To" }, h("option", { value: "all" }, "Everyone"), agents.map((a) => h("option", { value: `agent:${a.name}` }, a.name))); @@ -3603,13 +3708,75 @@ async function viewAgents() { } catch (error) { unread = error.message; } + // The roster is the bridge's unified directory (#14374): fleet + // registry rows and notes identities, each with its credential + // state. Where that read cannot be made (an older bridge, no + // credential), the fleet roster from the ops document still stands, + // and the screen says the credential state is not shown. + let directory = null; + try { + const got = await api("directory"); + if (Array.isArray(got)) directory = got; + } catch { + directory = null; + } + const roster = + directory ?? + agents.map((a) => ({ + surface: "fleet", + name: a.name, + groups: a.groups ?? [], + presence: "last_seen", + last_seen: a.last_seen ?? null, + unread: a.unread ?? (a.unread_commands ?? 0) + (a.unread_messages ?? 0), + unread_commands: a.unread_commands ?? 0, + unread_messages: a.unread_messages ?? 0, + credential: null, + })); + const agentCard = (a) => { + const cred = a.credential; + const credSaid = !cred + ? "credential state not shown" + : cred.state === "active" + ? `credentials active${cred.scopes?.length ? ` (${cred.scopes.join(", ")})` : ""}` + : "credentials revoked"; + const meta = + a.surface === "notes" + ? `notes only · no presence on this surface · ${credSaid}` + : `${(a.groups || []).join(", ")} · seen ${ago(a.last_seen) || "never"} · ${a.unread_commands ?? 0} commands and ${a.unread_messages ?? 0} messages unread · ${credSaid}`; + return card( + h("div", { class: "row" }, h("h3", {}, a.name), chip(a.surface, a.surface === "notes" ? "warn" : "good")), + h("p", { class: "meta" }, meta), + cred?.state === "active" + ? h( + "div", + { class: "row end" }, + h( + "button", + { + class: "small ghost", + onclick: async (e) => { + const yes = await ask({ + title: `Revoke ${a.name}'s ${a.surface === "notes" ? "notes tokens" : "bridge credentials"}?`, + text: "It is cut off from the bridge until it is given a new credential. This is the per-agent kill switch.", + okLabel: "Revoke", + danger: true, + }); + if (yes !== null) act("agent.revoke", { surface: a.surface, name: a.name }, `Revoked ${a.name}`, e.target); + }, + }, + "Revoke", + ), + ) + : null, + ); + }; return [ ...notices(docs.ops, ["agents"]), compose, - h("h2", {}, `Agents (${agents.length})`), - ...agents.map((a) => - card(h("h3", {}, a.name), h("p", { class: "meta" }, `${(a.groups || []).join(", ")} · seen ${ago(a.last_seen) || "never"} · ${a.unread_commands ?? 0} commands and ${a.unread_messages ?? 0} messages unread`)), - ), + h("h2", {}, `Agents (${roster.length})`), + directory === null ? empty("The unified directory could not be read just now; the fleet roster is shown, without credential state.") : null, + ...roster.map(agentCard), h("h2", {}, "Recent messages"), ...(recent.length ? recent.map((m) => card(h("p", { class: "meta" }, `${ago(m.ts)} · ${m.direction} · ${m.agent} · ${m.kind}`), h("p", {}, String(m.body ?? "").slice(0, 600)))) @@ -3696,6 +3863,7 @@ const VIEWS = { "more/prs": ["Pull requests", viewPrs, "ops"], "more/issues": ["Ranked issues", viewIssues, "ops"], "more/agents": ["Agents", viewAgents, "ops"], + "more/messages": ["Messages", viewMessages], "more/services": ["Services", viewServices, "ops"], "more/notify": ["Notifications", viewNotify], "more/phone": ["Phones", viewPhone], diff --git a/pm-stack/console/public/outbox.js b/pm-stack/console/public/outbox.js index 963803c282..1b0db82ecc 100644 --- a/pm-stack/console/public/outbox.js +++ b/pm-stack/console/public/outbox.js @@ -27,6 +27,8 @@ "issue.rank", "task.move", "message.send", + // A revocation done late is still the right act (#14374). + "agent.revoke", "intake.send", ]); /** Actions on something that may have changed by the time they are @@ -83,6 +85,11 @@ return of("pr", a.pr); case "unit.act": return of("unit", a.unit); + case "agent.revoke": { + const surface = typeof a.surface === "string" ? a.surface : ""; + const name = typeof a.name === "string" ? a.name : ""; + return surface === "" || name === "" ? null : `agent:${surface}:${name}`; + } default: return null; } @@ -140,6 +147,8 @@ return "Accept the recommended answers"; case "message.send": return `Message to ${Array.isArray(a.to) ? a.to.join(", ") : a.to}${quoted(a.text)}`; + case "agent.revoke": + return `Revoke ${a.name ?? "an agent"}'s ${a.surface === "notes" ? "notes tokens" : "bridge credentials"}`; case "unit.act": return `${a.action} ${a.unit}`; // The platform's own second half of something it filed itself: diff --git a/pm-stack/console/src/actions.ts b/pm-stack/console/src/actions.ts index 08002ade1d..d0ce024f63 100644 --- a/pm-stack/console/src/actions.ts +++ b/pm-stack/console/src/actions.ts @@ -211,6 +211,17 @@ export function actions( touch: [], audit: (a) => ({ to: a.to, command: a.command === true }), }, + // Revoke an agent's bridge credentials from the Agents screen + // (#14374): the per-agent kill switch. It changes no document + // section — the Agents screen reads the directory fresh — and it + // is held for a machine when asked at the edge: revoking is the + // owner's act through the owner token, never the edge's + // read-scope credential (edge-proto.ts). + "agent.revoke": { + run: (a) => ops.revokeCredential(a.surface, a.name), + touch: [], + audit: ids("surface", "name"), + }, }; } diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index d5d0bb8a51..e47cd81520 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -284,6 +284,12 @@ export const HOLDABLE = new Set([ "issue.rank", "task.move", "message.send", + // A revocation is the owner's kill switch (#14374): done late it is + // still the right act — a credential revoked an hour late is revoked, + // and one already revoked answers so — so it is held for a machine + // rather than refused while the laptop is away. The edge itself + // never revokes: its bridge credential holds the read scope only. + "agent.revoke", "prompt.enqueue", // What the owner says is never lost for want of a machine: it is // kept and filed when one is back (or filed here, when the edge can). @@ -322,6 +328,13 @@ export function subjectOf(kind: string, args: Record | null | u return of("questions", a.set); case "pr.merge": return of("pr", a.pr); + case "agent.revoke": { + // One agent's credentials on one surface: two revocations of + // the same agent keep the owner's order. + const surface = typeof a.surface === "string" ? a.surface : ""; + const name = typeof a.name === "string" ? a.name : ""; + return surface === "" || name === "" ? null : `agent:${surface}:${name}`; + } case "unit.act": return of("unit", a.unit); default: diff --git a/pm-stack/console/src/ops.ts b/pm-stack/console/src/ops.ts index 783e6c9178..31d3c0e350 100644 --- a/pm-stack/console/src/ops.ts +++ b/pm-stack/console/src/ops.ts @@ -534,6 +534,129 @@ export class Ops { return Array.isArray(log) ? log : []; } + /** + * The owner's unified pipeline (#14374, design §4.9): one feed over + * connector messages, fleet mailboxes and notes, read through + * `fleet bridge pipeline`. The owner's view is never sender-stripped + * — an instruction shows who really sent it here; anonymity is what + * agents see, never this console. Filters are the bridge's own + * (kind / sender / receiver / surface / batch / unread / work + * state); each value is validated here and travels as its own + * argument. (Named for the bridge's feed, not this class's own + * queue-store pipeline above.) + */ + async pipelineFeed(query: URLSearchParams) { + const argv = [this.cfg.fleetBin, "bridge", "pipeline", "--order", "desc"]; + const one = (param: string, flag: string, name: string, ok: RegExp) => { + const v = query.get(param); + if (v === null || v === "") return; + const value = text(v, name, 200); + if (!ok.test(value)) throw new OpError(400, `${name}: not a ${name}: ${JSON.stringify(value).slice(0, 80)}`); + argv.push(flag, value); + }; + one("kind", "--kind", "kind", /^(message|instruction|command|note)$/); + one("surface", "--surface", "surface", /^(connector|fleet|notes)$/); + one("sender", "--sender", "sender", /^[A-Za-z0-9][A-Za-z0-9@:._/-]{0,127}$/); + one("receiver", "--receiver", "receiver", /^[A-Za-z0-9][A-Za-z0-9@:._/-]{0,127}$/); + one("batch", "--batch", "batch", /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/); + one("work_state", "--work-state", "work state", /^[a-z][a-z0-9_-]{0,63}$/); + if (query.get("unread") === "1" || query.get("unread_only") === "true") argv.push("--unread"); + const limit = query.get("limit"); + argv.push("--limit", String(limit === null || limit === "" ? 100 : Math.min(id(limit, "limit"), 200))); + const rows = ( + JSON.parse(await this.must(argv)) as { messages?: unknown } | null + )?.messages; + return Array.isArray(rows) ? rows : []; + } + + /** Per-agent credential state on the bridge (#14374): active or + * revoked, the scopes the live credentials carry. State only — the + * bridge never returns a hash, and neither does this. */ + async credentials() { + const rows = ( + JSON.parse(await this.must([this.cfg.fleetBin, "bridge", "credentials"])) as { credentials?: unknown } | null + )?.credentials; + return Array.isArray(rows) ? (rows as Record[]) : []; + } + + /** + * The unified agents list for the Agents screen (#14374, design + * §4.9): the bridge's directory (`fleet bridge directory` — fleet + * registry rows and notes identities, each marked by surface) with + * each row's credential state merged in. A fleet row's state comes + * from the credential view under the agent's own name; a notes + * row's from its identity's token scopes — an identity whose tokens + * were revoked keeps its directory place with both scopes off, + * which is the revoked state the screen shows. Notes identities + * have no presence: the bridge says `presence: "none"` and this + * merge invents nothing. + */ + async directory() { + const [dir, creds] = await Promise.all([ + this.must([this.cfg.fleetBin, "bridge", "directory"]).then( + (out) => (JSON.parse(out) as { agents?: unknown } | null)?.agents, + ), + this.credentials().catch(() => [] as Record[]), + ]); + const rows = Array.isArray(dir) ? (dir as Record[]) : []; + const byAgent = new Map(creds.map((c) => [String(c.agent), c])); + return rows.map((row) => { + if (row.surface === "fleet") { + const c = byAgent.get(String(row.name)); + return { + ...row, + credential: c + ? { + state: c.state, + scopes: Array.isArray(c.scopes) ? c.scopes : [], + credentials: typeof c.credentials === "number" ? c.credentials : 0, + created: c.created ?? null, + revoked_at: c.revoked_at ?? null, + } + : null, + }; + } + const scopes = (row.scopes ?? {}) as { can_send?: unknown; can_inbox?: unknown }; + const live = scopes.can_send === true || scopes.can_inbox === true; + return { + ...row, + credential: { + state: live ? "active" : "revoked", + scopes: [ + ...(scopes.can_send === true ? ["send"] : []), + ...(scopes.can_inbox === true ? ["inbox"] : []), + ], + credentials: null, + created: row.first_seen ?? null, + revoked_at: null, + }, + }; + }); + } + + /** + * Revoke an agent's bridge credentials from the Agents screen + * (#14374): the owner's kill switch, per surface — a fleet agent's + * credentials, or a notes identity's tokens. Revoking is the + * owner's act: on the laptop it runs here; at the edge the action + * is held for a machine (edge-proto.ts), never performed by the + * edge's read-scope credential. + */ + async revokeCredential(surface: unknown, name: unknown) { + const s = text(surface, "surface", 20); + if (s !== "fleet" && s !== "notes") throw new OpError(400, `surface: not a surface: ${JSON.stringify(s)}`); + const n = text(name, "name", 200); + if (!/^[A-Za-z0-9][A-Za-z0-9@._/-]{0,127}$/.test(n)) { + throw new OpError(400, `name: not an agent name: ${JSON.stringify(n).slice(0, 80)}`); + } + const argv = + s === "fleet" + ? [this.cfg.fleetBin, "bridge", "revoke", "--agent", n] + : [this.cfg.fleetBin, "bridge", "revoke", "--identity", n]; + const out = JSON.parse(await this.must(argv)) as { revoked?: unknown }; + return { surface: s, name: n, revoked: typeof out.revoked === "number" ? out.revoked : 0 }; + } + /** Send a message or a command to agents, groups, or everyone. */ async send(to: unknown, body: unknown, command: unknown) { if (!Array.isArray(to) || to.length === 0 || to.length > 50) throw new OpError(400, "to: one to fifty targets"); diff --git a/pm-stack/console/src/reads.ts b/pm-stack/console/src/reads.ts index 9eb674d8cf..d2d9f8adc9 100644 --- a/pm-stack/console/src/reads.ts +++ b/pm-stack/console/src/reads.ts @@ -52,6 +52,15 @@ export async function platformRead( // edge/src/direct.ts reads it the same way.) case "messages": return ops.messages(query.get("limit")); + // The unified owner pipeline and the unified agents list + // (#14374). Same story as `messages`: at the edge these are + // read through the PM bridge credential (edge/src/direct.ts + // translates the bridge argv); on a machine the server's switch + // may answer first, and either way the Ops call is the same. + case "pipeline": + return ops.pipelineFeed(query); + case "directory": + return ops.directory(); case "trends": return trends ? trends.read(query.get("days"), fresh, query.get("end")) : undefined; } diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts index 041b0e5490..d4bacaeb2b 100644 --- a/pm-stack/console/test/console.test.ts +++ b/pm-stack/console/test/console.test.ts @@ -742,6 +742,92 @@ describe("operations", () => { expect(r.calls.length).toBe(2); }); + test("the pipeline read carries the owner's filters as the bridge's own flags, and checks them first", async () => { + const rows = [{ surface: "fleet", kind: "command", sender_addr: "agent:felix", receiver: "agent:archer", body: "do it" }]; + const r = recorder(() => JSON.stringify({ messages: rows })); + const ops = new Ops(CFG, r.run); + const got = await ops.pipelineFeed( + new URLSearchParams({ kind: "command", sender: "felix", surface: "fleet", unread: "1", limit: "25" }), + ); + expect(got).toEqual(rows); + expect(r.calls[0].argv).toEqual([ + "fleet", "bridge", "pipeline", "--order", "desc", + "--kind", "command", "--surface", "fleet", "--sender", "felix", "--unread", "--limit", "25", + ]); + // A filter the bridge has no such value for is refused here, and + // nothing is run for it. + await expect(ops.pipelineFeed(new URLSearchParams({ kind: "shout" }))).rejects.toThrow(OpError); + await expect(ops.pipelineFeed(new URLSearchParams({ surface: "smoke-signal" }))).rejects.toThrow(OpError); + await expect(ops.pipelineFeed(new URLSearchParams({ sender: "a b" }))).rejects.toThrow(OpError); + expect(r.calls.length).toBe(1); + }); + + test("the directory merges credential state in, and a revocation shows on the next read", async () => { + // The bridge's answers, as they stand: felix's credential live. + let credentialState = [ + { agent: "felix", state: "active", scopes: ["inbox", "send"], addr: null, credentials: 1, live: 1, created: "2026-11-24T00:00:00Z", revoked_at: null }, + ]; + const r = recorder((argv) => { + if (argv[2] === "directory") { + return JSON.stringify({ + agents: [ + { surface: "fleet", name: "felix", groups: ["muse"], presence: "last_seen", last_seen: "2026-11-24T01:00:00Z", unread: 3 }, + { surface: "notes", name: "muse/scout", identity: "muse/scout", scopes: { can_send: true, can_inbox: false }, presence: "none", first_seen: "2026-11-24T00:00:00Z", last_seen: null }, + ], + }); + } + if (argv[2] === "credentials") return JSON.stringify({ credentials: credentialState }); + if (argv[2] === "revoke") return JSON.stringify({ ok: true, revoked: 1 }); + return ""; + }); + const ops = new Ops(CFG, r.run); + const before = (await ops.directory()) as { + name: string; + presence: string; + last_seen: string | null; + credential: { state: string; scopes: string[] } | null; + }[]; + const felix = before.find((a) => a.name === "felix"); + expect(felix?.credential).toEqual({ + state: "active", + scopes: ["inbox", "send"], + credentials: 1, + created: "2026-11-24T00:00:00Z", + revoked_at: null, + }); + // A notes-only identity is in the list, marked notes-only: no + // presence is invented for it, and its live token scopes are its + // credential state. + const scout = before.find((a) => a.name === "muse/scout"); + expect(scout?.presence).toBe("none"); + expect(scout?.last_seen).toBeNull(); + expect(scout?.credential?.state).toBe("active"); + expect(scout?.credential?.scopes).toEqual(["send"]); + + // The revoke action runs the bridge's own verb, audits only the + // surface and the name, and the next directory read shows it. + const table = actions(ops, {} as never); + expect(table["agent.revoke"].audit({ surface: "fleet", name: "felix", secret: "x" })).toEqual({ + surface: "fleet", + name: "felix", + }); + const done = (await table["agent.revoke"].run({ surface: "fleet", name: "felix" })) as { revoked: number }; + expect(done.revoked).toBe(1); + expect(r.calls.at(-1)?.argv).toEqual(["fleet", "bridge", "revoke", "--agent", "felix"]); + credentialState = [ + { agent: "felix", state: "revoked", scopes: [], addr: null, credentials: 1, live: 0, created: "2026-11-24T00:00:00Z", revoked_at: "2026-11-24T02:00:00Z" }, + ]; + const after = (await ops.directory()) as { name: string; credential: { state: string } | null }[]; + expect(after.find((a) => a.name === "felix")?.credential?.state).toBe("revoked"); + // A notes identity is revoked by its identity, and a surface that + // is neither is refused before anything runs. + await table["agent.revoke"].run({ surface: "notes", name: "muse/scout" }); + expect(r.calls.at(-1)?.argv).toEqual(["fleet", "bridge", "revoke", "--identity", "muse/scout"]); + const calls = r.calls.length; + await expect(table["agent.revoke"].run({ surface: "smoke-signal", name: "felix" })).rejects.toThrow(OpError); + expect(r.calls.length).toBe(calls); + }); + test("ranking an issue adds the new rank before it removes the others", async () => { const r = recorder((argv) => argv.includes("repos/developing-today/code/issues/12279") diff --git a/pm-stack/console/test/direct.test.ts b/pm-stack/console/test/direct.test.ts index 6eae7fce16..bc085c3c53 100644 --- a/pm-stack/console/test/direct.test.ts +++ b/pm-stack/console/test/direct.test.ts @@ -279,6 +279,93 @@ describe("the edge's run: the bridge through its binding", () => { expect(h.calls[2].url).toBe("https://bridge.internal/fleet/pm-cred-test/messages?limit=5&order=desc"); }); + test("the unified views are reads of the same binding; a revoke is a machine's", async () => { + const h = bridgeHarness(); + h.answer.status = 200; + h.answer.body = { messages: [{ id: 1, surface: "fleet", sender_addr: "agent:felix-1" }] }; + const feed = await h.run([ + "fleet", "bridge", "pipeline", + "--kind", "command", "--sender", "felix-1", "--unread", "--limit", "25", "--order", "desc", + ]); + expect(h.calls[0].url).toBe( + "https://bridge.internal/fleet/pm-cred-test/pipeline?kind=command&sender=felix-1&unread_only=true&limit=25&order=desc", + ); + expect(JSON.parse(feed.stdout)).toEqual({ messages: [{ id: 1, surface: "fleet", sender_addr: "agent:felix-1" }] }); + await h.run(["fleet", "bridge", "directory"]); + expect(h.calls[1].url).toBe("https://bridge.internal/fleet/pm-cred-test/directory"); + await h.run(["fleet", "bridge", "credentials"]); + expect(h.calls[2].url).toBe("https://bridge.internal/fleet/pm-cred-test/credentials"); + expect(h.seen).toEqual([ + { to: "bridge", write: false, status: 200 }, + { to: "bridge", write: false, status: 200 }, + { to: "bridge", write: false, status: 200 }, + ]); + // Revoking is the owner's act through the owner token: the edge's + // read-scope credential never carries it, so the verb is refused + // here and the action is held for a machine instead. + await expect(h.run(["fleet", "bridge", "revoke", "--agent", "felix-1"])).rejects.toThrow(/needs a machine/); + await expect(h.run(["fleet", "bridge", "revoke", "--identity", "muse/felix-1"])).rejects.toThrow(/needs a machine/); + expect(h.calls).toHaveLength(3); + }); + + test("the classes read the pipeline and the merged directory through the bridge, and cannot revoke there", async () => { + // A bridge that answers each of the unified views with its own rows. + const byPath = (url: string) => { + if (url.includes("/pipeline")) { + return { + messages: [ + { surface: "connector", id: 1, kind: "instruction", sender_addr: "user:drew", receiver: "claude", body: "owner instruction" }, + { surface: "fleet", id: 2, kind: "command", sender_addr: "agent:felix-1", receiver: "agent:archer-1", body: "agent command" }, + { surface: "notes", id: 3, kind: "note", sender_addr: "user:drew", receiver: "muse/felix-1", body: "a note" }, + ], + }; + } + if (url.endsWith("/directory")) { + return { + agents: [ + { surface: "fleet", name: "felix-1", groups: ["muse"], presence: "last_seen", last_seen: "2026-11-24T01:00:00Z", unread: 2 }, + { surface: "notes", name: "muse/scout-1", identity: "muse/scout-1", scopes: { can_send: false, can_inbox: false }, presence: "none", last_seen: null }, + ], + }; + } + if (url.endsWith("/credentials")) { + return { + credentials: [ + { agent: "felix-1", state: "active", scopes: ["inbox", "send"], addr: null, credentials: 1, live: 1, created: "2026-11-24T00:00:00Z", revoked_at: null }, + ], + }; + } + throw new Error(`unexpected bridge fetch ${url}`); + }; + const bridgeFetch = (async (url: string) => ({ ok: true, status: 200, json: async () => byPath(String(url)) })) as unknown as Fetch; + const { ops } = directClasses(edgeConfig, { + githubToken: "gh-test", + queueToken: "queue-test", + bridgeToken: "pm-cred-test", + bridgeFetch, + } as never); + // The pipeline: rows from all three surfaces, real senders kept. + const feed = (await ops.pipelineFeed(new URLSearchParams({ kind: "command" }))) as { sender_addr: string }[]; + expect(feed.map((m) => m.sender_addr)).toEqual(["user:drew", "agent:felix-1", "user:drew"]); + // The directory: the fleet row carries its credential state; the + // notes-only identity is present, presence none, and its revoked + // tokens read as a revoked credential. + const directory = (await ops.directory()) as { + name: string; + presence: string; + last_seen: string | null; + credential: { state: string } | null; + }[]; + const felix = directory.find((a) => a.name === "felix-1"); + expect(felix?.credential?.state).toBe("active"); + const scout = directory.find((a) => a.name === "muse/scout-1"); + expect(scout?.presence).toBe("none"); + expect(scout?.last_seen).toBeNull(); + expect(scout?.credential?.state).toBe("revoked"); + // And a revoke asked of the edge's classes is a machine's. + await expect(ops.revokeCredential("fleet", "felix-1")).rejects.toThrow(/needs a machine/); + }); + test("the agents section is read by the class that reads it on the laptop", async () => { const ops = { agents: async () => [{ name: "felix-1" }] }; expect(await directRead("agents", ops as never, {} as never)).toEqual([{ name: "felix-1" }]); diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index cf008d8b3f..1bfec2cd39 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -677,6 +677,21 @@ async function setup(options: { direct?: boolean; kinds?: readonly string[]; bri const bridgeLog = [ { id: 3, agent: "lane-1", direction: "inbound", kind: "message", sender: "service:pm-stack", body: "earlier" }, ]; + // The unified views the console's Messages and Agents screens read + // (#14374): one row per surface with its real sender, the unified + // directory (a notes-only identity included), and credential state. + const bridgePipeline = [ + { surface: "connector", id: 11, kind: "instruction", sender_addr: "user:drew", sender_label: "drew", receiver: "claude", direction: "inbound", read_at: null, body: "owner instruction" }, + { surface: "fleet", id: 12, kind: "command", sender_addr: "agent:lane-1", sender_label: "lane-1", receiver: "agent:lane-2", direction: "inbound", read_at: null, body: "agent command" }, + { surface: "notes", id: 13, kind: "note", sender_addr: "user:drew", sender_label: "drew", receiver: "muse/lane-1", direction: "inbound", read_at: null, body: "a note" }, + ]; + const bridgeDirectory = [ + { surface: "fleet", name: "lane-1", groups: ["muse"], presence: "last_seen", first_seen: "2026-11-24T00:00:00Z", last_seen: "2026-11-24T01:00:00Z", unread: 1 }, + { surface: "notes", name: "muse/scout-1", identity: "muse/scout-1", scopes: { can_send: true, can_inbox: true }, presence: "none", first_seen: "2026-11-24T00:00:00Z", last_seen: null }, + ]; + const bridgeCredentials = [ + { agent: "lane-1", state: "active", scopes: ["inbox", "send"], addr: null, credentials: 1, live: 1, created: "2026-11-24T00:00:00Z", revoked_at: null }, + ]; const bridgeRefuses = { on: false }; const bridgeFetch = (async ( url: string, @@ -695,6 +710,15 @@ async function setup(options: { direct?: boolean; kinds?: readonly string[]; bri if (method === "GET" && u.includes("/messages")) { return { ok: true, status: 200, json: async () => ({ messages: bridgeLog }) }; } + if (method === "GET" && u.includes("/pipeline")) { + return { ok: true, status: 200, json: async () => ({ messages: bridgePipeline }) }; + } + if (method === "GET" && u.endsWith("/directory")) { + return { ok: true, status: 200, json: async () => ({ agents: bridgeDirectory }) }; + } + if (method === "GET" && u.endsWith("/credentials")) { + return { ok: true, status: 200, json: async () => ({ credentials: bridgeCredentials }) }; + } throw new Error(`unexpected bridge fetch ${method} ${u}`); }) as never; /** The direct source, made to fail by a test that turns it on. */ @@ -3843,6 +3867,59 @@ describe("the edge does the core itself", () => { expect(w.hostSaw).not.toContain("GET /console/api/messages?limit=15"); }); + test("the unified pipeline and directory are read at the edge, and a revoke is held for a machine, never done here", async () => { + const w = await setup({ direct: true, bridge: true }); + await w.hostReads(); + await w.link.now.once(); + w.hostSaw.length = 0; + w.net.hostUp = false; + // The Messages screen's read: one feed over all three surfaces, + // the filters the owner chose carried to the bridge, and every + // row's real sender intact — an agent's command names the agent. + const feed = (await (await w.browse("/console/api/pipeline?kind=command&sender=lane-1")).json()) as { + surface: string; + sender_addr: string; + }[]; + expect(feed.map((m) => [m.surface, m.sender_addr])).toEqual([ + ["connector", "user:drew"], + ["fleet", "agent:lane-1"], + ["notes", "user:drew"], + ]); + // The Agents screen's read: the unified directory with credential + // state merged in — the fleet agent active, the notes-only + // identity present with no presence invented for it. + const directory = (await (await w.browse("/console/api/directory")).json()) as { + name: string; + surface: string; + presence: string; + last_seen: string | null; + credential: { state: string } | null; + }[]; + const lane = directory.find((a) => a.name === "lane-1"); + expect(lane?.credential?.state).toBe("active"); + const scout = directory.find((a) => a.name === "muse/scout-1"); + expect(scout?.surface).toBe("notes"); + expect(scout?.presence).toBe("none"); + expect(scout?.last_seen).toBeNull(); + expect(scout?.credential?.state).toBe("active"); + expect(w.bridgeCalls.map((c) => `${c.method} ${c.url}`)).toEqual([ + "GET https://bridge.internal/fleet/pm-cred-test/pipeline?order=desc&kind=command&sender=lane-1&limit=100", + "GET https://bridge.internal/fleet/pm-cred-test/directory", + "GET https://bridge.internal/fleet/pm-cred-test/credentials", + ]); + expect(w.hostSaw).not.toContain("GET /console/api/pipeline?kind=command&sender=lane-1"); + expect(w.hostSaw).not.toContain("GET /console/api/directory"); + // A revoke asked here is held for a machine — the edge's + // credential holds the read scope only — and the bridge is not + // asked for one. + const callsBefore = w.bridgeCalls.length; + const held = await w.act("agent.revoke", { surface: "fleet", name: "lane-1" }); + expect(await held.json()).toEqual({ ok: true, held: true, result: null, waits: "machine" }); + expect(w.bridgeCalls).toHaveLength(callsBefore); + const machines = (await (await w.browse("/console/api/machines")).json()) as MachinesAnswer; + expect(machines.held.map((entry) => entry.kind)).toEqual(["agent.revoke"]); + }); + test("a bridge credential the bridge no longer knows stops the send here, with the reason said", async () => { const w = await setup({ direct: true, bridge: true }); await w.hostReads(); diff --git a/pm-stack/platform/workers.json b/pm-stack/platform/workers.json index 20b35e0122..644bbd46cd 100644 --- a/pm-stack/platform/workers.json +++ b/pm-stack/platform/workers.json @@ -7,7 +7,7 @@ "title": "PM console", "group": "platform", "path": "pm-stack/console/edge", - "does": "Serves the PM app, does the core itself (the board, prompts, pull requests, ranked issues, the plan), sends messages to agents itself through the message bridge on a service binding (as service:pm-stack), and holds what waits for a machine.", + "does": "Serves the PM app, does the core itself (the board, prompts, pull requests, ranked issues, the plan), sends messages to agents itself through the message bridge on a service binding (as service:pm-stack), reads the bridge's unified message pipeline, agents directory and credential state there too, and holds what waits for a machine.", "state": "in service", "deploy": "actions", "workflow": "pm-console-edge-deploy.yml",