NAK: agent runtime
NAK (Ngamia Agent Kernel) runs agents. It drives the loop between a model and
its tools, enforces limits, checks citations, and records every step in a
durable event log. The service binary is ngamia-runtime.
NAK is private. Developers reach it only through the public API at
https://api.ngamia.com, which calls NAK on their behalf. This page is for
developers who want to understand run behavior and for operators who deploy
the engine.
You never call NAK directly. Start runs with POST /v1/agents/{slug}/runs on
the platform API. The platform relays NAK’s outcome or event stream back to you.
How a run works
A run belongs to one principal: a user, an app and a tenant (the workspace). NAK derives the principal from a verified credential, never from the request body.
- Start. NAK resolves the agent, lists the tools the agent may use, and
writes a
RunStartedevent. This event pins the agent, its limits, the exact tool catalog, and the fingerprints of the tool source, policy and validator. - Model call. NAK builds the context (system instructions, optional memory facts, the transcript) and asks the model for the next reply.
- Budget check. Before a reply is accepted, NAK checks the step and token budgets. A reply that would exceed either budget fails the run.
- Tool calls. Each requested call is validated against the tool’s JSON
schema and checked by policy. An allowed call is recorded as
ToolStartedbefore it runs andToolFinishedafter. NAK assigns the call IDs (s{step}-{index}), not the provider. - Finish. When the model replies without tool calls, NAK records
RunCompletedwith the final text.
Unknown tools, invalid arguments and policy denials become tool error results.
The model sees them and can continue. Model errors end the run with RunFailed.
Limits
| Limit | Meaning |
|---|---|
max_steps | Combined count of model replies and tool calls in a run. Set per agent. |
max_total_tokens | Cumulative input plus output tokens the run may use. Set per agent. |
| Output tokens | Each model call is capped at NAK_MAX_OUTPUT_TOKENS (default 900). |
| Tool output | Tool output is truncated to a byte ceiling before it is stored. In platform mode the ceiling is 36,000 bytes; knowledge evidence is bounded to 18,000 bytes per search. |
| Timeouts | One model attempt: 45 s. One tool call: 25 s. Model calls are retried up to NAK_MODEL_ATTEMPTS times (default 3). |
Run statuses
| Status | Meaning |
|---|---|
running | Accepted and being driven in the background (returned for "wait": false). |
completed | Finished with output. |
waiting_approval | Paused before a tool call that needs approval. See Known limits. |
failed | Ended with an error, for example step limit reached or token budget reached. |
cancelled | Stopped on request, with a reason. |
Event log
Each run is an ordered list of events in the run store. The current state of a run is rebuilt by replaying its events; the log is the source of truth. The log format is version 5, and NAK also replays version 4 logs.
| Stored event | Public stream name | Extra data |
|---|---|---|
RunStarted | run.started | agent, thread_id, previous_run_id |
ModelReplied | model.replied | text, tool_calls (id, name, args), input_tokens, output_tokens |
ToolStarted | tool.started | call_id |
ToolFinished | tool.finished | call_id, is_error, output |
ApprovalRequested | approval.requested | call, reason, digest, expires_at_ms |
ApprovalResolved | approval.resolved | call_id, granted, approver |
RunCompleted | run.completed | output |
RunFailed | run.failed | error |
RunCancelled | run.cancelled | reason |
Every public event also carries run_id, seq and at_ms. The SSE id is
the sequence number, so a client resumes with Last-Event-ID or ?after=.
The stream replays stored events first, then follows new ones. It ends at a
terminal event, at an approval pause, or after ten minutes. Text arrives one
model reply at a time, not token by token. The principal, pinned catalog and
fingerprints are never included.
Replay checks the log’s structure: no sequence gaps, one principal, a single
RunStarted first, budgets respected, and nothing after a terminal event.
These checks catch malformed logs. They are not cryptographic tamper proofs.
Conversations. A new run can name a completed run of the same caller in
previous_run_id. NAK copies that run’s user messages and final answers as
history (at most 40 messages and 64 KiB, oldest dropped first). Tool calls and
tool results are not carried.
Platform mode
With NAK_AGENT_SOURCE=platform, NAK runs the agents that businesses define on
the Ngamia platform. This is how api.ngamia.com is deployed.
Callers and assertions
Only the platform may start or read runs. Each request carries a service
assertion (nak-te-assertion-v1): an Ed25519 JWT with
- issuer
NAK_PLATFORM_ASSERTION_ISSUER(defaultngamia-platform), - audience
NAK_PLATFORM_AUDIENCE(defaultngamia-nak), - app
platformand a UUID tenant (the workspace), - a lifetime of at most 60 s, and a UUID
jtithat is accepted once.
The public keys come from NAK_PLATFORM_ASSERTION_KEYS, a JSON map of key ID
to base64url Ed25519 public key (1 to 8 keys). Every run is bound to the
assertion’s subject, so one end user cannot read another’s runs.
Agent definitions
NAK fetches the agent and the workspace settings from the platform’s internal API:
GET {NAK_PLATFORM_URL}/internal/v1/agents/{slug}: name, instructions, model, tools, memory flag, andmax_steps/max_total_tokens.GET {NAK_PLATFORM_URL}/internal/v1/workspace-runtime: the workspace’s model key, default model, and UBONGO read key.
NAK signs these calls with its own assertion key (audience ngamia-platform).
Results are cached for 30 s. Workspace settings that lack a model key or
knowledge key are re-checked after 3 s, so a newly configured workspace does
not wait. A run pins the definition it started with. Edits apply to new runs.
The internal API is never exposed at the edge. Plain http:// to the platform
is allowed only on loopback or with NAK_PLATFORM_ALLOW_HTTP=true.
Model
Model calls go to the Ngamia model gateway (NAK_NGAMIA_BASE_URL) with the
workspace’s own model key and the agent’s model, so usage and billing stay
per workspace. A workspace without a model key cannot run agents; the run fails
with a message to set the key in workspace settings.
Knowledge and citations
knowledge_search queries the workspace’s UBONGO tenant with the workspace’s
read key. A workspace that has not provisioned knowledge is not offered the
tool. When the tool is offered, NAK tells the model to cite claims as
[[cite:ID]] and to treat retrieved text as data, not instructions.
On the final answer, NAK checks every citation:
- Citations to passages that were not retrieved in this turn are dropped.
- Valid citations are numbered.
- The cited passages are listed under Sources:.
- If nothing was retrieved, all citation markers are removed.
Tools
The agent’s tools list filters what the model is offered. Two kinds exist:
knowledge_search(above).- TE tools, offered only when
NAK_TE_ENDPOINTis set, the tool is listed inNAK_TE_ALLOWED_TOOLSas an exacttool_id@version, and TE declares it read-only. TE still authorizes each call with KATIBA, using a fresh NAK assertion (audiencengamia-te). If TE is down, its tools are removed for that run and knowledge search continues.
Memory
KUMBUKUMBU memory is used only when the agent has memory: true and
NAK_KUMBU_ENDPOINT is set. NAK recalls up to five facts into the prompt. Unless
NAK_KUMBU_FORWARD_EVENTS=false, each turn’s user input and final answer are
sent to memory for extraction. Memory failures never fail a run; recall
degrades to no facts.
Policy and approvals
NAK uses a platform policy with a high default risk floor. knowledge_search
and the allowlisted TE tools have a low floor. A tool’s effective risk is the
higher of its declared risk and its floor, and any side-effecting tool is
always high risk. High risk requires human approval.
NAK has no approval authority yet. Its approval verifier (DenyApprovals)
refuses every decision, and platform agents set an approval window of zero.
So a high-risk or approval-requiring call never runs. NAK also refuses to start
a run if an offered tool is side-effecting without durable idempotency, or
does not declare its execution mode.
HTTP surface
NAK listens on NAK_BIND (default 127.0.0.1:8090). Every /v1 and /mcp
route requires a credential.
| Route | Purpose | Relayed by the platform |
|---|---|---|
POST /v1/runs | Start a run: agent, input, optional previous_run_id, wait. Honors Idempotency-Key. | Yes, as POST /v1/agents/{slug}/runs |
GET /v1/runs/{run_id} | Run status. | Yes |
GET /v1/runs/{run_id}/events | Server-Sent Events, resumable. | Yes |
POST /v1/runs/{run_id}/continue | Continue an unfinished run with its pinned configuration. | Yes |
POST /v1/runs/{run_id}/cancel | Stop an unfinished run. | Yes |
POST /v1/runs/{run_id}/approval | Submit an approval decision and proof. | No |
/mcp | MCP Streamable HTTP (run_agent, get_run_status, continue_run, resume_approval). | No |
GET /healthz | Process health only. Unauthenticated. | No |
GET /readyz | Dependency readiness. Unauthenticated. | No |
Start behavior:
- Idempotency. The run ID is derived from the caller and the
Idempotency-Key, so a repeat returns the same run. Reusing a key with a different agent, input orprevious_run_idreturns409 idempotency_key_reused. - Background execution. A run keeps going if the client disconnects. With
"wait": falsethe response is202with{"status":"running"}.
| Error code | HTTP | Cause |
|---|---|---|
unauthorized | 401 | Missing, invalid or replayed assertion. |
not_found | 404 | Unknown agent or run, or a run owned by another caller. |
run_in_progress, run_conflict | 409 | Another worker is driving the run, or a store sequence conflict. |
idempotency_key_reused | 409 | Same key, different request. |
workspace_budget_exhausted | 429 | Monthly token budget used up. |
overloaded | 503 | More than NAK_MAX_CONCURRENT_REQUESTS run requests at once. |
temporarily_unavailable | 503 | A dependency returned a transient error. |
The platform does not pass engine errors through. Its callers get unavailable
and a request_id.
Storage
SQLite (NAK_STORE=sqlite, default) | PostgreSQL (NAK_STORE=postgres) | |
|---|---|---|
| Run log | Local file NAK_RUN_DB (WAL, full sync). | NAK_DATABASE_URL, pool size NAK_STORE_MAX_CONNECTIONS (default 10). TLS verify-full is forced. |
| Replay guard | Local file NAK_REPLAY_DB. Single node only. | Table nak_assertion_replays, shared by all replicas. |
| Topology | One node. | Several replicas. |
Apply the PostgreSQL schema as a separate deployment step with a DDL-capable role:
ngamia-runtime migrateIt uses NAK_MIGRATION_DATABASE_URL, else NAK_DATABASE_URL, and is
idempotent. At startup NAK checks that the tables exist. Give the runtime role
only read and write privileges.
Neither store encrypts run content at the application layer. Events hold user input, answers and tool output. Protect the database, backups and access.
Configuration
| Variable | Default | Purpose |
|---|---|---|
NAK_AGENT_SOURCE | (unset) | platform runs platform-defined agents. |
NAK_BIND | 127.0.0.1:8090 | Listen address. |
NAK_NGAMIA_BASE_URL | required | Ngamia model gateway. |
NAK_UBONGO_BASE_URL | required | UBONGO origin. HTTPS unless loopback. |
NAK_UBONGO_ALLOW_HTTP | false | Allow plain HTTP to UBONGO. |
NAK_PLATFORM_URL | required (platform) | Platform base for /internal/v1. |
NAK_PLATFORM_ALLOW_HTTP | false | Allow http:// to the platform on a private network. |
NAK_PLATFORM_ASSERTION_KEYS | required (platform) | JSON map of key ID to Ed25519 public key (1 to 8). |
NAK_PLATFORM_ASSERTION_ISSUER | ngamia-platform | Expected issuer of caller assertions. |
NAK_PLATFORM_AUDIENCE | ngamia-nak | Expected audience of caller assertions. |
NAK_ASSERTION_KEY_FILE | required (platform, TE, memory) | NAK’s Ed25519 private key, PKCS#8 DER. Must not be readable by group or others. |
NAK_ASSERTION_KEY_ID | required with key file | Key ID that verifiers map to NAK’s public key. |
NAK_ASSERTION_ISSUER | ngamia-nak | Issuer of NAK’s outgoing assertions. |
NAK_STORE | sqlite | sqlite or postgres. |
NAK_RUN_DB | ./data/ngamia-runs.sqlite3 | SQLite run log. |
NAK_REPLAY_DB | ./data/ngamia-assertions.sqlite3 | SQLite replay guard. |
NAK_DATABASE_URL | required (postgres) | Runtime database connection. |
NAK_MIGRATION_DATABASE_URL | NAK_DATABASE_URL | Connection used by migrate. |
NAK_STORE_MAX_CONNECTIONS | 10 | PostgreSQL pool size. |
NAK_TE_ENDPOINT | (unset) | TE origin. Empty disables TE tools. |
NAK_TE_AUDIENCE | ngamia-te | Audience for TE assertions. |
NAK_TE_ALLOWED_TOOLS | required with TE | Comma-separated tool_id@version names. |
NAK_KUMBU_ENDPOINT | (unset) | KUMBUKUMBU origin. Empty disables memory. |
NAK_KUMBU_AUDIENCE | ngamia-kumbukumbu | Audience for memory assertions. |
NAK_KUMBU_FORWARD_EVENTS | on | false stops sending turns to memory. |
NAK_MAX_OUTPUT_TOKENS | 900 | Output cap per model call. |
NAK_MODEL_ATTEMPTS | 3 | Attempts per model call. |
NAK_MAX_CONCURRENT_REQUESTS | 64 | Run requests handled at once. Event streams are not counted. |
NAK_MONTHLY_TOKEN_BUDGET | (unset) | Optional tokens per workspace per calendar month (UTC). |
Outside platform mode, NAK serves a fixed knowledge assistant configured with
NAK_IDENTITY_MODE (go_assertion or kida), NAK_WORKSPACE_CONFIG_FILE
and the NAK_IDENTITY_SECRET or NAK_KIDA_* variables. See
NAK/crates/runtime/README.md.
Operations
Health and readiness
GET /healthzreturns{"status":"ok"}while the process runs. It checks nothing else.GET /readyzreturns200only when the run store, the model gateway health endpoint, UBONGO’s/readyz, and (in KIDA mode) the KIDA key cache are ready. Otherwise it returns503with adependenciesmap showing which failed.
UBONGO is part of readiness even for workspaces that do not use knowledge.
Route traffic on /readyz, and use /healthz for liveness.
Crash recovery and continue
A background supervisor runs every 30 s. It reads the store’s event feed and continues runs that have shown no progress for 5 minutes, for example after a crash, and records expiry for unanswered approvals. The first pass reads the whole feed.
POST /v1/runs/{run_id}/continue does the same on demand. It replays the log
and resumes with the pinned configuration. If an agent, tool catalog or policy
changed in a way that alters a fingerprint, continuation fails closed.
A tool call is bracketed by ToolStarted and ToolFinished. If NAK stops in
between, recovery calls the tool again with the same run-id:call-id key, so
the tool must deduplicate. Platform mode offers only read-only tools.
Scaling
With NAK_STORE=postgres, NAK is stateless apart from the database. Run two or
more replicas. Any replica can serve /events and /continue, and assertion
replay protection holds across replicas. If two supervisors continue the same
run, the store’s sequence check lets one win. With SQLite, run one node.
PostgreSQL cursor allocation is serialized at commit, which can limit append throughput under load.
Known limits
- No approval flow. Calls that need human approval (high risk or side effects) are refused. Only read-only, low-risk tools run.
- No side-effecting tools. TE tools are offered only if read-only.
- No encryption at rest for run content in either store. Retention, deletion and backup automation are the operator’s job.
- Readiness includes UBONGO, so a UBONGO outage marks NAK not ready.
- Budget lag. The monthly token budget is counted by the supervisor, so enforcement lags by up to one pass and a run already started may finish.
- Cancellation does not interrupt a tool call already in flight; its result is not recorded.
- Streaming is per model reply, not per token.
Repository docs
| Path | Content |
|---|---|
docs/ARCHITECTURE.md | Whole-platform architecture and run flow. |
NAK/README.md | Crates and build commands. |
NAK/docs/architecture.md | Kernel components, lifecycle and accounting. |
NAK/docs/event-log.md | Event format v5, ordering and replay invariants. |
NAK/docs/server.md | REST, SSE, MCP, stores and HTTPS deployment. |
NAK/docs/operations.md | Recovery, upgrades and platform mode. |
NAK/docs/security.md | Trust boundaries, approvals, budgets and prompt injection. |
NAK/docs/te-integration.md | TE contract, assertions and engine variables. |
NAK/crates/runtime/README.md | Runtime host setup outside platform mode. |