# AGNT API Documentation This document provides comprehensive documentation for all API endpoints in the AGNT backend system. ## Workspace File Routes Base path: `/api/workspace-files` Hosted instances only. Bearer authentication and a current cloud workspace capability are required on every request. Team membership alone does not grant file access. | Method | Path | Capability | Behavior | |---|---|---|---| | GET | `/:teamId/:workspaceId/files` | `files.read` | List the teamspace's files (top level): `[{ name, bytes, modifiedAt }]`, newest first | | GET | `/:teamId/:workspaceId/content?path=` | `files.read` | Download a regular file as an attachment | | PUT | `/:teamId/:workspaceId/content?path=` | `files.write` | Write an `application/octet-stream` body, maximum 10 MiB | | DELETE | `/:teamId/:workspaceId/content?path=` | `files.write` | Delete a regular file: `{ deleted: true }`. Directories are refused (400) | Storage is private and partitioned by team, tenant and workspace. Absolute paths, traversal, links and drive-qualified paths are refused. These routes do not expose the desktop project directory. Missing files return 404; permission refusals return 403. This is distinct from approved execution permission. ## Local API (http://localhost:3333/api/) ## Table of Contents (Local) - [Authentication](#authentication) - [Closed Loop System (PRD-091)](#closed-loop-system-prd-091) - [Agent Routes](#agent-routes) - [Async Tool Routes](#async-tool-routes) - [Provider Auth Routes](#provider-auth-routes) - [Desktop Sign-In Routes](#desktop-sign-in-routes) - [Contract Routes](#contract-routes) - [Content Output Routes](#content-output-routes) - [Custom Provider Routes](#custom-provider-routes) - [Custom Tool Routes](#custom-tool-routes) - [Tenant Proxy Routes](#tenant-proxy-routes) - [AGNT Services Routes](#agnt-services-routes) - [Email Listener Routes](#email-listener-routes) - [Execution Routes](#execution-routes) - [Evolution / Insight Routes](#evolution--insight-routes) - [Experiment Routes](#experiment-routes) - [FileSystem Routes](#filesystem-routes) - [Workspace File Routes](#workspace-file-routes) - [Goal Routes](#goal-routes) - [Group Routes](#group-routes) - [Layout Routes](#layout-routes) - [Ledger Routes](#ledger-routes) - [Cluster Routes](#cluster-routes) - [Routing Routes](#routing-routes) - [MCP Routes](#mcp-routes) - [Browser Agent Routes](#browser-agent-routes) - [Memory Routes](#memory-routes) - [Local LLM Gateway Routes](#local-llm-gateway-routes) - [Model Routes](#model-routes) - [Mutation History Routes](#mutation-history-routes) - [NPM Routes](#npm-routes) - [Orchestrator Routes](#orchestrator-routes) - [Plugin Routes](#plugin-routes) - [Schedule Routes](#schedule-routes) - [Import Routes](#import-routes) - [Skill Routes](#skill-routes) - [Skill Discovery Routes](#skill-discovery-routes) - [SkillForge Routes](#skillforge-routes) - [Speech Routes](#speech-routes) - [Stream Routes](#stream-routes) - [Tool Schema Routes](#tool-schema-routes) - [Tools Routes](#tools-routes) - [User Routes](#user-routes) - [Wallet Routes](#wallet-routes) - [Webhook Routes](#webhook-routes) - [Widget Definition Routes](#widget-definition-routes) - [Workflow Routes](#workflow-routes) - [System Routes](#system-routes) - [Pairing Routes](#pairing-routes) - [Image Routes](#image-routes) - [Local File Routes](#local-file-routes) - [Conversation Settings Routes](#conversation-settings-routes) - [Admin Routes](#admin-routes) - [Artifacts](#artifacts) - [Team Routes](#team-routes) --- ## Authentication Most endpoints require authentication using JWT tokens. Include the token in the Authorization header: ``` Authorization: Bearer ``` The authentication middleware (`authenticateToken`) will: - Extract user information from the JWT token - Set `req.user` with user data including `id`, `email`, and `auth_type` - Store token and user data in session for backend operations - Continue as unauthenticated if no valid token is provided ### API keys (integrations) A sign-in token expires after 30 days and nothing refreshes it, so it is the wrong credential for a bot or script. Use an **AGNT API key** instead: create one under **Settings → API Key**, then send it exactly like a token: ``` Authorization: Bearer agnt_sk_<64 hex characters> ``` - A key does not expire. It stops working only when it is replaced or revoked. - One key per account. Generating a new key revokes the previous one; revoking leaves none. The key is shown once; api.agnt.gg stores only its SHA-256. - It works on a desktop install and on a hosted tenant. The backend cannot check a key locally, so it asks api.agnt.gg (`GET /users/auth/status`) and caches the answer for 5 minutes, the same path a tenant uses for tokens, including the membership check. A revoked key can therefore keep working here for up to 5 minutes. - A key is accepted wherever a sign-in token is, including the calls this backend makes to api.agnt.gg on your behalf. When no live sign-in token is held, background work (pollers, workflow nodes, provider credentials) uses the key; a live sign-in token always takes precedence. - A key cannot create another key. Creating and revoking keys requires the signed-in app. ### Hosted instances (AGNT Cloud) A desktop install verifies tokens locally with `JWT_SECRET`. A **hosted tenant** cannot: it holds a private random secret so the published key is not sitting on an internet-facing box, which means a genuine cloud token never verifies locally. With `AGNT_AUTH_MODE=verify-remote` it asks `api.agnt.gg` instead. That introduces a second question. "Is this token genuine?" is true for **every** account the issuer has ever created, and signup is open — so a genuine token is not permission to use *this* machine. Three environment variables decide: | Variable | Meaning | | -------- | ------- | | `AGNT_TENANT_SLUG` | Set only by `tenant.sh`. Its presence is what makes this a hosted instance. | | `AGNT_TENANT_OWNER` | The account that owns it. Always a member. | | `AGNT_TENANT_MEMBERS` | Comma-separated allow-list. Membership from the first line, not owner-equality, because Business Cloud sells seats. | **The slug decides the mode, not the member list.** No slug means a desktop install and no check at all, so every existing install is unaffected. A slug with no members **refuses to boot** (exit `78`) rather than admitting everyone or locking out its owner — both of those fail silently. Live membership comes from `GET /users/auth/status?tenant=`, on the call the backend already makes for every token. When the issuer answers, that answer decides; when it cannot, the env list is the **floor**, never a ceiling silence can raise. #### Responses a hosted instance can return | Status | Reason | Meaning | Client action | | ------ | ------ | ------- | ------------- | | `401` | — | No token, or a forged one. Unchanged from desktop. | Re-authenticate | | `403` | `not_tenant_member` | Genuine account, wrong instance. | Show "this instance belongs to another account". **Do not clear the token** — it is valid for the cloud and for their own instance. | | `402` | — | Subscription lapsed. Served by the fleet proxy; the container is stopped. | Update billing | | `429` | — | Daily runtime budget spent. Carries `Retry-After` with the seconds until reset (UTC midnight). | Back off until the reset, or upgrade to Always-On | `402` and `429` come from the fleet layer rather than the app — the container is not running when they are returned. A request cannot buy more runtime. #### Waking a sleeping instance On the Personal Cloud plan a tenant stops after 15 minutes idle. The next request is caught by the proxy and handed to a waker **with its method, path, headers and body intact**; the waker starts the container, waits for it, and forwards the original request. Cold path is about 6–8 seconds and the caller gets their real response — no splash page, and a webhook POST is never dropped. The fleet also wakes a sleeping tenant when its own cron is due, or when events are queued at the control plane. `SchedulerService` ticks in-process, so a stopped tenant would otherwise never fire a schedule. ### Token Storage & Access The JWT token is **not stored in the database**. It lives in three places depending on context: | Context | Where the token lives | How to access it | | ------------------------------------ | ------------------------------------------------------ | ------------------------------------------------ | | Widgets (iframe) | Never enters the iframe | Use the global `agnt` SDK (auth is proxied) | | Frontend (Vue app, browser) | `localStorage` | `localStorage.getItem('token')` (legacy callsites) | | Backend services (Express) | `req.headers.authorization` or `req.session.userToken` | Passed as `authToken` parameter between services | | Orchestrator tools (spawned Node.js) | `process.env.AGNT_AUTH_TOKEN` | Automatically injected by the orchestrator | ### Widgets (browser iframe — use the agnt SDK) The widget runtime injects a global `agnt` object into every widget iframe at mount time. **The token never enters the iframe** — every call is proxied through the parent via `postMessage` and executed by the parent's authenticated axios instance. Widget code should NOT read `localStorage`, NOT set `Authorization` headers, NOT write a `getToken()` helper. Bypassing the SDK will 401. ```js // Plugin / native / registry tool execution (most common widget use case) const joke = await agnt.tool('chucknorris-get-joke', { category: 'dev' }); // Any /api/* endpoint const agents = await agnt.fetch('/api/agents'); const created = await agnt.fetch('/api/agents', { method: 'POST', body: { name: 'My Agent' }, // object or JSON.stringify(...) both work }); // User context, available synchronously console.log(agnt.user); // { id, email, name } | null ``` `agnt.tool` returns the tool's `result` directly (not the `{ success, result }` envelope) and throws on tool failure. `agnt.fetch` returns the parsed response body and throws on non-2xx. `agnt.fetch` is allowlisted to `/api/*` paths and to standard HTTP methods (GET/POST/PUT/PATCH/DELETE). ### Frontend Vue app (browser, non-widget context) The Vue app stores the JWT in `localStorage` under the key `token` and a global axios interceptor in `frontend/src/main.js` attaches `Authorization: Bearer ...` to every outbound request automatically. New code should use the existing axios setup; reach for `localStorage.getItem('token')` only when bypassing axios. ```js // Most code — interceptor handles auth automatically import axios from 'axios'; const { data } = await axios.get('/api/agents'); // Bypass case (raw fetch outside axios): const token = localStorage.getItem('token'); const res = await fetch('/api/agents', { headers: { Authorization: `Bearer ${token}` } }); ``` ### Backend Services (Express context) Inside Express route handlers and services, the token arrives via the request header and is cached in the session by the `authenticateToken` middleware: ```js // In a route handler — token from the request const authToken = req.headers.authorization; // "Bearer " // Or from session (set automatically by middleware after first auth) const sessionData = getUserTokenFromSession(req); // sessionData = { token: "", user: { id, email, auth_type } } // Services receive it as a parameter — just pass it along const result = await someService.doWork(args, authToken); ``` ### Orchestrator Tools (spawned Node.js context) When the orchestrator's `execute_javascript_code` tool runs code, it spawns an isolated Node.js process. There is no `req`, no session, and no `localStorage`. The orchestrator automatically injects the user's token as an environment variable: ```js const API = 'http://localhost:3333/api'; const TOKEN = process.env.AGNT_AUTH_TOKEN; // automatically provided const res = await fetch(API + '/agents/', { headers: { Authorization: 'Bearer ' + TOKEN, 'Content-Type': 'application/json', }, }); const data = await res.json(); console.log(JSON.stringify(data, null, 2)); ``` > **Important:** Each context has its own way to get the token — don't mix them. `localStorage` only exists in the browser. `req.session` only exists in Express handlers. `process.env.AGNT_AUTH_TOKEN` only exists in orchestrator-spawned processes. --- ### List Connected Providers **GET** `/api/auth/connected` - **Authentication**: Optional — env-sourced providers are install-global and return even for unauthenticated callers; per-user rows are included when a bearer token resolves a userId - **Description**: List OAuth/API-key providers currently connected. Shape mirrors the remote `/auth/connected` response so the frontend can merge both sources without normalization. - **Response**: ```json [ { "providerId": "openai", "connected": true } ] ``` ### Notify Provider Changed **POST** `/api/auth/providers/notify-changed` - **Authentication**: None - **Description**: The UI posts provider CRUD to the cloud API directly, so the local backend never sees the write. This endpoint lets a client tell the local backend "a provider changed" so every connected tab refreshes via Socket.IO. - **Body**: ```json { "event": "created | updated | deleted", "providerId": "openai" } ``` - **Response**: `{ "success": true }` — `400` if `event` is not one of the three valid values --- ## Closed Loop System (PRD-091) AGNT runs a self-improvement loop across four primitives that together let goals fire on a cadence, mutations prove themselves before promoting, safe insights auto-apply, contracts enforce runtime invariants, and regressions auto-revert. **This section is required reading for any agent that touches scheduling, auto-apply, budgets, or revert.** ### The four primitives | Primitive | Base path | What it stores | Layer | |---|---|---|---| | **Schedules** | `/api/schedules` | Durable cron entries (target + cron + next_run). Survives backend restart. | 1 (Clock) | | **Wallets** | `/api/wallets` | Linear capability budgets (root + sub-wallets). Sub-wallets can never exceed parent balance. | 3 (Budgets) | | **Contracts** | `/api/contracts` | Runtime invariants mined from successful executions ("output must be JSON", "step count ≤ 5"). | 5 (Invariants) | | **Mutation History** | `/api/mutations` | Every router-applied change, with before-snapshot + fitness baseline. | 7 (Provenance) | Plus the **Autonomy Router** at `POST /api/insights/route` which decides per pending insight whether to **direct-apply**, **gate via sandbox**, **escalate to the user**, or **skip**. Driven by `EvolutionSettingsModel.autonomy` (off by default). ### When to use which endpoint (intent → call) | User says... | Call | |---|---| | "Run this goal every morning at 9 ET" | `POST /api/schedules` with `targetType:'goal'`, `cron:'0 9 * * *'`, `timezone:'America/New_York'` | | "When will my schedule fire next?" | `POST /api/schedules/preview` (no persist) — or `GET /api/schedules/:id` and read `next_run` | | "Show me what AGNT auto-changed lately" | `GET /api/mutations` | | "Did that auto-change regress quality?" | `POST /api/mutations/:id/canary-check` | | "Undo that auto-applied change" | `POST /api/mutations/:id/revert` | | "Turn on autonomy" | `POST /api/insights/settings` with `{ autonomy: { enabled: true } }` | | "Apply all my safe pending insights" | `POST /api/insights/route` (sweeps every pending insight through the router) | | "Route just this one insight" | `POST /api/insights/:id/route` | | "What's my budget?" | `GET /api/wallets/root` | | "Add credit to my budget" | `POST /api/wallets/root/topup` | | "Spin up a sub-budget for this agent" | (server-side) `WalletService.allocate(...)` — no public route yet | | "Show this agent's spend ledger" | `GET /api/wallets/:id/ledger` | | "Does this output satisfy our quality contracts?" | `POST /api/contracts/check` | | "Show me what rules have been mined" | `GET /api/contracts` | ### Safety contract (the agent MUST respect this) 1. **Never** flip `autonomy.enabled` on the user's behalf without explicit, in-conversation confirmation. It is off by default for a reason. 2. **Never** call `POST /api/insights/:id/apply` on insights with `priority: 'critical'` or `category: 'parameter_tune' | 'bottleneck'` without explicit confirmation. 3. **Always** call `POST /api/mutations/:id/canary-check` before suggesting `revert`. Show the user the verdict (`regression: true|false`, `delta`, `fitnessAfter`). 4. **Always** call `GET /api/wallets/root` before scheduling a recurring goal that will incur LLM cost — confirm there is budget. 5. **Default to escalation, not direct-apply.** When in doubt, use `POST /api/insights/route` (which respects the router) rather than `POST /api/insights/:id/apply` (which bypasses it). ### Layered guarantees the safety contract relies on - The router itself returns `{ decision: 'escalate', reason: 'autonomy_disabled' }` for every insight when `autonomy.enabled === false`. Flipping `enabled` is the *only* way auto-apply turns on. - Every router-applied mutation captures `fitness_before` at apply time. Revert is non-lossy because the before-snapshot lives in `mutation_history`. - `VerifierGate` enforces `delta > MIN_DELTA (0.05)` AND structural-constraint gates before promote. A regression cannot pass the gate. - Wallets cap blast radius — even if autonomy is on AND all gates pass, a tool with a depleted wallet cannot keep spending. ### Default policy values (live in `AutonomyPolicy.DEFAULTS`) ```json { "enabled": false, "minConfidence": 0.7, "minDelta": 0.05, "maxBlastRadius": 0.5, "dailyBudget": 20, "allowedCategories": [ "memory", "prompt_refinement", "tool_preference", "contract_proposal", "skill_recommendation", "pattern", "antipattern" ], "requireGateAbove": 0.45 } ``` Insight with `blast_radius >= requireGateAbove` is routed `gated` (sandbox-tested) instead of `direct`. Insight with `blast_radius > maxBlastRadius` is `escalate`d (human required). ### Realtime events the frontend listens for | Event | When it fires | |---|---| | `autonomy.router.decision` | Router emits a decision per insight | | `autonomy.mutation.applied` | A mutation lands in `mutation_history` | | `autonomy.canary.regression` | Periodic canary sweep detects a regression | | `scheduler.tick` | Scheduler tick fires a schedule | | `scheduler.run.complete` | A scheduled run finishes | (Implemented in `frontend/src/composables/useRealtimeSync.js`.) --- ## Agent Routes Base path: `/api/agents` ### Health Check **GET** `/health` - **Authentication**: None - **Description**: Check if the agent service is running - **Response**: ```json { "status": "OK" } ``` ### Get All Agents **GET** `/` - **Authentication**: Required - **Description**: Retrieve all agents for the authenticated user- **Note**: Include trailing slash (`/api/agents/`) for best compatibility - **Response**: ```json { "agents": [ { "id": "67b9bf15-a5c7-4153-936b-5959dc83b03c", "name": "Content Manager", "description": "Main content manager", "status": "active", "icon": "data:image/png;base64,...", "category": "Content & Media", "provider": "openai", "model": "gpt-4o", "assignedTools": ["web_search"], "assignedWorkflows": [], "systemPrompt": "Persona / directives text", "assignedSkills": [], "toolAccessMode": "restricted", "resourceId": 1, "creditsUsed": 0, "creditLimit": 1000, "workflows": 0, "lastActive": null, "successRate": null } ] } ``` **Important**: The response wraps agents in an `agents` array property, not a direct array. `icon` can be a large base64 data URL — use `GET /summary` for lightweight lists. ### Get All Agents (Summary) **GET** `/summary` - **Authentication**: Required - **Description**: Lightweight agent list. Drops the three biggest per-row payload contributors (base64 `icon`, `systemPrompt`, and the tools/workflows/skills arrays) and returns counts instead. Use for rendering agent cards; hit `GET /:id` when you need the full record. - **Response**: ```json { "agents": [ { "id": "67b9bf15-a5c7-4153-936b-5959dc83b03c", "name": "Content Manager", "description": "Main content manager", "status": "active", "category": "Content & Media", "provider": "openai", "model": "gpt-4o", "toolCount": 3, "skillCount": 1, "workflows": 0, "creditsUsed": 0, "creditLimit": 1000, "lastActive": null, "successRate": null, "createdAt": "2026-01-01T00:00:00Z", "updatedAt": "2026-01-01T00:00:00Z" } ] } ``` ### Save/Update Agent **POST** `/save` - **Authentication**: Required - **Description**: Create a new agent or update an existing one - **Body**: the agent wrapped in `agent`: ```json { "agent": { "id": "optional-agent-id", "name": "Agent Name", "description": "Agent description", "status": "ACTIVE", "systemPrompt": "Optional persona / directives", "assignedTools": ["web_search", "web_scrape"], "assignedSkills": ["skill-id-or-slug"], "toolAccessMode": "restricted" } } ``` - `name` is required for a new agent; an edit that omits it keeps the stored name. `status` defaults to `"ACTIVE"` (an edit keeps the stored status). `assignedTools`/`assignedWorkflows` default to `[]`. - **Errors**: `400` when the body is not `{ agent: { ... } }`, when a new agent has no `name`, or (on `PUT /:id`) when `agent.id` differs from the URL. **`toolAccessMode`** (string, `"restricted"` | `"open"`, default `"restricted"`) controls the agent's runtime tool surface in chat: | Mode | Tool surface | |---|---| | `restricted` (default) | `assignedTools` are the ceiling. The agent sees only its assigned tools plus a baseline (web_search, skill activation via `activate_skill`, memory read/write via `recall`/`save_agent_memory`/`get_agent_memories`, `discover_tools`) and universal primitives. | | `open` | Full main-chat dynamic tool surface (default tools + keyword-triggered groups + persistent `discover_tools` loads), with `assignedTools` pinned always-on regardless of keyword matching. | Any value other than `"open"` is sanitized to `"restricted"` on save. In both modes the agent's system prompt is built by the unified prompt builder: persona-first, full skills catalog with the agent's `assignedSkills` highlighted as specialty skills, and persistent agent-scoped memory.- **Response** (`200`): ```json { "message": "New agent created", "agentId": "agent-id" } ``` `message` is `"New agent created"` or `"Agent updated"`. If `id` is omitted (or belongs to another user's agent), a new agent is created with a fresh UUID. New agents inherit the user's selected provider/model when `provider`/`model` are not supplied; if neither the body nor user settings yield a provider+model the request fails with `400`. ### Get Agent by ID **GET** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Agent ID- **Description**: Retrieve a specific agent by ID (full record, owner only — `403` otherwise, `404` if not found) - **Response**: ```json { "id": "agent-id", "name": "Agent Name", "description": "Agent description", "status": "active", "icon": "data:image/png;base64,...", "category": "Content & Media", "provider": "openai", "model": "gpt-4o", "systemPrompt": "Persona / directives text", "assignedTools": ["web_search"], "assignedWorkflows": [], "assignedSkills": [], "toolAccessMode": "restricted", "created_by": "user-id", "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z" } ``` Note: this endpoint returns the raw DB row plus parsed arrays — timestamps are snake_case (`created_at`), unlike the camelCase list endpoints. ### Update Agent **PUT** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Agent ID - **Description**: Same handler as `POST /save`: the same `{ agent: { ... } }` body (name, description, systemPrompt, assignedTools, assignedSkills, assignedWorkflows, toolAccessMode, provider, model, icon, category, status, creditLimit) and the same response. The agent saved is the one in the URL; `agent.id` may be omitted: ```json { "message": "Agent updated", "agentId": "agent-id" } ``` ### Delete Agent **DELETE** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Agent ID - **Description**: Delete an agent by ID. Also deletes the agent's memories and broadcasts `AGENT_DELETED` to the user's connected clients. In a teamspace: an owner/admin, or the member who created the agent; otherwise `403`. - **Response**: ```json { "message": "Agent deleted successfully." } ``` ### Chat with Agent **POST** `/:id/chat` - **Authentication**: Required - **Parameters**: - `id` (path): Agent ID- **Note**: Agent chats run through the same unified orchestrator as the main chat — persona-first system prompt, full skills catalog (assigned skills highlighted), persistent agent-scoped memory, and the tool surface determined by the agent's `toolAccessMode` (see Save/Update Agent). External bridges (Discord, Mattermost, etc.) get identical behavior through this endpoint. - **Body**: ```json { "message": "Your message here", "history": [{ "role": "user", "content": "earlier turn" }], "conversationId": "optional-stable-conversation-key", "provider": "optional-override", "model": "optional-override", "enabledTools": ["web_search"] } ``` All fields except `message` are optional. The agent's saved provider/model always wins over `provider`/`model` in the body (then the user's selected settings); to pin a pair for one call, use `runtime.model.override`. `conversationId` keys persistent conversation history. `enabledTools` narrows (never widens) the agent's tool surface. - **Response**: Server-sent events stream (same event vocabulary as [Universal Chat](#universal-chat) — `conversation_started`, `content_delta`, `tool_start`/`tool_end`, `final_content`, `done`, …). There is no JSON response mode. #### Runtime options (`runtime`) By default an agent call runs the full chat-app turn: the platform system prompt (~10–12K tokens of rendering rules, skills catalog, memory, the user's custom instructions), the agent's tools, a conversation log, cross-tab broadcasts (which make the open app adopt and **save the run as a conversation**) and a post-turn insight pass. A programmatic caller sends `runtime` to load and write only what it needs. ```json { "message": "STATE t=42s …", "runtime": { "profile": "realtime", "prompt": { "append": "Reply ONLY with JSON Lines." }, "model": { "provider": "groq", "model": "openai/gpt-oss-120b", "override": true }, "limits": { "maxInputTokens": 2000, "timeoutMs": 8000 } } } ``` **Profiles** — a preset; any field below can then be overridden individually. | Profile | Prompt | Tools | Writes | Broadcast | Failover | Stream | Use for | |---|---|---|---|---|---|---|---| | `ui` (default) | full | agent's | everything | yes | chain | all events | the chat app — identical to sending no `runtime` | | `api` | lean, no memory / skills / custom instructions | agent's | none | no | chain | all events | scripts, webhooks, integrations | | `background` | lean, with memory / skills / custom instructions | agent's | conversation log, state, insights | no | chain | all events | cron, batch jobs, agent-to-agent delegation | | `realtime` | persona only | none | none | no | none | minimal + `line` | games, voice loops, classifiers | **Fields** | Field | Values | Meaning | |---|---|---| | `profile` | `ui` \| `api` \| `background` \| `realtime` | Preset (default `ui`). | | `prompt.platform` | `full` \| `lean` \| `none` | `full` = today's prompt. `lean` = tool and execution rules without chat-window blocks (artifacts, inline HTML, file embeds, chart guide). `none` = the agent's identity and instructions only. | | `prompt.memory`, `prompt.skills`, `prompt.customInstructions`, `prompt.workspace` | boolean | Include that section. A section that is off is not looked up at all. | | `prompt.append` | string (≤ 20,000 chars) | Caller contract appended at the end of the system prompt (output format, schema). | | `tools` | `agent` \| `none` \| `["name", …]` | A list **narrows** the agent's surface; naming a tool the agent is not allowed grants nothing. `[]` = `none`. | | `persist.conversationLog` | boolean | Write `conversation_logs` (the model's own history). | | `persist.transcript` | boolean | Mirror the turn into the saved conversation row. | | `persist.conversationState` | boolean | Keep the turn's state for async-tool follow-ups and prompt-cache restore. Off = async tool results cannot post back. | | `persist.insights` | boolean | Run post-turn insight extraction (a second model call). | | `broadcast` | boolean | Announce the run and mirror its events to the user's other clients. Only the `ui` profile can broadcast. | | `model.provider`, `model.model`, `model.override` | strings, boolean | With `override: true` (both names required), this call uses that pair instead of the agent's. | | `model.fallback` | `chain` \| `none` | `none` = no failover: a provider failure arrives as an `error` event (`recoverable: false`) instead of being answered by another model. | | `stream.events` | `all` \| `minimal` | `minimal` = `conversation_started`, `agent_execution_started`, `content_delta`, `line`, `final_content`, `error`, `provider_fallback`, `agent_execution_completed`, `done`. | | `stream.lines` | boolean | Emit `event: line` / `data: {"text", "index"}` for each complete line of the answer the moment its newline arrives (JSON-Lines callers can act on line 1 while line 2 is generating). | | `limits.maxInputTokens` | integer \| null | Refuse the call (an `error` event, nothing sent to the provider) if the request would exceed it. | | `limits.timeoutMs` | integer ≤ 600000 \| null | Abort the turn after this long. | | `limits.maxToolRounds` | integer 0–100 \| null | Cap tool rounds (never raises the configured cap). | | `limits.cancelOnDisconnect` | boolean | Abort generation when the caller closes the stream. (Normally a run outlives its socket so the app can reattach; a non-broadcast caller is never reattached.) | **Guarantees.** No `runtime` behaves exactly as before. Unknown keys and invalid values are a `400`, never a silent fallback to the expensive default. Every call still writes its execution trace, which records the provider/model that actually **served** the turn. A non-`ui` profile never rewrites the account's default provider. `runtime` is accepted on `/:id/chat` and `/:id/chat-stream` only. **Scenarios** | Scenario | Send | |---|---| | Game or voice brain | `{ "profile": "realtime", "prompt": { "append": "" } }` | | Same prompt across several models (benchmark) | `realtime` + `model: { provider, model, override: true }`, failover stays `none` | | Webhook / Zapier one-shot | `{ "profile": "api" }` | | Classification / extraction to a schema | `{ "profile": "realtime", "prompt": { "append": "" } }` | | Voice assistant that can search | `{ "profile": "realtime", "tools": ["web_search"], "prompt": { "platform": "lean" } }` | | Nightly report, delegated agent turn | `{ "profile": "background" }` | | Embedded widget chat with its own history | `{ "profile": "api", "persist": { "conversationLog": true, "conversationState": true } }` + a stable `conversationId` | ### Stream Chat with Agent **POST** `/:id/chat-stream` - **Authentication**: Required - **Parameters**: - `id` (path): Agent ID - **Description**: Identical to `POST /:id/chat` (both routes call the same universal handler and both stream). Kept for backward compatibility. - **Response**: Server-sent events stream ### Get Agent Suggestions **POST** `/:id/suggestions` - **Authentication**: Required - **Parameters**: - `id` (path): Agent ID - **Body**: ```json { "lastUserMessage": "the user's last message", "lastAssistantMessage": "the agent's last reply", "history": [] } ``` `provider`/`model` are auto-filled from the agent's saved config; the agent's persona and assigned-tool list are injected into the suggestion prompt. - **Response** (JSON, not a stream): ```json { "suggestions": [ { "id": "suggestion_1", "text": "Draft the outline", "icon": "\ud83d\udcdd" }, { "id": "suggestion_2", "text": "Search for sources", "icon": "\ud83d\udd0d" }, { "id": "suggestion_3", "text": "Summarize so far", "icon": "\ud83d\udccb" } ] } ``` On LLM failure the endpoint still returns `200` with three generic fallback suggestions plus an `error` field. ### Export Agent **GET** `/:id/export` - **Authentication**: Required (owner only — `403` otherwise) - **Parameters**: - `id` (path): Agent ID - **Description**: Export a portable agent envelope (persona, provider/model, assigned tools/skills/workflows by name/id — no memories, no credentials). - **Response**: ```json { "_format": "agnt-agent", "_version": 1, "payload": { "name": "Agent Name", "description": "...", "icon": null, "provider": "openai", "model": "gpt-4o", "systemPrompt": "...", "category": "", "status": "ACTIVE", "creditLimit": 1000, "assignedTools": ["web_search"], "assignedSkills": [], "assignedWorkflows": [] }, "exported_at": "2026-01-01T00:00:00Z" } ``` ### Import Agent **POST** `/import` - **Authentication**: Required - **Body**: An export envelope (either the envelope itself or wrapped as `{ "envelope": { ... } }`) - **Response** (`201`): ```json { "success": true, "agentId": "new-agent-id", "missingRefs": { "tools": [], "skills": [], "workflows": [] } } ``` `missingRefs` lists referenced tools/skills/workflows that don't exist in this installation (the agent is still created). Malformed envelopes return `400`. --- ## Async Tool Routes Base path: `/api/async-tools` > ## \u26A0\uFE0F Critical Behaviour Notes (read before integrating) > > These behaviours were discovered during empirical stress-testing on 2026-05-04. Most of the silent-degradation cases were fixed in the same dated commit \u2014 see [`ASYNC-TOOLS-REFERENCE.md` \u00A7 Recent Fixes](./ASYNC-TOOLS-REFERENCE.md#recent-fixes-2026-05-04) for the fix table. > > **\ud83d\udd34 In-batch ordering is NOT guaranteed.** When multiple async tool calls are submitted in the same function-calls block, the orchestrator fires them all in the **same millisecond** with no ordering. Submitting a `write` followed by a `read` of the same path can produce a read failure (`ENOENT`) 2+ seconds *before* the write completes. This is by design \u2014 async tools are independent and unordered. **Use synchronous calls for any read-after-write or dependent operation.** Non-LLM integrators (workflow nodes, webhook handlers, third-party callers) must enforce ordering themselves: await the queued result before issuing the next dependent call. > > **\u2705 Silent-degradation parameter patterns FIXED (2026-05-04).** The four shapes below used to silently fall back to a one-shot. They now return a structured validation error at queue time so callers can self-correct: > 1. `_interval: 0` (or negative / non-numeric) \u2014 rejected. > 2. `_stopAfter: N` without `_interval` \u2014 rejected. > 3. `_duration: N` without `_interval` \u2014 rejected. > 4. `_delayFirst: true` without `_interval` \u2014 rejected. > > **\u2705 Failure observability FIXED (2026-05-04).** The `GET /api/async-tools/status` endpoint now reports three failure-related counters: > - `failed` \u2014 system-level failures only (worker crashed/aborted). Same semantics as before. > - `businessFailed` \u2014 completed executions whose inner `result.success === false` (ENOENT, EPERM, per-iteration errors in periodic runs). > - `totalFailed` \u2014 `failed + businessFailed`, exact (the source sets are disjoint). > > **\u2705 Autonomous-message banner FIXED (2026-05-04).** The wrapper that delivers async results into the conversation now inspects the inner result and emits `\u26A0\uFE0F ASYNC TOOL FINISHED WITH ERROR` with an honesty directive when the operation reported failure, instead of always claiming success. > > **\u2705 Sub-second intervals work** (validated down to `_interval: 0.1`), but at intervals shorter than the tool\u2019s own execution time the actual gap is dominated by tool throughput, not the timer. Note: `_interval: 0` is no longer accepted (see fix above). > > **\u2705 True OS-level concurrency is real** \u2014 five parallel `ping` shells took 5.2 s total instead of 21 s. > > **\u26a0\ufe0f Whole feature is experimental and OFF by default (2026-05-04).** A per-user setting (`asyncToolsEnabled` on `PUT /api/users/settings`) gates whether the LLM can use async tools at all. With it OFF (default), the universal async control params drop off every tool schema AND the async-guidance prompt section is omitted, so the LLM has no way to know async exists. In-flight tasks that started before the toggle flipped run to completion. New users see the chat behave like a conventional sync-only assistant until they explicitly enable the feature in Settings. See [`ASYNC-TOOLS-REFERENCE.md` \u00a7 Async tools toggle](./ASYNC-TOOLS-REFERENCE.md#async-tools-toggle-per-user-setting-2026-05-04) for the full contract. ### Tool-Call Async Parameters (How to Use Async) Every tool in the AGNT registry — native, plugin, registry, MCP — supports background and recurring execution via a set of universal **underscore-prefixed parameters**. These are **not** part of the tool's own schema; they are intercepted by the orchestrator before the tool runs. > 📘 **For the comprehensive guide with worked examples, error handling patterns, edge cases, and empirically-validated test results, see [`ASYNC-TOOLS-REFERENCE.md`](./ASYNC-TOOLS-REFERENCE.md).** #### Universal Async Parameters | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `_executeAsync` | boolean | `false` | Run the tool in the background. Returns an `executionId` immediately; results arrive later via autonomous message. | | `_interval` | integer (seconds) | — | Re-run the tool every N seconds. Requires `_executeAsync`. | | `_stopAfter` | integer | — | Stop after N iterations. Requires `_interval`. | | `_duration` | number (minutes) | — | Stop after N minutes total. Decimals allowed (e.g. `0.1` = 6 seconds). Requires `_interval`. | | `_delayFirst` | boolean | `false` | Skip the immediate first run — wait one full `_interval` before the first execution. Requires `_interval`. | | `_estimatedMinutes` | number | — | UI hint for expected duration. **No functional impact** on scheduling — purely cosmetic. | #### Common Patterns **Run once in the background:** ```json { "query": "latest AI news", "_executeAsync": true } ``` **Run a real tool once after a delay (e.g. send a reminder email in 1 hour):** ```json { "to": "user@example.com", "subject": "Reminder", "body": "Don't forget!", "_executeAsync": true, "_interval": 3600, "_stopAfter": 1, "_delayFirst": true } ``` **Run every 60 seconds, exactly 5 times:** ```json { "...": "...", "_executeAsync": true, "_interval": 60, "_stopAfter": 5 } ``` **Scrape a site every 5 minutes for 1 hour:** ```json { "url": "https://example.com", "_executeAsync": true, "_interval": 300, "_duration": 60 } ``` **Safety-belt pattern (stop at whichever limit hits first):** ```json { "...": "...", "_executeAsync": true, "_interval": 60, "_stopAfter": 100, "_duration": 60 } ``` #### Response Shapes **Sync (no async params)** — returns the tool's native payload directly: ```json { "success": true, "total": 20, "individualRolls": [20], "error": null } ``` **Async, queued** — returned immediately when `_executeAsync: true`: ```json { "success": true, "status": "queued", "executionId": "8604c5b0-8515-4cb1-8894-918acb31ac25", "message": " started in the background. You'll receive updates as it progresses.", "estimatedDuration": null } ``` **Async, completed (one-shot)** — arrives via autonomous message: ```json { "success": true, "status": "completed", "executionId": "8604c5b0-8515-4cb1-8894-918acb31ac25", "result": "{\"success\":true,\"total\":20,...}", "duration": 480 } ``` > The `result` field is often a **JSON-stringified payload**. Clients must `JSON.parse()` it before consuming. **Periodic execution completed** — a single combined payload after the full schedule finishes: ```json { "success": true, "status": "completed", "executionId": "af4cd05e-0c19-4e3b-96fb-fc38c57d81bc", "result": { "periodicExecution": true, "totalIterations": 3, "results": [ { "iteration": 1, "result": "{...}", "timestamp": 1777909033895 }, { "iteration": 2, "result": "{...}", "timestamp": 1777909043897 }, { "iteration": 3, "result": "{...}", "timestamp": 1777909053906 } ], "totalDuration": 20011 }, "duration": 20011 } ``` #### Two-Layer Status Model (Critical) Async responses have **two independent layers** that must both be checked: 1. **System layer** — the outer envelope (`success`, `status`). Tells you whether the orchestrator queued/ran the task. 2. **Business-logic layer** — `result.success` or the parsed payload. Tells you whether the tool's operation actually succeeded. A task can be `status: "completed"` at the system level while `result.success: false` at the business layer (e.g. file not found, invalid parameter, API error). ```javascript if (response.status === "completed") { const inner = typeof response.result === "string" ? JSON.parse(response.result) : response.result; if (inner.success) { // use inner data } else { // handle inner.error (e.g. ENOENT, EPERM, validation message) } } ``` #### Empirically-Verified Behaviors These behaviors were validated via live tool calls (see `ASYNC-TOOLS-REFERENCE.md` for the full test log): - **Validation runs at execution time, not queue time.** Invalid parameters are queued successfully and only fail when the task actually runs. - **Conflicting stop conditions:** when both `_stopAfter` and `_duration` are set, **whichever limit triggers first wins**. Tested with `_stopAfter: 100` + `_duration: 0.1` (6 s) — task stopped at 3 iterations. - **Parallel concurrency:** 19+ simultaneous async calls in a single function-calls block all queue and execute cleanly. No rate limit observed. - **Mixed sync + async** in the same function-calls block works — sync results return inline, async return execution IDs. - **Periodic results are batched.** A periodic task delivers **no output** until the full schedule completes. Use separate async calls (one per assistant message) if streaming is required. - **`_estimatedMinutes` is purely cosmetic.** Tasks run as fast as they can regardless of the estimate. - **Minimum interval** tested: 1 second (with ~10–20 ms drift per iteration). Sub-second intervals untested. - **Decimal `_duration`** values work (e.g. `0.1` = 6 seconds). - **Error envelope:** business-logic failures (`ENOENT`, `EPERM`, validation errors) surface inside `result.error` while the outer `status` remains `"completed"`. The system never crashes or hangs on bad input. #### Anti-Patterns ❌ **Do not** use async for dependent tasks. If Task B references Task A's output, Task A must be sync. ❌ **Do not** build a fake `sleep` / `echo` / `timer` tool to schedule something later. Attach `_executeAsync`, `_interval`, `_stopAfter: 1`, `_delayFirst: true` directly to the **real tool you want to run**. ❌ **Do not** start a periodic task without `_stopAfter` or `_duration`. It will run until cancelled via `POST /cancel/:executionId`. --- ### Get Queue Status **GET** `/status` - **Authentication**: Required - **Description**: Get async tool queue statistics - **Response**: ```json { "success": true, "stats": { "pending": 0, "running": 2, "completed": 15, "failed": 1 } } ``` ### Get Executions by Conversation **GET** `/executions/:conversationId` - **Authentication**: Required - **Parameters**: - `conversationId` (path): Conversation ID - **Description**: Get all async tool executions for a conversation - **Response**: ```json { "success": true, "executions": [ { "executionId": "exec-id", "toolName": "tool-name", "status": "running|completed|failed|cancelled", "startedAt": "2024-01-01T00:00:00Z", "completedAt": null } ] } ``` ### Get Running Executions **GET** `/executions/:conversationId/running` - **Authentication**: Required - **Parameters**: - `conversationId` (path): Conversation ID - **Description**: Get only running async tool executions for a conversation - **Response**: ```json { "success": true, "executions": [] } ``` ### Get Execution Details **GET** `/execution/:executionId` - **Authentication**: Required - **Parameters**: - `executionId` (path): Execution ID - **Description**: Get details of a specific async tool execution - **Response**: ```json { "success": true, "execution": { "executionId": "exec-id", "toolName": "tool-name", "status": "completed", "result": {} } } ``` - **Error** (404): Execution not found ### Cancel Execution **POST** `/cancel/:executionId` - **Authentication**: Required - **Parameters**: - `executionId` (path): Execution ID - **Description**: Cancel a running async tool execution - **Response**: ```json { "success": true, "message": "Async tool execution cancelled successfully" } ``` ### Cancel All Executions for Conversation **POST** `/cancel-all/:conversationId` - **Authentication**: Required - **Parameters**: - `conversationId` (path): Conversation ID - **Description**: Cancel all running async tools for a conversation (global stop) - **Response**: ```json { "success": true, "cancelled": 3 } ``` --- ## Desktop Sign-In Routes Base path: `/api/auth/desktop` Signing in with Google on the desktop app opens the user's **real browser**, where their Google session already exists, rather than an Electron window with an empty cookie jar. A browser the app did not open has no `window.opener`, so there is no `postMessage` path back — these routes are the loopback address the answer comes home to. This is the shape RFC 8252 recommends for native apps. **Every route here is deliberately unauthenticated**, because the caller is in the middle of obtaining a session and does not have one yet. Two properties replace that: - **Loopback only.** Requests are refused with 403 unless `req.socket.remoteAddress` is a loopback address. Read from the socket and not from `req.ip`, because `req.ip` honours the caller-supplied `X-Forwarded-For` header when `trust proxy` is set. - **The nonce is the credential.** 256 bits from `crypto.randomBytes`, single use, write once, five-minute TTL, and capped in number. The flow: the app calls `/begin`, opens the browser at the remote Google endpoint passing `/handoff/:nonce` as the redirect target, and polls `/claim` until the browser lands. ### Begin a Desktop Sign-In **POST** `/begin` - **Authentication**: None (loopback only) - **Description**: Allocates a nonce for one sign-in attempt. - **Response**: ```json { "nonce": "3f7a...64 hex chars" } ``` ### Receive the Session (browser lands here) **GET** `/handoff/:nonce?token=` - **Authentication**: None (loopback only) - **Description**: Where the remote API redirects the user's browser once Google has signed them in. Records the token against the nonce and renders a "you can close this tab" page. Always answers with a **page**, never a bare status: this is a real tab a person is looking at. - **Responses**: `200` recorded · `400` no token in the callback · `410` unknown, expired, or already answered. - Sends `Cache-Control: no-store` and `Referrer-Policy: no-referrer`, since the token is in the request URL. ### Claim the Session (the app polls here) **GET** `/handoff/:nonce/claim` - **Authentication**: None (loopback only) - **Description**: Takes the token once it has arrived. Single use — a second call returns 404. - **Responses**: - `200` `{ "token": "" }` - `204` the browser has not answered yet; keep polling - `404` unknown, expired, or already claimed; stop polling --- ## Provider Auth Routes Base path: `/api/providers` All provider authentication is handled through a single unified router. The `:providerId` parameter identifies the provider (e.g., `claude-code`, `openai-codex`, `gemini-cli`, `openai`, `anthropic`, etc.). Local CLI providers use filesystem-backed credentials; remote providers proxy to agnt.gg. **Note:** An unknown `:providerId` returns 404: `{ "success": false, "error": "Unknown provider: " }`. **Auth Dispatcher** (`AuthDispatcher.js`) maps each provider's `authScheme` to an auth manager and a set of capabilities: | Auth Scheme | Local | Capabilities | | ------------- | ----- | ----------------------------------------------------------------------------------------- | | `claude-code` | Yes | status, connect-token, disconnect, refresh, oauth-pkce | | `codex` | Yes | status, disconnect, device-auth | | `gemini-cli` | Yes | status, connect-apikey, disconnect, refresh, oauth-loopback, set-auth-method, gcp-project | | `bearer` | No | status, connect-apikey, disconnect | | `api-key` | No | status, connect-apikey, disconnect | | `query-param` | No | status, connect-apikey, disconnect | ### Get Provider Auth Status **GET** `/:providerId/auth/status` - **Authentication**: Required - **Description**: Check whether credentials exist for this provider and whether its API is usable. For local CLI providers, checks filesystem credentials. For remote providers, returns basic info (use the connection health endpoint for remote status). - **Response** (local provider): ```json { "success": true, "available": true, "apiUsable": true, "hint": "Claude Code is connected and the Anthropic API is usable." } ``` For `openai-codex`, also includes `codexWorkdir` and `toolRunner` fields. - **Response** (remote provider): ```json { "success": true, "available": false, "providerId": "openai", "local": false, "hint": "Use connection health endpoint for remote provider status." } ``` ### Get Provider Capabilities **GET** `/:providerId/auth/capabilities` - **Authentication**: Required - **Description**: Return the capabilities and metadata for a provider's auth scheme - **Response**: ```json { "success": true, "providerId": "claude-code", "providerName": "Claude Code", "local": true, "remote": false, "capabilities": ["status", "connect-token", "disconnect", "refresh", "oauth-pkce"] } ``` ### Connect Provider **POST** `/:providerId/auth/connect` - **Authentication**: Required. (Historically unauthenticated for local providers; `authenticateToken` now rejects, so a token is needed for both local and remote.) - **Description**: Save credentials for a provider. Body and response vary by auth scheme. - **Body** (claude-code — token): ```json { "token": "sk-ant-..." } ``` - **Body** (gemini-cli — API key): ```json { "apiKey": "AIza..." } ``` - **Body** (remote providers — proxied to agnt.gg): ```json { "apiKey": "sk-..." } ``` - **Response** (claude-code): ```json { "success": true, "message": "Token saved successfully", "apiUsable": true } ``` - **Response** (gemini-cli): ```json { "success": true, "message": "Gemini CLI connected successfully", "apiUsable": true } ``` - **Response** (remote providers): Proxied from agnt.gg - **Error** (400): Missing or invalid credentials for the auth scheme - **Error** (400): `{ "error": "Connect not supported for " }` if local provider has no connect handler ### Disconnect Provider **POST** `/:providerId/auth/disconnect` - **Authentication**: Required. (Historically unauthenticated for local providers; `authenticateToken` now rejects, so a token is needed for both local and remote.) - **Description**: Remove credentials for a provider. Local providers delete filesystem credentials; remote providers proxy to agnt.gg. - **Response**: ```json { "success": true } ``` ### Refresh Token **POST** `/:providerId/auth/refresh` - **Authentication**: Required - **Description**: Refresh the access token using the stored refresh token. Only supported for local providers with the `refresh` capability (claude-code, gemini-cli). - **Response** (success): ```json { "success": true, "refreshed": true, "available": true, "apiUsable": true } ``` - **Error** (400): `{ "error": "Refresh not supported for this provider" }` if provider lacks `refresh` capability - **Error** (401 — claude-code specific): `{ "code": "REAUTH_REQUIRED", "error": "..." }` if refresh token is revoked - **Error** (502): `{ "code": "REFRESH_FAILED", "error": "..." }` if token refresh fails upstream ### Start OAuth Flow **GET** `/:providerId/auth/oauth/start` - **Authentication**: Required - **Description**: Initiate an OAuth flow. For `claude-code`, starts Anthropic PKCE OAuth. For `gemini-cli`, starts Google loopback OAuth. Only supported for local providers. - **Error** (400): `{ "error": "OAuth start not supported for remote providers" }` if provider is not local - **Response**: ```json { "success": true, "authUrl": "https://console.anthropic.com/oauth/authorize?...", "sessionId": "session-uuid" } ``` ### Exchange OAuth Code (claude-code PKCE) **POST** `/:providerId/auth/oauth/exchange` - **Authentication**: Required - **Description**: Submit the code#state string copied from Anthropic's callback page. Only supported for providers with `oauth-pkce` capability. - **Body**: ```json { "sessionId": "session-uuid", "codeState": "auth-code#state-value" } ``` - **Response**: ```json { "success": true } ``` - **Error** (400): `{ "error": "OAuth exchange not supported for this provider" }` if provider lacks `oauth-pkce` capability - **Error** (400): `{ "error": "sessionId and codeState are required" }` if body is incomplete - **Error** (400): `{ "error": "Could not parse the authorization code. Please copy the full code from the Anthropic page and try again." }` if code/state parsing fails ### Poll OAuth Status (gemini-cli loopback) **GET** `/:providerId/auth/oauth/status?sessionId=...` - **Authentication**: Required - **Parameters**: - `sessionId` (query, required): The session ID from the OAuth start endpoint - **Description**: Poll the loopback OAuth session state. Only supported for providers with `oauth-loopback` capability. - **Response**: ```json { "success": true, "state": "pending|completed|expired|error" } ``` - **Error** (400): `{ "error": "Missing sessionId" }` if query param missing - **Error** (400): `{ "error": "OAuth status polling not supported for this provider" }` if provider lacks `oauth-loopback` capability ### Start Device Auth (openai-codex) **POST** `/:providerId/auth/device/start` - **Authentication**: Required - **Description**: Start device login flow. Returns a URL and code the user enters in a browser. Only supported for providers with `device-auth` capability. - **Response**: ```json { "success": true, "sessionId": "session-uuid", "deviceUrl": "https://auth.openai.com/device", "deviceCode": "ABCD-1234", "state": "pending", "message": null, "startedAt": "2024-01-01T00:00:00Z", "expiresAt": "2024-01-01T00:15:00Z", "hint": "Open the URL, enter the code, then return here. We will poll for completion." } ``` - **Error** (400): `{ "error": "Device auth not supported for this provider" }` if provider lacks `device-auth` capability ### Poll Device Auth Status (openai-codex) **GET** `/:providerId/auth/device/status?sessionId=...` - **Authentication**: Required - **Parameters**: - `sessionId` (query, required): The session ID from the device start endpoint - **Description**: Poll the device login session state. Only supported for providers with `device-auth` capability. - **Response**: ```json { "success": true, "state": "pending|completed|expired|error" } ``` - **Error** (400): `{ "error": "sessionId is required" }` if query param missing or not a string - **Error** (400): `{ "error": "Device auth not supported for this provider" }` if provider lacks `device-auth` capability ### Set Auth Method (gemini-cli) **POST** `/:providerId/auth/set-auth-method` - **Authentication**: Required - **Description**: Switch between API key and OAuth authentication methods. When switching to `api-key`, removes OAuth credentials from `~/.gemini/oauth_creds.json`. When switching to `oauth`, removes API key from `~/.gemini/.env`. Only supported for providers with `set-auth-method` capability. - **Body**: ```json { "method": "api-key|oauth" } ``` - **Response**: ```json { "success": true, "available": true, "apiUsable": true } ``` - **Error** (400): `{ "error": "method must be \"api-key\" or \"oauth\"" }` if method is invalid - **Error** (400): `{ "error": "set-auth-method not supported for this provider" }` if provider lacks capability ### Set GCP Project (gemini-cli) **POST** `/:providerId/auth/gcp-project` - **Authentication**: Required - **Description**: Set the Google Cloud Project ID (required for workspace/organization accounts). Only supported for providers with `gcp-project` capability. - **Body**: ```json { "projectId": "my-gcp-project" } ``` - **Response**: ```json { "success": true, "projectId": "my-gcp-project" } ``` - **Error** (400): `{ "error": "Missing projectId" }` if body is incomplete - **Error** (400): `{ "error": "GCP project not supported for this provider" }` if provider lacks capability --- ## Contract Routes Base path: `/api/contracts` > **Read-only.** Contracts are kept as evidence: `GET` routes still answer, but every write (`POST`, `PUT`, `PATCH`, `DELETE`) returns `410 { error: 'learning_lifecycle_required', replacement: '/api/learning' }`. Behaviour changes go through the Learning lifecycle (`/api/learning`). The write routes below are documented for history only. Contracts are refinement-type runtime invariants (PRD-091 Layer 5). They are either **authored** by the user/agent or **mined** by `InsightEngine` from successful executions ("output must be JSON", "step count ≤ 5", "response includes citation block"). At runtime, `ContractsService.check` evaluates whether evidence satisfies the contract; violations are counted on the contract row and feed into `FitnessScoreService` (contract cleanliness component). ### Contract shape ```json { "id": "uuid", "user_id": "user-uuid", "target_type": "tool|workflow|skill|agent", "target_id": "target-uuid", "name": "Output must be valid JSON", "predicate": { "type": "json_valid", "field": "output" }, "source": "authored|mined", "status": "active|disabled|deprecated", "confidence": 0.92, "evidence_count": 47, "violation_count": 2, "created_at": "...", "updated_at": "..." } ``` ### List Contracts **GET** `/` - **Authentication**: Required - **Parameters**: - `status` (query, optional): `active`, `disabled`, `deprecated` - `targetType` (query, optional): `tool`, `workflow`, `skill`, `agent` - **Response**: ```json { "success": true, "contracts": [ { ... } ] } ``` ### Create Contract **POST** `/` - **Authentication**: Required - **Body**: ```json { "targetType": "tool", "targetId": "web-search", "name": "Output must include source URLs", "predicate": { "type": "regex", "field": "output", "pattern": "https?://" }, "confidence": 0.9 } ``` - **Description**: Authors a new contract. `targetType` and `targetId` scope the contract to a specific asset; `predicate` is a JSON shape interpreted by `ContractsService.check`. Errors return `400` if required fields are missing. - **Response** (`201`): ```json { "success": true, "contract": { ... } } ``` ### Get Single Contract **GET** `/:id` - **Authentication**: Required - **Response**: ```json { "success": true, "contract": { ... } } ``` - **Errors**: `404` not found, `403` forbidden ### Get Contract Violations **GET** `/:id/violations` - **Authentication**: Required - **Description**: Returns the violation history for a contract — useful when surfacing why a `canary-check` flagged regression. - **Response**: ```json { "success": true, "violations": [ { "id": "v-uuid", "contract_id": "c-uuid", "source_execution_id": "exec-uuid", "details": { "expected": "...", "actual": "..." }, "created_at": "..." } ] } ``` ### Update Contract Status **PATCH** `/:id` - **Authentication**: Required - **Body**: ```json { "status": "disabled" } ``` - **Description**: Currently only `status` is mutable. Use this to disable a noisy contract without deleting it. - **Response**: ```json { "success": true, "contract": { ... } } ``` ### Check Evidence Against Active Contracts **POST** `/check` - **Authentication**: Required - **Body**: ```json { "targetType": "tool", "targetId": "web-search", "runtimeState": { "output": "..." }, "sourceExecutionId": "exec-uuid" } ``` - **Description**: Evaluates `runtimeState` against every active contract for `(targetType, targetId)`. Records evidence on each contract; persists a violation row if a predicate fails. Returns per-contract verdicts. - **Response**: ```json { "success": true, "checked": 3, "passed": 2, "failed": 1, "verdicts": [ { "contractId": "...", "name": "...", "passed": true }, { "contractId": "...", "name": "...", "passed": false, "violationId": "..." } ] } ``` ### Delete Contract **DELETE** `/:id` - **Authentication**: Required - **Response**: ```json { "success": true, "deleted": true } ``` --- ## Content Output Routes Base path: `/api/content-outputs` ### Health Check **GET** `/health` - **Authentication**: None - **Description**: Check if the content output service is running - **Response**: ```json { "status": "OK" } ``` ### Get All Content Outputs **GET** `/` - **Authentication**: Required - **Description**: Retrieve all content outputs for the authenticated user - **Response**: ```json [ { "id": "output-id", "title": "Output Title", "content": "Content data", "workflowId": "workflow-id", "toolId": "tool-id", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ] ``` ### Save/Update Content Output **POST** `/save` - **Authentication**: Required - **Description**: Create a new content output or update an existing one - **Body**: ```json { "id": "optional-output-id", "title": "Output Title", "content": "Content data", "workflowId": "workflow-id", "toolId": "tool-id" } ``` - **Response**: ```json { "success": true, "output": { "id": "output-id", "title": "Output Title", "content": "Content data", "workflowId": "workflow-id", "toolId": "tool-id", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } } ``` ### Get Content Output by ID **GET** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Content output ID - **Description**: Retrieve a specific content output by ID - **Response**: ```json { "id": "output-id", "title": "Output Title", "content": "Content data", "workflowId": "workflow-id", "toolId": "tool-id", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ``` ### Update Content Output **PUT** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Content output ID - **Body**: ```json { "title": "Updated Title", "content": "Updated content data" } ``` - **Response**: ```json { "success": true, "output": { "id": "output-id", "title": "Updated Title", "content": "Updated content data", "workflowId": "workflow-id", "toolId": "tool-id", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } } ``` ### Rename Content Output **PATCH** `/:id/rename` - **Authentication**: Required - **Parameters**: - `id` (path): Content output ID - **Body**: ```json { "title": "New Title" } ``` - **Response**: ```json { "success": true, "output": { "id": "output-id", "title": "New Title", "content": "Content data", "workflowId": "workflow-id", "toolId": "tool-id", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } } ``` ### Delete Content Output **DELETE** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Content output ID - **Description**: Delete a content output by ID - **Response**: ```json { "success": true, "message": "Content output deleted successfully" } ``` ### Get Content Outputs by Workflow **GET** `/workflow/:workflowId` - **Authentication**: Required - **Parameters**: - `workflowId` (path): Workflow ID - **Description**: Retrieve all content outputs for a specific workflow - **Response**: ```json [ { "id": "output-id", "title": "Output Title", "content": "Content data", "workflowId": "workflow-id", "toolId": "tool-id", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ] ``` ### Get Content Outputs by Tool **GET** `/tool/:toolId` - **Authentication**: Required - **Parameters**: - `toolId` (path): Tool ID - **Description**: Retrieve all content outputs for a specific tool - **Response**: ```json [ { "id": "output-id", "title": "Output Title", "content": "Content data", "workflowId": "workflow-id", "toolId": "tool-id", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ] ``` --- ## Custom Provider Routes Base path: `/api/custom-providers` Manage user-created custom OpenAI-compatible providers (e.g., local Ollama, LM Studio, or any OpenAI-compatible API endpoint). ### Get All Custom Providers **GET** `/` - **Authentication**: Required - **Description**: Retrieve all custom providers for the authenticated user - **Response**: ```json { "success": true, "providers": [ { "id": "uuid", "user_id": "user-uuid", "provider_name": "Local LM Studio", "base_url": "http://localhost:1234", "is_active": 1, "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-01T00:00:00Z" } ], "count": 1 } ``` ### Create Custom Provider **POST** `/` - **Authentication**: Required - **Body**: ```json { "provider_name": "Custom Provider", "base_url": "https://api.example.com", "api_key": "your-api-key" } ``` - `provider_name` (required): Display name - `base_url` (required): API base URL - `api_key` (optional): API key for authentication - **Response** (201 Created): ```json { "success": true, "provider": { "id": "uuid", "user_id": "user-uuid", "provider_name": "Custom Provider", "base_url": "https://api.example.com", "is_active": 1, "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-01T00:00:00Z" }, "message": "Custom provider created successfully" } ``` - **Error** (400): `{ "error": "Missing required fields: provider_name, base_url" }` ### Get Custom Provider by ID **GET** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Provider UUID - **Description**: Retrieve a specific custom provider by ID - **Response**: ```json { "success": true, "provider": { "id": "uuid", "user_id": "user-uuid", "provider_name": "Custom Provider", "base_url": "https://api.example.com", "is_active": 1, "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-01T00:00:00Z" } } ``` - **Error** (404): `{ "error": "Provider not found" }` ### Update Custom Provider **PUT** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Provider UUID - **Body** (all fields optional): ```json { "provider_name": "Updated Provider Name", "base_url": "https://api.updated.com", "api_key": "new-api-key", "is_active": 1 } ``` - **Response**: ```json { "success": true, "provider": { "id": "uuid", "user_id": "user-uuid", "provider_name": "Updated Provider Name", "base_url": "https://api.updated.com", "is_active": 1, "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-01T00:00:00Z" }, "message": "Custom provider updated successfully" } ``` - **Error** (404): Provider not found ### Delete Custom Provider **DELETE** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Provider UUID - **Description**: Delete a custom provider by ID - **Response**: ```json { "success": true, "message": "Custom provider deleted successfully" } ``` - **Error** (404): Provider not found ### Get Provider Templates **GET** `/templates` - **Authentication**: None - **Description**: Get all pre-configured provider templates for creating custom providers. Includes cloud APIs (Mistral, Fireworks, Perplexity, etc.) and local inference servers (Ollama, LM Studio). - **Response**: ```json { "success": true, "templates": [ { "key": "ollama", "name": "Ollama (Local)", "baseURL": "http://localhost:11434/v1", "defaultModel": "llama3.2", "supportsTools": true, "supportsStreaming": true, "requiresApiKey": false, "description": "Ollama — Run open-source LLMs locally" }, { "key": "mistral", "name": "Mistral AI", "baseURL": "https://api.mistral.ai/v1", "defaultModel": "mistral-large-latest", "supportsTools": true, "supportsVision": true, "supportsStreaming": true, "description": "Mistral AI — European AI lab with efficient, high-quality models" } ], "count": 10 } ``` ### Test Custom Provider Connection **POST** `/test` - **Authentication**: Required - **Description**: Test connection to a custom provider without saving it. Normalizes the URL (adds `/v1` if needed) and calls the `/models` endpoint. - **Body**: ```json { "base_url": "https://api.example.com", "api_key": "your-api-key" } ``` - `base_url` (required): API base URL to test - `api_key` (optional): API key for authentication - **Response** (success): ```json { "success": true, "modelsCount": 15, "models": ["model-1", "model-2", "model-3", "model-4", "model-5"] } ``` **Note:** Returns at most 5 model IDs as a preview. - **Response** (connection failure): ```json { "success": false, "error": "HTTP 401: Unauthorized" } ``` - **Error** (400): `{ "error": "Missing required fields: base_url" }` ### Get Custom Provider Models **GET** `/:id/models` - **Authentication**: Required - **Parameters**: - `id` (path): Provider UUID - **Description**: Fetch all available models from a custom provider - **Response**: ```json { "success": true, "models": ["model-1", "model-2", "model-3"], "count": 3 } ``` --- ## Custom Tool Routes Base path: `/api/custom-tools` ### Health Check **GET** `/health` - **Authentication**: None - **Description**: Check if the custom tool service is running - **Response**: ```json { "status": "OK" } ``` ### Get All Custom Tools **GET** `/` - **Authentication**: Required - **Description**: Retrieve all custom tools for the authenticated user - **Response**: ```json [ { "id": "tool-id", "name": "Custom Tool", "description": "Tool description", "config": {}, "userId": "user-id", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ] ``` ### Save/Update Custom Tool **POST** `/save` - **Authentication**: Required - **Description**: Create a new custom tool or update an existing one - **Body**: ```json { "id": "optional-tool-id", "name": "Custom Tool", "description": "Tool description", "config": {} } ``` - **Response**: ```json { "success": true, "tool": { "id": "tool-id", "name": "Custom Tool", "description": "Tool description", "config": {}, "userId": "user-id", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } } ``` ### Get Custom Tool by ID **GET** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Tool ID - **Description**: Retrieve a specific custom tool by ID - **Response**: ```json { "id": "tool-id", "name": "Custom Tool", "description": "Tool description", "config": {}, "userId": "user-id", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ``` ### Update Custom Tool **PUT** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Tool ID - **Body**: ```json { "name": "Updated Tool Name", "description": "Updated description", "config": {} } ``` - **Response**: ```json { "success": true, "tool": { "id": "tool-id", "name": "Updated Tool Name", "description": "Updated description", "config": {}, "userId": "user-id", "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } } ``` ### Delete Custom Tool **DELETE** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Tool ID - **Description**: Delete a custom tool by ID - **Response**: ```json { "success": true, "message": "Custom tool deleted successfully" } ``` --- ## Tenant Proxy Routes Base path: `/api/tenants` The account's cloud instances, passed through to `api.agnt.gg/tenants` with the caller's own session. The Teams page manages the instance behind a team from here: who holds a seat, and the instance link. Only these routes are forwarded; everything else answers 404. ### List Instances **GET** `/` - **Authentication**: Required - **Description**: Every instance the account owns or is a member of, with plan, status, role and seat counts ### Instance Detail **GET** `/:slug` - **Authentication**: Required - **Description**: One instance with its members and seats ### Add Seat **POST** `/:slug/members` - **Authentication**: Required (owner or admin of the instance) - **Body**: `{ "email": "colleague@company.com", "role": "member" }` - **Description**: Gives an existing AGNT account a seat on the instance ### Remove Seat **DELETE** `/:slug/members/:userId` - **Authentication**: Required (owner or admin, or the member themselves) ## Local Model Routes Base path: `/api/local-models` Behind "Run a model on this machine". The Local provider is whichever local server has the requested model: AGNT's own llama.cpp server, LM Studio (`127.0.0.1:1234`), Ollama (`127.0.0.1:11434`) or a llama-server on `127.0.0.1:8080` (`backend/src/services/localModels`). AGNT can also install and run a model itself: it detects the GPU, downloads a pinned llama.cpp build and a catalog model (both SHA-256 verified, resumable), and starts it on a free loopback port. A hosted instance never downloads or runs anything. ### Get Local Model Status **GET** `/status` - **Authentication**: Required - **Description**: Every known local server and its models, LM Studio's install state, and AGNT's own runtime: hardware, the catalog priced against it (`fit`: `gpu` / `mixed` / `too_big`), the recommended model, and setup progress - **Response**: ```json { "ready": true, "running": true, "models": ["qwen3.5-4b"], "server": { "id": "agnt", "name": "AGNT local runtime", "baseURL": "http://127.0.0.1:54658/v1" }, "servers": [{ "id": "ollama", "name": "Ollama", "baseURL": "http://127.0.0.1:11434/v1", "running": false, "models": [] }], "installed": false, "canStart": false, "downloadUrl": "https://lmstudio.ai/download", "managed": { "supported": true, "hardware": { "gpu": "NVIDIA GeForce GTX 1660 SUPER", "vramBytes": 6442450944, "ramBytes": 34234916864 }, "engine": { "tag": "b11476", "build": "win32-x64-cuda12", "label": "NVIDIA CUDA 12", "bytes": 655965580, "installed": true }, "models": [{ "id": "qwen3.5-4b", "name": "Qwen 3.5 4B", "blurb": "...", "sizeBytes": 2740937888, "fit": "gpu", "downloaded": true, "recommended": true }], "recommendedId": "qwen3.5-4b", "activeModelId": "qwen3.5-4b", "server": { "port": 54658, "modelId": "qwen3.5-4b", "baseURL": "http://127.0.0.1:54658/v1" }, "job": null } } ``` `ready` means a Local model can be used now (AGNT's own model counts once downloaded: it starts on the first request). ### Prepare a Local Model **POST** `/prepare` - **Authentication**: Required - **Description**: Makes a local model able to run a chat turn before the app switches to it. LM Studio loads models with its own default context (4096 tokens), and one AGNT turn needs about 23K, so an LM Studio chat model loaded too small (or not loaded) is reloaded with 32768 tokens of context, or its own maximum when smaller, under the same id (`lms unload` / `lms load --context-length`), then verified. Embedding models are never chosen. Servers without LM Studio's native API (Ollama, llama-server, AGNT's own runtime) size their own context: `{ "skipped": true }`. - **Body**: `{ "model": "qwen3.5-4b" }` (optional; defaults to the loaded chat model, else the first chat model) - **Response**: `200 { "model": "qwen3.5-4b", "contextLength": 32768, "reloaded": true }`, or `422 { "error": "load_failed" | "no_chat_model" | "model_not_found" | "not_installed", "model", "contextLength", "detail" }` ### Start LM Studio **POST** `/start` - **Authentication**: Required - **Description**: Starts LM Studio's server if it is installed and stopped, then waits up to 30 seconds for it to answer. Returns the same shape as `/status`, plus `error` (`not_installed`, `start_failed` with `detail`, `start_timeout`, `not_available_on_hosted`) when it could not. ### Set Up AGNT's Local Model **POST** `/managed/setup` - **Authentication**: Required - **Body**: `{ "modelId": "qwen3.5-4b" }` (optional; defaults to the model recommended for this machine; must be a catalog id) - **Description**: Starts the one-click setup in the background (engine download, model download, start) and returns the status at once. Progress is `managed.job`: `{ modelId, phase: engine | model | starting | ready | error | cancelled, bytesDone, bytesTotal, error, errorCode }`. A second call while one runs joins it. - **Errors**: 400 `unknown_model`, `too_big`, `no_model_fits`, `unsupported_platform`, `not_available_on_hosted`; 409 `busy` (a different model is being set up) ### Cancel Setup **POST** `/managed/cancel` - **Authentication**: Required - **Description**: Stops a running download. Downloaded bytes are kept, so the next setup resumes. Returns the status. ## AGNT Services Routes Base path: `/api/agnt-services` What the hosted AGNT services (Models, Search, Sandbox, Mail, Webhooks) have given this account. These are read-only lookups the editor uses to show a trigger's real address; the addresses themselves are minted by the services, not derived locally. ### Get Entitlements **GET** `/entitlements` - **Authentication**: Required - **Description**: Whether this account may use each hosted service under its plan - **Response**: ```json { "models": true, "search": true, "sandbox": true, "mail": true, "webhooks": true } ``` ### Get Usage **GET** `/usage` - **Authentication**: Required - **Description**: This month's usage across all five hosted services, each answering for itself. A service that cannot be reached is reported with `ok: false` and an error, without hiding the others. - **Response**: ```json { "services": [ { "service": "search", "ok": true, "plan": "AGNT included allowance", "period": "2026-09", "resetAt": 1790812800000, "meters": [ { "key": "searches", "label": "Searches", "used": 10, "included": 1400, "unit": "searches" } ], "balanceMicroUSD": 0, "allowOverage": false } ], "fetchedAt": 1790041000000 } ``` ### Get Inbox Address **GET** `/inbox` - **Authentication**: Required - **Description**: The hosted inbox every "Built-in Email" trigger listens on; created on first use - **Response**: `{ "pro": true, "address": "agent-x@mail.agnt.gg", "inboxId": "..." }` or `{ "pro": false, "address": null }` ### Get Webhook URL **GET** `/webhook/:workflowId` - **Authentication**: Required - **Description**: The public `https://webhooks.agnt.gg/in/{slug}` URL of a workflow's webhook. `url` is null until the workflow has been activated once. - **Response**: `{ "pro": true, "url": "https://webhooks.agnt.gg/in/abc123", "state": "active" }` ## Email Listener Routes Base path: `/api/email-listeners` ### Get Email Listeners **GET** `/` - **Authentication**: Required - **Description**: Get all workflows with `receive-email` trigger nodes for the authenticated user - **Response**: ```json { "success": true, "listeners": [ { "id": "workflow-id", "workflow_id": "workflow-id", "workflow_name": "Email Handler Workflow", "workflow_status": "active", "email_address": "workflow-123@agnt.gg", "email_config": "Built-in Email", "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-01T00:00:00Z" } ] } ``` --- ## Execution Routes Base path: `/api/executions` ### Get All Executions **GET** `/` - **Authentication**: Required - **Description**: Retrieve all executions for the authenticated user - **Response**: ```json [ { "id": "execution-id", "type": "agent|workflow|tool", "status": "running|completed|failed", "startTime": "2024-01-01T00:00:00Z", "endTime": "2024-01-01T00:05:00Z", "metadata": {} } ] ``` ### Get Agent Activity Data **POST** `/activity` - **Authentication**: Required - **Body**: ```json { "agentId": "agent-id", "timeRange": { "start": "2024-01-01T00:00:00Z", "end": "2024-01-02T00:00:00Z" } } ``` - **Response**: ```json { "activities": [ { "timestamp": "2024-01-01T00:00:00Z", "type": "chat|execution", "details": {} } ], "summary": { "totalChats": 10, "totalExecutions": 5 } } ``` ### Get Execution Details **GET** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Execution ID - **Description**: Retrieve detailed information about a specific execution - **Response**: ```json { "id": "execution-id", "type": "agent|workflow|tool", "status": "running|completed|failed", "startTime": "2024-01-01T00:00:00Z", "endTime": "2024-01-01T00:05:00Z", "input": {}, "output": {}, "logs": [ { "timestamp": "2024-01-01T00:00:00Z", "level": "info|error|debug", "message": "Log message" } ], "metadata": {} } ``` ### Get Agent Executions **GET** `/agents/list` - **Authentication**: Required - **Description**: Get all agent/orchestrator execution traces - **Response**: ```json { "success": true, "runs": [ { "id": "run-id", "agentId": "agent-id", "agentName": "Agent Name", "status": "completed|running|failed", "startedAt": "2024-01-01T00:00:00Z", "completedAt": "2024-01-01T00:05:00Z", "tokensUsed": 1500, "cost": 0.003 } ] } ``` ### Get Agent Execution Details **GET** `/agents/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Execution/run ID - **Description**: Get detailed agent execution trace including messages and tool calls - **Response**: ```json { "success": true, "run": { "id": "run-id", "agentId": "agent-id", "status": "completed", "messages": [], "toolCalls": [], "tokensUsed": 1500, "cost": 0.003, "startedAt": "2024-01-01T00:00:00Z", "completedAt": "2024-01-01T00:05:00Z" } } ``` ### Delete Agent Execution **DELETE** `/agents/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Execution/run ID - **Description**: Delete a specific agent execution trace - **Response**: ```json { "success": true, "message": "Agent execution deleted" } ``` ### Clear Completed Agent Executions **POST** `/agents/clear-completed` - **Authentication**: Required - **Description**: Clear all completed agent execution traces for the authenticated user - **Response**: ```json { "success": true, "cleared": 15 } ``` --- ### Get Conversation Summary **GET** `/conversation/:conversationId/summary` - **Authentication**: Required - **Description**: Per-conversation monitoring summary — aggregates tokens, cache usage, and cost across all executions in the conversation - **Response**: Aggregate totals object for the conversation --- ## Evolution / Insight Routes Base path: `/api/insights` The unified evolution system extracts actionable insights from agent chats, goal executions, and workflow runs. Insights can target agents, skills, workflows, or tools and are automatically generated when executions complete. The system also manages per-agent memory (facts, preferences, corrections learned from conversations). ### List Insights **GET** `/` - **Authentication**: Required - **Parameters**: - `targetType` (query, optional): Filter by target type (`agent`, `skill`, `workflow`, `tool`) - `targetId` (query, optional): Filter by target ID - `status` (query, optional): Filter by status (`pending`, `applied`, `rejected`) - `category` (query, optional): Filter by category (`memory`, `prompt_refinement`, `skill_recommendation`, `tool_preference`, `bottleneck`, `optimization`, `error_pattern`, `skill_candidate`) - `limit` (query, optional): Max results (default: 100) - **Response**: ```json { "success": true, "insights": [ { "id": "insight-uuid", "user_id": "user-id", "source_type": "agent_chat|goal|workflow", "source_id": "execution-id", "target_type": "agent|skill|workflow|tool", "target_id": "agent-id", "category": "prompt_refinement", "title": "Insight title", "description": "Detailed description", "confidence": 0.85, "priority": "medium", "status": "pending", "source_context": {}, "evidence": {}, "applied_result": null, "created_at": "2024-01-01T00:00:00Z" } ] } ``` ### Get Insight Stats **GET** `/stats` - **Authentication**: Required - **Description**: Get aggregated insight counts grouped by status and target type - **Response**: ```json { "success": true, "statusCounts": { "pending": 12, "applied": 8, "rejected": 2 }, "targetCounts": { "agent": 10, "skill": 5, "workflow": 7 } } ``` ### Get Insights by Target **GET** `/target/:targetType/:targetId` - **Authentication**: Required - **Parameters**: - `targetType` (path): `agent`, `skill`, `workflow`, or `tool` - `targetId` (path): Target entity ID - `status` (query, optional): Filter by status - **Description**: Get all insights targeting a specific entity (e.g., all insights for a particular agent) - **Response**: ```json { "success": true, "insights": [ ... ] } ``` ### Get Insights by Source **GET** `/source/:sourceType/:sourceId` - **Authentication**: Required - **Parameters**: - `sourceType` (path): `agent_chat`, `goal`, or `workflow` - `sourceId` (path): Source execution ID - **Description**: Get all insights generated from a specific execution (e.g., all insights extracted from a particular goal run) - **Response**: ```json { "success": true, "insights": [ ... ] } ``` ### Get Single Insight **GET** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Insight ID - **Response**: ```json { "success": true, "insight": { ... } } ``` - **Error** (404): Insight not found ### Autonomy Router — Route Pending Insights (PRD-091 Layer 4) **POST** `/route` - **Authentication**: Required - **Body** (optional): ```json { "provider": "anthropic", "model": "claude-sonnet-4-20250514" } ``` - **Description**: Sweeps every pending insight for the user through the `InsightAutonomyRouter`. Each insight is evaluated by `AutonomyPolicy.evaluate(insight, settings, ctx)` against `EvolutionSettingsModel.autonomy`. Per-insight verdicts: - **`direct`** — apply now (memory, low blast radius, high confidence) - **`gated`** — sandbox-test before applying (blast radius ≥ `requireGateAbove`) - **`escalate`** — surface to the user as `pending` with `autonomy_decision: 'escalate'` (high blast OR low confidence OR over budget) - **`skip`** — autonomy disabled (the default state) Every applied insight gets a row in `mutation_history` with `fitness_before` captured for canary detection. **Prefer this over `/:id/apply` for unattended flows.** - **Response**: ```json { "success": true, "summary": { "evaluated": 12, "direct": 4, "gated": 2, "escalated": 5, "skipped": 1, "mutationIds": ["m-uuid", "m-uuid", "..."] } } ``` ### Autonomy Router — Route One Insight **POST** `/:id/route` - **Authentication**: Required - **Body** (optional): same `{ provider, model }` override as above - **Description**: Same logic as `POST /route` but applied to a single insight by id. Useful when surfacing "auto-handle this?" affordance per row. - **Response**: ```json { "success": true, "result": { "decision": "direct|gated|escalate|skip", "reason": "low_blast_high_confidence", "blastRadius": 0.1, "mutationId": "m-uuid|null" } } ``` ### Evolution Settings — Get **GET** `/settings` - **Authentication**: Required - **Description**: Returns the user's evolution settings, including the autonomy policy block. Defaults live in `AutonomyPolicy.DEFAULTS` (see Closed Loop System section above) — only user overrides are persisted. - **Response**: ```json { "success": true, "settings": { "autonomy": { "enabled": false, "minConfidence": 0.7, "maxBlastRadius": 0.5, "dailyBudget": 20, "allowedCategories": ["memory", "prompt_refinement", "..."], "requireGateAbove": 0.45 } } } ``` ### Evolution Settings — Update (Opt-In Switch) **POST** `/settings` - **Authentication**: Required - **Body**: ```json { "autonomy": { "enabled": true, "minConfidence": 0.8 } } ``` - **Description**: **This is the user opt-in switch.** Flipping `autonomy.enabled` to `true` is what permits the router to direct-apply insights. The agent must **never** flip this without explicit, in-conversation confirmation from the user. - **Response**: ```json { "success": true, "settings": { ... } } ``` ### Apply Insight (Direct, Bypasses Router) **POST** `/:id/apply` - **Authentication**: Required - **Parameters**: - `id` (path): Insight ID - **Body** (optional): ```json { "provider": "anthropic", "model": "claude-sonnet-4-20250514" } ``` - **Description**: Apply an insight to its target entity. For agent prompt refinements, uses LLM to merge the improvement into the agent's system prompt. Provider/model override the user's defaults for the LLM call. The insight status is updated to `applied`. > **Note vs. router endpoints above:** `/:id/apply` is the human-confirmed path — bypasses `AutonomyPolicy` entirely and just runs the applicator. Use this when the user clicks an "Apply" button. Use `POST /route` or `POST /:id/route` for unattended / batched application that respects the user's policy. **Do not call `/apply` on critical-priority insights without explicit confirmation.** - **Response**: ```json { "success": true, "result": { "applied": true, "changes": { ... } } } ``` ### Reject Insight **POST** `/:id/reject` - **Authentication**: Required - **Parameters**: - `id` (path): Insight ID - **Description**: Mark an insight as rejected - **Response**: ```json { "success": true, "message": "Insight rejected" } ``` ### Delete Insight **DELETE** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Insight ID - **Response**: ```json { "success": true, "deleted": true } ``` ### Trigger Periodic Rollup **POST** `/rollup` - **Authentication**: Required - **Description**: Manually trigger tool usage rollup analysis. Extracts tool preference insights from recent execution history. - **Response**: ```json { "success": true, "count": 3, "insightIds": ["id-1", "id-2", "id-3"] } ``` ### Get Agent Memories **GET** `/memory/:agentId` - **Authentication**: Required - **Parameters**: - `agentId` (path): Agent ID - `memoryType` (query, optional): Filter by type (`fact`, `preference`, `correction`) - **Description**: Get all memories for an agent. Memories are facts, preferences, and corrections learned from conversations. - **Response**: ```json { "success": true, "memories": [ { "id": "memory-uuid", "agent_id": "agent-id", "user_id": "user-id", "memory_type": "fact", "content": "User prefers TypeScript over JavaScript", "relevance_score": 0.9, "created_at": "2024-01-01T00:00:00Z" } ] } ``` ### Add Agent Memory **POST** `/memory/:agentId` - **Authentication**: Required - **Parameters**: - `agentId` (path): Agent ID - **Body**: ```json { "memoryType": "fact|preference|correction", "content": "User prefers concise answers" } ``` - **Response**: ```json { "success": true, "id": "memory-uuid" } ``` ### Update Agent Memory **PUT** `/memory/entry/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Memory entry ID - **Body**: ```json { "content": "Updated memory content", "relevanceScore": 0.95, "memoryType": "preference" } ``` - **Response**: ```json { "success": true, "updated": true } ``` ### Delete Agent Memory **DELETE** `/memory/entry/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Memory entry ID - **Response**: ```json { "success": true, "deleted": true } ``` --- ### Run Core Evolution Loop **POST** `/api/evolution/core/run` - **Authentication**: Required - **Description**: Runs the built-in evolution loop in recommendation-first mode. GA work is synchronous/CPU-bound, so all numeric inputs are defensively clamped server-side. - **Body** (all optional): ```json { "lookbackDays": 7, "pendingInsightLimit": 250, "populationSize": 24, "generations": 10, "eliteCount": 6, "apply": false } ``` - Clamps: `lookbackDays` 1–90, `pendingInsightLimit` 1–5000, `populationSize` 1–200, `generations` 1–50, `eliteCount` 1–populationSize - **Response**: ```json { "success": true, "recommendation": {} } ``` ### List Core Evolution Runs **GET** `/api/evolution/core/runs` - **Authentication**: Required - **Parameters**: - `limit` (query, optional): 1–2000, default 200 - **Response**: `{ "success": true, "runs": [...] }` ### List Performance Snapshots **GET** `/api/evolution/core/snapshots` - **Authentication**: Required - **Parameters**: - `limit` (query, optional): 1–2000, default 200 - **Description**: Recent user-scoped evolution performance snapshots - **Response**: `{ "success": true, "snapshots": [...] }` ### Get All Memories **GET** `/api/insights/memory` - **Authentication**: Required - **Description**: All agent memories for the current user, across all agents - **Parameters**: - `limit` (query, optional): 1–50000, default 5000 - `sort` (query, optional): `recent` (default) or `relevance` - **Response**: ```json { "success": true, "memories": [], "count": 0 } ``` ### Delete Orphaned Memories **DELETE** `/api/insights/memory/orphaned` - **Authentication**: Required - **Description**: Deletes every memory whose `agent_id` no longer exists (i.e. the agent was deleted). The special ids `orchestrator` and `__orchestrator__` are always preserved. - **Response**: ```json { "success": true, "deleted": 7 } ``` --- ## Memory Routes Base path: `/api/memory` Hybrid full-text search across the user's persistent history — the "remember anything" layer. Backed by SQLite FTS5 virtual tables that shadow `conversation_logs`, `agent_executions`, `content_outputs`, `insights`, `agent_memory`, and `workflow_versions`. Triggers keep the indexes in sync; the source tables remain the system of record. The same surface is also exposed to the chat orchestrator as the `recall`, `list_recent`, and `get_trace` tools. ### Search **GET** `/search` - **Authentication**: Required - **Description**: Hybrid keyword + date-range search across all (or a subset of) memory sources. When `q` is provided, results are ranked by BM25 relevance; when omitted, the endpoint falls back to time-ordered recent rows (same shape as `/recent`). - **Query Parameters**: - `q` (string, optional): Keyword(s). Tokens are sanitized (alphanumeric + `-_` only), prefix-matched, and AND-ed. e.g. `q=pokemon mew` matches both terms with prefix expansion. - **Alias**: `query` is accepted as a synonym for `q`. If both are sent, `q` wins. - `since` (ISO-8601, optional): Lower bound on the source's timestamp column (e.g. `2026-05-19T00:00:00Z`). - `until` (ISO-8601, optional): Upper bound. - `sources` (CSV, optional): Subset of `conversations,executions,outputs,insights,memory,versions`. Omit to search all. - `limit` (integer, optional): Max results to return. Default 50, cap 200. - **Example**: `GET /api/memory/search?q=pokemon&since=2026-05-19T00:00:00Z&sources=conversations,outputs&limit=20` - **Response**: ```json { "success": true, "count": 12, "results": [ { "kind": "conversation", "id": "conversation-uuid", "timestamp": "2026-05-24T19:23:00Z", "title": "make a pokemon red mew starter save", "snippet": "...generated «pokemon» starter screenshots...", "score": -7.42, "meta": { "conversation_id": "conversation-uuid", "row_id": 4221 } }, { "kind": "execution", "id": "execution-uuid", "timestamp": "2026-05-24T19:24:11Z", "title": "Orchestrator run · completed", "snippet": "...wrote ascii_screen.py for «pokemon»...", "score": -6.91, "meta": { "execution_id": "execution-uuid", "conversation_id": "conversation-uuid", "agent_id": null, "agent_name": "Orchestrator", "status": "completed", "provider": "OpenAI-Codex", "model": "gpt-5.5", "end_time": "2026-05-24T19:25:03Z" } } ] } ``` Each result row is normalized to `{ kind, id, timestamp, title, snippet, score?, meta }`. `kind` is one of `conversation | execution | output | insight | memory | version`. `score` is BM25 (lower = more relevant) and is only present when `q` was provided. `meta` carries kind-specific identifiers — most importantly `meta.execution_id`, which you can pass to `/trace/:id` for the full trace. ### Recent **GET** `/recent` - **Authentication**: Required - **Description**: Time-bounded "what happened recently?" lookup without a keyword. Useful for "what did you do last week" style questions where the user wants a chronological summary, not a search. - **Query Parameters**: - `days` (integer, optional): Days back from now. Default 7. Minimum 1. - `kind` (string, optional): Restrict to a single source: `conversations | executions | outputs | insights | memory | versions`. Omit to include all. - `limit` (integer, optional): Max results to return. Default 100, cap 500. - **Example**: `GET /api/memory/recent?days=7&kind=executions&limit=50` - **Response**: Same shape as `/search`, but rows are sorted by `timestamp DESC` and have no `score` field. ### Get Trace Detail **GET** `/trace/:executionId` - **Authentication**: Required - **Description**: Full detail for a single `agent_executions` row plus its `agent_tool_executions` children. Convenience wrapper around `GET /api/executions/agents/:id` that additionally parses each tool call's `input` / `output` JSON. - **Parameters**: - `executionId` (path): The `agent_executions.id` UUID. Most easily obtained from `result.meta.execution_id` on a `/search` or `/recent` result. - **Response**: ```json { "success": true, "trace": { "id": "execution-uuid", "agentId": null, "agentName": "Orchestrator", "conversationId": "conversation-uuid", "userId": "user-uuid", "status": "completed", "startTime": "2026-05-24T19:24:11Z", "endTime": "2026-05-24T19:25:03Z", "initialPrompt": "make a pokemon red mew starter save", "finalResponse": "Created the starter save and saved screenshots to ...", "provider": "OpenAI-Codex", "model": "gpt-5.5", "totalTokens": 66319, "estimatedCost": 0.0906, "toolExecutions": [ { "id": "tool-exec-uuid", "tool_name": "execute_shell_command", "start_time": "2026-05-24T19:24:14Z", "end_time": "2026-05-24T19:24:15Z", "status": "completed", "input": { "command": "node inspect_save.py", "cwd": "." }, "output": { "success": true, "stdout": "..." }, "error": null, "credits_used": 0.12 } ] } } ``` If the trace doesn't exist (or belongs to a different user), responds `404 { success: false, error: "Trace not found" }`. ### Implementation Notes - FTS5 indexes are created on first boot via `setupFullTextSearch()` in `backend/src/models/database/fts.js`. Existing rows are backfilled once; thereafter `AFTER INSERT / UPDATE / DELETE` triggers keep the FTS tables in sync with their source. - Keyword sanitization strips everything but `[a-zA-Z0-9_-]`, then appends `*` to each surviving token for prefix expansion. This is both safe (no FTS5 syntax injection) and forgiving (`pokemon` matches `pokemons`, `pokemon-red`). - All queries are scoped to `req.user.userId` — there is no cross-user visibility. `workflow_versions` doesn't store `user_id` directly, so the versions source joins through `workflows.user_id` for scoping. - Wrong-method requests (e.g. `POST /api/memory/search`) respond `405` with `{ success: false, error: "Method POST not allowed. Use GET ..." }` and an `Allow: GET` header — never an HTML error page. --- ## Experiment Routes Base path: `/api/experiments` Manages A/B testing experiments, evaluation datasets, and benchmarks for the evolution system. ### Create Eval Dataset **POST** `/datasets` - **Authentication**: Required - **Description**: Create an evaluation dataset (manual or synthetic) - **Body**: ```json { "name": "Dataset Name", "skillId": "skill-id", "category": "general", "source": "manual|synthetic|history|golden", "items": [ { "taskInput": "Test input", "expectedBehavior": "What a good response looks like", "metadata": {} } ], "splitConfig": { "train": 0.7, "test": 0.2, "validation": 0.1 } } ``` - **Notes** (`source: "manual"`): - Each item needs `taskInput` and `expectedBehavior`; `input` and `expectedOutput` are accepted as aliases. - `category` defaults to `manual`. `splitConfig` ratios must be between 0 and 1 and sum to 1; omitted, the split is 0.6 / 0.2 / 0.2. - A malformed request returns `400 { "error": "" }`. - **Response**: ```json { "success": true, "datasetId": "dataset-uuid" } ``` ### List Datasets **GET** `/datasets` - **Authentication**: Required - **Parameters**: - `skillId` (query, optional): Filter by skill - `category` (query, optional): Filter by category - **Response**: ```json { "success": true, "datasets": [ { "id": "dataset-id", "name": "Dataset Name", "skillId": "skill-id", "category": "general", "source": "manual", "itemCount": 100, "createdAt": "2024-01-01T00:00:00Z" } ] } ``` ### Generate Dataset **POST** `/datasets/generate` - **Authentication**: Required - **Description**: Auto-generate a dataset from goal history, golden standards, or synthetically - **Body**: ```json { "skillId": "skill-id", "source": "history|golden|synthetic", "category": "general", "provider": "openai", "model": "gpt-4" } ``` - **Response**: ```json { "success": true, "datasetId": "dataset-uuid" } ``` ### Get Dataset with Splits **GET** `/datasets/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Dataset ID - **Response**: ```json { "success": true, "dataset": { "id": "dataset-id", "name": "Dataset Name", "items": [] }, "splits": { "train": [], "test": [], "validation": [] } } ``` ### Delete Dataset **DELETE** `/datasets/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Dataset ID - **Response**: ```json { "success": true } ``` ### Get Benchmarks **GET** `/benchmarks` - **Authentication**: Required - **Description**: List golden standard benchmarks available for experiments - **Response**: ```json { "success": true, "benchmarks": [ { "id": "benchmark-id", "name": "Benchmark Name", "sourceGoalId": "goal-id", "createdAt": "2024-01-01T00:00:00Z" } ] } ``` ### Create Experiment **POST** `/` - **Authentication**: Required - **Body**: ```json { "name": "Experiment Name", "hypothesis": "Skill v2 will outperform v1 on accuracy", "type": "ab_test|benchmark|regression", "sourceGoalId": "goal-id", "benchmarkId": "benchmark-id", "skillId": "skill-id", "evalDatasetId": "dataset-id", "config": {} } ``` - **Response**: ```json { "success": true, "experiment": { "id": "experiment-id", "name": "Experiment Name", "status": "created", "createdAt": "2024-01-01T00:00:00Z" } } ``` ### List Experiments **GET** `/` - **Authentication**: Required - **Parameters**: - `status` (query, optional): Filter by status - `limit` (query, optional): Max results (default: 50) - **Response**: ```json { "success": true, "experiments": [ { "id": "experiment-id", "name": "Experiment Name", "status": "created|running|completed|failed", "type": "ab_test", "createdAt": "2024-01-01T00:00:00Z" } ] } ``` ### Get Experiment with Results **GET** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Experiment ID - **Response**: ```json { "success": true, "experiment": { "id": "experiment-id", "name": "Experiment Name", "status": "completed", "results": {}, "createdAt": "2024-01-01T00:00:00Z" } } ``` ### Run Experiment **POST** `/:id/run` - **Authentication**: Required - **Parameters**: - `id` (path): Experiment ID - **Body** (optional): ```json { "provider": "openai", "model": "gpt-4" } ``` - **Description**: Fire-and-forget experiment execution. Returns immediately while the experiment runs in the background. - **Response**: ```json { "success": true, "message": "Experiment run started" } ``` ### Delete Experiment **DELETE** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Experiment ID - **Response**: ```json { "success": true } ``` ### Get Experiment Runs **GET** `/:id/runs` - **Authentication**: Required - **Parameters**: - `id` (path): Experiment ID - **Description**: Get all run results for an experiment - **Response**: ```json { "success": true, "runs": [ { "id": "run-id", "experimentId": "experiment-id", "status": "completed", "results": {}, "startedAt": "2024-01-01T00:00:00Z", "completedAt": "2024-01-01T00:05:00Z" } ] } ``` --- ## FileSystem Routes Base path: `/api/filesystem` Provides a sandboxed file system for the built-in code editor. All file paths are relative to the configured workspace root. Path traversal outside the workspace is blocked (403). ### Get Settings **GET** `/settings` - **Authentication**: Required - **Description**: Returns the current workspace root directory and default root - **Response**: ```json { "workspaceRoot": "/home/user/.agnt/data/projects", "defaultRoot": "/home/user/.agnt/data/projects" } ``` ### Update Settings **PUT** `/settings` - **Authentication**: Required - **Description**: Update the workspace root directory - **Body**: ```json { "workspaceRoot": "/path/to/new/workspace" } ``` - **Response**: ```json { "success": true, "workspaceRoot": "/path/to/new/workspace" } ``` ### Get Directory Tree **GET** `/tree?dir=` - **Authentication**: Required - **Parameters**: - `dir` (query, optional): Relative path within workspace (default: root) - **Description**: Returns directory listing for the given relative path. Hidden files (dot-prefixed) are excluded. Directories are listed first. - **Response**: ```json { "items": [ { "name": "src", "type": "directory", "path": "src" }, { "name": "index.js", "type": "file", "path": "index.js" } ], "root": "/" } ``` ### Read File **GET** `/file?path=` - **Authentication**: Required - **Parameters**: - `path` (query, required): Relative file path within workspace - **Description**: Returns the content of a file as UTF-8 text - **Response**: ```json { "content": "file contents here...", "path": "src/index.js" } ``` - **Error** (404): File not found ### Write File **POST** `/file` - **Authentication**: Required - **Description**: Create or overwrite a file. Parent directories are created automatically. - **Body**: ```json { "path": "src/index.js", "content": "console.log('hello');" } ``` - **Response**: ```json { "success": true, "path": "src/index.js" } ``` ### Create Directory **POST** `/mkdir` - **Authentication**: Required - **Description**: Create a directory (recursive) - **Body**: ```json { "path": "src/components" } ``` - **Response**: ```json { "success": true, "path": "src/components" } ``` ### Rename / Move **POST** `/rename` - **Authentication**: Required - **Description**: Rename or move a file or directory - **Body**: ```json { "oldPath": "src/old-name.js", "newPath": "src/new-name.js" } ``` - **Response**: ```json { "success": true, "oldPath": "src/old-name.js", "newPath": "src/new-name.js" } ``` ### Delete File or Directory **DELETE** `/file?path=` - **Authentication**: Required - **Parameters**: - `path` (query, required): Relative path within workspace - **Description**: Delete a file or directory (recursive for directories) - **Response**: ```json { "success": true, "path": "src/old-file.js" } ``` - **Error** (404): File not found --- ### Search Files **GET** `/search` - **Authentication**: Required - **Description**: Recursively searches file/directory names under `dir` (default: workspace root). Case-insensitive substring match on the name. Returns a `truncated` flag when the result cap or entry-scan cap is hit (safety valve for pathological workspaces). - **Parameters**: - `q` (query, required): search substring - `dir` (query, optional): subdirectory relative to workspace root - **Response**: ```json { "items": [], "truncated": false } ``` ### Serve Raw File **GET** `/raw` - **Authentication**: Required - **Description**: Serves a workspace file with its native content type (images, videos, etc.) via streaming. Path traversal outside the workspace root is rejected with `403`. - **Parameters**: - `path` (query, required): file path relative to workspace root - **Response**: File bytes with the detected `Content-Type`; `400` if `path` is missing ### Upload Files **POST** `/upload` - **Authentication**: Required - **Content-Type**: `multipart/form-data` - **Description**: OS drag-and-drop uploads. Files land inside `dir` (relative to workspace root; empty string = root). Name collisions get a `" (n)"` suffix before the extension. - **Body**: - `dir` (string, optional): target directory relative to workspace root - `files` (file[]): one or more files - **Response**: List of stored files. `400` if no files are uploaded or `dir` resolves to a file instead of a directory --- ## Goal Routes Base path: `/api/goals` ### Health Check **GET** `/health` - **Authentication**: None - **Description**: Check if the goal service is running - **Response**: ```json { "status": "OK" } ``` ### Get All Goals **GET** `/` - **Authentication**: Required - **Description**: Retrieve all goals for the authenticated user. Includes aggregated token usage from goal evaluations. - **Response**: ```json [ { "id": "goal-id", "title": "Goal Title", "description": "Goal description", "status": "active|paused|completed|validated|needs_review|failed", "priority": "low|medium|high", "task_count": 5, "completed_tasks": 3, "input_tokens": 15000, "output_tokens": 3200, "total_tokens": 18200, "estimated_cost": 0.045, "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ] ``` ### Create Goal **POST** `/create` - **Authentication**: Required - **Body**: ```json { "title": "Goal Title", "description": "Goal description", "priority": "low|medium|high", "config": {} } ``` - **Response**: ```json { "success": true, "goal": { "id": "goal-id", "title": "Goal Title", "description": "Goal description", "status": "active", "priority": "medium", "config": {}, "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } } ``` ### Execute Goal **POST** `/:goalId/execute` - **Authentication**: Required - **Parameters**: - `goalId` (path): Goal ID - **Body** (optional): ```json { "provider": "anthropic", "model": "claude-sonnet-4-20250514" } ``` - **Description**: Start goal execution. Any failed or stuck tasks are reset to pending. The provider/model override the user's default settings for this execution and all downstream operations (task execution, evaluation, insight extraction, skill evolution). - **Response**: ```json { "message": "Goal execution started", "goalId": "goal-id", "status": "executing" } ``` ### Get Goal by ID **GET** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Goal ID - **Description**: Retrieve a specific goal with tasks and aggregated token usage from evaluations and task executions - **Response**: ```json { "goal": { "id": "goal-id", "title": "Goal Title", "description": "Goal description", "status": "active|paused|completed|validated|needs_review|failed", "priority": "low|medium|high", "config": {}, "tasks": [], "total_duration": 120, "credits_used": 120, "input_tokens": 15000, "output_tokens": 3200, "total_tokens": 18200, "estimated_cost": 0.045, "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } } ``` ### Get Goal Status **GET** `/:id/status` - **Authentication**: Required - **Parameters**: - `id` (path): Goal ID - **Description**: Get the current status of a goal - **Response**: ```json { "goalId": "goal-id", "status": "active|paused|completed|failed", "progress": 75, "lastExecution": "2024-01-01T00:00:00Z", "nextExecution": "2024-01-01T01:00:00Z" } ``` ### Pause Goal **POST** `/:id/pause` - **Authentication**: Required - **Parameters**: - `id` (path): Goal ID - **Description**: Pause an active goal - **Response**: ```json { "success": true, "message": "Goal paused successfully" } ``` ### Resume Goal **POST** `/:id/resume` - **Authentication**: Required - **Parameters**: - `id` (path): Goal ID - **Body** (optional): ```json { "provider": "anthropic", "model": "claude-sonnet-4-20250514" } ``` - **Description**: Resume a paused or failed goal. Failed/stuck tasks are reset to pending. Provider/model are forwarded to all downstream operations. - **Response**: ```json { "message": "Goal resumed" } ``` ### Delete Goal **DELETE** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Goal ID - **Description**: Delete a goal by ID - **Response**: ```json { "success": true, "message": "Goal deleted successfully" } ``` ### Execute Goal Autonomously (AGI Loop) **POST** `/:goalId/execute-autonomous` - **Authentication**: Required - **Parameters**: - `goalId` (path): Goal ID - **Body** (optional): ```json { "maxIterations": 50, "provider": "anthropic", "model": "claude-sonnet-4-20250514" } ``` - **Description**: Trigger autonomous goal execution. The system iterates through execute → evaluate → re-plan cycles until the goal passes evaluation or reaches `maxIterations`. Provider/model are forwarded to task execution, evaluation, re-planning, insight extraction, and skill evolution. Broadcasts real-time `goal:iteration_*` events via WebSocket. - **Response**: ```json { "message": "Autonomous goal execution started", "goalId": "goal-id", "maxIterations": 50 } ``` ### Get Iteration History **GET** `/:goalId/iterations` - **Authentication**: Required - **Parameters**: - `goalId` (path): Goal ID - **Description**: Get the full iteration history for an autonomous goal execution. Each iteration includes evaluation scores and re-planned task data. - **Response**: ```json { "success": true, "iterations": [ { "iteration": 1, "action": "Description of action taken", "result": {}, "evaluation": {}, "evaluation_score": 65.5, "evaluation_passed": 0, "world_state_snapshot": {}, "replanned_tasks": [], "duration_ms": 45000, "timestamp": "2024-01-01T00:00:00Z" } ] } ``` ### Get World State **GET** `/:goalId/world-state` - **Authentication**: Required - **Parameters**: - `goalId` (path): Goal ID - **Description**: Get the current world state snapshot for a goal's autonomous execution - **Response**: ```json { "success": true, "worldState": { "goalId": "goal-id", "currentIteration": 5, "state": {}, "updatedAt": "2024-01-01T00:00:00Z" } } ``` ### Revert to Iteration **POST** `/:goalId/revert/:iteration` - **Authentication**: Required - **Parameters**: - `goalId` (path): Goal ID - `iteration` (path): Iteration number to revert to - **Description**: Revert the goal's execution state to a specific iteration - **Response**: ```json { "success": true, "revertedToIteration": 3, "worldState": {} } ``` ### Review Goal **POST** `/:id/review` - **Authentication**: Required - **Parameters**: - `id` (path): Goal ID - **Description**: Approve or reject a goal that is in `needs_review` status - **Body**: ```json { "status": "approved|rejected", "feedback": "Optional feedback message" } ``` - **Response**: ```json { "success": true, "goal": { "id": "goal-id", "status": "approved", "reviewedAt": "2024-01-01T00:00:00Z" } } ``` ### Evaluate Goal **POST** `/:id/evaluate` - **Authentication**: Required - **Parameters**: - `id` (path): Goal ID - **Body**: ```json { "evaluation_type": "automatic", "provider": "anthropic", "model": "claude-sonnet-4-20250514" } ``` - **Description**: Evaluate a completed goal using LLM-as-judge. Each task output is scored against its success criteria, then an overall evaluation is produced. Token usage is tracked and stored per evaluation. The goal status is set to `validated` (score ≥ 70%) or `needs_review`. - **Response**: ```json { "passed": true, "status": "validated", "scores": { "overall": 85, "taskScores": {} }, "feedback": "Detailed evaluation feedback...", "input_tokens": 8000, "output_tokens": 1500, "total_tokens": 9500, "estimated_cost": 0.025 } ``` ### Get Evaluation Report **GET** `/:id/evaluation` - **Authentication**: Required - **Parameters**: - `id` (path): Goal ID - **Description**: Get evaluation report for a goal - **Response**: ```json { "goalId": "goal-id", "evaluations": [ { "timestamp": "2024-01-01T00:00:00Z", "score": 85, "metrics": {}, "recommendations": [] } ] } ``` ### Save as Golden Standard **POST** `/:id/golden-standard` - **Authentication**: Required - **Parameters**: - `id` (path): Goal ID - **Body**: ```json { "name": "Golden Standard Name", "description": "Description of the golden standard" } ``` - **Response**: ```json { "success": true, "goldenStandard": { "id": "golden-standard-id", "name": "Golden Standard Name", "description": "Description", "sourceGoalId": "goal-id", "createdAt": "2024-01-01T00:00:00Z" } } ``` ### Get Golden Standards **GET** `/golden-standards/list` - **Authentication**: Required - **Description**: Retrieve all golden standards - **Response**: ```json { "goldenStandards": [ { "id": "golden-standard-id", "name": "Golden Standard Name", "description": "Description", "sourceGoalId": "goal-id", "createdAt": "2024-01-01T00:00:00Z" } ] } ``` --- ### Get All Goals (Summary) **GET** `/summary` - **Authentication**: Required - **Description**: Lightweight goal list — summary rows for rendering lists without loading full task payloads - **Parameters**: - `includeDeleted` (query, optional): `true` to include soft-deleted goals - **Response**: ```json { "goals": [] } ``` --- ## Layout Routes Base path: `/api/layouts` Manages per-user widget layout pages for the dashboard. Each page stores a grid layout of widgets. ### Get All Layouts **GET** `/` - **Authentication**: Required - **Description**: Get all layout pages for the authenticated user - **Response**: ```json { "pages": [ { "id": "uuid", "user_id": "user-id", "page_id": "dashboard", "page_name": "Dashboard", "page_icon": "fas fa-th", "page_order": 0, "route": "/dashboard", "layout_data": "[...]", "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-01T00:00:00Z" } ] } ``` ### Create Layout **POST** `/` - **Authentication**: Required - **Description**: Create a new layout page - **Body**: ```json { "page_id": "my-page", "page_name": "My Page", "page_icon": "fas fa-th", "page_order": 1, "route": "/my-page", "layout_data": "[]" } ``` - **Response** (201): ```json { "message": "Layout created", "id": "uuid", "page_id": "my-page" } ``` ### Update Layout **PUT** `/:pageId` - **Authentication**: Required - **Parameters**: - `pageId` (path): Page identifier - **Description**: Update a layout page (upserts if not found) - **Body**: ```json { "page_name": "Updated Name", "page_icon": "fas fa-chart-bar", "page_order": 2, "route": "/updated-page", "layout_data": "[...]" } ``` - **Response**: ```json { "message": "Layout updated", "page_id": "my-page" } ``` ### Delete Layout **DELETE** `/:pageId` - **Authentication**: Required - **Parameters**: - `pageId` (path): Page identifier - **Description**: Delete a layout page - **Response**: ```json { "message": "Layout deleted", "page_id": "my-page" } ``` ### Reset Layout **POST** `/reset/:pageId` - **Authentication**: Required - **Parameters**: - `pageId` (path): Page identifier - **Description**: Reset a page to default layout - **Body**: ```json { "layout_data": "[]" } ``` - **Response**: ```json { "message": "Layout reset", "page_id": "my-page" } ``` ## Team Routes Base path: `/api/teams` An initial same-server team library, separate from personal canvas layouts and conversation groups. Team rows, membership, invitations, assets, immutable revisions and audit events persist in `teams.db` beneath the configured data directory. No real personal-resource execution or cross-instance synchronization is granted by these routes. Every route requires the normal authenticated session. Team lookups are membership-scoped; nonmembers receive 404. Viewers may read all team library assets. Members may edit them. Owners/admins manage invitations; only the owner removes members. No local file paths or credentials are dereferenced from asset bodies. **GET** `/` - **Authentication**: Required - Lists teams containing the current user; returns id, name, owner_id and membership role. **POST** `/` - **Authentication**: Required - Body: `{ name }` (1–100 characters). Creates a private team with this user as protected owner. **POST** `/accept` - **Authentication**: Required - Body: `{ token }`. Consumes a single-use invitation only when the authenticated email matches. Expired/revoked/used tokens return 404; mismatched email returns 403. **GET** `/:teamId/members` - **Authentication**: Required - Team members only. Returns membership identities, email and role. **DELETE** `/:teamId/members/:memberId` - **Authentication**: Required - Owner only. Cannot remove the owner. Removes team access while retaining shared asset history. **GET** `/:teamId/invitations` - **Authentication**: Required - Owner/admin only. Lists unexpired pending invitations without tokens or hashes. **POST** `/:teamId/invitations` - **Authentication**: Required - Owner/admin only. Body: `{ email, role: 'viewer' | 'member' | 'admin' }`. - Returns one-time plaintext token, id, email, role and expiry. Only its SHA-256 hash is stored. The token is sent by the owner privately; this endpoint does not send email. Seven-day expiry; duplicate pending invitations return 409. **DELETE** `/:teamId/invitations/:id` - **Authentication**: Required - Owner/admin only. Invalidates the pending invitation. **GET** `/:teamId/assets` - **Authentication**: Required - Team members only. Lists up to 500 asset metadata rows (no body). **GET** `/:teamId/assets/:id` - **Authentication**: Required - Team members only. Optional positive integer `revision` selects an immutable historical body; default is current revision. **POST** `/:teamId/assets` - **Authentication**: Required - Owner/admin/member only. Body: `{ id?, name, kind, content, expectedRevision? }`. - Name: 1–180 characters. Kinds: markdown, text, html, csv, agent, workflow, tool, skill, widget, goal. Content is an inert UTF-8 definition/document, maximum 200 KB. - Existing asset requires its expected revision; mismatch returns 409 with no write. Each successful write creates a new immutable revision. No tool dispatch, credential binding, personal object mutation, or execution occurs. **DELETE** `/:teamId/assets/:id` - **Authentication**: Required - Owner/admin, or the member who created the asset (author of revision 1); anyone else gets 403. Deletes the asset and all its revisions and records an `asset.deleted` event. Returns `{ deleted: true, id }`. - The published copy of a teamspace item (pinned by a publish) returns 409: delete the item in its teamspace instead. Teamspace docs are deleted through their teamspace (404 here). **GET** `/:teamId/activity` - **Authentication**: Required - Team members only. Last 100 attributable team events, without asset body or invitation token. Membership and writes are checked in serialized SQLite transactions. Team endpoints set `Cache-Control: no-store`. Hosted-team entitlement/seat accounting, shared workflow execution, per-resource guest exceptions, automatic mail and independent cloud tenancy are not implemented by this first library slice. ### Teamspace collaboration (chat, board, docs, inbox) Served by the team's own instance (`AGNT_TENANT_SLUG` set), under the same router as the routes above. Every `/:teamId/workspaces/:workspaceId/...` path is checked against the cloud first: team access, then the per-workspace capability (`resources.read` on GET, `resources.write` otherwise). Viewers read; owners, admins and members write. People named in a mention or an assignment must be members of the team; agents must be native agents of that teamspace. A realtime `team:space` signal (`{teamId, workspaceId, kind, taskId?, docId?}`, ids only) goes to every member on each change, and `team:inbox` (`{teamId}`) to anyone whose inbox changed; clients refetch through these routes. Mentions and assignees are `{ kind: 'person' | 'agent', id }`. Task statuses: `todo`, `doing`, `review`, `done`. **Chat** - **GET** `/:teamId/workspaces/:workspaceId/messages?before=`: the latest 200 messages, oldest first. - **POST** `/:teamId/workspaces/:workspaceId/messages`: body `{ body, mentions? }` (1–4000 characters, at most 20 mentions). Each mentioned teammate gets an inbox item. Each mentioned agent (up to 3) gets a card made from the message and starts on it (see Agents on cards). - **DELETE** `/:teamId/workspaces/:workspaceId/messages/:messageId`: the author, or an owner/admin. **Board** - **GET** `/:teamId/workspaces/:workspaceId/tasks`: up to 500 cards, with comment counts. - **GET** `/:teamId/workspaces/:workspaceId/tasks/:taskId`: one card with its thread. - **POST** `/:teamId/workspaces/:workspaceId/tasks`: body `{ title, status?, assignee?, due?, sourceMessageId? }`. Assigning a teammate notifies them; assigning an agent starts it. - **PATCH** `/:teamId/workspaces/:workspaceId/tasks/:taskId`: body `{ expectedRevision, title?, status?, assignee?, due? }`. A stale `expectedRevision` returns 409 `revision_conflict` and writes nothing. - **DELETE** `/:teamId/workspaces/:workspaceId/tasks/:taskId`: the card's creator, or an owner/admin. - **POST** `/:teamId/workspaces/:workspaceId/tasks/:taskId/comments`: body `{ body, mentions? }`. Notifies the assignee, the creator and anyone mentioned (never the author). An @agent hands the card to that agent. - **POST** `/:teamId/workspaces/:workspaceId/tasks/:taskId/approve`: body `{ saveAsDoc? }`. Only when an agent result is waiting (else 409 `not_waiting`). Moves the card to `done`; with `saveAsDoc` the result becomes a teamspace doc. Returns `{ task, doc }`. - **POST** `/:teamId/workspaces/:workspaceId/tasks/:taskId/send-back`: body `{ note? }`. The agent runs again with the note. **Running teamspace items.** In a team scope (`X-AGNT-Team-ID`), owners, admins and members run agents, workflows and goals directly (`/workflows/:id/start`, `/agents/:id/chat`, `/goals/:id/execute`, ...); nothing has to be published first. A run acts as the person who started it (`runActor.js`): for anyone but the instance owner, memberIsolation runs its code, shell and files in the kernel tool sandbox, refuses SQL and refuses plugins the owner has not approved, exactly as in that member's chat. It uses the teamspace's connections, which the owner controls: their team policy "Run workflows and agents" (`workflows.run`; off → 403 `{ code: 'team_policy_denied', permission }`) and each member's `runs.execute` and `connections.use` in that teamspace (Team → Members → capabilities). Work that continues without a request (a listening workflow's triggers, restores after a restart, a goal run by a schedule) keeps acting as the last person who switched it on, changed it or ran it. Viewers cannot run. Publishing (`POST .../native/:kind/:id/publish`, owners/admins) is still how an item gets an approved revision on a team connection; an agent on a board card runs its published revision when it has one, and otherwise its current definition as the teammate who assigned it. **Deleting in a teamspace.** Agents: an owner/admin, or the member who created the agent (recorded at creation; agents created before this was recorded are owner/admin only). Board cards, docs and library assets follow the same rule. **Agents on cards.** The agent's PUBLISHED revision runs through the same path as `/native/agent/:id/run` (team connection, recorded in `team_native_runs`), after the response. An agent with no published revision runs its current definition as the teammate who assigned the card (same rules as running it directly, see "Running teamspace items"). The card shows `agentState` `running`, then `waiting` with the result in its thread and an `approval` inbox item for the card's creator, or `blocked` with a plain reason (for example, not published yet). Nothing reaches `done` without a person. **Docs** (versioned team assets linked to one teamspace; excluded from `/assets`, so they are reachable only through their teamspace) - **GET** `/:teamId/workspaces/:workspaceId/docs`: names and revisions, newest first. - **GET** `/:teamId/workspaces/:workspaceId/docs/:docId`: the current revision with its content. - **POST** `/:teamId/workspaces/:workspaceId/docs`: body `{ name, content? }` (content at most 200 KB). - **PUT** `/:teamId/workspaces/:workspaceId/docs/:docId`: body `{ expectedRevision, name?, content? }`. Each save is a new immutable revision; a stale revision returns 409 `revision_conflict`. - **DELETE** `/:teamId/workspaces/:workspaceId/docs/:docId`: the doc's creator, or an owner/admin. Unlinks it from the teamspace; its revisions are kept. **People** - **GET** `/:teamId/workspaces/:workspaceId/people`: `{ memberIds, agents: [{ id, name, status }] }` for mentions and assignment. Names come from `GET /:teamId/members`. **Inbox** (per person, across the team) - **GET** `/:teamId/inbox`: the latest 200 items: `{ id, kind, actor, summary, workspaceId, target, state, read, createdAt }`. Kinds: `mention`, `assigned`, `approval` (state `pending` / `approved` / `sent_back` / `superseded`), `run`, `shared`. - **POST** `/:teamId/inbox/:itemId/read`, **POST** `/:teamId/inbox/read-all`: only your own items. ## Workspace Routes Base path: `/api/workspaces` Cross-device persistence for the Workspaces page (canvas tabs). Backed by the existing `widget_layouts` table, with rows namespaced by `route = 'workspace:'` (no schema migration). Conflict resolution is last-write-wins per workspace on an `updatedAt` epoch carried inside each workspace's data. ### Get Workspaces **GET** `/` - **Authentication**: Required - **Description**: Get all of the authenticated user's synced workspaces - **Response**: ```json { "workspaces": [ { "id": "ws_abc123", "name": "Coding", "order": 0, "widgets": [], "ai": { "provider": "groq", "model": "llama-3.1-70b" }, "updatedAt": 1730000000000 } ] } ``` ### Sync Workspaces **PUT** `/` - **Authentication**: Required - **Description**: Whole-set upsert of the user's workspaces (last-write-wins per workspace on `updatedAt`). `deletedIds` removes workspaces so a tab closed on one device does not resurrect from another. - **Body**: ```json { "workspaces": [ { "id": "ws_abc123", "name": "Coding", "order": 0, "widgets": [], "ai": null, "updatedAt": 1730000000000 } ], "deletedIds": ["ws_old"] } ``` - **Response**: ```json { "message": "Workspaces synced", "count": 1, "deleted": 1 } ``` ### Delete Workspace **DELETE** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): the workspace id - **Response**: ```json { "message": "Workspace deleted", "id": "ws_abc123" } ``` --- ## Routing Routes Base path: `/api/routing` Read API over **dynamic provider routing** — the decision log, not the switch. The routing mode itself is an ordinary user setting (`routingMode` / `routingPolicy` on `PUT /api/user/settings`); these endpoints only answer *what has the router been doing, and what did it save*. ### How routing decides A turn is routed by the first scope that expresses an opinion — request, then conversation, then agent, then the account default. `pinned` means "use this exact model" and ends the search; `default` means "keep looking"; `dynamic` hands the choice to the router. A request that names a concrete `provider` **and** `model` without naming a `routingMode` is treated as pinned. That is deliberate and load-bearing: every integration written before this feature does exactly that, so enabling routing cannot silently relocate an existing API consumer's traffic. ### Honest savings `savedUsd` sums `baseline − chosen` over decisions where **both** costs were known, and reports `unpricedDecisions` separately. A model with no published price contributes to the second number, never to the first — treating unknown as zero is how routing savings claims become unreproducible. ### Get Routing Summary **GET** `/summary` - **Authentication**: Required - **Parameters**: - `hours` (query, optional): lookback window, default `24`, capped at 90 days - `shadow` (query, optional): `1` for decisions that were computed but not executed; omit for all - **Response**: ```json { "decisions": 412, "savedUsd": 9.86, "predictedUsd": 2.14, "unpricedDecisions": 3, "distribution": [ { "provider": "anthropic", "model": "claude-haiku-4-5", "calls": 251, "share": 0.609 } ] } ``` ### Get Recent Routing Decisions **GET** `/recent` - **Authentication**: Required - **Parameters**: - `limit` (query, optional): default `20`, max `200` - **Response**: array of decisions, newest first. Each carries the chosen tier **and** the baseline the account default would have used, so a decision can be graded after the fact rather than merely observed. ```json [ { "id": "…", "origin": "orchestrator", "mode": "dynamic", "policy": "balanced", "stake": "normal", "verifiability": "subjective", "chosen": { "provider": "anthropic", "model": "claude-haiku-4-5", "reason": "cache-warm" }, "baseline": { "provider": "openai", "model": "gpt-5.2" }, "predictedCostUsd": 0.0041, "baselineCostUsd": 0.0192, "candidatesConsidered": 14, "shadow": false, "ts": "2026-08-14 17:22:03" } ] ``` --- ## Cluster Routes Base path: `/api/cluster` Multi-node execution. One AGNT install is the **primary** — it owns the database, the sockets, and the goal loop — and any number of **worker** nodes claim tasks from it over this API and execute them with their own agents and their own provider credentials. **No database is shared.** A worker never writes to the primary's SQLite file; it asks for a task, does the work locally, and posts the result back. That is why there is no shared-storage requirement, no Redis, and no distributed lock. **Zero config for single-machine installs.** Every AGNT install is a primary with no workers by default. Nothing polls, no extra queries run, and there is no new way to fail. The cluster code is inert until someone deliberately enrolls a worker. --- ### Architecture ``` ┌──────────────────────────────────────────────────────────────┐ │ PRIMARY (your machine) │ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────────────────────┐ │ │ │ Goals DB │ │ Task │ │ /api/cluster/* │ │ │ │ (SQLite) │ │ Queue │ │ enroll / claim / renew / │ │ │ │ │ │ │ │ complete / release │ │ │ └──────────┘ └──────────┘ └──────────────────────────┘ │ │ │ ▲ │ │ │ claim/complete │ HTTP │ │ ▼ │ │ │ ┌─────────────────┐ │ │ │ │ LLM Ledger │ │ │ │ │ (spend by node)│ │ │ │ └─────────────────┘ │ │ └──────────────────────────────────────────┼────────────────────┘ │ ┌────────────────────────────┼───────────────────┐ │ │ │ ┌────────┴─────────┐ ┌─────────┴────────┐ │ │ WORKER A │ │ WORKER B │ │ │ (Hetzner VPS) │ │ (second laptop) │ │ │ │ │ │ │ │ Own agents │ │ Own agents │ │ │ Own provider keys│ │ Own provider keys│ │ │ Own SQLite │ │ Own SQLite │ │ │ Own ENCRYPTION_ │ │ Own ENCRYPTION_ │ │ │ KEY │ │ KEY │ │ └───────────────────┘ └───────────────────┘ │ │ │ │ └────────────────────────────┴───────────────────┘ ``` **Pull, not push.** Workers ask for work; the primary does not track what is alive or schedule assignments. Adding capacity is starting a container with two environment variables. Removing capacity is turning it off — the lease expires and the work returns to the queue on its own. --- ### Security Model #### Two credentials, two audiences | Route | Caller | Credential | Middleware | |---|---|---|---| | `POST /enroll`, `GET /nodes` | Signed-in operator (human) | Normal session token (`Authorization: Bearer `) | `authenticateToken` | | All other routes | Worker node (machine) | Node grant (`Authorization: Bearer `) | `authenticateClusterNode` | #### Node grants - Signed with `CLUSTER_SECRET` — a per-install key generated on first boot, **never** `JWT_SECRET`. Reusing `JWT_SECRET` would mean a leak of either credential compromises both, and a stolen user session could be replayed as a node token. - Algorithm allowlist: `['HS256']` only. Without an explicit allowlist, jsonwebtoken honours the `alg` header the token itself carries, including `none`. - Audience: `agnt-cluster-node`. A session token cannot claim work; a node grant cannot reach user routes. - The node id is **inside** the grant. A worker cannot choose its own identity, so it cannot renew or release another node's claims. - Resolved via `secretResolver` cascade: `process.env` → keyfile (`/secrets/CLUSTER_SECRET`) → CSPRNG on first boot (persisted with exclusive-create `wx` flag so concurrent processes don't race). #### What a forged grant gets you - A grant forged with the user's `JWT_SECRET` → **401** (wrong secret entirely). - A grant forged with a guessed `CLUSTER_SECRET` → **401** (signature mismatch). - A valid session token on a node route → **401** (audience mismatch). - A valid node grant on a user route → **401** (middleware mismatch). --- ### Claims: Leases, Not Locks A claim carries an expiry (default 120 seconds). A node that stops renewing stops owning, so a worker that crashes needs no heartbeat protocol and no operator — its task returns to the queue on its own once the lease lapses. | Property | Guarantee | |---|---| | **Exactly-once execution** | Strict claims on the pull path — two processes sharing one node id cannot both take a task. Proven by a 4-way live race, not just unit tests. | | **Crash recovery** | Lease expires → task returns to `pending` → anyone takes it. | | **Retry bound** | `attempt_count` caps how many times a task that kills its claimant may be retried (default 3). | | **Owner-scoped renewal** | Only the holder can renew. Another node gets `409 claim_lost`, never `401` — the grant is valid, the claim is not. | | **Stale overwrite protection** | A node whose lease lapsed mid-task gets `409 claim_lost` on `/complete` rather than overwriting a fresher result. | #### Re-entrancy modes `TaskModel.claim()` accepts `{ reentrant: true | false }`: | Caller | Mode | Why | |---|---|---| | `claimNext` (pull path / workers) | **strict** (`reentrant: false`) | Two processes may legitimately share one node id (same grant in two containers). A live lease means somebody is working. | | `TaskOrchestrator` (local goal loop) | **re-entrant** (`reentrant: true`, default) | One process, sequential claims. Re-entrancy buys resume: kill AGNT mid-task, restart inside the lease window, and the goal picks up instead of stalling on a lease it owns. | --- ### Setting Up a Worker #### Step 1: Enrol on the primary From your running AGNT (the primary), as a signed-in user: ```bash curl -X POST http://localhost:3333/api/cluster/enroll \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"label": "hetzner-fsn1"}' ``` Response: ```json { "success": true, "nodeId": "node_a1b2c3d4e5f6...", "token": "eyJhbGciOiJIUzI1NiIs...", "expiresAt": "2026-11-17T12:00:00.000Z", "env": { "AGNT_NODE_ROLE": "worker", "AGNT_CLUSTER_PRIMARY": "http://your-ip:3333", "AGNT_CLUSTER_TOKEN": "eyJhbGciOiJIUzI1NiIs..." } } ``` The token is returned **once** and not stored on the primary. Treat it like a password. #### Step 2: Start the worker Set the three env vars on the second machine and start AGNT normally: ```bash # Docker docker run \ -e AGNT_NODE_ROLE=worker \ -e AGNT_CLUSTER_PRIMARY=http://your-ip:3333 \ -e AGNT_CLUSTER_TOKEN=eyJhbGciOiJIUzI1NiIs... \ agnt # Or from source (second laptop / VPS) export AGNT_NODE_ROLE=worker export AGNT_CLUSTER_PRIMARY=http://your-ip:3333 export AGNT_CLUSTER_TOKEN=eyJhbGciOiJIUzI1NiIs... npm start # Or Windows cmd set AGNT_NODE_ROLE=worker set AGNT_CLUSTER_PRIMARY=http://your-ip:3333 set AGNT_CLUSTER_TOKEN=eyJhbGciOiJIUzI1NiIs... npm start ``` The worker boots, sees `AGNT_NODE_ROLE=worker`, validates its grant against the primary via `GET /whoami`, and begins the pull loop: poll → claim → execute → report back. #### Step 3: Create a goal — tasks fan out automatically Create any goal on the primary (via the UI or API). The goal system breaks it into tasks. Your machine and every enrolled worker race to claim them. A task goes to whoever asks first. #### Environment variables | Variable | Required | Description | |---|---|---| | `AGNT_NODE_ROLE` | Yes | `worker` to enable the pull loop. Anything else (including unset or misspelled) means `primary`. | | `AGNT_CLUSTER_PRIMARY` | Yes (workers) | Base URL of the primary, e.g. `http://192.168.1.50:3333` or `https://agnt.example.com` | | `AGNT_CLUSTER_TOKEN` | Yes (workers) | The node grant from `/enroll`. | | `AGNT_NODE_LABEL` | No | Display name in the fleet view. Defaults to `os.hostname()`. | | `AGNT_SPEND_LIMIT_USD` | No | Hard ceiling per local day. No new work is admitted at or above it; **work in flight always finishes** — a running task is never killed for a billing reason. | | `AGNT_SPEND_SOFT_LIMIT_USD` | No | Warning threshold. Logs once per day, never stops anything. | --- ### Spend Attribution & Admission Every LLM call a worker makes is reported in the `/complete` payload's `spend` array. The primary re-prices each row with its own cost catalogue and records it with the **worker's** `node_id` — so fleet cost breakdown is a single query against `llm_calls`. **Admission check:** at claim time, if `AGNT_SPEND_LIMIT_USD` is set, the primary sums today's spend and refuses new claims at or above the ceiling. Returns `429` with `code: "spend_ceiling_reached"`. This check **fails closed**: a limit that is configured but cannot be evaluated stops new claims, because a spend check that fails open risks a node with live provider credentials, no ceiling, and no observer. Contrast with `planEntitlements.js`, which **fails open** (unknown plan → entitled) — different question, opposite answer. --- ### Worker Pull Loop (ClusterWorker.js) The worker runs an indefinite loop: 1. `POST /claim` → if `204`, backoff (jittered 2–10s so N workers don't synchronise into a herd). 2. Got a task → start a lease-renewal timer (every `leaseMs / 2`, so 60s by default). If renewal returns `409 claim_lost`, abort the work. 3. Execute the task using the worker's own agents and provider credentials. 4. `POST /complete` with the result and the spend array. 5. Loop. On grant expiry or repeated auth failures the worker stops polling and logs the reason. It does not retry — the operator re-enrols. --- ### Endpoints #### `POST /enroll` - **Auth**: Session token (operator) - **Description**: Mint a node grant. The primary generates the node id and signs the grant with `CLUSTER_SECRET`. The token is returned once and not stored. **Request body:** ```json { "label": "hetzner-fsn1", "ttlDays": 90 } ``` Both fields optional. `label` defaults to empty (the worker will use its hostname). `ttlDays` defaults to 90. **Response `200`:** ```json { "success": true, "nodeId": "node_a1b2c3d4e5f6...", "token": "eyJhbGciOiJIUzI1NiIs...", "expiresAt": "2026-11-17T12:00:00.000Z", "env": { "AGNT_NODE_ROLE": "worker", "AGNT_CLUSTER_PRIMARY": "http://your-ip:3333", "AGNT_CLUSTER_TOKEN": "eyJhbGciOiJIUzI1NiIs..." } } ``` --- #### `GET /nodes` - **Auth**: Session token (operator) - **Description**: Every node this primary has heard from, most recent first, plus `self`. **Observational only** — the list is an in-memory map rebuilt from traffic and empties when the primary restarts. Nothing decides anything from it; enrolment is the grant, the claim is the permission, the lease is the liveness signal. **Response `200`:** ```json { "success": true, "self": { "nodeId": "23cbd2e763cf07a7...", "role": "primary", "label": "DESKTOP-38VA1OR" }, "nodes": [ { "nodeId": "node_a1b2c3d4e5f6...", "label": "hetzner-fsn1", "userId": "", "lastSeen": "2026-08-19T14:30:00.000Z", "stale": false, "claims": 12, "completions": 10, "failures": 2 } ] } ``` A node is marked `stale: true` if its last contact was >5 minutes ago. --- #### `GET /whoami` - **Auth**: Node grant - **Description**: Lets a worker confirm its grant is valid before starting the poll loop. The worker calls this on boot. **Response `200`:** ```json { "success": true, "nodeId": "node_a1b2c3d4e5f6...", "userId": "", "label": "hetzner-fsn1", "role": "worker" } ``` **Response `401`:** ```json { "error": "Invalid or expired cluster node grant.", "code": "cluster_grant_invalid" } ``` --- #### `POST /claim` - **Auth**: Node grant - **Description**: Claim at most one task, scoped to the goals of the account the grant was issued to. Uses **strict** (non-re-entrant) claiming so two processes sharing one node id cannot both take the same task. **Request body:** ```json { "goalId": "", "leaseMs": 120000 } ``` Both fields optional. Omit `goalId` to claim from any executing goal. `leaseMs` defaults to 120000 (2 minutes). **Response `200` (task claimed):** ```json { "success": true, "task": { "id": "", "goal_id": "", "title": "Research competitor X", "description": "...", "status": "running", "order_index": 0, "dependencies": "[]", "required_tools": "[\"web_search\", \"web_scrape\"]", "attempt_count": 1, "claimed_by": "node_a1b2c3d4e5f6...", "claim_expires_at": 1787312400000 }, "goal": { "id": "", "title": "Competitive analysis", "description": "...", "success_criteria": "{...}" }, "leaseMs": 120000 } ``` **Response `204`** — No work available. The worker should backoff (jittered 2–10 seconds). **Response `429`:** ```json { "error": "Spend ceiling reached for today.", "code": "spend_ceiling_reached" } ``` --- #### `POST /renew` - **Auth**: Node grant - **Description**: Extend the lease on a task this node holds. Workers call this every `leaseMs / 2` while executing. If the claim has moved on (another node took it after the lease lapsed), returns `409` — **never** `401`. **Request body:** ```json { "taskId": "", "leaseMs": 120000 } ``` **Response `200`:** ```json { "success": true, "expiresAt": 1787312520000 } ``` **Response `409`:** ```json { "error": "This node no longer holds the claim on this task.", "code": "claim_lost" } ``` When the worker receives `409 claim_lost`, it **aborts** the in-progress execution immediately — the task has been reassigned. --- #### `POST /release` - **Auth**: Node grant - **Description**: Voluntarily hand a claim back instead of waiting out the lease. Used when a worker knows it cannot complete a task (e.g. missing provider credentials for the required model). **Request body:** ```json { "taskId": "" } ``` **Response `200`:** ```json { "success": true } ``` --- #### `POST /complete` - **Auth**: Node grant - **Description**: Report the outcome of an executed task. Ownership is re-checked at write time, so a node whose lease lapsed mid-task gets `409 claim_lost` rather than overwriting a fresher result. **Request body:** ```json { "taskId": "", "status": "completed", "result": { "content": "Competitor X has 45% market share...", "artifacts": [] }, "spend": [ { "provider": "anthropic", "model": "claude-sonnet-4-5-20250929", "originId": "", "input_tokens": 12500, "output_tokens": 3200, "status": "ok" } ] } ``` For failed tasks: ```json { "taskId": "", "status": "failed", "error": "Provider returned 429: rate limit exceeded", "spend": [] } ``` **Response `200`:** ```json { "success": true } ``` **Response `409`:** ```json { "error": "This node no longer holds the claim on this task.", "code": "claim_lost" } ``` **Spend handling:** the `spend` array carries the LLM call rows the worker measured locally. The primary re-prices each row with its own cost catalogue (so pricing is consistent fleet-wide) and records them in the `llm_calls` table with `node_id` set to the **worker's** node id. Fleet cost breakdown is then a single query: ```sql SELECT node_id, SUM(cost_usd) AS total FROM llm_calls WHERE origin_id = '' GROUP BY node_id; ``` --- ### Error Reference | Status | Code | Meaning | Action | |---|---|---|---| | `200` | — | Success | — | | `204` | — | No work available | Backoff 2–10s (jittered) | | `400` | `missing_task_id` | `taskId` not provided | Fix the request | | `401` | `cluster_grant_invalid` | Grant expired, wrong secret, wrong audience, or session token on a node route | Re-enrol on the primary | | `404` | `task_not_found` | Task id does not exist | Drop the reference | | `409` | `claim_lost` | This node no longer holds the claim (lease lapsed, another node took it) | Abort in-progress work; do NOT retry the same task | | `429` | `spend_ceiling_reached` | Daily spend limit hit | Backoff; wait for the next UTC day or raise `AGNT_SPEND_LIMIT_USD` | | `500` | — | Server error | Retry with backoff | --- ### Operational Guide #### Monitoring the fleet ```bash # From the primary, as a signed-in user: curl -s http://localhost:3333/api/cluster/nodes \ -H "Authorization: Bearer " | jq . ``` Shows `self` (the primary) and every worker that has talked to it since the last restart, with claim/completion/failure counts and staleness. #### Revoking a worker There is no explicit revocation endpoint. The grant has a TTL (default 90 days). To cut a worker off immediately: 1. Restart the primary — this rotates `CLUSTER_SECRET` if the keyfile is deleted first (`/secrets/CLUSTER_SECRET`). 2. Re-enrol any workers you want to keep. #### Scaling - **Add capacity:** enrol a new worker, start it. It begins pulling immediately. - **Remove capacity:** stop the worker. Its leased tasks return to the queue after 120s (or sooner if `attempt_count` has been reached). - **Same grant, multiple containers:** works, but each container shares the node id, so the strict claim ensures only one of them gets each task. #### Failure modes | Failure | Recovery | |---|---| | Worker crashes mid-task | Lease expires (120s) → task returns to queue → any node takes it | | Worker loses network | Same as crash — lease expiry is the only liveness signal | | Primary restarts | Fleet view empties (it's in-memory). Workers continue polling — their grants are still valid. No tasks are lost — they're in SQLite. | | Grant expires | Worker gets `401` on next poll → stops the loop → logs the reason. Operator re-enrols. | | Spend ceiling hit | `429` on `/claim` → worker backs off. In-flight work always completes. | #### Database columns added | Table | Column | Type | Description | |---|---|---|---| | `tasks` | `claimed_by` | TEXT | Node id of the current claimant, or NULL | | `tasks` | `claim_expires_at` | INTEGER | Epoch ms when the lease lapses | | `tasks` | `attempt_count` | INTEGER | How many times this task has been claimed | | `llm_calls` | `node_id` | TEXT | Which node made this LLM call | All columns are additive. Old code ignores them. A downgrade needs no data migration. --- ## Ledger Routes Base path: `/api/ledger` The execution ledger (PRD-122): one row per LLM request/response round-trip, across **every** execution path — orchestrator chat, agent runs, workflow LLM nodes, goal tasks and goal evaluations. Before this existed, four subsystems each kept their own books and two kept none, so "what did this cost?" was not answerable from AGNT's own data. Every row is written by exactly one function (`services/execution/LedgerRecorder.js`); `backend/src/services/execution/ledgerContracts.spec.js` fails the build if a second write path appears. ### The cost triple Every monetary response carries three numbers, and consumers must render all three: | Field | Meaning | |---|---| | `costUsd` | Charged spend. Excludes subscription-seat usage. | | `unpricedCalls` | Calls whose model has no pricing metadata. Their cost is **unknown**, stored as `NULL`, and deliberately NOT folded into the total as zero. | | `notionalUsd` | What subscription-provider usage (Claude Code, Codex, Gemini CLI…) *would* have cost on a metered API. Not money charged. | A total that silently omits `unpricedCalls` reintroduces the defect this ledger was built to fix, so surfaces should read `"$1.23 · 3 calls unpriced"` rather than presenting a bare figure. ### Get Spend Summary **GET** `/summary` - **Authentication**: Required - **Parameters**: - `window` (query, optional): `today` (default), or `7d` / `30d` style - `since` / `until` (query, optional): explicit bounds; override `window` **`Nd` means N CALENDAR DAYS back to local midnight — not a rolling N×24 hours.** The dashboard usage chart asks for calendar dates and the rollup groups them with `DATE(..., 'localtime')`, so a rolling window would begin up to 24 hours later than the chart's and the two figures would never reconcile; anyone comparing them would reasonably conclude one was broken. Same boundary, same buckets. Pinned by `LedgerRoutes.test.js`. - **Response**: ```json { "success": true, "costUsd": 3.4212, "notionalUsd": 0.88, "uncachedCostUsd": 15.22, "savedUsd": 11.80, "notionalUncachedUsd": 4.10, "notionalSavedUsd": 3.22, "unpricedCalls": 2, "calls": 147, "inputTokens": 1840233, "outputTokens": 92011, "cacheReadTokens": 1502000, "cacheWriteTokens": 210500, "ledgerHealth": { "totalFailures": 0, "byProcess": [], "thisProcess": { "recorded": 147, "failed": 0, "lastError": null, "scope": "backend", "pid": 24924 } } } ``` `savedUsd` is what prompt caching saved: the same pricing function run with and without the cache breakdown, so the two can never drift. It is negative on a turn that first writes a cache prefix (Anthropic cache writes cost 1.25x/2.0x), which is reported honestly rather than clamped to zero. **Charged and notional are separate axes throughout.** `savedUsd` pairs with `costUsd`; `notionalSavedUsd` pairs with `notionalUsd`. Crossing them would produce arithmetic nonsense, and reporting only the charged axis would make savings a structural zero for every subscription user — the exact audience for whom savings is the only meaningful money on the page. **`ledgerHealth.totalFailures` is the tripwire.** A non-zero value means ledger writes are being dropped and every total above is understated. It is deliberately **cross-process**. AGNT runs the workflow engine as a separate OS process (`backend/src/workflow/WorkflowProcess.js`) from the HTTP API (`backend/server.js`). Both write LLM calls to the same SQLite file but share no memory, so an in-process counter answering this endpoint would report a serene zero while the workflow process dropped every write — a tripwire that cannot trip for the path most likely to break. `byProcess` therefore reads from the shared `ledger_write_failures` table, keyed by process role. `thisProcess` is the in-memory counter for whichever process served the request. It is kept because it still works when the database itself is the broken thing, and it carries an explicit `scope` so it can never be mistaken for a global figure. ### Get Spend Breakdown **GET** `/breakdown` - **Authentication**: Required - **Parameters**: - `groupBy` (query, optional): one of `origin` (default), `provider`, `model`, `origin_id`, `conversation`, `day` - `window` / `since` / `until` (query, optional): as above - **Response**: `{ "success": true, "groupBy": "origin", "rows": [ { "bucket": "goal_task", ...cost triple } ] }` - **Errors**: `400` if `groupBy` is not whitelisted. It is the one value that reaches SQL as an identifier rather than a bound parameter, so the whitelist is what makes it safe. Origins: `chat`, `agent`, `goal_task`, `goal_eval`, `workflow_node`, `insight`, `system`. ### Get Run Tree **GET** `/tree/:executionId` The run tree rooted at the given execution, with per-node and subtree cost. Resolves the whole tree from any member, not just the root. - **Authentication**: Required - **Response**: ```json { "success": true, "rootExecutionId": "uuid", "nodes": [ { "id": "uuid", "parentExecutionId": "uuid|null", "agentName": "Research Assistant", "origin": "agent", "status": "completed", "provider": "anthropic", "model": "claude-sonnet-4-5-20250929", "ledger": { "costUsd": 0.42, "calls": 6, "unpricedCalls": 0 } } ], "unattached": [ { "origin": "goal_task", "originId": "goal-uuid", "costUsd": 1.10, "calls": 12 } ], "subtree": { "costUsd": 1.52, "notionalUsd": 0, "unpricedCalls": 0, "calls": 18 } } ``` - **Errors**: `404` if the execution does not exist or belongs to another user. `unattached` carries ledger rows that belong to the tree but have no `agent_executions` row of their own — goal tasks and evaluations. They are real spend, and omitting them would make `subtree.costUsd` quietly low. ### Notes - **History before 2026-08-01 was inherited, not fabricated.** The ledger began recording on 2026-08-01; on first boot after that it backfills earlier history from two sources, each stamped with the run's original date: - **Agent runs** from `agent_executions`, copying the cost that was **measured at run time** (provider, model, tokens and cache split included). Marker `prd122_backfill_agent_executions`. - **Workflow LLM nodes** from `node_executions`, which stored tokens but never provider or model. Those are recovered from the workflow definition (`workflows.workflow_data` → `nodes[].parameters`) — the same place the run read them from. Marker `prd122_backfill_node_executions`. Two limitations, stated rather than hidden. The workflow definition consulted is the **current** one, so a node whose model was changed after a run is priced with today's model; and `node_executions` never stored a cache split, so those rows price at standard rates and **claim zero savings** rather than assuming a hit rate. A node deleted from its workflow since the run is left unpriced rather than guessed at. Both backfills are per-row idempotent and resumable: dedup is by "does this execution already have a ledger row", so an interrupted run simply continues on the next boot. Goal-evaluation history is not backfilled — `goal_evaluations` records neither provider nor model, and nothing else can supply them. - **`credits_used` is not money.** Across `agent_executions`, `workflow_executions` and goal detail, that column stores **wall-clock seconds**. It is retained under its historical name because existing UI reads it. Every monetary figure comes from this ledger. - **Cost is an estimate, not an invoice.** `estimate_calibration` corrects for CLI-backed providers that inject invisible preamble, but surfaces should label the figure *estimated*. --- ## MCP Routes Base path: `/api/mcp` ### Get All MCP Servers **GET** `/servers` - **Authentication**: Required - **Description**: Retrieve all MCP servers for the authenticated user - **Response**: ```json { "success": true, "servers": [ { "name": "server-name", "description": "Server description", "url": "https://server-url.com", "status": "active|inactive", "config": {} } ] } ``` ### Add MCP Server **POST** `/servers` - **Authentication**: Required - **Body**: ```json { "name": "server-name", "description": "Server description", "url": "https://server-url.com", "config": {} } ``` - **Response**: ```json { "success": true, "server": { "name": "server-name", "description": "Server description", "url": "https://server-url.com", "status": "active", "config": {}, "createdAt": "2024-01-01T00:00:00Z" } } ``` ### Update MCP Server **PUT** `/servers/:name` - **Authentication**: Required - **Parameters**: - `name` (path): Server name - **Body**: ```json { "description": "Updated description", "url": "https://updated-url.com", "config": {} } ``` - **Response**: ```json { "success": true, "server": { "name": "server-name", "description": "Updated description", "url": "https://updated-url.com", "status": "active", "config": {}, "updatedAt": "2024-01-01T00:00:00Z" } } ``` ### Delete MCP Server **DELETE** `/servers/:name` - **Authentication**: Required - **Parameters**: - `name` (path): Server name - **Description**: Delete an MCP server by name - **Response**: ```json { "success": true, "message": "MCP server deleted successfully" } ``` ### Get Server Capabilities **GET** `/servers/:name/capabilities` - **Authentication**: Required - **Parameters**: - `name` (path): Server name - **Description**: Get capabilities of a specific MCP server - **Response**: ```json { "success": true, "capabilities": { "tools": ["tool1", "tool2"], "resources": ["resource1", "resource2"], "prompts": ["prompt1", "prompt2"] } } ``` ### Test MCP Server Connection **POST** `/servers/:name/test` - **Authentication**: Required - **Parameters**: - `name` (path): Server name - **Description**: Test connection to an MCP server - **Response**: ```json { "success": true, "message": "Connection successful", "latency": 150, "capabilities": { "tools": ["tool1", "tool2"], "resources": ["resource1", "resource2"] } } ``` --- ## Browser Agent Routes Base path: `/api/browser-agent` Registers the browser AGNT is currently rendering, so a chat turn can drive it. The Browser widget hosts a real Chromium surface (an Electron ``) and opens a CDP bridge onto that one surface (`electron/CdpBridge.js`). The widget has **no controls of its own** — no task box, no provider picker. It is steered from the workspace chat, exactly the way Workflow Forge is. These routes are only how the widget announces that a browser exists; the `ai_browser_use` tool finds it on its own (`services/browserSurfaces.js`). There is deliberately **no run endpoint**. A second way to start a browser task would be a second place for provider resolution, model defaults and gateway tokens to drift from the tool that already does all of it. ### Register (or refresh) a surface **POST** `/surface` - **Authentication**: Required - **Body**: `{ instanceId, cdpUrl, url?, title? }` - **Description**: Announces a live browser surface. Re-posted on every navigation, so the registry knows where each window is. When more than one Browser widget is open, the most recently refreshed surface is the one a chat turn drives — which is the window the user was last working in. - **Errors**: `400` with `reason: "not-a-bridge"` when `cdpUrl` is not a loopback bridge (`ws://127.0.0.1:/`). Accepting anything else would turn this into a way to point the agent at an arbitrary CDP endpoint on the network. - **Errors**: `400` with `reason: "unreachable"` when the announcement arrives from a **different machine**. `127.0.0.1` names the CLIENT's loopback in that case, not the backend's, so the bridge is real and simply not reachable from here — the documented remote-backend topology. The client should render a streamed surface instead (see `POST /view`). This case previously succeeded, and the agent silently drove a browser on the server while the user watched an empty widget. ### Watch a surface **POST** `/view` - **Authentication**: Required - **Body**: `{ instanceId?, workspaceId?, launch? }` - **Description**: Starts a CDP screencast of the named surface, or joins one already running, and returns `{ instanceId, transport, viewers, joined }`. Frames are then delivered over Socket.IO as `browser:frame` to the caller's `user:` room. This is how a plain browser tab, a paired phone, or a desktop app pointed at a remote backend watches a browser it cannot embed. - **The client never supplies a `cdpUrl`** — it does not have one and must not. It names WHICH surface it means; the backend looks the endpoint up. A viewer can therefore only ever watch a browser this backend already owns. - **Candidates are PROBED, never trusted.** The registry is in memory and is updated by a widget that cannot promise to run its own teardown, so an entry routinely outlives the socket it names. This route connects before it answers and drops every candidate that does not, which is what stops a dead surface being handed out repeatedly. Reporting a remembered endpoint produced exactly that: `ECONNREFUSED 127.0.0.1:` on every call, forever, for a browser that no longer existed. - **Launches on demand** when nothing live is found, unless `launch: false`. This is not a race with a chat turn: the launcher shares one in-flight launch and reuses a running browser, so a widget mounting as a turn starts gets the same browser rather than a second one. The launch is **hidden** (headless, with a self-naming start page): the stream is the window, and a visible launch put a second, redundant Chrome window on the host desktop. - **Errors**: `404` when there is nothing to watch — the normal cold-start case, and also what is returned (with `reason: "stale"`) when a browser dies in the gap between the probe and the attach. The entry is forgotten first, so a retrying client recovers instead of repeating the same failure. `503` when no browser can be opened on that machine at all; a client should stop polling and show the message rather than spin forever. ### Stop watching **DELETE** `/view/:instanceId` - **Authentication**: Required - **Description**: Drops one viewer. Ref-counted: the screencast stops when the last viewer leaves, and the browser itself keeps running — the agent may still be mid-task, and closing a window because somebody looked away would be its own bug. ### Is anything streaming there **GET** `/view/:instanceId` - **Authentication**: Required - **Description**: Returns `{ streaming: boolean }`. ### Socket.IO events | Direction | Event | Payload | |---|---|---| | server → client | `browser:frame` | `{ instanceId, data, metadata, frameId }` | | server → client | `browser:navigated` | `{ instanceId, url }` | | server → client | `browser:stopped` | `{ instanceId, reason }` | | client → server | `browser:ack` | `{ instanceId, frameId }` | | client → server | `browser:input` | `{ instanceId, method, params }` | | client → server | `browser:watching` / `browser:unwatching` | `{ instanceId }` | `browser:ack` is sent **after the client paints**, never on arrival. Chromium will not send the next frame until the current one is acked, so acking on render is what makes a slow viewer throttle itself instead of drowning in frames it cannot draw. `browser:stopped` is emitted only when a stream ends on its OWN — the browser exited or the connection dropped. A viewer that has not been told keeps showing the last frame it received, which is indistinguishable from a page that simply stopped changing. It is deliberately NOT sent when a viewer leaves on purpose. `browser:input` accepts only `Input.dispatchMouseEvent`, `Input.dispatchKeyEvent` and `Input.insertText`. The allowlist is by exact method, not by `Input.` prefix — `Input.dispatchDragEvent` can initiate a file drag. ### Withdraw a surface **DELETE** `/surface/:instanceId` - **Authentication**: Required - **Description**: Called when the widget unmounts. Withdrawing first matters: an entry pointing at a bridge that is about to close would send the next chat turn to a dead socket. ### Which browser would run now **GET** `/surface` - **Authentication**: Required - **Description**: Diagnostic. Returns `{ instanceId, url, title }` or `null`. The bridge endpoint is deliberately **not** returned — it is a credential for driving the user's browser, not status. --- ## Local LLM Gateway Routes Base path: `/api/llm` An OpenAI-compatible `/chat/completions` shim over AGNT's own provider stack, so a child process on this machine can make LLM calls as the user who started the work. It exists for providers that cannot be handed to a third-party SDK at all — Claude Code, Codex, Gemini CLI, Antigravity, Grok Build and Cursor authenticate with refreshed OAuth sessions or a local CLI login, and Chutes needs an encrypted transport. Its first consumer is the Browser Agent node's Python runner. **This is not a general-purpose proxy.** It is deliberately narrow: - **Loopback only.** Requests from another machine get `403`. - **Its own credential.** Not the session JWT. A caller presents a random per-run token minted by `services/ai/localGatewayTokens.js`, bound to one user, one provider and one model, expiring on a timer and revoked when the run that needed it ends. It opens this route and nothing else. - **The grant decides what runs.** A `model` in the body that differs from the bound model is a `400`, never a substitution. - **No streaming.** `stream: true` is a `400` rather than a faked stream. - **Sampling hints are ignored.** `temperature`, `top_p`, `max_completion_tokens` and `frequency_penalty` are not forwarded; the provider's own configuration applies, as it does everywhere else in AGNT. ### Chat Completion **POST** `/v1/chat/completions` - **Authentication**: Required — `Authorization: Bearer `. Not a session JWT; see above. - **Description**: Runs one non-streaming completion against the provider and model the presented token is bound to. - **Request body**: OpenAI `chat.completion` shape. `messages` is required. `tools` and `response_format` are supported. Inline `data:` images in message content are forwarded to the provider as vision input; remote image URLs are **not** fetched. - **Response**: An OpenAI `chat.completion` object, including `usage` with `prompt_tokens_details.cached_tokens`. ```json { "id": "chatcmpl-...", "object": "chat.completion", "created": 1786299490, "model": "claude-sonnet-4-5-20250929", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "The capital of France is Paris." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 35, "completion_tokens": 10, "total_tokens": 45, "prompt_tokens_details": { "cached_tokens": 0 } } } ``` - **Errors**: - `401` — token missing, unknown, expired or revoked. - `403` — caller is not on this machine. - `400` — empty `messages`, a model the grant does not cover, or `stream: true`. - `502` — the provider failed, or was asked for JSON via `response_format` and replied with something that will not parse. The message quotes what it said. --- ## Model Routes Base path: `/api/models` Also mounted at `/api/openrouter` for legacy backward compatibility (all routes below work at both base paths). ### List Available Providers To discover all available built-in providers, request models for an unknown provider name. The error response includes the full list: **GET** `/:provider/models` (with an invalid provider name) ```json { "success": false, "error": "Unknown provider: invalid", "availableProviders": [ "openai", "anthropic", "gemini", "grokai", "groq", "deepseek", "openrouter", "togetherai", "cerebras", "kimi", "minimax", "zai", "openai-codex", "claude-code", "gemini-cli" ] } ``` Alternatively, the [Provider Health](#get-provider-health) endpoint returns status for all providers, and [Provider Templates](#get-provider-templates) lists additional custom-provider-ready templates. ### Get Models by Provider **GET** `/:provider/models` - **Authentication**: Required (except for static-model providers like `openai-codex` and CLI providers which use local auth) - **Parameters**: - `provider` (path): Provider key or display name. Keys: `openai`, `anthropic`, `gemini`, `grokai` (alias: `grok`), `groq`, `deepseek`, `openrouter`, `togetherai`, `cerebras`, `kimi`, `minimax`, `zai`, `openai-codex`, `claude-code`, `gemini-cli`. Display names like `"Z-AI"` or `"Grok AI"` are also resolved. - `category` (query, optional): Filter by category — `all` (default), `programming`, `creative`, `reasoning` - `useCache` (query, optional): Use cached models — `true` (default) or `false` - `format` (query, optional): Response format — `names` (default, array of model ID strings) or `full` (array of model objects with metadata) - **Description**: Fetch available models from a specific provider - **Response** (`format=names`, default): ```json { "success": true, "models": ["gpt-4o", "gpt-4-turbo", "gpt-3.5-turbo"], "cached": true, "count": 3 } ``` - **Response** (`format=full`): ```json { "success": true, "models": [ { "id": "gpt-4o", "name": "gpt-4o", "description": "", "createdAt": "2024-05-13T00:00:00Z", "ownedBy": "openai" } ], "cached": true, "count": 1 } ``` - **Error** (400): `{ "error": "Unknown provider: ", "availableProviders": [...] }` if provider not found - **Error** (400): Provider-specific auth errors (e.g., CLI not connected, API key not found) - **Error** (401): `{ "error": "Authentication required to fetch models" }` if JWT missing for standard providers ### Refresh Models Cache **POST** `/:provider/models/refresh` - **Authentication**: Required (same rules as GET) - **Parameters**: - `provider` (path): Provider key or display name - **Description**: Clear the models cache and fetch fresh models from the provider API - **Response**: ```json { "success": true, "models": ["gpt-4o", "gpt-4-turbo"], "count": 2, "message": "openai models cache refreshed successfully" } ``` ### Get OpenRouter Models (Legacy) **GET** `/models` - **Description**: Legacy endpoint — redirects internally to `/:provider/models` with `provider=openrouter` - **Response**: Same as `GET /:provider/models` for openrouter ### Refresh OpenRouter Models (Legacy) **POST** `/models/refresh` - **Description**: Legacy endpoint — redirects internally to `/:provider/models/refresh` with `provider=openrouter` - **Response**: Same as `POST /:provider/models/refresh` for openrouter ### Get Provider Metadata (All Models) **GET** `/:provider/metadata` - **Authentication**: None - **Parameters**: - `provider` (path): Provider key - **Description**: Get metadata (cost, context window, capabilities) for all models from a specific provider. Sourced from static configuration, not live API calls. - **Response**: ```json { "success": true, "provider": "openai", "metadata": { "gpt-4o": { "contextWindow": 128000, "maxOutputTokens": 16384, "inputCostPer1M": 2.5, "outputCostPer1M": 10.0, "supportsVision": true, "supportsTools": true, "reasoning": false } } } ``` **Note:** Returns `null` metadata for providers without configured model metadata. ### Get Model Metadata (Single Model) **GET** `/:provider/metadata/:modelId` - **Authentication**: None - **Parameters**: - `provider` (path): Provider key - `modelId` (path): Model ID - `inputTokens` (query, optional): Input token count for cost estimate - `outputTokens` (query, optional): Output token count for cost estimate - **Description**: Get metadata for a specific model, optionally with cost estimate. The `cost` field is only included when both `inputTokens` and `outputTokens` are provided. - **Response**: ```json { "success": true, "provider": "openai", "model": "gpt-4o", "metadata": { "contextWindow": 128000, "maxOutputTokens": 16384, "inputCostPer1M": 2.5, "outputCostPer1M": 10.0, "supportsVision": true, "supportsTools": true }, "reasoning": false, "cost": { "inputCost": 0.0025, "outputCost": 0.01, "totalCost": 0.0125 } } ``` - **Response** (model not found in metadata): `{ "success": true, "provider": "openai", "model": "unknown-model", "metadata": null }` ### Get Provider Health **GET** `/provider-health` - **Authentication**: None - **Description**: The result of the last `POST /provider-health/check`, without making new API calls. Nothing runs that check on its own, so until someone calls it every provider reads `unknown`: that means "never checked", not "down". To learn whether providers work, call `POST /provider-health/check` (authenticated; it probes each provider with the caller's own credentials). Chat routing does not read this: it learns from real calls, per account (`providerHealth`). - **Response**: ```json { "success": true, "overall": "degraded", "healthy": 8, "degraded": 0, "unhealthy": 1, "unknown": 0, "total": 9, "providers": { "openai": { "status": "healthy", "lastChecked": "2024-01-01T00:00:00Z" }, "anthropic": { "status": "healthy", "lastChecked": "2024-01-01T00:00:00Z" }, "gemini": { "status": "unhealthy", "error": "Invalid API key", "lastChecked": "2024-01-01T00:00:00Z" } } } ``` The `overall` field is one of: `healthy`, `degraded` (some unhealthy/degraded), `critical` (all unhealthy), `unknown`. ### Check Provider Health (Live) **POST** `/provider-health/check` - **Authentication**: Optional (if `Authorization: Bearer ` is provided, the user's stored API keys are used for more accurate health checks) - **Description**: Run fresh live health checks against all configured providers. More expensive than the cached GET endpoint — makes actual API calls. - **Response**: ```json { "success": true, "overall": "healthy", "healthy": 9, "degraded": 0, "unhealthy": 0, "unknown": 0, "total": 9, "providers": { "openai": { "status": "healthy", "lastChecked": "2024-01-01T00:00:00Z" }, "anthropic": { "status": "healthy", "lastChecked": "2024-01-01T00:00:00Z" } } } ``` ### Get Model Categories **GET** `/models/categories` - **Authentication**: None - **Description**: Get available model categories for filtering - **Response**: ```json { "success": true, "categories": [ { "id": "all", "name": "All Models", "description": "All available models" }, { "id": "programming", "name": "Programming", "description": "Models optimized for code generation and programming tasks" }, { "id": "creative", "name": "Creative", "description": "Models optimized for creative writing and content generation" }, { "id": "reasoning", "name": "Reasoning", "description": "Models optimized for logical reasoning and problem solving" } ] } ``` --- ### Get Schema Version **GET** `/schema-version` - **Authentication**: None - **Description**: Hash of the current model schema — clients poll this to know when cached model lists are stale - **Response**: ```json { "success": true, "version": "" } ``` ### List Models (legacy OpenRouter shape) **GET** `/models` - **Authentication**: None - **Description**: Legacy alias — forces `provider=openrouter` and re-dispatches to `GET /:provider/models` ### Refresh Models (legacy OpenRouter shape) **POST** `/models/refresh` - **Authentication**: None - **Description**: Legacy alias — forces `provider=openrouter` and re-dispatches to `POST /:provider/models/refresh` ### Get Model Categories **GET** `/models/categories` - **Authentication**: None - **Description**: Static model category list - **Response**: ```json { "success": true, "categories": [ { "id": "all", "name": "All Models", "description": "All available models" }, { "id": "programming", "name": "Programming", "description": "Models optimized for code generation and programming tasks" }, { "id": "creative", "name": "Creative", "description": "Models optimized for creative writing and content generation" }, { "id": "reasoning", "name": "Reasoning", "description": "Models optimized for logical reasoning and problem solving" } ] } ``` ### Get Model Metadata (provider) **GET** `/:provider/metadata` - **Authentication**: None - **Description**: Metadata for all models of a provider - **Response**: ```json { "success": true, "provider": "openai", "metadata": [] } ``` ### Get Model Metadata (single model) **GET** `/:provider/metadata/:modelId` - **Authentication**: None - **Parameters**: - `inputTokens`, `outputTokens` (query, optional): when both are present the response includes a `cost` estimate - **Response** (`metadata` is `null` for unknown models): ```json { "success": true, "provider": "openai", "model": "gpt-4o", "metadata": {}, "reasoning": false, "cost": {} } ``` ### Get Provider Health **GET** `/provider-health` - **Authentication**: None - **Description**: The last explicit check's results; `unknown` until `POST /provider-health/check` runs (see [Get Provider Health](#get-provider-health) above) - **Response**: ```json { "success": true, "providers": {} } ``` ### Check Provider Health **POST** `/provider-health/check` - **Authentication**: Optional — the user is resolved from the bearer token when present - **Description**: Triggers a fresh provider health check - **Response**: Updated provider health ### OpenRouter legacy mount The same router is also mounted at **`/api/openrouter`** for backward compatibility (`server.js` line 189). Every endpoint in this section is reachable under either base — `/api/models` is canonical, `/api/openrouter` is the legacy alias. --- ## Mutation History Routes Base path: `/api/mutations` Every router-applied change is recorded here (PRD-091 Layer 7). Each row captures the *before-state snapshot* and the `fitness_before` baseline so a regression can trigger non-lossy revert. **This is the audit trail the agent should consult when the user asks "what did AGNT change?" or "undo that change."** ### Mutation shape ```json { "id": "uuid", "user_id": "user-uuid", "insight_id": "insight-uuid|null", "target_type": "agent|skill|workflow|tool|memory", "target_id": "target-uuid", "operation": "apply|revert", "status": "applied|reverted|failed", "before_snapshot": { "...": "...": "the asset as it was before the change" }, "after_snapshot": { "...": "...": "the asset as written" }, "fitness_before": 0.82, "fitness_after": 0.78, "fitness_delta": -0.04, "reverted_reason": "manual|canary_regression|null", "created_at": "...", "reverted_at": "..." } ``` ### List Mutations **GET** `/` - **Authentication**: Required - **Parameters**: - `status` (query, optional): `applied`, `reverted`, `failed` - `targetType` (query, optional): `agent`, `skill`, `workflow`, `tool`, `memory` - `limit` (query, optional): default `200` - **Description**: Returns the mutation history for the authenticated user, newest first. - **Response**: ```json { "success": true, "history": [ { ... } ] } ``` ### Get Single Mutation **GET** `/:id` - **Authentication**: Required - **Description**: Full row including `before_snapshot` and `after_snapshot`. Use this to render a diff or to surface what changed. - **Response**: ```json { "success": true, "mutation": { ... } } ``` - **Errors**: `404` not found, `403` forbidden ### Canary Check (Detect Regression) **POST** `/:id/canary-check` - **Authentication**: Required - **Description**: Re-scores fitness for the mutated asset right now (using `FitnessScoreService.forTool` / `forWorkflow`) and compares against the stored `fitness_before` baseline. Persists `fitness_after` and `fitness_delta` on the row. **The agent should call this before suggesting revert.** - **Response**: ```json { "success": true, "verdict": { "regression": true, "delta": -0.12, "fitnessAfter": 0.70 } } ``` - **Verdict shape:** - `regression: true` when `delta < -0.05` (default `minDelta`) - `regression: false, reason: 'not_applicable'` when mutation isn't in `applied` status - `regression: false, reason: 'no_baseline'` when `fitness_before` was never captured - `regression: false, reason: 'no_after_score'` when there's no recent execution data to score against ### Revert Mutation **POST** `/:id/revert` - **Authentication**: Required - **Body** (optional): ```json { "reason": "manual" } ``` - **Description**: Marks the mutation row as `reverted` with `reverted_reason`. The actual rollback uses the `before_snapshot` to restore the asset (handled by the model). Safe to call only when canary-check confirms regression OR the user explicitly requests it. - **Response**: ```json { "success": true } ``` - **Default `reason`**: `"manual"` when the user triggers revert; the periodic canary sweep uses `"canary_regression"`. --- ## NPM Routes Base path: `/api/npm` ### Search MCP Servers **GET** `/search` - **Authentication**: Required - **Parameters**: - `q` (query): Search query - `limit` (query): Maximum results (optional) - **Description**: Search for MCP servers on NPM - **Response**: ```json { "success": true, "packages": [ { "name": "package-name", "version": "1.0.0", "description": "Package description", "author": "Author Name", "keywords": ["mcp", "server"], "downloads": 1000 } ] } ``` ### Get Popular Servers **GET** `/popular` - **Authentication**: Required - **Description**: Get popular MCP servers from NPM - **Response**: ```json { "success": true, "packages": [ { "name": "popular-package", "version": "1.0.0", "description": "Popular package description", "downloads": 10000, "rating": 4.5 } ] } ``` ### Get Package Details **GET** `/package/:packageName` - **Authentication**: Required - **Parameters**: - `packageName` (path): NPM package name - **Description**: Get detailed information about a specific NPM package - **Response**: ```json { "success": true, "package": { "name": "package-name", "version": "1.0.0", "description": "Package description", "author": "Author Name", "license": "MIT", "repository": "https://github.com/user/repo", "dependencies": {}, "downloads": { "lastWeek": 1000, "lastMonth": 5000, "total": 50000 }, "readme": "README content" } } ``` ### Test Package **POST** `/test` - **Authentication**: Required - **Body**: ```json { "packageName": "package-name", "version": "1.0.0" } ``` - **Response**: ```json { "success": true, "testResults": { "compatible": true, "issues": [], "recommendations": [] } } ``` --- ## Orchestrator Routes Base path: `/api/orchestrator` ### Health Check **GET** `/health` - **Authentication**: None - **Description**: Check if the orchestrator service is running - **Response**: ```json { "status": "OK" } ``` ### Get Available Tools **GET** `/tools` - **Authentication**: Required - **Description**: Get the list of tools available to the orchestrator (native tools, registry tools, and installed plugin tools). Used by the frontend tool selector to render available actions. - **Response**: ```json { "tools": [ { "name": "tool_name", "description": "What the tool does", "parameters": { "type": "object", "properties": {} }, "category": "native|plugin|registry" } ] } ``` ### Universal Chat **POST** `/chat` - **Authentication**: Required - **Content-Type**: `multipart/form-data` (or JSON when no files are attached) - **Body** (common parameters, all optional except `message`): - `message` (string): Chat message - `messages` (array): Full message array (alternative to `message` + `history`) - `history` (array): Prior turns as `{ role, content }` objects - `conversationId` (string): Stable key for persistent conversation state (context, loaded tool groups, activated skills) - `provider` / `model` (string): LLM override. Resolution order: body → agent record (saved-agent chats) → user's selected settings → first provider with valid credentials - `enabledTools` (array): Explicit tool whitelist from the tool selector. Narrows the surface; an empty array means zero tools - `reasoningEnabled` (boolean) / `reasoningValue` (string): Extended-thinking controls for reasoning-capable models - `files` (file[]): Optional file attachments (max 20MB each) - Surface-context parameters (any one of these routes the chat to that surface): `agentId`/`agentContext`/`agentState`, `workflowId`/`workflowContext`/`workflowState`, `toolId`/`toolContext`/`toolState`, `widgetId`/`widgetContext`/`widgetState`, `goalId`/`goalContext`, `codeId`/`codeContext`, `skillId`/`skillInstructions`/`skillName`/`skillDescription`/`skillAllowedTools` - **Description**: Universal chat handler. The chat type is detected from the route path and/or which context parameters are present; all typed routes below share this handler and differ only in the injected page context. - **Response**: Server-sent events stream. Key named events: | Event | Payload highlights | |---|---| | `conversation_started` | `conversationId` | | `files_processed` | attached-file summaries | | `assistant_message` | `assistantMessageId` for the turn | | `content_delta` / `reasoning_delta` | `delta`, `accumulated` text | | `tool_pending` / `tool_start` / `tool_end` | tool call id, name, args / result / error | | `tool_executions` | per-round tool execution details | | `image_generated` | image refs for generated images | | `data_content` / `data_offloaded` | large tool results moved to the offload store | | `context_status` / `context_managed` | context-window usage / trimming info | | `steering_applied` | mid-run user steering acknowledged | | `frontend_event` | UI-targeted tool side effects (highlights, tours) | | `error` | error message for the turn | | `final_content` | complete assistant response text | | `done` | stream end | ### Agent Chat **POST** `/agent-chat` - **Authentication**: Required - **Content-Type**: `multipart/form-data` - **Body**: Universal Chat parameters plus: - `agentId` (string): A saved agent ID for a persona chat, or the sentinel `"agent-chat"` for the AgentForge builder surface (Annie persona + agent-management functions) - **Description**: Saved-agent chats get the unified prompt (agent persona first, full skills catalog with specialty highlights, agent-scoped memory) and the tool surface defined by the agent's `toolAccessMode`. Equivalent to `POST /api/agents/:id/chat`, which resolves the agent server-side. - **Response**: Server-sent events stream ### Workflow Chat **POST** `/workflow-chat` - **Authentication**: Required - **Content-Type**: `multipart/form-data` - **Body**: - `workflowId` (string): Workflow ID - `message` (string): Chat message - `files` (file[]): Optional file attachments - **Description**: Chat with a specific workflow - **Response**: Server-sent events stream ### Tool Chat **POST** `/tool-chat` - **Authentication**: Required - **Content-Type**: `multipart/form-data` - **Body**: - `toolId` (string): Tool ID - `message` (string): Chat message - `files` (file[]): Optional file attachments - **Description**: Chat with a specific tool - **Response**: Server-sent events stream ### Goal Chat **POST** `/goal-chat` - **Authentication**: Required - **Content-Type**: `multipart/form-data` - **Body**: - `goalId` (string): Goal ID - `message` (string): Chat message - `files` (file[]): Optional file attachments - **Description**: Chat with a specific goal - **Response**: Server-sent events stream ### Artifact Chat **POST** `/artifact-chat` - **Authentication**: Required - **Content-Type**: `multipart/form-data` - **Body**: - `message` (string): Chat message - `codeContext` (object, optional): Context from the artifacts workspace (active file, selection, open files) - `files` (file[]): Optional file attachments (max 20MB each) - **Description**: Chat handler for the Artifacts workspace ("Annie" assistant). Streams responses and calls the workspace file-operation tools (`read_file`, `write_file`, `edit_file`, `list_files`) against the user's workspace root. See the [Artifacts](#artifacts) section for full details on storage, tools, and events. - **Response**: Server-sent events stream ### Widget Chat **POST** `/widget-chat` - **Authentication**: Required - **Content-Type**: `multipart/form-data` - **Body**: - `message` (string): Chat message - `files` (file[]): Optional file attachments (max 20MB each) - **Description**: Widget-specific chat with streaming. Used for creating and editing custom dashboard widgets. - **Response**: Server-sent events stream### Get Suggestions **POST** `/suggestions` - **Authentication**: Required - **Body**: ```json { "lastUserMessage": "the user's last message", "lastAssistantMessage": "the assistant's last reply", "history": [], "provider": "openai", "model": "gpt-4o", "agentContext": {} } ``` `provider` and `model` are **required** (`400` without them). `agentContext` is optional and shapes suggestions to an agent's persona/tools. - **Response** (JSON, not a stream): ```json { "suggestions": [ { "id": "suggestion_1", "text": "Draft the outline", "icon": "\ud83d\udcdd" }, { "id": "suggestion_2", "text": "Search for sources", "icon": "\ud83d\udd0d" }, { "id": "suggestion_3", "text": "Summarize so far", "icon": "\ud83d\udccb" } ] } ``` On LLM failure the endpoint returns `200` with three generic fallback suggestions plus an `error` field. --- ## Plugin Routes Base path: `/api/plugins` ### Get Installed Plugins **GET** `/installed` - **Authentication**: Required - **Description**: Get list of installed plugins with their status - **Response**: ```json { "success": true, "plugins": [ { "name": "plugin-name", "version": "1.0.0", "description": "Plugin description", "status": "active|inactive|error", "tools": ["tool1", "tool2"] } ], "stats": { "total": 5, "active": 3, "inactive": 2 } } ``` ### Get Installed Plugin Details **GET** `/installed/:name` - **Authentication**: Required - **Parameters**: - `name` (path): Plugin name - **Description**: Get details of a specific installed plugin, including each tool's full input schema (use this to discover param types and allowed values without guessing). - **Response**: ```json { "success": true, "plugin": { "name": "chucknorris-joke-plugin", "displayName": "Chuck Norris Jokes", "version": "1.0.0", "description": "Fetch random Chuck Norris jokes from the public Chuck Norris API.", "author": "AGNT User", "isValid": true, "tools": [ { "type": "chucknorris-get-joke", "title": "Get Random Chuck Norris Joke", "description": "Retrieves a random Chuck Norris joke, optionally filtered by category.", "category": "action", "schema": { "title": "Get Random Chuck Norris Joke", "description": "Retrieves a random Chuck Norris joke, optionally filtered by category.", "inputSchema": { "type": "object", "properties": { "category": { "type": "string", "enum": ["animal", "career", "celebrity", "dev", "explicit", "fashion", "food", "history", "money", "movie", "music", "political", "religion", "science", "sport", "travel"] } } } } } ] } } ``` - **Response (404)**: `{ "success": false, "error": "Plugin '' not found" }` ### Get Plugin Source Code **GET** `/installed/:name/source` - **Authentication**: Required - **Parameters**: - `name` (path): Plugin name - **Description**: Get source code of an installed plugin - **Response**: ```json { "success": true, "files": { "manifest.json": "{...}", "package.json": "{...}", "index.js": "console.log('hello');" } } ``` ### Get Plugin Package **GET** `/installed/:name/package` - **Authentication**: Required - **Parameters**: - `name` (path): Plugin name - **Description**: Get the plugin as a packaged .agnt file (base64 encoded) - **Response**: ```json { "success": true, "data": "base64-encoded-package-data", "size": 1024000, "fileName": "plugin-name.agnt" } ``` ### Get Marketplace Plugins **GET** `/marketplace` - **Authentication**: Required - **Description**: Get list of available plugins from the marketplace - **Response**: ```json { "plugins": [ { "name": "marketplace-plugin", "version": "1.0.0", "description": "Marketplace plugin description", "author": "Author Name", "downloads": 1000, "rating": 4.5 } ] } ``` ### Install Plugin from Marketplace **POST** `/install` - **Authentication**: Required - **Body**: ```json { "name": "plugin-name", "version": "latest" } ``` - **Response**: ```json { "success": true, "message": "Plugin installed successfully", "plugin": { "name": "plugin-name", "version": "1.0.0" } } ``` ### Install Plugin from File **POST** `/install-file` - **Authentication**: Required - **Body**: ```json { "name": "plugin-name", "fileData": "base64-encoded-file-data", "fileName": "plugin.agnt" } ``` - **Response**: ```json { "success": true, "message": "Plugin installed successfully", "plugin": { "name": "plugin-name", "version": "1.0.0" } } ``` ### Uninstall Plugin **DELETE** `/:name` - **Authentication**: Required - **Parameters**: - `name` (path): Plugin name - **Description**: Uninstall a plugin - **Response**: ```json { "success": true, "message": "Plugin uninstalled successfully" } ``` ### Get Plugin Tools **GET** `/tools` - **Authentication**: Required - **Description**: Get all tools provided by plugins - **Response**: ```json { "success": true, "tools": [ { "type": "tool-type", "title": "Tool Title", "description": "Tool description", "category": "action", "icon": "tool-icon", "plugin": "plugin-name" } ], "count": 1 } ``` ### Plugin Forge (AI authoring) Plugins are written in the Plugin Forge chat, not through dedicated generation endpoints. The chat's `plugin` surface edits the draft with orchestrator tools (`generate_plugin`, `edit_plugin_file`, `write_plugin_file`, `delete_plugin_file`, `install_plugin`, `test_plugin_tool`, `load_plugin`); `install_plugin` builds and installs through `/build-generated` below. ### Build Generated Plugin **POST** `/build-generated` - **Authentication**: Required - **Body**: ```json { "manifest": {}, "toolCode": {}, "packageJson": {}, "installAfterBuild": true } ``` - **Response**: ```json { "success": true, "pluginName": "generated-plugin", "outputFile": "/path/to/plugin.agnt", "installed": true, "installResult": { "success": true } } ``` ### Reload Plugins **POST** `/reload` - **Authentication**: Required - **Description**: Reload all plugins (useful after manual changes) - **Response**: ```json { "success": true, "message": "Plugins reloaded", "stats": { "total": 5, "active": 3 }, "orchestratorReload": { "success": true }, "workflowProcessReload": { "success": true } } ``` --- ### Get Plugin Assets **GET** `/:name/assets` - **Authentication**: Required - **Description**: Ecosystem assets a plugin currently owns (agents, workflows, skills, widgets) with per-asset `is_user_modified` flags — powers the uninstall confirmation modal so the user can see what will be deleted vs preserved - **Response**: ```json { "success": true, "assets": [ { "asset_type": "agent", "asset_slug": "my-agent", "local_id": "uuid", "installed_at": "2024-01-01T00:00:00Z", "deprecated_at": null, "is_user_modified": 0 } ] } ``` ### Bundle Plugin from Assets **POST** `/bundle-from-assets` - **Authentication**: Required - **Description**: Builds a `.agnt` archive (base64) plus a generated manifest from selected local assets. Optional `install: true` also installs the bundle on this instance. - **Response**: `{ "archive": "", "manifest": {...} }` ### Check Plugin Auth Requirements **POST** `/install-file/check-auth` - **Authentication**: Required - **Description**: Scans a bundle's `authProvider` declarations across its tools, and says whether everyone who installs it could connect each one, by the same rule the marketplace applies at publish (`plugins/lib/validate-core.js` `checkPluginSignIns`). A sign-in is connectable when it is declared in the plugin's own `manifest.auth` or is a shared AGNT sign-in (`GET https://api.agnt.gg/auth/providers`, no Authorization header). The desktop publish buttons call this before uploading. - **Body**: ```json { "fileData": "" } ``` - **Response**: ```json { "success": true, "pluginName": "calendly-plugin", "version": "1.1.0", "requiredAuthProviders": ["calendly"], "signIns": [{ "id": "calendly", "source": "shared" }], "signInErrors": [], "signInPublishErrors": [], "signInWarnings": [], "publishable": true, "assetCounts": { "tools": 2, "agents": 0, "workflows": 0, "skills": 0, "widgets": 0 } } ``` `source` is `plugin` (bundled in `manifest.auth`), `shared`, `unresolved` (only its author could connect it) or `unknown` (the shared list could not be read). `signInErrors` block everywhere (a malformed `auth` entry, or one carrying a credential); `signInPublishErrors` block publishing (an unresolved sign-in, or an `auth` id that redefines a shared one). `publishable` is `false` when the marketplace would refuse it and `null` when it could not be told here. ### Inspect Plugin **GET** `/inspect/:name` - **Authentication**: Required - **Description**: The disclosure report the install-consent modal renders: integrity state, detected capabilities (with file:line evidence), declared permissions, the undeclared diff, and the trust tier the plugin would receive - **Response**: Inspection report object ### Install Plugin from GitHub **POST** `/install-github` - **Authentication**: Required - **Description**: Pulls a plugin directly from GitHub through the same staged/validated/permission-gated install path. Returns `{ requiresConfirmation: true }` on a moved repo and `{ requiresConsent: true }` on permission escalation. ### Get Update Settings **GET** `/update-settings` - **Authentication**: Required - **Description**: Auto-update scheduler settings - **Response**: `{ "success": true, "settings": {...} }` ### Set Update Settings **POST** `/update-settings` - **Authentication**: Required - **Body**: ```json { "autoCheck": true, "intervalHours": 24 } ``` - **Response**: `{ "success": true, "settings": {...} }` ### Set Per-Plugin Update Policy **POST** `/update-policy/:name` - **Authentication**: Required - **Description**: Per-plugin auto-update policy, stored on the registry entry (merge semantics preserve it across installs/updates). `404` if the plugin isn't installed, `400` on an invalid policy. - **Body**: ```json { "policy": "auto | notify | pinned" } ``` - **Response**: `{ "success": true, "name": "...", "policy": "..." }` ### Check for Plugin Updates **GET** `/updates` - **Authentication**: Required - **Description**: Compares every installed plugin's version against the marketplace catalog. Non-semver installed versions (`local`, `latest`, `unknown`) surface as status `unknown-version` — never compared, never auto-updated over. - **Response**: Per-plugin update status list ### Update Plugin **POST** `/update/:name` - **Authentication**: Required - **Description**: Updates a single plugin via the staged-install path (stage → validate → permission-diff gate → atomic swap). An update requesting NEW permissions returns `{ requiresConsent: true, permissionDiff }` and changes nothing on disk until re-called with `acceptedPermissions: true`. On success all plugin processes are reloaded. - **Body**: ```json { "acceptedPermissions": false } ``` --- ## Checkpoint Routes Base path: `/api/checkpoints` Tasks in chat. When Annie does real work (anything that sends, posts, pays or changes something), she posts a **checkpoint** card in the conversation with the `task_checkpoint` tool and her turn ends there: the plan, the exact draft to check, a routine run's specifics, the final review, or a routine to turn on. Nothing happens until the person decides. The client records the decision here, then sends the person's reply into the same chat so Annie carries on. A checkpoint is private to the person whose conversation it is, including on a team's instance (this API is private-in-team: a team header never pools it). Another person's id returns 404. A conversation has at most one pending checkpoint; a newer card marks the older one `superseded`. On a team instance the work can also be a card on a teamspace board: it is created and moved through the team routes with the person's own token (pending: Review; approved: In progress; final or routine approved: Done). A board that cannot be reached never blocks the checkpoint. Each change sends the person's windows a realtime `checkpoint:changed` event (`{ id, conversationId, state }`). Checkpoint shape: `{ id, conversationId, outputId, kind: 'plan' | 'review' | 'run' | 'final' | 'routine', title, content (markdown), taskTitle, state: 'pending' | 'approved' | 'changes' | 'skipped' | 'superseded', note, task: { teamId, workspaceId, id } | null, createdAt, decidedAt }`. **GET** `/` - **Authentication**: Required - Without a query: your pending checkpoints, newest first (Home's "Needs you"). With `?conversationId=`: every checkpoint in that conversation of yours. **GET** `/:id` - **Authentication**: Required - One of your checkpoints. **POST** `/:id/locate` - **Authentication**: Required - Body: `{ outputId }`. Records which saved chat the card lives in, so "Review" can reopen it. Set once; later calls keep the first value. **POST** `/:id/decide` - **Authentication**: Required - Body: `{ decision: 'approved' | 'changes' | 'skipped', note? }`. Only a pending checkpoint, once (else 409 `not_pending`). `skipped` is for a routine run (`kind: 'run'`). Returns `{ checkpoint, linkError }`. ## Schedule Routes Base path: `/api/schedules` The durable cron scheduler (PRD-091 Layer 1). Use when the user wants recurring execution of a goal. Survives backend restart, uses in-zone DST-correct timing, idempotent on `last_run`. Hangs on `HeartbeatService` — no separate process. ### Schedule shape ```json { "id": "uuid", "user_id": "user-uuid", "target_type": "goal", "target_id": "goal-uuid", "cron": "0 9 * * MON-FRI", "timezone": "America/New_York", "next_run": "2026-06-22T13:00:00.000Z", "last_run": "2026-06-19T13:00:00.000Z", "enabled": true, "on_missed": "fire_once", "created_at": "..." } ``` ### Supported cron syntax 5-field cron (`minute hour dom month dow`) plus macros: - **Macros**: `@hourly`, `@daily`, `@midnight`, `@weekly`, `@monthly`, `@yearly`, `@annually` - **Fields**: `*`, `*/N`, `A-B`, `A,B,C`, day-of-week names (`MON`–`SUN`), `7` aliases to `0` (Sunday) - **Dom/dow OR semantics**: when both restricted, the schedule fires when *either* matches (standard cron) - **Timezone**: IANA name (e.g. `America/New_York`, `Europe/London`). Defaults to `UTC`. ### `on_missed` values | Value | Behavior on backend restart | |---|---| | `fire_once` (default) | If next_run is in the past, fire once then resume | | `fire_all` | Fire once for each missed slot (use sparingly — can cascade) | | `skip` | Skip missed firings; only resume forward | ### List Schedules **GET** `/` - **Authentication**: Required - **Response**: ```json { "success": true, "schedules": [ { ... } ] } ``` ### Get Schedules by Target **GET** `/target/:targetType/:targetId` - **Authentication**: Required - **Parameters**: - `targetType` (path): `goal` (MVP currently only supports goal) - `targetId` (path): the goal ID - **Description**: Useful for the Goals UI to show "this goal is scheduled." - **Response**: ```json { "success": true, "schedules": [ { ... } ] } ``` ### Preview Cron Firings (No Persist) **POST** `/preview` - **Authentication**: Required - **Body**: ```json { "cron": "0 9 * * MON-FRI", "timezone": "America/New_York", "count": 5 } ``` - **Description**: Validates the cron expression and returns the next `count` firing times (max 25). **Persists nothing.** Use this when surfacing "this schedule will next fire on..." in the UI before the user clicks Create. - **Response**: ```json { "success": true, "previews": [ "2026-06-22T13:00:00.000Z", "2026-06-23T13:00:00.000Z", "2026-06-24T13:00:00.000Z" ] } ``` - **Errors**: `400` when `cron` is missing or invalid. ### Create Schedule **POST** `/` - **Authentication**: Required - **Body**: ```json { "targetType": "goal", "targetId": "goal-uuid", "cron": "0 9 * * MON-FRI", "timezone": "America/New_York", "enabled": true, "onMissed": "fire_once" } ``` - **Description**: Creates a schedule. `next_run` is computed from `cron` + `timezone`. `enabled` defaults to `true`. `onMissed` defaults to `fire_once`. - **Response** (`201`): ```json { "success": true, "schedule": { ... } } ``` - **Errors**: - `400` when `targetType`, `targetId`, or `cron` is missing - `400` when `cron` is invalid (per `isValidCron`) ### Update Schedule **PATCH** `/:id` - **Authentication**: Required - **Body** (any subset): ```json { "cron": "0 10 * * MON-FRI", "timezone": "Europe/London", "enabled": false, "onMissed": "skip" } ``` - **Description**: Updates schedule fields. When `cron`, `timezone`, or `onMissed` change, `next_run` is recomputed. Setting `enabled: false` pauses without deleting. - **Response**: ```json { "success": true, "schedule": { ... } } ``` - **Errors**: `404` not found, `403` forbidden, `400` invalid cron ### Fire Schedule Now **POST** `/:id/fire-now` - **Authentication**: Required - **Description**: Manually trigger the schedule's target (currently invokes `TaskOrchestrator.executeGoalAutonomous`). Returns as soon as the run has started; the run continues in the background. Poll **Get Run History** for its outcome. The regular cadence continues: `next_run` stays on the next cron slot. Useful for "test run" or "I want it now." - **Response** (`202`): ```json { "success": true, "result": { "fired": true, "scheduleId": "schedule-uuid", "runId": "run-uuid", "status": "running" } } ``` - **Errors**: `404` not found, `403` forbidden, `409` the schedule cannot fire (`reason` says why, e.g. an invalid cron) ### Get Run History **GET** `/:id/runs` - **Authentication**: Required - **Parameters**: - `limit` (query, optional): max `500`, default `50` - **Response**: ```json { "success": true, "runs": [ { "id": "run-uuid", "schedule_id": "schedule-uuid", "target_type": "goal", "target_id": "goal-uuid", "run_target_id": "goal-uuid", "fired_at": "2026-06-19T13:00:00.000Z", "status": "completed", "error": null, "duration_ms": 4823 } ] } ``` - **Run status**: `running` while in flight, then `completed`, `failed` (see `error`), or the goal run's own outcome (`stopped`, `stuck`, `needs_review`, `max_iterations`). `interrupted` means the app stopped before the run finished. `duration_ms` is `null` until the run ends and for runs recorded before 0.6.7. ### Delete Schedule **DELETE** `/:id` - **Authentication**: Required - **Response**: ```json { "success": true, "deleted": true } ``` --- ## Import Routes Base path: `/api/import` Bring a user's existing setup in from the other AI agent tools installed on the same machine — Hermes, OpenClaw, Claude Code, Codex, Cursor and Gemini CLI. > **Skills usually need no import at all.** `SkillDiscoveryService` already > scans every one of these tools' `skills/` directories, so their skills work in > AGNT untouched. What these routes add is *ownership*: copying a skill into > `~/.agnt/skills/` so uninstalling the tool it came from no longer takes it > away. Persona and memory have no equivalent in discovery and are genuinely > new records. ### Detect Importable Setup **GET** `/detect` - **Authentication**: Required - **Description**: Read-only scan of the installed harnesses. Runs during onboarding, so it is bounded by a ~2.5s timeout and answers with an empty result rather than an error if it cannot finish. `skills.importable` counts only skills AGNT does not already have, deduplicated across tools. - **Response**: ```json { "sources": [ { "id": "hermes", "label": "Hermes", "icon": "agent", "home": "C:\\Users\\you\\.hermes", "skills": { "total": 9, "importable": 8, "names": ["media-use"] }, "persona": { "available": true, "origins": ["SOUL.md"], "bytes": 513, "preview": "You are..." }, "memories": { "count": 7 } } ], "totals": { "sources": 6, "skillsSeen": 49, "skillsImportable": 8, "personas": 2, "memories": 8 } } ``` ### Run Import **POST** `/run` - **Authentication**: Required - **Description**: Copy the selected items into AGNT. Additive only — a skill whose name already exists is skipped, never overwritten. Each array holds harness ids; the server re-scans and ignores any id it does not recognise. - **Request Body**: ```json { "skills": ["hermes"], "personas": ["openclaw"], "memories": ["hermes"] } ``` - **Response**: ```json { "imported": { "skills": 8, "agents": 1, "memories": 7 }, "items": [{ "kind": "skill", "name": "media-use", "source": "hermes", "status": "imported" }], "failures": [{ "kind": "skill", "name": "broken", "source": "hermes", "error": "Invalid SKILL.md" }] } ``` - **Errors**: `400` if nothing is selected or the arrays are malformed; `401` without a user. Per-item failures are reported in `failures` rather than aborting the run. --- ## Skill Routes Base path: `/api/skills` Manage reusable agent skills — named instruction sets that can be assigned to agents. ### Get All Skills **GET** `/` - **Authentication**: Required - **Description**: Get all skills for the authenticated user - **Response**: ```json { "skills": [ { "id": "skill-uuid", "name": "Code Reviewer", "description": "Reviews code for quality and security", "instructions": "When reviewing code...", "icon": "fas fa-code", "category": "development", "allowed_tools": "[\"code-search\",\"file-read\"]", "license": "", "compatibility": "", "metadata": "{\"relations\":{\"depends-on\":[\"hyperframes-core\"]},\"provenance\":{\"source-trace\":\"goal-uuid\",\"rationale\":\"...\"}}", "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-01T00:00:00Z" } ] } ``` ### Get Skill by ID **GET** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Skill ID - **Response**: ```json { "skill": { ... } } ``` - **Error** (404): Skill not found ### Create Skill **POST** `/` - **Authentication**: Required - **Body**: ```json { "skill": { "name": "Code Reviewer", "description": "Reviews code for quality and security", "instructions": "When reviewing code, focus on...", "icon": "fas fa-code", "category": "development", "allowedTools": ["code-search", "file-read"] } } ``` - **Response** (201): ```json { "skill": { ... }, "skillId": "skill-uuid" } ``` ### Update Skill **PUT** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Skill ID - **Body**: ```json { "skill": { "name": "Updated Name", "description": "Updated description", "instructions": "Updated instructions..." } } ``` - **Response**: ```json { "skill": { ... } } ``` ### Delete Skill **DELETE** `/:id` - **Authentication**: Required - **Parameters**: - `id` (path): Skill ID - **Response**: ```json { "message": "Skill deleted" } ``` - **Error** (404): Skill not found ### Export Skill as Markdown **GET** `/:id/export` - **Authentication**: Required - **Parameters**: - `id` (path): Skill ID - **Description**: Export a skill as a `.SKILL.md` file with YAML frontmatter and markdown body - **Response**: `text/markdown` file download ### Import Skill from Markdown **POST** `/import` - **Authentication**: Required - **Content-Type**: `text/plain` - **Description**: Import a skill from SKILL.md content (YAML frontmatter + markdown body) - **Body**: Raw text content of a `.SKILL.md` file ``` --- name: "My Skill" description: "Skill description" category: "general" icon: "fas fa-puzzle-piece" allowed-tools: - code-search - file-read --- Instructions for the skill go here... ``` - **Response** (201): ```json { "skill": { ... }, "skillId": "skill-uuid" } ``` ### Skill relations and provenance Skills can declare how they relate to other skills, and where they came from. Both live inside the spec's free-form `metadata` map, so no new frontmatter fields are introduced and skills stay portable to other agentskills.io clients (which simply ignore `metadata`). In a `SKILL.md` file: ```yaml --- name: hyperframes-cli description: Use the HyperFrames CLI development loop. metadata: relations: depends-on: - hyperframes-core # activate that skill too composes-with: - media-use # complementary, often used together supersedes: - old-render-pipeline # prefer this skill over that one provenance: source-trace: 9acd74bc-34e5-4f25-bde2-1aef13965318 extracted: "2026-08-03" rationale: Extracted from the batch-render loop; generalizes to any batch render, fails on multi-repo targets. confidence: 0.82 --- ``` Over the API, `metadata` is a JSON **string** on database-backed skills (`/api/skills`) and a parsed **object** on filesystem-discovered skills (`/api/skills/discovered`). Consumers should handle both. #### Relation types | Key | Meaning | | --- | --- | | `depends-on` | This skill requires the target to function. Activating it surfaces a prompt to activate the target as well. | | `composes-with` | Complementary skill, frequently useful alongside this one. | | `supersedes` | This skill replaces the target. While both are present, the target is omitted from the skill catalog and activating it warns the caller. | Values are arrays of skill slugs (a bare string is accepted and treated as a single-element array). Unknown relation types and malformed slugs produce **warnings, never errors** — the rest of the skill still loads. #### Provenance fields | Field | Meaning | | --- | --- | | `source-trace` | Goal or execution ID the skill was extracted from. | | `extracted` | `YYYY-MM-DD` extraction date. | | `rationale` | Where the pattern came from, when it generalizes, when it fails. | | `confidence` | `0.0`–`1.0` judge confidence at extraction time. | | `history` | Appended on each SkillForge refinement: one entry per version, giving the skill a lineage. | Skills forged automatically by [SkillForge](#skillforge-routes) populate `provenance` from the trace analysis. Refinements append to `provenance.history` rather than overwriting the original extraction record. #### Effect on the skill catalog The `` catalog injected into agent prompts is relation-aware: - A `depends-on` relation is annotated inline — `- hyperframes-cli: … [needs: hyperframes-core]`. - A skill is omitted from the catalog when another skill **present in the same catalog** declares that it `supersedes` it. If the successor is absent the superseded skill is still listed, so a capability is never orphaned. Relations and provenance survive a full `GET /:id/export` → `POST /import` round-trip. --- ## SkillForge Routes Base path: `/api/skillforge` SkillForge is the skill evolution subsystem within the unified evolution engine. It analyzes goal execution traces via the TraceAnalyzer, extracts patterns and anti-patterns, evolves skills with improved instructions, and tracks performance over time using a Skill Evolution Score (SES). Runs automatically after goal completion when `autoAnalyze` is enabled, or can be triggered manually. ### Get Eligible Goals **GET** `/eligible-goals` - **Authentication**: Required - **Description**: List completed goals that are available for skill forging/analysis - **Response**: ```json { "success": true, "goals": [ { "id": "goal-id", "title": "Goal Title", "status": "completed", "completedAt": "2024-01-01T00:00:00Z" } ] } ``` ### Analyze Goal Trace **POST** `/analyze/:goalId` - **Authentication**: Required - **Parameters**: - `goalId` (path): Goal ID - **Body** (optional): ```json { "provider": "anthropic", "model": "claude-sonnet-4-20250514" } ``` - **Description**: Analyze a goal's execution trace using LLM-as-judge to extract patterns, anti-patterns, and a reusable skill candidate. Provider/model override the user's defaults for the LLM analysis call. - **Response**: ```json { "success": true, "analysis": { "patterns": [], "antipatterns": [], "insights": [], "skillCandidate": {} } } ``` ### Evolve Skill **POST** `/evolve/:goalId` - **Authentication**: Required - **Parameters**: - `goalId` (path): Goal ID - **Body** (optional): ```json { "provider": "anthropic", "model": "claude-sonnet-4-20250514" } ``` - **Description**: Full analysis and skill evolution — analyzes the goal trace, creates or updates a skill with merged instructions, and records the evolution with SES tracking. Provider/model are forwarded to trace analysis and skill instruction merging. - **Response**: ```json { "success": true, "result": { "skillId": "skill-id", "previousVersion": 1, "newVersion": 2, "sesDelta": 0.15, "improvements": [] } } ``` ### Get All Evaluations **GET** `/evaluations` - **Authentication**: Required - **Parameters**: - `limit` (query, optional): Max results (default: 50) - **Description**: List all skill evaluations for the authenticated user - **Response**: ```json { "success": true, "evaluations": [ { "id": "eval-id", "skillId": "skill-id", "score": 85, "sesDelta": 0.12, "createdAt": "2024-01-01T00:00:00Z" } ] } ``` ### Get Evaluations for Skill **GET** `/evaluations/:skillId` - **Authentication**: Required - **Parameters**: - `skillId` (path): Skill ID - **Description**: Get all evaluations for a specific skill - **Response**: ```json { "success": true, "evaluations": [ { "id": "eval-id", "skillId": "skill-id", "score": 85, "sesDelta": 0.12, "version": 2, "createdAt": "2024-01-01T00:00:00Z" } ] } ``` ### Get Leaderboard **GET** `/leaderboard` - **Authentication**: Required - **Parameters**: - `limit` (query, optional): Max results (default: 20) - **Description**: Get top skills ranked by average SES delta - **Response**: ```json { "success": true, "leaderboard": [ { "skillId": "skill-id", "skillName": "Code Reviewer", "avgSesDelta": 0.25, "totalEvolutions": 8, "currentVersion": 5 } ] } ``` ### Get Skill Version History **GET** `/skill/:skillId/versions` - **Authentication**: Required - **Parameters**: - `skillId` (path): Skill ID - **Description**: Get the version history for a skill's evolution - **Response**: ```json { "success": true, "versions": [ { "version": 3, "sesDelta": 0.15, "changes": "Improved error handling patterns", "createdAt": "2024-01-01T00:00:00Z" } ] } ``` ### Get Skill Lineage **GET** `/skill/:skillId/lineage` - **Authentication**: Required - **Parameters**: - `skillId` (path): Skill ID - **Description**: Get the full evolutionary lineage of a skill — every ancestor, mutation, and stats - **Response**: ```json { "success": true, "lineage": [ { "version": 1, "parentGoalId": "goal-id", "sesDelta": 0.0, "createdAt": "2024-01-01T00:00:00Z" } ], "stats": { "totalEvolutions": 5, "avgSesDelta": 0.18, "bestVersion": 4 } } ``` ### Get Aggregate Stats **GET** `/stats` - **Authentication**: Required - **Description**: Get aggregate SkillForge statistics for the user - **Response**: ```json { "success": true, "stats": { "totalSkills": 12, "totalEvolutions": 45, "totalEvaluations": 120, "avgSesDelta": 0.15, "topSkill": "Code Reviewer" } } ``` ### Get SkillForge Settings **GET** `/settings` - **Authentication**: Required - **Description**: Get SkillForge configuration settings - **Response**: ```json { "success": true, "settings": { "autoAnalyze": false, "evaluationThreshold": 0.7, "maxVersions": 50 } } ``` ### Update SkillForge Settings **POST** `/settings` - **Authentication**: Required - **Body**: ```json { "autoAnalyze": true, "evaluationThreshold": 0.8, "maxVersions": 100 } ``` - **Response**: ```json { "success": true, "settings": { "autoAnalyze": true, "evaluationThreshold": 0.8, "maxVersions": 100 } } ``` --- ## Speech Routes Base path: `/api/speech` ### Transcribe Audio **POST** `/transcribe` - **Authentication**: Required - **Content-Type**: `multipart/form-data` - **Body**: - `audio` (file): Audio file to transcribe (max 10MB) - **Description**: Transcribe audio file to text using Whisper - **Response**: ```json { "success": true, "transcript": "Transcribed text from audio" } ``` ### Get Speech Service Status **GET** `/status` - **Authentication**: None - **Description**: Get Whisper service status - **Response**: ```json { "success": true, "status": "ready|loading|error", "model": "whisper-1", "initialized": true } ``` ### Initialize Speech Service **POST** `/initialize` - **Authentication**: Required - **Description**: Initialize Whisper service (download model if needed) - **Response**: ```json { "success": true, "message": "Whisper service initialized successfully" } ``` --- ## Stream Routes Base path: `/api/stream` ### Health Check **GET** `/health` - **Authentication**: None - **Description**: Check if the stream service is running - **Response**: ```json { "status": "OK" } ``` ### Start Tool Forge Stream **POST** `/start-tool-forge-stream` - **Authentication**: Required - **Content-Type**: `multipart/form-data` - **Body**: - `prompt` (string): Tool generation prompt - `files` (file[]): Optional file attachments - **Response**: Server-sent events stream ### Cancel Tool Forge Stream **POST** `/cancel-tool-forge-stream` - **Authentication**: Required - **Body**: ```json { "streamId": "stream-id" } ``` - **Response**: ```json { "success": true, "message": "Stream cancelled" } ``` ### Start Chat Stream **POST** `/start-chat-stream` - **Authentication**: Required - **Content-Type**: `multipart/form-data` - **Body**: - `message` (string): Chat message - `files` (file[]): Optional file attachments - **Response**: Server-sent events stream ### Cancel Chat Stream **POST** `/cancel-chat-stream` - **Authentication**: Required - **Body**: ```json { "streamId": "stream-id" } ``` - **Response**: ```json { "success": true, "message": "Stream cancelled" } ``` ### Generate Tool **POST** `/generate-tool` - **Authentication**: Required - **Body**: ```json { "description": "Tool description", "provider": "openai", "model": "gpt-4" } ``` - **Response**: ```json { "success": true, "tool": { "name": "Generated Tool", "description": "Tool description", "config": {} } } ``` ### Generate Workflow **POST** `/generate-workflow` - **Authentication**: Required - **Body**: ```json { "description": "Workflow description", "provider": "openai", "model": "gpt-4" } ``` - **Response**: ```json { "success": true, "workflow": { "name": "Generated Workflow", "description": "Workflow description", "nodes": [], "edges": [] } } ``` ### Generate Agent **POST** `/generate-agent` - **Authentication**: Required - **Body**: ```json { "description": "Agent description", "provider": "openai", "model": "gpt-4" } ``` - **Response**: ```json { "success": true, "agent": { "name": "Generated Agent", "description": "Agent description", "config": {} } } ``` --- ## Tool Schema Routes Base path: `/api/tool-schemas` ### Get All Tool Schemas **GET** `/schemas` - **Authentication**: None - **Description**: Get all tool schemas organized by category - **Response**: ```json { "triggers": [ { "type": "trigger-type", "title": "Trigger Title", "description": "Trigger description", "schema": {} } ], "actions": [ { "type": "action-type", "title": "Action Title", "description": "Action description", "schema": {} } ], "utilities": [ { "type": "utility-type", "title": "Utility Title", "description": "Utility description", "schema": {} } ] } ``` ### Get Tool Schema by Type **GET** `/schemas/:toolType` - **Authentication**: None - **Parameters**: - `toolType` (path): Tool type - **Description**: Get schema for a specific tool - **Response**: ```json { "type": "tool-type", "title": "Tool Title", "description": "Tool description", "schema": { "properties": {}, "required": [] } } ``` ### Get Schemas by Category **GET** `/schemas/category/:category` - **Authentication**: None - **Parameters**: - `category` (path): Category name (triggers, actions, utilities, etc.) - **Description**: Get schemas by category - **Response**: ```json [ { "type": "tool-type", "title": "Tool Title", "description": "Tool description", "schema": {} } ] ``` ### Get Registry Statistics **GET** `/stats` - **Authentication**: None - **Description**: Get registry statistics - **Response**: ```json { "totalTools": 50, "categories": { "triggers": 10, "actions": 25, "utilities": 15 }, "lastUpdated": "2024-01-01T00:00:00Z" } ``` ### Get Tool Metadata **GET** `/metadata/:toolType` - **Authentication**: None - **Parameters**: - `toolType` (path): Tool type - **Description**: Get metadata for a specific tool (includes source info) - **Response**: ```json { "type": "tool-type", "source": "builtin|plugin|custom", "plugin": "plugin-name", "version": "1.0.0", "author": "Author Name", "createdAt": "2024-01-01T00:00:00Z" } ``` ### Reload Registry **POST** `/reload` - **Authentication**: Required - **Description**: Reload the registry (useful for development) - **Response**: ```json { "success": true, "message": "Tool registry reloaded successfully", "stats": { "totalTools": 50, "categories": { "triggers": 10, "actions": 25, "utilities": 15 } } } ``` --- ## Tools Routes Base path: `/api/tools` ### Get Orchestrator Tools **GET** `/orchestrator-tools` - **Authentication**: Required - **Description**: Get all orchestrator tools (native, registry, and plugin tools) - **Response**: ```json { "tools": [ { "id": "tool-name", "name": "Tool Name", "title": "Tool Title", "description": "Tool description", "category": "Data & Knowledge", "is_builtin": true, "is_plugin": false, "plugin_name": null } ] } ``` ### Get Workflow Tools **GET** `/workflow-tools` - **Authentication**: Required - **Description**: Get all tools for the workflow designer including plugins and custom tools - **Response**: ```json { "triggers": [ { "type": "trigger-type", "title": "Trigger Title", "description": "Trigger description", "icon": "trigger-icon", "isPlugin": false } ], "actions": [ { "type": "action-type", "title": "Action Title", "description": "Action description", "icon": "action-icon", "isPlugin": false } ], "utilities": [ { "type": "utility-type", "title": "Utility Title", "description": "Utility description", "icon": "utility-icon", "isPlugin": false } ], "widgets": [], "controls": [], "custom": [ { "id": "custom-tool-id", "name": "Custom Tool", "description": "Custom tool description" } ] } ``` ### Get Plugin Tools Only **GET** `/plugins-only` - **Authentication**: Required - **Description**: Get only plugin tools (for real-time updates) - **Response**: ```json { "success": true, "plugins": { "triggers": [ { "type": "plugin-trigger", "title": "Plugin Trigger", "description": "Description", "icon": "puzzle-piece", "isPlugin": true, "pluginName": "plugin-name" } ], "actions": [], "utilities": [], "widgets": [], "controls": [], "custom": [] }, "totalCount": 1 } ``` ### Execute Tool **POST** `/:toolName/execute` - **Authentication**: Required - **Parameters**: - `toolName` (path): Tool identifier — accepts kebab-case (`chucknorris-get-joke`) or snake_case (`chucknorris_get_joke`). Resolves across native orchestrator tools, agent/workflow/goal/code/widget/tool-forge tools, registry tools, and installed plugin tools. - **Body**: ```json { "args": { "category": "dev" } } ``` - **Description**: Universal tool execution endpoint. Invokes any registered tool by name with the supplied arguments and returns the parsed result. Argument validation, OAuth resolution for tools that require it, and registry/plugin dispatch are all handled internally — this is the same pipeline the chat orchestrator uses to call tools. - **Response (success)**: ```json { "success": true, "tool": "chucknorris-get-joke", "result": { "joke": "Chuck Norris doesn't write code...", "id": "abc123", "categories": ["dev"], "url": "https://api.chucknorris.io/jokes/abc123" } } ``` - **Response (tool reported failure)**: ```json { "success": false, "tool": "chucknorris-get-joke", "error": "Validation failed: 'category' must be one of [...]", "details": { "...": "full payload returned by the tool" } } ``` - **Response 401**: `{ "success": false, "error": "Authentication required" }` --- ## User Routes Base path: `/api/users` ### Health Check **GET** `/health` - **Authentication**: None - **Description**: Check if the user service is running - **Response**: ```json { "status": "OK" } ``` ### Get User Stats **GET** `/user-stats` - **Authentication**: Required - **Description**: Get user statistics - **Response**: ```json { "agents": 5, "workflows": 10, "tools": 3, "goals": 2, "executions": 100, "storageUsed": "1.2GB" } ``` ### Get User Settings **GET** `/settings` - **Authentication**: Required - **Description**: Get user settings - **Response**: ```json { "theme": "dark", "language": "en", "notifications": { "email": true, "push": false }, "preferences": {} } ``` ### Update User Settings **PUT** `/settings` - **Authentication**: Required - **Body**: ```json { "theme": "light", "language": "es", "notifications": { "email": false, "push": true } } ``` - **Response**: ```json { "success": true, "settings": { "theme": "light", "language": "es", "notifications": { "email": false, "push": true } } } ``` ### Get User Preferences **GET** `/preferences` - **Authentication**: Required - **Description**: Cross-device UI preferences (theme, font, panel geometry). Distinct from `/settings`, which holds account-level AI configuration and is replace-on-write. - **Query params**: - `deviceId` (optional) — 1-64 chars of `[A-Za-z0-9_-]`. When supplied, that device's geometry is resolved into `preferences.device`. When omitted the response shape is unchanged: `device` is `{}` and `deviceId` is `null`, while `global` and `knownDevices` are still returned in full. `knownDevices` is deliberately not gated on `deviceId` — a caller listing a user's devices has no device of its own to name. - **Response**: ```json { "success": true, "preferences": { "global": { "currentTheme": "dark", "fontFamily": "sans", "bgOpacity": 90 }, "device": { "uiScale": 100, "leftPanelWidth": 384 }, "deviceId": "dev-abc123", "updatedAt": 1786029683945, "knownDevices": [ { "deviceId": "dev-abc123", "label": "iMac", "updatedAt": 1786029683945, "current": true } ] } } ``` ### Update User Preferences **PUT** `/preferences` - **Authentication**: Required - **Description**: Merges a patch into the stored preferences. Send only the keys that changed; unsent keys are preserved, so an older client cannot erase a key it does not know about. An explicit `null` deletes a key. - **Scopes**: `global` keys (theme, font, background treatment) sync everywhere. `device` keys (panel widths, UI scale, collapse state) are stored per `deviceId`, because pixel geometry chosen on a 27-inch display is wrong on a laptop. - **Conflict resolution**: `global` is last-write-wins on `updatedAt`; a patch older than the stored state is ignored and reported as `result.global.staleIgnored`. `device` writes always apply, being uncontended by construction. - **Body**: ```json { "global": { "currentTheme": "cyberpunk", "fontFamily": null }, "device": { "leftPanelWidth": 420 }, "deviceId": "dev-abc123", "deviceLabel": "iMac", "updatedAt": 1786029683945 } ``` - **Notes**: - `updatedAt` (epoch ms) should be the moment the user acted, not the moment the request was built. Defaults to server time when omitted. - `deviceId` is required whenever `device` is present (400 otherwise). - Unknown or malformed keys are dropped, not stored, and are listed in `result.*.rejected` so a client can see the write was refused. - Custom background media is **not** synced — it lives in browser IndexedDB. Only the `useCustomBackground` / `bgOpacity` / `bgBlur` treatment flags cross devices. - **Response**: ```json { "success": true, "preferences": { "global": { "currentTheme": "cyberpunk" }, "device": { "leftPanelWidth": 420 }, "deviceId": "dev-abc123", "updatedAt": 1786029683945, "knownDevices": [] }, "result": { "global": { "applied": ["currentTheme"], "deleted": ["fontFamily"], "rejected": [], "staleIgnored": false }, "device": { "applied": ["leftPanelWidth"], "deleted": [], "rejected": [], "deviceId": "dev-abc123" }, "evictedDevices": [] } } ``` - **Errors**: `400` malformed body / missing `deviceId` / non-numeric `updatedAt`; `404` user not found; `413` payload exceeds 64 KB. ### Sync Token **POST** `/sync-token` - **Authentication**: Required - **Description**: Sync user token across services - **Response**: ```json { "success": true, "message": "Token synced successfully" } ``` ### Get Token Status **GET** `/token-status` - **Authentication**: None - **Description**: Get current token status - **Response**: ```json { "valid": true, "expiresIn": 3600, "refreshRequired": false } ``` ### Get Connection Health **GET** `/connection-health` - **Authentication**: Required - **Description**: Get health status of all provider connections - **Response**: ```json { "success": true, "data": { "overall": "healthy|degraded", "healthyConnections": 51, "totalConnections": 52, "timestamp": "2026-01-01T15:42:40.838Z", "providers": [ { "provider": "openai", "status": "healthy", "lastChecked": "2026-01-01T15:42:39.786Z", "details": {} }, { "provider": "anthropic", "status": "healthy", "lastChecked": "2026-01-01T15:42:37.303Z", "details": {} }, { "provider": "twitter", "status": "error", "lastChecked": "2026-01-01T15:42:40.643Z", "error": "Failed to retrieve access token from remote auth service." } ] } } ``` **Important**: - The response wraps data in a `data` object, not at the root level. - Provider status values are `"healthy"` or `"error"` (not `"connected"`). - Each provider object has a `provider` field (lowercase provider name), not `name` or `id`. - Failed providers include an `error` field instead of `details`. ### Get Single Provider Health **GET** `/connection-health/:providerId` - **Authentication**: Required - **Parameters**: - `providerId` (path): Provider ID - **Description**: Get health status of a specific provider - **Response**: ```json { "id": "openai", "name": "OpenAI", "status": "connected", "lastCheck": "2024-01-01T00:00:00Z", "latency": 150, "details": {} } ``` ### Get Connection Health Stream **GET** `/connection-health-stream` - **Authentication**: Required (via token query parameter) - **Parameters**: - `token` (query): JWT token - **Description**: Get real-time connection health updates via SSE - **Response**: Server-sent events stream --- ### Get Security Policy **GET** `/security-policy` - **Authentication**: Required - **Description**: The current user's security policy - **Response**: Security policy object ### Update Security Policy **PUT** `/security-policy` - **Authentication**: Required - **Description**: Update the current user's security policy - **Response**: Updated security policy object ### Reset Security Policy **DELETE** `/security-policy` - **Authentication**: Required - **Description**: Reset the current user's security policy to defaults - **Response**: Confirmation object ### Get Security Audit **GET** `/security-audit` - **Authentication**: Required - **Description**: Security audit information for the current user - **Response**: Security audit object --- ## Wallet Routes Base path: `/api/wallets` Linear-type capability budgets (PRD-091 Layer 3). Each user has a **root wallet**; sub-wallets are derived via `WalletService.allocate` and can never duplicate funds because every debit and transfer goes through an atomic guard with a `balance >= amount` check. Conservation invariant: across allocate / consume / release cycles, the sum of all active balances is exactly `(root topup total) - (total consumed)`. The agent can rely on this — see `WalletService.spec.js` invariant tests. ### Wallet shape ```json { "id": "uuid", "user_id": "user-uuid", "owner_type": "user|agent|workflow|tool|run", "owner_id": "owner-uuid", "parent_id": "uuid|null", "kind": "tokens", "balance": 850, "status": "active|closed", "created_at": "...", "updated_at": "..." } ``` ### List Wallets **GET** `/` - **Authentication**: Required - **Parameters**: - `ownerType` (query, optional): filter by owner type - `status` (query, optional): `active`, `closed` - **Response**: ```json { "success": true, "wallets": [ { ... } ] } ``` ### Get-or-Create Root Wallet **GET** `/root` - **Authentication**: Required - **Description**: Returns the user's root wallet (`owner_type:'user'`, `parent_id:null`). Creates it on first call with `balance:0`. - **Response**: ```json { "success": true, "wallet": { ... } } ``` ### Top Up Root Wallet **POST** `/root/topup` - **Authentication**: Required - **Body**: ```json { "amount": 1000, "note": "monthly_recharge" } ``` - **Description**: Adds `amount` to the user's root wallet balance and writes a `topup` ledger entry. Idempotent on the API surface — repeated calls add repeatedly, so the agent should confirm with the user before topping up. - **Response**: ```json { "success": true, "wallet": { ... } } ``` - **Errors**: `400` on invalid amount. ### Get Single Wallet **GET** `/:id` - **Authentication**: Required - **Response**: ```json { "success": true, "wallet": { ... } } ``` - **Errors**: `404` not found, `403` forbidden ### Get Wallet Ledger **GET** `/:id/ledger` - **Authentication**: Required - **Parameters**: - `limit` (query, optional): max `1000`, default `200` - **Description**: Returns the transaction log for this wallet. Each entry has `amount` (negative for debit), `op` (`topup` / `consume` / `allocate_in` / `allocate_out` / `release_sweep` / `release_recv`), optional `source_kind` / `source_id` linking to the asset that spent (e.g. tool, agent run). - **Response**: ```json { "success": true, "ledger": [ { "id": "led-uuid", "wallet_id": "wal-uuid", "amount": -30, "op": "consume", "source_kind": "tool", "source_id": "web-search", "note": null, "created_at": "..." } ] } ``` ### Release Wallet **POST** `/:id/release` - **Authentication**: Required - **Description**: Sweeps the wallet's remaining balance back to its parent (if any), then marks the wallet `closed`. Safe to call multiple times — a second call on an already-closed wallet is a no-op. - **Response**: ```json { "success": true, "wallet": { ... } } ``` - **Use case**: An agent run finishes; release its sub-wallet so the leftover budget flows back to root. ### Notes on consume / allocate There is currently **no public HTTP endpoint** for `consume` or `allocate`. Those operations live on the server-side `WalletService` and are invoked by tool executors, the orchestrator, and the scheduler. The HTTP surface is intentionally limited to read + root-topup + release — i.e. the operations a UI or agent on behalf of a user needs. Agent code that needs to debit an arbitrary wallet should call `WalletService.consume(walletId, amount)` directly, not over HTTP. --- ## Webhook Routes Base path: `/api/webhooks` ### Get All Webhooks **GET** `/` - **Authentication**: Required - **Description**: Get all webhooks for the authenticated user - **Response**: ```json { "success": true, "webhooks": [ { "id": "webhook-id", "workflowId": "workflow-id", "url": "https://example.com/webhook", "secret": "webhook-secret", "events": ["trigger"], "active": true, "createdAt": "2024-01-01T00:00:00Z" } ] } ``` ### Get Webhook by Workflow ID **GET** `/workflow/:workflowId` - **Authentication**: Required - **Parameters**: - `workflowId` (path): Workflow ID - **Description**: Get webhook associated with a specific workflow - **Response**: ```json { "success": true, "webhook": { "id": "webhook-id", "workflowId": "workflow-id", "url": "https://example.com/webhook", "secret": "webhook-secret", "events": ["trigger"], "active": true, "createdAt": "2024-01-01T00:00:00Z" } } ``` ### Delete Webhook by Workflow ID **DELETE** `/workflow/:workflowId` - **Authentication**: Required - **Parameters**: - `workflowId` (path): Workflow ID - **Description**: Delete webhook associated with a specific workflow - **Response**: ```json { "success": true, "message": "Webhook deleted successfully" } ``` --- ## Widget Definition Routes Base path: `/api/widget-definitions` Manage custom widget definitions for the dashboard. Widgets are user-created HTML/JS components that can be placed on layout pages. ### Get All Widget Definitions **GET** `/` - **Authentication**: Required - **Description**: Get all widget definitions for the user (including shared ones) - **Response**: ```json { "widgets": [ { "id": "cw_abc123def456", "user_id": "user-id", "name": "System Monitor", "description": "Displays system metrics", "icon": "fas fa-chart-line", "category": "monitoring", "widget_type": "html", "source_code": "
...
", "config": {}, "data_bindings": [], "default_size": { "cols": 4, "rows": 3 }, "min_size": { "cols": 2, "rows": 2 }, "useThemeStyles": true, "is_shared": 0, "is_published": 0, "version": "1.0.0", "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-01T00:00:00Z" } ] } ``` ### Get Widget Definition by ID **GET** `/:widgetId` - **Authentication**: Required - **Parameters**: - `widgetId` (path): Widget definition ID - **Response**: ```json { "widget": { ... } } ``` - **Error** (404): Widget definition not found ### Create Widget Definition **POST** `/` - **Authentication**: Required - **Body**: ```json { "name": "My Widget", "description": "A custom widget", "icon": "fas fa-puzzle-piece", "category": "custom", "widget_type": "html", "source_code": "
Hello World
", "config": {}, "data_bindings": [], "default_size": { "cols": 4, "rows": 3 }, "min_size": { "cols": 2, "rows": 2 }, "useThemeStyles": true } ``` - **Response** (201): ```json { "message": "Widget definition created", "id": "cw_abc123def456", "widget": { ... } } ``` ### Update Widget Definition **PUT** `/:widgetId` - **Authentication**: Required - **Parameters**: - `widgetId` (path): Widget definition ID - **Description**: Partial update — only provided fields are changed - **Body**: ```json { "name": "Updated Name", "source_code": "
Updated
", "is_shared": true, "useThemeStyles": false } ``` - **Response**: ```json { "message": "Widget definition updated", "id": "cw_abc123def456" } ``` ### Delete Widget Definition **DELETE** `/:widgetId` - **Authentication**: Required - **Parameters**: - `widgetId` (path): Widget definition ID - **Response**: ```json { "message": "Widget definition deleted", "id": "cw_abc123def456" } ``` ### Duplicate Widget Definition **POST** `/:widgetId/duplicate` - **Authentication**: Required - **Parameters**: - `widgetId` (path): Widget definition ID to duplicate - **Description**: Create a copy of an existing widget definition with " (copy)" appended to the name - **Response** (201): ```json { "message": "Widget duplicated", "id": "cw_newid123456" } ``` ### Export Widget Definition **GET** `/:widgetId/export` - **Authentication**: Required - **Parameters**: - `widgetId` (path): Widget definition ID - **Description**: Export a widget definition as a portable JSON object - **Response**: ```json { "export": { "_format": "agnt-widget", "_version": "1.0.0", "name": "My Widget", "description": "A custom widget", "icon": "fas fa-puzzle-piece", "category": "custom", "widget_type": "html", "source_code": "
Hello World
", "config": {}, "data_bindings": [], "default_size": { "cols": 4, "rows": 3 }, "min_size": { "cols": 2, "rows": 2 }, "exported_at": "2024-01-01T00:00:00Z" } } ``` ### Import Widget Definition **POST** `/import` - **Authentication**: Required - **Description**: Import a widget definition from an exported JSON object - **Body**: ```json { "widget_data": { "_format": "agnt-widget", "_version": "1.0.0", "name": "Imported Widget", "source_code": "
Imported
", ... } } ``` - **Response** (201): Same as Create Widget Definition ### Capture Widget Thumbnail **POST** `/capture-thumbnail` - **Authentication**: Required - **Description**: Render an HTML widget in a headless Puppeteer browser and return a JPEG screenshot as a base64 data URL. The renderer reuses a persistent browser instance (auto-closed after 60s idle) and auto-dismisses any `alert`/`confirm`/`prompt` dialogs so popup-heavy widgets don't block. - **Body**: ```json { "html": "...", "storageData": { "token": "", "...": "any other localStorage keys to inject before render" } } ``` - `html` (required): Full HTML document for the widget. - `storageData` (optional): Object whose keys/values get written into the headless page's `localStorage` before the widget loads. Pass the user's token here if the widget makes authenticated fetches during render. - **Response**: ```json { "thumbnail": "data:image/jpeg;base64,..." } ``` - **Notes**: Used by the widget editor and by the orchestrator's chat-driven widget flow (`generate_widget` / `edit_widget_code`). Capture is fire-and-forget from the frontend — the resulting `thumbnail` data URL is then PUT back to `/api/widget-definitions/:widgetId` to persist. --- ## Workflow Routes Base path: `/api/workflows` ### Health Check **GET** `/health` - **Authentication**: None - **Handler**: `WorkflowService.healthCheck` - **Description**: Check if the workflow service is running - **Response**: ```json { "status": "OK" } ``` ### Get All Workflows **GET** `/` - **Authentication**: Required - **Handler**: `WorkflowService.getAllWorkflows` - **Description**: Retrieve all workflows for the authenticated user - **Response**: ```json [ { "id": "workflow-id", "name": "Workflow Name", "description": "Workflow description", "status": "active|inactive", "nodes": [], "edges": [], "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ] ``` ### Get All Workflows Summary **GET** `/summary` - **Authentication**: Required - **Handler**: `WorkflowService.getAllWorkflowsSummary` - **Description**: Retrieve a lightweight summary of all workflows for the authenticated user (no full workflow_data). This is registered **before** any `/:id` routes in Express to avoid path conflicts. - **Response**: ```json [ { "id": "workflow-id", "name": "Workflow Name", "status": "active", "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-01T00:00:00Z" } ] ``` ### Save Workflow **POST** `/save` - **Authentication**: Required - **Handler**: `WorkflowService.saveWorkflow` - **Body**: the workflow wrapped in `workflow` (omit `id` to create one): ```json { "workflow": { "id": "optional-workflow-id", "name": "Workflow Name", "description": "Workflow description", "nodes": [ { "id": "n1", "type": "generic-trigger", "category": "trigger", "text": "Start", "parameters": {} }, { "id": "n2", "type": "generate-with-ai-llm", "text": "Draft Reply", "parameters": { "prompt": "{{Start.output}}" } } ], "edges": [{ "id": "e1", "start": { "id": "n1" }, "end": { "id": "n2" } }] } } ``` - **Node and edge rules** (`validateWorkflowShape`, what the engine dereferences): every node needs a unique non-empty `id`, a `type` (the tool or trigger to run) and a `text`, its display name, lowercased to resolve `{{Node Name.output}}` references. Every edge needs `start.id` and `end.id` naming declared nodes. Absent `nodes`/`edges` save as an empty draft. - **Response** (`201`): ```json { "message": "New workflow created", "workflowId": "workflow-id" } ``` `message` is `"New workflow created"` or `"Workflow updated"`. **Errors**: `400` `Request body must be { workflow: { ... } } with a workflow object.`, or `400` `Workflow does not match the shape the workflow engine executes.` with `details` naming each node/edge and field. ### Analyze Dependencies **POST** `/analyze-dependencies` - **Authentication**: Required - **Handler**: `WorkflowService.analyzeDependencies` - **Description**: Analyze node dependencies within a workflow. This is registered **before** any `/:id` routes in Express to avoid path conflicts. - **Body**: Workflow data with nodes and edges - **Response**: Dependency analysis result ### Get Workflow by ID **GET** `/:id` - **Authentication**: Required - **Handler**: `WorkflowService.getWorkflowById` - **Parameters**: - `id` (path): Workflow ID - **Description**: Retrieve a specific workflow by ID - **Response**: ```json { "id": "workflow-id", "name": "Workflow Name", "description": "Workflow description", "status": "active|inactive", "nodes": [], "edges": [], "config": {}, "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } ``` ### Update Workflow **PUT** `/:id` - **Authentication**: Required - **Handler**: `WorkflowService.updateWorkflow` - **Parameters**: - `id` (path): Workflow ID - **Body**: the same `{ workflow: { ... } }` shape and node/edge rules as [Save Workflow](#save-workflow); a flat body is refused with `400`: ```json { "workflow": { "name": "Updated Workflow Name", "nodes": [{ "id": "n1", "type": "generic-trigger", "category": "trigger", "text": "Start", "parameters": {} }], "edges": [] } } ``` - **Response** (`200`): ```json { "message": "Workflow updated", "workflowId": "workflow-id" } ``` ### Delete Workflow **DELETE** `/:id` - **Authentication**: Required - **Handler**: `WorkflowService.deleteWorkflow` - **Parameters**: - `id` (path): Workflow ID - **Description**: Delete a workflow by ID - **Response**: ```json { "success": true, "message": "Workflow deleted successfully" } ``` ### Rename Workflow **PUT** `/:id/name` - **Authentication**: Required - **Handler**: `WorkflowService.renameWorkflow` - **Parameters**: - `id` (path): Workflow ID - **Body**: ```json { "name": "New Workflow Name" } ``` - **Response**: ```json { "success": true, "workflow": { "id": "workflow-id", "name": "New Workflow Name", "description": "Workflow description", "status": "inactive", "nodes": [], "edges": [], "config": {}, "createdAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z" } } ``` ### Get Workflow Status **GET** `/:id/status` - **Authentication**: Required - **Handler**: `WorkflowService.fetchWorkflowState` - **Parameters**: - `id` (path): Workflow ID - **Description**: Fetch the current state of a workflow - **Response**: ```json { "workflowId": "workflow-id", "status": "active|inactive|error", "lastExecution": "2024-01-01T00:00:00Z", "executionCount": 10, "errorCount": 0, "state": {} } ``` > **Note**: The status values are `active`, `inactive`, or `error`. There is no `completed`, `failed`, or `progress` field. This endpoint returns the workflow's activation state, not an execution progress tracker. > **⚠ CONTRACT CHANGE — `/start`, `/stop` and `/:id/status` now report failure with a failure status.** > > These three used to answer **`200` with an error inside the body** when the > operation had not happened. `activateWorkflow` ended in `res.json(result)` > with no status argument, and `WorkflowProcessBridge` returned > `{ status: 'error' }` as though "error" were a workflow state — so a start > that never armed was indistinguishable from one that did. > > Every in-tree caller gates on `response.ok`, which meant a workflow could > report "started" with nothing listening, no trigger registered, and no error > shown to the user. > > They now answer **`503`** when the workflow process is unreachable and > **`500`** when the operation itself failed. > > **Who this affects.** The JavaScript SDK (`base/js/libs/agnt.js`) is axios, > which rejects on non-2xx. Any integration that was quietly receiving > `{ error }` at `200` and reading it as success will now throw. That is the > point of the change — but it is a breaking change for anything that had > adapted to the old behaviour. ### Activate Workflow (Start) **POST** `/:id/start` - **Authentication**: Required - **Handler**: `WorkflowService.activateWorkflow` - **Parameters**: - `id` (path): Workflow ID - **Description**: Activate a workflow so it begins listening for triggers (e.g., timer, webhook). It runs the SAVED workflow; it does **not** accept runtime `inputs`, it toggles the workflow's active state. - **Response** (`200`): what the workflow process reports, for example: ```json { "message": "Workflow queued for execution" } ``` - **Errors**: - `404` — no such workflow for the caller. - `409` `{ code: 'ALREADY_ACTIVE' }` — it is already running. - `400` `{ code: 'invalid_trigger', details }` — a trigger's parameters are not ones its type accepts (for example a timer `schedule` that is not one of its options). `details` names each node, field and the allowed values. A node whose `type` is a trigger (`trigger-*`, `generic-trigger`, `webhook-listener`, `receive-*`) is treated as one even without `"category": "trigger"`. - `403` `{ code: 'team_policy_denied', permission: 'workflows.run' }`, or a 403 for a missing `runs.execute` / `connections.use` — in a team scope (`X-AGNT-Team-ID`), the owner has not allowed this teammate to run here (see [Team Routes](#team-routes), "Running teamspace items"). Teammates' runs act as themselves, in the tool sandbox. - `403` `{ code: 'team_policy_denied', permission }` — the team owner has turned off a permission this workflow needs (`workflows.run`, `automations.schedule` or `triggers.external`). - `403` `{ error: 'Upgrade required', code: 'PLAN_REQUIRED' | 'PLAN_LIMIT' }` — the plan does not include its triggers or automation. - `503` — the workflow process is not reachable, so the start could not be attempted. Retryable. - `500` — the start was attempted and failed. ### Run Workflow Now **POST** `/:id/run` - **Authentication**: Required - **Handler**: `WorkflowService.runWorkflowOnce` - **Parameters**: - `id` (path): Workflow ID - `input` (body, optional): an object. The trigger node passes it on as its output, so later nodes read it as the trigger's output. - **Description**: Run the SAVED workflow once, now, starting from its trigger node(s), whatever the trigger type (timer, webhook, email, `generic-trigger`), and answer when it finishes. It does **not** switch the workflow on: its switched-on state is left exactly as it was. Use it to test a workflow, or to fire a generic trigger by hand. In a team scope it runs as the caller, under the same rules as `/start`. Recorded as a normal run in `/executions`. - **Response** (`200` when every node succeeded, `422` when one failed): ```json { "success": true, "executionId": "execution-id", "outputs": { "n1": {}, "n2": { "result": 42 } }, "errors": {} } ``` - **Errors**: `404` no such workflow; `403` the team owner has not allowed this teammate to run here; `500` the run could not start. ### Deactivate Workflow (Stop) **POST** `/:id/stop` - **Authentication**: Required - **Handler**: `WorkflowService.deactivateWorkflow` - **Parameters**: - `id` (path): Workflow ID - **Description**: Deactivate a workflow so it stops listening for triggers. This does **not** cancel a currently-running execution — it toggles the workflow's active state to inactive. - **Response**: ```json { "success": true, "message": "Workflow deactivated successfully", "workflowId": "workflow-id" } ``` --- ### Workflow Version Control Routes > These endpoints manage workflow version history, checkpoints, and comparisons. > > `/:workflowId/versions/compare` and `/:workflowId/versions/stats` are registered before `/:workflowId/versions/:versionId`, so neither is taken as a version id. ### List Workflow Versions **GET** `/:workflowId/versions` - **Authentication**: Required - **Handler**: `WorkflowVersionService.getVersionHistory` - **Parameters**: - `workflowId` (path): Workflow ID - `limit` (query, optional): Max versions to return (default: 50) - `offset` (query, optional): Pagination offset (default: 0) - `checkpointsOnly` (query, optional): If `"true"`, only return checkpoint versions - **Description**: List the version history for a workflow - **Response**: ```json { "success": true, "versions": [ { "version_number": 5, "source": "chat", "change_description": "Added new API node", "is_checkpoint": false, "checkpoint_name": null, "created_at": "2024-01-01T00:00:00Z" } ] } ``` ### Get Specific Version **GET** `/:workflowId/versions/:versionId` - **Authentication**: Required - **Handler**: `WorkflowVersionService.getVersion` - **Parameters**: - `workflowId` (path): Workflow ID - `versionId` (path): Version number (integer) - **Description**: Get the full data for a specific workflow version - **Response**: ```json { "success": true, "version": { "version_number": 3, "workflow_state": { "...": "..." }, "source": "manual", "change_description": "Checkpoint before refactor", "is_checkpoint": true, "checkpoint_name": "Pre-refactor", "created_at": "2024-01-01T00:00:00Z" } } ``` - **Error** (404): Version not found ### Revert to Version **POST** `/:workflowId/revert` - **Authentication**: Required - **Handler**: `WorkflowVersionService.revertToVersion` - **Parameters**: - `workflowId` (path): Workflow ID - **Description**: Revert a workflow to a previous version. Broadcasts `workflow:reverted` via WebSocket. - **Body**: ```json { "versionId": 3 } ``` - **Validation**: `versionId` is required (returns 400 if missing) - **Response**: ```json { "success": true, "revertedToVersion": 3, "workflowState": { "...": "..." } } ``` ### Create Checkpoint **POST** `/:workflowId/checkpoint` - **Authentication**: Required - **Handler**: `WorkflowVersionService.createCheckpoint` - **Parameters**: - `workflowId` (path): Workflow ID - **Description**: Save a named checkpoint of the current workflow state - **Body**: ```json { "name": "Before big changes", "currentWorkflowState": { "...": "..." } } ``` - **Validation**: Both `name` and `currentWorkflowState` are required (returns 400 if either is missing) - **Response**: ```json { "success": true, "versionNumber": 6, "checkpointName": "Before big changes" } ``` ### Compare Versions **GET** `/:workflowId/versions/compare?versionA=1&versionB=3` - **Authentication**: Required - **Handler**: `WorkflowVersionService.compareVersions` - **Parameters**: - `workflowId` (path): Workflow ID - `versionA` (query, required): First version number - `versionB` (query, required): Second version number - **Description**: Get a diff between two workflow versions - **Validation**: Both `versionA` and `versionB` are required (returns 400 if either is missing) - **Response**: ```json { "success": true, "diff": { "nodesAdded": [], "nodesRemoved": [], "nodesModified": [], "edgesAdded": [], "edgesRemoved": [] } } ``` ### Version Storage Stats **GET** `/:workflowId/versions/stats` - **Authentication**: Required - **Handler**: `WorkflowVersionService.getStorageStats` - **Parameters**: - `workflowId` (path): Workflow ID - **Description**: Get storage statistics for a workflow's version history - **Response**: ```json { "success": true, "stats": { "totalVersions": 12, "checkpoints": 3, "totalSizeBytes": 45678, "oldestVersion": "2024-01-01T00:00:00Z", "newestVersion": "2024-03-01T00:00:00Z" } } ``` --- ### Export Workflow **GET** `/:id/export` - **Authentication**: Required - **Description**: Exports a workflow as a portable envelope (PRD-057). `403` if the workflow is not shareable and belongs to another user; `404` if not found. - **Response**: Workflow envelope JSON ### Import Workflow **POST** `/import` - **Authentication**: Required - **Description**: Imports a workflow envelope (PRD-057). `201` on success; `400` on a malformed envelope. Reports tool types referenced by the workflow that aren't installed locally. - **Body**: `{ "envelope": {...} }` (or the envelope object directly) - **Response**: ```json { "success": true, "workflowId": "uuid", "missingToolTypes": [] } ``` --- ## System Routes Base path: `/api/system` System-level operations: status and restart. ### Get System Status **GET** `/status` - **Authentication**: None — intentionally unauthenticated: the frontend polls this while the backend drains/reboots, and the Electron supervisor may check it too. Exposes nothing sensitive (state/pid/uptime). - **Response**: RestartManager status object (state, pid, uptime) ### Restart Backend **POST** `/restart` - **Authentication**: Required - **Description**: Initiates a backend restart. Responds `202` first, then starts the drain — the 2s grace period guarantees the response flushes before the socket dies. Backend is back in ~10–20 seconds. `409` if a restart is already in progress. - **Body**: ```json { "reason": "optional reason string" } ``` - **Response** (202): ```json { "success": true, "message": "Restart initiated. Backend will be back in ~10-20 seconds.", "gracePeriodMs": 2000 } ``` --- ## Pairing Routes Base path: `/api/pairing` Lets a phone join an authenticated session by scanning a QR code, so a JWT never has to be typed on a phone keyboard. Also owns the "Allow phone access" toggle (Settings -> Configuration -> Phone Access), which controls the interface the backend binds to. ### Protocol 1. An authenticated client `POST /code`. The server mints a 128-bit single-use code with a 120 s TTL and stashes **the caller's own token** against it, in memory only — never on disk, never in the database. 2. The QR encodes only `/pair?c=` — **never the token**. QR codes get photographed, screen-shared and left on desks; a 2-minute single-use code is a far smaller blast radius than a 7-day JWT. 3. The phone opens that URL and `POST /claim` with the code. The code is consumed atomically and the token is returned exactly once. The phone receives the initiator's existing token rather than a freshly signed one on purpose: under `TRUST_REMOTE_AUTH` the tokens that matter are issued by the remote auth server, and a locally-signed substitute would pass local verification while failing every upstream call. Handing over the real token gives the phone exactly the same capabilities as the desktop that authorised it, and nothing more. ### Which origin goes in the QR The address is derived from **the request that asked for the code**, not from the server's own network interfaces. A client that just reached the server has demonstrated an address that works; a network-interface scan is only correct when the server happens to be the machine the user is sitting at. Resolution order (first hit wins), implemented in `backend/src/services/ReachableOrigin.js`: | # | Source | Where it comes from | |---|--------|---------------------| | 1 | `configured` | `PUBLIC_ORIGIN` env, or `publicOrigin` in `remote-access.json` | | 2 | `forwarded` | `X-Forwarded-Proto` / `-Host` / `-Port`, **only from a peer trusted under `TRUST_PROXY`** | | 3 | `request` | The `Host` header — the address this client actually used | | 4 | `interface` | Network-interface scan; withheld when the socket is loopback-only, since nothing is listening on those addresses | Sources 1-3 are evidence. Source 4 is inference, so it is suppressed when it cannot be true. All usable candidates are returned so an ambiguous topology (multi-homed host, VPN alongside Wi-Fi, split-horizon DNS) can be resolved by the one participant who knows the answer: the user. `X-Forwarded-*` is gated because it decides where a pairing code is sent — an unauthenticated header that anyone able to reach the port can invent. The trust decision reads the **socket peer**, never `req.ip` (which Express rewrites from `X-Forwarded-For` once `trust proxy` is enabled). | `TRUST_PROXY` | Peers whose forwarded headers are honoured | |---------------|--------------------------------------------| | unset / `loopback` (default) | `127.0.0.0/8`, `::1` — a reverse proxy on the same machine | | `private` | also RFC1918 peers — Docker/compose sibling containers | | `all` / `true` / `1` | any peer. Only on a network you fully control | | `none` / `false` / `0` | never | ### Get Pairing Status **GET** `/status` - **Authentication**: Required - **Description**: Where this server is reachable, whether LAN access is on, and whether the running socket matches the saved setting. `lanEnabled` describes **reality** (the open socket or a live external request), while `desiredLanEnabled` reflects the saved toggle — they disagree while a restart is pending, and the UI needs both. - **Response**: ```json { "success": true, "lanEnabled": true, "bindHost": "0.0.0.0", "bindSource": "config", "restartRequired": false, "port": 3333, "desiredLanEnabled": true, "networkName": "Example Network 5G", "lastExternalRequest": { "ip": "192.168.1.77", "at": "2026-07-28T10:14:02.001Z" }, "addresses": [{ "address": "192.168.1.50", "iface": "Wi-Fi" }], "origins": [ { "origin": "http://192.168.1.50:3333", "source": "interface", "label": "This machine on Wi-Fi", "external": true } ], "urls": ["http://192.168.1.50:3333"] } ``` - `networkName` is best-effort and `null` on wired or unknown setups — it turns "connect your phone to the same Wi-Fi" into an instruction the user can check. - `lastExternalRequest` is `null` until something other than this machine reaches the server. It separates "the phone never got here" from "it got here and something later went wrong". - `urls` is the flat list of externally-usable origins, kept for older frontends. Prefer `origins`. ### Set LAN Access **POST** `/lan-access` - **Authentication**: Required - **Description**: Persists the "Allow phone access" toggle to `remote-access.json`. The open socket does not move, so this almost always returns `restartRequired: true`. `BIND_HOST` in the environment outranks the toggle; when it does, `envPinned` is `true` and the message says so rather than letting the user flip a switch that silently does nothing. - **Body**: ```json { "enabled": true } ``` - **Response**: ```json { "success": true, "lanEnabled": false, "desiredLanEnabled": true, "envPinned": false, "restartRequired": true, "message": "Saved. Restart the backend to apply it." } ``` Apply it with **POST** `/api/system/restart`. ### Create Pairing Code **POST** `/code` - **Authentication**: Required - **Rate limit**: 20 per minute; at most 20 codes outstanding (`429` beyond either) - **Description**: Mints a single-use code and returns a scannable URL per reachable origin. The response never contains a token. - **Response** (200): ```json { "success": true, "code": "5f3c…32 hex chars", "expiresAt": 1785312000000, "ttlMs": 120000, "url": "https://agnt.example.com/pair?c=5f3c…", "origin": "https://agnt.example.com", "origins": [ { "origin": "https://agnt.example.com", "source": "forwarded", "label": "Via reverse proxy", "external": true, "url": "https://agnt.example.com/pair?c=5f3c…" } ], "addresses": [{ "address": "192.168.1.50", "iface": "Wi-Fi" }] } ``` The code is held in server memory keyed only by itself, so it is claimable from **any** origin that reaches the server — which is what makes offering a choice of `origins` honest rather than decorative. - **Response** (409) — nothing could redeem it, so no code is minted: ```json { "success": false, "error": "This server is only listening on localhost, and nothing else has reached it, so a phone cannot connect.", "restartRequired": true, "bindHost": "127.0.0.1" } ``` A loopback-bound server behind a reverse proxy does **not** hit this — binding to loopback is the correct configuration there, and a live proxied request is proof that something external can reach us. - **Note**: the URL uses the history-mode path `/pair?c=`, not `#/pair`. The frontend router uses `createWebHistory`, so a fragment would load `/` and never mount the pairing view. ### Claim Pairing Code **POST** `/claim` - **Authentication**: **None — by design.** The code *is* the credential. This is the one endpoint a not-yet-authenticated phone must be able to call. - **Rate limit**: 10 per minute. 128 bits is already unguessable; the limiter makes it not worth the packets. - **Body**: ```json { "code": "5f3c…32 hex chars" } ``` - **Response** (200): ```json { "success": true, "token": "", "user": { "id": "u1", "email": "a@b.c" } } ``` - **Errors**: `400` malformed code (validated as `/^[a-f0-9]{32}$/` before any lookup); `404` invalid, already used, or expired; `401` the authorising session expired between mint and claim. - Lookup is time-equalised across hit and miss so it cannot be used as an oracle. ### Revoke All Codes **POST** `/revoke` - **Authentication**: Required - **Description**: Drops every outstanding code. Already-claimed tokens are unaffected — this cancels pending pairings, it does not sign anyone out. - **Response**: ```json { "success": true, "revoked": 2 } ``` --- ## Image Routes Base path: `/api/images` Serves images generated by the image-generation tools. ### Get Image **GET** `/:id` - **Authentication**: Required - **Description**: Serves a stored generated image by id with the correct content type and `Cache-Control: private, max-age=31536000, immutable`. `404` if not found. - **Response**: Image bytes --- ## Local File Routes Base path: `/api/local-file` Streams local files over HTTP with Range support. The chat renderer rewrites `file:///` URLs to this endpoint so `