Skip to content

Latest commit

 

History

History
2111 lines (1824 loc) · 121 KB

AdminAPI.md

File metadata and controls

2111 lines (1824 loc) · 121 KB

Admin API

The Kern admin API is served by the localhost admin service.

Base URL after port forwarding:

http://127.0.0.1:7443

API requests authenticate with a session cookie, except for the login ceremonies and narrowly scoped public-login status described below. POST /v1/login with {"password": "<admin-password>"} returns an HttpOnly, SameSite=Strict session cookie immediately when no passkey is configured. Once a passkey is enrolled, public HTTPS login returns WebAuthn request options and mints the session only after POST /v1/login/passkey verifies the second factor. Subsequent requests send the session cookie automatically and must also include the CSRF header X-Kern-Csrf: 1. POST /v1/logout revokes the session and clears the cookie. The password is presented only at /v1/login and never replayed on later requests; there is no bearer-token path.

Requests to the public tunnel hostname must arrive over HTTPS (the origin redirects or refuses cleartext). SSH-forwarded loopback requests use HTTP. Repeated failed logins are throttled and return 429; see admin login sessions.

API responses are JSON except for documented file/media streams. Static UI assets also return their own content types: GET /, GET /oauth/callback, the admin CSS/JavaScript/favicon paths, and the trusted Chat and Web Apps UI modules under /workspace/ are served by the admin service without authentication. /workspace/ is an asset namespace within the admin UI, not a separate server or trust boundary. They return only static files and perform no state change. The sole unauthenticated JSON read is GET /v1/login/status on the configured public HTTPS hostname; it returns only whether a passkey is enrolled. Login ceremonies and the narrowly scoped public media capability route also run before session authentication. All remaining API routes, including every workspace proxy request, require an authenticated caller.

Contents

Host AI inference providers

GET    /v1/host-inference/providers
PUT    /v1/host-inference/providers/{provider}
DELETE /v1/host-inference/providers/{provider}

These operator-only routes manage host-owned inference connections. Provider metadata never includes the stored API key. Records from the GET list include enabled/configured state, feature toggles, and a usage object with current-calendar-month UTC totals. PUT and DELETE return the changed connection metadata without querying the independent usage counter:

{
  "provider": "openai",
  "enabled": true,
  "configured": true,
  "features": {},
  "updated_at": "2026-09-20T00:00:00Z",
  "usage": {
    "month_to_date": 0.001234,
    "currency": "USD",
    "requests": 12,
    "measured_requests": 12,
    "priced_requests": 12,
    "input_tokens": 4200,
    "cached_input_tokens": 1000,
    "output_tokens": 300
  }
}

requests counts provider responses admitted to the bounded metering writer. measured_requests counts responses with a valid provider usage object, and priced_requests counts responses whose fixed model had a reviewed price at request time. A gap is preserved so the estimate never silently treats unknown usage as zero. Only GPT-6 Luna and Jev usage is retained; responses with missing or unsupported model names are skipped with a Host diagnostic. Cost reflects the price at request time. If the writer is saturated or unavailable, Kern records a Host diagnostic.

PUT accepts the closed object enabled, optional write-only api_key, and the provider's exact features object. Enablement and the key are independent: a provider enabled without a saved key stays unused until the key is saved. DELETE disables the provider and removes its key; retained usage remains visible for the current month. These routes do not expose an agent-facing inference action.

Errors

Every non-2xx response returns this JSON envelope:

{
  "error": {
    "message": "Human-readable error message"
  }
}

Error response fields:

Field Required Type Values Meaning
error.message Yes string Human-readable error message for logs and operator display.

Error status codes:

HTTP status Meaning
400 Request JSON, query string, or field value is invalid.
401 Missing or invalid admin password or session.
403 A cookie-authenticated request is missing the X-Kern-Csrf header, or the Workspace service attempted a disallowed host route.
404 Requested resource or route does not exist.
409 Request conflicts with current runtime, thread, approval, or credential state.
413 Request body exceeds the 1 MiB admin API limit.
415 Login has a missing, duplicate, or unsupported Content-Type; it requires exactly one application/json media type.
429 Too many failed admin logins from this source (retry after the lockout window), or the selected runtime is already running its maximum concurrent threads (retry when one finishes).
503 A required local service is unavailable or busy, or the shared admin request capacity is exhausted. The latter includes error.code: "host_busy" and Retry-After: 5.
502 The workspace backend or delegated tools service is unavailable or returned an invalid response.
500 Host-side error.

Session

POST /v1/login
POST /v1/login/passkey
GET  /v1/login/status
POST /v1/logout

POST /v1/login takes {"password": "<admin-password>"} and requires exactly one Content-Type: application/json header. Parameters such as charset=UTF-8 are allowed. Missing or duplicate Content-Type headers and other media types (including text/plain, form-urlencoded, and multipart) return 415 before password verification or throttle accounting, without issuing a cookie. Clients using curl -d must also set -H 'Content-Type: application/json'; the default form media type is rejected.

With no passkey, a correct password returns {"ok": true} and an HttpOnly; SameSite=Strict session cookie: tc_admin_session on SSH-forwarded HTTP, or __Host-tc_admin_session with Secure; Path=/ and no Domain on public HTTPS. A wrong password returns 401 and sets no cookie. When passkeys are configured on the public HTTPS path, a correct password instead returns {"passkey_required": true, "publicKey": {...}} and a five-minute, non-session pre-authentication cookie. The browser submits its WebAuthn assertion to POST /v1/login/passkey; only successful verification mints the admin session. The assertion route therefore runs before session authentication, but it is not an independent login path: it requires the unguessable pre-authentication cookie issued only after a correct password. That cookie and its server-side challenge expire after five minutes, are bound to the same client source and public origin, and are consumed by the first assertion attempt whether it succeeds or fails. Repeated password failures are throttled with 429.

GET /v1/login/status is available only through the configured public HTTPS admin hostname and returns {"passkey_configured": true|false} with Cache-Control: no-store. It requires no session so the login page and Kern Cloud can accurately show whether public login has its second factor enabled. It exposes no credential identifiers or metadata. The SSH-forward origin returns 404, preserving its database-independent recovery path.

Authenticated passkey enrollment uses:

GET  /v1/admin-passkeys
POST /v1/admin-passkeys/register/options
POST /v1/admin-passkeys/register

The status response tells the UI whether credentials exist and whether setup is available on the current public HTTPS hostname. Registration requires an authenticated session, a fresh single-use challenge, an ES256 resident credential, and authenticator user verification. Enrollment is not offered on the SSH-forward origin: every route in this passkey-management namespace returns 404 there because WebAuthn credentials are scoped to their public RP domain. The host stores only the credential id, public key, signature counter, transports, backup flag, and timestamps.

POST /v1/logout revokes the current session and clears the cookie, returning {"ok": true}. Like every non-login route it requires an authenticated caller; a cookie-authenticated call must include the X-Kern-Csrf header.

Health

GET /v1/health

Response:

{
  "status": "ok",
  "issues": [],
  "agent_name": "kern-dev-agent",
  "agent_runtime": {
    "runtimes": [
      {
        "type": "codex",
        "status": "active",
        "active_thread_ids": []
      },
      {
        "type": "claude_code",
        "status": "deactivated",
        "active_thread_ids": []
      }
    ]
  },
  "network_controls": {
    "status": "active"
  },
  "version": {
    "status": "ok",
    "runtime": "x.y.z",
    "state": "x.y.z"
  },
  "upgrade": {
    "available": true,
    "latest": "x.y.z"
  },
  "lifetime_tokens": {
    "input_tokens": 0,
    "cached_input_tokens": 0,
    "cache_write_tokens": 0,
    "output_tokens": 0
  },
  "history": {
    "threads": 24,
    "messages": 1286,
    "activities": 9431
  },
  "host_runtime": {
    "cpu": {
      "usage_percent": 12.5
    },
    "memory": {
      "used_bytes": 980000000,
      "total_bytes": 2147483648
    },
    "filesystem": {
      "mounts": {
        "root": {
          "used_bytes": 6000000000,
          "total_bytes": 17179869184
        },
        "admin": {
          "used_bytes": 250000000,
          "total_bytes": 17179869184
        },
        "agent": {
          "used_bytes": 500000000,
          "total_bytes": 8589934592
        }
      }
    },
    "swap": {
      "allocated_bytes": 6442450944,
      "used_bytes": 536870912
    }
  }
}

Response fields:

Field Type Values Meaning
status enum ok, degraded Overall host health. ok means the agent runtimes, network controls, versions, and root-volume capacity are healthy. degraded means the admin service is responding but at least one issue is present.
issues array Actionable reasons for a degraded status; empty when status is ok.
issues[].kind enum agent_runtime, network_controls, version, root_filesystem Component that caused the degraded status.
issues[].summary string Short operator-facing reason.
issues[].detail string Specific status or error detail.
issues[].next_step string Recommended operator action.
agent_name string Host name from the input config.
agent_runtime.runtimes array Status records for every supported runtime.
agent_runtime.runtimes[].type enum codex, codex-2, codex-3, claude_code, grok, grok-2, hermes, script Agent runtime type; script is the providerless, schedule-only Bash runtime.
agent_runtime.runtimes[].status enum deactivated, loading, awaiting_login, active, error Current agent runtime supervisor state.
agent_runtime.runtimes[].active_thread_ids string array Threads with a live turn on this runtime.
network_controls.status enum active, error Derived network policy enforcement state.
version.status enum ok, mismatch, error Version health for the running root volume and preserved admin state.
version.runtime string or null Kern version from /opt/kern-host/VERSION.
version.state string or null Kern preserved-state version from admin disk version.json.
upgrade.available boolean Whether the public infiloop2/kern main-branch version is newer than the running version. This advisory check does not affect overall health.
upgrade.latest string or null Latest valid version returned by a successful public-repository check, or null until the first check succeeds after service start. A failed later check preserves the last successful value.
lifetime_tokens object Host lifetime known token totals across all providers: input_tokens, cached_input_tokens, cache_write_tokens, output_tokens. Four disjoint integer buckets, starting at feature deployment without backfill. Updated by measurement deltas, including corrections, and unaffected by the 90-day detail retention. Missing measurements contribute no known tokens; these are consumption totals, not billing or complete coverage.
history.threads integer Monotonic number of agent threads recorded on this host.
history.messages integer Monotonic number of user messages recorded on this host.
history.activities integer Monotonic number of agent messages and activity records, including tool calls, commands, reasoning, and other agent work.
host_runtime.cpu.usage_percent number 0-100 Current host CPU usage percentage.
host_runtime.memory.used_bytes integer Current host memory used, in bytes.
host_runtime.memory.total_bytes integer Total host memory, in bytes.
host_runtime.filesystem.mounts.root.used_bytes integer Current root filesystem used space, in bytes.
host_runtime.filesystem.mounts.root.total_bytes integer Total root filesystem capacity, in bytes.
host_runtime.filesystem.mounts.admin.used_bytes integer optional Current admin data volume (/mnt/kern-admin) used space, in bytes.
host_runtime.filesystem.mounts.admin.total_bytes integer optional Total admin data volume (/mnt/kern-admin) capacity, in bytes.
host_runtime.filesystem.mounts.agent.used_bytes integer optional Current agent data volume (/mnt/kern-agent) used space, in bytes.
host_runtime.filesystem.mounts.agent.total_bytes integer optional Total agent data volume (/mnt/kern-agent) capacity, in bytes.
host_runtime.swap.allocated_bytes integer Filesystem-backed RAM swap allocated to the host, in bytes.
host_runtime.swap.used_bytes integer Current filesystem-backed RAM swap used, in bytes.

Runtime status is deactivated when that runtime's managed provider integration or additional account is disabled, loading while the runtime is starting, awaiting_login while an OAuth runtime needs operator login, active while it can accept work, and error when the runtime supervisor cannot make it healthy. Hermes has no OAuth flow: while Bedrock is enabled it is awaiting_login until a validated credential is connected, then active.

network_controls.status is derived, not stored. It is active when the persisted network policy is valid and the proxy process is listening. It is error when the policy cannot be parsed or policy enforcement is not healthy. The error state fails closed and denies all network access.

Agent Runtime

GET  /v1/agent-runtime/status
GET  /v1/agent-runtime/account
PUT  /v1/agent-runtime/account-enabled
POST /v1/agent-runtime/refresh
POST /v1/agent-runtime/codex-oauth-login
GET  /v1/agent-runtime/codex-oauth-login
POST /v1/agent-runtime/codex-2-oauth-login
GET  /v1/agent-runtime/codex-2-oauth-login
POST /v1/agent-runtime/codex-3-oauth-login
GET  /v1/agent-runtime/codex-3-oauth-login
POST /v1/agent-runtime/claude-oauth-login
GET  /v1/agent-runtime/claude-oauth-login
POST /v1/agent-runtime/claude-oauth-login/complete
POST /v1/agent-runtime/grok-oauth-login
GET  /v1/agent-runtime/grok-oauth-login
POST /v1/agent-runtime/grok-2-oauth-login
GET  /v1/agent-runtime/grok-2-oauth-login
GET  /v1/agent-runtime/bedrock-credentials
POST /v1/agent-runtime/bedrock-credentials
DELETE /v1/agent-runtime/bedrock-credentials
POST /v1/agent-runtime/reset-linked-account

Agent runtime endpoints:

Method Path Request Response Behavior
GET /v1/agent-runtime/status none Agent runtime status response Returns current state for every runtime.
GET /v1/agent-runtime/account none Agent account response Returns the current account status for every runtime.
PUT /v1/agent-runtime/account-enabled {"agent_runtime":"codex-2","enabled":true} Agent account response Enables or disables one additional account (codex-2, codex-3, or grok-2). Exactly these two fields are required; enabled must be a boolean. Invalid bodies or primary runtimes return 400.
POST /v1/agent-runtime/refresh Agent runtime refresh request Agent account response Attempts to refresh provider account/status for one runtime or all runtimes, then returns the current account response.
POST /v1/agent-runtime/codex-oauth-login none Codex OAuth login response Starts a Codex OAuth login flow and returns the device code and login link.
GET /v1/agent-runtime/codex-oauth-login none Codex OAuth login response Returns the current Codex OAuth device code and login link.
POST /v1/agent-runtime/codex-2-oauth-login none Codex OAuth login response Starts a Codex 2 OAuth login flow and returns the device code and login link.
GET /v1/agent-runtime/codex-2-oauth-login none Codex OAuth login response Returns the current Codex 2 OAuth device code and login link.
POST /v1/agent-runtime/codex-3-oauth-login none Codex OAuth login response Starts a Codex 3 OAuth login flow and returns the device code and login link.
GET /v1/agent-runtime/codex-3-oauth-login none Codex OAuth login response Returns the current Codex 3 OAuth device code and login link.
POST /v1/agent-runtime/claude-oauth-login none Claude OAuth login response Starts a Claude Code OAuth login process and returns the login link.
GET /v1/agent-runtime/claude-oauth-login none Claude OAuth login response Returns the current Claude Code OAuth login link.
POST /v1/agent-runtime/claude-oauth-login/complete {"code": "..."} status response Submits the browser login code back to the waiting Claude Code OAuth process.
POST /v1/agent-runtime/grok-oauth-login none Grok OAuth login response Starts a Grok device-code login against xAI and returns the user code and login link. There is no completion endpoint: xAI polls its own approval and resolves the waiting login.
GET /v1/agent-runtime/grok-oauth-login none Grok OAuth login response Returns the current Grok device code and login link.
POST /v1/agent-runtime/grok-2-oauth-login none Grok OAuth login response Starts a Grok 2 device-code login against xAI and returns the user code and login link. There is no completion endpoint: xAI polls its own approval and resolves the waiting login.
GET /v1/agent-runtime/grok-2-oauth-login none Grok OAuth login response Returns the current Grok 2 device code and login link.
GET /v1/agent-runtime/bedrock-credentials none {"connected": false} or {"connected": true, "access_key_id": "AKIA...", "region": "us-east-1"} Returns whether the Bedrock connection is stored plus its non-secret access key id and region. The secret is never returned.
POST /v1/agent-runtime/bedrock-credentials {"access_key_id": "AKIA...", "secret_access_key": "...", "region": "us-east-1"} {"status": "accepted"} Synchronously validates the Bedrock long-term IAM access key pair with STS, then stores the credential, region, and account metadata atomically. Validation runs even while Bedrock is disabled; a rejected candidate returns 400, is not retained, and leaves any previous validated connection unchanged. AWS checks model-specific invocation permission and model access on the first real turn, avoiding a paid setup invocation. Later AWS failures are reported by the turn that encounters them; they do not create a stored credential-health state. The request accepts exactly these three fields; the secret is never returned.
DELETE /v1/agent-runtime/bedrock-credentials none status response Disconnects the AWS account, clears its credential, region, and account metadata, then fails running Hermes turns. The live usage counters are retained: they record work already done.
POST /v1/agent-runtime/reset-linked-account {"agent_runtime": "codex"|"codex-2"|"codex-3"|"claude_code"|"grok"|"grok-2"} status response Clears the selected OAuth runtime's linked account state. Bedrock uses the credential endpoint above because it uses an IAM credential instead of OAuth.

The runtime-specific OAuth login endpoints work while that runtime's status is awaiting_login or error — an errored runtime (changed account, malformed local credentials) is recovered by simply logging in again. They return 409 in any other state, including deactivated. POST /v1/agent-runtime/reset-linked-account takes {"agent_runtime": "codex"}, {"agent_runtime": "codex-2"}, {"agent_runtime": "codex-3"}, {"agent_runtime": "claude_code"}, or {"agent_runtime": "grok"}, or {"agent_runtime": "grok-2"} and deletes that runtime's linked-account guard: the operator-approved anchor, its proxy pin, and any pending OAuth approval. Use it to unlink the account, for example to switch a runtime to a different provider account. It may be called in any runtime status. It also moves the runtime out of active, clears local agent auth files, closes that runtime's live processes, and fails its running turns so no process from the old linked account keeps executing. The runtime is then ready for a fresh operator login that links an account again. GET /v1/agent-runtime/account does not accept query parameters; it always returns one account-status entry per runtime. POST /v1/agent-runtime/refresh accepts {} to refresh all runtimes, or {"agent_runtime": "codex"}, {"agent_runtime": "codex-2"}, {"agent_runtime": "codex-3"}, {"agent_runtime": "claude_code"}, {"agent_runtime": "grok"}, {"agent_runtime": "grok-2"}, or {"agent_runtime": "hermes"} to refresh one. For enabled accounts it forces a provider check instead of reusing a remembered live-validation verdict. Disabled additional accounts are skipped. It returns the same response shape as GET /v1/agent-runtime/account.

Linked, enabled Claude Code and Grok accounts also expose data_training: {"allowed": true, "checked_at": "2026-10-16T10:00:00+00:00", "attempted_at": "2026-10-16T10:00:00+00:00"}. allowed is true when training is allowed, false when opted out, and null until verified. Timestamps are nullable ISO 8601 strings. A failed check advances attempted_at and preserves the last successful verdict and checked_at. Checks run after activation, then approximately every ten minutes while unknown or after failures, and daily after success. Manual runtime refresh forces a check. Disabled accounts are not checked. Resetting or replacing the linked account clears its privacy result. Codex does not expose this field.

Primary accounts follow their overall provider switch. Additional accounts require explicit enablement and an enabled provider. A disabled additional account reports deactivated, makes no automatic or manual provider checks, and cannot start OAuth login or new work. Disabling stops its running turns, closes pending login flows, and revokes both data-plane and status-probe proxy authorization, while preserving its anchor, credentials, sessions, and historical usage. Enabling starts a background refresh; if the provider is off, its status is deactivated. Provider off/on cycles and linked-account resets preserve the account opt-in. The upgrade enables existing operator-approved anchors; unlinked slots start disabled.

Agent runtime status response:

{
  "runtimes": [
    {
      "type": "codex",
      "status": "active",
      "active_thread_ids": []
    },
    {
      "type": "claude_code",
      "status": "deactivated",
      "active_thread_ids": []
    }
  ]
}

Agent runtime status response fields:

Field Type Values Meaning
runtimes[].type enum codex, codex-2, codex-3, claude_code, grok, grok-2, hermes, script Agent runtime type; script is the providerless, schedule-only Bash runtime.
runtimes[].status enum deactivated, loading, awaiting_login, active, error Current runtime state. Codex uses its rate-limit request and, if that fails, one Codex-owned forced refresh. Claude Code uses a /usage probe for the pinned token, or provider profile attestation for a new or rotated token. Grok uses live auth, entitlement, and billing probes through the managed xAI proxy. Bedrock is active when the integration is enabled and its synchronously validated credential/account row is present. AWS checks model-specific invocation permission and current credential validity on the first real turn; later provider failures are turn failures.
runtimes[].active_thread_ids string array Threads with a live turn on that runtime, sorted by thread id. Empty when no turn is running.
runtimes[].error_message string optional Present only while status is error: the underlying runtime failure message.

Agent account response:

{
  "accounts": [
    {
      "agent_runtime": "codex",
      "provider": "openai",
      "status": "active",
      "account_id": "acct_...",
      "email": "operator@example.com",
      "plan_type": "pro",
      "codex_usage": {
        "last_checked_at": "2026-06-29T23:10:00Z",
        "rate_limits": {
          "primary": {
            "used_percent": 60,
            "window_duration_mins": 300,
            "resets_at": 1782788896
          },
          "secondary": {
            "used_percent": 20,
            "window_duration_mins": 10080,
            "resets_at": 1783296254
          },
          "credits": {
            "has_credits": false,
            "unlimited": false,
            "balance": "0"
          }
        }
      }
    },
    {
      "agent_runtime": "claude_code",
      "provider": "claude",
      "status": "active",
      "account_id": "uuid...",
      "email": "operator@example.com",
      "plan_type": "pro",
      "claude_usage": {
        "current_session_used_percent": 0,
        "current_session_resets_at": 1782781800,
        "weekly_used_percent": 0,
        "weekly_resets_at": 1783094340,
        "fable_weekly_used_percent": 0,
        "fable_weekly_resets_at": 1783094340,
        "last_checked_at": "2026-06-29T23:10:00Z"
      }
    },
    {
      "provider": "bedrock",
      "agent_runtimes": ["hermes"],
      "status": "active",
      "account_id": "123456789012",
      "arn": "arn:aws:iam::123456789012:user/kern-bedrock",
      "bedrock_usage": {
        "month_to_date": 0.3102,
        "currency": "USD",
        "requests": 41,
        "metered_requests": 41,
        "input_tokens": 402118,
        "output_tokens": 31889,
        "cache_read_tokens": 0,
        "cache_write_tokens": 0
      }
    }
  ]
}

Agent account response fields:

Field Type Values Meaning
accounts[].agent_runtime enum codex, codex-2, codex-3, claude_code, grok, grok-2 Runtime for an OAuth provider record. Absent on the Bedrock record.
accounts[].agent_runtimes string array ["hermes"] Runtime that uses the Bedrock provider. Present only on the Bedrock record.
accounts[].provider enum openai, claude, xai, bedrock Managed AI provider.
accounts[].status enum deactivated, loading, awaiting_login, active, error Current provider account status. OAuth runtimes use awaiting_login when operator login is required. Bedrock has no OAuth flow: its status is awaiting_login until a synchronously validated credential is connected, then active. Later inference failures are reported on their turns, not persisted as provider status.
accounts[].enabled boolean present only for codex-2, codex-3, and grok-2 The additional account's stored opt-in. false reports deactivated and omits plan/usage metadata; linked identity remains visible. Primary accounts inherit their provider switch and omit this field.
accounts[].account_id string optional The linked provider account id; for bedrock this is the 12-digit AWS account id. Present whenever a validated account identity is available.
accounts[].email string optional Present when available from the linked account metadata.
accounts[].arn string optional The STS-attested IAM identity of the connected AWS credential. Present only on the Bedrock provider record while its account is linked.
accounts[].plan_type string optional Common plan name for the provider account. Present only while the runtime is active.
accounts[].codex_usage object optional Codex-specific usage metadata. Present only for the Codex runtime when Codex reports rate limits.
accounts[].codex_usage.last_checked_at string optional UTC timestamp when Kern last refreshed the cached Codex usage snapshot. Active runtimes are rechecked every 300 seconds.
accounts[].codex_usage.rate_limits object optional Codex rate-limit snapshot.
accounts[].codex_usage.rate_limits.primary object optional Codex 300-minute rate-limit window.
accounts[].codex_usage.rate_limits.secondary object optional Codex 10080-minute rate-limit window.
accounts[].codex_usage.rate_limits.primary.used_percent, accounts[].codex_usage.rate_limits.secondary.used_percent number optional Percent used for this window.
accounts[].codex_usage.rate_limits.primary.window_duration_mins, accounts[].codex_usage.rate_limits.secondary.window_duration_mins number optional Window duration in minutes.
accounts[].codex_usage.rate_limits.primary.resets_at, accounts[].codex_usage.rate_limits.secondary.resets_at number optional Unix timestamp when this window resets.
accounts[].codex_usage.rate_limits.credits object optional Codex credit snapshot.
accounts[].codex_usage.rate_limits.credits.has_credits boolean optional Whether the account has credits.
accounts[].codex_usage.rate_limits.credits.unlimited boolean optional Codex unlimited.
accounts[].codex_usage.rate_limits.credits.balance string optional Codex credit balance.
accounts[].claude_usage object optional Claude Code usage metadata parsed from claude -p "/usage" --output-format json. Windows parse independently, so any subset of the fields below can be present.
accounts[].claude_usage.current_session_used_percent number optional Percent used for the current Claude Code session.
accounts[].claude_usage.current_session_resets_at number optional Unix timestamp when the current Claude Code session window resets.
accounts[].claude_usage.weekly_used_percent number optional Percent used for the current Claude Code weekly window across all models.
accounts[].claude_usage.weekly_resets_at number optional Unix timestamp when the Claude Code weekly window resets.
accounts[].claude_usage.fable_weekly_used_percent number optional Percent used for the Fable-specific weekly window.
accounts[].claude_usage.fable_weekly_resets_at number optional Unix timestamp when the Fable-specific weekly window resets.
accounts[].claude_usage.last_checked_at string optional UTC timestamp of the provider read that produced this Claude usage snapshot. Active runtimes are rechecked every 300 seconds; the explicit refresh endpoint forces an immediate provider read. If no usage window parses, claude_usage is absent rather than stale.
accounts[].coding_data_retention_opt_out boolean optional Present only on the Grok record when xAI reports it: whether the linked account has opted out of coding-data retention. Absent when xAI does not report a value, which is not the same as false.
accounts[].grok_usage object optional Grok subscription usage metadata. Present only for the Grok runtime when xAI reports a usage snapshot; xAI often reports none, in which case the field is absent rather than zero.
accounts[].grok_usage.usage_percent number Percent of the subscription credit allowance used, as xAI reports it. The snapshot is built only when this parses, so grok_usage is never present without it.
accounts[].grok_usage.period_type enum optional, daily, weekly, monthly Billing period xAI reports for the current window, normalized from its own spelling. Absent when xAI reports a period this host does not recognise.
accounts[].grok_usage.resets_at number optional Unix timestamp when the current period ends.
accounts[].grok_usage.subscription_tier string optional Subscription tier name as xAI reports it.
accounts[].grok_usage.on_demand_enabled boolean optional Whether the account may spend beyond its subscription allowance on demand.
accounts[].grok_usage.last_checked_at string optional UTC timestamp of the provider read that produced this Grok usage snapshot.
accounts[].bedrock_usage object always on the bedrock record Live Hermes month-to-date usage. For each allowed Bedrock response the network proxy records the token usage AWS reports and the USD it prices that response at, per model and UTC day; this sums the current month from those stored counters, so every accounts read is current with no AWS call. Usage survives credential resets: the counters record work already done.
accounts[].bedrock_usage.month_to_date number Current-month cost: the sum of the USD the proxy priced each metered response at when it recorded it, using the host's on-demand catalog rates. Final once recorded; a later rate edit does not rewrite it. An estimate of what AWS will bill, not the bill itself.
accounts[].bedrock_usage.currency string Always USD (the catalog rates' currency).
accounts[].bedrock_usage.requests number Allowed Bedrock invocations forwarded this month.
accounts[].bedrock_usage.metered_requests number Invocations whose response carried a parseable usage record. A gap below requests means AWS errors or unparsed responses, that is, possible undercounting. A model outside the price table is still metered; its tokens count but it adds nothing to month_to_date.
accounts[].bedrock_usage.input_tokens, .output_tokens, .cache_read_tokens, .cache_write_tokens number Month-to-date token totals as AWS reported them per response. The cached-token counters mirror the Converse usage shape, including cache reads and writes reported for supported models.

Codex OAuth login response:

{
  "status": "awaiting_login",
  "device_code": "ABCD-EFGH",
  "login_url": "https://auth.openai.com/activate",
  "expires_at": "2026-06-08T00:10:00Z"
}

Codex OAuth login response fields:

Field Type Values Meaning
status enum awaiting_login Current Codex OAuth login state.
device_code string Code the operator enters on the Codex OAuth login page.
login_url string Operator URL for Codex OAuth login.
expires_at string RFC 3339 timestamp Time when the device code expires.

Claude OAuth login response:

{
  "status": "awaiting_code",
  "login_url": "https://claude.com/cai/oauth/authorize?...",
  "expires_at": "2026-06-08T00:10:00Z"
}

Grok OAuth login response:

{
  "status": "awaiting_login",
  "device_code": "ABCD-EFGH",
  "login_url": "https://accounts.x.ai/device?user_code=ABCD-EFGH",
  "expires_at": "2026-06-08T00:10:00Z"
}

Grok OAuth login response fields:

Field Type Values Meaning
status enum awaiting_login Current Grok OAuth login state.
device_code string Code the operator confirms on the xAI device-login page. It also appears as the user_code parameter inside login_url.
login_url string Operator URL for the xAI device login.
expires_at string RFC 3339 timestamp Time when the device code expires.

Unlike Claude, Grok has no completion endpoint. xAI polls its own approval and resolves the waiting login, so the operator confirms the code in the browser and the runtime becomes active on its own.

After opening the URL and completing browser login, submit the displayed code to POST /v1/agent-runtime/claude-oauth-login/complete:

{
  "code": "..."
}

Agent runtime reset-linked-account response:

{
  "status": "accepted"
}

Agent runtime reset-linked-account response fields:

Field Type Values Meaning
status enum accepted The linked account was reset.

Threads

POST /v1/threads/{thread_id}/messages
GET  /v1/threads
GET  /v1/threads/{thread_id}
POST /v1/threads/{thread_id}/stop
POST /v1/threads/{thread_id}/clear-memory
GET  /v1/threads/{thread_id}/events?since=<seq>&limit=<n>&message_bytes=<b>

All agent work runs on threads. A thread is a durable conversation with a client-chosen id (thread_id) and a session configuration (agent_runtime, model, effort); it is created implicitly by its first message, never by a separate create call. The public model has no turn resource or turn lifecycle: a thread is simply idle or running, and its history is one chronological stream. Work on the same thread is serialized; work on different threads runs in parallel, up to 50 per runtime. Codex resumes the thread's provider conversation by id on a fresh app-server; Claude Code and Hermes resume by their recorded provider session ids. An idle thread may replace all three configuration fields atomically on its next message. That clears the old provider session and starts a fresh one with a handoff that independently reserves up to 100,000 characters for the newest retained user and agent messages and up to 150,000 characters for the newest activity records. Activity records become compact summaries capped at 8,000 characters each, so large command results or generated source cannot displace the retained conversation. The durable thread id and visible history do not change.

There is no queue. A message is synchronously accepted into an idle or running thread, or rejected with a descriptive 409 or 429; the caller decides whether and when to retry. Agent work runs only while its chosen runtime is active: a message for a non-active runtime is rejected at admission. Policy changes and provider-status refreshes own the transition out of active; either transition closes that runtime's live processes, including a run admitted just before the transition, and records thread.error. Any runtime/CLI exception during execution — including a provider rate limit — also returns the thread to idle with thread.error and its error message.

The agent-facing retained-history endpoints are POST /v1/conversation-history/search and POST /v1/conversation-history/read, proxied through Workspace. They return bounded message, notice, and optional activity records, preserving notice kinds instead of relabeling them as user messages. Their roles and notice_kinds filters are independent; context/action details require include_details. See the history contract for schemas, limits, and examples. These history projections are separate from the raw thread event endpoint below.

Thread endpoints:

Method Path Request Response Behavior
POST /v1/threads/{thread_id}/messages Send message request Send message response Durably admits an idle thread's initial message or synchronously delivers a running thread's steer, creating the thread on its first message. Rejected with 409/429 when it cannot be accepted; there is no queue.
GET /v1/threads?before=<cursor>&limit=<n>&prefix=<text> query parameters optional Thread list response Lists one newest-first page of threads with their session configuration, live status, and nullable current task title. prefix is an optional filter/query optimization and conveys no ownership or authorization.
GET /v1/threads/{thread_id} none {"thread": {...}} Returns one thread's session and event sequence fields; the list-only task title is omitted. 404 when no thread row exists. Accepts no query parameters.
POST /v1/threads/{thread_id}/stop none {"status": "accepted"} Stops the thread's running work: the thread returns durably to idle, a thread.stopped event is appended, and process interruption is requested. 404 for an unknown thread; 409 (the thread has no running work) when the thread is idle. The thread survives and a later message resumes the conversation, but sends receive a retryable 409 until the old process has fully shut down.
POST /v1/threads/{thread_id}/clear-memory none {"status": "cleared"} Clears the thread's working memory: the provider session mapping is dropped so the next run opens a new provider conversation, a thread.memory_cleared event is appended, and that event's seq becomes the thread's handoff floor so the next run is not handed the cleared context. Nothing is deleted — retained events stay readable here and in conversation history, while Chat hides events older than the latest clear boundary. 404 for an unknown thread; 409 (working memory can be cleared only while the thread is idle) while a turn is running. A thread stopped moments earlier reads as idle while its process is still closing, and clearing then returns the retryable 409 the thread is still finishing; retry shortly until that worker is gone — the fence that stops it restoring the session just cleared. Retry that one rather than treating it as a failure; the Workspace proxy does this for Chat.
GET /v1/threads/{thread_id}/events?since=<seq>&limit=<n>&message_bytes=<b> query parameters optional Event list response One chronological page of the thread's event stream. See Events.

Operator and peer-authenticated Workspace-service callers use the same thread id contract. The three prefixes identify the product thread kind; they do not convey authority or prevent operator inspection and recovery. Thread summaries include latest_event_seq, the newest retained event sequence for that thread (or 0 before any activity), so clients can detect changes without relying on the whole-second last_used_at timestamp. They also include latest_message_seq, the newest retained thread.message or delivered thread.notice (payload.source: "user") sequence, or 0. Context injections, action receipts, and agent activity do not advance unread-message indicators.

Stop has no mailbox or deferred delivery. The HTTP request synchronizes directly with steering and provider event writes, commits thread.stopped, changes the private phase to FINISHING, and requests a non-blocking process interrupt before returning accepted. Provider session ids are persisted by adapter callbacks as soon as they become usable, not deferred to Stop. The owning execution thread still closes and verifies the scope before releasing the same-thread fence; a send during that short cleanup window receives the documented retryable 409.

Send message request:

{
  "agent_runtime": "codex",
  "model": "gpt-6.2-sol",
  "effort": "high",
  "message": "Implement this change and report the result."
}

Send message request fields:

Field Required Type Meaning
message Yes string Message for the agent runtime. Must be 1 to 50,000 characters. The host handles idle and running threads; callers use the same operation for both.
agent_runtime New thread or configuration change enum Runtime for the thread: codex, codex-2, codex-3, claude_code, grok, grok-2, or hermes. Supply it together with model and effort. On an existing thread, a matching triple resumes or steers the current provider session; a different triple starts a fresh provider session only while the thread is idle.
model New thread or configuration change enum Model for this session. Codex accepts gpt-6.2-sol, gpt-6.2-astra, or gpt-6-luna; Claude Code accepts claude-opus-5-5, claude-fable-5-2, or claude-sonnet-5-5; Grok accepts grok-4.7; Hermes accepts the Bedrock model ids deepseek.v3.2, qwen.qwen3-coder-next, us.moonshotai.kimi-k3.1, us.zai.glm-5.3, or minimax.minimax-m2.5. Must be supplied together with agent_runtime and effort. List and get responses expose the current session configuration; retained conversation and usage records preserve their history.
effort New thread or configuration change enum Effort for this session. Codex accepts high, max, ultra, high-fast, or high-ultrafast, except Luna accepts only high and max. The two speed presets request High reasoning with Fast or Ultrafast processing; the other presets send no speed override. Model, plan, and workspace availability are enforced by Codex; Kern surfaces provider errors without falling back. Claude Code accepts high, max, or ultracode; ultracode enables its xhigh effort plus dynamic workflow orchestration. Grok accepts xhigh or high. Hermes accepts high (its headless CLI exposes no effort control). Must be supplied together with agent_runtime and model.

The path's thread_id must be at most 64 lowercase letters, digits, or hyphens: app- or thread- followed by a nonempty suffix, or schedule- followed by a positive decimal integer without leading zeros. Any other value is 404 (no such route). The same rule applies to operator and Workspace-service callers. Workspace marks operator relays with operator_sent_message: true; Kern deliveries instead require kern_notice: {kind, summary} from the trusted Workspace service. Operator requests cannot supply Kern notice metadata. The first message requires all three configuration fields. Later messages may omit all three or repeat the complete matching triple. A different complete triple rotates an idle thread to a new provider session in the same admission transaction; a partial triple returns 400, and a change while running returns 409. The synthetic handoff is sent only to the new provider: the visible event stream records a completed thread.activity describing the old and new session configuration, followed by the operator's new message and a compact thread.notice with notice.kind: "history_transfer". Its historical_context stores a bounded beginning/end preview of at most 24 KiB, with an explicit marker when the middle is omitted. The full provider handoff independently preserves up to 100,000 characters of newest conversation and 150,000 characters of newest bounded activity summaries; older retained history may be omitted. Provider-side context and cache reads from the previous session are not available. Thread rows referenced by retained events are preserved; otherwise the host retains the 100,000 most recently used mappings per runtime. Once a thread is no longer retained, supplying a configuration starts a fresh provider conversation.

The same bounded handoff is used without a configuration change when an existing thread has retained events but no provider session id—for example, after startup failed before the replacement provider published a resumable id. A brand-new thread with no history receives only its first message.

Follow-up message request:

{
  "message": "Continue with the implementation."
}

Send message response:

{
  "status": "accepted",
  "thread": {
    "thread_id": "thread-feature-1",
    "agent_runtime": "codex",
    "model": "gpt-6.2-sol",
    "effort": "high",
    "last_used_at": "2026-06-08T00:00:00Z",
    "status": "running"
  }
}

Send message response fields:

Field Type Values Meaning
status enum accepted The host accepted the message and its durable input event committed. Operator input uses thread.message; Kern input uses thread.notice. Idle and running threads intentionally have the same response.
thread object The thread, in the same shape as a thread list entry.

For an idle thread, the host durably admits the message and starts its runtime worker; accepted does not mean the provider has accepted that initial message yet. A later startup/provider failure appears as thread.error. For a running thread, accepted means the live provider transport acknowledged the message and its durable input event then committed. Codex acknowledgement is a successful turn/steer JSON-RPC response. The Codex stdout reader routes that response directly to the waiting request, so processing unrelated activity notifications cannot delay acknowledgement. Claude Code exposes no per-message response, so its acknowledgement is a successful write and flush to the live stream-json stdin. There is no host steer mailbox and no delivery-marker table.

If provider acknowledgement succeeds but the following database write fails, the API returns an error and no user event appears even though the CLI may act on the message. Retrying can deliver it twice. This deliberately at-least-once failure edge is the trade for avoiding a durable cross-system delivery protocol; callers may safely retry when duplicate natural-language steering is acceptable. Hermes cannot receive another message while it is running: a message for a busy Hermes thread returns 409; a later message after it becomes idle resumes the stored provider conversation.

Message rejections (there is no queue, so each names the condition and the caller retries):

Status Condition error.message
409 The thread's runtime is not active (its status is loading, awaiting_login, or error). <Runtime> runtime is <status>; messages run only while it is active
409 The thread's runtime is disabled in the network policy. <Runtime> runtime is deactivated; enable its provider under Home > Agent runtimes
409 The admitted process has not yet accepted its initial message. This private startup phase is normally brief; retry the same request. the agent is starting; retry shortly
409 The previous work is durably final but its runtime process is still shutting down. The live fence remains so a new message never races the dying process; retry the same request. the agent is finishing; retry shortly
409 Hermes has no mid-run input channel. Hermes cannot accept another message while running; wait for it to finish
409 A message tries to change configuration while work is running. thread runtime, model, and effort can change only while the thread is idle
409 The thread's current session configuration left the option matrix and the message does not replace it. this thread runs a session configuration that is no longer offered; select a currently offered model to continue
429 The runtime is at its admission cap. Each runtime owns an independent pool of 50 concurrent threads. Host memory, process, proxy, and tool capacity are shared and may still limit actual throughput. <Runtime> runtime is already running 50 concurrent threads; retry when one finishes
502 A provider that already declared itself running rejects a synchronous message. The host records thread.error, finalizes the run, and begins cleanup rather than treating this as startup. <Runtime> rejected the message: <provider detail>

Thread list response:

{
  "threads": [
    {
      "thread_id": "thread-feature-1",
      "agent_runtime": "codex",
      "model": "gpt-6.2-sol",
      "effort": "high",
      "last_used_at": "2026-06-08T00:05:00Z",
      "status": "running"
    }
  ],
  "next_before": "WyIyMDI2LTA2LTA4VDAwOjA1OjAwWiIsImZlYXR1cmUtY2hhdC0xIl0"
}

An uncursored request returns the newest page. limit=<n> defaults to 100 and must be between 1 and 100. When another page exists, the response includes an opaque next_before cursor; pass it unchanged as before=<cursor> to load older threads. Ordering uses last_used_at followed by globally unique thread_id, so equal timestamps paginate without omissions. The cursor is a URL-safe encoding of that composite position, not a thread id or a secret; clients treat it as opaque so the sort-key representation can change without changing their parsing logic.

Thread list response fields:

Field Type Meaning
threads thread array Recent known threads sorted by last_used_at descending.
next_before string Optional opaque cursor for the next older page. Absent when this is the last page.
threads[].thread_id string Client-generated conversation id.
threads[].agent_runtime enum Runtime for this thread: codex, codex-2, codex-3, claude_code, grok, grok-2, or hermes.
threads[].model enum Model for the thread's current provider session.
threads[].effort enum Effort for the thread's current provider session.
threads[].last_used_at string Latest message or successful-settlement timestamp known for this thread.
threads[].status enum Public current state: running while an admitted execution still owns the thread fence (including private startup and cleanup), idle otherwise.

The host stores current run state privately on the thread row; lifecycle markers are not public events. After a host restart or reboot, each thread left running is atomically returned to idle and receives one thread.error event (host runtime restarted while the thread was running). Internally, each live execution moves through STARTING, RUNNING, FINISHING, and CLOSED. The database commits admission before STARTING and finalization before FINISHING, leaving process startup and teardown as in-memory lifecycle work. A provider publishes a non-empty resumable session id as soon as it proves one usable; Kern persists that callback immediately for the matching run and never stores an empty replacement.

POST /v1/threads/{thread_id}/stop commits thread.stopped and the idle database state, moves the execution to FINISHING, requests a prompt interrupt, and returns accepted. The owning execution thread performs bounded process and systemd-scope cleanup. A send during that short cleanup receives the retryable FINISHING conflict above. If the scope cannot be proven gone, Kern records thread.error and deliberately retains the fence; this indicates host process-management failure and should be recovered with a host restart.

Swarm

GET /v1/swarm requires an operator session. Optional q searches names, purposes, and task titles (up to 100 characters). The response contains generated_at, all matching active agents, and has_more: false. Idle/disconnected agents are included; Bash jobs are excluded.

Each agent has thread_id, kind (app, on-demand, standing, spawned), name, purpose, agent_runtime, model, nullable next_run_at, and:

  • state: busy while running; otherwise failed when the latest event is thread.error, or idle.
  • task: nullable generated title for on-demand Chats only. App/Standing agents show their purpose; Spawned agents show their parent and name.
  • spawned_by_thread_id: parent identity for Spawned agents, otherwise null.
  • pending_approval_count: pending native tool approvals and gated GitHub pushes attributed to the thread, independent of runtime status.

GET /v1/swarm/interactions is operator-only, without query parameters. It returns since, through (UTC dates), interactions, earlier and metrics. The window is today plus the previous 29 UTC dates; daily counts are retained for 90 UTC dates. Each day's messages and tokens are weighted by 0.5 ^ (age_days / 7).

  • interactions: directed pairs with at least one message in the window, as sender_thread_id, target_thread_id, integer count (window messages), float weight (recency-weighted count) and last_day (UTC date). At most 1,000 pairs ranked by weight descending, then count and sender/target ID for stable ties. Pairs with an archived Chat or App, or a deleted or Bash schedule, are dropped before the cap.
  • earlier: pairs with retained messages but none in the window, as sender_thread_id, target_thread_id, integer count, last_day; the same endpoint filter, at most 1,000 by last_day descending.
  • metrics: per identity, raw window operator_messages, agent_peers, total_tokens, tokens_partial, plus weighted with the same three signals recency-weighted (a peer counts by its latest contact). Ranking uses weighted; metrics include links that are not returned.

This bounds layout springs and SVG paths; all agents stay on the map and stored daily counts are not truncated. Counts are recorded atomically on accepted agent message delivery, including spawning/steering, and accepted operator messages. Operator sends use the reserved sender ID operator, derived from the authenticated operator or trusted Workspace browser path, never message text. Scheduled wake-ups, rejected sends and generated replies do not create operator links. Daily buckets contain no message text, event IDs or summaries. Buckets older than 90 days are removed on the next accepted delivery; reads always exclude expired dates. Earlier messages are not backfilled.

Accepted automated deliveries use the reserved sender ID kern-host when neither a trusted peer sender nor operator provenance is present. This covers scheduled triggers, approval outcomes and restart notices, on admission and live steering. Bash jobs stay excluded. Host counts are recorded from delivery, without historical reconstruction. Host messages contribute neither operator-message counts nor distinct agent peers in involvement metrics.

The Swarm map shows all active agent characters plus synthetic Operator and Kern host nodes. These sender nodes sit at the centre of the map and have no agent runtime, involvement score or conversation link. Recency-weighted 30-day involvement determines how closely each agent orbits the operator and its orb size (60% direct operator messages, 25% distinct agent peers, 15% known tokens, each scaled with diminishing returns across active identities); rings mark involvement tiers. Combined bidirectional message volume draws collaborators together using bounded passes; spawned agents also join their parent with a dashed lineage line. The canvas pans without bounds. Arrow width shows recency-weighted directed volume; select a node or link to inspect exact counts. This represents communication, not formal reporting lines. Status/count refreshes preserve positions; roster changes or Arrange recalculate the layout using current weights. Zoom/fit controls and a duplicate attention sidebar keep errors and approvals accessible. State/search filters highlight matches without removing other nodes. Communication-count failures leave the agent snapshot usable with no/stale links and an error notice.

Events

GET /v1/threads/{thread_id}/events?since=<seq>&limit=<n>&message_bytes=<b>
GET /v1/events?before=<seq>&limit=<n>

Event endpoints:

Method Path Request Response Behavior
GET /v1/threads/{thread_id}/events?since=<seq>&limit=<n>&message_bytes=<b> query parameters optional Event list response One chronological page of the flat thread event stream.
GET /v1/events?before=<seq>&limit=<n> query parameters optional Event list response Lists newest agent events before an optional sequence cursor.

The two endpoints serve different access patterns. Thread events follow one conversation: an uncursored request returns the newest page (in chronological order, so opening a long thread does not scan its full history), before=<seq> loads earlier history, and since=<seq> keeps a loaded tail current with events whose seq > since — use the highest returned seq as the next since, and keep the same since when a response is empty. since and before cannot be combined. limit=<n> is optional, defaults to 100, and must be between 1 and 100. message_bytes=<b> is optional and must be between 1 and 200,000: when supplied, each event's message and error_message payload text is truncated to that many encoded bytes, and an activity's detail and output fields share the same budget (at most 24 KiB of it goes to detail), before the response crosses a proxy boundary; every clipped value ends with … (truncated).

The audit log across all threads pages newest-first like the network audit log: the first request returns the newest events, and before=<seq> continues with events whose seq is lower than that cursor. limit=<n> is optional, defaults to 100, and must be between 1 and 100.

The host retains the newest 100,000,000-event sequence window globally; older events are discarded and can no longer be listed. Sequence gaps can leave fewer rows. For events both outside the newest 1,000,000-event sequence window and older than three calendar months, background maintenance removes activity detail/output and notice details, and clears memory_recall_details and historical_context. Cleared fields are omitted, without placeholder text. Message text and compact metadata remain until whole-event retention deletes the row.

Event list response:

{
  "events": [
    {
      "event_id": "event_123",
      "seq": 42,
      "timestamp": "2026-06-08T00:00:00Z",
      "event_type": "thread.message",
      "thread_id": "thread-feature-1",
      "payload": {
        "message": "Update from the agent.",
        "source": "agent"
      }
    }
  ]
}

Event list response fields:

Field Type Meaning
events event array Events ordered by seq: chronological for thread events, newest first for /v1/events. Empty when no matching events are available.

Event fields:

Field Type Values Meaning
event_id string Stable event id (event_<seq>).
seq integer Monotonic host-local event sequence number.
timestamp string RFC 3339 timestamp Event time.
event_type enum See event types below. Event type.
thread_id string or null Related thread id for thread events, or null for agent runtime events.
payload object Event-specific JSON payload.

Event types:

thread.message
thread.activity
thread.error
thread.stopped
thread.memory_cleared
thread.notice
agent_runtime.active
agent_runtime.login_completed
agent_runtime.linked_account_reset
agent_runtime.deactivated
agent_runtime.account_enabled
agent_runtime.account_disabled

thread.message payload fields:

Field Type Values Meaning
message string Every accepted operator message and every completed agent message including the final one.
source enum agent, user Message source.
notice.kind string operator Explicit marker on new operator input. Pasting a Kern preamble does not change the message's provenance. Absent on agent replies and older untyped records.

thread.memory_cleared payload fields:

Field Type Values Meaning
message string The operator-facing boundary notice. Deliberately not an activity payload: clients that collapse events by activity.activity_id would merge repeated clears onto one position.

A client that requests explicit event_type filters must include thread.memory_cleared to render the boundary. It is a display event only: it is never handed to a provider, and a conversation-only view that drops thread.activity is still expected to fetch it.

thread.notice payload fields:

Field Type Description
notice.kind enum Specific input, context, or action kind from the notice catalog. No generic kind.
notice.summary string One display line, at most 100 characters.
notice.details string, when recorded Exact injected identity/memory message for confirmed memory injections. Action outcome and request details are bounded to 20 KB of JSON-encoded text with an explicit truncation marker.
source user, when delivered Present only on input actually delivered to the provider. Context and action receipts omit it.
message string, when recorded Exact provider text for delivered input, including its preamble; compact summary for context notices. Action receipts omit it.
memory_page_ids string array, when recorded Selected page ids on memory injection or suggestion notices. An empty array means no pages were selected.
memory_recall_details string, when recorded Memory retrieval/selection diagnostics or suggestion text; injection notices show their exact notice.details message when expanded.
historical_context string, when recorded Bounded beginning/end preview of transferred history, at most 24 KiB.

Clients must include thread.notice in explicit event filters even when hiding thread.activity. Render notice.summary as the compact text and open the recorded details on click. Delivered notices count as conversation for search, unread indicators, and provider handoffs. Context and action receipts are not replayed as input. The notice specification describes all kinds, producers, and bounds.

Kern records “Historical context transferred” only when retained conversation or activity is included for a new provider session, respecting the latest working-memory clear boundary. “Self identity and N memories injected” confirms the immutable thread identity and counts the validated self/swarm pages included in each model turn. Identity is included even with zero memories. Existing self-memory is loaded before shared-memory search. Live steering, script turns, and rejected admissions produce no injection notice.

Chat, scheduled-agent Chat, and App conversations show these notices even with activity hidden. They are display events: they are excluded from conversation search and future history handoffs. They describe Kern's prompt assembly, not provider acknowledgement or provider-managed context/compaction.

thread.activity payload fields:

Field Type Values Meaning
activity object One provider-independent activity record, normalized from Claude Code stream-json content blocks, Codex app-server ThreadItems, or Hermes tool-call hook events.

activity object fields:

Field Type Values Meaning
activity.provider string The runtime that produced the record.
activity.activity_id string Opaque host-scoped correlation key tying started and completed snapshots of one activity. The host scopes a provider id to its private execution so a fresh provider process may safely reuse ids.
activity.kind enum reasoning, plan, command, file_change, tool, agent, search, image, wait, status Activity category.
activity.phase enum started, completed Snapshot phase. An activity with no completed snapshot proves it began, not that it finished (for example when the thread was stopped mid-activity).
activity.title string Short operator-facing summary.
activity.detail string optional Rich text detail (a command line, a plan, reasoning text). Retained up to 256 KiB; any clipping ends with … (truncated).
activity.output string optional Command or tool output. Retained up to 256 KiB with the same truncation marker.
activity.status string optional Provider status text for the snapshot.
activity.append_output boolean optional true when this snapshot's output appends to the previous snapshot's output for the same activity_id instead of replacing it.

thread.error payload fields:

Field Type Values Meaning
error_message string Human-readable agent failure message.

thread.stopped uses the top-level thread_id field and an empty payload {}. It is emitted when POST /v1/threads/{thread_id}/stop ends running work.

agent_runtime.active uses thread_id: null and payload {"agent_runtime": "codex"}, {"agent_runtime": "codex-2"}, {"agent_runtime": "codex-3"}, {"agent_runtime": "claude_code"}, {"agent_runtime": "grok"}, {"agent_runtime": "grok-2"}, or {"agent_runtime": "hermes"}.

agent_runtime.login_completed uses thread_id: null and payload {"agent_runtime": "codex"}, {"agent_runtime": "codex-2"}, {"agent_runtime": "codex-3"}, {"agent_runtime": "claude_code"}, {"agent_runtime": "grok"}, or {"agent_runtime": "grok-2"}. Hermes has no login flow.

agent_runtime.linked_account_reset uses thread_id: null and payload {"agent_runtime": "codex"}, {"agent_runtime": "codex-2"}, {"agent_runtime": "codex-3"}, {"agent_runtime": "claude_code"}, {"agent_runtime": "grok"}, {"agent_runtime": "grok-2"}, or {"agent_runtime": "hermes"} when an operator reset cleared that runtime's linked account (the audit record of the reset-linked-account endpoint).

agent_runtime.deactivated uses thread_id: null and payload {"agent_runtime": "codex"}, {"agent_runtime": "codex-2"}, {"agent_runtime": "codex-3"}, {"agent_runtime": "claude_code"}, {"agent_runtime": "grok"}, {"agent_runtime": "grok-2"}, or {"agent_runtime": "hermes"} when a runtime is disabled because its managed provider integration is disabled.

agent_runtime.account_enabled and agent_runtime.account_disabled use thread_id: null and payload {"agent_runtime":"codex-2"} (or codex-3 / grok-2) for explicit operator changes to an additional account's opt-in. These are separate from provider deactivation; default-disabled slots do not emit provider-deactivation events at startup.

Agent Files

GET /v1/agent-files?path=<path>
GET /v1/agent-files/read?path=<path>
GET /v1/agent-files/content?path=<path>
GET /v1/agent-files/download?path=<path>
POST /v1/agent-files/upload?filename=<name>

Agent file endpoints:

Method Path Request Response Behavior
GET /v1/agent-files?path=<path> path query parameter is optional; default / Agent file list response Lists one directory under the agent home, including hidden entries.
GET /v1/agent-files/read?path=<path> path query parameter is optional; default / Agent file read response Reads one regular file under the agent home as a UTF-8 text preview.
GET /v1/agent-files/content?path=<path> Required path query parameter Bounded image or video bytes Streams supported media inline for the Files viewer.
GET /v1/agent-files/download?path=<path> Required path query parameter Bounded regular-file bytes with Content-Disposition: attachment Downloads any regular file up to 200,000,000 bytes without rendering its contents.
POST /v1/agent-files/upload?filename=<name> Raw file bytes; Content-Length is required {"file": {...}} Uploads one file into the agent home's user-files/ directory. The body is capped at 25 MiB.

The API treats / as /mnt/kern-agent/agent-home. Paths that resolve outside that home are rejected. Symlinks are not supported: directory listings omit symlink entries, and direct requests for symlink paths return a validation error.

Directory listings inspect and return at most 1,000 entries. Returned entries are sorted. If the scan hits the cap, truncated is true.

Agent file list response:

{
  "path": "/workspace",
  "truncated": false,
  "entries": [
    {
      "name": ".env",
      "path": "/workspace/.env",
      "type": "file",
      "size_bytes": 123,
      "modified_at": "2026-06-08T00:00:00Z"
    }
  ]
}

Agent file read response:

{
  "path": "/workspace/README.md",
  "size_bytes": 123,
  "truncated": false,
  "encoding": "utf-8",
  "content": "File contents..."
}

Text previews allow only known text, source, and configuration extensions and standard filenames such as README, LICENSE, and .gitignore. The allowlist is defined in host/bootstrap/helpers/read-agent-file.sh. Files must be valid UTF-8 without binary control bytes and no larger than 1 MiB. Unknown types (including archives) and oversized files are rejected before reading their contents. These requests succeed with metadata only, for example:

{
  "path": "/workspace/assets.zip",
  "size_bytes": 10033207,
  "preview_unavailable": "unsupported_type"
}

preview_unavailable is unsupported_type, too_large, or binary; no content is returned. The Files viewer shows a download-only message. Image and video previews support JPEG, PNG, WebP, MP4, and MOV up to 25 MiB; larger media are rejected before streaming and remain downloadable within the separate 200,000,000-byte download limit.

Upload filename is the original basename, not a path. It must be non-empty, at most 200 UTF-8 bytes, and contain no slash, backslash, NUL, or control character. The host publishes a completed upload atomically under user-files/ and prefixes its stored name with a sortable UTC timestamp. It never overwrites an existing file. Incomplete uploads are removed.

{
  "file": {
    "path": "user-files/20260722T120000.123456Z_reference.png",
    "name": "20260722T120000.123456Z_reference.png",
    "original_name": "reference.png",
    "size_bytes": 12345,
    "uploaded_at": "2026-07-22T12:00:00.123456Z"
  }
}

path is relative to /mnt/kern-agent/agent-home, which is also the agent runtime's working directory. Uploads are durable workspace data and are not pruned automatically.

Dictation

GET  /v1/dictation/ready
POST /v1/dictation/transcribe

Both routes require the operator session and CSRF header and accept no query parameters. Readiness returns {"ready": true} only when the resident local model is loaded. Transcription accepts exactly {"audio": "<base64>"}, containing mono 16 kHz PCM16 samples (no file header), at most twelve seconds or 384,000 raw bytes, and returns {"text": "..."}. Invalid audio returns 400; an unavailable, loading, or busy worker returns 503. Requests do not load the model or store audio on the host. See dictation behavior and recovery.

Agent Processes

GET /v1/agent-processes

Returns a read-only diagnostic snapshot of Codex, Claude Code, and processes spawned by those runtimes. This is process state, not turn state: short-lived turn processes may exit before the next snapshot. The response contains at most 1,000 processes; when more matching processes exist, truncated is true.

Response:

{
  "truncated": false,
  "processes": [
    {
      "pid": 1234,
      "state": "S",
      "name": "codex",
      "cmdline": "codex app-server --listen stdio://",
      "rss_bytes": 92274688,
      "elapsed_seconds": 184
    }
  ]
}

Network

GET    /v1/network/policy
PUT    /v1/network/policy
GET    /v1/network-tools/github-credential
PUT    /v1/network-tools/github-credential
DELETE /v1/network-tools/github-credential
GET    /v1/network-tools/xai-video-storage
PUT    /v1/network-tools/xai-video-storage
DELETE /v1/network-tools/xai-video-storage
POST   /v1/network-tools/github-audit
GET    /v1/network-tools/github-pending-pushes
POST   /v1/network-tools/github-pending-pushes/<id>/approve
POST   /v1/network-tools/github-pending-pushes/<id>/reject
GET    /v1/network/events?before=<seq>&decision=<allowed|denied|all>&limit=<n>

Network endpoints:

Method Path Request Response Behavior
GET /v1/network/policy none Network policy response Returns active network policy.
PUT /v1/network/policy Network policy request Network policy response Replaces network policy atomically. Disabling a managed provider integration deactivates its runtime, clears its account pin, closes its live runtime processes, and fails its running turns.
GET /v1/network-tools/github-credential none GitHub credential metadata Returns credential metadata only; never the token.
PUT /v1/network-tools/github-credential GitHub credential request GitHub credential metadata Stores or replaces the single fixed GitHub token. The token field is write-only.
DELETE /v1/network-tools/github-credential none GitHub credential metadata Removes the stored credential and withdraws the proxy-injected working token.
GET /v1/network-tools/xai-video-storage none Grok video storage metadata Returns configuration status, bucket and region; never either credential.
PUT /v1/network-tools/xai-video-storage Grok video storage request Grok video storage metadata Replaces all four fields; credentials are write-only. Does not enable Grok or change network policy.
DELETE /v1/network-tools/xai-video-storage none {configured: false} Removes storage configuration; leaves bucket objects, Grok login and custom-domain rules intact.
POST /v1/network-tools/github-audit none GitHub credential metadata Force-refreshes the per-repository audits and returns the updated metadata (including repository_audits).
GET /v1/network-tools/github-pending-pushes none {pending_pushes: [...]} Lists pushes held by the .github approval gate: id, owner, repo, ref_updates, changed_paths, requested_at, status.
POST /v1/network-tools/github-pending-pushes/<id>/approve none {pending_push: {...}} Replays the held push to GitHub with the working token through the approve-github-push root helper and marks it approved. 404 if unknown, 409 if already resolved, another resolution is in progress, no working token is available (the row stays pending), or the replay fails. Replay failures mark the row failed after one best-effort cleanup.
POST /v1/network-tools/github-pending-pushes/<id>/reject none {pending_push: {...}} Cleans up pending quarantine refs (best-effort) and marks the held push rejected. 404/409 as above.
GET /v1/network/events?before=<seq>&decision=<allowed|denied|all>&limit=<n> query parameters optional Network event response Lists newest network decision events before an optional sequence cursor.

The github-credential routes work whether or not network_integrations.github is enabled, so the credential can be staged before the integration is turned on; the proxy-injected working token is only ever published while GitHub is enabled.

Network policy request:

{
  "network_integrations": {
    "openai": {"enabled": true},
    "github": {
      "enabled": true,
      "write_repositories": [
        {"owner": "infiloop2", "repo": "kern"}
      ]
    },
    "custom": {
      "domains": {
        "example.com": {
          "allow_http_methods": ["GET", "HEAD"],
          "path_guards": ["^/$", "^/docs(?:/.*)?$"]
        }
      }
    }
  }
}

The request body is the replacement runtime network controls object using the schema from NetworkControls.md.

When PUT /v1/network/policy is accepted, the replacement policy has been validated and atomically written. Concurrent replacements are last-writer-wins: the stored policy is always exactly one submitted body, never a blend.

Network policy response:

The API response uses the operator-facing network controls shape. Managed integration domains are not listed under the custom integration; the proxy maps each public field directly to its typed integration config, and credential secrets are never included.

{
  "network_controls": {
    "network_integrations": {
      "openai": {"enabled": true},
      "github": {
        "enabled": true,
        "write_repositories": [
          {"owner": "infiloop2", "repo": "kern"}
        ]
      },
      "custom": {
        "domains": {
          "example.com": {
            "allow_http_methods": ["GET", "HEAD"],
            "path_guards": ["^/$", "^/docs(?:/.*)?$"]
          }
        }
      }
    }
  },
  "updated_at": "2026-06-08T00:00:00Z"
}

Network policy response fields:

Field Type Meaning
network_controls object Runtime network controls using the schema from NetworkControls.md.
updated_at string RFC 3339 timestamp for the last policy update. Present in responses only.

GitHub credential request — fine-grained PAT mode:

{
  "mode": "pat",
  "token": "github_pat_..."
}

GitHub credential request — GitHub App mode (the host mints installation-wide tokens and refreshes them before their one-hour expiry; the proxy's repo guard, not the token, is the per-repository boundary — see NetworkControls.md):

{
  "mode": "app",
  "app_id": "12345",
  "installation_id": "67890",
  "private_key_pem": "-----BEGIN RSA PRIVATE KEY-----\n..."
}

GitHub credential request fields (fields outside the chosen mode are rejected):

Field Type Required Meaning
mode string Yes pat or app.
token string pat mode only The fine-grained personal access token.
app_id string app mode only The numeric GitHub App id.
installation_id string app mode only The numeric installation id.
private_key_pem string app mode only The App's PEM private key.

token and private_key_pem are write-only: they are encrypted at rest and never returned by any endpoint or echoed by the UI. While GitHub is enabled and a credential is stored, the network proxy injects the active token into policy-approved GitHub requests — the agent never holds the credential — and plain git and gh read any repository the token reaches and write to the configured write_repositories; see NetworkControls.md.

GitHub credential metadata response — returned by all three github-credential methods and by POST /v1/network-tools/github-audit:

{
  "configured": true,
  "mode": "app",
  "app_id": "12345",
  "installation_id": "67890",
  "app_token_expires_at": "2026-06-08T01:00:00Z",
  "updated_at": "2026-06-08T00:00:00Z",
  "validation": {"status": "ok", "checked_at": "2026-06-08T00:00:00Z"},
  "repository_audits": [
    {
      "owner": "infiloop2",
      "repo": "kern",
      "audited_at": "2026-06-08T00:00:00Z",
      "warnings": [
        {
          "code": "unprotected_default_branch",
          "severity": "critical",
          "message": "The token can push and the default branch is unprotected: ..."
        }
      ]
    }
  ]
}

GitHub credential metadata response fields:

Field Type Present Meaning
configured boolean Always Whether a credential is stored.
mode string When configured pat or app.
updated_at string When configured RFC 3339 time the credential was last stored.
app_id string app mode only The stored GitHub App id.
installation_id string app mode only The stored installation id.
app_token_expires_at string app mode, once the host has minted an installation token Expiry of the current minted token (the host re-mints before it passes). Absent until the first successful mint.
validation object When configured Credential health: {"status": "not_checked"} before the first check, {"status": "ok", "checked_at": ...} after a success, {"status": "error", "message": ..., "checked_at": ...} after a failure — on failure the working token is withdrawn (fail closed) and the poller retries.
repository_audits array When the policy lists write_repositories One entry per listed write repository, in policy order. Audits warn, never gate: a failed or missing audit never blocks the credential or a policy publish. If no credential is configured, each repository reports an incomplete-audit warning.

repository_audits[] entry fields:

Field Type Present Meaning
owner string Always The write repository's owner.
repo string Always The write repository's name.
audited_at string Once an audit attempt has been stored; absent while the first attempt is still pending RFC 3339 time of the last audit attempt (success or failure).
warnings array Always Operator warnings, each {"code", "severity", "message"} with severity critical or warning — for example a public write repository, an unprotected default branch the token can push, workflows whose triggers expose secrets to PR-influenced code, or an incomplete audit when Kern lacks enough information. Empty means a clean audit.
error string When the last audit attempt failed Raw failure detail for diagnostics; the same condition also appears as a warning and the next poller pass retries it.

Network event response:

Network event endpoints return newest-first events. Pass before=<seq> to continue with events whose seq is lower than that cursor. decision=allowed or decision=denied filters the listed events; decision=all is equivalent to omitting the filter. limit=<n> is optional, defaults to 100, and must be between 1 and 100.

Network events are only defined for HTTP, HTTPS, WebSocket, and secure WebSocket requests. SSH and other non-HTTP traffic are not represented by this endpoint.

The host retains only the most recent 1,000,000 network events; older events are discarded and can no longer be listed.

{
  "events": [
    {
      "seq": 42,
      "timestamp": "2026-06-08T00:00:00Z",
      "protocol": "https",
      "method": "GET",
      "host": "api.github.com",
      "port": 443,
      "path": "/repos/infiversehq/kern-host",
      "query": "per_page=5",
      "decision": "allowed"
    }
  ]
}

A denied event additionally carries a stable snake_case reason_code (e.g. host_not_allowed, openai_web_tool_denied) identifying the denial class; allowed events omit it. The same code is the proxy's 403 response body, and the agent-facing recent_network_denials tool maps it to guidance.

Network event response fields:

Field Type Meaning
events network event array Up to limit newest-first events.

Network event fields:

Field Type Values Meaning
seq integer Monotonic host-local network event sequence number.
timestamp string RFC 3339 timestamp Decision time.
protocol enum http, https, ws, wss Request protocol.
method enum GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT HTTP method. For WebSocket requests, this is the handshake method. CONNECT appears only on denied HTTPS or secure WebSocket tunnels that were refused before an inner request was read; allowed tunnels are logged with the method of the inner request.
host string Requested host.
port integer Requested TCP port.
path string Request path without the query string.
query string Request query string without the leading ?, or an empty string when no query was present.
decision enum allowed, denied Network decision.
reason_code string optional Present only on denied events: the stable snake_case code for the denial class. The agent-facing recent_network_denials tool joins it against per-integration guidance.

Grok video storage

These authenticated admin routes back the Grok integration's Video storage form. They work independently of policy enablement; storing credentials does not enable Grok or allow network access to the bucket.

PUT /v1/network-tools/xai-video-storage replaces the whole configuration:

{
  "bucket": "my-grok-videos",
  "region": "us-east-1",
  "access_key_id": "AKIA...",
  "secret_access_key": "..."
}

All four fields are required strings. Unknown fields and invalid values return 400 without changing the saved configuration. bucket accepts 3-63 lowercase letters, digits or hyphens, beginning and ending with a letter or digit. region must match the commercial AWS region-name format. access_key_id must be a long-term IAM key ID beginning AKIA; secret_access_key must be the 40-character IAM secret. Custom endpoints and temporary session credentials are not accepted. Validation checks formats, not AWS permissions or bucket existence.

GET and successful PUT return:

{
  "configured": true,
  "bucket": "my-grok-videos",
  "region": "us-east-1"
}

An absent configuration and successful DELETE return { "configured": false }. These admin responses return neither the access-key ID nor the secret. The secret is encrypted at rest; admin can replace/delete it and the proxy can only read it. The agent never receives the secret access key. Video download URLs contain the access-key ID in X-Amz-Credential and a time-limited signature authorizing the download. Deleting configuration blocks new video work; existing signed URLs can remain valid in AWS until expiry or key revocation. Bucket contents and custom-domain rules are not deleted. Replacement or removal can interrupt active video jobs.

The separate download allowlist, AWS permissions and privacy behavior are covered in the Grok integration guide and internal xAI integration documentation.

Workspace

GET|POST|PUT|DELETE /v1/workspace/chat/{backend_path}
GET|POST|PUT|DELETE /v1/workspace/web-apps/{backend_path}
GET|POST|PUT|DELETE /v1/workspace/memory/{backend_path}
GET|POST|PUT|DELETE /v1/workspace/schedules/{backend_path}
GET|POST|PUT|DELETE /v1/workspace/reminders/{backend_path}
GET|POST|PUT|DELETE /v1/workspace/getting-started/{backend_path}

These authenticated, CSRF-protected prefixes expose Kern's fixed Workspace resources. They are not a package registry: there is no package listing, manifest, generic UI route, or arbitrary app id. The admin API consumes the operator session and proxies JSON plus query parameters to the single workspace listener without forwarding cookies or authorization headers. It adds the fixed backend path prefix and no identity header.

Chat backend paths include /threads for thread-* Chat navigation, /scheduled-agents for active schedule-* navigation, thread messages, events, stop, rename, archive, and unarchive. Web App backend paths include /apps, state/conversation/messages, whole-App revisions/restore, runtime actions, stop, rename, archive, and unarchive. Global Memory and Schedules expose ordinary CRUD plus operator-only deleted/history/restore views. Validation and response envelopes are owned by the Workspace service.

Trusted UI assets are served at /workspace/... and mounted by the admin page in Shadow DOM. The special /workspace/capability-worker-sandbox.js asset is a trusted Worker broker with a networkless CSP. It starts generated Web App JavaScript only in an opaque data: child worker; it is not a general workspace API.

The Workspace service reaches its narrow host-thread API over a peer-authenticated Unix socket. See Chat and Web Apps workspaces.

Approvals

GET /v1/approvals?view=pending&page=1 is operator-only, protected by the normal admin session and CSRF checks. view is pending (default) or history; page is a positive integer and is clamped to the last page. Counts and rows are live reads; concurrent changes can briefly make totals differ from returned rows or shift items between page requests.

The response contains items, page, pages, page_size (always 10), total, pending_count, and history_count. Pending rows sort by creation time; history rows sort by decision time. Each item has kind (tool or github_push), id, source, summary, status, created_at, and updated_at (Unix seconds). Tool items also include tool_id, action_id, connection_id, account_label, and result; GitHub items include owner, repo, ref_updates, changed_paths, and result. Tool payloads are omitted and remain behind the existing authenticated detail endpoint.

Tools

GET  /v1/tools
PUT  /v1/tools/{tool_id}/config
POST /v1/tools/{tool_id}/enable
POST /v1/tools/{tool_id}/disable
POST /v1/tools/{tool_id}/oauth_connect/start
POST /v1/tools/{tool_id}/oauth_connect/complete
POST /v1/tools/{tool_id}/oauth_connect/disconnect
POST /v1/tools/{tool_id}/service/status
POST /v1/tools/{tool_id}/service/connect
POST /v1/tools/{tool_id}/service/disconnect
GET  /v1/tools/{tool_id}/approvals
GET  /v1/tools/{tool_id}/approvals/{approval_id}
GET|HEAD /v1/tools/whatsapp/approvals/{approval_id}/media
POST /v1/tools/{tool_id}/approvals/{approval_id}/approve
POST /v1/tools/{tool_id}/approvals/{approval_id}/deny
GET  /v1/tools/events
GET  /v1/tools/events/{seq}

Bundled tool packages the agent can call once the operator enables them; see the tool contract and host integration for how calls, state, and approvals flow through the host.

Tool endpoints:

Method Path Request Response Behavior
GET /v1/tools none Tool list response Lists every bundled tool with its manifest (actions with per-action data policy, config requirements), enablement, per-tool config status, and connection state. Responses never include config values, tokens, client secrets, or linked-device session keys.
PUT /v1/tools/{tool_id}/config {"key", "value"} {"tool_id", "key", "set"} Sets one config value declared by that tool's manifest. Config is scoped per tool (a repeated key name holds an independent value per tool) and every value is a secret: write-only, stored encrypted at rest (secretbox); an empty value clears the key. 400 when key is not declared by {tool_id}.
POST /v1/tools/{tool_id}/enable none {"tool_id", "enabled"} Enables the tool for agent calls. Not gated on config: a tool can be enabled with partial or no config set (per-key config status is reported by GET /v1/tools); an action that needs an unset key fails when the tool reads it. For WhatsApp this also requests immediate linked-device listener startup; if startup fails, enablement remains committed and a later request or service restart retries it.
POST /v1/tools/{tool_id}/disable none {"tool_id", "enabled"} Disables the tool. Stored connections and credentials are kept; use disconnect to remove them. For WhatsApp this stops the listener while retaining its local session and cache.
POST /v1/tools/{tool_id}/oauth_connect/start {"redirect_uri", "connection_id"?} {"authorization_url", "state", "connection_id"} Starts the tool's OAuth connect flow (OAuth tools only, 409 otherwise or when disabled). For mcp_oauth, the connection id is always default; other ids are rejected, and disconnect is required before connecting again. For oauth, omit connection_id to connect another account; Kern generates the opaque connection id returned in the response. Pass an existing id to reconnect that account. Preserve the returned id for complete. The UI uses <admin origin>/oauth/callback as the redirect URI; register that URL with the OAuth provider. Reached over SSH-forwarded localhost it is a loopback URL such as http://localhost:7443/oauth/callback (providers accept loopback without HTTPS); reached over a Cloudflare Tunnel hostname it is that HTTPS origin's /oauth/callback. Building the URL needs no egress and runs in the admin service; the later code exchange (oauth_connect/complete) runs in the dedicated tools service.
POST /v1/tools/{tool_id}/oauth_connect/complete {"code", "state", "redirect_uri", "connection_id"} {"account": {...}, "connection_id"} Completes the OAuth flow for the connection id returned by start and stores tokens in that connection's credential store. Returns the connected account (see ConnectionAccount below); 400 for a missing connection id or invalid/expired state. The mcp_oauth type also accepts an omitted id, using default.
POST /v1/tools/{tool_id}/oauth_connect/disconnect {"connection_id"} {"tool_id", "connected": false, "connection_id"} Revokes third-party tokens where possible and deletes only the selected connection. The mcp_oauth type accepts an omitted id, using default.
POST /v1/tools/{tool_id}/service/status none Service status Returns operator-only connection state for a manifest-declared service. For WhatsApp this may include a short-lived QR data URL while enabled, or suspended when a registered session is retained while disabled; agent tool actions never receive it.
POST /v1/tools/{tool_id}/service/connect none Service status Asks the tool-owned service to connect. For WhatsApp this starts or resumes the linked-device session and waits briefly for either a QR code or a connected state. Requires the tool to be enabled.
POST /v1/tools/{tool_id}/service/disconnect none Service status Asks the tool-owned service to disconnect. For WhatsApp this logs out the linked device and deletes its durable session keys and bounded local message cache. Available even while the tool is disabled.
GET /v1/tools/{tool_id}/approvals none Approval list response Lists {tool_id}'s action approvals as a bounded working set: pending first (so open decisions surface at the top), then newest decided ones as bounded history. The unified operator queue uses /v1/approvals; this tool-scoped endpoint remains available. Payload is omitted from the list; fetch it per approval. The paginated audit trail is /v1/tools/events.
GET /v1/tools/{tool_id}/approvals/{approval_id} none {"approval"} The full approval record for {approval_id}, including its (up to 64 KiB) payload. 404 when {approval_id} is not an approval of {tool_id}.
GET, HEAD /v1/tools/whatsapp/approvals/{approval_id}/media Optional single Range header Private image/video stream Requires the admin session. Streams only the exact live staged asset in a pending WhatsApp send_message approval; no public grant or source path is accepted. 200 full body, 206 valid byte range, 416 invalid range, 404 missing/nonpending approval or unavailable/changed asset, 503 media capacity exhausted. HEAD returns headers only. Responses are private/no-store; query parameters and fragments are unsupported. See WhatsApp media contract.
POST /v1/tools/{tool_id}/approvals/{approval_id}/approve none {"approval", "result"} Approves a pending approval and immediately executes the recorded payload exactly once; the response carries the terminal approval record (executed or failed) and the execution result. 404 when {approval_id} is not an approval of {tool_id}; 409 when it is not pending.
POST /v1/tools/{tool_id}/approvals/{approval_id}/deny none {"approval"} Denies a pending approval; terminal. 404 when {approval_id} is not an approval of {tool_id}; 409 when it is not pending.
GET /v1/tools/events ?before=&limit= {"events": [...]} The tool audit log, newest first: tool calls, approval decisions, OAuth connect/disconnect, enable/disable, and config set/clear events. Linked-device session changes are live connection state rather than durable audit events. Pages with the same before (an event seq) and limit cursor model as /v1/events and /v1/network/events.
GET /v1/tools/events/{seq} none {"event": {...}} Loads one tool event with its exact action arguments. The paginated list returns only has_arguments, so live refreshes do not repeatedly transfer up to 64 KiB per event. 404 when {seq} does not exist.

Tool list response:

{
  "tools": [
    {
      "tool_id": "example_tool",
      "display_name": "Example Tool",
      "description": "Read and act on a connected third-party account. Sensitive actions are approval-gated.",
      "connection": "oauth",
      "enabled": true,
      "actions": [
        {
          "id": "search_items",
          "description": "Search items.",
          "data_policy": "Read-only. Sends the query to Example and returns item ids and metadata. Runs directly with no approval.",
          "approval": "direct",
          "input_schema": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"], "additionalProperties": false},
          "output_schema": {"type": "object", "required": ["message", "items"], "properties": {"message": {"type": "string", "description": "How many items matched."}, "items": {"type": "array", "description": "Matching items, newest first.", "items": {"type": "object", "properties": {"id": {"type": "string", "description": "Item id; pass to send_item."}}, "additionalProperties": false}}}, "additionalProperties": false},
          "returns_asset": false
        },
        {
          "id": "send_item",
          "description": "Queue approval to send an item.",
          "data_policy": "Sends an item through the connected account. Queued for approval before any third-party state changes.",
          "approval": "operator",
          "input_schema": {"type": "object", "properties": {"item_id": {"type": "string"}}, "required": ["item_id"], "additionalProperties": false},
          "output_schema": {},
          "returns_asset": false
        }
      ],
      "config": [
        {"key": "EXAMPLE_CLIENT_ID", "description": "Third-party client id for the hosting deployment.", "set": true},
        {"key": "EXAMPLE_CLIENT_SECRET", "description": "Third-party client secret for the hosting deployment.", "set": true}
      ],
      "protections": [
        "OAuth tokens stay in the host credential store and are never exposed to the agent.",
        "Writes wait for explicit operator approval."
      ],
      "setup_steps": [
        {
          "title": "Create an OAuth client",
          "description": "Create a Web application client and register the exact Kern callback URI.",
          "link_url": "https://provider.example/oauth-guide",
          "link_label": "View provider instructions",
          "image_path": "/guide-assets/provider-oauth-client.png",
          "image_alt": "Provider Web application client form.",
          "show_callback": true,
          "show_config": false
        }
      ],
      "data_summary": {
        "cards": [
          {
            "title": "What leaves this host",
            "description": "Only the query text, filters, and resource ids an action uses.",
            "points": [],
            "links": []
          },
          {
            "title": "Where it can go",
            "description": "Only to Provider's API service.",
            "points": [],
            "links": []
          },
          {
            "title": "What Provider can do with it",
            "description": "Provider processes request data under its privacy policy.",
            "points": [{"label": "Before connecting", "text": "Review the connected account's data settings."}],
            "links": [{"label": "Provider privacy policy", "url": "https://provider.example/privacy"}]
          },
          {
            "title": "How long Provider retains it",
            "description": "Provider retains request records for at most 90 days.",
            "points": [],
            "links": [{"label": "Provider privacy policy", "url": "https://provider.example/privacy"}]
          }
        ]
      },
      "connected_accounts": [
        {
          "connection_id": "connection_0123456789abcdef01234567",
          "account": {"id": "provider-sub-1", "label": "operator@example.com", "scopes": ["..."]}
        }
      ],
      "connection_status": {"connected": true, "account": {"id": "provider-sub-1", "label": "operator@example.com", "scopes": ["..."]}}
    }
  ]
}

The example above is illustrative; the fields are the same for every bundled tool. Each tool object has:

Field Meaning
tool_id Stable package identifier; keys config, credentials, approvals, and audit records.
display_name, description Operator-facing name and one-line summary from the manifest.
connection oauth (operator third-party auth), mcp_oauth (hosted MCP OAuth with one fixed default connection), enable_only (deployment key only), or whatsapp_linked_device (WhatsApp QR linking).
enabled Whether the operator has enabled the tool for agent calls.
reports_cost Tool-level boolean indicating whether tool code reports USD charges. False means untracked, not zero-priced.
actions[] Each action's stable id, description, per-action data_policy, approval (direct or operator), input_schema, input_protections, output_schema, returns_asset, and cost_description (string explaining that action's charges). input_protections maps each direct input name to {kind, description, allow_identifiers, allow_machine_tokens, allow_longer_text, identifiers_condition}; kind is validated (with a concise description) or parameter_guard (with the three boolean exception flags). identifiers_condition is null or decimal (the identifier exception applies only to all-digit values). It describes existing checks and does not configure execution. Approval actions return an empty map. Both schemas name every field and close every object (additionalProperties: false). output_schema is empty {} exactly for the actions that return no JSON result: an approval-gated one, which returns a user-visible message, and a returns_asset one, whose whole result is a file streamed into the agent workspace. A field the provider may not supply is declared as a oneOf union with {"type": "null"}.
config[] This tool's declared config keys with description and set. All config is secret and scoped per tool; values are never returned (see PUT /v1/tools/{tool_id}/config).
protections[] Short operator-facing safeguards rendered on the focused Home integration page.
setup_steps[] Ordered provider-side and Kern setup steps. A step may include a provider documentation link and a local audited screenshot with alt text; show_callback/show_config render this host's OAuth callback URI or the tool's config keys inside that step.
data_summary The operator-facing data story as exactly four cards, in order: what leaves this host, where it can go, what the third party can do with it, and how long it retains it. Each card has a description and/or labeled points, plus authoritative policy links.
connected_accounts OAuth tools only: every connected account as {"connection_id", "account": ConnectionAccount}. connection_id is an opaque host-generated slot identifier used by agent calls and OAuth lifecycle endpoints; it is not derived from an email or provider id. Never contains tokens or client secrets.
connection_status OAuth tools: transitional aggregate {"connected": bool, "account"?: ConnectionAccount} using the first connection. Linked-device tools: current supervised-session state and, only on the operator API, a pending QR data URL when linking.

ConnectionAccount is the explicit connected-account structure every OAuth tool returns and the host stores/displays: {"id", "label", "scopes"} — id is the stable provider account identifier (e.g. a Google sub) used to bind approvals to the connected account, label is the human-readable account (an email), and scopes are the granted OAuth scopes.

Approval record:

{
  "approval_id": "approval_7.Xr9K2unguessable-token",
  "tool_id": "gmail",
  "action_id": "send_email",
  "connection_id": "connection_0123456789abcdef01234567",
  "account_id": "provider-sub-1",
  "account_label": "operator@example.com",
  "status": "pending",
  "summary": "Send Gmail message to billing@example.com with subject \"Invoice\".",
  "payload": {"...": "the exact JSON the tool executes if approved"},
  "result": "",
  "created_at": 1782200000,
  "decided_at": 0
}
Field Type Value
approval_id string Host-assigned id approval_<number>.<token>: the sequential number plus an unguessable capability token, so the id itself is the agent's poll capability and a guessed number never resolves.
tool_id string The tool the approval belongs to.
action_id string The manifest action id (ActionSpec.id) the approval will execute.
connection_id string The host connection selected when the action was queued; empty for an enable-only tool.
account_id string The stable provider account id snapshotted when the action was queued. Empty for an enable-only tool or a retained approval created before multi-account support.
account_label string The provider account's display label snapshotted for the approval UI; empty in the same cases as account_id.
status string One of pending, approved, denied, expired, executed, failed. Terminal states are denied, expired, executed, failed.
summary string Redacted, operator-displayable description of the proposed action (1-500 UTF-8 bytes).
payload object The exact JSON the tool executes if approved (up to 64 KiB). Omitted from the list response; returned by GET /v1/tools/{tool_id}/approvals/{approval_id}.
result string The terminal outcome text: the executed action's user-visible ApprovalExecuted.message, or the failure error. Empty until executed or failed.
created_at integer Unix seconds when the approval was created.
decided_at integer Unix seconds when the approval reached a terminal state; 0 while pending.

Every approval is single-use, and pending approvals expire after 24 hours. New approval creation is capped while too many are already pending, so a runaway agent cannot grow admin storage without bound or hide older decisions from the operator. Agents queue approvals by calling approval-gated actions through the tools MCP surface; the pending call response carries the token-bearing approval_id, which check_tool_approval verifies before returning the summary or terminal result, so another agent process cannot enumerate old approvals by guessing sequential ids. Only these admin endpoints decide approvals.

Tool event summary (from /v1/tools/events):

{
  "seq": 412,
  "timestamp": "2026-07-08T01:15:00Z",
  "event_id": "tool_event_412",
  "tool_id": "example_tool",
  "action_id": "send_item",
  "connection_id": "connection_0123456789abcdef01234567",
  "account_id": "provider-sub-1",
  "account_label": "operator@example.com",
  "outcome": "executed",
  "detail": "approval_7",
  "has_arguments": true
}
Field Type Value
seq integer Monotonic event id, returned newest-first. Page older events by setting before to the oldest seq you have.
timestamp string ISO 8601 UTC time the event was recorded.
event_id string tool_event_<seq>.
tool_id string The tool the event concerns.
action_id string The manifest action id (ActionSpec.id) for a call; oauth_connect for a connect/disconnect, enablement for an enable/disable, or config for a config change.
connection_id string The selected host connection for an OAuth event; empty for enable-only tools and pre-profile audit history.
account_id, account_label string Non-secret provider identity snapshotted for the event; empty where no account identity was available.
outcome string For a tool call: executed, pending_approval, or failed. For an approval decision: executed, failed, or denied. For an OAuth connection change: connected or disconnected. For an enablement change: enabled or disabled. For a config change: set or cleared.
detail string Short context string: an error message, the related approval_id, the connected account label, or the config key that changed. May be empty.
has_arguments boolean true for an accepted tool call or approval decision, including calls whose exact argument object is {}. false for config, enablement, and connection lifecycle events.

GET /v1/tools/events/{seq} returns the same fields plus arguments, either the exact schema-validated tool input, the exact approved/denied payload, or null for a lifecycle event. Argument objects are capped at 64 KiB. They are stored in the local Postgres tool_events.arguments column. The tools service writes tool-call, approval, and OAuth events through its scoped database role; the admin service writes config and enablement events and reads the table for the Tool Audit Log. The UI loads arguments only after the operator expands an event. Tool config values and OAuth callback parameters are never stored as event arguments.

Public media capabilities

GET|HEAD /tool-media/{token}

Approved Instagram publishing can temporarily expose one staged media file on the configured public HTTPS hostname. This route uses a random 256-bit, process-local capability instead of an admin session. It is unavailable over the SSH-forward origin. Links expire within fifteen minutes and are revoked when the approved callback ends, the asset is deleted, or the tools service restarts. Existing downloads may finish after revocation. Single byte ranges are supported and responses prohibit caching. No App, filesystem path, or staging id is a public capability. See media handoff.

Database storage

GET /v1/database-storage is an authenticated operator-only, read-only snapshot. It accepts no query parameters and returns:

{"database_bytes": 4294967296, "tables": [{"name": "agent_events", "description": "Conversation messages and agent activity", "estimated_rows": 7500000, "total_bytes": 3221225472, "retention": "…", "row_target": 100000000}]}

Tables in the public schema are ordered by total size descending, then name. total_bytes includes indexes and TOAST (large stored values), including space PostgreSQL can reuse. database_bytes also includes database catalogs; it is not volume usage and excludes WAL, backups and external files. estimated_rows comes from pg_class.reltuples, last updated by PostgreSQL maintenance. It may be stale or null when no estimate is available. No table contents are scanned or returned. Each statement has a three-second timeout and a 500 ms lock timeout.

retention explains current deletion/replacement behavior. Unknown tables say that their policy is undocumented; they are not assumed to be retained forever. row_target is non-null only for whole-table history targets, never per-owner quotas or limits on subsets. Estimated percentages do not predict deletion: audit logs prune by sequence windows, gaps can leave fewer rows, and cleanup is batched. This endpoint neither changes retention nor reports past data loss. The Home panel loads only when opened or manually refreshed.

Host diagnostics

GET /v1/host-diagnostics
GET /v1/host-diagnostics/{id}
Method Path Request Response Behavior
GET /v1/host-diagnostics ?before=&limit=&service=&severity=&component= {"events": [...], "components": [...]} Lists host errors, warnings, and maintenance information newest first. before is the row's ordering seq, limit is 1–100, optional service selects one exact systemd service name, and optional severity accepts error, warning, or info, and optional component selects an exact component name (1–256 UTF-8 bytes). components lists distinct names across the entire retained log, independent of filters and pagination. List rows omit traceback, context, and fingerprint.
GET /v1/host-diagnostics/{id} none {"diagnostic": {...}} Loads the full bounded diagnostic record by its stable numeric id, including traceback, context, and fingerprint. Returns 404 when the row does not exist.

The API is display-only: there are no resolve, dismiss, delete, or report routes. Ordinary validation, user-decision, and network-policy outcomes do not belong in this log. Informational maintenance records use severity=info and kind=maintenance; Codex cleanup emits per-account start/completion summaries with counts, skip reasons, duration, and outcome in detail context. See Host diagnostics for best-effort capture, safety, and retention.

Host diagnostic list rows contain stable id and diagnostic_id fields, the rotating newest-first paging cursor seq, first_seen_at, last_seen_at, service, component, kind, severity, exception_type, summary, occurrence_count, host_version, boot_id, pid, and has_details. Detail reads additionally contain traceback, context, and fingerprint.

Host Runtime

POST /v1/host-runtime/reboot

Host runtime endpoints:

Method Path Request Response Behavior
POST /v1/host-runtime/reboot none Host runtime mutation response Reboots the host machine.

Host runtime mutation response:

{
  "status": "accepted"
}

Host runtime mutation response fields:

Field Type Values Meaning
status enum accepted Host runtime operation was accepted and will be applied asynchronously.

Token analytics

GET /v1/analytics is operator-only and accepts no query parameters. It returns since, until, seven UTC days, and groups aggregated by thread, selected runtime/model, measurement day, and UTC hour. Each group has thread_id, name, kind (chats, apps, or schedules), runtime, model, day, hour (an integer from 0 through 23), turns, tokens, measured_turns, and active. A Chat or App is active when it exists and is not archived; a schedule is active when its definition exists and is not deleted. A pruned schedule remains inactive. This flag describes current membership, not whether an agent is running. Both counter objects use input_tokens, cached_input_tokens, cache_write_tokens, and output_tokens.

tokens sums available values (null if none); measured_turns gives the number of turns contributing to each bucket. Fewer measured turns than turns means a partial total. The report contains no prompts or responses. See token analytics.

Tool usage

GET /v1/tools/usage

Requires the authenticated operator session. No request body or query parameters. Returns tool-reported USD charges for the current UTC calendar month. Amounts are decimal dollar strings.

Field Type Meaning
month_to_date decimal string Sum of reported amounts.
tools array Visible bundled tools, each with tool_id, display_name, enabled, and month_to_date (decimal string).

The overall total includes all recorded charges. Tool cards cover bundled integrations. The response includes tools with nonzero month-to-date spend and enabled tools that declare cost reporting. The endpoint sums UTC-day counters updated when a new charge row is inserted. Charge rows and daily counters retain action attribution for future reports. Repeated charge IDs do not change the original amount, attribution, or month. This endpoint does not contact providers or recalculate historical prices.

Auto-approval sleep settings

GET /v1/auto-approvals includes settings with sleep_start_minute and sleep_end_minute, as well as the current quiet flag and next_review_at. Both settings are whole minutes after midnight UTC (0–1439); defaults are 0 and 480 (00:00–08:00 UTC).

PUT /v1/auto-approvals/settings accepts exactly these two integer fields:

{"sleep_start_minute": 1320, "sleep_end_minute": 360}

This example sleeps from 22:00 through 06:00 UTC. The forward interval must be at least 360 minutes; equal times and shorter intervals return HTTP 400. Success returns {"saved": true} and wakes the scheduler to recompute its next review. Configuration is stored durably; an already running review may finish. Both routes require an operator session and are unavailable to agents.

Fixed GitHub push auto-approval

GET /v1/auto-approvals includes catalog action tool_id: "github", action_id: "push", with a display name and fixed_instructions. PUT /v1/auto-approvals/policy accepts that pair and the exact fixed text in instructions; altered text returns 400. DELETE with the same pair removes it. Both writes require the operator session. GitHub push reviews are independent of the tool sleep settings and next_review_at.

Shared history adds kind (tool or github_push). Push rows have a push-<id> approval identity and request containing push_id, ref_updates and changed_paths. Push status approved means the replay succeeded; outcome: "approved" only records the model decision. approval_error remains separate from both. Ordinary GitHub approval summaries include has_auto_policy and auto_review, as tool summaries do.

Connected browser controls

POST /v1/browser/{operation} accepts an object body, no query parameters, and requires the normal operator session and CSRF checks. Workspace principals cannot use these routes. Operations are list, create, check, open, frame, input, save, cancel, disconnect, network_get, network_save and network_test. Active-session operations require Browser to be enabled; listing, cancellation, disconnection and network configuration remain available when disabled. The admin service delegates over the browser service's peer-authenticated socket; browser errors become HTTP 409.

The browser interface reference describes operation inputs, lease rules, frames and account state.