Skip to content

Latest commit

 

History

History
562 lines (419 loc) · 21.6 KB

http-api.md

File metadata and controls

562 lines (419 loc) · 21.6 KB
title HTTP API
description A REST + Server-Sent Events API for building external clients — mobile apps, dashboards, integrations.
sidebar
order
3
lazyagent --api

Starts an HTTP API on http://127.0.0.1:7421. If the port is busy the server tries up to 10 sequential ports (7421–7431) and binds to the first available one; the actual address is printed to stderr on startup. Pass --host to pin a custom address and disable the fallback.

lazyagent API playground

Authentication

All data endpoints under /api/* require a Bearer token. The token is derived from a passphrase with PBKDF2-SHA256 plus a public per-install salt. GET /api and GET /api/auth are public so browsers and clients can load the playground and fetch the KDF parameters before deriving the token locally.

First run

lazyagent --api

If no passphrase is configured, lazyagent prompts for one (twice, for confirmation), requires at least 12 characters, saves it to ~/.config/lazyagent/config.json under api_passphrase, and prints the derived bearer token to stderr once for the interactive setup:

API authentication enabled.
Bearer token: zqh9_r0QeYpLiLSQGZMYriIWqNZgZOu3Qc_l7wtraV4
Use header:   Authorization: Bearer <token>

On later startups the token is not printed to avoid leaking it into service logs. Use lazyagent passphrase --show when you explicitly need the raw token.

Non-interactive setup

If --api runs without a TTY (e.g. from launchd, a service, CI), set the passphrase via env var instead:

LAZYAGENT_API_PASSPHRASE='your-passphrase' lazyagent --api

The env var takes precedence over the config file value and is never written to disk.

Rotating the passphrase

lazyagent passphrase             # prompt for a new one and save it
lazyagent passphrase --show      # print the current bearer token without prompting

The passphrase subcommand is independent of the server — change credentials any time. Any running lazyagent --api keeps the old token until you restart it.

Token derivation algorithm

salt        = value from GET /api/auth, also stored as api_salt in config
iterations  = 600_000
hash        = SHA-256
key length  = 32 bytes
encoding    = base64url, no padding  → 43-char token

Test vector — every client implementation must produce this exact value for the sample salt:

Passphrase Salt Bearer token
pippo lazyagent-api-v1 zqh9_r0QeYpLiLSQGZMYriIWqNZgZOu3Qc_l7wtraV4

JavaScript (browser, Web Crypto)

async function getAuthInfo(baseURL = "") {
  const res = await fetch(`${baseURL}/api/auth`);
  return await res.json();
}

async function deriveToken(passphrase, salt) {
  const enc = new TextEncoder();
  const baseKey = await crypto.subtle.importKey(
    "raw", enc.encode(passphrase.trim()), { name: "PBKDF2" }, false, ["deriveBits"]
  );
  const bits = await crypto.subtle.deriveBits(
    { name: "PBKDF2", hash: "SHA-256",
      salt: enc.encode(salt), iterations: 600_000 },
    baseKey, 32 * 8
  );
  const bytes = new Uint8Array(bits);
  let s = ""; for (const b of bytes) s += String.fromCharCode(b);
  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

Swift (iOS, CommonCrypto)

import CommonCrypto

func deriveToken(_ passphrase: String, salt: String) -> String {
    let pp = passphrase.trimmingCharacters(in: .whitespaces)
    let saltBytes = Array(salt.utf8)
    var key = [UInt8](repeating: 0, count: 32)
    _ = pp.withCString { ppPtr in
        CCKeyDerivationPBKDF(
            CCPBKDFAlgorithm(kCCPBKDF2),
            ppPtr, strlen(ppPtr),
            saltBytes, saltBytes.count,
            CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256),
            600_000, &key, 32)
    }
    return Data(key).base64EncodedString()
        .replacingOccurrences(of: "+", with: "-")
        .replacingOccurrences(of: "/", with: "_")
        .replacingOccurrences(of: "=", with: "")
}

Kotlin (Android, javax.crypto)

import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
import android.util.Base64

fun deriveToken(passphrase: String, salt: String): String {
    val spec = PBEKeySpec(
        passphrase.trim().toCharArray(),
        salt.toByteArray(Charsets.UTF_8),
        600_000, 32 * 8)
    val key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
        .generateSecret(spec).encoded
    return Base64.encodeToString(key, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)
}

curl / shell

PASSPHRASE='your-configured-passphrase'
SALT=$(curl -s http://127.0.0.1:7421/api/auth | python3 -c '
import json, sys
print(json.load(sys.stdin)["salt"])')
TOKEN=$(PASSPHRASE="$PASSPHRASE" SALT="$SALT" python3 - <<'PY'
import os, hashlib, base64
salt = os.environ["SALT"].encode()
pp = os.environ["PASSPHRASE"].strip().encode()
key = hashlib.pbkdf2_hmac("sha256", pp, salt, 600_000, dklen=32)
print(base64.urlsafe_b64encode(key).rstrip(b"=").decode())
PY
)

curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:7421/api/sessions

Sending the token

Use case How
Regular fetch / curl Authorization: Bearer <token> header
Browser EventSource (SSE) ?token=<token> query string (header not supported)

The query-string fallback is only accepted on /api/events for SSE clients that cannot set custom headers. Use the Authorization header everywhere else; query strings appear in server logs and shell history.

Interactive playground

Open http://127.0.0.1:7421/api in a browser for the interactive playground. The page prompts for your passphrase, derives the token in-browser using the same PBKDF2 algorithm, and uses it for every subsequent call. Your passphrase never leaves the page; only the derived token is sent to the server.

The playground HTML page itself is unauthenticated so the browser can load it; all data endpoints behind it require the token.

Data freshness

Three mechanisms keep the API current:

  1. File system watcher — detects JSONL changes with a 200 ms debounce.
  2. Activity ticker (1 s) — re-evaluates activity states (idle/thinking/waiting transitions).
  3. Safety reload (30 s) — full rescan as a fallback in case a file event was missed.

SSE clients receive pushes from all three. REST clients see the latest state on each request.

At startup, the API completes its initial discovery before it begins serving requests, so the first REST response and SSE snapshot are complete rather than progressively populated. It still reuses lazyagent's persistent discovery cache to keep that initial scan fast. The cache may contain session metadata and short transcript snippets; see Persistent discovery cache for location, permissions, and cleanup behavior.

Network access

By default the server binds to 127.0.0.1 (localhost only). To expose it on the network — e.g. for a mobile companion app on the same Wi-Fi:

lazyagent --api --host 0.0.0.0:7421

The Bearer-token requirement applies regardless of bind address, but the API is plain HTTP — anyone on the network can read your traffic. For internet-facing exposure put the server behind an HTTPS reverse proxy (nginx, Caddy, Cloudflare Tunnel).

Endpoints

GET /api/sessions

List all visible sessions within the configured time window.

Query parameters (all optional):

Parameter Type Description
search string Filter by project path (case-insensitive substring match)
filter string Filter by activity kind (e.g. thinking, writing, idle)
dir string Filter to sessions whose CWD is this directory or a subdirectory of it — the same matching lazyagent sessions uses. Must be an absolute path (there's no meaningful "current directory" for a remote client). The directory does not need to exist on the machine running the server.

Response: 200 OK

[
  {
    "session_id": "abc123",
    "cwd": "/Users/me/projects/myapp",
    "short_name": "…/projects/myapp",
    "custom_name": "my-api-project",
    "activity": "thinking",
    "is_active": true,
    "model": "claude-sonnet-4-20250514",
    "git_branch": "main",
    "cost_usd": 0.42,
    "last_activity": "2026-03-08T15:30:00Z",
    "total_messages": 24
  }
]

Possible activity values: idle, waiting, thinking, compacting, reading, writing, running, searching, browsing, spawning. See Activity states for meanings.

Example — sessions under one project:

curl -H "Authorization: Bearer $TOKEN" \
  "http://127.0.0.1:7421/api/sessions?dir=/Users/me/projects/myapp"

Response: 400 Bad Request — dir is not an absolute path:

{ "error": "dir must be an absolute path" }

GET /api/sessions/{id}

Full details for a single session.

Response: 200 OK

{
  "session_id": "abc123",
  "cwd": "/Users/me/projects/myapp",
  "short_name": "…/projects/myapp",
  "custom_name": "my-api-project",
  "activity": "writing",
  "is_active": true,
  "model": "claude-sonnet-4-20250514",
  "git_branch": "feature/api",
  "cost_usd": 1.23,
  "last_activity": "2026-03-08T15:30:00Z",
  "total_messages": 48,
  "version": "1.0.33",
  "is_worktree": false,
  "main_repo": "",
  "input_tokens": 125000,
  "output_tokens": 42000,
  "cache_creation_tokens": 50000,
  "cache_read_tokens": 80000,
  "user_messages": 20,
  "assistant_messages": 28,
  "current_tool": "Edit",
  "last_file_write": "internal/api/server.go",
  "last_file_write_at": "2026-03-08T15:29:50Z",
  "recent_tools": [
    {"name": "Read", "timestamp": "2026-03-08T15:29:30Z"},
    {"name": "Edit", "timestamp": "2026-03-08T15:29:50Z"}
  ],
  "recent_messages": [
    {"role": "user", "text": "Add the API endpoint", "timestamp": "2026-03-08T15:28:00Z"},
    {"role": "assistant", "text": "I'll create the endpoint...", "timestamp": "2026-03-08T15:28:05Z"}
  ],
  "resume_command": "claude --resume abc123",
  "resume_command_yolo": "claude --dangerously-skip-permissions --resume abc123"
}

resume_command remains the normal, backward-compatible command. resume_command_yolo contains the agent-specific permissive variant and is omitted when the agent has no distinct YOLO mode, as with pi.

The timestamp field in recent_tools and recent_messages is optional and omitted when the time is unknown. Agents such as Grok record no per-item timestamp in their transcripts; only the most recent tool call and the most recent message carry a timestamp (the session's last-activity time — the best available).

Returns 404 Not Found if the session doesn't exist.

PUT /api/sessions/{id}/name

Set a custom name for a session. Names are persisted in ~/.config/lazyagent/session-names.json and shared across TUI, GUI, and API in real time.

Request body:

{ "name": "my-api-project" }

An empty "name" resets to the default path-based label.

Response: 200 OK

{ "session_id": "abc123", "custom_name": "my-api-project" }

Triggers an SSE update event to all connected clients.

DELETE /api/sessions/{id}/name

Remove the custom name (reset to default).

Response: 200 OK

{ "session_id": "abc123", "custom_name": "" }

Also triggers an SSE update.

GET /api/agents

IDE chats and Cursor cloud agents in one list, with a shared status. Idle agents are omitted unless ?all=true.

Cloud agents need a saved Cursor API key or the LAZYAGENT_CURSOR_API_KEY environment override. Without either, only IDE chats are returned. All Cursor list pages are read before idle agents are filtered out, so an active agent beyond the first 100 is still included.

Cursor cloud agent setup

  1. Sign in to Cursor Dashboard → API Keys and create a user API key for the Cloud Agents API. See Cursor's API key documentation.

  2. Save it once using the hidden prompt:

    lazyagent credentials set cursor

    This writes providers.cursor.api_key to credentials.json beside lazyagent's config.json. The file has 0600 permissions and the directory has 0700 permissions. All interfaces read this shared location. You can also save the key in GUI Settings under Cursor cloud agents; the saved value is never returned to the frontend.

  3. Start or restart the API:

    lazyagent --api
  4. Query GET /api/agents using your usual lazyagent bearer token. Add ?all=true to include idle cloud agents, and check errors for failed or pending cloud lookups.

The Cursor key authenticates lazyagent to Cursor. The API passphrase authenticates your clients to lazyagent; configure it separately.

Check the active source or remove the saved key without printing its value:

lazyagent credentials status cursor
lazyagent credentials remove cursor

For temporary overrides or a secret-manager deployment, the existing environment variable still works and takes precedence over the saved key:

LAZYAGENT_CURSOR_API_KEY='YOUR_CURSOR_API_KEY' lazyagent --api

Environment overrides are not copied into credentials.json. Removing a saved key does not unset an environment override. The key is resolved when the API server is created; restart it after setting, rotating, or removing credentials. GUI Settings updates its own monitor immediately.

Services, login items, and separately launched desktop processes can use the saved credential when running as the same user with the same config directory. See Provider API credentials for paths and the extensible file format. There is no key field in ordinary config.json.

Cloud agents also appear in the TUI and both GUI layouts when Cursor is among the enabled providers. Demo mode and other-agent-only monitors stay local. /api/sessions and maintenance commands continue to operate on local sessions. Local Cursor discovery needs no cloud API key.

Cloud caching and errors

Cloud results are cached for 30 seconds; failures and partial results are cached for 5 seconds. Repository metadata is taken from list items when available, otherwise loaded from each agent's detail endpoint and cached for 5 minutes. The cloud repo field contains the first repository URL and is omitted for agents without a repository.

Cloud url values are restricted to HTTPS agent pages on cursor.com. Missing or invalid upstream URLs fall back to https://cursor.com/agents/<escaped-id>, matching the TUI and GUI actions.

A request waits at most 10 seconds for cloud data. A slower refresh continues in the background, shared by all callers, with a 2-minute deadline and a 30-second timeout per upstream request. Until it finishes, the API returns available IDE agents and the last cloud snapshot, with refresh in progress; cloud results may be incomplete in errors. When the refresh finishes, later polls receive the result.

If a page or repository lookup fails, available IDE and cloud agents are still returned alongside an entry in errors. A failed repository lookup leaves repo absent, or keeps its last cached value if available. Check errors before treating the result as complete.

Response: 200 OK

{
  "agents": [
    {
      "id": "bc-1",
      "source": "cloud",
      "agent": "cursor",
      "name": "cloud run",
      "status": "working",
      "repo": "https://github.com/o/r",
      "url": "https://cursor.com/agents/bc-1",
      "updated_at": "2026-11-03T20:00:00Z"
    }
  ],
  "errors": []
}

source is ide or cloud. status is working, needs_you or idle (IDE waiting maps to needs_you). errors lists sources that failed, such as cloud: list cursor agents: cursor api returned 401, so an empty agents list can be told apart from a broken lookup.

GET /api/stats

Summary statistics.

Response: 200 OK

{
  "total_sessions": 5,
  "active_sessions": 2,
  "window_minutes": 30
}

GET /api/auth

Public KDF metadata needed to derive the Bearer token from a passphrase. This endpoint is intentionally unauthenticated; the salt is public and not a secret.

Response: 200 OK

{
  "salt": "lazyagent-api-v1-2CwLr3D6GKbVv5m0Pu1nHQ",
  "iterations": 600000,
  "key_length": 32,
  "hash": "SHA-256",
  "encoding": "base64url-no-padding"
}

GET /api/config

Current lazyagent configuration. The api_passphrase and api_salt fields are omitted from this response; use GET /api/auth for public auth metadata. The server never echoes the passphrase back to clients, even authenticated ones.

Response: 200 OK

{
  "window_minutes": 30,
  "default_filter": "",
  "editor": "",
  "launch_at_login": false,
  "notifications": false,
  "notify_after_sec": 30
}

GET /api/limits

Rate-limit usage, banked limit resets, and extra credits for Claude Code, Codex, Grok, Kimi, and Cursor. The body is the same document lazyagent limits --json prints, field for field; see JSON output for every key.

Query Description
agent claude, codex, grok, kimi, cursor, or all (default). Case-insensitive.

Response: 200 OK (abridged)

{
  "generated_at": "2026-11-11T10:30:00Z",
  "reports": [
    {
      "agent": "claude",
      "provider": "Claude Code",
      "windows": [
        { "label": "7-day", "scope": "", "used_percent": 14, "resets_at": "2026-11-15T09:00:00Z", "reset_in_seconds": 340200 },
        { "label": "7-day", "scope": "Fable", "used_percent": 18, "detail": "9% of the weekly limit used, capped at 50%" }
      ],
      "resets": [
        { "label": "One full limit reset (November 2026)", "left": 1, "total": 1, "usable": true, "expires_at": "2026-12-10T22:00:00Z" }
      ],
      "credits": [
        { "label": "Extra usage", "unit": "EUR", "enabled": false, "status": "set by your organization" }
      ]
    }
  ],
  "errors": [
    { "agent": "cursor", "kind": "not_installed", "message": "..." }
  ]
}

A failing provider never fails the request: it appears in errors with kind set to not_installed, unavailable, or error, and the other providers are still reported. An unknown agent returns 400 with {"error": "..."}.

Rate limit toward the providers. The providers' usage endpoints are undocumented and answer sustained polling with 429, so the API never queries them more than once every 120 seconds, however often clients call it and whichever agent they pass. One provider round answers every selector until it is 120 seconds old; the next request after that runs a new round, and requests that arrive while it runs wait for it (up to 30 seconds). The Age header gives the age of that round in seconds. generated_at and the countdown fields (reset_in_seconds, expires_in_seconds, next_available_in_seconds) are computed on every request, so they stay accurate between rounds. Polling more often than every two minutes returns the same provider data. lazyagent only reads these endpoints and never redeems a reset.

GET /api/events

Server-Sent Events stream for real-time updates. The server pushes an update event whenever session data changes (file-watcher trigger, activity-state transition, periodic reload). An initial snapshot is sent immediately on connection.

Event format:

event: update
data: {"sessions":[...],"stats":{"total_sessions":5,"active_sessions":2,"window_minutes":30}}

The data JSON contains:

Field Type Description
sessions SessionItem[] Same shape as GET /api/sessions
stats StatsResponse Same shape as GET /api/stats

Client examples

Browser JavaScript

// EventSource cannot set headers — pass the token in the query string.
const { salt } = await getAuthInfo('http://127.0.0.1:7421');
const token = await deriveToken(passphrase, salt);   // see "Token derivation algorithm"
const evtSource = new EventSource(
  `http://127.0.0.1:7421/api/events?token=${encodeURIComponent(token)}`
);

evtSource.addEventListener('update', (e) => {
  const { sessions, stats } = JSON.parse(e.data);
  console.log(`${stats.active_sessions} active sessions`);
  sessions.forEach(s => console.log(`${s.short_name}: ${s.activity}`));
});

// Other endpoints use the standard Authorization header:
const res = await fetch('http://127.0.0.1:7421/api/sessions', {
  headers: { 'Authorization': `Bearer ${token}` }
});

React Native

import EventSource from 'react-native-sse';

const auth = await fetch('http://YOUR_HOST:7421/api/auth').then(r => r.json());
const salt = auth.salt;
const token = await deriveToken(passphrase, salt);   // see "Token derivation algorithm"

// react-native-sse supports Authorization headers natively.
const es = new EventSource('http://YOUR_HOST:7421/api/events', {
  headers: { Authorization: `Bearer ${token}` }
});

es.addEventListener('update', (event) => {
  const { sessions, stats } = JSON.parse(event.data);
  setSessions(sessions);
  setStats(stats);
});

// Cleanup
es.close();

Both examples rely on standard SSE auto-reconnect behavior — if the server restarts, the client reconnects and receives a fresh snapshot.