Docs
Contents

Agent Runtime API

Before running the examples, replace <APPBASE_ENDPOINT_WITH_V1> with the intended environment API endpoint and verify that the project and credentials belong to that environment.

REST API reference documentation for the Project Agent Runtime. Business backends connect via a project-level API Key to the managed agent runtime engine (/v1/agent-runtime/project/*) under the current project, centrally managing project runtime configuration, lexicon bindings, AI Gateway tool discovery, and Skill package uploads, and through userId isolating and managing sessions (Thread), asynchronous tasks (Run), resumable streaming events (SSE), and client tool callbacks (Client Tool) for different business end users.

Resources and Base Paths

Core Resource Models and Responsibility Boundaries

Resource objectCore identifier and pathOwnership scopeKey semantics and lifecycle notes
Project Runtime State /v1/agent-runtime/projectProject sharinginitialized: boolean Indicates whether the current project's agent workspace has completed initialization; repeating POST initialization is idempotent and will not clear existing configuration and history.
Project Configuration (Config)/v1/agent-runtime/project/configProject-sharedContains system_prompt, model_id, model_parameters, context window and output token budget, maximum reasoning steps and timeout duration, as well as memory_enabled, powercontext_enabled (mutually exclusive with Memory), knowledge_search_enabled, and knowledge_base_ids; returns a read-only config_hash. The effective configuration is frozen when a Run is accepted; modifying project configuration does not affect in-flight Runs.
Available Model List (ModelList)/v1/agent-runtime/project/modelsProject-sharedLists the chat (chat) and embedding (embedding) models currently configured in the project and available for selection by the Agent Runtime.
Project Lexicon Bindings (LexiconBindings)/v1/agent-runtime/project/lexiconsProject-sharedMounts the lexicons under the current project (up to 100, sorted by priority ascending) to the Agent Runtime, supporting synonym/expansion term rewriting queries as well as short-circuit interception (stopIntercept: true) and preset compliance replies (stopReply) when stop stopwords are hit.
AI Gateway Binding (Gateway)/v1/agent-runtime/project/gatewayProject-sharedBinds an AI Gateway (gateway_id) in the same project whose status is ACTIVE and which has an available published snapshot, enabling agents to automatically discover and call MCP / HTTP tools and Client Tools within the authorized scope at runtime (Shared V2 projects only).
Skill Package (Skill)/v1/agent-runtime/project/skills/{skillId}Project-sharedUploads .zip / .tar.gz / .tgz archive packages (limit 10 MiB, root directory contains SKILL.md with YAML Front Matter) for agents to discover and read task instructions and operational guidelines on demand; uploading a skill package does not mean executing arbitrary scripts.
Session (Thread)/v1/agent-runtime/project/threads/{threadId}User-isolated (userId)Carries the multi-turn continuous conversation history of the same business user, with a status of ACTIVE or ARCHIVED. At most one unfinished Run may exist in the same Thread at any given time.
Run/v1/agent-runtime/project/runs/{runId}User-isolated (userId)A ReAct reasoning and tool-calling loop triggered by one user message; POST /runs accepts asynchronously and returns 202 Accepted (replaying the same request carrying Idempotency-Key returns 200 OK and idempotent_replay: true).
Message.../threads/{threadId}/messages, .../runs/{runId}/messagesUser-isolated (userId)Persisted session or single-run message records, sorted by the incrementing in-session sequence number message_seq, with types covering USER, ASSISTANT, TOOL_CALL, TOOL_RESULT.
Streaming Event (SSE Event)/v1/agent-runtime/project/runs/{runId}/eventsUser-isolated (userId)A bounded incremental event stream based on the AG-UI protocol (text/event-stream), supporting resumption via Last-Event-ID after disconnection; an SSE disconnect does not cancel the background Run.
Model Invocation Record (ModelInvocation)/v1/agent-runtime/project/runs/{runId}/model-invocationsUser-isolated (userId)Records the input/output/cache/reasoning token usage, duration, and status of each model reasoning step (AGENT_RESPONSE, CONTEXT_COMPACTION, MEMORY) within a single Run.
Context Compaction Record (ContextCompaction)/v1/agent-runtime/project/threads/{threadId}/context-compactionsUser-isolated (userId)When the session history approaches the context budget, the Runtime automatically summarizes earlier history and retains recent messages; this endpoint returns an audit timeline of context compaction events.

ReAct Execution Loop and Streaming Recovery Architecture

  1. The business backend holds the Project API Key and calls POST /v1/agent-runtime/project/runs, passing userId, thread_id, user_message, and Idempotency-Key. The API validates project permissions and lexicon stopword rules, freezes the configuration snapshot, and returns 202 Accepted (run_id, status=QUEUED).

  2. The backend subscribes to SSE via GET /v1/agent-runtime/project/runs/{runId}/events?userId=.... The Runtime loads the Thread history, retrieves Memory / PowerContext, and computes the context token budget.

  3. Within the max_steps and max_duration_ms limits, the Runtime loops model calls, sending prompts, context, and authorized tool schemas; the model returns answer increments or tool call requests.

  4. Server-side tool calls first validate the parameter schema and trusted identity, then execute Knowledge retrieval or AI Gateway tools, and persist TOOL_RESULT. Client tool calls push TOOL_CALL_START / TOOL_CALL_ARGS / TOOL_CALL_END and the Run enters WAITING_CLIENT_TOOL; after the application returns userId, toolCallId, content / error to /runs/{runId}/tool-messages, the same Run is resumed via QUEUED back to RUNNING.

  5. During reasoning, the Runtime continuously pushes SSE frames such as TEXT_MESSAGE_CONTENT with incrementing event IDs. On completion, it persists the final ASSISTANT message and ModelInvocation usage, updates the Run to SUCCEEDED, and pushes RUN_FINISHED.

  6. The backend retrieves persisted messages and knowledge source references via GET /v1/agent-runtime/project/runs/{runId}/messages?userId=.... On SSE disconnection, Last-Event-ID can be carried to resume; the disconnect itself does not cancel the background Run.

Run Lifecycle State Machine

Initial stateSubsequent statesTrigger condition
InitialSUBMITTING → QUEUEDRun registered and enqueued
QUEUEDRUNNINGWorker begins execution
RUNNINGWAITING_CLIENT_TOOLWaiting for client tool result
WAITING_CLIENT_TOOLQUEUEDCalling /runs/{runId}/tool-messages to return the result
RUNNINGSUCCEEDED / FAILEDExecution succeeded or failed, entering a terminal state
RUNNINGCANCEL_REQUESTED → CANCELLEDCalling /runs/{runId}/cancel, waiting for the execution step to exit
QUEUED / WAITING_CLIENT_TOOLCANCELLEDCalling /runs/{runId}/cancel, entering the cancelled terminal state directly

SUCCEEDED, FAILED, and CANCELLED are all terminal states.

Run statusStatus categoryMeaningStandard client handling action
SUBMITTINGIn progressTask is being registered and its persistence record initializedContinue polling or wait until it enters QUEUED
QUEUEDIn progressTask is queued waiting for Worker execution (or re-queued after a client tool result is returned)Establish or maintain the SSE subscription; never create a duplicate new Run
RUNNINGIn progressWorker is executing model reasoning, context compaction, or server-side tool callsConsume the SSE event stream in real time; if termination is needed, explicitly call /cancel
WAITING_CLIENT_TOOLPaused/waitingThe model triggered a client tool call of source: "CLIENT" and is waiting for the application to return the execution resultValidate the tool name and parameters, perform the locally approved operation, then call POST /runs/{runId}/tool-messages to resume the same Run
CANCEL_REQUESTEDIn progressCancellation request accepted, waiting for the current execution step to exit safelyKeep observing the status until it converges to a terminal state CANCELLED
SUCCEEDEDFinal stateTask execution completed and final answer has been persistedStop listening to the event stream and call GET /runs/{runId}/messages to read the final persisted message
FAILEDFinal stateTask terminated due to model rate limiting, context overflow, upstream exceptions, or tool failureRead the Run object's error.code and error.message for troubleshooting or to notify the user
CANCELLEDFinal stateTask has been explicitly cancelled and its status has convergedKeep existing history; note that cancellation does not automatically roll back business side effects already produced by external tools

Authentication and Permissions

For common request header conventions, see General Conventions. Project-level agent workbench APIs use a two-tier security model of Project API Key authentication + userId multi-tenant user isolation:

Request Headers and API Key Scope Matrix

Header / RequirementExample ValueRequired Rules and Permission Boundary Description
X-Appwrite-Projectenterprise-ai-hub-210Required. Specifies the target project ID; it is not appended to the URL path.
X-Appwrite-Key<APPBASE_API_KEY>Required. A valid Server API Key belonging to the current project (supports standard Project API Keys and dynamic Project Keys; must be kept only in a controlled business backend and must never be delivered to browsers or mobile clients).
Required Permission Scopeagent-runtime.projectThe project configuration and Thread/Run endpoints listed here require agent-runtime.project. Other project paths may require different scopes: for example, GET /v1/agent-runtime/project/version-binding uses agent-runtime.read and depends on the Agent Management switch. Check each endpoint's requirements.
Idempotency-Keyreq_zhangwei_20261022_001POST /v1/agent-runtime/project/runs Recommended to include (1–128 byte ASCII string). Replaying with the same project, same userId, and same request body returns the original Run (HTTP 200 + idempotent_replay: true); the same key with a different request body returns 409 IDEMPOTENCY_KEY_CONFLICT.
Last-Event-ID21GET /v1/agent-runtime/project/runs/{runId}/events Optionally included when reconnecting after a disconnection; pass in the last received outer SSE frame id to resume unread events.

Internal service coordination authentication: When the agent workbench internally calls an enabled Memory, Knowledge Base, or AI Gateway within the same project at runtime, the platform automatically issues an internal trusted runtime context to complete authentication; there is no need to additionally check the Memory or Knowledge public API Scope for the caller's Project API Key.

userId Business User Isolation Contract (Core Specification)

The business backend can serve tens of thousands of business end users (such as user_zhangwei_001 and user_lina_002) using the same Project API Key, without needing to create platform Accounts for end users in Agentbase in advance:

  1. Format and case normalization:

    • The field name is strictly camelCase userId (not user_id).

    • The value must be 1–128 ASCII letters, digits, or underscores (regex: ^[A-Za-z0-9_]{1,128}$), and must be passed as a JSON string or Query string (purely numeric identities must be written as "123"; JSON numbers, arrays, objects, null, hyphens -, whitespace, or Chinese characters are rejected).

    • Case-insensitive; the server normalizes everything to lowercase: "User_ZhangWei_001" and "user_zhangwei_001" point to the same user isolation space.

    • Reserved word restriction: system (including any casing such as SYSTEM) is a platform-reserved identity and must not be supplied externally.

  2. Strict distinction of parameter location (no duplicate passing):

    • Project-level shared configuration endpoints (service initialization, configuration reads/writes, model listing, lexicon binding, AI Gateway binding, and Skill package management): do not pass userId; this parameter is neither required nor allowed.

    • User-level session and run endpoints (/threads, /runs, and all their sub-resources): every request must include userId, where POST requests must place it in the JSON request body (Body), and GET and DELETE requests must place it in the URL query parameters (Query); providing userId in both Query and Body simultaneously is strictly forbidden.

  3. Strong cross-user isolation semantics:

    • After a Thread is created, all subsequent operations on that Thread and its subordinate Runs (submitting a Run, querying status, subscribing to SSE, pulling messages, returning client tool results, cancelling a Run, archiving the Thread) must carry the same userId used at creation time.

    • If a user_lina_002 is supplied to access a threadId or runId belonging to user_zhangwei_001, the server uniformly rejects it with 404 NOT_FOUND (resource not visible), neither leaking the resource's existence nor altering its ownership.


Endpoint List

The following table lists the project configuration and user session/run endpoints covered here. Other project endpoints include GET / PUT /v1/agent-runtime/project/tool-discovery (uses agent-runtime.project) and GET /v1/agent-runtime/project/version-binding (uses agent-runtime.read; registered only when Agent Management is enabled). Availability and configuration depend on the target environment.

CategoryMethod + Full PathRequired ScopeuserId Requirement and LocationIdempotencySuccess Status CodePurpose Description
Service InitializationGET /v1/agent-runtime/projectagent-runtime.projectNot requiredIdempotent200Queries whether the Agent Runtime of the current project has been initialized (initialized)
Service InitializationPOST /v1/agent-runtime/projectagent-runtime.projectNot requiredIdempotent200Explicitly initializes the Agent Runtime of the current project (repeated calls do not clear configuration)
Project ConfigurationGET /v1/agent-runtime/project/configagent-runtime.projectNot requiredIdempotent200Reads the current project's agent configuration and read-only config_hash
Project ConfigurationPATCH /v1/agent-runtime/project/configagent-runtime.projectNot requiredConditionally idempotent200Sparsely updates the project agent configuration (model, prompt, budget, Memory/PowerContext/Knowledge switches)
Model CatalogGET /v1/agent-runtime/project/modelsagent-runtime.projectNot requiredIdempotent200Lists the models and capability tags available to the agent workbench in the current project (chat / embedding)
Lexicon BindingGET /v1/agent-runtime/project/lexiconsagent-runtime.projectNot requiredIdempotent200Reads the lexicon list bound to the current project's agent workbench and the stopword blocking policy
Lexicon BindingPUT /v1/agent-runtime/project/lexiconsagent-runtime.projectNot requiredIdempotent200Fully sets the bound lexicon priority list, enabled, stopIntercept, and stopReply of the agent workbench
AI GatewayGET /v1/agent-runtime/project/gatewayagent-runtime.projectNot requiredIdempotent200Reads the AI Gateway bound to the current project's agent workbench (gateway_id)
AI GatewayPUT /v1/agent-runtime/project/gatewayagent-runtime.projectNot requiredIdempotent200Binds to or switches to an AI Gateway in the same project that is in ACTIVE state and has an available snapshot
Skill ManagementGET /v1/agent-runtime/project/skillsagent-runtime.projectNot requiredIdempotent200Lists the Skill packages uploaded in the current project and the capacity quota (skill_count / skill_limit)
Skill ManagementPOST /v1/agent-runtime/project/skillsagent-runtime.projectNot requiredNon-idempotent201Uploads a new Skill archive package via multipart/form-data (.zip / .tar.gz / .tgz)
Skill ManagementGET /v1/agent-runtime/project/skills/{skillId}agent-runtime.projectNot requiredIdempotent200Reads the metadata, front_matter, and content_hash of a specified Skill package
Skill ManagementPUT /v1/agent-runtime/project/skills/{skillId}agent-runtime.projectNot requiredIdempotent200Uploads a new archive package to fully replace the content of the specified skillId
Skill ManagementDELETE /v1/agent-runtime/project/skills/{skillId}agent-runtime.projectNot requiredIdempotent204Deletes the specified skillId Skill package
Session ManagementPOST /v1/agent-runtime/project/threadsagent-runtime.projectRequired (JSON Body)Non-idempotent201Creates a new continuous conversation Thread for the specified userId
Session ManagementGET /v1/agent-runtime/project/threadsagent-runtime.projectRequired (URL Query)Idempotent200Lists the session list for the specified userId in descending order by update time (supports limit)
Session ManagementGET /v1/agent-runtime/project/threads/{threadId}agent-runtime.projectRequired (URL Query)Idempotent200Queries the status and title of a single Thread under the specified userId
Session ManagementDELETE /v1/agent-runtime/project/threads/{threadId}agent-runtime.projectRequired (URL Query)Idempotent204Archives the Thread for the specified userId (status set to ARCHIVED; long-term memory is not deleted)
Session HistoryGET /v1/agent-runtime/project/threads/{threadId}/messagesagent-runtime.projectRequired (URL Query)Idempotent200Reads persisted session messages with pagination by after (message_seq) and limit cursor
Session HistoryGET /v1/agent-runtime/project/threads/{threadId}/context-compactionsagent-runtime.projectRequired (URL Query)Idempotent200Reads the session's automatic context compaction event records
Run ManagementPOST /v1/agent-runtime/project/runsagent-runtime.projectRequired (JSON Body)Idempotent (requires Idempotency-Key)202 (replay 200)Submits a user message within the specified Thread and asynchronously starts a ReAct Run
Run ManagementGET /v1/agent-runtime/project/runs/{runId}agent-runtime.projectRequired (URL Query)Idempotent200Queries the current run status and error details of the specified runId
Run ManagementPOST /v1/agent-runtime/project/runs/{runId}/cancelagent-runtime.projectRequired (JSON Body)Idempotent202 or 200Explicitly request cancellation of a Run that is queued, running, or waiting for client tools
Streaming EventsGET /v1/agent-runtime/project/runs/{runId}/eventsagent-runtime.projectRequired (URL Query)Idempotent200Subscribes to the AG-UI protocol SSE incremental event stream, with Last-Event-ID reconnection after disconnection
Run MessagesGET /v1/agent-runtime/project/runs/{runId}/messagesagent-runtime.projectRequired (URL Query)Idempotent200Reads the persisted messages produced by a single Run by after (message_seq) and limit
Client ToolsPOST /v1/agent-runtime/project/runs/{runId}/tool-messagesagent-runtime.projectRequired (JSON Body)Idempotent (reuse id)202Returns the client tool result to a Run in WAITING_CLIENT_TOOL so execution can continue
Model UsageGET /v1/agent-runtime/project/runs/{runId}/model-invocationsagent-runtime.projectRequired (URL Query)Idempotent200Reads the model call details, Token consumption, and latency records for each inference step of a single Run

Requests and Responses

The following sections present, endpoint by endpoint in business integration order, the complete input parameter tables, output Schemas, executable curl examples, and real HTTP response examples.

1. Service Status and Initialization

1.1 Query service initialization status: GET /v1/agent-runtime/project

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

{
  "initialized": true
}

1.2 Initialize the project agent workbench: POST /v1/agent-runtime/project

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --header 'Content-Type: application/json' \
  --data '{}'

)

Response example (200 OK):

{
  "initialized": true
}

2. Project Configuration and Available Model Catalog

2.1 List available project models: GET /v1/agent-runtime/project/models

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/models' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

{
  "models": [
    {
      "model_id": "qwen-plus",
      "capabilities": [
        "chat"
      ]
    },
    {
      "model_id": "qwen-turbo",
      "capabilities": [
        "chat"
      ]
    },
    {
      "model_id": "text-embedding-v3",
      "capabilities": [
        "embedding"
      ]
    }
  ]
}

2.2 Read the project agent configuration: GET /v1/agent-runtime/project/config

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/config' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

{
  "system_prompt": "你是企业智能客服与知识中台助手,请优先检索企业知识库回答问题,保留引用来源。",
  "model_id": "qwen-plus",
  "model_parameters": {
    "temperature": 0.3,
    "top_p": 0.9
  },
  "context_window_tokens": 32768,
  "reserved_output_tokens": 2048,
  "max_steps": 12,
  "max_duration_ms": 120000,
  "memory_enabled": true,
  "powercontext_enabled": false,
  "knowledge_search_enabled": true,
  "knowledge_base_ids": [
    "kb_enterprise_support"
  ],
  "memory_embedding_model_id": "text-embedding-v3",
  "memory_embedding_dimensions": 1024,
  "config_hash": "8f9d2a7e4b1c6f03981e2d5c4a7b8e9f"
}

2.3 Sparsely update the project agent configuration: PATCH /v1/agent-runtime/project/config

Request body parameter table (ConfigPatch):

Field nameTypeRequiredConstraints and business semantics
system_promptstring | nullNoSystem prompt (0–200,000 characters); pass an empty string or null to use the platform default behavior.
model_idstringRequired on first saveA model ID within the project with chat capability (e.g. qwen-plus).
model_parametersobject | nullRequired on first saveOnly temperature (0–1) and top_p (0–1) are allowed; pass {} or null to clear explicit sampling parameters.
context_window_tokensintegerRequired on first saveTotal context window Token count (> 0, e.g. 32768, 65536).
reserved_output_tokensintegerRequired on first saveToken budget reserved for model output (> 0 and must be less than context_window_tokens).
max_stepsintegerRequired on first saveMaximum number of ReAct reasoning steps allowed per Run (> 0, e.g. 12).
max_duration_msintegerRequired on first saveMaximum execution duration allowed per Run (milliseconds, > 0, e.g. 120000).
memory_enabledbooleanNoWhether to enable project long-term memory (the Memory service must first be initialized and enabled in the project; strictly mutually exclusive with powercontext_enabled).
powercontext_enabledbooleanNoWhether to enable managed PowerContext (a Shared V2 project must first initialize PowerContext to the ready state; enabling this automatically disables memory_enabled, and setting both to true in the same request returns 400).
knowledge_search_enabledbooleanNoWhether to enable the enterprise knowledge base retrieval tool (knowledge_retrieve). When newly enabled, at least 1 knowledge_base_ids must be specified at the same time.
knowledge_base_idsstring[]Conditionally requiredArray of knowledge base IDs in this project that may be retrieved (at most 100 distinct valid IDs, e.g. ["kb_enterprise_support"]).
memory_embedding_model_idstring | nullNoEmbedding model ID used by Memory (e.g. text-embedding-v3).
memory_embedding_dimensionsinteger | nullNoEmbedding vector dimension used by Memory (> 0, e.g. 1024; must match the project Memory configuration).

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request PATCH \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/config' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --header 'Content-Type: application/json' \
  --data '{
    "system_prompt": "你是企业智能客服与知识中台助手,请优先检索企业知识库回答问题,保留引用来源。",
    "model_id": "qwen-plus",
    "model_parameters": {
      "temperature": 0.3,
      "top_p": 0.9
    },
    "context_window_tokens": 32768,
    "reserved_output_tokens": 2048,
    "max_steps": 12,
    "max_duration_ms": 120000,
    "memory_enabled": true,
    "powercontext_enabled": false,
    "knowledge_search_enabled": true,
    "knowledge_base_ids": [
      "kb_enterprise_support"
    ],
    "memory_embedding_model_id": "text-embedding-v3",
    "memory_embedding_dimensions": 1024
  }'

)

Response example (200 OK):

{
  "system_prompt": "你是企业智能客服与知识中台助手,请优先检索企业知识库回答问题,保留引用来源。",
  "model_id": "qwen-plus",
  "model_parameters": {
    "temperature": 0.3,
    "top_p": 0.9
  },
  "context_window_tokens": 32768,
  "reserved_output_tokens": 2048,
  "max_steps": 12,
  "max_duration_ms": 120000,
  "memory_enabled": true,
  "powercontext_enabled": false,
  "knowledge_search_enabled": true,
  "knowledge_base_ids": [
    "kb_enterprise_support"
  ],
  "memory_embedding_model_id": "text-embedding-v3",
  "memory_embedding_dimensions": 1024,
  "config_hash": "9c4e1b2d5a8f70316e9d4c2b1a0f8e7d"
}

3. Project Lexicon Binding and Stopword Blocking (Lexicons)

The agent workbench supports binding business lexicons under the current project (synonyms synonym, expansion terms expansion, stopwords stop), effective during conversational retrieval rewriting and input compliance interception.

3.1 Read the bound lexicon configuration: GET /v1/agent-runtime/project/lexicons

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/lexicons' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

{
  "enabled": true,
  "stopIntercept": true,
  "stopReply": "您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。",
  "bindings": [
    {
      "lexiconId": "lex_enterprise_synonyms",
      "priority": 1
    },
    {
      "lexiconId": "lex_support_stopwords",
      "priority": 2
    }
  ]
}

3.2 Update the bound lexicon configuration: PUT /v1/agent-runtime/project/lexicons

Field nameTypeRequiredDefault valueConstraints and business semantics
bindingsarrayYes[]Ordered lexicon binding array (at most 100 items; duplicate lexiconId values are forbidden). Each item must be strictly {"lexiconId": string, "priority": integer}, where priority is an integer from 0–2147483647; lower values indicate higher priority.
enabledbooleanNofalseWhether to enable the bound lexicon rules.
stopInterceptbooleanNotrueWhether to immediately short-circuit and block the current Run when user input matches a stop (stopword) lexicon entry.
stopReplystringNo""The preset compliance message returned directly when a stopword short-circuit block is triggered (up to 4096 characters).

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request PUT \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/lexicons' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --header 'Content-Type: application/json' \
  --data '{
    "enabled": true,
    "stopIntercept": true,
    "stopReply": "您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。",
    "bindings": [
      {
        "lexiconId": "lex_enterprise_synonyms",
        "priority": 1
      },
      {
        "lexiconId": "lex_support_stopwords",
        "priority": 2
      }
    ]
  }'

)

Response example (200 OK):

{
  "enabled": true,
  "stopIntercept": true,
  "stopReply": "您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。",
  "bindings": [
    {
      "lexiconId": "lex_enterprise_synonyms",
      "priority": 1
    },
    {
      "lexiconId": "lex_support_stopwords",
      "priority": 2
    }
  ]
}

4. AI Gateway Binding

AI Gateway binding requires the current project to use the Shared V2 storage mode and the target Gateway to be in the ACTIVE state with an available snapshot already published in the current region.

4.1 Read the bound AI Gateway: GET /v1/agent-runtime/project/gateway

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/gateway' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

{
  "gateway_id": "gw_7194685489feb1e169548619",
  "created_at": "2026-10-22T08:00:00Z"
}

4.2 Bind or switch AI Gateway: PUT /v1/agent-runtime/project/gateway

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request PUT \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/gateway' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --header 'Content-Type: application/json' \
  --data '{
    "gateway_id": "gw_7194685489feb1e169548619"
  }'

)

Response example (200 OK):

{
  "gateway_id": "gw_7194685489feb1e169548619",
  "created_at": "2026-10-22T08:00:00Z"
}

5. Skill Package Management

Skill archive packages support the .zip, .tar.gz, or .tgz formats, with a maximum size of 10 MiB per package. The root directory must contain a SKILL.md with YAML Front Matter (name: 1–64 lowercase letters/digits/single hyphens; description: 1–1024 characters).

5.1 Upload a Skill package: POST /v1/agent-runtime/project/skills

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/skills' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --form 'file=@./enterprise-order-sop.zip'

)

Response example (201 Created):

{
  "skill_id": "skill_order_sop_01",
  "name": "enterprise-order-sop",
  "description": "企业订单查询、异常催单与退换货标准处理流程规范。",
  "front_matter": {
    "name": "enterprise-order-sop",
    "description": "企业订单查询、异常催单与退换货标准处理流程规范。"
  },
  "content_hash": "sha256:4a8b9c1d2e3f5a6b7c8d9e0f1a2b3c4d",
  "created_by": "api_key_enterprise",
  "created_at": "2026-10-22T08:05:00Z",
  "updated_at": "2026-10-22T08:05:00Z"
}

5.2 List project Skill packages: GET /v1/agent-runtime/project/skills

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/skills' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

{
  "items": [
    {
      "skill_id": "skill_order_sop_01",
      "name": "enterprise-order-sop",
      "description": "企业订单查询、异常催单与退换货标准处理流程规范。",
      "front_matter": {
        "name": "enterprise-order-sop",
        "description": "企业订单查询、异常催单与退换货标准处理流程规范。"
      },
      "content_hash": "sha256:4a8b9c1d2e3f5a6b7c8d9e0f1a2b3c4d",
      "created_by": "api_key_enterprise",
      "created_at": "2026-10-22T08:05:00Z",
      "updated_at": "2026-10-22T08:05:00Z"
    }
  ],
  "skill_catalog_hash": "cat_9f8e7d6c5b4a3210",
  "skill_count": 1,
  "skill_limit": 10
}

5.3 Read a single Skill's metadata: GET /v1/agent-runtime/project/skills/{skillId}

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/skills/skill_order_sop_01' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK): returns the same Skill JSON object as the upload response (without the binary archive stream).

5.4 Replace a Skill package: PUT /v1/agent-runtime/project/skills/{skillId}

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request PUT \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/skills/skill_order_sop_01' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --form 'file=@./enterprise-order-sop-v2.zip'

)

Response example (200 OK): returns the updated Skill JSON object (with content_hash and updated_at refreshed).

5.5 Delete a Skill package: DELETE /v1/agent-runtime/project/skills/{skillId}

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request DELETE \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/skills/skill_order_sop_01' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example: HTTP/1.1 204 No Content (no response body).


6. Thread Management and History Reading

6.1 Create a thread: POST /v1/agent-runtime/project/threads

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --header 'Content-Type: application/json' \
  --data '{
    "userId": "user_zhangwei_001"
  }'

)

Response example (201 Created):

{
  "thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
  "title": null,
  "status": "ACTIVE"
}

6.2 List user threads: GET /v1/agent-runtime/project/threads

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads?userId=user_zhangwei_001&limit=50' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

[
  {
    "thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
    "title": "专票开具与订单发货咨询",
    "status": "ACTIVE"
  }
]

6.3 Query a single thread: GET /v1/agent-runtime/project/threads/{threadId}

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads/th_01ja9x8k2m4n6p8q0r2s4t6v8w?userId=user_zhangwei_001' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

{
  "thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
  "title": "专票开具与订单发货咨询",
  "status": "ACTIVE"
}

6.4 Archive a thread: DELETE /v1/agent-runtime/project/threads/{threadId}

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request DELETE \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads/th_01ja9x8k2m4n6p8q0r2s4t6v8w?userId=user_zhangwei_001' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example: HTTP/1.1 204 No Content.

6.5 Read thread persisted messages: GET /v1/agent-runtime/project/threads/{threadId}/messages

Message object (Message) field descriptions:

Field nameTypeDescription
message_idstringUnique message identifier
thread_idstringID of the thread the message belongs to
run_idstringID of the Run that produced the message
trace_idstring (optional)Associated Observability Trace ID
message_seqintegerStrictly increasing message sequence number within a session (used for after cursor pagination and client-side deduplication)
message_typestringEnum: USER, ASSISTANT, TOOL_CALL, TOOL_RESULT
payloadstring | objectUSER and ASSISTANT messages are plain string text; TOOL_CALL and TOOL_RESULT are structured JSON objects
tool_call_idstring | nullTool call association ID (null for ordinary text messages)
created_atstringRFC 3339 UTC creation time

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads/th_01ja9x8k2m4n6p8q0r2s4t6v8w/messages?userId=user_zhangwei_001&after=0&limit=100' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

[
  {
    "message_id": "msg_01ja9x9a1b2c3d4e5f6g7h8j9k",
    "thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
    "run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
    "message_seq": 1,
    "message_type": "USER",
    "payload": "请帮我查询订单 ORD-20261022-889 的发货状态,并说明跨月退货如何处理增值税专用发票。",
    "tool_call_id": null,
    "created_at": "2026-10-22T08:10:00Z"
  },
  {
    "message_id": "msg_01ja9x9f9e8d7c6b5a4f3e2d1c",
    "thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
    "run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
    "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
    "message_seq": 4,
    "message_type": "ASSISTANT",
    "payload": "订单 ORD-20261022-889 已通过顺丰发出。若跨月发生退货且增值税专用发票已认证抵扣,需由购买方在税务系统填开《开具红字增值税专用发票信息表》,审核通过后方可开具红字发票。",
    "tool_call_id": null,
    "created_at": "2026-10-22T08:10:04Z"
  }
]

6.6 Read session context compaction records: GET /v1/agent-runtime/project/threads/{threadId}/context-compactions

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads/th_01ja9x8k2m4n6p8q0r2s4t6v8w/context-compactions?userId=user_zhangwei_001' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

{
  "items": [
    {
      "run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
      "event_seq": 12,
      "type": "CONTEXT_COMPACTION_COMPLETED",
      "payload": [],
      "created_at": "2026-10-22T08:10:02Z"
    }
  ]
}

7 Run submission, streaming subscription, client tool result return, and model call records

7.1 Create and asynchronously submit a Run: POST /v1/agent-runtime/project/runs

Field nameTypeRequiredConstraints and description
userIdstringYesMust exactly match (case-insensitive) the business user ID that the target thread_id belongs to.
thread_idstringYesTarget session ID. An unfinished active Run must not exist under the same Thread, otherwise 409 THREAD_BUSY is returned.
user_messagestringYesNon-empty text message of the user's input for this turn.

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --header 'Idempotency-Key: req_zhangwei_20261022_001' \
  --header 'Content-Type: application/json' \
  --header 'Accept: application/json' \
  --data '{
    "userId": "user_zhangwei_001",
    "thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
    "user_message": "请帮我查询订单 ORD-20261022-889 的发货状态,并说明跨月退货如何处理增值税专用发票。"
  }'

)

First acceptance response example (202 Accepted):

{
  "run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
  "status": "QUEUED",
  "created_at": "2026-10-22T08:10:00Z"
}

Replay response example with the same Idempotency-Key and identical request body (200 OK):

{
  "run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
  "status": "RUNNING",
  "created_at": "2026-10-22T08:10:00Z",
  "idempotent_replay": true
}

7.2 Query Run status: GET /v1/agent-runtime/project/runs/{runId}

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9?userId=user_zhangwei_001' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

{
  "run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
  "status": "SUCCEEDED",
  "created_at": "2026-10-22T08:10:00Z"
}

7.3 Subscribe to the resumable SSE event stream: GET /v1/agent-runtime/project/runs/{runId}/events

Complete table of SSE event types (AG-UI protocol):

Event typedata Core JSON fieldsClient-side handling semantics
RUN_STARTEDrunId, threadIdMarks the start of the current Run's execution
TEXT_MESSAGE_STARTmessageId, role: "assistant"Initializes an assistant answer message container
TEXT_MESSAGE_CONTENTmessageId, delta: stringAppends streamed answer text fragments according to messageId
TEXT_MESSAGE_ENDmessageIdCurrent paragraph text output is complete (does not mean the entire Run has ended)
REASONING_START / REASONING_END / REASONING_MESSAGE_ENDmessageIdMaintains display state boundaries for the model's thinking/reasoning process
REASONING_MESSAGE_START / REASONING_MESSAGE_CONTENTmessageId, role: "reasoning", delta: stringDisplays streamed model thinking fragments
TOOL_CALL_STARTtoolCallId, toolCallName, toolCallSourceRecords the start of a tool call (toolCallSource is either "CLIENT" or a server-side tool source)
TOOL_CALL_ARGStoolCallId, toolCallSource, delta: stringConcatenates tool call argument JSON fragments according to toolCallId (non-client tools may be masked as {"redacted":true})
TOOL_CALL_ENDtoolCallId, toolCallSourceTool argument transmission is complete; if toolCallSource === "CLIENT", query the Run status, and after it enters WAITING_CLIENT_TOOL, execute the local tool and return
TOOL_CALL_RESULTtoolCallId, messageId, role: "tool", contentTool result has been recorded (default notification summary is {"status":"completed"}; the full structured result is read via the message API)
RUN_FINISHEDrunId, threadIdRun completed normally; subsequently read the Run final state and persisted messages
RUN_ERRORrunId, threadId, message, code (optional)Run execution errored or was canceled (e.g., code: "RUN_CANCELLED"); read the Run status to confirm the final state
CUSTOMname, value: objectPlatform extension events: appbase.context.compaction (context compaction), appbase.run.cancelled (cancellation notice), appbase.stream.attempt_aborted (Worker failover discarding a temporary output attempt; the client should calibrate the UI based on persisted messages)

First connection and reconnect/resume call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
# Subscribe to the event stream for the first time
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET -N \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/events?userId=user_zhangwei_001' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --header 'Accept: text/event-stream'

# After disconnection, resume the same Run by carrying Last-Event-ID
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET -N \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/events?userId=user_zhangwei_001' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --header 'Accept: text/event-stream' \
  --header 'Last-Event-ID: 20'

)

SSE response stream example (200 OK):

id: 21
event: TEXT_MESSAGE_CONTENT
data: {"type":"TEXT_MESSAGE_CONTENT","timestamp":1792656603000,"messageId":"msg_01ja9x9f9e8d7c6b5a4f3e2d1c","delta":"订单 ORD-20261022-889 已通过顺丰发出。"}

id: 22
event: RUN_FINISHED
data: {"type":"RUN_FINISHED","timestamp":1792656604000,"runId":"run_01ja9x90a1b2c3d4e5f6g7h8j9","threadId":"th_01ja9x8k2m4n6p8q0r2s4t6v8w"}

7.4 Return client tool results: POST /v1/agent-runtime/project/runs/{runId}/tool-messages

When a Run is paused in the WAITING_CLIENT_TOOL state because a CLIENT tool was triggered, the business side executes the local approved logic and calls this API to return the result, continuing the same Run.

Field nameTypeRequiredConstraints and description
userIdstringYesMust be consistent with the business user ID that the current Run belongs to.
idstringYesClient-generated unique identifier of the tool message (kept unchanged when retrying the same return).
rolestringYesFixed to "tool".
toolCallIdstringYesCorresponds to the toolCallId in the TOOL_CALL_START / TOOL_CALL_END events.
contentstringYesJSON-serialized string (note: must be a string, e.g., "{\"order_id\":\"ORD-20261022-889\",\"status\":\"shipped\"}"; you cannot pass a JSON object directly; when returning a failure you may pass "{}"). If the tool declared a outputSchema in the Gateway, the success result will be validated against that Schema.
errorstringNoWhen local tool execution fails, fill in an explanation of the error so the model becomes aware of the failure and continues making decisions.

Call example (successful return):

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/tool-messages' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --header 'Content-Type: application/json' \
  --data '{
    "userId": "user_zhangwei_001",
    "id": "tmsg_01ja9x9c4d5e6f7g8h9j0k1l2m",
    "role": "tool",
    "toolCallId": "call_order_lookup_001",
    "content": "{\"order_id\":\"ORD-20261022-889\",\"status\":\"shipped\",\"carrier\":\"SF-Express\"}"
  }'

)

Response example (202 Accepted):

{
  "run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
  "status": "QUEUED",
  "created_at": "2026-10-22T08:10:00Z"
}

7.5 Cancel a Run: POST /v1/agent-runtime/project/runs/{runId}/cancel

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/cancel' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @- \
  --header 'Content-Type: application/json' \
  --data '{
    "userId": "user_zhangwei_001"
  }'

)

Response example (202 Accepted):

{
  "run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
  "status": "CANCEL_REQUESTED",
  "created_at": "2026-10-22T08:10:00Z"
}

7.6 Read persisted messages of a single Run: GET /v1/agent-runtime/project/runs/{runId}/messages

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/messages?userId=user_zhangwei_001&after=0&limit=100' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK): Returns a Message[] array with the same structure as GET /threads/{threadId}/messages, containing only messages produced by this runId (including knowledge base retrieval fragments in TOOL_CALL and TOOL_RESULT, and the final ASSISTANT answer).

7.7 Read model call records of a single Run: GET /v1/agent-runtime/project/runs/{runId}/model-invocations

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
  '<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/model-invocations?userId=user_zhangwei_001' \
  --header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
  --header @-

)

Response example (200 OK):

{
  "items": [
    {
      "invocation_id": "inv_01ja9x92b3c4d5e6f7g8h9j0k1",
      "model_step": 1,
      "purpose": "AGENT_RESPONSE",
      "attempt": 1,
      "model_id": "qwen-plus",
      "input_tokens": 1420,
      "output_tokens": 215,
      "cached_tokens": 0,
      "reasoning_tokens": null,
      "provider_usage_available": true,
      "provider_request_id": "chatcmpl-9f8e7d6c-dashscope",
      "duration_ms": 1580,
      "status": "SUCCEEDED",
      "started_at": "2026-10-22T08:10:01Z",
      "finished_at": "2026-10-22T08:10:02.580Z"
    }
  ]
}

Errors and boundaries

Error response structure

Project-level agent workbench APIs may return two types of error structures, and clients should be compatible with both:

  1. Runtime domain errors (RuntimeError):

{
  "error": {
    "code": "THREAD_BUSY",
    "message": "thread has an open run"
  },
  "request_id": "req_01ja9x9z8y7x6w5v4u3t2s1r0q"
}
  1. Platform gateway-layer errors (PlatformError) (triggered during API Key authentication, Scope validation, and parameter format validation):

{
  "message": "Invalid `userId` param: Value must be a valid string of 1 to 128 alphanumeric or underscore characters.",
  "code": 400,
  "type": "general_argument_invalid",
  "version": "2.10.0"
}
  1. SSE cursor expiration error (HTTP 409): May be returned when the cache still contains entries and Last-Event-ID is too far behind. Default retention is 30 minutes, measured from the Run deadline for ordinary events and from publication time for terminal events; the entry limit may evict older events sooner. If the entire cache is absent, terminal Runs or Runs waiting for a client tool may return fallback events instead of 409; check the Run state and persisted messages:

{
  "code": "stream_cursor_expired",
  "earliest_event_id": 300,
  "latest_event_id": 650
}

Troubleshooting table of common status codes and business error codes

HTTP status / occurrence locationError code (error.code / type / code)Trigger reasonStandard client recovery and troubleshooting strategy
400 Bad Requestgeneral_argument_invalid / INVALID_REQUESTMissing or invalid userId (e.g., containing a hyphen -, passing system, putting it in the wrong Query/Body location, or passing it twice); or both memory_enabled and powercontext_enabled set to true; or enabling knowledge retrieval without selecting a knowledge_base_ids.Verify the userId regex (^[A-Za-z0-9_]{1,128}$) and the parameter location (POST in Body, GET/DELETE in Query); verify configuration mutual-exclusion and the non-empty knowledge base constraint.
401 / 403user_unauthorized / general_access_forbiddenX-Appwrite-Project does not match the API Key, or the API Key lacks the agent-runtime.project Scope.In the Console, check the agent-runtime.project permission Scope for the current project's API Key.
404 Not FoundNOT_FOUND / lexicon_not_foundthreadId, runId, or skillId does not exist, or the passed userId does not match the user who created the Thread/Run, or the AI Gateway has not been bound yet.Verify that the resource ID and its owning userId are consistent; cross-user access is always rejected as not found.
409 ConflictSTATE_CONFLICTA business API was called before the project Agent Runtime was initialized, or a config_hash optimistic-locking conflict occurred during concurrent multi-user updates to /config.Call POST /v1/agent-runtime/project first to initialize; on configuration conflict, re-GET /config and merge changes before retrying.
409 ConflictTHREAD_BUSYThe target thread_id already has an active Run in the SUBMITTING, QUEUED, RUNNING, WAITING_CLIENT_TOOL, or CANCEL_REQUESTED state.Continue subscribing to or polling the existing active Run; if waiting for a client tool, return tool-messages; if the old task truly needs to be abandoned, call /cancel first and wait for the final state.
409 ConflictIDEMPOTENCY_KEY_CONFLICTThe same Idempotency-Key was used to submit a different thread_id, userId, or user_message.Retrying the same submission must keep the request body completely identical; a new Idempotency-Key must be generated when asking a new question.
409 Conflictstream_cursor_expiredThe Last-Event-ID carried on reconnection has slid out of the bounded event stream cache window.First call GET /runs/{runId} and GET /runs/{runId}/messages to recover persisted state and messages; if the Run is still running, resubscribe from earliest_event_id - 1 — never create a duplicate Run.
Run FAILEDMODEL_RATE_LIMITEDThe upstream model provider (e.g., DashScope) triggered TPM / RPM rate limiting.Check the model provider's quota and concurrency, apply exponential backoff, and start a new Run as needed.
Run FAILEDMODEL_UPSTREAM_FAILEDUpstream model call timed out, credentials expired, or an abnormal response was returned.Check the provider_request_id and error details in GET /runs/{runId}/model-invocations, and troubleshoot LLM Provider connectivity.
Run FAILEDCONTEXT_BUDGET_EXCEEDED / CONTEXT_PREPARE_FAILED / CONTEXT_FRESH_TAIL_TOO_LARGEA single user input, tool definition, or recent uncompressed messages exceeded the input budget of context_window_tokens - reserved_output_tokens.Increase context_window_tokens, reduce reserved_output_tokens appropriately, or streamline single-turn input and the number of mounted tools.
Run FAILEDRUN_DEADLINE_EXCEEDEDThe total execution time of a single Run exceeded the configured max_duration_ms.Investigate slow tool call durations, or appropriately raise max_duration_ms in PATCH /config.
Run FAILEDTOOL_RESULT_UNKNOWNAn external tool call was interrupted by a network outage or process restart during execution, so it cannot be confirmed whether the external write operation took effect.Never blindly and automatically redo side-effecting tool calls; first query the real state of the external business system, confirm it, and then decide on subsequent actions.
503 Service UnavailableRUN_ADMISSION_DISABLEDThe instance is under maintenance or paused from accepting new Runs.Keep the original Idempotency-Key and retry with delayed backoff.

Correspondence with the Server SDK

Project workbench endpoints are under /v1/agent-runtime/project/*. From your backend, send HTTP or SSE requests to the configured Agentbase endpoint using X-Appwrite-Project and a suitably scoped X-Appwrite-Key. Disable automatic redirects. See the SDK integration guide for supported installation options and the Agent Runtime SDK reference for request guidance.

Business actionHTTP method and pathRequest authentication header and userId locationBackend HTTP request
Query / initialize workbenchGET | POST /v1/agent-runtime/projectX-Appwrite-Project + X-Appwrite-Key (no userId)Send the project headers with GET or POST {} (see the Agent Runtime SDK reference)
Read / update workbench configurationGET | PATCH /v1/agent-runtime/project/configX-Appwrite-Project + X-Appwrite-Key (no userId)GET Reads configuration and config_hash; PATCH sends a sparse JSON configuration object
List available modelsGET /v1/agent-runtime/project/modelsX-Appwrite-Project + X-Appwrite-Key (no userId)GET Reads models[] (including model_id and capabilities)
Read / bind project lexiconGET | PUT /v1/agent-runtime/project/lexiconsX-Appwrite-Project + X-Appwrite-Key (no userId)GET / PUT JSON { bindings, enabled, stopIntercept, stopReply }
Read / bind AI GatewayGET | PUT /v1/agent-runtime/project/gatewayX-Appwrite-Project + X-Appwrite-Key (no userId)GET / PUT JSON { gateway_id }
Skill package managementGET | POST /v1/agent-runtime/project/skills, GET | PUT | DELETE .../skills/{skillId}X-Appwrite-Project + X-Appwrite-Key (no userId)Upload and replacement use multipart/form-data (field file)
Create / query / archive ThreadPOST | GET /v1/agent-runtime/project/threads, GET | DELETE .../threads/{threadId}POST Pass userId in the JSON Body; GET/DELETE pass userId in the QueryMap a stable lowercase userId per business end user and call
Read session messages and context compactionGET .../threads/{threadId}/messages, GET .../threads/{threadId}/context-compactionsPass userId in the Query (pass after and limit additionally for message pagination)Use the message_seq at the end of the previous page as the after of the next page
Create / query / cancel RunPOST /v1/agent-runtime/project/runs, GET .../runs/{runId}, POST .../runs/{runId}/cancelPOST passes userId in the Body (creation includes the Idempotency-Key header); GET passes userId in the QueryCreation acceptance returns 202 and run_id, decoupled from the SSE subscription
Subscribe to the resumable SSE event streamGET /v1/agent-runtime/project/runs/{runId}/eventsPass userId in the Query; Header carries Accept: text/event-stream and optional Last-Event-IDUse a streaming HTTP client to parse AG-UI events frame by frame and record the latest id
Returns the client tool resultPOST /v1/agent-runtime/project/runs/{runId}/tool-messagesPass in the Body { userId, id, role: "tool", toolCallId, content, error? }Return to the same runId in the WAITING_CLIENT_TOOL state
Read Run messages and model callsGET .../runs/{runId}/messages, GET .../runs/{runId}/model-invocationsPass userId in the QueryAfter the final state, read the final persisted answer, knowledge retrieval citations, and per-step Token consumption

2.12.0 endpoints and compatibility

Paths below are relative to /v1. Server requests carry X-Appwrite-Project and X-Appwrite-Key; keep the key on the server. Scopes below are necessary; dataset access, ownership and resource state may add checks. HTTP 202 means accepted; use the returned operation identifier to read its terminal result.

HTTPScopeSDK
GET /powercontext/subjects/{subjectId}users.readpowercontext.resolveSubject

GET /powercontext/subjects/{subjectId}

Resolve a PowerContext authorization subject

ParameterLocationRequiredTypeConstraints / defaultMeaning
subjectIdpathyesstring—Application user ID or backend-owned UID.
kindquerynostringenum=account, external; default="account"Identity source.

Success response: HTTP 200 — any.

Errors and retries

400/422: check types, enumerations and rules. 401/403: verify identity and scopes; dataset analyses additionally require trace and dataset read access. 404: check that the resource exists in the current project. 409: read current state before deciding to retry. 429: honor Retry-After. After 5xx or network loss, inspect operation state first. Preserve an idempotency key across retries; change it only for a deliberate new operation. Confirm deletion and clearing targets before writing.