# Get the agent card
Source: https://docs.getbindu.com/api-reference/agent-discovery/get-the-agent-card
/openapi.yaml get /.well-known/agent.json
The A2A standard discovery document. Any client that knows the
agent's base URL can `GET` this to learn the agent's DID,
capabilities, published skills, and where to send requests.
# Root redirect to agent card
Source: https://docs.getbindu.com/api-reference/agent-discovery/root-redirect-to-agent-card
/openapi.yaml get /
A convenience: `GET /` returns `302 Found` pointing at the
agent card. Useful for humans browsing to the agent's base
URL — they end up at something meaningful instead of a 404.
# Resolve a DID (via JSON body)
Source: https://docs.getbindu.com/api-reference/did-resolution/resolve-a-did-via-json-body
/openapi.yaml post /did/resolve
Alternate form for clients that prefer POST (keeps the DID
out of URL logs). Returns the same document `GET` would.
# Liveness + readiness probe
Source: https://docs.getbindu.com/api-reference/health-&-monitoring/liveness-+-readiness-probe
/openapi.yaml get /health
Returns 200 when healthy, 503 when any mandatory dependency
(storage, scheduler, message bus, grpc) is degraded. The body
carries per-component status so orchestrators can show which
specific thing is broken.
# Prometheus metrics (text exposition)
Source: https://docs.getbindu.com/api-reference/health-&-monitoring/prometheus-metrics-text-exposition
/openapi.yaml get /metrics
Standard Prometheus text format. Key series include:
- `http_requests_total{method, path, status}` — request counts
- `http_request_duration_seconds` — latency histogram
- `agent_tasks_active` — count by state
- `agent_tasks_completed_total{state}` — lifetime terminal counts
- `agent_llm_tokens_total{direction, model}` — token usage
# Liveness and basic configuration probe.
Source: https://docs.getbindu.com/api-reference/health/liveness-and-basic-configuration-probe
/gateway-openapi.yaml get /health
Unauthenticated, cheap, returns immediately. Does NOT verify
downstream connectivity (Supabase, OpenRouter, Hydra) — it only
reports whether the gateway process has booted with the expected
config. Use this for container liveness checks; for readiness
probes that include downstream health, build a higher-level
check.
# The gateway's self-published DID document.
Source: https://docs.getbindu.com/api-reference/identity/the-gateways-self-published-did-document
/gateway-openapi.yaml get /.well-known/did.json
Returns a W3C DID Core v1-compatible document with the gateway's
Ed25519 public key under `authentication[]`. A2A peers that
accept `did_signed` requests fetch this to verify the gateway's
outbound signatures.
**Availability:** only registered when the gateway has a DID
identity configured via env — `BINDU_GATEWAY_DID_SEED`,
`BINDU_GATEWAY_AUTHOR`, and `BINDU_GATEWAY_NAME` all set. When no
identity is loaded this endpoint returns 404.
**Caching:** the gateway's DID is stable across process lifetime
(env-driven); responses carry `Cache-Control: public, max-age=300`
as a defense against bad caches that would otherwise hold the key
indefinitely.
**Content-Type:** `application/did+json` per W3C DID Core, not
plain `application/json`. Some DID resolvers enforce the media
type.
**Auth:** none. Well-known endpoints are public by spec — the
whole point is that any peer can resolve the DID without
credentials.
# JSON-RPC 2.0 endpoint (all agent operations dispatch here)
Source: https://docs.getbindu.com/api-reference/json-rpc/json-rpc-20-endpoint-all-agent-operations-dispatch-here
/openapi.yaml post /
Every write or read operation on tasks, messages, and contexts
uses this endpoint. The `method` field in the body selects the
operation. See the *Error catalog* in the top-level description
for every possible `error.code`.
**Accepted methods:** `message/send`, `message/stream`
*(experimental)*, `tasks/get`, `tasks/list`, `tasks/cancel`,
`tasks/feedback`, `contexts/list`, `contexts/clear`.
**Casing tolerance:** the server accepts both camelCase
(`taskId`) and snake_case (`task_id`) in `params` — pick one
and stick with it per-call. Responses are always snake_case.
**Size limit:** request bodies over 10 MB return `413
Payload Too Large` at the ASGI layer (does not use the
JSON-RPC error envelope).
**Idempotency:** `message/send` is NOT idempotent — a repeat
call creates a new task. If you need idempotency, have your
client generate a stable `messageId` and use `contexts/list`
+ `tasks/list` to check whether you've already sent it.
# Ask whether this agent can handle a task
Source: https://docs.getbindu.com/api-reference/negotiation/ask-whether-this-agent-can-handle-a-task
/openapi.yaml post /agent/negotiation
Orchestrators use this to pick the best agent for a task
before sending a real `message/send`. The agent returns a
capability score (0–1) weighted across skill match, I/O
compatibility, performance, load, and cost.
A score below the caller's `min_score` is interpreted as
"decline" — the orchestrator should route the task
elsewhere. This endpoint never actually performs the task;
it's advisory.
# Browser-facing payment capture page (HTML)
Source: https://docs.getbindu.com/api-reference/payment-x402/browser-facing-payment-capture-page-html
/openapi.yaml get /payment-capture
HTML page users browse to in order to complete payment via a
browser wallet. Not a machine-callable endpoint — clients that
want programmatic payment should use the x402 flow directly.
# Poll (or long-poll) a payment session
Source: https://docs.getbindu.com/api-reference/payment-x402/poll-or-long-poll-a-payment-session
/openapi.yaml get /api/payment-status/{sessionId}
# Start an x402 payment session
Source: https://docs.getbindu.com/api-reference/payment-x402/start-an-x402-payment-session
/openapi.yaml post /api/start-payment-session
Initiates a payment session for agents that charge per
request. Returns a session handle the caller uses with
`message/send` (via the `X-PAYMENT` header or session-linked
metadata) until the session is spent or expired.
Paid agents only. Unpaid agents return `404`.
# Open a plan; stream SSE of the orchestration.
Source: https://docs.getbindu.com/api-reference/plan/open-a-plan;-stream-sse-of-the-orchestration
/gateway-openapi.yaml post /plan
Accepts a user question + agent catalog, starts (or resumes) a
session, and streams Server-Sent Events as the planner runs.
### Session continuation
Pass `session_id` to resume an existing session — history persists,
the planner sees prior turns. Omit to start a fresh session. The
server returns the resolved `session_id` in the first SSE frame
(`event: session`), even for new sessions, so clients can cache it.
### Catalog immutability per session
The `agents` catalog is stored on first plan and refreshed on each
subsequent call; agents added or removed between plans take effect
immediately but don't retroactively change prior turns' tool sets.
### Streaming & abort
Closing the HTTP connection aborts the plan — in-flight A2A calls
receive an `AbortSignal` and the planner loop terminates. Clients
that want a partial result should buffer `text.delta` frames
client-side rather than relying on `final`.
# Get details for one skill
Source: https://docs.getbindu.com/api-reference/skills/get-details-for-one-skill
/openapi.yaml get /agent/skills/{skillId}
# Get skill documentation (Markdown)
Source: https://docs.getbindu.com/api-reference/skills/get-skill-documentation-markdown
/openapi.yaml get /agent/skills/{skillId}/documentation
The authoritative user-facing doc for this skill. Returns the
frontmatter-ed Markdown file the agent shipped. Use this
instead of the short `description` when you need full usage
guidance, examples, or input schemas.
# List all skills this agent publishes
Source: https://docs.getbindu.com/api-reference/skills/list-all-skills-this-agent-publishes
/openapi.yaml get /agent/skills
# API Introduction
Source: https://docs.getbindu.com/api/introduction
Complete HTTP API reference for Bindu agents
## Overview
Every Bindu agent exposes a standard HTTP API that follows the A2A (Agent-to-Agent) protocol. This API is automatically generated when you call `bindufy()` — you never write route handlers manually.
The API is **generic** and works identically across all agents, regardless of their specific capabilities. Domain-specific behavior is handled by your agent's handler function, not by custom endpoints.
***
## Base URL
```bash Local Development theme={null}
http://localhost:3773
```
```bash Production theme={null}
https://your-agent.getbindu.com
```
***
## Architecture: One Endpoint, Many Methods
Unlike traditional REST APIs, Bindu uses **JSON-RPC 2.0** over HTTP. Almost all operations go to a single endpoint:
```
POST /
```
The `method` field in the request body determines what operation to perform:
| Method | Purpose |
| ------------------------------------- | ----------------------------------------------- |
| `message/send` | Send a message to the agent, creates a new task |
| `message/stream` | Stream task updates (experimental) |
| `tasks/get` | Get the status and results of a task |
| `tasks/list` | List all tasks for the current context |
| `tasks/cancel` | Cancel a running task |
| `tasks/feedback` | Provide feedback on a completed task |
| `tasks/pushNotificationConfig/set` | Register a webhook for task updates |
| `tasks/pushNotificationConfig/get` | Read the webhook registered for a task |
| `tasks/pushNotificationConfig/list` | List webhook configs for a task |
| `tasks/pushNotificationConfig/delete` | Remove a webhook from a task |
| `contexts/list` | List all conversation contexts |
| `contexts/clear` | Clear a conversation context |
***
## Quick Start
### 1. Send a Message
```bash theme={null}
curl -X POST http://localhost:3773 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer " \
-d '{
"jsonrpc": "2.0",
"method": "message/send",
"params": {
"message": {
"role": "user",
"parts": [
{
"kind": "text",
"text": "hello"
}
],
"kind": "message",
"messageId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"contextId": "8e4d2c1a-9b3e-4f7a-9c2d-1a5e6b7c8d9f",
"taskId": "3a2b1c4d-5e6f-4a7b-8c9d-0e1f2a3b4c51"
},
"configuration": {
"acceptedOutputModes": ["application/json"]
}
},
"id": "6d8e9f0a-1b2c-4d3e-8f9a-0b1c2d3e4f5a"
}'
```
### 2. Get Task Status
```bash theme={null}
curl -X POST http://localhost:3773 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer " \
-d '{
"jsonrpc": "2.0",
"method": "tasks/get",
"params": {
"taskId": "3a2b1c4d-5e6f-4a7b-8c9d-0e1f2a3b4c51"
},
"id": "b7c9e1f3-4a5d-4b8c-9e0f-1a2b3c4d5e6f"
}'
```
### 3. Get Agent Card
```bash theme={null}
curl http://localhost:3773/.well-known/agent.json
```
***
## Authentication
Bindu supports three layers of authentication:
### Layer 1: Bearer Token (Required)
OAuth2 access token from Ory Hydra:
```bash theme={null}
Authorization: Bearer
```
**Scopes:**
* `agent:read` — Read operations (tasks/get, tasks/list)
* `agent:write` — Write operations (message/send, tasks/cancel)
* `agent:execute` — Both read and write (legacy)
### Layer 2: DID Signature (Optional, Agent-to-Agent)
For agent-to-agent communication, sign requests with your DID:
```bash theme={null}
X-DID: did:bindu:author:agent:id
X-DID-Timestamp: 1713564000
X-DID-Signature:
```
### Layer 3: x402 Payment (Optional, Paid Agents)
For paid agents, include payment proof:
```bash theme={null}
X-PAYMENT:
```
***
## Task States
Every interaction creates a **Task** with a unique ID. Tasks follow this state machine:
### Non-Terminal States
Queued, not yet picked up by worker
Agent is actively processing
Paused, waiting for user clarification
Paused, waiting for authentication
### Terminal States
Success, artifacts available
Processing error occurred
User terminated the task
Agent declined to process
**Terminal tasks are immutable.** To refine a completed answer, submit a new `message/send` with `referenceTaskIds` pointing to the old task.
***
## Error Codes
Errors follow JSON-RPC 2.0 format:
```json theme={null}
{
"jsonrpc": "2.0",
"id": "6d8e9f0a-1b2c-4d3e-8f9a-0b1c2d3e4f5a"
"error": {
"code": -32602,
"message": "Invalid params",
"data": { "field": "taskId", "reason": "required" }
}
}
```
### Standard JSON-RPC Errors
| Code | Name | Meaning |
| -------- | ---------------- | ------------------------ |
| `-32700` | Parse error | Invalid JSON |
| `-32600` | Invalid Request | Malformed JSON-RPC |
| `-32601` | Method not found | Unknown method |
| `-32602` | Invalid params | Schema validation failed |
| `-32603` | Internal error | Server bug |
### A2A Protocol Errors
| Code | Name | Meaning |
| -------- | ---------------------------- | -------------------------- |
| `-32001` | TaskNotFound | Task doesn't exist |
| `-32002` | TaskNotCancelable | Task already terminal |
| `-32003` | PushNotificationNotSupported | Agent doesn't support push |
| `-32004` | UnsupportedOperation | Operation not available |
| `-32005` | ContentTypeNotSupported | Unsupported output format |
### Bindu Extensions
| Code | Name | Meaning |
| -------- | ----------------------- | --------------------------------- |
| `-32009` | AuthenticationRequired | Missing bearer token |
| `-32010` | InvalidToken | Token introspection failed |
| `-32011` | TokenExpired | Token past expiration |
| `-32012` | InvalidTokenSignature | DID signature verification failed |
| `-32013` | InsufficientPermissions | Missing required scope |
***
## Discovery Endpoints
### Agent Card
```bash theme={null}
GET /.well-known/agent.json
```
Returns the A2A discovery document with:
* Agent DID
* Capabilities
* Published skills
* Payment requirements
* Supported protocols
### Skills List
```bash theme={null}
GET /agent/skills
```
Returns array of all skills the agent publishes.
### Skill Details
```bash theme={null}
GET /agent/skills/{skillId}
```
Returns detailed documentation for a specific skill.
***
## Health & Monitoring
### Health Check
```bash theme={null}
GET /health
```
Returns `200` when healthy, `503` when degraded. Includes per-component status.
### Metrics
```bash theme={null}
GET /metrics
```
Prometheus text format metrics including:
* Request counts and latency
* Active tasks by state
* Token usage
* Error rates
***
## Webhooks & Push Notifications
For long-running tasks, you don't have to poll. Pass a `push_notification_config` inside `configuration` and the agent will `POST` updates to your webhook as the task progresses:
```json theme={null}
{
"jsonrpc": "2.0",
"method": "message/send",
"params": {
"message": { "...": "..." },
"configuration": {
"acceptedOutputModes": ["application/json"],
"long_running": true,
"push_notification_config": {
"id": "6d8e9f0a-1b2c-4d3e-8f9a-0b1c2d3e4f5a"
"url": "https://your-app.com/webhook",
"token": "secret_abc123"
}
}
},
"id": "b7c9e1f3-4a5d-4b8c-9e0f-1a2b3c4d5e6f"
}
```
Your webhook receives status updates (state changes) and artifact updates as they happen. See the [Push Notifications guide](/bindu/learn/notification/overview) for the full event shapes and how to build a receiver.
***
## Best Practices
Generate a UUID for each message and reuse it if you need to retry. Check `tasks/list` before resending to avoid duplicates.
Start with 1s intervals, double up to 30s max. Don't hammer the server with rapid polls.
Use the same `contextId` across multiple messages to maintain conversation history.
Don't assume tasks always complete successfully. Check for `failed`, `canceled`, and `rejected` states.
For agent-to-agent calls, always verify the response signature against the agent's public key.
***
## Next Steps
OAuth2 and DID setup
x402 payment protocol
Webhook updates for long-running tasks
Working code examples
# Task-First Pattern & Architecture
Source: https://docs.getbindu.com/bindu/concepts/task-first-and-architecture
Why Bindu treats tasks as the core execution unit and the layered architecture that powers it
Messages alone are enough for a simple chat loop. They are not enough when several agents are working at once, some tasks depend on others, and parts of the workflow may pause for input before continuing.
# Task-First Agent Pattern
## Why Task-First Matters
In [Key Concepts](/bindu/introduction/key-concepts#task-lifecycle--states), you saw how Bindu task states enable interactive conversations. The reason Bindu leans so hard on tasks is that tasks are what make orchestration possible in the first place.
| Message-first thinking | Task-first thinking |
| ----------------------------------------------------- | -------------------------------------------------------------------- |
| Communication is easy, but execution is hard to track | Every unit of work has a durable identifier and state |
| Parallel work becomes ambiguous | Multiple tasks can run at the same time with separate IDs |
| Dependencies live in application logic only | `referenceTaskIds` makes task relationships explicit |
| Paused work is hard to resume cleanly | State tells you whether work is `working`, `input-required`, or done |
| Multi-agent coordination gets messy quickly | Orchestrators can manage work by task instead of by guesswork |
That is the shift: in Bindu, a task is not just a log entry or status wrapper. It is the unit that makes parallel execution, dependency tracking, and interactive workflows manageable.
Bindu follows the A2A "Task-only Agent" pattern where all responses are Task objects. That is what gives orchestrators a stable unit to coordinate at scale.
## How The Task-First Pattern Works
Every message creates a task that moves through a lifecycle such as `submitted` -> `working` -> `input-required` -> `completed`. The message starts the work, but the task is what tracks it.
### The Core Model
A task gives the system a few things that a plain message cannot:
* a unique task ID
* clear task state
* explicit dependency links through `referenceTaskIds`
* safe parallel execution across agents
Every interaction becomes a unit of work with its own task ID.
A task can be working, blocked on input, completed, or failed without losing the thread of execution.
Tasks can depend on other tasks, which is what makes orchestration and parallelism practical.
### The Lifecycle: Create, Coordinate, Complete
Under the hood, every task-first workflow moves through three practical stages.
```mermaid theme={null}
sequenceDiagram
participant Client
participant Orchestrator
participant AgentA as Agent A
participant AgentB as Agent B
participant AgentC as Agent C
Note over Client,Orchestrator: 1. Create
Client->>Orchestrator: Send message
Orchestrator->>Orchestrator: Create task with unique task ID
Note over Orchestrator,AgentC: 2. Coordinate
Orchestrator->>AgentA: Run Task 1
Orchestrator->>AgentB: Run Task 2 in parallel
AgentB-->>Orchestrator: input-required or result
AgentA-->>Orchestrator: result
Orchestrator->>AgentC: Run Task 3 with referenceTaskIds
Note over AgentC,Client: 3. Complete
AgentC-->>Orchestrator: Final deliverable
Orchestrator-->>Client: Completed task
```
A message creates a task. That task gets a unique ID and starts its lifecycle in a known state.
The quick recap is still the core of the model:
```text theme={null}
submitted -> working -> input-required -> completed
```
The important part is not only the message itself. It is the fact that the work now has a durable identity the system can track.
Once work has task IDs, orchestrators can coordinate several pieces of work at the same time.
Real-world example: travel planning
```text theme={null}
Task1 -> WeatherAgent: "Check Helsinki weather next week"
-> Returns: weather-data.json
Task2 -> FlightAgent: "Book flight" (references Task1)
-> Asks: "How many travelers?"
-> State: input-required
Task3 -> HotelAgent: "Find hotel" (runs in parallel with Task2)
-> Returns: hotel-booking.pdf
Task4 -> ItineraryAgent: "Create itinerary" (waits for Task2 & Task3)
-> referenceTaskIds: [Task2, Task3]
-> Returns: complete-itinerary.pdf
```
Without task IDs, the orchestrator could not keep that workflow straight. With task IDs, dependencies and parallel work become explicit.
The task reaches a terminal state when the work is done, fails, is canceled, or is rejected.
At that point, the task becomes immutable. If the user wants refinement later, the system creates a new task instead of reopening the old one.
***
## Messages Vs Artifacts
Tasks sit at the center, but messages and artifacts still play different roles around them.
| Aspect | Messages | Artifacts |
| ---------------- | ------------------------------------------------------------------- | ------------------------------------ |
| **Purpose** | Interaction, negotiation, status updates, explanations | Final deliverable, task output |
| **Task State** | `working`, `input-required`, `auth-required`, `completed`, `failed` | `completed` only |
| **When Used** | During task execution AND at completion | When task completes successfully |
| **Immutability** | Task still mutable (non-terminal) or immutable (terminal) | Task becomes immutable |
| **Content** | Agent's response text, explanations, error messages | Structured deliverable (files, data) |
The distinction is important:
* **Intermediate states** (`input-required`, `auth-required`) - message only, no artifacts
* **Completed state** - message (explanation) plus artifact (deliverable)
* **Failed state** - message (error explanation) only, no artifacts
* **Canceled state** - state change only, no new content
Messages carry the conversation while work is happening. Artifacts carry the deliverable once the work is done.
### Task State Rules
There are two broad categories of task state.
**Non-terminal (task open):**
* `submitted`
* `working`
* `input-required`
* `auth-required`
**Terminal (task immutable):**
* `completed`
* `failed`
* `canceled`
* `rejected`
## A2A Protocol Compliance
The task-first model lines up with the A2A protocol in a few concrete ways.
Terminal tasks cannot restart. Refinements create new tasks.
Multiple tasks can share `contextId` so conversation history stays coherent.
`referenceTaskIds` gives the system a clean way to express chained work.
The practical consequences are:
* **Task Immutability** - terminal tasks cannot restart; refinements create new tasks
* **Context Continuity** - multiple tasks share `contextId` for conversation history
* **Parallel Execution** - tasks run independently, tracked by unique IDs
* **Dependency Management** - use `referenceTaskIds` to chain tasks
## The Value Of Task-First Execution
This model matters most when workflows stop being linear.
Multiple tasks can run at the same time because each task has its own ID and state. The system does not need to overload one message thread with all active work.
When one task depends on another, `referenceTaskIds` makes that dependency explicit. This is what lets an orchestrator wait for Task2 and Task3 before starting Task4.
A task can move into `input-required` or `auth-required` and stay there until the missing piece arrives. That pause does not destroy the task or require the system to infer where to resume.
Orchestrators like Sapthami can coordinate several agents because the work is represented as tasks, not just as a pile of messages with implied state.
***
# Architecture: How Bindu Works
When you send a message to a Bindu agent, a lot more happens than a simple function call. The request moves through protocol handling, security checks, task orchestration, worker execution, storage, and observability before it comes back as a result.
## Why Architecture Matters
In [Key Concepts](/bindu/introduction/key-concepts), you saw how task states like `submitted`, `input-required`, and `completed` make interactive workflows possible. The architecture is the part that makes those states real in a running system.
| Flat application model | Bindu layered architecture |
| ---------------------------------------------------------- | --------------------------------------------------------------- |
| Request handling, execution, and storage blur together | Each layer has a clear job in the lifecycle |
| Scaling usually means rewriting core pieces | Storage, queueing, and workers can evolve independently |
| Observability is bolted on late | Traces, LLM observability, and metrics are part of the runtime |
| Protocol support becomes tightly coupled to business logic | Protocol, security, orchestration, and execution stay separated |
| Hard to reason about what happens after a message arrives | The request flow is explicit from client to artifact |
That is the shift: Bindu is built as a layered system so each part of task execution can do one job well without collapsing into a single opaque runtime.
When a message creates a task, that task moves through several layers, not just one server endpoint. The architecture matters because each layer is responsible for part of that lifecycle.
## How Bindu Architecture Works
Bindu is organized into protocol, security, application, orchestration, storage, agent, and observability layers. Each one participates in turning a message into a task and a task into a result.
### The System Layout
```mermaid theme={null}
graph TB
subgraph "Client Layer"
Client[Client/Orchestrator]
Discovery[Agent Discovery]
end
subgraph "Protocol Layer"
HTTP[HTTP/JSON-RPC]
A2A[A2A Protocol v0.3.0]
X402[X402 Payment]
Negotiation[Negotiation]
end
subgraph "Security Layer"
Auth[Hydra OAuth2]
mTLS[Mutual TLS]
DID[DID Identity]
end
subgraph "Application Layer"
Server[BinduApplication
Starlette Web Server]
Router[Request Router]
Validator[Schema Validator]
end
subgraph "Orchestration Layer"
Manager[TaskManager
Central Coordinator]
Queue[Task Queue]
Worker[Worker Pool]
end
subgraph "Storage Layer"
Storage[(Storage Backend
Memory/PostgreSQL)]
Cache[(Cache Layer
Redis)]
end
subgraph "Agent Layer"
Agent[Your AI Agent
LangChain/CrewAI/Agno]
Skills[Skills Registry]
Tools[Tool Integrations]
end
subgraph "Observability Layer"
Traces[Distributed Tracing
Jaeger/OTLP]
LLMObs[LLM Observability
Phoenix/Langfuse]
Metrics[Metrics & Logs]
end
Client --> Discovery
Discovery --> HTTP
HTTP --> A2A
HTTP --> X402
HTTP --> Negotiation
A2A --> Auth
X402 --> Auth
Negotiation --> Auth
Auth --> DID
Auth --> mTLS
DID --> Server
mTLS --> Server
Server --> Router
Router --> Validator
Validator --> Manager
Manager --> Queue
Manager <--> Storage
Queue --> Worker
Worker <--> Storage
Worker <--> Cache
Worker --> Agent
Agent --> Skills
Agent --> Tools
Server -.traces.-> Traces
Manager -.traces.-> Traces
Worker -.traces.-> Traces
Agent -.traces.-> LLMObs
Manager -.metrics.-> Metrics
Worker -.metrics.-> Metrics
style Client fill:#e1f5ff
style Discovery fill:#d4f5e1
style HTTP fill:#fff4e1
style A2A fill:#e1ffe1
style X402 fill:#98fb98
style Negotiation fill:#e1ffe1
style Auth fill:#ffd4e1
style mTLS fill:#ffd4e1
style DID fill:#ffd4e1
style Server fill:#ffe1f5
style Router fill:#ffe1f5
style Validator fill:#ffe1f5
style Manager fill:#e1e1ff
style Queue fill:#e1e1ff
style Worker fill:#e1e1ff
style Storage fill:#ffe1e1
style Cache fill:#ffe1e1
style Agent fill:#e1f5ff
style Skills fill:#e1f5ff
style Tools fill:#e1f5ff
style Traces fill:#ffd700
style LLMObs fill:#ffd700
style Metrics fill:#ffd700
```
The layered structure is what lets Bindu stay simple on the surface while still handling protocol, identity, execution, and scaling concerns underneath.
Protocol, security, orchestration, storage, and observability each live in their own part of the system.
TaskManager sits in the middle because task state is the thing the rest of the system coordinates around.
Storage backends, queues, workers, and agent frameworks can change without changing the whole model.
### The Lifecycle: Accept, Execute, Return
Under the hood, every request moves through three practical stages.
```mermaid theme={null}
sequenceDiagram
participant Client
participant Server as BinduApplication
participant Auth as Auth Layer
participant Manager as TaskManager
participant Storage as Storage
participant Queue as Scheduler
participant Worker as Worker
participant Agent as AI Agent
participant Obs as Observability
Note over Client,Manager: 1. Accept
Client->>Server: POST / (message/send)
Server->>Obs: Start trace
Server->>Auth: Verify credentials
Auth-->>Server: Authenticated
Server->>Manager: Create task
Manager->>Storage: Save task (status: submitted)
Manager->>Queue: Enqueue task_id
Manager-->>Server: Task created
Server-->>Client: 200 OK (task with submitted state)
Note over Queue,Agent: 2. Execute
Queue->>Worker: Dequeue task_id
Worker->>Storage: Get task details
Worker->>Manager: Update status (working)
Manager->>Storage: Update status
Manager->>Client: Push notification (working)
Worker->>Agent: Execute with messages
Agent->>Obs: Log LLM calls
Agent-->>Worker: Result
Note over Worker,Client: 3. Return
Worker->>Manager: Complete task
Manager->>Storage: Save artifact
Manager->>Storage: Update status (completed)
Manager->>Client: Push notification (completed)
Manager->>Obs: End trace
Client->>Server: POST / (tasks/get)
Server->>Storage: Get task
Storage-->>Server: Task + artifact
Server-->>Client: 200 OK (task with artifacts)
```
A client sends a `message/send` request. The protocol and security layers handle the request first, then the application layer validates it and passes it to `TaskManager`.
`TaskManager` creates the task, stores it with state `submitted`, puts the task ID on the queue, and returns the task immediately.
A worker dequeues the task, fetches the task details, and moves the task into `working`.
The worker then calls your agent. That agent may use frameworks such as Agno, LangChain, CrewAI, or LlamaIndex, plus skills and tool integrations.
Once the agent returns a result, `TaskManager` saves the artifact, updates the task state, and makes the finished task available through retrieval APIs and notifications.
The request flow summary is still the same:
* **Phase 1: Submit (0-50ms)** - Client sends `message/send` -> Auth validates -> TaskManager creates task -> Returns `task_id` immediately
* **Phase 2: Execute (async)** - Worker dequeues -> Runs your agent -> Updates state (`working` -> `input-required` or `completed`)
* **Phase 3: Retrieve (anytime)** - Client polls with `tasks/get` -> Gets current state + artifacts
***
## Core Components
The architecture is easier to reason about when the layers are spelled out directly.
### Protocol Layer
* **A2A Protocol v0.3.0** - Agent-to-agent communication (task lifecycle, context management) over JSON-RPC 2.0
* **X402 Protocol** - Micropayments delivered as an A2A extension (payment sessions, cryptographic signatures)
* **Negotiation** - Bid/award flow for matching tasks to capable agents, exposed at `/agent/negotiation`
A2A method calls (`message/send`, `tasks/get`, `tasks/cancel`, `contexts/*`) are dispatched through JSON-RPC at `POST /`. Discovery, skills, payments, and negotiation use dedicated HTTP routes.
### Security And Identity Layer
* **Hydra OAuth2** - ORY Hydra acts as the OAuth2 / OIDC provider for authenticated routes
* **Mutual TLS** - Optional cert-pinned transport via the mTLS extension (step-ca issuance)
* **DID (Decentralized Identity)** - Unique, verifiable agent identity surfaced in the agent card and accepted in `allowed_dids` allowlists
### Application Layer
* **BinduApplication** - Starlette-based ASGI web server with async/await
* **Request Router** - Registers `/`, `/.well-known/agent.json`, `/agent/private.json` (when configured), `/agent/skills`, `/agent/skills/{skill_id}`, `/agent/skills/{skill_id}/documentation`, `/agent/negotiation`, `/did/resolve`, `/health`, `/metrics`, plus payment-session routes when X402 is enabled
* **Schema Validator** - Validates request structure and types
### Orchestration Layer
* **TaskManager** - Central coordinator that creates tasks, manages state, coordinates workers
* **Task Queue** - Memory (dev) or Redis (prod) for distributed task scheduling
* **Worker Pool** - Executes tasks asynchronously, handles retries and timeouts
### Storage Layer
* **Memory Storage** (dev) - In-memory dictionaries for tasks, contexts, artifacts
* **PostgreSQL** (prod) - ACID compliance, relational queries, JSON support
* **Redis Cache** - Session storage, rate limiting, pub/sub notifications
### Agent Layer
* **Framework Agnostic** - Works with Agno, LangChain, CrewAI, LlamaIndex
* **Skills Registry** - Defines agent capabilities via `/agent/skills` endpoint
* **Tool Integrations** - 113+ built-in toolkits for data, code, web, APIs
### Observability Layer
* **Distributed Tracing** - Jaeger/OTLP tracks requests across all components
* **LLM Observability** - Phoenix/Langfuse monitors token usage, latency, cost
* **Metrics** - Request rate, task duration, error rate, queue depth, worker utilization
The system works because these layers stay distinct. Protocol is not storage. Storage is not orchestration. Orchestration is not the agent itself.
## The Value Of Layered Architecture
The architecture is designed around a few practical goals.
* **Simplicity** - Wrap any agent with minimal code
* **Scalability** - From localhost to distributed cloud
* **Reliability** - Built-in error handling and recovery
* **Observability** - Complete visibility into operations
* **Security** - Authentication and identity built-in
* **Standards** - Protocol-first design (`A2A`, `X402`)
This is the point of the layered design: each part can evolve independently while still fitting into one coherent system.
## Real-World Use Cases
When you send "create sunset caption", the request hits the Protocol Layer, is authenticated by the Security Layer, validated in the Application Layer, turned into a task by `TaskManager`, executed by a worker, and returned as a completed task with an artifact.
If the agent asks "which platform?", the task does not disappear. `TaskManager` updates it into `input-required`, stores that state, and lets the same task continue when the user answers.
In development, the same architecture can run with in-memory storage and queues. In production, those pieces can move to PostgreSQL and Redis without changing the task model.
Tracing and metrics sit alongside execution so you can see requests move through the server, manager, worker, and agent instead of guessing which layer is slow or failing.
***
Bindu treats work as
something to track, coordinate, and complete explicitly
, so multi-agent execution stays understandable as systems grow.
Bindu works because each layer
does one part of the job clearly
, so task execution stays understandable as the system grows.
# Identity & Signed Calls
Source: https://docs.getbindu.com/bindu/gateway/identity
Give the gateway a DID - every outbound call gets a cryptographic signature that agents can verify.
Everything so far has been running on `localhost`. The agents accept unsigned requests because `"auth": { "type": "none" }` tells the gateway not to sign them. That's fine for development - there's no attacker between you and your own laptop.
**In production it isn't.** If your gateway calls an agent over the public internet, anyone who can reach that agent's URL can pretend to be your gateway. They can feed it garbage, steal its output, or (if the agent does anything side-effectful like sending email or moving money) cause real damage.
The fix is: the gateway gets a cryptographic identity and signs every outbound request. Agents verify the signature before processing. If an attacker tries to forge a request, the signature won't match the gateway's registered public key, and the agent rejects the call.
***
## What's a DID?
**DID** stands for **Decentralized Identifier**. It's a string that looks like:
```
did:bindu:alice_at_example_com:gateway:abc123
```
It uniquely identifies an agent or a gateway. Paired with it is an **Ed25519 key pair** - a private key (secret, 32 bytes, lives in an env var) and a public key (safe to share, published at a `.well-known` URL).
You sign outbound requests with the private key. Recipients verify with the public key. Standard public-key cryptography - what puts the green lock in your browser.
Read [Decentralized Identifiers (DIDs)](/bindu/learn/did/overview) for the full intuition. The milk-truck analogy there is the gentlest on-ramp we know.
***
## The three env vars
Generate a private key seed (once, keep it secret):
```bash theme={null}
python3 -c 'import os, base64; print(base64.b64encode(os.urandom(32)).decode())'
```
Add to `gateway/.env.local`:
```bash gateway/.env.local theme={null}
BINDU_GATEWAY_DID_SEED=
BINDU_GATEWAY_AUTHOR=you@example.com
BINDU_GATEWAY_NAME=gateway
```
That's enough for the gateway to have an identity. It won't be *useful* yet - we also need to tell the gateway where to publish its public key so agents can fetch it. That's the next piece.
***
## Hydra - the registration server
[Ory Hydra](https://www.ory.sh/hydra/) is an open-source OAuth 2.0 / OIDC server. You run your own Hydra (or share one with your peers) — there is no Bindu-hosted public Hydra. The gateway integrates with whichever Hydra you point it at.
**How it works:** the gateway registers itself as an OAuth client at boot using its DID as the `client_id` and a secret derived deterministically from the seed. The registry stores your DID + public key in the client's metadata; agents that want to verify your signatures fetch your `/.well-known/did.json`.
Two more env vars, pointing at your Hydra:
```bash gateway/.env.local theme={null}
BINDU_GATEWAY_HYDRA_ADMIN_URL=https://hydra-admin.
BINDU_GATEWAY_HYDRA_TOKEN_URL=https://hydra./oauth2/token
# Optional, space-separated. Defaults to "openid offline agent:read agent:write"
# BINDU_GATEWAY_HYDRA_SCOPE="openid offline agent:read agent:write"
```
**Partial Hydra config fails fast.** Both URLs must be set together, or neither. If you set only one, the gateway aborts boot with the error `Partial Hydra config — set both or neither`.
Restart `npm run dev`. You'll now see:
```
[bindu-gateway] DID identity loaded: did:bindu:you_at_example_com:gateway:
[bindu-gateway] public key (base58): 6MkjQ2r...
[bindu-gateway] registering with Hydra at https://hydra-admin....
[bindu-gateway] Hydra registration confirmed for did:bindu:...
[bindu-gateway] publishing DID document at /.well-known/did.json
[bindu-gateway] listening on http://0.0.0.0:3774
[bindu-gateway] session mode: stateless
```
Three things just happened:
Deterministic - same seed always produces the same DID.
As an OAuth client, with its DID as the `client_id` and its public key in the metadata. **Idempotent** - safe to restart as many times as you like.
The first call to a `did_signed` peer triggers an OAuth `client_credentials` exchange against `BINDU_GATEWAY_HYDRA_TOKEN_URL`; the resulting access token is cached in memory and proactively refreshed 30 seconds before expiry. Concurrent callers during a refresh share the same in-flight fetch — Hydra is hit at most once per refresh window.
The gateway also published its own DID document at `http://localhost:3774/.well-known/did.json`. Curl it:
```bash theme={null}
curl http://localhost:3774/.well-known/did.json
```
```json theme={null}
{
"@context": ["https://www.w3.org/ns/did/v1", "https://getbindu.com/ns/v1"],
"id": "did:bindu:you_at_example_com:gateway:abc123",
"authentication": [
{
"id": "did:bindu:you_at_example_com:gateway:abc123#key-1",
"type": "Ed25519VerificationKey2020",
"controller": "did:bindu:you_at_example_com:gateway:abc123",
"publicKeyBase58": "6MkjQ2r..."
}
]
}
```
That's your gateway's public key, served over HTTP, signed by no one but vouching for itself. Any agent that receives a signed request claiming to be from your DID can fetch this document, extract the public key, and verify the signature.
***
## Flipping a peer to signed mode
Change the `/plan` request:
```json theme={null}
{
"name": "research",
"endpoint": "https://research.example.com",
"auth": { "type": "did_signed" },
"trust": { "verifyDID": true, "pinnedDID": "did:bindu:..." },
"skills": [{ "id": "web_research" }]
}
```
No `token` or `envVar` on `auth` — the gateway will use its own Hydra token automatically. The optional `trust` block is a separate decision: it tells the gateway to verify *incoming* signatures from this peer (and, if `pinnedDID` is set, to reject responses signed by any other key). You can sign outbound without verifying inbound, or verify inbound without signing outbound — they're independent.
Re-fire. On the wire, three things change:
The gateway wraps the serialized JSON-RPC body in `{"body": , "did": , "timestamp": }` and serializes that envelope with a Python-compatible sorted-keys serializer (matches the reference agent's `json.dumps(payload, sort_keys=True)` byte-for-byte, spaces and all — see [`gateway/src/bindu/identity/local.ts`](https://github.com/GetBindu/Bindu/blob/main/gateway/src/bindu/identity/local.ts)). Those exact UTF-8 bytes are then signed with the gateway's Ed25519 private key.
`X-DID` (your gateway's DID), `X-DID-Signature` (base58 Ed25519 signature), and `X-DID-Timestamp` (unix seconds) go on every signed call.
`Authorization: Bearer ` — the cached client-credentials token from Hydra. Auto-refreshed 30s before expiry.
On the receiving side, the agent:
Via the gateway's `/.well-known/did.json` or a cached DID→key mapping.
Using the gateway's public key (`Ed25519VerificationKey2020`, base58-encoded in the DID document's `authentication` block).
Confirms it's real and unexpired.
Otherwise returns HTTP 401.
**Audit trail.** Each peer call's verification result is surfaced inline in the SSE stream — the `` envelope you saw in the quickstart carries a `verified` attribute with four possible values:
* `"yes"` — the peer signed and the signature checked out.
* `"no"` — at least one signed artifact failed verification. The task is also marked `failed`.
* `"unsigned"` — verification ran but the peer attached no signature. Treat the body as unverified hearsay.
* `"unknown"` — verification didn't run (no `trust.verifyDID`, no resolvable DID, or DID-document resolution failed).
`auth.type` and `trust.verifyDID` are two separate knobs: `auth.type: "did_signed"` controls how the gateway authenticates itself on outbound calls, while `trust.verifyDID: true` (with an optional `trust.pinnedDID`) is what asks the gateway to verify the *peer's* signatures on the way back. Turn both on against a properly-configured peer and you'll see `verified="yes"` on every successful call.
If any of those three checks fail - signature mismatch, unknown DID, invalid token - the agent returns HTTP 401 and the gateway surfaces that as `event: task.finished` with `state: failed` and a useful error message.
***
## Two modes: auto vs manual
One Hydra, shared by the gateway and its peers, handles all the registration and token exchange.
```bash gateway/.env.local theme={null}
BINDU_GATEWAY_DID_SEED=
BINDU_GATEWAY_AUTHOR=you@example.com
BINDU_GATEWAY_NAME=gateway
BINDU_GATEWAY_HYDRA_ADMIN_URL=https://hydra-admin.
BINDU_GATEWAY_HYDRA_TOKEN_URL=https://hydra./oauth2/token
```
Request side:
```json theme={null}
"auth": { "type": "did_signed" }
```
Use this unless you have a specific reason not to.
For federated setups where different peers trust different Hydra instances.
**Config** - set only the DID env vars (seed, author, name), not the Hydra URLs. For each peer, pre-register your gateway's DID with *that peer's* Hydra (out of band) and obtain an access token. Store the tokens in env vars per peer.
**Request side** - tell the gateway which env var to read with `tokenEnvVar`:
```json theme={null}
"auth": {
"type": "did_signed",
"tokenEnvVar": "PEER_A_TOKEN"
}
```
A peer-scoped `tokenEnvVar` wins over the auto provider, so you can run a hybrid setup: most peers on auto, a few on per-peer manual tokens.
***
## Chapter takeaway
Keep `auth.type: "none"`. No cryptography needed.
Configure the DID identity and flip peers to `did_signed`. The token and signature are automatic once the env vars are set; you never touch crypto code.
If something in this chapter isn't working, the most common cause is a missing env var - the gateway logs exactly which one on boot when a partial config is detected.
Last stop: **[Going to production →](/bindu/gateway/production)**
To maintain trust between agents -
every request is signed.
# Adding a Second Agent
Source: https://docs.getbindu.com/bindu/gateway/multi-agent
Three agents working on one question - the planner decides the order and passes results between them.
Stop the joke agent (Ctrl+C in its terminal). We'll start both it and four more using a helper script:
```bash theme={null}
./examples/gateway_test_fleet/start_fleet.sh
```
Expected output:
```
[joke_agent] started, pid=64945
[math_agent] started, pid=64958
[poet_agent] started, pid=64969
[research_agent] started, pid=64980
[faq_agent] started, pid=64993
```
Five agents now, each on its own port:
| Agent | Port | Does |
| ---------------- | ---- | ----------------------------------------- |
| `joke_agent` | 3773 | Tells jokes |
| `math_agent` | 3775 | Solves math problems step-by-step |
| `poet_agent` | 3776 | Writes short poems |
| `research_agent` | 3777 | Web search + summarize a factual question |
| `faq_agent` | 3778 | Answers from a canned FAQ |
Each is under \~100 lines of Python. Open any one - say `joke_agent.py` - and you'll see a small configuration that wires a language model (`openai/gpt-4o-mini`, dispatched through OpenRouter) to a few lines of instructions (*"tell jokes, refuse other requests"*). Narrow scope on purpose so mistakes are visible.
Gateway is already running from the [previous chapter](/bindu/gateway/quickstart); don't restart it.
***
## A three-agent question
Paste this into your curl terminal. It asks something that genuinely needs three agents to answer:
```bash theme={null}
curl -N http://localhost:3774/plan \
-H "Authorization: Bearer ${GATEWAY_API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"question": "First research the current approximate population of Tokyo. Then compute what exactly 0.5% of that population is. Finally write a 4-line poem celebrating that number of people.",
"agents": [
{
"name": "research", "endpoint": "http://localhost:3777",
"auth": { "type": "none" },
"skills": [{ "id": "web_research", "description": "Web search and summarize a factual question" }]
},
{
"name": "math", "endpoint": "http://localhost:3775",
"auth": { "type": "none" },
"skills": [{ "id": "solve", "description": "Solve math problems step-by-step" }]
},
{
"name": "poet", "endpoint": "http://localhost:3776",
"auth": { "type": "none" },
"skills": [{ "id": "write_poem", "description": "Write a short poem" }]
}
]
}'
```
This takes around 15 seconds and produces three `task.started` events, in order - research first, then math, then poet. Abbreviated output from a real run:
```
task.started → research called with "What is the current population of Tokyo?"
task.artifact → "Tokyo's metropolitan area has approximately 36.95 million people..."
task.finished → completed
task.started → math called with "Compute 0.5% of 36,950,000"
task.artifact → "0.005 × 36,950,000 = 184,750"
task.finished → completed
task.started → poet called with "Write a 4-line poem about 184,750 people"
task.artifact → "In Tokyo's heart, where dreams align, / 184,750 souls brightly shine, / ..."
task.finished → completed
text.delta → "Step 1 - Population: 36.95 million..."
...
final
done
```
**The gateway chose the order, extracted the right number from each reply, and passed it to the next agent - all without you writing a single line of glue code.** That's the whole point.
***
## How it chose
The planner saw three tools available (one per agent-skill combination):
| Tool name | Description |
| ---------------------------- | ------------------------------------------- |
| `call_research_web_research` | Web search and summarize a factual question |
| `call_math_solve` | Solve math problems step-by-step |
| `call_poet_write_poem` | Write a short poem |
**Where do those tool names come from?** The gateway builds them automatically from the `name` and `skills[].id` fields in your request: `call__`.
Then the planner read the question: *"First research… Then compute… Finally write a 4-line poem…"* The word *"First"* strongly suggests research is step 1, and the LLM picked `call_research_web_research`. It waited for the reply, re-read the question with the new context, decided the next step was math, picked `call_math_solve`, and so on.
All of this happens inside one HTTP request. The SSE stream is the gateway narrating what the planner decided.
***
## What if you added a fourth agent it doesn't need?
Try it. Add the joke agent to the catalog above and re-run:
```json theme={null}
{
"name": "joke", "endpoint": "http://localhost:3773",
"auth": { "type": "none" },
"skills": [{ "id": "tell_joke", "description": "Tell a joke" }]
}
```
The SSE output is the same - three `task.started` events for research, math, poet. The joke tool sat there unused.
**The planner only calls what it needs.** This matters in production: you can hand the gateway a catalog of 50 agents, and only the 2 or 3 relevant to a given question will actually be invoked.
***
## What is the planner, actually?
Inside the gateway, there's a single agent configuration file called `gateway/agents/planner.md`. It's a markdown file with YAML frontmatter — this is the real shape from the repo:
```yaml theme={null}
---
name: planner
description: Planning gateway for multi-agent Bindu collaboration
mode: primary
model: openrouter/anthropic/claude-sonnet-4.6
temperature: 0.3
steps: 10
permission:
agent_call: ask
---
# System prompt body - the planner's own instructions.
```
The body is the system prompt. On each `/plan` request, the gateway does this:
The registry is built once at boot by scanning `gateway/agents/*.md`. There's no per-request reload — see `gateway/src/agent/index.ts`.
Plus any prior turns the client sent in `history` (the gateway is stateless, so history travels on the request).
One tool per `agent.skill` pair, named `call__`.
Claude (or whatever model you picked) drives the loop.
Text deltas + tool calls + tool results.
Inside OpenRouter, Claude runs its agentic loop - text → tool call → tool result → more text → another tool call → final text. The gateway's job is just to execute the tool calls against your real agents and plumb the results back.
**Edits to `gateway/agents/planner.md` require a gateway restart.** The agent registry is populated once at boot and cached for the lifetime of the process. If you tweak the system prompt and want it to take effect, Ctrl+C and `npm run dev` again.
Next up: teach the planner reusable patterns without editing its system prompt. **[Recipes →](/bindu/gateway/recipes)**
Gateway doesn’t run agents randomly -
it decides the order and connects their outputs.
# The Bindu Gateway
Source: https://docs.getbindu.com/bindu/gateway/overview
An end to end story - planner, recipes, DID signing, all wired together.
**Budget about 45 minutes** if you're reading straight through and running the commands. If you skip the commands and just read, \~15 minutes. No prior knowledge of AI agents required - we'll introduce each idea when you need it, and never before.
You've heard the words. *Agent. Planner. A2A. Multi-agent orchestration.* By the end of this section you'll have run all of those things yourself, watched them talk to each other, and taught them a new trick.
***
## The roadmap
The problem an orchestrator solves - and what it is not.
Seven steps. One question. One agent. One streaming response.
Three agents, one question - watch the planner choose the order.
Teach the planner reusable patterns in plain markdown.
Cryptographic identity for production peer calls.
What to read, what to try, what to pin down.
***
## Why a gateway exists
Imagine you've built three AI agents. Each is a small program that listens on an HTTP port and answers specific kinds of questions:
Searches the web for facts.
Solves numerical problems.
Writes short verse.
Now a user asks:
> *"Look up the population of Tokyo, then calculate 0.5% of it, then write a four-line poem about that number of people."*
Without a gateway, **you** - the programmer - have to:
Read intent, split the work.
Wait for reply.
Fragile string munging.
Wait again.
Hope the format didn't change.
Wait one last time.
Write the user-facing response yourself.
That's not hard for one question. But what about the next hundred questions? Each one needs its own chain, its own parsing, its own error handling. And as soon as a new agent joins the roster, every existing chain might want to use it.
**The gateway is the thing that does steps 1–7 for you.** You hand it a question and a list of agents. It figures out which agents to call, in what order, with what input. You get back a stream of what happened and, at the end, a final answer.
***
## How does it "figure it out"?
The gateway has one trick: it uses an LLM - a large language model, like Claude or GPT - as a **planner**. The planner sees:
* The user's question.
* A short description of each available agent.
* Its own system prompt (general instructions the gateway operator wrote).
Then it decides, turn by turn, which agent to call next. The output of each call feeds back into the planner's context, and it decides whether to call another agent, write a final answer, or ask the user a clarifying question.
Modern LLMs are surprisingly good at this. Anthropic calls it [tool use](https://docs.anthropic.com/claude/docs/tool-use), OpenAI calls it "function calling" - same idea. The gateway wires your agents up as "tools" the planner can invoke and lets the LLM drive.
***
## What the gateway is not
It doesn't generate answers itself. It orchestrates the ones you already have.
You give it a list of agents per request. The agents run wherever they run - your laptop, a cluster, a third-party service. The gateway just calls them.
As long as each agent speaks the [A2A protocol](https://github.com/a2aproject/A2A) (a small JSON-RPC 2.0 spec authored by Google), the gateway can call it. Bindu implements A2A natively in both the Python core and the TypeScript gateway, so `bindufy()`-built agents speak it out of the box.
***
## What you'll build by the end
Three agents running locally, chained automatically to answer a multi-part question.
A short markdown file that teaches the planner a reusable pattern without writing any code.
A cryptographic identity - outbound calls get signed so downstream agents can verify the calls are really from your gateway.
Let's go. Next up: [Hello, gateway](/bindu/gateway/quickstart).
Gateway doesn't answer questions -
it decides who should.
# Going to Production
Source: https://docs.getbindu.com/bindu/gateway/production
What to read, what to try, what to pin down before you ship.
You've seen the gateway end-to-end. This page is the map of what's next.
***
## Reference material
The machine-readable contract for `/plan`, `/health`, and `/.well-known/did.json`. Every field, response, and example.
The operator's reference: configuration knobs, environment variables, the `/health` payload, troubleshooting, and where vendored code came from.
The planner LLM's system prompt. If the gateway is doing something you don't expect, start here.
The two shipped recipes - `multi-agent-research` and `payment-required-flow` - plus whatever you wrote. Each is a complete example.
***
## Hands-on next steps
The `gateway_test_fleet` example has 15 prebuilt test cases (`Q1`..`Q12` plus `Q_MULTIHOP`, `Q_INBOX_REPRO_A`, `Q_INBOX_REPRO_B`) covering edge behaviors — empty question, wrong bearer token on a peer, timeout, ambiguous question, nonexistent skill, multi-hop chains, inbox reproductions:
```bash theme={null}
./examples/gateway_test_fleet/run_matrix.sh
```
Each produces a full SSE log in `examples/gateway_test_fleet/logs/.sse` - open one and read it end to end. It's unusually readable once you know the event types.
The one from [the recipes chapter](/bindu/gateway/recipes) was generic. Try a tenant-specific policy - *"always prepend a compliance disclaimer to the final message,"* or *"for any question about PII, refuse and point at the legal agent."*
Copy `examples/gateway_test_fleet/joke_agent.py`, change the instructions, run it on port 3779, add it to a `/plan` request. Watch the planner pick it up without any gateway-side config change.
Open `gateway/agents/planner.md` and tighten or loosen its instructions. The agent registry is loaded once at boot and cached — Ctrl+C the gateway and `npm run dev` again to pick up your edits.
***
## Production checklist
If you're moving this past localhost:
Use [the identity chapter](/bindu/gateway/identity) as your walk-through. Unsigned calls are fine on localhost; they're a vulnerability anywhere else.
Distribute via your usual secret-management tool - not `.env.local`.
Add `model: openrouter/anthropic/claude-sonnet-4.6` (or whichever you want) to `gateway/agents/planner.md` frontmatter so upgrades are explicit, not implicit.
A runaway planner that loops 100 times at your expense is a real failure mode. Cap it via `preferences.max_steps` in the request body (and pair with `preferences.timeout_ms` for a wall-clock budget — default 30 min, max 6 h). See the [Gateway API reference](/gateway-api/introduction).
That's where you see token counts per plan. Log them. Alert on outliers.
***
## When you're stuck
Re-read the env var section of `gateway/README.md`. Partial DID or Hydra config fails fast with a message naming the missing var.
The descriptions you gave for `agents[].skills[].description` are probably too short or too vague. Anthropic's docs say tool descriptions are *"by far the most important factor in tool performance"* - 3–4 sentences on intent, inputs, outputs, and when to use it.
Your `OPENROUTER_API_KEY` is invalid or out of credit.
You're on an older gateway commit. `git pull`.
***
## That's the whole story
You have a gateway, five agents, the ability to add more, the ability to teach patterns via recipes, and the ability to sign outbound calls for production.
Everything else in this repo is either reference material for one of those five concepts, or internal implementation detail you don't need to read until you're ready to extend the gateway itself.
**Go build something.**
Every field, every response shape.
What each agent the gateway calls exposes.
The identity model under `did_signed`.
Ask questions, share recipes.
Now you have everything you need -
build systems you need.
# Quickstart
Source: https://docs.getbindu.com/bindu/gateway/quickstart
Six steps - one question, one agent, one streaming response.
This chapter has six steps. Follow them in order.
***
## Step 1 - What you need
You need two things before starting. You may already have them; skim and decide.
The gateway is TypeScript; we run it with `tsx`, no separate build step.
Paid proxy to dozens of models. The gateway uses it for the planner LLM.
```bash theme={null}
node --version # should print v22.x or higher
```
Sign up at [openrouter.ai](https://openrouter.ai), add a few dollars of credit, and copy the key from the *API* section. It looks like `sk-or-v1-`.
**No database required.** The gateway is **stateless** — it holds per-request state in memory for the lifetime of each `/plan` call and drops it when the call ends. The calling client owns durable history: pass prior turns in the `history` field and the latest compaction summary in `prior_summary` on the next call. Old releases required Supabase; that's gone.
***
## Step 2 - Get the code and install
```bash theme={null}
git clone https://github.com/GetBindu/Bindu
cd Bindu
# Python side - runs the small sample agents we'll call
uv sync --dev --extra agents
# TypeScript side - runs the gateway
cd gateway
npm install
cd ..
```
The `uv sync` line uses [uv](https://github.com/astral-sh/uv), a fast Python package manager. If you don't have it:
```bash theme={null}
curl -LsSf https://astral.sh/uv/install.sh | sh
```
***
## Step 3 - Configure the gateway
Create `gateway/.env.local` from the template:
```bash theme={null}
cp gateway/.env.example gateway/.env.local
```
Open it in an editor. Fill in:
```bash gateway/.env.local theme={null}
# One bearer token the caller must send to talk to the gateway.
# Generate a strong one:
# openssl rand -base64 32 | tr -d '=' | tr '+/' '-_'
# Paste the output here:
GATEWAY_API_KEY=
# The planner AI
OPENROUTER_API_KEY=sk-or-v1-
# Gateway listens here (these are optional — defaults shown)
GATEWAY_PORT=3774
GATEWAY_HOSTNAME=0.0.0.0
```
And `examples/.env` (used by the sample Python agents - the file already exists, you just add the key):
```bash examples/.env theme={null}
OPENROUTER_API_KEY=sk-or-v1-
```
**What's a "bearer token"?**
Think of `GATEWAY_API_KEY` like the password on a movie ticket booth. Whoever holds this string can ask the gateway to do work on their behalf. The gateway checks it on every request by hashing both sides and comparing the hashes in constant time (so neither a timing nor a length attack can recover the token). Don't paste it into chat apps or commit it to a public repo. Rotate it when you suspect it leaked.
You may notice old `SUPABASE_URL` / `SUPABASE_SERVICE_ROLE_KEY` lines in `.env.example`. Leave them blank — the gateway no longer reads them. See [`gateway/src/config/loader.ts:110`](https://github.com/GetBindu/Bindu/blob/main/gateway/src/config/loader.ts#L110) for the explicit removal note in the code.
***
## Step 4 - Start one agent
Open a terminal. Start the joke agent — one Python file that answers with jokes. We pin the port to 3773 with `BINDU_PORT` so it matches the next chapter's fleet layout (the file's own default is 5773):
```bash theme={null}
BINDU_PORT=3773 uv run python examples/gateway_test_fleet/joke_agent.py
```
The boot prints a block of `bindufy` setup logs. The last line you should see is:
```
INFO bindu.utils.server_runner: Starting uvicorn server at http://0.0.0.0:3773...
INFO bindu.utils.server_runner: Press Ctrl+C to stop the server gracefully
INFO: Uvicorn running on http://0.0.0.0:3773 (Press CTRL+C to quit)
```
Leave that terminal running.
***
## Step 5 - Start the gateway
In a **second** terminal:
```bash theme={null}
cd gateway
npm run dev
```
Expected output:
```
[bindu-gateway] no DID identity configured (set BINDU_GATEWAY_DID_SEED, _AUTHOR, _NAME to enable did_signed peer auth)
[bindu-gateway] listening on http://0.0.0.0:3774
[bindu-gateway] session mode: stateless
```
The *"no DID identity configured"* line is expected for now. The [DID signing chapter](/bindu/gateway/identity) turns on cryptographic signing. `session mode: stateless` is the only mode in the current gateway — the `mode` field is kept on the schema for forward-compat but `stateful` is rejected at boot. Leave this terminal running too.
***
## Step 6 - Ask a question
In a **third** terminal, load your gateway token into the shell so you don't have to copy-paste it every time:
```bash theme={null}
set -a && source gateway/.env.local && set +a
```
Now send the request:
```bash theme={null}
curl -N http://localhost:3774/plan \
-H "Authorization: Bearer ${GATEWAY_API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"question": "Tell me a joke about databases.",
"agents": [
{
"name": "joke",
"endpoint": "http://localhost:3773",
"auth": { "type": "none" },
"skills": [{ "id": "tell_joke", "description": "Tell a joke" }]
}
]
}'
```
The `-N` flag tells curl not to buffer - you'll see output appear one line at a time over about 5 seconds.
Expected stream (a few fields like `agent_did`, `agent_did_source`, and `signatures` are elided for readability — they're documented in the [Gateway API reference](/gateway-api/introduction)):
```
event: session
data: {"session_id":"8f3c4a1e-...","external_session_id":null,"created":true}
event: plan
data: {"plan_id":"b21e7c98-...","session_id":"8f3c4a1e-..."}
event: task.started
data: {"task_id":"call_01H...","agent":"joke","skill":"tell_joke","input":{"input":"Tell me a joke about databases."}}
event: task.artifact
data: {"task_id":"call_01H...","agent":"joke","content":"Why did the database admin break up? Because they had too many relationships!"}
event: task.finished
data: {"task_id":"call_01H...","agent":"joke","state":"completed"}
event: text.delta
data: {"session_id":"8f3c4a1e-...","part_id":"c9d2f60a-...","delta":"Here"}
event: text.delta
data: {"session_id":"8f3c4a1e-...","part_id":"c9d2f60a-...","delta":"'s a joke..."}
... (many more deltas) ...
event: final
data: {"session_id":"8f3c4a1e-...","stop_reason":"stop","usage":{"inputTokens":1130,"outputTokens":52,"totalTokens":1182,"cachedInputTokens":0}}
event: done
data: {}
```
**You made a plan.** 🎉
***
## Reading the output line by line
That format is called **Server-Sent Events** (SSE). It's plain HTTP, but the server keeps the connection open and writes events one at a time instead of sending one big response at the end. Two parts per event: a label (`event: session`) and a JSON payload (`data: {...}`).
What each event means, in the order they arrived:
| # | Event | What it means |
| - | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1 | `session` | The gateway opened an in-memory session for this `/plan` call. `session_id` is a per-call handle; `external_session_id` echoes whatever the client sent (or `null`). Since the gateway is stateless, this id is *not* a resumption key — to give the planner context across requests, pass prior turns via the `history` field on each call. |
| 2 | `plan` | The planner started its first turn. |
| 3 | `task.started` | The planner decided to call the joke agent. `input: {input: "..."}` is what it's sending. |
| 4 | `task.artifact` | The agent replied. The text inside `` is the real answer. That envelope is there so the planner (and you) remember this is *untrusted* data. The `verified` attribute takes one of four values — `yes`, `no`, `unsigned`, `unknown` — and is `unknown` here because the request didn't ask the gateway to verify peer signatures. Verification is opt-in per peer via the agent's `trust.verifyDID: true` flag (with an optional `trust.pinnedDID`) — it is **independent of `auth.type`**, which controls how the gateway authenticates outbound to the peer. Once `trust.verifyDID` is on, the label becomes `yes` (signed and verified), `no` (signature mismatch), or `unsigned` (the peer didn't sign). |
| 5 | `task.finished` | That call is complete. |
| 6 | `text.delta` (many) | The planner is now writing its own final answer, streamed a word or two at a time. Concatenate them in order (they all share a `part_id`). |
| 7 | `final` | Done. `stop_reason: "stop"` means "natural end". `usage` reports token counts for billing. |
| 8 | `done` | Last event. Close the connection. |
You may also see one more event on long conversations:
| Event | When | Meaning |
| -------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `compaction-summary` | Mid-stream, zero or one per call | The planner ran out of context window, compacted history into a summary. Persist the `summary` field client-side and ship it back as `prior_summary` on the next `/plan` call. |
***
## What's actually running
You now have three things talking to each other:
```mermaid theme={null}
flowchart LR
subgraph Client
A[curl]
end
subgraph Gateway
B[Bindu Gateway
in-memory state]
end
subgraph Services
C[OpenRouter]
end
subgraph Agent
E[joke_agent.py]
end
A -->|POST /plan| B
B -->|SSE stream| A
B -->|Planner LLM| C
B -->|A2A| E
```
The gateway is a **coordinator**. It doesn't answer the question itself; it picks an agent, sends the question, gets the reply, writes a final summary using its own planner LLM. It also doesn't persist anything — when the `/plan` call ends, the session is gone.
If this is the moment the idea clicks - great. Next we'll add a second agent so the gateway has a real choice to make: **[Adding a second agent →](/bindu/gateway/multi-agent)**
Gateway is stateless -
the client owns history.
# Recipes - Teaching Patterns
Source: https://docs.getbindu.com/bindu/gateway/recipes
Write a playbook once in plain markdown. The planner lazy-loads it when it recognizes a match.
The three-agent chain from the [previous chapter](/bindu/gateway/multi-agent) worked because the planner figured the plan out from scratch. That's fine once - but let's say your team keeps asking the same class of question:
> *"Research this, compute some percentage of it, write a poem about the result."*
Every plan the planner re-derives the same steps. You pay for the LLM time every time.
What if you could write the plan down *once*, in plain markdown, and have the planner load it on demand when it recognizes a match?
That's a **recipe**.
***
## The core idea: progressive disclosure
You could try solving this by dumping a big *"how to coordinate these agents"* paragraph into the planner's system prompt. Fine for one pattern. Doesn't scale - after 20 patterns, your system prompt is 20,000 tokens and the planner is paying to read it all on every request, even the ones that don't need any of them.
Recipes fix this with a technique called **progressive disclosure**. At every turn the planner sees:
* The *name* and *one-line description* of every recipe - cheap, a few hundred tokens even for dozens of recipes.
* A tool called `load_recipe({name})` in its toolbox.
Only when the planner recognizes a match does it call `load_recipe`. The tool's reply is the full recipe body - typically a 2–3 KB markdown playbook - injected into the conversation. The planner then follows the body for the rest of the turn.
You paid for the body's tokens exactly once per plan, and only when the recipe was actually relevant.
***
## Your first recipe
Let's write one. Create a file at `gateway/recipes/research-math-poem/RECIPE.md`:
```markdown gateway/recipes/research-math-poem/RECIPE.md theme={null}
---
name: research-math-poem
description: Research a factual number, compute a percentage of it, and write a short poem about the result. Load when the user asks a three-part question combining research, arithmetic, and creative writing.
tags: [research, math, creative]
triggers: [research and compute, percentage poem, population percent]
---
# Recipe: research-math-poem
Use this when the user's question has three distinct phases:
1. A factual lookup (population, revenue, distance, etc.)
2. A percentage or fraction applied to that number
3. A short creative response about the result
## Flow
1. **Research.** Call `call_research_web_research` with the user's exact
factual question. Don't translate or summarize it.
2. **Extract the number.** In your own reasoning (not as a tool call),
pull the headline figure from the research reply. Prefer the
*headline* number the user asked about, not incidental figures.
3. **Compute.** Call `call_math_solve` with the computation stated
explicitly: "Compute 0.5% of 36,950,000". Don't ask the math agent
to interpret - give it the exact expression.
4. **Create.** Call `call_poet_write_poem` with the computed number
and the user's creative framing (line count, mood, subject).
5. **Respond.** Write a final message that shows all three steps
briefly and ends with the poem.
## Constraints
- **Do not parallelize** the calls. The math depends on the research;
the poem depends on the math.
- **Do not invent the number** if research returns ambiguous output.
Ask the user to clarify which population/revenue/etc. they mean.
- **Do not skip the poem** if the user asked for one. If
`call_poet_write_poem` fails, surface the failure; don't silently
produce prose.
```
***
## Watching it load
Restart the gateway (Ctrl+C in its terminal, `npm run dev` again). The loader scans `gateway/recipes/` once at boot and caches the result — there is no per-request reload. To confirm yours was picked up, hit `/health`:
```bash theme={null}
curl -s http://localhost:3774/health | jq '.runtime.recipe_count'
```
```
3
```
Three because two recipes ship with the gateway by default — `multi-agent-research` and `payment-required-flow` (see [`gateway/recipes/`](https://github.com/GetBindu/Bindu/tree/main/gateway/recipes)) — plus your new one. If the count didn't go up, double-check the file path and frontmatter.
Now fire the same three-agent question from the previous chapter. In the SSE stream you should see an extra event early on:
```
event: task.started
data: {"task_id":"call_xyz...","agent":"load_recipe","skill":"","input":{"name":"research-math-poem"}}
event: task.artifact
data: {"task_id":"call_xyz...","content":"\n# Recipe: research-math-poem\n\nUse this when the user's question has three distinct phases: ..."}
event: task.finished
data: {"task_id":"call_xyz...","state":"completed"}
```
The planner recognized the match, called `load_recipe`, and now has your playbook in context. The rest of the plan - research, math, poet - follows the recipe.
***
## Does it actually change behavior?
Sometimes yes, sometimes no. The planner was already good at this class of question; the recipe mostly *pins the behavior* (forces the specific tool order, specific call shapes) rather than enabling something new.
Where recipes shine:
A recipe that says *"if you see `state: payment-required`, surface the payment URL to the user and STOP - do not retry"* is a policy the planner wouldn't invent on its own.
A recipe visible only to a certain agent can encode rules like *"always include a disclaimer"* or *"always call the compliance agent first."*
A recipe describing a 5-step workflow is a document your team can review, version, and reason about. Inline planner reasoning isn't.
See `gateway/recipes/payment-required-flow/RECIPE.md` in the repo for a real-world example of edge-case handling.
***
## Recipe layouts
Two supported shapes:
```
gateway/recipes/foo.md
```
A single markdown file. No bundled siblings. Good for short playbooks.
```
gateway/recipes/bar/RECIPE.md
gateway/recipes/bar/scripts/run.sh
gateway/recipes/bar/reference/notes.md
```
A directory with a `RECIPE.md` plus sibling files. Useful when the recipe refers to reference material or needs ship-alongside scripts. Siblings under `scripts/` and `reference/` are surfaced to the planner automatically.
When the planner loads a bundled recipe, the `load_recipe` tool result includes a `` listing of the sibling files (capped at 10 for token sanity). The planner can refer to them by relative path in its response or follow instructions in the body like *"run `scripts/validate.sh` before responding."*
***
## Frontmatter reference
```yaml theme={null}
---
name: unique-identifier # required; cannot start with "call_"
description: one-line summary # required (non-empty) - this is the hook
tags: [tag1, tag2] # optional; surfaced in verbose listings
triggers: [phrase, phrase] # optional; planner hints (not enforced)
---
```
Two rules the loader enforces:
Duplicate recipe names cause boot to fail with a clear error - silent precedence would make behavior depend on filesystem order.
Planner tool ids look like `call_agent_skill`; a recipe named `call_anything` would visually collide in the `load_recipe` tool description. Rejected at load time.
***
## Per-agent recipe visibility
The gateway's agent configs (in `gateway/agents/*.md`) have a `permission:` block. You can use it to scope recipes:
```yaml gateway/agents/planner.md theme={null}
permission:
recipe:
"internal-*": "deny" # this agent can't load recipes matching "internal-*"
"*": "allow" # everything else is fine
```
The planner only sees (and can only load) recipes matching its allowed patterns. Default is `allow` - agents with no `recipe:` rules see everything.
***
## The full authoring loop
Either `gateway/recipes/.md` or `gateway/recipes//RECIPE.md`.
The loader scans on boot (no hot reload yet).
Use the exact phrasing your users will use.
That's the planner saying *"I recognized this pattern."*
That's what the planner reads. Add specific keywords the user question likely contains.
Recipes are the single highest-leverage operator tool in the gateway. Spend an afternoon writing five for your common question shapes and you'll notice your planner's behavior firming up across the board.
Next: give the gateway a cryptographic identity and start signing outbound calls. **[DID signing →](/bindu/gateway/identity)**
Write the pattern once -
then planner loads it when it’s needed.
# Config reference
Source: https://docs.getbindu.com/bindu/get-started/config-reference
Every key in the bindufy config dict, what it does, and the env var that overrides it.
The `config` dict you hand to `bindufy()` is the whole settings surface. Four keys are required (three at the top level plus `deployment.expose`). The rest have defaults that work for `localhost`, and env-var overrides for when you ship.
## The required keys
The top-level [validator](https://github.com/getbindu/Bindu/blob/main/bindu/penguin/config_validator.py) checks three fields. A fourth, `deployment.expose`, is required by the deployment builder ([bindufy.py:332](https://github.com/getbindu/Bindu/blob/main/bindu/penguin/bindufy.py)) once `deployment` is present.
```python theme={null}
config = {
"author": "you@example.com",
"name": "research_agent",
"deployment": {
"url": "http://localhost:3773",
"expose": False, # required (no default); declares intent only — real tunnel is launch=True
},
}
```
| Key | What it does |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `author` | Goes into your agent's DID. Sanitized (`@` → `_at_`, `.` → `_`) so the DID stays URL-safe. Use the email you'd be okay seeing in another team's logs. |
| `name` | The human-readable slug. Also sanitized into the DID. |
| `deployment.url` | Where the agent listens. Must be a valid http(s) URL — validated via `urlparse`. |
| `deployment.expose` | Required (no default). Declares intent — `True` means the agent is meant to be publicly reachable, `False` means local-only. **Note**: the FRP public tunnel is actually opened by passing `launch=True` to `bindufy(config, handler, launch=True)`, not by this flag. `expose` is currently a placeholder for future trust-level signaling. |
Miss `author`, `name`, or `deployment.url` and the config validator raises `ConfigError: '' is a required field in the agent configuration.` with an example config attached. Miss `deployment.expose` (when a `deployment` block is present) and the deployment builder raises `ValueError: Missing required config field(s): deployment.expose` — different error class, different message format.
## The keys you'll actually touch
Everything below has a sensible default (taken from
[`ConfigValidator.DEFAULTS`](https://github.com/getbindu/Bindu/blob/main/bindu/penguin/config_validator.py)).
You override when you care.
```python theme={null}
config = {
# ...required keys above...
"description": "Research assistant with web search.",
"version": "1.0.0",
"deployment": {
"url": "http://localhost:3773",
"expose": True, # required; declares public-facing intent (tunnel comes from launch=True)
"cors_origins": ["http://localhost:5173"], # for the inbox UI or your frontend
},
"skills": ["skills/question-answering"], # see /bindu/skills/introduction/overview
"capabilities": {"push_notifications": True}, # webhook on task state change
"telemetry": True, # on by default; set False to opt out
}
```
| Key | Default | What it does |
| --------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `description` | `"A Bindu agent"` | Shown on the agent card. Other agents see this when they discover you. |
| `version` | bindu package version (`__version__`) | Your agent's version, not Bindu's. Bump it like you would any service. |
| `deployment.cors_origins` | `None` | Allowed origins for the HTTP server. Add your frontend here. |
| `skills` | `[]` | Folder paths to skill manifests. See [Skills](/bindu/skills/introduction/overview). |
| `private_skills` | `[]` | Private skill manifests — served from `/agent/private.json` behind Hydra auth, visible only to DIDs in `allowed_dids`. |
| `allowed_dids` | `[]` | DIDs allowed to see `private_skills` / call your agent under Hydra admission control. |
| `capabilities.push_notifications` | absent (= `False`) | Lets callers register webhooks so they can stop polling. |
| `capabilities.streaming` | absent (= `False`) | Server-Sent Events on `message/stream`. |
| `telemetry` | `True` | OpenTelemetry traces on. Set `False` to opt out, or override with `TELEMETRY_ENABLED=false` env var. |
| `agent_trust` | `None` | Trust-level config; see [DIDs](/bindu/learn/did/overview). |
| `execution_cost` | `None` | Per-call price (a dict or list of dicts). Setting this activates the x402 payment middleware — see [Payment](/bindu/learn/payment/introduction). |
## Storage and scheduler — set these via env
Putting database credentials in a Python dict is how secrets end up in git. The
[env-enricher](https://github.com/getbindu/Bindu/blob/main/bindu/utils/config/enricher.py)
fills these in for you when `storage` / `scheduler` aren't already in the config dict.
```bash theme={null}
# Storage — pick one
STORAGE_TYPE=memory # default; lost on restart
STORAGE_TYPE=postgres
DATABASE_URL=postgres://user:pass@host:5432/db # required when STORAGE_TYPE=postgres
# Scheduler — pick one
SCHEDULER_TYPE=memory # default; single-process
SCHEDULER_TYPE=redis
REDIS_URL=redis://localhost:6379/0 # required when SCHEDULER_TYPE=redis
```
Bindu refuses to start if `STORAGE_TYPE=postgres` but `DATABASE_URL` is unset (same for `SCHEDULER_TYPE=redis` / `REDIS_URL`) — no silent fallback to memory.
Local dev: leave both unset, you get in-memory. Production: set both, you get persistence and distributed task queues. Same `bindufy(config, handler)` either way.
Deeper guides: [Storage](/bindu/learn/storage/overview), [Scheduler](/bindu/learn/scheduler/overview).
## Auth, payments, and the rest
These are off by default. Turn them on when you need them — each one has its own page that goes deeper than this reference should.
| Feature | How you turn it on | Docs |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ |
| **OAuth2 (Hydra)** | Either path works: (1) put it in your config — `"auth": {"enabled": True, "provider": "hydra", "admin_url": "...", "public_url": "..."}` is applied to `app_settings.auth` and `app_settings.hydra` via [`prepare_auth_settings`](https://github.com/getbindu/Bindu/blob/main/bindu/utils/config/settings.py); (2) or use env vars `AUTH__ENABLED=true`, `HYDRA__ADMIN_URL=...`, `HYDRA__PUBLIC_URL=...` ([HydraSettings](https://github.com/getbindu/Bindu/blob/main/bindu/settings.py)). | [Authentication](/bindu/learn/authentication/overview) |
| **x402 payments** | Add `"execution_cost": {...}` to the config dict — the middleware activates when execution\_cost is present and produces payment requirements ([applications.py:686](https://github.com/getbindu/Bindu/blob/main/bindu/server/applications.py)). Env vars `X402__FACILITATOR_URL`, `X402_PAY_TO` configure it further. | [Payment](/bindu/learn/payment/introduction) |
| **OpenTelemetry** | On by default (`telemetry: True`). Send traces by setting env vars `OLTP_ENDPOINT=...`, optionally `OLTP_SERVICE_NAME`, `OLTP_HEADERS='{"Authorization":"..."}'`. Turn off with `TELEMETRY_ENABLED=false`. | [Observability](/bindu/learn/observability/overview) |
| **Sentry** | Env: `SENTRY_ENABLED=true`, `SENTRY_DSN=...` | [Observability](/bindu/learn/observability/overview) |
| **Private skills** | `"private_skills": [...]`, `"allowed_dids": [...]` | (Skills page covers it) |
| **Agent trust** | `"agent_trust": {...}` | [DIDs](/bindu/learn/did/overview) |
The pattern is consistent: feature lives in `config` if it's about agent identity or behavior, in env vars if it's about infrastructure or secrets.
## The "okay show me everything" example
Most production agents look something like this:
```python theme={null}
config = {
"author": "team@yourco.io",
"name": "research_agent",
"description": "Research assistant with web search and PDF Q&A.",
"version": "1.2.0",
"deployment": {
"url": "https://research.yourco.io",
"expose": False, # local-only intent — real DNS in prod, no FRP tunnel
"cors_origins": ["https://app.yourco.io"],
},
"capabilities": {
"push_notifications": True,
"streaming": True,
},
"skills": [
"skills/question-answering",
"skills/pdf-processing",
],
"auth": {
"enabled": True,
"provider": "hydra",
},
# telemetry is True by default; OTel endpoint comes from env (OLTP_ENDPOINT).
}
```
Everything else — storage, scheduler, Hydra URLs, OLTP endpoint, x402 facilitator — comes from env vars at deploy time. The dict stays small and your secrets stay out of git. You did not write the validator; the validator wrote you a useful error message instead.
## What you can't put in here
`config` is for static settings. If you're trying to:
* pass dynamic state per request → use the handler's `messages` arg
* share data between handler invocations → use [Storage](/bindu/learn/storage/overview), not module-level globals
* override behavior at runtime → you probably want a [skill](/bindu/skills/introduction/overview), not a config key
If you find yourself wanting a config key that isn't here, [open an issue](https://github.com/getbindu/Bindu/issues) — half the time it's already in `bindu/penguin/config_validator.py` under a name we forgot to document. The other half it's a real feature gap and we want to know.
# What's next
Source: https://docs.getbindu.com/bindu/get-started/next-steps
You have a live agent. Here's the order to read the rest of the docs in, depending on what you're trying to do.
Your agent is online. You sent it a message. It came back with a DID-signed response. Now what?
The honest answer is "depends what you're building." Here are the four paths the docs are organized around.
## I want to ship this to other humans
Real users, real domain, real uptime. Read in this order:
1. **[Install](/bindu/how-to/install)** — `uv add bindu` was for your laptop. Production wants `uv sync`, a venv, and a `.env` file.
2. **[Storage](/bindu/learn/storage/overview)** — switch from in-memory to Postgres so a restart doesn't eat your tasks.
3. **[Scheduler](/bindu/learn/scheduler/overview)** — switch from in-memory to Redis when you want more than one process.
4. **[Authentication](/bindu/learn/authentication/overview)** — Hydra OAuth2. Stop running open to the internet.
5. **[Observability](/bindu/learn/observability/overview)** — OpenTelemetry traces, Sentry errors. The boring stuff that saves you at 2am.
If you only do two of these, do storage and auth. Everything else can wait until you have users.
## I want this agent to talk to other agents
That's the whole point of A2A. Read these:
1. **[Skills](/bindu/skills/introduction/overview)** — declare what your agent can do so other agents can find it without guessing.
2. **[DIDs](/bindu/learn/did/overview)** — how callers verify the response really came from you, and how you verify them back.
3. **[Gateway](/bindu/gateway/overview)** — when you want a planner LLM to route a question across a fleet of agents.
4. **[Negotiation](/bindu/learn/negotiation/overview)** — when two agents need to agree on price and SLA before doing the work.
5. **[Notifications](/bindu/learn/notification/overview)** — webhook your caller when a long task finishes. Stop polling.
## I want this agent to take money
x402, USDC, EVM. Bindu was partly built for this.
1. **[Payment](/bindu/learn/payment/introduction)** — the protocol, the chains supported, the wallet config.
2. **[DIDs](/bindu/learn/did/overview)** if you skipped it — payment without identity is just a tip jar.
The shortest path is `examples/premium-advisor` in the repo. Caller hits the agent, gets a `402 Payment Required` with an invoice, pays in USDC, hits again with the receipt, gets the answer. End to end in 90 lines.
## I want to build this in TypeScript / Kotlin / something else
You don't have to write Python. Bindu has a [polyglot gRPC core](/bindu/grpc/overview).
1. **[gRPC overview](/bindu/grpc/overview)** — why the sidecar exists, how the two halves talk.
2. **[gRPC quickstart](/bindu/grpc/quickstart)** — the TypeScript-side equivalent of `your-first-agent`.
3. **[Building a custom SDK](/bindu/grpc/custom-sdks)** — for the language we don't ship yet. Usually a few hundred lines.
Same DID, same A2A protocol, same payment rails. The language is your choice.
## I'm stuck
The errors you'll hit are almost always one of these:
* **`address already in use` on `:3773`** — another Bindu agent is already running. `lsof -ti:3773 | xargs kill`.
* **`OPENAI_API_KEY not set`** — `.env` file isn't being loaded. Add `from dotenv import load_dotenv; load_dotenv()` at the top of your script. (`env_file` appears in the `bindufy()` docstring but is not actually wired up — call `load_dotenv` yourself.)
* **`ConfigError: 'author' is a required field in the agent configuration.`** — you typoed the key, or are missing one of `author` / `name` / `deployment.url` / `deployment.expose`. Re-read [Config reference](/bindu/get-started/config-reference).
* **`ConfigError: 'deployment.url' must be a valid http(s) URL, got '...'`** — your URL is missing the scheme or netloc. `urlparse` rejects anything not `http://`/`https://` with a host.
* **`DATABASE_URL environment variable is required when STORAGE_TYPE=postgres`** — you opted into Postgres without giving it a connection string. Either set `DATABASE_URL` or drop `STORAGE_TYPE=postgres` to fall back to memory.
* **Tunnel not working** — `expose: True` needs outbound 443 open. Behind a corporate firewall this won't fly. Use `expose: False` and a real domain.
Beyond that:
* [GitHub Issues](https://github.com/getbindu/Bindu/issues) for bugs and feature requests.
* [Discord](https://discord.gg/3w5zuYUuwt) for "is this supposed to work like this" questions. Maintainers hang out there.
* [Examples folder](https://github.com/getbindu/Bindu/tree/main/examples) — 30+ working agents covering most patterns. When in doubt, find the one closest to what you're building and steal the config.
That's the whole map. Pick a row, read it, ship something. One sunflower at a time.
# Your first agent
Source: https://docs.getbindu.com/bindu/get-started/your-first-agent
Copy 20 lines of Python, run it, watch your agent come online with a DID, an A2A endpoint, and an agent card other agents can discover.
Here's the deal. You've got `bindu` installed and an `OPENAI_API_KEY` in `.env` (or exported in your shell). The block below is the whole thing — copy it into `agent.py`, run it, and 60 seconds later you have a live agent at `http://localhost:3773`.
```python theme={null}
from dotenv import load_dotenv
from bindu.penguin.bindufy import bindufy
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.duckduckgo import DuckDuckGoTools
load_dotenv() # picks up OPENAI_API_KEY from .env
agent = Agent(
instructions="You are a research assistant.",
model=OpenAIChat(id="gpt-4o"),
tools=[DuckDuckGoTools()],
)
config = {
"author": "you@example.com",
"name": "research_agent",
"description": "Research assistant with web search.",
"deployment": {"url": "http://localhost:3773", "expose": True},
}
def handler(messages: list[dict[str, str]]):
return agent.run(input=messages)
bindufy(config, handler)
# To put it on the public internet via FRP:
# bindufy(config, handler, launch=True)
```
```bash theme={null}
uv run agent.py
```
You should see a sunflower in your terminal and a DID that looks like `did:bindu:you_at_example_com:research_agent:`. The `@` and `.` in your email get sanitized to `_at_` and `_` ([source](https://github.com/getbindu/Bindu/blob/main/bindu/extensions/did/did_agent_extension.py)) so the DID stays URL-safe. That's your agent. It's online.
## What just happened
Four things are doing work in those 20 lines. None of them are infrastructure you had to write.
**`agent`** is your brain. Agno here, but it could be LangChain, CrewAI, a bare OpenAI call, or your own loop. Bindu doesn't care — it never opens the box.
**`config`** is the agent's passport. The `author` and `name` get baked into a [DID](/bindu/learn/did/overview) — a cryptographic identity nobody can fake. The `deployment.expose` key is **required** (not optional): it declares whether the agent is intended to be publicly reachable (`True`) or local-only (`False`). The actual public-internet tunnel is opened by passing `launch=True` to `bindufy()` — see the commented line in the snippet.
**`handler`** is the function the rest of the world will call. It gets a list of messages, returns a response. That's the entire contract.
**`bindufy(config, handler)`** wires it all up. Behind it: A2A JSON-RPC routing, DID key generation, Ed25519 signatures on every response, OAuth2 scopes, x402 payment hooks, an A2A-compliant HTTP server on `:3773`, an optional FRP tunnel when you pass `launch=True`, and an agent card at `/.well-known/agent.json` so other agents can discover you. You did not write any of that. You're welcome.
## Try it
Open another terminal and send your agent a message:
```bash theme={null}
curl -X POST http://localhost:3773/ \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"method": "message/send",
"id": "1",
"params": {
"message": {
"role": "user",
"kind": "message",
"parts": [{"kind": "text", "text": "What is x402?"}],
"messageId": "m1",
"contextId": "c1",
"taskId": "t1"
}
}
}'
```
You get back a `taskId`. Poll `tasks/get` with it until `state` hits `completed`, and the answer comes out with a DID signature attached. Anyone on the network can verify it really came from your agent.
## Make it yours
Three things you can change in under a minute:
1. **Swap the prompt.** Change `instructions=` to whatever your agent actually does. Restart.
2. **Swap the model.** Replace `OpenAIChat(id="gpt-4o")` with `OpenRouter(id="openai/gpt-oss-120b")`, set `OPENROUTER_API_KEY` in `.env`. Done — every agent built on Bindu in the wild is on something like this.
3. **Add a tool.** Pile more into `tools=[...]`. The agent will figure out when to call them.
## What's next
You have a working agent. The interesting stuff starts when you give it a real job and connect it to others.
* **[Config reference](/bindu/get-started/config-reference)** — every key in that `config` dict, what it does, what env var overrides it.
* **[Skills](/bindu/skills/introduction/overview)** — declare what your agent can do so other agents can find it without guessing.
* **[Gateway](/bindu/gateway/overview)** — point a planner at a fleet of agents and let it route work between them.
* **[Examples](/examples/beginner/echo-agent)** — 30+ agents in this repo doing real things. CSV analysis, PDF Q\&A, cybersecurity newsletters, multi-agent swarms.
One sunflower at a time. Welcome to the agent internet.
# Agent Implementation
Source: https://docs.getbindu.com/bindu/grpc/agent-client
Handler patterns, state transitions, configuration, and how the bridge works under the hood
Your agent is running. Now the question is: what should it actually do?
This page covers the practical side of building with the sidecar. You will learn how to write handler functions, manage multi-turn conversations, configure your agent, define skills, and — if you are curious — understand exactly how the core talks to your code under the hood.
***
## Handler Patterns
The handler is the only code you write. Everything else — identity, auth, protocol, storage — lives in the sidecar. So let's start with the different shapes a handler can take.
### Simple Response
The simplest possible handler returns a string. The sidecar wraps it in an A2A response, signs it with your DID, and sends it back to the caller.
```typescript theme={null}
async (messages) => {
return "The answer is 42.";
}
```
### OpenAI SDK
Most agents will call an LLM. Here is the pattern with the OpenAI SDK — you receive the conversation history, pass it to the model, and return the result.
```typescript theme={null}
import OpenAI from "openai";
const openai = new OpenAI();
async (messages) => {
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: messages.map(m => ({
role: m.role as "user" | "assistant" | "system",
content: m.content,
})),
});
return response.choices[0].message.content || "";
}
```
### LangChain.js
If you prefer LangChain, the pattern is the same — only the LLM client changes. The sidecar does not care which framework you use inside the handler.
```typescript theme={null}
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({ model: "gpt-4o" });
async (messages) => {
const response = await llm.invoke(
messages.map(m => ({ role: m.role, content: m.content }))
);
return typeof response.content === "string"
? response.content
: JSON.stringify(response.content);
}
```
### Error Handling
If your handler throws, the SDK catches it and returns a gRPC error. `ManifestWorker` marks the task as failed. You do not need to build your own error plumbing — just let exceptions propagate naturally.
```typescript theme={null}
async (messages) => {
try {
return await myLlmCall(messages);
} catch (err) {
throw err;
}
}
```
***
## State Transitions
Sometimes a single response is not enough. Your handler can return two kinds of things: a string (which completes the task) or an object that tells the core to keep the conversation open.
### Multi-Turn Conversation
Instead of returning a simple string, return an object with `state: "input-required"`. This pauses the task and prompts the user for more information. When they reply, your handler is called again with the full conversation history.
```typescript theme={null}
async (messages) => {
if (messages.length === 1) {
return {
state: "input-required",
prompt: "Could you be more specific about what you're looking for?"
};
}
const lastMessage = messages[messages.length - 1].content;
return `Based on your clarification: here's the detailed answer about "${lastMessage}"...`;
}
```
### The Response Contract
Everything downstream depends on this contract. The transport can change, but the return types cannot.
| Handler returns | ManifestWorker does | Task state |
| ----------------------------------------------------------- | -------------------------------- | ---------------- |
| `"The capital of France is Paris."` | Creates message + artifact | `completed` |
| `{"state": "input-required", "prompt": "Can you clarify?"}` | Creates message, keeps task open | `input-required` |
| `{"state": "auth-required"}` | Creates message, keeps task open | `auth-required` |
The sidecar processes all three return shapes the same way regardless of whether the handler is Python, TypeScript, or Kotlin. That is the bigger pattern: the sidecar changes the transport, not the behavior contract.
***
## Adding Payments
If you want to charge for your agent's responses, add an `execution_cost` to the config. The sidecar handles the x402 payment protocol — your handler code does not change at all.
```typescript theme={null}
bindufy(
{
author: "dev@example.com",
name: "premium-agent",
deployment: { url: "http://localhost:3773", expose: true },
execution_cost: {
amount: "1000000",
token: "USDC",
network: "base-sepolia",
pay_to_address: "0xYourWalletAddress",
},
},
async (messages) => {
return "Premium response!";
}
);
```
***
## Configuration
The `bindufy()` config object is how you tell the sidecar what kind of microservice to build around your handler. Most fields are optional — the only required ones are `author`, `name`, and `deployment`.
```typescript theme={null}
bindufy({
author: "dev@example.com",
name: "my-agent",
deployment: {
url: "http://localhost:3773",
expose: true,
cors_origins: ["http://localhost:5173"],
},
description: "What my agent does",
version: "1.0.0",
skills: ["skills/question-answering"],
execution_cost: {
amount: "1000000",
token: "USDC",
network: "base-sepolia",
},
capabilities: {
streaming: false,
push_notifications: false,
},
coreAddress: "localhost:3774",
callbackPort: 0,
debug_mode: false,
telemetry: true,
num_history_sessions: 10,
}, handler);
```
***
## Skills
Skills describe what your agent can do. The sidecar reads them during startup and includes them in the agent card so other agents and clients can discover your capabilities.
### File-Based (Recommended)
Point to directories containing `skill.yaml` or `SKILL.md` files. The SDK reads them and sends the content to the core during registration.
```typescript theme={null}
bindufy({
skills: ["skills/question-answering", "skills/code-review"],
}, handler);
```
### Inline
You can also define skills directly in the config if you prefer to keep everything in one file.
```typescript theme={null}
bindufy({
skills: [{
name: "question-answering",
description: "Answer questions using GPT-4o",
tags: ["qa", "assistant"],
}],
}, handler);
```
***
## Types
The SDK exports the key types your handler works with. These are the shapes you will see most often.
```typescript theme={null}
interface ChatMessage {
role: string;
content: string;
}
type MessageHandler = (messages: ChatMessage[]) => Promise;
interface HandlerResponse {
content?: string;
state?: "input-required" | "auth-required";
prompt?: string;
metadata?: Record;
}
interface RegistrationResult {
agentId: string;
did: string;
agentUrl: string;
}
```
***
## What Happens When You Call `bindufy()`
Now that you know how to write handlers, let's look at what happens when `bindufy()` runs. You do not need to know this to use Bindu — but understanding the lifecycle makes debugging easier and gives you a clearer mental model of the system.
Loads yaml/markdown skill files from disk.
On a random port. This is where the core will call your handler.
As a child process.
Polls with TCP connect, 30s timeout.
With your config, skills, and callback address.
DID, auth, x402, manifest, HTTP server.
Registration complete.
Every 30 seconds in the reference TS SDK; the cadence is an SDK convention
rather than a core-enforced one.
Agent is ready.
***
## How the Bridge Works Under the Hood
If you are curious about what happens between the core receiving a message and your handler being called, this section explains the internal bridge. You do not need this to build agents, but it helps if you are debugging transport issues or building a [Custom SDK](/bindu/grpc/custom-sdks).
### The GrpcAgentClient
Inside the core, one component keeps the sidecar model elegant: `GrpcAgentClient`. It is a Python class that behaves like a function. `ManifestWorker` calls it the same way it would call a native Python handler:
```python theme={null}
raw_results = self.manifest.run(message_history or [])
```
For a Python agent, `manifest.run` is a wrapper around the developer's handler function. For a gRPC agent, `manifest.run` is assigned a `GrpcAgentClient` instance. When `ManifestWorker` executes it, Python invokes `GrpcAgentClient.__call__()`, which transparently makes the gRPC call across the boundary.
That is the design win. The sidecar changes the transport, not the downstream architecture. `ResultProcessor`, `ResponseDetector`, and `ArtifactBuilder` all work exactly the same way regardless of whether the handler is local or remote.
### How It Works
Three steps: ensure connection, call the SDK, convert back. That is the entire bridge.
```python theme={null}
class GrpcAgentClient:
def __init__(
self,
callback_address: str,
timeout: float = 30.0,
use_streaming: bool = False,
channel_credentials: grpc.ChannelCredentials | None = None,
) -> None:
self._address = callback_address
self._timeout = timeout
self._use_streaming = use_streaming
self._channel_credentials = channel_credentials
self._channel: grpc.Channel | None = None # lazy-initialized on first call
self._stub: agent_handler_pb2_grpc.AgentHandlerStub | None = None
def _ensure_connected(self) -> None:
# Built with `grpc.secure_channel` when channel_credentials is provided,
# otherwise `grpc.insecure_channel` for same-host SDK setups.
...
def __call__(self, messages, **kwargs):
self._ensure_connected()
# 1. Convert Python dicts to protobuf
proto_msgs = [ChatMessage(role=m["role"], content=m["content"]) for m in messages]
request = HandleRequest(messages=proto_msgs)
# 2. Call the SDK's AgentHandler over gRPC
if self._use_streaming:
return self._handle_streaming(request) # yields a generator
response = self._handle_unary(request)
# 3. Convert back to what ManifestWorker expects
if response.state:
result = {"state": response.state}
if response.prompt:
result["prompt"] = response.prompt
if response.content:
result["content"] = response.content
for key, value in response.metadata.items():
result[key] = value
return result
return response.content
```
Source: [`bindu/grpc/client.py`](https://github.com/getbindu/Bindu/blob/main/bindu/grpc/client.py).
### When It's Created
The bridge gets attached during registration. After this point, every task for the agent flows through it.
From [`bindu/grpc/service.py`](https://github.com/getbindu/Bindu/blob/main/bindu/grpc/service.py):
```python theme={null}
# In BinduServiceImpl.RegisterAgent():
grpc_client = GrpcAgentClient(
callback_address=request.grpc_callback_address,
timeout=app_settings.grpc.handler_timeout,
)
# Then handed to _bindufy_core as the handler:
manifest = _bindufy_core(
config=config,
handler_callable=grpc_client, # ← becomes manifest.run inside create_manifest()
...
)
```
After this point, `manifest.run` is the `GrpcAgentClient` instance. Everything in `ManifestWorker` / `ResultProcessor` / `ResponseDetector` then proceeds as if it were a normal Python handler.
### Connection Lifecycle
The client connects lazily — the gRPC channel is created on the first call, not during initialization. That avoids connection errors during registration if the SDK server is not fully ready yet.
When the SDK disconnects (Ctrl+C, crash), the next `HandleMessages` call fails with `grpc.StatusCode.UNAVAILABLE`. `ManifestWorker`'s existing error handling catches this and marks the task as failed.
### Health Checks and Capabilities
The core can also ask the sidecar whether the driver is still healthy:
```python theme={null}
grpc_client.health_check() # Is the SDK still running? Returns True/False
grpc_client.get_capabilities() # What can the SDK do? Returns name, version, etc.
```
Both methods are available on `GrpcAgentClient` for any caller that needs them
(for example a future capability-discovery sweep). They are **not** invoked from
the current `BinduService.Heartbeat` handler — heartbeats only update the
registry's `last_heartbeat` timestamp.
Current limitations:
* **Streaming** — `use_streaming=True` on `GrpcAgentClient` calls `HandleMessagesStream`,
which is fine in the proto. No shipped SDK implements the server side yet — the
TypeScript SDK returns `supports_streaming: false` from `GetCapabilities`.
* **Reconnection** — if the SDK crashes, the client does not retry. The agent must be
re-registered.
* **mTLS** — the channel is built via `grpc.secure_channel` *when* `channel_credentials`
is provided (from `MTLSAgentExtension.build_grpc_channel_credentials`), otherwise it
falls back to `grpc.insecure_channel`. Default deployments don't supply credentials
yet — see [Overview → Limitations](/bindu/grpc/overview#known-limitations) for the
operational gating.
***
## The Full Message Path
To tie everything together, here is the complete path for one message — from the outside world to your code and back:
```text theme={null}
ManifestWorker calls manifest.run(messages)
-> GrpcAgentClient.__call__([{"role": "user", "content": "What is quantum computing?"}])
-> Converts to protobuf: ChatMessage(role="user", content="What is quantum computing?")
-> gRPC call: AgentHandler.HandleMessages(HandleRequest{messages: [...]})
-> TypeScript SDK receives the call
-> Developer's handler runs: await openai.chat.completions.create(...)
-> OpenAI returns: "Quantum computing is a type of computation..."
-> SDK returns: HandleResponse{content: "Quantum computing is...", state: ""}
-> GrpcAgentClient sees state is empty, returns the string
-> ManifestWorker receives "Quantum computing is..." (same as a local handler)
-> ResultProcessor normalizes -> ResponseDetector says "completed"
-> ArtifactBuilder creates DID-signed artifact
-> User gets the response
```
The only component that knows gRPC exists is the bridge itself. Everything upstream and downstream just sees function calls and return values.
***
## Debugging
When something goes wrong, it usually helps to inspect each half of the sidecar separately. Check the core first (is it running?), then test the endpoint directly.
### Check Core Logs
```text theme={null}
[bindu-core] INFO gRPC server started on 0.0.0.0:3774
[bindu-core] INFO Agent registered: openai-assistant-agent
[bindu-core] INFO HTTP server started on 0.0.0.0:3773
```
### Test the Agent Manually
```bash theme={null}
curl http://localhost:3773/health
curl http://localhost:3773/.well-known/agent.json | python3 -m json.tool
curl -X POST http://localhost:3773 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "message/send",
"params": {
"message": {
"role": "user",
"parts": [{"kind": "text", "text": "Hello"}],
"messageId": "test-1",
"contextId": "test-2",
"taskId": "test-3",
"kind": "message"
}
},
"id": "1"
}'
```
### Port Conflicts
```bash theme={null}
lsof -ti:3773 -ti:3774 | xargs kill 2>/dev/null
```
***
## Limits to Keep in Mind
Current limitations:
* Streaming — available via `use_streaming=True` but requires SDK-side
`HandleMessagesStream` support.
* Requires Python — the Bindu core must be installed (`pip install bindu`).
* Single agent per port — each `bindufy()` call uses `:3773` for HTTP.
Review the sidecar architecture and current limits
Look up services, messages, ports, and config details
With the core handling the protocol and identity, your only job is to
focus on the agent's intelligence —
prompts, state, and tool execution.
# API Reference
Source: https://docs.getbindu.com/bindu/grpc/api-reference
Complete gRPC contract between SDKs and the Bindu core
This is the complete gRPC contract between SDKs and the Bindu core. Everything on this page is defined in `proto/agent_handler.proto` — the single source of truth for how SDKs register agents, send heartbeats, expose handler callbacks, and keep the language-agnostic runtime aligned with the Python core.
## Why This API Matters
The gRPC layer is not an add-on around Bindu. It is the contract that keeps registration, liveness, handler execution, and capability discovery consistent across SDKs while the core continues to run the shared infrastructure.
To understand why this matters, compare what happens without it:
| Ad-hoc SDK integration | Bindu gRPC contract |
| -------------------------------------------------------- | ------------------------------------------------------------------ |
| Each SDK invents its own registration and callback shape | One protocol defines the shared contract between SDKs and the core |
| Liveness and capability checks vary across languages | Heartbeat, HealthCheck, and GetCapabilities are standardized |
| Remote handlers can drift from local bindufy behavior | RegisterAgent preserves the same bindufy pipeline in the core |
| Message execution contracts become SDK-specific | HandleMessages keeps one handler request/response model |
| Operational behavior becomes harder to debug | Ports, methods, and message schemas stay explicit and testable |
The proto turns the language boundary into a stable interface. SDKs and the core can evolve around one shared contract instead of growing separate integration logic.
The reference here is not just a list of RPCs. It is the runtime boundary that allows
remote SDKs to participate in the same `bindufy` lifecycle as local Python agents.
## How The gRPC Contract Works
The contract is split across two services that face opposite directions. Understanding which service lives where is the key to reading the rest of this page.
### The Service Split
`BinduService` runs on port `3774` in the Bindu core. SDKs use it to register and manage agents.
`AgentHandler` runs on a dynamic port in the SDK. The core uses it to execute the developer's handler and query runtime status.
`BinduService` is the control plane for agent registration, heartbeats, and shutdown.
`AgentHandler` is the runtime callback plane for message handling and health checks.
Both sides follow the same message schema from `proto/agent_handler.proto`.
### The Lifecycle: Register, Execute, Maintain
Every SDK follows the same three-phase lifecycle. First the SDK registers with the core. Then the core calls the SDK when work arrives. Finally, the SDK keeps the connection alive and shuts down cleanly.
```mermaid theme={null}
sequenceDiagram
participant SDK
participant Core as BinduService (:3774)
participant Handler as AgentHandler (dynamic port)
Note over SDK,Core: 1. Register
SDK->>Core: RegisterAgent(config_json, skills, grpc_callback_address)
Core-->>SDK: RegisterAgentResponse
Note over Core,Handler: 2. Execute
Core->>Handler: HandleMessages(messages, task_id, context_id)
Handler-->>Core: HandleResponse
Note over SDK,Core: 3. Maintain
SDK->>Core: Heartbeat(agent_id, timestamp)
Core-->>SDK: HeartbeatResponse
SDK->>Core: UnregisterAgent(agent_id)
Core-->>SDK: UnregisterAgentResponse
```
Let's walk through each phase and look at the exact message shapes involved.
`RegisterAgent` is the main entry point. The SDK sends config, skills, and its
callback address. The core runs the full `bindufy` pipeline and returns the agent's
identity.
```protobuf Request theme={null}
message RegisterAgentRequest {
string config_json = 1; // Full config as JSON string
repeated SkillDefinition skills = 2; // Skills with file content
string grpc_callback_address = 3; // SDK's AgentHandler address
}
```
```protobuf Response theme={null}
message RegisterAgentResponse {
bool success = 1;
string agent_id = 2; // Generated UUID
string did = 3; // "did:bindu:author:name:id"
string agent_url = 4; // "http://localhost:3773"
string error = 5; // Error message if success=false
}
```
`config_json` matches the Python `bindufy()` config format:
```json theme={null}
{
"author": "dev@example.com",
"name": "my-agent",
"description": "What it does",
"deployment": {"url": "http://localhost:3773", "expose": true},
"execution_cost": {"amount": "1000000", "token": "USDC"}
}
```
The core validates config, generates agent ID as `UUID(SHA256("{author}:{name}").hexdigest()[:32])`
([`bindufy.py:74-76`](https://github.com/getbindu/Bindu/blob/main/bindu/penguin/bindufy.py#L74)),
creates Ed25519 DID keys, sets up x402 payments (when `execution_cost` is provided),
creates the manifest with `GrpcAgentClient` as the handler, and starts the HTTP/A2A
server on the configured URL.
The DID's `author` and `name` segments are sanitized (`@` → `_at_`, `.` → `_`, spaces → `_`,
lowercased) — see [`did_agent_extension.py:124`](https://github.com/getbindu/Bindu/blob/main/bindu/extensions/did/did_agent_extension.py#L124).
So `author = "Dev@Example.com"`, `name = "my-agent"` produces a DID like
`did:bindu:dev_at_example_com:my-agent:{agent_id}`.
`HandleMessages` is how the core invokes the SDK handler once work arrives. This is the
hot path — every user message passes through this RPC.
```protobuf Request theme={null}
message HandleRequest {
repeated ChatMessage messages = 1; // Conversation history
string task_id = 2; // reserved — not populated by GrpcAgentClient today
string context_id = 3; // reserved — not populated by GrpcAgentClient today
}
message ChatMessage {
string role = 1; // "user", "assistant", or "system"
string content = 2;
}
```
```protobuf Response theme={null}
message HandleResponse {
string content = 1; // The response text
string state = 2; // "" = completed, "input-required", "auth-required"
string prompt = 3; // Follow-up prompt (when state is set)
bool is_final = 4; // true for unary; true on last chunk for streaming
map metadata = 5; // Optional extra key-value pairs
}
```
`task_id` and `context_id` are part of the wire contract, but
[`GrpcAgentClient._build_request`](https://github.com/getbindu/Bindu/blob/main/bindu/grpc/client.py)
only sets `messages` today — both fields arrive as empty strings on the SDK side.
Treat them as reserved for forthcoming task-context propagation; SDKs should
ignore them for now.
Response rules:
* Normal response: `{content: "answer", state: ""}` → task completes
* Need more info: `{state: "input-required", prompt: "Can you clarify?"}` → task stays open
* Need auth: `{state: "auth-required"}` → task stays open
* Error: Return gRPC `INTERNAL` status → task fails
`Heartbeat` and `UnregisterAgent` handle liveness and clean shutdown. The heartbeat
keeps the core informed that your SDK is still running. Unregister tells it you are
leaving on purpose.
```protobuf Heartbeat theme={null}
message HeartbeatRequest {
string agent_id = 1;
int64 timestamp = 2; // Unix timestamp in milliseconds
}
message HeartbeatResponse {
bool acknowledged = 1; // true if agent_id is registered
int64 server_timestamp = 2;
}
```
```protobuf Shutdown theme={null}
message UnregisterAgentRequest { string agent_id = 1; }
message UnregisterAgentResponse { bool success = 1; string error = 2; }
```
SDKs typically send `Heartbeat` every \~30 seconds (the reference TypeScript SDK uses
30s) and call `UnregisterAgent` before exiting. The cadence is an SDK convention — the
Python core does not enforce or read it; `GRPC__HEALTH_CHECK_INTERVAL` exists in
settings but has no consumer in `bindu/grpc/` today.
***
## Service Reference
Here are the two services summarized for quick lookup.
### BinduService (port 3774)
Lives in the Bindu core. SDKs call this to register and manage agents.
| Method | What it does |
| ----------------- | ------------------------------------------------------------------------------------------------- |
| `RegisterAgent` | SDK sends config + skills, core runs the full `bindufy` pipeline and returns the agent's identity |
| `Heartbeat` | Keep-alive signal — SDK-driven cadence (TS SDK uses 30s; core does not enforce) |
| `UnregisterAgent` | Clean shutdown call before SDK exit |
### AgentHandler (dynamic port)
Lives in the SDK. The core calls this when work arrives.
| Method | What it does |
| ---------------------- | ------------------------------------------------------------------------------------------------ |
| `HandleMessages` | Core sends conversation history, SDK runs the developer's handler and returns the response |
| `HandleMessagesStream` | Server-side streaming variant — Python core wired, no shipped SDK implements the server side yet |
| `GetCapabilities` | Core queries what the SDK agent supports |
| `HealthCheck` | Core verifies the SDK is responsive |
`HandleMessagesStream` is **Python-side ready, not end-to-end usable**. `GrpcAgentClient`
calls it when initialized with `use_streaming=True`, and the proto contract is in place,
but no shipped SDK implements the server side. The TypeScript SDK still returns
`supports_streaming: false` from `GetCapabilities`. Use unary `HandleMessages` until an
SDK implements the streaming RPC.
***
## Shared Message Types
These message types are used across both services. Understanding them helps when building [Custom SDKs](/bindu/grpc/custom-sdks) or debugging registration issues.
### SkillDefinition
`SkillDefinition` is sent during registration and carries the skill file content so the core does not need filesystem access. The `name`, `description`, and `tags` fields describe the skill for discovery. The `input_modes` and `output_modes` declare what formats the skill accepts and produces. The `raw_content` and `format` fields carry the original file content so the core can process it directly.
```protobuf theme={null}
message SkillDefinition {
string name = 1;
string description = 2;
repeated string tags = 3;
repeated string input_modes = 4;
repeated string output_modes = 5;
string version = 6;
string author = 7;
string raw_content = 8; // Full skill.yaml or SKILL.md content
string format = 9; // "yaml" or "markdown"
}
```
Sending skill content during registration lets the SDK remain the source of truth for
skill files while the core receives the exact material it needs to build the manifest.
### Capability and Health Responses
These are the responses the core gets when it queries your SDK about what it can do and whether it is still running.
```protobuf Capabilities theme={null}
message GetCapabilitiesResponse {
string name = 1;
string description = 2;
string version = 3;
bool supports_streaming = 4;
repeated SkillDefinition skills = 5;
}
```
```protobuf Health theme={null}
message HealthCheckResponse {
bool healthy = 1;
string message = 2; // "OK" or diagnostic info
}
```
***
## Configuration
These environment variables control the gRPC server in the Bindu core. You typically do not need to change them unless you are running in a non-standard environment or debugging port conflicts.
| Variable | Default | Description |
| ----------------------------- | --------- | ---------------------------------- |
| `GRPC__ENABLED` | `false` | Enable gRPC server |
| `GRPC__HOST` | `0.0.0.0` | Bind address |
| `GRPC__PORT` | `3774` | Server port |
| `GRPC__MAX_WORKERS` | `10` | Thread pool size |
| `GRPC__MAX_MESSAGE_LENGTH` | `4194304` | Max message size (4MB) |
| `GRPC__HANDLER_TIMEOUT` | `30.0` | `HandleMessages` timeout (seconds) |
| `GRPC__HEALTH_CHECK_INTERVAL` | `30` | Health check interval (seconds) |
***
## Practical gRPC Calls
If you want to test the contract directly without writing SDK code, `grpcurl` lets you call any of these RPCs from the command line. This is useful for debugging registration issues or verifying that the core is running correctly.
```bash theme={null}
grpcurl -plaintext \
-import-path proto \
-proto agent_handler.proto \
localhost:3774 list
```
```bash theme={null}
grpcurl -plaintext -emit-defaults \
-proto proto/agent_handler.proto -import-path proto \
-d '{"agent_id": "test", "timestamp": 1711234567890}' \
localhost:3774 bindu.grpc.BinduService.Heartbeat
```
```bash theme={null}
grpcurl -plaintext -emit-defaults \
-proto proto/agent_handler.proto -import-path proto \
-d '{
"config_json": "{\"author\":\"test@example.com\",\"name\":\"test\",\"deployment\":{\"url\":\"http://localhost:3773\",\"expose\":true}}",
"skills": [],
"grpc_callback_address": "localhost:50052"
}' \
localhost:3774 bindu.grpc.BinduService.RegisterAgent
```
***
## Operational Guarantees
The proto keeps SDK registration, handler execution, and liveness signaling aligned
across languages.
Ports, message types, and RPC boundaries stay visible and testable with tools like
`grpcurl`.
## Related
* [gRPC Overview](/bindu/grpc/overview) — the conceptual tour of why the sidecar exists
* [Agent Implementation](/bindu/grpc/agent-client) — handler patterns and the bridge internals
* [Custom SDKs](/bindu/grpc/custom-sdks) — how to build SDKs for other languages using this contract
Bindu keeps the runtime contract
explicit at the boundary, so
SDKs and the core can behave like one system across languages.
# Custom SDKs
Source: https://docs.getbindu.com/bindu/grpc/custom-sdks
How to build Bindu SDKs for Rust, Go, Swift, or any language with gRPC
You have seen how the TypeScript SDK works. Now imagine doing the same thing in Rust, Go, Swift, or any language that has gRPC support. That is what this page is for.
The key insight is that the goal is not to rewrite the core. The goal is to build a new driver that can plug into the same engine. Because the sidecar keeps infrastructure centralized, each new language only needs a thin adapter — usually 200–400 lines of actual logic.
The architectural rule is simple: new languages get new drivers, not new engines.
***
## What an SDK Does
Before we dive into the steps, it helps to understand the four responsibilities every SDK shares. Under the hood, the SDK does four things:
1. **Implements `AgentHandler`** — a gRPC server that receives `HandleMessages` calls from the core and invokes the developer's handler
2. **Calls `BinduService.RegisterAgent`** — a gRPC client that registers the agent with the core
3. **Launches the Python core** — spawns `bindu serve --grpc` as a child process
4. **Exposes `bindufy(config, handler)`** — the developer-facing API that orchestrates all of the above
The proto contract at `proto/agent_handler.proto` is the single source of truth. As long as your SDK speaks that contract, it works with the core.
***
## Step 1: Generate gRPC Stubs
Before your SDK can talk to the core, it needs to speak the same language. The first job is to generate typed client and server stubs from the protobuf definition. Every gRPC ecosystem has its own tooling for this:
| Language | Tool | Command |
| -------- | -------------------- | -------------------------------------------------------------------- |
| Rust | `tonic-build` | Add `tonic-build` to `build.rs`, it compiles the proto at build time |
| Go | `protoc-gen-go-grpc` | `protoc --go_out=. --go-grpc_out=. proto/agent_handler.proto` |
| Swift | `grpc-swift` | `protoc --swift_out=. --grpc-swift_out=. proto/agent_handler.proto` |
| C# | `Grpc.Tools` | NuGet package auto-generates from `.proto` in the project |
The generated code gives you typed messages and service interfaces. Everything else in the SDK is built on top of those stubs.
***
## Step 2: Implement AgentHandler (Server)
This is the server that the core will call when work arrives. It is the language-specific half of the sidecar — how the engine talks back to the driver. Of the three RPCs, `HandleMessages` is the critical one.
### HandleMessages / HandleMessagesStream
This RPC receives conversation history, calls the developer's handler, and returns the response. Here is the shape of the request and response:
```text theme={null}
Input: HandleRequest { messages: [ChatMessage{role, content}, ...] }
Output: HandleResponse {
content: string,
state: string,
prompt: string,
is_final: bool,
metadata: map
}
```
The rules for converting your developer's handler return value into a `HandleResponse` are straightforward:
* If the handler returns a plain string, set `content` to the string and leave `state` empty.
* If the handler returns a state transition, set `state` to `"input-required"` or `"auth-required"` and `prompt` to the follow-up question.
* If the handler throws, return a gRPC `INTERNAL` error with the error message.
* Unary path (`HandleMessages`): Set `is_final` to `true` (there is only one response).
* Streaming path (`HandleMessagesStream`): Yield multiple `HandleResponse` chunks with `is_final: false`, and set `is_final: true` on the last chunk.
* Both paths use the exact same `HandleResponse` message shape.
### GetCapabilities
Return static info about the SDK. This is how the core discovers what your agent supports.
```text theme={null}
Output: GetCapabilitiesResponse { name, description, version, supports_streaming }
```
### HealthCheck
Return `{healthy: true, message: "OK"}`. `GrpcAgentClient.health_check()` can call
this on demand, but the core's `BinduService.Heartbeat` handler does **not**
invoke it — heartbeats only update the registry timestamp. Implement the RPC
anyway so future eviction sweeps and external watchdogs work.
***
## Step 3: Implement BinduService Client
Now build the other direction — the client that talks from your SDK into the core. This is how your SDK registers the agent and keeps it alive.
### RegisterAgent
This is the main entry point. It sends config, skills, and the SDK's callback address:
```text theme={null}
Input: RegisterAgentRequest {
config_json: string, // Full config as JSON
skills: [SkillDefinition], // Skills with raw file content
grpc_callback_address: string // e.g., "localhost:50052"
}
Output: RegisterAgentResponse { success, agent_id, did, agent_url, error }
```
The `config_json` is a JSON string matching the Python `bindufy()` config format. That is intentional. The schema lives in one place, and SDKs serialize to it.
### Heartbeat
Call this on a regular interval — the reference TypeScript SDK uses 30 seconds — to
signal liveness. The cadence is an SDK convention, not a core-enforced contract;
the Python core records `last_heartbeat` but does not currently evict stale
agents, so the value mainly matters when an external watchdog or future eviction
sweep is wired in.
```text theme={null}
Input: HeartbeatRequest { agent_id, timestamp }
```
### UnregisterAgent
Call this when your SDK process is shutting down cleanly so the core can release
the agent slot immediately. Today this is the **only** way an agent leaves the
registry — the Python core does not currently evict on heartbeat timeout, so
without `UnregisterAgent` a crashed SDK leaks its registry entry until the core
restarts.
```text theme={null}
Input: UnregisterAgentRequest { agent_id }
```
The TypeScript reference SDK does **not** currently call `UnregisterAgent` — its `SIGINT`
handler only clears the heartbeat interval and force-shuts the gRPC server. New SDKs
should improve on this and invoke `UnregisterAgent` from their shutdown path.
Together, `RegisterAgent`, `Heartbeat`, and `UnregisterAgent` are the control plane for the sidecar.
***
## Step 4: Implement Core Launcher
The SDK must be able to start the engine automatically. This is what makes the developer experience feel local even though the architecture is split. Without it, the developer would need to manually start the Python core in a separate terminal — and that would break the illusion of a single-process experience.
Pass the executable and arguments as a properly split array to your language's process
spawner — not as a single shell string.
The detection logic tries three approaches in order:
Pass the executable and arguments as a properly split array to your language's process
spawner — not as a single shell string.
Run `bindu` with args `["serve", "--grpc", "--grpc-port", "3774"]`
Run `uv` with args `["run", "bindu", "serve", "--grpc", "--grpc-port", "3774"]`
Run `python3` with args `["-m", "bindu.cli", "serve", "--grpc", "--grpc-port", "3774"]`
Poll every 500ms, timeout 30s.
Kill the child process cleanly.
***
## Step 5: Implement `bindufy()`
At this point, you have all the pieces. The last step is to wire them behind one developer-facing function. This is the moment where your SDK goes from "a collection of gRPC plumbing" to "a one-line developer experience."
```text theme={null}
function bindufy(config, handler):
skills = read_skill_files(config.skills)
callback_port = start_agent_handler_server(handler)
launch_python_core(grpc_port=3774)
wait_for_port(3774)
result = register_agent(config, skills, callback_address="localhost:{callback_port}")
start_heartbeat_loop(result.agent_id)
print("Agent registered! A2A URL: {result.agent_url}")
```
That is the whole idea. The SDK should feel small because the core already does the heavy lifting.
***
## Skill Loading
Skills live in the developer's project, not in the core. Your SDK is responsible for reading them and shipping their contents to the core during registration. This way the core does not need filesystem access to the SDK's project directory.
Look for `skill.yaml` first, then fall back to `SKILL.md`.
Load the raw file data.
For YAML: parse the body and pull out `name` and `description` (the reference TypeScript SDK
extracts only these two fields client-side — the rest is left to the core to parse from `raw_content`).
For Markdown: send `raw_content` as-is with `format: "markdown"`; the reference TS SDK does **not**
parse YAML frontmatter out of `SKILL.md`. If your SDK wants to surface more metadata locally
(e.g. for logging), parse it yourself — the core treats `raw_content` as the source of truth.
`{ name, description, tags, input_modes, output_modes, version, author, raw_content, format }`.
`tags`, `input_modes`, and `output_modes` default to sensible values (`[]`, `["text/plain"]`,
`["text/plain"]` in the TS SDK). Only `raw_content` and `format` are strictly required for
the core to fully reconstruct the skill.
***
## Testing Your SDK
The fastest way to keep an SDK honest is to test both the transport and the sidecar lifecycle. Start with unit tests to verify serialization, then work up to integration tests that exercise the full round trip.
Mock the gRPC channel and verify `HandleMessages` correctly invokes the handler and
serializes the response.
Start a real Bindu core with `bindu serve --grpc`, register an agent from your SDK,
send an A2A message, and verify the response. The Python E2E tests in
`tests/integration/grpc/test_grpc_e2e.py` show exactly this pattern.
Run one of the examples end to end and `curl` the agent.
***
## Reference: TypeScript SDK
If you want a concrete model to follow, the TypeScript SDK is the reference implementation. It is intentionally small — most of the complexity lives in the core, not in the SDK.
| File | What it does | Lines |
| ---------------------- | ----------------------------------- | ----- |
| `src/index.ts` | `bindufy()` function + skill loader | \~220 |
| `src/server.ts` | `AgentHandler` gRPC server | \~130 |
| `src/client.ts` | `BinduService` gRPC client | \~105 |
| `src/core-launcher.ts` | Spawns Python core | \~170 |
| `src/types.ts` | TypeScript interfaces | \~120 |
Total: \~745 lines. Most of that is type definitions and error handling. The core logic is under 300 lines.
See how the reference driver behaves from the developer's point of view
Review the protobuf messages and service contracts directly
***
## Publishing
Once your SDK works, publish it to the language's standard package registry so others can use it:
| Language | Registry | Package name convention |
| -------- | --------------------- | ---------------------------------- |
| Rust | crates.io | `bindu-sdk` |
| Go | Go modules | `github.com/getbindu/bindu-sdk-go` |
| Swift | Swift Package Manager | `bindu-sdk` |
| C# | NuGet | `Bindu.Sdk` |
Include the proto file in the package so users do not need to download it separately.
Because the infrastructure is entirely decoupled, building a new SDK is just a
matter of
satisfying the gRPC contract,
not rewriting the core engine.
# gRPC Overview
Source: https://docs.getbindu.com/bindu/grpc/overview
Why the gRPC sidecar exists, how the architecture works, and where the current limits are
This page is a conceptual tour. By the end, you will understand why Bindu uses a sidecar, how the two halves talk to each other, and what the tradeoffs are. You will not write any code here — that comes in the [Quickstart](/bindu/grpc/quickstart).
## The Multi-Language Problem
You want to build agent intelligence. What you keep getting dragged into is infrastructure.
You ship a solid TypeScript handler. Then someone asks for Kotlin. Then Python. Suddenly the real work is no longer prompts, tools, or reasoning. It is rebuilding auth, DID identity, A2A protocol handling, x402 payments, scheduling, storage, and service plumbing for every language.
That is the infrastructure trap. The part that should be reusable becomes the part you rewrite the most.
## The Goal: Language-Agnostic Agents
The goal is simple: make the developer write only the brain and let one reusable runtime provide the body.
That means a language-agnostic architecture where the public API stays the same, the infrastructure stays centralized, and teams can move between TypeScript, Kotlin, and Python without losing features or behavior.
The contract should feel boring in the best way:
```python Python theme={null}
bindufy(config, handler) # handler runs in the same process
```
```typescript TypeScript theme={null}
bindufy(config, handler) // handler runs here, infrastructure runs in Python
```
Same function name. Same config shape. Same outcome. Different language, same microservice.
## The gRPC Sidecar Architecture
Now that you know the problem, here is how Bindu solves it.
Bindu uses the sidecar model. Think of it as two halves of one system:
The **SDK** is the driver. It owns your logic, your framework choices, and your handler.
The **Python Core** is the engine. It owns the infrastructure: config validation, DID generation, auth, x402, scheduling, storage, manifest creation, and the A2A-facing HTTP server.
The bridge between them is gRPC: a high-performance, open-source RPC framework built on HTTP/2 and Protocol Buffers. Bindu uses it here instead of standard REST for three reasons:
* Strict typing keeps the SDKs and core aligned on one contract.
* Low latency keeps the local transport overhead tiny compared with the LLM call.
* Bidirectional calls let the SDK register with the core, then let the core call back into the SDK when work arrives.
The gRPC layer stays out of your way. You do not write proto files, manually boot a second service, or think about serialization. You call `bindufy()`, write the handler, and the SDK wires up the rest.
## The Big Picture
Here is how the two halves sit side by side. One process owns the logic. The other owns the infrastructure.
```text theme={null}
Their TypeScript code Bindu Core (Python, auto-started)
+---------------------+ +----------------------------+
| | | |
| OpenAI SDK | 1. Register | Config validation |
| LangChain | ------gRPC-----> | DID key generation |
| Any framework | | Auth (Hydra OAuth2) |
| | | x402 payment setup |
| handler(messages) | 2. Execute | Manifest creation |
| <------gRPC--------|<---------------- | Scheduler + Storage |
| | | HTTP/A2A server (:3773) |
+---------------------+ +----------------------------+
SDK process Core process
(developer's language) (Python, invisible)
```
Two processes. One terminal. You see your app. The SDK quietly manages the Python child process.
## Why Two Processes?
This is a fair question, so let's address it directly.
Because the alternatives are worse.
Option A: Rewrite the core in every language. DID, auth, x402, scheduler, storage, A2A in TypeScript, then Kotlin, then Python, then whatever comes next. Every bug gets fixed multiple times.
Option B: Keep one core, put a clean wire protocol in front of it, and let thin SDKs translate between the developer and that core.
Bindu chooses Option B. The sidecar is the boundary, and gRPC is the wire.
## What Actually Happens
Now that you understand the shape of the architecture, here is what happens at runtime in three quick beats:
The Python core handles DID, auth, x402, scheduling, storage, and the HTTP server.
You do not manually run a second service. The SDK detects how to launch it and spawns it.
It sends config, skills, and a callback address to the core. The core runs the full
`bindufy` pipeline and starts the A2A HTTP server.
A client sends an A2A message to `:3773`. The core receives it, builds task context,
and calls your handler back over gRPC.
```text theme={null}
Client --HTTP--> Bindu Core --gRPC--> TypeScript Handler --> OpenAI
:3773 (Python) :3774 (your code)
DID, Auth, x402 Just the handler.
Scheduler, Storage That's all you write.
A2A protocol
```
That is the full lifecycle: start, register, handle. If you want to see the detailed step-by-step of what happens during startup and message processing, the [Agent Implementation](/bindu/grpc/agent-client) page walks through every phase.
## Two Services, Two Directions
The sidecar works because calls move in both directions. The SDK talks to the core during startup. The core talks back to the SDK during execution. Let's look at each side.
**BinduService** (lives in the Python core on `:3774`) — the SDK calls this to register and manage its agent:
| Method | What it does |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `RegisterAgent` | "Here is my config, skills, and callback address. Turn me into a microservice." |
| `Heartbeat` | "I am still alive." (SDK convention — the reference TS SDK pings every 30s; cadence isn't enforced by the core) |
| `UnregisterAgent` | "I am shutting down. Clean up." Reserved for SDKs that implement graceful shutdown — the current TypeScript SDK does not call this. The core's registry records `last_heartbeat` but does **not** evict stale entries automatically yet; cleanup happens on explicit `UnregisterAgent` or core restart. |
**AgentHandler** (lives in the SDK on a dynamic port) — the core calls this when work arrives:
| Method | What it does |
| ----------------- | ---------------------------------------------------------------------- |
| `HandleMessages` | "A user sent this message. Run your handler and give me the response." |
| `GetCapabilities` | "What can you do?" |
| `HealthCheck` | "Are you still there?" |
This is exactly why Bindu does not use plain REST for this boundary. Both sides need typed contracts and both sides need to initiate calls cleanly. The [API Reference](/bindu/grpc/api-reference) documents every message and field if you want the full details.
## Python vs gRPC Agents
From the outside, both models look the same. Inside, the transport path differs. This table shows you exactly where they diverge and where they are identical.
| | Python Agent | gRPC Agent |
| ---------------- | -------------------------- | ---------------------------------------------------------------- |
| Developer calls | `bindufy(config, handler)` | `bindufy(config, handler)` (identical) |
| Handler runs in | Same process as core | Separate process |
| Core started by | `bindufy()` directly | SDK spawns as child process |
| Communication | In-process function call | gRPC over localhost |
| Latency overhead | 0ms | 1–5ms |
| Language | Python only | Any language with gRPC |
| DID, auth, x402 | Full support | Full support (identical) |
| Skills | Loaded from filesystem | Sent as data during registration |
| Streaming | Supported | Wire contract ready; not implemented in shipped SDKs (see below) |
From the outside, there is no visible difference. The agent card looks the same. The
DID is generated the same way. The A2A responses have the same structure. The
artifacts carry the same DID signatures. A client cannot tell whether the agent
behind `:3773` is Python, TypeScript, or Kotlin.
## Real Examples
If you want to see these ideas in working code, here are three examples that each use the same `bindufy()` pattern in different languages and frameworks:
GPT-4o agent with one `bindufy()` call
LangChain.js research assistant
Kotlin agent with the same pattern
## Known Limitations
The sidecar model already gives you full parity for core infrastructure. The current gaps are about transport security and edge-case resilience. None of these will affect you during local development, but they are worth knowing about before you deploy to production.
The transport supports mTLS — when `MTLSAgentExtension` provides credentials,
[`start_grpc_server`](https://github.com/getbindu/Bindu/blob/main/bindu/grpc/server.py)
binds via `server.add_secure_port(...)` and
[`GrpcAgentClient`](https://github.com/getbindu/Bindu/blob/main/bindu/grpc/client.py)
builds the channel via `grpc.secure_channel(...)`. When credentials are not provided,
the server falls back to `add_insecure_port` and the client to `grpc.insecure_channel`.
By default, deployments run **without** mTLS credentials — same-host setups (SDK and
core on `localhost`) don't need them, and the upstream Hydra audience whitelisting for
step-ca-issued certificates hasn't shipped yet. The code path is wired; the operational
rollout is the gating piece.
If the SDK process crashes mid-execution, the `GrpcAgentClient` does not retry.
The task fails, and the agent must be re-registered.
`ManifestWorker` catches the gRPC `UNAVAILABLE` error and marks the task as failed.
On restart, the SDK calls `RegisterAgent` again.
Each `GrpcAgentClient` creates a single gRPC channel lazily on first use. Under
high concurrency, all calls share one channel.
This is fine for most agents because gRPC multiplexes well via HTTP/2. At
extremely high concurrency, connection pooling would reduce contention.
The `/metrics` endpoint reports HTTP request metrics but not gRPC call metrics.
You cannot see `HandleMessages` latency, error rates, or call counts in the
dashboard.
Workaround: check the core log output, which includes timing information for each
handler call.
If you run two instances of the same TypeScript agent, each one registers
separately with a different callback address. There is no built-in routing to
spread load across instances.
Workaround: use a reverse proxy such as Envoy in front of the SDK instances, and
register the proxy address as the callback.
## Feature Comparison
This is the complete picture of what works today and what is still on the roadmap:
| Feature | Python Agents | gRPC Agents |
| ------------------------------------ | ---------------- | ----------------------------------------------------------------------------------- |
| Unary responses | works | works |
| Streaming responses | works | proto + `GrpcAgentClient` ready; TypeScript SDK returns `supports_streaming: false` |
| DID identity | works | works |
| x402 payments | works | works |
| Skills | works | works |
| State transitions (`input-required`) | works | works |
| Health checks | works | works |
| Multi-language | Python only | any language |
| Latency overhead | 0ms | 1–5ms |
| mTLS | N/A (in-process) | code wired, off by default (see Limitations) |
| Auto-reconnection | N/A (in-process) | not implemented |
The driver/engine split is highly robust. gRPC agents have full parity with Python
agents for identity, auth, payments, skills, streaming, and the A2A protocol. The
missing pieces are purely around advanced security hardening and distributed
resilience.
## Next Steps
You now have the conceptual map. From here, pick the path that matches where you are:
Build your first gRPC agent in 10 minutes
Handler patterns, state transitions, and how the bridge works under the hood
Build SDKs for other languages
Services, messages, ports, and env vars
Escape the infrastructure trap by keeping your logic entirely decoupled from
identity, protocols, and routing.
# gRPC Quickstart
Source: https://docs.getbindu.com/bindu/grpc/quickstart
The fastest path to your first working gRPC agent
This is the fastest path to the aha moment. You will build a simple TypeScript agent, call `bindufy()`, and watch the Bindu Core sidecar turn it into a real microservice.
You write the driver. The sidecar brings the engine: DID identity, A2A protocol compliance, x402 payment support, scheduling, storage, and an HTTP server.
Time to complete: \~10 minutes
The core generates and manages agent identity for you.
Your handler is exposed as a production-ready A2A service.
x402 support can be added without changing the transport model.
The sidecar handles task orchestration and persistence.
***
## Prerequisites
Before you start, make sure the local machine can run both halves of the sidecar model. You need a JavaScript runtime for your code and a Python runtime for the core.
Version 18 or higher
Version 3.12+ with Bindu installed
Get one at platform.openai.com/api-keys
Basic command line knowledge
### Install Bindu Python Core
The TypeScript SDK needs the Bindu Core installed on the machine. This is the engine half of the sidecar — your SDK will launch it automatically, but it needs to be available first.
```bash theme={null}
pip install bindu
# or with uv:
uv pip install bindu
```
The SDK launches the Python core automatically as a child process. You never start
the sidecar manually during normal SDK use.
***
## Step 1: Create Your Project
Start with a clean project directory. Nothing special here — just a standard Node.js project.
```bash theme={null}
mkdir my-first-agent
cd my-first-agent
npm init -y
```
***
## Step 2: Install Dependencies
Now install the packages your agent needs. The Bindu SDK handles the sidecar lifecycle, and you can use any LLM library you like alongside it.
```bash theme={null}
npm install @bindu/sdk openai dotenv
npm install -D tsx typescript @types/node
```
* `@bindu/sdk` — Bindu TypeScript SDK (gRPC, registration, sidecar lifecycle)
* `openai` — OpenAI Node.js SDK
* `dotenv` — Loads environment variables from `.env`
* `tsx` — TypeScript executor (dev dependency)
* `typescript` — TypeScript compiler (dev dependency)
***
## Step 3: Create Your Environment File
Your agent needs an API key to talk to OpenAI. Store it in a `.env` file so it stays out of your code.
```bash theme={null}
touch .env
```
```env theme={null}
OPENAI_API_KEY=sk-your-openai-api-key-here
OPENAI_MODEL=gpt-4o
```
Never commit your `.env` file to git.
```bash theme={null}
echo ".env" >> .gitignore
```
***
## Step 4: Create a Skill Definition
Skills tell the A2A protocol what your agent can do. Think of them as the agent's resume — other agents and clients read this to decide whether to talk to yours.
```bash theme={null}
mkdir -p skills/question-answering
```
Create `skills/question-answering/skill.yaml`:
```yaml theme={null}
name: question-answering
description: General question answering using GPT-4o
tags:
- qa
- assistant
- general-knowledge
input_modes:
- text/plain
output_modes:
- text/plain
version: 1.0.0
author: dev@example.com
```
You can also use Markdown format (`SKILL.md`) instead of YAML. Both formats are
supported.
***
## Step 5: Write Your Agent Code
This is the core of what you are building. Your code defines the driver — the handler function that receives messages and returns responses. `bindufy()` attaches the engine around it.
```typescript theme={null}
import { bindufy, ChatMessage } from "@bindu/sdk";
import OpenAI from "openai";
import * as dotenv from "dotenv";
dotenv.config();
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
bindufy(
{
author: "dev@example.com",
name: "my-first-agent",
description: "A helpful assistant powered by GPT-4o",
version: "1.0.0",
deployment: {
url: "http://localhost:3773",
expose: true,
cors_origins: ["http://localhost:5173"],
},
skills: ["skills/question-answering"],
},
async (messages: ChatMessage[]) => {
const response = await openai.chat.completions.create({
model: process.env.OPENAI_MODEL || "gpt-4o",
messages: messages.map((m) => ({
role: m.role as "user" | "assistant" | "system",
content: m.content,
})),
});
return response.choices[0].message.content || "";
}
);
```
Notice what you did *not* write: no server setup, no DID key generation, no authentication middleware, no protocol handling. That is the sidecar doing its job.
***
## Step 6: Run Your Agent
Everything is in place. Start your agent with a single command:
```bash theme={null}
npx tsx index.ts
```
You should see output like this:
```text theme={null}
Bindufy: my-first-agent
Author: dev@example.com
Starting Bindu core: /usr/local/bin/bindu serve --grpc --grpc-port 3774
Waiting for Bindu core gRPC on port 3774...
[bindu-core] gRPC server started on grpc://0.0.0.0:3774
[bindu-core] Waiting for SDK agent registrations...
Bindu core is ready.
AgentHandler gRPC server on :54321
Registering with Bindu core at localhost:3774...
Agent registered successfully!
Agent ID: 91547067-c183-e0fd-c150-27a3ca4135ed
DID: did:bindu:dev_at_example_com:my-first-agent:91547067...
A2A URL: http://localhost:3773
Waiting for messages...
```
Lines prefixed `[bindu-core]` come from the spawned Python core's stdout. Lines without
a prefix come from the SDK itself. The exact port after `AgentHandler gRPC server on :`
is OS-assigned (`callbackPort: 0` in your config), so it will differ each run.
Your agent is now running as a full microservice.
That is a lot of infrastructure that just appeared from one function call. Your agent has a DID identity, an A2A-compliant HTTP server, authentication, and is ready to receive messages.
***
## Step 7: Verify It Works
Let's make sure everything is working by sending your first message. Open a new terminal and try these commands.
### Send a message
```bash theme={null}
curl -s -X POST http://localhost:3773 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "message/send",
"params": {
"message": {
"role": "user",
"parts": [{"kind": "text", "text": "What is the capital of France?"}],
"messageId": "11111111-1111-1111-1111-111111111111",
"contextId": "22222222-2222-2222-2222-222222222222",
"taskId": "33333333-3333-3333-3333-333333333333",
"kind": "message"
},
"configuration": {
"acceptedOutputModes": ["text/plain"],
"blocking": true
}
},
"id": "11111111-1111-1111-1111-111111111111"
}' | python3 -m json.tool
```
`messageId`, `contextId`, and `taskId` are required fields in the A2A Message schema.
You must pass valid UUIDs. Omitting any of them will result in a validation error from
the core.
If everything is working, you should see a JSON response with the answer. That response traveled from your curl command, through the A2A HTTP server, across gRPC to your TypeScript handler, out to OpenAI, and back the same way.
### Check the agent card
Every Bindu agent exposes a machine-readable identity card. This is how other agents discover what yours can do.
```bash theme={null}
curl -s http://localhost:3773/.well-known/agent.json | python3 -m json.tool
```
### Check health
```bash theme={null}
curl -s http://localhost:3773/health
```
***
## What Just Happened?
Your agent is running. Let's slow down and understand what `bindufy()` actually did behind the scenes, because quite a lot happened in that one function call.
Spawned `bindu serve --grpc` as a child process.
For your handler on a dynamic, OS-assigned port.
Loaded `skills/question-answering/skill.yaml`.
Called `RegisterAgent` on the core with your config.
* Generated deterministic agent ID: `SHA256("{author}:{name}")` → first 32 hex chars → UUID format ([`bindufy.py:74-76`](https://github.com/getbindu/Bindu/blob/main/bindu/penguin/bindufy.py#L74))
* Created Ed25519 DID keys and sanitized the DID identifiers (`@` → `_at_`, `.` → `_`, spaces → `_`, lowercased — see [`did_agent_extension.py:124`](https://github.com/getbindu/Bindu/blob/main/bindu/extensions/did/did_agent_extension.py#L124))
* Set up authentication via Hydra OAuth2 (when `AUTH_ENABLED=true`; the paywall example explicitly disables this for local dev)
* Created the manifest with `GrpcAgentClient` as `agent_function` (passed through `_bindufy_core(..., handler_callable=grpc_client)`)
* Started HTTP/A2A server on `:3773`
Agent ID, DID, and A2A URL.
Pings core every 30 seconds to signal liveness (SDK convention — the cadence
is not enforced by the core).
Your code became the driver, and the sidecar brought the engine online around it.
***
## Project Structure
Here is what your project looks like now:
```text theme={null}
my-first-agent/
├── index.ts
├── package.json
├── .env
├── .gitignore
├── skills/
│ └── question-answering/
│ └── skill.yaml
└── node_modules/
```
***
## Troubleshooting
If something did not work, check the common issues below. Most problems come from missing prerequisites or port conflicts.
```bash theme={null}
pip install bindu
bindu --version
```
```bash theme={null}
lsof -ti:3773 -ti:3774 | xargs kill 2>/dev/null
```
```bash theme={null}
cat .env
# Should show: OPENAI_API_KEY=sk-...
```
Common causes:
* Invalid API key
* Model not available on your OpenAI plan
* Rate limiting
* Network connectivity
Common causes:
* Missing `author` or `name` in config
* Invalid `deployment.url` format
* Port conflicts
***
## Next Steps
You have a working agent. From here, the natural next question is: how do I make it smarter?
Handler patterns (multi-turn, LangChain, payments), state transitions, configuration, and how the bridge works under the hood
Build SDKs for Rust, Go, Swift, or any language with gRPC
The complete gRPC contract: services, messages, ports, and env vars
Revisit the sidecar architecture, tradeoffs, and current limitations
Get your first language-agnostic agent running in minutes without writing
a single line of infrastructure code
.
# Install
Source: https://docs.getbindu.com/bindu/how-to/install
Get Bindu into your environment in 30 seconds. uv is the short path; pip works too.
The install step should be boring. Two commands, no surprises.
## The short path: `uv`
```bash theme={null}
uv add bindu
```
That's it. If you don't have `uv` yet:
```bash theme={null}
curl -LsSf https://astral.sh/uv/install.sh | sh
```
Restart your shell, then `uv add bindu`. You need Python 3.12 or newer.
## The pip path
If you'd rather use a standard venv:
```bash theme={null}
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -U bindu
```
If `pip install` fails, the usual culprit is an old pip. Run `python -m pip install --upgrade pip` and retry.
## API keys
To run anything interesting you'll need a key for at least one LLM provider:
```bash theme={null}
# Pick one — agents in the examples folder use these
OPENAI_API_KEY=sk-...
OPENROUTER_API_KEY=sk-or-...
MINIMAX_API_KEY=...
```
Put them in a `.env` file at the project root. The examples all use `python-dotenv` to load it.
## Verify it worked
```bash theme={null}
uv run python -c "import bindu; print(bindu.__version__)"
```
You should see a version string (PyPI releases are `0.3.x`; source checkouts use CalVer like `2026.21.x.devN+g`). Either way, if it prints, Bindu imported cleanly — head to [Your first agent](/bindu/get-started/your-first-agent).
## Hacking on Bindu itself
Different goal — you want to contribute to the framework, not just use it:
```bash theme={null}
git clone https://github.com/getbindu/Bindu.git
cd Bindu
uv sync --dev
pre-commit run --all-files
```
The full contributor guide lives at [`.github/contributing.md`](https://github.com/getbindu/Bindu/blob/main/.github/contributing.md). Most of the day-to-day chat happens on [Discord](https://discord.gg/3w5zuYUuwt) — come say hi.
# The Bindu Inbox
Source: https://docs.getbindu.com/bindu/inbox/overview
A Gmail-shaped operator console for the A2A network — every signed JSON-RPC call between two DIDs, threaded and verifiable from the right rail.
**Budget about 20 minutes** to go from `git clone` to a signed message landing in the right rail. **No prior bindu knowledge required** — every step in the next chapter explains what it does and what you should see.
You've built an agent. Maybe two. They talk to each other over A2A. But the *traffic itself* — who called whom, with what body, signed by which DID, with which Hydra token — is invisible. It's HTTP. It's gone the moment it lands.
The inbox is the thing that makes that traffic visible. Every JSON-RPC message between two DIDs lands here as a row. Threads group by `context_id`. Signatures are verified inline so you can see whether a peer is actually who it claims to be. It's an **operator console** — for you, your auditor, and your future self trying to figure out what went wrong at 2am.
***
## The roadmap
The five processes that make the inbox tick, and why each one is there.
Five steps. One persona. Two demo peers. One signed message.
Prove from your terminal that calls really are signed and authed.
Layout, sending, reading a thread, replying.
Common boot failures and the env knobs that fix them.
***
## Why this exists
Most agent frameworks treat the wire as someone else's problem. You write a handler, you `POST` to it, you hope it returns. If something goes wrong — wrong signer, expired token, a peer that lied about its DID — you get a stack trace and you start grepping logs across three machines.
The inbox flips that. It treats **every A2A message as a first-class object** with:
* A **state pill** — `submitted` · `working` · `input-required` · `payment-required` · `auth-required` · `completed` · `failed`.
* A **trust pill** — `first-contact` (new peer) · `known` · `self` (your own agents / planner).
* A **DID** of the counterparty — click for the full agent card.
* The **canonical body** that was signed, the **signature**, and the **timestamp nonce** — all verifiable inline.
You don't have to trust the UI. The Verify tab in the right rail re-runs the signature check against the peer's published `publicKeyBase58` — same code path a hostile peer would face on the wire.
***
## What ends up running
By the time you finish the [quickstart](/bindu/inbox/quickstart), five things will be alive on your machine:
| Port | Process | What it does |
| ----------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------- |
| `3775` | Vite dev server | The React UI you open in your browser. |
| `3787` | Hono API (`server/index.ts`) | SQLite event store, webhook intake, outbound A2A composer. |
| `` (e.g. `5xxxx`) | Your personal agent (Python, spawned on demand) | Your DID + Hydra OAuth client. Listens for inbound A2A and signs everything you send. |
| `5773` + `5776` | Demo peers (joke + poet) | Two example agents to talk to. Optional — bring your own if you have them. |
| `3774` | Gateway (optional) | The planner. Only spawns when you message ≥2 agents at once. |
`3775` is hard-pinned (Vite refuses to drift) and `3787` is hard-coded; both have to be free before you start. If something else is on those ports the inbox won't boot — see [Troubleshooting](/bindu/inbox/troubleshooting#port-already-in-use).
***
## What "auth on" means here
There are three independent auth layers in play. The inbox uses all three:
| Layer | Who enforces it | Default |
| ------------------------------------------------------------------- | --------------------------------------------------- | --------------------- |
| **Peer A2A auth** — outbound calls must carry a JWT + DID signature | The peer's bindufy middleware (`-32009` if missing) | **On** |
| **Operator gate** — `/api/*` on the inbox requires a bearer token | `inbox/server/index.ts` | Off (single-user dev) |
| **Webhook gate** — agents POSTing back must carry a bearer token | `inbox/server/index.ts` | Off |
The first is non-negotiable once your personal agent is alive. The other two are belt-and-suspenders for multi-user or exposed deployments — leave them off until you actually share the URL. The full mechanics live in [Verify the auth](/bindu/inbox/verify-auth#what-auth-on-means).
***
## What the inbox is not
Threads are grouped by `context_id`, not by contact. The same peer can show up in dozens of unrelated threads and the inbox treats each one independently.
Your personal agent runs as a separate Python process the inbox spawns on demand. Demo peers and any peer you add run wherever they run. The inbox is the *observer*.
Single operator, single machine. `BINDU_COMMS_TOKEN` is a gate for sharing the URL with a teammate; full SSO is on the roadmap.
***
## What you'll have by the end
Your operator DID (`did:bindu:::`), an Ed25519 keypair on disk, and a Hydra OAuth client registered to that DID.
`joke_agent` and `poet_agent` running locally with `AUTH__ENABLED=true` — same auth shape as a production bindufy agent.
A `Sent` row, an `Inbox` reply, both signed, both verified, both threaded under the same `context_id`.
Let's go. Next up: [Quickstart](/bindu/inbox/quickstart).
The inbox doesn't generate traffic —
it makes the traffic legible.
# Troubleshooting
Source: https://docs.getbindu.com/bindu/inbox/troubleshooting
Common boot failures, what causes them, and the exact command that fixes each one.
Everything below is something that's actually broken on someone's machine at least once. The pattern is the same: a one-line diagnosis, the root cause, the fix.
***
## `npm install` fails on `better-sqlite3`
Native build needs Xcode CLI tools on macOS / `build-essential` on Linux.
```bash theme={null}
# macOS
xcode-select --install
# Linux (Debian/Ubuntu)
sudo apt install build-essential python3-dev
# Then:
rm -rf node_modules && npm install
```
***
## Port already in use
Symptom: `npm run dev` errors with `EADDRINUSE` on `3775` or `3787`. Usually an old inbox you forgot to stop.
```bash theme={null}
# Find the offending process (confirms it's stale)
lsof -ti:3775 -ti:3787 | xargs ps -p
# Kill it
lsof -ti:3775 -ti:3787 | xargs kill
```
Don't change the ports. `3775` is hard-pinned in Vite config; `3787` is hard-coded in the server. If you have a real conflict on those ports, kill the conflicting process — don't try to relocate the inbox.
***
## UI loads but everything fails with "Failed to fetch"
The API on `3787` died. Check the `[api]` lines in your `npm run dev` output. Most common cause: `better-sqlite3` ABI mismatch after a Node upgrade.
```bash theme={null}
npm rebuild better-sqlite3
```
If that doesn't do it, nuke `node_modules` and reinstall.
***
## Personal agent stays "down"
You clicked **Start**, the dot stayed gray. Open `~/.bindu/personal/logs/agent.log` and read the last 30 lines.
The personal agent needs an LLM. Either paste the key into Settings (gear icon) or export it before `npm run dev`:
```bash theme={null}
export OPENROUTER_API_KEY=sk-or-v1-...
```
Then click Stop → Start on the personal-agent card.
Your network / firewall is blocking `hydra-admin.getbindu.com`. Either fix the connectivity or point at a Hydra you can reach:
```bash theme={null}
export HYDRA__ADMIN_URL=https://hydra-admin.
export HYDRA__PUBLIC_URL=https://hydra.
```
Sanity check:
```bash theme={null}
curl -sI https://hydra.getbindu.com/.well-known/openid-configuration
```
If that 200s but the agent still can't reach Hydra, it's probably a proxy/cert chain issue inside your shell — not the public Hydra.
Install uv (see [Quickstart → Step 0](/bindu/inbox/quickstart#step-0-what-you-need)) or skip it entirely:
```bash theme={null}
export BINDU_PERSONAL_USE_VENV=1
```
That runs the personal agent under `/.venv/bin/python` instead. Requires that you've already done `uv sync` from the repo root.
***
## `-32009: Authentication is required` on every send
Your personal agent isn't running, or its Hydra OAuth client isn't registered.
```bash theme={null}
ls ~/.bindu/personal/.bindu/oauth_credentials.json
```
If that file is missing, the Hydra registration step never completed. Stop and re-spawn from the UI, and watch `~/.bindu/personal/logs/agent.log` for the Hydra error line.
***
## `spawn-demo-peers.sh` says OPENROUTER\_API\_KEY not set
The spawn script reads the key from either your shell env or `examples/.env`. Either is fine.
```bash theme={null}
# Option A: export in the current shell
export OPENROUTER_API_KEY=sk-or-v1-...
# Option B: persist for the demo agents
echo "OPENROUTER_API_KEY=sk-or-v1-..." > examples/.env
```
Then re-run the script.
***
## `agent-not-reachable` when adding a peer
The agent isn't up on that URL, or it's blocking `/.well-known/agent.json`.
```bash theme={null}
curl http://127.0.0.1:5773/.well-known/agent.json
```
If that returns no JSON, the agent isn't running — start it (or re-run `./scripts/spawn-demo-peers.sh` for the demo ones).
***
## `pipedream-not-configured` when connecting Gmail/Notion
The personal agent works fine without Pipedream — only the optional MCP tools need it. Either ignore the warning, or set the three Pipedream vars in Settings:
* `PIPEDREAM_PROJECT_ID`
* `PIPEDREAM_CLIENT_ID`
* `PIPEDREAM_CLIENT_SECRET`
***
## `unauthorized` on `/api/plan` (multi-agent compose)
Either `GATEWAY_API_KEY` isn't loaded (the inbox prints a warning at boot) or it doesn't match the gateway's value.
The inbox auto-reads `gateway/.env.local` on startup. Make sure:
* The file exists.
* `GATEWAY_API_KEY=` in it matches what the gateway itself loads.
* You restarted `npm run dev` after editing the file (env is read once at boot).
***
## `SyntaxError` on Python startup
You're on Python below 3.12. Install 3.12+ and re-run `uv sync` so `.venv` picks up the right interpreter.
```bash theme={null}
python3 --version # should be 3.12+
uv sync # rebuilds .venv against the correct python
```
***
## Nuke everything and start over
When you want a *truly* clean slate — new DID, new Hydra client, empty inbox:
```bash theme={null}
# 1 · Stop demo peers
./scripts/stop-demo-peers.sh
# 2 · In the UI: click Stop on the personal-agent card, then close the tab.
# 3 · Forget your DID + Hydra client
rm -rf ~/.bindu/personal/
# 4 · Wipe inbox history
rm -f inbox/data/events.db inbox/data/events.db-{shm,wal}
# 5 · Restart from the Quickstart
```
Step 3 deletes your private key. If your DID has been registered anywhere off-machine (e.g. a long-running peer recognizes it), those peers will see you as a new identity after the reset. For local-only work this doesn't matter.
***
## Still stuck?
Logs from `~/.bindu/personal/logs/agent.log` and the `[api]` lines from `npm run dev` are the two most useful things to attach.
Screenshots of the right rail + the Verify tab help a lot. Mention the personal-agent log tail if the spawn failed.
# Using the inbox
Source: https://docs.getbindu.com/bindu/inbox/using
Layout, sending to one or many agents, reading a thread, and replying.
By now your personal agent is alive, two demo peers are listed under Contacts, and you've sent one signed message. This chapter is the user manual for everything you'll do after that.
***
## Layout
| Pane | What it shows |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Left** | Folders (Inbox / Sent / Drafts / Archive), Contacts grouped into **Gateways** (orchestrators for multi-agent plans) and **Agents** (single-purpose peers). Your operator identity sits at the bottom. |
| **Middle** | Thread list — newest first, one row per `context_id`. The badge is the message count. |
| **Right** | Selected thread, oldest message at top. State pills + DID per row; bodies render inline. Reply composer pinned at the bottom. |
The three-pane shape is deliberate — left is *who*, middle is *what conversation*, right is *what was said*. You can navigate the entire thing with one hand.
***
## Sending
Click **Compose** at the top of the sidebar. The recipient picker drives the path:
Direct A2A `message/send` to that peer. No planner involved. The fastest path — round-trip is just inbox → peer → webhook back to inbox.
Comms auto-spawns a gateway (see `gateway-spawned-*` in Contacts), forwards your prompt as a plan, threads the per-agent tool calls under one `context_id`.
The gateway's `/plan` endpoint is bearer-gated. The inbox auto-loads `GATEWAY_API_KEY` from `gateway/.env.local` if it's there. If you didn't set one, multi-agent compose 401s — single-agent still works.
`⌘↵` sends. The composer closes; the row appears in **Sent**.
***
## Reading a thread
Click a thread in the middle pane. The right rail opens with the oldest message at the top.
Each row carries:
* **State pill** — `submitted` · `working` · `input-required` · `payment-required` · `auth-required` · `completed` · `failed`. Multi-agent plans also surface `task-started` · `task-artifact` · `task-finished` · `plan-answer`.
* **Trust pill** — `first-contact` (new peer) · `known` · `self` (your own agents / planner).
* **DID** of the counterparty — click for the full agent card.
* Body text rendered inline; the `` wrapper is stripped for readability.
**Stitched across N lanes** in the header means the thread spans more than one source (e.g. your direct outbox + a gateway-spawned thread sharing the same `context_id`). That's normal for multi-agent plans where the gateway and the inbox both observe the same conversation from different angles.
***
## Replying
Type in the box at the bottom of the open thread. `⌘↵` sends. The reply inherits the thread's `context_id` and chooses a task strategy:
| Situation | What the inbox does |
| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| Existing task still open | **Resume** — uses the same `taskId`. |
| Existing task ended terminal (`completed` / `failed`) | **Refine** — opens a new `taskId` with `referenceTaskIds` pointing back to the closed one. The peer can read the prior task as context. |
| Otherwise | **Start fresh** — new `taskId` under the same `contextId`. |
You don't pick. The composer reads the latest state pill in the thread and picks for you.
***
## Files & directories
If you ever want to look at what the inbox wrote to disk:
| Path | What's there |
| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `inbox/data/events.db` | SQLite event log. Delete to start fresh; the schema rebuilds on boot. Gitignored. |
| `inbox/.env.local` | Per-developer env. Gitignored. Same shell-env vars also work. |
| `inbox/scripts/logs/` | Demo-peer stdout/stderr. Gitignored. |
| `inbox/scripts/pids/` | Demo-peer pidfiles. Gitignored. |
| `~/.bindu/personal/persona.json` | Your operator persona. Hand-editable. |
| `~/.bindu/personal/.env` | Mode-`0600` env file: OpenRouter key, Pipedream tokens, Hydra URLs, `AUTH__ENABLED=true`. Regenerated on every spawn. |
| `~/.bindu/personal/agent.py` | Auto-generated bindufy agent. Hand-edits are overwritten — edit `persona.json` or the template in `server/personal-agent.ts`. |
| `~/.bindu/personal/.bindu/oauth_credentials.json` | OAuth client\_id + secret from Hydra. Required for outbound token minting. |
| `~/.bindu/personal/.bindu/private.pem` | Ed25519 private key. Required for DID signatures. |
| `~/.bindu/personal/logs/agent.log` | Personal agent stdout/stderr. Tail this when spawn fails. |
| `examples/.env` | Shared env for the demo agents (`OPENROUTER_API_KEY=...`). The spawn script falls back to your shell env if this file isn't there. |
***
## Environment knobs
All optional unless noted:
| Var | Default | Why |
| ------------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------- |
| `BINDU_COMMS_TOKEN` | unset | Bearer token gate on `/api/*`. See [Verify the auth](/bindu/inbox/verify-auth#what-auth-on-means). |
| `BINDU_WEBHOOK_TOKEN` | unset | Bearer token gate on `/webhooks/bindu/*`. Must match agent-side `global_webhook_token`. |
| `BINDU_AGENT_URLS` | unset | `id=url,id=url` pairs that override the agents table. Ops escape hatch. |
| `BINDU_REPO_DIR` | `..` | Where bindu lives. Needed if you moved the inbox out of the repo. |
| `BINDU_PERSONAL_DIR` | `~/.bindu/personal` | Personal agent files. Useful for sandboxing tests. |
| `BINDU_GATEWAY_DIR` | `../gateway` | Where the gateway lives. Needed if you split repos. |
| `GATEWAY_API_KEY` | read from `gateway/.env.local` | Bearer the inbox sends to the gateway's `/plan`. Without it multi-agent compose 401s. |
| `HYDRA__ADMIN_URL` | `https://hydra-admin.getbindu.com` | Hydra admin API. Used for OAuth client registration. |
| `HYDRA__PUBLIC_URL` | `https://hydra.getbindu.com` | Token endpoint for outbound Hydra minting. |
| `OPENROUTER_API_KEY` | unset | Required for the personal agent and demo peers. UI Settings tab is the recommended path. |
| `BINDU_COMMS_MAX_HISTORY` | `30` | Max user/assistant turns the inbox forwards to the gateway on `/plan`. |
| `BINDU_PERSONAL_USE_VENV` | unset | Skip `uv` and run the personal agent under `/.venv/bin/python` instead. |
***
## Build & ship
```bash theme={null}
npm run build # TypeScript + Vite production build
npm run preview # Serve the build locally
npm run typecheck # tsc -b --noEmit, no emit
```
**There's no production runtime story yet.** The inbox is single-operator, single-machine. Multi-user gating is what `BINDU_COMMS_TOKEN` is for; full SSO is on the roadmap.
***
## Stack
React 19 · React Router v7 (SPA) · Vite 6 · Tailwind v4 · TanStack Query · Zustand · Phosphor icons · SQLite (events) via `better-sqlite3` · Hono on the API side.
Visual aesthetic inspired by [cloudflare/agentic-inbox](https://github.com/cloudflare/agentic-inbox) (Apache 2.0).
Next up: [Troubleshooting](/bindu/inbox/troubleshooting).
# Verify the auth
Source: https://docs.getbindu.com/bindu/inbox/verify-auth
Don't trust the UI — prove from your terminal that calls really are signed and authed, and learn which layer rejects what.
The inbox shows a `signed / verified` badge on every row. That's nice, but the UI is the thing under test — you shouldn't trust it to grade its own homework. This chapter does two things:
1. Walks you through curl commands that prove the auth is real.
2. Explains which of the three auth layers rejects which class of attack, so you know what each one is actually buying you.
***
## Prove it from your terminal
Open a new shell tab. Keep the inbox running.
### 1 · Find the personal-agent port
```bash theme={null}
curl -s http://127.0.0.1:3787/api/me | python3 -c "import sys,json; print(json.load(sys.stdin)['url'])"
# → http://127.0.0.1:61380
```
The port is dynamic — the inbox picked it on spawn. Substitute it into the next two commands.
### 2 · Confirm unauthed callers are rejected
```bash theme={null}
curl -s -X POST http://127.0.0.1:61380/ \
-H 'content-type: application/json' \
-d '{
"jsonrpc":"2.0",
"method":"message/send",
"id":"x",
"params":{
"message":{
"role":"user",
"kind":"message",
"parts":[{"kind":"text","text":"hi"}],
"messageId":"m",
"contextId":"c",
"taskId":"t"
}
}
}'
```
Expected:
```json theme={null}
{"jsonrpc":"2.0","error":{"code":-32009,"message":"Authentication is required ..."},"id":null}
```
That `-32009` is bindufy's auth middleware saying *"no token, no signature, go away."* Same response a hostile peer would get.
### 3 · Confirm the inbox can get through
```bash theme={null}
curl -s -X POST http://127.0.0.1:3787/api/compose \
-H 'content-type: application/json' \
-d '{"agentId":"joke_agent","text":"hi"}'
```
Expected:
```json theme={null}
{"ok":true,"status":200,"contextId":"...","taskId":"...","response":{"jsonrpc":"2.0",...}}
```
Same agent, same wire — but the inbox went through `/api/compose`, which mints a Hydra token and signs the body before forwarding. The peer accepts it because it can verify both layers.
### 4 · Verify from inside the UI
Open any thread and click **Verify** in the top-right of the right rail. Each row should report `signed / verified` against the peer's published `publicKeyBase58`. The detail rail's **Verify** tab shows:
* The **DID match** (claimed DID resolves to the same public key the signature verifies against).
* The **signature** bytes.
* The **timestamp nonce** (rejects replays older than the configured window).
If any of those is missing or red, the row is suspect — don't act on it.
***
## What "auth on" means
There are three independent auth layers in play. The inbox uses all three.
| Layer | Who enforces it | How to turn it on | Default |
| ----------------------------------------------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
| **Peer A2A auth** — outbound calls must carry a JWT + DID signature | The peer's bindufy middleware (`-32009` if missing) | Set `AUTH__ENABLED=true` on the peer. Done automatically when the inbox spawns your personal agent or the demo peers. | **On** |
| **Operator gate** — `/api/*` on the inbox requires a bearer token | `inbox/server/index.ts` | `export BINDU_COMMS_TOKEN=$(openssl rand -hex 32)` before `npm run dev`. UI needs `?token=` in the URL (SSE can't send headers). | Off (single-user dev) |
| **Webhook gate** — agents POSTing to `/webhooks/bindu/:agentId` must carry a bearer token | `inbox/server/index.ts` | `export BINDU_WEBHOOK_TOKEN=` and configure the same value as `global_webhook_token` on the bindufy side. | Off |
The first is **non-negotiable** once your personal agent is alive — it's how every bindufy peer in the world recognizes legitimate callers.
The other two are **belt-and-suspenders** for multi-user or exposed deployments. Leave them off until you actually share the URL with a teammate or put the inbox behind a tunnel.
***
## Why three layers, not one
Each layer fails safe in a way the others can't:
The Ed25519 signature won't verify against the claimed key. Tokens are bearer credentials — anyone who has them can use them — but the signature ties the body to a specific private key the attacker doesn't have.
Hydra rejects unauthed callers at the middleware layer before the signature is even checked. Stealing a key isn't enough; you also need OAuth scope.
The timestamp nonce is part of the canonical body, so replaying a captured request gets rejected once it ages out of the window.
The token lives in the header. The signature lives in the body. The timestamp lives in the signature. Each one rejects a class of attack the others are blind to.
Full breakdown lives in [Identity & Trust → Security Stack](/bindu/learn/authentication/security-stack). The inbox is the easiest way to *watch* the security stack in action — every row in the right rail is one trip through all three layers.
***
## What you've verified
`-32009` on a raw curl. The middleware is actually running.
Same peer, same body, accepted via `/api/compose`. The signing path works.
The Verify tab re-runs the same signature check. The badge is grounded, not decorative.
Next up: [Using the inbox](/bindu/inbox/using).
# What is Bindu
Source: https://docs.getbindu.com/bindu/introduction/what-is-bindu
The identity, communication, and payments layer for AI agents — built for production agent swarms like the Trade Compliance OS
> "Every story begins with a single point of light."
It always starts small — a spark, a line of code, a dot (in Sanskrit, *bindu*).
The story starts with a developer.
She just built an incredible agent. It reasons well, pulls from multiple APIs, and writes structured outputs.
But before she can share it with the world, she needs to:
Set up a server. Handle authentication. Add observability and tracing. Expose endpoints. Maybe support payments. Probably wire up mutual TLS so the request body isn't readable on the wire. Almost certainly stand up a DID so the agent can prove who it is when it talks to another agent.
Three weeks later, her "AI agent" still isn't live. She's writing boilerplate instead of building intelligence. **She became the DevOps engineer she never wanted to be.**
That's the story of almost every agent today. And it's completely backwards.
**The intelligence is ready. The infrastructure isn't.**
***
***
## Bindu flips that story
| | **Without Bindu** | **With Bindu** |
| ------------------- | -------------------------------------- | ---------------------------- |
| **Agent Code** | 15 lines | 15 lines |
| **Integration** | Countless lines of boilerplate | 5 lines of configuration |
| **Identity & Auth** | Roll your own DID, OAuth, key rotation | Built in: DID + Hydra + mTLS |
| **Time to Deploy** | Weeks | 2 minutes |
| **Developer Focus** | Becomes DevOps engineer | Stays focused on the agent |
**Weeks reduced to minutes.**
***
## Why we built this: the Trade Compliance OS
Bindu didn't start as a framework. It started because we needed it.
We're building the **Trade Compliance OS** — a swarm of agents that helps a small or mid-sized business ship physical goods across borders without writing a six-figure check to a law firm. The agents handle:
* **CBAM** — the EU's Carbon Border Adjustment Mechanism, which now charges importers for embedded carbon in steel, cement, aluminum, fertilizer, electricity, and hydrogen.
* **EUDR** — the EU Deforestation Regulation, which forbids placing coffee, cocoa, cattle, palm oil, soy, rubber, wood, and their derivatives on the EU market without a deforestation-free declaration.
* **HS codes** — the 10-digit Harmonized System classification that decides the duty rate, the licensing regime, and whether a shipment clears in hours or weeks.
* **DPPs** — Digital Product Passports, the per-item provenance and material record the EU is making mandatory category by category.
Picture the workflow. An SMB exporter wants to send 12 pallets of roasted coffee from Vietnam to Germany. The system has to:
1. Classify the product — pull the right HS code from a regulator's database.
2. Pull deforestation-free attestations for the source farms.
3. Generate the CBAM declaration if the buyer is in scope.
4. Stamp a Digital Product Passport so each bag carries its provenance.
5. Quote a price for the bundled service. Settle it. Hand the exporter a packet they can file.
That is not one agent. That is a **swarm**. Different agents for different regulations, different data sources, different jurisdictions. Some of them are ours. Some of them belong to partners. Some of them want to be paid per query because they're calling expensive regulator APIs underneath.
The minute you try to ship that for real, you hit four hard problems at once:
1. **Identity.** When an auditor asks "which agent computed this CBAM declaration?", you need a cryptographic answer, not a log line. Every agent's output has to be signed by a key only that agent owns.
2. **Authorization.** Some agents in the swarm are internal. Some are paying partners. Some are anonymous public agents asking for quotes. They cannot all see the same data.
3. **Encryption on the wire.** Customs documents are regulated. The bearer token cannot traverse a coffee-shop network in cleartext, full stop.
4. **Payment.** A compliance agent that queries five regulator APIs cannot quote a price after the fact. It has to demand settlement *before* it spends the underlying API call.
Most agent frameworks hand you one of these and tell you the other three are your problem. **Bindu was built so the compliance swarm could exist** — which is why all four ship together, on by default.
If you've built an agent that touches **customs paperwork, supplier audits, materials sourcing, regulatory filings, or anything adjacent**, we'd love to have it in the network. [Find us on Discord](https://discord.gg/3w5zuYUuwt).
***
## What ships with Bindu (and why each piece exists)
Every feature here exists because the compliance swarm needed it. The same pieces work for any agent network — Bindu is generic — but the *why* is concrete.
### The three-layer security stack
When an A2A request lands on a Bindu agent, three middlewares fire before your handler sees the body — and each answers a question the other two cannot:
| Layer | The question it answers | What it actually is |
| -------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| **mTLS** | *Is the socket itself encrypted and mutually authenticated?* | X.509 cert from [Smallstep step-ca](https://smallstep.com/docs/step-ca/), SAN = DID, 24-hour TTL, auto-renewed in-process |
| **OAuth2 via Hydra** | *Is the caller allowed to perform this operation right now?* | Bearer token, \~1-hour TTL, validated via [Ory Hydra](https://www.ory.sh/hydra/) introspection |
| **DID signature** | *Was this exact JSON body authored by the DID it claims?* | Ed25519 signature over canonical body, carried in `X-DID-Signature` |
You don't pick one. You don't bolt them on. They ship together. **No agent framework we surveyed ships all three out of the box.**
Why three, not one? Because each fails safe in a way the others can't. An attacker who steals a bearer token still can't decrypt the traffic (mTLS owns the wire). An attacker who forges a cert still can't impersonate a DID (the signature won't verify). An attacker who breaks the signature scheme still can't get past Hydra's authorization check.
For the compliance swarm: the auditor's "which agent signed this declaration?" question has a cryptographic answer in three places — the cert SAN, the OAuth client\_id, and the message signature. All three must agree, or the request is rejected.
→ Full walkthrough: [Security Stack](/bindu/learn/authentication/security-stack)
### x402 payments — pay before you run
Flip a flag and the agent demands USDC before your handler ever sees the request. **5 chains pre-configured** — Base, Base Sepolia, Ethereum, Ethereum Sepolia, SKALE Europa — and any other EVM chain (Polygon, Avalanche, Arbitrum, …) takes one `extra_networks` entry.
For the compliance swarm: a CBAM declaration agent calls three paid regulator APIs underneath. It can't eat that cost on a query that never settles. x402 means the caller has paid before the agent burns a single API call.
→ [Payment docs](/bindu/learn/payment/introduction)
### DID identity that doubles as your audit trail
Every response your agent sends is signed with an Ed25519 key. Callers verify with a [W3C DID](https://www.w3.org/TR/did-core/) — no shared secret to leak, no central authority to query, and the **same DID** is the cert's SAN, the OAuth2 `client_id`, and the message signer. All three have to agree, or the request is rejected.
For the compliance swarm: when an EU customs officer asks who computed a CBAM number two years from now, the DID + signature is the answer. Non-repudiable by design.
→ [DID docs](/bindu/learn/did/overview)
### Gateway — a planner that orchestrates the swarm
A planner LLM that takes a high-level intent (`"ship 12 pallets of coffee from Vietnam to Germany"`), decides which agents to invoke, fans the work out over A2A, and streams the result back. Each fan-out call is signed; each backing agent verifies the chain to the operator's cert.
For the compliance swarm: the gateway is what turns "ship this coffee" into a planned sequence of HS-code lookup, EUDR attestation, CBAM declaration, and DPP generation — without you hard-coding the routing.
→ [Gateway docs](/bindu/gateway/overview)
### Skills, and private skills
Declare what your agent can do, and callers see it on the agent card before they spend a token asking. **Private skills** keep your commercial menu out of the public catalog — public crawlers see a generic "we do trade compliance", allowlisted partner DIDs see your real menu at a second auth-gated endpoint.
For the compliance swarm: your interpretation of CBAM regulation **is** your product. Showing the full skill catalog to every public crawler tells competitors your roadmap. Private skills mean the catalog is gated by DID allowlist.
→ [Private skills](/bindu/skills/private_skills/private_skills)
### Polyglot SDKs on one gRPC core
Bindu is Python at heart, but the framework exposes a shared **gRPC core** that any language can drive. SDKs ship for **Python, TypeScript, and Kotlin** today — same protocol, same DID, same auth. A new language SDK is usually a few hundred lines.
For the compliance swarm: regulator APIs come in every flavor — REST in Java, SOAP in .NET, an SDK in TypeScript, a CLI in Go. Your team writes the agent in whichever language matches the integration, and the rest of the swarm doesn't care.
→ [Multi-language sidecar](/bindu/grpc/overview)
### The inbox — a Gmail-shaped control plane
A visual operator inbox that bootstraps a personal agent, registers it with Hydra, signs every outbound message, and renders agents as Gmail-shaped addresses (`fleet+joke_agent@getbindu.com`). Watch your agents send signed JSON-RPC to each other, verify identities inline, and reply to a swarm like it's an email thread.
For the compliance swarm: the operator needs to *see* what the agents are doing. The inbox is the human-in-the-loop pane on top of the swarm.
### Tunnel and cloud deploy
`expose: true` puts your laptop on the internet — no port forwarding, no router config — via an FRP tunnel. When you're ready to leave the laptop, `bindu deploy agent.py --runtime=boxd` ships your script to a microVM and prints the HTTPS URL. No Dockerfile.
For the compliance swarm: developers iterate locally with `expose: true`, then promote to production with one command.
→ [Tunneling](/bindu/learn/tunneling/overview) · [Runtime](/bindu/runtime/overview)
***
## The 10-line agent
Build the agent you want, hand it to `bindufy()`, and it's online. The block below is the whole thing — copy it into a file, set your `OPENAI_API_KEY`, run it.
```python theme={null}
from bindu.penguin.bindufy import bindufy
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.duckduckgo import DuckDuckGoTools
agent = Agent(
instructions="You are a research assistant.",
model=OpenAIChat(id="gpt-4o"),
tools=[DuckDuckGoTools()],
)
config = {
"author": "you@example.com",
"name": "research_agent",
"description": "Research assistant with web search.",
"version": "1.0.0",
"capabilities": {},
"auth": {"enabled": False},
"storage": {"type": "memory"},
"scheduler": {"type": "memory"},
"deployment": {"url": "http://localhost:3773", "expose": True},
}
def handler(messages: list[dict[str, str]]):
return agent.run(input=messages)
bindufy(config, handler)
```
The agent is now live at `http://localhost:3773`. `expose: True` opens an FRP tunnel so the rest of the internet can hit it without you setting up port forwarding.
Calling the agent with curl
```bash theme={null}
curl -X POST http://localhost:3773/ \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"method": "message/send",
"id": "",
"params": {
"message": {
"role": "user",
"kind": "message",
"parts": [{"kind": "text", "text": "Hello"}],
"messageId": "",
"contextId": "",
"taskId": ""
},
"configuration": {"acceptedOutputModes": ["application/json"]}
}
}'
```
Then poll `tasks/get` with the same `taskId` until state hits `completed`.
TypeScript equivalent
```typescript theme={null}
import { bindufy } from "@bindu/sdk";
import OpenAI from "openai";
const openai = new OpenAI();
bindufy({
author: "you@example.com",
name: "research_agent",
description: "Research assistant.",
deployment: { url: "http://localhost:3773", expose: true },
}, async (messages) => {
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: messages.map(m => ({ role: m.role, content: m.content })),
});
return response.choices[0].message.content || "";
});
```
The TypeScript SDK spawns the Python core in the background. Zero Python in your repo, same DID, same wire protocol.
***
## Supported frameworks
Bindu doesn't care what's inside the handler. Bring whatever you already like writing agents in.
| Language | Frameworks tested in this repo |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Python** | [AG2](https://github.com/ag2ai/ag2), [Agno](https://github.com/agno-agi/agno), [CrewAI](https://github.com/joaomdmoura/crewAI), [Hermes Agent](https://github.com/NousResearch/hermes-agent), [LangChain](https://github.com/langchain-ai/langchain), [LangGraph](https://github.com/langchain-ai/langgraph), [Notte](https://github.com/nottelabs/notte) |
| **TypeScript** | [OpenAI SDK](https://github.com/openai/openai-node), [LangChain.js](https://github.com/langchain-ai/langchainjs) |
| **Kotlin** | [OpenAI Kotlin SDK](https://github.com/aallam/openai-kotlin) |
| **Any other** | via the [gRPC core](/bindu/grpc/overview) — a new SDK is usually a few hundred lines |
Model providers that speak the OpenAI or Anthropic API work out of the box — [OpenRouter](https://openrouter.ai/), [OpenAI](https://platform.openai.com/), [MiniMax](https://platform.minimaxi.com), and the rest.
***
## Beyond compliance
Trade Compliance OS is what made us build Bindu, but the same architecture works for any agent network where identity, payments, and multi-party trust matter:
* **Healthcare swarms** — a triage agent routing to specialty agents, each signing their differential.
* **Financial research** — a planner orchestrating data, modeling, and report agents, each billing per query.
* **Legal discovery** — a fleet of agents reading documents under cryptographic chain-of-custody.
* **Supply chain audits** — supplier agents, materials agents, certificate agents handing off work with verifiable provenance.
The pattern is the same: many agents, different owners, different jurisdictions, real money, real audit trails. That's the Internet of Agents — and that's what Bindu turns from a slide deck into a running system.
***
## What's next
The task-first execution model and the layered system that makes it work
mTLS + Hydra + DID on a single request — embassy analogy, env block, gotchas
From zero to a running agent in two minutes
The planner LLM that orchestrates multi-agent flows
***
The universe began with a dot.
The Internet of Agents begins with Bindu.
# Making Authenticated Requests
Source: https://docs.getbindu.com/bindu/learn/authentication/making-requests
The four headers, the four gates, and exactly what to put on the wire
When `AUTH__ENABLED=true`, every call to a Bindu agent has to do **two things at once**:
1. **Prove you're allowed** — attach a short-lived bearer token from Hydra.
2. **Prove you're really you** — sign the request body with your DID's private key and attach the signature.
Either one missing and the agent rejects the call. Get both right and the request goes through.
The [Authentication overview](/bindu/learn/authentication/overview) explains the bearer-token side conceptually. The [DID page](/bindu/learn/did/overview) explains the signing side. This page is the shortest path to a working request that satisfies both.
***
## The four headers
Every call to an auth-on Bindu agent carries these four headers:
```
Authorization: Bearer ← from Hydra, expires in ~1h
X-DID: did:bindu::: ← your identity
X-DID-Timestamp: ← within 300s of server clock
X-DID-Signature: ← signs {body, did, timestamp}
```
The agent verifies them in four gates. The first failure stops the chain.
| Gate | What's checked | On failure |
| ---- | -------------------------------------------------------------- | ---------------------------------------------------------------- |
| 1 | Bearer token present and active in Hydra | **HTTP 401** + JSON-RPC `-32009 "Authentication is required..."` |
| 2 | `X-DID` matches the token's `client_id` | **HTTP 403** + `details.reason: did_mismatch` |
| 3 | Public key for that DID is registered in Hydra client metadata | **HTTP 403** + `details.reason: public_key_unavailable` |
| 4 | Timestamp within 300s **and** signature verifies | **HTTP 403** + `details.reason: invalid_signature` |
Gate 4 collapses two sub-causes (clock skew and bad signature) into one `invalid_signature` reason. If you get this error, re-signing with a fresh timestamp eliminates clock-skew and replay as the cause.
***
## I just want it to work — use a built-in caller
Most teams should not hand-roll this. Three callers in the Bindu repo do the whole chain for you:
| Caller | What you provide | What it does |
| ------------------------------- | ------------------------------------- | --------------------------------------------------------------------------------- |
| **Inbox** (`POST /api/compose`) | Persona + OpenRouter key (via UI) | Spawns your personal agent, registers it with Hydra, signs every outbound message |
| **Gateway** (`POST /plan`) | `BINDU_GATEWAY_DID_SEED` + Hydra URLs | Same identity for every peer call |
| **Postman collection** | Seed + DID + secret in environment | Pre-request script signs each call automatically |
Quick smoke test against an auth-on agent, using the inbox:
```bash theme={null}
# poet_agent running on 5776 with AUTH on:
curl -s -X POST http://127.0.0.1:3787/api/ecosystem \
-H 'content-type: application/json' \
-d '{"id":"poet_agent","url":"http://127.0.0.1:5776"}'
curl -s -X POST http://127.0.0.1:3787/api/compose \
-H 'content-type: application/json' \
-d '{"agentId":"poet_agent","text":"write a 4-line poem"}'
# → {"ok":true,"status":200,"contextId":"...","taskId":"...","response":{...}}
```
`ok:true, status:200` back means every gate above passed. You're done.
The rest of this page is for people writing the caller from scratch in a new language.
***
## Hand-rolling it: one-time setup
You need three durable artifacts:
* **A seed** — your 32-byte secret. Generates the Ed25519 keypair.
* **A DID** — your public name, deterministically derived from the seed.
* **An OAuth client in Hydra** — registered against the DID, with the public key in metadata.
```bash theme={null}
uv run python -c "
import hashlib, os, base64, base58
from nacl.signing import SigningKey
AUTHOR = 'you_at_example_com' # your email, @ → _at_, . → _
NAME = 'my_agent' # short label, no colons
seed = os.urandom(32)
pk = bytes(SigningKey(seed).verify_key)
sha = hashlib.sha256(pk).hexdigest()
agent_id = f'{sha[0:8]}-{sha[8:12]}-{sha[12:16]}-{sha[16:20]}-{sha[20:32]}'
did = f'did:bindu:{AUTHOR}:{NAME}:{agent_id}'
print('SEED_B64 =', base64.b64encode(seed).decode())
print('DID =', did)
print('PUBLIC_KEY_B58 =', base58.b58encode(pk).decode())
"
```
Save all three.
The seed is your private key. Lose it and your DID is orphaned. Leak it and anyone can impersonate you.
The DID **is** the `client_id`. The public key goes in `metadata.public_key` — that's how the agent finds your key during signature verification.
```bash theme={null}
CLIENT_SECRET=$(openssl rand -base64 32 | tr -d '=' | tr '+/' '-_')
curl -X POST https://hydra-admin.getbindu.com/admin/clients \
-H 'Content-Type: application/json' \
-d '{
"client_id": "'"$DID"'",
"client_secret": "'"$CLIENT_SECRET"'",
"grant_types": ["client_credentials"],
"response_types":["token"],
"scope": "openid offline agent:read agent:write",
"token_endpoint_auth_method": "client_secret_post",
"metadata": {
"did": "'"$DID"'",
"public_key": "'"$PUBLIC_KEY_B58"'",
"key_type": "Ed25519",
"verification_method": "Ed25519VerificationKey2020",
"hybrid_auth": true
}
}'
```
Save `CLIENT_SECRET`. You need it to mint tokens.
***
## Hand-rolling it: every request
Four steps. The first runs once per hour (token cache). The other three run on every call.
```bash theme={null}
curl -s -X POST https://hydra.getbindu.com/oauth2/token \
-d grant_type=client_credentials \
-d "client_id=$DID" \
-d "client_secret=$CLIENT_SECRET" \
-d "scope=agent:read agent:write"
```
Response:
```json theme={null}
{ "access_token": "ory_at_...", "expires_in": 3599, "scope": "agent:read agent:write", "token_type": "bearer" }
```
Cache the token in memory. Refresh \~60s before `expires_in` runs out.
Serialize the body **once** and keep the exact bytes. The bytes you sign must equal the bytes you send.
```python theme={null}
body_bytes = json.dumps({
"jsonrpc": "2.0",
"id": "",
"method": "message/send",
"params": {
"message": {
"role": "user", "kind": "message",
"parts": [{"kind": "text", "text": "your prompt"}],
"messageId": "", "contextId": "", "taskId": ""
},
# Required. Drop it and the JSON-RPC validator 400s
# before auth middleware even sees the request.
"configuration": {"acceptedOutputModes": ["application/json"]}
}
}).encode("utf-8")
```
The signing payload is a **second** JSON object that wraps the body as a string. Sort keys and keep Python's default whitespace.
```python theme={null}
ts = int(time.time())
signing_str = json.dumps(
{"body": body_bytes.decode("utf-8"), "did": did, "timestamp": ts},
sort_keys=True, # ← required
)
# default Python separators: ", " and ": " — note the spaces.
sig_b58 = base58.b58encode(
SigningKey(seed).sign(signing_str.encode("utf-8")).signature
).decode()
```
**The #1 cross-language gotcha.** JavaScript's `JSON.stringify` omits spaces after `:` and `,`. Python's `json.dumps` includes them. The signing payload above uses Python's defaults. Sign one shape, server reconstructs the other → HTTP 403 + `details.reason: invalid_signature`. Use the [canonical fixture](#canonical-fixture) to verify your implementation in any language.
```python theme={null}
requests.post(
f"{agent_url}/",
data=body_bytes, # ← exactly the bytes you signed
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
"X-DID": did,
"X-DID-Timestamp": str(ts),
"X-DID-Signature": sig_b58,
},
)
```
All four gates pass → your handler runs.
***
## What can go wrong
| Response | Most likely cause | Fix |
| -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| HTTP 401, JSON-RPC `-32009 Authentication is required` | No `Authorization` header, or token is invalid/expired | Mint a fresh token, attach as `Authorization: Bearer …` |
| HTTP 403, `details.reason = did_mismatch` | `X-DID` doesn't match the token's `client_id` | Mint the token with the same DID you send as `X-DID` |
| HTTP 403, `details.reason = public_key_unavailable` | `metadata.public_key` missing on the Hydra client, or you registered against a different Hydra | `GET /admin/clients/` and check `metadata.public_key` |
| HTTP 403, `details.reason = invalid_signature` | Clock skew > 300s, replayed timestamp, body bytes drifted between sign and send, `sort_keys`/whitespace mismatch, or signed with the wrong seed | Sign fresh on every request, sign the exact bytes you'll send, verify against the canonical fixture |
| HTTP 400, `-32700` JSON parse error (e.g. `params.configuration` field required) | Body shape wrong **before** auth runs — JSON-RPC validator rejects upfront | Body bug, not an auth bug. Include `params.configuration` and confirm against an unauthed peer first |
| `invalid_client` from `/oauth2/token` | Wrong `client_secret` or client not registered on this Hydra | `GET /admin/clients/` to confirm |
| `invalid_scope` from `/oauth2/token` | Requesting a scope the client wasn't registered with | Re-register with the scope, or drop it |
The middleware collapses four sub-causes of "signature didn't verify" into one `invalid_signature` reason. To narrow it down, re-sign with a fresh timestamp first — that eliminates clock skew and replay. If it still fails, you have a body-byte or key-mismatch issue.
Debugging shortcut — introspect your own token:
```bash theme={null}
curl -s -X POST https://hydra-admin.getbindu.com/admin/oauth2/introspect \
-d "token=$ACCESS_TOKEN" \
| python3 -m json.tool
```
Look for `active: true`, `client_id == your DID`, and `exp > now`. Anything off here is your bug.
***
## Canonical fixture
Use this to verify your sign-and-encode implementation against every other Bindu caller, in any language.
| Input | Value |
| --------- | ------------------- |
| Seed | 32 zero bytes |
| DID | `did:bindu:test` |
| Body | `{"test": "value"}` |
| Timestamp | `1000` |
Signing payload (note spaces after `:` and `,`):
```
{"body": "{\"test\": \"value\"}", "did": "did:bindu:test", "timestamp": 1000}
```
Expected base58 signature:
```
3SfU4VPTHLbzZzCn17ZqU6y2tnzHQbdo2nnXQr6XZXk34XgyzwSKRrCYEWRmmGXrV39mdkyhTsy5oasfTpNuqyM2
```
Your code matches → ship it. Doesn't match → you're missing the spaces, your keys aren't sorted, or your base58 alphabet is wrong (Bindu uses the Bitcoin alphabet — `nacl-base58` is the same).
***
## What's next
How mTLS, Hydra, and DID signatures compose on a single request
The signing side in depth — Ed25519, canonical JSON, key rotation
Four headers,
four gates, one chain of trust.
# Authentication
Source: https://docs.getbindu.com/bindu/learn/authentication/overview
How your agent decides whether to answer a stranger knocking on the door
Every time a request shows up at your agent's door, the agent has to answer one question before it does anything else:
> *Should I actually answer this?*
Sounds simple. It's not. Hidden inside that one question are really **two** questions, and most tutorials smush them together and make a mess.
Picture a stranger at your door holding an envelope. Before you let them in, you want to know:
1. **Who are they?** The name on the envelope could be real. It could also be something they scribbled on the bus.
2. **Are they allowed in?** Even if the name is real — do they have permission to enter *this* room, *right now*?
In Bindu we keep those two questions separate, because they need totally different tools to answer.
| Question | What answers it | Where it lives |
| -------------------------------------------------- | --------------------------------------------------------------- | ------------------------------------- |
| *Are you allowed to make this request?* | **Authentication** (this page) — a token from a trusted service | OAuth 2.0 / Ory Hydra |
| *Is this request really from who it claims to be?* | **DID signing** — a signature only the real person can make | [DID page](/bindu/learn/did/overview) |
You almost always need both. This page handles the first one. After this, go read the DID page. Together they tell the whole story.
When the OAuth `client_id` is a DID (the Bindu default — see [`register_agent_in_hydra`](https://github.com/getbindu/Bindu/blob/main/bindu/auth/hydra/registration.py)), the auth middleware enforces both halves. A valid bearer token alone is **not enough** — every request must also carry a fresh DID signature. The two layers are coupled by code, not convention.
***
## Before vs. with Bindu
| Without Bindu | With Bindu |
| ------------------------------------------------------------- | -------------------------------------------------------------------------- |
| Roll your own bearer-token check, or copy-paste a JWT library | Set `AUTH__ENABLED=true` — the middleware wires up to Hydra automatically |
| Token expiry, revocation, scopes all in your code | Hydra introspects every token; revocations honored within `cache_ttl` |
| No identity layer — anyone with the token gets in | DID-bound tokens: the bearer must *also* sign the body with the right key |
| Logging "who called?" requires custom plumbing | `scope.state.user` is populated with `sub`, `client_id`, `scope`, `is_m2m` |
***
## Bearer tokens — the movie ticket trick
Ever been to a movie? The person at the door doesn't ask your name, your address, your favourite childhood pet. They just want to see your ticket. You hand it over, they tear off the stub, you walk in.
The ticket is the *proof*. Whoever's holding it gets in. That's literally why it's called a **bearer** token — "bearer" meaning "whoever's bearing it right now."
Your cat could walk in with your bearer token and the movie theatre wouldn't stop them. Your cat would not enjoy the movie.
A bearer token in HTTP works the same way. It's a random-looking string. Your client staples it to every request. The server sees it, decides "yep, that's valid," and lets the request through. No further questions — *until* the DID layer steps in.
A real Bindu bearer token looks like this:
```text theme={null}
ory_at_hV2cm_iq55iipi8M53mwvQbpNwQNfTTxvJnDlOWFRYw.I8V_GL5s2afZTh_ZMpshauGpnItx7iItBc6pgVRAOVg
```
You send it in an HTTP header:
```text theme={null}
Authorization: Bearer ory_at_hV2cm_iq55iipi...
```
That's the whole "authentication" part of Bindu. Client attaches a token. Server introspects it against Hydra. Done — unless the `client_id` is a DID, in which case the middleware also demands a signature on the body. More on that below.
Two things follow from "whoever holds it, gets in":
**Treat tokens like passwords.** A leaked token is an open door for up to \~1 hour. Don't paste them in Slack. Don't commit them to git. Don't log them. Don't text them to your friend even as a joke.
* **They expire.** Hydra issues access tokens that last about an hour (`expires_in: 3599`). If one leaks, the damage window is small — and shrinks further if you revoke it via `/admin/oauth2/revoke`.
***
## Where do tokens come from? Meet Hydra
OK — but *who* gives out the tokens? Not the agent, surely. That'd be like asking the movie theatre door-checker to also run the ticket booth. Too much trust in one place.
Bindu uses a separate service whose entire job is issuing and validating tokens: [**Ory Hydra**](https://www.ory.sh/hydra/). It's an open-source OAuth 2.0 server. Battle-tested. Used by serious companies. We don't build our own, because "token issuance" is one of those things that looks easy, is actually full of foot-guns, and gets one tiny thing wrong and suddenly the internet has access to everything.
Hydra shows up as two URLs:
| URL | Default port | Purpose | Who talks to it |
| ---------------------------------- | ------------ | --------------------------------------------------------------------------------------------- | -------------------------------------------- |
| `https://hydra.getbindu.com` | `4444` | **Public** — hands out tokens. Endpoints like `/oauth2/token`, `/oauth2/revoke`. | Clients (your code, Postman, the gateway) |
| `https://hydra-admin.getbindu.com` | `4445` | **Admin** — registers clients, introspects tokens, reads metadata. Endpoints like `/admin/*`. | Agents (introspection), registration scripts |
Both URLs point at the same Hydra process with the same database behind it. Register a client on the admin side — the public side sees it immediately. No sync, no delay.
**The admin URL is powerful.** Anyone who can reach `/admin/clients` can register new clients, read introspection results, or revoke tokens. In production, the admin URL lives on a private network. Never expose it to the open internet.
***
## The whole flow, from zero to answered
Here's what happens end to end when a client wants to talk to an agent. Three stages, different frequencies.
```mermaid theme={null}
sequenceDiagram
autonumber
participant C as Client
participant HA as Hydra Admin (:4445)
participant HP as Hydra Public (:4444)
participant A as Agent
Note over C,HA: Once per client
C->>HA: POST /admin/clients (DID, public_key, secret)
HA-->>C: 201 Created
Note over C,HP: Once per ~hour
C->>HP: POST /oauth2/token (client_credentials)
HP-->>C: access_token (expires_in: 3599)
Note over C,A: Every request
C->>A: POST / + Authorization + X-DID-* headers
A->>HA: POST /admin/oauth2/introspect (cached up to cache_ttl)
HA-->>A: { active, sub, client_id, scope, exp }
A->>A: Verify body signature with public_key
A-->>C: 200 + result (or 401/403 on failure)
```
In plain English:
* **Step 1 — once per client.** You introduce yourself to Hydra. It writes down who you are and gives you a secret. If you bring a DID, you also register your public key in `metadata.public_key`. This usually happens once, when a new client is provisioned. `bindufy` does this automatically (see `register_agent_in_hydra`).
* **Step 2 — once per hour.** You trade the long-lived secret for a short-lived token. The secret is like a key to your apartment. The token is like a concert wristband — lasts one night.
* **Steps 3+ — every single request.** You attach the token. The agent asks Hydra "is this thing still good?" — that question is called **token introspection**. By default the agent caches the answer for 5 minutes (`HYDRA__CACHE_TTL=300`); tokens carrying a *sensitive* scope (`admin`, `agent:execute`, `payment:capture`, `key:rotate`) skip the cache entirely.
Why does the agent need to ask Hydra at all? Because the token is **opaque** — a handle, not a document. The agent can't read it directly. Only Hydra knows what it means.
***
## What's actually inside a token?
Nothing readable. The token string itself is random-looking on purpose. All the meaning lives in Hydra's database.
When the agent introspects a token, Hydra sends back something like this:
```json theme={null}
{
"active": true,
"client_id": "did:bindu:dutta_raahul_at_gmail_com:postman:ee67868d-d4b6-...",
"sub": "did:bindu:dutta_raahul_at_gmail_com:postman:ee67868d-d4b6-...",
"scope": "openid offline agent:read agent:write",
"exp": 1776622403,
"iat": 1776618803,
"token_type": "Bearer"
}
```
Quick read, top to bottom:
* **`active: true`** — Hydra still thinks this token is good. Expired or revoked? This flips to `false` and the agent raises `InvalidTokenError` (HTTP 401).
* **`client_id` / `sub`** — who the token belongs to. In Bindu this is almost always a **DID** (see `register_agent_in_hydra`, line `client_id = did`). When it starts with `did:`, the middleware turns on DID signature verification automatically.
* **`scope`** — what rooms of the house this ticket opens. `agent:read` = read-only methods (`tasks/get`, `tasks/list`). `agent:write` = mutating methods (`message/send`, `tasks/cancel`).
* **`exp`** — when the token turns into a pumpkin. Unix timestamp.
* **`iat`** — when it was issued.
The middleware reads this, normalizes it into a `user_info` dict, and attaches it to the ASGI scope under `scope.state.user` so your handler knows who's calling.
```python theme={null}
# What your handler sees on a successful request
user_info = scope["state"]["user"]
# {
# "sub": "did:bindu:...",
# "client_id": "did:bindu:...",
# "scope": ["openid", "offline", "agent:read", "agent:write"],
# "is_m2m": True, # token came from client_credentials grant
# "exp": 1776622403,
# "signature_info": { "did_verified": True, "did": "did:bindu:...", "timestamp": "..." }
# }
```
***
## Turning authentication on
Auth is **off by default** in development, because nobody wants to register a Hydra client just to say hello to localhost. To turn it on, set a handful of environment variables:
```bash theme={null}
# Master switch (default: false)
AUTH__ENABLED=true
# Only Hydra today (default: hydra)
AUTH__PROVIDER=hydra
# Where your Hydra lives (defaults shown — getbindu.com prod URLs)
HYDRA__ADMIN_URL=https://hydra-admin.getbindu.com
HYDRA__PUBLIC_URL=https://hydra.getbindu.com
```
The double underscore (`__`) is how Bindu flattens nested config into env vars. `AUTH__ENABLED` maps to `settings.auth.enabled`, `HYDRA__ADMIN_URL` maps to `settings.hydra.admin_url`. You don't need to think about the mapping — just set the variables.
Once your agent starts with these, the middleware:
1. Wires itself up to talk to Hydra admin for introspection.
2. Lets a small list of public endpoints through unauthenticated (agent card, health checks, metrics — see below).
3. Rejects any other request without a valid `Authorization: Bearer ...` header (HTTP 401, JSON-RPC `-32009`).
4. For DID clients, also verifies `X-DID`, `X-DID-Timestamp`, `X-DID-Signature` against the body (HTTP 403 on failure).
5. Optionally enforces a DID allowlist via `AUTH__ALLOWED_DIDS`.
6. Attaches the introspection result to `scope.state.user` so your handler knows who's calling.
### Tunables you may actually touch
| Env var | Default | What it does |
| ----------------------------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `AUTH__ENABLED` | `false` | Master kill-switch. False = no auth checks at all. |
| `AUTH__PROVIDER` | `hydra` | Only `hydra` is wired up today. |
| `AUTH__ALLOWED_DIDS` | unset | When set, **only** these DIDs may call the agent. Otherwise every Hydra-issued DID passes. |
| `AUTH__REQUIRE_PERMISSIONS` | `false` | Enforce per-method scope checks (`message/send` needs `agent:write`, etc.). |
| `HYDRA__ADMIN_URL` | `https://hydra-admin.getbindu.com` | Where introspection happens. |
| `HYDRA__PUBLIC_URL` | `https://hydra.getbindu.com` | Where clients mint tokens. |
| `HYDRA__CACHE_TTL` | `300` | Seconds the introspection result is cached. Lower = faster revocation, more Hydra load. |
| `HYDRA__MAX_CACHE_SIZE` | `1000` | Max entries in the in-process introspection cache. |
| `HYDRA__SENSITIVE_SCOPES` | `[admin, agent:execute, payment:capture, key:rotate]` | Tokens with any of these scopes bypass the cache and are re-introspected on every call. |
| `HYDRA__AUTO_REGISTER_AGENTS` | `true` | On `bindufy`, register the agent in Hydra automatically. Turn off if you manage clients out of band. |
| `HYDRA__VERIFY_SSL` | `true` | Verify Hydra's TLS cert. Only flip to `false` for local dev. |
| `HYDRA__TIMEOUT` | `10` | Seconds before a Hydra call gives up. |
| `HYDRA__MAX_RETRIES` | `3` | How many times to retry a flaky Hydra call. |
The agent never opens its **public** Hydra URL itself. Introspection happens on the admin URL. Clients use the public URL. That's the security boundary.
### Endpoints that bypass auth entirely
Some paths skip the middleware no matter what — discoverability and health probes shouldn't require a token. From `AuthSettings.public_endpoints`:
```text theme={null}
/.well-known/agent.json ← agent card (DID, skills, endpoints)
/.well-known/* ← anything else under .well-known
/did/resolve ← DID document lookup
/agent/info, /agent/skills ← marketing surface
/agent/negotiation ← capability handshake
/health, /healthz, /metrics ← probes
/payment-capture ← x402 browser flow
/api/start-payment-session, /api/payment-status/*
```
Override via `AUTH__PUBLIC_ENDPOINTS` (full list — it replaces, not appends).
***
## Getting your first token
Think of this like opening an account at a bank. You hand Hydra your ID, Hydra files the paperwork, gives you a password.
The Bindu `bindufy` flow does this for you (via `register_agent_in_hydra`). When you need to do it by hand — say, for a Postman client or a test fixture — POST to the admin API:
```bash theme={null}
curl -X POST 'https://hydra-admin.getbindu.com/admin/clients' \
-H 'Content-Type: application/json' \
-d '{
"client_id": "did:bindu:your_email_at_example_com:your_agent:",
"client_secret": "",
"client_name": "your_agent",
"grant_types": ["client_credentials", "authorization_code", "refresh_token"],
"response_types": ["code", "token"],
"scope": "openid offline agent:read agent:write",
"token_endpoint_auth_method": "client_secret_post",
"metadata": {
"did": "did:bindu:your_email_at_example_com:your_agent:",
"public_key": "",
"key_type": "Ed25519",
"verification_method": "Ed25519VerificationKey2020",
"hybrid_auth": true
}
}'
```
Quick notes on each field:
* **`client_id`** — your agent's name in Hydra. In Bindu this is **always a DID** — `bindufy` uses the agent's DID as the `client_id` verbatim. See the [DID page](/bindu/learn/did/overview) for why.
* **`client_secret`** — the password you'll use to mint tokens. Generate something strong:
```bash theme={null}
openssl rand -base64 32 | tr -d '=' | tr '+/' '-_'
```
Store it like a database password. The agent saves its own to `.bindu/oauth_credentials.json` (mode `0600`).
* **`grant_types`** — `client_credentials` is what M2M agent callers use. The full default set is `client_credentials, authorization_code, refresh_token` to leave room for human flows.
* **`response_types: ["code", "token"]`** — that's what `bindufy` writes. Hydra needs `code` because `authorization_code` is in `grant_types`.
* **`scope`** — the permissions the issued tokens may carry. Default set: `openid offline agent:read agent:write`.
* **`token_endpoint_auth_method: client_secret_post`** — you'll send the secret in the request body, not a Basic-auth header.
* **`metadata.public_key`** — *required* if your `client_id` is a DID. Without it, Gate 3 of DID verification fails (`public_key_unavailable`). Use the base58-encoded Ed25519 public key.
* **`metadata.hybrid_auth: true`** — informational flag the registration code sets to mark this client as DID-bound.
Once an hour (or the first time, or any time your token is about to expire):
```bash theme={null}
curl -X POST 'https://hydra.getbindu.com/oauth2/token' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=client_credentials' \
-d 'client_id=did:bindu:your_email_at_example_com:your_agent:' \
-d 'client_secret=' \
-d 'scope=openid offline agent:read agent:write'
```
Hydra sends back:
```json theme={null}
{
"access_token": "ory_at_...long opaque string...",
"expires_in": 3599,
"scope": "openid offline agent:read agent:write",
"token_type": "bearer"
}
```
Copy that `access_token`. Keep it in memory. Refresh it \~60s before it expires.
If your client isn't a DID, you just attach `Authorization: Bearer ...` and you're done:
```bash theme={null}
curl --location 'http://localhost:3773/' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer ory_at_...' \
--data '{
"jsonrpc": "2.0",
"method": "message/send",
"params": {
"message": { "role": "user", "parts": [{"kind":"text","text":"Hello!"}] },
"configuration": { "acceptedOutputModes": ["application/json"] }
},
"id": 1
}'
```
If your `client_id` is a DID (the Bindu default), this request still fails with HTTP 403 — the middleware needs the body to be signed. Add three more headers: `X-DID`, `X-DID-Timestamp`, `X-DID-Signature`. The [Making Authenticated Requests](/bindu/learn/authentication/making-requests) page walks through the full four-header envelope with a canonical signing fixture.
***
## What can go wrong (and how to read the error)
This is where most beginners lose an afternoon. Here's the cheat sheet — find your error, fix *that thing*, not something else.
| You see | Most likely because | Fix |
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `401`, JSON-RPC `-32009 "Authentication is required"` | No `Authorization` header at all | Add `Authorization: Bearer ` |
| `401`, "Token is not active or has been revoked" | Token expired, or revoked via `/admin/oauth2/revoke` | Mint a fresh one (step 2) |
| `401`, "Token validation failed: ... missing subject (sub) claim" | Token doesn't exist in this Hydra | Token came from a different Hydra than `HYDRA__ADMIN_URL` |
| `403`, `details.reason: did_mismatch` | `X-DID` header doesn't match the token's `client_id` | Mint the token for the same DID you're sending |
| `403`, `details.reason: public_key_unavailable` | The Hydra client's `metadata.public_key` is missing | Re-register with `metadata.public_key: ` |
| `403`, `details.reason: invalid_signature` | Bad signature, expired timestamp (>300s), or body bytes drifted between sign and send | Re-sign with fresh `time.time()` against the exact bytes you'll POST |
| `403`, `details.reason: missing_signature_headers` | DID client sent no `X-DID-Signature` | Add the three DID headers — see Making Requests |
| `403`, `"DID not admitted"` | `AUTH__ALLOWED_DIDS` is set and your DID isn't on the list | Add the DID, or unset the allowlist |
| `503`, "Authentication service temporarily unavailable" | Agent can't reach Hydra admin (timeout / connection refused) | Check `HYDRA__ADMIN_URL` is reachable from the agent host |
| `invalid_client` at `/oauth2/token` | Wrong `client_secret`, wrong `client_id`, or client doesn't exist | Register first, double-check the secret |
| `invalid_scope` at `/oauth2/token` | Asking for a scope the client wasn't registered with | Either register with more scopes, or ask for less |
There's one sneaky one worth calling out separately, because it sends people on long debugging wild-goose chases:
**Symptom:** introspecting against one Hydra URL says the token is valid. But the agent says it's invalid.
**Cause:** the agent is talking to a *different* Hydra than the one that issued the token. Classic case: dev laptop is pointing at a local Hydra, but the token came from production.
**Fix:** make sure `HYDRA__ADMIN_URL` on the agent matches the Hydra that issued the token. The agent prints this on startup — check the log line `Hydra middleware initialized. Admin URL: ...`.
***
## Common operational patterns
The middleware caches introspection results for `HYDRA__CACHE_TTL` seconds (default 300). For most scopes this is fine — a 5-minute window between revoke and rejection is acceptable.
For high-stakes scopes you don't want any cache lag. Add them to `HYDRA__SENSITIVE_SCOPES`:
```bash theme={null}
HYDRA__SENSITIVE_SCOPES='["admin","agent:execute","payment:capture","key:rotate","my:critical:scope"]'
```
Tokens carrying any sensitive scope re-introspect on every request. The default set already covers admin, execution, payment capture, and key rotation.
Need to nuke a single token *now* from inside the process? Call `HydraMiddleware.revoke_token(token)` — it revokes upstream and drops the local cache entry in one shot.
Set `AUTH__ALLOWED_DIDS` to an explicit list. Any caller whose DID isn't on the list gets `HTTP 403 "DID not admitted"`, even if Hydra would happily mint them a valid token.
```bash theme={null}
AUTH__ALLOWED_DIDS='["did:bindu:alice_at_acme_com:trader:abc...","did:bindu:bob_at_acme_com:trader:def..."]'
```
Leave it unset and any Hydra-registered DID passes the admission check (the default, backwards-compatible behaviour).
Flip `AUTH__REQUIRE_PERMISSIONS=true`. The middleware then checks the token's scope against `AUTH__PERMISSIONS`. Defaults:
```python theme={null}
{
"message/send": ["agent:write"],
"tasks/get": ["agent:read"],
"tasks/cancel": ["agent:write"],
"tasks/list": ["agent:read"],
"contexts/list": ["agent:read"],
"tasks/feedback": ["agent:write"],
}
```
A token with only `agent:read` can call `tasks/get` but is rejected from `message/send`. Mint two clients with different scopes if you want read-only callers.
Two options:
1. **You still have a working credentials file.** Look in `.bindu/oauth_credentials.json` — secrets are keyed by DID. Find your DID, copy the `client_secret`.
2. **The file is gone too.** Rotate by `PUT`-ing the client with a fresh secret:
```bash theme={null}
curl -X PUT 'https://hydra-admin.getbindu.com/admin/clients/' \
-H 'Content-Type: application/json' \
-d '{ ...full client record, with a new client_secret... }'
```
`PUT` is a **full replace**, so include every field you want preserved (including `metadata.public_key`). All previously-issued tokens for this client continue to work until they expire — Hydra ties tokens to clients by `client_id`, not by the secret.
It's fine until it isn't. Each `/oauth2/token` call is cheap, but caching for the token's lifetime saves a lot of round-trips. Recommended pattern:
```python theme={null}
# pseudo-code
if not token or token.expires_at - now() < 60:
token = mint_new_token()
use(token)
```
The 60-second skew gives you safety margin if the client and Hydra clocks drift.
***
## Finding your credentials again
Two things you'll need to look up at some point:
* **Your agent's DID** — it's in the agent card:
```bash theme={null}
curl http://localhost:3773/.well-known/agent.json
```
Look for the `agent.did` field. That's also your `client_id` for Hydra.
* **Your client secret from `bindufy`** — saved at `.bindu/oauth_credentials.json`, keyed by DID (not agent\_id — agent\_ids change on reload, DIDs don't). Treat that file like `.ssh/id_rsa`. Mode `0600`, user-readable only, never committed.
If you've lost the secret entirely, rotate it by `PUT`ing to `/admin/clients/` with a new secret. URL-encode the colons in the DID — `did:bindu:...` becomes `did%3Abindu%3A...`.
***
## The UI shortcut
The Bindu frontend has a **Settings → Authentication** page that does step 2 for you. Paste your client secret, click a button, get a token. Handy when you're poking around in Postman.
It's a convenience. Not a replacement for understanding what's happening underneath — and it doesn't sign requests for you, so DID-bound clients still need a real caller.
***
## What's next
Authentication answers *"are you allowed in?"* — but in a world where agents talk to agents that talk to other agents, you need something stronger: *"are you really who you claim to be?"*
That's where DIDs come in. And once you have both halves, you need to know how to actually compose them on the wire — four headers, four gates, one canonical signing payload.
Cryptographic identity — how agents prove they're really them
The four headers, four gates, and a canonical signing fixture
How mTLS + Hydra + DID compose on a single request
The full HTTP surface of a Bindu agent
***
## Appendix: commands you'll reach for
Register a client (DID is the `client_id`, public key goes in `metadata`):
```bash theme={null}
curl -X POST 'https://hydra-admin.getbindu.com/admin/clients' \
-H 'Content-Type: application/json' \
-d '{ ...see step 1... }'
```
Look a client up (does it exist? what metadata does it have?):
```bash theme={null}
# URL-encode the colons in the DID
curl 'https://hydra-admin.getbindu.com/admin/clients/did%3Abindu%3A...'
```
Update a client (rotate secret, add `metadata.public_key`, etc. — full replace, not patch):
```bash theme={null}
curl -X PUT 'https://hydra-admin.getbindu.com/admin/clients/did%3Abindu%3A...' \
-H 'Content-Type: application/json' \
-d '{ ...full client record with changes... }'
```
Delete a client (careful — pre-issued tokens stay valid until they expire):
```bash theme={null}
curl -X DELETE 'https://hydra-admin.getbindu.com/admin/clients/did%3Abindu%3A...'
```
Introspect a token (debug "is this thing valid?"):
```bash theme={null}
curl -X POST 'https://hydra-admin.getbindu.com/admin/oauth2/introspect' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'token='
```
Revoke a token (kills it immediately upstream):
```bash theme={null}
curl -X POST 'https://hydra-admin.getbindu.com/admin/oauth2/revoke' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'token='
```
Generate a strong secret:
```bash theme={null}
openssl rand -base64 32 | tr -d '=' | tr '+/' '-_'
```
Mint a token from Python (no SDK required):
```python theme={null}
import requests
resp = requests.post(
"https://hydra.getbindu.com/oauth2/token",
data={
"grant_type": "client_credentials",
"client_id": "did:bindu:you_at_example_com:my_agent:",
"client_secret": "",
"scope": "openid offline agent:read agent:write",
},
timeout=10,
)
resp.raise_for_status()
token = resp.json()["access_token"] # opaque, e.g. ory_at_...
```
Authenticate -
prove the ticket, then prove the bearer.
# Security Stack: mTLS + Hydra + DID
Source: https://docs.getbindu.com/bindu/learn/authentication/security-stack
Three layers, three different questions, one chain of trust
The [Authentication overview](/bindu/learn/authentication/overview) covered the bearer-token side. The [DID page](/bindu/learn/did/overview) covered the signature side. This page is about **how all three layers compose** on a single request — and why you need all three.
The short version of where each layer fits:
```
Layer 3: DID signature → "is this message tampered with?" (Ed25519, in the body)
Layer 2: OAuth2 token → "are you allowed to make this call?" (Hydra, in the header)
Layer 1: mTLS certificate → "are you on the wire I think I am?" (step-ca, at the socket)
```
You need all three because they answer different questions. OAuth2 alone — an attacker on the wire reads your tokens. mTLS alone — anyone with a valid cert can call anything. DID signatures alone — you know who wrote a message but not whether to accept it. Together they form a chain, and any one can fail safe.
***
## Three questions, one analogy
Imagine you're a courier showing up at a fortified embassy. Before they let you inside, three different officers question you, in order:
1. **The marine at the front gate** checks that you arrived via the embassy's private armored convoy — not a stranger's truck. *If the convoy isn't ours, you don't even get to the gatehouse.*
2. **The receptionist at the desk** asks for your day-pass. It was issued this morning, expires at sundown, and lists which rooms you can enter. *If the pass is expired or for the wrong room, you don't get past the desk.*
3. **The diplomat in the office** opens the envelope you carried, checks the wax seal, and verifies the seal really was made by the foreign minister who claims to have sent it. *If the seal is missing or fake, your message is rejected even though you got this far.*
Three different officers. Three different checks. None of them is redundant — each catches a category of attack the others can't see.
| Embassy | Bindu |
| -------------- | ------------------------------------------------------------------------------------------------- |
| Armored convoy | **mTLS** — both endpoints present X.509 certs from step-ca; nobody else can speak on this socket |
| Day-pass | **OAuth2 bearer token** — Hydra issued it, \~1h TTL, scoped to specific operations |
| Wax seal | **DID signature** — Ed25519 signature over the JSON body, verifiable with the sender's public key |
***
## What each layer actually does
### Layer 1: mTLS (transport)
**What it answers:** *Is the TCP connection itself private and mutually authenticated?*
When agent A calls agent B over HTTPS, both ends present an X.509 certificate during the TLS handshake. Each cert was issued by Bindu's private step-ca, which only signs certs after the requester proves it owns a Hydra OAuth2 identity. The cert's Subject Alternative Name (SAN) embeds the agent's DID.
Practical consequences:
* A man-in-the-middle can't decrypt traffic — the session key was negotiated against B's real cert.
* A man-in-the-middle can't impersonate B — they don't have B's private key.
* A man-in-the-middle can't impersonate A to B either — B verifies A's client cert too.
* Bearer tokens never traverse the wire in cleartext — they're inside the TLS tunnel.
Cert TTL is **24 hours**. The agent silently renews \~8 hours before expiry. There is no CRL or OCSP — short TTL **is** the revocation strategy.
### Layer 2: Hydra OAuth2 (authorization)
**What it answers:** *Should I let this DID perform this operation right now?*
Each agent registers itself in Hydra as an OAuth2 client. The `client_id` **is** the agent's DID — so the DID lives in three places at once: the cert SAN, the OAuth2 client registry, and the message signature. They have to agree, or the request is rejected.
A caller fetches a bearer token from Hydra (`client_credentials` grant), then attaches it as `Authorization: Bearer ...` on every HTTP call. The receiver validates the token by introspecting against Hydra. Tokens last \~1h.
Bindu agents currently use a single scope (`agent:read agent:write`). Fine-grained authorization is on the roadmap once Kratos lands.
### Layer 3: DID signature (integrity & non-repudiation)
**What it answers:** *Was this exact JSON body authored by the DID it claims, and untampered with since?*
The sender signs the canonical JSON body of the request with their Ed25519 private key. Three HTTP headers carry the proof:
```
X-DID: did:bindu:::
X-DID-Timestamp:
X-DID-Signature:
```
The receiver fetches the sender's public key from Hydra client metadata, recomputes the canonical body, and verifies. Even if the bearer token was leaked and the TLS session was somehow compromised, a body that doesn't match the signature gets rejected.
Equally important: **the signature is non-repudiable**. The sender can't later claim "that wasn't me" — no one else has the private key that produced the signature.
See [Making Authenticated Requests](/bindu/learn/authentication/making-requests) for the exact signing payload and a canonical fixture.
***
## A single request, in order
A poet agent sends a one-line A2A message to a math agent. Both have mTLS on. The full timeline:
```
poet (https://127.0.0.1:5776) math (https://127.0.0.1:5775)
│
│ TCP SYN, SYN-ACK, ACK
│ ──────────────────────────────────────────────►│
│ │
│ TLS ClientHello (presents poet's cert) │
│ ──────────────────────────────────────────────►│
│ │
│ TLS ServerHello (presents math's cert) │
│ ◄──────────────────────────────────────────────│
│ │
│ Both ends verify chain → step-ca root │
│ Both ends pin DID in SAN │
│ │
│ [TLS session established — encrypted from here]
│ │
│ POST / │
│ Authorization: Bearer ory_at_... │
│ X-DID: did:bindu:...:poet:... │
│ X-DID-Timestamp: 1715961234 │
│ X-DID-Signature: 3xK9...base58 │
│ Content-Type: application/json │
│ │
│ {"jsonrpc":"2.0", "method":"message/send", │
│ "params":{"message":{"parts":[...]}}} │
│ ──────────────────────────────────────────────►│
│ │
│ │ middleware fires in order:
│ │ 1. mTLS already verified cert → DID = poet
│ │ 2. Auth middleware introspects Bearer
│ │ token at Hydra → token belongs to poet
│ │ 3. DID middleware recomputes signature
│ │ over body → confirms poet authored it
│ │ 4. All three identities must match
│ │
│ │ → hand to the handler
```
Any one of those four checks failing rejects the request. The handler never sees an unauthenticated, unverified, or impersonated call.
***
## Turning mTLS on
mTLS is opt-in. The full env block to turn it on for any agent:
```bash theme={null}
export AUTH__ENABLED=true
export AUTH__PROVIDER=hydra
export HYDRA__ADMIN_URL=https://hydra-admin.getbindu.com
export HYDRA__PUBLIC_URL=https://hydra.getbindu.com
export MTLS__ENABLED=true
export MTLS__MODE=hybrid # hybrid keeps Hydra on inbound too
export MTLS__REQUIRE_CLIENT_CERT=false # set true for full strict-mTLS
export MTLS__CA_URL=https://ca.getbindu.com
export MTLS__CA_ROOT_URL=https://ca.getbindu.com/roots.pem
export BINDU_ALLOW_PRIVATE_WEBHOOK_RANGES=1 # for local 127.0.0.1 webhooks
```
The agent handles the rest itself: registers with Hydra, requests an OIDC token with `aud=step-ca`, exchanges it at step-ca for a 24h X.509 cert, drops the cert files in `/.bindu/`, and serves uvicorn over HTTPS.
### Surface defaults
| Surface | Default | How to flip |
| ----------------------------------------------------- | --------------------------------------------------------------------- | ------------------------------------ |
| **Inbox personal agent** | mTLS **on** when `BINDU_PERSONAL_MTLS=1` is set on the comms server | Set the env var before `npm run dev` |
| **Spawned gateway** | mTLS on iff the personal agent has cert files on disk (inherits them) | Automatic — no action |
| **Fleet agents** (`examples/gateway_test_fleet/*.py`) | Plain HTTP unless the full mTLS env block is exported | Export the env block above |
| **Custom agents** | Plain HTTP unless `MTLS__ENABLED=true` and Hydra config is provided | Export the env block above |
***
## Verifying a running mTLS agent
Inspect the cert your agent is serving:
```bash theme={null}
openssl x509 \
-in ~/.bindu/personal/.bindu/tls_cert.pem \
-noout -subject -issuer -ext subjectAltName
```
You should see something like:
```
subject=CN=did:bindu:you_at_local:leonard-hofstadter:53f9d49f-e15b-...
issuer=CN=Bindu Intermediate CA
X509v3 Subject Alternative Name:
URI:https://hydra.getbindu.com#did:bindu:you_at_local:leonard-hofstadter:53f9d49f-e15b-...
```
The SAN URI is `https://hydra.getbindu.com#did:bindu:...` — the DID lives in the URL fragment. step-ca's Hydra OIDC provisioner emits it that way.
Peek at a fleet agent's cert SAN over the wire:
```bash theme={null}
openssl s_client -connect 127.0.0.1:5775 -servername math_agent \
2>/dev/null
Bindu's `app_settings = Settings()` is constructed at module-import time. If your `agent.py` imports bindu **before** calling `load_dotenv`, your `MTLS__` env vars land in `os.environ` but never reach the singleton — the agent silently serves plain HTTP even with `MTLS__ENABLED=true` in `.env`.
**Fix:** always `load_dotenv` first, before any bindu imports.
Agents register with Hydra and include `audience: ["step-ca"]` in their client config only when `mtls.enabled` is `True` at registration time. Register without mTLS, then enable it later, and the existing-client branch returns early — never patches the audience array. step-ca then rejects token requests with `400: Requested audience 'step-ca' has not been whitelisted`.
**Fix:** the registration flow now reconciles drift on every boot.
Hydra's `PUT /admin/clients/{id}` is a full replace, and `GET` never returns the `client_secret`. Building the PUT body from the GET response caused Hydra to overwrite the password with empty — the next `client_credentials` call then returned `401: passwords do not match`.
**Fix:** the reconciliation now re-sends the secret from local credentials in the PUT body.
`BinduApplication` defaulted its `url` field to `"http://localhost"` and `bindufy` never passed `deployment.url` through. Peers fetching `/.well-known/agent.json` got an unreachable address — no port, wrong scheme.
**Fix:** the resolved URL is now threaded into the constructor.
Node's bundled global `fetch` uses undici 6.x. The inbox and gateway both pin undici 8.x for the dispatcher API. Passing a v8 Agent to the v6 global `fetch` throws an opaque `TypeError: fetch failed`.
**Fix:** both call sites now switch to `undici.fetch` when a dispatcher is in play.
***
## Troubleshooting matrix
| Symptom | Most likely cause | Fix |
| ----------------------------------------------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Spawn hangs in `starting` for >60s | mTLS env didn't reach `app_settings` (load\_dotenv order) OR Hydra audience missing | Check `/health` over both `http://` and `https://`. Whichever responds tells you which scheme the agent picked. Grep boot log for `Bootstrapping mTLS` and `Patched Hydra client` |
| `transport: fetch failed` in gateway plan trace | undici v6/v8 mismatch, OR peer's cert SAN doesn't match expected DID | Upgrade to the current release |
| `400 Requested audience 'step-ca' has not been whitelisted` | Hydra client was created before mTLS was enabled | Restart the agent — registration patches drift automatically. Still failing? Delete `.bindu/oauth_credentials.json` to force a fresh registration |
| `401 passwords do not match` after toggling mTLS | A pre-fix reconciliation rotated the client secret | Delete `.bindu/oauth_credentials.json` and restart; the agent will recreate the Hydra client with matching secret |
| Inspector shows `fetch failed` on a healthy agent | `agents` table row points to a stale port from a prior spawn | Re-spawn. Or `sqlite3 inbox/data/events.db "DELETE FROM agents WHERE id='me'"` and re-add |
| `/.well-known/agent.json` shows `url: "http://localhost"` | Agent built on an older bindu — URL wasn't threaded into BinduApplication | Upgrade to the current release |
***
## Operational quick reference
```bash theme={null}
# What cert is my personal agent serving?
openssl x509 -in ~/.bindu/personal/.bindu/tls_cert.pem \
-noout -subject -dates -ext subjectAltName
# What audience is my Hydra client configured for?
curl -s "https://hydra-admin.getbindu.com/admin/clients/$(echo -n 'did:bindu:...' | jq -sRr @uri)" \
| jq '.audience'
# Is the gateway actually using my cert?
ps eww $(pgrep -f gateway.*src/index) | tr ' ' '\n' | grep BINDU_GATEWAY_TLS
# Verify peer DID from a fleet agent's cert SAN
openssl s_client -connect 127.0.0.1:5775 -servername math_agent \
2>/dev/null
The four headers, four gates, and canonical fixture
Ed25519 keys, canonical JSON, key rotation
Three layers,
three different questions, one chain of trust
.
# Decentralized Identifiers (DIDs)
Source: https://docs.getbindu.com/bindu/learn/did/overview
How agents prove they're really them — without trusting Big Tech
Read the [Authentication page](/bindu/learn/authentication/overview) first if you haven't. This page builds on it. In one line:
* **Authentication** (bearer tokens, Hydra) answers: *are you allowed to make this request?*
* **DIDs** answer the other half: *are you really who you say you are?*
You need both. Lose either and things break — or worse, go through when they shouldn't.
This page is the second half. We'll go slow, no assumed crypto background, lots of stories.
***
## The milk-truck problem
You run a coffee shop. Every morning at 6am, a truck pulls up claiming to be your milk delivery. The driver says, *"I'm from Acme Dairy, same as always."*
How do you know they really are? A few options:
1. **Ask for an ID card.** Anyone can print a card that says "Acme Dairy." You can't tell a real one from a fake one.
2. **Call Acme and ask, "is this driver yours?"** Works — but now you're calling Acme every single morning. And if Acme's phone line is down, no milk for anyone. Your cappuccinos are ruined.
3. **Acme gives the driver a special key.** A cryptographic one. The driver proves they have it, on the spot, without calling anyone. Even if Acme's office burns down overnight, the key still works.
Option 3 is the spirit of a **DID**.
Instead of calling a central authority to vouch for you (option 2), you carry proof you can demonstrate anywhere, to anyone, without a phone call. No gatekeeper. No single point of failure.
For software agents, "calling a central authority" looks like asking Facebook if this user is real, or asking a platform if this agent is legitimate. Which is great — until the platform decides to kick you off, or just disappears. Your identity disappears with it.
DIDs move your identity from a company's database into math. Math doesn't shut down.
***
## The passport and the day-pass
Imagine walking into a secure building. The security desk wants to know three things:
1. Is your **passport** a real passport? (Document authentic?)
2. Does the **face** on it match you? (Really you?)
3. Do you have a **day-pass** for today? (Allowed in *today*?)
Real life uses two documents:
* **The passport** — expensive to forge, issued once, lasts years. Proves *who you are*.
* **The day-pass** — a sticker you get at the front desk. Proves *you have access today*.
You need both. A passport without a day-pass? You're a verified stranger. A day-pass without a passport? Anyone could claim it.
Bindu uses the same pattern:
| Real life | Bindu |
| ---------------------------------- | ------------------------------------------------------- |
| Passport | **DID + signature** — long-lived cryptographic identity |
| Day-pass | **Bearer token** — short-lived (\~1 hour) access grant |
| Photo on passport | **Public key** stored in the DID document |
| Secret signature only you can make | **Private key** only you hold |
| Guard checks passport photo | Server checks DID signature |
| Guard checks day-pass | Server checks bearer token via Hydra |
This page is about the passport side. The day-pass side was the [Authentication page](/bindu/learn/authentication/overview).
***
## Public and private keys, without the math
Before we go further, one concept. You've probably heard **public-key cryptography** before. Here's what it actually means, stripped of math.
A **key pair** is two matched pieces of data — a **private key** and a **public key**. Born together, in one moment, from one random number. They have two almost-magical properties:
1. **You can give the public key to anyone.** Strangers on the internet. Billboards. T-shirts. Doesn't matter. That's why it's *public*.
2. **If you "sign" a message with the private key, anyone with the public key can verify the signature.** They can't *make* signatures — only you can, because only you have the private key. But they can check yours.
Think of it like a medieval scribe's **unique wax stamp**. The scribe keeps the stamp in a locked chest. The king gives an imprint of the stamp (the public key) to every city. Now:
* A letter with the stamp is verifiably from the scribe.
* A letter without it is just paper.
* A forged stamp gets spotted instantly because the stamp has unique geometry nobody else can reproduce.
Cryptographers love to call this stuff "elegant." What they mean is: someone really smart in the 1970s figured out how to build a lock where the key you give out (public) can only *verify* locks, but the key you keep (private) can actually *make* them. We're still collectively shocked this works.
In Bindu we use a specific kind of key pair called **Ed25519**. You don't need to know why. Just three facts:
* Keys are **tiny** — 32 bytes each. Fits in a header.
* **Fast** to sign and verify. Sub-millisecond.
* **Heavily audited.** Signal uses it. SSH uses it. Tor uses it. It's trusted.
Two terms to remember — we'll come back to them:
* **Seed** — a 32-byte random number that *generates* the key pair. If you have the seed, you can always re-derive both keys.
* **Signature** — the 64-byte output of signing a message. Usually encoded as Base58 so it's a readable string. If the signature verifies, you know the message really came from someone with the private key.
**A note on storage.** A Bindu agent doesn't store the seed itself — `DIDAgentExtension` in `bindu/extensions/did/did_agent_extension.py` writes a PKCS8 PEM private key to `private.pem` (mode `0o600`) and a SubjectPublicKeyInfo PEM to `public.pem` (mode `0o644`), under the `pki_dir` (default `.bindu/`). The PEM file can optionally be encrypted at rest with `key_password`. The "seed" pattern you'll see in scripts (Postman, browser POC) is a separate convenience — it derives the same key pair without ever touching PEM.
***
## What a DID actually is
Take a deep breath. A DID is just a **string**. A specific shape of string that says "this identifier belongs to a specific identity system, and here's where to look up more info about it."
Bindu DIDs look like this:
```
did:bindu:dutta_raahul_at_gmail_com:postman:ee67868d-d4b6-6441-93d6-ba4b29dc5e1d
```
Five parts, separated by colons (this is what `DIDAgentExtension.did` builds when `author`, `agent_name`, and `agent_id` are all set):
| Part | In the example | What it means |
| ---- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1 | `did` | The literal prefix. "This is a Decentralized Identifier." Every DID ever, in every system, starts with this. W3C standard. |
| 2 | `bindu` | The **method**. Tells you which DID system to use. Others exist: `did:web`, `did:ethr`, `did:key`. Here we use Bindu's. |
| 3 | `dutta_raahul_at_gmail_com` | The **author segment**. A human-readable identifier of whoever created this DID. Sanitized by `_sanitize_identifier`: lowercased, spaces → `_`, `@` → `_at_`, `.` → `_`. Pure metadata — helps humans know whose agent this is. |
| 4 | `postman` | The **agent name**. A short label, run through the same sanitizer. |
| 5 | `ee67868d-...-ba4b29dc5e1d` | The **agent ID** — a UUID-shaped string. By convention it's derived from the first 16 bytes of `sha256(public_key)` (the Postman generator does exactly that), but `DIDAgentExtension` will accept whatever `agent_id` you pass in. |
When you only supply a key — no author, no agent name — the extension falls back to a W3C `did:key` form: `did:key:z` (the `z` is the multibase prefix for Base58btc). Useful for ad-hoc identities; Bindu native agents always use the five-part `did:bindu:...` form.
### DID string rules
A few constraints — the ones enforced by `DIDValidation` in `bindu/extensions/did/validation.py`:
* Must start with `did:` (settings `did.prefix`)
* Must match the basic pattern `^did:[a-z0-9]+:.+$` (case-insensitive)
* For `did:bindu`: must match `^did:bindu:[^:]+:[^:]+(:[^:]+)?$` — author and agent name are mandatory, agent ID is optional in the regex but mandatory in practice
W3C also says: only ASCII letters, digits, and `._:%-`; case-sensitive; no `?`, `#`, or spaces; under 2048 characters. Bindu doesn't re-enforce all of these on the wire, but cross-protocol parsers will.
`DIDValidation` splits the DID with `split(":", bindu_parts - 1)` where `bindu_parts = 4`. That produces at most 4 chunks, so for a five-segment DID the last chunk is `agent_name:agent_id` glued together. The regex still accepts it, and `parts[3]` is checked for non-empty. Don't read more semantics into the validator than it actually enforces.
***
## The DID document — the thing servers actually trust
The DID string is just a name. To trust you, a server needs your **public key**. That mapping — DID string → public key — lives in a JSON file called the **DID document**.
Here's exactly what `DIDAgentExtension.get_did_document()` returns:
```json theme={null}
{
"@context": [
"https://www.w3.org/ns/did/v1",
"https://getbindu.com/ns/v1"
],
"id": "did:bindu:dutta_raahul_at_gmail_com:postman:ee67868d-d4b6-6441-93d6-ba4b29dc5e1d",
"created": "2026-04-19T17:23:45+00:00",
"authentication": [
{
"id": "did:bindu:...#key-1",
"type": "Ed25519VerificationKey2020",
"controller": "did:bindu:...",
"publicKeyBase58": "BJx2RYuVCGNkgXuxcQEYe8FKTBqypJjz5gvTxXto9kQv"
}
]
}
```
Line by line:
* **`@context`** — `["https://www.w3.org/ns/did/v1", "https://getbindu.com/ns/v1"]`. Parsers care; you don't.
* **`id`** — the DID itself.
* **`created`** — UTC ISO timestamp cached at extension construction time.
* **`authentication`** — a list of **verification methods**. The default one has a fragment `#key-1` (`did.key_fragment`), type `Ed25519VerificationKey2020`, controller equal to the DID itself, and the public key as **raw 32 bytes, Base58btc-encoded**.
**Where does Bindu store this document?** Two places, depending on who's resolving:
* The **agent** advertises its own DID document inline in `/.well-known/agent.json` and exposes `POST /did/resolve` (path from `did.resolver_endpoint`) for direct lookups.
* The **gateway** (when you authenticate against Hydra) stores client public keys in the Hydra OAuth client's `metadata.public_key` field. The middleware in `bindu/server/middleware/auth/hydra.py` pulls that key to verify the `X-DID-Signature` header.
`DIDValidation.validate_did_document` enforces `@context` and `id` are present, that each entry in `authentication` is an object with `type` and `controller`, and — if a `service` array is present — that every `serviceEndpoint` matches the configured `network.default_url`.
***
## Signing a request (what the client does)
You want to send a request to a Hydra-fronted Bindu agent. You want to sign it, so the agent knows the request really came from you — not a replay, not a man-in-the-middle tampering in transit.
The signer and the verifier share one contract: they must agree on the bytes. The reference implementation lives in `bindu/utils/did/signature.py::create_signature_payload`.
```mermaid theme={null}
sequenceDiagram
autonumber
participant App as Your code
participant Sign as Signer
(Python / JS)
participant Net as Network
participant Agent as Bindu agent
App->>App: serialize body to UTF-8 bytes (once!)
App->>Sign: body_bytes, did, timestamp=now
Sign->>Sign: payload = {"body": body_bytes.decode(),
"did": did, "timestamp": ts}
Sign->>Sign: payload_str = json.dumps(payload, sort_keys=True)
Sign->>Sign: sig = base58(Ed25519.sign(payload_str.utf8))
Sign-->>App: X-DID, X-DID-Timestamp, X-DID-Signature
App->>Net: POST /a2a/... with the SAME body_bytes
Net->>Agent: request arrives
Agent->>Agent: verify (4 gates, see below)
```
* **Body** — the exact bytes of the HTTP request body, as they'll go on the wire. Not a parsed object. Not "reformatted." The exact UTF-8 bytes the server will receive. **This is the single thing people get wrong most often.**
* **DID** — your DID string.
* **Timestamp** — current Unix time, in seconds (an integer).
`create_signature_payload` accepts `str` or `bytes` only. It rejects `dict` with `TypeError`. That's deliberate — passing a dict to the signer used to silently `json.dumps` it on the signer side while the verifier got whatever raw bytes the HTTP client decided to send, and the mismatch surfaced as `crypto_mismatch` with no clue why. **Serialize once, sign and send the same bytes.**
Combine the three into a small JSON object:
```python theme={null}
{"body": , "did": , "timestamp": }
```
Then serialize it **using Python's `json.dumps(sort_keys=True)` convention**. Two things matter:
1. **Keys sorted alphabetically** at every level. So `body` → `did` → `timestamp`.
2. **Default Python separators** — `", "` and `": "`. **With a space.** After the comma. After the colon.
That second rule is where every other language trips over its own feet. JavaScript's `JSON.stringify` omits those spaces by default. Python doesn't. If your client skips the spaces, the bytes you signed don't match the bytes the server reconstructs, and the signature fails — even though you "signed the right thing."
A correct payload for a small example:
```
{"body": "{\"test\": \"value\"}", "did": "did:bindu:test", "timestamp": 1000}
```
Notice the spaces after `:` and `,`. Notice `body` comes first. If what you produce matches `json.dumps(payload, sort_keys=True)`, you're good.
For JS/TS, replicate it with the `pythonSortedJson` helper from `docs/postman-did-signing.js` — it walks the value, sorts object keys, and inserts the Python-style separators.
Take the UTF-8 bytes of that payload string. Sign them with your Ed25519 private key. Base58-encode the resulting 64-byte signature.
In Python, against a `DIDAgentExtension`:
```python theme={null}
import json, time
payload = {"body": body_str, "did": did, "timestamp": int(time.time())}
payload_str = json.dumps(payload, sort_keys=True)
signature = did_extension.sign_text(payload_str) # returns base58 string
```
Or use the bundled `sign_request` helper:
```python theme={null}
from bindu.utils.did.signature import sign_request
body_bytes = json.dumps(data).encode("utf-8")
headers = sign_request(body_bytes, did, did_extension)
# headers == {"X-DID": ..., "X-DID-Signature": ..., "X-DID-Timestamp": ...}
httpx.post(url, content=body_bytes, headers=headers)
```
Three for the signature:
```
X-DID:
X-DID-Timestamp:
X-DID-Signature:
```
Plus your bearer token from the [Authentication flow](/bindu/learn/authentication/overview):
```
Authorization: Bearer
```
Send the request. The body on the wire has to be **exactly the same bytes** you used in the signing payload. If any middleware reformats the JSON between your sign-step and the network — the signature breaks.
### curl with signed headers
A complete, working curl once you've computed the signature:
```bash theme={null}
curl -X POST 'https://your-agent.getbindu.com/a2a/jsonrpc' \
-H 'Authorization: Bearer eyJhbGc...' \
-H 'X-DID: did:bindu:user_at_ex_com:my_agent:ee67868d-d4b6-6441-93d6-ba4b29dc5e1d' \
-H 'X-DID-Timestamp: 1747569600' \
-H 'X-DID-Signature: 3SfU4VPTHLbzZzCn17ZqU6y2tnzHQbdo2nnXQr6XZXk34XgyzwSKRrCYEWRmmGXrV39mdkyhTsy5oasfTpNuqyM2' \
-H 'Content-Type: application/json' \
--data-binary @body.json
```
`--data-binary @body.json` matters — `--data` strips newlines and breaks the signature.
***
## Verifying a request (what the server does)
When a Hydra-fronted Bindu agent receives your request, four gates fire in order (see `bindu/server/middleware/auth/hydra.py::_verify_did_signature_asgi` and `bindu/utils/did/signature.py::verify_signature`). Fail any one, and the request is rejected with a `reason` telling you which gate.
```mermaid theme={null}
flowchart TD
A[Incoming request] --> G1{Gate 1
Bearer token valid?
(Hydra introspect)}
G1 -->|no| R1[invalid_token / expired]
G1 -->|yes, client_id is did:*| G2{Gate 2
X-DID-* headers present?
X-DID == client_id?}
G2 -->|missing| R2a[missing_signature_headers]
G2 -->|mismatch| R2b[did_mismatch]
G2 -->|ok| G3{Gate 3
Public key in
Hydra metadata?}
G3 -->|no| R3[public_key_unavailable]
G3 -->|yes| G4a{Gate 4a
timestamp within
±300s?}
G4a -->|no| R4a[timestamp_out_of_window]
G4a -->|yes| G4b{Gate 4b
Ed25519 verify
signature?}
G4b -->|malformed b58| R4b[malformed_input]
G4b -->|bad sig| R4c[crypto_mismatch]
G4b -->|ok| OK[Request proceeds to handler]
```
Each `reason` in a rejection points to exactly one gate:
| Reason | Gate | What's wrong |
| --------------------------- | ---- | ------------------------------------------------------------------- |
| `missing_signature_headers` | 2 | Bearer token present, client is a DID, but no `X-DID-*` headers |
| `did_mismatch` | 2 | `X-DID` header disagrees with the token's `client_id` |
| `public_key_unavailable` | 3 | Hydra has no public key for this DID |
| `payload_too_large` | 3 | Body exceeds `MAX_BODY_SIZE_BYTES` — can't safely buffer for verify |
| `timestamp_out_of_window` | 4a | `\|now - X-DID-Timestamp\| > 300s` (replay guard) |
| `malformed_input` | 4b | `X-DID-Signature` or public key isn't valid Base58 / wrong length |
| `crypto_mismatch` | 4b | Signature doesn't verify — wrong key, wrong bytes, or tampering |
The verifier reconstructs the payload from the **raw ASGI body bytes** plus the `X-DID` and `X-DID-Timestamp` headers, then re-runs `json.dumps(payload, sort_keys=True)` and checks the signature against the result. The body bytes are buffered from the ASGI stream and replayed to downstream handlers via a proxy receiver — your handler still sees the body.
***
## Setting up your own DID from scratch
Two paths, depending on whether you're running an agent or signing as a client.
### Path A: Generate a seed and derive everything (client-side)
This is what the Postman pre-script and the browser POC do. One Python command does it all:
```bash theme={null}
python3 -c "
import os, base64, base58, hashlib
from nacl.signing import SigningKey
AUTHOR = 'your.email@example.com' # replace
NAME = 'my_agent' # replace (short, no colons)
seed = os.urandom(32)
sk = SigningKey(seed)
pk = bytes(sk.verify_key)
h = hashlib.sha256(pk).hexdigest()
agent_id = f'{h[0:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}'
author_safe = AUTHOR.replace('@', '_at_').replace('.', '_')
did = f'did:bindu:{author_safe}:{NAME}:{agent_id}'
print()
print('did =', did)
print('seed (base64) =', base64.b64encode(seed).decode())
print('public key (b58) =', base58.b58encode(pk).decode())
"
```
You get three lines. **Save them somewhere safe.** The seed is your private key.
Lose the seed and the DID is orphaned — there's no reset link, no recovery email, no customer support line. The DID just... becomes a string nobody can sign with anymore. It's the password equivalent of losing the only key to a chest at the bottom of the ocean.
### Path B: Let `DIDAgentExtension` manage the keypair (agent-side)
If you're embedding the DID extension into a Bindu agent, you don't write a script — you instantiate the extension and let it write `private.pem` / `public.pem` under `pki_dir` (default `.bindu/`):
```python theme={null}
from pathlib import Path
from bindu.extensions.did import DIDAgentExtension
ext = DIDAgentExtension(
recreate_keys=False, # True = rotate, with caution
key_dir=Path(".bindu"),
author="your.email@example.com",
agent_name="my_agent",
agent_id="ee67868d-d4b6-6441-93d6-ba4b29dc5e1d", # any UUID-shaped string
key_password=None, # or "env:DID_KEY_PASSWORD"
)
ext.generate_and_save_key_pair()
ext.check_integrity() # validates both keys + DID doc
print(ext.did) # did:bindu:your_email_at_ex_com:my_agent:ee67868d-...
print(ext.public_key_base58)
print(ext.get_did_document())
```
Files written:
* `private.pem` — Ed25519 PKCS8 PEM, mode `0o600` (or encrypted, if `key_password` set)
* `public.pem` — Ed25519 SubjectPublicKeyInfo PEM, mode `0o644`
### Register the client with Hydra
Whichever path you took, the gateway needs to know your public key. Register a Hydra OAuth client and stash the Base58 public key in `metadata.public_key`:
```bash theme={null}
curl -X POST 'https://hydra-admin.getbindu.com/admin/clients' \
-H 'Content-Type: application/json' \
-d '{
"client_id": "",
"client_secret": "",
"grant_types": ["client_credentials"],
"response_types": ["token"],
"scope": "openid offline agent:read agent:write",
"token_endpoint_auth_method": "client_secret_post",
"metadata": {
"agent_id": "",
"did": "",
"public_key": "",
"key_type": "Ed25519",
"verification_method": "Ed25519VerificationKey2020",
"hybrid_auth": true
}
}'
```
`metadata.public_key` is exactly what Gate 3 reads. `hybrid_auth: true` signals to the middleware that this client requires DID signatures on top of a bearer token — once that's set, unsigned requests get `missing_signature_headers`.
### Get a bearer token
Head back to the [Authentication guide](/bindu/learn/authentication/overview) — step 2 of "Getting your first token." Same flow, your shiny new DID is the `client_id`.
### Sign and send a request
Use `bindu/utils/did/signature.py::sign_request` (Python), the Postman pre-script from `docs/postman-did-signing.js` (JS, browser-compat Web Crypto), or roll your own. All three produce identical bytes — they've been cross-tested.
**Canonical fixture for cross-language testing**. Rolling your own signer? Use this:
* seed = 32 zero bytes
* DID = `did:bindu:test`
* body = `{"test": "value"}`
* timestamp = `1000`
Your signature should Base58-encode to:
```
3SfU4VPTHLbzZzCn17ZqU6y2tnzHQbdo2nnXQr6XZXk34XgyzwSKRrCYEWRmmGXrV39mdkyhTsy5oasfTpNuqyM2
```
If it doesn't, your Python-compatible JSON serialization is almost certainly the culprit — either missing spaces, or keys aren't sorted.
***
## What goes wrong in real life
This section is long because this is where people lose hours. Every one of these happened to a real person setting up Bindu. Learn from their pain.
`X-DID` must be **byte-identical** to the `client_id` Hydra returns when introspecting your token. Three things to check, in this order:
1. **Are you talking to the right Hydra?** Your agent's `HYDRA__ADMIN_URL` and the Hydra that issued your token must be the same. Run:
```bash theme={null}
curl -X POST '/admin/oauth2/introspect' -d 'token='
```
The `client_id` field must exactly match `X-DID`.
2. **Did a character get auto-edited?** Some clients (pasting from Slack, from Markdown tables) turn `-` into `–` (en dash). Same-looking, different bytes. Spot it with:
```bash theme={null}
diff <(xxd <<< "$a") <(xxd <<< "$b")
```
3. **Is Postman holding onto a stale token?** Open Postman Console (Option-Cmd-C) and read the actual outgoing headers — not what you think you sent, what actually went out.
Gate 4b tried to verify your signature and it didn't match. Four usual suspects:
* **Body bytes drifted.** Your signing code serialized the JSON object, then some middleware or HTTP client re-serialized the body before sending. Same object, different whitespace or key order. **Fix:** sign the exact string you'll put on the wire, not the parsed object. `create_signature_payload` raises `TypeError` on dicts specifically to make this hard to do by accident.
* **Wrong public key in Hydra.** You rotated the key locally but forgot to update `metadata.public_key`. Server verifies against the old key. **Fix:** re-register with the new key.
* **Python-compat JSON mismatch.** You're probably in JavaScript, and `JSON.stringify` omits the spaces. **Fix:** use `pythonSortedJson` from `docs/postman-did-signing.js`, or replicate it.
* **Actually forged / wrong seed.** The key you're signing with doesn't match the public key in Hydra. Walk the chain: `private key → public key → metadata.public_key`. One of the links is broken.
Verifier got either `X-DID-Signature` or the registered public key, and one of them didn't decode as valid Base58, or decoded to the wrong length. Common causes:
* You URL-encoded the signature. Don't — Base58 has no reserved characters.
* You sent the public key as hex instead of Base58.
* You concatenated/truncated bytes somewhere.
Confirm: `len(base58.b58decode(sig)) == 64` and `len(base58.b58decode(pubkey)) == 32`.
Two causes:
* **Your clock is wrong.** Check `date -u` against a known-good time server. Container clocks drift all the time.
* **Someone's replaying a captured request.** Or you're trying to resend a request your logs captured 10 minutes ago. Sign fresh every time.
The window is `±300s` by default (`max_age_seconds` in `verify_signature`).
The DID in `X-DID` doesn't have a public key registered with Hydra. Two paths:
* You haven't registered yet → see "Register the client with Hydra" above.
* You registered, but put the public key somewhere other than `metadata.public_key`. Look at `GET /admin/clients/` and confirm `metadata.public_key` is a non-empty Base58 string.
You sent `Authorization: Bearer ` where the token's `client_id` is a DID, but didn't send the three `X-DID-*` headers. Once `client_id` starts with `did:`, signing is mandatory — there's no "unsigned is fine" fallback (this used to fail-open and was closed; see `bugs/2026-04-18-did-signature-fail-open.md` in the repo).
Body exceeds the configured `MAX_BODY_SIZE_BYTES`. The middleware refuses to buffer arbitrarily large bodies for signature verification. Split the payload, or talk to whoever runs the gateway about raising the limit.
***
## Keeping your key safe
The private key — whether held as a 32-byte seed or as `private.pem` — is the single thing that gives you authority over your DID. Treat it like a password — but worse, because there's no "forgot password" flow. Lose it and the DID is gone forever.
Secret manager (1Password, AWS Secrets Manager, Vault) for prod. Gitignored `.env` for local. **Never** in source. Never logged in plaintext.
`DIDAgentExtension` writes `private.pem` mode `0o600` on POSIX. Verify with `ls -l ~/.bindu/private.pem` — should be `-rw-------`.
Pass `key_password` (or `env:DID_KEY_PASSWORD`) to `DIDAgentExtension` and the PEM is wrapped with `BestAvailableEncryption`. Loading the key without the password raises `ValueError`.
Generate new key, `PUT` to `/admin/clients/` with updated `metadata.public_key`, restart agent with `recreate_keys=True`, discard old key. Old signatures stop verifying immediately — do it in a maintenance window.
### If you think the key is compromised
Assume the attacker has full signing authority until you've:
* Rotated the key.
* Revoked all outstanding bearer tokens (Hydra's admin API can do this).
* Audited recent requests signed by this DID — what did the attacker do?
* Read your logs for unfamiliar `X-DID-Timestamp` values or weird request patterns.
Don't just rotate — **investigate**. The key didn't leak on its own.
***
## Bonus: agents sign their responses too
So far we've talked about you signing requests. Agents sign their responses right back. Every artifact a Bindu agent produces is run through `did_extension.sign_text(text_value)` in `bindu/utils/worker/artifacts.py`, and the Base58 signature is stuffed into the artifact metadata under the key `did.message.signature` (from `app_settings.did.agent_extension_metadata`).
Look for this inside a task response:
```json theme={null}
"metadata": {
"did.message.signature": ""
}
```
To verify, resolve the agent's DID document, grab `publicKeyBase58`, and check the signature against the message bytes using the same `verify_text` logic the extension uses internally:
```python theme={null}
from nacl.signing import VerifyKey
import base58
pk = VerifyKey(base58.b58decode(pub_key_b58))
pk.verify(text.encode("utf-8"), base58.b58decode(signature)) # raises if bad
```
The agent's DID lives in its agent card at `/.well-known/agent.json`, and the full DID document is at `POST /did/resolve`.
You don't *have* to verify. The server does the heavy lifting on the way in. But if you're building something compliance-heavy (legal, medical, financial), client-side verification gives you a proof you can put in an audit log.
***
## Signing is not encryption
One clarification that comes up constantly:
* **Signing** gives you **authenticity** ("really from this DID") and **integrity** ("not modified in transit"). It does **not** hide the contents. Anyone who sees the traffic can read the body as plain JSON.
* **Encryption** hides the contents. For network transport, use HTTPS (TLS). Bindu's public endpoints are HTTPS in production.
If you need messages to be unreadable even by the middle — that's **end-to-end encryption**, and it's a separate feature Bindu doesn't currently ship. TLS + DID signing is the production model.
***
## Why Ed25519 (optional reading)
The short version: Ed25519 is a modern elliptic-curve signature scheme that is:
* **Small.** Keys are 32 bytes, signatures 64 bytes. Fits in headers.
* **Fast.** Sub-millisecond sign/verify on modern CPUs.
* **Deterministic.** Same input → same signature. Makes cross-language testing painless.
* **Well-vetted.** Signal, Tor, SSH, RFC 8032. No known practical attacks.
The alternative was RSA. RSA keys are ten times larger, signatures are bigger, signing is slower, and RSA has a long and colourful history of subtly broken implementations. For a protocol that signs on every single request, Ed25519 is the right default.
If you ever see a DID from outside Bindu with a different key type, the `authentication[].type` in its DID document tells you which algorithm to use. Bindu-native DIDs always use `Ed25519VerificationKey2020`.
***
## Related
The bearer-token half. Read this first if you haven't.
Payment receipts are signed with the same DID keypair.
The governing standard for all DID methods.
The signature scheme itself.
***
## The whole thing in one paragraph
A DID is a long identifier string that maps, through a public document, to an Ed25519 public key. When you make a request, you sign specific bytes — `json.dumps({"body", "did", "timestamp"}, sort_keys=True)` — with your private key and attach the signature as `X-DID-Signature`. The middleware introspects your bearer token, checks that `X-DID` matches the token's `client_id`, looks up your public key in Hydra's `metadata.public_key`, reconstructs the same bytes from the raw ASGI body, and verifies. If everything lines up, the request reaches your handler; otherwise it's rejected with a one-word `reason` pointing at the exact gate that failed. Combined with the bearer token from the [Authentication page](/bindu/learn/authentication/overview), Bindu gets two independent guarantees: *this request is permitted* (token) and *this request is authentic* (signature). Lose either and the request is rejected. Get both right and you have a system where identity and access are verifiable end-to-end — without trusting any single central authority.
DID lets you -
prove yourself to agents.
# Health & metrics
Source: https://docs.getbindu.com/bindu/learn/health-metrics/overview
/health says yes — and if it can't, returns 503. /metrics says how, in Prometheus text. Both are wired up the moment bindufy() starts the server.
A process can be "running" and still broken. Postgres is down, Redis dropped the connection, the worker pool deadlocked — the agent is still binding port `:3773` and answering TCP, but the next real request fails.
So `/health` in Bindu does more than return `200 OK`. It walks the runtime — storage, scheduler, task manager — and returns `503 Service Unavailable` when any of them is missing or not running. `/metrics` exposes Prometheus text-format counters, gauges, histograms, and summaries for request traffic, latency, task state, errors, and per-agent task completion.
You do not configure either. Both endpoints are registered on `BinduApplication` startup, both are on the auth allowlist, and both are exempt from the startup gate so Kubernetes can probe the pod while storage and the scheduler are still coming up. Point your load balancer at `/health` and your scrapers at `/metrics` — you have visibility from request one.
## Liveness, readiness, metrics
Bindu does not split liveness and readiness across multiple paths. There is one health endpoint and it makes the strict choice for you: 200 means every dependency is ready, 503 means at least one is not.
| Question | Endpoint | Status code | Use for |
| ----------------------------------- | --------------------- | ----------- | -------------------------------------------- |
| Is the process alive at all? | `/health` reachable | TCP-level | Liveness probe |
| Is the agent ready to take work? | `/health` returns 200 | 200 vs 503 | Readiness probe, load balancer health checks |
| How has it been behaving over time? | `/metrics` | 200 | Prometheus scrape, Grafana dashboards |
Strict readiness means **storage + scheduler + task manager** are all initialized and the
task manager's run loop is active. Anything less and `/health` returns HTTP 503 with
`"status": "degraded"`, `"ready": false`, `"health": "degraded"`.
`/health` returns a single JSON document with runtime, application, and system blocks.
`/metrics` is Prometheus text format `version=0.0.4` — scrape it with anything OpenMetrics-compatible.
Both paths are exempt from the startup gate and the auth middleware allowlist, so probes never get a 500 or 401.
***
## Request flow
```mermaid theme={null}
sequenceDiagram
autonumber
participant Probe as Load balancer / kubelet
participant App as BinduApplication
participant MW as MetricsMiddleware
participant H as health_endpoint
participant Util as get_runtime_status
Probe->>App: GET /health
App->>MW: dispatch
MW->>H: call_next
H->>Util: inspect app._storage, app._scheduler, app.task_manager
Util-->>H: {storage_type, scheduler_type, task_manager_running, strict_ready}
H-->>MW: JSONResponse (200 or 503)
MW->>MW: record_http_request(method, endpoint, status, duration, sizes)
MW-->>App: response
App-->>Probe: 200 OK / 503 Service Unavailable
```
The metrics middleware runs on every request *except* `/metrics` itself (skipped to avoid feedback loops), sanitizes path parameters (UUIDs and numeric IDs are rewritten to `:id` to keep cardinality bounded), and feeds the global `PrometheusMetrics` singleton.
***
## /health
```bash Request theme={null}
curl -i http://localhost:3773/health
```
```json Response (200 — strict_ready) theme={null}
{
"version": "2026.6.7.dev65+g6742cd6eb.d20260210",
"health": "healthy",
"runtime": {
"storage_backend": "PostgresStorage",
"scheduler_backend": "RedisScheduler",
"task_manager_running": true,
"strict_ready": true
},
"application": {
"penguin_id": "8f5c…",
"agent_did": "did:bindu:…"
},
"system": {
"python_version": "3.12.4",
"platform": "Linux",
"environment": "production"
},
"status": "ok",
"ready": true,
"uptime_seconds": 37.56
}
```
```json Response (503 — degraded) theme={null}
{
"version": "2026.6.7.dev65+g6742cd6eb.d20260210",
"health": "degraded",
"runtime": {
"storage_backend": "PostgresStorage",
"scheduler_backend": null,
"task_manager_running": false,
"strict_ready": false
},
"application": {
"penguin_id": "8f5c…",
"agent_did": "did:bindu:…"
},
"system": {
"python_version": "3.12.4",
"platform": "Linux",
"environment": "production"
},
"status": "degraded",
"ready": false,
"uptime_seconds": 4.12
}
```
| Field | Type | Meaning |
| ------------------------------ | -------------- | ----------------------------------------------------------------------------- |
| `status` | string | `"ok"` when `strict_ready=true`, else `"degraded"` |
| `ready` | bool | Mirrors `runtime.strict_ready` — use this for readiness probes |
| `health` | string | `"healthy"` or `"degraded"` — same trigger as `status` |
| `uptime_seconds` | float | Seconds since the process imported `health.py` (monotonic clock) |
| `version` | string | Value of `bindu.__version__` |
| `runtime.storage_backend` | string \| null | Class name of `app._storage` (e.g. `PostgresStorage`, `InMemoryStorage`) |
| `runtime.scheduler_backend` | string \| null | Class name of `app._scheduler` (e.g. `RedisScheduler`, `MemoryScheduler`) |
| `runtime.task_manager_running` | bool | True only if `app.task_manager.is_running` |
| `runtime.strict_ready` | bool | True when **all** of storage, scheduler, task manager are present and running |
| `application.penguin_id` | string | UUID identifying this server process |
| `application.agent_did` | string \| null | Agent DID from the manifest, if present |
| `system.python_version` | string | `sys.version.split()[0]` |
| `system.platform` | string | `platform.system()` — e.g. `Linux`, `Darwin` |
| `system.environment` | string | Value of `$ENV` env var, defaults to `"development"` |
Kubernetes treats any 2xx as healthy; 503 fails the probe. That maps directly to
`strict_ready`, so a single config covers both liveness and readiness:
```yaml theme={null}
livenessProbe:
httpGet:
path: /health
port: 3773
initialDelaySeconds: 5
periodSeconds: 10
readinessProbe:
httpGet:
path: /health
port: 3773
initialDelaySeconds: 2
periodSeconds: 5
```
During boot — before storage and scheduler initialize inside the ASGI lifespan —
`/health` returns 503 without raising. The startup gate in
`BinduApplication.__call__` whitelists `/health`, `/healthz`, and `/metrics`, so probes
get a proper response code instead of a 500.
Only `/health` is registered as a route. The `/healthz` path is **whitelisted** in the
startup gate (so it cannot 500 mid-boot) but no handler exists for it — a request to
`/healthz` returns 404 once the app is running. Use `/health` everywhere.
***
## /metrics
```bash theme={null}
curl http://localhost:3773/metrics
```
Returns `text/plain; version=0.0.4; charset=utf-8` with `Cache-Control: no-cache`. Before generating output, the endpoint refreshes the per-agent active-task gauge by counting tasks in `submitted`, `working`, and `input-required` states from storage.
```prometheus theme={null}
# HELP http_requests_total Total number of HTTP requests
# TYPE http_requests_total counter
http_requests_total{method="GET",endpoint="/health",status="200"} 42
http_requests_total{method="POST",endpoint="/",status="200"} 17
# HELP http_request_duration_seconds HTTP request latency
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.1"} 55
http_request_duration_seconds_bucket{le="0.5"} 58
http_request_duration_seconds_bucket{le="1.0"} 59
http_request_duration_seconds_bucket{le="+Inf"} 59
http_request_duration_seconds_sum 4.2
http_request_duration_seconds_count 59
# HELP agent_tasks_active Currently active tasks
# TYPE agent_tasks_active gauge
agent_tasks_active{agent_id="did:bindu:abc123"} 3
# HELP agent_tasks_completed_total Total completed tasks
# TYPE agent_tasks_completed_total counter
agent_tasks_completed_total{agent_id="did:bindu:abc123",status="success"} 128
# HELP http_requests_in_flight Current number of HTTP requests being processed
# TYPE http_requests_in_flight gauge
http_requests_in_flight 1
```
### Metric reference
Total HTTP requests handled by `MetricsMiddleware`, labelled by method, sanitized endpoint, and status code.
Path parameters are normalized: UUIDs match `[0-9a-f]{8}-…` and runs of digits both collapse to `/:id`. That keeps cardinality bounded even with high-traffic task endpoints like `/tasks/`.
```promql theme={null}
rate(http_requests_total[5m])
sum by (status) (rate(http_requests_total[1m]))
```
Request latency in seconds. Buckets: `0.1`, `0.5`, `1.0`, `+Inf`. Exposes `_bucket`, `_sum`, `_count`.
The histogram is **global**, not per-endpoint — there are no method or path labels on the buckets. If you need per-route p95, build it from request count buckets in your aggregator, or alert on the global p95.
```promql theme={null}
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
```
Tasks currently in `submitted`, `working`, or `input-required` state for the agent. Updated lazily — only when `/metrics` is scraped, by querying `storage.count_tasks(status=…)` for each active state. Only emitted when at least one agent has reported.
Cumulative finished tasks per `(agent_id, status)`. Status values come from the task manager and are typically `success`, `failed`, or `canceled`. Only emitted when at least one task has completed.
```promql theme={null}
sum by (status) (rate(agent_tasks_completed_total[5m]))
```
End-to-end task execution time, labelled by `agent_id` and `status`. Buckets: `1`, `5`, `10`, `30`, `60`, `+Inf` seconds. Exposes `_bucket`, `_sum`, `_count`. Only emitted when at least one task has finished.
```promql theme={null}
histogram_quantile(0.95,
sum by (le, agent_id) (rate(task_duration_seconds_bucket[5m]))
)
```
Errors raised during task execution, labelled by `agent_id` and `error_type` (e.g. `timeout`, `validation`, `execution`). Only emitted when at least one error has been recorded.
Aggregate byte totals and counts for request and response bodies. Exposed as Prometheus
summaries with `_sum` and `_count` only (no quantiles). Sizes are read from the
`Content-Length` header — chunked responses without a length register as zero.
Number of concurrent in-flight HTTP requests. Incremented in the middleware before
`call_next`, decremented in the `finally` block, so it always reflects current
concurrency even on exceptions.
Always emitted, even at zero — useful for "agent is alive but idle" dashboards.
### Prometheus scrape config
```yaml theme={null}
scrape_configs:
- job_name: bindu-agents
metrics_path: /metrics
scrape_interval: 15s
static_configs:
- targets:
- localhost:3773
labels:
service: bindu
env: production
```
The metrics middleware **skips collection for `/metrics` itself**, so scrape calls do not
inflate `http_requests_total`. Your dashboards measure user traffic, not Prometheus
polling.
***
## Use cases
Use `/health` for both probes. The endpoint returns 503 while storage or scheduler is
initializing, so kubelet does not route traffic to a half-booted pod, and it returns 200
only once `task_manager.is_running` is true.
Point your LB at `GET /health`. Anything other than `200` should drain the instance.
`status: "degraded"` is your signal that the process is up but should not receive
traffic.
Scrape `/metrics` every 15s. Build dashboards on
`rate(http_requests_total)`, `histogram_quantile(0.95, …)` for p95 latency,
`agent_tasks_active` for concurrency, and `agent_errors_total` for fault rates.
If an agent appears live but rejects work, hit `/health` and inspect the `runtime`
block. A `null` `storage_backend` or `scheduler_backend` means initialization never
completed; `task_manager_running: false` means the loop exited or never started.
```bash theme={null}
curl -s http://localhost:3773/health | jq .runtime
```
Bindu's Sentry integration filters `/health`, `/healthz`, and `/metrics` out of
transaction traces by default (`SentrySettings.filter_transactions`), so probe and
scrape traffic does not eat your Sentry quota or pollute performance dashboards.
***
## Best practices
A TCP check on `:3773` will pass while storage is still connecting. Use HTTP `/health`
and treat any non-200 as not-ready.
The default Prometheus interval is enough for `agent_tasks_active` to track real
concurrency. Below 10s mostly buys noise.
By the time `/health` is unreachable you are already on fire. Alert on `status="degraded"`
or `health="degraded"` returns for an early warning.
Both `/health` and `/metrics` are in the auth allowlist by default. Do not put them
behind your OAuth gateway — probes and scrapers do not carry tokens.
***
## Related
* [Observability](/bindu/learn/observability/overview)
* [Storage](/bindu/learn/storage/overview)
* [Scheduler](/bindu/learn/scheduler/overview)
* [Prometheus](https://prometheus.io/)
* [OpenMetrics text format 0.0.4](https://prometheus.io/docs/instrumenting/exposition_formats/)
With Bindu, agent health is like a field of sunflowers —
each one standing on its own,
yet easy to observe and trust.
# Agent negotiation
Source: https://docs.getbindu.com/bindu/learn/negotiation/overview
Three agents can do this job. Which one should the orchestrator pick? Ask them — they know.
You have three research agents on the network. Two are good, one is overloaded, one charges 5x more than the others. Static routing — "always send research tasks to Agent A" — works until Agent A goes down or starts dropping quality on a topic outside its training.
Negotiation flips the question. Instead of the orchestrator guessing who's best, it asks each candidate to score itself against the task. The agent looks at its own skills, queue depth, latency profile, and (if x402 is enabled) price, and replies with an `accepted` flag, a numeric `score`, and a per-skill reasoning trail. The orchestrator ranks the replies and picks one.
The endpoint is `POST /agent/negotiation`. It's public — no auth, no DID handshake — so any orchestrator on the network can probe an agent before sending a real task.
Bindu ships the **client side** only: each agent self-assesses against an incoming
negotiation request. The broadcast-and-rank logic lives in the orchestrator, which is
out of scope for the runtime. See [Custom orchestrator](#custom-orchestrator) below for
a minimal implementation.
## How Bindu Negotiation Works
The agent owns the scoring. It knows its skills, its queue, its latency history, its prices. The orchestrator just asks the question and ranks the answers.
### The Negotiation Model
```text theme={null}
broadcast request -> per-agent self-assessment -> ranking -> selection
```
| Static routing | Negotiation |
| ------------------------------------------ | ---------------------------------------------- |
| Orchestrator hardcodes "send X to agent A" | Orchestrator asks "who can do X?" |
| Breaks when A is overloaded or down | Live load and latency feed the score |
| New agents need router config changes | New agents advertise skills and join the pool |
| Single point of failure | Per-request fan-out across candidates |
| No visibility into why A was chosen | Response includes subscores and matched skills |
Selection can change per request instead of being fixed in advance.
Responses include per-component subscores and per-skill match reasoning, not a
black-box yes or no.
Hard constraints reject early. Only candidates that survive the gate compute a full
score.
### The Lifecycle: Broadcast, Assess, Select
```mermaid theme={null}
sequenceDiagram
participant Orchestrator
participant Agent1
participant Agent2
participant Agent3
Note over Orchestrator: 1. Broadcast Request
Orchestrator->>Agent1: POST /agent/negotiation
Orchestrator->>Agent2: POST /agent/negotiation
Orchestrator->>Agent3: POST /agent/negotiation
Note over Agent1,Agent3: 2. Self-Assessment
Agent1->>Agent1: Hard constraints (IO, tools, cost, latency)
Agent1->>Agent1: Skill match (embeddings + keywords)
Agent1->>Agent1: Subscores: skill, IO, performance, load, cost
Agent1->>Agent1: Weighted final score
Agent2->>Agent2: Same assessment process
Agent3->>Agent3: Same assessment process
Note over Agent1,Agent3: 3. Return Scores
Agent1-->>Orchestrator: {accepted: true, score: 0.89, subscores...}
Agent2-->>Orchestrator: {accepted: true, score: 0.72}
Agent3-->>Orchestrator: {accepted: false, rejection_reason}
Note over Orchestrator: 4. Select Best Agent
Orchestrator->>Orchestrator: Rank by score
Orchestrator->>Agent1: Send task (highest score)
```
The orchestrator POSTs the same assessment request to every candidate URL. Only
`task_summary` is required — everything else (IO types, tools, latency budget, cost
cap, weights) is optional and turns into either a hard gate or a soft score.
```bash Request theme={null}
POST /agent/negotiation
Content-Type: application/json
{
"task_summary": "Extract tables from PDF invoices",
"task_details": "Process invoice PDFs and extract structured data",
"input_mime_types": ["application/pdf"],
"output_mime_types": ["application/json"],
"required_tools": ["pdf_parser"],
"forbidden_tools": ["web_search"],
"max_latency_ms": 5000,
"max_cost_amount": "0.001",
"min_score": 0.7,
"weights": {
"skill_match": 0.55,
"io_compatibility": 0.20,
"performance": 0.15,
"load": 0.05,
"cost": 0.05
}
}
```
```text Fields theme={null}
task_summary - Required. Brief description of the task (max 10000 chars).
task_details - Optional longer description; folded into keyword + embedding match.
input_mime_types - Hard gate. Reject if no skill declares any of these in input_modes.
output_mime_types - Hard gate. Reject if no skill declares any of these in output_modes.
required_tools - Hard gate. Reject if union of skills.allowed_tools misses any.
forbidden_tools - Hard gate. Reject if any skill.allowed_tools contains a forbidden tool.
max_latency_ms - Soft: shapes performance subscore. Hard reject only if estimate > 2x.
max_cost_amount - Soft if x402 enabled. Hard reject if agent price > cap.
min_score - Acceptance threshold. Default 0.0 — must also have skill match > 0.
weights - Optional override; auto-normalized to sum to 1.0.
```
The agent runs `CapabilityCalculator.calculate()`. The pipeline is fixed:
1. **Empty skill list** -> reject with `no_skills_advertised`.
2. **Hard constraints** -> check IO modes, required tools, forbidden tools. First failure exits with the matching `rejection_reason`.
3. **Skill match** -> hybrid score per skill (see [Capability matching](#capability-matching)).
4. **Cost** -> if x402 says the agent's price exceeds `max_cost_amount`, exit with `cost_exceeds_budget`.
5. **Latency** -> estimate from the skills' `performance.avg_processing_time_ms`. If the estimate exceeds `max_latency_ms * 2`, exit with `latency_exceeds_constraint`.
6. **Combine** -> weighted average of five subscores.
7. **Accept** if `final_score >= min_score` **and** at least one skill matched.
Default weights (from `app_settings.negotiation`):
```python theme={null}
score = (
skill_match * 0.55 + # capability fit (embeddings + keywords)
io_compatibility * 0.20 + # input/output mime support
performance * 0.15 + # estimated latency vs constraint
load * 0.05 + # 1 / (1 + queue_depth)
cost * 0.05 # linear discount under cap (if x402)
)
```
Any caller-supplied `weights` block is normalized to sum to 1.0 — you don't have to
pre-balance them.
The agent returns `accepted`, `score`, `confidence`, per-skill `skill_matches`, and a
`subscores` breakdown. The orchestrator filters by `accepted`, applies its own policy
(highest score, cheapest above threshold, lowest queue, etc.), and sends the actual
task to the winner.
```json Response (accepted) theme={null}
{
"accepted": true,
"score": 0.89,
"confidence": 0.95,
"skill_matches": [
{
"skill_id": "pdf-processing-v1",
"skill_name": "PDF Processing",
"score": 0.92,
"reasons": [
"semantic similarity: 0.95",
"tags: pdf, tables, extraction",
"capabilities: text_extraction, table_extraction"
]
}
],
"matched_tags": ["pdf", "tables", "extraction"],
"matched_capabilities": ["text_extraction", "table_extraction"],
"latency_estimate_ms": 2000,
"queue_depth": 2,
"subscores": {
"skill_match": 0.92,
"io_compatibility": 1.0,
"performance": 0.85,
"load": 0.3333,
"cost": 1.0
}
}
```
```json Response (rejected) theme={null}
{
"accepted": false,
"score": 0.0,
"confidence": 1.0,
"rejection_reason": "required_tool_missing"
}
```
```text Fields theme={null}
accepted - Final accept/reject decision.
score - Weighted final score in [0, 1].
confidence - Agent's self-assessed data-quality confidence (base 0.5 + boosts).
rejection_reason - One of: no_skills_advertised, input_mime_unsupported,
output_mime_unsupported, required_tool_missing,
forbidden_tool_present, cost_exceeds_budget,
latency_exceeds_constraint, score_below_threshold.
skill_matches - Ranked per-skill matches with reasoning strings.
matched_tags - Tags that intersected the task's keyword set.
matched_capabilities - capabilities_detail keys that intersected.
latency_estimate_ms - max(skill.performance.avg_processing_time_ms) or 5000 default.
queue_depth - Count of tasks currently in non-terminal states.
subscores - Per-component breakdown that produced score.
```
***
## Capability matching
Skill match is the largest weight (55%) and the most interesting part of the pipeline. It runs as a hybrid:
```python theme={null}
# Per skill, when an OpenRouter key is configured:
base = 0.7 * cosine(task_embedding, skill_embedding) # semantic
+ 0.3 * jaccard(task_keywords, skill_keywords) # exact tokens
# Then per-skill assessment block can boost:
if specialization.domain in task_summary.lower():
base = min(1.0, base + specialization.confidence_boost)
# Anti-patterns short-circuit the skill out of the pool:
if any(pattern in task_text for pattern in skill.assessment.anti_patterns):
skip this skill entirely
```
Without an OpenRouter key, the embedding term is dropped and the score is pure Jaccard over keywords. The pipeline still works — it just gets less forgiving on paraphrased tasks.
Embeddings come from OpenRouter (`text-embedding-3-small` by default). Skill embeddings
are computed once on first request and cached on the agent. Task embeddings are cached
in a per-instance LRU (max 1000 entries) so identical follow-ups don't re-hit the API.
### What the agent embeds per skill
The `SkillEmbedder` builds a single string from each skill's `name`, `description`, `tags`, `assessment.keywords`, and the keys of `capabilities_detail`. That string is what gets compared against the embedded `task_summary + task_details`.
### Keyword extraction
Both the task and each skill are tokenized with `re.split(r"[^a-z0-9]+", ...)`, lowercased, and filtered to tokens of length 2-100. Jaccard similarity (`|A ∩ B| / |A ∪ B|`) gives a deterministic, no-network fallback.
### Confidence
A separate signal from `score`. Confidence starts at 0.5 and gains:
* +0.2 if best skill match > 0.3, else +0.1 if any match exists
* +0.1 each for IO constraints, latency constraint, and queue depth being present in the request
It tells the orchestrator how much data the agent had to work with — not how good the fit is.
***
## Hard constraints and rejection
Hard constraints reject before any scoring happens. The full list:
```mermaid theme={null}
flowchart TD
A[Request arrives] --> B{Has skills?}
B -- no --> R1[no_skills_advertised]
B -- yes --> C{input_mime in any skill.input_modes?}
C -- no --> R2[input_mime_unsupported]
C -- yes --> D{output_mime in any skill.output_modes?}
D -- no --> R3[output_mime_unsupported]
D -- yes --> E{required_tools subset of union skill.allowed_tools?}
E -- no --> R4[required_tool_missing]
E -- yes --> F{forbidden_tools in any skill.allowed_tools?}
F -- yes --> R5[forbidden_tool_present]
F -- no --> G[Compute skill_match, io, load, cost]
G --> H{agent_cost > max_cost_amount?}
H -- yes --> R6[cost_exceeds_budget]
H -- no --> I{latency_estimate > 2x max_latency_ms?}
I -- yes --> R7[latency_exceeds_constraint]
I -- no --> J[Compute final_score]
J --> K{final_score >= min_score AND skill_match > 0?}
K -- no --> R8[score_below_threshold]
K -- yes --> ACCEPT[accepted: true]
```
The latency gate uses a 2x multiplier. Saying `max_latency_ms: 5000` rejects only when
the agent's estimated latency exceeds 10000 ms. Everything between 5000 and 10000 ms
passes the gate but contributes a lower `performance` subscore.
***
## Configuration
### Enable negotiation on an agent
```python theme={null}
config = {
"name": "my_agent",
"skills": ["skills/pdf-processing"],
"capabilities": {
"negotiation": True, # turns on /agent/negotiation auto-enrichment
"push_notifications": True, # required by the enricher branch for negotiation
},
"negotiation": {
"embedding_api_key": os.getenv("OPENROUTER_API_KEY"),
},
}
```
When `capabilities.negotiation` is `True`, Bindu reads `OPENROUTER_API_KEY` from the environment and injects it into `negotiation.embedding_api_key` if you haven't set it explicitly. With no key configured, the calculator silently falls back to keyword-only matching.
The `/agent/negotiation` route is always mounted — it doesn't require the capability
flag to respond. The flag controls config enrichment (auto-loading the OpenRouter key).
An agent that omits the flag but sets the key directly still gets full embedding-backed
matching.
### Authoring skills for good matches
Skill metadata is what the agent has to score against. Two fields move the needle most:
```yaml theme={null}
# skill.yaml
id: pdf-processing-v1
name: PDF Processing
description: Extracts tables and text from invoice and report PDFs
tags: [pdf, tables, extraction, invoice, ocr]
input_modes: [application/pdf]
output_modes: [application/json]
capabilities_detail:
text_extraction:
supported: true
types: [standard, ocr]
table_extraction:
supported: true
allowed_tools: [pdf_parser, ocr]
performance:
avg_processing_time_ms: 2000 # feeds latency_estimate_ms
assessment:
keywords: [pdf, extract, invoice, table, document]
specializations:
- domain: invoice_processing
confidence_boost: 0.3 # added to base when 'invoice_processing' appears in task
anti_patterns:
- pdf editing # task mentioning these makes the skill bow out
- create pdf
```
The `assessment` block is the lever. Keywords beef up the keyword side of the hybrid score, `specializations` give you targeted boosts when a domain phrase shows up in the task, and `anti_patterns` are how you opt out of tasks you'd technically match on tags but actually can't do well.
### Environment variables
```bash theme={null}
# Auto-injected when capabilities.negotiation is enabled
OPENROUTER_API_KEY=sk-or-v1-your-key-here
# Or set directly via NEGOTIATION__ prefix
NEGOTIATION__EMBEDDING_API_KEY=sk-or-v1-your-key-here
NEGOTIATION__EMBEDDING_MODEL=text-embedding-3-small
NEGOTIATION__USE_EMBEDDINGS=true
# Weight overrides (all are normalized at runtime)
NEGOTIATION__SKILL_MATCH_WEIGHT=0.55
NEGOTIATION__IO_COMPATIBILITY_WEIGHT=0.20
NEGOTIATION__PERFORMANCE_WEIGHT=0.15
NEGOTIATION__LOAD_WEIGHT=0.05
NEGOTIATION__COST_WEIGHT=0.05
# Hybrid match tuning
NEGOTIATION__EMBEDDING_WEIGHT=0.7
NEGOTIATION__KEYWORD_WEIGHT=0.3
```
***
## Asking "who can do X?"
### curl
```bash theme={null}
curl -sS -X POST http://localhost:3773/agent/negotiation \
-H 'Content-Type: application/json' \
-d '{
"task_summary": "Translate technical manual to Spanish",
"input_mime_types": ["text/plain"],
"output_mime_types": ["text/plain"],
"max_latency_ms": 8000,
"min_score": 0.6
}' | jq
```
### Python orchestrator
A minimum-viable orchestrator: fan out, filter rejections, rank, return the winner.
```python theme={null}
import asyncio
import httpx
async def probe(client, url, payload):
try:
r = await client.post(f"{url}/agent/negotiation", json=payload, timeout=5)
if r.status_code == 200:
return {"url": url, **r.json()}
except Exception:
return None
async def find_best_agent(task_summary, agent_urls, min_score=0.6):
payload = {"task_summary": task_summary, "min_score": min_score}
async with httpx.AsyncClient() as client:
results = await asyncio.gather(
*[probe(client, u, payload) for u in agent_urls]
)
accepted = [r for r in results if r and r.get("accepted")]
if not accepted:
return None
return max(accepted, key=lambda r: r["score"])
best = asyncio.run(find_best_agent(
"Extract tables from PDF invoice",
["http://agent1:3773", "http://agent2:3773", "http://agent3:3773"],
))
print(best["url"], best["score"])
```
***
## Real-world use cases
Query every translation agent in parallel. The specialist with matching domain
keywords (e.g. `technical_translation` in `specializations`) bubbles up over the
generalist even with a deeper queue.
```text theme={null}
Agent 1: accepted=true, score=0.98 (technical specialist, queue=2)
Agent 2: accepted=true, score=0.82 (general translator, queue=0)
Agent 3: accepted=false, reason=score_below_threshold (no technical specialization)
```
When an agent advertises a price via the `x402` capability, the `cost` subscore
becomes meaningful. Set `max_cost_amount` to your budget and the agent rejects with
`cost_exceeds_budget` if it can't fit. Among the survivors, pick by your own rule —
cheapest, fastest, highest score.
```python theme={null}
accepted = [r for r in results if r and r["accepted"] and r["score"] > 0.8]
cheapest = min(accepted, key=lambda r: r["subscores"]["cost"])
```
The orchestrator is yours to write. Bindu doesn't ship one — it ships the side of the
protocol that lets any agent answer the question honestly. Re-rank by custom
business rules without changing agents:
```python theme={null}
# Prefer agents with lower queue depth among those above the quality bar
candidates = [r for r in results if r and r["accepted"] and r["score"] > 0.75]
pick = min(candidates, key=lambda r: r.get("queue_depth", 0))
```
The Bindu gateway is stateless and forwards by agent ID — it does not orchestrate
negotiation. If you want capability-based routing in front of the gateway, run a
thin orchestrator that calls `/agent/negotiation` on each candidate and forwards the
real task to the winner via the gateway as usual.
***
## Edge cases & FAQ
Each agent returns `accepted: false` with a specific `rejection_reason`. The
orchestrator's job is to either fall back to a relaxed query (drop `min_score`, drop
`required_tools`), pick the highest-scoring rejection anyway and accept the risk, or
surface the failure to the caller. The agent itself takes no further action.
The calculator returns `accepted: false, rejection_reason: "no_skills_advertised"`
immediately. No scoring runs. Negotiation requires that the agent has declared at
least one `Skill` in its manifest.
`use_embeddings` stays on, but the lazy load fails the first time it's needed, logs
a warning, and flips the flag off. The pipeline degrades to pure keyword (Jaccard)
matching. You lose paraphrase resilience but the endpoint stays functional.
The endpoint asks the task manager's storage layer for all tasks and counts the ones
whose `status.state` is in `app_settings.agent.non_terminal_states`. So a busy agent
actually scores lower on `load` — the formula is `1 / (1 + queue_depth)`, which goes
from 1.0 at idle to 0.5 at one in-flight to 0.33 at two, and so on.
Yes. Self-assessment is a trust contract, not a proof. The orchestrator should track
actual outcomes (latency, success rate) and either down-rank dishonest agents or
publish reputation back into selection. Bindu does not enforce honesty in the
response — the protocol just exposes the agent's claim.
No. It's in the public-endpoints allowlist alongside `/agent/info` and
`/.well-known/agent.json`. Anyone reachable on the network can probe. If that's not
OK for your deployment, front the agent with a gateway or proxy that gates the
route.
***
## Design principles
Agents score themselves with real data — queue depth from storage, latency from
skill metadata, price from the x402 extension. Inflating scores is technically
possible but observably wrong over time.
Orchestrators tune weights per request. Same agent, same skills, different ranking
depending on whether you want speed, fit, or cost.
The endpoint is one POST with one JSON body. Build the orchestrator however you
like — broadcast, two-phase, hedged requests, reputation-weighted.
***
## Related
* [Skills](/bindu/skills/introduction/overview)
* [Scheduler](/bindu/learn/scheduler/overview)
* [Observability](/bindu/learn/observability/overview)
Bindu enables agents to negotiate like sunflowers —
independent in stance, yet
aligned in trust across the Internet of Agents.
# Push notifications
Source: https://docs.getbindu.com/bindu/learn/notification/overview
Stop polling. Your agent webhooks the caller when a task changes state, so they only ask once.
Your agent kicks off a job that takes 8 minutes. The caller has two bad options: hold the HTTP connection open for 8 minutes (and watch it die to a proxy timeout at minute 6), or poll `tasks/get` every few seconds (and discover that 95% of those calls return "still working").
Webhooks fix it. The caller registers a URL once, then goes about their day. When the task transitions — `working`, `input-required`, `completed`, `failed`, and so on — Bindu `POST`s a signed JSON event to that URL. One notification per real event. Zero wasted requests.
This follows the [A2A Protocol push notification spec](https://a2a-protocol.org/latest/specification/), so any A2A-compliant client can subscribe without custom code.
Use webhooks when a task may outlive a normal request timeout — minutes, hours, or days.
For sub-second responses, just keep the connection open and skip this entirely.
## Push vs polling
Client decides cadence. Wastes requests. Latency = poll interval. Works
everywhere, no inbound port required on the client.
Server decides cadence. One event per real state change. Sub-second latency.
Client must expose an HTTPS endpoint Bindu can reach.
| Property | Polling | Push |
| ------------------------------- | --------------------------- | ----------------------------------------------- |
| Requests per task | Many (one per poll) | One per state change |
| Worst-case latency | Poll interval | Network RTT |
| Client must accept inbound HTTP | No | Yes |
| Survives server restart | Trivially | Only if `long_running=true` |
| Auth direction | Client authenticates server | Server authenticates to client (`Bearer` token) |
***
## How it works
Register a webhook per task at `message/send`, or set one `global_webhook_url`
on the manifest that catches everything else.
When the caller sets `long_running=true`, the webhook config is written to
storage and reloaded on startup, so notifications survive restarts.
Bindu resolves the webhook hostname once, refuses private / loopback /
metadata IPs, and connects directly to the resolved address — no DNS-rebinding
window between validation and delivery.
```mermaid theme={null}
sequenceDiagram
participant Client
participant Handlers as MessageHandlers
participant Push as PushNotificationManager
participant Worker as ManifestWorker
participant Storage
participant Webhook as Webhook Receiver
Client->>Handlers: message/send (+ push_notification_config)
Handlers->>Push: register_push_config(persist=long_running)
Push->>Storage: save_webhook_config (if long_running)
Handlers->>Worker: schedule task
Worker->>Push: notify_lifecycle("working", final=False)
Push->>Webhook: POST status-update
Worker->>Worker: run manifest
Worker->>Push: notify_artifact(artifact)
Push->>Webhook: POST artifact-update
Worker->>Push: notify_lifecycle("completed", final=True)
Push->>Webhook: POST status-update (final=true)
```
Send `push_notification_config` inline with `message/send`, or call
`tasks/pushNotificationConfig/set` later. Add `long_running: true` if you
need the subscription to survive a Bindu restart.
`ManifestWorker` runs the task. Every state transition and every artifact
flush hits `PushNotificationManager`.
`NotificationService.send_event` validates the URL, JSON-encodes the event
(`default=str` for UUIDs/datetimes), POSTs with `Authorization: Bearer `,
and retries transient failures up to 3 attempts with exponential backoff.
***
## Quick start
### 1. Declare the capability
```python theme={null}
from bindu.penguin.manifest import bindufy
config = {
"name": "data-processor",
"capabilities": {"push_notifications": True}, # required
"global_webhook_url": "https://myapp.com/webhooks/global", # optional fallback
"global_webhook_token": "global_secret_token", # optional
}
bindufy(config, handler)
```
`WEBHOOK_URL` and `WEBHOOK_TOKEN` environment variables auto-populate
`global_webhook_url` / `global_webhook_token` when `push_notifications` is
enabled, so you can keep secrets out of code.
### 2. Send a task with a webhook
```python theme={null}
import requests
from uuid import uuid4
resp = requests.post("http://localhost:3773/", json={
"jsonrpc": "2.0",
"id": "req-1",
"method": "message/send",
"params": {
"message": {
"message_id": str(uuid4()),
"task_id": str(uuid4()),
"context_id": str(uuid4()),
"kind": "message",
"role": "user",
"parts": [{"kind": "text", "text": "Process large dataset"}],
},
"configuration": {
"accepted_output_modes": ["application/json"],
"long_running": True,
"push_notification_config": {
"id": str(uuid4()),
"url": "https://myapp.com/webhooks/task-updates",
"token": "secret_abc123",
},
},
},
})
print(resp.json()["result"]["id"])
```
### 3. Receive events
```python theme={null}
from fastapi import FastAPI, Request, Header, HTTPException
app = FastAPI()
EXPECTED = "Bearer secret_abc123"
@app.post("/webhooks/task-updates")
async def handle(request: Request, authorization: str = Header(None)):
if authorization != EXPECTED:
raise HTTPException(401)
event = await request.json()
kind = event["kind"]
if kind == "status-update":
state = event["status"]["state"]
print(f"task {event['task_id']} -> {state}")
# input-required / auth-required carry the prompt in status.message
if state in ("input-required", "auth-required"):
msg = event["status"].get("message", {})
print("agent asks:", msg.get("parts", [{}])[0].get("text"))
if event["final"]:
print("terminal")
elif kind == "artifact-update":
print("artifact:", event["artifact"].get("name"))
return {"ok": True}
```
If `capabilities.push_notifications` is missing or `False`, every push RPC
returns JSON-RPC error `-32005` (`PushNotificationNotSupportedError`) and no
events fire. Enable the capability first.
***
## Events Bindu actually emits
Bindu does not emit a `submitted` event. `submitted` is the initial database state set when a task is accepted; the first webhook you ever receive is `working`. Every event is a JSON-RPC-free POST body — no envelope, just the event object.
### Common envelope
Every event carries the same top-level fields:
```json theme={null}
{
"event_id": "550e8400-e29b-41d4-a716-446655440000",
"sequence": 1,
"timestamp": "2026-05-18T08:00:00.123456+00:00",
"kind": "status-update",
"task_id": "123e4567-e89b-12d3-a456-426614174000",
"context_id": "789e0123-e89b-12d3-a456-426614174000"
}
```
* `event_id` — unique per emission; use it to deduplicate on the receiver.
* `sequence` — monotonically increasing per task, starting at 1. Use to detect out-of-order delivery.
* `timestamp` — ISO 8601, UTC, microsecond precision.
Emitted when the worker picks the task up and transitions out of `submitted`.
```json theme={null}
{
"event_id": "...",
"sequence": 1,
"timestamp": "2026-05-18T08:00:00.123456+00:00",
"kind": "status-update",
"task_id": "...",
"context_id": "...",
"status": {
"state": "working",
"timestamp": "2026-05-18T08:00:00.123456+00:00"
},
"final": false
}
```
Emitted when the agent needs more from the user before it can continue.
The agent's prompt is embedded inside `status.message` as an A2A `Message`
so operator-facing clients (like the Bindu inbox) can show it directly.
```json theme={null}
{
"event_id": "...",
"sequence": 2,
"timestamp": "2026-05-18T08:01:00.000000+00:00",
"kind": "status-update",
"task_id": "...",
"context_id": "...",
"status": {
"state": "input-required",
"timestamp": "2026-05-18T08:01:00.000000+00:00",
"message": {
"role": "agent",
"kind": "message",
"parts": [{"kind": "text", "text": "Which date range should I use?"}]
}
},
"final": false
}
```
Same shape applies for `auth-required` and any future intermediate state
that passes a `status_message` through.
Emitted for each artifact the task produces, fired *after* the task has been
persisted to storage (outbox pattern — the DB write commits before the
notification leaves, so the webhook never references state that isn't yet
durable).
```json theme={null}
{
"event_id": "...",
"sequence": 3,
"timestamp": "2026-05-18T08:05:00.000000+00:00",
"kind": "artifact-update",
"task_id": "...",
"context_id": "...",
"artifact": {
"artifact_id": "456e7890-e89b-12d3-a456-426614174000",
"name": "results.json",
"parts": [
{"kind": "data", "data": {"records": 10000, "status": "ok"}}
]
}
}
```
JSON encoding uses `json.dumps(..., default=str)`, so UUIDs and datetimes
inside the artifact serialize as strings — your receiver should treat
`artifact_id` as a string, not a UUID type.
Terminal events. `final: true` tells the receiver no more events are coming
for this `task_id`.
```json theme={null}
{
"event_id": "...",
"sequence": 4,
"timestamp": "2026-05-18T08:05:01.000000+00:00",
"kind": "status-update",
"task_id": "...",
"context_id": "...",
"status": {
"state": "completed",
"timestamp": "2026-05-18T08:05:01.000000+00:00"
},
"final": true
}
```
Order is: all `artifact-update` events first (for `completed`), then the
terminal `status-update`.
**States that can appear in a `status-update`:** `working`, `input-required`,
`auth-required`, `completed`, `failed`, `canceled`, `rejected`. Bindu also
supports extended states (`payment-required`, `negotiation-bid-submitted`,
etc.) — these emit the same envelope when the worker transitions to them.
***
## Headers sent on every POST
```http theme={null}
POST /webhooks/task-updates HTTP/1.1
Host: myapp.com
Content-Type: application/json
Authorization: Bearer secret_abc123
```
That's it. There is no HMAC signature header today — authentication is the bearer token. Compare it constant-time on receive.
Bindu does **not** sign payloads with an HMAC. The bearer token is the only
authentication signal. If you need stronger integrity, mint a fresh token
per task and rotate aggressively, or terminate the webhook behind a gateway
that adds its own signing.
***
## Registration paths
Send `push_notification_config` in the `message/send` configuration.
The subscription exists before the task starts, so no `working` event
can race past you.
`tasks/pushNotificationConfig/set` — useful for late-binding a webhook
to an existing task, or rotating the URL/token mid-flight.
```json theme={null}
{
"params": {
"message": { /* ... */ },
"configuration": {
"accepted_output_modes": ["application/json"],
"long_running": true,
"push_notification_config": {
"id": "webhook-123",
"url": "https://myapp.com/webhook",
"token": "secret_token"
}
}
}
}
```
```json theme={null}
{
"jsonrpc": "2.0",
"id": "rpc-7",
"method": "tasks/pushNotificationConfig/set",
"params": {
"id": "task-123",
"long_running": true,
"push_notification_config": {
"id": "webhook-456",
"url": "https://myapp.com/webhook",
"token": "secret_token"
}
}
}
```
Only the task owner (the DID that originally submitted the task) may call
this. A non-owner gets `TaskNotFound` — Bindu does not leak that the task
exists.
***
## Persistence and fallback
### Long-running tasks
When the caller sets `long_running: true`, `PushNotificationManager` calls
`storage.save_webhook_config(task_id, config)`. On boot, `initialize()` calls
`storage.load_all_webhook_configs()` and reinstalls every subscription before
the worker pool starts accepting tasks.
```
POST / (message/send, long_running=true)
-> register_push_config(persist=True)
-> Storage.save_webhook_config
[ server crash + restart ]
-> PushNotificationManager.initialize()
-> Storage.load_all_webhook_configs() -> {task_id: config, ...}
-> notifications resume
```
If `long_running` is omitted or `false`, the subscription lives in memory
only. A restart silently drops it and the caller's webhook goes quiet.
### Webhook precedence
`get_effective_webhook_config(task_id)` resolves in this order:
1. Task-specific config registered for `task_id`
2. Manifest `global_webhook_url` (if set)
3. `None` — no delivery, event is dropped silently
***
## API reference
### RPC methods
```json tasks/pushNotificationConfig/set theme={null}
{
"jsonrpc": "2.0",
"id": "1",
"method": "tasks/pushNotificationConfig/set",
"params": {
"id": "task-123",
"long_running": true,
"push_notification_config": {
"id": "webhook-456",
"url": "https://myapp.com/webhook",
"token": "secret"
}
}
}
```
```json tasks/pushNotificationConfig/get theme={null}
{
"jsonrpc": "2.0",
"id": "2",
"method": "tasks/pushNotificationConfig/get",
"params": { "task_id": "task-123" }
}
```
```json tasks/pushNotificationConfig/list theme={null}
{
"jsonrpc": "2.0",
"id": "3",
"method": "tasks/pushNotificationConfig/list",
"params": { "id": "task-123" }
}
```
```json tasks/pushNotificationConfig/delete theme={null}
{
"jsonrpc": "2.0",
"id": "4",
"method": "tasks/pushNotificationConfig/delete",
"params": {
"id": "task-123",
"push_notification_config_id": "webhook-456"
}
}
```
All four methods enforce caller ownership. If `caller_did` does not match
the task owner stored at submission, the response is the same as a missing
task — Bindu refuses to leak existence.
### PushNotificationConfig
```python theme={null}
class PushNotificationConfig(TypedDict):
id: Required[UUID] # subscription ID — used for delete
url: Required[str] # http or https; private IPs rejected
token: NotRequired[str] # sent verbatim as "Authorization: Bearer "
authentication: NotRequired[SecurityScheme] # optional richer auth schema
```
***
## Delivery, retries, and failure handling
`NotificationService` lives in `bindu/utils/notifications.py` and handles every
outbound POST. It is not Kafka, not SNS, not a queue — it is a direct HTTP call
wrapped in the unified retry decorator.
| Knob | Value |
| ---------------- | --------------------------------------- |
| Transport | HTTP/HTTPS POST |
| Timeout | 5 s connect + read |
| Max attempts | 3 |
| Backoff | Exponential, `0.5s → 5s` |
| Retried on | 5xx, 429, connection errors, timeouts |
| Dropped on | 4xx (except 429) — logged and abandoned |
| After exhaustion | Logged, no DLQ, event is lost |
There is no dead-letter queue. If your endpoint is down for longer than the
retry window (\~10 s with backoff), the event is dropped. Treat webhook
delivery as *best-effort* and reconcile with `tasks/get` on reconnect for
anything you cannot afford to miss.
### Why 4xx is dropped
A 4xx means "your request is broken" — replaying it will fail the same way.
Bindu logs at `WARNING` and moves on rather than burning retry budget. `429`
is the exception: it means "slow down," so it gets the full retry treatment.
### SSRF protection (server side, automatic)
Before every POST, `validate_config` does this:
1. Parse the URL; require `http` or `https` scheme and a non-empty netloc.
2. Resolve the hostname via `socket.getaddrinfo` *once*.
3. Reject loopback / private / link-local / metadata addresses.
4. Pass the resolved IP through to the connection layer. The HTTP client
connects directly to that IP and uses the original hostname only for the
TLS SNI / cert verification.
This closes the TOCTOU DNS-rebinding window where a malicious DNS server could
return a public IP for validation and a private IP for the actual connection.
You do not need to re-implement any of this on the client.
***
## Receiver patterns
### Verify the token (constant-time)
```python theme={null}
import hmac
from fastapi import FastAPI, Request, Header, HTTPException
app = FastAPI()
EXPECTED = "Bearer secret_abc123"
@app.post("/webhook")
async def hook(request: Request, authorization: str = Header(None)):
if not authorization or not hmac.compare_digest(authorization, EXPECTED):
raise HTTPException(401)
return await _process(await request.json())
```
### Dedupe by `event_id`, order by `sequence`
```python theme={null}
seen: set[str] = set()
last_seq: dict[str, int] = {}
async def _process(event):
eid = event["event_id"]
if eid in seen:
return {"ok": True, "dedup": True}
seen.add(eid)
tid = event["task_id"]
if event["sequence"] <= last_seq.get(tid, 0):
# out-of-order or replay — fold into reconciliation pass, not state
return {"ok": True, "stale": True}
last_seq[tid] = event["sequence"]
# ... do work ...
return {"ok": True}
```
### Node / Express receiver
```javascript theme={null}
const express = require("express");
const app = express();
app.use(express.json());
const EXPECTED = "Bearer secret_abc123";
app.post("/webhook", (req, res) => {
if (req.headers.authorization !== EXPECTED) {
return res.status(401).json({ error: "unauthorized" });
}
const ev = req.body;
if (ev.kind === "status-update") {
console.log(`${ev.task_id} -> ${ev.status.state}${ev.final ? " (final)" : ""}`);
} else if (ev.kind === "artifact-update") {
console.log(`artifact ${ev.artifact.name} for ${ev.task_id}`);
}
res.json({ ok: true });
});
app.listen(8000);
```
### Smoke-test with curl
```bash theme={null}
curl -X POST https://myapp.com/webhooks/task-updates \
-H "Authorization: Bearer secret_abc123" \
-H "Content-Type: application/json" \
-d '{
"event_id": "test-1",
"sequence": 1,
"timestamp": "2026-05-18T00:00:00+00:00",
"kind": "status-update",
"task_id": "11111111-1111-1111-1111-111111111111",
"context_id": "22222222-2222-2222-2222-222222222222",
"status": {"state": "working", "timestamp": "2026-05-18T00:00:00+00:00"},
"final": false
}'
```
***
## Disabling
Drop `push_notifications` from `capabilities` (or set it to `False`) and all
four RPCs return JSON-RPC error `-32005` (`PushNotificationNotSupportedError`).
No events fire. Callers should fall back to `tasks/get`.
To disable just the global fallback while leaving per-task webhooks intact,
unset `global_webhook_url` (and unset `WEBHOOK_URL` in the environment).
***
## Troubleshooting
Confirm the capability flag is on:
```python theme={null}
manifest.capabilities["push_notifications"] is True
```
Confirm the subscription is registered:
```json theme={null}
{ "method": "tasks/pushNotificationConfig/get", "params": {"task_id": "task-123"} }
```
If `get` returns `Push notification configuration not found for task.`, the
inline `push_notification_config` in `message/send` was missing or the task
completed and the manager has dropped the entry.
`long_running: true` is required for persistence. Without it the
subscription is in-memory only.
```python theme={null}
"configuration": {
"long_running": True,
"push_notification_config": {...},
}
```
Bindu sends exactly `Authorization: Bearer ` — token verbatim, no
extra whitespace. The `token` you registered must match byte-for-byte.
Compare with `hmac.compare_digest`, not `==`.
`validate_config` rejects:
* Non-`http`/`https` schemes
* Missing hostname
* Hostnames that resolve to loopback, private, link-local, or cloud-metadata IPs
Use a publicly resolvable hostname. For local dev, expose via a tunnel
rather than pointing at `127.0.0.1` or `10.x.x.x`.
Bindu emits one event per state change, but a 5xx-then-success retry can
cause the same `event_id` to appear twice on the wire. Dedupe on
`event_id` and you are safe.
`artifact-update` events fire before the terminal `completed` event by
design. Within a single TCP-bound `task_id`, follow `sequence` to detect
reordering caused by retries.
***
## Related
How the 3-attempt exponential backoff is wired and how to tune it.
Where `long_running=true` actually persists webhook configs.
The path between `message/send` and the worker that fires events.
The interop contract this implementation follows.
Bindu turns long-running work into
something clients can follow without polling
, so tasks can keep running while updates keep moving.
# Observability
Source: https://docs.getbindu.com/bindu/learn/observability/overview
OpenInference traces and Sentry errors. The boring stuff that saves you at 2am.
Production is silent until it screams. At 2am you get the page: `agents/research` is slow. You log in. Which call is slow? Which downstream API? Was it the LLM, the retriever, or the tool? You scroll through unstructured logs hoping to spot the timestamp that explains everything.
You shouldn't have to do that. Bindu wires up two complementary signals on startup:
* **OpenInference** — semantic spans for agent frameworks (Agno, CrewAI, LangChain, LlamaIndex, DSPy, Haystack, AutoGen, etc.) and LLM providers (OpenAI, Anthropic, Mistral, Groq, Bedrock, VertexAI, Google GenAI, LiteLLM). Auto-detected at boot. Shipped over OTLP/HTTP to any compatible backend — Phoenix, Arize, Langfuse — or printed to your console if no endpoint is set.
* **Sentry** — exceptions, 5xx requests, performance transactions, release tagging. Auto-instruments Starlette HTTP endpoints, SQLAlchemy queries, Redis calls, and asyncio tasks. Strips secrets before they leave the process.
## Why Agent Observability Is Different
A typical web app trace ends with a SQL query. An agent trace doesn't.
| Concern | Web app | Agent |
| ------------------------- | ----------- | --------------------------------- |
| Slowest hop is usually... | DB query | LLM call or tool loop |
| Cost per request | \~free | $0.001 – $1+ per turn |
| Determinism | High | None |
| Retries | Idempotent | Side-effects on every call |
| "What did it do?" | Stack trace | Prompt + response + tool sequence |
OpenInference captures the agent-shaped data (prompts, tool calls, token counts, model name, reasoning steps) using semantic conventions designed for LLM workloads. Sentry handles the parts that look like a normal service (HTTP errors, DB latency, releases).
OpenInference auto-instruments your agent framework and LLM client, attaching prompts,
completions, tool calls, and token usage to each span.
Sentry captures unhandled exceptions and 5xx responses with stack trace, release tag,
environment, and request context. Secrets are scrubbed before send.
OTLP/HTTP spans flow to Phoenix, Arize, Langfuse, or anything that speaks
OpenTelemetry — no vendor lock-in.
## How It Works
```mermaid theme={null}
sequenceDiagram
participant Bindufy as bindufy()
participant Setup as observability.setup()
participant Detect as Framework Detector
participant OTel as TracerProvider
participant Sentry
participant Backend as Phoenix / Arize / Langfuse
participant SentryIO as Sentry.io
Note over Bindufy: Startup lifespan
Bindufy->>Setup: setup(endpoint, service_name, headers, ...)
Setup->>OTel: Create TracerProvider (service.name, version, env)
alt OLTP_ENDPOINT set
Setup->>OTel: BatchSpanProcessor + OTLPSpanExporter
else no endpoint
Setup->>OTel: SimpleSpanProcessor + ConsoleSpanExporter
end
Setup->>Detect: scan installed distributions
Detect-->>Setup: framework spec (agno / langchain / openai / ...)
Setup->>OTel: ().instrument(tracer_provider)
Bindufy->>Sentry: init_sentry() if SENTRY_ENABLED
Sentry->>Sentry: Starlette + SQLAlchemy + Redis + Asyncio integrations
Note over Bindufy: Request arrives
Bindufy->>OTel: spans (LLM call, tool call, retriever, ...)
OTel->>Backend: OTLP/HTTP, batched
Bindufy->>Sentry: capture exception / 5xx transaction
Sentry->>SentryIO: scrub PII → send
```
On startup, Bindu calls `observability.setup()` (OpenInference + OTel) and
`init_sentry()`. The tracer provider is always created — even with no endpoint,
spans print to console so local development works without a backend.
`setup()` walks installed Python distributions, picks the first supported framework
(agent frameworks before raw LLM SDKs to avoid double-instrumentation), and calls
its OpenInference instrumentor.
Spans batch-export to your OTLP endpoint. Exceptions and 5xx transactions hit Sentry.
Open Phoenix for trace timelines, Sentry for the stack trace.
If no agent framework is detected (or the installed version is below the OpenInference
minimum), Bindu logs the missing packages and the suggested install command, then
continues without LLM-level tracing. The tracer provider stays active so any other
OTel-emitting library still works.
***
## OpenInference Setup
### Auto-Detected Frameworks
Bindu picks the first match it finds, in this priority order. Agent frameworks come
before raw LLM SDKs so you don't get duplicate spans (e.g. Agno calling OpenAI shouldn't
emit one span from each).
| Tier | Frameworks |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Agent frameworks | `agno`, `crewai`, `langchain`, `llama-index`, `dspy`, `haystack`, `instructor`, `pydantic-ai`, `autogen`, `smolagents` |
| LLM providers | `litellm`, `openai`, `anthropic`, `mistralai`, `groq`, `bedrock`, `vertexai`, `google-genai` |
You don't list these in config. Whatever's in your `pyproject.toml` is what gets traced.
### Supported Backends
Local LLM observability UI. Default Bindu dev target. Run with `docker run -p 6006:6006 arizephoenix/phoenix`.
Self-hosted or cloud. LLM analytics, evals, and prompt management.
Production AI observability with drift detection.
Anything else that speaks OTLP/HTTP works too — Jaeger, Honeycomb, Grafana Tempo, etc.
You just need the right endpoint and headers.
### Configuration
Bindu's setup function takes its arguments either programmatically (via `bindufy` config)
or from environment variables that the config enricher reads. Env vars use the `OLTP_`
prefix (yes, with the `L` — it's the canonical spelling in the Bindu codebase).
`OLTP_HEADERS` must be valid JSON. The enricher calls `json.loads()` on it and raises
if it isn't parseable.
```bash theme={null}
# Master switch — defaults to true
TELEMETRY_ENABLED=true
# Where to send spans (omit for console output)
OLTP_ENDPOINT=https://cloud.langfuse.com/api/public/otel/v1/traces
# service.name attribute on every span
OLTP_SERVICE_NAME=research-agent
# Authentication headers as JSON
OLTP_HEADERS={"Authorization":"Basic "}
```
The `setup()` function also accepts these — pass them through `bindufy` config or rely
on the defaults in `bindu/observability/openinference.py`:
```bash theme={null}
# Resource attributes
OLTP_SERVICE_VERSION=1.0.0
OLTP_DEPLOYMENT_ENVIRONMENT=production
# BatchSpanProcessor tuning
OLTP_BATCH_MAX_QUEUE_SIZE=2048
OLTP_BATCH_SCHEDULE_DELAY_MILLIS=5000
OLTP_BATCH_MAX_EXPORT_BATCH_SIZE=512
OLTP_BATCH_EXPORT_TIMEOUT_MILLIS=30000
# Print each export result to logs
OLTP_VERBOSE_LOGGING=true
```
### Per-Backend Setup
Start Phoenix locally:
```bash theme={null}
docker run -p 6006:6006 arizephoenix/phoenix
```
Point Bindu at it:
```bash theme={null}
TELEMETRY_ENABLED=true
OLTP_ENDPOINT=http://localhost:6006/v1/traces
OLTP_SERVICE_NAME=research-agent-local
```
No headers required. Open `http://localhost:6006` to see traces stream in.
1. Sign up at [cloud.langfuse.com](https://cloud.langfuse.com) (or self-host).
2. Settings → API Keys → create a key pair.
3. Base64-encode `:`:
```bash theme={null}
echo -n "pk-xxx:sk-xxx" | base64
```
4. Configure env:
```bash theme={null}
TELEMETRY_ENABLED=true
OLTP_ENDPOINT=https://cloud.langfuse.com/api/public/otel/v1/traces
OLTP_SERVICE_NAME=research-agent
OLTP_HEADERS={"Authorization":"Basic "}
OLTP_VERBOSE_LOGGING=true
```
Langfuse needs the full path including `/api/public/otel/v1/traces`. Bindu's exporter
will log a hint if the endpoint looks wrong.
1. Sign up at [arize.com](https://arize.com).
2. Settings → API Keys → copy Space ID and API Key.
3. Configure env:
```bash theme={null}
TELEMETRY_ENABLED=true
OLTP_ENDPOINT=https://otlp.arize.com/v1
OLTP_SERVICE_NAME=research-agent
OLTP_HEADERS={"space_id":"","api_key":""}
OLTP_VERBOSE_LOGGING=true
```
Bindu uses `OTLPSpanExporter` from `opentelemetry.exporter.otlp.proto.http`. Anything
that accepts OTLP over HTTP (Jaeger, Honeycomb, Tempo, New Relic, Datadog OTLP) will
work — set the endpoint and required headers.
```bash theme={null}
TELEMETRY_ENABLED=true
OLTP_ENDPOINT=https://api.honeycomb.io/v1/traces
OLTP_HEADERS={"x-honeycomb-team":""}
```
`setup()` accepts a list — useful when you want Phoenix locally and Langfuse in
parallel. Each endpoint gets its own `BatchSpanProcessor`:
```python theme={null}
from bindu.observability import setup
setup(
oltp_endpoint=[
"http://localhost:6006/v1/traces",
"https://cloud.langfuse.com/api/public/otel/v1/traces",
],
oltp_headers={"Authorization": "Basic "},
oltp_service_name="research-agent",
)
```
### What Ends Up In a Trace
A typical agent turn looks roughly like this in Phoenix or Langfuse:
```text theme={null}
research-agent · message/send 1.2s
├─ AgnoAgent.run 1.2s
│ ├─ ChatOpenAI.chat 0.8s
│ │ ├─ openinference.span.kind = LLM
│ │ ├─ llm.model_name = gpt-4o-mini
│ │ ├─ llm.input_messages = [...]
│ │ ├─ llm.output_messages = [...]
│ │ ├─ llm.usage.prompt_tokens = 412
│ │ └─ llm.usage.completion_tokens = 87
│ └─ ToolCall.web_search 0.3s
│ ├─ openinference.span.kind = TOOL
│ ├─ tool.name = web_search
│ ├─ input.value = "latest LLM benchmarks 2025"
│ └─ output.value = [...]
```
Span structure follows the [OpenInference semantic conventions](https://github.com/Arize-ai/openinference/blob/main/spec/semantic_conventions.md).
***
## Sentry Setup
Sentry handles the operational side — exceptions, 5xx responses, slow transactions.
Bindu wires four integrations automatically:
* **Starlette** — every HTTP endpoint under `bindu/server/endpoints/`. Failed-request
status codes default to 500–511.
* **SQLAlchemy** — query spans when using PostgreSQL storage.
* **Redis** — Redis scheduler commands.
* **Asyncio** — task and gather instrumentation so async errors don't disappear.
### Configuration
Sentry uses two env-var shapes: flat (`SENTRY_ENABLED`, `SENTRY_DSN`) for the master
switches read by the config enricher, and nested (`SENTRY__*`) for fields on
`SentrySettings` — the double underscore maps to Pydantic's nested env delimiter.
```bash theme={null}
# Master switches (flat, read by enricher)
SENTRY_ENABLED=true
SENTRY_DSN=https://@.ingest.sentry.io/
# Nested settings (Pydantic SentrySettings)
SENTRY__ENVIRONMENT=production
SENTRY__RELEASE=research-agent@1.0.0 # defaults to bindu@ if unset
SENTRY__TRACES_SAMPLE_RATE=1.0 # 0.0–1.0
SENTRY__PROFILES_SAMPLE_RATE=0.1 # 0.0–1.0, default is 0.1 (not 1.0)
SENTRY__ENABLE_TRACING=true
SENTRY__SEND_DEFAULT_PII=false # keep false in production
SENTRY__ATTACH_STACKTRACE=true
SENTRY__MAX_BREADCRUMBS=100
SENTRY__DEBUG=false
```
If `SENTRY_ENABLED=true` but `SENTRY_DSN` is missing, the enricher raises at startup.
### Built-in Safety Rails
These are wired in `bindu/observability/sentry.py` — you get them for free.
* **PII scrubbing on every event.** `_before_send` strips `authorization`, `x-api-key`,
`cookie`, `x-auth-token` headers and `password`, `token`, `secret`, `api_key`,
`private_key` body keys before the event leaves the process.
* **Health-check noise filtering.** `_before_send_transaction` drops transactions whose
name matches `/healthz`, `/health`, `/metrics`, `/favicon.ico`.
* **Auto release tagging.** If `SENTRY__RELEASE` is unset, Bindu falls back to
`bindu@` from `bindu._version`.
* **Hostname as `server_name`** — set via `socket.gethostname()` if you don't override it.
* **Ignored exceptions.** `KeyboardInterrupt` and `SystemExit` are never reported.
### Enabling
[sentry.io](https://sentry.io) → New Project → Python → copy the DSN.
```bash theme={null}
SENTRY_ENABLED=true
SENTRY_DSN=https://xxx@xxx.ingest.sentry.io/xxx
SENTRY__ENVIRONMENT=production
SENTRY__RELEASE=research-agent@1.0.0
SENTRY__TRACES_SAMPLE_RATE=0.2 # sample 20% in prod
```
`init_sentry()` runs in the FastAPI/Starlette lifespan. Look for
`✅ Sentry initialized` in the logs.
***
## Adding Custom Spans and Context
OpenInference auto-instruments the framework. Anything outside the framework — your own
preprocessing, post-processing, business logic — needs explicit spans:
```python theme={null}
from opentelemetry import trace
tracer = trace.get_tracer("my-agent")
with tracer.start_as_current_span("preprocess_documents") as span:
span.set_attribute("doc.count", len(docs))
span.set_attribute("doc.total_bytes", total_bytes)
result = clean_and_chunk(docs)
span.set_attribute("chunks.count", len(result))
```
For Sentry, attach tags and context to all errors raised inside a request:
```python theme={null}
import sentry_sdk
sentry_sdk.set_tag("feature", "pdf-processing")
sentry_sdk.set_context("business", {
"plan": "premium",
"credits_remaining": 100,
})
# breadcrumbs show up on any subsequent exception
sentry_sdk.add_breadcrumb(
category="agent",
message="Started document ingestion",
level="info",
)
```
***
## Agent Configuration
No code changes are required — observability reads env vars on startup.
```python theme={null}
from bindu import bindufy
config = {
"author": "you@example.com",
"name": "research_agent",
"description": "A research assistant agent",
"deployment": {"url": "http://localhost:3773", "expose": True},
"skills": ["skills/question-answering"],
}
bindufy(config, handler)
```
The agent defines behavior. The environment defines how deeply it's observed.
***
## Production Tips
### Sample traces, not errors
```bash theme={null}
# Sentry: keep 100% of errors, sample 10% of transactions
SENTRY__TRACES_SAMPLE_RATE=0.1
SENTRY__PROFILES_SAMPLE_RATE=0.1
```
OpenInference doesn't sample by default — every span is exported. If you need head
sampling, configure it on the OTel backend (Phoenix, Tempo, etc.) or front the exporter
with a sampler.
### Separate environments
```bash theme={null}
# Development
SENTRY__ENVIRONMENT=development
OLTP_SERVICE_NAME=research-agent-dev
OLTP_ENDPOINT=http://localhost:6006/v1/traces
# Production
SENTRY__ENVIRONMENT=production
OLTP_SERVICE_NAME=research-agent-prod
OLTP_ENDPOINT=https://cloud.langfuse.com/api/public/otel/v1/traces
```
### No backend? You still get traces
If `OLTP_ENDPOINT` is unset, Bindu falls back to `ConsoleSpanExporter` — every span
pretty-prints to stdout. Great for local debugging, terrible for production. Set an
endpoint before you ship.
When Bindu can't reach the configured OTLP endpoint, the wrapped exporter logs a
one-time hint specific to the URL pattern (e.g. "Langfuse requires endpoint:
\/api/public/otel/v1/traces"). Check logs first when traces don't show up.
***
## Related
* [Health Check & Metrics](/bindu/learn/health-metrics/overview)
* [OpenInference (GitHub)](https://github.com/Arize-ai/openinference)
* [OpenInference Semantic Conventions](https://github.com/Arize-ai/openinference/blob/main/spec/semantic_conventions.md)
* [Phoenix Documentation](https://docs.arize.com/phoenix)
* [Langfuse Documentation](https://langfuse.com/docs)
* [Sentry Python SDK](https://docs.sentry.io/platforms/python/)
* [OpenTelemetry Python](https://opentelemetry.io/docs/languages/python/)
Bindu brings clarity to your agents —
each one visible, traceable, and growing in trust
across the Internet of Agents.
# Payment Integration (x402)
Source: https://docs.getbindu.com/bindu/learn/payment/introduction
Charge wallets per request — HTTP 402, on-chain settlement, replay-safe
Your agent costs real money to run — LLM tokens, compute, a paid API behind the scenes. You want callers to chip in *before* the work happens, programmatically, without invoices or dashboards or human approval.
Bindu plugs into [**x402**](https://github.com/coinbase/x402), an open protocol that revives the long-dormant `HTTP 402 Payment Required` status for machine payments. A caller hits your agent; if they haven't paid, you reply `402` with exactly what's owed. They sign a one-shot authorization with their wallet, retry with an `X-PAYMENT` header, and your handler runs only after a facilitator has verified the payment on-chain.
## Why HTTP 402
| Without payment gating | With Bindu x402 |
| ------------------------------------------------- | ----------------------------------------------------------------- |
| Anyone hits your handler; you eat the compute | Callers must prove payment before the handler runs |
| Billing depends on dashboards, webhooks, accounts | Settlement is a signed EIP-3009 authorization on a blockchain |
| Per-call micropayments are impractical | Per-call micropayments are native (USDC scales to 6 decimals) |
| Replay protection is your problem | Bindu rejects replayed nonces before settlement |
| Hard to compose into autonomous A2A workflows | Built into the A2A request path; agents can pay agents |
| Coupled to a centralized provider | Facilitator is pluggable; chains/tokens are operator-configurable |
x402 is for **per-request micropayments between machines** — a few cents
per call, on the request hot path. It is not a replacement for subscriptions,
marketplaces, or human checkout flows. Different problem, different tool.
## The Protocol Flow
```mermaid theme={null}
sequenceDiagram
participant Caller
participant Agent as Bindu Agent
participant Facilitator
participant Chain as Blockchain
Caller->>Agent: POST / (no X-PAYMENT header)
Agent-->>Caller: 402 Payment Required
{ x402Version, accepts:[...] }
Note over Caller: Sign EIP-3009 authorization
with wallet, base64 the payload
Caller->>Agent: POST / + X-PAYMENT:
Agent->>Agent: Decode payload, claim nonce
(replay check)
Agent->>Facilitator: POST /verify
Facilitator->>Chain: Recover signature + balanceOf
Facilitator-->>Agent: { isValid: true, payer }
Agent->>Agent: Run handler
Agent->>Facilitator: POST /settle
Facilitator->>Chain: Broadcast transferWithAuthorization
Facilitator-->>Agent: { success, transaction }
Agent-->>Caller: 200 OK + task receipt
```
Three trips, four moving parts:
1. **Caller** — anything that speaks HTTP and can sign with an EVM wallet.
2. **Your Bindu agent** — gatekeeper. Tells callers what it costs, accepts proof, runs the handler.
3. **Facilitator** — separate HTTP service. Reads the signature, checks the chain, broadcasts the transfer. Bindu never speaks to the blockchain directly; it trusts the facilitator's yes/no.
4. **Blockchain** — where USDC actually moves.
Standard HTTP. No SDK lock-in for the caller — just a header and a body.
Facilitator recovers EIP-3009 signatures and checks balance before the handler runs.
Nonces are claimed in Redis (or in-memory) before settlement. Re-sent payloads bounce.
***
## Turning Payments On
Add one block to your `bindufy` config — a price, a token, a network, an address:
```python theme={null}
from bindu.penguin.bindufy import bindufy
config = {
"author": "you@example.com",
"name": "paid_agent",
"description": "An agent that earns its keep.",
"deployment": {"url": "http://localhost:3773", "expose": True},
# ← The whole "I cost money" surface lives in this block.
"execution_cost": {
"amount": "0.01", # 1 cent. String, not float.
"token": "USDC", # USDC is what's supported today.
"network": "base-sepolia", # Base's testnet.
"pay_to_address": "0xYourWalletHere", # Where the money lands.
},
}
bindufy(config, handler)
```
That's it. Any caller hitting `message/send` without payment now gets a 402 describing exactly what's required.
By default only `message/send` is gated. To gate more methods set the
environment variable `X402__PROTECTED_METHODS` or edit
`app_settings.x402.protected_methods`. The default is intentionally narrow —
you don't want to charge for `tasks/get` polling.
### Multiple payment options
Make `execution_cost` a list and the 402 response advertises **all** of them. The caller picks one:
```python theme={null}
"execution_cost": [
{
"amount": "0.1",
"token": "USDC",
"network": "base",
"pay_to_address": "0xYourWallet",
},
{
"amount": "0.01",
"token": "USDC",
"network": "skale-europa",
"pay_to_address": "0xYourSkaleWallet",
},
],
```
Strings only for `amount`. The middleware multiplies by `10**asset_decimals`
(6 for USDC), so `"0.01"` becomes `10000` atomic units on the wire.
Floats round inconsistently; strings don't.
***
## What 402 Actually Looks Like
When a caller hits a protected method without `X-PAYMENT`, Bindu replies with the v2 wire format from `x402.PaymentRequired`:
```json theme={null}
{
"x402Version": 2,
"error": "X-PAYMENT header required",
"accepts": [
{
"scheme": "exact",
"network": "eip155:84532",
"asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"amount": "10000",
"payTo": "0xYourWallet",
"maxTimeoutSeconds": 60,
"extra": { "name": "USDC", "version": "2" }
}
],
"agent": {
"name": "paid_agent",
"description": "An agent that earns its keep.",
"agentCard": "/.well-known/agent.json"
}
}
```
The translation that just happened:
* `"0.01"` from your config → `"10000"` on the wire (atomic units; USDC has 6 decimals).
* `"base-sepolia"` from your config → `"eip155:84532"` (CAIP-2 chain ID; the x402 v2 SDK keys everything off CAIP-2 strings internally).
* `extra.name` / `extra.version` populate the **EIP-712 domain** the caller must sign over — must match the on-chain token's domain separator or signature recovery fails.
The `agent` block is Bindu-specific (not part of the x402 spec) — it lets callers discover the agent card without a second round-trip.
### What the caller sends back
The caller builds an EIP-3009 `TransferWithAuthorization`, signs it with their wallet, wraps it in the v2 payload envelope, and base64-encodes the JSON:
```json theme={null}
{
"x402Version": 2,
"payload": {
"signature": "0x...",
"authorization": {
"from": "0xCallerWallet",
"to": "0xYourWallet",
"value": "10000",
"validAfter": "0",
"validBefore": "9999999999",
"nonce": "0x"
}
},
"accepted": {
"scheme": "exact",
"network": "eip155:84532",
"asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"amount": "10000",
"payTo": "0xYourWallet",
"maxTimeoutSeconds": 60,
"extra": { "name": "USDC", "version": "2" }
}
}
```
That JSON, base64-encoded, becomes the `X-PAYMENT` header on the retry.
v1 payloads are **rejected** outright. The middleware logs
`"x402 v1 payment payloads are no longer accepted; please re-sign with v2"`
and returns 402. Re-sign with a v2 client.
***
## End-to-End Flow
Caller fires a `message/send` with no `X-PAYMENT`. Middleware replies 402
with the `accepts` block above.
```bash theme={null}
curl -i -X POST http://localhost:3773/ \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"method": "message/send",
"id": "req-1",
"params": { "message": { "role": "user", "parts": [{ "kind": "text", "text": "hi" }] } }
}'
# HTTP/1.1 402 Payment Required
# Content-Type: application/json
# { "x402Version": 2, "error": "X-PAYMENT header required", "accepts": [...] }
```
Caller signs an EIP-3009 authorization with their wallet, base64-encodes
the v2 payload, sends it as `X-PAYMENT`.
```bash theme={null}
PAYMENT=$(python build_payment.py) # produces base64 of the JSON above
curl -X POST http://localhost:3773/ \
-H 'Content-Type: application/json' \
-H "X-PAYMENT: $PAYMENT" \
-d '{ "jsonrpc": "2.0", "method": "message/send", "id": "req-2", "params": {...} }'
```
The middleware now:
1. Decodes the base64 + parses the v2 payload.
2. Matches it against your `execution_cost` requirements (`find_matching_requirements`).
3. Claims `(network, asset, nonce)` in the nonce store — **before** any facilitator round-trip. Replays bounce here.
4. Calls the facilitator's `/verify` — signature recovery + on-chain `balanceOf`. Trusts `result.is_valid`. No fall-through.
5. Hands the request off to your handler with `request.state.payer` set.
Your handler executes. When the task finishes, the worker calls the
facilitator's `/settle` endpoint, which broadcasts the
`transferWithAuthorization` on-chain. The receipt lands on the task:
```json theme={null}
{
"result": {
"status": { "state": "completed" },
"artifacts": [{ "parts": [{ "kind": "text", "text": "..." }] }],
"metadata": {
"x402.payment.status": "payment-completed",
"x402.payment.receipts": [{
"success": true,
"payer": "0xCallerWallet",
"transaction": "0x",
"network": "eip155:84532"
}]
}
}
}
```
The `metadata` block is your audit trail. `x402.payment.status` and
`x402.payment.receipts` are the keys to query later if you ever need to
reconcile, dispute, or refund.
***
## Browser-Capture Flow (for non-agent callers)
Sometimes the caller is a human, not another agent — and a human wants to click a MetaMask popup, not generate an EIP-3009 signature in Python. Bindu ships three endpoints that wrap the same x402 machinery in a browser-friendly flow:
| Endpoint | Method | Purpose |
| ---------------------------------- | ------ | --------------------------------------------------------------- |
| `/api/start-payment-session` | POST | Mint a session ID + `browser_url`. |
| `/payment-capture?session_id=...` | GET | Paywall page; renders MetaMask flow; captures the signed token. |
| `/api/payment-status/{session_id}` | GET | Poll for the captured `payment_token` (base64). |
```bash theme={null}
# 1. Start a session
curl -X POST http://localhost:3773/api/start-payment-session
# { "session_id": "...", "browser_url": ".../payment-capture?session_id=...",
# "expires_at": "...", "status": "pending" }
# 2. User opens browser_url, completes payment in their wallet.
# 3. Poll for the captured token
curl http://localhost:3773/api/payment-status/
# { "session_id": "...", "status": "completed",
# "payment_token": "" }
# 4. Use that payment_token as the X-PAYMENT header on your real request.
```
Sessions expire after **15 minutes** by default (see
`PaymentSessionManager(session_timeout_minutes=15)`). The token returned by
`/api/payment-status/...` is the same base64 payload the middleware expects
— Bindu **does not consume it** when you poll, so you can pass it on to
the actual `message/send` call.
***
## Facilitators and Networks
Bindu doesn't talk to chains directly. It talks to a **facilitator** — an HTTP service that implements `/supported`, `/verify`, `/settle` per the x402 spec. The facilitator is what dictates which chains and tokens actually work.
`https://x402.org/facilitator` — Coinbase-operated, this is what Bindu uses
out of the box. Supports Base mainnet, Base Sepolia, plus some non-EVM
chains (Solana, Algorand, Aptos, Stellar) via x402's broader scheme set.
**Does not** support SKALE, Polygon, Avalanche, Ethereum mainnet, or
arbitrary L2s. If you need those, you need a different facilitator.
Single environment variable:
```bash theme={null}
export X402__FACILITATOR_URL=https://your-facilitator.example.com
```
Bindu picks it up at startup and wires the
`HTTPFacilitatorClient(FacilitatorConfig(url=...))` into the
`x402ResourceServer`. Restart the agent for the change to take effect.
The x402 v2 SDK only ships built-in asset metadata for Base mainnet
(`eip155:8453`) and Base Sepolia (`eip155:84532`). For any other EVM
chain, you need to declare two things:
1. **A facilitator that supports it** (set via `X402__FACILITATOR_URL`).
2. **The USDC contract on that chain**, so Bindu can convert a
human-readable price like `"$0.01"` into atomic units of the right
ERC-20.
The second piece lives in `app_settings.x402.extra_networks`:
```python theme={null}
# bindu/settings.py — ships with this entry by default
extra_networks = {
"skale-europa": ExtraNetwork(
caip2="eip155:1187947933",
asset="0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",
asset_symbol="USDC",
asset_name="Bridged USDC (SKALE Bridge)",
asset_decimals=6,
asset_eip712_version="2",
),
}
```
`asset_name` and `asset_eip712_version` go straight into the EIP-712
domain the caller signs over — they **must** match the on-chain token's
`name()` and domain version, or signature recovery on the facilitator
side fails.
With that registered, your agent config uses the friendly slug:
```python theme={null}
"execution_cost": {
"amount": "0.01",
"token": "USDC",
"network": "skale-europa", # Bindu translates to eip155:1187947933
"pay_to_address": "0xYourWallet",
},
```
Bindu translates these friendly names to CAIP-2 automatically:
| Slug | CAIP-2 |
| ------------------------------ | -------------------------------- |
| `base-sepolia` | `eip155:84532` |
| `base`, `base-mainnet` | `eip155:8453` |
| `ethereum`, `ethereum-mainnet` | `eip155:1` |
| `ethereum-sepolia` | `eip155:11155111` |
| *(operator-defined)* | from `extra_networks[...].caip2` |
Anything else gets passed through verbatim — useful if you already speak
CAIP-2.
***
## Configuration Reference
All settings live on `app_settings.x402` (env prefix `X402__`):
| Setting | Env var | Default | Purpose |
| --------------------- | --------------------------- | --------------------------------------------- | ------------------------------------------------- |
| `facilitator_url` | `X402__FACILITATOR_URL` | `https://x402.org/facilitator` | Where `/verify` and `/settle` are called. |
| `default_network` | `X402__DEFAULT_NETWORK` | `base-sepolia` | Used when `execution_cost.network` is missing. |
| `pay_to_env` | `X402__PAY_TO_ENV` | `X402_PAY_TO` | Env var name for the recipient wallet (fallback). |
| `max_timeout_seconds` | `X402__MAX_TIMEOUT_SECONDS` | `600` | Hard ceiling on authorization windows. |
| `extension_uri` | `X402__EXTENSION_URI` | `https://github.com/google-a2a/a2a-x402/v0.1` | A2A extension URI advertised on the agent card. |
| `protected_methods` | `X402__PROTECTED_METHODS` | `["message/send"]` | JSON-RPC methods that demand payment. |
| `extra_networks` | (Python only) | `{ "skale-europa": ... }` | Operator-supplied EVM chain registrations. |
Per-requirement `max_timeout_seconds` is hard-coded to **60** in
`_create_payment_requirements` — that's the EIP-3009 authorization window
Bindu advertises in the 402. `app_settings.x402.max_timeout_seconds` is the
outer ceiling, not the per-request value.
***
## Replay Protection
Without server-side dedupe, a caller who saw one valid payment could replay it within the `validBefore` window and get unlimited work for one payment. Bindu closes this by claiming `(network, asset, nonce)` in a nonce store **before** calling the facilitator:
| Backend | When | TTL |
| -------------------- | -------------------------------------- | ---------------------------------- |
| `InMemoryNonceStore` | No Redis configured | `max_timeout_seconds + 60s buffer` |
| `RedisNonceStore` | `app_settings.scheduler.redis_url` set | Same, via `SET NX EX` (atomic) |
A replayed payload returns `402 { "error": "Payment nonce already used (replay)" }` and **never** reaches the facilitator. The buffer (`NONCE_TTL_BUFFER_SECONDS = 60`) keeps the dedupe key alive a bit past the EIP-3009 `validBefore` so clock skew or a slow settlement doesn't free the slot prematurely.
In-memory dedupe is **per-process**. If you run multiple Bindu workers
behind a load balancer without Redis, a replay against a sibling worker
will not be caught. Configure
`app_settings.scheduler.redis_url` for any production multi-process
deployment.
***
## How the Middleware Decides
Pipeline on every request to the protected path (`/`, `POST`):
1. **Parse JSON-RPC body.** Unparseable → `402 { "error": "Malformed JSON-RPC body" }`. (A previous `except Exception` here let bad bodies fall through to the handler unpaid; that's fixed.)
2. **Method check.** If the method isn't in `protected_methods`, the request flows straight through unpaid.
3. **`X-PAYMENT` present?** Missing → 402.
4. **Decode + parse v2 payload.** Bad base64 or bad JSON → 402.
5. **Match a requirement.** No match → `402 { "error": "No matching payment requirements found" }`.
6. **Claim the nonce.** Already used → `402 { "error": "Payment nonce already used (replay)" }`. Store error → fail closed.
7. **Facilitator `/verify`.** `isValid: false` or exception → 402 with `Invalid payment: ` or `Payment verification failed`.
8. **Handler runs.** On task completion, the worker calls `/settle` and stamps the receipt onto task metadata.
Every step **fails closed**. There is no fall-through path that runs the handler on an error.
***
## Going to Production
Use `base-sepolia` and the Coinbase facilitator. Get testnet ETH from a
Base Sepolia faucet for gas; get testnet USDC from the Base Sepolia USDC
faucet. Run the full flow against your own agent until the happy path is
boring.
Change `"network": "base-sepolia"` to `"network": "base"`. Same code,
same wallet shape, same payload shape — real USDC on Base mainnet.
Set `app_settings.scheduler.redis_url`. Without it, replay protection is
per-process and breaks under horizontal scale.
A penny per call sounds reasonable until an LLM call costs you five
cents. Math out provider cost vs `amount` before you ship. Each new task
needs a new payment — a finished task doesn't grant credit to the next
one.
Every settled task has `metadata["x402.payment.receipts"]` attached.
That's your audit trail. Persist it. If you ever need to dispute or
reconcile, this is where you start.
***
## Calling a Paid Agent from Python
Once you've got a base64 `X-PAYMENT` (either signed yourself or fetched from `/api/payment-status/...`), the actual call is unremarkable:
```python theme={null}
import httpx, uuid
async def call_paid_agent(payment_token: str, prompt: str) -> dict:
body = {
"jsonrpc": "2.0",
"method": "message/send",
"id": str(uuid.uuid4()),
"params": {
"configuration": {"accepted_output_modes": ["text"]},
"message": {
"role": "user",
"kind": "message",
"parts": [{"kind": "text", "text": prompt}],
"messageId": str(uuid.uuid4()),
"contextId": str(uuid.uuid4()),
"taskId": str(uuid.uuid4()),
},
},
}
async with httpx.AsyncClient() as client:
r = await client.post(
"http://localhost:3773/",
headers={"X-PAYMENT": payment_token, "Content-Type": "application/json"},
json=body,
)
return r.json()
```
For a complete signing example targeting Base Sepolia, see the `hermes_agent` example in the Bindu repo — same EIP-3009 flow works on any EVM chain.
***
## Troubleshooting
The `X-PAYMENT` header is missing, malformed, or doesn't match any
advertised requirement. The 402 body tells you exactly which (`error`
field).
The facilitator's `/verify` raised or returned `isValid: false`. Either
the signature is wrong, the chain is wrong, or the facilitator doesn't
know the chain you asked for. Check the agent's server logs for the
facilitator's `invalid_reason`.
Caller is sending the same authorization twice. They need to sign a
fresh one with a new nonce for every request.
The `accepted` block in the payload doesn't match anything in your
`execution_cost`. Usually a network or asset address mismatch — confirm
the caller signed for the same `network` and `asset` you advertised.
The caller's library is producing v1 payloads. v2 verification on the
Bindu side rejects them; re-sign with a v2 client.
***
## Related
* [x402 Protocol](https://github.com/coinbase/x402) — the open standard everything here is built on.
* [Base documentation](https://docs.base.org/network-information) — what you'll be paying on by default.
* [Decentralized Identifiers (DIDs)](/bindu/learn/did/overview) — pair payment with peer identity for end-to-end accountability.
Bindu allows agents to bloom independently —
turning trust into verifiable value,
and bringing light to the Internet of Agents.
# Retry Mechanism
Source: https://docs.getbindu.com/bindu/learn/retry/overview
Tenacity-based retry with exponential backoff (and optional jitter) for resilient Bindu agents
Things fail in production for ordinary reasons. A database connection drops. Redis goes away for a moment. An API times out. Most of those failures are transient. If the system treats every one of them as final, tasks fail for no good reason and recovering services get hammered the instant they come back.
Bindu wraps every brittle boundary — workers, storage, scheduler, outbound HTTP — in a small set of Tenacity decorators that retry transient errors with exponential backoff and reraise everything else immediately.
## Why Retry Matters
| Without retry | With Bindu retry |
| -------------------------------------------------------------- | ------------------------------------------------------------------------ |
| Temporary failures surface as immediate task failures | Transient errors recover automatically before users see them |
| Recovering services get a thundering herd | Per-attempt backoff (with jitter on three of four families) spreads load |
| Worker, storage, scheduler, and HTTP each need custom handling | Four named decorators wrap the same Tenacity machinery |
| Logic bugs and transient errors are retried indistinguishably | Only a narrow allowlist of transient exceptions is retried |
| Tuning behaviour requires code changes | `RETRY__*` env vars override every default |
## How Bindu Retry Works
All four decorators are thin wrappers around a single factory, `create_retry_decorator(operation_type, ...)`, defined in `bindu/utils/retry.py`. The factory:
1. Looks up the family's defaults on `app_settings.retry` (or honours your override).
2. Picks a wait strategy — `wait_random_exponential` (jitter) or `wait_exponential` (no jitter).
3. Builds an `AsyncRetrying` loop that retries only on `TRANSIENT_EXCEPTIONS`.
4. Logs at `WARNING` before each sleep (via `before_sleep_log`) and at `INFO` after each attempt (via `after_log`).
5. Reraises the original exception once attempts are exhausted (`reraise=True`).
Only **transient** exceptions are retried. Application errors like `ValueError` or `KeyError` raise on the first attempt — they are not in the retry list.
### The Lifecycle: Fail, Wait, Try Again
```mermaid theme={null}
sequenceDiagram
participant App as Caller
participant Dec as Decorator wrapper
participant Tn as AsyncRetrying (Tenacity)
participant Op as Wrapped function
App->>Dec: await wrapped(*args)
Dec->>Tn: enter retry loop (stop=stop_after_attempt(N))
loop attempt 1..N
Tn->>Op: invoke
alt Success
Op-->>Tn: return value
Tn-->>Dec: stop, return
Dec-->>App: result
else Transient exception
Op-->>Tn: raise ConnectionError / TimeoutError / OSError
Tn->>Tn: before_sleep_log(WARNING)
Tn->>Tn: wait = exponential([+jitter])
Tn->>Tn: after_log(INFO)
else Non-transient (e.g. ValueError)
Op-->>Tn: raise
Tn-->>Dec: reraise immediately (no retry)
Dec-->>App: raises
end
end
Tn-->>Dec: attempts exhausted -> reraise last exception
Dec-->>App: raises
```
### What Counts As Transient
The allowlist lives in `bindu/utils/retry.py` as `TRANSIENT_EXCEPTIONS`:
```python theme={null}
TRANSIENT_EXCEPTIONS = (
ConnectionError,
ConnectionRefusedError,
ConnectionResetError,
ConnectionAbortedError,
TimeoutError,
asyncio.TimeoutError,
OSError, # covers BrokenPipeError and friends
)
```
A second tuple, `HTTP_RETRYABLE_EXCEPTIONS`, extends this with `HTTPConnectionError`, `HTTPTimeoutError`, and `HTTPServerError` (5xx). It is defined for HTTP callers but the four headline decorators currently all use `TRANSIENT_EXCEPTIONS`.
Subclasses count: any custom exception that inherits from `ConnectionError`, `TimeoutError`, or `OSError` is retried automatically.
### Backoff: Plain vs. Jittered
Bindu picks between two Tenacity wait strategies per family:
```python theme={null}
wait_strategy = (
wait_random_exponential(multiplier=1, min=_min_wait, max=_max_wait)
if use_jitter
else wait_exponential(multiplier=1, min=_min_wait, max=_max_wait)
)
```
* `wait_exponential` doubles the wait each attempt, clamped to `[min_wait, max_wait]`. Deterministic. Used for **storage**.
* `wait_random_exponential` samples uniformly in `[0, min(max_wait, multiplier * 2^attempt)]`. Spreads retries to avoid thundering herds. Used for **worker**, **scheduler**, and **api**.
Storage is intentionally jitter-free: a single process serialises its own retries, and deterministic backoff is easier to reason about against a local in-memory store. Anything that talks over the network gets jitter so that N pods don't all retry at the same instant.
***
## The Four Decorator Families
Wraps `ManifestWorker` task execution. Default 3 attempts, 1.0–10.0 s, jittered. Used in `bindu/server/workers/manifest_worker.py` on `run_task` and `cancel_task`.
Wraps storage CRUD on the in-memory backend. Default 5 attempts, 0.5–5.0 s, **no jitter**. Used in `bindu/server/storage/memory_storage.py` on `load_task`, `submit_task`, `update_task`.
Wraps scheduler enqueue calls. Default 3 attempts, 1.0–8.0 s, jittered. Used in `bindu/server/scheduler/memory_scheduler.py` and `bindu/server/scheduler/redis_scheduler.py` on `run_task`, `cancel_task`, `pause_task`, `resume_task`.
Wraps outbound HTTP. Default 4 attempts, 1.0–15.0 s, jittered. Used via `create_retry_decorator("api")` on the HTTP client in `bindu/utils/http/client.py` (`get`, `post`, `put`, `delete`, `request`) and on push delivery in `bindu/utils/notifications.py` (`_post_with_retry`).
All four call into the same `create_retry_decorator(operation_type, ...)` factory. They exist as named convenience wrappers for grep-ability and for backward compatibility — calling `create_retry_decorator("api")` is exactly equivalent to `retry_api_call()`.
### Why four decorators, not one?
The split is operational, not technical:
* **Storage** retries should be many and fast — a flaky local connection deserves five 0.5–5 s pokes, not three 10 s sulks. Storage runs in-process, so jitter buys you nothing.
* **API** retries should be fewer and longer — remote services need room to breathe, and jitter prevents pods from synchronising.
* **Worker** retries cover task execution and should be conservative; retrying agent logic too aggressively masks real bugs.
* **Scheduler** retries cover broker hand-off, where the failure mode is "Redis briefly unavailable" — short attempts, modest wait.
Each family has its own env knobs so you can tune them independently without rebuilding the image.
***
## Defaults and Configuration
### Family Defaults
Defined in `RetrySettings` (`bindu/settings.py`):
| Family | `max_attempts` | `min_wait` | `max_wait` | Jitter |
| --------- | -------------- | ---------- | ---------- | ------ |
| worker | 3 | 1.0 s | 10.0 s | yes |
| storage | 5 | 0.5 s | 5.0 s | **no** |
| scheduler | 3 | 1.0 s | 8.0 s | yes |
| api | 4 | 1.0 s | 15.0 s | yes |
### Environment Variables
`RetrySettings` lives under the top-level `Settings` model, which uses `env_nested_delimiter="__"`. The variable name is `RETRY__`:
```bash theme={null}
# Worker
RETRY__WORKER_MAX_ATTEMPTS=3
RETRY__WORKER_MIN_WAIT=1.0
RETRY__WORKER_MAX_WAIT=10.0
# Storage
RETRY__STORAGE_MAX_ATTEMPTS=5
RETRY__STORAGE_MIN_WAIT=0.5
RETRY__STORAGE_MAX_WAIT=5.0
# Scheduler
RETRY__SCHEDULER_MAX_ATTEMPTS=3
RETRY__SCHEDULER_MIN_WAIT=1.0
RETRY__SCHEDULER_MAX_WAIT=8.0
# External API
RETRY__API_MAX_ATTEMPTS=4
RETRY__API_MIN_WAIT=1.0
RETRY__API_MAX_WAIT=15.0
```
Per-call overrides on the decorator (`@retry_storage_operation(max_attempts=10)`) win over env vars, which win over the defaults baked into `RetrySettings`. The `or` fallback inside `create_retry_decorator` means an override of `0` or `None` falls back to settings — pass a real positive value.
***
## Decorator Reference
**Family**: `worker` · **Jitter**: yes · **Defaults**: 3 attempts, 1.0–10.0 s
Wraps task execution on `ManifestWorker`. Failures during `manifest.run(...)` only retry when they bubble up as `ConnectionError`/`TimeoutError`/`OSError`. Agent-side `ValueError` or `RuntimeError` is **not** retried — the worker catches it, marks the task `failed`, and reraises.
Real call sites (`bindu/server/workers/manifest_worker.py`):
```python theme={null}
@retry_worker_operation() # line 96
async def run_task(self, params: TaskSendParams) -> None: ...
@retry_worker_operation(max_attempts=2) # line 232
async def cancel_task(self, params: TaskIdParams) -> None: ...
```
`cancel_task` deliberately caps at 2 attempts: a cancel that fails twice is not going to start working on attempt three.
**Family**: `storage` · **Jitter**: **no** (`wait_exponential`) · **Defaults**: 5 attempts, 0.5–5.0 s
Wraps storage CRUD on `InMemoryStorage`. The implementation overrides per-call to a tighter budget tuned for in-process memory:
`bindu/server/storage/memory_storage.py` (lines 41–44):
```python theme={null}
DEFAULT_STORAGE_RETRY_ATTEMPTS = 3
DEFAULT_STORAGE_MIN_WAIT = 0.1
DEFAULT_STORAGE_MAX_WAIT = 1.0
```
Applied at lines 71, 103, 242:
```python theme={null}
@retry_storage_operation(
max_attempts=DEFAULT_STORAGE_RETRY_ATTEMPTS,
min_wait=DEFAULT_STORAGE_MIN_WAIT,
max_wait=DEFAULT_STORAGE_MAX_WAIT,
)
async def load_task(self, task_id, history_length=None) -> Task | None: ...
```
Same decorator covers `submit_task` and `update_task`.
The Postgres storage backend does **not** use `@retry_storage_operation`. It calls `execute_with_retry` directly via its own `_retry_on_connection_error` helper (`bindu/server/storage/postgres_storage.py` line 243), keyed off `storage.postgres_max_retries` and `storage.postgres_retry_delay` from `StorageSettings`. So the `RETRY__STORAGE_*` env vars affect the in-memory backend and any code that uses the decorator directly — they do not retune Postgres.
**Family**: `scheduler` · **Jitter**: yes · **Defaults**: 3 attempts, 1.0–8.0 s
Wraps the four enqueue operations on both scheduler backends.
`bindu/server/scheduler/redis_scheduler.py` (lines 114, 124, 134, 144):
```python theme={null}
@retry_scheduler_operation()
async def run_task(self, params: TaskSendParams) -> None: ...
@retry_scheduler_operation()
async def cancel_task(self, params: TaskIdParams) -> None: ...
@retry_scheduler_operation()
async def pause_task(self, params: TaskIdParams) -> None: ...
@retry_scheduler_operation()
async def resume_task(self, params: TaskIdParams) -> None: ...
```
`bindu/server/scheduler/memory_scheduler.py` (lines 73, 83, 93, 103) overrides defaults for its anyio stream — tight 0.1–1.0 s window across 3 attempts:
```python theme={null}
DEFAULT_RETRY_ATTEMPTS = 3
DEFAULT_RETRY_MIN_WAIT = 0.1
DEFAULT_RETRY_MAX_WAIT = 1.0
@retry_scheduler_operation(
max_attempts=DEFAULT_RETRY_ATTEMPTS,
min_wait=DEFAULT_RETRY_MIN_WAIT,
max_wait=DEFAULT_RETRY_MAX_WAIT,
)
async def run_task(self, params: TaskSendParams) -> None: ...
```
**Family**: `api` · **Jitter**: yes · **Defaults**: 4 attempts, 1.0–15.0 s
The headline name. Internally, Bindu's HTTP client and push notifier reach for the factory directly so they can mix in extra parameters.
`bindu/utils/http/client.py` (lines 195, 219, 245, 271, 291):
```python theme={null}
@create_retry_decorator("api")
async def get(self, endpoint, *, params=None, headers=None, **kwargs): ...
@create_retry_decorator("api")
async def post(self, endpoint, *, data=None, json=None, headers=None, **kwargs): ...
```
`bindu/utils/notifications.py` (line 125) — push delivery uses a tighter override:
```python theme={null}
@create_retry_decorator("api", max_attempts=3, min_wait=0.5, max_wait=5.0)
async def _post_with_retry(self, url, resolved_ip, headers, payload, event): ...
```
Push delivery additionally short-circuits the retry for 4xx (except 429) inside the wrapped body — the decorator only sees the exceptions you let escape.
***
## Inside an Attempt
`AsyncRetrying` enters its loop with `stop=stop_after_attempt(N)`, `wait=`, `retry=retry_if_exception_type(TRANSIENT_EXCEPTIONS)`, `reraise=True`. A `debug` log records the attempt number.
The `with attempt:` block records success; the `async for` exits and the wrapper returns the value.
Anything outside `TRANSIENT_EXCEPTIONS` (e.g. `ValueError`) skips the retry-decision path and propagates immediately. There is no backoff and no further attempt.
`before_sleep_log(logger, WARNING)` writes a warning. The wait strategy computes the next sleep — `min(max_wait, multiplier * 2^attempt)` either deterministic (storage) or sampled uniformly (everyone else). `after_log(logger, INFO)` records the attempt outcome.
Once `stop_after_attempt` trips, `reraise=True` means the **original** exception is raised — not a `RetryError`. Callers see the underlying `ConnectionError` and can catch it normally.
***
## Examples
### Custom decorator usage
```python theme={null}
from bindu.utils.retry import (
retry_worker_operation,
retry_storage_operation,
retry_api_call,
)
@retry_worker_operation(max_attempts=2)
async def cancel_task(self, params): ...
@retry_storage_operation(max_attempts=10, min_wait=2.0)
async def slow_update(self, task_id, state): ...
@retry_api_call(max_attempts=6, max_wait=30.0)
async def call_llm(self, prompt: str) -> str: ...
```
### Ad-hoc retry (no decorator)
`execute_with_retry` is what `applications.py` uses to retry storage and scheduler construction at startup, and what `postgres_storage.py` uses for every query.
```python theme={null}
from bindu.utils.retry import execute_with_retry
result = await execute_with_retry(
fetch_remote_thing,
"task_id_123",
max_attempts=5,
min_wait=1.0,
max_wait=10.0,
)
```
It uses `wait_random_exponential` (jitter) and the same `TRANSIENT_EXCEPTIONS` allowlist.
### Env-var overrides for a noisy network
```bash theme={null}
# Network-flaky environment: more attempts, longer ceiling
RETRY__API_MAX_ATTEMPTS=6
RETRY__API_MIN_WAIT=2.0
RETRY__API_MAX_WAIT=30.0
# Local dev with reliable storage: keep retries snappy
RETRY__STORAGE_MAX_ATTEMPTS=3
RETRY__STORAGE_MIN_WAIT=0.1
RETRY__STORAGE_MAX_WAIT=1.0
```
### Make sure operations are idempotent
Anything wrapped by a retry decorator should be safe to run twice. Set-like operations are naturally idempotent:
```python theme={null}
@retry_storage_operation()
async def update_task_status(self, task_id: UUID, status: str) -> None:
await self.db.execute(
"UPDATE tasks SET status = :status WHERE task_id = :task_id",
{"status": status, "task_id": task_id},
)
```
### Distinguish transient from logic errors
```python theme={null}
@retry_api_call()
async def call_api(self, data: dict) -> dict:
response = await api_client.post("/endpoint", json=data)
if response.status_code == 400:
raise ValueError("Invalid request") # NOT retried - not in TRANSIENT_EXCEPTIONS
if response.status_code >= 500:
raise ConnectionError("Upstream 5xx") # retried
return response.json()
```
### Sample log output
A storage call that fails twice then succeeds (logger `bindu.utils.retry`):
```text theme={null}
[DEBUG] bindu.utils.retry Executing storage operation load_task (attempt 1/5)
[WARNING] bindu.utils.retry Retrying ... in 0.5 seconds as it raised ConnectionError: Database connection lost.
[INFO] bindu.utils.retry Finished call to 'load_task' after 0.512(s), this was the 1 time calling it.
[DEBUG] bindu.utils.retry Executing storage operation load_task (attempt 2/5)
[WARNING] bindu.utils.retry Retrying ... in 1.0 seconds as it raised ConnectionError: Database connection lost.
[INFO] bindu.utils.retry Finished call to 'load_task' after 1.013(s), this was the 2 time calling it.
[DEBUG] bindu.utils.retry Executing storage operation load_task (attempt 3/5)
[INFO] bindu.utils.retry Finished call to 'load_task' after 0.004(s), this was the 3 time calling it.
```
The `before_sleep_log` / `after_log` lines come from Tenacity directly; the `Executing ... operation` line comes from the wrapper inside `create_retry_decorator`.
***
## Troubleshooting
**Retries are taking too long.** Lower `max_attempts` and/or `max_wait`:
```bash theme={null}
RETRY__WORKER_MAX_ATTEMPTS=2
RETRY__WORKER_MAX_WAIT=5.0
```
**An operation never retries.** The exception is not in `TRANSIENT_EXCEPTIONS`. Either subclass `ConnectionError`/`TimeoutError`/`OSError` in your own exception, or wrap it before raising:
```python theme={null}
try:
await flaky_call()
except SomeLibraryError as e:
raise ConnectionError(str(e)) from e
```
**Retries hide a real bug.** A logic error wrapped as `ConnectionError` will be retried N times before failing — exactly what you don't want. Keep `TRANSIENT_EXCEPTIONS` narrow and raise application errors as `ValueError`/`RuntimeError` so they fail fast.
**Postgres retries don't respond to `RETRY__STORAGE_*`.** Correct — Postgres uses `storage.postgres_max_retries` / `storage.postgres_retry_delay` from `StorageSettings`, not `RetrySettings`.
***
## Testing
```python theme={null}
import pytest
from bindu.utils.retry import retry_worker_operation
@pytest.mark.asyncio
async def test_retry_success_after_failure():
attempts = 0
@retry_worker_operation(max_attempts=3, min_wait=0.01, max_wait=0.05)
async def flaky():
nonlocal attempts
attempts += 1
if attempts < 3:
raise ConnectionError("transient")
return "ok"
assert await flaky() == "ok"
assert attempts == 3
```
```bash theme={null}
uv run pytest tests/unit/test_retry.py -v
```
***
## Related
* [Storage](/bindu/learn/storage/overview) — backend that exposes the in-memory `@retry_storage_operation` calls and the Postgres `_retry_on_connection_error` helper.
* [Scheduler](/bindu/learn/scheduler/overview) — Redis and in-memory schedulers whose enqueue paths are retry-wrapped.
* [Notifications](/bindu/learn/notification/overview) — push delivery uses `@create_retry_decorator("api", ...)` with its own tighter budget.
* [Observability](/bindu/learn/observability/overview) — every retry attempt is logged via the `bindu.utils.retry` logger and surfaced through your existing log pipeline.
Bindu treats transient failures as
something to recover from, not something to fear
so agents stay resilient when networks, databases, and APIs stumble.
# Scheduler
Source: https://docs.getbindu.com/bindu/learn/scheduler/overview
The queue between an HTTP request and the actual work — so two callers don't stall each other, and a crash doesn't take your inbox with it.
Two requests hit your agent at the same time. Both want a 30-second answer. Without a scheduler, the second caller waits 30s for the first to finish, then 30s more for their own. A single-threaded agent is a queue of one — and queues of one are how production starts melting.
The scheduler sits between the `TaskManager` (your HTTP layer) and the `ManifestWorker` (your handler runner). Submission is non-blocking: the caller gets a `task_id` immediately and goes away. The worker pulls operations off the queue and executes them. Storage holds the heavy state; the queue stays lean.
In-memory for local dev. Redis for production. Same `bindufy(config, handler)` either way — you flip one or two environment variables.
Single process and don't care about restart survival? `SCHEDULER_TYPE=memory` is
the default, no setup needed. Multiple processes, horizontal scaling, or
durable queueing required? `SCHEDULER_TYPE=redis` + `REDIS_URL` and you're done.
## What the scheduler actually schedules
Not raw functions. Not HTTP requests. The scheduler queues **task operations** — small typed envelopes that tell the worker what to do with a `task_id` whose data already lives in storage.
```python theme={null}
# bindu/server/scheduler/base.py
TaskOperation = _RunTask | _CancelTask | _PauseTask | _ResumeTask
# "run" "cancel" "pause" "resume"
```
Four operations, one discriminator field. The queue holds operation envelopes; storage holds the task body. Workers pop an operation, load the task from storage, execute the handler, and write the result back. Two systems, one task — clean separation.
`run_task()` returns as soon as the operation lands on the queue. The HTTP
response carries the `task_id`, not the answer.
Multiple workers (or multiple agent processes, with Redis) pop from the same
queue. Redis guarantees each operation is delivered to exactly one worker.
The in-memory queue is bounded (100 ops). If producers outrun the worker, the
sender awaits — you get backpressure instead of unbounded memory growth.
***
## Backends at a glance
| | `memory` | `redis` |
| ---------------- | ------------------------------------------- | ----------------------------------------------------- |
| Selected by | `SCHEDULER_TYPE=memory` (default) | `SCHEDULER_TYPE=redis` |
| Transport | `anyio` memory object stream (buffer = 100) | Redis `LIST` (`RPUSH` / `BLPOP`) |
| Cross-process | No — single Python process only | Yes — many processes, many hosts |
| Restart survival | Lost on process exit | Pending ops survive; in-flight do not (see note) |
| Trace context | Live OpenTelemetry `Span` reference | Serialized `trace_id` / `span_id` |
| Extra deps | None | `redis[hiredis]` and a running Redis |
| Best for | Local dev, single-replica deploys, tests | Production, horizontal scaling, restart-safe queueing |
**Delivery semantics are at-least-once-on-enqueue, not exactly-once-on-execute.**
`BLPOP` atomically removes the operation from the queue before the worker
starts executing. If the worker crashes mid-handler, the operation is gone — the
task body is still in storage (state = `working`), but no one will retry it
unless you restart it explicitly. There is no visibility-timeout or
redelivery layer. For execution-level resilience, see [Retry](/bindu/learn/retry/overview).
***
## The dispatch flow
```mermaid theme={null}
sequenceDiagram
participant Client
participant TaskManager
participant Scheduler
participant Worker as ManifestWorker
participant Storage
Note over TaskManager,Worker: At startup
TaskManager->>Scheduler: create_scheduler(config)
TaskManager->>Worker: spawn loop
Worker->>Scheduler: async for op in receive_task_operations()
Note over Client,Storage: Per-request
Client->>TaskManager: message/send
TaskManager->>Storage: save Task (state = submitted)
TaskManager->>Scheduler: run_task(params)
alt memory backend
Scheduler->>Scheduler: write_stream.send(_RunTask)
else redis backend
Scheduler->>Scheduler: RPUSH bindu:tasks
end
TaskManager-->>Client: { task_id } (immediate)
alt memory backend
Scheduler-->>Worker: read_stream yields op
else redis backend
Scheduler-->>Worker: BLPOP returns op
end
Worker->>Storage: update state = working
Worker->>Worker: execute handler
Worker->>Storage: write artifact, state = completed | failed
Client->>TaskManager: tasks/get { task_id }
TaskManager->>Storage: load task + artifact
TaskManager-->>Client: result
```
Submission and execution never touch each other on the call stack. The HTTP request ends the moment the operation is on the queue.
***
## Backends
`InMemoryScheduler`. `anyio` memory object stream, bounded buffer of 100,
zero external dependencies. The default.
`RedisScheduler`. Redis list with `RPUSH` + `BLPOP`, connection pool of 10,
default queue key `bindu:tasks`.
### In-memory backend
```python theme={null}
# bindu/server/scheduler/memory_scheduler.py
self._write_stream, self._read_stream = anyio.create_memory_object_stream[
TaskOperation
](100)
```
A producer (`TaskManager`) and a consumer (`ManifestWorker`) share an `anyio` memory object stream. The stream is **bounded at 100 operations** — once full, `run_task()` awaits until the worker drains it. That's intentional: an unbounded queue would let a runaway producer eat the process's RAM.
Trace context is preserved by stashing a live OpenTelemetry `Span` reference directly in the operation envelope (`_current_span`). Cheap and exact, but only works inside one process — which is fine, since this backend is one process by definition.
### Redis backend
```python theme={null}
# bindu/server/scheduler/redis_scheduler.py
await self._redis_client.rpush(self.queue_name, serialized_task) # producer
result = await self._redis_client.blpop([self.queue_name], timeout=self.poll_timeout) # consumer
```
A plain Redis `LIST` (not a Stream, not a Sorted Set) keyed at `bindu:tasks` by default. Producers `RPUSH` JSON-serialized operations to the tail; consumers `BLPOP` from the head, blocking up to `poll_timeout` seconds (default `1s`) before retrying. Atomic on the Redis side — one operation, one worker.
Because operations cross process boundaries, the live `Span` from the in-memory case won't survive serialization. The Redis scheduler instead writes `trace_id` / `span_id` into the envelope so the worker can reconstruct a child span on the other side.
The connection pool is sized at `max_connections=10`, with `retry_on_timeout=True`. If Redis goes briefly unreachable mid-`BLPOP`, the receive loop logs and backs off **1 second** before retrying — no tight CPU loop. Producer-side, every `run_task` / `cancel_task` / `pause_task` / `resume_task` call is wrapped in `@retry_scheduler_operation` (Tenacity), so a transient blip won't drop your enqueue.
***
## Configuration
The scheduler reads from `SchedulerSettings` (Pydantic `BaseSettings`) in `bindu/settings.py`. Environment variables override defaults. The factory builds a `SchedulerConfig` from settings if you don't pass one.
Nothing is required. `SCHEDULER_TYPE=memory` is the default.
```bash theme={null}
# Optional — explicit is fine
SCHEDULER_TYPE=memory
```
No URL, no pool, no queue name. The buffer (100) is a code-level constant — change it by subclassing `InMemoryScheduler` if you really need to.
```bash theme={null}
SCHEDULER_TYPE=redis
# Pick ONE of: a full URL, or host+port (+ optional auth)
REDIS_URL=redis://localhost:6379/0
# or
REDIS_URL=rediss://default:****@redis-12345.upstash.io:6379
# Optional tuning
REDIS_POLL_TIMEOUT=1 # seconds; how long BLPOP blocks before re-polling
```
These are the env-var-mapped fields on `SchedulerSettings`:
| Field | Env var | Default |
| ------------------ | -------------------- | ------------- |
| `backend` | `SCHEDULER_TYPE` | `memory` |
| `redis_url` | `REDIS_URL` | `None` |
| `poll_timeout` | `REDIS_POLL_TIMEOUT` | `1` |
| `queue_name` | — | `bindu:tasks` |
| `max_connections` | — | `10` |
| `retry_on_timeout` | — | `true` |
`redis_host`, `redis_port`, `redis_password`, `redis_db` are also accepted on
the dataclass — the factory will assemble a URL from them if `REDIS_URL` is
not provided. Prefer the URL form; it's less error-prone.
Scheduler enqueue/cancel calls are wrapped with `@retry_scheduler_operation`.
Defaults from `RetrySettings`:
```python theme={null}
scheduler_max_attempts = 3
scheduler_min_wait = 1.0 # seconds
scheduler_max_wait = 8.0 # seconds
```
These cover transient producer-side failures (e.g. brief Redis disconnect during
`RPUSH`). They do **not** retry the agent handler — that's the worker's job, see
[Retry](/bindu/learn/retry/overview).
***
## Setup
`SCHEDULER_TYPE` is unset, so the factory returns `InMemoryScheduler`. Run
`uv run python main.py` and you're scheduled.
Start Redis locally (Docker is fine):
```bash theme={null}
docker run -d --name bindu-redis -p 6379:6379 redis:7-alpine
```
Set two env vars and restart:
```bash theme={null}
export SCHEDULER_TYPE=redis
export REDIS_URL=redis://localhost:6379/0
```
On boot you'll see `Redis scheduler connected to redis://localhost:6379/0`.
The factory does a `PING` first — if Redis is unreachable, startup fails
loudly instead of silently degrading.
Point a second process at the same Redis:
```bash theme={null}
# Instance A
SCHEDULER_TYPE=redis REDIS_URL=redis://redis:6379/0 uv run python main.py
# Instance B — same Redis, same queue
SCHEDULER_TYPE=redis REDIS_URL=redis://redis:6379/0 uv run python main.py
```
Both processes call `BLPOP` against `bindu:tasks`. Redis hands each operation
to exactly one waiter. No coordination code from you.
`export SCHEDULER_TYPE=memory` (or unset) and restart. Any operations sitting
in Redis stay in Redis — they're not processed by the in-memory backend.
Flush them with `RedisScheduler.clear_queue()` or `redis-cli DEL bindu:tasks`
if you don't want them resurrected next time you flip back.
***
## Choosing a backend
* You're developing locally and want zero setup.
* You're running a single process and don't need restart survival.
* You're writing tests — the in-memory backend is deterministic and fast.
* You don't care if a process crash drops a few pending submits.
* You run more than one agent process (multiple replicas, blue/green, autoscale).
* You need pending submissions to survive a restart or redeploy.
* You want to observe queue depth from outside the agent (`LLEN bindu:tasks`).
* You're already running Redis for storage or rate-limiting and want to consolidate.
**Memory backend:** nothing. The stream lives in the process; both the queue
and any in-flight handler die together. Storage state is still consistent
(the task row will show `submitted` or `working` forever until you clean it).
**Redis backend:** pending ops in `bindu:tasks` survive — when a new worker
starts, it `BLPOP`s them. In-flight ops (already popped, handler running)
are *not* recovered. The task body remains in storage; you can re-enqueue it
yourself, but the scheduler will not.
***
## Programmatic factory
Most agents don't need this — env vars are enough. But the factory is callable directly if you're embedding Bindu or writing tests:
```python theme={null}
from bindu.common.models import SchedulerConfig
from bindu.server.scheduler.factory import create_scheduler, close_scheduler
# Explicit Redis config
scheduler = await create_scheduler(SchedulerConfig(
type="redis",
redis_url="redis://localhost:6379/0",
queue_name="bindu:tasks",
max_connections=10,
poll_timeout=1,
))
async with scheduler: # opens Redis pool, pings on entry
await scheduler.run_task(params)
# ...
await close_scheduler(scheduler) # idempotent; safe on either backend
# Or: pass None to use app_settings defaults
scheduler = await create_scheduler(None)
```
The factory imports `RedisScheduler` lazily inside a `try/except ImportError`. If you don't have `redis` installed and you ask for `type="redis"`, you get a clear `ValueError: Redis scheduler requires redis package. Install with: pip install redis[hiredis]` — not an obscure import crash on startup.
***
## Observability and debug helpers
The Redis backend exposes a few helpers that are handy in ops:
```python theme={null}
await scheduler.health_check() # bool — PING-based readiness probe
await scheduler.get_queue_length() # int — LLEN bindu:tasks
await scheduler.clear_queue() # int — DEL bindu:tasks, returns count
```
For a quick external check without going through Python:
```bash theme={null}
redis-cli LLEN bindu:tasks # depth
redis-cli LRANGE bindu:tasks 0 4 # peek at the first 5 envelopes (JSON)
redis-cli DEL bindu:tasks # drain
```
Tracing crosses the boundary too: every operation carries `trace_id` / `span_id` (Redis) or a live `Span` (memory), so worker spans link back to the HTTP submit span in your OTLP backend. See [Observability](/bindu/learn/observability/overview).
***
## Operational notes
`REDIS_URL` belongs in `.env` (dev) or your orchestrator's secret manager
(prod). Don't bake connection strings into the `config` dict you pass to
`bindufy()` — that ends up in git.
If your Redis isn't on `localhost` or a private network, use `rediss://`
(TLS) and a password. Upstash, ElastiCache-in-transit-encryption, and
Redis Cloud all support it.
The default `1s` is a good tradeoff. Lower values reduce task-start latency
but increase Redis command rate. Higher values are cheaper on managed Redis
with command-based pricing.
A popped operation is gone from the queue. If you need redelivery on crash,
wrap your handler in retry logic and persist intent before doing
irrecoverable side effects.
***
## Related
* [Retry](/bindu/learn/retry/overview) — execution-level retries inside the handler
* [Storage](/bindu/learn/storage/overview) — where the task body actually lives
* [Observability](/bindu/learn/observability/overview) — tracing the dispatch flow end-to-end
* [Architecture](/bindu/concepts/task-first-and-architecture) — how scheduler, storage, and worker fit together
The scheduler is what separates
receiving work from doing work
— so your agent can always say yes, even when it's busy.
# Storage
Source: https://docs.getbindu.com/bindu/learn/storage/overview
Where Bindu keeps tasks, contexts, artifacts, and webhook configs so a restart doesn't eat your work.
Picture this. Your agent is mid-task — a user asked it to summarize a 200-page document, it's been thinking for 90 seconds — and the process restarts. Maybe a deploy, maybe an OOM, doesn't matter. With in-memory storage, that task is gone. The user sees an error. The agent doesn't even know it was working on something.
That's the trap: an agent that holds state in process memory is a demo, not a service. The moment uptime matters, you need persistence — and the moment you run more than one replica, you need a store every replica can see.
Bindu defaults to in-memory because local laptops don't have a Postgres handy. Switch to Postgres by setting two env vars and the same handler code keeps running — tasks, contexts, artifacts, and webhook configs all land in a durable store you can query, replay, and audit.
`memory` is the default. The only other backend is `postgres`. There is no
SQLite or file-based backend. Pick via `STORAGE_TYPE` — no code change in your
handler.
## How Bindu Storage Works
Every backend implements the same abstract `Storage` interface in `bindu/server/storage/base.py`. The TaskManager, workers, and handlers call that interface; the backend behind it is chosen at startup by the factory.
```mermaid theme={null}
graph LR
Handler[Your Handler] --> TM[TaskManager]
TM --> Iface[Storage Interface
base.py]
Iface --> Mem[InMemoryStorage
dict in process]
Iface --> PG[PostgresStorage
SQLAlchemy + asyncpg]
PG --> DB[(PostgreSQL
JSONB tables)]
style Handler fill:#e1f5ff
style Iface fill:#fff4e1
style Mem fill:#d4f5e1
style PG fill:#ffd4e1
style DB fill:#fce8d4
```
### What gets stored
Bindu's storage layer persists four things — not three. The earlier model in the spec missed `webhook_configs`:
One row per task in `tasks`. State, message history, artifacts, metadata,
owner DID, timestamps.
One row per conversation in `contexts`. Shared message history that spans
multiple tasks, plus arbitrary `context_data`.
Optional ratings and comments per task in `task_feedback`. One task can
have many feedback rows.
One push-notification config per task in `webhook_configs`. Survives
restarts so long-running tasks can still call back.
Artifacts are not a separate table — they live inside `tasks.artifacts` as a JSONB array on the task row.
### Backends at a glance
| | Memory | PostgreSQL |
| ---------------- | ------------------------------------ | -------------------------------------------------------- |
| Class | `InMemoryStorage` | `PostgresStorage` |
| Storage | Python `dict`s in process | JSONB tables via SQLAlchemy async + asyncpg |
| Persistence | Lost on restart | Survives restarts |
| Replicas | One process only | Many replicas share one DB |
| Concurrency | Single event loop | Connection pool (`pool_min=2`, `pool_max=10` by default) |
| Migrations | None | Alembic (manual or auto on startup) |
| Retries | `@retry_storage_operation` decorator | Tenacity wrapper on every call |
| Compare-and-swap | No `await` between read and write | Single `UPDATE ... WHERE state = :from` |
| Setup | None | Requires a running Postgres |
| `STORAGE_TYPE` | `memory` | `postgres` |
Both backends honour `OwnershipError` and `caller_did` checks the same way.
The protocol surface is identical — the only differences are durability,
concurrency, and operational cost.
***
## Configuration
Storage is configured purely from environment variables. Credentials don't belong in a Python `config` dict that ends up in git.
### Memory (default)
```bash theme={null}
# Default — no env vars needed. Just run your agent.
STORAGE_TYPE=memory
```
Tasks, contexts, feedback, and webhook configs live in a `dict` keyed by UUID. Gone when the process stops. Fine for `uv run agent.py` while you're building, useless beyond one replica.
### PostgreSQL
```bash theme={null}
STORAGE_TYPE=postgres
DATABASE_URL=postgresql+asyncpg://bindu_user:secret@localhost:5432/bindu_db
```
`DATABASE_URL` is the canonical name (`postgres_url` also works). Internally, if you pass a bare `postgresql://` URL, Bindu rewrites it to `postgresql+asyncpg://` so the async driver is used — but it's cleaner to write it correctly up front.
| Variable | Default | Meaning |
| ------------------------------------ | -------- | -------------------------------------------------------------------- |
| `STORAGE_TYPE` | `memory` | `memory` or `postgres`. |
| `DATABASE_URL` | *none* | Full async DSN. Required when `STORAGE_TYPE=postgres`. |
| `STORAGE__POSTGRES_POOL_MIN` | `2` | Minimum pooled connections (advisory). |
| `STORAGE__POSTGRES_POOL_MAX` | `10` | Max pool size. Passed to SQLAlchemy `pool_size`. |
| `STORAGE__POSTGRES_TIMEOUT` | `60` | Pool-checkout timeout in seconds. |
| `STORAGE__POSTGRES_COMMAND_TIMEOUT` | `30` | Per-command timeout. |
| `STORAGE__POSTGRES_MAX_RETRIES` | `3` | Retry attempts for transient errors. |
| `STORAGE__POSTGRES_RETRY_DELAY` | `1.0` | Base delay between retries (seconds). |
| `STORAGE__RUN_MIGRATIONS_ON_STARTUP` | `false` | Run Alembic `upgrade head` on connect. |
| `DID` / `POSTGRES_DID` | *none* | If set, isolates this agent's tables into a per-DID Postgres schema. |
`run_migrations_on_startup` defaults to **false** — the spec previously
suggested tables are created on first run, but in current code production
deployments run Alembic explicitly. Turn it on locally if you want
zero-touch bootstrap.
***
## The Storage Interface
Everything goes through `Storage` in `bindu/server/storage/base.py`. The methods your handler ends up exercising:
```python theme={null}
# Tasks
async def submit_task(context_id, message, caller_did=None) -> Task
async def load_task(task_id, history_length=None) -> Task | None
async def update_task(task_id, state, new_artifacts=None,
new_messages=None, metadata=None) -> Task
async def update_task_state_if(task_id, from_state, to_state) -> bool # CAS
async def list_tasks(length=None, offset=0, owner_did=None) -> list[Task]
async def list_tasks_by_context(context_id, length=None, offset=0,
owner_did=None) -> list[Task]
async def count_tasks(status=None) -> int
# Contexts
async def load_context(context_id) -> ContextT | None
async def append_to_contexts(context_id, messages) -> None
async def update_context(context_id, context) -> None
async def list_contexts(length=None, offset=0, owner_did=None) -> list[ContextT]
# Webhooks (persisted per task for long-running callbacks)
async def save_webhook_config(task_id, config) -> None
async def load_webhook_config(task_id) -> PushNotificationConfig | None
async def delete_webhook_config(task_id) -> None
async def load_all_webhook_configs() -> dict[UUID, PushNotificationConfig]
# Ownership / lifecycle
async def get_task_owner(task_id) -> str | None
async def get_context_owner(context_id) -> str | None
async def clear_context(context_id) -> None
async def clear_all() -> None
async def close() -> None
```
A few things worth calling out:
* **`update_task_state_if` is a compare-and-swap.** In Postgres it's a single `UPDATE ... WHERE state = :from`; in memory it's a comparison with no `await` between read and write. This is how cancel-vs-complete races stay correct.
* **`OwnershipError`** is raised by `submit_task` when a context already exists with a different `owner_did`. Handlers catch it and convert to `ContextNotFoundError` so they don't leak existence to the caller.
* **Terminal states are immutable.** `submit_task` on a task already in `completed`, `failed`, `canceled`, or `rejected` raises `ValueError` — you must create a new task with `reference_task_ids`.
### Using the factory
```python theme={null}
from bindu.server.storage.factory import create_storage, close_storage
storage = await create_storage() # reads STORAGE_TYPE from env
# or, with DID-based schema isolation:
storage = await create_storage(did="did:bindu:alice:agent1:abc123")
task = await storage.load_task(task_id)
# ... use storage ...
await close_storage(storage)
```
If `STORAGE_TYPE=postgres` and SQLAlchemy / asyncpg aren't installed, the factory raises a clear `ValueError` telling you to `pip install sqlalchemy[asyncio] asyncpg`.
***
## The Storage Lifecycle
```mermaid theme={null}
sequenceDiagram
participant Client
participant TM as TaskManager
participant S as Storage
participant W as Worker
participant A as Agent
Client->>TM: message/send
TM->>S: submit_task(context_id, message, caller_did)
S-->>TM: Task (state=submitted)
TM-->>Client: task_id
W->>S: load_task(task_id)
W->>S: update_task_state_if(task_id, submitted, working)
W->>A: execute
A-->>W: result + artifacts
W->>S: update_task(task_id, state=completed,
new_artifacts=[...], new_messages=[...])
W->>S: append_to_contexts(context_id, messages)
Client->>TM: tasks/get
TM->>S: load_task(task_id)
S-->>TM: Task (state=completed, history, artifacts)
TM-->>Client: full task
```
Every state transition is a write. If the process dies between `working` and `completed`, the row still exists in `submitted` or `working` — the scheduler can re-pick it up and the worker resumes from the last persisted state.
***
## The Postgres Schema
Defined in `bindu/server/storage/schema.py` via SQLAlchemy Core. Bindu uses **imperative mapping** — the protocol `TypedDict`s in `bindu/common/protocol/types.py` are the model; the schema module is just the table definition.
```text theme={null}
id UUID PRIMARY KEY
context_id UUID FK contexts(id) ON DELETE CASCADE
owner_did VARCHAR(255) NULL -- authenticated caller
kind VARCHAR(50) NOT NULL DEFAULT 'task'
state VARCHAR(50) NOT NULL -- submitted|working|...
state_timestamp TIMESTAMPTZ NOT NULL
history JSONB NOT NULL DEFAULT '[]'
artifacts JSONB NULL DEFAULT '[]'
metadata JSONB NULL DEFAULT '{}'
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ON UPDATE now()
```
Indexes: `context_id`, `state`, `created_at`, `updated_at`, `owner_did`,
and a GIN index on `metadata`.
```text theme={null}
id UUID PRIMARY KEY
owner_did VARCHAR(255) NULL -- write-once on first submit
context_data JSONB NOT NULL DEFAULT '{}'
message_history JSONB NULL DEFAULT '[]'
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ON UPDATE now()
```
Indexes: `created_at`, `updated_at`, `owner_did`, GIN on `context_data`.
```text theme={null}
id SERIAL PRIMARY KEY
task_id UUID FK tasks(id) ON DELETE CASCADE
feedback_data JSONB NOT NULL
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
```
Indexes: `task_id`, `created_at`.
```text theme={null}
task_id UUID PRIMARY KEY, FK tasks(id) ON DELETE CASCADE
config JSONB NOT NULL
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ON UPDATE now()
```
One config per task. Loaded into memory on startup so long-running tasks
can still call their callback after a restart.
A sample task row, decoded:
```json theme={null}
{
"id": "9b7f5e10-7b8d-4d4d-8c3d-6b6a4b8c1a99",
"context_id": "3f0e2c1a-1f4b-4f5b-8a2e-cdb8a9c3e7d1",
"owner_did": "did:bindu:alice:research-agent:abc123",
"kind": "task",
"state": "completed",
"state_timestamp": "2026-05-18T12:00:00+00:00",
"history": [
{"role": "user", "parts": [{"text": "Summarize this document"}]},
{"role": "agent", "parts": [{"text": "Here is the summary..."}]}
],
"artifacts": [
{"name": "summary", "parts": [{"text": "The document covers..."}]}
],
"metadata": {},
"created_at": "2026-05-18T11:59:58+00:00",
"updated_at": "2026-05-18T12:00:00+00:00"
}
```
### Helpers
`bindu/server/storage/helpers/` ships small utilities used by `PostgresStorage`:
* `validation.validate_uuid_type` / `normalization.normalize_uuid` — coerce string UUIDs to `UUID` and reject bad input early.
* `normalization.normalize_message_uuids` — fix up `task_id`, `context_id`, `message_id`, `reference_task_ids` on inbound messages.
* `serialization.serialize_for_jsonb` — recursively convert `UUID` to `str` so JSONB stays JSON-safe.
* `security.mask_database_url` — strip the password before logging (`user:***@host`).
* `security.sanitize_identifier` — used when DID-based schema isolation rewrites `search_path`; rejects anything that isn't `[A-Za-z0-9_]`.
* `db_operations.get_current_utc_timestamp`, `prepare_jsonb_value`, `create_update_values` — common building blocks for `UPDATE` statements.
***
## PostgreSQL Setup
```bash theme={null}
docker run -d \
--name bindu-postgres \
-e POSTGRES_USER=bindu_user \
-e POSTGRES_PASSWORD=secret \
-e POSTGRES_DB=bindu_db \
-p 5432:5432 \
postgres:16
```
```bash theme={null}
uv add 'sqlalchemy[asyncio]' asyncpg alembic
```
The factory imports `PostgresStorage` lazily — without these packages
you'll get a clear error at startup, not at runtime.
```bash theme={null}
export STORAGE_TYPE=postgres
export DATABASE_URL='postgresql+asyncpg://bindu_user:secret@localhost:5432/bindu_db'
```
For managed Postgres (Neon, RDS, Supabase) append `?sslmode=require`.
Either let Bindu do it on connect:
```bash theme={null}
export STORAGE__RUN_MIGRATIONS_ON_STARTUP=true
```
Or run Alembic yourself:
```bash theme={null}
uv run alembic upgrade head
```
Other useful Alembic commands:
```bash theme={null}
uv run alembic history # see applied/pending migrations
uv run alembic downgrade -1 # rollback one revision
```
Your handler code doesn't change. The factory picks up `STORAGE_TYPE`,
`PostgresStorage.connect()` opens the pool (`pool_pre_ping=True`), and
everything else is identical to memory mode.
***
## Retries, Pooling, Durability
* **Retries.** Memory wraps each call in a `@retry_storage_operation` decorator (3 attempts, 0.1s → 1.0s backoff). Postgres routes every call through `execute_with_retry` from `bindu.utils.retry`, governed by `STORAGE__POSTGRES_MAX_RETRIES` and `STORAGE__POSTGRES_RETRY_DELAY`. Same Tenacity primitives used elsewhere — see [Retry](/bindu/learn/retry/overview).
* **Pooling.** `PostgresStorage` creates a single `async_engine` per process with `pool_size=postgres_pool_max`, `max_overflow=0`, and `pool_pre_ping=True` so dead connections are detected before they bite a request.
* **Transactions.** Multi-step writes (`submit_task`, `update_task`) run inside `session.begin()`. The status update and the history/artifacts append commit atomically.
* **Durability.** Memory loses everything on restart, including queued webhook callbacks. Postgres persists every state transition; webhook configs reload on startup via `load_all_webhook_configs`.
***
## Real-World Use Cases
A user starts research, the agent asks a clarifying question
(`state=input-required`), the user replies. Postgres keeps both the task
row and the context's `message_history` so a follow-up `tasks/send` picks
up exactly where the agent paused — even across a redeploy.
Task takes minutes. Client registers a push-notification config; Bindu
writes it to `webhook_configs`. On restart, `load_all_webhook_configs`
rehydrates the in-memory map so the worker can still call the callback
when the task finishes.
Every state transition writes a row update. `history` and `artifacts` are
append-only JSONB arrays. Query by `owner_did`, `state`, or
`created_at` range — the indexes are already there.
With Postgres, N replicas of the same agent share one DB. Whoever wins
`update_task_state_if(submitted → working)` owns the task. The compare-
and-swap is a single SQL `UPDATE` — no two workers can both win.
Pass `DID=did:bindu:alice:agent1:...` and `PostgresStorage` rewrites
`search_path` to a sanitized per-DID Postgres schema. Same database,
isolated tables — handy for multi-tenant hosting.
***
## Security Best Practices
`DATABASE_URL` belongs in `.env` (gitignored) locally and in your
orchestrator's secret manager in prod. Bindu logs the URL with the
password masked via `mask_database_url`.
The agent only needs DML on its own tables (plus DDL if you let it run
migrations on startup). Don't give it `SUPERUSER`.
Append `?sslmode=require` (or stronger) when connecting to managed
Postgres. asyncpg supports the full `sslmode` ladder.
`caller_did` is recorded on every task and context. Pass the
authenticated DID through and let `OwnershipError` keep cross-tenant
leakage out of your error responses.
***
## Related
* [Architecture](/bindu/concepts/task-first-and-architecture)
* [Retry](/bindu/learn/retry/overview)
* [Scheduler](/bindu/learn/scheduler/overview)
* [Observability](/bindu/learn/observability/overview)
Storage is what turns a stateless script into
an agent that remembers —
every task, every turn, every artifact, every callback.
# Tunneling
Source: https://docs.getbindu.com/bindu/learn/tunneling/overview
Expose your local Bindu agent to the internet during development and testing
Local development is comfortable right up until something outside your machine needs to hit your agent. A webhook provider, a teammate, or a quick external test all run into the same wall: `localhost` does not exist anywhere except your own machine.
## Why Tunneling Matters
Bindu ships a built-in FRP-based tunnel so a local agent can be reached from the public internet without a deploy step. The agent process stays on your machine; only the network path changes.
| Local-only development | Development with tunneling |
| ----------------------------------------------- | --------------------------------------------------- |
| Agent is reachable only on `localhost` | Agent gets a public `https://` URL |
| Webhook testing is awkward or impossible | External services call back into your local agent |
| Sharing requires a deployment step | Anyone with the URL can hit the agent directly |
| Iteration stays trapped in one machine | Development stays local while access becomes public |
| Production setup is overkill for quick feedback | Public access is available for testing and demos |
Tunneling is for local development and testing only. Do not use it in production.
Production deployments should sit behind proper hosting, certificates, and auth — not
a shared FRP relay.
## What A Reverse Tunnel Actually Does
If you've never used FRP or ngrok before, the trust model is the important part.
A normal server *listens* for incoming connections. That doesn't work from a laptop behind NAT or a corporate firewall: nothing on the public internet can route a packet to `127.0.0.1`.
A **reverse tunnel** flips the direction. Your agent opens an **outbound** connection to a public FRP server. That connection stays open. When a request hits the public URL, the FRP server pushes it down the already-open socket to your agent, which responds back through the same pipe.
Your laptop never accepts a new inbound connection. It only keeps one outbound TCP
connection open to the FRP server. That is why this works through NAT and most
corporate firewalls, and it is the reason the agent — not the user — is the side that
initiates the tunnel.
Trust model in one line: anyone with the public URL can call your agent. Treat the URL as a development secret, and use Bindu's auth (Hydra, DID, x402) the same way you would in production if you're testing auth-protected flows.
## How Bindu Tunneling Works
Bindu uses [FRP (Fast Reverse Proxy)](https://github.com/fatedier/frp) to relay traffic between a public URL and your local agent.
The first time you enable tunneling, Bindu downloads the official `frpc` client binary
(currently `v0.61.0`) from the FRP GitHub releases and caches it under
`~/.bindu/frpc/`. Subsequent runs reuse the cached binary. If your OS or firewall
prompts about a new executable making outbound network connections, that is expected.
### The Public Address Model
Tunneling is enabled with `launch=True` in `bindufy()`:
```python theme={null}
from bindu import bindufy
config = {
"author": "your.email@example.com",
"name": "my_agent",
"description": "My development agent",
"deployment": {"url": "http://localhost:3773", "expose": True},
"skills": ["skills/question-answering"],
}
async def handler(message):
return {"role": "assistant", "content": "Hello!"}
# Enable tunneling for local development
bindufy(config, handler, launch=True)
```
When the agent starts, the logs look like this:
```text theme={null}
INFO bindu.penguin.bindufy Tunnel enabled, creating public URL...
INFO bindu.tunneling.manager Creating tunnel for localhost:3773 with subdomain 'abc12def3456'
INFO bindu.tunneling.binary Downloading FRP client binary for darwin_arm64...
INFO bindu.tunneling.binary ✅ FRP client binary downloaded to /Users/you/.bindu/frpc/frpc_darwin_arm64_v0.61.0
INFO bindu.tunneling.tunnel Starting FRP tunnel...
INFO bindu.tunneling.tunnel ✅ Tunnel established: https://abc12def3456.tunnel.getbindu.com
INFO bindu.penguin.bindufy ✅ Tunnel created: https://abc12def3456.tunnel.getbindu.com
🌐 Public URL: https://abc12def3456.tunnel.getbindu.com
```
The URL maps back to the local agent for as long as the process is alive.
Your agent still runs locally on `localhost:3773`. Nothing about the handler
changes.
A random 12-character subdomain is generated under `tunnel.getbindu.com` — one
lowercase letter followed by 11 alphanumerics.
This is meant for testing, webhooks, and demos — not production traffic.
### The Lifecycle: Start, Tunnel, Forward
Under the hood, tunneling moves through three practical stages.
```mermaid theme={null}
sequenceDiagram
participant User
participant TunnelURL as Public URL
(*.tunnel.getbindu.com)
participant FRPServer as Bindu FRP Server
(142.132.241.44:7000)
participant FRPClient as frpc
(your machine)
participant LocalAgent as Local Agent
(127.0.0.1:3773)
Note over LocalAgent,FRPServer: 1. Start — outbound connection from your machine
LocalAgent->>FRPClient: bindufy(launch=True) spawns frpc subprocess
FRPClient->>FRPServer: TCP connect to control port 7000
FRPClient->>FRPServer: Register subdomain (--sd abc12def3456)
FRPServer-->>FRPClient: "start proxy success"
Note over User,LocalAgent: 2. Tunnel — request comes in
User->>TunnelURL: HTTPS request
TunnelURL->>FRPServer: TLS-terminated forward
FRPServer->>FRPClient: Push request down the open socket
FRPClient->>LocalAgent: HTTP to 127.0.0.1:3773
Note over LocalAgent,User: 3. Forward — response goes back the same way
LocalAgent-->>FRPClient: Response
FRPClient-->>FRPServer: Forward response
FRPServer-->>TunnelURL: Forward response
TunnelURL-->>User: HTTPS response
```
`bindufy()` constructs a `TunnelConfig(enabled=True)`, the binary is downloaded if
missing, and a `TunnelManager` spawns `frpc` as a subprocess that connects to the
Bindu FRP server.
`frpc` registers a subdomain on the server. The subdomain is either:
* **Random** (default) — 12 characters: 1 lowercase letter + 11 lowercase letters or
digits, e.g. `abc12def3456`.
* **Custom** — whatever you set via `TUNNEL_SUBDOMAIN` env var, the `tunnel.subdomain`
config key, or by calling `TunnelManager.create_tunnel(subdomain="my-agent")`.
On success, the server replies `start proxy success` and Bindu logs the public URL.
For every public request, `frpc` reads it off the already-open socket and forwards
it to `127.0.0.1:`. Responses go back the same way. The agent has no
idea it's being tunneled — to the handler it looks like a normal local request.
When the agent process exits, `atexit` terminates the `frpc` subprocess and the
public URL stops resolving.
***
## Configuration
### TunnelConfig
The dataclass in `bindu.tunneling.config` controls every knob.
| Field | Type | Default | Notes |
| ---------------- | --------------- | --------------------- | --------------------------------------------------------------------------------------------------------------- |
| `enabled` | `bool` | `False` | Master switch. `launch=True` sets this to `True`. |
| `server_address` | `str` | `142.132.241.44:7000` | FRP server `host:port`. Override for self-hosted FRP. |
| `subdomain` | `Optional[str]` | `None` | Custom subdomain. Auto-generated if `None`. |
| `tunnel_domain` | `str` | `tunnel.getbindu.com` | Base domain the subdomain attaches to. |
| `protocol` | `str` | `"http"` | One of `http`, `https`, `tcp`. Passed straight to `frpc`. |
| `use_tls` | `bool` | `False` | TLS between `frpc` and the FRP server. The public URL is always `https` regardless — the server terminates TLS. |
| `local_host` | `str` | `127.0.0.1` | Local interface to forward to. |
| `local_port` | `Optional[int]` | `None` | Set automatically from your `deployment.url`. |
### Custom Subdomain
The default subdomain is random and changes every restart. To pin it, set
`TUNNEL_SUBDOMAIN`:
```bash theme={null}
export TUNNEL_SUBDOMAIN=my-agent-dev
uv run python my_agent.py
# → https://my-agent-dev.tunnel.getbindu.com
```
Or pass a tunnel block in your config:
```python theme={null}
config = {
"author": "your.email@example.com",
"name": "my_agent",
"deployment": {"url": "http://localhost:3773", "expose": True},
"skills": ["skills/question-answering"],
"tunnel": {
"enabled": True,
"subdomain": "my-agent-dev",
"protocol": "http",
},
}
bindufy(config, handler, launch=True)
```
Custom subdomains are first-come, first-served on the shared `tunnel.getbindu.com`
domain. If someone else already holds it, `frpc` will fail with a registration error
and Bindu falls back to running local-only.
### Environment Variables
Every `TunnelConfig` field has an env-var equivalent that
`create_tunnel_config_from_env()` reads:
| Variable | Maps to |
| ----------------------- | ---------------- |
| `TUNNEL_ENABLED` | `enabled` |
| `TUNNEL_SERVER_ADDRESS` | `server_address` |
| `TUNNEL_SUBDOMAIN` | `subdomain` |
| `TUNNEL_DOMAIN` | `tunnel_domain` |
| `TUNNEL_PROTOCOL` | `protocol` |
| `TUNNEL_USE_TLS` | `use_tls` |
| `TUNNEL_LOCAL_HOST` | `local_host` |
### DID-Derived Subdomains
`TunnelManager._generate_subdomain_from_did()` converts an agent DID into a DNS-safe
label (strips `did:`, replaces colons with hyphens, lowercases, truncates to 63 chars).
It exists for future stable per-agent URLs, but the default `create_tunnel()` path uses
the random generator — wire it in yourself if you want DID-stable URLs today:
```python theme={null}
from bindu.tunneling import TunnelManager
manager = TunnelManager()
did_subdomain = TunnelManager._generate_subdomain_from_did(
"did:bindu:alice:my_agent:0001"
)
# → "bindu-alice-my-agent-0001"
public_url = manager.create_tunnel(local_port=3773, subdomain=did_subdomain)
```
***
## Programmatic Use
`bindufy(..., launch=True)` is the common path. For tests, scripts, or anything that
isn't a full agent, `TunnelManager` can be used directly as a context manager — it
handles `frpc` cleanup on exit.
```python theme={null}
from bindu.tunneling import TunnelManager, TunnelConfig
# Expose any local HTTP service, not just a Bindu agent
with TunnelManager() as manager:
public_url = manager.create_tunnel(
local_port=3773,
subdomain="my-test-run",
)
print(f"Hit me at: {public_url}")
# ... run your test, send some traffic ...
# Tunnel is torn down here; frpc subprocess is terminated.
```
A more explicit config:
```python theme={null}
config = TunnelConfig(
enabled=True,
subdomain="webhook-staging",
protocol="http",
local_host="127.0.0.1",
)
with TunnelManager() as manager:
url = manager.create_tunnel(local_port=8000, config=config)
...
```
`TunnelManager` allows exactly one active tunnel per instance — calling
`create_tunnel()` twice raises `RuntimeError`. The process also registers an `atexit`
hook globally, so even hard exits clean up the `frpc` subprocess.
***
## Local Testing Through The Tunnel
### Basic Development Test
```bash theme={null}
# Terminal 1: Start agent with tunnel
uv run python my_agent.py
# Terminal 2: Test from anywhere
curl https://abc12def3456.tunnel.getbindu.com/.well-known/agent.json
curl https://abc12def3456.tunnel.getbindu.com/health
```
### End-To-End Webhook Test
A common reason to tunnel: an external service (Stripe, GitHub, a partner agent) needs
to POST into your local agent during development.
```bash theme={null}
# 1. Pin a subdomain so the upstream URL doesn't change every restart
export TUNNEL_SUBDOMAIN=alice-webhook-dev
uv run python my_agent.py
# → https://alice-webhook-dev.tunnel.getbindu.com
# 2. Register the URL with the upstream service
# e.g. set the webhook URL in Stripe / GitHub / your provider to:
# https://alice-webhook-dev.tunnel.getbindu.com/webhooks/incoming
# 3. Trigger an event upstream and watch your local logs.
# Requests land on your handler exactly as if the agent were deployed.
```
The tunneled agent is still your local process. If `python my_agent.py` stops, the
public URL keeps resolving for a moment but returns 404 — there's nothing behind it.
### Use Cases
Test your agent without deploying it. The agent runs on your machine, but the public
URL makes it reachable for quick external checks.
Let an external service call back into your local agent during development. Pin a
custom subdomain so the upstream URL doesn't change every restart.
Share the public URL so someone else can hit the agent without you having to deploy
it first. Combine with auth if the agent handles anything sensitive.
Use the tunnel for demos where local iteration matters more than production
deployment. Combine with `expose: True` in your `deployment` block so the agent card
advertises the public URL.
Point another agent at your tunnel URL to test A2A flows (negotiation, task send)
end-to-end without standing up shared infrastructure.
***
## Limits And Troubleshooting
Tunneling is intentionally narrow in scope. It solves development reachability, not
production hosting.
### Current Limits
* **Development only** — not suitable for production traffic.
* **Shared relay** — `tunnel.getbindu.com` is operated as a convenience, not as
guaranteed infrastructure. No SLA.
* **Temporary URLs by default** — the random 12-character subdomain changes every
restart unless you pin one.
* **One tunnel per `TunnelManager`** — start a second `bindufy(launch=True)` in the
same process and you'll get a `RuntimeError`.
* **No persistence** — when the agent stops, `frpc` is terminated and the URL stops
resolving.
### Troubleshooting
`frpc` couldn't reach the FRP server within the default 30-second timeout. Check
network egress first:
```bash theme={null}
# DNS + reachability
ping tunnel.getbindu.com
# The FRP control channel uses TCP 7000 on 142.132.241.44
nc -vz 142.132.241.44 7000
```
Corporate firewalls often block arbitrary outbound TCP ports. Port 7000 is the one
to allowlist.
If you pinned a subdomain via `TUNNEL_SUBDOMAIN` and someone else already holds it,
`frpc` exits non-zero. Bindu logs the failure and continues local-only. Pick
something less generic (`alice-agent-dev` beats `agent`).
On first run Bindu fetches `frpc__` from the official FRP GitHub release.
If your platform isn't in the release matrix, you'll see a 404 from
`bindu.tunneling.binary`. Download `frpc` manually from
[https://github.com/fatedier/frp/releases](https://github.com/fatedier/frp/releases) and drop it at
`~/.bindu/frpc/frpc___v0.61.0` with executable permissions.
Bindu registers an `atexit` hook to terminate `frpc`. If the parent dies in a way
that skips `atexit` (`kill -9`, OOM kill), the subprocess can linger. Kill it
manually:
```bash theme={null}
pkill -f "bindu-tunnel"
```
### For Production
Do not use tunneling in production. Use proper hosting with your own certificates and
ingress — Cloudflare, a managed load balancer, or whatever your platform offers — and
keep `launch=False` in deployed environments.
***
## Practical Boundaries
Tunneling is a good fit when you need quick public access to a local agent for
testing, demos, or webhook development.
It's the wrong fit for production traffic, persistent public infrastructure, or
anything that depends on strong uptime guarantees.
## Related
* [Architecture](/bindu/concepts/task-first-and-architecture)
Bindu tunneling makes a local agent
reachable for development without pretending to be production
, so testing can move faster without changing where you build.
# Agent card and discovery
Source: https://docs.getbindu.com/bindu/protocol/agent-card
AgentCard structure, AgentCapabilities, AgentInterface, AgentExtension, and the discovery flow.
Agent discovery enables clients to find and understand agent capabilities through standardized metadata. The AgentCard serves as the agent's "business card" containing identity, skills, and operational requirements.
### AgentIdentity
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class AgentIdentity(TypedDict):
"""Agent identity configuration with DID and other identifiers.
Establishes decentralized identity for agent authentication and discovery.
"""
did: Required[str]
"""The agent's Decentralized Identifier (DID)."""
did_document: Required[Dict[str, Any]]
"""The agent's DID document containing public keys and other identifiers."""
agentdns_url: NotRequired[str]
"""The agent's AgentDNS URL for decentralized identity resolution."""
endpoint: NotRequired[str]
"""The agent's endpoint URL for communication."""
public_key: Required[str]
"""The agent's public key for authentication."""
csr: Required[str]
"""The agent's Certificate Signing Request (CSR) for authentication."""
```
**Use Case: Decentralized Agent Identity**
```json theme={null}
{
"did": "did:example:agent123",
"didDocument": {
"id": "did:example:agent123",
"publicKey": [{
"id": "did:example:agent123#keys-1",
"type": "Ed25519VerificationKey2020",
"controller": "did:example:agent123",
"publicKeyMultibase": "zH3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV"
}]
},
"agentdnsUrl": "https://agentdns.example.com/agent123",
"endpoint": "https://agent.example.com/api",
"publicKey": "-----BEGIN PUBLIC KEY-----\nMIIB...",
"csr": "-----BEGIN CERTIFICATE REQUEST-----\nMIIC..."
}
```
**What it's for:** Establishing verifiable decentralized identity for agents using DIDs. Enables trustless discovery and authentication without central authorities. The DID document contains public keys for cryptographic verification.
***
### AgentInterface
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class AgentInterface(TypedDict):
"""An interface that the agent supports.
Declares available transport protocols and endpoints.
"""
transport: str
"""The transport protocol (e.g., 'jsonrpc', 'websocket')."""
url: str
"""The URL endpoint for this transport."""
description: NotRequired[str]
"""Description of this interface."""
```
**Use Case: Multiple Transport Support**
```json theme={null}
{
"transport": "websocket",
"url": "wss://agent.example.com/ws",
"description": "WebSocket interface for real-time streaming"
}
```
**What it's for:** Declaring multiple communication protocols an agent supports. Allows clients to choose between JSON-RPC, WebSocket, gRPC, or other transports based on their needs.
***
### AgentExtension
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class AgentExtension(TypedDict):
"""A declaration of an extension supported by an Agent.
Extensions add protocol capabilities beyond the core A2A specification.
"""
uri: str
"""The URI of the extension."""
description: NotRequired[str]
"""A description of how this agent uses this extension."""
required: NotRequired[bool]
"""Whether the client must follow specific requirements of the extension."""
params: NotRequired[dict[str, Any]]
"""Optional configuration for the extension."""
```
**Use Case: AP2 Payment Extension**
```json theme={null}
{
"uri": "https://github.com/google-agentic-commerce/ap2/tree/v0.1",
"description": "Supports AP2 protocol for agent payments",
"required": true,
"params": {
"roles": ["merchant", "shopper"]
}
}
```
**What it's for:** Declaring support for protocol extensions like AP2 (payments), custom authentication schemes, or specialized capabilities. The `required` flag indicates if clients must support the extension.
***
### Skill
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class Skill(TypedDict):
"""Skills are a unit of capability that an agent can perform.
Skills can be defined in two ways:
1. Inline (legacy): All metadata in config JSON
2. File-based (Claude-style): Rich documentation in SKILL.md files
"""
id: str
"""A unique identifier for the skill."""
name: str
"""Human readable name of the skill."""
description: str
"""A human-readable description of the skill."""
tags: list[str]
"""Set of tag-words describing classes of capabilities."""
examples: NotRequired[list[str]]
"""Example scenarios that the skill can perform."""
input_modes: list[str]
"""Supported mime types for input data."""
output_modes: list[str]
"""Supported mime types for output data."""
# Rich documentation fields (Claude-style skills)
documentation_path: NotRequired[str]
"""Path to the SKILL.md file containing detailed instructions."""
documentation_content: NotRequired[str]
"""Full content of the SKILL.md file."""
capabilities_detail: NotRequired[dict[str, Any]]
"""Structured capability details for orchestrator matching."""
requirements: NotRequired[dict[str, Any]]
"""Dependencies and system requirements."""
performance: NotRequired[dict[str, Any]]
"""Performance characteristics for orchestrator planning."""
version: NotRequired[str]
"""Skill version for compatibility tracking."""
allowed_tools: NotRequired[list[str]]
"""List of tools/capabilities this skill is allowed to use."""
```
**Use Case: Data Analysis Skill**
```json theme={null}
{
"id": "data-analysis",
"name": "Data Analysis",
"description": "Analyze datasets and generate insights",
"tags": ["analytics", "data", "statistics"],
"examples": [
"Analyze this sales data and find trends",
"Calculate statistics for this dataset"
],
"inputModes": ["text/csv", "application/json"],
"outputModes": ["text/plain", "application/json"],
"documentationPath": "./skills/data-analysis/SKILL.md",
"capabilitiesDetail": {
"statistical_analysis": {"supported": true, "methods": ["regression", "correlation"]},
"visualization": {"supported": true, "types": ["charts", "graphs"]}
},
"requirements": {
"packages": ["pandas", "numpy", "matplotlib"],
"minMemoryMb": 1024
},
"performance": {
"avgProcessingTimeMs": 5000,
"maxFileSizeMb": 100
},
"allowedTools": ["Read", "Write"]
}
```
**What it's for:** Defining what an agent can do. Supports both simple inline definitions and rich Claude-style documentation with SKILL.md files. Orchestrators use skills to match agents to tasks.
***
### AgentCapabilities
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class AgentCapabilities(TypedDict):
"""Defines optional capabilities supported by an agent.
Declares protocol features the agent implements.
"""
extensions: NotRequired[list[AgentExtension]]
"""List of extensions supported by the agent."""
push_notifications: NotRequired[bool]
"""Whether the agent supports push notifications."""
state_transition_history: NotRequired[bool]
"""Whether the agent supports state transition history."""
streaming: NotRequired[bool]
"""Whether the agent supports streaming."""
```
**Use Case: Full-Featured Agent**
```json theme={null}
{
"extensions": [
{
"uri": "https://github.com/google-agentic-commerce/ap2/tree/v0.1",
"description": "AP2 payment support",
"required": false
}
],
"pushNotifications": true,
"stateTransitionHistory": true,
"streaming": true
}
```
**What it's for:** Declaring which optional A2A protocol features the agent supports. Clients can choose agents based on required capabilities like streaming or push notifications.
***
### AgentCard
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class AgentCard(TypedDict):
"""The card that describes an agent - following bindu pattern.
The complete agent metadata for discovery and configuration.
"""
id: Required[UUID]
"""Unique identifier for the agent."""
name: Required[str]
"""Human readable name of the agent."""
description: Required[str]
"""A human-readable description of the agent."""
url: Required[str]
"""URL of the agent."""
version: Required[str]
"""Version of the agent."""
protocol_version: Required[str]
"""Version of the protocol used by the agent."""
documentation_url: NotRequired[str]
"""URL of the documentation of the agent."""
icon_url: NotRequired[str]
"""A URL to an icon for the agent."""
agent_trust: Required[AgentTrust]
"""Trust of the agent."""
capabilities: Required[AgentCapabilities]
"""Capabilities of the agent."""
skills: Required[List[Skill]]
"""Skills of the agent."""
kind: Required[Literal["agent", "team", "workflow"]]
"""Kind of the agent."""
execution_cost: NotRequired[AgentExecutionCost]
"""Execution cost of the agent."""
num_history_sessions: Required[int]
"""Number of history sessions of the agent."""
preferred_transport: NotRequired[str]
"""The transport of the preferred endpoint."""
extra_data: Required[Dict[str, Any]]
"""Extra data about the agent."""
debug_mode: Required[bool]
"""Debug mode of the agent."""
debug_level: Required[Literal[1, 2]]
"""Debug level of the agent."""
monitoring: Required[bool]
"""Monitoring of the agent."""
telemetry: Required[bool]
"""Telemetry of the agent."""
additional_interfaces: NotRequired[list[AgentInterface]]
"""Announcement of additional supported transports."""
security: NotRequired[list[dict[str, list[str]]]]
"""Security requirements for contacting the agent."""
security_schemes: NotRequired[dict[str, SecurityScheme]]
"""Security scheme definitions."""
default_input_modes: list[str]
"""Supported mime types for input data."""
default_output_modes: list[str]
"""Supported mime types for output data."""
```
**Use Case: Complete Agent Card**
```json theme={null}
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Data Analysis Agent",
"description": "Analyzes datasets and generates insights",
"url": "https://agent.example.com",
"version": "1.0.0",
"protocolVersion": "0.3.0",
"kind": "agent",
"agentTrust": {
"identityProvider": "keycloak",
"inheritedRoles": [],
"creatorId": "did:example:creator",
"creationTimestamp": 1698796800,
"trustVerificationRequired": true,
"allowedOperations": {}
},
"capabilities": {
"streaming": true,
"pushNotifications": true
},
"skills": [
{
"id": "data-analysis",
"name": "Data Analysis",
"description": "Analyze datasets",
"tags": ["analytics"],
"inputModes": ["text/csv"],
"outputModes": ["text/plain"]
}
],
"numHistorySessions": 10,
"debugMode": false,
"debugLevel": 1,
"monitoring": true,
"telemetry": true,
"defaultInputModes": ["text/plain"],
"defaultOutputModes": ["text/plain"],
"extraData": {}
}
```
**What it's for:** The complete agent metadata package. Clients fetch the AgentCard to discover capabilities, skills, security requirements, and operational characteristics before interacting with an agent.
### Agent Discovery Flow
```mermaid theme={null}
sequenceDiagram
participant Client
participant Registry as Agent Registry
participant Agent
Client->>Registry: Search for agents
(by skill, tag, capability)
Registry-->>Client: List of matching AgentCards
Client->>Client: Select agent
(based on skills, cost, trust)
Client->>Agent: GET /agent-card
Agent-->>Client: Complete AgentCard
Client->>Client: Verify AgentTrust
Check capabilities
Review execution cost
alt Agent meets requirements
Client->>Agent: Initiate task
(message/send)
Agent-->>Client: Task created
else Agent doesn't meet requirements
Client->>Registry: Search for alternative
end
```
**Summary:**
Agent discovery uses **AgentCard** as the central metadata structure containing identity (**AgentIdentity**), capabilities (**AgentCapabilities**), skills (**Skill**), and operational requirements. Agents declare support for extensions (**AgentExtension**) and multiple transports (**AgentInterface**). Clients discover agents through registries, evaluate their capabilities and costs, then establish secure connections using the declared security schemes and trust configurations.
***
# Context management
Source: https://docs.getbindu.com/bindu/protocol/context
ContextId, history sessions, and how Bindu threads conversations across turns.
Contexts serve as conversation containers in the Bindu protocol, managing the complete interaction lifecycle between clients and agents. They maintain conversation continuity, preserve context across multiple tasks, and provide session-level organization.
Context is a Bindu-specific extension `` that goes beyond the standard A2A protocol to enable sophisticated conversation management and session tracking.
### Context Object
A **Context** is a conversation session that groups related tasks and maintains interaction history. It provides the organizational structure for multi-turn conversations and enables agents to maintain state across multiple task executions.
**Schema:**
```python theme={null}
class Context(TypedDict):
"""Conversation session that groups related tasks and maintains interaction history.
Contexts serve as conversation containers in the bindu protocol, managing
the complete interaction lifecycle between clients and agents. They maintain
conversation continuity, preserve context across multiple tasks, and provide
session-level organization.
Core Responsibilities:
- Session Management: Group related tasks under a unified conversation
- History Preservation: Maintain complete message history across tasks
- Context Continuity: Preserve conversation state and references
- Metadata Tracking: Store session-level information and preferences
Context Lifecycle:
1. Creation: Client initiates conversation or system creates implicit context
2. Task Association: Multiple tasks can belong to the same context
3. History Building: Messages and artifacts accumulate over time
4. State Management: Track conversation status and metadata
5. Completion: Context can be closed or archived when conversation ends
Key Properties:
- Multi-Task: Contains multiple related tasks over time
- Stateful: Maintains conversation history and context
- Client-Controlled: Clients can explicitly manage context lifecycle
- Traceable: Unique ID enables context tracking and reference
Context Relationships:
- Contains: Multiple tasks (one-to-many relationship)
- Maintains: Complete conversation history across all tasks
- Preserves: Session-level metadata and preferences
- References: Can link to other contexts for complex workflows
"""
context_id: Required[UUID]
"""Unique identifier for the context."""
kind: Required[Literal["context"]]
"""Type discriminator, always "context"."""
tasks: NotRequired[list[UUID]]
"""List of task IDs belonging to this context."""
name: NotRequired[str]
"""Human-readable context name."""
description: NotRequired[str]
"""Context purpose or summary."""
role: Required[str]
"""Role of the context (e.g., "assistant", "analyst", "coordinator")."""
created_at: Required[str]
"""ISO 8601 datetime when context was created.
Example: "2023-10-27T10:00:00Z"
"""
updated_at: Required[str]
"""ISO 8601 datetime when context was last updated.
Example: "2023-10-27T10:00:00Z"
"""
status: NotRequired[Literal["active", "paused", "completed", "archived"]]
"""Current status of the context:
- active: Context is currently in use
- paused: Context is temporarily suspended
- completed: Context has finished its purpose
- archived: Context is stored for historical reference
"""
tags: NotRequired[list[str]]
"""Organizational tags for categorization and filtering."""
metadata: NotRequired[dict[str, Any]]
"""Custom context metadata for extensions and application-specific data."""
parent_context_id: NotRequired[UUID]
"""For nested or hierarchical contexts."""
reference_context_ids: NotRequired[list[UUID]]
"""Related contexts for cross-referencing."""
extensions: NotRequired[dict[str, Any]]
"""Additional protocol extensions."""
```
**Realistic Example: Multi-Task Analysis Context**
A client engages in a multi-turn conversation about market analysis:
```json theme={null}
{
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"kind": "context",
"name": "Q4 Market Analysis Session",
"description": "Comprehensive market analysis and strategic planning for Q4 2025",
"role": "analyst",
"createdAt": "2025-10-31T09:00:00Z",
"updatedAt": "2025-10-31T11:30:00Z",
"status": "active",
"tasks": [
"363422be-b0f9-4692-a24d-278670e7c7f1",
"8f7e6d5c-4b3a-2109-8765-fedcba098765",
"1a2b3c4d-5e6f-7890-abcd-ef1234567890"
],
"tags": ["market-analysis", "q4-2025", "strategic-planning"],
"metadata": {
"department": "Strategy",
"priority": "high",
"stakeholders": ["CEO", "CMO", "CFO"],
"deadline": "2025-11-15T00:00:00Z",
"budget": 50000,
"region": "North America"
}
}
```
**What This Example Shows:**
* **Context Identity**: Unique `contextId` for tracking the conversation
* **Session Organization**: Groups 3 related tasks under one conversation
* **Temporal Tracking**: Creation and update timestamps
* **Status Management**: Active status indicates ongoing work
* **Metadata Context**: Business context like department, priority, and stakeholders
* **Categorization**: Tags for filtering and organization
**Context vs Task:**
* **Context** = The conversation session (container)
* **Task** = Individual work units within the conversation
* One context can contain many tasks
* Tasks inherit context from their parent context
***
### Context Status States
Contexts can be in one of four states:
**Active States:**
* **`active`** - Context is currently in use
* New tasks can be added
* Conversation is ongoing
* Default state for new contexts
* **`paused`** - Context is temporarily suspended
* No new tasks should be created
* Existing tasks may continue
* Can be resumed to `active` state
**Terminal States:**
* **`completed`** - Context has finished its purpose
* All tasks are completed
* No new tasks should be added
* Context is considered closed
* **`archived`** - Context is stored for historical reference
* Preserved for audit or review
* Read-only access
* Cannot be modified or resumed
**State Transition Diagram:**
```mermaid theme={null}
stateDiagram-v2
[*] --> active: Context Created
active --> paused: Suspend
active --> completed: All Tasks Done
active --> archived: Archive
paused --> active: Resume
paused --> completed: Complete
paused --> archived: Archive
completed --> archived: Archive
archived --> [*]
note right of active
Default state
Tasks can be added
end note
note right of completed
Terminal state
All work finished
end note
note right of archived
Terminal state
Read-only
end note
```
***
### Context Operations & Parameters
Parameters used for various context operations including creation, querying, and management.
#### ContextIdParams
Simple parameters containing a context ID. Used internally whenever an
operation needs to identify a single context (for example, as the base
type extended by `ContextQueryParams` and `ContextsClearParams`).
**Schema:**
```python theme={null}
class ContextIdParams(TypedDict):
"""Parameters for context identification.
Used for operations that only require a context ID.
"""
context_id: Required[UUID]
"""The ID of the context."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata for the operation."""
```
***
#### ContextQueryParams
Extends `ContextIdParams` with a `history_length` cap — a future
building block for single-context retrieval. The currently exposed
RPC for listing contexts is `contexts/list`; see its params below.
**Schema:**
```python theme={null}
class ContextQueryParams(TypedDict):
"""Query parameters for a context.
Extends ContextIdParams to add history length control for efficient
retrieval of context information with task history.
"""
context_id: Required[UUID]
"""The ID of the context to query."""
history_length: NotRequired[int]
"""The maximum number of history messages to return per task."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata for the query."""
```
***
#### ListContextsParams
Parameters for listing multiple contexts with optional history limiting.
**Schema:**
```python theme={null}
class ListContextsParams(TypedDict):
"""Parameters for listing contexts.
Used to retrieve multiple contexts with control over history size
and filtering options to optimize payload and query performance.
"""
history_length: NotRequired[int]
"""The maximum number of history messages to return for each task in each context."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata for filtering or controlling the list operation.
Common filters:
- status: Filter by context status (active, paused, completed, archived)
- tags: Filter by tags
- role: Filter by context role
- limit: Maximum number of contexts to return
- offset: Pagination offset
- sortBy: Sort field (createdAt, updatedAt, name)
- sortOrder: Sort direction (asc, desc)
"""
```
**Example: List Active Contexts**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 9,
"method": "contexts/list",
"params": {
"historyLength": 3,
"metadata": {
"status": "active",
"limit": 10,
"sortBy": "updatedAt",
"sortOrder": "desc"
}
}
}
```
**Response:**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 9,
"result": {
"contexts": [
{
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"kind": "context",
"name": "Q4 Market Analysis Session",
"role": "analyst",
"status": "active",
"tasks": ["363422be-b0f9-4692-a24d-278670e7c7f1"],
"createdAt": "2025-10-31T09:00:00Z",
"updatedAt": "2025-10-31T11:30:00Z",
"tags": ["market-analysis", "q4-2025"]
},
{
"contextId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"kind": "context",
"name": "Customer Support Session",
"role": "support",
"status": "active",
"tasks": ["task-001", "task-002"],
"createdAt": "2025-10-31T10:15:00Z",
"updatedAt": "2025-10-31T11:25:00Z",
"tags": ["support", "customer-inquiry"]
}
],
"total": 15,
"page": 1,
"pageSize": 10
}
}
```
**Use Cases:**
* Dashboard views showing active conversations
* Context management interfaces
* Session monitoring and analytics
* Filtering contexts by status, role, or tags
* Pagination with history control
* Finding contexts by criteria
**Common Filtering Patterns:**
**By Status:**
```json theme={null}
{
"metadata": {
"status": "active"
}
}
```
**By Tags:**
```json theme={null}
{
"metadata": {
"tags": ["market-analysis", "high-priority"]
}
}
```
**By Date Range:**
```json theme={null}
{
"metadata": {
"createdAfter": "2025-10-01T00:00:00Z",
"createdBefore": "2025-10-31T23:59:59Z"
}
}
```
**With Pagination:**
```json theme={null}
{
"metadata": {
"limit": 20,
"offset": 40,
"sortBy": "updatedAt",
"sortOrder": "desc"
}
}
```
***
### Context Best Practices
**Context Decision Flow:**
```mermaid theme={null}
flowchart TD
Start[New Task Request] --> Question{Same topic/conversation?}
Question -->|Yes| Reuse[Reuse Existing Context]
Question -->|No| NewTopic{New project/domain?}
NewTopic -->|Yes| Create[Create New Context]
NewTopic -->|No| Roles{Different agent roles needed?}
Roles -->|Yes| Create
Roles -->|No| Reuse
Reuse --> Continue[Continue with context_id]
Create --> Name[Name: 'Project - Purpose']
Name --> Metadata[Add metadata: owner, timestamps]
Metadata --> Active[Status: active]
style Reuse fill:#90EE90
style Create fill:#87CEEB
```
**Lifecycle States:**
```mermaid theme={null}
stateDiagram-v2
[*] --> active: Create context
active --> paused: Temporarily inactive
paused --> active: Resume work
active --> completed: All work done
paused --> completed: Finish without resuming
completed --> [*]: Archive
note right of active
Working on tasks
Adding messages
end note
note right of completed
Historical reference
Ready for cleanup
end note
```
**Quick Tips:**
* **Naming**: Use format `"Project - Purpose"` (e.g., "Q4 Sales - Analysis", "Support - Ticket #1234")
* **Metadata**: Store business context, ownership, timestamps for filtering and tracking
* **Performance**: Use `historyLength` parameter to limit payload size when fetching contexts
* **Cleanup**: Regularly archive completed contexts to maintain system performance
***
# Credit system
Source: https://docs.getbindu.com/bindu/protocol/credit
Bindu-specific credit accounting that sits next to x402. Not part of A2A.
The credit system is a Bindu-specific extension for managing agent marketplace economics — centralized accounting of agent execution costs, creator monetization, and trust-gated access.
**Implementation status (2026-05): types only, no runtime enforcement.**
`AgentExecutionCost`, `ExecutionRequest`, and `ExecutionResponse` ship as TypedDicts in [`bindu/common/protocol/types.py:873-916`](https://github.com/getbindu/Bindu/blob/main/bindu/common/protocol/types.py) and are accepted on the wire, but there are **no JSON-RPC handlers** wired to debit or credit balances, no credit ledger storage, and no middleware that blocks execution on insufficient credits. For monetary gating that *is* live, use the x402 paywall — see [Payments](./payment).
The schemas below are stable; the orchestration around them is in design. Treat the flow diagrams as the target shape, not what runs today.
### AgentExecutionCost
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class AgentExecutionCost(TypedDict):
"""Defines the credit cost for executing an agent.
Sets pricing and access control for agent services.
"""
agent_id: Required[str]
"""The unique identifier of the agent."""
agent_name: Required[str]
"""The name of the agent."""
credits_per_request: Required[int]
"""The number of credits required to execute the agent."""
creator_did: Required[str]
"""The DID of the creator of the agent."""
minimum_trust_level: Required[TrustLevel]
"""The minimum trust level required to execute the agent."""
```
**Use Case: Premium Agent Pricing**
```json theme={null}
{
"agentId": "agent-analytics-pro",
"agentName": "Advanced Analytics Agent",
"creditsPerRequest": 100,
"creatorDid": "did:example:creator123",
"minimumTrustLevel": "analyst"
}
```
**What it's for:** Defining the cost and access requirements for running an agent. Creators set credit prices for their agents, and specify minimum trust levels to ensure only qualified users can execute sensitive operations.
***
### ExecutionRequest
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class ExecutionRequest(TypedDict):
"""Represents a request to execute an agent with credit verification.
Initiates agent execution with credit pre-authorization.
"""
request_id: Required[UUID]
"""The unique identifier of the request."""
executor_did: Required[str]
"""The DID of the executor."""
agent_id: Required[str]
"""The unique identifier of the agent."""
input_data: Required[str]
"""The input data for the agent execution."""
estimated_credits: Required[int]
"""The estimated number of credits required for the execution."""
trust_level: Required[TrustLevel]
"""The trust level of the executor."""
```
**Use Case: Agent Execution Request**
```json theme={null}
{
"requestId": "550e8400-e29b-41d4-a716-446655440000",
"executorDid": "did:example:user456",
"agentId": "agent-analytics-pro",
"inputData": "Analyze Q4 sales data for trends and anomalies",
"estimatedCredits": 100,
"trustLevel": "analyst"
}
```
**What it's for:** Requesting agent execution with credit verification. The system checks if the executor has sufficient credits and meets the minimum trust level before allowing execution.
***
### ExecutionResponse
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class ExecutionResponse(TypedDict):
"""Represents the response from an agent execution with credit deduction.
Returns execution results and credit transaction details.
"""
request_id: Required[UUID]
"""The unique identifier of the request."""
execution_id: Required[UUID]
"""The unique identifier of the execution."""
success: Required[bool]
"""Indicates whether the execution was successful."""
credits_charged: Required[int]
"""The number of credits charged for the execution."""
transaction_id: NotRequired[UUID]
"""The unique identifier of the transaction."""
output_data: NotRequired[str]
"""The output data from the agent execution."""
error_message: NotRequired[str]
"""The error message if the execution failed."""
execution_time: Required[str]
"""The time the execution was completed."""
```
**Use Case: Successful Execution**
```json theme={null}
{
"requestId": "550e8400-e29b-41d4-a716-446655440000",
"executionId": "660e8400-e29b-41d4-a716-446655440001",
"success": true,
"creditsCharged": 95,
"transactionId": "770e8400-e29b-41d4-a716-446655440002",
"outputData": "Analysis complete: Q4 sales increased 23% with peak in December...",
"executionTime": "2025-10-31T23:45:00Z"
}
```
**What it's for:** Returning execution results with credit transaction details. Shows actual credits charged (may differ from estimate), execution status, and output data. Failed executions may charge reduced or no credits depending on policy.
### Credit System Flow
```mermaid theme={null}
sequenceDiagram
participant User
participant Platform as Bindu
participant Agent
participant Creator
User->>Platform: ExecutionRequest
(agent_id, input_data, estimated_credits)
Platform->>Platform: Check user credits
Verify trust level
alt Insufficient credits or trust level
Platform-->>User: Execution denied
(error message)
else Credits available & authorized
Platform->>Agent: Execute task
Note over Agent: Processing...
Agent->>Platform: Return results
Platform->>Platform: Deduct credits from user
Credit creator account
Platform->>User: ExecutionResponse
(success, credits_charged, output)
Note over Platform,Creator: Credits transferred to creator
end
```
**Key Features:**
* **Pay-per-use model** - Users pay credits only for agent executions
* **Creator monetization** - Agent creators earn credits when their agents are used
* **Trust-based access** - Minimum trust levels prevent unauthorized or malicious usage
* **Transparent pricing** - Credit costs are known upfront via `AgentExecutionCost`
* **Transaction tracking** - Every execution generates a transaction record for auditing
**Use Cases:**
* Premium AI agents with specialized capabilities
* Resource-intensive data processing agents
* Enterprise agents requiring elevated permissions
* Marketplace for third-party agent services
* Usage-based billing for agent platforms
***
# Messages and parts
Source: https://docs.getbindu.com/bindu/protocol/messages-and-parts
Parts (TextPart, FilePart, DataPart), Message vs Artifact, and how content flows between agents.
Parts are the fundamental building blocks for agent communication in A2A. Here's how they work in practice:
### TextPart: Simple Text Communication
**Schema:**
```python theme={null}
class TextPart(TypedDict):
"""Represents a text segment within a message or artifact."""
kind: Literal["text"] # Discriminator, always "text"
text: str # The actual text content
metadata: NotRequired[dict[str, Any]] # Optional metadata for context
embeddings: NotRequired[list[float]] #The embeddings of Text.
```
**Use Case 1: User Instruction**
```json theme={null}
{
"kind": "text",
"text": "Analyze this image and highlight any faces."
}
```
**Use Case 2: Agent Status with Metadata**
```json theme={null}
{
"kind": "text",
"text": "Processing your request... Found 3 faces in the image.",
"metadata": {
"timestamp": "2025-10-31T10:00:00Z",
"confidence": 0.95,
"processingTime": "2.3s"
}
}
```
**What it's for:** Human-readable communication including instructions, status updates, error messages, and conversational text between agents and users.
***
### FilePart: Binary Content Exchange
**Schema:**
```python theme={null}
class FileWithBytes(TypedDict):
"""File representation with binary content."""
bytes: str # Base64-encoded file content
name: NotRequired[str] # File name (e.g., "document.pdf")
mimeType: NotRequired[str] # MIME type (e.g., "application/pdf")
embeddings: NotRequired[list[float]] #The embeddings of File.
class FileWithUri(TypedDict):
"""File representation with URI reference."""
uri: str # URL pointing to file content
name: NotRequired[str] # File name
mimeType: NotRequired[str] # MIME type
class FilePart(TypedDict):
"""Represents a file segment within a message or artifact."""
kind: Literal["file"] # Discriminator, always "file"
file: FileWithBytes | FileWithUri # File content (bytes or URI)
metadata: NotRequired[dict[str, Any]] # Optional metadata
embeddings: NotRequired[list[float]] #The embeddings of File.
```
**Use Case 1: Image Upload with Bytes (Client → Agent)**
```json theme={null}
{
"jsonrpc": "2.0",
"id": "req-007",
"method": "message/send",
"params": {
"message": {
"role": "user",
"parts": [
{
"kind": "text",
"text": "Analyze this image and highlight any faces."
},
{
"kind": "file",
"file": {
"name": "input_image.png",
"mimeType": "image/png",
"bytes": "iVBORw0KGgoAAAANSUhEUgAAAAUA..."
}
}
],
"messageId": "6dbc13b5-bd57-4c2b-b503-24e381b6c8d6"
}
}
}
```
**What it's for:** Binary content exchange including images, documents, media files, and data files. Use `bytes` for small files (\< 1MB), `uri` for large files to avoid payload bloat.
***
### DataPart: Structured Information Exchange
**Schema:**
```python theme={null}
class DataPart(TypedDict):
"""Represents a structured data segment (e.g., JSON) within a message or artifact."""
kind: Literal["data"] # Discriminator, always "data"
data: dict[str, Any] # Structured JSON data
metadata: NotRequired[dict[str, Any]] # Optional metadata
embeddings: NotRequired[list[float]] #The embeddings of Data.
```
**Use Case 1: Form Data Submission**
```json theme={null}
{
"kind": "data",
"data": {
"formType": "user_registration",
"fields": {
"username": "john_doe",
"email": "john@example.com",
"preferences": {
"newsletter": true,
"notifications": "daily"
}
},
"timestamp": "2025-10-31T10:00:00Z"
}
}
```
**What it's for:** Structured, machine-readable information including API responses, form data, query results, analytics, payment details, and any JSON-serializable data that needs programmatic processing.
***
### Key Takeaways: A2A Part Usage
**Part Types (A2A Standard):**
1. **TextPart** (`kind: "text"`): For conveying plain textual content
* Use for: Instructions, descriptions, status updates, conversational text
2. **FilePart** (`kind: "file"`): For conveying file-based content
* **FileWithBytes**: Small files provided as base64-encoded bytes
* **FileWithUri**: Large files referenced by URI
* Optional: `name` and `mimeType` fields
3. **DataPart** (`kind: "data"`): For conveying structured JSON data
* Use for: Forms, parameters, machine-readable information
* Data is a JSON object (`dict[str, Any]`)
**Common Features:**
* All parts support optional `metadata` field for additional context
* Parts can be used in both Messages and Artifacts
* Multiple parts can be combined in a single message
**Bindu Extensions** ``:
* `embeddings: list[float]` - Vector embeddings for semantic search and similarity
**Best Practices:**
* Use `bytes` for small files, `uri` for large files to avoid payload bloat
* Always specify `mimeType` for files to help agents process content correctly
* Use `metadata` for additional context (timestamps, confidence scores, error codes)
* Structure DataPart content with clear, consistent schemas
***
## Communication Types
### Message: Operational Communication
Messages are the primary way agents, users, and systems communicate during task execution. Unlike artifacts (which contain final results), messages carry operational content like instructions, status updates, and coordination.
**Schema:**
```python theme={null}
class Message(TypedDict):
"""Communication content exchanged between agents, users, and systems.
Messages represent all non-result communication in the bindu protocol.
Unlike Artifacts (which contain task outputs), Messages carry operational
content like instructions, status updates, context, and metadata.
Message Types:
- User Instructions: Task requests with context and files
- Agent Communication: Status updates, thoughts, coordination
- System Messages: Errors, warnings, protocol information
- Context Sharing: Background information, references, metadata
Multi-part Structure:
Messages can contain multiple parts to organize different content types:
- Text parts for instructions or descriptions
- File parts for context documents or references
- Data parts for structured metadata or parameters
Flow Pattern:
Client → Message (request) → Agent → Message (status) → Artifact (result)
"""
message_id: Required[UUID]
"""Identifier created by the message creator."""
context_id: Required[UUID]
"""The context the message is associated with."""
task_id: Required[UUID]
"""Identifier of task the message is related to."""
kind: Required[Literal["message"]]
"""The type discriminator, always "message"."""
role: Required[Literal["user", "agent", "system"]]
"""The role of the message sender."""
parts: Required[list[Part]]
"""The content parts of the message."""
metadata: NotRequired[dict[str, Any]]
"""Metadata associated with the message."""
reference_task_ids: NotRequired[list[UUID]]
"""List of identifiers of tasks that this message references."""
extensions: NotRequired[list[str]]
"""Array of extension URIs."""
```
**Message Roles:**
1. **user**: Messages from humans or client applications
* Task instructions and requests
* Follow-up questions
* Input responses
2. **agent**: Messages from AI agents
* Status updates ("Processing your request...")
* Thought processes and reasoning
* Coordination between agents
* Progress notifications
3. **system**: Protocol-level messages ``
* Error notifications
* Authentication warnings
* Protocol-level events
**Use Case 1: User Instruction with Context**
```json theme={null}
{
"messageId": "6dbc13b5-bd57-4c2b-b503-24e381b6c8d6",
"contextId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"taskId": "f9e8d7c6-b5a4-3210-9876-543210fedcba",
"kind": "message",
"role": "user",
"parts": [
{
"kind": "text",
"text": "Analyze this sales data and identify trends."
},
{
"kind": "file",
"file": {
"name": "sales_q4.csv",
"mimeType": "text/csv",
"uri": "https://example.com/files/sales_q4.csv"
}
}
],
"metadata": {
"priority": "high",
"deadline": "2025-11-01T00:00:00Z"
}
}
```
**What it's for:** Real-time communication during task execution including instructions, status updates, questions, coordination, and context sharing. Messages enable interactive, multi-turn conversations between users and agents.
***
### Artifact: Task Results
Artifacts are the **final, immutable outputs** produced by agents after completing work. Once created, they cannot be modified. Ensuring a permanent, trustworthy record of agent execution. They represent tangible deliverables like reports, generated code, processed files, or analysis results. Unlike messages (which are ephemeral communication), artifacts are the persistent, unchangeable products of agent work that can be reliably referenced, shared, and audited.
**Schema:**
```python theme={null}
class Artifact(TypedDict):
"""Represents the final output generated by an agent after completing a task.
Artifacts are immutable data structures that contain the results of agent execution.
They can contain multiple parts (text, files, structured data) and are uniquely
identified for tracking and retrieval.
A single task may produce multiple artifacts when the output naturally
separates into distinct deliverables (e.g., frontend + backend code).
"""
artifact_id: Required[UUID]
"""Unique identifier for the artifact."""
name: NotRequired[str]
"""Human-readable name of the artifact."""
description: NotRequired[str]
"""A description of the artifact."""
parts: NotRequired[list[Part]]
"""The content parts that make up the artifact."""
metadata: NotRequired[dict[str, Any]]
"""Metadata about the artifact."""
extensions: NotRequired[list[str]]
"""Array of extension URIs."""
append: NotRequired[bool]
"""Whether to append this artifact to an existing one. """
last_chunk: NotRequired[bool]
"""Whether this is the last chunk of the artifact. """
```
**Key Differences from Messages:**
* **Messages** = Operational communication during work (ephemeral)
* **Artifacts** = Final deliverable results after work (persistent)
**Use Case 1: Analysis Report Artifact**
```json theme={null}
{
"artifactId": "artifact-001",
"name": "Q4 Sales Analysis Report",
"description": "Comprehensive analysis of Q4 sales trends and patterns",
"parts": [
{
"kind": "text",
"text": "# Q4 Sales Analysis\n\n## Key Findings\n1. Revenue increased 23% compared to Q3\n2. Top performing region: West Coast (35% of total)\n3. Mobile sales grew 45% year-over-year\n\n## Recommendations\n- Increase inventory for top-selling products\n- Expand mobile marketing campaigns\n- Focus on West Coast market expansion"
},
{
"kind": "data",
"data": {
"summary": {
"totalRevenue": 2450000,
"growthRate": 0.23,
"topRegion": "West Coast",
"mobileGrowth": 0.45
},
"trends": [
{"month": "October", "revenue": 750000},
{"month": "November", "revenue": 820000},
{"month": "December", "revenue": 880000}
]
}
}
],
"metadata": {
"generatedAt": "2025-10-31T10:30:00Z",
"analysisType": "quarterly_sales",
"dataSource": "sales_q4.csv"
}
}
```
**What it's for:** Persistent, immutable deliverables that represent the completed work of an agent. Artifacts are the tangible outputs that users receive after task completion - reports, generated code, processed files, analysis results, or any final product of agent execution.
***
### Communication Flow Pattern
Understanding the relationship between Messages, Tasks, and Artifacts:
**Basic Task Execution Flow:**
```mermaid theme={null}
sequenceDiagram
participant Client
participant Server
participant Agent
Client->>Server: Send Message (user instruction)
Server->>Server: Create Task (state: submitted)
Server-->>Client: Task created
Server->>Agent: Process request
Note over Agent: Task state: working
Agent->>Agent: Generate result
Agent->>Server: Return Artifact
Server->>Server: Task state: completed
Server-->>Client: Task with Artifact
```
**Streaming Task Execution Flow:**
```mermaid theme={null}
sequenceDiagram
participant Client
participant Server
participant Agent
Client->>Server: message/stream
Server->>Server: Create Task (state: submitted)
Server-->>Client: SSE: status-update (submitted)
Server->>Agent: Process request
Note over Agent: Task state: working
Server-->>Client: SSE: status-update (working)
loop Artifact chunks
Agent->>Server: Artifact chunk
Server-->>Client: SSE: artifact-update (append: true)
end
Agent->>Server: Final chunk
Server-->>Client: SSE: artifact-update (append: false)
Server->>Server: Task state: completed
Server-->>Client: SSE: status-update (final: true)
```
**Multi-Turn Interaction Flow:**
```mermaid theme={null}
sequenceDiagram
participant Client
participant Server
participant Agent
Client->>Server: Send Message (initial request)
Server->>Server: Create Task (state: submitted)
Server->>Agent: Process request
Agent->>Server: Need more info
Server->>Server: Task state: input-required
Server-->>Client: Task + Agent Message (asking for clarification)
Client->>Server: Send Message (with taskId, providing input)
Server->>Agent: Resume with input
Note over Agent: Task state: working
Agent->>Server: Return Artifact
Server->>Server: Task state: completed
Server-->>Client: Task with Artifact
```
**Key Concepts:**
**Messages:**
* Carry instructions, context, and communication
* User messages initiate or continue tasks
* Agent messages provide status or request input
* Messages are part of the task's `history` array
**Tasks:**
* Central coordination unit tracking work lifecycle
* Created by server in response to user messages
* Contain status, history, and artifacts
* State transitions: `submitted` → `working` → `completed`
**Artifacts:**
* Final, immutable outputs attached to completed tasks
* Delivered as part of the task result
* Can be streamed in chunks for large outputs
* Multiple artifacts possible per task
**Example: Simple Question**
```json theme={null}
// Client sends message
{
"method": "message/send",
"params": {
"message": {
"role": "user",
"parts": [{"kind": "text", "text": "Analyze sales trends"}],
"messageId": "msg-001"
}
}
}
// Server responds with completed task
{
"result": {
"id": "task-001",
"contextId": "ctx-001",
"status": {"state": "completed"},
"artifacts": [{
"artifactId": "art-001",
"name": "Sales Analysis",
"parts": [{"kind": "text", "text": "Revenue increased 23%..."}]
}],
"history": [/* user message */],
"kind": "task"
}
}
```
***
# Agent negotiation
Source: https://docs.getbindu.com/bindu/protocol/negotiation
How two agents agree on price, latency, and SLA before doing work. Bindu-specific extension.
Agent-to-agent negotiation enables autonomous agents to coordinate, negotiate terms, and reach agreements for collaborative task execution. This protocol extension allows agents to propose, counter-propose, accept, or reject collaboration terms in a structured manner.
**Implementation status (2026-05): types only, no runtime endpoints.**
`NegotiationProposal`, `NegotiationContext`, `NegotiationStatus`, and `NegotiationSessionStatus` exist as TypedDicts/enums in [`bindu/common/protocol/types.py`](https://github.com/getbindu/Bindu/blob/main/bindu/common/protocol/types.py), but there are **no JSON-RPC methods** for `negotiation/*` and no server handlers driving the state transitions. The schemas are stable enough to plan against; the dispatch logic is not yet wired up.
Agents that need ad-hoc coordination today can carry these payloads inside `DataPart` content on regular `message/send` calls — the structure is well-defined, the routing is just up to your application.
### NegotiationProposal
A structured negotiation proposal exchanged between agents during the negotiation process.
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class NegotiationProposal(TypedDict):
"""Structured negotiation proposal exchanged between agents."""
proposal_id: Required[UUID]
"""The ID of the proposal."""
from_agent: Required[UUID]
"""The ID of the agent making the proposal."""
to_agent: Required[UUID]
"""The ID of the agent receiving the proposal."""
terms: Required[Dict[str, Any]]
"""The terms of the proposal."""
timestamp: Required[str]
"""The timestamp of the proposal."""
status: Required[NegotiationStatus]
"""The status of the proposal."""
```
**Example: Task Delegation Proposal**
```json theme={null}
{
"proposalId": "550e8400-e29b-41d4-a716-446655440000",
"fromAgent": "did:example:agent-1",
"toAgent": "did:example:agent-2",
"terms": {
"taskType": "data-processing",
"maxDurationMinutes": 30,
"costCredits": 100,
"priority": "high",
"deliverables": ["processed_data.csv", "analysis_report.pdf"]
},
"timestamp": "2025-10-31T10:00:00Z",
"status": "proposed"
}
```
**What it's for:** Enables agents to formally propose collaboration terms including task specifications, resource requirements, costs, and expected deliverables. Proposals can be accepted, rejected, or countered by the receiving agent.
***
### NegotiationContext
Context details for managing the complete lifecycle of agent-to-agent negotiations, including all participants and proposals.
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class NegotiationContext(TypedDict):
"""Context details for agent-to-agent negotiations."""
context_id: Required[UUID]
"""The ID of the context."""
status: Required[NegotiationStatus]
"""The status of the context."""
participants: Required[List[str]]
"""The participants in the context."""
proposals: Required[List[NegotiationProposal]]
"""The proposals in the context."""
```
**Example: Multi-Agent Negotiation Session**
```json theme={null}
{
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"status": "ongoing",
"participants": [
"did:example:agent-coordinator",
"did:example:agent-processor",
"did:example:agent-validator"
],
"proposals": [
{
"proposalId": "550e8400-e29b-41d4-a716-446655440000",
"fromAgent": "did:example:agent-coordinator",
"toAgent": "did:example:agent-processor",
"terms": {
"taskType": "data-processing",
"maxDurationMinutes": 30,
"costCredits": 100
},
"timestamp": "2025-10-31T10:00:00Z",
"status": "accepted"
},
{
"proposalId": "661f9511-f3ac-52e5-b827-557766551111",
"fromAgent": "did:example:agent-coordinator",
"toAgent": "did:example:agent-validator",
"terms": {
"taskType": "validation",
"maxDurationMinutes": 15,
"costCredits": 50
},
"timestamp": "2025-10-31T10:05:00Z",
"status": "proposed"
}
]
}
```
**What it's for:** Tracks the complete negotiation session between multiple agents, maintaining all proposals, counter-proposals, and the current negotiation status. Enables complex multi-party negotiations for collaborative task execution.
***
### Negotiation Flow Pattern
Understanding how agents negotiate and reach agreements:
**Basic Negotiation Flow:**
```mermaid theme={null}
sequenceDiagram
participant AgentA as Agent A
participant AgentB as Agent B
AgentA->>AgentA: Identify need for collaboration
AgentA->>AgentA: Create NegotiationContext
AgentA->>AgentB: Send NegotiationProposal
Note over AgentB: Status: proposed
AgentB->>AgentB: Evaluate proposal
alt Accept
AgentB->>AgentA: Accept (status: accepted)
Note over AgentA,AgentB: Task execution begins
else Reject
AgentB->>AgentA: Reject (status: rejected)
Note over AgentA,AgentB: Negotiation ends
else Counter
AgentB->>AgentA: Counter (status: countered)
Note over AgentA: Evaluate counter-proposal
AgentA->>AgentB: Response (accept/reject/counter)
end
```
**Multi-Agent Negotiation Flow:**
```mermaid theme={null}
sequenceDiagram
participant Coord as Coordinator
participant AgentA as Agent A
participant AgentB as Agent B
participant AgentC as Agent C
Coord->>Coord: Initiate NegotiationContext
Note over Coord: Identify required specialists
par Parallel negotiation tracks
Coord->>AgentA: Send Proposal
Coord->>AgentB: Send Proposal
Coord->>AgentC: Send Proposal
end
par Independent responses
AgentA-->>Coord: Accept
AgentB-->>Coord: Counter-proposal
AgentC-->>Coord: Reject
end
Coord->>Coord: Evaluate responses
Note over Coord: Adjust terms based on feedback
Coord->>AgentB: Send counter-proposal
AgentB-->>Coord: Accept
Note over Coord,AgentC: All required agents accepted
Note over Coord,AgentC: Collaborative task execution begins
```
**Negotiation Statuses (Individual Proposals):**
* **`proposed`** - Initial offer made, awaiting response
* **`accepted`** - Offer accepted, ready to proceed
* **`rejected`** - Offer declined, negotiation path closed
* **`countered`** - Counter-offer made, negotiation continues
**Session Statuses (Overall Context):**
* **`initiated`** - Negotiation session started
* **`ongoing`** - Active negotiation in progress
* **`completed`** - Agreement reached, all parties aligned
* **`rejected`** - Negotiation failed, no agreement possible
***
# Push notifications
Source: https://docs.getbindu.com/bindu/protocol/notifications
Webhook configuration so callers stop polling once a long-running task starts moving.
Push notification configurations define how servers send real-time updates to clients outside of active sessions. Bindu supports multiple notification patterns following the [A2A Protocol specification](https://a2a-protocol.org/latest/specification/).
### PushNotificationConfig
Defined in [`bindu/common/protocol/types.py:397`](https://github.com/getbindu/Bindu/blob/main/bindu/common/protocol/types.py#L397).
**Schema (exact):**
```python theme={null}
@pydantic.with_config(A2A_MODEL_CONFIG)
class PushNotificationConfig(TypedDict):
"""Configuration for push notifications.
When the server needs to notify the client of an update outside of a connected session.
"""
id: Required[UUID]
"""The ID of the push notification configuration."""
url: Required[str]
"""The URL of the push notification configuration."""
token: NotRequired[str]
"""The token of the push notification configuration."""
authentication: NotRequired[SecurityScheme]
"""The authentication of the push notification configuration."""
```
The `authentication` field is a [`SecurityScheme`](./security) — the same discriminated union used for inbound auth on the agent. This is a deliberate choice: the agent declares how *it* will authenticate to your webhook using the same vocabulary you'd use to declare how callers authenticate to it.
**Use Case: Webhook with bearer-token auth (`SecurityScheme` form)**
```json theme={null}
{
"id": "8f0b6df8-1f1e-4b2d-9b0a-6c5e7e4d3a2b",
"url": "https://client.example.com/webhook/notifications",
"token": "secure-webhook-token",
"authentication": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
"description": "Server-issued JWT for this webhook audience"
}
}
```
**Use Case: Webhook with API-key auth**
```json theme={null}
{
"id": "8f0b6df8-1f1e-4b2d-9b0a-6c5e7e4d3a2b",
"url": "https://client.example.com/webhook/notifications",
"authentication": {
"type": "apiKey",
"name": "X-Webhook-Key",
"in": "header"
}
}
```
**What it's for:** Configuring push notification endpoints where the server can send real-time updates to clients outside of active sessions. Used for notifying clients about task state changes, completion events, or errors without requiring constant polling.
***
### PushNotificationAuthenticationInfo
Defined in [`bindu/common/protocol/types.py:417`](https://github.com/getbindu/Bindu/blob/main/bindu/common/protocol/types.py#L417).
This type exists in the schema as an A2A-spec-compatibility shape, but `PushNotificationConfig.authentication` is typed as [`SecurityScheme`](./security), **not** `PushNotificationAuthenticationInfo`. Use `SecurityScheme` when sending a config; treat this type as informational.
**Schema:**
```python theme={null}
@pydantic.with_config(A2A_MODEL_CONFIG)
class PushNotificationAuthenticationInfo(TypedDict):
"""Authentication information for push notifications."""
schemes: list[str]
"""A list of supported authentication schemes (e.g., 'Basic', 'Bearer')."""
credentials: NotRequired[str]
"""Optional credentials required by the push notification endpoint."""
```
***
### TaskPushNotificationConfig
Defined in [`bindu/common/protocol/types.py:428`](https://github.com/getbindu/Bindu/blob/main/bindu/common/protocol/types.py#L428).
**Schema (exact):**
```python theme={null}
@pydantic.with_config(A2A_MODEL_CONFIG)
class TaskPushNotificationConfig(TypedDict):
"""Configuration for task push notifications."""
id: Required[UUID]
"""The ID of the task push notification configuration."""
push_notification_config: Required[PushNotificationConfig]
"""The push notification configuration of the task push notification configuration."""
long_running: NotRequired[bool]
"""Flag indicating task expects to run longer than typical request timeouts.
When True, the push_notification_config should be persisted for notifications
across server restarts. Defaults to False if not specified.
"""
```
The top-level `id` here is the **task ID** that this notification config is bound to — *not* a separate config identifier. The field is `id`, not `taskId`.
**Use Case: Long-running task with persistent webhook**
```json theme={null}
{
"id": "43667960-d455-4453-b0cf-1bae4955270d",
"longRunning": true,
"pushNotificationConfig": {
"id": "8f0b6df8-1f1e-4b2d-9b0a-6c5e7e4d3a2b",
"url": "https://client.example.com/webhook/a2a-notifications",
"token": "secure-client-token-for-task-aaa",
"authentication": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
}
```
**What it's for:** Associating specific tasks with push notification configurations. Setting `longRunning: true` tells the server to persist the webhook configuration across restarts so notifications still fire when the task finally completes. Wired through the JSON-RPC methods `tasks/pushNotificationConfig/{set,get,list,delete}` ([`settings.py:445-448`](https://github.com/getbindu/Bindu/blob/main/bindu/settings.py)).
### How Push Notifications Work
**Workflow:**
1. **Client configures** push notifications when sending a message via `message/send`
2. **Server acknowledges** the task and begins processing
3. **Server completes** the task and POSTs notification to the client's webhook URL
4. **Client validates** the notification using the token and authentication
5. **Client processes** the task update (e.g., updates UI, notifies user)
**Notification Delivery:**
When a task state changes, the server sends an HTTP POST to the configured webhook URL:
```http theme={null}
POST /webhook/a2a-notifications HTTP/1.1
Host: client.example.com
Authorization: Bearer
Content-Type: application/json
X-A2A-Notification-Token: secure-client-token-for-task-aaa
{
"id": "43667960-d455-4453-b0cf-1bae4955270d",
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"status": {
"state": "completed",
"timestamp": "2024-03-15T18:30:00Z"
},
"kind": "task"
}
```
### Summary
Push notifications solve a simple problem: instead of constantly asking "Is it done yet?", the agent calls you when it's finished.
```mermaid theme={null}
sequenceDiagram
participant Client
participant Agent
participant Webhook as Client Webhook
Client->>Agent: Send task + PushNotificationConfig
Note over Client,Agent: url, token, authentication
Agent-->>Client: Task accepted (submitted)
Note over Agent: Processing...
(hours/minutes)
Agent->>Webhook: POST /webhook
X-A2A-Notification-Token: token
Task completed
Webhook-->>Agent: 200 OK
Note over Webhook: Update UI, notify user
```
You configure a **PushNotificationConfig** with your webhook URL and token—like giving the agent your callback number. Add **PushNotificationAuthenticationInfo** to specify how the agent should authenticate when calling your webhook. Use **TaskPushNotificationConfig** to route different tasks to different endpoints with their own security requirements.
This eliminates polling overhead and enables real-time updates for long-running operations—report generation, batch processing, or workflows needing human confirmation.
***
# Protocol reference
Source: https://docs.getbindu.com/bindu/protocol/overview
Every type, enum, and message Bindu speaks. Split by topic so you don't have to scroll past 4,000 lines to find the one you need.
This section is the type-level truth. If you want to know what a `Task` looks like on the wire, what states it can be in, or what an `AgentCard` actually contains, the answer is on one of the pages below.
## What Bindu speaks
Bindu follows two open protocols and adds a handful of its own extensions.
| Protocol | Version | What it covers |
| ---------------------------------------------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------- |
| **[A2A](https://github.com/a2aproject/A2A) (Agent-to-Agent)** | v0.3.0 | The base layer — messages, tasks, agent cards, push notifications. Everything you need for one agent to call another. |
| **[AP2](https://github.com/google-agentic-commerce/AP2) (Agent Protocol 2)** | v0.1.0 | Payment mandates and the trust framework that lets agents transact without a human in the loop. |
| **Bindu extensions** | — | Negotiation, credit accounting, trust levels. Marked `` everywhere they appear. |
If you only read one page, read [Tasks and lifecycle](/bindu/protocol/tasks) — task state is the spine the rest of the protocol hangs off.
## Pages
TaskState, TrustLevel, NegotiationStatus, IdentityProvider. The vocabulary.
TextPart, FilePart, DataPart, Message vs Artifact — the shapes content can take.
The Task object, its status, and how it moves between states.
ContextId, history sessions, multi-turn conversations.
Price, latency, SLA agreed up front. Bindu-specific.
Auth schemes and how agents prove they're allowed.
Webhook on task state change. Stop polling.
AP2 payment models and the mandate trust framework.
Bindu's credit accounting layer next to x402.
TrustLevel, IdentityProvider, DID verification.
AgentCard, AgentCapabilities, AgentInterface. How clients find you.
This is a reference, not a tutorial. If you're trying to build an agent for the first time, go to [Your first agent](/bindu/get-started/your-first-agent) instead — you won't need most of this until you're three steps deeper.
# Payments (x402)
Source: https://docs.getbindu.com/bindu/protocol/payment
How a Bindu agent demands stablecoin payment before doing work — via the x402 HTTP-402 extension.
**What ships today.** Bindu's payment layer is the [x402 protocol](https://github.com/google-a2a/a2a-x402) — a stablecoin paywall over HTTP 402, originally from Coinbase, formalized as an A2A extension. The W3C Payment Request shapes (`PaymentMandate`, `IntentMandate`, `CartMandate`, etc.) sometimes referenced in AP2 drafts are **not implemented** in this codebase. If you find references to them anywhere in Bindu, treat those references as spec sketches rather than runtime types.
x402 lets a server respond with HTTP 402 plus a structured `paymentRequirements` payload, the client signs an EIP-3009 transfer-with-authorization, and the server forwards the signed payload to a facilitator that verifies signature + balance + replay. Settlement happens on-chain when the task completes.
Concretely, in Bindu:
* **Default network:** `base-sepolia` (Base Sepolia testnet)
* **Default token:** USDC
* **Default facilitator:** `https://x402.org/facilitator` (Coinbase-hosted)
* **Default protected method:** JSON-RPC `message/send`
* **Extension URI:** `https://github.com/google-a2a/a2a-x402/v0.1`
All of this is configurable via [`X402Settings`](https://github.com/getbindu/Bindu/blob/main/bindu/settings.py).
***
## Declaring payment on an agent
Add an `execution_cost` block to your agent config. Source: [`examples/beginner/agno_paywall_example.py`](https://github.com/getbindu/Bindu/blob/main/examples/beginner/agno_paywall_example.py):
```python theme={null}
from bindu.penguin.bindufy import bindufy
config = {
"author": "your.email@example.com",
"name": "research_agent_paywall",
"description": "A research assistant agent gated by x402 payment",
"deployment": {
"url": "http://localhost:3775",
"expose": True,
},
"execution_cost": {
"amount": "$0.0001", # USD string or atomic units
"token": "USDC",
"network": "base-sepolia",
"pay_to_address": "0x2654bb8B272f117c514aAc3d4032B1795366BA5d",
"protected_methods": ["message/send"],
},
}
def handler(messages):
...
bindufy(config, handler)
```
What each field means — see [`X402AgentExtension.__init__`](https://github.com/getbindu/Bindu/blob/main/bindu/extensions/x402/x402_agent_extension.py):
| Field | Required | Notes |
| ------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `amount` | yes (if no `payment_options`) | Either a USD string (`"$0.0001"`) or atomic units as a string (`"1000000"` = 1 USDC). |
| `token` | no (default `"USDC"`) | Token symbol the facilitator knows about. |
| `network` | no (default `"base-sepolia"`) | Any network the configured facilitator advertises. See `extra_networks` below for adding custom ones. |
| `pay_to_address` | yes (when payment is required) | EVM address that receives the funds. Required when `required=True`. |
| `protected_methods` | no | JSON-RPC methods that demand payment. Default `["message/send"]` from [`settings.py:378-381`](https://github.com/getbindu/Bindu/blob/main/bindu/settings.py). |
| `payment_options` | no | A list of dicts for multi-network / multi-token offers. The first entry becomes the primary; the full list is published as payment requirements. |
You can also offer multiple payment options:
```python theme={null}
"execution_cost": {
"payment_options": [
{"amount": "$0.0001", "token": "USDC", "network": "base-sepolia",
"pay_to_address": "0x2654..."},
{"amount": "$0.0001", "token": "USDC", "network": "skale-europa",
"pay_to_address": "0x2654..."},
],
"protected_methods": ["message/send"],
}
```
***
## The request/response flow
```mermaid theme={null}
sequenceDiagram
participant Client
participant Agent as Bindu Agent
participant Facilitator as x402 Facilitator
participant Chain as Base / EVM
Client->>Agent: POST / { "method": "message/send", ... }
Note over Client,Agent: No X-PAYMENT header
Agent-->>Client: 402 Payment Required
{ accepts: [PaymentRequirements...] }
Client->>Client: Build EIP-3009
"transferWithAuthorization" payload
(USDC.transfer, nonce, validBefore)
Client->>Client: Sign with payer key
Client->>Agent: POST /
X-PAYMENT: base64(payload)
X-A2A-Extensions: …/a2a-x402/v0.1
Agent->>Agent: Parse + match a requirement
Agent->>Agent: Claim (network, asset, nonce) in NonceStore
(replay prevention BEFORE facilitator)
Agent->>Facilitator: POST /verify { payload, requirement }
Facilitator->>Chain: Recover signer + check balance
Chain-->>Facilitator: ok
Facilitator-->>Agent: { is_valid: true, payer: 0x… }
Agent->>Agent: Attach payment context to request.state
(payment_payload, requirements, verify_response)
Agent-->>Client: 200 OK (JSON-RPC response)
Note over Agent,Chain: Settlement happens at task completion
```
This is implemented in [`bindu/server/middleware/x402/x402_middleware.py`](https://github.com/getbindu/Bindu/blob/main/bindu/server/middleware/x402/x402_middleware.py). The order — **claim nonce before facilitator verify** — is deliberate: replays cost zero facilitator round-trips, and we never rely on the on-chain contract to reject replays.
***
## Headers
### `X-A2A-Extensions` (activation)
Clients that want x402 to *engage* echo the extension URI on their request:
```http theme={null}
X-A2A-Extensions: https://github.com/google-a2a/a2a-x402/v0.1
```
The server confirms activation by echoing the same header on the response. Helper: [`X402ActivationHandler`](https://github.com/getbindu/Bindu/blob/main/bindu/extensions/x402/extension.py).
### `X-PAYMENT` (the signed payload)
The serialized x402 `PaymentPayload`, base64-encoded:
```http theme={null}
X-PAYMENT: eyJ4NDAyVmVyc2lvbiI6Mi…
```
The decoded payload is a JSON object the x402 SDK parses via `parse_payment_payload`. v1 payloads are explicitly rejected — only v2 (signed EIP-3009) is accepted.
***
## Payment-related task states
x402 introduces task states beyond standard A2A. From [`X402Settings`](https://github.com/getbindu/Bindu/blob/main/bindu/settings.py#L390-L395):
| State | Meaning |
| ------------------- | ------------------------------------------------------------------- |
| `payment-required` | Server returned 402; client must sign and re-send with `X-PAYMENT`. |
| `payment-submitted` | Client posted an `X-PAYMENT` header; verification is in flight. |
| `payment-verified` | Facilitator returned `is_valid: true`; task proceeds to execution. |
| `payment-completed` | Task finished; on-chain settlement receipt recorded. |
| `payment-failed` | Verification or settlement failed; receipt or error in metadata. |
These are written to `Task.metadata` under well-known keys ([`settings.py:384-388`](https://github.com/getbindu/Bindu/blob/main/bindu/settings.py)):
```python theme={null}
meta_status_key = "x402.payment.status"
meta_required_key = "x402.payment.required"
meta_payload_key = "x402.payment.payload"
meta_receipts_key = "x402.payment.receipts"
meta_error_key = "x402.payment.error"
```
Helpers in [`bindu/extensions/x402/utils.py`](https://github.com/getbindu/Bindu/blob/main/bindu/extensions/x402/utils.py) build these dicts:
```python theme={null}
def build_payment_completed_metadata(receipt: dict) -> dict[str, Any]:
return {
app_settings.x402.meta_status_key: app_settings.x402.status_completed,
app_settings.x402.meta_receipts_key: [receipt],
}
```
A completed task ends up with metadata roughly like:
```json theme={null}
{
"x402.payment.status": "payment-completed",
"x402.payment.receipts": [
{
"network": "base-sepolia",
"asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"tx_hash": "0x…",
"payer": "0x…",
"amount": "100"
}
]
}
```
(The exact receipt shape comes from the facilitator response.)
***
## 402 response shape (what your client gets)
When payment is missing or invalid, the middleware returns HTTP 402 with a JSON body the x402 SDK can consume. The minimal contract:
```json theme={null}
{
"x402Version": 2,
"accepts": [
{
"scheme": "exact",
"network": "base-sepolia",
"asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"maxAmountRequired": "100",
"payTo": "0x2654bb8B272f117c514aAc3d4032B1795366BA5d",
"maxTimeoutSeconds": 600,
"resource": "/",
"mimeType": "application/json",
"description": "…"
}
],
"error": "X-PAYMENT header required"
}
```
The `accepts` array contains every `PaymentRequirements` your agent published — one per entry in `payment_options` (or one synthesized from the single `amount`/`token`/`network`).
***
## Configuring the facilitator and networks
The Coinbase default (`https://x402.org/facilitator`) supports Base mainnet and Base Sepolia out of the box. For other EVM networks the SDK doesn't know about, add an entry to `X402Settings.extra_networks`:
```python theme={null}
from bindu.settings import ExtraNetwork
X402Settings.extra_networks = {
"skale-europa": ExtraNetwork(
caip2="eip155:1187947933",
asset="0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",
asset_symbol="USDC",
asset_name="Bridged USDC (SKALE Bridge)",
),
}
```
The facilitator must also know the network. The Coinbase default does **not** support SKALE today — point `facilitator_url` at one that does (e.g. `https://facilitator.x402.fi`).
All knobs are environment-driven (`X402__FACILITATOR_URL`, `X402__DEFAULT_NETWORK`, …) — see the `env_prefix="X402__"` on [`X402Settings`](https://github.com/getbindu/Bindu/blob/main/bindu/settings.py#L358).
***
## What's not in this implementation
So you know where the boundaries are:
* No `PaymentRequest` / `PaymentResponse` / `PaymentMandate` / `IntentMandate` / `CartMandate` types — those AP2 shapes don't exist as Python types in this repo. If you've seen them in older Bindu docs, they were spec sketches.
* No multi-currency fiat support — payments are stablecoin transfers on EVM chains via x402.
* No subscription model — every protected call is a one-shot payment authorization. Long-running tasks bind one payment to one task ID; renewals are not handled by the protocol.
* Settlement currently happens at task completion. There is no partial-credit / metered billing within a single task.
If you need one of these and want to discuss adding it, [open an issue](https://github.com/getbindu/Bindu/issues/new/choose).
# Security and authentication
Source: https://docs.getbindu.com/bindu/protocol/security
Authentication schemes, security definitions, and how agents prove they're allowed to do what they're doing.
Security schemes define how agents authenticate requests and establish trust. Bindu supports multiple authentication methods following the [A2A Protocol specification](https://a2a-protocol.org/latest/specification/).
### HTTPAuthSecurityScheme
**Schema:**
```python theme={null}
class HTTPAuthSecurityScheme(TypedDict):
"""HTTP security scheme supporting various authentication methods.
Supports standard HTTP authentication schemes including Basic, Bearer,
Digest, and custom schemes. Commonly used for token-based authentication
with JWTs or other bearer token formats.
"""
type: Required[Literal["http"]]
"""The type of the security scheme. Always "http"."""
scheme: Required[str]
"""The HTTP authentication scheme (e.g., "basic", "bearer", "digest")."""
bearer_format: NotRequired[str]
"""Format hint for bearer tokens (e.g., "JWT")."""
description: NotRequired[str]
"""Human-readable description of the security scheme."""
```
**Use Case 1: Bearer Token with JWT**
```json theme={null}
{
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
"description": "JWT bearer token authentication for API access"
}
```
**Use Case 2: Basic Authentication**
```json theme={null}
{
"type": "http",
"scheme": "basic",
"description": "HTTP Basic authentication with username and password"
}
```
**What it's for:** Token-based authentication using standard HTTP authentication schemes. Most commonly used with Bearer tokens (JWT) for stateless API authentication, but also supports Basic auth for simple username/password scenarios.
***
### APIKeySecurityScheme
**Schema:**
```python theme={null}
class APIKeySecurityScheme(TypedDict):
"""API Key security scheme for key-based authentication.
Supports passing API keys through query parameters, HTTP headers, or
cookies. Commonly used for simple service-to-service authentication
or public API access control.
"""
type: Required[Literal["apiKey"]]
"""The type of the security scheme. Always "apiKey"."""
name: Required[str]
"""The name of the header, query parameter, or cookie."""
in_: Required[Literal["query", "header", "cookie"]]
"""Location of the API key: "query", "header", or "cookie"."""
description: NotRequired[str]
"""Human-readable description of the security scheme."""
```
**Use Case 1: Header-based API Key**
```json theme={null}
{
"type": "apiKey",
"name": "X-API-Key",
"in": "header",
"description": "API key passed in custom X-API-Key header"
}
```
**What it's for:** Simple key-based authentication where a static or rotating API key is passed in requests. Ideal for service-to-service communication, webhook authentication, or public API rate limiting and access control.
***
### OAuth2SecurityScheme
**Schema:**
```python theme={null}
class OAuth2SecurityScheme(TypedDict):
"""OAuth2 security scheme for delegated authorization.
Supports multiple OAuth 2.0 flows including authorization code, implicit,
password credentials, and client credentials. Used for secure delegated
access where users authorize agents to act on their behalf.
"""
type: Required[Literal["oauth2"]]
"""The type of the security scheme. Always "oauth2"."""
flows: Required[dict[str, Any]]
"""OAuth2 flow configurations. Supported flows:
- authorizationCode: Authorization code flow (most secure)
- implicit: Implicit flow (browser-based)
- password: Resource owner password credentials flow
- clientCredentials: Client credentials flow (service-to-service)
"""
description: NotRequired[str]
"""Human-readable description of the security scheme."""
```
**Use Case 1: Authorization Code Flow (User Authorization)**
```json theme={null}
{
"type": "oauth2",
"flows": {
"authorizationCode": {
"authorizationUrl": "https://auth.example.com/oauth/authorize",
"tokenUrl": "https://auth.example.com/oauth/token",
"scopes": {
"read": "Read access to user data",
"write": "Write access to user data",
"admin": "Administrative access"
}
}
},
"description": "OAuth2 authorization code flow for user-delegated access"
}
```
**What it's for:** Delegated authorization where agents need to access resources on behalf of users or other services. Authorization code flow is used when users need to grant permission, while client credentials flow is used for direct service-to-service authentication without user involvement.
***
### OpenIdConnectSecurityScheme
**Schema:**
```python theme={null}
class OpenIdConnectSecurityScheme(TypedDict):
"""OpenID Connect security scheme for identity authentication.
Built on top of OAuth 2.0, OpenID Connect adds an identity layer for
user authentication. Uses discovery documents for automatic configuration
of endpoints and supported features.
"""
type: Required[Literal["openIdConnect"]]
"""The type of the security scheme. Always "openIdConnect"."""
open_id_connect_url: Required[str]
"""URL to the OpenID Connect discovery document.
Typically: https://auth.example.com/.well-known/openid-configuration
"""
description: NotRequired[str]
"""Human-readable description of the security scheme."""
```
**Use Case: Enterprise SSO with OpenID Connect**
```json theme={null}
{
"type": "openIdConnect",
"openIdConnectUrl": "https://auth.example.com/.well-known/openid-configuration",
"description": "OpenID Connect authentication with automatic discovery for enterprise SSO"
}
```
**What it's for:** Identity authentication using OpenID Connect, typically for enterprise single sign-on (SSO) scenarios. The discovery URL automatically configures authentication endpoints, supported scopes, and token formats, making it easier to integrate with identity providers like Keycloak, Azure AD, or Okta.
***
### MutualTLSSecurityScheme
**Implementation status (2026-05): schema only, transport not yet deployed.**
The `MutualTLSSecurityScheme` TypedDict ships and can be advertised in an agent card, but Bindu does **not yet terminate mTLS at the transport layer** in production. The supporting code (`bindu/extensions/mtls/` — `step_ca_client.py`, `cert_store.py`, `mtls_agent_extension.py`) targets a Smallstep `step-ca` certificate authority and is gated behind Hydra audience-whitelisting work that hasn't shipped. See `docs/MTLS_DEPLOYMENT_GUIDE.md` for the design. Until that lands, treat this scheme as forward-looking — safe to declare, not yet enforced.
**Schema:**
```python theme={null}
class MutualTLSSecurityScheme(TypedDict):
"""Mutual TLS security scheme for certificate-based authentication.
Uses client certificates for mutual authentication where both client
and server verify each other's identity. Provides strong cryptographic
authentication for high-security service-to-service communication.
"""
type: Required[Literal["mutualTLS"]]
"""The type of the security scheme. Always "mutualTLS"."""
description: NotRequired[str]
"""Human-readable description of the security scheme."""
```
**Use Case: High-Security Service Communication**
```json theme={null}
{
"type": "mutualTLS",
"description": "Client certificate authentication for secure service-to-service communication"
}
```
**What it's for:** High-security authentication using client certificates where both parties verify each other's identity through TLS. Commonly used in zero-trust architectures, financial services, healthcare systems, or any scenario requiring strong cryptographic authentication without relying on passwords or tokens.
***
### SecurityScheme: Union Type
The `SecurityScheme` type is a discriminated union of all security scheme types:
```python theme={null}
SecurityScheme = Annotated[
Union[
HTTPAuthSecurityScheme,
APIKeySecurityScheme,
OAuth2SecurityScheme,
OpenIdConnectSecurityScheme,
MutualTLSSecurityScheme,
],
Discriminator("type"),
]
```
The `type` field acts as a discriminator to determine which security scheme is being used. All security schemes use camelCase for field names (e.g., `bearerFormat`, `openIdConnectUrl`) following the A2A Protocol specification.
### Choosing the Right Security Scheme
**Quick Reference:**
| Scheme | Best For | Complexity | Security Level |
| -------------------------- | ------------------------------------- | ---------- | -------------- |
| **HTTP Auth (Bearer)** | API tokens, JWTs | Low | Medium-High |
| **HTTP Auth (Basic)** | Simple username/password | Very Low | Low-Medium |
| **API Key** | Service-to-service, webhooks | Very Low | Low-Medium |
| **OAuth2** | User authorization, delegated access | High | High |
| **OpenID Connect** | Enterprise SSO, identity verification | Medium | High |
| **Mutual TLS** *(planned)* | Zero-trust, high-security services | High | Very High |
**Decision Guide:**
* **Need simple token authentication?** → Use HTTP Auth with Bearer tokens (JWT)
* **Building a public API?** → Use API Key for rate limiting and access control
* **Users need to authorize agents?** → Use OAuth2 Authorization Code flow
* **Service-to-service without users?** → Use OAuth2 Client Credentials or API Key
* **Enterprise SSO integration?** → Use OpenID Connect
* **Maximum security required?** → Mutual TLS is the planned answer (see warning above); until it ships, layer OAuth2 client-credentials over TLS at the network edge
* **Legacy system with Basic auth?** → Use HTTP Auth with Basic scheme
**Security Best Practices:**
* Always use HTTPS/TLS for all authentication schemes except Mutual TLS (which provides its own transport security)
* Rotate API keys regularly and never commit them to version control
* Use short-lived tokens (15-60 minutes) with refresh token rotation for OAuth2
* Implement rate limiting regardless of authentication method
* Log authentication attempts and monitor for suspicious patterns
* Use the principle of least privilege - grant only necessary scopes/permissions
***
# Tasks and lifecycle
Source: https://docs.getbindu.com/bindu/protocol/tasks
Task object, status, state transitions, and the events agents emit during execution.
Tasks are the fundamental coordination mechanism in the A2A protocol. They represent stateful execution units that manage the complete lifecycle of work from client request to agent completion. Every interaction between a client and an agent is organized around tasks.
### Task Object
A **Task** is the central coordination unit that tracks work execution. It encapsulates the entire interaction related to a specific goal or request, maintaining conversation history, execution state, and generated artifacts.
**Schema:**
```python theme={null}
class Task(TypedDict):
"""Stateful execution unit coordinating client-agent interaction.
Tasks serve as the primary coordination mechanism in the bindu protocol,
managing the complete lifecycle from request to completion. They maintain
conversation history, track execution state, and collect generated artifacts.
Core Responsibilities:
- Message Exchange: Facilitate communication between clients and agents
- State Management: Track task progress and execution status
- Artifact Collection: Gather and organize agent-generated outputs
- History Tracking: Maintain complete conversation and decision trail
Task Lifecycle:
1. Creation: Client initiates task with initial message/requirements
2. Processing: Agent processes messages and updates status
3. Communication: Bidirectional message exchange as needed
4. Artifact Generation: Agent produces deliverable outputs
5. Completion: Final status update and artifact delivery
Key Properties:
- Client-Initiated: Always created by clients, never by agents
- Agent-Controlled: Status and progress determined by executing agent
- Stateful: Maintains complete execution context and history
- Traceable: Unique ID enables task tracking and reference
"""
id: Required[UUID]
"""Unique identifier for the task, generated by the server."""
context_id: Required[UUID]
"""The context this task belongs to for session management."""
kind: Required[Literal["task"]]
"""Type discriminator, always "task"."""
status: Required[TaskStatus]
"""Current status including state, timestamp, and optional message."""
artifacts: NotRequired[list[Artifact]]
"""Collection of outputs generated during task execution."""
history: NotRequired[list[Message]]
"""Complete conversation history for this task."""
metadata: NotRequired[dict[str, Any]]
"""Optional metadata for extensions and custom data."""
```
**Realistic Example: Data Analysis Task**
A client requests sales data analysis. The task tracks the entire interaction:
```json theme={null}
{
"id": "363422be-b0f9-4692-a24d-278670e7c7f1",
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"kind": "task",
"status": {
"state": "completed",
"timestamp": "2025-10-31T10:35:00Z",
"message": {
"messageId": "status-msg-001",
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"kind": "message",
"role": "agent",
"parts": [
{
"kind": "text",
"text": "Analysis complete. Identified 3 key trends and generated comprehensive report."
}
]
}
},
"artifacts": [
{
"artifactId": "9b6934dd-37e3-4eb1-8766-962efaab63a1",
"name": "Q4 Sales Analysis Report",
"description": "Comprehensive analysis of Q4 sales trends",
"parts": [
{
"kind": "text",
"text": "# Q4 Sales Analysis\n\n## Executive Summary\nRevenue increased 23% compared to Q3, driven primarily by mobile sales growth of 45% year-over-year.\n\n## Key Findings\n1. **Revenue Growth**: Total revenue reached $2.45M, up 23% from Q3\n2. **Regional Performance**: West Coast dominated with 35% of total sales\n3. **Mobile Surge**: Mobile channel grew 45% YoY, now 28% of total revenue\n\n## Recommendations\n- Increase inventory allocation for top-performing products\n- Expand mobile marketing campaigns in Q1\n- Focus expansion efforts on West Coast market"
},
{
"kind": "data",
"data": {
"summary": {
"totalRevenue": 2450000,
"growthRate": 0.23,
"topRegion": "West Coast",
"mobileGrowth": 0.45
},
"monthlyTrends": [
{"month": "October", "revenue": 750000, "growth": 0.18},
{"month": "November", "revenue": 820000, "growth": 0.21},
{"month": "December", "revenue": 880000, "growth": 0.27}
],
"topProducts": [
{"name": "Premium Widget", "revenue": 450000, "units": 1200},
{"name": "Standard Widget", "revenue": 380000, "units": 2500}
]
}
}
],
"metadata": {
"generatedAt": "2025-10-31T10:35:00Z",
"analysisType": "quarterly_sales",
"dataPoints": 15000
}
}
],
"history": [
{
"messageId": "9229e770-767c-417b-a0b0-f0741243c589",
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"kind": "message",
"role": "user",
"parts": [
{
"kind": "text",
"text": "Analyze Q4 sales data and identify key trends"
},
{
"kind": "file",
"file": {
"name": "sales_q4_2025.csv",
"mimeType": "text/csv",
"uri": "https://storage.example.com/data/sales_q4_2025.csv"
}
}
],
"metadata": {
"priority": "high",
"deadline": "2025-11-01T00:00:00Z"
}
},
{
"messageId": "agent-msg-001",
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"kind": "message",
"role": "agent",
"parts": [
{
"kind": "text",
"text": "Processing sales data... Analyzing 15,000 transactions across 3 months."
}
],
"metadata": {
"timestamp": "2025-10-31T10:30:15Z",
"processingStage": "data_loading"
}
}
],
"metadata": {
"estimatedDuration": "5 minutes",
"priority": "high",
"tags": ["analytics", "sales", "quarterly-report"]
}
}
```
**What This Example Shows:**
* **Task Identity**: Unique `id` and `contextId` for tracking
* **Status Tracking**: Current state (`completed`) with timestamp and agent message
* **Artifact Delivery**: Complete analysis report with both text and structured data
* **History Preservation**: Full conversation trail from initial request to completion
* **Metadata Context**: Additional information about priority, duration, and categorization
***
### TaskStatus Object
Represents the current state and context of a task at a specific point in time.
**Schema:**
```python theme={null}
class TaskStatus(TypedDict):
"""Status information for a task at a specific moment.
TaskStatus captures the current execution state along with contextual
information like timestamps and optional status messages from the agent.
"""
state: Required[TaskState]
"""Current lifecycle state of the task."""
message: NotRequired[Message]
"""Optional message providing status details or context."""
timestamp: Required[str]
"""ISO 8601 datetime when this status was recorded.
Example: "2025-10-31T10:00:00Z"
"""
```
**Example: Task Requiring Input**
```json theme={null}
{
"state": "input-required",
"timestamp": "2025-10-31T10:32:00Z",
"message": {
"messageId": "clarification-001",
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"kind": "message",
"role": "agent",
"parts": [
{
"kind": "text",
"text": "I found multiple data files. Which one should I analyze?\n\n1. sales_q4_2025_final.csv\n2. sales_q4_2025_draft.csv\n3. sales_q4_2025_corrected.csv"
}
]
}
}
```
***
### TaskState Enum
Defines all possible lifecycle states a task can be in during execution.
**Standard A2A States:**
* **`submitted`** - Task has been submitted and is awaiting execution
* Initial state when task is created
* Agent has acknowledged receipt but hasn't started processing
* **`working`** - Agent is actively working on the task
* Task is being processed
* May transition to `input-required`, `completed`, or `failed`
* **`input-required`** - Task is paused, waiting for user input
* Agent needs clarification or additional information
* Task will resume once user provides required input
* This is an interrupted state, not terminal
* **`completed`** - Task has been successfully completed
* Final deliverables are available in `artifacts`
* This is a terminal state - task cannot be modified
* **`canceled`** - Task has been canceled by the user
* User explicitly stopped the task before completion
* This is a terminal state
* **`failed`** - Task failed due to an error during execution
* Agent encountered an unrecoverable error
* Error details typically included in status message
* This is a terminal state
* **`rejected`** - Task was rejected by the agent and was not started
* Agent determined it cannot or will not perform the task
* May occur during initial creation or after assessment
* This is a terminal state
* **`auth-required`** - Task requires authentication to proceed
* Additional authentication needed from the client
* Authentication expected to come out-of-band
* Not a terminal state - task can resume after auth
**Bindu Extensions** ``:
* **`payment-required`** - Task requires payment to proceed
* **`unknown`** - Task is in an unknown or indeterminate state
* **`trust-verification-required`** - Task requires trust verification
* **`pending`** - Task is pending execution (queued)
* **`suspended`** - Task is suspended and not currently running
* **`resumed`** - Task has been resumed after suspension
* **`negotiation-bid-submitted`** - Task bid submitted for negotiation
* **`negotiation-bid-lost`** - Task bid was lost in negotiation
* **`negotiation-bid-won`** - Task bid was won in negotiation
**State Transition Diagram:**
```mermaid theme={null}
stateDiagram-v2
[*] --> submitted: Task Created
submitted --> working: Agent Starts
submitted --> rejected: Agent Declines
submitted --> canceled: User Cancels
working --> completed: Success
working --> failed: Error
working --> input_required: Needs Input
working --> auth_required: Needs Auth
working --> canceled: User Cancels
input_required --> working: Input Provided
input_required --> canceled: User Cancels
auth_required --> working: Auth Completed
auth_required --> canceled: User Cancels
completed --> [*]
failed --> [*]
rejected --> [*]
canceled --> [*]
note right of completed
Terminal State
Task cannot be modified
end note
note right of failed
Terminal State
Contains error details
end note
note right of rejected
Terminal State
Agent declined task
end note
note right of canceled
Terminal State
User stopped task
end note
```
**Legend:**
* **Terminal States**: `completed`, `failed`, `rejected`, `canceled` - Cannot transition further
* **Interrupted States**: `input-required`, `auth-required` - Can resume to `working`
* **Active States**: `submitted`, `working` - Task is being processed
***
### Task Events
Events notify clients of task state changes and artifact updates, typically used in streaming (SSE) or push notification scenarios to keep clients informed without polling.
#### TaskStatusUpdateEvent
Sent by the agent when a task's status changes, enabling real-time progress tracking.
**Schema:**
```python theme={null}
class TaskStatusUpdateEvent(TypedDict):
"""Event sent by the agent to notify the client of a change in a task's status.
This is typically used in streaming or subscription models to provide
real-time updates without requiring the client to poll for changes.
"""
task_id: Required[UUID]
"""The ID of the task being updated."""
context_id: Required[UUID]
"""The ID of the context the task is associated with."""
kind: Required[Literal["status-update"]]
"""The type of the event, always "status-update"."""
status: Required[TaskStatus]
"""The new status of the task."""
final: Required[bool]
"""Indicates if this is the final status update (terminal state reached)."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata about the event."""
```
**Example: Progress Update During Processing**
```json theme={null}
{
"taskId": "225d6247-06ba-4cda-a08b-33ae35c8dcfa",
"contextId": "05217e44-7e9f-473e-ab4f-2c2dde50a2b1",
"kind": "status-update",
"status": {
"state": "working",
"timestamp": "2025-10-31T10:30:15Z",
"message": {
"messageId": "progress-001",
"contextId": "05217e44-7e9f-473e-ab4f-2c2dde50a2b1",
"taskId": "225d6247-06ba-4cda-a08b-33ae35c8dcfa",
"kind": "message",
"role": "agent",
"parts": [
{
"kind": "text",
"text": "Analyzing data... 45% complete"
}
]
}
},
"final": false,
"metadata": {
"progressPercentage": 45,
"estimatedTimeRemaining": "2 minutes"
}
}
```
**Example: Final Status Update (Completion)**
```json theme={null}
{
"taskId": "225d6247-06ba-4cda-a08b-33ae35c8dcfa",
"contextId": "05217e44-7e9f-473e-ab4f-2c2dde50a2b1",
"kind": "status-update",
"status": {
"state": "completed",
"timestamp": "2025-10-31T10:35:00Z"
},
"final": true
}
```
**Use Cases:**
* Real-time progress tracking for long-running tasks
* Notifying clients when tasks require input or authentication
* Alerting on task completion or failure
* Streaming task execution updates via Server-Sent Events (SSE)
***
#### TaskArtifactUpdateEvent
Sent by the agent when an artifact is generated or updated, enabling incremental delivery of large outputs.
**Schema:**
```python theme={null}
class TaskArtifactUpdateEvent(TypedDict):
"""Event sent by the agent to notify the client that an artifact has been generated or updated.
This is typically used in streaming models to deliver large artifacts
incrementally, improving user experience for long-running tasks.
"""
task_id: Required[UUID]
"""The ID of the task producing the artifact."""
context_id: Required[UUID]
"""The ID of the context the task is associated with."""
kind: Required[Literal["artifact-update"]]
"""The type of the event, always "artifact-update"."""
artifact: Required[Artifact]
"""The artifact that has been generated or updated."""
append: NotRequired[bool]
"""If true, append to existing artifact. If false, replace existing artifact."""
last_chunk: NotRequired[bool]
"""If true, this is the last chunk of the artifact."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata about the event."""
```
**Example: First Chunk (New Artifact)**
```json theme={null}
{
"taskId": "225d6247-06ba-4cda-a08b-33ae35c8dcfa",
"contextId": "05217e44-7e9f-473e-ab4f-2c2dde50a2b1",
"kind": "artifact-update",
"artifact": {
"artifactId": "9b6934dd-37e3-4eb1-8766-962efaab63a1",
"name": "Market Analysis Report",
"parts": [
{
"kind": "text",
"text": "# Market Analysis Report\n\n## Executive Summary\n\nOur Q4 analysis reveals significant market shifts..."
}
]
},
"append": false,
"lastChunk": false,
"metadata": {
"chunkNumber": 1,
"totalChunks": 5
}
}
```
**Example: Subsequent Chunk (Append)**
```json theme={null}
{
"taskId": "225d6247-06ba-4cda-a08b-33ae35c8dcfa",
"contextId": "05217e44-7e9f-473e-ab4f-2c2dde50a2b1",
"kind": "artifact-update",
"artifact": {
"artifactId": "9b6934dd-37e3-4eb1-8766-962efaab63a1",
"name": "Market Analysis Report",
"parts": [
{
"kind": "text",
"text": "## Competitive Landscape\n\nThree major competitors have entered the market..."
}
]
},
"append": true,
"lastChunk": false,
"metadata": {
"chunkNumber": 3,
"totalChunks": 5
}
}
```
**Example: Final Chunk**
```json theme={null}
{
"taskId": "225d6247-06ba-4cda-a08b-33ae35c8dcfa",
"contextId": "05217e44-7e9f-473e-ab4f-2c2dde50a2b1",
"kind": "artifact-update",
"artifact": {
"artifactId": "9b6934dd-37e3-4eb1-8766-962efaab63a1",
"name": "Market Analysis Report",
"parts": [
{
"kind": "text",
"text": "## Recommendations\n\n1. Increase marketing spend by 20%\n2. Focus on mobile channels\n3. Expand into West Coast markets"
}
]
},
"append": true,
"lastChunk": true,
"metadata": {
"chunkNumber": 5,
"totalChunks": 5
}
}
```
**Use Cases:**
* Streaming large reports or documents in chunks
* Progressive rendering of generated content
* Real-time display of agent-generated outputs
* Reducing memory overhead for large artifacts
**Chunking Strategy:**
* `append: false` - Start new artifact or replace existing
* `append: true` - Add content to existing artifact
* `lastChunk: true` - Signal completion of artifact delivery
***
### Task Operations & Parameters
Parameters used for various task operations including execution, querying, and management.
#### TaskSendParams ``
Internal parameters for task execution within the Bindu framework.
**Schema:**
```python theme={null}
class TaskSendParams(TypedDict):
"""Internal parameters for task execution within the framework.
These parameters are used internally by the Bindu framework to manage
task execution and are not part of the standard A2A protocol.
"""
task_id: Required[UUID]
"""The ID of the task to execute."""
context_id: Required[UUID]
"""The ID of the context the task is associated with."""
message: NotRequired[Message]
"""The message to send to the task."""
history_length: NotRequired[int]
"""The maximum number of history messages to include."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata for task execution."""
```
**Example:**
```json theme={null}
{
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"message": {
"messageId": "msg-002",
"role": "user",
"parts": [
{
"kind": "text",
"text": "Use the final version of the data file"
}
],
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1"
},
"historyLength": 10,
"metadata": {
"priority": "high"
}
}
```
***
#### TaskIdParams
Simple parameters containing a task ID, used for basic task operations.
**Schema:**
```python theme={null}
class TaskIdParams(TypedDict):
"""Defines parameters containing a task ID, used for simple task operations.
This is a base parameter type for operations that only require a task ID,
such as cancellation or basic retrieval.
"""
task_id: Required[UUID]
"""The ID of the task."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata for the operation."""
```
**Example: Cancel Task**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 3,
"method": "tasks/cancel",
"params": {
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"metadata": {
"reason": "User requested cancellation"
}
}
}
```
***
#### TaskQueryParams
Parameters for querying task details with optional history limiting.
**Schema:**
```python theme={null}
class TaskQueryParams(TypedDict):
"""Defines parameters for querying a task, with an option to limit history length.
Extends TaskIdParams to add history length control for efficient
retrieval of task information.
"""
task_id: Required[UUID]
"""The ID of the task to query."""
history_length: NotRequired[int]
"""The maximum number of history messages to return."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata for the query."""
```
**Example: Get Task with Limited History**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 2,
"method": "tasks/get",
"params": {
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"historyLength": 5
}
}
```
**Response:**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"id": "363422be-b0f9-4692-a24d-278670e7c7f1",
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"kind": "task",
"status": {
"state": "completed",
"timestamp": "2025-10-31T10:35:00Z"
},
"artifacts": [/* artifacts */],
"history": [/* last 5 messages only */]
}
}
```
**Use Cases:**
* Retrieving task status without full history
* Reducing payload size for list operations
* Efficient polling for task updates
* Getting recent conversation context only
***
#### ListTasksParams ``
Parameters for listing multiple tasks with optional history limiting.
**Schema:**
```python theme={null}
class ListTasksParams(TypedDict):
"""Defines parameters for listing tasks.
This is a Bindu-specific extension for retrieving multiple tasks
with control over history size to optimize payload.
"""
history_length: NotRequired[int]
"""The maximum number of history messages to return for each task."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata for filtering or controlling the list operation."""
```
**Example: List All Tasks with Limited History**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 4,
"method": "tasks/list",
"params": {
"historyLength": 3,
"metadata": {
"status": "completed",
"limit": 10
}
}
}
```
**Response:**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 4,
"result": {
"tasks": [
{
"id": "task-001",
"contextId": "ctx-001",
"kind": "task",
"status": {
"state": "completed",
"timestamp": "2025-10-31T10:35:00Z"
},
"artifacts": [/* artifacts */],
"history": [/* last 3 messages only */]
},
{
"id": "task-002",
"contextId": "ctx-001",
"kind": "task",
"status": {
"state": "working",
"timestamp": "2025-10-31T10:38:00Z"
},
"history": [/* last 3 messages only */]
}
],
"total": 15,
"page": 1
}
}
```
**Use Cases:**
* Dashboard views showing multiple tasks
* Task management interfaces
* Batch status checking
* Filtering tasks by status or context
* Pagination with history control
***
#### TaskFeedbackParams ``
Parameters for providing feedback on completed tasks.
**Schema:**
```python theme={null}
class TaskFeedbackParams(TypedDict):
"""Defines parameters for providing feedback on a task.
This is a Bindu-specific extension that enables users to rate
and provide feedback on task execution quality.
"""
task_id: Required[UUID]
"""The ID of the task to provide feedback for."""
feedback: Required[str]
"""Textual feedback about the task execution."""
rating: NotRequired[int]
"""Optional rating from 1 (lowest) to 5 (highest)."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata about the feedback."""
```
**Example: Positive Feedback**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 5,
"method": "tasks/feedback",
"params": {
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"feedback": "Excellent analysis with actionable insights. The regional breakdown was particularly helpful and the recommendations are clear and practical.",
"rating": 5,
"metadata": {
"helpful": true,
"accurate": true,
"timely": true,
"wouldUseAgain": true
}
}
}
```
**Example: Constructive Feedback**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 6,
"method": "tasks/feedback",
"params": {
"taskId": "task-002",
"feedback": "The analysis was good but took longer than expected. Would appreciate more frequent progress updates.",
"rating": 3,
"metadata": {
"helpful": true,
"accurate": true,
"timely": false,
"suggestions": ["Add progress indicators", "Provide time estimates"]
}
}
}
```
**Response:**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 5,
"result": {
"success": true,
"feedbackId": "feedback-001",
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"timestamp": "2025-10-31T10:40:00Z"
}
}
```
**Rating Scale:**
* **5** - Excellent: Exceeded expectations
* **4** - Good: Met expectations well
* **3** - Satisfactory: Met basic expectations
* **2** - Poor: Below expectations
* **1** - Very Poor: Did not meet expectations
**Use Cases:**
* Quality assurance and agent improvement
* User satisfaction tracking
* Identifying areas for enhancement
* Training data for agent optimization
* Performance metrics and analytics
**Best Practices:**
* Provide specific, actionable feedback
* Use ratings consistently across tasks
* Include context in metadata
* Submit feedback promptly after task completion
* Be constructive in criticism
***
### Message Sending Parameters
Parameters for sending messages to agents to initiate or continue task interactions.
#### MessageSendConfiguration
Configuration options for message sending behavior.
**Schema:**
```python theme={null}
class MessageSendConfiguration(TypedDict):
"""Configuration for message sending.
Controls how the agent processes the message and how the client
receives responses, including output format preferences and blocking behavior.
"""
accepted_output_modes: Required[list[str]]
"""The accepted output modes (MIME types) for the response.
Examples: ["text/plain", "application/json", "text/markdown"]
"""
blocking: NotRequired[bool]
"""If true, the request blocks until the task completes or requires input.
If false, returns immediately with task in 'submitted' or 'working' state.
"""
history_length: NotRequired[int]
"""The maximum number of history messages to include in the response."""
push_notification_config: NotRequired[PushNotificationConfig]
"""Configuration for push notifications about task updates."""
```
**Example: Blocking Request with JSON Output**
```json theme={null}
{
"acceptedOutputModes": ["application/json", "text/plain"],
"blocking": true,
"historyLength": 10
}
```
**Example: Non-Blocking with Push Notifications**
```json theme={null}
{
"acceptedOutputModes": ["text/markdown", "text/plain"],
"blocking": false,
"push_notification_config": {
"id": "notif-001",
"url": "https://client.example.com/webhook/task-updates",
"token": "secret-webhook-token",
"authentication": {
"type": "http",
"scheme": "bearer"
}
}
}
```
***
#### MessageSendParams
Parameters for sending a message to an agent.
**Schema:**
```python theme={null}
class MessageSendParams(TypedDict):
"""Parameters for sending messages.
Used to initiate a new task or continue an existing one by sending
a message to the agent. Cannot be used to restart terminal tasks.
"""
message: Required[Message]
"""The message to send to the agent."""
configuration: Required[MessageSendConfiguration]
"""Configuration for how the message should be processed."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata for the request."""
```
**Example: Initiate New Task (Blocking)**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 1,
"method": "message/send",
"params": {
"message": {
"messageId": "9229e770-767c-417b-a0b0-f0741243c589",
"role": "user",
"parts": [
{
"kind": "text",
"text": "Analyze Q4 sales data and identify key trends"
},
{
"kind": "file",
"file": {
"name": "sales_q4.csv",
"mimeType": "text/csv",
"uri": "https://storage.example.com/data/sales_q4.csv"
}
}
]
},
"configuration": {
"acceptedOutputModes": ["text/plain", "application/json"],
"blocking": true,
"historyLength": 5
},
"metadata": {
"priority": "high",
"source": "dashboard"
}
}
}
```
**Response: Completed Task**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"id": "363422be-b0f9-4692-a24d-278670e7c7f1",
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"kind": "task",
"status": {
"state": "completed",
"timestamp": "2025-10-31T10:35:00Z"
},
"artifacts": [/* analysis results */],
"history": [/* conversation */]
}
}
```
**Example: Continue Existing Task (Provide Input)**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 2,
"method": "message/send",
"params": {
"message": {
"messageId": "msg-002",
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"contextId": "c295ea44-7543-4f78-b524-7a38915ad6e4",
"role": "user",
"parts": [
{
"kind": "text",
"text": "Use the final version: sales_q4_2025_final.csv"
}
]
},
"configuration": {
"acceptedOutputModes": ["text/plain"],
"blocking": false
}
}
}
```
**Important Notes:**
* Cannot restart tasks in terminal states (`completed`, `canceled`, `rejected`, `failed`)
* Use `blocking: true` for quick operations, `false` for long-running tasks
* `acceptedOutputModes` helps agent format response appropriately
* Include `taskId` in message to continue existing task
***
### Push Notification Parameters
Parameters for managing push notification configurations associated with tasks.
#### ListTaskPushNotificationConfigParams
Parameters for retrieving all push notification configurations for a task.
**Schema:**
```python theme={null}
class ListTaskPushNotificationConfigParams(TypedDict):
"""Parameters for getting list of pushNotificationConfigurations associated with a Task.
Retrieves all webhook configurations that receive updates for this task.
"""
id: Required[UUID]
"""The ID of the task."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata for the request."""
```
**Example:**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 7,
"method": "tasks/pushNotificationConfig/list",
"params": {
"id": "363422be-b0f9-4692-a24d-278670e7c7f1"
}
}
```
**Response:**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 7,
"result": {
"configs": [
{
"id": "notif-001",
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"url": "https://client.example.com/webhook/task-updates",
"authentication": {
"type": "http",
"scheme": "bearer"
}
},
{
"id": "notif-002",
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1",
"url": "https://backup.example.com/notifications",
"authentication": {
"type": "http",
"scheme": "bearer"
}
}
]
}
}
```
***
#### DeleteTaskPushNotificationConfigParams
Parameters for removing a push notification configuration from a task.
**Schema:**
```python theme={null}
class DeleteTaskPushNotificationConfigParams(TypedDict):
"""Parameters for removing pushNotificationConfiguration associated with a Task.
Removes a specific webhook configuration so it no longer receives
updates for this task.
"""
id: Required[UUID]
"""The ID of the task."""
push_notification_config_id: Required[UUID]
"""The ID of the push notification configuration to remove."""
metadata: NotRequired[dict[str, Any]]
"""Additional metadata for the request."""
```
**Example:**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 8,
"method": "tasks/pushNotificationConfig/delete",
"params": {
"id": "363422be-b0f9-4692-a24d-278670e7c7f1",
"push_notification_config_id": "notif-001",
"metadata": {
"reason": "Webhook endpoint deprecated"
}
}
}
```
**Response:**
```json theme={null}
{
"jsonrpc": "2.0",
"id": 8,
"result": {
"success": true,
"deletedConfigId": "notif-001",
"taskId": "363422be-b0f9-4692-a24d-278670e7c7f1"
}
}
```
**Use Cases:**
* Clean up obsolete webhook endpoints
* Remove notification configs after task completion
* Update notification routing by removing old configs
* Manage webhook lifecycle
**Related Methods:**
* `tasks/pushNotificationConfig/set` - Add or update notification config
* `tasks/pushNotificationConfig/get` - Retrieve specific config
* `tasks/pushNotificationConfig/list` - List all configs for a task
***
# Trust and identity
Source: https://docs.getbindu.com/bindu/protocol/trust
TrustLevel, identity providers, and how DID verification fits into the protocol.
Trust and identity management ensures secure agent operations through role-based access control and identity verification. Bindu authenticates with [Ory Hydra](https://www.ory.sh/hydra/) (OAuth2/OIDC); enterprise IdPs (Keycloak, Azure AD, Okta, Auth0) federate into Hydra rather than appearing as direct provider values.
**Implementation status (2026-05).** The TypedDicts on this page (`KeycloakRole`, `AgentTrust`) ship in [`bindu/common/protocol/types.py`](https://github.com/getbindu/Bindu/blob/main/bindu/common/protocol/types.py) and are accepted by the trust extension. The authorization-layer enforcement (the `require_permissions` flag in `bindu/auth/`) is being rebuilt on Ory Kratos; until that lands, role-based enforcement on RPC methods may not be wired up end-to-end. The `KeycloakRole` name is historical — the shape stays whether the federated IdP is Keycloak or another OIDC provider.
### KeycloakRole
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class KeycloakRole(TypedDict):
"""Keycloak role model.
Defines roles with permissions and trust levels for access control.
"""
role_id: Required[UUID]
"""The ID of the role."""
role_name: Required[str]
"""The name of the role."""
permissions: Required[List[str]]
"""The permissions of the role."""
trust_level: Required[TrustLevel]
"""The trust level of the role."""
realm_name: Required[str]
"""The realm name of the role."""
external_mappings: NotRequired[Dict[str, str]]
"""The external mappings of the role."""
operation_permissions: NotRequired[Dict[str, TrustLevel]]
"""The operation permissions of the role."""
```
**Use Case: Enterprise Admin Role**
```json theme={null}
{
"roleId": "550e8400-e29b-41d4-a716-446655440000",
"roleName": "enterprise_admin",
"permissions": [
"agent.create",
"agent.delete",
"user.manage",
"billing.view"
],
"trustLevel": "admin",
"realmName": "enterprise-production",
"externalMappings": {
"azure_ad": "Enterprise-Admins",
"okta": "admin-group"
},
"operationPermissions": {
"agent.execute": "operator",
"data.export": "admin"
}
}
```
**What it's for:** Defining roles with specific permissions and trust levels in Keycloak. Maps to external identity providers (Azure AD, Okta) for SSO integration. Operation permissions specify minimum trust levels required for specific actions.
***
### AgentTrust
**Schema:**
```python theme={null}
@pydantic.with_config(ConfigDict(alias_generator=to_camel))
class AgentTrust(TypedDict):
"""Trust configuration for an agent.
Establishes identity, permissions, and verification requirements for agent operations.
"""
identity_provider: Required[IdentityProvider]
"""The identity provider of the agent."""
inherited_roles: Required[List[KeycloakRole]]
"""The roles inherited by the agent."""
certificate: NotRequired[str]
"""The certificate of the agent."""
certificate_fingerprint: NotRequired[str]
"""The fingerprint of the certificate of the agent."""
creator_id: Union[UUID, int, str]
"""The creator ID of the agent."""
creation_timestamp: int
"""The creation timestamp of the agent."""
trust_verification_required: bool
"""Whether trust verification is required for this agent."""
allowed_operations: Dict[str, TrustLevel]
"""The allowed operations and their required trust levels."""
```
The `IdentityProvider` type alias only accepts `"hydra"` or `"custom"` today (see [types-and-enums](./types-and-enums)). Federation to Keycloak, Azure AD, Okta, or Auth0 is configured upstream of Hydra — at the trust layer the provider is still recorded as `"hydra"`.
**Use Case: Trusted Data Processing Agent**
```json theme={null}
{
"identityProvider": "hydra",
"inheritedRoles": [
{
"roleId": "660e8400-e29b-41d4-a716-446655440001",
"roleName": "data_processor",
"permissions": ["data.read", "data.process"],
"trustLevel": "operator",
"realmName": "enterprise-production"
}
],
"certificate": "-----BEGIN CERTIFICATE-----\nMIIC...",
"certificateFingerprint": "SHA256:a1b2c3d4e5f6...",
"creatorId": "did:example:creator789",
"creationTimestamp": 1698796800,
"trustVerificationRequired": true,
"allowedOperations": {
"data.read": "analyst",
"data.process": "operator",
"data.export": "admin"
}
}
```
**What it's for:** Configuring trust and identity for agents. Inherits roles from identity providers, uses certificates for cryptographic verification, and defines operation-level permissions. Trust verification ensures the agent's identity is validated before execution.
### Trust Architecture
```mermaid theme={null}
graph TD
A[User/Agent] --> B[Identity Provider]
B --> C{Authentication}
C -->|Success| D[Retrieve Roles]
C -->|Failure| E[Access Denied]
D --> F[KeycloakRole]
F --> G[Check Trust Level]
F --> H[Check Permissions]
G --> I{Meets Requirements?}
H --> I
I -->|Yes| J[AgentTrust Verified]
I -->|No| E
J --> K[Check Operation Permissions]
K --> L{Operation Allowed?}
L -->|Yes| M[Execute Operation]
L -->|No| E
style B fill:#87CEEB
style J fill:#90EE90
style E fill:#FFB6C1
```
**Trust Verification Flow:**
```mermaid theme={null}
sequenceDiagram
participant Agent
participant Platform as Bindu
participant IDP as Identity Provider
participant CertAuth as Certificate Authority
Agent->>Platform: Request operation
(with credentials)
Platform->>IDP: Authenticate agent
IDP-->>Platform: Return roles & permissions
alt Trust verification required
Platform->>CertAuth: Verify certificate
CertAuth-->>Platform: Certificate valid
end
Platform->>Platform: Check AgentTrust
- Verify trust level
- Check operation permissions
alt Authorized
Platform->>Agent: Operation allowed
Agent->>Platform: Execute operation
Platform-->>Agent: Operation result
else Unauthorized
Platform-->>Agent: Access denied
(insufficient trust/permissions)
end
```
**Summary:**
Trust and identity management combines role-based access control with enterprise identity providers. **KeycloakRole** defines permissions and trust levels with SSO mappings. **AgentTrust** configures agent identity verification using certificates and inherited roles. Each operation requires minimum trust levels, enabling fine-grained security for enterprise deployments, multi-tenant platforms, and high-security operations.
***
# Types and enums
Source: https://docs.getbindu.com/bindu/protocol/types-and-enums
TypeAlias and Enum definitions: TaskState, TrustLevel, NegotiationStatus, IdentityProvider, and the rest.
Protocol types use TypeAlias definitions for enums to ensure type safety and clear state management.
### TaskState
Defines all possible states a task can be in during its lifecycle:
**Standard A2A States:**
* `submitted` - Task has been submitted and is awaiting execution
* `working` - Agent is actively working on the task
* `input-required` - Task is paused, waiting for user input
* `completed` - Task has been successfully completed
* `canceled` - Task has been canceled by the user
* `failed` - Task failed due to an error during execution
* `rejected` - Task was rejected by the agent and was not started
* `auth-required` - Task requires authentication to proceed
**Bindu Extensions** ``:
* `payment-required` - Task requires payment to proceed
* `unknown` - Task is in an unknown or indeterminate state
* `trust-verification-required` - Task requires trust verification to proceed
* `pending` - Task is pending execution
* `suspended` - Task is suspended and not currently running
* `resumed` - Task is resumed and currently running
* `negotiation-bid-submitted` - Task is submitted for negotiation
* `negotiation-bid-lost` - Task bid was lost in negotiation
* `negotiation-bid-won` - Task bid was won in negotiation
### NegotiationStatus ``
Defines the status of individual negotiation proposals:
* `proposed` - Negotiation is proposed
* `accepted` - Negotiation is accepted
* `rejected` - Negotiation is rejected
* `countered` - Counter-offer made
### NegotiationSessionStatus ``
Defines the overall status of a negotiation session:
* `initiated` - Negotiation session is initiated
* `ongoing` - Negotiation session is ongoing
* `completed` - Negotiation session is completed
* `rejected` - Negotiation session is rejected
### TrustLevel ``
Defines role-based trust levels for agent authorization (ordered by permission level):
* `super_admin` - Highest level access, all operations permitted
* `admin` - Admin operations, minimal risk
* `manager` - Management operations, elevated permissions
* `operator` - System operations, moderate risk
* `editor` - Edit operations, moderate risk
* `analyst` - Standard operations
* `auditor` - Sensitive operations (read-only)
* `support` - Support operations, troubleshooting access
* `viewer` - View-only access, minimal permissions
* `guest` - Limited access, read-only operations
### IdentityProvider ``
Defined in [`bindu/common/protocol/types.py`](https://github.com/getbindu/Bindu/blob/main/bindu/common/protocol/types.py):
```python theme={null}
IdentityProvider: TypeAlias = Literal["hydra", "custom"]
```
* `hydra` — [Ory Hydra](https://www.ory.sh/hydra/) OAuth2/OIDC server (default for Bindu deployments)
* `custom` — operator-provided OIDC-compatible provider
The values `keycloak`, `azure_ad`, `okta`, and `auth0` are **not currently accepted** at runtime — federation to those IdPs happens upstream of Hydra. If you need them as first-class values, open an issue.
# Boxd runtime
Source: https://docs.getbindu.com/bindu/runtime/box
Deploy your bindu agent to a boxd microVM
## Situation
Your bindu agent runs fine locally, but `python my_agent.py` ties it to your
machine. The moment you close the terminal it's gone — no public URL, no
persistent identity, no way for other agents or users to reach it.
Hosting it yourself means provisioning a server, managing TLS, keeping the
process alive, and handling secrets safely. That's infrastructure work that
has nothing to do with your agent's logic.
***
## Task
Run your agent inside an isolated [boxd](https://boxd.sh) microVM — with its
own public HTTPS URL, cryptographic DID identity, and persistent state —
without changing a single line of your agent script.
***
## Action
### 1. Meet the requirements
* A boxd account and credentials — bindu accepts either form
([source](https://github.com/getbindu/Bindu/blob/main/bindu/runtime/boxd_provider.py)):
```bash theme={null}
export BOXD_API_KEY=""
# or, short-lived:
export BOXD_TOKEN=$(boxd login --json | jq -r .token)
```
* The boxd runtime extra for bindu:
```bash theme={null}
pip install 'bindu[runtime-boxd]'
```
### 2. Preview before you spend anything
```bash theme={null}
bindu deploy agent.py --runtime=boxd --dry-run
```
Prints the target VM name, source root, entry script, resource config,
env-var keys (values hidden), tarball file count and compressed size, and
any sensitive files that would be silently dropped. No VM is touched.
### 3. Deploy
```bash theme={null}
bindu deploy agent.py --runtime=boxd
```
That's it. Same script you run locally, one flag, public URL.
### 4. Tune the deploy with CLI flags
| Flag | Type | Default | Meaning |
| ----------------- | --------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--runtime` | str | `boxd` | Runtime provider. |
| `--name` | str | from `config["name"]` | Override the agent name (e.g. for preview envs). |
| `--image` | str | unset | **A1 mode:** boot from this Docker image instead of shipping source. See [custom image](/bindu/runtime/custom-image). |
| `--vcpu` | int | `2` | vCPUs for the VM. |
| `--memory` | str | `4G` | RAM. Accepts boxd size strings (`512M`, `4G`, …). |
| `--disk` | str | `20G` | Disk size. |
| `--auto-suspend` | int | `0` (disabled) | Seconds of idle (no HTTP request) before boxd auto-suspends the VM. Off by default — bindu agents commonly run background work (scheduler ticks, streaming LLM calls, websockets) that would be frozen mid-flight. Pass `--auto-suspend=60` only if your agent is pure request/response. |
| `--on-exit` | str | `suspend` | Behaviour on Ctrl-C: `suspend` (call `box.suspend()`), `destroy` (tear down VM), `detach` (leave running). |
| `--bindu-version` | str | unset | Pin the bindu version installed in the VM. `local` ships the host's source instead of pulling from PyPI — useful for testing a patched bindu. |
| `--env` | KEY=VALUE | — | Extra env var injected into the VM (repeatable). |
### 5. Understand the lifecycle
1. **First run** — bindu packages your project source, ships it to a fresh
VM, runs `pip install bindu` plus your deps, starts your agent, and polls
`/health` until ready. Cold path: \~10–30 seconds depending on dep weight.
2. **Subsequent runs (same agent name)** — the CLI reuses the existing VM,
updates source, restarts the agent. \~1–3 seconds.
3. **Ctrl-C with `--on-exit=suspend` (default)** — the CLI calls
`box.suspend()`, freezing the VM's memory. DID keys, vector store,
conversation history all survive. Re-running `bindu deploy` resumes in
1–3 seconds with state intact.
4. **`--auto-suspend=N`** — while the agent is running, suspend after N
seconds without an HTTP request. Avoid if the agent has scheduled tasks,
streaming LLM calls, or websocket connections — those will be frozen
mid-execution and most upstreams don't tolerate resuming mid-RPC.
### 6. Pass secrets safely
The agent's DID keys, x402 wallet, and OAuth tokens are generated and
persisted **inside the VM**. `BOXD_API_KEY` / `BOXD_TOKEN` stays on
your host and is never shipped. User secrets go in via `--env`:
```bash theme={null}
bindu deploy agent.py --runtime=boxd \
--env OPENAI_API_KEY=sk-... \
--env ANTHROPIC_API_KEY=sk-ant-...
```
The deploy CLI **never ships secret-looking files**. The exact patterns
are defined in
[`source_packager._SENSITIVE_PATTERNS`](https://github.com/getbindu/Bindu/blob/main/bindu/runtime/source_packager.py):
| Type | Patterns (exact `fnmatch`) |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Files | `.env`, `.env.*`, `*.pem`, `*.key`, `*.p12`, `*.pfx`, `*.kdbx`, `id_rsa`, `id_dsa`, `id_ecdsa`, `id_ed25519`, `credentials.json`, `credentials.yaml`, `credentials.yml`, `*.kubeconfig` |
| Dirs (whole subtree excluded) | `.aws/`, `.gnupg/`, `.ssh/`, `.bindu/` |
A warning lists what was dropped. Run `--dry-run` to see the full
list before deploying.
### 7. Source packaging rules
Your project root is auto-discovered by walking up from the entry script
looking for `pyproject.toml`, `setup.py`, `requirements.txt`, or `.git`
(see [`find_project_root`](https://github.com/getbindu/Bindu/blob/main/bindu/runtime/source_packager.py)).
The packager is **inclusion-by-default**: every file under the project
root ships unless it matches an exclude rule. There is no allowlist of
extensions — your `.csv`, `.sql`, `.html`, etc. all ship.
**Excluded by directory name** (any path segment matches):
`__pycache__/`, `.git/`, `.venv/`, `venv/`, `node_modules/`,
`.pytest_cache/`, `.mypy_cache/`, `.ruff_cache/`
**Excluded by suffix:** `.pyc`, `.pyo`, `.log`, `.sqlite`, `.db`
**Also excluded:** the sensitive patterns from Section 6, plus
everything matched by `.gitignore` and `.binduignore` at the project
root (same syntax as gitignore).
**Hard cap:** 50 MB compressed. Bigger sources fail fast with a
`SourceTooLargeError` pointing to `.binduignore`.
### 8. Dev tools while it's running
| Command | What it does |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bindu logs ` | Stream the agent's stdout/stderr to your terminal. Reads `/tmp/bindu-agent.log` inside the VM via `tail -F`. Pass `--no-follow` to `cat` the file and exit. |
| `bindu shell ` | Open an interactive `bash` inside the VM as the `boxd` user. You land in `/home/boxd`; your shipped source is at `/home/boxd/app`. |
***
## Result
Your agent is live at `https://.boxd.sh` — isolated, HTTPS, with a
cryptographic identity and persistent state across suspends. You didn't touch
a server, write a Dockerfile, or manage TLS.
### Troubleshooting
| Problem | Likely cause | Fix |
| ---------------------------------------------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `BOXD_API_KEY or BOXD_TOKEN must be set in the host environment` | No credentials in host env | `export BOXD_API_KEY=` (or `export BOXD_TOKEN=$(boxd login --json \| jq -r .token)`) |
| `script did not call bindufy()` | Entry script raised before reaching `bindufy()` | Run `python agent.py` directly to see the underlying error |
| `agent at did not become healthy within 60s` | VM up but agent failed to start | `bindu logs ` — common causes: missing dep, syntax error, port 3773 already in use |
| `pip install` failure | Dep not on PyPI or native build fails | Switch to [A1 mode](/bindu/runtime/custom-image) and install the dep at image-build time |
| Source >50 MB | Large data files included | Add them to `.binduignore` |
| Old bindu in VM rejects new features | Published bindu lags the host's | Pass `--bindu-version=local` to ship host source instead |
| `upload to /tmp/... corrupted after 3 attempts` | boxd write\_file truncation ([boxd#45](https://github.com/azin-tech/boxd/issues/45)) | Re-run `bindu deploy` — the corruption is intermittent and almost always clears on retry |
| Wrong code running after redeploy | boxd 0.1.x sometimes ships truncated tarballs | The deploy now sha256-verifies every upload and retries on mismatch. If it persists, run `bindu shell ` and check `cat /tmp/bindu-agent.pid` against `pgrep python3` |
Runtime with boxd -
turn your agent into a web discoverable service.
# Custom image (A1 mode)
Source: https://docs.getbindu.com/bindu/runtime/custom-image
Deploy your bindu agent with a custom Docker image
## Mess might happen when
Some agents can't rely on a plain `pip install` at deploy time:
* Native deps that require a Rust toolchain or system libraries.
* CI/CD pipelines that already produce container images.
* Teams that need pinned, auditable, reproducible deploys.
If any of these apply, the default A2 source-mount mode isn't enough.
You need full control over the environment your agent runs in.
## What to do then?
Get bindu to boot your agent from a Docker image you built and pushed,
instead of packaging your source folder and running `pip install` inside
the VM.
## How to do it
### 1. Write a Dockerfile
Your image must start an agent that listens on **`0.0.0.0:3773`** —
that's the port bindu's boxd proxy forwards public HTTPS traffic to
(see [`BINDU_DEFAULT_PORT`](https://github.com/getbindu/Bindu/blob/main/bindu/runtime/boxd_provider.py)).
You can either run the script directly or use the `bindu serve --script`
shim (both end up calling `bindufy()` inside your file):
```dockerfile theme={null}
FROM python:3.12-slim
# Install bindu + your deps
WORKDIR /app
COPY pyproject.toml requirements*.txt ./
RUN pip install bindu
RUN pip install -r requirements.txt # or: pip install -e .
# Copy your agent code
COPY . /app
# Make sure your bindufy() config binds 0.0.0.0:3773. Then either:
CMD ["python3", "/app/my_agent.py"]
# ...or via the CLI shim (equivalent):
# CMD ["bindu", "serve", "--script", "/app/my_agent.py"]
```
### 2. Build and push to a registry
Push to any public registry, or a private one with credentials
configured on your boxd account (e.g. `ghcr.io`, Docker Hub, ECR).
### 3. Deploy with `--image`
```bash theme={null}
bindu deploy my_agent.py \
--runtime=boxd \
--image=ghcr.io/me/my-agent:v1.2.0
```
When `--image` is set, bindu changes its behaviour ([deploy() source](https://github.com/getbindu/Bindu/blob/main/bindu/runtime/boxd_provider.py)):
* **No source upload** — your folder stays on your machine.
* **No `pip install` step** — deps are already baked into the image.
* **Image `CMD` is the entrypoint** — whatever you put in `CMD` starts
the agent. Bindu does **not** exec into the container after creation;
it only waits for `GET /health` on port 3773.
* **`--env` is not injected.** A2 source mode merges `--env` flags into
the agent process at start time, but the A1 branch skips
`_start_agent` entirely — env values currently never reach your
container. Bake required env into the image, or read them from a
secret store inside the agent. Tracked as a known gap; once fixed
this section will move to "everything else is identical."
Everything else — health checks, log streaming via
`/tmp/bindu-agent.log`, on-exit lifecycle — works as in A2, **provided
your image writes its stdout/stderr to `/tmp/bindu-agent.log`** if you
want `bindu logs ` to work. (The default A2 mode does this for
you via shell redirection; A1 images have to opt in.)
## You see that
Your agent boots from a pinned, reproducible image with full control
over every system dependency. Here's how that compares to the default
A2 mode:
| | A2 (source mount) | A1 (custom image) |
| --------------------- | ------------------------------------------------- | ---------------------------------- |
| Setup | None - just run | Build + push image |
| Iteration speed | Fast (1–3s warm) | Slow (build + push + redeploy) |
| Reproducibility | Depends on `pip install` resolving the same deps | Pinned by image hash |
| Native deps | Limited to what `pip install` can build in the VM | Anything that builds at image time |
| Image registry needed | No | Yes |
Use A1 when correctness and reproducibility matter more than iteration
speed - typically once you move from local development into a real
CI/CD pipeline.
Custom image lets you -
deploy your agent with custom dependencies.
# Overview
Source: https://docs.getbindu.com/bindu/runtime/overview
Deploy your bindu agent from your computer to the internet.
## Let's say
You've built an agent locally. It runs fine with `python my_agent.py` - but
the moment you close the terminal, it's gone. Nobody else can reach it, it
has no public URL, and keeping it alive means keeping your laptop open.
Moving an agent to the internet normally means provisioning a server,
configuring networking, managing TLS, and wiring up a process supervisor.
That's a lot of infrastructure for something that should just run.
***
## You want to
Run the **exact same script** you already have - no deploy concerns added to
it - on a real public URL, with its own HTTPS domain, cryptographic identity,
and persistent state. Without touching any infrastructure yourself.
***
## How it works
### The runtime model
A bindu agent's *runtime* is where its Python process actually executes. By
default that's your own terminal (in-process). The `bindu deploy` CLI lets
you run the same script *elsewhere* via a `RuntimeProvider`.
The canonical provider is `BoxdRuntimeProvider`, which runs the agent inside
a [boxd](https://boxd.sh) microVM - isolated from your laptop, with its own
public URL, DID, and HTTPS domain.
### Your script stays clean
No deploy concerns leak into the agent script itself:
```python theme={null}
from bindu.penguin.bindufy import bindufy
def handler(messages):
return [{"role": "assistant", "content": messages[-1]["content"]}]
config = {
"author": "you@example.com",
"name": "my-agent",
"description": "echo agent",
"deployment": {"url": "http://0.0.0.0:3773", "expose": True},
}
bindufy(config, handler)
```
`author` is required ([bindufy.py:396-401](https://github.com/getbindu/Bindu/blob/main/bindu/penguin/bindufy.py));
the agent's DID is derived from `author + name`.
### Two ways to run it - same script, different verb
**Locally:**
```bash theme={null}
python my_agent.py # serves on localhost:3773
```
**On the internet:**
```bash theme={null}
bindu deploy my_agent.py --runtime=boxd --auto-suspend=60
```
✓ my-agent serving at [https://my-agent.boxd.sh](https://my-agent.boxd.sh)
\[my-agent] INFO: Started server process \[12]
\[my-agent] INFO: Application startup complete.
Inside the VM, bindu invokes your script directly with
`python3 /home/boxd/app/my_agent.py` (the script's `bindufy()` call
serves in-process, exactly as it does locally). The process is
started detached via `setsid nohup` and its PID is tracked in
`/tmp/bindu-agent.pid` so redeploys can stop the old process cleanly.
See [`_start_agent` in `bindu/runtime/boxd_provider.py`](https://github.com/getbindu/Bindu/blob/main/bindu/runtime/boxd_provider.py).
### When to use each runtime
| | In-process (default) | Boxd runtime |
| ---------------- | -------------------- | ----------------------------- |
| How to run | `python my_agent.py` | `bindu deploy --runtime=boxd` |
| Best for | Local development | Production microservices |
| Public URL | No | Yes, HTTPS |
| Persistent state | No | Yes |
| Multi-tenant | No | Yes |
***
## Result
A2A clients can reach the agent at `https://my-agent.boxd.sh`. Ctrl-C
applies the configured `--on-exit` policy (default `suspend`: calls
`box.suspend()` so the VM freezes its memory + disk and stops billing
CPU). With `--auto-suspend=60` passed, the VM also auto-suspends after
60 seconds of HTTP idle. Re-running `bindu deploy` resumes the same VM
and pushes updated source. Your script never changed — only the launch
verb did.
### Current limitations (v1)
* One runtime provider ships in-tree: `boxd`. The abstraction supports others
(e2b, modal, fly.io) but no additional providers are bundled yet.
* No live source-watch or auto-redeploy. Editing your script requires
re-running `bindu deploy`.
* No declarative manifest (`bindu.toml`) yet - all deploy config is via CLI
flags. Planned as a follow-up.
***
## Continue learning
* **[Quickstart](/bindu/runtime/quickstart)** - friendly walkthrough for your
first deploy. Start here if you've never used `bindu deploy` before.
* **[Boxd runtime reference](/bindu/runtime/box)** - full `bindu deploy` flag
reference for the boxd runtime.
* **[Custom image (A1 mode)](/bindu/runtime/custom-image)** - deploy from a
user-built Docker image.
* **[Design rationale](/bindu/superpowers/specs/2026-04-29-bindu-runtime-design)**
* the reasoning behind the runtime abstraction.
Runtime lets you -
deploy your agent to the internet.
# Quickstart
Source: https://docs.getbindu.com/bindu/runtime/quickstart
Walkthrough to deploy your bindu agent that is on your computer but lives on the internet.
## Overview
This guide is a walkthrough of deploying a bindu agent to a tiny computer
that lives on the internet, end to end, with no prior experience assumed.
By the end of it, you'll have an agent answering requests at a real
`https://...` URL - one that you (or anyone you share the URL with) can
talk to from anywhere.
If you've already run an agent locally with `python my_agent.py` and want
to know "okay, how do I make this real?" then this is for you.
## Where everyone gets stuck
Right now, your bindu agent runs on your laptop. When you close the
terminal, the agent dies. Nobody else can reach it.
That's fine for development, but eventually you want the agent to be a *real service* -
running somewhere stable, on a public URL, that other agents and humans
can call.
We're going to ship the *exact same script* you'd run locally to a
[boxd](https://boxd.sh) **microVM** - A microVM is a tiny isolated Linux
machine that boots in seconds. Boxd handles the boring parts: spinning
up the machine, giving it an HTTPS domain, keeping it alive. You write
your agent script. One command does the rest.
The command will be:
```bash theme={null}
bindu deploy my_agent.py --runtime=boxd
```
That's it. Same script, one command, public URL.
***
## What is needed
Three things, in order:
### 1. A boxd account and API key
Go to [boxd.sh](https://boxd.sh), sign up, and grab an API key from the
dashboard. Keep it private — anyone with this key can spin up VMs that
get charged to your account.
Stash it in your shell. Bindu accepts either `BOXD_API_KEY` or
`BOXD_TOKEN` ([see the check in `BoxdRuntimeProvider.deploy`](https://github.com/getbindu/Bindu/blob/main/bindu/runtime/boxd_provider.py)):
```bash theme={null}
# Option 1: paste the key from the dashboard
export BOXD_API_KEY=""
# Option 2: short-lived token from the boxd CLI
export BOXD_TOKEN=$(boxd login --json | jq -r .token)
```
If you'd rather not retype it every time, add the line to your
`~/.zshrc` (or `~/.bashrc`).
> **Note:** the free tier covers small experiments. The example we
> deploy below uses \~\$0.01 of compute. If you forget to pause your VM
> when you're done, you'll keep paying for it idling - we'll cover how
> to pause it at the end.
### 2. Bindu with the boxd extra installed
If you already have bindu installed, just add the optional `boxd` piece:
```bash theme={null}
pip install 'bindu[runtime-boxd]'
```
Or, with `uv`:
```bash theme={null}
uv add 'bindu[runtime-boxd]'
```
This pulls in the `boxd` Python library that knows how to talk to the
boxd cloud. The base `bindu` install doesn't include it because most
people don't deploy to boxd - you only pull it in when you need it.
### 3. An agent script
If you already have one (`my_agent.py` or whatever), great - keep using
it. If not, copy the one bundled with bindu. It's a 10-line echo agent
that just sends back whatever you send to it:
```bash theme={null}
# From your shell, anywhere
curl -O https://raw.githubusercontent.com/getbindu/Bindu/main/examples/runtime-boxd-agent/agent.py
```
The whole thing looks like this:
```python theme={null}
from bindu.penguin.bindufy import bindufy
def handler(messages):
"""Echo the latest user message back."""
if not messages:
return "send a message"
return [
{
"role": "assistant",
"content": messages[-1].get("content", ""),
}
]
config = {
"author": "you@example.com",
"name": "runtime-boxd-example",
"description": "Echo agent running inside a boxd microVM.",
"deployment": {
"url": "http://0.0.0.0:3773",
"expose": True,
},
}
if __name__ == "__main__":
bindufy(config, handler)
```
Nothing complex here. A handler function, a config dict, a
`bindufy()` call. Notice there's *nothing* about boxd in this file,
the deploy logic lives entirely in the CLI. Same script works for
`python agent.py` locally and `bindu deploy agent.py` to the cloud.
***
## Step 1: see what would happen (a safe dry run)
Before you spend any money, let's see what bindu *would* do if you
deployed. This step doesn't touch the cloud at all:
```bash theme={null}
bindu deploy agent.py --runtime=boxd --dry-run
```
You should see something like:
```
DRY RUN — nothing will be deployed.
agent name: runtime-boxd-example
source root: /Users/you/playground
entry script: agent.py
provider: boxd
vcpu / memory: 2 / 4G
disk: 20G
auto_suspend: 0s
on_exit: suspend
tarball: 4 files, 2.4 KB compressed
```
The `bindu_version:` line only appears if you pass `--bindu-version`,
and `env keys:` (values hidden) only appears if you pass `--env`.
This is the *plan*. It tells you:
* **What the VM will be named** (`runtime-boxd-example` - bindu reads
this from `config["name"]` in your script).
* **What hardware it gets** (2 vCPUs, 4 GB RAM, 20 GB disk by default).
* **What files will be uploaded** (just 4 files - your script plus a
couple of metadata files).
If something looks wrong here (e.g., the agent name has a typo, or the
tarball is way bigger than you expected because you have a 200 MB
dataset in the same folder), fix it now. Dry runs are cheap.
> **Why "tarball"?** A tarball is just a bundle of files squished into
> one. Bindu packages up your folder into a single compressed file,
> uploads that one file to the VM, and unpacks it on the other side.
> Faster than uploading files one by one.
***
## Step 2: actually deploy
```bash theme={null}
bindu deploy agent.py --runtime=boxd
```
The first deploy takes about a minute. Here's what you'll see scrolling
past in your terminal:
```
warning: dropped 2 sensitive file(s) from the deploy tarball
✓ runtime-boxd-example serving at https://runtime-boxd-example.boxd.sh
[runtime-boxd-example] INFO Generated agent_id: 80fc00b6-a5ac-...
[runtime-boxd-example] INFO Initializing DID extension...
[runtime-boxd-example] INFO ✅ DID configuration and keys pass integrity check
[runtime-boxd-example] INFO Creating agent manifest...
[runtime-boxd-example] INFO Agent 'did:bindu:...' successfully bindufied!
[runtime-boxd-example] INFO Starting uvicorn server at 0.0.0.0:3773...
[runtime-boxd-example] INFO ✅ Storage initialized: InMemoryStorage
[runtime-boxd-example] INFO ✅ TaskManager started
[runtime-boxd-example] INFO Application startup complete.
```
A few things to notice:
* **"dropped 2 sensitive file(s)"** - bindu found things in your folder
that look like secrets (e.g., `.env`, `.pem` keys) and refused to
upload them. This is a safety net: a VM with a public IP is the *last*
place you want your API keys to live. We'll cover how to pass secrets
*correctly* in a moment.
* **"✓ runtime-boxd-example serving at https\://..."** - there it is.
Your agent is alive on the internet at that URL. Bookmark it.
* **All the `[runtime-boxd-example]` lines** - these are the logs from
*inside the VM*, streamed back to your terminal. The deploy command
stays in the foreground showing you logs until you hit Ctrl-C.
Leave the deploy command running. Open another terminal for the next
step.
> **What just happened:** bindu tar+gzip'd your project, told boxd
> "please make me a Linux VM," waited for it to boot, sha256-verified
> the upload, extracted to `/home/boxd/app`, ran
> `pip install --break-system-packages bindu` plus your `pyproject.toml`
> /`requirements.txt`, started your agent as
> `setsid nohup python3 /home/boxd/app/agent.py`, and polled `/health`
> on the boxd-assigned public URL until it returned 200. That's it.
***
## Step 3: talk to your live agent
In a fresh terminal:
```bash theme={null}
# Set this once
URL="https://runtime-boxd-example.boxd.sh"
# Is it alive?
curl $URL/health
```
You'll see something like:
```json theme={null}
{
"version": "0.3.14",
"health": "healthy",
"application": {
"agent_did": "did:bindu:you_at_example_com:runtime-boxd-example:80fc00b6-..."
},
"status": "ok",
"ready": true,
"uptime_seconds": 18.11
}
```
"Healthy". "Ready". Good. Notice the `agent_did` - that's your agent's
cryptographic identity. We'll come back to it.
Now let's send it an actual message. Bindu agents speak a protocol
called **A2A** ("agent-to-agent"). It's just JSON over HTTP, but the
shape is opinionated - every message needs a unique ID (a UUID), and
messages live inside *tasks*, which live inside *contexts* (think:
conversation threads).
The shortest possible "hello":
```bash theme={null}
REQ_ID=$(uuidgen)
MSG_ID=$(uuidgen)
CTX_ID=$(uuidgen)
TASK_ID=$(uuidgen)
curl -s -X POST $URL/ \
-H 'Content-Type: application/json' \
--data-raw "{
\"jsonrpc\": \"2.0\",
\"id\": \"$REQ_ID\",
\"method\": \"message/send\",
\"params\": {
\"configuration\": {\"acceptedOutputModes\": [\"text\"]},
\"message\": {
\"role\": \"user\",
\"kind\": \"message\",
\"parts\": [{\"kind\": \"text\", \"text\": \"hello!\"}],
\"messageId\": \"$MSG_ID\",
\"contextId\": \"$CTX_ID\",
\"taskId\": \"$TASK_ID\"
}
}
}" | python -m json.tool
```
You'll get back a *task object* - the agent has accepted your message
and is processing it. Pull out the task ID it returned:
```json theme={null}
{
"result": {
"id": "0df35c9d-b96d-...",
"status": {"state": "submitted"}
}
}
```
Now ask for the result:
```bash theme={null}
# Replace with the "id" from the previous response
curl -s -X POST $URL/ \
-H 'Content-Type: application/json' \
--data-raw "{
\"jsonrpc\": \"2.0\",
\"id\": \"$(uuidgen)\",
\"method\": \"tasks/get\",
\"params\": {\"taskId\": \"\"}
}" | python -m json.tool
```
And there's your echo, back from the VM:
```json theme={null}
{
"result": {
"status": {"state": "completed"},
"artifacts": [
{
"name": "result",
"parts": [
{
"text": "hello!",
"metadata": {
"did.message.signature": "Gj7ar6GJdTrjD8asKT24..."
}
}
]
}
]
}
}
```
The `did.message.signature` field is the agent *cryptographically
signing its response*. Anyone receiving this artifact can verify the
agent really sent it (and nobody tampered with it in transit) using the
agent's public DID. You didn't have to write a line of crypto code -
bindu handled it.
You just had a complete round-trip with an agent running in a VM you
don't manage, on a domain you don't own, with a signature you can
verify. That's the whole point.
***
## Step 4: pausing your VM (so you stop paying for it)
When you're done experimenting, head back to the terminal where
`bindu deploy` is still running. Press **Ctrl+C**.
By default, that **suspends** your VM. Suspending means: "freeze the
machine in its current state, keep the disk around, stop billing for
CPU." Cheap to keep, instant to wake up.
Next time you run `bindu deploy agent.py --runtime=boxd`, the same VM
resumes in a couple of seconds with everything exactly as you left it -
DID keys, conversation history, the lot.
If you want different behavior on Ctrl-C, pass `--on-exit`:
| Flag value | What happens on Ctrl-C |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `--on-exit=suspend` (default) | Freeze the VM. Keeps disk, stops CPU billing. Fast resume. |
| `--on-exit=destroy` | Delete the VM entirely. You'll start fresh next time. |
| `--on-exit=detach` | Leave the VM running. Bills continue. Useful when you want the agent to keep serving even after you close your laptop. |
If you want the VM to stay running but go to sleep automatically
during idle periods, use `--auto-suspend`:
```bash theme={null}
bindu deploy agent.py --runtime=boxd --auto-suspend=60
```
This means: "after 60 seconds with no HTTP requests, suspend yourself."
The next incoming request wakes it back up. Great for cost control on
agents that don't get traffic 24/7.
> **One known wart:** in bindu v2026.20.2, `--on-exit=suspend` sometimes
> doesn't fire cleanly when you hit Ctrl-C from a non-interactive shell
> (like a script). If you suspect the VM kept running, check the boxd
> dashboard. To force-suspend from Python:
>
> ```python theme={null}
> from boxd.aio import Compute
> import asyncio, os
>
> async def main():
> async with Compute(api_key=os.environ["BOXD_API_KEY"]) as c:
> box = await c.box.get("runtime-boxd-example")
> await box.stop() # or .destroy() to delete it entirely
>
> asyncio.run(main())
> ```
>
> Tracked in our bug list - interactive Ctrl-C from a normal terminal
> works fine; this is a corner case.
***
## What about secrets?
Your real agents will need API keys (OpenAI, Anthropic, etc.). **Never
put these in your script.** Two reasons:
1. If you check the script into git, your key goes with it.
2. Bindu refuses to upload `.env` files for the same reason.
The right way: pass them as `--env` flags on `bindu deploy`:
```bash theme={null}
bindu deploy agent.py --runtime=boxd \
--env OPENAI_API_KEY=sk-... \
--env ANTHROPIC_API_KEY=sk-ant-...
```
These get injected into the VM's environment, so your script can read
them with `os.getenv("OPENAI_API_KEY")` exactly like it would locally.
They don't end up in the source tarball, and they don't end up in git.
***
## Useful follow-up commands
While your VM is running:
| Command | What it does |
| --------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `bindu logs runtime-boxd-example` | Stream your agent's stdout to your terminal. Like `tail -f`. |
| `bindu logs runtime-boxd-example --no-follow` | Print the log so far and exit. |
| `bindu shell runtime-boxd-example` | Open an interactive bash shell *inside* the VM. Useful when something's broken and you want to poke around. |
The agent name (`runtime-boxd-example` here) is the same as
`config["name"]` in your script.
***
## Things that will happen at least once
**"BOXD\_API\_KEY or BOXD\_TOKEN must be set"** - you forgot the
`export BOXD_API_KEY=...` step. Check `echo $BOXD_API_KEY` is not
empty.
**"agent at \ did not become healthy within 60s"** - the VM is up
but your script crashed before serving. Run `bindu logs ` and look
at the bottom for the actual Python error. Common cause: you imported a
package that isn't in `pyproject.toml` (or `requirements.txt`).
**"old code is running after redeploy"** - bindu tracks the in-VM agent
PID at `/tmp/bindu-agent.pid` and on every redeploy sends SIGTERM, waits
up to 5s, then SIGKILL before exec'ing the new process (see
[`_start_agent`](https://github.com/getbindu/Bindu/blob/main/bindu/runtime/boxd_provider.py)).
If you still see stale output, the upload itself was probably
truncated — the deploy now sha256-verifies every `box.write_file` and
retries up to 3 times on mismatch, so check the warning lines above
the `✓ ... serving at` banner. As a last resort, `bindu shell `,
`cat /tmp/bindu-agent.pid` vs `pgrep python3`, and kill the stale PID
manually.
**"my agent works locally but fails inside the VM with `ModuleNotFoundError`"**
* the VM only installs the deps it can see. If your dep isn't in a
`pyproject.toml`, `requirements.txt`, or `setup.py` *inside the folder
that gets uploaded*, the VM doesn't know to install it. Easiest fix:
write a tiny `pyproject.toml` next to your `agent.py` listing the deps.
**"the tarball is way too big"** - bindu caps the upload at 50 MB
compressed. If you've got a virtualenv or model files in the same
folder, exclude them with a `.binduignore` file (works like
`.gitignore`):
```
# .binduignore
.venv/
data/
*.bin
```
***
## Where to go next
* **[Boxd runtime reference](/bindu/runtime/box)** - every `bindu deploy`
flag spelled out in detail. Read this when you start needing finer
control (bigger VMs, custom images, etc.).
* **[Custom image (A1 mode)](/bindu/runtime/custom-image)** - for when
your dep can't be `pip install`-ed and you need a pre-baked Docker
image.
* **[Overview](/bindu/runtime/overview)** - runtime providers and the
reasoning behind the design.
* **[boxd's own docs](https://docs.boxd.sh)** - the microVM platform
itself: pricing, regions, the Python SDK we're using under the hood.
## What you have now
You've now got a complete loop: write a script, deploy it, talk to it,
suspend it, redeploy it. That's the whole workflow. Everything else
(secrets, sizing, custom images) is just dialing in details on top of
this loop.
Runtime makes your -
agents talk over internet effortlessly.
# Skills
Source: https://docs.getbindu.com/bindu/skills/introduction/overview
Define what your agent can do and make it discoverable across the Internet of Agents
An agent without declared capabilities is a black box. Other agents, orchestrators, and clients have no way to know what it can do, whether it is the right agent for a task, or how to interact with it correctly.
Skills solve that. They are the formal declaration of what your agent knows how to do — structured, discoverable, and published through the agent card and a set of dedicated discovery endpoints.
## Why Skills Matter
In a multi-agent network, capability discovery is how work gets routed to the right agent. Without a standard way to declare skills, every integration becomes a custom handshake.
| Without skills | With Bindu skills |
| ------------------------------------------------ | -------------------------------------------------------- |
| Capabilities are implicit or undocumented | Skills are declared in a structured manifest |
| Orchestrators cannot discover what an agent does | Skills are published at `/agent/skills` |
| Task routing requires manual configuration | Agents can be matched to tasks by capability |
| No standard input/output contract | Each skill declares its `input_modes` and `output_modes` |
| Fine for single-agent scripts | Required for multi-agent systems |
That is the shift: skills turn an agent from a private script into a discoverable, composable node in the Internet of Agents.
Skills are defined as folders inside your project (conventionally under
`skills/`). Bindu reads them automatically during `bindufy()` and exposes them
on the agent card and a family of `/agent/skills` endpoints.
## How Bindu Skills Work
A skill is a directory that contains either a `skill.yaml` manifest, a `SKILL.md` markdown file with YAML frontmatter, or both. The loader in `bindu/utils/skills/loader.py` reads whichever it finds.
### The Skills Model
A minimal skill — using the canonical `skill.yaml` format — looks like this:
```
skills/
└── research/
└── skill.yaml
```
```yaml theme={null}
id: research-v1
name: research
version: 1.0.0
author: you@example.com
description: |
Multilingual web research skill that searches the internet and
summarizes findings in the user's language.
tags:
- research
- web-search
input_modes:
- text/plain
- application/json
output_modes:
- text/plain
- application/json
examples:
- "What is the Bindu framework?"
- "Latest news about AI agents"
```
Skills are defined in YAML (or Markdown with YAML frontmatter). No code is
required to declare what your agent can do.
Published at `/agent/skills`, `/agent/skills/{id}`, and `/agent/skills/{id}/documentation`
so orchestrators and other agents can find them.
Multiple skills per agent. Each skill is independently addressable by `id`.
### Two manifest formats: `skill.yaml` and `SKILL.md`
Bindu supports two on-disk formats. Pick whichever fits your workflow:
| File | When to use it |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `skill.yaml` | Pure metadata. Easy to diff, easy to generate from a template. The shape used by every Python example in the repo. |
| `SKILL.md` | YAML frontmatter + a rich Markdown body. Lets you ship operator-readable documentation alongside the manifest. Used by the TypeScript SDK examples. |
| Both in the same folder | Allowed. `skill.yaml` provides the metadata; the Markdown body of `SKILL.md` is attached as `markdown_content` for richer documentation. |
A `SKILL.md` file looks like this:
```markdown theme={null}
---
id: question-answering-v1
name: question-answering
version: 1.0.0
author: dev@example.com
tags:
- question-answering
- conversation
input_modes:
- text/plain
- application/json
output_modes:
- text/plain
- application/json
---
# Question Answering Skill
General-purpose question answering. Handles conversational queries,
explanations, code generation, analysis, and creative writing.
## Capabilities
### Conversational Q&A
- Direct question answering with contextual understanding
- Multi-turn conversation with history awareness
```
If neither `skill.yaml` nor `SKILL.md` exists in the folder, the loader raises `FileNotFoundError` with a message naming both filenames.
### The Lifecycle: Define, Register, Discover
```mermaid theme={null}
sequenceDiagram
participant Dev as Developer
participant Bindu as bindufy()
participant AgentCard as /.well-known/agent.json
participant SkillsEndpoint as /agent/skills
participant Orchestrator as Orchestrator / Caller
Note over Dev,Bindu: 1. Define
Dev->>Bindu: skills/ directory with skill.yaml or SKILL.md
Bindu->>Bindu: Load and validate skill manifests
Note over Bindu,SkillsEndpoint: 2. Register
Bindu->>AgentCard: Embed minimal skill refs in agent card
Bindu->>SkillsEndpoint: Expose rich skill metadata endpoints
Note over SkillsEndpoint,Orchestrator: 3. Discover
Orchestrator->>SkillsEndpoint: GET /agent/skills
SkillsEndpoint-->>Orchestrator: { skills: [...], total: N }
Orchestrator->>Orchestrator: Match task to agent by skill
```
Create a folder for each skill. The folder name is what most projects use
as the directory path in the config; the `id` field inside the manifest is
the actual identifier exposed on the wire.
```
your-agent/
├── main.py
├── agent_config.json
└── skills/
├── research/
│ └── skill.yaml
└── translate/
└── skill.yaml
```
Each `skill.yaml` (or `SKILL.md`) declares the skill's identity, tags,
`input_modes`, `output_modes`, and examples.
Reference the skill directories in your agent config:
```json theme={null}
{
"author": "you@example.com",
"name": "research_agent",
"description": "A research assistant agent",
"version": "1.0.0",
"skills": [
"skills/research",
"skills/translate"
],
"deployment": {
"url": "http://localhost:3773",
"expose": true
}
}
```
Bindu reads the manifests during `bindufy()` and registers them
automatically. No additional code is needed.
Once the agent is running, skills are available through several endpoints:
```bash theme={null}
# Agent card — minimal skill refs (id, name, documentation_path)
curl http://localhost:3773/.well-known/agent.json
# Skills list — rich metadata for all skills
curl http://localhost:3773/agent/skills
# Single skill — full metadata for one skill
curl http://localhost:3773/agent/skills/research-v1
# Raw documentation (the original skill.yaml / SKILL.md body)
curl http://localhost:3773/agent/skills/research-v1/documentation
```
The `/agent/skills` response is wrapped, not a bare array:
```json theme={null}
{
"skills": [
{
"id": "research-v1",
"name": "research",
"description": "Multilingual web research skill...",
"version": "1.0.0",
"tags": ["research", "web-search"],
"input_modes": ["text/plain", "application/json"],
"output_modes": ["text/plain", "application/json"],
"examples": ["What is the Bindu framework?"]
}
],
"total": 1
}
```
The agent card itself only carries a minimal reference per skill, to keep
the card payload small:
```json theme={null}
{
"skills": [
{
"id": "research-v1",
"name": "research",
"documentation_path": "http://localhost:3773/agent/skills/research-v1"
}
]
}
```
***
## The Skill Manifest
The `skill.yaml` (or `SKILL.md` frontmatter) is the complete definition of a skill. Only `id` and `name` are strictly required; the more you declare, the more useful the skill is for discovery and routing.
```yaml theme={null}
id: question-answering-v1
name: question-answering
version: 1.0.0
author: you@example.com
description: |
Answers questions using web search and reasoning.
tags:
- research
- search
- qa
input_modes:
- text/plain
output_modes:
- text/plain
- application/json
examples:
- "What is the capital of France?"
- "Who won the 2024 Nobel Prize in Physics?"
- "Summarize the latest news on AI regulation"
```
### Fields
| Field | Required | Description |
| -------------- | -------- | -------------------------------------------------------------------------------------------- |
| `id` | Yes | Unique identifier for the skill. Conventionally suffixed with a version, e.g. `research-v1`. |
| `name` | Yes | Human-readable name shown in the agent card. |
| `description` | No | What the skill does — used for capability matching. |
| `version` | No | Skill version string. Defaults to `"unknown"` if omitted. |
| `author` | No | Author email or identifier. |
| `tags` | No | Keywords for discovery and routing. |
| `examples` | No | Sample inputs that demonstrate the skill. |
| `input_modes` | No | MIME types the skill accepts (default: `["text/plain"]`). |
| `output_modes` | No | MIME types the skill produces (default: `["text/plain"]`). |
The wire format uses snake\_case: `input_modes` and `output_modes`. The same
fields appear under those exact keys in `/agent/skills` responses, so
orchestrators see the manifest as you wrote it.
Skills carrying a `SKILL.md` body also expose two extra fields on the wire:
* `documentation_content` — the raw file contents (returned in full from `/agent/skills/{id}/documentation`).
* `markdown_content` — the Markdown body below the frontmatter (returned in skill detail responses for clients that want rich text).
The list endpoint strips `documentation_content` to keep payloads small and surfaces a boolean `has_documentation` flag in single-skill detail responses instead. Use `/agent/skills/{id}/documentation` to fetch the full document.
***
## Multiple Skills
An agent can declare as many skills as it has capabilities. Each skill is independently addressable and can have its own I/O contract.
```
skills/
├── research/
│ └── skill.yaml
├── translate/
│ └── skill.yaml
├── collaborate/
│ └── skill.yaml
└── code-review/
└── skill.yaml
```
```json theme={null}
{
"skills": [
"skills/research",
"skills/translate",
"skills/collaborate",
"skills/code-review"
]
}
```
All declared skills appear in the agent card (as minimal refs) and in the full `/agent/skills` response. Orchestrators can inspect the full list and route tasks to the most appropriate skill.
### Inline skills
You can also declare a skill inline in the config without a folder on disk. This is useful for one-off skills or for SDKs that don't ship a `skills/` directory:
```json theme={null}
{
"skills": [
"skills/research",
{
"name": "ping",
"description": "Health check — replies with 'pong'",
"tags": ["health"]
}
]
}
```
The loader accepts a mixed list: strings resolve to folder paths, dictionaries become inline skills. Inline skills must contain at minimum a `name`.
***
## Skills and Task Routing
In a multi-agent system, an orchestrator fetches the skills of available agents and matches incoming tasks to the right agent based on skill tags, descriptions, and examples.
```mermaid theme={null}
graph LR
Task[Incoming Task
summarize this document] --> Orchestrator
Orchestrator --> AgentA[Agent A
skills: question-answering]
Orchestrator --> AgentB[Agent B
skills: summarization, translation]
Orchestrator --> AgentC[Agent C
skills: code-review, data-analysis]
AgentB --> Result[Task Routed to Agent B]
style Task fill:#e1f5ff
style Orchestrator fill:#fff4e1
style AgentA fill:#ffe1e1
style AgentB fill:#d4f5e1
style AgentC fill:#ffe1e1
style Result fill:#d4f5e1
```
The orchestrator does not need to know the agent's internals. The skill manifest is the contract.
***
## Real-World Use Cases
The `multilingual-collab-agent` example in `examples/multilingual-collab-agent`
declares three skills as separate folders: `research`, `translate`, and
`collaborate`. An orchestrator can route a translation task directly to
the right skill without guessing.
```json theme={null}
{
"skills": [
"skills/research",
"skills/translate",
"skills/collaborate"
]
}
```
A focused agent that only does one thing well. Declaring a single skill
makes its purpose unambiguous and easy to route to.
```yaml theme={null}
id: code-review-v1
name: code-review
description: Reviews Python code for bugs, style, and security issues
tags:
- code
- python
- review
- security
input_modes:
- text/plain
- text/x-python
output_modes:
- text/plain
- application/json
```
In a swarm, each agent declares its skills. The orchestrator builds a
capability map at startup by fetching `/agent/skills` from every agent,
then routes tasks dynamically based on what each agent can do.
If your skill descriptions are themselves part of the product, declare
them under `private_skills` in the config and supply an `allowed_dids`
allowlist. The public catalog stays generic; partners on the allowlist
get the full menu at `/agent/private.json`. See the
[Private skills](/bindu/skills/private_skills/private_skills) page and
the runnable example at `examples/private_skills_agent/`.
***
## Project Structure
Two real examples in this repo show the layout in practice:
```
examples/multilingual-collab-agent/
├── main.py
├── agent_config.json
└── skills/
├── research/
│ └── skill.yaml
├── translate/
│ └── skill.yaml
└── collaborate/
└── skill.yaml
```
```
examples/typescript-openai-agent/
└── skills/
└── question-answering/
└── SKILL.md # YAML frontmatter + Markdown body
```
Add more skills by creating new folders under `skills/` and adding a `skill.yaml` (or `SKILL.md`) to each one, then listing the folder path in the `skills` array of your agent config.
***
## Where to look in the code
* Loader: [`bindu/utils/skills/loader.py`](../../../../bindu/utils/skills/loader.py) — handles both `skill.yaml` and `SKILL.md`, plus inline dict skills.
* List endpoint: [`bindu/server/endpoints/skills.py`](../../../../bindu/server/endpoints/skills.py) — implements `/agent/skills`, `/agent/skills/{id}`, and `/agent/skills/{id}/documentation`.
* Agent card endpoint: [`bindu/server/endpoints/agent_card.py`](../../../../bindu/server/endpoints/agent_card.py) — minimizes each skill to `{id, name, documentation_path}` before serializing.
* Route registration: [`bindu/server/applications.py`](../../../../bindu/server/applications.py) — wires `/.well-known/agent.json`, `/agent/skills`, and `/agent/private.json`.
***
## Related
* [Private skills](/bindu/skills/private_skills/private_skills) — serve a public catalog to everyone and a fuller catalog to allowlisted DIDs only.
* [Architecture](/bindu/concepts/task-first-and-architecture)
* [A2A Protocol](https://google.github.io/A2A/)
Skills are how agents introduce themselves to the network -
not by what they are, but by what they can do.
# Private skills
Source: https://docs.getbindu.com/bindu/skills/private_skills/private_skills
Serve a public skill catalog to the world and a full catalog to approved partners only.
## Think the moment
Your agent advertises its skills the moment it boots. Anyone hitting
`/.well-known/agent.json` sees the full list - name, description, everything.
That's perfect for an open research agent that wants to be found. It's a
disaster for a commercial agent where the skill descriptions ARE the product.
Picture you've built a drug interaction agent for a hospital network.
Its real value isn't "I do pharmacology lookups" - every med-tech vendor does that.
It's "I flag contraindications across a patient's active prescriptions against our formulary, weighted by renal function markers from the last 90 days of lab results."
That sentence took your clinical team two years to refine.
Sitting plaintext on a public URL, it's your competitor's two-year shortcut.
***
## You should
Serve two views of the same agent - without changing what the agent actually
does:
* **A public view** - generic. "We do compliance." Routing gateways can still
find you without learning what you actually do well.
* **A partner view** - your real menu, but only to wallets you've
pre-approved.
That's what `private_skills` + `allowed_dids` give you.
***
## Here's how to set it up
### 1. Understand the split
```
Public web crawler Allowlisted partner agent
│ │
▼ ▼
/.well-known/agent.json /agent/private.json
│ │
▼ ▼
┌────────┐ ┌───────────────────┐
│ skills │ │ skills │
│ only │ ← same agent, two surfaces → │ + private_skills │
└────────┘ └───────────────────┘
```
The split is **per-skill, in the agent's config**. Public skills go in
`skills:`. Private skills go in `private_skills:`. The agent exposes only
the public list on the well-known URL and stands the private list up at a
second URL behind a two-layer gate.
### 2. Add three things to your config
```python theme={null}
config = {
"author": "acme.compliance@example.com",
"name": "acme_compliance_agent",
"deployment": {"url": "http://localhost:3773"},
"skills": [
"skills/public-greet",
"skills/public-status",
],
"private_skills": [
"skills/cbam-line-classify",
"skills/eudr-due-diligence",
],
"allowed_dids": [
"did:bindu:partner-bank:agent:abc123",
"did:bindu:partner-customs-broker:agent:def456",
],
}
```
This is exactly what `examples/private_skills_agent/acme_compliance_agent.py` ships
with — copy it, swap in your own DIDs, and you're done.
On disk, public and private skills look identical - each is a folder under
`skills/` with a `skill.yaml`. The split is purely a config-level decision.
Move a skill from public to private (or back) by editing two lines.
When neither `private_skills` nor `allowed_dids` is set, nothing changes.
The private endpoint isn't even registered. This feature is fully opt-in.
### 3. Understand the gate
Two layers stand between an HTTP request and the private catalog:
1. **Hydra middleware** - verifies the OAuth bearer token and confirms the
request was signed with the caller's DID private key. Rejects at 401 if
anything doesn't check out.
2. **The allowlist** - even an authenticated DID isn't automatically trusted.
The handler compares the caller's DID against `manifest.allowed_dids`. If it is not
on the list: 403.
Knowing who you are isn't enough - you also have to be on the list.
### 4. Try every path
Boot the runnable example:
```bash theme={null}
uv run python examples/private_skills_agent/acme_compliance_agent.py
```
**Random web crawler:**
```bash theme={null}
curl -s http://localhost:3773/.well-known/agent.json | jq '.skills[].id'
```
"public-greet"
"public-status"
Two skills. The contraindication-check and renal-adjusted-dosing skills don't appear.
**Outsider trying to peek:**
```bash theme={null}
curl -s -w "%{http_code}\n" http://localhost:3773/agent/private.json
```
```
{"error":"Authentication required for private agent card"}
401
```
The route exists but refuses without auth.
**Valid DID, not your partner:**
```
{"error":"DID not authorized for this agent's private skills"}
403
```
Server logs:
```
WARN private_catalog_access caller=did:bindu:somebody-else:agent:xyz ip=10.0.0.7 result=denied reason=not_in_allowlist
```
**Allowlisted partner:**
The merged card mirrors the public agent card shape but includes
`private_skills` in the `skills` array. Each entry is the minimal skill
reference (`id`, `name`, `documentation_path`) that Bindu puts on the
agent card; orchestrators follow the `documentation_path` to
`/agent/skills/{id}` for the full metadata.
```json theme={null}
{
"id": "...",
"name": "acme_compliance_agent",
"skills": [
{"id": "public-greet", "name": "greet", "documentation_path": "http://.../agent/skills/public-greet"},
{"id": "public-status", "name": "status", "documentation_path": "http://.../agent/skills/public-status"},
{"id": "cbam-line-classify", "name": "cbam-line-classify", "documentation_path": "http://.../agent/skills/cbam-line-classify"},
{"id": "eudr-due-diligence", "name": "eudr-due-diligence", "documentation_path": "http://.../agent/skills/eudr-due-diligence"}
]
}
```
Audit log:
```
INFO private_catalog_access caller=did:bindu:partner-bank:agent:abc123 ip=10.0.0.5 result=granted
```
The log line format is emitted verbatim by
[`bindu/server/endpoints/private_agent_card.py`](../../../../bindu/server/endpoints/private_agent_card.py) —
grep for `private_catalog_access` to see exactly who's been looking.
### 5. Manage partners over time
**Onboarding a partner** - get their DID, add it to `allowed_dids`, restart.
**Removing a partner** - delete their DID from the list, restart. Their next
request fails at the allowlist check. No race window, no key to chase.
**Audit trail** - every authenticated request to `/agent/private.json`
produces a structured log entry with `caller=`, `ip=`, `result=`, `reason=`.
Grep for `private_catalog_access` to see exactly who's been looking and when.
***
## Result
The web crawler sees a generic public catalog. Your approved partners see the
full menu. Nothing else changed - same agent, same skills, same code.
### When to use this - and when it's overkill
**Use it if:**
* Your skill descriptions reveal your roadmap (compliance, financial signals,
security research, anything proprietary).
* You're selling to partners under contracts that include "competitors can't
see our capabilities."
* You want tier-based discovery - gold partners see the full menu; trial users
see only the public preview.
**Skip it if:**
* Your agent is meant to be discovered - open research, demo agents, community
tools.
* You're behind a corporate firewall and only your own agents can reach the
URL anyway.
* You're early-stage and any discovery is good discovery.
### What this doesn't protect against
| Threat | Protected? |
| --------------------------------------------------- | ---------------------------------------- |
| Random web crawler indexing your menu | **Yes** |
| Unauthenticated peer hitting the private URL | **Yes** |
| Authenticated peer whose DID isn't on your list | **Yes** |
| An authorized partner re-publishing your catalog | **No** - use NDAs |
| Database backups containing skill descriptions | **No** - plaintext on disk by design |
| Operator-untrusted environments (multi-tenant PaaS) | **No** - encryption at rest is a Phase 2 |
For self-hosted Bindu deployments, the gate is enough. For enterprise
deployments under strict SOC2 controls, talk to us before shipping.
### Where to look in the code
* Handler: [`bindu/server/endpoints/private_agent_card.py`](../../../../bindu/server/endpoints/private_agent_card.py) — the `private_agent_card_endpoint` function, with the 401/403 branches and the `private_catalog_access` log lines.
* Config plumbing: [`bindu/penguin/bindufy.py`](../../../../bindu/penguin/bindufy.py) — search for `private_skills` and `allowed_dids`; both flow from the config dict into the `AgentManifest`.
* Manifest fields: [`bindu/common/models.py`](../../../../bindu/common/models.py) — `AgentManifest.private_skills: list[Skill]` and `AgentManifest.allowed_dids: list[str]`.
* Route registration: [`bindu/server/applications.py`](../../../../bindu/server/applications.py) — the `/agent/private.json` route is only registered when either `private_skills` or `allowed_dids` is set.
* Tests: [`tests/unit/server/endpoints/test_private_agent_card.py`](../../../../tests/unit/server/endpoints/test_private_agent_card.py) — covers the 401, 403, and 200 branches with a stub middleware.
* Runnable example: [`examples/private_skills_agent/`](../../../../examples/private_skills_agent/) — `acme_compliance_agent.py` plus four skill folders (two public, two private).
### Related
* [Skills overview](/bindu/skills/introduction/overview) — the underlying skill system both public and private skills are built on.
Private skills lets you -
control what partners see.
# v2026.12.5
Source: https://docs.getbindu.com/changelog/v2026.12.5
A new document-reading agent, many-currency payments, and a pile of reliability fixes
## A big release with a lot of small wins
This one touches a lot of the system. The headline changes:
* A new agent that can read PDFs and Word docs
* Payments that handle multiple currencies at once
* A handful of reliability fixes in the scheduler and storage
* The auth middleware got a rewrite for better performance
* The UI got kinder to screen readers
* 44 new tests so we break less in the future
***
## Before you upgrade
**Config validation got stricter.** If your `agent_config.json` is missing `deployment.url` or another required field, the agent now fails immediately on startup instead of crashing later. This is better — you find out right away. Just make sure your config is complete.
**Some constants moved.** If your code imports constants from deep paths inside the extension modules, check that the imports still resolve. A few settings were moved into dedicated constants modules.
***
## What's new
### An agent that reads documents
There's a new built-in agent that understands PDFs and DOCX files. Give it a document and it can work with the content inside.
On the upload side, the frontend only lets through allowed file types, and `FilePart.text` (the extracted text from the document) is carried through the whole pipeline so later steps can actually use it.
### Payments in more than one currency
Until now, a payment setup could only describe one currency. Now a single config can require multiple currencies and multiple asset types. A freelancer agent could ask for USDC on one chain, ETH on another, stable coins somewhere else — all defined in one place.
The payment validation is also stricter. Duplicate payment info can't sneak in, and half-broken payment states don't crash the whole endpoint. The A2A `message/send` endpoint no longer returns a generic 500 when something is off — you get a clear error instead.
### Two new example agents
* **DSPy agent** — a question-answering agent built with [DSPy](https://dspy.ai), with tests you can learn from.
* **LangGraph agent** — shows how to wire up a structured, multi-step workflow inside Bindu using [LangGraph](https://langchain-ai.github.io/langgraph/).
### A friendlier UI
* The Agent Inspector is now collapsible, with clearer messages when there's nothing to show. Much better for first-time users.
* "Skip to content" links and ARIA landmarks were added, so screen readers can navigate the UI properly.
* That annoying flicker when you switched between chats? Gone.
***
## What got fixed
**Scheduler.** Fixed three separate issues: a deadlock that could happen under load (AnyIO buffer contention), a CPU-eating loop in rare edge cases, and trace serialization failing when traces got very large.
**Storage.** Made the in-memory subsystem less likely to run out of memory. Database indexing is faster too.
**Auth middleware.** Rewrote the Hydra middleware from synchronous code to pure ASGI. This sounds technical, but the practical effect is real: better concurrency, WebSocket support, and proper cleanup of connections so nothing leaks.
**Configuration.** Now fails fast if `deployment.url` is missing, and the error messages for nested missing fields are much clearer.
***
## What got better behind the scenes
### More tests, fewer surprises
We added 44 new tests, focused on the pieces that matter most:
| Area | Tests added | Coverage before → after |
| ---------------- | ----------- | ----------------------- |
| ManifestWorker | +15 | 58% → 83% |
| BinduApplication | +20 | 16% → 30% |
| TaskManager | +9 | 67% → 75% |
Overall test coverage went from **58.59% to 60.11%** with **688 tests** passing.
***
## Migration
Make sure `deployment.url` is set. The validator now insists on it.
If you have custom payment setups, double-check they follow the new multi-currency rules.
If you've forked the scheduler, storage, or Hydra auth modules, pull this release in so you get the deadlock and ASGI fixes.
***
## Thanks
Huge thanks to everyone who made this release happen: **Paraschamoli, chandan-1427, varshayadav6, codesoumya2006, Prateekiiitg56, Co-vengers, nexpectArpit, AseemPrasad, shrguhaneogi-pixel, udaykiran243, arnab2001, Suvam-paul145, Subhajitdas99, DeviPadmavathi-LE, PardhaviArimilli, A-VISHAL, amr1tanshu,** and **underratedgitter.**
# v2026.20.2
Source: https://docs.getbindu.com/changelog/v2026.20.2
Hybrid auth fail-closed hotfix, plus bindu deploy and the boxd runtime
## Security Hotfix and `bindu deploy`
Two things happening in one release. First, a high-severity fix: the hybrid OAuth2 + DID middleware on the prior version had a fail-open path that silently collapsed the documented two-layer auth model to OAuth-only for any caller willing to omit the DID signature header. Second, a feature: `bindu deploy my_agent.py --runtime=boxd` now takes any working bindu script and ships it to a public HTTPS-served microVM with one command. No Dockerfile, no reverse proxy, no TLS plumbing.
The rest of the release is the gateway recipes work, DID provenance in SSE, agent-card fetching, a Hydra token-cache revocation fix, expanded examples, and broad doc refreshes including a beginner-friendly quickstart for the boxd runtime.
***
## Security First
**High-severity fix.** If you run `AUTH__ENABLED=true` with `did:*` OAuth clients on a public-facing agent, upgrade immediately. A stolen bearer token was previously sufficient to impersonate a DID agent for the full token TTL by simply omitting the `X-DID-Signature` header.
### What Was Broken
`_verify_did_signature_asgi` had two fail-open branches. If a `did:*` client called without an `X-DID-Signature` header, the middleware returned `is_valid=True` and let the request through. Same story if the client's Hydra `metadata.public_key` was missing. The signature gate was advisory in both cases.
### What's Fixed
Both branches now fail closed:
* **No signature header** → rejected with reason `missing_signature_headers`
* **No public key in Hydra metadata** → rejected with reason `public_key_unavailable`
Operator-facing warning logs explain how to remediate inline. There's no new config knob — the previous behavior was a bug, not a mode. A `did:*` client that cannot sign must either start signing or stop using a `did:*` `client_id`.
Bug walkthrough: `bugs/core/2026-04-18-did-signature-fail-open.md`.
### Bonus: Hydra Token Cache
The Hydra introspection cache held tokens for 5 minutes regardless of upstream revocation. Revoked tokens stayed valid until the cache expired. Now invalidation happens promptly. Coverage at `tests/unit/server/middleware/test_hydra_token_cache.py`.
***
## `bindu deploy` and the Boxd Runtime
Before this release, shipping a bindu agent to a stable public URL meant hand-rolling a Dockerfile, picking a hosting account, setting up a reverse proxy and TLS, and wiring port forwarding. Per agent. Every time.
Now:
```bash theme={null}
pip install 'bindu[runtime-boxd]'
export BOXD_API_KEY=
bindu deploy my_agent.py --runtime=boxd
```
That command provisions a microVM, ships your project source (with a sensitive-file denylist applied), installs deps, starts the agent, and prints a public HTTPS URL. Cold deploy is \~10–60s depending on dep weight. Warm redeploy is 1–15s with state preserved via suspend/resume on Ctrl-C.
### New CLI Surface
* `bindu deploy