Skip to content

Latest commit

 

History

History
631 lines (485 loc) · 15.3 KB

File metadata and controls

631 lines (485 loc) · 15.3 KB

Duragent API Reference

This document describes Duragent's HTTP API and CLI commands.

Core Gateways

Duragent provides built-in gateways for communication:

Gateway Use Case Protocol
CLI/TUI Local development, interactive sessions Terminal
HTTP REST Programmatic access, webhooks HTTP
SSE LLM token streaming HTTP

Platform integrations (Telegram, Discord, Slack) are handled via gateway plugins. See Architecture for details.

# duragent.yaml
gateways:
  http:
    enabled: true
    port: 8080

  cli:
    enabled: true

  external:
    - name: telegram
      command: duragent-gateway-telegram
      config:
        bot_token: ${TELEGRAM_BOT_TOKEN}

Response Format

Success Responses

Success responses return the data directly as JSON:

{
  "session_id": "session_abc123",
  "agent": "my-assistant",
  "status": "active",
  "created_at": "2025-01-24T10:00:00Z"
}

Error Responses (RFC 7807)

Errors use the RFC 7807 Problem Details format with Content-Type: application/problem+json:

{
  "type": "urn:duragent:problem:not-found",
  "title": "Not Found",
  "status": 404,
  "detail": "Agent 'my-agent' not found"
}

Standard problem types:

  • urn:duragent:problem:bad-request (400)
  • urn:duragent:problem:not-found (404)
  • urn:duragent:problem:internal-error (500)

Public API (Agent Interaction)

Agents

GET    /api/v1/agents                         # List loaded agents
GET    /api/v1/agents/{name}                  # Get agent info
GET    /api/v1/agents/{name}/spec             # Get agent spec (YAML)

Sessions

Sessions are durable conversation contexts that survive crashes, restarts, and disconnects.

GET    /api/v1/sessions                       # List all sessions
POST   /api/v1/sessions                       # Create new session
GET    /api/v1/sessions/{session_id}          # Get session details
DELETE /api/v1/sessions/{session_id}          # End session (archives state)

GET    /api/v1/sessions/{session_id}/messages # Get message history
POST   /api/v1/sessions/{session_id}/messages # Send message to session
POST   /api/v1/sessions/{session_id}/stream   # SSE stream for session

POST   /api/v1/sessions/{session_id}/attach   # Attach to session
POST   /api/v1/sessions/{session_id}/detach   # Detach from session
POST   /api/v1/sessions/{session_id}/cancel   # Cancel current execution

Session Behavior on Disconnect

Sessions follow tmux-like semantics: disconnection does not stop the session. The agent's behavior on disconnect is configurable:

Mode Behavior Use Case
continue Agent keeps executing, buffers output Async workflows, supervisor agents
pause Agent pauses at next safe point, waits for reconnect Interactive chat
# agent.yaml
session:
  on_disconnect: continue  # or: pause (default: continue)
  max_background_runtime: 30m  # Safety limit for background execution
  output_buffer_size: 1000  # Max messages to buffer while disconnected

Continue mode (default for supervisor agents):

User: "Refactor auth module and create PR when done"
Agent: [starts working]
      │
   [user disconnects - closes laptop, network drops, etc.]
      │
      ▼
Agent: [continues executing, buffers output]
Agent: [completes task, creates PR]
Agent: [sends notification via webhook/slack]
      │
      ... hours later ...
      │
User reconnects → sees full history and results

Pause mode (default for interactive agents):

User: "Help me debug this function"
Agent: [starts analyzing]
      │
   [user disconnects]
      │
      ▼
Agent: [pauses at next safe point]
Agent: [state persisted, waiting]
      │
      ... later ...
      │
User reconnects → agent resumes from pause point

Session States

State Description
active Session running, client attached
running Session running, client disconnected (continue mode)
paused Session paused, waiting for reconnect (pause mode)
ended Session completed or explicitly ended

Health

GET    /livez                                 # Liveness check
GET    /readyz                                # Readiness check
GET    /health                                # Combined health
GET    /version                               # Version info

Admin API (Agent Management)

Used by orchestrators (systems built on top of Duragent) to deploy and manage agents.

Authentication

# duragent.yaml
admin:
  enabled: true
  token: ${DURAGENT_ADMIN_TOKEN}  # Required for /api/v1/admin/* endpoints

Endpoints

# Agent Deployment
POST   /api/v1/admin/agents                   # Deploy agent (create/update)
DELETE /api/v1/admin/agents/{name}            # Remove agent
POST   /api/v1/admin/reload                   # Reload all agents from disk

# Export/Import
GET    /api/v1/admin/agents/{name}/export     # Export agent package
POST   /api/v1/admin/agents/import            # Import agent package

# Gateway Plugins
GET    /api/v1/admin/gateways                 # List gateway plugins
POST   /api/v1/admin/gateways/{name}/restart  # Restart gateway plugin

# Webhooks
POST   /api/v1/admin/webhooks                 # Register webhook
GET    /api/v1/admin/webhooks                 # List webhooks
DELETE /api/v1/admin/webhooks/{id}            # Remove webhook

SSE Streaming

SSE (Server-Sent Events) is used for streaming agent responses.

Connection

# Send a message and stream the response
curl -N -X POST http://localhost:8080/api/v1/sessions/{session_id}/stream \
  -H "Content-Type: application/json" \
  -d '{"content": "Your message here"}'

Request body:

  • content (required): The user message to send

Event Types

token — Partial response token

event: token
data: {"content": "Hello"}

done — Stream completed with usage statistics

event: done
data: {"usage": {"prompt_tokens": 10, "completion_tokens": 8, "total_tokens": 18}}

error — Error occurred

event: error
data: {"message": "LLM request failed: ..."}

Note: Additional event types (start, tool_call, tool_result) are planned for future versions when tool support is added.

Cancellation

To cancel an in-progress execution:

curl -X POST http://localhost:8080/api/v1/sessions/{session_id}/cancel

The SSE stream will emit a final event:

event: done
data: {"finish_reason": "cancelled"}

Examples

Deploy Agent via Admin API

curl -X POST http://localhost:8080/api/v1/admin/agents \
  -H "Authorization: Bearer ${DURAGENT_ADMIN_TOKEN}" \
  -H "Content-Type: application/yaml" \
  -d '
apiVersion: duragent/v1alpha1
kind: Agent
metadata:
  name: user_12345
spec:
  model:
    provider: openrouter
    name: anthropic/claude-sonnet-4
  session:
    on_disconnect: continue
  system_prompt: |
    You are a helpful assistant.
'

# Response (200 OK)
{
  "agent": "user_12345",
  "action": "created"
}

Create and Use a Session

# Create a new session
curl -X POST http://localhost:8080/api/v1/sessions \
  -H "Content-Type: application/json" \
  -d '{
    "agent": "my-assistant"
  }'

# Response (200 OK)
{
  "session_id": "session_abc123",
  "agent": "my-assistant",
  "status": "active",
  "created_at": "2025-01-24T10:00:00Z"
}

# Get session details
curl http://localhost:8080/api/v1/sessions/session_abc123

# Response (200 OK)
{
  "session_id": "session_abc123",
  "agent": "my-assistant",
  "status": "active",
  "created_at": "2025-01-24T10:00:00Z",
  "updated_at": "2025-01-24T10:05:00Z"
}

# Send a message to the session
curl -X POST http://localhost:8080/api/v1/sessions/session_abc123/messages \
  -H "Content-Type: application/json" \
  -d '{
    "content": "Hello, how are you?"
  }'

# Response (200 OK)
{
  "message_id": "msg_xyz789",
  "role": "assistant",
  "content": "Hello! I'm doing well, thank you for asking. How can I help you today?"
}

# Error case: Session not found (404)
curl http://localhost:8080/api/v1/sessions/invalid-id

# Response (404 Not Found, Content-Type: application/problem+json)
{
  "type": "urn:duragent:problem:not-found",
  "title": "Not Found",
  "status": 404,
  "detail": "Session not found"
}

Async Workflow (Fire and Forget)

# Create session with continue-on-disconnect
curl -X POST http://localhost:8080/api/v1/sessions \
  -H "Content-Type: application/json" \
  -d '{
    "agent": "code-supervisor"
  }'

# Send task and disconnect
curl -X POST http://localhost:8080/api/v1/sessions/session_abc123/messages \
  -H "Content-Type: application/json" \
  -d '{
    "content": "Implement JWT authentication. Create a PR when done and notify me on Slack."
  }'

# Response confirms task started
{
  "message_id": "msg_xyz789",
  "role": "assistant",
  "content": "I'll implement JWT authentication. This will involve several steps..."
}

# Client can now disconnect — agent continues working
# User receives Slack notification when complete

# Later: check session status
curl http://localhost:8080/api/v1/sessions/session_abc123

# Response shows session details
{
  "session_id": "session_abc123",
  "agent": "code-supervisor",
  "status": "active",
  "created_at": "2025-01-23T14:00:00Z",
  "updated_at": "2025-01-24T11:30:00Z"
}

# Reconnect and see full history
curl http://localhost:8080/api/v1/sessions/session_abc123/messages

Streaming Response (SSE)

curl -N -X POST http://localhost:8080/api/v1/sessions/session_abc123/stream \
  -H "Content-Type: application/json" \
  -d '{"content": "Write a short poem about coding"}'

# SSE events
event: token
data: {"content": "In "}

event: token
data: {"content": "lines "}

event: token
data: {"content": "of "}

event: token
data: {"content": "code..."}

event: done
data: {"usage": {"prompt_tokens": 15, "completion_tokens": 20, "total_tokens": 35}}

List and Manage Sessions

Note: List sessions endpoint (GET /api/v1/sessions) is planned for future versions.

# Get session details
curl http://localhost:8080/api/v1/sessions/session_abc123

# Response (200 OK)
{
  "session_id": "session_abc123",
  "agent": "my-assistant",
  "status": "active",
  "created_at": "2025-01-24T10:00:00Z",
  "updated_at": "2025-01-24T10:05:00Z"
}

# Future endpoints (not yet implemented):
# DELETE /api/v1/sessions/{session_id}  - End session
# POST   /api/v1/sessions/{session_id}/detach - Detach from session
# POST   /api/v1/sessions/{session_id}/attach - Attach to session

CLI

Server Commands

duragent serve

Start the Duragent server.

duragent serve [flags]

Flags:
  -p, --port int          HTTP port (default 8080)
  -a, --agents-dir string Path to agents directory (default ./.duragent/agents/)
  -c, --config string     Path to config file (default duragent.yaml)
      --admin-token       Admin API token (or use DURAGENT_ADMIN_TOKEN env)
      --watch             Watch for agent file changes (default true)

Example:

duragent serve --port 8080 --agents-dir ./agents/

Session Commands

duragent chat

Start an interactive chat session with an agent.

duragent chat [flags]

Flags:
  -a, --agent string      Agent name or path to agent directory
  -s, --session string    Session ID to resume (creates new if omitted)
      --host string       Remote Duragent host (default: local)
      --no-memory         Disable memory for this session

Example:

# Start new session
duragent chat --agent my-assistant

# Resume existing session
duragent chat --agent my-assistant --session session_abc123

duragent attach

Attach to an existing session (like tmux attach).

duragent attach <session_id> [flags]

Flags:
      --host string       Remote Duragent host (default: local)

Example:

# Attach to local session
duragent attach session_abc123

# Attach to remote session
duragent attach session_abc123 --host remote.example.com

When attaching to a session with on_disconnect: continue, you'll see any output that was buffered while you were away.

duragent sessions

List all sessions.

duragent sessions [flags]

Flags:
      --host string       Remote Duragent host (default: local)
      --status string     Filter by status: active, running, paused, ended, all (default: all)
  -o, --output string     Output format: table, json (default: table)

Example:

# List all sessions
duragent sessions

# Output
SESSION ID        AGENT            STATUS     ON_DISCONNECT  UPDATED
session_abc123    my-assistant     active     pause          2 minutes ago
session_def456    code-supervisor  running    continue       30 seconds ago
session_ghi789    helper           paused     pause          3 hours ago

# List only running sessions as JSON
duragent sessions --status running --output json

Agent Commands

duragent run

Run a single prompt and exit.

duragent run [flags] <prompt>

Flags:
  -a, --agent string      Agent name or path to agent directory
  -o, --output string     Output format: text, json (default: text)

Example:

duragent run --agent my-assistant "What is 2+2?"

duragent validate

Validate an agent specification.

duragent validate <agent_dir>

Exit codes:
  0  Valid agent spec
  1  Invalid agent spec (errors printed to stderr)

Example:

duragent validate ./agents/my-assistant/

duragent export

Export an agent package.

duragent export [flags]

Flags:
  -a, --agent string      Agent name or path
  -o, --output string     Output directory or file (.tar.gz)
      --include-sessions  Include session history (default: false)

Example:

# Export to directory
duragent export --agent my-assistant --output ./backup/

# Export as tarball
duragent export --agent my-assistant --output ./backup/my-assistant.tar.gz

duragent import

Import an agent package.

duragent import [flags]

Flags:
  -f, --file string       Path to agent package (directory or .tar.gz)
      --name string       Override agent name

Example:

duragent import --file ./backup/my-assistant.tar.gz

Interactive Commands

Within duragent chat, these commands are available:

Command Description
/help Show available commands
/detach or Ctrl+D Detach from session (agent continues if on_disconnect: continue)
/quit or /exit End session completely
/clear Clear screen
/history Show message history
/memory Show agent memory
/export Export current session
/status Show session status including on_disconnect behavior

Error Codes

Code HTTP Status Description
not_found 404 Resource not found
invalid_request 400 Malformed request
unauthorized 401 Missing or invalid auth
forbidden 403 Insufficient permissions
conflict 409 Resource conflict (e.g., session already attached)
rate_limited 429 Too many requests
internal_error 500 Server error
session_not_found 404 Session does not exist
session_ended 410 Session has been ended
agent_not_found 404 Agent does not exist
agent_error 500 Agent execution error