Skip to content

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. 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.
  2. 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).
  3. JSON everywhere. All request bodies and response bodies are application/json. SSE event data fields are JSON-serialized.
  4. 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.
  5. 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.
  6. 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.
  7. Versioned from day one. All endpoints are prefixed /zakardo/v1/. Breaking changes require a new version prefix.

All Zakardo Runtime routes mount under /zakardo/v1/:

apps/api/src/zakardo/index.ts
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.ts
app.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.

MethodPathDescriptionSection
POST/zakardo/v1/intentSubmit an intent (triggers planning)§3
GET/zakardo/v1/intent/:intentId/streamSSE stream for intent processing§4
GET/zakardo/v1/executionsList executions (paginated)§5
GET/zakardo/v1/executions/:executionIdGet execution details§5
GET/zakardo/v1/executions/:executionId/streamSSE stream for execution progress§4
POST/zakardo/v1/executions/:executionId/approveApprove a plan for execution§5
POST/zakardo/v1/executions/:executionId/rejectReject a plan§5
POST/zakardo/v1/executions/:executionId/cancelCancel a running execution§5
POST/zakardo/v1/executions/:executionId/gate/:gateIdRespond to a gate§6
POST/zakardo/v1/executions/:executionId/interaction/:stepIndexRespond to an interaction§6
GET/zakardo/v1/capabilitiesList registered capabilities§7
GET/zakardo/v1/capabilities/:nameGet capability details§7
GET/zakardo/v1/tracesList traces (paginated)§8
GET/zakardo/v1/traces/:traceIdGet full trace§8
GET/zakardo/v1/plansList plans in the Plan Library§9
GET/zakardo/v1/plans/:planIdGet plan details§9
GET/zakardo/v1/schemaGet schema metadata (entities, relations)§10
GET/zakardo/v1/healthHealth check§11
GET/zakardo/v1/executions/:executionId/eventsPoll execution events (non-SSE)§5.6

The primary entry point for all agentic interactions.

Request:

POST /zakardo/v1/intent
Content-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"
}
}
}
FieldTypeRequiredDescription
messagestringYesThe user’s intent in natural language (for expressed mode).
mode"expressed" | "packaged" | "structured"NoIntent input mode. Default: expressed.
execution_mode"live" | "dry_run" | "simulated"NoExecution mode. Default: live.
contextobjectNoAdditional context for the Planner.
context.conversation_idstringNoConversation ID for multi-turn context. Auto-generated if omitted.
context.metadataobjectNoArbitrary metadata passed to the Planner.
packaged_actionobjectConditionalRequired when mode is packaged. Pre-built action payload.
structured_payloadobjectConditionalRequired when mode is structured. Form/wizard-produced payload.

Response (synchronous):

HTTP/1.1 202 Accepted
Content-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).

For pre-built one-click actions:

{
"mode": "packaged",
"packaged_action": {
"action_id": "quick_create_customer",
"parameters": {
"name": "Alice Johnson",
"email": "[email protected]"
}
}
}

For form/wizard-produced payloads:

{
"mode": "structured",
"structured_payload": {
"goal": "create_customer",
"inputs": {
"name": "Alice Johnson",
"email": "[email protected]",
"company": "Acme Corp"
}
}
}

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.
GET /zakardo/v1/intent/:intentId/stream
Accept: text/event-stream

The client connects after receiving the intent_id from the intent submission response. The SSE stream covers the entire lifecycle: planning → approval → execution → result.

Every SSE event has a typed event field and a JSON data field:

event: <event_type>
data: <json_payload>
Event TypePhaseDescription
intent.receivedPlanningIntent has been received and processing started
intent.classifiedPlanningIntent classified (response mode determined)
planner.thinkingPlanningPlanner is generating (optional heartbeat)
planner.step_generatedPlanningA plan step has been generated (streamed incrementally)
planner.step_validatedPlanningA generated step passed runtime validation
planner.step_rejectedPlanningA generated step failed validation, LLM self-correcting
planner.clarificationPlanningPlanner needs clarification (CLARIFY mode)
planner.conversationPlanningPlanner response in CONVERSE mode
plan.draft_completePlanningFull Plan Draft generated
plan.enrichedPlanningPlan Enrichment complete, Full Plan IR ready
plan.validatedValidationValidator passed
plan.validation_failedValidationValidator failed (details in payload)
plan.awaiting_approvalApprovalPlan presented to user for approval
execution.startedExecutionPlan execution has begun
execution.step_startedExecutionA step is beginning execution
execution.step_completedExecutionA step completed successfully
execution.step_failedExecutionA step failed (transient or permanent)
execution.step_retryingExecutionA transient failure is being retried
execution.gate_triggeredExecutionA gate has been triggered, awaiting response
execution.gate_resolvedExecutionA gate has been resolved
execution.interaction_requiredExecutionAn interaction point has been reached
execution.interaction_resolvedExecutionInteraction response received
execution.completedResultAll steps completed, outbox committed
execution.failedResultExecution permanently failed
execution.cancelledResultExecution was cancelled by user
a2ui.messageResultA2UI message for frontend rendering
errorAnyStream-level error
{
"intent_id": "int_7f3a2e9b",
"response_mode": "GENERATE",
"confidence": 0.92,
"classified_at": "2026-02-10T20:00:01Z"
}
{
"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"
}
{
"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."
}
}
{
"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_id": "exec_9d4b3f2a",
"step_index": 0,
"capability": "list_customers",
"output": {
"customers": [
{ "id": "cust_1", "name": "Alice", "email": "[email protected]" },
{ "id": "cust_2", "name": "Bob", "email": "[email protected]" }
],
"total": 2
},
"duration_ms": 342,
"completed_at": "2026-02-10T20:00:08Z"
}
{
"execution_id": "exec_9d4b3f2a",
"message": {
"type": "a2ui",
"component": "data_table",
"props": {
"title": "Churned Customers",
"columns": ["Name", "Email", "Last Active"],
"rows": [
["Alice", "[email protected]", "2026-01-15"],
["Bob", "[email protected]", "2026-01-20"]
]
}
}
}

The SSE protocol supports automatic reconnection via the Last-Event-ID header. Every SSE event includes an id field:

id: evt_001
event: execution.step_completed
data: {"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:

  1. Client connects with Last-Event-ID: evt_042.
  2. Server queries Event Store: SELECT * FROM zakardo_execution_events WHERE execution_id = ? AND event_id > 'evt_042' ORDER BY event_id.
  3. Server replays all stored events as SSE messages.
  4. Server subscribes to the Event Channel for live events going forward.
  5. New events stream as they occur.

The server sends a heartbeat comment every 15 seconds to keep the connection alive:

: heartbeat

This prevents proxy timeouts and allows the client to detect connection loss.


GET /zakardo/v1/executions?status=running&limit=20&cursor=exec_abc
ParameterTypeDescription
statusstringFilter by status: running, completed, failed, paused, awaiting_approval
limitnumberMax results (default: 20, max: 100)
cursorstringCursor 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
}
GET /zakardo/v1/executions/:executionId

Response:

{
"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"
}
POST /zakardo/v1/executions/:executionId/approve
Content-Type: application/json
{
"comment": "Looks good, proceed."
}

Response:

{
"execution_id": "exec_9d4b3f2a",
"status": "running",
"message": "Plan approved. Execution started."
}
POST /zakardo/v1/executions/:executionId/reject
Content-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."
}
POST /zakardo/v1/executions/:executionId/cancel
Content-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."
}

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
ParameterTypeDescription
afterstringReturn events after this event_id (exclusive). Omit for all events.
limitnumberMax events per response (default: 50, max: 200).
typestringFilter 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.


When the Execution Engine pauses at a gate (per-step policy requiring approval), the client responds:

POST /zakardo/v1/executions/:executionId/gate/:gateId
Content-Type: application/json
{
"decision": "approve",
"comment": "Confirmed by manager."
}
FieldTypeRequiredDescription
decision"approve" | "deny"YesGate decision.
commentstringNoOptional 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."
}

When a capability declares an Interaction Spec and the Execution Engine pauses for user input:

POST /zakardo/v1/executions/:executionId/interaction/:stepIndex
Content-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."
}

GET /zakardo/v1/capabilities?tags=email&effect_class=READ&search=customer
ParameterTypeDescription
tagsstringComma-separated tags filter
effect_classstringFilter by effect class: READ, WRITE_INTERNAL, WRITE_EXTERNAL, DESTRUCTIVE
boundarystringFilter by boundary: LOCAL, REMOTE, USER_ENV
searchstringFull-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
}
GET /zakardo/v1/capabilities/:name?version=1.0.0

Returns 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
}

GET /zakardo/v1/traces?execution_id=exec_9d4b3f2a&limit=20
ParameterTypeDescription
execution_idstringFilter by execution
intent_idstringFilter by intent
limitnumberMax results (default: 20, max: 100)
cursorstringPagination 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
}
GET /zakardo/v1/traces/:traceId

Returns 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 }
}
]
}

GET /zakardo/v1/plans?status=promoted&search=customer
ParameterTypeDescription
statusstringFilter by lifecycle status: candidate, shadow, promoted, deprecated, quarantined, archived
searchstringSearch plan descriptions and intent patterns
limitnumberMax results (default: 20, max: 100)
cursorstringPagination 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
}
GET /zakardo/v1/plans/:planId

Returns the full plan including the Plan IR, intent pattern, trust score, execution history summary, and lifecycle status.


GET /zakardo/v1/schema

Returns 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"
}
]
}

GET /zakardo/v1/health

Returns 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 }
}
}

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"
}
}
FieldTypeDescription
codestringMachine-readable error code (SCREAMING_SNAKE_CASE).
categorystringError category (see below).
messagestringHuman-readable error message.
detailsobjectAdditional context (validation errors, field-level issues).
request_idstringUnique request identifier for debugging.
CategoryHTTP StatusDescription
validation400Request body failed validation
unauthorized401Authentication required or invalid
forbidden403User lacks permission for this action
not_found404Resource does not exist
conflict409State conflict (e.g., approving an already-running execution)
rate_limited429Rate limit exceeded
internal500Internal server error
service_unavailable503Upstream dependency unavailable (LLM provider, database)

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"
}
}

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>;
}

The developer’s auth middleware sets this context using Hono’s context storage:

apps/api/src/foundation/auth/middleware.ts
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.

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_id for isolation.
  • Plan Library — plans are scoped per tenant (a plan promoted for Tenant A is not used for Tenant B).

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.
config/execution.ts
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 },
},
],
},
});
{
"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.

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.


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.

Terminal window
npm install @zakardo/sdk
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,
});
OptionTypeRequiredDescription
baseUrlstringYesBase URL of the Zakardo Runtime API.
auth.tokenstringConditionalStatic bearer token.
auth.getToken() => Promise<string>ConditionalAsync token provider (for token refresh).
timeoutnumberNoDefault request timeout in ms (default: 30000).
retryRetryConfigNoClient-side retry config for failed requests.
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"
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 output
// List executions
const executions = await zakardo.executions.list({ status: 'running' });
// Get execution details
const detail = await zakardo.executions.get('exec_9d4b3f2a');
// Approve a plan
await zakardo.executions.approve('exec_9d4b3f2a');
// Reject a plan
await zakardo.executions.reject('exec_9d4b3f2a', { reason: 'Wrong scope' });
// Cancel a running execution
await zakardo.executions.cancel('exec_9d4b3f2a');
// Stream an existing execution
const stream = zakardo.executions.stream('exec_9d4b3f2a');
// Respond to a gate
await zakardo.executions.resolveGate('exec_9d4b3f2a', 'gate_step2_write', {
decision: 'approve',
comment: 'Confirmed by manager',
});
// Respond to an interaction
await zakardo.executions.resolveInteraction('exec_9d4b3f2a', 2, {
response: { selected_option: 'premium_plan', confirmed: true },
});
// Capabilities
const capabilities = await zakardo.capabilities.list({ tags: 'email' });
const capability = await zakardo.capabilities.get('send_email');
// Traces
const traces = await zakardo.traces.list({ executionId: 'exec_9d4b3f2a' });
const trace = await zakardo.traces.get('trace_abc123');
// Plans
const plans = await zakardo.plans.list({ status: 'promoted' });
const plan = await zakardo.plans.get('plan_abc123');
// Schema metadata
const schema = await zakardo.schema.get();
console.log(schema.tables);
// Health check
const health = await zakardo.health.check();
console.log(health.status);

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>
);
}

EndpointDefault LimitScope
POST /intent60/minutePer user
GET /*/stream10 concurrentPer user
All other endpoints300/minutePer 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 },
},
});
HTTP/1.1 429 Too Many Requests
Retry-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"
}
}

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.

EventBehavior
First intent with new conversation_idCreate conversation, start fresh context
Subsequent intents with same conversation_idAppend to conversation context
Clarification responseTreated as a continuation of the same intent
No activity for 30 minutes (configurable)Conversation expires, context cleared

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'],
}),
);

Zakardo routes inherit whatever security headers the developer configures globally. The Runtime API sets the following response headers on all responses:

HeaderValuePurpose
X-Request-IdUnique IDRequest tracing
X-Zakardo-VersionRuntime versionVersion identification
Cache-Controlno-storePrevent caching of dynamic responses

DecisionResolution
ProtocolREST + SSE. No WebSocket. SSE for real-time streaming, REST for everything else.
VersioningURL path prefix /zakardo/v1/. Breaking changes require new version.
AuthExternal. Runtime reads zakardo_user from Hono context. Never authenticates itself.
Error formatConsistent envelope: { error: { code, category, message, details, request_id } }.
SSE reconnectionLast-Event-ID header, server replays missed events from Event Store (zakardo_execution_events). Guaranteed complete catch-up.
Rate limitingPer-user, configurable. Intent submission: 60/min. SSE: 10 concurrent.
SDK architectureThin TypeScript client. Maps 1:1 to HTTP endpoints. Optional React hooks.
Intent submissionAsync (202 Accepted) + SSE stream. No synchronous plan generation.
Multi-tenanttenant_id propagated through policy, execution, traces, and plan library.
WebhooksOutbound, signed (HMAC-SHA256), fire-and-forget with retry. Configured in execution config.
ConversationsServer-managed via conversation_id. 30-minute expiry. Context replayed automatically.
Events pollingGET /executions/:id/events for non-SSE clients. Same Event Store data as SSE. Cursor-based with after parameter.

QuestionDeferred 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)