Runtime API
This document defines how the Zakardo Runtime exposes its functionality over HTTP, how clients consume it, and how the official SDK abstracts these interactions. It covers every endpoint mounted at
/zakardo/*, the SSE streaming protocol for real-time plan execution, the webhook system for async notifications, authentication integration, error responses, and the TypeScript client SDK.
Prerequisites: This document assumes familiarity with Full-Stack Framework, Execution Engine, Planner, Plan IR, Capability System, Policy and Governance, Plan Library, and Trace System.
1. Design Goals
Section titled “1. Design Goals”- One mount, everything included.
mountZakardo()returns a Hono sub-application with all endpoints pre-registered. Developers never manually wire Planner routes, Execution Engine routes, or Trace routes. - REST + SSE. Standard REST endpoints for CRUD operations and submissions. Server-Sent Events for real-time streaming during plan execution. No WebSocket (simpler, survivable across proxies, HTTP/2-native).
- JSON everywhere. All request bodies and response bodies are
application/json. SSE event data fields are JSON-serialized. - SDK-first API design. The HTTP API is designed to be consumed by the official SDK. Every endpoint has a corresponding SDK method. But the HTTP API is fully documented and usable without the SDK.
- Auth is external. The Runtime API assumes an authenticated user context is already present (resolved by the developer’s
authMiddleware). It reads user identity from a standardized context — it never performs authentication itself. - Errors are structured. Every error response follows a consistent envelope. HTTP status codes are semantically correct. Error bodies include machine-readable codes and human-readable messages.
- Versioned from day one. All endpoints are prefixed
/zakardo/v1/. Breaking changes require a new version prefix.
2. Route Architecture
Section titled “2. Route Architecture”2.1 Mount Point
Section titled “2.1 Mount Point”All Zakardo Runtime routes mount under /zakardo/v1/:
import { createZakardoApp } from '@zakardo/core';import config from '../../config/zakardo';import * as capabilities from '@my-app/capabilities';
export function mountZakardo() { return createZakardoApp({ config, capabilities: capabilities.all, });}
// apps/api/src/server.tsapp.use('/zakardo/*', authMiddleware);app.route('/zakardo', mountZakardo());createZakardoApp internally creates a Hono sub-application with all routes registered. The developer controls middleware (auth, CORS, rate limiting) on the mount point.
2.2 Route Map
Section titled “2.2 Route Map”| Method | Path | Description | Section |
|---|---|---|---|
POST | /zakardo/v1/intent | Submit an intent (triggers planning) | §3 |
GET | /zakardo/v1/intent/:intentId/stream | SSE stream for intent processing | §4 |
GET | /zakardo/v1/executions | List executions (paginated) | §5 |
GET | /zakardo/v1/executions/:executionId | Get execution details | §5 |
GET | /zakardo/v1/executions/:executionId/stream | SSE stream for execution progress | §4 |
POST | /zakardo/v1/executions/:executionId/approve | Approve a plan for execution | §5 |
POST | /zakardo/v1/executions/:executionId/reject | Reject a plan | §5 |
POST | /zakardo/v1/executions/:executionId/cancel | Cancel a running execution | §5 |
POST | /zakardo/v1/executions/:executionId/gate/:gateId | Respond to a gate | §6 |
POST | /zakardo/v1/executions/:executionId/interaction/:stepIndex | Respond to an interaction | §6 |
GET | /zakardo/v1/capabilities | List registered capabilities | §7 |
GET | /zakardo/v1/capabilities/:name | Get capability details | §7 |
GET | /zakardo/v1/traces | List traces (paginated) | §8 |
GET | /zakardo/v1/traces/:traceId | Get full trace | §8 |
GET | /zakardo/v1/plans | List plans in the Plan Library | §9 |
GET | /zakardo/v1/plans/:planId | Get plan details | §9 |
GET | /zakardo/v1/schema | Get schema metadata (entities, relations) | §10 |
GET | /zakardo/v1/health | Health check | §11 |
GET | /zakardo/v1/executions/:executionId/events | Poll execution events (non-SSE) | §5.6 |
3. Intent Submission
Section titled “3. Intent Submission”3.1 Submit Intent
Section titled “3.1 Submit Intent”The primary entry point for all agentic interactions.
Request:
POST /zakardo/v1/intentContent-Type: application/json{ "message": "Show me all deals closing this month", "mode": "expressed", "execution_mode": "live", "context": { "conversation_id": "conv_abc123", "metadata": { "source": "chat", "page": "/dashboard" } }}| Field | Type | Required | Description |
|---|---|---|---|
message | string | Yes | The user’s intent in natural language (for expressed mode). |
mode | "expressed" | "packaged" | "structured" | No | Intent input mode. Default: expressed. |
execution_mode | "live" | "dry_run" | "simulated" | No | Execution mode. Default: live. |
context | object | No | Additional context for the Planner. |
context.conversation_id | string | No | Conversation ID for multi-turn context. Auto-generated if omitted. |
context.metadata | object | No | Arbitrary metadata passed to the Planner. |
packaged_action | object | Conditional | Required when mode is packaged. Pre-built action payload. |
structured_payload | object | Conditional | Required when mode is structured. Form/wizard-produced payload. |
Response (synchronous):
HTTP/1.1 202 AcceptedContent-Type: application/json{ "intent_id": "int_7f3a2e9b", "conversation_id": "conv_abc123", "stream_url": "/zakardo/v1/intent/int_7f3a2e9b/stream", "status": "processing"}The intent submission returns immediately with a 202 Accepted. The client connects to the stream_url to receive real-time updates (Planner response mode, plan draft, approval request, execution progress, results).
3.2 Packaged Action Intent
Section titled “3.2 Packaged Action Intent”For pre-built one-click actions:
{ "mode": "packaged", "packaged_action": { "action_id": "quick_create_customer", "parameters": { "name": "Alice Johnson", } }}3.3 Structured Intent
Section titled “3.3 Structured Intent”For form/wizard-produced payloads:
{ "mode": "structured", "structured_payload": { "goal": "create_customer", "inputs": { "name": "Alice Johnson", "company": "Acme Corp" } }}4. SSE Streaming Protocol
Section titled “4. SSE Streaming Protocol”4.1 Overview
Section titled “4.1 Overview”Zakardo uses Server-Sent Events (SSE) for real-time streaming of intent processing, plan generation, and execution progress. SSE was chosen over WebSocket because:
- Simpler protocol (HTTP-based, one-directional server → client).
- Works through proxies, CDNs, and load balancers without special configuration.
- Native browser support via
EventSource. - HTTP/2 multiplexing eliminates the “one connection per stream” limitation.
- Automatic reconnection built into the protocol.
4.2 Connection
Section titled “4.2 Connection”GET /zakardo/v1/intent/:intentId/streamAccept: text/event-streamThe client connects after receiving the intent_id from the intent submission response. The SSE stream covers the entire lifecycle: planning → approval → execution → result.
4.3 Event Types
Section titled “4.3 Event Types”Every SSE event has a typed event field and a JSON data field:
event: <event_type>data: <json_payload>| Event Type | Phase | Description |
|---|---|---|
intent.received | Planning | Intent has been received and processing started |
intent.classified | Planning | Intent classified (response mode determined) |
planner.thinking | Planning | Planner is generating (optional heartbeat) |
planner.step_generated | Planning | A plan step has been generated (streamed incrementally) |
planner.step_validated | Planning | A generated step passed runtime validation |
planner.step_rejected | Planning | A generated step failed validation, LLM self-correcting |
planner.clarification | Planning | Planner needs clarification (CLARIFY mode) |
planner.conversation | Planning | Planner response in CONVERSE mode |
plan.draft_complete | Planning | Full Plan Draft generated |
plan.enriched | Planning | Plan Enrichment complete, Full Plan IR ready |
plan.validated | Validation | Validator passed |
plan.validation_failed | Validation | Validator failed (details in payload) |
plan.awaiting_approval | Approval | Plan presented to user for approval |
execution.started | Execution | Plan execution has begun |
execution.step_started | Execution | A step is beginning execution |
execution.step_completed | Execution | A step completed successfully |
execution.step_failed | Execution | A step failed (transient or permanent) |
execution.step_retrying | Execution | A transient failure is being retried |
execution.gate_triggered | Execution | A gate has been triggered, awaiting response |
execution.gate_resolved | Execution | A gate has been resolved |
execution.interaction_required | Execution | An interaction point has been reached |
execution.interaction_resolved | Execution | Interaction response received |
execution.completed | Result | All steps completed, outbox committed |
execution.failed | Result | Execution permanently failed |
execution.cancelled | Result | Execution was cancelled by user |
a2ui.message | Result | A2UI message for frontend rendering |
error | Any | Stream-level error |
4.4 Event Payloads
Section titled “4.4 Event Payloads”intent.classified
Section titled “intent.classified”{ "intent_id": "int_7f3a2e9b", "response_mode": "GENERATE", "confidence": 0.92, "classified_at": "2026-02-10T20:00:01Z"}planner.step_generated
Section titled “planner.step_generated”{ "intent_id": "int_7f3a2e9b", "step_index": 0, "step": { "capability": "list_customers", "description": "List all churned customers", "inputs": { "filter": { "status": "churned" } } }, "generated_at": "2026-02-10T20:00:02Z"}planner.clarification
Section titled “planner.clarification”{ "intent_id": "int_7f3a2e9b", "response_mode": "CLARIFY", "question": { "text": "Which region's customers do you mean?", "options": ["US", "EU", "APAC", "All regions"], "context": "There are customers in multiple regions. This affects which records are returned." }}plan.awaiting_approval
Section titled “plan.awaiting_approval”{ "intent_id": "int_7f3a2e9b", "execution_id": "exec_9d4b3f2a", "plan": { "steps": [ { "index": 0, "capability": "list_customers", "description": "List all churned customers", "effect_class": "READ", "inputs": { "filter": { "status": "churned" } } }, { "index": 1, "capability": "send_email_batch", "description": "Send recovery email to all churned customers", "effect_class": "WRITE_EXTERNAL", "inputs": { "recipients": "$steps[0].output.customers[*].email", "template_name": "recovery_promo" } } ], "summary": "This plan will find all churned customers and send them a recovery email.", "effect_summary": "READ (1 step), WRITE_EXTERNAL (1 step)", "estimated_duration_ms": 5000, "requires_approval": true }}execution.step_completed
Section titled “execution.step_completed”{ "execution_id": "exec_9d4b3f2a", "step_index": 0, "capability": "list_customers", "output": { "customers": [ ], "total": 2 }, "duration_ms": 342, "completed_at": "2026-02-10T20:00:08Z"}a2ui.message
Section titled “a2ui.message”{ "execution_id": "exec_9d4b3f2a", "message": { "type": "a2ui", "component": "data_table", "props": { "title": "Churned Customers", "columns": ["Name", "Email", "Last Active"], "rows": [ ] } }}4.5 SSE Reconnection
Section titled “4.5 SSE Reconnection”The SSE protocol supports automatic reconnection via the Last-Event-ID header. Every SSE event includes an id field:
id: evt_001event: execution.step_completeddata: {"execution_id": "exec_9d4b3f2a", "step_index": 0, ...}On reconnection, the client sends Last-Event-ID: evt_001 and the server replays all events after that ID from the Event Store (see Execution Engine Specification, §4.5). The Event Store persists every event to zakardo_execution_events before emitting it, so reconnection catch-up is always complete — even if the execution progressed significantly while the client was disconnected.
Reconnection flow:
- Client connects with
Last-Event-ID: evt_042. - Server queries Event Store:
SELECT * FROM zakardo_execution_events WHERE execution_id = ? AND event_id > 'evt_042' ORDER BY event_id. - Server replays all stored events as SSE messages.
- Server subscribes to the Event Channel for live events going forward.
- New events stream as they occur.
4.6 Heartbeat
Section titled “4.6 Heartbeat”The server sends a heartbeat comment every 15 seconds to keep the connection alive:
: heartbeatThis prevents proxy timeouts and allows the client to detect connection loss.
5. Execution Management
Section titled “5. Execution Management”5.1 List Executions
Section titled “5.1 List Executions”GET /zakardo/v1/executions?status=running&limit=20&cursor=exec_abc| Parameter | Type | Description |
|---|---|---|
status | string | Filter by status: running, completed, failed, paused, awaiting_approval |
limit | number | Max results (default: 20, max: 100) |
cursor | string | Cursor for pagination (opaque, from previous response) |
Response:
{ "executions": [ { "execution_id": "exec_9d4b3f2a", "intent_id": "int_7f3a2e9b", "status": "running", "current_step": 1, "total_steps": 3, "mode": "live", "created_at": "2026-02-10T20:00:00Z", "updated_at": "2026-02-10T20:00:08Z" } ], "cursor": "exec_next_abc", "has_more": true}5.2 Get Execution Details
Section titled “5.2 Get Execution Details”GET /zakardo/v1/executions/:executionIdResponse:
{ "execution_id": "exec_9d4b3f2a", "intent_id": "int_7f3a2e9b", "status": "completed", "mode": "live", "plan": { "steps": [ { "index": 0, "capability": "list_customers", "status": "completed", "output": { "customers": [...], "total": 2 }, "duration_ms": 342, "started_at": "2026-02-10T20:00:06Z", "completed_at": "2026-02-10T20:00:08Z" }, { "index": 1, "capability": "send_email_batch", "status": "completed", "output": { "sent_count": 2, "failed": [] }, "duration_ms": 1205, "started_at": "2026-02-10T20:00:08Z", "completed_at": "2026-02-10T20:00:09Z" } ] }, "trace_id": "trace_abc123", "created_at": "2026-02-10T20:00:00Z", "completed_at": "2026-02-10T20:00:09Z"}5.3 Approve Plan
Section titled “5.3 Approve Plan”POST /zakardo/v1/executions/:executionId/approveContent-Type: application/json{ "comment": "Looks good, proceed."}Response:
{ "execution_id": "exec_9d4b3f2a", "status": "running", "message": "Plan approved. Execution started."}5.4 Reject Plan
Section titled “5.4 Reject Plan”POST /zakardo/v1/executions/:executionId/rejectContent-Type: application/json{ "reason": "I want to exclude EU customers from this batch."}Response:
{ "execution_id": "exec_9d4b3f2a", "status": "rejected", "message": "Plan rejected. The intent can be resubmitted with modifications."}5.5 Cancel Execution
Section titled “5.5 Cancel Execution”POST /zakardo/v1/executions/:executionId/cancelContent-Type: application/json{ "reason": "No longer needed."}Cancellation is best-effort. If the current step has already committed, it is not rolled back (per Execution Engine Specification — no automatic compensation in v1). The Outbox discards any uncommitted external effects.
Response:
{ "execution_id": "exec_9d4b3f2a", "status": "cancelled", "steps_completed": 1, "steps_total": 3, "message": "Execution cancelled. 1 of 3 steps had already completed."}5.6 Events Polling
Section titled “5.6 Events Polling”For clients that cannot use SSE (mobile apps, CLI tools, server-to-server integrations), a polling endpoint provides access to the same execution events from the Event Store:
GET /zakardo/v1/executions/:executionId/events?after=evt_042&limit=50| Parameter | Type | Description |
|---|---|---|
after | string | Return events after this event_id (exclusive). Omit for all events. |
limit | number | Max events per response (default: 50, max: 200). |
type | string | Filter by event type (comma-separated). |
Response:
{ "execution_id": "exec_9d4b3f2a", "execution_status": "running", "events": [ { "event_id": "evt_043", "type": "execution.step_completed", "data": { "step_index": 1, "capability": "send_email_batch", "duration_ms": 1205 }, "timestamp": "2026-02-10T20:00:09Z" } ], "has_more": false, "latest_event_id": "evt_043"}The response includes execution_status so the client knows whether to keep polling. The latest_event_id provides the cursor for the next poll.
Recommended polling interval: 1-2 seconds for active executions, 5-10 seconds for waiting states.
6. Gates and Interactions
Section titled “6. Gates and Interactions”6.1 Gate Response
Section titled “6.1 Gate Response”When the Execution Engine pauses at a gate (per-step policy requiring approval), the client responds:
POST /zakardo/v1/executions/:executionId/gate/:gateIdContent-Type: application/json{ "decision": "approve", "comment": "Confirmed by manager."}| Field | Type | Required | Description |
|---|---|---|---|
decision | "approve" | "deny" | Yes | Gate decision. |
comment | string | No | Optional justification. Recorded in the Trace. |
Response:
{ "execution_id": "exec_9d4b3f2a", "gate_id": "gate_step2_write", "decision": "approve", "execution_status": "running", "message": "Gate approved. Execution resumed."}6.2 Interaction Response
Section titled “6.2 Interaction Response”When a capability declares an Interaction Spec and the Execution Engine pauses for user input:
POST /zakardo/v1/executions/:executionId/interaction/:stepIndexContent-Type: application/json{ "response": { "selected_option": "premium_plan", "confirmed": true }}The response body conforms to the capability’s declared Interaction Spec response schema. The Execution Engine validates the response against the schema before resuming.
Response:
{ "execution_id": "exec_9d4b3f2a", "step_index": 2, "interaction_resolved": true, "execution_status": "running", "message": "Interaction response received. Execution resumed."}7. Capability Registry
Section titled “7. Capability Registry”7.1 List Capabilities
Section titled “7.1 List Capabilities”GET /zakardo/v1/capabilities?tags=email&effect_class=READ&search=customer| Parameter | Type | Description |
|---|---|---|
tags | string | Comma-separated tags filter |
effect_class | string | Filter by effect class: READ, WRITE_INTERNAL, WRITE_EXTERNAL, DESTRUCTIVE |
boundary | string | Filter by boundary: LOCAL, REMOTE, USER_ENV |
search | string | Full-text search on name and description |
Response:
{ "capabilities": [ { "name": "list_customers", "version": "1.0.0", "description": "List customers with optional filters", "effect_class": "READ", "boundary": "LOCAL", "tags": ["customers", "crm"], "alternatives": ["get_customer"] } ], "total": 12}7.2 Get Capability Details
Section titled “7.2 Get Capability Details”GET /zakardo/v1/capabilities/:name?version=1.0.0Returns the full capability definition including input/output schemas, effect class, boundary, constraints, interaction spec, and anchored view configuration.
Response:
{ "name": "list_customers", "version": "1.0.0", "description": "List customers with optional filters", "effect_class": "READ", "boundary": "LOCAL", "tags": ["customers", "crm"], "alternatives": ["get_customer"], "input_schema": { "type": "object", "properties": { "filter": { "type": "object" }, "limit": { "type": "number", "default": 50 } } }, "output_schema": { "type": "object", "properties": { "customers": { "type": "array" }, "total": { "type": "number" } } }, "constraints": {}, "interaction_spec": null, "anchored_view": null}8. Trace Access
Section titled “8. Trace Access”8.1 List Traces
Section titled “8.1 List Traces”GET /zakardo/v1/traces?execution_id=exec_9d4b3f2a&limit=20| Parameter | Type | Description |
|---|---|---|
execution_id | string | Filter by execution |
intent_id | string | Filter by intent |
limit | number | Max results (default: 20, max: 100) |
cursor | string | Pagination cursor |
Response:
{ "traces": [ { "trace_id": "trace_abc123", "execution_id": "exec_9d4b3f2a", "intent_id": "int_7f3a2e9b", "status": "completed", "entry_count": 14, "started_at": "2026-02-10T20:00:00Z", "completed_at": "2026-02-10T20:00:09Z" } ], "cursor": null, "has_more": false}8.2 Get Full Trace
Section titled “8.2 Get Full Trace”GET /zakardo/v1/traces/:traceIdReturns the complete trace with all entries — per the Trace System Specification format. This is the primary debugging and observability endpoint.
Response:
{ "trace_id": "trace_abc123", "execution_id": "exec_9d4b3f2a", "entries": [ { "index": 0, "type": "INTENT_RECEIVED", "timestamp": "2026-02-10T20:00:00Z", "data": { "message": "Show me all deals closing this month" } }, { "index": 1, "type": "PLANNER_CLASSIFICATION", "timestamp": "2026-02-10T20:00:01Z", "data": { "response_mode": "GENERATE", "confidence": 0.92 } }, { "index": 2, "type": "STEP_GENERATED", "timestamp": "2026-02-10T20:00:02Z", "data": { "step_index": 0, "capability": "list_deals", "valid": true } } ]}9. Plan Library
Section titled “9. Plan Library”9.1 List Plans
Section titled “9.1 List Plans”GET /zakardo/v1/plans?status=promoted&search=customer| Parameter | Type | Description |
|---|---|---|
status | string | Filter by lifecycle status: candidate, shadow, promoted, deprecated, quarantined, archived |
search | string | Search plan descriptions and intent patterns |
limit | number | Max results (default: 20, max: 100) |
cursor | string | Pagination cursor |
Response:
{ "plans": [ { "plan_id": "plan_abc123", "intent_pattern": "list * customers", "status": "promoted", "trust_score": 0.95, "execution_count": 47, "success_rate": 0.98, "last_used_at": "2026-02-10T19:30:00Z", "created_at": "2026-01-15T10:00:00Z" } ], "cursor": null, "has_more": false}9.2 Get Plan Details
Section titled “9.2 Get Plan Details”GET /zakardo/v1/plans/:planIdReturns the full plan including the Plan IR, intent pattern, trust score, execution history summary, and lifecycle status.
10. Schema Metadata
Section titled “10. Schema Metadata”10.1 Get Schema
Section titled “10.1 Get Schema”GET /zakardo/v1/schemaReturns the normalized schema metadata extracted by the Data Adapter (see Data Layer Specification, Section 3). This endpoint exposes what business entities and relations the Planner understands.
Response:
{ "adapter": "prisma", "extracted_at": "2026-02-10T18:00:00Z", "tables": [ { "name": "customers", "description": "Customer records", "columns": [ { "name": "id", "db_type": "uuid", "zakardo_type": "string", "nullable": false }, { "name": "name", "db_type": "varchar", "zakardo_type": "string", "nullable": false }, { "name": "email", "db_type": "varchar", "zakardo_type": "string", "nullable": false }, { "name": "status", "db_type": "varchar", "zakardo_type": "string", "nullable": false } ], "primary_key": ["id"] } ], "relations": [ { "from": "orders", "to": "customers", "type": "many_to_one", "foreign_key": "customer_id" } ]}11. Health Check
Section titled “11. Health Check”GET /zakardo/v1/healthReturns the health status of all Zakardo Runtime subsystems.
Response:
{ "status": "healthy", "version": "0.1.0", "uptime_ms": 3600000, "subsystems": { "database": { "status": "healthy", "latency_ms": 3 }, "capability_registry": { "status": "healthy", "capabilities_loaded": 24 }, "planner": { "status": "healthy", "llm_provider": "openai" }, "execution_engine": { "status": "healthy", "active_executions": 2 }, "plan_library": { "status": "healthy", "plans_loaded": 156 } }}12. Error Response Format
Section titled “12. Error Response Format”12.1 Standard Error Envelope
Section titled “12.1 Standard Error Envelope”Every error response follows a consistent structure:
{ "error": { "code": "EXECUTION_NOT_FOUND", "category": "not_found", "message": "Execution exec_xyz does not exist.", "details": {}, "request_id": "req_abc123" }}| Field | Type | Description |
|---|---|---|
code | string | Machine-readable error code (SCREAMING_SNAKE_CASE). |
category | string | Error category (see below). |
message | string | Human-readable error message. |
details | object | Additional context (validation errors, field-level issues). |
request_id | string | Unique request identifier for debugging. |
12.2 Error Categories
Section titled “12.2 Error Categories”| Category | HTTP Status | Description |
|---|---|---|
validation | 400 | Request body failed validation |
unauthorized | 401 | Authentication required or invalid |
forbidden | 403 | User lacks permission for this action |
not_found | 404 | Resource does not exist |
conflict | 409 | State conflict (e.g., approving an already-running execution) |
rate_limited | 429 | Rate limit exceeded |
internal | 500 | Internal server error |
service_unavailable | 503 | Upstream dependency unavailable (LLM provider, database) |
12.3 Validation Errors
Section titled “12.3 Validation Errors”Validation errors include field-level details:
{ "error": { "code": "VALIDATION_ERROR", "category": "validation", "message": "Request body validation failed.", "details": { "fields": [ { "field": "message", "issue": "Required field is missing.", "expected": "string" } ] }, "request_id": "req_abc123" }}13. Authentication Integration
Section titled “13. Authentication Integration”13.1 Design
Section titled “13.1 Design”The Zakardo Runtime does not perform authentication. It relies on the developer’s authMiddleware to resolve user identity before the request reaches Zakardo routes.
The Runtime reads user context from a standardized interface:
interface ZakardoUserContext { /** Unique user identifier. */ user_id: string;
/** User roles (used by Policy Engine). */ roles: string[];
/** Tenant ID (for multi-tenant applications). */ tenant_id?: string;
/** Session ID. */ session_id?: string;
/** Additional claims from the auth provider. */ claims?: Record<string, unknown>;}13.2 Context Resolution
Section titled “13.2 Context Resolution”The developer’s auth middleware sets this context using Hono’s context storage:
import { createMiddleware } from 'hono/factory';
export const authMiddleware = createMiddleware(async (c, next) => { const token = c.req.header('Authorization')?.replace('Bearer ', ''); if (!token) return c.json( { error: { code: 'UNAUTHORIZED', category: 'unauthorized', message: 'Missing token' } }, 401, );
const session = await validateToken(token); if (!session) return c.json( { error: { code: 'UNAUTHORIZED', category: 'unauthorized', message: 'Invalid token' } }, 401, );
// Set Zakardo user context c.set('zakardo_user', { user_id: session.userId, roles: session.roles, tenant_id: session.tenantId, session_id: session.sessionId, });
await next();});The Runtime reads c.get('zakardo_user') on every request. If the context is missing, the Runtime returns a 401 error.
13.3 Multi-Tenant Isolation
Section titled “13.3 Multi-Tenant Isolation”For multi-tenant applications, the tenant_id in the user context is propagated through:
- Policy evaluation — policies can scope rules per tenant.
- Capability execution — capabilities receive
context.user.tenant_id. - Data queries — the developer’s data access layer should filter by tenant.
- Trace storage — traces are tagged with
tenant_idfor isolation. - Plan Library — plans are scoped per tenant (a plan promoted for Tenant A is not used for Tenant B).
14. Webhooks
Section titled “14. Webhooks”14.1 Overview
Section titled “14.1 Overview”For server-to-server integrations, Zakardo supports outbound webhooks that notify external systems of lifecycle events. This is useful for:
- Notifying a Slack bot when a plan completes.
- Triggering downstream workflows in external tools.
- Logging execution events to an external observability platform.
14.2 Configuration
Section titled “14.2 Configuration”export const execution = defineExecutionConfig({ // ... other config
webhooks: { endpoints: [ { url: 'https://hooks.slack.com/services/xxx', events: ['execution.completed', 'execution.failed'], secret: env.WEBHOOK_SECRET, timeout_ms: 5000, retry: { maxAttempts: 3, backoffMs: 1000 }, }, ], },});14.3 Webhook Payload
Section titled “14.3 Webhook Payload”{ "event": "execution.completed", "timestamp": "2026-02-10T20:00:09Z", "data": { "execution_id": "exec_9d4b3f2a", "intent_id": "int_7f3a2e9b", "status": "completed", "steps_completed": 2, "duration_ms": 9000 }, "signature": "sha256=abc123..."}Webhooks are signed using HMAC-SHA256 with the configured secret. The receiver validates the signature using the X-Zakardo-Signature header.
14.4 Delivery
Section titled “14.4 Delivery”Webhook delivery is fire-and-forget with retry. It uses the same retry logic as transient failure retry in the Execution Engine (exponential backoff). Webhook delivery does not block execution.
15. Client SDK
Section titled “15. Client SDK”15.1 Overview
Section titled “15.1 Overview”The official Zakardo client SDK (@zakardo/sdk) provides a typed TypeScript client for all Runtime API endpoints. It abstracts HTTP/SSE details while remaining thin.
npm install @zakardo/sdk15.2 Client Initialization
Section titled “15.2 Client Initialization”import { ZakardoClient } from '@zakardo/sdk';
const zakardo = new ZakardoClient({ baseUrl: 'https://api.myapp.com/zakardo/v1', auth: { token: 'user_session_token', // OR getToken: async () => await refreshToken(), }, timeout: 30000,});| Option | Type | Required | Description |
|---|---|---|---|
baseUrl | string | Yes | Base URL of the Zakardo Runtime API. |
auth.token | string | Conditional | Static bearer token. |
auth.getToken | () => Promise<string> | Conditional | Async token provider (for token refresh). |
timeout | number | No | Default request timeout in ms (default: 30000). |
retry | RetryConfig | No | Client-side retry config for failed requests. |
15.3 Core Methods
Section titled “15.3 Core Methods”Submit Intent
Section titled “Submit Intent”const result = await zakardo.intent.submit({ message: 'Show me all deals closing this month', executionMode: 'live',});
console.log(result.intentId); // "int_7f3a2e9b"console.log(result.streamUrl); // "/zakardo/v1/intent/int_7f3a2e9b/stream"Stream Intent (Full Lifecycle)
Section titled “Stream Intent (Full Lifecycle)”const stream = zakardo.intent.stream(result.intentId);
stream.on('planner.step_generated', (event) => { console.log(`Step ${event.step_index}: ${event.step.capability}`);});
stream.on('plan.awaiting_approval', (event) => { console.log('Plan ready for review:', event.plan.summary); // Auto-approve or present to user});
stream.on('execution.step_completed', (event) => { console.log(`Step ${event.step_index} done in ${event.duration_ms}ms`);});
stream.on('a2ui.message', (event) => { // Render A2UI component renderA2UI(event.message);});
stream.on('execution.completed', (event) => { console.log('All done!'); stream.close();});
stream.on('error', (event) => { console.error('Stream error:', event); stream.close();});One-Shot Intent (Submit + Stream in One Call)
Section titled “One-Shot Intent (Submit + Stream in One Call)”const execution = await zakardo.intent.execute({ message: 'Create a customer named Alice', executionMode: 'live', autoApprove: true, // Skip approval prompt for READ-only plans onStep: (event) => console.log(`Step: ${event.step.capability}`), onA2UI: (message) => renderA2UI(message),});
console.log(execution.status); // "completed"console.log(execution.result); // Final output15.4 Execution Management
Section titled “15.4 Execution Management”// List executionsconst executions = await zakardo.executions.list({ status: 'running' });
// Get execution detailsconst detail = await zakardo.executions.get('exec_9d4b3f2a');
// Approve a planawait zakardo.executions.approve('exec_9d4b3f2a');
// Reject a planawait zakardo.executions.reject('exec_9d4b3f2a', { reason: 'Wrong scope' });
// Cancel a running executionawait zakardo.executions.cancel('exec_9d4b3f2a');
// Stream an existing executionconst stream = zakardo.executions.stream('exec_9d4b3f2a');15.5 Gate and Interaction Responses
Section titled “15.5 Gate and Interaction Responses”// Respond to a gateawait zakardo.executions.resolveGate('exec_9d4b3f2a', 'gate_step2_write', { decision: 'approve', comment: 'Confirmed by manager',});
// Respond to an interactionawait zakardo.executions.resolveInteraction('exec_9d4b3f2a', 2, { response: { selected_option: 'premium_plan', confirmed: true },});15.6 Capabilities, Traces, Plans
Section titled “15.6 Capabilities, Traces, Plans”// Capabilitiesconst capabilities = await zakardo.capabilities.list({ tags: 'email' });const capability = await zakardo.capabilities.get('send_email');
// Tracesconst traces = await zakardo.traces.list({ executionId: 'exec_9d4b3f2a' });const trace = await zakardo.traces.get('trace_abc123');
// Plansconst plans = await zakardo.plans.list({ status: 'promoted' });const plan = await zakardo.plans.get('plan_abc123');15.7 Schema and Health
Section titled “15.7 Schema and Health”// Schema metadataconst schema = await zakardo.schema.get();console.log(schema.tables);
// Health checkconst health = await zakardo.health.check();console.log(health.status);15.8 React Hooks (Optional)
Section titled “15.8 React Hooks (Optional)”For React applications, the SDK exports hooks that integrate with the streaming lifecycle:
import { useZakardoIntent, useZakardoExecution } from '@zakardo/sdk/react';
function ChatInput() { const { submit, stream, status, plan, result } = useZakardoIntent();
const handleSubmit = (message: string) => { submit({ message }); };
return ( <div> {status === 'awaiting_approval' && ( <PlanReview plan={plan} onApprove={() => stream.approve()} /> )} {result && <A2UIRenderer messages={result.a2uiMessages} />} </div> );}16. Rate Limiting
Section titled “16. Rate Limiting”16.1 Default Limits
Section titled “16.1 Default Limits”| Endpoint | Default Limit | Scope |
|---|---|---|
POST /intent | 60/minute | Per user |
GET /*/stream | 10 concurrent | Per user |
| All other endpoints | 300/minute | Per user |
Rate limits are configurable via config/execution.ts:
export const execution = defineExecutionConfig({ rateLimiting: { intentSubmission: { windowMs: 60000, maxRequests: 60 }, streaming: { maxConcurrent: 10 }, general: { windowMs: 60000, maxRequests: 300 }, },});16.2 Rate Limit Response
Section titled “16.2 Rate Limit Response”HTTP/1.1 429 Too Many RequestsRetry-After: 12{ "error": { "code": "RATE_LIMITED", "category": "rate_limited", "message": "Rate limit exceeded. Retry after 12 seconds.", "details": { "retry_after_seconds": 12 }, "request_id": "req_abc123" }}17. Conversation and Multi-Turn
Section titled “17. Conversation and Multi-Turn”17.1 Conversation Model
Section titled “17.1 Conversation Model”Multi-turn interactions use a conversation_id to maintain context across intents:
// First turn{ "message": "Show me all customers", "context": { "conversation_id": "conv_new" } }
// Clarification response (same conversation){ "message": "I mean only the churned ones", "context": { "conversation_id": "conv_new" } }The Planner maintains a conversation buffer per conversation_id — previous intents, planner responses, clarification exchanges, and execution results. The buffer provides context for the next intent without the client replaying history.
17.2 Conversation Lifecycle
Section titled “17.2 Conversation Lifecycle”| Event | Behavior |
|---|---|
First intent with new conversation_id | Create conversation, start fresh context |
Subsequent intents with same conversation_id | Append to conversation context |
| Clarification response | Treated as a continuation of the same intent |
| No activity for 30 minutes (configurable) | Conversation expires, context cleared |
18. CORS and Security
Section titled “18. CORS and Security”18.1 CORS
Section titled “18.1 CORS”CORS configuration is the developer’s responsibility on the Hono server. Zakardo does not impose CORS rules. Recommended:
app.use( '/zakardo/*', cors({ origin: ['https://myapp.com'], credentials: true, allowMethods: ['GET', 'POST'], allowHeaders: ['Content-Type', 'Authorization'], }),);18.2 Security Headers
Section titled “18.2 Security Headers”Zakardo routes inherit whatever security headers the developer configures globally. The Runtime API sets the following response headers on all responses:
| Header | Value | Purpose |
|---|---|---|
X-Request-Id | Unique ID | Request tracing |
X-Zakardo-Version | Runtime version | Version identification |
Cache-Control | no-store | Prevent caching of dynamic responses |
19. Summary of Decisions
Section titled “19. Summary of Decisions”| Decision | Resolution |
|---|---|
| Protocol | REST + SSE. No WebSocket. SSE for real-time streaming, REST for everything else. |
| Versioning | URL path prefix /zakardo/v1/. Breaking changes require new version. |
| Auth | External. Runtime reads zakardo_user from Hono context. Never authenticates itself. |
| Error format | Consistent envelope: { error: { code, category, message, details, request_id } }. |
| SSE reconnection | Last-Event-ID header, server replays missed events from Event Store (zakardo_execution_events). Guaranteed complete catch-up. |
| Rate limiting | Per-user, configurable. Intent submission: 60/min. SSE: 10 concurrent. |
| SDK architecture | Thin TypeScript client. Maps 1:1 to HTTP endpoints. Optional React hooks. |
| Intent submission | Async (202 Accepted) + SSE stream. No synchronous plan generation. |
| Multi-tenant | tenant_id propagated through policy, execution, traces, and plan library. |
| Webhooks | Outbound, signed (HMAC-SHA256), fire-and-forget with retry. Configured in execution config. |
| Conversations | Server-managed via conversation_id. 30-minute expiry. Context replayed automatically. |
| Events polling | GET /executions/:id/events for non-SSE clients. Same Event Store data as SSE. Cursor-based with after parameter. |
20. Questions Deferred
Section titled “20. Questions Deferred”| Question | Deferred To |
|---|---|
| How is the SSE stream authenticated for long-lived connections? | Security Specification |
| What is the exact A2UI message format? | Frontend Architecture Specification |
| How are packaged actions discovered and listed? | Frontend Architecture Specification |
| How does the SDK handle offline/retry for mobile clients? | Mobile SDK Specification |
| What is the webhook signature verification algorithm? | Security Specification |
| How are conversation buffers stored and bounded? | Execution Engine Specification (addendum) |