ai-agents
What it does
CRUD over public.ai_agents (agent definitions: agent_type, model_config, system_prompt, tools, capabilities, constraints), plus action=run — the interactive entry point that executes a multi-turn agent episode against a thread (not against an agent row directly; the agent and prompt config are resolved inside runAgent from the thread's data.agent_id / data.prompt_config_id and type schema).
Route and methods
/.netlify/functions/ai-agents, reachable as /api/ai-agents (/api/* → /.netlify/functions/:splat, .framework/public/_redirects). Dispatch is by ?action= then method:
| Call | Handler |
|---|---|
POST /api/ai-agents?action=run | run (any method dispatches; a JSON body is required in practice) |
GET /api/ai-agents | list |
GET /api/ai-agents?id=<uuid> | get |
POST /api/ai-agents | create |
PATCH /api/ai-agents (id in body or query) | update |
DELETE /api/ai-agents?id=<uuid> | remove |
Authentication
Standard createHandler auth: x-api-key → machine principal, x-internal-secret → internal principal, Bearer <jwt> → human; anonymous → 401.
list/create/update/runrequirectx.accountId.- No role gate anywhere in this file —
create/update/removeonly require an authenticated person+account context; humans are bounded by RLS onctx.db, machines run service-role. rundebits theagent_steprate limit (.framework/functions/_shared/rate-limit.ts) — a fail-closed, cost-bearing action; over-limit throwsRateLimitError(HTTP 429 withretry_after).
Request contract
list (query): agent_type, is_active ('true'/'false'), limit (default 100), offset (default 0).
get (query): id.
create (body): name, agent_type required. Optional: app_id, description, model_config {}, system_prompt, tools [], capabilities [], constraints {}, metadata {}. account_id and created_by stamped from context.
update (id in body or query + body): allowlist — name, description, agent_type, model_config, system_prompt, tools, capabilities, constraints, metadata, is_active, app_id.
remove (query): id — hard delete.
run (body): thread_id required; user_message; mode ('step'/'complete'/'episode', default 'complete'); driver_token (optional — lets a client keep a stable driver identity across calls instead of ctx.requestId).
Response contract
Standard { data, error, meta } envelope.
- CRUD → sanitized row(s) (
{ id }for non-admins);remove→{ success: true }. run→{ ok, thread_id, message_id, status, turn_count, content, message_type, data, agent_id, prompt_config_id }wherestatuscomes from the thread'sdata.research_state(complete,awaiting_input,failed, …).turn_countcounts turns in the current episode — eachrunstarts a fresh episode, so it returns1even on the thread's Nth message; it is not a cumulative thread counter.- The thread a
runbinds to still needstarget_type/target_id(both NOT NULL) — a standalone agent-chat thread has no natural target; attach any record (e.g. the task/item it concerns). messagesincludes internalplan-phase progress rows (sender: 'internal', e.g. "Reviewing your question…") alongside real replies — customer surfaces should filter bydata.message_type/CUSTOMER_STEP_TYPES(.framework/functions/_shared/access.ts).- Lease-refused runs return HTTP 200 with
{ ok: true, status: 'running', driver_id }(plusalready_running: truein episode mode) — callers poll the thread rather than interleave writes. A replay of an already-answered episode returnsstatus: 'complete'withalready_done: trueand the last outbound message.
Side effects
runperforms a prompt-injection pre-flight (detectInjection); the app'sconfig.security.prompt_injectionmode ('off'/'flag'default/'block') decides whether the hit is audited (security.injection_detected) or rejected with HTTP 400.runclaims the thread's episode lease — atomically via theepisode_leasesRPC (.framework/migrations/064_episode_leases.sql), with a legacy heartbeat check as fallback — so concurrent drivers can't double-drive a thread.runexecutesrunAgent(.framework/functions/_shared/agent-runner.ts), which writes agent messages topublic.messagesand mutatesthreads.data .research_state. Episode mode runs inline under an 8-second budget, then the client's step loop continues under the same lease.- Rate limit is debited only after a successful lease claim — refused requests never double-charge an episode.
- CRUD emits
ai_agent.created/.updated/.deletedaudit rows topublic.logs.
Errors
| Condition | HTTP | Message |
|---|---|---|
Missing thread_id | 500 | thread_id is required |
| No person+account context | 500 | User context (person and account) required |
| Missing thread | 500 | Thread not found / PostgREST message |
Injection in block mode | 400 | Your message could not be processed automatically. A support specialist will review it. |
agent_step over limit | 429 | rate-limit message + retry_after |
Missing id | 500 | Agent ID is required |
| Row missing on delete | 500 | Agent not found |
| Bad action/method | 500 | Invalid action or method |
Most Errors map to 500 (no statusCode); the injection-block and rate-limit paths carry explicit 400/429 codes.
Agent notes
runtakes a thread, not an agent id — the agent binding lives onthreads.data.agent_id(or the thread type'sdesign_schema.default_agent_id). Creating anai_agentsrow does not wire it to anything.- Episode single-flight is keyed by
driver_id: pass a stabledriver_tokenfrom a polling client so re-entry renews the lease instead of being refused. - A "stuck" live driver blocks the thread for the 60-second lease TTL —
status: 'running'is a normal response, not an error. removeis a hard delete of the agent row; in-flight episodes are unaffected (they hold ids in thread data).- The dispatch
case 'run'ignores the HTTP method — aGET ?action=runreachesrunand fails on missingthread_id(body is null on GET).