Skip to the page

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.

Each agent owns one step
Each worker reads only briefs at its assigned stage and can commit only that stage’s transition.
Work is handed on
As soon as one worker commits, the next stage’s live subscription receives the brief without polling.
A crash loses nothing
Pipeline state lives in rows, so a restarted worker immediately picks up briefs waiting at its stage.
A person decides
Only the human requester can mark a brief Approved or Rejected, and no agent policy allows it.

Your worker processes run the model calls while Napalm holds the shared board and enforces stage boundaries.

Before you start#

Email and password sign-in
Each agent signs in with a separate account. Turn on this sign-in with napalm sign-in set. If your project confirms addresses, give each agent a mailbox you can read once.
A service key
Use a service key to mark each account as a kind of agent. Set the branch’s service globals to { "default::role": "service" } so the rules see the service role.
Live queries
An agent learns of new work from a live query over one HTTPS connection the agent opens. Nothing has to reach the agent from outside.

Keep the work on one board#

Each Brief is a row whose stage field records whose turn comes next. 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 with per-worker identities

Researcher and Critic workers authenticate as separate ext::auth::Identity accounts over one Brief table, advancing rows from Queued to Researched to Critiqued before human sign-off.

dbschema/default.gel
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));   # A statement sent to the API can't name ext::auth's types, so the schema looks an identity up for it.  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 {    # Not required: a caller reads their own identity alone, and the service reads none.    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
Sees Queued briefs. Its update commits only when the brief transitions to Researched with a draft.
The critic
Sees Researched briefs and nothing earlier. Its update must leave the brief Critiqued with a critique.
The requester
Reads their own briefs at every stage. Only the requester can mark a brief Approved or Rejected.

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#

An agent is an ext::auth::Identity like any person’s. An Agent row names the agent’s kind, and the rules read that row through global agent. An identity with no Agent row is an ordinary account and gets nothing from the agents’ rules.

dbschema/queries/addAgent.edgeql
insert Agent {  identity := identity_by_id(<uuid>$identity),  kind := <AgentKind>$kind,}
Set up the critic
# Agents sign in with an email address and a password.napalm sign-in set research --email-password # Sign each agent up once (SignIn.signUp), then make its identity an agent of one kind.napalm query research --file dbschema/queries/addAgent.edgeql \  --var identity=0192c3f4-6b1a-7d8e-9f00-1a2b3c4d5e6f --var kind=Critic # What the critic can read and change now, counted per type:napalm people reach research critic@agents.example.com

The identity’s id is the identity_id from the sign-up answer. To retire an agent, delete the matching Agent row. The agent’s next statement finds nothing.

Hand work on with a live query#

Both agents subscribe to the same deployed query, which has no filter. The rules give the researcher the queued briefs and the critic the researched briefs.

dbschema/queries/briefsToTake.edgeql
select Brief { id, topic, draft }
agents/critic.ts
// 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>() // The whole result first, then each change: a critic that restarts finds what waited for it.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)}
dbschema/queries/submitDraft.edgeql
update Brieffilter .id = <uuid>$briefset {  stage := Stage.Researched,  draft := <str>$draft,}
dbschema/queries/submitCritique.edgeql
update Brieffilter .id = <uuid>$briefset {  stage := Stage.Critiqued,  critique := <str>$critique,}
At commit
When the researcher commits an update, the brief leaves the researcher’s view and enters the critic’s subscription on that exact commit.
After a crash
A subscription opens with the whole result. A critic that was down gets every brief still waiting.
Two critics
Two critics may both start on one brief. The first update moves the brief out of reach, and the second update changes nothing.

Leave the decision to a person#

Only the requester’s access policy matches a Critiqued brief and permits Approved or Rejected. No agent policy reaches Critiqued rows, so no agent can finalize a decision.

Stage transitions enforced by update read and update write rules

Compiled update read and update write locks verify both the prior stage and the resulting stage on every mutation, preventing agents from skipping stages or self-approving.

dbschema/queries/decideBrief.edgeql
update Brieffilter .id = <uuid>$briefset { stage := <Stage>$stage }

The requester’s app can follow a brief’s stage with a separate live query and show each step at commit. If approving a brief sets off writes to other data, preview the changes for the person first with a dry run.

Call another project’s agent#

An agent that needs facts from another project gets no login to that project’s database. Every project answers Agent-to-Agent calls at /a2a under that project’s own rules.

  1. Make a read-only key on the other project

    napalm keys create billing --read-only --label research-pipeline. Hide the queries agents should not call with napalm queries offer billing internalFix --no-agents.

  2. Read the key’s agent card

    GetExtendedAgentCard lists the deployed queries and actions the key can call, with descriptions and variables.

  3. Call a query

    agents/researcher.ts
    // One call to the billing project's agent, with a read-only key of that project.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#

Your terminal
# What each agent can reach, counted per type against the rules.napalm people reach research researcher@agents.example.comnapalm people reach research critic@agents.example.com

The critic’s count shows only researched Brief rows to read and update, and no rows to delete. Once a brief is critiqued, sign in as the critic and try to approve the brief. The update finds no rows, because no rule of the critic’s reaches a critiqued brief.

Type a word or two to search every docs page.