Guides · Agents & copilots
Multi-agent pipelines
Coordinate multiple agents across stages of a shared board. Each agent signs in with scoped access to its own stage, and a person approves the final result.
- In the schema
ext::auth::Identity
What you’ll build#
You will coordinate a researcher agent and a critic agent over user-requested briefs across four database-enforced guarantees.
- Stage-scoped workers
- Each worker reads only briefs at its assigned stage and can commit only that stage’s transition.
- Live handoffs
- As soon as one worker commits, the next stage’s live subscription receives the brief without polling.
- Crash recovery
- Pipeline state lives in rows, so a restarted worker immediately picks up briefs waiting at its stage.
- Human sign-off
- Only the human requester can mark a brief
ApprovedorRejected, and no agent policy allows it.
Your worker processes run the model calls while Napalm holds the shared table and enforces stage boundaries.
Before you start#
- Email and password sign-in
- Each worker signs in with a dedicated account. Enable email-and-password sign-in with
napalm sign-in set. When email confirmation is enabled, assign each worker a mailbox you can verify once. - A service key
- Use a service key to assign each account an
Agentrole row. Configure the branch’s service globals as{ "default::role": "service" }so your schema policies recognize service calls. - Live queries
- Workers receive stage handoffs over outbound live query HTTPS streams without opening inbound ports.
Coordinate over a shared table#
Each Brief is a row whose stage field records the active pipeline step. Instead of passing ephemeral messages between processes, every worker reads and advances one shared table under stage-scoped policies, so crashes lose nothing and the requester can watch progress live.
Shared stage board
Separate worker identities advance brief rows stage by stage before human approval.
Declare the AgentKind and Stage enums alongside Agent and Brief so each worker’s policies bind directly to its role and current pipeline step:
using extension auth;using extension napalm;using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; global role: str; global agent := assert_single((select Agent filter .identity = global caller)); # Client queries cannot reference ext::auth types directly, so this helper resolves an Identity by UUID. function identity_by_id(target: uuid) -> optional ext::auth::Identity using (select ext::auth::Identity filter .id = target); scalar type AgentKind extending enum<Researcher, Critic>; scalar type Stage extending enum<Queued, Researched, Critiqued, Approved, Rejected>; type Agent { # Optional so service keys and other callers can read Agent without reading its Identity. identity: ext::auth::Identity { constraint exclusive; }; required kind: AgentKind; access policy service_has_full_access allow all using (global role ?= 'service'); access policy agent_reads_itself allow select using (.identity ?= global caller); } type Brief { required requester: ext::auth::Identity; required topic: str; required stage: Stage { default := Stage.Queued; }; draft: str; critique: str; access policy requester_can_read allow select using (.requester ?= global caller); access policy requester_can_ask allow insert using (.requester ?= global caller and .stage = Stage.Queued); access policy requester_decides_a_critiqued_brief allow update read using (.requester ?= global caller and .stage = Stage.Critiqued); access policy requester_approves_or_rejects allow update write using (.requester ?= global caller and .stage in {Stage.Approved, Stage.Rejected}); access policy researcher_takes_queued allow select, update read using ((global agent).kind ?= AgentKind.Researcher and .stage = Stage.Queued); access policy researcher_leaves_a_draft allow update write using ( (global agent).kind ?= AgentKind.Researcher and .stage = Stage.Researched and exists .draft ); access policy critic_takes_researched allow select, update read using ((global agent).kind ?= AgentKind.Critic and .stage = Stage.Researched); access policy critic_leaves_a_critique allow update write using ( (global agent).kind ?= AgentKind.Critic and .stage = Stage.Critiqued and exists .critique ); }}Each agent role combines two rules: update read selects the stage an agent may claim, and update write constrains the target state the row must reach on commit.
- The researcher
- Reads
Queuedbriefs. Its update commits only when the brief transitions toResearchedwith a draft. - The critic
- Reads
Researchedbriefs and nothing earlier. Its update must leave the briefCritiquedwith a critique. - The requester
- Reads their own briefs at every stage. Only the requester can mark a brief
ApprovedorRejected.
Even with a compromised prompt, a researcher cannot approve its own draft or read a brief held by the critic. PostgreSQL rejects out-of-stage writes inside the transaction.
Give each agent a separate sign-in#
Each worker authenticates as an ext::auth::Identity paired with an Agent row that records its role. Schema policies resolve that role through global agent, so an ordinary user account without an Agent row receives zero worker permissions:
insert Agent { identity := identity_by_id(<uuid>$identity), kind := <AgentKind>$kind,}Enable email-and-password sign-in, pass the identity_id returned at sign-up to addAgent and verify the worker’s row reach from your terminal:
# Enable email-and-password sign-in for worker accounts.napalm sign-in set research --email-password # Register each signed-up identity as a specific agent role.napalm query research --file dbschema/queries/addAgent.edgeql \ --var identity=0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f --var kind=Critic # Count accessible rows per type for the critic account.napalm people reach research critic@agents.example.comDeleting an Agent row retires that worker on its very next query.
Hand off stages with live queries#
Both workers subscribe to the same unfiltered briefsToTake query, while compiled select policies route Queued rows to the researcher and Researched rows to the critic:
select Brief { id, topic, draft }Each worker opens a live subscription under its own sign-in, tracks claimed IDs in memory and posts the stage output once the model call finishes:
// agents/critic.tsimport { NapalmClient, SignIn } from 'napalm-client'import { critiqueWithModel } from './model' // your model call type Brief = { id: string; topic: string; draft: string } const ADDRESS = 'https://research.napalmdata.com' const signIn = new SignIn(ADDRESS)await signIn.withPassword(process.env.CRITIC_EMAIL!, process.env.CRITIC_PASSWORD!)const napalm = new NapalmClient(ADDRESS, { signIn }) const taken = new Set<string>() // Initial snapshot followed by live deltas so a restarted worker picks up waiting briefs.napalm.subscribe<Brief, Record<string, never>>({ name: 'briefsToTake' }, {}, { onRows: ({ rows }) => { for (const brief of rows) { if (taken.has(brief.id)) continue taken.add(brief.id) void review(brief) } },}) async function review(brief: Brief) { const critique = await critiqueWithModel(brief.topic, brief.draft) const moved = await napalm.fetch(`${ADDRESS}/query/submitCritique`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ variables: { brief: brief.id, critique } }), }) if (!moved.ok) taken.delete(brief.id)}Single-purpose deployed queries advance each brief to its next stage, where update write policies verify both the target stage and its required output field:
update Brieffilter .id = <uuid>$briefset { stage := Stage.Researched, draft := <str>$draft,}The critic’s companion query transitions a Researched brief to Critiqued:
update Brieffilter .id = <uuid>$briefset { stage := Stage.Critiqued, critique := <str>$critique,}Live subscriptions and stage-scoped policies handle handoffs, restarts and races automatically:
- On commit
- When the researcher commits a draft, the brief leaves the researcher’s view and enters the critic’s live stream on that same commit.
- After a restart
- Opening a live subscription delivers the full current result set first, so a restarted critic immediately receives every waiting brief.
- Concurrent workers
- If two critics pick up the same brief, the first commit advances the stage and the second update matches zero rows.
Reserve final approval for a person#
Once the critic submits feedback, the brief enters Critiqued and leaves every worker’s reach. No agent policy matches Critiqued rows, so no agent can finalize a decision.
Human approval gate
Only the human requester’s policy permits final approval or rejection transitions.
Deploy decideBrief for your application UI so the signed-in requester can record Approved or Rejected:
update Brieffilter .id = <uuid>$briefset { stage := <Stage>$stage }The requester’s UI can subscribe to the brief’s stage with a live query to display progress as each worker commits. When approving a brief triggers broader mutations, preview the full diff first with a dry run.
Call another project over A2A#
When a worker needs records from another Napalm project, connect over Agent-to-Agent at /a2a instead of sharing database credentials. Each project evaluates incoming A2A calls under its own access policies.
Issue a read-only key on the peer project
Run
napalm keys create billing --read-only --label research-pipeline, and hide internal queries from agents withnapalm queries offer billing internalFix --no-agents.Inspect the caller-scoped agent card
GetExtendedAgentCardlists the deployed queries and actions that key may invoke along with their input schemas.Invoke the skill
agents/researcher.ts// Invoke a skill on the billing project's /a2a endpoint using a read-only key.const answer = await fetch('https://billing.napalmdata.com/a2a', { method: 'POST', headers: { Authorization: `Bearer ${process.env.BILLING_KEY}`, 'A2A-Version': '1.0', 'Content-Type': 'application/json', }, body: JSON.stringify({ jsonrpc: '2.0', id: crypto.randomUUID(), method: 'SendMessage', params: { message: { messageId: crypto.randomUUID(), role: 'ROLE_USER', parts: [{ data: { call: 'accountSummary', variables: { slug: 'acme' } } }], }, }, }),})const { result } = await answer.json()const rows = result.message.parts[0].data.data
Check each agent’s reach#
# Count accessible rows per type for each worker identity.napalm people reach research researcher@agents.example.comnapalm people reach research critic@agents.example.comThe critic’s reach count reports only Researched briefs for read and update, and zero rows for delete. Once a brief reaches Critiqued, attempting to approve it as the critic updates zero rows because no critic policy matches Critiqued briefs.