Agents API
Create, validate, import, export, publish, and execute agents.
List agents
Returns the agents visible to the caller, filtered by `type` (default `CUSTOM`). With `applicationId` it returns the agents of that application, without it only company-scoped agents (agents that belong to no application) are returned. Disabled agents are excluded unless `includeDisabled=true`.
Create workflow agent from complete spec
Creates one actual Docana workflow Agent record from a complete AgentSpec V2: create, build, or draft one new agent. Do not use `saveArtifact` or `importAgents` for this. Validate the complete spec first with `validateAgentSpec`; creation never publishes, so call `publishAgent` separately when the draft is ready.
Chat with agent builder
Converse with Docana's interactive agent-building expert. Two ways to use it: ask design questions (node types, transitions, why browsing tools are disabled, platform gotchas) even when authoring the spec yourself, or delegate the whole build and let it draft, validate, and import the spec. The builder can create or reuse tables and columns within the current application and configure record-saving steps. Table setup is saved immediately while the workflow remains a draft. Streams an AI-SDK UI-message response. Body: `{ messages?, assistantContext: { applicationId, ... }, data? }`.
Diff two agent specs
Compares two agent specs and reports the semantic changes between them: workflow nodes added, removed or modified; reasonings (decision-node evaluation criteria, matched by name) added, removed or modified; nodes whose routing rules (transitions) changed; and changed top-level fields. Each side is an agent in this deployment (`agentId`) or an inline spec / export bundle (`spec`), so two different agents can be compared — for example a production agent against its development copy. Specs are normalized before comparison (ids and per-environment criteria references are neutralized), and the normalized specs are returned for stable textual diffs.
Ask AI agent builder and get full reply
Converse with Docana's agent-building expert without streaming: send one message, receive the complete reply. Use it to ask design questions (node types, transitions, platform gotchas) even when authoring a spec yourself, or to delegate the build — when the builder creates or edits a spec, the response carries the persisted artifact (id, version, spec) alongside the reply. On follow-up requests pass the returned `threadId` (to continue the conversation) and `artifact.id` as `artifactId` (so the builder edits that spec instead of creating a new one). Replies can take a minute or two for complex requests; clients that can consume a stream may prefer `runAgentBuilder`. The builder can create or reuse tables and columns in the current application and configure native record-saving steps with their saved IDs. Table setup takes effect immediately; drafting a workflow does not run or publish it.
Import agent bundle
Imports an exported agent bundle (root agent plus sub-agents, evals, and routines) into an application. Use `createAgent` instead to create one new draft agent. The body is NOT a bare AgentSpec: to import a spec you authored, wrap it as `{ 'exportVersion': 1, 'agent': { 'name': '<name>', 'spec': <AgentSpec> } }`. Accepts `application/json` or `multipart/form-data` with a `file` field. Any supplied query `applicationId` must be a valid positive integer. When both valid body and query IDs are supplied, the body value wins.
Check import bundle agents
Inspects an export bundle and reports whether the root agent and its sub-agents already exist in the target application. Accepts `application/json` or `multipart/form-data` with a `file` field. `applicationId` may be supplied in the body or query string; it is required only when neither location supplies it. When both are supplied, the body value wins — the same precedence as the import endpoint.
Get AgentSpec V2 schema
Returns the JSON Schema (draft 2020-12) of the agent spec, derived from the canonical zod definition. Served as `application/schema+json` with a public cache policy.
Validate agent spec
Validates an agent spec against the AgentSpec V2 JSON Schema (see `GET /api/v1/agents/schema/`) without persisting anything. After a clean validation, create one draft with `createAgent`. Accepts either `{ 'spec': <agent-spec> }` or the spec object at the top level.
Get AgentEvalSpec schema
Returns the JSON Schema (draft 2020-12) of the agent eval spec, derived from the canonical zod definition. Served as `application/schema+json` with a public cache policy.
Get agent
Returns one agent in the same item shape as the `GET /api/agents/` list.
Update agent metadata
Updates only the canonical agent name and description. This idempotent operation never creates a draft version or changes publication.
Delete custom agent
Removes a custom agent from availability and disables its automation while preserving its execution and conversation history. Repeating the request is idempotent and retries scheduler cleanup. The `applicationId` query parameter is optional: when omitted, it is derived from the agent itself.
Set agent enabled state
Sets the requested absolute enabled state. Repeating the current state is an idempotent no-op and never changes publication, routines, or history.
Replace complete agent draft spec
Replaces the full draft AgentSpec V2; it is not a patch and never publishes. The path agentId overwrites spec.id. In this REST endpoint Agent.name is canonical: update the agent name with updateAgent first, then submit the same normalized spec.name.
Export agent bundle
Exports the agent (and, recursively, its sub-agents) as a portable bundle with inline evaluation criteria, evals and routines. Served as a JSON file download (`Content-Disposition: attachment`).
Get when agent’s spec versions went live
Returns one entry per published spec version in the window, oldest first, ordered by when it went live — which is not version order, since a rollback republishes an older version. `stamped` is false when the instant is the version’s creation time rather than a recorded publish, which is the case for versions published before that stamp existed. `days` defaults to 30 and is capped at 90.
List agent's spec versions
Returns one page of up to 50 versions of the agent's spec history, newest first, with the current and published version numbers. Page older versions with `before`. The version numbers are what `diffAgents` accepts as `version` on an `agentId` side, so this is how callers discover what to diff. Legacy agents without artifact-backed specs report `currentVersion: null` and no versions.
Publish agent spec
Equivalent to the UI Publish action. Explicitly call after create or update to promote the latest linked draft. It resolves inline criteria and rejects invalid AgentSpec V2/template defects. applicationId is the recommended scope and must exactly match the agent. For backwards compatibility, callers that omit it use the active agent’s application and receive deprecation headers. Legacy artifactId must match the linked draft; version is only a stale-client hint. Publishing an employee also activates responsibilities pending publication; intentionally paused and imported routines stay paused. Check routineActivation for failures that require retrying activation even when publication succeeds.
Update thread metadata
Updates `specThreadId` and/or `sandboxThreadId` in the agent metadata. Fields set to `null` are cleared; omitted fields are left untouched.
Run agent in sandbox
Streams an AI-SDK UI-message response of a sandbox agent run, including node lifecycle events and trace data. Body: `{ messages?, assistantContext: { applicationId, ... }, data? }`.
Execute published agent
Validates the request, schedules a background run of the published agent version and returns immediately with both the `executionId` and `assistantMessageId` handles the run will use. Output content is populated asynchronously. Body: `{ prompt: string, threadId?: string, context?: object, waitSeconds?: number, deliverToChannel?: boolean }`. With `deliverToChannel: true` and a `threadId`, the run's output (and any follow-up it schedules) is also sent through the channel the thread came in on, to the sender of its latest inbound message; without it the reply is only stored. Poll `getAgentExecution` with the returned id for status, node outputs and the threadId. An agent whose published spec has `workflow.dispatch: 'queued'`, or any run above the application's concurrency limit, is handed to the workers instead: the acknowledgement carries `executionStatus: 'QUEUED'` and the execution row exists right away, waiting for a worker. For an in-process run the row appears once the background run starts, so a brief 404 right after scheduling means 'not started yet' while a persistent one means the run failed to start. Optional bounded wait: `waitSeconds` (1-120) holds the response until the run settles or the window elapses; the response then carries `waitOutcome` (`completed`, `failed` or `timeout`) and, when the run settled, `executionStatus`. A timeout never cancels the run — keep polling `getAgentExecution` with the same `executionId`. Supports the `Idempotency-Key` header: a retry with the same key and body replays the stored ack (same executionId) instead of running the agent a second time. `waitSeconds` is a delivery preference, not part of the request identity: it is excluded from the idempotency payload hash, and replays return the stored asynchronous ack immediately without waiting.
Backfill deterministic agent Insights
Backfill deterministic agent Insights
List workflow nodes Insight can measure
Returns the current main draft artifact id and version of the agent together with a safe summary of its workflow nodes (id, label, type, position, nesting path, adjacent labels). Use these values as `source.node` when saving a Conversation Insights data point with `source.kind` `nodeReached` (boolean) or `nodeExecutionCount` (number) through `updateAgentInsights`. No full spec is returned. A legacy agent without a spec draft answers null artifact fields and an empty list.
List sandbox threads
Without `threadGroupId` the agent sandbox group (`agent-sandbox:{agentId}`) is listed with type AGENT_SANDBOX. Passing `threadGroupId` lists that group instead, optionally narrowed by `type`. `q` filters threads by the display text of their first user message.
List messages of agent thread
Looks the thread up by id within the agent application, so any agent thread works — sandbox, builder, and live execution threads (type AGENT, as returned by getAgentExecution) alike. `threadGroupId` and `type` are optional narrowing filters; a mismatch returns 404.
Cancel scheduled follow-up
Deletes the follow-up scheduler job so it never fires and marks the source execution node as cancelled. Idempotent: cancelling a follow-up whose job is already gone still succeeds. The `applicationId` query parameter is optional: when omitted, it is derived from the follow-up itself. To trigger the follow-up instead, use `POST /api/v1/agents/{agentId}/follow-ups/{followUpId}/fire-now/`.
Fire scheduled follow-up now
Runs the follow-up scheduler job now instead of waiting for its scheduled time. The schedule itself is not modified, but the later scheduled tick is absorbed by the worker because the manual run has already produced an assistant message. The `applicationId` query parameter is optional: when omitted, it is derived from the follow-up itself. To stop the follow-up instead, use `POST /api/v1/agents/{agentId}/follow-ups/{followUpId}/cancel/`.
Get Conversation Insights table connection
Read the current connection, table and delivery links, last successful sync and pending history copy. Reading this endpoint never creates a table or runs extraction.
Prepare Conversation Insights table or include history
Enable Insights and configure fields first with updateAgentInsights. Creates one managed table per agent in its application and asynchronously updates one current row per conversation using existing observations. Repeated calls reuse the table. The table follows the master Insights setting; includeHistory copies compatible historical observations without another LLM call. Conversation access and table row policies apply. Configure schedules, recipients and reports separately through table delivery tools; this operation sends nothing.
Set agent Conversation Insights config
Stores the given Conversation Insights configuration on the agent, replacing any existing config in full and keeping its managed table in sync whenever Insights is enabled with configured fields. Pass `insights: null` to clear the config and pause its table. Read the current config with `getAgent`: it is returned under `metadata.insights`. Each data point has a `type` (string, number or boolean) and an optional `source`: omit it for AI extraction, or use `nodeReached` (boolean) or `nodeExecutionCount` (number) with a `node` from `listAgentInsightSourceNodes` to measure a workflow node deterministically. Boolean and number points can decide an experiment winner; string points cannot. Use getAgentInsightTable for table links and configureAgentInsightTable to pause or include existing history. Unrelated to `pollAgentInsights`, which reads document insights results.