# 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. *** Sunflower Logo Bindu treats work as something to track, coordinate, and complete explicitly , so multi-agent execution stays understandable as systems grow. Sunflower Logo 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)** Sunflower Logo 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)** Sunflower Logo 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). Sunflower Logo 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. Sunflower Logo 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)** Sunflower Logo 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)** Sunflower Logo 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 Sunflower Logo 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 Sunflower Logo 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. Sunflower Logo 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 Sunflower Logo 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 Sunflower Logo 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.

Bindu inbox — three-pane layout with folders, threads, and a signed message in the right rail

*** ## 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). Sunflower Logo 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.** ***