Every app in the TAP ecosystem gets its own agent. But there's no delegation primitive: a main agent can't spawn sub-agents with scoped permissions. Without delegation, every sub-agent would need its own key and its own card step — which doesn't scale to multi-agent workflows.

The Agent Delegation Broker is a small runnable reference that closes that gap. A main agent mints a signed, policy-bound token for a sub-agent; the broker verifies the signature, enforces the policy on each request, revokes on demand, and keeps an audit trail. I also built an interactive browser demo so the flow is visible rather than abstract, and fixed an ESM/CJS interop bug along the way that's worth documenting for anyone shipping tweetnacl-util on Node 22.

Status: MVP, not production. Keys are in-memory, no auth, no replay protection. See the roadmap at the end.

| Layer | Technology | Reason | |---|---|---| | Runtime | Node.js 22 | LTS, native crypto.randomUUID | | Language | TypeScript 5.5 (strict, NodeNext ESM) | Type-safe service layer | | HTTP | Hono 4 + @hono/node-server | Tiny, fast, serveStatic for the demo | | Crypto | tweetnacl (Ed25519) + tweetnacl-util | Small, audited base64 + signing helpers | | Tooling | tsx, Vitest, ESLint, drizzle-kit | Hot reload, tests, lint, migrations | | Extras installed | Zod, pino, Drizzle + postgres.js | Ready to wire in later | | Demo | Vanilla HTML/CSS/JS | No build step, same-origin | | Packaging | Multi-stage Docker ( node:22-alpine ) | Slim runtime with dist/ +demo/ |

Deliberate choice: no database. Three in-memory Map s (tokens, audits) remove all setup friction for a reference. src/db.ts is scaffolding for the day persistence is needed.

┌─────────────────────┐      fetch() JSON       ┌──────────────────────────────┐
│  Browser (demo UI)  │ ───────────────────────► │  Hono app (src/server.ts)    │
│  demo/index.html    │ ◄─────────────────────── │  REST routes + serveStatic   │
└─────────────────────┘      JSON responses      └──────────────┬───────────────┘
                                                                 │ imports
                                                                 ▼
                                                  ┌──────────────────────────────┐
                                                  │ Service layer                │
                                                  │ src/services/delegation.ts   │
                                                  │ Ed25519 sign/verify, Maps,   │
                                                  │ policy logic, audit log      │
                                                  └──────────────┬───────────────┘
                                                                 ▼
                                                  ┌──────────────────────────────┐
                                                  │ tweetnacl / tweetnacl-util   │
                                                  │ Types (src/types.ts)         │
                                                  └──────────────────────────────┘

Lifecycle:

Main agent                Broker routes                Service layer (Maps)
     │                         │                              │
     │── POST /delegate ──────►│                              │
     │                         │── mintToken() ──────────────►│  sign(JSON(token))
     │◄── { token + signature }│◄─────────────────────────────│  tokens.set(id,…)
     │  Sub-agent presents token                              │  audits.push(mint)
     │── GET /verify/:id ─────►│── verifyToken() ────────────►│  verify(signature)
     │◄── { chain, verified } ─│◄─────────────────────────────│  audits.push(verify)
     │── POST /check ─────────►│── checkPolicy() ────────────►│  endpoint + spendCap
     │◄── { allowed } ─────────│◄─────────────────────────────│  audits.push(violation?)
     │── POST /revoke/:id ────►│── revokeToken() ────────────►│  revoked = true
     │◄── { revoked } ─────────│◄─────────────────────────────│  audits.push(revoke)

Three decisions worth calling out:

server.ts checks required fields and delegates. Business logic is testable over HTTP-free.services/delegation.ts, which owns the keypair and every sign/verify call. serveStatic serves demo/index.html from the same Hono process — no CORS, no second dev server.

// src/index.ts
import { serve } from '@hono/node-server'
import app from './server.js'

const PORT = Number(process.env.PORT) || 3000
serve({ fetch: app.fetch, port: PORT }, (info) => {
  console.log(`Agent Delegation Broker listening on :${info.port}`)
})
js
// src/server.ts (excerpt)
const app = new Hono()

app.use('/demo/*', serveStatic({ root: './' }))
app.get('/demo', serveStatic({ path: './demo/index.html' }))

app.post('/delegate', async (c: Context) => {
  const body = await c.req.json()
  const { mainAgentId, subAgentId, policy } = body
  if (!mainAgentId || !subAgentId || !policy) {
    return c.json({ code: 'invalid_request', detail: 'Missing …' }, 400)
  }
  const token = mintToken(mainAgentId, subAgentId, policy)
  return c.json({ token }, 201)
})

Small details like 201 Created and a 401 on invalid tokens make the API feel real to consumers and to the demo.

// src/services/delegation.ts (excerpt)
import nacl from 'tweetnacl'
import naclUtil from 'tweetnacl-util'

// tweetnacl-util is CommonJS (`export = util`); Node's ESM loader cannot
// provide named exports, so use the default (namespace) import instead.
const { encodeBase64, decodeBase64 } = naclUtil

const keyPair = nacl.sign.keyPair()

function signToken(token: Omit<DelegationToken, 'signature'>): string {
  const msgBytes = new TextEncoder().encode(JSON.stringify(token))
  return encodeBase64(nacl.sign.detached(msgBytes, keyPair.secretKey))
}

function verifyTokenSignature(token: DelegationToken): boolean {
  const { signature, ...rest } = token
  const msgBytes = new TextEncoder().encode(JSON.stringify(rest))
  return nacl.sign.detached.verify(msgBytes, decodeBase64(signature), keyPair.publicKey)
}

Because JSON.stringify preserves insertion order, signing the object without signature and verifying the same object with signature removed produces byte-identical messages.

Running npm run dev originally crashed:

SyntaxError: The requested module 'tweetnacl-util' does not provide
an export named 'decodeBase64'

Root cause: tweetnacl-util@0.15.1 is a CommonJS package whose .d.ts declares export = util — it exports a single object via module.exports. Node 22's ESM loader cannot statically detect named exports from that shape, so import { encodeBase64, decodeBase64 } fails at instantiation. The fix is a default import (Node supports that for CJS), then destructure:

import naclUtil from 'tweetnacl-util'
const { encodeBase64, decodeBase64 } = naclUtil

I applied the same default import to tweetnacl for consistency. TypeScript's esModuleInterop: true keeps both correctly typed. npm run build, npm run dev, and the compiled node dist/index.js all work after this change.

export function checkPolicy(tokenId: string, endpoint: string, amount: number) {
  const chain = verifyToken(tokenId)
  if (!chain) return { allowed: false, reason: 'Invalid or expired token' }
  const { policy } = chain

  if (policy.allowedEndpoints.length > 0 &&
      !policy.allowedEndpoints.includes(endpoint)) {
    return { allowed: false, reason: `Endpoint ${endpoint} not allowed` }
  }
  if (amount > policy.spendCap) {
    return { allowed: false, reason: `Amount ${amount} exceeds spend cap ${policy.spendCap}` }
  }
  return { allowed: true }
}

Note: rateLimitPerMinute is stored in the policy but not yet enforced — that's an open contribution.

// src/types.ts (excerpt)
export interface DelegationPolicy {
  spendCap: number
  allowedEndpoints: string[]
  ttlSeconds: number
  rateLimitPerMinute: number
}

export interface DelegationToken {
  id: string
  mainAgentId: string
  subAgentId: string
  policy: DelegationPolicy
  issuedAt: string
  expiresAt: string
  revoked: boolean
  signature: string
}

The browser page is the part that makes this project explainable in a screenshot. It calls the real API:

async function call(method, path, body) {
  const res = await fetch(base() + path, {
    method,
    headers: body ? { 'Content-Type': 'application/json' } : {},
    body: body ? JSON.stringify(body) : undefined,
  })
  const data = await res.json()
  setResp(method + ' ' + path, res.status, data, !res.ok)
  return { ok: res.ok, data }
}

Design: solid layered dark surfaces (no gradients), a translucent sticky header (backdrop-filter: saturate(180%) blur(20px)), iOS system colors (#0a84ff, #30d158, #ff453a, #bf5af2), size-specific type tracking, instant press feedback on :active, and proper reduced-motion / reduced-transparency / increased-contrast handling. The page shows a mint form, token card, step tracker, live JSON responses, audit trail, and the service public key — so someone can understand delegation in a minute without reading a single curl command.

The demo also makes the in-memory caveat visible: it notes that restarting the server changes the public key and clears all tokens.

npm install
npm run dev                      # http://localhost:3000
# or PORT=3100 npm run dev        → demo at http://127.0.0.1:3100/demo

npm run build && npm start
docker build -t agent-delegation-broker .
docker run -p 3000:3000 agent-delegation-broker

Try the lifecycle:

curl -X POST http://localhost:3000/delegate \
  -H 'Content-Type: application/json' \
  -d '{"mainAgentId":"main-1","subAgentId":"shopping-agent","policy":{"spendCap":100,"allowedEndpoints":["/pay"],"ttlSeconds":3600,"rateLimitPerMinute":30}}'

curl http://localhost:3000/verify/<tokenId>
curl -X POST http://localhost:3000/check \
  -H 'Content-Type: application/json' \
  -d '{"tokenId":"<tokenId>","endpoint":"/pay","amount":50}'
curl -X POST http://localhost:3000/revoke/<tokenId>
curl http://localhost:3000/audit

npm test currently exits 1 with "No test files found" — the first good contribution is a Vitest suite for the service layer.

rateLimitPerMinute (stored but unused).src/db.ts: persist tokens/audits and the signing key with Drizzle. kid in tokens; auth on /delegate and /revoke./check. MIT licensed and fork-friendly — if any of that sounds like a good first PR, go for it.

Code & more: https://www.dailybuild.xyz/project/333-agent-delegation-broker

原文来源:dev.to