Skip to Content
The Ngamia platform API is in preview. Endpoints may change before general availability.
EnginesNAK: agent runtime

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.

  1. Start. NAK resolves the agent, lists the tools the agent may use, and writes a RunStarted event. This event pins the agent, its limits, the exact tool catalog, and the fingerprints of the tool source, policy and validator.
  2. Model call. NAK builds the context (system instructions, optional memory facts, the transcript) and asks the model for the next reply.
  3. Budget check. Before a reply is accepted, NAK checks the step and token budgets. A reply that would exceed either budget fails the run.
  4. Tool calls. Each requested call is validated against the tool’s JSON schema and checked by policy. An allowed call is recorded as ToolStarted before it runs and ToolFinished after. NAK assigns the call IDs (s{step}-{index}), not the provider.
  5. Finish. When the model replies without tool calls, NAK records RunCompleted with 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

LimitMeaning
max_stepsCombined count of model replies and tool calls in a run. Set per agent.
max_total_tokensCumulative input plus output tokens the run may use. Set per agent.
Output tokensEach model call is capped at NAK_MAX_OUTPUT_TOKENS (default 900).
Tool outputTool 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.
TimeoutsOne model attempt: 45 s. One tool call: 25 s. Model calls are retried up to NAK_MODEL_ATTEMPTS times (default 3).

Run statuses

StatusMeaning
runningAccepted and being driven in the background (returned for "wait": false).
completedFinished with output.
waiting_approvalPaused before a tool call that needs approval. See Known limits.
failedEnded with an error, for example step limit reached or token budget reached.
cancelledStopped 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 eventPublic stream nameExtra data
RunStartedrun.startedagent, thread_id, previous_run_id
ModelRepliedmodel.repliedtext, tool_calls (id, name, args), input_tokens, output_tokens
ToolStartedtool.startedcall_id
ToolFinishedtool.finishedcall_id, is_error, output
ApprovalRequestedapproval.requestedcall, reason, digest, expires_at_ms
ApprovalResolvedapproval.resolvedcall_id, granted, approver
RunCompletedrun.completedoutput
RunFailedrun.failederror
RunCancelledrun.cancelledreason

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 (default ngamia-platform),
  • audience NAK_PLATFORM_AUDIENCE (default ngamia-nak),
  • app platform and a UUID tenant (the workspace),
  • a lifetime of at most 60 s, and a UUID jti that 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, and max_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_ENDPOINT is set, the tool is listed in NAK_TE_ALLOWED_TOOLS as an exact tool_id@version, and TE declares it read-only. TE still authorizes each call with KATIBA, using a fresh NAK assertion (audience ngamia-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.

RoutePurposeRelayed by the platform
POST /v1/runsStart 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}/eventsServer-Sent Events, resumable.Yes
POST /v1/runs/{run_id}/continueContinue an unfinished run with its pinned configuration.Yes
POST /v1/runs/{run_id}/cancelStop an unfinished run.Yes
POST /v1/runs/{run_id}/approvalSubmit an approval decision and proof.No
/mcpMCP Streamable HTTP (run_agent, get_run_status, continue_run, resume_approval).No
GET /healthzProcess health only. Unauthenticated.No
GET /readyzDependency 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 or previous_run_id returns 409 idempotency_key_reused.
  • Background execution. A run keeps going if the client disconnects. With "wait": false the response is 202 with {"status":"running"}.
Error codeHTTPCause
unauthorized401Missing, invalid or replayed assertion.
not_found404Unknown agent or run, or a run owned by another caller.
run_in_progress, run_conflict409Another worker is driving the run, or a store sequence conflict.
idempotency_key_reused409Same key, different request.
workspace_budget_exhausted429Monthly token budget used up.
overloaded503More than NAK_MAX_CONCURRENT_REQUESTS run requests at once.
temporarily_unavailable503A 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 logLocal file NAK_RUN_DB (WAL, full sync).NAK_DATABASE_URL, pool size NAK_STORE_MAX_CONNECTIONS (default 10). TLS verify-full is forced.
Replay guardLocal file NAK_REPLAY_DB. Single node only.Table nak_assertion_replays, shared by all replicas.
TopologyOne node.Several replicas.

Apply the PostgreSQL schema as a separate deployment step with a DDL-capable role:

ngamia-runtime migrate

It 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

VariableDefaultPurpose
NAK_AGENT_SOURCE(unset)platform runs platform-defined agents.
NAK_BIND127.0.0.1:8090Listen address.
NAK_NGAMIA_BASE_URLrequiredNgamia model gateway.
NAK_UBONGO_BASE_URLrequiredUBONGO origin. HTTPS unless loopback.
NAK_UBONGO_ALLOW_HTTPfalseAllow plain HTTP to UBONGO.
NAK_PLATFORM_URLrequired (platform)Platform base for /internal/v1.
NAK_PLATFORM_ALLOW_HTTPfalseAllow http:// to the platform on a private network.
NAK_PLATFORM_ASSERTION_KEYSrequired (platform)JSON map of key ID to Ed25519 public key (1 to 8).
NAK_PLATFORM_ASSERTION_ISSUERngamia-platformExpected issuer of caller assertions.
NAK_PLATFORM_AUDIENCEngamia-nakExpected audience of caller assertions.
NAK_ASSERTION_KEY_FILErequired (platform, TE, memory)NAK’s Ed25519 private key, PKCS#8 DER. Must not be readable by group or others.
NAK_ASSERTION_KEY_IDrequired with key fileKey ID that verifiers map to NAK’s public key.
NAK_ASSERTION_ISSUERngamia-nakIssuer of NAK’s outgoing assertions.
NAK_STOREsqlitesqlite or postgres.
NAK_RUN_DB./data/ngamia-runs.sqlite3SQLite run log.
NAK_REPLAY_DB./data/ngamia-assertions.sqlite3SQLite replay guard.
NAK_DATABASE_URLrequired (postgres)Runtime database connection.
NAK_MIGRATION_DATABASE_URLNAK_DATABASE_URLConnection used by migrate.
NAK_STORE_MAX_CONNECTIONS10PostgreSQL pool size.
NAK_TE_ENDPOINT(unset)TE origin. Empty disables TE tools.
NAK_TE_AUDIENCEngamia-teAudience for TE assertions.
NAK_TE_ALLOWED_TOOLSrequired with TEComma-separated tool_id@version names.
NAK_KUMBU_ENDPOINT(unset)KUMBUKUMBU origin. Empty disables memory.
NAK_KUMBU_AUDIENCEngamia-kumbukumbuAudience for memory assertions.
NAK_KUMBU_FORWARD_EVENTSonfalse stops sending turns to memory.
NAK_MAX_OUTPUT_TOKENS900Output cap per model call.
NAK_MODEL_ATTEMPTS3Attempts per model call.
NAK_MAX_CONCURRENT_REQUESTS64Run 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 /healthz returns {"status":"ok"} while the process runs. It checks nothing else.
  • GET /readyz returns 200 only when the run store, the model gateway health endpoint, UBONGO’s /readyz, and (in KIDA mode) the KIDA key cache are ready. Otherwise it returns 503 with a dependencies map 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

PathContent
docs/ARCHITECTURE.mdWhole-platform architecture and run flow.
NAK/README.mdCrates and build commands.
NAK/docs/architecture.mdKernel components, lifecycle and accounting.
NAK/docs/event-log.mdEvent format v5, ordering and replay invariants.
NAK/docs/server.mdREST, SSE, MCP, stores and HTTPS deployment.
NAK/docs/operations.mdRecovery, upgrades and platform mode.
NAK/docs/security.mdTrust boundaries, approvals, budgets and prompt injection.
NAK/docs/te-integration.mdTE contract, assertions and engine variables.
NAK/crates/runtime/README.mdRuntime host setup outside platform mode.