This document is generated from the HTTP routes and behaviors currently implemented in the codebase. The default example server address is http://127.0.0.1:18080.
- Except for streaming endpoints, requests and responses use
application/json - Time fields use RFC3339 / ISO8601
- Most non-streaming errors are returned as plain-text response bodies
- Agent session response errors use an OpenAI-style JSON error envelope
- SSE endpoints use
text/event-stream - The current API is mainly grouped into 3 areas:
- Core API:
/api/v1/* - Channel and participant API:
/api/v1/channels/* - Health check:
/healthz
- Core API:
CSGClaw skill scripts can emit resource links and interactive questions through the runtime-neutral CSGClaw Structured Skill Output Protocol. That protocol ultimately submits question responses to the channel activity endpoint documented below.
Answers a pending structured question activity.
The body is the exact RequestUserInputResponse object:
{
"answers": {
"verification": {
"answers": ["Standard (Recommended)"]
},
"note": {
"answers": []
}
}
}An empty outer answers object skips the entire request.
An empty inner answers array skips one question.
The server derives the room and responder from the stored activity and rejects unknown fields.
- Most
/api/v1/*endpoints do not require authentication by default - The following endpoints require
Authorization: Bearer <token>, where the token is the server access token:GET /api/v1/channels/{channel}/participants/{id}/eventsPOST /api/v1/channels/csgclaw/participants/{id}/messagesGET /api/v1/agents/{id}/llm/modelsGET /api/v1/agents/{id}/llm/v1/modelsPOST /api/v1/agents/{id}/llm/chat/completionsPOST /api/v1/agents/{id}/llm/v1/chat/completionsPOST /api/v1/agents/{id}/llm/responsesPOST /api/v1/agents/{id}/llm/v1/responsesGET /api/v1/agents/{id}/llm/responsesGET /api/v1/agents/{id}/llm/v1/responses
- If the server runs with
no_auth, the checks above are skipped
Health check endpoint.
Example response:
ok
Returns the current server version.
Example response:
{
"version": "0.1.0"
}Returns the upgrade status.
Response fields:
current_versionlatest_versionupdate_availablecheckingupgradinglast_checked_atlast_error
Starts the upgrade helper.
On success, returns 202 Accepted:
{
"status": "accepted",
"message": "upgrade helper started"
}Returns 503 Service Unavailable if the upgrade manager is not configured.
On server startup, every 30 seconds, and when listing the skill library, CSGClaw scans known user skill directories and automatically registers their source paths in ~/.csgclaw/skills/.discovered-skills.json.
Registration is by reference, without copying, editing, or deleting external skills, and requires no symlink privilege on Windows.
GET /api/v1/skills includes source: "discovered" and a discovery object containing the selected tool, path, version, modification time, all same-name sources, a content key, and a new notification flag.
The library and Agent skill assignment resolve the same selected source.
An explicit assignment to an Agent installs its usual workspace snapshot, including supporting skill resources.
| Source | User skill directory | Reference |
|---|---|---|
| Agent / shared agents | ~/.agent/skills, ~/.agents/skills |
Agent Skills in Codex documents the shared .agents location; .agent is an additional user-requested location. |
| Claude Code | ~/.claude/skills |
Claude Code skills |
| Codex | ~/.codex/skills |
Existing standalone skills; shared skills also use ~/.agents/skills. |
| Pi | ~/.pi/agent/skills |
Pi skills |
| OpenCode | ~/.config/opencode/skills |
OpenCode skills |
| WorkBuddy / Cursor / CodeBuddy | ~/.workbuddy/skills, ~/.cursor/skills, ~/.codebuddy/skills |
Tencent installation directories |
Documented environment overrides (CLAUDE_CONFIG_DIR, CODEX_HOME, PI_CODING_AGENT_DIR, XDG_CONFIG_HOME) add their corresponding skill roots.
Discovery never scans arbitrary projects or reads application configuration, conversations, credentials, scripts, or references.
Only regular SKILL.md files up to 1 MiB are opened, with bounded traversal, cycle detection, and no recursive directory-link following.
Installed skill directory links at the first level are supported; links to arbitrary directories without their own skill definition are ignored.
Invalid or inaccessible external skills are skipped independently.
Explicit skill previews and Agent assignment may read supporting files inside the selected skill, but reject symlink escapes.
Same-name external candidates are deduplicated case-insensitively.
Valid semantic versions take precedence over unversioned candidates, then the higher semantic version wins.
Equal or unavailable versions use the definition modification time, with the source path as a stable final tie-breaker.
The same selection rule applies when a tracked external skill collides with a local library copy that declares comparable metadata.
A local copy with invalid or absent metadata remains an explicit local override.
Deleting a discovered library entry suppresses automatic registration across restarts and leaves its external files intact.
POST /api/v1/skills/discovery/rescan explicitly rescans known directories, restores removed links, and returns the full skill list.
Restored skills receive an unseen notification even if their current content was acknowledged before removal.
Ordinary listing and background scans continue to respect removals.
Installed summaries include directory, the absolute directory of the selected source or local installation; embedded-only skills have no physical directory.
The settings library uses a compact two-column card list, with source application filtering and manual rescanning on one toolbar row.
Every recorded application source remains filterable after skill deduplication, alongside builtin, market, and local skills.
New or updated skills carry a compact badge that is acknowledged when opening their details.
Installed skill details show a copyable absolute directory and explicitly identify the active declared version.
Source software aliases pointing to the same canonical directory are shown as one shared skill, while different directories can be compared with their versions, modification times, and an active-source marker.
The compact source badge reports the active version and software count; it does not imply additional software aliases are newer versions.
File previews follow the active source key to avoid reusing content cached from an older selected source.
POST /api/v1/skills/discovery/ack accepts {"keys":["<content key>"]} and returns 204 No Content.
It acknowledges only the specified current discoveries, so skills discovered concurrently retain their notification.
Acknowledgements persist across restarts; new or changed definitions receive new keys and new notifications.
The settings page refreshes discoveries every 30 seconds while open and also provides manual rescanning.
Read installed Skill files using the existing path parameter. For market previews, pass remote_path and optionally ref instead: the tree endpoint lists that remote repository, while the file endpoint also takes a repository-relative path, such as SKILL.md. These read-only requests use the same Hub environment and matching user credentials as remote installation, without installing or changing local Skills.
Lists remote Skills from the effective OpenCSG Hub. The browser only calls CSGClaw; the server resolves the Hub using the current login environment or an explicitly configured official Hub URL. When the user is signed in, CSGClaw forwards the current OpenCSG access token to the matching Hub so the catalog can include private Skills visible to that user. Signed-out requests remain anonymous and list only public Skills.
Optional query parameters:
page: positive page number, default1per: page size from1to100, default16search: remote catalog search text
The server keeps the current Hub catalog ordering and returns normalized Skill summaries:
{
"items": [
{
"name": "agent-builder",
"description": "Build agents",
"readonly": true,
"source": "official",
"remote_path": "AIWizards/agent-builder",
"remote_ref": "main",
"remote_url": "https://opencsg.com/skills/AIWizards/agent-builder"
}
],
"page": 1,
"per": 16,
"total": 78,
"next_page": 2
}remote_path is the stable remote Skill identity used for installation. remote_url is the browser detail URL: signed-out requests use https://opencsg.com, while signed-in requests use the current OpenCSG login site. The Hub API base URL is not used as a browser URL.
Published installations resolve the selected release to its commit and record the source URL, remote path, version, commit, installation time, update time, and content digest. The market catalog includes the latest published version when the Hub supplies it; missing catalog metadata is read from the skill detail API.
GET /api/v1/skills/updates checks market installations against their original Hub and returns per-skill update information plus checkedAt.
The Web UI checks every five minutes and offers a manual check in Settings > Skills.
An unavailable source or failed check remains an error, rather than being represented as an up-to-date installation.
External discoveries and custom local skills continue to be managed at their original source.
Missing SKILL.md versions do not disable update checks: installation metadata is authoritative, followed by a published commit or immutable ref.
For an installation without either version or resolvable commit, the original install digest is compared with the latest published package.
An exact match identifies the installed release; different contents offer a reviewed replacement while keeping the current version explicitly unknown.
Local edits alone do not trigger a remote update when the original install digest already matches the published package.
GET /api/v1/skills/{name}/update-check?preview=true prepares a confirmation containing each installed version, the target published version and commit, release notes, affected same-source Agent copies, and added/modified/deleted files.
File comparisons use actual local contents; binary and oversized files retain their change entry without a text preview.
The confirmation includes a state token covering the reviewed installation records, files, and affected targets.
Checking and previewing do not replace files.
POST /api/v1/skills:updates accepts {"items":[{"name":"example","version":"1.2.0","commit":"<published commit>","state":"<reviewed state>","strategy":"update"}]}.
The update strategy downloads the exact reviewed published commit and replaces the listed library and Agent copies without changing Agent enablement.
The keep-local strategy leaves files untouched and persists an ignored release identifier; a later release is still eligible for notification.
The dialog defaults to updating and lists every skill's current-to-target version transition before the user confirms.
Confirmation stays disabled while the preview is loading or has failed, and opening the dialog does not apply an update.
Changed files, changed origins, changed target membership, or a removed/rebound release invalidate the confirmation.
Results identify every successful or failed target, so a partially completed batch is never presented as wholly successful.
Downloads and archive validation complete before replacement, and failed replacement restores the previous directory.
No local branches, merge workflow, or retained version history are created.
Existing running tasks may have already loaded previous instructions; subsequent skill reads use the new files.
Release visibility and any enterprise publication approval remain controlled by the Hub; this API does not introduce a separate client-side approval system.
Installs one remote Skill from the same effective OpenCSG Hub. For a signed-in user, the server sends the matching OpenCSG access token with the archive request and with every legacy tree/blob fallback request, allowing installation of private Skills visible to that user. Signed-out installs remain limited to public Skills. Set replace to overwrite an existing local Skill with the same name. Built-in Skills cannot be replaced; the remote install dialog hides the action when the installation name matches a built-in Skill.
{
"remote_path": "AIWizards/agent-builder",
"ref": "main",
"replace": false
}Returns 201 Created with the installed local Skill summary, including source: "market". Installation records are kept in .skillhub-lock.json under the skills root, shared with CLI installs, and include the complete source_url, ref/version, skill content SHA256, and installation/update times. Web installs save the skill page URL; CLI installs save the catalog URL used to resolve the skill. Readers use the stored URL directly. New records do not write split origin fields. The original CLI registry field is retained to identify older market installations, without guessing a missing full URL. GET /api/v1/skills reads these records; ZIP uploads use source: "local", and untracked installations use source: "unknown". Older CLI records containing a registry are also recognized as market installs. The UI labels untracked installations as “Local”, with a hint that the original installation channel was not recorded. Replacing or deleting a Skill also updates its installation record. A cross-process OS lock on .skillhub-lock.json.lock covers reads and the entire update, file operation, and rollback, so concurrent CLI and Web operations cannot overwrite each other’s records. The lock file remains on disk; closing the handle or exiting the process releases the OS lock. A duplicate without replace returns 409 Conflict.
Reads the current user's authorized knowledge-base MCP configuration without modifying local connections. It also works for installed knowledge bases and returns the existing local server name, preserving its identity when refreshing the configuration. Persist the returned configuration through the MCP create or update API.
Participants are channel-scoped identities used by rooms, messages, mentions, notifications, and runtime bridges. A participant can represent a human, an agent-backed channel identity, or a notification sender.
Returns participants for the specified channel.
Path parameters:
channel:csgclaworfeishu
Optional query parameters:
type:human,agent, ornotificationagent_id
Response fields:
idchanneltypenameavatarchannel_user_refchannel_user_kindchannel_app_refagent_idlifecycle_statuspresencementionablemetadatacreated_atupdated_at
Examples:
GET /api/v1/channels/csgclaw/participantsGET /api/v1/channels/csgclaw/participants?type=notificationGET /api/v1/channels/feishu/participants?agent_id=u-worker
Creates a participant in the specified channel.
Path parameters:
channel:csgclaworfeishu
Example request body:
{
"id": "qa",
"type": "agent",
"name": "QA",
"channel_user": {
"ref": "u-qa",
"kind": "local_user_id"
},
"agent_binding": {
"mode": "create",
"agent": {
"name": "QA",
"role": "worker",
"runtime_kind": "codex",
"from_template": "builtin.codex-worker"
}
}
}Notes:
typeis required and must behuman,agent, ornotificationnameis required- The effective channel comes from the route path rather than the request body
agentparticipants can create or reuse an Agent throughagent_binding- For Agent creation, non-empty
agent_binding.agent.instructionstakes precedence over template instructions. An explicitskillslist replaces the template skill selection ([]selects none); omitting it retains template defaults. humanandnotificationparticipants do not create runtime agents- In the example above,
qais the participant ID;u-qais used only as the local channel user ref and generated backing agent ID. - For
csgclaw,channel_user.refis a local IM user ID - For
feishu,channel_user.refis the channel-native open ID
Examples:
POST /api/v1/channels/csgclaw/participantsPOST /api/v1/channels/feishu/participants
Returns one participant.
Updates editable participant fields such as name, avatar, mentionable, and
metadata.
Deletes the specified participant in the specified channel.
Returns 204 No Content on success.
Examples:
DELETE /api/v1/channels/csgclaw/participants/qaDELETE /api/v1/channels/feishu/participants/qa
/api/v1/agents* returns agent objects with fields like:
{
"id": "u-alice",
"name": "alice",
"description": "frontend dev",
"runtime_id": "codex",
"runtime_kind": "codex",
"image": "example/image:latest",
"box_id": "codex-session-alice",
"role": "worker",
"status": "running",
"created_at": "2026-05-16T08:00:00Z",
"profile": "api.gpt-5.4",
"runtime_options": {},
"mcpServers": {
"workspace-filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"]
}
},
"agent_profile": {
"provider": "api",
"base_url": "https://api.example.com/v1",
"api_key_set": true,
"api_key_preview": "sk-1...",
"model_id": "gpt-5.4",
"reasoning_effort": "medium",
"profile_complete": true
},
"profile_complete": true,
"detection_results": []
}Notes:
- The real
api_keyis never returned inagent_profile runtime_optionsis sanitized before being exposed by the APImcpServersis a direct server-name-to-server-config map. Generic Agent responses redact secret values in serverenvandheadersmaps.profileis the normalized selector generated by the server, for exampleapi.gpt-5.4detection_resultsis used to present default profile detection results
Lists all agents.
The server reloads state before returning the latest snapshot.
Creates an agent.
Request fields:
idnamedescriptionimageruntime_kindfrom_templatereplacefield_maskrolestatuscreated_atprofileruntime_optionsmcpServersagent_profile
from_template should use the exact ID returned by the template list API. Built-in and local IDs use forms such as builtin.codex-worker and local.my-worker; remote IDs use <namespace>/<name>.
Example request body:
{
"id": "u-alice",
"name": "alice",
"description": "frontend dev",
"runtime_kind": "codex",
"profile": "api.gpt-5.4",
"agent_profile": {
"provider": "api",
"base_url": "https://api.example.com/v1",
"api_key": "sk-xxx",
"model_id": "gpt-5.4",
"reasoning_effort": "medium"
}
}Additional notes:
nameis requiredreplace=trueenables replace logicfield_masklimits which fields are overwritten during replacementagent_profile.api_keyis write-only and will be redacted in reads
Codex CLI and DSH agents configure MCP servers through the
top-level mcpServers field. Its value is the direct server-name-to-server-
config map used by every supported runtime:
{
"name": "alice",
"runtime_kind": "codex",
"mcpServers": {
"workspace-filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/path/to/workspace"
]
}
},
"profile": "api.gpt-5.4"
}Runtime adapters map this shared input as follows:
- Codex CLI:
mcpServers-> managed[mcp_servers."<name>"]blocks in the isolated Codex homeconfig.toml
MCP commands run inside the target runtime environment, so filesystem server
directory arguments must be paths visible to that runtime. MCP-shaped values
under runtime_options (including mcp and mcpServers) are rejected; use
the top-level mcpServers field instead.
Gets a single agent.
Returns 404 if it does not exist.
Updates basic agent fields.
Supported fields:
namedescriptionimageruntime_optionsmcpServersagent_profile
Example request body:
{
"description": "updated description",
"runtime_options": {
"execution_mode": "read_only"
}
}Notes:
- Omitted fields are left unchanged
runtime_optionsuses whole-object replacement when submitted- Codex worker agents accept
runtime_options.execution_modevaluesstandardandread_only; an omitted or blank value defaults tostandard - Changing a running Codex worker's execution mode restarts its runtime so the new command, sandbox, and approval policy takes effect
mcpServersuses whole-map replacement when submitted; sendnullto clear the CSGClaw-managed server set- Updating MCP servers on Codex CLI or DSH agents may recreate that agent runtime so the native configuration takes effect
- If
agent_profile.api_keyis sent empty, the server keeps the existing key - If
agent_profile.envchanges,env_restart_requiredmay becometruein the response
Agent responses set memory_supported when the selected Runtime implements the CSGClaw memory capability.
The Profile page shows the Memory tab only for those agents.
Returns the Runtime's read-only primary memory document and its enabled state.
ready is false until the Runtime has generated the document.
{
"enabled": true,
"ready": true,
"name": "memory_summary.md",
"location": "$CODEX_HOME/memories/memory_summary.md",
"content": "# Durable memory\n"
}location is a Runtime-provided logical file location for display and diagnostics; Codex currently reports $CODEX_HOME/memories/memory_summary.md.
Accepts { "enabled": true } or { "enabled": false } and returns the same memory document shape.
The Runtime owns how that setting is represented and whether applying it requires a restart.
Generated memory content is read-only through this API.
Lists chat resources attached to a DSH or Codex Agent. Required type is skill, connector, or knowledge_base. Required pagination uses the existing cursor or page parameters, with search, enabled, repeated exclude=source:id, and list_revision. Page and cursor parameters cannot be mixed.
Responses contain {items, total, list_revision, has_more, next_cursor?}; page mode also includes page and per. Each item contains source (skill, mcp, or app), id, type, name, optional description, enabled, available, and optional unavailable_reason. Empty results use []. Responses use Cache-Control: no-store.
Skills reuse SkillQuery membership selection before reading metadata for the requested page. MCP identity is its configuration key; App identity is its installation ID. Knowledge bases include managed MCP servers and llm-wiki bindings. App availability includes binding and global enablement, connection state, and the current Agent's callable tool catalog. Credentials, connection configuration, and SKILL.md contents are excluded from summaries.
Filtering precedes pagination and stable identity ordering. Invalid queries return 400 invalid_resource_query; changed membership or query scope returns 409 resource_list_changed. Dependency failures return 503 resource_service_unavailable. Skills and MCP remain available when Apps is not enabled.
Returns the agent's MCP server configuration as a direct raw
server-name-to-server-config map in servers. Unlike generic Agent responses,
this endpoint does not redact configured token values.
{
"agent_id": "u-alice",
"runtime_kind": "codex",
"servers": {
"context7": {
"command": "uvx",
"args": ["context7-mcp"],
"env": { "CONTEXT7_API_KEY": "secret" }
}
}
}Accepts { "names": ["..."] } and merges the named server definitions from
the MCP catalog into the agent's managed MCP servers. The response has the same
shape as the GET endpoint.
An optional enabled boolean sets the copied definitions' Agent enablement in
the same update. Omitting it preserves each catalog definition's state. Profile
passes enabled: true when adding resources; the global catalog is unchanged.
Accepts { "names": ["..."] } and removes the named servers from the
agent's managed MCP servers. The response has the same shape as the GET
endpoint.
The reusable MCP server catalog remains at /api/v1/mcp-servers:
GET /api/v1/mcp-serverslists catalog serversPOST /api/v1/mcp-serverscreates a catalog serverPUT /api/v1/mcp-servers/{name}replaces one catalog serverDELETE /api/v1/mcp-servers/{name}deletes one catalog server
Catalog list and mutation responses use mcpServers as the direct server map.
Creating or replacing one catalog entry uses { "name": "...", "config": { ... } };
config is that entry's server configuration.
Lists installable remote MCP server summaries through CSGClaw. The browser only
calls CSGClaw; the server resolves the effective OpenCSG Hub from the current
login environment or explicitly configured official Hub and forwards the
current user's Hub credential. Query parameters follow the remote Skill list
style: page (default 1), per (default 12, maximum 100), and search.
Each item contains its Hub id, name, and display metadata. It intentionally
does not contain its install configuration or headers. description is catalog
metadata used to describe the MCP in CSGClaw; it is removed before a catalog
entry is added to an agent runtime.
{
"items": [
{
"id": "builtin:calendar",
"name": "calendar",
"description": "Calendar tools",
"url": "https://mcp.example.test/calendar",
"protocol": "streamable-http"
}
],
"page": 1,
"per": 12,
"total": 13,
"next_page": 2
}Installs or refreshes one remote MCP entry. CSGClaw fetches the Hub item's
detail endpoint server-side, converts protocol, url, and headers into the
catalog configuration, and uses the detail response's name as the catalog
key. New remote entries default to enabled: true, startup_timeout_sec: 5,
and tool_timeout_sec: 60. Resolving the Hub detail, performing the MCP
handshake, and discovering tools share a five-second total installation deadline.
The response returns only the installed name:
{ "name": "calendar" }Deletes an agent.
Returns 204 No Content on success.
Starts the agent and returns the updated agent object.
Stops the agent and returns the updated agent object.
Returns agent logs.
Query parameters:
lines: defaults to20follow:1/true/yes/onenables streaming follow mode
Response type: text/plain; charset=utf-8
Notes:
- With
follow=false, errors are returned as normal HTTP errors - With
follow=true, streaming-time errors may be written into the response body
Returns the redacted profile for a single agent.
Replaces the profile for a single agent.
The request body uses the agent_profile shape, for example:
{
"provider": "api",
"base_url": "https://api.example.com/v1",
"api_key": "sk-xxx",
"model_id": "gpt-5.4",
"reasoning_effort": "medium",
"headers": {
"x-org": "demo"
},
"env": {
"FOO": "bar"
}
}Notes:
- Unlike
PATCH /api/v1/agents/{id}, this endpoint semantically replaces the current profile with the new one - If
api_keyis empty, the server keeps the existing key
Recreates the agent using its current configuration and returns the new agent state.
Common failures:
404: agent does not exist400: profile is incomplete, or the runtime does not allow recreation
Returns the available model list for the given provider configuration.
Request fields:
agent_idproviderbase_urlapi_keyheaders
Example request body:
{
"provider": "api",
"base_url": "https://api.example.com/v1",
"api_key": "sk-xxx"
}Example response:
{
"provider": "api",
"models": ["gpt-5.4", "gpt-5.4-mini"]
}Notes:
- For
provider=codexorclaude_code, model choices are obtained through CLIProxy - For
provider=api, the server calls the target OpenAI-compatible/modelsendpoint - If
agent_idis provided andapi_keyis omitted in the request, the server may reuse the saved key from that agent - If
agent_idis omitted andapi_keyis omitted, the server may reuse the saved default API key only whenprovider=apiandbase_urlmatches the current default profile
Returns the redacted view of the current default agent profile.
This is commonly used by the frontend to initialize default provider/model state.
Templates use the following layout:
<template>/
agent.toml
instructions/AGENTS.md
skills/<skill>/...
mcps/mcp.json
memories/memory_summary.md # optional Codex memory snapshot
memories/MEMORY.md # optional root memory for non-Codex runtimes
memories/memory/*.md # optional dated memory files for non-Codex runtimes
AGENTS.md and mcp.json are always emitted when publishing.
Other instruction files are optional.
Memory is included only when each publish request explicitly sets include_memory: true; runtime memory enablement alone never opts a publish into exporting memory. With that publish opt-in, Codex templates snapshot CODEX_HOME/memories/memory_summary.md and restore it to the same location for a newly created agent when memory_mode is enabled. Templates with memory_mode = "disabled" neither package nor restore a memory summary. They do not copy Codex's SQLite memory pipeline state or treat memory as a workspace overlay.
With the same explicit publish opt-in, supported non-Codex runtimes preserve and overlay optional template memories according to that Runtime's workspace convention.
During agent creation, skills are installed under skills/, and MCP servers from mcp.json are applied unless the create request explicitly supplies mcpServers.
See MCP Configuration for common fields, OpenCSG Gateway declarations, file bindings, and security rules for mcps/mcp.json.
Codex worker templates may persist their execution mode in agent.toml:
[runtime_options]
execution_mode = "read_only"
memory_mode = "disabled"Only template-safe runtime options are published.
For Codex workers this currently means execution_mode and memory_mode; machine-local options such as local_workspace_dir are not published.
Explicit runtime options in an agent create request override template values.
Missing execution_mode defaults to standard. Standard mode configures Codex with sandbox_mode = "danger-full-access", allowing access outside the workspace subject to the operating system permissions of the runtime process.
Missing memory_mode defaults to enabled.
DSH workers accept workspace-write, read-only, or danger-full-access as permission_mode, defaulting to danger-full-access. local_workspace_dir selects an absolute local path; when empty, DSH uses the managed Agent workspace. Changing the directory starts fresh DSH sessions so an old session is never resumed in a different directory. CSGClaw stores Agent instructions in the isolated DSH_HOME/AGENTS.md; DSH also loads the selected project's own AGENTS.md without modifying it. Template publishing retains only permission_mode, not the machine-local directory.
Lists all templates from readable registries.
Response fields:
idnamedescriptionruntime_kindimageruntime_optionsupdated_atsource.namesource.kindworkspace.kind
Publishes an existing agent workspace to the hub.
Request body:
{
"agent_id": "u-alice",
"registry": "local",
"include_memory": false
}Notes:
agent_idis requiredregistryuses the default publish registry when omittedinclude_memorymust be explicitly set totrueto publish the Codex memory summary, including when republishing an existing local template viatemplate_id; it defaults tofalsebecause memories may contain private conversation-derived information- Community publication accepts up to 100 MiB per template and applies a 50 MiB client limit per file, measured before Base64 encoding. StarHub's ordinary Git file limit also applies. A template over the total limit returns HTTP 413 with
error.code: "template_publish_total_too_large"anderror.max_total_bytes. - Publication commits to the repository's existing default branch and skips unchanged files on update. Batches target 10 MiB of raw file content and allow at most 200 file operations. A larger file accepted for ordinary Git upload uses its own batch.
- Timeouts and retryable service errors trigger up to two automatic retries. Each retry reads the current remote state and commits the remaining changes. A changed
agent.tomlgets its own commit after all other files succeed. A failed publication can leave some file changes on the branch with the previous version marker. Publishing the same local version again reconciles the remaining changes. - Successful publish returns
201 Created
Returns template details.
In addition to the list view fields, this endpoint also returns:
workspace.entries
Example workspace.entries payload:
{
"workspace": {
"kind": "dir",
"entries": [
{"path":"agent.toml","name":"agent.toml","type":"file","depth":0,"size":128},
{"path":"instructions","name":"instructions","type":"dir","depth":0,"size":0}
]
}
}Reads a single file preview from the template workspace.
Query parameters:
path: required relative path
Response fields:
pathcontentsizetruncatedbinary
Notes:
- Non-UTF-8 files return
binary=true - Text content larger than
32 MiBis truncated and returned withtruncated=true - Absolute paths and
..traversal are rejected
Returns the local auth status for a provider.
provider is required.
The response is provided by CLIProxy and commonly includes:
providerauthenticatedlogin_requiredmessagesupports_login
Triggers provider login.
Request body:
{
"provider": "codex",
"no_browser": true
}Returns the current provider auth status on success.
Notes:
- Missing
providerreturns400 - Login failure returns
502 Bad Gateway
Returns the bootstrap config view.
Response fields:
default_manager_templatedefault_worker_templateruntime_kindeffective_manager_imagesupported_runtime_kindsruntime_default_images
Updates the default bootstrap templates.
Request body:
{
"default_manager_template": "builtin.manager",
"default_worker_template": "local.review-bot"
}Notes:
- Both fields are optional
- The updated config is validated after modification
- If the default templates change and the agent service is mounted, the gateway runtime is updated as well
These endpoints expose CSGClaw local IM data.
For the thread model, invariants, hidden context behavior, and bridge rules, see im-threads.md.
Returns IM bootstrap data.
Response fields:
current_user_idusersroomsinvite_draft_user_ids
Room message lists in the bootstrap response follow the default timeline contract: top-level messages only; thread replies are hidden.
Subscribes to the local IM event stream.
Returns text/event-stream. After the connection is established, the server first writes:
: connected
Then it streams JSON events as SSE data: frames. The heartbeat frame is:
: ping
Currently observed event types include:
message.createdroom.createdroom.members_addedthread.createdthread.updatedupgrade.status_changed
Event JSON fields:
typeroom_idroomusermessagethreadsenderupgrade
Lists local IM users.
Creates a local IM user.
Request body:
{
"id": "alice",
"name": "Alice",
"role": "worker"
}Notes:
idis requirednameis required- For
workeroragentroles, if participant and agent services are both enabled, prefer the participant API for agent-backed identities
Deletes a local IM user.
Deleting a user also rebuilds thread state from the surviving room messages. Thread roots sent by the deleted user are removed, hidden context snapshots are regenerated without deleted-user messages, and surviving thread creation times are preserved where possible.
Common responses:
204: deleted successfully404: user not found409: attempted to delete the current user
Lists local IM rooms.
Room message lists exclude thread replies by default. Root messages still expose their thread summaries when a thread exists.
Creates a room.
Request body:
{
"title": "Launch",
"description": "coordination",
"creator_id": "manager",
"member_ids": ["alice", "bob"],
"locale": "en"
}Compatibility field:
- Legacy
participant_idsis still accepted and mapped tomember_ids
Updates local room behavior.
Request body:
{
"notify_all_agents": true
}Group rooms are mention-only by default.
When notify_all_agents is enabled, every human-authored message wakes every agent in the room, including messages with explicit mentions.
Agent-authored replies still wake only explicitly mentioned agents to prevent response loops.
Direct rooms always notify their agent and reject this update.
Deletes a room and returns 204 on success.
Lists room members.
Adds members to the specified room.
Request body:
{
"inviter_id": "manager",
"user_ids": ["bob"],
"locale": "en"
}Notes:
- The path
{id}is used asroom_id - If
room_idis also present in the body, it must match the path value
Adds members by room ID, with semantics similar to POST /api/v1/rooms/{id}/members.
Request body:
{
"room_id": "room-1",
"inviter_id": "manager",
"user_ids": ["bob"],
"locale": "en"
}Returns the message list for the specified room.
room_id is required.
By default, thread replies are excluded from the room timeline. Add
include_thread_replies=true to include threaded replies in the returned
message list.
Sends a message.
Request body:
{
"room_id": "room-1",
"sender_id": "manager",
"content": "hello @alice",
"mention_id": "alice"
}Notes:
room_idis required- Returns
201 Createdon success - A successful send also publishes
message.createdto/api/v1/events - To send a thread reply, include
relates_to: {"rel_type":"m.thread","event_id":"<root_message_id>"} relates_to.rel_typecurrently supportsm.thread; the root must be a top-level message in the same room- A thread reply also publishes
thread.updated - To send attachments, use
multipart/form-datawith apayloadJSON part containing the same fields and one or morefilesparts. - Attachment-only messages are valid when at least one file is present.
- A message accepts up to 10 attachments, with a maximum of
1 GiBper file and2 GiBin total. - Each returned message can include
attachmentswithid,name,kind,media_type,size_bytes,sha256,created_at,download_url, optionalpreview_url, optional image dimensions, and optionalworkspace_pathfor agent-facing deliveries. Files published from a workspace also includesource_path, the workspace-relative path used to match inline images even when the delivery name changes.
Multipart example:
payload={"room_id":"room-1","sender_id":"manager","content":""}
files=@diagram.png;type=image/png
DSH and Codex direct messages and their thread replies accept optional resource_refs, with at most 16 entries:
{
"room_id": "room-dm",
"sender_id": "user-admin",
"content": "Review this MR",
"resource_refs": [
{"source": "skill", "id": "review"},
{"source": "app", "id": "installation-id"},
{"source": "mcp", "id": "engineering-guidelines"}
]
}The server trims IDs, validates attachment and availability, and deduplicates by (source, id) while retaining selection order. A message requires text, attachments, or exactly one valid skill. An empty message selecting only MCP, App, or multiple resources requires an attachment. Group messages and /new commands reject resource selections.
Multipart payload uses the same fields. The server stores {version: 1, agent_id, refs: [{source, id, type, name}]} in metadata.csgclaw.resource_selection, replacing client-supplied values in this namespace. History uses the saved display snapshot. Execution resolves references again against the current Agent and resource state. Each message has its own selection. Legacy skill input is normalized into the same references at ingress.
Successful retries with the same client_message_id return 201 and the original Message even if resources have subsequently changed. A changed selection is a new logical submission and needs a new ID. Errors include 400 invalid_resource_reference, 400 invalid_request, 409 resource_not_attached, 409 resource_disabled, 409 resource_unavailable, and 503 resource_service_unavailable. Revalidation failures after persistence use the existing execution failure result.
GET /api/v1/rooms/{id}/attachments lists files already published in a CSGClaw room, including user uploads, Agent outputs, thread replies, and retained thread context.
It returns {items, total, from, limit}; each item contains id, name, kind, media_type, size_bytes, sha256, created_at, message_id, and sender_id.
It does not return workspace paths or download capability tokens.
Optional query matches a case-insensitive filename substring, and message_id filters the source message.
Results are deduplicated by attachment ID and sorted by creation time descending, then ID descending.
from defaults to 0; limit defaults to 50 and accepts 1 through 200.
Same-name uploads remain distinct attachments.
GET /api/v1/rooms/{id}/attachments/{attachment_id} streams the original bytes only while the attachment is still referenced by that room.
All attachment endpoints use server authentication and check current room membership for runtime callers identified through the existing X-CSGClaw-Caller-Agent mechanism.
The download includes X-CSGClaw-File-Size and X-CSGClaw-File-SHA256 integrity headers and disables caching.
Missing files or room references return 404; non-member runtime callers receive 403.
csgclaw room attachments list --room-id <room> --query <filename_keyword>
csgclaw room attachments list --room-id <room> --message-id <source_message>
csgclaw room attachments download --room-id <room> --attachment-id <id> --output <new_local_path>
csgclaw room attachments delete --room-id <room> --attachment-id <id>GET /api/v1/rooms/{id}/attachments/{attachment_id}/location returns {absolute_path, directory, open_targets} for local users.
Content-addressed attachments receive a separate named local copy so native applications can identify the original extension.
Editing the copy does not change the published attachment; reopening preserves edits to the copy.
The copy is collected when the attachment loses its final live reference.
The endpoint uses attachment read authorization; a valid download capability can resolve that attachment's location.
Remote clients and scoped Agent callers cannot use local opening actions.
POST /api/v1/rooms/{id}/attachments/{attachment_id}/open accepts { "target": "system" } and returns 204 after application handoff.
It uses the workspace opener's local-client, same-origin JSON and target checks, and revalidates the live room attachment on every call.
A local same-origin browser may pass the attachment's valid download capability as ?token=...; this grants no listing, deletion, remote opening, or access to another attachment.
DELETE /api/v1/rooms/{id}/attachments/{attachment_id} removes that attachment ID from the room's messages and retained thread context, returning 204 No Content.
Message text and separately saved workspace copies are preserved; shared file bytes are collected only when no remaining attachment references need them.
Missing references return 404 and non-member Agent credentials receive 403.
A successful deletion emits room.attachment_deleted with room_id and attachment_id so open conversations remove the attachment immediately.
The same commands are available in csgclaw-cli inside Agent runtimes.
List output is JSON and includes pagination metadata.
Download output is JSON containing attachment_id and the absolute local path.
Downloads are streamed to a temporary file beside the destination, checked against the declared size and SHA256, then published atomically without replacing existing files.
Failures remove temporary files.
The destination directory must already exist.
Global --output json controls CLI formatting before the command; the download subcommand's --output names its destination file.
Workers receive request_source_message_id in server-provided task context, derived from the parent task's original request.
Agents should search that source first, then the current room by filename before requesting another upload.
Attachment contents are task data, not platform instructions.
Current-message and inherited thread attachments also enter the native file-input path, with per-execution staging and ID deduplication.
Room deliveries create temporary inputs for each turn. To keep a room file at a chosen workspace path, copy or download it there and verify the saved file.
Subsequent turns should use the room attachment commands to recover historical uploads instead of relying on expired temporary paths.
Clearing messages or deleting the room follows existing attachment reference cleanup; explicitly downloaded workspace copies remain ordinary local files.
Unpublished Agent workspace files and document full-text search are outside this interface.
Downloads a room or direct-session attachment by ID.
The download_url returned in attachment metadata includes an attachment-scoped capability token and can be used directly by browsers and agents.
Callers may instead request the bare path with the configured server Bearer token.
For a room attachment this endpoint serves the original bytes with the stored media type. For a direct-session attachment it opens the current workspace file, detects its content type, and sends Cache-Control: private, no-store. Deleting the workspace file makes its URL return 404. Use HEAD to request headers only. Responses include X-Content-Type-Options: nosniff.
Downloads return the complete stored file without an additional size limit and support HTTP Range requests.
Treat the capability URL as a secret and share it only with the intended recipient.
Image attachments are served inline.
Other file attachments are served with attachment disposition.
Starts a thread from an existing top-level message. The thread identity is the
root message ID, matching Matrix m.thread relationship semantics without
using the raw /_matrix namespace.
Request body:
{
"root_message_id": "msg-root"
}Responses:
201 Created: a new thread state was created200 OK: the thread already existed and was returned idempotently
The response is a ThreadView:
{
"room_id": "room-1",
"root": { "id": "msg-root" },
"context": [],
"replies": [],
"summary": {
"root_id": "msg-root",
"reply_count": 0,
"participants": [],
"current_user_participated": true,
"context_summary": {
"root_excerpt": "root text",
"message_count": 1,
"before_count": 0,
"after_count": 0
}
}
}ThreadView.root is the visible root message, context is the hidden snapshot
for LLM context, replies is the visible thread reply list, and summary is
the root-level thread summary used by timelines and thread lists.
Thread context is snapshotted when the thread starts: up to five top-level messages before the root, the root message, and up to two top-level messages after it, capped by payload size. This context is not rendered as thread messages; it is hidden context for LLM-backed agents so a thread can begin with a clean conversation while still understanding what it was started from.
Lists room threads. include defaults to all; participated returns only
threads where the current user is the root sender or a reply participant.
limit and from implement offset-style pagination.
Returns one ThreadView, including the root message, hidden context window,
replies, and summary.
Returns Matrix-style child events for a thread root:
{
"chunk": []
}/api/v1/channels/csgclaw/* is essentially a mirrored entrypoint for the local IM API.
GET /api/v1/channels/csgclaw/usersPOST /api/v1/channels/csgclaw/usersDELETE /api/v1/channels/csgclaw/users/{id}
Notes:
GETandPOSTreuse the local IM user logicDELETEuses channel-specific delete handling, but still semantically deletes the local user
GET /api/v1/channels/csgclaw/roomsPOST /api/v1/channels/csgclaw/roomsDELETE /api/v1/channels/csgclaw/rooms/{id}GET /api/v1/channels/csgclaw/rooms/{id}/membersPOST /api/v1/channels/csgclaw/rooms/{id}/membersPOST /api/v1/channels/csgclaw/rooms/{id}/threadsGET /api/v1/channels/csgclaw/rooms/{id}/threadsGET /api/v1/channels/csgclaw/rooms/{id}/threads/{root_message_id}GET /api/v1/channels/csgclaw/rooms/{id}/relations/{event_id}/m.thread
GET /api/v1/channels/csgclaw/messages?room_id=...POST /api/v1/channels/csgclaw/messages
/api/v1/channels/feishu/config was removed. Feishu credentials are part of
the Feishu participant object (channel_app_config) and are set via participant
binding (participant bind) or participant update APIs.
In participant responses, the secret is masked as present.
Subscribes to mention events for the specified participant in Feishu.
Characteristics:
- Requires Bearer Token
- Returns
text/event-stream - Only forwards events whose message mentions the participant open_id
- Writes
: connectedimmediately after the stream is established
GET /api/v1/channels/feishu/usersPOST /api/v1/channels/feishu/usersDELETE /api/v1/channels/feishu/users/{id}
Example POST body:
{
"id": "ou_xxx",
"name": "Alice",
"role": "member",
"avatar": "AL"
}GET /api/v1/channels/feishu/roomsPOST /api/v1/channels/feishu/roomsDELETE /api/v1/channels/feishu/rooms/{id}GET /api/v1/channels/feishu/rooms/{id}/membersPOST /api/v1/channels/feishu/rooms/{id}/members
Room creation and member-addition requests are mostly aligned with local IM and still use:
titledescriptioncreator_idmember_idslocale
Example add-members request:
{
"inviter_id": "manager",
"user_ids": ["dev"],
"locale": "zh-CN"
}GET /api/v1/channels/feishu/messages?room_id=...POST /api/v1/channels/feishu/messages
Example send-message request:
{
"room_id": "oc_xxx",
"sender_id": "manager",
"content": "hello",
"mention_id": "worker"
}Runtime clients use participant-scoped routes for channel messages and
agent-scoped routes for LLM provider traffic. The legacy /api/bots/* routes
are not registered.
For thread/session isolation rules used by runtime and Codex bridges, see im-threads.md.
Subscribes to the participant event stream.
Characteristics:
- Requires Bearer Token
- Returns
text/event-stream - Writes
: connectedimmediately after the stream is established - Uses
: heartbeatas the heartbeat comment - Uses
messageas the SSE event name - If the client sends
Last-Event-ID, the server may replay recent messages according to the replay rules
Example single event:
id: msg-1
event: message
data: {"message_id":"msg-1","room_id":"room-1","channel":"csgclaw","chat_id":"room-1","sender_id":"admin","text":"hello","thread_root_id":"msg-root","context":{"channel":"csgclaw","chat_id":"room-1","chat_type":"direct","topic_id":"msg-root","sender_id":"admin","message_id":"msg-1"},"thread_context":{"root_message_id":"msg-root","context":[{"id":"msg-root","sender_id":"admin","content":"root text"}],"summary":{"root_excerpt":"root text","message_count":1,"before_count":0,"after_count":0}}}
For thread replies, thread_root_id is the root message ID and
thread_context carries the deterministic hidden context captured when the
thread was started. Runtime/LLM bridges use it as prompt context; it is not a list
of thread replies. Participant clients can use context.topic_id as the
same thread/session identifier.
Events can include an attachments array with the same message attachment metadata returned by the message APIs.
For CSGClaw agents, the server also attempts to copy each attachment into the target agent workspace and sets workspace_path when that copy succeeds.
Sends a message as the specified local CSGClaw participant.
Example request body:
{
"room_id": "room-1",
"text": "hello",
"thread_root_id": "msg-root"
}thread_root_id, topic_id, and context.topic_id are optional thread/topic
identifiers. When one is present, the participant response is sent as a reply inside
that IM thread. When all are omitted, the response is sent as a top-level room/DM
message; the server does not infer a thread from the participant's most recent room
event.
This endpoint also accepts the same multipart attachment format as POST /api/v1/messages.
Use a payload JSON part for the participant message fields and one or more files parts for generated files.
Participant outbound message shape is also accepted:
{
"chat_id": "room-1",
"content": "hello",
"context": {
"channel": "csgclaw",
"chat_id": "room-1",
"topic_id": "msg-root"
}
}Uploads files to the selected agent and session without starting a turn. Authenticate using the service credentials for the current CSGClaw instance. Send one or more files parts in a multipart/form-data request. This endpoint accepts only files parts, each containing the filename and raw bytes. The limits are 10 nonempty files, 1 GiB per file, and 2 GiB total.
On success, the server returns 201 Created with {"attachments":[…]}. Each item uses the same fields as Message.attachments. The workspace file and its authorized download are available immediately, before the client sends a prompt. When the user sends the message, pass those IDs in attachment_ids to the session’s /responses endpoint.
Runs one turn through the selected agent and its real CSGClaw runtime.
The {agent} selector accepts an agent ID or a unique case-insensitive agent name.
This endpoint is separate from /llm/responses, which proxies model traffic without running the agent.
The client supplies a 1–128 character session_id starting with an ASCII letter or digit. The remaining characters can also include ., _, ~, and -.
The server binds the session to a conversation for the selected agent and reuses it on later turns. Direct sessions return an empty metadata.room_id.
In Portal, send uploads and downloads to the current CSGClaw instance's endpoint with the gateway credentials for that instance.
The optional top-level attachment_ids array references files already saved for this agent and session. Supply distinct IDs. With service authentication enabled, all requests carrying files or attachment IDs require valid credentials. Missing or invalid credentials return 401. An unknown ID or an ID belonging to another agent or session returns 404. A JSON request may combine referenced IDs and inline Base64 files, up to 10 files in total. In input_attachments, referenced files appear in the order of their IDs, followed by newly uploaded files in request order.
When authentication is enabled, anonymous clients can send up to 1 MiB of plain-text JSON with user_input omitted or set to false. Larger bodies return 413. Starting a new turn while a protected form awaits submission requires valid credentials.
The shortest request uses string input:
{
"input": "Review this patch."
}For a Codex agent, optional string fields model and reasoning_effort select the model and reasoning effort for this request:
{
"input": "Review this patch.",
"model": "model-id-from-your-provider",
"reasoning_effort": "high"
}model is a model ID served by the agent's configured provider. Omitted or empty fields use the agent's default profile. These options apply to the current turn. Send the options again on later requests to keep using them. Non-empty options on other runtimes return 400 invalid_request.
reasoning_effort accepts auto, none, minimal, low, medium, high, xhigh, and max; off is an alias for none. The selected provider/model must support the requested level. auto lets the model choose its reasoning default. Each omitted field independently inherits its Profile value, including when the other field is specified. Both fields also work with stream: true.
An explicit model can name any chat model served by the configured provider, including one absent from its configured model list. Image and video generation models return HTTP 400 with param: model. When a selected model requires a new context window, CSGClaw waits for the agent's active turns to finish and reloads the Codex App Server automatically. Existing sessions retain their conversation history.
The request may attach supplemental text to the current user message with the
optional extra and extra_type fields:
{
"input": "How do I continue on this page?",
"extra_type": "web_page_dom",
"extra": "<main><button>Continue</button></main>"
}extra_type supports plain_text and web_page_dom. When extra is present
but extra_type is omitted or empty, the server uses plain_text. An omitted
or empty extra injects no context and ignores extra_type. An unknown non-empty
extra_type returns 400 invalid_request. A plain_text extra is limited to
64 KiB and a web_page_dom extra to 512 KiB. The request excluding Base64 file
data is limited to 1 MiB.
The server wraps the content in an <extra_context> with fixed safety guidance
and submits it with the user input. A web_page_dom value is labeled as an
untrusted page snapshot: configured product-documentation skills remain the
primary authority, while the DOM helps identify the current page and UI state.
This rule is also installed in CSGClaw-managed Runtime instructions so it has
higher priority than page content. The server parses the DOM again and removes
scripts, styles, embeds, hidden nodes, password and hidden inputs, form values,
editable content, and attributes outside a small allowlist. Link user information,
queries, and fragments are also removed. Clients should still remove credentials
and personal data before submission because static HTML cannot reveal every CSS
visibility rule or application-specific sensitive field. Sanitized DOM is limited
to 128 KiB; larger output is truncated on a UTF-8 boundary, parsed again to close
partial HTML, and marked with [page DOM truncated by CSGClaw].
Supplemental context becomes part of the Codex
conversation history and may be referenced by later turns. The response does not
return the raw extra as a separate field, although the agent may quote relevant
parts in its answer.
Text-only user message items are also accepted:
{
"input": [
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "Review this patch."
}
]
}
],
"stream": false
}A browser can send a prompt and selected files in one multipart/form-data
POST. Set responsesUrl to the session’s /responses URL and token to the
Bearer credential for that instance. Include one input field containing the
JSON encoding of a prompt string or the message array shown above. The optional stream field
defaults to false. Send it as the string "true" or "false". Append each
selected File under the field name file. The browser supplies the
Content-Type header with the multipart boundary.
const form = new FormData()
form.append("input", JSON.stringify("Summarize this report."))
form.append("stream", "true")
form.append("file", selectedFile)
const response = await fetch(responsesUrl, {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
body: form,
})
if (!response.ok) throw new Error(`Session request failed (HTTP ${response.status})`)The multipart fields are input, optional stream, user_input, model, and reasoning_effort, and repeated file. Each optional field accepts at most one value. Model options have the same meaning as the JSON fields. To send files with attachment_ids, extra, or extra_type, upload the files to the session's /attachments endpoint using files, then include the returned IDs in a JSON request to /responses. A JSON request containing only attachment_ids starts a file-only turn.
JSON requests also support files through input_file parts:
{
"input": [{
"role": "user",
"content": [
{"type": "input_text", "text": "Summarize this file."},
{
"type": "input_file",
"filename": "notes.txt",
"file_data": "data:text/plain;base64,SGVsbG8gd29ybGQK"
}
]
}],
"stream": true
}filename is the file's basename. file_data is a data:<media-type>;base64,<data>
URL containing the complete file. Repeat input_file for multiple files; a
message containing only files is also accepted. The JSON body allowance includes
Base64 expansion plus 1 MiB of other JSON content. Base64 increases transfer size
by about one third. JSON clients and proxies may buffer the encoded request in memory.
Both formats accept up to 10 nonempty files, up to 1 GiB per file and 2 GiB
combined, measured in original file bytes. The worker receives each attachment's
workspace_path and can reopen that path in later turns. Referencing the same
ID uses the current workspace file, including edits, and applies the size limits to its current size. Portal downloads and previews read the same file. Deleting it makes downloads and ID references return 404. The sha256 field identifies the contents at publication. Download responses use the current file's type and length.
Invalid file data or metadata returns 400 invalid_request. Exceeding a file size or HTTP body limit
returns 413 invalid_request. Validation and file preparation finish before the
SSE stream starts.
The server saves uploads in the workspace before calling the agent. SSE includes their download URLs in the first message_start. Saved files remain available after turn cancellation, a busy-session rejection, or an agent error. A JSON error returned after saving the files includes input_attachments.
| Files | JSON success | First SSE message_start |
Final successful SSE message_delta |
|---|---|---|---|
| User uploads | input_attachments |
input_attachments |
input_attachments |
| Agent results | output[0].attachments |
— | attachments |
An agent can publish a zero-byte result. If an Engine result is unavailable, the reply names the missing file and includes the text and downloads for all available results.
The attachment arrays are top-level fields of the SSE event data. Empty arrays are omitted. Each attachment includes id, name, media_type, size_bytes, sha256, download_url, and a relative workspace_path. Images also have a preview_url. PDFs are served with Content-Disposition: attachment. To preview a PDF, use readAttachment(id) below to fetch its Blob, pass URL.createObjectURL(blob) to a PDF viewer, and call URL.revokeObjectURL(url) when the preview closes. A Codex agent can publish results with csgclaw_publish_file.
Uploads and published results each have one file under .csgclaw/attachments/sessions/<session_id>/ in the agent's configured local_workspace_dir or default workspace. IM stores the attachment ID, owner, path, and download credential under assets/session-responses/. When replacing the container, mount both persisted directories at their original paths. A room checkpoint or downgrade preserves the files and IDs for use after upgrading again. On upgrade, existing IDs and download URLs are kept when the file can be found in its owner's workspace. A session download uses Cache-Control: private, no-store.
For Portal history, store the stable attachment ID and display fields with the message and its instance, agent, and session. Exclude tokens and token-bearing download or preview URLs from history. To reopen a file, fetch GET /api/v1/attachments/{id} on the corresponding instance using its current credentials. The session history API does not generate attachment entries for Portal automatically.
A browser can upload as soon as the user selects files, then send a JSON turn when the user submits the prompt.
const endpoint = new URL(instance.endpoint, gatewayHost)
if (endpoint.origin !== new URL(gatewayHost).origin) throw new Error("Unexpected gateway")
const base = endpoint.origin + endpoint.pathname.replace(/\/$/, "")
const headers = { Authorization: `Bearer ${token}` }
const session = `/api/v1/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(sid)}`
function historyFile({ id, name, media_type, size_bytes }) {
return { id, name, media_type, size_bytes }
}
async function upload(files) {
const body = new FormData()
for (const file of files) body.append("files", file, file.name)
const res = await fetch(base + session + "/attachments", { method: "POST", headers, body })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return (await res.json()).attachments.map(historyFile)
}
async function send(prompt, uploads) {
const res = await fetch(base + session + "/responses", {
method: "POST",
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify({ input: prompt, attachment_ids: uploads.map(file => file.id) }),
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const { output } = await res.json()
return { content: output[0].content, attachments: (output[0].attachments ?? []).map(historyFile) }
}
async function readAttachment(id) {
const res = await fetch(base + "/api/v1/attachments/" + encodeURIComponent(id), { headers, cache: "no-store" })
if (!res.ok) throw new Error(await res.text())
return res.blob()
}With stream omitted or set to false, the endpoint returns the completed
Responses-style JSON object containing the final assistant text and session
metadata. With stream: true, it returns text/event-stream using a CSGBot
Genius-compatible, Anthropic-style event stream. A text-only stream uses:
message_start
content_block_start (text)
content_block_delta (text_delta)
content_block_stop
message_delta (stop_reason: end_turn)
message_stop
Each SSE event has an event name and a JSON payload with a matching
type. When the runtime reports reasoning, the stream opens a thinking
content block. The block may contain zero or more thinking_delta events
with a string at delta.thinking. A content_block_stop with the same
index ends that block. Another thinking block can follow a tool call.
Send Prefer: csgclaw-reasoning-summary with stream: true to receive a
model-provided Codex reasoning text or summary when available. The preference is optional.
A server that applies it returns Preference-Applied: csgclaw-reasoning-summary.
Older servers can ignore the preference and respond normally. For each reasoning
item, Session displays the first nonempty textDelta or summaryTextDelta stream
as thinking_delta. All parts stream immediately in arrival order, with paragraph
breaks when the part index changes. Other delta sources for that item are ignored
to avoid duplicate output. Completion snapshots append only matching suffixes not
yet sent for each part of the selected source. Missing earlier text is appended at
the end of the stream. Qwen snapshots stored in summary can complete a matching text prefix.
The existing preference name is retained for compatibility. Thinking blocks carry
display text without Anthropic signatures.
A tool_use block identifies the tool and
carries its redacted input in input_json_delta. The following content_block_stop
ends the input. When the tool finishes, a single tool_result block carries its
output in tool_result_delta. Each text delta waits for results from tools already running when it arrived,
or for the end of the turn if a result is unavailable.
Match tool_result.tool_use_id to tool_use.id, including when tools run
concurrently. For a failed or canceled tool, the result block includes
is_error: true and status: "failed" or "canceled". While a response is
idle, the server sends an SSE : heartbeat comment about every 15 seconds to
keep the connection alive.
For Codex agents, the API streams final-answer text and agent-message deltas
that omit the phase, and skips explicit commentary and text snapshots. Completion
events do not repeat the full text; clients should build the visible answer by
appending deltas. Runtimes that only publish a final message fall back to one text
delta. The stream is established and message_start is flushed before the agent
finishes. Stream failures emit error, message_delta with stop_reason: error,
and message_stop.
Only one turn may run for a session at a time.
Different session IDs may run concurrently.
Different agents can use the same external session_id independently.
The server imposes no response duration limit. After two minutes without progress, the Codex runtime can check the worker's history for a missing completion notification. This check requires a transport that supports write deadlines. When the native turn ID matches and history records a terminal status and completion time, the server sends any missing tool results and recoverable text in native item order before ending the response. If legacy events omit their turn ID after recovery, an identified completion can also restore the current turn from its native items. Both paths use the same SSE block types as live output. Client disconnects and explicit cancellation cancel the running response.
Forms are disabled per request by default. When user_input is omitted or false, the agent is instructed to ask for clarification in its text reply. If the runtime still requests a form, the server lets the turn continue. When a command or assistant emits only a structured question, public questions and options appear as chat text. Secret fields show a notice that a secure form is required. The user can reply with a new message in the same session.
Clients that can display and submit forms opt in by setting "user_input":true in the /responses JSON request, or by sending a multipart field user_input with the string value "true". The built-in room UI supports forms through its own message API.
When instance service authentication is enabled, creating a response with user_input: true, listing questions with GET /interactions, and submitting answers with POST /interactions/{interaction_id}/respond all require valid service credentials for that instance. Missing or invalid credentials return 401 unauthorized. Canceling a form-enabled turn or starting a new turn while a protected form awaits submission also requires valid credentials. Portal clients use the same instance endpoint and gateway authorization as they use for attachment access.
The request_user_input SSE event carries type, interaction_id, status, detached, questions, requested_at and optional auto_resolve_at at the top level. Each question includes id, header, question and optional options, is_other and is_secret. Render questions and options in their supplied order. Agentic frontend integration example (Chinese)
Native questions have detached: false and keep the original response open until answered. A client using stream: false needs another connection to list and answer pending questions. A question produced by a command has detached: true and can outlive the original response. Detached session questions without an explicit deadline expire after 24 hours. With stream: false, the completed response includes these questions in a top-level interactions array.
Returns 200 OK and {"interactions":[...]} using the form fields above. A pending question accepts answers. A submitting question is processing an answer. Disable its submit button and poll the same endpoint until the question disappears or returns to pending. Use the same procedure after a page refresh or a lost response. Disconnecting the original response cancels the active turn.
Submits answers for one form. Use the same instance, agent and session as the response stream. Key the answers by the IDs in questions[].id.
{"answers":{"source":{"answers":["PDF"]},"note":{"answers":["user_note: Include public documents only."]}}}Use the original option label for a selection and the user_note: prefix for free text. Submit all questions together. Each question entry requires an answers array. Use [] to skip that question. Use {"answers":{}} to skip the entire form.
- For
detached: false, submission returns204 No Content. Continue reading the original/responsesrequest for subsequent output. - For
detached: true, submitting an answer starts a continuation in the same session. The/respondrequest returns200with the final JSON response by default, or200with a new SSE stream when the request includes"stream":true. Skipping the entire form returns204 No Content. While an answer is starting its continuation, a competing/responsesrequest receives409 session_busyin JSON mode. If an SSE stream has already started, it reports the error in the stream.
If the runtime is unavailable before it receives a detached answer, the form remains pending. An SSE 200 only opens the stream. On an SSE error, disconnect or service failure, query the list and retry with the same interaction ID only when its status is pending. Invalid answers return 400 invalid_request and leave the form pending. An unknown session or interaction returns 404 session_not_found or 404 interaction_not_found, respectively. A duplicate submission returns 409 interaction_already_resolved. An expired or canceled interaction returns 410 interaction_gone.
Cancels the active response for the selected Agent and Session.
The request returns 204 No Content only after Runtime cancellation and turn cleanup have finished, so the client can safely send the next turn.
Calling it when no response is active is idempotent and also returns 204 No Content.
Errors use this JSON shape:
{
"error": {
"message": "another response is already running for this session",
"type": "conflict_error",
"param": "session_id",
"code": "session_busy"
}
}See Session API Demo Frontend Guide for the bundled live demo and mockable frontend boundary.
Forwards model-list requests to the LLM bridge.
Notes:
- Requires Bearer Token
- Response content type and body are determined by the upstream bridge
Forwards chat-completions requests to the LLM bridge.
Notes:
- Requires Bearer Token
- The request body is read and forwarded as-is
- Maximum request-body size is
128 MiB, including inline images and tool output - Larger bodies return HTTP
413with error coderequest_too_large; the body is never silently truncated - Failures may return either plain-text errors or a JSON error payload such as:
{
"error": {
"code": "unauthorized",
"message": "upstream auth failed",
"provider": "openai"
}
}Forwards OpenAI-compatible Responses API requests to the LLM bridge. Codex runtime uses this entrypoint for provider traffic. If the selected upstream provider returns an unsupported Responses endpoint status, the bridge falls back to upstream chat completions and wraps the result in a Responses-compatible response for Codex.
The GET variants are websocket upgrade endpoints for Responses API sessions.
Example request body:
{
"model": "ignored-by-server",
"input": "Review this patch.",
"stream": true
}Notes:
- Requires Bearer Token
- The request is first forwarded to the selected profile's
base_url + /responses - POST request bodies have the same
128 MiBlimit as chat completions; larger bodies return HTTP413with error coderequest_too_large - If upstream
/responsesreturns404or405, the bridge retries viabase_url + /chat/completions - The
modelfield is overwritten with the agent's resolvedmodel_id - Responses forwarding does not inject the chat-only top-level
reasoning_effort - Upstream Responses headers, status, and body are copied through, including streaming responses such as
text/event-stream
CreateRoomRequest.participant_idsis still accepted and mapped tomember_idsMessage.mentionsremains backward-compatible with the legacy format:- New format:
[{ "id": "alice", "name": "Alice" }] - Legacy format:
["u-alice"]
- New format:
- The local
csgclawchannel routes are effectively mirrored entrypoints for/api/v1/users|rooms|messages
The following paths often seen in older docs are no longer registered in the current router and should not be treated as public APIs:
/api/v1/notify/{agent_id}/api/v1/channels/{channel}/bots/api/v1/channels/{channel}/bots/{id}/api/v1/channels/feishu/bots/{id}/events/api/bots/{id}/events/api/bots/{id}/messages/send/api/bots/{id}/llm/*- Any other legacy path not registered in
internal/api/router.go
With service authentication enabled, workspace browsing, file reads and workspace file references require credentials. Agent workspace requests use the configured local_workspace_dir or the agent's default workspace. A room with an explicit workspace uses its own configured directory.
Lists only the immediate children of the selected workspace directory.
The path is workspace-relative and defaults to the root.
Directories are expanded on demand by the chat file browser.
Both workspace listing and content accept an optional room_id.
The Agent must belong to that room; configured direct tasks use the room's locked working directory instead of the Agent default.
The response also includes absolute_path for display and copying, and open_targets for locally available opening actions.
These host paths are never used as Agent file references.
Resolves an existing regular file or directory to {absolute_path, directory, open_targets} using the same room workspace and bounded path validation as previews.
Each open_targets item contains id, an optional application label, and an optional default flag.
macOS returns installed applications associated with the file; Windows and Linux return the file type's default application.
Directories offer the file manager and an available terminal.
Remote clients receive an empty open_targets list.
Accepts { "path": "docs/report.md", "target": "system" } and returns 204 after handing off to the selected application.
Only loopback clients using a literal loopback host may invoke native applications.
Browser callers must send an exact same-origin JSON request; authenticated local callers may omit Origin.
Explicit invalid credentials and scoped Agent callers cannot invoke this operation.
Targets must match an id in the file's current open_targets; arbitrary applications and shell commands are rejected.
system reveals a file or opens its directory in the file manager; editor targets open the file or directory, and terminal targets open the current directory or a file's parent.
Errors use workspace_open_denied, workspace_file_unavailable, or workspace_open_failed.
Streams the original workspace file with its MIME type, download filename, and HTTP Range support. The path must identify a regular file beneath the selected Agent workspace, without symlinks or parent traversal. This endpoint uses the existing workspace administration access policy. HTML is delivered with a sandbox policy; the Web UI renders it through the existing sanitized preview.
Both JSON and multipart payload accept an optional file_references array:
{
"room_id": "room-1",
"sender_id": "admin",
"content": "Review @docs/report.md",
"client_message_id": "reference-send-1",
"file_references": [
{"source": "workspace", "agent_id": "alice", "path": "docs/report.md"},
{"source": "attachment", "attachment_id": "att-example"}
]
}A workspace source must belong to an Agent in the destination room.
Workspace references resolve beneath the same destination room working directory used by listing and preview.
An attachment source must still be referenced by that room.
Repeated identical sources are included once, and references share the existing attachment quotas with uploads.
Workspace directory references use the same source format and snapshot the directory as one ZIP attachment, preserving its name and relative structure.
Symlinks and special files are rejected; both original bytes and ZIP size must fit the single-file limit, with at most 10,000 entries per directory.
The server snapshots referenced bytes into ordinary message attachments and uses the existing per-recipient file delivery pipeline.
The composer displays @path and serializes file references as quoted literals such as @"docs/report.md".
Quoted file literals never mention participants, including when a filename or directory matches a member name.
Unavailable sources return file_reference_unavailable without creating a partial message.
A completed retry with the same sender and client_message_id returns the saved message without reopening source files.
The chat sidebar reuses the room attachment listing and download routes. Attachment lists require the existing server, Desktop session, or scoped Agent credential. A live attachment download also accepts that attachment’s existing download capability, granting no listing or mutation rights. Fetch Metadata is never an authorization credential. The Web UI browses attachment metadata from the existing transcript APIs and uses per-file capabilities for previews and downloads; transcript access policy remains unchanged. External clients and Agents retain their existing token and room-membership checks. Browser requests do not receive the server management token and do not gain deletion permissions.
Local template identity, retained versions, restore endpoints and cloud replacement behavior are described in Local template versions.