API Reference
This document describes the HTTP API exposed by the backup dashboard backend server. All API endpoints are mounted under /api unless otherwise stated. The API is built with Fiber and uses PostgreSQL as the persistence layer.
Base URL: http://localhost:8080 (or the configured PORT, falling back to SERVER_PORT)
Contract: one OpenAPI 3.1 file per service describes each of its routes, their parameters, bodies and answers: contracts/openapi/identity.json, contracts/openapi/runs.json, contracts/openapi/insights.json and contracts/openapi/notify.json, with what they share (the health checks, /metrics, the credentials, the error answers and the paging of lists) in contracts/openapi/common.json. A test calls every route and checks the answers against the file of the service that serves it, and CI refuses a breaking change; see contracts/README.md.
Accounts and authentication
Every request acts for one account (one person, keyed by their GitHub user id; account 1 is the deployment owner and holds everything recorded before accounts existed; see MULTI_USER_ARCHITECTURE.md). Every route reads and writes only that account's rows: an id that belongs to another account answers 404 exactly like an id that does not exist.
The caller (the principal) is resolved from these credentials, in this order:
| Credential | Sent as | Principal | Scopes |
|---|---|---|---|
| Service credential (the dashboard's server, the MCP server, the Observatory; ADR 0009) | X-Service-Credential: ghb_svc_.... Each service may call only the operations its policy gives it (routes/service.policy.go), with X-Account-Id never, for the owner only, or required as the policy says: 403 FORBIDDEN for another operation, 403 ACCOUNT_NOT_ALLOWED for a refused account, 400 ACCOUNT_REQUIRED for a missing one | ||
| Internal secret, deprecated (the Observatory, the MCP server, the dashboard's landing page) | X-Internal-Secret: <INTERNAL_SECRET>, or Authorization: Bearer <INTERNAL_SECRET> | internal, acting for the account in X-Account-Id: <id> | read, write |
| Dashboard session (the dashboard's server forwards the user's session) | Authorization: Bearer <JWT> (HS256 with JWT_SECRET, iss/aud github-backup, claims sub, exp, account_id) | session | read, write |
| Personal access token (created in the dashboard, Settings → Tokens) | Authorization: Bearer ghb_pat_… | personal_token | read, or read and write |
| Agent token (issued to a linked worker, see Agents) | Authorization: Bearer ghb_agt_… | agent | agent only |
Nothing, with API_REQUIRE_AUTH=false | owner_legacy: account 1 | read |
- The internal secret wins when several credentials are present, but every presented credential must be valid: an invalid one is
401even when another one would be accepted. Comparisons of the secret are constant-time; tokens are looked up by their SHA-256 and never logged. Credentials in the URL (?token=) are not read. - An internal caller must name the account it acts for with
X-Account-Idon every account-scoped route (400 ACCOUNT_REQUIREDwithout it,404 NOT_FOUNDfor an unknown account,403 ACCOUNT_DISABLEDfor a disabled one). The internal routes take noX-Account-Id. The header is ignored on every request without the secret. - A session whose account no longer exists is
401(sign in again); a session, token or agent of a disabled account403 ACCOUNT_DISABLED; a revoked or expired token401. - Each API process keeps the answer that authenticated a credential for 30 seconds. A token revoked or an agent unlinked through the API, and an account disabled (also directly in the database) or deleted, are refused at once by the process that made the change and within 2 seconds by every other one: each reads identity's revocations at most every 2 seconds while it serves requests. Other changes made in the database directly (scopes, expiry, plan) show within 30 seconds. A token's expiry is exact.
writeimpliesread. A route that needs a scope the principal lacks answers403 FORBIDDENwith"details": {"required_scope": "<scope>"}; a session-only route answers403 FORBIDDENto any other principal.401responses carryWWW-Authenticate: Bearer realm="github-backup-api".API_REQUIRE_AUTHdefaults totrue; the API then refuses to start unlessINTERNAL_SECRETandJWT_SECREThave at least 32 characters.API_REQUIRE_AUTH=false(local development only, logged as a warning) makes a request without credentials the owner, read only, and opens/metrics; presented credentials are still checked./health,/healthz,/readyand/readyzare always public.
The dashboard's browser code never talks to the API: its server-side proxy (/api/proxy/backup/*) and server components forward the signed-in user's session as Authorization: Bearer <JWT> and add no internal secret. The public landing page calls no API.
Who may call what (✓ allowed; R/W: needs the read/write scope):
| Routes | No credentials | Personal token | Agent token | Session | Internal + X-Account-Id | Internal without it |
|---|---|---|---|---|---|---|
Data routes (/api/backups*, /api/dashboard/stats, /api/metrics, /api/logs, /api/logs/stream, /api/repos, /api/repos/:owner/:name/archive, /api/backup-fixes*, /api/backup-runs/:id/fixes, /api/analytics/*), /ws/live, GET /api/me, GET /api/agents | 401 (owner with API_REQUIRE_AUTH=false) | R | 403 | ✓ | ✓ | 400 |
POST /api/requests, POST /api/fixes, PATCH /api/fixes/:id | 401 | W | 403 | ✓ | ✓ | 400 |
/api/tokens*, DELETE /api/agents/:id, /api/agents/link/*, /api/me/research, DELETE /api/me, GET /api/me/export, GET /api/runs/export | 401 | 403 | 403 | ✓ | 403 | 400 |
GET /api/alerts/channels*, GET /api/alerts/rules*, GET /api/alerts/deliveries | 401 | R | 403 | ✓ | 403 | 400 |
POST, PATCH and DELETE of /api/alerts/channels* and /api/alerts/rules* | 401 | W | 403 | ✓ | 403 | 400 |
/api/internal/* | 401 | 403 | 403 | 403 | ✓ | ✓ |
GET /metrics (Prometheus) | 401 (open with API_REQUIRE_AUTH=false) | 403 | 403 | 403 | ✓ | ✓ |
METRICS_TOKEN, sent as Authorization: Bearer, reads GET /metrics and nothing else (401 on every other route), so Prometheus needs no internal secret.
| /v1/runs*, /v1/schedule, /v1/requests/* | 401 | 403 | ✓ | 403 | 403 | 400 |
| /v1/agent/link, /v1/agent/link/token | public | public | public | public | public | public |
The former /api/internal/* duplicates of the data routes were removed; /api/internal/ now holds only the internal account routes.
Rate Limiting
Rate limits run after authentication, so only a verified credential chooses a bucket (an invalid one is answered with 401 first and can neither spend nor reach anyone else's budget). Exceeding a limit returns 429 RATE_LIMITED.
| Caller | Limit | Keyed on |
|---|---|---|
| Session or personal access token | 300 / min | The account (acct:<id>): the dashboard's server calls the API for every signed-in user from its own address |
| Agent token | 600 / min | The agent (agent:<id>) |
| All agent tokens of one account, together | 1200 / min | The account (agents:<id>), on top of each agent's own limit |
| No credentials (and the legacy owner) | 100 / min | Client IP (see below) |
Internal secret with X-Forwarded-For | 300 / min | The forwarded client IP |
Internal secret with an X-Forwarded-For holding no valid address | 300 / min | One shared bucket |
Internal secret without X-Forwarded-For (Observatory, MCP server, landing page) | not limited | - |
POST /api/internal/tokens/resolve (internal secret) | not limited per caller or forwarded address | - (it limits unknown tokens per end client, next row) |
Lookups of unknown ghb_… tokens | 60 / min | Client IP, or for POST /api/internal/tokens/resolve the end client's address in X-Client-Address (a missing or invalid one shares the bucket internal-unknown); both count in one budget per address. Past it the address gets 429 (with Retry-After) for any token, without a lookup, until the minute ends. Revoked or expired tokens, a disabled account's tokens and failed lookups do not count, so one client with a stale token cannot lock out everyone behind the same address |
POST /v1/agent/link | 10 / min | Client IP |
POST /v1/agent/link/token | 60 / min | Client IP (a safety bound: workers poll every 5 s and faster polls get slow_down) |
POST /public/waitlist | 30 / min | Client IP |
POST /api/alerts/channels/:id/test | 5 per 10 min | The account |
Every 429 carries Retry-After (seconds). Each API process counts on its own (RATELIMIT_BACKEND=memory, the default), so N processes allow every limit N times; RATELIMIT_BACKEND=postgres or valkey (with CACHE_URL) gives all of them one count. When that store fails or takes more than 500 ms, each process counts on its own again until it recovers, and the API logs a warning (at most once a minute per limit).
The client IP is the connection's peer address unless the peer is listed in TRUSTED_PROXIES (comma-separated IPs or CIDRs, default none). Then the TRUST_PROXY_HEADER header (default X-Forwarded-For) is read from the right and the first address that is not a trusted proxy is used, so a client cannot choose its bucket by adding entries to the header. The self-hosted stack sets it to its Docker network (GHB_SUBNET), where Caddy connects from. The MCP server resolves its clients' addresses the same way (src/platform/clientip).
Beyond the rate limits, /api sheds load: at most 4 requests per pooled database connection (DB_MAX_CONNS, so 40 by default) run at once, the next one waits up to 2 seconds for a slot, and then gets 503 SERVICE_BUSY with Retry-After: 2. The live log stream (/api/logs/stream) is not counted.
A refused token's 401 names the reason in error.details.reason: unknown, revoked or expired. The MCP server reads it to count only unknown tokens against its clients. With INTERNAL_SECRET it verifies its clients' tokens on POST /api/internal/tokens/resolve, so the API counts each client's unknown tokens against that client rather than against the MCP server's one address.
Request IDs
Every response carries X-Request-ID. A client-supplied X-Request-ID is kept when it matches [A-Za-z0-9._-]{1,64}; otherwise a random ID is generated. The ID appears in every log line of the request and in error bodies.
Paging
The lists (GET /api/backups, /api/logs, /api/analytics/history, /api/backup-fixes, /api/alerts/deliveries) return their rows newest first, a page at a time:
?limitsets the page size: default 50 (100 for fixes), at most 500.?page=Nreaches the first 10,000 rows. A page that starts past them is400 PAGE_TOO_DEEP, because an offset reads every row it skips.pagination.next_cursoris present when more rows follow.?before=<next_cursor>, with the same filters andlimit, fetches the next page at any depth. A cursor is opaque; one the API did not return is400, and so isbeforetogether withpageabove 1.pagination.total_pagesstops at the deepest page?pagereaches.GET /api/backup-fixesanswers with a bare array, so its next cursor is in theX-Next-Cursorheader (exposed to browsers through CORS, likeRetry-After).
Table of Contents
- Backups
- Dashboard & Metrics
- Analytics
- Repositories
- Logs
- Live Log Stream (SSE) and WebSocket
- Account, tokens and backup requests
- Internal account routes
- Agents (linked workers)
- Pre-order waitlist
- Alerts
- Billing
- Vector Embeddings & Hybrid Search
- AI Observatory & Agentic Chat
- Error Handling
- Data Models
All data routes below need a principal with the read scope and answer for its account only (see Accounts and authentication).
Backups
List Backup Runs
Endpoint: GET /api/backups
Retrieve a page of backup runs, newest first (see Paging).
Query Parameters:
| Parameter | Type | Default | Max | Description |
|---|---|---|---|---|
page | integer | 1 | first 10,000 rows | Page number (1-indexed) |
limit | integer | 50 | 500 | Results per page |
before | string | — | — | pagination.next_cursor of the previous page |
status | string | — | — | Only the runs with this status: running, completed or failed (another value: 400 BAD_REQUEST). pagination.total_items counts them alone |
Response: 200 OK
{
"data": [
{
"id": 1,
"started_at": "2024-06-17T10:30:00Z",
"completed_at": "2024-06-17T10:45:30Z",
"status": "completed",
"duration_ms": 870000,
"total_repos": 45,
"successful": 42,
"failed": 2,
"skipped": 1,
"error_message": ""
}
],
"pagination": {
"page": 1,
"limit": 50,
"total_items": 150,
"total_pages": 3,
"next_cursor": "MTcxODYyMDIwMDAwMDAwMC4x"
}
}
Status Values: completed, failed, running (as written by the worker)
Get Latest Backup
Endpoint: GET /api/backups/latest
Retrieve the most recent backup run (by started_at) with its linked fixes. Returns {"run": null} when there are no runs.
Response: 200 OK
{
"run": {
"id": 150,
"started_at": "2024-06-17T10:30:00Z",
"completed_at": "2024-06-17T10:45:30Z",
"status": "completed",
"duration_ms": 870000,
"total_repos": 45,
"successful": 42,
"failed": 2,
"skipped": 1,
"error_message": "",
"fixes": [
{"id": 4, "title": "Raise clone timeout", "commit_hash": "a1b2c3d", "author": "claude", "affected_runs": [149, 150]}
]
}
}
A run left running by a worker that stopped is marked failed with the error worker stopped without finishing by a background job (every 10 minutes, only while the database is in use); reading these endpoints never changes data.
Get Backup Run Details
Endpoint: GET /api/backups/:id
Retrieve detailed information for a specific backup run, including all repository backup results. A non-numeric id returns 400, an unknown one or another account's 404.
Path Parameters:
| Parameter | Type | Description |
|---|---|---|
id | integer | Backup run ID |
Response: 200 OK
{
"run": {
"id": 1,
"started_at": "2024-06-17T10:30:00Z",
"completed_at": "2024-06-17T10:45:30Z",
"status": "completed",
"duration_ms": 870000,
"total_repos": 45,
"successful": 42,
"failed": 2,
"skipped": 1,
"error_message": "",
"telemetry": {
"phases_ms": {"list": 1200, "load_state": 40, "plan": 900, "back_up": 867000},
"reasons": {"unchanged": 41, "pushed": 3, "previous_failed": 1},
"stat_outcomes": {"match": 41}
},
"agent": {"version": "1.4.0", "os": "linux/amd64", "sink": "s3"}
},
"results": [
{
"id": 1,
"run_id": 1,
"repo_full_name": "octocat/Hello-World",
"status": "completed",
"created_at": "2024-06-17T10:30:15Z",
"duration_ms": 5000,
"commit_hash": "abc123def456",
"archive_size_bytes": 1048576,
"error_message": "",
"reason_code": "pushed",
"stat_outcome": null,
"phases_ms": {"clone": 3800, "pack": 900, "upload": 300},
"cloned_bytes": 2310144
},
{
"id": 2,
"run_id": 1,
"repo_full_name": "octocat/Spoon-Knife",
"status": "failed",
"created_at": "2024-06-17T10:32:10Z",
"duration_ms": 3000,
"commit_hash": "",
"archive_size_bytes": 0,
"error_message": "Network timeout during clone"
}
]
}
Missing commit hashes and error messages are returned as empty strings. run.telemetry and run.agent are absent, and a result's reason_code, stat_outcome, phases_ms and cloned_bytes are null, where a worker older than them recorded the run. run.telemetry counts every repository in scope; results has only the repositories the run archived or failed.
Reason codes
Why the worker backed a repository up, or did not; the codes are recorded, so they are never renamed.
| Code | Meaning |
|---|---|
new | No recorded state: first backup |
forced | --force, or a backup request for it |
previous_failed | The previous attempt failed |
relisted | Listed again after GitHub stopped listing it |
no_longer_withheld | Private and withheld before, allowed now |
format_changed | The archive format changed (BACKUP_FORMAT) |
pushed | pushed_at differs from the recorded one |
key_changed | The archive key changed (a rename) |
sink_accepts_large | Too large before, and the sink now has no size limit |
archive_missing, archive_unchecked, archive_differs | Unchanged, but its stored archive was missing, could not be checked or read back, or differed from the recorded one (size or recorded checksum) |
archive_damaged | Unchanged, but its stored archive, read back in full, no longer had the recorded SHA-256 (damaged in place); the run finishes with problems |
unchanged, empty_unchanged, too_large_unchanged | Not backed up: nothing pushed since (and its archive checked) |
disabled | Not backed up: GitHub disabled it |
withheld | Not backed up: private, and the destination is not confirmed private |
over_limit | Not backed up this run: over --limit |
List Backup Fixes
Endpoint: GET /api/backup-fixes
The account's newest fixes, newest first, as an array (default 100, at most 500 with ?limit). When more follow, the X-Next-Cursor header holds the ?before of the next page (see Paging). GET /api/backup-fixes/:id returns one fix and GET /api/backup-runs/:id/fixes the fixes of one run.
{"id": 12, "title": "Raise the clone timeout", "description": "Large repositories need longer clones.", "commit_hash": "deadbeef", "author": "claude", "created_at": "2026-10-15T09:00:00Z", "updated_at": "2026-10-15T09:00:00Z", "affected_runs": [41, 42]}
commit_hash is "" without a commit; affected_runs lists the account's runs the fix addresses, ascending, and is left out when there are none.
Record a Fix
Endpoint: POST /api/fixes (write; served by runs)
Records a fix and the runs it addresses, all or nothing. The dashboard (through the Observatory), the MCP server and the Observatory record fixes here; insights serves them back under /api/backup-fixes.
{"title": "Raise the clone timeout", "description": "Large repositories need longer clones.", "commit_hash": "deadbeef", "affected_run_ids": [41, 42], "author": "claude"}
title: required, 1 to 300 characters, not only white space; stored as sent.description: required, at most 20,000 characters, may be"".commit_hash: 7 to 64 hexadecimal characters;null,""or left out for none.affected_run_ids: at most 500 run ids of the account; duplicates are ignored,nullor left out for none.author: at most 100 characters, stored as sent (""too). Left out ornull, it is the caller: the session's GitHub login,token:<id>for a personal token,service:<name>for a service credential,internalforINTERNAL_SECRET. Who recorded the fix is kept apart from it (recorded_by, the principal as inrequested_by).- Another field, a NUL character or a value of the wrong type:
400 BAD_REQUEST. A body over 256 KiB:413 PAYLOAD_TOO_LARGE.
Response: 201 Created with the fix as GET /api/backup-fixes/:id returns it. A run that does not exist or is another account's: 404 RUN_NOT_FOUND with the missing ids in error.details.run_ids, and nothing is recorded.
Retrying safely: send Idempotency-Key: <1 to 200 printable ASCII characters>, a new one per fix. The account's first request with the key records the fix; the same request again (compared by the SHA-256 of the fix it asks for: its fields after the defaults, the run ids sorted, each once) answers 200 OK with the fix as stored now and Idempotent-Replayed: true, even after one of its runs was deleted; a different request under the same key answers 422 IDEMPOTENCY_KEY_REUSED and records nothing. Two requests racing with one key record one fix. Keys belong to the account: another account may use the same one.
Change a Fix
Endpoint: PATCH /api/fixes/:id (write; served by runs)
Changes the fields the body names, all or nothing; a field left out or null keeps its value, so repeating a change leaves the same fix (only updated_at moves). The fields and their bounds are those of Record a Fix; commit_hash: "" removes the commit and affected_run_ids replaces the fix's runs ([] unlinks them all).
Response: 200 OK with the fix. Another account's fix, or none: 404 NOT_FOUND; a run as above: 404 RUN_NOT_FOUND, and nothing changes.
Dashboard & Metrics
Get Dashboard Statistics
Endpoint: GET /api/dashboard/stats
Retrieve aggregated statistics for the dashboard overview, including totals, success rates, and latest analytics. The totals of ended runs come from the account's rollup (insights.account_rollups), read in one batch with the runs in progress, the last run, the log count and the latest analytics snapshot: one database round trip while the rollup is current, and a recompute that is stored when the account's runs changed since. Totals from results (distinct_repos, total_size_bytes, largest_archive_bytes, largest_repository) count a run's results once it ended; run counts, the average duration, success_rate and last_run_* include runs in progress at once. success_rate is 100 - total_failed / total_repos * 100 (0 without repositories).
Timeout: 15 seconds (operations are cancelled if exceeded)
total_logs is exact while execution_logs has fewer than 10,000 rows and the planner estimate (pg_class.reltuples, refreshed by ANALYZE and autovacuum) above that, so the endpoint never counts the whole log table. largest_repository is the repository of the largest archive ever recorded.
Response: 200 OK
{
"total_runs": 150,
"total_repos": 1250,
"total_successful": 1180,
"total_failed": 45,
"total_skipped": 25,
"distinct_repos": 320,
"total_logs": 5420,
"success_rate": 94.4,
"last_run_status": "completed",
"last_run_at": "2024-06-17T10:45:30Z",
"avg_duration_ms": 900000,
"total_size_bytes": 536870912,
"largest_archive_bytes": 104857600,
"largest_repository": "octocat/large-repo",
"latest_analytics": {
"id": 1,
"run_id": 150,
"captured_at": "2024-06-17T10:45:30Z",
"head_commit": "abc123def456789",
"head_commit_message": "Merge pull request #1",
"head_commit_at": "2024-06-17T10:40:00Z",
"total_commits": 5420,
"branch_count": 12,
"tag_count": 3,
"tracked_files": 850,
"total_blob_size_bytes": 536870912,
"avg_blob_size_bytes": 631680,
"largest_blob_path": "data/archive.tar.gz",
"largest_blob_size_bytes": 104857600,
"archive_count": 320,
"total_archive_size_bytes": 536870912,
"avg_archive_size_bytes": 1677721,
"largest_archive_path": "archives/large-repo.tar.gz",
"largest_archive_size_bytes": 104857600
}
}
Get Metrics
Endpoint: GET /api/metrics
Retrieve the runs of the last days days with their totals, plus fleet totals and the latest analytics snapshot, in one database round trip.
Query Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
days | integer | 30 | Number of days to look back: values below 1 mean 30, values above 365 (the longest history a plan keeps) are capped at 365 |
days in the answer is the window used. runs lists the newest 1,000 runs of the window, oldest first; runs_truncated is true when the window holds more. The totals count every run of the window.
Response: 200 OK
{
"days": 30,
"runs": [ { "id": 149, "status": "completed", "started_at": "2024-06-16T10:30:00Z", "total_repos": 45, "successful": 45, "failed": 0, "skipped": 0, "duration_ms": 860000 } ],
"runs_truncated": false,
"total_runs": 30,
"avg_duration_ms": 900000,
"total_successful": 1320,
"total_failed": 12,
"total_skipped": 18,
"distinct_repos": 45,
"total_logs": 5420,
"total_size_bytes": 536870912,
"largest_archive_bytes": 104857600,
"largest_repository": "octocat/large-repo",
"latest_analytics": { "run_id": 150, "captured_at": "2024-06-17T10:45:30Z" }
}
total_logs follows the same exact-or-estimate rule as /api/dashboard/stats.
Analytics
List Analytics History
Endpoint: GET /api/analytics/history
Retrieve a page of repository analytics snapshots, newest first (see Paging).
Query Parameters:
| Parameter | Type | Default | Max | Description |
|---|---|---|---|---|
page | integer | 1 | first 10,000 rows | Page number |
limit (or page_size) | integer | 50 | 500 | Results per page |
before | string | — | — | pagination.next_cursor of the previous page |
Response: 200 OK
{
"data": [
{
"id": 1,
"run_id": 150,
"captured_at": "2024-06-17T10:45:30Z",
"head_commit": "abc123def456789",
"head_commit_message": "Merge pull request #1",
"head_commit_at": "2024-06-17T10:40:00Z",
"total_commits": 5420,
"branch_count": 12,
"tag_count": 3,
"tracked_files": 850,
"total_blob_size_bytes": 536870912,
"avg_blob_size_bytes": 631680,
"largest_blob_path": "data/archive.tar.gz",
"largest_blob_size_bytes": 104857600,
"archive_count": 320,
"total_archive_size_bytes": 536870912,
"avg_archive_size_bytes": 1677721,
"largest_archive_path": "archives/large-repo.tar.gz",
"largest_archive_size_bytes": 104857600
}
],
"pagination": {
"page": 1,
"limit": 50,
"total_items": 150,
"total_pages": 3
}
}
Get Latest Analytics
Endpoint: GET /api/analytics/latest
Retrieve the most recent analytics snapshot without pagination.
Response: 200 OK
{
"id": 1,
"run_id": 150,
"captured_at": "2024-06-17T10:45:30Z",
"head_commit": "abc123def456789",
"head_commit_message": "Merge pull request #1",
"head_commit_at": "2024-06-17T10:40:00Z",
"total_commits": 5420,
"branch_count": 12,
"tag_count": 3,
"tracked_files": 850,
"total_blob_size_bytes": 536870912,
"avg_blob_size_bytes": 631680,
"largest_blob_path": "data/archive.tar.gz",
"largest_blob_size_bytes": 104857600,
"archive_count": 320,
"total_archive_size_bytes": 536870912,
"avg_archive_size_bytes": 1677721,
"largest_archive_path": "archives/large-repo.tar.gz",
"largest_archive_size_bytes": 104857600
}
Get Analytics for Specific Run
Endpoint: GET /api/analytics/:id (also GET /api/analytics/run/:id, the same handler)
Retrieve the analytics snapshot for a specific backup run ID.
Path Parameters:
| Parameter | Type | Description |
|---|---|---|
id | integer | Backup run ID |
Response: 200 OK — Same structure as Get Latest Analytics
Repositories
Get Tracked Repositories
Endpoint: GET /api/repos
Retrieve every repository that has a backup result, each represented by its newest result (latest created_at, then highest id), largest archives first.
pagination.total_items comes from the account's rollup, so it counts the repositories of ended runs: while a run backs up a repository for the first time, the page can list one more repository than total_items.
Query Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
page | integer | 1 | Page number |
limit | integer | 50 | Results per page (max 500) |
Response: 200 OK
{
"data": [
{
"full_name": "octocat/Hello-World",
"last_status": "completed",
"last_commit_hash": "abc123def456",
"archive_size_bytes": 1048576,
"last_backed_up": "2024-06-17T10:45:30Z"
}
],
"pagination": {
"page": 1,
"limit": 50,
"total_items": 320,
"total_pages": 7
}
}
Get a Repository's Recorded Archive
Endpoint: GET /api/repos/:owner/:name/archive
What the worker's last attempt recorded for one repository of the account (worker_repo_state): where its archive is and its checksum. The MCP server's archive tools find the file by archive_key.
{"repository": "octocat/hello-world", "status": "ok", "archive_key": "octocat__hello-world.bundle", "archive_format": "bundle", "archive_sha256": "9f86d0…", "archive_size": 1048576}
repository:owner/namein lower case, the worker's key; the path's name is compared without case.status:ok,empty,too_large,failed,missingorwithheld.archive_key,archive_sha256,archive_size:nullwhen none is recorded;archive_format:bundle,tarball, ornullfor another recorded value.
404 NOT_FOUND when the account has no state for the repository, 400 BAD_REQUEST for a name GitHub does not allow.
Logs
Get Execution Logs
Endpoint: GET /api/logs
Retrieve stored execution logs for display in the UI.
Query Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
page | integer | 1 | Page number, within the first 10,000 rows |
limit | integer | 50 | Results per page (max 500) |
before | string | — | pagination.next_cursor of the previous page (see Paging) |
level | string | — | Filter by log level, any case (info, warn, error, debug; the worker writes lower case), or by several, comma-separated (error,warn,warning): a log matches any of them |
run_id | integer | — | Filter by specific backup run ID (non-numeric: 400) |
repository | string | — | Only the logs of this repository, owner/name compared without case (not a repository name: 400 BAD_REQUEST) |
Logs are listed newest first by created_at, then by id. Without filters, pagination.total_items is exact below 10,000 log rows and the planner estimate above. With a filter it is exact up to 10,000; past that it is 10,000 and pagination.total_capped is true.
Response: 200 OK
{
"data": [
{
"id": 1,
"created_at": "2024-06-17T10:30:15Z",
"level": "info",
"message": "Starting backup run",
"repository": "",
"run_id": 1
},
{
"id": 2,
"created_at": "2024-06-17T10:30:20Z",
"level": "INFO",
"message": "Cloning repository",
"repository": "octocat/Hello-World",
"run_id": 1
},
{
"id": 3,
"created_at": "2024-06-17T10:32:10Z",
"level": "ERROR",
"message": "Network timeout during clone",
"repository": "octocat/Spoon-Knife",
"run_id": 1
}
],
"pagination": {
"page": 1,
"limit": 50,
"total_items": 5420,
"total_pages": 109,
"next_cursor": "MTcxODYyMDMzMDAwMDAwMC4z"
}
}
Live Log Stream (Server-Sent Events)
Endpoint: GET /api/logs/stream
Streams the caller's account's new execution_logs rows as Server-Sent Events. It is under /api, so it is rate limited and needs a principal with the read scope (the dashboard reads it through its server-side proxy, which forwards the session). One poller serves every subscriber, and each row goes only to the subscribers of its account, live and when resuming.
Response headers: Content-Type: text/event-stream, Cache-Control: no-cache, X-Accel-Buffering: no.
Stream:
retry: 5000
id: 123
event: log
data: {"type":"log","id":123,"level":"info","message":"Cloning repository","repository":"octocat/Hello-World","timestamp":"2024-06-17T10:30:20.123456Z"}
: ping
- The stream opens with
retry: 5000, sends a: pingcomment every 15 seconds and ends after 5 minutes;EventSourcereconnects on its own and resumes. - The credential is checked again at every ping: once the token is revoked or expires, the session expires or the account is disabled (or the check fails), the stream ends, and the reconnect has to authenticate again.
- By default only rows written after the request are sent.
- Resuming: send
Last-Event-ID: <id>(EventSource does this when it reconnects) or?after_id=<id>. When both are presentLast-Event-IDwins, because a reconnecting EventSource repeats its original URL with a staleafter_id. The rows after that ID written before the stream started (at most the newest 1,000) are sent first, then live rows, without gaps or duplicates. A malformed or negative ID returns400. - Rows committed late: ids are handed out when a row is inserted, but a row is visible only once its transaction commits, so a row can show up after rows with higher ids were sent. The feed looks for such a row for 30 seconds and then sends it without an
id:line, soLast-Event-IDstays the newest id sent. A row later than that is still inGET /api/logs. - Limits: an account may hold 10 live streams at once (SSE and WebSocket together) and an API process 500. Past them a new stream gets
429 TOO_MANY_STREAMS(the account's) or503 SERVICE_BUSY(the server's), withRetry-After: 30. - A client too slow to keep up is disconnected and resumes on reconnect;
503 SERVICE_UNAVAILABLEmeans the live feed is unavailable.
const source = new EventSource('/api/logs/stream'); // through a same-origin proxy that forwards the session
source.addEventListener('log', (event) => console.log(JSON.parse(event.data)));
WebSocket
Real-time Live Logs
Endpoint: GET /ws/live
WebSocket stream of the caller's account's new execution_logs rows, as text messages with the JSON of the SSE data field. No history is replayed: a client receives the rows of its account written after it connected.
- Origin check: a handshake whose
Originheader is not listed inWS_ALLOWED_ORIGINS(comma-separated, default: the dashboard origins of the CORS configuration,*allows any) is refused with403. Clients that send noOrigin(not browsers) are accepted. - Limits: a handshake counts against the rate limits like any request. The streams of an account and of a process are limited as for SSE: a handshake past them is refused before the upgrade with
429 TOO_MANY_STREAMSor503 SERVICE_BUSY(Retry-After: 30), and a connection the feed refuses after the upgrade closes with 1013. - Authentication: the handshake needs a principal with the
readscope in its headers:Authorization: Bearer(a personal access token or a session) or the internal secret withX-Account-Id(401/400/403/404as for any route). A token in the URL (?token=) is not accepted. Browsers cannot set these headers on a WebSocket, so browser clients use the SSE endpoint through the dashboard proxy. - Keepalive: the server pings every 30 seconds and disconnects a client that has not answered within 75 seconds; every write has a 10 second deadline, and a client too slow to keep up is disconnected (close code 1013). On shutdown the server sends close code 1001.
- Lifetime: like the SSE stream, a connection ends after 5 minutes (close code 1000, "reconnect"), and the credential is checked again at every ping: a revoked or expired token, an expired session or a disabled account closes it with 1008, a check that cannot be made with 1013. Rows written while a client reconnects are not replayed; read them with
GET /api/logs.
Connection Example:
// Node, Go, Python...: a client that can send headers on the handshake.
const ws = new WebSocket('ws://localhost:8080/ws/live', { headers: { Authorization: `Bearer ${token}` } });
ws.onmessage = (event) => console.log(JSON.parse(event.data));
Log Entry:
{
"type": "log",
"id": 123,
"level": "info",
"message": "Cloning repository",
"repository": "octocat/Hello-World",
"timestamp": "2024-06-17T10:30:20.123456Z"
}
The WebSocket and SSE subscribers share one database poller. It runs only while at least one client is connected, polls every 2 seconds, backs off to 15 seconds after a minute without new rows and returns to 2 seconds as soon as rows arrive, so an idle API does not keep a scale-to-zero database awake. Each poll also asks for the ids its cursor skipped in the last 30 seconds (at most 1,000), so a row committed late reaches WebSocket clients too.
Health & Prometheus Metrics
| Endpoint | Auth | Description |
|---|---|---|
GET /health, GET /healthz | public | Liveness |
GET /ready, GET /readyz | public | Readiness (database ping; reports disconnected without the driver error) |
GET /metrics | internal secret or METRICS_TOKEN (open with API_REQUIRE_AUTH=false); sessions and tokens get 403 | Prometheus text (or JSON with ?format=json) of the whole process, no account's data; request series are keyed by route pattern (/api/backups/:id). ghb_owner_last_completed_run_timestamp_seconds is when the owner's last full backup run completed (0 when none did), once the owner watch has read it, and ghb_owner_alert_after_seconds is OWNER_ALERT_AFTER |
Account, tokens and backup requests
JSON bodies of these routes are limited to 16 KiB; malformed JSON or values are 400 BAD_REQUEST.
Current Account
Endpoint: GET /api/me (read; any principal but an agent)
The caller's account and how it authenticated. The MCP server uses it to check a personal token when it has no credential of its own, neither SERVICE_CREDENTIAL nor INTERNAL_SECRET (with one it uses POST /api/internal/tokens/resolve, which answers the same).
Response: 200 OK
{
"account": {
"id": 2,
"login": "octocat",
"display_name": "The Octocat",
"email": "octocat@example.com",
"plan": "pro",
"is_owner": false,
"created_at": "2026-10-01T09:00:00Z"
},
"principal": {"kind": "personal_token", "scopes": ["read", "write"]}
}
kind is session, personal_token, internal or owner_legacy. Unknown values are empty strings.
Research Telemetry Consent
Endpoints: GET /api/me/research (read) and PUT /api/me/research {"enabled": true|false} (write), dashboard sessions only. The runs service serves them and keeps consent in runs.research_consent (ADR 0012); an account that never consented answers off, and PUT answers 404 for an account identity does not publish.
Both answer {"enabled": false, "since": null or RFC 3339, "available": true}. available is false when the API has no RESEARCH_HMAC_KEY; turning research on then answers 503 RESEARCH_UNAVAILABLE.
- Turning it on keeps the first consent time.
- Turning it off deletes the account's research samples in the same transaction.
- Both are recorded in
audit_events(research.enabled,research.disabledwithdeleted_samples). - What a sample holds is described under Run Intake. Samples are deleted after 365 days.
Delete the Account
Endpoint: DELETE /api/me {"confirm": "<GitHub login>"} (write), dashboard sessions only.
Deletes the caller's account. Identity deletes at once, in one transaction, the account, its tokens, agents, link requests and audit events, and the AI assistant's sessions, messages, investigations, tool calls, confirmations, reports, OpenRouter key and search index entries, and writes an account.deleted event (contracts/events/account.deleted.v1.schema.json) in the same transaction. The runs, insights and notify services delete their rows of the account when their job runners take the event, within about 12 hours (a runner with deletion jobs passes at least that often even without traffic): the backup runs with their results, errors, logs and snapshots, the fixes, run requests, worker state and leases, research samples and the run events (runs), the dashboard's totals (insights), and the alert channels, rules, events and deliveries (notify). Backup archives are in the user's own storage and are not touched.
confirmmust be the account's GitHub login (compared without regard to case); otherwise400 CONFIRMATION_REQUIRED. It guards against a stray request.- The deployment owner's account is refused:
409 OWNER_ACCOUNT. - The account's tokens, agents and sessions stop working at once in the API process that deleted it, within 2 seconds in every other API process, and within
ACCOUNT_STATUS_CACHE_SECONDS(60 s) in the Observatory. - A running backup loses its run: the worker's next report is refused and it stops. The runs tables refuse new rows of the deleted account; runs and notify delete their rows a second time 5 minutes after the first, for writes that were in flight.
- Nothing is written to
audit_events(the account's events go with it); the API logsAccount deletedwith the account id and the counts.
Response: 200 OK with the rows identity deleted per table, and in pending the services that delete the rest afterwards. Rows removed by a cascade (a session's metadata) are not counted.
{"deleted": {"accounts": 1, "ai_chat_messages": 18, "api_tokens": 2}, "pending": ["runs", "insights", "notify"]}
Export the Account's Data
Endpoint: GET /api/me/export (read), dashboard sessions only.
The account, its tokens, agents and activity log as one JSON document, read from one consistent snapshot and streamed as a download (Content-Disposition: attachment; filename="github-backup-export-<UTC time>.json", Cache-Control: no-store). The backup history is the runs service's: GET /api/runs/export; the AI assistant's data is the Observatory's: GET /me/export. The dashboard's Settings > Your Data page joins the three into one file.
{
"format": "github-backup-export",
"version": 2,
"exported_at": "2026-10-15T09:00:00Z",
"account": {"id": 2, "github_login": "octocat", "email": "octocat@example.com"},
"tables": {"api_tokens": [], "agents": [], "audit_events": []}
}
tablesholdsapi_tokens(never the hash),agentsandaudit_events. Each row is as PostgreSQL renders it in JSON, every column included.versionchanges when a reader would have to change: version 1 also held the backup history.- The document ends with
}and a newline, its only raw newline. A failure after the response has started ends it without that ending, so a cut-off document is never mistaken for a whole one. - 3 exports per account per 10 minutes in each API process; more answer
429 RATE_LIMITEDwithRetry-After.
Export the Backup History
Endpoint: GET /api/runs/export (read), dashboard sessions only.
The account's rows in the runs service as one JSON document, as GET /api/me/export writes it (filename="github-backup-runs-export-<UTC time>.json").
{
"format": "github-backup-runs-export",
"version": 1,
"exported_at": "2026-10-15T09:00:00Z",
"account_id": 2,
"tables": {"backup_runs": [{"id": 3, "status": "completed"}], "execution_logs": []}
}
tablesholdsbackup_runs,backup_run_errors,backup_results,backup_result_errors,execution_logs,analytics_snapshots,backup_fixes,backup_fix_commits,backup_run_fixes,backup_run_requests,worker_repo_state,research_consentandresearch_samples.- It ends like
GET /api/me/export, and has its own 3 exports per account per 10 minutes;404for an account that was deleted.
Personal Access Tokens
Signed-in sessions only (403 FORBIDDEN for tokens and internal callers).
GET /api/tokens lists the account's personal tokens, newest first, revoked and expired ones included. Neither the token nor its hash is ever returned again.
{
"tokens": [
{
"id": 7,
"name": "laptop CLI",
"display": "ghb_pat_…a1b2",
"scopes": ["read"],
"created_at": "2026-10-01T09:00:00Z",
"last_used_at": "2026-10-03T18:12:00Z",
"expires_at": "2026-12-30T09:00:00Z",
"revoked_at": null
}
]
}
last_used_at is updated at most once a minute.
POST /api/tokens creates one (write):
{"name": "laptop CLI", "scopes": ["read", "write"], "expires_in_days": 90}
name: 1-100 characters.scopes:["read"]or["read", "write"](["write"]means both); anything else is400.expires_in_days:30,90(the default when omitted),365or0(never).- An account holds at most 20 active (not revoked, not expired) tokens:
409 TOO_MANY_TOKENS.
Response: 201 Created with Cache-Control: no-store. The token is shown this once:
{"token": "ghb_pat_Zm9v…", "info": {"id": 8, "name": "laptop CLI", "display": "ghb_pat_…x9Yz", "scopes": ["read", "write"], "created_at": "…", "last_used_at": null, "expires_at": "…", "revoked_at": null}}
DELETE /api/tokens/:id revokes one (write): 204, also when it was revoked already; 404 when it is not this account's personal token. Revocation takes effect on the next request to the API process that revoked it, and within 30 seconds on any other.
Token creation and revocation are recorded in audit_events (token.created, token.revoked, actor session:<login>).
Linked Agents
GET /api/agents (read) lists the account's linked workers, newest first, revoked ones included:
{"agents": [{"id": 3, "name": "home-server", "hostname": "home-server.lan", "version": "1.4.0", "created_at": "…", "last_seen_at": "…", "revoked_at": null}]}
last_seen_at is the last use of the agent's token (updated at most once a minute).
DELETE /api/agents/:id (session only, write) revokes the agent and its token: 204, also when it was revoked already; 404 when it is not this account's. The worker's next request gets 401.
Approve an Agent Link
Session only. The dashboard's /link page (where verification_uri points) uses both.
POST /api/agents/link/lookup {"user_code": "BCDF-GHJK"} (read) returns the pending link, so the page can show which machine asks before the user approves it:
{"user_code": "BCDF-GHJK", "agent_name": "home-server", "hostname": "home-server.lan", "version": "1.4.0", "expires_at": "…"}
POST /api/agents/link/approve {"user_code": "BCDF-GHJK"} (write) binds the link to the session's account: 200 {"agent_name", "hostname", "version"}. The worker's next poll receives its token. Only an account with a paid plan, or the deployment owner's, links a worker: any other gets 402 PLAN_REQUIRED, and the code stays pending, so it can be approved once the account pays (ADR 0022). An account has at most 10 active (not revoked) agents: approving past that answers 409 TOO_MANY_AGENTS ("an account may have at most 10 linked agents; revoke one on Settings > Agents first").
Both accept the code as typed (lower case, with a space or without the dash) and answer 404 for an unknown, expired, used or already approved code.
Queue a Backup
Endpoint: POST /api/requests (write)
Queues an on-demand backup for the account's next worker run: one repository, or every repository with target_repo null (or omitted).
{"target_repo": "octocat/Hello-World", "reason": "before the release"}
target_repo:owner/nameas GitHub allows them (a trailing.gitis dropped; stored in lower case), ornull.reason: at most 500 bytes.requested_by: only internal callers may set it (at most 100 characters, for exampleobservatory:<user>); otherwise it is the principal (session:<login>,token:<id>).
Response: 201 Created for a new request, 200 OK with "queued": false when the account already has a pending request for the same target (that one is returned, so a retry does not queue a second run):
{"id": 41, "target_repo": "octocat/hello-world", "requested_by": "session:octocat", "reason": "before the release", "status": "pending", "queued": true}
target_repo is "" for every repository.
Limits: an account without a paid plan queues nothing (402 PLAN_REQUIRED); a paying account (pro) may queue 10 requests per hour; the deployment owner has no limit. Every request created in the window counts, whatever became of it; a request answered with an existing pending one does not. Past the limit: 429 {"error": "MANUAL_RUN_LIMIT", "message"} with Retry-After, the seconds until the request that reached the limit leaves the window.
Internal account routes
Internal callers only (a service credential the policy allows, or the deprecated INTERNAL_SECRET; no X-Account-Id); every other principal gets 403.
Sign In a GitHub User
Endpoint: POST /api/internal/accounts/github
The dashboard's GitHub callback sends the user GitHub reported and receives the account to put in the session. The API is the single source of truth for sign-up:
{"github_user_id": 583231, "login": "octocat", "name": "The Octocat", "email": "octocat@example.com"}
- An existing account (same
github_user_id) signs in; its login, and its name and email when given, are refreshed. - The user whose id is
OWNER_GITHUB_USER_IDclaims account 1 while it is unclaimed (createdstaysfalse; auditaccount.owner_claimed). - Otherwise a new account is created if
SIGNUP_MODEallows it:allowlist(default) admitsALLOWED_GITHUB_USERS(numeric ids,login:idor logins) and the owner,openadmits anyone,closednobody (auditaccount.created).
Response: 200 OK
{"account": {"id": 2, "github_user_id": 583231, "login": "octocat", "display_name": "The Octocat", "email": "octocat@example.com", "plan": "none", "is_owner": false, "created_at": "…", "updated_at": "…", "disabled_at": null}, "created": true}
403 SIGNUP_CLOSED when the policy turns the user away (the message says why and can be shown to them), 403 ACCOUNT_DISABLED for a disabled account, 400 for a missing or non-positive github_user_id, an empty or longer than 39 characters login, or an email that is not an address.
Get an Account
Endpoint: GET /api/internal/accounts/:id
200 {"account": {…}} with the same fields, disabled or not (disabled_at says), or 404. None of the bundled services calls it (the Observatory reads the accounts table and the MCP server resolves tokens through POST /api/internal/tokens/resolve); it is for operators and other services that hold INTERNAL_SECRET.
Resolve a Personal Token
Endpoint: POST /api/internal/tokens/resolve
The MCP server, which has no database, verifies its clients' personal access tokens here instead of sending each one to GET /api/me from its own address:
{"token": "ghb_pat_…"}
with the header X-Client-Address: <the end client's IP>, as the MCP server determined it (its peer address, or the forwarding header of one of its TRUSTED_PROXIES).
Response: exactly what GET /api/me answers with that token as the bearer: 200 {"account", "principal"} (principal.kind is personal_token), 401 UNAUTHORIZED with error.details.reason unknown, revoked or expired, or 403 ACCOUNT_DISABLED. 400 when the body holds no well-formed personal token (agent tokens and sessions included); nothing is looked up then.
An unknown token counts against the address in X-Client-Address (canonical form, so ::ffff:203.0.113.7 is 203.0.113.7), in the same per-address budget as the tokens the API is sent directly; a missing or invalid address counts against one shared bucket, internal-unknown. An address past 60 unknown tokens a minute gets 429 RATE_LIMITED with Retry-After, without a lookup. The MCP server's own address is never counted, and the route is not rate limited per caller or forwarded address, so one MCP client's made-up tokens cannot lock out the MCP server's other users.
Agents (linked workers)
A worker without a database connection is linked to an account once and then reports its runs over /v1 with its agent token. Every /v1 body is limited to 2 MiB (413 PAYLOAD_TOO_LARGE).
Link a Worker
An OAuth device flow (RFC 8628). Both routes are public.
POST /v1/agent/link {"name": "home-server", "hostname": "home-server.lan", "version": "1.4.0"} (name defaults to hostname; 1-100 characters, hostname at most 255, version at most 100) starts a link, 10 a minute per address:
{
"device_code": "<43 characters>",
"user_code": "BCDF-GHJK",
"verification_uri": "https://backup.example.com/link",
"verification_uri_complete": "https://backup.example.com/link?code=BCDF-GHJK",
"expires_in": 600,
"interval": 5
}
The user code has 8 letters of BCDFGHJKLMNPQRSTVWXZ. verification_uri is APP_URL + /link; the API refuses to start with an APP_URL that is not https (plain http only for localhost, 127.0.0.1 and [::1]). The user opens it, signs in and approves the code (Approve an Agent Link).
POST /v1/agent/link/token {"device_code": "…"} is polled by the worker every interval seconds:
| Answer | Meaning |
|---|---|
400 {"error": "authorization_pending"} | Not approved yet; poll again after interval. |
400 {"error": "slow_down"} | Polled sooner than the interval; wait longer. |
400 {"error": "expired_token"} | Expired, already redeemed, or never issued: start a new link. |
400 {"error": "access_denied"} | Denied, or the approving account is disabled. |
400 {"error": "invalid_request"} | No device_code, or not JSON. |
409 {"error": "TOO_MANY_AGENTS", "message"} | Approved, but the account reached 10 active agents since (several links approved at once); the link stays approved until it expires, so a poll after the user revoked an agent succeeds. |
200 | Approved: the agent and its token were created (audit agent.linked). |
{"agent_token": "ghb_agt_…", "agent_id": 3, "account": {"id": 2, "login": "octocat"}, "control_plane": "https://api.backup.example.com"}
The token is issued once: the next poll answers expired_token. It has the agent scope only, never expires and is revoked with its agent. control_plane is API_PUBLIC_URL, or "" when unknown: the worker then keeps the URL it linked with. Both answers carry Cache-Control: no-store. Polls are bounded to 60 a minute per address.
Run Intake
Agent tokens only. Everything is written in the token's account through the same SQL as a self-hosted worker (src/platform/runstore), so the dashboard shows both alike; a run id of another account answers 404. :id must be a positive integer (400 otherwise).
Only the run's holder writes. The run routes (logs, results, progress, snapshot, complete) and claim/finish act only while the run is running and the account's lease names it as this agent's run (<host>:agent<id>:run<run_id>); anything else, a finished run or the run another machine of the account holds, answers 409 {"error": "RUN_NOT_HELD", "message"} and changes nothing. The check and the write happen in one transaction that locks the lease row, so a takeover cannot slip in between. fail-interrupted needs the account's live lease for one of this agent's runs (409 RUN_NOT_HELD otherwise), so it never fails the requests another machine's run is serving. A run whose lease was taken over or expired can no longer complete: an expired lease is held by nobody, its last holder included (the heartbeat answers 409 LEASE_LOST, the run's writes 409 RUN_NOT_HELD), and the abandoned-run job fails the run once the account's lease is free and the run has been quiet for 30 minutes.
| Route | Body | Answer |
|---|---|---|
POST /v1/runs | {"full": true, "worker_version": "1.4.0", "host": "home-server"} | 201 {"run_id", "lease": {"holder", "ttl_seconds": 600, "heartbeat_seconds": 60}, "research": false}, 409 {"error": "LEASE_HELD", "holder": "…"}, or 402 PLAN_REQUIRED when the account has no paid plan |
POST /v1/runs/:id/heartbeat | none or {} | 204, or 409 {"error": "LEASE_LOST"} |
POST /v1/runs/:id/logs | {"logs": [{"level", "message", "repository", "time"}]} | 204, or 409 RUN_NOT_HELD |
POST /v1/runs/:id/results | {"results": [{"repository", "status", "commit_hash", "archive_size", "duration_ms", "error", "reason", "stat_outcome", "phases_ms": {"clone", "pack", "upload"}, "cloned_bytes"}]} | 204, or 409 RUN_NOT_HELD |
POST /v1/runs/:id/progress | {"successful", "failed", "skipped"} | 204, or 409 RUN_NOT_HELD |
POST /v1/runs/:id/snapshot | {"captured_at", "head_commit", "head_message", "head_time", "total_commits", "branch_count", "tag_count", "archive_count", "archive_bytes", "largest_key", "largest_bytes"} | 204, or 409 RUN_NOT_HELD |
POST /v1/runs/:id/research | {"agent": {"version", "os", "sink"}, "samples": [{"repo_id", "reason", "status", "stat_outcome", "prior_pushed_at", "pushed_at", "size_kb", "cloned_bytes", "archive_bytes", "phases_ms", "shadow": {"head", "refs", "error"}}]} | 204, or 409 RUN_NOT_HELD |
POST /v1/runs/:id/complete | {"summary": {"total", "successful", "failed", "skipped"}, "duration_ms", "error": null, "telemetry": {"phases_ms", "reasons", "stat_outcomes"}, "agent": {"version", "os", "sink"}} | 204, or 409 RUN_NOT_HELD |
GET /v1/schedule | optional If-None-Match | {"last_full_run_at": null or RFC 3339, "pending_requests": 0, "slot": {"minute_of_week": 0-10079, "interval_minutes": 10080}, "next_run_at": null or RFC 3339, "check_after_seconds": 3600} with ETag: W/"s<slot>-r<runs_version>-q<requests_version>", or 304 without a body when If-None-Match matches |
POST /v1/requests/claim | {"run_id"} | {"requests": [{"id", "target_repo", "requested_by", "reason"}]}, or 409 RUN_NOT_HELD |
POST /v1/requests/finish | {"run_id", "done": [ids], "failed": [ids]} | 204, or 409 RUN_NOT_HELD |
POST /v1/requests/fail-interrupted | none or {} | {"failed": n}, or 409 RUN_NOT_HELD |
The schedule. Each account has a slot, a minute of the week in UTC counted from Monday 00:00: sha256("ghb-slot-v1:<account id>") as a big-endian number, modulo 10,080, so slots spread over the week and never change. next_run_at is the first slot at or after the last full run plus 3 days, null before any. A full run is due when next_run_at passed or there was none; with only pending requests the worker runs them alone. The ETag changes when a request is queued, claimed or finished, or a run starts or ends (runs.account_versions), not on a run's progress; a matching If-None-Match costs one primary-key read. Workers before this release send no If-None-Match and ignore the new fields.
-
Lease.
POST /v1/runstakes the account's run lease (one machine runs an account's backup at a time, self-hosted or linked) and starts arunningrun;full(defaulttrue) isfalsefor a run narrowed to some repositories, which the schedule does not count. The holder,<host>:agent<id>:run<run_id>, is unique per run. Renew it everyheartbeat_seconds; it is lostttl_secondsafter the last renewal. A heartbeat answers409 LEASE_LOSTonce the run ended or another holder took the lease: the worker must stop.POST /v1/runsis not idempotent: a retry after a lost reply finds the lease held by the first attempt until it expires. -
Logs and results. At most 500 per call. A log
messageand a resulterrorare free text: longer than 8 KiB (runstore.MaxTextBytes) they are cut on a character boundary and end in…, NUL characters are removed and invalid UTF-8 is replaced (runstore.CleanText), so one odd message never costs the batch.repository(200 characters) andcommit_hash(100) are identifiers: too long or with a NUL character they are400.levelis a lower-case slog level (debug,info,warn,error,info+2…;warningis read aswarn, empty asinfo);timeis RFC 3339 (omitted: the database's time). A result'sstatusis the worker's outcome (okis stored ascompleted, others keep their name),errorgoes tobackup_result_errors. Results are recorded all or nothing and are idempotent per run and repository: a repository the run already has a result for is skipped, and within one batch the last result of a repository counts, so a batch can be sent again after a timeout. -
Telemetry. Optional; workers older than these fields send none and the columns stay
NULL.- A result's
reasonis why it was backed up (a reason code),stat_outcomewhat checking its stored archive found (match,not_found,error,differs,damaged),phases_msits clone, pack and upload times andcloned_bytesthe size of its clone. Codes are lower-case letters, digits and_(at most 40); numbers cannot be negative (400). - A completion's
telemetryholds the run's phases in milliseconds (list,load_state,plan,back_up) and the repositories in scope counted by reason code and by stat outcome, at most 32 entries each.agentis the worker's version, operating system (linux/amd64) and sink type (git,local,s3). A later completion without them keeps what an earlier one recorded.
- A result's
-
Plan.
POST /v1/runsanswers402 PLAN_REQUIRED, before it takes the lease, when the account has no paid plan and is not the deployment owner's (ADR 0022). A run that started before the plan ended finishes; the worker's next run is refused. -
Research.
POST /v1/runsanswers"research": truewhen the account turned research telemetry on (PUT /api/me/research) and the API hasRESEARCH_HMAC_KEY. The worker then sends one sample per repository in scope, before the completion, at most 500 per call:repo_idis GitHub's numeric repository id, andreason,statusandstat_outcomeare codes;shadowis set for the repositories it probed withgit ls-remote(about one in ten):headis the commit HEAD names,refsa hex SHA-256 of the branches and tags with their commits, anderrora code (timeout,failed).
The API stores HMACs of
repo_id,headandrefs, never the values, and only a size bucket instead ofsize_kb. Without consent or without the key it answers204and stores nothing. A run keeps one sample per repository, so a batch sent again adds nothing. -
Snapshot. The run's analytics snapshot; a run keeps its first one.
head_messageis cleaned like a log message. -
Complete. Records the final counts,
duration_msand status exactly as a self-hosted worker does:failedwitherrorwhen it is set (cleaned like a log message),failedwithfailed repositories: Nwhen repositories failed, elsecompleted.summarymay also carry the worker'sengine.Summaryfields (InScope,BackedUp,Failed,Unchanged,Withheld,Empty,TooLarge), mapped likemonitor.Completion, whentotalis absent. It then releases the lease. A completion repeated after a lost reply (the run ended and the released lease still names it) answers204and changes nothing. -
Requests.
claimmarks the account's pending requests as running for the run and returns them, oldest first (a retry returns the same ones);finishrecords their outcome (ids that are not the account's running requests of that run are ignored; at most 10,000 ids per list);fail-interruptedmarks requests left running by an interrupted run as failed (only while holding the lease, see above). -
Rate limits. 600 requests a minute per agent, and 1200 a minute for all agents of one account together.
Pre-order waitlist
Join the Waitlist
POST /public/waitlist {"email": "dev@example.com", "source": "landing"} stores an address that asked to hear about the founding pre-order. Public, 30 a minute per address, bodies up to 2 KiB. The dashboard's same-origin POST /api/waitlist calls it for the landing page's form, with the browser's address in X-Forwarded-For when a trusted proxy reports it (the API believes that header only from a proxy listed in TRUSTED_PROXIES, so behind the dashboard the limit otherwise counts all of the dashboard's signups together; the dashboard limits each browser to 5 per 10 minutes itself).
email: one bare address of at most 254 characters with a dot in the domain (no display name, no list); stored as sent, compared case-insensitively.source: optional, 1-40 lowercase letters, digits or dashes; defaultlanding.
202 {"status": "accepted"} for a new and for a known address alike, so the route does not tell who signed up. 400 BAD_REQUEST for anything else. The rows are in waitlist_signups (migration 000012); read them with SELECT email, source, created_at FROM waitlist_signups ORDER BY created_at.
Alerts
The notify service (github-backup-notify, ADR 0017) sends an account's alerts: a failed run (run.failed), a missed run (run.missed: the account's slot passed, 24 hours went by and no full run completed or was running), and three billing events: billing.payment_failed, billing.subscription_ended and billing.renewal_due (a plan paid once ends in 14 days). Billing alerts link to the dashboard's /billing page. An account configures channels (where alerts go) and rules (which event types go to which channels). The routes need a session or a personal token (read to list, write to change); service credentials and INTERNAL_SECRET get 403. A dashboard page for them does not exist yet.
Alert Channels
GET /api/alerts/channels lists the account's channels, oldest first. A channel's URL and a webhook's signing secret are stored sealed (AES-256-GCM with NOTIFY_ENCRYPTION_KEY) and never returned; target shows the URL's host and the last four characters of its path:
{"channels": [{"id": 4, "kind": "slack", "name": "#backups", "target": "hooks.slack.com/…k9Qz", "enabled": true, "verified": true,
"failing": false, "failing_since": null, "consecutive_failures": 0, "last_error": null, "last_success_at": "2026-10-27T10:05:12Z",
"created_at": "…", "updated_at": "…"}]}
POST /api/alerts/channels {"kind", "target", "name", "enabled"} creates one (201 {"channel": {...}}):
kind | target |
|---|---|
slack | A Slack incoming webhook URL, https://hooks.slack.com/services/.... |
discord | A Discord webhook URL, https://discord.com/api/webhooks/... (or discordapp.com). |
webhook | Any https URL without credentials. The answer adds "signing_secret": "whsec_...", shown this once (Cache-Control: no-store). |
There is no e-mail channel: the product sends no e-mail (ADR 0020), and kind: "email" is 400 like any unknown kind. verified is always true; the field stays for older clients.
name(at most 100 characters) defaults totarget;enableddefaults totrue.- A URL whose host is an IP address that is private, loopback, link-local or reserved, or
localhost, is refused (400). When an alert is sent, the address the host resolves to is checked again on connecting, so a name that points inside the network is refused then (the delivery fails with that reason). Requests use no proxy, follow no redirect and give up after 15 seconds. 409 TOO_MANY_CHANNELSpast 20 channels,503 ENCRYPTION_UNAVAILABLEwhenNOTIFY_ENCRYPTION_KEYis not set (no channel can be stored without it).
GET /api/alerts/channels/:id returns one; PATCH /api/alerts/channels/:id {"name", "enabled"} renames, enables or disables it (to change the target, create a new channel); DELETE /api/alerts/channels/:id deletes it (204); its deliveries stay in the history with channel_id null.
POST /api/alerts/channels/:id/test sends a test alert (alert.test) now, once, and answers its delivery: "status": "sent", or "failed" with last_error. A failed test marks the channel failing like any other delivery; a disabled channel may be tested. 5 tests per account per 10 minutes.
A channel is failing once a delivery to it failed every attempt; failing_since, consecutive_failures and last_error say since when and why, and the next delivery sent clears them. Alerts keep going to a failing channel.
Alert Rules
GET /api/alerts/rules lists the account's rules, oldest first; GET /api/alerts/rules/:id returns one:
{"id": 2, "name": "Backup problems", "event_types": ["run.failed", "run.missed"], "channel_ids": [4, 7], "enabled": true,
"quiet_hours": {"start": "22:00", "end": "07:00", "time_zone": "Europe/Berlin"}, "min_interval_seconds": 3600,
"created_at": "…", "updated_at": "…"}
POST /api/alerts/rules creates one (201) from name, event_types (run.failed, run.missed, billing.payment_failed, billing.subscription_ended, billing.renewal_due) and channel_ids (1 to 20 of the account's channels), with enabled (default true), quiet_hours (default null) and min_interval_seconds (0 to 604800, default 0). PATCH /api/alerts/rules/:id changes the fields it is sent: quiet_hours: null removes them, channel_ids replaces the channels. DELETE /api/alerts/rules/:id deletes it (204). A channel id the account does not have is 404 CHANNEL_NOT_FOUND and changes nothing; past 50 rules, 409 TOO_MANY_RULES.
- Quiet hours (
startandendasHH:MM, different, in an IANA time zone): an alert due between them waits untilend; a window whose end is before its start runs past midnight. - Minimum interval: an event of a type the rule sent to a channel less than
min_interval_secondsago is not sent to it again (suppressed). - An event goes to each enabled channel once, through the first rule (by id) that names it.
Alert Deliveries
GET /api/alerts/deliveries lists the account's deliveries, newest first, paged like every list (Paging), only those of ?channel_id or with ?status when given:
{"data": [{"id": 31, "event_id": "9c3f6a1e-7d42-4b8e-a5c0-2e6f8b1d4a93", "event_type": "run.missed", "channel_id": 4, "channel_kind": "slack",
"rule_id": 2, "status": "sent", "attempts": 1, "last_error": null, "not_before": null, "created_at": "…", "updated_at": "…", "sent_at": "…"}],
"pagination": {"page": 1, "limit": 50, "total_items": 1, "total_pages": 1}}
status | Meaning |
|---|---|
pending | Waits to be sent: now, or at not_before (quiet hours). A failed attempt is tried again after the job queue's backoff (1 minute, doubling), 5 attempts in all. |
held | Beyond the account's rate (20 deliveries an hour): waits for its channel's digest, one message of up to 50 held alerts sent an hour later. |
sent | Delivered. |
digested | Delivered in a digest. |
failed | Every attempt failed, or the receiver refused it for good (a 4xx other than 408, 425 and 429, a redirect); its channel is failing. |
suppressed | Within its rule's minimum interval. |
skipped | Its channel was disabled or deleted before it went out, or it was an e-mail delivery still waiting when migration 000042 removed e-mail. |
Deliveries and the events they alert on are kept 30 days.
What a Channel Receives
- Slack and Discord: the subject and the text; Slack's markup characters are escaped and Discord's mentions turned off, so an alert pings nobody.
- Webhook:
POSTof the event's envelope as incontracts/events(id,type,version,occurred_at,producer,account_id,data), withContent-Type: application/json,User-Agent: github-backup-notify,X-GHB-Event: <type>,X-GHB-Delivery: <delivery id>andX-GHB-Signature: t=<unix seconds>,v1=<hex>, where the hex is the HMAC-SHA256 under the signing secret of the timestamp, a dot and the body. A receiver recomputes it, compares in constant time and refuses a timestamp older than a few minutes (sender.Verifydoes this in Go). A test's body has"type": "alert.test"; a digest's"type": "alert.digest"withdata.events, the held events, anddata.more, how many wait for the next digest. Any 2xx counts as delivered.
Billing
The billing service (github-backup-billing, ADR 0018) sells the plans. Amounts are integers in the currency's minor unit (paise, cents), tax included. A customer in India pays in rupees through a yearly subscription the provider renews (UPI AutoPay, cards); elsewhere the customer pays US dollars once a year and renews by paying again. Customers in the European Union and the United Kingdom are refused. The contract is contracts/openapi/billing.json.
List the Plans
GET /public/billing/plans is public, 60 a minute per address. It answers 200 {"plans": [...], "refund_policy": {"window_days": 14, "max_completed_runs": 1, "fee_bps": 1500}}. Each plan lists its cohorts, the price steps sold in position order: seats (null for the last step), sold (subscriptions ever activated and not refunded: the public seat counter) and on_sale (the step a checkout buys now), with one price per currency.
Open a Checkout
POST /api/billing/checkout (a session, the write scope):
{"plan_id": "personal", "customer": {"name": "Asha Rao", "email": "asha@example.com", "country": "IN", "state": "29", "gstin": "", "address": "12 MG Road, Bengaluru"}}
country decides the currency (INR in India, USD elsewhere). In India state is the two-digit GST state code of the place of supply; gstin, for a business, must start with it. The billing details are stored and printed on every invoice.
201 {"subscription_id", "url", "expires_at", "price_id", "currency", "amount_minor", "renewal"}: send the customer to url, the provider's payment page. The provider is not asked to e-mail the link or reminders to customer.email (ADR 0020); it only prefills the payment page. An open checkout for the same price is answered again. The price is the cohort on sale, or, for a one-time year renewed in its last 30 days, the price it was bought at.
400 for missing or malformed details, 403 COUNTRY_NOT_SERVED, 404 PLAN_NOT_FOUND, 409 ALREADY_SUBSCRIBED or CHECKOUT_IN_PROGRESS, 502 PAYMENT_PROVIDER_ERROR, 503 PAYMENTS_UNAVAILABLE when no provider is configured (RAZORPAY_KEY_ID unset).
The Account's Subscription
GET /api/billing/subscription (read) answers 200 {"subscription": {...} | null, "entitlement": {"plan": "none" | "pro", "valid_until"}}: the paid period that ends last, else an open checkout. There is no free plan: none is an account without a paid period, which can sign in and buy a plan, but links no worker, queues no backup and starts no run (402 PLAN_REQUIRED). status is pending (checkout open), active, past_due (a renewal the provider is still charging), cancelled (not renewed; access until current_period_end), ended, refunded or expired.
POST /api/billing/subscription/cancel (a session, write) stops the renewal: 200 {"subscription"}, or 404 NO_SUBSCRIPTION. Access lasts until the paid period ends.
Invoices
GET /api/billing/invoices (read) lists the account's invoices, newest first, at most 200. GET /api/billing/invoices/:id answers one, or 404. An invoice is numbered <prefix>/<yyyy>/<6 digits> per Indian financial year (GBI/2627/000001), with copies of the seller and buyer as they were, its lines, and its GST: tax_kind none (the seller is not registered), export (a buyer outside India), igst or cgst_sgst. credit_note names the credit note of a refunded invoice.
Refunds
GET /api/billing/refund (read) answers the quote: {"eligible", "reason", "paid_minor", "fee_minor", "refund_minor", "completed_runs", "deadline"}. The policy refunds the first payment of a subscription within 14 days if at most one backup run completed since, less 15%; renewals are not refunded. reason is no_payment, renewal, already_refunded, window_passed or too_many_runs.
POST /api/billing/refund (a session, write) sends that refund to the provider: 202 with the quote applied; the subscription ends when the provider confirms. 409 REFUND_NOT_ALLOWED with the quote in error.details, 502 PAYMENT_PROVIDER_ERROR.
Payment Provider Webhooks
POST /webhooks/:provider is public and verified by the provider's signature: for Razorpay (/webhooks/razorpay) the hex HMAC-SHA256 of the raw body under RAZORPAY_WEBHOOK_SECRET, in X-Razorpay-Signature. Bodies up to 1 MiB. 200 {"received": true} once recorded, and for a redelivery; 400 for an unknown provider, a bad signature (INVALID_SIGNATURE) or a body that is not an event. Any other answer makes the provider deliver it again. Subscribe the Razorpay webhook to: subscription.activated, subscription.charged, subscription.pending, subscription.halted, subscription.cancelled, subscription.completed, payment_link.paid, payment_link.expired, payment_link.cancelled, refund.processed, refund.failed.
Vector Embeddings & Hybrid Search
The Python Observatory provides high-performance vector search combining PostgreSQL Full-Text Search (FTS) and pgvector semantic embeddings with Reciprocal Rank Fusion (RRF). Since B7a it searches only the index (run failures, failed results, fixes and investigations, ADR 0008): when no chunk matches, nothing else is searched.
Hybrid Search
Endpoint: POST /search (Python Observatory: http://localhost:8000/search)
Execute a dual-layer hybrid search across embedding chunks and raw database tables. Needs a user token or X-Internal-Secret (the MCP server); internal calls use the server OpenRouter key pool, never a user's connected key.
Request Body:
{
"query": "authentication timeout during clone",
"source_types": ["execution_log", "backup_result", "investigation"],
"limit": 10,
"fts_weight": 0.3,
"semantic_weight": 0.7,
"rerank_model_id": "cohere/rerank-v3.5:free"
}
limit is 1 to 100 (default 20) and fts_weight and semantic_weight are 0 to 1; other values return 422.
Response: 200 OK
{
"results": [
{
"id": 42,
"source_type": "execution_log",
"source_id": "402",
"content": "[ERROR] Network timeout during clone (repo: octocat/Spoon-Knife)",
"score": 0.892154,
"metadata": {
"repository": "octocat/Spoon-Knife",
"level": "ERROR",
"run_id": 1
},
"reranked": true
}
],
"generation_id": 1,
"model_id": "google/text-embedding-004",
"total": 1
}
The embedding and search endpoints below wrap their payload as {"success": true, "message": "...", "data": <payload>}; the examples show the payload. /search needs a session token (Authorization: Bearer <JWT>) or X-Internal-Secret with X-Account-Id; /embeddings/status, /embeddings/switch-model and the other /embeddings/* actions need the owner's session (403 FORBIDDEN for any other account, because one index serves every account); the model lists (/api/embedding-models, /api/reranking-models) take no credential (Authorization: Bearer <JWT>).
List Free Embedding Models
Endpoint: GET /api/embedding-models
Retrieve the dynamic list of free embedding models fetched from OpenRouter (cached in memory, with a built-in fallback list). No credential needed; data is the list itself.
Response: 200 OK
[
{
"id": "nvidia/nemotron-3-embed-1b:free",
"name": "NVIDIA: Nemotron 3 Embed 1B (free)",
"dimensions": 2048,
"provider": "NVIDIA"
}
]
List Free Reranking Models
Endpoint: GET /api/reranking-models
Retrieve the dynamic list of free reranking models available via OpenRouter (cached in memory, with a built-in fallback list). No credential needed; data is the list itself.
Response: 200 OK
[
{
"id": "qwen/qwen3-reranker-8b",
"name": "Qwen: Qwen3 Reranker 8B",
"provider": "Qwen"
}
]
Get Embedding Status
Endpoint: GET /embeddings/status
The most recent generation (or ?generation_id=<id>): its embedding_generations row plus the count of its jobs by status; data is null when there is none.
Response: 200 OK
{
"id": 1,
"model_id": "google/text-embedding-004",
"dimensions": 768,
"status": "ACTIVE",
"total_items": 1250,
"processed_items": 1250,
"failed_items": 0,
"created_at": "2024-06-17T10:30:15Z",
"completed_at": "2024-06-17T10:44:00Z",
"activated_at": "2024-06-17T10:45:00Z",
"retired_at": null,
"job_counts": {"completed": 1250}
}
Switch Embedding Model
Endpoint: POST /embeddings/switch-model
Create a new BUILDING generation for a model and queue the Observatory's own sources (completed investigations); the background runner then backfills the run failures, failed results and fixes of every enabled account through the insights API (ADR 0013). The model's dimensions come from the model registry; chunking uses the service's settings.
Request Body:
{
"model_id": "google/text-embedding-004"
}
Response: 200 OK
{
"generation_id": 2,
"model_id": "google/text-embedding-004",
"status": "BUILDING",
"total_jobs_enqueued": 450,
"message": "Switched to model and enqueued source records"
}
Process Embedding Jobs Batch
Endpoint: POST /embeddings/process-batch (requires a bearer token)
Claim and embed queued jobs of a generation. One request runs up to max_batches batches and stops early when no job is left or after EMBEDDING_BATCH_TIME_BUDGET_SECONDS (default 25). Each job is written in its own savepoint, so one bad job does not fail the batch. When the last job is done, a BUILDING generation becomes READY (or FAILED if every job failed).
Request Body:
{
"generation_id": 2,
"batch_size": 50,
"max_batches": 5
}
batch_size is optional (1 to 500, default 50); max_batches is optional (1 to 50, default 1).
Response: 200 OK
{
"success": true,
"message": "Batch processed",
"data": {
"processed": 250,
"succeeded": 249,
"failed": 1,
"batches": 5,
"generation_status": "BUILDING"
}
}
Counts are jobs (source records), not chunks. 400 when the generation does not exist.
Activate Embedding Generation
Endpoint: POST /embeddings/activate?generation_id=2 (requires a bearer token)
Make a READY generation the one search uses. A BUILDING generation whose jobs are all finished is promoted to READY first. The generation it replaces is set to RETIRED and keeps its vectors until it is pruned; no generation is deleted here.
Response: 200 OK
{
"success": true,
"message": "Generation activated; the previously active generation was retired",
"data": {
"generation_id": 2,
"status": "ACTIVE",
"retired_generation_ids": [1]
}
}
404 for an unknown generation id, 409 when the generation is not READY (for example still BUILDING with pending jobs, or FAILED). Activating the active generation changes nothing.
Prune Stale Embedding Generations
Endpoint: POST /embeddings/prune (requires a bearer token)
Delete RETIRED and FAILED generations with their chunks and jobs. BUILDING, READY and ACTIVE generations are never pruned.
Response: 200 OK
{
"success": true,
"message": "Retired and failed embedding generations and stale failed jobs pruned",
"data": {
"deleted_generations": 1,
"deleted_jobs": 0
}
}
AI Observatory & Agentic Chat
The AI Observatory provides an autonomous agent with LangChain tool-calling RAG, SSE streaming, and Human-In-The-Loop (HITL) approval workflows. Every endpoint below needs Authorization: Bearer <token> (a session JWT; personal access tokens are not accepted), except /auth/login and the lists /api/models and /api/tools, which take no credential.
Login
Endpoint: POST /auth/login (form-encoded username, password)
Response: 200 OK
{"access_token": "<jwt>", "token_type": "bearer"}
Tokens are HS256 JWTs with issuer and audience github-backup (JWT_ISSUER, JWT_AUDIENCE) and an expiry; tokens without them are rejected. 401 for wrong credentials. After 5 failed attempts from one IP address within 5 minutes (LOGIN_MAX_FAILURES, LOGIN_FAILURE_WINDOW_SECONDS) the endpoint returns 429 with a Retry-After header. The address is the connection's peer, except for requests that carry a valid X-Internal-Secret: the dashboard server sends every browser's login with the secret and, when a trusted proxy reported it (DASHBOARD_TRUSTED_PROXY=true), the browser's address in X-Client-Address, and that address is used instead, so one browser cannot lock out the others. The limit is kept in process memory, so each instance counts separately and a restart clears it.
Current User
Endpoint: GET /auth/me
Response: 200 OK
{"success": true, "message": "Token is valid", "data": {"username": "octocat", "account_id": 2}}
401 for a missing, expired or invalid token.
Connect an OpenRouter Account
Endpoints: POST /me/openrouter/exchange, POST /me/openrouter/key, GET /me/openrouter, DELETE /me/openrouter
The assistant is bring-your-own-key: chat, search and embeddings run on the user's own OpenRouter key, and the server never spends the operator's key on another account. A user connects a key in one of two ways.
Sign in with OpenRouter. The dashboard runs the OpenRouter PKCE flow (S256) and posts the returned code with its verifier to POST /me/openrouter/exchange:
{"code": "<code from the OpenRouter callback>", "code_verifier": "<43 to 128 characters>"}
The observatory exchanges the code at POST https://openrouter.ai/api/v1/auth/keys and stores the key encrypted with CREDENTIALS_ENCRYPTION_KEY.
Paste an API key. POST /me/openrouter/key with {"api_key": "sk-or-v1-..."} (up to 512 characters, surrounding whitespace ignored). The observatory checks the key with GET https://openrouter.ai/api/v1/key before it stores it, and replaces any key the account had, including one marked invalid.
The key is never returned. Every endpoint returns the connection status:
{
"success": true,
"message": "OpenRouter connection status",
"data": {
"connected": true,
"source": "user",
"key_hint": "sk-or-...a1b2",
"connected_at": "2026-09-24T08:00:00+00:00",
"last_used_at": "2026-09-24T08:05:00+00:00",
"invalid": false
}
}
When no key is connected, connected is false and source is none: the assistant refuses the account's chat turns with 503 OPENROUTER_NOT_CONFIGURED (before a stream starts, so the question is not stored), and search runs on full-text search only. source is server only for the deployment owner's account (account 1) when the operator set OPENROUTER_ALLOW_SERVER_KEYS=true (default false) and OPENROUTER_API_KEY: then the owner's requests use the server key pool. Errors: 503 CREDENTIAL_STORAGE_UNAVAILABLE when CREDENTIALS_ENCRYPTION_KEY is not set or the table is missing, 400 OPENROUTER_EXCHANGE_FAILED when OpenRouter refuses the code, 502 OPENROUTER_EXCHANGE_UNAVAILABLE when OpenRouter cannot be reached; for a pasted key, 400 OPENROUTER_KEY_NOT_ACCEPTED when the value is not a key or OpenRouter does not accept it (nothing is stored), 502 OPENROUTER_KEY_CHECK_UNAVAILABLE when OpenRouter cannot check it right now.
A connected key is used only for its owner and requests never fall back to other keys. When OpenRouter rejects it (401) it is marked invalid and requests fail with 403 OPENROUTER_KEY_INVALID until the user signs in with OpenRouter again or pastes a new key; 402 OPENROUTER_OUT_OF_CREDITS and 429 OPENROUTER_RATE_LIMITED are passed on. 403 is used instead of 401 so the dashboard does not treat it as an ended session.
Chat and Chat Stream
Endpoints: POST /chat (JSON answer), POST /chat/stream (Server-Sent Events). GET /chat also answers, with the same fields as query parameters; there is no GET /chat/stream.
Request Body:
{
"session_id": "3f0a2c1e-5b7d-4e8f-9a6b-1c2d3e4f5a6b",
"question": "Investigate clone failure in repo octocat/Spoon-Knife",
"model": "openrouter/free-model:free"
}
question is at most 8000 characters and session_id must be a UUID (422 otherwise); model is optional and must be the default OPENROUTER_MODEL or a free model from the OpenRouter registry (400 MODEL_NOT_ALLOWED, 503 MODEL_REGISTRY_UNAVAILABLE when the registry cannot be read). The same check applies to rerank_model_id on POST /search.
The question is saved before the model is called, and the turn is saved with its final status (completed, failed, or cancelled when the client disconnected). The model sees the last AGENT_HISTORY_MAX_MESSAGES (default 20) messages of the session, role and content only. An unused session_id creates that session; one that belongs to another account is ignored and the turn runs in a new session of the caller's, never a 404. Read the session the turn ran in from data.session_id (POST /chat, GET /chat) or the info event's session_id (stream).
SSE Event Types (see docs/STREAMING_ARCHITECTURE.md for the full contract):
{"type": "info", "request_id": "...", "session_id": "...", "sources": [...]}: retrieved context, always first.{"type": "agent_reasoning", "iteration": 1, "request_id": "..."}: a model iteration started.{"type": "token", "text": "..."}: streamed answer text.{"type": "confirm_required", "confirm_id": "uuid", "name": "<tool>", "args": {...}, "tool_call_id": "..."}: HITL approval required, for a tool inCONFIRMATION_REQUIRED_TOOLS(none today).{"type": "tool_start", "name": "...", "args": {...}, "tool_call_id": "..."}and{"type": "tool_end", "name": "...", "tool_call_id": "...", "success": true, "duration_ms": 12.4, "result": "..."}(errorinstead ofresulton failure).{"type": "error", "message": "...", "code": "DEADLINE_EXCEEDED", "request_id": "..."}(SERVICE_BUSYwhen no LLM slot freed up withinLLM_SLOT_WAIT_SECONDS).{"type": "done", "answer": "...", "request_id": "..."}: always the last event.
POST /chat never runs a tool that needs confirmation, because it cannot ask. The agent has no tool that sends anything: asked to e-mail or send a report, it writes the report in its answer and points to the message's Download button in the dashboard.
An account runs at most LLM_MAX_CONCURRENT_TURNS_PER_ACCOUNT (2) turns at once per process: another gets 429 RATE_LIMITED with Retry-After: 5, before any SSE byte for a stream. A non-streamed turn whose LLM call found no free slot within LLM_SLOT_WAIT_SECONDS gets 503 SERVICE_BUSY with Retry-After.
Human-In-The-Loop Confirmation
Endpoint: POST /chat/confirm
Approve or reject a pending sensitive tool action announced by a confirm_required event.
Request Body:
{
"confirm_id": "uuid",
"approve": true
}
approved is accepted as an alias of approve.
Response: 200 OK
{
"success": true,
"message": "Confirmation recorded successfully",
"data": {"confirm_id": "uuid", "approved": true, "status": "approved"}
}
Only the user who started the turn can decide. 404 when the id is unknown or belongs to another user, 409 when it was already decided or has expired (after 120 seconds without a decision, which counts as rejected), 422 for a malformed id, 503 when the confirmation store is unavailable.
List Chat Sessions
Endpoint: GET /sessions
Retrieve the chat sessions. GET /sessions/{id}, PATCH /sessions/{id}, DELETE /sessions/{id} and GET /sessions/{id}/messages return 404 for unknown or malformed ids.
DELETE /sessions/{id} deletes the session with everything of its turns: the messages, the investigations, tool calls and confirmations, and the search index entries cut from the messages and investigations. DELETE /sessions/{id}/messages/{message_id} deletes one turn (both messages, by either one's id or the turn's request id) the same way; a message_id that is not a UUID is a no-op.
GET /sessions/{id}/messages returns the session's newest ?limit messages (default 200, at most 500) with their tool calls, oldest first. pagination.earlier_cursor, when set, is the ?before of the page of older messages; a before the Observatory did not return is 400.
POST /sessions with {"id"?, "session_name"?, "metadata"?} creates a session and returns it. id is optional: an unused id is taken as given, the caller's own session with that id is returned unchanged, and an id another account's session has is ignored, so the caller gets a new session under a fresh random id with the same 200 answer as any new session. Use the returned data.id.
Response: 200 OK
{
"success": true,
"message": "Sessions list retrieved",
"data": [
{
"id": "3f0a2c1e-5b7d-4e8f-9a6b-1c2d3e4f5a6b",
"session_name": "Investigate clone failure in octocat/Spoon-Knife",
"created_at": "2026-09-24T10:30:00Z",
"updated_at": "2026-09-24T10:34:00Z"
}
]
}
Export the Assistant's Data
Endpoint: GET /me/export
The signed-in account's assistant data as one JSON document, streamed as a download (github-backup-assistant-export-<UTC time>.json, Cache-Control: no-store), from one consistent snapshot:
{
"format": "github-backup-assistant-export",
"version": 1,
"exported_at": "2026-10-15T09:00:00+00:00",
"account_id": 2,
"tables": {"ai_chat_sessions": [], "ai_chat_messages": [], "investigations": [], "ai_openrouter_credentials": [{"key_hint": "sk-...a1b2"}]}
}
tablesholdsai_chat_sessions,ai_session_metadata,ai_chat_messages(a message outside any session through its turn's investigation),investigations,investigation_errors,ai_tool_calls,ai_tool_call_args,ai_tool_call_errors,ai_tool_confirmations,ai_reportsandai_openrouter_credentials. The last holds only the key's hint and dates, never the key. The search index is cut from these rows and the backup data, so it is left out.- Like the API's export, the document ends with
}and its only raw newline; a failure ends the response early. - 3 exports per account per 10 minutes in each process; more answer
429withRetry-After.503 SERVICE_UNAVAILABLEwithout a database. - Deleting the whole account is the API's
DELETE /api/me, which removes these rows too.
Observatory Errors and Readiness
Errors use {"success": false, "error": {"code": "...", "message": "..."}, "request_id": "..."}. Unexpected failures return 500 with the message Internal server error and the request_id (also in the X-Request-ID header); the exception text is only logged. 503 SERVICE_UNAVAILABLE means chat history storage is unavailable.
GET /ready returns 200 or 503 with one status word per component (database, go_backend, configuration) to everyone; the error details behind them (exception text, status codes) only go to callers with a user token or X-Internal-Secret. CORS accepts only the origins in CORS_ALLOWED_ORIGINS.
Reports are never sent anywhere (ADR 0020). In the dashboard a report is the assistant's answer, which its Download button saves as Markdown; the dashboard's proxy does not forward /reports, so these routes serve clients that call the Observatory directly with a session. POST /reports {"subject", "report_type", "report_data", "content_markdown"} renders the report type's template and stores the report for the account with status generated; an unknown report type gives 400, and any other field, such as recipients from older clients, gives 422 and stores nothing. GET /reports/{report_id}/download returns one of the account's stored reports as an attachment: its HTML (text/html), or its Markdown (text/markdown) when it has no HTML, named after its type and id, with Cache-Control: no-store, X-Content-Type-Options: nosniff and a sandboxing Content-Security-Policy so the file never runs as a page of this origin. A malformed id, another account's report, a missing one or one without content all give 404. GET /me/export holds every stored report. POST /reports/send and POST /internal/reports/email are gone (404/405). No response or export returns a report's pdf_path, recipients, sent_at or error_message: nothing writes them, and migration 000043 cleared the values e-mailed reports left.
GET /internal/jobs/pass runs one pass of the background jobs (ADR 0013) for a cron and answers its counts (claimed, completed, failed, lost, queued) in data. It takes only Authorization: Bearer <CRON_SECRET> (the cron that calls it sends it): 503 when CRON_SECRET is not set, 401 without it or with anything else (a session or a service credential included).
Error Handling
The API returns standard HTTP status codes and error responses:
| Status Code | Meaning |
|---|---|
| 200 | Success |
| 201 | Created (a personal token, a queued request, a run) |
| 204 | Success without a body |
| 400 | Bad Request (invalid parameters or body; ACCOUNT_REQUIRED) |
| 401 | Missing or invalid credentials (WWW-Authenticate: Bearer realm="github-backup-api") |
| 402 | The account has no paid plan (PLAN_REQUIRED) |
| 403 | Authenticated but not allowed (FORBIDDEN, ACCOUNT_DISABLED, SIGNUP_CLOSED) |
| 404 | Not Found: the resource does not exist or belongs to another account |
| 409 | Conflict (TOO_MANY_TOKENS, TOO_MANY_AGENTS, LEASE_HELD, LEASE_LOST, RUN_NOT_HELD) |
| 413 | Request body too large (PAYLOAD_TOO_LARGE) |
| 422 | The request cannot be applied as sent (IDEMPOTENCY_KEY_REUSED) |
| 429 | Too Many Requests (rate limit exceeded) |
| 500 | Internal Server Error |
| 503 | Service Unavailable (database connection issue) |
Error Response Format:
The data routes' validation and lookup errors (400, 404) return {"error": "<message>"}. Authentication, the account, internal and agent routes, rate limits and internal errors use the envelope:
{
"success": false,
"error": {
"code": "INTERNAL_ERROR",
"message": "internal server error (request_id 5f1c2b0e9a7d4c3b8e6f1a2d3c4b5a69)",
"request_id": "5f1c2b0e9a7d4c3b8e6f1a2d3c4b5a69"
},
"message": "internal server error (request_id 5f1c2b0e9a7d4c3b8e6f1a2d3c4b5a69)"
}
error.code | Status | When |
|---|---|---|
UNAUTHORIZED | 401 | No credentials where they are needed, or any invalid one (wrong secret, unknown, revoked or expired token, bad or expired session, a session whose account no longer exists); a refused token names details.reason (unknown, revoked, expired) |
FORBIDDEN | 403 | The principal lacks the scope (details.required_scope) or kind (details.required_kind) the route needs |
ACCOUNT_REQUIRED | 400 | An internal caller without X-Account-Id on an account-scoped route |
RESEARCH_UNAVAILABLE | 503 | PUT /api/me/research with enabled: true while the API has no RESEARCH_HMAC_KEY |
CONFIRMATION_REQUIRED | 400 | DELETE /api/me without the account's GitHub login in confirm |
OWNER_ACCOUNT | 409 | DELETE /api/me for the deployment owner's account |
PAGE_TOO_DEEP | 400 | A ?page that starts past the first 10,000 rows of a list; follow pagination.next_cursor instead |
ACCOUNT_DISABLED | 403 | The account of the session, token, agent or X-Account-Id is disabled |
NOT_FOUND | 404 | Unknown or another account's token, agent, link code, fix (PATCH /api/fixes/:id), repository state, run (agent routes) or X-Account-Id |
RUN_NOT_FOUND | 404 | A fix names a run that does not exist or is another account's (error.details.run_ids); nothing is recorded |
IDEMPOTENCY_KEY_REUSED | 422 | The account recorded a different fix under this Idempotency-Key |
BAD_REQUEST | 400 | Invalid body or parameter on the account, fix, internal and agent routes, and the newer list filters |
TOO_MANY_TOKENS | 409 | The account already has 20 active personal tokens |
TOO_MANY_AGENTS | 409 | The account already has 10 active agents (link approval, and the link poll as {"error": "TOO_MANY_AGENTS"}) |
SIGNUP_CLOSED | 403 | The sign-up policy turns a GitHub user away; the message says why |
PLAN_REQUIRED | 402 | The account has no paid plan: approving a link, POST /api/requests and POST /v1/runs are for paying accounts and the deployment owner |
PAYLOAD_TOO_LARGE | 413 | A body over 16 KiB on the account routes, 256 KiB on /api/fixes or 2 MiB on /v1 |
RATE_LIMITED | 429 | A rate limit or the limit on unknown tokens (with Retry-After) |
INTERNAL_ERROR | 500 | Unexpected error (details only in the log) |
SERVICE_UNAVAILABLE | 503 | Database or live feed unavailable |
SERVICE_BUSY | 503 | Too many /api requests in flight, or too many live streams on the server; retry after Retry-After seconds |
TOO_MANY_STREAMS | 429 | The account has 10 live log streams open (SSE and WebSocket together); retry after Retry-After seconds |
The agent routes answer the lease and link outcomes flat, as the worker expects: 409 {"error": "LEASE_HELD", "holder": "…"}, 409 {"error": "LEASE_LOST"}, 409 {"error": "RUN_NOT_HELD", "message": "…"}, 409 {"error": "TOO_MANY_AGENTS", "message": "…"} and 400 {"error": "<device flow error>"} on /v1/agent/link/token.
Internal errors never include database or driver messages; the details are logged with the same request ID. A panic in a handler is recovered and answered the same way.
Data Models
BackupRun
| Field | Type | Description |
|---|---|---|
id | integer | Unique identifier |
started_at | ISO 8601 timestamp | When the run started |
completed_at | ISO 8601 timestamp or null | When the run completed |
status | string | One of: completed, failed, running |
duration_ms | integer | Total duration in milliseconds |
total_repos | integer | Total repositories in the run |
successful | integer | Successfully backed up repos |
failed | integer | Failed backups |
skipped | integer | Skipped repos (no changes detected) |
error_message | string | Error details (from backup_run_errors / backup_result_errors), empty when none |
BackupResult
| Field | Type | Description |
|---|---|---|
id | integer | Unique identifier |
run_id | integer | Associated backup run ID |
repo_full_name | string | Repository full name (owner/repo) |
status | string | completed or failed; the worker also records empty (no branches or tags to archive) and too_large (over the git sink's 100 MiB file limit). Rows written by the old worker may say success. |
created_at | ISO 8601 timestamp | When the result was created |
duration_ms | integer | Time taken to backup this repo |
commit_hash | string | Git commit hash of the backup, empty when none |
archive_size_bytes | integer | Size of the generated archive |
error_message | string | Error details (from backup_run_errors / backup_result_errors), empty when none |
RepoAnalyticsSnapshot
| Field | Type | Description |
|---|---|---|
id | integer | Unique identifier |
run_id | integer or null | Associated backup run ID |
captured_at | ISO 8601 timestamp | When the snapshot was taken |
head_commit | string | Latest commit hash |
head_commit_message | string | Latest commit message |
head_commit_at | ISO 8601 timestamp or null | When the latest commit was made |
total_commits | integer | Total commits in backup repo |
branch_count | integer | Number of branches |
tag_count | integer | Number of tags |
tracked_files | integer | Total files being tracked |
total_blob_size_bytes | integer | Total blob size |
avg_blob_size_bytes | integer | Average blob size |
largest_blob_path | string | Path to largest blob |
largest_blob_size_bytes | integer | Size of largest blob |
archive_count | integer | Number of archives |
total_archive_size_bytes | integer | Total archive size |
avg_archive_size_bytes | integer | Average archive size |
largest_archive_path | string | Path to largest archive |
largest_archive_size_bytes | integer | Size of largest archive |
ExecutionLog
| Field | Type | Description |
|---|---|---|
id | integer | Unique identifier |
created_at | ISO 8601 timestamp | When the log was created |
level | string | Log level as written by the worker: info, warn, error |
message | string | Log message |
repository | string | Associated repository, empty when none |
run_id | integer or null | Associated backup run ID |
DashboardStats
| Field | Type | Description |
|---|---|---|
total_runs | integer | Total number of backup runs |
total_repos | integer | Total repositories processed |
total_successful | integer | Total successful backups |
total_failed | integer | Total failed backups |
total_skipped | integer | Total skipped backups |
distinct_repos | integer | Unique repositories backed up |
success_rate | float | Success percentage (0-100) |
last_run_status | string | Status of the last run: completed, failed or running |
last_run_at | ISO 8601 timestamp or null | When the last run occurred |
avg_duration_ms | integer | Average run duration |
total_size_bytes | integer | Total backup size |
largest_archive_bytes | integer | Size of largest archive |
largest_repository | string | Name of largest repository backup |
latest_analytics | RepoAnalyticsSnapshot or null | Most recent analytics snapshot |
Implementation Notes
- All responses are JSON-formatted.
- Timestamps are in ISO 8601 format with UTC timezone.
- All sizes are in bytes.
- Durations are in milliseconds.
- The API relies on PostgreSQL for persistence; ensure
DATABASE_URLis configured and the database is running. - All
/apiand/v1routes are rate-limited. Implement exponential backoff when receiving 429 responses. - The API has a 15 second read timeout and a 2 minute keep-alive idle timeout, and deliberately no write timeout (it would cut the live log stream).
- Response handlers are implemented in src/backend/github-backup-api/handlers/ directory.
- Routes are defined in
src/backend/github-backup-api/routes/app.routes.go; authentication inmiddleware/auth.middleware.go.