Documentation

API And Events

AgentHub public contracts are split into REST APIs, WebSocket events, runtime adapter events, and IM integration events. This page describes the intended boundaries; complete OpenAPI specs, event schemas, and SDK packages are still in development.

Development status

This page is not a complete API reference. Hub / Edge APIs and event schemas are evolving with the implementation. Before public integration, use the OpenAPI specs, event docs, and release notes in the owning repositories.

Contract Layers

LayerAudiencePurposeStatus
Hub APIWeb, Desktop, IM GatewaySessions, projects, devices, tasks, permissions, auditIn development
Edge APIDesktop, Hub, operator toolsWorkspace, run lifecycle, runtime adapters, artifacts, diff, previewIn development
WebSocket EventsWeb, Desktop, HubRun progress, message deltas, diff, approval, state changesIn development
Runtime Adapter EventsEdge internalsNormalized events for Claude Code, Codex, OpenCode, and custom runtimesContract shaped
IM Integration EventsFeishu/Lark GatewayMessage events, card actions, binding stateIn development

The owning source for protocol details is the AgentHub repository api/ directory. This public site keeps the reader-facing map: what each layer is for, which side owns it, and what should not cross the boundary.

Stability Matrix

AreaCurrent stabilityYou can rely onDo not rely on
Public site health/statsLive entry, fields follow implementationPublic pages, discovery files, low-risk health/status semanticsPrivate ops fields, admin routes, unauthorized audit
Hub client APIIn developmentTokenDance ID -> Hub session -> product authorization boundaryPaths or fields outside published OpenAPI
Edge loopback APIIn development, usable for local previewhealth, run, event, workspace allowlist, runtime profile semanticsFixed port, fixed token transport, undeclared fields
WebSocket eventsIn developmentevent envelope, run lifecycle, error-code directionUnversioned payload internals
Runtime adapter contractContract shapedNormalized message/tool/diff/artifact/approval/failure semanticsStable import path or third-party SDK submission process
Feishu/Lark eventsIn developmentim.message.receive_v1, card.action.trigger, 3-second ack, async queueFeishu OAuth as product login or full context in card payloads

Last public verification date: 2026-06-09. If the AgentHub repository OpenAPI or event schema conflicts with this page, treat the owning repository schema as authoritative and update this page in the same pass.

Hub API

Hub API owns collaboration and permission boundaries. Typical resources include:

  • sessions: user sessions, Hub sessions, and low-risk personalization state.
  • projects: team projects, workspace links, visibility, and membership.
  • devices: Desktop / Edge device registration, presence, and routing targets.
  • tasks: work requests from Web, Desktop, or IM.
  • runs: agent execution instances and run state.
  • audit: important actions, approvals, failures, and authorization decisions.

Hub API should not expose model API keys, and Web clients must not bypass Hub to operate local workspaces directly.

Expected Hub API groups:

GroupTypical pathsNotes
Authentication/client/auth/*TokenDance ID relying-party flow and Hub-local session issuance
Sessions/client/sessions, /client/sessions/{id}Web/Desktop collaboration state
Messages/client/sessions/{id}/messagesUser and agent conversation records
Agent tasks/web/agent-tasksHub-owned task creation for Web and collaboration surfaces
Agent profiles/client/agents, /client/sessions/{id}/agentsRuntime/profile inventory and per-session agent instances
Devices and targetsdevice registration, target routing endpointsUsed when Hub chooses which Edge may receive work
Audit and statuspublic stats, health, audit/event endpointsPublic stats can be exposed; sensitive audit stays authorized

Public examples should use placeholder hosts and tokens. Do not copy production admin keys, JWTs, or private callback payloads into docs.

The minimum request shape looks like this. Paths and fields remain in preview until the public OpenAPI is stable:

http
GET /client/sessions HTTP/1.1
Host: hub.example.invalid
Authorization: Bearer <agenthub_session_token>
Accept: application/json
JSON
{
  "items": [
    {
      "id": "session_123",
      "projectId": "project_123",
      "title": "Local review",
      "state": "active",
      "updatedAt": "2026-06-09T00:00:00Z"
    }
  ],
  "nextCursor": null
}

Edge API

Edge API owns the local execution boundary. Typical capabilities include:

  • list and select workspaces;
  • start, cancel, and inspect runs;
  • read run events, artifacts, diffs, and previews;
  • manage runtime adapter presets;
  • perform local health checks.

Edge sits close to the filesystem and process boundary, so it should default to conservative behavior: least privilege, workspace allowlist, explicit approval, and auditable events.

Expected Local Edge groups:

GroupTypical pathsNotes
Health/health, /v1/healthConfirms process, runtime, and local readiness
Runtime inventory/v1/agents, /v1/runnersLists real runtime adapters and compatibility runner presets
Runs/v1/runs, /v1/runs/{id}Starts and inspects local execution
Events/v1/eventsWebSocket stream for run events and replay
Permissions/v1/permissions/decideLocal approval bridge for runtime actions
Artifacts and previewsrun artifact, diff, file, preview endpointsLocal-only, workspace-scoped data

Browser WebSocket clients cannot reliably set custom headers, so a local Edge token may be passed during WebSocket upgrade using a query parameter. This protects only the loopback Edge process; Hub/Remote/Cloud routing still requires Hub-issued sessions, target authorization, and audit.

Preview example for creating a Local Edge run:

http
POST /v1/runs HTTP/1.1
Host: 127.0.0.1:3210
Content-Type: application/json
Authorization: Bearer <local_edge_token>
JSON
{
  "workspace": "workspace_123",
  "agentId": "codex-local",
  "input": {
    "text": "Review README and suggest one documentation improvement."
  },
  "mode": "read_only"
}

Example WebSocket event stream:

Text
ws://127.0.0.1:3210/v1/events?runId=run_123&token=<local_edge_token>

WebSocket Events

WebSocket events stream execution progress to Desktop/Web:

EventMeaning
run.startedRun created and started
run.message.deltaAgent message delta
run.tool.callAgent requested a tool call
run.tool.resultTool call result
run.diff.readyReviewable diff generated
run.artifact.readyFile, report, or preview artifact available
run.approval.requestedUser confirmation required
run.completedRun completed
run.failedRun failed

Fields should remain versionable. Clients must not depend on undeclared internal fields.

Event Vocabulary

Use this vocabulary across API docs, runtime adapters, Desktop/Web rendering, search terms, and release notes. Do not mix bare names such as message.delta with run-scoped names.

FamilyCanonical namesNotes
Lifecyclerun.created, run.started, run.completed, run.failed, run.cancelledDrives timeline state and terminal status
Messagerun.message.delta, run.message.completedStreams assistant/user-visible transcript text
Toolrun.tool.call, run.tool.resultDescribes normalized runtime tool activity
File and diffrun.file.read, run.file.changed, run.diff.ready, run.patch.proposedPaths must be relative to the allowed workspace
Artifact and previewrun.artifact.ready, run.preview.readyLinks generated reports, screenshots, previews, or docs
Approvalrun.approval.requested, run.approval.resolvedPauses risky write, shell, network, publish, or deploy actions
Runtime failureruntime.unavailable, runtime.timeout, schema.validation_failedStable failure codes for triage and UI recovery
Integrationintegration.message.received, integration.card.action, identity.binding.requiredGateway-to-Hub normalized events; raw Feishu/Lark names stay in gateway logs

Event Envelope

Every event should be easy for Desktop/Web to render and easy for audit code to store. Keep a stable envelope and version the payload:

FieldMeaning
idStable event id or sequence-backed id
seqMonotonic sequence within a stream where available
typeEvent type, for example run.tool.call
runIdRun that produced the event
sessionIdHub session or local thread when applicable
agentIdRuntime adapter or Hub agent instance when known
createdAtTimestamp generated by the owning service
payloadVersionable event-specific body

Recommended client behavior:

  • ignore unknown event types while preserving them in logs;
  • deduplicate by id or seq;
  • render partial events as progressive state, not final truth;
  • keep raw event details out of public screenshots when they contain paths, prompts, or model output that should stay private.

Example event:

JSON
{
  "id": "evt_001",
  "seq": 1,
  "type": "run.tool.call",
  "runId": "run_123",
  "sessionId": "session_123",
  "agentId": "codex-local",
  "createdAt": "2026-06-09T00:00:00Z",
  "payload": {
    "tool": "read_file",
    "label": "Read README",
    "status": "started"
  }
}

Runtime Adapter Events

Runtime adapters normalize CLI/runtime output. Claude Code NDJSON, Codex JSONL/event streams, and OpenCode JSON events should all become AgentHub events.

An adapter should at least express:

  • run start, completion, and failure;
  • model messages and deltas;
  • tool calls and tool results;
  • file changes, diffs, and artifacts;
  • states that require approval or additional input.

Runtime adapter events should use the run-scoped vocabulary above when describing runtime output: text deltas, tool calls, tool results, file changes, permission requests, session initialization, and final results. Adapter-specific raw messages may be attached for debugging only when they do not expose secrets.

IM Integration Events

Feishu/Lark integration events are handled by Integration Gateway and converted into Hub tasks or actions. Current focus:

  • im.message.receive_v1: direct message or group @mention to the bot.
  • card.action.trigger: interactive card action callback.
  • TokenDance ID binding state updates.

These events must be acknowledged quickly, slow work must be queued asynchronously, and secrets or full workspace context must not be placed in card payloads.

Error Shape

REST APIs should return a predictable error shape so Web/Desktop can show recoverable failures without parsing logs:

FieldMeaning
codeStable machine-readable error code
messageShort user-facing message
requestIdCorrelation id for logs and support
detailsOptional structured details safe for the caller

Use specific codes for expected states: invalid agent id, unauthorized target, workspace outside allowlist, permission denied, runtime unavailable, timeout, cancellation, and schema validation failure.

Recommended error codes:

CodeHTTPScenario
invalid_agent_id400Requested agent/profile does not exist
unauthorized_target403Hub does not allow this session to route to the target Edge
workspace_outside_allowlist403Workspace is outside the Edge allowlist
permission_denied403User or policy denied write, shell, network, or another action
runtime_unavailable503Runtime CLI is missing, unauthenticated, or adapter is unavailable
run_timeout504Run exceeded the configured timeout
run_cancelled409Run was cancelled by the user or system
schema_validation_failed422Request or event payload failed schema validation

Authorization Matrix

The contract should make the authorization boundary explicit before a handler starts work.

ActionRequired authorityRejection should look like
Read public docs/statusPublic siteStatic 404 or public-safe error
Open Hub Web sessionTokenDance ID subject + Hub product sessionunauthorized or login redirect boundary
Read project/session/taskHub project membershippermission_denied with request id
Route a task to an EdgeHub target authorization + Edge presenceunauthorized_target or target_offline
Read workspace file previewEdge workspace allowlist + product authorization when remoteworkspace_outside_allowlist
Start a runtime runEdge policy + runtime profile availabilityruntime_unavailable or permission_denied
Apply file writes or shell commandsExplicit user approval or policy grantapproval_rejected or permission_denied
Create Feishu/Lark taskVerified Integration Gateway event + TokenDance ID bindingbinding_required or permission_denied

Do not reuse TokenDance API keys for these product actions. TokenDance API keys authenticate model API calls through TokenDance Gateway; AgentHub product actions require TokenDance ID and Hub/Edge authorization.

Pagination And Idempotency

Hub APIs that list sessions, projects, tasks, runs, audit events, or messages should support cursor pagination. Public docs should not promise offset pagination unless the owning OpenAPI says so.

Recommended list shape:

JSON
{
  "items": [],
  "nextCursor": null,
  "requestId": "req_123"
}

Write endpoints that can be retried by Web, Desktop, Hub, or Integration Gateway should accept an idempotency key, or derive one from the upstream event id. This matters most for IM card actions, task creation, run creation, approval actions, and artifact publication.

Compatibility Checklist

Before treating an API or event group as stable, verify:

  1. English and Chinese docs describe the same status and boundary.
  2. OpenAPI or event schema exists in the owning AgentHub repository.
  3. Desktop/Web render unknown fields safely.
  4. Error codes cover unauthorized target, workspace allowlist, runtime unavailable, timeout, cancellation, and schema validation.
  5. Request and event examples use placeholder hosts, placeholder tokens, and redacted paths.
  6. Search index, sidebar TOC, llms.txt, sitemap, FAQ, and changelog mention the contract where relevant.

Security Boundary

  • TokenDance ID authenticates the user; Hub issues and validates AgentHub product sessions.
  • TokenDance API keys authenticate model API calls. They are not AgentHub browser login credentials.
  • Web is Hub-only and must not call Local Edge directly.
  • Desktop may call Local Edge on loopback for local execution.
  • Edge may touch local files only inside allowlisted workspaces.
  • Feishu/Lark events must resolve account binding through TokenDance ID before becoming Hub tasks.

Versioning

  • REST APIs should be governed by OpenAPI.
  • WebSocket events should have versionable schemas.
  • Runtime adapter contract changes must be synchronized with Desktop/Web rendering and audit logic.
  • Until a public SDK package is released, examples in docs are architectural guidance and do not promise stable import paths.

Schema Sources

Use this page as the public reading guide. For implementation work, consult these source-of-truth files in the AgentHub repository:

SourcePurposePublic link
api/openapi.yamlREST resource and schema contractGitHub
api/events.mdWebSocket and runtime event vocabularyGitHub
api/conventions.mdNaming, pagination, error, and compatibility conventionsGitHub
edge-server/README.mdLocal Edge runtime and loopback API boundaryGitHub
app/desktop/README.mdDesktop-to-Edge expectationsGitHub
app/web/README.mdWeb-to-Hub expectationsGitHub